hash
stringlengths
64
64
content
stringlengths
0
1.51M
4587c95f7f7e98d85e911137b23e531856572ab6b830bf6f1af39bb1162e0f79
#this module tests that SymPy works with true division turned on from sympy.core.numbers import (Float, Rational) from sympy.core.symbol import Symbol def test_truediv(): assert 1/2 != 0 assert Rational(1)/2 != 0 def dotest(s): x = Symbol("x") y = Symbol("y") l = [ Rational(2), Float("1.3"), x, y, pow(x, y)*y, 5, 5.5 ] for x in l: for y in l: s(x, y) return True def test_basic(): def s(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(s) 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)
bcc9b565ee4109af602158ba590f0e1b4cd85041b2d583718f2b2caced4632d2
from collections import defaultdict from sympy.core.basic import Basic from sympy.core.containers import (Dict, Tuple) from sympy.core.numbers import Integer from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.core.sympify import sympify from sympy.matrices.dense import Matrix from sympy.sets.sets import FiniteSet from sympy.core.containers import tuple_wrapper from sympy.core.expr import unchanged from sympy.core.function import Function, Lambda from sympy.core.relational import Eq from sympy.testing.pytest import raises from sympy.utilities.iterables import is_sequence, iterable from sympy.abc import x, y def test_Tuple(): t = (1, 2, 3, 4) st = Tuple(*t) assert set(sympify(t)) == set(st) assert len(t) == len(st) assert set(sympify(t[:2])) == set(st[:2]) assert isinstance(st[:], Tuple) assert st == Tuple(1, 2, 3, 4) assert st.func(*st.args) == st p, q, r, s = symbols('p q r s') t2 = (p, q, r, s) st2 = Tuple(*t2) assert st2.atoms() == set(t2) assert st == st2.subs({p: 1, q: 2, r: 3, s: 4}) # issue 5505 assert all(isinstance(arg, Basic) for arg in st.args) assert Tuple(p, 1).subs(p, 0) == Tuple(0, 1) assert Tuple(p, Tuple(p, 1)).subs(p, 0) == Tuple(0, Tuple(0, 1)) assert Tuple(t2) == Tuple(Tuple(*t2)) assert Tuple.fromiter(t2) == Tuple(*t2) assert Tuple.fromiter(x for x in range(4)) == Tuple(0, 1, 2, 3) assert st2.fromiter(st2.args) == st2 def test_Tuple_contains(): t1, t2 = Tuple(1), Tuple(2) assert t1 in Tuple(1, 2, 3, t1, Tuple(t2)) assert t2 not in Tuple(1, 2, 3, t1, Tuple(t2)) def test_Tuple_concatenation(): assert Tuple(1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4) assert (1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4) assert Tuple(1, 2) + (3, 4) == Tuple(1, 2, 3, 4) raises(TypeError, lambda: Tuple(1, 2) + 3) raises(TypeError, lambda: 1 + Tuple(2, 3)) #the Tuple case in __radd__ is only reached when a subclass is involved class Tuple2(Tuple): def __radd__(self, other): return Tuple.__radd__(self, other + other) assert Tuple(1, 2) + Tuple2(3, 4) == Tuple(1, 2, 1, 2, 3, 4) assert Tuple2(1, 2) + Tuple(3, 4) == Tuple(1, 2, 3, 4) def test_Tuple_equality(): assert not isinstance(Tuple(1, 2), tuple) assert (Tuple(1, 2) == (1, 2)) is True assert (Tuple(1, 2) != (1, 2)) is False assert (Tuple(1, 2) == (1, 3)) is False assert (Tuple(1, 2) != (1, 3)) is True assert (Tuple(1, 2) == Tuple(1, 2)) is True assert (Tuple(1, 2) != Tuple(1, 2)) is False assert (Tuple(1, 2) == Tuple(1, 3)) is False assert (Tuple(1, 2) != Tuple(1, 3)) is True def test_Tuple_Eq(): assert Eq(Tuple(), Tuple()) is S.true assert Eq(Tuple(1), 1) is S.false assert Eq(Tuple(1, 2), Tuple(1)) is S.false assert Eq(Tuple(1), Tuple(1)) is S.true assert Eq(Tuple(1, 2), Tuple(1, 3)) is S.false assert Eq(Tuple(1, 2), Tuple(1, 2)) is S.true assert unchanged(Eq, Tuple(1, x), Tuple(1, 2)) assert Eq(Tuple(1, x), Tuple(1, 2)).subs(x, 2) is S.true assert unchanged(Eq, Tuple(1, 2), x) f = Function('f') assert unchanged(Eq, Tuple(1), f(x)) assert Eq(Tuple(1), f(x)).subs(x, 1).subs(f, Lambda(y, (y,))) is S.true def test_Tuple_comparision(): assert (Tuple(1, 3) >= Tuple(-10, 30)) is S.true assert (Tuple(1, 3) <= Tuple(-10, 30)) is S.false assert (Tuple(1, 3) >= Tuple(1, 3)) is S.true assert (Tuple(1, 3) <= Tuple(1, 3)) is S.true def test_Tuple_tuple_count(): assert Tuple(0, 1, 2, 3).tuple_count(4) == 0 assert Tuple(0, 4, 1, 2, 3).tuple_count(4) == 1 assert Tuple(0, 4, 1, 4, 2, 3).tuple_count(4) == 2 assert Tuple(0, 4, 1, 4, 2, 4, 3).tuple_count(4) == 3 def test_Tuple_index(): assert Tuple(4, 0, 1, 2, 3).index(4) == 0 assert Tuple(0, 4, 1, 2, 3).index(4) == 1 assert Tuple(0, 1, 4, 2, 3).index(4) == 2 assert Tuple(0, 1, 2, 4, 3).index(4) == 3 assert Tuple(0, 1, 2, 3, 4).index(4) == 4 raises(ValueError, lambda: Tuple(0, 1, 2, 3).index(4)) raises(ValueError, lambda: Tuple(4, 0, 1, 2, 3).index(4, 1)) raises(ValueError, lambda: Tuple(0, 1, 2, 3, 4).index(4, 1, 4)) def test_Tuple_mul(): assert Tuple(1, 2, 3)*2 == Tuple(1, 2, 3, 1, 2, 3) assert 2*Tuple(1, 2, 3) == Tuple(1, 2, 3, 1, 2, 3) assert Tuple(1, 2, 3)*Integer(2) == Tuple(1, 2, 3, 1, 2, 3) assert Integer(2)*Tuple(1, 2, 3) == Tuple(1, 2, 3, 1, 2, 3) raises(TypeError, lambda: Tuple(1, 2, 3)*S.Half) raises(TypeError, lambda: S.Half*Tuple(1, 2, 3)) def test_tuple_wrapper(): @tuple_wrapper def wrap_tuples_and_return(*t): return t p = symbols('p') assert wrap_tuples_and_return(p, 1) == (p, 1) assert wrap_tuples_and_return((p, 1)) == (Tuple(p, 1),) assert wrap_tuples_and_return(1, (p, 2), 3) == (1, Tuple(p, 2), 3) def test_iterable_is_sequence(): ordered = [list(), tuple(), Tuple(), Matrix([[]])] unordered = [set()] not_sympy_iterable = [{}, '', ''] assert all(is_sequence(i) for i in ordered) assert all(not is_sequence(i) for i in unordered) assert all(iterable(i) for i in ordered + unordered) assert all(not iterable(i) for i in not_sympy_iterable) assert all(iterable(i, exclude=None) for i in not_sympy_iterable) def test_Dict(): x, y, z = symbols('x y z') d = Dict({x: 1, y: 2, z: 3}) assert d[x] == 1 assert d[y] == 2 raises(KeyError, lambda: d[2]) raises(KeyError, lambda: d['2']) assert len(d) == 3 assert set(d.keys()) == {x, y, z} assert set(d.values()) == {S.One, S(2), S(3)} assert d.get(5, 'default') == 'default' assert d.get('5', 'default') == 'default' assert x in d and z in d and not 5 in d and not '5' in d assert d.has(x) and d.has(1) # SymPy Basic .has method # Test input types # input - a Python dict # input - items as args - SymPy style assert (Dict({x: 1, y: 2, z: 3}) == Dict((x, 1), (y, 2), (z, 3))) raises(TypeError, lambda: Dict(((x, 1), (y, 2), (z, 3)))) with raises(NotImplementedError): d[5] = 6 # assert immutability assert set( d.items()) == {Tuple(x, S.One), Tuple(y, S(2)), Tuple(z, S(3))} assert set(d) == {x, y, z} assert str(d) == '{x: 1, y: 2, z: 3}' assert d.__repr__() == '{x: 1, y: 2, z: 3}' # Test creating a Dict from a Dict. d = Dict({x: 1, y: 2, z: 3}) assert d == Dict(d) # Test for supporting defaultdict d = defaultdict(int) assert d[x] == 0 assert d[y] == 0 assert d[z] == 0 assert Dict(d) d = Dict(d) assert len(d) == 3 assert set(d.keys()) == {x, y, z} assert set(d.values()) == {S.Zero, S.Zero, S.Zero} def test_issue_5788(): args = [(1, 2), (2, 1)] for o in [Dict, Tuple, FiniteSet]: # __eq__ and arg handling if o != Tuple: assert o(*args) == o(*reversed(args)) pair = [o(*args), o(*reversed(args))] assert sorted(pair) == sorted(reversed(pair)) assert set(o(*args)) # doesn't fail
93a1cda365ec542ffcc8c960430be193f8d0d0b692f01b0279d9988383fa587a
from sympy.core.add import Add from sympy.core.containers import Tuple from sympy.core.function import (Function, Lambda) from sympy.core.mul import Mul from sympy.core.numbers import (Float, I, Integer, Rational, pi) from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import Symbol 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.logic.boolalg import (false, Or, true, Xor) from sympy.matrices.dense import Matrix from sympy.polys.polytools import Poly from sympy.printing.repr import srepr from sympy.sets.fancysets import Range from sympy.sets.sets import Interval 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.external.gmpy import HAS_GMPY from sympy.sets import FiniteSet, EmptySet from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray import mpmath from collections import defaultdict, OrderedDict from mpmath.rational import mpq numpy = import_module('numpy') def test_issue_3538(): v = sympify("exp(x)") assert v == exp(x) assert type(v) == type(exp(x)) assert str(type(v)) == str(type(exp(x))) def test_sympify1(): assert sympify("x") == Symbol("x") assert sympify(" x") == Symbol("x") assert sympify(" x ") == Symbol("x") # issue 4877 n1 = S.Half assert sympify('--.5') == n1 assert sympify('-1/2') == -n1 assert sympify('-+--.5') == -n1 assert sympify('-.[3]') == Rational(-1, 3) assert sympify('.[3]') == Rational(1, 3) assert sympify('+.[3]') == Rational(1, 3) assert sympify('+0.[3]*10**-2') == Rational(1, 300) assert sympify('.[052631578947368421]') == Rational(1, 19) assert sympify('.0[526315789473684210]') == Rational(1, 19) assert sympify('.034[56]') == Rational(1711, 49500) # options to make reals into rationals assert sympify('1.22[345]', rational=True) == \ 1 + Rational(22, 100) + Rational(345, 99900) assert sympify('2/2.6', rational=True) == Rational(10, 13) assert sympify('2.6/2', rational=True) == Rational(13, 10) assert sympify('2.6e2/17', rational=True) == Rational(260, 17) assert sympify('2.6e+2/17', rational=True) == Rational(260, 17) assert sympify('2.6e-2/17', rational=True) == Rational(26, 17000) assert sympify('2.1+3/4', rational=True) == \ Rational(21, 10) + Rational(3, 4) assert sympify('2.234456', rational=True) == Rational(279307, 125000) assert sympify('2.234456e23', rational=True) == 223445600000000000000000 assert sympify('2.234456e-23', rational=True) == \ Rational(279307, 12500000000000000000000000000) assert sympify('-2.234456e-23', rational=True) == \ Rational(-279307, 12500000000000000000000000000) assert sympify('12345678901/17', rational=True) == \ Rational(12345678901, 17) assert sympify('1/.3 + x', rational=True) == Rational(10, 3) + x # make sure longs in fractions work assert sympify('222222222222/11111111111') == \ Rational(222222222222, 11111111111) # ... even if they come from repetend notation assert sympify('1/.2[123456789012]') == Rational(333333333333, 70781892967) # ... or from high precision reals assert sympify('.1234567890123456', rational=True) == \ Rational(19290123283179, 156250000000000) def test_sympify_Fraction(): try: import fractions except ImportError: pass else: value = sympify(fractions.Fraction(101, 127)) assert value == Rational(101, 127) and type(value) is Rational def test_sympify_gmpy(): if HAS_GMPY: if HAS_GMPY == 2: import gmpy2 as gmpy elif HAS_GMPY == 1: import gmpy value = sympify(gmpy.mpz(1000001)) assert value == Integer(1000001) and type(value) is Integer value = sympify(gmpy.mpq(101, 127)) assert value == Rational(101, 127) and type(value) is Rational @conserve_mpmath_dps def test_sympify_mpmath(): value = sympify(mpmath.mpf(1.0)) assert value == Float(1.0) and type(value) is Float mpmath.mp.dps = 12 assert sympify( mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-12")) == True assert sympify( mpmath.pi).epsilon_eq(Float("3.14159265359"), Float("1e-13")) == False mpmath.mp.dps = 6 assert sympify( mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-5")) == True assert sympify( mpmath.pi).epsilon_eq(Float("3.14159"), Float("1e-6")) == False assert sympify(mpmath.mpc(1.0 + 2.0j)) == Float(1.0) + Float(2.0)*I assert sympify(mpq(1, 2)) == S.Half def test_sympify2(): class A: def _sympy_(self): return Symbol("x")**3 a = A() assert _sympify(a) == x**3 assert sympify(a) == x**3 assert a == x**3 def test_sympify3(): assert sympify("x**3") == x**3 assert sympify("x^3") == x**3 assert sympify("1/2") == Integer(1)/2 raises(SympifyError, lambda: _sympify('x**3')) raises(SympifyError, lambda: _sympify('1/2')) def test_sympify_keywords(): raises(SympifyError, lambda: sympify('if')) raises(SympifyError, lambda: sympify('for')) raises(SympifyError, lambda: sympify('while')) raises(SympifyError, lambda: sympify('lambda')) def test_sympify_float(): assert sympify("1e-64") != 0 assert sympify("1e-20000") != 0 def test_sympify_bool(): assert sympify(True) is true assert sympify(False) is false def test_sympyify_iterables(): ans = [Rational(3, 10), Rational(1, 5)] assert sympify(['.3', '.2'], rational=True) == ans assert sympify(dict(x=0, y=1)) == {x: 0, y: 1} assert sympify(['1', '2', ['3', '4']]) == [S(1), S(2), [S(3), S(4)]] @XFAIL def test_issue_16772(): # because there is a converter for tuple, the # args are only sympified without the flags being passed # along; list, on the other hand, is not converted # with a converter so its args are traversed later ans = [Rational(3, 10), Rational(1, 5)] assert sympify(tuple(['.3', '.2']), rational=True) == Tuple(*ans) def test_issue_16859(): class no(float, CantSympify): pass raises(SympifyError, lambda: sympify(no(1.2))) def test_sympify4(): class A: def _sympy_(self): return Symbol("x") a = A() assert _sympify(a)**3 == x**3 assert sympify(a)**3 == x**3 assert a == x def test_sympify_text(): assert sympify('some') == Symbol('some') assert sympify('core') == Symbol('core') assert sympify('True') is True assert sympify('False') is False assert sympify('Poly') == Poly assert sympify('sin') == sin def test_sympify_function(): assert sympify('factor(x**2-1, x)') == -(1 - x)*(x + 1) assert sympify('sin(pi/2)*cos(pi)') == -Integer(1) def test_sympify_poly(): p = Poly(x**2 + x + 1, x) assert _sympify(p) is p assert sympify(p) is p def test_sympify_factorial(): assert sympify('x!') == factorial(x) assert sympify('(x+1)!') == factorial(x + 1) assert sympify('(1 + y*(x + 1))!') == factorial(1 + y*(x + 1)) assert sympify('(1 + y*(x + 1)!)^2') == (1 + y*factorial(x + 1))**2 assert sympify('y*x!') == y*factorial(x) assert sympify('x!!') == factorial2(x) assert sympify('(x+1)!!') == factorial2(x + 1) assert sympify('(1 + y*(x + 1))!!') == factorial2(1 + y*(x + 1)) assert sympify('(1 + y*(x + 1)!!)^2') == (1 + y*factorial2(x + 1))**2 assert sympify('y*x!!') == y*factorial2(x) assert sympify('factorial2(x)!') == factorial(factorial2(x)) raises(SympifyError, lambda: sympify("+!!")) raises(SympifyError, lambda: sympify(")!!")) raises(SympifyError, lambda: sympify("!")) raises(SympifyError, lambda: sympify("(!)")) raises(SympifyError, lambda: sympify("x!!!")) def test_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 == S.Half assert (-2)**(S(1)/2) == sqrt(2)*I def test_issue_4788(): assert srepr(S(1.0 + 0J)) == srepr(S(1.0)) == srepr(Float(1.0)) def test_issue_4798_None(): assert S(None) is None def test_issue_3218(): assert sympify("x+\ny") == x + y def test_issue_4988_builtins(): C = Symbol('C') vars = {'C': C} exp1 = sympify('C') assert exp1 == C # Make sure it did not get mixed up with sympy.C exp2 = sympify('C', vars) assert exp2 == C # Make sure it did not get mixed up with sympy.C def test_geometry(): p = sympify(Point(0, 1)) assert p == Point(0, 1) and isinstance(p, Point) L = sympify(Line(p, (1, 0))) assert L == Line((0, 1), (1, 0)) and isinstance(L, Line) def test_kernS(): s = '-1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x)))' # when 1497 is fixed, this no longer should pass: the expression # should be unchanged assert -1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x))) == -1 # sympification should not allow the constant to enter a Mul # or else the structure can change dramatically ss = kernS(s) assert ss != -1 and ss.simplify() == -1 s = '-1 - 2*(-(-x + 1/x)/(x*(x - 1/x)**2) - 1/(x*(x - 1/x)))'.replace( 'x', '_kern') ss = kernS(s) assert ss != -1 and ss.simplify() == -1 # issue 6687 assert (kernS('Interval(-1,-2 - 4*(-3))') == Interval(-1, Add(-2, Mul(12, 1, evaluate=False), evaluate=False))) assert kernS('_kern') == Symbol('_kern') assert kernS('E**-(x)') == exp(-x) e = 2*(x + y)*y assert kernS(['2*(x + y)*y', ('2*(x + y)*y',)]) == [e, (e,)] assert kernS('-(2*sin(x)**2 + 2*sin(x)*cos(x))*y/2') == \ -y*(2*sin(x)**2 + 2*sin(x)*cos(x))/2 # issue 15132 assert kernS('(1 - x)/(1 - x*(1-y))') == kernS('(1-x)/(1-(1-y)*x)') assert kernS('(1-2**-(4+1)*(1-y)*x)') == (1 - x*(1 - y)/32) assert kernS('(1-2**(4+1)*(1-y)*x)') == (1 - 32*x*(1 - y)) assert kernS('(1-2.*(1-y)*x)') == 1 - 2.*x*(1 - y) one = kernS('x - (x - 1)') assert one != 1 and one.expand() == 1 assert kernS("(2*x)/(x-1)") == 2*x/(x-1) def test_issue_6540_6552(): assert S('[[1/3,2], (2/5,)]') == [[Rational(1, 3), 2], (Rational(2, 5),)] assert S('[[2/6,2], (2/4,)]') == [[Rational(1, 3), 2], (S.Half,)] assert S('[[[2*(1)]]]') == [[[2]]] assert S('Matrix([2*(1)])') == Matrix([2]) def test_issue_6046(): assert str(S("Q & C", locals=_clash1)) == 'C & Q' assert str(S('pi(x)', locals=_clash2)) == 'pi(x)' locals = {} exec("from sympy.abc import Q, C", locals) assert str(S('C&Q', locals)) == 'C & Q' # clash can act as Symbol or Function assert str(S('pi(C, Q)', locals=_clash)) == 'pi(C, Q)' assert len(S('pi + x', locals=_clash2).free_symbols) == 2 # but not both raises(TypeError, lambda: S('pi + pi(x)', locals=_clash2)) assert all(set(i.values()) == {None} for i in ( _clash, _clash1, _clash2)) def test_issue_8821_highprec_from_str(): s = str(pi.evalf(128)) p = sympify(s) assert Abs(sin(p)) < 1e-127 def test_issue_10295(): if not numpy: skip("numpy not installed.") A = numpy.array([[1, 3, -1], [0, 1, 7]]) sA = S(A) assert sA.shape == (2, 3) for (ri, ci), val in numpy.ndenumerate(A): assert sA[ri, ci] == val B = numpy.array([-7, x, 3*y**2]) sB = S(B) assert sB.shape == (3,) assert B[0] == sB[0] == -7 assert B[1] == sB[1] == x assert B[2] == sB[2] == 3*y**2 C = numpy.arange(0, 24) C.resize(2,3,4) sC = S(C) assert sC[0, 0, 0].is_integer assert sC[0, 0, 0] == 0 a1 = numpy.array([1, 2, 3]) a2 = numpy.array([i for i in range(24)]) a2.resize(2, 4, 3) assert sympify(a1) == ImmutableDenseNDimArray([1, 2, 3]) assert sympify(a2) == ImmutableDenseNDimArray([i for i in range(24)], (2, 4, 3)) def test_Range(): # Only works in Python 3 where range returns a range type assert sympify(range(10)) == Range(10) assert _sympify(range(10)) == Range(10) def test_sympify_set(): n = Symbol('n') assert sympify({n}) == FiniteSet(n) assert sympify(set()) == EmptySet def test_sympify_numpy(): if not numpy: skip('numpy not installed. Abort numpy tests.') np = numpy def equal(x, y): return x == y and type(x) == type(y) assert sympify(np.bool_(1)) is S(True) try: assert equal( sympify(np.int_(1234567891234567891)), S(1234567891234567891)) assert equal( sympify(np.intp(1234567891234567891)), S(1234567891234567891)) except OverflowError: # May fail on 32-bit systems: Python int too large to convert to C long pass assert equal(sympify(np.intc(1234567891)), S(1234567891)) assert equal(sympify(np.int8(-123)), S(-123)) assert equal(sympify(np.int16(-12345)), S(-12345)) assert equal(sympify(np.int32(-1234567891)), S(-1234567891)) assert equal( sympify(np.int64(-1234567891234567891)), S(-1234567891234567891)) assert equal(sympify(np.uint8(123)), S(123)) assert equal(sympify(np.uint16(12345)), S(12345)) assert equal(sympify(np.uint32(1234567891)), S(1234567891)) assert equal( sympify(np.uint64(1234567891234567891)), S(1234567891234567891)) assert equal(sympify(np.float32(1.123456)), Float(1.123456, precision=24)) assert equal(sympify(np.float64(1.1234567891234)), Float(1.1234567891234, precision=53)) assert equal(sympify(np.longdouble(1.123456789)), Float(1.123456789, precision=80)) assert equal(sympify(np.complex64(1 + 2j)), S(1.0 + 2.0*I)) assert equal(sympify(np.complex128(1 + 2j)), S(1.0 + 2.0*I)) assert equal(sympify(np.longcomplex(1 + 2j)), S(1.0 + 2.0*I)) #float96 does not exist on all platforms if hasattr(np, 'float96'): assert equal(sympify(np.float96(1.123456789)), Float(1.123456789, precision=80)) #float128 does not exist on all platforms if hasattr(np, 'float128'): assert equal(sympify(np.float128(1.123456789123)), Float(1.123456789123, precision=80)) @XFAIL def test_sympify_rational_numbers_set(): ans = [Rational(3, 10), Rational(1, 5)] assert sympify({'.3', '.2'}, rational=True) == FiniteSet(*ans) def test_issue_13924(): if not numpy: skip("numpy not installed.") a = sympify(numpy.array([1])) assert isinstance(a, ImmutableDenseNDimArray) assert a[0] == 1 def test_numpy_sympify_args(): # Issue 15098. Make sure sympify args work with numpy types (like numpy.str_) if not numpy: skip("numpy not installed.") a = sympify(numpy.str_('a')) assert type(a) is Symbol assert a == Symbol('a') class CustomSymbol(Symbol): pass a = sympify(numpy.str_('a'), {"Symbol": CustomSymbol}) assert isinstance(a, CustomSymbol) a = sympify(numpy.str_('x^y')) assert a == x**y a = sympify(numpy.str_('x^y'), convert_xor=False) assert a == Xor(x, y) raises(SympifyError, lambda: sympify(numpy.str_('x'), strict=True)) a = sympify(numpy.str_('1.1')) assert isinstance(a, Float) assert a == 1.1 a = sympify(numpy.str_('1.1'), rational=True) assert isinstance(a, Rational) assert a == Rational(11, 10) a = sympify(numpy.str_('x + x')) assert isinstance(a, Mul) assert a == 2*x a = sympify(numpy.str_('x + x'), evaluate=False) assert isinstance(a, Add) assert a == Add(x, x, evaluate=False) def test_issue_5939(): a = Symbol('a') b = Symbol('b') assert sympify('''a+\nb''') == a + b def test_issue_16759(): d = sympify({.5: 1}) assert S.Half not in d assert Float(.5) in d assert d[.5] is S.One d = sympify(OrderedDict({.5: 1})) assert S.Half not in d assert Float(.5) in d assert d[.5] is S.One d = sympify(defaultdict(int, {.5: 1})) assert S.Half not in d assert Float(.5) in d assert d[.5] is S.One def test_issue_17811(): a = Function('a') assert sympify('a(x)*5', evaluate=False) == Mul(a(x), 5, evaluate=False) def test_issue_14706(): if not numpy: skip("numpy not installed.") z1 = numpy.zeros((1, 1), dtype=numpy.float64) z2 = numpy.zeros((2, 2), dtype=numpy.float64) z3 = numpy.zeros((), dtype=numpy.float64) y1 = numpy.ones((1, 1), dtype=numpy.float64) y2 = numpy.ones((2, 2), dtype=numpy.float64) y3 = numpy.ones((), dtype=numpy.float64) assert numpy.all(x + z1 == numpy.full((1, 1), x)) assert numpy.all(x + z2 == numpy.full((2, 2), x)) assert numpy.all(z1 + x == numpy.full((1, 1), x)) assert numpy.all(z2 + x == numpy.full((2, 2), x)) for z in [z3, numpy.int64(0), numpy.float64(0), numpy.complex64(0)]: assert x + z == x assert z + x == x assert isinstance(x + z, Symbol) assert isinstance(z + x, Symbol) # If these tests fail, then it means that numpy has finally # fixed the issue of scalar conversion for rank>0 arrays # which is mentioned in numpy/numpy#10404. In that case, # some changes have to be made in sympify.py. # Note: For future reference, for anyone who takes up this # issue when numpy has finally fixed their side of the problem, # the changes for this temporary fix were introduced in PR 18651 assert numpy.all(x + y1 == numpy.full((1, 1), x + 1.0)) assert numpy.all(x + y2 == numpy.full((2, 2), x + 1.0)) assert numpy.all(y1 + x == numpy.full((1, 1), x + 1.0)) assert numpy.all(y2 + x == numpy.full((2, 2), x + 1.0)) for y_ in [y3, numpy.int64(1), numpy.float64(1), numpy.complex64(1)]: assert x + y_ == y_ + x assert isinstance(x + y_, Add) assert isinstance(y_ + x, Add) assert x + numpy.array(x) == 2 * x assert x + numpy.array([x]) == numpy.array([2*x], dtype=object) assert sympify(numpy.array([1])) == ImmutableDenseNDimArray([1], 1) assert sympify(numpy.array([[[1]]])) == ImmutableDenseNDimArray([1], (1, 1, 1)) assert sympify(z1) == ImmutableDenseNDimArray([0], (1, 1)) assert sympify(z2) == ImmutableDenseNDimArray([0, 0, 0, 0], (2, 2)) assert sympify(z3) == ImmutableDenseNDimArray([0], ()) assert sympify(z3, strict=True) == 0.0 raises(SympifyError, lambda: sympify(numpy.array([1]), strict=True)) raises(SympifyError, lambda: sympify(z1, strict=True)) raises(SympifyError, lambda: sympify(z2, strict=True)) def test_issue_21536(): #test to check evaluate=False in case of iterable input u = sympify("x+3*x+2", evaluate=False) v = sympify("2*x+4*x+2+4", evaluate=False) assert u.is_Add and set(u.args) == {x, 3*x, 2} assert v.is_Add and set(v.args) == {2*x, 4*x, 2, 4} assert sympify(["x+3*x+2", "2*x+4*x+2+4"], evaluate=False) == [u, v] #test to check evaluate=True in case of iterable input u = sympify("x+3*x+2", evaluate=True) v = sympify("2*x+4*x+2+4", evaluate=True) assert u.is_Add and set(u.args) == {4*x, 2} assert v.is_Add and set(v.args) == {6*x, 6} assert sympify(["x+3*x+2", "2*x+4*x+2+4"], evaluate=True) == [u, v] #test to check evaluate with no input in case of iterable input u = sympify("x+3*x+2") v = sympify("2*x+4*x+2+4") assert u.is_Add and set(u.args) == {4*x, 2} assert v.is_Add and set(v.args) == {6*x, 6} assert sympify(["x+3*x+2", "2*x+4*x+2+4"]) == [u, v]
be57bc90847c05e8499b180472ebbd20115018b49a92f0d89f3e87200e9175bd
import math from sympy.concrete.products import (Product, product) from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.evalf import N from sympy.core.function import (Function, nfloat) from sympy.core.mul import Mul from sympy.core import (GoldenRatio) from sympy.core.numbers import (E, I, Rational, oo, zoo, nan, pi) from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial from sympy.functions.combinatorial.numbers import fibonacci from sympy.functions.elementary.complexes import (Abs, re, im) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (acosh, cosh) from sympy.functions.elementary.integers import (ceiling, floor) from sympy.functions.elementary.miscellaneous import (Max, sqrt) from sympy.functions.elementary.trigonometric import (acos, atan, cos, sin, tan) from sympy.integrals.integrals import (Integral, integrate) from sympy.polys.polytools import factor from sympy.printing.str import sstr from sympy.simplify.simplify import simplify from sympy.core.numbers import comp from sympy.core.evalf import (complex_accuracy, PrecisionExhausted, scaled_zero, get_integer_part, as_mpmath, evalf) from mpmath import inf, ninf from mpmath.libmp.libmpf import from_float from sympy.core.expr import unchanged from sympy.testing.pytest import raises, XFAIL from sympy.abc import n, x, y def NS(e, n=15, **options): return sstr(sympify(e).evalf(n, **options), full_prec=True) def test_evalf_helpers(): from mpmath.libmp import finf assert complex_accuracy((from_float(2.0), None, 35, None)) == 35 assert complex_accuracy((from_float(2.0), from_float(10.0), 35, 100)) == 37 assert complex_accuracy( (from_float(2.0), from_float(1000.0), 35, 100)) == 43 assert complex_accuracy((from_float(2.0), from_float(10.0), 100, 35)) == 35 assert complex_accuracy( (from_float(2.0), from_float(1000.0), 100, 35)) == 35 assert complex_accuracy(finf) == math.inf assert complex_accuracy(zoo) == math.inf raises(ValueError, lambda: get_integer_part(zoo, 1, {})) def test_evalf_basic(): assert NS('pi', 15) == '3.14159265358979' assert NS('2/3', 10) == '0.6666666667' assert NS('355/113-pi', 6) == '2.66764e-7' assert NS('16*atan(1/5)-4*atan(1/239)', 15) == '3.14159265358979' def test_cancellation(): assert NS(Add(pi, Rational(1, 10**1000), -pi, evaluate=False), 15, maxn=1200) == '1.00000000000000e-1000' def test_evalf_powers(): assert NS('pi**(10**20)', 10) == '1.339148777e+49714987269413385435' assert NS(pi**(10**100), 10) == ('4.946362032e+4971498726941338543512682882' '9089887365167832438044244613405349992494711208' '95526746555473864642912223') assert NS('2**(1/10**50)', 15) == '1.00000000000000' assert NS('2**(1/10**50)-1', 15) == '6.93147180559945e-51' # Evaluation of Rump's ill-conditioned polynomial def test_evalf_rump(): a = 1335*y**6/4 + x**2*(11*x**2*y**2 - y**6 - 121*y**4 - 2) + 11*y**8/2 + x/(2*y) assert NS(a, 15, subs={x: 77617, y: 33096}) == '-0.827396059946821' def test_evalf_complex(): assert NS('2*sqrt(pi)*I', 10) == '3.544907702*I' assert NS('3+3*I', 15) == '3.00000000000000 + 3.00000000000000*I' assert NS('E+pi*I', 15) == '2.71828182845905 + 3.14159265358979*I' assert NS('pi * (3+4*I)', 15) == '9.42477796076938 + 12.5663706143592*I' assert NS('I*(2+I)', 15) == '-1.00000000000000 + 2.00000000000000*I' @XFAIL def test_evalf_complex_bug(): assert NS('(pi+E*I)*(E+pi*I)', 15) in ('0.e-15 + 17.25866050002*I', '0.e-17 + 17.25866050002*I', '-0.e-17 + 17.25866050002*I') def test_evalf_complex_powers(): assert NS('(E+pi*I)**100000000000000000') == \ '-3.58896782867793e+61850354284995199 + 4.58581754997159e+61850354284995199*I' # XXX: rewrite if a+a*I simplification introduced in SymPy #assert NS('(pi + pi*I)**2') in ('0.e-15 + 19.7392088021787*I', '0.e-16 + 19.7392088021787*I') assert NS('(pi + pi*I)**2', chop=True) == '19.7392088021787*I' assert NS( '(pi + 1/10**8 + pi*I)**2') == '6.2831853e-8 + 19.7392088650106*I' assert NS('(pi + 1/10**12 + pi*I)**2') == '6.283e-12 + 19.7392088021850*I' assert NS('(pi + pi*I)**4', chop=True) == '-389.636364136010' assert NS( '(pi + 1/10**8 + pi*I)**4') == '-389.636366616512 + 2.4805021e-6*I' assert NS('(pi + 1/10**12 + pi*I)**4') == '-389.636364136258 + 2.481e-10*I' assert NS( '(10000*pi + 10000*pi*I)**4', chop=True) == '-3.89636364136010e+18' @XFAIL def test_evalf_complex_powers_bug(): assert NS('(pi + pi*I)**4') == '-389.63636413601 + 0.e-14*I' def test_evalf_exponentiation(): assert NS(sqrt(-pi)) == '1.77245385090552*I' assert NS(Pow(pi*I, Rational( 1, 2), evaluate=False)) == '1.25331413731550 + 1.25331413731550*I' assert NS(pi**I) == '0.413292116101594 + 0.910598499212615*I' assert NS(pi**(E + I/3)) == '20.8438653991931 + 8.36343473930031*I' assert NS((pi + I/3)**(E + I/3)) == '17.2442906093590 + 13.6839376767037*I' assert NS(exp(pi)) == '23.1406926327793' assert NS(exp(pi + E*I)) == '-21.0981542849657 + 9.50576358282422*I' assert NS(pi**pi) == '36.4621596072079' assert NS((-pi)**pi) == '-32.9138577418939 - 15.6897116534332*I' assert NS((-pi)**(-pi)) == '-0.0247567717232697 + 0.0118013091280262*I' # An example from Smith, "Multiple Precision Complex Arithmetic and Functions" def test_evalf_complex_cancellation(): A = Rational('63287/100000') B = Rational('52498/100000') C = Rational('69301/100000') D = Rational('83542/100000') F = Rational('2231321613/2500000000') # XXX: the number of returned mantissa digits in the real part could # change with the implementation. What matters is that the returned digits are # correct; those that are showing now are correct. # >>> ((A+B*I)*(C+D*I)).expand() # 64471/10000000000 + 2231321613*I/2500000000 # >>> 2231321613*4 # 8925286452L assert NS((A + B*I)*(C + D*I), 6) == '6.44710e-6 + 0.892529*I' assert NS((A + B*I)*(C + D*I), 10) == '6.447100000e-6 + 0.8925286452*I' assert NS((A + B*I)*( C + D*I) - F*I, 5) in ('6.4471e-6 + 0.e-14*I', '6.4471e-6 - 0.e-14*I') def test_evalf_logs(): assert NS("log(3+pi*I)", 15) == '1.46877619736226 + 0.808448792630022*I' assert NS("log(pi*I)", 15) == '1.14472988584940 + 1.57079632679490*I' assert NS('log(-1 + 0.00001)', 2) == '-1.0e-5 + 3.1*I' assert NS('log(100, 10, evaluate=False)', 15) == '2.00000000000000' assert NS('-2*I*log(-(-1)**(S(1)/9))', 15) == '-5.58505360638185' def test_evalf_trig(): assert NS('sin(1)', 15) == '0.841470984807897' assert NS('cos(1)', 15) == '0.540302305868140' assert NS('sin(10**-6)', 15) == '9.99999999999833e-7' assert NS('cos(10**-6)', 15) == '0.999999999999500' assert NS('sin(E*10**100)', 15) == '0.409160531722613' # Some input near roots assert NS(sin(exp(pi*sqrt(163))*pi), 15) == '-2.35596641936785e-12' assert NS(sin(pi*10**100 + Rational(7, 10**5), evaluate=False), 15, maxn=120) == \ '6.99999999428333e-5' assert NS(sin(Rational(7, 10**5), evaluate=False), 15) == \ '6.99999999428333e-5' # Check detection of various false identities def test_evalf_near_integers(): # Binet's formula f = lambda n: ((1 + sqrt(5))**n)/(2**n * sqrt(5)) assert NS(f(5000) - fibonacci(5000), 10, maxn=1500) == '5.156009964e-1046' # Some near-integer identities from # http://mathworld.wolfram.com/AlmostInteger.html assert NS('sin(2017*2**(1/5))', 15) == '-1.00000000000000' assert NS('sin(2017*2**(1/5))', 20) == '-0.99999999999999997857' assert NS('1+sin(2017*2**(1/5))', 15) == '2.14322287389390e-17' assert NS('45 - 613*E/37 + 35/991', 15) == '6.03764498766326e-11' def test_evalf_ramanujan(): assert NS(exp(pi*sqrt(163)) - 640320**3 - 744, 10) == '-7.499274028e-13' # A related identity A = 262537412640768744*exp(-pi*sqrt(163)) B = 196884*exp(-2*pi*sqrt(163)) C = 103378831900730205293632*exp(-3*pi*sqrt(163)) assert NS(1 - A - B + C, 10) == '1.613679005e-59' # Input that for various reasons have failed at some point def test_evalf_bugs(): assert NS(sin(1) + exp(-10**10), 10) == NS(sin(1), 10) assert NS(exp(10**10) + sin(1), 10) == NS(exp(10**10), 10) assert NS('expand_log(log(1+1/10**50))', 20) == '1.0000000000000000000e-50' assert NS('log(10**100,10)', 10) == '100.0000000' assert NS('log(2)', 10) == '0.6931471806' assert NS( '(sin(x)-x)/x**3', 15, subs={x: '1/10**50'}) == '-0.166666666666667' assert NS(sin(1) + Rational( 1, 10**100)*I, 15) == '0.841470984807897 + 1.00000000000000e-100*I' assert x.evalf() == x assert NS((1 + I)**2*I, 6) == '-2.00000' d = {n: ( -1)**Rational(6, 7), y: (-1)**Rational(4, 7), x: (-1)**Rational(2, 7)} assert NS((x*(1 + y*(1 + n))).subs(d).evalf(), 6) == '0.346011 + 0.433884*I' assert NS(((-I - sqrt(2)*I)**2).evalf()) == '-5.82842712474619' assert NS((1 + I)**2*I, 15) == '-2.00000000000000' # issue 4758 (1/2): assert NS(pi.evalf(69) - pi) == '-4.43863937855894e-71' # issue 4758 (2/2): With the bug present, this still only fails if the # terms are in the order given here. This is not generally the case, # because the order depends on the hashes of the terms. assert NS(20 - 5008329267844*n**25 - 477638700*n**37 - 19*n, subs={n: .01}) == '19.8100000000000' assert NS(((x - 1)*(1 - x)**1000).n() ) == '(1.00000000000000 - x)**1000*(x - 1.00000000000000)' assert NS((-x).n()) == '-x' assert NS((-2*x).n()) == '-2.00000000000000*x' assert NS((-2*x*y).n()) == '-2.00000000000000*x*y' assert cos(x).n(subs={x: 1+I}) == cos(x).subs(x, 1+I).n() # issue 6660. Also NaN != mpmath.nan # In this order: # 0*nan, 0/nan, 0*inf, 0/inf # 0+nan, 0-nan, 0+inf, 0-inf # >>> n = Some Number # n*nan, n/nan, n*inf, n/inf # n+nan, n-nan, n+inf, n-inf assert (0*E**(oo)).n() is S.NaN assert (0/E**(oo)).n() is S.Zero assert (0+E**(oo)).n() is S.Infinity assert (0-E**(oo)).n() is S.NegativeInfinity assert (5*E**(oo)).n() is S.Infinity assert (5/E**(oo)).n() is S.Zero assert (5+E**(oo)).n() is S.Infinity assert (5-E**(oo)).n() is S.NegativeInfinity #issue 7416 assert as_mpmath(0.0, 10, {'chop': True}) == 0 #issue 5412 assert ((oo*I).n() == S.Infinity*I) assert ((oo+oo*I).n() == S.Infinity + S.Infinity*I) #issue 11518 assert NS(2*x**2.5, 5) == '2.0000*x**2.5000' #issue 13076 assert NS(Mul(Max(0, y), x, evaluate=False).evalf()) == 'x*Max(0, y)' #issue 18516 assert NS(log(S(3273390607896141870013189696827599152216642046043064789483291368096133796404674554883270092325904157150886684127560071009217256545885393053328527589376)/36360291795869936842385267079543319118023385026001623040346035832580600191583895484198508262979388783308179702534403855752855931517013066142992430916562025780021771247847643450125342836565813209972590371590152578728008385990139795377610001).evalf(15, chop=True)) == '-oo' def test_evalf_integer_parts(): a = floor(log(8)/log(2) - exp(-1000), evaluate=False) b = floor(log(8)/log(2), evaluate=False) assert a.evalf() == 3 assert b.evalf() == 3 # equals, as a fallback, can still fail but it might succeed as here assert ceiling(10*(sin(1)**2 + cos(1)**2)) == 10 assert int(floor(factorial(50)/E, evaluate=False).evalf(70)) == \ int(11188719610782480504630258070757734324011354208865721592720336800) assert int(ceiling(factorial(50)/E, evaluate=False).evalf(70)) == \ int(11188719610782480504630258070757734324011354208865721592720336801) assert int(floor(GoldenRatio**999 / sqrt(5) + S.Half) .evalf(1000)) == fibonacci(999) assert int(floor(GoldenRatio**1000 / sqrt(5) + S.Half) .evalf(1000)) == fibonacci(1000) assert ceiling(x).evalf(subs={x: 3}) == 3 assert ceiling(x).evalf(subs={x: 3*I}) == 3.0*I assert ceiling(x).evalf(subs={x: 2 + 3*I}) == 2.0 + 3.0*I assert ceiling(x).evalf(subs={x: 3.}) == 3 assert ceiling(x).evalf(subs={x: 3.*I}) == 3.0*I assert ceiling(x).evalf(subs={x: 2. + 3*I}) == 2.0 + 3.0*I assert float((floor(1.5, evaluate=False)+1/9).evalf()) == 1 + 1/9 assert float((floor(0.5, evaluate=False)+20).evalf()) == 20 # issue 19991 n = 1169809367327212570704813632106852886389036911 r = 744723773141314414542111064094745678855643068 assert floor(n / (pi / 2)) == r assert floor(80782 * sqrt(2)) == 114242 # issue 20076 assert 260515 - floor(260515/pi + 1/2) * pi == atan(tan(260515)) def test_evalf_trig_zero_detection(): a = sin(160*pi, evaluate=False) t = a.evalf(maxn=100) assert abs(t) < 1e-100 assert t._prec < 2 assert a.evalf(chop=True) == 0 raises(PrecisionExhausted, lambda: a.evalf(strict=True)) def test_evalf_sum(): assert Sum(n,(n,1,2)).evalf() == 3. assert Sum(n,(n,1,2)).doit().evalf() == 3. # the next test should return instantly assert Sum(1/n,(n,1,2)).evalf() == 1.5 # issue 8219 assert Sum(E/factorial(n), (n, 0, oo)).evalf() == (E*E).evalf() # issue 8254 assert Sum(2**n*n/factorial(n), (n, 0, oo)).evalf() == (2*E*E).evalf() # issue 8411 s = Sum(1/x**2, (x, 100, oo)) assert s.n() == s.doit().n() def test_evalf_divergent_series(): raises(ValueError, lambda: Sum(1/n, (n, 1, oo)).evalf()) raises(ValueError, lambda: Sum(n/(n**2 + 1), (n, 1, oo)).evalf()) raises(ValueError, lambda: Sum((-1)**n, (n, 1, oo)).evalf()) raises(ValueError, lambda: Sum((-1)**n, (n, 1, oo)).evalf()) raises(ValueError, lambda: Sum(n**2, (n, 1, oo)).evalf()) raises(ValueError, lambda: Sum(2**n, (n, 1, oo)).evalf()) raises(ValueError, lambda: Sum((-2)**n, (n, 1, oo)).evalf()) raises(ValueError, lambda: Sum((2*n + 3)/(3*n**2 + 4), (n, 0, oo)).evalf()) raises(ValueError, lambda: Sum((0.5*n**3)/(n**4 + 1), (n, 0, oo)).evalf()) def test_evalf_product(): assert Product(n, (n, 1, 10)).evalf() == 3628800. assert comp(Product(1 - S.Half**2/n**2, (n, 1, oo)).n(5), 0.63662) assert Product(n, (n, -1, 3)).evalf() == 0 def test_evalf_py_methods(): assert abs(float(pi + 1) - 4.1415926535897932) < 1e-10 assert abs(complex(pi + 1) - 4.1415926535897932) < 1e-10 assert abs( complex(pi + E*I) - (3.1415926535897931 + 2.7182818284590451j)) < 1e-10 raises(TypeError, lambda: float(pi + x)) def test_evalf_power_subs_bugs(): assert (x**2).evalf(subs={x: 0}) == 0 assert sqrt(x).evalf(subs={x: 0}) == 0 assert (x**Rational(2, 3)).evalf(subs={x: 0}) == 0 assert (x**x).evalf(subs={x: 0}) == 1 assert (3**x).evalf(subs={x: 0}) == 1 assert exp(x).evalf(subs={x: 0}) == 1 assert ((2 + I)**x).evalf(subs={x: 0}) == 1 assert (0**x).evalf(subs={x: 0}) == 1 def test_evalf_arguments(): raises(TypeError, lambda: pi.evalf(method="garbage")) def test_implemented_function_evalf(): from sympy.utilities.lambdify import implemented_function f = Function('f') f = implemented_function(f, lambda x: x + 1) assert str(f(x)) == "f(x)" assert str(f(2)) == "f(2)" assert f(2).evalf() == 3 assert f(x).evalf() == f(x) f = implemented_function(Function('sin'), lambda x: x + 1) assert f(2).evalf() != sin(2) del f._imp_ # XXX: due to caching _imp_ would influence all other tests def test_evaluate_false(): for no in [0, False]: assert Add(3, 2, evaluate=no).is_Add assert Mul(3, 2, evaluate=no).is_Mul assert Pow(3, 2, evaluate=no).is_Pow assert Pow(y, 2, evaluate=True) - Pow(y, 2, evaluate=True) == 0 def test_evalf_relational(): assert Eq(x/5, y/10).evalf() == Eq(0.2*x, 0.1*y) # if this first assertion fails it should be replaced with # one that doesn't assert unchanged(Eq, (3 - I)**2/2 + I, 0) assert Eq((3 - I)**2/2 + I, 0).n() is S.false assert nfloat(Eq((3 - I)**2 + I, 0)) == S.false def test_issue_5486(): assert not cos(sqrt(0.5 + I)).n().is_Function def test_issue_5486_bug(): from sympy.core.expr import Expr from sympy.core.numbers import I assert abs(Expr._from_mpmath(I._to_mpmath(15), 15) - I) < 1.0e-15 def test_bugs(): from sympy.functions.elementary.complexes import (polar_lift, re) assert abs(re((1 + I)**2)) < 1e-15 # anything that evalf's to 0 will do in place of polar_lift assert abs(polar_lift(0)).n() == 0 def test_subs(): assert NS('besseli(-x, y) - besseli(x, y)', subs={x: 3.5, y: 20.0}) == \ '-4.92535585957223e-10' assert NS('Piecewise((x, x>0)) + Piecewise((1-x, x>0))', subs={x: 0.1}) == \ '1.00000000000000' raises(TypeError, lambda: x.evalf(subs=(x, 1))) def test_issue_4956_5204(): # issue 4956 v = S('''(-27*12**(1/3)*sqrt(31)*I + 27*2**(2/3)*3**(1/3)*sqrt(31)*I)/(-2511*2**(2/3)*3**(1/3) + (29*18**(1/3) + 9*2**(1/3)*3**(2/3)*sqrt(31)*I + 87*2**(1/3)*3**(1/6)*I)**2)''') assert NS(v, 1) == '0.e-118 - 0.e-118*I' # issue 5204 v = S('''-(357587765856 + 18873261792*249**(1/2) + 56619785376*I*83**(1/2) + 108755765856*I*3**(1/2) + 41281887168*6**(1/3)*(1422 + 54*249**(1/2))**(1/3) - 1239810624*6**(1/3)*249**(1/2)*(1422 + 54*249**(1/2))**(1/3) - 3110400000*I*6**(1/3)*83**(1/2)*(1422 + 54*249**(1/2))**(1/3) + 13478400000*I*3**(1/2)*6**(1/3)*(1422 + 54*249**(1/2))**(1/3) + 1274950152*6**(2/3)*(1422 + 54*249**(1/2))**(2/3) + 32347944*6**(2/3)*249**(1/2)*(1422 + 54*249**(1/2))**(2/3) - 1758790152*I*3**(1/2)*6**(2/3)*(1422 + 54*249**(1/2))**(2/3) - 304403832*I*6**(2/3)*83**(1/2)*(1422 + 4*249**(1/2))**(2/3))/(175732658352 + (1106028 + 25596*249**(1/2) + 76788*I*83**(1/2))**2)''') assert NS(v, 5) == '0.077284 + 1.1104*I' assert NS(v, 1) == '0.08 + 1.*I' def test_old_docstring(): a = (E + pi*I)*(E - pi*I) assert NS(a) == '17.2586605000200' assert a.n() == 17.25866050002001 def test_issue_4806(): assert integrate(atan(x)**2, (x, -1, 1)).evalf().round(1) == 0.5 assert atan(0, evaluate=False).n() == 0 def test_evalf_mul(): # SymPy should not try to expand this; it should be handled term-wise # in evalf through mpmath assert NS(product(1 + sqrt(n)*I, (n, 1, 500)), 1) == '5.e+567 + 2.e+568*I' def test_scaled_zero(): a, b = (([0], 1, 100, 1), -1) assert scaled_zero(100) == (a, b) assert scaled_zero(a) == (0, 1, 100, 1) a, b = (([1], 1, 100, 1), -1) assert scaled_zero(100, -1) == (a, b) assert scaled_zero(a) == (1, 1, 100, 1) raises(ValueError, lambda: scaled_zero(scaled_zero(100))) raises(ValueError, lambda: scaled_zero(100, 2)) raises(ValueError, lambda: scaled_zero(100, 0)) raises(ValueError, lambda: scaled_zero((1, 5, 1, 3))) def test_chop_value(): for i in range(-27, 28): assert (Pow(10, i)*2).n(chop=10**i) and not (Pow(10, i)).n(chop=10**i) def test_infinities(): assert oo.evalf(chop=True) == inf assert (-oo).evalf(chop=True) == ninf def test_to_mpmath(): assert sqrt(3)._to_mpmath(20)._mpf_ == (0, int(908093), -19, 20) assert S(3.2)._to_mpmath(20)._mpf_ == (0, int(838861), -18, 20) def test_issue_6632_evalf(): add = (-100000*sqrt(2500000001) + 5000000001) assert add.n() == 9.999999998e-11 assert (add*add).n() == 9.999999996e-21 def test_issue_4945(): from sympy.abc import H assert (H/0).evalf(subs={H:1}) == zoo def test_evalf_integral(): # test that workprec has to increase in order to get a result other than 0 eps = Rational(1, 1000000) assert Integral(sin(x), (x, -pi, pi + eps)).n(2)._prec == 10 def test_issue_8821_highprec_from_str(): s = str(pi.evalf(128)) p = N(s) assert Abs(sin(p)) < 1e-15 p = N(s, 64) assert Abs(sin(p)) < 1e-64 def test_issue_8853(): p = Symbol('x', even=True, positive=True) assert floor(-p - S.Half).is_even == False assert floor(-p + S.Half).is_even == True assert ceiling(p - S.Half).is_even == True assert ceiling(p + S.Half).is_even == False assert get_integer_part(S.Half, -1, {}, True) == (0, 0) assert get_integer_part(S.Half, 1, {}, True) == (1, 0) assert get_integer_part(Rational(-1, 2), -1, {}, True) == (-1, 0) assert get_integer_part(Rational(-1, 2), 1, {}, True) == (0, 0) def test_issue_17681(): class identity_func(Function): def _eval_evalf(self, *args, **kwargs): return self.args[0].evalf(*args, **kwargs) assert floor(identity_func(S(0))) == 0 assert get_integer_part(S(0), 1, {}, True) == (0, 0) def test_issue_9326(): from sympy.core.symbol import Dummy d1 = Dummy('d') d2 = Dummy('d') e = d1 + d2 assert e.evalf(subs = {d1: 1, d2: 2}) == 3 def test_issue_10323(): assert ceiling(sqrt(2**30 + 1)) == 2**15 + 1 def test_AssocOp_Function(): # the first arg of Min is not comparable in the imaginary part raises(ValueError, lambda: S(''' Min(-sqrt(3)*cos(pi/18)/6 + re(1/((-1/2 - sqrt(3)*I/2)*(1/6 + sqrt(3)*I/18)**(1/3)))/3 + sin(pi/18)/2 + 2 + I*(-cos(pi/18)/2 - sqrt(3)*sin(pi/18)/6 + im(1/((-1/2 - sqrt(3)*I/2)*(1/6 + sqrt(3)*I/18)**(1/3)))/3), re(1/((-1/2 + sqrt(3)*I/2)*(1/6 + sqrt(3)*I/18)**(1/3)))/3 - sqrt(3)*cos(pi/18)/6 - sin(pi/18)/2 + 2 + I*(im(1/((-1/2 + sqrt(3)*I/2)*(1/6 + sqrt(3)*I/18)**(1/3)))/3 - sqrt(3)*sin(pi/18)/6 + cos(pi/18)/2))''')) # if that is changed so a non-comparable number remains as # an arg, then the Min/Max instantiation needs to be changed # to watch out for non-comparable args when making simplifications # and the following test should be added instead (with e being # the sympified expression above): # raises(ValueError, lambda: e._eval_evalf(2)) def test_issue_10395(): eq = x*Max(0, y) assert nfloat(eq) == eq eq = x*Max(y, -1.1) assert nfloat(eq) == eq assert Max(y, 4).n() == Max(4.0, y) def test_issue_13098(): assert floor(log(S('9.'+'9'*20), 10)) == 0 assert ceiling(log(S('9.'+'9'*20), 10)) == 1 assert floor(log(20 - S('9.'+'9'*20), 10)) == 1 assert ceiling(log(20 - S('9.'+'9'*20), 10)) == 2 def test_issue_14601(): e = 5*x*y/2 - y*(35*(x**3)/2 - 15*x/2) subst = {x:0.0, y:0.0} e2 = e.evalf(subs=subst) assert float(e2) == 0.0 assert float((x + x*(x**2 + x)).evalf(subs={x: 0.0})) == 0.0 def test_issue_11151(): z = S.Zero e = Sum(z, (x, 1, 2)) assert e != z # it shouldn't evaluate # when it does evaluate, this is what it should give assert evalf(e, 15, {}) == \ evalf(z, 15, {}) == (None, None, 15, None) # so this shouldn't fail assert (e/2).n() == 0 # this was where the issue appeared expr0 = Sum(x**2 + x, (x, 1, 2)) expr1 = Sum(0, (x, 1, 2)) expr2 = expr1/expr0 assert simplify(factor(expr2) - expr2) == 0 def test_issue_13425(): assert N('2**.5', 30) == N('sqrt(2)', 30) assert N('x - x', 30) == 0 assert abs((N('pi*.1', 22)*10 - pi).n()) < 1e-22 def test_issue_17421(): assert N(acos(-I + acosh(cosh(cosh(1) + I)))) == 1.0*I def test_issue_20291(): from sympy.sets import EmptySet, Reals from sympy.sets.sets import (Complement, FiniteSet, Intersection) a = Symbol('a') b = Symbol('b') A = FiniteSet(a, b) assert A.evalf(subs={a: 1, b: 2}) == FiniteSet(1.0, 2.0) B = FiniteSet(a-b, 1) assert B.evalf(subs={a: 1, b: 2}) == FiniteSet(-1.0, 1.0) sol = Complement(Intersection(FiniteSet(-b/2 - sqrt(b**2-4*pi)/2), Reals), FiniteSet(0)) assert sol.evalf(subs={b: 1}) == EmptySet def test_evalf_with_zoo(): assert (1/x).evalf(subs={x: 0}) == zoo # issue 8242 assert (-1/x).evalf(subs={x: 0}) == zoo # PR 16150 assert (0 ** x).evalf(subs={x: -1}) == zoo # PR 16150 assert (0 ** x).evalf(subs={x: -1 + I}) == nan assert Mul(2, Pow(0, -1, evaluate=False), evaluate=False).evalf() == zoo # issue 21147 assert Mul(x, 1/x, evaluate=False).evalf(subs={x: 0}) == Mul(x, 1/x, evaluate=False).subs(x, 0) == nan assert Mul(1/x, 1/x, evaluate=False).evalf(subs={x: 0}) == zoo assert Mul(1/x, Abs(1/x), evaluate=False).evalf(subs={x: 0}) == zoo assert Abs(zoo, evaluate=False).evalf() == oo assert re(zoo, evaluate=False).evalf() == nan assert im(zoo, evaluate=False).evalf() == nan assert Add(zoo, zoo, evaluate=False).evalf() == nan assert Add(oo, zoo, evaluate=False).evalf() == nan assert Pow(zoo, -1, evaluate=False).evalf() == 0 assert Pow(zoo, Rational(-1, 3), evaluate=False).evalf() == 0 assert Pow(zoo, Rational(1, 3), evaluate=False).evalf() == zoo assert Pow(zoo, S.Half, evaluate=False).evalf() == zoo assert Pow(zoo, 2, evaluate=False).evalf() == zoo assert Pow(0, zoo, evaluate=False).evalf() == nan assert log(zoo, evaluate=False).evalf() == zoo assert zoo.evalf(chop=True) == zoo assert x.evalf(subs={x: zoo}) == zoo
9568fb55832fd1849b1a16f13b4e2ac7058d24350b02ad1fdd4908aa6b279827
from sympy import abc from sympy.concrete.summations import Sum from sympy.core.add import Add from sympy.core.function import (Derivative, Function, diff) from sympy.core.mul import Mul from sympy.core.numbers import (Float, I, Integer, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, Wild, symbols) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.hyper import meijerg from sympy.polys.polytools import Poly from sympy.simplify.radsimp import collect from sympy.simplify.simplify import signsimp from sympy.testing.pytest import XFAIL def test_symbol(): x = Symbol('x') a, b, c, p, q = map(Wild, 'abcpq') e = x assert e.match(x) == {} assert e.matches(x) == {} assert e.match(a) == {a: x} e = Rational(5) assert e.match(c) == {c: 5} assert e.match(e) == {} assert e.match(e + 1) is None def test_add(): x, y, a, b, c = map(Symbol, 'xyabc') p, q, r = map(Wild, 'pqr') e = a + b assert e.match(p + b) == {p: a} assert e.match(p + a) == {p: b} e = 1 + b assert e.match(p + b) == {p: 1} e = a + b + c assert e.match(a + p + c) == {p: b} assert e.match(b + p + c) == {p: a} e = a + b + c + x assert e.match(a + p + x + c) == {p: b} assert e.match(b + p + c + x) == {p: a} assert e.match(b) is None assert e.match(b + p) == {p: a + c + x} assert e.match(a + p + c) == {p: b + x} assert e.match(b + p + c) == {p: a + x} e = 4*x + 5 assert e.match(4*x + p) == {p: 5} assert e.match(3*x + p) == {p: x + 5} assert e.match(p*x + 5) == {p: 4} def test_power(): x, y, a, b, c = map(Symbol, 'xyabc') p, q, r = map(Wild, 'pqr') e = (x + y)**a assert e.match(p**q) == {p: x + y, q: a} assert e.match(p**p) is None e = (x + y)**(x + y) assert e.match(p**p) == {p: x + y} assert e.match(p**q) == {p: x + y, q: x + y} e = (2*x)**2 assert e.match(p*q**r) == {p: 4, q: x, r: 2} e = Integer(1) assert e.match(x**p) == {p: 0} def test_match_exclude(): x = Symbol('x') y = Symbol('y') p = Wild("p") q = Wild("q") r = Wild("r") e = Rational(6) assert e.match(2*p) == {p: 3} e = 3/(4*x + 5) assert e.match(3/(p*x + q)) == {p: 4, q: 5} e = 3/(4*x + 5) assert e.match(p/(q*x + r)) == {p: 3, q: 4, r: 5} e = 2/(x + 1) assert e.match(p/(q*x + r)) == {p: 2, q: 1, r: 1} e = 1/(x + 1) assert e.match(p/(q*x + r)) == {p: 1, q: 1, r: 1} e = 4*x + 5 assert e.match(p*x + q) == {p: 4, q: 5} e = 4*x + 5*y + 6 assert e.match(p*x + q*y + r) == {p: 4, q: 5, r: 6} a = Wild('a', exclude=[x]) e = 3*x assert e.match(p*x) == {p: 3} assert e.match(a*x) == {a: 3} e = 3*x**2 assert e.match(p*x) == {p: 3*x} assert e.match(a*x) is None e = 3*x + 3 + 6/x assert e.match(p*x**2 + p*x + 2*p) == {p: 3/x} assert e.match(a*x**2 + a*x + 2*a) is None def test_mul(): x, y, a, b, c = map(Symbol, 'xyabc') p, q = map(Wild, 'pq') e = 4*x assert e.match(p*x) == {p: 4} assert e.match(p*y) is None assert e.match(e + p*y) == {p: 0} e = a*x*b*c assert e.match(p*x) == {p: a*b*c} assert e.match(c*p*x) == {p: a*b} e = (a + b)*(a + c) assert e.match((p + b)*(p + c)) == {p: a} e = x assert e.match(p*x) == {p: 1} e = exp(x) assert e.match(x**p*exp(x*q)) == {p: 0, q: 1} e = I*Poly(x, x) assert e.match(I*p) == {p: x} def test_mul_noncommutative(): x, y = symbols('x y') A, B, C = symbols('A B C', commutative=False) u, v = symbols('u v', cls=Wild) w, z = symbols('w z', cls=Wild, commutative=False) assert (u*v).matches(x) in ({v: x, u: 1}, {u: x, v: 1}) assert (u*v).matches(x*y) in ({v: y, u: x}, {u: y, v: x}) assert (u*v).matches(A) is None assert (u*v).matches(A*B) is None assert (u*v).matches(x*A) is None assert (u*v).matches(x*y*A) is None assert (u*v).matches(x*A*B) is None assert (u*v).matches(x*y*A*B) is None assert (v*w).matches(x) is None assert (v*w).matches(x*y) is None assert (v*w).matches(A) == {w: A, v: 1} assert (v*w).matches(A*B) == {w: A*B, v: 1} assert (v*w).matches(x*A) == {w: A, v: x} assert (v*w).matches(x*y*A) == {w: A, v: x*y} assert (v*w).matches(x*A*B) == {w: A*B, v: x} assert (v*w).matches(x*y*A*B) == {w: A*B, v: x*y} assert (v*w).matches(-x) is None assert (v*w).matches(-x*y) is None assert (v*w).matches(-A) == {w: A, v: -1} assert (v*w).matches(-A*B) == {w: A*B, v: -1} assert (v*w).matches(-x*A) == {w: A, v: -x} assert (v*w).matches(-x*y*A) == {w: A, v: -x*y} assert (v*w).matches(-x*A*B) == {w: A*B, v: -x} assert (v*w).matches(-x*y*A*B) == {w: A*B, v: -x*y} assert (w*z).matches(x) is None assert (w*z).matches(x*y) is None assert (w*z).matches(A) is None assert (w*z).matches(A*B) == {w: A, z: B} assert (w*z).matches(B*A) == {w: B, z: A} assert (w*z).matches(A*B*C) in [{w: A, z: B*C}, {w: A*B, z: C}] assert (w*z).matches(x*A) is None assert (w*z).matches(x*y*A) is None assert (w*z).matches(x*A*B) is None assert (w*z).matches(x*y*A*B) is None assert (w*A).matches(A) is None assert (A*w*B).matches(A*B) is None assert (u*w*z).matches(x) is None assert (u*w*z).matches(x*y) is None assert (u*w*z).matches(A) is None assert (u*w*z).matches(A*B) == {u: 1, w: A, z: B} assert (u*w*z).matches(B*A) == {u: 1, w: B, z: A} assert (u*w*z).matches(x*A) is None assert (u*w*z).matches(x*y*A) is None assert (u*w*z).matches(x*A*B) == {u: x, w: A, z: B} assert (u*w*z).matches(x*B*A) == {u: x, w: B, z: A} assert (u*w*z).matches(x*y*A*B) == {u: x*y, w: A, z: B} assert (u*w*z).matches(x*y*B*A) == {u: x*y, w: B, z: A} assert (u*A).matches(x*A) == {u: x} assert (u*A).matches(x*A*B) is None assert (u*B).matches(x*A) is None assert (u*A*B).matches(x*A*B) == {u: x} assert (u*A*B).matches(x*B*A) is None assert (u*A*B).matches(x*A) is None assert (u*w*A).matches(x*A*B) is None assert (u*w*B).matches(x*A*B) == {u: x, w: A} assert (u*v*A*B).matches(x*A*B) in [{u: x, v: 1}, {v: x, u: 1}] assert (u*v*A*B).matches(x*B*A) is None assert (u*v*A*B).matches(u*v*A*C) is None def test_mul_noncommutative_mismatch(): A, B, C = symbols('A B C', commutative=False) w = symbols('w', cls=Wild, commutative=False) assert (w*B*w).matches(A*B*A) == {w: A} assert (w*B*w).matches(A*C*B*A*C) == {w: A*C} assert (w*B*w).matches(A*C*B*A*B) is None assert (w*B*w).matches(A*B*C) is None assert (w*w*C).matches(A*B*C) is None def test_mul_noncommutative_pow(): A, B, C = symbols('A B C', commutative=False) w = symbols('w', cls=Wild, commutative=False) assert (A*B*w).matches(A*B**2) == {w: B} assert (A*(B**2)*w*(B**3)).matches(A*B**8) == {w: B**3} assert (A*B*w*C).matches(A*(B**4)*C) == {w: B**3} assert (A*B*(w**(-1))).matches(A*B*(C**(-1))) == {w: C} assert (A*(B*w)**(-1)*C).matches(A*(B*C)**(-1)*C) == {w: C} assert ((w**2)*B*C).matches((A**2)*B*C) == {w: A} assert ((w**2)*B*(w**3)).matches((A**2)*B*(A**3)) == {w: A} assert ((w**2)*B*(w**4)).matches((A**2)*B*(A**2)) is None def test_complex(): a, b, c = map(Symbol, 'abc') x, y = map(Wild, 'xy') assert (1 + I).match(x + I) == {x: 1} assert (a + I).match(x + I) == {x: a} assert (2*I).match(x*I) == {x: 2} assert (a*I).match(x*I) == {x: a} assert (a*I).match(x*y) == {x: I, y: a} assert (2*I).match(x*y) == {x: 2, y: I} assert (a + b*I).match(x + y*I) == {x: a, y: b} def test_functions(): from sympy.core.function import WildFunction x = Symbol('x') g = WildFunction('g') p = Wild('p') q = Wild('q') f = cos(5*x) notf = x assert f.match(p*cos(q*x)) == {p: 1, q: 5} assert f.match(p*g) == {p: 1, g: cos(5*x)} assert notf.match(g) is None @XFAIL def test_functions_X1(): from sympy.core.function import WildFunction x = Symbol('x') g = WildFunction('g') p = Wild('p') q = Wild('q') f = cos(5*x) assert f.match(p*g(q*x)) == {p: 1, g: cos, q: 5} def test_interface(): x, y = map(Symbol, 'xy') p, q = map(Wild, 'pq') assert (x + 1).match(p + 1) == {p: x} assert (x*3).match(p*3) == {p: x} assert (x**3).match(p**3) == {p: x} assert (x*cos(y)).match(p*cos(q)) == {p: x, q: y} assert (x*y).match(p*q) in [{p:x, q:y}, {p:y, q:x}] assert (x + y).match(p + q) in [{p:x, q:y}, {p:y, q:x}] assert (x*y + 1).match(p*q) in [{p:1, q:1 + x*y}, {p:1 + x*y, q:1}] def test_derivative1(): x, y = map(Symbol, 'xy') p, q = map(Wild, 'pq') f = Function('f', nargs=1) fd = Derivative(f(x), x) assert fd.match(p) == {p: fd} assert (fd + 1).match(p + 1) == {p: fd} assert (fd).match(fd) == {} assert (3*fd).match(p*fd) is not None assert (3*fd - 1).match(p*fd + q) == {p: 3, q: -1} def test_derivative_bug1(): f = Function("f") x = Symbol("x") a = Wild("a", exclude=[f, x]) b = Wild("b", exclude=[f]) pattern = a * Derivative(f(x), x, x) + b expr = Derivative(f(x), x) + x**2 d1 = {b: x**2} d2 = pattern.xreplace(d1).matches(expr, d1) assert d2 is None def test_derivative2(): f = Function("f") x = Symbol("x") a = Wild("a", exclude=[f, x]) b = Wild("b", exclude=[f]) e = Derivative(f(x), x) assert e.match(Derivative(f(x), x)) == {} assert e.match(Derivative(f(x), x, x)) is None e = Derivative(f(x), x, x) assert e.match(Derivative(f(x), x)) is None assert e.match(Derivative(f(x), x, x)) == {} e = Derivative(f(x), x) + x**2 assert e.match(a*Derivative(f(x), x) + b) == {a: 1, b: x**2} assert e.match(a*Derivative(f(x), x, x) + b) is None e = Derivative(f(x), x, x) + x**2 assert e.match(a*Derivative(f(x), x) + b) is None assert e.match(a*Derivative(f(x), x, x) + b) == {a: 1, b: x**2} def test_match_deriv_bug1(): n = Function('n') l = Function('l') x = Symbol('x') p = Wild('p') e = diff(l(x), x)/x - diff(diff(n(x), x), x)/2 - \ diff(n(x), x)**2/4 + diff(n(x), x)*diff(l(x), x)/4 e = e.subs(n(x), -l(x)).doit() t = x*exp(-l(x)) t2 = t.diff(x, x)/t assert e.match( (p*t2).expand() ) == {p: Rational(-1, 2)} def test_match_bug2(): x, y = map(Symbol, 'xy') p, q, r = map(Wild, 'pqr') res = (x + y).match(p + q + r) assert (p + q + r).subs(res) == x + y def test_match_bug3(): x, a, b = map(Symbol, 'xab') p = Wild('p') assert (b*x*exp(a*x)).match(x*exp(p*x)) is None def test_match_bug4(): x = Symbol('x') p = Wild('p') e = x assert e.match(-p*x) == {p: -1} def test_match_bug5(): x = Symbol('x') p = Wild('p') e = -x assert e.match(-p*x) == {p: 1} def test_match_bug6(): x = Symbol('x') p = Wild('p') e = x assert e.match(3*p*x) == {p: Rational(1)/3} def test_match_polynomial(): x = Symbol('x') a = Wild('a', exclude=[x]) b = Wild('b', exclude=[x]) c = Wild('c', exclude=[x]) d = Wild('d', exclude=[x]) eq = 4*x**3 + 3*x**2 + 2*x + 1 pattern = a*x**3 + b*x**2 + c*x + d assert eq.match(pattern) == {a: 4, b: 3, c: 2, d: 1} assert (eq - 3*x**2).match(pattern) == {a: 4, b: 0, c: 2, d: 1} assert (x + sqrt(2) + 3).match(a + b*x + c*x**2) == \ {b: 1, a: sqrt(2) + 3, c: 0} def test_exclude(): x, y, a = map(Symbol, 'xya') p = Wild('p', exclude=[1, x]) q = Wild('q') r = Wild('r', exclude=[sin, y]) assert sin(x).match(r) is None assert cos(y).match(r) is None e = 3*x**2 + y*x + a assert e.match(p*x**2 + q*x + r) == {p: 3, q: y, r: a} e = x + 1 assert e.match(x + p) is None assert e.match(p + 1) is None assert e.match(x + 1 + p) == {p: 0} e = cos(x) + 5*sin(y) assert e.match(r) is None assert e.match(cos(y) + r) is None assert e.match(r + p*sin(q)) == {r: cos(x), p: 5, q: y} def test_floats(): a, b = map(Wild, 'ab') e = cos(0.12345, evaluate=False)**2 r = e.match(a*cos(b)**2) assert r == {a: 1, b: Float(0.12345)} def test_Derivative_bug1(): f = Function("f") x = abc.x a = Wild("a", exclude=[f(x)]) b = Wild("b", exclude=[f(x)]) eq = f(x).diff(x) assert eq.match(a*Derivative(f(x), x) + b) == {a: 1, b: 0} def test_match_wild_wild(): p = Wild('p') q = Wild('q') r = Wild('r') assert p.match(q + r) in [ {q: p, r: 0}, {q: 0, r: p} ] assert p.match(q*r) in [ {q: p, r: 1}, {q: 1, r: p} ] p = Wild('p') q = Wild('q', exclude=[p]) r = Wild('r') assert p.match(q + r) == {q: 0, r: p} assert p.match(q*r) == {q: 1, r: p} p = Wild('p') q = Wild('q', exclude=[p]) r = Wild('r', exclude=[p]) assert p.match(q + r) is None assert p.match(q*r) is None def test__combine_inverse(): x, y = symbols("x y") assert Mul._combine_inverse(x*I*y, x*I) == y assert Mul._combine_inverse(x*x**(1 + y), x**(1 + y)) == x assert Mul._combine_inverse(x*I*y, y*I) == x assert Mul._combine_inverse(oo*I*y, y*I) is oo assert Mul._combine_inverse(oo*I*y, oo*I) == y assert Mul._combine_inverse(oo*I*y, oo*I) == y assert Mul._combine_inverse(oo*y, -oo) == -y assert Mul._combine_inverse(-oo*y, oo) == -y assert Mul._combine_inverse((1-exp(x/y)),(exp(x/y)-1)) == -1 assert Add._combine_inverse(oo, oo) is S.Zero assert Add._combine_inverse(oo*I, oo*I) is S.Zero assert Add._combine_inverse(x*oo, x*oo) is S.Zero assert Add._combine_inverse(-x*oo, -x*oo) is S.Zero assert Add._combine_inverse((x - oo)*(x + oo), -oo) def test_issue_3773(): x = symbols('x') z, phi, r = symbols('z phi r') c, A, B, N = symbols('c A B N', cls=Wild) l = Wild('l', exclude=(0,)) eq = z * sin(2*phi) * r**7 matcher = c * sin(phi*N)**l * r**A * log(r)**B assert eq.match(matcher) == {c: z, l: 1, N: 2, A: 7, B: 0} assert (-eq).match(matcher) == {c: -z, l: 1, N: 2, A: 7, B: 0} assert (x*eq).match(matcher) == {c: x*z, l: 1, N: 2, A: 7, B: 0} assert (-7*x*eq).match(matcher) == {c: -7*x*z, l: 1, N: 2, A: 7, B: 0} matcher = c*sin(phi*N)**l * r**A assert eq.match(matcher) == {c: z, l: 1, N: 2, A: 7} assert (-eq).match(matcher) == {c: -z, l: 1, N: 2, A: 7} assert (x*eq).match(matcher) == {c: x*z, l: 1, N: 2, A: 7} assert (-7*x*eq).match(matcher) == {c: -7*x*z, l: 1, N: 2, A: 7} def test_issue_3883(): from sympy.abc import gamma, mu, x f = (-gamma * (x - mu)**2 - log(gamma) + log(2*pi))/2 a, b, c = symbols('a b c', cls=Wild, exclude=(gamma,)) assert f.match(a * log(gamma) + b * gamma + c) == \ {a: Rational(-1, 2), b: -(-mu + x)**2/2, c: log(2*pi)/2} assert f.expand().collect(gamma).match(a * log(gamma) + b * gamma + c) == \ {a: Rational(-1, 2), b: (-(x - mu)**2/2).expand(), c: (log(2*pi)/2).expand()} g1 = Wild('g1', exclude=[gamma]) g2 = Wild('g2', exclude=[gamma]) g3 = Wild('g3', exclude=[gamma]) assert f.expand().match(g1 * log(gamma) + g2 * gamma + g3) == \ {g3: log(2)/2 + log(pi)/2, g1: Rational(-1, 2), g2: -mu**2/2 + mu*x - x**2/2} def test_issue_4418(): x = Symbol('x') a, b, c = symbols('a b c', cls=Wild, exclude=(x,)) f, g = symbols('f g', cls=Function) eq = diff(g(x)*f(x).diff(x), x) assert eq.match( g(x).diff(x)*f(x).diff(x) + g(x)*f(x).diff(x, x) + c) == {c: 0} assert eq.match(a*g(x).diff( x)*f(x).diff(x) + b*g(x)*f(x).diff(x, x) + c) == {a: 1, b: 1, c: 0} def test_issue_4700(): f = Function('f') x = Symbol('x') a, b = symbols('a b', cls=Wild, exclude=(f(x),)) p = a*f(x) + b eq1 = sin(x) eq2 = f(x) + sin(x) eq3 = f(x) + x + sin(x) eq4 = x + sin(x) assert eq1.match(p) == {a: 0, b: sin(x)} assert eq2.match(p) == {a: 1, b: sin(x)} assert eq3.match(p) == {a: 1, b: x + sin(x)} assert eq4.match(p) == {a: 0, b: x + sin(x)} def test_issue_5168(): a, b, c = symbols('a b c', cls=Wild) x = Symbol('x') f = Function('f') assert x.match(a) == {a: x} assert x.match(a*f(x)**c) == {a: x, c: 0} assert x.match(a*b) == {a: 1, b: x} assert x.match(a*b*f(x)**c) == {a: 1, b: x, c: 0} assert (-x).match(a) == {a: -x} assert (-x).match(a*f(x)**c) == {a: -x, c: 0} assert (-x).match(a*b) == {a: -1, b: x} assert (-x).match(a*b*f(x)**c) == {a: -1, b: x, c: 0} assert (2*x).match(a) == {a: 2*x} assert (2*x).match(a*f(x)**c) == {a: 2*x, c: 0} assert (2*x).match(a*b) == {a: 2, b: x} assert (2*x).match(a*b*f(x)**c) == {a: 2, b: x, c: 0} assert (-2*x).match(a) == {a: -2*x} assert (-2*x).match(a*f(x)**c) == {a: -2*x, c: 0} assert (-2*x).match(a*b) == {a: -2, b: x} assert (-2*x).match(a*b*f(x)**c) == {a: -2, b: x, c: 0} def test_issue_4559(): x = Symbol('x') e = Symbol('e') w = Wild('w', exclude=[x]) y = Wild('y') # this is as it should be assert (3/x).match(w/y) == {w: 3, y: x} assert (3*x).match(w*y) == {w: 3, y: x} assert (x/3).match(y/w) == {w: 3, y: x} assert (3*x).match(y/w) == {w: S.One/3, y: x} assert (3*x).match(y/w) == {w: Rational(1, 3), y: x} # these could be allowed to fail assert (x/3).match(w/y) == {w: S.One/3, y: 1/x} assert (3*x).match(w/y) == {w: 3, y: 1/x} assert (3/x).match(w*y) == {w: 3, y: 1/x} # Note that solve will give # multiple roots but match only gives one: # # >>> solve(x**r-y**2,y) # [-x**(r/2), x**(r/2)] r = Symbol('r', rational=True) assert (x**r).match(y**2) == {y: x**(r/2)} assert (x**e).match(y**2) == {y: sqrt(x**e)} # since (x**i = y) -> x = y**(1/i) where i is an integer # the following should also be valid as long as y is not # zero when i is negative. a = Wild('a') e = S.Zero assert e.match(a) == {a: e} assert e.match(1/a) is None assert e.match(a**.3) is None e = S(3) assert e.match(1/a) == {a: 1/e} assert e.match(1/a**2) == {a: 1/sqrt(e)} e = pi assert e.match(1/a) == {a: 1/e} assert e.match(1/a**2) == {a: 1/sqrt(e)} assert (-e).match(sqrt(a)) is None assert (-e).match(a**2) == {a: I*sqrt(pi)} # The pattern matcher doesn't know how to handle (x - a)**2 == (a - x)**2. To # avoid ambiguity in actual applications, don't put a coefficient (including a # minus sign) in front of a wild. @XFAIL def test_issue_4883(): a = Wild('a') x = Symbol('x') e = [i**2 for i in (x - 2, 2 - x)] p = [i**2 for i in (x - a, a- x)] for eq in e: for pat in p: assert eq.match(pat) == {a: 2} def test_issue_4319(): x, y = symbols('x y') p = -x*(S.One/8 - y) ans = {S.Zero, y - S.One/8} def ok(pat): assert set(p.match(pat).values()) == ans ok(Wild("coeff", exclude=[x])*x + Wild("rest")) ok(Wild("w", exclude=[x])*x + Wild("rest")) ok(Wild("coeff", exclude=[x])*x + Wild("rest")) ok(Wild("w", exclude=[x])*x + Wild("rest")) ok(Wild("e", exclude=[x])*x + Wild("rest")) ok(Wild("ress", exclude=[x])*x + Wild("rest")) ok(Wild("resu", exclude=[x])*x + Wild("rest")) def test_issue_3778(): p, c, q = symbols('p c q', cls=Wild) x = Symbol('x') assert (sin(x)**2).match(sin(p)*sin(q)*c) == {q: x, c: 1, p: x} assert (2*sin(x)).match(sin(p) + sin(q) + c) == {q: x, c: 0, p: x} def test_issue_6103(): x = Symbol('x') a = Wild('a') assert (-I*x*oo).match(I*a*oo) == {a: -x} def test_issue_3539(): a = Wild('a') x = Symbol('x') assert (x - 2).match(a - x) is None assert (6/x).match(a*x) is None assert (6/x**2).match(a/x) == {a: 6/x} def test_gh_issue_2711(): x = Symbol('x') f = meijerg(((), ()), ((0,), ()), x) a = Wild('a') b = Wild('b') assert f.find(a) == {(S.Zero,), ((), ()), ((S.Zero,), ()), x, S.Zero, (), meijerg(((), ()), ((S.Zero,), ()), x)} assert f.find(a + b) == \ {meijerg(((), ()), ((S.Zero,), ()), x), x, S.Zero} assert f.find(a**2) == {meijerg(((), ()), ((S.Zero,), ()), x), x} def test_issue_17354(): from sympy.core.symbol import (Wild, symbols) x, y = symbols("x y", real=True) a, b = symbols("a b", cls=Wild) assert ((0 <= x).reversed | (y <= x)).match((1/a <= b) | (a <= b)) is None def test_match_issue_17397(): f = Function("f") x = Symbol("x") a3 = Wild('a3', exclude=[f(x), f(x).diff(x), f(x).diff(x, 2)]) b3 = Wild('b3', exclude=[f(x), f(x).diff(x), f(x).diff(x, 2)]) c3 = Wild('c3', exclude=[f(x), f(x).diff(x), f(x).diff(x, 2)]) deq = a3*(f(x).diff(x, 2)) + b3*f(x).diff(x) + c3*f(x) eq = (x-2)**2*(f(x).diff(x, 2)) + (x-2)*(f(x).diff(x)) + ((x-2)**2 - 4)*f(x) r = collect(eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq) assert r == {a3: (x - 2)**2, c3: (x - 2)**2 - 4, b3: x - 2} eq =x*f(x) + x*Derivative(f(x), (x, 2)) - 4*f(x) + Derivative(f(x), x) \ - 4*Derivative(f(x), (x, 2)) - 2*Derivative(f(x), x)/x + 4*Derivative(f(x), (x, 2))/x r = collect(eq, [f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq) assert r == {a3: x - 4 + 4/x, b3: 1 - 2/x, c3: x - 4} def test_match_issue_21942(): a, r, w = symbols('a, r, w', nonnegative=True) p = symbols('p', positive=True) g_ = Wild('g') pattern = g_ ** (1 / (1 - p)) eq = (a * r ** (1 - p) + w ** (1 - p) * (1 - a)) ** (1 / (1 - p)) m = {g_: a * r ** (1 - p) + w ** (1 - p) * (1 - a)} assert pattern.matches(eq) == m assert (-pattern).matches(-eq) == m assert pattern.matches(signsimp(eq)) is None def test_match_terms(): X, Y = map(Wild, "XY") x, y, z = symbols('x y z') assert (5*y - x).match(5*X - Y) == {X: y, Y: x} # 15907 assert (x + (y - 1)*z).match(x + X*z) == {X: y - 1} # 20747 assert (x - log(x/y)*(1-exp(x/y))).match(x - log(X/y)*(1-exp(x/y))) == {X: x} def test_match_bound(): V, W = map(Wild, "VW") x, y = symbols('x y') assert Sum(x, (x, 1, 2)).match(Sum(y, (y, 1, W))) == {W: 2} assert Sum(x, (x, 1, 2)).match(Sum(V, (V, 1, W))) == {W: 2, V:x} assert Sum(x, (x, 1, 2)).match(Sum(V, (V, 1, 2))) == {V:x}
ba5e8db1cf3bfd711fefb230130c399485a9ceba0289f89bcbd9272b769900c9
from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.mod import Mod from sympy.core.mul import Mul from sympy.core.numbers import (Float, I, Integer, Rational, comp, nan, oo, pi, zoo) from sympy.core.power import Pow from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol, symbols) from sympy.core.sympify import sympify from sympy.functions.combinatorial.factorials import factorial from sympy.functions.elementary.complexes import (im, re, sign) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.integers import floor from sympy.functions.elementary.miscellaneous import (Max, sqrt) from sympy.functions.elementary.trigonometric import (atan, cos, sin) from sympy.polys.polytools import Poly from sympy.sets.sets import FiniteSet from sympy.core.parameters import distribute from sympy.core.expr import unchanged from sympy.utilities.iterables import permutations from sympy.testing.pytest import XFAIL, raises, warns_deprecated_sympy from sympy.testing.randtest import verify_numerically from sympy.functions.elementary.trigonometric import asin from itertools import product 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) 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/2).is_integer is True assert (e**2/2).is_integer is True assert (2/k).is_integer is None assert (2/k**2).is_integer is None assert ((-1)**k*n).is_integer is True assert (3*k*e/2).is_integer is True assert (2*k*e/3).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(k, 1/k, evaluate=False).is_integer is None assert Mul(2., S.Half, evaluate=False).is_integer is None assert (2*sqrt(k)).is_integer is None assert (2*k**n).is_integer is None s = 2**2**2**Pow(2, 1000, evaluate=False) m = Mul(s, s, evaluate=False) assert m.is_integer # broken in 1.6 and before, see #20161 xq = Symbol('xq', rational=True) yq = Symbol('yq', rational=True) assert (xq*yq).is_integer is None e_20161 = Mul(-1,Mul(1,Pow(2,-1,evaluate=False),evaluate=False),evaluate=False) assert e_20161.is_integer is not True # expand(e_20161) -> -1/2, but no need to see that in the assumption without evaluation 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 # issue 8648 assert (m**2/2).is_even assert (m**2/3).is_even is False assert (2/m**2).is_odd is False assert (2/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 assert (-1/(x + 1)).is_integer is False # issue 8648-like k = Symbol('k', even=True) assert (k**3/2).is_integer assert (k**3/8).is_integer assert (k**3/16).is_integer is None assert (2/k).is_integer is None assert (2/k**2).is_integer is False o = Symbol('o', odd=True) assert (k/o).is_integer is None o = Symbol('o', odd=True, prime=True) assert (k/o).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 # test issue 20715 from sympy.core.parameters import evaluate x = S(-1) with evaluate(False): assert x.is_negative is True f = Pow(x, -1) with evaluate(False): assert f.is_imaginary is False 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(): 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) # issue 21373 from sympy.functions.elementary.trigonometric import sinh from sympy.functions.elementary.piecewise import Piecewise x_r, y_r = symbols('x_r y_r', real=True) (Piecewise((x_r, y_r > x_r), (y_r, True)) / z) % 1 expr = exp(sinh(Piecewise((x_r, y_r > x_r), (y_r, True)) / z)) expr.subs({1: 1.0}) sinh(Piecewise((x_r, y_r > x_r), (y_r, True)) * z ** -1.0).is_zero 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.functions.elementary.complexes 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 product(*[[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 product(*[[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.functions.elementary.trigonometric 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 def test_issue_17130(): e = Add(b, -b, I, -I, evaluate=False) assert e.is_zero is None # ideally this would be True def test_issue_21034(): e = -I*log((re(asin(5)) + I*im(asin(5)))/sqrt(re(asin(5))**2 + im(asin(5))**2))/pi assert e.round(2) def test_issue_22021(): from sympy.calculus.util import AccumBounds # these objects are special cases in Mul from sympy.tensor.tensor import TensorIndexType, tensor_indices, tensor_heads L = TensorIndexType("L") i = tensor_indices("i", L) A, B = tensor_heads("A B", [L]) e = A(i) + B(i) assert -e == -1*e e = zoo + x assert -e == -1*e a = AccumBounds(1, 2) e = a + x assert -e == -1*e for args in permutations((zoo, a, x)): e = Add(*args, evaluate=False) assert -e == -1*e assert 2*Add(1, x, x, evaluate=False) == 4*x + 2 def test_issue_22244(): assert -(zoo*x) == zoo*x
fd829222877a434a08cfd943b3bf14410aeff4b53eb8a6b3b5def0f0b5b0bb06
from sympy.core.logic import (fuzzy_not, Logic, And, Or, Not, fuzzy_and, fuzzy_or, _fuzzy_group, _torf, fuzzy_nand, fuzzy_xor) from sympy.testing.pytest import raises from itertools import product T = True F = False U = None def test_torf(): v = [T, F, U] for i in product(*[v]*3): assert _torf(i) is (True if all(j for j in i) else (False if all(j is False for j in i) else None)) def test_fuzzy_group(): v = [T, F, U] for i in product(*[v]*3): assert _fuzzy_group(i) is (None if None in i else (True if all(j for j in i) else False)) assert _fuzzy_group(i, quick_exit=True) is \ (None if (i.count(False) > 1) else (None if None in i else (True if all(j for j in i) else False))) it = (True if (i == 0) else None for i in range(2)) assert _torf(it) is None it = (True if (i == 1) else None for i in range(2)) assert _torf(it) is None def test_fuzzy_not(): assert fuzzy_not(T) == F assert fuzzy_not(F) == T assert fuzzy_not(U) == U def test_fuzzy_and(): assert fuzzy_and([T, T]) == T assert fuzzy_and([T, F]) == F assert fuzzy_and([T, U]) == U assert fuzzy_and([F, F]) == F assert fuzzy_and([F, U]) == F assert fuzzy_and([U, U]) == U assert [fuzzy_and([w]) for w in [U, T, F]] == [U, T, F] assert fuzzy_and([T, F, U]) == F assert fuzzy_and([]) == T raises(TypeError, lambda: fuzzy_and()) def test_fuzzy_or(): assert fuzzy_or([T, T]) == T assert fuzzy_or([T, F]) == T assert fuzzy_or([T, U]) == T assert fuzzy_or([F, F]) == F assert fuzzy_or([F, U]) == U assert fuzzy_or([U, U]) == U assert [fuzzy_or([w]) for w in [U, T, F]] == [U, T, F] assert fuzzy_or([T, F, U]) == T assert fuzzy_or([]) == F raises(TypeError, lambda: fuzzy_or()) def test_logic_cmp(): l1 = And('a', Not('b')) l2 = And('a', Not('b')) assert hash(l1) == hash(l2) assert (l1 == l2) == T assert (l1 != l2) == F assert And('a', 'b', 'c') == And('b', 'a', 'c') assert And('a', 'b', 'c') == And('c', 'b', 'a') assert And('a', 'b', 'c') == And('c', 'a', 'b') assert Not('a') < Not('b') assert (Not('b') < Not('a')) is False assert (Not('a') < 2) is False def test_logic_onearg(): assert And() is True assert Or() is False assert And(T) == T assert And(F) == F assert Or(T) == T assert Or(F) == F assert And('a') == 'a' assert Or('a') == 'a' def test_logic_xnotx(): assert And('a', Not('a')) == F assert Or('a', Not('a')) == T def test_logic_eval_TF(): assert And(F, F) == F assert And(F, T) == F assert And(T, F) == F assert And(T, T) == T assert Or(F, F) == F assert Or(F, T) == T assert Or(T, F) == T assert Or(T, T) == T assert And('a', T) == 'a' assert And('a', F) == F assert Or('a', T) == T assert Or('a', F) == 'a' def test_logic_combine_args(): assert And('a', 'b', 'a') == And('a', 'b') assert Or('a', 'b', 'a') == Or('a', 'b') assert And(And('a', 'b'), And('c', 'd')) == And('a', 'b', 'c', 'd') assert Or(Or('a', 'b'), Or('c', 'd')) == Or('a', 'b', 'c', 'd') assert Or('t', And('n', 'p', 'r'), And('n', 'r'), And('n', 'p', 'r'), 't', And('n', 'r')) == Or('t', And('n', 'p', 'r'), And('n', 'r')) def test_logic_expand(): t = And(Or('a', 'b'), 'c') assert t.expand() == Or(And('a', 'c'), And('b', 'c')) t = And(Or('a', Not('b')), 'b') assert t.expand() == And('a', 'b') t = And(Or('a', 'b'), Or('c', 'd')) assert t.expand() == \ Or(And('a', 'c'), And('a', 'd'), And('b', 'c'), And('b', 'd')) def test_logic_fromstring(): S = Logic.fromstring assert S('a') == 'a' assert S('!a') == Not('a') assert S('a & b') == And('a', 'b') assert S('a | b') == Or('a', 'b') assert S('a | b & c') == And(Or('a', 'b'), 'c') assert S('a & b | c') == Or(And('a', 'b'), 'c') assert S('a & b & c') == And('a', 'b', 'c') assert S('a | b | c') == Or('a', 'b', 'c') raises(ValueError, lambda: S('| a')) raises(ValueError, lambda: S('& a')) raises(ValueError, lambda: S('a | | b')) raises(ValueError, lambda: S('a | & b')) raises(ValueError, lambda: S('a & & b')) raises(ValueError, lambda: S('a |')) raises(ValueError, lambda: S('a|b')) raises(ValueError, lambda: S('!')) raises(ValueError, lambda: S('! a')) raises(ValueError, lambda: S('!(a + 1)')) raises(ValueError, lambda: S('')) def test_logic_not(): assert Not('a') != '!a' assert Not('!a') != 'a' assert Not(True) == False assert Not(False) == True # NOTE: we may want to change default Not behaviour and put this # functionality into some method. assert Not(And('a', 'b')) == Or(Not('a'), Not('b')) assert Not(Or('a', 'b')) == And(Not('a'), Not('b')) raises(ValueError, lambda: Not(1)) def test_formatting(): S = Logic.fromstring raises(ValueError, lambda: S('a&b')) raises(ValueError, lambda: S('a|b')) raises(ValueError, lambda: S('! a')) def test_fuzzy_xor(): assert fuzzy_xor((None,)) is None assert fuzzy_xor((None, True)) is None assert fuzzy_xor((None, False)) is None assert fuzzy_xor((True, False)) is True assert fuzzy_xor((True, True)) is False assert fuzzy_xor((True, True, False)) is False assert fuzzy_xor((True, True, False, True)) is True def test_fuzzy_nand(): for args in [(1, 0), (1, 1), (0, 0)]: assert fuzzy_nand(args) == fuzzy_not(fuzzy_and(args))
e8164a62a51e74047e8de1dc220b097a5247156ba8ba09a5d9cd4d3629711998
from sympy.core.sorting import default_sort_key, ordered from sympy.testing.pytest import raises from sympy.abc import x def test_default_sort_key(): func = lambda x: x assert sorted([func, x, func], key=default_sort_key) == [func, func, x] class C: def __repr__(self): return 'x.y' func = C() assert sorted([x, func], key=default_sort_key) == [func, x] def test_ordered(): # Issue 7210 - this had been failing with python2/3 problems assert (list(ordered([{1:3, 2:4, 9:10}, {1:3}])) == \ [{1: 3}, {1: 3, 2: 4, 9: 10}]) # warnings should not be raised for identical items l = [1, 1] assert list(ordered(l, warn=True)) == l l = [[1], [2], [1]] assert list(ordered(l, warn=True)) == [[1], [1], [2]] raises(ValueError, lambda: list(ordered(['a', 'ab'], keys=[lambda x: x[0]], default=False, warn=True)))
4e4eb669c539153ac6a1acdcb1852b8f982c027c1f0f5a782c496a3618cfa5db
"""Tests of tools for setting up interactive IPython sessions. """ from sympy.interactive.session import (init_ipython_session, enable_automatic_symbols, enable_automatic_int_sympification) from sympy.core import Symbol, Rational, Integer from sympy.external import import_module from sympy.testing.pytest import raises # TODO: The code below could be made more granular with something like: # # @requires('IPython', version=">=0.11") # def test_automatic_symbols(ipython): ipython = import_module("IPython", min_module_version="0.11") if not ipython: #bin/test will not execute any tests now disabled = True # WARNING: These tests will modify the existing IPython environment. IPython # uses a single instance for its interpreter, so there is no way to isolate # the test from another IPython session. It also means that if this test is # run twice in the same Python session it will fail. This isn't usually a # problem because the test suite is run in a subprocess by default, but if the # tests are run with subprocess=False it can pollute the current IPython # session. See the discussion in issue #15149. def test_automatic_symbols(): # NOTE: Because of the way the hook works, you have to use run_cell(code, # True). This means that the code must have no Out, or it will be printed # during the tests. app = init_ipython_session() app.run_cell("from sympy import *") enable_automatic_symbols(app) symbol = "verylongsymbolname" assert symbol not in app.user_ns app.run_cell("a = %s" % symbol, True) assert symbol not in app.user_ns app.run_cell("a = type(%s)" % symbol, True) assert app.user_ns['a'] == Symbol app.run_cell("%s = Symbol('%s')" % (symbol, symbol), True) assert symbol in app.user_ns # Check that built-in names aren't overridden app.run_cell("a = all == __builtin__.all", True) assert "all" not in app.user_ns assert app.user_ns['a'] is True # Check that SymPy names aren't overridden app.run_cell("import sympy") app.run_cell("a = factorial == sympy.factorial", True) assert app.user_ns['a'] is True def test_int_to_Integer(): # XXX: Warning, don't test with == here. 0.5 == Rational(1, 2) is True! app = init_ipython_session() app.run_cell("from sympy import Integer") app.run_cell("a = 1") assert isinstance(app.user_ns['a'], int) enable_automatic_int_sympification(app) app.run_cell("a = 1/2") assert isinstance(app.user_ns['a'], Rational) app.run_cell("a = 1") assert isinstance(app.user_ns['a'], Integer) app.run_cell("a = int(1)") assert isinstance(app.user_ns['a'], int) app.run_cell("a = (1/\n2)") assert app.user_ns['a'] == Rational(1, 2) # TODO: How can we test that the output of a SyntaxError is the original # input, not the transformed input? def test_ipythonprinting(): # Initialize and setup IPython session app = init_ipython_session() app.run_cell("ip = get_ipython()") app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy import Symbol") # Printing without printing extension app.run_cell("a = format(Symbol('pi'))") app.run_cell("a2 = format(Symbol('pi')**2)") # Deal with API change starting at IPython 1.0 if int(ipython.__version__.split(".")[0]) < 1: assert app.user_ns['a']['text/plain'] == "pi" assert app.user_ns['a2']['text/plain'] == "pi**2" else: assert app.user_ns['a'][0]['text/plain'] == "pi" assert app.user_ns['a2'][0]['text/plain'] == "pi**2" # Load printing extension app.run_cell("from sympy import init_printing") app.run_cell("init_printing()") # Printing with printing extension app.run_cell("a = format(Symbol('pi'))") app.run_cell("a2 = format(Symbol('pi')**2)") # Deal with API change starting at IPython 1.0 if int(ipython.__version__.split(".")[0]) < 1: assert app.user_ns['a']['text/plain'] in ('\N{GREEK SMALL LETTER PI}', 'pi') assert app.user_ns['a2']['text/plain'] in (' 2\n\N{GREEK SMALL LETTER PI} ', ' 2\npi ') else: assert app.user_ns['a'][0]['text/plain'] in ('\N{GREEK SMALL LETTER PI}', 'pi') assert app.user_ns['a2'][0]['text/plain'] in (' 2\n\N{GREEK SMALL LETTER PI} ', ' 2\npi ') def test_print_builtin_option(): # Initialize and setup IPython session app = init_ipython_session() app.run_cell("ip = get_ipython()") app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy import Symbol") app.run_cell("from sympy import init_printing") app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})") # Deal with API change starting at IPython 1.0 if int(ipython.__version__.split(".")[0]) < 1: text = app.user_ns['a']['text/plain'] raises(KeyError, lambda: app.user_ns['a']['text/latex']) else: text = app.user_ns['a'][0]['text/plain'] raises(KeyError, lambda: app.user_ns['a'][0]['text/latex']) # Note : Unicode of Python2 is equivalent to str in Python3. In Python 3 we have one # text type: str which holds Unicode data and two byte types bytes and bytearray. # XXX: How can we make this ignore the terminal width? This test fails if # the terminal is too narrow. assert text in ("{pi: 3.14, n_i: 3}", '{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}', "{n_i: 3, pi: 3.14}", '{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}') # If we enable the default printing, then the dictionary's should render # as a LaTeX version of the whole dict: ${\pi: 3.14, n_i: 3}$ app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True") app.run_cell("init_printing(use_latex=True)") app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})") # Deal with API change starting at IPython 1.0 if int(ipython.__version__.split(".")[0]) < 1: text = app.user_ns['a']['text/plain'] latex = app.user_ns['a']['text/latex'] else: text = app.user_ns['a'][0]['text/plain'] latex = app.user_ns['a'][0]['text/latex'] assert text in ("{pi: 3.14, n_i: 3}", '{n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3, \N{GREEK SMALL LETTER PI}: 3.14}', "{n_i: 3, pi: 3.14}", '{\N{GREEK SMALL LETTER PI}: 3.14, n\N{LATIN SUBSCRIPT SMALL LETTER I}: 3}') assert latex == r'$\displaystyle \left\{ n_{i} : 3, \ \pi : 3.14\right\}$' # Objects with an _latex overload should also be handled by our tuple # printer. app.run_cell("""\ class WithOverload: def _latex(self, printer): return r"\\LaTeX" """) app.run_cell("a = format((WithOverload(),))") # Deal with API change starting at IPython 1.0 if int(ipython.__version__.split(".")[0]) < 1: latex = app.user_ns['a']['text/latex'] else: latex = app.user_ns['a'][0]['text/latex'] assert latex == r'$\displaystyle \left( \LaTeX,\right)$' app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True") app.run_cell("init_printing(use_latex=True, print_builtin=False)") app.run_cell("a = format({Symbol('pi'): 3.14, Symbol('n_i'): 3})") # Deal with API change starting at IPython 1.0 if int(ipython.__version__.split(".")[0]) < 1: text = app.user_ns['a']['text/plain'] raises(KeyError, lambda: app.user_ns['a']['text/latex']) else: text = app.user_ns['a'][0]['text/plain'] raises(KeyError, lambda: app.user_ns['a'][0]['text/latex']) # Note : In Python 3 we have one text type: str which holds Unicode data # and two byte types bytes and bytearray. # Python 3.3.3 + IPython 0.13.2 gives: '{n_i: 3, pi: 3.14}' # Python 3.3.3 + IPython 1.1.0 gives: '{n_i: 3, pi: 3.14}' assert text in ("{pi: 3.14, n_i: 3}", "{n_i: 3, pi: 3.14}") def test_builtin_containers(): # Initialize and setup IPython session app = init_ipython_session() app.run_cell("ip = get_ipython()") app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True") app.run_cell("from sympy import init_printing, Matrix") app.run_cell('init_printing(use_latex=True, use_unicode=False)') # Make sure containers that shouldn't pretty print don't. app.run_cell('a = format((True, False))') app.run_cell('import sys') app.run_cell('b = format(sys.flags)') app.run_cell('c = format((Matrix([1, 2]),))') # Deal with API change starting at IPython 1.0 if int(ipython.__version__.split(".")[0]) < 1: assert app.user_ns['a']['text/plain'] == '(True, False)' assert 'text/latex' not in app.user_ns['a'] assert app.user_ns['b']['text/plain'][:10] == 'sys.flags(' assert 'text/latex' not in app.user_ns['b'] assert app.user_ns['c']['text/plain'] == \ """\ [1] \n\ ([ ],) [2] \ """ assert app.user_ns['c']['text/latex'] == '$\\displaystyle \\left( \\left[\\begin{matrix}1\\\\2\\end{matrix}\\right],\\right)$' else: assert app.user_ns['a'][0]['text/plain'] == '(True, False)' assert 'text/latex' not in app.user_ns['a'][0] assert app.user_ns['b'][0]['text/plain'][:10] == 'sys.flags(' assert 'text/latex' not in app.user_ns['b'][0] assert app.user_ns['c'][0]['text/plain'] == \ """\ [1] \n\ ([ ],) [2] \ """ assert app.user_ns['c'][0]['text/latex'] == '$\\displaystyle \\left( \\left[\\begin{matrix}1\\\\2\\end{matrix}\\right],\\right)$' def test_matplotlib_bad_latex(): # Initialize and setup IPython session app = init_ipython_session() app.run_cell("import IPython") app.run_cell("ip = get_ipython()") app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("from sympy import init_printing, Matrix") app.run_cell("init_printing(use_latex='matplotlib')") # The png formatter is not enabled by default in this context app.run_cell("inst.display_formatter.formatters['image/png'].enabled = True") # Make sure no warnings are raised by IPython app.run_cell("import warnings") # IPython.core.formatters.FormatterWarning was introduced in IPython 2.0 if int(ipython.__version__.split(".")[0]) < 2: app.run_cell("warnings.simplefilter('error')") else: app.run_cell("warnings.simplefilter('error', IPython.core.formatters.FormatterWarning)") # This should not raise an exception app.run_cell("a = format(Matrix([1, 2, 3]))") # issue 9799 app.run_cell("from sympy import Piecewise, Symbol, Eq") app.run_cell("x = Symbol('x'); pw = format(Piecewise((1, Eq(x, 0)), (0, True)))") def test_override_repr_latex(): # Initialize and setup IPython session app = init_ipython_session() app.run_cell("import IPython") app.run_cell("ip = get_ipython()") app.run_cell("inst = ip.instance()") app.run_cell("format = inst.display_formatter.format") app.run_cell("inst.display_formatter.formatters['text/latex'].enabled = True") app.run_cell("from sympy import init_printing") app.run_cell("from sympy import Symbol") app.run_cell("init_printing(use_latex=True)") app.run_cell("""\ class SymbolWithOverload(Symbol): def _repr_latex_(self): return r"Hello " + super()._repr_latex_() + " world" """) app.run_cell("a = format(SymbolWithOverload('s'))") if int(ipython.__version__.split(".")[0]) < 1: latex = app.user_ns['a']['text/latex'] else: latex = app.user_ns['a'][0]['text/latex'] assert latex == r'Hello $\displaystyle s$ world'
f11b4df594206b6a31b1c54f3e4306076f43cfc51bb24312daccd8b6a67af6ed
"""Benchmarks for polynomials over Galois fields. """ from sympy.polys.galoistools import gf_from_dict, gf_factor_sqf from sympy.polys.domains import ZZ from sympy.core.numbers import pi from sympy.ntheory.generate import nextprime def gathen_poly(n, p, K): return gf_from_dict({n: K.one, 1: K.one, 0: K.one}, p, K) def shoup_poly(n, p, K): f = [K.one] * (n + 1) for i in range(1, n + 1): f[i] = (f[i - 1]**2 + K.one) % p return f def genprime(n, K): return K(nextprime(int((2**n * pi).evalf()))) p_10 = genprime(10, ZZ) f_10 = gathen_poly(10, p_10, ZZ) p_20 = genprime(20, ZZ) f_20 = gathen_poly(20, p_20, ZZ) def timeit_gathen_poly_f10_zassenhaus(): gf_factor_sqf(f_10, p_10, ZZ, method='zassenhaus') def timeit_gathen_poly_f10_shoup(): gf_factor_sqf(f_10, p_10, ZZ, method='shoup') def timeit_gathen_poly_f20_zassenhaus(): gf_factor_sqf(f_20, p_20, ZZ, method='zassenhaus') def timeit_gathen_poly_f20_shoup(): gf_factor_sqf(f_20, p_20, ZZ, method='shoup') P_08 = genprime(8, ZZ) F_10 = shoup_poly(10, P_08, ZZ) P_18 = genprime(18, ZZ) F_20 = shoup_poly(20, P_18, ZZ) def timeit_shoup_poly_F10_zassenhaus(): gf_factor_sqf(F_10, P_08, ZZ, method='zassenhaus') def timeit_shoup_poly_F10_shoup(): gf_factor_sqf(F_10, P_08, ZZ, method='shoup') def timeit_shoup_poly_F20_zassenhaus(): gf_factor_sqf(F_20, P_18, ZZ, method='zassenhaus') def timeit_shoup_poly_F20_shoup(): gf_factor_sqf(F_20, P_18, ZZ, method='shoup')
76c0311a6286000dd3b62e7700f23610ec79c8b2a6ac6d57b1384d01c7d64a52
"""Implementation of :class:`AlgebraicField` class. """ from sympy.core.add import Add from sympy.core.mul import Mul from sympy.core.singleton import S from sympy.polys.domains.characteristiczero import CharacteristicZero from sympy.polys.domains.field import Field from sympy.polys.domains.simpledomain import SimpleDomain from sympy.polys.polyclasses import ANP from sympy.polys.polyerrors import CoercionFailed, DomainError, NotAlgebraic, IsomorphismFailed from sympy.utilities import public @public class AlgebraicField(Field, CharacteristicZero, SimpleDomain): r"""Algebraic number field :ref:`QQ(a)` A :ref:`QQ(a)` domain represents an `algebraic number field`_ `\mathbb{Q}(a)` as a :py:class:`~.Domain` in the domain system (see :ref:`polys-domainsintro`). A :py:class:`~.Poly` created from an expression involving `algebraic numbers`_ will treat the algebraic numbers as generators if the generators argument is not specified. >>> from sympy import Poly, Symbol, sqrt >>> x = Symbol('x') >>> Poly(x**2 + sqrt(2)) Poly(x**2 + (sqrt(2)), x, sqrt(2), domain='ZZ') That is a multivariate polynomial with ``sqrt(2)`` treated as one of the generators (variables). If the generators are explicitly specified then ``sqrt(2)`` will be considered to be a coefficient but by default the :ref:`EX` domain is used. To make a :py:class:`~.Poly` with a :ref:`QQ(a)` domain the argument ``extension=True`` can be given. >>> Poly(x**2 + sqrt(2), x) Poly(x**2 + sqrt(2), x, domain='EX') >>> Poly(x**2 + sqrt(2), x, extension=True) Poly(x**2 + sqrt(2), x, domain='QQ<sqrt(2)>') A generator of the algebraic field extension can also be specified explicitly which is particularly useful if the coefficients are all rational but an extension field is needed (e.g. to factor the polynomial). >>> Poly(x**2 + 1) Poly(x**2 + 1, x, domain='ZZ') >>> Poly(x**2 + 1, extension=sqrt(2)) Poly(x**2 + 1, x, domain='QQ<sqrt(2)>') It is possible to factorise a polynomial over a :ref:`QQ(a)` domain using the ``extension`` argument to :py:func:`~.factor` or by specifying the domain explicitly. >>> from sympy import factor, QQ >>> factor(x**2 - 2) x**2 - 2 >>> factor(x**2 - 2, extension=sqrt(2)) (x - sqrt(2))*(x + sqrt(2)) >>> factor(x**2 - 2, domain='QQ<sqrt(2)>') (x - sqrt(2))*(x + sqrt(2)) >>> factor(x**2 - 2, domain=QQ.algebraic_field(sqrt(2))) (x - sqrt(2))*(x + sqrt(2)) The ``extension=True`` argument can be used but will only create an extension that contains the coefficients which is usually not enough to factorise the polynomial. >>> p = x**3 + sqrt(2)*x**2 - 2*x - 2*sqrt(2) >>> factor(p) # treats sqrt(2) as a symbol (x + sqrt(2))*(x**2 - 2) >>> factor(p, extension=True) (x - sqrt(2))*(x + sqrt(2))**2 >>> factor(x**2 - 2, extension=True) # all rational coefficients x**2 - 2 It is also possible to use :ref:`QQ(a)` with the :py:func:`~.cancel` and :py:func:`~.gcd` functions. >>> from sympy import cancel, gcd >>> cancel((x**2 - 2)/(x - sqrt(2))) (x**2 - 2)/(x - sqrt(2)) >>> cancel((x**2 - 2)/(x - sqrt(2)), extension=sqrt(2)) x + sqrt(2) >>> gcd(x**2 - 2, x - sqrt(2)) 1 >>> gcd(x**2 - 2, x - sqrt(2), extension=sqrt(2)) x - sqrt(2) When using the domain directly :ref:`QQ(a)` can be used as a constructor to create instances which then support the operations ``+,-,*,**,/``. The :py:meth:`~.Domain.algebraic_field` method is used to construct a particular :ref:`QQ(a)` domain. The :py:meth:`~.Domain.from_sympy` method can be used to create domain elements from normal SymPy expressions. >>> K = QQ.algebraic_field(sqrt(2)) >>> K QQ<sqrt(2)> >>> xk = K.from_sympy(3 + 4*sqrt(2)) >>> xk # doctest: +SKIP ANP([4, 3], [1, 0, -2], QQ) Elements of :ref:`QQ(a)` are instances of :py:class:`~.ANP` which have limited printing support. The raw display shows the internal representation of the element as the list ``[4, 3]`` representing the coefficients of ``1`` and ``sqrt(2)`` for this element in the form ``a * sqrt(2) + b * 1`` where ``a`` and ``b`` are elements of :ref:`QQ`. The minimal polynomial for the generator ``(x**2 - 2)`` is also shown in the :ref:`dup-representation` as the list ``[1, 0, -2]``. We can use :py:meth:`~.Domain.to_sympy` to get a better printed form for the elements and to see the results of operations. >>> xk = K.from_sympy(3 + 4*sqrt(2)) >>> yk = K.from_sympy(2 + 3*sqrt(2)) >>> xk * yk # doctest: +SKIP ANP([17, 30], [1, 0, -2], QQ) >>> K.to_sympy(xk * yk) 17*sqrt(2) + 30 >>> K.to_sympy(xk + yk) 5 + 7*sqrt(2) >>> K.to_sympy(xk ** 2) 24*sqrt(2) + 41 >>> K.to_sympy(xk / yk) sqrt(2)/14 + 9/7 Any expression representing an algebraic number can be used to generate a :ref:`QQ(a)` domain provided its `minimal polynomial`_ can be computed. The function :py:func:`~.minpoly` function is used for this. >>> from sympy import exp, I, pi, minpoly >>> g = exp(2*I*pi/3) >>> g exp(2*I*pi/3) >>> g.is_algebraic True >>> minpoly(g, x) x**2 + x + 1 >>> factor(x**3 - 1, extension=g) (x - 1)*(x - exp(2*I*pi/3))*(x + 1 + exp(2*I*pi/3)) It is also possible to make an algebraic field from multiple extension elements. >>> K = QQ.algebraic_field(sqrt(2), sqrt(3)) >>> K QQ<sqrt(2) + sqrt(3)> >>> p = x**4 - 5*x**2 + 6 >>> factor(p) (x**2 - 3)*(x**2 - 2) >>> factor(p, domain=K) (x - sqrt(2))*(x + sqrt(2))*(x - sqrt(3))*(x + sqrt(3)) >>> factor(p, extension=[sqrt(2), sqrt(3)]) (x - sqrt(2))*(x + sqrt(2))*(x - sqrt(3))*(x + sqrt(3)) Multiple extension elements are always combined together to make a single `primitive element`_. In the case of ``[sqrt(2), sqrt(3)]`` the primitive element chosen is ``sqrt(2) + sqrt(3)`` which is why the domain displays as ``QQ<sqrt(2) + sqrt(3)>``. The minimal polynomial for the primitive element is computed using the :py:func:`~.primitive_element` function. >>> from sympy import primitive_element >>> primitive_element([sqrt(2), sqrt(3)], x) (x**4 - 10*x**2 + 1, [1, 1]) >>> minpoly(sqrt(2) + sqrt(3), x) x**4 - 10*x**2 + 1 The extension elements that generate the domain can be accessed from the domain using the :py:attr:`~.ext` and :py:attr:`~.orig_ext` attributes as instances of :py:class:`~.AlgebraicNumber`. The minimal polynomial for the primitive element as a :py:class:`~.DMP` instance is available as :py:attr:`~.mod`. >>> K = QQ.algebraic_field(sqrt(2), sqrt(3)) >>> K QQ<sqrt(2) + sqrt(3)> >>> K.ext sqrt(2) + sqrt(3) >>> K.orig_ext (sqrt(2), sqrt(3)) >>> K.mod DMP([1, 0, -10, 0, 1], QQ, None) Notes ===== It is not currently possible to generate an algebraic extension over any domain other than :ref:`QQ`. Ideally it would be possible to generate extensions like ``QQ(x)(sqrt(x**2 - 2))``. This is equivalent to the quotient ring ``QQ(x)[y]/(y**2 - x**2 + 2)`` and there are two implementations of this kind of quotient ring/extension in the :py:class:`~.QuotientRing` and :py:class:`~.MonogenicFiniteExtension` classes. Each of those implementations needs some work to make them fully usable though. .. _algebraic number field: https://en.wikipedia.org/wiki/Algebraic_number_field .. _algebraic numbers: https://en.wikipedia.org/wiki/Algebraic_number .. _minimal polynomial: https://en.wikipedia.org/wiki/Minimal_polynomial_(field_theory) .. _primitive element: https://en.wikipedia.org/wiki/Primitive_element_theorem """ dtype = ANP is_AlgebraicField = is_Algebraic = True is_Numerical = True has_assoc_Ring = False has_assoc_Field = True def __init__(self, dom, *ext): if not dom.is_QQ: raise DomainError("ground domain must be a rational field") from sympy.polys.numberfields import to_number_field if len(ext) == 1 and isinstance(ext[0], tuple): orig_ext = ext[0][1:] else: orig_ext = ext self.orig_ext = orig_ext """ Original elements given to generate the extension. >>> from sympy import QQ, sqrt >>> K = QQ.algebraic_field(sqrt(2), sqrt(3)) >>> K.orig_ext (sqrt(2), sqrt(3)) """ self.ext = to_number_field(ext) """ Primitive element used for the extension. >>> from sympy import QQ, sqrt >>> K = QQ.algebraic_field(sqrt(2), sqrt(3)) >>> K.ext sqrt(2) + sqrt(3) """ self.mod = self.ext.minpoly.rep """ Minimal polynomial for the primitive element of the extension. >>> from sympy import QQ, sqrt >>> K = QQ.algebraic_field(sqrt(2)) >>> K.mod DMP([1, 0, -2], QQ, None) """ self.domain = self.dom = dom self.ngens = 1 self.symbols = self.gens = (self.ext,) self.unit = self([dom(1), dom(0)]) self.zero = self.dtype.zero(self.mod.rep, dom) self.one = self.dtype.one(self.mod.rep, dom) def new(self, element): return self.dtype(element, self.mod.rep, self.dom) def __str__(self): return str(self.dom) + '<' + str(self.ext) + '>' def __hash__(self): return hash((self.__class__.__name__, self.dtype, self.dom, self.ext)) def __eq__(self, other): """Returns ``True`` if two domains are equivalent. """ return isinstance(other, AlgebraicField) and \ self.dtype == other.dtype and self.ext == other.ext def algebraic_field(self, *extension): r"""Returns an algebraic field, i.e. `\mathbb{Q}(\alpha, \ldots)`. """ return AlgebraicField(self.dom, *((self.ext,) + extension)) def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ # Precompute a converter to be reused: if not hasattr(self, '_converter'): self._converter = _make_converter(self) return self._converter(a) def from_sympy(self, a): """Convert SymPy's expression to ``dtype``. """ try: return self([self.dom.from_sympy(a)]) except CoercionFailed: pass from sympy.polys.numberfields import to_number_field try: return self(to_number_field(a, self.ext).native_coeffs()) except (NotAlgebraic, IsomorphismFailed): raise CoercionFailed( "%s is not a valid algebraic number in %s" % (a, self)) def from_ZZ(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_ZZ_python(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_QQ(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_QQ_python(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY ``mpz`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_QQ_gmpy(K1, a, K0): """Convert a GMPY ``mpq`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_RealField(K1, a, K0): """Convert a mpmath ``mpf`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def get_ring(self): """Returns a ring associated with ``self``. """ raise DomainError('there is no ring associated with %s' % self) def is_positive(self, a): """Returns True if ``a`` is positive. """ return self.dom.is_positive(a.LC()) def is_negative(self, a): """Returns True if ``a`` is negative. """ return self.dom.is_negative(a.LC()) def is_nonpositive(self, a): """Returns True if ``a`` is non-positive. """ return self.dom.is_nonpositive(a.LC()) def is_nonnegative(self, a): """Returns True if ``a`` is non-negative. """ return self.dom.is_nonnegative(a.LC()) def numer(self, a): """Returns numerator of ``a``. """ return a def denom(self, a): """Returns denominator of ``a``. """ return self.one def from_AlgebraicField(K1, a, K0): """Convert AlgebraicField element 'a' to another AlgebraicField """ return K1.from_sympy(K0.to_sympy(a)) def from_GaussianIntegerRing(K1, a, K0): """Convert a GaussianInteger element 'a' to ``dtype``. """ return K1.from_sympy(K0.to_sympy(a)) def from_GaussianRationalField(K1, a, K0): """Convert a GaussianRational element 'a' to ``dtype``. """ return K1.from_sympy(K0.to_sympy(a)) def _make_converter(K): """Construct the converter to convert back to Expr""" # Precompute the effect of converting to SymPy and expanding expressions # like (sqrt(2) + sqrt(3))**2. Asking Expr to do the expansion on every # conversion from K to Expr is slow. Here we compute the expansions for # each power of the generator and collect together the resulting algebraic # terms and the rational coefficients into a matrix. gen = K.ext.as_expr() todom = K.dom.from_sympy # We'll let Expr compute the expansions. We won't make any presumptions # about what this results in except that it is QQ-linear in some terms # that we will call algebraics. The final result will be expressed in # terms of those. powers = [S.One, gen] for n in range(2, K.mod.degree()): powers.append((gen * powers[-1]).expand()) # Collect the rational coefficients and algebraic Expr that can # map the ANP coefficients into an expanded SymPy expression terms = [dict(t.as_coeff_Mul()[::-1] for t in Add.make_args(p)) for p in powers] algebraics = set().union(*terms) matrix = [[todom(t.get(a, S.Zero)) for t in terms] for a in algebraics] # Create a function to do the conversion efficiently: def converter(a): """Convert a to Expr using converter""" ai = a.rep[::-1] tosympy = K.dom.to_sympy coeffs_dom = [sum(mij*aj for mij, aj in zip(mi, ai)) for mi in matrix] coeffs_sympy = [tosympy(c) for c in coeffs_dom] res = Add(*(Mul(c, a) for c, a in zip(coeffs_sympy, algebraics))) return res return converter
4faa8f364535109e83e419efc8949726fe33789e4c513e512eca2f3249174bd1
"""Implementation of mathematical domains. """ __all__ = [ 'Domain', 'FiniteField', 'IntegerRing', 'RationalField', 'RealField', 'ComplexField', 'AlgebraicField', 'PolynomialRing', 'FractionField', 'ExpressionDomain', 'PythonRational', 'GF', 'FF', 'ZZ', 'QQ', 'ZZ_I', 'QQ_I', 'RR', 'CC', 'EX', 'EXRAW', ] from .domain import Domain from .finitefield import FiniteField, FF, GF from .integerring import IntegerRing, ZZ from .rationalfield import RationalField, QQ from .algebraicfield import AlgebraicField from .gaussiandomains import ZZ_I, QQ_I from .realfield import RealField, RR from .complexfield import ComplexField, CC from .polynomialring import PolynomialRing from .fractionfield import FractionField from .expressiondomain import ExpressionDomain, EX from .expressionrawdomain import EXRAW from .pythonrational import PythonRational # This is imported purely for backwards compatibility because some parts of # the codebase used to import this from here and it's possible that downstream # does as well: from sympy.external.gmpy import GROUND_TYPES # noqa: F401 # # The rest of these are obsolete and provided only for backwards # compatibility: # from .pythonfinitefield import PythonFiniteField from .gmpyfinitefield import GMPYFiniteField from .pythonintegerring import PythonIntegerRing from .gmpyintegerring import GMPYIntegerRing from .pythonrationalfield import PythonRationalField from .gmpyrationalfield import GMPYRationalField FF_python = PythonFiniteField FF_gmpy = GMPYFiniteField ZZ_python = PythonIntegerRing ZZ_gmpy = GMPYIntegerRing QQ_python = PythonRationalField QQ_gmpy = GMPYRationalField __all__.extend(( 'PythonFiniteField', 'GMPYFiniteField', 'PythonIntegerRing', 'GMPYIntegerRing', 'PythonRational', 'GMPYRationalField', 'FF_python', 'FF_gmpy', 'ZZ_python', 'ZZ_gmpy', 'QQ_python', 'QQ_gmpy', ))
c8553cf85be80f1190f58a3e98a94eaa707ef7572da73fd34f4ccb466c7e8902
"""Implementation of :class:`FiniteField` class. """ from sympy.polys.domains.field import Field from sympy.polys.domains.modularinteger import ModularIntegerFactory from sympy.polys.domains.simpledomain import SimpleDomain from sympy.polys.polyerrors import CoercionFailed from sympy.utilities import public from sympy.polys.domains.groundtypes import SymPyInteger @public class FiniteField(Field, SimpleDomain): r"""Finite field of prime order :ref:`GF(p)` A :ref:`GF(p)` domain represents a `finite field`_ `\mathbb{F}_p` of prime order as :py:class:`~.Domain` in the domain system (see :ref:`polys-domainsintro`). A :py:class:`~.Poly` created from an expression with integer coefficients will have the domain :ref:`ZZ`. However, if the ``modulus=p`` option is given then the domain will be a finite field instead. >>> from sympy import Poly, Symbol >>> x = Symbol('x') >>> p = Poly(x**2 + 1) >>> p Poly(x**2 + 1, x, domain='ZZ') >>> p.domain ZZ >>> p2 = Poly(x**2 + 1, modulus=2) >>> p2 Poly(x**2 + 1, x, modulus=2) >>> p2.domain GF(2) It is possible to factorise a polynomial over :ref:`GF(p)` using the modulus argument to :py:func:`~.factor` or by specifying the domain explicitly. The domain can also be given as a string. >>> from sympy import factor, GF >>> factor(x**2 + 1) x**2 + 1 >>> factor(x**2 + 1, modulus=2) (x + 1)**2 >>> factor(x**2 + 1, domain=GF(2)) (x + 1)**2 >>> factor(x**2 + 1, domain='GF(2)') (x + 1)**2 It is also possible to use :ref:`GF(p)` with the :py:func:`~.cancel` and :py:func:`~.gcd` functions. >>> from sympy import cancel, gcd >>> cancel((x**2 + 1)/(x + 1)) (x**2 + 1)/(x + 1) >>> cancel((x**2 + 1)/(x + 1), domain=GF(2)) x + 1 >>> gcd(x**2 + 1, x + 1) 1 >>> gcd(x**2 + 1, x + 1, domain=GF(2)) x + 1 When using the domain directly :ref:`GF(p)` can be used as a constructor to create instances which then support the operations ``+,-,*,**,/`` >>> from sympy import GF >>> K = GF(5) >>> K GF(5) >>> x = K(3) >>> y = K(2) >>> x 3 mod 5 >>> y 2 mod 5 >>> x * y 1 mod 5 >>> x / y 4 mod 5 Notes ===== It is also possible to create a :ref:`GF(p)` domain of **non-prime** order but the resulting ring is **not** a field: it is just the ring of the integers modulo ``n``. >>> K = GF(9) >>> z = K(3) >>> z 3 mod 9 >>> z**2 0 mod 9 It would be good to have a proper implementation of prime power fields (``GF(p**n)``) but these are not yet implemented in SymPY. .. _finite field: https://en.wikipedia.org/wiki/Finite_field """ rep = 'FF' alias = 'FF' is_FiniteField = is_FF = True is_Numerical = True has_assoc_Ring = False has_assoc_Field = True dom = None mod = None def __init__(self, mod, symmetric=True): from sympy.polys.domains import ZZ dom = ZZ if mod <= 0: raise ValueError('modulus must be a positive integer, got %s' % mod) self.dtype = ModularIntegerFactory(mod, dom, symmetric, self) self.zero = self.dtype(0) self.one = self.dtype(1) self.dom = dom self.mod = mod def __str__(self): return 'GF(%s)' % self.mod def __hash__(self): return hash((self.__class__.__name__, self.dtype, self.mod, self.dom)) def __eq__(self, other): """Returns ``True`` if two domains are equivalent. """ return isinstance(other, FiniteField) and \ self.mod == other.mod and self.dom == other.dom def characteristic(self): """Return the characteristic of this domain. """ return self.mod def get_field(self): """Returns a field associated with ``self``. """ return self def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ return SymPyInteger(int(a)) def from_sympy(self, a): """Convert SymPy's Integer to SymPy's ``Integer``. """ if a.is_Integer: return self.dtype(self.dom.dtype(int(a))) elif a.is_Float and int(a) == a: return self.dtype(self.dom.dtype(int(a))) else: raise CoercionFailed("expected an integer, got %s" % a) def from_FF(K1, a, K0=None): """Convert ``ModularInteger(int)`` to ``dtype``. """ return K1.dtype(K1.dom.from_ZZ(a.val, K0.dom)) def from_FF_python(K1, a, K0=None): """Convert ``ModularInteger(int)`` to ``dtype``. """ return K1.dtype(K1.dom.from_ZZ_python(a.val, K0.dom)) def from_ZZ(K1, a, K0=None): """Convert Python's ``int`` to ``dtype``. """ return K1.dtype(K1.dom.from_ZZ_python(a, K0)) def from_ZZ_python(K1, a, K0=None): """Convert Python's ``int`` to ``dtype``. """ return K1.dtype(K1.dom.from_ZZ_python(a, K0)) def from_QQ(K1, a, K0=None): """Convert Python's ``Fraction`` to ``dtype``. """ if a.denominator == 1: return K1.from_ZZ_python(a.numerator) def from_QQ_python(K1, a, K0=None): """Convert Python's ``Fraction`` to ``dtype``. """ if a.denominator == 1: return K1.from_ZZ_python(a.numerator) def from_FF_gmpy(K1, a, K0=None): """Convert ``ModularInteger(mpz)`` to ``dtype``. """ return K1.dtype(K1.dom.from_ZZ_gmpy(a.val, K0.dom)) def from_ZZ_gmpy(K1, a, K0=None): """Convert GMPY's ``mpz`` to ``dtype``. """ return K1.dtype(K1.dom.from_ZZ_gmpy(a, K0)) def from_QQ_gmpy(K1, a, K0=None): """Convert GMPY's ``mpq`` to ``dtype``. """ if a.denominator == 1: return K1.from_ZZ_gmpy(a.numerator) def from_RealField(K1, a, K0): """Convert mpmath's ``mpf`` to ``dtype``. """ p, q = K0.to_rational(a) if q == 1: return K1.dtype(K1.dom.dtype(p)) FF = GF = FiniteField
2c1508229377cb740f4baa45616c2aa5c6b94a1a160f26996d9e8fc039bf4a60
"""Implementation of :class:`QuotientRing` class.""" 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: """ 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.printing.str import sstr return sstr(self.data) + " + " + str(self.ring.base_ideal) __repr__ = __str__ def __bool__(self): return not self.ring.is_zero(self) 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): if oth < 0: return self.ring.revert(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(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K1.ring.convert(a, K0)) from_ZZ_python = from_ZZ 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)
fd17a782d7f9bcddf0f46240b0315c377c8a6d68d8aa44dbb0f7716ed6e99671
"""Implementation of :class:`PolynomialRing` class. """ from sympy.polys.agca.modules import FreeModulePolyRing from sympy.polys.domains.characteristiczero import CharacteristicZero from sympy.polys.domains.compositedomain import CompositeDomain from sympy.polys.domains.old_fractionfield import FractionField from sympy.polys.domains.ring import Ring from sympy.polys.orderings import monomial_key, build_product_order from sympy.polys.polyclasses import DMP, DMF from sympy.polys.polyerrors import (GeneratorsNeeded, PolynomialError, CoercionFailed, ExactQuotientFailed, NotReversible) from sympy.polys.polyutils import dict_from_basic, basic_from_dict, _dict_reorder from sympy.utilities import public from sympy.utilities.iterables import iterable # XXX why does this derive from CharacteristicZero??? @public class PolynomialRingBase(Ring, CharacteristicZero, CompositeDomain): """ Base class for generalized polynomial rings. This base class should be used for uniform access to generalized polynomial rings. Subclasses only supply information about the element storage etc. Do not instantiate. """ has_assoc_Ring = True has_assoc_Field = True default_order = "grevlex" def __init__(self, dom, *gens, **opts): if not gens: raise GeneratorsNeeded("generators not specified") lev = len(gens) - 1 self.ngens = len(gens) self.zero = self.dtype.zero(lev, dom, ring=self) self.one = self.dtype.one(lev, dom, ring=self) self.domain = self.dom = dom self.symbols = self.gens = gens # NOTE 'order' may not be set if inject was called through CompositeDomain self.order = opts.get('order', monomial_key(self.default_order)) def new(self, element): return self.dtype(element, self.dom, len(self.gens) - 1, ring=self) def __str__(self): s_order = str(self.order) orderstr = ( " order=" + s_order) if s_order != self.default_order else "" return str(self.dom) + '[' + ','.join(map(str, self.gens)) + orderstr + ']' def __hash__(self): return hash((self.__class__.__name__, self.dtype, self.dom, self.gens, self.order)) def __eq__(self, other): """Returns ``True`` if two domains are equivalent. """ return isinstance(other, PolynomialRingBase) and \ self.dtype == other.dtype and self.dom == other.dom and \ self.gens == other.gens and self.order == other.order def from_ZZ(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_ZZ_python(K1, a, K0): """Convert a Python ``int`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_QQ(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_QQ_python(K1, a, K0): """Convert a Python ``Fraction`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_ZZ_gmpy(K1, a, K0): """Convert a GMPY ``mpz`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_QQ_gmpy(K1, a, K0): """Convert a GMPY ``mpq`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_RealField(K1, a, K0): """Convert a mpmath ``mpf`` object to ``dtype``. """ return K1(K1.dom.convert(a, K0)) def from_AlgebraicField(K1, a, K0): """Convert a ``ANP`` object to ``dtype``. """ if K1.dom == K0: return K1(a) def from_PolynomialRing(K1, a, K0): """Convert a ``PolyElement`` object to ``dtype``. """ if K1.gens == K0.symbols: if K1.dom == K0.dom: return K1(dict(a)) # set the correct ring else: convert_dom = lambda c: K1.dom.convert_from(c, K0.dom) return K1({m: convert_dom(c) for m, c in a.items()}) else: monoms, coeffs = _dict_reorder(a.to_dict(), K0.symbols, K1.gens) if K1.dom != K0.dom: coeffs = [ K1.dom.convert(c, K0.dom) for c in coeffs ] return K1(dict(zip(monoms, coeffs))) def from_GlobalPolynomialRing(K1, a, K0): """Convert a ``DMP`` object to ``dtype``. """ if K1.gens == K0.gens: if K1.dom == K0.dom: return K1(a.rep) # set the correct ring else: return K1(a.convert(K1.dom).rep) else: monoms, coeffs = _dict_reorder(a.to_dict(), K0.gens, K1.gens) if K1.dom != K0.dom: coeffs = [ K1.dom.convert(c, K0.dom) for c in coeffs ] return K1(dict(zip(monoms, coeffs))) def get_field(self): """Returns a field associated with ``self``. """ return FractionField(self.dom, *self.gens) 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): try: return 1/a except (ExactQuotientFailed, ZeroDivisionError): raise NotReversible('%s is not a unit' % a) def gcdex(self, a, b): """Extended GCD of ``a`` and ``b``. """ return a.gcdex(b) def gcd(self, a, b): """Returns GCD of ``a`` and ``b``. """ return a.gcd(b) def lcm(self, a, b): """Returns LCM of ``a`` and ``b``. """ return a.lcm(b) def factorial(self, a): """Returns factorial of ``a``. """ return self.dtype(self.dom.factorial(a)) def _vector_to_sdm(self, v, order): """ For internal use by the modules class. Convert an iterable of elements of this ring into a sparse distributed module element. """ raise NotImplementedError def _sdm_to_dics(self, s, n): """Helper for _sdm_to_vector.""" from sympy.polys.distributedmodules import sdm_to_dict dic = sdm_to_dict(s) res = [{} for _ in range(n)] for k, v in dic.items(): res[k[0]][k[1:]] = v return res def _sdm_to_vector(self, s, n): """ For internal use by the modules class. Convert a sparse distributed module into a list of length ``n``. Examples ======== >>> from sympy import QQ, ilex >>> from sympy.abc import x, y >>> R = QQ.old_poly_ring(x, y, order=ilex) >>> L = [((1, 1, 1), QQ(1)), ((0, 1, 0), QQ(1)), ((0, 0, 1), QQ(2))] >>> R._sdm_to_vector(L, 2) [x + 2*y, x*y] """ dics = self._sdm_to_dics(s, n) # NOTE this works for global and local rings! return [self(x) for x in dics] def free_module(self, rank): """ Generate a free module of rank ``rank`` over ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).free_module(2) QQ[x]**2 """ return FreeModulePolyRing(self, rank) def _vector_to_sdm_helper(v, order): """Helper method for common code in Global and Local poly rings.""" from sympy.polys.distributedmodules import sdm_from_dict d = {} for i, e in enumerate(v): for key, value in e.to_dict().items(): d[(i,) + key] = value return sdm_from_dict(d, order) @public class GlobalPolynomialRing(PolynomialRingBase): """A true polynomial ring, with objects DMP. """ is_PolynomialRing = is_Poly = True dtype = DMP def from_FractionField(K1, a, K0): """ Convert a ``DMF`` object to ``DMP``. Examples ======== >>> from sympy.polys.polyclasses import DMP, DMF >>> from sympy.polys.domains import ZZ >>> from sympy.abc import x >>> f = DMF(([ZZ(1), ZZ(1)], [ZZ(1)]), ZZ) >>> K = ZZ.old_frac_field(x) >>> F = ZZ.old_poly_ring(x).from_FractionField(f, K) >>> F == DMP([ZZ(1), ZZ(1)], ZZ) True >>> type(F) <class 'sympy.polys.polyclasses.DMP'> """ if a.denom().is_one: return K1.from_GlobalPolynomialRing(a.numer(), K0) def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ return basic_from_dict(a.to_sympy_dict(), *self.gens) def from_sympy(self, a): """Convert SymPy's expression to ``dtype``. """ try: rep, _ = dict_from_basic(a, gens=self.gens) except PolynomialError: raise CoercionFailed("Cannot convert %s to type %s" % (a, self)) for k, v in rep.items(): rep[k] = self.dom.from_sympy(v) return self(rep) def is_positive(self, a): """Returns True if ``LC(a)`` is positive. """ return self.dom.is_positive(a.LC()) def is_negative(self, a): """Returns True if ``LC(a)`` is negative. """ return self.dom.is_negative(a.LC()) def is_nonpositive(self, a): """Returns True if ``LC(a)`` is non-positive. """ return self.dom.is_nonpositive(a.LC()) def is_nonnegative(self, a): """Returns True if ``LC(a)`` is non-negative. """ return self.dom.is_nonnegative(a.LC()) def _vector_to_sdm(self, v, order): """ Examples ======== >>> from sympy import lex, QQ >>> from sympy.abc import x, y >>> R = QQ.old_poly_ring(x, y) >>> f = R.convert(x + 2*y) >>> g = R.convert(x * y) >>> R._vector_to_sdm([f, g], lex) [((1, 1, 1), 1), ((0, 1, 0), 1), ((0, 0, 1), 2)] """ return _vector_to_sdm_helper(v, order) class GeneralizedPolynomialRing(PolynomialRingBase): """A generalized polynomial ring, with objects DMF. """ dtype = DMF def new(self, a): """Construct an element of ``self`` domain from ``a``. """ res = self.dtype(a, self.dom, len(self.gens) - 1, ring=self) # make sure res is actually in our ring if res.denom().terms(order=self.order)[0][0] != (0,)*len(self.gens): from sympy.printing.str import sstr raise CoercionFailed("denominator %s not allowed in %s" % (sstr(res), self)) return res def __contains__(self, a): try: a = self.convert(a) except CoercionFailed: return False return a.denom().terms(order=self.order)[0][0] == (0,)*len(self.gens) def from_FractionField(K1, a, K0): dmf = K1.get_field().from_FractionField(a, K0) return K1((dmf.num, dmf.den)) def to_sympy(self, a): """Convert ``a`` to a SymPy object. """ return (basic_from_dict(a.numer().to_sympy_dict(), *self.gens) / basic_from_dict(a.denom().to_sympy_dict(), *self.gens)) def from_sympy(self, a): """Convert SymPy's expression to ``dtype``. """ p, q = a.as_numer_denom() num, _ = dict_from_basic(p, gens=self.gens) den, _ = dict_from_basic(q, gens=self.gens) for k, v in num.items(): num[k] = self.dom.from_sympy(v) for k, v in den.items(): den[k] = self.dom.from_sympy(v) return self((num, den)).cancel() def _vector_to_sdm(self, v, order): """ Turn an iterable into a sparse distributed module. Note that the vector is multiplied by a unit first to make all entries polynomials. Examples ======== >>> from sympy import ilex, QQ >>> from sympy.abc import x, y >>> R = QQ.old_poly_ring(x, y, order=ilex) >>> f = R.convert((x + 2*y) / (1 + x)) >>> g = R.convert(x * y) >>> R._vector_to_sdm([f, g], ilex) [((0, 0, 1), 2), ((0, 1, 0), 1), ((1, 1, 1), 1), ((1, 2, 1), 1)] """ # NOTE this is quite inefficient... u = self.one.numer() for x in v: u *= x.denom() return _vector_to_sdm_helper([x.numer()*u/x.denom() for x in v], order) @public def PolynomialRing(dom, *gens, **opts): r""" Create a generalized multivariate polynomial ring. A generalized polynomial ring is defined by a ground field `K`, a set of generators (typically `x_1, \ldots, x_n`) and a monomial order `<`. The monomial order can be global, local or mixed. In any case it induces a total ordering on the monomials, and there exists for every (non-zero) polynomial `f \in K[x_1, \ldots, x_n]` a well-defined "leading monomial" `LM(f) = LM(f, >)`. One can then define a multiplicative subset `S = S_> = \{f \in K[x_1, \ldots, x_n] | LM(f) = 1\}`. The generalized polynomial ring corresponding to the monomial order is `R = S^{-1}K[x_1, \ldots, x_n]`. If `>` is a so-called global order, that is `1` is the smallest monomial, then we just have `S = K` and `R = K[x_1, \ldots, x_n]`. Examples ======== A few examples may make this clearer. >>> from sympy.abc import x, y >>> from sympy import QQ Our first ring uses global lexicographic order. >>> R1 = QQ.old_poly_ring(x, y, order=(("lex", x, y),)) The second ring uses local lexicographic order. Note that when using a single (non-product) order, you can just specify the name and omit the variables: >>> R2 = QQ.old_poly_ring(x, y, order="ilex") The third and fourth rings use a mixed orders: >>> o1 = (("ilex", x), ("lex", y)) >>> o2 = (("lex", x), ("ilex", y)) >>> R3 = QQ.old_poly_ring(x, y, order=o1) >>> R4 = QQ.old_poly_ring(x, y, order=o2) We will investigate what elements of `K(x, y)` are contained in the various rings. >>> L = [x, 1/x, y/(1 + x), 1/(1 + y), 1/(1 + x*y)] >>> test = lambda R: [f in R for f in L] The first ring is just `K[x, y]`: >>> test(R1) [True, False, False, False, False] The second ring is R1 localised at the maximal ideal (x, y): >>> test(R2) [True, False, True, True, True] The third ring is R1 localised at the prime ideal (x): >>> test(R3) [True, False, True, False, True] Finally the fourth ring is R1 localised at `S = K[x, y] \setminus yK[y]`: >>> test(R4) [True, False, False, True, False] """ order = opts.get("order", GeneralizedPolynomialRing.default_order) if iterable(order): order = build_product_order(order, gens) order = monomial_key(order) opts['order'] = order if order.is_global: return GlobalPolynomialRing(dom, *gens, **opts) else: return GeneralizedPolynomialRing(dom, *gens, **opts)
25502f865194785db0cfc3971cd6191822e47dbf405e5cc3542b2cbca14a8513
"""Implementation of :class:`ModularInteger` class. """ from typing import Any, Dict as tDict, Tuple as tTuple, 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: tDict[tTuple[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
6c73c7766a4544159ef3a4cd312b04ea6e60aef1346d058b5a74464410713294
"""Ground types for various mathematical domains in SymPy. """ import builtins from sympy.external.gmpy import HAS_GMPY, factorial, sqrt PythonInteger = builtins.int PythonReal = builtins.float PythonComplex = builtins.complex from .pythonrational import PythonRational from sympy.core.numbers import ( igcdex as python_gcdex, igcd2 as python_gcd, ilcm as python_lcm, ) from sympy.core.numbers import (Float as SymPyReal, Integer as SymPyInteger, Rational as SymPyRational) if HAS_GMPY == 2: from gmpy2 import ( mpz as GMPYInteger, mpq as GMPYRational, numer as gmpy_numer, denom as gmpy_denom, gcdext as gmpy_gcdex, gcd as gmpy_gcd, lcm as gmpy_lcm, qdiv as gmpy_qdiv, ) gcdex = gmpy_gcdex gcd = gmpy_gcd lcm = gmpy_lcm else: class _GMPYInteger: def __init__(self, obj): pass class _GMPYRational: def __init__(self, obj): pass GMPYInteger = _GMPYInteger GMPYRational = _GMPYRational gmpy_numer = None gmpy_denom = None gmpy_gcdex = None gmpy_gcd = None gmpy_lcm = None gmpy_qdiv = None gcdex = python_gcdex gcd = python_gcd lcm = python_lcm __all__ = [ 'PythonInteger', 'PythonReal', 'PythonComplex', 'PythonRational', 'python_gcdex', 'python_gcd', 'python_lcm', 'SymPyReal', 'SymPyInteger', 'SymPyRational', 'GMPYInteger', 'GMPYRational', 'gmpy_numer', 'gmpy_denom', 'gmpy_gcdex', 'gmpy_gcd', 'gmpy_lcm', 'gmpy_qdiv', 'factorial', 'sqrt', 'GMPYInteger', 'GMPYRational', ]
25012a9f545f169197badbd61c8e7737f9436707d23f7d0ccdc3d0e83723edd8
"""Implementation of :class:`Domain` class. """ from typing import Any, Optional, Type from sympy.core import Basic, sympify from sympy.core.sorting import default_sort_key, ordered from sympy.external.gmpy import HAS_GMPY 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 public from sympy.utilities.decorator import deprecated from sympy.utilities.iterables import is_sequence @public class Domain: """Superclass for all domains in the polys domains system. See :ref:`polys-domainsintro` for an introductory explanation of the domains system. The :py:class:`~.Domain` class is an abstract base class for all of the concrete domain types. There are many different :py:class:`~.Domain` subclasses each of which has an associated ``dtype`` which is a class representing the elements of the domain. The coefficients of a :py:class:`~.Poly` are elements of a domain which must be a subclass of :py:class:`~.Domain`. Examples ======== The most common example domains are the integers :ref:`ZZ` and the rationals :ref:`QQ`. >>> from sympy import Poly, symbols, Domain >>> x, y = symbols('x, y') >>> p = Poly(x**2 + y) >>> p Poly(x**2 + y, x, y, domain='ZZ') >>> p.domain ZZ >>> isinstance(p.domain, Domain) True >>> Poly(x**2 + y/2) Poly(x**2 + 1/2*y, x, y, domain='QQ') The domains can be used directly in which case the domain object e.g. (:ref:`ZZ` or :ref:`QQ`) can be used as a constructor for elements of ``dtype``. >>> from sympy import ZZ, QQ >>> ZZ(2) 2 >>> ZZ.dtype # doctest: +SKIP <class 'int'> >>> type(ZZ(2)) # doctest: +SKIP <class 'int'> >>> QQ(1, 2) 1/2 >>> type(QQ(1, 2)) # doctest: +SKIP <class 'sympy.polys.domains.pythonrational.PythonRational'> The corresponding domain elements can be used with the arithmetic operations ``+,-,*,**`` and depending on the domain some combination of ``/,//,%`` might be usable. For example in :ref:`ZZ` both ``//`` (floor division) and ``%`` (modulo division) can be used but ``/`` (true division) cannot. Since :ref:`QQ` is a :py:class:`~.Field` its elements can be used with ``/`` but ``//`` and ``%`` should not be used. Some domains have a :py:meth:`~.Domain.gcd` method. >>> ZZ(2) + ZZ(3) 5 >>> ZZ(5) // ZZ(2) 2 >>> ZZ(5) % ZZ(2) 1 >>> QQ(1, 2) / QQ(2, 3) 3/4 >>> ZZ.gcd(ZZ(4), ZZ(2)) 2 >>> QQ.gcd(QQ(2,7), QQ(5,3)) 1/21 >>> ZZ.is_Field False >>> QQ.is_Field True There are also many other domains including: 1. :ref:`GF(p)` for finite fields of prime order. 2. :ref:`RR` for real (floating point) numbers. 3. :ref:`CC` for complex (floating point) numbers. 4. :ref:`QQ(a)` for algebraic number fields. 5. :ref:`K[x]` for polynomial rings. 6. :ref:`K(x)` for rational function fields. 7. :ref:`EX` for arbitrary expressions. Each domain is represented by a domain object and also an implementation class (``dtype``) for the elements of the domain. For example the :ref:`K[x]` domains are represented by a domain object which is an instance of :py:class:`~.PolynomialRing` and the elements are always instances of :py:class:`~.PolyElement`. The implementation class represents particular types of mathematical expressions in a way that is more efficient than a normal SymPy expression which is of type :py:class:`~.Expr`. The domain methods :py:meth:`~.Domain.from_sympy` and :py:meth:`~.Domain.to_sympy` are used to convert from :py:class:`~.Expr` to a domain element and vice versa. >>> from sympy import Symbol, ZZ, Expr >>> x = Symbol('x') >>> K = ZZ[x] # polynomial ring domain >>> K ZZ[x] >>> type(K) # class of the domain <class 'sympy.polys.domains.polynomialring.PolynomialRing'> >>> K.dtype # class of the elements <class 'sympy.polys.rings.PolyElement'> >>> p_expr = x**2 + 1 # Expr >>> p_expr x**2 + 1 >>> type(p_expr) <class 'sympy.core.add.Add'> >>> isinstance(p_expr, Expr) True >>> p_domain = K.from_sympy(p_expr) >>> p_domain # domain element x**2 + 1 >>> type(p_domain) <class 'sympy.polys.rings.PolyElement'> >>> K.to_sympy(p_domain) == p_expr True The :py:meth:`~.Domain.convert_from` method is used to convert domain elements from one domain to another. >>> from sympy import ZZ, QQ >>> ez = ZZ(2) >>> eq = QQ.convert_from(ez, ZZ) >>> type(ez) # doctest: +SKIP <class 'int'> >>> type(eq) # doctest: +SKIP <class 'sympy.polys.domains.pythonrational.PythonRational'> Elements from different domains should not be mixed in arithmetic or other operations: they should be converted to a common domain first. The domain method :py:meth:`~.Domain.unify` is used to find a domain that can represent all the elements of two given domains. >>> from sympy import ZZ, QQ, symbols >>> x, y = symbols('x, y') >>> ZZ.unify(QQ) QQ >>> ZZ[x].unify(QQ) QQ[x] >>> ZZ[x].unify(QQ[y]) QQ[x,y] If a domain is a :py:class:`~.Ring` then is might have an associated :py:class:`~.Field` and vice versa. The :py:meth:`~.Domain.get_field` and :py:meth:`~.Domain.get_ring` methods will find or create the associated domain. >>> from sympy import ZZ, QQ, Symbol >>> x = Symbol('x') >>> ZZ.has_assoc_Field True >>> ZZ.get_field() QQ >>> QQ.has_assoc_Ring True >>> QQ.get_ring() ZZ >>> K = QQ[x] >>> K QQ[x] >>> K.get_field() QQ(x) See also ======== DomainElement: abstract base class for domain elements construct_domain: construct a minimal domain for some expressions """ dtype = None # type: Optional[Type] """The type (class) of the elements of this :py:class:`~.Domain`: >>> from sympy import ZZ, QQ, Symbol >>> ZZ.dtype <class 'int'> >>> z = ZZ(2) >>> z 2 >>> type(z) <class 'int'> >>> type(z) == ZZ.dtype True Every domain has an associated **dtype** ("datatype") which is the class of the associated domain elements. See also ======== of_type """ zero = None # type: Optional[Any] """The zero element of the :py:class:`~.Domain`: >>> from sympy import QQ >>> QQ.zero 0 >>> QQ.of_type(QQ.zero) True See also ======== of_type one """ one = None # type: Optional[Any] """The one element of the :py:class:`~.Domain`: >>> from sympy import QQ >>> QQ.one 1 >>> QQ.of_type(QQ.one) True See also ======== of_type zero """ is_Ring = False """Boolean flag indicating if the domain is a :py:class:`~.Ring`. >>> from sympy import ZZ >>> ZZ.is_Ring True Basically every :py:class:`~.Domain` represents a ring so this flag is not that useful. See also ======== is_PID is_Field get_ring has_assoc_Ring """ is_Field = False """Boolean flag indicating if the domain is a :py:class:`~.Field`. >>> from sympy import ZZ, QQ >>> ZZ.is_Field False >>> QQ.is_Field True See also ======== is_PID is_Ring get_field has_assoc_Field """ has_assoc_Ring = False """Boolean flag indicating if the domain has an associated :py:class:`~.Ring`. >>> from sympy import QQ >>> QQ.has_assoc_Ring True >>> QQ.get_ring() ZZ See also ======== is_Field get_ring """ has_assoc_Field = False """Boolean flag indicating if the domain has an associated :py:class:`~.Field`. >>> from sympy import ZZ >>> ZZ.has_assoc_Field True >>> ZZ.get_field() QQ See also ======== is_Field get_field """ 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_SymbolicRawDomain = is_EXRAW = False is_FiniteExtension = False is_Exact = True is_Numerical = False is_Simple = False is_Composite = False is_PID = False """Boolean flag indicating if the domain is a `principal ideal domain`_. >>> from sympy import ZZ >>> ZZ.has_assoc_Field True >>> ZZ.get_field() QQ .. _principal ideal domain: https://en.wikipedia.org/wiki/Principal_ideal_domain See also ======== is_Field get_field """ 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): """Alias for :py:attr:`~.Domain.dtype`""" 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("Cannot 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 base is not None: if _not_a_coeff(element): raise CoercionFailed('%s is not in any domain' % element) return self.convert_from(element, base) if self.of_type(element): return element if _not_a_coeff(element): raise CoercionFailed('%s is not in any domain' % element) from sympy.polys.domains import ZZ, QQ, RealField, ComplexField if ZZ.of_type(element): return self.convert_from(element, ZZ) if isinstance(element, int): return self.convert_from(ZZ(element), ZZ) if HAS_GMPY: integers = ZZ if isinstance(element, integers.tp): return self.convert_from(element, integers) rationals = QQ 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("Cannot 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 domain element *a* to a SymPy expression (Expr). Explanation =========== Convert a :py:class:`~.Domain` element *a* to :py:class:`~.Expr`. Most public SymPy functions work with objects of type :py:class:`~.Expr`. The elements of a :py:class:`~.Domain` have a different internal representation. It is not possible to mix domain elements with :py:class:`~.Expr` so each domain has :py:meth:`~.Domain.to_sympy` and :py:meth:`~.Domain.from_sympy` methods to convert its domain elements to and from :py:class:`~.Expr`. Parameters ========== a: domain element An element of this :py:class:`~.Domain`. Returns ======= expr: Expr A normal SymPy expression of type :py:class:`~.Expr`. Examples ======== Construct an element of the :ref:`QQ` domain and then convert it to :py:class:`~.Expr`. >>> from sympy import QQ, Expr >>> q_domain = QQ(2) >>> q_domain 2 >>> q_expr = QQ.to_sympy(q_domain) >>> q_expr 2 Although the printed forms look similar these objects are not of the same type. >>> isinstance(q_domain, Expr) False >>> isinstance(q_expr, Expr) True Construct an element of :ref:`K[x]` and convert to :py:class:`~.Expr`. >>> from sympy import Symbol >>> x = Symbol('x') >>> K = QQ[x] >>> x_domain = K.gens[0] # generator x as a domain element >>> p_domain = x_domain**2/3 + 1 >>> p_domain 1/3*x**2 + 1 >>> p_expr = K.to_sympy(p_domain) >>> p_expr x**2/3 + 1 The :py:meth:`~.Domain.from_sympy` method is used for the opposite conversion from a normal SymPy expression to a domain element. >>> p_domain == p_expr False >>> K.from_sympy(p_expr) == p_domain True >>> K.to_sympy(p_domain) == p_expr True >>> K.from_sympy(K.to_sympy(p_domain)) == p_domain True >>> K.to_sympy(K.from_sympy(p_expr)) == p_expr True The :py:meth:`~.Domain.from_sympy` method makes it easier to construct domain elements interactively. >>> from sympy import Symbol >>> x = Symbol('x') >>> K = QQ[x] >>> K.from_sympy(x**2/3 + 1) 1/3*x**2 + 1 See also ======== from_sympy convert_from """ raise NotImplementedError def from_sympy(self, a): """Convert a SymPy expression to an element of this domain. Explanation =========== See :py:meth:`~.Domain.to_sympy` for explanation and examples. Parameters ========== expr: Expr A normal SymPy expression of type :py:class:`~.Expr`. Returns ======= a: domain element An element of this :py:class:`~.Domain`. See also ======== to_sympy convert_from """ raise NotImplementedError def sum(self, args): return sum(args) def from_FF(K1, a, K0): """Convert ``ModularInteger(int)`` to ``dtype``. """ return None 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_MonogenicFiniteExtension(K1, a, K0): """Convert an ``ExtensionElement`` to ``dtype``. """ return K1.convert_from(a.rep, K0.ring) def from_ExpressionDomain(K1, a, K0): """Convert a ``EX`` object to ``dtype``. """ return K1.from_sympy(a.ex) def from_ExpressionRawDomain(K1, a, K0): """Convert a ``EX`` object to ``dtype``. """ return K1.from_sympy(a) 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("Cannot 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_EXRAW: return K0 if K1.is_EXRAW: return K1 if K0.is_EX: return K0 if K1.is_EX: return K1 if K0.is_FiniteExtension or K1.is_FiniteExtension: if K1.is_FiniteExtension: K0, K1 = K1, K0 if K1.is_FiniteExtension: # Unifying two extensions. # Try to ensure that K0.unify(K1) == K1.unify(K0) if list(ordered([K0.modulus, K1.modulus]))[1] == K0.modulus: K0, K1 = K1, K0 return K1.set_domain(K0) else: # Drop the generator from other and unify with the base domain K1 = K1.drop(K0.symbol) K1 = K0.domain.unify(K1) return K0.set_domain(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 and domain.has_assoc_Ring): 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("Cannot create algebraic field over %s" % self) def inject(self, *symbols): """Inject generators into this domain. """ raise NotImplementedError def drop(self, *symbols): """Drop generators from this domain. """ if self.is_Simple: return self raise NotImplementedError # pragma: no cover 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 canonical_unit(self, a): if self.is_negative(a): return -self.one else: return self.one 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*. Analogue of ``a / b``. Explanation =========== This is essentially the same as ``a / b`` except that an error will be raised if the division is inexact (if there is any remainder) and the result will always be a domain element. When working in a :py:class:`~.Domain` that is not a :py:class:`~.Field` (e.g. :ref:`ZZ` or :ref:`K[x]`) ``exquo`` should be used instead of ``/``. The key invariant is that if ``q = K.exquo(a, b)`` (and ``exquo`` does not raise an exception) then ``a == b*q``. Examples ======== We can use ``K.exquo`` instead of ``/`` for exact division. >>> from sympy import ZZ >>> ZZ.exquo(ZZ(4), ZZ(2)) 2 >>> ZZ.exquo(ZZ(5), ZZ(2)) Traceback (most recent call last): ... ExactQuotientFailed: 2 does not divide 5 in ZZ Over a :py:class:`~.Field` such as :ref:`QQ`, division (with nonzero divisor) is always exact so in that case ``/`` can be used instead of :py:meth:`~.Domain.exquo`. >>> from sympy import QQ >>> QQ.exquo(QQ(5), QQ(2)) 5/2 >>> QQ(5) / QQ(2) 5/2 Parameters ========== a: domain element The dividend b: domain element The divisor Returns ======= q: domain element The exact quotient Raises ====== ExactQuotientFailed: if exact division is not possible. ZeroDivisionError: when the divisor is zero. See also ======== quo: Analogue of ``a // b`` rem: Analogue of ``a % b`` div: Analogue of ``divmod(a, b)`` Notes ===== Since the default :py:attr:`~.Domain.dtype` for :ref:`ZZ` is ``int`` (or ``mpz``) division as ``a / b`` should not be used as it would give a ``float``. >>> ZZ(4) / ZZ(2) 2.0 >>> ZZ(5) / ZZ(2) 2.5 Using ``/`` with :ref:`ZZ` will lead to incorrect results so :py:meth:`~.Domain.exquo` should be used instead. """ raise NotImplementedError def quo(self, a, b): """Quotient of *a* and *b*. Analogue of ``a // b``. ``K.quo(a, b)`` is equivalent to ``K.div(a, b)[0]``. See :py:meth:`~.Domain.div` for more explanation. See also ======== rem: Analogue of ``a % b`` div: Analogue of ``divmod(a, b)`` exquo: Analogue of ``a / b`` """ raise NotImplementedError def rem(self, a, b): """Modulo division of *a* and *b*. Analogue of ``a % b``. ``K.rem(a, b)`` is equivalent to ``K.div(a, b)[1]``. See :py:meth:`~.Domain.div` for more explanation. See also ======== quo: Analogue of ``a // b`` div: Analogue of ``divmod(a, b)`` exquo: Analogue of ``a / b`` """ raise NotImplementedError def div(self, a, b): """Quotient and remainder for *a* and *b*. Analogue of ``divmod(a, b)`` Explanation =========== This is essentially the same as ``divmod(a, b)`` except that is more consistent when working over some :py:class:`~.Field` domains such as :ref:`QQ`. When working over an arbitrary :py:class:`~.Domain` the :py:meth:`~.Domain.div` method should be used instead of ``divmod``. The key invariant is that if ``q, r = K.div(a, b)`` then ``a == b*q + r``. The result of ``K.div(a, b)`` is the same as the tuple ``(K.quo(a, b), K.rem(a, b))`` except that if both quotient and remainder are needed then it is more efficient to use :py:meth:`~.Domain.div`. Examples ======== We can use ``K.div`` instead of ``divmod`` for floor division and remainder. >>> from sympy import ZZ, QQ >>> ZZ.div(ZZ(5), ZZ(2)) (2, 1) If ``K`` is a :py:class:`~.Field` then the division is always exact with a remainder of :py:attr:`~.Domain.zero`. >>> QQ.div(QQ(5), QQ(2)) (5/2, 0) Parameters ========== a: domain element The dividend b: domain element The divisor Returns ======= (q, r): tuple of domain elements The quotient and remainder Raises ====== ZeroDivisionError: when the divisor is zero. See also ======== quo: Analogue of ``a // b`` rem: Analogue of ``a % b`` exquo: Analogue of ``a / b`` Notes ===== If ``gmpy`` is installed then the ``gmpy.mpq`` type will be used as the :py:attr:`~.Domain.dtype` for :ref:`QQ`. The ``gmpy.mpq`` type defines ``divmod`` in a way that is undesirable so :py:meth:`~.Domain.div` should be used instead of ``divmod``. >>> a = QQ(1) >>> b = QQ(3, 2) >>> a # doctest: +SKIP mpq(1,1) >>> b # doctest: +SKIP mpq(3,2) >>> divmod(a, b) # doctest: +SKIP (mpz(0), mpq(1,1)) >>> QQ.div(a, b) # doctest: +SKIP (mpq(2,3), mpq(0,1)) Using ``//`` or ``%`` with :ref:`QQ` will lead to incorrect results so :py:meth:`~.Domain.div` should be used instead. """ 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']
3173897e18eb2c0bbe502c9783a61131801cee7930e9201f918ebafd1286f44b
"""Tools for polynomial factorization routines in characteristic zero. """ from sympy.polys.rings import ring, xring from sympy.polys.domains import FF, ZZ, QQ, ZZ_I, QQ_I, RR, EX from sympy.polys import polyconfig as config from sympy.polys.polyerrors import DomainError from sympy.polys.polyclasses import ANP from sympy.polys.specialpolys import f_polys, w_polys from sympy.core.numbers import I from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin from sympy.ntheory.generate import nextprime from sympy.testing.pytest import raises, XFAIL f_0, f_1, f_2, f_3, f_4, f_5, f_6 = f_polys() w_1, w_2 = w_polys() def test_dup_trial_division(): R, x = ring("x", ZZ) assert R.dup_trial_division(x**5 + 8*x**4 + 25*x**3 + 38*x**2 + 28*x + 8, (x + 1, x + 2)) == [(x + 1, 2), (x + 2, 3)] def test_dmp_trial_division(): R, x, y = ring("x,y", ZZ) assert R.dmp_trial_division(x**5 + 8*x**4 + 25*x**3 + 38*x**2 + 28*x + 8, (x + 1, x + 2)) == [(x + 1, 2), (x + 2, 3)] def test_dup_zz_mignotte_bound(): R, x = ring("x", ZZ) assert R.dup_zz_mignotte_bound(2*x**2 + 3*x + 4) == 6 assert R.dup_zz_mignotte_bound(x**3 + 14*x**2 + 56*x + 64) == 152 def test_dmp_zz_mignotte_bound(): R, x, y = ring("x,y", ZZ) assert R.dmp_zz_mignotte_bound(2*x**2 + 3*x + 4) == 32 def test_dup_zz_hensel_step(): R, x = ring("x", ZZ) f = x**4 - 1 g = x**3 + 2*x**2 - x - 2 h = x - 2 s = -2 t = 2*x**2 - 2*x - 1 G, H, S, T = R.dup_zz_hensel_step(5, f, g, h, s, t) assert G == x**3 + 7*x**2 - x - 7 assert H == x - 7 assert S == 8 assert T == -8*x**2 - 12*x - 1 def test_dup_zz_hensel_lift(): R, x = ring("x", ZZ) f = x**4 - 1 F = [x - 1, x - 2, x + 2, x + 1] assert R.dup_zz_hensel_lift(ZZ(5), f, F, 4) == \ [x - 1, x - 182, x + 182, x + 1] def test_dup_zz_irreducible_p(): R, x = ring("x", ZZ) assert R.dup_zz_irreducible_p(3*x**4 + 2*x**3 + 6*x**2 + 8*x + 7) is None assert R.dup_zz_irreducible_p(3*x**4 + 2*x**3 + 6*x**2 + 8*x + 4) is None assert R.dup_zz_irreducible_p(3*x**4 + 2*x**3 + 6*x**2 + 8*x + 10) is True assert R.dup_zz_irreducible_p(3*x**4 + 2*x**3 + 6*x**2 + 8*x + 14) is True def test_dup_cyclotomic_p(): R, x = ring("x", ZZ) assert R.dup_cyclotomic_p(x - 1) is True assert R.dup_cyclotomic_p(x + 1) is True assert R.dup_cyclotomic_p(x**2 + x + 1) is True assert R.dup_cyclotomic_p(x**2 + 1) is True assert R.dup_cyclotomic_p(x**4 + x**3 + x**2 + x + 1) is True assert R.dup_cyclotomic_p(x**2 - x + 1) is True assert R.dup_cyclotomic_p(x**6 + x**5 + x**4 + x**3 + x**2 + x + 1) is True assert R.dup_cyclotomic_p(x**4 + 1) is True assert R.dup_cyclotomic_p(x**6 + x**3 + 1) is True assert R.dup_cyclotomic_p(0) is False assert R.dup_cyclotomic_p(1) is False assert R.dup_cyclotomic_p(x) is False assert R.dup_cyclotomic_p(x + 2) is False assert R.dup_cyclotomic_p(3*x + 1) is False assert R.dup_cyclotomic_p(x**2 - 1) is False f = x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1 assert R.dup_cyclotomic_p(f) is False g = x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1 assert R.dup_cyclotomic_p(g) is True R, x = ring("x", QQ) assert R.dup_cyclotomic_p(x**2 + x + 1) is True assert R.dup_cyclotomic_p(QQ(1,2)*x**2 + x + 1) is False R, x = ring("x", ZZ["y"]) assert R.dup_cyclotomic_p(x**2 + x + 1) is False def test_dup_zz_cyclotomic_poly(): R, x = ring("x", ZZ) assert R.dup_zz_cyclotomic_poly(1) == x - 1 assert R.dup_zz_cyclotomic_poly(2) == x + 1 assert R.dup_zz_cyclotomic_poly(3) == x**2 + x + 1 assert R.dup_zz_cyclotomic_poly(4) == x**2 + 1 assert R.dup_zz_cyclotomic_poly(5) == x**4 + x**3 + x**2 + x + 1 assert R.dup_zz_cyclotomic_poly(6) == x**2 - x + 1 assert R.dup_zz_cyclotomic_poly(7) == x**6 + x**5 + x**4 + x**3 + x**2 + x + 1 assert R.dup_zz_cyclotomic_poly(8) == x**4 + 1 assert R.dup_zz_cyclotomic_poly(9) == x**6 + x**3 + 1 def test_dup_zz_cyclotomic_factor(): R, x = ring("x", ZZ) assert R.dup_zz_cyclotomic_factor(0) is None assert R.dup_zz_cyclotomic_factor(1) is None assert R.dup_zz_cyclotomic_factor(2*x**10 - 1) is None assert R.dup_zz_cyclotomic_factor(x**10 - 3) is None assert R.dup_zz_cyclotomic_factor(x**10 + x**5 - 1) is None assert R.dup_zz_cyclotomic_factor(x + 1) == [x + 1] assert R.dup_zz_cyclotomic_factor(x - 1) == [x - 1] assert R.dup_zz_cyclotomic_factor(x**2 + 1) == [x**2 + 1] assert R.dup_zz_cyclotomic_factor(x**2 - 1) == [x - 1, x + 1] assert R.dup_zz_cyclotomic_factor(x**27 + 1) == \ [x + 1, x**2 - x + 1, x**6 - x**3 + 1, x**18 - x**9 + 1] assert R.dup_zz_cyclotomic_factor(x**27 - 1) == \ [x - 1, x**2 + x + 1, x**6 + x**3 + 1, x**18 + x**9 + 1] def test_dup_zz_factor(): R, x = ring("x", ZZ) assert R.dup_zz_factor(0) == (0, []) assert R.dup_zz_factor(7) == (7, []) assert R.dup_zz_factor(-7) == (-7, []) assert R.dup_zz_factor_sqf(0) == (0, []) assert R.dup_zz_factor_sqf(7) == (7, []) assert R.dup_zz_factor_sqf(-7) == (-7, []) assert R.dup_zz_factor(2*x + 4) == (2, [(x + 2, 1)]) assert R.dup_zz_factor_sqf(2*x + 4) == (2, [x + 2]) f = x**4 + x + 1 for i in range(0, 20): assert R.dup_zz_factor(f) == (1, [(f, 1)]) assert R.dup_zz_factor(x**2 + 2*x + 2) == \ (1, [(x**2 + 2*x + 2, 1)]) assert R.dup_zz_factor(18*x**2 + 12*x + 2) == \ (2, [(3*x + 1, 2)]) assert R.dup_zz_factor(-9*x**2 + 1) == \ (-1, [(3*x - 1, 1), (3*x + 1, 1)]) assert R.dup_zz_factor_sqf(-9*x**2 + 1) == \ (-1, [3*x - 1, 3*x + 1]) assert R.dup_zz_factor(x**3 - 6*x**2 + 11*x - 6) == \ (1, [(x - 3, 1), (x - 2, 1), (x - 1, 1)]) assert R.dup_zz_factor_sqf(x**3 - 6*x**2 + 11*x - 6) == \ (1, [x - 3, x - 2, x - 1]) assert R.dup_zz_factor(3*x**3 + 10*x**2 + 13*x + 10) == \ (1, [(x + 2, 1), (3*x**2 + 4*x + 5, 1)]) assert R.dup_zz_factor_sqf(3*x**3 + 10*x**2 + 13*x + 10) == \ (1, [x + 2, 3*x**2 + 4*x + 5]) assert R.dup_zz_factor(-x**6 + x**2) == \ (-1, [(x - 1, 1), (x + 1, 1), (x, 2), (x**2 + 1, 1)]) f = 1080*x**8 + 5184*x**7 + 2099*x**6 + 744*x**5 + 2736*x**4 - 648*x**3 + 129*x**2 - 324 assert R.dup_zz_factor(f) == \ (1, [(5*x**4 + 24*x**3 + 9*x**2 + 12, 1), (216*x**4 + 31*x**2 - 27, 1)]) f = -29802322387695312500000000000000000000*x**25 \ + 2980232238769531250000000000000000*x**20 \ + 1743435859680175781250000000000*x**15 \ + 114142894744873046875000000*x**10 \ - 210106372833251953125*x**5 \ + 95367431640625 assert R.dup_zz_factor(f) == \ (-95367431640625, [(5*x - 1, 1), (100*x**2 + 10*x - 1, 2), (625*x**4 + 125*x**3 + 25*x**2 + 5*x + 1, 1), (10000*x**4 - 3000*x**3 + 400*x**2 - 20*x + 1, 2), (10000*x**4 + 2000*x**3 + 400*x**2 + 30*x + 1, 2)]) f = x**10 - 1 config.setup('USE_CYCLOTOMIC_FACTOR', True) F_0 = R.dup_zz_factor(f) config.setup('USE_CYCLOTOMIC_FACTOR', False) F_1 = R.dup_zz_factor(f) assert F_0 == F_1 == \ (1, [(x - 1, 1), (x + 1, 1), (x**4 - x**3 + x**2 - x + 1, 1), (x**4 + x**3 + x**2 + x + 1, 1)]) config.setup('USE_CYCLOTOMIC_FACTOR') f = x**10 + 1 config.setup('USE_CYCLOTOMIC_FACTOR', True) F_0 = R.dup_zz_factor(f) config.setup('USE_CYCLOTOMIC_FACTOR', False) F_1 = R.dup_zz_factor(f) assert F_0 == F_1 == \ (1, [(x**2 + 1, 1), (x**8 - x**6 + x**4 - x**2 + 1, 1)]) config.setup('USE_CYCLOTOMIC_FACTOR') def test_dmp_zz_wang(): R, x,y,z = ring("x,y,z", ZZ) UV, _x = ring("x", ZZ) p = ZZ(nextprime(R.dmp_zz_mignotte_bound(w_1))) assert p == 6291469 t_1, k_1, e_1 = y, 1, ZZ(-14) t_2, k_2, e_2 = z, 2, ZZ(3) t_3, k_3, e_3 = y + z, 2, ZZ(-11) t_4, k_4, e_4 = y - z, 1, ZZ(-17) T = [t_1, t_2, t_3, t_4] K = [k_1, k_2, k_3, k_4] E = [e_1, e_2, e_3, e_4] T = zip([ t.drop(x) for t in T ], K) A = [ZZ(-14), ZZ(3)] S = R.dmp_eval_tail(w_1, A) cs, s = UV.dup_primitive(S) assert cs == 1 and s == S == \ 1036728*_x**6 + 915552*_x**5 + 55748*_x**4 + 105621*_x**3 - 17304*_x**2 - 26841*_x - 644 assert R.dmp_zz_wang_non_divisors(E, cs, ZZ(4)) == [7, 3, 11, 17] assert UV.dup_sqf_p(s) and UV.dup_degree(s) == R.dmp_degree(w_1) _, H = UV.dup_zz_factor_sqf(s) h_1 = 44*_x**2 + 42*_x + 1 h_2 = 126*_x**2 - 9*_x + 28 h_3 = 187*_x**2 - 23 assert H == [h_1, h_2, h_3] LC = [ lc.drop(x) for lc in [-4*y - 4*z, -y*z**2, y**2 - z**2] ] assert R.dmp_zz_wang_lead_coeffs(w_1, T, cs, E, H, A) == (w_1, H, LC) factors = R.dmp_zz_wang_hensel_lifting(w_1, H, LC, A, p) assert R.dmp_expand(factors) == w_1 @XFAIL def test_dmp_zz_wang_fail(): R, x,y,z = ring("x,y,z", ZZ) UV, _x = ring("x", ZZ) p = ZZ(nextprime(R.dmp_zz_mignotte_bound(w_1))) assert p == 6291469 H_1 = [44*x**2 + 42*x + 1, 126*x**2 - 9*x + 28, 187*x**2 - 23] H_2 = [-4*x**2*y - 12*x**2 - 3*x*y + 1, -9*x**2*y - 9*x - 2*y, x**2*y**2 - 9*x**2 + y - 9] H_3 = [-4*x**2*y - 12*x**2 - 3*x*y + 1, -9*x**2*y - 9*x - 2*y, x**2*y**2 - 9*x**2 + y - 9] c_1 = -70686*x**5 - 5863*x**4 - 17826*x**3 + 2009*x**2 + 5031*x + 74 c_2 = 9*x**5*y**4 + 12*x**5*y**3 - 45*x**5*y**2 - 108*x**5*y - 324*x**5 + 18*x**4*y**3 - 216*x**4*y**2 - 810*x**4*y + 2*x**3*y**4 + 9*x**3*y**3 - 252*x**3*y**2 - 288*x**3*y - 945*x**3 - 30*x**2*y**2 - 414*x**2*y + 2*x*y**3 - 54*x*y**2 - 3*x*y + 81*x + 12*y c_3 = -36*x**4*y**2 - 108*x**4*y - 27*x**3*y**2 - 36*x**3*y - 108*x**3 - 8*x**2*y**2 - 42*x**2*y - 6*x*y**2 + 9*x + 2*y assert R.dmp_zz_diophantine(H_1, c_1, [], 5, p) == [-3*x, -2, 1] assert R.dmp_zz_diophantine(H_2, c_2, [ZZ(-14)], 5, p) == [-x*y, -3*x, -6] assert R.dmp_zz_diophantine(H_3, c_3, [ZZ(-14)], 5, p) == [0, 0, -1] def test_issue_6355(): # This tests a bug in the Wang algorithm that occurred only with a very # specific set of random numbers. random_sequence = [-1, -1, 0, 0, 0, 0, -1, -1, 0, -1, 3, -1, 3, 3, 3, 3, -1, 3] R, x, y, z = ring("x,y,z", ZZ) f = 2*x**2 + y*z - y - z**2 + z assert R.dmp_zz_wang(f, seed=random_sequence) == [f] def test_dmp_zz_factor(): R, x = ring("x", ZZ) assert R.dmp_zz_factor(0) == (0, []) assert R.dmp_zz_factor(7) == (7, []) assert R.dmp_zz_factor(-7) == (-7, []) assert R.dmp_zz_factor(x**2 - 9) == (1, [(x - 3, 1), (x + 3, 1)]) R, x, y = ring("x,y", ZZ) assert R.dmp_zz_factor(0) == (0, []) assert R.dmp_zz_factor(7) == (7, []) assert R.dmp_zz_factor(-7) == (-7, []) assert R.dmp_zz_factor(x) == (1, [(x, 1)]) assert R.dmp_zz_factor(4*x) == (4, [(x, 1)]) assert R.dmp_zz_factor(4*x + 2) == (2, [(2*x + 1, 1)]) assert R.dmp_zz_factor(x*y + 1) == (1, [(x*y + 1, 1)]) assert R.dmp_zz_factor(y**2 + 1) == (1, [(y**2 + 1, 1)]) assert R.dmp_zz_factor(y**2 - 1) == (1, [(y - 1, 1), (y + 1, 1)]) assert R.dmp_zz_factor(x**2*y**2 + 6*x**2*y + 9*x**2 - 1) == (1, [(x*y + 3*x - 1, 1), (x*y + 3*x + 1, 1)]) assert R.dmp_zz_factor(x**2*y**2 - 9) == (1, [(x*y - 3, 1), (x*y + 3, 1)]) R, x, y, z = ring("x,y,z", ZZ) assert R.dmp_zz_factor(x**2*y**2*z**2 - 9) == \ (1, [(x*y*z - 3, 1), (x*y*z + 3, 1)]) R, x, y, z, u = ring("x,y,z,u", ZZ) assert R.dmp_zz_factor(x**2*y**2*z**2*u**2 - 9) == \ (1, [(x*y*z*u - 3, 1), (x*y*z*u + 3, 1)]) R, x, y, z = ring("x,y,z", ZZ) assert R.dmp_zz_factor(f_1) == \ (1, [(x + y*z + 20, 1), (x*y + z + 10, 1), (x*z + y + 30, 1)]) assert R.dmp_zz_factor(f_2) == \ (1, [(x**2*y**2 + x**2*z**2 + y + 90, 1), (x**3*y + x**3*z + z - 11, 1)]) assert R.dmp_zz_factor(f_3) == \ (1, [(x**2*y**2 + x*z**4 + x + z, 1), (x**3 + x*y*z + y**2 + y*z**3, 1)]) assert R.dmp_zz_factor(f_4) == \ (-1, [(x*y**3 + z**2, 1), (x**2*z + y**4*z**2 + 5, 1), (x**3*y - z**2 - 3, 1), (x**3*y**4 + z**2, 1)]) assert R.dmp_zz_factor(f_5) == \ (-1, [(x + y - z, 3)]) R, x, y, z, t = ring("x,y,z,t", ZZ) assert R.dmp_zz_factor(f_6) == \ (1, [(47*x*y + z**3*t**2 - t**2, 1), (45*x**3 - 9*y**3 - y**2 + 3*z**3 + 2*z*t, 1)]) R, x, y, z = ring("x,y,z", ZZ) assert R.dmp_zz_factor(w_1) == \ (1, [(x**2*y**2 - x**2*z**2 + y - z**2, 1), (x**2*y*z**2 + 3*x*z + 2*y, 1), (4*x**2*y + 4*x**2*z + x*y*z - 1, 1)]) R, x, y = ring("x,y", ZZ) f = -12*x**16*y + 240*x**12*y**3 - 768*x**10*y**4 + 1080*x**8*y**5 - 768*x**6*y**6 + 240*x**4*y**7 - 12*y**9 assert R.dmp_zz_factor(f) == \ (-12, [(y, 1), (x**2 - y, 6), (x**4 + 6*x**2*y + y**2, 1)]) def test_dup_qq_i_factor(): R, x = ring("x", QQ_I) i = QQ_I(0, 1) assert R.dup_qq_i_factor(x**2 - 2) == (QQ_I(1, 0), [(x**2 - 2, 1)]) assert R.dup_qq_i_factor(x**2 - 1) == (QQ_I(1, 0), [(x - 1, 1), (x + 1, 1)]) assert R.dup_qq_i_factor(x**2 + 1) == (QQ_I(1, 0), [(x - i, 1), (x + i, 1)]) assert R.dup_qq_i_factor(x**2/4 + 1) == \ (QQ_I(QQ(1, 4), 0), [(x - 2*i, 1), (x + 2*i, 1)]) assert R.dup_qq_i_factor(x**2 + 4) == \ (QQ_I(1, 0), [(x - 2*i, 1), (x + 2*i, 1)]) assert R.dup_qq_i_factor(x**2 + 2*x + 1) == \ (QQ_I(1, 0), [(x + 1, 2)]) assert R.dup_qq_i_factor(x**2 + 2*i*x - 1) == \ (QQ_I(1, 0), [(x + i, 2)]) f = 8192*x**2 + x*(22656 + 175232*i) - 921416 + 242313*i assert R.dup_qq_i_factor(f) == \ (QQ_I(8192, 0), [(x + QQ_I(QQ(177, 128), QQ(1369, 128)), 2)]) def test_dmp_qq_i_factor(): R, x, y = ring("x, y", QQ_I) i = QQ_I(0, 1) assert R.dmp_qq_i_factor(x**2 + 2*y**2) == \ (QQ_I(1, 0), [(x**2 + 2*y**2, 1)]) assert R.dmp_qq_i_factor(x**2 + y**2) == \ (QQ_I(1, 0), [(x - i*y, 1), (x + i*y, 1)]) assert R.dmp_qq_i_factor(x**2 + y**2/4) == \ (QQ_I(1, 0), [(x - i*y/2, 1), (x + i*y/2, 1)]) assert R.dmp_qq_i_factor(4*x**2 + y**2) == \ (QQ_I(4, 0), [(x - i*y/2, 1), (x + i*y/2, 1)]) def test_dup_zz_i_factor(): R, x = ring("x", ZZ_I) i = ZZ_I(0, 1) assert R.dup_zz_i_factor(x**2 - 2) == (ZZ_I(1, 0), [(x**2 - 2, 1)]) assert R.dup_zz_i_factor(x**2 - 1) == (ZZ_I(1, 0), [(x - 1, 1), (x + 1, 1)]) assert R.dup_zz_i_factor(x**2 + 1) == (ZZ_I(1, 0), [(x - i, 1), (x + i, 1)]) assert R.dup_zz_i_factor(x**2 + 4) == \ (ZZ_I(1, 0), [(x - 2*i, 1), (x + 2*i, 1)]) assert R.dup_zz_i_factor(x**2 + 2*x + 1) == \ (ZZ_I(1, 0), [(x + 1, 2)]) assert R.dup_zz_i_factor(x**2 + 2*i*x - 1) == \ (ZZ_I(1, 0), [(x + i, 2)]) f = 8192*x**2 + x*(22656 + 175232*i) - 921416 + 242313*i assert R.dup_zz_i_factor(f) == \ (ZZ_I(0, 1), [((64 - 64*i)*x + (773 + 596*i), 2)]) def test_dmp_zz_i_factor(): R, x, y = ring("x, y", ZZ_I) i = ZZ_I(0, 1) assert R.dmp_zz_i_factor(x**2 + 2*y**2) == \ (ZZ_I(1, 0), [(x**2 + 2*y**2, 1)]) assert R.dmp_zz_i_factor(x**2 + y**2) == \ (ZZ_I(1, 0), [(x - i*y, 1), (x + i*y, 1)]) assert R.dmp_zz_i_factor(4*x**2 + y**2) == \ (ZZ_I(1, 0), [(2*x - i*y, 1), (2*x + i*y, 1)]) def test_dup_ext_factor(): R, x = ring("x", QQ.algebraic_field(I)) def anp(element): return ANP(element, [QQ(1), QQ(0), QQ(1)], QQ) assert R.dup_ext_factor(0) == (anp([]), []) f = anp([QQ(1)])*x + anp([QQ(1)]) assert R.dup_ext_factor(f) == (anp([QQ(1)]), [(f, 1)]) g = anp([QQ(2)])*x + anp([QQ(2)]) assert R.dup_ext_factor(g) == (anp([QQ(2)]), [(f, 1)]) f = anp([QQ(7)])*x**4 + anp([QQ(1, 1)]) g = anp([QQ(1)])*x**4 + anp([QQ(1, 7)]) assert R.dup_ext_factor(f) == (anp([QQ(7)]), [(g, 1)]) f = anp([QQ(1)])*x**4 + anp([QQ(1)]) assert R.dup_ext_factor(f) == \ (anp([QQ(1, 1)]), [(anp([QQ(1)])*x**2 + anp([QQ(-1), QQ(0)]), 1), (anp([QQ(1)])*x**2 + anp([QQ( 1), QQ(0)]), 1)]) f = anp([QQ(4, 1)])*x**2 + anp([QQ(9, 1)]) assert R.dup_ext_factor(f) == \ (anp([QQ(4, 1)]), [(anp([QQ(1, 1)])*x + anp([-QQ(3, 2), QQ(0, 1)]), 1), (anp([QQ(1, 1)])*x + anp([ QQ(3, 2), QQ(0, 1)]), 1)]) f = anp([QQ(4, 1)])*x**4 + anp([QQ(8, 1)])*x**3 + anp([QQ(77, 1)])*x**2 + anp([QQ(18, 1)])*x + anp([QQ(153, 1)]) assert R.dup_ext_factor(f) == \ (anp([QQ(4, 1)]), [(anp([QQ(1, 1)])*x + anp([-QQ(4, 1), QQ(1, 1)]), 1), (anp([QQ(1, 1)])*x + anp([-QQ(3, 2), QQ(0, 1)]), 1), (anp([QQ(1, 1)])*x + anp([ QQ(3, 2), QQ(0, 1)]), 1), (anp([QQ(1, 1)])*x + anp([ QQ(4, 1), QQ(1, 1)]), 1)]) R, x = ring("x", QQ.algebraic_field(sqrt(2))) def anp(element): return ANP(element, [QQ(1), QQ(0), QQ(-2)], QQ) f = anp([QQ(1)])*x**4 + anp([QQ(1, 1)]) assert R.dup_ext_factor(f) == \ (anp([QQ(1)]), [(anp([QQ(1)])*x**2 + anp([QQ(-1), QQ(0)])*x + anp([QQ(1)]), 1), (anp([QQ(1)])*x**2 + anp([QQ( 1), QQ(0)])*x + anp([QQ(1)]), 1)]) f = anp([QQ(1, 1)])*x**2 + anp([QQ(2), QQ(0)])*x + anp([QQ(2, 1)]) assert R.dup_ext_factor(f) == \ (anp([QQ(1, 1)]), [(anp([1])*x + anp([1, 0]), 2)]) assert R.dup_ext_factor(f**3) == \ (anp([QQ(1, 1)]), [(anp([1])*x + anp([1, 0]), 6)]) f *= anp([QQ(2, 1)]) assert R.dup_ext_factor(f) == \ (anp([QQ(2, 1)]), [(anp([1])*x + anp([1, 0]), 2)]) assert R.dup_ext_factor(f**3) == \ (anp([QQ(8, 1)]), [(anp([1])*x + anp([1, 0]), 6)]) def test_dmp_ext_factor(): R, x,y = ring("x,y", QQ.algebraic_field(sqrt(2))) def anp(x): return ANP(x, [QQ(1), QQ(0), QQ(-2)], QQ) assert R.dmp_ext_factor(0) == (anp([]), []) f = anp([QQ(1)])*x + anp([QQ(1)]) assert R.dmp_ext_factor(f) == (anp([QQ(1)]), [(f, 1)]) g = anp([QQ(2)])*x + anp([QQ(2)]) assert R.dmp_ext_factor(g) == (anp([QQ(2)]), [(f, 1)]) f = anp([QQ(1)])*x**2 + anp([QQ(-2)])*y**2 assert R.dmp_ext_factor(f) == \ (anp([QQ(1)]), [(anp([QQ(1)])*x + anp([QQ(-1), QQ(0)])*y, 1), (anp([QQ(1)])*x + anp([QQ( 1), QQ(0)])*y, 1)]) f = anp([QQ(2)])*x**2 + anp([QQ(-4)])*y**2 assert R.dmp_ext_factor(f) == \ (anp([QQ(2)]), [(anp([QQ(1)])*x + anp([QQ(-1), QQ(0)])*y, 1), (anp([QQ(1)])*x + anp([QQ( 1), QQ(0)])*y, 1)]) def test_dup_factor_list(): R, x = ring("x", ZZ) assert R.dup_factor_list(0) == (0, []) assert R.dup_factor_list(7) == (7, []) R, x = ring("x", QQ) assert R.dup_factor_list(0) == (0, []) assert R.dup_factor_list(QQ(1, 7)) == (QQ(1, 7), []) R, x = ring("x", ZZ['t']) assert R.dup_factor_list(0) == (0, []) assert R.dup_factor_list(7) == (7, []) R, x = ring("x", QQ['t']) assert R.dup_factor_list(0) == (0, []) assert R.dup_factor_list(QQ(1, 7)) == (QQ(1, 7), []) R, x = ring("x", ZZ) assert R.dup_factor_list_include(0) == [(0, 1)] assert R.dup_factor_list_include(7) == [(7, 1)] assert R.dup_factor_list(x**2 + 2*x + 1) == (1, [(x + 1, 2)]) assert R.dup_factor_list_include(x**2 + 2*x + 1) == [(x + 1, 2)] # issue 8037 assert R.dup_factor_list(6*x**2 - 5*x - 6) == (1, [(2*x - 3, 1), (3*x + 2, 1)]) R, x = ring("x", QQ) assert R.dup_factor_list(QQ(1,2)*x**2 + x + QQ(1,2)) == (QQ(1, 2), [(x + 1, 2)]) R, x = ring("x", FF(2)) assert R.dup_factor_list(x**2 + 1) == (1, [(x + 1, 2)]) R, x = ring("x", RR) assert R.dup_factor_list(1.0*x**2 + 2.0*x + 1.0) == (1.0, [(1.0*x + 1.0, 2)]) assert R.dup_factor_list(2.0*x**2 + 4.0*x + 2.0) == (2.0, [(1.0*x + 1.0, 2)]) f = 6.7225336055071*x**2 - 10.6463972754741*x - 0.33469524022264 coeff, factors = R.dup_factor_list(f) assert coeff == RR(10.6463972754741) assert len(factors) == 1 assert factors[0][0].max_norm() == RR(1.0) assert factors[0][1] == 1 Rt, t = ring("t", ZZ) R, x = ring("x", Rt) f = 4*t*x**2 + 4*t**2*x assert R.dup_factor_list(f) == \ (4*t, [(x, 1), (x + t, 1)]) Rt, t = ring("t", QQ) R, x = ring("x", Rt) f = QQ(1, 2)*t*x**2 + QQ(1, 2)*t**2*x assert R.dup_factor_list(f) == \ (QQ(1, 2)*t, [(x, 1), (x + t, 1)]) R, x = ring("x", QQ.algebraic_field(I)) def anp(element): return ANP(element, [QQ(1), QQ(0), QQ(1)], QQ) f = anp([QQ(1, 1)])*x**4 + anp([QQ(2, 1)])*x**2 assert R.dup_factor_list(f) == \ (anp([QQ(1, 1)]), [(anp([QQ(1, 1)])*x, 2), (anp([QQ(1, 1)])*x**2 + anp([])*x + anp([QQ(2, 1)]), 1)]) R, x = ring("x", EX) raises(DomainError, lambda: R.dup_factor_list(EX(sin(1)))) def test_dmp_factor_list(): R, x, y = ring("x,y", ZZ) assert R.dmp_factor_list(0) == (ZZ(0), []) assert R.dmp_factor_list(7) == (7, []) R, x, y = ring("x,y", QQ) assert R.dmp_factor_list(0) == (QQ(0), []) assert R.dmp_factor_list(QQ(1, 7)) == (QQ(1, 7), []) Rt, t = ring("t", ZZ) R, x, y = ring("x,y", Rt) assert R.dmp_factor_list(0) == (0, []) assert R.dmp_factor_list(7) == (ZZ(7), []) Rt, t = ring("t", QQ) R, x, y = ring("x,y", Rt) assert R.dmp_factor_list(0) == (0, []) assert R.dmp_factor_list(QQ(1, 7)) == (QQ(1, 7), []) R, x, y = ring("x,y", ZZ) assert R.dmp_factor_list_include(0) == [(0, 1)] assert R.dmp_factor_list_include(7) == [(7, 1)] R, X = xring("x:200", ZZ) f, g = X[0]**2 + 2*X[0] + 1, X[0] + 1 assert R.dmp_factor_list(f) == (1, [(g, 2)]) f, g = X[-1]**2 + 2*X[-1] + 1, X[-1] + 1 assert R.dmp_factor_list(f) == (1, [(g, 2)]) R, x = ring("x", ZZ) assert R.dmp_factor_list(x**2 + 2*x + 1) == (1, [(x + 1, 2)]) R, x = ring("x", QQ) assert R.dmp_factor_list(QQ(1,2)*x**2 + x + QQ(1,2)) == (QQ(1,2), [(x + 1, 2)]) R, x, y = ring("x,y", ZZ) assert R.dmp_factor_list(x**2 + 2*x + 1) == (1, [(x + 1, 2)]) R, x, y = ring("x,y", QQ) assert R.dmp_factor_list(QQ(1,2)*x**2 + x + QQ(1,2)) == (QQ(1,2), [(x + 1, 2)]) R, x, y = ring("x,y", ZZ) f = 4*x**2*y + 4*x*y**2 assert R.dmp_factor_list(f) == \ (4, [(y, 1), (x, 1), (x + y, 1)]) assert R.dmp_factor_list_include(f) == \ [(4*y, 1), (x, 1), (x + y, 1)] R, x, y = ring("x,y", QQ) f = QQ(1,2)*x**2*y + QQ(1,2)*x*y**2 assert R.dmp_factor_list(f) == \ (QQ(1,2), [(y, 1), (x, 1), (x + y, 1)]) R, x, y = ring("x,y", RR) f = 2.0*x**2 - 8.0*y**2 assert R.dmp_factor_list(f) == \ (RR(8.0), [(0.5*x - y, 1), (0.5*x + y, 1)]) f = 6.7225336055071*x**2*y**2 - 10.6463972754741*x*y - 0.33469524022264 coeff, factors = R.dmp_factor_list(f) assert coeff == RR(10.6463972754741) assert len(factors) == 1 assert factors[0][0].max_norm() == RR(1.0) assert factors[0][1] == 1 Rt, t = ring("t", ZZ) R, x, y = ring("x,y", Rt) f = 4*t*x**2 + 4*t**2*x assert R.dmp_factor_list(f) == \ (4*t, [(x, 1), (x + t, 1)]) Rt, t = ring("t", QQ) R, x, y = ring("x,y", Rt) f = QQ(1, 2)*t*x**2 + QQ(1, 2)*t**2*x assert R.dmp_factor_list(f) == \ (QQ(1, 2)*t, [(x, 1), (x + t, 1)]) R, x, y = ring("x,y", FF(2)) raises(NotImplementedError, lambda: R.dmp_factor_list(x**2 + y**2)) R, x, y = ring("x,y", EX) raises(DomainError, lambda: R.dmp_factor_list(EX(sin(1)))) def test_dup_irreducible_p(): R, x = ring("x", ZZ) assert R.dup_irreducible_p(x**2 + x + 1) is True assert R.dup_irreducible_p(x**2 + 2*x + 1) is False def test_dmp_irreducible_p(): R, x, y = ring("x,y", ZZ) assert R.dmp_irreducible_p(x**2 + x + 1) is True assert R.dmp_irreducible_p(x**2 + 2*x + 1) is False
f5f62c14390493caf418d2233f79c3b3bc1702371051f10d476dd346c6810f1a
"""Test sparse polynomials. """ from functools import reduce 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.numbers import (oo, pi) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt 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(sqrt(2) + sqrt(3)) 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) r, F = sring([exp(2)]) f = r.from_expr(exp(2)) assert f == F[0] 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)]) def test_issue_21410(): R, x = ring('x', FF(2)) p = x**6 + x**5 + x**4 + x**3 + 1 assert p._pow_multinomial(4) == x**24 + x**20 + x**16 + x**12 + 1
184fb6e049d63804156308016f93c9cf2497e8410942cfaadc7445056b179131
from sympy.polys.rings import ring from sympy.polys.domains import ZZ, QQ, AlgebraicField from sympy.polys.modulargcd import ( modgcd_univariate, modgcd_bivariate, _chinese_remainder_reconstruction_multivariate, modgcd_multivariate, _to_ZZ_poly, _to_ANP_poly, func_field_modgcd, _func_field_modgcd_m) from sympy.functions.elementary.miscellaneous import sqrt def test_modgcd_univariate_integers(): R, x = ring("x", ZZ) f, g = R.zero, R.zero assert modgcd_univariate(f, g) == (0, 0, 0) f, g = R.zero, x assert modgcd_univariate(f, g) == (x, 0, 1) assert modgcd_univariate(g, f) == (x, 1, 0) f, g = R.zero, -x assert modgcd_univariate(f, g) == (x, 0, -1) assert modgcd_univariate(g, f) == (x, -1, 0) f, g = 2*x, R(2) assert modgcd_univariate(f, g) == (2, x, 1) f, g = 2*x + 2, 6*x**2 - 6 assert modgcd_univariate(f, g) == (2*x + 2, 1, 3*x - 3) f = x**4 + 8*x**3 + 21*x**2 + 22*x + 8 g = x**3 + 6*x**2 + 11*x + 6 h = x**2 + 3*x + 2 cff = x**2 + 5*x + 4 cfg = x + 3 assert modgcd_univariate(f, g) == (h, cff, cfg) f = x**4 - 4 g = x**4 + 4*x**2 + 4 h = x**2 + 2 cff = x**2 - 2 cfg = x**2 + 2 assert modgcd_univariate(f, g) == (h, cff, cfg) f = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 g = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 h = 1 cff = f cfg = g assert modgcd_univariate(f, g) == (h, cff, cfg) f = - 352518131239247345597970242177235495263669787845475025293906825864749649589178600387510272*x**49 \ + 46818041807522713962450042363465092040687472354933295397472942006618953623327997952*x**42 \ + 378182690892293941192071663536490788434899030680411695933646320291525827756032*x**35 \ + 112806468807371824947796775491032386836656074179286744191026149539708928*x**28 \ - 12278371209708240950316872681744825481125965781519138077173235712*x**21 \ + 289127344604779611146960547954288113529690984687482920704*x**14 \ + 19007977035740498977629742919480623972236450681*x**7 \ + 311973482284542371301330321821976049 g = 365431878023781158602430064717380211405897160759702125019136*x**21 \ + 197599133478719444145775798221171663643171734081650688*x**14 \ - 9504116979659010018253915765478924103928886144*x**7 \ - 311973482284542371301330321821976049 assert modgcd_univariate(f, f.diff(x))[0] == g f = 1317378933230047068160*x + 2945748836994210856960 g = 120352542776360960*x + 269116466014453760 h = 120352542776360960*x + 269116466014453760 cff = 10946 cfg = 1 assert modgcd_univariate(f, g) == (h, cff, cfg) def test_modgcd_bivariate_integers(): R, x, y = ring("x,y", ZZ) f, g = R.zero, R.zero assert modgcd_bivariate(f, g) == (0, 0, 0) f, g = 2*x, R(2) assert modgcd_bivariate(f, g) == (2, x, 1) f, g = x + 2*y, x + y assert modgcd_bivariate(f, g) == (1, f, g) f, g = x**2 + 2*x*y + y**2, x**3 + y**3 assert modgcd_bivariate(f, g) == (x + y, x + y, x**2 - x*y + y**2) f, g = x*y**2 + 2*x*y + x, x*y**3 + x assert modgcd_bivariate(f, g) == (x*y + x, y + 1, y**2 - y + 1) f, g = x**2*y**2 + x**2*y + 1, x*y**2 + x*y + 1 assert modgcd_bivariate(f, g) == (1, f, g) f = 2*x*y**2 + 4*x*y + 2*x + y**2 + 2*y + 1 g = 2*x*y**3 + 2*x + y**3 + 1 assert modgcd_bivariate(f, g) == (2*x*y + 2*x + y + 1, y + 1, y**2 - y + 1) f, g = 2*x**2 + 4*x + 2, x + 1 assert modgcd_bivariate(f, g) == (x + 1, 2*x + 2, 1) f, g = x + 1, 2*x**2 + 4*x + 2 assert modgcd_bivariate(f, g) == (x + 1, 1, 2*x + 2) f = 2*x**2 + 4*x*y - 2*x - 4*y g = x**2 + x - 2 assert modgcd_bivariate(f, g) == (x - 1, 2*x + 4*y, x + 2) f = 2*x**2 + 2*x*y - 3*x - 3*y g = 4*x*y - 2*x + 4*y**2 - 2*y assert modgcd_bivariate(f, g) == (x + y, 2*x - 3, 4*y - 2) def test_chinese_remainder(): R, x, y = ring("x, y", ZZ) p, q = 3, 5 hp = x**3*y - x**2 - 1 hq = -x**3*y - 2*x*y**2 + 2 hpq = _chinese_remainder_reconstruction_multivariate(hp, hq, p, q) assert hpq.trunc_ground(p) == hp assert hpq.trunc_ground(q) == hq T, z = ring("z", R) p, q = 3, 7 hp = (x*y + 1)*z**2 + x hq = (x**2 - 3*y)*z + 2 hpq = _chinese_remainder_reconstruction_multivariate(hp, hq, p, q) assert hpq.trunc_ground(p) == hp assert hpq.trunc_ground(q) == hq def test_modgcd_multivariate_integers(): R, x, y = ring("x,y", ZZ) f, g = R.zero, R.zero assert modgcd_multivariate(f, g) == (0, 0, 0) f, g = 2*x**2 + 4*x + 2, x + 1 assert modgcd_multivariate(f, g) == (x + 1, 2*x + 2, 1) f, g = x + 1, 2*x**2 + 4*x + 2 assert modgcd_multivariate(f, g) == (x + 1, 1, 2*x + 2) f = 2*x**2 + 2*x*y - 3*x - 3*y g = 4*x*y - 2*x + 4*y**2 - 2*y assert modgcd_multivariate(f, g) == (x + y, 2*x - 3, 4*y - 2) f, g = x*y**2 + 2*x*y + x, x*y**3 + x assert modgcd_multivariate(f, g) == (x*y + x, y + 1, y**2 - y + 1) f, g = x**2*y**2 + x**2*y + 1, x*y**2 + x*y + 1 assert modgcd_multivariate(f, g) == (1, f, g) f = x**4 + 8*x**3 + 21*x**2 + 22*x + 8 g = x**3 + 6*x**2 + 11*x + 6 h = x**2 + 3*x + 2 cff = x**2 + 5*x + 4 cfg = x + 3 assert modgcd_multivariate(f, g) == (h, cff, cfg) R, x, y, z, u = ring("x,y,z,u", ZZ) f, g = x + y + z, -x - y - z - u assert modgcd_multivariate(f, g) == (1, f, g) f, g = u**2 + 2*u + 1, 2*u + 2 assert modgcd_multivariate(f, g) == (u + 1, u + 1, 2) f, g = z**2*u**2 + 2*z**2*u + z**2 + z*u + z, u**2 + 2*u + 1 h, cff, cfg = u + 1, z**2*u + z**2 + z, u + 1 assert modgcd_multivariate(f, g) == (h, cff, cfg) assert modgcd_multivariate(g, f) == (h, cfg, cff) R, x, y, z = ring("x,y,z", ZZ) f, g = x - y*z, x - y*z assert modgcd_multivariate(f, g) == (x - y*z, 1, 1) f, g, h = R.fateman_poly_F_1() H, cff, cfg = modgcd_multivariate(f, g) assert H == h and H*cff == f and H*cfg == g R, x, y, z, u, v = ring("x,y,z,u,v", ZZ) f, g, h = R.fateman_poly_F_1() H, cff, cfg = modgcd_multivariate(f, g) assert H == h and H*cff == f and H*cfg == g R, x, y, z, u, v, a, b = ring("x,y,z,u,v,a,b", ZZ) f, g, h = R.fateman_poly_F_1() H, cff, cfg = modgcd_multivariate(f, g) assert H == h and H*cff == f and H*cfg == g R, x, y, z, u, v, a, b, c, d = ring("x,y,z,u,v,a,b,c,d", ZZ) f, g, h = R.fateman_poly_F_1() H, cff, cfg = modgcd_multivariate(f, g) assert H == h and H*cff == f and H*cfg == g R, x, y, z = ring("x,y,z", ZZ) f, g, h = R.fateman_poly_F_2() H, cff, cfg = modgcd_multivariate(f, g) assert H == h and H*cff == f and H*cfg == g f, g, h = R.fateman_poly_F_3() H, cff, cfg = modgcd_multivariate(f, g) assert H == h and H*cff == f and H*cfg == g R, x, y, z, t = ring("x,y,z,t", ZZ) f, g, h = R.fateman_poly_F_3() H, cff, cfg = modgcd_multivariate(f, g) assert H == h and H*cff == f and H*cfg == g def test_to_ZZ_ANP_poly(): A = AlgebraicField(QQ, sqrt(2)) R, x = ring("x", A) f = x*(sqrt(2) + 1) T, x_, z_ = ring("x_, z_", ZZ) f_ = x_*z_ + x_ assert _to_ZZ_poly(f, T) == f_ assert _to_ANP_poly(f_, R) == f R, x, t, s = ring("x, t, s", A) f = x*t**2 + x*s + sqrt(2) D, t_, s_ = ring("t_, s_", ZZ) T, x_, z_ = ring("x_, z_", D) f_ = (t_**2 + s_)*x_ + z_ assert _to_ZZ_poly(f, T) == f_ assert _to_ANP_poly(f_, R) == f def test_modgcd_algebraic_field(): A = AlgebraicField(QQ, sqrt(2)) R, x = ring("x", A) one = A.one f, g = 2*x, R(2) assert func_field_modgcd(f, g) == (one, f, g) f, g = 2*x, R(sqrt(2)) assert func_field_modgcd(f, g) == (one, f, g) f, g = 2*x + 2, 6*x**2 - 6 assert func_field_modgcd(f, g) == (x + 1, R(2), 6*x - 6) R, x, y = ring("x, y", A) f, g = x + sqrt(2)*y, x + y assert func_field_modgcd(f, g) == (one, f, g) f, g = x*y + sqrt(2)*y**2, R(sqrt(2))*y assert func_field_modgcd(f, g) == (y, x + sqrt(2)*y, R(sqrt(2))) f, g = x**2 + 2*sqrt(2)*x*y + 2*y**2, x + sqrt(2)*y assert func_field_modgcd(f, g) == (g, g, one) A = AlgebraicField(QQ, sqrt(2), sqrt(3)) R, x, y, z = ring("x, y, z", A) h = x**2*y**7 + sqrt(6)/21*z f, g = h*(27*y**3 + 1), h*(y + x) assert func_field_modgcd(f, g) == (h, 27*y**3+1, y+x) h = x**13*y**3 + 1/2*x**10 + 1/sqrt(2) f, g = h*(x + 1), h*sqrt(2)/sqrt(3) assert func_field_modgcd(f, g) == (h, x + 1, R(sqrt(2)/sqrt(3))) A = AlgebraicField(QQ, sqrt(2)**(-1)*sqrt(3)) R, x = ring("x", A) f, g = x + 1, x - 1 assert func_field_modgcd(f, g) == (A.one, f, g) # when func_field_modgcd suppors function fields, this test can be changed def test_modgcd_func_field(): D, t = ring("t", ZZ) R, x, z = ring("x, z", D) minpoly = (z**2*t**2 + z**2*t - 1).drop(0) f, g = x + 1, x - 1 assert _func_field_modgcd_m(f, g, minpoly) == R.one
0c9bbc09c677c70c7c9e3a630de48eca1cb17aa6589a17dbedd912094fa597b6
"""Tests for Dixon's and Macaulay's classes. """ from sympy.matrices.dense import Matrix from sympy.polys.polytools import factor from sympy.core import symbols from sympy.tensor.indexed import IndexedBase from sympy.polys.multivariate_resultants import (DixonResultant, MacaulayResultant) c, d = symbols("a, b") x, y = symbols("x, y") p = c * x + y q = x + d * y dixon = DixonResultant(polynomials=[p, q], variables=[x, y]) macaulay = MacaulayResultant(polynomials=[p, q], variables=[x, y]) def test_dixon_resultant_init(): """Test init method of DixonResultant.""" a = IndexedBase("alpha") assert dixon.polynomials == [p, q] assert dixon.variables == [x, y] assert dixon.n == 2 assert dixon.m == 2 assert dixon.dummy_variables == [a[0], a[1]] def test_get_dixon_polynomial_numerical(): """Test Dixon's polynomial for a numerical example.""" a = IndexedBase("alpha") p = x + y q = x ** 2 + y **3 h = x ** 2 + y dixon = DixonResultant([p, q, h], [x, y]) polynomial = -x * y ** 2 * a[0] - x * y ** 2 * a[1] - x * y * a[0] \ * a[1] - x * y * a[1] ** 2 - x * a[0] * a[1] ** 2 + x * a[0] - \ y ** 2 * a[0] * a[1] + y ** 2 * a[1] - y * a[0] * a[1] ** 2 + y * \ a[1] ** 2 assert dixon.get_dixon_polynomial().as_expr().expand() == polynomial def test_get_max_degrees(): """Tests max degrees function.""" p = x + y q = x ** 2 + y **3 h = x ** 2 + y dixon = DixonResultant(polynomials=[p, q, h], variables=[x, y]) dixon_polynomial = dixon.get_dixon_polynomial() assert dixon.get_max_degrees(dixon_polynomial) == [1, 2] def test_get_dixon_matrix(): """Test Dixon's resultant for a numerical example.""" x, y = symbols('x, y') p = x + y q = x ** 2 + y ** 3 h = x ** 2 + y dixon = DixonResultant([p, q, h], [x, y]) polynomial = dixon.get_dixon_polynomial() assert dixon.get_dixon_matrix(polynomial).det() == 0 def test_get_dixon_matrix_example_two(): """Test Dixon's matrix for example from [Palancz08]_.""" x, y, z = symbols('x, y, z') f = x ** 2 + y ** 2 - 1 + z * 0 g = x ** 2 + z ** 2 - 1 + y * 0 h = y ** 2 + z ** 2 - 1 example_two = DixonResultant([f, g, h], [y, z]) poly = example_two.get_dixon_polynomial() matrix = example_two.get_dixon_matrix(poly) expr = 1 - 8 * x ** 2 + 24 * x ** 4 - 32 * x ** 6 + 16 * x ** 8 assert (matrix.det() - expr).expand() == 0 def test_KSY_precondition(): """Tests precondition for KSY Resultant.""" A, B, C = symbols('A, B, C') m1 = Matrix([[1, 2, 3], [4, 5, 12], [6, 7, 18]]) m2 = Matrix([[0, C**2], [-2 * C, -C ** 2]]) m3 = Matrix([[1, 0], [0, 1]]) m4 = Matrix([[A**2, 0, 1], [A, 1, 1 / A]]) m5 = Matrix([[5, 1], [2, B], [0, 1], [0, 0]]) assert dixon.KSY_precondition(m1) == False assert dixon.KSY_precondition(m2) == True assert dixon.KSY_precondition(m3) == True assert dixon.KSY_precondition(m4) == False assert dixon.KSY_precondition(m5) == True def test_delete_zero_rows_and_columns(): """Tests method for deleting rows and columns containing only zeros.""" A, B, C = symbols('A, B, C') m1 = Matrix([[0, 0], [0, 0], [1, 2]]) m2 = Matrix([[0, 1, 2], [0, 3, 4], [0, 5, 6]]) m3 = Matrix([[0, 0, 0, 0], [0, 1, 2, 0], [0, 3, 4, 0], [0, 0, 0, 0]]) m4 = Matrix([[1, 0, 2], [0, 0, 0], [3, 0, 4]]) m5 = Matrix([[0, 0, 0, 1], [0, 0, 0, 2], [0, 0, 0, 3], [0, 0, 0, 4]]) m6 = Matrix([[0, 0, A], [B, 0, 0], [0, 0, C]]) assert dixon.delete_zero_rows_and_columns(m1) == Matrix([[1, 2]]) assert dixon.delete_zero_rows_and_columns(m2) == Matrix([[1, 2], [3, 4], [5, 6]]) assert dixon.delete_zero_rows_and_columns(m3) == Matrix([[1, 2], [3, 4]]) assert dixon.delete_zero_rows_and_columns(m4) == Matrix([[1, 2], [3, 4]]) assert dixon.delete_zero_rows_and_columns(m5) == Matrix([[1], [2], [3], [4]]) assert dixon.delete_zero_rows_and_columns(m6) == Matrix([[0, A], [B, 0], [0, C]]) def test_product_leading_entries(): """Tests product of leading entries method.""" A, B = symbols('A, B') m1 = Matrix([[1, 2, 3], [0, 4, 5], [0, 0, 6]]) m2 = Matrix([[0, 0, 1], [2, 0, 3]]) m3 = Matrix([[0, 0, 0], [1, 2, 3], [0, 0, 0]]) m4 = Matrix([[0, 0, A], [1, 2, 3], [B, 0, 0]]) assert dixon.product_leading_entries(m1) == 24 assert dixon.product_leading_entries(m2) == 2 assert dixon.product_leading_entries(m3) == 1 assert dixon.product_leading_entries(m4) == A * B def test_get_KSY_Dixon_resultant_example_one(): """Tests the KSY Dixon resultant for example one""" x, y, z = symbols('x, y, z') p = x * y * z q = x**2 - z**2 h = x + y + z dixon = DixonResultant([p, q, h], [x, y]) dixon_poly = dixon.get_dixon_polynomial() dixon_matrix = dixon.get_dixon_matrix(dixon_poly) D = dixon.get_KSY_Dixon_resultant(dixon_matrix) assert D == -z**3 def test_get_KSY_Dixon_resultant_example_two(): """Tests the KSY Dixon resultant for example two""" x, y, A = symbols('x, y, A') p = x * y + x * A + x - A**2 - A + y**2 + y q = x**2 + x * A - x + x * y + y * A - y h = x**2 + x * y + 2 * x - x * A - y * A - 2 * A dixon = DixonResultant([p, q, h], [x, y]) dixon_poly = dixon.get_dixon_polynomial() dixon_matrix = dixon.get_dixon_matrix(dixon_poly) D = factor(dixon.get_KSY_Dixon_resultant(dixon_matrix)) assert D == -8*A*(A - 1)*(A + 2)*(2*A - 1)**2 def test_macaulay_resultant_init(): """Test init method of MacaulayResultant.""" assert macaulay.polynomials == [p, q] assert macaulay.variables == [x, y] assert macaulay.n == 2 assert macaulay.degrees == [1, 1] assert macaulay.degree_m == 1 assert macaulay.monomials_size == 2 def test_get_degree_m(): assert macaulay._get_degree_m() == 1 def test_get_size(): assert macaulay.get_size() == 2 def test_macaulay_example_one(): """Tests the Macaulay for example from [Bruce97]_""" x, y, z = symbols('x, y, z') a_1_1, a_1_2, a_1_3 = symbols('a_1_1, a_1_2, a_1_3') a_2_2, a_2_3, a_3_3 = symbols('a_2_2, a_2_3, a_3_3') b_1_1, b_1_2, b_1_3 = symbols('b_1_1, b_1_2, b_1_3') b_2_2, b_2_3, b_3_3 = symbols('b_2_2, b_2_3, b_3_3') c_1, c_2, c_3 = symbols('c_1, c_2, c_3') f_1 = a_1_1 * x ** 2 + a_1_2 * x * y + a_1_3 * x * z + \ a_2_2 * y ** 2 + a_2_3 * y * z + a_3_3 * z ** 2 f_2 = b_1_1 * x ** 2 + b_1_2 * x * y + b_1_3 * x * z + \ b_2_2 * y ** 2 + b_2_3 * y * z + b_3_3 * z ** 2 f_3 = c_1 * x + c_2 * y + c_3 * z mac = MacaulayResultant([f_1, f_2, f_3], [x, y, z]) assert mac.degrees == [2, 2, 1] assert mac.degree_m == 3 assert mac.monomial_set == [x ** 3, x ** 2 * y, x ** 2 * z, x * y ** 2, x * y * z, x * z ** 2, y ** 3, y ** 2 *z, y * z ** 2, z ** 3] assert mac.monomials_size == 10 assert mac.get_row_coefficients() == [[x, y, z], [x, y, z], [x * y, x * z, y * z, z ** 2]] matrix = mac.get_matrix() assert matrix.shape == (mac.monomials_size, mac.monomials_size) assert mac.get_submatrix(matrix) == Matrix([[a_1_1, a_2_2], [b_1_1, b_2_2]]) def test_macaulay_example_two(): """Tests the Macaulay formulation for example from [Stiller96]_.""" x, y, z = symbols('x, y, z') a_0, a_1, a_2 = symbols('a_0, a_1, a_2') b_0, b_1, b_2 = symbols('b_0, b_1, b_2') c_0, c_1, c_2, c_3, c_4 = symbols('c_0, c_1, c_2, c_3, c_4') f = a_0 * y - a_1 * x + a_2 * z g = b_1 * x ** 2 + b_0 * y ** 2 - b_2 * z ** 2 h = c_0 * y - c_1 * x ** 3 + c_2 * x ** 2 * z - c_3 * x * z ** 2 + \ c_4 * z ** 3 mac = MacaulayResultant([f, g, h], [x, y, z]) assert mac.degrees == [1, 2, 3] assert mac.degree_m == 4 assert mac.monomials_size == 15 assert len(mac.get_row_coefficients()) == mac.n matrix = mac.get_matrix() assert matrix.shape == (mac.monomials_size, mac.monomials_size) assert mac.get_submatrix(matrix) == Matrix([[-a_1, a_0, a_2, 0], [0, -a_1, 0, 0], [0, 0, -a_1, 0], [0, 0, 0, -a_1]])
5352c18c0f3cd681b803ca0c5ea65ed2c678da9987ed8a51fd54898c1359cfec
"""Tests for tools for constructing domains for expressions. """ from sympy.polys.constructor import construct_domain from sympy.polys.domains import ZZ, QQ, ZZ_I, QQ_I, RR, CC, EX from sympy.polys.domains.realfield import RealField from sympy.polys.domains.complexfield import ComplexField from sympy.core import (Catalan, GoldenRatio) from sympy.core.numbers import (E, Float, I, Rational, pi) from sympy.core.singleton import S from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin from sympy.abc import x, y def test_construct_domain(): assert construct_domain([1, 2, 3]) == (ZZ, [ZZ(1), ZZ(2), ZZ(3)]) assert construct_domain([1, 2, 3], field=True) == (QQ, [QQ(1), QQ(2), QQ(3)]) assert construct_domain([S.One, S(2), S(3)]) == (ZZ, [ZZ(1), ZZ(2), ZZ(3)]) assert construct_domain([S.One, S(2), S(3)], field=True) == (QQ, [QQ(1), QQ(2), QQ(3)]) assert construct_domain([S.Half, S(2)]) == (QQ, [QQ(1, 2), QQ(2)]) result = construct_domain([3.14, 1, S.Half]) assert isinstance(result[0], RealField) assert result[1] == [RR(3.14), RR(1.0), RR(0.5)] result = construct_domain([3.14, I, S.Half]) assert isinstance(result[0], ComplexField) assert result[1] == [CC(3.14), CC(1.0j), CC(0.5)] assert construct_domain([1.0+I]) == (CC, [CC(1.0, 1.0)]) assert construct_domain([2.0+3.0*I]) == (CC, [CC(2.0, 3.0)]) assert construct_domain([1, I]) == (ZZ_I, [ZZ_I(1, 0), ZZ_I(0, 1)]) assert construct_domain([1, I/2]) == (QQ_I, [QQ_I(1, 0), QQ_I(0, S.Half)]) assert construct_domain([3.14, sqrt(2)], extension=None) == (EX, [EX(3.14), EX(sqrt(2))]) assert construct_domain([3.14, sqrt(2)], extension=True) == (EX, [EX(3.14), EX(sqrt(2))]) assert construct_domain([1, sqrt(2)], extension=None) == (EX, [EX(1), EX(sqrt(2))]) assert construct_domain([x, sqrt(x)]) == (EX, [EX(x), EX(sqrt(x))]) assert construct_domain([x, sqrt(x), sqrt(y)]) == (EX, [EX(x), EX(sqrt(x)), EX(sqrt(y))]) alg = QQ.algebraic_field(sqrt(2)) assert construct_domain([7, S.Half, sqrt(2)], extension=True) == \ (alg, [alg.convert(7), alg.convert(S.Half), alg.convert(sqrt(2))]) alg = QQ.algebraic_field(sqrt(2) + sqrt(3)) assert construct_domain([7, sqrt(2), sqrt(3)], extension=True) == \ (alg, [alg.convert(7), alg.convert(sqrt(2)), alg.convert(sqrt(3))]) dom = ZZ[x] assert construct_domain([2*x, 3]) == \ (dom, [dom.convert(2*x), dom.convert(3)]) dom = ZZ[x, y] assert construct_domain([2*x, 3*y]) == \ (dom, [dom.convert(2*x), dom.convert(3*y)]) dom = QQ[x] assert construct_domain([x/2, 3]) == \ (dom, [dom.convert(x/2), dom.convert(3)]) dom = QQ[x, y] assert construct_domain([x/2, 3*y]) == \ (dom, [dom.convert(x/2), dom.convert(3*y)]) dom = ZZ_I[x] assert construct_domain([2*x, I]) == \ (dom, [dom.convert(2*x), dom.convert(I)]) dom = ZZ_I[x, y] assert construct_domain([2*x, I*y]) == \ (dom, [dom.convert(2*x), dom.convert(I*y)]) dom = QQ_I[x] assert construct_domain([x/2, I]) == \ (dom, [dom.convert(x/2), dom.convert(I)]) dom = QQ_I[x, y] assert construct_domain([x/2, I*y]) == \ (dom, [dom.convert(x/2), dom.convert(I*y)]) dom = RR[x] assert construct_domain([x/2, 3.5]) == \ (dom, [dom.convert(x/2), dom.convert(3.5)]) dom = RR[x, y] assert construct_domain([x/2, 3.5*y]) == \ (dom, [dom.convert(x/2), dom.convert(3.5*y)]) dom = CC[x] assert construct_domain([I*x/2, 3.5]) == \ (dom, [dom.convert(I*x/2), dom.convert(3.5)]) dom = CC[x, y] assert construct_domain([I*x/2, 3.5*y]) == \ (dom, [dom.convert(I*x/2), dom.convert(3.5*y)]) dom = CC[x] assert construct_domain([x/2, I*3.5]) == \ (dom, [dom.convert(x/2), dom.convert(I*3.5)]) dom = CC[x, y] assert construct_domain([x/2, I*3.5*y]) == \ (dom, [dom.convert(x/2), dom.convert(I*3.5*y)]) dom = ZZ.frac_field(x) assert construct_domain([2/x, 3]) == \ (dom, [dom.convert(2/x), dom.convert(3)]) dom = ZZ.frac_field(x, y) assert construct_domain([2/x, 3*y]) == \ (dom, [dom.convert(2/x), dom.convert(3*y)]) dom = RR.frac_field(x) assert construct_domain([2/x, 3.5]) == \ (dom, [dom.convert(2/x), dom.convert(3.5)]) dom = RR.frac_field(x, y) assert construct_domain([2/x, 3.5*y]) == \ (dom, [dom.convert(2/x), dom.convert(3.5*y)]) dom = RealField(prec=336)[x] assert construct_domain([pi.evalf(100)*x]) == \ (dom, [dom.convert(pi.evalf(100)*x)]) assert construct_domain(2) == (ZZ, ZZ(2)) assert construct_domain(S(2)/3) == (QQ, QQ(2, 3)) assert construct_domain(Rational(2, 3)) == (QQ, QQ(2, 3)) assert construct_domain({}) == (ZZ, {}) def test_complex_exponential(): w = exp(-I*2*pi/3, evaluate=False) alg = QQ.algebraic_field(w) assert construct_domain([w**2, w, 1], extension=True) == ( alg, [alg.convert(w**2), alg.convert(w), alg.convert(1)] ) def test_composite_option(): assert construct_domain({(1,): sin(y)}, composite=False) == \ (EX, {(1,): EX(sin(y))}) assert construct_domain({(1,): y}, composite=False) == \ (EX, {(1,): EX(y)}) assert construct_domain({(1, 1): 1}, composite=False) == \ (ZZ, {(1, 1): 1}) assert construct_domain({(1, 0): y}, composite=False) == \ (EX, {(1, 0): EX(y)}) def test_precision(): f1 = Float("1.01") f2 = Float("1.0000000000000000000001") for u in [1, 1e-2, 1e-6, 1e-13, 1e-14, 1e-16, 1e-20, 1e-100, 1e-300, f1, f2]: result = construct_domain([u]) v = float(result[1][0]) assert abs(u - v) / u < 1e-14 # Test relative accuracy result = construct_domain([f1]) y = result[1][0] assert y-1 > 1e-50 result = construct_domain([f2]) y = result[1][0] assert y-1 > 1e-50 def test_issue_11538(): for n in [E, pi, Catalan]: assert construct_domain(n)[0] == ZZ[n] assert construct_domain(x + n)[0] == ZZ[x, n] assert construct_domain(GoldenRatio)[0] == EX assert construct_domain(x + GoldenRatio)[0] == EX
efcc65aefcef38ddb4e3b8ff0de43413c041660e99d64a09ce4b23e6b41a87d0
"""Tests for algorithms for partial fraction decomposition of rational functions. """ from sympy.polys.partfrac import ( apart_undetermined_coeffs, apart, apart_list, assemble_partfrac_list ) from sympy.core.expr import Expr from sympy.core.function import Lambda from sympy.core.numbers import (E, I, Rational, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Dummy, Symbol) from sympy.functions.elementary.miscellaneous import sqrt from sympy.matrices.dense import Matrix from sympy.polys.polytools import (Poly, factor) from sympy.polys.rationaltools import together from sympy.polys.rootoftools import RootSum from sympy.testing.pytest import raises, XFAIL from sympy.abc import x, y, a, b, c def test_apart(): assert apart(1) == 1 assert apart(1, x) == 1 f, g = (x**2 + 1)/(x + 1), 2/(x + 1) + x - 1 assert apart(f, full=False) == g assert apart(f, full=True) == g f, g = 1/(x + 2)/(x + 1), 1/(1 + x) - 1/(2 + x) assert apart(f, full=False) == g assert apart(f, full=True) == g f, g = 1/(x + 1)/(x + 5), -1/(5 + x)/4 + 1/(1 + x)/4 assert apart(f, full=False) == g assert apart(f, full=True) == g assert apart((E*x + 2)/(x - pi)*(x - 1), x) == \ 2 - E + E*pi + E*x + (E*pi + 2)*(pi - 1)/(x - pi) assert apart(Eq((x**2 + 1)/(x + 1), x), x) == Eq(x - 1 + 2/(x + 1), x) assert apart(x/2, y) == x/2 f, g = (x+y)/(2*x - y), Rational(3, 2)*y/(2*x - y) + S.Half assert apart(f, x, full=False) == g assert apart(f, x, full=True) == g f, g = (x+y)/(2*x - y), 3*x/(2*x - y) - 1 assert apart(f, y, full=False) == g assert apart(f, y, full=True) == g raises(NotImplementedError, lambda: apart(1/(x + 1)/(y + 2))) def test_apart_matrix(): M = Matrix(2, 2, lambda i, j: 1/(x + i + 1)/(x + j)) assert apart(M) == Matrix([ [1/x - 1/(x + 1), (x + 1)**(-2)], [1/(2*x) - (S.Half)/(x + 2), 1/(x + 1) - 1/(x + 2)], ]) def test_apart_symbolic(): f = a*x**4 + (2*b + 2*a*c)*x**3 + (4*b*c - a**2 + a*c**2)*x**2 + \ (-2*a*b + 2*b*c**2)*x - b**2 g = a**2*x**4 + (2*a*b + 2*c*a**2)*x**3 + (4*a*b*c + b**2 + a**2*c**2)*x**2 + (2*c*b**2 + 2*a*b*c**2)*x + b**2*c**2 assert apart(f/g, x) == 1/a - 1/(x + c)**2 - b**2/(a*(a*x + b)**2) assert apart(1/((x + a)*(x + b)*(x + c)), x) == \ 1/((a - c)*(b - c)*(c + x)) - 1/((a - b)*(b - c)*(b + x)) + \ 1/((a - b)*(a - c)*(a + x)) def _make_extension_example(): # https://github.com/sympy/sympy/issues/18531 from sympy.core import Mul def mul2(expr): # 2-arg mul hack... return Mul(2, expr, evaluate=False) f = ((x**2 + 1)**3/((x - 1)**2*(x + 1)**2*(-x**2 + 2*x + 1)*(x**2 + 2*x - 1))) g = (1/mul2(x - sqrt(2) + 1) - 1/mul2(x - sqrt(2) - 1) + 1/mul2(x + 1 + sqrt(2)) - 1/mul2(x - 1 + sqrt(2)) + 1/mul2((x + 1)**2) + 1/mul2((x - 1)**2)) return f, g def test_apart_extension(): f = 2/(x**2 + 1) g = I/(x + I) - I/(x - I) assert apart(f, extension=I) == g assert apart(f, gaussian=True) == g f = x/((x - 2)*(x + I)) assert factor(together(apart(f)).expand()) == f f, g = _make_extension_example() # XXX: Only works with dotprodsimp. See test_apart_extension_xfail below from sympy.matrices import dotprodsimp with dotprodsimp(True): assert apart(f, x, extension={sqrt(2)}) == g def test_apart_extension_xfail(): f, g = _make_extension_example() assert apart(f, x, extension={sqrt(2)}) == g def test_apart_full(): f = 1/(x**2 + 1) assert apart(f, full=False) == f assert apart(f, full=True).dummy_eq( -RootSum(x**2 + 1, Lambda(a, a/(x - a)), auto=False)/2) f = 1/(x**3 + x + 1) assert apart(f, full=False) == f assert apart(f, full=True).dummy_eq( RootSum(x**3 + x + 1, Lambda(a, (a**2*Rational(6, 31) - a*Rational(9, 31) + Rational(4, 31))/(x - a)), auto=False)) f = 1/(x**5 + 1) assert apart(f, full=False) == \ (Rational(-1, 5))*((x**3 - 2*x**2 + 3*x - 4)/(x**4 - x**3 + x**2 - x + 1)) + (Rational(1, 5))/(x + 1) assert apart(f, full=True).dummy_eq( -RootSum(x**4 - x**3 + x**2 - x + 1, Lambda(a, a/(x - a)), auto=False)/5 + (Rational(1, 5))/(x + 1)) def test_apart_undetermined_coeffs(): p = Poly(2*x - 3) q = Poly(x**9 - x**8 - x**6 + x**5 - 2*x**2 + 3*x - 1) r = (-x**7 - x**6 - x**5 + 4)/(x**8 - x**5 - 2*x + 1) + 1/(x - 1) assert apart_undetermined_coeffs(p, q) == r p = Poly(1, x, domain='ZZ[a,b]') q = Poly((x + a)*(x + b), x, domain='ZZ[a,b]') r = 1/((a - b)*(b + x)) - 1/((a - b)*(a + x)) assert apart_undetermined_coeffs(p, q) == r def test_apart_list(): from sympy.utilities.iterables import numbered_symbols def dummy_eq(i, j): if type(i) in (list, tuple): return all(dummy_eq(i, j) for i, j in zip(i, j)) return i == j or i.dummy_eq(j) w0, w1, w2 = Symbol("w0"), Symbol("w1"), Symbol("w2") _a = Dummy("a") f = (-2*x - 2*x**2) / (3*x**2 - 6*x) got = apart_list(f, x, dummies=numbered_symbols("w")) ans = (-1, Poly(Rational(2, 3), x, domain='QQ'), [(Poly(w0 - 2, w0, domain='ZZ'), Lambda(_a, 2), Lambda(_a, -_a + x), 1)]) assert dummy_eq(got, ans) got = apart_list(2/(x**2-2), x, dummies=numbered_symbols("w")) ans = (1, Poly(0, x, domain='ZZ'), [(Poly(w0**2 - 2, w0, domain='ZZ'), Lambda(_a, _a/2), Lambda(_a, -_a + x), 1)]) assert dummy_eq(got, ans) f = 36 / (x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2) got = apart_list(f, x, dummies=numbered_symbols("w")) ans = (1, Poly(0, x, domain='ZZ'), [(Poly(w0 - 2, w0, domain='ZZ'), Lambda(_a, 4), Lambda(_a, -_a + x), 1), (Poly(w1**2 - 1, w1, domain='ZZ'), Lambda(_a, -3*_a - 6), Lambda(_a, -_a + x), 2), (Poly(w2 + 1, w2, domain='ZZ'), Lambda(_a, -4), Lambda(_a, -_a + x), 1)]) assert dummy_eq(got, ans) def test_assemble_partfrac_list(): f = 36 / (x**5 - 2*x**4 - 2*x**3 + 4*x**2 + x - 2) pfd = apart_list(f) assert assemble_partfrac_list(pfd) == -4/(x + 1) - 3/(x + 1)**2 - 9/(x - 1)**2 + 4/(x - 2) a = Dummy("a") pfd = (1, Poly(0, x, domain='ZZ'), [([sqrt(2),-sqrt(2)], Lambda(a, a/2), Lambda(a, -a + x), 1)]) assert assemble_partfrac_list(pfd) == -1/(sqrt(2)*(x + sqrt(2))) + 1/(sqrt(2)*(x - sqrt(2))) @XFAIL def test_noncommutative_pseudomultivariate(): # apart doesn't go inside noncommutative expressions class foo(Expr): is_commutative=False e = x/(x + x*y) c = 1/(1 + y) assert apart(e + foo(e)) == c + foo(c) assert apart(e*foo(e)) == c*foo(c) def test_noncommutative(): class foo(Expr): is_commutative=False e = x/(x + x*y) c = 1/(1 + y) assert apart(e + foo()) == c + foo() def test_issue_5798(): assert apart( 2*x/(x**2 + 1) - (x - 1)/(2*(x**2 + 1)) + 1/(2*(x + 1)) - 2/x) == \ (3*x + 1)/(x**2 + 1)/2 + 1/(x + 1)/2 - 2/x
40cd58b7484e1c19d44ef767d7868545475f31013d3f6ab51e9cdeb9dfa7f9db
"""Tests for dense recursive polynomials' tools. """ from sympy.polys.densebasic import ( dup_normal, dmp_normal, dup_from_raw_dict, dmp_convert, dmp_swap, ) from sympy.polys.densearith import dmp_mul_ground from sympy.polys.densetools import ( dup_clear_denoms, dmp_clear_denoms, dup_integrate, dmp_integrate, dmp_integrate_in, dup_diff, dmp_diff, dmp_diff_in, dup_eval, dmp_eval, dmp_eval_in, dmp_eval_tail, dmp_diff_eval_in, dup_trunc, dmp_trunc, dmp_ground_trunc, dup_monic, dmp_ground_monic, dup_content, dmp_ground_content, dup_primitive, dmp_ground_primitive, dup_extract, dmp_ground_extract, dup_real_imag, dup_mirror, dup_scale, dup_shift, dup_transform, dup_compose, dmp_compose, dup_decompose, dmp_lift, dup_sign_variations, dup_revert, dmp_revert, ) from sympy.polys.polyclasses import ANP from sympy.polys.polyerrors import ( MultivariatePolynomialError, ExactQuotientFailed, NotReversible, DomainError, ) from sympy.polys.specialpolys import f_polys from sympy.polys.domains import FF, ZZ, QQ, EX from sympy.polys.rings import ring from sympy.core.numbers import I from sympy.core.singleton import S from sympy.functions.elementary.trigonometric import sin from sympy.abc import x from sympy.testing.pytest import raises f_0, f_1, f_2, f_3, f_4, f_5, f_6 = [ f.to_dense() for f in f_polys() ] def test_dup_integrate(): assert dup_integrate([], 1, QQ) == [] assert dup_integrate([], 2, QQ) == [] assert dup_integrate([QQ(1)], 1, QQ) == [QQ(1), QQ(0)] assert dup_integrate([QQ(1)], 2, QQ) == [QQ(1, 2), QQ(0), QQ(0)] assert dup_integrate([QQ(1), QQ(2), QQ(3)], 0, QQ) == \ [QQ(1), QQ(2), QQ(3)] assert dup_integrate([QQ(1), QQ(2), QQ(3)], 1, QQ) == \ [QQ(1, 3), QQ(1), QQ(3), QQ(0)] assert dup_integrate([QQ(1), QQ(2), QQ(3)], 2, QQ) == \ [QQ(1, 12), QQ(1, 3), QQ(3, 2), QQ(0), QQ(0)] assert dup_integrate([QQ(1), QQ(2), QQ(3)], 3, QQ) == \ [QQ(1, 60), QQ(1, 12), QQ(1, 2), QQ(0), QQ(0), QQ(0)] assert dup_integrate(dup_from_raw_dict({29: QQ(17)}, QQ), 3, QQ) == \ dup_from_raw_dict({32: QQ(17, 29760)}, QQ) assert dup_integrate(dup_from_raw_dict({29: QQ(17), 5: QQ(1, 2)}, QQ), 3, QQ) == \ dup_from_raw_dict({32: QQ(17, 29760), 8: QQ(1, 672)}, QQ) def test_dmp_integrate(): assert dmp_integrate([[[]]], 1, 2, QQ) == [[[]]] assert dmp_integrate([[[]]], 2, 2, QQ) == [[[]]] assert dmp_integrate([[[QQ(1)]]], 1, 2, QQ) == [[[QQ(1)]], [[]]] assert dmp_integrate([[[QQ(1)]]], 2, 2, QQ) == [[[QQ(1, 2)]], [[]], [[]]] assert dmp_integrate([[QQ(1)], [QQ(2)], [QQ(3)]], 0, 1, QQ) == \ [[QQ(1)], [QQ(2)], [QQ(3)]] assert dmp_integrate([[QQ(1)], [QQ(2)], [QQ(3)]], 1, 1, QQ) == \ [[QQ(1, 3)], [QQ(1)], [QQ(3)], []] assert dmp_integrate([[QQ(1)], [QQ(2)], [QQ(3)]], 2, 1, QQ) == \ [[QQ(1, 12)], [QQ(1, 3)], [QQ(3, 2)], [], []] assert dmp_integrate([[QQ(1)], [QQ(2)], [QQ(3)]], 3, 1, QQ) == \ [[QQ(1, 60)], [QQ(1, 12)], [QQ(1, 2)], [], [], []] def test_dmp_integrate_in(): f = dmp_convert(f_6, 3, ZZ, QQ) assert dmp_integrate_in(f, 2, 1, 3, QQ) == \ dmp_swap( dmp_integrate(dmp_swap(f, 0, 1, 3, QQ), 2, 3, QQ), 0, 1, 3, QQ) assert dmp_integrate_in(f, 3, 1, 3, QQ) == \ dmp_swap( dmp_integrate(dmp_swap(f, 0, 1, 3, QQ), 3, 3, QQ), 0, 1, 3, QQ) assert dmp_integrate_in(f, 2, 2, 3, QQ) == \ dmp_swap( dmp_integrate(dmp_swap(f, 0, 2, 3, QQ), 2, 3, QQ), 0, 2, 3, QQ) assert dmp_integrate_in(f, 3, 2, 3, QQ) == \ dmp_swap( dmp_integrate(dmp_swap(f, 0, 2, 3, QQ), 3, 3, QQ), 0, 2, 3, QQ) def test_dup_diff(): assert dup_diff([], 1, ZZ) == [] assert dup_diff([7], 1, ZZ) == [] assert dup_diff([2, 7], 1, ZZ) == [2] assert dup_diff([1, 2, 1], 1, ZZ) == [2, 2] assert dup_diff([1, 2, 3, 4], 1, ZZ) == [3, 4, 3] assert dup_diff([1, -1, 0, 0, 2], 1, ZZ) == [4, -3, 0, 0] f = dup_normal([17, 34, 56, -345, 23, 76, 0, 0, 12, 3, 7], ZZ) assert dup_diff(f, 0, ZZ) == f assert dup_diff(f, 1, ZZ) == [170, 306, 448, -2415, 138, 380, 0, 0, 24, 3] assert dup_diff(f, 2, ZZ) == dup_diff(dup_diff(f, 1, ZZ), 1, ZZ) assert dup_diff( f, 3, ZZ) == dup_diff(dup_diff(dup_diff(f, 1, ZZ), 1, ZZ), 1, ZZ) K = FF(3) f = dup_normal([17, 34, 56, -345, 23, 76, 0, 0, 12, 3, 7], K) assert dup_diff(f, 1, K) == dup_normal([2, 0, 1, 0, 0, 2, 0, 0, 0, 0], K) assert dup_diff(f, 2, K) == dup_normal([1, 0, 0, 2, 0, 0, 0], K) assert dup_diff(f, 3, K) == dup_normal([], K) assert dup_diff(f, 0, K) == f assert dup_diff(f, 2, K) == dup_diff(dup_diff(f, 1, K), 1, K) assert dup_diff( f, 3, K) == dup_diff(dup_diff(dup_diff(f, 1, K), 1, K), 1, K) def test_dmp_diff(): assert dmp_diff([], 1, 0, ZZ) == [] assert dmp_diff([[]], 1, 1, ZZ) == [[]] assert dmp_diff([[[]]], 1, 2, ZZ) == [[[]]] assert dmp_diff([[[1], [2]]], 1, 2, ZZ) == [[[]]] assert dmp_diff([[[1]], [[]]], 1, 2, ZZ) == [[[1]]] assert dmp_diff([[[3]], [[1]], [[]]], 1, 2, ZZ) == [[[6]], [[1]]] assert dmp_diff([1, -1, 0, 0, 2], 1, 0, ZZ) == \ dup_diff([1, -1, 0, 0, 2], 1, ZZ) assert dmp_diff(f_6, 0, 3, ZZ) == f_6 assert dmp_diff(f_6, 1, 3, ZZ) == [[[[8460]], [[]]], [[[135, 0, 0], [], [], [-135, 0, 0]]], [[[]]], [[[-423]], [[-47]], [[]], [[141], [], [94, 0], []], [[]]]] assert dmp_diff( f_6, 2, 3, ZZ) == dmp_diff(dmp_diff(f_6, 1, 3, ZZ), 1, 3, ZZ) assert dmp_diff(f_6, 3, 3, ZZ) == dmp_diff( dmp_diff(dmp_diff(f_6, 1, 3, ZZ), 1, 3, ZZ), 1, 3, ZZ) K = FF(23) F_6 = dmp_normal(f_6, 3, K) assert dmp_diff(F_6, 0, 3, K) == F_6 assert dmp_diff(F_6, 1, 3, K) == dmp_diff(F_6, 1, 3, K) assert dmp_diff(F_6, 2, 3, K) == dmp_diff(dmp_diff(F_6, 1, 3, K), 1, 3, K) assert dmp_diff(F_6, 3, 3, K) == dmp_diff( dmp_diff(dmp_diff(F_6, 1, 3, K), 1, 3, K), 1, 3, K) def test_dmp_diff_in(): assert dmp_diff_in(f_6, 2, 1, 3, ZZ) == \ dmp_swap(dmp_diff(dmp_swap(f_6, 0, 1, 3, ZZ), 2, 3, ZZ), 0, 1, 3, ZZ) assert dmp_diff_in(f_6, 3, 1, 3, ZZ) == \ dmp_swap(dmp_diff(dmp_swap(f_6, 0, 1, 3, ZZ), 3, 3, ZZ), 0, 1, 3, ZZ) assert dmp_diff_in(f_6, 2, 2, 3, ZZ) == \ dmp_swap(dmp_diff(dmp_swap(f_6, 0, 2, 3, ZZ), 2, 3, ZZ), 0, 2, 3, ZZ) assert dmp_diff_in(f_6, 3, 2, 3, ZZ) == \ dmp_swap(dmp_diff(dmp_swap(f_6, 0, 2, 3, ZZ), 3, 3, ZZ), 0, 2, 3, ZZ) def test_dup_eval(): assert dup_eval([], 7, ZZ) == 0 assert dup_eval([1, 2], 0, ZZ) == 2 assert dup_eval([1, 2, 3], 7, ZZ) == 66 def test_dmp_eval(): assert dmp_eval([], 3, 0, ZZ) == 0 assert dmp_eval([[]], 3, 1, ZZ) == [] assert dmp_eval([[[]]], 3, 2, ZZ) == [[]] assert dmp_eval([[1, 2]], 0, 1, ZZ) == [1, 2] assert dmp_eval([[[1]]], 3, 2, ZZ) == [[1]] assert dmp_eval([[[1, 2]]], 3, 2, ZZ) == [[1, 2]] assert dmp_eval([[3, 2], [1, 2]], 3, 1, ZZ) == [10, 8] assert dmp_eval([[[3, 2]], [[1, 2]]], 3, 2, ZZ) == [[10, 8]] def test_dmp_eval_in(): assert dmp_eval_in( f_6, -2, 1, 3, ZZ) == dmp_eval(dmp_swap(f_6, 0, 1, 3, ZZ), -2, 3, ZZ) assert dmp_eval_in( f_6, 7, 1, 3, ZZ) == dmp_eval(dmp_swap(f_6, 0, 1, 3, ZZ), 7, 3, ZZ) assert dmp_eval_in(f_6, -2, 2, 3, ZZ) == dmp_swap( dmp_eval(dmp_swap(f_6, 0, 2, 3, ZZ), -2, 3, ZZ), 0, 1, 2, ZZ) assert dmp_eval_in(f_6, 7, 2, 3, ZZ) == dmp_swap( dmp_eval(dmp_swap(f_6, 0, 2, 3, ZZ), 7, 3, ZZ), 0, 1, 2, ZZ) f = [[[int(45)]], [[]], [[]], [[int(-9)], [-1], [], [int(3), int(0), int(10), int(0)]]] assert dmp_eval_in(f, -2, 2, 2, ZZ) == \ [[45], [], [], [-9, -1, 0, -44]] def test_dmp_eval_tail(): assert dmp_eval_tail([[]], [1], 1, ZZ) == [] assert dmp_eval_tail([[[]]], [1], 2, ZZ) == [[]] assert dmp_eval_tail([[[]]], [1, 2], 2, ZZ) == [] assert dmp_eval_tail(f_0, [], 2, ZZ) == f_0 assert dmp_eval_tail(f_0, [1, -17, 8], 2, ZZ) == 84496 assert dmp_eval_tail(f_0, [-17, 8], 2, ZZ) == [-1409, 3, 85902] assert dmp_eval_tail(f_0, [8], 2, ZZ) == [[83, 2], [3], [302, 81, 1]] assert dmp_eval_tail(f_1, [-17, 8], 2, ZZ) == [-136, 15699, 9166, -27144] assert dmp_eval_tail( f_2, [-12, 3], 2, ZZ) == [-1377, 0, -702, -1224, 0, -624] assert dmp_eval_tail( f_3, [-12, 3], 2, ZZ) == [144, 82, -5181, -28872, -14868, -540] assert dmp_eval_tail( f_4, [25, -1], 2, ZZ) == [152587890625, 9765625, -59605407714843750, -3839159765625, -1562475, 9536712644531250, 610349546750, -4, 24414375000, 1562520] assert dmp_eval_tail(f_5, [25, -1], 2, ZZ) == [-1, -78, -2028, -17576] assert dmp_eval_tail(f_6, [0, 2, 4], 3, ZZ) == [5040, 0, 0, 4480] def test_dmp_diff_eval_in(): assert dmp_diff_eval_in(f_6, 2, 7, 1, 3, ZZ) == \ dmp_eval(dmp_diff(dmp_swap(f_6, 0, 1, 3, ZZ), 2, 3, ZZ), 7, 3, ZZ) def test_dup_revert(): f = [-QQ(1, 720), QQ(0), QQ(1, 24), QQ(0), -QQ(1, 2), QQ(0), QQ(1)] g = [QQ(61, 720), QQ(0), QQ(5, 24), QQ(0), QQ(1, 2), QQ(0), QQ(1)] assert dup_revert(f, 8, QQ) == g raises(NotReversible, lambda: dup_revert([QQ(1), QQ(0)], 3, QQ)) def test_dmp_revert(): f = [-QQ(1, 720), QQ(0), QQ(1, 24), QQ(0), -QQ(1, 2), QQ(0), QQ(1)] g = [QQ(61, 720), QQ(0), QQ(5, 24), QQ(0), QQ(1, 2), QQ(0), QQ(1)] assert dmp_revert(f, 8, 0, QQ) == g raises(MultivariatePolynomialError, lambda: dmp_revert([[1]], 2, 1, QQ)) def test_dup_trunc(): assert dup_trunc([1, 2, 3, 4, 5, 6], ZZ(3), ZZ) == [1, -1, 0, 1, -1, 0] assert dup_trunc([6, 5, 4, 3, 2, 1], ZZ(3), ZZ) == [-1, 1, 0, -1, 1] def test_dmp_trunc(): assert dmp_trunc([[]], [1, 2], 2, ZZ) == [[]] assert dmp_trunc([[1, 2], [1, 4, 1], [1]], [1, 2], 1, ZZ) == [[-3], [1]] def test_dmp_ground_trunc(): assert dmp_ground_trunc(f_0, ZZ(3), 2, ZZ) == \ dmp_normal( [[[1, -1, 0], [-1]], [[]], [[1, -1, 0], [1, -1, 1], [1]]], 2, ZZ) def test_dup_monic(): assert dup_monic([3, 6, 9], ZZ) == [1, 2, 3] raises(ExactQuotientFailed, lambda: dup_monic([3, 4, 5], ZZ)) assert dup_monic([], QQ) == [] assert dup_monic([QQ(1)], QQ) == [QQ(1)] assert dup_monic([QQ(7), QQ(1), QQ(21)], QQ) == [QQ(1), QQ(1, 7), QQ(3)] def test_dmp_ground_monic(): assert dmp_ground_monic([[3], [6], [9]], 1, ZZ) == [[1], [2], [3]] raises( ExactQuotientFailed, lambda: dmp_ground_monic([[3], [4], [5]], 1, ZZ)) assert dmp_ground_monic([[]], 1, QQ) == [[]] assert dmp_ground_monic([[QQ(1)]], 1, QQ) == [[QQ(1)]] assert dmp_ground_monic( [[QQ(7)], [QQ(1)], [QQ(21)]], 1, QQ) == [[QQ(1)], [QQ(1, 7)], [QQ(3)]] def test_dup_content(): assert dup_content([], ZZ) == ZZ(0) assert dup_content([1], ZZ) == ZZ(1) assert dup_content([-1], ZZ) == ZZ(1) assert dup_content([1, 1], ZZ) == ZZ(1) assert dup_content([2, 2], ZZ) == ZZ(2) assert dup_content([1, 2, 1], ZZ) == ZZ(1) assert dup_content([2, 4, 2], ZZ) == ZZ(2) assert dup_content([QQ(2, 3), QQ(4, 9)], QQ) == QQ(2, 9) assert dup_content([QQ(2, 3), QQ(4, 5)], QQ) == QQ(2, 15) def test_dmp_ground_content(): assert dmp_ground_content([[]], 1, ZZ) == ZZ(0) assert dmp_ground_content([[]], 1, QQ) == QQ(0) assert dmp_ground_content([[1]], 1, ZZ) == ZZ(1) assert dmp_ground_content([[-1]], 1, ZZ) == ZZ(1) assert dmp_ground_content([[1], [1]], 1, ZZ) == ZZ(1) assert dmp_ground_content([[2], [2]], 1, ZZ) == ZZ(2) assert dmp_ground_content([[1], [2], [1]], 1, ZZ) == ZZ(1) assert dmp_ground_content([[2], [4], [2]], 1, ZZ) == ZZ(2) assert dmp_ground_content([[QQ(2, 3)], [QQ(4, 9)]], 1, QQ) == QQ(2, 9) assert dmp_ground_content([[QQ(2, 3)], [QQ(4, 5)]], 1, QQ) == QQ(2, 15) assert dmp_ground_content(f_0, 2, ZZ) == ZZ(1) assert dmp_ground_content( dmp_mul_ground(f_0, ZZ(2), 2, ZZ), 2, ZZ) == ZZ(2) assert dmp_ground_content(f_1, 2, ZZ) == ZZ(1) assert dmp_ground_content( dmp_mul_ground(f_1, ZZ(3), 2, ZZ), 2, ZZ) == ZZ(3) assert dmp_ground_content(f_2, 2, ZZ) == ZZ(1) assert dmp_ground_content( dmp_mul_ground(f_2, ZZ(4), 2, ZZ), 2, ZZ) == ZZ(4) assert dmp_ground_content(f_3, 2, ZZ) == ZZ(1) assert dmp_ground_content( dmp_mul_ground(f_3, ZZ(5), 2, ZZ), 2, ZZ) == ZZ(5) assert dmp_ground_content(f_4, 2, ZZ) == ZZ(1) assert dmp_ground_content( dmp_mul_ground(f_4, ZZ(6), 2, ZZ), 2, ZZ) == ZZ(6) assert dmp_ground_content(f_5, 2, ZZ) == ZZ(1) assert dmp_ground_content( dmp_mul_ground(f_5, ZZ(7), 2, ZZ), 2, ZZ) == ZZ(7) assert dmp_ground_content(f_6, 3, ZZ) == ZZ(1) assert dmp_ground_content( dmp_mul_ground(f_6, ZZ(8), 3, ZZ), 3, ZZ) == ZZ(8) def test_dup_primitive(): assert dup_primitive([], ZZ) == (ZZ(0), []) assert dup_primitive([ZZ(1)], ZZ) == (ZZ(1), [ZZ(1)]) assert dup_primitive([ZZ(1), ZZ(1)], ZZ) == (ZZ(1), [ZZ(1), ZZ(1)]) assert dup_primitive([ZZ(2), ZZ(2)], ZZ) == (ZZ(2), [ZZ(1), ZZ(1)]) assert dup_primitive( [ZZ(1), ZZ(2), ZZ(1)], ZZ) == (ZZ(1), [ZZ(1), ZZ(2), ZZ(1)]) assert dup_primitive( [ZZ(2), ZZ(4), ZZ(2)], ZZ) == (ZZ(2), [ZZ(1), ZZ(2), ZZ(1)]) assert dup_primitive([], QQ) == (QQ(0), []) assert dup_primitive([QQ(1)], QQ) == (QQ(1), [QQ(1)]) assert dup_primitive([QQ(1), QQ(1)], QQ) == (QQ(1), [QQ(1), QQ(1)]) assert dup_primitive([QQ(2), QQ(2)], QQ) == (QQ(2), [QQ(1), QQ(1)]) assert dup_primitive( [QQ(1), QQ(2), QQ(1)], QQ) == (QQ(1), [QQ(1), QQ(2), QQ(1)]) assert dup_primitive( [QQ(2), QQ(4), QQ(2)], QQ) == (QQ(2), [QQ(1), QQ(2), QQ(1)]) assert dup_primitive( [QQ(2, 3), QQ(4, 9)], QQ) == (QQ(2, 9), [QQ(3), QQ(2)]) assert dup_primitive( [QQ(2, 3), QQ(4, 5)], QQ) == (QQ(2, 15), [QQ(5), QQ(6)]) def test_dmp_ground_primitive(): assert dmp_ground_primitive([[]], 1, ZZ) == (ZZ(0), [[]]) assert dmp_ground_primitive(f_0, 2, ZZ) == (ZZ(1), f_0) assert dmp_ground_primitive( dmp_mul_ground(f_0, ZZ(2), 2, ZZ), 2, ZZ) == (ZZ(2), f_0) assert dmp_ground_primitive(f_1, 2, ZZ) == (ZZ(1), f_1) assert dmp_ground_primitive( dmp_mul_ground(f_1, ZZ(3), 2, ZZ), 2, ZZ) == (ZZ(3), f_1) assert dmp_ground_primitive(f_2, 2, ZZ) == (ZZ(1), f_2) assert dmp_ground_primitive( dmp_mul_ground(f_2, ZZ(4), 2, ZZ), 2, ZZ) == (ZZ(4), f_2) assert dmp_ground_primitive(f_3, 2, ZZ) == (ZZ(1), f_3) assert dmp_ground_primitive( dmp_mul_ground(f_3, ZZ(5), 2, ZZ), 2, ZZ) == (ZZ(5), f_3) assert dmp_ground_primitive(f_4, 2, ZZ) == (ZZ(1), f_4) assert dmp_ground_primitive( dmp_mul_ground(f_4, ZZ(6), 2, ZZ), 2, ZZ) == (ZZ(6), f_4) assert dmp_ground_primitive(f_5, 2, ZZ) == (ZZ(1), f_5) assert dmp_ground_primitive( dmp_mul_ground(f_5, ZZ(7), 2, ZZ), 2, ZZ) == (ZZ(7), f_5) assert dmp_ground_primitive(f_6, 3, ZZ) == (ZZ(1), f_6) assert dmp_ground_primitive( dmp_mul_ground(f_6, ZZ(8), 3, ZZ), 3, ZZ) == (ZZ(8), f_6) assert dmp_ground_primitive([[ZZ(2)]], 1, ZZ) == (ZZ(2), [[ZZ(1)]]) assert dmp_ground_primitive([[QQ(2)]], 1, QQ) == (QQ(2), [[QQ(1)]]) assert dmp_ground_primitive( [[QQ(2, 3)], [QQ(4, 9)]], 1, QQ) == (QQ(2, 9), [[QQ(3)], [QQ(2)]]) assert dmp_ground_primitive( [[QQ(2, 3)], [QQ(4, 5)]], 1, QQ) == (QQ(2, 15), [[QQ(5)], [QQ(6)]]) def test_dup_extract(): f = dup_normal([2930944, 0, 2198208, 0, 549552, 0, 45796], ZZ) g = dup_normal([17585664, 0, 8792832, 0, 1099104, 0], ZZ) F = dup_normal([64, 0, 48, 0, 12, 0, 1], ZZ) G = dup_normal([384, 0, 192, 0, 24, 0], ZZ) assert dup_extract(f, g, ZZ) == (45796, F, G) def test_dmp_ground_extract(): f = dmp_normal( [[2930944], [], [2198208], [], [549552], [], [45796]], 1, ZZ) g = dmp_normal([[17585664], [], [8792832], [], [1099104], []], 1, ZZ) F = dmp_normal([[64], [], [48], [], [12], [], [1]], 1, ZZ) G = dmp_normal([[384], [], [192], [], [24], []], 1, ZZ) assert dmp_ground_extract(f, g, 1, ZZ) == (45796, F, G) def test_dup_real_imag(): assert dup_real_imag([], ZZ) == ([[]], [[]]) assert dup_real_imag([1], ZZ) == ([[1]], [[]]) assert dup_real_imag([1, 1], ZZ) == ([[1], [1]], [[1, 0]]) assert dup_real_imag([1, 2], ZZ) == ([[1], [2]], [[1, 0]]) assert dup_real_imag( [1, 2, 3], ZZ) == ([[1], [2], [-1, 0, 3]], [[2, 0], [2, 0]]) raises(DomainError, lambda: dup_real_imag([EX(1), EX(2)], EX)) def test_dup_mirror(): assert dup_mirror([], ZZ) == [] assert dup_mirror([1], ZZ) == [1] assert dup_mirror([1, 2, 3, 4, 5], ZZ) == [1, -2, 3, -4, 5] assert dup_mirror([1, 2, 3, 4, 5, 6], ZZ) == [-1, 2, -3, 4, -5, 6] def test_dup_scale(): assert dup_scale([], -1, ZZ) == [] assert dup_scale([1], -1, ZZ) == [1] assert dup_scale([1, 2, 3, 4, 5], -1, ZZ) == [1, -2, 3, -4, 5] assert dup_scale([1, 2, 3, 4, 5], -7, ZZ) == [2401, -686, 147, -28, 5] def test_dup_shift(): assert dup_shift([], 1, ZZ) == [] assert dup_shift([1], 1, ZZ) == [1] assert dup_shift([1, 2, 3, 4, 5], 1, ZZ) == [1, 6, 15, 20, 15] assert dup_shift([1, 2, 3, 4, 5], 7, ZZ) == [1, 30, 339, 1712, 3267] def test_dup_transform(): assert dup_transform([], [], [1, 1], ZZ) == [] assert dup_transform([], [1], [1, 1], ZZ) == [] assert dup_transform([], [1, 2], [1, 1], ZZ) == [] assert dup_transform([6, -5, 4, -3, 17], [1, -3, 4], [2, -3], ZZ) == \ [6, -82, 541, -2205, 6277, -12723, 17191, -13603, 4773] def test_dup_compose(): assert dup_compose([], [], ZZ) == [] assert dup_compose([], [1], ZZ) == [] assert dup_compose([], [1, 2], ZZ) == [] assert dup_compose([1], [], ZZ) == [1] assert dup_compose([1, 2, 0], [], ZZ) == [] assert dup_compose([1, 2, 1], [], ZZ) == [1] assert dup_compose([1, 2, 1], [1], ZZ) == [4] assert dup_compose([1, 2, 1], [7], ZZ) == [64] assert dup_compose([1, 2, 1], [1, -1], ZZ) == [1, 0, 0] assert dup_compose([1, 2, 1], [1, 1], ZZ) == [1, 4, 4] assert dup_compose([1, 2, 1], [1, 2, 1], ZZ) == [1, 4, 8, 8, 4] def test_dmp_compose(): assert dmp_compose([1, 2, 1], [1, 2, 1], 0, ZZ) == [1, 4, 8, 8, 4] assert dmp_compose([[[]]], [[[]]], 2, ZZ) == [[[]]] assert dmp_compose([[[]]], [[[1]]], 2, ZZ) == [[[]]] assert dmp_compose([[[]]], [[[1]], [[2]]], 2, ZZ) == [[[]]] assert dmp_compose([[[1]]], [], 2, ZZ) == [[[1]]] assert dmp_compose([[1], [2], [ ]], [[]], 1, ZZ) == [[]] assert dmp_compose([[1], [2], [1]], [[]], 1, ZZ) == [[1]] assert dmp_compose([[1], [2], [1]], [[1]], 1, ZZ) == [[4]] assert dmp_compose([[1], [2], [1]], [[7]], 1, ZZ) == [[64]] assert dmp_compose([[1], [2], [1]], [[1], [-1]], 1, ZZ) == [[1], [ ], [ ]] assert dmp_compose([[1], [2], [1]], [[1], [ 1]], 1, ZZ) == [[1], [4], [4]] assert dmp_compose( [[1], [2], [1]], [[1], [2], [1]], 1, ZZ) == [[1], [4], [8], [8], [4]] def test_dup_decompose(): assert dup_decompose([1], ZZ) == [[1]] assert dup_decompose([1, 0], ZZ) == [[1, 0]] assert dup_decompose([1, 0, 0, 0], ZZ) == [[1, 0, 0, 0]] assert dup_decompose([1, 0, 0, 0, 0], ZZ) == [[1, 0, 0], [1, 0, 0]] assert dup_decompose( [1, 0, 0, 0, 0, 0, 0], ZZ) == [[1, 0, 0, 0], [1, 0, 0]] assert dup_decompose([7, 0, 0, 0, 1], ZZ) == [[7, 0, 1], [1, 0, 0]] assert dup_decompose([4, 0, 3, 0, 2], ZZ) == [[4, 3, 2], [1, 0, 0]] f = [1, 0, 20, 0, 150, 0, 500, 0, 625, -2, 0, -10, 9] assert dup_decompose(f, ZZ) == [[1, 0, 0, -2, 9], [1, 0, 5, 0]] f = [2, 0, 40, 0, 300, 0, 1000, 0, 1250, -4, 0, -20, 18] assert dup_decompose(f, ZZ) == [[2, 0, 0, -4, 18], [1, 0, 5, 0]] f = [1, 0, 20, -8, 150, -120, 524, -600, 865, -1034, 600, -170, 29] assert dup_decompose(f, ZZ) == [[1, -8, 24, -34, 29], [1, 0, 5, 0]] R, t = ring("t", ZZ) f = [6*t**2 - 42, 48*t**2 + 96, 144*t**2 + 648*t + 288, 624*t**2 + 864*t + 384, 108*t**3 + 312*t**2 + 432*t + 192] assert dup_decompose(f, R.to_domain()) == [f] def test_dmp_lift(): q = [QQ(1, 1), QQ(0, 1), QQ(1, 1)] f = [ANP([QQ(1, 1)], q, QQ), ANP([], q, QQ), ANP([], q, QQ), ANP([QQ(1, 1), QQ(0, 1)], q, QQ), ANP([QQ(17, 1), QQ(0, 1)], q, QQ)] assert dmp_lift(f, 0, QQ.algebraic_field(I)) == \ [QQ(1), QQ(0), QQ(0), QQ(0), QQ(0), QQ(0), QQ(2), QQ(0), QQ(578), QQ(0), QQ(0), QQ(0), QQ(1), QQ(0), QQ(-578), QQ(0), QQ(83521)] raises(DomainError, lambda: dmp_lift([EX(1), EX(2)], 0, EX)) def test_dup_sign_variations(): assert dup_sign_variations([], ZZ) == 0 assert dup_sign_variations([1, 0], ZZ) == 0 assert dup_sign_variations([1, 0, 2], ZZ) == 0 assert dup_sign_variations([1, 0, 3, 0], ZZ) == 0 assert dup_sign_variations([1, 0, 4, 0, 5], ZZ) == 0 assert dup_sign_variations([-1, 0, 2], ZZ) == 1 assert dup_sign_variations([-1, 0, 3, 0], ZZ) == 1 assert dup_sign_variations([-1, 0, 4, 0, 5], ZZ) == 1 assert dup_sign_variations([-1, -4, -5], ZZ) == 0 assert dup_sign_variations([ 1, -4, -5], ZZ) == 1 assert dup_sign_variations([ 1, 4, -5], ZZ) == 1 assert dup_sign_variations([ 1, -4, 5], ZZ) == 2 assert dup_sign_variations([-1, 4, -5], ZZ) == 2 assert dup_sign_variations([-1, 4, 5], ZZ) == 1 assert dup_sign_variations([-1, -4, 5], ZZ) == 1 assert dup_sign_variations([ 1, 4, 5], ZZ) == 0 assert dup_sign_variations([-1, 0, -4, 0, -5], ZZ) == 0 assert dup_sign_variations([ 1, 0, -4, 0, -5], ZZ) == 1 assert dup_sign_variations([ 1, 0, 4, 0, -5], ZZ) == 1 assert dup_sign_variations([ 1, 0, -4, 0, 5], ZZ) == 2 assert dup_sign_variations([-1, 0, 4, 0, -5], ZZ) == 2 assert dup_sign_variations([-1, 0, 4, 0, 5], ZZ) == 1 assert dup_sign_variations([-1, 0, -4, 0, 5], ZZ) == 1 assert dup_sign_variations([ 1, 0, 4, 0, 5], ZZ) == 0 def test_dup_clear_denoms(): assert dup_clear_denoms([], QQ, ZZ) == (ZZ(1), []) assert dup_clear_denoms([QQ(1)], QQ, ZZ) == (ZZ(1), [QQ(1)]) assert dup_clear_denoms([QQ(7)], QQ, ZZ) == (ZZ(1), [QQ(7)]) assert dup_clear_denoms([QQ(7, 3)], QQ) == (ZZ(3), [QQ(7)]) assert dup_clear_denoms([QQ(7, 3)], QQ, ZZ) == (ZZ(3), [QQ(7)]) assert dup_clear_denoms( [QQ(3), QQ(1), QQ(0)], QQ, ZZ) == (ZZ(1), [QQ(3), QQ(1), QQ(0)]) assert dup_clear_denoms( [QQ(1), QQ(1, 2), QQ(0)], QQ, ZZ) == (ZZ(2), [QQ(2), QQ(1), QQ(0)]) assert dup_clear_denoms([QQ(3), QQ( 1), QQ(0)], QQ, ZZ, convert=True) == (ZZ(1), [ZZ(3), ZZ(1), ZZ(0)]) assert dup_clear_denoms([QQ(1), QQ( 1, 2), QQ(0)], QQ, ZZ, convert=True) == (ZZ(2), [ZZ(2), ZZ(1), ZZ(0)]) assert dup_clear_denoms( [EX(S(3)/2), EX(S(9)/4)], EX) == (EX(4), [EX(6), EX(9)]) assert dup_clear_denoms([EX(7)], EX) == (EX(1), [EX(7)]) assert dup_clear_denoms([EX(sin(x)/x), EX(0)], EX) == (EX(x), [EX(sin(x)), EX(0)]) def test_dmp_clear_denoms(): assert dmp_clear_denoms([[]], 1, QQ, ZZ) == (ZZ(1), [[]]) assert dmp_clear_denoms([[QQ(1)]], 1, QQ, ZZ) == (ZZ(1), [[QQ(1)]]) assert dmp_clear_denoms([[QQ(7)]], 1, QQ, ZZ) == (ZZ(1), [[QQ(7)]]) assert dmp_clear_denoms([[QQ(7, 3)]], 1, QQ) == (ZZ(3), [[QQ(7)]]) assert dmp_clear_denoms([[QQ(7, 3)]], 1, QQ, ZZ) == (ZZ(3), [[QQ(7)]]) assert dmp_clear_denoms( [[QQ(3)], [QQ(1)], []], 1, QQ, ZZ) == (ZZ(1), [[QQ(3)], [QQ(1)], []]) assert dmp_clear_denoms([[QQ( 1)], [QQ(1, 2)], []], 1, QQ, ZZ) == (ZZ(2), [[QQ(2)], [QQ(1)], []]) assert dmp_clear_denoms([QQ(3), QQ( 1), QQ(0)], 0, QQ, ZZ, convert=True) == (ZZ(1), [ZZ(3), ZZ(1), ZZ(0)]) assert dmp_clear_denoms([QQ(1), QQ(1, 2), QQ( 0)], 0, QQ, ZZ, convert=True) == (ZZ(2), [ZZ(2), ZZ(1), ZZ(0)]) assert dmp_clear_denoms([[QQ(3)], [QQ( 1)], []], 1, QQ, ZZ, convert=True) == (ZZ(1), [[QQ(3)], [QQ(1)], []]) assert dmp_clear_denoms([[QQ(1)], [QQ(1, 2)], []], 1, QQ, ZZ, convert=True) == (ZZ(2), [[QQ(2)], [QQ(1)], []]) assert dmp_clear_denoms( [[EX(S(3)/2)], [EX(S(9)/4)]], 1, EX) == (EX(4), [[EX(6)], [EX(9)]]) assert dmp_clear_denoms([[EX(7)]], 1, EX) == (EX(1), [[EX(7)]]) assert dmp_clear_denoms([[EX(sin(x)/x), EX(0)]], 1, EX) == (EX(x), [[EX(sin(x)), EX(0)]])
1514c77228e2a862af67543cf002573f6668718160c5ff7693e81713da7be66b
"""Tests for high-level polynomials manipulation functions. """ from sympy.polys.polyfuncs import ( symmetrize, horner, interpolate, rational_interpolate, viete, ) from sympy.polys.polyerrors import ( MultivariatePolynomialError, ) from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.testing.pytest import raises from sympy.abc import a, b, c, d, e, x, y, z def test_symmetrize(): assert symmetrize(0, x, y, z) == (0, 0) assert symmetrize(1, x, y, z) == (1, 0) s1 = x + y + z s2 = x*y + x*z + y*z assert symmetrize(1) == (1, 0) assert symmetrize(1, formal=True) == (1, 0, []) assert symmetrize(x) == (x, 0) assert symmetrize(x + 1) == (x + 1, 0) assert symmetrize(x, x, y) == (x + y, -y) assert symmetrize(x + 1, x, y) == (x + y + 1, -y) assert symmetrize(x, x, y, z) == (s1, -y - z) assert symmetrize(x + 1, x, y, z) == (s1 + 1, -y - z) assert symmetrize(x**2, x, y, z) == (s1**2 - 2*s2, -y**2 - z**2) assert symmetrize(x**2 + y**2) == (-2*x*y + (x + y)**2, 0) assert symmetrize(x**2 - y**2) == (-2*x*y + (x + y)**2, -2*y**2) assert symmetrize(x**3 + y**2 + a*x**2 + b*y**3, x, y) == \ (-3*x*y*(x + y) - 2*a*x*y + a*(x + y)**2 + (x + y)**3, y**2*(1 - a) + y**3*(b - 1)) U = [u0, u1, u2] = symbols('u:3') assert symmetrize(x + 1, x, y, z, formal=True, symbols=U) == \ (u0 + 1, -y - z, [(u0, x + y + z), (u1, x*y + x*z + y*z), (u2, x*y*z)]) assert symmetrize([1, 2, 3]) == [(1, 0), (2, 0), (3, 0)] assert symmetrize([1, 2, 3], formal=True) == ([(1, 0), (2, 0), (3, 0)], []) assert symmetrize([x + y, x - y]) == [(x + y, 0), (x + y, -2*y)] def test_horner(): assert horner(0) == 0 assert horner(1) == 1 assert horner(x) == x assert horner(x + 1) == x + 1 assert horner(x**2 + 1) == x**2 + 1 assert horner(x**2 + x) == (x + 1)*x assert horner(x**2 + x + 1) == (x + 1)*x + 1 assert horner( 9*x**4 + 8*x**3 + 7*x**2 + 6*x + 5) == (((9*x + 8)*x + 7)*x + 6)*x + 5 assert horner( a*x**4 + b*x**3 + c*x**2 + d*x + e) == (((a*x + b)*x + c)*x + d)*x + e assert horner(4*x**2*y**2 + 2*x**2*y + 2*x*y**2 + x*y, wrt=x) == (( 4*y + 2)*x*y + (2*y + 1)*y)*x assert horner(4*x**2*y**2 + 2*x**2*y + 2*x*y**2 + x*y, wrt=y) == (( 4*x + 2)*y*x + (2*x + 1)*x)*y def test_interpolate(): assert interpolate([1, 4, 9, 16], x) == x**2 assert interpolate([1, 4, 9, 25], x) == S(3)*x**3/2 - S(8)*x**2 + S(33)*x/2 - 9 assert interpolate([(1, 1), (2, 4), (3, 9)], x) == x**2 assert interpolate([(1, 2), (2, 5), (3, 10)], x) == 1 + x**2 assert interpolate({1: 2, 2: 5, 3: 10}, x) == 1 + x**2 assert interpolate({5: 2, 7: 5, 8: 10, 9: 13}, x) == \ -S(13)*x**3/24 + S(12)*x**2 - S(2003)*x/24 + 187 assert interpolate([(1, 3), (0, 6), (2, 5), (5, 7), (-2, 4)], x) == \ S(-61)*x**4/280 + S(247)*x**3/210 + S(139)*x**2/280 - S(1871)*x/420 + 6 assert interpolate((9, 4, 9), 3) == 9 assert interpolate((1, 9, 16), 1) is S.One assert interpolate(((x, 1), (2, 3)), x) is S.One assert interpolate(dict([(x, 1), (2, 3)]), x) is S.One assert interpolate(((2, x), (1, 3)), x) == x**2 - 4*x + 6 def test_rational_interpolate(): x, y = symbols('x,y') xdata = [1, 2, 3, 4, 5, 6] ydata1 = [120, 150, 200, 255, 312, 370] ydata2 = [-210, -35, 105, 231, 350, 465] assert rational_interpolate(list(zip(xdata, ydata1)), 2) == ( (60*x**2 + 60)/x ) assert rational_interpolate(list(zip(xdata, ydata1)), 3) == ( (60*x**2 + 60)/x ) assert rational_interpolate(list(zip(xdata, ydata2)), 2, X=y) == ( (105*y**2 - 525)/(y + 1) ) xdata = list(range(1,11)) ydata = [-1923885361858460, -5212158811973685, -9838050145867125, -15662936261217245, -22469424125057910, -30073793365223685, -38332297297028735, -47132954289530109, -56387719094026320, -66026548943876885] assert rational_interpolate(list(zip(xdata, ydata)), 5) == ( (-12986226192544605*x**4 + 8657484128363070*x**3 - 30301194449270745*x**2 + 4328742064181535*x - 4328742064181535)/(x**3 + 9*x**2 - 3*x + 11)) def test_viete(): r1, r2 = symbols('r1, r2') assert viete( a*x**2 + b*x + c, [r1, r2], x) == [(r1 + r2, -b/a), (r1*r2, c/a)] raises(ValueError, lambda: viete(1, [], x)) raises(ValueError, lambda: viete(x**2 + 1, [r1])) raises(MultivariatePolynomialError, lambda: viete(x + y, [r1]))
beb760dbbdf5f51dd9ae8fe2761415c487a898df4fea65378c7c97ec764a78c5
"""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.core.numbers import Rational from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt 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 def test_FracField_index(): a = symbols("a") F, x, y, z = field('x y z', QQ) assert F.index(x) == 0 assert F.index(y) == 1 raises(ValueError, lambda: F.index(1)) raises(ValueError, lambda: F.index(a)) pass
5ce3891421a6c649fedfac816f885af714266dabb22d651cedd97642ddc859a0
"""Tests for the implementation of RootOf class and related tools. """ from sympy.polys.polytools import Poly from sympy.polys.rootoftools import (rootof, RootOf, CRootOf, RootSum, _pure_key_dict as D) from sympy.polys.polyerrors import ( MultivariatePolynomialError, GeneratorsNeeded, PolynomialError, ) from sympy.core.function import (Function, Lambda) from sympy.core.numbers import (Float, I, Rational) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import tan from sympy.integrals.integrals import Integral from sympy.polys.orthopolys import legendre_poly from sympy.solvers.solvers import solve from sympy.testing.pytest import raises, slow from sympy.core.expr import unchanged from sympy.abc import a, b, x, y, z, r def test_CRootOf___new__(): assert rootof(x, 0) == 0 assert rootof(x, -1) == 0 assert rootof(x, S.Zero) == 0 assert rootof(x - 1, 0) == 1 assert rootof(x - 1, -1) == 1 assert rootof(x + 1, 0) == -1 assert rootof(x + 1, -1) == -1 assert rootof(x**2 + 2*x + 3, 0) == -1 - I*sqrt(2) assert rootof(x**2 + 2*x + 3, 1) == -1 + I*sqrt(2) assert rootof(x**2 + 2*x + 3, -1) == -1 + I*sqrt(2) assert rootof(x**2 + 2*x + 3, -2) == -1 - I*sqrt(2) r = rootof(x**2 + 2*x + 3, 0, radicals=False) assert isinstance(r, RootOf) is True r = rootof(x**2 + 2*x + 3, 1, radicals=False) assert isinstance(r, RootOf) is True r = rootof(x**2 + 2*x + 3, -1, radicals=False) assert isinstance(r, RootOf) is True r = rootof(x**2 + 2*x + 3, -2, radicals=False) assert isinstance(r, RootOf) is True assert rootof((x - 1)*(x + 1), 0, radicals=False) == -1 assert rootof((x - 1)*(x + 1), 1, radicals=False) == 1 assert rootof((x - 1)*(x + 1), -1, radicals=False) == 1 assert rootof((x - 1)*(x + 1), -2, radicals=False) == -1 assert rootof((x - 1)*(x + 1), 0, radicals=True) == -1 assert rootof((x - 1)*(x + 1), 1, radicals=True) == 1 assert rootof((x - 1)*(x + 1), -1, radicals=True) == 1 assert rootof((x - 1)*(x + 1), -2, radicals=True) == -1 assert rootof((x - 1)*(x**3 + x + 3), 0) == rootof(x**3 + x + 3, 0) assert rootof((x - 1)*(x**3 + x + 3), 1) == 1 assert rootof((x - 1)*(x**3 + x + 3), 2) == rootof(x**3 + x + 3, 1) assert rootof((x - 1)*(x**3 + x + 3), 3) == rootof(x**3 + x + 3, 2) assert rootof((x - 1)*(x**3 + x + 3), -1) == rootof(x**3 + x + 3, 2) assert rootof((x - 1)*(x**3 + x + 3), -2) == rootof(x**3 + x + 3, 1) assert rootof((x - 1)*(x**3 + x + 3), -3) == 1 assert rootof((x - 1)*(x**3 + x + 3), -4) == rootof(x**3 + x + 3, 0) assert rootof(x**4 + 3*x**3, 0) == -3 assert rootof(x**4 + 3*x**3, 1) == 0 assert rootof(x**4 + 3*x**3, 2) == 0 assert rootof(x**4 + 3*x**3, 3) == 0 raises(GeneratorsNeeded, lambda: rootof(0, 0)) raises(GeneratorsNeeded, lambda: rootof(1, 0)) raises(PolynomialError, lambda: rootof(Poly(0, x), 0)) raises(PolynomialError, lambda: rootof(Poly(1, x), 0)) raises(PolynomialError, lambda: rootof(x - y, 0)) # issue 8617 raises(PolynomialError, lambda: rootof(exp(x), 0)) raises(NotImplementedError, lambda: rootof(x**3 - x + sqrt(2), 0)) raises(NotImplementedError, lambda: rootof(x**3 - x + I, 0)) raises(IndexError, lambda: rootof(x**2 - 1, -4)) raises(IndexError, lambda: rootof(x**2 - 1, -3)) raises(IndexError, lambda: rootof(x**2 - 1, 2)) raises(IndexError, lambda: rootof(x**2 - 1, 3)) raises(ValueError, lambda: rootof(x**2 - 1, x)) assert rootof(Poly(x - y, x), 0) == y assert rootof(Poly(x**2 - y, x), 0) == -sqrt(y) assert rootof(Poly(x**2 - y, x), 1) == sqrt(y) assert rootof(Poly(x**3 - y, x), 0) == y**Rational(1, 3) assert rootof(y*x**3 + y*x + 2*y, x, 0) == -1 raises(NotImplementedError, lambda: rootof(x**3 + x + 2*y, x, 0)) assert rootof(x**3 + x + 1, 0).is_commutative is True def test_CRootOf_attributes(): r = rootof(x**3 + x + 3, 0) assert r.is_number assert r.free_symbols == set() # if the following assertion fails then multivariate polynomials # are apparently supported and the RootOf.free_symbols routine # should be changed to return whatever symbols would not be # the PurePoly dummy symbol raises(NotImplementedError, lambda: rootof(Poly(x**3 + y*x + 1, x), 0)) def test_CRootOf___eq__(): assert (rootof(x**3 + x + 3, 0) == rootof(x**3 + x + 3, 0)) is True assert (rootof(x**3 + x + 3, 0) == rootof(x**3 + x + 3, 1)) is False assert (rootof(x**3 + x + 3, 1) == rootof(x**3 + x + 3, 1)) is True assert (rootof(x**3 + x + 3, 1) == rootof(x**3 + x + 3, 2)) is False assert (rootof(x**3 + x + 3, 2) == rootof(x**3 + x + 3, 2)) is True assert (rootof(x**3 + x + 3, 0) == rootof(y**3 + y + 3, 0)) is True assert (rootof(x**3 + x + 3, 0) == rootof(y**3 + y + 3, 1)) is False assert (rootof(x**3 + x + 3, 1) == rootof(y**3 + y + 3, 1)) is True assert (rootof(x**3 + x + 3, 1) == rootof(y**3 + y + 3, 2)) is False assert (rootof(x**3 + x + 3, 2) == rootof(y**3 + y + 3, 2)) is True def test_CRootOf___eval_Eq__(): f = Function('f') eq = x**3 + x + 3 r = rootof(eq, 2) r1 = rootof(eq, 1) assert Eq(r, r1) is S.false assert Eq(r, r) is S.true assert unchanged(Eq, r, x) assert Eq(r, 0) is S.false assert Eq(r, S.Infinity) is S.false assert Eq(r, I) is S.false assert unchanged(Eq, r, f(0)) sol = solve(eq) for s in sol: if s.is_real: assert Eq(r, s) is S.false r = rootof(eq, 0) for s in sol: if s.is_real: assert Eq(r, s) is S.true eq = x**3 + x + 1 sol = solve(eq) assert [Eq(rootof(eq, i), j) for i in range(3) for j in sol ].count(True) == 3 assert Eq(rootof(eq, 0), 1 + S.ImaginaryUnit) == False def test_CRootOf_is_real(): assert rootof(x**3 + x + 3, 0).is_real is True assert rootof(x**3 + x + 3, 1).is_real is False assert rootof(x**3 + x + 3, 2).is_real is False def test_CRootOf_is_complex(): assert rootof(x**3 + x + 3, 0).is_complex is True def test_CRootOf_subs(): assert rootof(x**3 + x + 1, 0).subs(x, y) == rootof(y**3 + y + 1, 0) def test_CRootOf_diff(): assert rootof(x**3 + x + 1, 0).diff(x) == 0 assert rootof(x**3 + x + 1, 0).diff(y) == 0 @slow def test_CRootOf_evalf(): real = rootof(x**3 + x + 3, 0).evalf(n=20) assert real.epsilon_eq(Float("-1.2134116627622296341")) re, im = rootof(x**3 + x + 3, 1).evalf(n=20).as_real_imag() assert re.epsilon_eq( Float("0.60670583138111481707")) assert im.epsilon_eq(-Float("1.45061224918844152650")) re, im = rootof(x**3 + x + 3, 2).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("0.60670583138111481707")) assert im.epsilon_eq(Float("1.45061224918844152650")) p = legendre_poly(4, x, polys=True) roots = [str(r.n(17)) for r in p.real_roots()] # magnitudes are given by # sqrt(3/S(7) - 2*sqrt(6/S(5))/7) # and # sqrt(3/S(7) + 2*sqrt(6/S(5))/7) assert roots == [ "-0.86113631159405258", "-0.33998104358485626", "0.33998104358485626", "0.86113631159405258", ] re = rootof(x**5 - 5*x + 12, 0).evalf(n=20) assert re.epsilon_eq(Float("-1.84208596619025438271")) re, im = rootof(x**5 - 5*x + 12, 1).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("-0.351854240827371999559")) assert im.epsilon_eq(Float("-1.709561043370328882010")) re, im = rootof(x**5 - 5*x + 12, 2).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("-0.351854240827371999559")) assert im.epsilon_eq(Float("+1.709561043370328882010")) re, im = rootof(x**5 - 5*x + 12, 3).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("+1.272897223922499190910")) assert im.epsilon_eq(Float("-0.719798681483861386681")) re, im = rootof(x**5 - 5*x + 12, 4).evalf(n=20).as_real_imag() assert re.epsilon_eq(Float("+1.272897223922499190910")) assert im.epsilon_eq(Float("+0.719798681483861386681")) # issue 6393 assert str(rootof(x**5 + 2*x**4 + x**3 - 68719476736, 0).n(3)) == '147.' eq = (531441*x**11 + 3857868*x**10 + 13730229*x**9 + 32597882*x**8 + 55077472*x**7 + 60452000*x**6 + 32172064*x**5 - 4383808*x**4 - 11942912*x**3 - 1506304*x**2 + 1453312*x + 512) a, b = rootof(eq, 1).n(2).as_real_imag() c, d = rootof(eq, 2).n(2).as_real_imag() assert a == c assert b < d assert b == -d # issue 6451 r = rootof(legendre_poly(64, x), 7) assert r.n(2) == r.n(100).n(2) # issue 9019 r0 = rootof(x**2 + 1, 0, radicals=False) r1 = rootof(x**2 + 1, 1, radicals=False) assert r0.n(4) == -1.0*I assert r1.n(4) == 1.0*I # make sure verification is used in case a max/min traps the "root" assert str(rootof(4*x**5 + 16*x**3 + 12*x**2 + 7, 0).n(3)) == '-0.976' # watch out for UnboundLocalError c = CRootOf(90720*x**6 - 4032*x**4 + 84*x**2 - 1, 0) assert c._eval_evalf(2) # doesn't fail # watch out for imaginary parts that don't want to evaluate assert str(RootOf(x**16 + 32*x**14 + 508*x**12 + 5440*x**10 + 39510*x**8 + 204320*x**6 + 755548*x**4 + 1434496*x**2 + 877969, 10).n(2)) == '-3.4*I' assert abs(RootOf(x**4 + 10*x**2 + 1, 0).n(2)) < 0.4 # check reset and args r = [RootOf(x**3 + x + 3, i) for i in range(3)] r[0]._reset() for ri in r: i = ri._get_interval() ri.n(2) assert i != ri._get_interval() ri._reset() assert i == ri._get_interval() assert i == i.func(*i.args) def test_CRootOf_evalf_caching_bug(): r = rootof(x**5 - 5*x + 12, 1) r.n() a = r._get_interval() r = rootof(x**5 - 5*x + 12, 1) r.n() b = r._get_interval() assert a == b def test_CRootOf_real_roots(): assert Poly(x**5 + x + 1).real_roots() == [rootof(x**3 - x**2 + 1, 0)] assert Poly(x**5 + x + 1).real_roots(radicals=False) == [rootof( x**3 - x**2 + 1, 0)] # https://github.com/sympy/sympy/issues/20902 p = Poly(-3*x**4 - 10*x**3 - 12*x**2 - 6*x - 1, x, domain='ZZ') assert CRootOf.real_roots(p) == [S(-1), S(-1), S(-1), S(-1)/3] def test_CRootOf_all_roots(): assert Poly(x**5 + x + 1).all_roots() == [ rootof(x**3 - x**2 + 1, 0), Rational(-1, 2) - sqrt(3)*I/2, Rational(-1, 2) + sqrt(3)*I/2, rootof(x**3 - x**2 + 1, 1), rootof(x**3 - x**2 + 1, 2), ] assert Poly(x**5 + x + 1).all_roots(radicals=False) == [ rootof(x**3 - x**2 + 1, 0), rootof(x**2 + x + 1, 0, radicals=False), rootof(x**2 + x + 1, 1, radicals=False), rootof(x**3 - x**2 + 1, 1), rootof(x**3 - x**2 + 1, 2), ] def test_CRootOf_eval_rational(): p = legendre_poly(4, x, polys=True) roots = [r.eval_rational(n=18) for r in p.real_roots()] for root in roots: assert isinstance(root, Rational) roots = [str(root.n(17)) for root in roots] assert roots == [ "-0.86113631159405258", "-0.33998104358485626", "0.33998104358485626", "0.86113631159405258", ] def test_RootSum___new__(): f = x**3 + x + 3 g = Lambda(r, log(r*x)) s = RootSum(f, g) assert isinstance(s, RootSum) is True assert RootSum(f**2, g) == 2*RootSum(f, g) assert RootSum((x - 7)*f**3, g) == log(7*x) + 3*RootSum(f, g) # issue 5571 assert hash(RootSum((x - 7)*f**3, g)) == hash(log(7*x) + 3*RootSum(f, g)) raises(MultivariatePolynomialError, lambda: RootSum(x**3 + x + y)) raises(ValueError, lambda: RootSum(x**2 + 3, lambda x: x)) assert RootSum(f, exp) == RootSum(f, Lambda(x, exp(x))) assert RootSum(f, log) == RootSum(f, Lambda(x, log(x))) assert isinstance(RootSum(f, auto=False), RootSum) is True assert RootSum(f) == 0 assert RootSum(f, Lambda(x, x)) == 0 assert RootSum(f, Lambda(x, x**2)) == -2 assert RootSum(f, Lambda(x, 1)) == 3 assert RootSum(f, Lambda(x, 2)) == 6 assert RootSum(f, auto=False).is_commutative is True assert RootSum(f, Lambda(x, 1/(x + x**2))) == Rational(11, 3) assert RootSum(f, Lambda(x, y/(x + x**2))) == Rational(11, 3)*y assert RootSum(x**2 - 1, Lambda(x, 3*x**2), x) == 6 assert RootSum(x**2 - y, Lambda(x, 3*x**2), x) == 6*y assert RootSum(x**2 - 1, Lambda(x, z*x**2), x) == 2*z assert RootSum(x**2 - y, Lambda(x, z*x**2), x) == 2*z*y assert RootSum( x**2 - 1, Lambda(x, exp(x)), quadratic=True) == exp(-1) + exp(1) assert RootSum(x**3 + a*x + a**3, tan, x) == \ RootSum(x**3 + x + 1, Lambda(x, tan(a*x))) assert RootSum(a**3*x**3 + a*x + 1, tan, x) == \ RootSum(x**3 + x + 1, Lambda(x, tan(x/a))) def test_RootSum_free_symbols(): assert RootSum(x**3 + x + 3, Lambda(r, exp(r))).free_symbols == set() assert RootSum(x**3 + x + 3, Lambda(r, exp(a*r))).free_symbols == {a} assert RootSum( x**3 + x + y, Lambda(r, exp(a*r)), x).free_symbols == {a, y} def test_RootSum___eq__(): f = Lambda(x, exp(x)) assert (RootSum(x**3 + x + 1, f) == RootSum(x**3 + x + 1, f)) is True assert (RootSum(x**3 + x + 1, f) == RootSum(y**3 + y + 1, f)) is True assert (RootSum(x**3 + x + 1, f) == RootSum(x**3 + x + 2, f)) is False assert (RootSum(x**3 + x + 1, f) == RootSum(y**3 + y + 2, f)) is False def test_RootSum_doit(): rs = RootSum(x**2 + 1, exp) assert isinstance(rs, RootSum) is True assert rs.doit() == exp(-I) + exp(I) rs = RootSum(x**2 + a, exp, x) assert isinstance(rs, RootSum) is True assert rs.doit() == exp(-sqrt(-a)) + exp(sqrt(-a)) def test_RootSum_evalf(): rs = RootSum(x**2 + 1, exp) assert rs.evalf(n=20, chop=True).epsilon_eq(Float("1.0806046117362794348")) assert rs.evalf(n=15, chop=True).epsilon_eq(Float("1.08060461173628")) rs = RootSum(x**2 + a, exp, x) assert rs.evalf() == rs def test_RootSum_diff(): f = x**3 + x + 3 g = Lambda(r, exp(r*x)) h = Lambda(r, r*exp(r*x)) assert RootSum(f, g).diff(x) == RootSum(f, h) def test_RootSum_subs(): f = x**3 + x + 3 g = Lambda(r, exp(r*x)) F = y**3 + y + 3 G = Lambda(r, exp(r*y)) assert RootSum(f, g).subs(y, 1) == RootSum(f, g) assert RootSum(f, g).subs(x, y) == RootSum(F, G) def test_RootSum_rational(): assert RootSum( z**5 - z + 1, Lambda(z, z/(x - z))) == (4*x - 5)/(x**5 - x + 1) f = 161*z**3 + 115*z**2 + 19*z + 1 g = Lambda(z, z*log( -3381*z**4/4 - 3381*z**3/4 - 625*z**2/2 - z*Rational(125, 2) - 5 + exp(x))) assert RootSum(f, g).diff(x) == -( (5*exp(2*x) - 6*exp(x) + 4)*exp(x)/(exp(3*x) - exp(2*x) + 1))/7 def test_RootSum_independent(): f = (x**3 - a)**2*(x**4 - b)**3 g = Lambda(x, 5*tan(x) + 7) h = Lambda(x, tan(x)) r0 = RootSum(x**3 - a, h, x) r1 = RootSum(x**4 - b, h, x) assert RootSum(f, g, x).as_ordered_terms() == [10*r0, 15*r1, 126] def test_issue_7876(): l1 = Poly(x**6 - x + 1, x).all_roots() l2 = [rootof(x**6 - x + 1, i) for i in range(6)] assert frozenset(l1) == frozenset(l2) def test_issue_8316(): f = Poly(7*x**8 - 9) assert len(f.all_roots()) == 8 f = Poly(7*x**8 - 10) assert len(f.all_roots()) == 8 def test__imag_count(): from sympy.polys.rootoftools import _imag_count_of_factor def imag_count(p): return sum([_imag_count_of_factor(f)*m for f, m in p.factor_list()[1]]) assert imag_count(Poly(x**6 + 10*x**2 + 1)) == 2 assert imag_count(Poly(x**2)) == 0 assert imag_count(Poly([1]*3 + [-1], x)) == 0 assert imag_count(Poly(x**3 + 1)) == 0 assert imag_count(Poly(x**2 + 1)) == 2 assert imag_count(Poly(x**2 - 1)) == 0 assert imag_count(Poly(x**4 - 1)) == 2 assert imag_count(Poly(x**4 + 1)) == 0 assert imag_count(Poly([1, 2, 3], x)) == 0 assert imag_count(Poly(x**3 + x + 1)) == 0 assert imag_count(Poly(x**4 + x + 1)) == 0 def q(r1, r2, p): return Poly(((x - r1)*(x - r2)).subs(x, x**p), x) assert imag_count(q(-1, -2, 2)) == 4 assert imag_count(q(-1, 2, 2)) == 2 assert imag_count(q(1, 2, 2)) == 0 assert imag_count(q(1, 2, 4)) == 4 assert imag_count(q(-1, 2, 4)) == 2 assert imag_count(q(-1, -2, 4)) == 0 def test_RootOf_is_imaginary(): r = RootOf(x**4 + 4*x**2 + 1, 1) i = r._get_interval() assert r.is_imaginary and i.ax*i.bx <= 0 def test_is_disjoint(): eq = x**3 + 5*x + 1 ir = rootof(eq, 0)._get_interval() ii = rootof(eq, 1)._get_interval() assert ir.is_disjoint(ii) assert ii.is_disjoint(ir) def test_pure_key_dict(): p = D() assert (x in p) is False assert (1 in p) is False p[x] = 1 assert x in p assert y in p assert p[y] == 1 raises(KeyError, lambda: p[1]) def dont(k): p[k] = 2 raises(ValueError, lambda: dont(1)) @slow def test_eval_approx_relative(): CRootOf.clear_cache() t = [CRootOf(x**3 + 10*x + 1, i) for i in range(3)] assert [i.eval_rational(1e-1) for i in t] == [ Rational(-21, 220), Rational(15, 256) - I*Rational(805, 256), Rational(15, 256) + I*Rational(805, 256)] t[0]._reset() assert [i.eval_rational(1e-1, 1e-4) for i in t] == [ Rational(-21, 220), Rational(3275, 65536) - I*Rational(414645, 131072), Rational(3275, 65536) + I*Rational(414645, 131072)] assert S(t[0]._get_interval().dx) < 1e-1 assert S(t[1]._get_interval().dx) < 1e-1 assert S(t[1]._get_interval().dy) < 1e-4 assert S(t[2]._get_interval().dx) < 1e-1 assert S(t[2]._get_interval().dy) < 1e-4 t[0]._reset() assert [i.eval_rational(1e-4, 1e-4) for i in t] == [ Rational(-2001, 20020), Rational(6545, 131072) - I*Rational(414645, 131072), Rational(6545, 131072) + I*Rational(414645, 131072)] assert S(t[0]._get_interval().dx) < 1e-4 assert S(t[1]._get_interval().dx) < 1e-4 assert S(t[1]._get_interval().dy) < 1e-4 assert S(t[2]._get_interval().dx) < 1e-4 assert S(t[2]._get_interval().dy) < 1e-4 # in the following, the actual relative precision is # less than tested, but it should never be greater t[0]._reset() assert [i.eval_rational(n=2) for i in t] == [ Rational(-202201, 2024022), Rational(104755, 2097152) - I*Rational(6634255, 2097152), Rational(104755, 2097152) + I*Rational(6634255, 2097152)] assert abs(S(t[0]._get_interval().dx)/t[0]) < 1e-2 assert abs(S(t[1]._get_interval().dx)/t[1]).n() < 1e-2 assert abs(S(t[1]._get_interval().dy)/t[1]).n() < 1e-2 assert abs(S(t[2]._get_interval().dx)/t[2]).n() < 1e-2 assert abs(S(t[2]._get_interval().dy)/t[2]).n() < 1e-2 t[0]._reset() assert [i.eval_rational(n=3) for i in t] == [ Rational(-202201, 2024022), Rational(1676045, 33554432) - I*Rational(106148135, 33554432), Rational(1676045, 33554432) + I*Rational(106148135, 33554432)] assert abs(S(t[0]._get_interval().dx)/t[0]) < 1e-3 assert abs(S(t[1]._get_interval().dx)/t[1]).n() < 1e-3 assert abs(S(t[1]._get_interval().dy)/t[1]).n() < 1e-3 assert abs(S(t[2]._get_interval().dx)/t[2]).n() < 1e-3 assert abs(S(t[2]._get_interval().dy)/t[2]).n() < 1e-3 t[0]._reset() a = [i.eval_approx(2) for i in t] assert [str(i) for i in a] == [ '-0.10', '0.05 - 3.2*I', '0.05 + 3.2*I'] assert all(abs(((a[i] - t[i])/t[i]).n()) < 1e-2 for i in range(len(a))) def test_issue_15920(): r = rootof(x**5 - x + 1, 0) p = Integral(x, (x, 1, y)) assert unchanged(Eq, r, p) def test_issue_19113(): eq = y**3 - y + 1 # generator is a canonical x in RootOf assert str(Poly(eq).real_roots()) == '[CRootOf(x**3 - x + 1, 0)]' assert str(Poly(eq.subs(y, tan(y))).real_roots() ) == '[CRootOf(x**3 - x + 1, 0)]' assert str(Poly(eq.subs(y, tan(x))).real_roots() ) == '[CRootOf(x**3 - x + 1, 0)]'
0c10fb075eb9a760806d839ea6c77dfca5fbc50c94f2ab888c14862c6797831c
"""Tests for user-friendly public interface to polynomial functions. """ import pickle from sympy.polys.polytools import ( Poly, PurePoly, poly, parallel_poly_from_expr, degree, degree_list, total_degree, LC, LM, LT, pdiv, prem, pquo, pexquo, div, rem, quo, exquo, half_gcdex, gcdex, invert, subresultants, resultant, discriminant, terms_gcd, cofactors, gcd, gcd_list, lcm, lcm_list, 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, GroebnerBasis, is_zero_dimensional, _torational_factor_list, to_rational_coeffs) from sympy.polys.polyerrors import ( MultivariatePolynomialError, ExactQuotientFailed, PolificationFailed, ComputationFailed, UnificationFailed, RefinementFailed, GeneratorsNeeded, GeneratorsError, PolynomialError, CoercionFailed, DomainError, OptionError, FlagError) from sympy.polys.polyclasses import DMP from sympy.polys.fields import field from sympy.polys.domains import FF, ZZ, QQ, ZZ_I, QQ_I, RR, EX from sympy.polys.domains.realfield import RealField from sympy.polys.domains.complexfield import ComplexField from sympy.polys.orderings import lex, grlex, grevlex from sympy.core.add import Add from sympy.core.basic import _aresame from sympy.core.containers import Tuple from sympy.core.expr import Expr from sympy.core.function import (Derivative, diff, expand) from sympy.core.mul import _keep_coeff, Mul from sympy.core.numbers import (Float, I, Integer, Rational, oo, pi) from sympy.core.power import Pow from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.complexes import (im, re) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.hyperbolic import tanh from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import sin from sympy.matrices.dense import Matrix from sympy.matrices.expressions.matexpr import MatrixSymbol from sympy.polys.rootoftools import rootof from sympy.utilities.iterables import iterable from sympy.testing.pytest import raises, warns_deprecated_sympy from sympy.abc import a, b, c, d, p, q, t, w, x, y, z def _epsilon_eq(a, b): for u, v in zip(a, b): if abs(u - v) > 1e-10: return False return True def _strict_eq(a, b): if type(a) == type(b): if iterable(a): if len(a) == len(b): return all(_strict_eq(c, d) for c, d in zip(a, b)) else: return False else: return isinstance(a, Poly) and a.eq(b, strict=True) else: return False def test_Poly_mixed_operations(): p = Poly(x, x) with warns_deprecated_sympy(): p * exp(x) with warns_deprecated_sympy(): p + exp(x) with warns_deprecated_sympy(): p - exp(x) def test_Poly_from_dict(): K = FF(3) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict( {0: 1, 1: 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict( {(0,): 1, (1,): 5}, gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_dict({(0, 0): 1, (1, 1): 2}, gens=( x, y), domain=K).rep == DMP([[K(2), K(0)], [K(1)]], K) assert Poly.from_dict({0: 1, 1: 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {0: 1, 1: 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_dict( {(0,): 1, (1,): 2}, gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_dict({(1,): sin(y)}, gens=x, composite=False) == \ Poly(sin(y)*x, x, domain='EX') assert Poly.from_dict({(1,): y}, gens=x, composite=False) == \ Poly(y*x, x, domain='EX') assert Poly.from_dict({(1, 1): 1}, gens=(x, y), composite=False) == \ Poly(x*y, x, y, domain='ZZ') assert Poly.from_dict({(1, 0): y}, gens=(x, z), composite=False) == \ Poly(y*x, x, z, domain='EX') def test_Poly_from_list(): K = FF(3) assert Poly.from_list([2, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_list([5, 1], gens=x, domain=K).rep == DMP([K(2), K(1)], K) assert Poly.from_list([2, 1], gens=x).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_list([2, 1], gens=x, field=True).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_list([2, 1], gens=x, domain=ZZ).rep == DMP([ZZ(2), ZZ(1)], ZZ) assert Poly.from_list([2, 1], gens=x, domain=QQ).rep == DMP([QQ(2), QQ(1)], QQ) assert Poly.from_list([0, 1.0], gens=x).rep == DMP([RR(1.0)], RR) assert Poly.from_list([1.0, 0], gens=x).rep == DMP([RR(1.0), RR(0.0)], RR) raises(MultivariatePolynomialError, lambda: Poly.from_list([[]], gens=(x, y))) def test_Poly_from_poly(): f = Poly(x + 7, x, domain=ZZ) g = Poly(x + 2, x, modulus=3) h = Poly(x + y, x, y, domain=ZZ) K = FF(3) assert Poly.from_poly(f) == f assert Poly.from_poly(f, domain=K).rep == DMP([K(1), K(1)], K) assert Poly.from_poly(f, domain=ZZ).rep == DMP([1, 7], ZZ) assert Poly.from_poly(f, domain=QQ).rep == DMP([1, 7], QQ) assert Poly.from_poly(f, gens=x) == f assert Poly.from_poly(f, gens=x, domain=K).rep == DMP([K(1), K(1)], K) assert Poly.from_poly(f, gens=x, domain=ZZ).rep == DMP([1, 7], ZZ) assert Poly.from_poly(f, gens=x, domain=QQ).rep == DMP([1, 7], QQ) assert Poly.from_poly(f, gens=y) == Poly(x + 7, y, domain='ZZ[x]') raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=K)) raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=ZZ)) raises(CoercionFailed, lambda: Poly.from_poly(f, gens=y, domain=QQ)) assert Poly.from_poly(f, gens=(x, y)) == Poly(x + 7, x, y, domain='ZZ') assert Poly.from_poly( f, gens=(x, y), domain=ZZ) == Poly(x + 7, x, y, domain='ZZ') assert Poly.from_poly( f, gens=(x, y), domain=QQ) == Poly(x + 7, x, y, domain='QQ') assert Poly.from_poly( f, gens=(x, y), modulus=3) == Poly(x + 7, x, y, domain='FF(3)') K = FF(2) assert Poly.from_poly(g) == g assert Poly.from_poly(g, domain=ZZ).rep == DMP([1, -1], ZZ) raises(CoercionFailed, lambda: Poly.from_poly(g, domain=QQ)) assert Poly.from_poly(g, domain=K).rep == DMP([K(1), K(0)], K) assert Poly.from_poly(g, gens=x) == g assert Poly.from_poly(g, gens=x, domain=ZZ).rep == DMP([1, -1], ZZ) raises(CoercionFailed, lambda: Poly.from_poly(g, gens=x, domain=QQ)) assert Poly.from_poly(g, gens=x, domain=K).rep == DMP([K(1), K(0)], K) K = FF(3) assert Poly.from_poly(h) == h assert Poly.from_poly( h, domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly(h, domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K) assert Poly.from_poly(h, gens=x) == Poly(x + y, x, domain=ZZ[y]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=ZZ)) assert Poly.from_poly( h, gens=x, domain=ZZ[y]) == Poly(x + y, x, domain=ZZ[y]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, domain=QQ)) assert Poly.from_poly( h, gens=x, domain=QQ[y]) == Poly(x + y, x, domain=QQ[y]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=x, modulus=3)) assert Poly.from_poly(h, gens=y) == Poly(x + y, y, domain=ZZ[x]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=ZZ)) assert Poly.from_poly( h, gens=y, domain=ZZ[x]) == Poly(x + y, y, domain=ZZ[x]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, domain=QQ)) assert Poly.from_poly( h, gens=y, domain=QQ[x]) == Poly(x + y, y, domain=QQ[x]) raises(CoercionFailed, lambda: Poly.from_poly(h, gens=y, modulus=3)) assert Poly.from_poly(h, gens=(x, y)) == h assert Poly.from_poly( h, gens=(x, y), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, gens=(x, y), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly( h, gens=(x, y), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K) assert Poly.from_poly( h, gens=(y, x)).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, gens=(y, x), domain=ZZ).rep == DMP([[ZZ(1)], [ZZ(1), ZZ(0)]], ZZ) assert Poly.from_poly( h, gens=(y, x), domain=QQ).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly( h, gens=(y, x), domain=K).rep == DMP([[K(1)], [K(1), K(0)]], K) assert Poly.from_poly( h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) assert Poly.from_poly( h, gens=(x, y), field=True).rep == DMP([[QQ(1)], [QQ(1), QQ(0)]], QQ) def test_Poly_from_expr(): raises(GeneratorsNeeded, lambda: Poly.from_expr(S.Zero)) raises(GeneratorsNeeded, lambda: Poly.from_expr(S(7))) F3 = FF(3) assert Poly.from_expr(x + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(y + 5, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(x + 5, x, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(y + 5, y, domain=F3).rep == DMP([F3(1), F3(2)], F3) assert Poly.from_expr(x + y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3) assert Poly.from_expr(x + y, x, y, domain=F3).rep == DMP([[F3(1)], [F3(1), F3(0)]], F3) assert Poly.from_expr(x + 5).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, x).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5, y).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, x, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(y + 5, y, domain=ZZ).rep == DMP([1, 5], ZZ) assert Poly.from_expr(x + 5, x, y, domain=ZZ).rep == DMP([[1], [5]], ZZ) assert Poly.from_expr(y + 5, x, y, domain=ZZ).rep == DMP([[1, 5]], ZZ) def test_poly_from_domain_element(): dom = ZZ[x] assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = dom.get_field() assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = QQ[x] assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = dom.get_field() assert Poly(dom(x+1), y, domain=dom).rep == DMP([dom(x+1)], dom) dom = ZZ.old_poly_ring(x) assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = dom.get_field() assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = QQ.old_poly_ring(x) assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = dom.get_field() assert Poly(dom([1, 1]), y, domain=dom).rep == DMP([dom([1, 1])], dom) dom = QQ.algebraic_field(I) assert Poly(dom([1, 1]), x, domain=dom).rep == DMP([dom([1, 1])], dom) def test_Poly__new__(): raises(GeneratorsError, lambda: Poly(x + 1, x, x)) raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[x])) raises(GeneratorsError, lambda: Poly(x + y, x, y, domain=ZZ[y])) raises(OptionError, lambda: Poly(x, x, symmetric=True)) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, domain=QQ)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, gaussian=True)) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, gaussian=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=[sqrt(3)])) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=[sqrt(3)])) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, extension=True)) raises(OptionError, lambda: Poly(x + 2, x, modulus=3, extension=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=True)) raises(OptionError, lambda: Poly(x + 2, x, domain=ZZ, greedy=False)) raises(OptionError, lambda: Poly(x + 2, x, domain=QQ, field=False)) raises(NotImplementedError, lambda: Poly(x + 1, x, modulus=3, order='grlex')) raises(NotImplementedError, lambda: Poly(x + 1, x, order='grlex')) raises(GeneratorsNeeded, lambda: Poly({1: 2, 0: 1})) raises(GeneratorsNeeded, lambda: Poly([2, 1])) raises(GeneratorsNeeded, lambda: Poly((2, 1))) raises(GeneratorsNeeded, lambda: Poly(1)) f = a*x**2 + b*x + c assert Poly({2: a, 1: b, 0: c}, x) == f assert Poly(iter([a, b, c]), x) == f assert Poly([a, b, c], x) == f assert Poly((a, b, c), x) == f f = Poly({}, x, y, z) assert f.gens == (x, y, z) and f.as_expr() == 0 assert Poly(Poly(a*x + b*y, x, y), x) == Poly(a*x + b*y, x) assert Poly(3*x**2 + 2*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1] assert Poly(3*x**2 + 2*x + 1, domain='QQ').all_coeffs() == [3, 2, 1] assert Poly(3*x**2 + 2*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0] raises(CoercionFailed, lambda: Poly(3*x**2/5 + x*Rational(2, 5) + 1, domain='ZZ')) assert Poly( 3*x**2/5 + x*Rational(2, 5) + 1, domain='QQ').all_coeffs() == [Rational(3, 5), Rational(2, 5), 1] assert _epsilon_eq( Poly(3*x**2/5 + x*Rational(2, 5) + 1, domain='RR').all_coeffs(), [0.6, 0.4, 1.0]) assert Poly(3.0*x**2 + 2.0*x + 1, domain='ZZ').all_coeffs() == [3, 2, 1] assert Poly(3.0*x**2 + 2.0*x + 1, domain='QQ').all_coeffs() == [3, 2, 1] assert Poly( 3.0*x**2 + 2.0*x + 1, domain='RR').all_coeffs() == [3.0, 2.0, 1.0] raises(CoercionFailed, lambda: Poly(3.1*x**2 + 2.1*x + 1, domain='ZZ')) assert Poly(3.1*x**2 + 2.1*x + 1, domain='QQ').all_coeffs() == [Rational(31, 10), Rational(21, 10), 1] assert Poly(3.1*x**2 + 2.1*x + 1, domain='RR').all_coeffs() == [3.1, 2.1, 1.0] assert Poly({(2, 1): 1, (1, 2): 2, (1, 1): 3}, x, y) == \ Poly(x**2*y + 2*x*y**2 + 3*x*y, x, y) assert Poly(x**2 + 1, extension=I).get_domain() == QQ.algebraic_field(I) f = 3*x**5 - x**4 + x**3 - x** 2 + 65538 assert Poly(f, x, modulus=65537, symmetric=True) == \ Poly(3*x**5 - x**4 + x**3 - x** 2 + 1, x, modulus=65537, symmetric=True) assert Poly(f, x, modulus=65537, symmetric=False) == \ Poly(3*x**5 + 65536*x**4 + x**3 + 65536*x** 2 + 1, x, modulus=65537, symmetric=False) assert isinstance(Poly(x**2 + x + 1.0).get_domain(), RealField) assert isinstance(Poly(x**2 + x + I + 1.0).get_domain(), ComplexField) def test_Poly__args(): assert Poly(x**2 + 1).args == (x**2 + 1, x) def test_Poly__gens(): assert Poly((x - p)*(x - q), x).gens == (x,) assert Poly((x - p)*(x - q), p).gens == (p,) assert Poly((x - p)*(x - q), q).gens == (q,) assert Poly((x - p)*(x - q), x, p).gens == (x, p) assert Poly((x - p)*(x - q), x, q).gens == (x, q) assert Poly((x - p)*(x - q), x, p, q).gens == (x, p, q) assert Poly((x - p)*(x - q), p, x, q).gens == (p, x, q) assert Poly((x - p)*(x - q), p, q, x).gens == (p, q, x) assert Poly((x - p)*(x - q)).gens == (x, p, q) assert Poly((x - p)*(x - q), sort='x > p > q').gens == (x, p, q) assert Poly((x - p)*(x - q), sort='p > x > q').gens == (p, x, q) assert Poly((x - p)*(x - q), sort='p > q > x').gens == (p, q, x) assert Poly((x - p)*(x - q), x, p, q, sort='p > q > x').gens == (x, p, q) assert Poly((x - p)*(x - q), wrt='x').gens == (x, p, q) assert Poly((x - p)*(x - q), wrt='p').gens == (p, x, q) assert Poly((x - p)*(x - q), wrt='q').gens == (q, x, p) assert Poly((x - p)*(x - q), wrt=x).gens == (x, p, q) assert Poly((x - p)*(x - q), wrt=p).gens == (p, x, q) assert Poly((x - p)*(x - q), wrt=q).gens == (q, x, p) assert Poly((x - p)*(x - q), x, p, q, wrt='p').gens == (x, p, q) assert Poly((x - p)*(x - q), wrt='p', sort='q > x').gens == (p, q, x) assert Poly((x - p)*(x - q), wrt='q', sort='p > x').gens == (q, p, x) def test_Poly_zero(): assert Poly(x).zero == Poly(0, x, domain=ZZ) assert Poly(x/2).zero == Poly(0, x, domain=QQ) def test_Poly_one(): assert Poly(x).one == Poly(1, x, domain=ZZ) assert Poly(x/2).one == Poly(1, x, domain=QQ) def test_Poly__unify(): raises(UnificationFailed, lambda: Poly(x)._unify(y)) F3 = FF(3) F5 = FF(5) assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=3))[2:] == ( DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3)) assert Poly(x, x, modulus=3)._unify(Poly(y, y, modulus=5))[2:] == ( DMP([[F5(1)], []], F5), DMP([[F5(1), F5(0)]], F5)) assert Poly(y, x, y)._unify(Poly(x, x, modulus=3))[2:] == (DMP([[F3(1), F3(0)]], F3), DMP([[F3(1)], []], F3)) assert Poly(x, x, modulus=3)._unify(Poly(y, x, y))[2:] == (DMP([[F3(1)], []], F3), DMP([[F3(1), F3(0)]], F3)) assert Poly(x + 1, x)._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], ZZ), DMP([1, 2], ZZ)) assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([1, 1], QQ), DMP([1, 2], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ)) assert Poly(x + 1, x, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, x)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ)) assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], ZZ), DMP([[1], [2]], ZZ)) assert Poly(x + 1, x, y, domain='QQ')._unify(Poly(x + 2, y, x))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, x, y)._unify(Poly(x + 2, y, x, domain='QQ'))[2:] == (DMP([[1], [1]], QQ), DMP([[1], [2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], ZZ), DMP([[1, 2]], ZZ)) assert Poly(x + 1, y, x, domain='QQ')._unify(Poly(x + 2, x, y))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x + 1, y, x)._unify(Poly(x + 2, x, y, domain='QQ'))[2:] == (DMP([[1, 1]], QQ), DMP([[1, 2]], QQ)) assert Poly(x**2 + I, x, domain=ZZ_I).unify(Poly(x**2 + sqrt(2), x, extension=True)) == \ (Poly(x**2 + I, x, domain='QQ<sqrt(2) + I>'), Poly(x**2 + sqrt(2), x, domain='QQ<sqrt(2) + I>')) F, A, B = field("a,b", ZZ) assert Poly(a*x, x, domain='ZZ[a]')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \ (DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain())) assert Poly(a*x, x, domain='ZZ(a)')._unify(Poly(a*b*x, x, domain='ZZ(a,b)'))[2:] == \ (DMP([A, F(0)], F.to_domain()), DMP([A*B, F(0)], F.to_domain())) raises(CoercionFailed, lambda: Poly(Poly(x**2 + x**2*z, y, field=True), domain='ZZ(x)')) f = Poly(t**2 + t/3 + x, t, domain='QQ(x)') g = Poly(t**2 + t/3 + x, t, domain='QQ[x]') assert f._unify(g)[2:] == (f.rep, f.rep) def test_Poly_free_symbols(): assert Poly(x**2 + 1).free_symbols == {x} assert Poly(x**2 + y*z).free_symbols == {x, y, z} assert Poly(x**2 + y*z, x).free_symbols == {x, y, z} assert Poly(x**2 + sin(y*z)).free_symbols == {x, y, z} assert Poly(x**2 + sin(y*z), x).free_symbols == {x, y, z} assert Poly(x**2 + sin(y*z), x, domain=EX).free_symbols == {x, y, z} assert Poly(1 + x + x**2, x, y, z).free_symbols == {x} assert Poly(x + sin(y), z).free_symbols == {x, y} def test_PurePoly_free_symbols(): assert PurePoly(x**2 + 1).free_symbols == set() assert PurePoly(x**2 + y*z).free_symbols == set() assert PurePoly(x**2 + y*z, x).free_symbols == {y, z} assert PurePoly(x**2 + sin(y*z)).free_symbols == set() assert PurePoly(x**2 + sin(y*z), x).free_symbols == {y, z} assert PurePoly(x**2 + sin(y*z), x, domain=EX).free_symbols == {y, z} def test_Poly__eq__(): assert (Poly(x, x) == Poly(x, x)) is True assert (Poly(x, x, domain=QQ) == Poly(x, x)) is False assert (Poly(x, x) == Poly(x, x, domain=QQ)) is False assert (Poly(x, x, domain=ZZ[a]) == Poly(x, x)) is False assert (Poly(x, x) == Poly(x, x, domain=ZZ[a])) is False assert (Poly(x*y, x, y) == Poly(x, x)) is False assert (Poly(x, x, y) == Poly(x, x)) is False assert (Poly(x, x) == Poly(x, x, y)) is False assert (Poly(x**2 + 1, x) == Poly(y**2 + 1, y)) is False assert (Poly(y**2 + 1, y) == Poly(x**2 + 1, x)) is False f = Poly(x, x, domain=ZZ) g = Poly(x, x, domain=QQ) assert f.eq(g) is False assert f.ne(g) is True assert f.eq(g, strict=True) is False assert f.ne(g, strict=True) is True t0 = Symbol('t0') f = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='QQ[x,t0]') g = Poly((t0/2 + x**2)*t**2 - x**2*t, t, domain='ZZ(x,t0)') assert (f == g) is False def test_PurePoly__eq__(): assert (PurePoly(x, x) == PurePoly(x, x)) is True assert (PurePoly(x, x, domain=QQ) == PurePoly(x, x)) is True assert (PurePoly(x, x) == PurePoly(x, x, domain=QQ)) is True assert (PurePoly(x, x, domain=ZZ[a]) == PurePoly(x, x)) is True assert (PurePoly(x, x) == PurePoly(x, x, domain=ZZ[a])) is True assert (PurePoly(x*y, x, y) == PurePoly(x, x)) is False assert (PurePoly(x, x, y) == PurePoly(x, x)) is False assert (PurePoly(x, x) == PurePoly(x, x, y)) is False assert (PurePoly(x**2 + 1, x) == PurePoly(y**2 + 1, y)) is True assert (PurePoly(y**2 + 1, y) == PurePoly(x**2 + 1, x)) is True f = PurePoly(x, x, domain=ZZ) g = PurePoly(x, x, domain=QQ) assert f.eq(g) is True assert f.ne(g) is False assert f.eq(g, strict=True) is False assert f.ne(g, strict=True) is True f = PurePoly(x, x, domain=ZZ) g = PurePoly(y, y, domain=QQ) assert f.eq(g) is True assert f.ne(g) is False assert f.eq(g, strict=True) is False assert f.ne(g, strict=True) is True def test_PurePoly_Poly(): assert isinstance(PurePoly(Poly(x**2 + 1)), PurePoly) is True assert isinstance(Poly(PurePoly(x**2 + 1)), Poly) is True def test_Poly_get_domain(): assert Poly(2*x).get_domain() == ZZ assert Poly(2*x, domain='ZZ').get_domain() == ZZ assert Poly(2*x, domain='QQ').get_domain() == QQ assert Poly(x/2).get_domain() == QQ raises(CoercionFailed, lambda: Poly(x/2, domain='ZZ')) assert Poly(x/2, domain='QQ').get_domain() == QQ assert isinstance(Poly(0.2*x).get_domain(), RealField) def test_Poly_set_domain(): assert Poly(2*x + 1).set_domain(ZZ) == Poly(2*x + 1) assert Poly(2*x + 1).set_domain('ZZ') == Poly(2*x + 1) assert Poly(2*x + 1).set_domain(QQ) == Poly(2*x + 1, domain='QQ') assert Poly(2*x + 1).set_domain('QQ') == Poly(2*x + 1, domain='QQ') assert Poly(Rational(2, 10)*x + Rational(1, 10)).set_domain('RR') == Poly(0.2*x + 0.1) assert Poly(0.2*x + 0.1).set_domain('QQ') == Poly(Rational(2, 10)*x + Rational(1, 10)) raises(CoercionFailed, lambda: Poly(x/2 + 1).set_domain(ZZ)) raises(CoercionFailed, lambda: Poly(x + 1, modulus=2).set_domain(QQ)) raises(GeneratorsError, lambda: Poly(x*y, x, y).set_domain(ZZ[y])) def test_Poly_get_modulus(): assert Poly(x**2 + 1, modulus=2).get_modulus() == 2 raises(PolynomialError, lambda: Poly(x**2 + 1).get_modulus()) def test_Poly_set_modulus(): assert Poly( x**2 + 1, modulus=2).set_modulus(7) == Poly(x**2 + 1, modulus=7) assert Poly( x**2 + 5, modulus=7).set_modulus(2) == Poly(x**2 + 1, modulus=2) assert Poly(x**2 + 1).set_modulus(2) == Poly(x**2 + 1, modulus=2) raises(CoercionFailed, lambda: Poly(x/2 + 1).set_modulus(2)) def test_Poly_add_ground(): assert Poly(x + 1).add_ground(2) == Poly(x + 3) def test_Poly_sub_ground(): assert Poly(x + 1).sub_ground(2) == Poly(x - 1) def test_Poly_mul_ground(): assert Poly(x + 1).mul_ground(2) == Poly(2*x + 2) def test_Poly_quo_ground(): assert Poly(2*x + 4).quo_ground(2) == Poly(x + 2) assert Poly(2*x + 3).quo_ground(2) == Poly(x + 1) def test_Poly_exquo_ground(): assert Poly(2*x + 4).exquo_ground(2) == Poly(x + 2) raises(ExactQuotientFailed, lambda: Poly(2*x + 3).exquo_ground(2)) def test_Poly_abs(): assert Poly(-x + 1, x).abs() == abs(Poly(-x + 1, x)) == Poly(x + 1, x) def test_Poly_neg(): assert Poly(-x + 1, x).neg() == -Poly(-x + 1, x) == Poly(x - 1, x) def test_Poly_add(): assert Poly(0, x).add(Poly(0, x)) == Poly(0, x) assert Poly(0, x) + Poly(0, x) == Poly(0, x) assert Poly(1, x).add(Poly(0, x)) == Poly(1, x) assert Poly(1, x, y) + Poly(0, x) == Poly(1, x, y) assert Poly(0, x).add(Poly(1, x, y)) == Poly(1, x, y) assert Poly(0, x, y) + Poly(1, x, y) == Poly(1, x, y) assert Poly(1, x) + x == Poly(x + 1, x) with warns_deprecated_sympy(): Poly(1, x) + sin(x) assert Poly(x, x) + 1 == Poly(x + 1, x) assert 1 + Poly(x, x) == Poly(x + 1, x) def test_Poly_sub(): assert Poly(0, x).sub(Poly(0, x)) == Poly(0, x) assert Poly(0, x) - Poly(0, x) == Poly(0, x) assert Poly(1, x).sub(Poly(0, x)) == Poly(1, x) assert Poly(1, x, y) - Poly(0, x) == Poly(1, x, y) assert Poly(0, x).sub(Poly(1, x, y)) == Poly(-1, x, y) assert Poly(0, x, y) - Poly(1, x, y) == Poly(-1, x, y) assert Poly(1, x) - x == Poly(1 - x, x) with warns_deprecated_sympy(): Poly(1, x) - sin(x) assert Poly(x, x) - 1 == Poly(x - 1, x) assert 1 - Poly(x, x) == Poly(1 - x, x) def test_Poly_mul(): assert Poly(0, x).mul(Poly(0, x)) == Poly(0, x) assert Poly(0, x) * Poly(0, x) == Poly(0, x) assert Poly(2, x).mul(Poly(4, x)) == Poly(8, x) assert Poly(2, x, y) * Poly(4, x) == Poly(8, x, y) assert Poly(4, x).mul(Poly(2, x, y)) == Poly(8, x, y) assert Poly(4, x, y) * Poly(2, x, y) == Poly(8, x, y) assert Poly(1, x) * x == Poly(x, x) with warns_deprecated_sympy(): Poly(1, x) * sin(x) assert Poly(x, x) * 2 == Poly(2*x, x) assert 2 * Poly(x, x) == Poly(2*x, x) def test_issue_13079(): assert Poly(x)*x == Poly(x**2, x, domain='ZZ') assert x*Poly(x) == Poly(x**2, x, domain='ZZ') assert -2*Poly(x) == Poly(-2*x, x, domain='ZZ') assert S(-2)*Poly(x) == Poly(-2*x, x, domain='ZZ') assert Poly(x)*S(-2) == Poly(-2*x, x, domain='ZZ') def test_Poly_sqr(): assert Poly(x*y, x, y).sqr() == Poly(x**2*y**2, x, y) def test_Poly_pow(): assert Poly(x, x).pow(10) == Poly(x**10, x) assert Poly(x, x).pow(Integer(10)) == Poly(x**10, x) assert Poly(2*y, x, y).pow(4) == Poly(16*y**4, x, y) assert Poly(2*y, x, y).pow(Integer(4)) == Poly(16*y**4, x, y) assert Poly(7*x*y, x, y)**3 == Poly(343*x**3*y**3, x, y) raises(TypeError, lambda: Poly(x*y + 1, x, y)**(-1)) raises(TypeError, lambda: Poly(x*y + 1, x, y)**x) def test_Poly_divmod(): f, g = Poly(x**2), Poly(x) q, r = g, Poly(0, x) assert divmod(f, g) == (q, r) assert f // g == q assert f % g == r assert divmod(f, x) == (q, r) assert f // x == q assert f % x == r q, r = Poly(0, x), Poly(2, x) assert divmod(2, g) == (q, r) assert 2 // g == q assert 2 % g == r assert Poly(x)/Poly(x) == 1 assert Poly(x**2)/Poly(x) == x assert Poly(x)/Poly(x**2) == 1/x def test_Poly_eq_ne(): assert (Poly(x + y, x, y) == Poly(x + y, x, y)) is True assert (Poly(x + y, x) == Poly(x + y, x, y)) is False assert (Poly(x + y, x, y) == Poly(x + y, x)) is False assert (Poly(x + y, x) == Poly(x + y, x)) is True assert (Poly(x + y, y) == Poly(x + y, y)) is True assert (Poly(x + y, x, y) == x + y) is True assert (Poly(x + y, x) == x + y) is True assert (Poly(x + y, x, y) == x + y) is True assert (Poly(x + y, x) == x + y) is True assert (Poly(x + y, y) == x + y) is True assert (Poly(x + y, x, y) != Poly(x + y, x, y)) is False assert (Poly(x + y, x) != Poly(x + y, x, y)) is True assert (Poly(x + y, x, y) != Poly(x + y, x)) is True assert (Poly(x + y, x) != Poly(x + y, x)) is False assert (Poly(x + y, y) != Poly(x + y, y)) is False assert (Poly(x + y, x, y) != x + y) is False assert (Poly(x + y, x) != x + y) is False assert (Poly(x + y, x, y) != x + y) is False assert (Poly(x + y, x) != x + y) is False assert (Poly(x + y, y) != x + y) is False assert (Poly(x, x) == sin(x)) is False assert (Poly(x, x) != sin(x)) is True def test_Poly_nonzero(): assert not bool(Poly(0, x)) is True assert not bool(Poly(1, x)) is False def test_Poly_properties(): assert Poly(0, x).is_zero is True assert Poly(1, x).is_zero is False assert Poly(1, x).is_one is True assert Poly(2, x).is_one is False assert Poly(x - 1, x).is_sqf is True assert Poly((x - 1)**2, x).is_sqf is False assert Poly(x - 1, x).is_monic is True assert Poly(2*x - 1, x).is_monic is False assert Poly(3*x + 2, x).is_primitive is True assert Poly(4*x + 2, x).is_primitive is False assert Poly(1, x).is_ground is True assert Poly(x, x).is_ground is False assert Poly(x + y + z + 1).is_linear is True assert Poly(x*y*z + 1).is_linear is False assert Poly(x*y + z + 1).is_quadratic is True assert Poly(x*y*z + 1).is_quadratic is False assert Poly(x*y).is_monomial is True assert Poly(x*y + 1).is_monomial is False assert Poly(x**2 + x*y).is_homogeneous is True assert Poly(x**3 + x*y).is_homogeneous is False assert Poly(x).is_univariate is True assert Poly(x*y).is_univariate is False assert Poly(x*y).is_multivariate is True assert Poly(x).is_multivariate is False assert Poly( x**16 + x**14 - x**10 + x**8 - x**6 + x**2 + 1).is_cyclotomic is False assert Poly( x**16 + x**14 - x**10 - x**8 - x**6 + x**2 + 1).is_cyclotomic is True def test_Poly_is_irreducible(): assert Poly(x**2 + x + 1).is_irreducible is True assert Poly(x**2 + 2*x + 1).is_irreducible is False assert Poly(7*x + 3, modulus=11).is_irreducible is True assert Poly(7*x**2 + 3*x + 1, modulus=11).is_irreducible is False def test_Poly_subs(): assert Poly(x + 1).subs(x, 0) == 1 assert Poly(x + 1).subs(x, x) == Poly(x + 1) assert Poly(x + 1).subs(x, y) == Poly(y + 1) assert Poly(x*y, x).subs(y, x) == x**2 assert Poly(x*y, x).subs(x, y) == y**2 def test_Poly_replace(): assert Poly(x + 1).replace(x) == Poly(x + 1) assert Poly(x + 1).replace(y) == Poly(y + 1) raises(PolynomialError, lambda: Poly(x + y).replace(z)) assert Poly(x + 1).replace(x, x) == Poly(x + 1) assert Poly(x + 1).replace(x, y) == Poly(y + 1) assert Poly(x + y).replace(x, x) == Poly(x + y) assert Poly(x + y).replace(x, z) == Poly(z + y, z, y) assert Poly(x + y).replace(y, y) == Poly(x + y) assert Poly(x + y).replace(y, z) == Poly(x + z, x, z) assert Poly(x + y).replace(z, t) == Poly(x + y) raises(PolynomialError, lambda: Poly(x + y).replace(x, y)) assert Poly(x + y, x).replace(x, z) == Poly(z + y, z) assert Poly(x + y, y).replace(y, z) == Poly(x + z, z) raises(PolynomialError, lambda: Poly(x + y, x).replace(x, y)) raises(PolynomialError, lambda: Poly(x + y, y).replace(y, x)) def test_Poly_reorder(): raises(PolynomialError, lambda: Poly(x + y).reorder(x, z)) assert Poly(x + y, x, y).reorder(x, y) == Poly(x + y, x, y) assert Poly(x + y, x, y).reorder(y, x) == Poly(x + y, y, x) assert Poly(x + y, y, x).reorder(x, y) == Poly(x + y, x, y) assert Poly(x + y, y, x).reorder(y, x) == Poly(x + y, y, x) assert Poly(x + y, x, y).reorder(wrt=x) == Poly(x + y, x, y) assert Poly(x + y, x, y).reorder(wrt=y) == Poly(x + y, y, x) def test_Poly_ltrim(): f = Poly(y**2 + y*z**2, x, y, z).ltrim(y) assert f.as_expr() == y**2 + y*z**2 and f.gens == (y, z) assert Poly(x*y - x, z, x, y).ltrim(1) == Poly(x*y - x, x, y) raises(PolynomialError, lambda: Poly(x*y**2 + y**2, x, y).ltrim(y)) raises(PolynomialError, lambda: Poly(x*y - x, x, y).ltrim(-1)) def test_Poly_has_only_gens(): assert Poly(x*y + 1, x, y, z).has_only_gens(x, y) is True assert Poly(x*y + z, x, y, z).has_only_gens(x, y) is False raises(GeneratorsError, lambda: Poly(x*y**2 + y**2, x, y).has_only_gens(t)) def test_Poly_to_ring(): assert Poly(2*x + 1, domain='ZZ').to_ring() == Poly(2*x + 1, domain='ZZ') assert Poly(2*x + 1, domain='QQ').to_ring() == Poly(2*x + 1, domain='ZZ') raises(CoercionFailed, lambda: Poly(x/2 + 1).to_ring()) raises(DomainError, lambda: Poly(2*x + 1, modulus=3).to_ring()) def test_Poly_to_field(): assert Poly(2*x + 1, domain='ZZ').to_field() == Poly(2*x + 1, domain='QQ') assert Poly(2*x + 1, domain='QQ').to_field() == Poly(2*x + 1, domain='QQ') assert Poly(x/2 + 1, domain='QQ').to_field() == Poly(x/2 + 1, domain='QQ') assert Poly(2*x + 1, modulus=3).to_field() == Poly(2*x + 1, modulus=3) assert Poly(2.0*x + 1.0).to_field() == Poly(2.0*x + 1.0) def test_Poly_to_exact(): assert Poly(2*x).to_exact() == Poly(2*x) assert Poly(x/2).to_exact() == Poly(x/2) assert Poly(0.1*x).to_exact() == Poly(x/10) def test_Poly_retract(): f = Poly(x**2 + 1, x, domain=QQ[y]) assert f.retract() == Poly(x**2 + 1, x, domain='ZZ') assert f.retract(field=True) == Poly(x**2 + 1, x, domain='QQ') assert Poly(0, x, y).retract() == Poly(0, x, y) def test_Poly_slice(): f = Poly(x**3 + 2*x**2 + 3*x + 4) assert f.slice(0, 0) == Poly(0, x) assert f.slice(0, 1) == Poly(4, x) assert f.slice(0, 2) == Poly(3*x + 4, x) assert f.slice(0, 3) == Poly(2*x**2 + 3*x + 4, x) assert f.slice(0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x) assert f.slice(x, 0, 0) == Poly(0, x) assert f.slice(x, 0, 1) == Poly(4, x) assert f.slice(x, 0, 2) == Poly(3*x + 4, x) assert f.slice(x, 0, 3) == Poly(2*x**2 + 3*x + 4, x) assert f.slice(x, 0, 4) == Poly(x**3 + 2*x**2 + 3*x + 4, x) def test_Poly_coeffs(): assert Poly(0, x).coeffs() == [0] assert Poly(1, x).coeffs() == [1] assert Poly(2*x + 1, x).coeffs() == [2, 1] assert Poly(7*x**2 + 2*x + 1, x).coeffs() == [7, 2, 1] assert Poly(7*x**4 + 2*x + 1, x).coeffs() == [7, 2, 1] assert Poly(x*y**7 + 2*x**2*y**3).coeffs('lex') == [2, 1] assert Poly(x*y**7 + 2*x**2*y**3).coeffs('grlex') == [1, 2] def test_Poly_monoms(): assert Poly(0, x).monoms() == [(0,)] assert Poly(1, x).monoms() == [(0,)] assert Poly(2*x + 1, x).monoms() == [(1,), (0,)] assert Poly(7*x**2 + 2*x + 1, x).monoms() == [(2,), (1,), (0,)] assert Poly(7*x**4 + 2*x + 1, x).monoms() == [(4,), (1,), (0,)] assert Poly(x*y**7 + 2*x**2*y**3).monoms('lex') == [(2, 3), (1, 7)] assert Poly(x*y**7 + 2*x**2*y**3).monoms('grlex') == [(1, 7), (2, 3)] def test_Poly_terms(): assert Poly(0, x).terms() == [((0,), 0)] assert Poly(1, x).terms() == [((0,), 1)] assert Poly(2*x + 1, x).terms() == [((1,), 2), ((0,), 1)] assert Poly(7*x**2 + 2*x + 1, x).terms() == [((2,), 7), ((1,), 2), ((0,), 1)] assert Poly(7*x**4 + 2*x + 1, x).terms() == [((4,), 7), ((1,), 2), ((0,), 1)] assert Poly( x*y**7 + 2*x**2*y**3).terms('lex') == [((2, 3), 2), ((1, 7), 1)] assert Poly( x*y**7 + 2*x**2*y**3).terms('grlex') == [((1, 7), 1), ((2, 3), 2)] def test_Poly_all_coeffs(): assert Poly(0, x).all_coeffs() == [0] assert Poly(1, x).all_coeffs() == [1] assert Poly(2*x + 1, x).all_coeffs() == [2, 1] assert Poly(7*x**2 + 2*x + 1, x).all_coeffs() == [7, 2, 1] assert Poly(7*x**4 + 2*x + 1, x).all_coeffs() == [7, 0, 0, 2, 1] def test_Poly_all_monoms(): assert Poly(0, x).all_monoms() == [(0,)] assert Poly(1, x).all_monoms() == [(0,)] assert Poly(2*x + 1, x).all_monoms() == [(1,), (0,)] assert Poly(7*x**2 + 2*x + 1, x).all_monoms() == [(2,), (1,), (0,)] assert Poly(7*x**4 + 2*x + 1, x).all_monoms() == [(4,), (3,), (2,), (1,), (0,)] def test_Poly_all_terms(): assert Poly(0, x).all_terms() == [((0,), 0)] assert Poly(1, x).all_terms() == [((0,), 1)] assert Poly(2*x + 1, x).all_terms() == [((1,), 2), ((0,), 1)] assert Poly(7*x**2 + 2*x + 1, x).all_terms() == \ [((2,), 7), ((1,), 2), ((0,), 1)] assert Poly(7*x**4 + 2*x + 1, x).all_terms() == \ [((4,), 7), ((3,), 0), ((2,), 0), ((1,), 2), ((0,), 1)] def test_Poly_termwise(): f = Poly(x**2 + 20*x + 400) g = Poly(x**2 + 2*x + 4) def func(monom, coeff): (k,) = monom return coeff//10**(2 - k) assert f.termwise(func) == g def func(monom, coeff): (k,) = monom return (k,), coeff//10**(2 - k) assert f.termwise(func) == g def test_Poly_length(): assert Poly(0, x).length() == 0 assert Poly(1, x).length() == 1 assert Poly(x, x).length() == 1 assert Poly(x + 1, x).length() == 2 assert Poly(x**2 + 1, x).length() == 2 assert Poly(x**2 + x + 1, x).length() == 3 def test_Poly_as_dict(): assert Poly(0, x).as_dict() == {} assert Poly(0, x, y, z).as_dict() == {} assert Poly(1, x).as_dict() == {(0,): 1} assert Poly(1, x, y, z).as_dict() == {(0, 0, 0): 1} assert Poly(x**2 + 3, x).as_dict() == {(2,): 1, (0,): 3} assert Poly(x**2 + 3, x, y, z).as_dict() == {(2, 0, 0): 1, (0, 0, 0): 3} assert Poly(3*x**2*y*z**3 + 4*x*y + 5*x*z).as_dict() == {(2, 1, 3): 3, (1, 1, 0): 4, (1, 0, 1): 5} def test_Poly_as_expr(): assert Poly(0, x).as_expr() == 0 assert Poly(0, x, y, z).as_expr() == 0 assert Poly(1, x).as_expr() == 1 assert Poly(1, x, y, z).as_expr() == 1 assert Poly(x**2 + 3, x).as_expr() == x**2 + 3 assert Poly(x**2 + 3, x, y, z).as_expr() == x**2 + 3 assert Poly( 3*x**2*y*z**3 + 4*x*y + 5*x*z).as_expr() == 3*x**2*y*z**3 + 4*x*y + 5*x*z f = Poly(x**2 + 2*x*y**2 - y, x, y) assert f.as_expr() == -y + x**2 + 2*x*y**2 assert f.as_expr({x: 5}) == 25 - y + 10*y**2 assert f.as_expr({y: 6}) == -6 + 72*x + x**2 assert f.as_expr({x: 5, y: 6}) == 379 assert f.as_expr(5, 6) == 379 raises(GeneratorsError, lambda: f.as_expr({z: 7})) def test_Poly_lift(): assert Poly(x**4 - I*x + 17*I, x, gaussian=True).lift() == \ Poly(x**16 + 2*x**10 + 578*x**8 + x**4 - 578*x**2 + 83521, x, domain='QQ') def test_Poly_deflate(): assert Poly(0, x).deflate() == ((1,), Poly(0, x)) assert Poly(1, x).deflate() == ((1,), Poly(1, x)) assert Poly(x, x).deflate() == ((1,), Poly(x, x)) assert Poly(x**2, x).deflate() == ((2,), Poly(x, x)) assert Poly(x**17, x).deflate() == ((17,), Poly(x, x)) assert Poly( x**2*y*z**11 + x**4*z**11).deflate() == ((2, 1, 11), Poly(x*y*z + x**2*z)) def test_Poly_inject(): f = Poly(x**2*y + x*y**3 + x*y + 1, x) assert f.inject() == Poly(x**2*y + x*y**3 + x*y + 1, x, y) assert f.inject(front=True) == Poly(y**3*x + y*x**2 + y*x + 1, y, x) def test_Poly_eject(): f = Poly(x**2*y + x*y**3 + x*y + 1, x, y) assert f.eject(x) == Poly(x*y**3 + (x**2 + x)*y + 1, y, domain='ZZ[x]') assert f.eject(y) == Poly(y*x**2 + (y**3 + y)*x + 1, x, domain='ZZ[y]') ex = x + y + z + t + w g = Poly(ex, x, y, z, t, w) assert g.eject(x) == Poly(ex, y, z, t, w, domain='ZZ[x]') assert g.eject(x, y) == Poly(ex, z, t, w, domain='ZZ[x, y]') assert g.eject(x, y, z) == Poly(ex, t, w, domain='ZZ[x, y, z]') assert g.eject(w) == Poly(ex, x, y, z, t, domain='ZZ[w]') assert g.eject(t, w) == Poly(ex, x, y, z, domain='ZZ[t, w]') assert g.eject(z, t, w) == Poly(ex, x, y, domain='ZZ[z, t, w]') raises(DomainError, lambda: Poly(x*y, x, y, domain=ZZ[z]).eject(y)) raises(NotImplementedError, lambda: Poly(x*y, x, y, z).eject(y)) def test_Poly_exclude(): assert Poly(x, x, y).exclude() == Poly(x, x) assert Poly(x*y, x, y).exclude() == Poly(x*y, x, y) assert Poly(1, x, y).exclude() == Poly(1, x, y) def test_Poly__gen_to_level(): assert Poly(1, x, y)._gen_to_level(-2) == 0 assert Poly(1, x, y)._gen_to_level(-1) == 1 assert Poly(1, x, y)._gen_to_level( 0) == 0 assert Poly(1, x, y)._gen_to_level( 1) == 1 raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(-3)) raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level( 2)) assert Poly(1, x, y)._gen_to_level(x) == 0 assert Poly(1, x, y)._gen_to_level(y) == 1 assert Poly(1, x, y)._gen_to_level('x') == 0 assert Poly(1, x, y)._gen_to_level('y') == 1 raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level(z)) raises(PolynomialError, lambda: Poly(1, x, y)._gen_to_level('z')) def test_Poly_degree(): assert Poly(0, x).degree() is -oo assert Poly(1, x).degree() == 0 assert Poly(x, x).degree() == 1 assert Poly(0, x).degree(gen=0) is -oo assert Poly(1, x).degree(gen=0) == 0 assert Poly(x, x).degree(gen=0) == 1 assert Poly(0, x).degree(gen=x) is -oo assert Poly(1, x).degree(gen=x) == 0 assert Poly(x, x).degree(gen=x) == 1 assert Poly(0, x).degree(gen='x') is -oo assert Poly(1, x).degree(gen='x') == 0 assert Poly(x, x).degree(gen='x') == 1 raises(PolynomialError, lambda: Poly(1, x).degree(gen=1)) raises(PolynomialError, lambda: Poly(1, x).degree(gen=y)) raises(PolynomialError, lambda: Poly(1, x).degree(gen='y')) assert Poly(1, x, y).degree() == 0 assert Poly(2*y, x, y).degree() == 0 assert Poly(x*y, x, y).degree() == 1 assert Poly(1, x, y).degree(gen=x) == 0 assert Poly(2*y, x, y).degree(gen=x) == 0 assert Poly(x*y, x, y).degree(gen=x) == 1 assert Poly(1, x, y).degree(gen=y) == 0 assert Poly(2*y, x, y).degree(gen=y) == 1 assert Poly(x*y, x, y).degree(gen=y) == 1 assert degree(0, x) is -oo assert degree(1, x) == 0 assert degree(x, x) == 1 assert degree(x*y**2, x) == 1 assert degree(x*y**2, y) == 2 assert degree(x*y**2, z) == 0 assert degree(pi) == 1 raises(TypeError, lambda: degree(y**2 + x**3)) raises(TypeError, lambda: degree(y**2 + x**3, 1)) raises(PolynomialError, lambda: degree(x, 1.1)) raises(PolynomialError, lambda: degree(x**2/(x**3 + 1), x)) assert degree(Poly(0,x),z) is -oo assert degree(Poly(1,x),z) == 0 assert degree(Poly(x**2+y**3,y)) == 3 assert degree(Poly(y**2 + x**3, y, x), 1) == 3 assert degree(Poly(y**2 + x**3, x), z) == 0 assert degree(Poly(y**2 + x**3 + z**4, x), z) == 4 def test_Poly_degree_list(): assert Poly(0, x).degree_list() == (-oo,) assert Poly(0, x, y).degree_list() == (-oo, -oo) assert Poly(0, x, y, z).degree_list() == (-oo, -oo, -oo) assert Poly(1, x).degree_list() == (0,) assert Poly(1, x, y).degree_list() == (0, 0) assert Poly(1, x, y, z).degree_list() == (0, 0, 0) assert Poly(x**2*y + x**3*z**2 + 1).degree_list() == (3, 1, 2) assert degree_list(1, x) == (0,) assert degree_list(x, x) == (1,) assert degree_list(x*y**2) == (1, 2) raises(ComputationFailed, lambda: degree_list(1)) def test_Poly_total_degree(): assert Poly(x**2*y + x**3*z**2 + 1).total_degree() == 5 assert Poly(x**2 + z**3).total_degree() == 3 assert Poly(x*y*z + z**4).total_degree() == 4 assert Poly(x**3 + x + 1).total_degree() == 3 assert total_degree(x*y + z**3) == 3 assert total_degree(x*y + z**3, x, y) == 2 assert total_degree(1) == 0 assert total_degree(Poly(y**2 + x**3 + z**4)) == 4 assert total_degree(Poly(y**2 + x**3 + z**4, x)) == 3 assert total_degree(Poly(y**2 + x**3 + z**4, x), z) == 4 assert total_degree(Poly(x**9 + x*z*y + x**3*z**2 + z**7,x), z) == 7 def test_Poly_homogenize(): assert Poly(x**2+y).homogenize(z) == Poly(x**2+y*z) assert Poly(x+y).homogenize(z) == Poly(x+y, x, y, z) assert Poly(x+y**2).homogenize(y) == Poly(x*y+y**2) def test_Poly_homogeneous_order(): assert Poly(0, x, y).homogeneous_order() is -oo assert Poly(1, x, y).homogeneous_order() == 0 assert Poly(x, x, y).homogeneous_order() == 1 assert Poly(x*y, x, y).homogeneous_order() == 2 assert Poly(x + 1, x, y).homogeneous_order() is None assert Poly(x*y + x, x, y).homogeneous_order() is None assert Poly(x**5 + 2*x**3*y**2 + 9*x*y**4).homogeneous_order() == 5 assert Poly(x**5 + 2*x**3*y**3 + 9*x*y**4).homogeneous_order() is None def test_Poly_LC(): assert Poly(0, x).LC() == 0 assert Poly(1, x).LC() == 1 assert Poly(2*x**2 + x, x).LC() == 2 assert Poly(x*y**7 + 2*x**2*y**3).LC('lex') == 2 assert Poly(x*y**7 + 2*x**2*y**3).LC('grlex') == 1 assert LC(x*y**7 + 2*x**2*y**3, order='lex') == 2 assert LC(x*y**7 + 2*x**2*y**3, order='grlex') == 1 def test_Poly_TC(): assert Poly(0, x).TC() == 0 assert Poly(1, x).TC() == 1 assert Poly(2*x**2 + x, x).TC() == 0 def test_Poly_EC(): assert Poly(0, x).EC() == 0 assert Poly(1, x).EC() == 1 assert Poly(2*x**2 + x, x).EC() == 1 assert Poly(x*y**7 + 2*x**2*y**3).EC('lex') == 1 assert Poly(x*y**7 + 2*x**2*y**3).EC('grlex') == 2 def test_Poly_coeff(): assert Poly(0, x).coeff_monomial(1) == 0 assert Poly(0, x).coeff_monomial(x) == 0 assert Poly(1, x).coeff_monomial(1) == 1 assert Poly(1, x).coeff_monomial(x) == 0 assert Poly(x**8, x).coeff_monomial(1) == 0 assert Poly(x**8, x).coeff_monomial(x**7) == 0 assert Poly(x**8, x).coeff_monomial(x**8) == 1 assert Poly(x**8, x).coeff_monomial(x**9) == 0 assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(1) == 1 assert Poly(3*x*y**2 + 1, x, y).coeff_monomial(x*y**2) == 3 p = Poly(24*x*y*exp(8) + 23*x, x, y) assert p.coeff_monomial(x) == 23 assert p.coeff_monomial(y) == 0 assert p.coeff_monomial(x*y) == 24*exp(8) assert p.as_expr().coeff(x) == 24*y*exp(8) + 23 raises(NotImplementedError, lambda: p.coeff(x)) raises(ValueError, lambda: Poly(x + 1).coeff_monomial(0)) raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x)) raises(ValueError, lambda: Poly(x + 1).coeff_monomial(3*x*y)) def test_Poly_nth(): assert Poly(0, x).nth(0) == 0 assert Poly(0, x).nth(1) == 0 assert Poly(1, x).nth(0) == 1 assert Poly(1, x).nth(1) == 0 assert Poly(x**8, x).nth(0) == 0 assert Poly(x**8, x).nth(7) == 0 assert Poly(x**8, x).nth(8) == 1 assert Poly(x**8, x).nth(9) == 0 assert Poly(3*x*y**2 + 1, x, y).nth(0, 0) == 1 assert Poly(3*x*y**2 + 1, x, y).nth(1, 2) == 3 raises(ValueError, lambda: Poly(x*y + 1, x, y).nth(1)) def test_Poly_LM(): assert Poly(0, x).LM() == (0,) assert Poly(1, x).LM() == (0,) assert Poly(2*x**2 + x, x).LM() == (2,) assert Poly(x*y**7 + 2*x**2*y**3).LM('lex') == (2, 3) assert Poly(x*y**7 + 2*x**2*y**3).LM('grlex') == (1, 7) assert LM(x*y**7 + 2*x**2*y**3, order='lex') == x**2*y**3 assert LM(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7 def test_Poly_LM_custom_order(): f = Poly(x**2*y**3*z + x**2*y*z**3 + x*y*z + 1) rev_lex = lambda monom: tuple(reversed(monom)) assert f.LM(order='lex') == (2, 3, 1) assert f.LM(order=rev_lex) == (2, 1, 3) def test_Poly_EM(): assert Poly(0, x).EM() == (0,) assert Poly(1, x).EM() == (0,) assert Poly(2*x**2 + x, x).EM() == (1,) assert Poly(x*y**7 + 2*x**2*y**3).EM('lex') == (1, 7) assert Poly(x*y**7 + 2*x**2*y**3).EM('grlex') == (2, 3) def test_Poly_LT(): assert Poly(0, x).LT() == ((0,), 0) assert Poly(1, x).LT() == ((0,), 1) assert Poly(2*x**2 + x, x).LT() == ((2,), 2) assert Poly(x*y**7 + 2*x**2*y**3).LT('lex') == ((2, 3), 2) assert Poly(x*y**7 + 2*x**2*y**3).LT('grlex') == ((1, 7), 1) assert LT(x*y**7 + 2*x**2*y**3, order='lex') == 2*x**2*y**3 assert LT(x*y**7 + 2*x**2*y**3, order='grlex') == x*y**7 def test_Poly_ET(): assert Poly(0, x).ET() == ((0,), 0) assert Poly(1, x).ET() == ((0,), 1) assert Poly(2*x**2 + x, x).ET() == ((1,), 1) assert Poly(x*y**7 + 2*x**2*y**3).ET('lex') == ((1, 7), 1) assert Poly(x*y**7 + 2*x**2*y**3).ET('grlex') == ((2, 3), 2) def test_Poly_max_norm(): assert Poly(-1, x).max_norm() == 1 assert Poly( 0, x).max_norm() == 0 assert Poly( 1, x).max_norm() == 1 def test_Poly_l1_norm(): assert Poly(-1, x).l1_norm() == 1 assert Poly( 0, x).l1_norm() == 0 assert Poly( 1, x).l1_norm() == 1 def test_Poly_clear_denoms(): coeff, poly = Poly(x + 2, x).clear_denoms() assert coeff == 1 and poly == Poly( x + 2, x, domain='ZZ') and poly.get_domain() == ZZ coeff, poly = Poly(x/2 + 1, x).clear_denoms() assert coeff == 2 and poly == Poly( x + 2, x, domain='QQ') and poly.get_domain() == QQ coeff, poly = Poly(x/2 + 1, x).clear_denoms(convert=True) assert coeff == 2 and poly == Poly( x + 2, x, domain='ZZ') and poly.get_domain() == ZZ coeff, poly = Poly(x/y + 1, x).clear_denoms(convert=True) assert coeff == y and poly == Poly( x + y, x, domain='ZZ[y]') and poly.get_domain() == ZZ[y] coeff, poly = Poly(x/3 + sqrt(2), x, domain='EX').clear_denoms() assert coeff == 3 and poly == Poly( x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX coeff, poly = Poly( x/3 + sqrt(2), x, domain='EX').clear_denoms(convert=True) assert coeff == 3 and poly == Poly( x + 3*sqrt(2), x, domain='EX') and poly.get_domain() == EX def test_Poly_rat_clear_denoms(): f = Poly(x**2/y + 1, x) g = Poly(x**3 + y, x) assert f.rat_clear_denoms(g) == \ (Poly(x**2 + y, x), Poly(y*x**3 + y**2, x)) f = f.set_domain(EX) g = g.set_domain(EX) assert f.rat_clear_denoms(g) == (f, g) def test_issue_20427(): f = Poly(-117968192370600*18**(S(1)/3)/(217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3) + 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)) - 15720318185*2**(S(2)/3)*3**(S(1)/3)*(24201 + 253*sqrt(9165))**(S(2)/3)/(217603955769048*(24201 + 253*sqrt(9165))** (S(1)/3) + 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)) + 15720318185*12**(S(1)/3)*(24201 + 253*sqrt(9165))**(S(2)/3)/( 217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3) + 2273005839412* sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)) + 117968192370600*2**( S(1)/3)*3**(S(2)/3)/(217603955769048*(24201 + 253*sqrt(9165))**(S(1)/3) + 2273005839412*sqrt(9165)*(24201 + 253*sqrt(9165))**(S(1)/3)), x) assert f == Poly(0, x, domain='EX') def test_Poly_integrate(): assert Poly(x + 1).integrate() == Poly(x**2/2 + x) assert Poly(x + 1).integrate(x) == Poly(x**2/2 + x) assert Poly(x + 1).integrate((x, 1)) == Poly(x**2/2 + x) assert Poly(x*y + 1).integrate(x) == Poly(x**2*y/2 + x) assert Poly(x*y + 1).integrate(y) == Poly(x*y**2/2 + y) assert Poly(x*y + 1).integrate(x, x) == Poly(x**3*y/6 + x**2/2) assert Poly(x*y + 1).integrate(y, y) == Poly(x*y**3/6 + y**2/2) assert Poly(x*y + 1).integrate((x, 2)) == Poly(x**3*y/6 + x**2/2) assert Poly(x*y + 1).integrate((y, 2)) == Poly(x*y**3/6 + y**2/2) assert Poly(x*y + 1).integrate(x, y) == Poly(x**2*y**2/4 + x*y) assert Poly(x*y + 1).integrate(y, x) == Poly(x**2*y**2/4 + x*y) def test_Poly_diff(): assert Poly(x**2 + x).diff() == Poly(2*x + 1) assert Poly(x**2 + x).diff(x) == Poly(2*x + 1) assert Poly(x**2 + x).diff((x, 1)) == Poly(2*x + 1) assert Poly(x**2*y**2 + x*y).diff(x) == Poly(2*x*y**2 + y) assert Poly(x**2*y**2 + x*y).diff(y) == Poly(2*x**2*y + x) assert Poly(x**2*y**2 + x*y).diff(x, x) == Poly(2*y**2, x, y) assert Poly(x**2*y**2 + x*y).diff(y, y) == Poly(2*x**2, x, y) assert Poly(x**2*y**2 + x*y).diff((x, 2)) == Poly(2*y**2, x, y) assert Poly(x**2*y**2 + x*y).diff((y, 2)) == Poly(2*x**2, x, y) assert Poly(x**2*y**2 + x*y).diff(x, y) == Poly(4*x*y + 1) assert Poly(x**2*y**2 + x*y).diff(y, x) == Poly(4*x*y + 1) def test_issue_9585(): assert diff(Poly(x**2 + x)) == Poly(2*x + 1) assert diff(Poly(x**2 + x), x, evaluate=False) == \ Derivative(Poly(x**2 + x), x) assert Derivative(Poly(x**2 + x), x).doit() == Poly(2*x + 1) def test_Poly_eval(): assert Poly(0, x).eval(7) == 0 assert Poly(1, x).eval(7) == 1 assert Poly(x, x).eval(7) == 7 assert Poly(0, x).eval(0, 7) == 0 assert Poly(1, x).eval(0, 7) == 1 assert Poly(x, x).eval(0, 7) == 7 assert Poly(0, x).eval(x, 7) == 0 assert Poly(1, x).eval(x, 7) == 1 assert Poly(x, x).eval(x, 7) == 7 assert Poly(0, x).eval('x', 7) == 0 assert Poly(1, x).eval('x', 7) == 1 assert Poly(x, x).eval('x', 7) == 7 raises(PolynomialError, lambda: Poly(1, x).eval(1, 7)) raises(PolynomialError, lambda: Poly(1, x).eval(y, 7)) raises(PolynomialError, lambda: Poly(1, x).eval('y', 7)) assert Poly(123, x, y).eval(7) == Poly(123, y) assert Poly(2*y, x, y).eval(7) == Poly(2*y, y) assert Poly(x*y, x, y).eval(7) == Poly(7*y, y) assert Poly(123, x, y).eval(x, 7) == Poly(123, y) assert Poly(2*y, x, y).eval(x, 7) == Poly(2*y, y) assert Poly(x*y, x, y).eval(x, 7) == Poly(7*y, y) assert Poly(123, x, y).eval(y, 7) == Poly(123, x) assert Poly(2*y, x, y).eval(y, 7) == Poly(14, x) assert Poly(x*y, x, y).eval(y, 7) == Poly(7*x, x) assert Poly(x*y + y, x, y).eval({x: 7}) == Poly(8*y, y) assert Poly(x*y + y, x, y).eval({y: 7}) == Poly(7*x + 7, x) assert Poly(x*y + y, x, y).eval({x: 6, y: 7}) == 49 assert Poly(x*y + y, x, y).eval({x: 7, y: 6}) == 48 assert Poly(x*y + y, x, y).eval((6, 7)) == 49 assert Poly(x*y + y, x, y).eval([6, 7]) == 49 assert Poly(x + 1, domain='ZZ').eval(S.Half) == Rational(3, 2) assert Poly(x + 1, domain='ZZ').eval(sqrt(2)) == sqrt(2) + 1 raises(ValueError, lambda: Poly(x*y + y, x, y).eval((6, 7, 8))) raises(DomainError, lambda: Poly(x + 1, domain='ZZ').eval(S.Half, auto=False)) # issue 6344 alpha = Symbol('alpha') result = (2*alpha*z - 2*alpha + z**2 + 3)/(z**2 - 2*z + 1) f = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, domain='ZZ[alpha]') assert f.eval((z + 1)/(z - 1)) == result g = Poly(x**2 + (alpha - 1)*x - alpha + 1, x, y, domain='ZZ[alpha]') assert g.eval((z + 1)/(z - 1)) == Poly(result, y, domain='ZZ(alpha,z)') def test_Poly___call__(): f = Poly(2*x*y + 3*x + y + 2*z) assert f(2) == Poly(5*y + 2*z + 6) assert f(2, 5) == Poly(2*z + 31) assert f(2, 5, 7) == 45 def test_parallel_poly_from_expr(): assert parallel_poly_from_expr( [x - 1, x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [Poly(x - 1, x), x**2 - 1], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x - 1, Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr([Poly( x - 1, x), Poly(x**2 - 1, x)], x)[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x - 1, x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr([Poly( x - 1, x), x**2 - 1], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr([x - 1, Poly( x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr([Poly(x - 1, x), Poly( x**2 - 1, x)], x, y)[0] == [Poly(x - 1, x, y), Poly(x**2 - 1, x, y)] assert parallel_poly_from_expr( [x - 1, x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [Poly(x - 1, x), x**2 - 1])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x - 1, Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [Poly(x - 1, x), Poly(x**2 - 1, x)])[0] == [Poly(x - 1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, x**2 - 1])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [1, Poly(x**2 - 1, x)])[0] == [Poly(1, x), Poly(x**2 - 1, x)] assert parallel_poly_from_expr( [x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr( [x**2 - 1, 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr( [Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr( [Poly(x**2 - 1, x), 1])[0] == [Poly(x**2 - 1, x), Poly(1, x)] assert parallel_poly_from_expr([Poly(x, x, y), Poly(y, x, y)], x, y, order='lex')[0] == \ [Poly(x, x, y, domain='ZZ'), Poly(y, x, y, domain='ZZ')] raises(PolificationFailed, lambda: parallel_poly_from_expr([0, 1])) def test_pdiv(): f, g = x**2 - y**2, x - y q, r = x + y, 0 F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ] assert F.pdiv(G) == (Q, R) assert F.prem(G) == R assert F.pquo(G) == Q assert F.pexquo(G) == Q assert pdiv(f, g) == (q, r) assert prem(f, g) == r assert pquo(f, g) == q assert pexquo(f, g) == q assert pdiv(f, g, x, y) == (q, r) assert prem(f, g, x, y) == r assert pquo(f, g, x, y) == q assert pexquo(f, g, x, y) == q assert pdiv(f, g, (x, y)) == (q, r) assert prem(f, g, (x, y)) == r assert pquo(f, g, (x, y)) == q assert pexquo(f, g, (x, y)) == q assert pdiv(F, G) == (Q, R) assert prem(F, G) == R assert pquo(F, G) == Q assert pexquo(F, G) == Q assert pdiv(f, g, polys=True) == (Q, R) assert prem(f, g, polys=True) == R assert pquo(f, g, polys=True) == Q assert pexquo(f, g, polys=True) == Q assert pdiv(F, G, polys=False) == (q, r) assert prem(F, G, polys=False) == r assert pquo(F, G, polys=False) == q assert pexquo(F, G, polys=False) == q raises(ComputationFailed, lambda: pdiv(4, 2)) raises(ComputationFailed, lambda: prem(4, 2)) raises(ComputationFailed, lambda: pquo(4, 2)) raises(ComputationFailed, lambda: pexquo(4, 2)) def test_div(): f, g = x**2 - y**2, x - y q, r = x + y, 0 F, G, Q, R = [ Poly(h, x, y) for h in (f, g, q, r) ] assert F.div(G) == (Q, R) assert F.rem(G) == R assert F.quo(G) == Q assert F.exquo(G) == Q assert div(f, g) == (q, r) assert rem(f, g) == r assert quo(f, g) == q assert exquo(f, g) == q assert div(f, g, x, y) == (q, r) assert rem(f, g, x, y) == r assert quo(f, g, x, y) == q assert exquo(f, g, x, y) == q assert div(f, g, (x, y)) == (q, r) assert rem(f, g, (x, y)) == r assert quo(f, g, (x, y)) == q assert exquo(f, g, (x, y)) == q assert div(F, G) == (Q, R) assert rem(F, G) == R assert quo(F, G) == Q assert exquo(F, G) == Q assert div(f, g, polys=True) == (Q, R) assert rem(f, g, polys=True) == R assert quo(f, g, polys=True) == Q assert exquo(f, g, polys=True) == Q assert div(F, G, polys=False) == (q, r) assert rem(F, G, polys=False) == r assert quo(F, G, polys=False) == q assert exquo(F, G, polys=False) == q raises(ComputationFailed, lambda: div(4, 2)) raises(ComputationFailed, lambda: rem(4, 2)) raises(ComputationFailed, lambda: quo(4, 2)) raises(ComputationFailed, lambda: exquo(4, 2)) f, g = x**2 + 1, 2*x - 4 qz, rz = 0, x**2 + 1 qq, rq = x/2 + 1, 5 assert div(f, g) == (qq, rq) assert div(f, g, auto=True) == (qq, rq) assert div(f, g, auto=False) == (qz, rz) assert div(f, g, domain=ZZ) == (qz, rz) assert div(f, g, domain=QQ) == (qq, rq) assert div(f, g, domain=ZZ, auto=True) == (qq, rq) assert div(f, g, domain=ZZ, auto=False) == (qz, rz) assert div(f, g, domain=QQ, auto=True) == (qq, rq) assert div(f, g, domain=QQ, auto=False) == (qq, rq) assert rem(f, g) == rq assert rem(f, g, auto=True) == rq assert rem(f, g, auto=False) == rz assert rem(f, g, domain=ZZ) == rz assert rem(f, g, domain=QQ) == rq assert rem(f, g, domain=ZZ, auto=True) == rq assert rem(f, g, domain=ZZ, auto=False) == rz assert rem(f, g, domain=QQ, auto=True) == rq assert rem(f, g, domain=QQ, auto=False) == rq assert quo(f, g) == qq assert quo(f, g, auto=True) == qq assert quo(f, g, auto=False) == qz assert quo(f, g, domain=ZZ) == qz assert quo(f, g, domain=QQ) == qq assert quo(f, g, domain=ZZ, auto=True) == qq assert quo(f, g, domain=ZZ, auto=False) == qz assert quo(f, g, domain=QQ, auto=True) == qq assert quo(f, g, domain=QQ, auto=False) == qq f, g, q = x**2, 2*x, x/2 assert exquo(f, g) == q assert exquo(f, g, auto=True) == q raises(ExactQuotientFailed, lambda: exquo(f, g, auto=False)) raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ)) assert exquo(f, g, domain=QQ) == q assert exquo(f, g, domain=ZZ, auto=True) == q raises(ExactQuotientFailed, lambda: exquo(f, g, domain=ZZ, auto=False)) assert exquo(f, g, domain=QQ, auto=True) == q assert exquo(f, g, domain=QQ, auto=False) == q f, g = Poly(x**2), Poly(x) q, r = f.div(g) assert q.get_domain().is_ZZ and r.get_domain().is_ZZ r = f.rem(g) assert r.get_domain().is_ZZ q = f.quo(g) assert q.get_domain().is_ZZ q = f.exquo(g) assert q.get_domain().is_ZZ f, g = Poly(x+y, x), Poly(2*x+y, x) q, r = f.div(g) assert q.get_domain().is_Frac and r.get_domain().is_Frac # https://github.com/sympy/sympy/issues/19579 p = Poly(2+3*I, x, domain=ZZ_I) q = Poly(1-I, x, domain=ZZ_I) assert p.div(q, auto=False) == \ (Poly(0, x, domain='ZZ_I'), Poly(2 + 3*I, x, domain='ZZ_I')) assert p.div(q, auto=True) == \ (Poly(-S(1)/2 + 5*I/2, x, domain='QQ_I'), Poly(0, x, domain='QQ_I')) def test_issue_7864(): q, r = div(a, .408248290463863*a) assert abs(q - 2.44948974278318) < 1e-14 assert r == 0 def test_gcdex(): f, g = 2*x, x**2 - 16 s, t, h = x/32, Rational(-1, 16), 1 F, G, S, T, H = [ Poly(u, x, domain='QQ') for u in (f, g, s, t, h) ] assert F.half_gcdex(G) == (S, H) assert F.gcdex(G) == (S, T, H) assert F.invert(G) == S assert half_gcdex(f, g) == (s, h) assert gcdex(f, g) == (s, t, h) assert invert(f, g) == s assert half_gcdex(f, g, x) == (s, h) assert gcdex(f, g, x) == (s, t, h) assert invert(f, g, x) == s assert half_gcdex(f, g, (x,)) == (s, h) assert gcdex(f, g, (x,)) == (s, t, h) assert invert(f, g, (x,)) == s assert half_gcdex(F, G) == (S, H) assert gcdex(F, G) == (S, T, H) assert invert(F, G) == S assert half_gcdex(f, g, polys=True) == (S, H) assert gcdex(f, g, polys=True) == (S, T, H) assert invert(f, g, polys=True) == S assert half_gcdex(F, G, polys=False) == (s, h) assert gcdex(F, G, polys=False) == (s, t, h) assert invert(F, G, polys=False) == s assert half_gcdex(100, 2004) == (-20, 4) assert gcdex(100, 2004) == (-20, 1, 4) assert invert(3, 7) == 5 raises(DomainError, lambda: half_gcdex(x + 1, 2*x + 1, auto=False)) raises(DomainError, lambda: gcdex(x + 1, 2*x + 1, auto=False)) raises(DomainError, lambda: invert(x + 1, 2*x + 1, auto=False)) def test_revert(): f = Poly(1 - x**2/2 + x**4/24 - x**6/720) g = Poly(61*x**6/720 + 5*x**4/24 + x**2/2 + 1) assert f.revert(8) == g def test_subresultants(): f, g, h = x**2 - 2*x + 1, x**2 - 1, 2*x - 2 F, G, H = Poly(f), Poly(g), Poly(h) assert F.subresultants(G) == [F, G, H] assert subresultants(f, g) == [f, g, h] assert subresultants(f, g, x) == [f, g, h] assert subresultants(f, g, (x,)) == [f, g, h] assert subresultants(F, G) == [F, G, H] assert subresultants(f, g, polys=True) == [F, G, H] assert subresultants(F, G, polys=False) == [f, g, h] raises(ComputationFailed, lambda: subresultants(4, 2)) def test_resultant(): f, g, h = x**2 - 2*x + 1, x**2 - 1, 0 F, G = Poly(f), Poly(g) assert F.resultant(G) == h assert resultant(f, g) == h assert resultant(f, g, x) == h assert resultant(f, g, (x,)) == h assert resultant(F, G) == h assert resultant(f, g, polys=True) == h assert resultant(F, G, polys=False) == h assert resultant(f, g, includePRS=True) == (h, [f, g, 2*x - 2]) f, g, h = x - a, x - b, a - b F, G, H = Poly(f), Poly(g), Poly(h) assert F.resultant(G) == H assert resultant(f, g) == h assert resultant(f, g, x) == h assert resultant(f, g, (x,)) == h assert resultant(F, G) == H assert resultant(f, g, polys=True) == H assert resultant(F, G, polys=False) == h raises(ComputationFailed, lambda: resultant(4, 2)) def test_discriminant(): f, g = x**3 + 3*x**2 + 9*x - 13, -11664 F = Poly(f) assert F.discriminant() == g assert discriminant(f) == g assert discriminant(f, x) == g assert discriminant(f, (x,)) == g assert discriminant(F) == g assert discriminant(f, polys=True) == g assert discriminant(F, polys=False) == g f, g = a*x**2 + b*x + c, b**2 - 4*a*c F, G = Poly(f), Poly(g) assert F.discriminant() == G assert discriminant(f) == g assert discriminant(f, x, a, b, c) == g assert discriminant(f, (x, a, b, c)) == g assert discriminant(F) == G assert discriminant(f, polys=True) == G assert discriminant(F, polys=False) == g raises(ComputationFailed, lambda: discriminant(4)) def test_dispersion(): # We test only the API here. For more mathematical # tests see the dedicated test file. fp = poly((x + 1)*(x + 2), x) assert sorted(fp.dispersionset()) == [0, 1] assert fp.dispersion() == 1 fp = poly(x**4 - 3*x**2 + 1, x) gp = fp.shift(-3) assert sorted(fp.dispersionset(gp)) == [2, 3, 4] assert fp.dispersion(gp) == 4 def test_gcd_list(): F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2] assert gcd_list(F) == x - 1 assert gcd_list(F, polys=True) == Poly(x - 1) assert gcd_list([]) == 0 assert gcd_list([1, 2]) == 1 assert gcd_list([4, 6, 8]) == 2 assert gcd_list([x*(y + 42) - x*y - x*42]) == 0 gcd = gcd_list([], x) assert gcd.is_Number and gcd is S.Zero gcd = gcd_list([], x, polys=True) assert gcd.is_Poly and gcd.is_zero a = sqrt(2) assert gcd_list([a, -a]) == gcd_list([-a, a]) == a raises(ComputationFailed, lambda: gcd_list([], polys=True)) def test_lcm_list(): F = [x**3 - 1, x**2 - 1, x**2 - 3*x + 2] assert lcm_list(F) == x**5 - x**4 - 2*x**3 - x**2 + x + 2 assert lcm_list(F, polys=True) == Poly(x**5 - x**4 - 2*x**3 - x**2 + x + 2) assert lcm_list([]) == 1 assert lcm_list([1, 2]) == 2 assert lcm_list([4, 6, 8]) == 24 assert lcm_list([x*(y + 42) - x*y - x*42]) == 0 lcm = lcm_list([], x) assert lcm.is_Number and lcm is S.One lcm = lcm_list([], x, polys=True) assert lcm.is_Poly and lcm.is_one raises(ComputationFailed, lambda: lcm_list([], polys=True)) def test_gcd(): f, g = x**3 - 1, x**2 - 1 s, t = x**2 + x + 1, x + 1 h, r = x - 1, x**4 + x**3 - x - 1 F, G, S, T, H, R = [ Poly(u) for u in (f, g, s, t, h, r) ] assert F.cofactors(G) == (H, S, T) assert F.gcd(G) == H assert F.lcm(G) == R assert cofactors(f, g) == (h, s, t) assert gcd(f, g) == h assert lcm(f, g) == r assert cofactors(f, g, x) == (h, s, t) assert gcd(f, g, x) == h assert lcm(f, g, x) == r assert cofactors(f, g, (x,)) == (h, s, t) assert gcd(f, g, (x,)) == h assert lcm(f, g, (x,)) == r assert cofactors(F, G) == (H, S, T) assert gcd(F, G) == H assert lcm(F, G) == R assert cofactors(f, g, polys=True) == (H, S, T) assert gcd(f, g, polys=True) == H assert lcm(f, g, polys=True) == R assert cofactors(F, G, polys=False) == (h, s, t) assert gcd(F, G, polys=False) == h assert lcm(F, G, polys=False) == r f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0 h, s, t = g, 1.0*x + 1.0, 1.0 assert cofactors(f, g) == (h, s, t) assert gcd(f, g) == h assert lcm(f, g) == f f, g = 1.0*x**2 - 1.0, 1.0*x - 1.0 h, s, t = g, 1.0*x + 1.0, 1.0 assert cofactors(f, g) == (h, s, t) assert gcd(f, g) == h assert lcm(f, g) == f assert cofactors(8, 6) == (2, 4, 3) assert gcd(8, 6) == 2 assert lcm(8, 6) == 24 f, g = x**2 - 3*x - 4, x**3 - 4*x**2 + x - 4 l = x**4 - 3*x**3 - 3*x**2 - 3*x - 4 h, s, t = x - 4, x + 1, x**2 + 1 assert cofactors(f, g, modulus=11) == (h, s, t) assert gcd(f, g, modulus=11) == h assert lcm(f, g, modulus=11) == l f, g = x**2 + 8*x + 7, x**3 + 7*x**2 + x + 7 l = x**4 + 8*x**3 + 8*x**2 + 8*x + 7 h, s, t = x + 7, x + 1, x**2 + 1 assert cofactors(f, g, modulus=11, symmetric=False) == (h, s, t) assert gcd(f, g, modulus=11, symmetric=False) == h assert lcm(f, g, modulus=11, symmetric=False) == l a, b = sqrt(2), -sqrt(2) assert gcd(a, b) == gcd(b, a) == sqrt(2) a, b = sqrt(-2), -sqrt(-2) assert gcd(a, b) == gcd(b, a) == sqrt(2) assert gcd(Poly(x - 2, x), Poly(I*x, x)) == Poly(1, x, domain=ZZ_I) raises(TypeError, lambda: gcd(x)) raises(TypeError, lambda: lcm(x)) def test_gcd_numbers_vs_polys(): assert isinstance(gcd(3, 9), Integer) assert isinstance(gcd(3*x, 9), Integer) assert gcd(3, 9) == 3 assert gcd(3*x, 9) == 3 assert isinstance(gcd(Rational(3, 2), Rational(9, 4)), Rational) assert isinstance(gcd(Rational(3, 2)*x, Rational(9, 4)), Rational) assert gcd(Rational(3, 2), Rational(9, 4)) == Rational(3, 4) assert gcd(Rational(3, 2)*x, Rational(9, 4)) == 1 assert isinstance(gcd(3.0, 9.0), Float) assert isinstance(gcd(3.0*x, 9.0), Float) assert gcd(3.0, 9.0) == 1.0 assert gcd(3.0*x, 9.0) == 1.0 # partial fix of 20597 assert gcd(Mul(2, 3, evaluate=False), 2) == 2 def test_terms_gcd(): assert terms_gcd(1) == 1 assert terms_gcd(1, x) == 1 assert terms_gcd(x - 1) == x - 1 assert terms_gcd(-x - 1) == -x - 1 assert terms_gcd(2*x + 3) == 2*x + 3 assert terms_gcd(6*x + 4) == Mul(2, 3*x + 2, evaluate=False) assert terms_gcd(x**3*y + x*y**3) == x*y*(x**2 + y**2) assert terms_gcd(2*x**3*y + 2*x*y**3) == 2*x*y*(x**2 + y**2) assert terms_gcd(x**3*y/2 + x*y**3/2) == x*y/2*(x**2 + y**2) assert terms_gcd(x**3*y + 2*x*y**3) == x*y*(x**2 + 2*y**2) assert terms_gcd(2*x**3*y + 4*x*y**3) == 2*x*y*(x**2 + 2*y**2) assert terms_gcd(2*x**3*y/3 + 4*x*y**3/5) == x*y*Rational(2, 15)*(5*x**2 + 6*y**2) assert terms_gcd(2.0*x**3*y + 4.1*x*y**3) == x*y*(2.0*x**2 + 4.1*y**2) assert _aresame(terms_gcd(2.0*x + 3), 2.0*x + 3) assert terms_gcd((3 + 3*x)*(x + x*y), expand=False) == \ (3*x + 3)*(x*y + x) assert terms_gcd((3 + 3*x)*(x + x*sin(3 + 3*y)), expand=False, deep=True) == \ 3*x*(x + 1)*(sin(Mul(3, y + 1, evaluate=False)) + 1) assert terms_gcd(sin(x + x*y), deep=True) == \ sin(x*(y + 1)) eq = Eq(2*x, 2*y + 2*z*y) assert terms_gcd(eq) == Eq(2*x, 2*y*(z + 1)) assert terms_gcd(eq, deep=True) == Eq(2*x, 2*y*(z + 1)) raises(TypeError, lambda: terms_gcd(x < 2)) def test_trunc(): f, g = x**5 + 2*x**4 + 3*x**3 + 4*x**2 + 5*x + 6, x**5 - x**4 + x**2 - x F, G = Poly(f), Poly(g) assert F.trunc(3) == G assert trunc(f, 3) == g assert trunc(f, 3, x) == g assert trunc(f, 3, (x,)) == g assert trunc(F, 3) == G assert trunc(f, 3, polys=True) == G assert trunc(F, 3, polys=False) == g f, g = 6*x**5 + 5*x**4 + 4*x**3 + 3*x**2 + 2*x + 1, -x**4 + x**3 - x + 1 F, G = Poly(f), Poly(g) assert F.trunc(3) == G assert trunc(f, 3) == g assert trunc(f, 3, x) == g assert trunc(f, 3, (x,)) == g assert trunc(F, 3) == G assert trunc(f, 3, polys=True) == G assert trunc(F, 3, polys=False) == g f = Poly(x**2 + 2*x + 3, modulus=5) assert f.trunc(2) == Poly(x**2 + 1, modulus=5) def test_monic(): f, g = 2*x - 1, x - S.Half F, G = Poly(f, domain='QQ'), Poly(g) assert F.monic() == G assert monic(f) == g assert monic(f, x) == g assert monic(f, (x,)) == g assert monic(F) == G assert monic(f, polys=True) == G assert monic(F, polys=False) == g raises(ComputationFailed, lambda: monic(4)) assert monic(2*x**2 + 6*x + 4, auto=False) == x**2 + 3*x + 2 raises(ExactQuotientFailed, lambda: monic(2*x + 6*x + 1, auto=False)) assert monic(2.0*x**2 + 6.0*x + 4.0) == 1.0*x**2 + 3.0*x + 2.0 assert monic(2*x**2 + 3*x + 4, modulus=5) == x**2 - x + 2 def test_content(): f, F = 4*x + 2, Poly(4*x + 2) assert F.content() == 2 assert content(f) == 2 raises(ComputationFailed, lambda: content(4)) f = Poly(2*x, modulus=3) assert f.content() == 1 def test_primitive(): f, g = 4*x + 2, 2*x + 1 F, G = Poly(f), Poly(g) assert F.primitive() == (2, G) assert primitive(f) == (2, g) assert primitive(f, x) == (2, g) assert primitive(f, (x,)) == (2, g) assert primitive(F) == (2, G) assert primitive(f, polys=True) == (2, G) assert primitive(F, polys=False) == (2, g) raises(ComputationFailed, lambda: primitive(4)) f = Poly(2*x, modulus=3) g = Poly(2.0*x, domain=RR) assert f.primitive() == (1, f) assert g.primitive() == (1.0, g) assert primitive(S('-3*x/4 + y + 11/8')) == \ S('(1/8, -6*x + 8*y + 11)') def test_compose(): 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 F, G, H = map(Poly, (f, g, h)) assert G.compose(H) == F assert compose(g, h) == f assert compose(g, h, x) == f assert compose(g, h, (x,)) == f assert compose(G, H) == F assert compose(g, h, polys=True) == F assert compose(G, H, polys=False) == f assert F.decompose() == [G, H] assert decompose(f) == [g, h] assert decompose(f, x) == [g, h] assert decompose(f, (x,)) == [g, h] assert decompose(F) == [G, H] assert decompose(f, polys=True) == [G, H] assert decompose(F, polys=False) == [g, h] raises(ComputationFailed, lambda: compose(4, 2)) raises(ComputationFailed, lambda: decompose(4)) assert compose(x**2 - y**2, x - y, x, y) == x**2 - 2*x*y assert compose(x**2 - y**2, x - y, y, x) == -y**2 + 2*x*y def test_shift(): assert Poly(x**2 - 2*x + 1, x).shift(2) == Poly(x**2 + 2*x + 1, x) def test_transform(): # Also test that 3-way unification is done correctly assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \ Poly(4, x) == \ cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - 1))) assert Poly(x**2 - x/2 + 1, x).transform(Poly(x + 1), Poly(x - 1)) == \ Poly(3*x**2/2 + Rational(5, 2), x) == \ cancel((x - 1)**2*(x**2 - x/2 + 1).subs(x, (x + 1)/(x - 1))) assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + S.Half), Poly(x - 1)) == \ Poly(Rational(9, 4), x) == \ cancel((x - 1)**2*(x**2 - 2*x + 1).subs(x, (x + S.Half)/(x - 1))) assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1), Poly(x - S.Half)) == \ Poly(Rational(9, 4), x) == \ cancel((x - S.Half)**2*(x**2 - 2*x + 1).subs(x, (x + 1)/(x - S.Half))) # Unify ZZ, QQ, and RR assert Poly(x**2 - 2*x + 1, x).transform(Poly(x + 1.0), Poly(x - S.Half)) == \ Poly(Rational(9, 4), x, domain='RR') == \ cancel((x - S.Half)**2*(x**2 - 2*x + 1).subs(x, (x + 1.0)/(x - S.Half))) raises(ValueError, lambda: Poly(x*y).transform(Poly(x + 1), Poly(x - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(y + 1), Poly(x - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(y - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(x*y + 1), Poly(x - 1))) raises(ValueError, lambda: Poly(x).transform(Poly(x + 1), Poly(x*y - 1))) def test_sturm(): f, F = x, Poly(x, domain='QQ') g, G = 1, Poly(1, x, domain='QQ') assert F.sturm() == [F, G] assert sturm(f) == [f, g] assert sturm(f, x) == [f, g] assert sturm(f, (x,)) == [f, g] assert sturm(F) == [F, G] assert sturm(f, polys=True) == [F, G] assert sturm(F, polys=False) == [f, g] raises(ComputationFailed, lambda: sturm(4)) raises(DomainError, lambda: sturm(f, auto=False)) f = Poly(S(1024)/(15625*pi**8)*x**5 - S(4096)/(625*pi**8)*x**4 + S(32)/(15625*pi**4)*x**3 - S(128)/(625*pi**4)*x**2 + Rational(1, 62500)*x - Rational(1, 625), x, domain='ZZ(pi)') assert sturm(f) == \ [Poly(x**3 - 100*x**2 + pi**4/64*x - 25*pi**4/16, x, domain='ZZ(pi)'), Poly(3*x**2 - 200*x + pi**4/64, x, domain='ZZ(pi)'), Poly((Rational(20000, 9) - pi**4/96)*x + 25*pi**4/18, x, domain='ZZ(pi)'), Poly((-3686400000000*pi**4 - 11520000*pi**8 - 9*pi**12)/(26214400000000 - 245760000*pi**4 + 576*pi**8), x, domain='ZZ(pi)')] def test_gff(): f = x**5 + 2*x**4 - x**3 - 2*x**2 assert Poly(f).gff_list() == [(Poly(x), 1), (Poly(x + 2), 4)] assert gff_list(f) == [(x, 1), (x + 2, 4)] raises(NotImplementedError, lambda: gff(f)) f = x*(x - 1)**3*(x - 2)**2*(x - 4)**2*(x - 5) assert Poly(f).gff_list() == [( Poly(x**2 - 5*x + 4), 1), (Poly(x**2 - 5*x + 4), 2), (Poly(x), 3)] assert gff_list(f) == [(x**2 - 5*x + 4, 1), (x**2 - 5*x + 4, 2), (x, 3)] raises(NotImplementedError, lambda: gff(f)) def test_norm(): a, b = sqrt(2), sqrt(3) f = Poly(a*x + b*y, x, y, extension=(a, b)) assert f.norm() == Poly(4*x**4 - 12*x**2*y**2 + 9*y**4, x, y, domain='QQ') def test_sqf_norm(): assert sqf_norm(x**2 - 2, extension=sqrt(3)) == \ (1, x**2 - 2*sqrt(3)*x + 1, x**4 - 10*x**2 + 1) assert sqf_norm(x**2 - 3, extension=sqrt(2)) == \ (1, x**2 - 2*sqrt(2)*x - 1, x**4 - 10*x**2 + 1) assert Poly(x**2 - 2, extension=sqrt(3)).sqf_norm() == \ (1, Poly(x**2 - 2*sqrt(3)*x + 1, x, extension=sqrt(3)), Poly(x**4 - 10*x**2 + 1, x, domain='QQ')) assert Poly(x**2 - 3, extension=sqrt(2)).sqf_norm() == \ (1, Poly(x**2 - 2*sqrt(2)*x - 1, x, extension=sqrt(2)), Poly(x**4 - 10*x**2 + 1, x, domain='QQ')) def test_sqf(): 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 F, G, H, P = map(Poly, (f, g, h, p)) assert F.sqf_part() == P assert sqf_part(f) == p assert sqf_part(f, x) == p assert sqf_part(f, (x,)) == p assert sqf_part(F) == P assert sqf_part(f, polys=True) == P assert sqf_part(F, polys=False) == p assert F.sqf_list() == (1, [(G, 1), (H, 2)]) assert sqf_list(f) == (1, [(g, 1), (h, 2)]) assert sqf_list(f, x) == (1, [(g, 1), (h, 2)]) assert sqf_list(f, (x,)) == (1, [(g, 1), (h, 2)]) assert sqf_list(F) == (1, [(G, 1), (H, 2)]) assert sqf_list(f, polys=True) == (1, [(G, 1), (H, 2)]) assert sqf_list(F, polys=False) == (1, [(g, 1), (h, 2)]) assert F.sqf_list_include() == [(G, 1), (H, 2)] raises(ComputationFailed, lambda: sqf_part(4)) assert sqf(1) == 1 assert sqf_list(1) == (1, []) assert sqf((2*x**2 + 2)**7) == 128*(x**2 + 1)**7 assert sqf(f) == g*h**2 assert sqf(f, x) == g*h**2 assert sqf(f, (x,)) == g*h**2 d = x**2 + y**2 assert sqf(f/d) == (g*h**2)/d assert sqf(f/d, x) == (g*h**2)/d assert sqf(f/d, (x,)) == (g*h**2)/d assert sqf(x - 1) == x - 1 assert sqf(-x - 1) == -x - 1 assert sqf(x - 1) == x - 1 assert sqf(6*x - 10) == Mul(2, 3*x - 5, evaluate=False) assert sqf((6*x - 10)/(3*x - 6)) == Rational(2, 3)*((3*x - 5)/(x - 2)) assert sqf(Poly(x**2 - 2*x + 1)) == (x - 1)**2 f = 3 + x - x*(1 + x) + x**2 assert sqf(f) == 3 f = (x**2 + 2*x + 1)**20000000000 assert sqf(f) == (x + 1)**40000000000 assert sqf_list(f) == (1, [(x + 1, 40000000000)]) def test_factor(): f = x**5 - x**3 - x**2 + 1 u = x + 1 v = x - 1 w = x**2 + x + 1 F, U, V, W = map(Poly, (f, u, v, w)) assert F.factor_list() == (1, [(U, 1), (V, 2), (W, 1)]) assert factor_list(f) == (1, [(u, 1), (v, 2), (w, 1)]) assert factor_list(f, x) == (1, [(u, 1), (v, 2), (w, 1)]) assert factor_list(f, (x,)) == (1, [(u, 1), (v, 2), (w, 1)]) assert factor_list(F) == (1, [(U, 1), (V, 2), (W, 1)]) assert factor_list(f, polys=True) == (1, [(U, 1), (V, 2), (W, 1)]) assert factor_list(F, polys=False) == (1, [(u, 1), (v, 2), (w, 1)]) assert F.factor_list_include() == [(U, 1), (V, 2), (W, 1)] assert factor_list(1) == (1, []) assert factor_list(6) == (6, []) assert factor_list(sqrt(3), x) == (sqrt(3), []) assert factor_list((-1)**x, x) == (1, [(-1, x)]) assert factor_list((2*x)**y, x) == (1, [(2, y), (x, y)]) assert factor_list(sqrt(x*y), x) == (1, [(x*y, S.Half)]) assert factor(6) == 6 and factor(6).is_Integer assert factor_list(3*x) == (3, [(x, 1)]) assert factor_list(3*x**2) == (3, [(x, 2)]) assert factor(3*x) == 3*x assert factor(3*x**2) == 3*x**2 assert factor((2*x**2 + 2)**7) == 128*(x**2 + 1)**7 assert factor(f) == u*v**2*w assert factor(f, x) == u*v**2*w assert factor(f, (x,)) == u*v**2*w g, p, q, r = x**2 - y**2, x - y, x + y, x**2 + 1 assert factor(f/g) == (u*v**2*w)/(p*q) assert factor(f/g, x) == (u*v**2*w)/(p*q) assert factor(f/g, (x,)) == (u*v**2*w)/(p*q) p = Symbol('p', positive=True) i = Symbol('i', integer=True) r = Symbol('r', real=True) assert factor(sqrt(x*y)).is_Pow is True assert factor(sqrt(3*x**2 - 3)) == sqrt(3)*sqrt((x - 1)*(x + 1)) assert factor(sqrt(3*x**2 + 3)) == sqrt(3)*sqrt(x**2 + 1) assert factor((y*x**2 - y)**i) == y**i*(x - 1)**i*(x + 1)**i assert factor((y*x**2 + y)**i) == y**i*(x**2 + 1)**i assert factor((y*x**2 - y)**t) == (y*(x - 1)*(x + 1))**t assert factor((y*x**2 + y)**t) == (y*(x**2 + 1))**t f = sqrt(expand((r**2 + 1)*(p + 1)*(p - 1)*(p - 2)**3)) g = sqrt((p - 2)**3*(p - 1))*sqrt(p + 1)*sqrt(r**2 + 1) assert factor(f) == g assert factor(g) == g g = (x - 1)**5*(r**2 + 1) f = sqrt(expand(g)) assert factor(f) == sqrt(g) f = Poly(sin(1)*x + 1, x, domain=EX) assert f.factor_list() == (1, [(f, 1)]) f = x**4 + 1 assert factor(f) == f assert factor(f, extension=I) == (x**2 - I)*(x**2 + I) assert factor(f, gaussian=True) == (x**2 - I)*(x**2 + I) assert factor( f, extension=sqrt(2)) == (x**2 + sqrt(2)*x + 1)*(x**2 - sqrt(2)*x + 1) assert factor(x**2 + 4*I*x - 4) == (x + 2*I)**2 f = x**2 + 2*I*x - 4 assert factor(f) == f f = 8192*x**2 + x*(22656 + 175232*I) - 921416 + 242313*I f_zzi = I*(x*(64 - 64*I) + 773 + 596*I)**2 f_qqi = 8192*(x + S(177)/128 + 1369*I/128)**2 assert factor(f) == f_zzi assert factor(f, domain=ZZ_I) == f_zzi assert factor(f, domain=QQ_I) == f_qqi f = x**2 + 2*sqrt(2)*x + 2 assert factor(f, extension=sqrt(2)) == (x + sqrt(2))**2 assert factor(f**3, extension=sqrt(2)) == (x + sqrt(2))**6 assert factor(x**2 - 2*y**2, extension=sqrt(2)) == \ (x + sqrt(2)*y)*(x - sqrt(2)*y) assert factor(2*x**2 - 4*y**2, extension=sqrt(2)) == \ 2*((x + sqrt(2)*y)*(x - sqrt(2)*y)) assert factor(x - 1) == x - 1 assert factor(-x - 1) == -x - 1 assert factor(x - 1) == x - 1 assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False) assert factor(x**11 + x + 1, modulus=65537, symmetric=True) == \ (x**2 + x + 1)*(x**9 - x**8 + x**6 - x**5 + x**3 - x** 2 + 1) assert factor(x**11 + x + 1, modulus=65537, symmetric=False) == \ (x**2 + x + 1)*(x**9 + 65536*x**8 + x**6 + 65536*x**5 + x**3 + 65536*x** 2 + 1) f = x/pi + x*sin(x)/pi g = y/(pi**2 + 2*pi + 1) + y*sin(x)/(pi**2 + 2*pi + 1) assert factor(f) == x*(sin(x) + 1)/pi assert factor(g) == y*(sin(x) + 1)/(pi + 1)**2 assert factor(Eq( x**2 + 2*x + 1, x**3 + 1)) == Eq((x + 1)**2, (x + 1)*(x**2 - x + 1)) f = (x**2 - 1)/(x**2 + 4*x + 4) assert factor(f) == (x + 1)*(x - 1)/(x + 2)**2 assert factor(f, x) == (x + 1)*(x - 1)/(x + 2)**2 f = 3 + x - x*(1 + x) + x**2 assert factor(f) == 3 assert factor(f, x) == 3 assert factor(1/(x**2 + 2*x + 1/x) - 1) == -((1 - x + 2*x**2 + x**3)/(1 + 2*x**2 + x**3)) assert factor(f, expand=False) == f raises(PolynomialError, lambda: factor(f, x, expand=False)) raises(FlagError, lambda: factor(x**2 - 1, polys=True)) assert factor([x, Eq(x**2 - y**2, Tuple(x**2 - z**2, 1/x + 1/y))]) == \ [x, Eq((x - y)*(x + y), Tuple((x - z)*(x + z), (x + y)/x/y))] assert not isinstance( Poly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True assert isinstance( PurePoly(x**3 + x + 1).factor_list()[1][0][0], PurePoly) is True assert factor(sqrt(-x)) == sqrt(-x) # issue 5917 e = (-2*x*(-x + 1)*(x - 1)*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2)*(x**2*(x - 1) - x*(x - 1) - x) - (-2*x**2*(x - 1)**2 - x*(-x + 1)*(-x*(-x + 1) + x*(x - 1)))*(x**2*(x - 1)**4 - x*(-x*(-x + 1)*(x - 1) - x*(x - 1)**2))) assert factor(e) == 0 # deep option assert factor(sin(x**2 + x) + x, deep=True) == sin(x*(x + 1)) + x assert factor(sin(x**2 + x)*x, deep=True) == sin(x*(x + 1))*x assert factor(sqrt(x**2)) == sqrt(x**2) # issue 13149 assert factor(expand((0.5*x+1)*(0.5*y+1))) == Mul(1.0, 0.5*x + 1.0, 0.5*y + 1.0, evaluate = False) assert factor(expand((0.5*x+0.5)**2)) == 0.25*(1.0*x + 1.0)**2 eq = x**2*y**2 + 11*x**2*y + 30*x**2 + 7*x*y**2 + 77*x*y + 210*x + 12*y**2 + 132*y + 360 assert factor(eq, x) == (x + 3)*(x + 4)*(y**2 + 11*y + 30) assert factor(eq, x, deep=True) == (x + 3)*(x + 4)*(y**2 + 11*y + 30) assert factor(eq, y, deep=True) == (y + 5)*(y + 6)*(x**2 + 7*x + 12) # fraction option f = 5*x + 3*exp(2 - 7*x) assert factor(f, deep=True) == factor(f, deep=True, fraction=True) assert factor(f, deep=True, fraction=False) == 5*x + 3*exp(2)*exp(-7*x) def test_factor_large(): f = (x**2 + 4*x + 4)**10000000*(x**2 + 1)*(x**2 + 2*x + 1)**1234567 g = ((x**2 + 2*x + 1)**3000*y**2 + (x**2 + 2*x + 1)**3000*2*y + ( x**2 + 2*x + 1)**3000) assert factor(f) == (x + 2)**20000000*(x**2 + 1)*(x + 1)**2469134 assert factor(g) == (x + 1)**6000*(y + 1)**2 assert factor_list( f) == (1, [(x + 1, 2469134), (x + 2, 20000000), (x**2 + 1, 1)]) assert factor_list(g) == (1, [(y + 1, 2), (x + 1, 6000)]) f = (x**2 - y**2)**200000*(x**7 + 1) g = (x**2 + y**2)**200000*(x**7 + 1) assert factor(f) == \ (x + 1)*(x - y)**200000*(x + y)**200000*(x**6 - x**5 + x**4 - x**3 + x**2 - x + 1) assert factor(g, gaussian=True) == \ (x + 1)*(x - I*y)**200000*(x + I*y)**200000*(x**6 - x**5 + x**4 - x**3 + x**2 - x + 1) assert factor_list(f) == \ (1, [(x + 1, 1), (x - y, 200000), (x + y, 200000), (x**6 - x**5 + x**4 - x**3 + x**2 - x + 1, 1)]) assert factor_list(g, gaussian=True) == \ (1, [(x + 1, 1), (x - I*y, 200000), (x + I*y, 200000), ( x**6 - x**5 + x**4 - x**3 + x**2 - x + 1, 1)]) def test_factor_noeval(): assert factor(6*x - 10) == Mul(2, 3*x - 5, evaluate=False) assert factor((6*x - 10)/(3*x - 6)) == Mul(Rational(2, 3), 3*x - 5, 1/(x - 2)) def test_intervals(): assert intervals(0) == [] assert intervals(1) == [] assert intervals(x, sqf=True) == [(0, 0)] assert intervals(x) == [((0, 0), 1)] assert intervals(x**128) == [((0, 0), 128)] assert intervals([x**2, x**4]) == [((0, 0), {0: 2, 1: 4})] f = Poly((x*Rational(2, 5) - Rational(17, 3))*(4*x + Rational(1, 257))) assert f.intervals(sqf=True) == [(-1, 0), (14, 15)] assert f.intervals() == [((-1, 0), 1), ((14, 15), 1)] assert f.intervals(fast=True, sqf=True) == [(-1, 0), (14, 15)] assert f.intervals(fast=True) == [((-1, 0), 1), ((14, 15), 1)] assert f.intervals(eps=Rational(1, 10)) == f.intervals(eps=0.1) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert f.intervals(eps=Rational(1, 100)) == f.intervals(eps=0.01) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert f.intervals(eps=Rational(1, 1000)) == f.intervals(eps=0.001) == \ [((Rational(-1, 1002), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert f.intervals(eps=Rational(1, 10000)) == f.intervals(eps=0.0001) == \ [((Rational(-1, 1028), Rational(-1, 1028)), 1), ((Rational(85, 6), Rational(85, 6)), 1)] f = (x*Rational(2, 5) - Rational(17, 3))*(4*x + Rational(1, 257)) assert intervals(f, sqf=True) == [(-1, 0), (14, 15)] assert intervals(f) == [((-1, 0), 1), ((14, 15), 1)] assert intervals(f, eps=Rational(1, 10)) == intervals(f, eps=0.1) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert intervals(f, eps=Rational(1, 100)) == intervals(f, eps=0.01) == \ [((Rational(-1, 258), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert intervals(f, eps=Rational(1, 1000)) == intervals(f, eps=0.001) == \ [((Rational(-1, 1002), 0), 1), ((Rational(85, 6), Rational(85, 6)), 1)] assert intervals(f, eps=Rational(1, 10000)) == intervals(f, eps=0.0001) == \ [((Rational(-1, 1028), Rational(-1, 1028)), 1), ((Rational(85, 6), Rational(85, 6)), 1)] f = Poly((x**2 - 2)*(x**2 - 3)**7*(x + 1)*(7*x + 3)**3) assert f.intervals() == \ [((-2, Rational(-3, 2)), 7), ((Rational(-3, 2), -1), 1), ((-1, -1), 1), ((-1, 0), 3), ((1, Rational(3, 2)), 1), ((Rational(3, 2), 2), 7)] assert intervals([x**5 - 200, x**5 - 201]) == \ [((Rational(75, 26), Rational(101, 35)), {0: 1}), ((Rational(309, 107), Rational(26, 9)), {1: 1})] assert intervals([x**5 - 200, x**5 - 201], fast=True) == \ [((Rational(75, 26), Rational(101, 35)), {0: 1}), ((Rational(309, 107), Rational(26, 9)), {1: 1})] assert intervals([x**2 - 200, x**2 - 201]) == \ [((Rational(-71, 5), Rational(-85, 6)), {1: 1}), ((Rational(-85, 6), -14), {0: 1}), ((14, Rational(85, 6)), {0: 1}), ((Rational(85, 6), Rational(71, 5)), {1: 1})] assert intervals([x + 1, x + 2, x - 1, x + 1, 1, x - 1, x - 1, (x - 2)**2]) == \ [((-2, -2), {1: 1}), ((-1, -1), {0: 1, 3: 1}), ((1, 1), {2: 1, 5: 1, 6: 1}), ((2, 2), {7: 2})] f, g, h = x**2 - 2, x**4 - 4*x**2 + 4, x - 1 assert intervals(f, inf=Rational(7, 4), sqf=True) == [] assert intervals(f, inf=Rational(7, 5), sqf=True) == [(Rational(7, 5), Rational(3, 2))] assert intervals(f, sup=Rational(7, 4), sqf=True) == [(-2, -1), (1, Rational(3, 2))] assert intervals(f, sup=Rational(7, 5), sqf=True) == [(-2, -1)] assert intervals(g, inf=Rational(7, 4)) == [] assert intervals(g, inf=Rational(7, 5)) == [((Rational(7, 5), Rational(3, 2)), 2)] assert intervals(g, sup=Rational(7, 4)) == [((-2, -1), 2), ((1, Rational(3, 2)), 2)] assert intervals(g, sup=Rational(7, 5)) == [((-2, -1), 2)] assert intervals([g, h], inf=Rational(7, 4)) == [] assert intervals([g, h], inf=Rational(7, 5)) == [((Rational(7, 5), Rational(3, 2)), {0: 2})] assert intervals([g, h], sup=S( 7)/4) == [((-2, -1), {0: 2}), ((1, 1), {1: 1}), ((1, Rational(3, 2)), {0: 2})] assert intervals( [g, h], sup=Rational(7, 5)) == [((-2, -1), {0: 2}), ((1, 1), {1: 1})] assert intervals([x + 2, x**2 - 2]) == \ [((-2, -2), {0: 1}), ((-2, -1), {1: 1}), ((1, 2), {1: 1})] assert intervals([x + 2, x**2 - 2], strict=True) == \ [((-2, -2), {0: 1}), ((Rational(-3, 2), -1), {1: 1}), ((1, 2), {1: 1})] f = 7*z**4 - 19*z**3 + 20*z**2 + 17*z + 20 assert intervals(f) == [] real_part, complex_part = intervals(f, all=True, sqf=True) assert real_part == [] assert all(re(a) < re(r) < re(b) and im( a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f))) assert complex_part == [(Rational(-40, 7) - I*Rational(40, 7), 0), (Rational(-40, 7), I*Rational(40, 7)), (I*Rational(-40, 7), Rational(40, 7)), (0, Rational(40, 7) + I*Rational(40, 7))] real_part, complex_part = intervals(f, all=True, sqf=True, eps=Rational(1, 10)) assert real_part == [] assert all(re(a) < re(r) < re(b) and im( a) < im(r) < im(b) for (a, b), r in zip(complex_part, nroots(f))) raises(ValueError, lambda: intervals(x**2 - 2, eps=10**-100000)) raises(ValueError, lambda: Poly(x**2 - 2).intervals(eps=10**-100000)) raises( ValueError, lambda: intervals([x**2 - 2, x**2 - 3], eps=10**-100000)) def test_refine_root(): f = Poly(x**2 - 2) assert f.refine_root(1, 2, steps=0) == (1, 2) assert f.refine_root(-2, -1, steps=0) == (-2, -1) assert f.refine_root(1, 2, steps=None) == (1, Rational(3, 2)) assert f.refine_root(-2, -1, steps=None) == (Rational(-3, 2), -1) assert f.refine_root(1, 2, steps=1) == (1, Rational(3, 2)) assert f.refine_root(-2, -1, steps=1) == (Rational(-3, 2), -1) assert f.refine_root(1, 2, steps=1, fast=True) == (1, Rational(3, 2)) assert f.refine_root(-2, -1, steps=1, fast=True) == (Rational(-3, 2), -1) assert f.refine_root(1, 2, eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12)) assert f.refine_root(1, 2, eps=1e-2) == (Rational(24, 17), Rational(17, 12)) raises(PolynomialError, lambda: (f**2).refine_root(1, 2, check_sqf=True)) raises(RefinementFailed, lambda: (f**2).refine_root(1, 2)) raises(RefinementFailed, lambda: (f**2).refine_root(2, 3)) f = x**2 - 2 assert refine_root(f, 1, 2, steps=1) == (1, Rational(3, 2)) assert refine_root(f, -2, -1, steps=1) == (Rational(-3, 2), -1) assert refine_root(f, 1, 2, steps=1, fast=True) == (1, Rational(3, 2)) assert refine_root(f, -2, -1, steps=1, fast=True) == (Rational(-3, 2), -1) assert refine_root(f, 1, 2, eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12)) assert refine_root(f, 1, 2, eps=1e-2) == (Rational(24, 17), Rational(17, 12)) raises(PolynomialError, lambda: refine_root(1, 7, 8, eps=Rational(1, 100))) raises(ValueError, lambda: Poly(f).refine_root(1, 2, eps=10**-100000)) raises(ValueError, lambda: refine_root(f, 1, 2, eps=10**-100000)) def test_count_roots(): assert count_roots(x**2 - 2) == 2 assert count_roots(x**2 - 2, inf=-oo) == 2 assert count_roots(x**2 - 2, sup=+oo) == 2 assert count_roots(x**2 - 2, inf=-oo, sup=+oo) == 2 assert count_roots(x**2 - 2, inf=-2) == 2 assert count_roots(x**2 - 2, inf=-1) == 1 assert count_roots(x**2 - 2, sup=1) == 1 assert count_roots(x**2 - 2, sup=2) == 2 assert count_roots(x**2 - 2, inf=-1, sup=1) == 0 assert count_roots(x**2 - 2, inf=-2, sup=2) == 2 assert count_roots(x**2 - 2, inf=-1, sup=1) == 0 assert count_roots(x**2 - 2, inf=-2, sup=2) == 2 assert count_roots(x**2 + 2) == 0 assert count_roots(x**2 + 2, inf=-2*I) == 2 assert count_roots(x**2 + 2, sup=+2*I) == 2 assert count_roots(x**2 + 2, inf=-2*I, sup=+2*I) == 2 assert count_roots(x**2 + 2, inf=0) == 0 assert count_roots(x**2 + 2, sup=0) == 0 assert count_roots(x**2 + 2, inf=-I) == 1 assert count_roots(x**2 + 2, sup=+I) == 1 assert count_roots(x**2 + 2, inf=+I/2, sup=+I) == 0 assert count_roots(x**2 + 2, inf=-I, sup=-I/2) == 0 raises(PolynomialError, lambda: count_roots(1)) def test_Poly_root(): f = Poly(2*x**3 - 7*x**2 + 4*x + 4) assert f.root(0) == Rational(-1, 2) assert f.root(1) == 2 assert f.root(2) == 2 raises(IndexError, lambda: f.root(3)) assert Poly(x**5 + x + 1).root(0) == rootof(x**3 - x**2 + 1, 0) def test_real_roots(): assert real_roots(x) == [0] assert real_roots(x, multiple=False) == [(0, 1)] assert real_roots(x**3) == [0, 0, 0] assert real_roots(x**3, multiple=False) == [(0, 3)] assert real_roots(x*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0] assert real_roots(x*(x**3 + x + 3), multiple=False) == [(rootof( x**3 + x + 3, 0), 1), (0, 1)] assert real_roots( x**3*(x**3 + x + 3)) == [rootof(x**3 + x + 3, 0), 0, 0, 0] assert real_roots(x**3*(x**3 + x + 3), multiple=False) == [(rootof( x**3 + x + 3, 0), 1), (0, 3)] f = 2*x**3 - 7*x**2 + 4*x + 4 g = x**3 + x + 1 assert Poly(f).real_roots() == [Rational(-1, 2), 2, 2] assert Poly(g).real_roots() == [rootof(g, 0)] def test_all_roots(): f = 2*x**3 - 7*x**2 + 4*x + 4 g = x**3 + x + 1 assert Poly(f).all_roots() == [Rational(-1, 2), 2, 2] assert Poly(g).all_roots() == [rootof(g, 0), rootof(g, 1), rootof(g, 2)] def test_nroots(): assert Poly(0, x).nroots() == [] assert Poly(1, x).nroots() == [] assert Poly(x**2 - 1, x).nroots() == [-1.0, 1.0] assert Poly(x**2 + 1, x).nroots() == [-1.0*I, 1.0*I] roots = Poly(x**2 - 1, x).nroots() assert roots == [-1.0, 1.0] roots = Poly(x**2 + 1, x).nroots() assert roots == [-1.0*I, 1.0*I] roots = Poly(x**2/3 - Rational(1, 3), x).nroots() assert roots == [-1.0, 1.0] roots = Poly(x**2/3 + Rational(1, 3), x).nroots() assert roots == [-1.0*I, 1.0*I] assert Poly(x**2 + 2*I, x).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I] assert Poly( x**2 + 2*I, x, extension=I).nroots() == [-1.0 + 1.0*I, 1.0 - 1.0*I] assert Poly(0.2*x + 0.1).nroots() == [-0.5] roots = nroots(x**5 + x + 1, n=5) eps = Float("1e-5") assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.true assert im(roots[0]) == 0.0 assert re(roots[1]) == -0.5 assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.true assert re(roots[2]) == -0.5 assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.true assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.true assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.true assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.true assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.true eps = Float("1e-6") assert re(roots[0]).epsilon_eq(-0.75487, eps) is S.false assert im(roots[0]) == 0.0 assert re(roots[1]) == -0.5 assert im(roots[1]).epsilon_eq(-0.86602, eps) is S.false assert re(roots[2]) == -0.5 assert im(roots[2]).epsilon_eq(+0.86602, eps) is S.false assert re(roots[3]).epsilon_eq(+0.87743, eps) is S.false assert im(roots[3]).epsilon_eq(-0.74486, eps) is S.false assert re(roots[4]).epsilon_eq(+0.87743, eps) is S.false assert im(roots[4]).epsilon_eq(+0.74486, eps) is S.false raises(DomainError, lambda: Poly(x + y, x).nroots()) raises(MultivariatePolynomialError, lambda: Poly(x + y).nroots()) assert nroots(x**2 - 1) == [-1.0, 1.0] roots = nroots(x**2 - 1) assert roots == [-1.0, 1.0] assert nroots(x + I) == [-1.0*I] assert nroots(x + 2*I) == [-2.0*I] raises(PolynomialError, lambda: nroots(0)) # issue 8296 f = Poly(x**4 - 1) assert f.nroots(2) == [w.n(2) for w in f.all_roots()] assert str(Poly(x**16 + 32*x**14 + 508*x**12 + 5440*x**10 + 39510*x**8 + 204320*x**6 + 755548*x**4 + 1434496*x**2 + 877969).nroots(2)) == ('[-1.7 - 1.9*I, -1.7 + 1.9*I, -1.7 ' '- 2.5*I, -1.7 + 2.5*I, -1.0*I, 1.0*I, -1.7*I, 1.7*I, -2.8*I, ' '2.8*I, -3.4*I, 3.4*I, 1.7 - 1.9*I, 1.7 + 1.9*I, 1.7 - 2.5*I, ' '1.7 + 2.5*I]') assert str(Poly(1e-15*x**2 -1).nroots()) == ('[-31622776.6016838, 31622776.6016838]') def test_ground_roots(): f = x**6 - 4*x**4 + 4*x**3 - x**2 assert Poly(f).ground_roots() == {S.One: 2, S.Zero: 2} assert ground_roots(f) == {S.One: 2, S.Zero: 2} def test_nth_power_roots_poly(): f = x**4 - x**2 + 1 f_2 = (x**2 - x + 1)**2 f_3 = (x**2 + 1)**2 f_4 = (x**2 + x + 1)**2 f_12 = (x - 1)**4 assert nth_power_roots_poly(f, 1) == f raises(ValueError, lambda: nth_power_roots_poly(f, 0)) raises(ValueError, lambda: nth_power_roots_poly(f, x)) assert factor(nth_power_roots_poly(f, 2)) == f_2 assert factor(nth_power_roots_poly(f, 3)) == f_3 assert factor(nth_power_roots_poly(f, 4)) == f_4 assert factor(nth_power_roots_poly(f, 12)) == f_12 raises(MultivariatePolynomialError, lambda: nth_power_roots_poly( x + y, 2, x, y)) def test_torational_factor_list(): p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + sqrt(2))})) assert _torational_factor_list(p, x) == (-2, [ (-x*(1 + sqrt(2))/2 + 1, 1), (-x*(1 + sqrt(2)) - 1, 1), (-x*(1 + sqrt(2)) + 1, 1)]) p = expand(((x**2-1)*(x-2)).subs({x:x*(1 + 2**Rational(1, 4))})) assert _torational_factor_list(p, x) is None def test_cancel(): assert cancel(0) == 0 assert cancel(7) == 7 assert cancel(x) == x assert cancel(oo) is oo assert cancel((2, 3)) == (1, 2, 3) assert cancel((1, 0), x) == (1, 1, 0) assert cancel((0, 1), x) == (1, 0, 1) f, g, p, q = 4*x**2 - 4, 2*x - 2, 2*x + 2, 1 F, G, P, Q = [ Poly(u, x) for u in (f, g, p, q) ] assert F.cancel(G) == (1, P, Q) assert cancel((f, g)) == (1, p, q) assert cancel((f, g), x) == (1, p, q) assert cancel((f, g), (x,)) == (1, p, q) assert cancel((F, G)) == (1, P, Q) assert cancel((f, g), polys=True) == (1, P, Q) assert cancel((F, G), polys=False) == (1, p, q) f = (x**2 - 2)/(x + sqrt(2)) assert cancel(f) == f assert cancel(f, greedy=False) == x - sqrt(2) f = (x**2 - 2)/(x - sqrt(2)) assert cancel(f) == f assert cancel(f, greedy=False) == x + sqrt(2) assert cancel((x**2/4 - 1, x/2 - 1)) == (1, x + 2, 2) # assert cancel((x**2/4 - 1, x/2 - 1)) == (S.Half, x + 2, 1) assert cancel((x**2 - y)/(x - y)) == 1/(x - y)*(x**2 - y) assert cancel((x**2 - y**2)/(x - y), x) == x + y assert cancel((x**2 - y**2)/(x - y), y) == x + y assert cancel((x**2 - y**2)/(x - y)) == x + y assert cancel((x**3 - 1)/(x**2 - 1)) == (x**2 + x + 1)/(x + 1) assert cancel((x**3/2 - S.Half)/(x**2 - 1)) == (x**2 + x + 1)/(2*x + 2) assert cancel((exp(2*x) + 2*exp(x) + 1)/(exp(x) + 1)) == exp(x) + 1 f = Poly(x**2 - a**2, x) g = Poly(x - a, x) F = Poly(x + a, x, domain='ZZ[a]') G = Poly(1, x, domain='ZZ[a]') assert cancel((f, g)) == (1, F, G) f = x**3 + (sqrt(2) - 2)*x**2 - (2*sqrt(2) + 3)*x - 3*sqrt(2) g = x**2 - 2 assert cancel((f, g), extension=True) == (1, x**2 - 2*x - 3, x - sqrt(2)) f = Poly(-2*x + 3, x) g = Poly(-x**9 + x**8 + x**6 - x**5 + 2*x**2 - 3*x + 1, x) assert cancel((f, g)) == (1, -f, -g) f = Poly(y, y, domain='ZZ(x)') g = Poly(1, y, domain='ZZ[x]') assert f.cancel( g) == (1, Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)')) assert f.cancel(g, include=True) == ( Poly(y, y, domain='ZZ(x)'), Poly(1, y, domain='ZZ(x)')) f = Poly(5*x*y + x, y, domain='ZZ(x)') g = Poly(2*x**2*y, y, domain='ZZ(x)') assert f.cancel(g, include=True) == ( Poly(5*y + 1, y, domain='ZZ(x)'), Poly(2*x*y, y, domain='ZZ(x)')) f = -(-2*x - 4*y + 0.005*(z - y)**2)/((z - y)*(-z + y + 2)) assert cancel(f).is_Mul == True P = tanh(x - 3.0) Q = tanh(x + 3.0) f = ((-2*P**2 + 2)*(-P**2 + 1)*Q**2/2 + (-2*P**2 + 2)*(-2*Q**2 + 2)*P*Q - (-2*P**2 + 2)*P**2*Q**2 + (-2*Q**2 + 2)*(-Q**2 + 1)*P**2/2 - (-2*Q**2 + 2)*P**2*Q**2)/(2*sqrt(P**2*Q**2 + 0.0001)) \ + (-(-2*P**2 + 2)*P*Q**2/2 - (-2*Q**2 + 2)*P**2*Q/2)*((-2*P**2 + 2)*P*Q**2/2 + (-2*Q**2 + 2)*P**2*Q/2)/(2*(P**2*Q**2 + 0.0001)**Rational(3, 2)) assert cancel(f).is_Mul == True # issue 7022 A = Symbol('A', commutative=False) p1 = Piecewise((A*(x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True)) p2 = Piecewise((A*(x - 1), x > 1), (1/x, True)) assert cancel(p1) == p2 assert cancel(2*p1) == 2*p2 assert cancel(1 + p1) == 1 + p2 assert cancel((x**2 - 1)/(x + 1)*p1) == (x - 1)*p2 assert cancel((x**2 - 1)/(x + 1) + p1) == (x - 1) + p2 p3 = Piecewise(((x**2 - 1)/(x + 1), x > 1), ((x + 2)/(x**2 + 2*x), True)) p4 = Piecewise(((x - 1), x > 1), (1/x, True)) assert cancel(p3) == p4 assert cancel(2*p3) == 2*p4 assert cancel(1 + p3) == 1 + p4 assert cancel((x**2 - 1)/(x + 1)*p3) == (x - 1)*p4 assert cancel((x**2 - 1)/(x + 1) + p3) == (x - 1) + p4 # issue 9363 M = MatrixSymbol('M', 5, 5) assert cancel(M[0,0] + 7) == M[0,0] + 7 expr = sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2] / z assert cancel(expr) == (z*sin(M[1, 4] + M[2, 1] * 5 * M[4, 0]) - 5 * M[1, 2]) / z assert cancel((x**2 + 1)/(x - I)) == x + I def test_reduced(): f = 2*x**4 + y**2 - x**2 + y**3 G = [x**3 - x, y**3 - y] Q = [2*x, 1] r = x**2 + y**2 + y assert reduced(f, G) == (Q, r) assert reduced(f, G, x, y) == (Q, r) H = groebner(G) assert H.reduce(f) == (Q, r) Q = [Poly(2*x, x, y), Poly(1, x, y)] r = Poly(x**2 + y**2 + y, x, y) assert _strict_eq(reduced(f, G, polys=True), (Q, r)) assert _strict_eq(reduced(f, G, x, y, polys=True), (Q, r)) H = groebner(G, polys=True) assert _strict_eq(H.reduce(f), (Q, r)) f = 2*x**3 + y**3 + 3*y G = groebner([x**2 + y**2 - 1, x*y - 2]) Q = [x**2 - x*y**3/2 + x*y/2 + y**6/4 - y**4/2 + y**2/4, -y**5/4 + y**3/2 + y*Rational(3, 4)] r = 0 assert reduced(f, G) == (Q, r) assert G.reduce(f) == (Q, r) assert reduced(f, G, auto=False)[1] != 0 assert G.reduce(f, auto=False)[1] != 0 assert G.contains(f) is True assert G.contains(f + 1) is False assert reduced(1, [1], x) == ([1], 0) raises(ComputationFailed, lambda: reduced(1, [1])) def test_groebner(): assert groebner([], x, y, z) == [] assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex') == [1 + x**2, -1 + y**4] assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex') == [-1 + y**4, z**3, 1 + x**2] assert groebner([x**2 + 1, y**4*x + x**3], x, y, order='lex', polys=True) == \ [Poly(1 + x**2, x, y), Poly(-1 + y**4, x, y)] assert groebner([x**2 + 1, y**4*x + x**3, x*y*z**3], x, y, z, order='grevlex', polys=True) == \ [Poly(-1 + y**4, x, y, z), Poly(z**3, x, y, z), Poly(1 + x**2, x, y, z)] assert groebner([x**3 - 1, x**2 - 1]) == [x - 1] assert groebner([Eq(x**3, 1), Eq(x**2, 1)]) == [x - 1] F = [3*x**2 + y*z - 5*x - 1, 2*x + 3*x*y + y**2, x - 3*y + x*z - 2*z**2] f = z**9 - x**2*y**3 - 3*x*y**2*z + 11*y*z**2 + x**2*z**2 - 5 G = groebner(F, x, y, z, modulus=7, symmetric=False) assert G == [1 + x + y + 3*z + 2*z**2 + 2*z**3 + 6*z**4 + z**5, 1 + 3*y + y**2 + 6*z**2 + 3*z**3 + 3*z**4 + 3*z**5 + 4*z**6, 1 + 4*y + 4*z + y*z + 4*z**3 + z**4 + z**6, 6 + 6*z + z**2 + 4*z**3 + 3*z**4 + 6*z**5 + 3*z**6 + z**7] Q, r = reduced(f, G, x, y, z, modulus=7, symmetric=False, polys=True) assert sum([ q*g for q, g in zip(Q, G.polys)], r) == Poly(f, modulus=7) F = [x*y - 2*y, 2*y**2 - x**2] assert groebner(F, x, y, order='grevlex') == \ [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y] assert groebner(F, y, x, order='grevlex') == \ [x**3 - 2*x**2, -x**2 + 2*y**2, x*y - 2*y] assert groebner(F, order='grevlex', field=True) == \ [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y] assert groebner([1], x) == [1] assert groebner([x**2 + 2.0*y], x, y) == [1.0*x**2 + 2.0*y] raises(ComputationFailed, lambda: groebner([1])) assert groebner([x**2 - 1, x**3 + 1], method='buchberger') == [x + 1] assert groebner([x**2 - 1, x**3 + 1], method='f5b') == [x + 1] raises(ValueError, lambda: groebner([x, y], method='unknown')) def test_fglm(): F = [a + b + c + d, a*b + a*d + b*c + b*d, a*b*c + a*b*d + a*c*d + b*c*d, a*b*c*d - 1] G = groebner(F, a, b, c, d, order=grlex) B = [ 4*a + 3*d**9 - 4*d**5 - 3*d, 4*b + 4*c - 3*d**9 + 4*d**5 + 7*d, 4*c**2 + 3*d**10 - 4*d**6 - 3*d**2, 4*c*d**4 + 4*c - d**9 + 4*d**5 + 5*d, d**12 - d**8 - d**4 + 1, ] assert groebner(F, a, b, c, d, order=lex) == B assert G.fglm(lex) == B F = [9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9, -72*t*x**7 - 252*t*x**6 + 192*t*x**5 + 1260*t*x**4 + 312*t*x**3 - 404*t*x**2 - 576*t*x + \ 108*t - 72*x**7 - 256*x**6 + 192*x**5 + 1280*x**4 + 312*x**3 - 576*x + 96] G = groebner(F, t, x, order=grlex) B = [ 203577793572507451707*t + 627982239411707112*x**7 - 666924143779443762*x**6 - \ 10874593056632447619*x**5 + 5119998792707079562*x**4 + 72917161949456066376*x**3 + \ 20362663855832380362*x**2 - 142079311455258371571*x + 183756699868981873194, 9*x**8 + 36*x**7 - 32*x**6 - 252*x**5 - 78*x**4 + 468*x**3 + 288*x**2 - 108*x + 9, ] assert groebner(F, t, x, order=lex) == B assert G.fglm(lex) == B F = [x**2 - x - 3*y + 1, -2*x + y**2 + y - 1] G = groebner(F, x, y, order=lex) B = [ x**2 - x - 3*y + 1, y**2 - 2*x + y - 1, ] assert groebner(F, x, y, order=grlex) == B assert G.fglm(grlex) == B def test_is_zero_dimensional(): assert is_zero_dimensional([x, y], x, y) is True assert is_zero_dimensional([x**3 + y**2], x, y) is False assert is_zero_dimensional([x, y, z], x, y, z) is True assert is_zero_dimensional([x, y, z], x, y, z, t) is False F = [x*y - z, y*z - x, x*y - y] assert is_zero_dimensional(F, x, y, z) is True F = [x**2 - 2*x*z + 5, x*y**2 + y*z**3, 3*y**2 - 8*z**2] assert is_zero_dimensional(F, x, y, z) is True def test_GroebnerBasis(): F = [x*y - 2*y, 2*y**2 - x**2] G = groebner(F, x, y, order='grevlex') H = [y**3 - 2*y, x**2 - 2*y**2, x*y - 2*y] P = [ Poly(h, x, y) for h in H ] assert groebner(F + [0], x, y, order='grevlex') == G assert isinstance(G, GroebnerBasis) is True assert len(G) == 3 assert G[0] == H[0] and not G[0].is_Poly assert G[1] == H[1] and not G[1].is_Poly assert G[2] == H[2] and not G[2].is_Poly assert G[1:] == H[1:] and not any(g.is_Poly for g in G[1:]) assert G[:2] == H[:2] and not any(g.is_Poly for g in G[1:]) assert G.exprs == H assert G.polys == P assert G.gens == (x, y) assert G.domain == ZZ assert G.order == grevlex assert G == H assert G == tuple(H) assert G == P assert G == tuple(P) assert G != [] G = groebner(F, x, y, order='grevlex', polys=True) assert G[0] == P[0] and G[0].is_Poly assert G[1] == P[1] and G[1].is_Poly assert G[2] == P[2] and G[2].is_Poly assert G[1:] == P[1:] and all(g.is_Poly for g in G[1:]) assert G[:2] == P[:2] and all(g.is_Poly for g in G[1:]) def test_poly(): assert poly(x) == Poly(x, x) assert poly(y) == Poly(y, y) assert poly(x + y) == Poly(x + y, x, y) assert poly(x + sin(x)) == Poly(x + sin(x), x, sin(x)) assert poly(x + y, wrt=y) == Poly(x + y, y, x) assert poly(x + sin(x), wrt=sin(x)) == Poly(x + sin(x), sin(x), x) assert poly(x*y + 2*x*z**2 + 17) == Poly(x*y + 2*x*z**2 + 17, x, y, z) assert poly(2*(y + z)**2 - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - 1, y, z) assert poly( x*(y + z)**2 - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - 1, x, y, z) assert poly(2*x*( y + z)**2 - 1) == Poly(2*x*y**2 + 4*x*y*z + 2*x*z**2 - 1, x, y, z) assert poly(2*( y + z)**2 - x - 1) == Poly(2*y**2 + 4*y*z + 2*z**2 - x - 1, x, y, z) assert poly(x*( y + z)**2 - x - 1) == Poly(x*y**2 + 2*x*y*z + x*z**2 - x - 1, x, y, z) assert poly(2*x*(y + z)**2 - x - 1) == Poly(2*x*y**2 + 4*x*y*z + 2* x*z**2 - x - 1, x, y, z) assert poly(x*y + (x + y)**2 + (x + z)**2) == \ Poly(2*x*z + 3*x*y + y**2 + z**2 + 2*x**2, x, y, z) assert poly(x*y*(x + y)*(x + z)**2) == \ Poly(x**3*y**2 + x*y**2*z**2 + y*x**2*z**2 + 2*z*x**2* y**2 + 2*y*z*x**3 + y*x**4, x, y, z) assert poly(Poly(x + y + z, y, x, z)) == Poly(x + y + z, y, x, z) assert poly((x + y)**2, x) == Poly(x**2 + 2*x*y + y**2, x, domain=ZZ[y]) assert poly((x + y)**2, y) == Poly(x**2 + 2*x*y + y**2, y, domain=ZZ[x]) assert poly(1, x) == Poly(1, x) raises(GeneratorsNeeded, lambda: poly(1)) # issue 6184 assert poly(x + y, x, y) == Poly(x + y, x, y) assert poly(x + y, y, x) == Poly(x + y, y, x) def test_keep_coeff(): u = Mul(2, x + 1, evaluate=False) assert _keep_coeff(S.One, x) == x assert _keep_coeff(S.NegativeOne, x) == -x assert _keep_coeff(S(1.0), x) == 1.0*x assert _keep_coeff(S(-1.0), x) == -1.0*x assert _keep_coeff(S.One, 2*x) == 2*x assert _keep_coeff(S(2), x/2) == x assert _keep_coeff(S(2), sin(x)) == 2*sin(x) assert _keep_coeff(S(2), x + 1) == u assert _keep_coeff(x, 1/x) == 1 assert _keep_coeff(x + 1, S(2)) == u assert _keep_coeff(S.Half, S.One) == S.Half p = Pow(2, 3, evaluate=False) assert _keep_coeff(S(-1), p) == Mul(-1, p, evaluate=False) a = Add(2, p, evaluate=False) assert _keep_coeff(S.Half, a, clear=True ) == Mul(S.Half, a, evaluate=False) assert _keep_coeff(S.Half, a, clear=False ) == Add(1, Mul(S.Half, p, evaluate=False), evaluate=False) def test_poly_matching_consistency(): # Test for this issue: # https://github.com/sympy/sympy/issues/5514 assert I * Poly(x, x) == Poly(I*x, x) assert Poly(x, x) * I == Poly(I*x, x) def test_issue_5786(): assert expand(factor(expand( (x - I*y)*(z - I*t)), extension=[I])) == -I*t*x - t*y + x*z - I*y*z def test_noncommutative(): class foo(Expr): is_commutative=False e = x/(x + x*y) c = 1/( 1 + y) assert cancel(foo(e)) == foo(c) assert cancel(e + foo(e)) == c + foo(c) assert cancel(e*foo(c)) == c*foo(c) def test_to_rational_coeffs(): assert to_rational_coeffs( Poly(x**3 + y*x**2 + sqrt(y), x, domain='EX')) is None # issue 21268 assert to_rational_coeffs( Poly(y**3 + sqrt(2)*y**2*sin(x) + 1, y)) is None assert to_rational_coeffs(Poly(x, y)) is None assert to_rational_coeffs(Poly(sqrt(2)*y)) is None def test_factor_terms(): # issue 7067 assert factor_list(x*(x + y)) == (1, [(x, 1), (x + y, 1)]) assert sqf_list(x*(x + y)) == (1, [(x**2 + x*y, 1)]) def test_as_list(): # issue 14496 assert Poly(x**3 + 2, x, domain='ZZ').as_list() == [1, 0, 0, 2] assert Poly(x**2 + y + 1, x, y, domain='ZZ').as_list() == [[1], [], [1, 1]] assert Poly(x**2 + y + 1, x, y, z, domain='ZZ').as_list() == \ [[[1]], [[]], [[1], [1]]] def test_issue_11198(): assert factor_list(sqrt(2)*x) == (sqrt(2), [(x, 1)]) assert factor_list(sqrt(2)*sin(x), sin(x)) == (sqrt(2), [(sin(x), 1)]) def test_Poly_precision(): # Make sure Poly doesn't lose precision p = Poly(pi.evalf(100)*x) assert p.as_expr() == pi.evalf(100)*x def test_issue_12400(): # Correction of check for negative exponents assert poly(1/(1+sqrt(2)), x) == \ Poly(1/(1+sqrt(2)), x, domain='EX') def test_issue_14364(): assert gcd(S(6)*(1 + sqrt(3))/5, S(3)*(1 + sqrt(3))/10) == Rational(3, 10) * (1 + sqrt(3)) assert gcd(sqrt(5)*Rational(4, 7), sqrt(5)*Rational(2, 3)) == sqrt(5)*Rational(2, 21) assert lcm(Rational(2, 3)*sqrt(3), Rational(5, 6)*sqrt(3)) == S(10)*sqrt(3)/3 assert lcm(3*sqrt(3), 4/sqrt(3)) == 12*sqrt(3) assert lcm(S(5)*(1 + 2**Rational(1, 3))/6, S(3)*(1 + 2**Rational(1, 3))/8) == Rational(15, 2) * (1 + 2**Rational(1, 3)) assert gcd(Rational(2, 3)*sqrt(3), Rational(5, 6)/sqrt(3)) == sqrt(3)/18 assert gcd(S(4)*sqrt(13)/7, S(3)*sqrt(13)/14) == sqrt(13)/14 # gcd_list and lcm_list assert gcd([S(2)*sqrt(47)/7, S(6)*sqrt(47)/5, S(8)*sqrt(47)/5]) == sqrt(47)*Rational(2, 35) assert gcd([S(6)*(1 + sqrt(7))/5, S(2)*(1 + sqrt(7))/7, S(4)*(1 + sqrt(7))/13]) == (1 + sqrt(7))*Rational(2, 455) assert lcm((Rational(7, 2)/sqrt(15), Rational(5, 6)/sqrt(15), Rational(5, 8)/sqrt(15))) == Rational(35, 2)/sqrt(15) assert lcm([S(5)*(2 + 2**Rational(5, 7))/6, S(7)*(2 + 2**Rational(5, 7))/2, S(13)*(2 + 2**Rational(5, 7))/4]) == Rational(455, 2) * (2 + 2**Rational(5, 7)) def test_issue_15669(): x = Symbol("x", positive=True) expr = (16*x**3/(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**2 - 2*2**Rational(4, 5)*x*(-x**2 + sqrt(8*x**2 + (x**2 - 2)**2) + 2)**Rational(3, 5) + 10*x) assert factor(expr, deep=True) == x*(x**2 + 2) def test_issue_17988(): x = Symbol('x') p = poly(x - 1) with warns_deprecated_sympy(): M = Matrix([[poly(x + 1), poly(x + 1)]]) with warns_deprecated_sympy(): assert p * M == M * p == Matrix([[poly(x**2 - 1), poly(x**2 - 1)]]) def test_issue_18205(): assert cancel((2 + I)*(3 - I)) == 7 + I assert cancel((2 + I)*(2 - I)) == 5 def test_issue_8695(): p = (x**2 + 1) * (x - 1)**2 * (x - 2)**3 * (x - 3)**3 result = (1, [(x**2 + 1, 1), (x - 1, 2), (x**2 - 5*x + 6, 3)]) assert sqf_list(p) == result def test_issue_19113(): eq = sin(x)**3 - sin(x) + 1 raises(PolynomialError, lambda: refine_root(eq, 1, 2, 1e-2)) raises(PolynomialError, lambda: count_roots(eq, -1, 1)) raises(PolynomialError, lambda: real_roots(eq)) raises(PolynomialError, lambda: nroots(eq)) raises(PolynomialError, lambda: ground_roots(eq)) raises(PolynomialError, lambda: nth_power_roots_poly(eq, 2)) def test_issue_19360(): f = 2*x**2 - 2*sqrt(2)*x*y + y**2 assert factor(f, extension=sqrt(2)) == 2*(x - (sqrt(2)*y/2))**2 f = -I*t*x - t*y + x*z - I*y*z assert factor(f, extension=I) == (x - I*y)*(-I*t + z) def test_poly_copy_equals_original(): poly = Poly(x + y, x, y, z) copy = poly.copy() assert poly == copy, ( "Copied polynomial not equal to original.") assert poly.gens == copy.gens, ( "Copied polynomial has different generators than original.") def test_deserialized_poly_equals_original(): poly = Poly(x + y, x, y, z) deserialized = pickle.loads(pickle.dumps(poly)) assert poly == deserialized, ( "Deserialized polynomial not equal to original.") assert poly.gens == deserialized.gens, ( "Deserialized polynomial has different generators than original.") def test_issue_20389(): result = degree(x * (x + 1) - x ** 2 - x, x) assert result == -oo def test_issue_20985(): from sympy.core.symbol import symbols w, R = symbols('w R') poly = Poly(1.0 + I*w/R, w, 1/R) assert poly.degree() == S(1)
e0fab9189c1285cef987cc303667735b7a1aca4900c3a5b851572376c7984ed2
from sympy.polys.galoistools import ( gf_crt, gf_crt1, gf_crt2, gf_int, gf_degree, gf_strip, gf_trunc, gf_normal, gf_from_dict, gf_to_dict, gf_from_int_poly, gf_to_int_poly, gf_neg, gf_add_ground, gf_sub_ground, gf_mul_ground, gf_add, gf_sub, gf_add_mul, gf_sub_mul, gf_mul, gf_sqr, gf_div, gf_rem, gf_quo, gf_exquo, gf_lshift, gf_rshift, gf_expand, gf_pow, gf_pow_mod, gf_gcdex, gf_gcd, gf_lcm, gf_cofactors, gf_LC, gf_TC, gf_monic, gf_eval, gf_multi_eval, gf_compose, gf_compose_mod, gf_trace_map, gf_diff, gf_irreducible, gf_irreducible_p, gf_irred_p_ben_or, gf_irred_p_rabin, gf_sqf_list, gf_sqf_part, gf_sqf_p, gf_Qmatrix, gf_Qbasis, gf_ddf_zassenhaus, gf_ddf_shoup, gf_edf_zassenhaus, gf_edf_shoup, gf_berlekamp, gf_factor_sqf, gf_factor, gf_value, linear_congruence, csolve_prime, gf_csolve, gf_frobenius_map, gf_frobenius_monomial_base ) from sympy.polys.polyerrors import ( ExactQuotientFailed, ) from sympy.polys import polyconfig as config from sympy.polys.domains import ZZ from sympy.core.numbers import pi from sympy.ntheory.generate import nextprime from sympy.testing.pytest import raises def test_gf_crt(): U = [49, 76, 65] M = [99, 97, 95] p = 912285 u = 639985 assert gf_crt(U, M, ZZ) == u E = [9215, 9405, 9603] S = [62, 24, 12] assert gf_crt1(M, ZZ) == (p, E, S) assert gf_crt2(U, M, p, E, S, ZZ) == u def test_gf_int(): assert gf_int(0, 5) == 0 assert gf_int(1, 5) == 1 assert gf_int(2, 5) == 2 assert gf_int(3, 5) == -2 assert gf_int(4, 5) == -1 assert gf_int(5, 5) == 0 def test_gf_degree(): assert gf_degree([]) == -1 assert gf_degree([1]) == 0 assert gf_degree([1, 0]) == 1 assert gf_degree([1, 0, 0, 0, 1]) == 4 def test_gf_strip(): assert gf_strip([]) == [] assert gf_strip([0]) == [] assert gf_strip([0, 0, 0]) == [] assert gf_strip([1]) == [1] assert gf_strip([0, 1]) == [1] assert gf_strip([0, 0, 0, 1]) == [1] assert gf_strip([1, 2, 0]) == [1, 2, 0] assert gf_strip([0, 1, 2, 0]) == [1, 2, 0] assert gf_strip([0, 0, 0, 1, 2, 0]) == [1, 2, 0] def test_gf_trunc(): assert gf_trunc([], 11) == [] assert gf_trunc([1], 11) == [1] assert gf_trunc([22], 11) == [] assert gf_trunc([12], 11) == [1] assert gf_trunc([11, 22, 17, 1, 0], 11) == [6, 1, 0] assert gf_trunc([12, 23, 17, 1, 0], 11) == [1, 1, 6, 1, 0] def test_gf_normal(): assert gf_normal([11, 22, 17, 1, 0], 11, ZZ) == [6, 1, 0] def test_gf_from_to_dict(): f = {11: 12, 6: 2, 0: 25} F = {11: 1, 6: 2, 0: 3} g = [1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 3] assert gf_from_dict(f, 11, ZZ) == g assert gf_to_dict(g, 11) == F f = {11: -5, 4: 0, 3: 1, 0: 12} F = {11: -5, 3: 1, 0: 1} g = [6, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1] assert gf_from_dict(f, 11, ZZ) == g assert gf_to_dict(g, 11) == F assert gf_to_dict([10], 11, symmetric=True) == {0: -1} assert gf_to_dict([10], 11, symmetric=False) == {0: 10} def test_gf_from_to_int_poly(): assert gf_from_int_poly([1, 0, 7, 2, 20], 5) == [1, 0, 2, 2, 0] assert gf_to_int_poly([1, 0, 4, 2, 3], 5) == [1, 0, -1, 2, -2] assert gf_to_int_poly([10], 11, symmetric=True) == [-1] assert gf_to_int_poly([10], 11, symmetric=False) == [10] def test_gf_LC(): assert gf_LC([], ZZ) == 0 assert gf_LC([1], ZZ) == 1 assert gf_LC([1, 2], ZZ) == 1 def test_gf_TC(): assert gf_TC([], ZZ) == 0 assert gf_TC([1], ZZ) == 1 assert gf_TC([1, 2], ZZ) == 2 def test_gf_monic(): assert gf_monic(ZZ.map([]), 11, ZZ) == (0, []) assert gf_monic(ZZ.map([1]), 11, ZZ) == (1, [1]) assert gf_monic(ZZ.map([2]), 11, ZZ) == (2, [1]) assert gf_monic(ZZ.map([1, 2, 3, 4]), 11, ZZ) == (1, [1, 2, 3, 4]) assert gf_monic(ZZ.map([2, 3, 4, 5]), 11, ZZ) == (2, [1, 7, 2, 8]) def test_gf_arith(): assert gf_neg([], 11, ZZ) == [] assert gf_neg([1], 11, ZZ) == [10] assert gf_neg([1, 2, 3], 11, ZZ) == [10, 9, 8] assert gf_add_ground([], 0, 11, ZZ) == [] assert gf_sub_ground([], 0, 11, ZZ) == [] assert gf_add_ground([], 3, 11, ZZ) == [3] assert gf_sub_ground([], 3, 11, ZZ) == [8] assert gf_add_ground([1], 3, 11, ZZ) == [4] assert gf_sub_ground([1], 3, 11, ZZ) == [9] assert gf_add_ground([8], 3, 11, ZZ) == [] assert gf_sub_ground([3], 3, 11, ZZ) == [] assert gf_add_ground([1, 2, 3], 3, 11, ZZ) == [1, 2, 6] assert gf_sub_ground([1, 2, 3], 3, 11, ZZ) == [1, 2, 0] assert gf_mul_ground([], 0, 11, ZZ) == [] assert gf_mul_ground([], 1, 11, ZZ) == [] assert gf_mul_ground([1], 0, 11, ZZ) == [] assert gf_mul_ground([1], 1, 11, ZZ) == [1] assert gf_mul_ground([1, 2, 3], 0, 11, ZZ) == [] assert gf_mul_ground([1, 2, 3], 1, 11, ZZ) == [1, 2, 3] assert gf_mul_ground([1, 2, 3], 7, 11, ZZ) == [7, 3, 10] assert gf_add([], [], 11, ZZ) == [] assert gf_add([1], [], 11, ZZ) == [1] assert gf_add([], [1], 11, ZZ) == [1] assert gf_add([1], [1], 11, ZZ) == [2] assert gf_add([1], [2], 11, ZZ) == [3] assert gf_add([1, 2], [1], 11, ZZ) == [1, 3] assert gf_add([1], [1, 2], 11, ZZ) == [1, 3] assert gf_add([1, 2, 3], [8, 9, 10], 11, ZZ) == [9, 0, 2] assert gf_sub([], [], 11, ZZ) == [] assert gf_sub([1], [], 11, ZZ) == [1] assert gf_sub([], [1], 11, ZZ) == [10] assert gf_sub([1], [1], 11, ZZ) == [] assert gf_sub([1], [2], 11, ZZ) == [10] assert gf_sub([1, 2], [1], 11, ZZ) == [1, 1] assert gf_sub([1], [1, 2], 11, ZZ) == [10, 10] assert gf_sub([3, 2, 1], [8, 9, 10], 11, ZZ) == [6, 4, 2] assert gf_add_mul( [1, 5, 6], [7, 3], [8, 0, 6, 1], 11, ZZ) == [1, 2, 10, 8, 9] assert gf_sub_mul( [1, 5, 6], [7, 3], [8, 0, 6, 1], 11, ZZ) == [10, 9, 3, 2, 3] assert gf_mul([], [], 11, ZZ) == [] assert gf_mul([], [1], 11, ZZ) == [] assert gf_mul([1], [], 11, ZZ) == [] assert gf_mul([1], [1], 11, ZZ) == [1] assert gf_mul([5], [7], 11, ZZ) == [2] assert gf_mul([3, 0, 0, 6, 1, 2], [4, 0, 1, 0], 11, ZZ) == [1, 0, 3, 2, 4, 3, 1, 2, 0] assert gf_mul([4, 0, 1, 0], [3, 0, 0, 6, 1, 2], 11, ZZ) == [1, 0, 3, 2, 4, 3, 1, 2, 0] assert gf_mul([2, 0, 0, 1, 7], [2, 0, 0, 1, 7], 11, ZZ) == [4, 0, 0, 4, 6, 0, 1, 3, 5] assert gf_sqr([], 11, ZZ) == [] assert gf_sqr([2], 11, ZZ) == [4] assert gf_sqr([1, 2], 11, ZZ) == [1, 4, 4] assert gf_sqr([2, 0, 0, 1, 7], 11, ZZ) == [4, 0, 0, 4, 6, 0, 1, 3, 5] def test_gf_division(): raises(ZeroDivisionError, lambda: gf_div([1, 2, 3], [], 11, ZZ)) raises(ZeroDivisionError, lambda: gf_rem([1, 2, 3], [], 11, ZZ)) raises(ZeroDivisionError, lambda: gf_quo([1, 2, 3], [], 11, ZZ)) raises(ZeroDivisionError, lambda: gf_quo([1, 2, 3], [], 11, ZZ)) assert gf_div([1], [1, 2, 3], 7, ZZ) == ([], [1]) assert gf_rem([1], [1, 2, 3], 7, ZZ) == [1] assert gf_quo([1], [1, 2, 3], 7, ZZ) == [] f = ZZ.map([5, 4, 3, 2, 1, 0]) g = ZZ.map([1, 2, 3]) q = [5, 1, 0, 6] r = [3, 3] assert gf_div(f, g, 7, ZZ) == (q, r) assert gf_rem(f, g, 7, ZZ) == r assert gf_quo(f, g, 7, ZZ) == q raises(ExactQuotientFailed, lambda: gf_exquo(f, g, 7, ZZ)) f = ZZ.map([5, 4, 3, 2, 1, 0]) g = ZZ.map([1, 2, 3, 0]) q = [5, 1, 0] r = [6, 1, 0] assert gf_div(f, g, 7, ZZ) == (q, r) assert gf_rem(f, g, 7, ZZ) == r assert gf_quo(f, g, 7, ZZ) == q raises(ExactQuotientFailed, lambda: gf_exquo(f, g, 7, ZZ)) assert gf_quo(ZZ.map([1, 2, 1]), ZZ.map([1, 1]), 11, ZZ) == [1, 1] def test_gf_shift(): f = [1, 2, 3, 4, 5] assert gf_lshift([], 5, ZZ) == [] assert gf_rshift([], 5, ZZ) == ([], []) assert gf_lshift(f, 1, ZZ) == [1, 2, 3, 4, 5, 0] assert gf_lshift(f, 2, ZZ) == [1, 2, 3, 4, 5, 0, 0] assert gf_rshift(f, 0, ZZ) == (f, []) assert gf_rshift(f, 1, ZZ) == ([1, 2, 3, 4], [5]) assert gf_rshift(f, 3, ZZ) == ([1, 2], [3, 4, 5]) assert gf_rshift(f, 5, ZZ) == ([], f) def test_gf_expand(): F = [([1, 1], 2), ([1, 2], 3)] assert gf_expand(F, 11, ZZ) == [1, 8, 3, 5, 6, 8] assert gf_expand((4, F), 11, ZZ) == [4, 10, 1, 9, 2, 10] def test_gf_powering(): assert gf_pow([1, 0, 0, 1, 8], 0, 11, ZZ) == [1] assert gf_pow([1, 0, 0, 1, 8], 1, 11, ZZ) == [1, 0, 0, 1, 8] assert gf_pow([1, 0, 0, 1, 8], 2, 11, ZZ) == [1, 0, 0, 2, 5, 0, 1, 5, 9] assert gf_pow([1, 0, 0, 1, 8], 5, 11, ZZ) == \ [1, 0, 0, 5, 7, 0, 10, 6, 2, 10, 9, 6, 10, 6, 6, 0, 5, 2, 5, 9, 10] assert gf_pow([1, 0, 0, 1, 8], 8, 11, ZZ) == \ [1, 0, 0, 8, 9, 0, 6, 8, 10, 1, 2, 5, 10, 7, 7, 9, 1, 2, 0, 0, 6, 2, 5, 2, 5, 7, 7, 9, 10, 10, 7, 5, 5] assert gf_pow([1, 0, 0, 1, 8], 45, 11, ZZ) == \ [ 1, 0, 0, 1, 8, 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, 4, 0, 0, 4, 10, 0, 0, 0, 0, 0, 0, 10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 6, 4, 0, 0, 0, 0, 0, 0, 8, 0, 0, 8, 9, 0, 0, 0, 0, 0, 0, 10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 4, 0, 0, 4, 10, 0, 0, 0, 0, 0, 0, 8, 0, 0, 8, 9, 0, 0, 0, 0, 0, 0, 9, 0, 0, 9, 6, 0, 0, 0, 0, 0, 0, 3, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 10, 0, 0, 10, 3, 0, 0, 0, 0, 0, 0, 2, 0, 0, 2, 5, 0, 0, 0, 0, 0, 0, 4, 0, 0, 4, 10] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 0, ZZ.map([2, 0, 7]), 11, ZZ) == [1] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 1, ZZ.map([2, 0, 7]), 11, ZZ) == [1, 1] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 2, ZZ.map([2, 0, 7]), 11, ZZ) == [2, 3] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 5, ZZ.map([2, 0, 7]), 11, ZZ) == [7, 8] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 8, ZZ.map([2, 0, 7]), 11, ZZ) == [1, 5] assert gf_pow_mod(ZZ.map([1, 0, 0, 1, 8]), 45, ZZ.map([2, 0, 7]), 11, ZZ) == [5, 4] def test_gf_gcdex(): assert gf_gcdex(ZZ.map([]), ZZ.map([]), 11, ZZ) == ([1], [], []) assert gf_gcdex(ZZ.map([2]), ZZ.map([]), 11, ZZ) == ([6], [], [1]) assert gf_gcdex(ZZ.map([]), ZZ.map([2]), 11, ZZ) == ([], [6], [1]) assert gf_gcdex(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == ([], [6], [1]) assert gf_gcdex(ZZ.map([]), ZZ.map([3, 0]), 11, ZZ) == ([], [4], [1, 0]) assert gf_gcdex(ZZ.map([3, 0]), ZZ.map([]), 11, ZZ) == ([4], [], [1, 0]) assert gf_gcdex(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == ([], [4], [1, 0]) assert gf_gcdex(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == ([5, 6], [6], [1, 7]) def test_gf_gcd(): assert gf_gcd(ZZ.map([]), ZZ.map([]), 11, ZZ) == [] assert gf_gcd(ZZ.map([2]), ZZ.map([]), 11, ZZ) == [1] assert gf_gcd(ZZ.map([]), ZZ.map([2]), 11, ZZ) == [1] assert gf_gcd(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == [1] assert gf_gcd(ZZ.map([]), ZZ.map([1, 0]), 11, ZZ) == [1, 0] assert gf_gcd(ZZ.map([1, 0]), ZZ.map([]), 11, ZZ) == [1, 0] assert gf_gcd(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == [1, 0] assert gf_gcd(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == [1, 7] def test_gf_lcm(): assert gf_lcm(ZZ.map([]), ZZ.map([]), 11, ZZ) == [] assert gf_lcm(ZZ.map([2]), ZZ.map([]), 11, ZZ) == [] assert gf_lcm(ZZ.map([]), ZZ.map([2]), 11, ZZ) == [] assert gf_lcm(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == [1] assert gf_lcm(ZZ.map([]), ZZ.map([1, 0]), 11, ZZ) == [] assert gf_lcm(ZZ.map([1, 0]), ZZ.map([]), 11, ZZ) == [] assert gf_lcm(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == [1, 0] assert gf_lcm(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == [1, 8, 8, 8, 7] def test_gf_cofactors(): assert gf_cofactors(ZZ.map([]), ZZ.map([]), 11, ZZ) == ([], [], []) assert gf_cofactors(ZZ.map([2]), ZZ.map([]), 11, ZZ) == ([1], [2], []) assert gf_cofactors(ZZ.map([]), ZZ.map([2]), 11, ZZ) == ([1], [], [2]) assert gf_cofactors(ZZ.map([2]), ZZ.map([2]), 11, ZZ) == ([1], [2], [2]) assert gf_cofactors(ZZ.map([]), ZZ.map([1, 0]), 11, ZZ) == ([1, 0], [], [1]) assert gf_cofactors(ZZ.map([1, 0]), ZZ.map([]), 11, ZZ) == ([1, 0], [1], []) assert gf_cofactors(ZZ.map([3, 0]), ZZ.map([3, 0]), 11, ZZ) == ( [1, 0], [3], [3]) assert gf_cofactors(ZZ.map([1, 8, 7]), ZZ.map([1, 7, 1, 7]), 11, ZZ) == ( ([1, 7], [1, 1], [1, 0, 1])) def test_gf_diff(): assert gf_diff([], 11, ZZ) == [] assert gf_diff([7], 11, ZZ) == [] assert gf_diff([7, 3], 11, ZZ) == [7] assert gf_diff([7, 3, 1], 11, ZZ) == [3, 3] assert gf_diff([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], 11, ZZ) == [] def test_gf_eval(): assert gf_eval([], 4, 11, ZZ) == 0 assert gf_eval([], 27, 11, ZZ) == 0 assert gf_eval([7], 4, 11, ZZ) == 7 assert gf_eval([7], 27, 11, ZZ) == 7 assert gf_eval([1, 0, 3, 2, 4, 3, 1, 2, 0], 0, 11, ZZ) == 0 assert gf_eval([1, 0, 3, 2, 4, 3, 1, 2, 0], 4, 11, ZZ) == 9 assert gf_eval([1, 0, 3, 2, 4, 3, 1, 2, 0], 27, 11, ZZ) == 5 assert gf_eval([4, 0, 0, 4, 6, 0, 1, 3, 5], 0, 11, ZZ) == 5 assert gf_eval([4, 0, 0, 4, 6, 0, 1, 3, 5], 4, 11, ZZ) == 3 assert gf_eval([4, 0, 0, 4, 6, 0, 1, 3, 5], 27, 11, ZZ) == 9 assert gf_multi_eval([3, 2, 1], [0, 1, 2, 3], 11, ZZ) == [1, 6, 6, 1] def test_gf_compose(): assert gf_compose([], [1, 0], 11, ZZ) == [] assert gf_compose_mod([], [1, 0], [1, 0], 11, ZZ) == [] assert gf_compose([1], [], 11, ZZ) == [1] assert gf_compose([1, 0], [], 11, ZZ) == [] assert gf_compose([1, 0], [1, 0], 11, ZZ) == [1, 0] f = ZZ.map([1, 1, 4, 9, 1]) g = ZZ.map([1, 1, 1]) h = ZZ.map([1, 0, 0, 2]) assert gf_compose(g, h, 11, ZZ) == [1, 0, 0, 5, 0, 0, 7] assert gf_compose_mod(g, h, f, 11, ZZ) == [3, 9, 6, 10] def test_gf_trace_map(): f = ZZ.map([1, 1, 4, 9, 1]) a = [1, 1, 1] c = ZZ.map([1, 0]) b = gf_pow_mod(c, 11, f, 11, ZZ) assert gf_trace_map(a, b, c, 0, f, 11, ZZ) == \ ([1, 1, 1], [1, 1, 1]) assert gf_trace_map(a, b, c, 1, f, 11, ZZ) == \ ([5, 2, 10, 3], [5, 3, 0, 4]) assert gf_trace_map(a, b, c, 2, f, 11, ZZ) == \ ([5, 9, 5, 3], [10, 1, 5, 7]) assert gf_trace_map(a, b, c, 3, f, 11, ZZ) == \ ([1, 10, 6, 0], [7]) assert gf_trace_map(a, b, c, 4, f, 11, ZZ) == \ ([1, 1, 1], [1, 1, 8]) assert gf_trace_map(a, b, c, 5, f, 11, ZZ) == \ ([5, 2, 10, 3], [5, 3, 0, 0]) assert gf_trace_map(a, b, c, 11, f, 11, ZZ) == \ ([1, 10, 6, 0], [10]) def test_gf_irreducible(): assert gf_irreducible_p(gf_irreducible(1, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(2, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(3, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(4, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(5, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(6, 11, ZZ), 11, ZZ) is True assert gf_irreducible_p(gf_irreducible(7, 11, ZZ), 11, ZZ) is True def test_gf_irreducible_p(): assert gf_irred_p_ben_or(ZZ.map([7]), 11, ZZ) is True assert gf_irred_p_ben_or(ZZ.map([7, 3]), 11, ZZ) is True assert gf_irred_p_ben_or(ZZ.map([7, 3, 1]), 11, ZZ) is False assert gf_irred_p_rabin(ZZ.map([7]), 11, ZZ) is True assert gf_irred_p_rabin(ZZ.map([7, 3]), 11, ZZ) is True assert gf_irred_p_rabin(ZZ.map([7, 3, 1]), 11, ZZ) is False config.setup('GF_IRRED_METHOD', 'ben-or') assert gf_irreducible_p(ZZ.map([7]), 11, ZZ) is True assert gf_irreducible_p(ZZ.map([7, 3]), 11, ZZ) is True assert gf_irreducible_p(ZZ.map([7, 3, 1]), 11, ZZ) is False config.setup('GF_IRRED_METHOD', 'rabin') assert gf_irreducible_p(ZZ.map([7]), 11, ZZ) is True assert gf_irreducible_p(ZZ.map([7, 3]), 11, ZZ) is True assert gf_irreducible_p(ZZ.map([7, 3, 1]), 11, ZZ) is False config.setup('GF_IRRED_METHOD', 'other') raises(KeyError, lambda: gf_irreducible_p([7], 11, ZZ)) config.setup('GF_IRRED_METHOD') f = ZZ.map([1, 9, 9, 13, 16, 15, 6, 7, 7, 7, 10]) g = ZZ.map([1, 7, 16, 7, 15, 13, 13, 11, 16, 10, 9]) h = gf_mul(f, g, 17, ZZ) assert gf_irred_p_ben_or(f, 17, ZZ) is True assert gf_irred_p_ben_or(g, 17, ZZ) is True assert gf_irred_p_ben_or(h, 17, ZZ) is False assert gf_irred_p_rabin(f, 17, ZZ) is True assert gf_irred_p_rabin(g, 17, ZZ) is True assert gf_irred_p_rabin(h, 17, ZZ) is False def test_gf_squarefree(): assert gf_sqf_list([], 11, ZZ) == (0, []) assert gf_sqf_list([1], 11, ZZ) == (1, []) assert gf_sqf_list([1, 1], 11, ZZ) == (1, [([1, 1], 1)]) assert gf_sqf_p([], 11, ZZ) is True assert gf_sqf_p([1], 11, ZZ) is True assert gf_sqf_p([1, 1], 11, ZZ) is True f = gf_from_dict({11: 1, 0: 1}, 11, ZZ) assert gf_sqf_p(f, 11, ZZ) is False assert gf_sqf_list(f, 11, ZZ) == \ (1, [([1, 1], 11)]) f = [1, 5, 8, 4] assert gf_sqf_p(f, 11, ZZ) is False assert gf_sqf_list(f, 11, ZZ) == \ (1, [([1, 1], 1), ([1, 2], 2)]) assert gf_sqf_part(f, 11, ZZ) == [1, 3, 2] f = [1, 0, 0, 2, 0, 0, 2, 0, 0, 1, 0] assert gf_sqf_list(f, 3, ZZ) == \ (1, [([1, 0], 1), ([1, 1], 3), ([1, 2], 6)]) def test_gf_frobenius_map(): f = ZZ.map([2, 0, 1, 0, 2, 2, 0, 2, 2, 2]) g = ZZ.map([1,1,0,2,0,1,0,2,0,1]) p = 3 b = gf_frobenius_monomial_base(g, p, ZZ) h = gf_frobenius_map(f, g, b, p, ZZ) h1 = gf_pow_mod(f, p, g, p, ZZ) assert h == h1 def test_gf_berlekamp(): f = gf_from_int_poly([1, -3, 1, -3, -1, -3, 1], 11) Q = [[1, 0, 0, 0, 0, 0], [3, 5, 8, 8, 6, 5], [3, 6, 6, 1, 10, 0], [9, 4, 10, 3, 7, 9], [7, 8, 10, 0, 0, 8], [8, 10, 7, 8, 10, 8]] V = [[1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 0], [0, 0, 7, 9, 0, 1]] assert gf_Qmatrix(f, 11, ZZ) == Q assert gf_Qbasis(Q, 11, ZZ) == V assert gf_berlekamp(f, 11, ZZ) == \ [[1, 1], [1, 5, 3], [1, 2, 3, 4]] f = ZZ.map([1, 0, 1, 0, 10, 10, 8, 2, 8]) Q = ZZ.map([[1, 0, 0, 0, 0, 0, 0, 0], [2, 1, 7, 11, 10, 12, 5, 11], [3, 6, 4, 3, 0, 4, 7, 2], [4, 3, 6, 5, 1, 6, 2, 3], [2, 11, 8, 8, 3, 1, 3, 11], [6, 11, 8, 6, 2, 7, 10, 9], [5, 11, 7, 10, 0, 11, 7, 12], [3, 3, 12, 5, 0, 11, 9, 12]]) V = [[1, 0, 0, 0, 0, 0, 0, 0], [0, 5, 5, 0, 9, 5, 1, 0], [0, 9, 11, 9, 10, 12, 0, 1]] assert gf_Qmatrix(f, 13, ZZ) == Q assert gf_Qbasis(Q, 13, ZZ) == V assert gf_berlekamp(f, 13, ZZ) == \ [[1, 3], [1, 8, 4, 12], [1, 2, 3, 4, 6]] def test_gf_ddf(): f = gf_from_dict({15: ZZ(1), 0: ZZ(-1)}, 11, ZZ) g = [([1, 0, 0, 0, 0, 10], 1), ([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], 2)] assert gf_ddf_zassenhaus(f, 11, ZZ) == g assert gf_ddf_shoup(f, 11, ZZ) == g f = gf_from_dict({63: ZZ(1), 0: ZZ(1)}, 2, ZZ) g = [([1, 1], 1), ([1, 1, 1], 2), ([1, 1, 1, 1, 1, 1, 1], 3), ([1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1], 6)] assert gf_ddf_zassenhaus(f, 2, ZZ) == g assert gf_ddf_shoup(f, 2, ZZ) == g f = gf_from_dict({6: ZZ(1), 5: ZZ(-1), 4: ZZ(1), 3: ZZ(1), 1: ZZ(-1)}, 3, ZZ) g = [([1, 1, 0], 1), ([1, 1, 0, 1, 2], 2)] assert gf_ddf_zassenhaus(f, 3, ZZ) == g assert gf_ddf_shoup(f, 3, ZZ) == g f = ZZ.map([1, 2, 5, 26, 677, 436, 791, 325, 456, 24, 577]) g = [([1, 701], 1), ([1, 110, 559, 532, 694, 151, 110, 70, 735, 122], 9)] assert gf_ddf_zassenhaus(f, 809, ZZ) == g assert gf_ddf_shoup(f, 809, ZZ) == g p = ZZ(nextprime(int((2**15 * pi).evalf()))) f = gf_from_dict({15: 1, 1: 1, 0: 1}, p, ZZ) g = [([1, 22730, 68144], 2), ([1, 64876, 83977, 10787, 12561, 68608, 52650, 88001, 84356], 4), ([1, 15347, 95022, 84569, 94508, 92335], 5)] assert gf_ddf_zassenhaus(f, p, ZZ) == g assert gf_ddf_shoup(f, p, ZZ) == g def test_gf_edf(): f = ZZ.map([1, 1, 0, 1, 2]) g = ZZ.map([[1, 0, 1], [1, 1, 2]]) assert gf_edf_zassenhaus(f, 2, 3, ZZ) == g assert gf_edf_shoup(f, 2, 3, ZZ) == g def test_gf_factor(): assert gf_factor([], 11, ZZ) == (0, []) assert gf_factor([1], 11, ZZ) == (1, []) assert gf_factor([1, 1], 11, ZZ) == (1, [([1, 1], 1)]) assert gf_factor_sqf([], 11, ZZ) == (0, []) assert gf_factor_sqf([1], 11, ZZ) == (1, []) assert gf_factor_sqf([1, 1], 11, ZZ) == (1, [[1, 1]]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor_sqf([], 11, ZZ) == (0, []) assert gf_factor_sqf([1], 11, ZZ) == (1, []) assert gf_factor_sqf([1, 1], 11, ZZ) == (1, [[1, 1]]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor_sqf([], 11, ZZ) == (0, []) assert gf_factor_sqf([1], 11, ZZ) == (1, []) assert gf_factor_sqf([1, 1], 11, ZZ) == (1, [[1, 1]]) config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor_sqf(ZZ.map([]), 11, ZZ) == (0, []) assert gf_factor_sqf(ZZ.map([1]), 11, ZZ) == (1, []) assert gf_factor_sqf(ZZ.map([1, 1]), 11, ZZ) == (1, [[1, 1]]) f, p = ZZ.map([1, 0, 0, 1, 0]), 2 g = (1, [([1, 0], 1), ([1, 1], 1), ([1, 1, 1], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g g = (1, [[1, 0], [1, 1], [1, 1, 1]]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor_sqf(f, p, ZZ) == g f, p = gf_from_int_poly([1, -3, 1, -3, -1, -3, 1], 11), 11 g = (1, [([1, 1], 1), ([1, 5, 3], 1), ([1, 2, 3, 4], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = [1, 5, 8, 4], 11 g = (1, [([1, 1], 1), ([1, 2], 2)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = [1, 1, 10, 1, 0, 10, 10, 10, 0, 0], 11 g = (1, [([1, 0], 2), ([1, 9, 5], 1), ([1, 3, 0, 8, 5, 2], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = gf_from_dict({32: 1, 0: 1}, 11, ZZ), 11 g = (1, [([1, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 10], 1), ([1, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 10], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = gf_from_dict({32: ZZ(8), 0: ZZ(5)}, 11, ZZ), 11 g = (8, [([1, 3], 1), ([1, 8], 1), ([1, 0, 9], 1), ([1, 2, 2], 1), ([1, 9, 2], 1), ([1, 0, 5, 0, 7], 1), ([1, 0, 6, 0, 7], 1), ([1, 0, 0, 0, 1, 0, 0, 0, 6], 1), ([1, 0, 0, 0, 10, 0, 0, 0, 6], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g f, p = gf_from_dict({63: ZZ(8), 0: ZZ(5)}, 11, ZZ), 11 g = (8, [([1, 7], 1), ([1, 4, 5], 1), ([1, 6, 8, 2], 1), ([1, 9, 9, 2], 1), ([1, 0, 0, 9, 0, 0, 4], 1), ([1, 2, 0, 8, 4, 6, 4], 1), ([1, 2, 3, 8, 0, 6, 4], 1), ([1, 2, 6, 0, 8, 4, 4], 1), ([1, 3, 3, 1, 6, 8, 4], 1), ([1, 5, 6, 0, 8, 6, 4], 1), ([1, 6, 2, 7, 9, 8, 4], 1), ([1, 10, 4, 7, 10, 7, 4], 1), ([1, 10, 10, 1, 4, 9, 4], 1)]) config.setup('GF_FACTOR_METHOD', 'berlekamp') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g # Gathen polynomials: x**n + x + 1 (mod p > 2**n * pi) p = ZZ(nextprime(int((2**15 * pi).evalf()))) f = gf_from_dict({15: 1, 1: 1, 0: 1}, p, ZZ) assert gf_sqf_p(f, p, ZZ) is True g = (1, [([1, 22730, 68144], 1), ([1, 81553, 77449, 86810, 4724], 1), ([1, 86276, 56779, 14859, 31575], 1), ([1, 15347, 95022, 84569, 94508, 92335], 1)]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g g = (1, [[1, 22730, 68144], [1, 81553, 77449, 86810, 4724], [1, 86276, 56779, 14859, 31575], [1, 15347, 95022, 84569, 94508, 92335]]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor_sqf(f, p, ZZ) == g # Shoup polynomials: f = a_0 x**n + a_1 x**(n-1) + ... + a_n # (mod p > 2**(n-2) * pi), where a_n = a_{n-1}**2 + 1, a_0 = 1 p = ZZ(nextprime(int((2**4 * pi).evalf()))) f = ZZ.map([1, 2, 5, 26, 41, 39, 38]) assert gf_sqf_p(f, p, ZZ) is True g = (1, [([1, 44, 26], 1), ([1, 11, 25, 18, 30], 1)]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor(f, p, ZZ) == g g = (1, [[1, 44, 26], [1, 11, 25, 18, 30]]) config.setup('GF_FACTOR_METHOD', 'zassenhaus') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'shoup') assert gf_factor_sqf(f, p, ZZ) == g config.setup('GF_FACTOR_METHOD', 'other') raises(KeyError, lambda: gf_factor([1, 1], 11, ZZ)) config.setup('GF_FACTOR_METHOD') def test_gf_csolve(): assert gf_value([1, 7, 2, 4], 11) == 2204 assert linear_congruence(4, 3, 5) == [2] assert linear_congruence(0, 3, 5) == [] assert linear_congruence(6, 1, 4) == [] assert linear_congruence(0, 5, 5) == [0, 1, 2, 3, 4] assert linear_congruence(3, 12, 15) == [4, 9, 14] assert linear_congruence(6, 0, 18) == [0, 3, 6, 9, 12, 15] # with power = 1 assert csolve_prime([1, 3, 2, 17], 7) == [3] assert csolve_prime([1, 3, 1, 5], 5) == [0, 1] assert csolve_prime([3, 6, 9, 3], 3) == [0, 1, 2] # with power > 1 assert csolve_prime( [1, 1, 223], 3, 4) == [4, 13, 22, 31, 40, 49, 58, 67, 76] assert csolve_prime([3, 5, 2, 25], 5, 3) == [16, 50, 99] assert csolve_prime([3, 2, 2, 49], 7, 3) == [147, 190, 234] assert gf_csolve([1, 1, 7], 189) == [13, 49, 76, 112, 139, 175] assert gf_csolve([1, 3, 4, 1, 30], 60) == [10, 30] assert gf_csolve([1, 1, 7], 15) == []
bc1103082f3671c1afc6c113479c6bdf243bd07a3f1d4aafd50f7bd2f59fe383
"""Tests for functions for generating interesting polynomials. """ from sympy.core.add import Add from sympy.core.symbol import symbols from sympy.functions.elementary.miscellaneous import sqrt from sympy.ntheory.generate import prime from sympy.polys.domains.integerring import ZZ from sympy.polys.polytools import Poly from sympy.utilities.iterables import permute_signs from sympy.testing.pytest import raises from sympy.polys.specialpolys import ( swinnerton_dyer_poly, cyclotomic_poly, symmetric_poly, random_poly, interpolating_poly, fateman_poly_F_1, dmp_fateman_poly_F_1, fateman_poly_F_2, dmp_fateman_poly_F_2, fateman_poly_F_3, dmp_fateman_poly_F_3, ) from sympy.abc import x, y, z def test_swinnerton_dyer_poly(): raises(ValueError, lambda: swinnerton_dyer_poly(0, x)) assert swinnerton_dyer_poly(1, x, polys=True) == Poly(x**2 - 2) assert swinnerton_dyer_poly(1, x) == x**2 - 2 assert swinnerton_dyer_poly(2, x) == x**4 - 10*x**2 + 1 assert swinnerton_dyer_poly( 3, x) == x**8 - 40*x**6 + 352*x**4 - 960*x**2 + 576 # we only need to check that the polys arg works but # we may as well test that the roots are correct p = [sqrt(prime(i)) for i in range(1, 5)] assert str([i.n(3) for i in swinnerton_dyer_poly(4, polys=True).all_roots()] ) == str(sorted([Add(*i).n(3) for i in permute_signs(p)])) def test_cyclotomic_poly(): raises(ValueError, lambda: cyclotomic_poly(0, x)) assert cyclotomic_poly(1, x, polys=True) == Poly(x - 1) assert cyclotomic_poly(1, x) == x - 1 assert cyclotomic_poly(2, x) == x + 1 assert cyclotomic_poly(3, x) == x**2 + x + 1 assert cyclotomic_poly(4, x) == x**2 + 1 assert cyclotomic_poly(5, x) == x**4 + x**3 + x**2 + x + 1 assert cyclotomic_poly(6, x) == x**2 - x + 1 def test_symmetric_poly(): raises(ValueError, lambda: symmetric_poly(-1, x, y, z)) raises(ValueError, lambda: symmetric_poly(5, x, y, z)) assert symmetric_poly(1, x, y, z, polys=True) == Poly(x + y + z) assert symmetric_poly(1, (x, y, z), polys=True) == Poly(x + y + z) assert symmetric_poly(0, x, y, z) == 1 assert symmetric_poly(1, x, y, z) == x + y + z assert symmetric_poly(2, x, y, z) == x*y + x*z + y*z assert symmetric_poly(3, x, y, z) == x*y*z def test_random_poly(): poly = random_poly(x, 10, -100, 100, polys=False) assert Poly(poly).degree() == 10 assert all(-100 <= coeff <= 100 for coeff in Poly(poly).coeffs()) is True poly = random_poly(x, 10, -100, 100, polys=True) assert poly.degree() == 10 assert all(-100 <= coeff <= 100 for coeff in poly.coeffs()) is True def test_interpolating_poly(): x0, x1, x2, x3, y0, y1, y2, y3 = symbols('x:4, y:4') assert interpolating_poly(0, x) == 0 assert interpolating_poly(1, x) == y0 assert interpolating_poly(2, x) == \ y0*(x - x1)/(x0 - x1) + y1*(x - x0)/(x1 - x0) assert interpolating_poly(3, x) == \ y0*(x - x1)*(x - x2)/((x0 - x1)*(x0 - x2)) + \ y1*(x - x0)*(x - x2)/((x1 - x0)*(x1 - x2)) + \ y2*(x - x0)*(x - x1)/((x2 - x0)*(x2 - x1)) assert interpolating_poly(4, x) == \ y0*(x - x1)*(x - x2)*(x - x3)/((x0 - x1)*(x0 - x2)*(x0 - x3)) + \ y1*(x - x0)*(x - x2)*(x - x3)/((x1 - x0)*(x1 - x2)*(x1 - x3)) + \ y2*(x - x0)*(x - x1)*(x - x3)/((x2 - x0)*(x2 - x1)*(x2 - x3)) + \ y3*(x - x0)*(x - x1)*(x - x2)/((x3 - x0)*(x3 - x1)*(x3 - x2)) raises(ValueError, lambda: interpolating_poly(2, x, (x, 2), (1, 3))) raises(ValueError, lambda: interpolating_poly(2, x, (x + y, 2), (1, 3))) raises(ValueError, lambda: interpolating_poly(2, x + y, (x, 2), (1, 3))) raises(ValueError, lambda: interpolating_poly(2, 3, (4, 5), (6, 7))) raises(ValueError, lambda: interpolating_poly(2, 3, (4, 5), (6, 7, 8))) assert interpolating_poly(0, x, (1, 2), (3, 4)) == 0 assert interpolating_poly(1, x, (1, 2), (3, 4)) == 3 assert interpolating_poly(2, x, (1, 2), (3, 4)) == x + 2 def test_fateman_poly_F_1(): f, g, h = fateman_poly_F_1(1) F, G, H = dmp_fateman_poly_F_1(1, ZZ) assert [ t.rep.rep for t in [f, g, h] ] == [F, G, H] f, g, h = fateman_poly_F_1(3) F, G, H = dmp_fateman_poly_F_1(3, ZZ) assert [ t.rep.rep for t in [f, g, h] ] == [F, G, H] def test_fateman_poly_F_2(): f, g, h = fateman_poly_F_2(1) F, G, H = dmp_fateman_poly_F_2(1, ZZ) assert [ t.rep.rep for t in [f, g, h] ] == [F, G, H] f, g, h = fateman_poly_F_2(3) F, G, H = dmp_fateman_poly_F_2(3, ZZ) assert [ t.rep.rep for t in [f, g, h] ] == [F, G, H] def test_fateman_poly_F_3(): f, g, h = fateman_poly_F_3(1) F, G, H = dmp_fateman_poly_F_3(1, ZZ) assert [ t.rep.rep for t in [f, g, h] ] == [F, G, H] f, g, h = fateman_poly_F_3(3) F, G, H = dmp_fateman_poly_F_3(3, ZZ) assert [ t.rep.rep for t in [f, g, h] ] == [F, G, H]
dd60d11ff6707652a78113572c8bc3d2df05b0860b157acaf66a7b69ad74f3e0
"""Tests for efficient functions for generating orthogonal polynomials. """ from sympy.core.numbers import Rational as Q from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.polys.polytools import Poly from sympy.testing.pytest import raises from sympy.polys.orthopolys import ( jacobi_poly, gegenbauer_poly, chebyshevt_poly, chebyshevu_poly, hermite_poly, legendre_poly, laguerre_poly, spherical_bessel_fn, ) from sympy.abc import x, a, b def test_jacobi_poly(): raises(ValueError, lambda: jacobi_poly(-1, a, b, x)) assert jacobi_poly(1, a, b, x, polys=True) == Poly( (a/2 + b/2 + 1)*x + a/2 - b/2, x, domain='ZZ(a,b)') assert jacobi_poly(0, a, b, x) == 1 assert jacobi_poly(1, a, b, x) == a/2 - b/2 + x*(a/2 + b/2 + 1) assert jacobi_poly(2, a, b, x) == (a**2/8 - a*b/4 - a/8 + b**2/8 - b/8 + x**2*(a**2/8 + a*b/4 + a*Q(7, 8) + b**2/8 + b*Q(7, 8) + Q(3, 2)) + x*(a**2/4 + a*Q(3, 4) - b**2/4 - b*Q(3, 4)) - S.Half) assert jacobi_poly(1, a, b, polys=True) == Poly( (a/2 + b/2 + 1)*x + a/2 - b/2, x, domain='ZZ(a,b)') def test_gegenbauer_poly(): raises(ValueError, lambda: gegenbauer_poly(-1, a, x)) assert gegenbauer_poly( 1, a, x, polys=True) == Poly(2*a*x, x, domain='ZZ(a)') assert gegenbauer_poly(0, a, x) == 1 assert gegenbauer_poly(1, a, x) == 2*a*x assert gegenbauer_poly(2, a, x) == -a + x**2*(2*a**2 + 2*a) assert gegenbauer_poly( 3, a, x) == x**3*(4*a**3/3 + 4*a**2 + a*Q(8, 3)) + x*(-2*a**2 - 2*a) assert gegenbauer_poly(1, S.Half).dummy_eq(x) assert gegenbauer_poly(1, a, polys=True) == Poly(2*a*x, x, domain='ZZ(a)') def test_chebyshevt_poly(): raises(ValueError, lambda: chebyshevt_poly(-1, x)) assert chebyshevt_poly(1, x, polys=True) == Poly(x) assert chebyshevt_poly(0, x) == 1 assert chebyshevt_poly(1, x) == x assert chebyshevt_poly(2, x) == 2*x**2 - 1 assert chebyshevt_poly(3, x) == 4*x**3 - 3*x assert chebyshevt_poly(4, x) == 8*x**4 - 8*x**2 + 1 assert chebyshevt_poly(5, x) == 16*x**5 - 20*x**3 + 5*x assert chebyshevt_poly(6, x) == 32*x**6 - 48*x**4 + 18*x**2 - 1 assert chebyshevt_poly(1).dummy_eq(x) assert chebyshevt_poly(1, polys=True) == Poly(x) def test_chebyshevu_poly(): raises(ValueError, lambda: chebyshevu_poly(-1, x)) assert chebyshevu_poly(1, x, polys=True) == Poly(2*x) assert chebyshevu_poly(0, x) == 1 assert chebyshevu_poly(1, x) == 2*x assert chebyshevu_poly(2, x) == 4*x**2 - 1 assert chebyshevu_poly(3, x) == 8*x**3 - 4*x assert chebyshevu_poly(4, x) == 16*x**4 - 12*x**2 + 1 assert chebyshevu_poly(5, x) == 32*x**5 - 32*x**3 + 6*x assert chebyshevu_poly(6, x) == 64*x**6 - 80*x**4 + 24*x**2 - 1 assert chebyshevu_poly(1).dummy_eq(2*x) assert chebyshevu_poly(1, polys=True) == Poly(2*x) def test_hermite_poly(): raises(ValueError, lambda: hermite_poly(-1, x)) assert hermite_poly(1, x, polys=True) == Poly(2*x) assert hermite_poly(0, x) == 1 assert hermite_poly(1, x) == 2*x assert hermite_poly(2, x) == 4*x**2 - 2 assert hermite_poly(3, x) == 8*x**3 - 12*x assert hermite_poly(4, x) == 16*x**4 - 48*x**2 + 12 assert hermite_poly(5, x) == 32*x**5 - 160*x**3 + 120*x assert hermite_poly(6, x) == 64*x**6 - 480*x**4 + 720*x**2 - 120 assert hermite_poly(1).dummy_eq(2*x) assert hermite_poly(1, polys=True) == Poly(2*x) def test_legendre_poly(): raises(ValueError, lambda: legendre_poly(-1, x)) assert legendre_poly(1, x, polys=True) == Poly(x, domain='QQ') assert legendre_poly(0, x) == 1 assert legendre_poly(1, x) == x assert legendre_poly(2, x) == Q(3, 2)*x**2 - Q(1, 2) assert legendre_poly(3, x) == Q(5, 2)*x**3 - Q(3, 2)*x assert legendre_poly(4, x) == Q(35, 8)*x**4 - Q(30, 8)*x**2 + Q(3, 8) assert legendre_poly(5, x) == Q(63, 8)*x**5 - Q(70, 8)*x**3 + Q(15, 8)*x assert legendre_poly(6, x) == Q( 231, 16)*x**6 - Q(315, 16)*x**4 + Q(105, 16)*x**2 - Q(5, 16) assert legendre_poly(1).dummy_eq(x) assert legendre_poly(1, polys=True) == Poly(x) def test_laguerre_poly(): raises(ValueError, lambda: laguerre_poly(-1, x)) assert laguerre_poly(1, x, polys=True) == Poly(-x + 1, domain='QQ') assert laguerre_poly(0, x) == 1 assert laguerre_poly(1, x) == -x + 1 assert laguerre_poly(2, x) == Q(1, 2)*x**2 - Q(4, 2)*x + 1 assert laguerre_poly(3, x) == -Q(1, 6)*x**3 + Q(9, 6)*x**2 - Q(18, 6)*x + 1 assert laguerre_poly(4, x) == Q( 1, 24)*x**4 - Q(16, 24)*x**3 + Q(72, 24)*x**2 - Q(96, 24)*x + 1 assert laguerre_poly(5, x) == -Q(1, 120)*x**5 + Q(25, 120)*x**4 - Q( 200, 120)*x**3 + Q(600, 120)*x**2 - Q(600, 120)*x + 1 assert laguerre_poly(6, x) == Q(1, 720)*x**6 - Q(36, 720)*x**5 + Q(450, 720)*x**4 - Q(2400, 720)*x**3 + Q(5400, 720)*x**2 - Q(4320, 720)*x + 1 assert laguerre_poly(0, x, a) == 1 assert laguerre_poly(1, x, a) == -x + a + 1 assert laguerre_poly(2, x, a) == x**2/2 + (-a - 2)*x + a**2/2 + a*Q(3, 2) + 1 assert laguerre_poly(3, x, a) == -x**3/6 + (a/2 + Q( 3)/2)*x**2 + (-a**2/2 - a*Q(5, 2) - 3)*x + a**3/6 + a**2 + a*Q(11, 6) + 1 assert laguerre_poly(1).dummy_eq(-x + 1) assert laguerre_poly(1, polys=True) == Poly(-x + 1) def test_spherical_bessel_fn(): x, z = symbols("x z") assert spherical_bessel_fn(1, z) == 1/z**2 assert spherical_bessel_fn(2, z) == -1/z + 3/z**3 assert spherical_bessel_fn(3, z) == -6/z**2 + 15/z**4 assert spherical_bessel_fn(4, z) == 1/z - 45/z**3 + 105/z**5
ae8ebe174bc9ad1e3ab32979434cee5df5d0cc4444b6591601e455f71244df56
from sympy.core.symbol import var from sympy.polys.polytools import (pquo, prem, sturm, subresultants) from sympy.matrices import Matrix from sympy.polys.subresultants_qq_zz import (sylvester, res, res_q, res_z, bezout, subresultants_sylv, modified_subresultants_sylv, subresultants_bezout, modified_subresultants_bezout, backward_eye, sturm_pg, sturm_q, sturm_amv, euclid_pg, euclid_q, euclid_amv, modified_subresultants_pg, subresultants_pg, subresultants_amv_q, quo_z, rem_z, subresultants_amv, modified_subresultants_amv, subresultants_rem, subresultants_vv, subresultants_vv_2) def test_sylvester(): x = var('x') assert sylvester(x**3 -7, 0, x) == sylvester(x**3 -7, 0, x, 1) == Matrix([[0]]) assert sylvester(0, x**3 -7, x) == sylvester(0, x**3 -7, x, 1) == Matrix([[0]]) assert sylvester(x**3 -7, 0, x, 2) == Matrix([[0]]) assert sylvester(0, x**3 -7, x, 2) == Matrix([[0]]) assert sylvester(x**3 -7, 7, x).det() == sylvester(x**3 -7, 7, x, 1).det() == 343 assert sylvester(7, x**3 -7, x).det() == sylvester(7, x**3 -7, x, 1).det() == 343 assert sylvester(x**3 -7, 7, x, 2).det() == -343 assert sylvester(7, x**3 -7, x, 2).det() == 343 assert sylvester(3, 7, x).det() == sylvester(3, 7, x, 1).det() == sylvester(3, 7, x, 2).det() == 1 assert sylvester(3, 0, x).det() == sylvester(3, 0, x, 1).det() == sylvester(3, 0, x, 2).det() == 1 assert sylvester(x - 3, x - 8, x) == sylvester(x - 3, x - 8, x, 1) == sylvester(x - 3, x - 8, x, 2) == Matrix([[1, -3], [1, -8]]) assert sylvester(x**3 - 7*x + 7, 3*x**2 - 7, x) == sylvester(x**3 - 7*x + 7, 3*x**2 - 7, x, 1) == Matrix([[1, 0, -7, 7, 0], [0, 1, 0, -7, 7], [3, 0, -7, 0, 0], [0, 3, 0, -7, 0], [0, 0, 3, 0, -7]]) assert sylvester(x**3 - 7*x + 7, 3*x**2 - 7, x, 2) == Matrix([ [1, 0, -7, 7, 0, 0], [0, 3, 0, -7, 0, 0], [0, 1, 0, -7, 7, 0], [0, 0, 3, 0, -7, 0], [0, 0, 1, 0, -7, 7], [0, 0, 0, 3, 0, -7]]) def test_subresultants_sylv(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 assert subresultants_sylv(p, q, x) == subresultants(p, q, x) assert subresultants_sylv(p, q, x)[-1] == res(p, q, x) assert subresultants_sylv(p, q, x) != euclid_amv(p, q, x) amv_factors = [1, 1, -1, 1, -1, 1] assert subresultants_sylv(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))] p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert subresultants_sylv(p, q, x) == euclid_amv(p, q, x) def test_modified_subresultants_sylv(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 amv_factors = [1, 1, -1, 1, -1, 1] assert modified_subresultants_sylv(p, q, x) == [i*j for i, j in zip(amv_factors, subresultants_amv(p, q, x))] assert modified_subresultants_sylv(p, q, x)[-1] != res_q(p + x**8, q, x) assert modified_subresultants_sylv(p, q, x) != sturm_amv(p, q, x) p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert modified_subresultants_sylv(p, q, x) == sturm_amv(p, q, x) assert modified_subresultants_sylv(-p, q, x) != sturm_amv(-p, q, x) def test_res(): x = var('x') assert res(3, 5, x) == 1 def test_res_q(): x = var('x') assert res_q(3, 5, x) == 1 def test_res_z(): x = var('x') assert res_z(3, 5, x) == 1 assert res(3, 5, x) == res_q(3, 5, x) == res_z(3, 5, x) def test_bezout(): x = var('x') p = -2*x**5+7*x**3+9*x**2-3*x+1 q = -10*x**4+21*x**2+18*x-3 assert bezout(p, q, x, 'bz').det() == sylvester(p, q, x, 2).det() assert bezout(p, q, x, 'bz').det() != sylvester(p, q, x, 1).det() assert bezout(p, q, x, 'prs') == backward_eye(5) * bezout(p, q, x, 'bz') * backward_eye(5) def test_subresultants_bezout(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 assert subresultants_bezout(p, q, x) == subresultants(p, q, x) assert subresultants_bezout(p, q, x)[-1] == sylvester(p, q, x).det() assert subresultants_bezout(p, q, x) != euclid_amv(p, q, x) amv_factors = [1, 1, -1, 1, -1, 1] assert subresultants_bezout(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))] p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert subresultants_bezout(p, q, x) == euclid_amv(p, q, x) def test_modified_subresultants_bezout(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 amv_factors = [1, 1, -1, 1, -1, 1] assert modified_subresultants_bezout(p, q, x) == [i*j for i, j in zip(amv_factors, subresultants_amv(p, q, x))] assert modified_subresultants_bezout(p, q, x)[-1] != sylvester(p + x**8, q, x).det() assert modified_subresultants_bezout(p, q, x) != sturm_amv(p, q, x) p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert modified_subresultants_bezout(p, q, x) == sturm_amv(p, q, x) assert modified_subresultants_bezout(-p, q, x) != sturm_amv(-p, q, x) def test_sturm_pg(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 assert sturm_pg(p, q, x)[-1] != sylvester(p, q, x, 2).det() sam_factors = [1, 1, -1, -1, 1, 1] assert sturm_pg(p, q, x) == [i*j for i,j in zip(sam_factors, euclid_pg(p, q, x))] p = -9*x**5 - 5*x**3 - 9 q = -45*x**4 - 15*x**2 assert sturm_pg(p, q, x, 1)[-1] == sylvester(p, q, x, 1).det() assert sturm_pg(p, q, x)[-1] != sylvester(p, q, x, 2).det() assert sturm_pg(-p, q, x)[-1] == sylvester(-p, q, x, 2).det() assert sturm_pg(-p, q, x) == modified_subresultants_pg(-p, q, x) def test_sturm_q(): x = var('x') p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert sturm_q(p, q, x) == sturm(p) assert sturm_q(-p, -q, x) != sturm(-p) def test_sturm_amv(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 assert sturm_amv(p, q, x)[-1] != sylvester(p, q, x, 2).det() sam_factors = [1, 1, -1, -1, 1, 1] assert sturm_amv(p, q, x) == [i*j for i,j in zip(sam_factors, euclid_amv(p, q, x))] p = -9*x**5 - 5*x**3 - 9 q = -45*x**4 - 15*x**2 assert sturm_amv(p, q, x, 1)[-1] == sylvester(p, q, x, 1).det() assert sturm_amv(p, q, x)[-1] != sylvester(p, q, x, 2).det() assert sturm_amv(-p, q, x)[-1] == sylvester(-p, q, x, 2).det() assert sturm_pg(-p, q, x) == modified_subresultants_pg(-p, q, x) def test_euclid_pg(): x = var('x') p = x**6+x**5-x**4-x**3+x**2-x+1 q = 6*x**5+5*x**4-4*x**3-3*x**2+2*x-1 assert euclid_pg(p, q, x)[-1] == sylvester(p, q, x).det() assert euclid_pg(p, q, x) == subresultants_pg(p, q, x) p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 assert euclid_pg(p, q, x)[-1] != sylvester(p, q, x, 2).det() sam_factors = [1, 1, -1, -1, 1, 1] assert euclid_pg(p, q, x) == [i*j for i,j in zip(sam_factors, sturm_pg(p, q, x))] def test_euclid_q(): x = var('x') p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert euclid_q(p, q, x)[-1] == -sturm(p)[-1] def test_euclid_amv(): x = var('x') p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert euclid_amv(p, q, x)[-1] == sylvester(p, q, x).det() assert euclid_amv(p, q, x) == subresultants_amv(p, q, x) p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 assert euclid_amv(p, q, x)[-1] != sylvester(p, q, x, 2).det() sam_factors = [1, 1, -1, -1, 1, 1] assert euclid_amv(p, q, x) == [i*j for i,j in zip(sam_factors, sturm_amv(p, q, x))] def test_modified_subresultants_pg(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 amv_factors = [1, 1, -1, 1, -1, 1] assert modified_subresultants_pg(p, q, x) == [i*j for i, j in zip(amv_factors, subresultants_pg(p, q, x))] assert modified_subresultants_pg(p, q, x)[-1] != sylvester(p + x**8, q, x).det() assert modified_subresultants_pg(p, q, x) != sturm_pg(p, q, x) p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert modified_subresultants_pg(p, q, x) == sturm_pg(p, q, x) assert modified_subresultants_pg(-p, q, x) != sturm_pg(-p, q, x) def test_subresultants_pg(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 assert subresultants_pg(p, q, x) == subresultants(p, q, x) assert subresultants_pg(p, q, x)[-1] == sylvester(p, q, x).det() assert subresultants_pg(p, q, x) != euclid_pg(p, q, x) amv_factors = [1, 1, -1, 1, -1, 1] assert subresultants_pg(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))] p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert subresultants_pg(p, q, x) == euclid_pg(p, q, x) def test_subresultants_amv_q(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 assert subresultants_amv_q(p, q, x) == subresultants(p, q, x) assert subresultants_amv_q(p, q, x)[-1] == sylvester(p, q, x).det() assert subresultants_amv_q(p, q, x) != euclid_amv(p, q, x) amv_factors = [1, 1, -1, 1, -1, 1] assert subresultants_amv_q(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))] p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert subresultants_amv(p, q, x) == euclid_amv(p, q, x) def test_rem_z(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 assert rem_z(p, -q, x) != prem(p, -q, x) def test_quo_z(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 assert quo_z(p, -q, x) != pquo(p, -q, x) y = var('y') q = 3*x**6 + 5*y**4 - 4*x**2 - 9*x + 21 assert quo_z(p, -q, x) == pquo(p, -q, x) def test_subresultants_amv(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 assert subresultants_amv(p, q, x) == subresultants(p, q, x) assert subresultants_amv(p, q, x)[-1] == sylvester(p, q, x).det() assert subresultants_amv(p, q, x) != euclid_amv(p, q, x) amv_factors = [1, 1, -1, 1, -1, 1] assert subresultants_amv(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))] p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert subresultants_amv(p, q, x) == euclid_amv(p, q, x) def test_modified_subresultants_amv(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 amv_factors = [1, 1, -1, 1, -1, 1] assert modified_subresultants_amv(p, q, x) == [i*j for i, j in zip(amv_factors, subresultants_amv(p, q, x))] assert modified_subresultants_amv(p, q, x)[-1] != sylvester(p + x**8, q, x).det() assert modified_subresultants_amv(p, q, x) != sturm_amv(p, q, x) p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert modified_subresultants_amv(p, q, x) == sturm_amv(p, q, x) assert modified_subresultants_amv(-p, q, x) != sturm_amv(-p, q, x) def test_subresultants_rem(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 assert subresultants_rem(p, q, x) == subresultants(p, q, x) assert subresultants_rem(p, q, x)[-1] == sylvester(p, q, x).det() assert subresultants_rem(p, q, x) != euclid_amv(p, q, x) amv_factors = [1, 1, -1, 1, -1, 1] assert subresultants_rem(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))] p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert subresultants_rem(p, q, x) == euclid_amv(p, q, x) def test_subresultants_vv(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 assert subresultants_vv(p, q, x) == subresultants(p, q, x) assert subresultants_vv(p, q, x)[-1] == sylvester(p, q, x).det() assert subresultants_vv(p, q, x) != euclid_amv(p, q, x) amv_factors = [1, 1, -1, 1, -1, 1] assert subresultants_vv(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))] p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert subresultants_vv(p, q, x) == euclid_amv(p, q, x) def test_subresultants_vv_2(): x = var('x') p = x**8 + x**6 - 3*x**4 - 3*x**3 + 8*x**2 + 2*x - 5 q = 3*x**6 + 5*x**4 - 4*x**2 - 9*x + 21 assert subresultants_vv_2(p, q, x) == subresultants(p, q, x) assert subresultants_vv_2(p, q, x)[-1] == sylvester(p, q, x).det() assert subresultants_vv_2(p, q, x) != euclid_amv(p, q, x) amv_factors = [1, 1, -1, 1, -1, 1] assert subresultants_vv_2(p, q, x) == [i*j for i, j in zip(amv_factors, modified_subresultants_amv(p, q, x))] p = x**3 - 7*x + 7 q = 3*x**2 - 7 assert subresultants_vv_2(p, q, x) == euclid_amv(p, q, x)
cfd0d476df0ade56249b82322c7d42bfe4ca7bbe873fe13269191956c7d66fa5
"""Tests for options manager for :class:`Poly` and public API functions. """ from sympy.polys.polyoptions import ( Options, Expand, Gens, Wrt, Sort, Order, Field, Greedy, Domain, Split, Gaussian, Extension, Modulus, Symmetric, Strict, Auto, Frac, Formal, Polys, Include, All, Gen, Symbols, Method) from sympy.polys.orderings import lex from sympy.polys.domains import FF, GF, ZZ, QQ, QQ_I, RR, CC, EX from sympy.polys.polyerrors import OptionError, GeneratorsError from sympy.core.numbers import (I, Integer) from sympy.core.symbol import Symbol from sympy.functions.elementary.miscellaneous import sqrt from sympy.testing.pytest import raises from sympy.abc import x, y, z def test_Options_clone(): opt = Options((x, y, z), {'domain': 'ZZ'}) assert opt.gens == (x, y, z) assert opt.domain == ZZ assert ('order' in opt) is False new_opt = opt.clone({'gens': (x, y), 'order': 'lex'}) assert opt.gens == (x, y, z) assert opt.domain == ZZ assert ('order' in opt) is False assert new_opt.gens == (x, y) assert new_opt.domain == ZZ assert ('order' in new_opt) is True def test_Expand_preprocess(): assert Expand.preprocess(False) is False assert Expand.preprocess(True) is True assert Expand.preprocess(0) is False assert Expand.preprocess(1) is True raises(OptionError, lambda: Expand.preprocess(x)) def test_Expand_postprocess(): opt = {'expand': True} Expand.postprocess(opt) assert opt == {'expand': True} def test_Gens_preprocess(): assert Gens.preprocess((None,)) == () assert Gens.preprocess((x, y, z)) == (x, y, z) assert Gens.preprocess(((x, y, z),)) == (x, y, z) a = Symbol('a', commutative=False) raises(GeneratorsError, lambda: Gens.preprocess((x, x, y))) raises(GeneratorsError, lambda: Gens.preprocess((x, y, a))) def test_Gens_postprocess(): opt = {'gens': (x, y)} Gens.postprocess(opt) assert opt == {'gens': (x, y)} def test_Wrt_preprocess(): assert Wrt.preprocess(x) == ['x'] assert Wrt.preprocess('') == [] assert Wrt.preprocess(' ') == [] assert Wrt.preprocess('x,y') == ['x', 'y'] assert Wrt.preprocess('x y') == ['x', 'y'] assert Wrt.preprocess('x, y') == ['x', 'y'] assert Wrt.preprocess('x , y') == ['x', 'y'] assert Wrt.preprocess(' x, y') == ['x', 'y'] assert Wrt.preprocess(' x, y') == ['x', 'y'] assert Wrt.preprocess([x, y]) == ['x', 'y'] raises(OptionError, lambda: Wrt.preprocess(',')) raises(OptionError, lambda: Wrt.preprocess(0)) def test_Wrt_postprocess(): opt = {'wrt': ['x']} Wrt.postprocess(opt) assert opt == {'wrt': ['x']} def test_Sort_preprocess(): assert Sort.preprocess([x, y, z]) == ['x', 'y', 'z'] assert Sort.preprocess((x, y, z)) == ['x', 'y', 'z'] assert Sort.preprocess('x > y > z') == ['x', 'y', 'z'] assert Sort.preprocess('x>y>z') == ['x', 'y', 'z'] raises(OptionError, lambda: Sort.preprocess(0)) raises(OptionError, lambda: Sort.preprocess({x, y, z})) def test_Sort_postprocess(): opt = {'sort': 'x > y'} Sort.postprocess(opt) assert opt == {'sort': 'x > y'} def test_Order_preprocess(): assert Order.preprocess('lex') == lex def test_Order_postprocess(): opt = {'order': True} Order.postprocess(opt) assert opt == {'order': True} def test_Field_preprocess(): assert Field.preprocess(False) is False assert Field.preprocess(True) is True assert Field.preprocess(0) is False assert Field.preprocess(1) is True raises(OptionError, lambda: Field.preprocess(x)) def test_Field_postprocess(): opt = {'field': True} Field.postprocess(opt) assert opt == {'field': True} def test_Greedy_preprocess(): assert Greedy.preprocess(False) is False assert Greedy.preprocess(True) is True assert Greedy.preprocess(0) is False assert Greedy.preprocess(1) is True raises(OptionError, lambda: Greedy.preprocess(x)) def test_Greedy_postprocess(): opt = {'greedy': True} Greedy.postprocess(opt) assert opt == {'greedy': True} def test_Domain_preprocess(): assert Domain.preprocess(ZZ) == ZZ assert Domain.preprocess(QQ) == QQ assert Domain.preprocess(EX) == EX assert Domain.preprocess(FF(2)) == FF(2) assert Domain.preprocess(ZZ[x, y]) == ZZ[x, y] assert Domain.preprocess('Z') == ZZ assert Domain.preprocess('Q') == QQ assert Domain.preprocess('ZZ') == ZZ assert Domain.preprocess('QQ') == QQ assert Domain.preprocess('EX') == EX assert Domain.preprocess('FF(23)') == FF(23) assert Domain.preprocess('GF(23)') == GF(23) raises(OptionError, lambda: Domain.preprocess('Z[]')) assert Domain.preprocess('Z[x]') == ZZ[x] assert Domain.preprocess('Q[x]') == QQ[x] assert Domain.preprocess('R[x]') == RR[x] assert Domain.preprocess('C[x]') == CC[x] assert Domain.preprocess('ZZ[x]') == ZZ[x] assert Domain.preprocess('QQ[x]') == QQ[x] assert Domain.preprocess('RR[x]') == RR[x] assert Domain.preprocess('CC[x]') == CC[x] assert Domain.preprocess('Z[x,y]') == ZZ[x, y] assert Domain.preprocess('Q[x,y]') == QQ[x, y] assert Domain.preprocess('R[x,y]') == RR[x, y] assert Domain.preprocess('C[x,y]') == CC[x, y] assert Domain.preprocess('ZZ[x,y]') == ZZ[x, y] assert Domain.preprocess('QQ[x,y]') == QQ[x, y] assert Domain.preprocess('RR[x,y]') == RR[x, y] assert Domain.preprocess('CC[x,y]') == CC[x, y] raises(OptionError, lambda: Domain.preprocess('Z()')) assert Domain.preprocess('Z(x)') == ZZ.frac_field(x) assert Domain.preprocess('Q(x)') == QQ.frac_field(x) assert Domain.preprocess('ZZ(x)') == ZZ.frac_field(x) assert Domain.preprocess('QQ(x)') == QQ.frac_field(x) assert Domain.preprocess('Z(x,y)') == ZZ.frac_field(x, y) assert Domain.preprocess('Q(x,y)') == QQ.frac_field(x, y) assert Domain.preprocess('ZZ(x,y)') == ZZ.frac_field(x, y) assert Domain.preprocess('QQ(x,y)') == QQ.frac_field(x, y) assert Domain.preprocess('Q<I>') == QQ.algebraic_field(I) assert Domain.preprocess('QQ<I>') == QQ.algebraic_field(I) assert Domain.preprocess('Q<sqrt(2), I>') == QQ.algebraic_field(sqrt(2), I) assert Domain.preprocess( 'QQ<sqrt(2), I>') == QQ.algebraic_field(sqrt(2), I) raises(OptionError, lambda: Domain.preprocess('abc')) def test_Domain_postprocess(): raises(GeneratorsError, lambda: Domain.postprocess({'gens': (x, y), 'domain': ZZ[y, z]})) raises(GeneratorsError, lambda: Domain.postprocess({'gens': (), 'domain': EX})) raises(GeneratorsError, lambda: Domain.postprocess({'domain': EX})) def test_Split_preprocess(): assert Split.preprocess(False) is False assert Split.preprocess(True) is True assert Split.preprocess(0) is False assert Split.preprocess(1) is True raises(OptionError, lambda: Split.preprocess(x)) def test_Split_postprocess(): raises(NotImplementedError, lambda: Split.postprocess({'split': True})) def test_Gaussian_preprocess(): assert Gaussian.preprocess(False) is False assert Gaussian.preprocess(True) is True assert Gaussian.preprocess(0) is False assert Gaussian.preprocess(1) is True raises(OptionError, lambda: Gaussian.preprocess(x)) def test_Gaussian_postprocess(): opt = {'gaussian': True} Gaussian.postprocess(opt) assert opt == { 'gaussian': True, 'domain': QQ_I, } def test_Extension_preprocess(): assert Extension.preprocess(True) is True assert Extension.preprocess(1) is True assert Extension.preprocess([]) is None assert Extension.preprocess(sqrt(2)) == {sqrt(2)} assert Extension.preprocess([sqrt(2)]) == {sqrt(2)} assert Extension.preprocess([sqrt(2), I]) == {sqrt(2), I} raises(OptionError, lambda: Extension.preprocess(False)) raises(OptionError, lambda: Extension.preprocess(0)) def test_Extension_postprocess(): opt = {'extension': {sqrt(2)}} Extension.postprocess(opt) assert opt == { 'extension': {sqrt(2)}, 'domain': QQ.algebraic_field(sqrt(2)), } opt = {'extension': True} Extension.postprocess(opt) assert opt == {'extension': True} def test_Modulus_preprocess(): assert Modulus.preprocess(23) == 23 assert Modulus.preprocess(Integer(23)) == 23 raises(OptionError, lambda: Modulus.preprocess(0)) raises(OptionError, lambda: Modulus.preprocess(x)) def test_Modulus_postprocess(): opt = {'modulus': 5} Modulus.postprocess(opt) assert opt == { 'modulus': 5, 'domain': FF(5), } opt = {'modulus': 5, 'symmetric': False} Modulus.postprocess(opt) assert opt == { 'modulus': 5, 'domain': FF(5, False), 'symmetric': False, } def test_Symmetric_preprocess(): assert Symmetric.preprocess(False) is False assert Symmetric.preprocess(True) is True assert Symmetric.preprocess(0) is False assert Symmetric.preprocess(1) is True raises(OptionError, lambda: Symmetric.preprocess(x)) def test_Symmetric_postprocess(): opt = {'symmetric': True} Symmetric.postprocess(opt) assert opt == {'symmetric': True} def test_Strict_preprocess(): assert Strict.preprocess(False) is False assert Strict.preprocess(True) is True assert Strict.preprocess(0) is False assert Strict.preprocess(1) is True raises(OptionError, lambda: Strict.preprocess(x)) def test_Strict_postprocess(): opt = {'strict': True} Strict.postprocess(opt) assert opt == {'strict': True} def test_Auto_preprocess(): assert Auto.preprocess(False) is False assert Auto.preprocess(True) is True assert Auto.preprocess(0) is False assert Auto.preprocess(1) is True raises(OptionError, lambda: Auto.preprocess(x)) def test_Auto_postprocess(): opt = {'auto': True} Auto.postprocess(opt) assert opt == {'auto': True} def test_Frac_preprocess(): assert Frac.preprocess(False) is False assert Frac.preprocess(True) is True assert Frac.preprocess(0) is False assert Frac.preprocess(1) is True raises(OptionError, lambda: Frac.preprocess(x)) def test_Frac_postprocess(): opt = {'frac': True} Frac.postprocess(opt) assert opt == {'frac': True} def test_Formal_preprocess(): assert Formal.preprocess(False) is False assert Formal.preprocess(True) is True assert Formal.preprocess(0) is False assert Formal.preprocess(1) is True raises(OptionError, lambda: Formal.preprocess(x)) def test_Formal_postprocess(): opt = {'formal': True} Formal.postprocess(opt) assert opt == {'formal': True} def test_Polys_preprocess(): assert Polys.preprocess(False) is False assert Polys.preprocess(True) is True assert Polys.preprocess(0) is False assert Polys.preprocess(1) is True raises(OptionError, lambda: Polys.preprocess(x)) def test_Polys_postprocess(): opt = {'polys': True} Polys.postprocess(opt) assert opt == {'polys': True} def test_Include_preprocess(): assert Include.preprocess(False) is False assert Include.preprocess(True) is True assert Include.preprocess(0) is False assert Include.preprocess(1) is True raises(OptionError, lambda: Include.preprocess(x)) def test_Include_postprocess(): opt = {'include': True} Include.postprocess(opt) assert opt == {'include': True} def test_All_preprocess(): assert All.preprocess(False) is False assert All.preprocess(True) is True assert All.preprocess(0) is False assert All.preprocess(1) is True raises(OptionError, lambda: All.preprocess(x)) def test_All_postprocess(): opt = {'all': True} All.postprocess(opt) assert opt == {'all': True} def test_Gen_postprocess(): opt = {'gen': x} Gen.postprocess(opt) assert opt == {'gen': x} def test_Symbols_preprocess(): raises(OptionError, lambda: Symbols.preprocess(x)) def test_Symbols_postprocess(): opt = {'symbols': [x, y, z]} Symbols.postprocess(opt) assert opt == {'symbols': [x, y, z]} def test_Method_preprocess(): raises(OptionError, lambda: Method.preprocess(10)) def test_Method_postprocess(): opt = {'method': 'f5b'} Method.postprocess(opt) assert opt == {'method': 'f5b'}
bdca13b1c1910756de7fd5217251dcb0a9c1269f5b69ec6343e7a75ead7ea4a3
"""Tests for dense recursive polynomials' basic tools. """ from sympy.polys.densebasic import ( dup_LC, dmp_LC, dup_TC, dmp_TC, dmp_ground_LC, dmp_ground_TC, dmp_true_LT, dup_degree, dmp_degree, dmp_degree_in, dmp_degree_list, dup_strip, dmp_strip, dmp_validate, dup_reverse, dup_copy, dmp_copy, dup_normal, dmp_normal, dup_convert, dmp_convert, dup_from_sympy, dmp_from_sympy, dup_nth, dmp_nth, dmp_ground_nth, dmp_zero_p, dmp_zero, dmp_one_p, dmp_one, dmp_ground_p, dmp_ground, dmp_negative_p, dmp_positive_p, dmp_zeros, dmp_grounds, dup_from_dict, dup_from_raw_dict, dup_to_dict, dup_to_raw_dict, dmp_from_dict, dmp_to_dict, dmp_swap, dmp_permute, dmp_nest, dmp_raise, dup_deflate, dmp_deflate, dup_multi_deflate, dmp_multi_deflate, dup_inflate, dmp_inflate, dmp_exclude, dmp_include, dmp_inject, dmp_eject, dup_terms_gcd, dmp_terms_gcd, dmp_list_terms, dmp_apply_pairs, dup_slice, dup_random, ) from sympy.polys.specialpolys import f_polys from sympy.polys.domains import ZZ, QQ from sympy.polys.rings import ring from sympy.core.singleton import S from sympy.testing.pytest import raises from sympy.core.numbers import oo f_0, f_1, f_2, f_3, f_4, f_5, f_6 = [ f.to_dense() for f in f_polys() ] def test_dup_LC(): assert dup_LC([], ZZ) == 0 assert dup_LC([2, 3, 4, 5], ZZ) == 2 def test_dup_TC(): assert dup_TC([], ZZ) == 0 assert dup_TC([2, 3, 4, 5], ZZ) == 5 def test_dmp_LC(): assert dmp_LC([[]], ZZ) == [] assert dmp_LC([[2, 3, 4], [5]], ZZ) == [2, 3, 4] assert dmp_LC([[[]]], ZZ) == [[]] assert dmp_LC([[[2], [3, 4]], [[5]]], ZZ) == [[2], [3, 4]] def test_dmp_TC(): assert dmp_TC([[]], ZZ) == [] assert dmp_TC([[2, 3, 4], [5]], ZZ) == [5] assert dmp_TC([[[]]], ZZ) == [[]] assert dmp_TC([[[2], [3, 4]], [[5]]], ZZ) == [[5]] def test_dmp_ground_LC(): assert dmp_ground_LC([[]], 1, ZZ) == 0 assert dmp_ground_LC([[2, 3, 4], [5]], 1, ZZ) == 2 assert dmp_ground_LC([[[]]], 2, ZZ) == 0 assert dmp_ground_LC([[[2], [3, 4]], [[5]]], 2, ZZ) == 2 def test_dmp_ground_TC(): assert dmp_ground_TC([[]], 1, ZZ) == 0 assert dmp_ground_TC([[2, 3, 4], [5]], 1, ZZ) == 5 assert dmp_ground_TC([[[]]], 2, ZZ) == 0 assert dmp_ground_TC([[[2], [3, 4]], [[5]]], 2, ZZ) == 5 def test_dmp_true_LT(): assert dmp_true_LT([[]], 1, ZZ) == ((0, 0), 0) assert dmp_true_LT([[7]], 1, ZZ) == ((0, 0), 7) assert dmp_true_LT([[1, 0]], 1, ZZ) == ((0, 1), 1) assert dmp_true_LT([[1], []], 1, ZZ) == ((1, 0), 1) assert dmp_true_LT([[1, 0], []], 1, ZZ) == ((1, 1), 1) def test_dup_degree(): assert dup_degree([]) is -oo assert dup_degree([1]) == 0 assert dup_degree([1, 0]) == 1 assert dup_degree([1, 0, 0, 0, 1]) == 4 def test_dmp_degree(): assert dmp_degree([[]], 1) is -oo assert dmp_degree([[[]]], 2) is -oo assert dmp_degree([[1]], 1) == 0 assert dmp_degree([[2], [1]], 1) == 1 def test_dmp_degree_in(): assert dmp_degree_in([[[]]], 0, 2) is -oo assert dmp_degree_in([[[]]], 1, 2) is -oo assert dmp_degree_in([[[]]], 2, 2) is -oo assert dmp_degree_in([[[1]]], 0, 2) == 0 assert dmp_degree_in([[[1]]], 1, 2) == 0 assert dmp_degree_in([[[1]]], 2, 2) == 0 assert dmp_degree_in(f_4, 0, 2) == 9 assert dmp_degree_in(f_4, 1, 2) == 12 assert dmp_degree_in(f_4, 2, 2) == 8 assert dmp_degree_in(f_6, 0, 2) == 4 assert dmp_degree_in(f_6, 1, 2) == 4 assert dmp_degree_in(f_6, 2, 2) == 6 assert dmp_degree_in(f_6, 3, 3) == 3 raises(IndexError, lambda: dmp_degree_in([[1]], -5, 1)) def test_dmp_degree_list(): assert dmp_degree_list([[[[ ]]]], 3) == (-oo, -oo, -oo, -oo) assert dmp_degree_list([[[[1]]]], 3) == ( 0, 0, 0, 0) assert dmp_degree_list(f_0, 2) == (2, 2, 2) assert dmp_degree_list(f_1, 2) == (3, 3, 3) assert dmp_degree_list(f_2, 2) == (5, 3, 3) assert dmp_degree_list(f_3, 2) == (5, 4, 7) assert dmp_degree_list(f_4, 2) == (9, 12, 8) assert dmp_degree_list(f_5, 2) == (3, 3, 3) assert dmp_degree_list(f_6, 3) == (4, 4, 6, 3) def test_dup_strip(): assert dup_strip([]) == [] assert dup_strip([0]) == [] assert dup_strip([0, 0, 0]) == [] assert dup_strip([1]) == [1] assert dup_strip([0, 1]) == [1] assert dup_strip([0, 0, 0, 1]) == [1] assert dup_strip([1, 2, 0]) == [1, 2, 0] assert dup_strip([0, 1, 2, 0]) == [1, 2, 0] assert dup_strip([0, 0, 0, 1, 2, 0]) == [1, 2, 0] def test_dmp_strip(): assert dmp_strip([0, 1, 0], 0) == [1, 0] assert dmp_strip([[]], 1) == [[]] assert dmp_strip([[], []], 1) == [[]] assert dmp_strip([[], [], []], 1) == [[]] assert dmp_strip([[[]]], 2) == [[[]]] assert dmp_strip([[[]], [[]]], 2) == [[[]]] assert dmp_strip([[[]], [[]], [[]]], 2) == [[[]]] assert dmp_strip([[[1]]], 2) == [[[1]]] assert dmp_strip([[[]], [[1]]], 2) == [[[1]]] assert dmp_strip([[[]], [[1]], [[]]], 2) == [[[1]], [[]]] def test_dmp_validate(): assert dmp_validate([]) == ([], 0) assert dmp_validate([0, 0, 0, 1, 0]) == ([1, 0], 0) assert dmp_validate([[[]]]) == ([[[]]], 2) assert dmp_validate([[0], [], [0], [1], [0]]) == ([[1], []], 1) raises(ValueError, lambda: dmp_validate([[0], 0, [0], [1], [0]])) def test_dup_reverse(): assert dup_reverse([1, 2, 0, 3]) == [3, 0, 2, 1] assert dup_reverse([1, 2, 3, 0]) == [3, 2, 1] def test_dup_copy(): f = [ZZ(1), ZZ(0), ZZ(2)] g = dup_copy(f) g[0], g[2] = ZZ(7), ZZ(0) assert f != g def test_dmp_copy(): f = [[ZZ(1)], [ZZ(2), ZZ(0)]] g = dmp_copy(f, 1) g[0][0], g[1][1] = ZZ(7), ZZ(1) assert f != g def test_dup_normal(): assert dup_normal([0, 0, 2, 1, 0, 11, 0], ZZ) == \ [ZZ(2), ZZ(1), ZZ(0), ZZ(11), ZZ(0)] def test_dmp_normal(): assert dmp_normal([[0], [], [0, 2, 1], [0], [11], []], 1, ZZ) == \ [[ZZ(2), ZZ(1)], [], [ZZ(11)], []] def test_dup_convert(): K0, K1 = ZZ['x'], ZZ f = [K0(1), K0(2), K0(0), K0(3)] assert dup_convert(f, K0, K1) == \ [ZZ(1), ZZ(2), ZZ(0), ZZ(3)] def test_dmp_convert(): K0, K1 = ZZ['x'], ZZ f = [[K0(1)], [K0(2)], [], [K0(3)]] assert dmp_convert(f, 1, K0, K1) == \ [[ZZ(1)], [ZZ(2)], [], [ZZ(3)]] def test_dup_from_sympy(): assert dup_from_sympy([S.One, S(2)], ZZ) == \ [ZZ(1), ZZ(2)] assert dup_from_sympy([S.Half, S(3)], QQ) == \ [QQ(1, 2), QQ(3, 1)] def test_dmp_from_sympy(): assert dmp_from_sympy([[S.One, S(2)], [S.Zero]], 1, ZZ) == \ [[ZZ(1), ZZ(2)], []] assert dmp_from_sympy([[S.Half, S(2)]], 1, QQ) == \ [[QQ(1, 2), QQ(2, 1)]] def test_dup_nth(): assert dup_nth([1, 2, 3], 0, ZZ) == 3 assert dup_nth([1, 2, 3], 1, ZZ) == 2 assert dup_nth([1, 2, 3], 2, ZZ) == 1 assert dup_nth([1, 2, 3], 9, ZZ) == 0 raises(IndexError, lambda: dup_nth([3, 4, 5], -1, ZZ)) def test_dmp_nth(): assert dmp_nth([[1], [2], [3]], 0, 1, ZZ) == [3] assert dmp_nth([[1], [2], [3]], 1, 1, ZZ) == [2] assert dmp_nth([[1], [2], [3]], 2, 1, ZZ) == [1] assert dmp_nth([[1], [2], [3]], 9, 1, ZZ) == [] raises(IndexError, lambda: dmp_nth([[3], [4], [5]], -1, 1, ZZ)) def test_dmp_ground_nth(): assert dmp_ground_nth([[]], (0, 0), 1, ZZ) == 0 assert dmp_ground_nth([[1], [2], [3]], (0, 0), 1, ZZ) == 3 assert dmp_ground_nth([[1], [2], [3]], (1, 0), 1, ZZ) == 2 assert dmp_ground_nth([[1], [2], [3]], (2, 0), 1, ZZ) == 1 assert dmp_ground_nth([[1], [2], [3]], (2, 1), 1, ZZ) == 0 assert dmp_ground_nth([[1], [2], [3]], (3, 0), 1, ZZ) == 0 raises(IndexError, lambda: dmp_ground_nth([[3], [4], [5]], (2, -1), 1, ZZ)) def test_dmp_zero_p(): assert dmp_zero_p([], 0) is True assert dmp_zero_p([[]], 1) is True assert dmp_zero_p([[[]]], 2) is True assert dmp_zero_p([[[1]]], 2) is False def test_dmp_zero(): assert dmp_zero(0) == [] assert dmp_zero(2) == [[[]]] def test_dmp_one_p(): assert dmp_one_p([1], 0, ZZ) is True assert dmp_one_p([[1]], 1, ZZ) is True assert dmp_one_p([[[1]]], 2, ZZ) is True assert dmp_one_p([[[12]]], 2, ZZ) is False def test_dmp_one(): assert dmp_one(0, ZZ) == [ZZ(1)] assert dmp_one(2, ZZ) == [[[ZZ(1)]]] def test_dmp_ground_p(): assert dmp_ground_p([], 0, 0) is True assert dmp_ground_p([[]], 0, 1) is True assert dmp_ground_p([[]], 1, 1) is False assert dmp_ground_p([[ZZ(1)]], 1, 1) is True assert dmp_ground_p([[[ZZ(2)]]], 2, 2) is True assert dmp_ground_p([[[ZZ(2)]]], 3, 2) is False assert dmp_ground_p([[[ZZ(3)], []]], 3, 2) is False assert dmp_ground_p([], None, 0) is True assert dmp_ground_p([[]], None, 1) is True assert dmp_ground_p([ZZ(1)], None, 0) is True assert dmp_ground_p([[[ZZ(1)]]], None, 2) is True assert dmp_ground_p([[[ZZ(3)], []]], None, 2) is False def test_dmp_ground(): assert dmp_ground(ZZ(0), 2) == [[[]]] assert dmp_ground(ZZ(7), -1) == ZZ(7) assert dmp_ground(ZZ(7), 0) == [ZZ(7)] assert dmp_ground(ZZ(7), 2) == [[[ZZ(7)]]] def test_dmp_zeros(): assert dmp_zeros(4, 0, ZZ) == [[], [], [], []] assert dmp_zeros(0, 2, ZZ) == [] assert dmp_zeros(1, 2, ZZ) == [[[[]]]] assert dmp_zeros(2, 2, ZZ) == [[[[]]], [[[]]]] assert dmp_zeros(3, 2, ZZ) == [[[[]]], [[[]]], [[[]]]] assert dmp_zeros(3, -1, ZZ) == [0, 0, 0] def test_dmp_grounds(): assert dmp_grounds(ZZ(7), 0, 2) == [] assert dmp_grounds(ZZ(7), 1, 2) == [[[[7]]]] assert dmp_grounds(ZZ(7), 2, 2) == [[[[7]]], [[[7]]]] assert dmp_grounds(ZZ(7), 3, 2) == [[[[7]]], [[[7]]], [[[7]]]] assert dmp_grounds(ZZ(7), 3, -1) == [7, 7, 7] def test_dmp_negative_p(): assert dmp_negative_p([[[]]], 2, ZZ) is False assert dmp_negative_p([[[1], [2]]], 2, ZZ) is False assert dmp_negative_p([[[-1], [2]]], 2, ZZ) is True def test_dmp_positive_p(): assert dmp_positive_p([[[]]], 2, ZZ) is False assert dmp_positive_p([[[1], [2]]], 2, ZZ) is True assert dmp_positive_p([[[-1], [2]]], 2, ZZ) is False def test_dup_from_to_dict(): assert dup_from_raw_dict({}, ZZ) == [] assert dup_from_dict({}, ZZ) == [] assert dup_to_raw_dict([]) == {} assert dup_to_dict([]) == {} assert dup_to_raw_dict([], ZZ, zero=True) == {0: ZZ(0)} assert dup_to_dict([], ZZ, zero=True) == {(0,): ZZ(0)} f = [3, 0, 0, 2, 0, 0, 0, 0, 8] g = {8: 3, 5: 2, 0: 8} h = {(8,): 3, (5,): 2, (0,): 8} assert dup_from_raw_dict(g, ZZ) == f assert dup_from_dict(h, ZZ) == f assert dup_to_raw_dict(f) == g assert dup_to_dict(f) == h R, x,y = ring("x,y", ZZ) K = R.to_domain() f = [R(3), R(0), R(2), R(0), R(0), R(8)] g = {5: R(3), 3: R(2), 0: R(8)} h = {(5,): R(3), (3,): R(2), (0,): R(8)} assert dup_from_raw_dict(g, K) == f assert dup_from_dict(h, K) == f assert dup_to_raw_dict(f) == g assert dup_to_dict(f) == h def test_dmp_from_to_dict(): assert dmp_from_dict({}, 1, ZZ) == [[]] assert dmp_to_dict([[]], 1) == {} assert dmp_to_dict([], 0, ZZ, zero=True) == {(0,): ZZ(0)} assert dmp_to_dict([[]], 1, ZZ, zero=True) == {(0, 0): ZZ(0)} f = [[3], [], [], [2], [], [], [], [], [8]] g = {(8, 0): 3, (5, 0): 2, (0, 0): 8} assert dmp_from_dict(g, 1, ZZ) == f assert dmp_to_dict(f, 1) == g def test_dmp_swap(): f = dmp_normal([[1, 0, 0], [], [1, 0], [], [1]], 1, ZZ) g = dmp_normal([[1, 0, 0, 0, 0], [1, 0, 0], [1]], 1, ZZ) assert dmp_swap(f, 1, 1, 1, ZZ) == f assert dmp_swap(f, 0, 1, 1, ZZ) == g assert dmp_swap(g, 0, 1, 1, ZZ) == f raises(IndexError, lambda: dmp_swap(f, -1, -7, 1, ZZ)) def test_dmp_permute(): f = dmp_normal([[1, 0, 0], [], [1, 0], [], [1]], 1, ZZ) g = dmp_normal([[1, 0, 0, 0, 0], [1, 0, 0], [1]], 1, ZZ) assert dmp_permute(f, [0, 1], 1, ZZ) == f assert dmp_permute(g, [0, 1], 1, ZZ) == g assert dmp_permute(f, [1, 0], 1, ZZ) == g assert dmp_permute(g, [1, 0], 1, ZZ) == f def test_dmp_nest(): assert dmp_nest(ZZ(1), 2, ZZ) == [[[1]]] assert dmp_nest([[1]], 0, ZZ) == [[1]] assert dmp_nest([[1]], 1, ZZ) == [[[1]]] assert dmp_nest([[1]], 2, ZZ) == [[[[1]]]] def test_dmp_raise(): assert dmp_raise([], 2, 0, ZZ) == [[[]]] assert dmp_raise([[1]], 0, 1, ZZ) == [[1]] assert dmp_raise([[1, 2, 3], [], [2, 3]], 2, 1, ZZ) == \ [[[[1]], [[2]], [[3]]], [[[]]], [[[2]], [[3]]]] def test_dup_deflate(): assert dup_deflate([], ZZ) == (1, []) assert dup_deflate([2], ZZ) == (1, [2]) assert dup_deflate([1, 2, 3], ZZ) == (1, [1, 2, 3]) assert dup_deflate([1, 0, 2, 0, 3], ZZ) == (2, [1, 2, 3]) assert dup_deflate(dup_from_raw_dict({7: 1, 1: 1}, ZZ), ZZ) == \ (1, [1, 0, 0, 0, 0, 0, 1, 0]) assert dup_deflate(dup_from_raw_dict({7: 1, 0: 1}, ZZ), ZZ) == \ (7, [1, 1]) assert dup_deflate(dup_from_raw_dict({7: 1, 3: 1}, ZZ), ZZ) == \ (1, [1, 0, 0, 0, 1, 0, 0, 0]) assert dup_deflate(dup_from_raw_dict({7: 1, 4: 1}, ZZ), ZZ) == \ (1, [1, 0, 0, 1, 0, 0, 0, 0]) assert dup_deflate(dup_from_raw_dict({8: 1, 4: 1}, ZZ), ZZ) == \ (4, [1, 1, 0]) assert dup_deflate(dup_from_raw_dict({8: 1}, ZZ), ZZ) == \ (8, [1, 0]) assert dup_deflate(dup_from_raw_dict({7: 1}, ZZ), ZZ) == \ (7, [1, 0]) assert dup_deflate(dup_from_raw_dict({1: 1}, ZZ), ZZ) == \ (1, [1, 0]) def test_dmp_deflate(): assert dmp_deflate([[]], 1, ZZ) == ((1, 1), [[]]) assert dmp_deflate([[2]], 1, ZZ) == ((1, 1), [[2]]) f = [[1, 0, 0], [], [1, 0], [], [1]] assert dmp_deflate(f, 1, ZZ) == ((2, 1), [[1, 0, 0], [1, 0], [1]]) def test_dup_multi_deflate(): assert dup_multi_deflate(([2],), ZZ) == (1, ([2],)) assert dup_multi_deflate(([], []), ZZ) == (1, ([], [])) assert dup_multi_deflate(([1, 2, 3],), ZZ) == (1, ([1, 2, 3],)) assert dup_multi_deflate(([1, 0, 2, 0, 3],), ZZ) == (2, ([1, 2, 3],)) assert dup_multi_deflate(([1, 0, 2, 0, 3], [2, 0, 0]), ZZ) == \ (2, ([1, 2, 3], [2, 0])) assert dup_multi_deflate(([1, 0, 2, 0, 3], [2, 1, 0]), ZZ) == \ (1, ([1, 0, 2, 0, 3], [2, 1, 0])) def test_dmp_multi_deflate(): assert dmp_multi_deflate(([[]],), 1, ZZ) == \ ((1, 1), ([[]],)) assert dmp_multi_deflate(([[]], [[]]), 1, ZZ) == \ ((1, 1), ([[]], [[]])) assert dmp_multi_deflate(([[1]], [[]]), 1, ZZ) == \ ((1, 1), ([[1]], [[]])) assert dmp_multi_deflate(([[1]], [[2]]), 1, ZZ) == \ ((1, 1), ([[1]], [[2]])) assert dmp_multi_deflate(([[1]], [[2, 0]]), 1, ZZ) == \ ((1, 1), ([[1]], [[2, 0]])) assert dmp_multi_deflate(([[2, 0]], [[2, 0]]), 1, ZZ) == \ ((1, 1), ([[2, 0]], [[2, 0]])) assert dmp_multi_deflate( ([[2]], [[2, 0, 0]]), 1, ZZ) == ((1, 2), ([[2]], [[2, 0]])) assert dmp_multi_deflate( ([[2, 0, 0]], [[2, 0, 0]]), 1, ZZ) == ((1, 2), ([[2, 0]], [[2, 0]])) assert dmp_multi_deflate(([2, 0, 0], [1, 0, 4, 0, 1]), 0, ZZ) == \ ((2,), ([2, 0], [1, 4, 1])) f = [[1, 0, 0], [], [1, 0], [], [1]] g = [[1, 0, 1, 0], [], [1]] assert dmp_multi_deflate((f,), 1, ZZ) == \ ((2, 1), ([[1, 0, 0], [1, 0], [1]],)) assert dmp_multi_deflate((f, g), 1, ZZ) == \ ((2, 1), ([[1, 0, 0], [1, 0], [1]], [[1, 0, 1, 0], [1]])) def test_dup_inflate(): assert dup_inflate([], 17, ZZ) == [] assert dup_inflate([1, 2, 3], 1, ZZ) == [1, 2, 3] assert dup_inflate([1, 2, 3], 2, ZZ) == [1, 0, 2, 0, 3] assert dup_inflate([1, 2, 3], 3, ZZ) == [1, 0, 0, 2, 0, 0, 3] assert dup_inflate([1, 2, 3], 4, ZZ) == [1, 0, 0, 0, 2, 0, 0, 0, 3] raises(IndexError, lambda: dup_inflate([1, 2, 3], 0, ZZ)) def test_dmp_inflate(): assert dmp_inflate([1], (3,), 0, ZZ) == [1] assert dmp_inflate([[]], (3, 7), 1, ZZ) == [[]] assert dmp_inflate([[2]], (1, 2), 1, ZZ) == [[2]] assert dmp_inflate([[2, 0]], (1, 1), 1, ZZ) == [[2, 0]] assert dmp_inflate([[2, 0]], (1, 2), 1, ZZ) == [[2, 0, 0]] assert dmp_inflate([[2, 0]], (1, 3), 1, ZZ) == [[2, 0, 0, 0]] assert dmp_inflate([[1, 0, 0], [1], [1, 0]], (2, 1), 1, ZZ) == \ [[1, 0, 0], [], [1], [], [1, 0]] raises(IndexError, lambda: dmp_inflate([[]], (-3, 7), 1, ZZ)) def test_dmp_exclude(): assert dmp_exclude([[[]]], 2, ZZ) == ([], [[[]]], 2) assert dmp_exclude([[[7]]], 2, ZZ) == ([], [[[7]]], 2) assert dmp_exclude([1, 2, 3], 0, ZZ) == ([], [1, 2, 3], 0) assert dmp_exclude([[1], [2, 3]], 1, ZZ) == ([], [[1], [2, 3]], 1) assert dmp_exclude([[1, 2, 3]], 1, ZZ) == ([0], [1, 2, 3], 0) assert dmp_exclude([[1], [2], [3]], 1, ZZ) == ([1], [1, 2, 3], 0) assert dmp_exclude([[[1, 2, 3]]], 2, ZZ) == ([0, 1], [1, 2, 3], 0) assert dmp_exclude([[[1]], [[2]], [[3]]], 2, ZZ) == ([1, 2], [1, 2, 3], 0) def test_dmp_include(): assert dmp_include([1, 2, 3], [], 0, ZZ) == [1, 2, 3] assert dmp_include([1, 2, 3], [0], 0, ZZ) == [[1, 2, 3]] assert dmp_include([1, 2, 3], [1], 0, ZZ) == [[1], [2], [3]] assert dmp_include([1, 2, 3], [0, 1], 0, ZZ) == [[[1, 2, 3]]] assert dmp_include([1, 2, 3], [1, 2], 0, ZZ) == [[[1]], [[2]], [[3]]] def test_dmp_inject(): R, x,y = ring("x,y", ZZ) K = R.to_domain() assert dmp_inject([], 0, K) == ([[[]]], 2) assert dmp_inject([[]], 1, K) == ([[[[]]]], 3) assert dmp_inject([R(1)], 0, K) == ([[[1]]], 2) assert dmp_inject([[R(1)]], 1, K) == ([[[[1]]]], 3) assert dmp_inject([R(1), 2*x + 3*y + 4], 0, K) == ([[[1]], [[2], [3, 4]]], 2) f = [3*x**2 + 7*x*y + 5*y**2, 2*x, R(0), x*y**2 + 11] g = [[[3], [7, 0], [5, 0, 0]], [[2], []], [[]], [[1, 0, 0], [11]]] assert dmp_inject(f, 0, K) == (g, 2) def test_dmp_eject(): R, x,y = ring("x,y", ZZ) K = R.to_domain() assert dmp_eject([[[]]], 2, K) == [] assert dmp_eject([[[[]]]], 3, K) == [[]] assert dmp_eject([[[1]]], 2, K) == [R(1)] assert dmp_eject([[[[1]]]], 3, K) == [[R(1)]] assert dmp_eject([[[1]], [[2], [3, 4]]], 2, K) == [R(1), 2*x + 3*y + 4] f = [3*x**2 + 7*x*y + 5*y**2, 2*x, R(0), x*y**2 + 11] g = [[[3], [7, 0], [5, 0, 0]], [[2], []], [[]], [[1, 0, 0], [11]]] assert dmp_eject(g, 2, K) == f def test_dup_terms_gcd(): assert dup_terms_gcd([], ZZ) == (0, []) assert dup_terms_gcd([1, 0, 1], ZZ) == (0, [1, 0, 1]) assert dup_terms_gcd([1, 0, 1, 0], ZZ) == (1, [1, 0, 1]) def test_dmp_terms_gcd(): assert dmp_terms_gcd([[]], 1, ZZ) == ((0, 0), [[]]) assert dmp_terms_gcd([1, 0, 1, 0], 0, ZZ) == ((1,), [1, 0, 1]) assert dmp_terms_gcd([[1], [], [1], []], 1, ZZ) == ((1, 0), [[1], [], [1]]) assert dmp_terms_gcd( [[1, 0], [], [1]], 1, ZZ) == ((0, 0), [[1, 0], [], [1]]) assert dmp_terms_gcd( [[1, 0], [1, 0, 0], [], []], 1, ZZ) == ((2, 1), [[1], [1, 0]]) def test_dmp_list_terms(): assert dmp_list_terms([[[]]], 2, ZZ) == [((0, 0, 0), 0)] assert dmp_list_terms([[[1]]], 2, ZZ) == [((0, 0, 0), 1)] assert dmp_list_terms([1, 2, 4, 3, 5], 0, ZZ) == \ [((4,), 1), ((3,), 2), ((2,), 4), ((1,), 3), ((0,), 5)] assert dmp_list_terms([[1], [2, 4], [3, 5, 0]], 1, ZZ) == \ [((2, 0), 1), ((1, 1), 2), ((1, 0), 4), ((0, 2), 3), ((0, 1), 5)] f = [[2, 0, 0, 0], [1, 0, 0], []] assert dmp_list_terms(f, 1, ZZ, order='lex') == [((2, 3), 2), ((1, 2), 1)] assert dmp_list_terms( f, 1, ZZ, order='grlex') == [((2, 3), 2), ((1, 2), 1)] f = [[2, 0, 0, 0], [1, 0, 0, 0, 0, 0], []] assert dmp_list_terms(f, 1, ZZ, order='lex') == [((2, 3), 2), ((1, 5), 1)] assert dmp_list_terms( f, 1, ZZ, order='grlex') == [((1, 5), 1), ((2, 3), 2)] def test_dmp_apply_pairs(): h = lambda a, b: a*b assert dmp_apply_pairs([1, 2, 3], [4, 5, 6], h, [], 0, ZZ) == [4, 10, 18] assert dmp_apply_pairs([2, 3], [4, 5, 6], h, [], 0, ZZ) == [10, 18] assert dmp_apply_pairs([1, 2, 3], [5, 6], h, [], 0, ZZ) == [10, 18] assert dmp_apply_pairs( [[1, 2], [3]], [[4, 5], [6]], h, [], 1, ZZ) == [[4, 10], [18]] assert dmp_apply_pairs( [[1, 2], [3]], [[4], [5, 6]], h, [], 1, ZZ) == [[8], [18]] assert dmp_apply_pairs( [[1], [2, 3]], [[4, 5], [6]], h, [], 1, ZZ) == [[5], [18]] def test_dup_slice(): f = [1, 2, 3, 4] assert dup_slice(f, 0, 0, ZZ) == [] assert dup_slice(f, 0, 1, ZZ) == [4] assert dup_slice(f, 0, 2, ZZ) == [3, 4] assert dup_slice(f, 0, 3, ZZ) == [2, 3, 4] assert dup_slice(f, 0, 4, ZZ) == [1, 2, 3, 4] assert dup_slice(f, 0, 4, ZZ) == f assert dup_slice(f, 0, 9, ZZ) == f assert dup_slice(f, 1, 0, ZZ) == [] assert dup_slice(f, 1, 1, ZZ) == [] assert dup_slice(f, 1, 2, ZZ) == [3, 0] assert dup_slice(f, 1, 3, ZZ) == [2, 3, 0] assert dup_slice(f, 1, 4, ZZ) == [1, 2, 3, 0] assert dup_slice([1, 2], 0, 3, ZZ) == [1, 2] def test_dup_random(): f = dup_random(0, -10, 10, ZZ) assert dup_degree(f) == 0 assert all(-10 <= c <= 10 for c in f) f = dup_random(1, -20, 20, ZZ) assert dup_degree(f) == 1 assert all(-20 <= c <= 20 for c in f) f = dup_random(2, -30, 30, ZZ) assert dup_degree(f) == 2 assert all(-30 <= c <= 30 for c in f) f = dup_random(3, -40, 40, ZZ) assert dup_degree(f) == 3 assert all(-40 <= c <= 40 for c in f)
a65d95acdfddd9718e547bef02768d43391d153750823b7d78f828e35b28051b
from sympy.testing.pytest import raises from sympy.polys.polymatrix import PolyMatrix from sympy.polys import Poly from sympy.core.singleton import S from sympy.matrices.dense import Matrix from sympy.polys.domains.integerring import ZZ from sympy.polys.domains.rationalfield import QQ from sympy.abc import x, y def _test_polymatrix(): pm1 = PolyMatrix([[Poly(x**2, x), Poly(-x, x)], [Poly(x**3, x), Poly(-1 + x, x)]]) v1 = PolyMatrix([[1, 0], [-1, 0]], ring='ZZ[x]') m1 = PolyMatrix([[1, 0], [-1, 0]], ring='ZZ[x]') A = PolyMatrix([[Poly(x**2 + x, x), Poly(0, x)], \ [Poly(x**3 - x + 1, x), Poly(0, x)]]) B = PolyMatrix([[Poly(x**2, x), Poly(-x, x)], [Poly(-x**2, x), Poly(x, x)]]) assert A.ring == ZZ[x] assert isinstance(pm1*v1, PolyMatrix) assert pm1*v1 == A assert pm1*m1 == A assert v1*pm1 == B pm2 = PolyMatrix([[Poly(x**2, x, domain='QQ'), Poly(0, x, domain='QQ'), Poly(-x**2, x, domain='QQ'), \ Poly(x**3, x, domain='QQ'), Poly(0, x, domain='QQ'), Poly(-x**3, x, domain='QQ')]]) assert pm2.ring == QQ[x] v2 = PolyMatrix([1, 0, 0, 0, 0, 0], ring='ZZ[x]') m2 = PolyMatrix([1, 0, 0, 0, 0, 0], ring='ZZ[x]') C = PolyMatrix([[Poly(x**2, x, domain='QQ')]]) assert pm2*v2 == C assert pm2*m2 == C pm3 = PolyMatrix([[Poly(x**2, x), S.One]], ring='ZZ[x]') v3 = S.Half*pm3 assert v3 == PolyMatrix([[Poly(S.Half*x**2, x, domain='QQ'), S.Half]], ring='QQ[x]') assert pm3*S.Half == v3 assert v3.ring == QQ[x] pm4 = PolyMatrix([[Poly(x**2, x, domain='ZZ'), Poly(-x**2, x, domain='ZZ')]]) v4 = PolyMatrix([1, -1], ring='ZZ[x]') assert pm4*v4 == PolyMatrix([[Poly(2*x**2, x, domain='ZZ')]]) assert len(PolyMatrix(ring=ZZ[x])) == 0 assert PolyMatrix([1, 0, 0, 1], x)/(-1) == PolyMatrix([-1, 0, 0, -1], x) def test_polymatrix_constructor(): M1 = PolyMatrix([[x, y]], ring=QQ[x,y]) assert M1.ring == QQ[x,y] assert M1.domain == QQ assert M1.gens == (x, y) assert M1.shape == (1, 2) assert M1.rows == 1 assert M1.cols == 2 assert len(M1) == 2 assert list(M1) == [Poly(x, (x, y), domain=QQ), Poly(y, (x, y), domain=QQ)] M2 = PolyMatrix([[x, y]], ring=QQ[x][y]) assert M2.ring == QQ[x][y] assert M2.domain == QQ[x] assert M2.gens == (y,) assert M2.shape == (1, 2) assert M2.rows == 1 assert M2.cols == 2 assert len(M2) == 2 assert list(M2) == [Poly(x, (y,), domain=QQ[x]), Poly(y, (y,), domain=QQ[x])] assert PolyMatrix([[x, y]], y) == PolyMatrix([[x, y]], ring=ZZ.frac_field(x)[y]) assert PolyMatrix([[x, y]], ring='ZZ[x,y]') == PolyMatrix([[x, y]], ring=ZZ[x,y]) assert PolyMatrix([[x, y]], (x, y)) == PolyMatrix([[x, y]], ring=QQ[x,y]) assert PolyMatrix([[x, y]], x, y) == PolyMatrix([[x, y]], ring=QQ[x,y]) assert PolyMatrix([x, y]) == PolyMatrix([[x], [y]], ring=QQ[x,y]) assert PolyMatrix(1, 2, [x, y]) == PolyMatrix([[x, y]], ring=QQ[x,y]) assert PolyMatrix(1, 2, lambda i,j: [x,y][j]) == PolyMatrix([[x, y]], ring=QQ[x,y]) assert PolyMatrix(0, 2, [], x, y).shape == (0, 2) assert PolyMatrix(2, 0, [], x, y).shape == (2, 0) assert PolyMatrix([[], []], x, y).shape == (2, 0) assert PolyMatrix(ring=QQ[x,y]) == PolyMatrix(0, 0, [], ring=QQ[x,y]) == PolyMatrix([], ring=QQ[x,y]) raises(TypeError, lambda: PolyMatrix()) raises(TypeError, lambda: PolyMatrix(1)) assert PolyMatrix([Poly(x), Poly(y)]) == PolyMatrix([[x], [y]], ring=ZZ[x,y]) # XXX: Maybe a bug in parallel_poly_from_expr (x lost from gens and domain): assert PolyMatrix([Poly(y, x), 1]) == PolyMatrix([[y], [1]], ring=QQ[y]) def test_polymatrix_eq(): assert (PolyMatrix([x]) == PolyMatrix([x])) is True assert (PolyMatrix([y]) == PolyMatrix([x])) is False assert (PolyMatrix([x]) != PolyMatrix([x])) is False assert (PolyMatrix([y]) != PolyMatrix([x])) is True assert PolyMatrix([[x, y]]) != PolyMatrix([x, y]) == PolyMatrix([[x], [y]]) assert PolyMatrix([x], ring=QQ[x]) != PolyMatrix([x], ring=ZZ[x]) assert PolyMatrix([x]) != Matrix([x]) assert PolyMatrix([x]).to_Matrix() == Matrix([x]) assert PolyMatrix([1], x) == PolyMatrix([1], x) assert PolyMatrix([1], x) != PolyMatrix([1], y) def test_polymatrix_from_Matrix(): assert PolyMatrix.from_Matrix(Matrix([1, 2]), x) == PolyMatrix([1, 2], x, ring=QQ[x]) assert PolyMatrix.from_Matrix(Matrix([1]), ring=QQ[x]) == PolyMatrix([1], x) pmx = PolyMatrix([1, 2], x) pmy = PolyMatrix([1, 2], y) assert pmx != pmy assert pmx.set_gens(y) == pmy def test_polymatrix_repr(): assert repr(PolyMatrix([[1, 2]], x)) == 'PolyMatrix([[1, 2]], ring=QQ[x])' assert repr(PolyMatrix(0, 2, [], x)) == 'PolyMatrix(0, 2, [], ring=QQ[x])' def test_polymatrix_getitem(): M = PolyMatrix([[1, 2], [3, 4]], x) assert M[:, :] == M assert M[0, :] == PolyMatrix([[1, 2]], x) assert M[:, 0] == PolyMatrix([1, 3], x) assert M[0, 0] == Poly(1, x, domain=QQ) assert M[0] == Poly(1, x, domain=QQ) assert M[:2] == [Poly(1, x, domain=QQ), Poly(2, x, domain=QQ)] def test_polymatrix_arithmetic(): M = PolyMatrix([[1, 2], [3, 4]], x) assert M + M == PolyMatrix([[2, 4], [6, 8]], x) assert M - M == PolyMatrix([[0, 0], [0, 0]], x) assert -M == PolyMatrix([[-1, -2], [-3, -4]], x) raises(TypeError, lambda: M + 1) raises(TypeError, lambda: M - 1) raises(TypeError, lambda: 1 + M) raises(TypeError, lambda: 1 - M) assert M * M == PolyMatrix([[7, 10], [15, 22]], x) assert 2 * M == PolyMatrix([[2, 4], [6, 8]], x) assert M * 2 == PolyMatrix([[2, 4], [6, 8]], x) assert S(2) * M == PolyMatrix([[2, 4], [6, 8]], x) assert M * S(2) == PolyMatrix([[2, 4], [6, 8]], x) raises(TypeError, lambda: [] * M) raises(TypeError, lambda: M * []) M2 = PolyMatrix([[1, 2]], ring=ZZ[x]) assert S.Half * M2 == PolyMatrix([[S.Half, 1]], ring=QQ[x]) assert M2 * S.Half == PolyMatrix([[S.Half, 1]], ring=QQ[x]) assert M / 2 == PolyMatrix([[S(1)/2, 1], [S(3)/2, 2]], x) assert M / Poly(2, x) == PolyMatrix([[S(1)/2, 1], [S(3)/2, 2]], x) raises(TypeError, lambda: M / []) def test_polymatrix_manipulations(): M1 = PolyMatrix([[1, 2], [3, 4]], x) assert M1.transpose() == PolyMatrix([[1, 3], [2, 4]], x) M2 = PolyMatrix([[5, 6], [7, 8]], x) assert M1.row_join(M2) == PolyMatrix([[1, 2, 5, 6], [3, 4, 7, 8]], x) assert M1.col_join(M2) == PolyMatrix([[1, 2], [3, 4], [5, 6], [7, 8]], x) assert M1.applyfunc(lambda e: 2*e) == PolyMatrix([[2, 4], [6, 8]], x) def test_polymatrix_ones_zeros(): assert PolyMatrix.zeros(1, 2, x) == PolyMatrix([[0, 0]], x) assert PolyMatrix.eye(2, x) == PolyMatrix([[1, 0], [0, 1]], x) def test_polymatrix_rref(): M = PolyMatrix([[1, 2], [3, 4]], x) assert M.rref() == (PolyMatrix.eye(2, x), (0, 1)) raises(ValueError, lambda: PolyMatrix([1, 2], ring=ZZ[x]).rref()) raises(ValueError, lambda: PolyMatrix([1, x], ring=QQ[x]).rref()) def test_polymatrix_nullspace(): M = PolyMatrix([[1, 2], [3, 6]], x) assert M.nullspace() == [PolyMatrix([-2, 1], x)] raises(ValueError, lambda: PolyMatrix([1, 2], ring=ZZ[x]).nullspace()) raises(ValueError, lambda: PolyMatrix([1, x], ring=QQ[x]).nullspace()) assert M.rank() == 1
c24be3ccd3f5207f9276e6cd939249ece59c63eccd17acf7b77da47e9f4d72cd
"""Tests for tools for manipulation of rational expressions. """ from sympy.polys.rationaltools import together from sympy.core.mul import Mul from sympy.core.numbers import Rational from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.trigonometric import sin from sympy.integrals.integrals import Integral from sympy.abc import x, y, z A, B = symbols('A,B', commutative=False) def test_together(): assert together(0) == 0 assert together(1) == 1 assert together(x*y*z) == x*y*z assert together(x + y) == x + y assert together(1/x) == 1/x assert together(1/x + 1) == (x + 1)/x assert together(1/x + 3) == (3*x + 1)/x assert together(1/x + x) == (x**2 + 1)/x assert together(1/x + S.Half) == (x + 2)/(2*x) assert together(S.Half + x/2) == Mul(S.Half, x + 1, evaluate=False) assert together(1/x + 2/y) == (2*x + y)/(y*x) assert together(1/(1 + 1/x)) == x/(1 + x) assert together(x/(1 + 1/x)) == x**2/(1 + x) assert together(1/x + 1/y + 1/z) == (x*y + x*z + y*z)/(x*y*z) assert together(1/(1 + x + 1/y + 1/z)) == y*z/(y + z + y*z + x*y*z) assert together(1/(x*y) + 1/(x*y)**2) == y**(-2)*x**(-2)*(1 + x*y) assert together(1/(x*y) + 1/(x*y)**4) == y**(-4)*x**(-4)*(1 + x**3*y**3) assert together(1/(x**7*y) + 1/(x*y)**4) == y**(-4)*x**(-7)*(x**3 + y**3) assert together(5/(2 + 6/(3 + 7/(4 + 8/(5 + 9/x))))) == \ Rational(5, 2)*((171 + 119*x)/(279 + 203*x)) assert together(1 + 1/(x + 1)**2) == (1 + (x + 1)**2)/(x + 1)**2 assert together(1 + 1/(x*(1 + x))) == (1 + x*(1 + x))/(x*(1 + x)) assert together( 1/(x*(x + 1)) + 1/(x*(x + 2))) == (3 + 2*x)/(x*(1 + x)*(2 + x)) assert together(1 + 1/(2*x + 2)**2) == (4*(x + 1)**2 + 1)/(4*(x + 1)**2) assert together(sin(1/x + 1/y)) == sin(1/x + 1/y) assert together(sin(1/x + 1/y), deep=True) == sin((x + y)/(x*y)) assert together(1/exp(x) + 1/(x*exp(x))) == (1 + x)/(x*exp(x)) assert together(1/exp(2*x) + 1/(x*exp(3*x))) == (1 + exp(x)*x)/(x*exp(3*x)) assert together(Integral(1/x + 1/y, x)) == Integral((x + y)/(x*y), x) assert together(Eq(1/x + 1/y, 1 + 1/z)) == Eq((x + y)/(x*y), (z + 1)/z) assert together((A*B)**-1 + (B*A)**-1) == (A*B)**-1 + (B*A)**-1
42cdd0425d166264e7918136a2f4f174b7aee8362758efcea1498bc0d0d9cd2c
"""Tests for useful utilities for higher level polynomial classes. """ from sympy.core.mul import Mul from sympy.core.numbers import (Integer, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.integrals.integrals import Integral from sympy.testing.pytest import raises from sympy.polys.polyutils import ( _nsort, _sort_gens, _unify_gens, _analyze_gens, _sort_factors, parallel_dict_from_expr, dict_from_expr, ) from sympy.polys.polyerrors import PolynomialError from sympy.polys.domains import ZZ x, y, z, p, q, r, s, t, u, v, w = symbols('x,y,z,p,q,r,s,t,u,v,w') A, B = symbols('A,B', commutative=False) def test__nsort(): # issue 6137 r = S('''[3/2 + sqrt(-14/3 - 2*(-415/216 + 13*I/12)**(1/3) - 4/sqrt(-7/3 + 61/(18*(-415/216 + 13*I/12)**(1/3)) + 2*(-415/216 + 13*I/12)**(1/3)) - 61/(18*(-415/216 + 13*I/12)**(1/3)))/2 - sqrt(-7/3 + 61/(18*(-415/216 + 13*I/12)**(1/3)) + 2*(-415/216 + 13*I/12)**(1/3))/2, 3/2 - sqrt(-7/3 + 61/(18*(-415/216 + 13*I/12)**(1/3)) + 2*(-415/216 + 13*I/12)**(1/3))/2 - sqrt(-14/3 - 2*(-415/216 + 13*I/12)**(1/3) - 4/sqrt(-7/3 + 61/(18*(-415/216 + 13*I/12)**(1/3)) + 2*(-415/216 + 13*I/12)**(1/3)) - 61/(18*(-415/216 + 13*I/12)**(1/3)))/2, 3/2 + sqrt(-14/3 - 2*(-415/216 + 13*I/12)**(1/3) + 4/sqrt(-7/3 + 61/(18*(-415/216 + 13*I/12)**(1/3)) + 2*(-415/216 + 13*I/12)**(1/3)) - 61/(18*(-415/216 + 13*I/12)**(1/3)))/2 + sqrt(-7/3 + 61/(18*(-415/216 + 13*I/12)**(1/3)) + 2*(-415/216 + 13*I/12)**(1/3))/2, 3/2 + sqrt(-7/3 + 61/(18*(-415/216 + 13*I/12)**(1/3)) + 2*(-415/216 + 13*I/12)**(1/3))/2 - sqrt(-14/3 - 2*(-415/216 + 13*I/12)**(1/3) + 4/sqrt(-7/3 + 61/(18*(-415/216 + 13*I/12)**(1/3)) + 2*(-415/216 + 13*I/12)**(1/3)) - 61/(18*(-415/216 + 13*I/12)**(1/3)))/2]''') ans = [r[1], r[0], r[-1], r[-2]] assert _nsort(r) == ans assert len(_nsort(r, separated=True)[0]) == 0 b, c, a = exp(-1000), exp(-999), exp(-1001) assert _nsort((b, c, a)) == [a, b, c] # issue 12560 a = cos(1)**2 + sin(1)**2 - 1 assert _nsort([a]) == [a] def test__sort_gens(): assert _sort_gens([]) == () assert _sort_gens([x]) == (x,) assert _sort_gens([p]) == (p,) assert _sort_gens([q]) == (q,) assert _sort_gens([x, p]) == (x, p) assert _sort_gens([p, x]) == (x, p) assert _sort_gens([q, p]) == (p, q) assert _sort_gens([q, p, x]) == (x, p, q) assert _sort_gens([x, p, q], wrt=x) == (x, p, q) assert _sort_gens([x, p, q], wrt=p) == (p, x, q) assert _sort_gens([x, p, q], wrt=q) == (q, x, p) assert _sort_gens([x, p, q], wrt='x') == (x, p, q) assert _sort_gens([x, p, q], wrt='p') == (p, x, q) assert _sort_gens([x, p, q], wrt='q') == (q, x, p) assert _sort_gens([x, p, q], wrt='x,q') == (x, q, p) assert _sort_gens([x, p, q], wrt='q,x') == (q, x, p) assert _sort_gens([x, p, q], wrt='p,q') == (p, q, x) assert _sort_gens([x, p, q], wrt='q,p') == (q, p, x) assert _sort_gens([x, p, q], wrt='x, q') == (x, q, p) assert _sort_gens([x, p, q], wrt='q, x') == (q, x, p) assert _sort_gens([x, p, q], wrt='p, q') == (p, q, x) assert _sort_gens([x, p, q], wrt='q, p') == (q, p, x) assert _sort_gens([x, p, q], wrt=[x, 'q']) == (x, q, p) assert _sort_gens([x, p, q], wrt=[q, 'x']) == (q, x, p) assert _sort_gens([x, p, q], wrt=[p, 'q']) == (p, q, x) assert _sort_gens([x, p, q], wrt=[q, 'p']) == (q, p, x) assert _sort_gens([x, p, q], wrt=['x', 'q']) == (x, q, p) assert _sort_gens([x, p, q], wrt=['q', 'x']) == (q, x, p) assert _sort_gens([x, p, q], wrt=['p', 'q']) == (p, q, x) assert _sort_gens([x, p, q], wrt=['q', 'p']) == (q, p, x) assert _sort_gens([x, p, q], sort='x > p > q') == (x, p, q) assert _sort_gens([x, p, q], sort='p > x > q') == (p, x, q) assert _sort_gens([x, p, q], sort='p > q > x') == (p, q, x) assert _sort_gens([x, p, q], wrt='x', sort='q > p') == (x, q, p) assert _sort_gens([x, p, q], wrt='p', sort='q > x') == (p, q, x) assert _sort_gens([x, p, q], wrt='q', sort='p > x') == (q, p, x) # https://github.com/sympy/sympy/issues/19353 n1 = Symbol('\n1') assert _sort_gens([n1]) == (n1,) assert _sort_gens([x, n1]) == (x, n1) X = symbols('x0,x1,x2,x10,x11,x12,x20,x21,x22') assert _sort_gens(X) == X def test__unify_gens(): assert _unify_gens([], []) == () assert _unify_gens([x], [x]) == (x,) assert _unify_gens([y], [y]) == (y,) assert _unify_gens([x, y], [x]) == (x, y) assert _unify_gens([x], [x, y]) == (x, y) assert _unify_gens([x, y], [x, y]) == (x, y) assert _unify_gens([y, x], [y, x]) == (y, x) assert _unify_gens([x], [y]) == (x, y) assert _unify_gens([y], [x]) == (y, x) assert _unify_gens([x], [y, x]) == (y, x) assert _unify_gens([y, x], [x]) == (y, x) assert _unify_gens([x, y, z], [x, y, z]) == (x, y, z) assert _unify_gens([z, y, x], [x, y, z]) == (z, y, x) assert _unify_gens([x, y, z], [z, y, x]) == (x, y, z) assert _unify_gens([z, y, x], [z, y, x]) == (z, y, x) assert _unify_gens([x, y, z], [t, x, p, q, z]) == (t, x, y, p, q, z) def test__analyze_gens(): assert _analyze_gens((x, y, z)) == (x, y, z) assert _analyze_gens([x, y, z]) == (x, y, z) assert _analyze_gens(([x, y, z],)) == (x, y, z) assert _analyze_gens(((x, y, z),)) == (x, y, z) def test__sort_factors(): assert _sort_factors([], multiple=True) == [] assert _sort_factors([], multiple=False) == [] F = [[1, 2, 3], [1, 2], [1]] G = [[1], [1, 2], [1, 2, 3]] assert _sort_factors(F, multiple=False) == G F = [[1, 2], [1, 2, 3], [1, 2], [1]] G = [[1], [1, 2], [1, 2], [1, 2, 3]] assert _sort_factors(F, multiple=False) == G F = [[2, 2], [1, 2, 3], [1, 2], [1]] G = [[1], [1, 2], [2, 2], [1, 2, 3]] assert _sort_factors(F, multiple=False) == G F = [([1, 2, 3], 1), ([1, 2], 1), ([1], 1)] G = [([1], 1), ([1, 2], 1), ([1, 2, 3], 1)] assert _sort_factors(F, multiple=True) == G F = [([1, 2], 1), ([1, 2, 3], 1), ([1, 2], 1), ([1], 1)] G = [([1], 1), ([1, 2], 1), ([1, 2], 1), ([1, 2, 3], 1)] assert _sort_factors(F, multiple=True) == G F = [([2, 2], 1), ([1, 2, 3], 1), ([1, 2], 1), ([1], 1)] G = [([1], 1), ([1, 2], 1), ([2, 2], 1), ([1, 2, 3], 1)] assert _sort_factors(F, multiple=True) == G F = [([2, 2], 1), ([1, 2, 3], 1), ([1, 2], 2), ([1], 1)] G = [([1], 1), ([2, 2], 1), ([1, 2], 2), ([1, 2, 3], 1)] assert _sort_factors(F, multiple=True) == G def test__dict_from_expr_if_gens(): assert dict_from_expr( Integer(17), gens=(x,)) == ({(0,): Integer(17)}, (x,)) assert dict_from_expr( Integer(17), gens=(x, y)) == ({(0, 0): Integer(17)}, (x, y)) assert dict_from_expr( Integer(17), gens=(x, y, z)) == ({(0, 0, 0): Integer(17)}, (x, y, z)) assert dict_from_expr( Integer(-17), gens=(x,)) == ({(0,): Integer(-17)}, (x,)) assert dict_from_expr( Integer(-17), gens=(x, y)) == ({(0, 0): Integer(-17)}, (x, y)) assert dict_from_expr(Integer( -17), gens=(x, y, z)) == ({(0, 0, 0): Integer(-17)}, (x, y, z)) assert dict_from_expr( Integer(17)*x, gens=(x,)) == ({(1,): Integer(17)}, (x,)) assert dict_from_expr( Integer(17)*x, gens=(x, y)) == ({(1, 0): Integer(17)}, (x, y)) assert dict_from_expr(Integer( 17)*x, gens=(x, y, z)) == ({(1, 0, 0): Integer(17)}, (x, y, z)) assert dict_from_expr( Integer(17)*x**7, gens=(x,)) == ({(7,): Integer(17)}, (x,)) assert dict_from_expr( Integer(17)*x**7*y, gens=(x, y)) == ({(7, 1): Integer(17)}, (x, y)) assert dict_from_expr(Integer(17)*x**7*y*z**12, gens=( x, y, z)) == ({(7, 1, 12): Integer(17)}, (x, y, z)) assert dict_from_expr(x + 2*y + 3*z, gens=(x,)) == \ ({(1,): Integer(1), (0,): 2*y + 3*z}, (x,)) assert dict_from_expr(x + 2*y + 3*z, gens=(x, y)) == \ ({(1, 0): Integer(1), (0, 1): Integer(2), (0, 0): 3*z}, (x, y)) assert dict_from_expr(x + 2*y + 3*z, gens=(x, y, z)) == \ ({(1, 0, 0): Integer( 1), (0, 1, 0): Integer(2), (0, 0, 1): Integer(3)}, (x, y, z)) assert dict_from_expr(x*y + 2*x*z + 3*y*z, gens=(x,)) == \ ({(1,): y + 2*z, (0,): 3*y*z}, (x,)) assert dict_from_expr(x*y + 2*x*z + 3*y*z, gens=(x, y)) == \ ({(1, 1): Integer(1), (1, 0): 2*z, (0, 1): 3*z}, (x, y)) assert dict_from_expr(x*y + 2*x*z + 3*y*z, gens=(x, y, z)) == \ ({(1, 1, 0): Integer( 1), (1, 0, 1): Integer(2), (0, 1, 1): Integer(3)}, (x, y, z)) assert dict_from_expr(2**y*x, gens=(x,)) == ({(1,): 2**y}, (x,)) assert dict_from_expr(Integral(x, (x, 1, 2)) + x) == ( {(0, 1): 1, (1, 0): 1}, (x, Integral(x, (x, 1, 2)))) raises(PolynomialError, lambda: dict_from_expr(2**y*x, gens=(x, y))) def test__dict_from_expr_no_gens(): assert dict_from_expr(Integer(17)) == ({(): Integer(17)}, ()) assert dict_from_expr(x) == ({(1,): Integer(1)}, (x,)) assert dict_from_expr(y) == ({(1,): Integer(1)}, (y,)) assert dict_from_expr(x*y) == ({(1, 1): Integer(1)}, (x, y)) assert dict_from_expr( x + y) == ({(1, 0): Integer(1), (0, 1): Integer(1)}, (x, y)) assert dict_from_expr(sqrt(2)) == ({(1,): Integer(1)}, (sqrt(2),)) assert dict_from_expr(sqrt(2), greedy=False) == ({(): sqrt(2)}, ()) assert dict_from_expr(x*y, domain=ZZ[x]) == ({(1,): x}, (y,)) assert dict_from_expr(x*y, domain=ZZ[y]) == ({(1,): y}, (x,)) assert dict_from_expr(3*sqrt( 2)*pi*x*y, extension=None) == ({(1, 1, 1, 1): 3}, (x, y, pi, sqrt(2))) assert dict_from_expr(3*sqrt( 2)*pi*x*y, extension=True) == ({(1, 1, 1): 3*sqrt(2)}, (x, y, pi)) assert dict_from_expr(3*sqrt( 2)*pi*x*y, extension=True) == ({(1, 1, 1): 3*sqrt(2)}, (x, y, pi)) f = cos(x)*sin(x) + cos(x)*sin(y) + cos(y)*sin(x) + cos(y)*sin(y) assert dict_from_expr(f) == ({(0, 1, 0, 1): 1, (0, 1, 1, 0): 1, (1, 0, 0, 1): 1, (1, 0, 1, 0): 1}, (cos(x), cos(y), sin(x), sin(y))) def test__parallel_dict_from_expr_if_gens(): assert parallel_dict_from_expr([x + 2*y + 3*z, Integer(7)], gens=(x,)) == \ ([{(1,): Integer(1), (0,): 2*y + 3*z}, {(0,): Integer(7)}], (x,)) def test__parallel_dict_from_expr_no_gens(): assert parallel_dict_from_expr([x*y, Integer(3)]) == \ ([{(1, 1): Integer(1)}, {(0, 0): Integer(3)}], (x, y)) assert parallel_dict_from_expr([x*y, 2*z, Integer(3)]) == \ ([{(1, 1, 0): Integer( 1)}, {(0, 0, 1): Integer(2)}, {(0, 0, 0): Integer(3)}], (x, y, z)) assert parallel_dict_from_expr((Mul(x, x**2, evaluate=False),)) == \ ([{(3,): 1}], (x,)) def test_parallel_dict_from_expr(): assert parallel_dict_from_expr([Eq(x, 1), Eq( x**2, 2)]) == ([{(0,): -Integer(1), (1,): Integer(1)}, {(0,): -Integer(2), (2,): Integer(1)}], (x,)) raises(PolynomialError, lambda: parallel_dict_from_expr([A*B - B*A])) def test_dict_from_expr(): assert dict_from_expr(Eq(x, 1)) == \ ({(0,): -Integer(1), (1,): Integer(1)}, (x,)) raises(PolynomialError, lambda: dict_from_expr(A*B - B*A)) raises(PolynomialError, lambda: dict_from_expr(S.true))
7baa7375b9cfe2831c501776294b796644119c3730e5650e2ee05b82bd503a16
"""Tests for algorithms for computing symbolic roots of polynomials. """ from sympy.core.numbers import (I, Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, Wild, symbols) from sympy.functions.elementary.complexes import (conjugate, im, re) from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import (root, sqrt) from sympy.functions.elementary.piecewise import Piecewise from sympy.functions.elementary.trigonometric import (acos, cos, sin) from sympy.polys.domains.integerring import ZZ from sympy.sets.sets import Interval from sympy.simplify.powsimp import powsimp from sympy.polys import Poly, cyclotomic_poly, intervals, nroots, rootof from sympy.polys.polyroots import (root_factors, roots_linear, roots_quadratic, roots_cubic, roots_quartic, roots_cyclotomic, roots_binomial, preprocess_roots, roots) from sympy.polys.orthopolys import legendre_poly from sympy.polys.polyerrors import PolynomialError from sympy.polys.polyutils import _nsort from sympy.testing.pytest import raises, slow from sympy.testing.randtest import verify_numerically import mpmath from itertools import product a, b, c, d, e, q, t, x, y, z = symbols('a,b,c,d,e,q,t,x,y,z') def _check(roots): # this is the desired invariant for roots returned # by all_roots. It is trivially true for linear # polynomials. nreal = sum([1 if i.is_real else 0 for i in roots]) assert list(sorted(roots[:nreal])) == list(roots[:nreal]) for ix in range(nreal, len(roots), 2): if not ( roots[ix + 1] == roots[ix] or roots[ix + 1] == conjugate(roots[ix])): return False return True def test_roots_linear(): assert roots_linear(Poly(2*x + 1, x)) == [Rational(-1, 2)] def test_roots_quadratic(): assert roots_quadratic(Poly(2*x**2, x)) == [0, 0] assert roots_quadratic(Poly(2*x**2 + 3*x, x)) == [Rational(-3, 2), 0] assert roots_quadratic(Poly(2*x**2 + 3, x)) == [-I*sqrt(6)/2, I*sqrt(6)/2] assert roots_quadratic(Poly(2*x**2 + 4*x + 3, x)) == [-1 - I*sqrt(2)/2, -1 + I*sqrt(2)/2] _check(Poly(2*x**2 + 4*x + 3, x).all_roots()) f = x**2 + (2*a*e + 2*c*e)/(a - c)*x + (d - b + a*e**2 - c*e**2)/(a - c) assert roots_quadratic(Poly(f, x)) == \ [-e*(a + c)/(a - c) - sqrt(a*b + c*d - a*d - b*c + 4*a*c*e**2)/(a - c), -e*(a + c)/(a - c) + sqrt(a*b + c*d - a*d - b*c + 4*a*c*e**2)/(a - c)] # check for simplification f = Poly(y*x**2 - 2*x - 2*y, x) assert roots_quadratic(f) == \ [-sqrt(2*y**2 + 1)/y + 1/y, sqrt(2*y**2 + 1)/y + 1/y] f = Poly(x**2 + (-y**2 - 2)*x + y**2 + 1, x) assert roots_quadratic(f) == \ [1,y**2 + 1] f = Poly(sqrt(2)*x**2 - 1, x) r = roots_quadratic(f) assert r == _nsort(r) # issue 8255 f = Poly(-24*x**2 - 180*x + 264) assert [w.n(2) for w in f.all_roots(radicals=True)] == \ [w.n(2) for w in f.all_roots(radicals=False)] for _a, _b, _c in product((-2, 2), (-2, 2), (0, -1)): f = Poly(_a*x**2 + _b*x + _c) roots = roots_quadratic(f) assert roots == _nsort(roots) def test_issue_7724(): eq = Poly(x**4*I + x**2 + I, x) assert roots(eq) == { sqrt(I/2 + sqrt(5)*I/2): 1, sqrt(-sqrt(5)*I/2 + I/2): 1, -sqrt(I/2 + sqrt(5)*I/2): 1, -sqrt(-sqrt(5)*I/2 + I/2): 1} def test_issue_8438(): p = Poly([1, y, -2, -3], x).as_expr() roots = roots_cubic(Poly(p, x), x) z = Rational(-3, 2) - I*Rational(7, 2) # this will fail in code given in commit msg post = [r.subs(y, z) for r in roots] assert set(post) == \ set(roots_cubic(Poly(p.subs(y, z), x))) # /!\ if p is not made an expression, this is *very* slow assert all(p.subs({y: z, x: i}).n(2, chop=True) == 0 for i in post) def test_issue_8285(): roots = (Poly(4*x**8 - 1, x)*Poly(x**2 + 1)).all_roots() assert _check(roots) f = Poly(x**4 + 5*x**2 + 6, x) ro = [rootof(f, i) for i in range(4)] roots = Poly(x**4 + 5*x**2 + 6, x).all_roots() assert roots == ro assert _check(roots) # more than 2 complex roots from which to identify the # imaginary ones roots = Poly(2*x**8 - 1).all_roots() assert _check(roots) assert len(Poly(2*x**10 - 1).all_roots()) == 10 # doesn't fail def test_issue_8289(): roots = (Poly(x**2 + 2)*Poly(x**4 + 2)).all_roots() assert _check(roots) roots = Poly(x**6 + 3*x**3 + 2, x).all_roots() assert _check(roots) roots = Poly(x**6 - x + 1).all_roots() assert _check(roots) # all imaginary roots with multiplicity of 2 roots = Poly(x**4 + 4*x**2 + 4, x).all_roots() assert _check(roots) def test_issue_14291(): assert Poly(((x - 1)**2 + 1)*((x - 1)**2 + 2)*(x - 1) ).all_roots() == [1, 1 - I, 1 + I, 1 - sqrt(2)*I, 1 + sqrt(2)*I] p = x**4 + 10*x**2 + 1 ans = [rootof(p, i) for i in range(4)] assert Poly(p).all_roots() == ans _check(ans) def test_issue_13340(): eq = Poly(y**3 + exp(x)*y + x, y, domain='EX') roots_d = roots(eq) assert len(roots_d) == 3 def test_issue_14522(): eq = Poly(x**4 + x**3*(16 + 32*I) + x**2*(-285 + 386*I) + x*(-2824 - 448*I) - 2058 - 6053*I, x) roots_eq = roots(eq) assert all(eq(r) == 0 for r in roots_eq) def test_issue_15076(): sol = roots_quartic(Poly(t**4 - 6*t**2 + t/x - 3, t)) assert sol[0].has(x) def test_issue_16589(): eq = Poly(x**4 - 8*sqrt(2)*x**3 + 4*x**3 - 64*sqrt(2)*x**2 + 1024*x, x) roots_eq = roots(eq) assert 0 in roots_eq def test_roots_cubic(): assert roots_cubic(Poly(2*x**3, x)) == [0, 0, 0] assert roots_cubic(Poly(x**3 - 3*x**2 + 3*x - 1, x)) == [1, 1, 1] # valid for arbitrary y (issue 21263) r = root(y, 3) assert roots_cubic(Poly(x**3 - y, x)) == [r, r*(-S.Half + sqrt(3)*I/2), r*(-S.Half - sqrt(3)*I/2)] # simpler form when y is negative assert roots_cubic(Poly(x**3 - -1, x)) == \ [-1, S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2] assert roots_cubic(Poly(2*x**3 - 3*x**2 - 3*x - 1, x))[0] == \ S.Half + 3**Rational(1, 3)/2 + 3**Rational(2, 3)/2 eq = -x**3 + 2*x**2 + 3*x - 2 assert roots(eq, trig=True, multiple=True) == \ roots_cubic(Poly(eq, x), trig=True) == [ Rational(2, 3) + 2*sqrt(13)*cos(acos(8*sqrt(13)/169)/3)/3, -2*sqrt(13)*sin(-acos(8*sqrt(13)/169)/3 + pi/6)/3 + Rational(2, 3), -2*sqrt(13)*cos(-acos(8*sqrt(13)/169)/3 + pi/3)/3 + Rational(2, 3), ] def test_roots_quartic(): assert roots_quartic(Poly(x**4, x)) == [0, 0, 0, 0] assert roots_quartic(Poly(x**4 + x**3, x)) in [ [-1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1] ] assert roots_quartic(Poly(x**4 - x**3, x)) in [ [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1] ] lhs = roots_quartic(Poly(x**4 + x, x)) rhs = [S.Half + I*sqrt(3)/2, S.Half - I*sqrt(3)/2, S.Zero, -S.One] assert sorted(lhs, key=hash) == sorted(rhs, key=hash) # test of all branches of roots quartic for i, (a, b, c, d) in enumerate([(1, 2, 3, 0), (3, -7, -9, 9), (1, 2, 3, 4), (1, 2, 3, 4), (-7, -3, 3, -6), (-3, 5, -6, -4), (6, -5, -10, -3)]): if i == 2: c = -a*(a**2/S(8) - b/S(2)) elif i == 3: d = a*(a*(a**2*Rational(3, 256) - b/S(16)) + c/S(4)) eq = x**4 + a*x**3 + b*x**2 + c*x + d ans = roots_quartic(Poly(eq, x)) assert all(eq.subs(x, ai).n(chop=True) == 0 for ai in ans) # not all symbolic quartics are unresolvable eq = Poly(q*x + q/4 + x**4 + x**3 + 2*x**2 - Rational(1, 3), x) sol = roots_quartic(eq) assert all(verify_numerically(eq.subs(x, i), 0) for i in sol) z = symbols('z', negative=True) eq = x**4 + 2*x**3 + 3*x**2 + x*(z + 11) + 5 zans = roots_quartic(Poly(eq, x)) assert all([verify_numerically(eq.subs(((x, i), (z, -1))), 0) for i in zans]) # but some are (see also issue 4989) # it's ok if the solution is not Piecewise, but the tests below should pass eq = Poly(y*x**4 + x**3 - x + z, x) ans = roots_quartic(eq) assert all(type(i) == Piecewise for i in ans) reps = ( dict(y=Rational(-1, 3), z=Rational(-1, 4)), # 4 real dict(y=Rational(-1, 3), z=Rational(-1, 2)), # 2 real dict(y=Rational(-1, 3), z=-2)) # 0 real for rep in reps: sol = roots_quartic(Poly(eq.subs(rep), x)) assert all([verify_numerically(w.subs(rep) - s, 0) for w, s in zip(ans, sol)]) def test_issue_21287(): assert not any(isinstance(i, Piecewise) for i in roots_quartic( Poly(x**4 - x**2*(3 + 5*I) + 2*x*(-1 + I) - 1 + 3*I, x))) def test_roots_cyclotomic(): assert roots_cyclotomic(cyclotomic_poly(1, x, polys=True)) == [1] assert roots_cyclotomic(cyclotomic_poly(2, x, polys=True)) == [-1] assert roots_cyclotomic(cyclotomic_poly( 3, x, polys=True)) == [Rational(-1, 2) - I*sqrt(3)/2, Rational(-1, 2) + I*sqrt(3)/2] assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True)) == [-I, I] assert roots_cyclotomic(cyclotomic_poly( 6, x, polys=True)) == [S.Half - I*sqrt(3)/2, S.Half + I*sqrt(3)/2] assert roots_cyclotomic(cyclotomic_poly(7, x, polys=True)) == [ -cos(pi/7) - I*sin(pi/7), -cos(pi/7) + I*sin(pi/7), -cos(pi*Rational(3, 7)) - I*sin(pi*Rational(3, 7)), -cos(pi*Rational(3, 7)) + I*sin(pi*Rational(3, 7)), cos(pi*Rational(2, 7)) - I*sin(pi*Rational(2, 7)), cos(pi*Rational(2, 7)) + I*sin(pi*Rational(2, 7)), ] assert roots_cyclotomic(cyclotomic_poly(8, x, polys=True)) == [ -sqrt(2)/2 - I*sqrt(2)/2, -sqrt(2)/2 + I*sqrt(2)/2, sqrt(2)/2 - I*sqrt(2)/2, sqrt(2)/2 + I*sqrt(2)/2, ] assert roots_cyclotomic(cyclotomic_poly(12, x, polys=True)) == [ -sqrt(3)/2 - I/2, -sqrt(3)/2 + I/2, sqrt(3)/2 - I/2, sqrt(3)/2 + I/2, ] assert roots_cyclotomic( cyclotomic_poly(1, x, polys=True), factor=True) == [1] assert roots_cyclotomic( cyclotomic_poly(2, x, polys=True), factor=True) == [-1] assert roots_cyclotomic(cyclotomic_poly(3, x, polys=True), factor=True) == \ [-root(-1, 3), -1 + root(-1, 3)] assert roots_cyclotomic(cyclotomic_poly(4, x, polys=True), factor=True) == \ [-I, I] assert roots_cyclotomic(cyclotomic_poly(5, x, polys=True), factor=True) == \ [-root(-1, 5), -root(-1, 5)**3, root(-1, 5)**2, -1 - root(-1, 5)**2 + root(-1, 5) + root(-1, 5)**3] assert roots_cyclotomic(cyclotomic_poly(6, x, polys=True), factor=True) == \ [1 - root(-1, 3), root(-1, 3)] def test_roots_binomial(): assert roots_binomial(Poly(5*x, x)) == [0] assert roots_binomial(Poly(5*x**4, x)) == [0, 0, 0, 0] assert roots_binomial(Poly(5*x + 2, x)) == [Rational(-2, 5)] A = 10**Rational(3, 4)/10 assert roots_binomial(Poly(5*x**4 + 2, x)) == \ [-A - A*I, -A + A*I, A - A*I, A + A*I] _check(roots_binomial(Poly(x**8 - 2))) a1 = Symbol('a1', nonnegative=True) b1 = Symbol('b1', nonnegative=True) r0 = roots_quadratic(Poly(a1*x**2 + b1, x)) r1 = roots_binomial(Poly(a1*x**2 + b1, x)) assert powsimp(r0[0]) == powsimp(r1[0]) assert powsimp(r0[1]) == powsimp(r1[1]) for a, b, s, n in product((1, 2), (1, 2), (-1, 1), (2, 3, 4, 5)): if a == b and a != 1: # a == b == 1 is sufficient continue p = Poly(a*x**n + s*b) ans = roots_binomial(p) assert ans == _nsort(ans) # issue 8813 assert roots(Poly(2*x**3 - 16*y**3, x)) == { 2*y*(Rational(-1, 2) - sqrt(3)*I/2): 1, 2*y: 1, 2*y*(Rational(-1, 2) + sqrt(3)*I/2): 1} def test_roots_preprocessing(): f = a*y*x**2 + y - b coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1 assert poly == Poly(a*y*x**2 + y - b, x) f = c**3*x**3 + c**2*x**2 + c*x + a coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1/c assert poly == Poly(x**3 + x**2 + x + a, x) f = c**3*x**3 + c**2*x**2 + a coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1/c assert poly == Poly(x**3 + x**2 + a, x) f = c**3*x**3 + c*x + a coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1/c assert poly == Poly(x**3 + x + a, x) f = c**3*x**3 + a coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 1/c assert poly == Poly(x**3 + a, x) E, F, J, L = symbols("E,F,J,L") f = -21601054687500000000*E**8*J**8/L**16 + \ 508232812500000000*F*x*E**7*J**7/L**14 - \ 4269543750000000*E**6*F**2*J**6*x**2/L**12 + \ 16194716250000*E**5*F**3*J**5*x**3/L**10 - \ 27633173750*E**4*F**4*J**4*x**4/L**8 + \ 14840215*E**3*F**5*J**3*x**5/L**6 + \ 54794*E**2*F**6*J**2*x**6/(5*L**4) - \ 1153*E*J*F**7*x**7/(80*L**2) + \ 633*F**8*x**8/160000 coeff, poly = preprocess_roots(Poly(f, x)) assert coeff == 20*E*J/(F*L**2) assert poly == 633*x**8 - 115300*x**7 + 4383520*x**6 + 296804300*x**5 - 27633173750*x**4 + \ 809735812500*x**3 - 10673859375000*x**2 + 63529101562500*x - 135006591796875 f = Poly(-y**2 + x**2*exp(x), y, domain=ZZ[x, exp(x)]) g = Poly(-y**2 + exp(x), y, domain=ZZ[exp(x)]) assert preprocess_roots(f) == (x, g) def test_roots0(): assert roots(1, x) == {} assert roots(x, x) == {S.Zero: 1} assert roots(x**9, x) == {S.Zero: 9} assert roots(((x - 2)*(x + 3)*(x - 4)).expand(), x) == {-S(3): 1, S(2): 1, S(4): 1} assert roots(2*x + 1, x) == {Rational(-1, 2): 1} assert roots((2*x + 1)**2, x) == {Rational(-1, 2): 2} assert roots((2*x + 1)**5, x) == {Rational(-1, 2): 5} assert roots((2*x + 1)**10, x) == {Rational(-1, 2): 10} assert roots(x**4 - 1, x) == {I: 1, S.One: 1, -S.One: 1, -I: 1} assert roots((x**4 - 1)**2, x) == {I: 2, S.One: 2, -S.One: 2, -I: 2} assert roots(((2*x - 3)**2).expand(), x) == {Rational( 3, 2): 2} assert roots(((2*x + 3)**2).expand(), x) == {Rational(-3, 2): 2} assert roots(((2*x - 3)**3).expand(), x) == {Rational( 3, 2): 3} assert roots(((2*x + 3)**3).expand(), x) == {Rational(-3, 2): 3} assert roots(((2*x - 3)**5).expand(), x) == {Rational( 3, 2): 5} assert roots(((2*x + 3)**5).expand(), x) == {Rational(-3, 2): 5} assert roots(((a*x - b)**5).expand(), x) == { b/a: 5} assert roots(((a*x + b)**5).expand(), x) == {-b/a: 5} assert roots(x**2 + (-a - 1)*x + a, x) == {a: 1, S.One: 1} assert roots(x**4 - 2*x**2 + 1, x) == {S.One: 2, S.NegativeOne: 2} assert roots(x**6 - 4*x**4 + 4*x**3 - x**2, x) == \ {S.One: 2, -1 - sqrt(2): 1, S.Zero: 2, -1 + sqrt(2): 1} assert roots(x**8 - 1, x) == { sqrt(2)/2 + I*sqrt(2)/2: 1, sqrt(2)/2 - I*sqrt(2)/2: 1, -sqrt(2)/2 + I*sqrt(2)/2: 1, -sqrt(2)/2 - I*sqrt(2)/2: 1, S.One: 1, -S.One: 1, I: 1, -I: 1 } f = -2016*x**2 - 5616*x**3 - 2056*x**4 + 3324*x**5 + 2176*x**6 - \ 224*x**7 - 384*x**8 - 64*x**9 assert roots(f) == {S.Zero: 2, -S(2): 2, S(2): 1, Rational(-7, 2): 1, Rational(-3, 2): 1, Rational(-1, 2): 1, Rational(3, 2): 1} assert roots((a + b + c)*x - (a + b + c + d), x) == {(a + b + c + d)/(a + b + c): 1} assert roots(x**3 + x**2 - x + 1, x, cubics=False) == {} assert roots(((x - 2)*( x + 3)*(x - 4)).expand(), x, cubics=False) == {-S(3): 1, S(2): 1, S(4): 1} assert roots(((x - 2)*(x + 3)*(x - 4)*(x - 5)).expand(), x, cubics=False) == \ {-S(3): 1, S(2): 1, S(4): 1, S(5): 1} assert roots(x**3 + 2*x**2 + 4*x + 8, x) == {-S(2): 1, -2*I: 1, 2*I: 1} assert roots(x**3 + 2*x**2 + 4*x + 8, x, cubics=True) == \ {-2*I: 1, 2*I: 1, -S(2): 1} assert roots((x**2 - x)*(x**3 + 2*x**2 + 4*x + 8), x ) == \ {S.One: 1, S.Zero: 1, -S(2): 1, -2*I: 1, 2*I: 1} r1_2, r1_3 = S.Half, Rational(1, 3) x0 = (3*sqrt(33) + 19)**r1_3 x1 = 4/x0/3 x2 = x0/3 x3 = sqrt(3)*I/2 x4 = x3 - r1_2 x5 = -x3 - r1_2 assert roots(x**3 + x**2 - x + 1, x, cubics=True) == { -x1 - x2 - r1_3: 1, -x1/x4 - x2*x4 - r1_3: 1, -x1/x5 - x2*x5 - r1_3: 1, } f = (x**2 + 2*x + 3).subs(x, 2*x**2 + 3*x).subs(x, 5*x - 4) r13_20, r1_20 = [ Rational(*r) for r in ((13, 20), (1, 20)) ] s2 = sqrt(2) assert roots(f, x) == { r13_20 + r1_20*sqrt(1 - 8*I*s2): 1, r13_20 - r1_20*sqrt(1 - 8*I*s2): 1, r13_20 + r1_20*sqrt(1 + 8*I*s2): 1, r13_20 - r1_20*sqrt(1 + 8*I*s2): 1, } f = x**4 + x**3 + x**2 + x + 1 r1_4, r1_8, r5_8 = [ Rational(*r) for r in ((1, 4), (1, 8), (5, 8)) ] assert roots(f, x) == { -r1_4 + r1_4*5**r1_2 + I*(r5_8 + r1_8*5**r1_2)**r1_2: 1, -r1_4 + r1_4*5**r1_2 - I*(r5_8 + r1_8*5**r1_2)**r1_2: 1, -r1_4 - r1_4*5**r1_2 + I*(r5_8 - r1_8*5**r1_2)**r1_2: 1, -r1_4 - r1_4*5**r1_2 - I*(r5_8 - r1_8*5**r1_2)**r1_2: 1, } f = z**3 + (-2 - y)*z**2 + (1 + 2*y - 2*x**2)*z - y + 2*x**2 assert roots(f, z) == { S.One: 1, S.Half + S.Half*y + S.Half*sqrt(1 - 2*y + y**2 + 8*x**2): 1, S.Half + S.Half*y - S.Half*sqrt(1 - 2*y + y**2 + 8*x**2): 1, } assert roots(a*b*c*x**3 + 2*x**2 + 4*x + 8, x, cubics=False) == {} assert roots(a*b*c*x**3 + 2*x**2 + 4*x + 8, x, cubics=True) != {} assert roots(x**4 - 1, x, filter='Z') == {S.One: 1, -S.One: 1} assert roots(x**4 - 1, x, filter='I') == {I: 1, -I: 1} assert roots((x - 1)*(x + 1), x) == {S.One: 1, -S.One: 1} assert roots( (x - 1)*(x + 1), x, predicate=lambda r: r.is_positive) == {S.One: 1} assert roots(x**4 - 1, x, filter='Z', multiple=True) == [-S.One, S.One] assert roots(x**4 - 1, x, filter='I', multiple=True) == [I, -I] ar, br = symbols('a, b', real=True) p = x**2*(ar-br)**2 + 2*x*(br-ar) + 1 assert roots(p, x, filter='R') == {1/(ar - br): 2} assert roots(x**3, x, multiple=True) == [S.Zero, S.Zero, S.Zero] assert roots(1234, x, multiple=True) == [] f = x**6 - x**5 + x**4 - x**3 + x**2 - x + 1 assert roots(f) == { -I*sin(pi/7) + cos(pi/7): 1, -I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 1, -I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 1, I*sin(pi/7) + cos(pi/7): 1, I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 1, I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 1, } g = ((x**2 + 1)*f**2).expand() assert roots(g) == { -I*sin(pi/7) + cos(pi/7): 2, -I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 2, -I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 2, I*sin(pi/7) + cos(pi/7): 2, I*sin(pi*Rational(2, 7)) - cos(pi*Rational(2, 7)): 2, I*sin(pi*Rational(3, 7)) + cos(pi*Rational(3, 7)): 2, -I: 1, I: 1, } r = roots(x**3 + 40*x + 64) real_root = [rx for rx in r if rx.is_real][0] cr = 108 + 6*sqrt(1074) assert real_root == -2*root(cr, 3)/3 + 20/root(cr, 3) eq = Poly((7 + 5*sqrt(2))*x**3 + (-6 - 4*sqrt(2))*x**2 + (-sqrt(2) - 1)*x + 2, x, domain='EX') assert roots(eq) == {-1 + sqrt(2): 1, -2 + 2*sqrt(2): 1, -sqrt(2) + 1: 1} eq = Poly(41*x**5 + 29*sqrt(2)*x**5 - 153*x**4 - 108*sqrt(2)*x**4 + 175*x**3 + 125*sqrt(2)*x**3 - 45*x**2 - 30*sqrt(2)*x**2 - 26*sqrt(2)*x - 26*x + 24, x, domain='EX') assert roots(eq) == {-sqrt(2) + 1: 1, -2 + 2*sqrt(2): 1, -1 + sqrt(2): 1, -4 + 4*sqrt(2): 1, -3 + 3*sqrt(2): 1} eq = Poly(x**3 - 2*x**2 + 6*sqrt(2)*x**2 - 8*sqrt(2)*x + 23*x - 14 + 14*sqrt(2), x, domain='EX') assert roots(eq) == {-2*sqrt(2) + 2: 1, -2*sqrt(2) + 1: 1, -2*sqrt(2) - 1: 1} assert roots(Poly((x + sqrt(2))**3 - 7, x, domain='EX')) == \ {-sqrt(2) + root(7, 3)*(-S.Half - sqrt(3)*I/2): 1, -sqrt(2) + root(7, 3)*(-S.Half + sqrt(3)*I/2): 1, -sqrt(2) + root(7, 3): 1} def test_roots_slow(): """Just test that calculating these roots does not hang. """ a, b, c, d, x = symbols("a,b,c,d,x") f1 = x**2*c + (a/b) + x*c*d - a f2 = x**2*(a + b*(c - d)*a) + x*a*b*c/(b*d - d) + (a*d - c/d) assert list(roots(f1, x).values()) == [1, 1] assert list(roots(f2, x).values()) == [1, 1] (zz, yy, xx, zy, zx, yx, k) = symbols("zz,yy,xx,zy,zx,yx,k") e1 = (zz - k)*(yy - k)*(xx - k) + zy*yx*zx + zx - zy - yx e2 = (zz - k)*yx*yx + zx*(yy - k)*zx + zy*zy*(xx - k) assert list(roots(e1 - e2, k).values()) == [1, 1, 1] f = x**3 + 2*x**2 + 8 R = list(roots(f).keys()) assert not any(i for i in [f.subs(x, ri).n(chop=True) for ri in R]) def test_roots_inexact(): R1 = roots(x**2 + x + 1, x, multiple=True) R2 = roots(x**2 + x + 1.0, x, multiple=True) for r1, r2 in zip(R1, R2): assert abs(r1 - r2) < 1e-12 f = x**4 + 3.0*sqrt(2.0)*x**3 - (78.0 + 24.0*sqrt(3.0))*x**2 \ + 144.0*(2*sqrt(3.0) + 9.0) R1 = roots(f, multiple=True) R2 = (-12.7530479110482, -3.85012393732929, 4.89897948556636, 7.46155167569183) for r1, r2 in zip(R1, R2): assert abs(r1 - r2) < 1e-10 def test_roots_preprocessed(): E, F, J, L = symbols("E,F,J,L") f = -21601054687500000000*E**8*J**8/L**16 + \ 508232812500000000*F*x*E**7*J**7/L**14 - \ 4269543750000000*E**6*F**2*J**6*x**2/L**12 + \ 16194716250000*E**5*F**3*J**5*x**3/L**10 - \ 27633173750*E**4*F**4*J**4*x**4/L**8 + \ 14840215*E**3*F**5*J**3*x**5/L**6 + \ 54794*E**2*F**6*J**2*x**6/(5*L**4) - \ 1153*E*J*F**7*x**7/(80*L**2) + \ 633*F**8*x**8/160000 assert roots(f, x) == {} R1 = roots(f.evalf(), x, multiple=True) R2 = [-1304.88375606366, 97.1168816800648, 186.946430171876, 245.526792947065, 503.441004174773, 791.549343830097, 1273.16678129348, 1850.10650616851] w = Wild('w') p = w*E*J/(F*L**2) assert len(R1) == len(R2) for r1, r2 in zip(R1, R2): match = r1.match(p) assert match is not None and abs(match[w] - r2) < 1e-10 def test_roots_mixed(): f = -1936 - 5056*x - 7592*x**2 + 2704*x**3 - 49*x**4 _re, _im = intervals(f, all=True) _nroots = nroots(f) _sroots = roots(f, multiple=True) _re = [ Interval(a, b) for (a, b), _ in _re ] _im = [ Interval(re(a), re(b))*Interval(im(a), im(b)) for (a, b), _ in _im ] _intervals = _re + _im _sroots = [ r.evalf() for r in _sroots ] _nroots = sorted(_nroots, key=lambda x: x.sort_key()) _sroots = sorted(_sroots, key=lambda x: x.sort_key()) for _roots in (_nroots, _sroots): for i, r in zip(_intervals, _roots): if r.is_real: assert r in i else: assert (re(r), im(r)) in i def test_root_factors(): assert root_factors(Poly(1, x)) == [Poly(1, x)] assert root_factors(Poly(x, x)) == [Poly(x, x)] assert root_factors(x**2 - 1, x) == [x + 1, x - 1] assert root_factors(x**2 - y, x) == [x - sqrt(y), x + sqrt(y)] assert root_factors((x**4 - 1)**2) == \ [x + 1, x + 1, x - 1, x - 1, x - I, x - I, x + I, x + I] assert root_factors(Poly(x**4 - 1, x), filter='Z') == \ [Poly(x + 1, x), Poly(x - 1, x), Poly(x**2 + 1, x)] assert root_factors(8*x**2 + 12*x**4 + 6*x**6 + x**8, x, filter='Q') == \ [x, x, x**6 + 6*x**4 + 12*x**2 + 8] @slow def test_nroots1(): n = 64 p = legendre_poly(n, x, polys=True) raises(mpmath.mp.NoConvergence, lambda: p.nroots(n=3, maxsteps=5)) roots = p.nroots(n=3) # The order of roots matters. They are ordered from smallest to the # largest. assert [str(r) for r in roots] == \ ['-0.999', '-0.996', '-0.991', '-0.983', '-0.973', '-0.961', '-0.946', '-0.930', '-0.911', '-0.889', '-0.866', '-0.841', '-0.813', '-0.784', '-0.753', '-0.720', '-0.685', '-0.649', '-0.611', '-0.572', '-0.531', '-0.489', '-0.446', '-0.402', '-0.357', '-0.311', '-0.265', '-0.217', '-0.170', '-0.121', '-0.0730', '-0.0243', '0.0243', '0.0730', '0.121', '0.170', '0.217', '0.265', '0.311', '0.357', '0.402', '0.446', '0.489', '0.531', '0.572', '0.611', '0.649', '0.685', '0.720', '0.753', '0.784', '0.813', '0.841', '0.866', '0.889', '0.911', '0.930', '0.946', '0.961', '0.973', '0.983', '0.991', '0.996', '0.999'] def test_nroots2(): p = Poly(x**5 + 3*x + 1, x) roots = p.nroots(n=3) # The order of roots matters. The roots are ordered by their real # components (if they agree, then by their imaginary components), # with real roots appearing first. assert [str(r) for r in roots] == \ ['-0.332', '-0.839 - 0.944*I', '-0.839 + 0.944*I', '1.01 - 0.937*I', '1.01 + 0.937*I'] roots = p.nroots(n=5) assert [str(r) for r in roots] == \ ['-0.33199', '-0.83907 - 0.94385*I', '-0.83907 + 0.94385*I', '1.0051 - 0.93726*I', '1.0051 + 0.93726*I'] def test_roots_composite(): assert len(roots(Poly(y**3 + y**2*sqrt(x) + y + x, y, composite=True))) == 3 def test_issue_19113(): eq = cos(x)**3 - cos(x) + 1 raises(PolynomialError, lambda: roots(eq)) def test_issue_17454(): assert roots([1, -3*(-4 - 4*I)**2/8 + 12*I, 0], multiple=True) == [0, 0] def test_issue_20913(): assert Poly(x + 9671406556917067856609794, x).real_roots() == [-9671406556917067856609794] assert Poly(x**3 + 4, x).real_roots() == [-2**(S(2)/3)]
47c8ff36e6c8c159be8a3e1d98b669e2fc6306c4dbb70fdfb1965d2765fb8a28
"""Computational algebraic field theory. """ __all__ = [ 'AlgebraicNumber', 'minpoly', 'minimal_polynomial', 'primitive_element', 'field_isomorphism', 'to_number_field', 'isolate', ] from sympy.core.numbers import AlgebraicNumber from .minpoly import minpoly, minimal_polynomial, primitive_element from .isomorphism import field_isomorphism from .numbers import to_number_field, isolate
091b85e3b56b2394ad5ae8364465c265d2eefce8b5611e86ac4ca0526e567d6d
"""Algebraic numbers -- forms of expression, and isolation.""" from sympy.core.numbers import AlgebraicNumber from sympy.core.sympify import sympify from sympy.polys.numberfields.isomorphism import field_isomorphism from sympy.polys.numberfields.minpoly import minpoly, primitive_element from sympy.polys.polyerrors import IsomorphismFailed from sympy.printing.lambdarepr import IntervalPrinter from sympy.utilities import ( lambdify, public ) from mpmath import mp @public def to_number_field(extension, theta=None, *, gen=None): """Express `extension` in the field generated by `theta`. """ if hasattr(extension, '__iter__'): extension = list(extension) else: extension = [extension] if len(extension) == 1 and isinstance(extension[0], tuple): return AlgebraicNumber(extension[0]) minpoly, coeffs = primitive_element(extension, gen, polys=True) root = sum([ coeff*ext for coeff, ext in zip(coeffs, extension) ]) if theta is None: return AlgebraicNumber((minpoly, root)) else: theta = sympify(theta) if not theta.is_AlgebraicNumber: theta = AlgebraicNumber(theta, gen=gen) coeffs = field_isomorphism(root, theta) if coeffs is not None: return AlgebraicNumber(theta, coeffs) else: raise IsomorphismFailed( "%s is not in a subfield of %s" % (root, theta.root)) @public def isolate(alg, eps=None, fast=False): """Give a rational isolating interval for an algebraic number. """ alg = sympify(alg) if alg.is_Rational: return (alg, alg) elif not alg.is_real: raise NotImplementedError( "complex algebraic numbers are not supported") func = lambdify((), alg, modules="mpmath", printer=IntervalPrinter()) poly = minpoly(alg, polys=True) intervals = poly.intervals(sqf=True) dps, done = mp.dps, False try: while not done: alg = func() for a, b in intervals: if a <= alg.a and alg.b <= b: done = True break else: mp.dps *= 2 finally: mp.dps = dps if eps is not None: a, b = poly.refine_root(a, b, eps=eps, fast=fast) return (a, b)
cec5d59081b2c1f1a9f34b3e22817be98d1e9ecc9eff34383e7a0506c1dd4b33
"""Isomorphisms of number fields.""" from sympy.core.add import Add from sympy.core.numbers import AlgebraicNumber from sympy.core.singleton import S from sympy.core.sympify import sympify from sympy.ntheory import sieve from sympy.polys.polytools import Poly, factor_list from sympy.utilities import public from mpmath import pslq, mp def is_isomorphism_possible(a, b): """Returns `True` if there is a chance for isomorphism. """ n = a.minpoly.degree() m = b.minpoly.degree() if m % n != 0: return False if n == m: return True da = a.minpoly.discriminant() db = b.minpoly.discriminant() i, k, half = 1, m//n, db//2 while True: p = sieve[i] P = p**k if P > half: break if ((da % p) % 2) and not (db % P): return False i += 1 return True def field_isomorphism_pslq(a, b): """Construct field isomorphism using PSLQ algorithm. """ if not a.root.is_real or not b.root.is_real: raise NotImplementedError("PSLQ doesn't support complex coefficients") f = a.minpoly g = b.minpoly.replace(f.gen) n, m, prev = 100, b.minpoly.degree(), None for i in range(1, 5): A = a.root.evalf(n) B = b.root.evalf(n) basis = [1, B] + [ B**i for i in range(2, m) ] + [A] dps, mp.dps = mp.dps, n coeffs = pslq(basis, maxcoeff=int(1e10), maxsteps=1000) mp.dps = dps if coeffs is None: break if coeffs != prev: prev = coeffs else: break coeffs = [S(c)/coeffs[-1] for c in coeffs[:-1]] while not coeffs[-1]: coeffs.pop() coeffs = list(reversed(coeffs)) h = Poly(coeffs, f.gen, domain='QQ') if f.compose(h).rem(g).is_zero: d, approx = len(coeffs) - 1, 0 for i, coeff in enumerate(coeffs): approx += coeff*B**(d - i) if A*approx < 0: return [ -c for c in coeffs ] else: return coeffs elif f.compose(-h).rem(g).is_zero: return [ -c for c in coeffs ] else: n *= 2 return None def field_isomorphism_factor(a, b): """Construct field isomorphism via factorization. """ _, factors = factor_list(a.minpoly, extension=b) for f, _ in factors: if f.degree() == 1: coeffs = f.rep.TC().to_sympy_list() d, terms = len(coeffs) - 1, [] for i, coeff in enumerate(coeffs): terms.append(coeff*b.root**(d - i)) root = Add(*terms) if (a.root - root).evalf(chop=True) == 0: return coeffs if (a.root + root).evalf(chop=True) == 0: return [-c for c in coeffs] return None @public def field_isomorphism(a, b, *, fast=True): """Construct an isomorphism between two number fields. """ a, b = sympify(a), sympify(b) if not a.is_AlgebraicNumber: a = AlgebraicNumber(a) if not b.is_AlgebraicNumber: b = AlgebraicNumber(b) if a == b: return a.coeffs() n = a.minpoly.degree() m = b.minpoly.degree() if n == 1: return [a.root] if m % n != 0: return None if fast: try: result = field_isomorphism_pslq(a, b) if result is not None: return result except NotImplementedError: pass return field_isomorphism_factor(a, b)
6d54a6888c224c9abd5fc379448230a706b6ec7c08c8855ae4f8ba7313f8adc6
"""Minimal polynomials for algebraic numbers.""" from functools import reduce from sympy.core.add import Add from sympy.core.function import expand_mul, expand_multinomial from sympy.core.mul import Mul from sympy.core import (GoldenRatio, TribonacciConstant) from sympy.core.numbers import (I, Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import Dummy from sympy.core.sympify import sympify from sympy.functions import sqrt, cbrt from sympy.core.exprtools import Factors from sympy.core.function import _mexpand from sympy.core.traversal import preorder_traversal from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.trigonometric import cos, sin, tan from sympy.ntheory.factor_ import divisors from sympy.utilities.iterables import subsets from sympy.polys.densetools import dup_eval from sympy.polys.domains import ZZ, QQ, FractionField from sympy.polys.orthopolys import dup_chebyshevt from sympy.polys.polyerrors import ( NotAlgebraic, GeneratorsError, ) from sympy.polys.polytools import ( Poly, PurePoly, invert, factor_list, groebner, resultant, degree, poly_from_expr, parallel_poly_from_expr, lcm ) from sympy.polys.polyutils import dict_from_expr, expr_from_dict, illegal from sympy.polys.ring_series import rs_compose_add from sympy.polys.rings import ring from sympy.polys.rootoftools import CRootOf from sympy.polys.specialpolys import cyclotomic_poly from sympy.simplify.radsimp import _split_gcd from sympy.simplify.simplify import _is_sum_surds from sympy.utilities import ( numbered_symbols, public, sift ) def _choose_factor(factors, x, v, dom=QQ, prec=200, bound=5): """ Return a factor having root ``v`` It is assumed that one of the factors has root ``v``. """ if isinstance(factors[0], tuple): factors = [f[0] for f in factors] if len(factors) == 1: return factors[0] prec1 = 10 points = {} symbols = dom.symbols if hasattr(dom, 'symbols') else [] while prec1 <= prec: # when dealing with non-Rational numbers we usually evaluate # with `subs` argument but we only need a ballpark evaluation xv = {x:v if not v.is_number else v.n(prec1)} fe = [f.as_expr().xreplace(xv) for f in factors] # assign integers [0, n) to symbols (if any) for n in subsets(range(bound), k=len(symbols), repetition=True): for s, i in zip(symbols, n): points[s] = i # evaluate the expression at these points candidates = [(abs(f.subs(points).n(prec1)), i) for i,f in enumerate(fe)] # if we get invalid numbers (e.g. from division by zero) # we try again if any(i in illegal for i, _ in candidates): continue # find the smallest two -- if they differ significantly # then we assume we have found the factor that becomes # 0 when v is substituted into it can = sorted(candidates) (a, ix), (b, _) = can[:2] if b > a * 10**6: # XXX what to use? return factors[ix] prec1 *= 2 raise NotImplementedError("multiple candidates for the minimal polynomial of %s" % v) def _separate_sq(p): """ helper function for ``_minimal_polynomial_sq`` It selects a rational ``g`` such that the polynomial ``p`` consists of a sum of terms whose surds squared have gcd equal to ``g`` and a sum of terms with surds squared prime with ``g``; then it takes the field norm to eliminate ``sqrt(g)`` See simplify.simplify.split_surds and polytools.sqf_norm. Examples ======== >>> from sympy import sqrt >>> from sympy.abc import x >>> from sympy.polys.numberfields.minpoly import _separate_sq >>> p= -x + sqrt(2) + sqrt(3) + sqrt(7) >>> p = _separate_sq(p); p -x**2 + 2*sqrt(3)*x + 2*sqrt(7)*x - 2*sqrt(21) - 8 >>> p = _separate_sq(p); p -x**4 + 4*sqrt(7)*x**3 - 32*x**2 + 8*sqrt(7)*x + 20 >>> p = _separate_sq(p); p -x**8 + 48*x**6 - 536*x**4 + 1728*x**2 - 400 """ def is_sqrt(expr): return expr.is_Pow and expr.exp is S.Half # p = c1*sqrt(q1) + ... + cn*sqrt(qn) -> a = [(c1, q1), .., (cn, qn)] a = [] for y in p.args: if not y.is_Mul: if is_sqrt(y): a.append((S.One, y**2)) elif y.is_Atom: a.append((y, S.One)) elif y.is_Pow and y.exp.is_integer: a.append((y, S.One)) else: raise NotImplementedError continue T, F = sift(y.args, is_sqrt, binary=True) a.append((Mul(*F), Mul(*T)**2)) a.sort(key=lambda z: z[1]) if a[-1][1] is S.One: # there are no surds return p surds = [z for y, z in a] for i in range(len(surds)): if surds[i] != 1: break g, b1, b2 = _split_gcd(*surds[i:]) a1 = [] a2 = [] for y, z in a: if z in b1: a1.append(y*z**S.Half) else: a2.append(y*z**S.Half) p1 = Add(*a1) p2 = Add(*a2) p = _mexpand(p1**2) - _mexpand(p2**2) return p def _minimal_polynomial_sq(p, n, x): """ Returns the minimal polynomial for the ``nth-root`` of a sum of surds or ``None`` if it fails. Parameters ========== p : sum of surds n : positive integer x : variable of the returned polynomial Examples ======== >>> from sympy.polys.numberfields.minpoly import _minimal_polynomial_sq >>> from sympy import sqrt >>> from sympy.abc import x >>> q = 1 + sqrt(2) + sqrt(3) >>> _minimal_polynomial_sq(q, 3, x) x**12 - 4*x**9 - 4*x**6 + 16*x**3 - 8 """ p = sympify(p) n = sympify(n) if not n.is_Integer or not n > 0 or not _is_sum_surds(p): return None pn = p**Rational(1, n) # eliminate the square roots p -= x while 1: p1 = _separate_sq(p) if p1 is p: p = p1.subs({x:x**n}) break else: p = p1 # _separate_sq eliminates field extensions in a minimal way, so that # if n = 1 then `p = constant*(minimal_polynomial(p))` # if n > 1 it contains the minimal polynomial as a factor. if n == 1: p1 = Poly(p) if p.coeff(x**p1.degree(x)) < 0: p = -p p = p.primitive()[1] return p # by construction `p` has root `pn` # the minimal polynomial is the factor vanishing in x = pn factors = factor_list(p)[1] result = _choose_factor(factors, x, pn) return result def _minpoly_op_algebraic_element(op, ex1, ex2, x, dom, mp1=None, mp2=None): """ return the minimal polynomial for ``op(ex1, ex2)`` Parameters ========== op : operation ``Add`` or ``Mul`` ex1, ex2 : expressions for the algebraic elements x : indeterminate of the polynomials dom: ground domain mp1, mp2 : minimal polynomials for ``ex1`` and ``ex2`` or None Examples ======== >>> from sympy import sqrt, Add, Mul, QQ >>> from sympy.polys.numberfields.minpoly import _minpoly_op_algebraic_element >>> from sympy.abc import x, y >>> p1 = sqrt(sqrt(2) + 1) >>> p2 = sqrt(sqrt(2) - 1) >>> _minpoly_op_algebraic_element(Mul, p1, p2, x, QQ) x - 1 >>> q1 = sqrt(y) >>> q2 = 1 / y >>> _minpoly_op_algebraic_element(Add, q1, q2, x, QQ.frac_field(y)) x**2*y**2 - 2*x*y - y**3 + 1 References ========== .. [1] https://en.wikipedia.org/wiki/Resultant .. [2] I.M. Isaacs, Proc. Amer. Math. Soc. 25 (1970), 638 "Degrees of sums in a separable field extension". """ y = Dummy(str(x)) if mp1 is None: mp1 = _minpoly_compose(ex1, x, dom) if mp2 is None: mp2 = _minpoly_compose(ex2, y, dom) else: mp2 = mp2.subs({x: y}) if op is Add: # mp1a = mp1.subs({x: x - y}) if dom == QQ: R, X = ring('X', QQ) p1 = R(dict_from_expr(mp1)[0]) p2 = R(dict_from_expr(mp2)[0]) else: (p1, p2), _ = parallel_poly_from_expr((mp1, x - y), x, y) r = p1.compose(p2) mp1a = r.as_expr() elif op is Mul: mp1a = _muly(mp1, x, y) else: raise NotImplementedError('option not available') if op is Mul or dom != QQ: r = resultant(mp1a, mp2, gens=[y, x]) else: r = rs_compose_add(p1, p2) r = expr_from_dict(r.as_expr_dict(), x) deg1 = degree(mp1, x) deg2 = degree(mp2, y) if op is Mul and deg1 == 1 or deg2 == 1: # if deg1 = 1, then mp1 = x - a; mp1a = x - y - a; # r = mp2(x - a), so that `r` is irreducible return r r = Poly(r, x, domain=dom) _, factors = r.factor_list() res = _choose_factor(factors, x, op(ex1, ex2), dom) return res.as_expr() def _invertx(p, x): """ Returns ``expand_mul(x**degree(p, x)*p.subs(x, 1/x))`` """ p1 = poly_from_expr(p, x)[0] n = degree(p1) a = [c * x**(n - i) for (i,), c in p1.terms()] return Add(*a) def _muly(p, x, y): """ Returns ``_mexpand(y**deg*p.subs({x:x / y}))`` """ p1 = poly_from_expr(p, x)[0] n = degree(p1) a = [c * x**i * y**(n - i) for (i,), c in p1.terms()] return Add(*a) def _minpoly_pow(ex, pw, x, dom, mp=None): """ Returns ``minpoly(ex**pw, x)`` Parameters ========== ex : algebraic element pw : rational number x : indeterminate of the polynomial dom: ground domain mp : minimal polynomial of ``p`` Examples ======== >>> from sympy import sqrt, QQ, Rational >>> from sympy.polys.numberfields.minpoly import _minpoly_pow, minpoly >>> from sympy.abc import x, y >>> p = sqrt(1 + sqrt(2)) >>> _minpoly_pow(p, 2, x, QQ) x**2 - 2*x - 1 >>> minpoly(p**2, x) x**2 - 2*x - 1 >>> _minpoly_pow(y, Rational(1, 3), x, QQ.frac_field(y)) x**3 - y >>> minpoly(y**Rational(1, 3), x) x**3 - y """ pw = sympify(pw) if not mp: mp = _minpoly_compose(ex, x, dom) if not pw.is_rational: raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex) if pw < 0: if mp == x: raise ZeroDivisionError('%s is zero' % ex) mp = _invertx(mp, x) if pw == -1: return mp pw = -pw ex = 1/ex y = Dummy(str(x)) mp = mp.subs({x: y}) n, d = pw.as_numer_denom() res = Poly(resultant(mp, x**d - y**n, gens=[y]), x, domain=dom) _, factors = res.factor_list() res = _choose_factor(factors, x, ex**pw, dom) return res.as_expr() def _minpoly_add(x, dom, *a): """ returns ``minpoly(Add(*a), dom, x)`` """ mp = _minpoly_op_algebraic_element(Add, a[0], a[1], x, dom) p = a[0] + a[1] for px in a[2:]: mp = _minpoly_op_algebraic_element(Add, p, px, x, dom, mp1=mp) p = p + px return mp def _minpoly_mul(x, dom, *a): """ returns ``minpoly(Mul(*a), dom, x)`` """ mp = _minpoly_op_algebraic_element(Mul, a[0], a[1], x, dom) p = a[0] * a[1] for px in a[2:]: mp = _minpoly_op_algebraic_element(Mul, p, px, x, dom, mp1=mp) p = p * px return mp def _minpoly_sin(ex, x): """ Returns the minimal polynomial of ``sin(ex)`` see http://mathworld.wolfram.com/TrigonometryAngles.html """ c, a = ex.args[0].as_coeff_Mul() if a is pi: if c.is_rational: n = c.q q = sympify(n) if q.is_prime: # for a = pi*p/q with q odd prime, using chebyshevt # write sin(q*a) = mp(sin(a))*sin(a); # the roots of mp(x) are sin(pi*p/q) for p = 1,..., q - 1 a = dup_chebyshevt(n, ZZ) return Add(*[x**(n - i - 1)*a[i] for i in range(n)]) if c.p == 1: if q == 9: return 64*x**6 - 96*x**4 + 36*x**2 - 3 if n % 2 == 1: # for a = pi*p/q with q odd, use # sin(q*a) = 0 to see that the minimal polynomial must be # a factor of dup_chebyshevt(n, ZZ) a = dup_chebyshevt(n, ZZ) a = [x**(n - i)*a[i] for i in range(n + 1)] r = Add(*a) _, factors = factor_list(r) res = _choose_factor(factors, x, ex) return res expr = ((1 - cos(2*c*pi))/2)**S.Half res = _minpoly_compose(expr, x, QQ) return res raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex) def _minpoly_cos(ex, x): """ Returns the minimal polynomial of ``cos(ex)`` see http://mathworld.wolfram.com/TrigonometryAngles.html """ c, a = ex.args[0].as_coeff_Mul() if a is pi: if c.is_rational: if c.p == 1: if c.q == 7: return 8*x**3 - 4*x**2 - 4*x + 1 if c.q == 9: return 8*x**3 - 6*x + 1 elif c.p == 2: q = sympify(c.q) if q.is_prime: s = _minpoly_sin(ex, x) return _mexpand(s.subs({x:sqrt((1 - x)/2)})) # for a = pi*p/q, cos(q*a) =T_q(cos(a)) = (-1)**p n = int(c.q) a = dup_chebyshevt(n, ZZ) a = [x**(n - i)*a[i] for i in range(n + 1)] r = Add(*a) - (-1)**c.p _, factors = factor_list(r) res = _choose_factor(factors, x, ex) return res raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex) def _minpoly_tan(ex, x): """ Returns the minimal polynomial of ``tan(ex)`` see https://github.com/sympy/sympy/issues/21430 """ c, a = ex.args[0].as_coeff_Mul() if a is pi: if c.is_rational: c = c * 2 n = int(c.q) a = n if c.p % 2 == 0 else 1 terms = [] for k in range((c.p+1)%2, n+1, 2): terms.append(a*x**k) a = -(a*(n-k-1)*(n-k)) // ((k+1)*(k+2)) r = Add(*terms) _, factors = factor_list(r) res = _choose_factor(factors, x, ex) return res raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex) def _minpoly_exp(ex, x): """ Returns the minimal polynomial of ``exp(ex)`` """ c, a = ex.args[0].as_coeff_Mul() q = sympify(c.q) if a == I*pi: if c.is_rational: if c.p == 1 or c.p == -1: if q == 3: return x**2 - x + 1 if q == 4: return x**4 + 1 if q == 6: return x**4 - x**2 + 1 if q == 8: return x**8 + 1 if q == 9: return x**6 - x**3 + 1 if q == 10: return x**8 - x**6 + x**4 - x**2 + 1 if q.is_prime: s = 0 for i in range(q): s += (-x)**i return s # x**(2*q) = product(factors) factors = [cyclotomic_poly(i, x) for i in divisors(2*q)] mp = _choose_factor(factors, x, ex) return mp else: raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex) raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex) def _minpoly_rootof(ex, x): """ Returns the minimal polynomial of a ``CRootOf`` object. """ p = ex.expr p = p.subs({ex.poly.gens[0]:x}) _, factors = factor_list(p, x) result = _choose_factor(factors, x, ex) return result def _minpoly_compose(ex, x, dom): """ Computes the minimal polynomial of an algebraic element using operations on minimal polynomials Examples ======== >>> from sympy import minimal_polynomial, sqrt, Rational >>> from sympy.abc import x, y >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=True) x**2 - 2*x - 1 >>> minimal_polynomial(sqrt(y) + 1/y, x, compose=True) x**2*y**2 - 2*x*y - y**3 + 1 """ if ex.is_Rational: return ex.q*x - ex.p if ex is I: _, factors = factor_list(x**2 + 1, x, domain=dom) return x**2 + 1 if len(factors) == 1 else x - I if ex is GoldenRatio: _, factors = factor_list(x**2 - x - 1, x, domain=dom) if len(factors) == 1: return x**2 - x - 1 else: return _choose_factor(factors, x, (1 + sqrt(5))/2, dom=dom) if ex is TribonacciConstant: _, factors = factor_list(x**3 - x**2 - x - 1, x, domain=dom) if len(factors) == 1: return x**3 - x**2 - x - 1 else: fac = (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3 return _choose_factor(factors, x, fac, dom=dom) if hasattr(dom, 'symbols') and ex in dom.symbols: return x - ex if dom.is_QQ and _is_sum_surds(ex): # eliminate the square roots ex -= x while 1: ex1 = _separate_sq(ex) if ex1 is ex: return ex else: ex = ex1 if ex.is_Add: res = _minpoly_add(x, dom, *ex.args) elif ex.is_Mul: f = Factors(ex).factors r = sift(f.items(), lambda itx: itx[0].is_Rational and itx[1].is_Rational) if r[True] and dom == QQ: ex1 = Mul(*[bx**ex for bx, ex in r[False] + r[None]]) r1 = dict(r[True]) dens = [y.q for y in r1.values()] lcmdens = reduce(lcm, dens, 1) neg1 = S.NegativeOne expn1 = r1.pop(neg1, S.Zero) nums = [base**(y.p*lcmdens // y.q) for base, y in r1.items()] ex2 = Mul(*nums) mp1 = minimal_polynomial(ex1, x) # use the fact that in SymPy canonicalization products of integers # raised to rational powers are organized in relatively prime # bases, and that in ``base**(n/d)`` a perfect power is # simplified with the root # Powers of -1 have to be treated separately to preserve sign. mp2 = ex2.q*x**lcmdens - ex2.p*neg1**(expn1*lcmdens) ex2 = neg1**expn1 * ex2**Rational(1, lcmdens) res = _minpoly_op_algebraic_element(Mul, ex1, ex2, x, dom, mp1=mp1, mp2=mp2) else: res = _minpoly_mul(x, dom, *ex.args) elif ex.is_Pow: res = _minpoly_pow(ex.base, ex.exp, x, dom) elif ex.__class__ is sin: res = _minpoly_sin(ex, x) elif ex.__class__ is cos: res = _minpoly_cos(ex, x) elif ex.__class__ is tan: res = _minpoly_tan(ex, x) elif ex.__class__ is exp: res = _minpoly_exp(ex, x) elif ex.__class__ is CRootOf: res = _minpoly_rootof(ex, x) else: raise NotAlgebraic("%s doesn't seem to be an algebraic element" % ex) return res @public def minimal_polynomial(ex, x=None, compose=True, polys=False, domain=None): """ Computes the minimal polynomial of an algebraic element. Parameters ========== ex : Expr Element or expression whose minimal polynomial is to be calculated. x : Symbol, optional Independent variable of the minimal polynomial compose : boolean, optional (default=True) Method to use for computing minimal polynomial. If ``compose=True`` (default) then ``_minpoly_compose`` is used, if ``compose=False`` then groebner bases are used. polys : boolean, optional (default=False) If ``True`` returns a ``Poly`` object else an ``Expr`` object. domain : Domain, optional Ground domain Notes ===== By default ``compose=True``, the minimal polynomial of the subexpressions of ``ex`` are computed, then the arithmetic operations on them are performed using the resultant and factorization. If ``compose=False``, a bottom-up algorithm is used with ``groebner``. The default algorithm stalls less frequently. If no ground domain is given, it will be generated automatically from the expression. Examples ======== >>> from sympy import minimal_polynomial, sqrt, solve, QQ >>> from sympy.abc import x, y >>> minimal_polynomial(sqrt(2), x) x**2 - 2 >>> minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2))) x - sqrt(2) >>> minimal_polynomial(sqrt(2) + sqrt(3), x) x**4 - 10*x**2 + 1 >>> minimal_polynomial(solve(x**3 + x + 3)[0], x) x**3 + x + 3 >>> minimal_polynomial(sqrt(y), x) x**2 - y """ ex = sympify(ex) if ex.is_number: # not sure if it's always needed but try it for numbers (issue 8354) ex = _mexpand(ex, recursive=True) for expr in preorder_traversal(ex): if expr.is_AlgebraicNumber: compose = False break if x is not None: x, cls = sympify(x), Poly else: x, cls = Dummy('x'), PurePoly if not domain: if ex.free_symbols: domain = FractionField(QQ, list(ex.free_symbols)) else: domain = QQ if hasattr(domain, 'symbols') and x in domain.symbols: raise GeneratorsError("the variable %s is an element of the ground " "domain %s" % (x, domain)) if compose: result = _minpoly_compose(ex, x, domain) result = result.primitive()[1] c = result.coeff(x**degree(result, x)) if c.is_negative: result = expand_mul(-result) return cls(result, x, field=True) if polys else result.collect(x) if not domain.is_QQ: raise NotImplementedError("groebner method only works for QQ") result = _minpoly_groebner(ex, x, cls) return cls(result, x, field=True) if polys else result.collect(x) def _minpoly_groebner(ex, x, cls): """ Computes the minimal polynomial of an algebraic number using Groebner bases Examples ======== >>> from sympy import minimal_polynomial, sqrt, Rational >>> from sympy.abc import x >>> minimal_polynomial(sqrt(2) + 3*Rational(1, 3), x, compose=False) x**2 - 2*x - 1 """ generator = numbered_symbols('a', cls=Dummy) mapping, symbols = {}, {} def update_mapping(ex, exp, base=None): a = next(generator) symbols[ex] = a if base is not None: mapping[ex] = a**exp + base else: mapping[ex] = exp.as_expr(a) return a def bottom_up_scan(ex): if ex.is_Atom: if ex is S.ImaginaryUnit: if ex not in mapping: return update_mapping(ex, 2, 1) else: return symbols[ex] elif ex.is_Rational: return ex elif ex.is_Add: return Add(*[ bottom_up_scan(g) for g in ex.args ]) elif ex.is_Mul: return Mul(*[ bottom_up_scan(g) for g in ex.args ]) elif ex.is_Pow: if ex.exp.is_Rational: if ex.exp < 0: minpoly_base = _minpoly_groebner(ex.base, x, cls) inverse = invert(x, minpoly_base).as_expr() base_inv = inverse.subs(x, ex.base).expand() if ex.exp == -1: return bottom_up_scan(base_inv) else: ex = base_inv**(-ex.exp) if not ex.exp.is_Integer: base, exp = ( ex.base**ex.exp.p).expand(), Rational(1, ex.exp.q) else: base, exp = ex.base, ex.exp base = bottom_up_scan(base) expr = base**exp if expr not in mapping: return update_mapping(expr, 1/exp, -base) else: return symbols[expr] elif ex.is_AlgebraicNumber: if ex.root not in mapping: return update_mapping(ex.root, ex.minpoly) else: return symbols[ex.root] raise NotAlgebraic("%s doesn't seem to be an algebraic number" % ex) def simpler_inverse(ex): """ Returns True if it is more likely that the minimal polynomial algorithm works better with the inverse """ if ex.is_Pow: if (1/ex.exp).is_integer and ex.exp < 0: if ex.base.is_Add: return True if ex.is_Mul: hit = True for p in ex.args: if p.is_Add: return False if p.is_Pow: if p.base.is_Add and p.exp > 0: return False if hit: return True return False inverted = False ex = expand_multinomial(ex) if ex.is_AlgebraicNumber: return ex.minpoly.as_expr(x) elif ex.is_Rational: result = ex.q*x - ex.p else: inverted = simpler_inverse(ex) if inverted: ex = ex**-1 res = None if ex.is_Pow and (1/ex.exp).is_Integer: n = 1/ex.exp res = _minimal_polynomial_sq(ex.base, n, x) elif _is_sum_surds(ex): res = _minimal_polynomial_sq(ex, S.One, x) if res is not None: result = res if res is None: bus = bottom_up_scan(ex) F = [x - bus] + list(mapping.values()) G = groebner(F, list(symbols.values()) + [x], order='lex') _, factors = factor_list(G[-1]) # by construction G[-1] has root `ex` result = _choose_factor(factors, x, ex) if inverted: result = _invertx(result, x) if result.coeff(x**degree(result, x)) < 0: result = expand_mul(-result) return result minpoly = minimal_polynomial def _switch_domain(g, K): # An algebraic relation f(a, b) = 0 over Q can also be written # g(b) = 0 where g is in Q(a)[x] and h(a) = 0 where h is in Q(b)[x]. # This function transforms g into h where Q(b) = K. frep = g.rep.inject() hrep = frep.eject(K, front=True) return g.new(hrep, g.gens[0]) def _linsolve(p): # Compute root of linear polynomial. c, d = p.rep.rep return -d/c @public def primitive_element(extension, x=None, *, ex=False, polys=False): """Construct a common number field for all extensions. """ if not extension: raise ValueError("Cannot compute primitive element for empty extension") if x is not None: x, cls = sympify(x), Poly else: x, cls = Dummy('x'), PurePoly if not ex: gen, coeffs = extension[0], [1] g = minimal_polynomial(gen, x, polys=True) for ext in extension[1:]: _, factors = factor_list(g, extension=ext) g = _choose_factor(factors, x, gen) s, _, g = g.sqf_norm() gen += s*ext coeffs.append(s) if not polys: return g.as_expr(), coeffs else: return cls(g), coeffs gen, coeffs = extension[0], [1] f = minimal_polynomial(gen, x, polys=True) K = QQ.algebraic_field((f, gen)) # incrementally constructed field reps = [K.unit] # representations of extension elements in K for ext in extension[1:]: p = minimal_polynomial(ext, x, polys=True) L = QQ.algebraic_field((p, ext)) _, factors = factor_list(f, domain=L) f = _choose_factor(factors, x, gen) s, g, f = f.sqf_norm() gen += s*ext coeffs.append(s) K = QQ.algebraic_field((f, gen)) h = _switch_domain(g, K) erep = _linsolve(h.gcd(p)) # ext as element of K ogen = K.unit - s*erep # old gen as element of K reps = [dup_eval(_.rep, ogen, K) for _ in reps] + [erep] H = [_.rep for _ in reps] if not polys: return f.as_expr(), coeffs, H else: return f, coeffs, H
f2b87a890b76eb3174a8acc795fa865ca6732ae198e98e6df6104d5461bdbf93
"""Computations with ideals of polynomial rings.""" from sympy.polys.polyerrors import CoercionFailed from sympy.polys.polyutils import IntegerPowerable class Ideal(IntegerPowerable): """ Abstract base class for ideals. Do not instantiate - use explicit constructors in the ring class instead: >>> from sympy import QQ >>> from sympy.abc import x >>> QQ.old_poly_ring(x).ideal(x+1) <x + 1> Attributes - ring - the ring this ideal belongs to Non-implemented methods: - _contains_elem - _contains_ideal - _quotient - _intersect - _union - _product - is_whole_ring - is_zero - is_prime, is_maximal, is_primary, is_radical - is_principal - height, depth - radical Methods that likely should be overridden in subclasses: - reduce_element """ def _contains_elem(self, x): """Implementation of element containment.""" raise NotImplementedError def _contains_ideal(self, I): """Implementation of ideal containment.""" raise NotImplementedError def _quotient(self, J): """Implementation of ideal quotient.""" raise NotImplementedError def _intersect(self, J): """Implementation of ideal intersection.""" raise NotImplementedError def is_whole_ring(self): """Return True if ``self`` is the whole ring.""" raise NotImplementedError def is_zero(self): """Return True if ``self`` is the zero ideal.""" raise NotImplementedError def _equals(self, J): """Implementation of ideal equality.""" return self._contains_ideal(J) and J._contains_ideal(self) def is_prime(self): """Return True if ``self`` is a prime ideal.""" raise NotImplementedError def is_maximal(self): """Return True if ``self`` is a maximal ideal.""" raise NotImplementedError def is_radical(self): """Return True if ``self`` is a radical ideal.""" raise NotImplementedError def is_primary(self): """Return True if ``self`` is a primary ideal.""" raise NotImplementedError def is_principal(self): """Return True if ``self`` is a principal ideal.""" raise NotImplementedError def radical(self): """Compute the radical of ``self``.""" raise NotImplementedError def depth(self): """Compute the depth of ``self``.""" raise NotImplementedError def height(self): """Compute the height of ``self``.""" raise NotImplementedError # TODO more # non-implemented methods end here def __init__(self, ring): self.ring = ring def _check_ideal(self, J): """Helper to check ``J`` is an ideal of our ring.""" if not isinstance(J, Ideal) or J.ring != self.ring: raise ValueError( 'J must be an ideal of %s, got %s' % (self.ring, J)) def contains(self, elem): """ Return True if ``elem`` is an element of this ideal. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).ideal(x+1, x-1).contains(3) True >>> QQ.old_poly_ring(x).ideal(x**2, x**3).contains(x) False """ return self._contains_elem(self.ring.convert(elem)) def subset(self, other): """ Returns True if ``other`` is is a subset of ``self``. Here ``other`` may be an ideal. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> I = QQ.old_poly_ring(x).ideal(x+1) >>> I.subset([x**2 - 1, x**2 + 2*x + 1]) True >>> I.subset([x**2 + 1, x + 1]) False >>> I.subset(QQ.old_poly_ring(x).ideal(x**2 - 1)) True """ if isinstance(other, Ideal): return self._contains_ideal(other) return all(self._contains_elem(x) for x in other) def quotient(self, J, **opts): r""" Compute the ideal quotient of ``self`` by ``J``. That is, if ``self`` is the ideal `I`, compute the set `I : J = \{x \in R | xJ \subset I \}`. Examples ======== >>> from sympy.abc import x, y >>> from sympy import QQ >>> R = QQ.old_poly_ring(x, y) >>> R.ideal(x*y).quotient(R.ideal(x)) <y> """ self._check_ideal(J) return self._quotient(J, **opts) def intersect(self, J): """ Compute the intersection of self with ideal J. Examples ======== >>> from sympy.abc import x, y >>> from sympy import QQ >>> R = QQ.old_poly_ring(x, y) >>> R.ideal(x).intersect(R.ideal(y)) <x*y> """ self._check_ideal(J) return self._intersect(J) def saturate(self, J): r""" Compute the ideal saturation of ``self`` by ``J``. That is, if ``self`` is the ideal `I`, compute the set `I : J^\infty = \{x \in R | xJ^n \subset I \text{ for some } n\}`. """ raise NotImplementedError # Note this can be implemented using repeated quotient def union(self, J): """ Compute the ideal generated by the union of ``self`` and ``J``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).ideal(x**2 - 1).union(QQ.old_poly_ring(x).ideal((x+1)**2)) == QQ.old_poly_ring(x).ideal(x+1) True """ self._check_ideal(J) return self._union(J) def product(self, J): r""" Compute the ideal product of ``self`` and ``J``. That is, compute the ideal generated by products `xy`, for `x` an element of ``self`` and `y \in J`. Examples ======== >>> from sympy.abc import x, y >>> from sympy import QQ >>> QQ.old_poly_ring(x, y).ideal(x).product(QQ.old_poly_ring(x, y).ideal(y)) <x*y> """ self._check_ideal(J) return self._product(J) 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 __add__(self, e): if not isinstance(e, Ideal): R = self.ring.quotient_ring(self) if isinstance(e, R.dtype): return e if isinstance(e, R.ring.dtype): return R(e) return R.convert(e) self._check_ideal(e) return self.union(e) __radd__ = __add__ def __mul__(self, e): if not isinstance(e, Ideal): try: e = self.ring.ideal(e) except CoercionFailed: return NotImplemented self._check_ideal(e) return self.product(e) __rmul__ = __mul__ def _zeroth_power(self): return self.ring.ideal(1) def _first_power(self): # Raising to any power but 1 returns a new instance. So we mult by 1 # here so that the first power is no exception. return self * 1 def __eq__(self, e): if not isinstance(e, Ideal) or e.ring != self.ring: return False return self._equals(e) def __ne__(self, e): return not (self == e) class ModuleImplementedIdeal(Ideal): """ Ideal implementation relying on the modules code. Attributes: - _module - the underlying module """ def __init__(self, ring, module): Ideal.__init__(self, ring) self._module = module def _contains_elem(self, x): return self._module.contains([x]) def _contains_ideal(self, J): if not isinstance(J, ModuleImplementedIdeal): raise NotImplementedError return self._module.is_submodule(J._module) def _intersect(self, J): if not isinstance(J, ModuleImplementedIdeal): raise NotImplementedError return self.__class__(self.ring, self._module.intersect(J._module)) def _quotient(self, J, **opts): if not isinstance(J, ModuleImplementedIdeal): raise NotImplementedError return self._module.module_quotient(J._module, **opts) def _union(self, J): if not isinstance(J, ModuleImplementedIdeal): raise NotImplementedError return self.__class__(self.ring, self._module.union(J._module)) @property def gens(self): """ Return generators for ``self``. Examples ======== >>> from sympy import QQ >>> from sympy.abc import x, y >>> list(QQ.old_poly_ring(x, y).ideal(x, y, x**2 + y).gens) [x, y, x**2 + y] """ return (x[0] for x in self._module.gens) def is_zero(self): """ Return True if ``self`` is the zero ideal. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> QQ.old_poly_ring(x).ideal(x).is_zero() False >>> QQ.old_poly_ring(x).ideal().is_zero() True """ return self._module.is_zero() def is_whole_ring(self): """ Return True if ``self`` is the whole ring, i.e. one generator is a unit. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ, ilex >>> QQ.old_poly_ring(x).ideal(x).is_whole_ring() False >>> QQ.old_poly_ring(x).ideal(3).is_whole_ring() True >>> QQ.old_poly_ring(x, order=ilex).ideal(2 + x).is_whole_ring() True """ return self._module.is_full_module() def __repr__(self): from sympy.printing.str import sstr return '<' + ','.join(sstr(x) for [x] in self._module.gens) + '>' # NOTE this is the only method using the fact that the module is a SubModule def _product(self, J): if not isinstance(J, ModuleImplementedIdeal): raise NotImplementedError return self.__class__(self.ring, self._module.submodule( *[[x*y] for [x] in self._module.gens for [y] in J._module.gens])) def in_terms_of_generators(self, e): """ Express ``e`` in terms of the generators of ``self``. Examples ======== >>> from sympy.abc import x >>> from sympy import QQ >>> I = QQ.old_poly_ring(x).ideal(x**2 + 1, x) >>> I.in_terms_of_generators(1) [1, -x] """ return self._module.in_terms_of_generators([e]) def reduce_element(self, x, **options): return self._module.reduce_element([x], **options)[0]
5190679afb104c746449519db2dea792ca7d6b4ed9603eb9780ae32fdd67dfe4
""" 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 copy import copy from functools import 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 from sympy.utilities.iterables import iterable # TODO # - module saturation # - module quotient/intersection for quotient rings # - free resoltutions / syzygies # - finding small/minimal generating sets # - ... ########################################################################## ## Abstract base classes ################################################# ########################################################################## class Module: """ 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: """ 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.printing.str 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 [FreeModuleElement(self, tuple(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 # First bullet point k = len(self.gens) r = self.rank zero = self.ring.convert(0) one = self.ring.convert(1) 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] = one if j == i else zero m = FreeModuleElement(Rkr, tuple(m)) newgens.append(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 == zero 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)
81a30d57dea9294b981d9f0177b40eb36ec9d486db2609048f259c4cb7bc1852
""" 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 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: """ 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)
be29a98b674d62562940aab6dc60ce9312ed0d898f9a3abc061645570f54492d
'''Functions returning normal forms of matrices''' from collections import defaultdict from .domainmatrix import DomainMatrix from .exceptions import DMDomainError, DMShapeError from sympy.ntheory.modular import symmetric_residue from sympy.polys.domains import QQ, ZZ # TODO (future work): # There are faster algorithms for Smith and Hermite normal forms, which # we should implement. See e.g. the Kannan-Bachem algorithm: # <https://www.researchgate.net/publication/220617516_Polynomial_Algorithms_for_Computing_the_Smith_and_Hermite_Normal_Forms_of_an_Integer_Matrix> def smith_normal_form(m): ''' Return the Smith Normal Form of a matrix `m` over the ring `domain`. This will only work if the ring is a principal ideal domain. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> from sympy.polys.matrices.normalforms import smith_normal_form >>> m = DomainMatrix([[ZZ(12), ZZ(6), ZZ(4)], ... [ZZ(3), ZZ(9), ZZ(6)], ... [ZZ(2), ZZ(16), ZZ(14)]], (3, 3), ZZ) >>> print(smith_normal_form(m).to_Matrix()) Matrix([[1, 0, 0], [0, 10, 0], [0, 0, -30]]) ''' invs = invariant_factors(m) smf = DomainMatrix.diag(invs, m.domain, m.shape) return smf def add_columns(m, i, j, a, b, c, d): # replace m[:, i] by a*m[:, i] + b*m[:, j] # and m[:, j] by c*m[:, i] + d*m[:, j] for k in range(len(m)): e = m[k][i] m[k][i] = a*e + b*m[k][j] m[k][j] = c*e + d*m[k][j] def invariant_factors(m): ''' Return the tuple of abelian invariants for a matrix `m` (as in the Smith-Normal form) References ========== [1] https://en.wikipedia.org/wiki/Smith_normal_form#Algorithm [2] http://sierra.nmsu.edu/morandi/notes/SmithNormalForm.pdf ''' domain = m.domain if not domain.is_PID: msg = "The matrix entries must be over a principal ideal domain" raise ValueError(msg) if 0 in m.shape: return () rows, cols = shape = m.shape m = list(m.to_dense().rep) def add_rows(m, i, j, a, b, c, d): # replace m[i, :] by a*m[i, :] + b*m[j, :] # and m[j, :] by c*m[i, :] + d*m[j, :] for k in range(cols): e = m[i][k] m[i][k] = a*e + b*m[j][k] m[j][k] = c*e + d*m[j][k] def clear_column(m): # make m[1:, 0] zero by row and column operations if m[0][0] == 0: return m # pragma: nocover pivot = m[0][0] for j in range(1, rows): if m[j][0] == 0: continue d, r = domain.div(m[j][0], pivot) if r == 0: add_rows(m, 0, j, 1, 0, -d, 1) else: a, b, g = domain.gcdex(pivot, m[j][0]) d_0 = domain.div(m[j][0], g)[0] d_j = domain.div(pivot, g)[0] add_rows(m, 0, j, a, b, d_0, -d_j) pivot = g return m def clear_row(m): # make m[0, 1:] zero by row and column operations if m[0][0] == 0: return m # pragma: nocover pivot = m[0][0] for j in range(1, cols): if m[0][j] == 0: continue d, r = domain.div(m[0][j], pivot) if r == 0: add_columns(m, 0, j, 1, 0, -d, 1) else: a, b, g = domain.gcdex(pivot, m[0][j]) d_0 = domain.div(m[0][j], g)[0] d_j = domain.div(pivot, g)[0] add_columns(m, 0, j, a, b, d_0, -d_j) pivot = g return m # permute the rows and columns until m[0,0] is non-zero if possible ind = [i for i in range(rows) if m[i][0] != 0] if ind and ind[0] != 0: m[0], m[ind[0]] = m[ind[0]], m[0] else: ind = [j for j in range(cols) if m[0][j] != 0] if ind and ind[0] != 0: for row in m: row[0], row[ind[0]] = row[ind[0]], row[0] # make the first row and column except m[0,0] zero while (any(m[0][i] != 0 for i in range(1,cols)) or any(m[i][0] != 0 for i in range(1,rows))): m = clear_column(m) m = clear_row(m) if 1 in shape: invs = () else: lower_right = DomainMatrix([r[1:] for r in m[1:]], (rows-1, cols-1), domain) invs = invariant_factors(lower_right) if m[0][0]: result = [m[0][0]] result.extend(invs) # in case m[0] doesn't divide the invariants of the rest of the matrix for i in range(len(result)-1): if result[i] and domain.div(result[i+1], result[i])[1] != 0: g = domain.gcd(result[i+1], result[i]) result[i+1] = domain.div(result[i], g)[0]*result[i+1] result[i] = g else: break else: result = invs + (m[0][0],) return tuple(result) def _gcdex(a, b): """ This supports the functions that compute Hermite Normal Form. Let x, y be the coefficients returned by the extended Euclidean Algorithm, so that x*a + y*b = g. In the algorithms for computing HNF, it is critical that x, y not only satisfy the condition of being small in magnitude -- namely that |x| <= |b|/g, |y| <- |a|/g -- but also that y == 0 when a | b. """ x, y, g = ZZ.gcdex(a, b) if a != 0 and b % a == 0: y = 0 x = -1 if a < 0 else 1 return x, y, g def _hermite_normal_form(A): r""" Compute the Hermite Normal Form of DomainMatrix *A* over :ref:`ZZ`. Parameters ========== A: DomainMatrix over domain :ref:`ZZ`. Returns ======= DomainMatrix The HNF of matrix *A*. Raises ====== DMDomainError If the domain of the matrix is not :ref:`ZZ`. References ========== [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* (See Algorithm 2.4.5.) """ if not A.domain.is_ZZ: raise DMDomainError('Matrix must be over domain ZZ.') # We work one row at a time, starting from the bottom row, and working our # way up. The total number of rows we will consider is min(m, n), where # A is an m x n matrix. m, n = A.shape rows = min(m, n) A = A.to_dense().rep.copy() # Our goal is to put pivot entries in the rightmost columns. # Invariant: Before processing each row, k should be the index of the # leftmost column in which we have so far put a pivot. k = n for i in range(m - 1, m - 1 - rows, -1): k -= 1 # k now points to the column in which we want to put a pivot. # We want zeros in all entries to the left of the pivot column. for j in range(k - 1, -1, -1): if A[i][j] != 0: # Replace cols j, k by lin combs of these cols such that, in row i, # col j has 0, while col k has the gcd of their row i entries. Note # that this ensures a nonzero entry in col k. u, v, d = _gcdex(A[i][k], A[i][j]) r, s = A[i][k] // d, A[i][j] // d add_columns(A, k, j, u, v, -s, r) b = A[i][k] # Do not want the pivot entry to be negative. if b < 0: add_columns(A, k, k, -1, 0, -1, 0) b = -b # The pivot entry will be 0 iff the row was 0 from the pivot col all the # way to the left. In this case, we are still working on the same pivot # col for the next row. Therefore: if b == 0: k += 1 # If the pivot entry is nonzero, then we want to reduce all entries to its # right in the sense of the division algorithm, i.e. make them all remainders # w.r.t. the pivot as divisor. else: for j in range(k + 1, n): q = A[i][j] // b add_columns(A, j, k, 1, -q, 0, 1) # Finally, the HNF consists of those columns of A in which we succeeded in making # a nonzero pivot. return DomainMatrix.from_rep(A)[:, k:] def _hermite_normal_form_modulo_D(A, D): r""" Perform the mod *D* Hermite Normal Form reduction algorithm on DomainMatrix *A*. Explanation =========== If *A* is an $m \times n$ matrix of rank $m$, having Hermite Normal Form $W$, and if *D* is any positive integer known in advance to be a multiple of $\det(W)$, then the HNF of *A* can be computed by an algorithm that works mod *D* in order to prevent coefficient explosion. Parameters ========== A: $m \times n $ DomainMatrix over domain :ref:ZZ, having rank $m$. D: positive integer known to be a multiple of the determinant of the HNF of *A*. Returns ======= DomainMatrix The HNF of matrix *A*. Raises ====== DMDomainError If the domain of the matrix is not :ref:`ZZ`. DMShapeError If the matrix has more rows than columns. References ========== [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* (See Algorithm 2.4.8.) """ if not A.domain.is_ZZ: raise DMDomainError('Matrix must be over domain ZZ.') def add_columns_mod_R(m, R, i, j, a, b, c, d): # replace m[:, i] by (a*m[:, i] + b*m[:, j]) % R # and m[:, j] by (c*m[:, i] + d*m[:, j]) % R for k in range(len(m)): e = m[k][i] m[k][i] = symmetric_residue((a * e + b * m[k][j]) % R, R) m[k][j] = symmetric_residue((c * e + d * m[k][j]) % R, R) W = defaultdict(dict) m, n = A.shape if n < m: raise DMShapeError('Matrix must have at least as many columns as rows.') A = A.to_dense().rep.copy() k = n R = ZZ(abs(D)) for i in range(m - 1, -1, -1): k -= 1 for j in range(k - 1, -1, -1): if A[i][j] != 0: u, v, d = _gcdex(A[i][k], A[i][j]) r, s = A[i][k] // d, A[i][j] // d add_columns_mod_R(A, R, k, j, u, v, -s, r) b = A[i][k] if b == 0: A[i][k] = b = R u, v, d = _gcdex(b, R) for ii in range(m): W[ii][i] = u*A[ii][k] % R if W[i][i] == 0: W[i][i] = R for j in range(i + 1, m): q = W[i][j] // W[i][i] add_columns(W, j, i, 1, -q, 0, 1) R //= d return DomainMatrix(W, (m, m), ZZ).to_dense() def hermite_normal_form(A, *, D=None, check_rank=False): r''' Compute the Hermite Normal Form of DomainMatrix *A* over :ref:`ZZ`. Parameters ========== A: $m \times n$ DomainMatrix over domain :ref:`ZZ`. D: positive integer (optional) Let $W$ be the HNF of *A*. If known in advance, a positive integer *D* being any multiple of $\det(W)$ may be provided. In this case, if *A* also has rank $m$, then we may use an alternative algorithm that works mod *D* in order to prevent coefficient explosion. check_rank: boolean (default ``False``) The basic assumption is that, if you pass a value for *D*, then you already believe that *A* has rank $m$, so we do not waste time checking it for you. If you do want this to be checked (and the ordinary, non-modulo *D* algorithm to be used if the check fails), then set *check_rank* to ``True``. Returns ======= DomainMatrix The HNF of matrix *A*. Raises ====== DMDomainError If the domain of the matrix is not :ref:`ZZ`. DMShapeError If the mod *D* algorithm is used but the matrix has more rows than columns. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> from sympy.polys.matrices.normalforms import hermite_normal_form >>> m = DomainMatrix([[ZZ(12), ZZ(6), ZZ(4)], ... [ZZ(3), ZZ(9), ZZ(6)], ... [ZZ(2), ZZ(16), ZZ(14)]], (3, 3), ZZ) >>> print(hermite_normal_form(m).to_Matrix()) Matrix([[10, 0, 2], [0, 15, 3], [0, 0, 2]]) References ========== [1] Cohen, H. *A Course in Computational Algebraic Number Theory.* (See Algorithms 2.4.5 and 2.4.8.) ''' if not A.domain.is_ZZ: raise DMDomainError('Matrix must be over domain ZZ.') if D is not None and (not check_rank or A.convert_to(QQ).rank() == A.shape[0]): return _hermite_normal_form_modulo_D(A, D) else: return _hermite_normal_form(A)
65a3c9322f25db6777177aee752e0dab34add31c316ecdeec27430961851f75a
""" sympy.polys.matrices package. The main export from this package is the DomainMatrix class which is a lower-level implementation of matrices based on the polys Domains. This implementation is typically a lot faster than SymPy's standard Matrix class but is a work in progress and is still experimental. """ from .domainmatrix import DomainMatrix, DM __all__ = [ 'DomainMatrix', 'DM', ]
e803216413d8641dc183ac040f3d124f7e2ef9bb059d74945bf14bed37f709f5
""" Module for the DomainMatrix class. A DomainMatrix represents a matrix with elements that are in a particular Domain. Each DomainMatrix internally wraps a DDM which is used for the lower-level operations. The idea is that the DomainMatrix class provides the convenience routines for converting between Expr and the poly domains as well as unifying matrices with different domains. """ from functools import reduce from typing import Union as tUnion, Tuple as tTuple from sympy.core.sympify import _sympify from ..domains import Domain from ..constructor import construct_domain from .exceptions import (DMNonSquareMatrixError, DMShapeError, DMDomainError, DMFormatError, DMBadInputError, DMNotAField) from .ddm import DDM from .sdm import SDM from .domainscalar import DomainScalar from sympy.polys.domains import ZZ, EXRAW def DM(rows, domain): """Convenient alias for DomainMatrix.from_list Examples ======= >>> from sympy import ZZ >>> from sympy.polys.matrices import DM >>> DM([[1, 2], [3, 4]], ZZ) DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ) See also ======= DomainMatrix.from_list """ return DomainMatrix.from_list(rows, domain) class DomainMatrix: r""" Associate Matrix with :py:class:`~.Domain` Explanation =========== DomainMatrix uses :py:class:`~.Domain` for its internal representation which makes it more faster for many common operations than current SymPy Matrix class, but this advantage makes it not entirely compatible with Matrix. DomainMatrix could be found analogous to numpy arrays with "dtype". In the DomainMatrix, each matrix has a domain such as :ref:`ZZ` or :ref:`QQ(a)`. Examples ======== Creating a DomainMatrix from the existing Matrix class: >>> from sympy import Matrix >>> from sympy.polys.matrices import DomainMatrix >>> Matrix1 = Matrix([ ... [1, 2], ... [3, 4]]) >>> A = DomainMatrix.from_Matrix(Matrix1) >>> A DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ) Driectly forming a DomainMatrix: >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ) See Also ======== DDM SDM Domain Poly """ rep: tUnion[SDM, DDM] shape: tTuple[int, int] domain: Domain def __new__(cls, rows, shape, domain, *, fmt=None): """ Creates a :py:class:`~.DomainMatrix`. Parameters ========== rows : Represents elements of DomainMatrix as list of lists shape : Represents dimension of DomainMatrix domain : Represents :py:class:`~.Domain` of DomainMatrix Raises ====== TypeError If any of rows, shape and domain are not provided """ if isinstance(rows, (DDM, SDM)): raise TypeError("Use from_rep to initialise from SDM/DDM") elif isinstance(rows, list): rep = DDM(rows, shape, domain) elif isinstance(rows, dict): rep = SDM(rows, shape, domain) else: msg = "Input should be list-of-lists or dict-of-dicts" raise TypeError(msg) if fmt is not None: if fmt == 'sparse': rep = rep.to_sdm() elif fmt == 'dense': rep = rep.to_ddm() else: raise ValueError("fmt should be 'sparse' or 'dense'") return cls.from_rep(rep) def __getnewargs__(self): rep = self.rep if isinstance(rep, DDM): arg = list(rep) elif isinstance(rep, SDM): arg = dict(rep) else: raise RuntimeError # pragma: no cover return arg, self.shape, self.domain def __getitem__(self, key): i, j = key m, n = self.shape if not (isinstance(i, slice) or isinstance(j, slice)): return DomainScalar(self.rep.getitem(i, j), self.domain) if not isinstance(i, slice): if not -m <= i < m: raise IndexError("Row index out of range") i = i % m i = slice(i, i+1) if not isinstance(j, slice): if not -n <= j < n: raise IndexError("Column index out of range") j = j % n j = slice(j, j+1) return self.from_rep(self.rep.extract_slice(i, j)) def getitem_sympy(self, i, j): return self.domain.to_sympy(self.rep.getitem(i, j)) def extract(self, rowslist, colslist): return self.from_rep(self.rep.extract(rowslist, colslist)) def __setitem__(self, key, value): i, j = key if not self.domain.of_type(value): raise TypeError if isinstance(i, int) and isinstance(j, int): self.rep.setitem(i, j, value) else: raise NotImplementedError @classmethod def from_rep(cls, rep): """Create a new DomainMatrix efficiently from DDM/SDM. Examples ======== Create a :py:class:`~.DomainMatrix` with an dense internal representation as :py:class:`~.DDM`: >>> from sympy.polys.domains import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> from sympy.polys.matrices.ddm import DDM >>> drep = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> dM = DomainMatrix.from_rep(drep) >>> dM DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ) Create a :py:class:`~.DomainMatrix` with a sparse internal representation as :py:class:`~.SDM`: >>> from sympy.polys.matrices import DomainMatrix >>> from sympy.polys.matrices.sdm import SDM >>> from sympy import ZZ >>> drep = SDM({0:{1:ZZ(1)},1:{0:ZZ(2)}}, (2, 2), ZZ) >>> dM = DomainMatrix.from_rep(drep) >>> dM DomainMatrix({0: {1: 1}, 1: {0: 2}}, (2, 2), ZZ) Parameters ========== rep: SDM or DDM The internal sparse or dense representation of the matrix. Returns ======= DomainMatrix A :py:class:`~.DomainMatrix` wrapping *rep*. Notes ===== This takes ownership of rep as its internal representation. If rep is being mutated elsewhere then a copy should be provided to ``from_rep``. Only minimal verification or checking is done on *rep* as this is supposed to be an efficient internal routine. """ if not isinstance(rep, (DDM, SDM)): raise TypeError("rep should be of type DDM or SDM") self = super().__new__(cls) self.rep = rep self.shape = rep.shape self.domain = rep.domain return self @classmethod def from_list(cls, rows, domain): r""" Convert a list of lists into a DomainMatrix Parameters ========== rows: list of lists Each element of the inner lists should be either the single arg, or tuple of args, that would be passed to the domain constructor in order to form an element of the domain. See examples. Returns ======= DomainMatrix containing elements defined in rows Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import FF, QQ, ZZ >>> A = DomainMatrix.from_list([[1, 0, 1], [0, 0, 1]], ZZ) >>> A DomainMatrix([[1, 0, 1], [0, 0, 1]], (2, 3), ZZ) >>> B = DomainMatrix.from_list([[1, 0, 1], [0, 0, 1]], FF(7)) >>> B DomainMatrix([[1 mod 7, 0 mod 7, 1 mod 7], [0 mod 7, 0 mod 7, 1 mod 7]], (2, 3), GF(7)) >>> C = DomainMatrix.from_list([[(1, 2), (3, 1)], [(1, 4), (5, 1)]], QQ) >>> C DomainMatrix([[1/2, 3], [1/4, 5]], (2, 2), QQ) See Also ======== from_list_sympy """ nrows = len(rows) ncols = 0 if not nrows else len(rows[0]) conv = lambda e: domain(*e) if isinstance(e, tuple) else domain(e) domain_rows = [[conv(e) for e in row] for row in rows] return DomainMatrix(domain_rows, (nrows, ncols), domain) @classmethod def from_list_sympy(cls, nrows, ncols, rows, **kwargs): r""" Convert a list of lists of Expr into a DomainMatrix using construct_domain Parameters ========== nrows: number of rows ncols: number of columns rows: list of lists Returns ======= DomainMatrix containing elements of rows Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy.abc import x, y, z >>> A = DomainMatrix.from_list_sympy(1, 3, [[x, y, z]]) >>> A DomainMatrix([[x, y, z]], (1, 3), ZZ[x,y,z]) See Also ======== sympy.polys.constructor.construct_domain, from_dict_sympy """ assert len(rows) == nrows assert all(len(row) == ncols for row in rows) items_sympy = [_sympify(item) for row in rows for item in row] domain, items_domain = cls.get_domain(items_sympy, **kwargs) domain_rows = [[items_domain[ncols*r + c] for c in range(ncols)] for r in range(nrows)] return DomainMatrix(domain_rows, (nrows, ncols), domain) @classmethod def from_dict_sympy(cls, nrows, ncols, elemsdict, **kwargs): """ Parameters ========== nrows: number of rows ncols: number of cols elemsdict: dict of dicts containing non-zero elements of the DomainMatrix Returns ======= DomainMatrix containing elements of elemsdict Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy.abc import x,y,z >>> elemsdict = {0: {0:x}, 1:{1: y}, 2: {2: z}} >>> A = DomainMatrix.from_dict_sympy(3, 3, elemsdict) >>> A DomainMatrix({0: {0: x}, 1: {1: y}, 2: {2: z}}, (3, 3), ZZ[x,y,z]) See Also ======== from_list_sympy """ if not all(0 <= r < nrows for r in elemsdict): raise DMBadInputError("Row out of range") if not all(0 <= c < ncols for row in elemsdict.values() for c in row): raise DMBadInputError("Column out of range") items_sympy = [_sympify(item) for row in elemsdict.values() for item in row.values()] domain, items_domain = cls.get_domain(items_sympy, **kwargs) idx = 0 items_dict = {} for i, row in elemsdict.items(): items_dict[i] = {} for j in row: items_dict[i][j] = items_domain[idx] idx += 1 return DomainMatrix(items_dict, (nrows, ncols), domain) @classmethod def from_Matrix(cls, M, fmt='sparse',**kwargs): r""" Convert Matrix to DomainMatrix Parameters ========== M: Matrix Returns ======= Returns DomainMatrix with identical elements as M Examples ======== >>> from sympy import Matrix >>> from sympy.polys.matrices import DomainMatrix >>> M = Matrix([ ... [1.0, 3.4], ... [2.4, 1]]) >>> A = DomainMatrix.from_Matrix(M) >>> A DomainMatrix({0: {0: 1.0, 1: 3.4}, 1: {0: 2.4, 1: 1.0}}, (2, 2), RR) We can keep internal representation as ddm using fmt='dense' >>> from sympy import Matrix, QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix.from_Matrix(Matrix([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]]), fmt='dense') >>> A.rep [[1/2, 3/4], [0, 0]] See Also ======== Matrix """ if fmt == 'dense': return cls.from_list_sympy(*M.shape, M.tolist(), **kwargs) return cls.from_dict_sympy(*M.shape, M.todod(), **kwargs) @classmethod def get_domain(cls, items_sympy, **kwargs): K, items_K = construct_domain(items_sympy, **kwargs) return K, items_K def copy(self): return self.from_rep(self.rep.copy()) def convert_to(self, K): r""" Change the domain of DomainMatrix to desired domain or field Parameters ========== K : Represents the desired domain or field Returns ======= DomainMatrix DomainMatrix with the desired domain or field Examples ======== >>> from sympy import ZZ, ZZ_I >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A.convert_to(ZZ_I) DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ_I) """ return self.from_rep(self.rep.convert_to(K)) def to_sympy(self): return self.convert_to(EXRAW) def to_field(self): r""" Returns a DomainMatrix with the appropriate field Returns ======= DomainMatrix DomainMatrix with the appropriate field Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A.to_field() DomainMatrix([[1, 2], [3, 4]], (2, 2), QQ) """ K = self.domain.get_field() return self.convert_to(K) def to_sparse(self): """ Return a sparse DomainMatrix representation of *self*. Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import QQ >>> A = DomainMatrix([[1, 0],[0, 2]], (2, 2), QQ) >>> A.rep [[1, 0], [0, 2]] >>> B = A.to_sparse() >>> B.rep {0: {0: 1}, 1: {1: 2}} """ if self.rep.fmt == 'sparse': return self return self.from_rep(SDM.from_ddm(self.rep)) def to_dense(self): """ Return a dense DomainMatrix representation of *self*. Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import QQ >>> A = DomainMatrix({0: {0: 1}, 1: {1: 2}}, (2, 2), QQ) >>> A.rep {0: {0: 1}, 1: {1: 2}} >>> B = A.to_dense() >>> B.rep [[1, 0], [0, 2]] """ if self.rep.fmt == 'dense': return self return self.from_rep(SDM.to_ddm(self.rep)) @classmethod def _unify_domain(cls, *matrices): """Convert matrices to a common domain""" domains = {matrix.domain for matrix in matrices} if len(domains) == 1: return matrices domain = reduce(lambda x, y: x.unify(y), domains) return tuple(matrix.convert_to(domain) for matrix in matrices) @classmethod def _unify_fmt(cls, *matrices, fmt=None): """Convert matrices to the same format. If all matrices have the same format, then return unmodified. Otherwise convert both to the preferred format given as *fmt* which should be 'dense' or 'sparse'. """ formats = {matrix.rep.fmt for matrix in matrices} if len(formats) == 1: return matrices if fmt == 'sparse': return tuple(matrix.to_sparse() for matrix in matrices) elif fmt == 'dense': return tuple(matrix.to_dense() for matrix in matrices) else: raise ValueError("fmt should be 'sparse' or 'dense'") def unify(self, *others, fmt=None): """ Unifies the domains and the format of self and other matrices. Parameters ========== others : DomainMatrix fmt: string 'dense', 'sparse' or `None` (default) The preferred format to convert to if self and other are not already in the same format. If `None` or not specified then no conversion if performed. Returns ======= Tuple[DomainMatrix] Matrices with unified domain and format Examples ======== Unify the domain of DomainMatrix that have different domains: >>> from sympy import ZZ, QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) >>> B = DomainMatrix([[QQ(1, 2), QQ(2)]], (1, 2), QQ) >>> Aq, Bq = A.unify(B) >>> Aq DomainMatrix([[1, 2]], (1, 2), QQ) >>> Bq DomainMatrix([[1/2, 2]], (1, 2), QQ) Unify the format (dense or sparse): >>> A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) >>> B = DomainMatrix({0:{0: ZZ(1)}}, (2, 2), ZZ) >>> B.rep {0: {0: 1}} >>> A2, B2 = A.unify(B, fmt='dense') >>> B2.rep [[1, 0], [0, 0]] See Also ======== convert_to, to_dense, to_sparse """ matrices = (self,) + others matrices = DomainMatrix._unify_domain(*matrices) if fmt is not None: matrices = DomainMatrix._unify_fmt(*matrices, fmt=fmt) return matrices def to_Matrix(self): r""" Convert DomainMatrix to Matrix Returns ======= Matrix MutableDenseMatrix for the DomainMatrix Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A.to_Matrix() Matrix([ [1, 2], [3, 4]]) See Also ======== from_Matrix """ from sympy.matrices.dense import MutableDenseMatrix elemlist = self.rep.to_list() elements_sympy = [self.domain.to_sympy(e) for row in elemlist for e in row] return MutableDenseMatrix(*self.shape, elements_sympy) def to_list(self): return self.rep.to_list() def to_list_flat(self): return self.rep.to_list_flat() def to_dok(self): return self.rep.to_dok() def __repr__(self): return 'DomainMatrix(%s, %r, %r)' % (str(self.rep), self.shape, self.domain) def transpose(self): """Matrix transpose of ``self``""" return self.from_rep(self.rep.transpose()) def flat(self): rows, cols = self.shape return [self[i,j].element for i in range(rows) for j in range(cols)] @property def is_zero_matrix(self): return self.rep.is_zero_matrix() @property def is_upper(self): """ Says whether this matrix is upper-triangular. True can be returned even if the matrix is not square. """ return self.rep.is_upper() @property def is_lower(self): """ Says whether this matrix is lower-triangular. True can be returned even if the matrix is not square. """ return self.rep.is_lower() @property def is_square(self): return self.shape[0] == self.shape[1] def rank(self): rref, pivots = self.rref() return len(pivots) def hstack(A, *B): r"""Horizontally stack the given matrices. Parameters ========== B: DomainMatrix Matrices to stack horizontally. Returns ======= DomainMatrix DomainMatrix by stacking horizontally. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ) >>> A.hstack(B) DomainMatrix([[1, 2, 5, 6], [3, 4, 7, 8]], (2, 4), ZZ) >>> C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ) >>> A.hstack(B, C) DomainMatrix([[1, 2, 5, 6, 9, 10], [3, 4, 7, 8, 11, 12]], (2, 6), ZZ) See Also ======== unify """ A, *B = A.unify(*B, fmt='dense') return DomainMatrix.from_rep(A.rep.hstack(*(Bk.rep for Bk in B))) def vstack(A, *B): r"""Vertically stack the given matrices. Parameters ========== B: DomainMatrix Matrices to stack vertically. Returns ======= DomainMatrix DomainMatrix by stacking vertically. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ) >>> A.vstack(B) DomainMatrix([[1, 2], [3, 4], [5, 6], [7, 8]], (4, 2), ZZ) >>> C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ) >>> A.vstack(B, C) DomainMatrix([[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]], (6, 2), ZZ) See Also ======== unify """ A, *B = A.unify(*B, fmt='dense') return DomainMatrix.from_rep(A.rep.vstack(*(Bk.rep for Bk in B))) def applyfunc(self, func, domain=None): if domain is None: domain = self.domain return self.from_rep(self.rep.applyfunc(func, domain)) def __add__(A, B): if not isinstance(B, DomainMatrix): return NotImplemented A, B = A.unify(B, fmt='dense') return A.add(B) def __sub__(A, B): if not isinstance(B, DomainMatrix): return NotImplemented A, B = A.unify(B, fmt='dense') return A.sub(B) def __neg__(A): return A.neg() def __mul__(A, B): """A * B""" if isinstance(B, DomainMatrix): A, B = A.unify(B, fmt='dense') return A.matmul(B) elif B in A.domain: return A.scalarmul(B) elif isinstance(B, DomainScalar): A, B = A.unify(B) return A.scalarmul(B.element) else: return NotImplemented def __rmul__(A, B): if B in A.domain: return A.rscalarmul(B) elif isinstance(B, DomainScalar): A, B = A.unify(B) return A.rscalarmul(B.element) else: return NotImplemented def __pow__(A, n): """A ** n""" if not isinstance(n, int): return NotImplemented return A.pow(n) def _check(a, op, b, ashape, bshape): if a.domain != b.domain: msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain) raise DMDomainError(msg) if ashape != bshape: msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape) raise DMShapeError(msg) if a.rep.fmt != b.rep.fmt: msg = "Format mismatch: %s %s %s" % (a.rep.fmt, op, b.rep.fmt) raise DMFormatError(msg) def add(A, B): r""" Adds two DomainMatrix matrices of the same Domain Parameters ========== A, B: DomainMatrix matrices to add Returns ======= DomainMatrix DomainMatrix after Addition Raises ====== DMShapeError If the dimensions of the two DomainMatrix are not equal ValueError If the domain of the two DomainMatrix are not same Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> B = DomainMatrix([ ... [ZZ(4), ZZ(3)], ... [ZZ(2), ZZ(1)]], (2, 2), ZZ) >>> A.add(B) DomainMatrix([[5, 5], [5, 5]], (2, 2), ZZ) See Also ======== sub, matmul """ A._check('+', B, A.shape, B.shape) return A.from_rep(A.rep.add(B.rep)) def sub(A, B): r""" Subtracts two DomainMatrix matrices of the same Domain Parameters ========== A, B: DomainMatrix matrices to substract Returns ======= DomainMatrix DomainMatrix after Substraction Raises ====== DMShapeError If the dimensions of the two DomainMatrix are not equal ValueError If the domain of the two DomainMatrix are not same Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> B = DomainMatrix([ ... [ZZ(4), ZZ(3)], ... [ZZ(2), ZZ(1)]], (2, 2), ZZ) >>> A.sub(B) DomainMatrix([[-3, -1], [1, 3]], (2, 2), ZZ) See Also ======== add, matmul """ A._check('-', B, A.shape, B.shape) return A.from_rep(A.rep.sub(B.rep)) def neg(A): r""" Returns the negative of DomainMatrix Parameters ========== A : Represents a DomainMatrix Returns ======= DomainMatrix DomainMatrix after Negation Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A.neg() DomainMatrix([[-1, -2], [-3, -4]], (2, 2), ZZ) """ return A.from_rep(A.rep.neg()) def mul(A, b): r""" Performs term by term multiplication for the second DomainMatrix w.r.t first DomainMatrix. Returns a DomainMatrix whose rows are list of DomainMatrix matrices created after term by term multiplication. Parameters ========== A, B: DomainMatrix matrices to multiply term-wise Returns ======= DomainMatrix DomainMatrix after term by term multiplication Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> B = DomainMatrix([ ... [ZZ(1), ZZ(1)], ... [ZZ(0), ZZ(1)]], (2, 2), ZZ) >>> A.mul(B) DomainMatrix([[DomainMatrix([[1, 1], [0, 1]], (2, 2), ZZ), DomainMatrix([[2, 2], [0, 2]], (2, 2), ZZ)], [DomainMatrix([[3, 3], [0, 3]], (2, 2), ZZ), DomainMatrix([[4, 4], [0, 4]], (2, 2), ZZ)]], (2, 2), ZZ) See Also ======== matmul """ return A.from_rep(A.rep.mul(b)) def rmul(A, b): return A.from_rep(A.rep.rmul(b)) def matmul(A, B): r""" Performs matrix multiplication of two DomainMatrix matrices Parameters ========== A, B: DomainMatrix to multiply Returns ======= DomainMatrix DomainMatrix after multiplication Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> B = DomainMatrix([ ... [ZZ(1), ZZ(1)], ... [ZZ(0), ZZ(1)]], (2, 2), ZZ) >>> A.matmul(B) DomainMatrix([[1, 3], [3, 7]], (2, 2), ZZ) See Also ======== mul, pow, add, sub """ A._check('*', B, A.shape[1], B.shape[0]) return A.from_rep(A.rep.matmul(B.rep)) def _scalarmul(A, lamda, reverse): if lamda == A.domain.zero: return DomainMatrix.zeros(A.shape, A.domain) elif lamda == A.domain.one: return A.copy() elif reverse: return A.rmul(lamda) else: return A.mul(lamda) def scalarmul(A, lamda): return A._scalarmul(lamda, reverse=False) def rscalarmul(A, lamda): return A._scalarmul(lamda, reverse=True) def mul_elementwise(A, B): assert A.domain == B.domain return A.from_rep(A.rep.mul_elementwise(B.rep)) def __truediv__(A, lamda): """ Method for Scalar Divison""" if isinstance(lamda, int): lamda = DomainScalar(ZZ(lamda), ZZ) if not isinstance(lamda, DomainScalar): return NotImplemented A, lamda = A.to_field().unify(lamda) if lamda.element == lamda.domain.zero: raise ZeroDivisionError if lamda.element == lamda.domain.one: return A.to_field() return A.mul(1 / lamda.element) def pow(A, n): r""" Computes A**n Parameters ========== A : DomainMatrix n : exponent for A Returns ======= DomainMatrix DomainMatrix on computing A**n Raises ====== NotImplementedError if n is negative. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(1)], ... [ZZ(0), ZZ(1)]], (2, 2), ZZ) >>> A.pow(2) DomainMatrix([[1, 2], [0, 1]], (2, 2), ZZ) See Also ======== matmul """ nrows, ncols = A.shape if nrows != ncols: raise DMNonSquareMatrixError('Power of a nonsquare matrix') if n < 0: raise NotImplementedError('Negative powers') elif n == 0: return A.eye(nrows, A.domain) elif n == 1: return A elif n % 2 == 1: return A * A**(n - 1) else: sqrtAn = A ** (n // 2) return sqrtAn * sqrtAn def scc(self): """Compute the strongly connected components of a DomainMatrix Explanation =========== A square matrix can be considered as the adjacency matrix for a directed graph where the row and column indices are the vertices. In this graph if there is an edge from vertex ``i`` to vertex ``j`` if ``M[i, j]`` is nonzero. This routine computes the strongly connected components of that graph which are subsets of the rows and columns that are connected by some nonzero element of the matrix. The strongly connected components are useful because many operations such as the determinant can be computed by working with the submatrices corresponding to each component. Examples ======== Find the strongly connected components of a matrix: >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> M = DomainMatrix([[ZZ(1), ZZ(0), ZZ(2)], ... [ZZ(0), ZZ(3), ZZ(0)], ... [ZZ(4), ZZ(6), ZZ(5)]], (3, 3), ZZ) >>> M.scc() [[1], [0, 2]] Compute the determinant from the components: >>> MM = M.to_Matrix() >>> MM Matrix([ [1, 0, 2], [0, 3, 0], [4, 6, 5]]) >>> MM[[1], [1]] Matrix([[3]]) >>> MM[[0, 2], [0, 2]] Matrix([ [1, 2], [4, 5]]) >>> MM.det() -9 >>> MM[[1], [1]].det() * MM[[0, 2], [0, 2]].det() -9 The components are given in reverse topological order and represent a permutation of the rows and columns that will bring the matrix into block lower-triangular form: >>> MM[[1, 0, 2], [1, 0, 2]] Matrix([ [3, 0, 0], [0, 1, 2], [6, 4, 5]]) Returns ======= List of lists of integers Each list represents a strongly connected component. See also ======== sympy.matrices.matrices.MatrixBase.strongly_connected_components sympy.utilities.iterables.strongly_connected_components """ rows, cols = self.shape assert rows == cols return self.rep.scc() def rref(self): r""" Returns reduced-row echelon form and list of pivots for the DomainMatrix Returns ======= (DomainMatrix, list) reduced-row echelon form and list of pivots for the DomainMatrix Raises ====== ValueError If the domain of DomainMatrix not a Field Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [QQ(2), QQ(-1), QQ(0)], ... [QQ(-1), QQ(2), QQ(-1)], ... [QQ(0), QQ(0), QQ(2)]], (3, 3), QQ) >>> rref_matrix, rref_pivots = A.rref() >>> rref_matrix DomainMatrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]], (3, 3), QQ) >>> rref_pivots (0, 1, 2) See Also ======== convert_to, lu """ if not self.domain.is_Field: raise DMNotAField('Not a field') rref_ddm, pivots = self.rep.rref() return self.from_rep(rref_ddm), tuple(pivots) def columnspace(self): r""" Returns the columnspace for the DomainMatrix Returns ======= DomainMatrix The columns of this matrix form a basis for the columnspace. Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [QQ(1), QQ(-1)], ... [QQ(2), QQ(-2)]], (2, 2), QQ) >>> A.columnspace() DomainMatrix([[1], [2]], (2, 1), QQ) """ if not self.domain.is_Field: raise DMNotAField('Not a field') rref, pivots = self.rref() rows, cols = self.shape return self.extract(range(rows), pivots) def rowspace(self): r""" Returns the rowspace for the DomainMatrix Returns ======= DomainMatrix The rows of this matrix form a basis for the rowspace. Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [QQ(1), QQ(-1)], ... [QQ(2), QQ(-2)]], (2, 2), QQ) >>> A.rowspace() DomainMatrix([[1, -1]], (1, 2), QQ) """ if not self.domain.is_Field: raise DMNotAField('Not a field') rref, pivots = self.rref() rows, cols = self.shape return self.extract(range(len(pivots)), range(cols)) def nullspace(self): r""" Returns the nullspace for the DomainMatrix Returns ======= DomainMatrix The rows of this matrix form a basis for the nullspace. Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [QQ(1), QQ(-1)], ... [QQ(2), QQ(-2)]], (2, 2), QQ) >>> A.nullspace() DomainMatrix([[1, 1]], (1, 2), QQ) """ if not self.domain.is_Field: raise DMNotAField('Not a field') return self.from_rep(self.rep.nullspace()[0]) def inv(self): r""" Finds the inverse of the DomainMatrix if exists Returns ======= DomainMatrix DomainMatrix after inverse Raises ====== ValueError If the domain of DomainMatrix not a Field DMNonSquareMatrixError If the DomainMatrix is not a not Square DomainMatrix Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [QQ(2), QQ(-1), QQ(0)], ... [QQ(-1), QQ(2), QQ(-1)], ... [QQ(0), QQ(0), QQ(2)]], (3, 3), QQ) >>> A.inv() DomainMatrix([[2/3, 1/3, 1/6], [1/3, 2/3, 1/3], [0, 0, 1/2]], (3, 3), QQ) See Also ======== neg """ if not self.domain.is_Field: raise DMNotAField('Not a field') m, n = self.shape if m != n: raise DMNonSquareMatrixError inv = self.rep.inv() return self.from_rep(inv) def det(self): r""" Returns the determinant of a Square DomainMatrix Returns ======= S.Complexes determinant of Square DomainMatrix Raises ====== ValueError If the domain of DomainMatrix not a Field Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A.det() -2 """ m, n = self.shape if m != n: raise DMNonSquareMatrixError return self.rep.det() def lu(self): r""" Returns Lower and Upper decomposition of the DomainMatrix Returns ======= (L, U, exchange) L, U are Lower and Upper decomposition of the DomainMatrix, exchange is the list of indices of rows exchanged in the decomposition. Raises ====== ValueError If the domain of DomainMatrix not a Field Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [QQ(1), QQ(-1)], ... [QQ(2), QQ(-2)]], (2, 2), QQ) >>> A.lu() (DomainMatrix([[1, 0], [2, 1]], (2, 2), QQ), DomainMatrix([[1, -1], [0, 0]], (2, 2), QQ), []) See Also ======== lu_solve """ if not self.domain.is_Field: raise DMNotAField('Not a field') L, U, swaps = self.rep.lu() return self.from_rep(L), self.from_rep(U), swaps def lu_solve(self, rhs): r""" Solver for DomainMatrix x in the A*x = B Parameters ========== rhs : DomainMatrix B Returns ======= DomainMatrix x in A*x = B Raises ====== DMShapeError If the DomainMatrix A and rhs have different number of rows ValueError If the domain of DomainMatrix A not a Field Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [QQ(1), QQ(2)], ... [QQ(3), QQ(4)]], (2, 2), QQ) >>> B = DomainMatrix([ ... [QQ(1), QQ(1)], ... [QQ(0), QQ(1)]], (2, 2), QQ) >>> A.lu_solve(B) DomainMatrix([[-2, -1], [3/2, 1]], (2, 2), QQ) See Also ======== lu """ if self.shape[0] != rhs.shape[0]: raise DMShapeError("Shape") if not self.domain.is_Field: raise DMNotAField('Not a field') sol = self.rep.lu_solve(rhs.rep) return self.from_rep(sol) def _solve(A, b): # XXX: Not sure about this method or its signature. It is just created # because it is needed by the holonomic module. if A.shape[0] != b.shape[0]: raise DMShapeError("Shape") if A.domain != b.domain or not A.domain.is_Field: raise DMNotAField('Not a field') Aaug = A.hstack(b) Arref, pivots = Aaug.rref() particular = Arref.from_rep(Arref.rep.particular()) nullspace_rep, nonpivots = Arref[:,:-1].rep.nullspace() nullspace = Arref.from_rep(nullspace_rep) return particular, nullspace def charpoly(self): r""" Returns the coefficients of the characteristic polynomial of the DomainMatrix. These elements will be domain elements. The domain of the elements will be same as domain of the DomainMatrix. Returns ======= list coefficients of the characteristic polynomial Raises ====== DMNonSquareMatrixError If the DomainMatrix is not a not Square DomainMatrix Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> A.charpoly() [1, -5, -2] """ m, n = self.shape if m != n: raise DMNonSquareMatrixError("not square") return self.rep.charpoly() @classmethod def eye(cls, shape, domain): r""" Return identity matrix of size n Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import QQ >>> DomainMatrix.eye(3, QQ) DomainMatrix({0: {0: 1}, 1: {1: 1}, 2: {2: 1}}, (3, 3), QQ) """ if isinstance(shape, int): shape = (shape, shape) return cls.from_rep(SDM.eye(shape, domain)) @classmethod def diag(cls, diagonal, domain, shape=None): r""" Return diagonal matrix with entries from ``diagonal``. Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import ZZ >>> DomainMatrix.diag([ZZ(5), ZZ(6)], ZZ) DomainMatrix({0: {0: 5}, 1: {1: 6}}, (2, 2), ZZ) """ if shape is None: N = len(diagonal) shape = (N, N) return cls.from_rep(SDM.diag(diagonal, domain, shape)) @classmethod def zeros(cls, shape, domain, *, fmt='sparse'): """Returns a zero DomainMatrix of size shape, belonging to the specified domain Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import QQ >>> DomainMatrix.zeros((2, 3), QQ) DomainMatrix({}, (2, 3), QQ) """ return cls.from_rep(SDM.zeros(shape, domain)) @classmethod def ones(cls, shape, domain): """Returns a DomainMatrix of 1s, of size shape, belonging to the specified domain Examples ======== >>> from sympy.polys.matrices import DomainMatrix >>> from sympy import QQ >>> DomainMatrix.ones((2,3), QQ) DomainMatrix([[1, 1, 1], [1, 1, 1]], (2, 3), QQ) """ return cls.from_rep(DDM.ones(shape, domain)) def __eq__(A, B): r""" Checks for two DomainMatrix matrices to be equal or not Parameters ========== A, B: DomainMatrix to check equality Returns ======= Boolean True for equal, else False Raises ====== NotImplementedError If B is not a DomainMatrix Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices import DomainMatrix >>> A = DomainMatrix([ ... [ZZ(1), ZZ(2)], ... [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> B = DomainMatrix([ ... [ZZ(1), ZZ(1)], ... [ZZ(0), ZZ(1)]], (2, 2), ZZ) >>> A.__eq__(A) True >>> A.__eq__(B) False """ if not isinstance(A, type(B)): return NotImplemented return A.domain == B.domain and A.rep == B.rep def unify_eq(A, B): if A.shape != B.shape: return False if A.domain != B.domain: A, B = A.unify(B) return A == B
7d3668e517d4bdd3ff3e149f5295b50674e614eea54edf63001194370825b5af
""" Module to define exceptions to be used in sympy.polys.matrices modules and classes. Ideally all exceptions raised in these modules would be defined and documented here and not e.g. imported from matrices. Also ideally generic exceptions like ValueError/TypeError would not be raised anywhere. """ class DMError(Exception): """Base class for errors raised by DomainMatrix""" pass class DMBadInputError(DMError): """list of lists is inconsistent with shape""" pass class DMDomainError(DMError): """domains do not match""" pass class DMNotAField(DMDomainError): """domain is not a field""" pass class DMFormatError(DMError): """mixed dense/sparse not supported""" pass class DMNonInvertibleMatrixError(DMError): """The matrix in not invertible""" pass class DMRankError(DMError): """matrix does not have expected rank""" pass class DMShapeError(DMError): """shapes are inconsistent""" pass class DMNonSquareMatrixError(DMShapeError): """The matrix is not square""" pass __all__ = [ 'DMError', 'DMBadInputError', 'DMDomainError', 'DMFormatError', 'DMRankError', 'DMShapeError', 'DMNotAField', 'DMNonInvertibleMatrixError', 'DMNonSquareMatrixError', ]
18effb8de988c375172f49b625346d6669d7ae7faae2ca218d5a2bcc287ef69f
""" Module for the SDM class. """ from operator import add, neg, pos, sub, mul from collections import defaultdict from sympy.utilities.iterables import _strongly_connected_components from .exceptions import DMBadInputError, DMDomainError, DMShapeError from .ddm import DDM class SDM(dict): r"""Sparse matrix based on polys domain elements This is a dict subclass and is a wrapper for a dict of dicts that supports basic matrix arithmetic +, -, *, **. In order to create a new :py:class:`~.SDM`, a dict of dicts mapping non-zero elements to their corresponding row and column in the matrix is needed. We also need to specify the shape and :py:class:`~.Domain` of our :py:class:`~.SDM` object. We declare a 2x2 :py:class:`~.SDM` matrix belonging to QQ domain as shown below. The 2x2 Matrix in the example is .. math:: A = \left[\begin{array}{ccc} 0 & \frac{1}{2} \\ 0 & 0 \end{array} \right] >>> from sympy.polys.matrices.sdm import SDM >>> from sympy import QQ >>> elemsdict = {0:{1:QQ(1, 2)}} >>> A = SDM(elemsdict, (2, 2), QQ) >>> A {0: {1: 1/2}} We can manipulate :py:class:`~.SDM` the same way as a Matrix class >>> from sympy import ZZ >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) >>> B = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ) >>> A + B {0: {0: 3, 1: 2}, 1: {0: 1, 1: 4}} Multiplication >>> A*B {0: {1: 8}, 1: {0: 3}} >>> A*ZZ(2) {0: {1: 4}, 1: {0: 2}} """ fmt = 'sparse' def __init__(self, elemsdict, shape, domain): super().__init__(elemsdict) self.shape = self.rows, self.cols = m, n = shape self.domain = domain if not all(0 <= r < m for r in self): raise DMBadInputError("Row out of range") if not all(0 <= c < n for row in self.values() for c in row): raise DMBadInputError("Column out of range") def getitem(self, i, j): try: return self[i][j] except KeyError: m, n = self.shape if -m <= i < m and -n <= j < n: try: return self[i % m][j % n] except KeyError: return self.domain.zero else: raise IndexError("index out of range") def setitem(self, i, j, value): m, n = self.shape if not (-m <= i < m and -n <= j < n): raise IndexError("index out of range") i, j = i % m, j % n if value: try: self[i][j] = value except KeyError: self[i] = {j: value} else: rowi = self.get(i, None) if rowi is not None: try: del rowi[j] except KeyError: pass else: if not rowi: del self[i] def extract_slice(self, slice1, slice2): m, n = self.shape ri = range(m)[slice1] ci = range(n)[slice2] sdm = {} for i, row in self.items(): if i in ri: row = {ci.index(j): e for j, e in row.items() if j in ci} if row: sdm[ri.index(i)] = row return self.new(sdm, (len(ri), len(ci)), self.domain) def extract(self, rows, cols): if not (self and rows and cols): return self.zeros((len(rows), len(cols)), self.domain) m, n = self.shape if not (-m <= min(rows) <= max(rows) < m): raise IndexError('Row index out of range') if not (-n <= min(cols) <= max(cols) < n): raise IndexError('Column index out of range') # rows and cols can contain duplicates e.g. M[[1, 2, 2], [0, 1]] # Build a map from row/col in self to list of rows/cols in output rowmap = defaultdict(list) colmap = defaultdict(list) for i2, i1 in enumerate(rows): rowmap[i1 % m].append(i2) for j2, j1 in enumerate(cols): colmap[j1 % n].append(j2) # Used to efficiently skip zero rows/cols rowset = set(rowmap) colset = set(colmap) sdm1 = self sdm2 = {} for i1 in rowset & set(sdm1): row1 = sdm1[i1] row2 = {} for j1 in colset & set(row1): row1_j1 = row1[j1] for j2 in colmap[j1]: row2[j2] = row1_j1 if row2: for i2 in rowmap[i1]: sdm2[i2] = row2.copy() return self.new(sdm2, (len(rows), len(cols)), self.domain) def __str__(self): rowsstr = [] for i, row in self.items(): elemsstr = ', '.join('%s: %s' % (j, elem) for j, elem in row.items()) rowsstr.append('%s: {%s}' % (i, elemsstr)) return '{%s}' % ', '.join(rowsstr) def __repr__(self): cls = type(self).__name__ rows = dict.__repr__(self) return '%s(%s, %s, %s)' % (cls, rows, self.shape, self.domain) @classmethod def new(cls, sdm, shape, domain): """ Parameters ========== sdm: A dict of dicts for non-zero elements in SDM shape: tuple representing dimension of SDM domain: Represents :py:class:`~.Domain` of SDM Returns ======= An :py:class:`~.SDM` object Examples ======== >>> from sympy.polys.matrices.sdm import SDM >>> from sympy import QQ >>> elemsdict = {0:{1: QQ(2)}} >>> A = SDM.new(elemsdict, (2, 2), QQ) >>> A {0: {1: 2}} """ return cls(sdm, shape, domain) def copy(A): """ Returns the copy of a :py:class:`~.SDM` object Examples ======== >>> from sympy.polys.matrices.sdm import SDM >>> from sympy import QQ >>> elemsdict = {0:{1:QQ(2)}, 1:{}} >>> A = SDM(elemsdict, (2, 2), QQ) >>> B = A.copy() >>> B {0: {1: 2}, 1: {}} """ Ac = {i: Ai.copy() for i, Ai in A.items()} return A.new(Ac, A.shape, A.domain) @classmethod def from_list(cls, ddm, shape, domain): """ Parameters ========== ddm: list of lists containing domain elements shape: Dimensions of :py:class:`~.SDM` matrix domain: Represents :py:class:`~.Domain` of :py:class:`~.SDM` object Returns ======= :py:class:`~.SDM` containing elements of ddm Examples ======== >>> from sympy.polys.matrices.sdm import SDM >>> from sympy import QQ >>> ddm = [[QQ(1, 2), QQ(0)], [QQ(0), QQ(3, 4)]] >>> A = SDM.from_list(ddm, (2, 2), QQ) >>> A {0: {0: 1/2}, 1: {1: 3/4}} """ m, n = shape if not (len(ddm) == m and all(len(row) == n for row in ddm)): raise DMBadInputError("Inconsistent row-list/shape") getrow = lambda i: {j:ddm[i][j] for j in range(n) if ddm[i][j]} irows = ((i, getrow(i)) for i in range(m)) sdm = {i: row for i, row in irows if row} return cls(sdm, shape, domain) @classmethod def from_ddm(cls, ddm): """ converts object of :py:class:`~.DDM` to :py:class:`~.SDM` Examples ======== >>> from sympy.polys.matrices.ddm import DDM >>> from sympy.polys.matrices.sdm import SDM >>> from sympy import QQ >>> ddm = DDM( [[QQ(1, 2), 0], [0, QQ(3, 4)]], (2, 2), QQ) >>> A = SDM.from_ddm(ddm) >>> A {0: {0: 1/2}, 1: {1: 3/4}} """ return cls.from_list(ddm, ddm.shape, ddm.domain) def to_list(M): """ Converts a :py:class:`~.SDM` object to a list Examples ======== >>> from sympy.polys.matrices.sdm import SDM >>> from sympy import QQ >>> elemsdict = {0:{1:QQ(2)}, 1:{}} >>> A = SDM(elemsdict, (2, 2), QQ) >>> A.to_list() [[0, 2], [0, 0]] """ m, n = M.shape zero = M.domain.zero ddm = [[zero] * n for _ in range(m)] for i, row in M.items(): for j, e in row.items(): ddm[i][j] = e return ddm def to_list_flat(M): m, n = M.shape zero = M.domain.zero flat = [zero] * (m * n) for i, row in M.items(): for j, e in row.items(): flat[i*n + j] = e return flat def to_dok(M): return {(i, j): e for i, row in M.items() for j, e in row.items()} def to_ddm(M): """ Convert a :py:class:`~.SDM` object to a :py:class:`~.DDM` object Examples ======== >>> from sympy.polys.matrices.sdm import SDM >>> from sympy import QQ >>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ) >>> A.to_ddm() [[0, 2], [0, 0]] """ return DDM(M.to_list(), M.shape, M.domain) def to_sdm(M): return M @classmethod def zeros(cls, shape, domain): r""" Returns a :py:class:`~.SDM` of size shape, belonging to the specified domain In the example below we declare a matrix A where, .. math:: A := \left[\begin{array}{ccc} 0 & 0 & 0 \\ 0 & 0 & 0 \end{array} \right] >>> from sympy.polys.matrices.sdm import SDM >>> from sympy import QQ >>> A = SDM.zeros((2, 3), QQ) >>> A {} """ return cls({}, shape, domain) @classmethod def ones(cls, shape, domain): one = domain.one m, n = shape row = dict(zip(range(n), [one]*n)) sdm = {i: row.copy() for i in range(m)} return cls(sdm, shape, domain) @classmethod def eye(cls, shape, domain): """ Returns a identity :py:class:`~.SDM` matrix of dimensions size x size, belonging to the specified domain Examples ======== >>> from sympy.polys.matrices.sdm import SDM >>> from sympy import QQ >>> I = SDM.eye((2, 2), QQ) >>> I {0: {0: 1}, 1: {1: 1}} """ rows, cols = shape one = domain.one sdm = {i: {i: one} for i in range(min(rows, cols))} return cls(sdm, shape, domain) @classmethod def diag(cls, diagonal, domain, shape): sdm = {i: {i: v} for i, v in enumerate(diagonal) if v} return cls(sdm, shape, domain) def transpose(M): """ Returns the transpose of a :py:class:`~.SDM` matrix Examples ======== >>> from sympy.polys.matrices.sdm import SDM >>> from sympy import QQ >>> A = SDM({0:{1:QQ(2)}, 1:{}}, (2, 2), QQ) >>> A.transpose() {1: {0: 2}} """ MT = sdm_transpose(M) return M.new(MT, M.shape[::-1], M.domain) def __add__(A, B): if not isinstance(B, SDM): return NotImplemented return A.add(B) def __sub__(A, B): if not isinstance(B, SDM): return NotImplemented return A.sub(B) def __neg__(A): return A.neg() def __mul__(A, B): """A * B""" if isinstance(B, SDM): return A.matmul(B) elif B in A.domain: return A.mul(B) else: return NotImplemented def __rmul__(a, b): if b in a.domain: return a.rmul(b) else: return NotImplemented def matmul(A, B): """ Performs matrix multiplication of two SDM matrices Parameters ========== A, B: SDM to multiply Returns ======= SDM SDM after multiplication Raises ====== DomainError If domain of A does not match with that of B Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) >>> B = SDM({0:{0:ZZ(2), 1:ZZ(3)}, 1:{0:ZZ(4)}}, (2, 2), ZZ) >>> A.matmul(B) {0: {0: 8}, 1: {0: 2, 1: 3}} """ if A.domain != B.domain: raise DMDomainError m, n = A.shape n2, o = B.shape if n != n2: raise DMShapeError C = sdm_matmul(A, B, A.domain, m, o) return A.new(C, (m, o), A.domain) def mul(A, b): """ Multiplies each element of A with a scalar b Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) >>> A.mul(ZZ(3)) {0: {1: 6}, 1: {0: 3}} """ Csdm = unop_dict(A, lambda aij: aij*b) return A.new(Csdm, A.shape, A.domain) def rmul(A, b): Csdm = unop_dict(A, lambda aij: b*aij) return A.new(Csdm, A.shape, A.domain) def mul_elementwise(A, B): if A.domain != B.domain: raise DMDomainError if A.shape != B.shape: raise DMShapeError zero = A.domain.zero fzero = lambda e: zero Csdm = binop_dict(A, B, mul, fzero, fzero) return A.new(Csdm, A.shape, A.domain) def add(A, B): """ Adds two :py:class:`~.SDM` matrices Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) >>> B = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ) >>> A.add(B) {0: {0: 3, 1: 2}, 1: {0: 1, 1: 4}} """ Csdm = binop_dict(A, B, add, pos, pos) return A.new(Csdm, A.shape, A.domain) def sub(A, B): """ Subtracts two :py:class:`~.SDM` matrices Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) >>> B = SDM({0:{0: ZZ(3)}, 1:{1:ZZ(4)}}, (2, 2), ZZ) >>> A.sub(B) {0: {0: -3, 1: 2}, 1: {0: 1, 1: -4}} """ Csdm = binop_dict(A, B, sub, pos, neg) return A.new(Csdm, A.shape, A.domain) def neg(A): """ Returns the negative of a :py:class:`~.SDM` matrix Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) >>> A.neg() {0: {1: -2}, 1: {0: -1}} """ Csdm = unop_dict(A, neg) return A.new(Csdm, A.shape, A.domain) def convert_to(A, K): """ Converts the :py:class:`~.Domain` of a :py:class:`~.SDM` matrix to K Examples ======== >>> from sympy import ZZ, QQ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0:{1: ZZ(2)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) >>> A.convert_to(QQ) {0: {1: 2}, 1: {0: 1}} """ Kold = A.domain if K == Kold: return A.copy() Ak = unop_dict(A, lambda e: K.convert_from(e, Kold)) return A.new(Ak, A.shape, K) def scc(A): """Strongly connected components of a square matrix *A*. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0:{0: ZZ(2)}, 1:{1:ZZ(1)}}, (2, 2), ZZ) >>> A.scc() [[0], [1]] See also ======== sympy.polys.matrices.domainmatrix.DomainMatrix.scc """ rows, cols = A.shape assert rows == cols V = range(rows) Emap = {v: list(A.get(v, [])) for v in V} return _strongly_connected_components(V, Emap) def rref(A): """ Returns reduced-row echelon form and list of pivots for the :py:class:`~.SDM` Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(2), 1:QQ(4)}}, (2, 2), QQ) >>> A.rref() ({0: {0: 1, 1: 2}}, [0]) """ B, pivots, _ = sdm_irref(A) return A.new(B, A.shape, A.domain), pivots def inv(A): """ Returns inverse of a matrix A Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) >>> A.inv() {0: {0: -2, 1: 1}, 1: {0: 3/2, 1: -1/2}} """ return A.from_ddm(A.to_ddm().inv()) def det(A): """ Returns determinant of A Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) >>> A.det() -2 """ return A.to_ddm().det() def lu(A): """ Returns LU decomposition for a matrix A Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) >>> A.lu() ({0: {0: 1}, 1: {0: 3, 1: 1}}, {0: {0: 1, 1: 2}, 1: {1: -2}}, []) """ L, U, swaps = A.to_ddm().lu() return A.from_ddm(L), A.from_ddm(U), swaps def lu_solve(A, b): """ Uses LU decomposition to solve Ax = b, Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) >>> b = SDM({0:{0:QQ(1)}, 1:{0:QQ(2)}}, (2, 1), QQ) >>> A.lu_solve(b) {1: {0: 1/2}} """ return A.from_ddm(A.to_ddm().lu_solve(b.to_ddm())) def nullspace(A): """ Returns nullspace for a :py:class:`~.SDM` matrix A Examples ======== >>> from sympy import QQ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0: QQ(2), 1: QQ(4)}}, (2, 2), QQ) >>> A.nullspace() ({0: {0: -2, 1: 1}}, [1]) """ ncols = A.shape[1] one = A.domain.one B, pivots, nzcols = sdm_irref(A) K, nonpivots = sdm_nullspace_from_rref(B, one, ncols, pivots, nzcols) K = dict(enumerate(K)) shape = (len(K), ncols) return A.new(K, shape, A.domain), nonpivots def particular(A): ncols = A.shape[1] B, pivots, nzcols = sdm_irref(A) P = sdm_particular_from_rref(B, ncols, pivots) rep = {0:P} if P else {} return A.new(rep, (1, ncols-1), A.domain) def hstack(A, *B): """Horizontally stacks :py:class:`~.SDM` matrices. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ) >>> B = SDM({0: {0: ZZ(5), 1: ZZ(6)}, 1: {0: ZZ(7), 1: ZZ(8)}}, (2, 2), ZZ) >>> A.hstack(B) {0: {0: 1, 1: 2, 2: 5, 3: 6}, 1: {0: 3, 1: 4, 2: 7, 3: 8}} >>> C = SDM({0: {0: ZZ(9), 1: ZZ(10)}, 1: {0: ZZ(11), 1: ZZ(12)}}, (2, 2), ZZ) >>> A.hstack(B, C) {0: {0: 1, 1: 2, 2: 5, 3: 6, 4: 9, 5: 10}, 1: {0: 3, 1: 4, 2: 7, 3: 8, 4: 11, 5: 12}} """ Anew = dict(A.copy()) rows, cols = A.shape domain = A.domain for Bk in B: Bkrows, Bkcols = Bk.shape assert Bkrows == rows assert Bk.domain == domain for i, Bki in Bk.items(): Ai = Anew.get(i, None) if Ai is None: Anew[i] = Ai = {} for j, Bkij in Bki.items(): Ai[j + cols] = Bkij cols += Bkcols return A.new(Anew, (rows, cols), A.domain) def vstack(A, *B): """Vertically stacks :py:class:`~.SDM` matrices. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices.sdm import SDM >>> A = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ) >>> B = SDM({0: {0: ZZ(5), 1: ZZ(6)}, 1: {0: ZZ(7), 1: ZZ(8)}}, (2, 2), ZZ) >>> A.vstack(B) {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}, 2: {0: 5, 1: 6}, 3: {0: 7, 1: 8}} >>> C = SDM({0: {0: ZZ(9), 1: ZZ(10)}, 1: {0: ZZ(11), 1: ZZ(12)}}, (2, 2), ZZ) >>> A.vstack(B, C) {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}, 2: {0: 5, 1: 6}, 3: {0: 7, 1: 8}, 4: {0: 9, 1: 10}, 5: {0: 11, 1: 12}} """ Anew = dict(A.copy()) rows, cols = A.shape domain = A.domain for Bk in B: Bkrows, Bkcols = Bk.shape assert Bkcols == cols assert Bk.domain == domain for i, Bki in Bk.items(): Anew[i + rows] = Bki rows += Bkrows return A.new(Anew, (rows, cols), A.domain) def applyfunc(self, func, domain): sdm = {i: {j: func(e) for j, e in row.items()} for i, row in self.items()} return self.new(sdm, self.shape, domain) def charpoly(A): """ Returns the coefficients of the characteristic polynomial of the :py:class:`~.SDM` matrix. These elements will be domain elements. The domain of the elements will be same as domain of the :py:class:`~.SDM`. Examples ======== >>> from sympy import QQ, Symbol >>> from sympy.polys.matrices.sdm import SDM >>> from sympy.polys import Poly >>> A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) >>> A.charpoly() [1, -5, -2] We can create a polynomial using the coefficients using :py:class:`~.Poly` >>> x = Symbol('x') >>> p = Poly(A.charpoly(), x, domain=A.domain) >>> p Poly(x**2 - 5*x - 2, x, domain='QQ') """ return A.to_ddm().charpoly() def is_zero_matrix(self): """ Says whether this matrix has all zero entries. """ return not self def is_upper(self): """ Says whether this matrix is upper-triangular. True can be returned even if the matrix is not square. """ return all(i <= j for i, row in self.items() for j in row) def is_lower(self): """ Says whether this matrix is lower-triangular. True can be returned even if the matrix is not square. """ return all(i >= j for i, row in self.items() for j in row) def binop_dict(A, B, fab, fa, fb): Anz, Bnz = set(A), set(B) C = {} for i in Anz & Bnz: Ai, Bi = A[i], B[i] Ci = {} Anzi, Bnzi = set(Ai), set(Bi) for j in Anzi & Bnzi: Cij = fab(Ai[j], Bi[j]) if Cij: Ci[j] = Cij for j in Anzi - Bnzi: Cij = fa(Ai[j]) if Cij: Ci[j] = Cij for j in Bnzi - Anzi: Cij = fb(Bi[j]) if Cij: Ci[j] = Cij if Ci: C[i] = Ci for i in Anz - Bnz: Ai = A[i] Ci = {} for j, Aij in Ai.items(): Cij = fa(Aij) if Cij: Ci[j] = Cij if Ci: C[i] = Ci for i in Bnz - Anz: Bi = B[i] Ci = {} for j, Bij in Bi.items(): Cij = fb(Bij) if Cij: Ci[j] = Cij if Ci: C[i] = Ci return C def unop_dict(A, f): B = {} for i, Ai in A.items(): Bi = {} for j, Aij in Ai.items(): Bij = f(Aij) if Bij: Bi[j] = Bij if Bi: B[i] = Bi return B def sdm_transpose(M): MT = {} for i, Mi in M.items(): for j, Mij in Mi.items(): try: MT[j][i] = Mij except KeyError: MT[j] = {i: Mij} return MT def sdm_matmul(A, B, K, m, o): # # Should be fast if A and B are very sparse. # Consider e.g. A = B = eye(1000). # # The idea here is that we compute C = A*B in terms of the rows of C and # B since the dict of dicts representation naturally stores the matrix as # rows. The ith row of C (Ci) is equal to the sum of Aik * Bk where Bk is # the kth row of B. The algorithm below loops over each nonzero element # Aik of A and if the corresponding row Bj is nonzero then we do # Ci += Aik * Bk. # To make this more efficient we don't need to loop over all elements Aik. # Instead for each row Ai we compute the intersection of the nonzero # columns in Ai with the nonzero rows in B. That gives the k such that # Aik and Bk are both nonzero. In Python the intersection of two sets # of int can be computed very efficiently. # if K.is_EXRAW: return sdm_matmul_exraw(A, B, K, m, o) C = {} B_knz = set(B) for i, Ai in A.items(): Ci = {} Ai_knz = set(Ai) for k in Ai_knz & B_knz: Aik = Ai[k] for j, Bkj in B[k].items(): Cij = Ci.get(j, None) if Cij is not None: Cij = Cij + Aik * Bkj if Cij: Ci[j] = Cij else: Ci.pop(j) else: Cij = Aik * Bkj if Cij: Ci[j] = Cij if Ci: C[i] = Ci return C def sdm_matmul_exraw(A, B, K, m, o): # # Like sdm_matmul above except that: # # - Handles cases like 0*oo -> nan (sdm_matmul skips multipication by zero) # - Uses K.sum (Add(*items)) for efficient addition of Expr # zero = K.zero C = {} B_knz = set(B) for i, Ai in A.items(): Ci_list = defaultdict(list) Ai_knz = set(Ai) # Nonzero row/column pair for k in Ai_knz & B_knz: Aik = Ai[k] if zero * Aik == zero: # This is the main inner loop: for j, Bkj in B[k].items(): Ci_list[j].append(Aik * Bkj) else: for j in range(o): Ci_list[j].append(Aik * B[k].get(j, zero)) # Zero row in B, check for infinities in A for k in Ai_knz - B_knz: zAik = zero * Ai[k] if zAik != zero: for j in range(o): Ci_list[j].append(zAik) # Add terms using K.sum (Add(*terms)) for efficiency Ci = {} for j, Cij_list in Ci_list.items(): Cij = K.sum(Cij_list) if Cij: Ci[j] = Cij if Ci: C[i] = Ci # Find all infinities in B for k, Bk in B.items(): for j, Bkj in Bk.items(): if zero * Bkj != zero: for i in range(m): Aik = A.get(i, {}).get(k, zero) # If Aik is not zero then this was handled above if Aik == zero: Ci = C.get(i, {}) Cij = Ci.get(j, zero) + Aik * Bkj if Cij != zero: Ci[j] = Cij else: # pragma: no cover # Not sure how we could get here but let's raise an # exception just in case. raise RuntimeError C[i] = Ci return C def sdm_irref(A): """RREF and pivots of a sparse matrix *A*. Compute the reduced row echelon form (RREF) of the matrix *A* and return a list of the pivot columns. This routine does not work in place and leaves the original matrix *A* unmodified. Examples ======== This routine works with a dict of dicts sparse representation of a matrix: >>> from sympy import QQ >>> from sympy.polys.matrices.sdm import sdm_irref >>> A = {0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}} >>> Arref, pivots, _ = sdm_irref(A) >>> Arref {0: {0: 1}, 1: {1: 1}} >>> pivots [0, 1] The analogous calculation with :py:class:`~.Matrix` would be >>> from sympy import Matrix >>> M = Matrix([[1, 2], [3, 4]]) >>> Mrref, pivots = M.rref() >>> Mrref Matrix([ [1, 0], [0, 1]]) >>> pivots (0, 1) Notes ===== The cost of this algorithm is determined purely by the nonzero elements of the matrix. No part of the cost of any step in this algorithm depends on the number of rows or columns in the matrix. No step depends even on the number of nonzero rows apart from the primary loop over those rows. The implementation is much faster than ddm_rref for sparse matrices. In fact at the time of writing it is also (slightly) faster than the dense implementation even if the input is a fully dense matrix so it seems to be faster in all cases. The elements of the matrix should support exact division with ``/``. For example elements of any domain that is a field (e.g. ``QQ``) should be fine. No attempt is made to handle inexact arithmetic. """ # # Any zeros in the matrix are not stored at all so an element is zero if # its row dict has no index at that key. A row is entirely zero if its # row index is not in the outer dict. Since rref reorders the rows and # removes zero rows we can completely discard the row indices. The first # step then copies the row dicts into a list sorted by the index of the # first nonzero column in each row. # # The algorithm then processes each row Ai one at a time. Previously seen # rows are used to cancel their pivot columns from Ai. Then a pivot from # Ai is chosen and is cancelled from all previously seen rows. At this # point Ai joins the previously seen rows. Once all rows are seen all # elimination has occurred and the rows are sorted by pivot column index. # # The previously seen rows are stored in two separate groups. The reduced # group consists of all rows that have been reduced to a single nonzero # element (the pivot). There is no need to attempt any further reduction # with these. Rows that still have other nonzeros need to be considered # when Ai is cancelled from the previously seen rows. # # A dict nonzerocolumns is used to map from a column index to a set of # previously seen rows that still have a nonzero element in that column. # This means that we can cancel the pivot from Ai into the previously seen # rows without needing to loop over each row that might have a zero in # that column. # # Row dicts sorted by index of first nonzero column # (Maybe sorting is not needed/useful.) Arows = sorted((Ai.copy() for Ai in A.values()), key=min) # Each processed row has an associated pivot column. # pivot_row_map maps from the pivot column index to the row dict. # This means that we can represent a set of rows purely as a set of their # pivot indices. pivot_row_map = {} # Set of pivot indices for rows that are fully reduced to a single nonzero. reduced_pivots = set() # Set of pivot indices for rows not fully reduced nonreduced_pivots = set() # Map from column index to a set of pivot indices representing the rows # that have a nonzero at that column. nonzero_columns = defaultdict(set) while Arows: # Select pivot element and row Ai = Arows.pop() # Nonzero columns from fully reduced pivot rows can be removed Ai = {j: Aij for j, Aij in Ai.items() if j not in reduced_pivots} # Others require full row cancellation for j in nonreduced_pivots & set(Ai): Aj = pivot_row_map[j] Aij = Ai[j] Ainz = set(Ai) Ajnz = set(Aj) for k in Ajnz - Ainz: Ai[k] = - Aij * Aj[k] Ai.pop(j) Ainz.remove(j) for k in Ajnz & Ainz: Aik = Ai[k] - Aij * Aj[k] if Aik: Ai[k] = Aik else: Ai.pop(k) # We have now cancelled previously seen pivots from Ai. # If it is zero then discard it. if not Ai: continue # Choose a pivot from Ai: j = min(Ai) Aij = Ai[j] pivot_row_map[j] = Ai Ainz = set(Ai) # Normalise the pivot row to make the pivot 1. # # This approach is slow for some domains. Cross cancellation might be # better for e.g. QQ(x) with division delayed to the final steps. Aijinv = Aij**-1 for l in Ai: Ai[l] *= Aijinv # Use Aij to cancel column j from all previously seen rows for k in nonzero_columns.pop(j, ()): Ak = pivot_row_map[k] Akj = Ak[j] Aknz = set(Ak) for l in Ainz - Aknz: Ak[l] = - Akj * Ai[l] nonzero_columns[l].add(k) Ak.pop(j) Aknz.remove(j) for l in Ainz & Aknz: Akl = Ak[l] - Akj * Ai[l] if Akl: Ak[l] = Akl else: # Drop nonzero elements Ak.pop(l) if l != j: nonzero_columns[l].remove(k) if len(Ak) == 1: reduced_pivots.add(k) nonreduced_pivots.remove(k) if len(Ai) == 1: reduced_pivots.add(j) else: nonreduced_pivots.add(j) for l in Ai: if l != j: nonzero_columns[l].add(j) # All done! pivots = sorted(reduced_pivots | nonreduced_pivots) pivot2row = {p: n for n, p in enumerate(pivots)} nonzero_columns = {c: set(pivot2row[p] for p in s) for c, s in nonzero_columns.items()} rows = [pivot_row_map[i] for i in pivots] rref = dict(enumerate(rows)) return rref, pivots, nonzero_columns def sdm_nullspace_from_rref(A, one, ncols, pivots, nonzero_cols): """Get nullspace from A which is in RREF""" nonpivots = sorted(set(range(ncols)) - set(pivots)) K = [] for j in nonpivots: Kj = {j:one} for i in nonzero_cols.get(j, ()): Kj[pivots[i]] = -A[i][j] K.append(Kj) return K, nonpivots def sdm_particular_from_rref(A, ncols, pivots): """Get a particular solution from A which is in RREF""" P = {} for i, j in enumerate(pivots): Ain = A[i].get(ncols-1, None) if Ain is not None: P[j] = Ain / A[i][j] return P
bc60a28810f8bf158f9a54f533167a56aac11fe5962940a99192b5e445fc3222
""" Module for the ddm_* routines for operating on a matrix in list of lists matrix representation. These routines are used internally by the DDM class which also provides a friendlier interface for them. The idea here is to implement core matrix routines in a way that can be applied to any simple list representation without the need to use any particular matrix class. For example we can compute the RREF of a matrix like: >>> from sympy.polys.matrices.dense import ddm_irref >>> M = [[1, 2, 3], [4, 5, 6]] >>> pivots = ddm_irref(M) >>> M [[1.0, 0.0, -1.0], [0, 1.0, 2.0]] These are lower-level routines that work mostly in place.The routines at this level should not need to know what the domain of the elements is but should ideally document what operations they will use and what functions they need to be provided with. The next-level up is the DDM class which uses these routines but wraps them up with an interface that handles copying etc and keeps track of the Domain of the elements of the matrix: >>> from sympy.polys.domains import QQ >>> from sympy.polys.matrices.ddm import DDM >>> M = DDM([[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]], (2, 3), QQ) >>> M [[1, 2, 3], [4, 5, 6]] >>> Mrref, pivots = M.rref() >>> Mrref [[1, 0, -1], [0, 1, 2]] """ from operator import mul from .exceptions import ( DMShapeError, DMNonInvertibleMatrixError, DMNonSquareMatrixError, ) def ddm_transpose(a): """matrix transpose""" aT = list(map(list, zip(*a))) return aT def ddm_iadd(a, b): """a += b""" for ai, bi in zip(a, b): for j, bij in enumerate(bi): ai[j] += bij def ddm_isub(a, b): """a -= b""" for ai, bi in zip(a, b): for j, bij in enumerate(bi): ai[j] -= bij def ddm_ineg(a): """a <-- -a""" for ai in a: for j, aij in enumerate(ai): ai[j] = -aij def ddm_imul(a, b): for ai in a: for j, aij in enumerate(ai): ai[j] = aij * b def ddm_irmul(a, b): for ai in a: for j, aij in enumerate(ai): ai[j] = b * aij def ddm_imatmul(a, b, c): """a += b @ c""" cT = list(zip(*c)) for bi, ai in zip(b, a): for j, cTj in enumerate(cT): ai[j] = sum(map(mul, bi, cTj), ai[j]) def ddm_irref(a, _partial_pivot=False): """a <-- rref(a)""" # a is (m x n) m = len(a) if not m: return [] n = len(a[0]) i = 0 pivots = [] for j in range(n): # Proper pivoting should be used for all domains for performance # reasons but it is only strictly needed for RR and CC (and possibly # other domains like RR(x)). This path is used by DDM.rref() if the # domain is RR or CC. It uses partial (row) pivoting based on the # absolute value of the pivot candidates. if _partial_pivot: ip = max(range(i, m), key=lambda ip: abs(a[ip][j])) a[i], a[ip] = a[ip], a[i] # pivot aij = a[i][j] # zero-pivot if not aij: for ip in range(i+1, m): aij = a[ip][j] # row-swap if aij: a[i], a[ip] = a[ip], a[i] break else: # next column continue # normalise row ai = a[i] aijinv = aij**-1 for l in range(j, n): ai[l] *= aijinv # ai[j] = one # eliminate above and below to the right for k, ak in enumerate(a): if k == i or not ak[j]: continue akj = ak[j] ak[j] -= akj # ak[j] = zero for l in range(j+1, n): ak[l] -= akj * ai[l] # next row pivots.append(j) i += 1 # no more rows? if i >= m: break return pivots def ddm_idet(a, K): """a <-- echelon(a); return det""" # Bareiss algorithm # https://www.math.usm.edu/perry/Research/Thesis_DRL.pdf # a is (m x n) m = len(a) if not m: return K.one n = len(a[0]) exquo = K.exquo # uf keeps track of the sign change from row swaps uf = K.one for k in range(n-1): if not a[k][k]: for i in range(k+1, n): if a[i][k]: a[k], a[i] = a[i], a[k] uf = -uf break else: return K.zero akkm1 = a[k-1][k-1] if k else K.one for i in range(k+1, n): for j in range(k+1, n): a[i][j] = exquo(a[i][j]*a[k][k] - a[i][k]*a[k][j], akkm1) return uf * a[-1][-1] def ddm_iinv(ainv, a, K): if not K.is_Field: raise ValueError('Not a field') # a is (m x n) m = len(a) if not m: return n = len(a[0]) if m != n: raise DMNonSquareMatrixError eye = [[K.one if i==j else K.zero for j in range(n)] for i in range(n)] Aaug = [row + eyerow for row, eyerow in zip(a, eye)] pivots = ddm_irref(Aaug) if pivots != list(range(n)): raise DMNonInvertibleMatrixError('Matrix det == 0; not invertible.') ainv[:] = [row[n:] for row in Aaug] def ddm_ilu_split(L, U, K): """L, U <-- LU(U)""" m = len(U) if not m: return [] n = len(U[0]) swaps = ddm_ilu(U) zeros = [K.zero] * min(m, n) for i in range(1, m): j = min(i, n) L[i][:j] = U[i][:j] U[i][:j] = zeros[:j] return swaps def ddm_ilu(a): """a <-- LU(a)""" m = len(a) if not m: return [] n = len(a[0]) swaps = [] for i in range(min(m, n)): if not a[i][i]: for ip in range(i+1, m): if a[ip][i]: swaps.append((i, ip)) a[i], a[ip] = a[ip], a[i] break else: # M = Matrix([[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]]) continue for j in range(i+1, m): l_ji = a[j][i] / a[i][i] a[j][i] = l_ji for k in range(i+1, n): a[j][k] -= l_ji * a[i][k] return swaps def ddm_ilu_solve(x, L, U, swaps, b): """x <-- solve(L*U*x = swaps(b))""" m = len(U) if not m: return n = len(U[0]) m2 = len(b) if not m2: raise DMShapeError("Shape mismtch") o = len(b[0]) if m != m2: raise DMShapeError("Shape mismtch") if m < n: raise NotImplementedError("Underdetermined") if swaps: b = [row[:] for row in b] for i1, i2 in swaps: b[i1], b[i2] = b[i2], b[i1] # solve Ly = b y = [[None] * o for _ in range(m)] for k in range(o): for i in range(m): rhs = b[i][k] for j in range(i): rhs -= L[i][j] * y[j][k] y[i][k] = rhs if m > n: for i in range(n, m): for j in range(o): if y[i][j]: raise DMNonInvertibleMatrixError # Solve Ux = y for k in range(o): for i in reversed(range(n)): if not U[i][i]: raise DMNonInvertibleMatrixError rhs = y[i][k] for j in range(i+1, n): rhs -= U[i][j] * x[j][k] x[i][k] = rhs / U[i][i] def ddm_berk(M, K): m = len(M) if not m: return [[K.one]] n = len(M[0]) if m != n: raise DMShapeError("Not square") if n == 1: return [[K.one], [-M[0][0]]] a = M[0][0] R = [M[0][1:]] C = [[row[0]] for row in M[1:]] A = [row[1:] for row in M[1:]] q = ddm_berk(A, K) T = [[K.zero] * n for _ in range(n+1)] for i in range(n): T[i][i] = K.one T[i+1][i] = -a for i in range(2, n+1): if i == 2: AnC = C else: C = AnC AnC = [[K.zero] for row in C] ddm_imatmul(AnC, A, C) RAnC = [[K.zero]] ddm_imatmul(RAnC, R, AnC) for j in range(0, n+1-i): T[i+j][j] = -RAnC[0][0] qout = [[K.zero] for _ in range(n+1)] ddm_imatmul(qout, T, q) return qout
a9018cf62b23c6066311f0808219d6b2275b13a4d672dbb556a80b6b3a070742
""" Module for the DDM class. The DDM class is an internal representation used by DomainMatrix. The letters DDM stand for Dense Domain Matrix. A DDM instance represents a matrix using elements from a polynomial Domain (e.g. ZZ, QQ, ...) in a dense-matrix representation. Basic usage: >>> from sympy import ZZ, QQ >>> from sympy.polys.matrices.ddm import DDM >>> A = DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ) >>> A.shape (2, 2) >>> A [[0, 1], [-1, 0]] >>> type(A) <class 'sympy.polys.matrices.ddm.DDM'> >>> A @ A [[-1, 0], [0, -1]] The ddm_* functions are designed to operate on DDM as well as on an ordinary list of lists: >>> from sympy.polys.matrices.dense import ddm_idet >>> ddm_idet(A, QQ) 1 >>> ddm_idet([[0, 1], [-1, 0]], QQ) 1 >>> A [[-1, 0], [0, -1]] Note that ddm_idet modifies the input matrix in-place. It is recommended to use the DDM.det method as a friendlier interface to this instead which takes care of copying the matrix: >>> B = DDM([[ZZ(0), ZZ(1)], [ZZ(-1), ZZ(0)]], (2, 2), ZZ) >>> B.det() 1 Normally DDM would not be used directly and is just part of the internal representation of DomainMatrix which adds further functionality including e.g. unifying domains. The dense format used by DDM is a list of lists of elements e.g. the 2x2 identity matrix is like [[1, 0], [0, 1]]. The DDM class itself is a subclass of list and its list items are plain lists. Elements are accessed as e.g. ddm[i][j] where ddm[i] gives the ith row and ddm[i][j] gets the element in the jth column of that row. Subclassing list makes e.g. iteration and indexing very efficient. We do not override __getitem__ because it would lose that benefit. The core routines are implemented by the ddm_* functions defined in dense.py. Those functions are intended to be able to operate on a raw list-of-lists representation of matrices with most functions operating in-place. The DDM class takes care of copying etc and also stores a Domain object associated with its elements. This makes it possible to implement things like A + B with domain checking and also shape checking so that the list of lists representation is friendlier. """ from itertools import chain from .exceptions import DMBadInputError, DMShapeError, DMDomainError from .dense import ( ddm_transpose, ddm_iadd, ddm_isub, ddm_ineg, ddm_imul, ddm_irmul, ddm_imatmul, ddm_irref, ddm_idet, ddm_iinv, ddm_ilu_split, ddm_ilu_solve, ddm_berk, ) class DDM(list): """Dense matrix based on polys domain elements This is a list subclass and is a wrapper for a list of lists that supports basic matrix arithmetic +, -, *, **. """ fmt = 'dense' def __init__(self, rowslist, shape, domain): super().__init__(rowslist) self.shape = self.rows, self.cols = m, n = shape self.domain = domain if not (len(self) == m and all(len(row) == n for row in self)): raise DMBadInputError("Inconsistent row-list/shape") def getitem(self, i, j): return self[i][j] def setitem(self, i, j, value): self[i][j] = value def extract_slice(self, slice1, slice2): ddm = [row[slice2] for row in self[slice1]] rows = len(ddm) cols = len(ddm[0]) if ddm else len(range(self.shape[1])[slice2]) return DDM(ddm, (rows, cols), self.domain) def extract(self, rows, cols): ddm = [] for i in rows: rowi = self[i] ddm.append([rowi[j] for j in cols]) return DDM(ddm, (len(rows), len(cols)), self.domain) def to_list(self): return list(self) def to_list_flat(self): flat = [] for row in self: flat.extend(row) return flat def flatiter(self): return chain.from_iterable(self) def flat(self): items = [] for row in self: items.extend(row) return items def to_dok(self): return {(i, j): e for i, row in enumerate(self) for j, e in enumerate(row)} def to_ddm(self): return self def to_sdm(self): return SDM.from_list(self, self.shape, self.domain) def convert_to(self, K): Kold = self.domain if K == Kold: return self.copy() rows = ([K.convert_from(e, Kold) for e in row] for row in self) return DDM(rows, self.shape, K) def __str__(self): rowsstr = ['[%s]' % ', '.join(map(str, row)) for row in self] return '[%s]' % ', '.join(rowsstr) def __repr__(self): cls = type(self).__name__ rows = list.__repr__(self) return '%s(%s, %s, %s)' % (cls, rows, self.shape, self.domain) def __eq__(self, other): if not isinstance(other, DDM): return False return (super().__eq__(other) and self.domain == other.domain) def __ne__(self, other): return not self.__eq__(other) @classmethod def zeros(cls, shape, domain): z = domain.zero m, n = shape rowslist = ([z] * n for _ in range(m)) return DDM(rowslist, shape, domain) @classmethod def ones(cls, shape, domain): one = domain.one m, n = shape rowlist = ([one] * n for _ in range(m)) return DDM(rowlist, shape, domain) @classmethod def eye(cls, size, domain): one = domain.one ddm = cls.zeros((size, size), domain) for i in range(size): ddm[i][i] = one return ddm def copy(self): copyrows = (row[:] for row in self) return DDM(copyrows, self.shape, self.domain) def transpose(self): rows, cols = self.shape if rows: ddmT = ddm_transpose(self) else: ddmT = [[]] * cols return DDM(ddmT, (cols, rows), self.domain) def __add__(a, b): if not isinstance(b, DDM): return NotImplemented return a.add(b) def __sub__(a, b): if not isinstance(b, DDM): return NotImplemented return a.sub(b) def __neg__(a): return a.neg() def __mul__(a, b): if b in a.domain: return a.mul(b) else: return NotImplemented def __rmul__(a, b): if b in a.domain: return a.mul(b) else: return NotImplemented def __matmul__(a, b): if isinstance(b, DDM): return a.matmul(b) else: return NotImplemented @classmethod def _check(cls, a, op, b, ashape, bshape): if a.domain != b.domain: msg = "Domain mismatch: %s %s %s" % (a.domain, op, b.domain) raise DMDomainError(msg) if ashape != bshape: msg = "Shape mismatch: %s %s %s" % (a.shape, op, b.shape) raise DMShapeError(msg) def add(a, b): """a + b""" a._check(a, '+', b, a.shape, b.shape) c = a.copy() ddm_iadd(c, b) return c def sub(a, b): """a - b""" a._check(a, '-', b, a.shape, b.shape) c = a.copy() ddm_isub(c, b) return c def neg(a): """-a""" b = a.copy() ddm_ineg(b) return b def mul(a, b): c = a.copy() ddm_imul(c, b) return c def rmul(a, b): c = a.copy() ddm_irmul(c, b) return c def matmul(a, b): """a @ b (matrix product)""" m, o = a.shape o2, n = b.shape a._check(a, '*', b, o, o2) c = a.zeros((m, n), a.domain) ddm_imatmul(c, a, b) return c def mul_elementwise(a, b): assert a.shape == b.shape assert a.domain == b.domain c = [[aij * bij for aij, bij in zip(ai, bi)] for ai, bi in zip(a, b)] return DDM(c, a.shape, a.domain) def hstack(A, *B): """Horizontally stacks :py:class:`~.DDM` matrices. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices.sdm import DDM >>> A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> B = DDM([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ) >>> A.hstack(B) [[1, 2, 5, 6], [3, 4, 7, 8]] >>> C = DDM([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ) >>> A.hstack(B, C) [[1, 2, 5, 6, 9, 10], [3, 4, 7, 8, 11, 12]] """ Anew = list(A.copy()) rows, cols = A.shape domain = A.domain for Bk in B: Bkrows, Bkcols = Bk.shape assert Bkrows == rows assert Bk.domain == domain cols += Bkcols for i, Bki in enumerate(Bk): Anew[i].extend(Bki) return DDM(Anew, (rows, cols), A.domain) def vstack(A, *B): """Vertically stacks :py:class:`~.DDM` matrices. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices.sdm import DDM >>> A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) >>> B = DDM([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ) >>> A.vstack(B) [[1, 2], [3, 4], [5, 6], [7, 8]] >>> C = DDM([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ) >>> A.vstack(B, C) [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]] """ Anew = list(A.copy()) rows, cols = A.shape domain = A.domain for Bk in B: Bkrows, Bkcols = Bk.shape assert Bkcols == cols assert Bk.domain == domain rows += Bkrows Anew.extend(Bk.copy()) return DDM(Anew, (rows, cols), A.domain) def applyfunc(self, func, domain): elements = (list(map(func, row)) for row in self) return DDM(elements, self.shape, domain) def scc(a): """Strongly connected components of a square matrix *a*. Examples ======== >>> from sympy import ZZ >>> from sympy.polys.matrices.sdm import DDM >>> A = DDM([[ZZ(1), ZZ(0)], [ZZ(0), ZZ(1)]], (2, 2), ZZ) >>> A.scc() [[0], [1]] See also ======== sympy.polys.matrices.domainmatrix.DomainMatrix.scc """ return a.to_sdm().scc() def rref(a): """Reduced-row echelon form of a and list of pivots""" b = a.copy() K = a.domain partial_pivot = K.is_RealField or K.is_ComplexField pivots = ddm_irref(b, _partial_pivot=partial_pivot) return b, pivots def nullspace(a): rref, pivots = a.rref() rows, cols = a.shape domain = a.domain basis = [] nonpivots = [] for i in range(cols): if i in pivots: continue nonpivots.append(i) vec = [domain.one if i == j else domain.zero for j in range(cols)] for ii, jj in enumerate(pivots): vec[jj] -= rref[ii][i] basis.append(vec) return DDM(basis, (len(basis), cols), domain), nonpivots def particular(a): return a.to_sdm().particular().to_ddm() def det(a): """Determinant of a""" m, n = a.shape if m != n: raise DMShapeError("Determinant of non-square matrix") b = a.copy() K = b.domain deta = ddm_idet(b, K) return deta def inv(a): """Inverse of a""" m, n = a.shape if m != n: raise DMShapeError("Determinant of non-square matrix") ainv = a.copy() K = a.domain ddm_iinv(ainv, a, K) return ainv def lu(a): """L, U decomposition of a""" m, n = a.shape K = a.domain U = a.copy() L = a.eye(m, K) swaps = ddm_ilu_split(L, U, K) return L, U, swaps def lu_solve(a, b): """x where a*x = b""" m, n = a.shape m2, o = b.shape a._check(a, 'lu_solve', b, m, m2) L, U, swaps = a.lu() x = a.zeros((n, o), a.domain) ddm_ilu_solve(x, L, U, swaps, b) return x def charpoly(a): """Coefficients of characteristic polynomial of a""" K = a.domain m, n = a.shape if m != n: raise DMShapeError("Charpoly of non-square matrix") vec = ddm_berk(a, K) coeffs = [vec[i][0] for i in range(n+1)] return coeffs def is_zero_matrix(self): """ Says whether this matrix has all zero entries. """ zero = self.domain.zero return all(Mij == zero for Mij in self.flatiter()) def is_upper(self): """ Says whether this matrix is upper-triangular. True can be returned even if the matrix is not square. """ zero = self.domain.zero return all(Mij == zero for i, Mi in enumerate(self) for Mij in Mi[:i]) def is_lower(self): """ Says whether this matrix is lower-triangular. True can be returned even if the matrix is not square. """ zero = self.domain.zero return all(Mij == zero for i, Mi in enumerate(self) for Mij in Mi[i+1:]) from .sdm import SDM
058a2ad42a88efa4434a6d3141da75bfb0efd67e6c75c99eb3e6ffcbf01f5bed
"""Tests for quotient rings.""" from sympy.polys.domains.integerring import ZZ from sympy.polys.domains.rationalfield import QQ from sympy.abc import x, y from sympy.polys.polyerrors import NotReversible from sympy.testing.pytest import raises def test_QuotientRingElement(): R = QQ.old_poly_ring(x)/[x**10] X = R.convert(x) assert X*(X + 1) == R.convert(x**2 + x) assert X*x == R.convert(x**2) assert x*X == R.convert(x**2) assert X + x == R.convert(2*x) assert x + X == 2*X assert X**2 == R.convert(x**2) assert 1/(1 - X) == R.convert(sum(x**i for i in range(10))) assert X**10 == R.zero assert X != x raises(NotReversible, lambda: 1/X) def test_QuotientRing(): I = QQ.old_poly_ring(x).ideal(x**2 + 1) R = QQ.old_poly_ring(x)/I assert R == QQ.old_poly_ring(x)/[x**2 + 1] assert R == QQ.old_poly_ring(x)/QQ.old_poly_ring(x).ideal(x**2 + 1) assert R != QQ.old_poly_ring(x) assert R.convert(1)/x == -x + I assert -1 + I == x**2 + I assert R.convert(ZZ(1), ZZ) == 1 + I assert R.convert(R.convert(x), R) == R.convert(x) X = R.convert(x) Y = QQ.old_poly_ring(x).convert(x) assert -1 + I == X**2 + I assert -1 + I == Y**2 + I assert R.to_sympy(X) == x raises(ValueError, lambda: QQ.old_poly_ring(x)/QQ.old_poly_ring(x, y).ideal(x)) R = QQ.old_poly_ring(x, order="ilex") I = R.ideal(x) assert R.convert(1) + I == (R/I).convert(1)
ad1fc928c575ff4feb7005a75d99bdb1a3ba65c0cb87e4e172dc49e643367faf
"""Tests for classes defining properties of ground domains, e.g. ZZ, QQ, ZZ[x] ... """ from sympy.core.numbers import (E, Float, I, Integer, Rational, oo, pi) from sympy.core.singleton import S from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin from sympy.polys.polytools import Poly from sympy.abc import x, y, z from sympy.external.gmpy import HAS_GMPY from sympy.polys.domains import (ZZ, QQ, RR, CC, FF, GF, EX, EXRAW, ZZ_gmpy, ZZ_python, QQ_gmpy, QQ_python) from sympy.polys.domains.algebraicfield import AlgebraicField from sympy.polys.domains.gaussiandomains import ZZ_I, QQ_I from sympy.polys.domains.polynomialring import PolynomialRing from sympy.polys.domains.realfield import RealField from sympy.polys.rings import ring from sympy.polys.fields import field from sympy.polys.agca.extensions import FiniteExtension from sympy.polys.polyerrors import ( UnificationFailed, GeneratorsError, CoercionFailed, NotInvertible, DomainError) from sympy.polys.polyutils import illegal from sympy.testing.pytest import raises from itertools import product ALG = QQ.algebraic_field(sqrt(2), sqrt(3)) def unify(K0, K1): return K0.unify(K1) def test_Domain_unify(): F3 = GF(3) assert unify(F3, F3) == F3 assert unify(F3, ZZ) == ZZ assert unify(F3, QQ) == QQ assert unify(F3, ALG) == ALG assert unify(F3, RR) == RR assert unify(F3, CC) == CC assert unify(F3, ZZ[x]) == ZZ[x] assert unify(F3, ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(F3, EX) == EX assert unify(ZZ, F3) == ZZ assert unify(ZZ, ZZ) == ZZ assert unify(ZZ, QQ) == QQ assert unify(ZZ, ALG) == ALG assert unify(ZZ, RR) == RR assert unify(ZZ, CC) == CC assert unify(ZZ, ZZ[x]) == ZZ[x] assert unify(ZZ, ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ, EX) == EX assert unify(QQ, F3) == QQ assert unify(QQ, ZZ) == QQ assert unify(QQ, QQ) == QQ assert unify(QQ, ALG) == ALG assert unify(QQ, RR) == RR assert unify(QQ, CC) == CC assert unify(QQ, ZZ[x]) == QQ[x] assert unify(QQ, ZZ.frac_field(x)) == QQ.frac_field(x) assert unify(QQ, EX) == EX assert unify(ZZ_I, F3) == ZZ_I assert unify(ZZ_I, ZZ) == ZZ_I assert unify(ZZ_I, ZZ_I) == ZZ_I assert unify(ZZ_I, QQ) == QQ_I assert unify(ZZ_I, ALG) == QQ.algebraic_field(I, sqrt(2), sqrt(3)) assert unify(ZZ_I, RR) == CC assert unify(ZZ_I, CC) == CC assert unify(ZZ_I, ZZ[x]) == ZZ_I[x] assert unify(ZZ_I, ZZ_I[x]) == ZZ_I[x] assert unify(ZZ_I, ZZ.frac_field(x)) == ZZ_I.frac_field(x) assert unify(ZZ_I, ZZ_I.frac_field(x)) == ZZ_I.frac_field(x) assert unify(ZZ_I, EX) == EX assert unify(QQ_I, F3) == QQ_I assert unify(QQ_I, ZZ) == QQ_I assert unify(QQ_I, ZZ_I) == QQ_I assert unify(QQ_I, QQ) == QQ_I assert unify(QQ_I, ALG) == QQ.algebraic_field(I, sqrt(2), sqrt(3)) assert unify(QQ_I, RR) == CC assert unify(QQ_I, CC) == CC assert unify(QQ_I, ZZ[x]) == QQ_I[x] assert unify(QQ_I, ZZ_I[x]) == QQ_I[x] assert unify(QQ_I, QQ[x]) == QQ_I[x] assert unify(QQ_I, QQ_I[x]) == QQ_I[x] assert unify(QQ_I, ZZ.frac_field(x)) == QQ_I.frac_field(x) assert unify(QQ_I, ZZ_I.frac_field(x)) == QQ_I.frac_field(x) assert unify(QQ_I, QQ.frac_field(x)) == QQ_I.frac_field(x) assert unify(QQ_I, QQ_I.frac_field(x)) == QQ_I.frac_field(x) assert unify(QQ_I, EX) == EX assert unify(RR, F3) == RR assert unify(RR, ZZ) == RR assert unify(RR, QQ) == RR assert unify(RR, ALG) == RR assert unify(RR, RR) == RR assert unify(RR, CC) == CC assert unify(RR, ZZ[x]) == RR[x] assert unify(RR, ZZ.frac_field(x)) == RR.frac_field(x) assert unify(RR, EX) == EX assert RR[x].unify(ZZ.frac_field(y)) == RR.frac_field(x, y) assert unify(CC, F3) == CC assert unify(CC, ZZ) == CC assert unify(CC, QQ) == CC assert unify(CC, ALG) == CC assert unify(CC, RR) == CC assert unify(CC, CC) == CC assert unify(CC, ZZ[x]) == CC[x] assert unify(CC, ZZ.frac_field(x)) == CC.frac_field(x) assert unify(CC, EX) == EX assert unify(ZZ[x], F3) == ZZ[x] assert unify(ZZ[x], ZZ) == ZZ[x] assert unify(ZZ[x], QQ) == QQ[x] assert unify(ZZ[x], ALG) == ALG[x] assert unify(ZZ[x], RR) == RR[x] assert unify(ZZ[x], CC) == CC[x] assert unify(ZZ[x], ZZ[x]) == ZZ[x] assert unify(ZZ[x], ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ[x], EX) == EX assert unify(ZZ.frac_field(x), F3) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), ZZ) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), QQ) == QQ.frac_field(x) assert unify(ZZ.frac_field(x), ALG) == ALG.frac_field(x) assert unify(ZZ.frac_field(x), RR) == RR.frac_field(x) assert unify(ZZ.frac_field(x), CC) == CC.frac_field(x) assert unify(ZZ.frac_field(x), ZZ[x]) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), EX) == EX assert unify(EX, F3) == EX assert unify(EX, ZZ) == EX assert unify(EX, QQ) == EX assert unify(EX, ALG) == EX assert unify(EX, RR) == EX assert unify(EX, CC) == EX assert unify(EX, ZZ[x]) == EX assert unify(EX, ZZ.frac_field(x)) == EX assert unify(EX, EX) == EX def test_Domain_unify_composite(): assert unify(ZZ.poly_ring(x), ZZ) == ZZ.poly_ring(x) assert unify(ZZ.poly_ring(x), QQ) == QQ.poly_ring(x) assert unify(QQ.poly_ring(x), ZZ) == QQ.poly_ring(x) assert unify(QQ.poly_ring(x), QQ) == QQ.poly_ring(x) assert unify(ZZ, ZZ.poly_ring(x)) == ZZ.poly_ring(x) assert unify(QQ, ZZ.poly_ring(x)) == QQ.poly_ring(x) assert unify(ZZ, QQ.poly_ring(x)) == QQ.poly_ring(x) assert unify(QQ, QQ.poly_ring(x)) == QQ.poly_ring(x) assert unify(ZZ.poly_ring(x, y), ZZ) == ZZ.poly_ring(x, y) assert unify(ZZ.poly_ring(x, y), QQ) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x, y), ZZ) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x, y), QQ) == QQ.poly_ring(x, y) assert unify(ZZ, ZZ.poly_ring(x, y)) == ZZ.poly_ring(x, y) assert unify(QQ, ZZ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(ZZ, QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(QQ, QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(ZZ.frac_field(x), ZZ) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), QQ) == QQ.frac_field(x) assert unify(QQ.frac_field(x), ZZ) == QQ.frac_field(x) assert unify(QQ.frac_field(x), QQ) == QQ.frac_field(x) assert unify(ZZ, ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(QQ, ZZ.frac_field(x)) == QQ.frac_field(x) assert unify(ZZ, QQ.frac_field(x)) == QQ.frac_field(x) assert unify(QQ, QQ.frac_field(x)) == QQ.frac_field(x) assert unify(ZZ.frac_field(x, y), ZZ) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), QQ) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x, y), ZZ) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x, y), QQ) == QQ.frac_field(x, y) assert unify(ZZ, ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(QQ, ZZ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(ZZ, QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(QQ, QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(ZZ.poly_ring(x), ZZ.poly_ring(x)) == ZZ.poly_ring(x) assert unify(ZZ.poly_ring(x), QQ.poly_ring(x)) == QQ.poly_ring(x) assert unify(QQ.poly_ring(x), ZZ.poly_ring(x)) == QQ.poly_ring(x) assert unify(QQ.poly_ring(x), QQ.poly_ring(x)) == QQ.poly_ring(x) assert unify(ZZ.poly_ring(x, y), ZZ.poly_ring(x)) == ZZ.poly_ring(x, y) assert unify(ZZ.poly_ring(x, y), QQ.poly_ring(x)) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x, y), ZZ.poly_ring(x)) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x, y), QQ.poly_ring(x)) == QQ.poly_ring(x, y) assert unify(ZZ.poly_ring(x), ZZ.poly_ring(x, y)) == ZZ.poly_ring(x, y) assert unify(ZZ.poly_ring(x), QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x), ZZ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(QQ.poly_ring(x), QQ.poly_ring(x, y)) == QQ.poly_ring(x, y) assert unify(ZZ.poly_ring(x, y), ZZ.poly_ring(x, z)) == ZZ.poly_ring(x, y, z) assert unify(ZZ.poly_ring(x, y), QQ.poly_ring(x, z)) == QQ.poly_ring(x, y, z) assert unify(QQ.poly_ring(x, y), ZZ.poly_ring(x, z)) == QQ.poly_ring(x, y, z) assert unify(QQ.poly_ring(x, y), QQ.poly_ring(x, z)) == QQ.poly_ring(x, y, z) assert unify(ZZ.frac_field(x), ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), QQ.frac_field(x)) == QQ.frac_field(x) assert unify(QQ.frac_field(x), ZZ.frac_field(x)) == QQ.frac_field(x) assert unify(QQ.frac_field(x), QQ.frac_field(x)) == QQ.frac_field(x) assert unify(ZZ.frac_field(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x, y), ZZ.frac_field(x)) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y) assert unify(ZZ.frac_field(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x), ZZ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(QQ.frac_field(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z) assert unify(ZZ.frac_field(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z) assert unify(QQ.frac_field(x, y), ZZ.frac_field(x, z)) == QQ.frac_field(x, y, z) assert unify(QQ.frac_field(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z) assert unify(ZZ.poly_ring(x), ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(ZZ.poly_ring(x), QQ.frac_field(x)) == ZZ.frac_field(x) assert unify(QQ.poly_ring(x), ZZ.frac_field(x)) == ZZ.frac_field(x) assert unify(QQ.poly_ring(x), QQ.frac_field(x)) == QQ.frac_field(x) assert unify(ZZ.poly_ring(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y) assert unify(ZZ.poly_ring(x, y), QQ.frac_field(x)) == ZZ.frac_field(x, y) assert unify(QQ.poly_ring(x, y), ZZ.frac_field(x)) == ZZ.frac_field(x, y) assert unify(QQ.poly_ring(x, y), QQ.frac_field(x)) == QQ.frac_field(x, y) assert unify(ZZ.poly_ring(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(ZZ.poly_ring(x), QQ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(QQ.poly_ring(x), ZZ.frac_field(x, y)) == ZZ.frac_field(x, y) assert unify(QQ.poly_ring(x), QQ.frac_field(x, y)) == QQ.frac_field(x, y) assert unify(ZZ.poly_ring(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z) assert unify(ZZ.poly_ring(x, y), QQ.frac_field(x, z)) == ZZ.frac_field(x, y, z) assert unify(QQ.poly_ring(x, y), ZZ.frac_field(x, z)) == ZZ.frac_field(x, y, z) assert unify(QQ.poly_ring(x, y), QQ.frac_field(x, z)) == QQ.frac_field(x, y, z) assert unify(ZZ.frac_field(x), ZZ.poly_ring(x)) == ZZ.frac_field(x) assert unify(ZZ.frac_field(x), QQ.poly_ring(x)) == ZZ.frac_field(x) assert unify(QQ.frac_field(x), ZZ.poly_ring(x)) == ZZ.frac_field(x) assert unify(QQ.frac_field(x), QQ.poly_ring(x)) == QQ.frac_field(x) assert unify(ZZ.frac_field(x, y), ZZ.poly_ring(x)) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), QQ.poly_ring(x)) == ZZ.frac_field(x, y) assert unify(QQ.frac_field(x, y), ZZ.poly_ring(x)) == ZZ.frac_field(x, y) assert unify(QQ.frac_field(x, y), QQ.poly_ring(x)) == QQ.frac_field(x, y) assert unify(ZZ.frac_field(x), ZZ.poly_ring(x, y)) == ZZ.frac_field(x, y) assert unify(ZZ.frac_field(x), QQ.poly_ring(x, y)) == ZZ.frac_field(x, y) assert unify(QQ.frac_field(x), ZZ.poly_ring(x, y)) == ZZ.frac_field(x, y) assert unify(QQ.frac_field(x), QQ.poly_ring(x, y)) == QQ.frac_field(x, y) assert unify(ZZ.frac_field(x, y), ZZ.poly_ring(x, z)) == ZZ.frac_field(x, y, z) assert unify(ZZ.frac_field(x, y), QQ.poly_ring(x, z)) == ZZ.frac_field(x, y, z) assert unify(QQ.frac_field(x, y), ZZ.poly_ring(x, z)) == ZZ.frac_field(x, y, z) assert unify(QQ.frac_field(x, y), QQ.poly_ring(x, z)) == QQ.frac_field(x, y, z) def test_Domain_unify_algebraic(): sqrt5 = QQ.algebraic_field(sqrt(5)) sqrt7 = QQ.algebraic_field(sqrt(7)) sqrt57 = QQ.algebraic_field(sqrt(5), sqrt(7)) assert sqrt5.unify(sqrt7) == sqrt57 assert sqrt5.unify(sqrt5[x, y]) == sqrt5[x, y] assert sqrt5[x, y].unify(sqrt5) == sqrt5[x, y] assert sqrt5.unify(sqrt5.frac_field(x, y)) == sqrt5.frac_field(x, y) assert sqrt5.frac_field(x, y).unify(sqrt5) == sqrt5.frac_field(x, y) assert sqrt5.unify(sqrt7[x, y]) == sqrt57[x, y] assert sqrt5[x, y].unify(sqrt7) == sqrt57[x, y] assert sqrt5.unify(sqrt7.frac_field(x, y)) == sqrt57.frac_field(x, y) assert sqrt5.frac_field(x, y).unify(sqrt7) == sqrt57.frac_field(x, y) def test_Domain_unify_FiniteExtension(): KxZZ = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ)) KxQQ = FiniteExtension(Poly(x**2 - 2, x, domain=QQ)) KxZZy = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ[y])) KxQQy = FiniteExtension(Poly(x**2 - 2, x, domain=QQ[y])) assert KxZZ.unify(KxZZ) == KxZZ assert KxQQ.unify(KxQQ) == KxQQ assert KxZZy.unify(KxZZy) == KxZZy assert KxQQy.unify(KxQQy) == KxQQy assert KxZZ.unify(ZZ) == KxZZ assert KxZZ.unify(QQ) == KxQQ assert KxQQ.unify(ZZ) == KxQQ assert KxQQ.unify(QQ) == KxQQ assert KxZZ.unify(ZZ[y]) == KxZZy assert KxZZ.unify(QQ[y]) == KxQQy assert KxQQ.unify(ZZ[y]) == KxQQy assert KxQQ.unify(QQ[y]) == KxQQy assert KxZZy.unify(ZZ) == KxZZy assert KxZZy.unify(QQ) == KxQQy assert KxQQy.unify(ZZ) == KxQQy assert KxQQy.unify(QQ) == KxQQy assert KxZZy.unify(ZZ[y]) == KxZZy assert KxZZy.unify(QQ[y]) == KxQQy assert KxQQy.unify(ZZ[y]) == KxQQy assert KxQQy.unify(QQ[y]) == KxQQy K = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ[y])) assert K.unify(ZZ) == K assert K.unify(ZZ[x]) == K assert K.unify(ZZ[y]) == K assert K.unify(ZZ[x, y]) == K Kz = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ[y, z])) assert K.unify(ZZ[z]) == Kz assert K.unify(ZZ[x, z]) == Kz assert K.unify(ZZ[y, z]) == Kz assert K.unify(ZZ[x, y, z]) == Kz Kx = FiniteExtension(Poly(x**2 - 2, x, domain=ZZ)) Ky = FiniteExtension(Poly(y**2 - 2, y, domain=ZZ)) Kxy = FiniteExtension(Poly(y**2 - 2, y, domain=Kx)) assert Kx.unify(Kx) == Kx assert Ky.unify(Ky) == Ky assert Kx.unify(Ky) == Kxy assert Ky.unify(Kx) == Kxy def test_Domain_unify_with_symbols(): raises(UnificationFailed, lambda: ZZ[x, y].unify_with_symbols(ZZ, (y, z))) raises(UnificationFailed, lambda: ZZ.unify_with_symbols(ZZ[x, y], (y, z))) def test_Domain__contains__(): assert (0 in EX) is True assert (0 in ZZ) is True assert (0 in QQ) is True assert (0 in RR) is True assert (0 in CC) is True assert (0 in ALG) is True assert (0 in ZZ[x, y]) is True assert (0 in QQ[x, y]) is True assert (0 in RR[x, y]) is True assert (-7 in EX) is True assert (-7 in ZZ) is True assert (-7 in QQ) is True assert (-7 in RR) is True assert (-7 in CC) is True assert (-7 in ALG) is True assert (-7 in ZZ[x, y]) is True assert (-7 in QQ[x, y]) is True assert (-7 in RR[x, y]) is True assert (17 in EX) is True assert (17 in ZZ) is True assert (17 in QQ) is True assert (17 in RR) is True assert (17 in CC) is True assert (17 in ALG) is True assert (17 in ZZ[x, y]) is True assert (17 in QQ[x, y]) is True assert (17 in RR[x, y]) is True assert (Rational(-1, 7) in EX) is True assert (Rational(-1, 7) in ZZ) is False assert (Rational(-1, 7) in QQ) is True assert (Rational(-1, 7) in RR) is True assert (Rational(-1, 7) in CC) is True assert (Rational(-1, 7) in ALG) is True assert (Rational(-1, 7) in ZZ[x, y]) is False assert (Rational(-1, 7) in QQ[x, y]) is True assert (Rational(-1, 7) in RR[x, y]) is True assert (Rational(3, 5) in EX) is True assert (Rational(3, 5) in ZZ) is False assert (Rational(3, 5) in QQ) is True assert (Rational(3, 5) in RR) is True assert (Rational(3, 5) in CC) is True assert (Rational(3, 5) in ALG) is True assert (Rational(3, 5) in ZZ[x, y]) is False assert (Rational(3, 5) in QQ[x, y]) is True assert (Rational(3, 5) in RR[x, y]) is True assert (3.0 in EX) is True assert (3.0 in ZZ) is True assert (3.0 in QQ) is True assert (3.0 in RR) is True assert (3.0 in CC) is True assert (3.0 in ALG) is True assert (3.0 in ZZ[x, y]) is True assert (3.0 in QQ[x, y]) is True assert (3.0 in RR[x, y]) is True assert (3.14 in EX) is True assert (3.14 in ZZ) is False assert (3.14 in QQ) is True assert (3.14 in RR) is True assert (3.14 in CC) is True assert (3.14 in ALG) is True assert (3.14 in ZZ[x, y]) is False assert (3.14 in QQ[x, y]) is True assert (3.14 in RR[x, y]) is True assert (oo in ALG) is False assert (oo in ZZ[x, y]) is False assert (oo in QQ[x, y]) is False assert (-oo in ZZ) is False assert (-oo in QQ) is False assert (-oo in ALG) is False assert (-oo in ZZ[x, y]) is False assert (-oo in QQ[x, y]) is False assert (sqrt(7) in EX) is True assert (sqrt(7) in ZZ) is False assert (sqrt(7) in QQ) is False assert (sqrt(7) in RR) is True assert (sqrt(7) in CC) is True assert (sqrt(7) in ALG) is False assert (sqrt(7) in ZZ[x, y]) is False assert (sqrt(7) in QQ[x, y]) is False assert (sqrt(7) in RR[x, y]) is True assert (2*sqrt(3) + 1 in EX) is True assert (2*sqrt(3) + 1 in ZZ) is False assert (2*sqrt(3) + 1 in QQ) is False assert (2*sqrt(3) + 1 in RR) is True assert (2*sqrt(3) + 1 in CC) is True assert (2*sqrt(3) + 1 in ALG) is True assert (2*sqrt(3) + 1 in ZZ[x, y]) is False assert (2*sqrt(3) + 1 in QQ[x, y]) is False assert (2*sqrt(3) + 1 in RR[x, y]) is True assert (sin(1) in EX) is True assert (sin(1) in ZZ) is False assert (sin(1) in QQ) is False assert (sin(1) in RR) is True assert (sin(1) in CC) is True assert (sin(1) in ALG) is False assert (sin(1) in ZZ[x, y]) is False assert (sin(1) in QQ[x, y]) is False assert (sin(1) in RR[x, y]) is True assert (x**2 + 1 in EX) is True assert (x**2 + 1 in ZZ) is False assert (x**2 + 1 in QQ) is False assert (x**2 + 1 in RR) is False assert (x**2 + 1 in CC) is False assert (x**2 + 1 in ALG) is False assert (x**2 + 1 in ZZ[x]) is True assert (x**2 + 1 in QQ[x]) is True assert (x**2 + 1 in RR[x]) is True assert (x**2 + 1 in ZZ[x, y]) is True assert (x**2 + 1 in QQ[x, y]) is True assert (x**2 + 1 in RR[x, y]) is True assert (x**2 + y**2 in EX) is True assert (x**2 + y**2 in ZZ) is False assert (x**2 + y**2 in QQ) is False assert (x**2 + y**2 in RR) is False assert (x**2 + y**2 in CC) is False assert (x**2 + y**2 in ALG) is False assert (x**2 + y**2 in ZZ[x]) is False assert (x**2 + y**2 in QQ[x]) is False assert (x**2 + y**2 in RR[x]) is False assert (x**2 + y**2 in ZZ[x, y]) is True assert (x**2 + y**2 in QQ[x, y]) is True assert (x**2 + y**2 in RR[x, y]) is True assert (Rational(3, 2)*x/(y + 1) - z in QQ[x, y, z]) is False def test_Domain_get_ring(): assert ZZ.has_assoc_Ring is True assert QQ.has_assoc_Ring is True assert ZZ[x].has_assoc_Ring is True assert QQ[x].has_assoc_Ring is True assert ZZ[x, y].has_assoc_Ring is True assert QQ[x, y].has_assoc_Ring is True assert ZZ.frac_field(x).has_assoc_Ring is True assert QQ.frac_field(x).has_assoc_Ring is True assert ZZ.frac_field(x, y).has_assoc_Ring is True assert QQ.frac_field(x, y).has_assoc_Ring is True assert EX.has_assoc_Ring is False assert RR.has_assoc_Ring is False assert ALG.has_assoc_Ring is False assert ZZ.get_ring() == ZZ assert QQ.get_ring() == ZZ assert ZZ[x].get_ring() == ZZ[x] assert QQ[x].get_ring() == QQ[x] assert ZZ[x, y].get_ring() == ZZ[x, y] assert QQ[x, y].get_ring() == QQ[x, y] assert ZZ.frac_field(x).get_ring() == ZZ[x] assert QQ.frac_field(x).get_ring() == QQ[x] assert ZZ.frac_field(x, y).get_ring() == ZZ[x, y] assert QQ.frac_field(x, y).get_ring() == QQ[x, y] assert EX.get_ring() == EX assert RR.get_ring() == RR # XXX: This should also be like RR raises(DomainError, lambda: ALG.get_ring()) def test_Domain_get_field(): assert EX.has_assoc_Field is True assert ZZ.has_assoc_Field is True assert QQ.has_assoc_Field is True assert RR.has_assoc_Field is True assert ALG.has_assoc_Field is True assert ZZ[x].has_assoc_Field is True assert QQ[x].has_assoc_Field is True assert ZZ[x, y].has_assoc_Field is True assert QQ[x, y].has_assoc_Field is True assert EX.get_field() == EX assert ZZ.get_field() == QQ assert QQ.get_field() == QQ assert RR.get_field() == RR assert ALG.get_field() == ALG assert ZZ[x].get_field() == ZZ.frac_field(x) assert QQ[x].get_field() == QQ.frac_field(x) assert ZZ[x, y].get_field() == ZZ.frac_field(x, y) assert QQ[x, y].get_field() == QQ.frac_field(x, y) def test_Domain_get_exact(): assert EX.get_exact() == EX assert ZZ.get_exact() == ZZ assert QQ.get_exact() == QQ assert RR.get_exact() == QQ assert ALG.get_exact() == ALG assert ZZ[x].get_exact() == ZZ[x] assert QQ[x].get_exact() == QQ[x] assert ZZ[x, y].get_exact() == ZZ[x, y] assert QQ[x, y].get_exact() == QQ[x, y] assert ZZ.frac_field(x).get_exact() == ZZ.frac_field(x) assert QQ.frac_field(x).get_exact() == QQ.frac_field(x) assert ZZ.frac_field(x, y).get_exact() == ZZ.frac_field(x, y) assert QQ.frac_field(x, y).get_exact() == QQ.frac_field(x, y) def test_Domain_is_unit(): nums = [-2, -1, 0, 1, 2] invring = [False, True, False, True, False] invfield = [True, True, False, True, True] ZZx, QQx, QQxf = ZZ[x], QQ[x], QQ.frac_field(x) assert [ZZ.is_unit(ZZ(n)) for n in nums] == invring assert [QQ.is_unit(QQ(n)) for n in nums] == invfield assert [ZZx.is_unit(ZZx(n)) for n in nums] == invring assert [QQx.is_unit(QQx(n)) for n in nums] == invfield assert [QQxf.is_unit(QQxf(n)) for n in nums] == invfield assert ZZx.is_unit(ZZx(x)) is False assert QQx.is_unit(QQx(x)) is False assert QQxf.is_unit(QQxf(x)) is True def test_Domain_convert(): def check_element(e1, e2, K1, K2, K3): assert type(e1) is type(e2), '%s, %s: %s %s -> %s' % (e1, e2, K1, K2, K3) assert e1 == e2, '%s, %s: %s %s -> %s' % (e1, e2, K1, K2, K3) def check_domains(K1, K2): K3 = K1.unify(K2) check_element(K3.convert_from( K1.one, K1), K3.one, K1, K2, K3) check_element(K3.convert_from( K2.one, K2), K3.one, K1, K2, K3) check_element(K3.convert_from(K1.zero, K1), K3.zero, K1, K2, K3) check_element(K3.convert_from(K2.zero, K2), K3.zero, K1, K2, K3) def composite_domains(K): domains = [ K, K[y], K[z], K[y, z], K.frac_field(y), K.frac_field(z), K.frac_field(y, z), # XXX: These should be tested and made to work... # K.old_poly_ring(y), K.old_frac_field(y), ] return domains QQ2 = QQ.algebraic_field(sqrt(2)) QQ3 = QQ.algebraic_field(sqrt(3)) doms = [ZZ, QQ, QQ2, QQ3, QQ_I, ZZ_I, RR, CC] for i, K1 in enumerate(doms): for K2 in doms[i:]: for K3 in composite_domains(K1): for K4 in composite_domains(K2): check_domains(K3, K4) assert QQ.convert(10e-52) == QQ(1684996666696915, 1684996666696914987166688442938726917102321526408785780068975640576) R, xr = ring("x", ZZ) assert ZZ.convert(xr - xr) == 0 assert ZZ.convert(xr - xr, R.to_domain()) == 0 assert CC.convert(ZZ_I(1, 2)) == CC(1, 2) assert CC.convert(QQ_I(1, 2)) == CC(1, 2) K1 = QQ.frac_field(x) K2 = ZZ.frac_field(x) K3 = QQ[x] K4 = ZZ[x] Ks = [K1, K2, K3, K4] for Ka, Kb in product(Ks, Ks): assert Ka.convert_from(Kb.from_sympy(x), Kb) == Ka.from_sympy(x) assert K2.convert_from(QQ(1, 2), QQ) == K2(QQ(1, 2)) def test_GlobalPolynomialRing_convert(): K1 = QQ.old_poly_ring(x) K2 = QQ[x] assert K1.convert(x) == K1.convert(K2.convert(x), K2) assert K2.convert(x) == K2.convert(K1.convert(x), K1) K1 = QQ.old_poly_ring(x, y) K2 = QQ[x] assert K1.convert(x) == K1.convert(K2.convert(x), K2) #assert K2.convert(x) == K2.convert(K1.convert(x), K1) K1 = ZZ.old_poly_ring(x, y) K2 = QQ[x] assert K1.convert(x) == K1.convert(K2.convert(x), K2) #assert K2.convert(x) == K2.convert(K1.convert(x), K1) def test_PolynomialRing__init(): R, = ring("", ZZ) assert ZZ.poly_ring() == R.to_domain() def test_FractionField__init(): F, = field("", ZZ) assert ZZ.frac_field() == F.to_domain() def test_FractionField_convert(): K = QQ.frac_field(x) assert K.convert(QQ(2, 3), QQ) == K.from_sympy(Rational(2, 3)) K = QQ.frac_field(x) assert K.convert(ZZ(2), ZZ) == K.from_sympy(Integer(2)) def test_inject(): assert ZZ.inject(x, y, z) == ZZ[x, y, z] assert ZZ[x].inject(y, z) == ZZ[x, y, z] assert ZZ.frac_field(x).inject(y, z) == ZZ.frac_field(x, y, z) raises(GeneratorsError, lambda: ZZ[x].inject(x)) def test_drop(): assert ZZ.drop(x) == ZZ assert ZZ[x].drop(x) == ZZ assert ZZ[x, y].drop(x) == ZZ[y] assert ZZ.frac_field(x).drop(x) == ZZ assert ZZ.frac_field(x, y).drop(x) == ZZ.frac_field(y) assert ZZ[x][y].drop(y) == ZZ[x] assert ZZ[x][y].drop(x) == ZZ[y] assert ZZ.frac_field(x)[y].drop(x) == ZZ[y] assert ZZ.frac_field(x)[y].drop(y) == ZZ.frac_field(x) Ky = FiniteExtension(Poly(x**2-1, x, domain=ZZ[y])) K = FiniteExtension(Poly(x**2-1, x, domain=ZZ)) assert Ky.drop(y) == K raises(GeneratorsError, lambda: Ky.drop(x)) def test_Domain_map(): seq = ZZ.map([1, 2, 3, 4]) assert all(ZZ.of_type(elt) for elt in seq) seq = ZZ.map([[1, 2, 3, 4]]) assert all(ZZ.of_type(elt) for elt in seq[0]) and len(seq) == 1 def test_Domain___eq__(): assert (ZZ[x, y] == ZZ[x, y]) is True assert (QQ[x, y] == QQ[x, y]) is True assert (ZZ[x, y] == QQ[x, y]) is False assert (QQ[x, y] == ZZ[x, y]) is False assert (ZZ.frac_field(x, y) == ZZ.frac_field(x, y)) is True assert (QQ.frac_field(x, y) == QQ.frac_field(x, y)) is True assert (ZZ.frac_field(x, y) == QQ.frac_field(x, y)) is False assert (QQ.frac_field(x, y) == ZZ.frac_field(x, y)) is False assert RealField()[x] == RR[x] def test_Domain__algebraic_field(): alg = ZZ.algebraic_field(sqrt(2)) assert alg.ext.minpoly == Poly(x**2 - 2) assert alg.dom == QQ alg = QQ.algebraic_field(sqrt(2)) assert alg.ext.minpoly == Poly(x**2 - 2) assert alg.dom == QQ alg = alg.algebraic_field(sqrt(3)) assert alg.ext.minpoly == Poly(x**4 - 10*x**2 + 1) assert alg.dom == QQ def test_PolynomialRing_from_FractionField(): F, x,y = field("x,y", ZZ) R, X,Y = ring("x,y", ZZ) f = (x**2 + y**2)/(x + 1) g = (x**2 + y**2)/4 h = x**2 + y**2 assert R.to_domain().from_FractionField(f, F.to_domain()) is None assert R.to_domain().from_FractionField(g, F.to_domain()) == X**2/4 + Y**2/4 assert R.to_domain().from_FractionField(h, F.to_domain()) == X**2 + Y**2 F, x,y = field("x,y", QQ) R, X,Y = ring("x,y", QQ) f = (x**2 + y**2)/(x + 1) g = (x**2 + y**2)/4 h = x**2 + y**2 assert R.to_domain().from_FractionField(f, F.to_domain()) is None assert R.to_domain().from_FractionField(g, F.to_domain()) == X**2/4 + Y**2/4 assert R.to_domain().from_FractionField(h, F.to_domain()) == X**2 + Y**2 def test_FractionField_from_PolynomialRing(): R, x,y = ring("x,y", QQ) F, X,Y = field("x,y", ZZ) f = 3*x**2 + 5*y**2 g = x**2/3 + y**2/5 assert F.to_domain().from_PolynomialRing(f, R.to_domain()) == 3*X**2 + 5*Y**2 assert F.to_domain().from_PolynomialRing(g, R.to_domain()) == (5*X**2 + 3*Y**2)/15 def test_FF_of_type(): assert FF(3).of_type(FF(3)(1)) is True assert FF(5).of_type(FF(5)(3)) is True assert FF(5).of_type(FF(7)(3)) is False def test___eq__(): assert not QQ[x] == ZZ[x] assert not QQ.frac_field(x) == ZZ.frac_field(x) def test_RealField_from_sympy(): assert RR.convert(S.Zero) == RR.dtype(0) assert RR.convert(S(0.0)) == RR.dtype(0.0) assert RR.convert(S.One) == RR.dtype(1) assert RR.convert(S(1.0)) == RR.dtype(1.0) assert RR.convert(sin(1)) == RR.dtype(sin(1).evalf()) def test_not_in_any_domain(): check = illegal + [x] + [ float(i) for i in illegal if i != S.ComplexInfinity] for dom in (ZZ, QQ, RR, CC, EX): for i in check: if i == x and dom == EX: continue assert i not in dom, (i, dom) raises(CoercionFailed, lambda: dom.convert(i)) def test_ModularInteger(): F3 = FF(3) a = F3(0) assert isinstance(a, F3.dtype) and a == 0 a = F3(1) assert isinstance(a, F3.dtype) and a == 1 a = F3(2) assert isinstance(a, F3.dtype) and a == 2 a = F3(3) assert isinstance(a, F3.dtype) and a == 0 a = F3(4) assert isinstance(a, F3.dtype) and a == 1 a = F3(F3(0)) assert isinstance(a, F3.dtype) and a == 0 a = F3(F3(1)) assert isinstance(a, F3.dtype) and a == 1 a = F3(F3(2)) assert isinstance(a, F3.dtype) and a == 2 a = F3(F3(3)) assert isinstance(a, F3.dtype) and a == 0 a = F3(F3(4)) assert isinstance(a, F3.dtype) and a == 1 a = -F3(1) assert isinstance(a, F3.dtype) and a == 2 a = -F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 2 + F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2) + 2 assert isinstance(a, F3.dtype) and a == 1 a = F3(2) + F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2) + F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 3 - F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(3) - 2 assert isinstance(a, F3.dtype) and a == 1 a = F3(3) - F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(3) - F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 2*F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)*2 assert isinstance(a, F3.dtype) and a == 1 a = F3(2)*F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)*F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 2/F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)/2 assert isinstance(a, F3.dtype) and a == 1 a = F3(2)/F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)/F3(2) assert isinstance(a, F3.dtype) and a == 1 a = 1 % F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(1) % 2 assert isinstance(a, F3.dtype) and a == 1 a = F3(1) % F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(1) % F3(2) assert isinstance(a, F3.dtype) and a == 1 a = F3(2)**0 assert isinstance(a, F3.dtype) and a == 1 a = F3(2)**1 assert isinstance(a, F3.dtype) and a == 2 a = F3(2)**2 assert isinstance(a, F3.dtype) and a == 1 F7 = FF(7) a = F7(3)**100000000000 assert isinstance(a, F7.dtype) and a == 4 a = F7(3)**-100000000000 assert isinstance(a, F7.dtype) and a == 2 a = F7(3)**S(2) assert isinstance(a, F7.dtype) and a == 2 assert bool(F3(3)) is False assert bool(F3(4)) is True F5 = FF(5) a = F5(1)**(-1) assert isinstance(a, F5.dtype) and a == 1 a = F5(2)**(-1) assert isinstance(a, F5.dtype) and a == 3 a = F5(3)**(-1) assert isinstance(a, F5.dtype) and a == 2 a = F5(4)**(-1) assert isinstance(a, F5.dtype) and a == 4 assert (F5(1) < F5(2)) is True assert (F5(1) <= F5(2)) is True assert (F5(1) > F5(2)) is False assert (F5(1) >= F5(2)) is False assert (F5(3) < F5(2)) is False assert (F5(3) <= F5(2)) is False assert (F5(3) > F5(2)) is True assert (F5(3) >= F5(2)) is True assert (F5(1) < F5(7)) is True assert (F5(1) <= F5(7)) is True assert (F5(1) > F5(7)) is False assert (F5(1) >= F5(7)) is False assert (F5(3) < F5(7)) is False assert (F5(3) <= F5(7)) is False assert (F5(3) > F5(7)) is True assert (F5(3) >= F5(7)) is True assert (F5(1) < 2) is True assert (F5(1) <= 2) is True assert (F5(1) > 2) is False assert (F5(1) >= 2) is False assert (F5(3) < 2) is False assert (F5(3) <= 2) is False assert (F5(3) > 2) is True assert (F5(3) >= 2) is True assert (F5(1) < 7) is True assert (F5(1) <= 7) is True assert (F5(1) > 7) is False assert (F5(1) >= 7) is False assert (F5(3) < 7) is False assert (F5(3) <= 7) is False assert (F5(3) > 7) is True assert (F5(3) >= 7) is True raises(NotInvertible, lambda: F5(0)**(-1)) raises(NotInvertible, lambda: F5(5)**(-1)) raises(ValueError, lambda: FF(0)) raises(ValueError, lambda: FF(2.1)) def test_QQ_int(): assert int(QQ(2**2000, 3**1250)) == 455431 assert int(QQ(2**100, 3)) == 422550200076076467165567735125 def test_RR_double(): assert RR(3.14) > 1e-50 assert RR(1e-13) > 1e-50 assert RR(1e-14) > 1e-50 assert RR(1e-15) > 1e-50 assert RR(1e-20) > 1e-50 assert RR(1e-40) > 1e-50 def test_RR_Float(): f1 = Float("1.01") f2 = Float("1.0000000000000000000001") assert f1._prec == 53 assert f2._prec == 80 assert RR(f1)-1 > 1e-50 assert RR(f2)-1 < 1e-50 # RR's precision is lower than f2's RR2 = RealField(prec=f2._prec) assert RR2(f1)-1 > 1e-50 assert RR2(f2)-1 > 1e-50 # RR's precision is equal to f2's def test_CC_double(): assert CC(3.14).real > 1e-50 assert CC(1e-13).real > 1e-50 assert CC(1e-14).real > 1e-50 assert CC(1e-15).real > 1e-50 assert CC(1e-20).real > 1e-50 assert CC(1e-40).real > 1e-50 assert CC(3.14j).imag > 1e-50 assert CC(1e-13j).imag > 1e-50 assert CC(1e-14j).imag > 1e-50 assert CC(1e-15j).imag > 1e-50 assert CC(1e-20j).imag > 1e-50 assert CC(1e-40j).imag > 1e-50 def test_gaussian_domains(): I = S.ImaginaryUnit a, b, c, d = [ZZ_I.convert(x) for x in (5, 2 + I, 3 - I, 5 - 5)] ZZ_I.gcd(a, b) == b ZZ_I.gcd(a, c) == b ZZ_I.lcm(a, b) == a ZZ_I.lcm(a, c) == d assert ZZ_I(3, 4) != QQ_I(3, 4) # XXX is this right or should QQ->ZZ if possible? assert ZZ_I(3, 0) != 3 # and should this go to Integer? assert QQ_I(S(3)/4, 0) != S(3)/4 # and this to Rational? assert ZZ_I(0, 0).quadrant() == 0 assert ZZ_I(-1, 0).quadrant() == 2 assert QQ_I.convert(QQ(3, 2)) == QQ_I(QQ(3, 2), QQ(0)) assert QQ_I.convert(QQ(3, 2), QQ) == QQ_I(QQ(3, 2), QQ(0)) for G in (QQ_I, ZZ_I): q = G(3, 4) assert str(q) == '3 + 4*I' assert q.parent() == G assert q._get_xy(pi) == (None, None) assert q._get_xy(2) == (2, 0) assert q._get_xy(2*I) == (0, 2) assert hash(q) == hash((3, 4)) assert G(1, 2) == G(1, 2) assert G(1, 2) != G(1, 3) assert G(3, 0) == G(3) assert q + q == G(6, 8) assert q - q == G(0, 0) assert 3 - q == -q + 3 == G(0, -4) assert 3 + q == q + 3 == G(6, 4) assert q * q == G(-7, 24) assert 3 * q == q * 3 == G(9, 12) assert q ** 0 == G(1, 0) assert q ** 1 == q assert q ** 2 == q * q == G(-7, 24) assert q ** 3 == q * q * q == G(-117, 44) assert 1 / q == q ** -1 == QQ_I(S(3)/25, - S(4)/25) assert q / 1 == QQ_I(3, 4) assert q / 2 == QQ_I(S(3)/2, 2) assert q/3 == QQ_I(1, S(4)/3) assert 3/q == QQ_I(S(9)/25, -S(12)/25) i, r = divmod(q, 2) assert 2*i + r == q i, r = divmod(2, q) assert q*i + r == G(2, 0) raises(ZeroDivisionError, lambda: q % 0) raises(ZeroDivisionError, lambda: q / 0) raises(ZeroDivisionError, lambda: q // 0) raises(ZeroDivisionError, lambda: divmod(q, 0)) raises(ZeroDivisionError, lambda: divmod(q, 0)) raises(TypeError, lambda: q + x) raises(TypeError, lambda: q - x) raises(TypeError, lambda: x + q) raises(TypeError, lambda: x - q) raises(TypeError, lambda: q * x) raises(TypeError, lambda: x * q) raises(TypeError, lambda: q / x) raises(TypeError, lambda: x / q) raises(TypeError, lambda: q // x) raises(TypeError, lambda: x // q) assert G.from_sympy(S(2)) == G(2, 0) assert G.to_sympy(G(2, 0)) == S(2) raises(CoercionFailed, lambda: G.from_sympy(pi)) PR = G.inject(x) assert isinstance(PR, PolynomialRing) assert PR.domain == G assert len(PR.gens) == 1 and PR.gens[0].as_expr() == x if G is QQ_I: AF = G.as_AlgebraicField() assert isinstance(AF, AlgebraicField) assert AF.domain == QQ assert AF.ext.args[0] == I for qi in [G(-1, 0), G(1, 0), G(0, -1), G(0, 1)]: assert G.is_negative(qi) is False assert G.is_positive(qi) is False assert G.is_nonnegative(qi) is False assert G.is_nonpositive(qi) is False domains = [ZZ_python(), QQ_python(), AlgebraicField(QQ, I)] if HAS_GMPY: domains += [ZZ_gmpy(), QQ_gmpy()] for K in domains: assert G.convert(K(2)) == G(2, 0) assert G.convert(K(2), K) == G(2, 0) for K in ZZ_I, QQ_I: assert G.convert(K(1, 1)) == G(1, 1) assert G.convert(K(1, 1), K) == G(1, 1) if G == ZZ_I: assert repr(q) == 'ZZ_I(3, 4)' assert q//3 == G(1, 1) assert 12//q == G(1, -2) assert 12 % q == G(1, 2) assert q % 2 == G(-1, 0) assert i == G(0, 0) assert r == G(2, 0) assert G.get_ring() == G assert G.get_field() == QQ_I else: assert repr(q) == 'QQ_I(3, 4)' assert G.get_ring() == ZZ_I assert G.get_field() == G assert q//3 == G(1, S(4)/3) assert 12//q == G(S(36)/25, -S(48)/25) assert 12 % q == G(0, 0) assert q % 2 == G(0, 0) assert i == G(S(6)/25, -S(8)/25), (G,i) assert r == G(0, 0) q2 = G(S(3)/2, S(5)/3) assert G.numer(q2) == ZZ_I(9, 10) assert G.denom(q2) == ZZ_I(6) def test_EX_EXRAW(): assert EXRAW.zero is S.Zero assert EXRAW.one is S.One assert EX(1) == EX.Expression(1) assert EX(1).ex is S.One assert EXRAW(1) is S.One # EX has cancelling but EXRAW does not assert 2*EX((x + y*x)/x) == EX(2 + 2*y) != 2*((x + y*x)/x) assert 2*EXRAW((x + y*x)/x) == 2*((x + y*x)/x) != (1 + y) assert EXRAW.convert_from(EX(1), EX) is EXRAW.one assert EX.convert_from(EXRAW(1), EXRAW) == EX.one assert EXRAW.from_sympy(S.One) is S.One assert EXRAW.to_sympy(EXRAW.one) is S.One raises(CoercionFailed, lambda: EXRAW.from_sympy([])) assert EXRAW.get_field() == EXRAW assert EXRAW.unify(EX) == EXRAW assert EX.unify(EXRAW) == EXRAW def test_canonical_unit(): for K in [ZZ, QQ, RR]: # CC? assert K.canonical_unit(K(2)) == K(1) assert K.canonical_unit(K(-2)) == K(-1) for K in [ZZ_I, QQ_I]: i = K.from_sympy(I) assert K.canonical_unit(K(2)) == K(1) assert K.canonical_unit(K(2)*i) == -i assert K.canonical_unit(-K(2)) == K(-1) assert K.canonical_unit(-K(2)*i) == i K = ZZ[x] assert K.canonical_unit(K(x + 1)) == K(1) assert K.canonical_unit(K(-x + 1)) == K(-1) K = ZZ_I[x] assert K.canonical_unit(K.from_sympy(I*x)) == ZZ_I(0, -1) K = ZZ_I.frac_field(x, y) i = K.from_sympy(I) assert i / i == K.one assert (K.one + i)/(i - K.one) == -i def test_issue_18278(): assert str(RR(2).parent()) == 'RR' assert str(CC(2).parent()) == 'CC' def test_Domain_is_negative(): I = S.ImaginaryUnit a, b = [CC.convert(x) for x in (2 + I, 5)] assert CC.is_negative(a) == False assert CC.is_negative(b) == False def test_Domain_is_positive(): I = S.ImaginaryUnit a, b = [CC.convert(x) for x in (2 + I, 5)] assert CC.is_positive(a) == False assert CC.is_positive(b) == False def test_Domain_is_nonnegative(): I = S.ImaginaryUnit a, b = [CC.convert(x) for x in (2 + I, 5)] assert CC.is_nonnegative(a) == False assert CC.is_nonnegative(b) == False def test_Domain_is_nonpositive(): I = S.ImaginaryUnit a, b = [CC.convert(x) for x in (2 + I, 5)] assert CC.is_nonpositive(a) == False assert CC.is_nonpositive(b) == False def test_exponential_domain(): K = ZZ[E] eK = K.from_sympy(E) assert K.from_sympy(exp(3)) == eK ** 3 assert K.convert(exp(3)) == eK ** 3
3b758f392c81517a737129437516b0c5ad881046b744b7e4a17eed36ae3d79df
"""Tests on algebraic numbers. """ from sympy.core.containers import Tuple from sympy.core.numbers import (AlgebraicNumber, I, Rational) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.miscellaneous import sqrt from sympy.polys.polytools import Poly from sympy.testing.pytest import raises from sympy.polys.numberfields.numbers import ( to_number_field, isolate, ) from sympy.polys.polyerrors import IsomorphismFailed from sympy.polys.polyclasses import DMP from sympy.polys.domains import QQ from sympy.printing.lambdarepr import IntervalPrinter from sympy.abc import x, y Q = Rational def test_to_number_field(): assert to_number_field(sqrt(2)) == AlgebraicNumber(sqrt(2)) assert to_number_field( [sqrt(2), sqrt(3)]) == AlgebraicNumber(sqrt(2) + sqrt(3)) a = AlgebraicNumber(sqrt(2) + sqrt(3), [S.Half, S.Zero, Rational(-9, 2), S.Zero]) assert to_number_field(sqrt(2), sqrt(2) + sqrt(3)) == a assert to_number_field(sqrt(2), AlgebraicNumber(sqrt(2) + sqrt(3))) == a raises(IsomorphismFailed, lambda: to_number_field(sqrt(2), sqrt(3))) def test_AlgebraicNumber(): minpoly, root = x**2 - 2, sqrt(2) a = AlgebraicNumber(root, gen=x) assert a.rep == DMP([QQ(1), QQ(0)], QQ) assert a.root == root assert a.alias is None assert a.minpoly == minpoly assert a.is_number assert a.is_aliased is False assert a.coeffs() == [S.One, S.Zero] assert a.native_coeffs() == [QQ(1), QQ(0)] a = AlgebraicNumber(root, gen=x, alias='y') assert a.rep == DMP([QQ(1), QQ(0)], QQ) assert a.root == root assert a.alias == Symbol('y') assert a.minpoly == minpoly assert a.is_number assert a.is_aliased is True a = AlgebraicNumber(root, gen=x, alias=Symbol('y')) assert a.rep == DMP([QQ(1), QQ(0)], QQ) assert a.root == root assert a.alias == Symbol('y') assert a.minpoly == minpoly assert a.is_number assert a.is_aliased is True assert AlgebraicNumber(sqrt(2), []).rep == DMP([], QQ) assert AlgebraicNumber(sqrt(2), ()).rep == DMP([], QQ) assert AlgebraicNumber(sqrt(2), (0, 0)).rep == DMP([], QQ) assert AlgebraicNumber(sqrt(2), [8]).rep == DMP([QQ(8)], QQ) assert AlgebraicNumber(sqrt(2), [Rational(8, 3)]).rep == DMP([QQ(8, 3)], QQ) assert AlgebraicNumber(sqrt(2), [7, 3]).rep == DMP([QQ(7), QQ(3)], QQ) assert AlgebraicNumber( sqrt(2), [Rational(7, 9), Rational(3, 2)]).rep == DMP([QQ(7, 9), QQ(3, 2)], QQ) assert AlgebraicNumber(sqrt(2), [1, 2, 3]).rep == DMP([QQ(2), QQ(5)], QQ) a = AlgebraicNumber(AlgebraicNumber(root, gen=x), [1, 2]) assert a.rep == DMP([QQ(1), QQ(2)], QQ) assert a.root == root assert a.alias is None assert a.minpoly == minpoly assert a.is_number assert a.is_aliased is False assert a.coeffs() == [S.One, S(2)] assert a.native_coeffs() == [QQ(1), QQ(2)] a = AlgebraicNumber((minpoly, root), [1, 2]) assert a.rep == DMP([QQ(1), QQ(2)], QQ) assert a.root == root assert a.alias is None assert a.minpoly == minpoly assert a.is_number assert a.is_aliased is False a = AlgebraicNumber((Poly(minpoly), root), [1, 2]) assert a.rep == DMP([QQ(1), QQ(2)], QQ) assert a.root == root assert a.alias is None assert a.minpoly == minpoly assert a.is_number assert a.is_aliased is False assert AlgebraicNumber( sqrt(3)).rep == DMP([ QQ(1), QQ(0)], QQ) assert AlgebraicNumber(-sqrt(3)).rep == DMP([ QQ(1), QQ(0)], QQ) a = AlgebraicNumber(sqrt(2)) b = AlgebraicNumber(sqrt(2)) assert a == b c = AlgebraicNumber(sqrt(2), gen=x) assert a == b assert a == c a = AlgebraicNumber(sqrt(2), [1, 2]) b = AlgebraicNumber(sqrt(2), [1, 3]) assert a != b and a != sqrt(2) + 3 assert (a == x) is False and (a != x) is True a = AlgebraicNumber(sqrt(2), [1, 0]) b = AlgebraicNumber(sqrt(2), [1, 0], alias=y) assert a.as_poly(x) == Poly(x, domain='QQ') assert b.as_poly() == Poly(y, domain='QQ') assert a.as_expr() == sqrt(2) assert a.as_expr(x) == x assert b.as_expr() == sqrt(2) assert b.as_expr(x) == x a = AlgebraicNumber(sqrt(2), [2, 3]) b = AlgebraicNumber(sqrt(2), [2, 3], alias=y) p = a.as_poly() assert p == Poly(2*p.gen + 3) assert a.as_poly(x) == Poly(2*x + 3, domain='QQ') assert b.as_poly() == Poly(2*y + 3, domain='QQ') assert a.as_expr() == 2*sqrt(2) + 3 assert a.as_expr(x) == 2*x + 3 assert b.as_expr() == 2*sqrt(2) + 3 assert b.as_expr(x) == 2*x + 3 a = AlgebraicNumber(sqrt(2)) b = to_number_field(sqrt(2)) assert a.args == b.args == (sqrt(2), Tuple(1, 0)) b = AlgebraicNumber(sqrt(2), alias='alpha') assert b.args == (sqrt(2), Tuple(1, 0), Symbol('alpha')) a = AlgebraicNumber(sqrt(2), [1, 2, 3]) assert a.args == (sqrt(2), Tuple(1, 2, 3)) def test_to_algebraic_integer(): a = AlgebraicNumber(sqrt(3), gen=x).to_algebraic_integer() assert a.minpoly == x**2 - 3 assert a.root == sqrt(3) assert a.rep == DMP([QQ(1), QQ(0)], QQ) a = AlgebraicNumber(2*sqrt(3), gen=x).to_algebraic_integer() assert a.minpoly == x**2 - 12 assert a.root == 2*sqrt(3) assert a.rep == DMP([QQ(1), QQ(0)], QQ) a = AlgebraicNumber(sqrt(3)/2, gen=x).to_algebraic_integer() assert a.minpoly == x**2 - 12 assert a.root == 2*sqrt(3) assert a.rep == DMP([QQ(1), QQ(0)], QQ) a = AlgebraicNumber(sqrt(3)/2, [Rational(7, 19), 3], gen=x).to_algebraic_integer() assert a.minpoly == x**2 - 12 assert a.root == 2*sqrt(3) assert a.rep == DMP([QQ(7, 19), QQ(3)], QQ) def test_IntervalPrinter(): ip = IntervalPrinter() assert ip.doprint(x**Q(1, 3)) == "x**(mpi('1/3'))" assert ip.doprint(sqrt(x)) == "x**(mpi('1/2'))" def test_isolate(): assert isolate(1) == (1, 1) assert isolate(S.Half) == (S.Half, S.Half) assert isolate(sqrt(2)) == (1, 2) assert isolate(-sqrt(2)) == (-2, -1) assert isolate(sqrt(2), eps=Rational(1, 100)) == (Rational(24, 17), Rational(17, 12)) assert isolate(-sqrt(2), eps=Rational(1, 100)) == (Rational(-17, 12), Rational(-24, 17)) raises(NotImplementedError, lambda: isolate(I))
e4ea102c942bcdc09708e074cda1c2774901f993d0194df6a468cb8f8aafb586
"""Tests for minimal polynomials. """ from sympy.core.function import expand from sympy.core import (GoldenRatio, TribonacciConstant) from sympy.core.numbers import (AlgebraicNumber, I, Rational, oo, pi) from sympy.core.singleton import S from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import (cbrt, sqrt) from sympy.functions.elementary.trigonometric import (cos, sin, tan) from sympy.polys.polytools import Poly from sympy.solvers.solveset import nonlinsolve from sympy.geometry import Circle, intersection from sympy.testing.pytest import raises, slow from sympy.sets.sets import FiniteSet from sympy.geometry.point import Point2D from sympy.polys.numberfields.minpoly import ( minimal_polynomial, primitive_element, _choose_factor, ) from sympy.polys.partfrac import apart from sympy.polys.polyerrors import ( NotAlgebraic, GeneratorsError, ) from sympy.polys.domains import QQ from sympy.polys.rootoftools import rootof from sympy.polys.polytools import degree from sympy.abc import x, y, z Q = Rational def test_minimal_polynomial(): assert minimal_polynomial(-7, x) == x + 7 assert minimal_polynomial(-1, x) == x + 1 assert minimal_polynomial( 0, x) == x assert minimal_polynomial( 1, x) == x - 1 assert minimal_polynomial( 7, x) == x - 7 assert minimal_polynomial(sqrt(2), x) == x**2 - 2 assert minimal_polynomial(sqrt(5), x) == x**2 - 5 assert minimal_polynomial(sqrt(6), x) == x**2 - 6 assert minimal_polynomial(2*sqrt(2), x) == x**2 - 8 assert minimal_polynomial(3*sqrt(5), x) == x**2 - 45 assert minimal_polynomial(4*sqrt(6), x) == x**2 - 96 assert minimal_polynomial(2*sqrt(2) + 3, x) == x**2 - 6*x + 1 assert minimal_polynomial(3*sqrt(5) + 6, x) == x**2 - 12*x - 9 assert minimal_polynomial(4*sqrt(6) + 7, x) == x**2 - 14*x - 47 assert minimal_polynomial(2*sqrt(2) - 3, x) == x**2 + 6*x + 1 assert minimal_polynomial(3*sqrt(5) - 6, x) == x**2 + 12*x - 9 assert minimal_polynomial(4*sqrt(6) - 7, x) == x**2 + 14*x - 47 assert minimal_polynomial(sqrt(1 + sqrt(6)), x) == x**4 - 2*x**2 - 5 assert minimal_polynomial(sqrt(I + sqrt(6)), x) == x**8 - 10*x**4 + 49 assert minimal_polynomial(2*I + sqrt(2 + I), x) == x**4 + 4*x**2 + 8*x + 37 assert minimal_polynomial(sqrt(2) + sqrt(3), x) == x**4 - 10*x**2 + 1 assert minimal_polynomial( sqrt(2) + sqrt(3) + sqrt(6), x) == x**4 - 22*x**2 - 48*x - 23 a = 1 - 9*sqrt(2) + 7*sqrt(3) assert minimal_polynomial( 1/a, x) == 392*x**4 - 1232*x**3 + 612*x**2 + 4*x - 1 assert minimal_polynomial( 1/sqrt(a), x) == 392*x**8 - 1232*x**6 + 612*x**4 + 4*x**2 - 1 raises(NotAlgebraic, lambda: minimal_polynomial(oo, x)) raises(NotAlgebraic, lambda: minimal_polynomial(2**y, x)) raises(NotAlgebraic, lambda: minimal_polynomial(sin(1), x)) assert minimal_polynomial(sqrt(2)).dummy_eq(x**2 - 2) assert minimal_polynomial(sqrt(2), x) == x**2 - 2 assert minimal_polynomial(sqrt(2), polys=True) == Poly(x**2 - 2) assert minimal_polynomial(sqrt(2), x, polys=True) == Poly(x**2 - 2, domain='QQ') assert minimal_polynomial(sqrt(2), x, polys=True, compose=False) == Poly(x**2 - 2, domain='QQ') a = AlgebraicNumber(sqrt(2)) b = AlgebraicNumber(sqrt(3)) assert minimal_polynomial(a, x) == x**2 - 2 assert minimal_polynomial(b, x) == x**2 - 3 assert minimal_polynomial(a, x, polys=True) == Poly(x**2 - 2, domain='QQ') assert minimal_polynomial(b, x, polys=True) == Poly(x**2 - 3, domain='QQ') assert minimal_polynomial(sqrt(a/2 + 17), x) == 2*x**4 - 68*x**2 + 577 assert minimal_polynomial(sqrt(b/2 + 17), x) == 4*x**4 - 136*x**2 + 1153 a, b = sqrt(2)/3 + 7, AlgebraicNumber(sqrt(2)/3 + 7) f = 81*x**8 - 2268*x**6 - 4536*x**5 + 22644*x**4 + 63216*x**3 - \ 31608*x**2 - 189648*x + 141358 assert minimal_polynomial(sqrt(a) + sqrt(sqrt(a)), x) == f assert minimal_polynomial(sqrt(b) + sqrt(sqrt(b)), x) == f assert minimal_polynomial( a**Q(3, 2), x) == 729*x**4 - 506898*x**2 + 84604519 # issue 5994 eq = S(''' -1/(800*sqrt(-1/240 + 1/(18000*(-1/17280000 + sqrt(15)*I/28800000)**(1/3)) + 2*(-1/17280000 + sqrt(15)*I/28800000)**(1/3)))''') assert minimal_polynomial(eq, x) == 8000*x**2 - 1 ex = (sqrt(5)*sqrt(I)/(5*sqrt(1 + 125*I)) + 25*sqrt(5)/(I**Q(5,2)*(1 + 125*I)**Q(3,2)) + 3125*sqrt(5)/(I**Q(11,2)*(1 + 125*I)**Q(3,2)) + 5*I*sqrt(1 - I/125)) mp = minimal_polynomial(ex, x) assert mp == 25*x**4 + 5000*x**2 + 250016 ex = 1 + sqrt(2) + sqrt(3) mp = minimal_polynomial(ex, x) assert mp == x**4 - 4*x**3 - 4*x**2 + 16*x - 8 ex = 1/(1 + sqrt(2) + sqrt(3)) mp = minimal_polynomial(ex, x) assert mp == 8*x**4 - 16*x**3 + 4*x**2 + 4*x - 1 p = (expand((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3))**Rational(1, 3) mp = minimal_polynomial(p, x) assert mp == x**8 - 8*x**7 - 56*x**6 + 448*x**5 + 480*x**4 - 5056*x**3 + 1984*x**2 + 7424*x - 3008 p = expand((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3) mp = minimal_polynomial(p, x) assert mp == x**8 - 512*x**7 - 118208*x**6 + 31131136*x**5 + 647362560*x**4 - 56026611712*x**3 + 116994310144*x**2 + 404854931456*x - 27216576512 assert minimal_polynomial(S("-sqrt(5)/2 - 1/2 + (-sqrt(5)/2 - 1/2)**2"), x) == x - 1 a = 1 + sqrt(2) assert minimal_polynomial((a*sqrt(2) + a)**3, x) == x**2 - 198*x + 1 p = 1/(1 + sqrt(2) + sqrt(3)) assert minimal_polynomial(p, x, compose=False) == 8*x**4 - 16*x**3 + 4*x**2 + 4*x - 1 p = 2/(1 + sqrt(2) + sqrt(3)) assert minimal_polynomial(p, x, compose=False) == x**4 - 4*x**3 + 2*x**2 + 4*x - 2 assert minimal_polynomial(1 + sqrt(2)*I, x, compose=False) == x**2 - 2*x + 3 assert minimal_polynomial(1/(1 + sqrt(2)) + 1, x, compose=False) == x**2 - 2 assert minimal_polynomial(sqrt(2)*I + I*(1 + sqrt(2)), x, compose=False) == x**4 + 18*x**2 + 49 # minimal polynomial of I assert minimal_polynomial(I, x, domain=QQ.algebraic_field(I)) == x - I K = QQ.algebraic_field(I*(sqrt(2) + 1)) assert minimal_polynomial(I, x, domain=K) == x - I assert minimal_polynomial(I, x, domain=QQ) == x**2 + 1 assert minimal_polynomial(I, x, domain='QQ(y)') == x**2 + 1 #issue 11553 assert minimal_polynomial(GoldenRatio, x) == x**2 - x - 1 assert minimal_polynomial(TribonacciConstant + 3, x) == x**3 - 10*x**2 + 32*x - 34 assert minimal_polynomial(GoldenRatio, x, domain=QQ.algebraic_field(sqrt(5))) == \ 2*x - sqrt(5) - 1 assert minimal_polynomial(TribonacciConstant, x, domain=QQ.algebraic_field(cbrt(19 - 3*sqrt(33)))) == \ 48*x - 19*(19 - 3*sqrt(33))**Rational(2, 3) - 3*sqrt(33)*(19 - 3*sqrt(33))**Rational(2, 3) \ - 16*(19 - 3*sqrt(33))**Rational(1, 3) - 16 # AlgebraicNumber with an alias. # Wester H24 phi = AlgebraicNumber(S.GoldenRatio.expand(func=True), alias='phi') assert minimal_polynomial(phi, x) == x**2 - x - 1 def test_minimal_polynomial_issue_19732(): # https://github.com/sympy/sympy/issues/19732 expr = (-280898097948878450887044002323982963174671632174995451265117559518123750720061943079105185551006003416773064305074191140286225850817291393988597615/(-488144716373031204149459129212782509078221364279079444636386844223983756114492222145074506571622290776245390771587888364089507840000000*sqrt(238368341569)*sqrt(S(11918417078450)/63568729 - 24411360*sqrt(238368341569)/63568729) + 238326799225996604451373809274348704114327860564921529846705817404208077866956345381951726531296652901169111729944612727047670549086208000000*sqrt(S(11918417078450)/63568729 - 24411360*sqrt(238368341569)/63568729)) - 180561807339168676696180573852937120123827201075968945871075967679148461189459480842956689723484024031016208588658753107/(-59358007109636562851035004992802812513575019937126272896569856090962677491318275291141463850327474176000000*sqrt(238368341569)*sqrt(S(11918417078450)/63568729 - 24411360*sqrt(238368341569)/63568729) + 28980348180319251787320809875930301310576055074938369007463004788921613896002936637780993064387310446267596800000*sqrt(S(11918417078450)/63568729 - 24411360*sqrt(238368341569)/63568729))) poly = (2151288870990266634727173620565483054187142169311153766675688628985237817262915166497766867289157986631135400926544697981091151416655364879773546003475813114962656742744975460025956167152918469472166170500512008351638710934022160294849059721218824490226159355197136265032810944357335461128949781377875451881300105989490353140886315677977149440000000000000000000000*x**4 - 5773274155644072033773937864114266313663195672820501581692669271302387257492905909558846459600429795784309388968498783843631580008547382703258503404023153694528041873101120067477617592651525155101107144042679962433039557235772239171616433004024998230222455940044709064078962397144550855715640331680262171410099614469231080995436488414164502751395405398078353242072696360734131090111239998110773292915337556205692674790561090109440000000000000*x**2 + 211295968822207088328287206509522887719741955693091053353263782924470627623790749534705683380138972642560898936171035770539616881000369889020398551821767092685775598633794696371561234818461806577723412581353857653829324364446419444210520602157621008010129702779407422072249192199762604318993590841636967747488049176548615614290254356975376588506729604345612047361483789518445332415765213187893207704958013682516462853001964919444736320672860140355089) assert minimal_polynomial(expr, x) == poly def test_minimal_polynomial_hi_prec(): p = 1/sqrt(1 - 9*sqrt(2) + 7*sqrt(3) + Rational(1, 10)**30) mp = minimal_polynomial(p, x) # checked with Wolfram Alpha assert mp.coeff(x**6) == -1232000000000000000000000000001223999999999999999999999999999987999999999999999999999999999996000000000000000000000000000000 def test_minimal_polynomial_sq(): from sympy.core.add import Add from sympy.core.function import expand_multinomial p = expand_multinomial((1 + 5*sqrt(2) + 2*sqrt(3))**3) mp = minimal_polynomial(p**Rational(1, 3), x) assert mp == x**4 - 4*x**3 - 118*x**2 + 244*x + 1321 p = expand_multinomial((1 + sqrt(2) - 2*sqrt(3) + sqrt(7))**3) mp = minimal_polynomial(p**Rational(1, 3), x) assert mp == x**8 - 8*x**7 - 56*x**6 + 448*x**5 + 480*x**4 - 5056*x**3 + 1984*x**2 + 7424*x - 3008 p = Add(*[sqrt(i) for i in range(1, 12)]) mp = minimal_polynomial(p, x) assert mp.subs({x: 0}) == -71965773323122507776 def test_minpoly_compose(): # issue 6868 eq = S(''' -1/(800*sqrt(-1/240 + 1/(18000*(-1/17280000 + sqrt(15)*I/28800000)**(1/3)) + 2*(-1/17280000 + sqrt(15)*I/28800000)**(1/3)))''') mp = minimal_polynomial(eq + 3, x) assert mp == 8000*x**2 - 48000*x + 71999 # issue 5888 assert minimal_polynomial(exp(I*pi/8), x) == x**8 + 1 mp = minimal_polynomial(sin(pi/7) + sqrt(2), x) assert mp == 4096*x**12 - 63488*x**10 + 351488*x**8 - 826496*x**6 + \ 770912*x**4 - 268432*x**2 + 28561 mp = minimal_polynomial(cos(pi/7) + sqrt(2), x) assert mp == 64*x**6 - 64*x**5 - 432*x**4 + 304*x**3 + 712*x**2 - \ 232*x - 239 mp = minimal_polynomial(exp(I*pi/7) + sqrt(2), x) assert mp == x**12 - 2*x**11 - 9*x**10 + 16*x**9 + 43*x**8 - 70*x**7 - 97*x**6 + 126*x**5 + 211*x**4 - 212*x**3 - 37*x**2 + 142*x + 127 mp = minimal_polynomial(sin(pi/7) + sqrt(2), x) assert mp == 4096*x**12 - 63488*x**10 + 351488*x**8 - 826496*x**6 + \ 770912*x**4 - 268432*x**2 + 28561 mp = minimal_polynomial(cos(pi/7) + sqrt(2), x) assert mp == 64*x**6 - 64*x**5 - 432*x**4 + 304*x**3 + 712*x**2 - \ 232*x - 239 mp = minimal_polynomial(exp(I*pi/7) + sqrt(2), x) assert mp == x**12 - 2*x**11 - 9*x**10 + 16*x**9 + 43*x**8 - 70*x**7 - 97*x**6 + 126*x**5 + 211*x**4 - 212*x**3 - 37*x**2 + 142*x + 127 mp = minimal_polynomial(exp(I*pi*Rational(2, 7)), x) assert mp == x**6 + x**5 + x**4 + x**3 + x**2 + x + 1 mp = minimal_polynomial(exp(I*pi*Rational(2, 15)), x) assert mp == x**8 - x**7 + x**5 - x**4 + x**3 - x + 1 mp = minimal_polynomial(cos(pi*Rational(2, 7)), x) assert mp == 8*x**3 + 4*x**2 - 4*x - 1 mp = minimal_polynomial(sin(pi*Rational(2, 7)), x) ex = (5*cos(pi*Rational(2, 7)) - 7)/(9*cos(pi/7) - 5*cos(pi*Rational(3, 7))) mp = minimal_polynomial(ex, x) assert mp == x**3 + 2*x**2 - x - 1 assert minimal_polynomial(-1/(2*cos(pi/7)), x) == x**3 + 2*x**2 - x - 1 assert minimal_polynomial(sin(pi*Rational(2, 15)), x) == \ 256*x**8 - 448*x**6 + 224*x**4 - 32*x**2 + 1 assert minimal_polynomial(sin(pi*Rational(5, 14)), x) == 8*x**3 - 4*x**2 - 4*x + 1 assert minimal_polynomial(cos(pi/15), x) == 16*x**4 + 8*x**3 - 16*x**2 - 8*x + 1 ex = rootof(x**3 +x*4 + 1, 0) mp = minimal_polynomial(ex, x) assert mp == x**3 + 4*x + 1 mp = minimal_polynomial(ex + 1, x) assert mp == x**3 - 3*x**2 + 7*x - 4 assert minimal_polynomial(exp(I*pi/3), x) == x**2 - x + 1 assert minimal_polynomial(exp(I*pi/4), x) == x**4 + 1 assert minimal_polynomial(exp(I*pi/6), x) == x**4 - x**2 + 1 assert minimal_polynomial(exp(I*pi/9), x) == x**6 - x**3 + 1 assert minimal_polynomial(exp(I*pi/10), x) == x**8 - x**6 + x**4 - x**2 + 1 assert minimal_polynomial(sin(pi/9), x) == 64*x**6 - 96*x**4 + 36*x**2 - 3 assert minimal_polynomial(sin(pi/11), x) == 1024*x**10 - 2816*x**8 + \ 2816*x**6 - 1232*x**4 + 220*x**2 - 11 ex = 2**Rational(1, 3)*exp(Rational(2, 3)*I*pi) assert minimal_polynomial(ex, x) == x**3 - 2 raises(NotAlgebraic, lambda: minimal_polynomial(cos(pi*sqrt(2)), x)) raises(NotAlgebraic, lambda: minimal_polynomial(sin(pi*sqrt(2)), x)) raises(NotAlgebraic, lambda: minimal_polynomial(exp(I*pi*sqrt(2)), x)) # issue 5934 ex = 1/(-36000 - 7200*sqrt(5) + (12*sqrt(10)*sqrt(sqrt(5) + 5) + 24*sqrt(10)*sqrt(-sqrt(5) + 5))**2) + 1 raises(ZeroDivisionError, lambda: minimal_polynomial(ex, x)) ex = sqrt(1 + 2**Rational(1,3)) + sqrt(1 + 2**Rational(1,4)) + sqrt(2) mp = minimal_polynomial(ex, x) assert degree(mp) == 48 and mp.subs({x:0}) == -16630256576 ex = tan(pi/5, evaluate=False) mp = minimal_polynomial(ex, x) assert mp == x**4 - 10*x**2 + 5 assert mp.subs(x, tan(pi/5)).is_zero ex = tan(pi/6, evaluate=False) mp = minimal_polynomial(ex, x) assert mp == 3*x**2 - 1 assert mp.subs(x, tan(pi/6)).is_zero ex = tan(pi/10, evaluate=False) mp = minimal_polynomial(ex, x) assert mp == 5*x**4 - 10*x**2 + 1 assert mp.subs(x, tan(pi/10)).is_zero raises(NotAlgebraic, lambda: minimal_polynomial(tan(pi*sqrt(2)), x)) def test_minpoly_issue_7113(): # see discussion in https://github.com/sympy/sympy/pull/2234 from sympy.simplify.simplify import nsimplify r = nsimplify(pi, tolerance=0.000000001) mp = minimal_polynomial(r, x) assert mp == 1768292677839237920489538677417507171630859375*x**109 - \ 2734577732179183863586489182929671773182898498218854181690460140337930774573792597743853652058046464 def test_minpoly_issue_7574(): ex = -(-1)**Rational(1, 3) + (-1)**Rational(2,3) assert minimal_polynomial(ex, x) == x + 1 def test_choose_factor(): # Test that this does not enter an infinite loop: bad_factors = [Poly(x-2, x), Poly(x+2, x)] raises(NotImplementedError, lambda: _choose_factor(bad_factors, x, sqrt(3))) def test_primitive_element(): assert primitive_element([sqrt(2)], x) == (x**2 - 2, [1]) assert primitive_element( [sqrt(2), sqrt(3)], x) == (x**4 - 10*x**2 + 1, [1, 1]) assert primitive_element([sqrt(2)], x, polys=True) == (Poly(x**2 - 2, domain='QQ'), [1]) assert primitive_element([sqrt( 2), sqrt(3)], x, polys=True) == (Poly(x**4 - 10*x**2 + 1, domain='QQ'), [1, 1]) assert primitive_element( [sqrt(2)], x, ex=True) == (x**2 - 2, [1], [[1, 0]]) assert primitive_element([sqrt(2), sqrt(3)], x, ex=True) == \ (x**4 - 10*x**2 + 1, [1, 1], [[Q(1, 2), 0, -Q(9, 2), 0], [- Q(1, 2), 0, Q(11, 2), 0]]) assert primitive_element( [sqrt(2)], x, ex=True, polys=True) == (Poly(x**2 - 2, domain='QQ'), [1], [[1, 0]]) assert primitive_element([sqrt(2), sqrt(3)], x, ex=True, polys=True) == \ (Poly(x**4 - 10*x**2 + 1, domain='QQ'), [1, 1], [[Q(1, 2), 0, -Q(9, 2), 0], [-Q(1, 2), 0, Q(11, 2), 0]]) assert primitive_element([sqrt(2)], polys=True) == (Poly(x**2 - 2), [1]) raises(ValueError, lambda: primitive_element([], x, ex=False)) raises(ValueError, lambda: primitive_element([], x, ex=True)) # Issue 14117 a, b = I*sqrt(2*sqrt(2) + 3), I*sqrt(-2*sqrt(2) + 3) assert primitive_element([a, b, I], x) == (x**4 + 6*x**2 + 1, [1, 0, 0]) def test_minpoly_fraction_field(): assert minimal_polynomial(1/x, y) == -x*y + 1 assert minimal_polynomial(1 / (x + 1), y) == (x + 1)*y - 1 assert minimal_polynomial(sqrt(x), y) == y**2 - x assert minimal_polynomial(sqrt(x + 1), y) == y**2 - x - 1 assert minimal_polynomial(sqrt(x) / x, y) == x*y**2 - 1 assert minimal_polynomial(sqrt(2) * sqrt(x), y) == y**2 - 2 * x assert minimal_polynomial(sqrt(2) + sqrt(x), y) == \ y**4 + (-2*x - 4)*y**2 + x**2 - 4*x + 4 assert minimal_polynomial(x**Rational(1,3), y) == y**3 - x assert minimal_polynomial(x**Rational(1,3) + sqrt(x), y) == \ y**6 - 3*x*y**4 - 2*x*y**3 + 3*x**2*y**2 - 6*x**2*y - x**3 + x**2 assert minimal_polynomial(sqrt(x) / z, y) == z**2*y**2 - x assert minimal_polynomial(sqrt(x) / (z + 1), y) == (z**2 + 2*z + 1)*y**2 - x assert minimal_polynomial(1/x, y, polys=True) == Poly(-x*y + 1, y, domain='ZZ(x)') assert minimal_polynomial(1 / (x + 1), y, polys=True) == \ Poly((x + 1)*y - 1, y, domain='ZZ(x)') assert minimal_polynomial(sqrt(x), y, polys=True) == Poly(y**2 - x, y, domain='ZZ(x)') assert minimal_polynomial(sqrt(x) / z, y, polys=True) == \ Poly(z**2*y**2 - x, y, domain='ZZ(x, z)') # this is (sqrt(1 + x**3)/x).integrate(x).diff(x) - sqrt(1 + x**3)/x a = sqrt(x)/sqrt(1 + x**(-3)) - sqrt(x**3 + 1)/x + 1/(x**Rational(5, 2)* \ (1 + x**(-3))**Rational(3, 2)) + 1/(x**Rational(11, 2)*(1 + x**(-3))**Rational(3, 2)) assert minimal_polynomial(a, y) == y raises(NotAlgebraic, lambda: minimal_polynomial(exp(x), y)) raises(GeneratorsError, lambda: minimal_polynomial(sqrt(x), x)) raises(GeneratorsError, lambda: minimal_polynomial(sqrt(x) - y, x)) raises(NotImplementedError, lambda: minimal_polynomial(sqrt(x), y, compose=False)) @slow def test_minpoly_fraction_field_slow(): assert minimal_polynomial(minimal_polynomial(sqrt(x**Rational(1,5) - 1), y).subs(y, sqrt(x**Rational(1,5) - 1)), z) == z def test_minpoly_domain(): assert minimal_polynomial(sqrt(2), x, domain=QQ.algebraic_field(sqrt(2))) == \ x - sqrt(2) assert minimal_polynomial(sqrt(8), x, domain=QQ.algebraic_field(sqrt(2))) == \ x - 2*sqrt(2) assert minimal_polynomial(sqrt(Rational(3,2)), x, domain=QQ.algebraic_field(sqrt(2))) == 2*x**2 - 3 raises(NotAlgebraic, lambda: minimal_polynomial(y, x, domain=QQ)) def test_issue_14831(): a = -2*sqrt(2)*sqrt(12*sqrt(2) + 17) assert minimal_polynomial(a, x) == x**2 + 16*x - 8 e = (-3*sqrt(12*sqrt(2) + 17) + 12*sqrt(2) + 17 - 2*sqrt(2)*sqrt(12*sqrt(2) + 17)) assert minimal_polynomial(e, x) == x def test_issue_18248(): assert nonlinsolve([x*y**3-sqrt(2)/3, x*y**6-4/(9*(sqrt(3)))],x,y) == \ FiniteSet((sqrt(3)/2, sqrt(6)/3), (sqrt(3)/2, -sqrt(6)/6 - sqrt(2)*I/2), (sqrt(3)/2, -sqrt(6)/6 + sqrt(2)*I/2)) def test_issue_13230(): c1 = Circle(Point2D(3, sqrt(5)), 5) c2 = Circle(Point2D(4, sqrt(7)), 6) assert intersection(c1, c2) == [Point2D(-1 + (-sqrt(7) + sqrt(5))*(-2*sqrt(7)/29 + 9*sqrt(5)/29 + sqrt(196*sqrt(35) + 1941)/29), -2*sqrt(7)/29 + 9*sqrt(5)/29 + sqrt(196*sqrt(35) + 1941)/29), Point2D(-1 + (-sqrt(7) + sqrt(5))*(-sqrt(196*sqrt(35) + 1941)/29 - 2*sqrt(7)/29 + 9*sqrt(5)/29), -sqrt(196*sqrt(35) + 1941)/29 - 2*sqrt(7)/29 + 9*sqrt(5)/29)] def test_issue_19760(): e = 1/(sqrt(1 + sqrt(2)) - sqrt(2)*sqrt(1 + sqrt(2))) + 1 mp_expected = x**4 - 4*x**3 + 4*x**2 - 2 for comp in (True, False): mp = Poly(minimal_polynomial(e, compose=comp)) assert mp(x) == mp_expected, "minimal_polynomial(e, compose=%s) = %s; %s expected" % (comp, mp(x), mp_expected) def test_issue_20163(): assert apart(1/(x**6+1), extension=[sqrt(3), I]) == \ (sqrt(3) + I)/(2*x + sqrt(3) + I)/6 + \ (sqrt(3) - I)/(2*x + sqrt(3) - I)/6 - \ (sqrt(3) - I)/(2*x - sqrt(3) + I)/6 - \ (sqrt(3) + I)/(2*x - sqrt(3) - I)/6 + \ I/(x + I)/6 - I/(x - I)/6
bb033ce2c807d9aeb78bc5791edb06ddd8be458f5e9f4d9f33cd053f37b4746f
"""Tests for numberfield isomorphisms. """ from sympy.core.numbers import (AlgebraicNumber, I, Rational) from sympy.core.singleton import S from sympy.functions.elementary.miscellaneous import sqrt from sympy.testing.pytest import raises from sympy.polys.numberfields.isomorphism import ( is_isomorphism_possible, field_isomorphism_pslq, field_isomorphism, ) Q = Rational def test_field_isomorphism_pslq(): a = AlgebraicNumber(I) b = AlgebraicNumber(I*sqrt(3)) raises(NotImplementedError, lambda: field_isomorphism_pslq(a, b)) a = AlgebraicNumber(sqrt(2)) b = AlgebraicNumber(sqrt(3)) c = AlgebraicNumber(sqrt(7)) d = AlgebraicNumber(sqrt(2) + sqrt(3)) e = AlgebraicNumber(sqrt(2) + sqrt(3) + sqrt(7)) assert field_isomorphism_pslq(a, a) == [1, 0] assert field_isomorphism_pslq(a, b) is None assert field_isomorphism_pslq(a, c) is None assert field_isomorphism_pslq(a, d) == [Q(1, 2), 0, -Q(9, 2), 0] assert field_isomorphism_pslq( a, e) == [Q(1, 80), 0, -Q(1, 2), 0, Q(59, 20), 0] assert field_isomorphism_pslq(b, a) is None assert field_isomorphism_pslq(b, b) == [1, 0] assert field_isomorphism_pslq(b, c) is None assert field_isomorphism_pslq(b, d) == [-Q(1, 2), 0, Q(11, 2), 0] assert field_isomorphism_pslq(b, e) == [-Q( 3, 640), 0, Q(67, 320), 0, -Q(297, 160), 0, Q(313, 80), 0] assert field_isomorphism_pslq(c, a) is None assert field_isomorphism_pslq(c, b) is None assert field_isomorphism_pslq(c, c) == [1, 0] assert field_isomorphism_pslq(c, d) is None assert field_isomorphism_pslq(c, e) == [Q( 3, 640), 0, -Q(71, 320), 0, Q(377, 160), 0, -Q(469, 80), 0] assert field_isomorphism_pslq(d, a) is None assert field_isomorphism_pslq(d, b) is None assert field_isomorphism_pslq(d, c) is None assert field_isomorphism_pslq(d, d) == [1, 0] assert field_isomorphism_pslq(d, e) == [-Q( 3, 640), 0, Q(71, 320), 0, -Q(377, 160), 0, Q(549, 80), 0] assert field_isomorphism_pslq(e, a) is None assert field_isomorphism_pslq(e, b) is None assert field_isomorphism_pslq(e, c) is None assert field_isomorphism_pslq(e, d) is None assert field_isomorphism_pslq(e, e) == [1, 0] f = AlgebraicNumber(3*sqrt(2) + 8*sqrt(7) - 5) assert field_isomorphism_pslq( f, e) == [Q(3, 80), 0, -Q(139, 80), 0, Q(347, 20), 0, -Q(761, 20), -5] def test_field_isomorphism(): assert field_isomorphism(3, sqrt(2)) == [3] assert field_isomorphism( I*sqrt(3), I*sqrt(3)/2) == [ 2, 0] assert field_isomorphism(-I*sqrt(3), I*sqrt(3)/2) == [-2, 0] assert field_isomorphism( I*sqrt(3), -I*sqrt(3)/2) == [-2, 0] assert field_isomorphism(-I*sqrt(3), -I*sqrt(3)/2) == [ 2, 0] assert field_isomorphism( 2*I*sqrt(3)/7, 5*I*sqrt(3)/3) == [ Rational(6, 35), 0] assert field_isomorphism(-2*I*sqrt(3)/7, 5*I*sqrt(3)/3) == [Rational(-6, 35), 0] assert field_isomorphism( 2*I*sqrt(3)/7, -5*I*sqrt(3)/3) == [Rational(-6, 35), 0] assert field_isomorphism(-2*I*sqrt(3)/7, -5*I*sqrt(3)/3) == [ Rational(6, 35), 0] assert field_isomorphism( 2*I*sqrt(3)/7 + 27, 5*I*sqrt(3)/3) == [ Rational(6, 35), 27] assert field_isomorphism( -2*I*sqrt(3)/7 + 27, 5*I*sqrt(3)/3) == [Rational(-6, 35), 27] assert field_isomorphism( 2*I*sqrt(3)/7 + 27, -5*I*sqrt(3)/3) == [Rational(-6, 35), 27] assert field_isomorphism( -2*I*sqrt(3)/7 + 27, -5*I*sqrt(3)/3) == [ Rational(6, 35), 27] p = AlgebraicNumber( sqrt(2) + sqrt(3)) q = AlgebraicNumber(-sqrt(2) + sqrt(3)) r = AlgebraicNumber( sqrt(2) - sqrt(3)) s = AlgebraicNumber(-sqrt(2) - sqrt(3)) pos_coeffs = [ S.Half, S.Zero, Rational(-9, 2), S.Zero] neg_coeffs = [Rational(-1, 2), S.Zero, Rational(9, 2), S.Zero] a = AlgebraicNumber(sqrt(2)) assert is_isomorphism_possible(a, p) is True assert is_isomorphism_possible(a, q) is True assert is_isomorphism_possible(a, r) is True assert is_isomorphism_possible(a, s) is True assert field_isomorphism(a, p, fast=True) == pos_coeffs assert field_isomorphism(a, q, fast=True) == neg_coeffs assert field_isomorphism(a, r, fast=True) == pos_coeffs assert field_isomorphism(a, s, fast=True) == neg_coeffs assert field_isomorphism(a, p, fast=False) == pos_coeffs assert field_isomorphism(a, q, fast=False) == neg_coeffs assert field_isomorphism(a, r, fast=False) == pos_coeffs assert field_isomorphism(a, s, fast=False) == neg_coeffs a = AlgebraicNumber(-sqrt(2)) assert is_isomorphism_possible(a, p) is True assert is_isomorphism_possible(a, q) is True assert is_isomorphism_possible(a, r) is True assert is_isomorphism_possible(a, s) is True assert field_isomorphism(a, p, fast=True) == neg_coeffs assert field_isomorphism(a, q, fast=True) == pos_coeffs assert field_isomorphism(a, r, fast=True) == neg_coeffs assert field_isomorphism(a, s, fast=True) == pos_coeffs assert field_isomorphism(a, p, fast=False) == neg_coeffs assert field_isomorphism(a, q, fast=False) == pos_coeffs assert field_isomorphism(a, r, fast=False) == neg_coeffs assert field_isomorphism(a, s, fast=False) == pos_coeffs pos_coeffs = [ S.Half, S.Zero, Rational(-11, 2), S.Zero] neg_coeffs = [Rational(-1, 2), S.Zero, Rational(11, 2), S.Zero] a = AlgebraicNumber(sqrt(3)) assert is_isomorphism_possible(a, p) is True assert is_isomorphism_possible(a, q) is True assert is_isomorphism_possible(a, r) is True assert is_isomorphism_possible(a, s) is True assert field_isomorphism(a, p, fast=True) == neg_coeffs assert field_isomorphism(a, q, fast=True) == neg_coeffs assert field_isomorphism(a, r, fast=True) == pos_coeffs assert field_isomorphism(a, s, fast=True) == pos_coeffs assert field_isomorphism(a, p, fast=False) == neg_coeffs assert field_isomorphism(a, q, fast=False) == neg_coeffs assert field_isomorphism(a, r, fast=False) == pos_coeffs assert field_isomorphism(a, s, fast=False) == pos_coeffs a = AlgebraicNumber(-sqrt(3)) assert is_isomorphism_possible(a, p) is True assert is_isomorphism_possible(a, q) is True assert is_isomorphism_possible(a, r) is True assert is_isomorphism_possible(a, s) is True assert field_isomorphism(a, p, fast=True) == pos_coeffs assert field_isomorphism(a, q, fast=True) == pos_coeffs assert field_isomorphism(a, r, fast=True) == neg_coeffs assert field_isomorphism(a, s, fast=True) == neg_coeffs assert field_isomorphism(a, p, fast=False) == pos_coeffs assert field_isomorphism(a, q, fast=False) == pos_coeffs assert field_isomorphism(a, r, fast=False) == neg_coeffs assert field_isomorphism(a, s, fast=False) == neg_coeffs pos_coeffs = [ Rational(3, 2), S.Zero, Rational(-33, 2), -S(8)] neg_coeffs = [Rational(-3, 2), S.Zero, Rational(33, 2), -S(8)] a = AlgebraicNumber(3*sqrt(3) - 8) assert is_isomorphism_possible(a, p) is True assert is_isomorphism_possible(a, q) is True assert is_isomorphism_possible(a, r) is True assert is_isomorphism_possible(a, s) is True assert field_isomorphism(a, p, fast=True) == neg_coeffs assert field_isomorphism(a, q, fast=True) == neg_coeffs assert field_isomorphism(a, r, fast=True) == pos_coeffs assert field_isomorphism(a, s, fast=True) == pos_coeffs assert field_isomorphism(a, p, fast=False) == neg_coeffs assert field_isomorphism(a, q, fast=False) == neg_coeffs assert field_isomorphism(a, r, fast=False) == pos_coeffs assert field_isomorphism(a, s, fast=False) == pos_coeffs a = AlgebraicNumber(3*sqrt(2) + 2*sqrt(3) + 1) pos_1_coeffs = [ S.Half, S.Zero, Rational(-5, 2), S.One] neg_5_coeffs = [Rational(-5, 2), S.Zero, Rational(49, 2), S.One] pos_5_coeffs = [ Rational(5, 2), S.Zero, Rational(-49, 2), S.One] neg_1_coeffs = [Rational(-1, 2), S.Zero, Rational(5, 2), S.One] assert is_isomorphism_possible(a, p) is True assert is_isomorphism_possible(a, q) is True assert is_isomorphism_possible(a, r) is True assert is_isomorphism_possible(a, s) is True assert field_isomorphism(a, p, fast=True) == pos_1_coeffs assert field_isomorphism(a, q, fast=True) == neg_5_coeffs assert field_isomorphism(a, r, fast=True) == pos_5_coeffs assert field_isomorphism(a, s, fast=True) == neg_1_coeffs assert field_isomorphism(a, p, fast=False) == pos_1_coeffs assert field_isomorphism(a, q, fast=False) == neg_5_coeffs assert field_isomorphism(a, r, fast=False) == pos_5_coeffs assert field_isomorphism(a, s, fast=False) == neg_1_coeffs a = AlgebraicNumber(sqrt(2)) b = AlgebraicNumber(sqrt(3)) c = AlgebraicNumber(sqrt(7)) assert is_isomorphism_possible(a, b) is True assert is_isomorphism_possible(b, a) is True assert is_isomorphism_possible(c, p) is False assert field_isomorphism(sqrt(2), sqrt(3), fast=True) is None assert field_isomorphism(sqrt(3), sqrt(2), fast=True) is None assert field_isomorphism(sqrt(2), sqrt(3), fast=False) is None assert field_isomorphism(sqrt(3), sqrt(2), fast=False) is None
8b720740d5d007214c0af8e3c9dfe1c302520a2523d33d6b4704bd5852b60057
from sympy.core.symbol import symbols from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.polys import QQ, ZZ from sympy.polys.polytools import Poly from sympy.polys.polyerrors import NotInvertible from sympy.polys.agca.extensions import FiniteExtension from sympy.polys.domainmatrix import DomainMatrix from sympy.testing.pytest import raises from sympy.abc import x, y, t def test_FiniteExtension(): # Gaussian integers A = FiniteExtension(Poly(x**2 + 1, x)) assert A.rank == 2 assert str(A) == 'ZZ[x]/(x**2 + 1)' i = A.generator assert i.parent() is A assert i*i == A(-1) raises(TypeError, lambda: i*()) assert A.basis == (A.one, i) assert A(1) == A.one assert i**2 == A(-1) assert i**2 != -1 # no coercion assert (2 + i)*(1 - i) == 3 - i assert (1 + i)**8 == A(16) assert A(1).inverse() == A(1) raises(NotImplementedError, lambda: A(2).inverse()) # Finite field of order 27 F = FiniteExtension(Poly(x**3 - x + 1, x, modulus=3)) assert F.rank == 3 a = F.generator # also generates the cyclic group F - {0} assert F.basis == (F(1), a, a**2) assert a**27 == a assert a**26 == F(1) assert a**13 == F(-1) assert a**9 == a + 1 assert a**3 == a - 1 assert a**6 == a**2 + a + 1 assert F(x**2 + x).inverse() == 1 - a assert F(x + 2)**(-1) == F(x + 2).inverse() assert a**19 * a**(-19) == F(1) assert (a - 1) / (2*a**2 - 1) == a**2 + 1 assert (a - 1) // (2*a**2 - 1) == a**2 + 1 assert 2/(a**2 + 1) == a**2 - a + 1 assert (a**2 + 1)/2 == -a**2 - 1 raises(NotInvertible, lambda: F(0).inverse()) # Function field of an elliptic curve K = FiniteExtension(Poly(t**2 - x**3 - x + 1, t, field=True)) assert K.rank == 2 assert str(K) == 'ZZ(x)[t]/(t**2 - x**3 - x + 1)' y = K.generator c = 1/(x**3 - x**2 + x - 1) assert ((y + x)*(y - x)).inverse() == K(c) assert (y + x)*(y - x)*c == K(1) # explicit inverse of y + x def test_FiniteExtension_eq_hash(): # Test eq and hash p1 = Poly(x**2 - 2, x, domain=ZZ) p2 = Poly(x**2 - 2, x, domain=QQ) K1 = FiniteExtension(p1) K2 = FiniteExtension(p2) assert K1 == FiniteExtension(Poly(x**2 - 2)) assert K2 != FiniteExtension(Poly(x**2 - 2)) assert len({K1, K2, FiniteExtension(p1)}) == 2 def test_FiniteExtension_mod(): # Test mod K = FiniteExtension(Poly(x**3 + 1, x, domain=QQ)) xf = K(x) assert (xf**2 - 1) % 1 == K.zero assert 1 % (xf**2 - 1) == K.zero assert (xf**2 - 1) / (xf - 1) == xf + 1 assert (xf**2 - 1) // (xf - 1) == xf + 1 assert (xf**2 - 1) % (xf - 1) == K.zero raises(ZeroDivisionError, lambda: (xf**2 - 1) % 0) raises(TypeError, lambda: xf % []) raises(TypeError, lambda: [] % xf) # Test mod over ring K = FiniteExtension(Poly(x**3 + 1, x, domain=ZZ)) xf = K(x) assert (xf**2 - 1) % 1 == K.zero raises(NotImplementedError, lambda: (xf**2 - 1) % (xf - 1)) def test_FiniteExtension_from_sympy(): # Test to_sympy/from_sympy K = FiniteExtension(Poly(x**3 + 1, x, domain=ZZ)) xf = K(x) assert K.from_sympy(x) == xf assert K.to_sympy(xf) == x def test_FiniteExtension_set_domain(): KZ = FiniteExtension(Poly(x**2 + 1, x, domain='ZZ')) KQ = FiniteExtension(Poly(x**2 + 1, x, domain='QQ')) assert KZ.set_domain(QQ) == KQ def test_FiniteExtension_exquo(): # Test exquo K = FiniteExtension(Poly(x**4 + 1)) xf = K(x) assert K.exquo(xf**2 - 1, xf - 1) == xf + 1 def test_FiniteExtension_convert(): # Test from_MonogenicFiniteExtension K1 = FiniteExtension(Poly(x**2 + 1)) K2 = QQ[x] x1, x2 = K1(x), K2(x) assert K1.convert(x2) == x1 assert K2.convert(x1) == x2 K = FiniteExtension(Poly(x**2 - 1, domain=QQ)) assert K.convert_from(QQ(1, 2), QQ) == K.one/2 def test_FiniteExtension_division_ring(): # Test division in FiniteExtension over a ring KQ = FiniteExtension(Poly(x**2 - 1, x, domain=QQ)) KZ = FiniteExtension(Poly(x**2 - 1, x, domain=ZZ)) KQt = FiniteExtension(Poly(x**2 - 1, x, domain=QQ[t])) KQtf = FiniteExtension(Poly(x**2 - 1, x, domain=QQ.frac_field(t))) assert KQ.is_Field is True assert KZ.is_Field is False assert KQt.is_Field is False assert KQtf.is_Field is True for K in KQ, KZ, KQt, KQtf: xK = K.convert(x) assert xK / K.one == xK assert xK // K.one == xK assert xK % K.one == K.zero raises(ZeroDivisionError, lambda: xK / K.zero) raises(ZeroDivisionError, lambda: xK // K.zero) raises(ZeroDivisionError, lambda: xK % K.zero) if K.is_Field: assert xK / xK == K.one assert xK // xK == K.one assert xK % xK == K.zero else: raises(NotImplementedError, lambda: xK / xK) raises(NotImplementedError, lambda: xK // xK) raises(NotImplementedError, lambda: xK % xK) def test_FiniteExtension_Poly(): K = FiniteExtension(Poly(x**2 - 2)) p = Poly(x, y, domain=K) assert p.domain == K assert p.as_expr() == x assert (p**2).as_expr() == 2 K = FiniteExtension(Poly(x**2 - 2, x, domain=QQ)) K2 = FiniteExtension(Poly(t**2 - 2, t, domain=K)) assert str(K2) == 'QQ[x]/(x**2 - 2)[t]/(t**2 - 2)' eK = K2.convert(x + t) assert K2.to_sympy(eK) == x + t assert K2.to_sympy(eK ** 2) == 4 + 2*x*t p = Poly(x + t, y, domain=K2) assert p**2 == Poly(4 + 2*x*t, y, domain=K2) def test_FiniteExtension_sincos_jacobian(): # Use FiniteExtensino to compute the Jacobian of a matrix involving sin # and cos of different symbols. r, p, t = symbols('rho, phi, theta') elements = [ [sin(p)*cos(t), r*cos(p)*cos(t), -r*sin(p)*sin(t)], [sin(p)*sin(t), r*cos(p)*sin(t), r*sin(p)*cos(t)], [ cos(p), -r*sin(p), 0], ] def make_extension(K): K = FiniteExtension(Poly(sin(p)**2+cos(p)**2-1, sin(p), domain=K[cos(p)])) K = FiniteExtension(Poly(sin(t)**2+cos(t)**2-1, sin(t), domain=K[cos(t)])) return K Ksc1 = make_extension(ZZ[r]) Ksc2 = make_extension(ZZ)[r] for K in [Ksc1, Ksc2]: elements_K = [[K.convert(e) for e in row] for row in elements] J = DomainMatrix(elements_K, (3, 3), K) det = J.charpoly()[-1] * (-K.one)**3 assert det == K.convert(r**2*sin(p))
1dd7e673174456e7046ed7e6cd5abc8bfd701a88d3e5be431395487db4ccc779
"""Test modules.py code.""" from sympy.polys.agca.modules import FreeModule, ModuleOrder, FreeModulePolyRing from sympy.polys import CoercionFailed, QQ, lex, grlex, ilex, ZZ from sympy.abc import x, y, z from sympy.testing.pytest import raises from sympy.core.numbers import Rational def test_FreeModuleElement(): M = QQ.old_poly_ring(x).free_module(3) e = M.convert([1, x, x**2]) f = [QQ.old_poly_ring(x).convert(1), QQ.old_poly_ring(x).convert(x), QQ.old_poly_ring(x).convert(x**2)] assert list(e) == f assert f[0] == e[0] assert f[1] == e[1] assert f[2] == e[2] raises(IndexError, lambda: e[3]) g = M.convert([x, 0, 0]) assert e + g == M.convert([x + 1, x, x**2]) assert f + g == M.convert([x + 1, x, x**2]) assert -e == M.convert([-1, -x, -x**2]) assert e - g == M.convert([1 - x, x, x**2]) assert e != g assert M.convert([x, x, x]) / QQ.old_poly_ring(x).convert(x) == [1, 1, 1] R = QQ.old_poly_ring(x, order="ilex") assert R.free_module(1).convert([x]) / R.convert(x) == [1] def test_FreeModule(): M1 = FreeModule(QQ.old_poly_ring(x), 2) assert M1 == FreeModule(QQ.old_poly_ring(x), 2) assert M1 != FreeModule(QQ.old_poly_ring(y), 2) assert M1 != FreeModule(QQ.old_poly_ring(x), 3) M2 = FreeModule(QQ.old_poly_ring(x, order="ilex"), 2) assert [x, 1] in M1 assert [x] not in M1 assert [2, y] not in M1 assert [1/(x + 1), 2] not in M1 e = M1.convert([x, x**2 + 1]) X = QQ.old_poly_ring(x).convert(x) assert e == [X, X**2 + 1] assert e == [x, x**2 + 1] assert 2*e == [2*x, 2*x**2 + 2] assert e*2 == [2*x, 2*x**2 + 2] assert e/2 == [x/2, (x**2 + 1)/2] assert x*e == [x**2, x**3 + x] assert e*x == [x**2, x**3 + x] assert X*e == [x**2, x**3 + x] assert e*X == [x**2, x**3 + x] assert [x, 1] in M2 assert [x] not in M2 assert [2, y] not in M2 assert [1/(x + 1), 2] in M2 e = M2.convert([x, x**2 + 1]) X = QQ.old_poly_ring(x, order="ilex").convert(x) assert e == [X, X**2 + 1] assert e == [x, x**2 + 1] assert 2*e == [2*x, 2*x**2 + 2] assert e*2 == [2*x, 2*x**2 + 2] assert e/2 == [x/2, (x**2 + 1)/2] assert x*e == [x**2, x**3 + x] assert e*x == [x**2, x**3 + x] assert e/(1 + x) == [x/(1 + x), (x**2 + 1)/(1 + x)] assert X*e == [x**2, x**3 + x] assert e*X == [x**2, x**3 + x] M3 = FreeModule(QQ.old_poly_ring(x, y), 2) assert M3.convert(e) == M3.convert([x, x**2 + 1]) assert not M3.is_submodule(0) assert not M3.is_zero() raises(NotImplementedError, lambda: ZZ.old_poly_ring(x).free_module(2)) raises(NotImplementedError, lambda: FreeModulePolyRing(ZZ, 2)) raises(CoercionFailed, lambda: M1.convert(QQ.old_poly_ring(x).free_module(3) .convert([1, 2, 3]))) raises(CoercionFailed, lambda: M3.convert(1)) def test_ModuleOrder(): o1 = ModuleOrder(lex, grlex, False) o2 = ModuleOrder(ilex, lex, False) assert o1 == ModuleOrder(lex, grlex, False) assert (o1 != ModuleOrder(lex, grlex, False)) is False assert o1 != o2 assert o1((1, 2, 3)) == (1, (5, (2, 3))) assert o2((1, 2, 3)) == (-1, (2, 3)) def test_SubModulePolyRing_global(): R = QQ.old_poly_ring(x, y) F = R.free_module(3) Fd = F.submodule([1, 0, 0], [1, 2, 0], [1, 2, 3]) M = F.submodule([x**2 + y**2, 1, 0], [x, y, 1]) assert F == Fd assert Fd == F assert F != M assert M != F assert Fd != M assert M != Fd assert Fd == F.submodule(*F.basis()) assert Fd.is_full_module() assert not M.is_full_module() assert not Fd.is_zero() assert not M.is_zero() assert Fd.submodule().is_zero() assert M.contains([x**2 + y**2 + x, 1 + y, 1]) assert not M.contains([x**2 + y**2 + x, 1 + y, 2]) assert M.contains([y**2, 1 - x*y, -x]) assert not F.submodule([1 + x, 0, 0]) == F.submodule([1, 0, 0]) assert F.submodule([1, 0, 0], [0, 1, 0]).union(F.submodule([0, 0, 1])) == F assert not M.is_submodule(0) m = F.convert([x**2 + y**2, 1, 0]) n = M.convert(m) assert m.module is F assert n.module is M raises(ValueError, lambda: M.submodule([1, 0, 0])) raises(TypeError, lambda: M.union(1)) raises(ValueError, lambda: M.union(R.free_module(1).submodule([x]))) assert F.submodule([x, x, x]) != F.submodule([x, x, x], order="ilex") def test_SubModulePolyRing_local(): R = QQ.old_poly_ring(x, y, order=ilex) F = R.free_module(3) Fd = F.submodule([1 + x, 0, 0], [1 + y, 2 + 2*y, 0], [1, 2, 3]) M = F.submodule([x**2 + y**2, 1, 0], [x, y, 1]) assert F == Fd assert Fd == F assert F != M assert M != F assert Fd != M assert M != Fd assert Fd == F.submodule(*F.basis()) assert Fd.is_full_module() assert not M.is_full_module() assert not Fd.is_zero() assert not M.is_zero() assert Fd.submodule().is_zero() assert M.contains([x**2 + y**2 + x, 1 + y, 1]) assert not M.contains([x**2 + y**2 + x, 1 + y, 2]) assert M.contains([y**2, 1 - x*y, -x]) assert F.submodule([1 + x, 0, 0]) == F.submodule([1, 0, 0]) assert F.submodule( [1, 0, 0], [0, 1, 0]).union(F.submodule([0, 0, 1 + x*y])) == F raises(ValueError, lambda: M.submodule([1, 0, 0])) def test_SubModulePolyRing_nontriv_global(): R = QQ.old_poly_ring(x, y, z) F = R.free_module(1) def contains(I, f): return F.submodule(*[[g] for g in I]).contains([f]) assert contains([x, y], x) assert contains([x, y], x + y) assert not contains([x, y], 1) assert not contains([x, y], z) assert contains([x**2 + y, x**2 + x], x - y) assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x**2) assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**3) assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**4) assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x*y**2) assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x**4 + y**3 + 2*z*y*x) assert contains([x + y + z, x*y + x*z + y*z, x*y*z], x*y*z) assert contains([x, 1 + x + y, 5 - 7*y], 1) assert contains( [x**3 + y**3, y**3 + z**3, z**3 + x**3, x**2*y + x**2*z + y**2*z], x**3) assert not contains( [x**3 + y**3, y**3 + z**3, z**3 + x**3, x**2*y + x**2*z + y**2*z], x**2 + y**2) # compare local order assert not contains([x*(1 + x + y), y*(1 + z)], x) assert not contains([x*(1 + x + y), y*(1 + z)], x + y) def test_SubModulePolyRing_nontriv_local(): R = QQ.old_poly_ring(x, y, z, order=ilex) F = R.free_module(1) def contains(I, f): return F.submodule(*[[g] for g in I]).contains([f]) assert contains([x, y], x) assert contains([x, y], x + y) assert not contains([x, y], 1) assert not contains([x, y], z) assert contains([x**2 + y, x**2 + x], x - y) assert not contains([x + y + z, x*y + x*z + y*z, x*y*z], x**2) assert contains([x*(1 + x + y), y*(1 + z)], x) assert contains([x*(1 + x + y), y*(1 + z)], x + y) def test_syzygy(): R = QQ.old_poly_ring(x, y, z) M = R.free_module(1).submodule([x*y], [y*z], [x*z]) S = R.free_module(3).submodule([0, x, -y], [z, -x, 0]) assert M.syzygy_module() == S M2 = M / ([x*y*z],) S2 = R.free_module(3).submodule([z, 0, 0], [0, x, 0], [0, 0, y]) assert M2.syzygy_module() == S2 F = R.free_module(3) assert F.submodule(*F.basis()).syzygy_module() == F.submodule() R2 = QQ.old_poly_ring(x, y, z) / [x*y*z] M3 = R2.free_module(1).submodule([x*y], [y*z], [x*z]) S3 = R2.free_module(3).submodule([z, 0, 0], [0, x, 0], [0, 0, y]) assert M3.syzygy_module() == S3 def test_in_terms_of_generators(): R = QQ.old_poly_ring(x, order="ilex") M = R.free_module(2).submodule([2*x, 0], [1, 2]) assert M.in_terms_of_generators( [x, x]) == [R.convert(Rational(1, 4)), R.convert(x/2)] raises(ValueError, lambda: M.in_terms_of_generators([1, 0])) M = R.free_module(2) / ([x, 0], [1, 1]) SM = M.submodule([1, x]) assert SM.in_terms_of_generators([2, 0]) == [R.convert(-2/(x - 1))] R = QQ.old_poly_ring(x, y) / [x**2 - y**2] M = R.free_module(2) SM = M.submodule([x, 0], [0, y]) assert SM.in_terms_of_generators( [x**2, x**2]) == [R.convert(x), R.convert(y)] def test_QuotientModuleElement(): R = QQ.old_poly_ring(x) F = R.free_module(3) N = F.submodule([1, x, x**2]) M = F/N e = M.convert([x**2, 2, 0]) assert M.convert([x + 1, x**2 + x, x**3 + x**2]) == 0 assert e == [x**2, 2, 0] + N == F.convert([x**2, 2, 0]) + N == \ M.convert(F.convert([x**2, 2, 0])) assert M.convert([x**2 + 1, 2*x + 2, x**2]) == e + [0, x, 0] == \ e + M.convert([0, x, 0]) == e + F.convert([0, x, 0]) assert M.convert([x**2 + 1, 2, x**2]) == e - [0, x, 0] == \ e - M.convert([0, x, 0]) == e - F.convert([0, x, 0]) assert M.convert([0, 2, 0]) == M.convert([x**2, 4, 0]) - e == \ [x**2, 4, 0] - e == F.convert([x**2, 4, 0]) - e assert M.convert([x**3 + x**2, 2*x + 2, 0]) == (1 + x)*e == \ R.convert(1 + x)*e == e*(1 + x) == e*R.convert(1 + x) assert -e == [-x**2, -2, 0] f = [x, x, 0] + N assert M.convert([1, 1, 0]) == f / x == f / R.convert(x) M2 = F/[(2, 2*x, 2*x**2), (0, 0, 1)] G = R.free_module(2) M3 = G/[[1, x]] M4 = F.submodule([1, x, x**2], [1, 0, 0]) / N raises(CoercionFailed, lambda: M.convert(G.convert([1, x]))) raises(CoercionFailed, lambda: M.convert(M3.convert([1, x]))) raises(CoercionFailed, lambda: M.convert(M2.convert([1, x, x]))) assert M2.convert(M.convert([2, x, x**2])) == [2, x, 0] assert M.convert(M4.convert([2, 0, 0])) == [2, 0, 0] def test_QuotientModule(): R = QQ.old_poly_ring(x) F = R.free_module(3) N = F.submodule([1, x, x**2]) M = F/N assert M != F assert M != N assert M == F / [(1, x, x**2)] assert not M.is_zero() assert (F / F.basis()).is_zero() SQ = F.submodule([1, x, x**2], [2, 0, 0]) / N assert SQ == M.submodule([2, x, x**2]) assert SQ != M.submodule([2, 1, 0]) assert SQ != M assert M.is_submodule(SQ) assert not SQ.is_full_module() raises(ValueError, lambda: N/F) raises(ValueError, lambda: F.submodule([2, 0, 0]) / N) raises(ValueError, lambda: R.free_module(2)/F) raises(CoercionFailed, lambda: F.convert(M.convert([1, x, x**2]))) M1 = F / [[1, 1, 1]] M2 = M1.submodule([1, 0, 0], [0, 1, 0]) assert M1 == M2 def test_ModulesQuotientRing(): R = QQ.old_poly_ring(x, y, order=(("lex", x), ("ilex", y))) / [x**2 + 1] M1 = R.free_module(2) assert M1 == R.free_module(2) assert M1 != QQ.old_poly_ring(x).free_module(2) assert M1 != R.free_module(3) assert [x, 1] in M1 assert [x] not in M1 assert [1/(R.convert(x) + 1), 2] in M1 assert [1, 2/(1 + y)] in M1 assert [1, 2/y] not in M1 assert M1.convert([x**2, y]) == [-1, y] F = R.free_module(3) Fd = F.submodule([x**2, 0, 0], [1, 2, 0], [1, 2, 3]) M = F.submodule([x**2 + y**2, 1, 0], [x, y, 1]) assert F == Fd assert Fd == F assert F != M assert M != F assert Fd != M assert M != Fd assert Fd == F.submodule(*F.basis()) assert Fd.is_full_module() assert not M.is_full_module() assert not Fd.is_zero() assert not M.is_zero() assert Fd.submodule().is_zero() assert M.contains([x**2 + y**2 + x, -x**2 + y, 1]) assert not M.contains([x**2 + y**2 + x, 1 + y, 2]) assert M.contains([y**2, 1 - x*y, -x]) assert F.submodule([x, 0, 0]) == F.submodule([1, 0, 0]) assert not F.submodule([y, 0, 0]) == F.submodule([1, 0, 0]) assert F.submodule([1, 0, 0], [0, 1, 0]).union(F.submodule([0, 0, 1])) == F assert not M.is_submodule(0) def test_module_mul(): R = QQ.old_poly_ring(x) M = R.free_module(2) S1 = M.submodule([x, 0], [0, x]) S2 = M.submodule([x**2, 0], [0, x**2]) I = R.ideal(x) assert I*M == M*I == S1 == x*M == M*x assert I*S1 == S2 == x*S1 def test_intersection(): # SCA, example 2.8.5 F = QQ.old_poly_ring(x, y).free_module(2) M1 = F.submodule([x, y], [y, 1]) M2 = F.submodule([0, y - 1], [x, 1], [y, x]) I = F.submodule([x, y], [y**2 - y, y - 1], [x*y + y, x + 1]) I1, rel1, rel2 = M1.intersect(M2, relations=True) assert I1 == M2.intersect(M1) == I for i, g in enumerate(I1.gens): assert g == sum(c*x for c, x in zip(rel1[i], M1.gens)) \ == sum(d*y for d, y in zip(rel2[i], M2.gens)) assert F.submodule([x, y]).intersect(F.submodule([y, x])).is_zero() def test_quotient(): # SCA, example 2.8.6 R = QQ.old_poly_ring(x, y, z) F = R.free_module(2) assert F.submodule([x*y, x*z], [y*z, x*y]).module_quotient( F.submodule([y, z], [z, y])) == QQ.old_poly_ring(x, y, z).ideal(x**2*y**2 - x*y*z**2) assert F.submodule([x, y]).module_quotient(F.submodule()).is_whole_ring() M = F.submodule([x**2, x**2], [y**2, y**2]) N = F.submodule([x + y, x + y]) q, rel = M.module_quotient(N, relations=True) assert q == R.ideal(y**2, x - y) for i, g in enumerate(q.gens): assert g*N.gens[0] == sum(c*x for c, x in zip(rel[i], M.gens)) def test_groebner_extendend(): M = QQ.old_poly_ring(x, y, z).free_module(3).submodule([x + 1, y, 1], [x*y, z, z**2]) G, R = M._groebner_vec(extended=True) for i, g in enumerate(G): assert g == sum(c*gen for c, gen in zip(R[i], M.gens))
9b484599c4f3bd9f2c65b6e759e10dc332b2b9fa44f735b0651f96088e247695
"""Tests for homomorphisms.""" from sympy.core.singleton import S from sympy.polys.domains.rationalfield import QQ from sympy.abc import x, y from sympy.polys.agca import homomorphism from sympy.testing.pytest import raises def test_printing(): R = QQ.old_poly_ring(x) assert str(homomorphism(R.free_module(1), R.free_module(1), [0])) == \ 'Matrix([[0]]) : QQ[x]**1 -> QQ[x]**1' assert str(homomorphism(R.free_module(2), R.free_module(2), [0, 0])) == \ 'Matrix([ \n[0, 0], : QQ[x]**2 -> QQ[x]**2\n[0, 0]]) ' assert str(homomorphism(R.free_module(1), R.free_module(1) / [[x]], [0])) == \ 'Matrix([[0]]) : QQ[x]**1 -> QQ[x]**1/<[x]>' assert str(R.free_module(0).identity_hom()) == 'Matrix(0, 0, []) : QQ[x]**0 -> QQ[x]**0' def test_operations(): F = QQ.old_poly_ring(x).free_module(2) G = QQ.old_poly_ring(x).free_module(3) f = F.identity_hom() g = homomorphism(F, F, [0, [1, x]]) h = homomorphism(F, F, [[1, 0], 0]) i = homomorphism(F, G, [[1, 0, 0], [0, 1, 0]]) assert f == f assert f != g assert f != i assert (f != F.identity_hom()) is False assert 2*f == f*2 == homomorphism(F, F, [[2, 0], [0, 2]]) assert f/2 == homomorphism(F, F, [[S.Half, 0], [0, S.Half]]) assert f + g == homomorphism(F, F, [[1, 0], [1, x + 1]]) assert f - g == homomorphism(F, F, [[1, 0], [-1, 1 - x]]) assert f*g == g == g*f assert h*g == homomorphism(F, F, [0, [1, 0]]) assert g*h == homomorphism(F, F, [0, 0]) assert i*f == i assert f([1, 2]) == [1, 2] assert g([1, 2]) == [2, 2*x] assert i.restrict_domain(F.submodule([x, x]))([x, x]) == i([x, x]) h1 = h.quotient_domain(F.submodule([0, 1])) assert h1([1, 0]) == h([1, 0]) assert h1.restrict_domain(h1.domain.submodule([x, 0]))([x, 0]) == h([x, 0]) raises(TypeError, lambda: f/g) raises(TypeError, lambda: f + 1) raises(TypeError, lambda: f + i) raises(TypeError, lambda: f - 1) raises(TypeError, lambda: f*i) def test_creation(): F = QQ.old_poly_ring(x).free_module(3) G = QQ.old_poly_ring(x).free_module(2) SM = F.submodule([1, 1, 1]) Q = F / SM SQ = Q.submodule([1, 0, 0]) matrix = [[1, 0], [0, 1], [-1, -1]] h = homomorphism(F, G, matrix) h2 = homomorphism(Q, G, matrix) assert h.quotient_domain(SM) == h2 raises(ValueError, lambda: h.quotient_domain(F.submodule([1, 0, 0]))) assert h2.restrict_domain(SQ) == homomorphism(SQ, G, matrix) raises(ValueError, lambda: h.restrict_domain(G)) raises(ValueError, lambda: h.restrict_codomain(G.submodule([1, 0]))) raises(ValueError, lambda: h.quotient_codomain(F)) im = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] for M in [F, SM, Q, SQ]: assert M.identity_hom() == homomorphism(M, M, im) assert SM.inclusion_hom() == homomorphism(SM, F, im) assert SQ.inclusion_hom() == homomorphism(SQ, Q, im) assert Q.quotient_hom() == homomorphism(F, Q, im) assert SQ.quotient_hom() == homomorphism(SQ.base, SQ, im) class conv: def convert(x, y=None): return x class dummy: container = conv() def submodule(*args): return None raises(TypeError, lambda: homomorphism(dummy(), G, matrix)) raises(TypeError, lambda: homomorphism(F, dummy(), matrix)) raises( ValueError, lambda: homomorphism(QQ.old_poly_ring(x, y).free_module(3), G, matrix)) raises(ValueError, lambda: homomorphism(F, G, [0, 0])) def test_properties(): R = QQ.old_poly_ring(x, y) F = R.free_module(2) h = homomorphism(F, F, [[x, 0], [y, 0]]) assert h.kernel() == F.submodule([-y, x]) assert h.image() == F.submodule([x, 0], [y, 0]) assert not h.is_injective() assert not h.is_surjective() assert h.restrict_codomain(h.image()).is_surjective() assert h.restrict_domain(F.submodule([1, 0])).is_injective() assert h.quotient_domain( h.kernel()).restrict_codomain(h.image()).is_isomorphism() R2 = QQ.old_poly_ring(x, y, order=(("lex", x), ("ilex", y))) / [x**2 + 1] F = R2.free_module(2) h = homomorphism(F, F, [[x, 0], [y, y + 1]]) assert h.is_isomorphism()
4f595865e5bed0dc03c43386e9924bafe38809fc58db06b47d51d5d95e845d29
""" Tests for the sympy.polys.matrices.eigen module """ from sympy.core.singleton import S from sympy.functions.elementary.miscellaneous import sqrt from sympy.matrices.dense import Matrix from sympy.polys.agca.extensions import FiniteExtension from sympy.polys.domains import QQ from sympy.polys.polytools import Poly from sympy.polys.rootoftools import CRootOf from sympy.polys.matrices.domainmatrix import DomainMatrix from sympy.polys.matrices.eigen import dom_eigenvects, dom_eigenvects_to_sympy def test_dom_eigenvects_rational(): # Rational eigenvalues A = DomainMatrix([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ) rational_eigenvects = [ (QQ, QQ(3), 1, DomainMatrix([[QQ(1), QQ(1)]], (1, 2), QQ)), (QQ, QQ(0), 1, DomainMatrix([[QQ(-2), QQ(1)]], (1, 2), QQ)), ] assert dom_eigenvects(A) == (rational_eigenvects, []) # Test converting to Expr: sympy_eigenvects = [ (S(3), 1, [Matrix([1, 1])]), (S(0), 1, [Matrix([-2, 1])]), ] assert dom_eigenvects_to_sympy(rational_eigenvects, [], Matrix) == sympy_eigenvects def test_dom_eigenvects_algebraic(): # Algebraic eigenvalues A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) Avects = dom_eigenvects(A) # Extract the dummy to build the expected result: lamda = Avects[1][0][1].gens[0] irreducible = Poly(lamda**2 - 5*lamda - 2, lamda, domain=QQ) K = FiniteExtension(irreducible) KK = K.from_sympy algebraic_eigenvects = [ (K, irreducible, 1, DomainMatrix([[KK((lamda-4)/3), KK(1)]], (1, 2), K)), ] assert Avects == ([], algebraic_eigenvects) # Test converting to Expr: sympy_eigenvects = [ (S(5)/2 - sqrt(33)/2, 1, [Matrix([[-sqrt(33)/6 - S(1)/2], [1]])]), (S(5)/2 + sqrt(33)/2, 1, [Matrix([[-S(1)/2 + sqrt(33)/6], [1]])]), ] assert dom_eigenvects_to_sympy([], algebraic_eigenvects, Matrix) == sympy_eigenvects def test_dom_eigenvects_rootof(): # Algebraic eigenvalues A = DomainMatrix([ [0, 0, 0, 0, -1], [1, 0, 0, 0, 1], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 1, 0]], (5, 5), QQ) Avects = dom_eigenvects(A) # Extract the dummy to build the expected result: lamda = Avects[1][0][1].gens[0] irreducible = Poly(lamda**5 - lamda + 1, lamda, domain=QQ) K = FiniteExtension(irreducible) KK = K.from_sympy algebraic_eigenvects = [ (K, irreducible, 1, DomainMatrix([ [KK(lamda**4-1), KK(lamda**3), KK(lamda**2), KK(lamda), KK(1)] ], (1, 5), K)), ] assert Avects == ([], algebraic_eigenvects) # Test converting to Expr (slow): l0, l1, l2, l3, l4 = [CRootOf(lamda**5 - lamda + 1, i) for i in range(5)] sympy_eigenvects = [ (l0, 1, [Matrix([-1 + l0**4, l0**3, l0**2, l0, 1])]), (l1, 1, [Matrix([-1 + l1**4, l1**3, l1**2, l1, 1])]), (l2, 1, [Matrix([-1 + l2**4, l2**3, l2**2, l2, 1])]), (l3, 1, [Matrix([-1 + l3**4, l3**3, l3**2, l3, 1])]), (l4, 1, [Matrix([-1 + l4**4, l4**3, l4**2, l4, 1])]), ] assert dom_eigenvects_to_sympy([], algebraic_eigenvects, Matrix) == sympy_eigenvects
ccfb1a09cd794954944a4589dfcdffcff96bc4dbcecda17681a0e95cc3ce1bfa
from sympy.testing.pytest import raises from sympy.core.symbol import Symbol from sympy.polys.matrices.normalforms import ( invariant_factors, smith_normal_form, hermite_normal_form, _hermite_normal_form, _hermite_normal_form_modulo_D) from sympy.polys.domains import ZZ, QQ from sympy.polys.matrices import DomainMatrix, DM from sympy.polys.matrices.exceptions import DMDomainError, DMShapeError def test_smith_normal(): m = DM([[12, 6, 4, 8], [3, 9, 6, 12], [2, 16, 14, 28], [20, 10, 10, 20]], ZZ) smf = DM([[1, 0, 0, 0], [0, 10, 0, 0], [0, 0, -30, 0], [0, 0, 0, 0]], ZZ) assert smith_normal_form(m).to_dense() == smf x = Symbol('x') m = DM([[x-1, 1, -1], [ 0, x, -1], [ 0, -1, x]], QQ[x]) dx = m.domain.gens[0] assert invariant_factors(m) == (1, dx-1, dx**2-1) zr = DomainMatrix([], (0, 2), ZZ) zc = DomainMatrix([[], []], (2, 0), ZZ) assert smith_normal_form(zr).to_dense() == zr assert smith_normal_form(zc).to_dense() == zc assert smith_normal_form(DM([[2, 4]], ZZ)).to_dense() == DM([[2, 0]], ZZ) assert smith_normal_form(DM([[0, -2]], ZZ)).to_dense() == DM([[-2, 0]], ZZ) assert smith_normal_form(DM([[0], [-2]], ZZ)).to_dense() == DM([[-2], [0]], ZZ) m = DM([[3, 0, 0, 0], [0, 0, 0, 0], [0, 0, 2, 0]], ZZ) snf = DM([[1, 0, 0, 0], [0, 6, 0, 0], [0, 0, 0, 0]], ZZ) assert smith_normal_form(m).to_dense() == snf raises(ValueError, lambda: smith_normal_form(DM([[1]], ZZ[x]))) def test_hermite_normal(): m = DM([[2, 7, 17, 29, 41], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]], ZZ) hnf = DM([[1, 0, 0], [0, 2, 1], [0, 0, 1]], ZZ) assert hermite_normal_form(m) == hnf assert hermite_normal_form(m, D=2) == hnf assert hermite_normal_form(m, D=2, check_rank=True) == hnf m = m.transpose() hnf = DM([[37, 0, 19], [222, -6, 113], [48, 0, 25], [0, 2, 1], [0, 0, 1]], ZZ) assert hermite_normal_form(m) == hnf raises(DMShapeError, lambda: _hermite_normal_form_modulo_D(m, 96)) m = DM([[8, 28, 68, 116, 164], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]], ZZ) hnf = DM([[4, 0, 0], [0, 2, 1], [0, 0, 1]], ZZ) assert hermite_normal_form(m) == hnf assert hermite_normal_form(m, D=8) == hnf assert hermite_normal_form(m, D=8, check_rank=True) == hnf m = DM([[10, 8, 6, 30, 2], [45, 36, 27, 18, 9], [5, 4, 3, 2, 1]], ZZ) hnf = DM([[26, 2], [0, 9], [0, 1]], ZZ) assert hermite_normal_form(m) == hnf m = DM([[2, 7], [0, 0], [0, 0]], ZZ) hnf = DM([[], [], []], ZZ) assert hermite_normal_form(m) == hnf m = DM([[-2, 1], [0, 1]], ZZ) hnf = DM([[2, 1], [0, 1]], ZZ) assert hermite_normal_form(m) == hnf m = DomainMatrix([[QQ(1)]], (1, 1), QQ) raises(DMDomainError, lambda: hermite_normal_form(m)) raises(DMDomainError, lambda: _hermite_normal_form(m)) raises(DMDomainError, lambda: _hermite_normal_form_modulo_D(m, 1))
ded1618e40356a513cdbb422c3d9803e55a44a057749eb2ba9e87e3711d7b00e
from sympy.testing.pytest import raises from sympy.external.gmpy import HAS_GMPY from sympy.polys import ZZ, QQ from sympy.polys.matrices.ddm import DDM from sympy.polys.matrices.exceptions import ( DMShapeError, DMNonInvertibleMatrixError, DMDomainError, DMBadInputError) def test_DDM_init(): items = [[ZZ(0), ZZ(1), ZZ(2)], [ZZ(3), ZZ(4), ZZ(5)]] shape = (2, 3) ddm = DDM(items, shape, ZZ) assert ddm.shape == shape assert ddm.rows == 2 assert ddm.cols == 3 assert ddm.domain == ZZ raises(DMBadInputError, lambda: DDM([[ZZ(2), ZZ(3)]], (2, 2), ZZ)) raises(DMBadInputError, lambda: DDM([[ZZ(1)], [ZZ(2), ZZ(3)]], (2, 2), ZZ)) def test_DDM_getsetitem(): ddm = DDM([[ZZ(2), ZZ(3)], [ZZ(4), ZZ(5)]], (2, 2), ZZ) assert ddm[0][0] == ZZ(2) assert ddm[0][1] == ZZ(3) assert ddm[1][0] == ZZ(4) assert ddm[1][1] == ZZ(5) raises(IndexError, lambda: ddm[2][0]) raises(IndexError, lambda: ddm[0][2]) ddm[0][0] = ZZ(-1) assert ddm[0][0] == ZZ(-1) def test_DDM_str(): ddm = DDM([[ZZ(0), ZZ(1)], [ZZ(2), ZZ(3)]], (2, 2), ZZ) if HAS_GMPY: # pragma: no cover assert str(ddm) == '[[0, 1], [2, 3]]' assert repr(ddm) == 'DDM([[mpz(0), mpz(1)], [mpz(2), mpz(3)]], (2, 2), ZZ)' else: # pragma: no cover assert repr(ddm) == 'DDM([[0, 1], [2, 3]], (2, 2), ZZ)' assert str(ddm) == '[[0, 1], [2, 3]]' def test_DDM_eq(): items = [[ZZ(0), ZZ(1)], [ZZ(2), ZZ(3)]] ddm1 = DDM(items, (2, 2), ZZ) ddm2 = DDM(items, (2, 2), ZZ) assert (ddm1 == ddm1) is True assert (ddm1 == items) is False assert (items == ddm1) is False assert (ddm1 == ddm2) is True assert (ddm2 == ddm1) is True assert (ddm1 != ddm1) is False assert (ddm1 != items) is True assert (items != ddm1) is True assert (ddm1 != ddm2) is False assert (ddm2 != ddm1) is False ddm3 = DDM([[ZZ(0), ZZ(1)], [ZZ(3), ZZ(3)]], (2, 2), ZZ) ddm3 = DDM(items, (2, 2), QQ) assert (ddm1 == ddm3) is False assert (ddm3 == ddm1) is False assert (ddm1 != ddm3) is True assert (ddm3 != ddm1) is True def test_DDM_convert_to(): ddm = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ) assert ddm.convert_to(ZZ) == ddm ddmq = ddm.convert_to(QQ) assert ddmq.domain == QQ def test_DDM_zeros(): ddmz = DDM.zeros((3, 4), QQ) assert list(ddmz) == [[QQ(0)] * 4] * 3 assert ddmz.shape == (3, 4) assert ddmz.domain == QQ def test_DDM_ones(): ddmone = DDM.ones((2, 3), QQ) assert list(ddmone) == [[QQ(1)] * 3] * 2 assert ddmone.shape == (2, 3) assert ddmone.domain == QQ def test_DDM_eye(): ddmz = DDM.eye(3, QQ) f = lambda i, j: QQ(1) if i == j else QQ(0) assert list(ddmz) == [[f(i, j) for i in range(3)] for j in range(3)] assert ddmz.shape == (3, 3) assert ddmz.domain == QQ def test_DDM_copy(): ddm1 = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) ddm2 = ddm1.copy() assert (ddm1 == ddm2) is True ddm1[0][0] = QQ(-1) assert (ddm1 == ddm2) is False ddm2[0][0] = QQ(-1) assert (ddm1 == ddm2) is True def test_DDM_transpose(): ddm = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) ddmT = DDM([[QQ(1), QQ(2)]], (1, 2), QQ) assert ddm.transpose() == ddmT ddm02 = DDM([], (0, 2), QQ) ddm02T = DDM([[], []], (2, 0), QQ) assert ddm02.transpose() == ddm02T assert ddm02T.transpose() == ddm02 ddm0 = DDM([], (0, 0), QQ) assert ddm0.transpose() == ddm0 def test_DDM_add(): A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) B = DDM([[ZZ(3)], [ZZ(4)]], (2, 1), ZZ) C = DDM([[ZZ(4)], [ZZ(6)]], (2, 1), ZZ) AQ = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) assert A + B == A.add(B) == C raises(DMShapeError, lambda: A + DDM([[ZZ(5)]], (1, 1), ZZ)) raises(TypeError, lambda: A + ZZ(1)) raises(TypeError, lambda: ZZ(1) + A) raises(DMDomainError, lambda: A + AQ) raises(DMDomainError, lambda: AQ + A) def test_DDM_sub(): A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) B = DDM([[ZZ(3)], [ZZ(4)]], (2, 1), ZZ) C = DDM([[ZZ(-2)], [ZZ(-2)]], (2, 1), ZZ) AQ = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) D = DDM([[ZZ(5)]], (1, 1), ZZ) assert A - B == A.sub(B) == C raises(TypeError, lambda: A - ZZ(1)) raises(TypeError, lambda: ZZ(1) - A) raises(DMShapeError, lambda: A - D) raises(DMShapeError, lambda: D - A) raises(DMShapeError, lambda: A.sub(D)) raises(DMShapeError, lambda: D.sub(A)) raises(DMDomainError, lambda: A - AQ) raises(DMDomainError, lambda: AQ - A) raises(DMDomainError, lambda: A.sub(AQ)) raises(DMDomainError, lambda: AQ.sub(A)) def test_DDM_neg(): A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) An = DDM([[ZZ(-1)], [ZZ(-2)]], (2, 1), ZZ) assert -A == A.neg() == An assert -An == An.neg() == A def test_DDM_mul(): A = DDM([[ZZ(1)]], (1, 1), ZZ) A2 = DDM([[ZZ(2)]], (1, 1), ZZ) assert A * ZZ(2) == A2 assert ZZ(2) * A == A2 raises(TypeError, lambda: [[1]] * A) raises(TypeError, lambda: A * [[1]]) def test_DDM_matmul(): A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) B = DDM([[ZZ(3), ZZ(4)]], (1, 2), ZZ) AB = DDM([[ZZ(3), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ) BA = DDM([[ZZ(11)]], (1, 1), ZZ) assert A @ B == A.matmul(B) == AB assert B @ A == B.matmul(A) == BA raises(TypeError, lambda: A @ 1) raises(TypeError, lambda: A @ [[3, 4]]) Bq = DDM([[QQ(3), QQ(4)]], (1, 2), QQ) raises(DMDomainError, lambda: A @ Bq) raises(DMDomainError, lambda: Bq @ A) C = DDM([[ZZ(1)]], (1, 1), ZZ) assert A @ C == A.matmul(C) == A raises(DMShapeError, lambda: C @ A) raises(DMShapeError, lambda: C.matmul(A)) Z04 = DDM([], (0, 4), ZZ) Z40 = DDM([[]]*4, (4, 0), ZZ) Z50 = DDM([[]]*5, (5, 0), ZZ) Z05 = DDM([], (0, 5), ZZ) Z45 = DDM([[0] * 5] * 4, (4, 5), ZZ) Z54 = DDM([[0] * 4] * 5, (5, 4), ZZ) Z00 = DDM([], (0, 0), ZZ) assert Z04 @ Z45 == Z04.matmul(Z45) == Z05 assert Z45 @ Z50 == Z45.matmul(Z50) == Z40 assert Z00 @ Z04 == Z00.matmul(Z04) == Z04 assert Z50 @ Z00 == Z50.matmul(Z00) == Z50 assert Z00 @ Z00 == Z00.matmul(Z00) == Z00 assert Z50 @ Z04 == Z50.matmul(Z04) == Z54 raises(DMShapeError, lambda: Z05 @ Z40) raises(DMShapeError, lambda: Z05.matmul(Z40)) def test_DDM_hstack(): A = DDM([[ZZ(1), ZZ(2), ZZ(3)]], (1, 3), ZZ) B = DDM([[ZZ(4), ZZ(5)]], (1, 2), ZZ) C = DDM([[ZZ(6)]], (1, 1), ZZ) Ah = A.hstack(B) assert Ah.shape == (1, 5) assert Ah.domain == ZZ assert Ah == DDM([[ZZ(1), ZZ(2), ZZ(3), ZZ(4), ZZ(5)]], (1, 5), ZZ) Ah = A.hstack(B, C) assert Ah.shape == (1, 6) assert Ah.domain == ZZ assert Ah == DDM([[ZZ(1), ZZ(2), ZZ(3), ZZ(4), ZZ(5), ZZ(6)]], (1, 6), ZZ) def test_DDM_vstack(): A = DDM([[ZZ(1)], [ZZ(2)], [ZZ(3)]], (3, 1), ZZ) B = DDM([[ZZ(4)], [ZZ(5)]], (2, 1), ZZ) C = DDM([[ZZ(6)]], (1, 1), ZZ) Ah = A.vstack(B) assert Ah.shape == (5, 1) assert Ah.domain == ZZ assert Ah == DDM([[ZZ(1)], [ZZ(2)], [ZZ(3)], [ZZ(4)], [ZZ(5)]], (5, 1), ZZ) Ah = A.vstack(B, C) assert Ah.shape == (6, 1) assert Ah.domain == ZZ assert Ah == DDM([[ZZ(1)], [ZZ(2)], [ZZ(3)], [ZZ(4)], [ZZ(5)], [ZZ(6)]], (6, 1), ZZ) def test_DDM_applyfunc(): A = DDM([[ZZ(1), ZZ(2), ZZ(3)]], (1, 3), ZZ) B = DDM([[ZZ(2), ZZ(4), ZZ(6)]], (1, 3), ZZ) assert A.applyfunc(lambda x: 2*x, ZZ) == B def test_DDM_rref(): A = DDM([], (0, 4), QQ) assert A.rref() == (A, []) A = DDM([[QQ(0), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ) Ar = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) pivots = [0, 1] assert A.rref() == (Ar, pivots) A = DDM([[QQ(1), QQ(2), QQ(1)], [QQ(3), QQ(4), QQ(1)]], (2, 3), QQ) Ar = DDM([[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]], (2, 3), QQ) pivots = [0, 1] assert A.rref() == (Ar, pivots) A = DDM([[QQ(3), QQ(4), QQ(1)], [QQ(1), QQ(2), QQ(1)]], (2, 3), QQ) Ar = DDM([[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]], (2, 3), QQ) pivots = [0, 1] assert A.rref() == (Ar, pivots) A = DDM([[QQ(1), QQ(0)], [QQ(1), QQ(3)], [QQ(0), QQ(1)]], (3, 2), QQ) Ar = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]], (3, 2), QQ) pivots = [0, 1] assert A.rref() == (Ar, pivots) A = DDM([[QQ(1), QQ(0), QQ(1)], [QQ(3), QQ(0), QQ(1)]], (2, 3), QQ) Ar = DDM([[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(0), QQ(1)]], (2, 3), QQ) pivots = [0, 2] assert A.rref() == (Ar, pivots) def test_DDM_nullspace(): A = DDM([[QQ(1), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ) Anull = DDM([[QQ(-1), QQ(1)]], (1, 2), QQ) nonpivots = [1] assert A.nullspace() == (Anull, nonpivots) def test_DDM_particular(): A = DDM([[QQ(1), QQ(0)]], (1, 2), QQ) assert A.particular() == DDM.zeros((1, 1), QQ) def test_DDM_det(): # 0x0 case A = DDM([], (0, 0), ZZ) assert A.det() == ZZ(1) # 1x1 case A = DDM([[ZZ(2)]], (1, 1), ZZ) assert A.det() == ZZ(2) # 2x2 case A = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.det() == ZZ(-2) # 3x3 with swap A = DDM([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]], (3, 3), ZZ) assert A.det() == ZZ(0) # 2x2 QQ case A = DDM([[QQ(1, 2), QQ(1, 2)], [QQ(1, 3), QQ(1, 4)]], (2, 2), QQ) assert A.det() == QQ(-1, 24) # Nonsquare error A = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) raises(DMShapeError, lambda: A.det()) # Nonsquare error with empty matrix A = DDM([], (0, 1), ZZ) raises(DMShapeError, lambda: A.det()) def test_DDM_inv(): A = DDM([[QQ(1, 1), QQ(2, 1)], [QQ(3, 1), QQ(4, 1)]], (2, 2), QQ) Ainv = DDM([[QQ(-2, 1), QQ(1, 1)], [QQ(3, 2), QQ(-1, 2)]], (2, 2), QQ) assert A.inv() == Ainv A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ) raises(DMShapeError, lambda: A.inv()) A = DDM([[ZZ(2)]], (1, 1), ZZ) raises(ValueError, lambda: A.inv()) A = DDM([], (0, 0), QQ) assert A.inv() == A A = DDM([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ) raises(DMNonInvertibleMatrixError, lambda: A.inv()) def test_DDM_lu(): A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) L, U, swaps = A.lu() assert L == DDM([[QQ(1), QQ(0)], [QQ(3), QQ(1)]], (2, 2), QQ) assert U == DDM([[QQ(1), QQ(2)], [QQ(0), QQ(-2)]], (2, 2), QQ) assert swaps == [] A = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]] Lexp = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 1]] Uexp = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]] to_dom = lambda rows, dom: [[dom(e) for e in row] for row in rows] A = DDM(to_dom(A, QQ), (4, 4), QQ) Lexp = DDM(to_dom(Lexp, QQ), (4, 4), QQ) Uexp = DDM(to_dom(Uexp, QQ), (4, 4), QQ) L, U, swaps = A.lu() assert L == Lexp assert U == Uexp assert swaps == [] def test_DDM_lu_solve(): # Basic example A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) x = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) assert A.lu_solve(b) == x # Example with swaps A = DDM([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) assert A.lu_solve(b) == x # Overdetermined, consistent A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ) b = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ) assert A.lu_solve(b) == x # Overdetermined, inconsistent b = DDM([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ) raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b)) # Square, noninvertible A = DDM([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ) b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b)) # Underdetermined A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ) b = DDM([[QQ(3)]], (1, 1), QQ) raises(NotImplementedError, lambda: A.lu_solve(b)) # Domain mismatch bz = DDM([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) raises(DMDomainError, lambda: A.lu_solve(bz)) # Shape mismatch b3 = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ) raises(DMShapeError, lambda: A.lu_solve(b3)) def test_DDM_charpoly(): A = DDM([], (0, 0), ZZ) assert A.charpoly() == [ZZ(1)] A = DDM([ [ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) Avec = [ZZ(1), ZZ(-15), ZZ(-18), ZZ(0)] assert A.charpoly() == Avec A = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ) raises(DMShapeError, lambda: A.charpoly()) def test_DDM_getitem(): dm = DDM([ [ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) assert dm.getitem(1, 1) == ZZ(5) assert dm.getitem(1, -2) == ZZ(5) assert dm.getitem(-1, -3) == ZZ(7) raises(IndexError, lambda: dm.getitem(3, 3)) def test_DDM_setitem(): dm = DDM.zeros((3, 3), ZZ) dm.setitem(0, 0, 1) dm.setitem(1, -2, 1) dm.setitem(-1, -1, 1) assert dm == DDM.eye(3, ZZ) raises(IndexError, lambda: dm.setitem(3, 3, 0)) def test_DDM_extract_slice(): dm = DDM([ [ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) assert dm.extract_slice(slice(0, 3), slice(0, 3)) == dm assert dm.extract_slice(slice(1, 3), slice(-2)) == DDM([[4], [7]], (2, 1), ZZ) assert dm.extract_slice(slice(1, 3), slice(-2)) == DDM([[4], [7]], (2, 1), ZZ) assert dm.extract_slice(slice(2, 3), slice(-2)) == DDM([[ZZ(7)]], (1, 1), ZZ) assert dm.extract_slice(slice(0, 2), slice(-2)) == DDM([[1], [4]], (2, 1), ZZ) assert dm.extract_slice(slice(-1), slice(-1)) == DDM([[1, 2], [4, 5]], (2, 2), ZZ) assert dm.extract_slice(slice(2), slice(3, 4)) == DDM([[], []], (2, 0), ZZ) assert dm.extract_slice(slice(3, 4), slice(2)) == DDM([], (0, 2), ZZ) assert dm.extract_slice(slice(3, 4), slice(3, 4)) == DDM([], (0, 0), ZZ) def test_DDM_extract(): dm1 = DDM([ [ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) dm2 = DDM([ [ZZ(6), ZZ(4)], [ZZ(3), ZZ(1)]], (2, 2), ZZ) assert dm1.extract([1, 0], [2, 0]) == dm2 assert dm1.extract([-2, 0], [-1, 0]) == dm2 assert dm1.extract([], []) == DDM.zeros((0, 0), ZZ) assert dm1.extract([1], []) == DDM.zeros((1, 0), ZZ) assert dm1.extract([], [1]) == DDM.zeros((0, 1), ZZ) raises(IndexError, lambda: dm2.extract([2], [0])) raises(IndexError, lambda: dm2.extract([0], [2])) raises(IndexError, lambda: dm2.extract([-3], [0])) raises(IndexError, lambda: dm2.extract([0], [-3])) def test_DDM_flat(): dm = DDM([ [ZZ(6), ZZ(4)], [ZZ(3), ZZ(1)]], (2, 2), ZZ) assert dm.flat() == [ZZ(6), ZZ(4), ZZ(3), ZZ(1)] def test_DDM_is_zero_matrix(): A = DDM([[QQ(1), QQ(0)], [QQ(0), QQ(0)]], (2, 2), QQ) Azero = DDM.zeros((1, 2), QQ) assert A.is_zero_matrix() is False assert Azero.is_zero_matrix() is True def test_DDM_is_upper(): # Wide matrices: A = DDM([ [QQ(1), QQ(2), QQ(3), QQ(4)], [QQ(0), QQ(5), QQ(6), QQ(7)], [QQ(0), QQ(0), QQ(8), QQ(9)] ], (3, 4), QQ) B = DDM([ [QQ(1), QQ(2), QQ(3), QQ(4)], [QQ(0), QQ(5), QQ(6), QQ(7)], [QQ(0), QQ(7), QQ(8), QQ(9)] ], (3, 4), QQ) assert A.is_upper() is True assert B.is_upper() is False # Tall matrices: A = DDM([ [QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(5), QQ(6)], [QQ(0), QQ(0), QQ(8)], [QQ(0), QQ(0), QQ(0)] ], (4, 3), QQ) B = DDM([ [QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(5), QQ(6)], [QQ(0), QQ(0), QQ(8)], [QQ(0), QQ(0), QQ(10)] ], (4, 3), QQ) assert A.is_upper() is True assert B.is_upper() is False def test_DDM_is_lower(): # Tall matrices: A = DDM([ [QQ(1), QQ(2), QQ(3), QQ(4)], [QQ(0), QQ(5), QQ(6), QQ(7)], [QQ(0), QQ(0), QQ(8), QQ(9)] ], (3, 4), QQ).transpose() B = DDM([ [QQ(1), QQ(2), QQ(3), QQ(4)], [QQ(0), QQ(5), QQ(6), QQ(7)], [QQ(0), QQ(7), QQ(8), QQ(9)] ], (3, 4), QQ).transpose() assert A.is_lower() is True assert B.is_lower() is False # Wide matrices: A = DDM([ [QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(5), QQ(6)], [QQ(0), QQ(0), QQ(8)], [QQ(0), QQ(0), QQ(0)] ], (4, 3), QQ).transpose() B = DDM([ [QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(5), QQ(6)], [QQ(0), QQ(0), QQ(8)], [QQ(0), QQ(0), QQ(10)] ], (4, 3), QQ).transpose() assert A.is_lower() is True assert B.is_lower() is False
74706f65858ce87c420d9587d020f1f38d3a2d9ef588676c84cb6f1993df08ac
from sympy.testing.pytest import raises from sympy.core.numbers import Integer, Rational from sympy.core.singleton import S from sympy.functions import sqrt from sympy.matrices.dense import Matrix from sympy.polys.domains import FF, ZZ, QQ, EXRAW from sympy.polys.matrices.domainmatrix import DomainMatrix, DomainScalar, DM from sympy.polys.matrices.exceptions import ( DMBadInputError, DMDomainError, DMShapeError, DMFormatError, DMNotAField, DMNonSquareMatrixError, DMNonInvertibleMatrixError, ) from sympy.polys.matrices.ddm import DDM from sympy.polys.matrices.sdm import SDM def test_DM(): ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A = DM([[1, 2], [3, 4]], ZZ) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == ZZ def test_DomainMatrix_init(): lol = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]] dod = {0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}} ddm = DDM(lol, (2, 2), ZZ) sdm = SDM(dod, (2, 2), ZZ) A = DomainMatrix(lol, (2, 2), ZZ) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == ZZ A = DomainMatrix(dod, (2, 2), ZZ) assert A.rep == sdm assert A.shape == (2, 2) assert A.domain == ZZ raises(TypeError, lambda: DomainMatrix(ddm, (2, 2), ZZ)) raises(TypeError, lambda: DomainMatrix(sdm, (2, 2), ZZ)) raises(TypeError, lambda: DomainMatrix(Matrix([[1]]), (1, 1), ZZ)) for fmt, rep in [('sparse', sdm), ('dense', ddm)]: A = DomainMatrix(lol, (2, 2), ZZ, fmt=fmt) assert A.rep == rep A = DomainMatrix(dod, (2, 2), ZZ, fmt=fmt) assert A.rep == rep raises(ValueError, lambda: DomainMatrix(lol, (2, 2), ZZ, fmt='invalid')) raises(DMBadInputError, lambda: DomainMatrix([[ZZ(1), ZZ(2)]], (2, 2), ZZ)) def test_DomainMatrix_from_rep(): ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A = DomainMatrix.from_rep(ddm) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == ZZ sdm = SDM({0: {0: ZZ(1), 1:ZZ(2)}, 1: {0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) A = DomainMatrix.from_rep(sdm) assert A.rep == sdm assert A.shape == (2, 2) assert A.domain == ZZ A = DomainMatrix([[ZZ(1)]], (1, 1), ZZ) raises(TypeError, lambda: DomainMatrix.from_rep(A)) def test_DomainMatrix_from_list(): ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A = DomainMatrix.from_list([[1, 2], [3, 4]], ZZ) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == ZZ dom = FF(7) ddm = DDM([[dom(1), dom(2)], [dom(3), dom(4)]], (2, 2), dom) A = DomainMatrix.from_list([[1, 2], [3, 4]], dom) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == dom ddm = DDM([[QQ(1, 2), QQ(3, 1)], [QQ(1, 4), QQ(5, 1)]], (2, 2), QQ) A = DomainMatrix.from_list([[(1, 2), (3, 1)], [(1, 4), (5, 1)]], QQ) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == QQ def test_DomainMatrix_from_list_sympy(): ddm = DDM([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A = DomainMatrix.from_list_sympy(2, 2, [[1, 2], [3, 4]]) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == ZZ K = QQ.algebraic_field(sqrt(2)) ddm = DDM( [[K.convert(1 + sqrt(2)), K.convert(2 + sqrt(2))], [K.convert(3 + sqrt(2)), K.convert(4 + sqrt(2))]], (2, 2), K ) A = DomainMatrix.from_list_sympy( 2, 2, [[1 + sqrt(2), 2 + sqrt(2)], [3 + sqrt(2), 4 + sqrt(2)]], extension=True) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == K def test_DomainMatrix_from_dict_sympy(): sdm = SDM({0: {0: QQ(1, 2)}, 1: {1: QQ(2, 3)}}, (2, 2), QQ) sympy_dict = {0: {0: Rational(1, 2)}, 1: {1: Rational(2, 3)}} A = DomainMatrix.from_dict_sympy(2, 2, sympy_dict) assert A.rep == sdm assert A.shape == (2, 2) assert A.domain == QQ fds = DomainMatrix.from_dict_sympy raises(DMBadInputError, lambda: fds(2, 2, {3: {0: Rational(1, 2)}})) raises(DMBadInputError, lambda: fds(2, 2, {0: {3: Rational(1, 2)}})) def test_DomainMatrix_from_Matrix(): sdm = SDM({0: {0: ZZ(1), 1: ZZ(2)}, 1: {0: ZZ(3), 1: ZZ(4)}}, (2, 2), ZZ) A = DomainMatrix.from_Matrix(Matrix([[1, 2], [3, 4]])) assert A.rep == sdm assert A.shape == (2, 2) assert A.domain == ZZ K = QQ.algebraic_field(sqrt(2)) sdm = SDM( {0: {0: K.convert(1 + sqrt(2)), 1: K.convert(2 + sqrt(2))}, 1: {0: K.convert(3 + sqrt(2)), 1: K.convert(4 + sqrt(2))}}, (2, 2), K ) A = DomainMatrix.from_Matrix( Matrix([[1 + sqrt(2), 2 + sqrt(2)], [3 + sqrt(2), 4 + sqrt(2)]]), extension=True) assert A.rep == sdm assert A.shape == (2, 2) assert A.domain == K A = DomainMatrix.from_Matrix(Matrix([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]]), fmt='dense') ddm = DDM([[QQ(1, 2), QQ(3, 4)], [QQ(0, 1), QQ(0, 1)]], (2, 2), QQ) assert A.rep == ddm assert A.shape == (2, 2) assert A.domain == QQ def test_DomainMatrix_eq(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A == A B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(1)]], (2, 2), ZZ) assert A != B C = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]] assert A != C def test_DomainMatrix_unify_eq(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) B1 = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) B2 = DomainMatrix([[QQ(1), QQ(3)], [QQ(3), QQ(4)]], (2, 2), QQ) B3 = DomainMatrix([[ZZ(1)]], (1, 1), ZZ) assert A.unify_eq(B1) is True assert A.unify_eq(B2) is False assert A.unify_eq(B3) is False def test_DomainMatrix_get_domain(): K, items = DomainMatrix.get_domain([1, 2, 3, 4]) assert items == [ZZ(1), ZZ(2), ZZ(3), ZZ(4)] assert K == ZZ K, items = DomainMatrix.get_domain([1, 2, 3, Rational(1, 2)]) assert items == [QQ(1), QQ(2), QQ(3), QQ(1, 2)] assert K == QQ def test_DomainMatrix_convert_to(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Aq = A.convert_to(QQ) assert Aq == DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) def test_DomainMatrix_to_sympy(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.to_sympy() == A.convert_to(EXRAW) def test_DomainMatrix_to_field(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Aq = A.to_field() assert Aq == DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) def test_DomainMatrix_to_sparse(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A_sparse = A.to_sparse() assert A_sparse.rep == {0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}} def test_DomainMatrix_to_dense(): A = DomainMatrix({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ) A_dense = A.to_dense() assert A_dense.rep == DDM([[1, 2], [3, 4]], (2, 2), ZZ) def test_DomainMatrix_unify(): Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) assert Az.unify(Az) == (Az, Az) assert Az.unify(Aq) == (Aq, Aq) assert Aq.unify(Az) == (Aq, Aq) assert Aq.unify(Aq) == (Aq, Aq) As = DomainMatrix({0: {1: ZZ(1)}, 1:{0:ZZ(2)}}, (2, 2), ZZ) Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert As.unify(As) == (As, As) assert Ad.unify(Ad) == (Ad, Ad) Bs, Bd = As.unify(Ad, fmt='dense') assert Bs.rep == DDM([[0, 1], [2, 0]], (2, 2), ZZ) assert Bd.rep == DDM([[1, 2],[3, 4]], (2, 2), ZZ) Bs, Bd = As.unify(Ad, fmt='sparse') assert Bs.rep == SDM({0: {1: 1}, 1: {0: 2}}, (2, 2), ZZ) assert Bd.rep == SDM({0: {0: 1, 1: 2}, 1: {0: 3, 1: 4}}, (2, 2), ZZ) raises(ValueError, lambda: As.unify(Ad, fmt='invalid')) def test_DomainMatrix_to_Matrix(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.to_Matrix() == Matrix([[1, 2], [3, 4]]) def test_DomainMatrix_to_list(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.to_list() == [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]] def test_DomainMatrix_to_list_flat(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.to_list_flat() == [ZZ(1), ZZ(2), ZZ(3), ZZ(4)] def test_DomainMatrix_to_dok(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.to_dok() == {(0, 0):ZZ(1), (0, 1):ZZ(2), (1, 0):ZZ(3), (1, 1):ZZ(4)} def test_DomainMatrix_repr(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert repr(A) == 'DomainMatrix([[1, 2], [3, 4]], (2, 2), ZZ)' def test_DomainMatrix_transpose(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) AT = DomainMatrix([[ZZ(1), ZZ(3)], [ZZ(2), ZZ(4)]], (2, 2), ZZ) assert A.transpose() == AT def test_DomainMatrix_flat(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.flat() == [ZZ(1), ZZ(2), ZZ(3), ZZ(4)] def test_DomainMatrix_is_zero_matrix(): A = DomainMatrix([[ZZ(1)]], (1, 1), ZZ) B = DomainMatrix([[ZZ(0)]], (1, 1), ZZ) assert A.is_zero_matrix is False assert B.is_zero_matrix is True def test_DomainMatrix_is_upper(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(0), ZZ(4)]], (2, 2), ZZ) B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.is_upper is True assert B.is_upper is False def test_DomainMatrix_is_lower(): A = DomainMatrix([[ZZ(1), ZZ(0)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.is_lower is True assert B.is_lower is False def test_DomainMatrix_is_square(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) B = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)], [ZZ(5), ZZ(6)]], (3, 2), ZZ) assert A.is_square is True assert B.is_square is False def test_DomainMatrix_rank(): A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(6), QQ(8)]], (3, 2), QQ) assert A.rank() == 2 def test_DomainMatrix_add(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) B = DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ) assert A + A == A.add(A) == B A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) L = [[2, 3], [3, 4]] raises(TypeError, lambda: A + L) raises(TypeError, lambda: L + A) A1 = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A2 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) raises(DMShapeError, lambda: A1 + A2) raises(DMShapeError, lambda: A2 + A1) raises(DMShapeError, lambda: A1.add(A2)) raises(DMShapeError, lambda: A2.add(A1)) Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) Asum = DomainMatrix([[QQ(2), QQ(4)], [QQ(6), QQ(8)]], (2, 2), QQ) assert Az + Aq == Asum assert Aq + Az == Asum raises(DMDomainError, lambda: Az.add(Aq)) raises(DMDomainError, lambda: Aq.add(Az)) As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ) Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Asd = As + Ad Ads = Ad + As assert Asd == DomainMatrix([[1, 3], [5, 4]], (2, 2), ZZ) assert Asd.rep == DDM([[1, 3], [5, 4]], (2, 2), ZZ) assert Ads == DomainMatrix([[1, 3], [5, 4]], (2, 2), ZZ) assert Ads.rep == DDM([[1, 3], [5, 4]], (2, 2), ZZ) raises(DMFormatError, lambda: As.add(Ad)) def test_DomainMatrix_sub(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) B = DomainMatrix([[ZZ(0), ZZ(0)], [ZZ(0), ZZ(0)]], (2, 2), ZZ) assert A - A == A.sub(A) == B A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) L = [[2, 3], [3, 4]] raises(TypeError, lambda: A - L) raises(TypeError, lambda: L - A) A1 = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A2 = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) raises(DMShapeError, lambda: A1 - A2) raises(DMShapeError, lambda: A2 - A1) raises(DMShapeError, lambda: A1.sub(A2)) raises(DMShapeError, lambda: A2.sub(A1)) Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) Adiff = DomainMatrix([[QQ(0), QQ(0)], [QQ(0), QQ(0)]], (2, 2), QQ) assert Az - Aq == Adiff assert Aq - Az == Adiff raises(DMDomainError, lambda: Az.sub(Aq)) raises(DMDomainError, lambda: Aq.sub(Az)) As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ) Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Asd = As - Ad Ads = Ad - As assert Asd == DomainMatrix([[-1, -1], [-1, -4]], (2, 2), ZZ) assert Asd.rep == DDM([[-1, -1], [-1, -4]], (2, 2), ZZ) assert Asd == -Ads assert Asd.rep == -Ads.rep def test_DomainMatrix_neg(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Aneg = DomainMatrix([[ZZ(-1), ZZ(-2)], [ZZ(-3), ZZ(-4)]], (2, 2), ZZ) assert -A == A.neg() == Aneg def test_DomainMatrix_mul(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A2 = DomainMatrix([[ZZ(7), ZZ(10)], [ZZ(15), ZZ(22)]], (2, 2), ZZ) assert A*A == A.matmul(A) == A2 A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) L = [[1, 2], [3, 4]] raises(TypeError, lambda: A * L) raises(TypeError, lambda: L * A) Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Aq = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) Aprod = DomainMatrix([[QQ(7), QQ(10)], [QQ(15), QQ(22)]], (2, 2), QQ) assert Az * Aq == Aprod assert Aq * Az == Aprod raises(DMDomainError, lambda: Az.matmul(Aq)) raises(DMDomainError, lambda: Aq.matmul(Az)) A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) AA = DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ) x = ZZ(2) assert A * x == x * A == A.mul(x) == AA A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) AA = DomainMatrix.zeros((2, 2), ZZ) x = ZZ(0) assert A * x == x * A == A.mul(x).to_sparse() == AA As = DomainMatrix({0: {1: ZZ(1)}, 1: {0: ZZ(2)}}, (2, 2), ZZ) Ad = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) Asd = As * Ad Ads = Ad * As assert Asd == DomainMatrix([[3, 4], [2, 4]], (2, 2), ZZ) assert Asd.rep == DDM([[3, 4], [2, 4]], (2, 2), ZZ) assert Ads == DomainMatrix([[4, 1], [8, 3]], (2, 2), ZZ) assert Ads.rep == DDM([[4, 1], [8, 3]], (2, 2), ZZ) def test_DomainMatrix_mul_elementwise(): A = DomainMatrix([[ZZ(2), ZZ(2)], [ZZ(0), ZZ(0)]], (2, 2), ZZ) B = DomainMatrix([[ZZ(4), ZZ(0)], [ZZ(3), ZZ(0)]], (2, 2), ZZ) C = DomainMatrix([[ZZ(8), ZZ(0)], [ZZ(0), ZZ(0)]], (2, 2), ZZ) assert A.mul_elementwise(B) == C assert B.mul_elementwise(A) == C def test_DomainMatrix_pow(): eye = DomainMatrix.eye(2, ZZ) A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) A2 = DomainMatrix([[ZZ(7), ZZ(10)], [ZZ(15), ZZ(22)]], (2, 2), ZZ) A3 = DomainMatrix([[ZZ(37), ZZ(54)], [ZZ(81), ZZ(118)]], (2, 2), ZZ) assert A**0 == A.pow(0) == eye assert A**1 == A.pow(1) == A assert A**2 == A.pow(2) == A2 assert A**3 == A.pow(3) == A3 raises(TypeError, lambda: A ** Rational(1, 2)) raises(NotImplementedError, lambda: A ** -1) raises(NotImplementedError, lambda: A.pow(-1)) A = DomainMatrix.zeros((2, 1), ZZ) raises(DMNonSquareMatrixError, lambda: A ** 1) def test_DomainMatrix_scc(): Ad = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(0), ZZ(1), ZZ(0)], [ZZ(2), ZZ(0), ZZ(4)]], (3, 3), ZZ) As = Ad.to_sparse() Addm = Ad.rep Asdm = As.rep for A in [Ad, As, Addm, Asdm]: assert Ad.scc() == [[1], [0, 2]] def test_DomainMatrix_rref(): A = DomainMatrix([], (0, 1), QQ) assert A.rref() == (A, ()) A = DomainMatrix([[QQ(1)]], (1, 1), QQ) assert A.rref() == (A, (0,)) A = DomainMatrix([[QQ(0)]], (1, 1), QQ) assert A.rref() == (A, ()) A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) Ar, pivots = A.rref() assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) assert pivots == (0, 1) A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) Ar, pivots = A.rref() assert Ar == DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) assert pivots == (0, 1) A = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ) Ar, pivots = A.rref() assert Ar == DomainMatrix([[QQ(0), QQ(1)], [QQ(0), QQ(0)]], (2, 2), QQ) assert pivots == (1,) Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) raises(DMNotAField, lambda: Az.rref()) def test_DomainMatrix_columnspace(): A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ) Acol = DomainMatrix([[QQ(1), QQ(1)], [QQ(2), QQ(3)]], (2, 2), QQ) assert A.columnspace() == Acol Az = DomainMatrix([[ZZ(1), ZZ(-1), ZZ(1)], [ZZ(2), ZZ(-2), ZZ(3)]], (2, 3), ZZ) raises(DMNotAField, lambda: Az.columnspace()) A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ, fmt='sparse') Acol = DomainMatrix({0: {0: QQ(1), 1: QQ(1)}, 1: {0: QQ(2), 1: QQ(3)}}, (2, 2), QQ) assert A.columnspace() == Acol def test_DomainMatrix_rowspace(): A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ) assert A.rowspace() == A Az = DomainMatrix([[ZZ(1), ZZ(-1), ZZ(1)], [ZZ(2), ZZ(-2), ZZ(3)]], (2, 3), ZZ) raises(DMNotAField, lambda: Az.rowspace()) A = DomainMatrix([[QQ(1), QQ(-1), QQ(1)], [QQ(2), QQ(-2), QQ(3)]], (2, 3), QQ, fmt='sparse') assert A.rowspace() == A def test_DomainMatrix_nullspace(): A = DomainMatrix([[QQ(1), QQ(1)], [QQ(1), QQ(1)]], (2, 2), QQ) Anull = DomainMatrix([[QQ(-1), QQ(1)]], (1, 2), QQ) assert A.nullspace() == Anull Az = DomainMatrix([[ZZ(1), ZZ(1)], [ZZ(1), ZZ(1)]], (2, 2), ZZ) raises(DMNotAField, lambda: Az.nullspace()) def test_DomainMatrix_solve(): # XXX: Maybe the _solve method should be changed... A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ) b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ) particular = DomainMatrix([[1, 0]], (1, 2), QQ) nullspace = DomainMatrix([[-2, 1]], (1, 2), QQ) assert A._solve(b) == (particular, nullspace) b3 = DomainMatrix([[QQ(1)], [QQ(1)], [QQ(1)]], (3, 1), QQ) raises(DMShapeError, lambda: A._solve(b3)) bz = DomainMatrix([[ZZ(1)], [ZZ(1)]], (2, 1), ZZ) raises(DMNotAField, lambda: A._solve(bz)) def test_DomainMatrix_inv(): A = DomainMatrix([], (0, 0), QQ) assert A.inv() == A A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) Ainv = DomainMatrix([[QQ(-2), QQ(1)], [QQ(3, 2), QQ(-1, 2)]], (2, 2), QQ) assert A.inv() == Ainv Az = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) raises(DMNotAField, lambda: Az.inv()) Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) raises(DMNonSquareMatrixError, lambda: Ans.inv()) Aninv = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(6)]], (2, 2), QQ) raises(DMNonInvertibleMatrixError, lambda: Aninv.inv()) def test_DomainMatrix_det(): A = DomainMatrix([], (0, 0), ZZ) assert A.det() == 1 A = DomainMatrix([[1]], (1, 1), ZZ) assert A.det() == 1 A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.det() == ZZ(-2) A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(3), ZZ(5)]], (3, 3), ZZ) assert A.det() == ZZ(-1) A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]], (3, 3), ZZ) assert A.det() == ZZ(0) Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) raises(DMNonSquareMatrixError, lambda: Ans.det()) A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) assert A.det() == QQ(-2) def test_DomainMatrix_lu(): A = DomainMatrix([], (0, 0), QQ) assert A.lu() == (A, A, []) A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) L = DomainMatrix([[QQ(1), QQ(0)], [QQ(3), QQ(1)]], (2, 2), QQ) U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(-2)]], (2, 2), QQ) swaps = [] assert A.lu() == (L, U, swaps) A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) L = DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) U = DomainMatrix([[QQ(3), QQ(4)], [QQ(0), QQ(2)]], (2, 2), QQ) swaps = [(0, 1)] assert A.lu() == (L, U, swaps) A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ) L = DomainMatrix([[QQ(1), QQ(0)], [QQ(2), QQ(1)]], (2, 2), QQ) U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(0)]], (2, 2), QQ) swaps = [] assert A.lu() == (L, U, swaps) A = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ) L = DomainMatrix([[QQ(1), QQ(0)], [QQ(0), QQ(1)]], (2, 2), QQ) U = DomainMatrix([[QQ(0), QQ(2)], [QQ(0), QQ(4)]], (2, 2), QQ) swaps = [] assert A.lu() == (L, U, swaps) A = DomainMatrix([[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]], (2, 3), QQ) L = DomainMatrix([[QQ(1), QQ(0)], [QQ(4), QQ(1)]], (2, 2), QQ) U = DomainMatrix([[QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(-3), QQ(-6)]], (2, 3), QQ) swaps = [] assert A.lu() == (L, U, swaps) A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ) L = DomainMatrix([ [QQ(1), QQ(0), QQ(0)], [QQ(3), QQ(1), QQ(0)], [QQ(5), QQ(2), QQ(1)]], (3, 3), QQ) U = DomainMatrix([[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]], (3, 2), QQ) swaps = [] assert A.lu() == (L, U, swaps) A = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 1, 2]] L = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 1]] U = [[1, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 1], [0, 0, 0, 1]] to_dom = lambda rows, dom: [[dom(e) for e in row] for row in rows] A = DomainMatrix(to_dom(A, QQ), (4, 4), QQ) L = DomainMatrix(to_dom(L, QQ), (4, 4), QQ) U = DomainMatrix(to_dom(U, QQ), (4, 4), QQ) assert A.lu() == (L, U, []) A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) raises(DMNotAField, lambda: A.lu()) def test_DomainMatrix_lu_solve(): # Base case A = b = x = DomainMatrix([], (0, 0), QQ) assert A.lu_solve(b) == x # Basic example A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ) x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) assert A.lu_solve(b) == x # Example with swaps A = DomainMatrix([[QQ(0), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ) x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) assert A.lu_solve(b) == x # Non-invertible A = DomainMatrix([[QQ(1), QQ(2)], [QQ(2), QQ(4)]], (2, 2), QQ) b = DomainMatrix([[QQ(1)], [QQ(2)]], (2, 1), QQ) raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b)) # Overdetermined, consistent A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ) b = DomainMatrix([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ) x = DomainMatrix([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) assert A.lu_solve(b) == x # Overdetermined, inconsistent A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ) b = DomainMatrix([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ) raises(DMNonInvertibleMatrixError, lambda: A.lu_solve(b)) # Underdetermined A = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) b = DomainMatrix([[QQ(1)]], (1, 1), QQ) raises(NotImplementedError, lambda: A.lu_solve(b)) # Non-field A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) b = DomainMatrix([[ZZ(1)], [ZZ(2)]], (2, 1), ZZ) raises(DMNotAField, lambda: A.lu_solve(b)) # Shape mismatch A = DomainMatrix([[QQ(1), QQ(2)], [QQ(3), QQ(4)]], (2, 2), QQ) b = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) raises(DMShapeError, lambda: A.lu_solve(b)) def test_DomainMatrix_charpoly(): A = DomainMatrix([], (0, 0), ZZ) assert A.charpoly() == [ZZ(1)] A = DomainMatrix([[1]], (1, 1), ZZ) assert A.charpoly() == [ZZ(1), ZZ(-1)] A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert A.charpoly() == [ZZ(1), ZZ(-5), ZZ(-2)] A = DomainMatrix([[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) assert A.charpoly() == [ZZ(1), ZZ(-15), ZZ(-18), ZZ(0)] Ans = DomainMatrix([[QQ(1), QQ(2)]], (1, 2), QQ) raises(DMNonSquareMatrixError, lambda: Ans.charpoly()) def test_DomainMatrix_eye(): A = DomainMatrix.eye(3, QQ) assert A.rep == SDM.eye((3, 3), QQ) assert A.shape == (3, 3) assert A.domain == QQ def test_DomainMatrix_zeros(): A = DomainMatrix.zeros((1, 2), QQ) assert A.rep == SDM.zeros((1, 2), QQ) assert A.shape == (1, 2) assert A.domain == QQ def test_DomainMatrix_ones(): A = DomainMatrix.ones((2, 3), QQ) assert A.rep == DDM.ones((2, 3), QQ) assert A.shape == (2, 3) assert A.domain == QQ def test_DomainMatrix_diag(): A = DomainMatrix({0:{0:ZZ(2)}, 1:{1:ZZ(3)}}, (2, 2), ZZ) assert DomainMatrix.diag([ZZ(2), ZZ(3)], ZZ) == A A = DomainMatrix({0:{0:ZZ(2)}, 1:{1:ZZ(3)}}, (3, 4), ZZ) assert DomainMatrix.diag([ZZ(2), ZZ(3)], ZZ, (3, 4)) == A def test_DomainMatrix_hstack(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ) C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ) AB = DomainMatrix([ [ZZ(1), ZZ(2), ZZ(5), ZZ(6)], [ZZ(3), ZZ(4), ZZ(7), ZZ(8)]], (2, 4), ZZ) ABC = DomainMatrix([ [ZZ(1), ZZ(2), ZZ(5), ZZ(6), ZZ(9), ZZ(10)], [ZZ(3), ZZ(4), ZZ(7), ZZ(8), ZZ(11), ZZ(12)]], (2, 6), ZZ) assert A.hstack(B) == AB assert A.hstack(B, C) == ABC def test_DomainMatrix_vstack(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) B = DomainMatrix([[ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (2, 2), ZZ) C = DomainMatrix([[ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (2, 2), ZZ) AB = DomainMatrix([ [ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)], [ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)]], (4, 2), ZZ) ABC = DomainMatrix([ [ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)], [ZZ(5), ZZ(6)], [ZZ(7), ZZ(8)], [ZZ(9), ZZ(10)], [ZZ(11), ZZ(12)]], (6, 2), ZZ) assert A.vstack(B) == AB assert A.vstack(B, C) == ABC def test_DomainMatrix_applyfunc(): A = DomainMatrix([[ZZ(1), ZZ(2)]], (1, 2), ZZ) B = DomainMatrix([[ZZ(2), ZZ(4)]], (1, 2), ZZ) assert A.applyfunc(lambda x: 2*x) == B def test_DomainMatrix_scalarmul(): A = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) lamda = DomainScalar(QQ(3)/QQ(2), QQ) assert A * lamda == DomainMatrix([[QQ(3, 2), QQ(3)], [QQ(9, 2), QQ(6)]], (2, 2), QQ) assert A * 2 == DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ) assert 2 * A == DomainMatrix([[ZZ(2), ZZ(4)], [ZZ(6), ZZ(8)]], (2, 2), ZZ) assert A * DomainScalar(ZZ(0), ZZ) == DomainMatrix({}, (2, 2), ZZ) assert A * DomainScalar(ZZ(1), ZZ) == A raises(TypeError, lambda: A * 1.5) def test_DomainMatrix_truediv(): A = DomainMatrix.from_Matrix(Matrix([[1, 2], [3, 4]])) lamda = DomainScalar(QQ(3)/QQ(2), QQ) assert A / lamda == DomainMatrix({0: {0: QQ(2, 3), 1: QQ(4, 3)}, 1: {0: QQ(2), 1: QQ(8, 3)}}, (2, 2), QQ) b = DomainScalar(ZZ(1), ZZ) assert A / b == DomainMatrix({0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ) assert A / 1 == DomainMatrix({0: {0: QQ(1), 1: QQ(2)}, 1: {0: QQ(3), 1: QQ(4)}}, (2, 2), QQ) assert A / 2 == DomainMatrix({0: {0: QQ(1, 2), 1: QQ(1)}, 1: {0: QQ(3, 2), 1: QQ(2)}}, (2, 2), QQ) raises(ZeroDivisionError, lambda: A / 0) raises(TypeError, lambda: A / 1.5) raises(ZeroDivisionError, lambda: A / DomainScalar(ZZ(0), ZZ)) def test_DomainMatrix_getitem(): dM = DomainMatrix([ [ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) assert dM[1:,:-2] == DomainMatrix([[ZZ(4)], [ZZ(7)]], (2, 1), ZZ) assert dM[2,:-2] == DomainMatrix([[ZZ(7)]], (1, 1), ZZ) assert dM[:-2,:-2] == DomainMatrix([[ZZ(1)]], (1, 1), ZZ) assert dM[:-1,0:2] == DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(4), ZZ(5)]], (2, 2), ZZ) assert dM[:, -1] == DomainMatrix([[ZZ(3)], [ZZ(6)], [ZZ(9)]], (3, 1), ZZ) assert dM[-1, :] == DomainMatrix([[ZZ(7), ZZ(8), ZZ(9)]], (1, 3), ZZ) assert dM[::-1, :] == DomainMatrix([ [ZZ(7), ZZ(8), ZZ(9)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(1), ZZ(2), ZZ(3)]], (3, 3), ZZ) raises(IndexError, lambda: dM[4, :-2]) raises(IndexError, lambda: dM[:-2, 4]) assert dM[1, 2] == DomainScalar(ZZ(6), ZZ) assert dM[-2, 2] == DomainScalar(ZZ(6), ZZ) assert dM[1, -2] == DomainScalar(ZZ(5), ZZ) assert dM[-1, -3] == DomainScalar(ZZ(7), ZZ) raises(IndexError, lambda: dM[3, 3]) raises(IndexError, lambda: dM[1, 4]) raises(IndexError, lambda: dM[-1, -4]) dM = DomainMatrix({0: {0: ZZ(1)}}, (10, 10), ZZ) assert dM[5, 5] == DomainScalar(ZZ(0), ZZ) assert dM[0, 0] == DomainScalar(ZZ(1), ZZ) dM = DomainMatrix({1: {0: 1}}, (2,1), ZZ) assert dM[0:, 0] == DomainMatrix({1: {0: 1}}, (2, 1), ZZ) raises(IndexError, lambda: dM[3, 0]) dM = DomainMatrix({2: {2: ZZ(1)}, 4: {4: ZZ(1)}}, (5, 5), ZZ) assert dM[:2,:2] == DomainMatrix({}, (2, 2), ZZ) assert dM[2:,2:] == DomainMatrix({0: {0: 1}, 2: {2: 1}}, (3, 3), ZZ) assert dM[3:,3:] == DomainMatrix({1: {1: 1}}, (2, 2), ZZ) assert dM[2:, 6:] == DomainMatrix({}, (3, 0), ZZ) def test_DomainMatrix_getitem_sympy(): dM = DomainMatrix({2: {2: ZZ(2)}, 4: {4: ZZ(1)}}, (5, 5), ZZ) val1 = dM.getitem_sympy(0, 0) assert val1 is S.Zero val2 = dM.getitem_sympy(2, 2) assert val2 == 2 and isinstance(val2, Integer) def test_DomainMatrix_extract(): dM1 = DomainMatrix([ [ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]], (3, 3), ZZ) dM2 = DomainMatrix([ [ZZ(1), ZZ(3)], [ZZ(7), ZZ(9)]], (2, 2), ZZ) assert dM1.extract([0, 2], [0, 2]) == dM2 assert dM1.to_sparse().extract([0, 2], [0, 2]) == dM2.to_sparse() assert dM1.extract([0, -1], [0, -1]) == dM2 assert dM1.to_sparse().extract([0, -1], [0, -1]) == dM2.to_sparse() dM3 = DomainMatrix([ [ZZ(1), ZZ(2), ZZ(2)], [ZZ(4), ZZ(5), ZZ(5)], [ZZ(4), ZZ(5), ZZ(5)]], (3, 3), ZZ) assert dM1.extract([0, 1, 1], [0, 1, 1]) == dM3 assert dM1.to_sparse().extract([0, 1, 1], [0, 1, 1]) == dM3.to_sparse() empty = [ ([], [], (0, 0)), ([1], [], (1, 0)), ([], [1], (0, 1)), ] for rows, cols, size in empty: assert dM1.extract(rows, cols) == DomainMatrix.zeros(size, ZZ).to_dense() assert dM1.to_sparse().extract(rows, cols) == DomainMatrix.zeros(size, ZZ) dM = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) bad_indices = [([2], [0]), ([0], [2]), ([-3], [0]), ([0], [-3])] for rows, cols in bad_indices: raises(IndexError, lambda: dM.extract(rows, cols)) raises(IndexError, lambda: dM.to_sparse().extract(rows, cols)) def test_DomainMatrix_setitem(): dM = DomainMatrix({2: {2: ZZ(1)}, 4: {4: ZZ(1)}}, (5, 5), ZZ) dM[2, 2] = ZZ(2) assert dM == DomainMatrix({2: {2: ZZ(2)}, 4: {4: ZZ(1)}}, (5, 5), ZZ) def setitem(i, j, val): dM[i, j] = val raises(TypeError, lambda: setitem(2, 2, QQ(1, 2))) raises(NotImplementedError, lambda: setitem(slice(1, 2), 2, ZZ(1))) def test_DomainMatrix_pickling(): import pickle dM = DomainMatrix({2: {2: ZZ(1)}, 4: {4: ZZ(1)}}, (5, 5), ZZ) assert pickle.loads(pickle.dumps(dM)) == dM dM = DomainMatrix([[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]], (2, 2), ZZ) assert pickle.loads(pickle.dumps(dM)) == dM
cc7ba81798f067a637fb594c8d2f3df58d4453dced5800b16eaf923bb2246d13
# # test_linsolve.py # # Test the internal implementation of linsolve. # from sympy.testing.pytest import raises from sympy.core.numbers import I from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.abc import x, y, z from sympy.polys.matrices.linsolve import _linsolve from sympy.polys.solvers import PolyNonlinearError def test__linsolve(): assert _linsolve([], [x]) == {x:x} assert _linsolve([S.Zero], [x]) == {x:x} assert _linsolve([x-1,x-2], [x]) is None assert _linsolve([x-1], [x]) == {x:1} assert _linsolve([x-1, y], [x, y]) == {x:1, y:S.Zero} assert _linsolve([2*I], [x]) is None raises(PolyNonlinearError, lambda: _linsolve([x*(1 + x)], [x])) def test__linsolve_float(): # This should give the exact answer: eqs = [ y - x, y - 0.0216 * x ] sol = {x:0.0, y:0.0} assert _linsolve(eqs, (x, y)) == sol # Other cases should be close to eps def all_close(sol1, sol2, eps=1e-15): close = lambda a, b: abs(a - b) < eps assert sol1.keys() == sol2.keys() return all(close(sol1[s], sol2[s]) for s in sol1) eqs = [ 0.8*x + 0.8*z + 0.2, 0.9*x + 0.7*y + 0.2*z + 0.9, 0.7*x + 0.2*y + 0.2*z + 0.5 ] sol_exact = {x:-29/42, y:-11/21, z:37/84} sol_linsolve = _linsolve(eqs, [x,y,z]) assert all_close(sol_exact, sol_linsolve) eqs = [ 0.9*x + 0.3*y + 0.4*z + 0.6, 0.6*x + 0.9*y + 0.1*z + 0.7, 0.4*x + 0.6*y + 0.9*z + 0.5 ] sol_exact = {x:-88/175, y:-46/105, z:-1/25} sol_linsolve = _linsolve(eqs, [x,y,z]) assert all_close(sol_exact, sol_linsolve) eqs = [ 0.4*x + 0.3*y + 0.6*z + 0.7, 0.4*x + 0.3*y + 0.9*z + 0.9, 0.7*x + 0.9*y, ] sol_exact = {x:-9/5, y:7/5, z:-2/3} sol_linsolve = _linsolve(eqs, [x,y,z]) assert all_close(sol_exact, sol_linsolve) eqs = [ x*(0.7 + 0.6*I) + y*(0.4 + 0.7*I) + z*(0.9 + 0.1*I) + 0.5, 0.2*I*x + 0.2*I*y + z*(0.9 + 0.2*I) + 0.1, x*(0.9 + 0.7*I) + y*(0.9 + 0.7*I) + z*(0.9 + 0.4*I) + 0.4, ] sol_exact = { x:-6157/7995 - 411/5330*I, y:8519/15990 + 1784/7995*I, z:-34/533 + 107/1599*I, } sol_linsolve = _linsolve(eqs, [x,y,z]) assert all_close(sol_exact, sol_linsolve) # XXX: This system for x and y over RR(z) is problematic. # # eqs = [ # x*(0.2*z + 0.9) + y*(0.5*z + 0.8) + 0.6, # 0.1*x*z + y*(0.1*z + 0.6) + 0.9, # ] # # linsolve(eqs, [x, y]) # The solution for x comes out as # # -3.9e-5*z**2 - 3.6e-5*z - 8.67361737988404e-20 # x = ---------------------------------------------- # 3.0e-6*z**3 - 1.3e-5*z**2 - 5.4e-5*z # # The 8e-20 in the numerator should be zero which would allow z to cancel # from top and bottom. It should be possible to avoid this somehow because # the inverse of the matrix only has a quadratic factor (the determinant) # in the denominator. def test__linsolve_deprecated(): assert _linsolve([Eq(x**2, x**2+y)], [x, y]) == {x:x, y:S.Zero} assert _linsolve([(x+y)**2-x**2], [x]) == {x:-y/2} assert _linsolve([Eq((x+y)**2, x**2)], [x]) == {x:-y/2}
220fd227cea9a20babf4011f71eb4efcbd357f2d561617be13d83d9e0553971b
from sympy.testing.pytest import raises from sympy.polys import ZZ, QQ from sympy.polys.matrices.ddm import DDM from sympy.polys.matrices.dense import ( ddm_transpose, ddm_iadd, ddm_isub, ddm_ineg, ddm_imatmul, ddm_imul, ddm_irref, ddm_idet, ddm_iinv, ddm_ilu, ddm_ilu_split, ddm_ilu_solve, ddm_berk) from sympy.polys.matrices.exceptions import ( DMShapeError, DMNonInvertibleMatrixError, DMNonSquareMatrixError) def test_ddm_transpose(): a = [[1, 2], [3, 4]] assert ddm_transpose(a) == [[1, 3], [2, 4]] def test_ddm_iadd(): a = [[1, 2], [3, 4]] b = [[5, 6], [7, 8]] ddm_iadd(a, b) assert a == [[6, 8], [10, 12]] def test_ddm_isub(): a = [[1, 2], [3, 4]] b = [[5, 6], [7, 8]] ddm_isub(a, b) assert a == [[-4, -4], [-4, -4]] def test_ddm_ineg(): a = [[1, 2], [3, 4]] ddm_ineg(a) assert a == [[-1, -2], [-3, -4]] def test_ddm_matmul(): a = [[1, 2], [3, 4]] ddm_imul(a, 2) assert a == [[2, 4], [6, 8]] a = [[1, 2], [3, 4]] ddm_imul(a, 0) assert a == [[0, 0], [0, 0]] def test_ddm_imatmul(): a = [[1, 2, 3], [4, 5, 6]] b = [[1, 2], [3, 4], [5, 6]] c1 = [[0, 0], [0, 0]] ddm_imatmul(c1, a, b) assert c1 == [[22, 28], [49, 64]] c2 = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] ddm_imatmul(c2, b, a) assert c2 == [[9, 12, 15], [19, 26, 33], [29, 40, 51]] b3 = [[1], [2], [3]] c3 = [[0], [0]] ddm_imatmul(c3, a, b3) assert c3 == [[14], [32]] def test_ddm_irref(): # Empty matrix A = [] Ar = [] pivots = [] assert ddm_irref(A) == pivots assert A == Ar # Standard square case A = [[QQ(0), QQ(1)], [QQ(1), QQ(1)]] Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]] pivots = [0, 1] assert ddm_irref(A) == pivots assert A == Ar # m < n case A = [[QQ(1), QQ(2), QQ(1)], [QQ(3), QQ(4), QQ(1)]] Ar = [[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]] pivots = [0, 1] assert ddm_irref(A) == pivots assert A == Ar # same m < n but reversed A = [[QQ(3), QQ(4), QQ(1)], [QQ(1), QQ(2), QQ(1)]] Ar = [[QQ(1), QQ(0), QQ(-1)], [QQ(0), QQ(1), QQ(1)]] pivots = [0, 1] assert ddm_irref(A) == pivots assert A == Ar # m > n case A = [[QQ(1), QQ(0)], [QQ(1), QQ(3)], [QQ(0), QQ(1)]] Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]] pivots = [0, 1] assert ddm_irref(A) == pivots assert A == Ar # Example with missing pivot A = [[QQ(1), QQ(0), QQ(1)], [QQ(3), QQ(0), QQ(1)]] Ar = [[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(0), QQ(1)]] pivots = [0, 2] assert ddm_irref(A) == pivots assert A == Ar # Example with missing pivot and no replacement A = [[QQ(0), QQ(1)], [QQ(0), QQ(2)], [QQ(1), QQ(0)]] Ar = [[QQ(1), QQ(0)], [QQ(0), QQ(1)], [QQ(0), QQ(0)]] pivots = [0, 1] assert ddm_irref(A) == pivots assert A == Ar def test_ddm_idet(): A = [] assert ddm_idet(A, ZZ) == ZZ(1) A = [[ZZ(2)]] assert ddm_idet(A, ZZ) == ZZ(2) A = [[ZZ(1), ZZ(2)], [ZZ(3), ZZ(4)]] assert ddm_idet(A, ZZ) == ZZ(-2) A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(3), ZZ(5)]] assert ddm_idet(A, ZZ) == ZZ(-1) A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(1), ZZ(2), ZZ(4)], [ZZ(1), ZZ(2), ZZ(5)]] assert ddm_idet(A, ZZ) == ZZ(0) A = [[QQ(1, 2), QQ(1, 2)], [QQ(1, 3), QQ(1, 4)]] assert ddm_idet(A, QQ) == QQ(-1, 24) def test_ddm_inv(): A = [] Ainv = [] ddm_iinv(Ainv, A, QQ) assert Ainv == A A = [] Ainv = [] raises(ValueError, lambda: ddm_iinv(Ainv, A, ZZ)) A = [[QQ(1), QQ(2)]] Ainv = [[QQ(0), QQ(0)]] raises(DMNonSquareMatrixError, lambda: ddm_iinv(Ainv, A, QQ)) A = [[QQ(1, 1), QQ(2, 1)], [QQ(3, 1), QQ(4, 1)]] Ainv = [[QQ(0), QQ(0)], [QQ(0), QQ(0)]] Ainv_expected = [[QQ(-2, 1), QQ(1, 1)], [QQ(3, 2), QQ(-1, 2)]] ddm_iinv(Ainv, A, QQ) assert Ainv == Ainv_expected A = [[QQ(1, 1), QQ(2, 1)], [QQ(2, 1), QQ(4, 1)]] Ainv = [[QQ(0), QQ(0)], [QQ(0), QQ(0)]] raises(DMNonInvertibleMatrixError, lambda: ddm_iinv(Ainv, A, QQ)) def test_ddm_ilu(): A = [] Alu = [] swaps = ddm_ilu(A) assert A == Alu assert swaps == [] A = [[]] Alu = [[]] swaps = ddm_ilu(A) assert A == Alu assert swaps == [] A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]] Alu = [[QQ(1), QQ(2)], [QQ(3), QQ(-2)]] swaps = ddm_ilu(A) assert A == Alu assert swaps == [] A = [[QQ(0), QQ(2)], [QQ(3), QQ(4)]] Alu = [[QQ(3), QQ(4)], [QQ(0), QQ(2)]] swaps = ddm_ilu(A) assert A == Alu assert swaps == [(0, 1)] A = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)], [QQ(7), QQ(8), QQ(9)]] Alu = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(-3), QQ(-6)], [QQ(7), QQ(2), QQ(0)]] swaps = ddm_ilu(A) assert A == Alu assert swaps == [] A = [[QQ(0), QQ(1), QQ(2)], [QQ(0), QQ(1), QQ(3)], [QQ(1), QQ(1), QQ(2)]] Alu = [[QQ(1), QQ(1), QQ(2)], [QQ(0), QQ(1), QQ(3)], [QQ(0), QQ(1), QQ(-1)]] swaps = ddm_ilu(A) assert A == Alu assert swaps == [(0, 2)] A = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]] Alu = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(-3), QQ(-6)]] swaps = ddm_ilu(A) assert A == Alu assert swaps == [] A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]] Alu = [[QQ(1), QQ(2)], [QQ(3), QQ(-2)], [QQ(5), QQ(2)]] swaps = ddm_ilu(A) assert A == Alu assert swaps == [] def test_ddm_ilu_split(): U = [] L = [] Uexp = [] Lexp = [] swaps = ddm_ilu_split(L, U, QQ) assert U == Uexp assert L == Lexp assert swaps == [] U = [[]] L = [[QQ(1)]] Uexp = [[]] Lexp = [[QQ(1)]] swaps = ddm_ilu_split(L, U, QQ) assert U == Uexp assert L == Lexp assert swaps == [] U = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]] L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]] Uexp = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)]] Lexp = [[QQ(1), QQ(0)], [QQ(3), QQ(1)]] swaps = ddm_ilu_split(L, U, QQ) assert U == Uexp assert L == Lexp assert swaps == [] U = [[QQ(1), QQ(2), QQ(3)], [QQ(4), QQ(5), QQ(6)]] L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]] Uexp = [[QQ(1), QQ(2), QQ(3)], [QQ(0), QQ(-3), QQ(-6)]] Lexp = [[QQ(1), QQ(0)], [QQ(4), QQ(1)]] swaps = ddm_ilu_split(L, U, QQ) assert U == Uexp assert L == Lexp assert swaps == [] U = [[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]] L = [[QQ(1), QQ(0), QQ(0)], [QQ(0), QQ(1), QQ(0)], [QQ(0), QQ(0), QQ(1)]] Uexp = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]] Lexp = [[QQ(1), QQ(0), QQ(0)], [QQ(3), QQ(1), QQ(0)], [QQ(5), QQ(2), QQ(1)]] swaps = ddm_ilu_split(L, U, QQ) assert U == Uexp assert L == Lexp assert swaps == [] def test_ddm_ilu_solve(): # Basic example # A = [[QQ(1), QQ(2)], [QQ(3), QQ(4)]] U = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)]] L = [[QQ(1), QQ(0)], [QQ(3), QQ(1)]] swaps = [] b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ) xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) ddm_ilu_solve(x, L, U, swaps, b) assert x == xexp # Example with swaps # A = [[QQ(0), QQ(2)], [QQ(3), QQ(4)]] U = [[QQ(3), QQ(4)], [QQ(0), QQ(2)]] L = [[QQ(1), QQ(0)], [QQ(0), QQ(1)]] swaps = [(0, 1)] b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ) xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) ddm_ilu_solve(x, L, U, swaps, b) assert x == xexp # Overdetermined, consistent # A = DDM([[QQ(1), QQ(2)], [QQ(3), QQ(4)], [QQ(5), QQ(6)]], (3, 2), QQ) U = [[QQ(1), QQ(2)], [QQ(0), QQ(-2)], [QQ(0), QQ(0)]] L = [[QQ(1), QQ(0), QQ(0)], [QQ(3), QQ(1), QQ(0)], [QQ(5), QQ(2), QQ(1)]] swaps = [] b = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ) x = DDM([[QQ(0)], [QQ(0)]], (2, 1), QQ) xexp = DDM([[QQ(0)], [QQ(1, 2)]], (2, 1), QQ) ddm_ilu_solve(x, L, U, swaps, b) assert x == xexp # Overdetermined, inconsistent b = DDM([[QQ(1)], [QQ(2)], [QQ(4)]], (3, 1), QQ) raises(DMNonInvertibleMatrixError, lambda: ddm_ilu_solve(x, L, U, swaps, b)) # Square, noninvertible # A = DDM([[QQ(1), QQ(2)], [QQ(1), QQ(2)]], (2, 2), QQ) U = [[QQ(1), QQ(2)], [QQ(0), QQ(0)]] L = [[QQ(1), QQ(0)], [QQ(1), QQ(1)]] swaps = [] b = DDM([[QQ(1)], [QQ(2)]], (2, 1), QQ) raises(DMNonInvertibleMatrixError, lambda: ddm_ilu_solve(x, L, U, swaps, b)) # Underdetermined # A = DDM([[QQ(1), QQ(2)]], (1, 2), QQ) U = [[QQ(1), QQ(2)]] L = [[QQ(1)]] swaps = [] b = DDM([[QQ(3)]], (1, 1), QQ) raises(NotImplementedError, lambda: ddm_ilu_solve(x, L, U, swaps, b)) # Shape mismatch b3 = DDM([[QQ(1)], [QQ(2)], [QQ(3)]], (3, 1), QQ) raises(DMShapeError, lambda: ddm_ilu_solve(x, L, U, swaps, b3)) # Empty shape mismatch U = [[QQ(1)]] L = [[QQ(1)]] swaps = [] x = [[QQ(1)]] b = [] raises(DMShapeError, lambda: ddm_ilu_solve(x, L, U, swaps, b)) # Empty system U = [] L = [] swaps = [] b = [] x = [] ddm_ilu_solve(x, L, U, swaps, b) assert x == [] def test_ddm_charpoly(): A = [] assert ddm_berk(A, ZZ) == [[ZZ(1)]] A = [[ZZ(1), ZZ(2), ZZ(3)], [ZZ(4), ZZ(5), ZZ(6)], [ZZ(7), ZZ(8), ZZ(9)]] Avec = [[ZZ(1)], [ZZ(-15)], [ZZ(-18)], [ZZ(0)]] assert ddm_berk(A, ZZ) == Avec A = DDM([[ZZ(1), ZZ(2)]], (1, 2), ZZ) raises(DMShapeError, lambda: ddm_berk(A, ZZ))
1f4a0d664366c293fc8ba529cac9e40fbc9abded04dd853767c74a1a86d26ce0
""" Tests for the basic functionality of the SDM class. """ from itertools import product from sympy.core.singleton import S from sympy.external.gmpy import HAS_GMPY from sympy.testing.pytest import raises from sympy.polys.domains import QQ, ZZ, EXRAW from sympy.polys.matrices.sdm import SDM from sympy.polys.matrices.ddm import DDM from sympy.polys.matrices.exceptions import (DMBadInputError, DMDomainError, DMShapeError) def test_SDM(): A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ) assert A.domain == ZZ assert A.shape == (2, 2) assert dict(A) == {0:{0:ZZ(1)}} raises(DMBadInputError, lambda: SDM({5:{1:ZZ(0)}}, (2, 2), ZZ)) raises(DMBadInputError, lambda: SDM({0:{5:ZZ(0)}}, (2, 2), ZZ)) def test_DDM_str(): sdm = SDM({0:{0:ZZ(1)}, 1:{1:ZZ(1)}}, (2, 2), ZZ) assert str(sdm) == '{0: {0: 1}, 1: {1: 1}}' if HAS_GMPY: # pragma: no cover assert repr(sdm) == 'SDM({0: {0: mpz(1)}, 1: {1: mpz(1)}}, (2, 2), ZZ)' else: # pragma: no cover assert repr(sdm) == 'SDM({0: {0: 1}, 1: {1: 1}}, (2, 2), ZZ)' def test_SDM_new(): A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ) B = A.new({}, (2, 2), ZZ) assert B == SDM({}, (2, 2), ZZ) def test_SDM_copy(): A = SDM({0:{0:ZZ(1)}}, (2, 2), ZZ) B = A.copy() assert A == B A[0][0] = ZZ(2) assert A != B def test_SDM_from_list(): A = SDM.from_list([[ZZ(0), ZZ(1)], [ZZ(1), ZZ(0)]], (2, 2), ZZ) assert A == SDM({0:{1:ZZ(1)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) raises(DMBadInputError, lambda: SDM.from_list([[ZZ(0)], [ZZ(0), ZZ(1)]], (2, 2), ZZ)) raises(DMBadInputError, lambda: SDM.from_list([[ZZ(0), ZZ(1)]], (2, 2), ZZ)) def test_SDM_to_list(): A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ) assert A.to_list() == [[ZZ(0), ZZ(1)], [ZZ(0), ZZ(0)]] A = SDM({}, (0, 2), ZZ) assert A.to_list() == [] A = SDM({}, (2, 0), ZZ) assert A.to_list() == [[], []] def test_SDM_to_list_flat(): A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ) assert A.to_list_flat() == [ZZ(0), ZZ(1), ZZ(0), ZZ(0)] def test_SDM_to_dok(): A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ) assert A.to_dok() == {(0, 1): ZZ(1)} def test_SDM_from_ddm(): A = DDM([[ZZ(1), ZZ(0)], [ZZ(1), ZZ(0)]], (2, 2), ZZ) B = SDM.from_ddm(A) assert B.domain == ZZ assert B.shape == (2, 2) assert dict(B) == {0:{0:ZZ(1)}, 1:{0:ZZ(1)}} def test_SDM_to_ddm(): A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ) B = DDM([[ZZ(0), ZZ(1)], [ZZ(0), ZZ(0)]], (2, 2), ZZ) assert A.to_ddm() == B def test_SDM_to_sdm(): A = SDM({0:{1: ZZ(1)}}, (2, 2), ZZ) assert A.to_sdm() == A def test_SDM_getitem(): A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) assert A.getitem(0, 0) == ZZ.zero assert A.getitem(0, 1) == ZZ.one assert A.getitem(1, 0) == ZZ.zero assert A.getitem(-2, -2) == ZZ.zero assert A.getitem(-2, -1) == ZZ.one assert A.getitem(-1, -2) == ZZ.zero raises(IndexError, lambda: A.getitem(2, 0)) raises(IndexError, lambda: A.getitem(0, 2)) def test_SDM_setitem(): A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) A.setitem(0, 0, ZZ(1)) assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ) A.setitem(1, 0, ZZ(1)) assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{0:ZZ(1)}}, (2, 2), ZZ) A.setitem(1, 0, ZZ(0)) assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ) # Repeat the above test so that this time the row is empty A.setitem(1, 0, ZZ(0)) assert A == SDM({0:{0:ZZ(1), 1:ZZ(1)}}, (2, 2), ZZ) A.setitem(0, 0, ZZ(0)) assert A == SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) # This time the row is there but column is empty A.setitem(0, 0, ZZ(0)) assert A == SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) raises(IndexError, lambda: A.setitem(2, 0, ZZ(1))) raises(IndexError, lambda: A.setitem(0, 2, ZZ(1))) def test_SDM_extract_slice(): A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) B = A.extract_slice(slice(1, 2), slice(1, 2)) assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ) def test_SDM_extract(): A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) B = A.extract([1], [1]) assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ) B = A.extract([1, 0], [1, 0]) assert B == SDM({0:{0:ZZ(4), 1:ZZ(3)}, 1:{0:ZZ(2), 1:ZZ(1)}}, (2, 2), ZZ) B = A.extract([1, 1], [1, 1]) assert B == SDM({0:{0:ZZ(4), 1:ZZ(4)}, 1:{0:ZZ(4), 1:ZZ(4)}}, (2, 2), ZZ) B = A.extract([-1], [-1]) assert B == SDM({0:{0:ZZ(4)}}, (1, 1), ZZ) A = SDM({}, (2, 2), ZZ) B = A.extract([0, 1, 0], [0, 0]) assert B == SDM({}, (3, 2), ZZ) A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) assert A.extract([], []) == SDM.zeros((0, 0), ZZ) assert A.extract([1], []) == SDM.zeros((1, 0), ZZ) assert A.extract([], [1]) == SDM.zeros((0, 1), ZZ) raises(IndexError, lambda: A.extract([2], [0])) raises(IndexError, lambda: A.extract([0], [2])) raises(IndexError, lambda: A.extract([-3], [0])) raises(IndexError, lambda: A.extract([0], [-3])) def test_SDM_zeros(): A = SDM.zeros((2, 2), ZZ) assert A.domain == ZZ assert A.shape == (2, 2) assert dict(A) == {} def test_SDM_ones(): A = SDM.ones((1, 2), QQ) assert A.domain == QQ assert A.shape == (1, 2) assert dict(A) == {0:{0:QQ(1), 1:QQ(1)}} def test_SDM_eye(): A = SDM.eye((2, 2), ZZ) assert A.domain == ZZ assert A.shape == (2, 2) assert dict(A) == {0:{0:ZZ(1)}, 1:{1:ZZ(1)}} def test_SDM_diag(): A = SDM.diag([ZZ(1), ZZ(2)], ZZ, (2, 3)) assert A == SDM({0:{0:ZZ(1)}, 1:{1:ZZ(2)}}, (2, 3), ZZ) def test_SDM_transpose(): A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(1), 1:ZZ(3)}, 1:{0:ZZ(2), 1:ZZ(4)}}, (2, 2), ZZ) assert A.transpose() == B A = SDM({0:{1:ZZ(2)}}, (2, 2), ZZ) B = SDM({1:{0:ZZ(2)}}, (2, 2), ZZ) assert A.transpose() == B A = SDM({0:{1:ZZ(2)}}, (1, 2), ZZ) B = SDM({1:{0:ZZ(2)}}, (2, 1), ZZ) assert A.transpose() == B def test_SDM_mul(): A = SDM({0:{0:ZZ(2)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ) assert A*ZZ(2) == B assert ZZ(2)*A == B raises(TypeError, lambda: A*QQ(1, 2)) raises(TypeError, lambda: QQ(1, 2)*A) def test_SDM_mul_elementwise(): A = SDM({0:{0:ZZ(2), 1:ZZ(2)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(4)}, 1:{0:ZZ(3)}}, (2, 2), ZZ) C = SDM({0:{0:ZZ(8)}}, (2, 2), ZZ) assert A.mul_elementwise(B) == C assert B.mul_elementwise(A) == C Aq = A.convert_to(QQ) A1 = SDM({0:{0:ZZ(1)}}, (1, 1), ZZ) raises(DMDomainError, lambda: Aq.mul_elementwise(B)) raises(DMShapeError, lambda: A1.mul_elementwise(B)) def test_SDM_matmul(): A = SDM({0:{0:ZZ(2)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ) assert A.matmul(A) == A*A == B C = SDM({0:{0:ZZ(2)}}, (2, 2), QQ) raises(DMDomainError, lambda: A.matmul(C)) A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(7), 1:ZZ(10)}, 1:{0:ZZ(15), 1:ZZ(22)}}, (2, 2), ZZ) assert A.matmul(A) == A*A == B A22 = SDM({0:{0:ZZ(4)}}, (2, 2), ZZ) A32 = SDM({0:{0:ZZ(2)}}, (3, 2), ZZ) A23 = SDM({0:{0:ZZ(4)}}, (2, 3), ZZ) A33 = SDM({0:{0:ZZ(8)}}, (3, 3), ZZ) A22 = SDM({0:{0:ZZ(8)}}, (2, 2), ZZ) assert A32.matmul(A23) == A33 assert A23.matmul(A32) == A22 # XXX: @ not supported by SDM... #assert A32.matmul(A23) == A32 @ A23 == A33 #assert A23.matmul(A32) == A23 @ A32 == A22 #raises(DMShapeError, lambda: A23 @ A22) raises(DMShapeError, lambda: A23.matmul(A22)) A = SDM({0: {0: ZZ(-1), 1: ZZ(1)}}, (1, 2), ZZ) B = SDM({0: {0: ZZ(-1)}, 1: {0: ZZ(-1)}}, (2, 1), ZZ) assert A.matmul(B) == A*B == SDM({}, (1, 1), ZZ) def test_matmul_exraw(): def dm(d): result = {} for i, row in d.items(): row = {j:val for j, val in row.items() if val} if row: result[i] = row return SDM(result, (2, 2), EXRAW) values = [S.NegativeInfinity, S.NegativeOne, S.Zero, S.One, S.Infinity] for a, b, c, d in product(*[values]*4): Ad = dm({0: {0:a, 1:b}, 1: {0:c, 1:d}}) Ad2 = dm({0: {0:a*a + b*c, 1:a*b + b*d}, 1:{0:c*a + d*c, 1: c*b + d*d}}) assert Ad * Ad == Ad2 def test_SDM_add(): A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ) C = SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{1:ZZ(6)}}, (2, 2), ZZ) assert A.add(B) == B.add(A) == A + B == B + A == C A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ) C = SDM({0:{0:ZZ(1), 1:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ) assert A.add(B) == B.add(A) == A + B == B + A == C raises(TypeError, lambda: A + []) def test_SDM_sub(): A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ) B = SDM({0:{0:ZZ(1)}, 1:{0:ZZ(-2), 1:ZZ(3)}}, (2, 2), ZZ) C = SDM({0:{0:ZZ(-1), 1:ZZ(1)}, 1:{0:ZZ(4)}}, (2, 2), ZZ) assert A.sub(B) == A - B == C raises(TypeError, lambda: A - []) def test_SDM_neg(): A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ) B = SDM({0:{1:ZZ(-1)}, 1:{0:ZZ(-2), 1:ZZ(-3)}}, (2, 2), ZZ) assert A.neg() == -A == B def test_SDM_convert_to(): A = SDM({0:{1:ZZ(1)}, 1:{0:ZZ(2), 1:ZZ(3)}}, (2, 2), ZZ) B = SDM({0:{1:QQ(1)}, 1:{0:QQ(2), 1:QQ(3)}}, (2, 2), QQ) C = A.convert_to(QQ) assert C == B assert C.domain == QQ D = A.convert_to(ZZ) assert D == A assert D.domain == ZZ def test_SDM_hstack(): A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) B = SDM({1:{1:ZZ(1)}}, (2, 2), ZZ) AA = SDM({0:{1:ZZ(1), 3:ZZ(1)}}, (2, 4), ZZ) AB = SDM({0:{1:ZZ(1)}, 1:{3:ZZ(1)}}, (2, 4), ZZ) assert SDM.hstack(A) == A assert SDM.hstack(A, A) == AA assert SDM.hstack(A, B) == AB def test_SDM_vstack(): A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) B = SDM({1:{1:ZZ(1)}}, (2, 2), ZZ) AA = SDM({0:{1:ZZ(1)}, 2:{1:ZZ(1)}}, (4, 2), ZZ) AB = SDM({0:{1:ZZ(1)}, 3:{1:ZZ(1)}}, (4, 2), ZZ) assert SDM.vstack(A) == A assert SDM.vstack(A, A) == AA assert SDM.vstack(A, B) == AB def test_SDM_applyfunc(): A = SDM({0:{1:ZZ(1)}}, (2, 2), ZZ) B = SDM({0:{1:ZZ(2)}}, (2, 2), ZZ) assert A.applyfunc(lambda x: 2*x, ZZ) == B def test_SDM_inv(): A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) B = SDM({0:{0:QQ(-2), 1:QQ(1)}, 1:{0:QQ(3, 2), 1:QQ(-1, 2)}}, (2, 2), QQ) assert A.inv() == B def test_SDM_det(): A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) assert A.det() == QQ(-2) def test_SDM_lu(): A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) L = SDM({0:{0:QQ(1)}, 1:{0:QQ(3), 1:QQ(1)}}, (2, 2), QQ) #U = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(-2)}}, (2, 2), QQ) #swaps = [] # This doesn't quite work. U has some nonzero elements in the lower part. #assert A.lu() == (L, U, swaps) assert A.lu()[0] == L def test_SDM_lu_solve(): A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) b = SDM({0:{0:QQ(1)}, 1:{0:QQ(2)}}, (2, 1), QQ) x = SDM({1:{0:QQ(1, 2)}}, (2, 1), QQ) assert A.matmul(x) == b assert A.lu_solve(b) == x def test_SDM_charpoly(): A = SDM({0:{0:ZZ(1), 1:ZZ(2)}, 1:{0:ZZ(3), 1:ZZ(4)}}, (2, 2), ZZ) assert A.charpoly() == [ZZ(1), ZZ(-5), ZZ(-2)] def test_SDM_nullspace(): A = SDM({0:{0:QQ(1), 1:QQ(1)}}, (2, 2), QQ) assert A.nullspace()[0] == SDM({0:{0:QQ(-1), 1:QQ(1)}}, (1, 2), QQ) def test_SDM_rref(): eye2 = SDM({0:{0:QQ(1)}, 1:{1:QQ(1)}}, (2, 2), QQ) A = SDM({0:{0:QQ(1), 1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) assert A.rref() == (eye2, [0, 1]) A = SDM({0:{0:QQ(1)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) assert A.rref() == (eye2, [0, 1]) A = SDM({0:{1:QQ(2)}, 1:{0:QQ(3), 1:QQ(4)}}, (2, 2), QQ) assert A.rref() == (eye2, [0, 1]) A = SDM({0:{0:QQ(1), 1:QQ(2), 2:QQ(3)}, 1:{0:QQ(4), 1:QQ(5), 2:QQ(6)}, 2:{0:QQ(7), 1:QQ(8), 2:QQ(9)} }, (3, 3), QQ) Arref = SDM({0:{0:QQ(1), 2:QQ(-1)}, 1:{1:QQ(1), 2:QQ(2)}}, (3, 3), QQ) assert A.rref() == (Arref, [0, 1]) A = SDM({0:{0:QQ(1), 1:QQ(2), 3:QQ(1)}, 1:{0:QQ(1), 1:QQ(1), 2:QQ(9)}}, (2, 4), QQ) Arref = SDM({0:{0:QQ(1), 2:QQ(18), 3:QQ(-1)}, 1:{1:QQ(1), 2:QQ(-9), 3:QQ(1)}}, (2, 4), QQ) assert A.rref() == (Arref, [0, 1]) A = SDM({0:{0:QQ(1), 1:QQ(1), 2:QQ(1)}, 1:{0:QQ(1), 1:QQ(2), 2:QQ(2)}}, (2, 3), QQ) Arref = SDM( {0: {0: QQ(1,1)}, 1: {1: QQ(1,1), 2: QQ(1,1)}}, (2, 3), QQ) assert A.rref() == (Arref, [0, 1]) def test_SDM_particular(): A = SDM({0:{0:QQ(1)}}, (2, 2), QQ) Apart = SDM.zeros((1, 2), QQ) assert A.particular() == Apart def test_SDM_is_zero_matrix(): A = SDM({0: {0: QQ(1)}}, (2, 2), QQ) Azero = SDM.zeros((1, 2), QQ) assert A.is_zero_matrix() is False assert Azero.is_zero_matrix() is True def test_SDM_is_upper(): A = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)}, 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)}, 2: {2: QQ(8), 3: QQ(9)}}, (3, 4), QQ) B = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)}, 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)}, 2: {1: QQ(7), 2: QQ(8), 3: QQ(9)}}, (3, 4), QQ) assert A.is_upper() is True assert B.is_upper() is False def test_SDM_is_lower(): A = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)}, 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)}, 2: {2: QQ(8), 3: QQ(9)}}, (3, 4), QQ ).transpose() B = SDM({0: {0: QQ(1), 1: QQ(2), 2: QQ(3), 3: QQ(4)}, 1: {1: QQ(5), 2: QQ(6), 3: QQ(7)}, 2: {1: QQ(7), 2: QQ(8), 3: QQ(9)}}, (3, 4), QQ ).transpose() assert A.is_lower() is True assert B.is_lower() is False
137b9282b81b4d1fc67ab8b41bad35f74dbbcafd83f3bc9b6a07dacfe82588a2
from sympy.core.add import Add from sympy.core.basic import Basic from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.logic.boolalg import 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.functions.elementary.trigonometric import (cos, sin) 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.matrices.expressions.matexpr 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.sets.sets 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.sets.sets import FiniteSet a, b, c, x, y, z = symbols('a,b,c,x,y,z') expr = FiniteSet(Basic(S(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(S(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.sets.sets 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.functions.elementary.trigonometric import (cos, sin) 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)))
e1396072157a356b817a4271f511a5323c77f94c289f38086170f2b5beec0515
from sympy.unify.core import Compound, Variable, CondVariable, allcombinations from sympy.unify import core a,b,c = 'a', 'b', 'c' w,x,y,z = map(Variable, 'wxyz') C = Compound def is_associative(x): return isinstance(x, Compound) and (x.op in ('Add', 'Mul', 'CAdd', 'CMul')) def is_commutative(x): return isinstance(x, Compound) and (x.op in ('CAdd', 'CMul')) def unify(a, b, s={}): return core.unify(a, b, s=s, is_associative=is_associative, is_commutative=is_commutative) def test_basic(): assert list(unify(a, x, {})) == [{x: a}] assert list(unify(a, x, {x: 10})) == [] assert list(unify(1, x, {})) == [{x: 1}] assert list(unify(a, a, {})) == [{}] assert list(unify((w, x), (y, z), {})) == [{w: y, x: z}] assert list(unify(x, (a, b), {})) == [{x: (a, b)}] assert list(unify((a, b), (x, x), {})) == [] assert list(unify((y, z), (x, x), {}))!= [] assert list(unify((a, (b, c)), (a, (x, y)), {})) == [{x: b, y: c}] def test_ops(): assert list(unify(C('Add', (a,b,c)), C('Add', (a,x,y)), {})) == \ [{x:b, y:c}] assert list(unify(C('Add', (C('Mul', (1,2)), b,c)), C('Add', (x,y,c)), {})) == \ [{x: C('Mul', (1,2)), y:b}] def test_associative(): c1 = C('Add', (1,2,3)) c2 = C('Add', (x,y)) assert tuple(unify(c1, c2, {})) == ({x: 1, y: C('Add', (2, 3))}, {x: C('Add', (1, 2)), y: 3}) def test_commutative(): c1 = C('CAdd', (1,2,3)) c2 = C('CAdd', (x,y)) result = list(unify(c1, c2, {})) assert {x: 1, y: C('CAdd', (2, 3))} in result assert ({x: 2, y: C('CAdd', (1, 3))} in result or {x: 2, y: C('CAdd', (3, 1))} in result) def _test_combinations_assoc(): assert set(allcombinations((1,2,3), (a,b), True)) == \ {(((1, 2), (3,)), (a, b)), (((1,), (2, 3)), (a, b))} def _test_combinations_comm(): assert set(allcombinations((1,2,3), (a,b), None)) == \ {(((1,), (2, 3)), ('a', 'b')), (((2,), (3, 1)), ('a', 'b')), (((3,), (1, 2)), ('a', 'b')), (((1, 2), (3,)), ('a', 'b')), (((2, 3), (1,)), ('a', 'b')), (((3, 1), (2,)), ('a', 'b'))} def test_allcombinations(): assert set(allcombinations((1,2), (1,2), 'commutative')) ==\ {(((1,),(2,)), ((1,),(2,))), (((1,),(2,)), ((2,),(1,)))} def test_commutativity(): c1 = Compound('CAdd', (a, b)) c2 = Compound('CAdd', (x, y)) assert is_commutative(c1) and is_commutative(c2) assert len(list(unify(c1, c2, {}))) == 2 def test_CondVariable(): expr = C('CAdd', (1, 2)) x = Variable('x') y = CondVariable('y', lambda a: a % 2 == 0) z = CondVariable('z', lambda a: a > 3) pattern = C('CAdd', (x, y)) assert list(unify(expr, pattern, {})) == \ [{x: 1, y: 2}] z = CondVariable('z', lambda a: a > 3) pattern = C('CAdd', (z, y)) assert list(unify(expr, pattern, {})) == [] def test_defaultdict(): assert next(unify(Variable('x'), 'foo')) == {Variable('x'): 'foo'}
613ef40d51826be6803b3a08e19b654d959bbd3451d26d1fb19489a5e4469328
from sympy.unify.rewrite import rewriterule from sympy.core.basic import Basic from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.trigonometric import sin from sympy.abc import x, y from sympy.strategies.rl import rebuild from sympy.assumptions import Q p, q = Symbol('p'), Symbol('q') def test_simple(): rl = rewriterule(Basic(p, 1), Basic(p, 2), variables=(p,)) assert list(rl(Basic(3, 1))) == [Basic(3, 2)] p1 = p**2 p2 = p**3 rl = rewriterule(p1, p2, variables=(p,)) expr = x**2 assert list(rl(expr)) == [x**3] def test_simple_variables(): rl = rewriterule(Basic(x, 1), Basic(x, 2), variables=(x,)) assert list(rl(Basic(3, 1))) == [Basic(3, 2)] rl = rewriterule(x**2, x**3, variables=(x,)) assert list(rl(y**2)) == [y**3] def test_moderate(): p1 = p**2 + q**3 p2 = (p*q)**4 rl = rewriterule(p1, p2, (p, q)) expr = x**2 + y**3 assert list(rl(expr)) == [(x*y)**4] def test_sincos(): p1 = sin(p)**2 + sin(p)**2 p2 = 1 rl = rewriterule(p1, p2, (p, q)) assert list(rl(sin(x)**2 + sin(x)**2)) == [1] assert list(rl(sin(y)**2 + sin(y)**2)) == [1] def test_Exprs_ok(): rl = rewriterule(p+q, q+p, (p, q)) next(rl(x+y)).is_commutative str(next(rl(x+y))) def test_condition_simple(): rl = rewriterule(x, x+1, [x], lambda x: x < 10) assert not list(rl(S(15))) assert rebuild(next(rl(S(5)))) == 6 def test_condition_multiple(): rl = rewriterule(x + y, x**y, [x,y], lambda x, y: x.is_integer) a = Symbol('a') b = Symbol('b', integer=True) expr = a + b assert list(rl(expr)) == [b**a] c = Symbol('c', integer=True) d = Symbol('d', integer=True) assert set(rl(c + d)) == {c**d, d**c} def test_assumptions(): rl = rewriterule(x + y, x**y, [x, y], assume=Q.integer(x)) a, b = map(Symbol, 'ab') expr = a + b assert list(rl(expr, Q.integer(b))) == [b**a]
06deddc6490faeffb0f789e09c5974cff26faca4129c79362ba61e490a2256cf
#!/usr/bin/env python """ Import diagnostics. Run bin/diagnose_imports.py --help for details. """ from typing import Dict as tDict if __name__ == "__main__": import sys import inspect import builtins import optparse from os.path import abspath, dirname, join, normpath this_file = abspath(__file__) sympy_dir = join(dirname(this_file), '..', '..', '..') sympy_dir = normpath(sympy_dir) sys.path.insert(0, sympy_dir) option_parser = optparse.OptionParser( usage= "Usage: %prog option [options]\n" "\n" "Import analysis for imports between SymPy modules.") option_group = optparse.OptionGroup( option_parser, 'Analysis options', 'Options that define what to do. Exactly one of these must be given.') option_group.add_option( '--problems', help= 'Print all import problems, that is: ' 'If an import pulls in a package instead of a module ' '(e.g. sympy.core instead of sympy.core.add); ' # see ##PACKAGE## 'if it imports a symbol that is already present; ' # see ##DUPLICATE## 'if it imports a symbol ' 'from somewhere other than the defining module.', # see ##ORIGIN## action='count') option_group.add_option( '--origins', help= 'For each imported symbol in each module, ' 'print the module that defined it. ' '(This is useful for import refactoring.)', action='count') option_parser.add_option_group(option_group) option_group = optparse.OptionGroup( option_parser, 'Sort options', 'These options define the sort order for output lines. ' 'At most one of these options is allowed. ' 'Unsorted output will reflect the order in which imports happened.') option_group.add_option( '--by-importer', help='Sort output lines by name of importing module.', action='count') option_group.add_option( '--by-origin', help='Sort output lines by name of imported module.', action='count') option_parser.add_option_group(option_group) (options, args) = option_parser.parse_args() if args: option_parser.error( 'Unexpected arguments %s (try %s --help)' % (args, sys.argv[0])) if options.problems > 1: option_parser.error('--problems must not be given more than once.') if options.origins > 1: option_parser.error('--origins must not be given more than once.') if options.by_importer > 1: option_parser.error('--by-importer must not be given more than once.') if options.by_origin > 1: option_parser.error('--by-origin must not be given more than once.') options.problems = options.problems == 1 options.origins = options.origins == 1 options.by_importer = options.by_importer == 1 options.by_origin = options.by_origin == 1 if not options.problems and not options.origins: option_parser.error( 'At least one of --problems and --origins is required') if options.problems and options.origins: option_parser.error( 'At most one of --problems and --origins is allowed') if options.by_importer and options.by_origin: option_parser.error( 'At most one of --by-importer and --by-origin is allowed') options.by_process = not options.by_importer and not options.by_origin builtin_import = builtins.__import__ class Definition: """Information about a symbol's definition.""" def __init__(self, name, value, definer): self.name = name self.value = value self.definer = definer def __hash__(self): return hash(self.name) def __eq__(self, other): return self.name == other.name and self.value == other.value def __ne__(self, other): return not (self == other) def __repr__(self): return 'Definition(%s, ..., %s)' % ( repr(self.name), repr(self.definer)) # Maps each function/variable to name of module to define it symbol_definers = {} # type: tDict[Definition, str] def in_module(a, b): """Is a the same module as or a submodule of b?""" return a == b or a != None and b != None and a.startswith(b + '.') def relevant(module): """Is module relevant for import checking? Only imports between relevant modules will be checked.""" return in_module(module, 'sympy') sorted_messages = [] def msg(msg, *args): global options, sorted_messages if options.by_process: print(msg % args) else: sorted_messages.append(msg % args) def tracking_import(module, globals=globals(), locals=[], fromlist=None, level=-1): """__import__ wrapper - does not change imports at all, but tracks them. Default order is implemented by doing output directly. All other orders are implemented by collecting output information into a sorted list that will be emitted after all imports are processed. Indirect imports can only occur after the requested symbol has been imported directly (because the indirect import would not have a module to pick the symbol up from). So this code detects indirect imports by checking whether the symbol in question was already imported. Keeps the semantics of __import__ unchanged.""" global options, symbol_definers caller_frame = inspect.getframeinfo(sys._getframe(1)) importer_filename = caller_frame.filename importer_module = globals['__name__'] if importer_filename == caller_frame.filename: importer_reference = '%s line %s' % ( importer_filename, str(caller_frame.lineno)) else: importer_reference = importer_filename result = builtin_import(module, globals, locals, fromlist, level) importee_module = result.__name__ # We're only interested if importer and importee are in SymPy if relevant(importer_module) and relevant(importee_module): for symbol in result.__dict__.iterkeys(): definition = Definition( symbol, result.__dict__[symbol], importer_module) if not definition in symbol_definers: symbol_definers[definition] = importee_module if hasattr(result, '__path__'): ##PACKAGE## # The existence of __path__ is documented in the tutorial on modules. # Python 3.3 documents this in http://docs.python.org/3.3/reference/import.html if options.by_origin: msg('Error: %s (a package) is imported by %s', module, importer_reference) else: msg('Error: %s contains package import %s', importer_reference, module) if fromlist != None: symbol_list = fromlist if '*' in symbol_list: if (importer_filename.endswith('__init__.py') or importer_filename.endswith('__init__.pyc') or importer_filename.endswith('__init__.pyo')): # We do not check starred imports inside __init__ # That's the normal "please copy over its imports to my namespace" symbol_list = [] else: symbol_list = result.__dict__.iterkeys() for symbol in symbol_list: if not symbol in result.__dict__: if options.by_origin: msg('Error: %s.%s is not defined (yet), but %s tries to import it', importee_module, symbol, importer_reference) else: msg('Error: %s tries to import %s.%s, which did not define it (yet)', importer_reference, importee_module, symbol) else: definition = Definition( symbol, result.__dict__[symbol], importer_module) symbol_definer = symbol_definers[definition] if symbol_definer == importee_module: ##DUPLICATE## if options.by_origin: msg('Error: %s.%s is imported again into %s', importee_module, symbol, importer_reference) else: msg('Error: %s imports %s.%s again', importer_reference, importee_module, symbol) else: ##ORIGIN## if options.by_origin: msg('Error: %s.%s is imported by %s, which should import %s.%s instead', importee_module, symbol, importer_reference, symbol_definer, symbol) else: msg('Error: %s imports %s.%s but should import %s.%s instead', importer_reference, importee_module, symbol, symbol_definer, symbol) return result builtins.__import__ = tracking_import __import__('sympy') sorted_messages.sort() for message in sorted_messages: print(message)
8f2bd4c0c572a6af4ed4c04d07a625e279fb403b30148bdcf4c8860663a6e7a6
# coding=utf-8 from os import walk, sep, pardir from os.path import split, join, abspath, exists, isfile from glob import glob import re import random import ast from sympy.testing.pytest import raises from sympy.testing.quality_unicode import _test_this_file_encoding # System path separator (usually slash or backslash) to be # used with excluded files, e.g. # exclude = set([ # "%(sep)smpmath%(sep)s" % sepd, # ]) sepd = {"sep": sep} # path and sympy_path SYMPY_PATH = abspath(join(split(__file__)[0], pardir, pardir)) # go to sympy/ assert exists(SYMPY_PATH) TOP_PATH = abspath(join(SYMPY_PATH, pardir)) BIN_PATH = join(TOP_PATH, "bin") EXAMPLES_PATH = join(TOP_PATH, "examples") # Error messages message_space = "File contains trailing whitespace: %s, line %s." message_implicit = "File contains an implicit import: %s, line %s." message_tabs = "File contains tabs instead of spaces: %s, line %s." message_carriage = "File contains carriage returns at end of line: %s, line %s" message_str_raise = "File contains string exception: %s, line %s" message_gen_raise = "File contains generic exception: %s, line %s" message_old_raise = "File contains old-style raise statement: %s, line %s, \"%s\"" message_eof = "File does not end with a newline: %s, line %s" message_multi_eof = "File ends with more than 1 newline: %s, line %s" message_test_suite_def = "Function should start with 'test_' or '_': %s, line %s" message_duplicate_test = "This is a duplicate test function: %s, line %s" message_self_assignments = "File contains assignments to self/cls: %s, line %s." message_func_is = "File contains '.func is': %s, line %s." implicit_test_re = re.compile(r'^\s*(>>> )?(\.\.\. )?from .* import .*\*') str_raise_re = re.compile( r'^\s*(>>> )?(\.\.\. )?raise(\s+(\'|\")|\s*(\(\s*)+(\'|\"))') gen_raise_re = re.compile( r'^\s*(>>> )?(\.\.\. )?raise(\s+Exception|\s*(\(\s*)+Exception)') old_raise_re = re.compile(r'^\s*(>>> )?(\.\.\. )?raise((\s*\(\s*)|\s+)\w+\s*,') test_suite_def_re = re.compile(r'^def\s+(?!(_|test))[^(]*\(\s*\)\s*:$') test_ok_def_re = re.compile(r'^def\s+test_.*:$') test_file_re = re.compile(r'.*[/\\]test_.*\.py$') func_is_re = re.compile(r'\.\s*func\s+is') def tab_in_leading(s): """Returns True if there are tabs in the leading whitespace of a line, including the whitespace of docstring code samples.""" n = len(s) - len(s.lstrip()) if not s[n:n + 3] in ['...', '>>>']: check = s[:n] else: smore = s[n + 3:] check = s[:n] + smore[:len(smore) - len(smore.lstrip())] return not (check.expandtabs() == check) def find_self_assignments(s): """Returns a list of "bad" assignments: if there are instances of assigning to the first argument of the class method (except for staticmethod's). """ t = [n for n in ast.parse(s).body if isinstance(n, ast.ClassDef)] bad = [] for c in t: for n in c.body: if not isinstance(n, ast.FunctionDef): continue if any(d.id == 'staticmethod' for d in n.decorator_list if isinstance(d, ast.Name)): continue if n.name == '__new__': continue if not n.args.args: continue first_arg = n.args.args[0].arg for m in ast.walk(n): if isinstance(m, ast.Assign): for a in m.targets: if isinstance(a, ast.Name) and a.id == first_arg: bad.append(m) elif (isinstance(a, ast.Tuple) and any(q.id == first_arg for q in a.elts if isinstance(q, ast.Name))): bad.append(m) return bad def check_directory_tree(base_path, file_check, exclusions=set(), pattern="*.py"): """ Checks all files in the directory tree (with base_path as starting point) with the file_check function provided, skipping files that contain any of the strings in the set provided by exclusions. """ if not base_path: return for root, dirs, files in walk(base_path): check_files(glob(join(root, pattern)), file_check, exclusions) def check_files(files, file_check, exclusions=set(), pattern=None): """ Checks all files with the file_check function provided, skipping files that contain any of the strings in the set provided by exclusions. """ if not files: return for fname in files: if not exists(fname) or not isfile(fname): continue if any(ex in fname for ex in exclusions): continue if pattern is None or re.match(pattern, fname): file_check(fname) def test_files(): """ This test tests all files in SymPy and checks that: o no lines contains a trailing whitespace o no lines end with \r\n o no line uses tabs instead of spaces o that the file ends with a single newline o there are no general or string exceptions o there are no old style raise statements o name of arg-less test suite functions start with _ or test_ o no duplicate function names that start with test_ o no assignments to self variable in class methods o no lines contain ".func is" except in the test suite """ def test(fname): with open(fname, encoding="utf8") as test_file: test_this_file(fname, test_file) with open(fname, encoding='utf8') as test_file: _test_this_file_encoding(fname, test_file) def test_this_file(fname, test_file): line = None # to flag the case where there were no lines in file tests = 0 test_set = set() for idx, line in enumerate(test_file): if test_file_re.match(fname): if test_suite_def_re.match(line): assert False, message_test_suite_def % (fname, idx + 1) if test_ok_def_re.match(line): tests += 1 test_set.add(line[3:].split('(')[0].strip()) if len(test_set) != tests: assert False, message_duplicate_test % (fname, idx + 1) if line.endswith(" \n") or line.endswith("\t\n"): assert False, message_space % (fname, idx + 1) if line.endswith("\r\n"): assert False, message_carriage % (fname, idx + 1) if tab_in_leading(line): assert False, message_tabs % (fname, idx + 1) if str_raise_re.search(line): assert False, message_str_raise % (fname, idx + 1) if gen_raise_re.search(line): assert False, message_gen_raise % (fname, idx + 1) if (implicit_test_re.search(line) and not list(filter(lambda ex: ex in fname, import_exclude))): assert False, message_implicit % (fname, idx + 1) if func_is_re.search(line) and not test_file_re.search(fname): assert False, message_func_is % (fname, idx + 1) result = old_raise_re.search(line) if result is not None: assert False, message_old_raise % ( fname, idx + 1, result.group(2)) if line is not None: if line == '\n' and idx > 0: assert False, message_multi_eof % (fname, idx + 1) elif not line.endswith('\n'): # eof newline check assert False, message_eof % (fname, idx + 1) # Files to test at top level top_level_files = [join(TOP_PATH, file) for file in [ "isympy.py", "build.py", "setup.py", "setupegg.py", ]] # Files to exclude from all tests exclude = { "%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevparser.py" % sepd, "%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlexer.py" % sepd, "%(sep)ssympy%(sep)sparsing%(sep)sautolev%(sep)s_antlr%(sep)sautolevlistener.py" % sepd, "%(sep)ssympy%(sep)sparsing%(sep)slatex%(sep)s_antlr%(sep)slatexparser.py" % sepd, "%(sep)ssympy%(sep)sparsing%(sep)slatex%(sep)s_antlr%(sep)slatexlexer.py" % sepd, } # Files to exclude from the implicit import test import_exclude = { # glob imports are allowed in top-level __init__.py: "%(sep)ssympy%(sep)s__init__.py" % sepd, # these __init__.py should be fixed: # XXX: not really, they use useful import pattern (DRY) "%(sep)svector%(sep)s__init__.py" % sepd, "%(sep)smechanics%(sep)s__init__.py" % sepd, "%(sep)squantum%(sep)s__init__.py" % sepd, "%(sep)spolys%(sep)s__init__.py" % sepd, "%(sep)spolys%(sep)sdomains%(sep)s__init__.py" % sepd, # interactive SymPy executes ``from sympy import *``: "%(sep)sinteractive%(sep)ssession.py" % sepd, # isympy.py executes ``from sympy import *``: "%(sep)sisympy.py" % sepd, # these two are import timing tests: "%(sep)sbin%(sep)ssympy_time.py" % sepd, "%(sep)sbin%(sep)ssympy_time_cache.py" % sepd, # Taken from Python stdlib: "%(sep)sparsing%(sep)ssympy_tokenize.py" % sepd, # this one should be fixed: "%(sep)splotting%(sep)spygletplot%(sep)s" % sepd, # False positive in the docstring "%(sep)sbin%(sep)stest_external_imports.py" % sepd, "%(sep)sbin%(sep)stest_submodule_imports.py" % sepd, # These are deprecated stubs that can be removed at some point: "%(sep)sutilities%(sep)sruntests.py" % sepd, "%(sep)sutilities%(sep)spytest.py" % sepd, "%(sep)sutilities%(sep)srandtest.py" % sepd, "%(sep)sutilities%(sep)stmpfiles.py" % sepd, "%(sep)sutilities%(sep)squality_unicode.py" % sepd, "%(sep)sutilities%(sep)sbenchmarking.py" % sepd, } check_files(top_level_files, test) check_directory_tree(BIN_PATH, test, {"~", ".pyc", ".sh"}, "*") check_directory_tree(SYMPY_PATH, test, exclude) check_directory_tree(EXAMPLES_PATH, test, exclude) def _with_space(c): # return c with a random amount of leading space return random.randint(0, 10)*' ' + c def test_raise_statement_regular_expression(): candidates_ok = [ "some text # raise Exception, 'text'", "raise ValueError('text') # raise Exception, 'text'", "raise ValueError('text')", "raise ValueError", "raise ValueError('text')", "raise ValueError('text') #,", # Talking about an exception in a docstring ''''"""This function will raise ValueError, except when it doesn't"""''', "raise (ValueError('text')", ] str_candidates_fail = [ "raise 'exception'", "raise 'Exception'", 'raise "exception"', 'raise "Exception"', "raise 'ValueError'", ] gen_candidates_fail = [ "raise Exception('text') # raise Exception, 'text'", "raise Exception('text')", "raise Exception", "raise Exception('text')", "raise Exception('text') #,", "raise Exception, 'text'", "raise Exception, 'text' # raise Exception('text')", "raise Exception, 'text' # raise Exception, 'text'", ">>> raise Exception, 'text'", ">>> raise Exception, 'text' # raise Exception('text')", ">>> raise Exception, 'text' # raise Exception, 'text'", ] old_candidates_fail = [ "raise Exception, 'text'", "raise Exception, 'text' # raise Exception('text')", "raise Exception, 'text' # raise Exception, 'text'", ">>> raise Exception, 'text'", ">>> raise Exception, 'text' # raise Exception('text')", ">>> raise Exception, 'text' # raise Exception, 'text'", "raise ValueError, 'text'", "raise ValueError, 'text' # raise Exception('text')", "raise ValueError, 'text' # raise Exception, 'text'", ">>> raise ValueError, 'text'", ">>> raise ValueError, 'text' # raise Exception('text')", ">>> raise ValueError, 'text' # raise Exception, 'text'", "raise(ValueError,", "raise (ValueError,", "raise( ValueError,", "raise ( ValueError,", "raise(ValueError ,", "raise (ValueError ,", "raise( ValueError ,", "raise ( ValueError ,", ] for c in candidates_ok: assert str_raise_re.search(_with_space(c)) is None, c assert gen_raise_re.search(_with_space(c)) is None, c assert old_raise_re.search(_with_space(c)) is None, c for c in str_candidates_fail: assert str_raise_re.search(_with_space(c)) is not None, c for c in gen_candidates_fail: assert gen_raise_re.search(_with_space(c)) is not None, c for c in old_candidates_fail: assert old_raise_re.search(_with_space(c)) is not None, c def test_implicit_imports_regular_expression(): candidates_ok = [ "from sympy import something", ">>> from sympy import something", "from sympy.somewhere import something", ">>> from sympy.somewhere import something", "import sympy", ">>> import sympy", "import sympy.something.something", "... import sympy", "... import sympy.something.something", "... from sympy import something", "... from sympy.somewhere import something", ">> from sympy import *", # To allow 'fake' docstrings "# from sympy import *", "some text # from sympy import *", ] candidates_fail = [ "from sympy import *", ">>> from sympy import *", "from sympy.somewhere import *", ">>> from sympy.somewhere import *", "... from sympy import *", "... from sympy.somewhere import *", ] for c in candidates_ok: assert implicit_test_re.search(_with_space(c)) is None, c for c in candidates_fail: assert implicit_test_re.search(_with_space(c)) is not None, c def test_test_suite_defs(): candidates_ok = [ " def foo():\n", "def foo(arg):\n", "def _foo():\n", "def test_foo():\n", ] candidates_fail = [ "def foo():\n", "def foo() :\n", "def foo( ):\n", "def foo():\n", ] for c in candidates_ok: assert test_suite_def_re.search(c) is None, c for c in candidates_fail: assert test_suite_def_re.search(c) is not None, c def test_test_duplicate_defs(): candidates_ok = [ "def foo():\ndef foo():\n", "def test():\ndef test_():\n", "def test_():\ndef test__():\n", ] candidates_fail = [ "def test_():\ndef test_ ():\n", "def test_1():\ndef test_1():\n", ] ok = (None, 'check') def check(file): tests = 0 test_set = set() for idx, line in enumerate(file.splitlines()): if test_ok_def_re.match(line): tests += 1 test_set.add(line[3:].split('(')[0].strip()) if len(test_set) != tests: return False, message_duplicate_test % ('check', idx + 1) return None, 'check' for c in candidates_ok: assert check(c) == ok for c in candidates_fail: assert check(c) != ok def test_find_self_assignments(): candidates_ok = [ "class A(object):\n def foo(self, arg): arg = self\n", "class A(object):\n def foo(self, arg): self.prop = arg\n", "class A(object):\n def foo(self, arg): obj, obj2 = arg, self\n", "class A(object):\n @classmethod\n def bar(cls, arg): arg = cls\n", "class A(object):\n def foo(var, arg): arg = var\n", ] candidates_fail = [ "class A(object):\n def foo(self, arg): self = arg\n", "class A(object):\n def foo(self, arg): obj, self = arg, arg\n", "class A(object):\n def foo(self, arg):\n if arg: self = arg", "class A(object):\n @classmethod\n def foo(cls, arg): cls = arg\n", "class A(object):\n def foo(var, arg): var = arg\n", ] for c in candidates_ok: assert find_self_assignments(c) == [] for c in candidates_fail: assert find_self_assignments(c) != [] def test_test_unicode_encoding(): unicode_whitelist = ['foo'] unicode_strict_whitelist = ['bar'] fname = 'abc' test_file = ['α'] raises(AssertionError, lambda: _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)) fname = 'abc' test_file = ['# coding=utf-8', 'α'] raises(AssertionError, lambda: _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)) fname = 'abc' test_file = ['# coding=utf-8', 'abc'] raises(AssertionError, lambda: _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)) fname = 'abc' test_file = ['abc'] _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist) fname = 'foo' test_file = ['α'] raises(AssertionError, lambda: _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)) fname = 'foo' test_file = ['# coding=utf-8', 'α'] _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist) fname = 'foo' test_file = ['# coding=utf-8', 'abc'] raises(AssertionError, lambda: _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)) fname = 'foo' test_file = ['abc'] raises(AssertionError, lambda: _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)) fname = 'bar' test_file = ['α'] raises(AssertionError, lambda: _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)) fname = 'bar' test_file = ['# coding=utf-8', 'α'] _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist) fname = 'bar' test_file = ['# coding=utf-8', 'abc'] _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist) fname = 'bar' test_file = ['abc'] _test_this_file_encoding( fname, test_file, unicode_whitelist, unicode_strict_whitelist)
06cdac7a4743272c3fc2b5291bbbd94061f4cb44b80b801bc464a9794ffc0b6b
from sympy.vector.vector import Vector from sympy.vector.coordsysrect import CoordSys3D from sympy.vector.functions import express, matrix_to_vector, orthogonalize from sympy.core.numbers import Rational from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix from sympy.testing.pytest import raises N = CoordSys3D('N') q1, q2, q3, q4, q5 = symbols('q1 q2 q3 q4 q5') A = N.orient_new_axis('A', q1, N.k) # type: ignore B = A.orient_new_axis('B', q2, A.i) C = B.orient_new_axis('C', q3, B.j) def test_express(): assert express(Vector.zero, N) == Vector.zero assert express(S.Zero, N) is S.Zero assert express(A.i, C) == cos(q3)*C.i + sin(q3)*C.k assert express(A.j, C) == sin(q2)*sin(q3)*C.i + cos(q2)*C.j - \ sin(q2)*cos(q3)*C.k assert express(A.k, C) == -sin(q3)*cos(q2)*C.i + sin(q2)*C.j + \ cos(q2)*cos(q3)*C.k assert express(A.i, N) == cos(q1)*N.i + sin(q1)*N.j assert express(A.j, N) == -sin(q1)*N.i + cos(q1)*N.j assert express(A.k, N) == N.k assert express(A.i, A) == A.i assert express(A.j, A) == A.j assert express(A.k, A) == A.k assert express(A.i, B) == B.i assert express(A.j, B) == cos(q2)*B.j - sin(q2)*B.k assert express(A.k, B) == sin(q2)*B.j + cos(q2)*B.k assert express(A.i, C) == cos(q3)*C.i + sin(q3)*C.k assert express(A.j, C) == sin(q2)*sin(q3)*C.i + cos(q2)*C.j - \ sin(q2)*cos(q3)*C.k assert express(A.k, C) == -sin(q3)*cos(q2)*C.i + sin(q2)*C.j + \ cos(q2)*cos(q3)*C.k # Check to make sure UnitVectors get converted properly assert express(N.i, N) == N.i assert express(N.j, N) == N.j assert express(N.k, N) == N.k assert express(N.i, A) == (cos(q1)*A.i - sin(q1)*A.j) assert express(N.j, A) == (sin(q1)*A.i + cos(q1)*A.j) assert express(N.k, A) == A.k assert express(N.i, B) == (cos(q1)*B.i - sin(q1)*cos(q2)*B.j + sin(q1)*sin(q2)*B.k) assert express(N.j, B) == (sin(q1)*B.i + cos(q1)*cos(q2)*B.j - sin(q2)*cos(q1)*B.k) assert express(N.k, B) == (sin(q2)*B.j + cos(q2)*B.k) assert express(N.i, C) == ( (cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3))*C.i - sin(q1)*cos(q2)*C.j + (sin(q3)*cos(q1) + sin(q1)*sin(q2)*cos(q3))*C.k) assert express(N.j, C) == ( (sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1))*C.i + cos(q1)*cos(q2)*C.j + (sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3))*C.k) assert express(N.k, C) == (-sin(q3)*cos(q2)*C.i + sin(q2)*C.j + cos(q2)*cos(q3)*C.k) assert express(A.i, N) == (cos(q1)*N.i + sin(q1)*N.j) assert express(A.j, N) == (-sin(q1)*N.i + cos(q1)*N.j) assert express(A.k, N) == N.k assert express(A.i, A) == A.i assert express(A.j, A) == A.j assert express(A.k, A) == A.k assert express(A.i, B) == B.i assert express(A.j, B) == (cos(q2)*B.j - sin(q2)*B.k) assert express(A.k, B) == (sin(q2)*B.j + cos(q2)*B.k) assert express(A.i, C) == (cos(q3)*C.i + sin(q3)*C.k) assert express(A.j, C) == (sin(q2)*sin(q3)*C.i + cos(q2)*C.j - sin(q2)*cos(q3)*C.k) assert express(A.k, C) == (-sin(q3)*cos(q2)*C.i + sin(q2)*C.j + cos(q2)*cos(q3)*C.k) assert express(B.i, N) == (cos(q1)*N.i + sin(q1)*N.j) assert express(B.j, N) == (-sin(q1)*cos(q2)*N.i + cos(q1)*cos(q2)*N.j + sin(q2)*N.k) assert express(B.k, N) == (sin(q1)*sin(q2)*N.i - sin(q2)*cos(q1)*N.j + cos(q2)*N.k) assert express(B.i, A) == A.i assert express(B.j, A) == (cos(q2)*A.j + sin(q2)*A.k) assert express(B.k, A) == (-sin(q2)*A.j + cos(q2)*A.k) assert express(B.i, B) == B.i assert express(B.j, B) == B.j assert express(B.k, B) == B.k assert express(B.i, C) == (cos(q3)*C.i + sin(q3)*C.k) assert express(B.j, C) == C.j assert express(B.k, C) == (-sin(q3)*C.i + cos(q3)*C.k) assert express(C.i, N) == ( (cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3))*N.i + (sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1))*N.j - sin(q3)*cos(q2)*N.k) assert express(C.j, N) == ( -sin(q1)*cos(q2)*N.i + cos(q1)*cos(q2)*N.j + sin(q2)*N.k) assert express(C.k, N) == ( (sin(q3)*cos(q1) + sin(q1)*sin(q2)*cos(q3))*N.i + (sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3))*N.j + cos(q2)*cos(q3)*N.k) assert express(C.i, A) == (cos(q3)*A.i + sin(q2)*sin(q3)*A.j - sin(q3)*cos(q2)*A.k) assert express(C.j, A) == (cos(q2)*A.j + sin(q2)*A.k) assert express(C.k, A) == (sin(q3)*A.i - sin(q2)*cos(q3)*A.j + cos(q2)*cos(q3)*A.k) assert express(C.i, B) == (cos(q3)*B.i - sin(q3)*B.k) assert express(C.j, B) == B.j assert express(C.k, B) == (sin(q3)*B.i + cos(q3)*B.k) assert express(C.i, C) == C.i assert express(C.j, C) == C.j assert express(C.k, C) == C.k == (C.k) # Check to make sure Vectors get converted back to UnitVectors assert N.i == express((cos(q1)*A.i - sin(q1)*A.j), N).simplify() assert N.j == express((sin(q1)*A.i + cos(q1)*A.j), N).simplify() assert N.i == express((cos(q1)*B.i - sin(q1)*cos(q2)*B.j + sin(q1)*sin(q2)*B.k), N).simplify() assert N.j == express((sin(q1)*B.i + cos(q1)*cos(q2)*B.j - sin(q2)*cos(q1)*B.k), N).simplify() assert N.k == express((sin(q2)*B.j + cos(q2)*B.k), N).simplify() assert A.i == express((cos(q1)*N.i + sin(q1)*N.j), A).simplify() assert A.j == express((-sin(q1)*N.i + cos(q1)*N.j), A).simplify() assert A.j == express((cos(q2)*B.j - sin(q2)*B.k), A).simplify() assert A.k == express((sin(q2)*B.j + cos(q2)*B.k), A).simplify() assert A.i == express((cos(q3)*C.i + sin(q3)*C.k), A).simplify() assert A.j == express((sin(q2)*sin(q3)*C.i + cos(q2)*C.j - sin(q2)*cos(q3)*C.k), A).simplify() assert A.k == express((-sin(q3)*cos(q2)*C.i + sin(q2)*C.j + cos(q2)*cos(q3)*C.k), A).simplify() assert B.i == express((cos(q1)*N.i + sin(q1)*N.j), B).simplify() assert B.j == express((-sin(q1)*cos(q2)*N.i + cos(q1)*cos(q2)*N.j + sin(q2)*N.k), B).simplify() assert B.k == express((sin(q1)*sin(q2)*N.i - sin(q2)*cos(q1)*N.j + cos(q2)*N.k), B).simplify() assert B.j == express((cos(q2)*A.j + sin(q2)*A.k), B).simplify() assert B.k == express((-sin(q2)*A.j + cos(q2)*A.k), B).simplify() assert B.i == express((cos(q3)*C.i + sin(q3)*C.k), B).simplify() assert B.k == express((-sin(q3)*C.i + cos(q3)*C.k), B).simplify() assert C.i == express((cos(q3)*A.i + sin(q2)*sin(q3)*A.j - sin(q3)*cos(q2)*A.k), C).simplify() assert C.j == express((cos(q2)*A.j + sin(q2)*A.k), C).simplify() assert C.k == express((sin(q3)*A.i - sin(q2)*cos(q3)*A.j + cos(q2)*cos(q3)*A.k), C).simplify() assert C.i == express((cos(q3)*B.i - sin(q3)*B.k), C).simplify() assert C.k == express((sin(q3)*B.i + cos(q3)*B.k), C).simplify() def test_matrix_to_vector(): m = Matrix([[1], [2], [3]]) assert matrix_to_vector(m, C) == C.i + 2*C.j + 3*C.k m = Matrix([[0], [0], [0]]) assert matrix_to_vector(m, N) == matrix_to_vector(m, C) == \ Vector.zero m = Matrix([[q1], [q2], [q3]]) assert matrix_to_vector(m, N) == q1*N.i + q2*N.j + q3*N.k def test_orthogonalize(): C = CoordSys3D('C') a, b = symbols('a b', integer=True) i, j, k = C.base_vectors() v1 = i + 2*j v2 = 2*i + 3*j v3 = 3*i + 5*j v4 = 3*i + j v5 = 2*i + 2*j v6 = a*i + b*j v7 = 4*a*i + 4*b*j assert orthogonalize(v1, v2) == [C.i + 2*C.j, C.i*Rational(2, 5) + -C.j/5] # from wikipedia assert orthogonalize(v4, v5, orthonormal=True) == \ [(3*sqrt(10))*C.i/10 + (sqrt(10))*C.j/10, (-sqrt(10))*C.i/10 + (3*sqrt(10))*C.j/10] raises(ValueError, lambda: orthogonalize(v1, v2, v3)) raises(ValueError, lambda: orthogonalize(v6, v7))
39f29aa45f40fe0f57e89c6061cd147f1221c17cd1111cda8fe1228d008938dc
from sympy.core.numbers import pi from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.vector.coordsysrect import CoordSys3D from sympy.vector.parametricregion import ParametricRegion, parametric_region_list from sympy.geometry import Point, Segment, Curve, Ellipse, Line, Parabola, Polygon from sympy.testing.pytest import raises from sympy.abc import a, b, r, t, x, y, z, theta, phi C = CoordSys3D('C') def test_ParametricRegion(): point = ParametricRegion((3, 4)) assert point.definition == (3, 4) assert point.parameters == () assert point.limits == {} assert point.dimensions == 0 # line x = y line_xy = ParametricRegion((y, y), (y, 1, 5)) assert line_xy .definition == (y, y) assert line_xy.parameters == (y,) assert line_xy.dimensions == 1 # line y = z line_yz = ParametricRegion((x,t,t), x, (t, 1, 2)) assert line_yz.definition == (x,t,t) assert line_yz.parameters == (x, t) assert line_yz.limits == {t: (1, 2)} assert line_yz.dimensions == 1 p1 = ParametricRegion((9*a, -16*b), (a, 0, 2), (b, -1, 5)) assert p1.definition == (9*a, -16*b) assert p1.parameters == (a, b) assert p1.limits == {a: (0, 2), b: (-1, 5)} assert p1.dimensions == 2 p2 = ParametricRegion((t, t**3), t) assert p2.parameters == (t,) assert p2.limits == {} assert p2.dimensions == 0 circle = ParametricRegion((r*cos(theta), r*sin(theta)), r, (theta, 0, 2*pi)) assert circle.definition == (r*cos(theta), r*sin(theta)) assert circle.dimensions == 1 halfdisc = ParametricRegion((r*cos(theta), r*sin(theta)), (r, -2, 2), (theta, 0, pi)) assert halfdisc.definition == (r*cos(theta), r*sin(theta)) assert halfdisc.parameters == (r, theta) assert halfdisc.limits == {r: (-2, 2), theta: (0, pi)} assert halfdisc.dimensions == 2 ellipse = ParametricRegion((a*cos(t), b*sin(t)), (t, 0, 8)) assert ellipse.parameters == (t,) assert ellipse.limits == {t: (0, 8)} assert ellipse.dimensions == 1 cylinder = ParametricRegion((r*cos(theta), r*sin(theta), z), (r, 0, 1), (theta, 0, 2*pi), (z, 0, 4)) assert cylinder.parameters == (r, theta, z) assert cylinder.dimensions == 3 sphere = ParametricRegion((r*sin(phi)*cos(theta),r*sin(phi)*sin(theta), r*cos(phi)), r, (theta, 0, 2*pi), (phi, 0, pi)) assert sphere.definition == (r*sin(phi)*cos(theta),r*sin(phi)*sin(theta), r*cos(phi)) assert sphere.parameters == (r, theta, phi) assert sphere.dimensions == 2 raises(ValueError, lambda: ParametricRegion((a*t**2, 2*a*t), (a, -2))) raises(ValueError, lambda: ParametricRegion((a, b), (a**2, sin(b)), (a, 2, 4, 6))) def test_parametric_region_list(): point = Point(-5, 12) assert parametric_region_list(point) == [ParametricRegion((-5, 12))] e = Ellipse(Point(2, 8), 2, 6) assert parametric_region_list(e, t) == [ParametricRegion((2*cos(t) + 2, 6*sin(t) + 8), (t, 0, 2*pi))] c = Curve((t, t**3), (t, 5, 3)) assert parametric_region_list(c) == [ParametricRegion((t, t**3), (t, 5, 3))] s = Segment(Point(2, 11, -6), Point(0, 2, 5)) assert parametric_region_list(s, t) == [ParametricRegion((2 - 2*t, 11 - 9*t, 11*t - 6), (t, 0, 1))] s1 = Segment(Point(0, 0), (1, 0)) assert parametric_region_list(s1, t) == [ParametricRegion((t, 0), (t, 0, 1))] s2 = Segment(Point(1, 2, 3), Point(1, 2, 5)) assert parametric_region_list(s2, t) == [ParametricRegion((1, 2, 2*t + 3), (t, 0, 1))] s3 = Segment(Point(12, 56), Point(12, 56)) assert parametric_region_list(s3) == [ParametricRegion((12, 56))] poly = Polygon((1,3), (-3, 8), (2, 4)) assert parametric_region_list(poly, t) == [ParametricRegion((1 - 4*t, 5*t + 3), (t, 0, 1)), ParametricRegion((5*t - 3, 8 - 4*t), (t, 0, 1)), ParametricRegion((2 - t, 4 - t), (t, 0, 1))] p1 = Parabola(Point(0, 0), Line(Point(5, 8), Point(7,8))) raises(ValueError, lambda: parametric_region_list(p1))
d22c501b010976d6420652f4c183e4cd4d036977b9eed6bb34559039a2ae5620
from sympy.core import Rational, S from sympy.simplify import simplify, trigsimp from sympy.core.function import (Derivative, Function, diff) from sympy.core.numbers import pi from sympy.core.symbol import symbols from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.integrals.integrals import Integral from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix from sympy.vector.vector import Vector, BaseVector, VectorAdd, \ VectorMul, VectorZero from sympy.vector.coordsysrect import CoordSys3D from sympy.vector.vector import Cross, Dot, cross from sympy.testing.pytest import raises C = CoordSys3D('C') i, j, k = C.base_vectors() a, b, c = symbols('a b c') def test_cross(): v1 = C.x * i + C.z * C.z * j v2 = C.x * i + C.y * j + C.z * k assert Cross(v1, v2) == Cross(C.x*C.i + C.z**2*C.j, C.x*C.i + C.y*C.j + C.z*C.k) assert Cross(v1, v2).doit() == C.z**3*C.i + (-C.x*C.z)*C.j + (C.x*C.y - C.x*C.z**2)*C.k assert cross(v1, v2) == C.z**3*C.i + (-C.x*C.z)*C.j + (C.x*C.y - C.x*C.z**2)*C.k assert Cross(v1, v2) == -Cross(v2, v1) assert Cross(v1, v2) + Cross(v2, v1) == Vector.zero def test_dot(): v1 = C.x * i + C.z * C.z * j v2 = C.x * i + C.y * j + C.z * k assert Dot(v1, v2) == Dot(C.x*C.i + C.z**2*C.j, C.x*C.i + C.y*C.j + C.z*C.k) assert Dot(v1, v2).doit() == C.x**2 + C.y*C.z**2 assert Dot(v1, v2).doit() == C.x**2 + C.y*C.z**2 assert Dot(v1, v2) == Dot(v2, v1) def test_vector_sympy(): """ Test whether the Vector framework confirms to the hashing and equality testing properties of SymPy. """ v1 = 3*j assert v1 == j*3 assert v1.components == {j: 3} v2 = 3*i + 4*j + 5*k v3 = 2*i + 4*j + i + 4*k + k assert v3 == v2 assert v3.__hash__() == v2.__hash__() def test_vector(): assert isinstance(i, BaseVector) assert i != j assert j != k assert k != i assert i - i == Vector.zero assert i + Vector.zero == i assert i - Vector.zero == i assert Vector.zero != 0 assert -Vector.zero == Vector.zero v1 = a*i + b*j + c*k v2 = a**2*i + b**2*j + c**2*k v3 = v1 + v2 v4 = 2 * v1 v5 = a * i assert isinstance(v1, VectorAdd) assert v1 - v1 == Vector.zero assert v1 + Vector.zero == v1 assert v1.dot(i) == a assert v1.dot(j) == b assert v1.dot(k) == c assert i.dot(v2) == a**2 assert j.dot(v2) == b**2 assert k.dot(v2) == c**2 assert v3.dot(i) == a**2 + a assert v3.dot(j) == b**2 + b assert v3.dot(k) == c**2 + c assert v1 + v2 == v2 + v1 assert v1 - v2 == -1 * (v2 - v1) assert a * v1 == v1 * a assert isinstance(v5, VectorMul) assert v5.base_vector == i assert v5.measure_number == a assert isinstance(v4, Vector) assert isinstance(v4, VectorAdd) assert isinstance(v4, Vector) assert isinstance(Vector.zero, VectorZero) assert isinstance(Vector.zero, Vector) assert isinstance(v1 * 0, VectorZero) assert v1.to_matrix(C) == Matrix([[a], [b], [c]]) assert i.components == {i: 1} assert v5.components == {i: a} assert v1.components == {i: a, j: b, k: c} assert VectorAdd(v1, Vector.zero) == v1 assert VectorMul(a, v1) == v1*a assert VectorMul(1, i) == i assert VectorAdd(v1, Vector.zero) == v1 assert VectorMul(0, Vector.zero) == Vector.zero raises(TypeError, lambda: v1.outer(1)) raises(TypeError, lambda: v1.dot(1)) def test_vector_magnitude_normalize(): assert Vector.zero.magnitude() == 0 assert Vector.zero.normalize() == Vector.zero assert i.magnitude() == 1 assert j.magnitude() == 1 assert k.magnitude() == 1 assert i.normalize() == i assert j.normalize() == j assert k.normalize() == k v1 = a * i assert v1.normalize() == (a/sqrt(a**2))*i assert v1.magnitude() == sqrt(a**2) v2 = a*i + b*j + c*k assert v2.magnitude() == sqrt(a**2 + b**2 + c**2) assert v2.normalize() == v2 / v2.magnitude() v3 = i + j assert v3.normalize() == (sqrt(2)/2)*C.i + (sqrt(2)/2)*C.j def test_vector_simplify(): A, s, k, m = symbols('A, s, k, m') test1 = (1 / a + 1 / b) * i assert (test1 & i) != (a + b) / (a * b) test1 = simplify(test1) assert (test1 & i) == (a + b) / (a * b) assert test1.simplify() == simplify(test1) test2 = (A**2 * s**4 / (4 * pi * k * m**3)) * i test2 = simplify(test2) assert (test2 & i) == (A**2 * s**4 / (4 * pi * k * m**3)) test3 = ((4 + 4 * a - 2 * (2 + 2 * a)) / (2 + 2 * a)) * i test3 = simplify(test3) assert (test3 & i) == 0 test4 = ((-4 * a * b**2 - 2 * b**3 - 2 * a**2 * b) / (a + b)**2) * i test4 = simplify(test4) assert (test4 & i) == -2 * b v = (sin(a)+cos(a))**2*i - j assert trigsimp(v) == (2*sin(a + pi/4)**2)*i + (-1)*j assert trigsimp(v) == v.trigsimp() assert simplify(Vector.zero) == Vector.zero def test_vector_dot(): assert i.dot(Vector.zero) == 0 assert Vector.zero.dot(i) == 0 assert i & Vector.zero == 0 assert i.dot(i) == 1 assert i.dot(j) == 0 assert i.dot(k) == 0 assert i & i == 1 assert i & j == 0 assert i & k == 0 assert j.dot(i) == 0 assert j.dot(j) == 1 assert j.dot(k) == 0 assert j & i == 0 assert j & j == 1 assert j & k == 0 assert k.dot(i) == 0 assert k.dot(j) == 0 assert k.dot(k) == 1 assert k & i == 0 assert k & j == 0 assert k & k == 1 raises(TypeError, lambda: k.dot(1)) def test_vector_cross(): assert i.cross(Vector.zero) == Vector.zero assert Vector.zero.cross(i) == Vector.zero assert i.cross(i) == Vector.zero assert i.cross(j) == k assert i.cross(k) == -j assert i ^ i == Vector.zero assert i ^ j == k assert i ^ k == -j assert j.cross(i) == -k assert j.cross(j) == Vector.zero assert j.cross(k) == i assert j ^ i == -k assert j ^ j == Vector.zero assert j ^ k == i assert k.cross(i) == j assert k.cross(j) == -i assert k.cross(k) == Vector.zero assert k ^ i == j assert k ^ j == -i assert k ^ k == Vector.zero assert k.cross(1) == Cross(k, 1) def test_projection(): v1 = i + j + k v2 = 3*i + 4*j v3 = 0*i + 0*j assert v1.projection(v1) == i + j + k assert v1.projection(v2) == Rational(7, 3)*C.i + Rational(7, 3)*C.j + Rational(7, 3)*C.k assert v1.projection(v1, scalar=True) == S.One assert v1.projection(v2, scalar=True) == Rational(7, 3) assert v3.projection(v1) == Vector.zero assert v3.projection(v1, scalar=True) == S.Zero def test_vector_diff_integrate(): f = Function('f') v = f(a)*C.i + a**2*C.j - C.k assert Derivative(v, a) == Derivative((f(a))*C.i + a**2*C.j + (-1)*C.k, a) assert (diff(v, a) == v.diff(a) == Derivative(v, a).doit() == (Derivative(f(a), a))*C.i + 2*a*C.j) assert (Integral(v, a) == (Integral(f(a), a))*C.i + (Integral(a**2, a))*C.j + (Integral(-1, a))*C.k) def test_vector_args(): raises(ValueError, lambda: BaseVector(3, C)) raises(TypeError, lambda: BaseVector(0, Vector.zero))
5f8233bf2b9e55c00dac9954eff69b07ee06868804f9ba2942aa4195e196e5fe
from sympy.core.numbers import pi from sympy.core.singleton import S from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) 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) == 180*pi c4 = ImplicitRegion((x, y), (x - 3)**2 + (y - 4)**2 - 9) assert vector_integrate(1, c4) == 6*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))
b1f504fd5abd1ff6a0bd54c05dcb4d9cc483febd7ad334c66ad8530654fb2b59
from sympy.core.numbers import pi from sympy.core.symbol import symbols from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix from sympy.simplify.simplify import simplify from sympy.vector import (CoordSys3D, Vector, Dyadic, DyadicAdd, DyadicMul, DyadicZero, BaseDyadic, express) A = CoordSys3D('A') def test_dyadic(): a, b = symbols('a, b') assert Dyadic.zero != 0 assert isinstance(Dyadic.zero, DyadicZero) assert BaseDyadic(A.i, A.j) != BaseDyadic(A.j, A.i) assert (BaseDyadic(Vector.zero, A.i) == BaseDyadic(A.i, Vector.zero) == Dyadic.zero) d1 = A.i | A.i d2 = A.j | A.j d3 = A.i | A.j assert isinstance(d1, BaseDyadic) d_mul = a*d1 assert isinstance(d_mul, DyadicMul) assert d_mul.base_dyadic == d1 assert d_mul.measure_number == a assert isinstance(a*d1 + b*d3, DyadicAdd) assert d1 == A.i.outer(A.i) assert d3 == A.i.outer(A.j) v1 = a*A.i - A.k v2 = A.i + b*A.j assert v1 | v2 == v1.outer(v2) == a * (A.i|A.i) + (a*b) * (A.i|A.j) +\ - (A.k|A.i) - b * (A.k|A.j) assert d1 * 0 == Dyadic.zero assert d1 != Dyadic.zero assert d1 * 2 == 2 * (A.i | A.i) assert d1 / 2. == 0.5 * d1 assert d1.dot(0 * d1) == Vector.zero assert d1 & d2 == Dyadic.zero assert d1.dot(A.i) == A.i == d1 & A.i assert d1.cross(Vector.zero) == Dyadic.zero assert d1.cross(A.i) == Dyadic.zero assert d1 ^ A.j == d1.cross(A.j) assert d1.cross(A.k) == - A.i | A.j assert d2.cross(A.i) == - A.j | A.k == d2 ^ A.i assert A.i ^ d1 == Dyadic.zero assert A.j.cross(d1) == - A.k | A.i == A.j ^ d1 assert Vector.zero.cross(d1) == Dyadic.zero assert A.k ^ d1 == A.j | A.i assert A.i.dot(d1) == A.i & d1 == A.i assert A.j.dot(d1) == Vector.zero assert Vector.zero.dot(d1) == Vector.zero assert A.j & d2 == A.j assert d1.dot(d3) == d1 & d3 == A.i | A.j == d3 assert d3 & d1 == Dyadic.zero q = symbols('q') B = A.orient_new_axis('B', q, A.k) assert express(d1, B) == express(d1, B, B) expr1 = ((cos(q)**2) * (B.i | B.i) + (-sin(q) * cos(q)) * (B.i | B.j) + (-sin(q) * cos(q)) * (B.j | B.i) + (sin(q)**2) * (B.j | B.j)) assert (express(d1, B) - expr1).simplify() == Dyadic.zero expr2 = (cos(q)) * (B.i | A.i) + (-sin(q)) * (B.j | A.i) assert (express(d1, B, A) - expr2).simplify() == Dyadic.zero expr3 = (cos(q)) * (A.i | B.i) + (-sin(q)) * (A.i | B.j) assert (express(d1, A, B) - expr3).simplify() == Dyadic.zero assert d1.to_matrix(A) == Matrix([[1, 0, 0], [0, 0, 0], [0, 0, 0]]) assert d1.to_matrix(A, B) == Matrix([[cos(q), -sin(q), 0], [0, 0, 0], [0, 0, 0]]) assert d3.to_matrix(A) == Matrix([[0, 1, 0], [0, 0, 0], [0, 0, 0]]) a, b, c, d, e, f = symbols('a, b, c, d, e, f') v1 = a * A.i + b * A.j + c * A.k v2 = d * A.i + e * A.j + f * A.k d4 = v1.outer(v2) assert d4.to_matrix(A) == Matrix([[a * d, a * e, a * f], [b * d, b * e, b * f], [c * d, c * e, c * f]]) d5 = v1.outer(v1) C = A.orient_new_axis('C', q, A.i) for expected, actual in zip(C.rotation_matrix(A) * d5.to_matrix(A) * \ C.rotation_matrix(A).T, d5.to_matrix(C)): assert (expected - actual).simplify() == 0 def test_dyadic_simplify(): x, y, z, k, n, m, w, f, s, A = symbols('x, y, z, k, n, m, w, f, s, A') N = CoordSys3D('N') dy = N.i | N.i test1 = (1 / x + 1 / y) * dy assert (N.i & test1 & N.i) != (x + y) / (x * y) test1 = test1.simplify() assert test1.simplify() == simplify(test1) assert (N.i & test1 & N.i) == (x + y) / (x * y) test2 = (A**2 * s**4 / (4 * pi * k * m**3)) * dy test2 = test2.simplify() assert (N.i & test2 & N.i) == (A**2 * s**4 / (4 * pi * k * m**3)) test3 = ((4 + 4 * x - 2 * (2 + 2 * x)) / (2 + 2 * x)) * dy test3 = test3.simplify() assert (N.i & test3 & N.i) == 0 test4 = ((-4 * x * y**2 - 2 * y**3 - 2 * x**2 * y) / (x + y)**2) * dy test4 = test4.simplify() assert (N.i & test4 & N.i) == -2 * y
33093d32269807bd6d3fca3359c9a257aba72821ec3fba0fa46f3607acb0cfd7
from sympy.core.function import Derivative from sympy.vector.vector import Vector from sympy.vector.coordsysrect import CoordSys3D from sympy.simplify import simplify from sympy.core.symbol import symbols from sympy.core import S from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.vector.vector import Dot from sympy.vector.operators import curl, divergence, gradient, Gradient, Divergence, Cross from sympy.vector.deloperator import Del from sympy.vector.functions import (is_conservative, is_solenoidal, scalar_potential, directional_derivative, laplacian, scalar_potential_difference) from sympy.testing.pytest import raises C = CoordSys3D('C') i, j, k = C.base_vectors() x, y, z = C.base_scalars() delop = Del() a, b, c, q = symbols('a b c q') def test_del_operator(): # Tests for curl assert delop ^ Vector.zero == Vector.zero assert ((delop ^ Vector.zero).doit() == Vector.zero == curl(Vector.zero)) assert delop.cross(Vector.zero) == delop ^ Vector.zero assert (delop ^ i).doit() == Vector.zero assert delop.cross(2*y**2*j, doit=True) == Vector.zero assert delop.cross(2*y**2*j) == delop ^ 2*y**2*j v = x*y*z * (i + j + k) assert ((delop ^ v).doit() == (-x*y + x*z)*i + (x*y - y*z)*j + (-x*z + y*z)*k == curl(v)) assert delop ^ v == delop.cross(v) assert (delop.cross(2*x**2*j) == (Derivative(0, C.y) - Derivative(2*C.x**2, C.z))*C.i + (-Derivative(0, C.x) + Derivative(0, C.z))*C.j + (-Derivative(0, C.y) + Derivative(2*C.x**2, C.x))*C.k) assert (delop.cross(2*x**2*j, doit=True) == 4*x*k == curl(2*x**2*j)) #Tests for divergence assert delop & Vector.zero is S.Zero == divergence(Vector.zero) assert (delop & Vector.zero).doit() is S.Zero assert delop.dot(Vector.zero) == delop & Vector.zero assert (delop & i).doit() is S.Zero assert (delop & x**2*i).doit() == 2*x == divergence(x**2*i) assert (delop.dot(v, doit=True) == x*y + y*z + z*x == divergence(v)) assert delop & v == delop.dot(v) assert delop.dot(1/(x*y*z) * (i + j + k), doit=True) == \ - 1 / (x*y*z**2) - 1 / (x*y**2*z) - 1 / (x**2*y*z) v = x*i + y*j + z*k assert (delop & v == Derivative(C.x, C.x) + Derivative(C.y, C.y) + Derivative(C.z, C.z)) assert delop.dot(v, doit=True) == 3 == divergence(v) assert delop & v == delop.dot(v) assert simplify((delop & v).doit()) == 3 #Tests for gradient assert (delop.gradient(0, doit=True) == Vector.zero == gradient(0)) assert delop.gradient(0) == delop(0) assert (delop(S.Zero)).doit() == Vector.zero assert (delop(x) == (Derivative(C.x, C.x))*C.i + (Derivative(C.x, C.y))*C.j + (Derivative(C.x, C.z))*C.k) assert (delop(x)).doit() == i == gradient(x) assert (delop(x*y*z) == (Derivative(C.x*C.y*C.z, C.x))*C.i + (Derivative(C.x*C.y*C.z, C.y))*C.j + (Derivative(C.x*C.y*C.z, C.z))*C.k) assert (delop.gradient(x*y*z, doit=True) == y*z*i + z*x*j + x*y*k == gradient(x*y*z)) assert delop(x*y*z) == delop.gradient(x*y*z) assert (delop(2*x**2)).doit() == 4*x*i assert ((delop(a*sin(y) / x)).doit() == -a*sin(y)/x**2 * i + a*cos(y)/x * j) #Tests for directional derivative assert (Vector.zero & delop)(a) is S.Zero assert ((Vector.zero & delop)(a)).doit() is S.Zero assert ((v & delop)(Vector.zero)).doit() == Vector.zero assert ((v & delop)(S.Zero)).doit() is S.Zero assert ((i & delop)(x)).doit() == 1 assert ((j & delop)(y)).doit() == 1 assert ((k & delop)(z)).doit() == 1 assert ((i & delop)(x*y*z)).doit() == y*z assert ((v & delop)(x)).doit() == x assert ((v & delop)(x*y*z)).doit() == 3*x*y*z assert (v & delop)(x + y + z) == C.x + C.y + C.z assert ((v & delop)(x + y + z)).doit() == x + y + z assert ((v & delop)(v)).doit() == v assert ((i & delop)(v)).doit() == i assert ((j & delop)(v)).doit() == j assert ((k & delop)(v)).doit() == k assert ((v & delop)(Vector.zero)).doit() == Vector.zero # Tests for laplacian on scalar fields assert laplacian(x*y*z) is S.Zero assert laplacian(x**2) == S(2) assert laplacian(x**2*y**2*z**2) == \ 2*y**2*z**2 + 2*x**2*z**2 + 2*x**2*y**2 A = CoordSys3D('A', transformation="spherical", variable_names=["r", "theta", "phi"]) B = CoordSys3D('B', transformation='cylindrical', variable_names=["r", "theta", "z"]) assert laplacian(A.r + A.theta + A.phi) == 2/A.r + cos(A.theta)/(A.r**2*sin(A.theta)) assert laplacian(B.r + B.theta + B.z) == 1/B.r # Tests for laplacian on vector fields assert laplacian(x*y*z*(i + j + k)) == Vector.zero assert laplacian(x*y**2*z*(i + j + k)) == \ 2*x*z*i + 2*x*z*j + 2*x*z*k def test_product_rules(): """ Tests the six product rules defined with respect to the Del operator References ========== .. [1] https://en.wikipedia.org/wiki/Del """ #Define the scalar and vector functions f = 2*x*y*z g = x*y + y*z + z*x u = x**2*i + 4*j - y**2*z*k v = 4*i + x*y*z*k # First product rule lhs = delop(f * g, doit=True) rhs = (f * delop(g) + g * delop(f)).doit() assert simplify(lhs) == simplify(rhs) # Second product rule lhs = delop(u & v).doit() rhs = ((u ^ (delop ^ v)) + (v ^ (delop ^ u)) + \ ((u & delop)(v)) + ((v & delop)(u))).doit() assert simplify(lhs) == simplify(rhs) # Third product rule lhs = (delop & (f*v)).doit() rhs = ((f * (delop & v)) + (v & (delop(f)))).doit() assert simplify(lhs) == simplify(rhs) # Fourth product rule lhs = (delop & (u ^ v)).doit() rhs = ((v & (delop ^ u)) - (u & (delop ^ v))).doit() assert simplify(lhs) == simplify(rhs) # Fifth product rule lhs = (delop ^ (f * v)).doit() rhs = (((delop(f)) ^ v) + (f * (delop ^ v))).doit() assert simplify(lhs) == simplify(rhs) # Sixth product rule lhs = (delop ^ (u ^ v)).doit() rhs = (u * (delop & v) - v * (delop & u) + (v & delop)(u) - (u & delop)(v)).doit() assert simplify(lhs) == simplify(rhs) P = C.orient_new_axis('P', q, C.k) # type: ignore scalar_field = 2*x**2*y*z grad_field = gradient(scalar_field) vector_field = y**2*i + 3*x*j + 5*y*z*k curl_field = curl(vector_field) def test_conservative(): assert is_conservative(Vector.zero) is True assert is_conservative(i) is True assert is_conservative(2 * i + 3 * j + 4 * k) is True assert (is_conservative(y*z*i + x*z*j + x*y*k) is True) assert is_conservative(x * j) is False assert is_conservative(grad_field) is True assert is_conservative(curl_field) is False assert (is_conservative(4*x*y*z*i + 2*x**2*z*j) is False) assert is_conservative(z*P.i + P.x*k) is True def test_solenoidal(): assert is_solenoidal(Vector.zero) is True assert is_solenoidal(i) is True assert is_solenoidal(2 * i + 3 * j + 4 * k) is True assert (is_solenoidal(y*z*i + x*z*j + x*y*k) is True) assert is_solenoidal(y * j) is False assert is_solenoidal(grad_field) is False assert is_solenoidal(curl_field) is True assert is_solenoidal((-2*y + 3)*k) is True assert is_solenoidal(cos(q)*i + sin(q)*j + cos(q)*P.k) is True assert is_solenoidal(z*P.i + P.x*k) is True def test_directional_derivative(): assert directional_derivative(C.x*C.y*C.z, 3*C.i + 4*C.j + C.k) == C.x*C.y + 4*C.x*C.z + 3*C.y*C.z assert directional_derivative(5*C.x**2*C.z, 3*C.i + 4*C.j + C.k) == 5*C.x**2 + 30*C.x*C.z assert directional_derivative(5*C.x**2*C.z, 4*C.j) is S.Zero D = CoordSys3D("D", "spherical", variable_names=["r", "theta", "phi"], vector_names=["e_r", "e_theta", "e_phi"]) r, theta, phi = D.base_scalars() e_r, e_theta, e_phi = D.base_vectors() assert directional_derivative(r**2*e_r, e_r) == 2*r*e_r assert directional_derivative(5*r**2*phi, 3*e_r + 4*e_theta + e_phi) == 5*r**2 + 30*r*phi def test_scalar_potential(): assert scalar_potential(Vector.zero, C) == 0 assert scalar_potential(i, C) == x assert scalar_potential(j, C) == y assert scalar_potential(k, C) == z assert scalar_potential(y*z*i + x*z*j + x*y*k, C) == x*y*z assert scalar_potential(grad_field, C) == scalar_field assert scalar_potential(z*P.i + P.x*k, C) == x*z*cos(q) + y*z*sin(q) assert scalar_potential(z*P.i + P.x*k, P) == P.x*P.z raises(ValueError, lambda: scalar_potential(x*j, C)) def test_scalar_potential_difference(): point1 = C.origin.locate_new('P1', 1*i + 2*j + 3*k) point2 = C.origin.locate_new('P2', 4*i + 5*j + 6*k) genericpointC = C.origin.locate_new('RP', x*i + y*j + z*k) genericpointP = P.origin.locate_new('PP', P.x*P.i + P.y*P.j + P.z*P.k) assert scalar_potential_difference(S.Zero, C, point1, point2) == 0 assert (scalar_potential_difference(scalar_field, C, C.origin, genericpointC) == scalar_field) assert (scalar_potential_difference(grad_field, C, C.origin, genericpointC) == scalar_field) assert scalar_potential_difference(grad_field, C, point1, point2) == 948 assert (scalar_potential_difference(y*z*i + x*z*j + x*y*k, C, point1, genericpointC) == x*y*z - 6) potential_diff_P = (2*P.z*(P.x*sin(q) + P.y*cos(q))* (P.x*cos(q) - P.y*sin(q))**2) assert (scalar_potential_difference(grad_field, P, P.origin, genericpointP).simplify() == potential_diff_P.simplify()) def test_differential_operators_curvilinear_system(): A = CoordSys3D('A', transformation="spherical", variable_names=["r", "theta", "phi"]) B = CoordSys3D('B', transformation='cylindrical', variable_names=["r", "theta", "z"]) # Test for spherical coordinate system and gradient assert gradient(3*A.r + 4*A.theta) == 3*A.i + 4/A.r*A.j assert gradient(3*A.r*A.phi + 4*A.theta) == 3*A.phi*A.i + 4/A.r*A.j + (3/sin(A.theta))*A.k assert gradient(0*A.r + 0*A.theta+0*A.phi) == Vector.zero assert gradient(A.r*A.theta*A.phi) == A.theta*A.phi*A.i + A.phi*A.j + (A.theta/sin(A.theta))*A.k # Test for spherical coordinate system and divergence assert divergence(A.r * A.i + A.theta * A.j + A.phi * A.k) == \ (sin(A.theta)*A.r + cos(A.theta)*A.r*A.theta)/(sin(A.theta)*A.r**2) + 3 + 1/(sin(A.theta)*A.r) assert divergence(3*A.r*A.phi*A.i + A.theta*A.j + A.r*A.theta*A.phi*A.k) == \ (sin(A.theta)*A.r + cos(A.theta)*A.r*A.theta)/(sin(A.theta)*A.r**2) + 9*A.phi + A.theta/sin(A.theta) assert divergence(Vector.zero) == 0 assert divergence(0*A.i + 0*A.j + 0*A.k) == 0 # Test for spherical coordinate system and curl assert curl(A.r*A.i + A.theta*A.j + A.phi*A.k) == \ (cos(A.theta)*A.phi/(sin(A.theta)*A.r))*A.i + (-A.phi/A.r)*A.j + A.theta/A.r*A.k assert curl(A.r*A.j + A.phi*A.k) == (cos(A.theta)*A.phi/(sin(A.theta)*A.r))*A.i + (-A.phi/A.r)*A.j + 2*A.k # Test for cylindrical coordinate system and gradient assert gradient(0*B.r + 0*B.theta+0*B.z) == Vector.zero assert gradient(B.r*B.theta*B.z) == B.theta*B.z*B.i + B.z*B.j + B.r*B.theta*B.k assert gradient(3*B.r) == 3*B.i assert gradient(2*B.theta) == 2/B.r * B.j assert gradient(4*B.z) == 4*B.k # Test for cylindrical coordinate system and divergence assert divergence(B.r*B.i + B.theta*B.j + B.z*B.k) == 3 + 1/B.r assert divergence(B.r*B.j + B.z*B.k) == 1 # Test for cylindrical coordinate system and curl assert curl(B.r*B.j + B.z*B.k) == 2*B.k assert curl(3*B.i + 2/B.r*B.j + 4*B.k) == Vector.zero def test_mixed_coordinates(): # gradient a = CoordSys3D('a') b = CoordSys3D('b') c = CoordSys3D('c') assert gradient(a.x*b.y) == b.y*a.i + a.x*b.j assert gradient(3*cos(q)*a.x*b.x+a.y*(a.x+(cos(q)+b.x))) ==\ (a.y + 3*b.x*cos(q))*a.i + (a.x + b.x + cos(q))*a.j + (3*a.x*cos(q) + a.y)*b.i # Some tests need further work: # assert gradient(a.x*(cos(a.x+b.x))) == (cos(a.x + b.x))*a.i + a.x*Gradient(cos(a.x + b.x)) # assert gradient(cos(a.x + b.x)*cos(a.x + b.z)) == Gradient(cos(a.x + b.x)*cos(a.x + b.z)) assert gradient(a.x**b.y) == Gradient(a.x**b.y) # assert gradient(cos(a.x+b.y)*a.z) == None assert gradient(cos(a.x*b.y)) == Gradient(cos(a.x*b.y)) assert gradient(3*cos(q)*a.x*b.x*a.z*a.y+ b.y*b.z + cos(a.x+a.y)*b.z) == \ (3*a.y*a.z*b.x*cos(q) - b.z*sin(a.x + a.y))*a.i + \ (3*a.x*a.z*b.x*cos(q) - b.z*sin(a.x + a.y))*a.j + (3*a.x*a.y*b.x*cos(q))*a.k + \ (3*a.x*a.y*a.z*cos(q))*b.i + b.z*b.j + (b.y + cos(a.x + a.y))*b.k # divergence assert divergence(a.i*a.x+a.j*a.y+a.z*a.k + b.i*b.x+b.j*b.y+b.z*b.k + c.i*c.x+c.j*c.y+c.z*c.k) == S(9) # assert divergence(3*a.i*a.x*cos(a.x+b.z) + a.j*b.x*c.z) == None assert divergence(3*a.i*a.x*a.z + b.j*b.x*c.z + 3*a.j*a.z*a.y) == \ 6*a.z + b.x*Dot(b.j, c.k) assert divergence(3*cos(q)*a.x*b.x*b.i*c.x) == \ 3*a.x*b.x*cos(q)*Dot(b.i, c.i) + 3*a.x*c.x*cos(q) + 3*b.x*c.x*cos(q)*Dot(b.i, a.i) assert divergence(a.x*b.x*c.x*Cross(a.x*a.i, a.y*b.j)) ==\ a.x*b.x*c.x*Divergence(Cross(a.x*a.i, a.y*b.j)) + \ b.x*c.x*Dot(Cross(a.x*a.i, a.y*b.j), a.i) + \ a.x*c.x*Dot(Cross(a.x*a.i, a.y*b.j), b.i) + \ a.x*b.x*Dot(Cross(a.x*a.i, a.y*b.j), c.i) assert divergence(a.x*b.x*c.x*(a.x*a.i + b.x*b.i)) == \ 4*a.x*b.x*c.x +\ a.x**2*c.x*Dot(a.i, b.i) +\ a.x**2*b.x*Dot(a.i, c.i) +\ b.x**2*c.x*Dot(b.i, a.i) +\ a.x*b.x**2*Dot(b.i, c.i)
3213efc8baf7b29a92969dc5ef9281c3ed0f49493cbfecfa9dce2ec2cd17df98
from sympy.testing.pytest import raises, warns_deprecated_sympy from sympy.vector.coordsysrect import CoordSys3D, CoordSysCartesian from sympy.vector.scalar import BaseScalar from sympy.core.function import expand from sympy.core.numbers import pi from sympy.core.symbol import symbols from sympy.functions.elementary.hyperbolic import (cosh, sinh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, atan2, cos, sin) from sympy.matrices.dense import zeros from sympy.matrices.immutable import ImmutableDenseMatrix as Matrix from sympy.simplify.simplify import simplify from sympy.vector.functions import express from sympy.vector.point import Point from sympy.vector.vector import Vector from sympy.vector.orienters import (AxisOrienter, BodyOrienter, SpaceOrienter, QuaternionOrienter) x, y, z = symbols('x y z') a, b, c, q = symbols('a b c q') q1, q2, q3, q4 = symbols('q1 q2 q3 q4') def test_func_args(): A = CoordSys3D('A') assert A.x.func(*A.x.args) == A.x expr = 3*A.x + 4*A.y assert expr.func(*expr.args) == expr assert A.i.func(*A.i.args) == A.i v = A.x*A.i + A.y*A.j + A.z*A.k assert v.func(*v.args) == v assert A.origin.func(*A.origin.args) == A.origin def test_coordsyscartesian_equivalence(): A = CoordSys3D('A') A1 = CoordSys3D('A') assert A1 == A B = CoordSys3D('B') assert A != B def test_orienters(): A = CoordSys3D('A') axis_orienter = AxisOrienter(a, A.k) body_orienter = BodyOrienter(a, b, c, '123') space_orienter = SpaceOrienter(a, b, c, '123') q_orienter = QuaternionOrienter(q1, q2, q3, q4) assert axis_orienter.rotation_matrix(A) == Matrix([ [ cos(a), sin(a), 0], [-sin(a), cos(a), 0], [ 0, 0, 1]]) assert body_orienter.rotation_matrix() == Matrix([ [ cos(b)*cos(c), sin(a)*sin(b)*cos(c) + sin(c)*cos(a), sin(a)*sin(c) - sin(b)*cos(a)*cos(c)], [-sin(c)*cos(b), -sin(a)*sin(b)*sin(c) + cos(a)*cos(c), sin(a)*cos(c) + sin(b)*sin(c)*cos(a)], [ sin(b), -sin(a)*cos(b), cos(a)*cos(b)]]) assert space_orienter.rotation_matrix() == Matrix([ [cos(b)*cos(c), sin(c)*cos(b), -sin(b)], [sin(a)*sin(b)*cos(c) - sin(c)*cos(a), sin(a)*sin(b)*sin(c) + cos(a)*cos(c), sin(a)*cos(b)], [sin(a)*sin(c) + sin(b)*cos(a)*cos(c), -sin(a)*cos(c) + sin(b)*sin(c)*cos(a), cos(a)*cos(b)]]) assert q_orienter.rotation_matrix() == Matrix([ [q1**2 + q2**2 - q3**2 - q4**2, 2*q1*q4 + 2*q2*q3, -2*q1*q3 + 2*q2*q4], [-2*q1*q4 + 2*q2*q3, q1**2 - q2**2 + q3**2 - q4**2, 2*q1*q2 + 2*q3*q4], [2*q1*q3 + 2*q2*q4, -2*q1*q2 + 2*q3*q4, q1**2 - q2**2 - q3**2 + q4**2]]) def test_coordinate_vars(): """ Tests the coordinate variables functionality with respect to reorientation of coordinate systems. """ A = CoordSys3D('A') # Note that the name given on the lhs is different from A.x._name assert BaseScalar(0, A, 'A_x', r'\mathbf{{x}_{A}}') == A.x assert BaseScalar(1, A, 'A_y', r'\mathbf{{y}_{A}}') == A.y assert BaseScalar(2, A, 'A_z', r'\mathbf{{z}_{A}}') == A.z assert BaseScalar(0, A, 'A_x', r'\mathbf{{x}_{A}}').__hash__() == A.x.__hash__() assert isinstance(A.x, BaseScalar) and \ isinstance(A.y, BaseScalar) and \ isinstance(A.z, BaseScalar) assert A.x*A.y == A.y*A.x assert A.scalar_map(A) == {A.x: A.x, A.y: A.y, A.z: A.z} assert A.x.system == A assert A.x.diff(A.x) == 1 B = A.orient_new_axis('B', q, A.k) assert B.scalar_map(A) == {B.z: A.z, B.y: -A.x*sin(q) + A.y*cos(q), B.x: A.x*cos(q) + A.y*sin(q)} assert A.scalar_map(B) == {A.x: B.x*cos(q) - B.y*sin(q), A.y: B.x*sin(q) + B.y*cos(q), A.z: B.z} assert express(B.x, A, variables=True) == A.x*cos(q) + A.y*sin(q) assert express(B.y, A, variables=True) == -A.x*sin(q) + A.y*cos(q) assert express(B.z, A, variables=True) == A.z assert expand(express(B.x*B.y*B.z, A, variables=True)) == \ expand(A.z*(-A.x*sin(q) + A.y*cos(q))*(A.x*cos(q) + A.y*sin(q))) assert express(B.x*B.i + B.y*B.j + B.z*B.k, A) == \ (B.x*cos(q) - B.y*sin(q))*A.i + (B.x*sin(q) + \ B.y*cos(q))*A.j + B.z*A.k assert simplify(express(B.x*B.i + B.y*B.j + B.z*B.k, A, \ variables=True)) == \ A.x*A.i + A.y*A.j + A.z*A.k assert express(A.x*A.i + A.y*A.j + A.z*A.k, B) == \ (A.x*cos(q) + A.y*sin(q))*B.i + \ (-A.x*sin(q) + A.y*cos(q))*B.j + A.z*B.k assert simplify(express(A.x*A.i + A.y*A.j + A.z*A.k, B, \ variables=True)) == \ B.x*B.i + B.y*B.j + B.z*B.k N = B.orient_new_axis('N', -q, B.k) assert N.scalar_map(A) == \ {N.x: A.x, N.z: A.z, N.y: A.y} C = A.orient_new_axis('C', q, A.i + A.j + A.k) mapping = A.scalar_map(C) assert mapping[A.x].equals(C.x*(2*cos(q) + 1)/3 + C.y*(-2*sin(q + pi/6) + 1)/3 + C.z*(-2*cos(q + pi/3) + 1)/3) assert mapping[A.y].equals(C.x*(-2*cos(q + pi/3) + 1)/3 + C.y*(2*cos(q) + 1)/3 + C.z*(-2*sin(q + pi/6) + 1)/3) assert mapping[A.z].equals(C.x*(-2*sin(q + pi/6) + 1)/3 + C.y*(-2*cos(q + pi/3) + 1)/3 + C.z*(2*cos(q) + 1)/3) D = A.locate_new('D', a*A.i + b*A.j + c*A.k) assert D.scalar_map(A) == {D.z: A.z - c, D.x: A.x - a, D.y: A.y - b} E = A.orient_new_axis('E', a, A.k, a*A.i + b*A.j + c*A.k) assert A.scalar_map(E) == {A.z: E.z + c, A.x: E.x*cos(a) - E.y*sin(a) + a, A.y: E.x*sin(a) + E.y*cos(a) + b} assert E.scalar_map(A) == {E.x: (A.x - a)*cos(a) + (A.y - b)*sin(a), E.y: (-A.x + a)*sin(a) + (A.y - b)*cos(a), E.z: A.z - c} F = A.locate_new('F', Vector.zero) assert A.scalar_map(F) == {A.z: F.z, A.x: F.x, A.y: F.y} def test_rotation_matrix(): N = CoordSys3D('N') A = N.orient_new_axis('A', q1, N.k) B = A.orient_new_axis('B', q2, A.i) C = B.orient_new_axis('C', q3, B.j) D = N.orient_new_axis('D', q4, N.j) E = N.orient_new_space('E', q1, q2, q3, '123') F = N.orient_new_quaternion('F', q1, q2, q3, q4) G = N.orient_new_body('G', q1, q2, q3, '123') assert N.rotation_matrix(C) == 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)]]) test_mat = D.rotation_matrix(C) - Matrix( [[cos(q1) * cos(q3) * cos(q4) - sin(q3) * (- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4)), - sin(q2) * sin(q4) - sin(q1) * cos(q2) * cos(q4), sin(q3) * cos(q1) * cos(q4) + cos(q3) * \ (- sin(q4) * cos(q2) + sin(q1) * sin(q2) * cos(q4))], \ [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(q4) * cos(q1) * cos(q3) - sin(q3) * (cos(q2) * cos(q4) + \ sin(q1) * sin(q2) * \ sin(q4)), sin(q2) * cos(q4) - sin(q1) * sin(q4) * cos(q2), sin(q3) * \ sin(q4) * cos(q1) + cos(q3) * (cos(q2) * cos(q4) + \ sin(q1) * sin(q2) * sin(q4))]]) assert test_mat.expand() == zeros(3, 3) assert E.rotation_matrix(N) == Matrix( [[cos(q2)*cos(q3), sin(q3)*cos(q2), -sin(q2)], [sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), \ sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q2)], \ [sin(q1)*sin(q3) + sin(q2)*cos(q1)*cos(q3), - \ sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1), cos(q1)*cos(q2)]]) assert F.rotation_matrix(N) == Matrix([[ q1**2 + q2**2 - q3**2 - q4**2, 2*q1*q4 + 2*q2*q3, -2*q1*q3 + 2*q2*q4],[ -2*q1*q4 + 2*q2*q3, q1**2 - q2**2 + q3**2 - q4**2, 2*q1*q2 + 2*q3*q4], [2*q1*q3 + 2*q2*q4, -2*q1*q2 + 2*q3*q4, q1**2 - q2**2 - q3**2 + q4**2]]) assert G.rotation_matrix(N) == Matrix([[ cos(q2)*cos(q3), sin(q1)*sin(q2)*cos(q3) + sin(q3)*cos(q1), sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3)], [ -sin(q3)*cos(q2), -sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3), sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)],[ sin(q2), -sin(q1)*cos(q2), cos(q1)*cos(q2)]]) def test_vector_with_orientation(): """ Tests the effects of orientation of coordinate systems on basic vector operations. """ N = CoordSys3D('N') A = N.orient_new_axis('A', q1, N.k) B = A.orient_new_axis('B', q2, A.i) C = B.orient_new_axis('C', q3, B.j) # Test to_matrix v1 = a*N.i + b*N.j + c*N.k assert v1.to_matrix(A) == Matrix([[ a*cos(q1) + b*sin(q1)], [-a*sin(q1) + b*cos(q1)], [ c]]) # Test dot assert N.i.dot(A.i) == cos(q1) assert N.i.dot(A.j) == -sin(q1) assert N.i.dot(A.k) == 0 assert N.j.dot(A.i) == sin(q1) assert N.j.dot(A.j) == cos(q1) assert N.j.dot(A.k) == 0 assert N.k.dot(A.i) == 0 assert N.k.dot(A.j) == 0 assert N.k.dot(A.k) == 1 assert N.i.dot(A.i + A.j) == -sin(q1) + cos(q1) == \ (A.i + A.j).dot(N.i) assert A.i.dot(C.i) == cos(q3) assert A.i.dot(C.j) == 0 assert A.i.dot(C.k) == sin(q3) assert A.j.dot(C.i) == sin(q2)*sin(q3) assert A.j.dot(C.j) == cos(q2) assert A.j.dot(C.k) == -sin(q2)*cos(q3) assert A.k.dot(C.i) == -cos(q2)*sin(q3) assert A.k.dot(C.j) == sin(q2) assert A.k.dot(C.k) == cos(q2)*cos(q3) # Test cross assert N.i.cross(A.i) == sin(q1)*A.k assert N.i.cross(A.j) == cos(q1)*A.k assert N.i.cross(A.k) == -sin(q1)*A.i - cos(q1)*A.j assert N.j.cross(A.i) == -cos(q1)*A.k assert N.j.cross(A.j) == sin(q1)*A.k assert N.j.cross(A.k) == cos(q1)*A.i - sin(q1)*A.j assert N.k.cross(A.i) == A.j assert N.k.cross(A.j) == -A.i assert N.k.cross(A.k) == Vector.zero assert N.i.cross(A.i) == sin(q1)*A.k assert N.i.cross(A.j) == cos(q1)*A.k assert N.i.cross(A.i + A.j) == sin(q1)*A.k + cos(q1)*A.k assert (A.i + A.j).cross(N.i) == (-sin(q1) - cos(q1))*N.k assert A.i.cross(C.i) == sin(q3)*C.j assert A.i.cross(C.j) == -sin(q3)*C.i + cos(q3)*C.k assert A.i.cross(C.k) == -cos(q3)*C.j assert C.i.cross(A.i) == (-sin(q3)*cos(q2))*A.j + \ (-sin(q2)*sin(q3))*A.k assert C.j.cross(A.i) == (sin(q2))*A.j + (-cos(q2))*A.k assert express(C.k.cross(A.i), C).trigsimp() == cos(q3)*C.j def test_orient_new_methods(): N = CoordSys3D('N') orienter1 = AxisOrienter(q4, N.j) orienter2 = SpaceOrienter(q1, q2, q3, '123') orienter3 = QuaternionOrienter(q1, q2, q3, q4) orienter4 = BodyOrienter(q1, q2, q3, '123') D = N.orient_new('D', (orienter1, )) E = N.orient_new('E', (orienter2, )) F = N.orient_new('F', (orienter3, )) G = N.orient_new('G', (orienter4, )) assert D == N.orient_new_axis('D', q4, N.j) assert E == N.orient_new_space('E', q1, q2, q3, '123') assert F == N.orient_new_quaternion('F', q1, q2, q3, q4) assert G == N.orient_new_body('G', q1, q2, q3, '123') def test_locatenew_point(): """ Tests Point class, and locate_new method in CoordSysCartesian. """ A = CoordSys3D('A') assert isinstance(A.origin, Point) v = a*A.i + b*A.j + c*A.k C = A.locate_new('C', v) assert C.origin.position_wrt(A) == \ C.position_wrt(A) == \ C.origin.position_wrt(A.origin) == v assert A.origin.position_wrt(C) == \ A.position_wrt(C) == \ A.origin.position_wrt(C.origin) == -v assert A.origin.express_coordinates(C) == (-a, -b, -c) p = A.origin.locate_new('p', -v) assert p.express_coordinates(A) == (-a, -b, -c) assert p.position_wrt(C.origin) == p.position_wrt(C) == \ -2 * v p1 = p.locate_new('p1', 2*v) assert p1.position_wrt(C.origin) == Vector.zero assert p1.express_coordinates(C) == (0, 0, 0) p2 = p.locate_new('p2', A.i) assert p1.position_wrt(p2) == 2*v - A.i assert p2.express_coordinates(C) == (-2*a + 1, -2*b, -2*c) def test_create_new(): a = CoordSys3D('a') c = a.create_new('c', transformation='spherical') assert c._parent == a assert c.transformation_to_parent() == \ (c.r*sin(c.theta)*cos(c.phi), c.r*sin(c.theta)*sin(c.phi), c.r*cos(c.theta)) assert c.transformation_from_parent() == \ (sqrt(a.x**2 + a.y**2 + a.z**2), acos(a.z/sqrt(a.x**2 + a.y**2 + a.z**2)), atan2(a.y, a.x)) def test_evalf(): A = CoordSys3D('A') v = 3*A.i + 4*A.j + a*A.k assert v.n() == v.evalf() assert v.evalf(subs={a:1}) == v.subs(a, 1).evalf() def test_lame_coefficients(): a = CoordSys3D('a', 'spherical') assert a.lame_coefficients() == (1, a.r, sin(a.theta)*a.r) a = CoordSys3D('a') assert a.lame_coefficients() == (1, 1, 1) a = CoordSys3D('a', 'cartesian') assert a.lame_coefficients() == (1, 1, 1) a = CoordSys3D('a', 'cylindrical') assert a.lame_coefficients() == (1, a.r, 1) def test_transformation_equations(): x, y, z = symbols('x y z') # Str a = CoordSys3D('a', transformation='spherical', variable_names=["r", "theta", "phi"]) r, theta, phi = a.base_scalars() assert r == a.r assert theta == a.theta assert phi == a.phi raises(AttributeError, lambda: a.x) raises(AttributeError, lambda: a.y) raises(AttributeError, lambda: a.z) assert a.transformation_to_parent() == ( r*sin(theta)*cos(phi), r*sin(theta)*sin(phi), r*cos(theta) ) assert a.lame_coefficients() == (1, r, r*sin(theta)) assert a.transformation_from_parent_function()(x, y, z) == ( sqrt(x ** 2 + y ** 2 + z ** 2), acos((z) / sqrt(x**2 + y**2 + z**2)), atan2(y, x) ) a = CoordSys3D('a', transformation='cylindrical', variable_names=["r", "theta", "z"]) r, theta, z = a.base_scalars() assert a.transformation_to_parent() == ( r*cos(theta), r*sin(theta), z ) assert a.lame_coefficients() == (1, a.r, 1) assert a.transformation_from_parent_function()(x, y, z) == (sqrt(x**2 + y**2), atan2(y, x), z) a = CoordSys3D('a', 'cartesian') assert a.transformation_to_parent() == (a.x, a.y, a.z) assert a.lame_coefficients() == (1, 1, 1) assert a.transformation_from_parent_function()(x, y, z) == (x, y, z) # Variables and expressions # Cartesian with equation tuple: x, y, z = symbols('x y z') a = CoordSys3D('a', ((x, y, z), (x, y, z))) a._calculate_inv_trans_equations() assert a.transformation_to_parent() == (a.x1, a.x2, a.x3) assert a.lame_coefficients() == (1, 1, 1) assert a.transformation_from_parent_function()(x, y, z) == (x, y, z) r, theta, z = symbols("r theta z") # Cylindrical with equation tuple: a = CoordSys3D('a', [(r, theta, z), (r*cos(theta), r*sin(theta), z)], variable_names=["r", "theta", "z"]) r, theta, z = a.base_scalars() assert a.transformation_to_parent() == ( r*cos(theta), r*sin(theta), z ) assert a.lame_coefficients() == ( sqrt(sin(theta)**2 + cos(theta)**2), sqrt(r**2*sin(theta)**2 + r**2*cos(theta)**2), 1 ) # ==> this should simplify to (1, r, 1), tests are too slow with `simplify`. # Definitions with `lambda`: # Cartesian with `lambda` a = CoordSys3D('a', lambda x, y, z: (x, y, z)) assert a.transformation_to_parent() == (a.x1, a.x2, a.x3) assert a.lame_coefficients() == (1, 1, 1) a._calculate_inv_trans_equations() assert a.transformation_from_parent_function()(x, y, z) == (x, y, z) # Spherical with `lambda` a = CoordSys3D('a', lambda r, theta, phi: (r*sin(theta)*cos(phi), r*sin(theta)*sin(phi), r*cos(theta)), variable_names=["r", "theta", "phi"]) r, theta, phi = a.base_scalars() assert a.transformation_to_parent() == ( r*sin(theta)*cos(phi), r*sin(phi)*sin(theta), r*cos(theta) ) assert a.lame_coefficients() == ( sqrt(sin(phi)**2*sin(theta)**2 + sin(theta)**2*cos(phi)**2 + cos(theta)**2), sqrt(r**2*sin(phi)**2*cos(theta)**2 + r**2*sin(theta)**2 + r**2*cos(phi)**2*cos(theta)**2), sqrt(r**2*sin(phi)**2*sin(theta)**2 + r**2*sin(theta)**2*cos(phi)**2) ) # ==> this should simplify to (1, r, sin(theta)*r), `simplify` is too slow. # Cylindrical with `lambda` a = CoordSys3D('a', lambda r, theta, z: (r*cos(theta), r*sin(theta), z), variable_names=["r", "theta", "z"] ) r, theta, z = a.base_scalars() assert a.transformation_to_parent() == (r*cos(theta), r*sin(theta), z) assert a.lame_coefficients() == ( sqrt(sin(theta)**2 + cos(theta)**2), sqrt(r**2*sin(theta)**2 + r**2*cos(theta)**2), 1 ) # ==> this should simplify to (1, a.x, 1) raises(TypeError, lambda: CoordSys3D('a', transformation={ x: x*sin(y)*cos(z), y:x*sin(y)*sin(z), z: x*cos(y)})) def test_check_orthogonality(): x, y, z = symbols('x y z') u,v = symbols('u, v') a = CoordSys3D('a', transformation=((x, y, z), (x*sin(y)*cos(z), x*sin(y)*sin(z), x*cos(y)))) assert a._check_orthogonality(a._transformation) is True a = CoordSys3D('a', transformation=((x, y, z), (x * cos(y), x * sin(y), z))) assert a._check_orthogonality(a._transformation) is True a = CoordSys3D('a', transformation=((u, v, z), (cosh(u) * cos(v), sinh(u) * sin(v), z))) assert a._check_orthogonality(a._transformation) is True raises(ValueError, lambda: CoordSys3D('a', transformation=((x, y, z), (x, x, z)))) raises(ValueError, lambda: CoordSys3D('a', transformation=( (x, y, z), (x*sin(y/2)*cos(z), x*sin(y)*sin(z), x*cos(y))))) def test_coordsys3d(): with warns_deprecated_sympy(): assert CoordSysCartesian("C") == CoordSys3D("C") def test_rotation_trans_equations(): a = CoordSys3D('a') from sympy.core.symbol import symbols q0 = symbols('q0') assert a._rotation_trans_equations(a._parent_rotation_matrix, a.base_scalars()) == (a.x, a.y, a.z) assert a._rotation_trans_equations(a._inverse_rotation_matrix(), a.base_scalars()) == (a.x, a.y, a.z) b = a.orient_new_axis('b', 0, -a.k) assert b._rotation_trans_equations(b._parent_rotation_matrix, b.base_scalars()) == (b.x, b.y, b.z) assert b._rotation_trans_equations(b._inverse_rotation_matrix(), b.base_scalars()) == (b.x, b.y, b.z) c = a.orient_new_axis('c', q0, -a.k) assert c._rotation_trans_equations(c._parent_rotation_matrix, c.base_scalars()) == \ (-sin(q0) * c.y + cos(q0) * c.x, sin(q0) * c.x + cos(q0) * c.y, c.z) assert c._rotation_trans_equations(c._inverse_rotation_matrix(), c.base_scalars()) == \ (sin(q0) * c.y + cos(q0) * c.x, -sin(q0) * c.x + cos(q0) * c.y, c.z)
4bf4cf4763d39c062bc6a23db928858fa67f4634ff8b0368a32e9bc8edaa0fbe
from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.functions.elementary.miscellaneous import 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())
29ec545af73f370a761d6ac46e1c623bb31e685c5895c92ba7ffd393083ec265
from sympy.vector import CoordSys3D, Gradient, Divergence, Curl, VectorZero, Laplacian from sympy.printing.repr import srepr R = CoordSys3D('R') s1 = R.x*R.y*R.z # type: ignore s2 = R.x + 3*R.y**2 # type: ignore s3 = R.x**2 + R.y**2 + R.z**2 # type: ignore v1 = R.x*R.i + R.z*R.z*R.j # type: ignore v2 = R.x*R.i + R.y*R.j + R.z*R.k # type: ignore v3 = R.x**2*R.i + R.y**2*R.j + R.z**2*R.k # type: ignore def test_Gradient(): assert Gradient(s1) == Gradient(R.x*R.y*R.z) assert Gradient(s2) == Gradient(R.x + 3*R.y**2) assert Gradient(s1).doit() == R.y*R.z*R.i + R.x*R.z*R.j + R.x*R.y*R.k assert Gradient(s2).doit() == R.i + 6*R.y*R.j def test_Divergence(): assert Divergence(v1) == Divergence(R.x*R.i + R.z*R.z*R.j) assert Divergence(v2) == Divergence(R.x*R.i + R.y*R.j + R.z*R.k) assert Divergence(v1).doit() == 1 assert Divergence(v2).doit() == 3 # issue 22384 Rc = CoordSys3D('R', transformation='cylindrical') assert Divergence(Rc.i).doit() == 1/Rc.r def test_Curl(): assert Curl(v1) == Curl(R.x*R.i + R.z*R.z*R.j) assert Curl(v2) == Curl(R.x*R.i + R.y*R.j + R.z*R.k) assert Curl(v1).doit() == (-2*R.z)*R.i assert Curl(v2).doit() == VectorZero() def test_Laplacian(): assert Laplacian(s3) == Laplacian(R.x**2 + R.y**2 + R.z**2) assert Laplacian(v3) == Laplacian(R.x**2*R.i + R.y**2*R.j + R.z**2*R.k) assert Laplacian(s3).doit() == 6 assert Laplacian(v3).doit() == 2*R.i + 2*R.j + 2*R.k assert srepr(Laplacian(s3)) == \ 'Laplacian(Add(Pow(R.x, Integer(2)), Pow(R.y, Integer(2)), Pow(R.z, Integer(2))))'
e4170f6752b2c7683aaadae44f23168acf79945a5c090a19a56bf8158bb2d042
# -*- coding: utf-8 -*- from sympy.core.function import Function from sympy.integrals.integrals import Integral from sympy.printing.latex import latex from sympy.printing.pretty 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}}"
41171fa03b09b42b5cbe315bd7c841107ba9c9c2e0013d8ea2117a1a93528724
from sympy.core.numbers import (Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import (Dummy, symbols) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (asin, cos, sin) from sympy.geometry import Line, Point, Ray, Segment, Point3D, Line3D, Ray3D, Segment3D, Plane, Circle from sympy.geometry.util import are_coplanar from sympy.testing.pytest import raises def test_plane(): x, y, z, u, v = symbols('x y z u v', real=True) p1 = Point3D(0, 0, 0) p2 = Point3D(1, 1, 1) p3 = Point3D(1, 2, 3) pl3 = Plane(p1, p2, p3) pl4 = Plane(p1, normal_vector=(1, 1, 1)) pl4b = Plane(p1, p2) pl5 = Plane(p3, normal_vector=(1, 2, 3)) pl6 = Plane(Point3D(2, 3, 7), normal_vector=(2, 2, 2)) pl7 = Plane(Point3D(1, -5, -6), normal_vector=(1, -2, 1)) pl8 = Plane(p1, normal_vector=(0, 0, 1)) pl9 = Plane(p1, normal_vector=(0, 12, 0)) pl10 = Plane(p1, normal_vector=(-2, 0, 0)) pl11 = Plane(p2, normal_vector=(0, 0, 1)) l1 = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1)) l2 = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1)) l3 = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9)) raises(ValueError, lambda: Plane(p1, p1, p1)) assert Plane(p1, p2, p3) != Plane(p1, p3, p2) assert Plane(p1, p2, p3).is_coplanar(Plane(p1, p3, p2)) assert Plane(p1, p2, p3).is_coplanar(p1) assert Plane(p1, p2, p3).is_coplanar(Circle(p1, 1)) is False assert Plane(p1, normal_vector=(0, 0, 1)).is_coplanar(Circle(p1, 1)) assert pl3 == Plane(Point3D(0, 0, 0), normal_vector=(1, -2, 1)) assert pl3 != pl4 assert pl4 == pl4b assert pl5 == Plane(Point3D(1, 2, 3), normal_vector=(1, 2, 3)) assert pl5.equation(x, y, z) == x + 2*y + 3*z - 14 assert pl3.equation(x, y, z) == x - 2*y + z assert pl3.p1 == p1 assert pl4.p1 == p1 assert pl5.p1 == p3 assert pl4.normal_vector == (1, 1, 1) assert pl5.normal_vector == (1, 2, 3) assert p1 in pl3 assert p1 in pl4 assert p3 in pl5 assert pl3.projection(Point(0, 0)) == p1 p = pl3.projection(Point3D(1, 1, 0)) assert p == Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6)) assert p in pl3 l = pl3.projection_line(Line(Point(0, 0), Point(1, 1))) assert l == Line3D(Point3D(0, 0, 0), Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6))) assert l in pl3 # get a segment that does not intersect the plane which is also # parallel to pl3's normal veector t = Dummy() r = pl3.random_point() a = pl3.perpendicular_line(r).arbitrary_point(t) s = Segment3D(a.subs(t, 1), a.subs(t, 2)) assert s.p1 not in pl3 and s.p2 not in pl3 assert pl3.projection_line(s).equals(r) assert pl3.projection_line(Segment(Point(1, 0), Point(1, 1))) == \ Segment3D(Point3D(Rational(5, 6), Rational(1, 3), Rational(-1, 6)), Point3D(Rational(7, 6), Rational(2, 3), Rational(1, 6))) assert pl6.projection_line(Ray(Point(1, 0), Point(1, 1))) == \ Ray3D(Point3D(Rational(14, 3), Rational(11, 3), Rational(11, 3)), Point3D(Rational(13, 3), Rational(13, 3), Rational(10, 3))) assert pl3.perpendicular_line(r.args) == pl3.perpendicular_line(r) assert pl3.is_parallel(pl6) is False assert pl4.is_parallel(pl6) assert pl3.is_parallel(Line(p1, p2)) assert pl6.is_parallel(l1) is False assert pl3.is_perpendicular(pl6) assert pl4.is_perpendicular(pl7) assert pl6.is_perpendicular(pl7) assert pl6.is_perpendicular(pl4) is False assert pl6.is_perpendicular(l1) is False assert pl6.is_perpendicular(Line((0, 0, 0), (1, 1, 1))) assert pl6.is_perpendicular((1, 1)) is False assert pl6.distance(pl6.arbitrary_point(u, v)) == 0 assert pl7.distance(pl7.arbitrary_point(u, v)) == 0 assert pl6.distance(pl6.arbitrary_point(t)) == 0 assert pl7.distance(pl7.arbitrary_point(t)) == 0 assert pl6.p1.distance(pl6.arbitrary_point(t)).simplify() == 1 assert pl7.p1.distance(pl7.arbitrary_point(t)).simplify() == 1 assert pl3.arbitrary_point(t) == Point3D(-sqrt(30)*sin(t)/30 + \ 2*sqrt(5)*cos(t)/5, sqrt(30)*sin(t)/15 + sqrt(5)*cos(t)/5, sqrt(30)*sin(t)/6) assert pl3.arbitrary_point(u, v) == Point3D(2*u - v, u + 2*v, 5*v) assert pl7.distance(Point3D(1, 3, 5)) == 5*sqrt(6)/6 assert pl6.distance(Point3D(0, 0, 0)) == 4*sqrt(3) assert pl6.distance(pl6.p1) == 0 assert pl7.distance(pl6) == 0 assert pl7.distance(l1) == 0 assert pl6.distance(Segment3D(Point3D(2, 3, 1), Point3D(1, 3, 4))) == \ pl6.distance(Point3D(1, 3, 4)) == 4*sqrt(3)/3 assert pl6.distance(Segment3D(Point3D(1, 3, 4), Point3D(0, 3, 7))) == \ pl6.distance(Point3D(0, 3, 7)) == 2*sqrt(3)/3 assert pl6.distance(Segment3D(Point3D(0, 3, 7), Point3D(-1, 3, 10))) == 0 assert pl6.distance(Segment3D(Point3D(-1, 3, 10), Point3D(-2, 3, 13))) == 0 assert pl6.distance(Segment3D(Point3D(-2, 3, 13), Point3D(-3, 3, 16))) == \ pl6.distance(Point3D(-2, 3, 13)) == 2*sqrt(3)/3 assert pl6.distance(Plane(Point3D(5, 5, 5), normal_vector=(8, 8, 8))) == sqrt(3) assert pl6.distance(Ray3D(Point3D(1, 3, 4), direction_ratio=[1, 0, -3])) == 4*sqrt(3)/3 assert pl6.distance(Ray3D(Point3D(2, 3, 1), direction_ratio=[-1, 0, 3])) == 0 assert pl6.angle_between(pl3) == pi/2 assert pl6.angle_between(pl6) == 0 assert pl6.angle_between(pl4) == 0 assert pl7.angle_between(Line3D(Point3D(2, 3, 5), Point3D(2, 4, 6))) == \ -asin(sqrt(3)/6) assert pl6.angle_between(Ray3D(Point3D(2, 4, 1), Point3D(6, 5, 3))) == \ asin(sqrt(7)/3) assert pl7.angle_between(Segment3D(Point3D(5, 6, 1), Point3D(1, 2, 4))) == \ asin(7*sqrt(246)/246) assert are_coplanar(l1, l2, l3) is False assert are_coplanar(l1) is False assert are_coplanar(Point3D(2, 7, 2), Point3D(0, 0, 2), Point3D(1, 1, 2), Point3D(1, 2, 2)) assert are_coplanar(Plane(p1, p2, p3), Plane(p1, p3, p2)) assert Plane.are_concurrent(pl3, pl4, pl5) is False assert Plane.are_concurrent(pl6) is False raises(ValueError, lambda: Plane.are_concurrent(Point3D(0, 0, 0))) raises(ValueError, lambda: Plane((1, 2, 3), normal_vector=(0, 0, 0))) assert pl3.parallel_plane(Point3D(1, 2, 5)) == Plane(Point3D(1, 2, 5), \ normal_vector=(1, -2, 1)) # perpendicular_plane p = Plane((0, 0, 0), (1, 0, 0)) # default assert p.perpendicular_plane() == Plane(Point3D(0, 0, 0), (0, 1, 0)) # 1 pt assert p.perpendicular_plane(Point3D(1, 0, 1)) == \ Plane(Point3D(1, 0, 1), (0, 1, 0)) # pts as tuples assert p.perpendicular_plane((1, 0, 1), (1, 1, 1)) == \ Plane(Point3D(1, 0, 1), (0, 0, -1)) # more than two planes raises(ValueError, lambda: p.perpendicular_plane((1, 0, 1), (1, 1, 1), (1, 1, 0))) a, b = Point3D(0, 0, 0), Point3D(0, 1, 0) Z = (0, 0, 1) p = Plane(a, normal_vector=Z) # case 4 assert p.perpendicular_plane(a, b) == Plane(a, (1, 0, 0)) n = Point3D(*Z) # case 1 assert p.perpendicular_plane(a, n) == Plane(a, (-1, 0, 0)) # case 2 assert Plane(a, normal_vector=b.args).perpendicular_plane(a, a + b) == \ Plane(Point3D(0, 0, 0), (1, 0, 0)) # case 1&3 assert Plane(b, normal_vector=Z).perpendicular_plane(b, b + n) == \ Plane(Point3D(0, 1, 0), (-1, 0, 0)) # case 2&3 assert Plane(b, normal_vector=b.args).perpendicular_plane(n, n + b) == \ Plane(Point3D(0, 0, 1), (1, 0, 0)) p = Plane(a, normal_vector=(0, 0, 1)) assert p.perpendicular_plane() == Plane(a, normal_vector=(1, 0, 0)) assert pl6.intersection(pl6) == [pl6] assert pl4.intersection(pl4.p1) == [pl4.p1] assert pl3.intersection(pl6) == [ Line3D(Point3D(8, 4, 0), Point3D(2, 4, 6))] assert pl3.intersection(Line3D(Point3D(1,2,4), Point3D(4,4,2))) == [ Point3D(2, Rational(8, 3), Rational(10, 3))] assert pl3.intersection(Plane(Point3D(6, 0, 0), normal_vector=(2, -5, 3)) ) == [Line3D(Point3D(-24, -12, 0), Point3D(-25, -13, -1))] assert pl6.intersection(Ray3D(Point3D(2, 3, 1), Point3D(1, 3, 4))) == [ Point3D(-1, 3, 10)] assert pl6.intersection(Segment3D(Point3D(2, 3, 1), Point3D(1, 3, 4))) == [] assert pl7.intersection(Line(Point(2, 3), Point(4, 2))) == [ Point3D(Rational(13, 2), Rational(3, 4), 0)] r = Ray(Point(2, 3), Point(4, 2)) assert Plane((1,2,0), normal_vector=(0,0,1)).intersection(r) == [ Ray3D(Point(2, 3), Point(4, 2))] assert pl9.intersection(pl8) == [Line3D(Point3D(0, 0, 0), Point3D(12, 0, 0))] assert pl10.intersection(pl11) == [Line3D(Point3D(0, 0, 1), Point3D(0, 2, 1))] assert pl4.intersection(pl8) == [Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))] assert pl11.intersection(pl8) == [] assert pl9.intersection(pl11) == [Line3D(Point3D(0, 0, 1), Point3D(12, 0, 1))] assert pl9.intersection(pl4) == [Line3D(Point3D(0, 0, 0), Point3D(12, 0, -12))] assert pl3.random_point() in pl3 assert pl3.random_point(seed=1) in pl3 # test geometrical entity using equals assert pl4.intersection(pl4.p1)[0].equals(pl4.p1) assert pl3.intersection(pl6)[0].equals(Line3D(Point3D(8, 4, 0), Point3D(2, 4, 6))) pl8 = Plane((1, 2, 0), normal_vector=(0, 0, 1)) assert pl8.intersection(Line3D(p1, (1, 12, 0)))[0].equals(Line((0, 0, 0), (0.1, 1.2, 0))) assert pl8.intersection(Ray3D(p1, (1, 12, 0)))[0].equals(Ray((0, 0, 0), (1, 12, 0))) assert pl8.intersection(Segment3D(p1, (21, 1, 0)))[0].equals(Segment3D(p1, (21, 1, 0))) assert pl8.intersection(Plane(p1, normal_vector=(0, 0, 112)))[0].equals(pl8) assert pl8.intersection(Plane(p1, normal_vector=(0, 12, 0)))[0].equals( Line3D(p1, direction_ratio=(112 * pi, 0, 0))) assert pl8.intersection(Plane(p1, normal_vector=(11, 0, 1)))[0].equals( Line3D(p1, direction_ratio=(0, -11, 0))) assert pl8.intersection(Plane(p1, normal_vector=(1, 0, 11)))[0].equals( Line3D(p1, direction_ratio=(0, 11, 0))) assert pl8.intersection(Plane(p1, normal_vector=(-1, -1, -11)))[0].equals( Line3D(p1, direction_ratio=(1, -1, 0))) assert pl3.random_point() in pl3 assert len(pl8.intersection(Ray3D(Point3D(0, 2, 3), Point3D(1, 0, 3)))) == 0 # check if two plane are equals assert pl6.intersection(pl6)[0].equals(pl6) assert pl8.equals(Plane(p1, normal_vector=(0, 12, 0))) is False assert pl8.equals(pl8) assert pl8.equals(Plane(p1, normal_vector=(0, 0, -12))) assert pl8.equals(Plane(p1, normal_vector=(0, 0, -12*sqrt(3)))) assert pl8.equals(p1) is False # issue 8570 l2 = Line3D(Point3D(Rational(50000004459633, 5000000000000), Rational(-891926590718643, 1000000000000000), Rational(231800966893633, 100000000000000)), Point3D(Rational(50000004459633, 50000000000000), Rational(-222981647679771, 250000000000000), Rational(231800966893633, 100000000000000))) p2 = Plane(Point3D(Rational(402775636372767, 100000000000000), Rational(-97224357654973, 100000000000000), Rational(216793600814789, 100000000000000)), (-S('9.00000087501922'), -S('4.81170658872543e-13'), S('0.0'))) assert str([i.n(2) for i in p2.intersection(l2)]) == \ '[Point3D(4.0, -0.89, 2.3)]' def test_dimension_normalization(): A = Plane(Point3D(1, 1, 2), normal_vector=(1, 1, 1)) b = Point(1, 1) assert A.projection(b) == Point(Rational(5, 3), Rational(5, 3), Rational(2, 3)) a, b = Point(0, 0), Point3D(0, 1) Z = (0, 0, 1) p = Plane(a, normal_vector=Z) assert p.perpendicular_plane(a, b) == Plane(Point3D(0, 0, 0), (1, 0, 0)) assert Plane((1, 2, 1), (2, 1, 0), (3, 1, 2) ).intersection((2, 1)) == [Point(2, 1, 0)] def test_parameter_value(): t, u, v = symbols("t, u v") p1, p2, p3 = Point(0, 0, 0), Point(0, 0, 1), Point(0, 1, 0) p = Plane(p1, p2, p3) assert p.parameter_value((0, -3, 2), t) == {t: asin(2*sqrt(13)/13)} assert p.parameter_value((0, -3, 2), u, v) == {u: 3, v: 2} assert p.parameter_value(p1, t) == p1 raises(ValueError, lambda: p.parameter_value((1, 0, 0), t)) raises(ValueError, lambda: p.parameter_value(Line(Point(0, 0), Point(1, 1)), t)) raises(ValueError, lambda: p.parameter_value((0, -3, 2), t, 1))
293f0b1d941134a5d8731b76a88ed194da1e5ffed1fb8442b2b5999b92764bfa
from sympy.core.numbers import (Float, Rational, oo, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, cos, sin) from sympy.simplify.simplify import simplify from sympy.functions.elementary.trigonometric import tan from sympy.geometry import (Circle, GeometryError, Line, Point, Ray, Segment, Triangle, intersection, Point3D, Line3D, Ray3D, Segment3D, Point2D, Line2D) from sympy.geometry.line import Undecidable from sympy.geometry.polygon import _asa as asa from sympy.utilities.iterables import cartes from sympy.testing.pytest import raises, warns x = Symbol('x', real=True) y = Symbol('y', real=True) z = Symbol('z', real=True) k = Symbol('k', real=True) x1 = Symbol('x1', real=True) y1 = Symbol('y1', real=True) t = Symbol('t', real=True) a, b = symbols('a,b', real=True) m = symbols('m', real=True) def test_object_from_equation(): from sympy.abc import x, y, a, b assert Line(3*x + y + 18) == Line2D(Point2D(0, -18), Point2D(1, -21)) assert Line(3*x + 5 * y + 1) == Line2D( Point2D(0, Rational(-1, 5)), Point2D(1, Rational(-4, 5))) assert Line(3*a + b + 18, x="a", y="b") == Line2D( Point2D(0, -18), Point2D(1, -21)) assert Line(3*x + y) == Line2D(Point2D(0, 0), Point2D(1, -3)) assert Line(x + y) == Line2D(Point2D(0, 0), Point2D(1, -1)) assert Line(Eq(3*a + b, -18), x="a", y=b) == Line2D( Point2D(0, -18), Point2D(1, -21)) # issue 22361 assert Line(x - 1) == Line2D(Point2D(1, 0), Point2D(1, 1)) assert Line(2*x - 2, y=x) == Line2D(Point2D(0, 1), Point2D(1, 1)) assert Line(y) == Line2D(Point2D(0, 0), Point2D(1, 0)) assert Line(2*y, x=y) == Line2D(Point2D(0, 0), Point2D(0, 1)) assert Line(y, x=y) == Line2D(Point2D(0, 0), Point2D(0, 1)) raises(ValueError, lambda: Line(x / y)) raises(ValueError, lambda: Line(a / b, x='a', y='b')) raises(ValueError, lambda: Line(y / x)) raises(ValueError, lambda: Line(b / a, x='a', y='b')) raises(ValueError, lambda: Line((x + 1)**2 + y)) def feq(a, b): """Test if two floating point values are 'equal'.""" t_float = Float("1.0E-10") return -t_float < a - b < t_float def test_angle_between(): a = Point(1, 2, 3, 4) b = a.orthogonal_direction o = a.origin assert feq(Line.angle_between(Line(Point(0, 0), Point(1, 1)), Line(Point(0, 0), Point(5, 0))).evalf(), pi.evalf() / 4) assert Line(a, o).angle_between(Line(b, o)) == pi / 2 assert Line3D.angle_between(Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1)), Line3D(Point3D(0, 0, 0), Point3D(5, 0, 0))) == acos(sqrt(3) / 3) def test_closing_angle(): a = Ray((0, 0), angle=0) b = Ray((1, 2), angle=pi/2) assert a.closing_angle(b) == -pi/2 assert b.closing_angle(a) == pi/2 assert a.closing_angle(a) == 0 def test_smallest_angle(): a = Line(Point(1, 1), Point(1, 2)) b = Line(Point(1, 1),Point(2, 3)) assert a.smallest_angle_between(b) == acos(2*sqrt(5)/5) def test_svg(): a = Line(Point(1, 1),Point(1, 2)) assert a._svg() == '<path fill-rule="evenodd" fill="#66cc99" stroke="#555555" stroke-width="2.0" opacity="0.6" d="M 1.00000000000000,1.00000000000000 L 1.00000000000000,2.00000000000000" marker-start="url(#markerReverseArrow)" marker-end="url(#markerArrow)"/>' a = Segment(Point(1, 0),Point(1, 1)) assert a._svg() == '<path fill-rule="evenodd" fill="#66cc99" stroke="#555555" stroke-width="2.0" opacity="0.6" d="M 1.00000000000000,0 L 1.00000000000000,1.00000000000000" />' a = Ray(Point(2, 3), Point(3, 5)) assert a._svg() == '<path fill-rule="evenodd" fill="#66cc99" stroke="#555555" stroke-width="2.0" opacity="0.6" d="M 2.00000000000000,3.00000000000000 L 3.00000000000000,5.00000000000000" marker-start="url(#markerCircle)" marker-end="url(#markerArrow)"/>' def test_arbitrary_point(): l1 = Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1)) l2 = Line(Point(x1, x1), Point(y1, y1)) assert l2.arbitrary_point() in l2 assert Ray((1, 1), angle=pi / 4).arbitrary_point() == \ Point(t + 1, t + 1) assert Segment((1, 1), (2, 3)).arbitrary_point() == Point(1 + t, 1 + 2 * t) assert l1.perpendicular_segment(l1.arbitrary_point()) == l1.arbitrary_point() assert Ray3D((1, 1, 1), direction_ratio=[1, 2, 3]).arbitrary_point() == \ Point3D(t + 1, 2 * t + 1, 3 * t + 1) assert Segment3D(Point3D(0, 0, 0), Point3D(1, 1, 1)).midpoint == \ Point3D(S.Half, S.Half, S.Half) assert Segment3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1)).length == sqrt(3) * sqrt((x1 - y1) ** 2) assert Segment3D((1, 1, 1), (2, 3, 4)).arbitrary_point() == \ Point3D(t + 1, 2 * t + 1, 3 * t + 1) raises(ValueError, (lambda: Line((x, 1), (2, 3)).arbitrary_point(x))) def test_are_concurrent_2d(): l1 = Line(Point(0, 0), Point(1, 1)) l2 = Line(Point(x1, x1), Point(x1, 1 + x1)) assert Line.are_concurrent(l1) is False assert Line.are_concurrent(l1, l2) assert Line.are_concurrent(l1, l1, l1, l2) assert Line.are_concurrent(l1, l2, Line(Point(5, x1), Point(Rational(-3, 5), x1))) assert Line.are_concurrent(l1, Line(Point(0, 0), Point(-x1, x1)), l2) is False def test_are_concurrent_3d(): p1 = Point3D(0, 0, 0) l1 = Line(p1, Point3D(1, 1, 1)) parallel_1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)) parallel_2 = Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0)) assert Line3D.are_concurrent(l1) is False assert Line3D.are_concurrent(l1, Line(Point3D(x1, x1, x1), Point3D(y1, y1, y1))) is False assert Line3D.are_concurrent(l1, Line3D(p1, Point3D(x1, x1, x1)), Line(Point3D(x1, x1, x1), Point3D(x1, 1 + x1, 1))) is True assert Line3D.are_concurrent(parallel_1, parallel_2) is False def test_arguments(): """Functions accepting `Point` objects in `geometry` should also accept tuples, lists, and generators and automatically convert them to points.""" from sympy.utilities.iterables import subsets singles2d = ((1, 2), [1, 3], Point(1, 5)) doubles2d = subsets(singles2d, 2) l2d = Line(Point2D(1, 2), Point2D(2, 3)) singles3d = ((1, 2, 3), [1, 2, 4], Point(1, 2, 6)) doubles3d = subsets(singles3d, 2) l3d = Line(Point3D(1, 2, 3), Point3D(1, 1, 2)) singles4d = ((1, 2, 3, 4), [1, 2, 3, 5], Point(1, 2, 3, 7)) doubles4d = subsets(singles4d, 2) l4d = Line(Point(1, 2, 3, 4), Point(2, 2, 2, 2)) # test 2D test_single = ['contains', 'distance', 'equals', 'parallel_line', 'perpendicular_line', 'perpendicular_segment', 'projection', 'intersection'] for p in doubles2d: Line2D(*p) for func in test_single: for p in singles2d: getattr(l2d, func)(p) # test 3D for p in doubles3d: Line3D(*p) for func in test_single: for p in singles3d: getattr(l3d, func)(p) # test 4D for p in doubles4d: Line(*p) for func in test_single: for p in singles4d: getattr(l4d, func)(p) def test_basic_properties_2d(): p1 = Point(0, 0) p2 = Point(1, 1) p10 = Point(2000, 2000) p_r3 = Ray(p1, p2).random_point() p_r4 = Ray(p2, p1).random_point() l1 = Line(p1, p2) l3 = Line(Point(x1, x1), Point(x1, 1 + x1)) l4 = Line(p1, Point(1, 0)) r1 = Ray(p1, Point(0, 1)) r2 = Ray(Point(0, 1), p1) s1 = Segment(p1, p10) p_s1 = s1.random_point() assert Line((1, 1), slope=1) == Line((1, 1), (2, 2)) assert Line((1, 1), slope=oo) == Line((1, 1), (1, 2)) assert Line((1, 1), slope=oo).bounds == (1, 1, 1, 2) assert Line((1, 1), slope=-oo) == Line((1, 1), (1, 2)) assert Line(p1, p2).scale(2, 1) == Line(p1, Point(2, 1)) assert Line(p1, p2) == Line(p1, p2) assert Line(p1, p2) != Line(p2, p1) assert l1 != Line(Point(x1, x1), Point(y1, y1)) assert l1 != l3 assert Line(p1, p10) != Line(p10, p1) assert Line(p1, p10) != p1 assert p1 in l1 # is p1 on the line l1? assert p1 not in l3 assert s1 in Line(p1, p10) assert Ray(Point(0, 0), Point(0, 1)) in Ray(Point(0, 0), Point(0, 2)) assert Ray(Point(0, 0), Point(0, 2)) in Ray(Point(0, 0), Point(0, 1)) assert Ray(Point(0, 0), Point(0, 2)).xdirection == S.Zero assert Ray(Point(0, 0), Point(1, 2)).xdirection == S.Infinity assert Ray(Point(0, 0), Point(-1, 2)).xdirection == S.NegativeInfinity assert Ray(Point(0, 0), Point(2, 0)).ydirection == S.Zero assert Ray(Point(0, 0), Point(2, 2)).ydirection == S.Infinity assert Ray(Point(0, 0), Point(2, -2)).ydirection == S.NegativeInfinity assert (r1 in s1) is False assert Segment(p1, p2) in s1 assert Ray(Point(x1, x1), Point(x1, 1 + x1)) != Ray(p1, Point(-1, 5)) assert Segment(p1, p2).midpoint == Point(S.Half, S.Half) assert Segment(p1, Point(-x1, x1)).length == sqrt(2 * (x1 ** 2)) assert l1.slope == 1 assert l3.slope is oo assert l4.slope == 0 assert Line(p1, Point(0, 1)).slope is oo assert Line(r1.source, r1.random_point()).slope == r1.slope assert Line(r2.source, r2.random_point()).slope == r2.slope assert Segment(Point(0, -1), Segment(p1, Point(0, 1)).random_point()).slope == Segment(p1, Point(0, 1)).slope assert l4.coefficients == (0, 1, 0) assert Line((-x, x), (-x + 1, x - 1)).coefficients == (1, 1, 0) assert Line(p1, Point(0, 1)).coefficients == (1, 0, 0) # issue 7963 r = Ray((0, 0), angle=x) assert r.subs(x, 3 * pi / 4) == Ray((0, 0), (-1, 1)) assert r.subs(x, 5 * pi / 4) == Ray((0, 0), (-1, -1)) assert r.subs(x, -pi / 4) == Ray((0, 0), (1, -1)) assert r.subs(x, pi / 2) == Ray((0, 0), (0, 1)) assert r.subs(x, -pi / 2) == Ray((0, 0), (0, -1)) for ind in range(0, 5): assert l3.random_point() in l3 assert p_r3.x >= p1.x and p_r3.y >= p1.y assert p_r4.x <= p2.x and p_r4.y <= p2.y assert p1.x <= p_s1.x <= p10.x and p1.y <= p_s1.y <= p10.y assert hash(s1) != hash(Segment(p10, p1)) assert s1.plot_interval() == [t, 0, 1] assert Line(p1, p10).plot_interval() == [t, -5, 5] assert Ray((0, 0), angle=pi / 4).plot_interval() == [t, 0, 10] def test_basic_properties_3d(): p1 = Point3D(0, 0, 0) p2 = Point3D(1, 1, 1) p3 = Point3D(x1, x1, x1) p5 = Point3D(x1, 1 + x1, 1) l1 = Line3D(p1, p2) l3 = Line3D(p3, p5) r1 = Ray3D(p1, Point3D(-1, 5, 0)) r3 = Ray3D(p1, p2) s1 = Segment3D(p1, p2) assert Line3D((1, 1, 1), direction_ratio=[2, 3, 4]) == Line3D(Point3D(1, 1, 1), Point3D(3, 4, 5)) assert Line3D((1, 1, 1), direction_ratio=[1, 5, 7]) == Line3D(Point3D(1, 1, 1), Point3D(2, 6, 8)) assert Line3D((1, 1, 1), direction_ratio=[1, 2, 3]) == Line3D(Point3D(1, 1, 1), Point3D(2, 3, 4)) assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).direction_cosine == [1, 0, 0] assert Line3D(Line3D(p1, Point3D(0, 1, 0))) == Line3D(p1, Point3D(0, 1, 0)) assert Ray3D(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0))) == Ray3D(p1, Point3D(1, 0, 0)) assert Line3D(p1, p2) != Line3D(p2, p1) assert l1 != l3 assert l1 != Line3D(p3, Point3D(y1, y1, y1)) assert r3 != r1 assert Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 1)) in Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)) assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)) in Ray3D(Point3D(0, 0, 0), Point3D(1, 1, 1)) assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).xdirection == S.Infinity assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).ydirection == S.Infinity assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 2)).zdirection == S.Infinity assert Ray3D(Point3D(0, 0, 0), Point3D(-2, 2, 2)).xdirection == S.NegativeInfinity assert Ray3D(Point3D(0, 0, 0), Point3D(2, -2, 2)).ydirection == S.NegativeInfinity assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, -2)).zdirection == S.NegativeInfinity assert Ray3D(Point3D(0, 0, 0), Point3D(0, 2, 2)).xdirection == S.Zero assert Ray3D(Point3D(0, 0, 0), Point3D(2, 0, 2)).ydirection == S.Zero assert Ray3D(Point3D(0, 0, 0), Point3D(2, 2, 0)).zdirection == S.Zero assert p1 in l1 assert p1 not in l3 assert l1.direction_ratio == [1, 1, 1] assert s1.midpoint == Point3D(S.Half, S.Half, S.Half) # Test zdirection assert Ray3D(p1, Point3D(0, 0, -1)).zdirection is S.NegativeInfinity def test_contains(): p1 = Point(0, 0) r = Ray(p1, Point(4, 4)) r1 = Ray3D(p1, Point3D(0, 0, -1)) r2 = Ray3D(p1, Point3D(0, 1, 0)) r3 = Ray3D(p1, Point3D(0, 0, 1)) l = Line(Point(0, 1), Point(3, 4)) # Segment contains assert Point(0, (a + b) / 2) in Segment((0, a), (0, b)) assert Point((a + b) / 2, 0) in Segment((a, 0), (b, 0)) assert Point3D(0, 1, 0) in Segment3D((0, 1, 0), (0, 1, 0)) assert Point3D(1, 0, 0) in Segment3D((1, 0, 0), (1, 0, 0)) assert Segment3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).contains([]) is True assert Segment3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).contains( Segment3D(Point3D(2, 2, 2), Point3D(3, 2, 2))) is False # Line contains assert l.contains(Point(0, 1)) is True assert l.contains((0, 1)) is True assert l.contains((0, 0)) is False # Ray contains assert r.contains(p1) is True assert r.contains((1, 1)) is True assert r.contains((1, 3)) is False assert r.contains(Segment((1, 1), (2, 2))) is True assert r.contains(Segment((1, 2), (2, 5))) is False assert r.contains(Ray((2, 2), (3, 3))) is True assert r.contains(Ray((2, 2), (3, 5))) is False assert r1.contains(Segment3D(p1, Point3D(0, 0, -10))) is True assert r1.contains(Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))) is False assert r2.contains(Point3D(0, 0, 0)) is True assert r3.contains(Point3D(0, 0, 0)) is True assert Ray3D(Point3D(1, 1, 1), Point3D(1, 0, 0)).contains([]) is False assert Line3D((0, 0, 0), (x, y, z)).contains((2 * x, 2 * y, 2 * z)) with warns(UserWarning): assert Line3D(p1, Point3D(0, 1, 0)).contains(Point(1.0, 1.0)) is False with warns(UserWarning): assert r3.contains(Point(1.0, 1.0)) is False def test_contains_nonreal_symbols(): u, v, w, z = symbols('u, v, w, z') l = Segment(Point(u, w), Point(v, z)) p = Point(u*Rational(2, 3) + v/3, w*Rational(2, 3) + z/3) assert l.contains(p) def test_distance_2d(): p1 = Point(0, 0) p2 = Point(1, 1) half = S.Half s1 = Segment(Point(0, 0), Point(1, 1)) s2 = Segment(Point(half, half), Point(1, 0)) r = Ray(p1, p2) assert s1.distance(Point(0, 0)) == 0 assert s1.distance((0, 0)) == 0 assert s2.distance(Point(0, 0)) == 2 ** half / 2 assert s2.distance(Point(Rational(3) / 2, Rational(3) / 2)) == 2 ** half assert Line(p1, p2).distance(Point(-1, 1)) == sqrt(2) assert Line(p1, p2).distance(Point(1, -1)) == sqrt(2) assert Line(p1, p2).distance(Point(2, 2)) == 0 assert Line(p1, p2).distance((-1, 1)) == sqrt(2) assert Line((0, 0), (0, 1)).distance(p1) == 0 assert Line((0, 0), (0, 1)).distance(p2) == 1 assert Line((0, 0), (1, 0)).distance(p1) == 0 assert Line((0, 0), (1, 0)).distance(p2) == 1 assert r.distance(Point(-1, -1)) == sqrt(2) assert r.distance(Point(1, 1)) == 0 assert r.distance(Point(-1, 1)) == sqrt(2) assert Ray((1, 1), (2, 2)).distance(Point(1.5, 3)) == 3 * sqrt(2) / 4 assert r.distance((1, 1)) == 0 def test_dimension_normalization(): with warns(UserWarning): assert Ray((1, 1), (2, 1, 2)) == Ray((1, 1, 0), (2, 1, 2)) def test_distance_3d(): p1, p2 = Point3D(0, 0, 0), Point3D(1, 1, 1) p3 = Point3D(Rational(3) / 2, Rational(3) / 2, Rational(3) / 2) s1 = Segment3D(Point3D(0, 0, 0), Point3D(1, 1, 1)) s2 = Segment3D(Point3D(S.Half, S.Half, S.Half), Point3D(1, 0, 1)) r = Ray3D(p1, p2) assert s1.distance(p1) == 0 assert s2.distance(p1) == sqrt(3) / 2 assert s2.distance(p3) == 2 * sqrt(6) / 3 assert s1.distance((0, 0, 0)) == 0 assert s2.distance((0, 0, 0)) == sqrt(3) / 2 assert s1.distance(p1) == 0 assert s2.distance(p1) == sqrt(3) / 2 assert s2.distance(p3) == 2 * sqrt(6) / 3 assert s1.distance((0, 0, 0)) == 0 assert s2.distance((0, 0, 0)) == sqrt(3) / 2 # Line to point assert Line3D(p1, p2).distance(Point3D(-1, 1, 1)) == 2 * sqrt(6) / 3 assert Line3D(p1, p2).distance(Point3D(1, -1, 1)) == 2 * sqrt(6) / 3 assert Line3D(p1, p2).distance(Point3D(2, 2, 2)) == 0 assert Line3D(p1, p2).distance((2, 2, 2)) == 0 assert Line3D(p1, p2).distance((1, -1, 1)) == 2 * sqrt(6) / 3 assert Line3D((0, 0, 0), (0, 1, 0)).distance(p1) == 0 assert Line3D((0, 0, 0), (0, 1, 0)).distance(p2) == sqrt(2) assert Line3D((0, 0, 0), (1, 0, 0)).distance(p1) == 0 assert Line3D((0, 0, 0), (1, 0, 0)).distance(p2) == sqrt(2) # Ray to point assert r.distance(Point3D(-1, -1, -1)) == sqrt(3) assert r.distance(Point3D(1, 1, 1)) == 0 assert r.distance((-1, -1, -1)) == sqrt(3) assert r.distance((1, 1, 1)) == 0 assert Ray3D((0, 0, 0), (1, 1, 2)).distance((-1, -1, 2)) == 4 * sqrt(3) / 3 assert Ray3D((1, 1, 1), (2, 2, 2)).distance(Point3D(1.5, -3, -1)) == Rational(9) / 2 assert Ray3D((1, 1, 1), (2, 2, 2)).distance(Point3D(1.5, 3, 1)) == sqrt(78) / 6 def test_equals(): p1 = Point(0, 0) p2 = Point(1, 1) l1 = Line(p1, p2) l2 = Line((0, 5), slope=m) l3 = Line(Point(x1, x1), Point(x1, 1 + x1)) assert l1.perpendicular_line(p1.args).equals(Line(Point(0, 0), Point(1, -1))) assert l1.perpendicular_line(p1).equals(Line(Point(0, 0), Point(1, -1))) assert Line(Point(x1, x1), Point(y1, y1)).parallel_line(Point(-x1, x1)). \ equals(Line(Point(-x1, x1), Point(-y1, 2 * x1 - y1))) assert l3.parallel_line(p1.args).equals(Line(Point(0, 0), Point(0, -1))) assert l3.parallel_line(p1).equals(Line(Point(0, 0), Point(0, -1))) assert (l2.distance(Point(2, 3)) - 2 * abs(m + 1) / sqrt(m ** 2 + 1)).equals(0) assert Line3D(p1, Point3D(0, 1, 0)).equals(Point(1.0, 1.0)) is False assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).equals(Line3D(Point3D(-5, 0, 0), Point3D(-1, 0, 0))) is True assert Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)).equals(Line3D(p1, Point3D(0, 1, 0))) is False assert Ray3D(p1, Point3D(0, 0, -1)).equals(Point(1.0, 1.0)) is False assert Ray3D(p1, Point3D(0, 0, -1)).equals(Ray3D(p1, Point3D(0, 0, -1))) is True assert Line3D((0, 0), (t, t)).perpendicular_line(Point(0, 1, 0)).equals( Line3D(Point3D(0, 1, 0), Point3D(S.Half, S.Half, 0))) assert Line3D((0, 0), (t, t)).perpendicular_segment(Point(0, 1, 0)).equals(Segment3D((0, 1), (S.Half, S.Half))) assert Line3D(p1, Point3D(0, 1, 0)).equals(Point(1.0, 1.0)) is False def test_equation(): p1 = Point(0, 0) p2 = Point(1, 1) l1 = Line(p1, p2) l3 = Line(Point(x1, x1), Point(x1, 1 + x1)) assert simplify(l1.equation()) in (x - y, y - x) assert simplify(l3.equation()) in (x - x1, x1 - x) assert simplify(l1.equation()) in (x - y, y - x) assert simplify(l3.equation()) in (x - x1, x1 - x) assert Line(p1, Point(1, 0)).equation(x=x, y=y) == y assert Line(p1, Point(0, 1)).equation() == x assert Line(Point(2, 0), Point(2, 1)).equation() == x - 2 assert Line(p2, Point(2, 1)).equation() == y - 1 assert Line3D(Point(x1, x1, x1), Point(y1, y1, y1) ).equation() == (-x + y, -x + z) assert Line3D(Point(1, 2, 3), Point(2, 3, 4) ).equation() == (-x + y - 1, -x + z - 2) assert Line3D(Point(1, 2, 3), Point(1, 3, 4) ).equation() == (x - 1, -y + z - 1) assert Line3D(Point(1, 2, 3), Point(2, 2, 4) ).equation() == (y - 2, -x + z - 2) assert Line3D(Point(1, 2, 3), Point(2, 3, 3) ).equation() == (-x + y - 1, z - 3) assert Line3D(Point(1, 2, 3), Point(1, 2, 4) ).equation() == (x - 1, y - 2) assert Line3D(Point(1, 2, 3), Point(1, 3, 3) ).equation() == (x - 1, z - 3) assert Line3D(Point(1, 2, 3), Point(2, 2, 3) ).equation() == (y - 2, z - 3) def test_intersection_2d(): p1 = Point(0, 0) p2 = Point(1, 1) p3 = Point(x1, x1) p4 = Point(y1, y1) l1 = Line(p1, p2) l3 = Line(Point(0, 0), Point(3, 4)) r1 = Ray(Point(1, 1), Point(2, 2)) r2 = Ray(Point(0, 0), Point(3, 4)) r4 = Ray(p1, p2) r6 = Ray(Point(0, 1), Point(1, 2)) r7 = Ray(Point(0.5, 0.5), Point(1, 1)) s1 = Segment(p1, p2) s2 = Segment(Point(0.25, 0.25), Point(0.5, 0.5)) s3 = Segment(Point(0, 0), Point(3, 4)) assert intersection(l1, p1) == [p1] assert intersection(l1, Point(x1, 1 + x1)) == [] assert intersection(l1, Line(p3, p4)) in [[l1], [Line(p3, p4)]] assert intersection(l1, l1.parallel_line(Point(x1, 1 + x1))) == [] assert intersection(l3, l3) == [l3] assert intersection(l3, r2) == [r2] assert intersection(l3, s3) == [s3] assert intersection(s3, l3) == [s3] assert intersection(Segment(Point(-10, 10), Point(10, 10)), Segment(Point(-5, -5), Point(-5, 5))) == [] assert intersection(r2, l3) == [r2] assert intersection(r1, Ray(Point(2, 2), Point(0, 0))) == [Segment(Point(1, 1), Point(2, 2))] assert intersection(r1, Ray(Point(1, 1), Point(-1, -1))) == [Point(1, 1)] assert intersection(r1, Segment(Point(0, 0), Point(2, 2))) == [Segment(Point(1, 1), Point(2, 2))] assert r4.intersection(s2) == [s2] assert r4.intersection(Segment(Point(2, 3), Point(3, 4))) == [] assert r4.intersection(Segment(Point(-1, -1), Point(0.5, 0.5))) == [Segment(p1, Point(0.5, 0.5))] assert r4.intersection(Ray(p2, p1)) == [s1] assert Ray(p2, p1).intersection(r6) == [] assert r4.intersection(r7) == r7.intersection(r4) == [r7] assert Ray3D((0, 0), (3, 0)).intersection(Ray3D((1, 0), (3, 0))) == [Ray3D((1, 0), (3, 0))] assert Ray3D((1, 0), (3, 0)).intersection(Ray3D((0, 0), (3, 0))) == [Ray3D((1, 0), (3, 0))] assert Ray(Point(0, 0), Point(0, 4)).intersection(Ray(Point(0, 1), Point(0, -1))) == \ [Segment(Point(0, 0), Point(0, 1))] assert Segment3D((0, 0), (3, 0)).intersection( Segment3D((1, 0), (2, 0))) == [Segment3D((1, 0), (2, 0))] assert Segment3D((1, 0), (2, 0)).intersection( Segment3D((0, 0), (3, 0))) == [Segment3D((1, 0), (2, 0))] assert Segment3D((0, 0), (3, 0)).intersection( Segment3D((3, 0), (4, 0))) == [Point3D((3, 0))] assert Segment3D((0, 0), (3, 0)).intersection( Segment3D((2, 0), (5, 0))) == [Segment3D((2, 0), (3, 0))] assert Segment3D((0, 0), (3, 0)).intersection( Segment3D((-2, 0), (1, 0))) == [Segment3D((0, 0), (1, 0))] assert Segment3D((0, 0), (3, 0)).intersection( Segment3D((-2, 0), (0, 0))) == [Point3D(0, 0)] assert s1.intersection(Segment(Point(1, 1), Point(2, 2))) == [Point(1, 1)] assert s1.intersection(Segment(Point(0.5, 0.5), Point(1.5, 1.5))) == [Segment(Point(0.5, 0.5), p2)] assert s1.intersection(Segment(Point(4, 4), Point(5, 5))) == [] assert s1.intersection(Segment(Point(-1, -1), p1)) == [p1] assert s1.intersection(Segment(Point(-1, -1), Point(0.5, 0.5))) == [Segment(p1, Point(0.5, 0.5))] assert s1.intersection(Line(Point(1, 0), Point(2, 1))) == [] assert s1.intersection(s2) == [s2] assert s2.intersection(s1) == [s2] assert asa(120, 8, 52) == \ Triangle( Point(0, 0), Point(8, 0), Point(-4 * cos(19 * pi / 90) / sin(2 * pi / 45), 4 * sqrt(3) * cos(19 * pi / 90) / sin(2 * pi / 45))) assert Line((0, 0), (1, 1)).intersection(Ray((1, 0), (1, 2))) == [Point(1, 1)] assert Line((0, 0), (1, 1)).intersection(Segment((1, 0), (1, 2))) == [Point(1, 1)] assert Ray((0, 0), (1, 1)).intersection(Ray((1, 0), (1, 2))) == [Point(1, 1)] assert Ray((0, 0), (1, 1)).intersection(Segment((1, 0), (1, 2))) == [Point(1, 1)] assert Ray((0, 0), (10, 10)).contains(Segment((1, 1), (2, 2))) is True assert Segment((1, 1), (2, 2)) in Line((0, 0), (10, 10)) assert s1.intersection(Ray((1, 1), (4, 4))) == [Point(1, 1)] # This test is disabled because it hangs after rref changes which simplify # intermediate results and return a different representation from when the # test was written. # # 16628 - this should be fast # p0 = Point2D(Rational(249, 5), Rational(497999, 10000)) # p1 = Point2D((-58977084786*sqrt(405639795226) + 2030690077184193 + # 20112207807*sqrt(630547164901) + 99600*sqrt(255775022850776494562626)) # /(2000*sqrt(255775022850776494562626) + 1991998000*sqrt(405639795226) # + 1991998000*sqrt(630547164901) + 1622561172902000), # (-498000*sqrt(255775022850776494562626) - 995999*sqrt(630547164901) + # 90004251917891999 + # 496005510002*sqrt(405639795226))/(10000*sqrt(255775022850776494562626) # + 9959990000*sqrt(405639795226) + 9959990000*sqrt(630547164901) + # 8112805864510000)) # p2 = Point2D(Rational(497, 10), Rational(-497, 10)) # p3 = Point2D(Rational(-497, 10), Rational(-497, 10)) # l = Line(p0, p1) # s = Segment(p2, p3) # n = (-52673223862*sqrt(405639795226) - 15764156209307469 - # 9803028531*sqrt(630547164901) + # 33200*sqrt(255775022850776494562626)) # d = sqrt(405639795226) + 315274080450 + 498000*sqrt( # 630547164901) + sqrt(255775022850776494562626) # assert intersection(l, s) == [ # Point2D(n/d*Rational(3, 2000), Rational(-497, 10))] def test_line_intersection(): # see also test_issue_11238 in test_matrices.py x0 = tan(pi*Rational(13, 45)) x1 = sqrt(3) x2 = x0**2 x, y = [8*x0/(x0 + x1), (24*x0 - 8*x1*x2)/(x2 - 3)] assert Line(Point(0, 0), Point(1, -sqrt(3))).contains(Point(x, y)) is True def test_intersection_3d(): p1 = Point3D(0, 0, 0) p2 = Point3D(1, 1, 1) l1 = Line3D(p1, p2) l2 = Line3D(Point3D(0, 0, 0), Point3D(3, 4, 0)) r1 = Ray3D(Point3D(1, 1, 1), Point3D(2, 2, 2)) r2 = Ray3D(Point3D(0, 0, 0), Point3D(3, 4, 0)) s1 = Segment3D(Point3D(0, 0, 0), Point3D(3, 4, 0)) assert intersection(l1, p1) == [p1] assert intersection(l1, Point3D(x1, 1 + x1, 1)) == [] assert intersection(l1, l1.parallel_line(p1)) == [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1))] assert intersection(l2, r2) == [r2] assert intersection(l2, s1) == [s1] assert intersection(r2, l2) == [r2] assert intersection(r1, Ray3D(Point3D(1, 1, 1), Point3D(-1, -1, -1))) == [Point3D(1, 1, 1)] assert intersection(r1, Segment3D(Point3D(0, 0, 0), Point3D(2, 2, 2))) == [ Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))] assert intersection(Ray3D(Point3D(1, 0, 0), Point3D(-1, 0, 0)), Ray3D(Point3D(0, 1, 0), Point3D(0, -1, 0))) \ == [Point3D(0, 0, 0)] assert intersection(r1, Ray3D(Point3D(2, 2, 2), Point3D(0, 0, 0))) == \ [Segment3D(Point3D(1, 1, 1), Point3D(2, 2, 2))] assert intersection(s1, r2) == [s1] assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).intersection(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) == \ [Point3D(2, 2, 1)] assert Line3D((0, 1, 2), (0, 2, 3)).intersection(Line3D((0, 1, 2), (0, 1, 1))) == [Point3D(0, 1, 2)] assert Line3D((0, 0), (t, t)).intersection(Line3D((0, 1), (t, t))) == \ [Point3D(t, t)] assert Ray3D(Point3D(0, 0, 0), Point3D(0, 4, 0)).intersection(Ray3D(Point3D(0, 1, 1), Point3D(0, -1, 1))) == [] def test_is_parallel(): p1 = Point3D(0, 0, 0) p2 = Point3D(1, 1, 1) p3 = Point3D(x1, x1, x1) l2 = Line(Point(x1, x1), Point(y1, y1)) l2_1 = Line(Point(x1, x1), Point(x1, 1 + x1)) assert Line.is_parallel(Line(Point(0, 0), Point(1, 1)), l2) assert Line.is_parallel(l2, Line(Point(x1, x1), Point(x1, 1 + x1))) is False assert Line.is_parallel(l2, l2.parallel_line(Point(-x1, x1))) assert Line.is_parallel(l2_1, l2_1.parallel_line(Point(0, 0))) assert Line3D(p1, p2).is_parallel(Line3D(p1, p2)) # same as in 2D assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).is_parallel(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) is False assert Line3D(p1, p2).parallel_line(p3) == Line3D(Point3D(x1, x1, x1), Point3D(x1 + 1, x1 + 1, x1 + 1)) assert Line3D(p1, p2).parallel_line(p3.args) == \ Line3D(Point3D(x1, x1, x1), Point3D(x1 + 1, x1 + 1, x1 + 1)) assert Line3D(Point3D(4, 0, 1), Point3D(0, 4, 1)).is_parallel(Line3D(Point3D(0, 0, 1), Point3D(4, 4, 1))) is False def test_is_perpendicular(): p1 = Point(0, 0) p2 = Point(1, 1) l1 = Line(p1, p2) l2 = Line(Point(x1, x1), Point(y1, y1)) l1_1 = Line(p1, Point(-x1, x1)) # 2D assert Line.is_perpendicular(l1, l1_1) assert Line.is_perpendicular(l1, l2) is False p = l1.random_point() assert l1.perpendicular_segment(p) == p # 3D assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)), Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))) is True assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)), Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0))) is False assert Line3D.is_perpendicular(Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1)), Line3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1))) is False def test_is_similar(): p1 = Point(2000, 2000) p2 = p1.scale(2, 2) r1 = Ray3D(Point3D(1, 1, 1), Point3D(1, 0, 0)) r2 = Ray(Point(0, 0), Point(0, 1)) s1 = Segment(Point(0, 0), p1) assert s1.is_similar(Segment(p1, p2)) assert s1.is_similar(r2) is False assert r1.is_similar(Line3D(Point3D(1, 1, 1), Point3D(1, 0, 0))) is True assert r1.is_similar(Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0))) is False def test_length(): s2 = Segment3D(Point3D(x1, x1, x1), Point3D(y1, y1, y1)) assert Line(Point(0, 0), Point(1, 1)).length is oo assert s2.length == sqrt(3) * sqrt((x1 - y1) ** 2) assert Line3D(Point3D(0, 0, 0), Point3D(1, 1, 1)).length is oo def test_projection(): p1 = Point(0, 0) p2 = Point3D(0, 0, 0) p3 = Point(-x1, x1) l1 = Line(p1, Point(1, 1)) l2 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)) l3 = Line3D(p2, Point3D(1, 1, 1)) r1 = Ray(Point(1, 1), Point(2, 2)) assert Line(Point(x1, x1), Point(y1, y1)).projection(Point(y1, y1)) == Point(y1, y1) assert Line(Point(x1, x1), Point(x1, 1 + x1)).projection(Point(1, 1)) == Point(x1, 1) assert Segment(Point(-2, 2), Point(0, 4)).projection(r1) == Segment(Point(-1, 3), Point(0, 4)) assert Segment(Point(0, 4), Point(-2, 2)).projection(r1) == Segment(Point(0, 4), Point(-1, 3)) assert l1.projection(p3) == p1 assert l1.projection(Ray(p1, Point(-1, 5))) == Ray(Point(0, 0), Point(2, 2)) assert l1.projection(Ray(p1, Point(-1, 1))) == p1 assert r1.projection(Ray(Point(1, 1), Point(-1, -1))) == Point(1, 1) assert r1.projection(Ray(Point(0, 4), Point(-1, -5))) == Segment(Point(1, 1), Point(2, 2)) assert r1.projection(Segment(Point(-1, 5), Point(-5, -10))) == Segment(Point(1, 1), Point(2, 2)) assert r1.projection(Ray(Point(1, 1), Point(-1, -1))) == Point(1, 1) assert r1.projection(Ray(Point(0, 4), Point(-1, -5))) == Segment(Point(1, 1), Point(2, 2)) assert r1.projection(Segment(Point(-1, 5), Point(-5, -10))) == Segment(Point(1, 1), Point(2, 2)) assert l3.projection(Ray3D(p2, Point3D(-1, 5, 0))) == Ray3D(Point3D(0, 0, 0), Point3D(Rational(4, 3), Rational(4, 3), Rational(4, 3))) assert l3.projection(Ray3D(p2, Point3D(-1, 1, 1))) == Ray3D(Point3D(0, 0, 0), Point3D(Rational(1, 3), Rational(1, 3), Rational(1, 3))) assert l2.projection(Point3D(5, 5, 0)) == Point3D(5, 0) assert l2.projection(Line3D(Point3D(0, 1, 0), Point3D(1, 1, 0))).equals(l2) def test_perpendicular_bisector(): s1 = Segment(Point(0, 0), Point(1, 1)) aline = Line(Point(S.Half, S.Half), Point(Rational(3, 2), Rational(-1, 2))) on_line = Segment(Point(S.Half, S.Half), Point(Rational(3, 2), Rational(-1, 2))).midpoint assert s1.perpendicular_bisector().equals(aline) assert s1.perpendicular_bisector(on_line).equals(Segment(s1.midpoint, on_line)) assert s1.perpendicular_bisector(on_line + (1, 0)).equals(aline) def test_raises(): d, e = symbols('a,b', real=True) s = Segment((d, 0), (e, 0)) raises(TypeError, lambda: Line((1, 1), 1)) raises(ValueError, lambda: Line(Point(0, 0), Point(0, 0))) raises(Undecidable, lambda: Point(2 * d, 0) in s) raises(ValueError, lambda: Ray3D(Point(1.0, 1.0))) raises(ValueError, lambda: Line3D(Point3D(0, 0, 0), Point3D(0, 0, 0))) raises(TypeError, lambda: Line3D((1, 1), 1)) raises(ValueError, lambda: Line3D(Point3D(0, 0, 0))) raises(TypeError, lambda: Ray((1, 1), 1)) raises(GeometryError, lambda: Line(Point(0, 0), Point(1, 0)) .projection(Circle(Point(0, 0), 1))) def test_ray_generation(): assert Ray((1, 1), angle=pi / 4) == Ray((1, 1), (2, 2)) assert Ray((1, 1), angle=pi / 2) == Ray((1, 1), (1, 2)) assert Ray((1, 1), angle=-pi / 2) == Ray((1, 1), (1, 0)) assert Ray((1, 1), angle=-3 * pi / 2) == Ray((1, 1), (1, 2)) assert Ray((1, 1), angle=5 * pi / 2) == Ray((1, 1), (1, 2)) assert Ray((1, 1), angle=5.0 * pi / 2) == Ray((1, 1), (1, 2)) assert Ray((1, 1), angle=pi) == Ray((1, 1), (0, 1)) assert Ray((1, 1), angle=3.0 * pi) == Ray((1, 1), (0, 1)) assert Ray((1, 1), angle=4.0 * pi) == Ray((1, 1), (2, 1)) assert Ray((1, 1), angle=0) == Ray((1, 1), (2, 1)) assert Ray((1, 1), angle=4.05 * pi) == Ray(Point(1, 1), Point(2, -sqrt(5) * sqrt(2 * sqrt(5) + 10) / 4 - sqrt( 2 * sqrt(5) + 10) / 4 + 2 + sqrt(5))) assert Ray((1, 1), angle=4.02 * pi) == Ray(Point(1, 1), Point(2, 1 + tan(4.02 * pi))) assert Ray((1, 1), angle=5) == Ray((1, 1), (2, 1 + tan(5))) assert Ray3D((1, 1, 1), direction_ratio=[4, 4, 4]) == Ray3D(Point3D(1, 1, 1), Point3D(5, 5, 5)) assert Ray3D((1, 1, 1), direction_ratio=[1, 2, 3]) == Ray3D(Point3D(1, 1, 1), Point3D(2, 3, 4)) assert Ray3D((1, 1, 1), direction_ratio=[1, 1, 1]) == Ray3D(Point3D(1, 1, 1), Point3D(2, 2, 2)) def test_symbolic_intersect(): # Issue 7814. circle = Circle(Point(x, 0), y) line = Line(Point(k, z), slope=0) assert line.intersection(circle) == [Point(x + sqrt((y - z) * (y + z)), z), Point(x - sqrt((y - z) * (y + z)), z)] def test_issue_2941(): def _check(): for f, g in cartes(*[(Line, Ray, Segment)] * 2): l1 = f(a, b) l2 = g(c, d) assert l1.intersection(l2) == l2.intersection(l1) # intersect at end point c, d = (-2, -2), (-2, 0) a, b = (0, 0), (1, 1) _check() # midline intersection c, d = (-2, -3), (-2, 0) _check() def test_parameter_value(): t = Symbol('t') p1, p2 = Point(0, 1), Point(5, 6) l = Line(p1, p2) assert l.parameter_value((5, 6), t) == {t: 1} raises(ValueError, lambda: l.parameter_value((0, 0), t)) def test_bisectors(): r1 = Line3D(Point3D(0, 0, 0), Point3D(1, 0, 0)) r2 = Line3D(Point3D(0, 0, 0), Point3D(0, 1, 0)) bisections = r1.bisectors(r2) assert bisections == [Line3D(Point3D(0, 0, 0), Point3D(1, 1, 0)), Line3D(Point3D(0, 0, 0), Point3D(1, -1, 0))] ans = [Line3D(Point3D(0, 0, 0), Point3D(1, 0, 1)), Line3D(Point3D(0, 0, 0), Point3D(-1, 0, 1))] l1 = (0, 0, 0), (0, 0, 1) l2 = (0, 0), (1, 0) for a, b in cartes((Line, Segment, Ray), repeat=2): assert a(*l1).bisectors(b(*l2)) == ans def test_issue_8615(): a = Line3D(Point3D(6, 5, 0), Point3D(6, -6, 0)) b = Line3D(Point3D(6, -1, 19/10), Point3D(6, -1, 0)) assert a.intersection(b) == [Point3D(6, -1, 0)]
bef396ac5ac9b8d00581bad5875c0f63de28f87fbce455a59c8cb2a362acb7d7
from sympy.core.numbers import Rational from sympy.core.singleton import S from sympy.geometry import Circle, Line, Point, Polygon, Segment from sympy.sets import FiniteSet, Union, Intersection, EmptySet def test_booleans(): """ test basic unions and intersections """ half = S.Half p1, p2, p3, p4 = map(Point, [(0, 0), (1, 0), (5, 1), (0, 1)]) p5, p6, p7 = map(Point, [(3, 2), (1, -1), (0, 2)]) l1 = Line(Point(0,0), Point(1,1)) l2 = Line(Point(half, half), Point(5,5)) l3 = Line(p2, p3) l4 = Line(p3, p4) poly1 = Polygon(p1, p2, p3, p4) poly2 = Polygon(p5, p6, p7) poly3 = Polygon(p1, p2, p5) assert Union(l1, l2).equals(l1) assert Intersection(l1, l2).equals(l1) assert Intersection(l1, l4) == FiniteSet(Point(1,1)) assert Intersection(Union(l1, l4), l3) == FiniteSet(Point(Rational(-1, 3), Rational(-1, 3)), Point(5, 1)) assert Intersection(l1, FiniteSet(Point(7,-7))) == EmptySet assert Intersection(Circle(Point(0,0), 3), Line(p1,p2)) == FiniteSet(Point(-3,0), Point(3,0)) assert Intersection(l1, FiniteSet(p1)) == FiniteSet(p1) assert Union(l1, FiniteSet(p1)) == l1 fs = FiniteSet(Point(Rational(1, 3), 1), Point(Rational(2, 3), 0), Point(Rational(9, 5), Rational(1, 5)), Point(Rational(7, 3), 1)) # test the intersection of polygons assert Intersection(poly1, poly2) == fs # make sure if we union polygons with subsets, the subsets go away assert Union(poly1, poly2, fs) == Union(poly1, poly2) # make sure that if we union with a FiniteSet that isn't a subset, # that the points in the intersection stop being listed assert Union(poly1, FiniteSet(Point(0,0), Point(3,5))) == Union(poly1, FiniteSet(Point(3,5))) # intersect two polygons that share an edge assert Intersection(poly1, poly3) == Union(FiniteSet(Point(Rational(3, 2), 1), Point(2, 1)), Segment(Point(0, 0), Point(1, 0)))
9bfb3e030bcc3a32ce036be8ca63df37d92b8cfa37f67b45a380a6097787f646
from sympy.core.numbers import (Rational, oo, pi) from sympy.core.relational import Eq from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sec from sympy.geometry.line import Segment2D from sympy.geometry.point import Point2D from sympy.geometry import (Circle, Ellipse, GeometryError, Line, Point, Polygon, Ray, RegularPolygon, Segment, Triangle, intersection) from sympy.testing.pytest import raises, slow from sympy.integrals.integrals 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(ValueError, lambda: Ellipse()) raises(GeometryError, lambda: Circle(Point(0, 0))) raises(GeometryError, lambda: Circle(Symbol('x')*Symbol('y'))) # 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 e1 in e1 assert e2 in e2 assert 1 not in e2 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 raises(ValueError, lambda: Ellipse(Point(x, y), 1, 1).arbitrary_point(parameter='x')) # 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))), ] assert Circle(Point(5, 5), 5).tangent_lines(Point(4, 0)) == \ [Line(Point(4, 0), Point(Rational(40, 13), Rational(5, 13))), Line(Point(4, 0), Point(5, 0))] assert Circle(Point(5, 5), 5).tangent_lines(Point(0, 6)) == \ [Line(Point(0, 6), Point(0, 7)), Line(Point(0, 6), Point(Rational(5, 13), Rational(90, 13)))] # 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))) raises(TypeError, lambda: Ellipse.intersection(e2, 1)) # 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) # test for the case with seed r = e3.random_point(seed=1) 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))) assert Circle((0, 1), 1).reflect(Line((0, 0), (1, 1))) == Circle(Point2D(1, 0), -1) 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((10, 0), (10, 10))) is False 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"/>'
c107aa355bc4c4a55a82e4bc642e395d4a445a38bc55456ededa9b98fa79615a
from sympy.core.function import (Derivative, Function) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.functions.elementary.exponential import exp from sympy.functions.elementary.miscellaneous import sqrt from sympy.geometry import Point, Point2D, Line, Polygon, Segment, convex_hull,\ intersection, centroid, Point3D, Line3D from sympy.geometry.util import idiff, closest_points, farthest_points, _ordered_points, are_coplanar from sympy.solvers.solvers import solve from sympy.testing.pytest import raises def test_idiff(): x = Symbol('x', real=True) y = Symbol('y', real=True) t = Symbol('t', real=True) f = Function('f') g = Function('g') # the use of idiff in ellipse also provides coverage circ = x**2 + y**2 - 4 ans = 3*x*(-x**2 - y**2)/y**5 assert ans == idiff(circ, y, x, 3).simplify() assert ans == idiff(circ, [y], x, 3).simplify() assert idiff(circ, y, x, 3).simplify() == ans explicit = 12*x/sqrt(-x**2 + 4)**5 assert ans.subs(y, solve(circ, y)[0]).equals(explicit) assert True in [sol.diff(x, 3).equals(explicit) for sol in solve(circ, y)] assert idiff(x + t + y, [y, t], x) == -Derivative(t, x) - 1 assert idiff(f(x) * exp(f(x)) - x * exp(x), f(x), x) == (x + 1) * exp(x - f(x))/(f(x) + 1) assert idiff(f(x) - y * exp(x), [f(x), y], x) == (y + Derivative(y, x)) * exp(x) assert idiff(f(x) - y * exp(x), [y, f(x)], x) == -y + exp(-x) * Derivative(f(x), x) assert idiff(f(x) - g(x), [f(x), g(x)], x) == Derivative(g(x), x) def test_intersection(): assert intersection(Point(0, 0)) == [] raises(TypeError, lambda: intersection(Point(0, 0), 3)) assert intersection( Segment((0, 0), (2, 0)), Segment((-1, 0), (1, 0)), Line((0, 0), (0, 1)), pairwise=True) == [ Point(0, 0), Segment((0, 0), (1, 0))] assert intersection( Line((0, 0), (0, 1)), Segment((0, 0), (2, 0)), Segment((-1, 0), (1, 0)), pairwise=True) == [ Point(0, 0), Segment((0, 0), (1, 0))] assert intersection( Line((0, 0), (0, 1)), Segment((0, 0), (2, 0)), Segment((-1, 0), (1, 0)), Line((0, 0), slope=1), pairwise=True) == [ Point(0, 0), Segment((0, 0), (1, 0))] def test_convex_hull(): raises(TypeError, lambda: convex_hull(Point(0, 0), 3)) points = [(1, -1), (1, -2), (3, -1), (-5, -2), (15, -4)] assert convex_hull(*points, **dict(polygon=False)) == ( [Point2D(-5, -2), Point2D(1, -1), Point2D(3, -1), Point2D(15, -4)], [Point2D(-5, -2), Point2D(15, -4)]) def test_centroid(): p = Polygon((0, 0), (10, 0), (10, 10)) q = p.translate(0, 20) assert centroid(p, q) == Point(20, 40)/3 p = Segment((0, 0), (2, 0)) q = Segment((0, 0), (2, 2)) assert centroid(p, q) == Point(1, -sqrt(2) + 2) assert centroid(Point(0, 0), Point(2, 0)) == Point(2, 0)/2 assert centroid(Point(0, 0), Point(0, 0), Point(2, 0)) == Point(2, 0)/3 def test_farthest_points_closest_points(): from random import randint from sympy.utilities.iterables import subsets for how in (min, max): if how is min: func = closest_points else: func = farthest_points raises(ValueError, lambda: func(Point2D(0, 0), Point2D(0, 0))) # 3rd pt dx is close and pt is closer to 1st pt p1 = [Point2D(0, 0), Point2D(3, 0), Point2D(1, 1)] # 3rd pt dx is close and pt is closer to 2nd pt p2 = [Point2D(0, 0), Point2D(3, 0), Point2D(2, 1)] # 3rd pt dx is close and but pt is not closer p3 = [Point2D(0, 0), Point2D(3, 0), Point2D(1, 10)] # 3rd pt dx is not closer and it's closer to 2nd pt p4 = [Point2D(0, 0), Point2D(3, 0), Point2D(4, 0)] # 3rd pt dx is not closer and it's closer to 1st pt p5 = [Point2D(0, 0), Point2D(3, 0), Point2D(-1, 0)] # duplicate point doesn't affect outcome dup = [Point2D(0, 0), Point2D(3, 0), Point2D(3, 0), Point2D(-1, 0)] # symbolic x = Symbol('x', positive=True) s = [Point2D(a) for a in ((x, 1), (x + 3, 2), (x + 2, 2))] for points in (p1, p2, p3, p4, p5, s, dup): d = how(i.distance(j) for i, j in subsets(points, 2)) ans = a, b = list(func(*points))[0] a.distance(b) == d assert ans == _ordered_points(ans) # if the following ever fails, the above tests were not sufficient # and the logical error in the routine should be fixed points = set() while len(points) != 7: points.add(Point2D(randint(1, 100), randint(1, 100))) points = list(points) d = how(i.distance(j) for i, j in subsets(points, 2)) ans = a, b = list(func(*points))[0] a.distance(b) == d assert ans == _ordered_points(ans) # equidistant points a, b, c = ( Point2D(0, 0), Point2D(1, 0), Point2D(S.Half, sqrt(3)/2)) ans = {_ordered_points((i, j)) for i, j in subsets((a, b, c), 2)} assert closest_points(b, c, a) == ans assert farthest_points(b, c, a) == ans # unique to farthest points = [(1, 1), (1, 2), (3, 1), (-5, 2), (15, 4)] assert farthest_points(*points) == { (Point2D(-5, 2), Point2D(15, 4))} points = [(1, -1), (1, -2), (3, -1), (-5, -2), (15, -4)] assert farthest_points(*points) == { (Point2D(-5, -2), Point2D(15, -4))} assert farthest_points((1, 1), (0, 0)) == { (Point2D(0, 0), Point2D(1, 1))} raises(ValueError, lambda: farthest_points((1, 1))) def test_are_coplanar(): a = Line3D(Point3D(5, 0, 0), Point3D(1, -1, 1)) b = Line3D(Point3D(0, -2, 0), Point3D(3, 1, 1)) c = Line3D(Point3D(0, -1, 0), Point3D(5, -1, 9)) d = Line(Point2D(0, 3), Point2D(1, 5)) assert are_coplanar(a, b, c) == False assert are_coplanar(a, d) == False
5e94ee364151e7786c1b6308280434a8039184b31923ede7b1ecc2bdb60b5dbc
from sympy.core.basic import Basic from sympy.core.numbers import (I, Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.functions.elementary.miscellaneous import sqrt from sympy.geometry import Line, Point, Point2D, Point3D, Line3D, Plane from sympy.geometry.entity import rotate, scale, translate, GeometryEntity from sympy.matrices import Matrix from sympy.utilities.iterables import subsets, permutations, cartes from sympy.utilities.misc import Undecidable from sympy.testing.pytest import raises, warns def test_point(): x = Symbol('x', real=True) y = Symbol('y', real=True) x1 = Symbol('x1', real=True) x2 = Symbol('x2', real=True) y1 = Symbol('y1', real=True) y2 = Symbol('y2', real=True) half = S.Half p1 = Point(x1, x2) p2 = Point(y1, y2) p3 = Point(0, 0) p4 = Point(1, 1) p5 = Point(0, 1) line = Line(Point(1, 0), slope=1) assert p1 in p1 assert p1 not in p2 assert p2.y == y2 assert (p3 + p4) == p4 assert (p2 - p1) == Point(y1 - x1, y2 - x2) assert -p2 == Point(-y1, -y2) raises(TypeError, lambda: Point(1)) raises(ValueError, lambda: Point([1])) raises(ValueError, lambda: Point(3, I)) raises(ValueError, lambda: Point(2*I, I)) raises(ValueError, lambda: Point(3 + I, I)) assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3)) assert Point.midpoint(p3, p4) == Point(half, half) assert Point.midpoint(p1, p4) == Point(half + half*x1, half + half*x2) assert Point.midpoint(p2, p2) == p2 assert p2.midpoint(p2) == p2 assert p1.origin == Point(0, 0) assert Point.distance(p3, p4) == sqrt(2) assert Point.distance(p1, p1) == 0 assert Point.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2) raises(TypeError, lambda: Point.distance(p1, 0)) raises(TypeError, lambda: Point.distance(p1, GeometryEntity())) # distance should be symmetric assert p1.distance(line) == line.distance(p1) assert p4.distance(line) == line.distance(p4) assert Point.taxicab_distance(p4, p3) == 2 assert Point.canberra_distance(p4, p5) == 1 raises(ValueError, lambda: Point.canberra_distance(p3, p3)) p1_1 = Point(x1, x1) p1_2 = Point(y2, y2) p1_3 = Point(x1 + 1, x1) assert Point.is_collinear(p3) with warns(UserWarning): assert Point.is_collinear(p3, Point(p3, dim=4)) assert p3.is_collinear() assert Point.is_collinear(p3, p4) assert Point.is_collinear(p3, p4, p1_1, p1_2) assert Point.is_collinear(p3, p4, p1_1, p1_3) is False assert Point.is_collinear(p3, p3, p4, p5) is False raises(TypeError, lambda: Point.is_collinear(line)) raises(TypeError, lambda: p1_1.is_collinear(line)) assert p3.intersection(Point(0, 0)) == [p3] assert p3.intersection(p4) == [] assert p3.intersection(line) == [] assert Point.intersection(Point(0, 0, 0), Point(0, 0)) == [Point(0, 0, 0)] x_pos = Symbol('x', real=True, positive=True) p2_1 = Point(x_pos, 0) p2_2 = Point(0, x_pos) p2_3 = Point(-x_pos, 0) p2_4 = Point(0, -x_pos) p2_5 = Point(x_pos, 5) assert Point.is_concyclic(p2_1) assert Point.is_concyclic(p2_1, p2_2) assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_4) for pts in permutations((p2_1, p2_2, p2_3, p2_5)): assert Point.is_concyclic(*pts) is False assert Point.is_concyclic(p4, p4 * 2, p4 * 3) is False assert Point(0, 0).is_concyclic((1, 1), (2, 2), (2, 1)) is False assert Point.is_concyclic(Point(0, 0, 0, 0), Point(1, 0, 0, 0), Point(1, 1, 0, 0), Point(1, 1, 1, 0)) is False assert p1.is_scalar_multiple(p1) assert p1.is_scalar_multiple(2*p1) assert not p1.is_scalar_multiple(p2) assert Point.is_scalar_multiple(Point(1, 1), (-1, -1)) assert Point.is_scalar_multiple(Point(0, 0), (0, -1)) # test when is_scalar_multiple can't be determined raises(Undecidable, lambda: Point.is_scalar_multiple(Point(sympify("x1%y1"), sympify("x2%y2")), Point(0, 1))) assert Point(0, 1).orthogonal_direction == Point(1, 0) assert Point(1, 0).orthogonal_direction == Point(0, 1) assert p1.is_zero is None assert p3.is_zero assert p4.is_zero is False assert p1.is_nonzero is None assert p3.is_nonzero is False assert p4.is_nonzero assert p4.scale(2, 3) == Point(2, 3) assert p3.scale(2, 3) == p3 assert p4.rotate(pi, Point(0.5, 0.5)) == p3 assert p1.__radd__(p2) == p1.midpoint(p2).scale(2, 2) assert (-p3).__rsub__(p4) == p3.midpoint(p4).scale(2, 2) assert p4 * 5 == Point(5, 5) assert p4 / 5 == Point(0.2, 0.2) assert 5 * p4 == Point(5, 5) raises(ValueError, lambda: Point(0, 0) + 10) # Point differences should be simplified assert Point(x*(x - 1), y) - Point(x**2 - x, y + 1) == Point(0, -1) a, b = S.Half, Rational(1, 3) assert Point(a, b).evalf(2) == \ Point(a.n(2), b.n(2), evaluate=False) raises(ValueError, lambda: Point(1, 2) + 1) # test project assert Point.project((0, 1), (1, 0)) == Point(0, 0) assert Point.project((1, 1), (1, 0)) == Point(1, 0) raises(ValueError, lambda: Point.project(p1, Point(0, 0))) # test transformations p = Point(1, 0) assert p.rotate(pi/2) == Point(0, 1) assert p.rotate(pi/2, p) == p p = Point(1, 1) assert p.scale(2, 3) == Point(2, 3) assert p.translate(1, 2) == Point(2, 3) assert p.translate(1) == Point(2, 1) assert p.translate(y=1) == Point(1, 2) assert p.translate(*p.args) == Point(2, 2) # Check invalid input for transform raises(ValueError, lambda: p3.transform(p3)) raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]]))) # test __contains__ assert 0 in Point(0, 0, 0, 0) assert 1 not in Point(0, 0, 0, 0) # test affine_rank assert Point.affine_rank() == -1 def test_point3D(): x = Symbol('x', real=True) y = Symbol('y', real=True) x1 = Symbol('x1', real=True) x2 = Symbol('x2', real=True) x3 = Symbol('x3', real=True) y1 = Symbol('y1', real=True) y2 = Symbol('y2', real=True) y3 = Symbol('y3', real=True) half = S.Half p1 = Point3D(x1, x2, x3) p2 = Point3D(y1, y2, y3) p3 = Point3D(0, 0, 0) p4 = Point3D(1, 1, 1) p5 = Point3D(0, 1, 2) assert p1 in p1 assert p1 not in p2 assert p2.y == y2 assert (p3 + p4) == p4 assert (p2 - p1) == Point3D(y1 - x1, y2 - x2, y3 - x3) assert -p2 == Point3D(-y1, -y2, -y3) assert Point(34.05, sqrt(3)) == Point(Rational(681, 20), sqrt(3)) assert Point3D.midpoint(p3, p4) == Point3D(half, half, half) assert Point3D.midpoint(p1, p4) == Point3D(half + half*x1, half + half*x2, half + half*x3) assert Point3D.midpoint(p2, p2) == p2 assert p2.midpoint(p2) == p2 assert Point3D.distance(p3, p4) == sqrt(3) assert Point3D.distance(p1, p1) == 0 assert Point3D.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2 + p2.z**2) p1_1 = Point3D(x1, x1, x1) p1_2 = Point3D(y2, y2, y2) p1_3 = Point3D(x1 + 1, x1, x1) Point3D.are_collinear(p3) assert Point3D.are_collinear(p3, p4) assert Point3D.are_collinear(p3, p4, p1_1, p1_2) assert Point3D.are_collinear(p3, p4, p1_1, p1_3) is False assert Point3D.are_collinear(p3, p3, p4, p5) is False assert p3.intersection(Point3D(0, 0, 0)) == [p3] assert p3.intersection(p4) == [] assert p4 * 5 == Point3D(5, 5, 5) assert p4 / 5 == Point3D(0.2, 0.2, 0.2) assert 5 * p4 == Point3D(5, 5, 5) raises(ValueError, lambda: Point3D(0, 0, 0) + 10) # Test coordinate properties assert p1.coordinates == (x1, x2, x3) assert p2.coordinates == (y1, y2, y3) assert p3.coordinates == (0, 0, 0) assert p4.coordinates == (1, 1, 1) assert p5.coordinates == (0, 1, 2) assert p5.x == 0 assert p5.y == 1 assert p5.z == 2 # Point differences should be simplified assert Point3D(x*(x - 1), y, 2) - Point3D(x**2 - x, y + 1, 1) == \ Point3D(0, -1, 1) a, b, c = S.Half, Rational(1, 3), Rational(1, 4) assert Point3D(a, b, c).evalf(2) == \ Point(a.n(2), b.n(2), c.n(2), evaluate=False) raises(ValueError, lambda: Point3D(1, 2, 3) + 1) # test transformations p = Point3D(1, 1, 1) assert p.scale(2, 3) == Point3D(2, 3, 1) assert p.translate(1, 2) == Point3D(2, 3, 1) assert p.translate(1) == Point3D(2, 1, 1) assert p.translate(z=1) == Point3D(1, 1, 2) assert p.translate(*p.args) == Point3D(2, 2, 2) # Test __new__ assert Point3D(0.1, 0.2, evaluate=False, on_morph='ignore').args[0].is_Float # Test length property returns correctly assert p.length == 0 assert p1_1.length == 0 assert p1_2.length == 0 # Test are_colinear type error raises(TypeError, lambda: Point3D.are_collinear(p, x)) # Test are_coplanar assert Point.are_coplanar() assert Point.are_coplanar((1, 2, 0), (1, 2, 0), (1, 3, 0)) assert Point.are_coplanar((1, 2, 0), (1, 2, 3)) with warns(UserWarning): raises(ValueError, lambda: Point2D.are_coplanar((1, 2), (1, 2, 3))) assert Point3D.are_coplanar((1, 2, 0), (1, 2, 3)) assert Point.are_coplanar((0, 0, 0), (1, 1, 0), (1, 1, 1), (1, 2, 1)) is False planar2 = Point3D(1, -1, 1) planar3 = Point3D(-1, 1, 1) assert Point3D.are_coplanar(p, planar2, planar3) == True assert Point3D.are_coplanar(p, planar2, planar3, p3) == False assert Point.are_coplanar(p, planar2) planar2 = Point3D(1, 1, 2) planar3 = Point3D(1, 1, 3) assert Point3D.are_coplanar(p, planar2, planar3) # line, not plane plane = Plane((1, 2, 1), (2, 1, 0), (3, 1, 2)) assert Point.are_coplanar(*[plane.projection(((-1)**i, i)) for i in range(4)]) # all 2D points are coplanar assert Point.are_coplanar(Point(x, y), Point(x, x + y), Point(y, x + 2)) is True # Test Intersection assert planar2.intersection(Line3D(p, planar3)) == [Point3D(1, 1, 2)] # Test Scale assert planar2.scale(1, 1, 1) == planar2 assert planar2.scale(2, 2, 2, planar3) == Point3D(1, 1, 1) assert planar2.scale(1, 1, 1, p3) == planar2 # Test Transform identity = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) assert p.transform(identity) == p trans = Matrix([[1, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 0, 1]]) assert p.transform(trans) == Point3D(2, 2, 2) raises(ValueError, lambda: p.transform(p)) raises(ValueError, lambda: p.transform(Matrix([[1, 0], [0, 1]]))) # Test Equals assert p.equals(x1) == False # Test __sub__ p_4d = Point(0, 0, 0, 1) with warns(UserWarning): assert p - p_4d == Point(1, 1, 1, -1) p_4d3d = Point(0, 0, 1, 0) with warns(UserWarning): assert p - p_4d3d == Point(1, 1, 0, 0) def test_Point2D(): # Test Distance p1 = Point2D(1, 5) p2 = Point2D(4, 2.5) p3 = (6, 3) assert p1.distance(p2) == sqrt(61)/2 assert p2.distance(p3) == sqrt(17)/2 # Test coordinates assert p1.x == 1 assert p1.y == 5 assert p2.x == 4 assert p2.y == 2.5 assert p1.coordinates == (1, 5) assert p2.coordinates == (4, 2.5) # test bounds assert p1.bounds == (1, 5, 1, 5) def test_issue_9214(): p1 = Point3D(4, -2, 6) p2 = Point3D(1, 2, 3) p3 = Point3D(7, 2, 3) assert Point3D.are_collinear(p1, p2, p3) is False def test_issue_11617(): p1 = Point3D(1,0,2) p2 = Point2D(2,0) with warns(UserWarning): assert p1.distance(p2) == sqrt(5) def test_transform(): p = Point(1, 1) assert p.transform(rotate(pi/2)) == Point(-1, 1) assert p.transform(scale(3, 2)) == Point(3, 2) assert p.transform(translate(1, 2)) == Point(2, 3) assert Point(1, 1).scale(2, 3, (4, 5)) == \ Point(-2, -7) assert Point(1, 1).translate(4, 5) == \ Point(5, 6) def test_concyclic_doctest_bug(): p1, p2 = Point(-1, 0), Point(1, 0) p3, p4 = Point(0, 1), Point(-1, 2) assert Point.is_concyclic(p1, p2, p3) assert not Point.is_concyclic(p1, p2, p3, p4) def test_arguments(): """Functions accepting `Point` objects in `geometry` should also accept tuples and lists and automatically convert them to points.""" singles2d = ((1,2), [1,2], Point(1,2)) singles2d2 = ((1,3), [1,3], Point(1,3)) doubles2d = cartes(singles2d, singles2d2) p2d = Point2D(1,2) singles3d = ((1,2,3), [1,2,3], Point(1,2,3)) doubles3d = subsets(singles3d, 2) p3d = Point3D(1,2,3) singles4d = ((1,2,3,4), [1,2,3,4], Point(1,2,3,4)) doubles4d = subsets(singles4d, 2) p4d = Point(1,2,3,4) # test 2D test_single = ['distance', 'is_scalar_multiple', 'taxicab_distance', 'midpoint', 'intersection', 'dot', 'equals', '__add__', '__sub__'] test_double = ['is_concyclic', 'is_collinear'] for p in singles2d: Point2D(p) for func in test_single: for p in singles2d: getattr(p2d, func)(p) for func in test_double: for p in doubles2d: getattr(p2d, func)(*p) # test 3D test_double = ['is_collinear'] for p in singles3d: Point3D(p) for func in test_single: for p in singles3d: getattr(p3d, func)(p) for func in test_double: for p in doubles3d: getattr(p3d, func)(*p) # test 4D test_double = ['is_collinear'] for p in singles4d: Point(p) for func in test_single: for p in singles4d: getattr(p4d, func)(p) for func in test_double: for p in doubles4d: getattr(p4d, func)(*p) # test evaluate=False for ops x = Symbol('x') a = Point(0, 1) assert a + (0.1, x) == Point(0.1, 1 + x, evaluate=False) a = Point(0, 1) assert a/10.0 == Point(0, 0.1, evaluate=False) a = Point(0, 1) assert a*10.0 == Point(0.0, 10.0, evaluate=False) # test evaluate=False when changing dimensions u = Point(.1, .2, evaluate=False) u4 = Point(u, dim=4, on_morph='ignore') assert u4.args == (.1, .2, 0, 0) assert all(i.is_Float for i in u4.args[:2]) # and even when *not* changing dimensions assert all(i.is_Float for i in Point(u).args) # never raise error if creating an origin assert Point(dim=3, on_morph='error') # raise error with unmatched dimension raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='error')) # test unknown on_morph raises(ValueError, lambda: Point(1, 1, dim=3, on_morph='unknown')) # test invalid expressions raises(TypeError, lambda: Point(Basic(), Basic())) def test_unit(): assert Point(1, 1).unit == Point(sqrt(2)/2, sqrt(2)/2) def test_dot(): raises(TypeError, lambda: Point(1, 2).dot(Line((0, 0), (1, 1)))) def test__normalize_dimension(): assert Point._normalize_dimension(Point(1, 2), Point(3, 4)) == [ Point(1, 2), Point(3, 4)] assert Point._normalize_dimension( Point(1, 2), Point(3, 4, 0), on_morph='ignore') == [ Point(1, 2, 0), Point(3, 4, 0)] def test_direction_cosine(): p1 = Point3D(0, 0, 0) p2 = Point3D(1, 1, 1) assert p1.direction_cosine(Point3D(1, 0, 0)) == [1, 0, 0] assert p1.direction_cosine(Point3D(0, 1, 0)) == [0, 1, 0] assert p1.direction_cosine(Point3D(0, 0, pi)) == [0, 0, 1] assert p1.direction_cosine(Point3D(5, 0, 0)) == [1, 0, 0] assert p1.direction_cosine(Point3D(0, sqrt(3), 0)) == [0, 1, 0] assert p1.direction_cosine(Point3D(0, 0, 5)) == [0, 0, 1] assert p1.direction_cosine(Point3D(2.4, 2.4, 0)) == [sqrt(2)/2, sqrt(2)/2, 0] assert p1.direction_cosine(Point3D(1, 1, 1)) == [sqrt(3) / 3, sqrt(3) / 3, sqrt(3) / 3] assert p1.direction_cosine(Point3D(-12, 0 -15)) == [-4*sqrt(41)/41, -5*sqrt(41)/41, 0] assert p2.direction_cosine(Point3D(0, 0, 0)) == [-sqrt(3) / 3, -sqrt(3) / 3, -sqrt(3) / 3] assert p2.direction_cosine(Point3D(1, 1, 12)) == [0, 0, 1] assert p2.direction_cosine(Point3D(12, 1, 12)) == [sqrt(2) / 2, 0, sqrt(2) / 2]
a23da8ae7cd5d2ac5cc955e736c86680c9add76fa0451605980ced99341750db
from sympy.core.numbers import (Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import Symbol from sympy.geometry import (Circle, Ellipse, Point, Line, Parabola, Polygon, Ray, RegularPolygon, Segment, Triangle, Plane, Curve) from sympy.geometry.entity import scale, GeometryEntity from sympy.testing.pytest import raises from random import random def test_entity(): x = Symbol('x', real=True) y = Symbol('y', real=True) assert GeometryEntity(x, y) in GeometryEntity(x, y) raises(NotImplementedError, lambda: Point(0, 0) in GeometryEntity(x, y)) assert GeometryEntity(x, y) == GeometryEntity(x, y) assert GeometryEntity(x, y).equals(GeometryEntity(x, y)) c = Circle((0, 0), 5) assert GeometryEntity.encloses(c, Point(0, 0)) assert GeometryEntity.encloses(c, Segment((0, 0), (1, 1))) assert GeometryEntity.encloses(c, Line((0, 0), (1, 1))) is False assert GeometryEntity.encloses(c, Circle((0, 0), 4)) assert GeometryEntity.encloses(c, Polygon(Point(0, 0), Point(1, 0), Point(0, 1))) assert GeometryEntity.encloses(c, RegularPolygon(Point(8, 8), 1, 3)) is False def test_svg(): a = Symbol('a') b = Symbol('b') d = Symbol('d') entity = Circle(Point(a, b), d) assert entity._repr_svg_() is None entity = Circle(Point(0, 0), S.Infinity) assert entity._repr_svg_() is None def test_subs(): x = Symbol('x', real=True) y = Symbol('y', real=True) p = Point(x, 2) q = Point(1, 1) r = Point(3, 4) for o in [p, Segment(p, q), Ray(p, q), Line(p, q), Triangle(p, q, r), RegularPolygon(p, 3, 6), Polygon(p, q, r, Point(5, 4)), Circle(p, 3), Ellipse(p, 3, 4)]: assert 'y' in str(o.subs(x, y)) assert p.subs({x: 1}) == Point(1, 2) assert Point(1, 2).subs(Point(1, 2), Point(3, 4)) == Point(3, 4) assert Point(1, 2).subs((1, 2), Point(3, 4)) == Point(3, 4) assert Point(1, 2).subs(Point(1, 2), Point(3, 4)) == Point(3, 4) assert Point(1, 2).subs({(1, 2)}) == Point(2, 2) raises(ValueError, lambda: Point(1, 2).subs(1)) raises(ValueError, lambda: Point(1, 1).subs((Point(1, 1), Point(1, 2)), 1, 2)) def test_transform(): assert scale(1, 2, (3, 4)).tolist() == \ [[1, 0, 0], [0, 2, 0], [0, -4, 1]] def test_reflect_entity_overrides(): x = Symbol('x', real=True) y = Symbol('y', real=True) b = Symbol('b') m = Symbol('m') l = Line((0, b), slope=m) p = Point(x, y) r = p.reflect(l) c = Circle((x, y), 3) cr = c.reflect(l) assert cr == Circle(r, -3) assert c.area == -cr.area pent = RegularPolygon((1, 2), 1, 5) l = Line(pent.vertices[1], slope=Rational(random() - .5, random() - .5)) rpent = pent.reflect(l) assert rpent.center == pent.center.reflect(l) rvert = [i.reflect(l) for i in pent.vertices] for v in rpent.vertices: for i in range(len(rvert)): ri = rvert[i] if ri.equals(v): rvert.remove(ri) break assert not rvert assert pent.area.equals(-rpent.area) def test_geometry_EvalfMixin(): x = pi t = Symbol('t') for g in [ Point(x, x), Plane(Point(0, x, 0), (0, 0, x)), Curve((x*t, x), (t, 0, x)), Ellipse((x, x), x, -x), Circle((x, x), x), Line((0, x), (x, 0)), Segment((0, x), (x, 0)), Ray((0, x), (x, 0)), Parabola((0, x), Line((-x, 0), (x, 0))), Polygon((0, 0), (0, x), (x, 0), (x, x)), RegularPolygon((0, x), x, 4, x), Triangle((0, 0), (x, 0), (x, x)), ]: assert str(g).replace('pi', '3.1') == str(g.n(2))
da0c5f40dfe612b972daa394c1c789010d738f7bbbe558ee21a35d95a4b75b98
from sympy.core.numbers import (Float, Rational, oo, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.complexes import Abs from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (acos, cos, sin) from sympy.functions.elementary.trigonometric import tan from sympy.geometry import (Circle, Ellipse, GeometryError, Point, Point2D, Polygon, Ray, RegularPolygon, Segment, Triangle, are_similar, convex_hull, intersection, Line, Ray2D) from sympy.testing.pytest import raises, slow, warns from sympy.testing.randtest import verify_numerically from sympy.geometry.polygon import rad, deg from sympy.integrals.integrals import integrate def feq(a, b): """Test if two floating point values are 'equal'.""" t_float = Float("1.0E-10") return -t_float < a - b < t_float @slow def test_polygon(): x = Symbol('x', real=True) y = Symbol('y', real=True) q = Symbol('q', real=True) u = Symbol('u', real=True) v = Symbol('v', real=True) w = Symbol('w', real=True) x1 = Symbol('x1', real=True) half = S.Half a, b, c = Point(0, 0), Point(2, 0), Point(3, 3) t = Triangle(a, b, c) assert Polygon(Point(0, 0)) == Point(0, 0) assert Polygon(a, Point(1, 0), b, c) == t assert Polygon(Point(1, 0), b, c, a) == t assert Polygon(b, c, a, Point(1, 0)) == t # 2 "remove folded" tests assert Polygon(a, Point(3, 0), b, c) == t assert Polygon(a, b, Point(3, -1), b, c) == t # remove multiple collinear points assert Polygon(Point(-4, 15), Point(-11, 15), Point(-15, 15), Point(-15, 33/5), Point(-15, -87/10), Point(-15, -15), Point(-42/5, -15), Point(-2, -15), Point(7, -15), Point(15, -15), Point(15, -3), Point(15, 10), Point(15, 15)) == \ Polygon(Point(-15, -15), Point(15, -15), Point(15, 15), Point(-15, 15)) p1 = Polygon( Point(0, 0), Point(3, -1), Point(6, 0), Point(4, 5), Point(2, 3), Point(0, 3)) p2 = Polygon( Point(6, 0), Point(3, -1), Point(0, 0), Point(0, 3), Point(2, 3), Point(4, 5)) p3 = Polygon( Point(0, 0), Point(3, 0), Point(5, 2), Point(4, 4)) p4 = Polygon( Point(0, 0), Point(4, 4), Point(5, 2), Point(3, 0)) p5 = Polygon( Point(0, 0), Point(4, 4), Point(0, 4)) p6 = Polygon( Point(-11, 1), Point(-9, 6.6), Point(-4, -3), Point(-8.4, -8.7)) p7 = Polygon( Point(x, y), Point(q, u), Point(v, w)) p8 = Polygon( Point(x, y), Point(v, w), Point(q, u)) p9 = Polygon( Point(0, 0), Point(4, 4), Point(3, 0), Point(5, 2)) p10 = Polygon( Point(0, 2), Point(2, 2), Point(0, 0), Point(2, 0)) p11 = Polygon(Point(0, 0), 1, n=3) p12 = Polygon(Point(0, 0), 1, 0, n=3) r = Ray(Point(-9, 6.6), Point(-9, 5.5)) # # General polygon # assert p1 == p2 assert len(p1.args) == 6 assert len(p1.sides) == 6 assert p1.perimeter == 5 + 2*sqrt(10) + sqrt(29) + sqrt(8) assert p1.area == 22 assert not p1.is_convex() assert Polygon((-1, 1), (2, -1), (2, 1), (-1, -1), (3, 0) ).is_convex() is False # ensure convex for both CW and CCW point specification assert p3.is_convex() assert p4.is_convex() dict5 = p5.angles assert dict5[Point(0, 0)] == pi / 4 assert dict5[Point(0, 4)] == pi / 2 assert p5.encloses_point(Point(x, y)) is None assert p5.encloses_point(Point(1, 3)) assert p5.encloses_point(Point(0, 0)) is False assert p5.encloses_point(Point(4, 0)) is False assert p1.encloses(Circle(Point(2.5, 2.5), 5)) is False assert p1.encloses(Ellipse(Point(2.5, 2), 5, 6)) is False p5.plot_interval('x') == [x, 0, 1] assert p5.distance( Polygon(Point(10, 10), Point(14, 14), Point(10, 14))) == 6 * sqrt(2) assert p5.distance( Polygon(Point(1, 8), Point(5, 8), Point(8, 12), Point(1, 12))) == 4 with warns(UserWarning, \ match="Polygons may intersect producing erroneous output"): Polygon(Point(0, 0), Point(1, 0), Point(1, 1)).distance( Polygon(Point(0, 0), Point(0, 1), Point(1, 1))) assert hash(p5) == hash(Polygon(Point(0, 0), Point(4, 4), Point(0, 4))) assert hash(p1) == hash(p2) assert hash(p7) == hash(p8) assert hash(p3) != hash(p9) assert p5 == Polygon(Point(4, 4), Point(0, 4), Point(0, 0)) assert Polygon(Point(4, 4), Point(0, 4), Point(0, 0)) in p5 assert p5 != Point(0, 4) assert Point(0, 1) in p5 assert p5.arbitrary_point('t').subs(Symbol('t', real=True), 0) == \ Point(0, 0) raises(ValueError, lambda: Polygon( Point(x, 0), Point(0, y), Point(x, y)).arbitrary_point('x')) assert p6.intersection(r) == [Point(-9, Rational(-84, 13)), Point(-9, Rational(33, 5))] assert p10.area == 0 assert p11 == RegularPolygon(Point(0, 0), 1, 3, 0) assert p11 == p12 assert p11.vertices[0] == Point(1, 0) assert p11.args[0] == Point(0, 0) p11.spin(pi/2) assert p11.vertices[0] == Point(0, 1) # # Regular polygon # p1 = RegularPolygon(Point(0, 0), 10, 5) p2 = RegularPolygon(Point(0, 0), 5, 5) raises(GeometryError, lambda: RegularPolygon(Point(0, 0), Point(0, 1), Point(1, 1))) raises(GeometryError, lambda: RegularPolygon(Point(0, 0), 1, 2)) raises(ValueError, lambda: RegularPolygon(Point(0, 0), 1, 2.5)) assert p1 != p2 assert p1.interior_angle == pi*Rational(3, 5) assert p1.exterior_angle == pi*Rational(2, 5) assert p2.apothem == 5*cos(pi/5) assert p2.circumcenter == p1.circumcenter == Point(0, 0) assert p1.circumradius == p1.radius == 10 assert p2.circumcircle == Circle(Point(0, 0), 5) assert p2.incircle == Circle(Point(0, 0), p2.apothem) assert p2.inradius == p2.apothem == (5 * (1 + sqrt(5)) / 4) p2.spin(pi / 10) dict1 = p2.angles assert dict1[Point(0, 5)] == 3 * pi / 5 assert p1.is_convex() assert p1.rotation == 0 assert p1.encloses_point(Point(0, 0)) assert p1.encloses_point(Point(11, 0)) is False assert p2.encloses_point(Point(0, 4.9)) p1.spin(pi/3) assert p1.rotation == pi/3 assert p1.vertices[0] == Point(5, 5*sqrt(3)) for var in p1.args: if isinstance(var, Point): assert var == Point(0, 0) else: assert var in (5, 10, pi / 3) assert p1 != Point(0, 0) assert p1 != p5 # while spin works in place (notice that rotation is 2pi/3 below) # rotate returns a new object p1_old = p1 assert p1.rotate(pi/3) == RegularPolygon(Point(0, 0), 10, 5, pi*Rational(2, 3)) assert p1 == p1_old assert p1.area == (-250*sqrt(5) + 1250)/(4*tan(pi/5)) assert p1.length == 20*sqrt(-sqrt(5)/8 + Rational(5, 8)) assert p1.scale(2, 2) == \ RegularPolygon(p1.center, p1.radius*2, p1._n, p1.rotation) assert RegularPolygon((0, 0), 1, 4).scale(2, 3) == \ Polygon(Point(2, 0), Point(0, 3), Point(-2, 0), Point(0, -3)) assert repr(p1) == str(p1) # # Angles # angles = p4.angles assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483")) assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544")) assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388")) assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449")) angles = p3.angles assert feq(angles[Point(0, 0)].evalf(), Float("0.7853981633974483")) assert feq(angles[Point(4, 4)].evalf(), Float("1.2490457723982544")) assert feq(angles[Point(5, 2)].evalf(), Float("1.8925468811915388")) assert feq(angles[Point(3, 0)].evalf(), Float("2.3561944901923449")) # # Triangle # p1 = Point(0, 0) p2 = Point(5, 0) p3 = Point(0, 5) t1 = Triangle(p1, p2, p3) t2 = Triangle(p1, p2, Point(Rational(5, 2), sqrt(Rational(75, 4)))) t3 = Triangle(p1, Point(x1, 0), Point(0, x1)) s1 = t1.sides assert Triangle(p1, p2, p1) == Polygon(p1, p2, p1) == Segment(p1, p2) raises(GeometryError, lambda: Triangle(Point(0, 0))) # Basic stuff assert Triangle(p1, p1, p1) == p1 assert Triangle(p2, p2*2, p2*3) == Segment(p2, p2*3) assert t1.area == Rational(25, 2) assert t1.is_right() assert t2.is_right() is False assert t3.is_right() assert p1 in t1 assert t1.sides[0] in t1 assert Segment((0, 0), (1, 0)) in t1 assert Point(5, 5) not in t2 assert t1.is_convex() assert feq(t1.angles[p1].evalf(), pi.evalf()/2) assert t1.is_equilateral() is False assert t2.is_equilateral() assert t3.is_equilateral() is False assert are_similar(t1, t2) is False assert are_similar(t1, t3) assert are_similar(t2, t3) is False assert t1.is_similar(Point(0, 0)) is False assert t1.is_similar(t2) is False # Bisectors bisectors = t1.bisectors() assert bisectors[p1] == Segment( p1, Point(Rational(5, 2), Rational(5, 2))) assert t2.bisectors()[p2] == Segment( Point(5, 0), Point(Rational(5, 4), 5*sqrt(3)/4)) p4 = Point(0, x1) assert t3.bisectors()[p4] == Segment(p4, Point(x1*(sqrt(2) - 1), 0)) ic = (250 - 125*sqrt(2))/50 assert t1.incenter == Point(ic, ic) # Inradius assert t1.inradius == t1.incircle.radius == 5 - 5*sqrt(2)/2 assert t2.inradius == t2.incircle.radius == 5*sqrt(3)/6 assert t3.inradius == t3.incircle.radius == x1**2/((2 + sqrt(2))*Abs(x1)) # Exradius assert t1.exradii[t1.sides[2]] == 5*sqrt(2)/2 # Excenters assert t1.excenters[t1.sides[2]] == Point2D(25*sqrt(2), -5*sqrt(2)/2) # Circumcircle assert t1.circumcircle.center == Point(2.5, 2.5) # Medians + Centroid m = t1.medians assert t1.centroid == Point(Rational(5, 3), Rational(5, 3)) assert m[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2))) assert t3.medians[p1] == Segment(p1, Point(x1/2, x1/2)) assert intersection(m[p1], m[p2], m[p3]) == [t1.centroid] assert t1.medial == Triangle(Point(2.5, 0), Point(0, 2.5), Point(2.5, 2.5)) # Nine-point circle assert t1.nine_point_circle == Circle(Point(2.5, 0), Point(0, 2.5), Point(2.5, 2.5)) assert t1.nine_point_circle == Circle(Point(0, 0), Point(0, 2.5), Point(2.5, 2.5)) # Perpendicular altitudes = t1.altitudes assert altitudes[p1] == Segment(p1, Point(Rational(5, 2), Rational(5, 2))) assert altitudes[p2].equals(s1[0]) assert altitudes[p3] == s1[2] assert t1.orthocenter == p1 t = S('''Triangle( Point(100080156402737/5000000000000, 79782624633431/500000000000), Point(39223884078253/2000000000000, 156345163124289/1000000000000), Point(31241359188437/1250000000000, 338338270939941/1000000000000000))''') assert t.orthocenter == S('''Point(-780660869050599840216997''' '''79471538701955848721853/80368430960602242240789074233100000000000000,''' '''20151573611150265741278060334545897615974257/16073686192120448448157''' '''8148466200000000000)''') # Ensure assert len(intersection(*bisectors.values())) == 1 assert len(intersection(*altitudes.values())) == 1 assert len(intersection(*m.values())) == 1 # Distance p1 = Polygon( Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1)) p2 = Polygon( Point(0, Rational(5)/4), Point(1, Rational(5)/4), Point(1, Rational(9)/4), Point(0, Rational(9)/4)) p3 = Polygon( Point(1, 2), Point(2, 2), Point(2, 1)) p4 = Polygon( Point(1, 1), Point(Rational(6)/5, 1), Point(1, Rational(6)/5)) pt1 = Point(half, half) pt2 = Point(1, 1) '''Polygon to Point''' assert p1.distance(pt1) == half assert p1.distance(pt2) == 0 assert p2.distance(pt1) == Rational(3)/4 assert p3.distance(pt2) == sqrt(2)/2 '''Polygon to Polygon''' # p1.distance(p2) emits a warning with warns(UserWarning, \ match="Polygons may intersect producing erroneous output"): assert p1.distance(p2) == half/2 assert p1.distance(p3) == sqrt(2)/2 # p3.distance(p4) emits a warning with warns(UserWarning, \ match="Polygons may intersect producing erroneous output"): assert p3.distance(p4) == (sqrt(2)/2 - sqrt(Rational(2)/25)/2) def test_convex_hull(): p = [Point(-5, -1), Point(-2, 1), Point(-2, -1), Point(-1, -3), \ Point(0, 0), Point(1, 1), Point(2, 2), Point(2, -1), Point(3, 1), \ Point(4, -1), Point(6, 2)] ch = Polygon(p[0], p[3], p[9], p[10], p[6], p[1]) #test handling of duplicate points p.append(p[3]) #more than 3 collinear points another_p = [Point(-45, -85), Point(-45, 85), Point(-45, 26), \ Point(-45, -24)] ch2 = Segment(another_p[0], another_p[1]) assert convex_hull(*another_p) == ch2 assert convex_hull(*p) == ch assert convex_hull(p[0]) == p[0] assert convex_hull(p[0], p[1]) == Segment(p[0], p[1]) # no unique points assert convex_hull(*[p[-1]]*3) == p[-1] # collection of items assert convex_hull(*[Point(0, 0), \ Segment(Point(1, 0), Point(1, 1)), \ RegularPolygon(Point(2, 0), 2, 4)]) == \ Polygon(Point(0, 0), Point(2, -2), Point(4, 0), Point(2, 2)) def test_encloses(): # square with a dimpled left side s = Polygon(Point(0, 0), Point(1, 0), Point(1, 1), Point(0, 1), \ Point(S.Half, S.Half)) # the following is True if the polygon isn't treated as closing on itself assert s.encloses(Point(0, S.Half)) is False assert s.encloses(Point(S.Half, S.Half)) is False # it's a vertex assert s.encloses(Point(Rational(3, 4), S.Half)) is True def test_triangle_kwargs(): assert Triangle(sss=(3, 4, 5)) == \ Triangle(Point(0, 0), Point(3, 0), Point(3, 4)) assert Triangle(asa=(30, 2, 30)) == \ Triangle(Point(0, 0), Point(2, 0), Point(1, sqrt(3)/3)) assert Triangle(sas=(1, 45, 2)) == \ Triangle(Point(0, 0), Point(2, 0), Point(sqrt(2)/2, sqrt(2)/2)) assert Triangle(sss=(1, 2, 5)) is None assert deg(rad(180)) == 180 def test_transform(): pts = [Point(0, 0), Point(S.Half, Rational(1, 4)), Point(1, 1)] pts_out = [Point(-4, -10), Point(-3, Rational(-37, 4)), Point(-2, -7)] assert Triangle(*pts).scale(2, 3, (4, 5)) == Triangle(*pts_out) assert RegularPolygon((0, 0), 1, 4).scale(2, 3, (4, 5)) == \ Polygon(Point(-2, -10), Point(-4, -7), Point(-6, -10), Point(-4, -13)) # Checks for symmetric scaling assert RegularPolygon((0, 0), 1, 4).scale(2, 2) == \ RegularPolygon(Point2D(0, 0), 2, 4, 0) def test_reflect(): x = Symbol('x', real=True) y = Symbol('y', real=True) b = Symbol('b') m = Symbol('m') l = Line((0, b), slope=m) p = Point(x, y) r = p.reflect(l) dp = l.perpendicular_segment(p).length dr = l.perpendicular_segment(r).length assert verify_numerically(dp, dr) assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((3, 0), slope=oo)) \ == Triangle(Point(5, 0), Point(4, 0), Point(4, 2)) assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((0, 3), slope=oo)) \ == Triangle(Point(-1, 0), Point(-2, 0), Point(-2, 2)) assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((0, 3), slope=0)) \ == Triangle(Point(1, 6), Point(2, 6), Point(2, 4)) assert Polygon((1, 0), (2, 0), (2, 2)).reflect(Line((3, 0), slope=0)) \ == Triangle(Point(1, 0), Point(2, 0), Point(2, -2)) def test_bisectors(): p1, p2, p3 = Point(0, 0), Point(1, 0), Point(0, 1) p = Polygon(Point(0, 0), Point(2, 0), Point(1, 1), Point(0, 3)) q = Polygon(Point(1, 0), Point(2, 0), Point(3, 3), Point(-1, 5)) poly = Polygon(Point(3, 4), Point(0, 0), Point(8, 7), Point(-1, 1), Point(19, -19)) t = Triangle(p1, p2, p3) assert t.bisectors()[p2] == Segment(Point(1, 0), Point(0, sqrt(2) - 1)) assert p.bisectors()[Point2D(0, 3)] == Ray2D(Point2D(0, 3), \ Point2D(sin(acos(2*sqrt(5)/5)/2), 3 - cos(acos(2*sqrt(5)/5)/2))) assert q.bisectors()[Point2D(-1, 5)] == \ Ray2D(Point2D(-1, 5), Point2D(-1 + sqrt(29)*(5*sin(acos(9*sqrt(145)/145)/2) + \ 2*cos(acos(9*sqrt(145)/145)/2))/29, sqrt(29)*(-5*cos(acos(9*sqrt(145)/145)/2) + \ 2*sin(acos(9*sqrt(145)/145)/2))/29 + 5)) assert poly.bisectors()[Point2D(-1, 1)] == Ray2D(Point2D(-1, 1), \ Point2D(-1 + sin(acos(sqrt(26)/26)/2 + pi/4), 1 - sin(-acos(sqrt(26)/26)/2 + pi/4))) def test_incenter(): assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).incenter \ == Point(1 - sqrt(2)/2, 1 - sqrt(2)/2) def test_inradius(): assert Triangle(Point(0, 0), Point(4, 0), Point(0, 3)).inradius == 1 def test_incircle(): assert Triangle(Point(0, 0), Point(2, 0), Point(0, 2)).incircle \ == Circle(Point(2 - sqrt(2), 2 - sqrt(2)), 2 - sqrt(2)) def test_exradii(): t = Triangle(Point(0, 0), Point(6, 0), Point(0, 2)) assert t.exradii[t.sides[2]] == (-2 + sqrt(10)) def test_medians(): t = Triangle(Point(0, 0), Point(1, 0), Point(0, 1)) assert t.medians[Point(0, 0)] == Segment(Point(0, 0), Point(S.Half, S.Half)) def test_medial(): assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).medial \ == Triangle(Point(S.Half, 0), Point(S.Half, S.Half), Point(0, S.Half)) def test_nine_point_circle(): assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).nine_point_circle \ == Circle(Point2D(Rational(1, 4), Rational(1, 4)), sqrt(2)/4) def test_eulerline(): assert Triangle(Point(0, 0), Point(1, 0), Point(0, 1)).eulerline \ == Line(Point2D(0, 0), Point2D(S.Half, S.Half)) assert Triangle(Point(0, 0), Point(10, 0), Point(5, 5*sqrt(3))).eulerline \ == Point2D(5, 5*sqrt(3)/3) assert Triangle(Point(4, -6), Point(4, -1), Point(-3, 3)).eulerline \ == Line(Point2D(Rational(64, 7), 3), Point2D(Rational(-29, 14), Rational(-7, 2))) def test_intersection(): poly1 = Triangle(Point(0, 0), Point(1, 0), Point(0, 1)) poly2 = Polygon(Point(0, 1), Point(-5, 0), Point(0, -4), Point(0, Rational(1, 5)), Point(S.Half, -0.1), Point(1, 0), Point(0, 1)) assert poly1.intersection(poly2) == [Point2D(Rational(1, 3), 0), Segment(Point(0, Rational(1, 5)), Point(0, 0)), Segment(Point(1, 0), Point(0, 1))] assert poly2.intersection(poly1) == [Point(Rational(1, 3), 0), Segment(Point(0, 0), Point(0, Rational(1, 5))), Segment(Point(1, 0), Point(0, 1))] assert poly1.intersection(Point(0, 0)) == [Point(0, 0)] assert poly1.intersection(Point(-12, -43)) == [] assert poly2.intersection(Line((-12, 0), (12, 0))) == [Point(-5, 0), Point(0, 0), Point(Rational(1, 3), 0), Point(1, 0)] assert poly2.intersection(Line((-12, 12), (12, 12))) == [] assert poly2.intersection(Ray((-3, 4), (1, 0))) == [Segment(Point(1, 0), Point(0, 1))] assert poly2.intersection(Circle((0, -1), 1)) == [Point(0, -2), Point(0, 0)] assert poly1.intersection(poly1) == [Segment(Point(0, 0), Point(1, 0)), Segment(Point(0, 1), Point(0, 0)), Segment(Point(1, 0), Point(0, 1))] assert poly2.intersection(poly2) == [Segment(Point(-5, 0), Point(0, -4)), Segment(Point(0, -4), Point(0, Rational(1, 5))), Segment(Point(0, Rational(1, 5)), Point(S.Half, Rational(-1, 10))), Segment(Point(0, 1), Point(-5, 0)), Segment(Point(S.Half, Rational(-1, 10)), Point(1, 0)), Segment(Point(1, 0), Point(0, 1))] assert poly2.intersection(Triangle(Point(0, 1), Point(1, 0), Point(-1, 1))) \ == [Point(Rational(-5, 7), Rational(6, 7)), Segment(Point2D(0, 1), Point(1, 0))] assert poly1.intersection(RegularPolygon((-12, -15), 3, 3)) == [] def test_parameter_value(): t = Symbol('t') sq = Polygon((0, 0), (0, 1), (1, 1), (1, 0)) assert sq.parameter_value((0.5, 1), t) == {t: Rational(3, 8)} q = Polygon((0, 0), (2, 1), (2, 4), (4, 0)) assert q.parameter_value((4, 0), t) == {t: -6 + 3*sqrt(5)} # ~= 0.708 raises(ValueError, lambda: sq.parameter_value((5, 6), t)) raises(ValueError, lambda: sq.parameter_value(Circle(Point(0, 0), 1), t)) def test_issue_12966(): poly = Polygon(Point(0, 0), Point(0, 10), Point(5, 10), Point(5, 5), Point(10, 5), Point(10, 0)) t = Symbol('t') pt = poly.arbitrary_point(t) DELTA = 5/poly.perimeter assert [pt.subs(t, DELTA*i) for i in range(int(1/DELTA))] == [ Point(0, 0), Point(0, 5), Point(0, 10), Point(5, 10), Point(5, 5), Point(10, 5), Point(10, 0), Point(5, 0)] def test_second_moment_of_area(): x, y = symbols('x, y') # triangle p1, p2, p3 = [(0, 0), (4, 0), (0, 2)] p = (0, 0) # equation of hypotenuse eq_y = (1-x/4)*2 I_yy = integrate((x**2) * (integrate(1, (y, 0, eq_y))), (x, 0, 4)) I_xx = integrate(1 * (integrate(y**2, (y, 0, eq_y))), (x, 0, 4)) I_xy = integrate(x * (integrate(y, (y, 0, eq_y))), (x, 0, 4)) triangle = Polygon(p1, p2, p3) assert (I_xx - triangle.second_moment_of_area(p)[0]) == 0 assert (I_yy - triangle.second_moment_of_area(p)[1]) == 0 assert (I_xy - triangle.second_moment_of_area(p)[2]) == 0 # rectangle p1, p2, p3, p4=[(0, 0), (4, 0), (4, 2), (0, 2)] I_yy = integrate((x**2) * integrate(1, (y, 0, 2)), (x, 0, 4)) I_xx = integrate(1 * integrate(y**2, (y, 0, 2)), (x, 0, 4)) I_xy = integrate(x * integrate(y, (y, 0, 2)), (x, 0, 4)) rectangle = Polygon(p1, p2, p3, p4) assert (I_xx - rectangle.second_moment_of_area(p)[0]) == 0 assert (I_yy - rectangle.second_moment_of_area(p)[1]) == 0 assert (I_xy - rectangle.second_moment_of_area(p)[2]) == 0 r = RegularPolygon(Point(0, 0), 5, 3) assert r.second_moment_of_area() == (1875*sqrt(3)/S(32), 1875*sqrt(3)/S(32), 0) def test_first_moment(): a, b = symbols('a, b', positive=True) # rectangle p1 = Polygon((0, 0), (a, 0), (a, b), (0, b)) assert p1.first_moment_of_area() == (a*b**2/8, a**2*b/8) assert p1.first_moment_of_area((a/3, b/4)) == (-3*a*b**2/32, -a**2*b/9) p1 = Polygon((0, 0), (40, 0), (40, 30), (0, 30)) assert p1.first_moment_of_area() == (4500, 6000) # triangle p2 = Polygon((0, 0), (a, 0), (a/2, b)) assert p2.first_moment_of_area() == (4*a*b**2/81, a**2*b/24) assert p2.first_moment_of_area((a/8, b/6)) == (-25*a*b**2/648, -5*a**2*b/768) p2 = Polygon((0, 0), (12, 0), (12, 30)) p2.first_moment_of_area() == (1600/3, -640/3) def test_section_modulus_and_polar_second_moment_of_area(): a, b = symbols('a, b', positive=True) x, y = symbols('x, y') rectangle = Polygon((0, b), (0, 0), (a, 0), (a, b)) assert rectangle.section_modulus(Point(x, y)) == (a*b**3/12/(-b/2 + y), a**3*b/12/(-a/2 + x)) assert rectangle.polar_second_moment_of_area() == a**3*b/12 + a*b**3/12 convex = RegularPolygon((0, 0), 1, 6) assert convex.section_modulus() == (Rational(5, 8), sqrt(3)*Rational(5, 16)) assert convex.polar_second_moment_of_area() == 5*sqrt(3)/S(8) concave = Polygon((0, 0), (1, 8), (3, 4), (4, 6), (7, 1)) assert concave.section_modulus() == (Rational(-6371, 429), Rational(-9778, 519)) assert concave.polar_second_moment_of_area() == Rational(-38669, 252) def test_cut_section(): # concave polygon p = Polygon((-1, -1), (1, Rational(5, 2)), (2, 1), (3, Rational(5, 2)), (4, 2), (5, 3), (-1, 3)) l = Line((0, 0), (Rational(9, 2), 3)) p1 = p.cut_section(l)[0] p2 = p.cut_section(l)[1] assert p1 == Polygon( Point2D(Rational(-9, 13), Rational(-6, 13)), Point2D(1, Rational(5, 2)), Point2D(Rational(24, 13), Rational(16, 13)), Point2D(Rational(12, 5), Rational(8, 5)), Point2D(3, Rational(5, 2)), Point2D(Rational(24, 7), Rational(16, 7)), Point2D(Rational(9, 2), 3), Point2D(-1, 3), Point2D(-1, Rational(-2, 3))) assert p2 == Polygon(Point2D(-1, -1), Point2D(Rational(-9, 13), Rational(-6, 13)), Point2D(Rational(24, 13), Rational(16, 13)), Point2D(2, 1), Point2D(Rational(12, 5), Rational(8, 5)), Point2D(Rational(24, 7), Rational(16, 7)), Point2D(4, 2), Point2D(5, 3), Point2D(Rational(9, 2), 3), Point2D(-1, Rational(-2, 3))) # convex polygon p = RegularPolygon(Point2D(0, 0), 6, 6) s = p.cut_section(Line((0, 0), slope=1)) assert s[0] == Polygon(Point2D(-3*sqrt(3) + 9, -3*sqrt(3) + 9), Point2D(3, 3*sqrt(3)), Point2D(-3, 3*sqrt(3)), Point2D(-6, 0), Point2D(-9 + 3*sqrt(3), -9 + 3*sqrt(3))) assert s[1] == Polygon(Point2D(6, 0), Point2D(-3*sqrt(3) + 9, -3*sqrt(3) + 9), Point2D(-9 + 3*sqrt(3), -9 + 3*sqrt(3)), Point2D(-3, -3*sqrt(3)), Point2D(3, -3*sqrt(3))) # case where line does not intersects but coincides with the edge of polygon a, b = 20, 10 t1, t2, t3, t4 = [(0, b), (0, 0), (a, 0), (a, b)] p = Polygon(t1, t2, t3, t4) p1, p2 = p.cut_section(Line((0, b), slope=0)) assert p1 == None assert p2 == Polygon(Point2D(0, 10), Point2D(0, 0), Point2D(20, 0), Point2D(20, 10)) p3, p4 = p.cut_section(Line((0, 0), slope=0)) assert p3 == Polygon(Point2D(0, 10), Point2D(0, 0), Point2D(20, 0), Point2D(20, 10)) assert p4 == None # case where the line does not intersect with a polygon at all raises(ValueError, lambda: p.cut_section(Line((0, a), slope=0))) def test_type_of_triangle(): # Isoceles triangle p1 = Polygon(Point(0, 0), Point(5, 0), Point(2, 4)) assert p1.is_isosceles() == True assert p1.is_scalene() == False assert p1.is_equilateral() == False # Scalene triangle p2 = Polygon (Point(0, 0), Point(0, 2), Point(4, 0)) assert p2.is_isosceles() == False assert p2.is_scalene() == True assert p2.is_equilateral() == False # Equilateral triagle p3 = Polygon(Point(0, 0), Point(6, 0), Point(3, sqrt(27))) assert p3.is_isosceles() == True assert p3.is_scalene() == False assert p3.is_equilateral() == True def test_do_poly_distance(): # Non-intersecting polygons square1 = Polygon (Point(0, 0), Point(0, 1), Point(1, 1), Point(1, 0)) triangle1 = Polygon(Point(1, 2), Point(2, 2), Point(2, 1)) assert square1._do_poly_distance(triangle1) == sqrt(2)/2 # Polygons which sides intersect square2 = Polygon(Point(1, 0), Point(2, 0), Point(2, 1), Point(1, 1)) with warns(UserWarning, \ match="Polygons may intersect producing erroneous output"): assert square1._do_poly_distance(square2) == 0 # Polygons which bodies intersect triangle2 = Polygon(Point(0, -1), Point(2, -1), Point(S.Half, S.Half)) with warns(UserWarning, \ match="Polygons may intersect producing erroneous output"): assert triangle2._do_poly_distance(square1) == 0
0950fcdd9d5382941ca750197f734340d20736c48894f12fc66603a13a40d69a
from sympy.core.numbers import (Rational, oo) from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.functions.elementary.complexes import sign from sympy.functions.elementary.miscellaneous import sqrt from sympy.geometry.ellipse import (Circle, Ellipse) from sympy.geometry.line import (Line, Ray2D, Segment2D) from sympy.geometry.parabola import Parabola from sympy.geometry.point import (Point, Point2D) from sympy.testing.pytest import raises def test_parabola_geom(): a, b = symbols('a b') p1 = Point(0, 0) p2 = Point(3, 7) p3 = Point(0, 4) p4 = Point(6, 0) p5 = Point(a, a) d1 = Line(Point(4, 0), Point(4, 9)) d2 = Line(Point(7, 6), Point(3, 6)) d3 = Line(Point(4, 0), slope=oo) d4 = Line(Point(7, 6), slope=0) d5 = Line(Point(b, a), slope=oo) d6 = Line(Point(a, b), slope=0) half = S.Half pa1 = Parabola(None, d2) pa2 = Parabola(directrix=d1) pa3 = Parabola(p1, d1) pa4 = Parabola(p2, d2) pa5 = Parabola(p2, d4) pa6 = Parabola(p3, d2) pa7 = Parabola(p2, d1) pa8 = Parabola(p4, d1) pa9 = Parabola(p4, d3) pa10 = Parabola(p5, d5) pa11 = Parabola(p5, d6) raises(ValueError, lambda: Parabola(Point(7, 8, 9), Line(Point(6, 7), Point(7, 7)))) raises(NotImplementedError, lambda: Parabola(Point(7, 8), Line(Point(3, 7), Point(2, 9)))) raises(ValueError, lambda: Parabola(Point(0, 2), Line(Point(7, 2), Point(6, 2)))) raises(ValueError, lambda: Parabola(Point(7, 8), Point(3, 8))) # Basic Stuff assert pa1.focus == Point(0, 0) assert pa1.ambient_dimension == S(2) assert pa2 == pa3 assert pa4 != pa7 assert pa6 != pa7 assert pa6.focus == Point2D(0, 4) assert pa6.focal_length == 1 assert pa6.p_parameter == -1 assert pa6.vertex == Point2D(0, 5) assert pa6.eccentricity == 1 assert pa7.focus == Point2D(3, 7) assert pa7.focal_length == half assert pa7.p_parameter == -half assert pa7.vertex == Point2D(7*half, 7) assert pa4.focal_length == half assert pa4.p_parameter == half assert pa4.vertex == Point2D(3, 13*half) assert pa8.focal_length == 1 assert pa8.p_parameter == 1 assert pa8.vertex == Point2D(5, 0) assert pa4.focal_length == pa5.focal_length assert pa4.p_parameter == pa5.p_parameter assert pa4.vertex == pa5.vertex assert pa4.equation() == pa5.equation() assert pa8.focal_length == pa9.focal_length assert pa8.p_parameter == pa9.p_parameter assert pa8.vertex == pa9.vertex assert pa8.equation() == pa9.equation() assert pa10.focal_length == pa11.focal_length == sqrt((a - b) ** 2) / 2 # if a, b real == abs(a - b)/2 assert pa11.vertex == Point(*pa10.vertex[::-1]) == Point(a, a - sqrt((a - b)**2)*sign(a - b)/2) # change axis x->y, y->x on pa10 def test_parabola_intersection(): l1 = Line(Point(1, -2), Point(-1,-2)) l2 = Line(Point(1, 2), Point(-1,2)) l3 = Line(Point(1, 0), Point(-1,0)) p1 = Point(0,0) p2 = Point(0, -2) p3 = Point(120, -12) parabola1 = Parabola(p1, l1) # parabola with parabola assert parabola1.intersection(parabola1) == [parabola1] assert parabola1.intersection(Parabola(p1, l2)) == [Point2D(-2, 0), Point2D(2, 0)] assert parabola1.intersection(Parabola(p2, l3)) == [Point2D(0, -1)] assert parabola1.intersection(Parabola(Point(16, 0), l1)) == [Point2D(8, 15)] assert parabola1.intersection(Parabola(Point(0, 16), l1)) == [Point2D(-6, 8), Point2D(6, 8)] assert parabola1.intersection(Parabola(p3, l3)) == [] # parabola with point assert parabola1.intersection(p1) == [] assert parabola1.intersection(Point2D(0, -1)) == [Point2D(0, -1)] assert parabola1.intersection(Point2D(4, 3)) == [Point2D(4, 3)] # parabola with line assert parabola1.intersection(Line(Point2D(-7, 3), Point(12, 3))) == [Point2D(-4, 3), Point2D(4, 3)] assert parabola1.intersection(Line(Point(-4, -1), Point(4, -1))) == [Point(0, -1)] assert parabola1.intersection(Line(Point(2, 0), Point(0, -2))) == [Point2D(2, 0)] raises(TypeError, lambda: parabola1.intersection(Line(Point(0, 0, 0), Point(1, 1, 1)))) # parabola with segment assert parabola1.intersection(Segment2D((-4, -5), (4, 3))) == [Point2D(0, -1), Point2D(4, 3)] assert parabola1.intersection(Segment2D((0, -5), (0, 6))) == [Point2D(0, -1)] assert parabola1.intersection(Segment2D((-12, -65), (14, -68))) == [] # parabola with ray assert parabola1.intersection(Ray2D((-4, -5), (4, 3))) == [Point2D(0, -1), Point2D(4, 3)] assert parabola1.intersection(Ray2D((0, 7), (1, 14))) == [Point2D(14 + 2*sqrt(57), 105 + 14*sqrt(57))] assert parabola1.intersection(Ray2D((0, 7), (0, 14))) == [] # parabola with ellipse/circle assert parabola1.intersection(Circle(p1, 2)) == [Point2D(-2, 0), Point2D(2, 0)] assert parabola1.intersection(Circle(p2, 1)) == [Point2D(0, -1), Point2D(0, -1)] assert parabola1.intersection(Ellipse(p2, 2, 1)) == [Point2D(0, -1), Point2D(0, -1)] assert parabola1.intersection(Ellipse(Point(0, 19), 5, 7)) == [] assert parabola1.intersection(Ellipse((0, 3), 12, 4)) == \ [Point2D(0, -1), Point2D(0, -1), Point2D(-4*sqrt(17)/3, Rational(59, 9)), Point2D(4*sqrt(17)/3, Rational(59, 9))] # parabola with unsupported type raises(TypeError, lambda: parabola1.intersection(2))
c4be2e45601a978997671b9085cb3d40e86ce8c85e09b14dc87d5ab2afdad884
from sympy.core.containers import Tuple from sympy.core.numbers import (Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.hyperbolic import asinh from sympy.functions.elementary.miscellaneous import sqrt from sympy.geometry import Curve, Line, Point, Ellipse, Ray, Segment, Circle, Polygon, RegularPolygon from sympy.testing.pytest import raises, slow def test_curve(): x = Symbol('x', real=True) s = Symbol('s') z = Symbol('z') # this curve is independent of the indicated parameter c = Curve([2*s, s**2], (z, 0, 2)) assert c.parameter == z assert c.functions == (2*s, s**2) assert c.arbitrary_point() == Point(2*s, s**2) assert c.arbitrary_point(z) == Point(2*s, s**2) # this is how it is normally used c = Curve([2*s, s**2], (s, 0, 2)) assert c.parameter == s assert c.functions == (2*s, s**2) t = Symbol('t') # the t returned as assumptions assert c.arbitrary_point() != Point(2*t, t**2) t = Symbol('t', real=True) # now t has the same assumptions so the test passes assert c.arbitrary_point() == Point(2*t, t**2) assert c.arbitrary_point(z) == Point(2*z, z**2) assert c.arbitrary_point(c.parameter) == Point(2*s, s**2) assert c.arbitrary_point(None) == Point(2*s, s**2) assert c.plot_interval() == [t, 0, 2] assert c.plot_interval(z) == [z, 0, 2] assert Curve([x, x], (x, 0, 1)).rotate(pi/2) == Curve([-x, x], (x, 0, 1)) assert Curve([x, x], (x, 0, 1)).rotate(pi/2, (1, 2)).scale(2, 3).translate( 1, 3).arbitrary_point(s) == \ Line((0, 0), (1, 1)).rotate(pi/2, (1, 2)).scale(2, 3).translate( 1, 3).arbitrary_point(s) == \ Point(-2*s + 7, 3*s + 6) raises(ValueError, lambda: Curve((s), (s, 1, 2))) raises(ValueError, lambda: Curve((x, x * 2), (1, x))) raises(ValueError, lambda: Curve((s, s + t), (s, 1, 2)).arbitrary_point()) raises(ValueError, lambda: Curve((s, s + t), (t, 1, 2)).arbitrary_point(s)) @slow def test_free_symbols(): a, b, c, d, e, f, s = symbols('a:f,s') assert Point(a, b).free_symbols == {a, b} assert Line((a, b), (c, d)).free_symbols == {a, b, c, d} assert Ray((a, b), (c, d)).free_symbols == {a, b, c, d} assert Ray((a, b), angle=c).free_symbols == {a, b, c} assert Segment((a, b), (c, d)).free_symbols == {a, b, c, d} assert Line((a, b), slope=c).free_symbols == {a, b, c} assert Curve((a*s, b*s), (s, c, d)).free_symbols == {a, b, c, d} assert Ellipse((a, b), c, d).free_symbols == {a, b, c, d} assert Ellipse((a, b), c, eccentricity=d).free_symbols == \ {a, b, c, d} assert Ellipse((a, b), vradius=c, eccentricity=d).free_symbols == \ {a, b, c, d} assert Circle((a, b), c).free_symbols == {a, b, c} assert Circle((a, b), (c, d), (e, f)).free_symbols == \ {e, d, c, b, f, a} assert Polygon((a, b), (c, d), (e, f)).free_symbols == \ {e, b, d, f, a, c} assert RegularPolygon((a, b), c, d, e).free_symbols == {e, a, b, c, d} def test_transform(): x = Symbol('x', real=True) y = Symbol('y', real=True) c = Curve((x, x**2), (x, 0, 1)) cout = Curve((2*x - 4, 3*x**2 - 10), (x, 0, 1)) pts = [Point(0, 0), Point(S.Half, Rational(1, 4)), Point(1, 1)] pts_out = [Point(-4, -10), Point(-3, Rational(-37, 4)), Point(-2, -7)] assert c.scale(2, 3, (4, 5)) == cout assert [c.subs(x, xi/2) for xi in Tuple(0, 1, 2)] == pts assert [cout.subs(x, xi/2) for xi in Tuple(0, 1, 2)] == pts_out assert Curve((x + y, 3*x), (x, 0, 1)).subs(y, S.Half) == \ Curve((x + S.Half, 3*x), (x, 0, 1)) assert Curve((x, 3*x), (x, 0, 1)).translate(4, 5) == \ Curve((x + 4, 3*x + 5), (x, 0, 1)) def test_length(): t = Symbol('t', real=True) c1 = Curve((t, 0), (t, 0, 1)) assert c1.length == 1 c2 = Curve((t, t), (t, 0, 1)) assert c2.length == sqrt(2) c3 = Curve((t ** 2, t), (t, 2, 5)) assert c3.length == -sqrt(17) - asinh(4) / 4 + asinh(10) / 4 + 5 * sqrt(101) / 2 def test_parameter_value(): t = Symbol('t') C = Curve([2*t, t**2], (t, 0, 2)) assert C.parameter_value((2, 1), t) == {t: 1} raises(ValueError, lambda: C.parameter_value((2, 0), t)) def test_issue_17997(): t, s = symbols('t s') c = Curve((t, t**2), (t, 0, 10)) p = Curve([2*s, s**2], (s, 0, 2)) assert c(2) == Point(2, 4) assert p(1) == Point(2, 1)
1186eaa2302d6107416866a1584bc67bfc89821aeb73e6624e3c46ae3747cf27
from sympy.holonomic import (DifferentialOperator, HolonomicFunction, DifferentialOperators, from_hyper, from_meijerg, expr_to_holonomic) from sympy.holonomic.recurrence import RecurrenceOperators, HolonomicSequence from sympy.core import EulerGamma from sympy.core.numbers import (I, Rational, pi) from sympy.core.singleton import S from sympy.core.symbol import (Symbol, symbols) from sympy.functions.elementary.exponential import (exp, log) from sympy.functions.elementary.hyperbolic import (asinh, cosh) from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import (cos, sin) from sympy.functions.special.bessel import besselj from sympy.functions.special.beta_functions import beta from sympy.functions.special.error_functions import (Ci, Si, erf, erfc) from sympy.functions.special.gamma_functions import gamma from sympy.functions.special.hyper import (hyper, meijerg) from sympy.printing.str import sstr from sympy.series.order import O from sympy.simplify.hyperexpand import hyperexpand from sympy.polys.domains.integerring import ZZ from sympy.polys.domains.rationalfield import QQ from sympy.polys.domains.realfield import RR def test_DifferentialOperator(): x = symbols('x') R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') assert Dx == R.derivative_operator assert Dx == DifferentialOperator([R.base.zero, R.base.one], R) assert x * Dx + x**2 * Dx**2 == DifferentialOperator([0, x, x**2], R) assert (x**2 + 1) + Dx + x * \ Dx**5 == DifferentialOperator([x**2 + 1, 1, 0, 0, 0, x], R) assert (x * Dx + x**2 + 1 - Dx * (x**3 + x))**3 == (-48 * x**6) + \ (-57 * x**7) * Dx + (-15 * x**8) * Dx**2 + (-x**9) * Dx**3 p = (x * Dx**2 + (x**2 + 3) * Dx**5) * (Dx + x**2) q = (2 * x) + (4 * x**2) * Dx + (x**3) * Dx**2 + \ (20 * x**2 + x + 60) * Dx**3 + (10 * x**3 + 30 * x) * Dx**4 + \ (x**4 + 3 * x**2) * Dx**5 + (x**2 + 3) * Dx**6 assert p == q def test_HolonomicFunction_addition(): x = symbols('x') R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') p = HolonomicFunction(Dx**2 * x, x) q = HolonomicFunction((2) * Dx + (x) * Dx**2, x) assert p == q p = HolonomicFunction(x * Dx + 1, x) q = HolonomicFunction(Dx + 1, x) r = HolonomicFunction((x - 2) + (x**2 - 2) * Dx + (x**2 - x) * Dx**2, x) assert p + q == r p = HolonomicFunction(x * Dx + Dx**2 * (x**2 + 2), x) q = HolonomicFunction(Dx - 3, x) r = HolonomicFunction((-54 * x**2 - 126 * x - 150) + (-135 * x**3 - 252 * x**2 - 270 * x + 140) * Dx +\ (-27 * x**4 - 24 * x**2 + 14 * x - 150) * Dx**2 + \ (9 * x**4 + 15 * x**3 + 38 * x**2 + 30 * x +40) * Dx**3, x) assert p + q == r p = HolonomicFunction(Dx**5 - 1, x) q = HolonomicFunction(x**3 + Dx, x) r = HolonomicFunction((-x**18 + 45*x**14 - 525*x**10 + 1575*x**6 - x**3 - 630*x**2) + \ (-x**15 + 30*x**11 - 195*x**7 + 210*x**3 - 1)*Dx + (x**18 - 45*x**14 + 525*x**10 - \ 1575*x**6 + x**3 + 630*x**2)*Dx**5 + (x**15 - 30*x**11 + 195*x**7 - 210*x**3 + \ 1)*Dx**6, x) assert p+q == r p = x**2 + 3*x + 8 q = x**3 - 7*x + 5 p = p*Dx - p.diff() q = q*Dx - q.diff() r = HolonomicFunction(p, x) + HolonomicFunction(q, x) s = HolonomicFunction((6*x**2 + 18*x + 14) + (-4*x**3 - 18*x**2 - 62*x + 10)*Dx +\ (x**4 + 6*x**3 + 31*x**2 - 10*x - 71)*Dx**2, x) assert r == s def test_HolonomicFunction_multiplication(): x = symbols('x') R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') p = HolonomicFunction(Dx+x+x*Dx**2, x) q = HolonomicFunction(x*Dx+Dx*x+Dx**2, x) r = HolonomicFunction((8*x**6 + 4*x**4 + 6*x**2 + 3) + (24*x**5 - 4*x**3 + 24*x)*Dx + \ (8*x**6 + 20*x**4 + 12*x**2 + 2)*Dx**2 + (8*x**5 + 4*x**3 + 4*x)*Dx**3 + \ (2*x**4 + x**2)*Dx**4, x) assert p*q == r p = HolonomicFunction(Dx**2+1, x) q = HolonomicFunction(Dx-1, x) r = HolonomicFunction((2) + (-2)*Dx + (1)*Dx**2, x) assert p*q == r p = HolonomicFunction(Dx**2+1+x+Dx, x) q = HolonomicFunction((Dx*x-1)**2, x) r = HolonomicFunction((4*x**7 + 11*x**6 + 16*x**5 + 4*x**4 - 6*x**3 - 7*x**2 - 8*x - 2) + \ (8*x**6 + 26*x**5 + 24*x**4 - 3*x**3 - 11*x**2 - 6*x - 2)*Dx + \ (8*x**6 + 18*x**5 + 15*x**4 - 3*x**3 - 6*x**2 - 6*x - 2)*Dx**2 + (8*x**5 + \ 10*x**4 + 6*x**3 - 2*x**2 - 4*x)*Dx**3 + (4*x**5 + 3*x**4 - x**2)*Dx**4, x) assert p*q == r p = HolonomicFunction(x*Dx**2-1, x) q = HolonomicFunction(Dx*x-x, x) r = HolonomicFunction((x - 3) + (-2*x + 2)*Dx + (x)*Dx**2, x) assert p*q == r def test_addition_initial_condition(): x = symbols('x') R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') p = HolonomicFunction(Dx-1, x, 0, [3]) q = HolonomicFunction(Dx**2+1, x, 0, [1, 0]) r = HolonomicFunction(-1 + Dx - Dx**2 + Dx**3, x, 0, [4, 3, 2]) assert p + q == r p = HolonomicFunction(Dx - x + Dx**2, x, 0, [1, 2]) q = HolonomicFunction(Dx**2 + x, x, 0, [1, 0]) r = HolonomicFunction((-x**4 - x**3/4 - x**2 + Rational(1, 4)) + (x**3 + x**2/4 + x*Rational(3, 4) + 1)*Dx + \ (x*Rational(-3, 2) + Rational(7, 4))*Dx**2 + (x**2 - x*Rational(7, 4) + Rational(1, 4))*Dx**3 + (x**2 + x/4 + S.Half)*Dx**4, x, 0, [2, 2, -2, 2]) assert p + q == r p = HolonomicFunction(Dx**2 + 4*x*Dx + x**2, x, 0, [3, 4]) q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 1]) r = HolonomicFunction((x**6 + 2*x**4 - 5*x**2 - 6) + (4*x**5 + 36*x**3 - 32*x)*Dx + \ (x**6 + 3*x**4 + 5*x**2 - 9)*Dx**2 + (4*x**5 + 36*x**3 - 32*x)*Dx**3 + (x**4 + \ 10*x**2 - 3)*Dx**4, x, 0, [4, 5, -1, -17]) assert p + q == r q = HolonomicFunction(Dx**3 + x, x, 2, [3, 0, 1]) p = HolonomicFunction(Dx - 1, x, 2, [1]) r = HolonomicFunction((-x**2 - x + 1) + (x**2 + x)*Dx + (-x - 2)*Dx**3 + \ (x + 1)*Dx**4, x, 2, [4, 1, 2, -5 ]) assert p + q == r p = expr_to_holonomic(sin(x)) q = expr_to_holonomic(1/x, x0=1) r = HolonomicFunction((x**2 + 6) + (x**3 + 2*x)*Dx + (x**2 + 6)*Dx**2 + (x**3 + 2*x)*Dx**3, \ x, 1, [sin(1) + 1, -1 + cos(1), -sin(1) + 2]) assert p + q == r C_1 = symbols('C_1') p = expr_to_holonomic(sqrt(x)) q = expr_to_holonomic(sqrt(x**2-x)) r = (p + q).to_expr().subs(C_1, -I/2).expand() assert r == I*sqrt(x)*sqrt(-x + 1) + sqrt(x) def test_multiplication_initial_condition(): x = symbols('x') R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') p = HolonomicFunction(Dx**2 + x*Dx - 1, x, 0, [3, 1]) q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 1]) r = HolonomicFunction((x**4 + 14*x**2 + 60) + 4*x*Dx + (x**4 + 9*x**2 + 20)*Dx**2 + \ (2*x**3 + 18*x)*Dx**3 + (x**2 + 10)*Dx**4, x, 0, [3, 4, 2, 3]) assert p * q == r p = HolonomicFunction(Dx**2 + x, x, 0, [1, 0]) q = HolonomicFunction(Dx**3 - x**2, x, 0, [3, 3, 3]) r = HolonomicFunction((x**8 - 37*x**7/27 - 10*x**6/27 - 164*x**5/9 - 184*x**4/9 + \ 160*x**3/27 + 404*x**2/9 + 8*x + Rational(40, 3)) + (6*x**7 - 128*x**6/9 - 98*x**5/9 - 28*x**4/9 + \ 8*x**3/9 + 28*x**2 + x*Rational(40, 9) - 40)*Dx + (3*x**6 - 82*x**5/9 + 76*x**4/9 + 4*x**3/3 + \ 220*x**2/9 - x*Rational(80, 3))*Dx**2 + (-2*x**6 + 128*x**5/27 - 2*x**4/3 -80*x**2/9 + Rational(200, 9))*Dx**3 + \ (3*x**5 - 64*x**4/9 - 28*x**3/9 + 6*x**2 - x*Rational(20, 9) - Rational(20, 3))*Dx**4 + (-4*x**3 + 64*x**2/9 + \ x*Rational(8, 3))*Dx**5 + (x**4 - 64*x**3/27 - 4*x**2/3 + Rational(20, 9))*Dx**6, x, 0, [3, 3, 3, -3, -12, -24]) assert p * q == r p = HolonomicFunction(Dx - 1, x, 0, [2]) q = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) r = HolonomicFunction(2 -2*Dx + Dx**2, x, 0, [0, 2]) assert p * q == r q = HolonomicFunction(x*Dx**2 + 1 + 2*Dx, x, 0,[0, 1]) r = HolonomicFunction((x - 1) + (-2*x + 2)*Dx + x*Dx**2, x, 0, [0, 2]) assert p * q == r p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 3]) q = HolonomicFunction(Dx**3 + 1, x, 0, [1, 2, 1]) r = HolonomicFunction(6*Dx + 3*Dx**2 + 2*Dx**3 - 3*Dx**4 + Dx**6, x, 0, [1, 5, 14, 17, 17, 2]) assert p * q == r p = expr_to_holonomic(sin(x)) q = expr_to_holonomic(1/x, x0=1) r = HolonomicFunction(x + 2*Dx + x*Dx**2, x, 1, [sin(1), -sin(1) + cos(1)]) assert p * q == r p = expr_to_holonomic(sqrt(x)) q = expr_to_holonomic(sqrt(x**2-x)) r = (p * q).to_expr() assert r == I*x*sqrt(-x + 1) def test_HolonomicFunction_composition(): x = symbols('x') R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') p = HolonomicFunction(Dx-1, x).composition(x**2+x) r = HolonomicFunction((-2*x - 1) + Dx, x) assert p == r p = HolonomicFunction(Dx**2+1, x).composition(x**5+x**2+1) r = HolonomicFunction((125*x**12 + 150*x**9 + 60*x**6 + 8*x**3) + (-20*x**3 - 2)*Dx + \ (5*x**4 + 2*x)*Dx**2, x) assert p == r p = HolonomicFunction(Dx**2*x+x, x).composition(2*x**3+x**2+1) r = HolonomicFunction((216*x**9 + 324*x**8 + 180*x**7 + 152*x**6 + 112*x**5 + \ 36*x**4 + 4*x**3) + (24*x**4 + 16*x**3 + 3*x**2 - 6*x - 1)*Dx + (6*x**5 + 5*x**4 + \ x**3 + 3*x**2 + x)*Dx**2, x) assert p == r p = HolonomicFunction(Dx**2+1, x).composition(1-x**2) r = HolonomicFunction((4*x**3) - Dx + x*Dx**2, x) assert p == r p = HolonomicFunction(Dx**2+1, x).composition(x - 2/(x**2 + 1)) r = HolonomicFunction((x**12 + 6*x**10 + 12*x**9 + 15*x**8 + 48*x**7 + 68*x**6 + \ 72*x**5 + 111*x**4 + 112*x**3 + 54*x**2 + 12*x + 1) + (12*x**8 + 32*x**6 + \ 24*x**4 - 4)*Dx + (x**12 + 6*x**10 + 4*x**9 + 15*x**8 + 16*x**7 + 20*x**6 + 24*x**5+ \ 15*x**4 + 16*x**3 + 6*x**2 + 4*x + 1)*Dx**2, x) assert p == r def test_from_hyper(): x = symbols('x') R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') p = hyper([1, 1], [Rational(3, 2)], x**2/4) q = HolonomicFunction((4*x) + (5*x**2 - 8)*Dx + (x**3 - 4*x)*Dx**2, x, 1, [2*sqrt(3)*pi/9, -4*sqrt(3)*pi/27 + Rational(4, 3)]) r = from_hyper(p) assert r == q p = from_hyper(hyper([1], [Rational(3, 2)], x**2/4)) q = HolonomicFunction(-x + (-x**2/2 + 2)*Dx + x*Dx**2, x) # x0 = 1 y0 = '[sqrt(pi)*exp(1/4)*erf(1/2), -sqrt(pi)*exp(1/4)*erf(1/2)/2 + 1]' assert sstr(p.y0) == y0 assert q.annihilator == p.annihilator def test_from_meijerg(): x = symbols('x') R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') p = from_meijerg(meijerg(([], [Rational(3, 2)]), ([S.Half], [S.Half, 1]), x)) q = HolonomicFunction(x/2 - Rational(1, 4) + (-x**2 + x/4)*Dx + x**2*Dx**2 + x**3*Dx**3, x, 1, \ [1/sqrt(pi), 1/(2*sqrt(pi)), -1/(4*sqrt(pi))]) assert p == q p = from_meijerg(meijerg(([], []), ([0], []), x)) q = HolonomicFunction(1 + Dx, x, 0, [1]) assert p == q p = from_meijerg(meijerg(([1], []), ([S.Half], [0]), x)) q = HolonomicFunction((x + S.Half)*Dx + x*Dx**2, x, 1, [sqrt(pi)*erf(1), exp(-1)]) assert p == q p = from_meijerg(meijerg(([0], [1]), ([0], []), 2*x**2)) q = HolonomicFunction((3*x**2 - 1)*Dx + x**3*Dx**2, x, 1, [-exp(Rational(-1, 2)) + 1, -exp(Rational(-1, 2))]) assert p == q def test_to_Sequence(): x = symbols('x') R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') n = symbols('n', integer=True) _, Sn = RecurrenceOperators(ZZ.old_poly_ring(n), 'Sn') p = HolonomicFunction(x**2*Dx**4 + x + Dx, x).to_sequence() q = [(HolonomicSequence(1 + (n + 2)*Sn**2 + (n**4 + 6*n**3 + 11*n**2 + 6*n)*Sn**3), 0, 1)] assert p == q p = HolonomicFunction(x**2*Dx**4 + x**3 + Dx**2, x).to_sequence() q = [(HolonomicSequence(1 + (n**4 + 14*n**3 + 72*n**2 + 163*n + 140)*Sn**5), 0, 0)] assert p == q p = HolonomicFunction(x**3*Dx**4 + 1 + Dx**2, x).to_sequence() q = [(HolonomicSequence(1 + (n**4 - 2*n**3 - n**2 + 2*n)*Sn + (n**2 + 3*n + 2)*Sn**2), 0, 0)] assert p == q p = HolonomicFunction(3*x**3*Dx**4 + 2*x*Dx + x*Dx**3, x).to_sequence() q = [(HolonomicSequence(2*n + (3*n**4 - 6*n**3 - 3*n**2 + 6*n)*Sn + (n**3 + 3*n**2 + 2*n)*Sn**2), 0, 1)] assert p == q def test_to_Sequence_Initial_Coniditons(): x = symbols('x') R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') n = symbols('n', integer=True) _, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn') p = HolonomicFunction(Dx - 1, x, 0, [1]).to_sequence() q = [(HolonomicSequence(-1 + (n + 1)*Sn, 1), 0)] assert p == q p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]).to_sequence() q = [(HolonomicSequence(1 + (n**2 + 3*n + 2)*Sn**2, [0, 1]), 0)] assert p == q p = HolonomicFunction(Dx**2 + 1 + x**3*Dx, x, 0, [2, 3]).to_sequence() q = [(HolonomicSequence(n + Sn**2 + (n**2 + 7*n + 12)*Sn**4, [2, 3, -1, Rational(-1, 2), Rational(1, 12)]), 1)] assert p == q p = HolonomicFunction(x**3*Dx**5 + 1 + Dx, x).to_sequence() q = [(HolonomicSequence(1 + (n + 1)*Sn + (n**5 - 5*n**3 + 4*n)*Sn**2), 0, 3)] assert p == q C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3') p = expr_to_holonomic(log(1+x**2)) q = [(HolonomicSequence(n**2 + (n**2 + 2*n)*Sn**2, [0, 0, C_2]), 0, 1)] assert p.to_sequence() == q p = p.diff() q = [(HolonomicSequence((n + 2) + (n + 2)*Sn**2, [C_0, 0]), 1, 0)] assert p.to_sequence() == q p = expr_to_holonomic(erf(x) + x).to_sequence() q = [(HolonomicSequence((2*n**2 - 2*n) + (n**3 + 2*n**2 - n - 2)*Sn**2, [0, 1 + 2/sqrt(pi), 0, C_3]), 0, 2)] assert p == q def test_series(): x = symbols('x') R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') p = HolonomicFunction(Dx**2 + 2*x*Dx, x, 0, [0, 1]).series(n=10) q = x - x**3/3 + x**5/10 - x**7/42 + x**9/216 + O(x**10) assert p == q p = HolonomicFunction(Dx - 1, x).composition(x**2, 0, [1]) # e^(x**2) q = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]) # cos(x) r = (p * q).series(n=10) # expansion of cos(x) * exp(x**2) s = 1 + x**2/2 + x**4/24 - 31*x**6/720 - 179*x**8/8064 + O(x**10) assert r == s t = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]) # log(1 + x) r = (p * t + q).series(n=10) s = 1 + x - x**2 + 4*x**3/3 - 17*x**4/24 + 31*x**5/30 - 481*x**6/720 +\ 71*x**7/105 - 20159*x**8/40320 + 379*x**9/840 + O(x**10) assert r == s p = HolonomicFunction((6+6*x-3*x**2) - (10*x-3*x**2-3*x**3)*Dx + \ (4-6*x**3+2*x**4)*Dx**2, x, 0, [0, 1]).series(n=7) q = x + x**3/6 - 3*x**4/16 + x**5/20 - 23*x**6/960 + O(x**7) assert p == q p = HolonomicFunction((6+6*x-3*x**2) - (10*x-3*x**2-3*x**3)*Dx + \ (4-6*x**3+2*x**4)*Dx**2, x, 0, [1, 0]).series(n=7) q = 1 - 3*x**2/4 - x**3/4 - 5*x**4/32 - 3*x**5/40 - 17*x**6/384 + O(x**7) assert p == q p = expr_to_holonomic(erf(x) + x).series(n=10) C_3 = symbols('C_3') q = (erf(x) + x).series(n=10) assert p.subs(C_3, -2/(3*sqrt(pi))) == q assert expr_to_holonomic(sqrt(x**3 + x)).series(n=10) == sqrt(x**3 + x).series(n=10) assert expr_to_holonomic((2*x - 3*x**2)**Rational(1, 3)).series() == ((2*x - 3*x**2)**Rational(1, 3)).series() assert expr_to_holonomic(sqrt(x**2-x)).series() == (sqrt(x**2-x)).series() assert expr_to_holonomic(cos(x)**2/x**2, y0={-2: [1, 0, -1]}).series(n=10) == (cos(x)**2/x**2).series(n=10) assert expr_to_holonomic(cos(x)**2/x**2, x0=1).series(n=10).together() == (cos(x)**2/x**2).series(n=10, x0=1).together() assert expr_to_holonomic(cos(x-1)**2/(x-1)**2, x0=1, y0={-2: [1, 0, -1]}).series(n=10) \ == (cos(x-1)**2/(x-1)**2).series(x0=1, n=10) def test_evalf_euler(): x = symbols('x') R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') # log(1+x) p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]) # path taken is a straight line from 0 to 1, on the real axis r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] s = '0.699525841805253' # approx. equal to log(2) i.e. 0.693147180559945 assert sstr(p.evalf(r, method='Euler')[-1]) == s # path taken is a traingle 0-->1+i-->2 r = [0.1 + 0.1*I] for i in range(9): r.append(r[-1]+0.1+0.1*I) for i in range(10): r.append(r[-1]+0.1-0.1*I) # close to the exact solution 1.09861228866811 # imaginary part also close to zero s = '1.07530466271334 - 0.0251200594793912*I' assert sstr(p.evalf(r, method='Euler')[-1]) == s # sin(x) p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) s = '0.905546532085401 - 6.93889390390723e-18*I' assert sstr(p.evalf(r, method='Euler')[-1]) == s # computing sin(pi/2) using this method # using a linear path from 0 to pi/2 r = [0.1] for i in range(14): r.append(r[-1] + 0.1) r.append(pi/2) s = '1.08016557252834' # close to 1.0 (exact solution) assert sstr(p.evalf(r, method='Euler')[-1]) == s # trying different path, a rectangle (0-->i-->pi/2 + i-->pi/2) # computing the same value sin(pi/2) using different path r = [0.1*I] for i in range(9): r.append(r[-1]+0.1*I) for i in range(15): r.append(r[-1]+0.1) r.append(pi/2+I) for i in range(10): r.append(r[-1]-0.1*I) # close to 1.0 s = '0.976882381836257 - 1.65557671738537e-16*I' assert sstr(p.evalf(r, method='Euler')[-1]) == s # cos(x) p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]) # compute cos(pi) along 0-->pi r = [0.05] for i in range(61): r.append(r[-1]+0.05) r.append(pi) # close to -1 (exact answer) s = '-1.08140824719196' assert sstr(p.evalf(r, method='Euler')[-1]) == s # a rectangular path (0 -> i -> 2+i -> 2) r = [0.1*I] for i in range(9): r.append(r[-1]+0.1*I) for i in range(20): r.append(r[-1]+0.1) for i in range(10): r.append(r[-1]-0.1*I) p = HolonomicFunction(Dx**2 + 1, x, 0, [1,1]).evalf(r, method='Euler') s = '0.501421652861245 - 3.88578058618805e-16*I' assert sstr(p[-1]) == s def test_evalf_rk4(): x = symbols('x') R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') # log(1+x) p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]) # path taken is a straight line from 0 to 1, on the real axis r = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1] s = '0.693146363174626' # approx. equal to log(2) i.e. 0.693147180559945 assert sstr(p.evalf(r)[-1]) == s # path taken is a traingle 0-->1+i-->2 r = [0.1 + 0.1*I] for i in range(9): r.append(r[-1]+0.1+0.1*I) for i in range(10): r.append(r[-1]+0.1-0.1*I) # close to the exact solution 1.09861228866811 # imaginary part also close to zero s = '1.098616 + 1.36083e-7*I' assert sstr(p.evalf(r)[-1].n(7)) == s # sin(x) p = HolonomicFunction(Dx**2 + 1, x, 0, [0, 1]) s = '0.90929463522785 + 1.52655665885959e-16*I' assert sstr(p.evalf(r)[-1]) == s # computing sin(pi/2) using this method # using a linear path from 0 to pi/2 r = [0.1] for i in range(14): r.append(r[-1] + 0.1) r.append(pi/2) s = '0.999999895088917' # close to 1.0 (exact solution) assert sstr(p.evalf(r)[-1]) == s # trying different path, a rectangle (0-->i-->pi/2 + i-->pi/2) # computing the same value sin(pi/2) using different path r = [0.1*I] for i in range(9): r.append(r[-1]+0.1*I) for i in range(15): r.append(r[-1]+0.1) r.append(pi/2+I) for i in range(10): r.append(r[-1]-0.1*I) # close to 1.0 s = '1.00000003415141 + 6.11940487991086e-16*I' assert sstr(p.evalf(r)[-1]) == s # cos(x) p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]) # compute cos(pi) along 0-->pi r = [0.05] for i in range(61): r.append(r[-1]+0.05) r.append(pi) # close to -1 (exact answer) s = '-0.999999993238714' assert sstr(p.evalf(r)[-1]) == s # a rectangular path (0 -> i -> 2+i -> 2) r = [0.1*I] for i in range(9): r.append(r[-1]+0.1*I) for i in range(20): r.append(r[-1]+0.1) for i in range(10): r.append(r[-1]-0.1*I) p = HolonomicFunction(Dx**2 + 1, x, 0, [1,1]).evalf(r) s = '0.493152791638442 - 1.41553435639707e-15*I' assert sstr(p[-1]) == s def test_expr_to_holonomic(): x = symbols('x') R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') p = expr_to_holonomic((sin(x)/x)**2) q = HolonomicFunction(8*x + (4*x**2 + 6)*Dx + 6*x*Dx**2 + x**2*Dx**3, x, 0, \ [1, 0, Rational(-2, 3)]) assert p == q p = expr_to_holonomic(1/(1+x**2)**2) q = HolonomicFunction(4*x + (x**2 + 1)*Dx, x, 0, [1]) assert p == q p = expr_to_holonomic(exp(x)*sin(x)+x*log(1+x)) q = HolonomicFunction((2*x**3 + 10*x**2 + 20*x + 18) + (-2*x**4 - 10*x**3 - 20*x**2 \ - 18*x)*Dx + (2*x**5 + 6*x**4 + 7*x**3 + 8*x**2 + 10*x - 4)*Dx**2 + \ (-2*x**5 - 5*x**4 - 2*x**3 + 2*x**2 - x + 4)*Dx**3 + (x**5 + 2*x**4 - x**3 - \ 7*x**2/2 + x + Rational(5, 2))*Dx**4, x, 0, [0, 1, 4, -1]) assert p == q p = expr_to_holonomic(x*exp(x)+cos(x)+1) q = HolonomicFunction((-x - 3)*Dx + (x + 2)*Dx**2 + (-x - 3)*Dx**3 + (x + 2)*Dx**4, x, \ 0, [2, 1, 1, 3]) assert p == q assert (x*exp(x)+cos(x)+1).series(n=10) == p.series(n=10) p = expr_to_holonomic(log(1 + x)**2 + 1) q = HolonomicFunction(Dx + (3*x + 3)*Dx**2 + (x**2 + 2*x + 1)*Dx**3, x, 0, [1, 0, 2]) assert p == q p = expr_to_holonomic(erf(x)**2 + x) q = HolonomicFunction((8*x**4 - 2*x**2 + 2)*Dx**2 + (6*x**3 - x/2)*Dx**3 + \ (x**2+ Rational(1, 4))*Dx**4, x, 0, [0, 1, 8/pi, 0]) assert p == q p = expr_to_holonomic(cosh(x)*x) q = HolonomicFunction((-x**2 + 2) -2*x*Dx + x**2*Dx**2, x, 0, [0, 1]) assert p == q p = expr_to_holonomic(besselj(2, x)) q = HolonomicFunction((x**2 - 4) + x*Dx + x**2*Dx**2, x, 0, [0, 0]) assert p == q p = expr_to_holonomic(besselj(0, x) + exp(x)) q = HolonomicFunction((-x**2 - x/2 + S.Half) + (x**2 - x/2 - Rational(3, 2))*Dx + (-x**2 + x/2 + 1)*Dx**2 +\ (x**2 + x/2)*Dx**3, x, 0, [2, 1, S.Half]) assert p == q p = expr_to_holonomic(sin(x)**2/x) q = HolonomicFunction(4 + 4*x*Dx + 3*Dx**2 + x*Dx**3, x, 0, [0, 1, 0]) assert p == q p = expr_to_holonomic(sin(x)**2/x, x0=2) q = HolonomicFunction((4) + (4*x)*Dx + (3)*Dx**2 + (x)*Dx**3, x, 2, [sin(2)**2/2, sin(2)*cos(2) - sin(2)**2/4, -3*sin(2)**2/4 + cos(2)**2 - sin(2)*cos(2)]) assert p == q p = expr_to_holonomic(log(x)/2 - Ci(2*x)/2 + Ci(2)/2) q = HolonomicFunction(4*Dx + 4*x*Dx**2 + 3*Dx**3 + x*Dx**4, x, 0, \ [-log(2)/2 - EulerGamma/2 + Ci(2)/2, 0, 1, 0]) assert p == q p = p.to_expr() q = log(x)/2 - Ci(2*x)/2 + Ci(2)/2 assert p == q p = expr_to_holonomic(x**S.Half, x0=1) q = HolonomicFunction(x*Dx - S.Half, x, 1, [1]) assert p == q p = expr_to_holonomic(sqrt(1 + x**2)) q = HolonomicFunction((-x) + (x**2 + 1)*Dx, x, 0, [1]) assert p == q assert (expr_to_holonomic(sqrt(x) + sqrt(2*x)).to_expr()-\ (sqrt(x) + sqrt(2*x))).simplify() == 0 assert expr_to_holonomic(3*x+2*sqrt(x)).to_expr() == 3*x+2*sqrt(x) p = expr_to_holonomic((x**4+x**3+5*x**2+3*x+2)/x**2, lenics=3) q = HolonomicFunction((-2*x**4 - x**3 + 3*x + 4) + (x**5 + x**4 + 5*x**3 + 3*x**2 + \ 2*x)*Dx, x, 0, {-2: [2, 3, 5]}) assert p == q p = expr_to_holonomic(1/(x-1)**2, lenics=3, x0=1) q = HolonomicFunction((2) + (x - 1)*Dx, x, 1, {-2: [1, 0, 0]}) assert p == q a = symbols("a") p = expr_to_holonomic(sqrt(a*x), x=x) assert p.to_expr() == sqrt(a)*sqrt(x) def test_to_hyper(): x = symbols('x') R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') p = HolonomicFunction(Dx - 2, x, 0, [3]).to_hyper() q = 3 * hyper([], [], 2*x) assert p == q p = hyperexpand(HolonomicFunction((1 + x) * Dx - 3, x, 0, [2]).to_hyper()).expand() q = 2*x**3 + 6*x**2 + 6*x + 2 assert p == q p = HolonomicFunction((1 + x)*Dx**2 + Dx, x, 0, [0, 1]).to_hyper() q = -x**2*hyper((2, 2, 1), (3, 2), -x)/2 + x assert p == q p = HolonomicFunction(2*x*Dx + Dx**2, x, 0, [0, 2/sqrt(pi)]).to_hyper() q = 2*x*hyper((S.Half,), (Rational(3, 2),), -x**2)/sqrt(pi) assert p == q p = hyperexpand(HolonomicFunction(2*x*Dx + Dx**2, x, 0, [1, -2/sqrt(pi)]).to_hyper()) q = erfc(x) assert p.rewrite(erfc) == q p = hyperexpand(HolonomicFunction((x**2 - 1) + x*Dx + x**2*Dx**2, x, 0, [0, S.Half]).to_hyper()) q = besselj(1, x) assert p == q p = hyperexpand(HolonomicFunction(x*Dx**2 + Dx + x, x, 0, [1, 0]).to_hyper()) q = besselj(0, x) assert p == q def test_to_expr(): x = symbols('x') R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') p = HolonomicFunction(Dx - 1, x, 0, [1]).to_expr() q = exp(x) assert p == q p = HolonomicFunction(Dx**2 + 1, x, 0, [1, 0]).to_expr() q = cos(x) assert p == q p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 0]).to_expr() q = cosh(x) assert p == q p = HolonomicFunction(2 + (4*x - 1)*Dx + \ (x**2 - x)*Dx**2, x, 0, [1, 2]).to_expr().expand() q = 1/(x**2 - 2*x + 1) assert p == q p = expr_to_holonomic(sin(x)**2/x).integrate((x, 0, x)).to_expr() q = (sin(x)**2/x).integrate((x, 0, x)) assert p == q C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3') p = expr_to_holonomic(log(1+x**2)).to_expr() q = C_2*log(x**2 + 1) assert p == q p = expr_to_holonomic(log(1+x**2)).diff().to_expr() q = C_0*x/(x**2 + 1) assert p == q p = expr_to_holonomic(erf(x) + x).to_expr() q = 3*C_3*x - 3*sqrt(pi)*C_3*erf(x)/2 + x + 2*x/sqrt(pi) assert p == q p = expr_to_holonomic(sqrt(x), x0=1).to_expr() assert p == sqrt(x) assert expr_to_holonomic(sqrt(x)).to_expr() == sqrt(x) p = expr_to_holonomic(sqrt(1 + x**2)).to_expr() assert p == sqrt(1+x**2) p = expr_to_holonomic((2*x**2 + 1)**Rational(2, 3)).to_expr() assert p == (2*x**2 + 1)**Rational(2, 3) p = expr_to_holonomic(sqrt(-x**2+2*x)).to_expr() assert p == sqrt(x)*sqrt(-x + 2) p = expr_to_holonomic((-2*x**3+7*x)**Rational(2, 3)).to_expr() q = x**Rational(2, 3)*(-2*x**2 + 7)**Rational(2, 3) assert p == q p = from_hyper(hyper((-2, -3), (S.Half, ), x)) s = hyperexpand(hyper((-2, -3), (S.Half, ), x)) D_0 = Symbol('D_0') C_0 = Symbol('C_0') assert (p.to_expr().subs({C_0:1, D_0:0}) - s).simplify() == 0 p.y0 = {0: [1], S.Half: [0]} assert p.to_expr() == s assert expr_to_holonomic(x**5).to_expr() == x**5 assert expr_to_holonomic(2*x**3-3*x**2).to_expr().expand() == \ 2*x**3-3*x**2 a = symbols("a") p = (expr_to_holonomic(1.4*x)*expr_to_holonomic(a*x, x)).to_expr() q = 1.4*a*x**2 assert p == q p = (expr_to_holonomic(1.4*x)+expr_to_holonomic(a*x, x)).to_expr() q = x*(a + 1.4) assert p == q p = (expr_to_holonomic(1.4*x)+expr_to_holonomic(x)).to_expr() assert p == 2.4*x def test_integrate(): x = symbols('x') R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') p = expr_to_holonomic(sin(x)**2/x, x0=1).integrate((x, 2, 3)) q = '0.166270406994788' assert sstr(p) == q p = expr_to_holonomic(sin(x)).integrate((x, 0, x)).to_expr() q = 1 - cos(x) assert p == q p = expr_to_holonomic(sin(x)).integrate((x, 0, 3)) q = 1 - cos(3) assert p == q p = expr_to_holonomic(sin(x)/x, x0=1).integrate((x, 1, 2)) q = '0.659329913368450' assert sstr(p) == q p = expr_to_holonomic(sin(x)**2/x, x0=1).integrate((x, 1, 0)) q = '-0.423690480850035' assert sstr(p) == q p = expr_to_holonomic(sin(x)/x) assert p.integrate(x).to_expr() == Si(x) assert p.integrate((x, 0, 2)) == Si(2) p = expr_to_holonomic(sin(x)**2/x) q = p.to_expr() assert p.integrate(x).to_expr() == q.integrate((x, 0, x)) assert p.integrate((x, 0, 1)) == q.integrate((x, 0, 1)) assert expr_to_holonomic(1/x, x0=1).integrate(x).to_expr() == log(x) p = expr_to_holonomic((x + 1)**3*exp(-x), x0=-1).integrate(x).to_expr() q = (-x**3 - 6*x**2 - 15*x + 6*exp(x + 1) - 16)*exp(-x) assert p == q p = expr_to_holonomic(cos(x)**2/x**2, y0={-2: [1, 0, -1]}).integrate(x).to_expr() q = -Si(2*x) - cos(x)**2/x assert p == q p = expr_to_holonomic(sqrt(x**2+x)).integrate(x).to_expr() q = (x**Rational(3, 2)*(2*x**2 + 3*x + 1) - x*sqrt(x + 1)*asinh(sqrt(x)))/(4*x*sqrt(x + 1)) assert p == q p = expr_to_holonomic(sqrt(x**2+1)).integrate(x).to_expr() q = (sqrt(x**2+1)).integrate(x) assert (p-q).simplify() == 0 p = expr_to_holonomic(1/x**2, y0={-2:[1, 0, 0]}) r = expr_to_holonomic(1/x**2, lenics=3) assert p == r q = expr_to_holonomic(cos(x)**2) assert (r*q).integrate(x).to_expr() == -Si(2*x) - cos(x)**2/x def test_diff(): x, y = symbols('x, y') R, Dx = DifferentialOperators(ZZ.old_poly_ring(x), 'Dx') p = HolonomicFunction(x*Dx**2 + 1, x, 0, [0, 1]) assert p.diff().to_expr() == p.to_expr().diff().simplify() p = HolonomicFunction(Dx**2 - 1, x, 0, [1, 0]) assert p.diff(x, 2).to_expr() == p.to_expr() p = expr_to_holonomic(Si(x)) assert p.diff().to_expr() == sin(x)/x assert p.diff(y) == 0 C_0, C_1, C_2, C_3 = symbols('C_0, C_1, C_2, C_3') q = Si(x) assert p.diff(x).to_expr() == q.diff() assert p.diff(x, 2).to_expr().subs(C_0, Rational(-1, 3)).cancel() == q.diff(x, 2).cancel() assert p.diff(x, 3).series().subs({C_3: Rational(-1, 3), C_0: 0}) == q.diff(x, 3).series() def test_extended_domain_in_expr_to_holonomic(): x = symbols('x') p = expr_to_holonomic(1.2*cos(3.1*x)) assert p.to_expr() == 1.2*cos(3.1*x) assert sstr(p.integrate(x).to_expr()) == '0.387096774193548*sin(3.1*x)' _, Dx = DifferentialOperators(RR.old_poly_ring(x), 'Dx') p = expr_to_holonomic(1.1329138213*x) q = HolonomicFunction((-1.1329138213) + (1.1329138213*x)*Dx, x, 0, {1: [1.1329138213]}) assert p == q assert p.to_expr() == 1.1329138213*x assert sstr(p.integrate((x, 1, 2))) == sstr((1.1329138213*x).integrate((x, 1, 2))) y, z = symbols('y, z') p = expr_to_holonomic(sin(x*y*z), x=x) assert p.to_expr() == sin(x*y*z) assert p.integrate(x).to_expr() == (-cos(x*y*z) + 1)/(y*z) p = expr_to_holonomic(sin(x*y + z), x=x).integrate(x).to_expr() q = (cos(z) - cos(x*y + z))/y assert p == q a = symbols('a') p = expr_to_holonomic(a*x, x) assert p.to_expr() == a*x assert p.integrate(x).to_expr() == a*x**2/2 D_2, C_1 = symbols("D_2, C_1") p = expr_to_holonomic(x) + expr_to_holonomic(1.2*cos(x)) p = p.to_expr().subs(D_2, 0) assert p - x - 1.2*cos(1.0*x) == 0 p = expr_to_holonomic(x) * expr_to_holonomic(1.2*cos(x)) p = p.to_expr().subs(C_1, 0) assert p - 1.2*x*cos(1.0*x) == 0 def test_to_meijerg(): x = symbols('x') assert hyperexpand(expr_to_holonomic(sin(x)).to_meijerg()) == sin(x) assert hyperexpand(expr_to_holonomic(cos(x)).to_meijerg()) == cos(x) assert hyperexpand(expr_to_holonomic(exp(x)).to_meijerg()) == exp(x) assert hyperexpand(expr_to_holonomic(log(x)).to_meijerg()).simplify() == log(x) assert expr_to_holonomic(4*x**2/3 + 7).to_meijerg() == 4*x**2/3 + 7 assert hyperexpand(expr_to_holonomic(besselj(2, x), lenics=3).to_meijerg()) == besselj(2, x) p = hyper((Rational(-1, 2), -3), (), x) assert from_hyper(p).to_meijerg() == hyperexpand(p) p = hyper((S.One, S(3)), (S(2), ), x) assert (hyperexpand(from_hyper(p).to_meijerg()) - hyperexpand(p)).expand() == 0 p = from_hyper(hyper((-2, -3), (S.Half, ), x)) s = hyperexpand(hyper((-2, -3), (S.Half, ), x)) C_0 = Symbol('C_0') C_1 = Symbol('C_1') D_0 = Symbol('D_0') assert (hyperexpand(p.to_meijerg()).subs({C_0:1, D_0:0}) - s).simplify() == 0 p.y0 = {0: [1], S.Half: [0]} assert (hyperexpand(p.to_meijerg()) - s).simplify() == 0 p = expr_to_holonomic(besselj(S.Half, x), initcond=False) assert (p.to_expr() - (D_0*sin(x) + C_0*cos(x) + C_1*sin(x))/sqrt(x)).simplify() == 0 p = expr_to_holonomic(besselj(S.Half, x), y0={Rational(-1, 2): [sqrt(2)/sqrt(pi), sqrt(2)/sqrt(pi)]}) assert (p.to_expr() - besselj(S.Half, x) - besselj(Rational(-1, 2), x)).simplify() == 0 def test_gaussian(): mu, x = symbols("mu x") sd = symbols("sd", positive=True) Q = QQ[mu, sd].get_field() e = sqrt(2)*exp(-(-mu + x)**2/(2*sd**2))/(2*sqrt(pi)*sd) h1 = expr_to_holonomic(e, x, domain=Q) _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx') h2 = HolonomicFunction((-mu/sd**2 + x/sd**2) + (1)*Dx, x) assert h1 == h2 def test_beta(): a, b, x = symbols("a b x", positive=True) e = x**(a - 1)*(-x + 1)**(b - 1)/beta(a, b) Q = QQ[a, b].get_field() h1 = expr_to_holonomic(e, x, domain=Q) _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx') h2 = HolonomicFunction((a + x*(-a - b + 2) - 1) + (x**2 - x)*Dx, x) assert h1 == h2 def test_gamma(): a, b, x = symbols("a b x", positive=True) e = b**(-a)*x**(a - 1)*exp(-x/b)/gamma(a) Q = QQ[a, b].get_field() h1 = expr_to_holonomic(e, x, domain=Q) _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx') h2 = HolonomicFunction((-a + 1 + x/b) + (x)*Dx, x) assert h1 == h2 def test_symbolic_power(): x, n = symbols("x n") Q = QQ[n].get_field() _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx') h1 = HolonomicFunction((-1) + (x)*Dx, x) ** -n h2 = HolonomicFunction((n) + (x)*Dx, x) assert h1 == h2 def test_negative_power(): x = symbols("x") _, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') h1 = HolonomicFunction((-1) + (x)*Dx, x) ** -2 h2 = HolonomicFunction((2) + (x)*Dx, x) assert h1 == h2 def test_expr_in_power(): x, n = symbols("x n") Q = QQ[n].get_field() _, Dx = DifferentialOperators(Q.old_poly_ring(x), 'Dx') h1 = HolonomicFunction((-1) + (x)*Dx, x) ** (n - 3) h2 = HolonomicFunction((-n + 3) + (x)*Dx, x) assert h1 == h2 def test_DifferentialOperatorEqPoly(): x = symbols('x', integer=True) R, Dx = DifferentialOperators(QQ.old_poly_ring(x), 'Dx') do = DifferentialOperator([x**2, R.base.zero, R.base.zero], R) do2 = DifferentialOperator([x**2, 1, x], R) assert not do == do2 # polynomial comparison issue, see https://github.com/sympy/sympy/pull/15799 # should work once that is solved # p = do.listofpoly[0] # assert do == p p2 = do2.listofpoly[0] assert not do2 == p2
1c46c0df20a7230e080c5575adbdc68e63384820c364beda611943ecf5ae4058
from sympy.holonomic.recurrence import RecurrenceOperators, RecurrenceOperator from sympy.core.symbol import symbols from sympy.polys.domains.rationalfield import QQ def test_RecurrenceOperator(): n = symbols('n', integer=True) R, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn') assert Sn*n == (n + 1)*Sn assert Sn*n**2 == (n**2+1+2*n)*Sn assert Sn**2*n**2 == (n**2 + 4*n + 4)*Sn**2 p = (Sn**3*n**2 + Sn*n)**2 q = (n**2 + 3*n + 2)*Sn**2 + (2*n**3 + 19*n**2 + 57*n + 52)*Sn**4 + (n**4 + 18*n**3 + \ 117*n**2 + 324*n + 324)*Sn**6 assert p == q def test_RecurrenceOperatorEqPoly(): n = symbols('n', integer=True) R, Sn = RecurrenceOperators(QQ.old_poly_ring(n), 'Sn') rr = RecurrenceOperator([n**2, 0, 0], R) rr2 = RecurrenceOperator([n**2, 1, n], R) assert not rr == rr2 # polynomial comparison issue, see https://github.com/sympy/sympy/pull/15799 # should work once that is solved # d = rr.listofpoly[0] # assert rr == d d2 = rr2.listofpoly[0] assert not rr2 == d2
e5e3ecbb9899e5b2795891ce15088a40deead4035f15bd10129a8d73079c2f09
from sympy.external import import_module lfortran = import_module('lfortran') if lfortran: from sympy.codegen.ast import (Variable, IntBaseType, FloatBaseType, String, Return, FunctionDefinition, Assignment) from sympy.core import Add, Mul, Integer, Float from sympy.core.symbol import Symbol asr_mod = lfortran.asr asr = lfortran.asr.asr src_to_ast = lfortran.ast.src_to_ast ast_to_asr = lfortran.semantic.ast_to_asr.ast_to_asr """ This module contains all the necessary Classes and Function used to Parse Fortran code into SymPy expression The module and its API are currently under development and experimental. It is also dependent on LFortran for the ASR that is converted to SymPy syntax which is also under development. The module only supports the features currently supported by the LFortran ASR which will be updated as the development of LFortran and this module progresses You might find unexpected bugs and exceptions while using the module, feel free to report them to the SymPy Issue Tracker The API for the module might also change while in development if better and more effective ways are discovered for the process Features Supported ================== - Variable Declarations (integers and reals) - Function Definitions - Assignments and Basic Binary Operations Notes ===== The module depends on an external dependency LFortran : Required to parse Fortran source code into ASR Refrences ========= .. [1] https://github.com/sympy/sympy/issues .. [2] https://gitlab.com/lfortran/lfortran .. [3] https://docs.lfortran.org/ """ class ASR2PyVisitor(asr.ASTVisitor): # type: ignore """ Visitor Class for LFortran ASR It is a Visitor class derived from asr.ASRVisitor which visits all the nodes of the LFortran ASR and creates corresponding AST node for each ASR node """ def __init__(self): """Initialize the Parser""" self._py_ast = [] def visit_TranslationUnit(self, node): """ Function to visit all the elements of the Translation Unit created by LFortran ASR """ for s in node.global_scope.symbols: sym = node.global_scope.symbols[s] self.visit(sym) for item in node.items: self.visit(item) def visit_Assignment(self, node): """Visitor Function for Assignment Visits each Assignment is the LFortran ASR and creates corresponding assignment for SymPy. Notes ===== The function currently only supports variable assignment and binary operation assignments of varying multitudes. Any type of numberS or array is not supported. Raises ====== NotImplementedError() when called for Numeric assignments or Arrays """ # TODO: Arithmatic Assignment if isinstance(node.target, asr.Variable): target = node.target value = node.value if isinstance(value, asr.Variable): new_node = Assignment( Variable( target.name ), Variable( value.name ) ) elif (type(value) == asr.BinOp): exp_ast = call_visitor(value) for expr in exp_ast: new_node = Assignment( Variable(target.name), expr ) else: raise NotImplementedError("Numeric assignments not supported") else: raise NotImplementedError("Arrays not supported") self._py_ast.append(new_node) def visit_BinOp(self, node): """Visitor Function for Binary Operations Visits each binary operation present in the LFortran ASR like addition, subtraction, multiplication, division and creates the corresponding operation node in SymPy's AST In case of more than one binary operations, the function calls the call_visitor() function on the child nodes of the binary operations recursively until all the operations have been processed. Notes ===== The function currently only supports binary operations with Variables or other binary operations. Numerics are not supported as of yet. Raises ====== NotImplementedError() when called for Numeric assignments """ # TODO: Integer Binary Operations op = node.op lhs = node.left rhs = node.right if (type(lhs) == asr.Variable): left_value = Symbol(lhs.name) elif(type(lhs) == asr.BinOp): l_exp_ast = call_visitor(lhs) for exp in l_exp_ast: left_value = exp else: raise NotImplementedError("Numbers Currently not supported") if (type(rhs) == asr.Variable): right_value = Symbol(rhs.name) elif(type(rhs) == asr.BinOp): r_exp_ast = call_visitor(rhs) for exp in r_exp_ast: right_value = exp else: raise NotImplementedError("Numbers Currently not supported") if isinstance(op, asr.Add): new_node = Add(left_value, right_value) elif isinstance(op, asr.Sub): new_node = Add(left_value, -right_value) elif isinstance(op, asr.Div): new_node = Mul(left_value, 1/right_value) elif isinstance(op, asr.Mul): new_node = Mul(left_value, right_value) self._py_ast.append(new_node) def visit_Variable(self, node): """Visitor Function for Variable Declaration Visits each variable declaration present in the ASR and creates a Symbol declaration for each variable Notes ===== The functions currently only support declaration of integer and real variables. Other data types are still under development. Raises ====== NotImplementedError() when called for unsupported data types """ if isinstance(node.type, asr.Integer): var_type = IntBaseType(String('integer')) value = Integer(0) elif isinstance(node.type, asr.Real): var_type = FloatBaseType(String('real')) value = Float(0.0) else: raise NotImplementedError("Data type not supported") if not (node.intent == 'in'): new_node = Variable( node.name ).as_Declaration( type = var_type, value = value ) self._py_ast.append(new_node) def visit_Sequence(self, seq): """Visitor Function for code sequence Visits a code sequence/ block and calls the visitor function on all the children of the code block to create corresponding code in python """ if seq is not None: for node in seq: self._py_ast.append(call_visitor(node)) def visit_Num(self, node): """Visitor Function for Numbers in ASR This function is currently under development and will be updated with improvements in the LFortran ASR """ # TODO:Numbers when the LFortran ASR is updated # self._py_ast.append(Integer(node.n)) pass def visit_Function(self, node): """Visitor Function for function Definitions Visits each function definition present in the ASR and creates a function definition node in the Python AST with all the elements of the given function The functions declare all the variables required as SymPy symbols in the function before the function definition This function also the call_visior_function to parse the contents of the function body """ # TODO: Return statement, variable declaration fn_args = [Variable(arg_iter.name) for arg_iter in node.args] fn_body = [] fn_name = node.name for i in node.body: fn_ast = call_visitor(i) try: fn_body_expr = fn_ast except UnboundLocalError: fn_body_expr = [] for sym in node.symtab.symbols: decl = call_visitor(node.symtab.symbols[sym]) for symbols in decl: fn_body.append(symbols) for elem in fn_body_expr: fn_body.append(elem) fn_body.append( Return( Variable( node.return_var.name ) ) ) if isinstance(node.return_var.type, asr.Integer): ret_type = IntBaseType(String('integer')) elif isinstance(node.return_var.type, asr.Real): ret_type = FloatBaseType(String('real')) else: raise NotImplementedError("Data type not supported") new_node = FunctionDefinition( return_type = ret_type, name = fn_name, parameters = fn_args, body = fn_body ) self._py_ast.append(new_node) def ret_ast(self): """Returns the AST nodes""" return self._py_ast else: class ASR2PyVisitor(): # type: ignore def __init__(self, *args, **kwargs): raise ImportError('lfortran not available') def call_visitor(fort_node): """Calls the AST Visitor on the Module This function is used to call the AST visitor for a program or module It imports all the required modules and calls the visit() function on the given node Parameters ========== fort_node : LFortran ASR object Node for the operation for which the NodeVisitor is called Returns ======= res_ast : list list of SymPy AST Nodes """ v = ASR2PyVisitor() v.visit(fort_node) res_ast = v.ret_ast() return res_ast def src_to_sympy(src): """Wrapper function to convert the given Fortran source code to SymPy Expressions Parameters ========== src : string A string with the Fortran source code Returns ======= py_src : string A string with the Python source code compatible with SymPy """ a_ast = src_to_ast(src, translation_unit=False) a = ast_to_asr(a_ast) py_src = call_visitor(a) return py_src
c5cf8ab60e2f6247b8a86d83718746520f780965d441b257ae722c189ddd3beb
from sympy.external import import_module import os cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']}) """ This module contains all the necessary Classes and Function used to Parse C and C++ code into SymPy expression The module serves as a backend for SymPyExpression to parse C code It is also dependent on Clang's AST and SymPy's Codegen AST. The module only supports the features currently supported by the Clang and codegen AST which will be updated as the development of codegen AST and this module progresses. You might find unexpected bugs and exceptions while using the module, feel free to report them to the SymPy Issue Tracker Features Supported ================== - Variable Declarations (integers and reals) - Assignment (using integer & floating literal and function calls) - Function Definitions nad Declaration - Function Calls - Compound statements, Return statements Notes ===== The module is dependent on an external dependency which needs to be installed to use the features of this module. Clang: The C and C++ compiler which is used to extract an AST from the provided C source code. Refrences ========= .. [1] https://github.com/sympy/sympy/issues .. [2] https://clang.llvm.org/docs/ .. [3] https://clang.llvm.org/docs/IntroductionToTheClangAST.html """ if cin: from sympy.codegen.ast import (Variable, Integer, Float, FunctionPrototype, FunctionDefinition, FunctionCall, none, Return, Assignment, intc, int8, int16, int64, uint8, uint16, uint32, uint64, float32, float64, float80, aug_assign, bool_, While, CodeBlock) from sympy.codegen.cnodes import (PreDecrement, PostDecrement, PreIncrement, PostIncrement) from sympy.core import Add, Mod, Mul, Pow, Rel from sympy.logic.boolalg import And, as_Boolean, Not, Or from sympy.core.symbol import Symbol from sympy.core.sympify import sympify from sympy.logic.boolalg import (false, true) import sys import tempfile class BaseParser: """Base Class for the C parser""" def __init__(self): """Initializes the Base parser creating a Clang AST index""" self.index = cin.Index.create() def diagnostics(self, out): """Diagostics function for the Clang AST""" for diag in self.tu.diagnostics: print('%s %s (line %s, col %s) %s' % ( { 4: 'FATAL', 3: 'ERROR', 2: 'WARNING', 1: 'NOTE', 0: 'IGNORED', }[diag.severity], diag.location.file, diag.location.line, diag.location.column, diag.spelling ), file=out) class CCodeConverter(BaseParser): """The Code Convereter for Clang AST The converter object takes the C source code or file as input and converts them to SymPy Expressions. """ def __init__(self): """Initializes the code converter""" super().__init__() self._py_nodes = [] self._data_types = { "void": { cin.TypeKind.VOID: none }, "bool": { cin.TypeKind.BOOL: bool_ }, "int": { cin.TypeKind.SCHAR: int8, cin.TypeKind.SHORT: int16, cin.TypeKind.INT: intc, cin.TypeKind.LONG: int64, cin.TypeKind.UCHAR: uint8, cin.TypeKind.USHORT: uint16, cin.TypeKind.UINT: uint32, cin.TypeKind.ULONG: uint64 }, "float": { cin.TypeKind.FLOAT: float32, cin.TypeKind.DOUBLE: float64, cin.TypeKind.LONGDOUBLE: float80 } } def parse(self, filenames, flags): """Function to parse a file with C source code It takes the filename as an attribute and creates a Clang AST Translation Unit parsing the file. Then the transformation function is called on the transaltion unit, whose reults are collected into a list which is returned by the function. Parameters ========== filenames : string Path to the C file to be parsed flags: list Arguments to be passed to Clang while parsing the C code Returns ======= py_nodes: list A list of SymPy AST nodes """ filename = os.path.abspath(filenames) self.tu = self.index.parse( filename, args=flags, options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD ) for child in self.tu.cursor.get_children(): if child.kind == cin.CursorKind.VAR_DECL: self._py_nodes.append(self.transform(child)) elif (child.kind == cin.CursorKind.FUNCTION_DECL): self._py_nodes.append(self.transform(child)) else: pass return self._py_nodes def parse_str(self, source, flags): """Function to parse a string with C source code It takes the source code as an attribute, stores it in a temporary file and creates a Clang AST Translation Unit parsing the file. Then the transformation function is called on the transaltion unit, whose reults are collected into a list which is returned by the function. Parameters ========== source : string Path to the C file to be parsed flags: list Arguments to be passed to Clang while parsing the C code Returns ======= py_nodes: list A list of SymPy AST nodes """ file = tempfile.NamedTemporaryFile(mode = 'w+', suffix = '.cpp') file.write(source) file.seek(0) self.tu = self.index.parse( file.name, args=flags, options=cin.TranslationUnit.PARSE_DETAILED_PROCESSING_RECORD ) file.close() for child in self.tu.cursor.get_children(): if child.kind == cin.CursorKind.VAR_DECL: self._py_nodes.append(self.transform(child)) elif (child.kind == cin.CursorKind.FUNCTION_DECL): self._py_nodes.append(self.transform(child)) else: pass return self._py_nodes def transform(self, node): """Transformation Function for Clang AST nodes It determines the kind of node and calls the respective transformation function for that node. Raises ====== NotImplementedError : if the transformation for the provided node is not implemented """ try: handler = getattr(self, 'transform_%s' % node.kind.name.lower()) except AttributeError: print( "Ignoring node of type %s (%s)" % ( node.kind, ' '.join( t.spelling for t in node.get_tokens()) ), file=sys.stderr ) handler = None if handler: result = handler(node) return result def transform_var_decl(self, node): """Transformation Function for Variable Declaration Used to create nodes for variable declarations and assignments with values or function call for the respective nodes in the clang AST Returns ======= A variable node as Declaration, with the initial value if given Raises ====== NotImplementedError : if called for data types not currently implemented Notes ===== The function currently supports following data types: Boolean: bool, _Bool Integer: 8-bit: signed char and unsigned char 16-bit: short, short int, signed short, signed short int, unsigned short, unsigned short int 32-bit: int, signed int, unsigned int 64-bit: long, long int, signed long, signed long int, unsigned long, unsigned long int Floating point: Single Precision: float Double Precision: double Extended Precision: long double """ if node.type.kind in self._data_types["int"]: type = self._data_types["int"][node.type.kind] elif node.type.kind in self._data_types["float"]: type = self._data_types["float"][node.type.kind] elif node.type.kind in self._data_types["bool"]: type = self._data_types["bool"][node.type.kind] else: raise NotImplementedError("Only bool, int " "and float are supported") try: children = node.get_children() child = next(children) #ignoring namespace and type details for the variable while child.kind == cin.CursorKind.NAMESPACE_REF: child = next(children) while child.kind == cin.CursorKind.TYPE_REF: child = next(children) val = self.transform(child) supported_rhs = [ cin.CursorKind.INTEGER_LITERAL, cin.CursorKind.FLOATING_LITERAL, cin.CursorKind.UNEXPOSED_EXPR, cin.CursorKind.BINARY_OPERATOR, cin.CursorKind.PAREN_EXPR, cin.CursorKind.UNARY_OPERATOR, cin.CursorKind.CXX_BOOL_LITERAL_EXPR ] if child.kind in supported_rhs: if isinstance(val, str): value = Symbol(val) elif isinstance(val, bool): if node.type.kind in self._data_types["int"]: value = Integer(0) if val == False else Integer(1) elif node.type.kind in self._data_types["float"]: value = Float(0.0) if val == False else Float(1.0) elif node.type.kind in self._data_types["bool"]: value = sympify(val) elif isinstance(val, (Integer, int, Float, float)): if node.type.kind in self._data_types["int"]: value = Integer(val) elif node.type.kind in self._data_types["float"]: value = Float(val) elif node.type.kind in self._data_types["bool"]: value = sympify(bool(val)) else: value = val return Variable( node.spelling ).as_Declaration( type = type, value = value ) elif child.kind == cin.CursorKind.CALL_EXPR: return Variable( node.spelling ).as_Declaration( value = val ) else: raise NotImplementedError("Given " "variable declaration \"{}\" " "is not possible to parse yet!" .format(" ".join( t.spelling for t in node.get_tokens() ) )) except StopIteration: return Variable( node.spelling ).as_Declaration( type = type ) def transform_function_decl(self, node): """Transformation Function For Function Declaration Used to create nodes for function declarations and definitions for the respective nodes in the clang AST Returns ======= function : Codegen AST node - FunctionPrototype node if function body is not present - FunctionDefinition node if the function body is present """ if node.result_type.kind in self._data_types["int"]: ret_type = self._data_types["int"][node.result_type.kind] elif node.result_type.kind in self._data_types["float"]: ret_type = self._data_types["float"][node.result_type.kind] elif node.result_type.kind in self._data_types["bool"]: ret_type = self._data_types["bool"][node.result_type.kind] elif node.result_type.kind in self._data_types["void"]: ret_type = self._data_types["void"][node.result_type.kind] else: raise NotImplementedError("Only void, bool, int " "and float are supported") body = [] param = [] try: children = node.get_children() child = next(children) # If the node has any children, the first children will be the # return type and namespace for the function declaration. These # nodes can be ignored. while child.kind == cin.CursorKind.NAMESPACE_REF: child = next(children) while child.kind == cin.CursorKind.TYPE_REF: child = next(children) # Subsequent nodes will be the parameters for the function. try: while True: decl = self.transform(child) if (child.kind == cin.CursorKind.PARM_DECL): param.append(decl) elif (child.kind == cin.CursorKind.COMPOUND_STMT): for val in decl: body.append(val) else: body.append(decl) child = next(children) except StopIteration: pass except StopIteration: pass if body == []: function = FunctionPrototype( return_type = ret_type, name = node.spelling, parameters = param ) else: function = FunctionDefinition( return_type = ret_type, name = node.spelling, parameters = param, body = body ) return function def transform_parm_decl(self, node): """Transformation function for Parameter Declaration Used to create parameter nodes for the required functions for the respective nodes in the clang AST Returns ======= param : Codegen AST Node Variable node with the value nad type of the variable Raises ====== ValueError if multiple children encountered in the parameter node """ if node.type.kind in self._data_types["int"]: type = self._data_types["int"][node.type.kind] elif node.type.kind in self._data_types["float"]: type = self._data_types["float"][node.type.kind] elif node.type.kind in self._data_types["bool"]: type = self._data_types["bool"][node.type.kind] else: raise NotImplementedError("Only bool, int " "and float are supported") try: children = node.get_children() child = next(children) # Any namespace nodes can be ignored while child.kind in [cin.CursorKind.NAMESPACE_REF, cin.CursorKind.TYPE_REF, cin.CursorKind.TEMPLATE_REF]: child = next(children) # If there is a child, it is the default value of the parameter. lit = self.transform(child) if node.type.kind in self._data_types["int"]: val = Integer(lit) elif node.type.kind in self._data_types["float"]: val = Float(lit) elif node.type.kind in self._data_types["bool"]: val = sympify(bool(lit)) else: raise NotImplementedError("Only bool, int " "and float are supported") param = Variable( node.spelling ).as_Declaration( type = type, value = val ) except StopIteration: param = Variable( node.spelling ).as_Declaration( type = type ) try: self.transform(next(children)) raise ValueError("Can't handle multiple children on parameter") except StopIteration: pass return param def transform_integer_literal(self, node): """Transformation function for integer literal Used to get the value and type of the given integer literal. Returns ======= val : list List with two arguments type and Value type contains the type of the integer value contains the value stored in the variable Notes ===== Only Base Integer type supported for now """ try: value = next(node.get_tokens()).spelling except StopIteration: # No tokens value = node.literal return int(value) def transform_floating_literal(self, node): """Transformation function for floating literal Used to get the value and type of the given floating literal. Returns ======= val : list List with two arguments type and Value type contains the type of float value contains the value stored in the variable Notes ===== Only Base Float type supported for now """ try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): # No tokens value = node.literal return float(value) def transform_string_literal(self, node): #TODO: No string type in AST #type = #try: # value = next(node.get_tokens()).spelling #except (StopIteration, ValueError): # No tokens # value = node.literal #val = [type, value] #return val pass def transform_character_literal(self, node): """Transformation function for character literal Used to get the value of the given character literal. Returns ======= val : int val contains the ascii value of the character literal Notes ===== Only for cases where character is assigned to a integer value, since character literal is not in SymPy AST """ try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): # No tokens value = node.literal return ord(str(value[1])) def transform_cxx_bool_literal_expr(self, node): """Transformation function for boolean literal Used to get the value of the given boolean literal. Returns ======= value : bool value contains the boolean value of the variable """ try: value = next(node.get_tokens()).spelling except (StopIteration, ValueError): value = node.literal return True if value == 'true' else False def transform_unexposed_decl(self,node): """Transformation function for unexposed declarations""" pass def transform_unexposed_expr(self, node): """Transformation function for unexposed expression Unexposed expressions are used to wrap float, double literals and expressions Returns ======= expr : Codegen AST Node the result from the wrapped expression None : NoneType No childs are found for the node Raises ====== ValueError if the expression contains multiple children """ # Ignore unexposed nodes; pass whatever is the first # (and should be only) child unaltered. try: children = node.get_children() expr = self.transform(next(children)) except StopIteration: return None try: next(children) raise ValueError("Unexposed expression has > 1 children.") except StopIteration: pass return expr def transform_decl_ref_expr(self, node): """Returns the name of the declaration reference""" return node.spelling def transform_call_expr(self, node): """Transformation function for a call expression Used to create function call nodes for the function calls present in the C code Returns ======= FunctionCall : Codegen AST Node FunctionCall node with parameters if any parameters are present """ param = [] children = node.get_children() child = next(children) while child.kind == cin.CursorKind.NAMESPACE_REF: child = next(children) while child.kind == cin.CursorKind.TYPE_REF: child = next(children) first_child = self.transform(child) try: for child in children: arg = self.transform(child) if (child.kind == cin.CursorKind.INTEGER_LITERAL): param.append(Integer(arg)) elif (child.kind == cin.CursorKind.FLOATING_LITERAL): param.append(Float(arg)) else: param.append(arg) return FunctionCall(first_child, param) except StopIteration: return FunctionCall(first_child) def transform_return_stmt(self, node): """Returns the Return Node for a return statement""" return Return(next(node.get_children()).spelling) def transform_compound_stmt(self, node): """Transformation function for compond statemets Returns ======= expr : list list of Nodes for the expressions present in the statement None : NoneType if the compound statement is empty """ try: expr = [] children = node.get_children() for child in children: expr.append(self.transform(child)) except StopIteration: return None return expr def transform_decl_stmt(self, node): """Transformation function for declaration statements These statements are used to wrap different kinds of declararions like variable or function declaration The function calls the transformer function for the child of the given node Returns ======= statement : Codegen AST Node contains the node returned by the children node for the type of declaration Raises ====== ValueError if multiple children present """ try: children = node.get_children() statement = self.transform(next(children)) except StopIteration: pass try: self.transform(next(children)) raise ValueError("Don't know how to handle multiple statements") except StopIteration: pass return statement def transform_paren_expr(self, node): """Transformation function for Parenthesized expressions Returns the result from its children nodes """ return self.transform(next(node.get_children())) def transform_compound_assignment_operator(self, node): """Transformation function for handling shorthand operators Returns ======= augmented_assignment_expression: Codegen AST node shorthand assignment expression represented as Codegen AST Raises ====== NotImplementedError If the shorthand operator for bitwise operators (~=, ^=, &=, |=, <<=, >>=) is encountered """ return self.transform_binary_operator(node) def transform_unary_operator(self, node): """Transformation function for handling unary operators Returns ======= unary_expression: Codegen AST node simplified unary expression represented as Codegen AST Raises ====== NotImplementedError If dereferencing operator(*), address operator(&) or bitwise NOT operator(~) is encountered """ # supported operators list operators_list = ['+', '-', '++', '--', '!'] tokens = [token for token in node.get_tokens()] # it can be either pre increment/decrement or any other operator from the list if tokens[0].spelling in operators_list: child = self.transform(next(node.get_children())) # (decl_ref) e.g.; int a = ++b; or simply ++b; if isinstance(child, str): if tokens[0].spelling == '+': return Symbol(child) if tokens[0].spelling == '-': return Mul(Symbol(child), -1) if tokens[0].spelling == '++': return PreIncrement(Symbol(child)) if tokens[0].spelling == '--': return PreDecrement(Symbol(child)) if tokens[0].spelling == '!': return Not(Symbol(child)) # e.g.; int a = -1; or int b = -(1 + 2); else: if tokens[0].spelling == '+': return child if tokens[0].spelling == '-': return Mul(child, -1) if tokens[0].spelling == '!': return Not(sympify(bool(child))) # it can be either post increment/decrement # since variable name is obtained in token[0].spelling elif tokens[1].spelling in ['++', '--']: child = self.transform(next(node.get_children())) if tokens[1].spelling == '++': return PostIncrement(Symbol(child)) if tokens[1].spelling == '--': return PostDecrement(Symbol(child)) else: raise NotImplementedError("Dereferencing operator, " "Address operator and bitwise NOT operator " "have not been implemented yet!") def transform_binary_operator(self, node): """Transformation function for handling binary operators Returns ======= binary_expression: Codegen AST node simplified binary expression represented as Codegen AST Raises ====== NotImplementedError If a bitwise operator or unary operator(which is a child of any binary operator in Clang AST) is encountered """ # get all the tokens of assignment # and store it in the tokens list tokens = [token for token in node.get_tokens()] # supported operators list operators_list = ['+', '-', '*', '/', '%','=', '>', '>=', '<', '<=', '==', '!=', '&&', '||', '+=', '-=', '*=', '/=', '%='] # this stack will contain variable content # and type of variable in the rhs combined_variables_stack = [] # this stack will contain operators # to be processed in the rhs operators_stack = [] # iterate through every token for token in tokens: # token is either '(', ')' or # any of the supported operators from the operator list if token.kind == cin.TokenKind.PUNCTUATION: # push '(' to the operators stack if token.spelling == '(': operators_stack.append('(') elif token.spelling == ')': # keep adding the expression to the # combined variables stack unless # '(' is found while (operators_stack and operators_stack[-1] != '('): if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation( lhs, rhs, operator)) # pop '(' operators_stack.pop() # token is an operator (supported) elif token.spelling in operators_list: while (operators_stack and self.priority_of(token.spelling) <= self.priority_of( operators_stack[-1])): if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation( lhs, rhs, operator)) # push current operator operators_stack.append(token.spelling) # token is a bitwise operator elif token.spelling in ['&', '|', '^', '<<', '>>']: raise NotImplementedError( "Bitwise operator has not been " "implemented yet!") # token is a shorthand bitwise operator elif token.spelling in ['&=', '|=', '^=', '<<=', '>>=']: raise NotImplementedError( "Shorthand bitwise operator has not been " "implemented yet!") else: raise NotImplementedError( "Given token {} is not implemented yet!" .format(token.spelling)) # token is an identifier(variable) elif token.kind == cin.TokenKind.IDENTIFIER: combined_variables_stack.append( [token.spelling, 'identifier']) # token is a literal elif token.kind == cin.TokenKind.LITERAL: combined_variables_stack.append( [token.spelling, 'literal']) # token is a keyword, either true or false elif (token.kind == cin.TokenKind.KEYWORD and token.spelling in ['true', 'false']): combined_variables_stack.append( [token.spelling, 'boolean']) else: raise NotImplementedError( "Given token {} is not implemented yet!" .format(token.spelling)) # process remaining operators while operators_stack: if len(combined_variables_stack) < 2: raise NotImplementedError( "Unary operators as a part of " "binary operators is not " "supported yet!") rhs = combined_variables_stack.pop() lhs = combined_variables_stack.pop() operator = operators_stack.pop() combined_variables_stack.append( self.perform_operation(lhs, rhs, operator)) return combined_variables_stack[-1][0] def priority_of(self, op): """To get the priority of given operator""" if op in ['=', '+=', '-=', '*=', '/=', '%=']: return 1 if op in ['&&', '||']: return 2 if op in ['<', '<=', '>', '>=', '==', '!=']: return 3 if op in ['+', '-']: return 4 if op in ['*', '/', '%']: return 5 return 0 def perform_operation(self, lhs, rhs, op): """Performs operation supported by the SymPy core Returns ======= combined_variable: list contains variable content and type of variable """ lhs_value = self.get_expr_for_operand(lhs) rhs_value = self.get_expr_for_operand(rhs) if op == '+': return [Add(lhs_value, rhs_value), 'expr'] if op == '-': return [Add(lhs_value, -rhs_value), 'expr'] if op == '*': return [Mul(lhs_value, rhs_value), 'expr'] if op == '/': return [Mul(lhs_value, Pow(rhs_value, Integer(-1))), 'expr'] if op == '%': return [Mod(lhs_value, rhs_value), 'expr'] if op in ['<', '<=', '>', '>=', '==', '!=']: return [Rel(lhs_value, rhs_value, op), 'expr'] if op == '&&': return [And(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr'] if op == '||': return [Or(as_Boolean(lhs_value), as_Boolean(rhs_value)), 'expr'] if op == '=': return [Assignment(Variable(lhs_value), rhs_value), 'expr'] if op in ['+=', '-=', '*=', '/=', '%=']: return [aug_assign(Variable(lhs_value), op[0], rhs_value), 'expr'] def get_expr_for_operand(self, combined_variable): """Gives out SymPy Codegen AST node AST node returned is corresponding to combined variable passed.Combined variable contains variable content and type of variable """ if combined_variable[1] == 'identifier': return Symbol(combined_variable[0]) if combined_variable[1] == 'literal': if '.' in combined_variable[0]: return Float(float(combined_variable[0])) else: return Integer(int(combined_variable[0])) if combined_variable[1] == 'expr': return combined_variable[0] if combined_variable[1] == 'boolean': return true if combined_variable[0] == 'true' else false def transform_null_stmt(self, node): """Handles Null Statement and returns None""" return none def transform_while_stmt(self, node): """Transformation function for handling while statement Returns ======= while statement : Codegen AST Node contains the while statement node having condition and statement block """ children = node.get_children() condition = self.transform(next(children)) statements = self.transform(next(children)) if isinstance(statements, list): statement_block = CodeBlock(*statements) else: statement_block = CodeBlock(statements) return While(condition, statement_block) else: class CCodeConverter(): # type: ignore def __init__(self, *args, **kwargs): raise ImportError("Module not Installed") def parse_c(source): """Function for converting a C source code The function reads the source code present in the given file and parses it to give out SymPy Expressions Returns ======= src : list List of Python expression strings """ converter = CCodeConverter() if os.path.exists(source): src = converter.parse(source, flags = []) else: src = converter.parse_str(source, flags = []) return src
ddfbb8c7cc1e3320cbab74826383d74c001d1f714cfa6dcc36efabe24eb436f9
from sympy.parsing.sym_expr import SymPyExpression from sympy.testing.pytest import raises from sympy.external import import_module lfortran = import_module('lfortran') cin = import_module('clang.cindex', import_kwargs = {'fromlist': ['cindex']}) if lfortran and cin: from sympy.codegen.ast import (Variable, IntBaseType, FloatBaseType, String, Declaration, FloatType) from sympy.core import Integer, Float from sympy.core.symbol import Symbol expr1 = SymPyExpression() src = """\ integer :: a, b, c, d real :: p, q, r, s """ def test_c_parse(): src1 = """\ int a, b = 4; float c, d = 2.4; """ expr1.convert_to_expr(src1, 'c') ls = expr1.return_expr() assert ls[0] == Declaration( Variable( Symbol('a'), type=IntBaseType(String('intc')) ) ) assert ls[1] == Declaration( Variable( Symbol('b'), type=IntBaseType(String('intc')), value=Integer(4) ) ) assert ls[2] == Declaration( Variable( Symbol('c'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ) ) ) assert ls[3] == Declaration( Variable( Symbol('d'), type=FloatType( String('float32'), nbits=Integer(32), nmant=Integer(23), nexp=Integer(8) ), value=Float('2.3999999999999999', precision=53) ) ) def test_fortran_parse(): expr = SymPyExpression(src, 'f') ls = expr.return_expr() assert ls[0] == Declaration( Variable( Symbol('a'), type=IntBaseType(String('integer')), value=Integer(0) ) ) assert ls[1] == Declaration( Variable( Symbol('b'), type=IntBaseType(String('integer')), value=Integer(0) ) ) assert ls[2] == Declaration( Variable( Symbol('c'), type=IntBaseType(String('integer')), value=Integer(0) ) ) assert ls[3] == Declaration( Variable( Symbol('d'), type=IntBaseType(String('integer')), value=Integer(0) ) ) assert ls[4] == Declaration( Variable( Symbol('p'), type=FloatBaseType(String('real')), value=Float('0.0', precision=53) ) ) assert ls[5] == Declaration( Variable( Symbol('q'), type=FloatBaseType(String('real')), value=Float('0.0', precision=53) ) ) assert ls[6] == Declaration( Variable( Symbol('r'), type=FloatBaseType(String('real')), value=Float('0.0', precision=53) ) ) assert ls[7] == Declaration( Variable( Symbol('s'), type=FloatBaseType(String('real')), value=Float('0.0', precision=53) ) ) def test_convert_py(): src1 = ( src + """\ a = b + c s = p * q / r """ ) expr1.convert_to_expr(src1, 'f') exp_py = expr1.convert_to_python() assert exp_py == [ 'a = 0', 'b = 0', 'c = 0', 'd = 0', 'p = 0.0', 'q = 0.0', 'r = 0.0', 's = 0.0', 'a = b + c', 's = p*q/r' ] def test_convert_fort(): src1 = ( src + """\ a = b + c s = p * q / r """ ) expr1.convert_to_expr(src1, 'f') exp_fort = expr1.convert_to_fortran() assert exp_fort == [ ' integer*4 a', ' integer*4 b', ' integer*4 c', ' integer*4 d', ' real*8 p', ' real*8 q', ' real*8 r', ' real*8 s', ' a = b + c', ' s = p*q/r' ] def test_convert_c(): src1 = ( src + """\ a = b + c s = p * q / r """ ) expr1.convert_to_expr(src1, 'f') exp_c = expr1.convert_to_c() assert exp_c == [ 'int a = 0', 'int b = 0', 'int c = 0', 'int d = 0', 'double p = 0.0', 'double q = 0.0', 'double r = 0.0', 'double s = 0.0', 'a = b + c;', 's = p*q/r;' ] def test_exceptions(): src = 'int a;' raises(ValueError, lambda: SymPyExpression(src)) raises(ValueError, lambda: SymPyExpression(mode = 'c')) raises(NotImplementedError, lambda: SymPyExpression(src, mode = 'd')) elif not lfortran and not cin: def test_raise(): raises(ImportError, lambda: SymPyExpression('int a;', 'c')) raises(ImportError, lambda: SymPyExpression('integer :: a', 'f'))
4866dac2b2786bbf344c900554c38d73b63763c558815aac207c5519a89c6f11
from sympy.testing.pytest import raises from sympy.parsing.sym_expr import SymPyExpression from sympy.external import import_module lfortran = import_module('lfortran') if lfortran: from sympy.codegen.ast import (Variable, IntBaseType, FloatBaseType, String, Return, FunctionDefinition, Assignment, Declaration, CodeBlock) from sympy.core import Integer, Float, Add from sympy.core.symbol import Symbol expr1 = SymPyExpression() expr2 = SymPyExpression() src = """\ integer :: a, b, c, d real :: p, q, r, s """ def test_sym_expr(): src1 = ( src + """\ d = a + b -c """ ) expr3 = SymPyExpression(src,'f') expr4 = SymPyExpression(src1,'f') ls1 = expr3.return_expr() ls2 = expr4.return_expr() for i in range(0, 7): assert isinstance(ls1[i], Declaration) assert isinstance(ls2[i], Declaration) assert isinstance(ls2[8], Assignment) assert ls1[0] == Declaration( Variable( Symbol('a'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls1[1] == Declaration( Variable( Symbol('b'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls1[2] == Declaration( Variable( Symbol('c'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls1[3] == Declaration( Variable( Symbol('d'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls1[4] == Declaration( Variable( Symbol('p'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) assert ls1[5] == Declaration( Variable( Symbol('q'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) assert ls1[6] == Declaration( Variable( Symbol('r'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) assert ls1[7] == Declaration( Variable( Symbol('s'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) assert ls2[8] == Assignment( Variable(Symbol('d')), Symbol('a') + Symbol('b') - Symbol('c') ) def test_assignment(): src1 = ( src + """\ a = b c = d p = q r = s """ ) expr1.convert_to_expr(src1, 'f') ls1 = expr1.return_expr() for iter in range(0, 12): if iter < 8: assert isinstance(ls1[iter], Declaration) else: assert isinstance(ls1[iter], Assignment) assert ls1[8] == Assignment( Variable(Symbol('a')), Variable(Symbol('b')) ) assert ls1[9] == Assignment( Variable(Symbol('c')), Variable(Symbol('d')) ) assert ls1[10] == Assignment( Variable(Symbol('p')), Variable(Symbol('q')) ) assert ls1[11] == Assignment( Variable(Symbol('r')), Variable(Symbol('s')) ) def test_binop_add(): src1 = ( src + """\ c = a + b d = a + c s = p + q + r """ ) expr1.convert_to_expr(src1, 'f') ls1 = expr1.return_expr() for iter in range(8, 11): assert isinstance(ls1[iter], Assignment) assert ls1[8] == Assignment( Variable(Symbol('c')), Symbol('a') + Symbol('b') ) assert ls1[9] == Assignment( Variable(Symbol('d')), Symbol('a') + Symbol('c') ) assert ls1[10] == Assignment( Variable(Symbol('s')), Symbol('p') + Symbol('q') + Symbol('r') ) def test_binop_sub(): src1 = ( src + """\ c = a - b d = a - c s = p - q - r """ ) expr1.convert_to_expr(src1, 'f') ls1 = expr1.return_expr() for iter in range(8, 11): assert isinstance(ls1[iter], Assignment) assert ls1[8] == Assignment( Variable(Symbol('c')), Symbol('a') - Symbol('b') ) assert ls1[9] == Assignment( Variable(Symbol('d')), Symbol('a') - Symbol('c') ) assert ls1[10] == Assignment( Variable(Symbol('s')), Symbol('p') - Symbol('q') - Symbol('r') ) def test_binop_mul(): src1 = ( src + """\ c = a * b d = a * c s = p * q * r """ ) expr1.convert_to_expr(src1, 'f') ls1 = expr1.return_expr() for iter in range(8, 11): assert isinstance(ls1[iter], Assignment) assert ls1[8] == Assignment( Variable(Symbol('c')), Symbol('a') * Symbol('b') ) assert ls1[9] == Assignment( Variable(Symbol('d')), Symbol('a') * Symbol('c') ) assert ls1[10] == Assignment( Variable(Symbol('s')), Symbol('p') * Symbol('q') * Symbol('r') ) def test_binop_div(): src1 = ( src + """\ c = a / b d = a / c s = p / q r = q / p """ ) expr1.convert_to_expr(src1, 'f') ls1 = expr1.return_expr() for iter in range(8, 12): assert isinstance(ls1[iter], Assignment) assert ls1[8] == Assignment( Variable(Symbol('c')), Symbol('a') / Symbol('b') ) assert ls1[9] == Assignment( Variable(Symbol('d')), Symbol('a') / Symbol('c') ) assert ls1[10] == Assignment( Variable(Symbol('s')), Symbol('p') / Symbol('q') ) assert ls1[11] == Assignment( Variable(Symbol('r')), Symbol('q') / Symbol('p') ) def test_mul_binop(): src1 = ( src + """\ d = a + b - c c = a * b + d s = p * q / r r = p * s + q / p """ ) expr1.convert_to_expr(src1, 'f') ls1 = expr1.return_expr() for iter in range(8, 12): assert isinstance(ls1[iter], Assignment) assert ls1[8] == Assignment( Variable(Symbol('d')), Symbol('a') + Symbol('b') - Symbol('c') ) assert ls1[9] == Assignment( Variable(Symbol('c')), Symbol('a') * Symbol('b') + Symbol('d') ) assert ls1[10] == Assignment( Variable(Symbol('s')), Symbol('p') * Symbol('q') / Symbol('r') ) assert ls1[11] == Assignment( Variable(Symbol('r')), Symbol('p') * Symbol('s') + Symbol('q') / Symbol('p') ) def test_function(): src1 = """\ integer function f(a,b) integer :: x, y f = x + y end function """ expr1.convert_to_expr(src1, 'f') for iter in expr1.return_expr(): assert isinstance(iter, FunctionDefinition) assert iter == FunctionDefinition( IntBaseType(String('integer')), name=String('f'), parameters=( Variable(Symbol('a')), Variable(Symbol('b')) ), body=CodeBlock( Declaration( Variable( Symbol('a'), type=IntBaseType(String('integer')), value=Integer(0) ) ), Declaration( Variable( Symbol('b'), type=IntBaseType(String('integer')), value=Integer(0) ) ), Declaration( Variable( Symbol('f'), type=IntBaseType(String('integer')), value=Integer(0) ) ), Declaration( Variable( Symbol('x'), type=IntBaseType(String('integer')), value=Integer(0) ) ), Declaration( Variable( Symbol('y'), type=IntBaseType(String('integer')), value=Integer(0) ) ), Assignment( Variable(Symbol('f')), Add(Symbol('x'), Symbol('y')) ), Return(Variable(Symbol('f'))) ) ) def test_var(): expr1.convert_to_expr(src, 'f') ls = expr1.return_expr() for iter in expr1.return_expr(): assert isinstance(iter, Declaration) assert ls[0] == Declaration( Variable( Symbol('a'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls[1] == Declaration( Variable( Symbol('b'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls[2] == Declaration( Variable( Symbol('c'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls[3] == Declaration( Variable( Symbol('d'), type = IntBaseType(String('integer')), value = Integer(0) ) ) assert ls[4] == Declaration( Variable( Symbol('p'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) assert ls[5] == Declaration( Variable( Symbol('q'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) assert ls[6] == Declaration( Variable( Symbol('r'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) assert ls[7] == Declaration( Variable( Symbol('s'), type = FloatBaseType(String('real')), value = Float(0.0) ) ) else: def test_raise(): from sympy.parsing.fortran.fortran_parser import ASR2PyVisitor raises(ImportError, lambda: ASR2PyVisitor()) raises(ImportError, lambda: SymPyExpression(' ', mode = 'f'))
515ae4bd00b73513153d471caac008cec0100d3ae505a6d7d019a40510533b87
from sympy.core.singleton import S from sympy.core.symbol import symbols from sympy.parsing.ast_parser import parse_expr from sympy.testing.pytest import raises from sympy.core.sympify import SympifyError def test_parse_expr(): a, b = symbols('a, b') # tests issue_16393 parse_expr('a + b', {}) == a + b raises(SympifyError, lambda: parse_expr('a + ', {})) # tests Transform.visit_Num parse_expr('1 + 2', {}) == S(3) parse_expr('1 + 2.0', {}) == S(3.0) # tests Transform.visit_Name parse_expr('Rational(1, 2)', {}) == S(1)/2 parse_expr('a', {'a': a}) == a