hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
b948cb71f2ab7d6f84041e8df687c4489830e3f41a70a58dd5f2dad1eb67ea26 | """Tests for OO layer of several polynomial representations. """
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.polys.domains import ZZ, QQ
from sympy.polys.polyclasses import DMP, DMF, ANP
from sympy.polys.polyerrors import (CoercionFailed, ExactQuotientFailed,
NotInvertible)
from sympy.polys.specialpolys import f_polys
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_DMP___init__():
f = DMP([[0], [], [0, 1, 2], [3]], ZZ)
assert f.rep == [[1, 2], [3]]
assert f.dom == ZZ
assert f.lev == 1
f = DMP([[1, 2], [3]], ZZ, 1)
assert f.rep == [[1, 2], [3]]
assert f.dom == ZZ
assert f.lev == 1
f = DMP({(1, 1): 1, (0, 0): 2}, ZZ, 1)
assert f.rep == [[1, 0], [2]]
assert f.dom == ZZ
assert f.lev == 1
def test_DMP___eq__():
assert DMP([[ZZ(1), ZZ(2)], [ZZ(3)]], ZZ) == \
DMP([[ZZ(1), ZZ(2)], [ZZ(3)]], ZZ)
assert DMP([[ZZ(1), ZZ(2)], [ZZ(3)]], ZZ) == \
DMP([[QQ(1), QQ(2)], [QQ(3)]], QQ)
assert DMP([[QQ(1), QQ(2)], [QQ(3)]], QQ) == \
DMP([[ZZ(1), ZZ(2)], [ZZ(3)]], ZZ)
assert DMP([[[ZZ(1)]]], ZZ) != DMP([[ZZ(1)]], ZZ)
assert DMP([[ZZ(1)]], ZZ) != DMP([[[ZZ(1)]]], ZZ)
def test_DMP___bool__():
assert bool(DMP([[]], ZZ)) is False
assert bool(DMP([[1]], ZZ)) is True
def test_DMP_to_dict():
f = DMP([[3], [], [2], [], [8]], ZZ)
assert f.to_dict() == \
{(4, 0): 3, (2, 0): 2, (0, 0): 8}
assert f.to_sympy_dict() == \
{(4, 0): ZZ.to_sympy(3), (2, 0): ZZ.to_sympy(2), (0, 0):
ZZ.to_sympy(8)}
def test_DMP_properties():
assert DMP([[]], ZZ).is_zero is True
assert DMP([[1]], ZZ).is_zero is False
assert DMP([[1]], ZZ).is_one is True
assert DMP([[2]], ZZ).is_one is False
assert DMP([[1]], ZZ).is_ground is True
assert DMP([[1], [2], [1]], ZZ).is_ground is False
assert DMP([[1], [2, 0], [1, 0]], ZZ).is_sqf is True
assert DMP([[1], [2, 0], [1, 0, 0]], ZZ).is_sqf is False
assert DMP([[1, 2], [3]], ZZ).is_monic is True
assert DMP([[2, 2], [3]], ZZ).is_monic is False
assert DMP([[1, 2], [3]], ZZ).is_primitive is True
assert DMP([[2, 4], [6]], ZZ).is_primitive is False
def test_DMP_arithmetics():
f = DMP([[2], [2, 0]], ZZ)
assert f.mul_ground(2) == DMP([[4], [4, 0]], ZZ)
assert f.quo_ground(2) == DMP([[1], [1, 0]], ZZ)
raises(ExactQuotientFailed, lambda: f.exquo_ground(3))
f = DMP([[-5]], ZZ)
g = DMP([[5]], ZZ)
assert f.abs() == g
assert abs(f) == g
assert g.neg() == f
assert -g == f
h = DMP([[]], ZZ)
assert f.add(g) == h
assert f + g == h
assert g + f == h
assert f + 5 == h
assert 5 + f == h
h = DMP([[-10]], ZZ)
assert f.sub(g) == h
assert f - g == h
assert g - f == -h
assert f - 5 == h
assert 5 - f == -h
h = DMP([[-25]], ZZ)
assert f.mul(g) == h
assert f * g == h
assert g * f == h
assert f * 5 == h
assert 5 * f == h
h = DMP([[25]], ZZ)
assert f.sqr() == h
assert f.pow(2) == h
assert f**2 == h
raises(TypeError, lambda: f.pow('x'))
f = DMP([[1], [], [1, 0, 0]], ZZ)
g = DMP([[2], [-2, 0]], ZZ)
q = DMP([[2], [2, 0]], ZZ)
r = DMP([[8, 0, 0]], ZZ)
assert f.pdiv(g) == (q, r)
assert f.pquo(g) == q
assert f.prem(g) == r
raises(ExactQuotientFailed, lambda: f.pexquo(g))
f = DMP([[1], [], [1, 0, 0]], ZZ)
g = DMP([[1], [-1, 0]], ZZ)
q = DMP([[1], [1, 0]], ZZ)
r = DMP([[2, 0, 0]], ZZ)
assert f.div(g) == (q, r)
assert f.quo(g) == q
assert f.rem(g) == r
assert divmod(f, g) == (q, r)
assert f // g == q
assert f % g == r
raises(ExactQuotientFailed, lambda: f.exquo(g))
def test_DMP_functionality():
f = DMP([[1], [2, 0], [1, 0, 0]], ZZ)
g = DMP([[1], [1, 0]], ZZ)
h = DMP([[1]], ZZ)
assert f.degree() == 2
assert f.degree_list() == (2, 2)
assert f.total_degree() == 2
assert f.LC() == ZZ(1)
assert f.TC() == ZZ(0)
assert f.nth(1, 1) == ZZ(2)
raises(TypeError, lambda: f.nth(0, 'x'))
assert f.max_norm() == 2
assert f.l1_norm() == 4
u = DMP([[2], [2, 0]], ZZ)
assert f.diff(m=1, j=0) == u
assert f.diff(m=1, j=1) == u
raises(TypeError, lambda: f.diff(m='x', j=0))
u = DMP([1, 2, 1], ZZ)
v = DMP([1, 2, 1], ZZ)
assert f.eval(a=1, j=0) == u
assert f.eval(a=1, j=1) == v
assert f.eval(1).eval(1) == ZZ(4)
assert f.cofactors(g) == (g, g, h)
assert f.gcd(g) == g
assert f.lcm(g) == f
u = DMP([[QQ(45), QQ(30), QQ(5)]], QQ)
v = DMP([[QQ(1), QQ(2, 3), QQ(1, 9)]], QQ)
assert u.monic() == v
assert (4*f).content() == ZZ(4)
assert (4*f).primitive() == (ZZ(4), f)
f = DMP([[1], [2], [3], [4], [5], [6]], ZZ)
assert f.trunc(3) == DMP([[1], [-1], [], [1], [-1], []], ZZ)
f = DMP(f_4, ZZ)
assert f.sqf_part() == -f
assert f.sqf_list() == (ZZ(-1), [(-f, 1)])
f = DMP([[-1], [], [], [5]], ZZ)
g = DMP([[3, 1], [], []], ZZ)
h = DMP([[45, 30, 5]], ZZ)
r = DMP([675, 675, 225, 25], ZZ)
assert f.subresultants(g) == [f, g, h]
assert f.resultant(g) == r
f = DMP([1, 3, 9, -13], ZZ)
assert f.discriminant() == -11664
f = DMP([QQ(2), QQ(0)], QQ)
g = DMP([QQ(1), QQ(0), QQ(-16)], QQ)
s = DMP([QQ(1, 32), QQ(0)], QQ)
t = DMP([QQ(-1, 16)], QQ)
h = DMP([QQ(1)], QQ)
assert f.half_gcdex(g) == (s, h)
assert f.gcdex(g) == (s, t, h)
assert f.invert(g) == s
f = DMP([[1], [2], [3]], QQ)
raises(ValueError, lambda: f.half_gcdex(f))
raises(ValueError, lambda: f.gcdex(f))
raises(ValueError, lambda: f.invert(f))
f = DMP([1, 0, 20, 0, 150, 0, 500, 0, 625, -2, 0, -10, 9], ZZ)
g = DMP([1, 0, 0, -2, 9], ZZ)
h = DMP([1, 0, 5, 0], ZZ)
assert g.compose(h) == f
assert f.decompose() == [g, h]
f = DMP([[1], [2], [3]], QQ)
raises(ValueError, lambda: f.decompose())
raises(ValueError, lambda: f.sturm())
def test_DMP_exclude():
f = [[[[[[[[[[[[[[[[[[[[[[[[[[1]], [[]]]]]]]]]]]]]]]]]]]]]]]]]]
J = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 24, 25]
assert DMP(f, ZZ).exclude() == (J, DMP([1, 0], ZZ))
assert DMP([[1], [1, 0]], ZZ).exclude() == ([], DMP([[1], [1, 0]], ZZ))
def test_DMF__init__():
f = DMF(([[0], [], [0, 1, 2], [3]], [[1, 2, 3]]), ZZ)
assert f.num == [[1, 2], [3]]
assert f.den == [[1, 2, 3]]
assert f.lev == 1
assert f.dom == ZZ
f = DMF(([[1, 2], [3]], [[1, 2, 3]]), ZZ, 1)
assert f.num == [[1, 2], [3]]
assert f.den == [[1, 2, 3]]
assert f.lev == 1
assert f.dom == ZZ
f = DMF(([[-1], [-2]], [[3], [-4]]), ZZ)
assert f.num == [[-1], [-2]]
assert f.den == [[3], [-4]]
assert f.lev == 1
assert f.dom == ZZ
f = DMF(([[1], [2]], [[-3], [4]]), ZZ)
assert f.num == [[-1], [-2]]
assert f.den == [[3], [-4]]
assert f.lev == 1
assert f.dom == ZZ
f = DMF(([[1], [2]], [[-3], [4]]), ZZ)
assert f.num == [[-1], [-2]]
assert f.den == [[3], [-4]]
assert f.lev == 1
assert f.dom == ZZ
f = DMF(([[]], [[-3], [4]]), ZZ)
assert f.num == [[]]
assert f.den == [[1]]
assert f.lev == 1
assert f.dom == ZZ
f = DMF(17, ZZ, 1)
assert f.num == [[17]]
assert f.den == [[1]]
assert f.lev == 1
assert f.dom == ZZ
f = DMF(([[1], [2]]), ZZ)
assert f.num == [[1], [2]]
assert f.den == [[1]]
assert f.lev == 1
assert f.dom == ZZ
f = DMF([[0], [], [0, 1, 2], [3]], ZZ)
assert f.num == [[1, 2], [3]]
assert f.den == [[1]]
assert f.lev == 1
assert f.dom == ZZ
f = DMF({(1, 1): 1, (0, 0): 2}, ZZ, 1)
assert f.num == [[1, 0], [2]]
assert f.den == [[1]]
assert f.lev == 1
assert f.dom == ZZ
f = DMF(([[QQ(1)], [QQ(2)]], [[-QQ(3)], [QQ(4)]]), QQ)
assert f.num == [[-QQ(1)], [-QQ(2)]]
assert f.den == [[QQ(3)], [-QQ(4)]]
assert f.lev == 1
assert f.dom == QQ
f = DMF(([[QQ(1, 5)], [QQ(2, 5)]], [[-QQ(3, 7)], [QQ(4, 7)]]), QQ)
assert f.num == [[-QQ(7)], [-QQ(14)]]
assert f.den == [[QQ(15)], [-QQ(20)]]
assert f.lev == 1
assert f.dom == QQ
raises(ValueError, lambda: DMF(([1], [[1]]), ZZ))
raises(ZeroDivisionError, lambda: DMF(([1], []), ZZ))
def test_DMF__bool__():
assert bool(DMF([[]], ZZ)) is False
assert bool(DMF([[1]], ZZ)) is True
def test_DMF_properties():
assert DMF([[]], ZZ).is_zero is True
assert DMF([[]], ZZ).is_one is False
assert DMF([[1]], ZZ).is_zero is False
assert DMF([[1]], ZZ).is_one is True
assert DMF(([[1]], [[2]]), ZZ).is_one is False
def test_DMF_arithmetics():
f = DMF([[7], [-9]], ZZ)
g = DMF([[-7], [9]], ZZ)
assert f.neg() == -f == g
f = DMF(([[1]], [[1], []]), ZZ)
g = DMF(([[1]], [[1, 0]]), ZZ)
h = DMF(([[1], [1, 0]], [[1, 0], []]), ZZ)
assert f.add(g) == f + g == h
assert g.add(f) == g + f == h
h = DMF(([[-1], [1, 0]], [[1, 0], []]), ZZ)
assert f.sub(g) == f - g == h
h = DMF(([[1]], [[1, 0], []]), ZZ)
assert f.mul(g) == f*g == h
assert g.mul(f) == g*f == h
h = DMF(([[1, 0]], [[1], []]), ZZ)
assert f.quo(g) == f/g == h
h = DMF(([[1]], [[1], [], [], []]), ZZ)
assert f.pow(3) == f**3 == h
h = DMF(([[1]], [[1, 0, 0, 0]]), ZZ)
assert g.pow(3) == g**3 == h
h = DMF(([[1, 0]], [[1]]), ZZ)
assert g.pow(-1) == g**-1 == h
def test_ANP___init__():
rep = [QQ(1), QQ(1)]
mod = [QQ(1), QQ(0), QQ(1)]
f = ANP(rep, mod, QQ)
assert f.rep == [QQ(1), QQ(1)]
assert f.mod == [QQ(1), QQ(0), QQ(1)]
assert f.dom == QQ
rep = {1: QQ(1), 0: QQ(1)}
mod = {2: QQ(1), 0: QQ(1)}
f = ANP(rep, mod, QQ)
assert f.rep == [QQ(1), QQ(1)]
assert f.mod == [QQ(1), QQ(0), QQ(1)]
assert f.dom == QQ
f = ANP(1, mod, QQ)
assert f.rep == [QQ(1)]
assert f.mod == [QQ(1), QQ(0), QQ(1)]
assert f.dom == QQ
f = ANP([1, 0.5], mod, QQ)
assert all(QQ.of_type(a) for a in f.rep)
raises(CoercionFailed, lambda: ANP([sqrt(2)], mod, QQ))
def test_ANP___eq__():
a = ANP([QQ(1), QQ(1)], [QQ(1), QQ(0), QQ(1)], QQ)
b = ANP([QQ(1), QQ(1)], [QQ(1), QQ(0), QQ(2)], QQ)
assert (a == a) is True
assert (a != a) is False
assert (a == b) is False
assert (a != b) is True
b = ANP([QQ(1), QQ(2)], [QQ(1), QQ(0), QQ(1)], QQ)
assert (a == b) is False
assert (a != b) is True
def test_ANP___bool__():
assert bool(ANP([], [QQ(1), QQ(0), QQ(1)], QQ)) is False
assert bool(ANP([QQ(1)], [QQ(1), QQ(0), QQ(1)], QQ)) is True
def test_ANP_properties():
mod = [QQ(1), QQ(0), QQ(1)]
assert ANP([QQ(0)], mod, QQ).is_zero is True
assert ANP([QQ(1)], mod, QQ).is_zero is False
assert ANP([QQ(1)], mod, QQ).is_one is True
assert ANP([QQ(2)], mod, QQ).is_one is False
def test_ANP_arithmetics():
mod = [QQ(1), QQ(0), QQ(0), QQ(-2)]
a = ANP([QQ(2), QQ(-1), QQ(1)], mod, QQ)
b = ANP([QQ(1), QQ(2)], mod, QQ)
c = ANP([QQ(-2), QQ(1), QQ(-1)], mod, QQ)
assert a.neg() == -a == c
c = ANP([QQ(2), QQ(0), QQ(3)], mod, QQ)
assert a.add(b) == a + b == c
assert b.add(a) == b + a == c
c = ANP([QQ(2), QQ(-2), QQ(-1)], mod, QQ)
assert a.sub(b) == a - b == c
c = ANP([QQ(-2), QQ(2), QQ(1)], mod, QQ)
assert b.sub(a) == b - a == c
c = ANP([QQ(3), QQ(-1), QQ(6)], mod, QQ)
assert a.mul(b) == a*b == c
assert b.mul(a) == b*a == c
c = ANP([QQ(-1, 43), QQ(9, 43), QQ(5, 43)], mod, QQ)
assert a.pow(0) == a**(0) == ANP(1, mod, QQ)
assert a.pow(1) == a**(1) == a
assert a.pow(-1) == a**(-1) == c
assert a.quo(a) == a.mul(a.pow(-1)) == a*a**(-1) == ANP(1, mod, QQ)
c = ANP([], [1, 0, 0, -2], QQ)
r1 = a.rem(b)
(q, r2) = a.div(b)
assert r1 == r2 == c == a % b
raises(NotInvertible, lambda: a.div(c))
raises(NotInvertible, lambda: a.rem(c))
# Comparison with "hard-coded" value fails despite looking identical
# from sympy import Rational
# c = ANP([Rational(11, 10), Rational(-1, 5), Rational(-3, 5)], [1, 0, 0, -2], QQ)
assert q == a/b # == c
def test_ANP_unify():
mod = [QQ(1), QQ(0), QQ(-2)]
a = ANP([QQ(1)], mod, QQ)
b = ANP([ZZ(1)], mod, ZZ)
assert a.unify(b)[0] == QQ
assert b.unify(a)[0] == QQ
assert a.unify(a)[0] == QQ
assert b.unify(b)[0] == ZZ
def test___hash__():
# issue 5571
# Make sure int vs. long doesn't affect hashing with Python ground types
assert DMP([[1, 2], [3]], ZZ) == DMP([[int(1), int(2)], [int(3)]], ZZ)
assert hash(DMP([[1, 2], [3]], ZZ)) == hash(DMP([[int(1), int(2)], [int(3)]], ZZ))
assert DMF(
([[1, 2], [3]], [[1]]), ZZ) == DMF(([[int(1), int(2)], [int(3)]], [[int(1)]]), ZZ)
assert hash(DMF(([[1, 2], [3]], [[1]]), ZZ)) == hash(DMF(([[int(1),
int(2)], [int(3)]], [[int(1)]]), ZZ))
assert ANP([1, 1], [1, 0, 1], ZZ) == ANP([int(1), int(1)], [int(1), int(0), int(1)], ZZ)
assert hash(
ANP([1, 1], [1, 0, 1], ZZ)) == hash(ANP([int(1), int(1)], [int(1), int(0), int(1)], ZZ))
|
b18aa7b9261b3995024959e8365e45f353cd25f9cf4681f352d13c06ba5cd892 | """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.core.random 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*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)]
|
690066feb80ac631ce09392d39827e688e42a5be7d201bd6262c990a8c1c33e2 | """Utilities for algebraic number theory. """
from sympy.core.sympify import sympify
from sympy.ntheory.factor_ import factorint
from sympy.polys.domains.rationalfield import QQ
from sympy.polys.domains.integerring import ZZ
from sympy.polys.matrices.exceptions import DMRankError
from sympy.polys.numberfields.minpoly import minpoly
from sympy.printing.lambdarepr import IntervalPrinter
from sympy.utilities.decorator import public
from sympy.utilities.lambdify import lambdify
from mpmath import mp
def is_rat(c):
r"""
Test whether an argument is of an acceptable type to be used as a rational
number.
Explanation
===========
Returns ``True`` on any argument of type ``int``, :ref:`ZZ`, or :ref:`QQ`.
See Also
========
is_int
"""
# ``c in QQ`` is too accepting (e.g. ``3.14 in QQ`` is ``True``),
# ``QQ.of_type(c)`` is too demanding (e.g. ``QQ.of_type(3)`` is ``False``).
#
# Meanwhile, if gmpy2 is installed then ``ZZ.of_type()`` accepts only
# ``mpz``, not ``int``, so we need another clause to ensure ``int`` is
# accepted.
return isinstance(c, int) or ZZ.of_type(c) or QQ.of_type(c)
def is_int(c):
r"""
Test whether an argument is of an acceptable type to be used as an integer.
Explanation
===========
Returns ``True`` on any argument of type ``int`` or :ref:`ZZ`.
See Also
========
is_rat
"""
# If gmpy2 is installed then ``ZZ.of_type()`` accepts only
# ``mpz``, not ``int``, so we need another clause to ensure ``int`` is
# accepted.
return isinstance(c, int) or ZZ.of_type(c)
def get_num_denom(c):
r"""
Given any argument on which :py:func:`~.is_rat` is ``True``, return the
numerator and denominator of this number.
See Also
========
is_rat
"""
r = QQ(c)
return r.numerator, r.denominator
@public
def extract_fundamental_discriminant(a):
r"""
Extract a fundamental discriminant from an integer *a*.
Explanation
===========
Given any rational integer *a* that is 0 or 1 mod 4, write $a = d f^2$,
where $d$ is either 1 or a fundamental discriminant, and return a pair
of dictionaries ``(D, F)`` giving the prime factorizations of $d$ and $f$
respectively, in the same format returned by :py:func:`~.factorint`.
A fundamental discriminant $d$ is different from unity, and is either
1 mod 4 and squarefree, or is 0 mod 4 and such that $d/4$ is squarefree
and 2 or 3 mod 4. This is the same as being the discriminant of some
quadratic field.
Examples
========
>>> from sympy.polys.numberfields.utilities import extract_fundamental_discriminant
>>> print(extract_fundamental_discriminant(-432))
({3: 1, -1: 1}, {2: 2, 3: 1})
For comparison:
>>> from sympy import factorint
>>> print(factorint(-432))
{2: 4, 3: 3, -1: 1}
Parameters
==========
a: int, must be 0 or 1 mod 4
Returns
=======
Pair ``(D, F)`` of dictionaries.
Raises
======
ValueError
If *a* is not 0 or 1 mod 4.
References
==========
.. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
(See Prop. 5.1.3)
"""
if a % 4 not in [0, 1]:
raise ValueError('To extract fundamental discriminant, number must be 0 or 1 mod 4.')
if a == 0:
return {}, {0: 1}
if a == 1:
return {}, {}
a_factors = factorint(a)
D = {}
F = {}
# First pass: just make d squarefree, and a/d a perfect square.
# We'll count primes (and units! i.e. -1) that are 3 mod 4 and present in d.
num_3_mod_4 = 0
for p, e in a_factors.items():
if e % 2 == 1:
D[p] = 1
if p % 4 == 3:
num_3_mod_4 += 1
if e >= 3:
F[p] = (e - 1) // 2
else:
F[p] = e // 2
# Second pass: if d is cong. to 2 or 3 mod 4, then we must steal away
# another factor of 4 from f**2 and give it to d.
even = 2 in D
if even or num_3_mod_4 % 2 == 1:
e2 = F[2]
assert e2 > 0
if e2 == 1:
del F[2]
else:
F[2] = e2 - 1
D[2] = 3 if even else 2
return D, F
@public
class AlgIntPowers:
r"""
Compute the powers of an algebraic integer.
Explanation
===========
Given an algebraic integer $\theta$ by its monic irreducible polynomial
``T`` over :ref:`ZZ`, this class computes representations of arbitrarily
high powers of $\theta$, as :ref:`ZZ`-linear combinations over
$\{1, \theta, \ldots, \theta^{n-1}\}$, where $n = \deg(T)$.
The representations are computed using the linear recurrence relations for
powers of $\theta$, derived from the polynomial ``T``. See [1], Sec. 4.2.2.
Optionally, the representations may be reduced with respect to a modulus.
Examples
========
>>> from sympy import Poly, cyclotomic_poly
>>> from sympy.polys.numberfields.utilities import AlgIntPowers
>>> T = Poly(cyclotomic_poly(5))
>>> zeta_pow = AlgIntPowers(T)
>>> print(zeta_pow[0])
[1, 0, 0, 0]
>>> print(zeta_pow[1])
[0, 1, 0, 0]
>>> print(zeta_pow[4]) # doctest: +SKIP
[-1, -1, -1, -1]
>>> print(zeta_pow[24]) # doctest: +SKIP
[-1, -1, -1, -1]
References
==========
.. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
"""
def __init__(self, T, modulus=None):
"""
Parameters
==========
T : :py:class:`~.Poly`
The monic irreducible polynomial over :ref:`ZZ` defining the
algebraic integer.
modulus : int, None, optional
If not ``None``, all representations will be reduced w.r.t. this.
"""
self.T = T
self.modulus = modulus
self.n = T.degree()
self.powers_n_and_up = [[-c % self for c in reversed(T.rep.rep)][:-1]]
self.max_so_far = self.n
def red(self, exp):
return exp if self.modulus is None else exp % self.modulus
def __rmod__(self, other):
return self.red(other)
def compute_up_through(self, e):
m = self.max_so_far
if e <= m: return
n = self.n
r = self.powers_n_and_up
c = r[0]
for k in range(m+1, e+1):
b = r[k-1-n][n-1]
r.append(
[c[0]*b % self] + [
(r[k-1-n][i-1] + c[i]*b) % self for i in range(1, n)
]
)
self.max_so_far = e
def get(self, e):
n = self.n
if e < 0:
raise ValueError('Exponent must be non-negative.')
elif e < n:
return [1 if i == e else 0 for i in range(n)]
else:
self.compute_up_through(e)
return self.powers_n_and_up[e - n]
def __getitem__(self, item):
return self.get(item)
@public
def coeff_search(m, R):
r"""
Generate coefficients for searching through polynomials.
Explanation
===========
Lead coeff is always non-negative. Explore all combinations with coeffs
bounded in absolute value before increasing the bound. Skip the all-zero
list, and skip any repeats. See examples.
Examples
========
>>> from sympy.polys.numberfields.utilities import coeff_search
>>> cs = coeff_search(2, 1)
>>> C = [next(cs) for i in range(13)]
>>> print(C)
[[1, 1], [1, 0], [1, -1], [0, 1], [2, 2], [2, 1], [2, 0], [2, -1], [2, -2],
[1, 2], [1, -2], [0, 2], [3, 3]]
Parameters
==========
m : int
Length of coeff list.
R : int
Initial max abs val for coeffs (will increase as search proceeds).
Returns
=======
generator
Infinite generator of lists of coefficients.
"""
R0 = R
c = [R] * m
while True:
if R == R0 or R in c or -R in c:
yield c[:]
j = m - 1
while c[j] == -R:
j -= 1
c[j] -= 1
for i in range(j + 1, m):
c[i] = R
for j in range(m):
if c[j] != 0:
break
else:
R += 1
c = [R] * m
def supplement_a_subspace(M):
r"""
Extend a basis for a subspace to a basis for the whole space.
Explanation
===========
Given an $n \times r$ matrix *M* of rank $r$ (so $r \leq n$), this function
computes an invertible $n \times n$ matrix $B$ such that the first $r$
columns of $B$ equal *M*.
This operation can be interpreted as a way of extending a basis for a
subspace, to give a basis for the whole space.
To be precise, suppose you have an $n$-dimensional vector space $V$, with
basis $\{v_1, v_2, \ldots, v_n\}$, and an $r$-dimensional subspace $W$ of
$V$, spanned by a basis $\{w_1, w_2, \ldots, w_r\}$, where the $w_j$ are
given as linear combinations of the $v_i$. If the columns of *M* represent
the $w_j$ as such linear combinations, then the columns of the matrix $B$
computed by this function give a new basis $\{u_1, u_2, \ldots, u_n\}$ for
$V$, again relative to the $\{v_i\}$ basis, and such that $u_j = w_j$
for $1 \leq j \leq r$.
Examples
========
Note: The function works in terms of columns, so in these examples we
print matrix transposes in order to make the columns easier to inspect.
>>> from sympy.polys.matrices import DM
>>> from sympy import QQ, FF
>>> from sympy.polys.numberfields.utilities import supplement_a_subspace
>>> M = DM([[1, 7, 0], [2, 3, 4]], QQ).transpose()
>>> print(supplement_a_subspace(M).to_Matrix().transpose())
Matrix([[1, 7, 0], [2, 3, 4], [1, 0, 0]])
>>> M2 = M.convert_to(FF(7))
>>> print(M2.to_Matrix().transpose())
Matrix([[1, 0, 0], [2, 3, -3]])
>>> print(supplement_a_subspace(M2).to_Matrix().transpose())
Matrix([[1, 0, 0], [2, 3, -3], [0, 1, 0]])
Parameters
==========
M : :py:class:`~.DomainMatrix`
The columns give the basis for the subspace.
Returns
=======
:py:class:`~.DomainMatrix`
This matrix is invertible and its first $r$ columns equal *M*.
Raises
======
DMRankError
If *M* was not of maximal rank.
References
==========
.. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*
(See Sec. 2.3.2.)
"""
n, r = M.shape
# Let In be the n x n identity matrix.
# Form the augmented matrix [M | In] and compute RREF.
Maug = M.hstack(M.eye(n, M.domain))
R, pivots = Maug.rref()
if pivots[:r] != tuple(range(r)):
raise DMRankError('M was not of maximal rank')
# Let J be the n x r matrix equal to the first r columns of In.
# Since M is of rank r, RREF reduces [M | In] to [J | A], where A is the product of
# elementary matrices Ei corresp. to the row ops performed by RREF. Since the Ei are
# invertible, so is A. Let B = A^(-1).
A = R[:, r:]
B = A.inv()
# Then B is the desired matrix. It is invertible, since B^(-1) == A.
# And A * [M | In] == [J | A]
# => A * M == J
# => M == B * J == the first r columns of B.
return B
@public
def isolate(alg, eps=None, fast=False):
"""
Find a rational isolating interval for a real algebraic number.
Examples
========
>>> from sympy import isolate, sqrt, Rational
>>> print(isolate(sqrt(2))) # doctest: +SKIP
(1, 2)
>>> print(isolate(sqrt(2), eps=Rational(1, 100)))
(24/17, 17/12)
Parameters
==========
alg : str, int, :py:class:`~.Expr`
The algebraic number to be isolated. Must be a real number, to use this
particular function. However, see also :py:meth:`.Poly.intervals`,
which isolates complex roots when you pass ``all=True``.
eps : positive element of :ref:`QQ`, None, optional (default=None)
Precision to be passed to :py:meth:`.Poly.refine_root`
fast : boolean, optional (default=False)
Say whether fast refinement procedure should be used.
(Will be passed to :py:meth:`.Poly.refine_root`.)
Returns
=======
Pair of rational numbers defining an isolating interval for the given
algebraic number.
See Also
========
.Poly.intervals
"""
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)
|
372e0f8ccaedc7bd24eafc159a2bda47086f77842a923edc162b7dec1ceb6f49 | """Prime ideals in number fields. """
from sympy.core.expr import Expr
from sympy.polys.polytools import Poly
from sympy.polys.domains.finitefield import FF
from sympy.polys.domains.rationalfield import QQ
from sympy.polys.domains.integerring import ZZ
from sympy.polys.matrices.domainmatrix import DomainMatrix
from sympy.polys.polyerrors import CoercionFailed, GeneratorsNeeded
from sympy.polys.polyutils import IntegerPowerable
from sympy.utilities.decorator import public
from .basis import round_two, nilradical_mod_p
from .exceptions import StructureError
from .modules import ModuleEndomorphism, find_min_poly
from .utilities import coeff_search, supplement_a_subspace
def _check_formal_conditions_for_maximal_order(submodule):
r"""
Several functions in this module accept an argument which is to be a
:py:class:`~.Submodule` representing the maximal order in a number field,
such as returned by the :py:func:`~sympy.polys.numberfields.basis.round_two`
algorithm.
We do not attempt to check that the given ``Submodule`` actually represents
a maximal order, but we do check a basic set of formal conditions that the
``Submodule`` must satisfy, at a minimum. The purpose is to catch an
obviously ill-formed argument.
"""
prefix = 'The submodule representing the maximal order should '
cond = None
if not submodule.is_power_basis_submodule():
cond = 'be a direct submodule of a power basis.'
elif not submodule.starts_with_unity():
cond = 'have 1 as its first generator.'
elif not submodule.is_sq_maxrank_HNF():
cond = 'have square matrix, of maximal rank, in Hermite Normal Form.'
if cond is not None:
raise StructureError(prefix + cond)
class PrimeIdeal(IntegerPowerable):
r"""
A prime ideal in a ring of algebraic integers.
"""
def __init__(self, ZK, p, alpha, f, e=None):
"""
Parameters
==========
ZK : :py:class:`~.Submodule`
The maximal order where this ideal lives.
p : int
The rational prime this ideal divides.
alpha : :py:class:`~.PowerBasisElement`
Such that the ideal is equal to ``p*ZK + alpha*ZK``.
f : int
The inertia degree.
e : int, ``None``, optional
The ramification index, if already known. If ``None``, we will
compute it here.
"""
_check_formal_conditions_for_maximal_order(ZK)
self.ZK = ZK
self.p = p
self.alpha = alpha
self.f = f
self._test_factor = None
self.e = e if e is not None else self.valuation(p * ZK)
def pretty(self, field_gen=None, just_gens=False):
"""
Print a representation of this prime ideal.
Examples
========
>>> from sympy import cyclotomic_poly, QQ
>>> from sympy.abc import x, zeta
>>> T = cyclotomic_poly(7, x)
>>> K = QQ.algebraic_field((T, zeta))
>>> P = K.primes_above(11)
>>> print(P[0].pretty())
[ (11, x**3 + 5*x**2 + 4*x - 1) e=1, f=3 ]
>>> print(P[0].pretty(field_gen=zeta))
[ (11, zeta**3 + 5*zeta**2 + 4*zeta - 1) e=1, f=3 ]
>>> print(P[0].pretty(field_gen=zeta, just_gens=True))
(11, zeta**3 + 5*zeta**2 + 4*zeta - 1)
Parameters
==========
field_gen : :py:class:`~.Symbol`, ``None``, optional (default=None)
The symbol to use for the generator of the field. This will appear
in our representation of ``self.alpha``. If ``None``, we use the
variable of the defining polynomial of ``self.ZK``.
just_gens : bool, optional (default=False)
If ``True``, just print the "(p, alpha)" part, showing "just the
generators" of the prime ideal. Otherwise, print a string of the
form "[ (p, alpha) e=..., f=... ]", giving the ramification index
and inertia degree, along with the generators.
"""
field_gen = field_gen or self.ZK.parent.T.gen
p, alpha, e, f = self.p, self.alpha, self.e, self.f
alpha_rep = str(alpha.numerator(x=field_gen).as_expr())
if alpha.denom > 1:
alpha_rep = f'({alpha_rep})/{alpha.denom}'
gens = f'({p}, {alpha_rep})'
if just_gens:
return gens
return f'[ {gens} e={e}, f={f} ]'
def __repr__(self):
return self.pretty()
def as_submodule(self):
r"""
Represent this prime ideal as a :py:class:`~.Submodule`.
Explanation
===========
The :py:class:`~.PrimeIdeal` class serves to bundle information about
a prime ideal, such as its inertia degree, ramification index, and
two-generator representation, as well as to offer helpful methods like
:py:meth:`~.PrimeIdeal.valuation` and
:py:meth:`~.PrimeIdeal.test_factor`.
However, in order to be added and multiplied by other ideals or
rational numbers, it must first be converted into a
:py:class:`~.Submodule`, which is a class that supports these
operations.
In many cases, the user need not perform this conversion deliberately,
since it is automatically performed by the arithmetic operator methods
:py:meth:`~.PrimeIdeal.__add__` and :py:meth:`~.PrimeIdeal.__mul__`.
Raising a :py:class:`~.PrimeIdeal` to a non-negative integer power is
also supported.
Examples
========
>>> from sympy import Poly, cyclotomic_poly, prime_decomp
>>> T = Poly(cyclotomic_poly(7))
>>> P0 = prime_decomp(7, T)[0]
>>> print(P0**6 == 7*P0.ZK)
True
Note that, on both sides of the equation above, we had a
:py:class:`~.Submodule`. In the next equation we recall that adding
ideals yields their GCD. This time, we need a deliberate conversion
to :py:class:`~.Submodule` on the right:
>>> print(P0 + 7*P0.ZK == P0.as_submodule())
True
Returns
=======
:py:class:`~.Submodule`
Will be equal to ``self.p * self.ZK + self.alpha * self.ZK``.
See Also
========
__add__
__mul__
"""
M = self.p * self.ZK + self.alpha * self.ZK
# Pre-set expensive boolean properties whose value we already know:
M._starts_with_unity = False
M._is_sq_maxrank_HNF = True
return M
def __eq__(self, other):
if isinstance(other, PrimeIdeal):
return self.as_submodule() == other.as_submodule()
return NotImplemented
def __add__(self, other):
"""
Convert to a :py:class:`~.Submodule` and add to another
:py:class:`~.Submodule`.
See Also
========
as_submodule
"""
return self.as_submodule() + other
__radd__ = __add__
def __mul__(self, other):
"""
Convert to a :py:class:`~.Submodule` and multiply by another
:py:class:`~.Submodule` or a rational number.
See Also
========
as_submodule
"""
return self.as_submodule() * other
__rmul__ = __mul__
def _zeroth_power(self):
return self.ZK
def _first_power(self):
return self
def test_factor(self):
r"""
Compute a test factor for this prime ideal.
Explanation
===========
Write $\mathfrak{p}$ for this prime ideal, $p$ for the rational prime
it divides. Then, for computing $\mathfrak{p}$-adic valuations it is
useful to have a number $\beta \in \mathbb{Z}_K$ such that
$p/\mathfrak{p} = p \mathbb{Z}_K + \beta \mathbb{Z}_K$.
Essentially, this is the same as the number $\Psi$ (or the "reagent")
from Kummer's 1847 paper (*Ueber die Zerlegung...*, Crelle vol. 35) in
which ideal divisors were invented.
"""
if self._test_factor is None:
self._test_factor = _compute_test_factor(self.p, [self.alpha], self.ZK)
return self._test_factor
def valuation(self, I):
r"""
Compute the $\mathfrak{p}$-adic valuation of integral ideal I at this
prime ideal.
Parameters
==========
I : :py:class:`~.Submodule`
See Also
========
prime_valuation
"""
return prime_valuation(I, self)
def reduce_poly(self, f, gen=None):
r"""
Reduce a univariate :py:class:`~.Poly` *f*, or an :py:class:`~.Expr`
expressing the same, modulo this :py:class:`~.PrimeIdeal`.
Explanation
===========
If our second generator $\alpha$ is zero, then we simply reduce the
coefficients of *f* mod the rational prime $p$ lying under this ideal.
Otherwise we first reduce *f* mod $\alpha$ (as a polynomial in the same
variable as *f*), and then mod $p$.
Examples
========
>>> from sympy import QQ, cyclotomic_poly, symbols
>>> zeta = symbols('zeta')
>>> Phi = cyclotomic_poly(7, zeta)
>>> k = QQ.algebraic_field((Phi, zeta))
>>> P = k.primes_above(11)
>>> frp = P[0]
>>> B = k.integral_basis(fmt='sympy')
>>> print([frp.reduce_poly(b, zeta) for b in B])
[1, zeta, zeta**2, -5*zeta**2 - 4*zeta + 1, -zeta**2 - zeta - 5,
4*zeta**2 - zeta - 1]
Parameters
==========
f : :py:class:`~.Poly`, :py:class:`~.Expr`
The univariate polynomial to be reduced.
gen : :py:class:`~.Symbol`, None, optional (default=None)
Symbol to use as the variable in the polynomials. If *f* is a
:py:class:`~.Poly` or a non-constant :py:class:`~.Expr`, this
replaces its variable. If *f* is a constant :py:class:`~.Expr`,
then *gen* must be supplied.
Returns
=======
:py:class:`~.Poly`, :py:class:`~.Expr`
Type is same as that of given *f*. If returning a
:py:class:`~.Poly`, its domain will be the finite field
$\mathbb{F}_p$.
Raises
======
GeneratorsNeeded
If *f* is a constant :py:class:`~.Expr` and *gen* is ``None``.
NotImplementedError
If *f* is other than :py:class:`~.Poly` or :py:class:`~.Expr`,
or is not univariate.
"""
if isinstance(f, Expr):
try:
g = Poly(f)
except GeneratorsNeeded as e:
if gen is None:
raise e from None
g = Poly(f, gen)
return self.reduce_poly(g).as_expr()
if isinstance(f, Poly) and f.is_univariate:
a = self.alpha.poly(f.gen)
if a != 0:
f = f.rem(a)
return f.set_modulus(self.p)
raise NotImplementedError
def _compute_test_factor(p, gens, ZK):
r"""
Compute the test factor for a :py:class:`~.PrimeIdeal` $\mathfrak{p}$.
Parameters
==========
p : int
The rational prime $\mathfrak{p}$ divides
gens : list of :py:class:`PowerBasisElement`
A complete set of generators for $\mathfrak{p}$ over *ZK*, EXCEPT that
an element equivalent to rational *p* can and should be omitted (since
it has no effect except to waste time).
ZK : :py:class:`~.Submodule`
The maximal order where the prime ideal $\mathfrak{p}$ lives.
Returns
=======
:py:class:`~.PowerBasisElement`
References
==========
.. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
(See Proposition 4.8.15.)
"""
_check_formal_conditions_for_maximal_order(ZK)
E = ZK.endomorphism_ring()
matrices = [E.inner_endomorphism(g).matrix(modulus=p) for g in gens]
B = DomainMatrix.zeros((0, ZK.n), FF(p)).vstack(*matrices)
# A nonzero element of the nullspace of B will represent a
# lin comb over the omegas which (i) is not a multiple of p
# (since it is nonzero over FF(p)), while (ii) is such that
# its product with each g in gens _is_ a multiple of p (since
# B represents multiplication by these generators). Theory
# predicts that such an element must exist, so nullspace should
# be non-trivial.
x = B.nullspace()[0, :].transpose()
beta = ZK.parent(ZK.matrix * x, denom=ZK.denom)
return beta
@public
def prime_valuation(I, P):
r"""
Compute the *P*-adic valuation for an integral ideal *I*.
Examples
========
>>> from sympy import QQ
>>> from sympy.abc import theta
>>> from sympy.polys import cyclotomic_poly
>>> from sympy.polys.numberfields import prime_valuation
>>> T = cyclotomic_poly(5)
>>> K = QQ.algebraic_field((T, theta))
>>> P = K.primes_above(5)
>>> ZK = K.maximal_order()
>>> print(prime_valuation(25*ZK, P[0]))
8
Parameters
==========
I : :py:class:`~.Submodule`
An integral ideal whose valuation is desired.
P : :py:class:`~.PrimeIdeal`
The prime at which to compute the valuation.
Returns
=======
int
See Also
========
.PrimeIdeal.valuation
References
==========
.. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
(See Algorithm 4.8.17.)
"""
p, ZK = P.p, P.ZK
n, W, d = ZK.n, ZK.matrix, ZK.denom
A = W.convert_to(QQ).inv() * I.matrix * d / I.denom
# Although A must have integer entries, given that I is an integral ideal,
# as a DomainMatrix it will still be over QQ, so we convert back:
A = A.convert_to(ZZ)
D = A.det()
if D % p != 0:
return 0
beta = P.test_factor()
f = d ** n // W.det()
need_complete_test = (f % p == 0)
v = 0
while True:
# Entering the loop, the cols of A represent lin combs of omegas.
# Turn them into lin combs of thetas:
A = W * A
# And then one column at a time...
for j in range(n):
c = ZK.parent(A[:, j], denom=d)
c *= beta
# ...turn back into lin combs of omegas, after multiplying by beta:
c = ZK.represent(c).flat()
for i in range(n):
A[i, j] = c[i]
if A[n - 1, n - 1].element % p != 0:
break
A = A / p
# As noted above, domain converts to QQ even when division goes evenly.
# So must convert back, even when we don't "need_complete_test".
if need_complete_test:
# In this case, having a non-integer entry is actually just our
# halting condition.
try:
A = A.convert_to(ZZ)
except CoercionFailed:
break
else:
# In this case theory says we should not have any non-integer entries.
A = A.convert_to(ZZ)
v += 1
return v
def _two_elt_rep(gens, ZK, p, f=None, Np=None):
r"""
Given a set of *ZK*-generators of a prime ideal, compute a set of just two
*ZK*-generators for the same ideal, one of which is *p* itself.
Parameters
==========
gens : list of :py:class:`PowerBasisElement`
Generators for the prime ideal over *ZK*, the ring of integers of the
field $K$.
ZK : :py:class:`~.Submodule`
The maximal order in $K$.
p : int
The rational prime divided by the prime ideal.
f : int, optional
The inertia degree of the prime ideal, if known.
Np : int, optional
The norm $p^f$ of the prime ideal, if known.
NOTE: There is no reason to supply both *f* and *Np*. Either one will
save us from having to compute the norm *Np* ourselves. If both are known,
*Np* is preferred since it saves one exponentiation.
Returns
=======
:py:class:`~.PowerBasisElement` representing a single algebraic integer
alpha such that the prime ideal is equal to ``p*ZK + alpha*ZK``.
References
==========
.. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
(See Algorithm 4.7.10.)
"""
_check_formal_conditions_for_maximal_order(ZK)
pb = ZK.parent
T = pb.T
# Detect the special cases in which either (a) all generators are multiples
# of p, or (b) there are no generators (so `all` is vacuously true):
if all((g % p).equiv(0) for g in gens):
return pb.zero()
if Np is None:
if f is not None:
Np = p**f
else:
Np = abs(pb.submodule_from_gens(gens).matrix.det())
omega = ZK.basis_element_pullbacks()
beta = [p*om for om in omega[1:]] # note: we omit omega[0] == 1
beta += gens
search = coeff_search(len(beta), 1)
for c in search:
alpha = sum(ci*betai for ci, betai in zip(c, beta))
# Note: It may be tempting to reduce alpha mod p here, to try to work
# with smaller numbers, but must not do that, as it can result in an
# infinite loop! E.g. try factoring 2 in Q(sqrt(-7)).
n = alpha.norm(T) // Np
if n % p != 0:
# Now can reduce alpha mod p.
return alpha % p
def _prime_decomp_easy_case(p, ZK):
r"""
Compute the decomposition of rational prime *p* in the ring of integers
*ZK* (given as a :py:class:`~.Submodule`), in the "easy case", i.e. the
case where *p* does not divide the index of $\theta$ in *ZK*, where
$\theta$ is the generator of the ``PowerBasis`` of which *ZK* is a
``Submodule``.
"""
T = ZK.parent.T
T_bar = Poly(T, modulus=p)
lc, fl = T_bar.factor_list()
return [PrimeIdeal(ZK, p,
ZK.parent.element_from_poly(Poly(t, domain=ZZ)),
t.degree(), e)
for t, e in fl]
def _prime_decomp_compute_kernel(I, p, ZK):
r"""
Parameters
==========
I : :py:class:`~.Module`
An ideal of ``ZK/pZK``.
p : int
The rational prime being factored.
ZK : :py:class:`~.Submodule`
The maximal order.
Returns
=======
Pair ``(N, G)``, where:
``N`` is a :py:class:`~.Module` representing the kernel of the map
``a |--> a**p - a`` on ``(O/pO)/I``, guaranteed to be a module with
unity.
``G`` is a :py:class:`~.Module` representing a basis for the separable
algebra ``A = O/I`` (see Cohen).
"""
W = I.matrix
n, r = W.shape
# Want to take the Fp-basis given by the columns of I, adjoin (1, 0, ..., 0)
# (which we know is not already in there since I is a basis for a prime ideal)
# and then supplement this with additional columns to make an invertible n x n
# matrix. This will then represent a full basis for ZK, whose first r columns
# are pullbacks of the basis for I.
if r == 0:
B = W.eye(n, ZZ)
else:
B = W.hstack(W.eye(n, ZZ)[:, 0])
if B.shape[1] < n:
B = supplement_a_subspace(B.convert_to(FF(p))).convert_to(ZZ)
G = ZK.submodule_from_matrix(B)
# Must compute G's multiplication table _before_ discarding the first r
# columns. (See Step 9 in Alg 6.2.9 in Cohen, where the betas are actually
# needed in order to represent each product of gammas. However, once we've
# found the representations, then we can ignore the betas.)
G.compute_mult_tab()
G = G.discard_before(r)
phi = ModuleEndomorphism(G, lambda x: x**p - x)
N = phi.kernel(modulus=p)
assert N.starts_with_unity()
return N, G
def _prime_decomp_maximal_ideal(I, p, ZK):
r"""
We have reached the case where we have a maximal (hence prime) ideal *I*,
which we know because the quotient ``O/I`` is a field.
Parameters
==========
I : :py:class:`~.Module`
An ideal of ``O/pO``.
p : int
The rational prime being factored.
ZK : :py:class:`~.Submodule`
The maximal order.
Returns
=======
:py:class:`~.PrimeIdeal` instance representing this prime
"""
m, n = I.matrix.shape
f = m - n
G = ZK.matrix * I.matrix
gens = [ZK.parent(G[:, j], denom=ZK.denom) for j in range(G.shape[1])]
alpha = _two_elt_rep(gens, ZK, p, f=f)
return PrimeIdeal(ZK, p, alpha, f)
def _prime_decomp_split_ideal(I, p, N, G, ZK):
r"""
Perform the step in the prime decomposition algorithm where we have determined
the the quotient ``ZK/I`` is _not_ a field, and we want to perform a non-trivial
factorization of *I* by locating an idempotent element of ``ZK/I``.
"""
assert I.parent == ZK and G.parent is ZK and N.parent is G
# Since ZK/I is not a field, the kernel computed in the previous step contains
# more than just the prime field Fp, and our basis N for the nullspace therefore
# contains at least a second column (which represents an element outside Fp).
# Let alpha be such an element:
alpha = N(1).to_parent()
assert alpha.module is G
alpha_powers = []
m = find_min_poly(alpha, FF(p), powers=alpha_powers)
# TODO (future work):
# We don't actually need full factorization, so might use a faster method
# to just break off a single non-constant factor m1?
lc, fl = m.factor_list()
m1 = fl[0][0]
m2 = m.quo(m1)
U, V, g = m1.gcdex(m2)
# Sanity check: theory says m is squarefree, so m1, m2 should be coprime:
assert g == 1
E = list(reversed(Poly(U * m1, domain=ZZ).rep.rep))
eps1 = sum(E[i]*alpha_powers[i] for i in range(len(E)))
eps2 = 1 - eps1
idemps = [eps1, eps2]
factors = []
for eps in idemps:
e = eps.to_parent()
assert e.module is ZK
D = I.matrix.convert_to(FF(p)).hstack(*[
(e * om).column(domain=FF(p)) for om in ZK.basis_elements()
])
W = D.columnspace().convert_to(ZZ)
H = ZK.submodule_from_matrix(W)
factors.append(H)
return factors
@public
def prime_decomp(p, T=None, ZK=None, dK=None, radical=None):
r"""
Compute the decomposition of rational prime *p* in a number field.
Explanation
===========
Ordinarily this should be accessed through the
:py:meth:`~.AlgebraicField.primes_above` method of an
:py:class:`~.AlgebraicField`.
Examples
========
>>> from sympy import Poly, QQ
>>> from sympy.abc import x, theta
>>> T = Poly(x ** 3 + x ** 2 - 2 * x + 8)
>>> K = QQ.algebraic_field((T, theta))
>>> print(K.primes_above(2))
[[ (2, x**2 + 1) e=1, f=1 ], [ (2, (x**2 + 3*x + 2)/2) e=1, f=1 ],
[ (2, (3*x**2 + 3*x)/2) e=1, f=1 ]]
Parameters
==========
p : int
The rational prime whose decomposition is desired.
T : :py:class:`~.Poly`, optional
Monic irreducible polynomial defining the number field $K$ in which to
factor. NOTE: at least one of *T* or *ZK* must be provided.
ZK : :py:class:`~.Submodule`, optional
The maximal order for $K$, if already known.
NOTE: at least one of *T* or *ZK* must be provided.
dK : int, optional
The discriminant of the field $K$, if already known.
radical : :py:class:`~.Submodule`, optional
The nilradical mod *p* in the integers of $K$, if already known.
Returns
=======
List of :py:class:`~.PrimeIdeal` instances.
References
==========
.. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
(See Algorithm 6.2.9.)
"""
if T is None and ZK is None:
raise ValueError('At least one of T or ZK must be provided.')
if ZK is not None:
_check_formal_conditions_for_maximal_order(ZK)
if T is None:
T = ZK.parent.T
radicals = {}
if dK is None or ZK is None:
ZK, dK = round_two(T, radicals=radicals)
dT = T.discriminant()
f_squared = dT // dK
if f_squared % p != 0:
return _prime_decomp_easy_case(p, ZK)
radical = radical or radicals.get(p) or nilradical_mod_p(ZK, p)
stack = [radical]
primes = []
while stack:
I = stack.pop()
N, G = _prime_decomp_compute_kernel(I, p, ZK)
if N.n == 1:
P = _prime_decomp_maximal_ideal(I, p, ZK)
primes.append(P)
else:
I1, I2 = _prime_decomp_split_ideal(I, p, N, G, ZK)
stack.extend([I1, I2])
return primes
|
a14bab27178b370c66d1bdccb10fe302a9fee42d1a21b7e6e9731acc218105fe | """Computational algebraic field theory. """
__all__ = [
'minpoly', 'minimal_polynomial',
'field_isomorphism', 'primitive_element', 'to_number_field',
'isolate',
'round_two',
'prime_decomp', 'prime_valuation',
]
from .minpoly import minpoly, minimal_polynomial
from .subfield import field_isomorphism, primitive_element, to_number_field
from .utilities import isolate
from .basis import round_two
from .primes import prime_decomp, prime_valuation
|
5067abae7e27a5df6b9a7dc23f671bafc9415b9a364754d0eaf738e3261d1d1d | r"""Modules in number fields.
The classes defined here allow us to work with finitely generated, free
modules, whose generators are algebraic numbers.
There is an abstract base class called :py:class:`~.Module`, which has two
concrete subclasses, :py:class:`~.PowerBasis` and :py:class:`~.Submodule`.
Every module is defined by its basis, or set of generators:
* For a :py:class:`~.PowerBasis`, the generators are the first $n$ powers
(starting with the zeroth) of an algebraic integer $\theta$ of degree $n$.
The :py:class:`~.PowerBasis` is constructed by passing the minimal
polynomial of $\theta$.
* For a :py:class:`~.Submodule`, the generators are a set of
$\mathbb{Q}$-linear combinations of the generators of another module. That
other module is then the "parent" of the :py:class:`~.Submodule`. The
coefficients of the $\mathbb{Q}$-linear combinations may be given by an
integer matrix, and a positive integer denominator. Each column of the matrix
defines a generator.
>>> from sympy.polys import Poly, cyclotomic_poly, ZZ
>>> from sympy.abc import x
>>> from sympy.polys.matrices import DomainMatrix, DM
>>> from sympy.polys.numberfields.modules import PowerBasis
>>> T = Poly(cyclotomic_poly(5, x))
>>> A = PowerBasis(T)
>>> print(A)
PowerBasis(x**4 + x**3 + x**2 + x + 1)
>>> B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ), denom=3)
>>> print(B)
Submodule[[2, 0, 0, 0], [0, 2, 0, 0], [0, 0, 2, 0], [0, 0, 0, 2]]/3
>>> print(B.parent)
PowerBasis(x**4 + x**3 + x**2 + x + 1)
Thus, every module is either a :py:class:`~.PowerBasis`,
or a :py:class:`~.Submodule`, some ancestor of which is a
:py:class:`~.PowerBasis`. (If ``S`` is a :py:class:`~.Submodule`, then its
ancestors are ``S.parent``, ``S.parent.parent``, and so on).
The :py:class:`~.ModuleElement` class represents a linear combination of the
generators of any module. Critically, the coefficients of this linear
combination are not restricted to be integers, but may be any rational
numbers. This is necessary so that any and all algebraic integers be
representable, starting from the power basis in a primitive element $\theta$
for the number field in question. For example, in a quadratic field
$\mathbb{Q}(\sqrt{d})$ where $d \equiv 1 \mod{4}$, a denominator of $2$ is
needed.
A :py:class:`~.ModuleElement` can be constructed from an integer column vector
and a denominator:
>>> U = Poly(x**2 - 5)
>>> M = PowerBasis(U)
>>> e = M(DM([[1], [1]], ZZ), denom=2)
>>> print(e)
[1, 1]/2
>>> print(e.module)
PowerBasis(x**2 - 5)
The :py:class:`~.PowerBasisElement` class is a subclass of
:py:class:`~.ModuleElement` that represents elements of a
:py:class:`~.PowerBasis`, and adds functionality pertinent to elements
represented directly over powers of the primitive element $\theta$.
Arithmetic with module elements
===============================
While a :py:class:`~.ModuleElement` represents a linear combination over the
generators of a particular module, recall that every module is either a
:py:class:`~.PowerBasis` or a descendant (along a chain of
:py:class:`~.Submodule` objects) thereof, so that in fact every
:py:class:`~.ModuleElement` represents an algebraic number in some field
$\mathbb{Q}(\theta)$, where $\theta$ is the defining element of some
:py:class:`~.PowerBasis`. It thus makes sense to talk about the number field
to which a given :py:class:`~.ModuleElement` belongs.
This means that any two :py:class:`~.ModuleElement` instances can be added,
subtracted, multiplied, or divided, provided they belong to the same number
field. Similarly, since $\mathbb{Q}$ is a subfield of every number field,
any :py:class:`~.ModuleElement` may be added, multiplied, etc. by any
rational number.
>>> from sympy import QQ
>>> from sympy.polys.numberfields.modules import to_col
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
>>> e = A(to_col([0, 2, 0, 0]), denom=3)
>>> f = A(to_col([0, 0, 0, 7]), denom=5)
>>> g = C(to_col([1, 1, 1, 1]))
>>> e + f
[0, 10, 0, 21]/15
>>> e - f
[0, 10, 0, -21]/15
>>> e - g
[-9, -7, -9, -9]/3
>>> e + QQ(7, 10)
[21, 20, 0, 0]/30
>>> e * f
[-14, -14, -14, -14]/15
>>> e ** 2
[0, 0, 4, 0]/9
>>> f // g
[7, 7, 7, 7]/15
>>> f * QQ(2, 3)
[0, 0, 0, 14]/15
However, care must be taken with arithmetic operations on
:py:class:`~.ModuleElement`, because the module $C$ to which the result will
belong will be the nearest common ancestor (NCA) of the modules $A$, $B$ to
which the two operands belong, and $C$ may be different from either or both
of $A$ and $B$.
>>> A = PowerBasis(T)
>>> B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
>>> C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
>>> print((B(0) * C(0)).module == A)
True
Before the arithmetic operation is performed, copies of the two operands are
automatically converted into elements of the NCA (the operands themselves are
not modified). This upward conversion along an ancestor chain is easy: it just
requires the successive multiplication by the defining matrix of each
:py:class:`~.Submodule`.
Conversely, downward conversion, i.e. representing a given
:py:class:`~.ModuleElement` in a submodule, is also supported -- namely by
the :py:meth:`~sympy.polys.numberfields.modules.Submodule.represent` method
-- but is not guaranteed to succeed in general, since the given element may
not belong to the submodule. The main circumstance in which this issue tends
to arise is with multiplication, since modules, while closed under addition,
need not be closed under multiplication.
Multiplication
--------------
Generally speaking, a module need not be closed under multiplication, i.e. need
not form a ring. However, many of the modules we work with in the context of
number fields are in fact rings, and our classes do support multiplication.
Specifically, any :py:class:`~.Module` can attempt to compute its own
multiplication table, but this does not happen unless an attempt is made to
multiply two :py:class:`~.ModuleElement` instances belonging to it.
>>> A = PowerBasis(T)
>>> print(A._mult_tab is None)
True
>>> a = A(0)*A(1)
>>> print(A._mult_tab is None)
False
Every :py:class:`~.PowerBasis` is, by its nature, closed under multiplication,
so instances of :py:class:`~.PowerBasis` can always successfully compute their
multiplication table.
When a :py:class:`~.Submodule` attempts to compute its multiplication table,
it converts each of its own generators into elements of its parent module,
multiplies them there, in every possible pairing, and then tries to
represent the results in itself, i.e. as $\mathbb{Z}$-linear combinations
over its own generators. This will succeed if and only if the submodule is
in fact closed under multiplication.
Module Homomorphisms
====================
Many important number theoretic algorithms require the calculation of the
kernel of one or more module homomorphisms. Accordingly we have several
lightweight classes, :py:class:`~.ModuleHomomorphism`,
:py:class:`~.ModuleEndomorphism`, :py:class:`~.InnerEndomorphism`, and
:py:class:`~.EndomorphismRing`, which provide the minimal necessary machinery
to support this.
"""
from sympy.core.numbers import igcd, ilcm
from sympy.core.symbol import Dummy
from sympy.polys.polytools import Poly
from sympy.polys.densetools import dup_clear_denoms
from sympy.polys.domains.finitefield import FF
from sympy.polys.domains.rationalfield import QQ
from sympy.polys.domains.integerring import ZZ
from sympy.polys.matrices.domainmatrix import DomainMatrix
from sympy.polys.matrices.exceptions import DMBadInputError
from sympy.polys.matrices.normalforms import hermite_normal_form
from sympy.polys.polyerrors import CoercionFailed, UnificationFailed
from sympy.polys.polyutils import IntegerPowerable
from .exceptions import ClosureFailure, MissingUnityError
from .utilities import AlgIntPowers, is_int, is_rat, get_num_denom
def to_col(coeffs):
r"""Transform a list of integer coefficients into a column vector."""
return DomainMatrix([[ZZ(c) for c in coeffs]], (1, len(coeffs)), ZZ).transpose()
class Module:
"""
Generic finitely-generated module.
This is an abstract base class, and should not be instantiated directly.
The two concrete subclasses are :py:class:`~.PowerBasis` and
:py:class:`~.Submodule`.
Every :py:class:`~.Submodule` is derived from another module, referenced
by its ``parent`` attribute. If ``S`` is a submodule, then we refer to
``S.parent``, ``S.parent.parent``, and so on, as the "ancestors" of
``S``. Thus, every :py:class:`~.Module` is either a
:py:class:`~.PowerBasis` or a :py:class:`~.Submodule`, some ancestor of
which is a :py:class:`~.PowerBasis`.
"""
@property
def n(self):
"""The number of generators of this module."""
raise NotImplementedError
def mult_tab(self):
"""
Get the multiplication table for this module (if closed under mult).
Explanation
===========
Computes a dictionary ``M`` of dictionaries of lists, representing the
upper triangular half of the multiplication table.
In other words, if ``0 <= i <= j < self.n``, then ``M[i][j]`` is the
list ``c`` of coefficients such that
``g[i] * g[j] == sum(c[k]*g[k], k in range(self.n))``,
where ``g`` is the list of generators of this module.
If ``j < i`` then ``M[i][j]`` is undefined.
Examples
========
>>> from sympy.polys import Poly, cyclotomic_poly
>>> from sympy.polys.numberfields.modules import PowerBasis
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> print(A.mult_tab()) # doctest: +SKIP
{0: {0: [1, 0, 0, 0], 1: [0, 1, 0, 0], 2: [0, 0, 1, 0], 3: [0, 0, 0, 1]},
1: {1: [0, 0, 1, 0], 2: [0, 0, 0, 1], 3: [-1, -1, -1, -1]},
2: {2: [-1, -1, -1, -1], 3: [1, 0, 0, 0]},
3: {3: [0, 1, 0, 0]}}
Returns
=======
dict of dict of lists
Raises
======
ClosureFailure
If the module is not closed under multiplication.
"""
raise NotImplementedError
@property
def parent(self):
"""
The parent module, if any, for this module.
Explanation
===========
For a :py:class:`~.Submodule` this is its ``parent`` attribute; for a
:py:class:`~.PowerBasis` this is ``None``.
Returns
=======
:py:class:`~.Module`, ``None``
See Also
========
Module
"""
return None
def represent(self, elt):
r"""
Represent a module element as an integer-linear combination over the
generators of this module.
Explanation
===========
In our system, to "represent" always means to write a
:py:class:`~.ModuleElement` as a :ref:`ZZ`-linear combination over the
generators of the present :py:class:`~.Module`. Furthermore, the
incoming :py:class:`~.ModuleElement` must belong to an ancestor of
the present :py:class:`~.Module` (or to the present
:py:class:`~.Module` itself).
The most common application is to represent a
:py:class:`~.ModuleElement` in a :py:class:`~.Submodule`. For example,
this is involved in computing multiplication tables.
On the other hand, representing in a :py:class:`~.PowerBasis` is an
odd case, and one which tends not to arise in practice, except for
example when using a :py:class:`~.ModuleEndomorphism` on a
:py:class:`~.PowerBasis`.
In such a case, (1) the incoming :py:class:`~.ModuleElement` must
belong to the :py:class:`~.PowerBasis` itself (since the latter has no
proper ancestors) and (2) it is "representable" iff it belongs to
$\mathbb{Z}[\theta]$ (although generally a
:py:class:`~.PowerBasisElement` may represent any element of
$\mathbb{Q}(\theta)$, i.e. any algebraic number).
Examples
========
>>> from sympy import Poly, cyclotomic_poly
>>> from sympy.polys.numberfields.modules import PowerBasis, to_col
>>> from sympy.abc import zeta
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> a = A(to_col([2, 4, 6, 8]))
The :py:class:`~.ModuleElement` ``a`` has all even coefficients.
If we represent ``a`` in the submodule ``B = 2*A``, the coefficients in
the column vector will be halved:
>>> B = A.submodule_from_gens([2*A(i) for i in range(4)])
>>> b = B.represent(a)
>>> print(b.transpose()) # doctest: +SKIP
DomainMatrix([[1, 2, 3, 4]], (1, 4), ZZ)
However, the element of ``B`` so defined still represents the same
algebraic number:
>>> print(a.poly(zeta).as_expr())
8*zeta**3 + 6*zeta**2 + 4*zeta + 2
>>> print(B(b).over_power_basis().poly(zeta).as_expr())
8*zeta**3 + 6*zeta**2 + 4*zeta + 2
Parameters
==========
elt : :py:class:`~.ModuleElement`
The module element to be represented. Must belong to some ancestor
module of this module (including this module itself).
Returns
=======
:py:class:`~.DomainMatrix` over :ref:`ZZ`
This will be a column vector, representing the coefficients of a
linear combination of this module's generators, which equals the
given element.
Raises
======
ClosureFailure
If the given element cannot be represented as a :ref:`ZZ`-linear
combination over this module.
See Also
========
.Submodule.represent
.PowerBasis.represent
"""
raise NotImplementedError
def ancestors(self, include_self=False):
"""
Return the list of ancestor modules of this module, from the
foundational :py:class:`~.PowerBasis` downward, optionally including
``self``.
See Also
========
Module
"""
c = self.parent
a = [] if c is None else c.ancestors(include_self=True)
if include_self:
a.append(self)
return a
def power_basis_ancestor(self):
"""
Return the :py:class:`~.PowerBasis` that is an ancestor of this module.
See Also
========
Module
"""
if isinstance(self, PowerBasis):
return self
c = self.parent
if c is not None:
return c.power_basis_ancestor()
return None
def nearest_common_ancestor(self, other):
"""
Locate the nearest common ancestor of this module and another.
Returns
=======
:py:class:`~.Module`, ``None``
See Also
========
Module
"""
sA = self.ancestors(include_self=True)
oA = other.ancestors(include_self=True)
nca = None
for sa, oa in zip(sA, oA):
if sa == oa:
nca = sa
else:
break
return nca
def is_compat_col(self, col):
"""Say whether *col* is a suitable column vector for this module."""
return isinstance(col, DomainMatrix) and col.shape == (self.n, 1) and col.domain.is_ZZ
def __call__(self, spec, denom=1):
r"""
Generate a :py:class:`~.ModuleElement` belonging to this module.
Examples
========
>>> from sympy.polys import Poly, cyclotomic_poly
>>> from sympy.polys.numberfields.modules import PowerBasis, to_col
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> e = A(to_col([1, 2, 3, 4]), denom=3)
>>> print(e) # doctest: +SKIP
[1, 2, 3, 4]/3
>>> f = A(2)
>>> print(f) # doctest: +SKIP
[0, 0, 1, 0]
Parameters
==========
spec : :py:class:`~.DomainMatrix`, int
Specifies the numerators of the coefficients of the
:py:class:`~.ModuleElement`. Can be either a column vector over
:ref:`ZZ`, whose length must equal the number $n$ of generators of
this module, or else an integer ``j``, $0 \leq j < n$, which is a
shorthand for column $j$ of $I_n$, the $n \times n$ identity
matrix.
denom : int, optional (default=1)
Denominator for the coefficients of the
:py:class:`~.ModuleElement`.
Returns
=======
:py:class:`~.ModuleElement`
The coefficients are the entries of the *spec* vector, divided by
*denom*.
"""
if isinstance(spec, int) and 0 <= spec < self.n:
spec = DomainMatrix.eye(self.n, ZZ)[:, spec].to_dense()
if not self.is_compat_col(spec):
raise ValueError('Compatible column vector required.')
return make_mod_elt(self, spec, denom=denom)
def starts_with_unity(self):
"""Say whether the module's first generator equals unity."""
raise NotImplementedError
def basis_elements(self):
"""
Get list of :py:class:`~.ModuleElement` being the generators of this
module.
"""
return [self(j) for j in range(self.n)]
def zero(self):
"""Return a :py:class:`~.ModuleElement` representing zero."""
return self(0) * 0
def one(self):
"""
Return a :py:class:`~.ModuleElement` representing unity,
and belonging to the first ancestor of this module (including
itself) that starts with unity.
"""
return self.element_from_rational(1)
def element_from_rational(self, a):
"""
Return a :py:class:`~.ModuleElement` representing a rational number.
Explanation
===========
The returned :py:class:`~.ModuleElement` will belong to the first
module on this module's ancestor chain (including this module
itself) that starts with unity.
Examples
========
>>> from sympy.polys import Poly, cyclotomic_poly, QQ
>>> from sympy.polys.numberfields.modules import PowerBasis
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> a = A.element_from_rational(QQ(2, 3))
>>> print(a) # doctest: +SKIP
[2, 0, 0, 0]/3
Parameters
==========
a : int, :ref:`ZZ`, :ref:`QQ`
Returns
=======
:py:class:`~.ModuleElement`
"""
raise NotImplementedError
def submodule_from_gens(self, gens, hnf=True, hnf_modulus=None):
"""
Form the submodule generated by a list of :py:class:`~.ModuleElement`
belonging to this module.
Examples
========
>>> from sympy.polys import Poly, cyclotomic_poly
>>> from sympy.polys.numberfields.modules import PowerBasis
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> gens = [A(0), 2*A(1), 3*A(2), 4*A(3)//5]
>>> B = A.submodule_from_gens(gens)
>>> print(B) # doctest: +SKIP
Submodule[[5, 0, 0, 0], [0, 10, 0, 0], [0, 0, 15, 0], [0, 0, 0, 4]]/5
Parameters
==========
gens : list of :py:class:`~.ModuleElement` belonging to this module.
hnf : boolean, optional (default=True)
If True, we will reduce the matrix into Hermite Normal Form before
forming the :py:class:`~.Submodule`.
hnf_modulus : int, None, optional (default=None)
Modulus for use in the HNF reduction algorithm. See
:py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`.
Returns
=======
:py:class:`~.Submodule`
See Also
========
submodule_from_matrix
"""
if not all(g.module == self for g in gens):
raise ValueError('Generators must belong to this module.')
n = len(gens)
if n == 0:
raise ValueError('Need at least one generator.')
m = gens[0].n
d = gens[0].denom if n == 1 else ilcm(*[g.denom for g in gens])
B = DomainMatrix.zeros((m, 0), ZZ).hstack(*[(d // g.denom) * g.col for g in gens])
if hnf:
B = hermite_normal_form(B, D=hnf_modulus)
return self.submodule_from_matrix(B, denom=d)
def submodule_from_matrix(self, B, denom=1):
"""
Form the submodule generated by the elements of this module indicated
by the columns of a matrix, with an optional denominator.
Examples
========
>>> from sympy.polys import Poly, cyclotomic_poly, ZZ
>>> from sympy.polys.matrices import DM
>>> from sympy.polys.numberfields.modules import PowerBasis
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> B = A.submodule_from_matrix(DM([
... [0, 10, 0, 0],
... [0, 0, 7, 0],
... ], ZZ).transpose(), denom=15)
>>> print(B) # doctest: +SKIP
Submodule[[0, 10, 0, 0], [0, 0, 7, 0]]/15
Parameters
==========
B : :py:class:`~.DomainMatrix` over :ref:`ZZ`
Each column gives the numerators of the coefficients of one
generator of the submodule. Thus, the number of rows of *B* must
equal the number of generators of the present module.
denom : int, optional (default=1)
Common denominator for all generators of the submodule.
Returns
=======
:py:class:`~.Submodule`
Raises
======
ValueError
If the given matrix *B* is not over :ref:`ZZ` or its number of rows
does not equal the number of generators of the present module.
See Also
========
submodule_from_gens
"""
m, n = B.shape
if not B.domain.is_ZZ:
raise ValueError('Matrix must be over ZZ.')
if not m == self.n:
raise ValueError('Matrix row count must match base module.')
return Submodule(self, B, denom=denom)
def whole_submodule(self):
"""
Return a submodule equal to this entire module.
Explanation
===========
This is useful when you have a :py:class:`~.PowerBasis` and want to
turn it into a :py:class:`~.Submodule` (in order to use methods
belonging to the latter).
"""
B = DomainMatrix.eye(self.n, ZZ)
return self.submodule_from_matrix(B)
def endomorphism_ring(self):
"""Form the :py:class:`~.EndomorphismRing` for this module."""
return EndomorphismRing(self)
class PowerBasis(Module):
"""The module generated by the powers of an algebraic integer."""
def __init__(self, T):
"""
Parameters
==========
T : :py:class:`~.Poly`
The monic, irreducible, univariate polynomial over :ref:`ZZ`, a
root of which is the generator of the power basis.
"""
self.T = T
self._n = T.degree()
self._mult_tab = None
def __repr__(self):
return f'PowerBasis({self.T.as_expr()})'
def __eq__(self, other):
if isinstance(other, PowerBasis):
return self.T == other.T
return NotImplemented
@property
def n(self):
return self._n
def mult_tab(self):
if self._mult_tab is None:
self.compute_mult_tab()
return self._mult_tab
def compute_mult_tab(self):
theta_pow = AlgIntPowers(self.T)
M = {}
n = self.n
for u in range(n):
M[u] = {}
for v in range(u, n):
M[u][v] = theta_pow[u + v]
self._mult_tab = M
def represent(self, elt):
r"""
Represent a module element as an integer-linear combination over the
generators of this module.
See Also
========
.Module.represent
.Submodule.represent
"""
if elt.module == self and elt.denom == 1:
return elt.column()
else:
raise ClosureFailure('Element not representable in ZZ[theta].')
def starts_with_unity(self):
return True
def element_from_rational(self, a):
return self(0) * a
def element_from_poly(self, f):
"""
Produce an element of this module, representing *f* after reduction mod
our defining minimal polynomial.
Parameters
==========
f : :py:class:`~.Poly` over :ref:`ZZ` in same var as our defining poly.
Returns
=======
:py:class:`~.PowerBasisElement`
"""
n, k = self.n, f.degree()
if k >= n:
f = f % self.T
if f == 0:
return self.zero()
d, c = dup_clear_denoms(f.rep.rep, QQ, convert=True)
c = list(reversed(c))
ell = len(c)
z = [ZZ(0)] * (n - ell)
col = to_col(c + z)
return self(col, denom=d)
class Submodule(Module, IntegerPowerable):
"""A submodule of another module."""
def __init__(self, parent, matrix, denom=1, mult_tab=None):
"""
Parameters
==========
parent : :py:class:`~.Module`
The module from which this one is derived.
matrix : :py:class:`~.DomainMatrix` over :ref:`ZZ`
The matrix whose columns define this submodule's generators as
linear combinations over the parent's generators.
denom : int, optional (default=1)
Denominator for the coefficients given by the matrix.
mult_tab : dict, ``None``, optional
If already known, the multiplication table for this module may be
supplied.
"""
self._parent = parent
self._matrix = matrix
self._denom = denom
self._mult_tab = mult_tab
self._n = matrix.shape[1]
self._QQ_matrix = None
self._starts_with_unity = None
self._is_sq_maxrank_HNF = None
def __repr__(self):
r = 'Submodule' + repr(self.matrix.transpose().to_Matrix().tolist())
if self.denom > 1:
r += f'/{self.denom}'
return r
def reduced(self):
"""
Produce a reduced version of this submodule.
Explanation
===========
In the reduced version, it is guaranteed that 1 is the only positive
integer dividing both the submodule's denominator, and every entry in
the submodule's matrix.
Returns
=======
:py:class:`~.Submodule`
"""
if self.denom == 1:
return self
g = igcd(self.denom, *self.coeffs)
if g == 1:
return self
return type(self)(self.parent, (self.matrix / g).convert_to(ZZ), denom=self.denom // g, mult_tab=self._mult_tab)
def discard_before(self, r):
"""
Produce a new module by discarding all generators before a given
index *r*.
"""
W = self.matrix[:, r:]
s = self.n - r
M = None
mt = self._mult_tab
if mt is not None:
M = {}
for u in range(s):
M[u] = {}
for v in range(u, s):
M[u][v] = mt[r + u][r + v][r:]
return Submodule(self.parent, W, denom=self.denom, mult_tab=M)
@property
def n(self):
return self._n
def mult_tab(self):
if self._mult_tab is None:
self.compute_mult_tab()
return self._mult_tab
def compute_mult_tab(self):
gens = self.basis_element_pullbacks()
M = {}
n = self.n
for u in range(n):
M[u] = {}
for v in range(u, n):
M[u][v] = self.represent(gens[u] * gens[v]).flat()
self._mult_tab = M
@property
def parent(self):
return self._parent
@property
def matrix(self):
return self._matrix
@property
def coeffs(self):
return self.matrix.flat()
@property
def denom(self):
return self._denom
@property
def QQ_matrix(self):
"""
:py:class:`~.DomainMatrix` over :ref:`QQ`, equal to
``self.matrix / self.denom``, and guaranteed to be dense.
Explanation
===========
Depending on how it is formed, a :py:class:`~.DomainMatrix` may have
an internal representation that is sparse or dense. We guarantee a
dense representation here, so that tests for equivalence of submodules
always come out as expected.
Examples
========
>>> from sympy.polys import Poly, cyclotomic_poly, ZZ
>>> from sympy.abc import x
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy.polys.numberfields.modules import PowerBasis
>>> T = Poly(cyclotomic_poly(5, x))
>>> A = PowerBasis(T)
>>> B = A.submodule_from_matrix(3*DomainMatrix.eye(4, ZZ), denom=6)
>>> C = A.submodule_from_matrix(DomainMatrix.eye(4, ZZ), denom=2)
>>> print(B.QQ_matrix == C.QQ_matrix)
True
Returns
=======
:py:class:`~.DomainMatrix` over :ref:`QQ`
"""
if self._QQ_matrix is None:
self._QQ_matrix = (self.matrix / self.denom).to_dense()
return self._QQ_matrix
def starts_with_unity(self):
if self._starts_with_unity is None:
self._starts_with_unity = self(0).equiv(1)
return self._starts_with_unity
def is_sq_maxrank_HNF(self):
if self._is_sq_maxrank_HNF is None:
self._is_sq_maxrank_HNF = is_sq_maxrank_HNF(self._matrix)
return self._is_sq_maxrank_HNF
def is_power_basis_submodule(self):
return isinstance(self.parent, PowerBasis)
def element_from_rational(self, a):
if self.starts_with_unity():
return self(0) * a
else:
return self.parent.element_from_rational(a)
def basis_element_pullbacks(self):
"""
Return list of this submodule's basis elements as elements of the
submodule's parent module.
"""
return [e.to_parent() for e in self.basis_elements()]
def represent(self, elt):
"""
Represent a module element as an integer-linear combination over the
generators of this module.
See Also
========
.Module.represent
.PowerBasis.represent
"""
if elt.module == self:
return elt.column()
elif elt.module == self.parent:
try:
# The given element should be a ZZ-linear combination over our
# basis vectors; however, due to the presence of denominators,
# we need to solve over QQ.
A = self.QQ_matrix
b = elt.QQ_col
x = A._solve(b)[0].transpose()
x = x.convert_to(ZZ)
except DMBadInputError:
raise ClosureFailure('Element outside QQ-span of this basis.')
except CoercionFailed:
raise ClosureFailure('Element in QQ-span but not ZZ-span of this basis.')
return x
elif isinstance(self.parent, Submodule):
coeffs_in_parent = self.parent.represent(elt)
parent_element = self.parent(coeffs_in_parent)
return self.represent(parent_element)
else:
raise ClosureFailure('Element outside ancestor chain of this module.')
def is_compat_submodule(self, other):
return isinstance(other, Submodule) and other.parent == self.parent
def __eq__(self, other):
if self.is_compat_submodule(other):
return other.QQ_matrix == self.QQ_matrix
return NotImplemented
def add(self, other, hnf=True, hnf_modulus=None):
"""
Add this :py:class:`~.Submodule` to another.
Explanation
===========
This represents the module generated by the union of the two modules'
sets of generators.
Parameters
==========
other : :py:class:`~.Submodule`
hnf : boolean, optional (default=True)
If ``True``, reduce the matrix of the combined module to its
Hermite Normal Form.
hnf_modulus : :ref:`ZZ`, None, optional
If a positive integer is provided, use this as modulus in the
HNF reduction. See
:py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`.
Returns
=======
:py:class:`~.Submodule`
"""
d, e = self.denom, other.denom
m = ilcm(d, e)
a, b = m // d, m // e
B = (a * self.matrix).hstack(b * other.matrix)
if hnf:
B = hermite_normal_form(B, D=hnf_modulus)
return self.parent.submodule_from_matrix(B, denom=m)
def __add__(self, other):
if self.is_compat_submodule(other):
return self.add(other)
return NotImplemented
__radd__ = __add__
def mul(self, other, hnf=True, hnf_modulus=None):
"""
Multiply this :py:class:`~.Submodule` by a rational number, a
:py:class:`~.ModuleElement`, or another :py:class:`~.Submodule`.
Explanation
===========
To multiply by a rational number or :py:class:`~.ModuleElement` means
to form the submodule whose generators are the products of this
quantity with all the generators of the present submodule.
To multiply by another :py:class:`~.Submodule` means to form the
submodule whose generators are all the products of one generator from
the one submodule, and one generator from the other.
Parameters
==========
other : int, :ref:`ZZ`, :ref:`QQ`, :py:class:`~.ModuleElement`, :py:class:`~.Submodule`
hnf : boolean, optional (default=True)
If ``True``, reduce the matrix of the product module to its
Hermite Normal Form.
hnf_modulus : :ref:`ZZ`, None, optional
If a positive integer is provided, use this as modulus in the
HNF reduction. See
:py:func:`~sympy.polys.matrices.normalforms.hermite_normal_form`.
Returns
=======
:py:class:`~.Submodule`
"""
if is_rat(other):
a, b = get_num_denom(other)
if a == b == 1:
return self
else:
return Submodule(self.parent,
self.matrix * a, denom=self.denom * b,
mult_tab=None).reduced()
elif isinstance(other, ModuleElement) and other.module == self.parent:
# The submodule is multiplied by an element of the parent module.
# We presume this means we want a new submodule of the parent module.
gens = [other * e for e in self.basis_element_pullbacks()]
return self.parent.submodule_from_gens(gens, hnf=hnf, hnf_modulus=hnf_modulus)
elif self.is_compat_submodule(other):
# This case usually means you're multiplying ideals, and want another
# ideal, i.e. another submodule of the same parent module.
alphas, betas = self.basis_element_pullbacks(), other.basis_element_pullbacks()
gens = [a * b for a in alphas for b in betas]
return self.parent.submodule_from_gens(gens, hnf=hnf, hnf_modulus=hnf_modulus)
return NotImplemented
def __mul__(self, other):
return self.mul(other)
__rmul__ = __mul__
def _first_power(self):
return self
def is_sq_maxrank_HNF(dm):
r"""
Say whether a :py:class:`~.DomainMatrix` is in that special case of Hermite
Normal Form, in which the matrix is also square and of maximal rank.
Explanation
===========
We commonly work with :py:class:`~.Submodule` instances whose matrix is in
this form, and it can be useful to be able to check that this condition is
satisfied.
For example this is the case with the :py:class:`~.Submodule` ``ZK``
returned by :py:func:`~sympy.polys.numberfields.basis.round_two`, which
represents the maximal order in a number field, and with ideals formed
therefrom, such as ``2 * ZK``.
"""
if dm.domain.is_ZZ and dm.is_square and dm.is_upper:
n = dm.shape[0]
for i in range(n):
d = dm[i, i].element
if d <= 0:
return False
for j in range(i + 1, n):
if not (0 <= dm[i, j].element < d):
return False
return True
return False
def make_mod_elt(module, col, denom=1):
r"""
Factory function which builds a :py:class:`~.ModuleElement`, but ensures
that it is a :py:class:`~.PowerBasisElement` if the module is a
:py:class:`~.PowerBasis`.
"""
if isinstance(module, PowerBasis):
return PowerBasisElement(module, col, denom=denom)
else:
return ModuleElement(module, col, denom=denom)
class ModuleElement(IntegerPowerable):
r"""
Represents an element of a :py:class:`~.Module`.
NOTE: Should not be constructed directly. Use the
:py:meth:`~.Module.__call__` method or the :py:func:`make_mod_elt()`
factory function instead.
"""
def __init__(self, module, col, denom=1):
"""
Parameters
==========
module : :py:class:`~.Module`
The module to which this element belongs.
col : :py:class:`~.DomainMatrix` over :ref:`ZZ`
Column vector giving the numerators of the coefficients of this
element.
denom : int, optional (default=1)
Denominator for the coefficients of this element.
"""
self.module = module
self.col = col
self.denom = denom
self._QQ_col = None
def __repr__(self):
r = str([int(c) for c in self.col.flat()])
if self.denom > 1:
r += f'/{self.denom}'
return r
def reduced(self):
"""
Produce a reduced version of this ModuleElement, i.e. one in which the
gcd of the denominator together with all numerator coefficients is 1.
"""
if self.denom == 1:
return self
g = igcd(self.denom, *self.coeffs)
if g == 1:
return self
return type(self)(self.module,
(self.col / g).convert_to(ZZ),
denom=self.denom // g)
def reduced_mod_p(self, p):
"""
Produce a version of this :py:class:`~.ModuleElement` in which all
numerator coefficients have been reduced mod *p*.
"""
return make_mod_elt(self.module,
self.col.convert_to(FF(p)).convert_to(ZZ),
denom=self.denom)
@classmethod
def from_int_list(cls, module, coeffs, denom=1):
"""
Make a :py:class:`~.ModuleElement` from a list of ints (instead of a
column vector).
"""
col = to_col(coeffs)
return cls(module, col, denom=denom)
@property
def n(self):
"""The length of this element's column."""
return self.module.n
def __len__(self):
return self.n
def column(self, domain=None):
"""
Get a copy of this element's column, optionally converting to a domain.
"""
return self.col.convert_to(domain)
@property
def coeffs(self):
return self.col.flat()
@property
def QQ_col(self):
"""
:py:class:`~.DomainMatrix` over :ref:`QQ`, equal to
``self.col / self.denom``, and guaranteed to be dense.
See Also
========
.Submodule.QQ_matrix
"""
if self._QQ_col is None:
self._QQ_col = (self.col / self.denom).to_dense()
return self._QQ_col
def to_parent(self):
"""
Transform into a :py:class:`~.ModuleElement` belonging to the parent of
this element's module.
"""
if not isinstance(self.module, Submodule):
raise ValueError('Not an element of a Submodule.')
return make_mod_elt(
self.module.parent, self.module.matrix * self.col,
denom=self.module.denom * self.denom)
def to_ancestor(self, anc):
"""
Transform into a :py:class:`~.ModuleElement` belonging to a given
ancestor of this element's module.
Parameters
==========
anc : :py:class:`~.Module`
"""
if anc == self.module:
return self
else:
return self.to_parent().to_ancestor(anc)
def over_power_basis(self):
"""
Transform into a :py:class:`~.PowerBasisElement` over our
:py:class:`~.PowerBasis` ancestor.
"""
e = self
while not isinstance(e.module, PowerBasis):
e = e.to_parent()
return e
def is_compat(self, other):
"""
Test whether other is another :py:class:`~.ModuleElement` with same
module.
"""
return isinstance(other, ModuleElement) and other.module == self.module
def unify(self, other):
"""
Try to make a compatible pair of :py:class:`~.ModuleElement`, one
equivalent to this one, and one equivalent to the other.
Explanation
===========
We search for the nearest common ancestor module for the pair of
elements, and represent each one there.
Returns
=======
Pair ``(e1, e2)``
Each ``ei`` is a :py:class:`~.ModuleElement`, they belong to the
same :py:class:`~.Module`, ``e1`` is equivalent to ``self``, and
``e2`` is equivalent to ``other``.
Raises
======
UnificationFailed
If ``self`` and ``other`` have no common ancestor module.
"""
if self.module == other.module:
return self, other
nca = self.module.nearest_common_ancestor(other.module)
if nca is not None:
return self.to_ancestor(nca), other.to_ancestor(nca)
raise UnificationFailed(f"Cannot unify {self} with {other}")
def __eq__(self, other):
if self.is_compat(other):
return self.QQ_col == other.QQ_col
return NotImplemented
def equiv(self, other):
"""
A :py:class:`~.ModuleElement` may test as equivalent to a rational
number or another :py:class:`~.ModuleElement`, if they represent the
same algebraic number.
Explanation
===========
This method is intended to check equivalence only in those cases in
which it is easy to test; namely, when *other* is either a
:py:class:`~.ModuleElement` that can be unified with this one (i.e. one
which shares a common :py:class:`~.PowerBasis` ancestor), or else a
rational number (which is easy because every :py:class:`~.PowerBasis`
represents every rational number).
Parameters
==========
other : int, :ref:`ZZ`, :ref:`QQ`, :py:class:`~.ModuleElement`
Returns
=======
bool
Raises
======
UnificationFailed
If ``self`` and ``other`` do not share a common
:py:class:`~.PowerBasis` ancestor.
"""
if self == other:
return True
elif isinstance(other, ModuleElement):
a, b = self.unify(other)
return a == b
elif is_rat(other):
if isinstance(self, PowerBasisElement):
return self == self.module(0) * other
else:
return self.over_power_basis().equiv(other)
return False
def __add__(self, other):
"""
A :py:class:`~.ModuleElement` can be added to a rational number, or to
another :py:class:`~.ModuleElement`.
Explanation
===========
When the other summand is a rational number, it will be converted into
a :py:class:`~.ModuleElement` (belonging to the first ancestor of this
module that starts with unity).
In all cases, the sum belongs to the nearest common ancestor (NCA) of
the modules of the two summands. If the NCA does not exist, we return
``NotImplemented``.
"""
if self.is_compat(other):
d, e = self.denom, other.denom
m = ilcm(d, e)
u, v = m // d, m // e
col = to_col([u * a + v * b for a, b in zip(self.coeffs, other.coeffs)])
return type(self)(self.module, col, denom=m).reduced()
elif isinstance(other, ModuleElement):
try:
a, b = self.unify(other)
except UnificationFailed:
return NotImplemented
return a + b
elif is_rat(other):
return self + self.module.element_from_rational(other)
return NotImplemented
__radd__ = __add__
def __neg__(self):
return self * -1
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
def __mul__(self, other):
"""
A :py:class:`~.ModuleElement` can be multiplied by a rational number,
or by another :py:class:`~.ModuleElement`.
Explanation
===========
When the multiplier is a rational number, the product is computed by
operating directly on the coefficients of this
:py:class:`~.ModuleElement`.
When the multiplier is another :py:class:`~.ModuleElement`, the product
will belong to the nearest common ancestor (NCA) of the modules of the
two operands, and that NCA must have a multiplication table. If the NCA
does not exist, we return ``NotImplemented``. If the NCA does not have
a mult. table, ``ClosureFailure`` will be raised.
"""
if self.is_compat(other):
M = self.module.mult_tab()
A, B = self.col.flat(), other.col.flat()
n = self.n
C = [0] * n
for u in range(n):
for v in range(u, n):
c = A[u] * B[v]
if v > u:
c += A[v] * B[u]
if c != 0:
R = M[u][v]
for k in range(n):
C[k] += c * R[k]
d = self.denom * other.denom
return self.from_int_list(self.module, C, denom=d)
elif isinstance(other, ModuleElement):
try:
a, b = self.unify(other)
except UnificationFailed:
return NotImplemented
return a * b
elif is_rat(other):
a, b = get_num_denom(other)
if a == b == 1:
return self
else:
return make_mod_elt(self.module,
self.col * a, denom=self.denom * b).reduced()
return NotImplemented
__rmul__ = __mul__
def _zeroth_power(self):
return self.module.one()
def _first_power(self):
return self
def __floordiv__(self, a):
if is_rat(a):
a = QQ(a)
return self * (1/a)
elif isinstance(a, ModuleElement):
return self * (1//a)
return NotImplemented
def __rfloordiv__(self, a):
return a // self.over_power_basis()
def __mod__(self, m):
r"""
Reducing a :py:class:`~.ModuleElement` mod an integer *m* reduces all
numerator coeffs mod $d m$, where $d$ is the denominator of the
:py:class:`~.ModuleElement`.
Explanation
===========
Recall that a :py:class:`~.ModuleElement` $b$ represents a
$\mathbb{Q}$-linear combination over the basis elements
$\{\beta_0, \beta_1, \ldots, \beta_{n-1}\}$ of a module $B$. It uses a
common denominator $d$, so that the representation is in the form
$b=\frac{c_0 \beta_0 + c_1 \beta_1 + \cdots + c_{n-1} \beta_{n-1}}{d}$,
with $d$ and all $c_i$ in $\mathbb{Z}$, and $d > 0$.
If we want to work modulo $m B$, this means we want to reduce the
coefficients of $b$ mod $m$. We can think of reducing an arbitrary
rational number $r/s$ mod $m$ as adding or subtracting an integer
multiple of $m$ so that the result is positive and less than $m$.
But this is equivalent to reducing $r$ mod $m \cdot s$.
Examples
========
>>> from sympy import Poly, cyclotomic_poly
>>> from sympy.polys.numberfields.modules import PowerBasis
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> a = (A(0) + 15*A(1))//2
>>> print(a)
[1, 15, 0, 0]/2
Here, ``a`` represents the number $\frac{1 + 15\zeta}{2}$. If we reduce
mod 7,
>>> print(a % 7)
[1, 1, 0, 0]/2
we get $\frac{1 + \zeta}{2}$. Effectively, we subtracted $7 \zeta$.
But it was achieved by reducing the numerator coefficients mod $14$.
"""
if is_int(m):
M = m * self.denom
col = to_col([c % M for c in self.coeffs])
return type(self)(self.module, col, denom=self.denom)
return NotImplemented
class PowerBasisElement(ModuleElement):
r"""
Subclass for :py:class:`~.ModuleElement` instances whose module is a
:py:class:`~.PowerBasis`.
"""
@property
def T(self):
"""Access the defining polynomial of the :py:class:`~.PowerBasis`."""
return self.module.T
def numerator(self, x=None):
"""Obtain the numerator as a polynomial over :ref:`ZZ`."""
x = x or self.T.gen
return Poly(reversed(self.coeffs), x, domain=ZZ)
def poly(self, x=None):
"""Obtain the number as a polynomial over :ref:`QQ`."""
return self.numerator(x=x) // self.denom
def norm(self, T=None):
"""Compute the norm of this number."""
T = T or self.T
x = T.gen
A = self.numerator(x=x)
return T.resultant(A) // self.denom ** self.n
def inverse(self):
f = self.poly()
f_inv = f.invert(self.T)
return self.module.element_from_poly(f_inv)
def __rfloordiv__(self, a):
return self.inverse() * a
def _negative_power(self, e, modulo=None):
return self.inverse() ** abs(e)
class ModuleHomomorphism:
r"""A homomorphism from one module to another."""
def __init__(self, domain, codomain, mapping):
r"""
Parameters
==========
domain : :py:class:`~.Module`
The domain of the mapping.
codomain : :py:class:`~.Module`
The codomain of the mapping.
mapping : callable
An arbitrary callable is accepted, but should be chosen so as
to represent an actual module homomorphism. In particular, should
accept elements of *domain* and return elements of *codomain*.
Examples
========
>>> from sympy import Poly, cyclotomic_poly
>>> from sympy.polys.numberfields.modules import PowerBasis, ModuleHomomorphism
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> B = A.submodule_from_gens([2*A(j) for j in range(4)])
>>> phi = ModuleHomomorphism(A, B, lambda x: 6*x)
>>> print(phi.matrix()) # doctest: +SKIP
DomainMatrix([[3, 0, 0, 0], [0, 3, 0, 0], [0, 0, 3, 0], [0, 0, 0, 3]], (4, 4), ZZ)
"""
self.domain = domain
self.codomain = codomain
self.mapping = mapping
def matrix(self, modulus=None):
r"""
Compute the matrix of this homomorphism.
Parameters
==========
modulus : int, optional
A positive prime number $p$ if the matrix should be reduced mod
$p$.
Returns
=======
:py:class:`~.DomainMatrix`
The matrix is over :ref:`ZZ`, or else over :ref:`GF(p)` if a
modulus was given.
"""
basis = self.domain.basis_elements()
cols = [self.codomain.represent(self.mapping(elt)) for elt in basis]
if not cols:
return DomainMatrix.zeros((self.codomain.n, 0), ZZ).to_dense()
M = cols[0].hstack(*cols[1:])
if modulus:
M = M.convert_to(FF(modulus))
return M
def kernel(self, modulus=None):
r"""
Compute a Submodule representing the kernel of this homomorphism.
Parameters
==========
modulus : int, optional
A positive prime number $p$ if the kernel should be computed mod
$p$.
Returns
=======
:py:class:`~.Submodule`
This submodule's generators span the kernel of this
homomorphism over :ref:`ZZ`, or else over :ref:`GF(p)` if a
modulus was given.
"""
M = self.matrix(modulus=modulus)
if modulus is None:
M = M.convert_to(QQ)
# Note: Even when working over a finite field, what we want here is
# the pullback into the integers, so in this case the conversion to ZZ
# below is appropriate. When working over ZZ, the kernel should be a
# ZZ-submodule, so, while the conversion to QQ above was required in
# order for the nullspace calculation to work, conversion back to ZZ
# afterward should always work.
# TODO:
# Watch <https://github.com/sympy/sympy/issues/21834>, which calls
# for fraction-free algorithms. If this is implemented, we can skip
# the conversion to `QQ` above.
K = M.nullspace().convert_to(ZZ).transpose()
return self.domain.submodule_from_matrix(K)
class ModuleEndomorphism(ModuleHomomorphism):
r"""A homomorphism from one module to itself."""
def __init__(self, domain, mapping):
r"""
Parameters
==========
domain : :py:class:`~.Module`
The common domain and codomain of the mapping.
mapping : callable
An arbitrary callable is accepted, but should be chosen so as
to represent an actual module endomorphism. In particular, should
accept and return elements of *domain*.
"""
super().__init__(domain, domain, mapping)
class InnerEndomorphism(ModuleEndomorphism):
r"""
An inner endomorphism on a module, i.e. the endomorphism corresponding to
multiplication by a fixed element.
"""
def __init__(self, domain, multiplier):
r"""
Parameters
==========
domain : :py:class:`~.Module`
The domain and codomain of the endomorphism.
multiplier : :py:class:`~.ModuleElement`
The element $a$ defining the mapping as $x \mapsto a x$.
"""
super().__init__(domain, lambda x: multiplier * x)
self.multiplier = multiplier
class EndomorphismRing:
r"""The ring of endomorphisms on a module."""
def __init__(self, domain):
"""
Parameters
==========
domain : :py:class:`~.Module`
The domain and codomain of the endomorphisms.
"""
self.domain = domain
def inner_endomorphism(self, multiplier):
r"""
Form an inner endomorphism belonging to this endomorphism ring.
Parameters
==========
multiplier : :py:class:`~.ModuleElement`
Element $a$ defining the inner endomorphism $x \mapsto a x$.
Returns
=======
:py:class:`~.InnerEndomorphism`
"""
return InnerEndomorphism(self.domain, multiplier)
def represent(self, element):
r"""
Represent an element of this endomorphism ring, as a single column
vector.
Explanation
===========
Let $M$ be a module, and $E$ its ring of endomorphisms. Let $N$ be
another module, and consider a homomorphism $\varphi: N \rightarrow E$.
In the event that $\varphi$ is to be represented by a matrix $A$, each
column of $A$ must represent an element of $E$. This is possible when
the elements of $E$ are themselves representable as matrices, by
stacking the columns of such a matrix into a single column.
This method supports calculating such matrices $A$, by representing
an element of this endomorphism ring first as a matrix, and then
stacking that matrix's columns into a single column.
Examples
========
Note that in these examples we print matrix transposes, to make their
columns easier to inspect.
>>> from sympy import Poly, cyclotomic_poly
>>> from sympy.polys.numberfields.modules import PowerBasis
>>> from sympy.polys.numberfields.modules import ModuleHomomorphism
>>> T = Poly(cyclotomic_poly(5))
>>> M = PowerBasis(T)
>>> E = M.endomorphism_ring()
Let $\zeta$ be a primitive 5th root of unity, a generator of our field,
and consider the inner endomorphism $\tau$ on the ring of integers,
induced by $\zeta$:
>>> zeta = M(1)
>>> tau = E.inner_endomorphism(zeta)
>>> tau.matrix().transpose() # doctest: +SKIP
DomainMatrix(
[[0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [-1, -1, -1, -1]],
(4, 4), ZZ)
The matrix representation of $\tau$ is as expected. The first column
shows that multiplying by $\zeta$ carries $1$ to $\zeta$, the second
column that it carries $\zeta$ to $\zeta^2$, and so forth.
The ``represent`` method of the endomorphism ring ``E`` stacks these
into a single column:
>>> E.represent(tau).transpose() # doctest: +SKIP
DomainMatrix(
[[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1]],
(1, 16), ZZ)
This is useful when we want to consider a homomorphism $\varphi$ having
``E`` as codomain:
>>> phi = ModuleHomomorphism(M, E, lambda x: E.inner_endomorphism(x))
and we want to compute the matrix of such a homomorphism:
>>> phi.matrix().transpose() # doctest: +SKIP
DomainMatrix(
[[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1],
[0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1, 1, 0, 0, 0],
[0, 0, 0, 1, -1, -1, -1, -1, 1, 0, 0, 0, 0, 1, 0, 0]],
(4, 16), ZZ)
Note that the stacked matrix of $\tau$ occurs as the second column in
this example. This is because $\zeta$ is the second basis element of
``M``, and $\varphi(\zeta) = \tau$.
Parameters
==========
element : :py:class:`~.ModuleEndomorphism` belonging to this ring.
Returns
=======
:py:class:`~.DomainMatrix`
Column vector equalling the vertical stacking of all the columns
of the matrix that represents the given *element* as a mapping.
"""
if isinstance(element, ModuleEndomorphism) and element.domain == self.domain:
M = element.matrix()
# Transform the matrix into a single column, which should reproduce
# the original columns, one after another.
m, n = M.shape
if n == 0:
return M
return M[:, 0].vstack(*[M[:, j] for j in range(1, n)])
raise NotImplementedError
def find_min_poly(alpha, domain, x=None, powers=None):
r"""
Find a polynomial of least degree (not necessarily irreducible) satisfied
by an element of a finitely-generated ring with unity.
Examples
========
For the $n$th cyclotomic field, $n$ an odd prime, consider the quadratic
equation whose roots are the two periods of length $(n-1)/2$. Article 356
of Gauss tells us that we should get $x^2 + x - (n-1)/4$ or
$x^2 + x + (n+1)/4$ according to whether $n$ is 1 or 3 mod 4, respectively.
>>> from sympy import Poly, cyclotomic_poly, primitive_root, QQ
>>> from sympy.abc import x
>>> from sympy.polys.numberfields.modules import PowerBasis, find_min_poly
>>> n = 13
>>> g = primitive_root(n)
>>> C = PowerBasis(Poly(cyclotomic_poly(n, x)))
>>> ee = [g**(2*k+1) % n for k in range((n-1)//2)]
>>> eta = sum(C(e) for e in ee)
>>> print(find_min_poly(eta, QQ, x=x).as_expr())
x**2 + x - 3
>>> n = 19
>>> g = primitive_root(n)
>>> C = PowerBasis(Poly(cyclotomic_poly(n, x)))
>>> ee = [g**(2*k+2) % n for k in range((n-1)//2)]
>>> eta = sum(C(e) for e in ee)
>>> print(find_min_poly(eta, QQ, x=x).as_expr())
x**2 + x + 5
Parameters
==========
alpha : :py:class:`~.ModuleElement`
The element whose min poly is to be found, and whose module has
multiplication and starts with unity.
domain : :py:class:`~.Domain`
The desired domain of the polynomial.
x : :py:class:`~.Symbol`, optional
The desired variable for the polynomial.
powers : list, optional
If desired, pass an empty list. The powers of *alpha* (as
:py:class:`~.ModuleElement` instances) from the zeroth up to the degree
of the min poly will be recorded here, as we compute them.
Returns
=======
:py:class:`~.Poly`, ``None``
The minimal polynomial for alpha, or ``None`` if no polynomial could be
found over the desired domain.
Raises
======
MissingUnityError
If the module to which alpha belongs does not start with unity.
ClosureFailure
If the module to which alpha belongs is not closed under
multiplication.
"""
R = alpha.module
if not R.starts_with_unity():
raise MissingUnityError("alpha must belong to finitely generated ring with unity.")
if powers is None:
powers = []
one = R(0)
powers.append(one)
powers_matrix = one.column(domain=domain)
ak = alpha
m = None
for k in range(1, R.n + 1):
powers.append(ak)
ak_col = ak.column(domain=domain)
try:
X = powers_matrix._solve(ak_col)[0]
except DMBadInputError:
# This means alpha^k still isn't in the domain-span of the lower powers.
powers_matrix = powers_matrix.hstack(ak_col)
ak *= alpha
else:
# alpha^k is in the domain-span of the lower powers, so we have found a
# minimal-degree poly for alpha.
coeffs = [1] + [-c for c in reversed(X.to_list_flat())]
x = x or Dummy('x')
if domain.is_FF:
m = Poly(coeffs, x, modulus=domain.mod)
else:
m = Poly(coeffs, x, domain=domain)
break
return m
|
5f7e8bed0e37a27b3db368b96efa7f3551a0bf71715d96b14de3b79862d0124e | """Computing integral bases for number fields. """
from sympy.polys.polytools import Poly
from sympy.polys.domains.integerring import ZZ
from sympy.polys.domains.rationalfield import QQ
from sympy.polys.polyerrors import CoercionFailed
from sympy.utilities.decorator import public
from .modules import ModuleEndomorphism, ModuleHomomorphism, PowerBasis
from .utilities import extract_fundamental_discriminant
def _apply_Dedekind_criterion(T, p):
r"""
Apply the "Dedekind criterion" to test whether the order needs to be
enlarged relative to a given prime *p*.
"""
x = T.gen
T_bar = Poly(T, modulus=p)
lc, fl = T_bar.factor_list()
assert lc == 1
g_bar = Poly(1, x, modulus=p)
for ti_bar, _ in fl:
g_bar *= ti_bar
h_bar = T_bar // g_bar
g = Poly(g_bar, domain=ZZ)
h = Poly(h_bar, domain=ZZ)
f = (g * h - T) // p
f_bar = Poly(f, modulus=p)
Z_bar = f_bar
for b in [g_bar, h_bar]:
Z_bar = Z_bar.gcd(b)
U_bar = T_bar // Z_bar
m = Z_bar.degree()
return U_bar, m
def nilradical_mod_p(H, p, q=None):
r"""
Compute the nilradical mod *p* for a given order *H*, and prime *p*.
Explanation
===========
This is the ideal $I$ in $H/pH$ consisting of all elements some positive
power of which is zero in this quotient ring, i.e. is a multiple of *p*.
Parameters
==========
H : :py:class:`~.Submodule`
The given order.
p : int
The rational prime.
q : int, optional
If known, the smallest power of *p* that is $>=$ the dimension of *H*.
If not provided, we compute it here.
Returns
=======
:py:class:`~.Module` representing the nilradical mod *p* in *H*.
References
==========
.. [1] Cohen, H. *A Course in Computational Algebraic Number Theory*.
(See Lemma 6.1.6.)
"""
n = H.n
if q is None:
q = p
while q < n:
q *= p
phi = ModuleEndomorphism(H, lambda x: x**q)
return phi.kernel(modulus=p)
def _second_enlargement(H, p, q):
r"""
Perform the second enlargement in the Round Two algorithm.
"""
Ip = nilradical_mod_p(H, p, q=q)
B = H.parent.submodule_from_matrix(H.matrix * Ip.matrix, denom=H.denom)
C = B + p*H
E = C.endomorphism_ring()
phi = ModuleHomomorphism(H, E, lambda x: E.inner_endomorphism(x))
gamma = phi.kernel(modulus=p)
G = H.parent.submodule_from_matrix(H.matrix * gamma.matrix, denom=H.denom * p)
H1 = G + H
return H1, Ip
@public
def round_two(T, radicals=None):
r"""
Zassenhaus's "Round 2" algorithm.
Explanation
===========
Carry out Zassenhaus's "Round 2" algorithm on a monic irreducible
polynomial *T* over :ref:`ZZ`. This computes an integral basis and the
discriminant for the field $K = \mathbb{Q}[x]/(T(x))$.
Ordinarily this function need not be called directly, as one can instead
access the :py:meth:`~.AlgebraicField.maximal_order`,
:py:meth:`~.AlgebraicField.integral_basis`, and
:py:meth:`~.AlgebraicField.discriminant` methods of an
:py:class:`~.AlgebraicField`.
Examples
========
Working through an AlgebraicField:
>>> from sympy import Poly, QQ
>>> from sympy.abc import x, theta
>>> T = Poly(x ** 3 + x ** 2 - 2 * x + 8)
>>> K = QQ.algebraic_field((T, theta))
>>> print(K.maximal_order())
Submodule[[2, 0, 0], [0, 2, 0], [0, 1, 1]]/2
>>> print(K.discriminant())
-503
>>> print(K.integral_basis(fmt='sympy'))
[1, theta, theta**2/2 + theta/2]
Calling directly:
>>> from sympy import Poly
>>> from sympy.abc import x
>>> from sympy.polys.numberfields.basis import round_two
>>> T = Poly(x ** 3 + x ** 2 - 2 * x + 8)
>>> print(round_two(T))
(Submodule[[2, 0, 0], [0, 2, 0], [0, 1, 1]]/2, -503)
The nilradicals mod $p$ that are sometimes computed during the Round Two
algorithm may be useful in further calculations. Pass a dictionary under
`radicals` to receive these:
>>> T = Poly(x**3 + 3*x**2 + 5)
>>> rad = {}
>>> ZK, dK = round_two(T, radicals=rad)
>>> print(rad)
{3: Submodule[[-1, 1, 0], [-1, 0, 1]]}
Parameters
==========
T : :py:class:`~.Poly`
The irreducible monic polynomial over :ref:`ZZ` defining the number
field.
radicals : dict, optional
This is a way for any $p$-radicals (if computed) to be returned by
reference. If desired, pass an empty dictionary. If the algorithm
reaches the point where it computes the nilradical mod $p$ of the ring
of integers $Z_K$, then an $\mathbb{F}_p$-basis for this ideal will be
stored in this dictionary under the key ``p``. This can be useful for
other algorithms, such as prime decomposition.
Returns
=======
Pair ``(ZK, dK)``, where:
``ZK`` is a :py:class:`~sympy.polys.numberfields.modules.Submodule`
representing the maximal order.
``dK`` is the discriminant of the field $K = \mathbb{Q}[x]/(T(x))$.
See Also
========
.AlgebraicField.maximal_order
.AlgebraicField.integral_basis
.AlgebraicField.discriminant
References
==========
.. [1] Cohen, H. *A Course in Computational Algebraic Number Theory.*
"""
if T.domain == QQ:
try:
T = Poly(T, domain=ZZ)
except CoercionFailed:
pass # Let the error be raised by the next clause.
if ( not T.is_univariate
or not T.is_irreducible
or not T.is_monic
or not T.domain == ZZ):
raise ValueError('Round 2 requires a monic irreducible univariate polynomial over ZZ.')
n = T.degree()
D = T.discriminant()
D_modulus = ZZ.from_sympy(abs(D))
# D must be 0 or 1 mod 4 (see Cohen Sec 4.4), which ensures we can write
# it in the form D = D_0 * F**2, where D_0 is 1 or a fundamental discriminant.
_, F = extract_fundamental_discriminant(D)
Ztheta = PowerBasis(T)
H = Ztheta.whole_submodule()
nilrad = None
while F:
# Next prime:
p, e = F.popitem()
U_bar, m = _apply_Dedekind_criterion(T, p)
if m == 0:
continue
# For a given prime p, the first enlargement of the order spanned by
# the current basis can be done in a simple way:
U = Ztheta.element_from_poly(Poly(U_bar, domain=ZZ))
# TODO:
# Theory says only first m columns of the U//p*H term below are needed.
# Could be slightly more efficient to use only those. Maybe `Submodule`
# class should support a slice operator?
H = H.add(U // p * H, hnf_modulus=D_modulus)
if e <= m:
continue
# A second, and possibly more, enlargements for p will be needed.
# These enlargements require a more involved procedure.
q = p
while q < n:
q *= p
H1, nilrad = _second_enlargement(H, p, q)
while H1 != H:
H = H1
H1, nilrad = _second_enlargement(H, p, q)
# Note: We do not store all nilradicals mod p, only the very last. This is
# because, unless computed against the entire integral basis, it might not
# be accurate. (In other words, if H was not already equal to ZK when we
# passed it to `_second_enlargement`, then we can't trust the nilradical
# so computed.) Example: if T(x) = x ** 3 + 15 * x ** 2 - 9 * x + 13, then
# F is divisible by 2, 3, and 7, and the nilradical mod 2 as computed above
# will not be accurate for the full, maximal order ZK.
if nilrad is not None and isinstance(radicals, dict):
radicals[p] = nilrad
ZK = H
# Pre-set expensive boolean properties which we already know to be true:
ZK._starts_with_unity = True
ZK._is_sq_maxrank_HNF = True
dK = (D * ZK.matrix.det() ** 2) // ZK.denom ** (2 * n)
return ZK, dK
|
20ddfa3e21ef5af1f960eb56994d041d23e22a11abc8f7b370e6b075099eb0ca | """Special exception classes for numberfields. """
class ClosureFailure(Exception):
r"""
Signals that a :py:class:`ModuleElement` which we tried to represent in a
certain :py:class:`Module` cannot in fact be represented there.
Examples
========
>>> from sympy.polys import Poly, cyclotomic_poly, ZZ
>>> from sympy.polys.matrices import DomainMatrix
>>> from sympy.polys.numberfields.modules import PowerBasis, to_col, ClosureFailure
>>> from sympy.testing.pytest import raises
>>> T = Poly(cyclotomic_poly(5))
>>> A = PowerBasis(T)
>>> B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
Because we are in a cyclotomic field, the power basis ``A`` is an integral
basis, and the submodule ``B`` is just the ideal $(2)$. Therefore ``B`` can
represent an element having all even coefficients over the power basis:
>>> a1 = A(to_col([2, 4, 6, 8]))
>>> print(B.represent(a1))
DomainMatrix([[1], [2], [3], [4]], (4, 1), ZZ)
but ``B`` cannot represent an element with an odd coefficient:
>>> a2 = A(to_col([1, 2, 2, 2]))
>>> print(raises(ClosureFailure, lambda: B.represent(a2)))
<ExceptionInfo ClosureFailure('Element in QQ-span but not ZZ-span of this basis.')>
"""
pass
class StructureError(Exception):
r"""
Represents cases in which an algebraic structure was expected to have a
certain property, or be of a certain type, but was not.
"""
pass
class MissingUnityError(StructureError):
r"""Structure should contain a unity element but does not."""
pass
__all__ = [
'ClosureFailure', 'StructureError', 'MissingUnityError',
]
|
10ffd4685f49b2ec4ae814fd2f27b747e717952797df0ddfc89efb10fe4433e4 | """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.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
else:
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()
if a == I*pi:
if c.is_rational:
q = sympify(c.q)
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):
"""
Transform a given algebraic expression *ex* into a multivariate
polynomial, by introducing fresh variables with defining equations.
Explanation
===========
The critical elements of the algebraic expression *ex* are root
extractions, instances of :py:class:`~.AlgebraicNumber`, and negative
powers.
When we encounter a root extraction or an :py:class:`~.AlgebraicNumber`
we replace this expression with a fresh variable ``a_i``, and record
the defining polynomial for ``a_i``. For example, if ``a_0**(1/3)``
occurs, we will replace it with ``a_1``, and record the new defining
polynomial ``a_1**3 - a_0``.
When we encounter a negative power we transform it into a positive
power by algebraically inverting the base. This means computing the
minimal polynomial in ``x`` for the base, inverting ``x`` modulo this
poly (which generates a new polynomial) and then substituting the
original base expression for ``x`` in this last polynomial.
We return the transformed expression, and we record the defining
equations for new symbols using the ``update_mapping()`` function.
"""
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:
if exp.is_Integer:
return expr.expand()
else:
return update_mapping(expr, 1 / exp, -base)
else:
return symbols[expr]
elif ex.is_AlgebraicNumber:
if ex not in mapping:
return update_mapping(ex, ex.minpoly_of_element())
else:
return symbols[ex]
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_of_element().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
@public
def minpoly(ex, x=None, compose=True, polys=False, domain=None):
"""This is a synonym for :py:func:`~.minimal_polynomial`."""
return minimal_polynomial(ex, x=x, compose=compose, polys=polys, domain=domain)
|
b015e971fd638d557cfe6da6f9d2ed77214c0b5a71709d7ce967d0655a4091ea | r"""
Functions in ``polys.numberfields.subfield`` solve the "Subfield Problem" and
allied problems, for algebraic number fields.
Following Cohen (see [Cohen93]_ Section 4.5), we can define the main problem as
follows:
* **Subfield Problem:**
Given two number fields $\mathbb{Q}(\alpha)$, $\mathbb{Q}(\beta)$
via the minimal polynomials for their generators $\alpha$ and $\beta$, decide
whether one field is isomorphic to a subfield of the other.
From a solution to this problem flow solutions to the following problems as
well:
* **Primitive Element Problem:**
Given several algebraic numbers
$\alpha_1, \ldots, \alpha_m$, compute a single algebraic number $\theta$
such that $\mathbb{Q}(\alpha_1, \ldots, \alpha_m) = \mathbb{Q}(\theta)$.
* **Field Isomorphism Problem:**
Decide whether two number fields
$\mathbb{Q}(\alpha)$, $\mathbb{Q}(\beta)$ are isomorphic.
* **Field Membership Problem:**
Given two algebraic numbers $\alpha$,
$\beta$, decide whether $\alpha \in \mathbb{Q}(\beta)$, and if so write
$\alpha = f(\beta)$ for some $f(x) \in \mathbb{Q}[x]$.
"""
from sympy.core.add import Add
from sympy.core.numbers import AlgebraicNumber
from sympy.core.singleton import S
from sympy.core.symbol import Dummy
from sympy.core.sympify import sympify
from sympy.ntheory import sieve
from sympy.polys.densetools import dup_eval
from sympy.polys.domains import QQ
from sympy.polys.numberfields.minpoly import _choose_factor, minimal_polynomial
from sympy.polys.polyerrors import IsomorphismFailed
from sympy.polys.polytools import Poly, PurePoly, 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):
r"""
Find an embedding of one number field into another.
Explanation
===========
This function looks for an isomorphism from $\mathbb{Q}(a)$ onto some
subfield of $\mathbb{Q}(b)$. Thus, it solves the Subfield Problem.
Examples
========
>>> from sympy import sqrt, field_isomorphism, I
>>> print(field_isomorphism(3, sqrt(2))) # doctest: +SKIP
[3]
>>> print(field_isomorphism( I*sqrt(3), I*sqrt(3)/2)) # doctest: +SKIP
[2, 0]
Parameters
==========
a : :py:class:`~.Expr`
Any expression representing an algebraic number.
b : :py:class:`~.Expr`
Any expression representing an algebraic number.
fast : boolean, optional (default=True)
If ``True``, we first attempt a potentially faster way of computing the
isomorphism, falling back on a slower method if this fails. If
``False``, we go directly to the slower method, which is guaranteed to
return a result.
Returns
=======
List of rational numbers, or None
If $\mathbb{Q}(a)$ is not isomorphic to some subfield of
$\mathbb{Q}(b)$, then return ``None``. Otherwise, return a list of
rational numbers representing an element of $\mathbb{Q}(b)$ to which
$a$ may be mapped, in order to define a monomorphism, i.e. an
isomorphism from $\mathbb{Q}(a)$ to some subfield of $\mathbb{Q}(b)$.
The elements of the list are the coefficients of falling powers of $b$.
"""
a, b = sympify(a), sympify(b)
if not a.is_AlgebraicNumber:
a = AlgebraicNumber(a)
if not b.is_AlgebraicNumber:
b = AlgebraicNumber(b)
a = a.to_primitive_element()
b = b.to_primitive_element()
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)
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):
r"""
Find a single generator for a number field given by several generators.
Explanation
===========
The basic problem is this: Given several algebraic numbers
$\alpha_1, \alpha_2, \ldots, \alpha_n$, find a single algebraic number
$\theta$ such that
$\mathbb{Q}(\alpha_1, \alpha_2, \ldots, \alpha_n) = \mathbb{Q}(\theta)$.
This function actually guarantees that $\theta$ will be a linear
combination of the $\alpha_i$, with non-negative integer coefficients.
Furthermore, if desired, this function will tell you how to express each
$\alpha_i$ as a $\mathbb{Q}$-linear combination of the powers of $\theta$.
Examples
========
>>> from sympy import primitive_element, sqrt, S, minpoly, simplify
>>> from sympy.abc import x
>>> f, lincomb, reps = primitive_element([sqrt(2), sqrt(3)], x, ex=True)
Then ``lincomb`` tells us the primitive element as a linear combination of
the given generators ``sqrt(2)`` and ``sqrt(3)``.
>>> print(lincomb)
[1, 1]
This means the primtiive element is $\sqrt{2} + \sqrt{3}$.
Meanwhile ``f`` is the minimal polynomial for this primitive element.
>>> print(f)
x**4 - 10*x**2 + 1
>>> print(minpoly(sqrt(2) + sqrt(3), x))
x**4 - 10*x**2 + 1
Finally, ``reps`` (which was returned only because we set keyword arg
``ex=True``) tells us how to recover each of the generators $\sqrt{2}$ and
$\sqrt{3}$ as $\mathbb{Q}$-linear combinations of the powers of the
primitive element $\sqrt{2} + \sqrt{3}$.
>>> print([S(r) for r in reps[0]])
[1/2, 0, -9/2, 0]
>>> theta = sqrt(2) + sqrt(3)
>>> print(simplify(theta**3/2 - 9*theta/2))
sqrt(2)
>>> print([S(r) for r in reps[1]])
[-1/2, 0, 11/2, 0]
>>> print(simplify(-theta**3/2 + 11*theta/2))
sqrt(3)
Parameters
==========
extension : list of :py:class:`~.Expr`
Each expression must represent an algebraic number $\alpha_i$.
x : :py:class:`~.Symbol`, optional (default=None)
The desired symbol to appear in the computed minimal polynomial for the
primitive element $\theta$. If ``None``, we use a dummy symbol.
ex : boolean, optional (default=False)
If and only if ``True``, compute the representation of each $\alpha_i$
as a $\mathbb{Q}$-linear combination over the powers of $\theta$.
polys : boolean, optional (default=False)
If ``True``, return the minimal polynomial as a :py:class:`~.Poly`.
Otherwise return it as an :py:class:`~.Expr`.
Returns
=======
Pair (f, coeffs) or triple (f, coeffs, reps), where:
``f`` is the minimal polynomial for the primitive element.
``coeffs`` gives the primitive element as a linear combination of the
given generators.
``reps`` is present if and only if argument ``ex=True`` was passed,
and is a list of lists of rational numbers. Each list gives the
coefficients of falling powers of the primitive element, to recover
one of the original, given generators.
"""
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
@public
def to_number_field(extension, theta=None, *, gen=None):
r"""
Express one algebraic number in the field generated by another.
Explanation
===========
Given two algebraic numbers $\eta, \theta$, this function either expresses
$\eta$ as an element of $\mathbb{Q}(\theta)$, or else raises an exception
if $\eta \not\in \mathbb{Q}(\theta)$.
This function is essentially just a convenience, utilizing
:py:func:`~.field_isomorphism` (our solution of the Subfield Problem) to
solve this, the Field Membership Problem.
As an additional convenience, this function allows you to pass a list of
algebraic numbers $\alpha_1, \alpha_2, \ldots, \alpha_n$ instead of $\eta$.
It then computes $\eta$ for you, as a solution of the Primitive Element
Problem, using :py:func:`~.primitive_element` on the list of $\alpha_i$.
Examples
========
>>> from sympy import sqrt, to_number_field
>>> eta = sqrt(2)
>>> theta = sqrt(2) + sqrt(3)
>>> a = to_number_field(eta, theta)
>>> print(type(a))
<class 'sympy.core.numbers.AlgebraicNumber'>
>>> a.root
sqrt(2) + sqrt(3)
>>> print(a)
sqrt(2)
>>> a.coeffs()
[1/2, 0, -9/2, 0]
We get an :py:class:`~.AlgebraicNumber`, whose ``.root`` is $\theta$, whose
value is $\eta$, and whose ``.coeffs()`` show how to write $\eta$ as a
$\mathbb{Q}$-linear combination in falling powers of $\theta$.
Parameters
==========
extension : :py:class:`~.Expr` or list of :py:class:`~.Expr`
Either the algebraic number that is to be expressed in the other field,
or else a list of algebraic numbers, a primitive element for which is
to be expressed in the other field.
theta : :py:class:`~.Expr`, None, optional (default=None)
If an :py:class:`~.Expr` representing an algebraic number, behavior is
as described under **Explanation**. If ``None``, then this function
reduces to a shorthand for calling :py:func:`~.primitive_element` on
``extension`` and turning the computed primitive element into an
:py:class:`~.AlgebraicNumber`.
gen : :py:class:`~.Symbol`, None, optional (default=None)
If provided, this will be used as the generator symbol for the returned
:py:class:`~.AlgebraicNumber`.
Returns
=======
AlgebraicNumber
Belonging to $\mathbb{Q}(\theta)$ and equaling $\eta$.
Raises
======
IsomorphismFailed
If $\eta \not\in \mathbb{Q}(\theta)$.
See Also
========
field_isomorphism
primitive_element
"""
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))
|
3407fa997f63577d0dd2a41bd70292c105a1ba777528fae9da9f5acc7593d560 | '''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):
r"""
This supports the functions that compute Hermite Normal Form.
Explanation
===========
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 : :py:class:`~.DomainMatrix` over domain :ref:`ZZ`.
Returns
=======
:py:class:`~.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
:py:class:`~.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 : :py:class:`~.DomainMatrix` over :ref:`ZZ`
$m \times n$ matrix, having rank $m$.
D : :ref:`ZZ`
Positive integer, known to be a multiple of the determinant of the
HNF of *A*.
Returns
=======
:py:class:`~.DomainMatrix`
The HNF of matrix *A*.
Raises
======
DMDomainError
If the domain of the matrix is not :ref:`ZZ`, or
if *D* is given but is not in :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.')
if not ZZ.of_type(D) or D < 1:
raise DMDomainError('Modulus D must be positive element of 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 = 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 :py:class:`~.DomainMatrix` *A* over
:ref:`ZZ`.
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]])
Parameters
==========
A : $m \times n$ ``DomainMatrix`` over :ref:`ZZ`.
D : :ref:`ZZ`, 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, optional (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
=======
:py:class:`~.DomainMatrix`
The HNF of matrix *A*.
Raises
======
DMDomainError
If the domain of the matrix is not :ref:`ZZ`, or
if *D* is given but is not in :ref:`ZZ`.
DMShapeError
If the mod *D* algorithm is used but the matrix has more rows than
columns.
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)
|
2ff8d680564f0255d289205adc60c3d481cd2a0159c95803030538ad52311bf1 | """
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.
Alternatively, ``None`` may be passed, in which case this method
just returns a copy of this DomainMatrix.
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)
"""
if K is None:
return self.copy()
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) or ZZ.of_type(lamda):
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
|
e064e8be355f7416dd1ecba423ff696bb433e9a26b253374f8b07b82b0d63a6d | #
# sympy.polys.matrices.linsolve module
#
# This module defines the _linsolve function which is the internal workhorse
# used by linsolve. This computes the solution of a system of linear equations
# using the SDM sparse matrix implementation in sympy.polys.matrices.sdm. This
# is a replacement for solve_lin_sys in sympy.polys.solvers which is
# inefficient for large sparse systems due to the use of a PolyRing with many
# generators:
#
# https://github.com/sympy/sympy/issues/20857
#
# The implementation of _linsolve here handles:
#
# - Extracting the coefficients from the Expr/Eq input equations.
# - Constructing a domain and converting the coefficients to
# that domain.
# - Using the SDM.rref, SDM.nullspace etc methods to generate the full
# solution working with arithmetic only in the domain of the coefficients.
#
# The routines here are particularly designed to be efficient for large sparse
# systems of linear equations although as well as dense systems. It is
# possible that for some small dense systems solve_lin_sys which uses the
# dense matrix implementation DDM will be more efficient. With smaller systems
# though the bulk of the time is spent just preprocessing the inputs and the
# relative time spent in rref is too small to be noticeable.
#
from collections import defaultdict
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.polys.constructor import construct_domain
from sympy.polys.solvers import PolyNonlinearError
from .sdm import (
SDM,
sdm_irref,
sdm_particular_from_rref,
sdm_nullspace_from_rref
)
def _linsolve(eqs, syms):
"""Solve a linear system of equations.
Examples
========
Solve a linear system with a unique solution:
>>> from sympy import symbols, Eq
>>> from sympy.polys.matrices.linsolve import _linsolve
>>> x, y = symbols('x, y')
>>> eqs = [Eq(x + y, 1), Eq(x - y, 2)]
>>> _linsolve(eqs, [x, y])
{x: 3/2, y: -1/2}
In the case of underdetermined systems the solution will be expressed in
terms of the unknown symbols that are unconstrained:
>>> _linsolve([Eq(x + y, 0)], [x, y])
{x: -y, y: y}
"""
# Number of unknowns (columns in the non-augmented matrix)
nsyms = len(syms)
# Convert to sparse augmented matrix (len(eqs) x (nsyms+1))
eqsdict, rhs = _linear_eq_to_dict(eqs, syms)
Aaug = sympy_dict_to_dm(eqsdict, rhs, syms)
K = Aaug.domain
# sdm_irref has issues with float matrices. This uses the ddm_rref()
# function. When sdm_rref() can handle float matrices reasonably this
# should be removed...
if K.is_RealField or K.is_ComplexField:
Aaug = Aaug.to_ddm().rref()[0].to_sdm()
# Compute reduced-row echelon form (RREF)
Arref, pivots, nzcols = sdm_irref(Aaug)
# No solution:
if pivots and pivots[-1] == nsyms:
return None
# Particular solution for non-homogeneous system:
P = sdm_particular_from_rref(Arref, nsyms+1, pivots)
# Nullspace - general solution to homogeneous system
# Note: using nsyms not nsyms+1 to ignore last column
V, nonpivots = sdm_nullspace_from_rref(Arref, K.one, nsyms, pivots, nzcols)
# Collect together terms from particular and nullspace:
sol = defaultdict(list)
for i, v in P.items():
sol[syms[i]].append(K.to_sympy(v))
for npi, Vi in zip(nonpivots, V):
sym = syms[npi]
for i, v in Vi.items():
sol[syms[i]].append(sym * K.to_sympy(v))
# Use a single call to Add for each term:
sol = {s: Add(*terms) for s, terms in sol.items()}
# Fill in the zeros:
zero = S.Zero
for s in set(syms) - set(sol):
sol[s] = zero
# All done!
return sol
def sympy_dict_to_dm(eqs_coeffs, eqs_rhs, syms):
"""Convert a system of dict equations to a sparse augmented matrix"""
elems = set(eqs_rhs).union(*(e.values() for e in eqs_coeffs))
K, elems_K = construct_domain(elems, field=True, extension=True)
elem_map = dict(zip(elems, elems_K))
neqs = len(eqs_coeffs)
nsyms = len(syms)
sym2index = dict(zip(syms, range(nsyms)))
eqsdict = []
for eq, rhs in zip(eqs_coeffs, eqs_rhs):
eqdict = {sym2index[s]: elem_map[c] for s, c in eq.items()}
if rhs:
eqdict[nsyms] = - elem_map[rhs]
if eqdict:
eqsdict.append(eqdict)
sdm_aug = SDM(enumerate(eqsdict), (neqs, nsyms+1), K)
return sdm_aug
def _expand_eqs_deprecated(eqs):
"""Use expand to cancel nonlinear terms.
This approach matches previous behaviour of linsolve but should be
deprecated.
"""
def expand_eq(eq):
if eq.is_Equality:
eq = eq.lhs - eq.rhs
return eq.expand()
return [expand_eq(eq) for eq in eqs]
def _linear_eq_to_dict(eqs, syms):
"""Convert a system Expr/Eq equations into dict form"""
try:
return _linear_eq_to_dict_inner(eqs, syms)
except PolyNonlinearError:
# XXX: This should be deprecated:
eqs = _expand_eqs_deprecated(eqs)
return _linear_eq_to_dict_inner(eqs, syms)
def _linear_eq_to_dict_inner(eqs, syms):
"""Convert a system Expr/Eq equations into dict form"""
syms = set(syms)
eqsdict, eqs_rhs = [], []
for eq in eqs:
rhs, eqdict = _lin_eq2dict(eq, syms)
eqsdict.append(eqdict)
eqs_rhs.append(rhs)
return eqsdict, eqs_rhs
def _lin_eq2dict(a, symset):
"""Efficiently convert a linear equation to a dict of coefficients"""
if a in symset:
return S.Zero, {a: S.One}
elif a.is_Add:
terms_list = defaultdict(list)
coeff_list = []
for ai in a.args:
ci, ti = _lin_eq2dict(ai, symset)
coeff_list.append(ci)
for mij, cij in ti.items():
terms_list[mij].append(cij)
coeff = Add(*coeff_list)
terms = {sym: Add(*coeffs) for sym, coeffs in terms_list.items()}
return coeff, terms
elif a.is_Mul:
terms = terms_coeff = None
coeff_list = []
for ai in a.args:
ci, ti = _lin_eq2dict(ai, symset)
if not ti:
coeff_list.append(ci)
elif terms is None:
terms = ti
terms_coeff = ci
else:
raise PolyNonlinearError
coeff = Mul(*coeff_list)
if terms is None:
return coeff, {}
else:
terms = {sym: coeff * c for sym, c in terms.items()}
return coeff * terms_coeff, terms
elif a.is_Equality:
return _lin_eq2dict(a.lhs - a.rhs, symset)
elif not a.has_free(*symset):
return a, {}
else:
raise PolyNonlinearError
|
47dfcb80a5c33fecb3bb8af7f45fb0245dd7a0bf9779c6de69f68f9e0d510e36 | """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*I)]
assert ZZ_I.gcd(a, b) == b
assert ZZ_I.gcd(a, c) == b
assert ZZ_I.lcm(a, b) == a
assert 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
|
6a217adeea09c67887ff2521882bf1842008c235f728eac4b5a76eb5f9574ed8 | from sympy.abc import theta, x
from sympy.core import S
from sympy.core.numbers import AlgebraicNumber
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.polys import Poly, cyclotomic_poly
from sympy.polys.domains import QQ
from sympy.polys.matrices import DomainMatrix, DM
from sympy.polys.numberfields.basis import round_two
from sympy.testing.pytest import raises
def test_round_two():
# Poly must be monic, irreducible, and over ZZ:
raises(ValueError, lambda: round_two(Poly(3 * x ** 2 + 1)))
raises(ValueError, lambda: round_two(Poly(x ** 2 - 1)))
raises(ValueError, lambda: round_two(Poly(x ** 2 + QQ(1, 2))))
# Test on many fields:
cases = (
# A couple of cyclotomic fields:
(cyclotomic_poly(5), DomainMatrix.eye(4, QQ), 125),
(cyclotomic_poly(7), DomainMatrix.eye(6, QQ), -16807),
# A couple of quadratic fields (one 1 mod 4, one 3 mod 4):
(x ** 2 - 5, DM([[1, (1, 2)], [0, (1, 2)]], QQ), 5),
(x ** 2 - 7, DM([[1, 0], [0, 1]], QQ), 28),
# Dedekind's example of a field with 2 as essential disc divisor:
(x ** 3 + x ** 2 - 2 * x + 8, DM([[1, 0, 0], [0, 1, 0], [0, (1, 2), (1, 2)]], QQ).transpose(), -503),
# A bunch of cubics with various forms for F -- all of these require
# second or third enlargements. (Five of them require a third, while the rest require just a second.)
# F = 2^2
(x**3 + 3 * x**2 - 4 * x + 4, DM([((1, 2), (1, 4), (1, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), -83),
# F = 2^2 * 3
(x**3 + 3 * x**2 + 3 * x - 3, DM([((1, 2), 0, (1, 2)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -108),
# F = 2^3
(x**3 + 5 * x**2 - x + 3, DM([((1, 4), 0, (3, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), -31),
# F = 2^2 * 5
(x**3 + 5 * x**2 - 5 * x - 5, DM([((1, 2), 0, (1, 2)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), 1300),
# F = 3^2
(x**3 + 3 * x**2 + 5, DM([((1, 3), (1, 3), (1, 3)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -135),
# F = 3^3
(x**3 + 6 * x**2 + 3 * x - 1, DM([((1, 3), (1, 3), (1, 3)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), 81),
# F = 2^2 * 3^2
(x**3 + 6 * x**2 + 4, DM([((1, 3), (2, 3), (1, 3)), (0, 1, 0), (0, 0, (1, 2))], QQ).transpose(), -108),
# F = 2^3 * 7
(x**3 + 7 * x**2 + 7 * x - 7, DM([((1, 4), 0, (3, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), 49),
# F = 2^2 * 13
(x**3 + 7 * x**2 - x + 5, DM([((1, 2), 0, (1, 2)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -2028),
# F = 2^4
(x**3 + 7 * x**2 - 5 * x + 5, DM([((1, 4), 0, (3, 4)), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), -140),
# F = 5^2
(x**3 + 4 * x**2 - 3 * x + 7, DM([((1, 5), (4, 5), (4, 5)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -175),
# F = 7^2
(x**3 + 8 * x**2 + 5 * x - 1, DM([((1, 7), (6, 7), (2, 7)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), 49),
# F = 2 * 5 * 7
(x**3 + 8 * x**2 - 2 * x + 6, DM([(1, 0, 0), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -14700),
# F = 2^2 * 3 * 5
(x**3 + 6 * x**2 - 3 * x + 8, DM([(1, 0, 0), (0, (1, 4), (1, 4)), (0, 0, 1)], QQ).transpose(), -675),
# F = 2 * 3^2 * 7
(x**3 + 9 * x**2 + 6 * x - 8, DM([(1, 0, 0), (0, (1, 2), (1, 2)), (0, 0, 1)], QQ).transpose(), 3969),
# F = 2^2 * 3^2 * 7
(x**3 + 15 * x**2 - 9 * x + 13, DM([((1, 6), (1, 3), (1, 6)), (0, 1, 0), (0, 0, 1)], QQ).transpose(), -5292),
)
for f, B_exp, d_exp in cases:
K = QQ.algebraic_field((f, theta))
B = K.maximal_order().QQ_matrix
d = K.discriminant()
assert d == d_exp
# The computed basis need not equal the expected one, but their quotient
# must be unimodular:
assert (B.inv()*B_exp).det()**2 == 1
def test_AlgebraicField_integral_basis():
alpha = AlgebraicNumber(sqrt(5), alias='alpha')
k = QQ.algebraic_field(alpha)
B0 = k.integral_basis()
B1 = k.integral_basis(fmt='sympy')
B2 = k.integral_basis(fmt='alg')
assert B0 == [k([1]), k([S.Half, S.Half])]
assert B1 == [1, S.Half + alpha/2]
assert B2 == [alpha.field_element([1]),
alpha.field_element([S.Half, S.Half])]
|
4f761f168b9764d7011b601f2c443bed4ab2fbf4d3b9f19352ccac9b350736e0 | from sympy.abc import x
from sympy.core.numbers import (I, Rational)
from sympy.core.singleton import S
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.polys import Poly, cyclotomic_poly
from sympy.polys.domains import FF, QQ
from sympy.polys.matrices import DomainMatrix, DM
from sympy.polys.matrices.exceptions import DMRankError
from sympy.polys.numberfields.utilities import (
AlgIntPowers, coeff_search, extract_fundamental_discriminant,
isolate, supplement_a_subspace,
)
from sympy.printing.lambdarepr import IntervalPrinter
from sympy.testing.pytest import raises
def test_AlgIntPowers_01():
T = Poly(cyclotomic_poly(5))
zeta_pow = AlgIntPowers(T)
raises(ValueError, lambda: zeta_pow[-1])
for e in range(10):
a = e % 5
if a < 4:
c = zeta_pow[e]
assert c[a] == 1 and all(c[i] == 0 for i in range(4) if i != a)
else:
assert zeta_pow[e] == [-1] * 4
def test_AlgIntPowers_02():
T = Poly(x**3 + 2*x**2 + 3*x + 4)
m = 7
theta_pow = AlgIntPowers(T, m)
for e in range(10):
computed = theta_pow[e]
coeffs = (Poly(x)**e % T + Poly(x**3)).rep.rep[1:]
expected = [c % m for c in reversed(coeffs)]
assert computed == expected
def test_coeff_search():
C = []
search = coeff_search(2, 1)
for i, c in enumerate(search):
C.append(c)
if i == 12:
break
assert C == [[1, 1], [1, 0], [1, -1], [0, 1], [2, 2], [2, 1], [2, 0], [2, -1], [2, -2], [1, 2], [1, -2], [0, 2], [3, 3]]
def test_extract_fundamental_discriminant():
# To extract, integer must be 0 or 1 mod 4.
raises(ValueError, lambda: extract_fundamental_discriminant(2))
raises(ValueError, lambda: extract_fundamental_discriminant(3))
# Try many cases, of different forms:
cases = (
(0, {}, {0: 1}),
(1, {}, {}),
(8, {2: 3}, {}),
(-8, {2: 3, -1: 1}, {}),
(12, {2: 2, 3: 1}, {}),
(36, {}, {2: 1, 3: 1}),
(45, {5: 1}, {3: 1}),
(48, {2: 2, 3: 1}, {2: 1}),
(1125, {5: 1}, {3: 1, 5: 1}),
)
for a, D_expected, F_expected in cases:
D, F = extract_fundamental_discriminant(a)
assert D == D_expected
assert F == F_expected
def test_supplement_a_subspace_1():
M = DM([[1, 7, 0], [2, 3, 4]], QQ).transpose()
# First supplement over QQ:
B = supplement_a_subspace(M)
assert B[:, :2] == M
assert B[:, 2] == DomainMatrix.eye(3, QQ).to_dense()[:, 0]
# Now supplement over FF(7):
M = M.convert_to(FF(7))
B = supplement_a_subspace(M)
assert B[:, :2] == M
# When we work mod 7, first col of M goes to [1, 0, 0],
# so the supplementary vector cannot equal this, as it did
# when we worked over QQ. Instead, we get the second std basis vector:
assert B[:, 2] == DomainMatrix.eye(3, FF(7)).to_dense()[:, 1]
def test_supplement_a_subspace_2():
M = DM([[1, 0, 0], [2, 0, 0]], QQ).transpose()
with raises(DMRankError):
supplement_a_subspace(M)
def test_IntervalPrinter():
ip = IntervalPrinter()
assert ip.doprint(x**Rational(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))
|
334bd92019e33c11d5e2f1549cf0482daaa247f7204ae539d24141fafee5d600 | """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.polys.numberfields.subfield import to_number_field
from sympy.polys.polyclasses import DMP
from sympy.polys.domains import QQ
from sympy.polys.rootoftools import CRootOf
from sympy.abc import x, y
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))
a = AlgebraicNumber(sqrt(2), [1, 2], "alpha")
b = AlgebraicNumber(a)
c = AlgebraicNumber(a, alias="gamma")
assert a == b
assert c.alias.name == "gamma"
a = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1)/2, 0, S(-9)/2, 0])
b = AlgebraicNumber(a, [1, 0, 0])
assert b.root == a.root
assert a.to_root() == sqrt(2)
assert b.to_root() == 2
a = AlgebraicNumber(2)
assert a.is_primitive_element is True
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_AlgebraicNumber_to_root():
assert AlgebraicNumber(sqrt(2)).to_root() == sqrt(2)
zeta5_squared = AlgebraicNumber(CRootOf(x**5 - 1, 4), coeffs=[1, 0, 0])
assert zeta5_squared.to_root() == CRootOf(x**4 + x**3 + x**2 + x + 1, 1)
zeta3_squared = AlgebraicNumber(CRootOf(x**3 - 1, 2), coeffs=[1, 0, 0])
assert zeta3_squared.to_root() == -S(1)/2 - sqrt(3)*I/2
assert zeta3_squared.to_root(radicals=False) == CRootOf(x**2 + x + 1, 0)
|
78232577633f6ba451b8ff9721454290abc25aa71b80a7f677eb2a1c4b479aca | """Tests for the subfield problem and allied problems. """
from sympy.core.numbers import (AlgebraicNumber, I, Rational)
from sympy.core.singleton import S
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.polys.numberfields.subfield import (
is_isomorphism_possible,
field_isomorphism_pslq,
field_isomorphism,
primitive_element,
to_number_field,
)
from sympy.polys.polyerrors import IsomorphismFailed
from sympy.polys.polytools import Poly
from sympy.testing.pytest import raises
from sympy.abc import x
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
a = AlgebraicNumber(sqrt(2))
b = AlgebraicNumber(2 ** (S(1) / 3))
assert is_isomorphism_possible(a, b) is False
assert field_isomorphism(a, b) is None
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_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_issue_22561():
a = to_number_field(sqrt(2), sqrt(2) + sqrt(3))
b = to_number_field(sqrt(2), sqrt(2) + sqrt(5))
assert field_isomorphism(a, b) == [1, 0]
|
f5fba98aeaccd7309531e4d51c3113af43c8d3c6508638a629ede78d5a128f06 | """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.power import Pow
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,
_choose_factor,
_minpoly_op_algebraic_element,
_separate_sq,
_minpoly_groebner,
)
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
assert minimal_polynomial(sin(pi/21), x) == 4096*x**12 - 11264*x**10 + \
11264*x**8 - 4992*x**6 + 960*x**4 - 64*x**2 + 1
assert minimal_polynomial(cos(pi/9), x) == 8*x**3 - 6*x - 1
ex = 2**Rational(1, 3)*exp(2*I*pi/3)
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(1.618*I*pi), 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_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
def test_issue_22559():
alpha = AlgebraicNumber(sqrt(2))
assert minimal_polynomial(alpha**3, x) == x**2 - 8
def test_issue_22561():
a = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1) / 2, 0, S(-9) / 2, 0], gen=x)
assert a.as_expr() == sqrt(2)
assert minimal_polynomial(a, x) == x**2 - 2
assert minimal_polynomial(a**3, x) == x**2 - 8
def test_separate_sq_not_impl():
raises(NotImplementedError, lambda: _separate_sq(x**(S(1)/3) + x))
def test_minpoly_op_algebraic_element_not_impl():
raises(NotImplementedError,
lambda: _minpoly_op_algebraic_element(Pow, sqrt(2), sqrt(3), x, QQ))
def test_minpoly_groebner():
assert _minpoly_groebner(S(2)/3, x, Poly) == 3*x - 2
assert _minpoly_groebner(
(sqrt(2) + 3)*(sqrt(2) + 1), x, Poly) == x**2 - 10*x - 7
assert _minpoly_groebner((sqrt(2) + 3)**(S(1)/3)*(sqrt(2) + 1)**(S(1)/3),
x, Poly) == x**6 - 10*x**3 - 7
assert _minpoly_groebner((sqrt(2) + 3)**(-S(1)/3)*(sqrt(2) + 1)**(S(1)/3),
x, Poly) == 7*x**6 - 2*x**3 - 1
raises(NotAlgebraic, lambda: _minpoly_groebner(pi**2, x, Poly))
|
fe646817e43e8ec5785cb3836da536f8023bba5d37375cf70325a088c7992f82 | from sympy import QQ, ZZ, S
from sympy.abc import x, theta
from sympy.core.mul import prod
from sympy.ntheory import factorint
from sympy.ntheory.residue_ntheory import n_order
from sympy.polys import Poly, cyclotomic_poly
from sympy.polys.matrices import DomainMatrix
from sympy.polys.numberfields.basis import round_two
from sympy.polys.numberfields.exceptions import StructureError
from sympy.polys.numberfields.modules import PowerBasis
from sympy.polys.numberfields.primes import (
prime_decomp, _two_elt_rep,
_check_formal_conditions_for_maximal_order,
)
from sympy.polys.polyerrors import GeneratorsNeeded
from sympy.testing.pytest import raises
def test_check_formal_conditions_for_maximal_order():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
D = A.submodule_from_matrix(DomainMatrix.eye(4, ZZ)[:, :-1])
# Is a direct submodule of a power basis, but lacks 1 as first generator:
raises(StructureError, lambda: _check_formal_conditions_for_maximal_order(B))
# Is not a direct submodule of a power basis:
raises(StructureError, lambda: _check_formal_conditions_for_maximal_order(C))
# Is direct submod of pow basis, and starts with 1, but not sq/max rank/HNF:
raises(StructureError, lambda: _check_formal_conditions_for_maximal_order(D))
def test_two_elt_rep():
ell = 7
T = Poly(cyclotomic_poly(ell))
ZK, dK = round_two(T)
for p in [29, 13, 11, 5]:
P = prime_decomp(p, T)
for Pi in P:
# We have Pi in two-element representation, and, because we are
# looking at a cyclotomic field, this was computed by the "easy"
# method that just factors T mod p. We will now convert this to
# a set of Z-generators, then convert that back into a two-element
# rep. The latter need not be identical to the two-elt rep we
# already have, but it must have the same HNF.
H = p*ZK + Pi.alpha*ZK
gens = H.basis_element_pullbacks()
# Note: we could supply f = Pi.f, but prefer to test behavior without it.
b = _two_elt_rep(gens, ZK, p)
if b != Pi.alpha:
H2 = p*ZK + b*ZK
assert H2 == H
def test_valuation_at_prime_ideal():
p = 7
T = Poly(cyclotomic_poly(p))
ZK, dK = round_two(T)
P = prime_decomp(p, T, dK=dK, ZK=ZK)
assert len(P) == 1
P0 = P[0]
v = P0.valuation(p*ZK)
assert v == P0.e
# Test easy 0 case:
assert P0.valuation(5*ZK) == 0
def test_decomp_1():
# All prime decompositions in cyclotomic fields are in the "easy case,"
# since the index is unity.
# Here we check the ramified prime.
T = Poly(cyclotomic_poly(7))
raises(ValueError, lambda: prime_decomp(7))
P = prime_decomp(7, T)
assert len(P) == 1
P0 = P[0]
assert P0.e == 6
assert P0.f == 1
# Test powers:
assert P0**0 == P0.ZK
assert P0**1 == P0
assert P0**6 == 7 * P0.ZK
def test_decomp_2():
# More easy cyclotomic cases, but here we check unramified primes.
ell = 7
T = Poly(cyclotomic_poly(ell))
for p in [29, 13, 11, 5]:
f_exp = n_order(p, ell)
g_exp = (ell - 1) // f_exp
P = prime_decomp(p, T)
assert len(P) == g_exp
for Pi in P:
assert Pi.e == 1
assert Pi.f == f_exp
def test_decomp_3():
T = Poly(x ** 2 - 35)
rad = {}
ZK, dK = round_two(T, radicals=rad)
# 35 is 3 mod 4, so field disc is 4*5*7, and theory says each of the
# rational primes 2, 5, 7 should be the square of a prime ideal.
for p in [2, 5, 7]:
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p))
assert len(P) == 1
assert P[0].e == 2
assert P[0]**2 == p*ZK
def test_decomp_4():
T = Poly(x ** 2 - 21)
rad = {}
ZK, dK = round_two(T, radicals=rad)
# 21 is 1 mod 4, so field disc is 3*7, and theory says the
# rational primes 3, 7 should be the square of a prime ideal.
for p in [3, 7]:
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p))
assert len(P) == 1
assert P[0].e == 2
assert P[0]**2 == p*ZK
def test_decomp_5():
# Here is our first test of the "hard case" of prime decomposition.
# We work in a quadratic extension Q(sqrt(d)) where d is 1 mod 4, and
# we consider the factorization of the rational prime 2, which divides
# the index.
# Theory says the form of p's factorization depends on the residue of
# d mod 8, so we consider both cases, d = 1 mod 8 and d = 5 mod 8.
for d in [-7, -3]:
T = Poly(x ** 2 - d)
rad = {}
ZK, dK = round_two(T, radicals=rad)
p = 2
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p))
if d % 8 == 1:
assert len(P) == 2
assert all(P[i].e == 1 and P[i].f == 1 for i in range(2))
assert prod(Pi**Pi.e for Pi in P) == p * ZK
else:
assert d % 8 == 5
assert len(P) == 1
assert P[0].e == 1
assert P[0].f == 2
assert P[0].as_submodule() == p * ZK
def test_decomp_6():
# Another case where 2 divides the index. This is Dedekind's example of
# an essential discriminant divisor. (See Cohen, Excercise 6.10.)
T = Poly(x ** 3 + x ** 2 - 2 * x + 8)
rad = {}
ZK, dK = round_two(T, radicals=rad)
p = 2
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p))
assert len(P) == 3
assert all(Pi.e == Pi.f == 1 for Pi in P)
assert prod(Pi**Pi.e for Pi in P) == p*ZK
def test_decomp_7():
# Try working through an AlgebraicField
T = Poly(x ** 3 + x ** 2 - 2 * x + 8)
K = QQ.algebraic_field((T, theta))
p = 2
P = K.primes_above(p)
ZK = K.maximal_order()
assert len(P) == 3
assert all(Pi.e == Pi.f == 1 for Pi in P)
assert prod(Pi**Pi.e for Pi in P) == p*ZK
def test_decomp_8():
# This time we consider various cubics, and try factoring all primes
# dividing the index.
cases = (
x ** 3 + 3 * x ** 2 - 4 * x + 4,
x ** 3 + 3 * x ** 2 + 3 * x - 3,
x ** 3 + 5 * x ** 2 - x + 3,
x ** 3 + 5 * x ** 2 - 5 * x - 5,
x ** 3 + 3 * x ** 2 + 5,
x ** 3 + 6 * x ** 2 + 3 * x - 1,
x ** 3 + 6 * x ** 2 + 4,
x ** 3 + 7 * x ** 2 + 7 * x - 7,
x ** 3 + 7 * x ** 2 - x + 5,
x ** 3 + 7 * x ** 2 - 5 * x + 5,
x ** 3 + 4 * x ** 2 - 3 * x + 7,
x ** 3 + 8 * x ** 2 + 5 * x - 1,
x ** 3 + 8 * x ** 2 - 2 * x + 6,
x ** 3 + 6 * x ** 2 - 3 * x + 8,
x ** 3 + 9 * x ** 2 + 6 * x - 8,
x ** 3 + 15 * x ** 2 - 9 * x + 13,
)
'''
def display(T, p, radical, P, I, J):
"""Useful for inspection, when running test manually."""
print('=' * 20)
print(T, p, radical)
for Pi in P:
print(f' ({Pi.pretty()})')
print("I: ", I)
print("J: ", J)
print(f'Equal: {I == J}')
'''
for g in cases:
T = Poly(g)
rad = {}
ZK, dK = round_two(T, radicals=rad)
dT = T.discriminant()
f_squared = dT // dK
F = factorint(f_squared)
for p in F:
radical = rad.get(p)
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=radical)
I = prod(Pi**Pi.e for Pi in P)
J = p * ZK
#display(T, p, radical, P, I, J)
assert I == J
def test_PrimeIdeal_eq():
# `==` should fail on objects of different types, so even a completely
# inert PrimeIdeal should test unequal to the rational prime it divides.
T = Poly(cyclotomic_poly(7))
P0 = prime_decomp(5, T)[0]
assert P0.f == 6
assert P0.as_submodule() == 5 * P0.ZK
assert P0 != 5
def test_PrimeIdeal_add():
T = Poly(cyclotomic_poly(7))
P0 = prime_decomp(7, T)[0]
# Adding ideals computes their GCD, so adding the ramified prime dividing
# 7 to 7 itself should reproduce this prime (as a submodule).
assert P0 + 7 * P0.ZK == P0.as_submodule()
def test_pretty_printing():
d = -7
T = Poly(x ** 2 - d)
rad = {}
ZK, dK = round_two(T, radicals=rad)
p = 2
P = prime_decomp(p, T, dK=dK, ZK=ZK, radical=rad.get(p))
assert repr(P[0]) == '[ (2, (3*x + 1)/2) e=1, f=1 ]'
assert P[0].pretty(field_gen=theta) == '[ (2, (3*theta + 1)/2) e=1, f=1 ]'
assert P[0].pretty(field_gen=theta, just_gens=True) == '(2, (3*theta + 1)/2)'
def test_PrimeIdeal_reduce_poly():
T = Poly(cyclotomic_poly(7, x))
k = QQ.algebraic_field((T, x))
P = k.primes_above(11)
frp = P[0]
B = k.integral_basis(fmt='sympy')
assert [frp.reduce_poly(b, x) for b in B] == [
1, x, x ** 2, -5 * x ** 2 - 4 * x + 1, -x ** 2 - x - 5,
4 * x ** 2 - x - 1]
Q = k.primes_above(19)
frq = Q[0]
assert frq.alpha.equiv(0)
assert frq.reduce_poly(20*x**2 + 10) == x**2 - 9
raises(GeneratorsNeeded, lambda: frp.reduce_poly(S(1)))
raises(NotImplementedError, lambda: frp.reduce_poly(1))
|
f9a2c8d9f29915c998ff9052de166dfefd6e3f4704a835c6da08d9ee5bbc1892 | from sympy.abc import x, zeta
from sympy.polys import Poly, cyclotomic_poly
from sympy.polys.domains import FF, QQ, ZZ
from sympy.polys.matrices import DomainMatrix, DM
from sympy.polys.numberfields.exceptions import (
ClosureFailure, MissingUnityError
)
from sympy.polys.numberfields.modules import (
Module, ModuleElement, ModuleEndomorphism, PowerBasis, PowerBasisElement,
find_min_poly, is_sq_maxrank_HNF, make_mod_elt, to_col,
)
from sympy.polys.numberfields.utilities import is_int
from sympy.polys.polyerrors import UnificationFailed
from sympy.testing.pytest import raises
def test_to_col():
c = [1, 2, 3, 4]
m = to_col(c)
assert m.domain.is_ZZ
assert m.shape == (4, 1)
assert m.flat() == c
def test_Module_NotImplemented():
M = Module()
raises(NotImplementedError, lambda: M.n)
raises(NotImplementedError, lambda: M.mult_tab())
raises(NotImplementedError, lambda: M.represent(None))
raises(NotImplementedError, lambda: M.starts_with_unity())
raises(NotImplementedError, lambda: M.element_from_rational(QQ(2, 3)))
def test_Module_ancestors():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
D = B.submodule_from_matrix(5 * DomainMatrix.eye(4, ZZ))
assert C.ancestors(include_self=True) == [A, B, C]
assert D.ancestors(include_self=True) == [A, B, D]
assert C.power_basis_ancestor() == A
assert C.nearest_common_ancestor(D) == B
M = Module()
assert M.power_basis_ancestor() is None
def test_Module_compat_col():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
col = to_col([1, 2, 3, 4])
row = col.transpose()
assert A.is_compat_col(col) is True
assert A.is_compat_col(row) is False
assert A.is_compat_col(1) is False
assert A.is_compat_col(DomainMatrix.eye(3, ZZ)[:, 0]) is False
assert A.is_compat_col(DomainMatrix.eye(4, QQ)[:, 0]) is False
assert A.is_compat_col(DomainMatrix.eye(4, ZZ)[:, 0]) is True
def test_Module_call():
T = Poly(cyclotomic_poly(5, x))
B = PowerBasis(T)
assert B(0).col.flat() == [1, 0, 0, 0]
assert B(1).col.flat() == [0, 1, 0, 0]
col = DomainMatrix.eye(4, ZZ)[:, 2]
assert B(col).col == col
raises(ValueError, lambda: B(-1))
def test_Module_starts_with_unity():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
assert A.starts_with_unity() is True
assert B.starts_with_unity() is False
def test_Module_basis_elements():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
basis = B.basis_elements()
bp = B.basis_element_pullbacks()
for i, (e, p) in enumerate(zip(basis, bp)):
c = [0] * 4
assert e.module == B
assert p.module == A
c[i] = 1
assert e == B(to_col(c))
c[i] = 2
assert p == A(to_col(c))
def test_Module_zero():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
assert A.zero().col.flat() == [0, 0, 0, 0]
assert A.zero().module == A
assert B.zero().col.flat() == [0, 0, 0, 0]
assert B.zero().module == B
def test_Module_one():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
assert A.one().col.flat() == [1, 0, 0, 0]
assert A.one().module == A
assert B.one().col.flat() == [1, 0, 0, 0]
assert B.one().module == A
def test_Module_element_from_rational():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
rA = A.element_from_rational(QQ(22, 7))
rB = B.element_from_rational(QQ(22, 7))
assert rA.coeffs == [22, 0, 0, 0]
assert rA.denom == 7
assert rA.module == A
assert rB.coeffs == [22, 0, 0, 0]
assert rB.denom == 7
assert rB.module == A
def test_Module_submodule_from_gens():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
gens = [2*A(0), 2*A(1), 6*A(0), 6*A(1)]
B = A.submodule_from_gens(gens)
# Because the 3rd and 4th generators do not add anything new, we expect
# the cols of the matrix of B to just reproduce the first two gens:
M = gens[0].column().hstack(gens[1].column())
assert B.matrix == M
# At least one generator must be provided:
raises(ValueError, lambda: A.submodule_from_gens([]))
# All generators must belong to A:
raises(ValueError, lambda: A.submodule_from_gens([3*A(0), B(0)]))
def test_Module_submodule_from_matrix():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
e = B(to_col([1, 2, 3, 4]))
f = e.to_parent()
assert f.col.flat() == [2, 4, 6, 8]
# Matrix must be over ZZ:
raises(ValueError, lambda: A.submodule_from_matrix(DomainMatrix.eye(4, QQ)))
# Number of rows of matrix must equal number of generators of module A:
raises(ValueError, lambda: A.submodule_from_matrix(2 * DomainMatrix.eye(5, ZZ)))
def test_Module_whole_submodule():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.whole_submodule()
e = B(to_col([1, 2, 3, 4]))
f = e.to_parent()
assert f.col.flat() == [1, 2, 3, 4]
e0, e1, e2, e3 = B(0), B(1), B(2), B(3)
assert e2 * e3 == e0
assert e3 ** 2 == e1
def test_PowerBasis_repr():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
assert repr(A) == 'PowerBasis(x**4 + x**3 + x**2 + x + 1)'
def test_PowerBasis_eq():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = PowerBasis(T)
assert A == B
def test_PowerBasis_mult_tab():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
M = A.mult_tab()
exp = {0: {0: [1, 0, 0, 0], 1: [0, 1, 0, 0], 2: [0, 0, 1, 0], 3: [0, 0, 0, 1]},
1: {1: [0, 0, 1, 0], 2: [0, 0, 0, 1], 3: [-1, -1, -1, -1]},
2: {2: [-1, -1, -1, -1], 3: [1, 0, 0, 0]},
3: {3: [0, 1, 0, 0]}}
# We get the table we expect:
assert M == exp
# And all entries are of expected type:
assert all(is_int(c) for u in M for v in M[u] for c in M[u][v])
def test_PowerBasis_represent():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
col = to_col([1, 2, 3, 4])
a = A(col)
assert A.represent(a) == col
b = A(col, denom=2)
raises(ClosureFailure, lambda: A.represent(b))
def test_PowerBasis_element_from_poly():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
f = Poly(1 + 2*x)
g = Poly(x**4)
h = Poly(0, x)
assert A.element_from_poly(f).coeffs == [1, 2, 0, 0]
assert A.element_from_poly(g).coeffs == [-1, -1, -1, -1]
assert A.element_from_poly(h).coeffs == [0, 0, 0, 0]
def test_Submodule_repr():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ), denom=3)
assert repr(B) == 'Submodule[[2, 0, 0, 0], [0, 2, 0, 0], [0, 0, 2, 0], [0, 0, 0, 2]]/3'
def test_Submodule_reduced():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
C = A.submodule_from_matrix(6 * DomainMatrix.eye(4, ZZ), denom=3)
D = C.reduced()
assert D.denom == 1 and D == C == B
def test_Submodule_discard_before():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
B.compute_mult_tab()
C = B.discard_before(2)
assert C.parent == B.parent
assert B.is_sq_maxrank_HNF() and not C.is_sq_maxrank_HNF()
assert C.matrix == B.matrix[:, 2:]
assert C.mult_tab() == {0: {0: [-2, -2], 1: [0, 0]}, 1: {1: [0, 0]}}
def test_Submodule_QQ_matrix():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
C = A.submodule_from_matrix(6 * DomainMatrix.eye(4, ZZ), denom=3)
assert C.QQ_matrix == B.QQ_matrix
def test_Submodule_represent():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
a0 = A(to_col([6, 12, 18, 24]))
a1 = A(to_col([2, 4, 6, 8]))
a2 = A(to_col([1, 3, 5, 7]))
b1 = B.represent(a1)
assert b1.flat() == [1, 2, 3, 4]
c0 = C.represent(a0)
assert c0.flat() == [1, 2, 3, 4]
Y = A.submodule_from_matrix(DomainMatrix([
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
], (3, 4), ZZ).transpose())
U = Poly(cyclotomic_poly(7, x))
Z = PowerBasis(U)
z0 = Z(to_col([1, 2, 3, 4, 5, 6]))
raises(ClosureFailure, lambda: Y.represent(A(3)))
raises(ClosureFailure, lambda: B.represent(a2))
raises(ClosureFailure, lambda: B.represent(z0))
def test_Submodule_is_compat_submodule():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
D = C.submodule_from_matrix(5 * DomainMatrix.eye(4, ZZ))
assert B.is_compat_submodule(C) is True
assert B.is_compat_submodule(A) is False
assert B.is_compat_submodule(D) is False
def test_Submodule_eq():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
C = A.submodule_from_matrix(6 * DomainMatrix.eye(4, ZZ), denom=3)
assert C == B
def test_Submodule_add():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(DomainMatrix([
[4, 0, 0, 0],
[0, 4, 0, 0],
], (2, 4), ZZ).transpose(), denom=6)
C = A.submodule_from_matrix(DomainMatrix([
[0, 10, 0, 0],
[0, 0, 7, 0],
], (2, 4), ZZ).transpose(), denom=15)
D = A.submodule_from_matrix(DomainMatrix([
[20, 0, 0, 0],
[ 0, 20, 0, 0],
[ 0, 0, 14, 0],
], (3, 4), ZZ).transpose(), denom=30)
assert B + C == D
U = Poly(cyclotomic_poly(7, x))
Z = PowerBasis(U)
Y = Z.submodule_from_gens([Z(0), Z(1)])
raises(TypeError, lambda: B + Y)
def test_Submodule_mul():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
C = A.submodule_from_matrix(DomainMatrix([
[0, 10, 0, 0],
[0, 0, 7, 0],
], (2, 4), ZZ).transpose(), denom=15)
C1 = A.submodule_from_matrix(DomainMatrix([
[0, 20, 0, 0],
[0, 0, 14, 0],
], (2, 4), ZZ).transpose(), denom=3)
C2 = A.submodule_from_matrix(DomainMatrix([
[0, 0, 10, 0],
[0, 0, 0, 7],
], (2, 4), ZZ).transpose(), denom=15)
C3_unred = A.submodule_from_matrix(DomainMatrix([
[0, 0, 100, 0],
[0, 0, 0, 70],
[0, 0, 0, 70],
[-49, -49, -49, -49]
], (4, 4), ZZ).transpose(), denom=225)
C3 = A.submodule_from_matrix(DomainMatrix([
[4900, 4900, 0, 0],
[4410, 4410, 10, 0],
[2107, 2107, 7, 7]
], (3, 4), ZZ).transpose(), denom=225)
assert C * 1 == C
assert C ** 1 == C
assert C * 10 == C1
assert C * A(1) == C2
assert C.mul(C, hnf=False) == C3_unred
assert C * C == C3
assert C ** 2 == C3
def test_is_HNF():
M = DM([
[3, 2, 1],
[0, 2, 1],
[0, 0, 1]
], ZZ)
M1 = DM([
[3, 2, 1],
[0, -2, 1],
[0, 0, 1]
], ZZ)
M2 = DM([
[3, 2, 3],
[0, 2, 1],
[0, 0, 1]
], ZZ)
assert is_sq_maxrank_HNF(M) is True
assert is_sq_maxrank_HNF(M1) is False
assert is_sq_maxrank_HNF(M2) is False
def test_make_mod_elt():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
col = to_col([1, 2, 3, 4])
eA = make_mod_elt(A, col)
eB = make_mod_elt(B, col)
assert isinstance(eA, PowerBasisElement)
assert not isinstance(eB, PowerBasisElement)
def test_ModuleElement_repr():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
e = A(to_col([1, 2, 3, 4]), denom=2)
assert repr(e) == '[1, 2, 3, 4]/2'
def test_ModuleElement_reduced():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
e = A(to_col([2, 4, 6, 8]), denom=2)
f = e.reduced()
assert f.denom == 1 and f == e
def test_ModuleElement_reduced_mod_p():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
e = A(to_col([20, 40, 60, 80]))
f = e.reduced_mod_p(7)
assert f.coeffs == [-1, -2, -3, 3]
def test_ModuleElement_from_int_list():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
c = [1, 2, 3, 4]
assert ModuleElement.from_int_list(A, c).coeffs == c
def test_ModuleElement_len():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
e = A(0)
assert len(e) == 4
def test_ModuleElement_column():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
e = A(0)
col1 = e.column()
assert col1 == e.col and col1 is not e.col
col2 = e.column(domain=FF(5))
assert col2.domain.is_FF
def test_ModuleElement_QQ_col():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
e = A(to_col([1, 2, 3, 4]), denom=1)
f = A(to_col([3, 6, 9, 12]), denom=3)
assert e.QQ_col == f.QQ_col
def test_ModuleElement_to_ancestors():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
D = C.submodule_from_matrix(5 * DomainMatrix.eye(4, ZZ))
eD = D(0)
eC = eD.to_parent()
eB = eD.to_ancestor(B)
eA = eD.over_power_basis()
assert eC.module is C and eC.coeffs == [5, 0, 0, 0]
assert eB.module is B and eB.coeffs == [15, 0, 0, 0]
assert eA.module is A and eA.coeffs == [30, 0, 0, 0]
a = A(0)
raises(ValueError, lambda: a.to_parent())
def test_ModuleElement_compatibility():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
C = B.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
D = B.submodule_from_matrix(5 * DomainMatrix.eye(4, ZZ))
assert C(0).is_compat(C(1)) is True
assert C(0).is_compat(D(0)) is False
u, v = C(0).unify(D(0))
assert u.module is B and v.module is B
assert C(C.represent(u)) == C(0) and D(D.represent(v)) == D(0)
u, v = C(0).unify(C(1))
assert u == C(0) and v == C(1)
U = Poly(cyclotomic_poly(7, x))
Z = PowerBasis(U)
raises(UnificationFailed, lambda: C(0).unify(Z(1)))
def test_ModuleElement_eq():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
e = A(to_col([1, 2, 3, 4]), denom=1)
f = A(to_col([3, 6, 9, 12]), denom=3)
assert e == f
U = Poly(cyclotomic_poly(7, x))
Z = PowerBasis(U)
assert e != Z(0)
assert e != 3.14
def test_ModuleElement_equiv():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
e = A(to_col([1, 2, 3, 4]), denom=1)
f = A(to_col([3, 6, 9, 12]), denom=3)
assert e.equiv(f)
C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
g = C(to_col([1, 2, 3, 4]), denom=1)
h = A(to_col([3, 6, 9, 12]), denom=1)
assert g.equiv(h)
assert C(to_col([5, 0, 0, 0]), denom=7).equiv(QQ(15, 7))
U = Poly(cyclotomic_poly(7, x))
Z = PowerBasis(U)
raises(UnificationFailed, lambda: e.equiv(Z(0)))
assert e.equiv(3.14) is False
def test_ModuleElement_add():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
e = A(to_col([1, 2, 3, 4]), denom=6)
f = A(to_col([5, 6, 7, 8]), denom=10)
g = C(to_col([1, 1, 1, 1]), denom=2)
assert e + f == A(to_col([10, 14, 18, 22]), denom=15)
assert e - f == A(to_col([-5, -4, -3, -2]), denom=15)
assert e + g == A(to_col([10, 11, 12, 13]), denom=6)
assert e + QQ(7, 10) == A(to_col([26, 10, 15, 20]), denom=30)
assert g + QQ(7, 10) == A(to_col([22, 15, 15, 15]), denom=10)
U = Poly(cyclotomic_poly(7, x))
Z = PowerBasis(U)
raises(TypeError, lambda: e + Z(0))
raises(TypeError, lambda: e + 3.14)
def test_ModuleElement_mul():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
e = A(to_col([0, 2, 0, 0]), denom=3)
f = A(to_col([0, 0, 0, 7]), denom=5)
g = C(to_col([0, 0, 0, 1]), denom=2)
h = A(to_col([0, 0, 3, 1]), denom=7)
assert e * f == A(to_col([-14, -14, -14, -14]), denom=15)
assert e * g == A(to_col([-1, -1, -1, -1]))
assert e * h == A(to_col([-2, -2, -2, 4]), denom=21)
assert e * QQ(6, 5) == A(to_col([0, 4, 0, 0]), denom=5)
assert (g * QQ(10, 21)).equiv(A(to_col([0, 0, 0, 5]), denom=7))
assert e // QQ(6, 5) == A(to_col([0, 5, 0, 0]), denom=9)
U = Poly(cyclotomic_poly(7, x))
Z = PowerBasis(U)
raises(TypeError, lambda: e * Z(0))
raises(TypeError, lambda: e * 3.14)
raises(TypeError, lambda: e // 3.14)
raises(ZeroDivisionError, lambda: e // 0)
def test_ModuleElement_div():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
e = A(to_col([0, 2, 0, 0]), denom=3)
f = A(to_col([0, 0, 0, 7]), denom=5)
g = C(to_col([1, 1, 1, 1]))
assert e // f == 10*A(3)//21
assert e // g == -2*A(2)//9
assert 3 // g == -A(1)
def test_ModuleElement_pow():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
C = A.submodule_from_matrix(3 * DomainMatrix.eye(4, ZZ))
e = A(to_col([0, 2, 0, 0]), denom=3)
g = C(to_col([0, 0, 0, 1]), denom=2)
assert e ** 3 == A(to_col([0, 0, 0, 8]), denom=27)
assert g ** 2 == C(to_col([0, 3, 0, 0]), denom=4)
assert e ** 0 == A(to_col([1, 0, 0, 0]))
assert g ** 0 == A(to_col([1, 0, 0, 0]))
assert e ** 1 == e
assert g ** 1 == g
def test_ModuleElement_mod():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
e = A(to_col([1, 15, 8, 0]), denom=2)
assert e % 7 == A(to_col([1, 1, 8, 0]), denom=2)
raises(TypeError, lambda: e % QQ(1, 2))
def test_PowerBasisElement_polys():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
e = A(to_col([1, 15, 8, 0]), denom=2)
assert e.numerator(x=zeta) == Poly(8 * zeta ** 2 + 15 * zeta + 1, domain=ZZ)
assert e.poly(x=zeta) == Poly(4 * zeta ** 2 + QQ(15, 2) * zeta + QQ(1, 2), domain=QQ)
def test_PowerBasisElement_norm():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
lam = A(to_col([1, -1, 0, 0]))
assert lam.norm() == 5
def test_PowerBasisElement_inverse():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
e = A(to_col([1, 1, 1, 1]))
assert 2 // e == -2*A(1)
assert e ** -3 == -A(3)
def test_ModuleHomomorphism_matrix():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
phi = ModuleEndomorphism(A, lambda a: a ** 2)
M = phi.matrix()
assert M == DomainMatrix([
[1, 0, -1, 0],
[0, 0, -1, 1],
[0, 1, -1, 0],
[0, 0, -1, 0]
], (4, 4), ZZ)
def test_ModuleHomomorphism_kernel():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
phi = ModuleEndomorphism(A, lambda a: a ** 5)
N = phi.kernel()
assert N.n == 3
def test_EndomorphismRing_represent():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
R = A.endomorphism_ring()
phi = R.inner_endomorphism(A(1))
col = R.represent(phi)
assert col.transpose() == DomainMatrix([
[0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, -1, -1, -1, -1]
], (1, 16), ZZ)
B = A.submodule_from_matrix(DomainMatrix.zeros((4, 0), ZZ))
S = B.endomorphism_ring()
psi = S.inner_endomorphism(A(1))
col = S.represent(psi)
assert col == DomainMatrix([], (0, 0), ZZ)
raises(NotImplementedError, lambda: R.represent(3.14))
def test_find_min_poly():
T = Poly(cyclotomic_poly(5, x))
A = PowerBasis(T)
powers = []
m = find_min_poly(A(1), QQ, x=x, powers=powers)
assert m == Poly(T, domain=QQ)
assert len(powers) == 5
# powers list need not be passed
m = find_min_poly(A(1), QQ, x=x)
assert m == Poly(T, domain=QQ)
B = A.submodule_from_matrix(2 * DomainMatrix.eye(4, ZZ))
raises(MissingUnityError, lambda: find_min_poly(B(1), QQ))
|
7f197c87be05461dab3dc964fe7c0f10bc6448c9f799bbfc51da7ad89255df69 | 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=ZZ(2)) == hnf
assert hermite_normal_form(m, D=ZZ(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, ZZ(96)))
raises(DMDomainError, lambda: _hermite_normal_form_modulo_D(m, QQ(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=ZZ(8)) == hnf
assert hermite_normal_form(m, D=ZZ(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, ZZ(1)))
|
22345aeae09f02ed619ba5eb3757d451a000d86795c62e4881569fe2f65ce0b9 | 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)
Acopy = A.convert_to(None)
assert Acopy == A and Acopy is not A
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
|
79b983fa003c523d0a7c869acd5c834018b0c28f0b34e4a0d3303f40538548b3 | from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
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(S(1), S(2), S(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, (S(1), S(2), S(3)))
expected = Basic(S(1), S(2), S(3))
assert construct(expr) == expected
def test_nested():
expr = Basic(S(1), Basic(S(2)), S(3))
cmpd = Compound(Basic, (S(1), Compound(Basic, Tuple(2)), S(3)))
assert deconstruct(expr) == cmpd
assert construct(cmpd) == expr
def test_unify():
expr = Basic(S(1), S(2), S(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(S(1), S(2)), Basic(S(1), x), {}, variables=(x,))) == [{x: 2}]
def test_s_input():
expr = Basic(S(1), S(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)))
|
06003cce6773f4dc3e5dbbb8fb0dd4001796ca9a8bbe6cbd5732fbe3812662d1 | 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, S(1)), Basic(p, S(2)), variables=(p,))
assert list(rl(Basic(S(3), S(1)))) == [Basic(S(3), S(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, S(1)), Basic(x, S(2)), variables=(x,))
assert list(rl(Basic(S(3), S(1)))) == [Basic(S(3), S(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]
|
20244bb5d53b9d764e249a327d095f6b4bae8be5008887531a8be591dae77801 | #!/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 definition not 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 symbol not 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)
|
897f53241dfa5ce602c65bc36edc6ba19595258e395fdc289616274c2dae4a81 | # 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."
message_bare_expr = "File contains bare expression: %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)
class _Visit(ast.NodeVisitor):
"""return the line number corresponding to the
line on which a bare expression appears if it is a binary op
or a comparison that is not in a with block.
EXAMPLES
========
>>> import ast
>>> class _Visit(ast.NodeVisitor):
... def visit_Expr(self, node):
... if isinstance(node.value, (ast.BinOp, ast.Compare)):
... print(node.lineno)
... def visit_With(self, node):
... pass # no checking there
...
>>> code='''x = 1 # line 1
... for i in range(3):
... x == 2 # <-- 3
... if x == 2:
... x == 3 # <-- 5
... x + 1 # <-- 6
... x = 1
... if x == 1:
... print(1)
... while x != 1:
... x == 1 # <-- 11
... with raises(TypeError):
... c == 1
... raise TypeError
... assert x == 1
... '''
>>> _Visit().visit(ast.parse(code))
3
5
6
11
"""
def visit_Expr(self, node):
if isinstance(node.value, (ast.BinOp, ast.Compare)):
assert None, message_bare_expr % ('', node.lineno)
def visit_With(self, node):
pass
BareExpr = _Visit()
def line_with_bare_expr(code):
"""return None or else 0-based line number of code on which
a bare expression appeared.
"""
tree = ast.parse(code)
try:
BareExpr.visit(tree)
except AssertionError as msg:
assert msg.args
msg = msg.args[0]
assert msg.startswith(message_bare_expr.split(':', 1)[0])
return int(msg.rsplit(' ', 1)[1].rstrip('.')) # the line number
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
o there is no do-nothing expression like `a == b` or `x + 1`
"""
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):
idx = None
code = test_file.read()
test_file.seek(0) # restore reader to head
py = fname if sep not in fname else fname.rsplit(sep, 1)[-1]
if py.startswith('test_'):
idx = line_with_bare_expr(code)
if idx is not None:
assert False, message_bare_expr % (fname, idx + 1)
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)
|
42044f9ccac264933a20658971b5da9698bc4cf5b32308655b0dbbf3faceb5ce | 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))
def test_srepr():
from sympy.printing.repr import srepr
res = "CoordSys3D(Str('C'), Tuple(ImmutableDenseMatrix([[Integer(1), "\
"Integer(0), Integer(0)], [Integer(0), Integer(1), Integer(0)], "\
"[Integer(0), Integer(0), Integer(1)]]), VectorZero())).i"
assert srepr(C.i) == res
|
055461aebfc9780b022affc4fa40368da5c1f195d37e3ee790d813e68f973897 | 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
assert 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))
|
7f547e04bffadd505b7345e0117fcb63357fdceba961de21a79473464e9d01b2 | 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
def test_dyadic_srepr():
from sympy.printing.repr import srepr
N = CoordSys3D('N')
dy = N.i | N.j
res = "BaseDyadic(CoordSys3D(Str('N'), Tuple(ImmutableDenseMatrix([["\
"Integer(1), Integer(0), Integer(0)], [Integer(0), Integer(1), "\
"Integer(0)], [Integer(0), Integer(0), Integer(1)]]), "\
"VectorZero())).i, CoordSys3D(Str('N'), Tuple(ImmutableDenseMatrix("\
"[[Integer(1), Integer(0), Integer(0)], [Integer(0), Integer(1), "\
"Integer(0)], [Integer(0), Integer(0), Integer(1)]]), VectorZero())).j)"
assert srepr(dy) == res
|
e1222143b9b5ec109696d564af66c8d0fc35046b26c7e5aade00f71c60d66a23 | 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)
assert r1.regular_point() == (-4,)
c1 = ImplicitRegion((x, y), x**2 + y**2 - 4)
assert c1.regular_point() == (0, -2)
c2 = ImplicitRegion((x, y), (x - S(5)/2)**2 + y**2 - (S(1)/4)**2)
assert c2.regular_point() == (S(5)/2, -S(1)/4)
c3 = ImplicitRegion((x, y), (y - 5)**2 - 16*(x - 5))
assert c3.regular_point() == (5, 5)
r2 = ImplicitRegion((x, y), x**2 - 4*x*y - 3*y**2 + 4*x + 8*y - 5)
assert r2.regular_point() == (S(4)/7, S(9)/7)
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))
assert conic.rational_parametrization(t) == (
S(17)/2 + 4/(3*t**2 + 4*t + 1), 4*t/(3*t**2 + 4*t + 1) - S(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())
|
9c740874632955301e2a2fda731d34581533224b0cf04753ec9e857a13cdc795 | # -*- 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)\\left(\\mathbf{\\hat{i}_{N}}{\\middle|}' +
'\\mathbf{\\hat{k}_{N}}\\right)')
assert latex(d[9]) == ('\\left(\\mathbf{\\hat{k}_{C}}{\\middle|}' +
'\\mathbf{\\hat{k}_{N}}\\right) + \\left(' +
'\\mathbf{\\hat{i}_{N}}{\\middle|}\\mathbf{' +
'\\hat{k}_{N}}\\right)')
assert latex(d[11]) == ('(a^{2} + b)\\left(\\mathbf{\\hat{i}_{N}}' +
'{\\middle|}\\mathbf{\\hat{k}_{N}}\\right) + ' +
'(\\int f{\\left(b \\right)}\\, db)\\left(' +
'\\mathbf{\\hat{k}_{N}}{\\middle|}\\mathbf{' +
'\\hat{k}_{N}}\\right)')
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}}"
|
cbabd831dea0bd8a12c848840624712489639d01966d3893101627a2e07ed12f | 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 sympy.core.random import randint
from sympy.utilities.iterables import subsets
for how in (min, max):
if how == 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, dup, s):
d = how(i.distance(j) for i, j in subsets(set(points), 2))
ans = a, b = list(func(*points))[0]
assert 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]
assert 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
|
32488e54032279bae2dda40a5c3040e2a71f1da05fc5c8befe703ddfad22bd62 | 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', 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]
|
d2904a766448113ab4a49623c518f7e01d23fa8e7a7f88aacc9cbd2786ee53b5 | 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
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)
slope = S.ComplexInfinity
while slope is S.ComplexInfinity:
slope = Rational(*(x._random()/2).as_real_imag())
l = Line(pent.vertices[1], slope=slope)
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))
|
6bc1ada859b24b53778667f81b8e6f5665c534654208f30a4d0b4f72a92113ac | 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.core.random 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
assert 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))
assert p2.first_moment_of_area() == (S(1600)/3, -S(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
|
80f1d2d8c87d810a4b6d26021d998d715a0b46fda4e3fd0726f82ed9c138d535 | 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
assert parse_expr('a + b', {}) == a + b
raises(SympifyError, lambda: parse_expr('a + ', {}))
# tests Transform.visit_Num
assert parse_expr('1 + 2', {}) == S(3)
assert parse_expr('1 + 2.0', {}) == S(3.0)
# tests Transform.visit_Name
assert parse_expr('Rational(1, 2)', {}) == S(1)/2
assert parse_expr('a', {'a': a}) == a
|
bd809310bb6fee4e303af0f0b6a612453d1b138019de3eaffc66386e8acd19c7 | # -*- coding: utf-8 -*-
import sys
from sympy.assumptions import Q
from sympy.core import Symbol, Function, Float, Rational, Integer, I, Mul, Pow, Eq
from sympy.functions import exp, factorial, factorial2, sin
from sympy.logic import And
from sympy.series import Limit
from sympy.testing.pytest import raises, skip
from sympy.parsing.sympy_parser import (
parse_expr, standard_transformations, rationalize, TokenError,
split_symbols, implicit_multiplication, convert_equals_signs,
convert_xor, function_exponentiation, lambda_notation, auto_symbol,
repeated_decimals, implicit_multiplication_application,
auto_number, factorial_notation, implicit_application,
_transformation, T
)
def test_sympy_parser():
x = Symbol('x')
inputs = {
'2*x': 2 * x,
'3.00': Float(3),
'22/7': Rational(22, 7),
'2+3j': 2 + 3*I,
'exp(x)': exp(x),
'x!': factorial(x),
'x!!': factorial2(x),
'(x + 1)! - 1': factorial(x + 1) - 1,
'3.[3]': Rational(10, 3),
'.0[3]': Rational(1, 30),
'3.2[3]': Rational(97, 30),
'1.3[12]': Rational(433, 330),
'1 + 3.[3]': Rational(13, 3),
'1 + .0[3]': Rational(31, 30),
'1 + 3.2[3]': Rational(127, 30),
'.[0011]': Rational(1, 909),
'0.1[00102] + 1': Rational(366697, 333330),
'1.[0191]': Rational(10190, 9999),
'10!': 3628800,
'-(2)': -Integer(2),
'[-1, -2, 3]': [Integer(-1), Integer(-2), Integer(3)],
'Symbol("x").free_symbols': x.free_symbols,
"S('S(3).n(n=3)')": 3.00,
'factorint(12, visual=True)': Mul(
Pow(2, 2, evaluate=False),
Pow(3, 1, evaluate=False),
evaluate=False),
'Limit(sin(x), x, 0, dir="-")': Limit(sin(x), x, 0, dir='-'),
'Q.even(x)': Q.even(x),
}
for text, result in inputs.items():
assert parse_expr(text) == result
raises(TypeError, lambda:
parse_expr('x', standard_transformations))
raises(TypeError, lambda:
parse_expr('x', transformations=lambda x,y: 1))
raises(TypeError, lambda:
parse_expr('x', transformations=(lambda x,y: 1,)))
raises(TypeError, lambda: parse_expr('x', transformations=((),)))
raises(TypeError, lambda: parse_expr('x', {}, [], []))
raises(TypeError, lambda: parse_expr('x', [], [], {}))
raises(TypeError, lambda: parse_expr('x', [], [], {}))
def test_rationalize():
inputs = {
'0.123': Rational(123, 1000)
}
transformations = standard_transformations + (rationalize,)
for text, result in inputs.items():
assert parse_expr(text, transformations=transformations) == result
def test_factorial_fail():
inputs = ['x!!!', 'x!!!!', '(!)']
for text in inputs:
try:
parse_expr(text)
assert False
except TokenError:
assert True
def test_repeated_fail():
inputs = ['1[1]', '.1e1[1]', '0x1[1]', '1.1j[1]', '1.1[1 + 1]',
'0.1[[1]]', '0x1.1[1]']
# All are valid Python, so only raise TypeError for invalid indexing
for text in inputs:
raises(TypeError, lambda: parse_expr(text))
inputs = ['0.1[', '0.1[1', '0.1[]']
for text in inputs:
raises((TokenError, SyntaxError), lambda: parse_expr(text))
def test_repeated_dot_only():
assert parse_expr('.[1]') == Rational(1, 9)
assert parse_expr('1 + .[1]') == Rational(10, 9)
def test_local_dict():
local_dict = {
'my_function': lambda x: x + 2
}
inputs = {
'my_function(2)': Integer(4)
}
for text, result in inputs.items():
assert parse_expr(text, local_dict=local_dict) == result
def test_local_dict_split_implmult():
t = standard_transformations + (split_symbols, implicit_multiplication,)
w = Symbol('w', real=True)
y = Symbol('y')
assert parse_expr('yx', local_dict={'x':w}, transformations=t) == y*w
def test_local_dict_symbol_to_fcn():
x = Symbol('x')
d = {'foo': Function('bar')}
assert parse_expr('foo(x)', local_dict=d) == d['foo'](x)
d = {'foo': Symbol('baz')}
raises(TypeError, lambda: parse_expr('foo(x)', local_dict=d))
def test_global_dict():
global_dict = {
'Symbol': Symbol
}
inputs = {
'Q & S': And(Symbol('Q'), Symbol('S'))
}
for text, result in inputs.items():
assert parse_expr(text, global_dict=global_dict) == result
def test_issue_2515():
raises(TokenError, lambda: parse_expr('(()'))
raises(TokenError, lambda: parse_expr('"""'))
def test_issue_7663():
x = Symbol('x')
e = '2*(x+1)'
assert parse_expr(e, evaluate=0) == parse_expr(e, evaluate=False)
assert parse_expr(e, evaluate=0).equals(2*(x+1))
def test_recursive_evaluate_false_10560():
inputs = {
'4*-3' : '4*-3',
'-4*3' : '(-4)*3',
"-2*x*y": '(-2)*x*y',
"x*-4*x": "x*(-4)*x"
}
for text, result in inputs.items():
assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
def test_function_evaluate_false():
inputs = [
'Abs(0)', 'im(0)', 're(0)', 'sign(0)', 'arg(0)', 'conjugate(0)',
'acos(0)', 'acot(0)', 'acsc(0)', 'asec(0)', 'asin(0)', 'atan(0)',
'acosh(0)', 'acoth(0)', 'acsch(0)', 'asech(0)', 'asinh(0)', 'atanh(0)',
'cos(0)', 'cot(0)', 'csc(0)', 'sec(0)', 'sin(0)', 'tan(0)',
'cosh(0)', 'coth(0)', 'csch(0)', 'sech(0)', 'sinh(0)', 'tanh(0)',
'exp(0)', 'log(0)', 'sqrt(0)',
]
for case in inputs:
expr = parse_expr(case, evaluate=False)
assert case == str(expr) != str(expr.doit())
assert str(parse_expr('ln(0)', evaluate=False)) == 'log(0)'
assert str(parse_expr('cbrt(0)', evaluate=False)) == '0**(1/3)'
def test_issue_10773():
inputs = {
'-10/5': '(-10)/5',
'-10/-5' : '(-10)/(-5)',
}
for text, result in inputs.items():
assert parse_expr(text, evaluate=False) == parse_expr(result, evaluate=False)
def test_split_symbols():
transformations = standard_transformations + \
(split_symbols, implicit_multiplication,)
x = Symbol('x')
y = Symbol('y')
xy = Symbol('xy')
assert parse_expr("xy") == xy
assert parse_expr("xy", transformations=transformations) == x*y
def test_split_symbols_function():
transformations = standard_transformations + \
(split_symbols, implicit_multiplication,)
x = Symbol('x')
y = Symbol('y')
a = Symbol('a')
f = Function('f')
assert parse_expr("ay(x+1)", transformations=transformations) == a*y*(x+1)
assert parse_expr("af(x+1)", transformations=transformations,
local_dict={'f':f}) == a*f(x+1)
def test_functional_exponent():
t = standard_transformations + (convert_xor, function_exponentiation)
x = Symbol('x')
y = Symbol('y')
a = Symbol('a')
yfcn = Function('y')
assert parse_expr("sin^2(x)", transformations=t) == (sin(x))**2
assert parse_expr("sin^y(x)", transformations=t) == (sin(x))**y
assert parse_expr("exp^y(x)", transformations=t) == (exp(x))**y
assert parse_expr("E^y(x)", transformations=t) == exp(yfcn(x))
assert parse_expr("a^y(x)", transformations=t) == a**(yfcn(x))
def test_match_parentheses_implicit_multiplication():
transformations = standard_transformations + \
(implicit_multiplication,)
raises(TokenError, lambda: parse_expr('(1,2),(3,4]',transformations=transformations))
def test_convert_equals_signs():
transformations = standard_transformations + \
(convert_equals_signs, )
x = Symbol('x')
y = Symbol('y')
assert parse_expr("1*2=x", transformations=transformations) == Eq(2, x)
assert parse_expr("y = x", transformations=transformations) == Eq(y, x)
assert parse_expr("(2*y = x) = False",
transformations=transformations) == Eq(Eq(2*y, x), False)
def test_parse_function_issue_3539():
x = Symbol('x')
f = Function('f')
assert parse_expr('f(x)') == f(x)
def test_split_symbols_numeric():
transformations = (
standard_transformations +
(implicit_multiplication_application,))
n = Symbol('n')
expr1 = parse_expr('2**n * 3**n')
expr2 = parse_expr('2**n3**n', transformations=transformations)
assert expr1 == expr2 == 2**n*3**n
expr1 = parse_expr('n12n34', transformations=transformations)
assert expr1 == n*12*n*34
def test_unicode_names():
assert parse_expr('α') == Symbol('α')
def test_python3_features():
# Make sure the tokenizer can handle Python 3-only features
if sys.version_info < (3, 7):
skip("test_python3_features requires Python 3.7 or newer")
assert parse_expr("123_456") == 123456
assert parse_expr("1.2[3_4]") == parse_expr("1.2[34]") == Rational(611, 495)
assert parse_expr("1.2[012_012]") == parse_expr("1.2[012012]") == Rational(400, 333)
assert parse_expr('.[3_4]') == parse_expr('.[34]') == Rational(34, 99)
assert parse_expr('.1[3_4]') == parse_expr('.1[34]') == Rational(133, 990)
assert parse_expr('123_123.123_123[3_4]') == parse_expr('123123.123123[34]') == Rational(12189189189211, 99000000)
def test_issue_19501():
x = Symbol('x')
eq = parse_expr('E**x(1+x)', local_dict={'x': x}, transformations=(
standard_transformations +
(implicit_multiplication_application,)))
assert eq.free_symbols == {x}
def test_parsing_definitions():
from sympy.abc import x
assert len(_transformation) == 12 # if this changes, extend below
assert _transformation[0] == lambda_notation
assert _transformation[1] == auto_symbol
assert _transformation[2] == repeated_decimals
assert _transformation[3] == auto_number
assert _transformation[4] == factorial_notation
assert _transformation[5] == implicit_multiplication_application
assert _transformation[6] == convert_xor
assert _transformation[7] == implicit_application
assert _transformation[8] == implicit_multiplication
assert _transformation[9] == convert_equals_signs
assert _transformation[10] == function_exponentiation
assert _transformation[11] == rationalize
assert T[:5] == T[0,1,2,3,4] == standard_transformations
t = _transformation
assert T[-1, 0] == (t[len(t) - 1], t[0])
assert T[:5, 8] == standard_transformations + (t[8],)
assert parse_expr('0.3x^2', transformations='all') == 3*x**2/10
assert parse_expr('sin 3x', transformations='implicit') == sin(3*x)
def test_builtins():
cases = [
('abs(x)', 'Abs(x)'),
('max(x, y)', 'Max(x, y)'),
('min(x, y)', 'Min(x, y)'),
('pow(x, y)', 'Pow(x, y)'),
]
for built_in_func_call, sympy_func_call in cases:
assert parse_expr(built_in_func_call) == parse_expr(sympy_func_call)
assert str(parse_expr('pow(38, -1, 97)')) == '23'
|
dd9d9ca24832586d32d17c51c37aa2e1388695a44ec07e2c8ebdb7478b0964d7 | from typing import Type
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.expr import Expr
from sympy.core.function import expand
from sympy.core.mul import Mul
from sympy.core.power import Pow
from sympy.core.symbol import Symbol
from sympy.polys.polyroots import roots
from sympy.polys.polytools import (cancel, degree)
from sympy.core.containers import Tuple
from sympy.core.evalf import EvalfMixin
from sympy.core.logic import fuzzy_and
from sympy.core.numbers import Integer, ComplexInfinity
from sympy.core.symbol import Dummy
from sympy.core.sympify import sympify, _sympify
from sympy.polys import Poly, rootof
from sympy.series import limit
from sympy.matrices import ImmutableMatrix, eye
from sympy.matrices.expressions import MatMul, MatAdd
from mpmath.libmp.libmpf import prec_to_dps
__all__ = ['TransferFunction', 'Series', 'MIMOSeries', 'Parallel', 'MIMOParallel',
'Feedback', 'MIMOFeedback', 'TransferFunctionMatrix']
def _roots(poly, var):
""" like roots, but works on higher-order polynomials. """
r = roots(poly, var, multiple=True)
n = degree(poly)
if len(r) != n:
r = [rootof(poly, var, k) for k in range(n)]
return r
class LinearTimeInvariant(Basic, EvalfMixin):
"""A common class for all the Linear Time-Invariant Dynamical Systems."""
_clstype: Type
# Users should not directly interact with this class.
def __new__(cls, *system, **kwargs):
if cls is LinearTimeInvariant:
raise NotImplementedError('The LTICommon class is not meant to be used directly.')
return super(LinearTimeInvariant, cls).__new__(cls, *system, **kwargs)
@classmethod
def _check_args(cls, args):
if not args:
raise ValueError("Atleast 1 argument must be passed.")
if not all(isinstance(arg, cls._clstype) for arg in args):
raise TypeError(f"All arguments must be of type {cls._clstype}.")
var_set = {arg.var for arg in args}
if len(var_set) != 1:
raise ValueError("All transfer functions should use the same complex variable"
f" of the Laplace transform. {len(var_set)} different values found.")
@property
def is_SISO(self):
"""Returns `True` if the passed LTI system is SISO else returns False."""
return self._is_SISO
class SISOLinearTimeInvariant(LinearTimeInvariant):
"""A common class for all the SISO Linear Time-Invariant Dynamical Systems."""
# Users should not directly interact with this class.
_is_SISO = True
class MIMOLinearTimeInvariant(LinearTimeInvariant):
"""A common class for all the MIMO Linear Time-Invariant Dynamical Systems."""
# Users should not directly interact with this class.
_is_SISO = False
SISOLinearTimeInvariant._clstype = SISOLinearTimeInvariant
MIMOLinearTimeInvariant._clstype = MIMOLinearTimeInvariant
def _check_other_SISO(func):
def wrapper(*args, **kwargs):
if not isinstance(args[-1], SISOLinearTimeInvariant):
return NotImplemented
else:
return func(*args, **kwargs)
return wrapper
def _check_other_MIMO(func):
def wrapper(*args, **kwargs):
if not isinstance(args[-1], MIMOLinearTimeInvariant):
return NotImplemented
else:
return func(*args, **kwargs)
return wrapper
class TransferFunction(SISOLinearTimeInvariant):
r"""
A class for representing LTI (Linear, time-invariant) systems that can be strictly described
by ratio of polynomials in the Laplace transform complex variable. The arguments
are ``num``, ``den``, and ``var``, where ``num`` and ``den`` are numerator and
denominator polynomials of the ``TransferFunction`` respectively, and the third argument is
a complex variable of the Laplace transform used by these polynomials of the transfer function.
``num`` and ``den`` can be either polynomials or numbers, whereas ``var``
has to be a Symbol.
Explanation
===========
Generally, a dynamical system representing a physical model can be described in terms of Linear
Ordinary Differential Equations like -
$\small{b_{m}y^{\left(m\right)}+b_{m-1}y^{\left(m-1\right)}+\dots+b_{1}y^{\left(1\right)}+b_{0}y=
a_{n}x^{\left(n\right)}+a_{n-1}x^{\left(n-1\right)}+\dots+a_{1}x^{\left(1\right)}+a_{0}x}$
Here, $x$ is the input signal and $y$ is the output signal and superscript on both is the order of derivative
(not exponent). Derivative is taken with respect to the independent variable, $t$. Also, generally $m$ is greater
than $n$.
It is not feasible to analyse the properties of such systems in their native form therefore, we use
mathematical tools like Laplace transform to get a better perspective. Taking the Laplace transform
of both the sides in the equation (at zero initial conditions), we get -
$\small{\mathcal{L}[b_{m}y^{\left(m\right)}+b_{m-1}y^{\left(m-1\right)}+\dots+b_{1}y^{\left(1\right)}+b_{0}y]=
\mathcal{L}[a_{n}x^{\left(n\right)}+a_{n-1}x^{\left(n-1\right)}+\dots+a_{1}x^{\left(1\right)}+a_{0}x]}$
Using the linearity property of Laplace transform and also considering zero initial conditions
(i.e. $\small{y(0^{-}) = 0}$, $\small{y'(0^{-}) = 0}$ and so on), the equation
above gets translated to -
$\small{b_{m}\mathcal{L}[y^{\left(m\right)}]+\dots+b_{1}\mathcal{L}[y^{\left(1\right)}]+b_{0}\mathcal{L}[y]=
a_{n}\mathcal{L}[x^{\left(n\right)}]+\dots+a_{1}\mathcal{L}[x^{\left(1\right)}]+a_{0}\mathcal{L}[x]}$
Now, applying Derivative property of Laplace transform,
$\small{b_{m}s^{m}\mathcal{L}[y]+\dots+b_{1}s\mathcal{L}[y]+b_{0}\mathcal{L}[y]=
a_{n}s^{n}\mathcal{L}[x]+\dots+a_{1}s\mathcal{L}[x]+a_{0}\mathcal{L}[x]}$
Here, the superscript on $s$ is **exponent**. Note that the zero initial conditions assumption, mentioned above, is very important
and cannot be ignored otherwise the dynamical system cannot be considered time-independent and the simplified equation above
cannot be reached.
Collecting $\mathcal{L}[y]$ and $\mathcal{L}[x]$ terms from both the sides and taking the ratio
$\frac{ \mathcal{L}\left\{y\right\} }{ \mathcal{L}\left\{x\right\} }$, we get the typical rational form of transfer
function.
The numerator of the transfer function is, therefore, the Laplace transform of the output signal
(The signals are represented as functions of time) and similarly, the denominator
of the transfer function is the Laplace transform of the input signal. It is also a convention
to denote the input and output signal's Laplace transform with capital alphabets like shown below.
$H(s) = \frac{Y(s)}{X(s)} = \frac{ \mathcal{L}\left\{y(t)\right\} }{ \mathcal{L}\left\{x(t)\right\} }$
$s$, also known as complex frequency, is a complex variable in the Laplace domain. It corresponds to the
equivalent variable $t$, in the time domain. Transfer functions are sometimes also referred to as the Laplace
transform of the system's impulse response. Transfer function, $H$, is represented as a rational
function in $s$ like,
$H(s) =\ \frac{a_{n}s^{n}+a_{n-1}s^{n-1}+\dots+a_{1}s+a_{0}}{b_{m}s^{m}+b_{m-1}s^{m-1}+\dots+b_{1}s+b_{0}}$
Parameters
==========
num : Expr, Number
The numerator polynomial of the transfer function.
den : Expr, Number
The denominator polynomial of the transfer function.
var : Symbol
Complex variable of the Laplace transform used by the
polynomials of the transfer function.
Raises
======
TypeError
When ``var`` is not a Symbol or when ``num`` or ``den`` is not a
number or a polynomial.
ValueError
When ``den`` is zero.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(s + a, s**2 + s + 1, s)
>>> tf1
TransferFunction(a + s, s**2 + s + 1, s)
>>> tf1.num
a + s
>>> tf1.den
s**2 + s + 1
>>> tf1.var
s
>>> tf1.args
(a + s, s**2 + s + 1, s)
Any complex variable can be used for ``var``.
>>> tf2 = TransferFunction(a*p**3 - a*p**2 + s*p, p + a**2, p)
>>> tf2
TransferFunction(a*p**3 - a*p**2 + p*s, a**2 + p, p)
>>> tf3 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
>>> tf3
TransferFunction((p - 1)*(p + 3), (p - 1)*(p + 5), p)
To negate a transfer function the ``-`` operator can be prepended:
>>> tf4 = TransferFunction(-a + s, p**2 + s, p)
>>> -tf4
TransferFunction(a - s, p**2 + s, p)
>>> tf5 = TransferFunction(s**4 - 2*s**3 + 5*s + 4, s + 4, s)
>>> -tf5
TransferFunction(-s**4 + 2*s**3 - 5*s - 4, s + 4, s)
You can use a Float or an Integer (or other constants) as numerator and denominator:
>>> tf6 = TransferFunction(1/2, 4, s)
>>> tf6.num
0.500000000000000
>>> tf6.den
4
>>> tf6.var
s
>>> tf6.args
(0.5, 4, s)
You can take the integer power of a transfer function using the ``**`` operator:
>>> tf7 = TransferFunction(s + a, s - a, s)
>>> tf7**3
TransferFunction((a + s)**3, (-a + s)**3, s)
>>> tf7**0
TransferFunction(1, 1, s)
>>> tf8 = TransferFunction(p + 4, p - 3, p)
>>> tf8**-1
TransferFunction(p - 3, p + 4, p)
Addition, subtraction, and multiplication of transfer functions can form
unevaluated ``Series`` or ``Parallel`` objects.
>>> tf9 = TransferFunction(s + 1, s**2 + s + 1, s)
>>> tf10 = TransferFunction(s - p, s + 3, s)
>>> tf11 = TransferFunction(4*s**2 + 2*s - 4, s - 1, s)
>>> tf12 = TransferFunction(1 - s, s**2 + 4, s)
>>> tf9 + tf10
Parallel(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-p + s, s + 3, s))
>>> tf10 - tf11
Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(-4*s**2 - 2*s + 4, s - 1, s))
>>> tf9 * tf10
Series(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-p + s, s + 3, s))
>>> tf10 - (tf9 + tf12)
Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(-s - 1, s**2 + s + 1, s), TransferFunction(s - 1, s**2 + 4, s))
>>> tf10 - (tf9 * tf12)
Parallel(TransferFunction(-p + s, s + 3, s), Series(TransferFunction(-1, 1, s), TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(1 - s, s**2 + 4, s)))
>>> tf11 * tf10 * tf9
Series(TransferFunction(4*s**2 + 2*s - 4, s - 1, s), TransferFunction(-p + s, s + 3, s), TransferFunction(s + 1, s**2 + s + 1, s))
>>> tf9 * tf11 + tf10 * tf12
Parallel(Series(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(4*s**2 + 2*s - 4, s - 1, s)), Series(TransferFunction(-p + s, s + 3, s), TransferFunction(1 - s, s**2 + 4, s)))
>>> (tf9 + tf12) * (tf10 + tf11)
Series(Parallel(TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(1 - s, s**2 + 4, s)), Parallel(TransferFunction(-p + s, s + 3, s), TransferFunction(4*s**2 + 2*s - 4, s - 1, s)))
These unevaluated ``Series`` or ``Parallel`` objects can convert into the
resultant transfer function using ``.doit()`` method or by ``.rewrite(TransferFunction)``.
>>> ((tf9 + tf10) * tf12).doit()
TransferFunction((1 - s)*((-p + s)*(s**2 + s + 1) + (s + 1)*(s + 3)), (s + 3)*(s**2 + 4)*(s**2 + s + 1), s)
>>> (tf9 * tf10 - tf11 * tf12).rewrite(TransferFunction)
TransferFunction(-(1 - s)*(s + 3)*(s**2 + s + 1)*(4*s**2 + 2*s - 4) + (-p + s)*(s - 1)*(s + 1)*(s**2 + 4), (s - 1)*(s + 3)*(s**2 + 4)*(s**2 + s + 1), s)
See Also
========
Feedback, Series, Parallel
References
==========
.. [1] https://en.wikipedia.org/wiki/Transfer_function
.. [2] https://en.wikipedia.org/wiki/Laplace_transform
"""
def __new__(cls, num, den, var):
num, den = _sympify(num), _sympify(den)
if not isinstance(var, Symbol):
raise TypeError("Variable input must be a Symbol.")
if den == 0:
raise ValueError("TransferFunction cannot have a zero denominator.")
if (((isinstance(num, Expr) and num.has(Symbol)) or num.is_number) and
((isinstance(den, Expr) and den.has(Symbol)) or den.is_number)):
obj = super(TransferFunction, cls).__new__(cls, num, den, var)
obj._num = num
obj._den = den
obj._var = var
return obj
else:
raise TypeError("Unsupported type for numerator or denominator of TransferFunction.")
@classmethod
def from_rational_expression(cls, expr, var=None):
r"""
Creates a new ``TransferFunction`` efficiently from a rational expression.
Parameters
==========
expr : Expr, Number
The rational expression representing the ``TransferFunction``.
var : Symbol, optional
Complex variable of the Laplace transform used by the
polynomials of the transfer function.
Raises
======
ValueError
When ``expr`` is of type ``Number`` and optional parameter ``var``
is not passed.
When ``expr`` has more than one variables and an optional parameter
``var`` is not passed.
ZeroDivisionError
When denominator of ``expr`` is zero or it has ``ComplexInfinity``
in its numerator.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> expr1 = (s + 5)/(3*s**2 + 2*s + 1)
>>> tf1 = TransferFunction.from_rational_expression(expr1)
>>> tf1
TransferFunction(s + 5, 3*s**2 + 2*s + 1, s)
>>> expr2 = (a*p**3 - a*p**2 + s*p)/(p + a**2) # Expr with more than one variables
>>> tf2 = TransferFunction.from_rational_expression(expr2, p)
>>> tf2
TransferFunction(a*p**3 - a*p**2 + p*s, a**2 + p, p)
In case of conflict between two or more variables in a expression, SymPy will
raise a ``ValueError``, if ``var`` is not passed by the user.
>>> tf = TransferFunction.from_rational_expression((a + a*s)/(s**2 + s + 1))
Traceback (most recent call last):
...
ValueError: Conflicting values found for positional argument `var` ({a, s}). Specify it manually.
This can be corrected by specifying the ``var`` parameter manually.
>>> tf = TransferFunction.from_rational_expression((a + a*s)/(s**2 + s + 1), s)
>>> tf
TransferFunction(a*s + a, s**2 + s + 1, s)
``var`` also need to be specified when ``expr`` is a ``Number``
>>> tf3 = TransferFunction.from_rational_expression(10, s)
>>> tf3
TransferFunction(10, 1, s)
"""
expr = _sympify(expr)
if var is None:
_free_symbols = expr.free_symbols
_len_free_symbols = len(_free_symbols)
if _len_free_symbols == 1:
var = list(_free_symbols)[0]
elif _len_free_symbols == 0:
raise ValueError("Positional argument `var` not found in the TransferFunction defined. Specify it manually.")
else:
raise ValueError("Conflicting values found for positional argument `var` ({}). Specify it manually.".format(_free_symbols))
_num, _den = expr.as_numer_denom()
if _den == 0 or _num.has(ComplexInfinity):
raise ZeroDivisionError("TransferFunction cannot have a zero denominator.")
return cls(_num, _den, var)
@property
def num(self):
"""
Returns the numerator polynomial of the transfer function.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction(s**2 + p*s + 3, s - 4, s)
>>> G1.num
p*s + s**2 + 3
>>> G2 = TransferFunction((p + 5)*(p - 3), (p - 3)*(p + 1), p)
>>> G2.num
(p - 3)*(p + 5)
"""
return self._num
@property
def den(self):
"""
Returns the denominator polynomial of the transfer function.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction(s + 4, p**3 - 2*p + 4, s)
>>> G1.den
p**3 - 2*p + 4
>>> G2 = TransferFunction(3, 4, s)
>>> G2.den
4
"""
return self._den
@property
def var(self):
"""
Returns the complex variable of the Laplace transform used by the polynomials of
the transfer function.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G1.var
p
>>> G2 = TransferFunction(0, s - 5, s)
>>> G2.var
s
"""
return self._var
def _eval_subs(self, old, new):
arg_num = self.num.subs(old, new)
arg_den = self.den.subs(old, new)
argnew = TransferFunction(arg_num, arg_den, self.var)
return self if old == self.var else argnew
def _eval_evalf(self, prec):
return TransferFunction(
self.num._eval_evalf(prec),
self.den._eval_evalf(prec),
self.var)
def _eval_simplify(self, **kwargs):
tf = cancel(Mul(self.num, 1/self.den, evaluate=False), expand=False).as_numer_denom()
num_, den_ = tf[0], tf[1]
return TransferFunction(num_, den_, self.var)
def expand(self):
"""
Returns the transfer function with numerator and denominator
in expanded form.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> G1 = TransferFunction((a - s)**2, (s**2 + a)**2, s)
>>> G1.expand()
TransferFunction(a**2 - 2*a*s + s**2, a**2 + 2*a*s**2 + s**4, s)
>>> G2 = TransferFunction((p + 3*b)*(p - b), (p - b)*(p + 2*b), p)
>>> G2.expand()
TransferFunction(-3*b**2 + 2*b*p + p**2, -2*b**2 + b*p + p**2, p)
"""
return TransferFunction(expand(self.num), expand(self.den), self.var)
def dc_gain(self):
"""
Computes the gain of the response as the frequency approaches zero.
The DC gain is infinite for systems with pure integrators.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(s + 3, s**2 - 9, s)
>>> tf1.dc_gain()
-1/3
>>> tf2 = TransferFunction(p**2, p - 3 + p**3, p)
>>> tf2.dc_gain()
0
>>> tf3 = TransferFunction(a*p**2 - b, s + b, s)
>>> tf3.dc_gain()
(a*p**2 - b)/b
>>> tf4 = TransferFunction(1, s, s)
>>> tf4.dc_gain()
oo
"""
m = Mul(self.num, Pow(self.den, -1, evaluate=False), evaluate=False)
return limit(m, self.var, 0)
def poles(self):
"""
Returns the poles of a transfer function.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
>>> tf1.poles()
[-5, 1]
>>> tf2 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
>>> tf2.poles()
[I, I, -I, -I]
>>> tf3 = TransferFunction(s**2, a*s + p, s)
>>> tf3.poles()
[-p/a]
"""
return _roots(Poly(self.den, self.var), self.var)
def zeros(self):
"""
Returns the zeros of a transfer function.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
>>> tf1.zeros()
[-3, 1]
>>> tf2 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
>>> tf2.zeros()
[1, 1]
>>> tf3 = TransferFunction(s**2, a*s + p, s)
>>> tf3.zeros()
[0, 0]
"""
return _roots(Poly(self.num, self.var), self.var)
def is_stable(self):
"""
Returns True if the transfer function is asymptotically stable; else False.
This would not check the marginal or conditional stability of the system.
Examples
========
>>> from sympy.abc import s, p, a
>>> from sympy import symbols
>>> from sympy.physics.control.lti import TransferFunction
>>> q, r = symbols('q, r', negative=True)
>>> tf1 = TransferFunction((1 - s)**2, (s + 1)**2, s)
>>> tf1.is_stable()
True
>>> tf2 = TransferFunction((1 - p)**2, (s**2 + 1)**2, s)
>>> tf2.is_stable()
False
>>> tf3 = TransferFunction(4, q*s - r, s)
>>> tf3.is_stable()
False
>>> tf4 = TransferFunction(p + 1, a*p - s**2, p)
>>> tf4.is_stable() is None # Not enough info about the symbols to determine stability
True
"""
return fuzzy_and(pole.as_real_imag()[0].is_negative for pole in self.poles())
def __add__(self, other):
if isinstance(other, (TransferFunction, Series)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
return Parallel(self, other)
elif isinstance(other, Parallel):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
arg_list = list(other.args)
return Parallel(self, *arg_list)
else:
raise ValueError("TransferFunction cannot be added with {}.".
format(type(other)))
def __radd__(self, other):
return self + other
def __sub__(self, other):
if isinstance(other, (TransferFunction, Series)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
return Parallel(self, -other)
elif isinstance(other, Parallel):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
arg_list = [-i for i in list(other.args)]
return Parallel(self, *arg_list)
else:
raise ValueError("{} cannot be subtracted from a TransferFunction."
.format(type(other)))
def __rsub__(self, other):
return -self + other
def __mul__(self, other):
if isinstance(other, (TransferFunction, Parallel)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
return Series(self, other)
elif isinstance(other, Series):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
arg_list = list(other.args)
return Series(self, *arg_list)
else:
raise ValueError("TransferFunction cannot be multiplied with {}."
.format(type(other)))
__rmul__ = __mul__
def __truediv__(self, other):
if (isinstance(other, Parallel) and len(other.args) == 2 and isinstance(other.args[0], TransferFunction)
and isinstance(other.args[1], (Series, TransferFunction))):
if not self.var == other.var:
raise ValueError("Both TransferFunction and Parallel should use the"
" same complex variable of the Laplace transform.")
if other.args[1] == self:
# plant and controller with unit feedback.
return Feedback(self, other.args[0])
other_arg_list = list(other.args[1].args) if isinstance(other.args[1], Series) else other.args[1]
if other_arg_list == other.args[1]:
return Feedback(self, other_arg_list)
elif self in other_arg_list:
other_arg_list.remove(self)
else:
return Feedback(self, Series(*other_arg_list))
if len(other_arg_list) == 1:
return Feedback(self, *other_arg_list)
else:
return Feedback(self, Series(*other_arg_list))
else:
raise ValueError("TransferFunction cannot be divided by {}.".
format(type(other)))
__rtruediv__ = __truediv__
def __pow__(self, p):
p = sympify(p)
if not isinstance(p, Integer):
raise ValueError("Exponent must be an Integer.")
if p == 0:
return TransferFunction(1, 1, self.var)
elif p > 0:
num_, den_ = self.num**p, self.den**p
else:
p = abs(p)
num_, den_ = self.den**p, self.num**p
return TransferFunction(num_, den_, self.var)
def __neg__(self):
return TransferFunction(-self.num, self.den, self.var)
@property
def is_proper(self):
"""
Returns True if degree of the numerator polynomial is less than
or equal to degree of the denominator polynomial, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
>>> tf1.is_proper
False
>>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*p + 2, p)
>>> tf2.is_proper
True
"""
return degree(self.num, self.var) <= degree(self.den, self.var)
@property
def is_strictly_proper(self):
"""
Returns True if degree of the numerator polynomial is strictly less
than degree of the denominator polynomial, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf1.is_strictly_proper
False
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf2.is_strictly_proper
True
"""
return degree(self.num, self.var) < degree(self.den, self.var)
@property
def is_biproper(self):
"""
Returns True if degree of the numerator polynomial is equal to
degree of the denominator polynomial, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf1.is_biproper
True
>>> tf2 = TransferFunction(p**2, p + a, p)
>>> tf2.is_biproper
False
"""
return degree(self.num, self.var) == degree(self.den, self.var)
def to_expr(self):
"""
Converts a ``TransferFunction`` object to SymPy Expr.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction
>>> from sympy import Expr
>>> tf1 = TransferFunction(s, a*s**2 + 1, s)
>>> tf1.to_expr()
s/(a*s**2 + 1)
>>> isinstance(_, Expr)
True
>>> tf2 = TransferFunction(1, (p + 3*b)*(b - p), p)
>>> tf2.to_expr()
1/((b - p)*(3*b + p))
>>> tf3 = TransferFunction((s - 2)*(s - 3), (s - 1)*(s - 2)*(s - 3), s)
>>> tf3.to_expr()
((s - 3)*(s - 2))/(((s - 3)*(s - 2)*(s - 1)))
"""
if self.num != 1:
return Mul(self.num, Pow(self.den, -1, evaluate=False), evaluate=False)
else:
return Pow(self.den, -1, evaluate=False)
def _flatten_args(args, _cls):
temp_args = []
for arg in args:
if isinstance(arg, _cls):
temp_args.extend(arg.args)
else:
temp_args.append(arg)
return tuple(temp_args)
def _dummify_args(_arg, var):
dummy_dict = {}
dummy_arg_list = []
for arg in _arg:
_s = Dummy()
dummy_dict[_s] = var
dummy_arg = arg.subs({var: _s})
dummy_arg_list.append(dummy_arg)
return dummy_arg_list, dummy_dict
class Series(SISOLinearTimeInvariant):
r"""
A class for representing a series configuration of SISO systems.
Parameters
==========
args : SISOLinearTimeInvariant
SISO systems in a series configuration.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``Series(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed, SISO in this case.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf3 = TransferFunction(p**2, p + s, s)
>>> S1 = Series(tf1, tf2)
>>> S1
Series(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s))
>>> S1.var
s
>>> S2 = Series(tf2, Parallel(tf3, -tf1))
>>> S2
Series(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), Parallel(TransferFunction(p**2, p + s, s), TransferFunction(-a*p**2 - b*s, -p + s, s)))
>>> S2.var
s
>>> S3 = Series(Parallel(tf1, tf2), Parallel(tf2, tf3))
>>> S3
Series(Parallel(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)), Parallel(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), TransferFunction(p**2, p + s, s)))
>>> S3.var
s
You can get the resultant transfer function by using ``.doit()`` method:
>>> S3 = Series(tf1, tf2, -tf3)
>>> S3.doit()
TransferFunction(-p**2*(s**3 - 2)*(a*p**2 + b*s), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
>>> S4 = Series(tf2, Parallel(tf1, -tf3))
>>> S4.doit()
TransferFunction((s**3 - 2)*(-p**2*(-p + s) + (p + s)*(a*p**2 + b*s)), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
Notes
=====
All the transfer functions should use the same complex variable
``var`` of the Laplace transform.
See Also
========
MIMOSeries, Parallel, TransferFunction, Feedback
"""
def __new__(cls, *args, evaluate=False):
args = _flatten_args(args, Series)
cls._check_args(args)
obj = super().__new__(cls, *args)
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, Series, Parallel
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> Series(G1, G2).var
p
>>> Series(-G3, Parallel(G1, G2)).var
p
"""
return self.args[0].var
def doit(self, **kwargs):
"""
Returns the resultant transfer function obtained after evaluating
the transfer functions in series configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> Series(tf2, tf1).doit()
TransferFunction((s**3 - 2)*(a*p**2 + b*s), (-p + s)*(s**4 + 5*s + 6), s)
>>> Series(-tf1, -tf2).doit()
TransferFunction((2 - s**3)*(-a*p**2 - b*s), (-p + s)*(s**4 + 5*s + 6), s)
"""
_num_arg = (arg.doit().num for arg in self.args)
_den_arg = (arg.doit().den for arg in self.args)
res_num = Mul(*_num_arg, evaluate=True)
res_den = Mul(*_den_arg, evaluate=True)
return TransferFunction(res_num, res_den, self.var)
def _eval_rewrite_as_TransferFunction(self, *args, **kwargs):
return self.doit()
@_check_other_SISO
def __add__(self, other):
if isinstance(other, Parallel):
arg_list = list(other.args)
return Parallel(self, *arg_list)
return Parallel(self, other)
__radd__ = __add__
@_check_other_SISO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_SISO
def __mul__(self, other):
arg_list = list(self.args)
return Series(*arg_list, other)
def __truediv__(self, other):
if (isinstance(other, Parallel) and len(other.args) == 2
and isinstance(other.args[0], TransferFunction) and isinstance(other.args[1], Series)):
if not self.var == other.var:
raise ValueError("All the transfer functions should use the same complex variable "
"of the Laplace transform.")
self_arg_list = set(list(self.args))
other_arg_list = set(list(other.args[1].args))
res = list(self_arg_list ^ other_arg_list)
if len(res) == 0:
return Feedback(self, other.args[0])
elif len(res) == 1:
return Feedback(self, *res)
else:
return Feedback(self, Series(*res))
else:
raise ValueError("This transfer function expression is invalid.")
def __neg__(self):
return Series(TransferFunction(-1, 1, self.var), self)
def to_expr(self):
"""Returns the equivalent ``Expr`` object."""
return Mul(*(arg.to_expr() for arg in self.args), evaluate=False)
@property
def is_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is less than or equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
>>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*s + 2, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> S1 = Series(-tf2, tf1)
>>> S1.is_proper
False
>>> S2 = Series(tf1, tf2, tf3)
>>> S2.is_proper
True
"""
return self.doit().is_proper
@property
def is_strictly_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is strictly less than degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**2 + 5*s + 6, s)
>>> tf3 = TransferFunction(1, s**2 + s + 1, s)
>>> S1 = Series(tf1, tf2)
>>> S1.is_strictly_proper
False
>>> S2 = Series(tf1, tf2, tf3)
>>> S2.is_strictly_proper
True
"""
return self.doit().is_strictly_proper
@property
def is_biproper(self):
r"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(p, s**2, s)
>>> tf3 = TransferFunction(s**2, 1, s)
>>> S1 = Series(tf1, -tf2)
>>> S1.is_biproper
False
>>> S2 = Series(tf2, tf3)
>>> S2.is_biproper
True
"""
return self.doit().is_biproper
def _mat_mul_compatible(*args):
"""To check whether shapes are compatible for matrix mul."""
return all(args[i].num_outputs == args[i+1].num_inputs for i in range(len(args)-1))
class MIMOSeries(MIMOLinearTimeInvariant):
r"""
A class for representing a series configuration of MIMO systems.
Parameters
==========
args : MIMOLinearTimeInvariant
MIMO systems in a series configuration.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``MIMOSeries(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
``num_outputs`` of the MIMO system is not equal to the
``num_inputs`` of its adjacent MIMO system. (Matrix
multiplication constraint, basically)
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed, MIMO in this case.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import MIMOSeries, TransferFunctionMatrix
>>> from sympy import Matrix, pprint
>>> mat_a = Matrix([[5*s], [5]]) # 2 Outputs 1 Input
>>> mat_b = Matrix([[5, 1/(6*s**2)]]) # 1 Output 2 Inputs
>>> mat_c = Matrix([[1, s], [5/s, 1]]) # 2 Outputs 2 Inputs
>>> tfm_a = TransferFunctionMatrix.from_Matrix(mat_a, s)
>>> tfm_b = TransferFunctionMatrix.from_Matrix(mat_b, s)
>>> tfm_c = TransferFunctionMatrix.from_Matrix(mat_c, s)
>>> MIMOSeries(tfm_c, tfm_b, tfm_a)
MIMOSeries(TransferFunctionMatrix(((TransferFunction(1, 1, s), TransferFunction(s, 1, s)), (TransferFunction(5, s, s), TransferFunction(1, 1, s)))), TransferFunctionMatrix(((TransferFunction(5, 1, s), TransferFunction(1, 6*s**2, s)),)), TransferFunctionMatrix(((TransferFunction(5*s, 1, s),), (TransferFunction(5, 1, s),))))
>>> pprint(_, use_unicode=False) # For Better Visualization
[5*s] [1 s]
[---] [5 1 ] [- -]
[ 1 ] [- ----] [1 1]
[ ] *[1 2] *[ ]
[ 5 ] [ 6*s ]{t} [5 1]
[ - ] [- -]
[ 1 ]{t} [s 1]{t}
>>> MIMOSeries(tfm_c, tfm_b, tfm_a).doit()
TransferFunctionMatrix(((TransferFunction(150*s**4 + 25*s, 6*s**3, s), TransferFunction(150*s**4 + 5*s, 6*s**2, s)), (TransferFunction(150*s**3 + 25, 6*s**3, s), TransferFunction(150*s**3 + 5, 6*s**2, s))))
>>> pprint(_, use_unicode=False) # (2 Inputs -A-> 2 Outputs) -> (2 Inputs -B-> 1 Output) -> (1 Input -C-> 2 Outputs) is equivalent to (2 Inputs -Series Equivalent-> 2 Outputs).
[ 4 4 ]
[150*s + 25*s 150*s + 5*s]
[------------- ------------]
[ 3 2 ]
[ 6*s 6*s ]
[ ]
[ 3 3 ]
[ 150*s + 25 150*s + 5 ]
[ ----------- ---------- ]
[ 3 2 ]
[ 6*s 6*s ]{t}
Notes
=====
All the transfer function matrices should use the same complex variable ``var`` of the Laplace transform.
``MIMOSeries(A, B)`` is not equivalent to ``A*B``. It is always in the reverse order, that is ``B*A``.
See Also
========
Series, MIMOParallel
"""
def __new__(cls, *args, evaluate=False):
cls._check_args(args)
if _mat_mul_compatible(*args):
obj = super().__new__(cls, *args)
else:
raise ValueError("Number of input signals do not match the number"
" of output signals of adjacent systems for some args.")
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, MIMOSeries, TransferFunctionMatrix
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> tfm_1 = TransferFunctionMatrix([[G1, G2, G3]])
>>> tfm_2 = TransferFunctionMatrix([[G1], [G2], [G3]])
>>> MIMOSeries(tfm_2, tfm_1).var
p
"""
return self.args[0].var
@property
def num_inputs(self):
"""Returns the number of input signals of the series system."""
return self.args[0].num_inputs
@property
def num_outputs(self):
"""Returns the number of output signals of the series system."""
return self.args[-1].num_outputs
@property
def shape(self):
"""Returns the shape of the equivalent MIMO system."""
return self.num_outputs, self.num_inputs
def doit(self, cancel=False, **kwargs):
"""
Returns the resultant transfer function matrix obtained after evaluating
the MIMO systems arranged in a series configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, MIMOSeries, TransferFunctionMatrix
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tfm1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf2]])
>>> tfm2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf1]])
>>> MIMOSeries(tfm2, tfm1).doit()
TransferFunctionMatrix(((TransferFunction(2*(-p + s)*(s**3 - 2)*(a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)**2*(s**4 + 5*s + 6)**2, s), TransferFunction((-p + s)**2*(s**3 - 2)*(a*p**2 + b*s) + (-p + s)*(a*p**2 + b*s)**2*(s**4 + 5*s + 6), (-p + s)**3*(s**4 + 5*s + 6), s)), (TransferFunction((-p + s)*(s**3 - 2)**2*(s**4 + 5*s + 6) + (s**3 - 2)*(a*p**2 + b*s)*(s**4 + 5*s + 6)**2, (-p + s)*(s**4 + 5*s + 6)**3, s), TransferFunction(2*(s**3 - 2)*(a*p**2 + b*s), (-p + s)*(s**4 + 5*s + 6), s))))
"""
_arg = (arg.doit()._expr_mat for arg in reversed(self.args))
if cancel:
res = MatMul(*_arg, evaluate=True)
return TransferFunctionMatrix.from_Matrix(res, self.var)
_dummy_args, _dummy_dict = _dummify_args(_arg, self.var)
res = MatMul(*_dummy_args, evaluate=True)
temp_tfm = TransferFunctionMatrix.from_Matrix(res, self.var)
return temp_tfm.subs(_dummy_dict)
def _eval_rewrite_as_TransferFunctionMatrix(self, *args, **kwargs):
return self.doit()
@_check_other_MIMO
def __add__(self, other):
if isinstance(other, MIMOParallel):
arg_list = list(other.args)
return MIMOParallel(self, *arg_list)
return MIMOParallel(self, other)
__radd__ = __add__
@_check_other_MIMO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_MIMO
def __mul__(self, other):
if isinstance(other, MIMOSeries):
self_arg_list = list(self.args)
other_arg_list = list(other.args)
return MIMOSeries(*other_arg_list, *self_arg_list) # A*B = MIMOSeries(B, A)
arg_list = list(self.args)
return MIMOSeries(other, *arg_list)
def __neg__(self):
arg_list = list(self.args)
arg_list[0] = -arg_list[0]
return MIMOSeries(*arg_list)
class Parallel(SISOLinearTimeInvariant):
r"""
A class for representing a parallel configuration of SISO systems.
Parameters
==========
args : SISOLinearTimeInvariant
SISO systems in a parallel arrangement.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``Parallel(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel, Series
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf3 = TransferFunction(p**2, p + s, s)
>>> P1 = Parallel(tf1, tf2)
>>> P1
Parallel(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s))
>>> P1.var
s
>>> P2 = Parallel(tf2, Series(tf3, -tf1))
>>> P2
Parallel(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), Series(TransferFunction(p**2, p + s, s), TransferFunction(-a*p**2 - b*s, -p + s, s)))
>>> P2.var
s
>>> P3 = Parallel(Series(tf1, tf2), Series(tf2, tf3))
>>> P3
Parallel(Series(TransferFunction(a*p**2 + b*s, -p + s, s), TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)), Series(TransferFunction(s**3 - 2, s**4 + 5*s + 6, s), TransferFunction(p**2, p + s, s)))
>>> P3.var
s
You can get the resultant transfer function by using ``.doit()`` method:
>>> Parallel(tf1, tf2, -tf3).doit()
TransferFunction(-p**2*(-p + s)*(s**4 + 5*s + 6) + (-p + s)*(p + s)*(s**3 - 2) + (p + s)*(a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
>>> Parallel(tf2, Series(tf1, -tf3)).doit()
TransferFunction(-p**2*(a*p**2 + b*s)*(s**4 + 5*s + 6) + (-p + s)*(p + s)*(s**3 - 2), (-p + s)*(p + s)*(s**4 + 5*s + 6), s)
Notes
=====
All the transfer functions should use the same complex variable
``var`` of the Laplace transform.
See Also
========
Series, TransferFunction, Feedback
"""
def __new__(cls, *args, evaluate=False):
args = _flatten_args(args, Parallel)
cls._check_args(args)
obj = super().__new__(cls, *args)
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, Parallel, Series
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> Parallel(G1, G2).var
p
>>> Parallel(-G3, Series(G1, G2)).var
p
"""
return self.args[0].var
def doit(self, **kwargs):
"""
Returns the resultant transfer function obtained after evaluating
the transfer functions in parallel configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> Parallel(tf2, tf1).doit()
TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)
>>> Parallel(-tf1, -tf2).doit()
TransferFunction((2 - s**3)*(-p + s) + (-a*p**2 - b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)
"""
_arg = (arg.doit().to_expr() for arg in self.args)
res = Add(*_arg).as_numer_denom()
return TransferFunction(*res, self.var)
def _eval_rewrite_as_TransferFunction(self, *args, **kwargs):
return self.doit()
@_check_other_SISO
def __add__(self, other):
self_arg_list = list(self.args)
return Parallel(*self_arg_list, other)
__radd__ = __add__
@_check_other_SISO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_SISO
def __mul__(self, other):
if isinstance(other, Series):
arg_list = list(other.args)
return Series(self, *arg_list)
return Series(self, other)
def __neg__(self):
return Series(TransferFunction(-1, 1, self.var), self)
def to_expr(self):
"""Returns the equivalent ``Expr`` object."""
return Add(*(arg.to_expr() for arg in self.args), evaluate=False)
@property
def is_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is less than or equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
>>> tf2 = TransferFunction(p**2 - 4*p, p**3 + 3*s + 2, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(-tf2, tf1)
>>> P1.is_proper
False
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_proper
True
"""
return self.doit().is_proper
@property
def is_strictly_proper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is strictly less than degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(tf1, tf2)
>>> P1.is_strictly_proper
False
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_strictly_proper
True
"""
return self.doit().is_strictly_proper
@property
def is_biproper(self):
"""
Returns True if degree of the numerator polynomial of the resultant transfer
function is equal to degree of the denominator polynomial of
the same, else False.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, Parallel
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(p**2, p + s, s)
>>> tf3 = TransferFunction(s, s**2 + s + 1, s)
>>> P1 = Parallel(tf1, -tf2)
>>> P1.is_biproper
True
>>> P2 = Parallel(tf2, tf3)
>>> P2.is_biproper
False
"""
return self.doit().is_biproper
class MIMOParallel(MIMOLinearTimeInvariant):
r"""
A class for representing a parallel configuration of MIMO systems.
Parameters
==========
args : MIMOLinearTimeInvariant
MIMO Systems in a parallel arrangement.
evaluate : Boolean, Keyword
When passed ``True``, returns the equivalent
``MIMOParallel(*args).doit()``. Set to ``False`` by default.
Raises
======
ValueError
When no argument is passed.
``var`` attribute is not same for every system.
All MIMO systems passed do not have same shape.
TypeError
Any of the passed ``*args`` has unsupported type
A combination of SISO and MIMO systems is
passed. There should be homogeneity in the
type of systems passed, MIMO in this case.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix, MIMOParallel
>>> from sympy import Matrix, pprint
>>> expr_1 = 1/s
>>> expr_2 = s/(s**2-1)
>>> expr_3 = (2 + s)/(s**2 - 1)
>>> expr_4 = 5
>>> tfm_a = TransferFunctionMatrix.from_Matrix(Matrix([[expr_1, expr_2], [expr_3, expr_4]]), s)
>>> tfm_b = TransferFunctionMatrix.from_Matrix(Matrix([[expr_2, expr_1], [expr_4, expr_3]]), s)
>>> tfm_c = TransferFunctionMatrix.from_Matrix(Matrix([[expr_3, expr_4], [expr_1, expr_2]]), s)
>>> MIMOParallel(tfm_a, tfm_b, tfm_c)
MIMOParallel(TransferFunctionMatrix(((TransferFunction(1, s, s), TransferFunction(s, s**2 - 1, s)), (TransferFunction(s + 2, s**2 - 1, s), TransferFunction(5, 1, s)))), TransferFunctionMatrix(((TransferFunction(s, s**2 - 1, s), TransferFunction(1, s, s)), (TransferFunction(5, 1, s), TransferFunction(s + 2, s**2 - 1, s)))), TransferFunctionMatrix(((TransferFunction(s + 2, s**2 - 1, s), TransferFunction(5, 1, s)), (TransferFunction(1, s, s), TransferFunction(s, s**2 - 1, s)))))
>>> pprint(_, use_unicode=False) # For Better Visualization
[ 1 s ] [ s 1 ] [s + 2 5 ]
[ - ------] [------ - ] [------ - ]
[ s 2 ] [ 2 s ] [ 2 1 ]
[ s - 1] [s - 1 ] [s - 1 ]
[ ] + [ ] + [ ]
[s + 2 5 ] [ 5 s + 2 ] [ 1 s ]
[------ - ] [ - ------] [ - ------]
[ 2 1 ] [ 1 2 ] [ s 2 ]
[s - 1 ]{t} [ s - 1]{t} [ s - 1]{t}
>>> MIMOParallel(tfm_a, tfm_b, tfm_c).doit()
TransferFunctionMatrix(((TransferFunction(s**2 + s*(2*s + 2) - 1, s*(s**2 - 1), s), TransferFunction(2*s**2 + 5*s*(s**2 - 1) - 1, s*(s**2 - 1), s)), (TransferFunction(s**2 + s*(s + 2) + 5*s*(s**2 - 1) - 1, s*(s**2 - 1), s), TransferFunction(5*s**2 + 2*s - 3, s**2 - 1, s))))
>>> pprint(_, use_unicode=False)
[ 2 2 / 2 \ ]
[ s + s*(2*s + 2) - 1 2*s + 5*s*\s - 1/ - 1]
[ -------------------- -----------------------]
[ / 2 \ / 2 \ ]
[ s*\s - 1/ s*\s - 1/ ]
[ ]
[ 2 / 2 \ 2 ]
[s + s*(s + 2) + 5*s*\s - 1/ - 1 5*s + 2*s - 3 ]
[--------------------------------- -------------- ]
[ / 2 \ 2 ]
[ s*\s - 1/ s - 1 ]{t}
Notes
=====
All the transfer function matrices should use the same complex variable
``var`` of the Laplace transform.
See Also
========
Parallel, MIMOSeries
"""
def __new__(cls, *args, evaluate=False):
args = _flatten_args(args, MIMOParallel)
cls._check_args(args)
if any(arg.shape != args[0].shape for arg in args):
raise TypeError("Shape of all the args is not equal.")
obj = super().__new__(cls, *args)
return obj.doit() if evaluate else obj
@property
def var(self):
"""
Returns the complex variable used by all the systems.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOParallel
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> G4 = TransferFunction(p**2, p**2 - 1, p)
>>> tfm_a = TransferFunctionMatrix([[G1, G2], [G3, G4]])
>>> tfm_b = TransferFunctionMatrix([[G2, G1], [G4, G3]])
>>> MIMOParallel(tfm_a, tfm_b).var
p
"""
return self.args[0].var
@property
def num_inputs(self):
"""Returns the number of input signals of the parallel system."""
return self.args[0].num_inputs
@property
def num_outputs(self):
"""Returns the number of output signals of the parallel system."""
return self.args[0].num_outputs
@property
def shape(self):
"""Returns the shape of the equivalent MIMO system."""
return self.num_outputs, self.num_inputs
def doit(self, **kwargs):
"""
Returns the resultant transfer function matrix obtained after evaluating
the MIMO systems arranged in a parallel configuration.
Examples
========
>>> from sympy.abc import s, p, a, b
>>> from sympy.physics.control.lti import TransferFunction, MIMOParallel, TransferFunctionMatrix
>>> tf1 = TransferFunction(a*p**2 + b*s, s - p, s)
>>> tf2 = TransferFunction(s**3 - 2, s**4 + 5*s + 6, s)
>>> tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> tfm_2 = TransferFunctionMatrix([[tf2, tf1], [tf1, tf2]])
>>> MIMOParallel(tfm_1, tfm_2).doit()
TransferFunctionMatrix(((TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s), TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s)), (TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s), TransferFunction((-p + s)*(s**3 - 2) + (a*p**2 + b*s)*(s**4 + 5*s + 6), (-p + s)*(s**4 + 5*s + 6), s))))
"""
_arg = (arg.doit()._expr_mat for arg in self.args)
res = MatAdd(*_arg, evaluate=True)
return TransferFunctionMatrix.from_Matrix(res, self.var)
def _eval_rewrite_as_TransferFunctionMatrix(self, *args, **kwargs):
return self.doit()
@_check_other_MIMO
def __add__(self, other):
self_arg_list = list(self.args)
return MIMOParallel(*self_arg_list, other)
__radd__ = __add__
@_check_other_MIMO
def __sub__(self, other):
return self + (-other)
def __rsub__(self, other):
return -self + other
@_check_other_MIMO
def __mul__(self, other):
if isinstance(other, MIMOSeries):
arg_list = list(other.args)
return MIMOSeries(*arg_list, self)
return MIMOSeries(other, self)
def __neg__(self):
arg_list = [-arg for arg in list(self.args)]
return MIMOParallel(*arg_list)
class Feedback(SISOLinearTimeInvariant):
r"""
A class for representing closed-loop feedback interconnection between two
SISO input/output systems.
The first argument, ``sys1``, is the feedforward part of the closed-loop
system or in simple words, the dynamical model representing the process
to be controlled. The second argument, ``sys2``, is the feedback system
and controls the fed back signal to ``sys1``. Both ``sys1`` and ``sys2``
can either be ``Series`` or ``TransferFunction`` objects.
Parameters
==========
sys1 : Series, TransferFunction
The feedforward path system.
sys2 : Series, TransferFunction, optional
The feedback path system (often a feedback controller).
It is the model sitting on the feedback path.
If not specified explicitly, the sys2 is
assumed to be unit (1.0) transfer function.
sign : int, optional
The sign of feedback. Can either be ``1``
(for positive feedback) or ``-1`` (for negative feedback).
Default value is `-1`.
Raises
======
ValueError
When ``sys1`` and ``sys2`` are not using the
same complex variable of the Laplace transform.
When a combination of ``sys1`` and ``sys2`` yields
zero denominator.
TypeError
When either ``sys1`` or ``sys2`` is not a ``Series`` or a
``TransferFunction`` object.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1
Feedback(TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s), TransferFunction(5*s - 10, s + 7, s), -1)
>>> F1.var
s
>>> F1.args
(TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s), TransferFunction(5*s - 10, s + 7, s), -1)
You can get the feedforward and feedback path systems by using ``.sys1`` and ``.sys2`` respectively.
>>> F1.sys1
TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> F1.sys2
TransferFunction(5*s - 10, s + 7, s)
You can get the resultant closed loop transfer function obtained by negative feedback
interconnection using ``.doit()`` method.
>>> F1.doit()
TransferFunction((s + 7)*(s**2 - 4*s + 2)*(3*s**2 + 7*s - 3), ((s + 7)*(s**2 - 4*s + 2) + (5*s - 10)*(3*s**2 + 7*s - 3))*(s**2 - 4*s + 2), s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s)
>>> C = TransferFunction(5*s + 10, s + 10, s)
>>> F2 = Feedback(G*C, TransferFunction(1, 1, s))
>>> F2.doit()
TransferFunction((s + 10)*(5*s + 10)*(s**2 + 2*s + 3)*(2*s**2 + 5*s + 1), (s + 10)*((s + 10)*(s**2 + 2*s + 3) + (5*s + 10)*(2*s**2 + 5*s + 1))*(s**2 + 2*s + 3), s)
To negate a ``Feedback`` object, the ``-`` operator can be prepended:
>>> -F1
Feedback(TransferFunction(-3*s**2 - 7*s + 3, s**2 - 4*s + 2, s), TransferFunction(10 - 5*s, s + 7, s), -1)
>>> -F2
Feedback(Series(TransferFunction(-1, 1, s), TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s), TransferFunction(5*s + 10, s + 10, s)), TransferFunction(-1, 1, s), -1)
See Also
========
MIMOFeedback, Series, Parallel
"""
def __new__(cls, sys1, sys2=None, sign=-1):
if not sys2:
sys2 = TransferFunction(1, 1, sys1.var)
if not (isinstance(sys1, (TransferFunction, Series))
and isinstance(sys2, (TransferFunction, Series))):
raise TypeError("Unsupported type for `sys1` or `sys2` of Feedback.")
if sign not in [-1, 1]:
raise ValueError("Unsupported type for feedback. `sign` arg should "
"either be 1 (positive feedback loop) or -1 (negative feedback loop).")
if Mul(sys1.to_expr(), sys2.to_expr()).simplify() == sign:
raise ValueError("The equivalent system will have zero denominator.")
if sys1.var != sys2.var:
raise ValueError("Both `sys1` and `sys2` should be using the"
" same complex variable.")
return super().__new__(cls, sys1, sys2, _sympify(sign))
@property
def sys1(self):
"""
Returns the feedforward system of the feedback interconnection.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.sys1
TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p)
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - s, p + 2, p)
>>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P)
>>> F2.sys1
TransferFunction(1, 1, p)
"""
return self.args[0]
@property
def sys2(self):
"""
Returns the feedback controller of the feedback interconnection.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.sys2
TransferFunction(5*s - 10, s + 7, s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p)
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - s, p + 2, p)
>>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P)
>>> F2.sys2
Series(TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p), TransferFunction(5*p + 10, p + 10, p), TransferFunction(1 - s, p + 2, p))
"""
return self.args[1]
@property
def var(self):
"""
Returns the complex variable of the Laplace transform used by all
the transfer functions involved in the feedback interconnection.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.var
s
>>> G = TransferFunction(2*s**2 + 5*s + 1, p**2 + 2*p + 3, p)
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - s, p + 2, p)
>>> F2 = Feedback(TransferFunction(1, 1, p), G*C*P)
>>> F2.var
p
"""
return self.sys1.var
@property
def sign(self):
"""
Returns the type of MIMO Feedback model. ``1``
for Positive and ``-1`` for Negative.
"""
return self.args[2]
@property
def sensitivity(self):
"""
Returns the sensitivity function of the feedback loop.
Sensitivity of a Feedback system is the ratio
of change in the open loop gain to the change in
the closed loop gain.
.. note::
This method would not return the complementary
sensitivity function.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> C = TransferFunction(5*p + 10, p + 10, p)
>>> P = TransferFunction(1 - p, p + 2, p)
>>> F_1 = Feedback(P, C)
>>> F_1.sensitivity
1/((1 - p)*(5*p + 10)/((p + 2)*(p + 10)) + 1)
"""
return 1/(1 - self.sign*self.sys1.to_expr()*self.sys2.to_expr())
def doit(self, cancel=False, expand=False, **kwargs):
"""
Returns the resultant transfer function obtained by the
feedback interconnection.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, Feedback
>>> plant = TransferFunction(3*s**2 + 7*s - 3, s**2 - 4*s + 2, s)
>>> controller = TransferFunction(5*s - 10, s + 7, s)
>>> F1 = Feedback(plant, controller)
>>> F1.doit()
TransferFunction((s + 7)*(s**2 - 4*s + 2)*(3*s**2 + 7*s - 3), ((s + 7)*(s**2 - 4*s + 2) + (5*s - 10)*(3*s**2 + 7*s - 3))*(s**2 - 4*s + 2), s)
>>> G = TransferFunction(2*s**2 + 5*s + 1, s**2 + 2*s + 3, s)
>>> F2 = Feedback(G, TransferFunction(1, 1, s))
>>> F2.doit()
TransferFunction((s**2 + 2*s + 3)*(2*s**2 + 5*s + 1), (s**2 + 2*s + 3)*(3*s**2 + 7*s + 4), s)
Use kwarg ``expand=True`` to expand the resultant transfer function.
Use ``cancel=True`` to cancel out the common terms in numerator and
denominator.
>>> F2.doit(cancel=True, expand=True)
TransferFunction(2*s**2 + 5*s + 1, 3*s**2 + 7*s + 4, s)
>>> F2.doit(expand=True)
TransferFunction(2*s**4 + 9*s**3 + 17*s**2 + 17*s + 3, 3*s**4 + 13*s**3 + 27*s**2 + 29*s + 12, s)
"""
arg_list = list(self.sys1.args) if isinstance(self.sys1, Series) else [self.sys1]
# F_n and F_d are resultant TFs of num and den of Feedback.
F_n, unit = self.sys1.doit(), TransferFunction(1, 1, self.sys1.var)
if self.sign == -1:
F_d = Parallel(unit, Series(self.sys2, *arg_list)).doit()
else:
F_d = Parallel(unit, -Series(self.sys2, *arg_list)).doit()
_resultant_tf = TransferFunction(F_n.num * F_d.den, F_n.den * F_d.num, F_n.var)
if cancel:
_resultant_tf = _resultant_tf.simplify()
if expand:
_resultant_tf = _resultant_tf.expand()
return _resultant_tf
def _eval_rewrite_as_TransferFunction(self, num, den, sign, **kwargs):
return self.doit()
def __neg__(self):
return Feedback(-self.sys1, -self.sys2, self.sign)
def _is_invertible(a, b, sign):
"""
Checks whether a given pair of MIMO
systems passed is invertible or not.
"""
_mat = eye(a.num_outputs) - sign*(a.doit()._expr_mat)*(b.doit()._expr_mat)
_det = _mat.det()
return _det != 0
class MIMOFeedback(MIMOLinearTimeInvariant):
r"""
A class for representing closed-loop feedback interconnection between two
MIMO input/output systems.
Parameters
==========
sys1 : MIMOSeries, TransferFunctionMatrix
The MIMO system placed on the feedforward path.
sys2 : MIMOSeries, TransferFunctionMatrix
The system placed on the feedback path
(often a feedback controller).
sign : int, optional
The sign of feedback. Can either be ``1``
(for positive feedback) or ``-1`` (for negative feedback).
Default value is `-1`.
Raises
======
ValueError
When ``sys1`` and ``sys2`` are not using the
same complex variable of the Laplace transform.
Forward path model should have an equal number of inputs/outputs
to the feedback path outputs/inputs.
When product of ``sys1`` and ``sys2`` is not a square matrix.
When the equivalent MIMO system is not invertible.
TypeError
When either ``sys1`` or ``sys2`` is not a ``MIMOSeries`` or a
``TransferFunctionMatrix`` object.
Examples
========
>>> from sympy import Matrix, pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix, MIMOFeedback
>>> plant_mat = Matrix([[1, 1/s], [0, 1]])
>>> controller_mat = Matrix([[10, 0], [0, 10]]) # Constant Gain
>>> plant = TransferFunctionMatrix.from_Matrix(plant_mat, s)
>>> controller = TransferFunctionMatrix.from_Matrix(controller_mat, s)
>>> feedback = MIMOFeedback(plant, controller) # Negative Feedback (default)
>>> pprint(feedback, use_unicode=False)
/ [1 1] [10 0 ] \-1 [1 1]
| [- -] [-- - ] | [- -]
| [1 s] [1 1 ] | [1 s]
|I + [ ] *[ ] | * [ ]
| [0 1] [0 10] | [0 1]
| [- -] [- --] | [- -]
\ [1 1]{t} [1 1 ]{t}/ [1 1]{t}
To get the equivalent system matrix, use either ``doit`` or ``rewrite`` method.
>>> pprint(feedback.doit(), use_unicode=False)
[1 1 ]
[-- -----]
[11 121*s]
[ ]
[0 1 ]
[- -- ]
[1 11 ]{t}
To negate the ``MIMOFeedback`` object, use ``-`` operator.
>>> neg_feedback = -feedback
>>> pprint(neg_feedback.doit(), use_unicode=False)
[-1 -1 ]
[--- -----]
[ 11 121*s]
[ ]
[ 0 -1 ]
[ - --- ]
[ 1 11 ]{t}
See Also
========
Feedback, MIMOSeries, MIMOParallel
"""
def __new__(cls, sys1, sys2, sign=-1):
if not (isinstance(sys1, (TransferFunctionMatrix, MIMOSeries))
and isinstance(sys2, (TransferFunctionMatrix, MIMOSeries))):
raise TypeError("Unsupported type for `sys1` or `sys2` of MIMO Feedback.")
if sys1.num_inputs != sys2.num_outputs or \
sys1.num_outputs != sys2.num_inputs:
raise ValueError("Product of `sys1` and `sys2` "
"must yield a square matrix.")
if sign not in [-1, 1]:
raise ValueError("Unsupported type for feedback. `sign` arg should "
"either be 1 (positive feedback loop) or -1 (negative feedback loop).")
if not _is_invertible(sys1, sys2, sign):
raise ValueError("Non-Invertible system inputted.")
if sys1.var != sys2.var:
raise ValueError("Both `sys1` and `sys2` should be using the"
" same complex variable.")
return super().__new__(cls, sys1, sys2, _sympify(sign))
@property
def sys1(self):
r"""
Returns the system placed on the feedforward path of the MIMO feedback interconnection.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(s**2 + s + 1, s**2 - s + 1, s)
>>> tf2 = TransferFunction(1, s, s)
>>> tf3 = TransferFunction(1, 1, s)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf3, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1)
>>> F_1.sys1
TransferFunctionMatrix(((TransferFunction(s**2 + s + 1, s**2 - s + 1, s), TransferFunction(1, s, s)), (TransferFunction(1, s, s), TransferFunction(s**2 + s + 1, s**2 - s + 1, s))))
>>> pprint(_, use_unicode=False)
[ 2 ]
[s + s + 1 1 ]
[---------- - ]
[ 2 s ]
[s - s + 1 ]
[ ]
[ 2 ]
[ 1 s + s + 1]
[ - ----------]
[ s 2 ]
[ s - s + 1]{t}
"""
return self.args[0]
@property
def sys2(self):
r"""
Returns the feedback controller of the MIMO feedback interconnection.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(s**2, s**3 - s + 1, s)
>>> tf2 = TransferFunction(1, s, s)
>>> tf3 = TransferFunction(1, 1, s)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2)
>>> F_1.sys2
TransferFunctionMatrix(((TransferFunction(s**2, s**3 - s + 1, s), TransferFunction(1, 1, s)), (TransferFunction(1, 1, s), TransferFunction(1, s, s))))
>>> pprint(_, use_unicode=False)
[ 2 ]
[ s 1]
[---------- -]
[ 3 1]
[s - s + 1 ]
[ ]
[ 1 1]
[ - -]
[ 1 s]{t}
"""
return self.args[1]
@property
def var(self):
r"""
Returns the complex variable of the Laplace transform used by all
the transfer functions involved in the MIMO feedback loop.
Examples
========
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(p, 1 - p, p)
>>> tf2 = TransferFunction(1, p, p)
>>> tf3 = TransferFunction(1, 1, p)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1) # Positive feedback
>>> F_1.var
p
"""
return self.sys1.var
@property
def sign(self):
r"""
Returns the type of feedback interconnection of two models. ``1``
for Positive and ``-1`` for Negative.
"""
return self.args[2]
@property
def sensitivity(self):
r"""
Returns the sensitivity function matrix of the feedback loop.
Sensitivity of a closed-loop system is the ratio of change
in the open loop gain to the change in the closed loop gain.
.. note::
This method would not return the complementary
sensitivity function.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(p, 1 - p, p)
>>> tf2 = TransferFunction(1, p, p)
>>> tf3 = TransferFunction(1, 1, p)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf2, tf1]])
>>> sys2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf2]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1) # Positive feedback
>>> F_2 = MIMOFeedback(sys1, sys2) # Negative feedback
>>> pprint(F_1.sensitivity, use_unicode=False)
[ 4 3 2 5 4 2 ]
[- p + 3*p - 4*p + 3*p - 1 p - 2*p + 3*p - 3*p + 1 ]
[---------------------------- -----------------------------]
[ 4 3 2 5 4 3 2 ]
[ p + 3*p - 8*p + 8*p - 3 p + 3*p - 8*p + 8*p - 3*p]
[ ]
[ 4 3 2 3 2 ]
[ p - p - p + p 3*p - 6*p + 4*p - 1 ]
[ -------------------------- -------------------------- ]
[ 4 3 2 4 3 2 ]
[ p + 3*p - 8*p + 8*p - 3 p + 3*p - 8*p + 8*p - 3 ]
>>> pprint(F_2.sensitivity, use_unicode=False)
[ 4 3 2 5 4 2 ]
[p - 3*p + 2*p + p - 1 p - 2*p + 3*p - 3*p + 1]
[------------------------ --------------------------]
[ 4 3 5 4 2 ]
[ p - 3*p + 2*p - 1 p - 3*p + 2*p - p ]
[ ]
[ 4 3 2 4 3 ]
[ p - p - p + p 2*p - 3*p + 2*p - 1 ]
[ ------------------- --------------------- ]
[ 4 3 4 3 ]
[ p - 3*p + 2*p - 1 p - 3*p + 2*p - 1 ]
"""
_sys1_mat = self.sys1.doit()._expr_mat
_sys2_mat = self.sys2.doit()._expr_mat
return (eye(self.sys1.num_inputs) - \
self.sign*_sys1_mat*_sys2_mat).inv()
def doit(self, cancel=True, expand=False, **kwargs):
r"""
Returns the resultant transfer function matrix obtained by the
feedback interconnection.
Examples
========
>>> from sympy import pprint
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, MIMOFeedback
>>> tf1 = TransferFunction(s, 1 - s, s)
>>> tf2 = TransferFunction(1, s, s)
>>> tf3 = TransferFunction(5, 1, s)
>>> tf4 = TransferFunction(s - 1, s, s)
>>> tf5 = TransferFunction(0, 1, s)
>>> sys1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
>>> sys2 = TransferFunctionMatrix([[tf3, tf5], [tf5, tf5]])
>>> F_1 = MIMOFeedback(sys1, sys2, 1)
>>> pprint(F_1, use_unicode=False)
/ [ s 1 ] [5 0] \-1 [ s 1 ]
| [----- - ] [- -] | [----- - ]
| [1 - s s ] [1 1] | [1 - s s ]
|I - [ ] *[ ] | * [ ]
| [ 5 s - 1] [0 0] | [ 5 s - 1]
| [ - -----] [- -] | [ - -----]
\ [ 1 s ]{t} [1 1]{t}/ [ 1 s ]{t}
>>> pprint(F_1.doit(), use_unicode=False)
[ -s s - 1 ]
[------- ----------- ]
[6*s - 1 s*(6*s - 1) ]
[ ]
[5*s - 5 (s - 1)*(6*s + 24)]
[------- ------------------]
[6*s - 1 s*(6*s - 1) ]{t}
If the user wants the resultant ``TransferFunctionMatrix`` object without
canceling the common factors then the ``cancel`` kwarg should be passed ``False``.
>>> pprint(F_1.doit(cancel=False), use_unicode=False)
[ 25*s*(1 - s) 25 - 25*s ]
[ -------------------- -------------- ]
[ 25*(1 - 6*s)*(1 - s) 25*s*(1 - 6*s) ]
[ ]
[s*(25*s - 25) + 5*(1 - s)*(6*s - 1) s*(s - 1)*(6*s - 1) + s*(25*s - 25)]
[----------------------------------- -----------------------------------]
[ (1 - s)*(6*s - 1) 2 ]
[ s *(6*s - 1) ]{t}
If the user wants the expanded form of the resultant transfer function matrix,
the ``expand`` kwarg should be passed as ``True``.
>>> pprint(F_1.doit(expand=True), use_unicode=False)
[ -s s - 1 ]
[------- -------- ]
[6*s - 1 2 ]
[ 6*s - s ]
[ ]
[ 2 ]
[5*s - 5 6*s + 18*s - 24]
[------- ----------------]
[6*s - 1 2 ]
[ 6*s - s ]{t}
"""
_mat = self.sensitivity * self.sys1.doit()._expr_mat
_resultant_tfm = _to_TFM(_mat, self.var)
if cancel:
_resultant_tfm = _resultant_tfm.simplify()
if expand:
_resultant_tfm = _resultant_tfm.expand()
return _resultant_tfm
def _eval_rewrite_as_TransferFunctionMatrix(self, sys1, sys2, sign, **kwargs):
return self.doit()
def __neg__(self):
return MIMOFeedback(-self.sys1, -self.sys2, self.sign)
def _to_TFM(mat, var):
"""Private method to convert ImmutableMatrix to TransferFunctionMatrix efficiently"""
to_tf = lambda expr: TransferFunction.from_rational_expression(expr, var)
arg = [[to_tf(expr) for expr in row] for row in mat.tolist()]
return TransferFunctionMatrix(arg)
class TransferFunctionMatrix(MIMOLinearTimeInvariant):
r"""
A class for representing the MIMO (multiple-input and multiple-output)
generalization of the SISO (single-input and single-output) transfer function.
It is a matrix of transfer functions (``TransferFunction``, SISO-``Series`` or SISO-``Parallel``).
There is only one argument, ``arg`` which is also the compulsory argument.
``arg`` is expected to be strictly of the type list of lists
which holds the transfer functions or reducible to transfer functions.
Parameters
==========
arg : Nested ``List`` (strictly).
Users are expected to input a nested list of ``TransferFunction``, ``Series``
and/or ``Parallel`` objects.
Examples
========
.. note::
``pprint()`` can be used for better visualization of ``TransferFunctionMatrix`` objects.
>>> from sympy.abc import s, p, a
>>> from sympy import pprint
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, Series, Parallel
>>> tf_1 = TransferFunction(s + a, s**2 + s + 1, s)
>>> tf_2 = TransferFunction(p**4 - 3*p + 2, s + p, s)
>>> tf_3 = TransferFunction(3, s + 2, s)
>>> tf_4 = TransferFunction(-a + p, 9*s - 9, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1], [tf_2], [tf_3]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(3, s + 2, s),)))
>>> tfm_1.var
s
>>> tfm_1.num_inputs
1
>>> tfm_1.num_outputs
3
>>> tfm_1.shape
(3, 1)
>>> tfm_1.args
(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(3, s + 2, s),)),)
>>> tfm_2 = TransferFunctionMatrix([[tf_1, -tf_3], [tf_2, -tf_1], [tf_3, -tf_2]])
>>> tfm_2
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(p**4 - 3*p + 2, p + s, s), TransferFunction(-a - s, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-p**4 + 3*p - 2, p + s, s))))
>>> pprint(tfm_2, use_unicode=False) # pretty-printing for better visualization
[ a + s -3 ]
[ ---------- ----- ]
[ 2 s + 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[p - 3*p + 2 -a - s ]
[------------ ---------- ]
[ p + s 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[ 3 - p + 3*p - 2]
[ ----- --------------]
[ s + 2 p + s ]{t}
TransferFunctionMatrix can be transposed, if user wants to switch the input and output transfer functions
>>> tfm_2.transpose()
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(p**4 - 3*p + 2, p + s, s), TransferFunction(3, s + 2, s)), (TransferFunction(-3, s + 2, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(-p**4 + 3*p - 2, p + s, s))))
>>> pprint(_, use_unicode=False)
[ 4 ]
[ a + s p - 3*p + 2 3 ]
[---------- ------------ ----- ]
[ 2 p + s s + 2 ]
[s + s + 1 ]
[ ]
[ 4 ]
[ -3 -a - s - p + 3*p - 2]
[ ----- ---------- --------------]
[ s + 2 2 p + s ]
[ s + s + 1 ]{t}
>>> tf_5 = TransferFunction(5, s, s)
>>> tf_6 = TransferFunction(5*s, (2 + s**2), s)
>>> tf_7 = TransferFunction(5, (s*(2 + s**2)), s)
>>> tf_8 = TransferFunction(5, 1, s)
>>> tfm_3 = TransferFunctionMatrix([[tf_5, tf_6], [tf_7, tf_8]])
>>> tfm_3
TransferFunctionMatrix(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)), (TransferFunction(5, s*(s**2 + 2), s), TransferFunction(5, 1, s))))
>>> pprint(tfm_3, use_unicode=False)
[ 5 5*s ]
[ - ------]
[ s 2 ]
[ s + 2]
[ ]
[ 5 5 ]
[---------- - ]
[ / 2 \ 1 ]
[s*\s + 2/ ]{t}
>>> tfm_3.var
s
>>> tfm_3.shape
(2, 2)
>>> tfm_3.num_outputs
2
>>> tfm_3.num_inputs
2
>>> tfm_3.args
(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)), (TransferFunction(5, s*(s**2 + 2), s), TransferFunction(5, 1, s))),)
To access the ``TransferFunction`` at any index in the ``TransferFunctionMatrix``, use the index notation.
>>> tfm_3[1, 0] # gives the TransferFunction present at 2nd Row and 1st Col. Similar to that in Matrix classes
TransferFunction(5, s*(s**2 + 2), s)
>>> tfm_3[0, 0] # gives the TransferFunction present at 1st Row and 1st Col.
TransferFunction(5, s, s)
>>> tfm_3[:, 0] # gives the first column
TransferFunctionMatrix(((TransferFunction(5, s, s),), (TransferFunction(5, s*(s**2 + 2), s),)))
>>> pprint(_, use_unicode=False)
[ 5 ]
[ - ]
[ s ]
[ ]
[ 5 ]
[----------]
[ / 2 \]
[s*\s + 2/]{t}
>>> tfm_3[0, :] # gives the first row
TransferFunctionMatrix(((TransferFunction(5, s, s), TransferFunction(5*s, s**2 + 2, s)),))
>>> pprint(_, use_unicode=False)
[5 5*s ]
[- ------]
[s 2 ]
[ s + 2]{t}
To negate a transfer function matrix, ``-`` operator can be prepended:
>>> tfm_4 = TransferFunctionMatrix([[tf_2], [-tf_1], [tf_3]])
>>> -tfm_4
TransferFunctionMatrix(((TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(-3, s + 2, s),)))
>>> tfm_5 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, -tf_1]])
>>> -tfm_5
TransferFunctionMatrix(((TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(-p**4 + 3*p - 2, p + s, s)), (TransferFunction(-3, s + 2, s), TransferFunction(a + s, s**2 + s + 1, s))))
``subs()`` returns the ``TransferFunctionMatrix`` object with the value substituted in the expression. This will not
mutate your original ``TransferFunctionMatrix``.
>>> tfm_2.subs(p, 2) # substituting p everywhere in tfm_2 with 2.
TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(12, s + 2, s), TransferFunction(-a - s, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-12, s + 2, s))))
>>> pprint(_, use_unicode=False)
[ a + s -3 ]
[---------- ----- ]
[ 2 s + 2 ]
[s + s + 1 ]
[ ]
[ 12 -a - s ]
[ ----- ----------]
[ s + 2 2 ]
[ s + s + 1]
[ ]
[ 3 -12 ]
[ ----- ----- ]
[ s + 2 s + 2 ]{t}
>>> pprint(tfm_2, use_unicode=False) # State of tfm_2 is unchanged after substitution
[ a + s -3 ]
[ ---------- ----- ]
[ 2 s + 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[p - 3*p + 2 -a - s ]
[------------ ---------- ]
[ p + s 2 ]
[ s + s + 1 ]
[ ]
[ 4 ]
[ 3 - p + 3*p - 2]
[ ----- --------------]
[ s + 2 p + s ]{t}
``subs()`` also supports multiple substitutions.
>>> tfm_2.subs({p: 2, a: 1}) # substituting p with 2 and a with 1
TransferFunctionMatrix(((TransferFunction(s + 1, s**2 + s + 1, s), TransferFunction(-3, s + 2, s)), (TransferFunction(12, s + 2, s), TransferFunction(-s - 1, s**2 + s + 1, s)), (TransferFunction(3, s + 2, s), TransferFunction(-12, s + 2, s))))
>>> pprint(_, use_unicode=False)
[ s + 1 -3 ]
[---------- ----- ]
[ 2 s + 2 ]
[s + s + 1 ]
[ ]
[ 12 -s - 1 ]
[ ----- ----------]
[ s + 2 2 ]
[ s + s + 1]
[ ]
[ 3 -12 ]
[ ----- ----- ]
[ s + 2 s + 2 ]{t}
Users can reduce the ``Series`` and ``Parallel`` elements of the matrix to ``TransferFunction`` by using
``doit()``.
>>> tfm_6 = TransferFunctionMatrix([[Series(tf_3, tf_4), Parallel(tf_3, tf_4)]])
>>> tfm_6
TransferFunctionMatrix(((Series(TransferFunction(3, s + 2, s), TransferFunction(-a + p, 9*s - 9, s)), Parallel(TransferFunction(3, s + 2, s), TransferFunction(-a + p, 9*s - 9, s))),))
>>> pprint(tfm_6, use_unicode=False)
[ -a + p 3 -a + p 3 ]
[-------*----- ------- + -----]
[9*s - 9 s + 2 9*s - 9 s + 2]{t}
>>> tfm_6.doit()
TransferFunctionMatrix(((TransferFunction(-3*a + 3*p, (s + 2)*(9*s - 9), s), TransferFunction(27*s + (-a + p)*(s + 2) - 27, (s + 2)*(9*s - 9), s)),))
>>> pprint(_, use_unicode=False)
[ -3*a + 3*p 27*s + (-a + p)*(s + 2) - 27]
[----------------- ----------------------------]
[(s + 2)*(9*s - 9) (s + 2)*(9*s - 9) ]{t}
>>> tf_9 = TransferFunction(1, s, s)
>>> tf_10 = TransferFunction(1, s**2, s)
>>> tfm_7 = TransferFunctionMatrix([[Series(tf_9, tf_10), tf_9], [tf_10, Parallel(tf_9, tf_10)]])
>>> tfm_7
TransferFunctionMatrix(((Series(TransferFunction(1, s, s), TransferFunction(1, s**2, s)), TransferFunction(1, s, s)), (TransferFunction(1, s**2, s), Parallel(TransferFunction(1, s, s), TransferFunction(1, s**2, s)))))
>>> pprint(tfm_7, use_unicode=False)
[ 1 1 ]
[---- - ]
[ 2 s ]
[s*s ]
[ ]
[ 1 1 1]
[ -- -- + -]
[ 2 2 s]
[ s s ]{t}
>>> tfm_7.doit()
TransferFunctionMatrix(((TransferFunction(1, s**3, s), TransferFunction(1, s, s)), (TransferFunction(1, s**2, s), TransferFunction(s**2 + s, s**3, s))))
>>> pprint(_, use_unicode=False)
[1 1 ]
[-- - ]
[ 3 s ]
[s ]
[ ]
[ 2 ]
[1 s + s]
[-- ------]
[ 2 3 ]
[s s ]{t}
Addition, subtraction, and multiplication of transfer function matrices can form
unevaluated ``Series`` or ``Parallel`` objects.
- For addition and subtraction:
All the transfer function matrices must have the same shape.
- For multiplication (C = A * B):
The number of inputs of the first transfer function matrix (A) must be equal to the
number of outputs of the second transfer function matrix (B).
Also, use pretty-printing (``pprint``) to analyse better.
>>> tfm_8 = TransferFunctionMatrix([[tf_3], [tf_2], [-tf_1]])
>>> tfm_9 = TransferFunctionMatrix([[-tf_3]])
>>> tfm_10 = TransferFunctionMatrix([[tf_1], [tf_2], [tf_4]])
>>> tfm_11 = TransferFunctionMatrix([[tf_4], [-tf_1]])
>>> tfm_12 = TransferFunctionMatrix([[tf_4, -tf_1, tf_3], [-tf_2, -tf_4, -tf_3]])
>>> tfm_8 + tfm_10
MIMOParallel(TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a + p, 9*s - 9, s),))))
>>> pprint(_, use_unicode=False)
[ 3 ] [ a + s ]
[ ----- ] [ ---------- ]
[ s + 2 ] [ 2 ]
[ ] [ s + s + 1 ]
[ 4 ] [ ]
[p - 3*p + 2] [ 4 ]
[------------] + [p - 3*p + 2]
[ p + s ] [------------]
[ ] [ p + s ]
[ -a - s ] [ ]
[ ---------- ] [ -a + p ]
[ 2 ] [ ------- ]
[ s + s + 1 ]{t} [ 9*s - 9 ]{t}
>>> -tfm_10 - tfm_8
MIMOParallel(TransferFunctionMatrix(((TransferFunction(-a - s, s**2 + s + 1, s),), (TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a - p, 9*s - 9, s),))), TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),), (TransferFunction(-p**4 + 3*p - 2, p + s, s),), (TransferFunction(a + s, s**2 + s + 1, s),))))
>>> pprint(_, use_unicode=False)
[ -a - s ] [ -3 ]
[ ---------- ] [ ----- ]
[ 2 ] [ s + 2 ]
[ s + s + 1 ] [ ]
[ ] [ 4 ]
[ 4 ] [- p + 3*p - 2]
[- p + 3*p - 2] + [--------------]
[--------------] [ p + s ]
[ p + s ] [ ]
[ ] [ a + s ]
[ a - p ] [ ---------- ]
[ ------- ] [ 2 ]
[ 9*s - 9 ]{t} [ s + s + 1 ]{t}
>>> tfm_12 * tfm_8
MIMOSeries(TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(-a + p, 9*s - 9, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(3, s + 2, s)), (TransferFunction(-p**4 + 3*p - 2, p + s, s), TransferFunction(a - p, 9*s - 9, s), TransferFunction(-3, s + 2, s)))))
>>> pprint(_, use_unicode=False)
[ 3 ]
[ ----- ]
[ -a + p -a - s 3 ] [ s + 2 ]
[ ------- ---------- -----] [ ]
[ 9*s - 9 2 s + 2] [ 4 ]
[ s + s + 1 ] [p - 3*p + 2]
[ ] *[------------]
[ 4 ] [ p + s ]
[- p + 3*p - 2 a - p -3 ] [ ]
[-------------- ------- -----] [ -a - s ]
[ p + s 9*s - 9 s + 2]{t} [ ---------- ]
[ 2 ]
[ s + s + 1 ]{t}
>>> tfm_12 * tfm_8 * tfm_9
MIMOSeries(TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),),)), TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),))), TransferFunctionMatrix(((TransferFunction(-a + p, 9*s - 9, s), TransferFunction(-a - s, s**2 + s + 1, s), TransferFunction(3, s + 2, s)), (TransferFunction(-p**4 + 3*p - 2, p + s, s), TransferFunction(a - p, 9*s - 9, s), TransferFunction(-3, s + 2, s)))))
>>> pprint(_, use_unicode=False)
[ 3 ]
[ ----- ]
[ -a + p -a - s 3 ] [ s + 2 ]
[ ------- ---------- -----] [ ]
[ 9*s - 9 2 s + 2] [ 4 ]
[ s + s + 1 ] [p - 3*p + 2] [ -3 ]
[ ] *[------------] *[-----]
[ 4 ] [ p + s ] [s + 2]{t}
[- p + 3*p - 2 a - p -3 ] [ ]
[-------------- ------- -----] [ -a - s ]
[ p + s 9*s - 9 s + 2]{t} [ ---------- ]
[ 2 ]
[ s + s + 1 ]{t}
>>> tfm_10 + tfm_8*tfm_9
MIMOParallel(TransferFunctionMatrix(((TransferFunction(a + s, s**2 + s + 1, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a + p, 9*s - 9, s),))), MIMOSeries(TransferFunctionMatrix(((TransferFunction(-3, s + 2, s),),)), TransferFunctionMatrix(((TransferFunction(3, s + 2, s),), (TransferFunction(p**4 - 3*p + 2, p + s, s),), (TransferFunction(-a - s, s**2 + s + 1, s),)))))
>>> pprint(_, use_unicode=False)
[ a + s ] [ 3 ]
[ ---------- ] [ ----- ]
[ 2 ] [ s + 2 ]
[ s + s + 1 ] [ ]
[ ] [ 4 ]
[ 4 ] [p - 3*p + 2] [ -3 ]
[p - 3*p + 2] + [------------] *[-----]
[------------] [ p + s ] [s + 2]{t}
[ p + s ] [ ]
[ ] [ -a - s ]
[ -a + p ] [ ---------- ]
[ ------- ] [ 2 ]
[ 9*s - 9 ]{t} [ s + s + 1 ]{t}
These unevaluated ``Series`` or ``Parallel`` objects can convert into the
resultant transfer function matrix using ``.doit()`` method or by
``.rewrite(TransferFunctionMatrix)``.
>>> (-tfm_8 + tfm_10 + tfm_8*tfm_9).doit()
TransferFunctionMatrix(((TransferFunction((a + s)*(s + 2)**3 - 3*(s + 2)**2*(s**2 + s + 1) - 9*(s + 2)*(s**2 + s + 1), (s + 2)**3*(s**2 + s + 1), s),), (TransferFunction((p + s)*(-3*p**4 + 9*p - 6), (p + s)**2*(s + 2), s),), (TransferFunction((-a + p)*(s + 2)*(s**2 + s + 1)**2 + (a + s)*(s + 2)*(9*s - 9)*(s**2 + s + 1) + (3*a + 3*s)*(9*s - 9)*(s**2 + s + 1), (s + 2)*(9*s - 9)*(s**2 + s + 1)**2, s),)))
>>> (-tfm_12 * -tfm_8 * -tfm_9).rewrite(TransferFunctionMatrix)
TransferFunctionMatrix(((TransferFunction(3*(-3*a + 3*p)*(p + s)*(s + 2)*(s**2 + s + 1)**2 + 3*(-3*a - 3*s)*(p + s)*(s + 2)*(9*s - 9)*(s**2 + s + 1) + 3*(a + s)*(s + 2)**2*(9*s - 9)*(-p**4 + 3*p - 2)*(s**2 + s + 1), (p + s)*(s + 2)**3*(9*s - 9)*(s**2 + s + 1)**2, s),), (TransferFunction(3*(-a + p)*(p + s)*(s + 2)**2*(-p**4 + 3*p - 2)*(s**2 + s + 1) + 3*(3*a + 3*s)*(p + s)**2*(s + 2)*(9*s - 9) + 3*(p + s)*(s + 2)*(9*s - 9)*(-3*p**4 + 9*p - 6)*(s**2 + s + 1), (p + s)**2*(s + 2)**3*(9*s - 9)*(s**2 + s + 1), s),)))
See Also
========
TransferFunction, MIMOSeries, MIMOParallel, Feedback
"""
def __new__(cls, arg):
expr_mat_arg = []
try:
var = arg[0][0].var
except TypeError:
raise ValueError("`arg` param in TransferFunctionMatrix should "
"strictly be a nested list containing TransferFunction objects.")
for row_index, row in enumerate(arg):
temp = []
for col_index, element in enumerate(row):
if not isinstance(element, SISOLinearTimeInvariant):
raise TypeError("Each element is expected to be of type `SISOLinearTimeInvariant`.")
if var != element.var:
raise ValueError("Conflicting value(s) found for `var`. All TransferFunction instances in "
"TransferFunctionMatrix should use the same complex variable in Laplace domain.")
temp.append(element.to_expr())
expr_mat_arg.append(temp)
if isinstance(arg, (tuple, list, Tuple)):
# Making nested Tuple (sympy.core.containers.Tuple) from nested list or nested Python tuple
arg = Tuple(*(Tuple(*r, sympify=False) for r in arg), sympify=False)
obj = super(TransferFunctionMatrix, cls).__new__(cls, arg)
obj._expr_mat = ImmutableMatrix(expr_mat_arg)
return obj
@classmethod
def from_Matrix(cls, matrix, var):
"""
Creates a new ``TransferFunctionMatrix`` efficiently from a SymPy Matrix of ``Expr`` objects.
Parameters
==========
matrix : ``ImmutableMatrix`` having ``Expr``/``Number`` elements.
var : Symbol
Complex variable of the Laplace transform which will be used by the
all the ``TransferFunction`` objects in the ``TransferFunctionMatrix``.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix
>>> from sympy import Matrix, pprint
>>> M = Matrix([[s, 1/s], [1/(s+1), s]])
>>> M_tf = TransferFunctionMatrix.from_Matrix(M, s)
>>> pprint(M_tf, use_unicode=False)
[ s 1]
[ - -]
[ 1 s]
[ ]
[ 1 s]
[----- -]
[s + 1 1]{t}
>>> M_tf.elem_poles()
[[[], [0]], [[-1], []]]
>>> M_tf.elem_zeros()
[[[0], []], [[], [0]]]
"""
return _to_TFM(matrix, var)
@property
def var(self):
"""
Returns the complex variable used by all the transfer functions or
``Series``/``Parallel`` objects in a transfer function matrix.
Examples
========
>>> from sympy.abc import p, s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix, Series, Parallel
>>> G1 = TransferFunction(p**2 + 2*p + 4, p - 6, p)
>>> G2 = TransferFunction(p, 4 - p, p)
>>> G3 = TransferFunction(0, p**4 - 1, p)
>>> G4 = TransferFunction(s + 1, s**2 + s + 1, s)
>>> S1 = Series(G1, G2)
>>> S2 = Series(-G3, Parallel(G2, -G1))
>>> tfm1 = TransferFunctionMatrix([[G1], [G2], [G3]])
>>> tfm1.var
p
>>> tfm2 = TransferFunctionMatrix([[-S1, -S2], [S1, S2]])
>>> tfm2.var
p
>>> tfm3 = TransferFunctionMatrix([[G4]])
>>> tfm3.var
s
"""
return self.args[0][0][0].var
@property
def num_inputs(self):
"""
Returns the number of inputs of the system.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> G1 = TransferFunction(s + 3, s**2 - 3, s)
>>> G2 = TransferFunction(4, s**2, s)
>>> G3 = TransferFunction(p**2 + s**2, p - 3, s)
>>> tfm_1 = TransferFunctionMatrix([[G2, -G1, G3], [-G2, -G1, -G3]])
>>> tfm_1.num_inputs
3
See Also
========
num_outputs
"""
return self._expr_mat.shape[1]
@property
def num_outputs(self):
"""
Returns the number of outputs of the system.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunctionMatrix
>>> from sympy import Matrix
>>> M_1 = Matrix([[s], [1/s]])
>>> TFM = TransferFunctionMatrix.from_Matrix(M_1, s)
>>> print(TFM)
TransferFunctionMatrix(((TransferFunction(s, 1, s),), (TransferFunction(1, s, s),)))
>>> TFM.num_outputs
2
See Also
========
num_inputs
"""
return self._expr_mat.shape[0]
@property
def shape(self):
"""
Returns the shape of the transfer function matrix, that is, ``(# of outputs, # of inputs)``.
Examples
========
>>> from sympy.abc import s, p
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf1 = TransferFunction(p**2 - 1, s**4 + s**3 - p, p)
>>> tf2 = TransferFunction(1 - p, p**2 - 3*p + 7, p)
>>> tf3 = TransferFunction(3, 4, p)
>>> tfm1 = TransferFunctionMatrix([[tf1, -tf2]])
>>> tfm1.shape
(1, 2)
>>> tfm2 = TransferFunctionMatrix([[-tf2, tf3], [tf1, -tf1]])
>>> tfm2.shape
(2, 2)
"""
return self._expr_mat.shape
def __neg__(self):
neg = -self._expr_mat
return _to_TFM(neg, self.var)
@_check_other_MIMO
def __add__(self, other):
if not isinstance(other, MIMOParallel):
return MIMOParallel(self, other)
other_arg_list = list(other.args)
return MIMOParallel(self, *other_arg_list)
@_check_other_MIMO
def __sub__(self, other):
return self + (-other)
@_check_other_MIMO
def __mul__(self, other):
if not isinstance(other, MIMOSeries):
return MIMOSeries(other, self)
other_arg_list = list(other.args)
return MIMOSeries(*other_arg_list, self)
def __getitem__(self, key):
trunc = self._expr_mat.__getitem__(key)
if isinstance(trunc, ImmutableMatrix):
return _to_TFM(trunc, self.var)
return TransferFunction.from_rational_expression(trunc, self.var)
def transpose(self):
"""Returns the transpose of the ``TransferFunctionMatrix`` (switched input and output layers)."""
transposed_mat = self._expr_mat.transpose()
return _to_TFM(transposed_mat, self.var)
def elem_poles(self):
"""
Returns the poles of each element of the ``TransferFunctionMatrix``.
.. note::
Actual poles of a MIMO system are NOT the poles of individual elements.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf_1 = TransferFunction(3, (s + 1), s)
>>> tf_2 = TransferFunction(s + 6, (s + 1)*(s + 2), s)
>>> tf_3 = TransferFunction(s + 3, s**2 + 3*s + 2, s)
>>> tf_4 = TransferFunction(s + 2, s**2 + 5*s - 10, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, tf_4]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(3, s + 1, s), TransferFunction(s + 6, (s + 1)*(s + 2), s)), (TransferFunction(s + 3, s**2 + 3*s + 2, s), TransferFunction(s + 2, s**2 + 5*s - 10, s))))
>>> tfm_1.elem_poles()
[[[-1], [-2, -1]], [[-2, -1], [-5/2 + sqrt(65)/2, -sqrt(65)/2 - 5/2]]]
See Also
========
elem_zeros
"""
return [[element.poles() for element in row] for row in self.doit().args[0]]
def elem_zeros(self):
"""
Returns the zeros of each element of the ``TransferFunctionMatrix``.
.. note::
Actual zeros of a MIMO system are NOT the zeros of individual elements.
Examples
========
>>> from sympy.abc import s
>>> from sympy.physics.control.lti import TransferFunction, TransferFunctionMatrix
>>> tf_1 = TransferFunction(3, (s + 1), s)
>>> tf_2 = TransferFunction(s + 6, (s + 1)*(s + 2), s)
>>> tf_3 = TransferFunction(s + 3, s**2 + 3*s + 2, s)
>>> tf_4 = TransferFunction(s**2 - 9*s + 20, s**2 + 5*s - 10, s)
>>> tfm_1 = TransferFunctionMatrix([[tf_1, tf_2], [tf_3, tf_4]])
>>> tfm_1
TransferFunctionMatrix(((TransferFunction(3, s + 1, s), TransferFunction(s + 6, (s + 1)*(s + 2), s)), (TransferFunction(s + 3, s**2 + 3*s + 2, s), TransferFunction(s**2 - 9*s + 20, s**2 + 5*s - 10, s))))
>>> tfm_1.elem_zeros()
[[[], [-6]], [[-3], [4, 5]]]
See Also
========
elem_poles
"""
return [[element.zeros() for element in row] for row in self.doit().args[0]]
def _flat(self):
"""Returns flattened list of args in TransferFunctionMatrix"""
return [elem for tup in self.args[0] for elem in tup]
def _eval_evalf(self, prec):
"""Calls evalf() on each transfer function in the transfer function matrix"""
dps = prec_to_dps(prec)
mat = self._expr_mat.applyfunc(lambda a: a.evalf(n=dps))
return _to_TFM(mat, self.var)
def _eval_simplify(self, **kwargs):
"""Simplifies the transfer function matrix"""
simp_mat = self._expr_mat.applyfunc(lambda a: cancel(a, expand=False))
return _to_TFM(simp_mat, self.var)
def expand(self, **hints):
"""Expands the transfer function matrix"""
expand_mat = self._expr_mat.expand(**hints)
return _to_TFM(expand_mat, self.var)
|
1aada369d06caa5c7204e51a96b8933eb493912f928f1204549bcd3e2048c7a9 | from collections import deque
from sympy.core.random import randint
from sympy.external import import_module
from sympy.core.basic import Basic
from sympy.core.mul import Mul
from sympy.core.numbers import Number
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.dagger import Dagger
__all__ = [
# Public interfaces
'generate_gate_rules',
'generate_equivalent_ids',
'GateIdentity',
'bfs_identity_search',
'random_identity_search',
# "Private" functions
'is_scalar_sparse_matrix',
'is_scalar_nonsparse_matrix',
'is_degenerate',
'is_reducible',
]
np = import_module('numpy')
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
def is_scalar_sparse_matrix(circuit, nqubits, identity_only, eps=1e-11):
"""Checks if a given scipy.sparse matrix is a scalar matrix.
A scalar matrix is such that B = bI, where B is the scalar
matrix, b is some scalar multiple, and I is the identity
matrix. A scalar matrix would have only the element b along
it's main diagonal and zeroes elsewhere.
Parameters
==========
circuit : Gate tuple
Sequence of quantum gates representing a quantum circuit
nqubits : int
Number of qubits in the circuit
identity_only : bool
Check for only identity matrices
eps : number
The tolerance value for zeroing out elements in the matrix.
Values in the range [-eps, +eps] will be changed to a zero.
"""
if not np or not scipy:
pass
matrix = represent(Mul(*circuit), nqubits=nqubits,
format='scipy.sparse')
# In some cases, represent returns a 1D scalar value in place
# of a multi-dimensional scalar matrix
if (isinstance(matrix, int)):
return matrix == 1 if identity_only else True
# If represent returns a matrix, check if the matrix is diagonal
# and if every item along the diagonal is the same
else:
# Due to floating pointing operations, must zero out
# elements that are "very" small in the dense matrix
# See parameter for default value.
# Get the ndarray version of the dense matrix
dense_matrix = matrix.todense().getA()
# Since complex values can't be compared, must split
# the matrix into real and imaginary components
# Find the real values in between -eps and eps
bool_real = np.logical_and(dense_matrix.real > -eps,
dense_matrix.real < eps)
# Find the imaginary values between -eps and eps
bool_imag = np.logical_and(dense_matrix.imag > -eps,
dense_matrix.imag < eps)
# Replaces values between -eps and eps with 0
corrected_real = np.where(bool_real, 0.0, dense_matrix.real)
corrected_imag = np.where(bool_imag, 0.0, dense_matrix.imag)
# Convert the matrix with real values into imaginary values
corrected_imag = corrected_imag * complex(1j)
# Recombine the real and imaginary components
corrected_dense = corrected_real + corrected_imag
# Check if it's diagonal
row_indices = corrected_dense.nonzero()[0]
col_indices = corrected_dense.nonzero()[1]
# Check if the rows indices and columns indices are the same
# If they match, then matrix only contains elements along diagonal
bool_indices = row_indices == col_indices
is_diagonal = bool_indices.all()
first_element = corrected_dense[0][0]
# If the first element is a zero, then can't rescale matrix
# and definitely not diagonal
if (first_element == 0.0 + 0.0j):
return False
# The dimensions of the dense matrix should still
# be 2^nqubits if there are elements all along the
# the main diagonal
trace_of_corrected = (corrected_dense/first_element).trace()
expected_trace = pow(2, nqubits)
has_correct_trace = trace_of_corrected == expected_trace
# If only looking for identity matrices
# first element must be a 1
real_is_one = abs(first_element.real - 1.0) < eps
imag_is_zero = abs(first_element.imag) < eps
is_one = real_is_one and imag_is_zero
is_identity = is_one if identity_only else True
return bool(is_diagonal and has_correct_trace and is_identity)
def is_scalar_nonsparse_matrix(circuit, nqubits, identity_only, eps=None):
"""Checks if a given circuit, in matrix form, is equivalent to
a scalar value.
Parameters
==========
circuit : Gate tuple
Sequence of quantum gates representing a quantum circuit
nqubits : int
Number of qubits in the circuit
identity_only : bool
Check for only identity matrices
eps : number
This argument is ignored. It is just for signature compatibility with
is_scalar_sparse_matrix.
Note: Used in situations when is_scalar_sparse_matrix has bugs
"""
matrix = represent(Mul(*circuit), nqubits=nqubits)
# In some cases, represent returns a 1D scalar value in place
# of a multi-dimensional scalar matrix
if (isinstance(matrix, Number)):
return matrix == 1 if identity_only else True
# If represent returns a matrix, check if the matrix is diagonal
# and if every item along the diagonal is the same
else:
# Added up the diagonal elements
matrix_trace = matrix.trace()
# Divide the trace by the first element in the matrix
# if matrix is not required to be the identity matrix
adjusted_matrix_trace = (matrix_trace/matrix[0]
if not identity_only
else matrix_trace)
is_identity = matrix[0] == 1.0 if identity_only else True
has_correct_trace = adjusted_matrix_trace == pow(2, nqubits)
# The matrix is scalar if it's diagonal and the adjusted trace
# value is equal to 2^nqubits
return bool(
matrix.is_diagonal() and has_correct_trace and is_identity)
if np and scipy:
is_scalar_matrix = is_scalar_sparse_matrix
else:
is_scalar_matrix = is_scalar_nonsparse_matrix
def _get_min_qubits(a_gate):
if isinstance(a_gate, Pow):
return a_gate.base.min_qubits
else:
return a_gate.min_qubits
def ll_op(left, right):
"""Perform a LL operation.
A LL operation multiplies both left and right circuits
with the dagger of the left circuit's leftmost gate, and
the dagger is multiplied on the left side of both circuits.
If a LL is possible, it returns the new gate rule as a
2-tuple (LHS, RHS), where LHS is the left circuit and
and RHS is the right circuit of the new rule.
If a LL is not possible, None is returned.
Parameters
==========
left : Gate tuple
The left circuit of a gate rule expression.
right : Gate tuple
The right circuit of a gate rule expression.
Examples
========
Generate a new gate rule using a LL operation:
>>> from sympy.physics.quantum.identitysearch import ll_op
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> ll_op((x, y, z), ())
((Y(0), Z(0)), (X(0),))
>>> ll_op((y, z), (x,))
((Z(0),), (Y(0), X(0)))
"""
if (len(left) > 0):
ll_gate = left[0]
ll_gate_is_unitary = is_scalar_matrix(
(Dagger(ll_gate), ll_gate), _get_min_qubits(ll_gate), True)
if (len(left) > 0 and ll_gate_is_unitary):
# Get the new left side w/o the leftmost gate
new_left = left[1:len(left)]
# Add the leftmost gate to the left position on the right side
new_right = (Dagger(ll_gate),) + right
# Return the new gate rule
return (new_left, new_right)
return None
def lr_op(left, right):
"""Perform a LR operation.
A LR operation multiplies both left and right circuits
with the dagger of the left circuit's rightmost gate, and
the dagger is multiplied on the right side of both circuits.
If a LR is possible, it returns the new gate rule as a
2-tuple (LHS, RHS), where LHS is the left circuit and
and RHS is the right circuit of the new rule.
If a LR is not possible, None is returned.
Parameters
==========
left : Gate tuple
The left circuit of a gate rule expression.
right : Gate tuple
The right circuit of a gate rule expression.
Examples
========
Generate a new gate rule using a LR operation:
>>> from sympy.physics.quantum.identitysearch import lr_op
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> lr_op((x, y, z), ())
((X(0), Y(0)), (Z(0),))
>>> lr_op((x, y), (z,))
((X(0),), (Z(0), Y(0)))
"""
if (len(left) > 0):
lr_gate = left[len(left) - 1]
lr_gate_is_unitary = is_scalar_matrix(
(Dagger(lr_gate), lr_gate), _get_min_qubits(lr_gate), True)
if (len(left) > 0 and lr_gate_is_unitary):
# Get the new left side w/o the rightmost gate
new_left = left[0:len(left) - 1]
# Add the rightmost gate to the right position on the right side
new_right = right + (Dagger(lr_gate),)
# Return the new gate rule
return (new_left, new_right)
return None
def rl_op(left, right):
"""Perform a RL operation.
A RL operation multiplies both left and right circuits
with the dagger of the right circuit's leftmost gate, and
the dagger is multiplied on the left side of both circuits.
If a RL is possible, it returns the new gate rule as a
2-tuple (LHS, RHS), where LHS is the left circuit and
and RHS is the right circuit of the new rule.
If a RL is not possible, None is returned.
Parameters
==========
left : Gate tuple
The left circuit of a gate rule expression.
right : Gate tuple
The right circuit of a gate rule expression.
Examples
========
Generate a new gate rule using a RL operation:
>>> from sympy.physics.quantum.identitysearch import rl_op
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> rl_op((x,), (y, z))
((Y(0), X(0)), (Z(0),))
>>> rl_op((x, y), (z,))
((Z(0), X(0), Y(0)), ())
"""
if (len(right) > 0):
rl_gate = right[0]
rl_gate_is_unitary = is_scalar_matrix(
(Dagger(rl_gate), rl_gate), _get_min_qubits(rl_gate), True)
if (len(right) > 0 and rl_gate_is_unitary):
# Get the new right side w/o the leftmost gate
new_right = right[1:len(right)]
# Add the leftmost gate to the left position on the left side
new_left = (Dagger(rl_gate),) + left
# Return the new gate rule
return (new_left, new_right)
return None
def rr_op(left, right):
"""Perform a RR operation.
A RR operation multiplies both left and right circuits
with the dagger of the right circuit's rightmost gate, and
the dagger is multiplied on the right side of both circuits.
If a RR is possible, it returns the new gate rule as a
2-tuple (LHS, RHS), where LHS is the left circuit and
and RHS is the right circuit of the new rule.
If a RR is not possible, None is returned.
Parameters
==========
left : Gate tuple
The left circuit of a gate rule expression.
right : Gate tuple
The right circuit of a gate rule expression.
Examples
========
Generate a new gate rule using a RR operation:
>>> from sympy.physics.quantum.identitysearch import rr_op
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> rr_op((x, y), (z,))
((X(0), Y(0), Z(0)), ())
>>> rr_op((x,), (y, z))
((X(0), Z(0)), (Y(0),))
"""
if (len(right) > 0):
rr_gate = right[len(right) - 1]
rr_gate_is_unitary = is_scalar_matrix(
(Dagger(rr_gate), rr_gate), _get_min_qubits(rr_gate), True)
if (len(right) > 0 and rr_gate_is_unitary):
# Get the new right side w/o the rightmost gate
new_right = right[0:len(right) - 1]
# Add the rightmost gate to the right position on the right side
new_left = left + (Dagger(rr_gate),)
# Return the new gate rule
return (new_left, new_right)
return None
def generate_gate_rules(gate_seq, return_as_muls=False):
"""Returns a set of gate rules. Each gate rules is represented
as a 2-tuple of tuples or Muls. An empty tuple represents an arbitrary
scalar value.
This function uses the four operations (LL, LR, RL, RR)
to generate the gate rules.
A gate rule is an expression such as ABC = D or AB = CD, where
A, B, C, and D are gates. Each value on either side of the
equal sign represents a circuit. The four operations allow
one to find a set of equivalent circuits from a gate identity.
The letters denoting the operation tell the user what
activities to perform on each expression. The first letter
indicates which side of the equal sign to focus on. The
second letter indicates which gate to focus on given the
side. Once this information is determined, the inverse
of the gate is multiplied on both circuits to create a new
gate rule.
For example, given the identity, ABCD = 1, a LL operation
means look at the left value and multiply both left sides by the
inverse of the leftmost gate A. If A is Hermitian, the inverse
of A is still A. The resulting new rule is BCD = A.
The following is a summary of the four operations. Assume
that in the examples, all gates are Hermitian.
LL : left circuit, left multiply
ABCD = E -> AABCD = AE -> BCD = AE
LR : left circuit, right multiply
ABCD = E -> ABCDD = ED -> ABC = ED
RL : right circuit, left multiply
ABC = ED -> EABC = EED -> EABC = D
RR : right circuit, right multiply
AB = CD -> ABD = CDD -> ABD = C
The number of gate rules generated is n*(n+1), where n
is the number of gates in the sequence (unproven).
Parameters
==========
gate_seq : Gate tuple, Mul, or Number
A variable length tuple or Mul of Gates whose product is equal to
a scalar matrix
return_as_muls : bool
True to return a set of Muls; False to return a set of tuples
Examples
========
Find the gate rules of the current circuit using tuples:
>>> from sympy.physics.quantum.identitysearch import generate_gate_rules
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> generate_gate_rules((x, x))
{((X(0),), (X(0),)), ((X(0), X(0)), ())}
>>> generate_gate_rules((x, y, z))
{((), (X(0), Z(0), Y(0))), ((), (Y(0), X(0), Z(0))),
((), (Z(0), Y(0), X(0))), ((X(0),), (Z(0), Y(0))),
((Y(0),), (X(0), Z(0))), ((Z(0),), (Y(0), X(0))),
((X(0), Y(0)), (Z(0),)), ((Y(0), Z(0)), (X(0),)),
((Z(0), X(0)), (Y(0),)), ((X(0), Y(0), Z(0)), ()),
((Y(0), Z(0), X(0)), ()), ((Z(0), X(0), Y(0)), ())}
Find the gate rules of the current circuit using Muls:
>>> generate_gate_rules(x*x, return_as_muls=True)
{(1, 1)}
>>> generate_gate_rules(x*y*z, return_as_muls=True)
{(1, X(0)*Z(0)*Y(0)), (1, Y(0)*X(0)*Z(0)),
(1, Z(0)*Y(0)*X(0)), (X(0)*Y(0), Z(0)),
(Y(0)*Z(0), X(0)), (Z(0)*X(0), Y(0)),
(X(0)*Y(0)*Z(0), 1), (Y(0)*Z(0)*X(0), 1),
(Z(0)*X(0)*Y(0), 1), (X(0), Z(0)*Y(0)),
(Y(0), X(0)*Z(0)), (Z(0), Y(0)*X(0))}
"""
if isinstance(gate_seq, Number):
if return_as_muls:
return {(S.One, S.One)}
else:
return {((), ())}
elif isinstance(gate_seq, Mul):
gate_seq = gate_seq.args
# Each item in queue is a 3-tuple:
# i) first item is the left side of an equality
# ii) second item is the right side of an equality
# iii) third item is the number of operations performed
# The argument, gate_seq, will start on the left side, and
# the right side will be empty, implying the presence of an
# identity.
queue = deque()
# A set of gate rules
rules = set()
# Maximum number of operations to perform
max_ops = len(gate_seq)
def process_new_rule(new_rule, ops):
if new_rule is not None:
new_left, new_right = new_rule
if new_rule not in rules and (new_right, new_left) not in rules:
rules.add(new_rule)
# If haven't reached the max limit on operations
if ops + 1 < max_ops:
queue.append(new_rule + (ops + 1,))
queue.append((gate_seq, (), 0))
rules.add((gate_seq, ()))
while len(queue) > 0:
left, right, ops = queue.popleft()
# Do a LL
new_rule = ll_op(left, right)
process_new_rule(new_rule, ops)
# Do a LR
new_rule = lr_op(left, right)
process_new_rule(new_rule, ops)
# Do a RL
new_rule = rl_op(left, right)
process_new_rule(new_rule, ops)
# Do a RR
new_rule = rr_op(left, right)
process_new_rule(new_rule, ops)
if return_as_muls:
# Convert each rule as tuples into a rule as muls
mul_rules = set()
for rule in rules:
left, right = rule
mul_rules.add((Mul(*left), Mul(*right)))
rules = mul_rules
return rules
def generate_equivalent_ids(gate_seq, return_as_muls=False):
"""Returns a set of equivalent gate identities.
A gate identity is a quantum circuit such that the product
of the gates in the circuit is equal to a scalar value.
For example, XYZ = i, where X, Y, Z are the Pauli gates and
i is the imaginary value, is considered a gate identity.
This function uses the four operations (LL, LR, RL, RR)
to generate the gate rules and, subsequently, to locate equivalent
gate identities.
Note that all equivalent identities are reachable in n operations
from the starting gate identity, where n is the number of gates
in the sequence.
The max number of gate identities is 2n, where n is the number
of gates in the sequence (unproven).
Parameters
==========
gate_seq : Gate tuple, Mul, or Number
A variable length tuple or Mul of Gates whose product is equal to
a scalar matrix.
return_as_muls: bool
True to return as Muls; False to return as tuples
Examples
========
Find equivalent gate identities from the current circuit with tuples:
>>> from sympy.physics.quantum.identitysearch import generate_equivalent_ids
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> generate_equivalent_ids((x, x))
{(X(0), X(0))}
>>> generate_equivalent_ids((x, y, z))
{(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
(Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
Find equivalent gate identities from the current circuit with Muls:
>>> generate_equivalent_ids(x*x, return_as_muls=True)
{1}
>>> generate_equivalent_ids(x*y*z, return_as_muls=True)
{X(0)*Y(0)*Z(0), X(0)*Z(0)*Y(0), Y(0)*X(0)*Z(0),
Y(0)*Z(0)*X(0), Z(0)*X(0)*Y(0), Z(0)*Y(0)*X(0)}
"""
if isinstance(gate_seq, Number):
return {S.One}
elif isinstance(gate_seq, Mul):
gate_seq = gate_seq.args
# Filter through the gate rules and keep the rules
# with an empty tuple either on the left or right side
# A set of equivalent gate identities
eq_ids = set()
gate_rules = generate_gate_rules(gate_seq)
for rule in gate_rules:
l, r = rule
if l == ():
eq_ids.add(r)
elif r == ():
eq_ids.add(l)
if return_as_muls:
convert_to_mul = lambda id_seq: Mul(*id_seq)
eq_ids = set(map(convert_to_mul, eq_ids))
return eq_ids
class GateIdentity(Basic):
"""Wrapper class for circuits that reduce to a scalar value.
A gate identity is a quantum circuit such that the product
of the gates in the circuit is equal to a scalar value.
For example, XYZ = i, where X, Y, Z are the Pauli gates and
i is the imaginary value, is considered a gate identity.
Parameters
==========
args : Gate tuple
A variable length tuple of Gates that form an identity.
Examples
========
Create a GateIdentity and look at its attributes:
>>> from sympy.physics.quantum.identitysearch import GateIdentity
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> an_identity = GateIdentity(x, y, z)
>>> an_identity.circuit
X(0)*Y(0)*Z(0)
>>> an_identity.equivalent_ids
{(X(0), Y(0), Z(0)), (X(0), Z(0), Y(0)), (Y(0), X(0), Z(0)),
(Y(0), Z(0), X(0)), (Z(0), X(0), Y(0)), (Z(0), Y(0), X(0))}
"""
def __new__(cls, *args):
# args should be a tuple - a variable length argument list
obj = Basic.__new__(cls, *args)
obj._circuit = Mul(*args)
obj._rules = generate_gate_rules(args)
obj._eq_ids = generate_equivalent_ids(args)
return obj
@property
def circuit(self):
return self._circuit
@property
def gate_rules(self):
return self._rules
@property
def equivalent_ids(self):
return self._eq_ids
@property
def sequence(self):
return self.args
def __str__(self):
"""Returns the string of gates in a tuple."""
return str(self.circuit)
def is_degenerate(identity_set, gate_identity):
"""Checks if a gate identity is a permutation of another identity.
Parameters
==========
identity_set : set
A Python set with GateIdentity objects.
gate_identity : GateIdentity
The GateIdentity to check for existence in the set.
Examples
========
Check if the identity is a permutation of another identity:
>>> from sympy.physics.quantum.identitysearch import (
... GateIdentity, is_degenerate)
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> an_identity = GateIdentity(x, y, z)
>>> id_set = {an_identity}
>>> another_id = (y, z, x)
>>> is_degenerate(id_set, another_id)
True
>>> another_id = (x, x)
>>> is_degenerate(id_set, another_id)
False
"""
# For now, just iteratively go through the set and check if the current
# gate_identity is a permutation of an identity in the set
for an_id in identity_set:
if (gate_identity in an_id.equivalent_ids):
return True
return False
def is_reducible(circuit, nqubits, begin, end):
"""Determines if a circuit is reducible by checking
if its subcircuits are scalar values.
Parameters
==========
circuit : Gate tuple
A tuple of Gates representing a circuit. The circuit to check
if a gate identity is contained in a subcircuit.
nqubits : int
The number of qubits the circuit operates on.
begin : int
The leftmost gate in the circuit to include in a subcircuit.
end : int
The rightmost gate in the circuit to include in a subcircuit.
Examples
========
Check if the circuit can be reduced:
>>> from sympy.physics.quantum.identitysearch import is_reducible
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> is_reducible((x, y, z), 1, 0, 3)
True
Check if an interval in the circuit can be reduced:
>>> is_reducible((x, y, z), 1, 1, 3)
False
>>> is_reducible((x, y, y), 1, 1, 3)
True
"""
current_circuit = ()
# Start from the gate at "end" and go down to almost the gate at "begin"
for ndx in reversed(range(begin, end)):
next_gate = circuit[ndx]
current_circuit = (next_gate,) + current_circuit
# If a circuit as a matrix is equivalent to a scalar value
if (is_scalar_matrix(current_circuit, nqubits, False)):
return True
return False
def bfs_identity_search(gate_list, nqubits, max_depth=None,
identity_only=False):
"""Constructs a set of gate identities from the list of possible gates.
Performs a breadth first search over the space of gate identities.
This allows the finding of the shortest gate identities first.
Parameters
==========
gate_list : list, Gate
A list of Gates from which to search for gate identities.
nqubits : int
The number of qubits the quantum circuit operates on.
max_depth : int
The longest quantum circuit to construct from gate_list.
identity_only : bool
True to search for gate identities that reduce to identity;
False to search for gate identities that reduce to a scalar.
Examples
========
Find a list of gate identities:
>>> from sympy.physics.quantum.identitysearch import bfs_identity_search
>>> from sympy.physics.quantum.gate import X, Y, Z
>>> x = X(0); y = Y(0); z = Z(0)
>>> bfs_identity_search([x], 1, max_depth=2)
{GateIdentity(X(0), X(0))}
>>> bfs_identity_search([x, y, z], 1)
{GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
GateIdentity(Z(0), Z(0)), GateIdentity(X(0), Y(0), Z(0))}
Find a list of identities that only equal to 1:
>>> bfs_identity_search([x, y, z], 1, identity_only=True)
{GateIdentity(X(0), X(0)), GateIdentity(Y(0), Y(0)),
GateIdentity(Z(0), Z(0))}
"""
if max_depth is None or max_depth <= 0:
max_depth = len(gate_list)
id_only = identity_only
# Start with an empty sequence (implicitly contains an IdentityGate)
queue = deque([()])
# Create an empty set of gate identities
ids = set()
# Begin searching for gate identities in given space.
while (len(queue) > 0):
current_circuit = queue.popleft()
for next_gate in gate_list:
new_circuit = current_circuit + (next_gate,)
# Determines if a (strict) subcircuit is a scalar matrix
circuit_reducible = is_reducible(new_circuit, nqubits,
1, len(new_circuit))
# In many cases when the matrix is a scalar value,
# the evaluated matrix will actually be an integer
if (is_scalar_matrix(new_circuit, nqubits, id_only) and
not is_degenerate(ids, new_circuit) and
not circuit_reducible):
ids.add(GateIdentity(*new_circuit))
elif (len(new_circuit) < max_depth and
not circuit_reducible):
queue.append(new_circuit)
return ids
def random_identity_search(gate_list, numgates, nqubits):
"""Randomly selects numgates from gate_list and checks if it is
a gate identity.
If the circuit is a gate identity, the circuit is returned;
Otherwise, None is returned.
"""
gate_size = len(gate_list)
circuit = ()
for i in range(numgates):
next_gate = gate_list[randint(0, gate_size - 1)]
circuit = circuit + (next_gate,)
is_scalar = is_scalar_matrix(circuit, nqubits, False)
return circuit if is_scalar else None
|
1111f5291bbbd8d787d6c73e495cc59e699271534c0d5bbf942c465f1b3332a2 | """Dirac notation for states."""
from sympy.core.cache import cacheit
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import Function
from sympy.core.numbers import oo
from sympy.core.singleton import S
from sympy.functions.elementary.complexes import conjugate
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.integrals.integrals import integrate
from sympy.printing.pretty.stringpict import stringPict
from sympy.physics.quantum.qexpr import QExpr, dispatch_method
__all__ = [
'KetBase',
'BraBase',
'StateBase',
'State',
'Ket',
'Bra',
'TimeDepState',
'TimeDepBra',
'TimeDepKet',
'OrthogonalKet',
'OrthogonalBra',
'OrthogonalState',
'Wavefunction'
]
#-----------------------------------------------------------------------------
# States, bras and kets.
#-----------------------------------------------------------------------------
# ASCII brackets
_lbracket = "<"
_rbracket = ">"
_straight_bracket = "|"
# Unicode brackets
# MATHEMATICAL ANGLE BRACKETS
_lbracket_ucode = "\N{MATHEMATICAL LEFT ANGLE BRACKET}"
_rbracket_ucode = "\N{MATHEMATICAL RIGHT ANGLE BRACKET}"
# LIGHT VERTICAL BAR
_straight_bracket_ucode = "\N{LIGHT VERTICAL BAR}"
# Other options for unicode printing of <, > and | for Dirac notation.
# LEFT-POINTING ANGLE BRACKET
# _lbracket = "\u2329"
# _rbracket = "\u232A"
# LEFT ANGLE BRACKET
# _lbracket = "\u3008"
# _rbracket = "\u3009"
# VERTICAL LINE
# _straight_bracket = "\u007C"
class StateBase(QExpr):
"""Abstract base class for general abstract states in quantum mechanics.
All other state classes defined will need to inherit from this class. It
carries the basic structure for all other states such as dual, _eval_adjoint
and label.
This is an abstract base class and you should not instantiate it directly,
instead use State.
"""
@classmethod
def _operators_to_state(self, ops, **options):
""" Returns the eigenstate instance for the passed operators.
This method should be overridden in subclasses. It will handle being
passed either an Operator instance or set of Operator instances. It
should return the corresponding state INSTANCE or simply raise a
NotImplementedError. See cartesian.py for an example.
"""
raise NotImplementedError("Cannot map operators to states in this class. Method not implemented!")
def _state_to_operators(self, op_classes, **options):
""" Returns the operators which this state instance is an eigenstate
of.
This method should be overridden in subclasses. It will be called on
state instances and be passed the operator classes that we wish to make
into instances. The state instance will then transform the classes
appropriately, or raise a NotImplementedError if it cannot return
operator instances. See cartesian.py for examples,
"""
raise NotImplementedError(
"Cannot map this state to operators. Method not implemented!")
@property
def operators(self):
"""Return the operator(s) that this state is an eigenstate of"""
from .operatorset import state_to_operators # import internally to avoid circular import errors
return state_to_operators(self)
def _enumerate_state(self, num_states, **options):
raise NotImplementedError("Cannot enumerate this state!")
def _represent_default_basis(self, **options):
return self._represent(basis=self.operators)
#-------------------------------------------------------------------------
# Dagger/dual
#-------------------------------------------------------------------------
@property
def dual(self):
"""Return the dual state of this one."""
return self.dual_class()._new_rawargs(self.hilbert_space, *self.args)
@classmethod
def dual_class(self):
"""Return the class used to construct the dual."""
raise NotImplementedError(
'dual_class must be implemented in a subclass'
)
def _eval_adjoint(self):
"""Compute the dagger of this state using the dual."""
return self.dual
#-------------------------------------------------------------------------
# Printing
#-------------------------------------------------------------------------
def _pretty_brackets(self, height, use_unicode=True):
# Return pretty printed brackets for the state
# Ideally, this could be done by pform.parens but it does not support the angled < and >
# Setup for unicode vs ascii
if use_unicode:
lbracket, rbracket = getattr(self, 'lbracket_ucode', ""), getattr(self, 'rbracket_ucode', "")
slash, bslash, vert = '\N{BOX DRAWINGS LIGHT DIAGONAL UPPER RIGHT TO LOWER LEFT}', \
'\N{BOX DRAWINGS LIGHT DIAGONAL UPPER LEFT TO LOWER RIGHT}', \
'\N{BOX DRAWINGS LIGHT VERTICAL}'
else:
lbracket, rbracket = getattr(self, 'lbracket', ""), getattr(self, 'rbracket', "")
slash, bslash, vert = '/', '\\', '|'
# If height is 1, just return brackets
if height == 1:
return stringPict(lbracket), stringPict(rbracket)
# Make height even
height += (height % 2)
brackets = []
for bracket in lbracket, rbracket:
# Create left bracket
if bracket in {_lbracket, _lbracket_ucode}:
bracket_args = [ ' ' * (height//2 - i - 1) +
slash for i in range(height // 2)]
bracket_args.extend(
[' ' * i + bslash for i in range(height // 2)])
# Create right bracket
elif bracket in {_rbracket, _rbracket_ucode}:
bracket_args = [ ' ' * i + bslash for i in range(height // 2)]
bracket_args.extend([ ' ' * (
height//2 - i - 1) + slash for i in range(height // 2)])
# Create straight bracket
elif bracket in {_straight_bracket, _straight_bracket_ucode}:
bracket_args = [vert] * height
else:
raise ValueError(bracket)
brackets.append(
stringPict('\n'.join(bracket_args), baseline=height//2))
return brackets
def _sympystr(self, printer, *args):
contents = self._print_contents(printer, *args)
return '%s%s%s' % (getattr(self, 'lbracket', ""), contents, getattr(self, 'rbracket', ""))
def _pretty(self, printer, *args):
from sympy.printing.pretty.stringpict import prettyForm
# Get brackets
pform = self._print_contents_pretty(printer, *args)
lbracket, rbracket = self._pretty_brackets(
pform.height(), printer._use_unicode)
# Put together state
pform = prettyForm(*pform.left(lbracket))
pform = prettyForm(*pform.right(rbracket))
return pform
def _latex(self, printer, *args):
contents = self._print_contents_latex(printer, *args)
# The extra {} brackets are needed to get matplotlib's latex
# rendered to render this properly.
return '{%s%s%s}' % (getattr(self, 'lbracket_latex', ""), contents, getattr(self, 'rbracket_latex', ""))
class KetBase(StateBase):
"""Base class for Kets.
This class defines the dual property and the brackets for printing. This is
an abstract base class and you should not instantiate it directly, instead
use Ket.
"""
lbracket = _straight_bracket
rbracket = _rbracket
lbracket_ucode = _straight_bracket_ucode
rbracket_ucode = _rbracket_ucode
lbracket_latex = r'\left|'
rbracket_latex = r'\right\rangle '
@classmethod
def default_args(self):
return ("psi",)
@classmethod
def dual_class(self):
return BraBase
def __mul__(self, other):
"""KetBase*other"""
from sympy.physics.quantum.operator import OuterProduct
if isinstance(other, BraBase):
return OuterProduct(self, other)
else:
return Expr.__mul__(self, other)
def __rmul__(self, other):
"""other*KetBase"""
from sympy.physics.quantum.innerproduct import InnerProduct
if isinstance(other, BraBase):
return InnerProduct(other, self)
else:
return Expr.__rmul__(self, other)
#-------------------------------------------------------------------------
# _eval_* methods
#-------------------------------------------------------------------------
def _eval_innerproduct(self, bra, **hints):
"""Evaluate the inner product between this ket and a bra.
This is called to compute <bra|ket>, where the ket is ``self``.
This method will dispatch to sub-methods having the format::
``def _eval_innerproduct_BraClass(self, **hints):``
Subclasses should define these methods (one for each BraClass) to
teach the ket how to take inner products with bras.
"""
return dispatch_method(self, '_eval_innerproduct', bra, **hints)
def _apply_operator(self, op, **options):
"""Apply an Operator to this Ket.
This method will dispatch to methods having the format::
``def _apply_operator_OperatorName(op, **options):``
Subclasses should define these methods (one for each OperatorName) to
teach the Ket how operators act on it.
Parameters
==========
op : Operator
The Operator that is acting on the Ket.
options : dict
A dict of key/value pairs that control how the operator is applied
to the Ket.
"""
return dispatch_method(self, '_apply_operator', op, **options)
class BraBase(StateBase):
"""Base class for Bras.
This class defines the dual property and the brackets for printing. This
is an abstract base class and you should not instantiate it directly,
instead use Bra.
"""
lbracket = _lbracket
rbracket = _straight_bracket
lbracket_ucode = _lbracket_ucode
rbracket_ucode = _straight_bracket_ucode
lbracket_latex = r'\left\langle '
rbracket_latex = r'\right|'
@classmethod
def _operators_to_state(self, ops, **options):
state = self.dual_class()._operators_to_state(ops, **options)
return state.dual
def _state_to_operators(self, op_classes, **options):
return self.dual._state_to_operators(op_classes, **options)
def _enumerate_state(self, num_states, **options):
dual_states = self.dual._enumerate_state(num_states, **options)
return [x.dual for x in dual_states]
@classmethod
def default_args(self):
return self.dual_class().default_args()
@classmethod
def dual_class(self):
return KetBase
def __mul__(self, other):
"""BraBase*other"""
from sympy.physics.quantum.innerproduct import InnerProduct
if isinstance(other, KetBase):
return InnerProduct(self, other)
else:
return Expr.__mul__(self, other)
def __rmul__(self, other):
"""other*BraBase"""
from sympy.physics.quantum.operator import OuterProduct
if isinstance(other, KetBase):
return OuterProduct(other, self)
else:
return Expr.__rmul__(self, other)
def _represent(self, **options):
"""A default represent that uses the Ket's version."""
from sympy.physics.quantum.dagger import Dagger
return Dagger(self.dual._represent(**options))
class State(StateBase):
"""General abstract quantum state used as a base class for Ket and Bra."""
pass
class Ket(State, KetBase):
"""A general time-independent Ket in quantum mechanics.
Inherits from State and KetBase. This class should be used as the base
class for all physical, time-independent Kets in a system. This class
and its subclasses will be the main classes that users will use for
expressing Kets in Dirac notation [1]_.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
ket. This will usually be its symbol or its quantum numbers. For
time-dependent state, this will include the time.
Examples
========
Create a simple Ket and looking at its properties::
>>> from sympy.physics.quantum import Ket
>>> from sympy import symbols, I
>>> k = Ket('psi')
>>> k
|psi>
>>> k.hilbert_space
H
>>> k.is_commutative
False
>>> k.label
(psi,)
Ket's know about their associated bra::
>>> k.dual
<psi|
>>> k.dual_class()
<class 'sympy.physics.quantum.state.Bra'>
Take a linear combination of two kets::
>>> k0 = Ket(0)
>>> k1 = Ket(1)
>>> 2*I*k0 - 4*k1
2*I*|0> - 4*|1>
Compound labels are passed as tuples::
>>> n, m = symbols('n,m')
>>> k = Ket(n,m)
>>> k
|nm>
References
==========
.. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
"""
@classmethod
def dual_class(self):
return Bra
class Bra(State, BraBase):
"""A general time-independent Bra in quantum mechanics.
Inherits from State and BraBase. A Bra is the dual of a Ket [1]_. This
class and its subclasses will be the main classes that users will use for
expressing Bras in Dirac notation.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the
ket. This will usually be its symbol or its quantum numbers. For
time-dependent state, this will include the time.
Examples
========
Create a simple Bra and look at its properties::
>>> from sympy.physics.quantum import Bra
>>> from sympy import symbols, I
>>> b = Bra('psi')
>>> b
<psi|
>>> b.hilbert_space
H
>>> b.is_commutative
False
Bra's know about their dual Ket's::
>>> b.dual
|psi>
>>> b.dual_class()
<class 'sympy.physics.quantum.state.Ket'>
Like Kets, Bras can have compound labels and be manipulated in a similar
manner::
>>> n, m = symbols('n,m')
>>> b = Bra(n,m) - I*Bra(m,n)
>>> b
-I*<mn| + <nm|
Symbols in a Bra can be substituted using ``.subs``::
>>> b.subs(n,m)
<mm| - I*<mm|
References
==========
.. [1] https://en.wikipedia.org/wiki/Bra-ket_notation
"""
@classmethod
def dual_class(self):
return Ket
#-----------------------------------------------------------------------------
# Time dependent states, bras and kets.
#-----------------------------------------------------------------------------
class TimeDepState(StateBase):
"""Base class for a general time-dependent quantum state.
This class is used as a base class for any time-dependent state. The main
difference between this class and the time-independent state is that this
class takes a second argument that is the time in addition to the usual
label argument.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket. This
will usually be its symbol or its quantum numbers. For time-dependent
state, this will include the time as the final argument.
"""
#-------------------------------------------------------------------------
# Initialization
#-------------------------------------------------------------------------
@classmethod
def default_args(self):
return ("psi", "t")
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def label(self):
"""The label of the state."""
return self.args[:-1]
@property
def time(self):
"""The time of the state."""
return self.args[-1]
#-------------------------------------------------------------------------
# Printing
#-------------------------------------------------------------------------
def _print_time(self, printer, *args):
return printer._print(self.time, *args)
_print_time_repr = _print_time
_print_time_latex = _print_time
def _print_time_pretty(self, printer, *args):
pform = printer._print(self.time, *args)
return pform
def _print_contents(self, printer, *args):
label = self._print_label(printer, *args)
time = self._print_time(printer, *args)
return '%s;%s' % (label, time)
def _print_label_repr(self, printer, *args):
label = self._print_sequence(self.label, ',', printer, *args)
time = self._print_time_repr(printer, *args)
return '%s,%s' % (label, time)
def _print_contents_pretty(self, printer, *args):
label = self._print_label_pretty(printer, *args)
time = self._print_time_pretty(printer, *args)
return printer._print_seq((label, time), delimiter=';')
def _print_contents_latex(self, printer, *args):
label = self._print_sequence(
self.label, self._label_separator, printer, *args)
time = self._print_time_latex(printer, *args)
return '%s;%s' % (label, time)
class TimeDepKet(TimeDepState, KetBase):
"""General time-dependent Ket in quantum mechanics.
This inherits from ``TimeDepState`` and ``KetBase`` and is the main class
that should be used for Kets that vary with time. Its dual is a
``TimeDepBra``.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket. This
will usually be its symbol or its quantum numbers. For time-dependent
state, this will include the time as the final argument.
Examples
========
Create a TimeDepKet and look at its attributes::
>>> from sympy.physics.quantum import TimeDepKet
>>> k = TimeDepKet('psi', 't')
>>> k
|psi;t>
>>> k.time
t
>>> k.label
(psi,)
>>> k.hilbert_space
H
TimeDepKets know about their dual bra::
>>> k.dual
<psi;t|
>>> k.dual_class()
<class 'sympy.physics.quantum.state.TimeDepBra'>
"""
@classmethod
def dual_class(self):
return TimeDepBra
class TimeDepBra(TimeDepState, BraBase):
"""General time-dependent Bra in quantum mechanics.
This inherits from TimeDepState and BraBase and is the main class that
should be used for Bras that vary with time. Its dual is a TimeDepBra.
Parameters
==========
args : tuple
The list of numbers or parameters that uniquely specify the ket. This
will usually be its symbol or its quantum numbers. For time-dependent
state, this will include the time as the final argument.
Examples
========
>>> from sympy.physics.quantum import TimeDepBra
>>> b = TimeDepBra('psi', 't')
>>> b
<psi;t|
>>> b.time
t
>>> b.label
(psi,)
>>> b.hilbert_space
H
>>> b.dual
|psi;t>
"""
@classmethod
def dual_class(self):
return TimeDepKet
class OrthogonalState(State, StateBase):
"""General abstract quantum state used as a base class for Ket and Bra."""
pass
class OrthogonalKet(OrthogonalState, KetBase):
"""Orthogonal Ket in quantum mechanics.
The inner product of two states with different labels will give zero,
states with the same label will give one.
>>> from sympy.physics.quantum import OrthogonalBra, OrthogonalKet
>>> from sympy.abc import m, n
>>> (OrthogonalBra(n)*OrthogonalKet(n)).doit()
1
>>> (OrthogonalBra(n)*OrthogonalKet(n+1)).doit()
0
>>> (OrthogonalBra(n)*OrthogonalKet(m)).doit()
<n|m>
"""
@classmethod
def dual_class(self):
return OrthogonalBra
def _eval_innerproduct(self, bra, **hints):
if len(self.args) != len(bra.args):
raise ValueError('Cannot multiply a ket that has a different number of labels.')
for i in range(len(self.args)):
diff = self.args[i] - bra.args[i]
diff = diff.expand()
if diff.is_zero is False:
return 0
if diff.is_zero is None:
return None
return 1
class OrthogonalBra(OrthogonalState, BraBase):
"""Orthogonal Bra in quantum mechanics.
"""
@classmethod
def dual_class(self):
return OrthogonalKet
class Wavefunction(Function):
"""Class for representations in continuous bases
This class takes an expression and coordinates in its constructor. It can
be used to easily calculate normalizations and probabilities.
Parameters
==========
expr : Expr
The expression representing the functional form of the w.f.
coords : Symbol or tuple
The coordinates to be integrated over, and their bounds
Examples
========
Particle in a box, specifying bounds in the more primitive way of using
Piecewise:
>>> from sympy import Symbol, Piecewise, pi, N
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x = Symbol('x', real=True)
>>> n = 1
>>> L = 1
>>> g = Piecewise((0, x < 0), (0, x > L), (sqrt(2//L)*sin(n*pi*x/L), True))
>>> f = Wavefunction(g, x)
>>> f.norm
1
>>> f.is_normalized
True
>>> p = f.prob()
>>> p(0)
0
>>> p(L)
0
>>> p(0.5)
2
>>> p(0.85*L)
2*sin(0.85*pi)**2
>>> N(p(0.85*L))
0.412214747707527
Additionally, you can specify the bounds of the function and the indices in
a more compact way:
>>> from sympy import symbols, pi, diff
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sqrt(2/L)*sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.norm
1
>>> f(L+1)
0
>>> f(L-1)
sqrt(2)*sin(pi*n*(L - 1)/L)/sqrt(L)
>>> f(-1)
0
>>> f(0.85)
sqrt(2)*sin(0.85*pi*n/L)/sqrt(L)
>>> f(0.85, n=1, L=1)
sqrt(2)*sin(0.85*pi)
>>> f.is_commutative
False
All arguments are automatically sympified, so you can define the variables
as strings rather than symbols:
>>> expr = x**2
>>> f = Wavefunction(expr, 'x')
>>> type(f.variables[0])
<class 'sympy.core.symbol.Symbol'>
Derivatives of Wavefunctions will return Wavefunctions:
>>> diff(f, x)
Wavefunction(2*x, x)
"""
#Any passed tuples for coordinates and their bounds need to be
#converted to Tuples before Function's constructor is called, to
#avoid errors from calling is_Float in the constructor
def __new__(cls, *args, **options):
new_args = [None for i in args]
ct = 0
for arg in args:
if isinstance(arg, tuple):
new_args[ct] = Tuple(*arg)
else:
new_args[ct] = arg
ct += 1
return super().__new__(cls, *new_args, **options)
def __call__(self, *args, **options):
var = self.variables
if len(args) != len(var):
raise NotImplementedError(
"Incorrect number of arguments to function!")
ct = 0
#If the passed value is outside the specified bounds, return 0
for v in var:
lower, upper = self.limits[v]
#Do the comparison to limits only if the passed symbol is actually
#a symbol present in the limits;
#Had problems with a comparison of x > L
if isinstance(args[ct], Expr) and \
not (lower in args[ct].free_symbols
or upper in args[ct].free_symbols):
continue
if (args[ct] < lower) == True or (args[ct] > upper) == True:
return S.Zero
ct += 1
expr = self.expr
#Allows user to make a call like f(2, 4, m=1, n=1)
for symbol in list(expr.free_symbols):
if str(symbol) in options.keys():
val = options[str(symbol)]
expr = expr.subs(symbol, val)
return expr.subs(zip(var, args))
def _eval_derivative(self, symbol):
expr = self.expr
deriv = expr._eval_derivative(symbol)
return Wavefunction(deriv, *self.args[1:])
def _eval_conjugate(self):
return Wavefunction(conjugate(self.expr), *self.args[1:])
def _eval_transpose(self):
return self
@property
def free_symbols(self):
return self.expr.free_symbols
@property
def is_commutative(self):
"""
Override Function's is_commutative so that order is preserved in
represented expressions
"""
return False
@classmethod
def eval(self, *args):
return None
@property
def variables(self):
"""
Return the coordinates which the wavefunction depends on
Examples
========
>>> from sympy.physics.quantum.state import Wavefunction
>>> from sympy import symbols
>>> x,y = symbols('x,y')
>>> f = Wavefunction(x*y, x, y)
>>> f.variables
(x, y)
>>> g = Wavefunction(x*y, x)
>>> g.variables
(x,)
"""
var = [g[0] if isinstance(g, Tuple) else g for g in self._args[1:]]
return tuple(var)
@property
def limits(self):
"""
Return the limits of the coordinates which the w.f. depends on If no
limits are specified, defaults to ``(-oo, oo)``.
Examples
========
>>> from sympy.physics.quantum.state import Wavefunction
>>> from sympy import symbols
>>> x, y = symbols('x, y')
>>> f = Wavefunction(x**2, (x, 0, 1))
>>> f.limits
{x: (0, 1)}
>>> f = Wavefunction(x**2, x)
>>> f.limits
{x: (-oo, oo)}
>>> f = Wavefunction(x**2 + y**2, x, (y, -1, 2))
>>> f.limits
{x: (-oo, oo), y: (-1, 2)}
"""
limits = [(g[1], g[2]) if isinstance(g, Tuple) else (-oo, oo)
for g in self._args[1:]]
return dict(zip(self.variables, tuple(limits)))
@property
def expr(self):
"""
Return the expression which is the functional form of the Wavefunction
Examples
========
>>> from sympy.physics.quantum.state import Wavefunction
>>> from sympy import symbols
>>> x, y = symbols('x, y')
>>> f = Wavefunction(x**2, x)
>>> f.expr
x**2
"""
return self._args[0]
@property
def is_normalized(self):
"""
Returns true if the Wavefunction is properly normalized
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sqrt(2/L)*sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.is_normalized
True
"""
return (self.norm == 1.0)
@property # type: ignore
@cacheit
def norm(self):
"""
Return the normalization of the specified functional form.
This function integrates over the coordinates of the Wavefunction, with
the bounds specified.
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sqrt, sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sqrt(2/L)*sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.norm
1
>>> g = sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.norm
sqrt(2)*sqrt(L)/2
"""
exp = self.expr*conjugate(self.expr)
var = self.variables
limits = self.limits
for v in var:
curr_limits = limits[v]
exp = integrate(exp, (v, curr_limits[0], curr_limits[1]))
return sqrt(exp)
def normalize(self):
"""
Return a normalized version of the Wavefunction
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x = symbols('x', real=True)
>>> L = symbols('L', positive=True)
>>> n = symbols('n', integer=True, positive=True)
>>> g = sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.normalize()
Wavefunction(sqrt(2)*sin(pi*n*x/L)/sqrt(L), (x, 0, L))
"""
const = self.norm
if const is oo:
raise NotImplementedError("The function is not normalizable!")
else:
return Wavefunction((const)**(-1)*self.expr, *self.args[1:])
def prob(self):
r"""
Return the absolute magnitude of the w.f., `|\psi(x)|^2`
Examples
========
>>> from sympy import symbols, pi
>>> from sympy.functions import sin
>>> from sympy.physics.quantum.state import Wavefunction
>>> x, L = symbols('x,L', real=True)
>>> n = symbols('n', integer=True)
>>> g = sin(n*pi*x/L)
>>> f = Wavefunction(g, (x, 0, L))
>>> f.prob()
Wavefunction(sin(pi*n*x/L)**2, x)
"""
return Wavefunction(self.expr*conjugate(self.expr), *self.variables)
|
74ea6d4d5f7625c13c9c9f69dfdb8dee13d9a8893fa8d66e6beaac346fcebf80 | """An implementation of gates that act on qubits.
Gates are unitary operators that act on the space of qubits.
Medium Term Todo:
* Optimize Gate._apply_operators_Qubit to remove the creation of many
intermediate Qubit objects.
* Add commutation relationships to all operators and use this in gate_sort.
* Fix gate_sort and gate_simp.
* Get multi-target UGates plotting properly.
* Get UGate to work with either sympy/numpy matrices and output either
format. This should also use the matrix slots.
"""
from itertools import chain
import random
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Integer)
from sympy.core.power import Pow
from sympy.core.numbers import Number
from sympy.core.singleton import S as _S
from sympy.core.sorting import default_sort_key
from sympy.core.sympify import _sympify
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.printing.pretty.stringpict import prettyForm, stringPict
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.qexpr import QuantumError
from sympy.physics.quantum.hilbert import ComplexSpace
from sympy.physics.quantum.operator import (UnitaryOperator, Operator,
HermitianOperator)
from sympy.physics.quantum.matrixutils import matrix_tensor_product, matrix_eye
from sympy.physics.quantum.matrixcache import matrix_cache
from sympy.matrices.matrices import MatrixBase
from sympy.utilities.iterables import is_sequence
__all__ = [
'Gate',
'CGate',
'UGate',
'OneQubitGate',
'TwoQubitGate',
'IdentityGate',
'HadamardGate',
'XGate',
'YGate',
'ZGate',
'TGate',
'PhaseGate',
'SwapGate',
'CNotGate',
# Aliased gate names
'CNOT',
'SWAP',
'H',
'X',
'Y',
'Z',
'T',
'S',
'Phase',
'normalized',
'gate_sort',
'gate_simp',
'random_circuit',
'CPHASE',
'CGateS',
]
#-----------------------------------------------------------------------------
# Gate Super-Classes
#-----------------------------------------------------------------------------
_normalized = True
def _max(*args, **kwargs):
if "key" not in kwargs:
kwargs["key"] = default_sort_key
return max(*args, **kwargs)
def _min(*args, **kwargs):
if "key" not in kwargs:
kwargs["key"] = default_sort_key
return min(*args, **kwargs)
def normalized(normalize):
"""Set flag controlling normalization of Hadamard gates by 1/sqrt(2).
This is a global setting that can be used to simplify the look of various
expressions, by leaving off the leading 1/sqrt(2) of the Hadamard gate.
Parameters
----------
normalize : bool
Should the Hadamard gate include the 1/sqrt(2) normalization factor?
When True, the Hadamard gate will have the 1/sqrt(2). When False, the
Hadamard gate will not have this factor.
"""
global _normalized
_normalized = normalize
def _validate_targets_controls(tandc):
tandc = list(tandc)
# Check for integers
for bit in tandc:
if not bit.is_Integer and not bit.is_Symbol:
raise TypeError('Integer expected, got: %r' % tandc[bit])
# Detect duplicates
if len(list(set(tandc))) != len(tandc):
raise QuantumError(
'Target/control qubits in a gate cannot be duplicated'
)
class Gate(UnitaryOperator):
"""Non-controlled unitary gate operator that acts on qubits.
This is a general abstract gate that needs to be subclassed to do anything
useful.
Parameters
----------
label : tuple, int
A list of the target qubits (as ints) that the gate will apply to.
Examples
========
"""
_label_separator = ','
gate_name = 'G'
gate_name_latex = 'G'
#-------------------------------------------------------------------------
# Initialization/creation
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
args = Tuple(*UnitaryOperator._eval_args(args))
_validate_targets_controls(args)
return args
@classmethod
def _eval_hilbert_space(cls, args):
"""This returns the smallest possible Hilbert space."""
return ComplexSpace(2)**(_max(args) + 1)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def nqubits(self):
"""The total number of qubits this gate acts on.
For controlled gate subclasses this includes both target and control
qubits, so that, for examples the CNOT gate acts on 2 qubits.
"""
return len(self.targets)
@property
def min_qubits(self):
"""The minimum number of qubits this gate needs to act on."""
return _max(self.targets) + 1
@property
def targets(self):
"""A tuple of target qubits."""
return self.label
@property
def gate_name_plot(self):
return r'$%s$' % self.gate_name_latex
#-------------------------------------------------------------------------
# Gate methods
#-------------------------------------------------------------------------
def get_target_matrix(self, format='sympy'):
"""The matrix rep. of the target part of the gate.
Parameters
----------
format : str
The format string ('sympy','numpy', etc.)
"""
raise NotImplementedError(
'get_target_matrix is not implemented in Gate.')
#-------------------------------------------------------------------------
# Apply
#-------------------------------------------------------------------------
def _apply_operator_IntQubit(self, qubits, **options):
"""Redirect an apply from IntQubit to Qubit"""
return self._apply_operator_Qubit(qubits, **options)
def _apply_operator_Qubit(self, qubits, **options):
"""Apply this gate to a Qubit."""
# Check number of qubits this gate acts on.
if qubits.nqubits < self.min_qubits:
raise QuantumError(
'Gate needs a minimum of %r qubits to act on, got: %r' %
(self.min_qubits, qubits.nqubits)
)
# If the controls are not met, just return
if isinstance(self, CGate):
if not self.eval_controls(qubits):
return qubits
targets = self.targets
target_matrix = self.get_target_matrix(format='sympy')
# Find which column of the target matrix this applies to.
column_index = 0
n = 1
for target in targets:
column_index += n*qubits[target]
n = n << 1
column = target_matrix[:, int(column_index)]
# Now apply each column element to the qubit.
result = 0
for index in range(column.rows):
# TODO: This can be optimized to reduce the number of Qubit
# creations. We should simply manipulate the raw list of qubit
# values and then build the new Qubit object once.
# Make a copy of the incoming qubits.
new_qubit = qubits.__class__(*qubits.args)
# Flip the bits that need to be flipped.
for bit in range(len(targets)):
if new_qubit[targets[bit]] != (index >> bit) & 1:
new_qubit = new_qubit.flip(targets[bit])
# The value in that row and column times the flipped-bit qubit
# is the result for that part.
result += column[index]*new_qubit
return result
#-------------------------------------------------------------------------
# Represent
#-------------------------------------------------------------------------
def _represent_default_basis(self, **options):
return self._represent_ZGate(None, **options)
def _represent_ZGate(self, basis, **options):
format = options.get('format', 'sympy')
nqubits = options.get('nqubits', 0)
if nqubits == 0:
raise QuantumError(
'The number of qubits must be given as nqubits.')
# Make sure we have enough qubits for the gate.
if nqubits < self.min_qubits:
raise QuantumError(
'The number of qubits %r is too small for the gate.' % nqubits
)
target_matrix = self.get_target_matrix(format)
targets = self.targets
if isinstance(self, CGate):
controls = self.controls
else:
controls = []
m = represent_zbasis(
controls, targets, target_matrix, nqubits, format
)
return m
#-------------------------------------------------------------------------
# Print methods
#-------------------------------------------------------------------------
def _sympystr(self, printer, *args):
label = self._print_label(printer, *args)
return '%s(%s)' % (self.gate_name, label)
def _pretty(self, printer, *args):
a = stringPict(self.gate_name)
b = self._print_label_pretty(printer, *args)
return self._print_subscript_pretty(a, b)
def _latex(self, printer, *args):
label = self._print_label(printer, *args)
return '%s_{%s}' % (self.gate_name_latex, label)
def plot_gate(self, axes, gate_idx, gate_grid, wire_grid):
raise NotImplementedError('plot_gate is not implemented.')
class CGate(Gate):
"""A general unitary gate with control qubits.
A general control gate applies a target gate to a set of targets if all
of the control qubits have a particular values (set by
``CGate.control_value``).
Parameters
----------
label : tuple
The label in this case has the form (controls, gate), where controls
is a tuple/list of control qubits (as ints) and gate is a ``Gate``
instance that is the target operator.
Examples
========
"""
gate_name = 'C'
gate_name_latex = 'C'
# The values this class controls for.
control_value = _S.One
simplify_cgate = False
#-------------------------------------------------------------------------
# Initialization
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
# _eval_args has the right logic for the controls argument.
controls = args[0]
gate = args[1]
if not is_sequence(controls):
controls = (controls,)
controls = UnitaryOperator._eval_args(controls)
_validate_targets_controls(chain(controls, gate.targets))
return (Tuple(*controls), gate)
@classmethod
def _eval_hilbert_space(cls, args):
"""This returns the smallest possible Hilbert space."""
return ComplexSpace(2)**_max(_max(args[0]) + 1, args[1].min_qubits)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def nqubits(self):
"""The total number of qubits this gate acts on.
For controlled gate subclasses this includes both target and control
qubits, so that, for examples the CNOT gate acts on 2 qubits.
"""
return len(self.targets) + len(self.controls)
@property
def min_qubits(self):
"""The minimum number of qubits this gate needs to act on."""
return _max(_max(self.controls), _max(self.targets)) + 1
@property
def targets(self):
"""A tuple of target qubits."""
return self.gate.targets
@property
def controls(self):
"""A tuple of control qubits."""
return tuple(self.label[0])
@property
def gate(self):
"""The non-controlled gate that will be applied to the targets."""
return self.label[1]
#-------------------------------------------------------------------------
# Gate methods
#-------------------------------------------------------------------------
def get_target_matrix(self, format='sympy'):
return self.gate.get_target_matrix(format)
def eval_controls(self, qubit):
"""Return True/False to indicate if the controls are satisfied."""
return all(qubit[bit] == self.control_value for bit in self.controls)
def decompose(self, **options):
"""Decompose the controlled gate into CNOT and single qubits gates."""
if len(self.controls) == 1:
c = self.controls[0]
t = self.gate.targets[0]
if isinstance(self.gate, YGate):
g1 = PhaseGate(t)
g2 = CNotGate(c, t)
g3 = PhaseGate(t)
g4 = ZGate(t)
return g1*g2*g3*g4
if isinstance(self.gate, ZGate):
g1 = HadamardGate(t)
g2 = CNotGate(c, t)
g3 = HadamardGate(t)
return g1*g2*g3
else:
return self
#-------------------------------------------------------------------------
# Print methods
#-------------------------------------------------------------------------
def _print_label(self, printer, *args):
controls = self._print_sequence(self.controls, ',', printer, *args)
gate = printer._print(self.gate, *args)
return '(%s),%s' % (controls, gate)
def _pretty(self, printer, *args):
controls = self._print_sequence_pretty(
self.controls, ',', printer, *args)
gate = printer._print(self.gate)
gate_name = stringPict(self.gate_name)
first = self._print_subscript_pretty(gate_name, controls)
gate = self._print_parens_pretty(gate)
final = prettyForm(*first.right(gate))
return final
def _latex(self, printer, *args):
controls = self._print_sequence(self.controls, ',', printer, *args)
gate = printer._print(self.gate, *args)
return r'%s_{%s}{\left(%s\right)}' % \
(self.gate_name_latex, controls, gate)
def plot_gate(self, circ_plot, gate_idx):
"""
Plot the controlled gate. If *simplify_cgate* is true, simplify
C-X and C-Z gates into their more familiar forms.
"""
min_wire = int(_min(chain(self.controls, self.targets)))
max_wire = int(_max(chain(self.controls, self.targets)))
circ_plot.control_line(gate_idx, min_wire, max_wire)
for c in self.controls:
circ_plot.control_point(gate_idx, int(c))
if self.simplify_cgate:
if self.gate.gate_name == 'X':
self.gate.plot_gate_plus(circ_plot, gate_idx)
elif self.gate.gate_name == 'Z':
circ_plot.control_point(gate_idx, self.targets[0])
else:
self.gate.plot_gate(circ_plot, gate_idx)
else:
self.gate.plot_gate(circ_plot, gate_idx)
#-------------------------------------------------------------------------
# Miscellaneous
#-------------------------------------------------------------------------
def _eval_dagger(self):
if isinstance(self.gate, HermitianOperator):
return self
else:
return Gate._eval_dagger(self)
def _eval_inverse(self):
if isinstance(self.gate, HermitianOperator):
return self
else:
return Gate._eval_inverse(self)
def _eval_power(self, exp):
if isinstance(self.gate, HermitianOperator):
if exp == -1:
return Gate._eval_power(self, exp)
elif abs(exp) % 2 == 0:
return self*(Gate._eval_inverse(self))
else:
return self
else:
return Gate._eval_power(self, exp)
class CGateS(CGate):
"""Version of CGate that allows gate simplifications.
I.e. cnot looks like an oplus, cphase has dots, etc.
"""
simplify_cgate=True
class UGate(Gate):
"""General gate specified by a set of targets and a target matrix.
Parameters
----------
label : tuple
A tuple of the form (targets, U), where targets is a tuple of the
target qubits and U is a unitary matrix with dimension of
len(targets).
"""
gate_name = 'U'
gate_name_latex = 'U'
#-------------------------------------------------------------------------
# Initialization
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
targets = args[0]
if not is_sequence(targets):
targets = (targets,)
targets = Gate._eval_args(targets)
_validate_targets_controls(targets)
mat = args[1]
if not isinstance(mat, MatrixBase):
raise TypeError('Matrix expected, got: %r' % mat)
#make sure this matrix is of a Basic type
mat = _sympify(mat)
dim = 2**len(targets)
if not all(dim == shape for shape in mat.shape):
raise IndexError(
'Number of targets must match the matrix size: %r %r' %
(targets, mat)
)
return (targets, mat)
@classmethod
def _eval_hilbert_space(cls, args):
"""This returns the smallest possible Hilbert space."""
return ComplexSpace(2)**(_max(args[0]) + 1)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def targets(self):
"""A tuple of target qubits."""
return tuple(self.label[0])
#-------------------------------------------------------------------------
# Gate methods
#-------------------------------------------------------------------------
def get_target_matrix(self, format='sympy'):
"""The matrix rep. of the target part of the gate.
Parameters
----------
format : str
The format string ('sympy','numpy', etc.)
"""
return self.label[1]
#-------------------------------------------------------------------------
# Print methods
#-------------------------------------------------------------------------
def _pretty(self, printer, *args):
targets = self._print_sequence_pretty(
self.targets, ',', printer, *args)
gate_name = stringPict(self.gate_name)
return self._print_subscript_pretty(gate_name, targets)
def _latex(self, printer, *args):
targets = self._print_sequence(self.targets, ',', printer, *args)
return r'%s_{%s}' % (self.gate_name_latex, targets)
def plot_gate(self, circ_plot, gate_idx):
circ_plot.one_qubit_box(
self.gate_name_plot,
gate_idx, int(self.targets[0])
)
class OneQubitGate(Gate):
"""A single qubit unitary gate base class."""
nqubits = _S.One
def plot_gate(self, circ_plot, gate_idx):
circ_plot.one_qubit_box(
self.gate_name_plot,
gate_idx, int(self.targets[0])
)
def _eval_commutator(self, other, **hints):
if isinstance(other, OneQubitGate):
if self.targets != other.targets or self.__class__ == other.__class__:
return _S.Zero
return Operator._eval_commutator(self, other, **hints)
def _eval_anticommutator(self, other, **hints):
if isinstance(other, OneQubitGate):
if self.targets != other.targets or self.__class__ == other.__class__:
return Integer(2)*self*other
return Operator._eval_anticommutator(self, other, **hints)
class TwoQubitGate(Gate):
"""A two qubit unitary gate base class."""
nqubits = Integer(2)
#-----------------------------------------------------------------------------
# Single Qubit Gates
#-----------------------------------------------------------------------------
class IdentityGate(OneQubitGate):
"""The single qubit identity gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = '1'
gate_name_latex = '1'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('eye2', format)
def _eval_commutator(self, other, **hints):
return _S.Zero
def _eval_anticommutator(self, other, **hints):
return Integer(2)*other
class HadamardGate(HermitianOperator, OneQubitGate):
"""The single qubit Hadamard gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
>>> from sympy import sqrt
>>> from sympy.physics.quantum.qubit import Qubit
>>> from sympy.physics.quantum.gate import HadamardGate
>>> from sympy.physics.quantum.qapply import qapply
>>> qapply(HadamardGate(0)*Qubit('1'))
sqrt(2)*|0>/2 - sqrt(2)*|1>/2
>>> # Hadamard on bell state, applied on 2 qubits.
>>> psi = 1/sqrt(2)*(Qubit('00')+Qubit('11'))
>>> qapply(HadamardGate(0)*HadamardGate(1)*psi)
sqrt(2)*|00>/2 + sqrt(2)*|11>/2
"""
gate_name = 'H'
gate_name_latex = 'H'
def get_target_matrix(self, format='sympy'):
if _normalized:
return matrix_cache.get_matrix('H', format)
else:
return matrix_cache.get_matrix('Hsqrt2', format)
def _eval_commutator_XGate(self, other, **hints):
return I*sqrt(2)*YGate(self.targets[0])
def _eval_commutator_YGate(self, other, **hints):
return I*sqrt(2)*(ZGate(self.targets[0]) - XGate(self.targets[0]))
def _eval_commutator_ZGate(self, other, **hints):
return -I*sqrt(2)*YGate(self.targets[0])
def _eval_anticommutator_XGate(self, other, **hints):
return sqrt(2)*IdentityGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints):
return _S.Zero
def _eval_anticommutator_ZGate(self, other, **hints):
return sqrt(2)*IdentityGate(self.targets[0])
class XGate(HermitianOperator, OneQubitGate):
"""The single qubit X, or NOT, gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'X'
gate_name_latex = 'X'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('X', format)
def plot_gate(self, circ_plot, gate_idx):
OneQubitGate.plot_gate(self,circ_plot,gate_idx)
def plot_gate_plus(self, circ_plot, gate_idx):
circ_plot.not_point(
gate_idx, int(self.label[0])
)
def _eval_commutator_YGate(self, other, **hints):
return Integer(2)*I*ZGate(self.targets[0])
def _eval_anticommutator_XGate(self, other, **hints):
return Integer(2)*IdentityGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints):
return _S.Zero
def _eval_anticommutator_ZGate(self, other, **hints):
return _S.Zero
class YGate(HermitianOperator, OneQubitGate):
"""The single qubit Y gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'Y'
gate_name_latex = 'Y'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('Y', format)
def _eval_commutator_ZGate(self, other, **hints):
return Integer(2)*I*XGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints):
return Integer(2)*IdentityGate(self.targets[0])
def _eval_anticommutator_ZGate(self, other, **hints):
return _S.Zero
class ZGate(HermitianOperator, OneQubitGate):
"""The single qubit Z gate.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'Z'
gate_name_latex = 'Z'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('Z', format)
def _eval_commutator_XGate(self, other, **hints):
return Integer(2)*I*YGate(self.targets[0])
def _eval_anticommutator_YGate(self, other, **hints):
return _S.Zero
class PhaseGate(OneQubitGate):
"""The single qubit phase, or S, gate.
This gate rotates the phase of the state by pi/2 if the state is ``|1>`` and
does nothing if the state is ``|0>``.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'S'
gate_name_latex = 'S'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('S', format)
def _eval_commutator_ZGate(self, other, **hints):
return _S.Zero
def _eval_commutator_TGate(self, other, **hints):
return _S.Zero
class TGate(OneQubitGate):
"""The single qubit pi/8 gate.
This gate rotates the phase of the state by pi/4 if the state is ``|1>`` and
does nothing if the state is ``|0>``.
Parameters
----------
target : int
The target qubit this gate will apply to.
Examples
========
"""
gate_name = 'T'
gate_name_latex = 'T'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('T', format)
def _eval_commutator_ZGate(self, other, **hints):
return _S.Zero
def _eval_commutator_PhaseGate(self, other, **hints):
return _S.Zero
# Aliases for gate names.
H = HadamardGate
X = XGate
Y = YGate
Z = ZGate
T = TGate
Phase = S = PhaseGate
#-----------------------------------------------------------------------------
# 2 Qubit Gates
#-----------------------------------------------------------------------------
class CNotGate(HermitianOperator, CGate, TwoQubitGate):
"""Two qubit controlled-NOT.
This gate performs the NOT or X gate on the target qubit if the control
qubits all have the value 1.
Parameters
----------
label : tuple
A tuple of the form (control, target).
Examples
========
>>> from sympy.physics.quantum.gate import CNOT
>>> from sympy.physics.quantum.qapply import qapply
>>> from sympy.physics.quantum.qubit import Qubit
>>> c = CNOT(1,0)
>>> qapply(c*Qubit('10')) # note that qubits are indexed from right to left
|11>
"""
gate_name = 'CNOT'
gate_name_latex = r'\text{CNOT}'
simplify_cgate = True
#-------------------------------------------------------------------------
# Initialization
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
args = Gate._eval_args(args)
return args
@classmethod
def _eval_hilbert_space(cls, args):
"""This returns the smallest possible Hilbert space."""
return ComplexSpace(2)**(_max(args) + 1)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def min_qubits(self):
"""The minimum number of qubits this gate needs to act on."""
return _max(self.label) + 1
@property
def targets(self):
"""A tuple of target qubits."""
return (self.label[1],)
@property
def controls(self):
"""A tuple of control qubits."""
return (self.label[0],)
@property
def gate(self):
"""The non-controlled gate that will be applied to the targets."""
return XGate(self.label[1])
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
# The default printing of Gate works better than those of CGate, so we
# go around the overridden methods in CGate.
def _print_label(self, printer, *args):
return Gate._print_label(self, printer, *args)
def _pretty(self, printer, *args):
return Gate._pretty(self, printer, *args)
def _latex(self, printer, *args):
return Gate._latex(self, printer, *args)
#-------------------------------------------------------------------------
# Commutator/AntiCommutator
#-------------------------------------------------------------------------
def _eval_commutator_ZGate(self, other, **hints):
"""[CNOT(i, j), Z(i)] == 0."""
if self.controls[0] == other.targets[0]:
return _S.Zero
else:
raise NotImplementedError('Commutator not implemented: %r' % other)
def _eval_commutator_TGate(self, other, **hints):
"""[CNOT(i, j), T(i)] == 0."""
return self._eval_commutator_ZGate(other, **hints)
def _eval_commutator_PhaseGate(self, other, **hints):
"""[CNOT(i, j), S(i)] == 0."""
return self._eval_commutator_ZGate(other, **hints)
def _eval_commutator_XGate(self, other, **hints):
"""[CNOT(i, j), X(j)] == 0."""
if self.targets[0] == other.targets[0]:
return _S.Zero
else:
raise NotImplementedError('Commutator not implemented: %r' % other)
def _eval_commutator_CNotGate(self, other, **hints):
"""[CNOT(i, j), CNOT(i,k)] == 0."""
if self.controls[0] == other.controls[0]:
return _S.Zero
else:
raise NotImplementedError('Commutator not implemented: %r' % other)
class SwapGate(TwoQubitGate):
"""Two qubit SWAP gate.
This gate swap the values of the two qubits.
Parameters
----------
label : tuple
A tuple of the form (target1, target2).
Examples
========
"""
gate_name = 'SWAP'
gate_name_latex = r'\text{SWAP}'
def get_target_matrix(self, format='sympy'):
return matrix_cache.get_matrix('SWAP', format)
def decompose(self, **options):
"""Decompose the SWAP gate into CNOT gates."""
i, j = self.targets[0], self.targets[1]
g1 = CNotGate(i, j)
g2 = CNotGate(j, i)
return g1*g2*g1
def plot_gate(self, circ_plot, gate_idx):
min_wire = int(_min(self.targets))
max_wire = int(_max(self.targets))
circ_plot.control_line(gate_idx, min_wire, max_wire)
circ_plot.swap_point(gate_idx, min_wire)
circ_plot.swap_point(gate_idx, max_wire)
def _represent_ZGate(self, basis, **options):
"""Represent the SWAP gate in the computational basis.
The following representation is used to compute this:
SWAP = |1><1|x|1><1| + |0><0|x|0><0| + |1><0|x|0><1| + |0><1|x|1><0|
"""
format = options.get('format', 'sympy')
targets = [int(t) for t in self.targets]
min_target = _min(targets)
max_target = _max(targets)
nqubits = options.get('nqubits', self.min_qubits)
op01 = matrix_cache.get_matrix('op01', format)
op10 = matrix_cache.get_matrix('op10', format)
op11 = matrix_cache.get_matrix('op11', format)
op00 = matrix_cache.get_matrix('op00', format)
eye2 = matrix_cache.get_matrix('eye2', format)
result = None
for i, j in ((op01, op10), (op10, op01), (op00, op00), (op11, op11)):
product = nqubits*[eye2]
product[nqubits - min_target - 1] = i
product[nqubits - max_target - 1] = j
new_result = matrix_tensor_product(*product)
if result is None:
result = new_result
else:
result = result + new_result
return result
# Aliases for gate names.
CNOT = CNotGate
SWAP = SwapGate
def CPHASE(a,b): return CGateS((a,),Z(b))
#-----------------------------------------------------------------------------
# Represent
#-----------------------------------------------------------------------------
def represent_zbasis(controls, targets, target_matrix, nqubits, format='sympy'):
"""Represent a gate with controls, targets and target_matrix.
This function does the low-level work of representing gates as matrices
in the standard computational basis (ZGate). Currently, we support two
main cases:
1. One target qubit and no control qubits.
2. One target qubits and multiple control qubits.
For the base of multiple controls, we use the following expression [1]:
1_{2**n} + (|1><1|)^{(n-1)} x (target-matrix - 1_{2})
Parameters
----------
controls : list, tuple
A sequence of control qubits.
targets : list, tuple
A sequence of target qubits.
target_matrix : sympy.Matrix, numpy.matrix, scipy.sparse
The matrix form of the transformation to be performed on the target
qubits. The format of this matrix must match that passed into
the `format` argument.
nqubits : int
The total number of qubits used for the representation.
format : str
The format of the final matrix ('sympy', 'numpy', 'scipy.sparse').
Examples
========
References
----------
[1] http://www.johnlapeyre.com/qinf/qinf_html/node6.html.
"""
controls = [int(x) for x in controls]
targets = [int(x) for x in targets]
nqubits = int(nqubits)
# This checks for the format as well.
op11 = matrix_cache.get_matrix('op11', format)
eye2 = matrix_cache.get_matrix('eye2', format)
# Plain single qubit case
if len(controls) == 0 and len(targets) == 1:
product = []
bit = targets[0]
# Fill product with [I1,Gate,I2] such that the unitaries,
# I, cause the gate to be applied to the correct Qubit
if bit != nqubits - 1:
product.append(matrix_eye(2**(nqubits - bit - 1), format=format))
product.append(target_matrix)
if bit != 0:
product.append(matrix_eye(2**bit, format=format))
return matrix_tensor_product(*product)
# Single target, multiple controls.
elif len(targets) == 1 and len(controls) >= 1:
target = targets[0]
# Build the non-trivial part.
product2 = []
for i in range(nqubits):
product2.append(matrix_eye(2, format=format))
for control in controls:
product2[nqubits - 1 - control] = op11
product2[nqubits - 1 - target] = target_matrix - eye2
return matrix_eye(2**nqubits, format=format) + \
matrix_tensor_product(*product2)
# Multi-target, multi-control is not yet implemented.
else:
raise NotImplementedError(
'The representation of multi-target, multi-control gates '
'is not implemented.'
)
#-----------------------------------------------------------------------------
# Gate manipulation functions.
#-----------------------------------------------------------------------------
def gate_simp(circuit):
"""Simplifies gates symbolically
It first sorts gates using gate_sort. It then applies basic
simplification rules to the circuit, e.g., XGate**2 = Identity
"""
# Bubble sort out gates that commute.
circuit = gate_sort(circuit)
# Do simplifications by subing a simplification into the first element
# which can be simplified. We recursively call gate_simp with new circuit
# as input more simplifications exist.
if isinstance(circuit, Add):
return sum(gate_simp(t) for t in circuit.args)
elif isinstance(circuit, Mul):
circuit_args = circuit.args
elif isinstance(circuit, Pow):
b, e = circuit.as_base_exp()
circuit_args = (gate_simp(b)**e,)
else:
return circuit
# Iterate through each element in circuit, simplify if possible.
for i in range(len(circuit_args)):
# H,X,Y or Z squared is 1.
# T**2 = S, S**2 = Z
if isinstance(circuit_args[i], Pow):
if isinstance(circuit_args[i].base,
(HadamardGate, XGate, YGate, ZGate)) \
and isinstance(circuit_args[i].exp, Number):
# Build a new circuit taking replacing the
# H,X,Y,Z squared with one.
newargs = (circuit_args[:i] +
(circuit_args[i].base**(circuit_args[i].exp % 2),) +
circuit_args[i + 1:])
# Recursively simplify the new circuit.
circuit = gate_simp(Mul(*newargs))
break
elif isinstance(circuit_args[i].base, PhaseGate):
# Build a new circuit taking old circuit but splicing
# in simplification.
newargs = circuit_args[:i]
# Replace PhaseGate**2 with ZGate.
newargs = newargs + (ZGate(circuit_args[i].base.args[0])**
(Integer(circuit_args[i].exp/2)), circuit_args[i].base**
(circuit_args[i].exp % 2))
# Append the last elements.
newargs = newargs + circuit_args[i + 1:]
# Recursively simplify the new circuit.
circuit = gate_simp(Mul(*newargs))
break
elif isinstance(circuit_args[i].base, TGate):
# Build a new circuit taking all the old elements.
newargs = circuit_args[:i]
# Put an Phasegate in place of any TGate**2.
newargs = newargs + (PhaseGate(circuit_args[i].base.args[0])**
Integer(circuit_args[i].exp/2), circuit_args[i].base**
(circuit_args[i].exp % 2))
# Append the last elements.
newargs = newargs + circuit_args[i + 1:]
# Recursively simplify the new circuit.
circuit = gate_simp(Mul(*newargs))
break
return circuit
def gate_sort(circuit):
"""Sorts the gates while keeping track of commutation relations
This function uses a bubble sort to rearrange the order of gate
application. Keeps track of Quantum computations special commutation
relations (e.g. things that apply to the same Qubit do not commute with
each other)
circuit is the Mul of gates that are to be sorted.
"""
# Make sure we have an Add or Mul.
if isinstance(circuit, Add):
return sum(gate_sort(t) for t in circuit.args)
if isinstance(circuit, Pow):
return gate_sort(circuit.base)**circuit.exp
elif isinstance(circuit, Gate):
return circuit
if not isinstance(circuit, Mul):
return circuit
changes = True
while changes:
changes = False
circ_array = circuit.args
for i in range(len(circ_array) - 1):
# Go through each element and switch ones that are in wrong order
if isinstance(circ_array[i], (Gate, Pow)) and \
isinstance(circ_array[i + 1], (Gate, Pow)):
# If we have a Pow object, look at only the base
first_base, first_exp = circ_array[i].as_base_exp()
second_base, second_exp = circ_array[i + 1].as_base_exp()
# Use SymPy's hash based sorting. This is not mathematical
# sorting, but is rather based on comparing hashes of objects.
# See Basic.compare for details.
if first_base.compare(second_base) > 0:
if Commutator(first_base, second_base).doit() == 0:
new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
(circuit.args[i],) + circuit.args[i + 2:])
circuit = Mul(*new_args)
changes = True
break
if AntiCommutator(first_base, second_base).doit() == 0:
new_args = (circuit.args[:i] + (circuit.args[i + 1],) +
(circuit.args[i],) + circuit.args[i + 2:])
sign = _S.NegativeOne**(first_exp*second_exp)
circuit = sign*Mul(*new_args)
changes = True
break
return circuit
#-----------------------------------------------------------------------------
# Utility functions
#-----------------------------------------------------------------------------
def random_circuit(ngates, nqubits, gate_space=(X, Y, Z, S, T, H, CNOT, SWAP)):
"""Return a random circuit of ngates and nqubits.
This uses an equally weighted sample of (X, Y, Z, S, T, H, CNOT, SWAP)
gates.
Parameters
----------
ngates : int
The number of gates in the circuit.
nqubits : int
The number of qubits in the circuit.
gate_space : tuple
A tuple of the gate classes that will be used in the circuit.
Repeating gate classes multiple times in this tuple will increase
the frequency they appear in the random circuit.
"""
qubit_space = range(nqubits)
result = []
for i in range(ngates):
g = random.choice(gate_space)
if g == CNotGate or g == SwapGate:
qubits = random.sample(qubit_space, 2)
g = g(*qubits)
else:
qubit = random.choice(qubit_space)
g = g(qubit)
result.append(g)
return Mul(*result)
def zx_basis_transform(self, format='sympy'):
"""Transformation matrix from Z to X basis."""
return matrix_cache.get_matrix('ZX', format)
def zy_basis_transform(self, format='sympy'):
"""Transformation matrix from Z to Y basis."""
return matrix_cache.get_matrix('ZY', format)
|
aa68191d3f4e2d6284e6b37ee0341a954ec6bd150fb7c996c80751940eb87e4f | """Logic for representing operators in state in various bases.
TODO:
* Get represent working with continuous hilbert spaces.
* Document default basis functionality.
"""
from sympy.core.add import Add
from sympy.core.expr import Expr
from sympy.core.mul import Mul
from sympy.core.numbers import I
from sympy.core.power import Pow
from sympy.integrals.integrals import integrate
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.innerproduct import InnerProduct
from sympy.physics.quantum.qexpr import QExpr
from sympy.physics.quantum.tensorproduct import TensorProduct
from sympy.physics.quantum.matrixutils import flatten_scalar
from sympy.physics.quantum.state import KetBase, BraBase, StateBase
from sympy.physics.quantum.operator import Operator, OuterProduct
from sympy.physics.quantum.qapply import qapply
from sympy.physics.quantum.operatorset import operators_to_state, state_to_operators
__all__ = [
'represent',
'rep_innerproduct',
'rep_expectation',
'integrate_result',
'get_basis',
'enumerate_states'
]
#-----------------------------------------------------------------------------
# Represent
#-----------------------------------------------------------------------------
def _sympy_to_scalar(e):
"""Convert from a SymPy scalar to a Python scalar."""
if isinstance(e, Expr):
if e.is_Integer:
return int(e)
elif e.is_Float:
return float(e)
elif e.is_Rational:
return float(e)
elif e.is_Number or e.is_NumberSymbol or e == I:
return complex(e)
raise TypeError('Expected number, got: %r' % e)
def represent(expr, **options):
"""Represent the quantum expression in the given basis.
In quantum mechanics abstract states and operators can be represented in
various basis sets. Under this operation the follow transforms happen:
* Ket -> column vector or function
* Bra -> row vector of function
* Operator -> matrix or differential operator
This function is the top-level interface for this action.
This function walks the SymPy expression tree looking for ``QExpr``
instances that have a ``_represent`` method. This method is then called
and the object is replaced by the representation returned by this method.
By default, the ``_represent`` method will dispatch to other methods
that handle the representation logic for a particular basis set. The
naming convention for these methods is the following::
def _represent_FooBasis(self, e, basis, **options)
This function will have the logic for representing instances of its class
in the basis set having a class named ``FooBasis``.
Parameters
==========
expr : Expr
The expression to represent.
basis : Operator, basis set
An object that contains the information about the basis set. If an
operator is used, the basis is assumed to be the orthonormal
eigenvectors of that operator. In general though, the basis argument
can be any object that contains the basis set information.
options : dict
Key/value pairs of options that are passed to the underlying method
that finds the representation. These options can be used to
control how the representation is done. For example, this is where
the size of the basis set would be set.
Returns
=======
e : Expr
The SymPy expression of the represented quantum expression.
Examples
========
Here we subclass ``Operator`` and ``Ket`` to create the z-spin operator
and its spin 1/2 up eigenstate. By defining the ``_represent_SzOp``
method, the ket can be represented in the z-spin basis.
>>> from sympy.physics.quantum import Operator, represent, Ket
>>> from sympy import Matrix
>>> class SzUpKet(Ket):
... def _represent_SzOp(self, basis, **options):
... return Matrix([1,0])
...
>>> class SzOp(Operator):
... pass
...
>>> sz = SzOp('Sz')
>>> up = SzUpKet('up')
>>> represent(up, basis=sz)
Matrix([
[1],
[0]])
Here we see an example of representations in a continuous
basis. We see that the result of representing various combinations
of cartesian position operators and kets give us continuous
expressions involving DiracDelta functions.
>>> from sympy.physics.quantum.cartesian import XOp, XKet, XBra
>>> X = XOp()
>>> x = XKet()
>>> y = XBra('y')
>>> represent(X*x)
x*DiracDelta(x - x_2)
>>> represent(X*x*y)
x*DiracDelta(x - x_3)*DiracDelta(x_1 - y)
"""
format = options.get('format', 'sympy')
if isinstance(expr, QExpr) and not isinstance(expr, OuterProduct):
options['replace_none'] = False
temp_basis = get_basis(expr, **options)
if temp_basis is not None:
options['basis'] = temp_basis
try:
return expr._represent(**options)
except NotImplementedError as strerr:
#If no _represent_FOO method exists, map to the
#appropriate basis state and try
#the other methods of representation
options['replace_none'] = True
if isinstance(expr, (KetBase, BraBase)):
try:
return rep_innerproduct(expr, **options)
except NotImplementedError:
raise NotImplementedError(strerr)
elif isinstance(expr, Operator):
try:
return rep_expectation(expr, **options)
except NotImplementedError:
raise NotImplementedError(strerr)
else:
raise NotImplementedError(strerr)
elif isinstance(expr, Add):
result = represent(expr.args[0], **options)
for args in expr.args[1:]:
# scipy.sparse doesn't support += so we use plain = here.
result = result + represent(args, **options)
return result
elif isinstance(expr, Pow):
base, exp = expr.as_base_exp()
if format in ('numpy', 'scipy.sparse'):
exp = _sympy_to_scalar(exp)
base = represent(base, **options)
# scipy.sparse doesn't support negative exponents
# and warns when inverting a matrix in csr format.
if format == 'scipy.sparse' and exp < 0:
from scipy.sparse.linalg import inv
exp = - exp
base = inv(base.tocsc()).tocsr()
return base ** exp
elif isinstance(expr, TensorProduct):
new_args = [represent(arg, **options) for arg in expr.args]
return TensorProduct(*new_args)
elif isinstance(expr, Dagger):
return Dagger(represent(expr.args[0], **options))
elif isinstance(expr, Commutator):
A = represent(expr.args[0], **options)
B = represent(expr.args[1], **options)
return A*B - B*A
elif isinstance(expr, AntiCommutator):
A = represent(expr.args[0], **options)
B = represent(expr.args[1], **options)
return A*B + B*A
elif isinstance(expr, InnerProduct):
return represent(Mul(expr.bra, expr.ket), **options)
elif not isinstance(expr, (Mul, OuterProduct)):
# For numpy and scipy.sparse, we can only handle numerical prefactors.
if format in ('numpy', 'scipy.sparse'):
return _sympy_to_scalar(expr)
return expr
if not isinstance(expr, (Mul, OuterProduct)):
raise TypeError('Mul expected, got: %r' % expr)
if "index" in options:
options["index"] += 1
else:
options["index"] = 1
if "unities" not in options:
options["unities"] = []
result = represent(expr.args[-1], **options)
last_arg = expr.args[-1]
for arg in reversed(expr.args[:-1]):
if isinstance(last_arg, Operator):
options["index"] += 1
options["unities"].append(options["index"])
elif isinstance(last_arg, BraBase) and isinstance(arg, KetBase):
options["index"] += 1
elif isinstance(last_arg, KetBase) and isinstance(arg, Operator):
options["unities"].append(options["index"])
elif isinstance(last_arg, KetBase) and isinstance(arg, BraBase):
options["unities"].append(options["index"])
result = represent(arg, **options)*result
last_arg = arg
# All three matrix formats create 1 by 1 matrices when inner products of
# vectors are taken. In these cases, we simply return a scalar.
result = flatten_scalar(result)
result = integrate_result(expr, result, **options)
return result
def rep_innerproduct(expr, **options):
"""
Returns an innerproduct like representation (e.g. ``<x'|x>``) for the
given state.
Attempts to calculate inner product with a bra from the specified
basis. Should only be passed an instance of KetBase or BraBase
Parameters
==========
expr : KetBase or BraBase
The expression to be represented
Examples
========
>>> from sympy.physics.quantum.represent import rep_innerproduct
>>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet
>>> rep_innerproduct(XKet())
DiracDelta(x - x_1)
>>> rep_innerproduct(XKet(), basis=PxOp())
sqrt(2)*exp(-I*px_1*x/hbar)/(2*sqrt(hbar)*sqrt(pi))
>>> rep_innerproduct(PxKet(), basis=XOp())
sqrt(2)*exp(I*px*x_1/hbar)/(2*sqrt(hbar)*sqrt(pi))
"""
if not isinstance(expr, (KetBase, BraBase)):
raise TypeError("expr passed is not a Bra or Ket")
basis = get_basis(expr, **options)
if not isinstance(basis, StateBase):
raise NotImplementedError("Can't form this representation!")
if "index" not in options:
options["index"] = 1
basis_kets = enumerate_states(basis, options["index"], 2)
if isinstance(expr, BraBase):
bra = expr
ket = (basis_kets[1] if basis_kets[0].dual == expr else basis_kets[0])
else:
bra = (basis_kets[1].dual if basis_kets[0]
== expr else basis_kets[0].dual)
ket = expr
prod = InnerProduct(bra, ket)
result = prod.doit()
format = options.get('format', 'sympy')
return expr._format_represent(result, format)
def rep_expectation(expr, **options):
"""
Returns an ``<x'|A|x>`` type representation for the given operator.
Parameters
==========
expr : Operator
Operator to be represented in the specified basis
Examples
========
>>> from sympy.physics.quantum.cartesian import XOp, PxOp, PxKet
>>> from sympy.physics.quantum.represent import rep_expectation
>>> rep_expectation(XOp())
x_1*DiracDelta(x_1 - x_2)
>>> rep_expectation(XOp(), basis=PxOp())
<px_2|*X*|px_1>
>>> rep_expectation(XOp(), basis=PxKet())
<px_2|*X*|px_1>
"""
if "index" not in options:
options["index"] = 1
if not isinstance(expr, Operator):
raise TypeError("The passed expression is not an operator")
basis_state = get_basis(expr, **options)
if basis_state is None or not isinstance(basis_state, StateBase):
raise NotImplementedError("Could not get basis kets for this operator")
basis_kets = enumerate_states(basis_state, options["index"], 2)
bra = basis_kets[1].dual
ket = basis_kets[0]
return qapply(bra*expr*ket)
def integrate_result(orig_expr, result, **options):
"""
Returns the result of integrating over any unities ``(|x><x|)`` in
the given expression. Intended for integrating over the result of
representations in continuous bases.
This function integrates over any unities that may have been
inserted into the quantum expression and returns the result.
It uses the interval of the Hilbert space of the basis state
passed to it in order to figure out the limits of integration.
The unities option must be
specified for this to work.
Note: This is mostly used internally by represent(). Examples are
given merely to show the use cases.
Parameters
==========
orig_expr : quantum expression
The original expression which was to be represented
result: Expr
The resulting representation that we wish to integrate over
Examples
========
>>> from sympy import symbols, DiracDelta
>>> from sympy.physics.quantum.represent import integrate_result
>>> from sympy.physics.quantum.cartesian import XOp, XKet
>>> x_ket = XKet()
>>> X_op = XOp()
>>> x, x_1, x_2 = symbols('x, x_1, x_2')
>>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2))
x*DiracDelta(x - x_1)*DiracDelta(x_1 - x_2)
>>> integrate_result(X_op*x_ket, x*DiracDelta(x-x_1)*DiracDelta(x_1-x_2),
... unities=[1])
x*DiracDelta(x - x_2)
"""
if not isinstance(result, Expr):
return result
options['replace_none'] = True
if "basis" not in options:
arg = orig_expr.args[-1]
options["basis"] = get_basis(arg, **options)
elif not isinstance(options["basis"], StateBase):
options["basis"] = get_basis(orig_expr, **options)
basis = options.pop("basis", None)
if basis is None:
return result
unities = options.pop("unities", [])
if len(unities) == 0:
return result
kets = enumerate_states(basis, unities)
coords = [k.label[0] for k in kets]
for coord in coords:
if coord in result.free_symbols:
#TODO: Add support for sets of operators
basis_op = state_to_operators(basis)
start = basis_op.hilbert_space.interval.start
end = basis_op.hilbert_space.interval.end
result = integrate(result, (coord, start, end))
return result
def get_basis(expr, *, basis=None, replace_none=True, **options):
"""
Returns a basis state instance corresponding to the basis specified in
options=s. If no basis is specified, the function tries to form a default
basis state of the given expression.
There are three behaviors:
1. The basis specified in options is already an instance of StateBase. If
this is the case, it is simply returned. If the class is specified but
not an instance, a default instance is returned.
2. The basis specified is an operator or set of operators. If this
is the case, the operator_to_state mapping method is used.
3. No basis is specified. If expr is a state, then a default instance of
its class is returned. If expr is an operator, then it is mapped to the
corresponding state. If it is neither, then we cannot obtain the basis
state.
If the basis cannot be mapped, then it is not changed.
This will be called from within represent, and represent will
only pass QExpr's.
TODO (?): Support for Muls and other types of expressions?
Parameters
==========
expr : Operator or StateBase
Expression whose basis is sought
Examples
========
>>> from sympy.physics.quantum.represent import get_basis
>>> from sympy.physics.quantum.cartesian import XOp, XKet, PxOp, PxKet
>>> x = XKet()
>>> X = XOp()
>>> get_basis(x)
|x>
>>> get_basis(X)
|x>
>>> get_basis(x, basis=PxOp())
|px>
>>> get_basis(x, basis=PxKet)
|px>
"""
if basis is None and not replace_none:
return None
if basis is None:
if isinstance(expr, KetBase):
return _make_default(expr.__class__)
elif isinstance(expr, BraBase):
return _make_default(expr.dual_class())
elif isinstance(expr, Operator):
state_inst = operators_to_state(expr)
return (state_inst if state_inst is not None else None)
else:
return None
elif (isinstance(basis, Operator) or
(not isinstance(basis, StateBase) and issubclass(basis, Operator))):
state = operators_to_state(basis)
if state is None:
return None
elif isinstance(state, StateBase):
return state
else:
return _make_default(state)
elif isinstance(basis, StateBase):
return basis
elif issubclass(basis, StateBase):
return _make_default(basis)
else:
return None
def _make_default(expr):
# XXX: Catching TypeError like this is a bad way of distinguishing
# instances from classes. The logic using this function should be
# rewritten somehow.
try:
expr = expr()
except TypeError:
return expr
return expr
def enumerate_states(*args, **options):
"""
Returns instances of the given state with dummy indices appended
Operates in two different modes:
1. Two arguments are passed to it. The first is the base state which is to
be indexed, and the second argument is a list of indices to append.
2. Three arguments are passed. The first is again the base state to be
indexed. The second is the start index for counting. The final argument
is the number of kets you wish to receive.
Tries to call state._enumerate_state. If this fails, returns an empty list
Parameters
==========
args : list
See list of operation modes above for explanation
Examples
========
>>> from sympy.physics.quantum.cartesian import XBra, XKet
>>> from sympy.physics.quantum.represent import enumerate_states
>>> test = XKet('foo')
>>> enumerate_states(test, 1, 3)
[|foo_1>, |foo_2>, |foo_3>]
>>> test2 = XBra('bar')
>>> enumerate_states(test2, [4, 5, 10])
[<bar_4|, <bar_5|, <bar_10|]
"""
state = args[0]
if len(args) not in (2, 3):
raise NotImplementedError("Wrong number of arguments!")
if not isinstance(state, StateBase):
raise TypeError("First argument is not a state!")
if len(args) == 3:
num_states = args[2]
options['start_index'] = args[1]
else:
num_states = len(args[1])
options['index_list'] = args[1]
try:
ret = state._enumerate_state(num_states, **options)
except NotImplementedError:
ret = []
return ret
|
fe483cbb0233847736516bf134427015b76e7732475dff03fa11b5875df946bb | """Qubits for quantum computing.
Todo:
* Finish implementing measurement logic. This should include POVM.
* Update docstrings.
* Update tests.
"""
import math
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.numbers import Integer
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.functions.elementary.complexes import conjugate
from sympy.functions.elementary.exponential import log
from sympy.core.basic import _sympify
from sympy.external.gmpy import SYMPY_INTS
from sympy.matrices import Matrix, zeros
from sympy.printing.pretty.stringpict import prettyForm
from sympy.physics.quantum.hilbert import ComplexSpace
from sympy.physics.quantum.state import Ket, Bra, State
from sympy.physics.quantum.qexpr import QuantumError
from sympy.physics.quantum.represent import represent
from sympy.physics.quantum.matrixutils import (
numpy_ndarray, scipy_sparse_matrix
)
from mpmath.libmp.libintmath import bitcount
__all__ = [
'Qubit',
'QubitBra',
'IntQubit',
'IntQubitBra',
'qubit_to_matrix',
'matrix_to_qubit',
'matrix_to_density',
'measure_all',
'measure_partial',
'measure_partial_oneshot',
'measure_all_oneshot'
]
#-----------------------------------------------------------------------------
# Qubit Classes
#-----------------------------------------------------------------------------
class QubitState(State):
"""Base class for Qubit and QubitBra."""
#-------------------------------------------------------------------------
# Initialization/creation
#-------------------------------------------------------------------------
@classmethod
def _eval_args(cls, args):
# If we are passed a QubitState or subclass, we just take its qubit
# values directly.
if len(args) == 1 and isinstance(args[0], QubitState):
return args[0].qubit_values
# Turn strings into tuple of strings
if len(args) == 1 and isinstance(args[0], str):
args = tuple( S.Zero if qb == "0" else S.One for qb in args[0])
else:
args = tuple( S.Zero if qb == "0" else S.One if qb == "1" else qb for qb in args)
args = tuple(_sympify(arg) for arg in args)
# Validate input (must have 0 or 1 input)
for element in args:
if element not in (S.Zero, S.One):
raise ValueError(
"Qubit values must be 0 or 1, got: %r" % element)
return args
@classmethod
def _eval_hilbert_space(cls, args):
return ComplexSpace(2)**len(args)
#-------------------------------------------------------------------------
# Properties
#-------------------------------------------------------------------------
@property
def dimension(self):
"""The number of Qubits in the state."""
return len(self.qubit_values)
@property
def nqubits(self):
return self.dimension
@property
def qubit_values(self):
"""Returns the values of the qubits as a tuple."""
return self.label
#-------------------------------------------------------------------------
# Special methods
#-------------------------------------------------------------------------
def __len__(self):
return self.dimension
def __getitem__(self, bit):
return self.qubit_values[int(self.dimension - bit - 1)]
#-------------------------------------------------------------------------
# Utility methods
#-------------------------------------------------------------------------
def flip(self, *bits):
"""Flip the bit(s) given."""
newargs = list(self.qubit_values)
for i in bits:
bit = int(self.dimension - i - 1)
if newargs[bit] == 1:
newargs[bit] = 0
else:
newargs[bit] = 1
return self.__class__(*tuple(newargs))
class Qubit(QubitState, Ket):
"""A multi-qubit ket in the computational (z) basis.
We use the normal convention that the least significant qubit is on the
right, so ``|00001>`` has a 1 in the least significant qubit.
Parameters
==========
values : list, str
The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011').
Examples
========
Create a qubit in a couple of different ways and look at their attributes:
>>> from sympy.physics.quantum.qubit import Qubit
>>> Qubit(0,0,0)
|000>
>>> q = Qubit('0101')
>>> q
|0101>
>>> q.nqubits
4
>>> len(q)
4
>>> q.dimension
4
>>> q.qubit_values
(0, 1, 0, 1)
We can flip the value of an individual qubit:
>>> q.flip(1)
|0111>
We can take the dagger of a Qubit to get a bra:
>>> from sympy.physics.quantum.dagger import Dagger
>>> Dagger(q)
<0101|
>>> type(Dagger(q))
<class 'sympy.physics.quantum.qubit.QubitBra'>
Inner products work as expected:
>>> ip = Dagger(q)*q
>>> ip
<0101|0101>
>>> ip.doit()
1
"""
@classmethod
def dual_class(self):
return QubitBra
def _eval_innerproduct_QubitBra(self, bra, **hints):
if self.label == bra.label:
return S.One
else:
return S.Zero
def _represent_default_basis(self, **options):
return self._represent_ZGate(None, **options)
def _represent_ZGate(self, basis, **options):
"""Represent this qubits in the computational basis (ZGate).
"""
_format = options.get('format', 'sympy')
n = 1
definite_state = 0
for it in reversed(self.qubit_values):
definite_state += n*it
n = n*2
result = [0]*(2**self.dimension)
result[int(definite_state)] = 1
if _format == 'sympy':
return Matrix(result)
elif _format == 'numpy':
import numpy as np
return np.matrix(result, dtype='complex').transpose()
elif _format == 'scipy.sparse':
from scipy import sparse
return sparse.csr_matrix(result, dtype='complex').transpose()
def _eval_trace(self, bra, **kwargs):
indices = kwargs.get('indices', [])
#sort index list to begin trace from most-significant
#qubit
sorted_idx = list(indices)
if len(sorted_idx) == 0:
sorted_idx = list(range(0, self.nqubits))
sorted_idx.sort()
#trace out for each of index
new_mat = self*bra
for i in range(len(sorted_idx) - 1, -1, -1):
# start from tracing out from leftmost qubit
new_mat = self._reduced_density(new_mat, int(sorted_idx[i]))
if (len(sorted_idx) == self.nqubits):
#in case full trace was requested
return new_mat[0]
else:
return matrix_to_density(new_mat)
def _reduced_density(self, matrix, qubit, **options):
"""Compute the reduced density matrix by tracing out one qubit.
The qubit argument should be of type Python int, since it is used
in bit operations
"""
def find_index_that_is_projected(j, k, qubit):
bit_mask = 2**qubit - 1
return ((j >> qubit) << (1 + qubit)) + (j & bit_mask) + (k << qubit)
old_matrix = represent(matrix, **options)
old_size = old_matrix.cols
#we expect the old_size to be even
new_size = old_size//2
new_matrix = Matrix().zeros(new_size)
for i in range(new_size):
for j in range(new_size):
for k in range(2):
col = find_index_that_is_projected(j, k, qubit)
row = find_index_that_is_projected(i, k, qubit)
new_matrix[i, j] += old_matrix[row, col]
return new_matrix
class QubitBra(QubitState, Bra):
"""A multi-qubit bra in the computational (z) basis.
We use the normal convention that the least significant qubit is on the
right, so ``|00001>`` has a 1 in the least significant qubit.
Parameters
==========
values : list, str
The qubit values as a list of ints ([0,0,0,1,1,]) or a string ('011').
See also
========
Qubit: Examples using qubits
"""
@classmethod
def dual_class(self):
return Qubit
class IntQubitState(QubitState):
"""A base class for qubits that work with binary representations."""
@classmethod
def _eval_args(cls, args, nqubits=None):
# The case of a QubitState instance
if len(args) == 1 and isinstance(args[0], QubitState):
return QubitState._eval_args(args)
# otherwise, args should be integer
elif not all(isinstance(a, (int, Integer)) for a in args):
raise ValueError('values must be integers, got (%s)' % (tuple(type(a) for a in args),))
# use nqubits if specified
if nqubits is not None:
if not isinstance(nqubits, (int, Integer)):
raise ValueError('nqubits must be an integer, got (%s)' % type(nqubits))
if len(args) != 1:
raise ValueError(
'too many positional arguments (%s). should be (number, nqubits=n)' % (args,))
return cls._eval_args_with_nqubits(args[0], nqubits)
# For a single argument, we construct the binary representation of
# that integer with the minimal number of bits.
if len(args) == 1 and args[0] > 1:
#rvalues is the minimum number of bits needed to express the number
rvalues = reversed(range(bitcount(abs(args[0]))))
qubit_values = [(args[0] >> i) & 1 for i in rvalues]
return QubitState._eval_args(qubit_values)
# For two numbers, the second number is the number of bits
# on which it is expressed, so IntQubit(0,5) == |00000>.
elif len(args) == 2 and args[1] > 1:
return cls._eval_args_with_nqubits(args[0], args[1])
else:
return QubitState._eval_args(args)
@classmethod
def _eval_args_with_nqubits(cls, number, nqubits):
need = bitcount(abs(number))
if nqubits < need:
raise ValueError(
'cannot represent %s with %s bits' % (number, nqubits))
qubit_values = [(number >> i) & 1 for i in reversed(range(nqubits))]
return QubitState._eval_args(qubit_values)
def as_int(self):
"""Return the numerical value of the qubit."""
number = 0
n = 1
for i in reversed(self.qubit_values):
number += n*i
n = n << 1
return number
def _print_label(self, printer, *args):
return str(self.as_int())
def _print_label_pretty(self, printer, *args):
label = self._print_label(printer, *args)
return prettyForm(label)
_print_label_repr = _print_label
_print_label_latex = _print_label
class IntQubit(IntQubitState, Qubit):
"""A qubit ket that store integers as binary numbers in qubit values.
The differences between this class and ``Qubit`` are:
* The form of the constructor.
* The qubit values are printed as their corresponding integer, rather
than the raw qubit values. The internal storage format of the qubit
values in the same as ``Qubit``.
Parameters
==========
values : int, tuple
If a single argument, the integer we want to represent in the qubit
values. This integer will be represented using the fewest possible
number of qubits.
If a pair of integers and the second value is more than one, the first
integer gives the integer to represent in binary form and the second
integer gives the number of qubits to use.
List of zeros and ones is also accepted to generate qubit by bit pattern.
nqubits : int
The integer that represents the number of qubits.
This number should be passed with keyword ``nqubits=N``.
You can use this in order to avoid ambiguity of Qubit-style tuple of bits.
Please see the example below for more details.
Examples
========
Create a qubit for the integer 5:
>>> from sympy.physics.quantum.qubit import IntQubit
>>> from sympy.physics.quantum.qubit import Qubit
>>> q = IntQubit(5)
>>> q
|5>
We can also create an ``IntQubit`` by passing a ``Qubit`` instance.
>>> q = IntQubit(Qubit('101'))
>>> q
|5>
>>> q.as_int()
5
>>> q.nqubits
3
>>> q.qubit_values
(1, 0, 1)
We can go back to the regular qubit form.
>>> Qubit(q)
|101>
Please note that ``IntQubit`` also accepts a ``Qubit``-style list of bits.
So, the code below yields qubits 3, not a single bit ``1``.
>>> IntQubit(1, 1)
|3>
To avoid ambiguity, use ``nqubits`` parameter.
Use of this keyword is recommended especially when you provide the values by variables.
>>> IntQubit(1, nqubits=1)
|1>
>>> a = 1
>>> IntQubit(a, nqubits=1)
|1>
"""
@classmethod
def dual_class(self):
return IntQubitBra
def _eval_innerproduct_IntQubitBra(self, bra, **hints):
return Qubit._eval_innerproduct_QubitBra(self, bra)
class IntQubitBra(IntQubitState, QubitBra):
"""A qubit bra that store integers as binary numbers in qubit values."""
@classmethod
def dual_class(self):
return IntQubit
#-----------------------------------------------------------------------------
# Qubit <---> Matrix conversion functions
#-----------------------------------------------------------------------------
def matrix_to_qubit(matrix):
"""Convert from the matrix repr. to a sum of Qubit objects.
Parameters
----------
matrix : Matrix, numpy.matrix, scipy.sparse
The matrix to build the Qubit representation of. This works with
SymPy matrices, numpy matrices and scipy.sparse sparse matrices.
Examples
========
Represent a state and then go back to its qubit form:
>>> from sympy.physics.quantum.qubit import matrix_to_qubit, Qubit
>>> from sympy.physics.quantum.represent import represent
>>> q = Qubit('01')
>>> matrix_to_qubit(represent(q))
|01>
"""
# Determine the format based on the type of the input matrix
format = 'sympy'
if isinstance(matrix, numpy_ndarray):
format = 'numpy'
if isinstance(matrix, scipy_sparse_matrix):
format = 'scipy.sparse'
# Make sure it is of correct dimensions for a Qubit-matrix representation.
# This logic should work with sympy, numpy or scipy.sparse matrices.
if matrix.shape[0] == 1:
mlistlen = matrix.shape[1]
nqubits = log(mlistlen, 2)
ket = False
cls = QubitBra
elif matrix.shape[1] == 1:
mlistlen = matrix.shape[0]
nqubits = log(mlistlen, 2)
ket = True
cls = Qubit
else:
raise QuantumError(
'Matrix must be a row/column vector, got %r' % matrix
)
if not isinstance(nqubits, Integer):
raise QuantumError('Matrix must be a row/column vector of size '
'2**nqubits, got: %r' % matrix)
# Go through each item in matrix, if element is non-zero, make it into a
# Qubit item times the element.
result = 0
for i in range(mlistlen):
if ket:
element = matrix[i, 0]
else:
element = matrix[0, i]
if format in ('numpy', 'scipy.sparse'):
element = complex(element)
if element != 0.0:
# Form Qubit array; 0 in bit-locations where i is 0, 1 in
# bit-locations where i is 1
qubit_array = [int(i & (1 << x) != 0) for x in range(nqubits)]
qubit_array.reverse()
result = result + element*cls(*qubit_array)
# If SymPy simplified by pulling out a constant coefficient, undo that.
if isinstance(result, (Mul, Add, Pow)):
result = result.expand()
return result
def matrix_to_density(mat):
"""
Works by finding the eigenvectors and eigenvalues of the matrix.
We know we can decompose rho by doing:
sum(EigenVal*|Eigenvect><Eigenvect|)
"""
from sympy.physics.quantum.density import Density
eigen = mat.eigenvects()
args = [[matrix_to_qubit(Matrix(
[vector, ])), x[0]] for x in eigen for vector in x[2] if x[0] != 0]
if (len(args) == 0):
return S.Zero
else:
return Density(*args)
def qubit_to_matrix(qubit, format='sympy'):
"""Converts an Add/Mul of Qubit objects into it's matrix representation
This function is the inverse of ``matrix_to_qubit`` and is a shorthand
for ``represent(qubit)``.
"""
return represent(qubit, format=format)
#-----------------------------------------------------------------------------
# Measurement
#-----------------------------------------------------------------------------
def measure_all(qubit, format='sympy', normalize=True):
"""Perform an ensemble measurement of all qubits.
Parameters
==========
qubit : Qubit, Add
The qubit to measure. This can be any Qubit or a linear combination
of them.
format : str
The format of the intermediate matrices to use. Possible values are
('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
implemented.
Returns
=======
result : list
A list that consists of primitive states and their probabilities.
Examples
========
>>> from sympy.physics.quantum.qubit import Qubit, measure_all
>>> from sympy.physics.quantum.gate import H
>>> from sympy.physics.quantum.qapply import qapply
>>> c = H(0)*H(1)*Qubit('00')
>>> c
H(0)*H(1)*|00>
>>> q = qapply(c)
>>> measure_all(q)
[(|00>, 1/4), (|01>, 1/4), (|10>, 1/4), (|11>, 1/4)]
"""
m = qubit_to_matrix(qubit, format)
if format == 'sympy':
results = []
if normalize:
m = m.normalized()
size = max(m.shape) # Max of shape to account for bra or ket
nqubits = int(math.log(size)/math.log(2))
for i in range(size):
if m[i] != 0.0:
results.append(
(Qubit(IntQubit(i, nqubits=nqubits)), m[i]*conjugate(m[i]))
)
return results
else:
raise NotImplementedError(
"This function cannot handle non-SymPy matrix formats yet"
)
def measure_partial(qubit, bits, format='sympy', normalize=True):
"""Perform a partial ensemble measure on the specified qubits.
Parameters
==========
qubits : Qubit
The qubit to measure. This can be any Qubit or a linear combination
of them.
bits : tuple
The qubits to measure.
format : str
The format of the intermediate matrices to use. Possible values are
('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
implemented.
Returns
=======
result : list
A list that consists of primitive states and their probabilities.
Examples
========
>>> from sympy.physics.quantum.qubit import Qubit, measure_partial
>>> from sympy.physics.quantum.gate import H
>>> from sympy.physics.quantum.qapply import qapply
>>> c = H(0)*H(1)*Qubit('00')
>>> c
H(0)*H(1)*|00>
>>> q = qapply(c)
>>> measure_partial(q, (0,))
[(sqrt(2)*|00>/2 + sqrt(2)*|10>/2, 1/2), (sqrt(2)*|01>/2 + sqrt(2)*|11>/2, 1/2)]
"""
m = qubit_to_matrix(qubit, format)
if isinstance(bits, (SYMPY_INTS, Integer)):
bits = (int(bits),)
if format == 'sympy':
if normalize:
m = m.normalized()
possible_outcomes = _get_possible_outcomes(m, bits)
# Form output from function.
output = []
for outcome in possible_outcomes:
# Calculate probability of finding the specified bits with
# given values.
prob_of_outcome = 0
prob_of_outcome += (outcome.H*outcome)[0]
# If the output has a chance, append it to output with found
# probability.
if prob_of_outcome != 0:
if normalize:
next_matrix = matrix_to_qubit(outcome.normalized())
else:
next_matrix = matrix_to_qubit(outcome)
output.append((
next_matrix,
prob_of_outcome
))
return output
else:
raise NotImplementedError(
"This function cannot handle non-SymPy matrix formats yet"
)
def measure_partial_oneshot(qubit, bits, format='sympy'):
"""Perform a partial oneshot measurement on the specified qubits.
A oneshot measurement is equivalent to performing a measurement on a
quantum system. This type of measurement does not return the probabilities
like an ensemble measurement does, but rather returns *one* of the
possible resulting states. The exact state that is returned is determined
by picking a state randomly according to the ensemble probabilities.
Parameters
----------
qubits : Qubit
The qubit to measure. This can be any Qubit or a linear combination
of them.
bits : tuple
The qubits to measure.
format : str
The format of the intermediate matrices to use. Possible values are
('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
implemented.
Returns
-------
result : Qubit
The qubit that the system collapsed to upon measurement.
"""
import random
m = qubit_to_matrix(qubit, format)
if format == 'sympy':
m = m.normalized()
possible_outcomes = _get_possible_outcomes(m, bits)
# Form output from function
random_number = random.random()
total_prob = 0
for outcome in possible_outcomes:
# Calculate probability of finding the specified bits
# with given values
total_prob += (outcome.H*outcome)[0]
if total_prob >= random_number:
return matrix_to_qubit(outcome.normalized())
else:
raise NotImplementedError(
"This function cannot handle non-SymPy matrix formats yet"
)
def _get_possible_outcomes(m, bits):
"""Get the possible states that can be produced in a measurement.
Parameters
----------
m : Matrix
The matrix representing the state of the system.
bits : tuple, list
Which bits will be measured.
Returns
-------
result : list
The list of possible states which can occur given this measurement.
These are un-normalized so we can derive the probability of finding
this state by taking the inner product with itself
"""
# This is filled with loads of dirty binary tricks...You have been warned
size = max(m.shape) # Max of shape to account for bra or ket
nqubits = int(math.log(size, 2) + .1) # Number of qubits possible
# Make the output states and put in output_matrices, nothing in them now.
# Each state will represent a possible outcome of the measurement
# Thus, output_matrices[0] is the matrix which we get when all measured
# bits return 0. and output_matrices[1] is the matrix for only the 0th
# bit being true
output_matrices = []
for i in range(1 << len(bits)):
output_matrices.append(zeros(2**nqubits, 1))
# Bitmasks will help sort how to determine possible outcomes.
# When the bit mask is and-ed with a matrix-index,
# it will determine which state that index belongs to
bit_masks = []
for bit in bits:
bit_masks.append(1 << bit)
# Make possible outcome states
for i in range(2**nqubits):
trueness = 0 # This tells us to which output_matrix this value belongs
# Find trueness
for j in range(len(bit_masks)):
if i & bit_masks[j]:
trueness += j + 1
# Put the value in the correct output matrix
output_matrices[trueness][i] = m[i]
return output_matrices
def measure_all_oneshot(qubit, format='sympy'):
"""Perform a oneshot ensemble measurement on all qubits.
A oneshot measurement is equivalent to performing a measurement on a
quantum system. This type of measurement does not return the probabilities
like an ensemble measurement does, but rather returns *one* of the
possible resulting states. The exact state that is returned is determined
by picking a state randomly according to the ensemble probabilities.
Parameters
----------
qubits : Qubit
The qubit to measure. This can be any Qubit or a linear combination
of them.
format : str
The format of the intermediate matrices to use. Possible values are
('sympy','numpy','scipy.sparse'). Currently only 'sympy' is
implemented.
Returns
-------
result : Qubit
The qubit that the system collapsed to upon measurement.
"""
import random
m = qubit_to_matrix(qubit)
if format == 'sympy':
m = m.normalized()
random_number = random.random()
total = 0
result = 0
for i in m:
total += i*i.conjugate()
if total > random_number:
break
result += 1
return Qubit(IntQubit(result, int(math.log(max(m.shape), 2) + .1)))
else:
raise NotImplementedError(
"This function cannot handle non-SymPy matrix formats yet"
)
|
17d86ebd1fa48c5f5ea1f9dffe79cdfe4a99cf498e4896bb7504ef67de3809d8 | """
qasm.py - Functions to parse a set of qasm commands into a SymPy Circuit.
Examples taken from Chuang's page: http://www.media.mit.edu/quanta/qasm2circ/
The code returns a circuit and an associated list of labels.
>>> from sympy.physics.quantum.qasm import Qasm
>>> q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1')
>>> q.get_circuit()
CNOT(1,0)*H(1)
>>> q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1')
>>> q.get_circuit()
CNOT(1,0)*CNOT(0,1)*CNOT(1,0)
"""
__all__ = [
'Qasm',
]
from sympy.physics.quantum.gate import H, CNOT, X, Z, CGate, CGateS, SWAP, S, T,CPHASE
from sympy.physics.quantum.circuitplot import Mz
def read_qasm(lines):
return Qasm(*lines.splitlines())
def read_qasm_file(filename):
return Qasm(*open(filename).readlines())
def prod(c):
p = 1
for ci in c:
p *= ci
return p
def flip_index(i, n):
"""Reorder qubit indices from largest to smallest.
>>> from sympy.physics.quantum.qasm import flip_index
>>> flip_index(0, 2)
1
>>> flip_index(1, 2)
0
"""
return n-i-1
def trim(line):
"""Remove everything following comment # characters in line.
>>> from sympy.physics.quantum.qasm import trim
>>> trim('nothing happens here')
'nothing happens here'
>>> trim('something #happens here')
'something '
"""
if '#' not in line:
return line
return line.split('#')[0]
def get_index(target, labels):
"""Get qubit labels from the rest of the line,and return indices
>>> from sympy.physics.quantum.qasm import get_index
>>> get_index('q0', ['q0', 'q1'])
1
>>> get_index('q1', ['q0', 'q1'])
0
"""
nq = len(labels)
return flip_index(labels.index(target), nq)
def get_indices(targets, labels):
return [get_index(t, labels) for t in targets]
def nonblank(args):
for line in args:
line = trim(line)
if line.isspace():
continue
yield line
return
def fullsplit(line):
words = line.split()
rest = ' '.join(words[1:])
return fixcommand(words[0]), [s.strip() for s in rest.split(',')]
def fixcommand(c):
"""Fix Qasm command names.
Remove all of forbidden characters from command c, and
replace 'def' with 'qdef'.
"""
forbidden_characters = ['-']
c = c.lower()
for char in forbidden_characters:
c = c.replace(char, '')
if c == 'def':
return 'qdef'
return c
def stripquotes(s):
"""Replace explicit quotes in a string.
>>> from sympy.physics.quantum.qasm import stripquotes
>>> stripquotes("'S'") == 'S'
True
>>> stripquotes('"S"') == 'S'
True
>>> stripquotes('S') == 'S'
True
"""
s = s.replace('"', '') # Remove second set of quotes?
s = s.replace("'", '')
return s
class Qasm:
"""Class to form objects from Qasm lines
>>> from sympy.physics.quantum.qasm import Qasm
>>> q = Qasm('qubit q0', 'qubit q1', 'h q0', 'cnot q0,q1')
>>> q.get_circuit()
CNOT(1,0)*H(1)
>>> q = Qasm('qubit q0', 'qubit q1', 'cnot q0,q1', 'cnot q1,q0', 'cnot q0,q1')
>>> q.get_circuit()
CNOT(1,0)*CNOT(0,1)*CNOT(1,0)
"""
def __init__(self, *args, **kwargs):
self.defs = {}
self.circuit = []
self.labels = []
self.inits = {}
self.add(*args)
self.kwargs = kwargs
def add(self, *lines):
for line in nonblank(lines):
command, rest = fullsplit(line)
if self.defs.get(command): #defs come first, since you can override built-in
function = self.defs.get(command)
indices = self.indices(rest)
if len(indices) == 1:
self.circuit.append(function(indices[0]))
else:
self.circuit.append(function(indices[:-1], indices[-1]))
elif hasattr(self, command):
function = getattr(self, command)
function(*rest)
else:
print("Function %s not defined. Skipping" % command)
def get_circuit(self):
return prod(reversed(self.circuit))
def get_labels(self):
return list(reversed(self.labels))
def plot(self):
from sympy.physics.quantum.circuitplot import CircuitPlot
circuit, labels = self.get_circuit(), self.get_labels()
CircuitPlot(circuit, len(labels), labels=labels, inits=self.inits)
def qubit(self, arg, init=None):
self.labels.append(arg)
if init: self.inits[arg] = init
def indices(self, args):
return get_indices(args, self.labels)
def index(self, arg):
return get_index(arg, self.labels)
def nop(self, *args):
pass
def x(self, arg):
self.circuit.append(X(self.index(arg)))
def z(self, arg):
self.circuit.append(Z(self.index(arg)))
def h(self, arg):
self.circuit.append(H(self.index(arg)))
def s(self, arg):
self.circuit.append(S(self.index(arg)))
def t(self, arg):
self.circuit.append(T(self.index(arg)))
def measure(self, arg):
self.circuit.append(Mz(self.index(arg)))
def cnot(self, a1, a2):
self.circuit.append(CNOT(*self.indices([a1, a2])))
def swap(self, a1, a2):
self.circuit.append(SWAP(*self.indices([a1, a2])))
def cphase(self, a1, a2):
self.circuit.append(CPHASE(*self.indices([a1, a2])))
def toffoli(self, a1, a2, a3):
i1, i2, i3 = self.indices([a1, a2, a3])
self.circuit.append(CGateS((i1, i2), X(i3)))
def cx(self, a1, a2):
fi, fj = self.indices([a1, a2])
self.circuit.append(CGate(fi, X(fj)))
def cz(self, a1, a2):
fi, fj = self.indices([a1, a2])
self.circuit.append(CGate(fi, Z(fj)))
def defbox(self, *args):
print("defbox not supported yet. Skipping: ", args)
def qdef(self, name, ncontrols, symbol):
from sympy.physics.quantum.circuitplot import CreateOneQubitGate, CreateCGate
ncontrols = int(ncontrols)
command = fixcommand(name)
symbol = stripquotes(symbol)
if ncontrols > 0:
self.defs[command] = CreateCGate(symbol)
else:
self.defs[command] = CreateOneQubitGate(symbol)
|
54ba9ea173c7ba28eea74215330f0c7fb13f987a3d0df82824b3eb92bcfde157 | """Primitive circuit operations on quantum circuits."""
from functools import reduce
from sympy.core.sorting import default_sort_key
from sympy.core.containers import Tuple
from sympy.core.mul import Mul
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.utilities import numbered_symbols
from sympy.physics.quantum.gate import Gate
__all__ = [
'kmp_table',
'find_subcircuit',
'replace_subcircuit',
'convert_to_symbolic_indices',
'convert_to_real_indices',
'random_reduce',
'random_insert'
]
def kmp_table(word):
"""Build the 'partial match' table of the Knuth-Morris-Pratt algorithm.
Note: This is applicable to strings or
quantum circuits represented as tuples.
"""
# Current position in subcircuit
pos = 2
# Beginning position of candidate substring that
# may reappear later in word
cnd = 0
# The 'partial match' table that helps one determine
# the next location to start substring search
table = list()
table.append(-1)
table.append(0)
while pos < len(word):
if word[pos - 1] == word[cnd]:
cnd = cnd + 1
table.append(cnd)
pos = pos + 1
elif cnd > 0:
cnd = table[cnd]
else:
table.append(0)
pos = pos + 1
return table
def find_subcircuit(circuit, subcircuit, start=0, end=0):
"""Finds the subcircuit in circuit, if it exists.
Explanation
===========
If the subcircuit exists, the index of the start of
the subcircuit in circuit is returned; otherwise,
-1 is returned. The algorithm that is implemented
is the Knuth-Morris-Pratt algorithm.
Parameters
==========
circuit : tuple, Gate or Mul
A tuple of Gates or Mul representing a quantum circuit
subcircuit : tuple, Gate or Mul
A tuple of Gates or Mul to find in circuit
start : int
The location to start looking for subcircuit.
If start is the same or past end, -1 is returned.
end : int
The last place to look for a subcircuit. If end
is less than 1 (one), then the length of circuit
is taken to be end.
Examples
========
Find the first instance of a subcircuit:
>>> from sympy.physics.quantum.circuitutils import find_subcircuit
>>> from sympy.physics.quantum.gate import X, Y, Z, H
>>> circuit = X(0)*Z(0)*Y(0)*H(0)
>>> subcircuit = Z(0)*Y(0)
>>> find_subcircuit(circuit, subcircuit)
1
Find the first instance starting at a specific position:
>>> find_subcircuit(circuit, subcircuit, start=1)
1
>>> find_subcircuit(circuit, subcircuit, start=2)
-1
>>> circuit = circuit*subcircuit
>>> find_subcircuit(circuit, subcircuit, start=2)
4
Find the subcircuit within some interval:
>>> find_subcircuit(circuit, subcircuit, start=2, end=2)
-1
"""
if isinstance(circuit, Mul):
circuit = circuit.args
if isinstance(subcircuit, Mul):
subcircuit = subcircuit.args
if len(subcircuit) == 0 or len(subcircuit) > len(circuit):
return -1
if end < 1:
end = len(circuit)
# Location in circuit
pos = start
# Location in the subcircuit
index = 0
# 'Partial match' table
table = kmp_table(subcircuit)
while (pos + index) < end:
if subcircuit[index] == circuit[pos + index]:
index = index + 1
else:
pos = pos + index - table[index]
index = table[index] if table[index] > -1 else 0
if index == len(subcircuit):
return pos
return -1
def replace_subcircuit(circuit, subcircuit, replace=None, pos=0):
"""Replaces a subcircuit with another subcircuit in circuit,
if it exists.
Explanation
===========
If multiple instances of subcircuit exists, the first instance is
replaced. The position to being searching from (if different from
0) may be optionally given. If subcircuit cannot be found, circuit
is returned.
Parameters
==========
circuit : tuple, Gate or Mul
A quantum circuit.
subcircuit : tuple, Gate or Mul
The circuit to be replaced.
replace : tuple, Gate or Mul
The replacement circuit.
pos : int
The location to start search and replace
subcircuit, if it exists. This may be used
if it is known beforehand that multiple
instances exist, and it is desirable to
replace a specific instance. If a negative number
is given, pos will be defaulted to 0.
Examples
========
Find and remove the subcircuit:
>>> from sympy.physics.quantum.circuitutils import replace_subcircuit
>>> from sympy.physics.quantum.gate import X, Y, Z, H
>>> circuit = X(0)*Z(0)*Y(0)*H(0)*X(0)*H(0)*Y(0)
>>> subcircuit = Z(0)*Y(0)
>>> replace_subcircuit(circuit, subcircuit)
(X(0), H(0), X(0), H(0), Y(0))
Remove the subcircuit given a starting search point:
>>> replace_subcircuit(circuit, subcircuit, pos=1)
(X(0), H(0), X(0), H(0), Y(0))
>>> replace_subcircuit(circuit, subcircuit, pos=2)
(X(0), Z(0), Y(0), H(0), X(0), H(0), Y(0))
Replace the subcircuit:
>>> replacement = H(0)*Z(0)
>>> replace_subcircuit(circuit, subcircuit, replace=replacement)
(X(0), H(0), Z(0), H(0), X(0), H(0), Y(0))
"""
if pos < 0:
pos = 0
if isinstance(circuit, Mul):
circuit = circuit.args
if isinstance(subcircuit, Mul):
subcircuit = subcircuit.args
if isinstance(replace, Mul):
replace = replace.args
elif replace is None:
replace = ()
# Look for the subcircuit starting at pos
loc = find_subcircuit(circuit, subcircuit, start=pos)
# If subcircuit was found
if loc > -1:
# Get the gates to the left of subcircuit
left = circuit[0:loc]
# Get the gates to the right of subcircuit
right = circuit[loc + len(subcircuit):len(circuit)]
# Recombine the left and right side gates into a circuit
circuit = left + replace + right
return circuit
def _sympify_qubit_map(mapping):
new_map = {}
for key in mapping:
new_map[key] = sympify(mapping[key])
return new_map
def convert_to_symbolic_indices(seq, start=None, gen=None, qubit_map=None):
"""Returns the circuit with symbolic indices and the
dictionary mapping symbolic indices to real indices.
The mapping is 1 to 1 and onto (bijective).
Parameters
==========
seq : tuple, Gate/Integer/tuple or Mul
A tuple of Gate, Integer, or tuple objects, or a Mul
start : Symbol
An optional starting symbolic index
gen : object
An optional numbered symbol generator
qubit_map : dict
An existing mapping of symbolic indices to real indices
All symbolic indices have the format 'i#', where # is
some number >= 0.
"""
if isinstance(seq, Mul):
seq = seq.args
# A numbered symbol generator
index_gen = numbered_symbols(prefix='i', start=-1)
cur_ndx = next(index_gen)
# keys are symbolic indices; values are real indices
ndx_map = {}
def create_inverse_map(symb_to_real_map):
rev_items = lambda item: tuple([item[1], item[0]])
return dict(map(rev_items, symb_to_real_map.items()))
if start is not None:
if not isinstance(start, Symbol):
msg = 'Expected Symbol for starting index, got %r.' % start
raise TypeError(msg)
cur_ndx = start
if gen is not None:
if not isinstance(gen, numbered_symbols().__class__):
msg = 'Expected a generator, got %r.' % gen
raise TypeError(msg)
index_gen = gen
if qubit_map is not None:
if not isinstance(qubit_map, dict):
msg = ('Expected dict for existing map, got ' +
'%r.' % qubit_map)
raise TypeError(msg)
ndx_map = qubit_map
ndx_map = _sympify_qubit_map(ndx_map)
# keys are real indices; keys are symbolic indices
inv_map = create_inverse_map(ndx_map)
sym_seq = ()
for item in seq:
# Nested items, so recurse
if isinstance(item, Gate):
result = convert_to_symbolic_indices(item.args,
qubit_map=ndx_map,
start=cur_ndx,
gen=index_gen)
sym_item, new_map, cur_ndx, index_gen = result
ndx_map.update(new_map)
inv_map = create_inverse_map(ndx_map)
elif isinstance(item, (tuple, Tuple)):
result = convert_to_symbolic_indices(item,
qubit_map=ndx_map,
start=cur_ndx,
gen=index_gen)
sym_item, new_map, cur_ndx, index_gen = result
ndx_map.update(new_map)
inv_map = create_inverse_map(ndx_map)
elif item in inv_map:
sym_item = inv_map[item]
else:
cur_ndx = next(gen)
ndx_map[cur_ndx] = item
inv_map[item] = cur_ndx
sym_item = cur_ndx
if isinstance(item, Gate):
sym_item = item.__class__(*sym_item)
sym_seq = sym_seq + (sym_item,)
return sym_seq, ndx_map, cur_ndx, index_gen
def convert_to_real_indices(seq, qubit_map):
"""Returns the circuit with real indices.
Parameters
==========
seq : tuple, Gate/Integer/tuple or Mul
A tuple of Gate, Integer, or tuple objects or a Mul
qubit_map : dict
A dictionary mapping symbolic indices to real indices.
Examples
========
Change the symbolic indices to real integers:
>>> from sympy import symbols
>>> from sympy.physics.quantum.circuitutils import convert_to_real_indices
>>> from sympy.physics.quantum.gate import X, Y, H
>>> i0, i1 = symbols('i:2')
>>> index_map = {i0 : 0, i1 : 1}
>>> convert_to_real_indices(X(i0)*Y(i1)*H(i0)*X(i1), index_map)
(X(0), Y(1), H(0), X(1))
"""
if isinstance(seq, Mul):
seq = seq.args
if not isinstance(qubit_map, dict):
msg = 'Expected dict for qubit_map, got %r.' % qubit_map
raise TypeError(msg)
qubit_map = _sympify_qubit_map(qubit_map)
real_seq = ()
for item in seq:
# Nested items, so recurse
if isinstance(item, Gate):
real_item = convert_to_real_indices(item.args, qubit_map)
elif isinstance(item, (tuple, Tuple)):
real_item = convert_to_real_indices(item, qubit_map)
else:
real_item = qubit_map[item]
if isinstance(item, Gate):
real_item = item.__class__(*real_item)
real_seq = real_seq + (real_item,)
return real_seq
def random_reduce(circuit, gate_ids, seed=None):
"""Shorten the length of a quantum circuit.
Explanation
===========
random_reduce looks for circuit identities in circuit, randomly chooses
one to remove, and returns a shorter yet equivalent circuit. If no
identities are found, the same circuit is returned.
Parameters
==========
circuit : Gate tuple of Mul
A tuple of Gates representing a quantum circuit
gate_ids : list, GateIdentity
List of gate identities to find in circuit
seed : int or list
seed used for _randrange; to override the random selection, provide a
list of integers: the elements of gate_ids will be tested in the order
given by the list
"""
from sympy.core.random import _randrange
if not gate_ids:
return circuit
if isinstance(circuit, Mul):
circuit = circuit.args
ids = flatten_ids(gate_ids)
# Create the random integer generator with the seed
randrange = _randrange(seed)
# Look for an identity in the circuit
while ids:
i = randrange(len(ids))
id = ids.pop(i)
if find_subcircuit(circuit, id) != -1:
break
else:
# no identity was found
return circuit
# return circuit with the identity removed
return replace_subcircuit(circuit, id)
def random_insert(circuit, choices, seed=None):
"""Insert a circuit into another quantum circuit.
Explanation
===========
random_insert randomly chooses a location in the circuit to insert
a randomly selected circuit from amongst the given choices.
Parameters
==========
circuit : Gate tuple or Mul
A tuple or Mul of Gates representing a quantum circuit
choices : list
Set of circuit choices
seed : int or list
seed used for _randrange; to override the random selections, give
a list two integers, [i, j] where i is the circuit location where
choice[j] will be inserted.
Notes
=====
Indices for insertion should be [0, n] if n is the length of the
circuit.
"""
from sympy.core.random import _randrange
if not choices:
return circuit
if isinstance(circuit, Mul):
circuit = circuit.args
# get the location in the circuit and the element to insert from choices
randrange = _randrange(seed)
loc = randrange(len(circuit) + 1)
choice = choices[randrange(len(choices))]
circuit = list(circuit)
circuit[loc: loc] = choice
return tuple(circuit)
# Flatten the GateIdentity objects (with gate rules) into one single list
def flatten_ids(ids):
collapse = lambda acc, an_id: acc + sorted(an_id.equivalent_ids,
key=default_sort_key)
ids = reduce(collapse, ids, [])
ids.sort(key=default_sort_key)
return ids
|
230fbd80692cbd684f990fd57a9988f747a42b2cc774f96ae94e35c1d3388a42 | """
This module has all the classes and functions related to waves in optics.
**Contains**
* TWave
"""
__all__ = ['TWave']
from sympy.core.basic import Basic
from sympy.core.expr import Expr
from sympy.core.function import Derivative, Function
from sympy.core.numbers import (Number, pi, I)
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.core.sympify import _sympify, sympify
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (atan2, cos, sin)
from sympy.physics.units import speed_of_light, meter, second
c = speed_of_light.convert_to(meter/second)
class TWave(Expr):
r"""
This is a simple transverse sine wave travelling in a one-dimensional space.
Basic properties are required at the time of creation of the object,
but they can be changed later with respective methods provided.
Explanation
===========
It is represented as :math:`A \times cos(k*x - \omega \times t + \phi )`,
where :math:`A` is the amplitude, :math:`\omega` is the angular frequency,
:math:`k` is the wavenumber (spatial frequency), :math:`x` is a spatial variable
to represent the position on the dimension on which the wave propagates,
and :math:`\phi` is the phase angle of the wave.
Arguments
=========
amplitude : Sympifyable
Amplitude of the wave.
frequency : Sympifyable
Frequency of the wave.
phase : Sympifyable
Phase angle of the wave.
time_period : Sympifyable
Time period of the wave.
n : Sympifyable
Refractive index of the medium.
Raises
=======
ValueError : When neither frequency nor time period is provided
or they are not consistent.
TypeError : When anything other than TWave objects is added.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
>>> w1 = TWave(A1, f, phi1)
>>> w2 = TWave(A2, f, phi2)
>>> w3 = w1 + w2 # Superposition of two waves
>>> w3
TWave(sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2), f,
atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2)), 1/f, n)
>>> w3.amplitude
sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
>>> w3.phase
atan2(A1*sin(phi1) + A2*sin(phi2), A1*cos(phi1) + A2*cos(phi2))
>>> w3.speed
299792458*meter/(second*n)
>>> w3.angular_velocity
2*pi*f
"""
def __new__(
cls,
amplitude,
frequency=None,
phase=S.Zero,
time_period=None,
n=Symbol('n')):
if time_period is not None:
time_period = _sympify(time_period)
_frequency = S.One/time_period
if frequency is not None:
frequency = _sympify(frequency)
_time_period = S.One/frequency
if time_period is not None:
if frequency != S.One/time_period:
raise ValueError("frequency and time_period should be consistent.")
if frequency is None and time_period is None:
raise ValueError("Either frequency or time period is needed.")
if frequency is None:
frequency = _frequency
if time_period is None:
time_period = _time_period
amplitude = _sympify(amplitude)
phase = _sympify(phase)
n = sympify(n)
obj = Basic.__new__(cls, amplitude, frequency, phase, time_period, n)
return obj
@property
def amplitude(self):
"""
Returns the amplitude of the wave.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.amplitude
A
"""
return self.args[0]
@property
def frequency(self):
"""
Returns the frequency of the wave,
in cycles per second.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.frequency
f
"""
return self.args[1]
@property
def phase(self):
"""
Returns the phase angle of the wave,
in radians.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.phase
phi
"""
return self.args[2]
@property
def time_period(self):
"""
Returns the temporal period of the wave,
in seconds per cycle.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.time_period
1/f
"""
return self.args[3]
@property
def n(self):
"""
Returns the refractive index of the medium
"""
return self.args[4]
@property
def wavelength(self):
"""
Returns the wavelength (spatial period) of the wave,
in meters per cycle.
It depends on the medium of the wave.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.wavelength
299792458*meter/(second*f*n)
"""
return c/(self.frequency*self.n)
@property
def speed(self):
"""
Returns the propagation speed of the wave,
in meters per second.
It is dependent on the propagation medium.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.speed
299792458*meter/(second*n)
"""
return self.wavelength*self.frequency
@property
def angular_velocity(self):
"""
Returns the angular velocity of the wave,
in radians per second.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.angular_velocity
2*pi*f
"""
return 2*pi*self.frequency
@property
def wavenumber(self):
"""
Returns the wavenumber of the wave,
in radians per meter.
Examples
========
>>> from sympy import symbols
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.wavenumber
pi*second*f*n/(149896229*meter)
"""
return 2*pi/self.wavelength
def __str__(self):
"""String representation of a TWave."""
from sympy.printing import sstr
return type(self).__name__ + sstr(self.args)
__repr__ = __str__
def __add__(self, other):
"""
Addition of two waves will result in their superposition.
The type of interference will depend on their phase angles.
"""
if isinstance(other, TWave):
if self.frequency == other.frequency and self.wavelength == other.wavelength:
return TWave(sqrt(self.amplitude**2 + other.amplitude**2 + 2 *
self.amplitude*other.amplitude*cos(
self.phase - other.phase)),
self.frequency,
atan2(self.amplitude*sin(self.phase)
+ other.amplitude*sin(other.phase),
self.amplitude*cos(self.phase)
+ other.amplitude*cos(other.phase))
)
else:
raise NotImplementedError("Interference of waves with different frequencies"
" has not been implemented.")
else:
raise TypeError(type(other).__name__ + " and TWave objects cannot be added.")
def __mul__(self, other):
"""
Multiplying a wave by a scalar rescales the amplitude of the wave.
"""
other = sympify(other)
if isinstance(other, Number):
return TWave(self.amplitude*other, *self.args[1:])
else:
raise TypeError(type(other).__name__ + " and TWave objects cannot be multiplied.")
def __sub__(self, other):
return self.__add__(-1*other)
def __neg__(self):
return self.__mul__(-1)
def __radd__(self, other):
return self.__add__(other)
def __rmul__(self, other):
return self.__mul__(other)
def __rsub__(self, other):
return (-self).__radd__(other)
def _eval_rewrite_as_sin(self, *args, **kwargs):
return self.amplitude*sin(self.wavenumber*Symbol('x')
- self.angular_velocity*Symbol('t') + self.phase + pi/2, evaluate=False)
def _eval_rewrite_as_cos(self, *args, **kwargs):
return self.amplitude*cos(self.wavenumber*Symbol('x')
- self.angular_velocity*Symbol('t') + self.phase)
def _eval_rewrite_as_pde(self, *args, **kwargs):
mu, epsilon, x, t = symbols('mu, epsilon, x, t')
E = Function('E')
return Derivative(E(x, t), x, 2) + mu*epsilon*Derivative(E(x, t), t, 2)
def _eval_rewrite_as_exp(self, *args, **kwargs):
return self.amplitude*exp(I*(self.wavenumber*Symbol('x')
- self.angular_velocity*Symbol('t') + self.phase))
|
54d1edc5b418e215694a3bd98e72071ac3eed9e6a7ffbf835eb39d2d05d3b006 | from sympy.core.add import Add
from sympy.core.function import Function
from sympy.core.mul import Mul
from sympy.core.numbers import (I, Rational, oo)
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.matrices.dense import eye
from sympy.polys.polytools import factor
from sympy.polys.rootoftools import CRootOf
from sympy.simplify.simplify import simplify
from sympy.core.containers import Tuple
from sympy.matrices import ImmutableMatrix, Matrix
from sympy.physics.control import (TransferFunction, Series, Parallel,
Feedback, TransferFunctionMatrix, MIMOSeries, MIMOParallel, MIMOFeedback)
from sympy.testing.pytest import raises
a, x, b, s, g, d, p, k, a0, a1, a2, b0, b1, b2, tau, zeta, wn = symbols('a, x, b, s, g, d, p, k,\
a0:3, b0:3, tau, zeta, wn')
TF1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
TF2 = TransferFunction(k, 1, s)
TF3 = TransferFunction(a2*p - s, a2*s + p, s)
def test_TransferFunction_construction():
tf = TransferFunction(s + 1, s**2 + s + 1, s)
assert tf.num == (s + 1)
assert tf.den == (s**2 + s + 1)
assert tf.args == (s + 1, s**2 + s + 1, s)
tf1 = TransferFunction(s + 4, s - 5, s)
assert tf1.num == (s + 4)
assert tf1.den == (s - 5)
assert tf1.args == (s + 4, s - 5, s)
# using different polynomial variables.
tf2 = TransferFunction(p + 3, p**2 - 9, p)
assert tf2.num == (p + 3)
assert tf2.den == (p**2 - 9)
assert tf2.args == (p + 3, p**2 - 9, p)
tf3 = TransferFunction(p**3 + 5*p**2 + 4, p**4 + 3*p + 1, p)
assert tf3.args == (p**3 + 5*p**2 + 4, p**4 + 3*p + 1, p)
# no pole-zero cancellation on its own.
tf4 = TransferFunction((s + 3)*(s - 1), (s - 1)*(s + 5), s)
assert tf4.den == (s - 1)*(s + 5)
assert tf4.args == ((s + 3)*(s - 1), (s - 1)*(s + 5), s)
tf4_ = TransferFunction(p + 2, p + 2, p)
assert tf4_.args == (p + 2, p + 2, p)
tf5 = TransferFunction(s - 1, 4 - p, s)
assert tf5.args == (s - 1, 4 - p, s)
tf5_ = TransferFunction(s - 1, s - 1, s)
assert tf5_.args == (s - 1, s - 1, s)
tf6 = TransferFunction(5, 6, s)
assert tf6.num == 5
assert tf6.den == 6
assert tf6.args == (5, 6, s)
tf6_ = TransferFunction(1/2, 4, s)
assert tf6_.num == 0.5
assert tf6_.den == 4
assert tf6_.args == (0.500000000000000, 4, s)
tf7 = TransferFunction(3*s**2 + 2*p + 4*s, 8*p**2 + 7*s, s)
tf8 = TransferFunction(3*s**2 + 2*p + 4*s, 8*p**2 + 7*s, p)
assert not tf7 == tf8
tf7_ = TransferFunction(a0*s + a1*s**2 + a2*s**3, b0*p - b1*s, s)
tf8_ = TransferFunction(a0*s + a1*s**2 + a2*s**3, b0*p - b1*s, s)
assert tf7_ == tf8_
assert -(-tf7_) == tf7_ == -(-(-(-tf7_)))
tf9 = TransferFunction(a*s**3 + b*s**2 + g*s + d, d*p + g*p**2 + g*s, s)
assert tf9.args == (a*s**3 + b*s**2 + d + g*s, d*p + g*p**2 + g*s, s)
tf10 = TransferFunction(p**3 + d, g*s**2 + d*s + a, p)
tf10_ = TransferFunction(p**3 + d, g*s**2 + d*s + a, p)
assert tf10.args == (d + p**3, a + d*s + g*s**2, p)
assert tf10_ == tf10
tf11 = TransferFunction(a1*s + a0, b2*s**2 + b1*s + b0, s)
assert tf11.num == (a0 + a1*s)
assert tf11.den == (b0 + b1*s + b2*s**2)
assert tf11.args == (a0 + a1*s, b0 + b1*s + b2*s**2, s)
# when just the numerator is 0, leave the denominator alone.
tf12 = TransferFunction(0, p**2 - p + 1, p)
assert tf12.args == (0, p**2 - p + 1, p)
tf13 = TransferFunction(0, 1, s)
assert tf13.args == (0, 1, s)
# float exponents
tf14 = TransferFunction(a0*s**0.5 + a2*s**0.6 - a1, a1*p**(-8.7), s)
assert tf14.args == (a0*s**0.5 - a1 + a2*s**0.6, a1*p**(-8.7), s)
tf15 = TransferFunction(a2**2*p**(1/4) + a1*s**(-4/5), a0*s - p, p)
assert tf15.args == (a1*s**(-0.8) + a2**2*p**0.25, a0*s - p, p)
omega_o, k_p, k_o, k_i = symbols('omega_o, k_p, k_o, k_i')
tf18 = TransferFunction((k_p + k_o*s + k_i/s), s**2 + 2*omega_o*s + omega_o**2, s)
assert tf18.num == k_i/s + k_o*s + k_p
assert tf18.args == (k_i/s + k_o*s + k_p, omega_o**2 + 2*omega_o*s + s**2, s)
# ValueError when denominator is zero.
raises(ValueError, lambda: TransferFunction(4, 0, s))
raises(ValueError, lambda: TransferFunction(s, 0, s))
raises(ValueError, lambda: TransferFunction(0, 0, s))
raises(TypeError, lambda: TransferFunction(Matrix([1, 2, 3]), s, s))
raises(TypeError, lambda: TransferFunction(s**2 + 2*s - 1, s + 3, 3))
raises(TypeError, lambda: TransferFunction(p + 1, 5 - p, 4))
raises(TypeError, lambda: TransferFunction(3, 4, 8))
def test_TransferFunction_functions():
# classmethod from_rational_expression
expr_1 = Mul(0, Pow(s, -1, evaluate=False), evaluate=False)
expr_2 = s/0
expr_3 = (p*s**2 + 5*s)/(s + 1)**3
expr_4 = 6
expr_5 = ((2 + 3*s)*(5 + 2*s))/((9 + 3*s)*(5 + 2*s**2))
expr_6 = (9*s**4 + 4*s**2 + 8)/((s + 1)*(s + 9))
tf = TransferFunction(s + 1, s**2 + 2, s)
delay = exp(-s/tau)
expr_7 = delay*tf.to_expr()
H1 = TransferFunction.from_rational_expression(expr_7, s)
H2 = TransferFunction(s + 1, (s**2 + 2)*exp(s/tau), s)
expr_8 = Add(2, 3*s/(s**2 + 1), evaluate=False)
assert TransferFunction.from_rational_expression(expr_1) == TransferFunction(0, s, s)
raises(ZeroDivisionError, lambda: TransferFunction.from_rational_expression(expr_2))
raises(ValueError, lambda: TransferFunction.from_rational_expression(expr_3))
assert TransferFunction.from_rational_expression(expr_3, s) == TransferFunction((p*s**2 + 5*s), (s + 1)**3, s)
assert TransferFunction.from_rational_expression(expr_3, p) == TransferFunction((p*s**2 + 5*s), (s + 1)**3, p)
raises(ValueError, lambda: TransferFunction.from_rational_expression(expr_4))
assert TransferFunction.from_rational_expression(expr_4, s) == TransferFunction(6, 1, s)
assert TransferFunction.from_rational_expression(expr_5, s) == \
TransferFunction((2 + 3*s)*(5 + 2*s), (9 + 3*s)*(5 + 2*s**2), s)
assert TransferFunction.from_rational_expression(expr_6, s) == \
TransferFunction((9*s**4 + 4*s**2 + 8), (s + 1)*(s + 9), s)
assert H1 == H2
assert TransferFunction.from_rational_expression(expr_8, s) == \
TransferFunction(2*s**2 + 3*s + 2, s**2 + 1, s)
# explicitly cancel poles and zeros.
tf0 = TransferFunction(s**5 + s**3 + s, s - s**2, s)
a = TransferFunction(-(s**4 + s**2 + 1), s - 1, s)
assert tf0.simplify() == simplify(tf0) == a
tf1 = TransferFunction((p + 3)*(p - 1), (p - 1)*(p + 5), p)
b = TransferFunction(p + 3, p + 5, p)
assert tf1.simplify() == simplify(tf1) == b
# expand the numerator and the denominator.
G1 = TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
G2 = TransferFunction(1, -3, p)
c = (a2*s**p + a1*s**s + a0*p**p)*(p**s + s**p)
d = (b0*s**s + b1*p**s)*(b2*s*p + p**p)
e = a0*p**p*p**s + a0*p**p*s**p + a1*p**s*s**s + a1*s**p*s**s + a2*p**s*s**p + a2*s**(2*p)
f = b0*b2*p*s*s**s + b0*p**p*s**s + b1*b2*p*p**s*s + b1*p**p*p**s
g = a1*a2*s*s**p + a1*p*s + a2*b1*p*s*s**p + b1*p**2*s
G3 = TransferFunction(c, d, s)
G4 = TransferFunction(a0*s**s - b0*p**p, (a1*s + b1*s*p)*(a2*s**p + p), p)
assert G1.expand() == TransferFunction(s**2 - 2*s + 1, s**4 + 2*s**2 + 1, s)
assert tf1.expand() == TransferFunction(p**2 + 2*p - 3, p**2 + 4*p - 5, p)
assert G2.expand() == G2
assert G3.expand() == TransferFunction(e, f, s)
assert G4.expand() == TransferFunction(a0*s**s - b0*p**p, g, p)
# purely symbolic polynomials.
p1 = a1*s + a0
p2 = b2*s**2 + b1*s + b0
SP1 = TransferFunction(p1, p2, s)
expect1 = TransferFunction(2.0*s + 1.0, 5.0*s**2 + 4.0*s + 3.0, s)
expect1_ = TransferFunction(2*s + 1, 5*s**2 + 4*s + 3, s)
assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}) == expect1_
assert SP1.subs({a0: 1, a1: 2, b0: 3, b1: 4, b2: 5}).evalf() == expect1
assert expect1_.evalf() == expect1
c1, d0, d1, d2 = symbols('c1, d0:3')
p3, p4 = c1*p, d2*p**3 + d1*p**2 - d0
SP2 = TransferFunction(p3, p4, p)
expect2 = TransferFunction(2.0*p, 5.0*p**3 + 2.0*p**2 - 3.0, p)
expect2_ = TransferFunction(2*p, 5*p**3 + 2*p**2 - 3, p)
assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}) == expect2_
assert SP2.subs({c1: 2, d0: 3, d1: 2, d2: 5}).evalf() == expect2
assert expect2_.evalf() == expect2
SP3 = TransferFunction(a0*p**3 + a1*s**2 - b0*s + b1, a1*s + p, s)
expect3 = TransferFunction(2.0*p**3 + 4.0*s**2 - s + 5.0, p + 4.0*s, s)
expect3_ = TransferFunction(2*p**3 + 4*s**2 - s + 5, p + 4*s, s)
assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}) == expect3_
assert SP3.subs({a0: 2, a1: 4, b0: 1, b1: 5}).evalf() == expect3
assert expect3_.evalf() == expect3
SP4 = TransferFunction(s - a1*p**3, a0*s + p, p)
expect4 = TransferFunction(7.0*p**3 + s, p - s, p)
expect4_ = TransferFunction(7*p**3 + s, p - s, p)
assert SP4.subs({a0: -1, a1: -7}) == expect4_
assert SP4.subs({a0: -1, a1: -7}).evalf() == expect4
assert expect4_.evalf() == expect4
# Low-frequency (or DC) gain.
assert tf0.dc_gain() == 1
assert tf1.dc_gain() == Rational(3, 5)
assert SP2.dc_gain() == 0
assert expect4.dc_gain() == -1
assert expect2_.dc_gain() == 0
assert TransferFunction(1, s, s).dc_gain() == oo
# Poles of a transfer function.
tf_ = TransferFunction(x**3 - k, k, x)
_tf = TransferFunction(k, x**4 - k, x)
TF_ = TransferFunction(x**2, x**10 + x + x**2, x)
_TF = TransferFunction(x**10 + x + x**2, x**2, x)
assert G1.poles() == [I, I, -I, -I]
assert G2.poles() == []
assert tf1.poles() == [-5, 1]
assert expect4_.poles() == [s]
assert SP4.poles() == [-a0*s]
assert expect3.poles() == [-0.25*p]
assert str(expect2.poles()) == str([0.729001428685125, -0.564500714342563 - 0.710198984796332*I, -0.564500714342563 + 0.710198984796332*I])
assert str(expect1.poles()) == str([-0.4 - 0.66332495807108*I, -0.4 + 0.66332495807108*I])
assert _tf.poles() == [k**(Rational(1, 4)), -k**(Rational(1, 4)), I*k**(Rational(1, 4)), -I*k**(Rational(1, 4))]
assert TF_.poles() == [CRootOf(x**9 + x + 1, 0), 0, CRootOf(x**9 + x + 1, 1), CRootOf(x**9 + x + 1, 2),
CRootOf(x**9 + x + 1, 3), CRootOf(x**9 + x + 1, 4), CRootOf(x**9 + x + 1, 5), CRootOf(x**9 + x + 1, 6),
CRootOf(x**9 + x + 1, 7), CRootOf(x**9 + x + 1, 8)]
raises(NotImplementedError, lambda: TransferFunction(x**2, a0*x**10 + x + x**2, x).poles())
# Stability of a transfer function.
q, r = symbols('q, r', negative=True)
t = symbols('t', positive=True)
TF_ = TransferFunction(s**2 + a0 - a1*p, q*s - r, s)
stable_tf = TransferFunction(s**2 + a0 - a1*p, q*s - 1, s)
stable_tf_ = TransferFunction(s**2 + a0 - a1*p, q*s - t, s)
assert G1.is_stable() is False
assert G2.is_stable() is True
assert tf1.is_stable() is False # as one pole is +ve, and the other is -ve.
assert expect2.is_stable() is False
assert expect1.is_stable() is True
assert stable_tf.is_stable() is True
assert stable_tf_.is_stable() is True
assert TF_.is_stable() is False
assert expect4_.is_stable() is None # no assumption provided for the only pole 's'.
assert SP4.is_stable() is None
# Zeros of a transfer function.
assert G1.zeros() == [1, 1]
assert G2.zeros() == []
assert tf1.zeros() == [-3, 1]
assert expect4_.zeros() == [7**(Rational(2, 3))*(-s)**(Rational(1, 3))/7, -7**(Rational(2, 3))*(-s)**(Rational(1, 3))/14 -
sqrt(3)*7**(Rational(2, 3))*I*(-s)**(Rational(1, 3))/14, -7**(Rational(2, 3))*(-s)**(Rational(1, 3))/14 + sqrt(3)*7**(Rational(2, 3))*I*(-s)**(Rational(1, 3))/14]
assert SP4.zeros() == [(s/a1)**(Rational(1, 3)), -(s/a1)**(Rational(1, 3))/2 - sqrt(3)*I*(s/a1)**(Rational(1, 3))/2,
-(s/a1)**(Rational(1, 3))/2 + sqrt(3)*I*(s/a1)**(Rational(1, 3))/2]
assert str(expect3.zeros()) == str([0.125 - 1.11102430216445*sqrt(-0.405063291139241*p**3 - 1.0),
1.11102430216445*sqrt(-0.405063291139241*p**3 - 1.0) + 0.125])
assert tf_.zeros() == [k**(Rational(1, 3)), -k**(Rational(1, 3))/2 - sqrt(3)*I*k**(Rational(1, 3))/2,
-k**(Rational(1, 3))/2 + sqrt(3)*I*k**(Rational(1, 3))/2]
assert _TF.zeros() == [CRootOf(x**9 + x + 1, 0), 0, CRootOf(x**9 + x + 1, 1), CRootOf(x**9 + x + 1, 2),
CRootOf(x**9 + x + 1, 3), CRootOf(x**9 + x + 1, 4), CRootOf(x**9 + x + 1, 5), CRootOf(x**9 + x + 1, 6),
CRootOf(x**9 + x + 1, 7), CRootOf(x**9 + x + 1, 8)]
raises(NotImplementedError, lambda: TransferFunction(a0*x**10 + x + x**2, x**2, x).zeros())
# negation of TF.
tf2 = TransferFunction(s + 3, s**2 - s**3 + 9, s)
tf3 = TransferFunction(-3*p + 3, 1 - p, p)
assert -tf2 == TransferFunction(-s - 3, s**2 - s**3 + 9, s)
assert -tf3 == TransferFunction(3*p - 3, 1 - p, p)
# taking power of a TF.
tf4 = TransferFunction(p + 4, p - 3, p)
tf5 = TransferFunction(s**2 + 1, 1 - s, s)
expect2 = TransferFunction((s**2 + 1)**3, (1 - s)**3, s)
expect1 = TransferFunction((p + 4)**2, (p - 3)**2, p)
assert (tf4*tf4).doit() == tf4**2 == pow(tf4, 2) == expect1
assert (tf5*tf5*tf5).doit() == tf5**3 == pow(tf5, 3) == expect2
assert tf5**0 == pow(tf5, 0) == TransferFunction(1, 1, s)
assert Series(tf4).doit()**-1 == tf4**-1 == pow(tf4, -1) == TransferFunction(p - 3, p + 4, p)
assert (tf5*tf5).doit()**-1 == tf5**-2 == pow(tf5, -2) == TransferFunction((1 - s)**2, (s**2 + 1)**2, s)
raises(ValueError, lambda: tf4**(s**2 + s - 1))
raises(ValueError, lambda: tf5**s)
raises(ValueError, lambda: tf4**tf5)
# SymPy's own functions.
tf = TransferFunction(s - 1, s**2 - 2*s + 1, s)
tf6 = TransferFunction(s + p, p**2 - 5, s)
assert factor(tf) == TransferFunction(s - 1, (s - 1)**2, s)
assert tf.num.subs(s, 2) == tf.den.subs(s, 2) == 1
# subs & xreplace
assert tf.subs(s, 2) == TransferFunction(s - 1, s**2 - 2*s + 1, s)
assert tf6.subs(p, 3) == TransferFunction(s + 3, 4, s)
assert tf3.xreplace({p: s}) == TransferFunction(-3*s + 3, 1 - s, s)
raises(TypeError, lambda: tf3.xreplace({p: exp(2)}))
assert tf3.subs(p, exp(2)) == tf3
tf7 = TransferFunction(a0*s**p + a1*p**s, a2*p - s, s)
assert tf7.xreplace({s: k}) == TransferFunction(a0*k**p + a1*p**k, a2*p - k, k)
assert tf7.subs(s, k) == TransferFunction(a0*s**p + a1*p**s, a2*p - s, s)
# Conversion to Expr with to_expr()
tf8 = TransferFunction(a0*s**5 + 5*s**2 + 3, s**6 - 3, s)
tf9 = TransferFunction((5 + s), (5 + s)*(6 + s), s)
tf10 = TransferFunction(0, 1, s)
tf11 = TransferFunction(1, 1, s)
assert tf8.to_expr() == Mul((a0*s**5 + 5*s**2 + 3), Pow((s**6 - 3), -1, evaluate=False), evaluate=False)
assert tf9.to_expr() == Mul((s + 5), Pow((5 + s)*(6 + s), -1, evaluate=False), evaluate=False)
assert tf10.to_expr() == Mul(S(0), Pow(1, -1, evaluate=False), evaluate=False)
assert tf11.to_expr() == Pow(1, -1, evaluate=False)
def test_TransferFunction_addition_and_subtraction():
tf1 = TransferFunction(s + 6, s - 5, s)
tf2 = TransferFunction(s + 3, s + 1, s)
tf3 = TransferFunction(s + 1, s**2 + s + 1, s)
tf4 = TransferFunction(p, 2 - p, p)
# addition
assert tf1 + tf2 == Parallel(tf1, tf2)
assert tf3 + tf1 == Parallel(tf3, tf1)
assert -tf1 + tf2 + tf3 == Parallel(-tf1, tf2, tf3)
assert tf1 + (tf2 + tf3) == Parallel(tf1, tf2, tf3)
c = symbols("c", commutative=False)
raises(ValueError, lambda: tf1 + Matrix([1, 2, 3]))
raises(ValueError, lambda: tf2 + c)
raises(ValueError, lambda: tf3 + tf4)
raises(ValueError, lambda: tf1 + (s - 1))
raises(ValueError, lambda: tf1 + 8)
raises(ValueError, lambda: (1 - p**3) + tf1)
# subtraction
assert tf1 - tf2 == Parallel(tf1, -tf2)
assert tf3 - tf2 == Parallel(tf3, -tf2)
assert -tf1 - tf3 == Parallel(-tf1, -tf3)
assert tf1 - tf2 + tf3 == Parallel(tf1, -tf2, tf3)
raises(ValueError, lambda: tf1 - Matrix([1, 2, 3]))
raises(ValueError, lambda: tf3 - tf4)
raises(ValueError, lambda: tf1 - (s - 1))
raises(ValueError, lambda: tf1 - 8)
raises(ValueError, lambda: (s + 5) - tf2)
raises(ValueError, lambda: (1 + p**4) - tf1)
def test_TransferFunction_multiplication_and_division():
G1 = TransferFunction(s + 3, -s**3 + 9, s)
G2 = TransferFunction(s + 1, s - 5, s)
G3 = TransferFunction(p, p**4 - 6, p)
G4 = TransferFunction(p + 4, p - 5, p)
G5 = TransferFunction(s + 6, s - 5, s)
G6 = TransferFunction(s + 3, s + 1, s)
G7 = TransferFunction(1, 1, s)
# multiplication
assert G1*G2 == Series(G1, G2)
assert -G1*G5 == Series(-G1, G5)
assert -G2*G5*-G6 == Series(-G2, G5, -G6)
assert -G1*-G2*-G5*-G6 == Series(-G1, -G2, -G5, -G6)
assert G3*G4 == Series(G3, G4)
assert (G1*G2)*-(G5*G6) == \
Series(G1, G2, TransferFunction(-1, 1, s), Series(G5, G6))
assert G1*G2*(G5 + G6) == Series(G1, G2, Parallel(G5, G6))
c = symbols("c", commutative=False)
raises(ValueError, lambda: G3 * Matrix([1, 2, 3]))
raises(ValueError, lambda: G1 * c)
raises(ValueError, lambda: G3 * G5)
raises(ValueError, lambda: G5 * (s - 1))
raises(ValueError, lambda: 9 * G5)
raises(ValueError, lambda: G3 / Matrix([1, 2, 3]))
raises(ValueError, lambda: G6 / 0)
raises(ValueError, lambda: G3 / G5)
raises(ValueError, lambda: G5 / 2)
raises(ValueError, lambda: G5 / s**2)
raises(ValueError, lambda: (s - 4*s**2) / G2)
raises(ValueError, lambda: 0 / G4)
raises(ValueError, lambda: G5 / G6)
raises(ValueError, lambda: -G3 /G4)
raises(ValueError, lambda: G7 / (1 + G6))
raises(ValueError, lambda: G7 / (G5 * G6))
raises(ValueError, lambda: G7 / (G7 + (G5 + G6)))
def test_TransferFunction_is_proper():
omega_o, zeta, tau = symbols('omega_o, zeta, tau')
G1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
G2 = TransferFunction(tau - s**3, tau + p**4, tau)
G3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
G4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
assert G1.is_proper
assert G2.is_proper
assert G3.is_proper
assert not G4.is_proper
def test_TransferFunction_is_strictly_proper():
omega_o, zeta, tau = symbols('omega_o, zeta, tau')
tf1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
tf2 = TransferFunction(tau - s**3, tau + p**4, tau)
tf3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
tf4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
assert not tf1.is_strictly_proper
assert not tf2.is_strictly_proper
assert tf3.is_strictly_proper
assert not tf4.is_strictly_proper
def test_TransferFunction_is_biproper():
tau, omega_o, zeta = symbols('tau, omega_o, zeta')
tf1 = TransferFunction(omega_o**2, s**2 + p*omega_o*zeta*s + omega_o**2, omega_o)
tf2 = TransferFunction(tau - s**3, tau + p**4, tau)
tf3 = TransferFunction(a*b*s**3 + s**2 - a*p + s, b - s*p**2, p)
tf4 = TransferFunction(b*s**2 + p**2 - a*p + s, b - p**2, s)
assert tf1.is_biproper
assert tf2.is_biproper
assert not tf3.is_biproper
assert not tf4.is_biproper
def test_Series_construction():
tf = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
tf2 = TransferFunction(a2*p - s, a2*s + p, s)
tf3 = TransferFunction(a0*p + p**a1 - s, p, p)
tf4 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
inp = Function('X_d')(s)
out = Function('X')(s)
s0 = Series(tf, tf2)
assert s0.args == (tf, tf2)
assert s0.var == s
s1 = Series(Parallel(tf, -tf2), tf2)
assert s1.args == (Parallel(tf, -tf2), tf2)
assert s1.var == s
tf3_ = TransferFunction(inp, 1, s)
tf4_ = TransferFunction(-out, 1, s)
s2 = Series(tf, Parallel(tf3_, tf4_), tf2)
assert s2.args == (tf, Parallel(tf3_, tf4_), tf2)
s3 = Series(tf, tf2, tf4)
assert s3.args == (tf, tf2, tf4)
s4 = Series(tf3_, tf4_)
assert s4.args == (tf3_, tf4_)
assert s4.var == s
s6 = Series(tf2, tf4, Parallel(tf2, -tf), tf4)
assert s6.args == (tf2, tf4, Parallel(tf2, -tf), tf4)
s7 = Series(tf, tf2)
assert s0 == s7
assert not s0 == s2
raises(ValueError, lambda: Series(tf, tf3))
raises(ValueError, lambda: Series(tf, tf2, tf3, tf4))
raises(ValueError, lambda: Series(-tf3, tf2))
raises(TypeError, lambda: Series(2, tf, tf4))
raises(TypeError, lambda: Series(s**2 + p*s, tf3, tf2))
raises(TypeError, lambda: Series(tf3, Matrix([1, 2, 3, 4])))
def test_MIMOSeries_construction():
tf_1 = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
tf_2 = TransferFunction(a2*p - s, a2*s + p, s)
tf_3 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tfm_1 = TransferFunctionMatrix([[tf_1, tf_2, tf_3], [-tf_3, -tf_2, tf_1]])
tfm_2 = TransferFunctionMatrix([[-tf_2], [-tf_2], [-tf_3]])
tfm_3 = TransferFunctionMatrix([[-tf_3]])
tfm_4 = TransferFunctionMatrix([[TF3], [TF2], [-TF1]])
tfm_5 = TransferFunctionMatrix.from_Matrix(Matrix([1/p]), p)
s8 = MIMOSeries(tfm_2, tfm_1)
assert s8.args == (tfm_2, tfm_1)
assert s8.var == s
assert s8.shape == (s8.num_outputs, s8.num_inputs) == (2, 1)
s9 = MIMOSeries(tfm_3, tfm_2, tfm_1)
assert s9.args == (tfm_3, tfm_2, tfm_1)
assert s9.var == s
assert s9.shape == (s9.num_outputs, s9.num_inputs) == (2, 1)
s11 = MIMOSeries(tfm_3, MIMOParallel(-tfm_2, -tfm_4), tfm_1)
assert s11.args == (tfm_3, MIMOParallel(-tfm_2, -tfm_4), tfm_1)
assert s11.shape == (s11.num_outputs, s11.num_inputs) == (2, 1)
# arg cannot be empty tuple.
raises(ValueError, lambda: MIMOSeries())
# arg cannot contain SISO as well as MIMO systems.
raises(TypeError, lambda: MIMOSeries(tfm_1, tf_1))
# for all the adjascent transfer function matrices:
# no. of inputs of first TFM must be equal to the no. of outputs of the second TFM.
raises(ValueError, lambda: MIMOSeries(tfm_1, tfm_2, -tfm_1))
# all the TFMs must use the same complex variable.
raises(ValueError, lambda: MIMOSeries(tfm_3, tfm_5))
# Number or expression not allowed in the arguments.
raises(TypeError, lambda: MIMOSeries(2, tfm_2, tfm_3))
raises(TypeError, lambda: MIMOSeries(s**2 + p*s, -tfm_2, tfm_3))
raises(TypeError, lambda: MIMOSeries(Matrix([1/p]), tfm_3))
def test_Series_functions():
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tf2 = TransferFunction(k, 1, s)
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
assert tf1*tf2*tf3 == Series(tf1, tf2, tf3) == Series(Series(tf1, tf2), tf3) \
== Series(tf1, Series(tf2, tf3))
assert tf1*(tf2 + tf3) == Series(tf1, Parallel(tf2, tf3))
assert tf1*tf2 + tf5 == Parallel(Series(tf1, tf2), tf5)
assert tf1*tf2 - tf5 == Parallel(Series(tf1, tf2), -tf5)
assert tf1*tf2 + tf3 + tf5 == Parallel(Series(tf1, tf2), tf3, tf5)
assert tf1*tf2 - tf3 - tf5 == Parallel(Series(tf1, tf2), -tf3, -tf5)
assert tf1*tf2 - tf3 + tf5 == Parallel(Series(tf1, tf2), -tf3, tf5)
assert tf1*tf2 + tf3*tf5 == Parallel(Series(tf1, tf2), Series(tf3, tf5))
assert tf1*tf2 - tf3*tf5 == Parallel(Series(tf1, tf2), Series(TransferFunction(-1, 1, s), Series(tf3, tf5)))
assert tf2*tf3*(tf2 - tf1)*tf3 == Series(tf2, tf3, Parallel(tf2, -tf1), tf3)
assert -tf1*tf2 == Series(-tf1, tf2)
assert -(tf1*tf2) == Series(TransferFunction(-1, 1, s), Series(tf1, tf2))
raises(ValueError, lambda: tf1*tf2*tf4)
raises(ValueError, lambda: tf1*(tf2 - tf4))
raises(ValueError, lambda: tf3*Matrix([1, 2, 3]))
# evaluate=True -> doit()
assert Series(tf1, tf2, evaluate=True) == Series(tf1, tf2).doit() == \
TransferFunction(k, s**2 + 2*s*wn*zeta + wn**2, s)
assert Series(tf1, tf2, Parallel(tf1, -tf3), evaluate=True) == Series(tf1, tf2, Parallel(tf1, -tf3)).doit() == \
TransferFunction(k*(a2*s + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)**2, s)
assert Series(tf2, tf1, -tf3, evaluate=True) == Series(tf2, tf1, -tf3).doit() == \
TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert not Series(tf1, -tf2, evaluate=False) == Series(tf1, -tf2).doit()
assert Series(Parallel(tf1, tf2), Parallel(tf2, -tf3)).doit() == \
TransferFunction((k*(s**2 + 2*s*wn*zeta + wn**2) + 1)*(-a2*p + k*(a2*s + p) + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Series(-tf1, -tf2, -tf3).doit() == \
TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert -Series(tf1, tf2, tf3).doit() == \
TransferFunction(-k*(a2*p - s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Series(tf2, tf3, Parallel(tf2, -tf1), tf3).doit() == \
TransferFunction(k*(a2*p - s)**2*(k*(s**2 + 2*s*wn*zeta + wn**2) - 1), (a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Series(tf1, tf2).rewrite(TransferFunction) == TransferFunction(k, s**2 + 2*s*wn*zeta + wn**2, s)
assert Series(tf2, tf1, -tf3).rewrite(TransferFunction) == \
TransferFunction(k*(-a2*p + s), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
S1 = Series(Parallel(tf1, tf2), Parallel(tf2, -tf3))
assert S1.is_proper
assert not S1.is_strictly_proper
assert S1.is_biproper
S2 = Series(tf1, tf2, tf3)
assert S2.is_proper
assert S2.is_strictly_proper
assert not S2.is_biproper
S3 = Series(tf1, -tf2, Parallel(tf1, -tf3))
assert S3.is_proper
assert S3.is_strictly_proper
assert not S3.is_biproper
def test_MIMOSeries_functions():
tfm1 = TransferFunctionMatrix([[TF1, TF2, TF3], [-TF3, -TF2, TF1]])
tfm2 = TransferFunctionMatrix([[-TF1], [-TF2], [-TF3]])
tfm3 = TransferFunctionMatrix([[-TF1]])
tfm4 = TransferFunctionMatrix([[-TF2, -TF3], [-TF1, TF2]])
tfm5 = TransferFunctionMatrix([[TF2, -TF2], [-TF3, -TF2]])
tfm6 = TransferFunctionMatrix([[-TF3], [TF1]])
tfm7 = TransferFunctionMatrix([[TF1], [-TF2]])
assert tfm1*tfm2 + tfm6 == MIMOParallel(MIMOSeries(tfm2, tfm1), tfm6)
assert tfm1*tfm2 + tfm7 + tfm6 == MIMOParallel(MIMOSeries(tfm2, tfm1), tfm7, tfm6)
assert tfm1*tfm2 - tfm6 - tfm7 == MIMOParallel(MIMOSeries(tfm2, tfm1), -tfm6, -tfm7)
assert tfm4*tfm5 + (tfm4 - tfm5) == MIMOParallel(MIMOSeries(tfm5, tfm4), tfm4, -tfm5)
assert tfm4*-tfm6 + (-tfm4*tfm6) == MIMOParallel(MIMOSeries(-tfm6, tfm4), MIMOSeries(tfm6, -tfm4))
raises(ValueError, lambda: tfm1*tfm2 + TF1)
raises(TypeError, lambda: tfm1*tfm2 + a0)
raises(TypeError, lambda: tfm4*tfm6 - (s - 1))
raises(TypeError, lambda: tfm4*-tfm6 - 8)
raises(TypeError, lambda: (-1 + p**5) + tfm1*tfm2)
# Shape criteria.
raises(TypeError, lambda: -tfm1*tfm2 + tfm4)
raises(TypeError, lambda: tfm1*tfm2 - tfm4 + tfm5)
raises(TypeError, lambda: tfm1*tfm2 - tfm4*tfm5)
assert tfm1*tfm2*-tfm3 == MIMOSeries(-tfm3, tfm2, tfm1)
assert (tfm1*-tfm2)*tfm3 == MIMOSeries(tfm3, -tfm2, tfm1)
# Multiplication of a Series object with a SISO TF not allowed.
raises(ValueError, lambda: tfm4*tfm5*TF1)
raises(TypeError, lambda: tfm4*tfm5*a1)
raises(TypeError, lambda: tfm4*-tfm5*(s - 2))
raises(TypeError, lambda: tfm5*tfm4*9)
raises(TypeError, lambda: (-p**3 + 1)*tfm5*tfm4)
# Transfer function matrix in the arguments.
assert (MIMOSeries(tfm2, tfm1, evaluate=True) == MIMOSeries(tfm2, tfm1).doit()
== TransferFunctionMatrix(((TransferFunction(-k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2)**2 - (a2*s + p)**2,
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2, s),),
(TransferFunction(k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2),
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2, s),))))
# doit() should not cancel poles and zeros.
mat_1 = Matrix([[1/(1+s), (1+s)/(1+s**2+2*s)**3]])
mat_2 = Matrix([[(1+s)], [(1+s**2+2*s)**3/(1+s)]])
tm_1, tm_2 = TransferFunctionMatrix.from_Matrix(mat_1, s), TransferFunctionMatrix.from_Matrix(mat_2, s)
assert (MIMOSeries(tm_2, tm_1).doit()
== TransferFunctionMatrix(((TransferFunction(2*(s + 1)**2*(s**2 + 2*s + 1)**3, (s + 1)**2*(s**2 + 2*s + 1)**3, s),),)))
assert MIMOSeries(tm_2, tm_1).doit().simplify() == TransferFunctionMatrix(((TransferFunction(2, 1, s),),))
# calling doit() will expand the internal Series and Parallel objects.
assert (MIMOSeries(-tfm3, -tfm2, tfm1, evaluate=True)
== MIMOSeries(-tfm3, -tfm2, tfm1).doit()
== TransferFunctionMatrix(((TransferFunction(k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (a2*p - s)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (a2*s + p)**2,
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**3, s),),
(TransferFunction(-k**2*(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**2 + (-a2*p + s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*p - s)*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2),
(a2*s + p)**2*(s**2 + 2*s*wn*zeta + wn**2)**3, s),))))
assert (MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5, evaluate=True)
== MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5).doit()
== TransferFunctionMatrix(((TransferFunction(-k*(-a2*s - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s), TransferFunction(k*(-a2*p - \
k*(a2*s + p) + s), a2*s + p, s)), (TransferFunction(-k*(-a2*s - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2)), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s), \
TransferFunction((-a2*p + s)*(-a2*p - k*(a2*s + p) + s), (a2*s + p)**2, s)))) == MIMOSeries(MIMOParallel(tfm4, tfm5), tfm5).rewrite(TransferFunctionMatrix))
def test_Parallel_construction():
tf = TransferFunction(a0*s**3 + a1*s**2 - a2*s, b0*p**4 + b1*p**3 - b2*s*p, s)
tf2 = TransferFunction(a2*p - s, a2*s + p, s)
tf3 = TransferFunction(a0*p + p**a1 - s, p, p)
tf4 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
inp = Function('X_d')(s)
out = Function('X')(s)
p0 = Parallel(tf, tf2)
assert p0.args == (tf, tf2)
assert p0.var == s
p1 = Parallel(Series(tf, -tf2), tf2)
assert p1.args == (Series(tf, -tf2), tf2)
assert p1.var == s
tf3_ = TransferFunction(inp, 1, s)
tf4_ = TransferFunction(-out, 1, s)
p2 = Parallel(tf, Series(tf3_, -tf4_), tf2)
assert p2.args == (tf, Series(tf3_, -tf4_), tf2)
p3 = Parallel(tf, tf2, tf4)
assert p3.args == (tf, tf2, tf4)
p4 = Parallel(tf3_, tf4_)
assert p4.args == (tf3_, tf4_)
assert p4.var == s
p5 = Parallel(tf, tf2)
assert p0 == p5
assert not p0 == p1
p6 = Parallel(tf2, tf4, Series(tf2, -tf4))
assert p6.args == (tf2, tf4, Series(tf2, -tf4))
p7 = Parallel(tf2, tf4, Series(tf2, -tf), tf4)
assert p7.args == (tf2, tf4, Series(tf2, -tf), tf4)
raises(ValueError, lambda: Parallel(tf, tf3))
raises(ValueError, lambda: Parallel(tf, tf2, tf3, tf4))
raises(ValueError, lambda: Parallel(-tf3, tf4))
raises(TypeError, lambda: Parallel(2, tf, tf4))
raises(TypeError, lambda: Parallel(s**2 + p*s, tf3, tf2))
raises(TypeError, lambda: Parallel(tf3, Matrix([1, 2, 3, 4])))
def test_MIMOParallel_construction():
tfm1 = TransferFunctionMatrix([[TF1], [TF2], [TF3]])
tfm2 = TransferFunctionMatrix([[-TF3], [TF2], [TF1]])
tfm3 = TransferFunctionMatrix([[TF1]])
tfm4 = TransferFunctionMatrix([[TF2], [TF1], [TF3]])
tfm5 = TransferFunctionMatrix([[TF1, TF2], [TF2, TF1]])
tfm6 = TransferFunctionMatrix([[TF2, TF1], [TF1, TF2]])
tfm7 = TransferFunctionMatrix.from_Matrix(Matrix([[1/p]]), p)
p8 = MIMOParallel(tfm1, tfm2)
assert p8.args == (tfm1, tfm2)
assert p8.var == s
assert p8.shape == (p8.num_outputs, p8.num_inputs) == (3, 1)
p9 = MIMOParallel(MIMOSeries(tfm3, tfm1), tfm2)
assert p9.args == (MIMOSeries(tfm3, tfm1), tfm2)
assert p9.var == s
assert p9.shape == (p9.num_outputs, p9.num_inputs) == (3, 1)
p10 = MIMOParallel(tfm1, MIMOSeries(tfm3, tfm4), tfm2)
assert p10.args == (tfm1, MIMOSeries(tfm3, tfm4), tfm2)
assert p10.var == s
assert p10.shape == (p10.num_outputs, p10.num_inputs) == (3, 1)
p11 = MIMOParallel(tfm2, tfm1, tfm4)
assert p11.args == (tfm2, tfm1, tfm4)
assert p11.shape == (p11.num_outputs, p11.num_inputs) == (3, 1)
p12 = MIMOParallel(tfm6, tfm5)
assert p12.args == (tfm6, tfm5)
assert p12.shape == (p12.num_outputs, p12.num_inputs) == (2, 2)
p13 = MIMOParallel(tfm2, tfm4, MIMOSeries(-tfm3, tfm4), -tfm4)
assert p13.args == (tfm2, tfm4, MIMOSeries(-tfm3, tfm4), -tfm4)
assert p13.shape == (p13.num_outputs, p13.num_inputs) == (3, 1)
# arg cannot be empty tuple.
raises(TypeError, lambda: MIMOParallel(()))
# arg cannot contain SISO as well as MIMO systems.
raises(TypeError, lambda: MIMOParallel(tfm1, tfm2, TF1))
# all TFMs must have same shapes.
raises(TypeError, lambda: MIMOParallel(tfm1, tfm3, tfm4))
# all TFMs must be using the same complex variable.
raises(ValueError, lambda: MIMOParallel(tfm3, tfm7))
# Number or expression not allowed in the arguments.
raises(TypeError, lambda: MIMOParallel(2, tfm1, tfm4))
raises(TypeError, lambda: MIMOParallel(s**2 + p*s, -tfm4, tfm2))
def test_Parallel_functions():
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tf2 = TransferFunction(k, 1, s)
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
assert tf1 + tf2 + tf3 == Parallel(tf1, tf2, tf3)
assert tf1 + tf2 + tf3 + tf5 == Parallel(tf1, tf2, tf3, tf5)
assert tf1 + tf2 - tf3 - tf5 == Parallel(tf1, tf2, -tf3, -tf5)
assert tf1 + tf2*tf3 == Parallel(tf1, Series(tf2, tf3))
assert tf1 - tf2*tf3 == Parallel(tf1, -Series(tf2,tf3))
assert -tf1 - tf2 == Parallel(-tf1, -tf2)
assert -(tf1 + tf2) == Series(TransferFunction(-1, 1, s), Parallel(tf1, tf2))
assert (tf2 + tf3)*tf1 == Series(Parallel(tf2, tf3), tf1)
assert (tf1 + tf2)*(tf3*tf5) == Series(Parallel(tf1, tf2), tf3, tf5)
assert -(tf2 + tf3)*-tf5 == Series(TransferFunction(-1, 1, s), Parallel(tf2, tf3), -tf5)
assert tf2 + tf3 + tf2*tf1 + tf5 == Parallel(tf2, tf3, Series(tf2, tf1), tf5)
assert tf2 + tf3 + tf2*tf1 - tf3 == Parallel(tf2, tf3, Series(tf2, tf1), -tf3)
assert (tf1 + tf2 + tf5)*(tf3 + tf5) == Series(Parallel(tf1, tf2, tf5), Parallel(tf3, tf5))
raises(ValueError, lambda: tf1 + tf2 + tf4)
raises(ValueError, lambda: tf1 - tf2*tf4)
raises(ValueError, lambda: tf3 + Matrix([1, 2, 3]))
# evaluate=True -> doit()
assert Parallel(tf1, tf2, evaluate=True) == Parallel(tf1, tf2).doit() == \
TransferFunction(k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s)
assert Parallel(tf1, tf2, Series(-tf1, tf3), evaluate=True) == \
Parallel(tf1, tf2, Series(-tf1, tf3)).doit() == TransferFunction(k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)**2 + \
(-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) + (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)*(s**2 + \
2*s*wn*zeta + wn**2)**2, s)
assert Parallel(tf2, tf1, -tf3, evaluate=True) == Parallel(tf2, tf1, -tf3).doit() == \
TransferFunction(a2*s + k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2) \
, (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert not Parallel(tf1, -tf2, evaluate=False) == Parallel(tf1, -tf2).doit()
assert Parallel(Series(tf1, tf2), Series(tf2, tf3)).doit() == \
TransferFunction(k*(a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2) + k*(a2*s + p), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Parallel(-tf1, -tf2, -tf3).doit() == \
TransferFunction(-a2*s - k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + wn**2), \
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert -Parallel(tf1, tf2, tf3).doit() == \
TransferFunction(-a2*s - k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - p - (a2*p - s)*(s**2 + 2*s*wn*zeta + wn**2), \
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Parallel(tf2, tf3, Series(tf2, -tf1), tf3).doit() == \
TransferFunction(k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) - k*(a2*s + p) + (2*a2*p - 2*s)*(s**2 + 2*s*wn*zeta \
+ wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Parallel(tf1, tf2).rewrite(TransferFunction) == \
TransferFunction(k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s)
assert Parallel(tf2, tf1, -tf3).rewrite(TransferFunction) == \
TransferFunction(a2*s + k*(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2) + p + (-a2*p + s)*(s**2 + 2*s*wn*zeta + \
wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Parallel(tf1, Parallel(tf2, tf3)) == Parallel(tf1, tf2, tf3) == Parallel(Parallel(tf1, tf2), tf3)
P1 = Parallel(Series(tf1, tf2), Series(tf2, tf3))
assert P1.is_proper
assert not P1.is_strictly_proper
assert P1.is_biproper
P2 = Parallel(tf1, -tf2, -tf3)
assert P2.is_proper
assert not P2.is_strictly_proper
assert P2.is_biproper
P3 = Parallel(tf1, -tf2, Series(tf1, tf3))
assert P3.is_proper
assert not P3.is_strictly_proper
assert P3.is_biproper
def test_MIMOParallel_functions():
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
tfm1 = TransferFunctionMatrix([[TF1], [TF2], [TF3]])
tfm2 = TransferFunctionMatrix([[-TF2], [tf5], [-TF1]])
tfm3 = TransferFunctionMatrix([[tf5], [-tf5], [TF2]])
tfm4 = TransferFunctionMatrix([[TF2, -tf5], [TF1, tf5]])
tfm5 = TransferFunctionMatrix([[TF1, TF2], [TF3, -tf5]])
tfm6 = TransferFunctionMatrix([[-TF2]])
tfm7 = TransferFunctionMatrix([[tf4], [-tf4], [tf4]])
assert tfm1 + tfm2 + tfm3 == MIMOParallel(tfm1, tfm2, tfm3) == MIMOParallel(MIMOParallel(tfm1, tfm2), tfm3)
assert tfm2 - tfm1 - tfm3 == MIMOParallel(tfm2, -tfm1, -tfm3)
assert tfm2 - tfm3 + (-tfm1*tfm6*-tfm6) == MIMOParallel(tfm2, -tfm3, MIMOSeries(-tfm6, tfm6, -tfm1))
assert tfm1 + tfm1 - (-tfm1*tfm6) == MIMOParallel(tfm1, tfm1, -MIMOSeries(tfm6, -tfm1))
assert tfm2 - tfm3 - tfm1 + tfm2 == MIMOParallel(tfm2, -tfm3, -tfm1, tfm2)
assert tfm1 + tfm2 - tfm3 - tfm1 == MIMOParallel(tfm1, tfm2, -tfm3, -tfm1)
raises(ValueError, lambda: tfm1 + tfm2 + TF2)
raises(TypeError, lambda: tfm1 - tfm2 - a1)
raises(TypeError, lambda: tfm2 - tfm3 - (s - 1))
raises(TypeError, lambda: -tfm3 - tfm2 - 9)
raises(TypeError, lambda: (1 - p**3) - tfm3 - tfm2)
# All TFMs must use the same complex var. tfm7 uses 'p'.
raises(ValueError, lambda: tfm3 - tfm2 - tfm7)
raises(ValueError, lambda: tfm2 - tfm1 + tfm7)
# (tfm1 +/- tfm2) has (3, 1) shape while tfm4 has (2, 2) shape.
raises(TypeError, lambda: tfm1 + tfm2 + tfm4)
raises(TypeError, lambda: (tfm1 - tfm2) - tfm4)
assert (tfm1 + tfm2)*tfm6 == MIMOSeries(tfm6, MIMOParallel(tfm1, tfm2))
assert (tfm2 - tfm3)*tfm6*-tfm6 == MIMOSeries(-tfm6, tfm6, MIMOParallel(tfm2, -tfm3))
assert (tfm2 - tfm1 - tfm3)*(tfm6 + tfm6) == MIMOSeries(MIMOParallel(tfm6, tfm6), MIMOParallel(tfm2, -tfm1, -tfm3))
raises(ValueError, lambda: (tfm4 + tfm5)*TF1)
raises(TypeError, lambda: (tfm2 - tfm3)*a2)
raises(TypeError, lambda: (tfm3 + tfm2)*(s - 6))
raises(TypeError, lambda: (tfm1 + tfm2 + tfm3)*0)
raises(TypeError, lambda: (1 - p**3)*(tfm1 + tfm3))
# (tfm3 - tfm2) has (3, 1) shape while tfm4*tfm5 has (2, 2) shape.
raises(ValueError, lambda: (tfm3 - tfm2)*tfm4*tfm5)
# (tfm1 - tfm2) has (3, 1) shape while tfm5 has (2, 2) shape.
raises(ValueError, lambda: (tfm1 - tfm2)*tfm5)
# TFM in the arguments.
assert (MIMOParallel(tfm1, tfm2, evaluate=True) == MIMOParallel(tfm1, tfm2).doit()
== MIMOParallel(tfm1, tfm2).rewrite(TransferFunctionMatrix)
== TransferFunctionMatrix(((TransferFunction(-k*(s**2 + 2*s*wn*zeta + wn**2) + 1, s**2 + 2*s*wn*zeta + wn**2, s),), \
(TransferFunction(-a0 + a1*s**2 + a2*s + k*(a0 + s), a0 + s, s),), (TransferFunction(-a2*s - p + (a2*p - s)* \
(s**2 + 2*s*wn*zeta + wn**2), (a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s),))))
def test_Feedback_construction():
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tf2 = TransferFunction(k, 1, s)
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
tf6 = TransferFunction(s - p, p + s, p)
f1 = Feedback(TransferFunction(1, 1, s), tf1*tf2*tf3)
assert f1.args == (TransferFunction(1, 1, s), Series(tf1, tf2, tf3), -1)
assert f1.sys1 == TransferFunction(1, 1, s)
assert f1.sys2 == Series(tf1, tf2, tf3)
assert f1.var == s
f2 = Feedback(tf1, tf2*tf3)
assert f2.args == (tf1, Series(tf2, tf3), -1)
assert f2.sys1 == tf1
assert f2.sys2 == Series(tf2, tf3)
assert f2.var == s
f3 = Feedback(tf1*tf2, tf5)
assert f3.args == (Series(tf1, tf2), tf5, -1)
assert f3.sys1 == Series(tf1, tf2)
f4 = Feedback(tf4, tf6)
assert f4.args == (tf4, tf6, -1)
assert f4.sys1 == tf4
assert f4.var == p
f5 = Feedback(tf5, TransferFunction(1, 1, s))
assert f5.args == (tf5, TransferFunction(1, 1, s), -1)
assert f5.var == s
assert f5 == Feedback(tf5) # When sys2 is not passed explicitly, it is assumed to be unit tf.
f6 = Feedback(TransferFunction(1, 1, p), tf4)
assert f6.args == (TransferFunction(1, 1, p), tf4, -1)
assert f6.var == p
f7 = -Feedback(tf4*tf6, TransferFunction(1, 1, p))
assert f7.args == (Series(TransferFunction(-1, 1, p), Series(tf4, tf6)), -TransferFunction(1, 1, p), -1)
assert f7.sys1 == Series(TransferFunction(-1, 1, p), Series(tf4, tf6))
# denominator can't be a Parallel instance
raises(TypeError, lambda: Feedback(tf1, tf2 + tf3))
raises(TypeError, lambda: Feedback(tf1, Matrix([1, 2, 3])))
raises(TypeError, lambda: Feedback(TransferFunction(1, 1, s), s - 1))
raises(TypeError, lambda: Feedback(1, 1))
# raises(ValueError, lambda: Feedback(TransferFunction(1, 1, s), TransferFunction(1, 1, s)))
raises(ValueError, lambda: Feedback(tf2, tf4*tf5))
raises(ValueError, lambda: Feedback(tf2, tf1, 1.5)) # `sign` can only be -1 or 1
raises(ValueError, lambda: Feedback(tf1, -tf1**-1)) # denominator can't be zero
raises(ValueError, lambda: Feedback(tf4, tf5)) # Both systems should use the same `var`
def test_Feedback_functions():
tf = TransferFunction(1, 1, s)
tf1 = TransferFunction(1, s**2 + 2*zeta*wn*s + wn**2, s)
tf2 = TransferFunction(k, 1, s)
tf3 = TransferFunction(a2*p - s, a2*s + p, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
tf6 = TransferFunction(s - p, p + s, p)
assert tf / (tf + tf1) == Feedback(tf, tf1)
assert tf / (tf + tf1*tf2*tf3) == Feedback(tf, tf1*tf2*tf3)
assert tf1 / (tf + tf1*tf2*tf3) == Feedback(tf1, tf2*tf3)
assert (tf1*tf2) / (tf + tf1*tf2) == Feedback(tf1*tf2, tf)
assert (tf1*tf2) / (tf + tf1*tf2*tf5) == Feedback(tf1*tf2, tf5)
assert (tf1*tf2) / (tf + tf1*tf2*tf5*tf3) in (Feedback(tf1*tf2, tf5*tf3), Feedback(tf1*tf2, tf3*tf5))
assert tf4 / (TransferFunction(1, 1, p) + tf4*tf6) == Feedback(tf4, tf6)
assert tf5 / (tf + tf5) == Feedback(tf5, tf)
raises(TypeError, lambda: tf1*tf2*tf3 / (1 + tf1*tf2*tf3))
raises(ValueError, lambda: tf1*tf2*tf3 / tf3*tf5)
raises(ValueError, lambda: tf2*tf3 / (tf + tf2*tf3*tf4))
assert Feedback(tf, tf1*tf2*tf3).doit() == \
TransferFunction((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), k*(a2*p - s) + \
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Feedback(tf, tf1*tf2*tf3).sensitivity == \
1/(k*(a2*p - s)/((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
assert Feedback(tf1, tf2*tf3).doit() == \
TransferFunction((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2), (k*(a2*p - s) + \
(a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Feedback(tf1, tf2*tf3).sensitivity == \
1/(k*(a2*p - s)/((a2*s + p)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
assert Feedback(tf1*tf2, tf5).doit() == \
TransferFunction(k*(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2), (k*(-a0 + a1*s**2 + a2*s) + \
(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Feedback(tf1*tf2, tf5, 1).sensitivity == \
1/(-k*(-a0 + a1*s**2 + a2*s)/((a0 + s)*(s**2 + 2*s*wn*zeta + wn**2)) + 1)
assert Feedback(tf4, tf6).doit() == \
TransferFunction(p*(p + s)*(a0*p + p**a1 - s), p*(p*(p + s) + (-p + s)*(a0*p + p**a1 - s)), p)
assert -Feedback(tf4*tf6, TransferFunction(1, 1, p)).doit() == \
TransferFunction(-p*(-p + s)*(p + s)*(a0*p + p**a1 - s), p*(p + s)*(p*(p + s) + (-p + s)*(a0*p + p**a1 - s)), p)
assert Feedback(tf, tf).doit() == TransferFunction(1, 2, s)
assert Feedback(tf1, tf2*tf5).rewrite(TransferFunction) == \
TransferFunction((a0 + s)*(s**2 + 2*s*wn*zeta + wn**2), (k*(-a0 + a1*s**2 + a2*s) + \
(a0 + s)*(s**2 + 2*s*wn*zeta + wn**2))*(s**2 + 2*s*wn*zeta + wn**2), s)
assert Feedback(TransferFunction(1, 1, p), tf4).rewrite(TransferFunction) == \
TransferFunction(p, a0*p + p + p**a1 - s, p)
def test_MIMOFeedback_construction():
tf1 = TransferFunction(1, s, s)
tf2 = TransferFunction(s, s**3 - 1, s)
tf3 = TransferFunction(s, s + 1, s)
tf4 = TransferFunction(s, s**2 + 1, s)
tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
tfm_2 = TransferFunctionMatrix([[tf2, tf3], [tf4, tf1]])
tfm_3 = TransferFunctionMatrix([[tf3, tf4], [tf1, tf2]])
f1 = MIMOFeedback(tfm_1, tfm_2)
assert f1.args == (tfm_1, tfm_2, -1)
assert f1.sys1 == tfm_1
assert f1.sys2 == tfm_2
assert f1.var == s
assert f1.sign == -1
assert -(-f1) == f1
f2 = MIMOFeedback(tfm_2, tfm_1, 1)
assert f2.args == (tfm_2, tfm_1, 1)
assert f2.sys1 == tfm_2
assert f2.sys2 == tfm_1
assert f2.var == s
assert f2.sign == 1
f3 = MIMOFeedback(tfm_1, MIMOSeries(tfm_3, tfm_2))
assert f3.args == (tfm_1, MIMOSeries(tfm_3, tfm_2), -1)
assert f3.sys1 == tfm_1
assert f3.sys2 == MIMOSeries(tfm_3, tfm_2)
assert f3.var == s
assert f3.sign == -1
mat = Matrix([[1, 1/s], [0, 1]])
sys1 = controller = TransferFunctionMatrix.from_Matrix(mat, s)
f4 = MIMOFeedback(sys1, controller)
assert f4.args == (sys1, controller, -1)
assert f4.sys1 == f4.sys2 == sys1
def test_MIMOFeedback_errors():
tf1 = TransferFunction(1, s, s)
tf2 = TransferFunction(s, s**3 - 1, s)
tf3 = TransferFunction(s, s - 1, s)
tf4 = TransferFunction(s, s**2 + 1, s)
tf5 = TransferFunction(1, 1, s)
tf6 = TransferFunction(-1, s - 1, s)
tfm_1 = TransferFunctionMatrix([[tf1, tf2], [tf3, tf4]])
tfm_2 = TransferFunctionMatrix([[tf2, tf3], [tf4, tf1]])
tfm_3 = TransferFunctionMatrix.from_Matrix(eye(2), var=s)
tfm_4 = TransferFunctionMatrix([[tf1, tf5], [tf5, tf5]])
tfm_5 = TransferFunctionMatrix([[-tf3, tf3], [tf3, tf6]])
# tfm_4 is inverse of tfm_5. Therefore tfm_5*tfm_4 = I
tfm_6 = TransferFunctionMatrix([[-tf3]])
tfm_7 = TransferFunctionMatrix([[tf3, tf4]])
# Unsupported Types
raises(TypeError, lambda: MIMOFeedback(tf1, tf2))
raises(TypeError, lambda: MIMOFeedback(MIMOParallel(tfm_1, tfm_2), tfm_3))
# Shape Errors
raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_6, 1))
raises(ValueError, lambda: MIMOFeedback(tfm_7, tfm_7))
# sign not 1/-1
raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_2, -2))
# Non-Invertible Systems
raises(ValueError, lambda: MIMOFeedback(tfm_5, tfm_4, 1))
raises(ValueError, lambda: MIMOFeedback(tfm_4, -tfm_5))
raises(ValueError, lambda: MIMOFeedback(tfm_3, tfm_3, 1))
# Variable not same in both the systems
tfm_8 = TransferFunctionMatrix.from_Matrix(eye(2), var=p)
raises(ValueError, lambda: MIMOFeedback(tfm_1, tfm_8, 1))
def test_MIMOFeedback_functions():
tf1 = TransferFunction(1, s, s)
tf2 = TransferFunction(s, s - 1, s)
tf3 = TransferFunction(1, 1, s)
tf4 = TransferFunction(-1, s - 1, s)
tfm_1 = TransferFunctionMatrix.from_Matrix(eye(2), var=s)
tfm_2 = TransferFunctionMatrix([[tf1, tf3], [tf3, tf3]])
tfm_3 = TransferFunctionMatrix([[-tf2, tf2], [tf2, tf4]])
tfm_4 = TransferFunctionMatrix([[tf1, tf2], [-tf2, tf1]])
# sensitivity, doit(), rewrite()
F_1 = MIMOFeedback(tfm_2, tfm_3)
F_2 = MIMOFeedback(tfm_2, MIMOSeries(tfm_4, -tfm_1), 1)
assert F_1.sensitivity == Matrix([[1/2, 0], [0, 1/2]])
assert F_2.sensitivity == Matrix([[(-2*s**4 + s**2)/(s**2 - s + 1),
(2*s**3 - s**2)/(s**2 - s + 1)], [-s**2, s]])
assert F_1.doit() == \
TransferFunctionMatrix(((TransferFunction(1, 2*s, s),
TransferFunction(1, 2, s)), (TransferFunction(1, 2, s),
TransferFunction(1, 2, s)))) == F_1.rewrite(TransferFunctionMatrix)
assert F_2.doit(cancel=False, expand=True) == \
TransferFunctionMatrix(((TransferFunction(-s**5 + 2*s**4 - 2*s**3 + s**2, s**5 - 2*s**4 + 3*s**3 - 2*s**2 + s, s),
TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
assert F_2.doit(cancel=False) == \
TransferFunctionMatrix(((TransferFunction(s*(2*s**3 - s**2)*(s**2 - s + 1) + \
(-2*s**4 + s**2)*(s**2 - s + 1), s*(s**2 - s + 1)**2, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)),
(TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
assert F_2.doit() == \
TransferFunctionMatrix(((TransferFunction(s*(-2*s**2 + s*(2*s - 1) + 1), s**2 - s + 1, s),
TransferFunction(-2*s**3*(s - 1), s**2 - s + 1, s)), (TransferFunction(0, 1, s), TransferFunction(s*(1 - s), 1, s))))
assert F_2.doit(expand=True) == \
TransferFunctionMatrix(((TransferFunction(-s**2 + s, s**2 - s + 1, s), TransferFunction(-2*s**4 + 2*s**3, s**2 - s + 1, s)),
(TransferFunction(0, 1, s), TransferFunction(-s**2 + s, 1, s))))
assert -(F_1.doit()) == (-F_1).doit() # First negating then calculating vs calculating then negating.
def test_TransferFunctionMatrix_construction():
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
tf4 = TransferFunction(a0*p + p**a1 - s, p, p)
tfm3_ = TransferFunctionMatrix([[-TF3]])
assert tfm3_.shape == (tfm3_.num_outputs, tfm3_.num_inputs) == (1, 1)
assert tfm3_.args == Tuple(Tuple(Tuple(-TF3)))
assert tfm3_.var == s
tfm5 = TransferFunctionMatrix([[TF1, -TF2], [TF3, tf5]])
assert tfm5.shape == (tfm5.num_outputs, tfm5.num_inputs) == (2, 2)
assert tfm5.args == Tuple(Tuple(Tuple(TF1, -TF2), Tuple(TF3, tf5)))
assert tfm5.var == s
tfm7 = TransferFunctionMatrix([[TF1, TF2], [TF3, -tf5], [-tf5, TF2]])
assert tfm7.shape == (tfm7.num_outputs, tfm7.num_inputs) == (3, 2)
assert tfm7.args == Tuple(Tuple(Tuple(TF1, TF2), Tuple(TF3, -tf5), Tuple(-tf5, TF2)))
assert tfm7.var == s
# all transfer functions will use the same complex variable. tf4 uses 'p'.
raises(ValueError, lambda: TransferFunctionMatrix([[TF1], [TF2], [tf4]]))
raises(ValueError, lambda: TransferFunctionMatrix([[TF1, tf4], [TF3, tf5]]))
# length of all the lists in the TFM should be equal.
raises(ValueError, lambda: TransferFunctionMatrix([[TF1], [TF3, tf5]]))
raises(ValueError, lambda: TransferFunctionMatrix([[TF1, TF3], [tf5]]))
# lists should only support transfer functions in them.
raises(TypeError, lambda: TransferFunctionMatrix([[TF1, TF2], [TF3, Matrix([1, 2])]]))
raises(TypeError, lambda: TransferFunctionMatrix([[TF1, Matrix([1, 2])], [TF3, TF2]]))
# `arg` should strictly be nested list of TransferFunction
raises(ValueError, lambda: TransferFunctionMatrix([TF1, TF2, tf5]))
raises(ValueError, lambda: TransferFunctionMatrix([TF1]))
def test_TransferFunctionMatrix_functions():
tf5 = TransferFunction(a1*s**2 + a2*s - a0, s + a0, s)
# Classmethod (from_matrix)
mat_1 = ImmutableMatrix([
[s*(s + 1)*(s - 3)/(s**4 + 1), 2],
[p, p*(s + 1)/(s*(s**1 + 1))]
])
mat_2 = ImmutableMatrix([[(2*s + 1)/(s**2 - 9)]])
mat_3 = ImmutableMatrix([[1, 2], [3, 4]])
assert TransferFunctionMatrix.from_Matrix(mat_1, s) == \
TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)],
[TransferFunction(p, 1, s), TransferFunction(p, s, s)]])
assert TransferFunctionMatrix.from_Matrix(mat_2, s) == \
TransferFunctionMatrix([[TransferFunction(2*s + 1, s**2 - 9, s)]])
assert TransferFunctionMatrix.from_Matrix(mat_3, p) == \
TransferFunctionMatrix([[TransferFunction(1, 1, p), TransferFunction(2, 1, p)],
[TransferFunction(3, 1, p), TransferFunction(4, 1, p)]])
# Negating a TFM
tfm1 = TransferFunctionMatrix([[TF1], [TF2]])
assert -tfm1 == TransferFunctionMatrix([[-TF1], [-TF2]])
tfm2 = TransferFunctionMatrix([[TF1, TF2, TF3], [tf5, -TF1, -TF3]])
assert -tfm2 == TransferFunctionMatrix([[-TF1, -TF2, -TF3], [-tf5, TF1, TF3]])
# subs()
H_1 = TransferFunctionMatrix.from_Matrix(mat_1, s)
H_2 = TransferFunctionMatrix([[TransferFunction(a*p*s, k*s**2, s), TransferFunction(p*s, k*(s**2 - a), s)]])
assert H_1.subs(p, 1) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]])
assert H_1.subs({p: 1}) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]])
assert H_1.subs({p: 1, s: 1}) == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s)], [TransferFunction(1, 1, s), TransferFunction(1, s, s)]]) # This should ignore `s` as it is `var`
assert H_2.subs(p, 2) == TransferFunctionMatrix([[TransferFunction(2*a*s, k*s**2, s), TransferFunction(2*s, k*(-a + s**2), s)]])
assert H_2.subs(k, 1) == TransferFunctionMatrix([[TransferFunction(a*p*s, s**2, s), TransferFunction(p*s, -a + s**2, s)]])
assert H_2.subs(a, 0) == TransferFunctionMatrix([[TransferFunction(0, k*s**2, s), TransferFunction(p*s, k*s**2, s)]])
assert H_2.subs({p: 1, k: 1, a: a0}) == TransferFunctionMatrix([[TransferFunction(a0*s, s**2, s), TransferFunction(s, -a0 + s**2, s)]])
# transpose()
assert H_1.transpose() == TransferFunctionMatrix([[TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(p, 1, s)], [TransferFunction(2, 1, s), TransferFunction(p, s, s)]])
assert H_2.transpose() == TransferFunctionMatrix([[TransferFunction(a*p*s, k*s**2, s)], [TransferFunction(p*s, k*(-a + s**2), s)]])
assert H_1.transpose().transpose() == H_1
assert H_2.transpose().transpose() == H_2
# elem_poles()
assert H_1.elem_poles() == [[[-sqrt(2)/2 - sqrt(2)*I/2, -sqrt(2)/2 + sqrt(2)*I/2, sqrt(2)/2 - sqrt(2)*I/2, sqrt(2)/2 + sqrt(2)*I/2], []],
[[], [0]]]
assert H_2.elem_poles() == [[[0, 0], [sqrt(a), -sqrt(a)]]]
assert tfm2.elem_poles() == [[[wn*(-zeta + sqrt((zeta - 1)*(zeta + 1))), wn*(-zeta - sqrt((zeta - 1)*(zeta + 1)))], [], [-p/a2]],
[[-a0], [wn*(-zeta + sqrt((zeta - 1)*(zeta + 1))), wn*(-zeta - sqrt((zeta - 1)*(zeta + 1)))], [-p/a2]]]
# elem_zeros()
assert H_1.elem_zeros() == [[[-1, 0, 3], []], [[], []]]
assert H_2.elem_zeros() == [[[0], [0]]]
assert tfm2.elem_zeros() == [[[], [], [a2*p]],
[[-a2/(2*a1) - sqrt(4*a0*a1 + a2**2)/(2*a1), -a2/(2*a1) + sqrt(4*a0*a1 + a2**2)/(2*a1)], [], [a2*p]]]
# doit()
H_3 = TransferFunctionMatrix([[Series(TransferFunction(1, s**3 - 3, s), TransferFunction(s**2 - 2*s + 5, 1, s), TransferFunction(1, s, s))]])
H_4 = TransferFunctionMatrix([[Parallel(TransferFunction(s**3 - 3, 4*s**4 - s**2 - 2*s + 5, s), TransferFunction(4 - s**3, 4*s**4 - s**2 - 2*s + 5, s))]])
assert H_3.doit() == TransferFunctionMatrix([[TransferFunction(s**2 - 2*s + 5, s*(s**3 - 3), s)]])
assert H_4.doit() == TransferFunctionMatrix([[TransferFunction(1, 4*s**4 - s**2 - 2*s + 5, s)]])
# _flat()
assert H_1._flat() == [TransferFunction(s*(s - 3)*(s + 1), s**4 + 1, s), TransferFunction(2, 1, s), TransferFunction(p, 1, s), TransferFunction(p, s, s)]
assert H_2._flat() == [TransferFunction(a*p*s, k*s**2, s), TransferFunction(p*s, k*(-a + s**2), s)]
assert H_3._flat() == [Series(TransferFunction(1, s**3 - 3, s), TransferFunction(s**2 - 2*s + 5, 1, s), TransferFunction(1, s, s))]
assert H_4._flat() == [Parallel(TransferFunction(s**3 - 3, 4*s**4 - s**2 - 2*s + 5, s), TransferFunction(4 - s**3, 4*s**4 - s**2 - 2*s + 5, s))]
# evalf()
assert H_1.evalf() == \
TransferFunctionMatrix(((TransferFunction(s*(s - 3.0)*(s + 1.0), s**4 + 1.0, s), TransferFunction(2.0, 1, s)), (TransferFunction(1.0*p, 1, s), TransferFunction(p, s, s))))
assert H_2.subs({a:3.141, p:2.88, k:2}).evalf() == \
TransferFunctionMatrix(((TransferFunction(4.5230399999999999494093572138808667659759521484375, s, s),
TransferFunction(2.87999999999999989341858963598497211933135986328125*s, 2.0*s**2 - 6.282000000000000028421709430404007434844970703125, s)),))
# simplify()
H_5 = TransferFunctionMatrix([[TransferFunction(s**5 + s**3 + s, s - s**2, s),
TransferFunction((s + 3)*(s - 1), (s - 1)*(s + 5), s)]])
assert H_5.simplify() == simplify(H_5) == \
TransferFunctionMatrix(((TransferFunction(-s**4 - s**2 - 1, s - 1, s), TransferFunction(s + 3, s + 5, s)),))
# expand()
assert (H_1.expand()
== TransferFunctionMatrix(((TransferFunction(s**3 - 2*s**2 - 3*s, s**4 + 1, s), TransferFunction(2, 1, s)),
(TransferFunction(p, 1, s), TransferFunction(p, s, s)))))
assert H_5.expand() == \
TransferFunctionMatrix(((TransferFunction(s**5 + s**3 + s, -s**2 + s, s), TransferFunction(s**2 + 2*s - 3, s**2 + 4*s - 5, s)),))
|
7a670612a41e0affa4549c727d7eba4d9c5a849f296339c52c4d5fcb2cde6467 | from sympy.core.numbers import Integer
from sympy.core.symbol import Symbol
from sympy.physics.quantum.qexpr import QExpr, _qsympify_sequence
from sympy.physics.quantum.hilbert import HilbertSpace
from sympy.core.containers import Tuple
x = Symbol('x')
y = Symbol('y')
def test_qexpr_new():
q = QExpr(0)
assert q.label == (0,)
assert q.hilbert_space == HilbertSpace()
assert q.is_commutative is False
q = QExpr(0, 1)
assert q.label == (Integer(0), Integer(1))
q = QExpr._new_rawargs(HilbertSpace(), Integer(0), Integer(1))
assert q.label == (Integer(0), Integer(1))
assert q.hilbert_space == HilbertSpace()
def test_qexpr_commutative():
q1 = QExpr(x)
q2 = QExpr(y)
assert q1.is_commutative is False
assert q2.is_commutative is False
assert q1*q2 != q2*q1
q = QExpr._new_rawargs(Integer(0), Integer(1), HilbertSpace())
assert q.is_commutative is False
def test_qexpr_commutative_free_symbols():
q1 = QExpr(x)
assert q1.free_symbols.pop().is_commutative is False
q2 = QExpr('q2')
assert q2.free_symbols.pop().is_commutative is False
def test_qexpr_subs():
q1 = QExpr(x, y)
assert q1.subs(x, y) == QExpr(y, y)
assert q1.subs({x: 1, y: 2}) == QExpr(1, 2)
def test_qsympify():
assert _qsympify_sequence([[1, 2], [1, 3]]) == (Tuple(1, 2), Tuple(1, 3))
assert _qsympify_sequence(([1, 2, [3, 4, [2, ]], 1], 3)) == \
(Tuple(1, 2, Tuple(3, 4, Tuple(2,)), 1), 3)
assert _qsympify_sequence((1,)) == (1,)
|
061b31fe08f972962fe0185525142887194a93fadca788c7b524654cffa6ff1b | from sympy.core.mul import Mul
from sympy.core.numbers import I
from sympy.matrices.dense import Matrix
from sympy.printing.latex import latex
from sympy.physics.quantum import (Dagger, Commutator, AntiCommutator, qapply,
Operator, represent)
from sympy.physics.quantum.pauli import (SigmaOpBase, SigmaX, SigmaY, SigmaZ,
SigmaMinus, SigmaPlus,
qsimplify_pauli)
from sympy.physics.quantum.pauli import SigmaZKet, SigmaZBra
from sympy.testing.pytest import raises
sx, sy, sz = SigmaX(), SigmaY(), SigmaZ()
sx1, sy1, sz1 = SigmaX(1), SigmaY(1), SigmaZ(1)
sx2, sy2, sz2 = SigmaX(2), SigmaY(2), SigmaZ(2)
sm, sp = SigmaMinus(), SigmaPlus()
sm1, sp1 = SigmaMinus(1), SigmaPlus(1)
A, B = Operator("A"), Operator("B")
def test_pauli_operators_types():
assert isinstance(sx, SigmaOpBase) and isinstance(sx, SigmaX)
assert isinstance(sy, SigmaOpBase) and isinstance(sy, SigmaY)
assert isinstance(sz, SigmaOpBase) and isinstance(sz, SigmaZ)
assert isinstance(sm, SigmaOpBase) and isinstance(sm, SigmaMinus)
assert isinstance(sp, SigmaOpBase) and isinstance(sp, SigmaPlus)
def test_pauli_operators_commutator():
assert Commutator(sx, sy).doit() == 2 * I * sz
assert Commutator(sy, sz).doit() == 2 * I * sx
assert Commutator(sz, sx).doit() == 2 * I * sy
def test_pauli_operators_commutator_with_labels():
assert Commutator(sx1, sy1).doit() == 2 * I * sz1
assert Commutator(sy1, sz1).doit() == 2 * I * sx1
assert Commutator(sz1, sx1).doit() == 2 * I * sy1
assert Commutator(sx2, sy2).doit() == 2 * I * sz2
assert Commutator(sy2, sz2).doit() == 2 * I * sx2
assert Commutator(sz2, sx2).doit() == 2 * I * sy2
assert Commutator(sx1, sy2).doit() == 0
assert Commutator(sy1, sz2).doit() == 0
assert Commutator(sz1, sx2).doit() == 0
def test_pauli_operators_anticommutator():
assert AntiCommutator(sy, sz).doit() == 0
assert AntiCommutator(sz, sx).doit() == 0
assert AntiCommutator(sx, sm).doit() == 1
assert AntiCommutator(sx, sp).doit() == 1
def test_pauli_operators_adjoint():
assert Dagger(sx) == sx
assert Dagger(sy) == sy
assert Dagger(sz) == sz
def test_pauli_operators_adjoint_with_labels():
assert Dagger(sx1) == sx1
assert Dagger(sy1) == sy1
assert Dagger(sz1) == sz1
assert Dagger(sx1) != sx2
assert Dagger(sy1) != sy2
assert Dagger(sz1) != sz2
def test_pauli_operators_multiplication():
assert qsimplify_pauli(sx * sx) == 1
assert qsimplify_pauli(sy * sy) == 1
assert qsimplify_pauli(sz * sz) == 1
assert qsimplify_pauli(sx * sy) == I * sz
assert qsimplify_pauli(sy * sz) == I * sx
assert qsimplify_pauli(sz * sx) == I * sy
assert qsimplify_pauli(sy * sx) == - I * sz
assert qsimplify_pauli(sz * sy) == - I * sx
assert qsimplify_pauli(sx * sz) == - I * sy
def test_pauli_operators_multiplication_with_labels():
assert qsimplify_pauli(sx1 * sx1) == 1
assert qsimplify_pauli(sy1 * sy1) == 1
assert qsimplify_pauli(sz1 * sz1) == 1
assert isinstance(sx1 * sx2, Mul)
assert isinstance(sy1 * sy2, Mul)
assert isinstance(sz1 * sz2, Mul)
assert qsimplify_pauli(sx1 * sy1 * sx2 * sy2) == - sz1 * sz2
assert qsimplify_pauli(sy1 * sz1 * sz2 * sx2) == - sx1 * sy2
def test_pauli_states():
sx, sz = SigmaX(), SigmaZ()
up = SigmaZKet(0)
down = SigmaZKet(1)
assert qapply(sx * up) == down
assert qapply(sx * down) == up
assert qapply(sz * up) == up
assert qapply(sz * down) == - down
up = SigmaZBra(0)
down = SigmaZBra(1)
assert qapply(up * sx, dagger=True) == down
assert qapply(down * sx, dagger=True) == up
assert qapply(up * sz, dagger=True) == up
assert qapply(down * sz, dagger=True) == - down
assert Dagger(SigmaZKet(0)) == SigmaZBra(0)
assert Dagger(SigmaZBra(1)) == SigmaZKet(1)
raises(ValueError, lambda: SigmaZBra(2))
raises(ValueError, lambda: SigmaZKet(2))
def test_use_name():
assert sm.use_name is False
assert sm1.use_name is True
assert sx.use_name is False
assert sx1.use_name is True
def test_printing():
assert latex(sx) == r'{\sigma_x}'
assert latex(sx1) == r'{\sigma_x^{(1)}}'
assert latex(sy) == r'{\sigma_y}'
assert latex(sy1) == r'{\sigma_y^{(1)}}'
assert latex(sz) == r'{\sigma_z}'
assert latex(sz1) == r'{\sigma_z^{(1)}}'
assert latex(sm) == r'{\sigma_-}'
assert latex(sm1) == r'{\sigma_-^{(1)}}'
assert latex(sp) == r'{\sigma_+}'
assert latex(sp1) == r'{\sigma_+^{(1)}}'
def test_represent():
assert represent(sx) == Matrix([[0, 1], [1, 0]])
assert represent(sy) == Matrix([[0, -I], [I, 0]])
assert represent(sz) == Matrix([[1, 0], [0, -1]])
assert represent(sm) == Matrix([[0, 0], [1, 0]])
assert represent(sp) == Matrix([[0, 1], [0, 0]])
|
1efa6de36966b23a452aeb37d7a16c0de90e3d82197bd4b025302a961e171066 | from sympy.core.random import randint
from sympy.core.numbers import Integer
from sympy.matrices.dense import (Matrix, ones, zeros)
from sympy.physics.quantum.matrixutils import (
to_sympy, to_numpy, to_scipy_sparse, matrix_tensor_product,
matrix_to_zero, matrix_zeros, numpy_ndarray, scipy_sparse_matrix
)
from sympy.external import import_module
from sympy.testing.pytest import skip
m = Matrix([[1, 2], [3, 4]])
def test_sympy_to_sympy():
assert to_sympy(m) == m
def test_matrix_to_zero():
assert matrix_to_zero(m) == m
assert matrix_to_zero(Matrix([[0, 0], [0, 0]])) == Integer(0)
np = import_module('numpy')
def test_to_numpy():
if not np:
skip("numpy not installed.")
result = np.matrix([[1, 2], [3, 4]], dtype='complex')
assert (to_numpy(m) == result).all()
def test_matrix_tensor_product():
if not np:
skip("numpy not installed.")
l1 = zeros(4)
for i in range(16):
l1[i] = 2**i
l2 = zeros(4)
for i in range(16):
l2[i] = i
l3 = zeros(2)
for i in range(4):
l3[i] = i
vec = Matrix([1, 2, 3])
#test for Matrix known 4x4 matricies
numpyl1 = np.matrix(l1.tolist())
numpyl2 = np.matrix(l2.tolist())
numpy_product = np.kron(numpyl1, numpyl2)
args = [l1, l2]
sympy_product = matrix_tensor_product(*args)
assert numpy_product.tolist() == sympy_product.tolist()
numpy_product = np.kron(numpyl2, numpyl1)
args = [l2, l1]
sympy_product = matrix_tensor_product(*args)
assert numpy_product.tolist() == sympy_product.tolist()
#test for other known matrix of different dimensions
numpyl2 = np.matrix(l3.tolist())
numpy_product = np.kron(numpyl1, numpyl2)
args = [l1, l3]
sympy_product = matrix_tensor_product(*args)
assert numpy_product.tolist() == sympy_product.tolist()
numpy_product = np.kron(numpyl2, numpyl1)
args = [l3, l1]
sympy_product = matrix_tensor_product(*args)
assert numpy_product.tolist() == sympy_product.tolist()
#test for non square matrix
numpyl2 = np.matrix(vec.tolist())
numpy_product = np.kron(numpyl1, numpyl2)
args = [l1, vec]
sympy_product = matrix_tensor_product(*args)
assert numpy_product.tolist() == sympy_product.tolist()
numpy_product = np.kron(numpyl2, numpyl1)
args = [vec, l1]
sympy_product = matrix_tensor_product(*args)
assert numpy_product.tolist() == sympy_product.tolist()
#test for random matrix with random values that are floats
random_matrix1 = np.random.rand(randint(1, 5), randint(1, 5))
random_matrix2 = np.random.rand(randint(1, 5), randint(1, 5))
numpy_product = np.kron(random_matrix1, random_matrix2)
args = [Matrix(random_matrix1.tolist()), Matrix(random_matrix2.tolist())]
sympy_product = matrix_tensor_product(*args)
assert not (sympy_product - Matrix(numpy_product.tolist())).tolist() > \
(ones(sympy_product.rows, sympy_product.cols)*epsilon).tolist()
#test for three matrix kronecker
sympy_product = matrix_tensor_product(l1, vec, l2)
numpy_product = np.kron(l1, np.kron(vec, l2))
assert numpy_product.tolist() == sympy_product.tolist()
scipy = import_module('scipy', import_kwargs={'fromlist': ['sparse']})
def test_to_scipy_sparse():
if not np:
skip("numpy not installed.")
if not scipy:
skip("scipy not installed.")
else:
sparse = scipy.sparse
result = sparse.csr_matrix([[1, 2], [3, 4]], dtype='complex')
assert np.linalg.norm((to_scipy_sparse(m) - result).todense()) == 0.0
epsilon = .000001
def test_matrix_zeros_sympy():
sym = matrix_zeros(4, 4, format='sympy')
assert isinstance(sym, Matrix)
def test_matrix_zeros_numpy():
if not np:
skip("numpy not installed.")
num = matrix_zeros(4, 4, format='numpy')
assert isinstance(num, numpy_ndarray)
def test_matrix_zeros_scipy():
if not np:
skip("numpy not installed.")
if not scipy:
skip("scipy not installed.")
sci = matrix_zeros(4, 4, format='scipy.sparse')
assert isinstance(sci, scipy_sparse_matrix)
|
d49f8304c24504c704d3ef0269f3d0291308da7567b6935db332bdeb25fd9989 | # -*- encoding: utf-8 -*-
"""
TODO:
* Address Issue 2251, printing of spin states
"""
from typing import Dict as tDict, Any
from sympy.physics.quantum.anticommutator import AntiCommutator
from sympy.physics.quantum.cg import CG, Wigner3j, Wigner6j, Wigner9j
from sympy.physics.quantum.commutator import Commutator
from sympy.physics.quantum.constants import hbar
from sympy.physics.quantum.dagger import Dagger
from sympy.physics.quantum.gate import CGate, CNotGate, IdentityGate, UGate, XGate
from sympy.physics.quantum.hilbert import ComplexSpace, FockSpace, HilbertSpace, L2
from sympy.physics.quantum.innerproduct import InnerProduct
from sympy.physics.quantum.operator import Operator, OuterProduct, DifferentialOperator
from sympy.physics.quantum.qexpr import QExpr
from sympy.physics.quantum.qubit import Qubit, IntQubit
from sympy.physics.quantum.spin import Jz, J2, JzBra, JzBraCoupled, JzKet, JzKetCoupled, Rotation, WignerD
from sympy.physics.quantum.state import Bra, Ket, TimeDepBra, TimeDepKet
from sympy.physics.quantum.tensorproduct import TensorProduct
from sympy.physics.quantum.sho1d import RaisingOp
from sympy.core.function import (Derivative, Function)
from sympy.core.numbers import oo
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.matrices.dense import Matrix
from sympy.sets.sets import Interval
from sympy.testing.pytest import XFAIL
# Imports used in srepr strings
from sympy.physics.quantum.spin import JzOp
from sympy.printing import srepr
from sympy.printing.pretty import pretty as xpretty
from sympy.printing.latex import latex
MutableDenseMatrix = Matrix
ENV = {} # type: tDict[str, Any]
exec('from sympy import *', ENV)
exec('from sympy.physics.quantum import *', ENV)
exec('from sympy.physics.quantum.cg import *', ENV)
exec('from sympy.physics.quantum.spin import *', ENV)
exec('from sympy.physics.quantum.hilbert import *', ENV)
exec('from sympy.physics.quantum.qubit import *', ENV)
exec('from sympy.physics.quantum.qexpr import *', ENV)
exec('from sympy.physics.quantum.gate import *', ENV)
exec('from sympy.physics.quantum.constants import *', ENV)
def sT(expr, string):
"""
sT := sreprTest
from sympy/printing/tests/test_repr.py
"""
assert srepr(expr) == string
assert eval(string, ENV) == expr
def pretty(expr):
"""ASCII pretty-printing"""
return xpretty(expr, use_unicode=False, wrap_line=False)
def upretty(expr):
"""Unicode pretty-printing"""
return xpretty(expr, use_unicode=True, wrap_line=False)
def test_anticommutator():
A = Operator('A')
B = Operator('B')
ac = AntiCommutator(A, B)
ac_tall = AntiCommutator(A**2, B)
assert str(ac) == '{A,B}'
assert pretty(ac) == '{A,B}'
assert upretty(ac) == '{A,B}'
assert latex(ac) == r'\left\{A,B\right\}'
sT(ac, "AntiCommutator(Operator(Symbol('A')),Operator(Symbol('B')))")
assert str(ac_tall) == '{A**2,B}'
ascii_str = \
"""\
/ 2 \\\n\
<A ,B>\n\
\\ /\
"""
ucode_str = \
"""\
⎧ 2 ⎫\n\
⎨A ,B⎬\n\
⎩ ⎭\
"""
assert pretty(ac_tall) == ascii_str
assert upretty(ac_tall) == ucode_str
assert latex(ac_tall) == r'\left\{A^{2},B\right\}'
sT(ac_tall, "AntiCommutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
def test_cg():
cg = CG(1, 2, 3, 4, 5, 6)
wigner3j = Wigner3j(1, 2, 3, 4, 5, 6)
wigner6j = Wigner6j(1, 2, 3, 4, 5, 6)
wigner9j = Wigner9j(1, 2, 3, 4, 5, 6, 7, 8, 9)
assert str(cg) == 'CG(1, 2, 3, 4, 5, 6)'
ascii_str = \
"""\
5,6 \n\
C \n\
1,2,3,4\
"""
ucode_str = \
"""\
5,6 \n\
C \n\
1,2,3,4\
"""
assert pretty(cg) == ascii_str
assert upretty(cg) == ucode_str
assert latex(cg) == 'C^{5,6}_{1,2,3,4}'
assert latex(cg ** 2) == R'\left(C^{5,6}_{1,2,3,4}\right)^{2}'
sT(cg, "CG(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
assert str(wigner3j) == 'Wigner3j(1, 2, 3, 4, 5, 6)'
ascii_str = \
"""\
/1 3 5\\\n\
| |\n\
\\2 4 6/\
"""
ucode_str = \
"""\
⎛1 3 5⎞\n\
⎜ ⎟\n\
⎝2 4 6⎠\
"""
assert pretty(wigner3j) == ascii_str
assert upretty(wigner3j) == ucode_str
assert latex(wigner3j) == \
r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right)'
sT(wigner3j, "Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
assert str(wigner6j) == 'Wigner6j(1, 2, 3, 4, 5, 6)'
ascii_str = \
"""\
/1 2 3\\\n\
< >\n\
\\4 5 6/\
"""
ucode_str = \
"""\
⎧1 2 3⎫\n\
⎨ ⎬\n\
⎩4 5 6⎭\
"""
assert pretty(wigner6j) == ascii_str
assert upretty(wigner6j) == ucode_str
assert latex(wigner6j) == \
r'\left\{\begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \end{array}\right\}'
sT(wigner6j, "Wigner6j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
assert str(wigner9j) == 'Wigner9j(1, 2, 3, 4, 5, 6, 7, 8, 9)'
ascii_str = \
"""\
/1 2 3\\\n\
| |\n\
<4 5 6>\n\
| |\n\
\\7 8 9/\
"""
ucode_str = \
"""\
⎧1 2 3⎫\n\
⎪ ⎪\n\
⎨4 5 6⎬\n\
⎪ ⎪\n\
⎩7 8 9⎭\
"""
assert pretty(wigner9j) == ascii_str
assert upretty(wigner9j) == ucode_str
assert latex(wigner9j) == \
r'\left\{\begin{array}{ccc} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{array}\right\}'
sT(wigner9j, "Wigner9j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6), Integer(7), Integer(8), Integer(9))")
def test_commutator():
A = Operator('A')
B = Operator('B')
c = Commutator(A, B)
c_tall = Commutator(A**2, B)
assert str(c) == '[A,B]'
assert pretty(c) == '[A,B]'
assert upretty(c) == '[A,B]'
assert latex(c) == r'\left[A,B\right]'
sT(c, "Commutator(Operator(Symbol('A')),Operator(Symbol('B')))")
assert str(c_tall) == '[A**2,B]'
ascii_str = \
"""\
[ 2 ]\n\
[A ,B]\
"""
ucode_str = \
"""\
⎡ 2 ⎤\n\
⎣A ,B⎦\
"""
assert pretty(c_tall) == ascii_str
assert upretty(c_tall) == ucode_str
assert latex(c_tall) == r'\left[A^{2},B\right]'
sT(c_tall, "Commutator(Pow(Operator(Symbol('A')), Integer(2)),Operator(Symbol('B')))")
def test_constants():
assert str(hbar) == 'hbar'
assert pretty(hbar) == 'hbar'
assert upretty(hbar) == 'ℏ'
assert latex(hbar) == r'\hbar'
sT(hbar, "HBar()")
def test_dagger():
x = symbols('x')
expr = Dagger(x)
assert str(expr) == 'Dagger(x)'
ascii_str = \
"""\
+\n\
x \
"""
ucode_str = \
"""\
†\n\
x \
"""
assert pretty(expr) == ascii_str
assert upretty(expr) == ucode_str
assert latex(expr) == r'x^{\dagger}'
sT(expr, "Dagger(Symbol('x'))")
@XFAIL
def test_gate_failing():
a, b, c, d = symbols('a,b,c,d')
uMat = Matrix([[a, b], [c, d]])
g = UGate((0,), uMat)
assert str(g) == 'U(0)'
def test_gate():
a, b, c, d = symbols('a,b,c,d')
uMat = Matrix([[a, b], [c, d]])
q = Qubit(1, 0, 1, 0, 1)
g1 = IdentityGate(2)
g2 = CGate((3, 0), XGate(1))
g3 = CNotGate(1, 0)
g4 = UGate((0,), uMat)
assert str(g1) == '1(2)'
assert pretty(g1) == '1 \n 2'
assert upretty(g1) == '1 \n 2'
assert latex(g1) == r'1_{2}'
sT(g1, "IdentityGate(Integer(2))")
assert str(g1*q) == '1(2)*|10101>'
ascii_str = \
"""\
1 *|10101>\n\
2 \
"""
ucode_str = \
"""\
1 ⋅❘10101⟩\n\
2 \
"""
assert pretty(g1*q) == ascii_str
assert upretty(g1*q) == ucode_str
assert latex(g1*q) == r'1_{2} {\left|10101\right\rangle }'
sT(g1*q, "Mul(IdentityGate(Integer(2)), Qubit(Integer(1),Integer(0),Integer(1),Integer(0),Integer(1)))")
assert str(g2) == 'C((3,0),X(1))'
ascii_str = \
"""\
C /X \\\n\
3,0\\ 1/\
"""
ucode_str = \
"""\
C ⎛X ⎞\n\
3,0⎝ 1⎠\
"""
assert pretty(g2) == ascii_str
assert upretty(g2) == ucode_str
assert latex(g2) == r'C_{3,0}{\left(X_{1}\right)}'
sT(g2, "CGate(Tuple(Integer(3), Integer(0)),XGate(Integer(1)))")
assert str(g3) == 'CNOT(1,0)'
ascii_str = \
"""\
CNOT \n\
1,0\
"""
ucode_str = \
"""\
CNOT \n\
1,0\
"""
assert pretty(g3) == ascii_str
assert upretty(g3) == ucode_str
assert latex(g3) == r'\text{CNOT}_{1,0}'
sT(g3, "CNotGate(Integer(1),Integer(0))")
ascii_str = \
"""\
U \n\
0\
"""
ucode_str = \
"""\
U \n\
0\
"""
assert str(g4) == \
"""\
U((0,),Matrix([\n\
[a, b],\n\
[c, d]]))\
"""
assert pretty(g4) == ascii_str
assert upretty(g4) == ucode_str
assert latex(g4) == r'U_{0}'
sT(g4, "UGate(Tuple(Integer(0)),ImmutableDenseMatrix([[Symbol('a'), Symbol('b')], [Symbol('c'), Symbol('d')]]))")
def test_hilbert():
h1 = HilbertSpace()
h2 = ComplexSpace(2)
h3 = FockSpace()
h4 = L2(Interval(0, oo))
assert str(h1) == 'H'
assert pretty(h1) == 'H'
assert upretty(h1) == 'H'
assert latex(h1) == r'\mathcal{H}'
sT(h1, "HilbertSpace()")
assert str(h2) == 'C(2)'
ascii_str = \
"""\
2\n\
C \
"""
ucode_str = \
"""\
2\n\
C \
"""
assert pretty(h2) == ascii_str
assert upretty(h2) == ucode_str
assert latex(h2) == r'\mathcal{C}^{2}'
sT(h2, "ComplexSpace(Integer(2))")
assert str(h3) == 'F'
assert pretty(h3) == 'F'
assert upretty(h3) == 'F'
assert latex(h3) == r'\mathcal{F}'
sT(h3, "FockSpace()")
assert str(h4) == 'L2(Interval(0, oo))'
ascii_str = \
"""\
2\n\
L \
"""
ucode_str = \
"""\
2\n\
L \
"""
assert pretty(h4) == ascii_str
assert upretty(h4) == ucode_str
assert latex(h4) == r'{\mathcal{L}^2}\left( \left[0, \infty\right) \right)'
sT(h4, "L2(Interval(Integer(0), oo, false, true))")
assert str(h1 + h2) == 'H+C(2)'
ascii_str = \
"""\
2\n\
H + C \
"""
ucode_str = \
"""\
2\n\
H ⊕ C \
"""
assert pretty(h1 + h2) == ascii_str
assert upretty(h1 + h2) == ucode_str
assert latex(h1 + h2)
sT(h1 + h2, "DirectSumHilbertSpace(HilbertSpace(),ComplexSpace(Integer(2)))")
assert str(h1*h2) == "H*C(2)"
ascii_str = \
"""\
2\n\
H x C \
"""
ucode_str = \
"""\
2\n\
H ⨂ C \
"""
assert pretty(h1*h2) == ascii_str
assert upretty(h1*h2) == ucode_str
assert latex(h1*h2)
sT(h1*h2,
"TensorProductHilbertSpace(HilbertSpace(),ComplexSpace(Integer(2)))")
assert str(h1**2) == 'H**2'
ascii_str = \
"""\
x2\n\
H \
"""
ucode_str = \
"""\
⨂2\n\
H \
"""
assert pretty(h1**2) == ascii_str
assert upretty(h1**2) == ucode_str
assert latex(h1**2) == r'{\mathcal{H}}^{\otimes 2}'
sT(h1**2, "TensorPowerHilbertSpace(HilbertSpace(),Integer(2))")
def test_innerproduct():
x = symbols('x')
ip1 = InnerProduct(Bra(), Ket())
ip2 = InnerProduct(TimeDepBra(), TimeDepKet())
ip3 = InnerProduct(JzBra(1, 1), JzKet(1, 1))
ip4 = InnerProduct(JzBraCoupled(1, 1, (1, 1)), JzKetCoupled(1, 1, (1, 1)))
ip_tall1 = InnerProduct(Bra(x/2), Ket(x/2))
ip_tall2 = InnerProduct(Bra(x), Ket(x/2))
ip_tall3 = InnerProduct(Bra(x/2), Ket(x))
assert str(ip1) == '<psi|psi>'
assert pretty(ip1) == '<psi|psi>'
assert upretty(ip1) == '⟨ψ❘ψ⟩'
assert latex(
ip1) == r'\left\langle \psi \right. {\left|\psi\right\rangle }'
sT(ip1, "InnerProduct(Bra(Symbol('psi')),Ket(Symbol('psi')))")
assert str(ip2) == '<psi;t|psi;t>'
assert pretty(ip2) == '<psi;t|psi;t>'
assert upretty(ip2) == '⟨ψ;t❘ψ;t⟩'
assert latex(ip2) == \
r'\left\langle \psi;t \right. {\left|\psi;t\right\rangle }'
sT(ip2, "InnerProduct(TimeDepBra(Symbol('psi'),Symbol('t')),TimeDepKet(Symbol('psi'),Symbol('t')))")
assert str(ip3) == "<1,1|1,1>"
assert pretty(ip3) == '<1,1|1,1>'
assert upretty(ip3) == '⟨1,1❘1,1⟩'
assert latex(ip3) == r'\left\langle 1,1 \right. {\left|1,1\right\rangle }'
sT(ip3, "InnerProduct(JzBra(Integer(1),Integer(1)),JzKet(Integer(1),Integer(1)))")
assert str(ip4) == "<1,1,j1=1,j2=1|1,1,j1=1,j2=1>"
assert pretty(ip4) == '<1,1,j1=1,j2=1|1,1,j1=1,j2=1>'
assert upretty(ip4) == '⟨1,1,j₁=1,j₂=1❘1,1,j₁=1,j₂=1⟩'
assert latex(ip4) == \
r'\left\langle 1,1,j_{1}=1,j_{2}=1 \right. {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }'
sT(ip4, "InnerProduct(JzBraCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))),JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))))")
assert str(ip_tall1) == '<x/2|x/2>'
ascii_str = \
"""\
/ | \\ \n\
/ x|x \\\n\
\\ -|- /\n\
\\2|2/ \
"""
ucode_str = \
"""\
╱ │ ╲ \n\
╱ x│x ╲\n\
╲ ─│─ ╱\n\
╲2│2╱ \
"""
assert pretty(ip_tall1) == ascii_str
assert upretty(ip_tall1) == ucode_str
assert latex(ip_tall1) == \
r'\left\langle \frac{x}{2} \right. {\left|\frac{x}{2}\right\rangle }'
sT(ip_tall1, "InnerProduct(Bra(Mul(Rational(1, 2), Symbol('x'))),Ket(Mul(Rational(1, 2), Symbol('x'))))")
assert str(ip_tall2) == '<x|x/2>'
ascii_str = \
"""\
/ | \\ \n\
/ |x \\\n\
\\ x|- /\n\
\\ |2/ \
"""
ucode_str = \
"""\
╱ │ ╲ \n\
╱ │x ╲\n\
╲ x│─ ╱\n\
╲ │2╱ \
"""
assert pretty(ip_tall2) == ascii_str
assert upretty(ip_tall2) == ucode_str
assert latex(ip_tall2) == \
r'\left\langle x \right. {\left|\frac{x}{2}\right\rangle }'
sT(ip_tall2,
"InnerProduct(Bra(Symbol('x')),Ket(Mul(Rational(1, 2), Symbol('x'))))")
assert str(ip_tall3) == '<x/2|x>'
ascii_str = \
"""\
/ | \\ \n\
/ x| \\\n\
\\ -|x /\n\
\\2| / \
"""
ucode_str = \
"""\
╱ │ ╲ \n\
╱ x│ ╲\n\
╲ ─│x ╱\n\
╲2│ ╱ \
"""
assert pretty(ip_tall3) == ascii_str
assert upretty(ip_tall3) == ucode_str
assert latex(ip_tall3) == \
r'\left\langle \frac{x}{2} \right. {\left|x\right\rangle }'
sT(ip_tall3,
"InnerProduct(Bra(Mul(Rational(1, 2), Symbol('x'))),Ket(Symbol('x')))")
def test_operator():
a = Operator('A')
b = Operator('B', Symbol('t'), S.Half)
inv = a.inv()
f = Function('f')
x = symbols('x')
d = DifferentialOperator(Derivative(f(x), x), f(x))
op = OuterProduct(Ket(), Bra())
assert str(a) == 'A'
assert pretty(a) == 'A'
assert upretty(a) == 'A'
assert latex(a) == 'A'
sT(a, "Operator(Symbol('A'))")
assert str(inv) == 'A**(-1)'
ascii_str = \
"""\
-1\n\
A \
"""
ucode_str = \
"""\
-1\n\
A \
"""
assert pretty(inv) == ascii_str
assert upretty(inv) == ucode_str
assert latex(inv) == r'A^{-1}'
sT(inv, "Pow(Operator(Symbol('A')), Integer(-1))")
assert str(d) == 'DifferentialOperator(Derivative(f(x), x),f(x))'
ascii_str = \
"""\
/d \\\n\
DifferentialOperator|--(f(x)),f(x)|\n\
\\dx /\
"""
ucode_str = \
"""\
⎛d ⎞\n\
DifferentialOperator⎜──(f(x)),f(x)⎟\n\
⎝dx ⎠\
"""
assert pretty(d) == ascii_str
assert upretty(d) == ucode_str
assert latex(d) == \
r'DifferentialOperator\left(\frac{d}{d x} f{\left(x \right)},f{\left(x \right)}\right)'
sT(d, "DifferentialOperator(Derivative(Function('f')(Symbol('x')), Tuple(Symbol('x'), Integer(1))),Function('f')(Symbol('x')))")
assert str(b) == 'Operator(B,t,1/2)'
assert pretty(b) == 'Operator(B,t,1/2)'
assert upretty(b) == 'Operator(B,t,1/2)'
assert latex(b) == r'Operator\left(B,t,\frac{1}{2}\right)'
sT(b, "Operator(Symbol('B'),Symbol('t'),Rational(1, 2))")
assert str(op) == '|psi><psi|'
assert pretty(op) == '|psi><psi|'
assert upretty(op) == '❘ψ⟩⟨ψ❘'
assert latex(op) == r'{\left|\psi\right\rangle }{\left\langle \psi\right|}'
sT(op, "OuterProduct(Ket(Symbol('psi')),Bra(Symbol('psi')))")
def test_qexpr():
q = QExpr('q')
assert str(q) == 'q'
assert pretty(q) == 'q'
assert upretty(q) == 'q'
assert latex(q) == r'q'
sT(q, "QExpr(Symbol('q'))")
def test_qubit():
q1 = Qubit('0101')
q2 = IntQubit(8)
assert str(q1) == '|0101>'
assert pretty(q1) == '|0101>'
assert upretty(q1) == '❘0101⟩'
assert latex(q1) == r'{\left|0101\right\rangle }'
sT(q1, "Qubit(Integer(0),Integer(1),Integer(0),Integer(1))")
assert str(q2) == '|8>'
assert pretty(q2) == '|8>'
assert upretty(q2) == '❘8⟩'
assert latex(q2) == r'{\left|8\right\rangle }'
sT(q2, "IntQubit(8)")
def test_spin():
lz = JzOp('L')
ket = JzKet(1, 0)
bra = JzBra(1, 0)
cket = JzKetCoupled(1, 0, (1, 2))
cbra = JzBraCoupled(1, 0, (1, 2))
cket_big = JzKetCoupled(1, 0, (1, 2, 3))
cbra_big = JzBraCoupled(1, 0, (1, 2, 3))
rot = Rotation(1, 2, 3)
bigd = WignerD(1, 2, 3, 4, 5, 6)
smalld = WignerD(1, 2, 3, 0, 4, 0)
assert str(lz) == 'Lz'
ascii_str = \
"""\
L \n\
z\
"""
ucode_str = \
"""\
L \n\
z\
"""
assert pretty(lz) == ascii_str
assert upretty(lz) == ucode_str
assert latex(lz) == 'L_z'
sT(lz, "JzOp(Symbol('L'))")
assert str(J2) == 'J2'
ascii_str = \
"""\
2\n\
J \
"""
ucode_str = \
"""\
2\n\
J \
"""
assert pretty(J2) == ascii_str
assert upretty(J2) == ucode_str
assert latex(J2) == r'J^2'
sT(J2, "J2Op(Symbol('J'))")
assert str(Jz) == 'Jz'
ascii_str = \
"""\
J \n\
z\
"""
ucode_str = \
"""\
J \n\
z\
"""
assert pretty(Jz) == ascii_str
assert upretty(Jz) == ucode_str
assert latex(Jz) == 'J_z'
sT(Jz, "JzOp(Symbol('J'))")
assert str(ket) == '|1,0>'
assert pretty(ket) == '|1,0>'
assert upretty(ket) == '❘1,0⟩'
assert latex(ket) == r'{\left|1,0\right\rangle }'
sT(ket, "JzKet(Integer(1),Integer(0))")
assert str(bra) == '<1,0|'
assert pretty(bra) == '<1,0|'
assert upretty(bra) == '⟨1,0❘'
assert latex(bra) == r'{\left\langle 1,0\right|}'
sT(bra, "JzBra(Integer(1),Integer(0))")
assert str(cket) == '|1,0,j1=1,j2=2>'
assert pretty(cket) == '|1,0,j1=1,j2=2>'
assert upretty(cket) == '❘1,0,j₁=1,j₂=2⟩'
assert latex(cket) == r'{\left|1,0,j_{1}=1,j_{2}=2\right\rangle }'
sT(cket, "JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))")
assert str(cbra) == '<1,0,j1=1,j2=2|'
assert pretty(cbra) == '<1,0,j1=1,j2=2|'
assert upretty(cbra) == '⟨1,0,j₁=1,j₂=2❘'
assert latex(cbra) == r'{\left\langle 1,0,j_{1}=1,j_{2}=2\right|}'
sT(cbra, "JzBraCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))")
assert str(cket_big) == '|1,0,j1=1,j2=2,j3=3,j(1,2)=3>'
# TODO: Fix non-unicode pretty printing
# i.e. j1,2 -> j(1,2)
assert pretty(cket_big) == '|1,0,j1=1,j2=2,j3=3,j1,2=3>'
assert upretty(cket_big) == '❘1,0,j₁=1,j₂=2,j₃=3,j₁,₂=3⟩'
assert latex(cket_big) == \
r'{\left|1,0,j_{1}=1,j_{2}=2,j_{3}=3,j_{1,2}=3\right\rangle }'
sT(cket_big, "JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2), Integer(3)),Tuple(Tuple(Integer(1), Integer(2), Integer(3)), Tuple(Integer(1), Integer(3), Integer(1))))")
assert str(cbra_big) == '<1,0,j1=1,j2=2,j3=3,j(1,2)=3|'
assert pretty(cbra_big) == '<1,0,j1=1,j2=2,j3=3,j1,2=3|'
assert upretty(cbra_big) == '⟨1,0,j₁=1,j₂=2,j₃=3,j₁,₂=3❘'
assert latex(cbra_big) == \
r'{\left\langle 1,0,j_{1}=1,j_{2}=2,j_{3}=3,j_{1,2}=3\right|}'
sT(cbra_big, "JzBraCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(2), Integer(3)),Tuple(Tuple(Integer(1), Integer(2), Integer(3)), Tuple(Integer(1), Integer(3), Integer(1))))")
assert str(rot) == 'R(1,2,3)'
assert pretty(rot) == 'R (1,2,3)'
assert upretty(rot) == 'ℛ (1,2,3)'
assert latex(rot) == r'\mathcal{R}\left(1,2,3\right)'
sT(rot, "Rotation(Integer(1),Integer(2),Integer(3))")
assert str(bigd) == 'WignerD(1, 2, 3, 4, 5, 6)'
ascii_str = \
"""\
1 \n\
D (4,5,6)\n\
2,3 \
"""
ucode_str = \
"""\
1 \n\
D (4,5,6)\n\
2,3 \
"""
assert pretty(bigd) == ascii_str
assert upretty(bigd) == ucode_str
assert latex(bigd) == r'D^{1}_{2,3}\left(4,5,6\right)'
sT(bigd, "WignerD(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6))")
assert str(smalld) == 'WignerD(1, 2, 3, 0, 4, 0)'
ascii_str = \
"""\
1 \n\
d (4)\n\
2,3 \
"""
ucode_str = \
"""\
1 \n\
d (4)\n\
2,3 \
"""
assert pretty(smalld) == ascii_str
assert upretty(smalld) == ucode_str
assert latex(smalld) == r'd^{1}_{2,3}\left(4\right)'
sT(smalld, "WignerD(Integer(1), Integer(2), Integer(3), Integer(0), Integer(4), Integer(0))")
def test_state():
x = symbols('x')
bra = Bra()
ket = Ket()
bra_tall = Bra(x/2)
ket_tall = Ket(x/2)
tbra = TimeDepBra()
tket = TimeDepKet()
assert str(bra) == '<psi|'
assert pretty(bra) == '<psi|'
assert upretty(bra) == '⟨ψ❘'
assert latex(bra) == r'{\left\langle \psi\right|}'
sT(bra, "Bra(Symbol('psi'))")
assert str(ket) == '|psi>'
assert pretty(ket) == '|psi>'
assert upretty(ket) == '❘ψ⟩'
assert latex(ket) == r'{\left|\psi\right\rangle }'
sT(ket, "Ket(Symbol('psi'))")
assert str(bra_tall) == '<x/2|'
ascii_str = \
"""\
/ |\n\
/ x|\n\
\\ -|\n\
\\2|\
"""
ucode_str = \
"""\
╱ │\n\
╱ x│\n\
╲ ─│\n\
╲2│\
"""
assert pretty(bra_tall) == ascii_str
assert upretty(bra_tall) == ucode_str
assert latex(bra_tall) == r'{\left\langle \frac{x}{2}\right|}'
sT(bra_tall, "Bra(Mul(Rational(1, 2), Symbol('x')))")
assert str(ket_tall) == '|x/2>'
ascii_str = \
"""\
| \\ \n\
|x \\\n\
|- /\n\
|2/ \
"""
ucode_str = \
"""\
│ ╲ \n\
│x ╲\n\
│─ ╱\n\
│2╱ \
"""
assert pretty(ket_tall) == ascii_str
assert upretty(ket_tall) == ucode_str
assert latex(ket_tall) == r'{\left|\frac{x}{2}\right\rangle }'
sT(ket_tall, "Ket(Mul(Rational(1, 2), Symbol('x')))")
assert str(tbra) == '<psi;t|'
assert pretty(tbra) == '<psi;t|'
assert upretty(tbra) == '⟨ψ;t❘'
assert latex(tbra) == r'{\left\langle \psi;t\right|}'
sT(tbra, "TimeDepBra(Symbol('psi'),Symbol('t'))")
assert str(tket) == '|psi;t>'
assert pretty(tket) == '|psi;t>'
assert upretty(tket) == '❘ψ;t⟩'
assert latex(tket) == r'{\left|\psi;t\right\rangle }'
sT(tket, "TimeDepKet(Symbol('psi'),Symbol('t'))")
def test_tensorproduct():
tp = TensorProduct(JzKet(1, 1), JzKet(1, 0))
assert str(tp) == '|1,1>x|1,0>'
assert pretty(tp) == '|1,1>x |1,0>'
assert upretty(tp) == '❘1,1⟩⨂ ❘1,0⟩'
assert latex(tp) == \
r'{{\left|1,1\right\rangle }}\otimes {{\left|1,0\right\rangle }}'
sT(tp, "TensorProduct(JzKet(Integer(1),Integer(1)), JzKet(Integer(1),Integer(0)))")
def test_big_expr():
f = Function('f')
x = symbols('x')
e1 = Dagger(AntiCommutator(Operator('A') + Operator('B'), Pow(DifferentialOperator(Derivative(f(x), x), f(x)), 3))*TensorProduct(Jz**2, Operator('A') + Operator('B')))*(JzBra(1, 0) + JzBra(1, 1))*(JzKet(0, 0) + JzKet(1, -1))
e2 = Commutator(Jz**2, Operator('A') + Operator('B'))*AntiCommutator(Dagger(Operator('C')*Operator('D')), Operator('E').inv()**2)*Dagger(Commutator(Jz, J2))
e3 = Wigner3j(1, 2, 3, 4, 5, 6)*TensorProduct(Commutator(Operator('A') + Dagger(Operator('B')), Operator('C') + Operator('D')), Jz - J2)*Dagger(OuterProduct(Dagger(JzBra(1, 1)), JzBra(1, 0)))*TensorProduct(JzKetCoupled(1, 1, (1, 1)) + JzKetCoupled(1, 0, (1, 1)), JzKetCoupled(1, -1, (1, 1)))
e4 = (ComplexSpace(1)*ComplexSpace(2) + FockSpace()**2)*(L2(Interval(
0, oo)) + HilbertSpace())
assert str(e1) == '(Jz**2)x(Dagger(A) + Dagger(B))*{Dagger(DifferentialOperator(Derivative(f(x), x),f(x)))**3,Dagger(A) + Dagger(B)}*(<1,0| + <1,1|)*(|0,0> + |1,-1>)'
ascii_str = \
"""\
/ 3 \\ \n\
|/ +\\ | \n\
2 / + +\\ <| /d \\ | + +> \n\
/J \\ x \\A + B /*||DifferentialOperator|--(f(x)),f(x)| | ,A + B |*(<1,0| + <1,1|)*(|0,0> + |1,-1>)\n\
\\ z/ \\\\ \\dx / / / \
"""
ucode_str = \
"""\
⎧ 3 ⎫ \n\
⎪⎛ †⎞ ⎪ \n\
2 ⎛ † †⎞ ⎨⎜ ⎛d ⎞ ⎟ † †⎬ \n\
⎛J ⎞ ⨂ ⎝A + B ⎠⋅⎪⎜DifferentialOperator⎜──(f(x)),f(x)⎟ ⎟ ,A + B ⎪⋅(⟨1,0❘ + ⟨1,1❘)⋅(❘0,0⟩ + ❘1,-1⟩)\n\
⎝ z⎠ ⎩⎝ ⎝dx ⎠ ⎠ ⎭ \
"""
assert pretty(e1) == ascii_str
assert upretty(e1) == ucode_str
assert latex(e1) == \
r'{J_z^{2}}\otimes \left({A^{\dagger} + B^{\dagger}}\right) \left\{\left(DifferentialOperator\left(\frac{d}{d x} f{\left(x \right)},f{\left(x \right)}\right)^{\dagger}\right)^{3},A^{\dagger} + B^{\dagger}\right\} \left({\left\langle 1,0\right|} + {\left\langle 1,1\right|}\right) \left({\left|0,0\right\rangle } + {\left|1,-1\right\rangle }\right)'
sT(e1, "Mul(TensorProduct(Pow(JzOp(Symbol('J')), Integer(2)), Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), AntiCommutator(Pow(Dagger(DifferentialOperator(Derivative(Function('f')(Symbol('x')), Tuple(Symbol('x'), Integer(1))),Function('f')(Symbol('x')))), Integer(3)),Add(Dagger(Operator(Symbol('A'))), Dagger(Operator(Symbol('B'))))), Add(JzBra(Integer(1),Integer(0)), JzBra(Integer(1),Integer(1))), Add(JzKet(Integer(0),Integer(0)), JzKet(Integer(1),Integer(-1))))")
assert str(e2) == '[Jz**2,A + B]*{E**(-2),Dagger(D)*Dagger(C)}*[J2,Jz]'
ascii_str = \
"""\
[ 2 ] / -2 + +\\ [ 2 ]\n\
[/J \\ ,A + B]*<E ,D *C >*[J ,J ]\n\
[\\ z/ ] \\ / [ z]\
"""
ucode_str = \
"""\
⎡ 2 ⎤ ⎧ -2 † †⎫ ⎡ 2 ⎤\n\
⎢⎛J ⎞ ,A + B⎥⋅⎨E ,D ⋅C ⎬⋅⎢J ,J ⎥\n\
⎣⎝ z⎠ ⎦ ⎩ ⎭ ⎣ z⎦\
"""
assert pretty(e2) == ascii_str
assert upretty(e2) == ucode_str
assert latex(e2) == \
r'\left[J_z^{2},A + B\right] \left\{E^{-2},D^{\dagger} C^{\dagger}\right\} \left[J^2,J_z\right]'
sT(e2, "Mul(Commutator(Pow(JzOp(Symbol('J')), Integer(2)),Add(Operator(Symbol('A')), Operator(Symbol('B')))), AntiCommutator(Pow(Operator(Symbol('E')), Integer(-2)),Mul(Dagger(Operator(Symbol('D'))), Dagger(Operator(Symbol('C'))))), Commutator(J2Op(Symbol('J')),JzOp(Symbol('J'))))")
assert str(e3) == \
"Wigner3j(1, 2, 3, 4, 5, 6)*[Dagger(B) + A,C + D]x(-J2 + Jz)*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x|1,-1,j1=1,j2=1>"
ascii_str = \
"""\
[ + ] / 2 \\ \n\
/1 3 5\\*[B + A,C + D]x |- J + J |*|1,0><1,1|*(|1,0,j1=1,j2=1> + |1,1,j1=1,j2=1>)x |1,-1,j1=1,j2=1>\n\
| | \\ z/ \n\
\\2 4 6/ \
"""
ucode_str = \
"""\
⎡ † ⎤ ⎛ 2 ⎞ \n\
⎛1 3 5⎞⋅⎣B + A,C + D⎦⨂ ⎜- J + J ⎟⋅❘1,0⟩⟨1,1❘⋅(❘1,0,j₁=1,j₂=1⟩ + ❘1,1,j₁=1,j₂=1⟩)⨂ ❘1,-1,j₁=1,j₂=1⟩\n\
⎜ ⎟ ⎝ z⎠ \n\
⎝2 4 6⎠ \
"""
assert pretty(e3) == ascii_str
assert upretty(e3) == ucode_str
assert latex(e3) == \
r'\left(\begin{array}{ccc} 1 & 3 & 5 \\ 2 & 4 & 6 \end{array}\right) {\left[B^{\dagger} + A,C + D\right]}\otimes \left({- J^2 + J_z}\right) {\left|1,0\right\rangle }{\left\langle 1,1\right|} \left({{\left|1,0,j_{1}=1,j_{2}=1\right\rangle } + {\left|1,1,j_{1}=1,j_{2}=1\right\rangle }}\right)\otimes {{\left|1,-1,j_{1}=1,j_{2}=1\right\rangle }}'
sT(e3, "Mul(Wigner3j(Integer(1), Integer(2), Integer(3), Integer(4), Integer(5), Integer(6)), TensorProduct(Commutator(Add(Dagger(Operator(Symbol('B'))), Operator(Symbol('A'))),Add(Operator(Symbol('C')), Operator(Symbol('D')))), Add(Mul(Integer(-1), J2Op(Symbol('J'))), JzOp(Symbol('J')))), OuterProduct(JzKet(Integer(1),Integer(0)),JzBra(Integer(1),Integer(1))), TensorProduct(Add(JzKetCoupled(Integer(1),Integer(0),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1)))), JzKetCoupled(Integer(1),Integer(1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))), JzKetCoupled(Integer(1),Integer(-1),Tuple(Integer(1), Integer(1)),Tuple(Tuple(Integer(1), Integer(2), Integer(1))))))")
assert str(e4) == '(C(1)*C(2)+F**2)*(L2(Interval(0, oo))+H)'
ascii_str = \
"""\
// 1 2\\ x2\\ / 2 \\\n\
\\\\C x C / + F / x \\L + H/\
"""
ucode_str = \
"""\
⎛⎛ 1 2⎞ ⨂2⎞ ⎛ 2 ⎞\n\
⎝⎝C ⨂ C ⎠ ⊕ F ⎠ ⨂ ⎝L ⊕ H⎠\
"""
assert pretty(e4) == ascii_str
assert upretty(e4) == ucode_str
assert latex(e4) == \
r'\left(\left(\mathcal{C}^{1}\otimes \mathcal{C}^{2}\right)\oplus {\mathcal{F}}^{\otimes 2}\right)\otimes \left({\mathcal{L}^2}\left( \left[0, \infty\right) \right)\oplus \mathcal{H}\right)'
sT(e4, "TensorProductHilbertSpace((DirectSumHilbertSpace(TensorProductHilbertSpace(ComplexSpace(Integer(1)),ComplexSpace(Integer(2))),TensorPowerHilbertSpace(FockSpace(),Integer(2)))),(DirectSumHilbertSpace(L2(Interval(Integer(0), oo, false, true)),HilbertSpace())))")
def _test_sho1d():
ad = RaisingOp('a')
assert pretty(ad) == ' \N{DAGGER}\na '
assert latex(ad) == 'a^{\\dagger}'
|
3a3208baabbfd75e0eb2e16999aa15eae171f432640d3e5245516bd62c4df259 | from sympy.core.backend import Symbol, symbols, sin, cos, Matrix
from sympy.physics.vector import Point, ReferenceFrame, dynamicsymbols
from sympy.physics.mechanics import inertia, Body
from sympy.testing.pytest import raises
def test_default():
body = Body('body')
assert body.name == 'body'
assert body.loads == []
point = Point('body_masscenter')
point.set_vel(body.frame, 0)
com = body.masscenter
frame = body.frame
assert com.vel(frame) == point.vel(frame)
assert body.mass == Symbol('body_mass')
ixx, iyy, izz = symbols('body_ixx body_iyy body_izz')
ixy, iyz, izx = symbols('body_ixy body_iyz body_izx')
assert body.inertia == (inertia(body.frame, ixx, iyy, izz, ixy, iyz, izx),
body.masscenter)
def test_custom_rigid_body():
# Body with RigidBody.
rigidbody_masscenter = Point('rigidbody_masscenter')
rigidbody_mass = Symbol('rigidbody_mass')
rigidbody_frame = ReferenceFrame('rigidbody_frame')
body_inertia = inertia(rigidbody_frame, 1, 0, 0)
rigid_body = Body('rigidbody_body', rigidbody_masscenter, rigidbody_mass,
rigidbody_frame, body_inertia)
com = rigid_body.masscenter
frame = rigid_body.frame
rigidbody_masscenter.set_vel(rigidbody_frame, 0)
assert com.vel(frame) == rigidbody_masscenter.vel(frame)
assert com.pos_from(com) == rigidbody_masscenter.pos_from(com)
assert rigid_body.mass == rigidbody_mass
assert rigid_body.inertia == (body_inertia, rigidbody_masscenter)
assert rigid_body.is_rigidbody
assert hasattr(rigid_body, 'masscenter')
assert hasattr(rigid_body, 'mass')
assert hasattr(rigid_body, 'frame')
assert hasattr(rigid_body, 'inertia')
def test_particle_body():
# Body with Particle
particle_masscenter = Point('particle_masscenter')
particle_mass = Symbol('particle_mass')
particle_frame = ReferenceFrame('particle_frame')
particle_body = Body('particle_body', particle_masscenter, particle_mass,
particle_frame)
com = particle_body.masscenter
frame = particle_body.frame
particle_masscenter.set_vel(particle_frame, 0)
assert com.vel(frame) == particle_masscenter.vel(frame)
assert com.pos_from(com) == particle_masscenter.pos_from(com)
assert particle_body.mass == particle_mass
assert not hasattr(particle_body, "_inertia")
assert hasattr(particle_body, 'frame')
assert hasattr(particle_body, 'masscenter')
assert hasattr(particle_body, 'mass')
assert not particle_body.is_rigidbody
def test_particle_body_add_force():
# Body with Particle
particle_masscenter = Point('particle_masscenter')
particle_mass = Symbol('particle_mass')
particle_frame = ReferenceFrame('particle_frame')
particle_body = Body('particle_body', particle_masscenter, particle_mass,
particle_frame)
a = Symbol('a')
force_vector = a * particle_body.frame.x
particle_body.apply_force(force_vector, particle_body.masscenter)
assert len(particle_body.loads) == 1
point = particle_body.masscenter.locatenew(
particle_body._name + '_point0', 0)
point.set_vel(particle_body.frame, 0)
force_point = particle_body.loads[0][0]
frame = particle_body.frame
assert force_point.vel(frame) == point.vel(frame)
assert force_point.pos_from(force_point) == point.pos_from(force_point)
assert particle_body.loads[0][1] == force_vector
def test_body_add_force():
# Body with RigidBody.
rigidbody_masscenter = Point('rigidbody_masscenter')
rigidbody_mass = Symbol('rigidbody_mass')
rigidbody_frame = ReferenceFrame('rigidbody_frame')
body_inertia = inertia(rigidbody_frame, 1, 0, 0)
rigid_body = Body('rigidbody_body', rigidbody_masscenter, rigidbody_mass,
rigidbody_frame, body_inertia)
l = Symbol('l')
Fa = Symbol('Fa')
point = rigid_body.masscenter.locatenew(
'rigidbody_body_point0',
l * rigid_body.frame.x)
point.set_vel(rigid_body.frame, 0)
force_vector = Fa * rigid_body.frame.z
# apply_force with point
rigid_body.apply_force(force_vector, point)
assert len(rigid_body.loads) == 1
force_point = rigid_body.loads[0][0]
frame = rigid_body.frame
assert force_point.vel(frame) == point.vel(frame)
assert force_point.pos_from(force_point) == point.pos_from(force_point)
assert rigid_body.loads[0][1] == force_vector
# apply_force without point
rigid_body.apply_force(force_vector)
assert len(rigid_body.loads) == 2
assert rigid_body.loads[1][1] == force_vector
# passing something else than point
raises(TypeError, lambda: rigid_body.apply_force(force_vector, 0))
raises(TypeError, lambda: rigid_body.apply_force(0))
def test_body_add_torque():
body = Body('body')
torque_vector = body.frame.x
body.apply_torque(torque_vector)
assert len(body.loads) == 1
assert body.loads[0] == (body.frame, torque_vector)
raises(TypeError, lambda: body.apply_torque(0))
def test_body_masscenter_vel():
A = Body('A')
N = ReferenceFrame('N')
B = Body('B', frame=N)
A.masscenter.set_vel(N, N.z)
assert A.masscenter_vel(B) == N.z
assert A.masscenter_vel(N) == N.z
def test_body_ang_vel():
A = Body('A')
N = ReferenceFrame('N')
B = Body('B', frame=N)
A.frame.set_ang_vel(N, N.y)
assert A.ang_vel_in(B) == N.y
assert B.ang_vel_in(A) == -N.y
assert A.ang_vel_in(N) == N.y
def test_body_dcm():
A = Body('A')
B = Body('B')
A.frame.orient_axis(B.frame, B.frame.z, 10)
assert A.dcm(B) == Matrix([[cos(10), sin(10), 0], [-sin(10), cos(10), 0], [0, 0, 1]])
assert A.dcm(B.frame) == Matrix([[cos(10), sin(10), 0], [-sin(10), cos(10), 0], [0, 0, 1]])
def test_body_axis():
N = ReferenceFrame('N')
B = Body('B', frame=N)
assert B.x == N.x
assert B.y == N.y
assert B.z == N.z
def test_apply_force_multiple_one_point():
a, b = symbols('a b')
P = Point('P')
B = Body('B')
f1 = a*B.x
f2 = b*B.y
B.apply_force(f1, P)
assert B.loads == [(P, f1)]
B.apply_force(f2, P)
assert B.loads == [(P, f1+f2)]
def test_apply_force():
f, g = symbols('f g')
q, x, v1, v2 = dynamicsymbols('q x v1 v2')
P1 = Point('P1')
P2 = Point('P2')
B1 = Body('B1')
B2 = Body('B2')
N = ReferenceFrame('N')
P1.set_vel(B1.frame, v1*B1.x)
P2.set_vel(B2.frame, v2*B2.x)
force = f*q*N.z # time varying force
B1.apply_force(force, P1, B2, P2) #applying equal and opposite force on moving points
assert B1.loads == [(P1, force)]
assert B2.loads == [(P2, -force)]
g1 = B1.mass*g*N.y
g2 = B2.mass*g*N.y
B1.apply_force(g1) #applying gravity on B1 masscenter
B2.apply_force(g2) #applying gravity on B2 masscenter
assert B1.loads == [(P1,force), (B1.masscenter, g1)]
assert B2.loads == [(P2, -force), (B2.masscenter, g2)]
force2 = x*N.x
B1.apply_force(force2, reaction_body=B2) #Applying time varying force on masscenter
assert B1.loads == [(P1, force), (B1.masscenter, force2+g1)]
assert B2.loads == [(P2, -force), (B2.masscenter, -force2+g2)]
def test_apply_torque():
t = symbols('t')
q = dynamicsymbols('q')
B1 = Body('B1')
B2 = Body('B2')
N = ReferenceFrame('N')
torque = t*q*N.x
B1.apply_torque(torque, B2) #Applying equal and opposite torque
assert B1.loads == [(B1.frame, torque)]
assert B2.loads == [(B2.frame, -torque)]
torque2 = t*N.y
B1.apply_torque(torque2)
assert B1.loads == [(B1.frame, torque+torque2)]
def test_clear_load():
a = symbols('a')
P = Point('P')
B = Body('B')
force = a*B.z
B.apply_force(force, P)
assert B.loads == [(P, force)]
B.clear_loads()
assert B.loads == []
def test_remove_load():
P1 = Point('P1')
P2 = Point('P2')
B = Body('B')
f1 = B.x
f2 = B.y
B.apply_force(f1, P1)
B.apply_force(f2, P2)
assert B.loads == [(P1, f1), (P2, f2)]
B.remove_load(P2)
assert B.loads == [(P1, f1)]
B.apply_torque(f1.cross(f2))
assert B.loads == [(P1, f1), (B.frame, f1.cross(f2))]
B.remove_load()
assert B.loads == [(P1, f1)]
def test_apply_loads_on_multi_degree_freedom_holonomic_system():
"""Example based on: https://pydy.readthedocs.io/en/latest/examples/multidof-holonomic.html"""
W = Body('W') #Wall
B = Body('B') #Block
P = Body('P') #Pendulum
b = Body('b') #bob
q1, q2 = dynamicsymbols('q1 q2') #generalized coordinates
k, c, g, kT = symbols('k c g kT') #constants
F, T = dynamicsymbols('F T') #Specified forces
#Applying forces
B.apply_force(F*W.x)
W.apply_force(k*q1*W.x, reaction_body=B) #Spring force
W.apply_force(c*q1.diff()*W.x, reaction_body=B) #dampner
P.apply_force(P.mass*g*W.y)
b.apply_force(b.mass*g*W.y)
#Applying torques
P.apply_torque(kT*q2*W.z, reaction_body=b)
P.apply_torque(T*W.z)
assert B.loads == [(B.masscenter, (F - k*q1 - c*q1.diff())*W.x)]
assert P.loads == [(P.masscenter, P.mass*g*W.y), (P.frame, (T + kT*q2)*W.z)]
assert b.loads == [(b.masscenter, b.mass*g*W.y), (b.frame, -kT*q2*W.z)]
assert W.loads == [(W.masscenter, (c*q1.diff() + k*q1)*W.x)]
|
6216c40b245456a6abdfe528cd370a401ab5f363e4da839c4aff38041767ff8d | import functools, itertools
from sympy.core.sympify import _sympify, sympify
from sympy.core.expr import Expr
from sympy.core import Basic, Tuple
from sympy.tensor.array import ImmutableDenseNDimArray
from sympy.core.symbol import Symbol
from sympy.core.numbers import Integer
class ArrayComprehension(Basic):
"""
Generate a list comprehension.
Explanation
===========
If there is a symbolic dimension, for example, say [i for i in range(1, N)] where
N is a Symbol, then the expression will not be expanded to an array. Otherwise,
calling the doit() function will launch the expansion.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a
ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.doit()
[[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]]
>>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k))
>>> b.doit()
ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k))
"""
def __new__(cls, function, *symbols, **assumptions):
if any(len(l) != 3 or None for l in symbols):
raise ValueError('ArrayComprehension requires values lower and upper bound'
' for the expression')
arglist = [sympify(function)]
arglist.extend(cls._check_limits_validity(function, symbols))
obj = Basic.__new__(cls, *arglist, **assumptions)
obj._limits = obj._args[1:]
obj._shape = cls._calculate_shape_from_limits(obj._limits)
obj._rank = len(obj._shape)
obj._loop_size = cls._calculate_loop_size(obj._shape)
return obj
@property
def function(self):
"""The function applied across limits.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.function
10*i + j
"""
return self._args[0]
@property
def limits(self):
"""
The list of limits that will be applied while expanding the array.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.limits
((i, 1, 4), (j, 1, 3))
"""
return self._limits
@property
def free_symbols(self):
"""
The set of the free_symbols in the array.
Variables appeared in the bounds are supposed to be excluded
from the free symbol set.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.free_symbols
set()
>>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
>>> b.free_symbols
{k}
"""
expr_free_sym = self.function.free_symbols
for var, inf, sup in self._limits:
expr_free_sym.discard(var)
curr_free_syms = inf.free_symbols.union(sup.free_symbols)
expr_free_sym = expr_free_sym.union(curr_free_syms)
return expr_free_sym
@property
def variables(self):
"""The tuples of the variables in the limits.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.variables
[i, j]
"""
return [l[0] for l in self._limits]
@property
def bound_symbols(self):
"""The list of dummy variables.
Note
====
Note that all variables are dummy variables since a limit without
lower bound or upper bound is not accepted.
"""
return [l[0] for l in self._limits if len(l) != 1]
@property
def shape(self):
"""
The shape of the expanded array, which may have symbols.
Note
====
Both the lower and the upper bounds are included while
calculating the shape.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.shape
(4, 3)
>>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
>>> b.shape
(4, k + 3)
"""
return self._shape
@property
def is_shape_numeric(self):
"""
Test if the array is shape-numeric which means there is no symbolic
dimension.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.is_shape_numeric
True
>>> b = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, k+3))
>>> b.is_shape_numeric
False
"""
for _, inf, sup in self._limits:
if Basic(inf, sup).atoms(Symbol):
return False
return True
def rank(self):
"""The rank of the expanded array.
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.rank()
2
"""
return self._rank
def __len__(self):
"""
The length of the expanded array which means the number
of elements in the array.
Raises
======
ValueError : When the length of the array is symbolic
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> len(a)
12
"""
if self._loop_size.free_symbols:
raise ValueError('Symbolic length is not supported')
return self._loop_size
@classmethod
def _check_limits_validity(cls, function, limits):
#limits = sympify(limits)
new_limits = []
for var, inf, sup in limits:
var = _sympify(var)
inf = _sympify(inf)
#since this is stored as an argument, it should be
#a Tuple
if isinstance(sup, list):
sup = Tuple(*sup)
else:
sup = _sympify(sup)
new_limits.append(Tuple(var, inf, sup))
if any((not isinstance(i, Expr)) or i.atoms(Symbol, Integer) != i.atoms()
for i in [inf, sup]):
raise TypeError('Bounds should be an Expression(combination of Integer and Symbol)')
if (inf > sup) == True:
raise ValueError('Lower bound should be inferior to upper bound')
if var in inf.free_symbols or var in sup.free_symbols:
raise ValueError('Variable should not be part of its bounds')
return new_limits
@classmethod
def _calculate_shape_from_limits(cls, limits):
return tuple([sup - inf + 1 for _, inf, sup in limits])
@classmethod
def _calculate_loop_size(cls, shape):
if not shape:
return 0
loop_size = 1
for l in shape:
loop_size = loop_size * l
return loop_size
def doit(self):
if not self.is_shape_numeric:
return self
return self._expand_array()
def _expand_array(self):
res = []
for values in itertools.product(*[range(inf, sup+1)
for var, inf, sup
in self._limits]):
res.append(self._get_element(values))
return ImmutableDenseNDimArray(res, self.shape)
def _get_element(self, values):
temp = self.function
for var, val in zip(self.variables, values):
temp = temp.subs(var, val)
return temp
def tolist(self):
"""Transform the expanded array to a list.
Raises
======
ValueError : When there is a symbolic dimension
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.tolist()
[[11, 12, 13], [21, 22, 23], [31, 32, 33], [41, 42, 43]]
"""
if self.is_shape_numeric:
return self._expand_array().tolist()
raise ValueError("A symbolic array cannot be expanded to a list")
def tomatrix(self):
"""Transform the expanded array to a matrix.
Raises
======
ValueError : When there is a symbolic dimension
ValueError : When the rank of the expanded array is not equal to 2
Examples
========
>>> from sympy.tensor.array import ArrayComprehension
>>> from sympy import symbols
>>> i, j = symbols('i j')
>>> a = ArrayComprehension(10*i + j, (i, 1, 4), (j, 1, 3))
>>> a.tomatrix()
Matrix([
[11, 12, 13],
[21, 22, 23],
[31, 32, 33],
[41, 42, 43]])
"""
from sympy.matrices import Matrix
if not self.is_shape_numeric:
raise ValueError("A symbolic array cannot be expanded to a matrix")
if self._rank != 2:
raise ValueError('Dimensions must be of size of 2')
return Matrix(self._expand_array().tomatrix())
def isLambda(v):
LAMBDA = lambda: 0
return isinstance(v, type(LAMBDA)) and v.__name__ == LAMBDA.__name__
class ArrayComprehensionMap(ArrayComprehension):
'''
A subclass of ArrayComprehension dedicated to map external function lambda.
Notes
=====
Only the lambda function is considered.
At most one argument in lambda function is accepted in order to avoid ambiguity
in value assignment.
Examples
========
>>> from sympy.tensor.array import ArrayComprehensionMap
>>> from sympy import symbols
>>> i, j, k = symbols('i j k')
>>> a = ArrayComprehensionMap(lambda: 1, (i, 1, 4))
>>> a.doit()
[1, 1, 1, 1]
>>> b = ArrayComprehensionMap(lambda a: a+1, (j, 1, 4))
>>> b.doit()
[2, 3, 4, 5]
'''
def __new__(cls, function, *symbols, **assumptions):
if any(len(l) != 3 or None for l in symbols):
raise ValueError('ArrayComprehension requires values lower and upper bound'
' for the expression')
if not isLambda(function):
raise ValueError('Data type not supported')
arglist = cls._check_limits_validity(function, symbols)
obj = Basic.__new__(cls, *arglist, **assumptions)
obj._limits = obj._args
obj._shape = cls._calculate_shape_from_limits(obj._limits)
obj._rank = len(obj._shape)
obj._loop_size = cls._calculate_loop_size(obj._shape)
obj._lambda = function
return obj
@property
def func(self):
class _(ArrayComprehensionMap):
def __new__(cls, *args, **kwargs):
return ArrayComprehensionMap(self._lambda, *args, **kwargs)
return _
def _get_element(self, values):
temp = self._lambda
if self._lambda.__code__.co_argcount == 0:
temp = temp()
elif self._lambda.__code__.co_argcount == 1:
temp = temp(functools.reduce(lambda a, b: a*b, values))
return temp
|
c31130209bbac0ca186d2554c6692037a7781c30f72e0002129a5c9baf84e331 | import itertools
from collections.abc import Iterable
from sympy.core._print_helpers import Printable
from sympy.core.containers import Tuple
from sympy.core.function import diff
from sympy.core.singleton import S
from sympy.core.sympify import _sympify
from sympy.tensor.array.ndim_array import NDimArray
from sympy.tensor.array.dense_ndim_array import DenseNDimArray, ImmutableDenseNDimArray
from sympy.tensor.array.sparse_ndim_array import SparseNDimArray
def _arrayfy(a):
from sympy.matrices import MatrixBase
if isinstance(a, NDimArray):
return a
if isinstance(a, (MatrixBase, list, tuple, Tuple)):
return ImmutableDenseNDimArray(a)
return a
def tensorproduct(*args):
"""
Tensor product among scalars or array-like objects.
Examples
========
>>> from sympy.tensor.array import tensorproduct, Array
>>> from sympy.abc import x, y, z, t
>>> A = Array([[1, 2], [3, 4]])
>>> B = Array([x, y])
>>> tensorproduct(A, B)
[[[x, y], [2*x, 2*y]], [[3*x, 3*y], [4*x, 4*y]]]
>>> tensorproduct(A, x)
[[x, 2*x], [3*x, 4*x]]
>>> tensorproduct(A, B, B)
[[[[x**2, x*y], [x*y, y**2]], [[2*x**2, 2*x*y], [2*x*y, 2*y**2]]], [[[3*x**2, 3*x*y], [3*x*y, 3*y**2]], [[4*x**2, 4*x*y], [4*x*y, 4*y**2]]]]
Applying this function on two matrices will result in a rank 4 array.
>>> from sympy import Matrix, eye
>>> m = Matrix([[x, y], [z, t]])
>>> p = tensorproduct(eye(3), m)
>>> p
[[[[x, y], [z, t]], [[0, 0], [0, 0]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[x, y], [z, t]], [[0, 0], [0, 0]]], [[[0, 0], [0, 0]], [[0, 0], [0, 0]], [[x, y], [z, t]]]]
"""
from sympy.tensor.array import SparseNDimArray, ImmutableSparseNDimArray
if len(args) == 0:
return S.One
if len(args) == 1:
return _arrayfy(args[0])
from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct
from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
from sympy.matrices.expressions.matexpr import MatrixSymbol
if any(isinstance(arg, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)) for arg in args):
return ArrayTensorProduct(*args)
if len(args) > 2:
return tensorproduct(tensorproduct(args[0], args[1]), *args[2:])
# length of args is 2:
a, b = map(_arrayfy, args)
if not isinstance(a, NDimArray) or not isinstance(b, NDimArray):
return a*b
if isinstance(a, SparseNDimArray) and isinstance(b, SparseNDimArray):
lp = len(b)
new_array = {k1*lp + k2: v1*v2 for k1, v1 in a._sparse_array.items() for k2, v2 in b._sparse_array.items()}
return ImmutableSparseNDimArray(new_array, a.shape + b.shape)
product_list = [i*j for i in Flatten(a) for j in Flatten(b)]
return ImmutableDenseNDimArray(product_list, a.shape + b.shape)
def _util_contraction_diagonal(array, *contraction_or_diagonal_axes):
array = _arrayfy(array)
# Verify contraction_axes:
taken_dims = set()
for axes_group in contraction_or_diagonal_axes:
if not isinstance(axes_group, Iterable):
raise ValueError("collections of contraction/diagonal axes expected")
dim = array.shape[axes_group[0]]
for d in axes_group:
if d in taken_dims:
raise ValueError("dimension specified more than once")
if dim != array.shape[d]:
raise ValueError("cannot contract or diagonalize between axes of different dimension")
taken_dims.add(d)
rank = array.rank()
remaining_shape = [dim for i, dim in enumerate(array.shape) if i not in taken_dims]
cum_shape = [0]*rank
_cumul = 1
for i in range(rank):
cum_shape[rank - i - 1] = _cumul
_cumul *= int(array.shape[rank - i - 1])
# DEFINITION: by absolute position it is meant the position along the one
# dimensional array containing all the tensor components.
# Possible future work on this module: move computation of absolute
# positions to a class method.
# Determine absolute positions of the uncontracted indices:
remaining_indices = [[cum_shape[i]*j for j in range(array.shape[i])]
for i in range(rank) if i not in taken_dims]
# Determine absolute positions of the contracted indices:
summed_deltas = []
for axes_group in contraction_or_diagonal_axes:
lidx = []
for js in range(array.shape[axes_group[0]]):
lidx.append(sum([cum_shape[ig] * js for ig in axes_group]))
summed_deltas.append(lidx)
return array, remaining_indices, remaining_shape, summed_deltas
def tensorcontraction(array, *contraction_axes):
"""
Contraction of an array-like object on the specified axes.
Examples
========
>>> from sympy import Array, tensorcontraction
>>> from sympy import Matrix, eye
>>> tensorcontraction(eye(3), (0, 1))
3
>>> A = Array(range(18), (3, 2, 3))
>>> A
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]]
>>> tensorcontraction(A, (0, 2))
[21, 30]
Matrix multiplication may be emulated with a proper combination of
``tensorcontraction`` and ``tensorproduct``
>>> from sympy import tensorproduct
>>> from sympy.abc import a,b,c,d,e,f,g,h
>>> m1 = Matrix([[a, b], [c, d]])
>>> m2 = Matrix([[e, f], [g, h]])
>>> p = tensorproduct(m1, m2)
>>> p
[[[[a*e, a*f], [a*g, a*h]], [[b*e, b*f], [b*g, b*h]]], [[[c*e, c*f], [c*g, c*h]], [[d*e, d*f], [d*g, d*h]]]]
>>> tensorcontraction(p, (1, 2))
[[a*e + b*g, a*f + b*h], [c*e + d*g, c*f + d*h]]
>>> m1*m2
Matrix([
[a*e + b*g, a*f + b*h],
[c*e + d*g, c*f + d*h]])
"""
from sympy.tensor.array.expressions.array_expressions import _array_contraction
from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
from sympy.matrices.expressions.matexpr import MatrixSymbol
if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
return _array_contraction(array, *contraction_axes)
array, remaining_indices, remaining_shape, summed_deltas = _util_contraction_diagonal(array, *contraction_axes)
# Compute the contracted array:
#
# 1. external for loops on all uncontracted indices.
# Uncontracted indices are determined by the combinatorial product of
# the absolute positions of the remaining indices.
# 2. internal loop on all contracted indices.
# It sums the values of the absolute contracted index and the absolute
# uncontracted index for the external loop.
contracted_array = []
for icontrib in itertools.product(*remaining_indices):
index_base_position = sum(icontrib)
isum = S.Zero
for sum_to_index in itertools.product(*summed_deltas):
idx = array._get_tuple_index(index_base_position + sum(sum_to_index))
isum += array[idx]
contracted_array.append(isum)
if len(remaining_indices) == 0:
assert len(contracted_array) == 1
return contracted_array[0]
return type(array)(contracted_array, remaining_shape)
def tensordiagonal(array, *diagonal_axes):
"""
Diagonalization of an array-like object on the specified axes.
This is equivalent to multiplying the expression by Kronecker deltas
uniting the axes.
The diagonal indices are put at the end of the axes.
Examples
========
``tensordiagonal`` acting on a 2-dimensional array by axes 0 and 1 is
equivalent to the diagonal of the matrix:
>>> from sympy import Array, tensordiagonal
>>> from sympy import Matrix, eye
>>> tensordiagonal(eye(3), (0, 1))
[1, 1, 1]
>>> from sympy.abc import a,b,c,d
>>> m1 = Matrix([[a, b], [c, d]])
>>> tensordiagonal(m1, [0, 1])
[a, d]
In case of higher dimensional arrays, the diagonalized out dimensions
are appended removed and appended as a single dimension at the end:
>>> A = Array(range(18), (3, 2, 3))
>>> A
[[[0, 1, 2], [3, 4, 5]], [[6, 7, 8], [9, 10, 11]], [[12, 13, 14], [15, 16, 17]]]
>>> tensordiagonal(A, (0, 2))
[[0, 7, 14], [3, 10, 17]]
>>> from sympy import permutedims
>>> tensordiagonal(A, (0, 2)) == permutedims(Array([A[0, :, 0], A[1, :, 1], A[2, :, 2]]), [1, 0])
True
"""
if any(len(i) <= 1 for i in diagonal_axes):
raise ValueError("need at least two axes to diagonalize")
from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal, _array_diagonal
from sympy.matrices.expressions.matexpr import MatrixSymbol
if isinstance(array, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
return _array_diagonal(array, *diagonal_axes)
ArrayDiagonal._validate(array, *diagonal_axes)
array, remaining_indices, remaining_shape, diagonal_deltas = _util_contraction_diagonal(array, *diagonal_axes)
# Compute the diagonalized array:
#
# 1. external for loops on all undiagonalized indices.
# Undiagonalized indices are determined by the combinatorial product of
# the absolute positions of the remaining indices.
# 2. internal loop on all diagonal indices.
# It appends the values of the absolute diagonalized index and the absolute
# undiagonalized index for the external loop.
diagonalized_array = []
diagonal_shape = [len(i) for i in diagonal_deltas]
for icontrib in itertools.product(*remaining_indices):
index_base_position = sum(icontrib)
isum = []
for sum_to_index in itertools.product(*diagonal_deltas):
idx = array._get_tuple_index(index_base_position + sum(sum_to_index))
isum.append(array[idx])
isum = type(array)(isum).reshape(*diagonal_shape)
diagonalized_array.append(isum)
return type(array)(diagonalized_array, remaining_shape + diagonal_shape)
def derive_by_array(expr, dx):
r"""
Derivative by arrays. Supports both arrays and scalars.
Explanation
===========
Given the array `A_{i_1, \ldots, i_N}` and the array `X_{j_1, \ldots, j_M}`
this function will return a new array `B` defined by
`B_{j_1,\ldots,j_M,i_1,\ldots,i_N} := \frac{\partial A_{i_1,\ldots,i_N}}{\partial X_{j_1,\ldots,j_M}}`
Examples
========
>>> from sympy import derive_by_array
>>> from sympy.abc import x, y, z, t
>>> from sympy import cos
>>> derive_by_array(cos(x*t), x)
-t*sin(t*x)
>>> derive_by_array(cos(x*t), [x, y, z, t])
[-t*sin(t*x), 0, 0, -x*sin(t*x)]
>>> derive_by_array([x, y**2*z], [[x, y], [z, t]])
[[[1, 0], [0, 2*y*z]], [[0, y**2], [0, 0]]]
"""
from sympy.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
array_types = (Iterable, MatrixBase, NDimArray)
if isinstance(dx, array_types):
dx = ImmutableDenseNDimArray(dx)
for i in dx:
if not i._diff_wrt:
raise ValueError("cannot derive by this array")
if isinstance(expr, array_types):
if isinstance(expr, NDimArray):
expr = expr.as_immutable()
else:
expr = ImmutableDenseNDimArray(expr)
if isinstance(dx, array_types):
if isinstance(expr, SparseNDimArray):
lp = len(expr)
new_array = {k + i*lp: v
for i, x in enumerate(Flatten(dx))
for k, v in expr.diff(x)._sparse_array.items()}
else:
new_array = [[y.diff(x) for y in Flatten(expr)] for x in Flatten(dx)]
return type(expr)(new_array, dx.shape + expr.shape)
else:
return expr.diff(dx)
else:
expr = _sympify(expr)
if isinstance(dx, array_types):
return ImmutableDenseNDimArray([expr.diff(i) for i in Flatten(dx)], dx.shape)
else:
dx = _sympify(dx)
return diff(expr, dx)
def permutedims(expr, perm):
"""
Permutes the indices of an array.
Parameter specifies the permutation of the indices.
Examples
========
>>> from sympy.abc import x, y, z, t
>>> from sympy import sin
>>> from sympy import Array, permutedims
>>> a = Array([[x, y, z], [t, sin(x), 0]])
>>> a
[[x, y, z], [t, sin(x), 0]]
>>> permutedims(a, (1, 0))
[[x, t], [y, sin(x)], [z, 0]]
If the array is of second order, ``transpose`` can be used:
>>> from sympy import transpose
>>> transpose(a)
[[x, t], [y, sin(x)], [z, 0]]
Examples on higher dimensions:
>>> b = Array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
>>> permutedims(b, (2, 1, 0))
[[[1, 5], [3, 7]], [[2, 6], [4, 8]]]
>>> permutedims(b, (1, 2, 0))
[[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
``Permutation`` objects are also allowed:
>>> from sympy.combinatorics import Permutation
>>> permutedims(b, Permutation([1, 2, 0]))
[[[1, 5], [2, 6]], [[3, 7], [4, 8]]]
"""
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.expressions.array_expressions import _ArrayExpr
from sympy.tensor.array.expressions.array_expressions import _CodegenArrayAbstract
from sympy.tensor.array.expressions.array_expressions import _permute_dims
from sympy.matrices.expressions.matexpr import MatrixSymbol
if isinstance(expr, (_ArrayExpr, _CodegenArrayAbstract, MatrixSymbol)):
return _permute_dims(expr, perm)
if not isinstance(expr, NDimArray):
expr = ImmutableDenseNDimArray(expr)
from sympy.combinatorics import Permutation
if not isinstance(perm, Permutation):
perm = Permutation(list(perm))
if perm.size != expr.rank():
raise ValueError("wrong permutation size")
# Get the inverse permutation:
iperm = ~perm
new_shape = perm(expr.shape)
if isinstance(expr, SparseNDimArray):
return type(expr)({tuple(perm(expr._get_tuple_index(k))): v
for k, v in expr._sparse_array.items()}, new_shape)
indices_span = perm([range(i) for i in expr.shape])
new_array = [None]*len(expr)
for i, idx in enumerate(itertools.product(*indices_span)):
t = iperm(idx)
new_array[i] = expr[t]
return type(expr)(new_array, new_shape)
class Flatten(Printable):
'''
Flatten an iterable object to a list in a lazy-evaluation way.
Notes
=====
This class is an iterator with which the memory cost can be economised.
Optimisation has been considered to ameliorate the performance for some
specific data types like DenseNDimArray and SparseNDimArray.
Examples
========
>>> from sympy.tensor.array.arrayop import Flatten
>>> from sympy.tensor.array import Array
>>> A = Array(range(6)).reshape(2, 3)
>>> Flatten(A)
Flatten([[0, 1, 2], [3, 4, 5]])
>>> [i for i in Flatten(A)]
[0, 1, 2, 3, 4, 5]
'''
def __init__(self, iterable):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import NDimArray
if not isinstance(iterable, (Iterable, MatrixBase)):
raise NotImplementedError("Data type not yet supported")
if isinstance(iterable, list):
iterable = NDimArray(iterable)
self._iter = iterable
self._idx = 0
def __iter__(self):
return self
def __next__(self):
from sympy.matrices.matrices import MatrixBase
if len(self._iter) > self._idx:
if isinstance(self._iter, DenseNDimArray):
result = self._iter._array[self._idx]
elif isinstance(self._iter, SparseNDimArray):
if self._idx in self._iter._sparse_array:
result = self._iter._sparse_array[self._idx]
else:
result = 0
elif isinstance(self._iter, MatrixBase):
result = self._iter[self._idx]
elif hasattr(self._iter, '__next__'):
result = next(self._iter)
else:
result = self._iter[self._idx]
else:
raise StopIteration
self._idx += 1
return result
def next(self):
return self.__next__()
def _sympystr(self, printer):
return type(self).__name__ + '(' + printer._print(self._iter) + ')'
|
8fb9019b5a135fe0f55f7a947590be7190badff4edd12b1089b4641db2c40509 | from sympy.testing.pytest import raises
from sympy.tensor.toperators import PartialDerivative
from sympy.tensor.tensor import (TensorIndexType,
tensor_indices,
TensorHead, tensor_heads)
from sympy.core.numbers import Rational
from sympy.core.symbol import symbols
from sympy.matrices.dense import diag
from sympy.tensor.array import Array
from sympy.core.random import randint
L = TensorIndexType("L")
i, j, k, m, m1, m2, m3, m4 = tensor_indices("i j k m m1 m2 m3 m4", L)
i0 = tensor_indices("i0", L)
L_0, L_1 = tensor_indices("L_0 L_1", L)
A, B, C, D = tensor_heads("A B C D", [L])
H = TensorHead("H", [L, L])
def test_invalid_partial_derivative_valence():
raises(ValueError, lambda: PartialDerivative(C(j), D(-j)))
raises(ValueError, lambda: PartialDerivative(C(-j), D(j)))
def test_tensor_partial_deriv():
# Test flatten:
expr = PartialDerivative(PartialDerivative(A(i), A(j)), A(i))
assert expr.expr == A(L_0)
assert expr.variables == (A(j), A(L_0))
expr1 = PartialDerivative(A(i), A(j))
assert expr1.expr == A(i)
assert expr1.variables == (A(j),)
expr2 = A(i)*PartialDerivative(H(k, -i), A(j))
assert expr2.get_indices() == [L_0, k, -L_0, -j]
expr2b = A(i)*PartialDerivative(H(k, -i), A(-j))
assert expr2b.get_indices() == [L_0, k, -L_0, j]
expr3 = A(i)*PartialDerivative(B(k)*C(-i) + 3*H(k, -i), A(j))
assert expr3.get_indices() == [L_0, k, -L_0, -j]
expr4 = (A(i) + B(i))*PartialDerivative(C(j), D(j))
assert expr4.get_indices() == [i, L_0, -L_0]
expr4b = (A(i) + B(i))*PartialDerivative(C(-j), D(-j))
assert expr4b.get_indices() == [i, -L_0, L_0]
expr5 = (A(i) + B(i))*PartialDerivative(C(-i), D(j))
assert expr5.get_indices() == [L_0, -L_0, -j]
def test_replace_arrays_partial_derivative():
x, y, z, t = symbols("x y z t")
# d(A^i)/d(A_j) = d(g^ik A_k)/d(A_j) = g^ik delta_jk
expr = PartialDerivative(A(i), A(-j))
assert expr.get_free_indices() == [i, j]
assert expr.get_indices() == [i, j]
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, [i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, [i, j]) == Array([[1, 0], [0, -1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, 1)}, [i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, -1)}, [i, j]) == Array([[1, 0], [0, -1]])
expr = PartialDerivative(A(i), A(j))
assert expr.get_free_indices() == [i, -j]
assert expr.get_indices() == [i, -j]
assert expr.replace_with_arrays({A(i): [x, y]}, [i, -j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, [i, -j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, [i, -j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, 1)}, [i, -j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, -1)}, [i, -j]) == Array([[1, 0], [0, 1]])
expr = PartialDerivative(A(-i), A(-j))
assert expr.get_free_indices() == [-i, j]
assert expr.get_indices() == [-i, j]
assert expr.replace_with_arrays({A(-i): [x, y]}, [-i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, 1)}, [-i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, -1)}, [-i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, [-i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, [-i, j]) == Array([[1, 0], [0, 1]])
expr = PartialDerivative(A(i), A(i))
assert expr.get_free_indices() == []
assert expr.get_indices() == [L_0, -L_0]
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, []) == 2
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, []) == 2
expr = PartialDerivative(A(-i), A(-i))
assert expr.get_free_indices() == []
assert expr.get_indices() == [-L_0, L_0]
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, []) == 2
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, []) == 2
expr = PartialDerivative(H(i, j) + H(j, i), A(i))
assert expr.get_indices() == [L_0, j, -L_0]
assert expr.get_free_indices() == [j]
expr = PartialDerivative(H(i, j) + H(j, i), A(k))*B(-i)
assert expr.get_indices() == [L_0, j, -k, -L_0]
assert expr.get_free_indices() == [j, -k]
expr = PartialDerivative(A(i)*(H(-i, j) + H(j, -i)), A(j))
assert expr.get_indices() == [L_0, -L_0, L_1, -L_1]
assert expr.get_free_indices() == []
expr = A(j)*A(-j) + expr
assert expr.get_indices() == [L_0, -L_0, L_1, -L_1]
assert expr.get_free_indices() == []
expr = A(i)*(B(j)*PartialDerivative(C(-j), D(i)) + C(j)*PartialDerivative(D(-j), B(i)))
assert expr.get_indices() == [L_0, L_1, -L_1, -L_0]
assert expr.get_free_indices() == []
expr = A(i)*PartialDerivative(C(-j), D(i))
assert expr.get_indices() == [L_0, -j, -L_0]
assert expr.get_free_indices() == [-j]
def test_expand_partial_derivative_sum_rule():
tau = symbols("tau")
# check sum rule for D(tensor, symbol)
expr1aa = PartialDerivative(A(i), tau)
assert expr1aa._expand_partial_derivative() == PartialDerivative(A(i), tau)
expr1ab = PartialDerivative(A(i) + B(i), tau)
assert (expr1ab._expand_partial_derivative() ==
PartialDerivative(A(i), tau) +
PartialDerivative(B(i), tau))
expr1ac = PartialDerivative(A(i) + B(i) + C(i), tau)
assert (expr1ac._expand_partial_derivative() ==
PartialDerivative(A(i), tau) +
PartialDerivative(B(i), tau) +
PartialDerivative(C(i), tau))
# check sum rule for D(tensor, D(j))
expr1ba = PartialDerivative(A(i), D(j))
assert expr1ba._expand_partial_derivative() ==\
PartialDerivative(A(i), D(j))
expr1bb = PartialDerivative(A(i) + B(i), D(j))
assert (expr1bb._expand_partial_derivative() ==
PartialDerivative(A(i), D(j)) +
PartialDerivative(B(i), D(j)))
expr1bc = PartialDerivative(A(i) + B(i) + C(i), D(j))
assert expr1bc._expand_partial_derivative() ==\
PartialDerivative(A(i), D(j))\
+ PartialDerivative(B(i), D(j))\
+ PartialDerivative(C(i), D(j))
# check sum rule for D(tensor, H(j, k))
expr1ca = PartialDerivative(A(i), H(j, k))
assert expr1ca._expand_partial_derivative() ==\
PartialDerivative(A(i), H(j, k))
expr1cb = PartialDerivative(A(i) + B(i), H(j, k))
assert (expr1cb._expand_partial_derivative() ==
PartialDerivative(A(i), H(j, k))
+ PartialDerivative(B(i), H(j, k)))
expr1cc = PartialDerivative(A(i) + B(i) + C(i), H(j, k))
assert (expr1cc._expand_partial_derivative() ==
PartialDerivative(A(i), H(j, k))
+ PartialDerivative(B(i), H(j, k))
+ PartialDerivative(C(i), H(j, k)))
# check sum rule for D(D(tensor, D(j)), H(k, m))
expr1da = PartialDerivative(A(i), (D(j), H(k, m)))
assert expr1da._expand_partial_derivative() ==\
PartialDerivative(A(i), (D(j), H(k, m)))
expr1db = PartialDerivative(A(i) + B(i), (D(j), H(k, m)))
assert expr1db._expand_partial_derivative() ==\
PartialDerivative(A(i), (D(j), H(k, m)))\
+ PartialDerivative(B(i), (D(j), H(k, m)))
expr1dc = PartialDerivative(A(i) + B(i) + C(i), (D(j), H(k, m)))
assert expr1dc._expand_partial_derivative() ==\
PartialDerivative(A(i), (D(j), H(k, m)))\
+ PartialDerivative(B(i), (D(j), H(k, m)))\
+ PartialDerivative(C(i), (D(j), H(k, m)))
def test_expand_partial_derivative_constant_factor_rule():
nneg = randint(0, 1000)
pos = randint(1, 1000)
neg = -randint(1, 1000)
c1 = Rational(nneg, pos)
c2 = Rational(neg, pos)
c3 = Rational(nneg, neg)
expr2a = PartialDerivative(nneg*A(i), D(j))
assert expr2a._expand_partial_derivative() ==\
nneg*PartialDerivative(A(i), D(j))
expr2b = PartialDerivative(neg*A(i), D(j))
assert expr2b._expand_partial_derivative() ==\
neg*PartialDerivative(A(i), D(j))
expr2ca = PartialDerivative(c1*A(i), D(j))
assert expr2ca._expand_partial_derivative() ==\
c1*PartialDerivative(A(i), D(j))
expr2cb = PartialDerivative(c2*A(i), D(j))
assert expr2cb._expand_partial_derivative() ==\
c2*PartialDerivative(A(i), D(j))
expr2cc = PartialDerivative(c3*A(i), D(j))
assert expr2cc._expand_partial_derivative() ==\
c3*PartialDerivative(A(i), D(j))
def test_expand_partial_derivative_full_linearity():
nneg = randint(0, 1000)
pos = randint(1, 1000)
neg = -randint(1, 1000)
c1 = Rational(nneg, pos)
c2 = Rational(neg, pos)
c3 = Rational(nneg, neg)
# check full linearity
p = PartialDerivative(42, D(j))
assert p and not p._expand_partial_derivative()
expr3a = PartialDerivative(nneg*A(i) + pos*B(i), D(j))
assert expr3a._expand_partial_derivative() ==\
nneg*PartialDerivative(A(i), D(j))\
+ pos*PartialDerivative(B(i), D(j))
expr3b = PartialDerivative(nneg*A(i) + neg*B(i), D(j))
assert expr3b._expand_partial_derivative() ==\
nneg*PartialDerivative(A(i), D(j))\
+ neg*PartialDerivative(B(i), D(j))
expr3c = PartialDerivative(neg*A(i) + pos*B(i), D(j))
assert expr3c._expand_partial_derivative() ==\
neg*PartialDerivative(A(i), D(j))\
+ pos*PartialDerivative(B(i), D(j))
expr3d = PartialDerivative(c1*A(i) + c2*B(i), D(j))
assert expr3d._expand_partial_derivative() ==\
c1*PartialDerivative(A(i), D(j))\
+ c2*PartialDerivative(B(i), D(j))
expr3e = PartialDerivative(c2*A(i) + c1*B(i), D(j))
assert expr3e._expand_partial_derivative() ==\
c2*PartialDerivative(A(i), D(j))\
+ c1*PartialDerivative(B(i), D(j))
expr3f = PartialDerivative(c2*A(i) + c3*B(i), D(j))
assert expr3f._expand_partial_derivative() ==\
c2*PartialDerivative(A(i), D(j))\
+ c3*PartialDerivative(B(i), D(j))
expr3g = PartialDerivative(c3*A(i) + c2*B(i), D(j))
assert expr3g._expand_partial_derivative() ==\
c3*PartialDerivative(A(i), D(j))\
+ c2*PartialDerivative(B(i), D(j))
expr3h = PartialDerivative(c3*A(i) + c1*B(i), D(j))
assert expr3h._expand_partial_derivative() ==\
c3*PartialDerivative(A(i), D(j))\
+ c1*PartialDerivative(B(i), D(j))
expr3i = PartialDerivative(c1*A(i) + c3*B(i), D(j))
assert expr3i._expand_partial_derivative() ==\
c1*PartialDerivative(A(i), D(j))\
+ c3*PartialDerivative(B(i), D(j))
def test_expand_partial_derivative_product_rule():
# check product rule
expr4a = PartialDerivative(A(i)*B(j), D(k))
assert expr4a._expand_partial_derivative() == \
PartialDerivative(A(i), D(k))*B(j)\
+ A(i)*PartialDerivative(B(j), D(k))
expr4b = PartialDerivative(A(i)*B(j)*C(k), D(m))
assert expr4b._expand_partial_derivative() ==\
PartialDerivative(A(i), D(m))*B(j)*C(k)\
+ A(i)*PartialDerivative(B(j), D(m))*C(k)\
+ A(i)*B(j)*PartialDerivative(C(k), D(m))
expr4c = PartialDerivative(A(i)*B(j), C(k), D(m))
assert expr4c._expand_partial_derivative() ==\
PartialDerivative(A(i), C(k), D(m))*B(j) \
+ PartialDerivative(A(i), C(k))*PartialDerivative(B(j), D(m))\
+ PartialDerivative(A(i), D(m))*PartialDerivative(B(j), C(k))\
+ A(i)*PartialDerivative(B(j), C(k), D(m))
def test_eval_partial_derivative_expr_by_symbol():
tau, alpha = symbols("tau alpha")
expr1 = PartialDerivative(tau**alpha, tau)
assert expr1._perform_derivative() == alpha * 1 / tau * tau ** alpha
expr2 = PartialDerivative(2*tau + 3*tau**4, tau)
assert expr2._perform_derivative() == 2 + 12 * tau ** 3
expr3 = PartialDerivative(2*tau + 3*tau**4, alpha)
assert expr3._perform_derivative() == 0
def test_eval_partial_derivative_single_tensors_by_scalar():
tau, mu = symbols("tau mu")
expr = PartialDerivative(tau**mu, tau)
assert expr._perform_derivative() == mu*tau**mu/tau
expr1a = PartialDerivative(A(i), tau)
assert expr1a._perform_derivative() == 0
expr1b = PartialDerivative(A(-i), tau)
assert expr1b._perform_derivative() == 0
expr2a = PartialDerivative(H(i, j), tau)
assert expr2a._perform_derivative() == 0
expr2b = PartialDerivative(H(i, -j), tau)
assert expr2b._perform_derivative() == 0
expr2c = PartialDerivative(H(-i, j), tau)
assert expr2c._perform_derivative() == 0
expr2d = PartialDerivative(H(-i, -j), tau)
assert expr2d._perform_derivative() == 0
def test_eval_partial_derivative_single_1st_rank_tensors_by_tensor():
expr1 = PartialDerivative(A(i), A(j))
assert expr1._perform_derivative() - L.delta(i, -j) == 0
expr2 = PartialDerivative(A(i), A(-j))
assert expr2._perform_derivative() - L.metric(i, L_0) * L.delta(-L_0, j) == 0
expr3 = PartialDerivative(A(-i), A(-j))
assert expr3._perform_derivative() - L.delta(-i, j) == 0
expr4 = PartialDerivative(A(-i), A(j))
assert expr4._perform_derivative() - L.metric(-i, -L_0) * L.delta(L_0, -j) == 0
expr5 = PartialDerivative(A(i), B(j))
expr6 = PartialDerivative(A(i), C(j))
expr7 = PartialDerivative(A(i), D(j))
expr8 = PartialDerivative(A(i), H(j, k))
assert expr5._perform_derivative() == 0
assert expr6._perform_derivative() == 0
assert expr7._perform_derivative() == 0
assert expr8._perform_derivative() == 0
expr9 = PartialDerivative(A(i), A(i))
assert expr9._perform_derivative() - L.delta(L_0, -L_0) == 0
expr10 = PartialDerivative(A(-i), A(-i))
assert expr10._perform_derivative() - L.delta(-L_0, L_0) == 0
def test_eval_partial_derivative_single_2nd_rank_tensors_by_tensor():
expr1 = PartialDerivative(H(i, j), H(m, m1))
assert expr1._perform_derivative() - L.delta(i, -m) * L.delta(j, -m1) == 0
expr2 = PartialDerivative(H(i, j), H(-m, m1))
assert expr2._perform_derivative() - L.metric(i, L_0) * L.delta(-L_0, m) * L.delta(j, -m1) == 0
expr3 = PartialDerivative(H(i, j), H(m, -m1))
assert expr3._perform_derivative() - L.delta(i, -m) * L.metric(j, L_0) * L.delta(-L_0, m1) == 0
expr4 = PartialDerivative(H(i, j), H(-m, -m1))
assert expr4._perform_derivative() - L.metric(i, L_0) * L.delta(-L_0, m) * L.metric(j, L_1) * L.delta(-L_1, m1) == 0
def test_eval_partial_derivative_divergence_type():
expr1a = PartialDerivative(A(i), A(i))
expr1b = PartialDerivative(A(i), A(k))
expr1c = PartialDerivative(L.delta(-i, k) * A(i), A(k))
assert (expr1a._perform_derivative()
- (L.delta(-i, k) * expr1b._perform_derivative())).contract_delta(L.delta) == 0
assert (expr1a._perform_derivative()
- expr1c._perform_derivative()).contract_delta(L.delta) == 0
expr2a = PartialDerivative(H(i, j), H(i, j))
expr2b = PartialDerivative(H(i, j), H(k, m))
expr2c = PartialDerivative(L.delta(-i, k) * L.delta(-j, m) * H(i, j), H(k, m))
assert (expr2a._perform_derivative()
- (L.delta(-i, k) * L.delta(-j, m) * expr2b._perform_derivative())).contract_delta(L.delta) == 0
assert (expr2a._perform_derivative()
- expr2c._perform_derivative()).contract_delta(L.delta) == 0
def test_eval_partial_derivative_expr1():
tau, alpha = symbols("tau alpha")
# this is only some special expression
# tested: vector derivative
# tested: scalar derivative
# tested: tensor derivative
base_expr1 = A(i)*H(-i, j) + A(i)*A(-i)*A(j) + tau**alpha*A(j)
tensor_derivative = PartialDerivative(base_expr1, H(k, m))._perform_derivative()
vector_derivative = PartialDerivative(base_expr1, A(k))._perform_derivative()
scalar_derivative = PartialDerivative(base_expr1, tau)._perform_derivative()
assert (tensor_derivative - A(L_0)*L.metric(-L_0, -L_1)*L.delta(L_1, -k)*L.delta(j, -m)) == 0
assert (vector_derivative - (tau**alpha*L.delta(j, -k) +
L.delta(L_0, -k)*A(-L_0)*A(j) +
A(L_0)*L.metric(-L_0, -L_1)*L.delta(L_1, -k)*A(j) +
A(L_0)*A(-L_0)*L.delta(j, -k) +
L.delta(L_0, -k)*H(-L_0, j))).expand() == 0
assert (vector_derivative.contract_metric(L.metric).contract_delta(L.delta) -
(tau**alpha*L.delta(j, -k) + A(L_0)*A(-L_0)*L.delta(j, -k) + H(-k, j) + 2*A(j)*A(-k))).expand() == 0
assert scalar_derivative - alpha*1/tau*tau**alpha*A(j) == 0
def test_eval_partial_derivative_mixed_scalar_tensor_expr2():
tau, alpha = symbols("tau alpha")
base_expr2 = A(i)*A(-i) + tau**2
vector_expression = PartialDerivative(base_expr2, A(k))._perform_derivative()
assert (vector_expression -
(L.delta(L_0, -k)*A(-L_0) + A(L_0)*L.metric(-L_0, -L_1)*L.delta(L_1, -k))).expand() == 0
scalar_expression = PartialDerivative(base_expr2, tau)._perform_derivative()
assert scalar_expression == 2*tau
|
4951a26a0ed29f90546a953a14bd9e68fd93935f88138242aad4430816e09845 | from functools import wraps
from sympy.concrete.summations import Sum
from sympy.core.function import expand
from sympy.core.numbers import Integer
from sympy.matrices.dense import (Matrix, eye)
from sympy.tensor.indexed import Indexed
from sympy.combinatorics import Permutation
from sympy.core import S, Rational, Symbol, Basic, Add
from sympy.core.containers import Tuple
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.tensor.array import Array
from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, \
get_symmetric_group_sgs, TensorIndex, tensor_mul, TensAdd, \
riemann_cyclic_replace, riemann_cyclic, TensMul, tensor_heads, \
TensorManager, TensExpr, TensorHead, canon_bp, \
tensorhead, tensorsymmetry, TensorType, substitute_indices
from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy, ignore_warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.matrices import diag
def filter_warnings_decorator(f):
@wraps(f)
def wrapper():
with ignore_warnings(SymPyDeprecationWarning):
f()
return wrapper
def _is_equal(arg1, arg2):
if isinstance(arg1, TensExpr):
return arg1.equals(arg2)
elif isinstance(arg2, TensExpr):
return arg2.equals(arg1)
return arg1 == arg2
#################### Tests from tensor_can.py #######################
def test_canonicalize_no_slot_sym():
# A_d0 * B^d0; T_c = A^d0*B_d0
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, d0, d1 = tensor_indices('a,b,d0,d1', Lorentz)
A, B = tensor_heads('A,B', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(-d0)*B(d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0)*B(-L_0)'
# A^a * B^b; T_c = T
t = A(a)*B(b)
tc = t.canon_bp()
assert tc == t
# B^b * A^a
t1 = B(b)*A(a)
tc = t1.canon_bp()
assert str(tc) == 'A(a)*B(b)'
# A symmetric
# A^{b}_{d0}*A^{d0, a}; T_c = A^{a d0}*A{b}_{d0}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(b, -d0)*A(d0, a)
tc = t.canon_bp()
assert str(tc) == 'A(a, L_0)*A(b, -L_0)'
# A^{d1}_{d0}*B^d0*C_d1
# T_c = A^{d0 d1}*B_d0*C_d1
B, C = tensor_heads('B,C', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(d1, -d0)*B(d0)*C(-d1)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_0)*C(-L_1)'
# A without symmetry
# A^{d1}_{d0}*B^d0*C_d1 ord=[d0,-d0,d1,-d1]; g = [2,1,0,3,4,5]
# T_c = A^{d0 d1}*B_d1*C_d0; can = [0,2,3,1,4,5]
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, -d0)*B(d0)*C(-d1)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_1)*C(-L_0)'
# A, B without symmetry
# A^{d1}_{d0}*B_{d1}^{d0}
# T_c = A^{d0 d1}*B_{d0 d1}
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, -d0)*B(-d1, d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_0, -L_1)'
# A_{d0}^{d1}*B_{d1}^{d0}
# T_c = A^{d0 d1}*B_{d1 d0}
t = A(-d0, d1)*B(-d1, d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_1, -L_0)'
# A, B, C without symmetry
# A^{d1 d0}*B_{a d0}*C_{d1 b}
# T_c=A^{d0 d1}*B_{a d1}*C_{d0 b}
C = TensorHead('C', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-a, -L_1)*C(-L_0, -b)'
# A symmetric, B and C without symmetry
# A^{d1 d0}*B_{a d0}*C_{d1 b}
# T_c = A^{d0 d1}*B_{a d0}*C_{d1 b}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-a, -L_0)*C(-L_1, -b)'
# A and C symmetric, B without symmetry
# A^{d1 d0}*B_{a d0}*C_{d1 b} ord=[a,b,d0,-d0,d1,-d1]
# T_c = A^{d0 d1}*B_{a d0}*C_{b d1}
C = TensorHead('C', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-a, -L_0)*C(-b, -L_1)'
def test_canonicalize_no_dummies():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a, b, c, d', Lorentz)
# A commuting
# A^c A^b A^a
# T_c = A^a A^b A^c
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(c)*A(b)*A(a)
tc = t.canon_bp()
assert str(tc) == 'A(a)*A(b)*A(c)'
# A anticommuting
# A^c A^b A^a
# T_c = -A^a A^b A^c
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1), 1)
t = A(c)*A(b)*A(a)
tc = t.canon_bp()
assert str(tc) == '-A(a)*A(b)*A(c)'
# A commuting and symmetric
# A^{b,d}*A^{c,a}
# T_c = A^{a c}*A^{b d}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(b, d)*A(c, a)
tc = t.canon_bp()
assert str(tc) == 'A(a, c)*A(b, d)'
# A anticommuting and symmetric
# A^{b,d}*A^{c,a}
# T_c = -A^{a c}*A^{b d}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2), 1)
t = A(b, d)*A(c, a)
tc = t.canon_bp()
assert str(tc) == '-A(a, c)*A(b, d)'
# A^{c,a}*A^{b,d}
# T_c = A^{a c}*A^{b d}
t = A(c, a)*A(b, d)
tc = t.canon_bp()
assert str(tc) == 'A(a, c)*A(b, d)'
def test_tensorhead_construction_without_symmetry():
L = TensorIndexType('Lorentz')
A1 = TensorHead('A', [L, L])
A2 = TensorHead('A', [L, L], TensorSymmetry.no_symmetry(2))
assert A1 == A2
A3 = TensorHead('A', [L, L], TensorSymmetry.fully_symmetric(2)) # Symmetric
assert A1 != A3
def test_no_metric_symmetry():
# no metric symmetry; A no symmetry
# A^d1_d0 * A^d0_d1
# T_c = A^d0_d1 * A^d1_d0
Lorentz = TensorIndexType('Lorentz', dummy_name='L', metric_symmetry=0)
d0, d1, d2, d3 = tensor_indices('d:4', Lorentz)
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, -d0)*A(d0, -d1)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_0)'
# A^d1_d2 * A^d0_d3 * A^d2_d1 * A^d3_d0
# T_c = A^d0_d1 * A^d1_d0 * A^d2_d3 * A^d3_d2
t = A(d1, -d2)*A(d0, -d3)*A(d2, -d1)*A(d3, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_0)*A(L_2, -L_3)*A(L_3, -L_2)'
# A^d0_d2 * A^d1_d3 * A^d3_d0 * A^d2_d1
# T_c = A^d0_d1 * A^d1_d2 * A^d2_d3 * A^d3_d0
t = A(d0, -d1)*A(d1, -d2)*A(d2, -d3)*A(d3, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_2)*A(L_2, -L_3)*A(L_3, -L_0)'
def test_canonicalize1():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Lorentz)
# A_d0*A^d0; ord = [d0,-d0]
# T_c = A^d0*A_d0
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(-d0)*A(d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0)*A(-L_0)'
# A commuting
# A_d0*A_d1*A_d2*A^d2*A^d1*A^d0
# T_c = A^d0*A_d0*A^d1*A_d1*A^d2*A_d2
t = A(-d0)*A(-d1)*A(-d2)*A(d2)*A(d1)*A(d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0)*A(-L_0)*A(L_1)*A(-L_1)*A(L_2)*A(-L_2)'
# A anticommuting
# A_d0*A_d1*A_d2*A^d2*A^d1*A^d0
# T_c 0
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1), 1)
t = A(-d0)*A(-d1)*A(-d2)*A(d2)*A(d1)*A(d0)
tc = t.canon_bp()
assert tc == 0
# A commuting symmetric
# A^{d0 b}*A^a_d1*A^d1_d0
# T_c = A^{a d0}*A^{b d1}*A_{d0 d1}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d0, b)*A(a, -d1)*A(d1, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(a, L_0)*A(b, L_1)*A(-L_0, -L_1)'
# A, B commuting symmetric
# A^{d0 b}*A^d1_d0*B^a_d1
# T_c = A^{b d0}*A_d0^d1*B^a_d1
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d0, b)*A(d1, -d0)*B(a, -d1)
tc = t.canon_bp()
assert str(tc) == 'A(b, L_0)*A(-L_0, L_1)*B(a, -L_1)'
# A commuting symmetric
# A^{d1 d0 b}*A^{a}_{d1 d0}; ord=[a,b, d0,-d0,d1,-d1]
# T_c = A^{a d0 d1}*A^{b}_{d0 d1}
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3))
t = A(d1, d0, b)*A(a, -d1, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(a, L_0, L_1)*A(b, -L_0, -L_1)'
# A^{d3 d0 d2}*A^a0_{d1 d2}*A^d1_d3^a1*A^{a2 a3}_d0
# T_c = A^{a0 d0 d1}*A^a1_d0^d2*A^{a2 a3 d3}*A_{d1 d2 d3}
t = A(d3, d0, d2)*A(a0, -d1, -d2)*A(d1, -d3, a1)*A(a2, a3, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(a0, L_0, L_1)*A(a1, -L_0, L_2)*A(a2, a3, L_3)*A(-L_1, -L_2, -L_3)'
# A commuting symmetric, B antisymmetric
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# in this esxample and in the next three,
# renaming dummy indices and using symmetry of A,
# T = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3
# can = 0
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3))
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert tc == 0
# A anticommuting symmetric, B antisymmetric
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# T_c = A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3}
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3), 1)
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1, L_2)*A(-L_0, -L_1, L_3)*B(-L_2, -L_3)'
# A anticommuting symmetric, B antisymmetric commuting, antisymmetric metric
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# T_c = -A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3}
Spinor = TensorIndexType('Spinor', dummy_name='S', metric_symmetry=-1)
a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Spinor)
A = TensorHead('A', [Spinor]*3, TensorSymmetry.fully_symmetric(3), 1)
B = TensorHead('B', [Spinor]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert str(tc) == '-A(S_0, S_1, S_2)*A(-S_0, -S_1, S_3)*B(-S_2, -S_3)'
# A anticommuting symmetric, B antisymmetric anticommuting,
# no metric symmetry
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# T_c = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3
Mat = TensorIndexType('Mat', metric_symmetry=0, dummy_name='M')
a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Mat)
A = TensorHead('A', [Mat]*3, TensorSymmetry.fully_symmetric(3), 1)
B = TensorHead('B', [Mat]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert str(tc) == 'A(M_0, M_1, M_2)*A(-M_0, -M_1, -M_3)*B(-M_2, M_3)'
# Gamma anticommuting
# Gamma_{mu nu} * gamma^rho * Gamma^{nu mu alpha}
# T_c = -Gamma^{mu nu} * gamma^rho * Gamma_{alpha mu nu}
alpha, beta, gamma, mu, nu, rho = \
tensor_indices('alpha,beta,gamma,mu,nu,rho', Lorentz)
Gamma = TensorHead('Gamma', [Lorentz],
TensorSymmetry.fully_symmetric(1), 2)
Gamma2 = TensorHead('Gamma', [Lorentz]*2,
TensorSymmetry.fully_symmetric(-2), 2)
Gamma3 = TensorHead('Gamma', [Lorentz]*3,
TensorSymmetry.fully_symmetric(-3), 2)
t = Gamma2(-mu, -nu)*Gamma(rho)*Gamma3(nu, mu, alpha)
tc = t.canon_bp()
assert str(tc) == '-Gamma(L_0, L_1)*Gamma(rho)*Gamma(alpha, -L_0, -L_1)'
# Gamma_{mu nu} * Gamma^{gamma beta} * gamma_rho * Gamma^{nu mu alpha}
# T_c = Gamma^{mu nu} * Gamma^{beta gamma} * gamma_rho * Gamma^alpha_{mu nu}
t = Gamma2(mu, nu)*Gamma2(beta, gamma)*Gamma(-rho)*Gamma3(alpha, -mu, -nu)
tc = t.canon_bp()
assert str(tc) == 'Gamma(L_0, L_1)*Gamma(beta, gamma)*Gamma(-rho)*Gamma(alpha, -L_0, -L_1)'
# f^a_{b,c} antisymmetric in b,c; A_mu^a no symmetry
# f^c_{d a} * f_{c e b} * A_mu^d * A_nu^a * A^{nu e} * A^{mu b}
# g = [8,11,5, 9,13,7, 1,10, 3,4, 2,12, 0,6, 14,15]
# T_c = -f^{a b c} * f_a^{d e} * A^mu_b * A_{mu d} * A^nu_c * A_{nu e}
Flavor = TensorIndexType('Flavor', dummy_name='F')
a, b, c, d, e, ff = tensor_indices('a,b,c,d,e,f', Flavor)
mu, nu = tensor_indices('mu,nu', Lorentz)
f = TensorHead('f', [Flavor]*3, TensorSymmetry.direct_product(1, -2))
A = TensorHead('A', [Lorentz, Flavor], TensorSymmetry.no_symmetry(2))
t = f(c, -d, -a)*f(-c, -e, -b)*A(-mu, d)*A(-nu, a)*A(nu, e)*A(mu, b)
tc = t.canon_bp()
assert str(tc) == '-f(F_0, F_1, F_2)*f(-F_0, F_3, F_4)*A(L_0, -F_1)*A(-L_0, -F_3)*A(L_1, -F_2)*A(-L_1, -F_4)'
def test_bug_correction_tensor_indices():
# to make sure that tensor_indices does not return a list if creating
# only one index:
A = TensorIndexType("A")
i = tensor_indices('i', A)
assert not isinstance(i, (tuple, list))
assert isinstance(i, TensorIndex)
def test_riemann_invariants():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11 = \
tensor_indices('d0:12', Lorentz)
# R^{d0 d1}_{d1 d0}; ord = [d0,-d0,d1,-d1]
# T_c = -R^{d0 d1}_{d0 d1}
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(d0, d1, -d1, -d0)
tc = t.canon_bp()
assert str(tc) == '-R(L_0, L_1, -L_0, -L_1)'
# R_d11^d1_d0^d5 * R^{d6 d4 d0}_d5 * R_{d7 d2 d8 d9} *
# R_{d10 d3 d6 d4} * R^{d2 d7 d11}_d1 * R^{d8 d9 d3 d10}
# can = [0,2,4,6, 1,3,8,10, 5,7,12,14, 9,11,16,18, 13,15,20,22,
# 17,19,21<F10,23, 24,25]
# T_c = R^{d0 d1 d2 d3} * R_{d0 d1}^{d4 d5} * R_{d2 d3}^{d6 d7} *
# R_{d4 d5}^{d8 d9} * R_{d6 d7}^{d10 d11} * R_{d8 d9 d10 d11}
t = R(-d11,d1,-d0,d5)*R(d6,d4,d0,-d5)*R(-d7,-d2,-d8,-d9)* \
R(-d10,-d3,-d6,-d4)*R(d2,d7,d11,-d1)*R(d8,d9,d3,d10)
tc = t.canon_bp()
assert str(tc) == 'R(L_0, L_1, L_2, L_3)*R(-L_0, -L_1, L_4, L_5)*R(-L_2, -L_3, L_6, L_7)*R(-L_4, -L_5, L_8, L_9)*R(-L_6, -L_7, L_10, L_11)*R(-L_8, -L_9, -L_10, -L_11)'
def test_riemann_products():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
d0, d1, d2, d3, d4, d5, d6 = tensor_indices('d0:7', Lorentz)
a0, a1, a2, a3, a4, a5 = tensor_indices('a0:6', Lorentz)
a, b = tensor_indices('a,b', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
# R^{a b d0}_d0 = 0
t = R(a, b, d0, -d0)
tc = t.canon_bp()
assert tc == 0
# R^{d0 b a}_d0
# T_c = -R^{a d0 b}_d0
t = R(d0, b, a, -d0)
tc = t.canon_bp()
assert str(tc) == '-R(a, L_0, b, -L_0)'
# R^d1_d2^b_d0 * R^{d0 a}_d1^d2; ord=[a,b,d0,-d0,d1,-d1,d2,-d2]
# T_c = -R^{a d0 d1 d2}* R^b_{d0 d1 d2}
t = R(d1, -d2, b, -d0)*R(d0, a, -d1, d2)
tc = t.canon_bp()
assert str(tc) == '-R(a, L_0, L_1, L_2)*R(b, -L_0, -L_1, -L_2)'
# A symmetric commuting
# R^{d6 d5}_d2^d1 * R^{d4 d0 d2 d3} * A_{d6 d0} A_{d3 d1} * A_{d4 d5}
# g = [12,10,5,2, 8,0,4,6, 13,1, 7,3, 9,11,14,15]
# T_c = -R^{d0 d1 d2 d3} * R_d0^{d4 d5 d6} * A_{d1 d4}*A_{d2 d5}*A_{d3 d6}
V = TensorHead('V', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = R(d6, d5, -d2, d1)*R(d4, d0, d2, d3)*V(-d6, -d0)*V(-d3, -d1)*V(-d4, -d5)
tc = t.canon_bp()
assert str(tc) == '-R(L_0, L_1, L_2, L_3)*R(-L_0, L_4, L_5, L_6)*V(-L_1, -L_4)*V(-L_2, -L_5)*V(-L_3, -L_6)'
# R^{d2 a0 a2 d0} * R^d1_d2^{a1 a3} * R^{a4 a5}_{d0 d1}
# T_c = R^{a0 d0 a2 d1}*R^{a1 a3}_d0^d2*R^{a4 a5}_{d1 d2}
t = R(d2, a0, a2, d0)*R(d1, -d2, a1, a3)*R(a4, a5, -d0, -d1)
tc = t.canon_bp()
assert str(tc) == 'R(a0, L_0, a2, L_1)*R(a1, a3, -L_0, L_2)*R(a4, a5, -L_1, -L_2)'
######################################################################
def test_canonicalize2():
D = Symbol('D')
Eucl = TensorIndexType('Eucl', metric_symmetry=1, dim=D, dummy_name='E')
i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14 = \
tensor_indices('i0:15', Eucl)
A = TensorHead('A', [Eucl]*3, TensorSymmetry.fully_symmetric(-3))
# two examples from Cvitanovic, Group Theory page 59
# of identities for antisymmetric tensors of rank 3
# contracted according to the Kuratowski graph eq.(6.59)
t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i3,i7,i5)*A(-i2,-i5,i6)*A(-i4,-i6,i8)
t1 = t.canon_bp()
assert t1 == 0
# eq.(6.60)
#t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i2,i5,i6)*A(-i3,i7,i8)*A(-i6,-i7,i9)*
# A(-i8,i10,i13)*A(-i5,-i10,i11)*A(-i4,-i11,i12)*A(-i3,-i12,i14)
t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i2,i5,i6)*A(-i3,i7,i8)*A(-i6,-i7,i9)*\
A(-i8,i10,i13)*A(-i5,-i10,i11)*A(-i4,-i11,i12)*A(-i9,-i12,i14)
t1 = t.canon_bp()
assert t1 == 0
def test_canonicalize3():
D = Symbol('D')
Spinor = TensorIndexType('Spinor', dim=D, metric_symmetry=-1, dummy_name='S')
a0,a1,a2,a3,a4 = tensor_indices('a0:5', Spinor)
chi, psi = tensor_heads('chi,psi', [Spinor], TensorSymmetry.no_symmetry(1), 1)
t = chi(a1)*psi(a0)
t1 = t.canon_bp()
assert t1 == t
t = psi(a1)*chi(a0)
t1 = t.canon_bp()
assert t1 == -chi(a0)*psi(a1)
def test_TensorIndexType():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', metric_name='g', metric_symmetry=1,
dim=D, dummy_name='L')
m0, m1, m2, m3, m4 = tensor_indices('m0:5', Lorentz)
sym2 = TensorSymmetry.fully_symmetric(2)
sym2n = TensorSymmetry(*get_symmetric_group_sgs(2))
assert sym2 == sym2n
g = Lorentz.metric
assert str(g) == 'g(Lorentz,Lorentz)'
assert Lorentz.eps_dim == Lorentz.dim
TSpace = TensorIndexType('TSpace', dummy_name = 'TSpace')
i0, i1 = tensor_indices('i0 i1', TSpace)
g = TSpace.metric
A = TensorHead('A', [TSpace]*2, sym2)
assert str(A(i0,-i0).canon_bp()) == 'A(TSpace_0, -TSpace_0)'
def test_indices():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
assert a.tensor_index_type == Lorentz
assert a != -a
A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(a,b)*B(-b,c)
indices = t.get_indices()
L_0 = TensorIndex('L_0', Lorentz)
assert indices == [a, L_0, -L_0, c]
raises(ValueError, lambda: tensor_indices(3, Lorentz))
raises(ValueError, lambda: A(a,b,c))
A = TensorHead('A', [Lorentz, Lorentz])
assert A('a', 'b') == A(TensorIndex('a', Lorentz),
TensorIndex('b', Lorentz))
assert A('a', '-b') == A(TensorIndex('a', Lorentz),
TensorIndex('b', Lorentz, is_up=False))
assert A('a', TensorIndex('b', Lorentz)) == A(TensorIndex('a', Lorentz),
TensorIndex('b', Lorentz))
def test_TensorSymmetry():
assert TensorSymmetry.fully_symmetric(2) == \
TensorSymmetry(get_symmetric_group_sgs(2))
assert TensorSymmetry.fully_symmetric(-3) == \
TensorSymmetry(get_symmetric_group_sgs(3, True))
assert TensorSymmetry.direct_product(-4) == \
TensorSymmetry.fully_symmetric(-4)
assert TensorSymmetry.fully_symmetric(-1) == \
TensorSymmetry.fully_symmetric(1)
assert TensorSymmetry.direct_product(1, -1, 1) == \
TensorSymmetry.no_symmetry(3)
assert TensorSymmetry(get_symmetric_group_sgs(2)) == \
TensorSymmetry(*get_symmetric_group_sgs(2))
# TODO: add check for *get_symmetric_group_sgs(0)
sym = TensorSymmetry.fully_symmetric(-3)
assert sym.rank == 3
assert sym.base == Tuple(0, 1)
assert sym.generators == Tuple(Permutation(0, 1)(3, 4), Permutation(1, 2)(3, 4))
def test_TensExpr():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
g = Lorentz.metric
A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
raises(ValueError, lambda: g(c, d)/g(a, b))
raises(ValueError, lambda: S.One/g(a, b))
raises(ValueError, lambda: (A(c, d) + g(c, d))/g(a, b))
raises(ValueError, lambda: S.One/(A(c, d) + g(c, d)))
raises(ValueError, lambda: A(a, b) + A(a, c))
#t = A(a, b) + B(a, b) # assigned to t for below
#raises(NotImplementedError, lambda: TensExpr.__mul__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__add__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__radd__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__sub__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__rsub__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__truediv__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__rtruediv__(t, 'a'))
with ignore_warnings(SymPyDeprecationWarning):
# DO NOT REMOVE THIS AFTER DEPRECATION REMOVED:
raises(ValueError, lambda: A(a, b)**2)
raises(NotImplementedError, lambda: 2**A(a, b))
raises(NotImplementedError, lambda: abs(A(a, b)))
def test_TensorHead():
# simple example of algebraic expression
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
A = TensorHead('A', [Lorentz]*2)
assert A.name == 'A'
assert A.index_types == [Lorentz, Lorentz]
assert A.rank == 2
assert A.symmetry == TensorSymmetry.no_symmetry(2)
assert A.comm == 0
def test_add1():
assert TensAdd().args == ()
assert TensAdd().doit() == 0
# simple example of algebraic expression
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a,b,d0,d1,i,j,k = tensor_indices('a,b,d0,d1,i,j,k', Lorentz)
# A, B symmetric
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t1 = A(b, -d0)*B(d0, a)
assert TensAdd(t1).equals(t1)
t2a = B(d0, a) + A(d0, a)
t2 = A(b, -d0)*t2a
assert str(t2) == 'A(b, -L_0)*(A(L_0, a) + B(L_0, a))'
t2 = t2.expand()
assert str(t2) == 'A(b, -L_0)*A(L_0, a) + A(b, -L_0)*B(L_0, a)'
t2 = t2.canon_bp()
assert str(t2) == 'A(a, L_0)*A(b, -L_0) + A(b, L_0)*B(a, -L_0)'
t2b = t2 + t1
assert str(t2b) == 'A(a, L_0)*A(b, -L_0) + A(b, -L_0)*B(L_0, a) + A(b, L_0)*B(a, -L_0)'
t2b = t2b.canon_bp()
assert str(t2b) == 'A(a, L_0)*A(b, -L_0) + 2*A(b, L_0)*B(a, -L_0)'
p, q, r = tensor_heads('p,q,r', [Lorentz])
t = q(d0)*2
assert str(t) == '2*q(d0)'
t = 2*q(d0)
assert str(t) == '2*q(d0)'
t1 = p(d0) + 2*q(d0)
assert str(t1) == '2*q(d0) + p(d0)'
t2 = p(-d0) + 2*q(-d0)
assert str(t2) == '2*q(-d0) + p(-d0)'
t1 = p(d0)
t3 = t1*t2
assert str(t3) == 'p(L_0)*(2*q(-L_0) + p(-L_0))'
t3 = t3.expand()
assert str(t3) == 'p(L_0)*p(-L_0) + 2*p(L_0)*q(-L_0)'
t3 = t2*t1
t3 = t3.expand()
assert str(t3) == 'p(-L_0)*p(L_0) + 2*q(-L_0)*p(L_0)'
t3 = t3.canon_bp()
assert str(t3) == 'p(L_0)*p(-L_0) + 2*p(L_0)*q(-L_0)'
t1 = p(d0) + 2*q(d0)
t3 = t1*t2
t3 = t3.canon_bp()
assert str(t3) == 'p(L_0)*p(-L_0) + 4*p(L_0)*q(-L_0) + 4*q(L_0)*q(-L_0)'
t1 = p(d0) - 2*q(d0)
assert str(t1) == '-2*q(d0) + p(d0)'
t2 = p(-d0) + 2*q(-d0)
t3 = t1*t2
t3 = t3.canon_bp()
assert t3 == p(d0)*p(-d0) - 4*q(d0)*q(-d0)
t = p(i)*p(j)*(p(k) + q(k)) + p(i)*(p(j) + q(j))*(p(k) - 3*q(k))
t = t.canon_bp()
assert t == 2*p(i)*p(j)*p(k) - 2*p(i)*p(j)*q(k) + p(i)*p(k)*q(j) - 3*p(i)*q(j)*q(k)
t1 = (p(i) + q(i) + 2*r(i))*(p(j) - q(j))
t2 = (p(j) + q(j) + 2*r(j))*(p(i) - q(i))
t = t1 + t2
t = t.canon_bp()
assert t == 2*p(i)*p(j) + 2*p(i)*r(j) + 2*p(j)*r(i) - 2*q(i)*q(j) - 2*q(i)*r(j) - 2*q(j)*r(i)
t = p(i)*q(j)/2
assert 2*t == p(i)*q(j)
t = (p(i) + q(i))/2
assert 2*t == p(i) + q(i)
t = S.One - p(i)*p(-i)
t = t.canon_bp()
tz1 = t + p(-j)*p(j)
assert tz1 != 1
tz1 = tz1.canon_bp()
assert tz1.equals(1)
t = S.One + p(i)*p(-i)
assert (t - p(-j)*p(j)).canon_bp().equals(1)
t = A(a, b) + B(a, b)
assert t.rank == 2
t1 = t - A(a, b) - B(a, b)
assert t1 == 0
t = 1 - (A(a, -a) + B(a, -a))
t1 = 1 + (A(a, -a) + B(a, -a))
assert (t + t1).expand().equals(2)
t2 = 1 + A(a, -a)
assert t1 != t2
assert t2 != TensMul.from_data(0, [], [], [])
def test_special_eq_ne():
# test special equality cases:
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, d0, d1, i, j, k = tensor_indices('a,b,d0,d1,i,j,k', Lorentz)
# A, B symmetric
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
p, q, r = tensor_heads('p,q,r', [Lorentz])
t = 0*A(a, b)
assert _is_equal(t, 0)
assert _is_equal(t, S.Zero)
assert p(i) != A(a, b)
assert A(a, -a) != A(a, b)
assert 0*(A(a, b) + B(a, b)) == 0
assert 0*(A(a, b) + B(a, b)) is S.Zero
assert 3*(A(a, b) - A(a, b)) is S.Zero
assert p(i) + q(i) != A(a, b)
assert p(i) + q(i) != A(a, b) + B(a, b)
assert p(i) - p(i) == 0
assert p(i) - p(i) is S.Zero
assert _is_equal(A(a, b), A(b, a))
def test_add2():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
m, n, p, q = tensor_indices('m,n,p,q', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(-3))
t1 = 2*R(m, n, p, q) - R(m, q, n, p) + R(m, p, n, q)
t2 = t1*A(-n, -p, -q)
t2 = t2.canon_bp()
assert t2 == 0
t1 = Rational(2, 3)*R(m,n,p,q) - Rational(1, 3)*R(m,q,n,p) + Rational(1, 3)*R(m,p,n,q)
t2 = t1*A(-n, -p, -q)
t2 = t2.canon_bp()
assert t2 == 0
t = A(m, -m, n) + A(n, p, -p)
t = t.canon_bp()
assert t == 0
def test_add3():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
i0, i1 = tensor_indices('i0:2', Lorentz)
E, px, py, pz = symbols('E px py pz')
A = TensorHead('A', [Lorentz])
B = TensorHead('B', [Lorentz])
expr1 = A(i0)*A(-i0) - (E**2 - px**2 - py**2 - pz**2)
assert expr1.args == (-E**2, px**2, py**2, pz**2, A(i0)*A(-i0))
expr2 = E**2 - px**2 - py**2 - pz**2 - A(i0)*A(-i0)
assert expr2.args == (E**2, -px**2, -py**2, -pz**2, -A(i0)*A(-i0))
expr3 = A(i0)*A(-i0) - E**2 + px**2 + py**2 + pz**2
assert expr3.args == (-E**2, px**2, py**2, pz**2, A(i0)*A(-i0))
expr4 = B(i1)*B(-i1) + 2*E**2 - 2*px**2 - 2*py**2 - 2*pz**2 - A(i0)*A(-i0)
assert expr4.args == (2*E**2, -2*px**2, -2*py**2, -2*pz**2, B(i1)*B(-i1), -A(i0)*A(-i0))
def test_mul():
from sympy.abc import x
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
t = TensMul.from_data(S.One, [], [], [])
assert str(t) == '1'
A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = (1 + x)*A(a, b)
assert str(t) == '(x + 1)*A(a, b)'
assert t.index_types == [Lorentz, Lorentz]
assert t.rank == 2
assert t.dum == []
assert t.coeff == 1 + x
assert sorted(t.free) == [(a, 0), (b, 1)]
assert t.components == [A]
ts = A(a, b)
assert str(ts) == 'A(a, b)'
assert ts.index_types == [Lorentz, Lorentz]
assert ts.rank == 2
assert ts.dum == []
assert ts.coeff == 1
assert sorted(ts.free) == [(a, 0), (b, 1)]
assert ts.components == [A]
t = A(-b, a)*B(-a, c)*A(-c, d)
t1 = tensor_mul(*t.split())
assert t == t1
assert tensor_mul(*[]) == TensMul.from_data(S.One, [], [], [])
t = TensMul.from_data(1, [], [], [])
C = TensorHead('C', [])
assert str(C()) == 'C'
assert str(t) == '1'
assert t == 1
raises(ValueError, lambda: A(a, b)*A(a, c))
def test_substitute_indices():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
i, j, k, l, m, n, p, q = tensor_indices('i,j,k,l,m,n,p,q', Lorentz)
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
p = TensorHead('p', [Lorentz])
t = p(i)
t1 = t.substitute_indices((j, k))
assert t1 == t
t1 = t.substitute_indices((i, j))
assert t1 == p(j)
t1 = t.substitute_indices((i, -j))
assert t1 == p(-j)
t1 = t.substitute_indices((-i, j))
assert t1 == p(-j)
t1 = t.substitute_indices((-i, -j))
assert t1 == p(j)
t = A(m, n)
t1 = t.substitute_indices((m, i), (n, -i))
assert t1 == A(n, -n)
t1 = substitute_indices(t, (m, i), (n, -i))
assert t1 == A(n, -n)
t = A(i, k)*B(-k, -j)
t1 = t.substitute_indices((i, j), (j, k))
t1a = A(j, l)*B(-l, -k)
assert t1 == t1a
t1 = substitute_indices(t, (i, j), (j, k))
assert t1 == t1a
t = A(i, j) + B(i, j)
t1 = t.substitute_indices((j, -i))
t1a = A(i, -i) + B(i, -i)
assert t1 == t1a
t1 = substitute_indices(t, (j, -i))
assert t1 == t1a
def test_riemann_cyclic_replace():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
m0, m1, m2, m3 = tensor_indices('m:4', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(m0, m2, m1, m3)
t1 = riemann_cyclic_replace(t)
t1a = Rational(-1, 3)*R(m0, m3, m2, m1) + Rational(1, 3)*R(m0, m1, m2, m3) + Rational(2, 3)*R(m0, m2, m1, m3)
assert t1 == t1a
def test_riemann_cyclic():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
i, j, k, l, m, n, p, q = tensor_indices('i,j,k,l,m,n,p,q', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(i,j,k,l) + R(i,l,j,k) + R(i,k,l,j) - \
R(i,j,l,k) - R(i,l,k,j) - R(i,k,j,l)
t2 = t*R(-i,-j,-k,-l)
t3 = riemann_cyclic(t2)
assert t3 == 0
t = R(i,j,k,l)*(R(-i,-j,-k,-l) - 2*R(-i,-k,-j,-l))
t1 = riemann_cyclic(t)
assert t1 == 0
t = R(i,j,k,l)
t1 = riemann_cyclic(t)
assert t1 == Rational(-1, 3)*R(i, l, j, k) + Rational(1, 3)*R(i, k, j, l) + Rational(2, 3)*R(i, j, k, l)
t = R(i,j,k,l)*R(-k,-l,m,n)*(R(-m,-n,-i,-j) + 2*R(-m,-j,-n,-i))
t1 = riemann_cyclic(t)
assert t1 == 0
@XFAIL
def test_div():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
m0, m1, m2, m3 = tensor_indices('m0:4', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(m0,m1,-m1,m3)
t1 = t/S(4)
assert str(t1) == '(1/4)*R(m0, L_0, -L_0, m3)'
t = t.canon_bp()
assert not t1._is_canon_bp
t1 = t*4
assert t1._is_canon_bp
t1 = t1/4
assert t1._is_canon_bp
def test_contract_metric1():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
g = Lorentz.metric
p = TensorHead('p', [Lorentz])
t = g(a, b)*p(-b)
t1 = t.contract_metric(g)
assert t1 == p(a)
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
# case with g with all free indices
t1 = A(a,b)*B(-b,c)*g(d, e)
t2 = t1.contract_metric(g)
assert t1 == t2
# case of g(d, -d)
t1 = A(a,b)*B(-b,c)*g(-d, d)
t2 = t1.contract_metric(g)
assert t2 == D*A(a, d)*B(-d, c)
# g with one free index
t1 = A(a,b)*B(-b,-c)*g(c, d)
t2 = t1.contract_metric(g)
assert t2 == A(a, c)*B(-c, d)
# g with both indices contracted with another tensor
t1 = A(a,b)*B(-b,-c)*g(c, -a)
t2 = t1.contract_metric(g)
assert _is_equal(t2, A(a, b)*B(-b, -a))
t1 = A(a,b)*B(-b,-c)*g(c, d)*g(-a, -d)
t2 = t1.contract_metric(g)
assert _is_equal(t2, A(a,b)*B(-b,-a))
t1 = A(a,b)*g(-a,-b)
t2 = t1.contract_metric(g)
assert _is_equal(t2, A(a, -a))
assert not t2.free
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
g = Lorentz.metric
assert _is_equal(g(a, -a).contract_metric(g), Lorentz.dim) # no dim
def test_contract_metric2():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e, L_0 = tensor_indices('a,b,c,d,e,L_0', Lorentz)
g = Lorentz.metric
p, q = tensor_heads('p,q', [Lorentz])
t1 = g(a,b)*p(c)*p(-c)
t2 = 3*g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
assert t == 3*D*p(a)*p(-a)*q(b)*q(-b)
t1 = g(a,b)*p(c)*p(-c)
t2 = 3*q(-a)*q(-b)
t = t1*t2
t = t.contract_metric(g)
t = t.canon_bp()
assert t == 3*p(a)*p(-a)*q(b)*q(-b)
t1 = 2*g(a,b)*p(c)*p(-c)
t2 = - 3*g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
t = 6*g(a,b)*g(-a,-b)*p(c)*p(-c)*q(d)*q(-d)
t = t.contract_metric(g)
t1 = 2*g(a,b)*p(c)*p(-c)
t2 = q(-a)*q(-b) + 3*g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
assert t == (2 + 6*D)*p(a)*p(-a)*q(b)*q(-b)
t1 = p(a)*p(b) + p(a)*q(b) + 2*g(a,b)*p(c)*p(-c)
t2 = q(-a)*q(-b) - g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
t1 = (1 - 2*D)*p(a)*p(-a)*q(b)*q(-b) + p(a)*q(-a)*p(b)*q(-b)
assert canon_bp(t - t1) == 0
t = g(a,b)*g(c,d)*g(-b,-c)
t1 = t.contract_metric(g)
assert t1 == g(a, d)
t1 = g(a,b)*g(c,d) + g(a,c)*g(b,d) + g(a,d)*g(b,c)
t2 = t1.substitute_indices((a,-a),(b,-b),(c,-c),(d,-d))
t = t1*t2
t = t.contract_metric(g)
assert t.equals(3*D**2 + 6*D)
t = 2*p(a)*g(b,-b)
t1 = t.contract_metric(g)
assert t1.equals(2*D*p(a))
t = 2*p(a)*g(b,-a)
t1 = t.contract_metric(g)
assert t1 == 2*p(b)
M = Symbol('M')
t = (p(a)*p(b) + g(a, b)*M**2)*g(-a, -b) - D*M**2
t1 = t.contract_metric(g)
assert t1 == p(a)*p(-a)
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(a, b)*p(L_0)*g(-a, -b)
t1 = t.contract_metric(g)
assert str(t1) == 'A(L_1, -L_1)*p(L_0)' or str(t1) == 'A(-L_1, L_1)*p(L_0)'
def test_metric_contract3():
D = Symbol('D')
Spinor = TensorIndexType('Spinor', dim=D, metric_symmetry=-1, dummy_name='S')
a0, a1, a2, a3, a4 = tensor_indices('a0:5', Spinor)
C = Spinor.metric
chi, psi = tensor_heads('chi,psi', [Spinor], TensorSymmetry.no_symmetry(1), 1)
B = TensorHead('B', [Spinor]*2, TensorSymmetry.no_symmetry(2))
t = C(a0,-a0)
t1 = t.contract_metric(C)
assert t1.equals(-D)
t = C(-a0,a0)
t1 = t.contract_metric(C)
assert t1.equals(D)
t = C(a0,a1)*C(-a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(D)
t = C(a1,a0)*C(-a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(-D)
t = C(-a0,a1)*C(a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(-D)
t = C(a1,-a0)*C(a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(D)
t = C(a0,a1)*B(-a1,-a0)
t1 = t.contract_metric(C)
t1 = t1.canon_bp()
assert _is_equal(t1, B(a0,-a0))
t = C(a1,a0)*B(-a1,-a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(a0,-a0))
t = C(a0,-a1)*B(a1,-a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(a0,-a0))
t = C(-a0,a1)*B(-a1,a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(a0,-a0))
t = C(-a0,-a1)*B(a1,a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, B(a0,-a0))
t = C(-a1, a0)*B(a1,-a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, B(a0,-a0))
t = C(a0,a1)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, psi(a0))
t = C(a1,a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -psi(a0))
t = C(a0,a1)*chi(-a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -chi(a1)*psi(-a1))
t = C(a1,a0)*chi(-a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, chi(a1)*psi(-a1))
t = C(-a1,a0)*chi(-a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, chi(-a1)*psi(a1))
t = C(a0,-a1)*chi(-a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -chi(-a1)*psi(a1))
t = C(-a0,-a1)*chi(a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, chi(-a1)*psi(a1))
t = C(-a1,-a0)*chi(a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -chi(-a1)*psi(a1))
t = C(-a1,-a0)*B(a0,a2)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(-a1,a2)*psi(a1))
t = C(a1,a0)*B(-a2,-a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, B(-a2,a1)*psi(-a1))
def test_epsilon():
Lorentz = TensorIndexType('Lorentz', dim=4, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
epsilon = Lorentz.epsilon
p, q, r, s = tensor_heads('p,q,r,s', [Lorentz])
t = epsilon(b,a,c,d)
t1 = t.canon_bp()
assert t1 == -epsilon(a,b,c,d)
t = epsilon(c,b,d,a)
t1 = t.canon_bp()
assert t1 == epsilon(a,b,c,d)
t = epsilon(c,a,d,b)
t1 = t.canon_bp()
assert t1 == -epsilon(a,b,c,d)
t = epsilon(a,b,c,d)*p(-a)*q(-b)
t1 = t.canon_bp()
assert t1 == epsilon(c,d,a,b)*p(-a)*q(-b)
t = epsilon(c,b,d,a)*p(-a)*q(-b)
t1 = t.canon_bp()
assert t1 == epsilon(c,d,a,b)*p(-a)*q(-b)
t = epsilon(c,a,d,b)*p(-a)*q(-b)
t1 = t.canon_bp()
assert t1 == -epsilon(c,d,a,b)*p(-a)*q(-b)
t = epsilon(c,a,d,b)*p(-a)*p(-b)
t1 = t.canon_bp()
assert t1 == 0
t = epsilon(c,a,d,b)*p(-a)*q(-b) + epsilon(a,b,c,d)*p(-b)*q(-a)
t1 = t.canon_bp()
assert t1 == -2*epsilon(c,d,a,b)*p(-a)*q(-b)
# Test that epsilon can be create with a SymPy integer:
Lorentz = TensorIndexType('Lorentz', dim=Integer(4), dummy_name='L')
epsilon = Lorentz.epsilon
assert isinstance(epsilon, TensorHead)
def test_contract_delta1():
# see Group Theory by Cvitanovic page 9
n = Symbol('n')
Color = TensorIndexType('Color', dim=n, dummy_name='C')
a, b, c, d, e, f = tensor_indices('a,b,c,d,e,f', Color)
delta = Color.delta
def idn(a, b, d, c):
assert a.is_up and d.is_up
assert not (b.is_up or c.is_up)
return delta(a,c)*delta(d,b)
def T(a, b, d, c):
assert a.is_up and d.is_up
assert not (b.is_up or c.is_up)
return delta(a,b)*delta(d,c)
def P1(a, b, c, d):
return idn(a,b,c,d) - 1/n*T(a,b,c,d)
def P2(a, b, c, d):
return 1/n*T(a,b,c,d)
t = P1(a, -b, e, -f)*P1(f, -e, d, -c)
t1 = t.contract_delta(delta)
assert canon_bp(t1 - P1(a, -b, d, -c)) == 0
t = P2(a, -b, e, -f)*P2(f, -e, d, -c)
t1 = t.contract_delta(delta)
assert t1 == P2(a, -b, d, -c)
t = P1(a, -b, e, -f)*P2(f, -e, d, -c)
t1 = t.contract_delta(delta)
assert t1 == 0
t = P1(a, -b, b, -a)
t1 = t.contract_delta(delta)
assert t1.equals(n**2 - 1)
@filter_warnings_decorator
def test_fun():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
g = Lorentz.metric
p, q = tensor_heads('p q', [Lorentz])
t = q(c)*p(a)*q(b) + g(a,b)*g(c,d)*q(-d)
assert t(a,b,c) == t
assert canon_bp(t - t(b,a,c) - q(c)*p(a)*q(b) + q(c)*p(b)*q(a)) == 0
assert t(b,c,d) == q(d)*p(b)*q(c) + g(b,c)*g(d,e)*q(-e)
t1 = t.substitute_indices((a,b),(b,a))
assert canon_bp(t1 - q(c)*p(b)*q(a) - g(a,b)*g(c,d)*q(-d)) == 0
# check that g_{a b; c} = 0
# example taken from L. Brewin
# "A brief introduction to Cadabra" arxiv:0903.2085
# dg_{a b c} = \partial_{a} g_{b c} is symmetric in b, c
dg = TensorHead('dg', [Lorentz]*3, TensorSymmetry.direct_product(1, 2))
# gamma^a_{b c} is the Christoffel symbol
gamma = S.Half*g(a,d)*(dg(-b,-d,-c) + dg(-c,-b,-d) - dg(-d,-b,-c))
# t = g_{a b; c}
t = dg(-c,-a,-b) - g(-a,-d)*gamma(d,-b,-c) - g(-b,-d)*gamma(d,-a,-c)
t = t.contract_metric(g)
assert t == 0
t = q(c)*p(a)*q(b)
assert t(b,c,d) == q(d)*p(b)*q(c)
def test_TensorManager():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
LorentzH = TensorIndexType('LorentzH', dummy_name='LH')
i, j = tensor_indices('i,j', Lorentz)
ih, jh = tensor_indices('ih,jh', LorentzH)
p, q = tensor_heads('p q', [Lorentz])
ph, qh = tensor_heads('ph qh', [LorentzH])
Gsymbol = Symbol('Gsymbol')
GHsymbol = Symbol('GHsymbol')
TensorManager.set_comm(Gsymbol, GHsymbol, 0)
G = TensorHead('G', [Lorentz], TensorSymmetry.no_symmetry(1), Gsymbol)
assert TensorManager._comm_i2symbol[G.comm] == Gsymbol
GH = TensorHead('GH', [LorentzH], TensorSymmetry.no_symmetry(1), GHsymbol)
ps = G(i)*p(-i)
psh = GH(ih)*ph(-ih)
t = ps + psh
t1 = t*t
assert canon_bp(t1 - ps*ps - 2*ps*psh - psh*psh) == 0
qs = G(i)*q(-i)
qsh = GH(ih)*qh(-ih)
assert _is_equal(ps*qsh, qsh*ps)
assert not _is_equal(ps*qs, qs*ps)
n = TensorManager.comm_symbols2i(Gsymbol)
assert TensorManager.comm_i2symbol(n) == Gsymbol
assert GHsymbol in TensorManager._comm_symbols2i
raises(ValueError, lambda: TensorManager.set_comm(GHsymbol, 1, 2))
TensorManager.set_comms((Gsymbol,GHsymbol,0),(Gsymbol,1,1))
assert TensorManager.get_comm(n, 1) == TensorManager.get_comm(1, n) == 1
TensorManager.clear()
assert TensorManager.comm == [{0:0, 1:0, 2:0}, {0:0, 1:1, 2:None}, {0:0, 1:None}]
assert GHsymbol not in TensorManager._comm_symbols2i
nh = TensorManager.comm_symbols2i(GHsymbol)
assert TensorManager.comm_i2symbol(nh) == GHsymbol
assert GHsymbol in TensorManager._comm_symbols2i
def test_hash():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
g = Lorentz.metric
p, q = tensor_heads('p q', [Lorentz])
p_type = p.args[1]
t1 = p(a)*q(b)
t2 = p(a)*p(b)
assert hash(t1) != hash(t2)
t3 = p(a)*p(b) + g(a,b)
t4 = p(a)*p(b) - g(a,b)
assert hash(t3) != hash(t4)
assert a.func(*a.args) == a
assert Lorentz.func(*Lorentz.args) == Lorentz
assert g.func(*g.args) == g
assert p.func(*p.args) == p
assert p_type.func(*p_type.args) == p_type
assert p(a).func(*(p(a)).args) == p(a)
assert t1.func(*t1.args) == t1
assert t2.func(*t2.args) == t2
assert t3.func(*t3.args) == t3
assert t4.func(*t4.args) == t4
assert hash(a.func(*a.args)) == hash(a)
assert hash(Lorentz.func(*Lorentz.args)) == hash(Lorentz)
assert hash(g.func(*g.args)) == hash(g)
assert hash(p.func(*p.args)) == hash(p)
assert hash(p_type.func(*p_type.args)) == hash(p_type)
assert hash(p(a).func(*(p(a)).args)) == hash(p(a))
assert hash(t1.func(*t1.args)) == hash(t1)
assert hash(t2.func(*t2.args)) == hash(t2)
assert hash(t3.func(*t3.args)) == hash(t3)
assert hash(t4.func(*t4.args)) == hash(t4)
def check_all(obj):
return all([isinstance(_, Basic) for _ in obj.args])
assert check_all(a)
assert check_all(Lorentz)
assert check_all(g)
assert check_all(p)
assert check_all(p_type)
assert check_all(p(a))
assert check_all(t1)
assert check_all(t2)
assert check_all(t3)
assert check_all(t4)
tsymmetry = TensorSymmetry.direct_product(-2, 1, 3)
assert tsymmetry.func(*tsymmetry.args) == tsymmetry
assert hash(tsymmetry.func(*tsymmetry.args)) == hash(tsymmetry)
assert check_all(tsymmetry)
### TEST VALUED TENSORS ###
def _get_valued_base_test_variables():
minkowski = Matrix((
(1, 0, 0, 0),
(0, -1, 0, 0),
(0, 0, -1, 0),
(0, 0, 0, -1),
))
Lorentz = TensorIndexType('Lorentz', dim=4)
Lorentz.data = minkowski
i0, i1, i2, i3, i4 = tensor_indices('i0:5', Lorentz)
E, px, py, pz = symbols('E px py pz')
A = TensorHead('A', [Lorentz])
A.data = [E, px, py, pz]
B = TensorHead('B', [Lorentz], TensorSymmetry.no_symmetry(1), 'Gcomm')
B.data = range(4)
AB = TensorHead("AB", [Lorentz]*2)
AB.data = minkowski
ba_matrix = Matrix((
(1, 2, 3, 4),
(5, 6, 7, 8),
(9, 0, -1, -2),
(-3, -4, -5, -6),
))
BA = TensorHead("BA", [Lorentz]*2)
BA.data = ba_matrix
# Let's test the diagonal metric, with inverted Minkowski metric:
LorentzD = TensorIndexType('LorentzD')
LorentzD.data = [-1, 1, 1, 1]
mu0, mu1, mu2 = tensor_indices('mu0:3', LorentzD)
C = TensorHead('C', [LorentzD])
C.data = [E, px, py, pz]
### non-diagonal metric ###
ndm_matrix = (
(1, 1, 0,),
(1, 0, 1),
(0, 1, 0,),
)
ndm = TensorIndexType("ndm")
ndm.data = ndm_matrix
n0, n1, n2 = tensor_indices('n0:3', ndm)
NA = TensorHead('NA', [ndm])
NA.data = range(10, 13)
NB = TensorHead('NB', [ndm]*2)
NB.data = [[i+j for j in range(10, 13)] for i in range(10, 13)]
NC = TensorHead('NC', [ndm]*3)
NC.data = [[[i+j+k for k in range(4, 7)] for j in range(1, 4)] for i in range(2, 5)]
return (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4)
@filter_warnings_decorator
def test_valued_tensor_iter():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
list_BA = [Array([1, 2, 3, 4]), Array([5, 6, 7, 8]), Array([9, 0, -1, -2]), Array([-3, -4, -5, -6])]
# iteration on VTensorHead
assert list(A) == [E, px, py, pz]
assert list(ba_matrix) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, -1, -2, -3, -4, -5, -6]
assert list(BA) == list_BA
# iteration on VTensMul
assert list(A(i1)) == [E, px, py, pz]
assert list(BA(i1, i2)) == list_BA
assert list(3 * BA(i1, i2)) == [3 * i for i in list_BA]
assert list(-5 * BA(i1, i2)) == [-5 * i for i in list_BA]
# iteration on VTensAdd
# A(i1) + A(i1)
assert list(A(i1) + A(i1)) == [2*E, 2*px, 2*py, 2*pz]
assert BA(i1, i2) - BA(i1, i2) == 0
assert list(BA(i1, i2) - 2 * BA(i1, i2)) == [-i for i in list_BA]
@filter_warnings_decorator
def test_valued_tensor_covariant_contravariant_elements():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert A(-i0)[0] == A(i0)[0]
assert A(-i0)[1] == -A(i0)[1]
assert AB(i0, i1)[1, 1] == -1
assert AB(i0, -i1)[1, 1] == 1
assert AB(-i0, -i1)[1, 1] == -1
assert AB(-i0, i1)[1, 1] == 1
@filter_warnings_decorator
def test_valued_tensor_get_matrix():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
matab = AB(i0, i1).get_matrix()
assert matab == Matrix([
[1, 0, 0, 0],
[0, -1, 0, 0],
[0, 0, -1, 0],
[0, 0, 0, -1],
])
# when alternating contravariant/covariant with [1, -1, -1, -1] metric
# it becomes the identity matrix:
assert AB(i0, -i1).get_matrix() == eye(4)
# covariant and contravariant forms:
assert A(i0).get_matrix() == Matrix([E, px, py, pz])
assert A(-i0).get_matrix() == Matrix([E, -px, -py, -pz])
@filter_warnings_decorator
def test_valued_tensor_contraction():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert (A(i0) * A(-i0)).data == E ** 2 - px ** 2 - py ** 2 - pz ** 2
assert (A(i0) * A(-i0)).data == A ** 2
assert (A(i0) * A(-i0)).data == A(i0) ** 2
assert (A(i0) * B(-i0)).data == -px - 2 * py - 3 * pz
for i in range(4):
for j in range(4):
assert (A(i0) * B(-i1))[i, j] == [E, px, py, pz][i] * [0, -1, -2, -3][j]
# test contraction on the alternative Minkowski metric: [-1, 1, 1, 1]
assert (C(mu0) * C(-mu0)).data == -E ** 2 + px ** 2 + py ** 2 + pz ** 2
contrexp = A(i0) * AB(i1, -i0)
assert A(i0).rank == 1
assert AB(i1, -i0).rank == 2
assert contrexp.rank == 1
for i in range(4):
assert contrexp[i] == [E, px, py, pz][i]
@filter_warnings_decorator
def test_valued_tensor_self_contraction():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert AB(i0, -i0).data == 4
assert BA(i0, -i0).data == 2
@filter_warnings_decorator
def test_valued_tensor_pow():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert C**2 == -E**2 + px**2 + py**2 + pz**2
assert C**1 == sqrt(-E**2 + px**2 + py**2 + pz**2)
assert C(mu0)**2 == C**2
assert C(mu0)**1 == C**1
@filter_warnings_decorator
def test_valued_tensor_expressions():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
x1, x2, x3 = symbols('x1:4')
# test coefficient in contraction:
rank2coeff = x1 * A(i3) * B(i2)
assert rank2coeff[1, 1] == x1 * px
assert rank2coeff[3, 3] == 3 * pz * x1
coeff_expr = ((x1 * A(i4)) * (B(-i4) / x2)).data
assert coeff_expr.expand() == -px*x1/x2 - 2*py*x1/x2 - 3*pz*x1/x2
add_expr = A(i0) + B(i0)
assert add_expr[0] == E
assert add_expr[1] == px + 1
assert add_expr[2] == py + 2
assert add_expr[3] == pz + 3
sub_expr = A(i0) - B(i0)
assert sub_expr[0] == E
assert sub_expr[1] == px - 1
assert sub_expr[2] == py - 2
assert sub_expr[3] == pz - 3
assert (add_expr * B(-i0)).data == -px - 2*py - 3*pz - 14
expr1 = x1*A(i0) + x2*B(i0)
expr2 = expr1 * B(i1) * (-4)
expr3 = expr2 + 3*x3*AB(i0, i1)
expr4 = expr3 / 2
assert expr4 * 2 == expr3
expr5 = (expr4 * BA(-i1, -i0))
assert expr5.data.expand() == 28*E*x1 + 12*px*x1 + 20*py*x1 + 28*pz*x1 + 136*x2 + 3*x3
@filter_warnings_decorator
def test_valued_tensor_add_scalar():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
# one scalar summand after the contracted tensor
expr1 = A(i0)*A(-i0) - (E**2 - px**2 - py**2 - pz**2)
assert expr1.data == 0
# multiple scalar summands in front of the contracted tensor
expr2 = E**2 - px**2 - py**2 - pz**2 - A(i0)*A(-i0)
assert expr2.data == 0
# multiple scalar summands after the contracted tensor
expr3 = A(i0)*A(-i0) - E**2 + px**2 + py**2 + pz**2
assert expr3.data == 0
# multiple scalar summands and multiple tensors
expr4 = C(mu0)*C(-mu0) + 2*E**2 - 2*px**2 - 2*py**2 - 2*pz**2 - A(i0)*A(-i0)
assert expr4.data == 0
@filter_warnings_decorator
def test_noncommuting_components():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
euclid = TensorIndexType('Euclidean')
euclid.data = [1, 1]
i1, i2, i3 = tensor_indices('i1:4', euclid)
a, b, c, d = symbols('a b c d', commutative=False)
V1 = TensorHead('V1', [euclid]*2)
V1.data = [[a, b], (c, d)]
V2 = TensorHead('V2', [euclid]*2)
V2.data = [[a, c], [b, d]]
vtp = V1(i1, i2) * V2(-i2, -i1)
assert vtp.data == a**2 + b**2 + c**2 + d**2
assert vtp.data != a**2 + 2*b*c + d**2
vtp2 = V1(i1, i2)*V1(-i2, -i1)
assert vtp2.data == a**2 + b*c + c*b + d**2
assert vtp2.data != a**2 + 2*b*c + d**2
Vc = (b * V1(i1, -i1)).data
assert Vc.expand() == b * a + b * d
@filter_warnings_decorator
def test_valued_non_diagonal_metric():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
mmatrix = Matrix(ndm_matrix)
assert (NA(n0)*NA(-n0)).data == (NA(n0).get_matrix().T * mmatrix * NA(n0).get_matrix())[0, 0]
@filter_warnings_decorator
def test_valued_assign_numpy_ndarray():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
# this is needed to make sure that a numpy.ndarray can be assigned to a
# tensor.
arr = [E+1, px-1, py, pz]
A.data = Array(arr)
for i in range(4):
assert A(i0).data[i] == arr[i]
qx, qy, qz = symbols('qx qy qz')
A(-i0).data = Array([E, qx, qy, qz])
for i in range(4):
assert A(i0).data[i] == [E, -qx, -qy, -qz][i]
assert A.data[i] == [E, -qx, -qy, -qz][i]
# test on multi-indexed tensors.
random_4x4_data = [[(i**3-3*i**2)%(j+7) for i in range(4)] for j in range(4)]
AB(-i0, -i1).data = random_4x4_data
for i in range(4):
for j in range(4):
assert AB(i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)*(-1 if j else 1)
assert AB(-i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if j else 1)
assert AB(i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)
assert AB(-i0, -i1).data[i, j] == random_4x4_data[i][j]
AB(-i0, i1).data = random_4x4_data
for i in range(4):
for j in range(4):
assert AB(i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)
assert AB(-i0, i1).data[i, j] == random_4x4_data[i][j]
assert AB(i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)*(-1 if j else 1)
assert AB(-i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if j else 1)
@filter_warnings_decorator
def test_valued_metric_inverse():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
# let's assign some fancy matrix, just to verify it:
# (this has no physical sense, it's just testing sympy);
# it is symmetrical:
md = [[2, 2, 2, 1], [2, 3, 1, 0], [2, 1, 2, 3], [1, 0, 3, 2]]
Lorentz.data = md
m = Matrix(md)
metric = Lorentz.metric
minv = m.inv()
meye = eye(4)
# the Kronecker Delta:
KD = Lorentz.get_kronecker_delta()
for i in range(4):
for j in range(4):
assert metric(i0, i1).data[i, j] == m[i, j]
assert metric(-i0, -i1).data[i, j] == minv[i, j]
assert metric(i0, -i1).data[i, j] == meye[i, j]
assert metric(-i0, i1).data[i, j] == meye[i, j]
assert metric(i0, i1)[i, j] == m[i, j]
assert metric(-i0, -i1)[i, j] == minv[i, j]
assert metric(i0, -i1)[i, j] == meye[i, j]
assert metric(-i0, i1)[i, j] == meye[i, j]
assert KD(i0, -i1)[i, j] == meye[i, j]
@filter_warnings_decorator
def test_valued_canon_bp_swapaxes():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
e1 = A(i1)*A(i0)
e2 = e1.canon_bp()
assert e2 == A(i0)*A(i1)
for i in range(4):
for j in range(4):
assert e1[i, j] == e2[j, i]
o1 = B(i2)*A(i1)*B(i0)
o2 = o1.canon_bp()
for i in range(4):
for j in range(4):
for k in range(4):
assert o1[i, j, k] == o2[j, i, k]
@filter_warnings_decorator
def test_valued_components_with_wrong_symmetry():
IT = TensorIndexType('IT', dim=3)
i0, i1, i2, i3 = tensor_indices('i0:4', IT)
IT.data = [1, 1, 1]
A_nosym = TensorHead('A', [IT]*2)
A_sym = TensorHead('A', [IT]*2, TensorSymmetry.fully_symmetric(2))
A_antisym = TensorHead('A', [IT]*2, TensorSymmetry.fully_symmetric(-2))
mat_nosym = Matrix([[1,2,3],[4,5,6],[7,8,9]])
mat_sym = mat_nosym + mat_nosym.T
mat_antisym = mat_nosym - mat_nosym.T
A_nosym.data = mat_nosym
A_nosym.data = mat_sym
A_nosym.data = mat_antisym
def assign(A, dat):
A.data = dat
A_sym.data = mat_sym
raises(ValueError, lambda: assign(A_sym, mat_nosym))
raises(ValueError, lambda: assign(A_sym, mat_antisym))
A_antisym.data = mat_antisym
raises(ValueError, lambda: assign(A_antisym, mat_sym))
raises(ValueError, lambda: assign(A_antisym, mat_nosym))
A_sym.data = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
A_antisym.data = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
@filter_warnings_decorator
def test_issue_10972_TensMul_data():
Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='i', dim=2)
Lorentz.data = [-1, 1]
mu, nu, alpha, beta = tensor_indices('\\mu, \\nu, \\alpha, \\beta',
Lorentz)
u = TensorHead('u', [Lorentz])
u.data = [1, 0]
F = TensorHead('F', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
F.data = [[0, 1],
[-1, 0]]
mul_1 = F(mu, alpha) * u(-alpha) * F(nu, beta) * u(-beta)
assert (mul_1.data == Array([[0, 0], [0, 1]]))
mul_2 = F(mu, alpha) * F(nu, beta) * u(-alpha) * u(-beta)
assert (mul_2.data == mul_1.data)
assert ((mul_1 + mul_1).data == 2 * mul_1.data)
@filter_warnings_decorator
def test_TensMul_data():
Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='L', dim=4)
Lorentz.data = [-1, 1, 1, 1]
mu, nu, alpha, beta = tensor_indices('\\mu, \\nu, \\alpha, \\beta',
Lorentz)
u = TensorHead('u', [Lorentz])
u.data = [1, 0, 0, 0]
F = TensorHead('F', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
Ex, Ey, Ez, Bx, By, Bz = symbols('E_x E_y E_z B_x B_y B_z')
F.data = [
[0, Ex, Ey, Ez],
[-Ex, 0, Bz, -By],
[-Ey, -Bz, 0, Bx],
[-Ez, By, -Bx, 0]]
E = F(mu, nu) * u(-nu)
assert ((E(mu) * E(nu)).data ==
Array([[0, 0, 0, 0],
[0, Ex ** 2, Ex * Ey, Ex * Ez],
[0, Ex * Ey, Ey ** 2, Ey * Ez],
[0, Ex * Ez, Ey * Ez, Ez ** 2]])
)
assert ((E(mu) * E(nu)).canon_bp().data == (E(mu) * E(nu)).data)
assert ((F(mu, alpha) * F(beta, nu) * u(-alpha) * u(-beta)).data ==
- (E(mu) * E(nu)).data
)
assert ((F(alpha, mu) * F(beta, nu) * u(-alpha) * u(-beta)).data ==
(E(mu) * E(nu)).data
)
g = TensorHead('g', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
g.data = Lorentz.data
# tensor 'perp' is orthogonal to vector 'u'
perp = u(mu) * u(nu) + g(mu, nu)
mul_1 = u(-mu) * perp(mu, nu)
assert (mul_1.data == Array([0, 0, 0, 0]))
mul_2 = u(-mu) * perp(mu, alpha) * perp(nu, beta)
assert (mul_2.data == Array.zeros(4, 4, 4))
Fperp = perp(mu, alpha) * perp(nu, beta) * F(-alpha, -beta)
assert (Fperp.data[0, :] == Array([0, 0, 0, 0]))
assert (Fperp.data[:, 0] == Array([0, 0, 0, 0]))
mul_3 = u(-mu) * Fperp(mu, nu)
assert (mul_3.data == Array([0, 0, 0, 0]))
@filter_warnings_decorator
def test_issue_11020_TensAdd_data():
Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='i', dim=2)
Lorentz.data = [-1, 1]
a, b, c, d = tensor_indices('a, b, c, d', Lorentz)
i0, i1 = tensor_indices('i_0:2', Lorentz)
# metric tensor
g = TensorHead('g', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
g.data = Lorentz.data
u = TensorHead('u', [Lorentz])
u.data = [1, 0]
add_1 = g(b, c) * g(d, i0) * u(-i0) - g(b, c) * u(d)
assert (add_1.data == Array.zeros(2, 2, 2))
# Now let us replace index `d` with `a`:
add_2 = g(b, c) * g(a, i0) * u(-i0) - g(b, c) * u(a)
assert (add_2.data == Array.zeros(2, 2, 2))
# some more tests
# perp is tensor orthogonal to u^\mu
perp = u(a) * u(b) + g(a, b)
mul_1 = u(-a) * perp(a, b)
assert (mul_1.data == Array([0, 0]))
mul_2 = u(-c) * perp(c, a) * perp(d, b)
assert (mul_2.data == Array.zeros(2, 2, 2))
def test_index_iteration():
L = TensorIndexType("Lorentz", dummy_name="L")
i0, i1, i2, i3, i4 = tensor_indices('i0:5', L)
L0 = tensor_indices('L_0', L)
L1 = tensor_indices('L_1', L)
A = TensorHead("A", [L, L])
B = TensorHead("B", [L, L], TensorSymmetry.fully_symmetric(2))
e1 = A(i0,i2)
e2 = A(i0,-i0)
e3 = A(i0,i1)*B(i2,i3)
e4 = A(i0,i1)*B(i2,-i1)
e5 = A(i0,i1)*B(-i0,-i1)
e6 = e1 + e4
assert list(e1._iterate_free_indices) == [(i0, (1, 0)), (i2, (1, 1))]
assert list(e1._iterate_dummy_indices) == []
assert list(e1._iterate_indices) == [(i0, (1, 0)), (i2, (1, 1))]
assert list(e2._iterate_free_indices) == []
assert list(e2._iterate_dummy_indices) == [(L0, (1, 0)), (-L0, (1, 1))]
assert list(e2._iterate_indices) == [(L0, (1, 0)), (-L0, (1, 1))]
assert list(e3._iterate_free_indices) == [(i0, (0, 1, 0)), (i1, (0, 1, 1)), (i2, (1, 1, 0)), (i3, (1, 1, 1))]
assert list(e3._iterate_dummy_indices) == []
assert list(e3._iterate_indices) == [(i0, (0, 1, 0)), (i1, (0, 1, 1)), (i2, (1, 1, 0)), (i3, (1, 1, 1))]
assert list(e4._iterate_free_indices) == [(i0, (0, 1, 0)), (i2, (1, 1, 0))]
assert list(e4._iterate_dummy_indices) == [(L0, (0, 1, 1)), (-L0, (1, 1, 1))]
assert list(e4._iterate_indices) == [(i0, (0, 1, 0)), (L0, (0, 1, 1)), (i2, (1, 1, 0)), (-L0, (1, 1, 1))]
assert list(e5._iterate_free_indices) == []
assert list(e5._iterate_dummy_indices) == [(L0, (0, 1, 0)), (L1, (0, 1, 1)), (-L0, (1, 1, 0)), (-L1, (1, 1, 1))]
assert list(e5._iterate_indices) == [(L0, (0, 1, 0)), (L1, (0, 1, 1)), (-L0, (1, 1, 0)), (-L1, (1, 1, 1))]
assert list(e6._iterate_free_indices) == [(i0, (0, 0, 1, 0)), (i2, (0, 1, 1, 0)), (i0, (1, 1, 0)), (i2, (1, 1, 1))]
assert list(e6._iterate_dummy_indices) == [(L0, (0, 0, 1, 1)), (-L0, (0, 1, 1, 1))]
assert list(e6._iterate_indices) == [(i0, (0, 0, 1, 0)), (L0, (0, 0, 1, 1)), (i2, (0, 1, 1, 0)), (-L0, (0, 1, 1, 1)), (i0, (1, 1, 0)), (i2, (1, 1, 1))]
assert e1.get_indices() == [i0, i2]
assert e1.get_free_indices() == [i0, i2]
assert e2.get_indices() == [L0, -L0]
assert e2.get_free_indices() == []
assert e3.get_indices() == [i0, i1, i2, i3]
assert e3.get_free_indices() == [i0, i1, i2, i3]
assert e4.get_indices() == [i0, L0, i2, -L0]
assert e4.get_free_indices() == [i0, i2]
assert e5.get_indices() == [L0, L1, -L0, -L1]
assert e5.get_free_indices() == []
def test_tensor_expand():
L = TensorIndexType("L")
i, j, k = tensor_indices("i j k", L)
L_0 = TensorIndex("L_0", L)
A, B, C, D = tensor_heads("A B C D", [L])
assert isinstance(Add(A(i), B(i)), TensAdd)
assert isinstance(expand(A(i)+B(i)), TensAdd)
expr = A(i)*(A(-i)+B(-i))
assert expr.args == (A(L_0), A(-L_0) + B(-L_0))
assert expr != A(i)*A(-i) + A(i)*B(-i)
assert expr.expand() == A(i)*A(-i) + A(i)*B(-i)
assert str(expr) == "A(L_0)*(A(-L_0) + B(-L_0))"
expr = A(i)*A(j) + A(i)*B(j)
assert str(expr) == "A(i)*A(j) + A(i)*B(j)"
expr = A(-i)*(A(i)*A(j) + A(i)*B(j)*C(k)*C(-k))
assert expr != A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j)*C(k)*C(-k)
assert expr.expand() == A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j)*C(k)*C(-k)
assert str(expr) == "A(-L_0)*(A(L_0)*A(j) + A(L_0)*B(j)*C(L_1)*C(-L_1))"
assert str(expr.canon_bp()) == 'A(j)*A(L_0)*A(-L_0) + A(L_0)*A(-L_0)*B(j)*C(L_1)*C(-L_1)'
expr = A(-i)*(2*A(i)*A(j) + A(i)*B(j))
assert expr.expand() == 2*A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j)
expr = 2*A(i)*A(-i)
assert expr.coeff == 2
expr = A(i)*(B(j)*C(k) + C(j)*(A(k) + D(k)))
assert str(expr) == "A(i)*(B(j)*C(k) + C(j)*(A(k) + D(k)))"
assert str(expr.expand()) == "A(i)*B(j)*C(k) + A(i)*C(j)*A(k) + A(i)*C(j)*D(k)"
assert isinstance(TensMul(3), TensMul)
tm = TensMul(3).doit()
assert tm == 3
assert isinstance(tm, Integer)
p1 = B(j)*B(-j) + B(j)*C(-j)
p2 = C(-i)*p1
p3 = A(i)*p2
assert p3.expand() == A(i)*C(-i)*B(j)*B(-j) + A(i)*C(-i)*B(j)*C(-j)
expr = A(i)*(B(-i) + C(-i)*(B(j)*B(-j) + B(j)*C(-j)))
assert expr.expand() == A(i)*B(-i) + A(i)*C(-i)*B(j)*B(-j) + A(i)*C(-i)*B(j)*C(-j)
expr = C(-i)*(B(j)*B(-j) + B(j)*C(-j))
assert expr.expand() == C(-i)*B(j)*B(-j) + C(-i)*B(j)*C(-j)
def test_tensor_alternative_construction():
L = TensorIndexType("L")
i0, i1, i2, i3 = tensor_indices('i0:4', L)
A = TensorHead("A", [L])
x, y = symbols("x y")
assert A(i0) == A(Symbol("i0"))
assert A(-i0) == A(-Symbol("i0"))
raises(TypeError, lambda: A(x+y))
raises(ValueError, lambda: A(2*x))
def test_tensor_replacement():
L = TensorIndexType("L")
L2 = TensorIndexType("L2", dim=2)
i, j, k, l = tensor_indices("i j k l", L)
A, B, C, D = tensor_heads("A B C D", [L])
H = TensorHead("H", [L, L])
K = TensorHead("K", [L]*4)
expr = H(i, j)
repl = {H(i,-j): [[1,2],[3,4]], L: diag(1, -1)}
assert expr._extract_data(repl) == ([i, j], Array([[1, -2], [3, -4]]))
assert expr.replace_with_arrays(repl) == Array([[1, -2], [3, -4]])
assert expr.replace_with_arrays(repl, [i, j]) == Array([[1, -2], [3, -4]])
assert expr.replace_with_arrays(repl, [i, -j]) == Array([[1, 2], [3, 4]])
assert expr.replace_with_arrays(repl, [-i, j]) == Array([[1, -2], [-3, 4]])
assert expr.replace_with_arrays(repl, [-i, -j]) == Array([[1, 2], [-3, -4]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[1, 3], [-2, -4]])
assert expr.replace_with_arrays(repl, [j, -i]) == Array([[1, -3], [-2, 4]])
assert expr.replace_with_arrays(repl, [-j, i]) == Array([[1, 3], [2, 4]])
assert expr.replace_with_arrays(repl, [-j, -i]) == Array([[1, -3], [2, -4]])
# Test stability of optional parameter 'indices'
assert expr.replace_with_arrays(repl) == Array([[1, -2], [3, -4]])
expr = H(i,j)
repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)}
assert expr._extract_data(repl) == ([i, j], Array([[1, 2], [3, 4]]))
assert expr.replace_with_arrays(repl) == Array([[1, 2], [3, 4]])
assert expr.replace_with_arrays(repl, [i, j]) == Array([[1, 2], [3, 4]])
assert expr.replace_with_arrays(repl, [i, -j]) == Array([[1, -2], [3, -4]])
assert expr.replace_with_arrays(repl, [-i, j]) == Array([[1, 2], [-3, -4]])
assert expr.replace_with_arrays(repl, [-i, -j]) == Array([[1, -2], [-3, 4]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[1, 3], [2, 4]])
assert expr.replace_with_arrays(repl, [j, -i]) == Array([[1, -3], [2, -4]])
assert expr.replace_with_arrays(repl, [-j, i]) == Array([[1, 3], [-2, -4]])
assert expr.replace_with_arrays(repl, [-j, -i]) == Array([[1, -3], [-2, 4]])
# Not the same indices:
expr = H(i,k)
repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)}
assert expr._extract_data(repl) == ([i, k], Array([[1, 2], [3, 4]]))
expr = A(i)*A(-i)
repl = {A(i): [1,2], L: diag(1, -1)}
assert expr._extract_data(repl) == ([], -3)
assert expr.replace_with_arrays(repl, []) == -3
expr = K(i, j, -j, k)*A(-i)*A(-k)
repl = {A(i): [1, 2], K(i,j,k,l): Array([1]*2**4).reshape(2,2,2,2), L: diag(1, -1)}
assert expr._extract_data(repl)
expr = H(j, k)
repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)}
raises(ValueError, lambda: expr._extract_data(repl))
expr = A(i)
repl = {B(i): [1, 2]}
raises(ValueError, lambda: expr._extract_data(repl))
expr = A(i)
repl = {A(i): [[1, 2], [3, 4]]}
raises(ValueError, lambda: expr._extract_data(repl))
# TensAdd:
expr = A(k)*H(i, j) + B(k)*H(i, j)
repl = {A(k): [1], B(k): [1], H(i, j): [[1, 2],[3,4]], L:diag(1,1)}
assert expr._extract_data(repl) == ([k, i, j], Array([[[2, 4], [6, 8]]]))
assert expr.replace_with_arrays(repl, [k, i, j]) == Array([[[2, 4], [6, 8]]])
assert expr.replace_with_arrays(repl, [k, j, i]) == Array([[[2, 6], [4, 8]]])
expr = A(k)*A(-k) + 100
repl = {A(k): [2, 3], L: diag(1, 1)}
assert expr.replace_with_arrays(repl, []) == 113
## Symmetrization:
expr = H(i, j) + H(j, i)
repl = {H(i, j): [[1, 2], [3, 4]]}
assert expr._extract_data(repl) == ([i, j], Array([[2, 5], [5, 8]]))
assert expr.replace_with_arrays(repl, [i, j]) == Array([[2, 5], [5, 8]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[2, 5], [5, 8]])
## Anti-symmetrization:
expr = H(i, j) - H(j, i)
repl = {H(i, j): [[1, 2], [3, 4]]}
assert expr.replace_with_arrays(repl, [i, j]) == Array([[0, -1], [1, 0]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[0, 1], [-1, 0]])
# Tensors with contractions in replacements:
expr = K(i, j, k, -k)
repl = {K(i, j, k, -k): [[1, 2], [3, 4]]}
assert expr._extract_data(repl) == ([i, j], Array([[1, 2], [3, 4]]))
expr = H(i, -i)
repl = {H(i, -i): 42}
assert expr._extract_data(repl) == ([], 42)
expr = H(i, -i)
repl = {
H(-i, -j): Array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]),
L: Array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, -1, 0], [0, 0, 0, -1]]),
}
assert expr._extract_data(repl) == ([], 4)
# Replace with array, raise exception if indices are not compatible:
expr = A(i)*A(j)
repl = {A(i): [1, 2]}
raises(ValueError, lambda: expr.replace_with_arrays(repl, [j]))
# Raise exception if array dimension is not compatible:
expr = A(i)
repl = {A(i): [[1, 2]]}
raises(ValueError, lambda: expr.replace_with_arrays(repl, [i]))
# TensorIndexType with dimension, wrong dimension in replacement array:
u1, u2, u3 = tensor_indices("u1:4", L2)
U = TensorHead("U", [L2])
expr = U(u1)*U(-u2)
repl = {U(u1): [[1]]}
raises(ValueError, lambda: expr.replace_with_arrays(repl, [u1, -u2]))
def test_rewrite_tensor_to_Indexed():
L = TensorIndexType("L", dim=4)
A = TensorHead("A", [L]*4)
B = TensorHead("B", [L])
i0, i1, i2, i3 = symbols("i0:4")
L_0, L_1 = symbols("L_0:2")
a1 = A(i0, i1, i2, i3)
assert a1.rewrite(Indexed) == Indexed(Symbol("A"), i0, i1, i2, i3)
a2 = A(i0, -i0, i2, i3)
assert a2.rewrite(Indexed) == Sum(Indexed(Symbol("A"), L_0, L_0, i2, i3), (L_0, 0, 3))
a3 = a2 + A(i2, i3, i0, -i0)
assert a3.rewrite(Indexed) == \
Sum(Indexed(Symbol("A"), L_0, L_0, i2, i3), (L_0, 0, 3)) +\
Sum(Indexed(Symbol("A"), i2, i3, L_0, L_0), (L_0, 0, 3))
b1 = B(-i0)*a1
assert b1.rewrite(Indexed) == Sum(Indexed(Symbol("B"), L_0)*Indexed(Symbol("A"), L_0, i1, i2, i3), (L_0, 0, 3))
b2 = B(-i3)*a2
assert b2.rewrite(Indexed) == Sum(Indexed(Symbol("B"), L_1)*Indexed(Symbol("A"), L_0, L_0, i2, L_1), (L_0, 0, 3), (L_1, 0, 3))
def test_tensorsymmetry():
with warns_deprecated_sympy():
tensorsymmetry([1]*2)
def test_tensorhead():
with warns_deprecated_sympy():
tensorhead('A', [])
def test_TensorType():
with warns_deprecated_sympy():
sym2 = TensorSymmetry.fully_symmetric(2)
Lorentz = TensorIndexType('Lorentz')
S2 = TensorType([Lorentz]*2, sym2)
assert isinstance(S2, TensorType)
|
a42bea992714d28431c78e2a9bd4f73242885ca8151510e44872c385236a3886 | from sympy.core import symbols, Symbol, Tuple, oo, Dummy
from sympy.tensor.indexed import IndexException
from sympy.testing.pytest import raises
from sympy.utilities.iterables import iterable
# import test:
from sympy.concrete.summations import Sum
from sympy.core.function import Function, Subs, Derivative
from sympy.core.relational import (StrictLessThan, GreaterThan,
StrictGreaterThan, LessThan)
from sympy.core.singleton import S
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.series.order import Order
from sympy.sets.fancysets import Range
from sympy.tensor.indexed import IndexedBase, Idx, Indexed
def test_Idx_construction():
i, a, b = symbols('i a b', integer=True)
assert Idx(i) != Idx(i, 1)
assert Idx(i, a) == Idx(i, (0, a - 1))
assert Idx(i, oo) == Idx(i, (0, oo))
x = symbols('x', integer=False)
raises(TypeError, lambda: Idx(x))
raises(TypeError, lambda: Idx(0.5))
raises(TypeError, lambda: Idx(i, x))
raises(TypeError, lambda: Idx(i, 0.5))
raises(TypeError, lambda: Idx(i, (x, 5)))
raises(TypeError, lambda: Idx(i, (2, x)))
raises(TypeError, lambda: Idx(i, (2, 3.5)))
def test_Idx_properties():
i, a, b = symbols('i a b', integer=True)
assert Idx(i).is_integer
assert Idx(i).name == 'i'
assert Idx(i + 2).name == 'i + 2'
assert Idx('foo').name == 'foo'
def test_Idx_bounds():
i, a, b = symbols('i a b', integer=True)
assert Idx(i).lower is None
assert Idx(i).upper is None
assert Idx(i, a).lower == 0
assert Idx(i, a).upper == a - 1
assert Idx(i, 5).lower == 0
assert Idx(i, 5).upper == 4
assert Idx(i, oo).lower == 0
assert Idx(i, oo).upper is oo
assert Idx(i, (a, b)).lower == a
assert Idx(i, (a, b)).upper == b
assert Idx(i, (1, 5)).lower == 1
assert Idx(i, (1, 5)).upper == 5
assert Idx(i, (-oo, oo)).lower is -oo
assert Idx(i, (-oo, oo)).upper is oo
def test_Idx_fixed_bounds():
i, a, b, x = symbols('i a b x', integer=True)
assert Idx(x).lower is None
assert Idx(x).upper is None
assert Idx(x, a).lower == 0
assert Idx(x, a).upper == a - 1
assert Idx(x, 5).lower == 0
assert Idx(x, 5).upper == 4
assert Idx(x, oo).lower == 0
assert Idx(x, oo).upper is oo
assert Idx(x, (a, b)).lower == a
assert Idx(x, (a, b)).upper == b
assert Idx(x, (1, 5)).lower == 1
assert Idx(x, (1, 5)).upper == 5
assert Idx(x, (-oo, oo)).lower is -oo
assert Idx(x, (-oo, oo)).upper is oo
def test_Idx_inequalities():
i14 = Idx("i14", (1, 4))
i79 = Idx("i79", (7, 9))
i46 = Idx("i46", (4, 6))
i35 = Idx("i35", (3, 5))
assert i14 <= 5
assert i14 < 5
assert not (i14 >= 5)
assert not (i14 > 5)
assert 5 >= i14
assert 5 > i14
assert not (5 <= i14)
assert not (5 < i14)
assert LessThan(i14, 5)
assert StrictLessThan(i14, 5)
assert not GreaterThan(i14, 5)
assert not StrictGreaterThan(i14, 5)
assert i14 <= 4
assert isinstance(i14 < 4, StrictLessThan)
assert isinstance(i14 >= 4, GreaterThan)
assert not (i14 > 4)
assert isinstance(i14 <= 1, LessThan)
assert not (i14 < 1)
assert i14 >= 1
assert isinstance(i14 > 1, StrictGreaterThan)
assert not (i14 <= 0)
assert not (i14 < 0)
assert i14 >= 0
assert i14 > 0
from sympy.abc import x
assert isinstance(i14 < x, StrictLessThan)
assert isinstance(i14 > x, StrictGreaterThan)
assert isinstance(i14 <= x, LessThan)
assert isinstance(i14 >= x, GreaterThan)
assert i14 < i79
assert i14 <= i79
assert not (i14 > i79)
assert not (i14 >= i79)
assert i14 <= i46
assert isinstance(i14 < i46, StrictLessThan)
assert isinstance(i14 >= i46, GreaterThan)
assert not (i14 > i46)
assert isinstance(i14 < i35, StrictLessThan)
assert isinstance(i14 > i35, StrictGreaterThan)
assert isinstance(i14 <= i35, LessThan)
assert isinstance(i14 >= i35, GreaterThan)
iNone1 = Idx("iNone1")
iNone2 = Idx("iNone2")
assert isinstance(iNone1 < iNone2, StrictLessThan)
assert isinstance(iNone1 > iNone2, StrictGreaterThan)
assert isinstance(iNone1 <= iNone2, LessThan)
assert isinstance(iNone1 >= iNone2, GreaterThan)
def test_Idx_inequalities_current_fails():
i14 = Idx("i14", (1, 4))
assert S(5) >= i14
assert S(5) > i14
assert not (S(5) <= i14)
assert not (S(5) < i14)
def test_Idx_func_args():
i, a, b = symbols('i a b', integer=True)
ii = Idx(i)
assert ii.func(*ii.args) == ii
ii = Idx(i, a)
assert ii.func(*ii.args) == ii
ii = Idx(i, (a, b))
assert ii.func(*ii.args) == ii
def test_Idx_subs():
i, a, b = symbols('i a b', integer=True)
assert Idx(i, a).subs(a, b) == Idx(i, b)
assert Idx(i, a).subs(i, b) == Idx(b, a)
assert Idx(i).subs(i, 2) == Idx(2)
assert Idx(i, a).subs(a, 2) == Idx(i, 2)
assert Idx(i, (a, b)).subs(i, 2) == Idx(2, (a, b))
def test_IndexedBase_sugar():
i, j = symbols('i j', integer=True)
a = symbols('a')
A1 = Indexed(a, i, j)
A2 = IndexedBase(a)
assert A1 == A2[i, j]
assert A1 == A2[(i, j)]
assert A1 == A2[[i, j]]
assert A1 == A2[Tuple(i, j)]
assert all(a.is_Integer for a in A2[1, 0].args[1:])
def test_IndexedBase_subs():
i = symbols('i', integer=True)
a, b = symbols('a b')
A = IndexedBase(a)
B = IndexedBase(b)
assert A[i] == B[i].subs(b, a)
C = {1: 2}
assert C[1] == A[1].subs(A, C)
def test_IndexedBase_shape():
i, j, m, n = symbols('i j m n', integer=True)
a = IndexedBase('a', shape=(m, m))
b = IndexedBase('a', shape=(m, n))
assert b.shape == Tuple(m, n)
assert a[i, j] != b[i, j]
assert a[i, j] == b[i, j].subs(n, m)
assert b.func(*b.args) == b
assert b[i, j].func(*b[i, j].args) == b[i, j]
raises(IndexException, lambda: b[i])
raises(IndexException, lambda: b[i, i, j])
F = IndexedBase("F", shape=m)
assert F.shape == Tuple(m)
assert F[i].subs(i, j) == F[j]
raises(IndexException, lambda: F[i, j])
def test_IndexedBase_assumptions():
i = Symbol('i', integer=True)
a = Symbol('a')
A = IndexedBase(a, positive=True)
for c in (A, A[i]):
assert c.is_real
assert c.is_complex
assert not c.is_imaginary
assert c.is_nonnegative
assert c.is_nonzero
assert c.is_commutative
assert log(exp(c)) == c
assert A != IndexedBase(a)
assert A == IndexedBase(a, positive=True, real=True)
assert A[i] != Indexed(a, i)
def test_IndexedBase_assumptions_inheritance():
I = Symbol('I', integer=True)
I_inherit = IndexedBase(I)
I_explicit = IndexedBase('I', integer=True)
assert I_inherit.is_integer
assert I_explicit.is_integer
assert I_inherit.label.is_integer
assert I_explicit.label.is_integer
assert I_inherit == I_explicit
def test_issue_17652():
"""Regression test issue #17652.
IndexedBase.label should not upcast subclasses of Symbol
"""
class SubClass(Symbol):
pass
x = SubClass('X')
assert type(x) == SubClass
base = IndexedBase(x)
assert type(x) == SubClass
assert type(base.label) == SubClass
def test_Indexed_constructor():
i, j = symbols('i j', integer=True)
A = Indexed('A', i, j)
assert A == Indexed(Symbol('A'), i, j)
assert A == Indexed(IndexedBase('A'), i, j)
raises(TypeError, lambda: Indexed(A, i, j))
raises(IndexException, lambda: Indexed("A"))
assert A.free_symbols == {A, A.base.label, i, j}
def test_Indexed_func_args():
i, j = symbols('i j', integer=True)
a = symbols('a')
A = Indexed(a, i, j)
assert A == A.func(*A.args)
def test_Indexed_subs():
i, j, k = symbols('i j k', integer=True)
a, b = symbols('a b')
A = IndexedBase(a)
B = IndexedBase(b)
assert A[i, j] == B[i, j].subs(b, a)
assert A[i, j] == A[i, k].subs(k, j)
def test_Indexed_properties():
i, j = symbols('i j', integer=True)
A = Indexed('A', i, j)
assert A.name == 'A[i, j]'
assert A.rank == 2
assert A.indices == (i, j)
assert A.base == IndexedBase('A')
assert A.ranges == [None, None]
raises(IndexException, lambda: A.shape)
n, m = symbols('n m', integer=True)
assert Indexed('A', Idx(
i, m), Idx(j, n)).ranges == [Tuple(0, m - 1), Tuple(0, n - 1)]
assert Indexed('A', Idx(i, m), Idx(j, n)).shape == Tuple(m, n)
raises(IndexException, lambda: Indexed("A", Idx(i, m), Idx(j)).shape)
def test_Indexed_shape_precedence():
i, j = symbols('i j', integer=True)
o, p = symbols('o p', integer=True)
n, m = symbols('n m', integer=True)
a = IndexedBase('a', shape=(o, p))
assert a.shape == Tuple(o, p)
assert Indexed(
a, Idx(i, m), Idx(j, n)).ranges == [Tuple(0, m - 1), Tuple(0, n - 1)]
assert Indexed(a, Idx(i, m), Idx(j, n)).shape == Tuple(o, p)
assert Indexed(
a, Idx(i, m), Idx(j)).ranges == [Tuple(0, m - 1), (None, None)]
assert Indexed(a, Idx(i, m), Idx(j)).shape == Tuple(o, p)
def test_complex_indices():
i, j = symbols('i j', integer=True)
A = Indexed('A', i, i + j)
assert A.rank == 2
assert A.indices == (i, i + j)
def test_not_interable():
i, j = symbols('i j', integer=True)
A = Indexed('A', i, i + j)
assert not iterable(A)
def test_Indexed_coeff():
N = Symbol('N', integer=True)
len_y = N
i = Idx('i', len_y-1)
y = IndexedBase('y', shape=(len_y,))
a = (1/y[i+1]*y[i]).coeff(y[i])
b = (y[i]/y[i+1]).coeff(y[i])
assert a == b
def test_differentiation():
from sympy.functions.special.tensor_functions import KroneckerDelta
i, j, k, l = symbols('i j k l', cls=Idx)
a = symbols('a')
m, n = symbols("m, n", integer=True, finite=True)
assert m.is_real
h, L = symbols('h L', cls=IndexedBase)
hi, hj = h[i], h[j]
expr = hi
assert expr.diff(hj) == KroneckerDelta(i, j)
assert expr.diff(hi) == KroneckerDelta(i, i)
expr = S(2) * hi
assert expr.diff(hj) == S(2) * KroneckerDelta(i, j)
assert expr.diff(hi) == S(2) * KroneckerDelta(i, i)
assert expr.diff(a) is S.Zero
assert Sum(expr, (i, -oo, oo)).diff(hj) == Sum(2*KroneckerDelta(i, j), (i, -oo, oo))
assert Sum(expr.diff(hj), (i, -oo, oo)) == Sum(2*KroneckerDelta(i, j), (i, -oo, oo))
assert Sum(expr, (i, -oo, oo)).diff(hj).doit() == 2
assert Sum(expr.diff(hi), (i, -oo, oo)).doit() == Sum(2, (i, -oo, oo)).doit()
assert Sum(expr, (i, -oo, oo)).diff(hi).doit() is oo
expr = a * hj * hj / S(2)
assert expr.diff(hi) == a * h[j] * KroneckerDelta(i, j)
assert expr.diff(a) == hj * hj / S(2)
assert expr.diff(a, 2) is S.Zero
assert Sum(expr, (i, -oo, oo)).diff(hi) == Sum(a*KroneckerDelta(i, j)*h[j], (i, -oo, oo))
assert Sum(expr.diff(hi), (i, -oo, oo)) == Sum(a*KroneckerDelta(i, j)*h[j], (i, -oo, oo))
assert Sum(expr, (i, -oo, oo)).diff(hi).doit() == a*h[j]
assert Sum(expr, (j, -oo, oo)).diff(hi) == Sum(a*KroneckerDelta(i, j)*h[j], (j, -oo, oo))
assert Sum(expr.diff(hi), (j, -oo, oo)) == Sum(a*KroneckerDelta(i, j)*h[j], (j, -oo, oo))
assert Sum(expr, (j, -oo, oo)).diff(hi).doit() == a*h[i]
expr = a * sin(hj * hj)
assert expr.diff(hi) == 2*a*cos(hj * hj) * hj * KroneckerDelta(i, j)
assert expr.diff(hj) == 2*a*cos(hj * hj) * hj
expr = a * L[i, j] * h[j]
assert expr.diff(hi) == a*L[i, j]*KroneckerDelta(i, j)
assert expr.diff(hj) == a*L[i, j]
assert expr.diff(L[i, j]) == a*h[j]
assert expr.diff(L[k, l]) == a*KroneckerDelta(i, k)*KroneckerDelta(j, l)*h[j]
assert expr.diff(L[i, l]) == a*KroneckerDelta(j, l)*h[j]
assert Sum(expr, (j, -oo, oo)).diff(L[k, l]) == Sum(a * KroneckerDelta(i, k) * KroneckerDelta(j, l) * h[j], (j, -oo, oo))
assert Sum(expr, (j, -oo, oo)).diff(L[k, l]).doit() == a * KroneckerDelta(i, k) * h[l]
assert h[m].diff(h[m]) == 1
assert h[m].diff(h[n]) == KroneckerDelta(m, n)
assert Sum(a*h[m], (m, -oo, oo)).diff(h[n]) == Sum(a*KroneckerDelta(m, n), (m, -oo, oo))
assert Sum(a*h[m], (m, -oo, oo)).diff(h[n]).doit() == a
assert Sum(a*h[m], (n, -oo, oo)).diff(h[n]) == Sum(a*KroneckerDelta(m, n), (n, -oo, oo))
assert Sum(a*h[m], (m, -oo, oo)).diff(h[m]).doit() == oo*a
def test_indexed_series():
A = IndexedBase("A")
i = symbols("i", integer=True)
assert sin(A[i]).series(A[i]) == A[i] - A[i]**3/6 + A[i]**5/120 + Order(A[i]**6, A[i])
def test_indexed_is_constant():
A = IndexedBase("A")
i, j, k = symbols("i,j,k")
assert not A[i].is_constant()
assert A[i].is_constant(j)
assert not A[1+2*i, k].is_constant()
assert not A[1+2*i, k].is_constant(i)
assert A[1+2*i, k].is_constant(j)
assert not A[1+2*i, k].is_constant(k)
def test_issue_12533():
d = IndexedBase('d')
assert IndexedBase(range(5)) == Range(0, 5, 1)
assert d[0].subs(Symbol("d"), range(5)) == 0
assert d[0].subs(d, range(5)) == 0
assert d[1].subs(d, range(5)) == 1
assert Indexed(Range(5), 2) == 2
def test_issue_12780():
n = symbols("n")
i = Idx("i", (0, n))
raises(TypeError, lambda: i.subs(n, 1.5))
def test_issue_18604():
m = symbols("m")
assert Idx("i", m).name == 'i'
assert Idx("i", m).lower == 0
assert Idx("i", m).upper == m - 1
m = symbols("m", real=False)
raises(TypeError, lambda: Idx("i", m))
def test_Subs_with_Indexed():
A = IndexedBase("A")
i, j, k = symbols("i,j,k")
x, y, z = symbols("x,y,z")
f = Function("f")
assert Subs(A[i], A[i], A[j]).diff(A[j]) == 1
assert Subs(A[i], A[i], x).diff(A[i]) == 0
assert Subs(A[i], A[i], x).diff(A[j]) == 0
assert Subs(A[i], A[i], x).diff(x) == 1
assert Subs(A[i], A[i], x).diff(y) == 0
assert Subs(A[i], A[i], A[j]).diff(A[k]) == KroneckerDelta(j, k)
assert Subs(x, x, A[i]).diff(A[j]) == KroneckerDelta(i, j)
assert Subs(f(A[i]), A[i], x).diff(A[j]) == 0
assert Subs(f(A[i]), A[i], A[k]).diff(A[j]) == Derivative(f(A[k]), A[k])*KroneckerDelta(j, k)
assert Subs(x, x, A[i]**2).diff(A[j]) == 2*KroneckerDelta(i, j)*A[i]
assert Subs(A[i], A[i], A[j]**2).diff(A[k]) == 2*KroneckerDelta(j, k)*A[j]
assert Subs(A[i]*x, x, A[i]).diff(A[i]) == 2*A[i]
assert Subs(A[i]*x, x, A[i]).diff(A[j]) == 2*A[i]*KroneckerDelta(i, j)
assert Subs(A[i]*x, x, A[j]).diff(A[i]) == A[j] + A[i]*KroneckerDelta(i, j)
assert Subs(A[i]*x, x, A[j]).diff(A[j]) == A[i] + A[j]*KroneckerDelta(i, j)
assert Subs(A[i]*x, x, A[i]).diff(A[k]) == 2*A[i]*KroneckerDelta(i, k)
assert Subs(A[i]*x, x, A[j]).diff(A[k]) == KroneckerDelta(i, k)*A[j] + KroneckerDelta(j, k)*A[i]
assert Subs(A[i]*x, A[i], x).diff(A[i]) == 0
assert Subs(A[i]*x, A[i], x).diff(A[j]) == 0
assert Subs(A[i]*x, A[j], x).diff(A[i]) == x
assert Subs(A[i]*x, A[j], x).diff(A[j]) == x*KroneckerDelta(i, j)
assert Subs(A[i]*x, A[i], x).diff(A[k]) == 0
assert Subs(A[i]*x, A[j], x).diff(A[k]) == x*KroneckerDelta(i, k)
def test_complicated_derivative_with_Indexed():
x, y = symbols("x,y", cls=IndexedBase)
sigma = symbols("sigma")
i, j, k = symbols("i,j,k")
m0,m1,m2,m3,m4,m5 = symbols("m0:6")
f = Function("f")
expr = f((x[i] - y[i])**2/sigma)
_xi_1 = symbols("xi_1", cls=Dummy)
assert expr.diff(x[m0]).dummy_eq(
(x[i] - y[i])*KroneckerDelta(i, m0)*\
2*Subs(
Derivative(f(_xi_1), _xi_1),
(_xi_1,),
((x[i] - y[i])**2/sigma,)
)/sigma
)
assert expr.diff(x[m0]).diff(x[m1]).dummy_eq(
2*KroneckerDelta(i, m0)*\
KroneckerDelta(i, m1)*Subs(
Derivative(f(_xi_1), _xi_1),
(_xi_1,),
((x[i] - y[i])**2/sigma,)
)/sigma + \
4*(x[i] - y[i])**2*KroneckerDelta(i, m0)*KroneckerDelta(i, m1)*\
Subs(
Derivative(f(_xi_1), _xi_1, _xi_1),
(_xi_1,),
((x[i] - y[i])**2/sigma,)
)/sigma**2
)
|
61e47cd40668d263c1c7b4346b24ec40df24fc33f5a4b0e803872ff4897cc3dc | import random
from sympy.combinatorics import Permutation
from sympy.combinatorics.permutations import _af_invert
from sympy.testing.pytest import raises
from sympy.core.function import diff
from sympy.core.symbol import symbols
from sympy.functions.elementary.complexes import (adjoint, conjugate, transpose)
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.tensor.array import Array, ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableSparseNDimArray
from sympy.tensor.array.arrayop import tensorproduct, tensorcontraction, derive_by_array, permutedims, Flatten, \
tensordiagonal
def test_import_NDimArray():
from sympy.tensor.array import NDimArray
del NDimArray
def test_tensorproduct():
x,y,z,t = symbols('x y z t')
from sympy.abc import a,b,c,d
assert tensorproduct() == 1
assert tensorproduct([x]) == Array([x])
assert tensorproduct([x], [y]) == Array([[x*y]])
assert tensorproduct([x], [y], [z]) == Array([[[x*y*z]]])
assert tensorproduct([x], [y], [z], [t]) == Array([[[[x*y*z*t]]]])
assert tensorproduct(x) == x
assert tensorproduct(x, y) == x*y
assert tensorproduct(x, y, z) == x*y*z
assert tensorproduct(x, y, z, t) == x*y*z*t
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
A = ArrayType([x, y])
B = ArrayType([1, 2, 3])
C = ArrayType([a, b, c, d])
assert tensorproduct(A, B, C) == ArrayType([[[a*x, b*x, c*x, d*x], [2*a*x, 2*b*x, 2*c*x, 2*d*x], [3*a*x, 3*b*x, 3*c*x, 3*d*x]],
[[a*y, b*y, c*y, d*y], [2*a*y, 2*b*y, 2*c*y, 2*d*y], [3*a*y, 3*b*y, 3*c*y, 3*d*y]]])
assert tensorproduct([x, y], [1, 2, 3]) == tensorproduct(A, B)
assert tensorproduct(A, 2) == ArrayType([2*x, 2*y])
assert tensorproduct(A, [2]) == ArrayType([[2*x], [2*y]])
assert tensorproduct([2], A) == ArrayType([[2*x, 2*y]])
assert tensorproduct(a, A) == ArrayType([a*x, a*y])
assert tensorproduct(a, A, B) == ArrayType([[a*x, 2*a*x, 3*a*x], [a*y, 2*a*y, 3*a*y]])
assert tensorproduct(A, B, a) == ArrayType([[a*x, 2*a*x, 3*a*x], [a*y, 2*a*y, 3*a*y]])
assert tensorproduct(B, a, A) == ArrayType([[a*x, a*y], [2*a*x, 2*a*y], [3*a*x, 3*a*y]])
# tests for large scale sparse array
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
a = SparseArrayType({1:2, 3:4},(1000, 2000))
b = SparseArrayType({1:2, 3:4},(1000, 2000))
assert tensorproduct(a, b) == ImmutableSparseNDimArray({2000001: 4, 2000003: 8, 6000001: 8, 6000003: 16}, (1000, 2000, 1000, 2000))
def test_tensorcontraction():
from sympy.abc import a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x
B = Array(range(18), (2, 3, 3))
assert tensorcontraction(B, (1, 2)) == Array([12, 39])
C1 = Array([a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x], (2, 3, 2, 2))
assert tensorcontraction(C1, (0, 2)) == Array([[a + o, b + p], [e + s, f + t], [i + w, j + x]])
assert tensorcontraction(C1, (0, 2, 3)) == Array([a + p, e + t, i + x])
assert tensorcontraction(C1, (2, 3)) == Array([[a + d, e + h, i + l], [m + p, q + t, u + x]])
def test_derivative_by_array():
from sympy.abc import i, j, t, x, y, z
bexpr = x*y**2*exp(z)*log(t)
sexpr = sin(bexpr)
cexpr = cos(bexpr)
a = Array([sexpr])
assert derive_by_array(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t
assert derive_by_array(sexpr, [x, y, z]) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr])
assert derive_by_array(a, [x, y, z]) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]])
assert derive_by_array(sexpr, [[x, y], [z, t]]) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]])
assert derive_by_array(a, [[x, y], [z, t]]) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]])
assert derive_by_array([[x, y], [z, t]], [x, y]) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]])
assert derive_by_array([[x, y], [z, t]], [[x, y], [z, t]]) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]],
[[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
assert diff(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t
assert diff(sexpr, Array([x, y, z])) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr])
assert diff(a, Array([x, y, z])) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]])
assert diff(sexpr, Array([[x, y], [z, t]])) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]])
assert diff(a, Array([[x, y], [z, t]])) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]])
assert diff(Array([[x, y], [z, t]]), Array([x, y])) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]])
assert diff(Array([[x, y], [z, t]]), Array([[x, y], [z, t]])) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]],
[[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
# test for large scale sparse array
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
b = MutableSparseNDimArray({0:i, 1:j}, (10000, 20000))
assert derive_by_array(b, i) == ImmutableSparseNDimArray({0: 1}, (10000, 20000))
assert derive_by_array(b, (i, j)) == ImmutableSparseNDimArray({0: 1, 200000001: 1}, (2, 10000, 20000))
#https://github.com/sympy/sympy/issues/20655
U = Array([x, y, z])
E = 2
assert derive_by_array(E, U) == ImmutableDenseNDimArray([0, 0, 0])
def test_issue_emerged_while_discussing_10972():
ua = Array([-1,0])
Fa = Array([[0, 1], [-1, 0]])
po = tensorproduct(Fa, ua, Fa, ua)
assert tensorcontraction(po, (1, 2), (4, 5)) == Array([[0, 0], [0, 1]])
sa = symbols('a0:144')
po = Array(sa, [2, 2, 3, 3, 2, 2])
assert tensorcontraction(po, (0, 1), (2, 3), (4, 5)) == sa[0] + sa[108] + sa[111] + sa[124] + sa[127] + sa[140] + sa[143] + sa[16] + sa[19] + sa[3] + sa[32] + sa[35]
assert tensorcontraction(po, (0, 1, 4, 5), (2, 3)) == sa[0] + sa[111] + sa[127] + sa[143] + sa[16] + sa[32]
assert tensorcontraction(po, (0, 1), (4, 5)) == Array([[sa[0] + sa[108] + sa[111] + sa[3], sa[112] + sa[115] + sa[4] + sa[7],
sa[11] + sa[116] + sa[119] + sa[8]], [sa[12] + sa[120] + sa[123] + sa[15],
sa[124] + sa[127] + sa[16] + sa[19], sa[128] + sa[131] + sa[20] + sa[23]],
[sa[132] + sa[135] + sa[24] + sa[27], sa[136] + sa[139] + sa[28] + sa[31],
sa[140] + sa[143] + sa[32] + sa[35]]])
assert tensorcontraction(po, (0, 1), (2, 3)) == Array([[sa[0] + sa[108] + sa[124] + sa[140] + sa[16] + sa[32], sa[1] + sa[109] + sa[125] + sa[141] + sa[17] + sa[33]],
[sa[110] + sa[126] + sa[142] + sa[18] + sa[2] + sa[34], sa[111] + sa[127] + sa[143] + sa[19] + sa[3] + sa[35]]])
def test_array_permutedims():
sa = symbols('a0:144')
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
m1 = ArrayType(sa[:6], (2, 3))
assert permutedims(m1, (1, 0)) == transpose(m1)
assert m1.tomatrix().T == permutedims(m1, (1, 0)).tomatrix()
assert m1.tomatrix().T == transpose(m1).tomatrix()
assert m1.tomatrix().C == conjugate(m1).tomatrix()
assert m1.tomatrix().H == adjoint(m1).tomatrix()
assert m1.tomatrix().T == m1.transpose().tomatrix()
assert m1.tomatrix().C == m1.conjugate().tomatrix()
assert m1.tomatrix().H == m1.adjoint().tomatrix()
raises(ValueError, lambda: permutedims(m1, (0,)))
raises(ValueError, lambda: permutedims(m1, (0, 0)))
raises(ValueError, lambda: permutedims(m1, (1, 2, 0)))
# Some tests with random arrays:
dims = 6
shape = [random.randint(1,5) for i in range(dims)]
elems = [random.random() for i in range(tensorproduct(*shape))]
ra = ArrayType(elems, shape)
perm = list(range(dims))
# Randomize the permutation:
random.shuffle(perm)
# Test inverse permutation:
assert permutedims(permutedims(ra, perm), _af_invert(perm)) == ra
# Test that permuted shape corresponds to action by `Permutation`:
assert permutedims(ra, perm).shape == tuple(Permutation(perm)(shape))
z = ArrayType.zeros(4,5,6,7)
assert permutedims(z, (2, 3, 1, 0)).shape == (6, 7, 5, 4)
assert permutedims(z, [2, 3, 1, 0]).shape == (6, 7, 5, 4)
assert permutedims(z, Permutation([2, 3, 1, 0])).shape == (6, 7, 5, 4)
po = ArrayType(sa, [2, 2, 3, 3, 2, 2])
raises(ValueError, lambda: permutedims(po, (1, 1)))
raises(ValueError, lambda: po.transpose())
raises(ValueError, lambda: po.adjoint())
assert permutedims(po, reversed(range(po.rank()))) == ArrayType(
[[[[[[sa[0], sa[72]], [sa[36], sa[108]]], [[sa[12], sa[84]], [sa[48], sa[120]]], [[sa[24],
sa[96]], [sa[60], sa[132]]]],
[[[sa[4], sa[76]], [sa[40], sa[112]]], [[sa[16],
sa[88]], [sa[52], sa[124]]],
[[sa[28], sa[100]], [sa[64], sa[136]]]],
[[[sa[8],
sa[80]], [sa[44], sa[116]]], [[sa[20], sa[92]], [sa[56], sa[128]]], [[sa[32],
sa[104]], [sa[68], sa[140]]]]],
[[[[sa[2], sa[74]], [sa[38], sa[110]]], [[sa[14],
sa[86]], [sa[50], sa[122]]], [[sa[26], sa[98]], [sa[62], sa[134]]]],
[[[sa[6],
sa[78]], [sa[42], sa[114]]], [[sa[18], sa[90]], [sa[54], sa[126]]], [[sa[30],
sa[102]], [sa[66], sa[138]]]],
[[[sa[10], sa[82]], [sa[46], sa[118]]], [[sa[22],
sa[94]], [sa[58], sa[130]]],
[[sa[34], sa[106]], [sa[70], sa[142]]]]]],
[[[[[sa[1],
sa[73]], [sa[37], sa[109]]], [[sa[13], sa[85]], [sa[49], sa[121]]], [[sa[25],
sa[97]], [sa[61], sa[133]]]],
[[[sa[5], sa[77]], [sa[41], sa[113]]], [[sa[17],
sa[89]], [sa[53], sa[125]]],
[[sa[29], sa[101]], [sa[65], sa[137]]]],
[[[sa[9],
sa[81]], [sa[45], sa[117]]], [[sa[21], sa[93]], [sa[57], sa[129]]], [[sa[33],
sa[105]], [sa[69], sa[141]]]]],
[[[[sa[3], sa[75]], [sa[39], sa[111]]], [[sa[15],
sa[87]], [sa[51], sa[123]]], [[sa[27], sa[99]], [sa[63], sa[135]]]],
[[[sa[7],
sa[79]], [sa[43], sa[115]]], [[sa[19], sa[91]], [sa[55], sa[127]]], [[sa[31],
sa[103]], [sa[67], sa[139]]]],
[[[sa[11], sa[83]], [sa[47], sa[119]]], [[sa[23],
sa[95]], [sa[59], sa[131]]],
[[sa[35], sa[107]], [sa[71], sa[143]]]]]]])
assert permutedims(po, (1, 0, 2, 3, 4, 5)) == ArrayType(
[[[[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10],
sa[11]]]],
[[[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18],
sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]]],
[[[sa[24], sa[25]], [sa[26],
sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34],
sa[35]]]]],
[[[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78],
sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]]],
[[[sa[84], sa[85]], [sa[86],
sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94],
sa[95]]]],
[[[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102],
sa[103]]],
[[sa[104], sa[105]], [sa[106], sa[107]]]]]], [[[[[sa[36], sa[37]], [sa[38],
sa[39]]],
[[sa[40], sa[41]], [sa[42], sa[43]]],
[[sa[44], sa[45]], [sa[46],
sa[47]]]],
[[[sa[48], sa[49]], [sa[50], sa[51]]],
[[sa[52], sa[53]], [sa[54],
sa[55]]],
[[sa[56], sa[57]], [sa[58], sa[59]]]],
[[[sa[60], sa[61]], [sa[62],
sa[63]]],
[[sa[64], sa[65]], [sa[66], sa[67]]],
[[sa[68], sa[69]], [sa[70],
sa[71]]]]], [
[[[sa[108], sa[109]], [sa[110], sa[111]]],
[[sa[112], sa[113]], [sa[114],
sa[115]]],
[[sa[116], sa[117]], [sa[118], sa[119]]]],
[[[sa[120], sa[121]], [sa[122],
sa[123]]],
[[sa[124], sa[125]], [sa[126], sa[127]]],
[[sa[128], sa[129]], [sa[130],
sa[131]]]],
[[[sa[132], sa[133]], [sa[134], sa[135]]],
[[sa[136], sa[137]], [sa[138],
sa[139]]],
[[sa[140], sa[141]], [sa[142], sa[143]]]]]]])
assert permutedims(po, (0, 2, 1, 4, 3, 5)) == ArrayType(
[[[[[[sa[0], sa[1]], [sa[4], sa[5]], [sa[8], sa[9]]], [[sa[2], sa[3]], [sa[6], sa[7]], [sa[10],
sa[11]]]],
[[[sa[36], sa[37]], [sa[40], sa[41]], [sa[44], sa[45]]], [[sa[38],
sa[39]], [sa[42], sa[43]], [sa[46], sa[47]]]]],
[[[[sa[12], sa[13]], [sa[16],
sa[17]], [sa[20], sa[21]]], [[sa[14], sa[15]], [sa[18], sa[19]], [sa[22],
sa[23]]]],
[[[sa[48], sa[49]], [sa[52], sa[53]], [sa[56], sa[57]]], [[sa[50],
sa[51]], [sa[54], sa[55]], [sa[58], sa[59]]]]],
[[[[sa[24], sa[25]], [sa[28],
sa[29]], [sa[32], sa[33]]], [[sa[26], sa[27]], [sa[30], sa[31]], [sa[34],
sa[35]]]],
[[[sa[60], sa[61]], [sa[64], sa[65]], [sa[68], sa[69]]], [[sa[62],
sa[63]], [sa[66], sa[67]], [sa[70], sa[71]]]]]],
[[[[[sa[72], sa[73]], [sa[76],
sa[77]], [sa[80], sa[81]]], [[sa[74], sa[75]], [sa[78], sa[79]], [sa[82],
sa[83]]]],
[[[sa[108], sa[109]], [sa[112], sa[113]], [sa[116], sa[117]]], [[sa[110],
sa[111]], [sa[114], sa[115]],
[sa[118], sa[119]]]]],
[[[[sa[84], sa[85]], [sa[88],
sa[89]], [sa[92], sa[93]]], [[sa[86], sa[87]], [sa[90], sa[91]], [sa[94],
sa[95]]]],
[[[sa[120], sa[121]], [sa[124], sa[125]], [sa[128], sa[129]]], [[sa[122],
sa[123]], [sa[126], sa[127]],
[sa[130], sa[131]]]]],
[[[[sa[96], sa[97]], [sa[100],
sa[101]], [sa[104], sa[105]]], [[sa[98], sa[99]], [sa[102], sa[103]], [sa[106],
sa[107]]]],
[[[sa[132], sa[133]], [sa[136], sa[137]], [sa[140], sa[141]]], [[sa[134],
sa[135]], [sa[138], sa[139]],
[sa[142], sa[143]]]]]]])
po2 = po.reshape(4, 9, 2, 2)
assert po2 == ArrayType([[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10], sa[11]]], [[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18], sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]], [[sa[24], sa[25]], [sa[26], sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34], sa[35]]]], [[[sa[36], sa[37]], [sa[38], sa[39]]], [[sa[40], sa[41]], [sa[42], sa[43]]], [[sa[44], sa[45]], [sa[46], sa[47]]], [[sa[48], sa[49]], [sa[50], sa[51]]], [[sa[52], sa[53]], [sa[54], sa[55]]], [[sa[56], sa[57]], [sa[58], sa[59]]], [[sa[60], sa[61]], [sa[62], sa[63]]], [[sa[64], sa[65]], [sa[66], sa[67]]], [[sa[68], sa[69]], [sa[70], sa[71]]]], [[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78], sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]], [[sa[84], sa[85]], [sa[86], sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94], sa[95]]], [[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102], sa[103]]], [[sa[104], sa[105]], [sa[106], sa[107]]]], [[[sa[108], sa[109]], [sa[110], sa[111]]], [[sa[112], sa[113]], [sa[114], sa[115]]], [[sa[116], sa[117]], [sa[118], sa[119]]], [[sa[120], sa[121]], [sa[122], sa[123]]], [[sa[124], sa[125]], [sa[126], sa[127]]], [[sa[128], sa[129]], [sa[130], sa[131]]], [[sa[132], sa[133]], [sa[134], sa[135]]], [[sa[136], sa[137]], [sa[138], sa[139]]], [[sa[140], sa[141]], [sa[142], sa[143]]]]])
assert permutedims(po2, (3, 2, 0, 1)) == ArrayType([[[[sa[0], sa[4], sa[8], sa[12], sa[16], sa[20], sa[24], sa[28], sa[32]], [sa[36], sa[40], sa[44], sa[48], sa[52], sa[56], sa[60], sa[64], sa[68]], [sa[72], sa[76], sa[80], sa[84], sa[88], sa[92], sa[96], sa[100], sa[104]], [sa[108], sa[112], sa[116], sa[120], sa[124], sa[128], sa[132], sa[136], sa[140]]], [[sa[2], sa[6], sa[10], sa[14], sa[18], sa[22], sa[26], sa[30], sa[34]], [sa[38], sa[42], sa[46], sa[50], sa[54], sa[58], sa[62], sa[66], sa[70]], [sa[74], sa[78], sa[82], sa[86], sa[90], sa[94], sa[98], sa[102], sa[106]], [sa[110], sa[114], sa[118], sa[122], sa[126], sa[130], sa[134], sa[138], sa[142]]]], [[[sa[1], sa[5], sa[9], sa[13], sa[17], sa[21], sa[25], sa[29], sa[33]], [sa[37], sa[41], sa[45], sa[49], sa[53], sa[57], sa[61], sa[65], sa[69]], [sa[73], sa[77], sa[81], sa[85], sa[89], sa[93], sa[97], sa[101], sa[105]], [sa[109], sa[113], sa[117], sa[121], sa[125], sa[129], sa[133], sa[137], sa[141]]], [[sa[3], sa[7], sa[11], sa[15], sa[19], sa[23], sa[27], sa[31], sa[35]], [sa[39], sa[43], sa[47], sa[51], sa[55], sa[59], sa[63], sa[67], sa[71]], [sa[75], sa[79], sa[83], sa[87], sa[91], sa[95], sa[99], sa[103], sa[107]], [sa[111], sa[115], sa[119], sa[123], sa[127], sa[131], sa[135], sa[139], sa[143]]]]])
# test for large scale sparse array
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
A = SparseArrayType({1:1, 10000:2}, (10000, 20000, 10000))
assert permutedims(A, (0, 1, 2)) == A
assert permutedims(A, (1, 0, 2)) == SparseArrayType({1: 1, 100000000: 2}, (20000, 10000, 10000))
B = SparseArrayType({1:1, 20000:2}, (10000, 20000))
assert B.transpose() == SparseArrayType({10000: 1, 1: 2}, (20000, 10000))
def test_flatten():
from sympy.matrices.dense import Matrix
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray, Matrix]:
A = ArrayType(range(24)).reshape(4, 6)
assert [i for i in Flatten(A)] == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
for i, v in enumerate(Flatten(A)):
assert i == v
def test_tensordiagonal():
from sympy.matrices.dense import eye
expr = Array(range(9)).reshape(3, 3)
raises(ValueError, lambda: tensordiagonal(expr, [0], [1]))
raises(ValueError, lambda: tensordiagonal(expr, [0, 0]))
assert tensordiagonal(eye(3), [0, 1]) == Array([1, 1, 1])
assert tensordiagonal(expr, [0, 1]) == Array([0, 4, 8])
x, y, z = symbols("x y z")
expr2 = tensorproduct([x, y, z], expr)
assert tensordiagonal(expr2, [1, 2]) == Array([[0, 4*x, 8*x], [0, 4*y, 8*y], [0, 4*z, 8*z]])
assert tensordiagonal(expr2, [0, 1]) == Array([[0, 3*y, 6*z], [x, 4*y, 7*z], [2*x, 5*y, 8*z]])
assert tensordiagonal(expr2, [0, 1, 2]) == Array([0, 4*y, 8*z])
# assert tensordiagonal(expr2, [0]) == permutedims(expr2, [1, 2, 0])
# assert tensordiagonal(expr2, [1]) == permutedims(expr2, [0, 2, 1])
# assert tensordiagonal(expr2, [2]) == expr2
# assert tensordiagonal(expr2, [1], [2]) == expr2
# assert tensordiagonal(expr2, [0], [1]) == permutedims(expr2, [2, 0, 1])
a, b, c, X, Y, Z = symbols("a b c X Y Z")
expr3 = tensorproduct([x, y, z], [1, 2, 3], [a, b, c], [X, Y, Z])
assert tensordiagonal(expr3, [0, 1, 2, 3]) == Array([x*a*X, 2*y*b*Y, 3*z*c*Z])
assert tensordiagonal(expr3, [0, 1], [2, 3]) == tensorproduct([x, 2*y, 3*z], [a*X, b*Y, c*Z])
# assert tensordiagonal(expr3, [0], [1, 2], [3]) == tensorproduct([x, y, z], [a, 2*b, 3*c], [X, Y, Z])
assert tensordiagonal(tensordiagonal(expr3, [2, 3]), [0, 1]) == tensorproduct([a*X, b*Y, c*Z], [x, 2*y, 3*z])
raises(ValueError, lambda: tensordiagonal([[1, 2, 3], [4, 5, 6]], [0, 1]))
raises(ValueError, lambda: tensordiagonal(expr3.reshape(3, 3, 9), [1, 2]))
|
f638bfd78b339feaa82fa0d0e66bb320535a5de7d3ee7e793c58a05e8170939d | from copy import copy
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
from sympy.core.containers import Dict
from sympy.core.function import diff
from sympy.core.numbers import Rational
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.matrices import SparseMatrix
from sympy.tensor.indexed import (Indexed, IndexedBase)
from sympy.matrices import Matrix
from sympy.tensor.array.sparse_ndim_array import ImmutableSparseNDimArray
from sympy.testing.pytest import raises
def test_ndim_array_initiation():
arr_with_no_elements = ImmutableDenseNDimArray([], shape=(0,))
assert len(arr_with_no_elements) == 0
assert arr_with_no_elements.rank() == 1
raises(ValueError, lambda: ImmutableDenseNDimArray([0], shape=(0,)))
raises(ValueError, lambda: ImmutableDenseNDimArray([1, 2, 3], shape=(0,)))
raises(ValueError, lambda: ImmutableDenseNDimArray([], shape=()))
raises(ValueError, lambda: ImmutableSparseNDimArray([0], shape=(0,)))
raises(ValueError, lambda: ImmutableSparseNDimArray([1, 2, 3], shape=(0,)))
raises(ValueError, lambda: ImmutableSparseNDimArray([], shape=()))
arr_with_one_element = ImmutableDenseNDimArray([23])
assert len(arr_with_one_element) == 1
assert arr_with_one_element[0] == 23
assert arr_with_one_element[:] == ImmutableDenseNDimArray([23])
assert arr_with_one_element.rank() == 1
arr_with_symbol_element = ImmutableDenseNDimArray([Symbol('x')])
assert len(arr_with_symbol_element) == 1
assert arr_with_symbol_element[0] == Symbol('x')
assert arr_with_symbol_element[:] == ImmutableDenseNDimArray([Symbol('x')])
assert arr_with_symbol_element.rank() == 1
number5 = 5
vector = ImmutableDenseNDimArray.zeros(number5)
assert len(vector) == number5
assert vector.shape == (number5,)
assert vector.rank() == 1
vector = ImmutableSparseNDimArray.zeros(number5)
assert len(vector) == number5
assert vector.shape == (number5,)
assert vector._sparse_array == Dict()
assert vector.rank() == 1
n_dim_array = ImmutableDenseNDimArray(range(3**4), (3, 3, 3, 3,))
assert len(n_dim_array) == 3 * 3 * 3 * 3
assert n_dim_array.shape == (3, 3, 3, 3)
assert n_dim_array.rank() == 4
array_shape = (3, 3, 3, 3)
sparse_array = ImmutableSparseNDimArray.zeros(*array_shape)
assert len(sparse_array._sparse_array) == 0
assert len(sparse_array) == 3 * 3 * 3 * 3
assert n_dim_array.shape == array_shape
assert n_dim_array.rank() == 4
one_dim_array = ImmutableDenseNDimArray([2, 3, 1])
assert len(one_dim_array) == 3
assert one_dim_array.shape == (3,)
assert one_dim_array.rank() == 1
assert one_dim_array.tolist() == [2, 3, 1]
shape = (3, 3)
array_with_many_args = ImmutableSparseNDimArray.zeros(*shape)
assert len(array_with_many_args) == 3 * 3
assert array_with_many_args.shape == shape
assert array_with_many_args[0, 0] == 0
assert array_with_many_args.rank() == 2
shape = (int(3), int(3))
array_with_long_shape = ImmutableSparseNDimArray.zeros(*shape)
assert len(array_with_long_shape) == 3 * 3
assert array_with_long_shape.shape == shape
assert array_with_long_shape[int(0), int(0)] == 0
assert array_with_long_shape.rank() == 2
vector_with_long_shape = ImmutableDenseNDimArray(range(5), int(5))
assert len(vector_with_long_shape) == 5
assert vector_with_long_shape.shape == (int(5),)
assert vector_with_long_shape.rank() == 1
raises(ValueError, lambda: vector_with_long_shape[int(5)])
from sympy.abc import x
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
rank_zero_array = ArrayType(x)
assert len(rank_zero_array) == 1
assert rank_zero_array.shape == ()
assert rank_zero_array.rank() == 0
assert rank_zero_array[()] == x
raises(ValueError, lambda: rank_zero_array[0])
def test_reshape():
array = ImmutableDenseNDimArray(range(50), 50)
assert array.shape == (50,)
assert array.rank() == 1
array = array.reshape(5, 5, 2)
assert array.shape == (5, 5, 2)
assert array.rank() == 3
assert len(array) == 50
def test_getitem():
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
array = ArrayType(range(24)).reshape(2, 3, 4)
assert array.tolist() == [[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]
assert array[0] == ArrayType([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
assert array[0, 0] == ArrayType([0, 1, 2, 3])
value = 0
for i in range(2):
for j in range(3):
for k in range(4):
assert array[i, j, k] == value
value += 1
raises(ValueError, lambda: array[3, 4, 5])
raises(ValueError, lambda: array[3, 4, 5, 6])
raises(ValueError, lambda: array[3, 4, 5, 3:4])
def test_iterator():
array = ImmutableDenseNDimArray(range(4), (2, 2))
assert array[0] == ImmutableDenseNDimArray([0, 1])
assert array[1] == ImmutableDenseNDimArray([2, 3])
array = array.reshape(4)
j = 0
for i in array:
assert i == j
j += 1
def test_sparse():
sparse_array = ImmutableSparseNDimArray([0, 0, 0, 1], (2, 2))
assert len(sparse_array) == 2 * 2
# dictionary where all data is, only non-zero entries are actually stored:
assert len(sparse_array._sparse_array) == 1
assert sparse_array.tolist() == [[0, 0], [0, 1]]
for i, j in zip(sparse_array, [[0, 0], [0, 1]]):
assert i == ImmutableSparseNDimArray(j)
def sparse_assignment():
sparse_array[0, 0] = 123
assert len(sparse_array._sparse_array) == 1
raises(TypeError, sparse_assignment)
assert len(sparse_array._sparse_array) == 1
assert sparse_array[0, 0] == 0
assert sparse_array/0 == ImmutableSparseNDimArray([[S.NaN, S.NaN], [S.NaN, S.ComplexInfinity]], (2, 2))
# test for large scale sparse array
# equality test
assert ImmutableSparseNDimArray.zeros(100000, 200000) == ImmutableSparseNDimArray.zeros(100000, 200000)
# __mul__ and __rmul__
a = ImmutableSparseNDimArray({200001: 1}, (100000, 200000))
assert a * 3 == ImmutableSparseNDimArray({200001: 3}, (100000, 200000))
assert 3 * a == ImmutableSparseNDimArray({200001: 3}, (100000, 200000))
assert a * 0 == ImmutableSparseNDimArray({}, (100000, 200000))
assert 0 * a == ImmutableSparseNDimArray({}, (100000, 200000))
# __truediv__
assert a/3 == ImmutableSparseNDimArray({200001: Rational(1, 3)}, (100000, 200000))
# __neg__
assert -a == ImmutableSparseNDimArray({200001: -1}, (100000, 200000))
def test_calculation():
a = ImmutableDenseNDimArray([1]*9, (3, 3))
b = ImmutableDenseNDimArray([9]*9, (3, 3))
c = a + b
for i in c:
assert i == ImmutableDenseNDimArray([10, 10, 10])
assert c == ImmutableDenseNDimArray([10]*9, (3, 3))
assert c == ImmutableSparseNDimArray([10]*9, (3, 3))
c = b - a
for i in c:
assert i == ImmutableDenseNDimArray([8, 8, 8])
assert c == ImmutableDenseNDimArray([8]*9, (3, 3))
assert c == ImmutableSparseNDimArray([8]*9, (3, 3))
def test_ndim_array_converting():
dense_array = ImmutableDenseNDimArray([1, 2, 3, 4], (2, 2))
alist = dense_array.tolist()
assert alist == [[1, 2], [3, 4]]
matrix = dense_array.tomatrix()
assert (isinstance(matrix, Matrix))
for i in range(len(dense_array)):
assert dense_array[dense_array._get_tuple_index(i)] == matrix[i]
assert matrix.shape == dense_array.shape
assert ImmutableDenseNDimArray(matrix) == dense_array
assert ImmutableDenseNDimArray(matrix.as_immutable()) == dense_array
assert ImmutableDenseNDimArray(matrix.as_mutable()) == dense_array
sparse_array = ImmutableSparseNDimArray([1, 2, 3, 4], (2, 2))
alist = sparse_array.tolist()
assert alist == [[1, 2], [3, 4]]
matrix = sparse_array.tomatrix()
assert(isinstance(matrix, SparseMatrix))
for i in range(len(sparse_array)):
assert sparse_array[sparse_array._get_tuple_index(i)] == matrix[i]
assert matrix.shape == sparse_array.shape
assert ImmutableSparseNDimArray(matrix) == sparse_array
assert ImmutableSparseNDimArray(matrix.as_immutable()) == sparse_array
assert ImmutableSparseNDimArray(matrix.as_mutable()) == sparse_array
def test_converting_functions():
arr_list = [1, 2, 3, 4]
arr_matrix = Matrix(((1, 2), (3, 4)))
# list
arr_ndim_array = ImmutableDenseNDimArray(arr_list, (2, 2))
assert (isinstance(arr_ndim_array, ImmutableDenseNDimArray))
assert arr_matrix.tolist() == arr_ndim_array.tolist()
# Matrix
arr_ndim_array = ImmutableDenseNDimArray(arr_matrix)
assert (isinstance(arr_ndim_array, ImmutableDenseNDimArray))
assert arr_matrix.tolist() == arr_ndim_array.tolist()
assert arr_matrix.shape == arr_ndim_array.shape
def test_equality():
first_list = [1, 2, 3, 4]
second_list = [1, 2, 3, 4]
third_list = [4, 3, 2, 1]
assert first_list == second_list
assert first_list != third_list
first_ndim_array = ImmutableDenseNDimArray(first_list, (2, 2))
second_ndim_array = ImmutableDenseNDimArray(second_list, (2, 2))
fourth_ndim_array = ImmutableDenseNDimArray(first_list, (2, 2))
assert first_ndim_array == second_ndim_array
def assignment_attempt(a):
a[0, 0] = 0
raises(TypeError, lambda: assignment_attempt(second_ndim_array))
assert first_ndim_array == second_ndim_array
assert first_ndim_array == fourth_ndim_array
def test_arithmetic():
a = ImmutableDenseNDimArray([3 for i in range(9)], (3, 3))
b = ImmutableDenseNDimArray([7 for i in range(9)], (3, 3))
c1 = a + b
c2 = b + a
assert c1 == c2
d1 = a - b
d2 = b - a
assert d1 == d2 * (-1)
e1 = a * 5
e2 = 5 * a
e3 = copy(a)
e3 *= 5
assert e1 == e2 == e3
f1 = a / 5
f2 = copy(a)
f2 /= 5
assert f1 == f2
assert f1[0, 0] == f1[0, 1] == f1[0, 2] == f1[1, 0] == f1[1, 1] == \
f1[1, 2] == f1[2, 0] == f1[2, 1] == f1[2, 2] == Rational(3, 5)
assert type(a) == type(b) == type(c1) == type(c2) == type(d1) == type(d2) \
== type(e1) == type(e2) == type(e3) == type(f1)
z0 = -a
assert z0 == ImmutableDenseNDimArray([-3 for i in range(9)], (3, 3))
def test_higher_dimenions():
m3 = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert m3.tolist() == [[[10, 11, 12, 13],
[14, 15, 16, 17],
[18, 19, 20, 21]],
[[22, 23, 24, 25],
[26, 27, 28, 29],
[30, 31, 32, 33]]]
assert m3._get_tuple_index(0) == (0, 0, 0)
assert m3._get_tuple_index(1) == (0, 0, 1)
assert m3._get_tuple_index(4) == (0, 1, 0)
assert m3._get_tuple_index(12) == (1, 0, 0)
assert str(m3) == '[[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]'
m3_rebuilt = ImmutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]])
assert m3 == m3_rebuilt
m3_other = ImmutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]], (2, 3, 4))
assert m3 == m3_other
def test_rebuild_immutable_arrays():
sparr = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
densarr = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert sparr == sparr.func(*sparr.args)
assert densarr == densarr.func(*densarr.args)
def test_slices():
md = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert md[:] == ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert md[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
assert md[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
assert md[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
assert md[:, :, :] == md
sd = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert sd == ImmutableSparseNDimArray(md)
assert sd[:] == ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert sd[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
assert sd[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
assert sd[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
assert sd[:, :, :] == sd
def test_diff_and_applyfunc():
from sympy.abc import x, y, z
md = ImmutableDenseNDimArray([[x, y], [x*z, x*y*z]])
assert md.diff(x) == ImmutableDenseNDimArray([[1, 0], [z, y*z]])
assert diff(md, x) == ImmutableDenseNDimArray([[1, 0], [z, y*z]])
sd = ImmutableSparseNDimArray(md)
assert sd == ImmutableSparseNDimArray([x, y, x*z, x*y*z], (2, 2))
assert sd.diff(x) == ImmutableSparseNDimArray([[1, 0], [z, y*z]])
assert diff(sd, x) == ImmutableSparseNDimArray([[1, 0], [z, y*z]])
mdn = md.applyfunc(lambda x: x*3)
assert mdn == ImmutableDenseNDimArray([[3*x, 3*y], [3*x*z, 3*x*y*z]])
assert md != mdn
sdn = sd.applyfunc(lambda x: x/2)
assert sdn == ImmutableSparseNDimArray([[x/2, y/2], [x*z/2, x*y*z/2]])
assert sd != sdn
sdp = sd.applyfunc(lambda x: x+1)
assert sdp == ImmutableSparseNDimArray([[x + 1, y + 1], [x*z + 1, x*y*z + 1]])
assert sd != sdp
def test_op_priority():
from sympy.abc import x
md = ImmutableDenseNDimArray([1, 2, 3])
e1 = (1+x)*md
e2 = md*(1+x)
assert e1 == ImmutableDenseNDimArray([1+x, 2+2*x, 3+3*x])
assert e1 == e2
sd = ImmutableSparseNDimArray([1, 2, 3])
e3 = (1+x)*sd
e4 = sd*(1+x)
assert e3 == ImmutableDenseNDimArray([1+x, 2+2*x, 3+3*x])
assert e3 == e4
def test_symbolic_indexing():
x, y, z, w = symbols("x y z w")
M = ImmutableDenseNDimArray([[x, y], [z, w]])
i, j = symbols("i, j")
Mij = M[i, j]
assert isinstance(Mij, Indexed)
Ms = ImmutableSparseNDimArray([[2, 3*x], [4, 5]])
msij = Ms[i, j]
assert isinstance(msij, Indexed)
for oi, oj in [(0, 0), (0, 1), (1, 0), (1, 1)]:
assert Mij.subs({i: oi, j: oj}) == M[oi, oj]
assert msij.subs({i: oi, j: oj}) == Ms[oi, oj]
A = IndexedBase("A", (0, 2))
assert A[0, 0].subs(A, M) == x
assert A[i, j].subs(A, M) == M[i, j]
assert M[i, j].subs(M, A) == A[i, j]
assert isinstance(M[3 * i - 2, j], Indexed)
assert M[3 * i - 2, j].subs({i: 1, j: 0}) == M[1, 0]
assert isinstance(M[i, 0], Indexed)
assert M[i, 0].subs(i, 0) == M[0, 0]
assert M[0, i].subs(i, 1) == M[0, 1]
assert M[i, j].diff(x) == ImmutableDenseNDimArray([[1, 0], [0, 0]])[i, j]
assert Ms[i, j].diff(x) == ImmutableSparseNDimArray([[0, 3], [0, 0]])[i, j]
Mo = ImmutableDenseNDimArray([1, 2, 3])
assert Mo[i].subs(i, 1) == 2
Mos = ImmutableSparseNDimArray([1, 2, 3])
assert Mos[i].subs(i, 1) == 2
raises(ValueError, lambda: M[i, 2])
raises(ValueError, lambda: M[i, -1])
raises(ValueError, lambda: M[2, i])
raises(ValueError, lambda: M[-1, i])
raises(ValueError, lambda: Ms[i, 2])
raises(ValueError, lambda: Ms[i, -1])
raises(ValueError, lambda: Ms[2, i])
raises(ValueError, lambda: Ms[-1, i])
def test_issue_12665():
# Testing Python 3 hash of immutable arrays:
arr = ImmutableDenseNDimArray([1, 2, 3])
# This should NOT raise an exception:
hash(arr)
def test_zeros_without_shape():
arr = ImmutableDenseNDimArray.zeros()
assert arr == ImmutableDenseNDimArray(0)
def test_issue_21870():
a0 = ImmutableDenseNDimArray(0)
assert a0.rank() == 0
a1 = ImmutableDenseNDimArray(a0)
assert a1.rank() == 0
|
ac515ad28d0025880f367a6a8a397dd556fd116da480719073a72ef5fd5f22f6 | from copy import copy
from sympy.tensor.array.dense_ndim_array import MutableDenseNDimArray
from sympy.core.function import diff
from sympy.core.numbers import Rational
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.core.sympify import sympify
from sympy.matrices import SparseMatrix
from sympy.matrices import Matrix
from sympy.tensor.array.sparse_ndim_array import MutableSparseNDimArray
from sympy.testing.pytest import raises
def test_ndim_array_initiation():
arr_with_one_element = MutableDenseNDimArray([23])
assert len(arr_with_one_element) == 1
assert arr_with_one_element[0] == 23
assert arr_with_one_element.rank() == 1
raises(ValueError, lambda: arr_with_one_element[1])
arr_with_symbol_element = MutableDenseNDimArray([Symbol('x')])
assert len(arr_with_symbol_element) == 1
assert arr_with_symbol_element[0] == Symbol('x')
assert arr_with_symbol_element.rank() == 1
number5 = 5
vector = MutableDenseNDimArray.zeros(number5)
assert len(vector) == number5
assert vector.shape == (number5,)
assert vector.rank() == 1
raises(ValueError, lambda: arr_with_one_element[5])
vector = MutableSparseNDimArray.zeros(number5)
assert len(vector) == number5
assert vector.shape == (number5,)
assert vector._sparse_array == {}
assert vector.rank() == 1
n_dim_array = MutableDenseNDimArray(range(3**4), (3, 3, 3, 3,))
assert len(n_dim_array) == 3 * 3 * 3 * 3
assert n_dim_array.shape == (3, 3, 3, 3)
assert n_dim_array.rank() == 4
raises(ValueError, lambda: n_dim_array[0, 0, 0, 3])
raises(ValueError, lambda: n_dim_array[3, 0, 0, 0])
raises(ValueError, lambda: n_dim_array[3**4])
array_shape = (3, 3, 3, 3)
sparse_array = MutableSparseNDimArray.zeros(*array_shape)
assert len(sparse_array._sparse_array) == 0
assert len(sparse_array) == 3 * 3 * 3 * 3
assert n_dim_array.shape == array_shape
assert n_dim_array.rank() == 4
one_dim_array = MutableDenseNDimArray([2, 3, 1])
assert len(one_dim_array) == 3
assert one_dim_array.shape == (3,)
assert one_dim_array.rank() == 1
assert one_dim_array.tolist() == [2, 3, 1]
shape = (3, 3)
array_with_many_args = MutableSparseNDimArray.zeros(*shape)
assert len(array_with_many_args) == 3 * 3
assert array_with_many_args.shape == shape
assert array_with_many_args[0, 0] == 0
assert array_with_many_args.rank() == 2
shape = (int(3), int(3))
array_with_long_shape = MutableSparseNDimArray.zeros(*shape)
assert len(array_with_long_shape) == 3 * 3
assert array_with_long_shape.shape == shape
assert array_with_long_shape[int(0), int(0)] == 0
assert array_with_long_shape.rank() == 2
vector_with_long_shape = MutableDenseNDimArray(range(5), int(5))
assert len(vector_with_long_shape) == 5
assert vector_with_long_shape.shape == (int(5),)
assert vector_with_long_shape.rank() == 1
raises(ValueError, lambda: vector_with_long_shape[int(5)])
from sympy.abc import x
for ArrayType in [MutableDenseNDimArray, MutableSparseNDimArray]:
rank_zero_array = ArrayType(x)
assert len(rank_zero_array) == 1
assert rank_zero_array.shape == ()
assert rank_zero_array.rank() == 0
assert rank_zero_array[()] == x
raises(ValueError, lambda: rank_zero_array[0])
def test_sympify():
from sympy.abc import x, y, z, t
arr = MutableDenseNDimArray([[x, y], [1, z*t]])
arr_other = sympify(arr)
assert arr_other.shape == (2, 2)
assert arr_other == arr
def test_reshape():
array = MutableDenseNDimArray(range(50), 50)
assert array.shape == (50,)
assert array.rank() == 1
array = array.reshape(5, 5, 2)
assert array.shape == (5, 5, 2)
assert array.rank() == 3
assert len(array) == 50
def test_iterator():
array = MutableDenseNDimArray(range(4), (2, 2))
assert array[0] == MutableDenseNDimArray([0, 1])
assert array[1] == MutableDenseNDimArray([2, 3])
array = array.reshape(4)
j = 0
for i in array:
assert i == j
j += 1
def test_getitem():
for ArrayType in [MutableDenseNDimArray, MutableSparseNDimArray]:
array = ArrayType(range(24)).reshape(2, 3, 4)
assert array.tolist() == [[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]
assert array[0] == ArrayType([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
assert array[0, 0] == ArrayType([0, 1, 2, 3])
value = 0
for i in range(2):
for j in range(3):
for k in range(4):
assert array[i, j, k] == value
value += 1
raises(ValueError, lambda: array[3, 4, 5])
raises(ValueError, lambda: array[3, 4, 5, 6])
raises(ValueError, lambda: array[3, 4, 5, 3:4])
def test_sparse():
sparse_array = MutableSparseNDimArray([0, 0, 0, 1], (2, 2))
assert len(sparse_array) == 2 * 2
# dictionary where all data is, only non-zero entries are actually stored:
assert len(sparse_array._sparse_array) == 1
assert sparse_array.tolist() == [[0, 0], [0, 1]]
for i, j in zip(sparse_array, [[0, 0], [0, 1]]):
assert i == MutableSparseNDimArray(j)
sparse_array[0, 0] = 123
assert len(sparse_array._sparse_array) == 2
assert sparse_array[0, 0] == 123
assert sparse_array/0 == MutableSparseNDimArray([[S.ComplexInfinity, S.NaN], [S.NaN, S.ComplexInfinity]], (2, 2))
# when element in sparse array become zero it will disappear from
# dictionary
sparse_array[0, 0] = 0
assert len(sparse_array._sparse_array) == 1
sparse_array[1, 1] = 0
assert len(sparse_array._sparse_array) == 0
assert sparse_array[0, 0] == 0
# test for large scale sparse array
# equality test
a = MutableSparseNDimArray.zeros(100000, 200000)
b = MutableSparseNDimArray.zeros(100000, 200000)
assert a == b
a[1, 1] = 1
b[1, 1] = 2
assert a != b
# __mul__ and __rmul__
assert a * 3 == MutableSparseNDimArray({200001: 3}, (100000, 200000))
assert 3 * a == MutableSparseNDimArray({200001: 3}, (100000, 200000))
assert a * 0 == MutableSparseNDimArray({}, (100000, 200000))
assert 0 * a == MutableSparseNDimArray({}, (100000, 200000))
# __truediv__
assert a/3 == MutableSparseNDimArray({200001: Rational(1, 3)}, (100000, 200000))
# __neg__
assert -a == MutableSparseNDimArray({200001: -1}, (100000, 200000))
def test_calculation():
a = MutableDenseNDimArray([1]*9, (3, 3))
b = MutableDenseNDimArray([9]*9, (3, 3))
c = a + b
for i in c:
assert i == MutableDenseNDimArray([10, 10, 10])
assert c == MutableDenseNDimArray([10]*9, (3, 3))
assert c == MutableSparseNDimArray([10]*9, (3, 3))
c = b - a
for i in c:
assert i == MutableSparseNDimArray([8, 8, 8])
assert c == MutableDenseNDimArray([8]*9, (3, 3))
assert c == MutableSparseNDimArray([8]*9, (3, 3))
def test_ndim_array_converting():
dense_array = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
alist = dense_array.tolist()
assert alist == [[1, 2], [3, 4]]
matrix = dense_array.tomatrix()
assert (isinstance(matrix, Matrix))
for i in range(len(dense_array)):
assert dense_array[dense_array._get_tuple_index(i)] == matrix[i]
assert matrix.shape == dense_array.shape
assert MutableDenseNDimArray(matrix) == dense_array
assert MutableDenseNDimArray(matrix.as_immutable()) == dense_array
assert MutableDenseNDimArray(matrix.as_mutable()) == dense_array
sparse_array = MutableSparseNDimArray([1, 2, 3, 4], (2, 2))
alist = sparse_array.tolist()
assert alist == [[1, 2], [3, 4]]
matrix = sparse_array.tomatrix()
assert(isinstance(matrix, SparseMatrix))
for i in range(len(sparse_array)):
assert sparse_array[sparse_array._get_tuple_index(i)] == matrix[i]
assert matrix.shape == sparse_array.shape
assert MutableSparseNDimArray(matrix) == sparse_array
assert MutableSparseNDimArray(matrix.as_immutable()) == sparse_array
assert MutableSparseNDimArray(matrix.as_mutable()) == sparse_array
def test_converting_functions():
arr_list = [1, 2, 3, 4]
arr_matrix = Matrix(((1, 2), (3, 4)))
# list
arr_ndim_array = MutableDenseNDimArray(arr_list, (2, 2))
assert (isinstance(arr_ndim_array, MutableDenseNDimArray))
assert arr_matrix.tolist() == arr_ndim_array.tolist()
# Matrix
arr_ndim_array = MutableDenseNDimArray(arr_matrix)
assert (isinstance(arr_ndim_array, MutableDenseNDimArray))
assert arr_matrix.tolist() == arr_ndim_array.tolist()
assert arr_matrix.shape == arr_ndim_array.shape
def test_equality():
first_list = [1, 2, 3, 4]
second_list = [1, 2, 3, 4]
third_list = [4, 3, 2, 1]
assert first_list == second_list
assert first_list != third_list
first_ndim_array = MutableDenseNDimArray(first_list, (2, 2))
second_ndim_array = MutableDenseNDimArray(second_list, (2, 2))
third_ndim_array = MutableDenseNDimArray(third_list, (2, 2))
fourth_ndim_array = MutableDenseNDimArray(first_list, (2, 2))
assert first_ndim_array == second_ndim_array
second_ndim_array[0, 0] = 0
assert first_ndim_array != second_ndim_array
assert first_ndim_array != third_ndim_array
assert first_ndim_array == fourth_ndim_array
def test_arithmetic():
a = MutableDenseNDimArray([3 for i in range(9)], (3, 3))
b = MutableDenseNDimArray([7 for i in range(9)], (3, 3))
c1 = a + b
c2 = b + a
assert c1 == c2
d1 = a - b
d2 = b - a
assert d1 == d2 * (-1)
e1 = a * 5
e2 = 5 * a
e3 = copy(a)
e3 *= 5
assert e1 == e2 == e3
f1 = a / 5
f2 = copy(a)
f2 /= 5
assert f1 == f2
assert f1[0, 0] == f1[0, 1] == f1[0, 2] == f1[1, 0] == f1[1, 1] == \
f1[1, 2] == f1[2, 0] == f1[2, 1] == f1[2, 2] == Rational(3, 5)
assert type(a) == type(b) == type(c1) == type(c2) == type(d1) == type(d2) \
== type(e1) == type(e2) == type(e3) == type(f1)
z0 = -a
assert z0 == MutableDenseNDimArray([-3 for i in range(9)], (3, 3))
def test_higher_dimenions():
m3 = MutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert m3.tolist() == [[[10, 11, 12, 13],
[14, 15, 16, 17],
[18, 19, 20, 21]],
[[22, 23, 24, 25],
[26, 27, 28, 29],
[30, 31, 32, 33]]]
assert m3._get_tuple_index(0) == (0, 0, 0)
assert m3._get_tuple_index(1) == (0, 0, 1)
assert m3._get_tuple_index(4) == (0, 1, 0)
assert m3._get_tuple_index(12) == (1, 0, 0)
assert str(m3) == '[[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]'
m3_rebuilt = MutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]])
assert m3 == m3_rebuilt
m3_other = MutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]], (2, 3, 4))
assert m3 == m3_other
def test_slices():
md = MutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert md[:] == MutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert md[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
assert md[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
assert md[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
assert md[:, :, :] == md
sd = MutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert sd == MutableSparseNDimArray(md)
assert sd[:] == MutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert sd[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
assert sd[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
assert sd[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
assert sd[:, :, :] == sd
def test_slices_assign():
a = MutableDenseNDimArray(range(12), shape=(4, 3))
b = MutableSparseNDimArray(range(12), shape=(4, 3))
for i in [a, b]:
assert i.tolist() == [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
i[0, :] = [2, 2, 2]
assert i.tolist() == [[2, 2, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
i[0, 1:] = [8, 8]
assert i.tolist() == [[2, 8, 8], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
i[1:3, 1] = [20, 44]
assert i.tolist() == [[2, 8, 8], [3, 20, 5], [6, 44, 8], [9, 10, 11]]
def test_diff():
from sympy.abc import x, y, z
md = MutableDenseNDimArray([[x, y], [x*z, x*y*z]])
assert md.diff(x) == MutableDenseNDimArray([[1, 0], [z, y*z]])
assert diff(md, x) == MutableDenseNDimArray([[1, 0], [z, y*z]])
sd = MutableSparseNDimArray(md)
assert sd == MutableSparseNDimArray([x, y, x*z, x*y*z], (2, 2))
assert sd.diff(x) == MutableSparseNDimArray([[1, 0], [z, y*z]])
assert diff(sd, x) == MutableSparseNDimArray([[1, 0], [z, y*z]])
|
7b74a29fe60eda7791f7628f7320f86fc7f948f6d5e6f2da1b34651fb722d15b | from collections import defaultdict
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.mul import Mul
from sympy.core.numbers import Integer
from sympy.core.power import Pow
from sympy.core.sorting import default_sort_key
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.tensor.indexed import (Indexed, IndexedBase)
from sympy.combinatorics import Permutation
from sympy.matrices.expressions.matexpr import MatrixElement
from sympy.tensor.array.expressions.array_expressions import ArrayDiagonal, \
get_shape, ArrayElement, _array_tensor_product, _array_diagonal, _array_contraction, _array_add, \
_permute_dims
from sympy.tensor.array.expressions.utils import _get_argindex, _get_diagonal_indices
def convert_indexed_to_array(expr, first_indices=None):
r"""
Parse indexed expression into a form useful for code generation.
Examples
========
>>> from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array
>>> from sympy import MatrixSymbol, Sum, symbols
>>> i, j, k, d = symbols("i j k d")
>>> M = MatrixSymbol("M", d, d)
>>> N = MatrixSymbol("N", d, d)
Recognize the trace in summation form:
>>> expr = Sum(M[i, i], (i, 0, d-1))
>>> convert_indexed_to_array(expr)
ArrayContraction(M, (0, 1))
Recognize the extraction of the diagonal by using the same index `i` on
both axes of the matrix:
>>> expr = M[i, i]
>>> convert_indexed_to_array(expr)
ArrayDiagonal(M, (0, 1))
This function can help perform the transformation expressed in two
different mathematical notations as:
`\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}`
Recognize the matrix multiplication in summation form:
>>> expr = Sum(M[i, j]*N[j, k], (j, 0, d-1))
>>> convert_indexed_to_array(expr)
ArrayContraction(ArrayTensorProduct(M, N), (1, 2))
Specify that ``k`` has to be the starting index:
>>> convert_indexed_to_array(expr, first_indices=[k])
ArrayContraction(ArrayTensorProduct(N, M), (0, 3))
"""
result, indices = _convert_indexed_to_array(expr)
if any(isinstance(i, (int, Integer)) for i in indices):
result = ArrayElement(result, indices)
indices = []
if not first_indices:
return result
def _check_is_in(elem, indices):
if elem in indices:
return True
if any(elem in i for i in indices if isinstance(i, frozenset)):
return True
return False
repl = {j: i for i in indices if isinstance(i, frozenset) for j in i}
first_indices = [repl.get(i, i) for i in first_indices]
for i in first_indices:
if not _check_is_in(i, indices):
first_indices.remove(i)
first_indices.extend([i for i in indices if not _check_is_in(i, first_indices)])
def _get_pos(elem, indices):
if elem in indices:
return indices.index(elem)
for i, e in enumerate(indices):
if not isinstance(e, frozenset):
continue
if elem in e:
return i
raise ValueError("not found")
permutation = [_get_pos(i, first_indices) for i in indices]
return _permute_dims(result, permutation)
def _convert_indexed_to_array(expr):
if isinstance(expr, Sum):
function = expr.function
summation_indices = expr.variables
subexpr, subindices = _convert_indexed_to_array(function)
subindicessets = {j: i for i in subindices if isinstance(i, frozenset) for j in i}
summation_indices = sorted(set([subindicessets.get(i, i) for i in summation_indices]), key=default_sort_key)
# TODO: check that Kronecker delta is only contracted to one other element:
kronecker_indices = set([])
if isinstance(function, Mul):
for arg in function.args:
if not isinstance(arg, KroneckerDelta):
continue
arg_indices = sorted(set(arg.indices), key=default_sort_key)
if len(arg_indices) == 2:
kronecker_indices.update(arg_indices)
kronecker_indices = sorted(kronecker_indices, key=default_sort_key)
# Check dimensional consistency:
shape = get_shape(subexpr)
if shape:
for ind, istart, iend in expr.limits:
i = _get_argindex(subindices, ind)
if istart != 0 or iend+1 != shape[i]:
raise ValueError("summation index and array dimension mismatch: %s" % ind)
contraction_indices = []
subindices = list(subindices)
if isinstance(subexpr, ArrayDiagonal):
diagonal_indices = list(subexpr.diagonal_indices)
dindices = subindices[-len(diagonal_indices):]
subindices = subindices[:-len(diagonal_indices)]
for index in summation_indices:
if index in dindices:
position = dindices.index(index)
contraction_indices.append(diagonal_indices[position])
diagonal_indices[position] = None
diagonal_indices = [i for i in diagonal_indices if i is not None]
for i, ind in enumerate(subindices):
if ind in summation_indices:
pass
if diagonal_indices:
subexpr = _array_diagonal(subexpr.expr, *diagonal_indices)
else:
subexpr = subexpr.expr
axes_contraction = defaultdict(list)
for i, ind in enumerate(subindices):
include = all(j not in kronecker_indices for j in ind) if isinstance(ind, frozenset) else ind not in kronecker_indices
if ind in summation_indices and include:
axes_contraction[ind].append(i)
subindices[i] = None
for k, v in axes_contraction.items():
if any(i in kronecker_indices for i in k) if isinstance(k, frozenset) else k in kronecker_indices:
continue
contraction_indices.append(tuple(v))
free_indices = [i for i in subindices if i is not None]
indices_ret = list(free_indices)
indices_ret.sort(key=lambda x: free_indices.index(x))
return _array_contraction(
subexpr,
*contraction_indices,
free_indices=free_indices
), tuple(indices_ret)
if isinstance(expr, Mul):
args, indices = zip(*[_convert_indexed_to_array(arg) for arg in expr.args])
# Check if there are KroneckerDelta objects:
kronecker_delta_repl = {}
for arg in args:
if not isinstance(arg, KroneckerDelta):
continue
# Diagonalize two indices:
i, j = arg.indices
kindices = set(arg.indices)
if i in kronecker_delta_repl:
kindices.update(kronecker_delta_repl[i])
if j in kronecker_delta_repl:
kindices.update(kronecker_delta_repl[j])
kindices = frozenset(kindices)
for index in kindices:
kronecker_delta_repl[index] = kindices
# Remove KroneckerDelta objects, their relations should be handled by
# ArrayDiagonal:
newargs = []
newindices = []
for arg, loc_indices in zip(args, indices):
if isinstance(arg, KroneckerDelta):
continue
newargs.append(arg)
newindices.append(loc_indices)
flattened_indices = [kronecker_delta_repl.get(j, j) for i in newindices for j in i]
diagonal_indices, ret_indices = _get_diagonal_indices(flattened_indices)
tp = _array_tensor_product(*newargs)
if diagonal_indices:
return _array_diagonal(tp, *diagonal_indices), ret_indices
else:
return tp, ret_indices
if isinstance(expr, MatrixElement):
indices = expr.args[1:]
diagonal_indices, ret_indices = _get_diagonal_indices(indices)
if diagonal_indices:
return _array_diagonal(expr.args[0], *diagonal_indices), ret_indices
else:
return expr.args[0], ret_indices
if isinstance(expr, Indexed):
indices = expr.indices
diagonal_indices, ret_indices = _get_diagonal_indices(indices)
if diagonal_indices:
return _array_diagonal(expr.base, *diagonal_indices), ret_indices
else:
return expr.args[0], ret_indices
if isinstance(expr, IndexedBase):
raise NotImplementedError
if isinstance(expr, KroneckerDelta):
return expr, expr.indices
if isinstance(expr, Add):
args, indices = zip(*[_convert_indexed_to_array(arg) for arg in expr.args])
args = list(args)
# Check if all indices are compatible. Otherwise expand the dimensions:
index0set = set(indices[0])
index0 = indices[0]
for i in range(1, len(args)):
if set(indices[i]) != index0set:
raise NotImplementedError("indices must be the same")
permutation = Permutation([index0.index(j) for j in indices[i]])
# Perform index permutations:
args[i] = _permute_dims(args[i], permutation)
return _array_add(*args), index0
if isinstance(expr, Pow):
subexpr, subindices = _convert_indexed_to_array(expr.base)
if isinstance(expr.exp, (int, Integer)):
diags = zip(*[(2*i, 2*i + 1) for i in range(expr.exp)])
arr = _array_diagonal(_array_tensor_product(*[subexpr for i in range(expr.exp)]), *diags)
return arr, subindices
return expr, ()
|
e156993571d3136a23952da3d7f38571c43c2809b048df24cbd5c193eb79df94 | import itertools
from collections import defaultdict
from typing import Tuple as tTuple, Union as tUnion, FrozenSet, Dict as tDict, List, Optional
from functools import singledispatch
from itertools import accumulate
from sympy import MatMul, Basic, Wild
from sympy.assumptions.ask import (Q, ask)
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.matrices.expressions.diagonal import DiagMatrix
from sympy.matrices.expressions.hadamard import hadamard_product, HadamardPower
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.matrices.expressions.special import (Identity, ZeroMatrix, OneMatrix)
from sympy.matrices.expressions.trace import Trace
from sympy.matrices.expressions.transpose import Transpose
from sympy.combinatorics.permutations import _af_invert, Permutation
from sympy.matrices.common import MatrixCommon
from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
from sympy.matrices.expressions.matexpr import MatrixElement
from sympy.tensor.array.expressions.array_expressions import PermuteDims, ArrayDiagonal, \
ArrayTensorProduct, OneArray, get_rank, _get_subrank, ZeroArray, ArrayContraction, \
ArrayAdd, _CodegenArrayAbstract, get_shape, ArrayElementwiseApplyFunc, _ArrayExpr, _EditArrayContraction, _ArgE, \
ArrayElement, _array_tensor_product, _array_contraction, _array_diagonal, _array_add, _permute_dims
from sympy.tensor.array.expressions.utils import _get_mapping_from_subranks
def _get_candidate_for_matmul_from_contraction(scan_indices: List[Optional[int]], remaining_args: List[_ArgE]) -> tTuple[Optional[_ArgE], bool, int]:
scan_indices_int: List[int] = [i for i in scan_indices if i is not None]
if len(scan_indices_int) == 0:
return None, False, -1
transpose: bool = False
candidate: Optional[_ArgE] = None
candidate_index: int = -1
for arg_with_ind2 in remaining_args:
if not isinstance(arg_with_ind2.element, MatrixExpr):
continue
for index in scan_indices_int:
if candidate_index != -1 and candidate_index != index:
# A candidate index has already been selected, check
# repetitions only for that index:
continue
if index in arg_with_ind2.indices:
if set(arg_with_ind2.indices) == {index}:
# Index repeated twice in arg_with_ind2
candidate = None
break
if candidate is None:
candidate = arg_with_ind2
candidate_index = index
transpose = (index == arg_with_ind2.indices[1])
else:
# Index repeated more than twice, break
candidate = None
break
return candidate, transpose, candidate_index
def _insert_candidate_into_editor(editor: _EditArrayContraction, arg_with_ind: _ArgE, candidate: _ArgE, transpose1: bool, transpose2: bool):
other = candidate.element
other_index: Optional[int]
if transpose2:
other = Transpose(other)
other_index = candidate.indices[0]
else:
other_index = candidate.indices[1]
new_element = (Transpose(arg_with_ind.element) if transpose1 else arg_with_ind.element) * other
editor.args_with_ind.remove(candidate)
new_arge = _ArgE(new_element)
return new_arge, other_index
def _support_function_tp1_recognize(contraction_indices, args):
if len(contraction_indices) == 0:
return _a2m_tensor_product(*args)
ac = _array_contraction(_array_tensor_product(*args), *contraction_indices)
editor = _EditArrayContraction(ac)
editor.track_permutation_start()
while True:
flag_stop: bool = True
for i, arg_with_ind in enumerate(editor.args_with_ind):
if not isinstance(arg_with_ind.element, MatrixExpr):
continue
first_index = arg_with_ind.indices[0]
second_index = arg_with_ind.indices[1]
first_frequency = editor.count_args_with_index(first_index)
second_frequency = editor.count_args_with_index(second_index)
if first_index is not None and first_frequency == 1 and first_index == second_index:
flag_stop = False
arg_with_ind.element = Trace(arg_with_ind.element)._normalize()
arg_with_ind.indices = []
break
scan_indices = []
if first_frequency == 2:
scan_indices.append(first_index)
if second_frequency == 2:
scan_indices.append(second_index)
candidate, transpose, found_index = _get_candidate_for_matmul_from_contraction(scan_indices, editor.args_with_ind[i+1:])
if candidate is not None:
flag_stop = False
editor.track_permutation_merge(arg_with_ind, candidate)
transpose1 = found_index == first_index
new_arge, other_index = _insert_candidate_into_editor(editor, arg_with_ind, candidate, transpose1, transpose)
if found_index == first_index:
new_arge.indices = [second_index, other_index]
else:
new_arge.indices = [first_index, other_index]
set_indices = set(new_arge.indices)
if len(set_indices) == 1 and set_indices != {None}:
# This is a trace:
new_arge.element = Trace(new_arge.element)._normalize()
new_arge.indices = []
editor.args_with_ind[i] = new_arge
# TODO: is this break necessary?
break
if flag_stop:
break
editor.refresh_indices()
return editor.to_array_contraction()
def _find_trivial_matrices_rewrite(expr: ArrayTensorProduct):
# If there are matrices of trivial shape in the tensor product (i.e. shape
# (1, 1)), try to check if there is a suitable non-trivial MatMul where the
# expression can be inserted.
# For example, if "a" has shape (1, 1) and "b" has shape (k, 1), the
# expressions "_array_tensor_product(a, b*b.T)" can be rewritten as
# "b*a*b.T"
trivial_matrices = []
pos: Optional[int] = None
first: Optional[MatrixExpr] = None
second: Optional[MatrixExpr] = None
removed: List[int] = []
counter: int = 0
args: List[Optional[Basic]] = [i for i in expr.args]
for i, arg in enumerate(expr.args):
if isinstance(arg, MatrixExpr):
if arg.shape == (1, 1):
trivial_matrices.append(arg)
args[i] = None
removed.extend([counter, counter+1])
elif pos is None and isinstance(arg, MatMul):
margs = arg.args
for j, e in enumerate(margs):
if isinstance(e, MatrixExpr) and e.shape[1] == 1:
pos = i
first = MatMul.fromiter(margs[:j+1])
second = MatMul.fromiter(margs[j+1:])
break
counter += get_rank(arg)
if pos is None:
return expr, []
args[pos] = (first*MatMul.fromiter(i for i in trivial_matrices)*second).doit()
return _array_tensor_product(*[i for i in args if i is not None]), removed
@singledispatch
def _array2matrix(expr):
return expr
@_array2matrix.register(ZeroArray) # type: ignore
def _(expr: ZeroArray):
if get_rank(expr) == 2:
return ZeroMatrix(*expr.shape)
else:
return expr
@_array2matrix.register(ArrayTensorProduct) # type: ignore
def _(expr: ArrayTensorProduct):
return _a2m_tensor_product(*[_array2matrix(arg) for arg in expr.args])
@_array2matrix.register(ArrayContraction) # type: ignore
def _(expr: ArrayContraction):
expr = expr.flatten_contraction_of_diagonal()
expr = identify_removable_identity_matrices(expr)
expr = expr.split_multiple_contractions()
expr = identify_hadamard_products(expr)
if not isinstance(expr, ArrayContraction):
return _array2matrix(expr)
subexpr = expr.expr
contraction_indices: tTuple[tTuple[int]] = expr.contraction_indices
if contraction_indices == ((0,), (1,)) or (
contraction_indices == ((0,),) and subexpr.shape[1] == 1
) or (
contraction_indices == ((1,),) and subexpr.shape[0] == 1
):
shape = subexpr.shape
subexpr = _array2matrix(subexpr)
if isinstance(subexpr, MatrixExpr):
return OneMatrix(1, shape[0])*subexpr*OneMatrix(shape[1], 1)
if isinstance(subexpr, ArrayTensorProduct):
newexpr = _array_contraction(_array2matrix(subexpr), *contraction_indices)
contraction_indices = newexpr.contraction_indices
if any(i > 2 for i in newexpr.subranks):
addends = _array_add(*[_a2m_tensor_product(*j) for j in itertools.product(*[i.args if isinstance(i,
ArrayAdd) else [i] for i in expr.expr.args])])
newexpr = _array_contraction(addends, *contraction_indices)
if isinstance(newexpr, ArrayAdd):
ret = _array2matrix(newexpr)
return ret
assert isinstance(newexpr, ArrayContraction)
ret = _support_function_tp1_recognize(contraction_indices, list(newexpr.expr.args))
return ret
elif not isinstance(subexpr, _CodegenArrayAbstract):
ret = _array2matrix(subexpr)
if isinstance(ret, MatrixExpr):
assert expr.contraction_indices == ((0, 1),)
return _a2m_trace(ret)
else:
return _array_contraction(ret, *expr.contraction_indices)
@_array2matrix.register(ArrayDiagonal) # type: ignore
def _(expr: ArrayDiagonal):
pexpr = _array_diagonal(_array2matrix(expr.expr), *expr.diagonal_indices)
pexpr = identify_hadamard_products(pexpr)
if isinstance(pexpr, ArrayDiagonal):
pexpr = _array_diag2contr_diagmatrix(pexpr)
if expr == pexpr:
return expr
return _array2matrix(pexpr)
@_array2matrix.register(PermuteDims) # type: ignore
def _(expr: PermuteDims):
if expr.permutation.array_form == [1, 0]:
return _a2m_transpose(_array2matrix(expr.expr))
elif isinstance(expr.expr, ArrayTensorProduct):
ranks = expr.expr.subranks
inv_permutation = expr.permutation**(-1)
newrange = [inv_permutation(i) for i in range(sum(ranks))]
newpos = []
counter = 0
for rank in ranks:
newpos.append(newrange[counter:counter+rank])
counter += rank
newargs = []
newperm = []
scalars = []
for pos, arg in zip(newpos, expr.expr.args):
if len(pos) == 0:
scalars.append(_array2matrix(arg))
elif pos == sorted(pos):
newargs.append((_array2matrix(arg), pos[0]))
newperm.extend(pos)
elif len(pos) == 2:
newargs.append((_a2m_transpose(_array2matrix(arg)), pos[0]))
newperm.extend(reversed(pos))
else:
raise NotImplementedError()
newargs = [i[0] for i in newargs]
return _permute_dims(_a2m_tensor_product(*scalars, *newargs), _af_invert(newperm))
elif isinstance(expr.expr, ArrayContraction):
mat_mul_lines = _array2matrix(expr.expr)
if not isinstance(mat_mul_lines, ArrayTensorProduct):
flat_cyclic_form = [j for i in expr.permutation.cyclic_form for j in i]
expr_shape = get_shape(expr)
if all(expr_shape[i] == 1 for i in flat_cyclic_form):
return mat_mul_lines
return mat_mul_lines
# TODO: this assumes that all arguments are matrices, it may not be the case:
permutation = Permutation(2*len(mat_mul_lines.args)-1)*expr.permutation
permuted = [permutation(i) for i in range(2*len(mat_mul_lines.args))]
args_array = [None for i in mat_mul_lines.args]
for i in range(len(mat_mul_lines.args)):
p1 = permuted[2*i]
p2 = permuted[2*i+1]
if p1 // 2 != p2 // 2:
return _permute_dims(mat_mul_lines, permutation)
pos = p1 // 2
if p1 > p2:
args_array[i] = _a2m_transpose(mat_mul_lines.args[pos]) # type: ignore
else:
args_array[i] = mat_mul_lines.args[pos] # type: ignore
return _a2m_tensor_product(*args_array)
else:
return expr
@_array2matrix.register(ArrayAdd) # type: ignore
def _(expr: ArrayAdd):
addends = [_array2matrix(arg) for arg in expr.args]
return _a2m_add(*addends)
@_array2matrix.register(ArrayElementwiseApplyFunc) # type: ignore
def _(expr: ArrayElementwiseApplyFunc):
subexpr = _array2matrix(expr.expr)
if isinstance(subexpr, MatrixExpr):
if subexpr.shape != (1, 1):
d = expr.function.bound_symbols[0]
w = Wild("w", exclude=[d])
p = Wild("p", exclude=[d])
m = expr.function.expr.match(w*d**p)
if m is not None:
return m[w]*HadamardPower(subexpr, m[p])
return ElementwiseApplyFunction(expr.function, subexpr)
else:
return ArrayElementwiseApplyFunc(expr.function, subexpr)
@_array2matrix.register(ArrayElement) # type: ignore
def _(expr: ArrayElement):
ret = _array2matrix(expr.name)
if isinstance(ret, MatrixExpr):
return MatrixElement(ret, *expr.indices)
return ArrayElement(ret, expr.indices)
@singledispatch
def _remove_trivial_dims(expr):
return expr, []
@_remove_trivial_dims.register(ArrayTensorProduct) # type: ignore
def _(expr: ArrayTensorProduct):
# Recognize expressions like [x, y] with shape (k, 1, k, 1) as `x*y.T`.
# The matrix expression has to be equivalent to the tensor product of the
# matrices, with trivial dimensions (i.e. dim=1) dropped.
# That is, add contractions over trivial dimensions:
removed = []
newargs = []
cumul = list(accumulate([0] + [get_rank(arg) for arg in expr.args]))
pending = None
prev_i = None
for i, arg in enumerate(expr.args):
current_range = list(range(cumul[i], cumul[i+1]))
if isinstance(arg, OneArray):
removed.extend(current_range)
continue
if not isinstance(arg, (MatrixExpr, MatrixCommon)):
rarg, rem = _remove_trivial_dims(arg)
removed.extend(rem)
newargs.append(rarg)
continue
elif getattr(arg, "is_Identity", False) and arg.shape == (1, 1):
if arg.shape == (1, 1):
# Ignore identity matrices of shape (1, 1) - they are equivalent to scalar 1.
removed.extend(current_range)
continue
elif arg.shape == (1, 1):
arg, _ = _remove_trivial_dims(arg)
# Matrix is equivalent to scalar:
if len(newargs) == 0:
newargs.append(arg)
elif 1 in get_shape(newargs[-1]):
if newargs[-1].shape[1] == 1:
newargs[-1] = newargs[-1]*arg
else:
newargs[-1] = arg*newargs[-1]
removed.extend(current_range)
else:
newargs.append(arg)
elif 1 in arg.shape:
k = [i for i in arg.shape if i != 1][0]
if pending is None:
pending = k
prev_i = i
newargs.append(arg)
elif pending == k:
prev = newargs[-1]
if prev.shape[0] == 1:
d1 = cumul[prev_i]
prev = _a2m_transpose(prev)
else:
d1 = cumul[prev_i] + 1
if arg.shape[1] == 1:
d2 = cumul[i] + 1
arg = _a2m_transpose(arg)
else:
d2 = cumul[i]
newargs[-1] = prev*arg
pending = None
removed.extend([d1, d2])
else:
newargs.append(arg)
pending = k
prev_i = i
else:
newargs.append(arg)
pending = None
newexpr, newremoved = _a2m_tensor_product(*newargs), sorted(removed)
if isinstance(newexpr, ArrayTensorProduct):
newexpr, newremoved2 = _find_trivial_matrices_rewrite(newexpr)
newremoved = _combine_removed(-1, newremoved, newremoved2)
return newexpr, newremoved
@_remove_trivial_dims.register(ArrayAdd) # type: ignore
def _(expr: ArrayAdd):
rec = [_remove_trivial_dims(arg) for arg in expr.args]
newargs, removed = zip(*rec)
if len(set(map(tuple, removed))) != 1:
return expr, []
return _a2m_add(*newargs), removed[0]
@_remove_trivial_dims.register(PermuteDims) # type: ignore
def _(expr: PermuteDims):
subexpr, subremoved = _remove_trivial_dims(expr.expr)
p = expr.permutation.array_form
pinv = _af_invert(expr.permutation.array_form)
shift = list(accumulate([1 if i in subremoved else 0 for i in range(len(p))]))
premoved = [pinv[i] for i in subremoved]
p2 = [e - shift[e] for i, e in enumerate(p) if e not in subremoved]
# TODO: check if subremoved should be permuted as well...
newexpr = _permute_dims(subexpr, p2)
premoved = sorted(premoved)
if newexpr != expr:
newexpr, removed2 = _remove_trivial_dims(_array2matrix(newexpr))
premoved = _combine_removed(-1, premoved, removed2)
return newexpr, premoved
@_remove_trivial_dims.register(ArrayContraction) # type: ignore
def _(expr: ArrayContraction):
new_expr, removed0 = _array_contraction_to_diagonal_multiple_identity(expr)
if new_expr != expr:
new_expr2, removed1 = _remove_trivial_dims(_array2matrix(new_expr))
removed = _combine_removed(-1, removed0, removed1)
return new_expr2, removed
rank1 = get_rank(expr)
expr, removed1 = remove_identity_matrices(expr)
if not isinstance(expr, ArrayContraction):
expr2, removed2 = _remove_trivial_dims(expr)
return expr2, _combine_removed(rank1, removed1, removed2)
newexpr, removed2 = _remove_trivial_dims(expr.expr)
shifts = list(accumulate([1 if i in removed2 else 0 for i in range(get_rank(expr.expr))]))
new_contraction_indices = [tuple(j for j in i if j not in removed2) for i in expr.contraction_indices]
# Remove possible empty tuples "()":
new_contraction_indices = [i for i in new_contraction_indices if len(i) > 0]
contraction_indices_flat = [j for i in expr.contraction_indices for j in i]
removed2 = [i for i in removed2 if i not in contraction_indices_flat]
new_contraction_indices = [tuple(j - shifts[j] for j in i) for i in new_contraction_indices]
# Shift removed2:
removed2 = ArrayContraction._push_indices_up(expr.contraction_indices, removed2)
removed = _combine_removed(rank1, removed1, removed2)
return _array_contraction(newexpr, *new_contraction_indices), list(removed)
def _remove_diagonalized_identity_matrices(expr: ArrayDiagonal):
assert isinstance(expr, ArrayDiagonal)
editor = _EditArrayContraction(expr)
mapping = {i: {j for j in editor.args_with_ind if i in j.indices} for i in range(-1, -1-editor.number_of_diagonal_indices, -1)}
removed = []
counter: int = 0
for i, arg_with_ind in enumerate(editor.args_with_ind):
counter += len(arg_with_ind.indices)
if isinstance(arg_with_ind.element, Identity):
if None in arg_with_ind.indices and any(i is not None and (i < 0) == True for i in arg_with_ind.indices):
diag_ind = [j for j in arg_with_ind.indices if j is not None][0]
other = [j for j in mapping[diag_ind] if j != arg_with_ind][0]
if not isinstance(other.element, MatrixExpr):
continue
if 1 not in other.element.shape:
continue
if None not in other.indices:
continue
editor.args_with_ind[i].element = None
none_index = other.indices.index(None)
other.element = DiagMatrix(other.element)
other_range = editor.get_absolute_range(other)
removed.extend([other_range[0] + none_index])
editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None]
removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, get_rank(expr.expr))
return editor.to_array_contraction(), removed
@_remove_trivial_dims.register(ArrayDiagonal) # type: ignore
def _(expr: ArrayDiagonal):
newexpr, removed = _remove_trivial_dims(expr.expr)
shifts = list(accumulate([0] + [1 if i in removed else 0 for i in range(get_rank(expr.expr))]))
new_diag_indices = {i: tuple(j for j in i if j not in removed) for i in expr.diagonal_indices}
for old_diag_tuple, new_diag_tuple in new_diag_indices.items():
if len(new_diag_tuple) == 1:
removed = [i for i in removed if i not in old_diag_tuple]
new_diag_indices = [tuple(j - shifts[j] for j in i) for i in new_diag_indices.values()] # type: ignore
rank = get_rank(expr.expr)
removed = ArrayDiagonal._push_indices_up(expr.diagonal_indices, removed, rank)
removed = sorted({i for i in removed})
# If there are single axes to diagonalize remaining, it means that their
# corresponding dimension has been removed, they no longer need diagonalization:
new_diag_indices = [i for i in new_diag_indices if len(i) > 0] # type: ignore
if len(new_diag_indices) > 0:
newexpr2 = _array_diagonal(newexpr, *new_diag_indices, allow_trivial_diags=True)
else:
newexpr2 = newexpr
if isinstance(newexpr2, ArrayDiagonal):
newexpr3, removed2 = _remove_diagonalized_identity_matrices(newexpr2)
removed = _combine_removed(-1, removed, removed2)
return newexpr3, removed
else:
return newexpr2, removed
@_remove_trivial_dims.register(ElementwiseApplyFunction) # type: ignore
def _(expr: ElementwiseApplyFunction):
subexpr, removed = _remove_trivial_dims(expr.expr)
if subexpr.shape == (1, 1):
# TODO: move this to ElementwiseApplyFunction
return expr.function(subexpr), removed + [0, 1]
return ElementwiseApplyFunction(expr.function, subexpr), []
@_remove_trivial_dims.register(ArrayElementwiseApplyFunc) # type: ignore
def _(expr: ArrayElementwiseApplyFunc):
subexpr, removed = _remove_trivial_dims(expr.expr)
return ArrayElementwiseApplyFunc(expr.function, subexpr), removed
def convert_array_to_matrix(expr):
r"""
Recognize matrix expressions in codegen objects.
If more than one matrix multiplication line have been detected, return a
list with the matrix expressions.
Examples
========
>>> from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array
>>> from sympy.tensor.array import tensorcontraction, tensorproduct
>>> from sympy import MatrixSymbol, Sum
>>> from sympy.abc import i, j, k, l, N
>>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
>>> from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> C = MatrixSymbol("C", N, N)
>>> D = MatrixSymbol("D", N, N)
>>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1))
>>> cg = convert_indexed_to_array(expr)
>>> convert_array_to_matrix(cg)
A*B
>>> cg = convert_indexed_to_array(expr, first_indices=[k])
>>> convert_array_to_matrix(cg)
B.T*A.T
Transposition is detected:
>>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1))
>>> cg = convert_indexed_to_array(expr)
>>> convert_array_to_matrix(cg)
A.T*B
>>> cg = convert_indexed_to_array(expr, first_indices=[k])
>>> convert_array_to_matrix(cg)
B.T*A
Detect the trace:
>>> expr = Sum(A[i, i], (i, 0, N-1))
>>> cg = convert_indexed_to_array(expr)
>>> convert_array_to_matrix(cg)
Trace(A)
Recognize some more complex traces:
>>> expr = Sum(A[i, j]*B[j, i], (i, 0, N-1), (j, 0, N-1))
>>> cg = convert_indexed_to_array(expr)
>>> convert_array_to_matrix(cg)
Trace(A*B)
More complicated expressions:
>>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1))
>>> cg = convert_indexed_to_array(expr)
>>> convert_array_to_matrix(cg)
A*B.T*A.T
Expressions constructed from matrix expressions do not contain literal
indices, the positions of free indices are returned instead:
>>> expr = A*B
>>> cg = convert_matrix_to_array(expr)
>>> convert_array_to_matrix(cg)
A*B
If more than one line of matrix multiplications is detected, return
separate matrix multiplication factors embedded in a tensor product object:
>>> cg = tensorcontraction(tensorproduct(A, B, C, D), (1, 2), (5, 6))
>>> convert_array_to_matrix(cg)
ArrayTensorProduct(A*B, C*D)
The two lines have free indices at axes 0, 3 and 4, 7, respectively.
"""
rec = _array2matrix(expr)
rec, removed = _remove_trivial_dims(rec)
return rec
def _array_diag2contr_diagmatrix(expr: ArrayDiagonal):
if isinstance(expr.expr, ArrayTensorProduct):
args = list(expr.expr.args)
diag_indices = list(expr.diagonal_indices)
mapping = _get_mapping_from_subranks([_get_subrank(arg) for arg in args])
tuple_links = [[mapping[j] for j in i] for i in diag_indices]
contr_indices = []
total_rank = get_rank(expr)
replaced = [False for arg in args]
for i, (abs_pos, rel_pos) in enumerate(zip(diag_indices, tuple_links)):
if len(abs_pos) != 2:
continue
(pos1_outer, pos1_inner), (pos2_outer, pos2_inner) = rel_pos
arg1 = args[pos1_outer]
arg2 = args[pos2_outer]
if get_rank(arg1) != 2 or get_rank(arg2) != 2:
if replaced[pos1_outer]:
diag_indices[i] = None
if replaced[pos2_outer]:
diag_indices[i] = None
continue
pos1_in2 = 1 - pos1_inner
pos2_in2 = 1 - pos2_inner
if arg1.shape[pos1_in2] == 1:
if arg1.shape[pos1_inner] != 1:
darg1 = DiagMatrix(arg1)
else:
darg1 = arg1
args.append(darg1)
contr_indices.append(((pos2_outer, pos2_inner), (len(args)-1, pos1_inner)))
total_rank += 1
diag_indices[i] = None
args[pos1_outer] = OneArray(arg1.shape[pos1_in2])
replaced[pos1_outer] = True
elif arg2.shape[pos2_in2] == 1:
if arg2.shape[pos2_inner] != 1:
darg2 = DiagMatrix(arg2)
else:
darg2 = arg2
args.append(darg2)
contr_indices.append(((pos1_outer, pos1_inner), (len(args)-1, pos2_inner)))
total_rank += 1
diag_indices[i] = None
args[pos2_outer] = OneArray(arg2.shape[pos2_in2])
replaced[pos2_outer] = True
diag_indices_new = [i for i in diag_indices if i is not None]
cumul = list(accumulate([0] + [get_rank(arg) for arg in args]))
contr_indices2 = [tuple(cumul[a] + b for a, b in i) for i in contr_indices]
tc = _array_contraction(
_array_tensor_product(*args), *contr_indices2
)
td = _array_diagonal(tc, *diag_indices_new)
return td
return expr
def _a2m_mul(*args):
if not any(isinstance(i, _CodegenArrayAbstract) for i in args):
from sympy.matrices.expressions.matmul import MatMul
return MatMul(*args).doit()
else:
return _array_contraction(
_array_tensor_product(*args),
*[(2*i-1, 2*i) for i in range(1, len(args))]
)
def _a2m_tensor_product(*args):
scalars = []
arrays = []
for arg in args:
if isinstance(arg, (MatrixExpr, _ArrayExpr, _CodegenArrayAbstract)):
arrays.append(arg)
else:
scalars.append(arg)
scalar = Mul.fromiter(scalars)
if len(arrays) == 0:
return scalar
if scalar != 1:
if isinstance(arrays[0], _CodegenArrayAbstract):
arrays = [scalar] + arrays
else:
arrays[0] *= scalar
return _array_tensor_product(*arrays)
def _a2m_add(*args):
if not any(isinstance(i, _CodegenArrayAbstract) for i in args):
from sympy.matrices.expressions.matadd import MatAdd
return MatAdd(*args).doit()
else:
return _array_add(*args)
def _a2m_trace(arg):
if isinstance(arg, _CodegenArrayAbstract):
return _array_contraction(arg, (0, 1))
else:
from sympy.matrices.expressions.trace import Trace
return Trace(arg)
def _a2m_transpose(arg):
if isinstance(arg, _CodegenArrayAbstract):
return _permute_dims(arg, [1, 0])
else:
from sympy.matrices.expressions.transpose import Transpose
return Transpose(arg).doit()
def identify_hadamard_products(expr: tUnion[ArrayContraction, ArrayDiagonal]):
editor: _EditArrayContraction = _EditArrayContraction(expr)
map_contr_to_args: tDict[FrozenSet, List[_ArgE]] = defaultdict(list)
map_ind_to_inds: tDict[Optional[int], int] = defaultdict(int)
for arg_with_ind in editor.args_with_ind:
for ind in arg_with_ind.indices:
map_ind_to_inds[ind] += 1
if None in arg_with_ind.indices:
continue
map_contr_to_args[frozenset(arg_with_ind.indices)].append(arg_with_ind)
k: FrozenSet[int]
v: List[_ArgE]
for k, v in map_contr_to_args.items():
make_trace: bool = False
if len(k) == 1 and next(iter(k)) >= 0 and sum([next(iter(k)) in i for i in map_contr_to_args]) == 1:
# This is a trace: the arguments are fully contracted with only one
# index, and the index isn't used anywhere else:
make_trace = True
first_element = S.One
elif len(k) != 2:
# Hadamard product only defined for matrices:
continue
if len(v) == 1:
# Hadamard product with a single argument makes no sense:
continue
for ind in k:
if map_ind_to_inds[ind] <= 2:
# There is no other contraction, skip:
continue
def check_transpose(x):
x = [i if i >= 0 else -1-i for i in x]
return x == sorted(x)
# Check if expression is a trace:
if all([map_ind_to_inds[j] == len(v) and j >= 0 for j in k]) and all([j >= 0 for j in k]):
# This is a trace
make_trace = True
first_element = v[0].element
if not check_transpose(v[0].indices):
first_element = first_element.T
hadamard_factors = v[1:]
else:
hadamard_factors = v
# This is a Hadamard product:
hp = hadamard_product(*[i.element if check_transpose(i.indices) else Transpose(i.element) for i in hadamard_factors])
hp_indices = v[0].indices
if not check_transpose(hadamard_factors[0].indices):
hp_indices = list(reversed(hp_indices))
if make_trace:
hp = Trace(first_element*hp.T)._normalize()
hp_indices = []
editor.insert_after(v[0], _ArgE(hp, hp_indices))
for i in v:
editor.args_with_ind.remove(i)
return editor.to_array_contraction()
def identify_removable_identity_matrices(expr):
editor = _EditArrayContraction(expr)
flag: bool = True
while flag:
flag = False
for arg_with_ind in editor.args_with_ind:
if isinstance(arg_with_ind.element, Identity):
k = arg_with_ind.element.shape[0]
# Candidate for removal:
if arg_with_ind.indices == [None, None]:
# Free identity matrix, will be cleared by _remove_trivial_dims:
continue
elif None in arg_with_ind.indices:
ind = [j for j in arg_with_ind.indices if j is not None][0]
counted = editor.count_args_with_index(ind)
if counted == 1:
# Identity matrix contracted only on one index with itself,
# transform to a OneArray(k) element:
editor.insert_after(arg_with_ind, OneArray(k))
editor.args_with_ind.remove(arg_with_ind)
flag = True
break
elif counted > 2:
# Case counted = 2 is a matrix multiplication by identity matrix, skip it.
# Case counted > 2 is a multiple contraction,
# this is a case where the contraction becomes a diagonalization if the
# identity matrix is dropped.
continue
elif arg_with_ind.indices[0] == arg_with_ind.indices[1]:
ind = arg_with_ind.indices[0]
counted = editor.count_args_with_index(ind)
if counted > 1:
editor.args_with_ind.remove(arg_with_ind)
flag = True
break
else:
# This is a trace, skip it as it will be recognized somewhere else:
pass
elif ask(Q.diagonal(arg_with_ind.element)):
if arg_with_ind.indices == [None, None]:
continue
elif None in arg_with_ind.indices:
pass
elif arg_with_ind.indices[0] == arg_with_ind.indices[1]:
ind = arg_with_ind.indices[0]
counted = editor.count_args_with_index(ind)
if counted == 3:
# A_ai B_bi D_ii ==> A_ai D_ij B_bj
ind_new = editor.get_new_contraction_index()
other_args = [j for j in editor.args_with_ind if j != arg_with_ind]
other_args[1].indices = [ind_new if j == ind else j for j in other_args[1].indices]
arg_with_ind.indices = [ind, ind_new]
flag = True
break
return editor.to_array_contraction()
def remove_identity_matrices(expr: ArrayContraction):
editor = _EditArrayContraction(expr)
removed: List[int] = []
permutation_map = {}
free_indices = list(accumulate([0] + [sum([i is None for i in arg.indices]) for arg in editor.args_with_ind]))
free_map = {k: v for k, v in zip(editor.args_with_ind, free_indices[:-1])}
update_pairs = {}
for ind in range(editor.number_of_contraction_indices):
args = editor.get_args_with_index(ind)
identity_matrices = [i for i in args if isinstance(i.element, Identity)]
number_identity_matrices = len(identity_matrices)
# If the contraction involves a non-identity matrix and multiple identity matrices:
if number_identity_matrices != len(args) - 1 or number_identity_matrices == 0:
continue
# Get the non-identity element:
non_identity = [i for i in args if not isinstance(i.element, Identity)][0]
# Check that all identity matrices have at least one free index
# (otherwise they would be contractions to some other elements)
if any([None not in i.indices for i in identity_matrices]):
continue
# Mark the identity matrices for removal:
for i in identity_matrices:
i.element = None
removed.extend(range(free_map[i], free_map[i] + len([j for j in i.indices if j is None])))
last_removed = removed.pop(-1)
update_pairs[last_removed, ind] = non_identity.indices[:]
# Remove the indices from the non-identity matrix, as the contraction
# no longer exists:
non_identity.indices = [None if i == ind else i for i in non_identity.indices]
removed.sort()
shifts = list(accumulate([1 if i in removed else 0 for i in range(get_rank(expr))]))
for (last_removed, ind), non_identity_indices in update_pairs.items():
pos = [free_map[non_identity] + i for i, e in enumerate(non_identity_indices) if e == ind]
assert len(pos) == 1
for j in pos:
permutation_map[j] = last_removed
editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None]
ret_expr = editor.to_array_contraction()
permutation = []
counter = 0
counter2 = 0
for j in range(get_rank(expr)):
if j in removed:
continue
if counter2 in permutation_map:
target = permutation_map[counter2]
permutation.append(target - shifts[target])
counter2 += 1
else:
while counter in permutation_map.values():
counter += 1
permutation.append(counter)
counter += 1
counter2 += 1
ret_expr2 = _permute_dims(ret_expr, _af_invert(permutation))
return ret_expr2, removed
def _combine_removed(dim: int, removed1: List[int], removed2: List[int]) -> List[int]:
# Concatenate two axis removal operations as performed by
# _remove_trivial_dims,
removed1 = sorted(removed1)
removed2 = sorted(removed2)
i = 0
j = 0
removed = []
while True:
if j >= len(removed2):
while i < len(removed1):
removed.append(removed1[i])
i += 1
break
elif i < len(removed1) and removed1[i] <= i + removed2[j]:
removed.append(removed1[i])
i += 1
else:
removed.append(i + removed2[j])
j += 1
return removed
def _array_contraction_to_diagonal_multiple_identity(expr: ArrayContraction):
editor = _EditArrayContraction(expr)
editor.track_permutation_start()
removed: List[int] = []
diag_index_counter: int = 0
for i in range(editor.number_of_contraction_indices):
identities = []
args = []
for j, arg in enumerate(editor.args_with_ind):
if i not in arg.indices:
continue
if isinstance(arg.element, Identity):
identities.append(arg)
else:
args.append(arg)
if len(identities) == 0:
continue
if len(args) + len(identities) < 3:
continue
new_diag_ind = -1 - diag_index_counter
diag_index_counter += 1
# Variable "flag" to control whether to skip this contraction set:
flag: bool = True
for i1, id1 in enumerate(identities):
if None not in id1.indices:
flag = True
break
free_pos = list(range(*editor.get_absolute_free_range(id1)))[0]
editor._track_permutation[-1].append(free_pos) # type: ignore
id1.element = None
flag = False
break
if flag:
continue
for arg in identities[:i1] + identities[i1+1:]:
arg.element = None
removed.extend(range(*editor.get_absolute_free_range(arg)))
for arg in args:
arg.indices = [new_diag_ind if j == i else j for j in arg.indices]
for j, e in enumerate(editor.args_with_ind):
if e.element is None:
editor._track_permutation[j] = None # type: ignore
editor._track_permutation = [i for i in editor._track_permutation if i is not None] # type: ignore
# Renumber permutation array form in order to deal with deleted positions:
remap = {e: i for i, e in enumerate(sorted({k for j in editor._track_permutation for k in j}))}
editor._track_permutation = [[remap[j] for j in i] for i in editor._track_permutation]
editor.args_with_ind = [i for i in editor.args_with_ind if i.element is not None]
new_expr = editor.to_array_contraction()
return new_expr, removed
|
fb14be5ff89373fbb18776ba84f9df4f159dab592c03b8707c50f3a1b092968d | from sympy.core.basic import Basic
from sympy.core.function import Lambda
from sympy.core.mul import Mul
from sympy.core.numbers import Integer
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, symbols)
from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct)
from sympy.matrices.expressions.matadd import MatAdd
from sympy.matrices.expressions.matmul import MatMul
from sympy.matrices.expressions.matpow import MatPow
from sympy.matrices.expressions.trace import Trace
from sympy.matrices.expressions.transpose import Transpose
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.tensor.array.expressions.array_expressions import \
ArrayElementwiseApplyFunc, _array_tensor_product, _array_contraction, \
_array_diagonal, _array_add, _permute_dims
def convert_matrix_to_array(expr: Basic) -> Basic:
if isinstance(expr, MatMul):
args_nonmat = []
args = []
for arg in expr.args:
if isinstance(arg, MatrixExpr):
args.append(arg)
else:
args_nonmat.append(convert_matrix_to_array(arg))
contractions = [(2*i+1, 2*i+2) for i in range(len(args)-1)]
scalar = _array_tensor_product(*args_nonmat) if args_nonmat else S.One
if scalar == 1:
tprod = _array_tensor_product(
*[convert_matrix_to_array(arg) for arg in args])
else:
tprod = _array_tensor_product(
scalar,
*[convert_matrix_to_array(arg) for arg in args])
return _array_contraction(
tprod,
*contractions
)
elif isinstance(expr, MatAdd):
return _array_add(
*[convert_matrix_to_array(arg) for arg in expr.args]
)
elif isinstance(expr, Transpose):
return _permute_dims(
convert_matrix_to_array(expr.args[0]), [1, 0]
)
elif isinstance(expr, Trace):
inner_expr: MatrixExpr = convert_matrix_to_array(expr.arg) # type: ignore
return _array_contraction(inner_expr, (0, len(inner_expr.shape) - 1))
elif isinstance(expr, Mul):
return _array_tensor_product(*[convert_matrix_to_array(i) for i in expr.args])
elif isinstance(expr, Pow):
base = convert_matrix_to_array(expr.base)
if (expr.exp > 0) == True:
return _array_tensor_product(*[base for i in range(expr.exp)])
else:
return expr
elif isinstance(expr, MatPow):
base = convert_matrix_to_array(expr.base)
if expr.exp.is_Integer != True:
b = symbols("b", cls=Dummy)
return ArrayElementwiseApplyFunc(Lambda(b, b**expr.exp), convert_matrix_to_array(base))
elif (expr.exp > 0) == True:
return convert_matrix_to_array(MatMul.fromiter(base for i in range(expr.exp)))
else:
return expr
elif isinstance(expr, HadamardProduct):
tp = _array_tensor_product(*[convert_matrix_to_array(arg) for arg in expr.args])
diag = [[2*i for i in range(len(expr.args))], [2*i+1 for i in range(len(expr.args))]]
return _array_diagonal(tp, *diag)
elif isinstance(expr, HadamardPower):
base, exp = expr.args
if isinstance(exp, Integer) and exp > 0:
return convert_matrix_to_array(HadamardProduct.fromiter(base for i in range(exp)))
else:
d = Dummy("d")
return ArrayElementwiseApplyFunc(Lambda(d, d**exp), base)
else:
return expr
|
c80b49b01a963dcb7b8a4c3a381a3ca8024be017533ce40cbb634f1025e8c0ae | import operator
from collections import defaultdict, Counter
from functools import reduce
import itertools
from itertools import accumulate
from typing import Optional, List, Dict as tDict, Tuple as tTuple
import typing
from sympy import Integer, KroneckerDelta
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import (Function, Lambda)
from sympy.core.mul import Mul
from sympy.core.singleton import S
from sympy.core.sorting import default_sort_key
from sympy.core.symbol import (Dummy, Symbol)
from sympy.matrices.expressions.diagonal import diagonalize_vector
from sympy.matrices.expressions.matexpr import MatrixExpr
from sympy.matrices.expressions.special import ZeroMatrix
from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensordiagonal, tensorproduct)
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
from sympy.tensor.array.ndim_array import NDimArray
from sympy.tensor.indexed import (Indexed, IndexedBase)
from sympy.matrices.expressions.matexpr import MatrixElement
from sympy.tensor.array.expressions.utils import _apply_recursively_over_nested_lists, _sort_contraction_indices, \
_get_mapping_from_subranks, _build_push_indices_up_func_transformation, _get_contraction_links, \
_build_push_indices_down_func_transformation
from sympy.combinatorics import Permutation
from sympy.combinatorics.permutations import _af_invert
from sympy.core.sympify import _sympify
class _ArrayExpr(Expr):
pass
class ArraySymbol(_ArrayExpr):
"""
Symbol representing an array expression
"""
def __new__(cls, symbol, shape: typing.Iterable) -> "ArraySymbol":
if isinstance(symbol, str):
symbol = Symbol(symbol)
# symbol = _sympify(symbol)
shape = Tuple(*map(_sympify, shape))
obj = Expr.__new__(cls, symbol, shape)
return obj
@property
def name(self):
return self._args[0]
@property
def shape(self):
return self._args[1]
def __getitem__(self, item):
return ArrayElement(self, item)
def as_explicit(self):
if not all(i.is_Integer for i in self.shape):
raise ValueError("cannot express explicit array with symbolic shape")
data = [self[i] for i in itertools.product(*[range(j) for j in self.shape])]
return ImmutableDenseNDimArray(data).reshape(*self.shape)
class ArrayElement(_ArrayExpr):
"""
An element of an array.
"""
_diff_wrt = True
is_symbol = True
is_commutative = True
def __new__(cls, name, indices):
if isinstance(name, str):
name = Symbol(name)
name = _sympify(name)
indices = _sympify(tuple(indices))
if hasattr(name, "shape"):
if any((i >= s) == True for i, s in zip(indices, name.shape)):
raise ValueError("shape is out of bounds")
if any((i < 0) == True for i in indices):
raise ValueError("shape contains negative values")
obj = Expr.__new__(cls, name, indices)
return obj
@property
def name(self):
return self._args[0]
@property
def indices(self):
return self._args[1]
def _eval_derivative(self, s):
if not isinstance(s, ArrayElement):
return S.Zero
if s == self:
return S.One
if s.name != self.name:
return S.Zero
return Mul.fromiter(KroneckerDelta(i, j) for i, j in zip(self.indices, s.indices))
class ZeroArray(_ArrayExpr):
"""
Symbolic array of zeros. Equivalent to ``ZeroMatrix`` for matrices.
"""
def __new__(cls, *shape):
if len(shape) == 0:
return S.Zero
shape = map(_sympify, shape)
obj = Expr.__new__(cls, *shape)
return obj
@property
def shape(self):
return self._args
def as_explicit(self):
if not all(i.is_Integer for i in self.shape):
raise ValueError("Cannot return explicit form for symbolic shape.")
return ImmutableDenseNDimArray.zeros(*self.shape)
class OneArray(_ArrayExpr):
"""
Symbolic array of ones.
"""
def __new__(cls, *shape):
if len(shape) == 0:
return S.One
shape = map(_sympify, shape)
obj = Expr.__new__(cls, *shape)
return obj
@property
def shape(self):
return self._args
def as_explicit(self):
if not all(i.is_Integer for i in self.shape):
raise ValueError("Cannot return explicit form for symbolic shape.")
return ImmutableDenseNDimArray([S.One for i in range(reduce(operator.mul, self.shape))]).reshape(*self.shape)
class _CodegenArrayAbstract(Basic):
@property
def subranks(self):
"""
Returns the ranks of the objects in the uppermost tensor product inside
the current object. In case no tensor products are contained, return
the atomic ranks.
Examples
========
>>> from sympy.tensor.array import tensorproduct, tensorcontraction
>>> from sympy import MatrixSymbol
>>> M = MatrixSymbol("M", 3, 3)
>>> N = MatrixSymbol("N", 3, 3)
>>> P = MatrixSymbol("P", 3, 3)
Important: do not confuse the rank of the matrix with the rank of an array.
>>> tp = tensorproduct(M, N, P)
>>> tp.subranks
[2, 2, 2]
>>> co = tensorcontraction(tp, (1, 2), (3, 4))
>>> co.subranks
[2, 2, 2]
"""
return self._subranks[:]
def subrank(self):
"""
The sum of ``subranks``.
"""
return sum(self.subranks)
@property
def shape(self):
return self._shape
class ArrayTensorProduct(_CodegenArrayAbstract):
r"""
Class to represent the tensor product of array-like objects.
"""
def __new__(cls, *args, **kwargs):
args = [_sympify(arg) for arg in args]
canonicalize = kwargs.pop("canonicalize", False)
ranks = [get_rank(arg) for arg in args]
obj = Basic.__new__(cls, *args)
obj._subranks = ranks
shapes = [get_shape(i) for i in args]
if any(i is None for i in shapes):
obj._shape = None
else:
obj._shape = tuple(j for i in shapes for j in i)
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
args = self.args
args = self._flatten(args)
ranks = [get_rank(arg) for arg in args]
# Check if there are nested permutation and lift them up:
permutation_cycles = []
for i, arg in enumerate(args):
if not isinstance(arg, PermuteDims):
continue
permutation_cycles.extend([[k + sum(ranks[:i]) for k in j] for j in arg.permutation.cyclic_form])
args[i] = arg.expr
if permutation_cycles:
return _permute_dims(_array_tensor_product(*args), Permutation(sum(ranks)-1)*Permutation(permutation_cycles))
if len(args) == 1:
return args[0]
# If any object is a ZeroArray, return a ZeroArray:
if any(isinstance(arg, (ZeroArray, ZeroMatrix)) for arg in args):
shapes = reduce(operator.add, [get_shape(i) for i in args], ())
return ZeroArray(*shapes)
# If there are contraction objects inside, transform the whole
# expression into `ArrayContraction`:
contractions = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayContraction)}
if contractions:
ranks = [_get_subrank(arg) if isinstance(arg, ArrayContraction) else get_rank(arg) for arg in args]
cumulative_ranks = list(accumulate([0] + ranks))[:-1]
tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayContraction) else arg for arg in args])
contraction_indices = [tuple(cumulative_ranks[i] + k for k in j) for i, arg in contractions.items() for j in arg.contraction_indices]
return _array_contraction(tp, *contraction_indices)
diagonals = {i: arg for i, arg in enumerate(args) if isinstance(arg, ArrayDiagonal)}
if diagonals:
inverse_permutation = []
last_perm = []
ranks = [get_rank(arg) for arg in args]
cumulative_ranks = list(accumulate([0] + ranks))[:-1]
for i, arg in enumerate(args):
if isinstance(arg, ArrayDiagonal):
i1 = get_rank(arg) - len(arg.diagonal_indices)
i2 = len(arg.diagonal_indices)
inverse_permutation.extend([cumulative_ranks[i] + j for j in range(i1)])
last_perm.extend([cumulative_ranks[i] + j for j in range(i1, i1 + i2)])
else:
inverse_permutation.extend([cumulative_ranks[i] + j for j in range(get_rank(arg))])
inverse_permutation.extend(last_perm)
tp = _array_tensor_product(*[arg.expr if isinstance(arg, ArrayDiagonal) else arg for arg in args])
ranks2 = [_get_subrank(arg) if isinstance(arg, ArrayDiagonal) else get_rank(arg) for arg in args]
cumulative_ranks2 = list(accumulate([0] + ranks2))[:-1]
diagonal_indices = [tuple(cumulative_ranks2[i] + k for k in j) for i, arg in diagonals.items() for j in arg.diagonal_indices]
return _permute_dims(_array_diagonal(tp, *diagonal_indices), _af_invert(inverse_permutation))
return self.func(*args, canonicalize=False)
def doit(self, **kwargs):
deep = kwargs.get("deep", True)
if deep:
return self.func(*[arg.doit(**kwargs) for arg in self.args])._canonicalize()
else:
return self._canonicalize()
@classmethod
def _flatten(cls, args):
args = [i for arg in args for i in (arg.args if isinstance(arg, cls) else [arg])]
return args
def as_explicit(self):
return tensorproduct(*[arg.as_explicit() if hasattr(arg, "as_explicit") else arg for arg in self.args])
class ArrayAdd(_CodegenArrayAbstract):
r"""
Class for elementwise array additions.
"""
def __new__(cls, *args, **kwargs):
args = [_sympify(arg) for arg in args]
ranks = [get_rank(arg) for arg in args]
ranks = list(set(ranks))
if len(ranks) != 1:
raise ValueError("summing arrays of different ranks")
shapes = [arg.shape for arg in args]
if len({i for i in shapes if i is not None}) > 1:
raise ValueError("mismatching shapes in addition")
canonicalize = kwargs.pop("canonicalize", False)
obj = Basic.__new__(cls, *args)
obj._subranks = ranks
if any(i is None for i in shapes):
obj._shape = None
else:
obj._shape = shapes[0]
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
args = self.args
# Flatten:
args = self._flatten_args(args)
shapes = [get_shape(arg) for arg in args]
args = [arg for arg in args if not isinstance(arg, (ZeroArray, ZeroMatrix))]
if len(args) == 0:
if any(i for i in shapes if i is None):
raise NotImplementedError("cannot handle addition of ZeroMatrix/ZeroArray and undefined shape object")
return ZeroArray(*shapes[0])
elif len(args) == 1:
return args[0]
return self.func(*args, canonicalize=False)
def doit(self, **kwargs):
deep = kwargs.get("deep", True)
if deep:
return self.func(*[arg.doit(**kwargs) for arg in self.args])._canonicalize()
else:
return self._canonicalize()
@classmethod
def _flatten_args(cls, args):
new_args = []
for arg in args:
if isinstance(arg, ArrayAdd):
new_args.extend(arg.args)
else:
new_args.append(arg)
return new_args
def as_explicit(self):
return reduce(operator.add, [arg.as_explicit() for arg in self.args])
class PermuteDims(_CodegenArrayAbstract):
r"""
Class to represent permutation of axes of arrays.
Examples
========
>>> from sympy.tensor.array import permutedims
>>> from sympy import MatrixSymbol
>>> M = MatrixSymbol("M", 3, 3)
>>> cg = permutedims(M, [1, 0])
The object ``cg`` represents the transposition of ``M``, as the permutation
``[1, 0]`` will act on its indices by switching them:
`M_{ij} \Rightarrow M_{ji}`
This is evident when transforming back to matrix form:
>>> from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
>>> convert_array_to_matrix(cg)
M.T
>>> N = MatrixSymbol("N", 3, 2)
>>> cg = permutedims(N, [1, 0])
>>> cg.shape
(2, 3)
Permutations of tensor products are simplified in order to achieve a
standard form:
>>> from sympy.tensor.array import tensorproduct
>>> M = MatrixSymbol("M", 4, 5)
>>> tp = tensorproduct(M, N)
>>> tp.shape
(4, 5, 3, 2)
>>> perm1 = permutedims(tp, [2, 3, 1, 0])
The args ``(M, N)`` have been sorted and the permutation has been
simplified, the expression is equivalent:
>>> perm1.expr.args
(N, M)
>>> perm1.shape
(3, 2, 5, 4)
>>> perm1.permutation
(2 3)
The permutation in its array form has been simplified from
``[2, 3, 1, 0]`` to ``[0, 1, 3, 2]``, as the arguments of the tensor
product `M` and `N` have been switched:
>>> perm1.permutation.array_form
[0, 1, 3, 2]
We can nest a second permutation:
>>> perm2 = permutedims(perm1, [1, 0, 2, 3])
>>> perm2.shape
(2, 3, 5, 4)
>>> perm2.permutation.array_form
[1, 0, 3, 2]
"""
def __new__(cls, expr, permutation, **kwargs):
from sympy.combinatorics import Permutation
expr = _sympify(expr)
permutation = Permutation(permutation)
permutation_size = permutation.size
expr_rank = get_rank(expr)
if permutation_size != expr_rank:
raise ValueError("Permutation size must be the length of the shape of expr")
canonicalize = kwargs.pop("canonicalize", False)
obj = Basic.__new__(cls, expr, permutation)
obj._subranks = [get_rank(expr)]
shape = get_shape(expr)
if shape is None:
obj._shape = None
else:
obj._shape = tuple(shape[permutation(i)] for i in range(len(shape)))
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
expr = self.expr
permutation = self.permutation
if isinstance(expr, PermuteDims):
subexpr = expr.expr
subperm = expr.permutation
permutation = permutation * subperm
expr = subexpr
if isinstance(expr, ArrayContraction):
expr, permutation = self._PermuteDims_denestarg_ArrayContraction(expr, permutation)
if isinstance(expr, ArrayTensorProduct):
expr, permutation = self._PermuteDims_denestarg_ArrayTensorProduct(expr, permutation)
if isinstance(expr, (ZeroArray, ZeroMatrix)):
return ZeroArray(*[expr.shape[i] for i in permutation.array_form])
plist = permutation.array_form
if plist == sorted(plist):
return expr
return self.func(expr, permutation, canonicalize=False)
def doit(self, **kwargs):
deep = kwargs.get("deep", True)
if deep:
return self.func(*[arg.doit(**kwargs) for arg in self.args])._canonicalize()
else:
return self._canonicalize()
@property
def expr(self):
return self.args[0]
@property
def permutation(self):
return self.args[1]
@classmethod
def _PermuteDims_denestarg_ArrayTensorProduct(cls, expr, permutation):
# Get the permutation in its image-form:
perm_image_form = _af_invert(permutation.array_form)
args = list(expr.args)
# Starting index global position for every arg:
cumul = list(accumulate([0] + expr.subranks))
# Split `perm_image_form` into a list of list corresponding to the indices
# of every argument:
perm_image_form_in_components = [perm_image_form[cumul[i]:cumul[i+1]] for i in range(len(args))]
# Create an index, target-position-key array:
ps = [(i, sorted(comp)) for i, comp in enumerate(perm_image_form_in_components)]
# Sort the array according to the target-position-key:
# In this way, we define a canonical way to sort the arguments according
# to the permutation.
ps.sort(key=lambda x: x[1])
# Read the inverse-permutation (i.e. image-form) of the args:
perm_args_image_form = [i[0] for i in ps]
# Apply the args-permutation to the `args`:
args_sorted = [args[i] for i in perm_args_image_form]
# Apply the args-permutation to the array-form of the permutation of the axes (of `expr`):
perm_image_form_sorted_args = [perm_image_form_in_components[i] for i in perm_args_image_form]
new_permutation = Permutation(_af_invert([j for i in perm_image_form_sorted_args for j in i]))
return _array_tensor_product(*args_sorted), new_permutation
@classmethod
def _PermuteDims_denestarg_ArrayContraction(cls, expr, permutation):
if not isinstance(expr, ArrayContraction):
return expr, permutation
if not isinstance(expr.expr, ArrayTensorProduct):
return expr, permutation
args = expr.expr.args
subranks = [get_rank(arg) for arg in expr.expr.args]
contraction_indices = expr.contraction_indices
contraction_indices_flat = [j for i in contraction_indices for j in i]
cumul = list(accumulate([0] + subranks))
# Spread the permutation in its array form across the args in the corresponding
# tensor-product arguments with free indices:
permutation_array_blocks_up = []
image_form = _af_invert(permutation.array_form)
counter = 0
for i, e in enumerate(subranks):
current = []
for j in range(cumul[i], cumul[i+1]):
if j in contraction_indices_flat:
continue
current.append(image_form[counter])
counter += 1
permutation_array_blocks_up.append(current)
# Get the map of axis repositioning for every argument of tensor-product:
index_blocks = [[j for j in range(cumul[i], cumul[i+1])] for i, e in enumerate(expr.subranks)]
index_blocks_up = expr._push_indices_up(expr.contraction_indices, index_blocks)
inverse_permutation = permutation**(-1)
index_blocks_up_permuted = [[inverse_permutation(j) for j in i if j is not None] for i in index_blocks_up]
# Sorting key is a list of tuple, first element is the index of `args`, second element of
# the tuple is the sorting key to sort `args` of the tensor product:
sorting_keys = list(enumerate(index_blocks_up_permuted))
sorting_keys.sort(key=lambda x: x[1])
# Now we can get the permutation acting on the args in its image-form:
new_perm_image_form = [i[0] for i in sorting_keys]
# Apply the args-level permutation to various elements:
new_index_blocks = [index_blocks[i] for i in new_perm_image_form]
new_index_perm_array_form = _af_invert([j for i in new_index_blocks for j in i])
new_args = [args[i] for i in new_perm_image_form]
new_contraction_indices = [tuple(new_index_perm_array_form[j] for j in i) for i in contraction_indices]
new_expr = _array_contraction(_array_tensor_product(*new_args), *new_contraction_indices)
new_permutation = Permutation(_af_invert([j for i in [permutation_array_blocks_up[k] for k in new_perm_image_form] for j in i]))
return new_expr, new_permutation
@classmethod
def _check_permutation_mapping(cls, expr, permutation):
subranks = expr.subranks
index2arg = [i for i, arg in enumerate(expr.args) for j in range(expr.subranks[i])]
permuted_indices = [permutation(i) for i in range(expr.subrank())]
new_args = list(expr.args)
arg_candidate_index = index2arg[permuted_indices[0]]
current_indices = []
new_permutation = []
inserted_arg_cand_indices = set([])
for i, idx in enumerate(permuted_indices):
if index2arg[idx] != arg_candidate_index:
new_permutation.extend(current_indices)
current_indices = []
arg_candidate_index = index2arg[idx]
current_indices.append(idx)
arg_candidate_rank = subranks[arg_candidate_index]
if len(current_indices) == arg_candidate_rank:
new_permutation.extend(sorted(current_indices))
local_current_indices = [j - min(current_indices) for j in current_indices]
i1 = index2arg[i]
new_args[i1] = _permute_dims(new_args[i1], Permutation(local_current_indices))
inserted_arg_cand_indices.add(arg_candidate_index)
current_indices = []
new_permutation.extend(current_indices)
# TODO: swap args positions in order to simplify the expression:
# TODO: this should be in a function
args_positions = list(range(len(new_args)))
# Get possible shifts:
maps = {}
cumulative_subranks = [0] + list(accumulate(subranks))
for i in range(0, len(subranks)):
s = set([index2arg[new_permutation[j]] for j in range(cumulative_subranks[i], cumulative_subranks[i+1])])
if len(s) != 1:
continue
elem = next(iter(s))
if i != elem:
maps[i] = elem
# Find cycles in the map:
lines = []
current_line = []
while maps:
if len(current_line) == 0:
k, v = maps.popitem()
current_line.append(k)
else:
k = current_line[-1]
if k not in maps:
current_line = []
continue
v = maps.pop(k)
if v in current_line:
lines.append(current_line)
current_line = []
continue
current_line.append(v)
for line in lines:
for i, e in enumerate(line):
args_positions[line[(i + 1) % len(line)]] = e
# TODO: function in order to permute the args:
permutation_blocks = [[new_permutation[cumulative_subranks[i] + j] for j in range(e)] for i, e in enumerate(subranks)]
new_args = [new_args[i] for i in args_positions]
new_permutation_blocks = [permutation_blocks[i] for i in args_positions]
new_permutation2 = [j for i in new_permutation_blocks for j in i]
return _array_tensor_product(*new_args), Permutation(new_permutation2) # **(-1)
@classmethod
def _check_if_there_are_closed_cycles(cls, expr, permutation):
args = list(expr.args)
subranks = expr.subranks
cyclic_form = permutation.cyclic_form
cumulative_subranks = [0] + list(accumulate(subranks))
cyclic_min = [min(i) for i in cyclic_form]
cyclic_max = [max(i) for i in cyclic_form]
cyclic_keep = []
for i, cycle in enumerate(cyclic_form):
flag = True
for j in range(0, len(cumulative_subranks) - 1):
if cyclic_min[i] >= cumulative_subranks[j] and cyclic_max[i] < cumulative_subranks[j+1]:
# Found a sinkable cycle.
args[j] = _permute_dims(args[j], Permutation([[k - cumulative_subranks[j] for k in cyclic_form[i]]]))
flag = False
break
if flag:
cyclic_keep.append(cyclic_form[i])
return _array_tensor_product(*args), Permutation(cyclic_keep, size=permutation.size)
def nest_permutation(self):
r"""
DEPRECATED.
"""
ret = self._nest_permutation(self.expr, self.permutation)
if ret is None:
return self
return ret
@classmethod
def _nest_permutation(cls, expr, permutation):
if isinstance(expr, ArrayTensorProduct):
return _permute_dims(*cls._check_if_there_are_closed_cycles(expr, permutation))
elif isinstance(expr, ArrayContraction):
# Invert tree hierarchy: put the contraction above.
cycles = permutation.cyclic_form
newcycles = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *cycles)
newpermutation = Permutation(newcycles)
new_contr_indices = [tuple(newpermutation(j) for j in i) for i in expr.contraction_indices]
return _array_contraction(PermuteDims(expr.expr, newpermutation), *new_contr_indices)
elif isinstance(expr, ArrayAdd):
return _array_add(*[PermuteDims(arg, permutation) for arg in expr.args])
return None
def as_explicit(self):
return permutedims(self.expr.as_explicit(), self.permutation)
class ArrayDiagonal(_CodegenArrayAbstract):
r"""
Class to represent the diagonal operator.
Explanation
===========
In a 2-dimensional array it returns the diagonal, this looks like the
operation:
`A_{ij} \rightarrow A_{ii}`
The diagonal over axes 1 and 2 (the second and third) of the tensor product
of two 2-dimensional arrays `A \otimes B` is
`\Big[ A_{ab} B_{cd} \Big]_{abcd} \rightarrow \Big[ A_{ai} B_{id} \Big]_{adi}`
In this last example the array expression has been reduced from
4-dimensional to 3-dimensional. Notice that no contraction has occurred,
rather there is a new index `i` for the diagonal, contraction would have
reduced the array to 2 dimensions.
Notice that the diagonalized out dimensions are added as new dimensions at
the end of the indices.
"""
def __new__(cls, expr, *diagonal_indices, **kwargs):
expr = _sympify(expr)
diagonal_indices = [Tuple(*sorted(i)) for i in diagonal_indices]
canonicalize = kwargs.get("canonicalize", False)
shape = get_shape(expr)
if shape is not None:
cls._validate(expr, *diagonal_indices, **kwargs)
# Get new shape:
positions, shape = cls._get_positions_shape(shape, diagonal_indices)
else:
positions = None
if len(diagonal_indices) == 0:
return expr
obj = Basic.__new__(cls, expr, *diagonal_indices)
obj._positions = positions
obj._subranks = _get_subranks(expr)
obj._shape = shape
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
expr = self.expr
diagonal_indices = self.diagonal_indices
trivial_diags = [i for i in diagonal_indices if len(i) == 1]
if len(trivial_diags) > 0:
trivial_pos = {e[0]: i for i, e in enumerate(diagonal_indices) if len(e) == 1}
diag_pos = {e: i for i, e in enumerate(diagonal_indices) if len(e) > 1}
diagonal_indices_short = [i for i in diagonal_indices if len(i) > 1]
rank1 = get_rank(self)
rank2 = len(diagonal_indices)
rank3 = rank1 - rank2
inv_permutation = []
counter1: int = 0
indices_down = ArrayDiagonal._push_indices_down(diagonal_indices_short, list(range(rank1)), get_rank(expr))
for i in indices_down:
if i in trivial_pos:
inv_permutation.append(rank3 + trivial_pos[i])
elif isinstance(i, (Integer, int)):
inv_permutation.append(counter1)
counter1 += 1
else:
inv_permutation.append(rank3 + diag_pos[i])
permutation = _af_invert(inv_permutation)
if len(diagonal_indices_short) > 0:
return _permute_dims(_array_diagonal(expr, *diagonal_indices_short), permutation)
else:
return _permute_dims(expr, permutation)
if isinstance(expr, ArrayAdd):
return self._ArrayDiagonal_denest_ArrayAdd(expr, *diagonal_indices)
if isinstance(expr, ArrayDiagonal):
return self._ArrayDiagonal_denest_ArrayDiagonal(expr, *diagonal_indices)
if isinstance(expr, PermuteDims):
return self._ArrayDiagonal_denest_PermuteDims(expr, *diagonal_indices)
if isinstance(expr, (ZeroArray, ZeroMatrix)):
positions, shape = self._get_positions_shape(expr.shape, diagonal_indices)
return ZeroArray(*shape)
return self.func(expr, *diagonal_indices, canonicalize=False)
def doit(self, **kwargs):
deep = kwargs.get("deep", True)
if deep:
return self.func(*[arg.doit(**kwargs) for arg in self.args])._canonicalize()
else:
return self._canonicalize()
@staticmethod
def _validate(expr, *diagonal_indices, **kwargs):
# Check that no diagonalization happens on indices with mismatched
# dimensions:
shape = get_shape(expr)
for i in diagonal_indices:
if any(j >= len(shape) for j in i):
raise ValueError("index is larger than expression shape")
if len({shape[j] for j in i}) != 1:
raise ValueError("diagonalizing indices of different dimensions")
if not kwargs.get("allow_trivial_diags", False) and len(i) <= 1:
raise ValueError("need at least two axes to diagonalize")
if len(set(i)) != len(i):
raise ValueError("axis index cannot be repeated")
@staticmethod
def _remove_trivial_dimensions(shape, *diagonal_indices):
return [tuple(j for j in i) for i in diagonal_indices if shape[i[0]] != 1]
@property
def expr(self):
return self.args[0]
@property
def diagonal_indices(self):
return self.args[1:]
@staticmethod
def _flatten(expr, *outer_diagonal_indices):
inner_diagonal_indices = expr.diagonal_indices
all_inner = [j for i in inner_diagonal_indices for j in i]
all_inner.sort()
# TODO: add API for total rank and cumulative rank:
total_rank = _get_subrank(expr)
inner_rank = len(all_inner)
outer_rank = total_rank - inner_rank
shifts = [0 for i in range(outer_rank)]
counter = 0
pointer = 0
for i in range(outer_rank):
while pointer < inner_rank and counter >= all_inner[pointer]:
counter += 1
pointer += 1
shifts[i] += pointer
counter += 1
outer_diagonal_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_diagonal_indices)
diagonal_indices = inner_diagonal_indices + outer_diagonal_indices
return _array_diagonal(expr.expr, *diagonal_indices)
@classmethod
def _ArrayDiagonal_denest_ArrayAdd(cls, expr, *diagonal_indices):
return _array_add(*[_array_diagonal(arg, *diagonal_indices) for arg in expr.args])
@classmethod
def _ArrayDiagonal_denest_ArrayDiagonal(cls, expr, *diagonal_indices):
return cls._flatten(expr, *diagonal_indices)
@classmethod
def _ArrayDiagonal_denest_PermuteDims(cls, expr: PermuteDims, *diagonal_indices):
back_diagonal_indices = [[expr.permutation(j) for j in i] for i in diagonal_indices]
nondiag = [i for i in range(get_rank(expr)) if not any(i in j for j in diagonal_indices)]
back_nondiag = [expr.permutation(i) for i in nondiag]
remap = {e: i for i, e in enumerate(sorted(back_nondiag))}
new_permutation1 = [remap[i] for i in back_nondiag]
shift = len(new_permutation1)
diag_block_perm = [i + shift for i in range(len(back_diagonal_indices))]
new_permutation = new_permutation1 + diag_block_perm
return _permute_dims(
_array_diagonal(
expr.expr,
*back_diagonal_indices
),
new_permutation
)
def _push_indices_down_nonstatic(self, indices):
transform = lambda x: self._positions[x] if x < len(self._positions) else None
return _apply_recursively_over_nested_lists(transform, indices)
def _push_indices_up_nonstatic(self, indices):
def transform(x):
for i, e in enumerate(self._positions):
if (isinstance(e, int) and x == e) or (isinstance(e, tuple) and x in e):
return i
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _push_indices_down(cls, diagonal_indices, indices, rank):
positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
transform = lambda x: positions[x] if x < len(positions) else None
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _push_indices_up(cls, diagonal_indices, indices, rank):
positions, shape = cls._get_positions_shape(range(rank), diagonal_indices)
def transform(x):
for i, e in enumerate(positions):
if (isinstance(e, int) and x == e) or (isinstance(e, (tuple, Tuple)) and (x in e)):
return i
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _get_positions_shape(cls, shape, diagonal_indices):
data1 = tuple((i, shp) for i, shp in enumerate(shape) if not any(i in j for j in diagonal_indices))
pos1, shp1 = zip(*data1) if data1 else ((), ())
data2 = tuple((i, shape[i[0]]) for i in diagonal_indices)
pos2, shp2 = zip(*data2) if data2 else ((), ())
positions = pos1 + pos2
shape = shp1 + shp2
return positions, shape
def as_explicit(self):
return tensordiagonal(self.expr.as_explicit(), *self.diagonal_indices)
class ArrayElementwiseApplyFunc(_CodegenArrayAbstract):
def __new__(cls, function, element):
if not isinstance(function, Lambda):
d = Dummy('d')
function = Lambda(d, function(d))
obj = _CodegenArrayAbstract.__new__(cls, function, element)
obj._subranks = _get_subranks(element)
return obj
@property
def function(self):
return self.args[0]
@property
def expr(self):
return self.args[1]
@property
def shape(self):
return self.expr.shape
def _get_function_fdiff(self):
d = Dummy("d")
function = self.function(d)
fdiff = function.diff(d)
if isinstance(fdiff, Function):
fdiff = type(fdiff)
else:
fdiff = Lambda(d, fdiff)
return fdiff
class ArrayContraction(_CodegenArrayAbstract):
r"""
This class is meant to represent contractions of arrays in a form easily
processable by the code printers.
"""
def __new__(cls, expr, *contraction_indices, **kwargs):
contraction_indices = _sort_contraction_indices(contraction_indices)
expr = _sympify(expr)
canonicalize = kwargs.get("canonicalize", False)
obj = Basic.__new__(cls, expr, *contraction_indices)
obj._subranks = _get_subranks(expr)
obj._mapping = _get_mapping_from_subranks(obj._subranks)
free_indices_to_position = {i: i for i in range(sum(obj._subranks)) if all(i not in cind for cind in contraction_indices)}
obj._free_indices_to_position = free_indices_to_position
shape = get_shape(expr)
cls._validate(expr, *contraction_indices)
if shape:
shape = tuple(shp for i, shp in enumerate(shape) if not any(i in j for j in contraction_indices))
obj._shape = shape
if canonicalize:
return obj._canonicalize()
return obj
def _canonicalize(self):
expr = self.expr
contraction_indices = self.contraction_indices
if len(contraction_indices) == 0:
return expr
if isinstance(expr, ArrayContraction):
return self._ArrayContraction_denest_ArrayContraction(expr, *contraction_indices)
if isinstance(expr, (ZeroArray, ZeroMatrix)):
return self._ArrayContraction_denest_ZeroArray(expr, *contraction_indices)
if isinstance(expr, PermuteDims):
return self._ArrayContraction_denest_PermuteDims(expr, *contraction_indices)
if isinstance(expr, ArrayTensorProduct):
expr, contraction_indices = self._sort_fully_contracted_args(expr, contraction_indices)
expr, contraction_indices = self._lower_contraction_to_addends(expr, contraction_indices)
if len(contraction_indices) == 0:
return expr
if isinstance(expr, ArrayDiagonal):
return self._ArrayContraction_denest_ArrayDiagonal(expr, *contraction_indices)
if isinstance(expr, ArrayAdd):
return self._ArrayContraction_denest_ArrayAdd(expr, *contraction_indices)
# Check single index contractions on 1-dimensional axes:
contraction_indices = [i for i in contraction_indices if len(i) > 1 or get_shape(expr)[i[0]] != 1]
if len(contraction_indices) == 0:
return expr
return self.func(expr, *contraction_indices, canonicalize=False)
def doit(self, **kwargs):
deep = kwargs.get("deep", True)
if deep:
return self.func(*[arg.doit(**kwargs) for arg in self.args])._canonicalize()
else:
return self._canonicalize()
def __mul__(self, other):
if other == 1:
return self
else:
raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.")
def __rmul__(self, other):
if other == 1:
return self
else:
raise NotImplementedError("Product of N-dim arrays is not uniquely defined. Use another method.")
@staticmethod
def _validate(expr, *contraction_indices):
shape = get_shape(expr)
if shape is None:
return
# Check that no contraction happens when the shape is mismatched:
for i in contraction_indices:
if len({shape[j] for j in i if shape[j] != -1}) != 1:
raise ValueError("contracting indices of different dimensions")
@classmethod
def _push_indices_down(cls, contraction_indices, indices):
flattened_contraction_indices = [j for i in contraction_indices for j in i]
flattened_contraction_indices.sort()
transform = _build_push_indices_down_func_transformation(flattened_contraction_indices)
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _push_indices_up(cls, contraction_indices, indices):
flattened_contraction_indices = [j for i in contraction_indices for j in i]
flattened_contraction_indices.sort()
transform = _build_push_indices_up_func_transformation(flattened_contraction_indices)
return _apply_recursively_over_nested_lists(transform, indices)
@classmethod
def _lower_contraction_to_addends(cls, expr, contraction_indices):
if isinstance(expr, ArrayAdd):
raise NotImplementedError()
if not isinstance(expr, ArrayTensorProduct):
return expr, contraction_indices
subranks = expr.subranks
cumranks = list(accumulate([0] + subranks))
contraction_indices_remaining = []
contraction_indices_args = [[] for i in expr.args]
backshift = set([])
for i, contraction_group in enumerate(contraction_indices):
for j in range(len(expr.args)):
if not isinstance(expr.args[j], ArrayAdd):
continue
if all(cumranks[j] <= k < cumranks[j+1] for k in contraction_group):
contraction_indices_args[j].append([k - cumranks[j] for k in contraction_group])
backshift.update(contraction_group)
break
else:
contraction_indices_remaining.append(contraction_group)
if len(contraction_indices_remaining) == len(contraction_indices):
return expr, contraction_indices
total_rank = get_rank(expr)
shifts = list(accumulate([1 if i in backshift else 0 for i in range(total_rank)]))
contraction_indices_remaining = [Tuple.fromiter(j - shifts[j] for j in i) for i in contraction_indices_remaining]
ret = _array_tensor_product(*[
_array_contraction(arg, *contr) for arg, contr in zip(expr.args, contraction_indices_args)
])
return ret, contraction_indices_remaining
def split_multiple_contractions(self):
"""
Recognize multiple contractions and attempt at rewriting them as paired-contractions.
This allows some contractions involving more than two indices to be
rewritten as multiple contractions involving two indices, thus allowing
the expression to be rewritten as a matrix multiplication line.
Examples:
* `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C`
Care for:
- matrix being diagonalized (i.e. `A_ii`)
- vectors being diagonalized (i.e. `a_i0`)
Multiple contractions can be split into matrix multiplications if
not more than two arguments are non-diagonals or non-vectors.
Vectors get diagonalized while diagonal matrices remain diagonal.
The non-diagonal matrices can be at the beginning or at the end
of the final matrix multiplication line.
"""
editor = _EditArrayContraction(self)
contraction_indices = self.contraction_indices
onearray_insert = []
for indl, links in enumerate(contraction_indices):
if len(links) <= 2:
continue
# Check multiple contractions:
#
# Examples:
#
# * `A_ij b_j0 C_jk` ===> `A*DiagMatrix(b)*C \otimes OneArray(1)` with permutation (1 2)
#
# Care for:
# - matrix being diagonalized (i.e. `A_ii`)
# - vectors being diagonalized (i.e. `a_i0`)
# Multiple contractions can be split into matrix multiplications if
# not more than three arguments are non-diagonals or non-vectors.
#
# Vectors get diagonalized while diagonal matrices remain diagonal.
# The non-diagonal matrices can be at the beginning or at the end
# of the final matrix multiplication line.
positions = editor.get_mapping_for_index(indl)
# Also consider the case of diagonal matrices being contracted:
current_dimension = self.expr.shape[links[0]]
not_vectors: tTuple[_ArgE, int] = []
vectors: tTuple[_ArgE, int] = []
for arg_ind, rel_ind in positions:
arg = editor.args_with_ind[arg_ind]
mat = arg.element
abs_arg_start, abs_arg_end = editor.get_absolute_range(arg)
other_arg_pos = 1-rel_ind
other_arg_abs = abs_arg_start + other_arg_pos
if ((1 not in mat.shape) or
((current_dimension == 1) is True and mat.shape != (1, 1)) or
any(other_arg_abs in l for li, l in enumerate(contraction_indices) if li != indl)
):
not_vectors.append((arg, rel_ind))
else:
vectors.append((arg, rel_ind))
if len(not_vectors) > 2:
# If more than two arguments in the multiple contraction are
# non-vectors and non-diagonal matrices, we cannot find a way
# to split this contraction into a matrix multiplication line:
continue
# Three cases to handle:
# - zero non-vectors
# - one non-vector
# - two non-vectors
for v, rel_ind in vectors:
v.element = diagonalize_vector(v.element)
vectors_to_loop = not_vectors[:1] + vectors + not_vectors[1:]
first_not_vector, rel_ind = vectors_to_loop[0]
new_index = first_not_vector.indices[rel_ind]
for v, rel_ind in vectors_to_loop[1:-1]:
v.indices[rel_ind] = new_index
new_index = editor.get_new_contraction_index()
assert v.indices.index(None) == 1 - rel_ind
v.indices[v.indices.index(None)] = new_index
onearray_insert.append(v)
last_vec, rel_ind = vectors_to_loop[-1]
last_vec.indices[rel_ind] = new_index
for v in onearray_insert:
editor.insert_after(v, _ArgE(OneArray(1), [None]))
return editor.to_array_contraction()
def flatten_contraction_of_diagonal(self):
if not isinstance(self.expr, ArrayDiagonal):
return self
contraction_down = self.expr._push_indices_down(self.expr.diagonal_indices, self.contraction_indices)
new_contraction_indices = []
diagonal_indices = self.expr.diagonal_indices[:]
for i in contraction_down:
contraction_group = list(i)
for j in i:
diagonal_with = [k for k in diagonal_indices if j in k]
contraction_group.extend([l for k in diagonal_with for l in k])
diagonal_indices = [k for k in diagonal_indices if k not in diagonal_with]
new_contraction_indices.append(sorted(set(contraction_group)))
new_contraction_indices = ArrayDiagonal._push_indices_up(diagonal_indices, new_contraction_indices)
return _array_contraction(
_array_diagonal(
self.expr.expr,
*diagonal_indices
),
*new_contraction_indices
)
@staticmethod
def _get_free_indices_to_position_map(free_indices, contraction_indices):
free_indices_to_position = {}
flattened_contraction_indices = [j for i in contraction_indices for j in i]
counter = 0
for ind in free_indices:
while counter in flattened_contraction_indices:
counter += 1
free_indices_to_position[ind] = counter
counter += 1
return free_indices_to_position
@staticmethod
def _get_index_shifts(expr):
"""
Get the mapping of indices at the positions before the contraction
occurs.
Examples
========
>>> from sympy.tensor.array import tensorproduct, tensorcontraction
>>> from sympy import MatrixSymbol
>>> M = MatrixSymbol("M", 3, 3)
>>> N = MatrixSymbol("N", 3, 3)
>>> cg = tensorcontraction(tensorproduct(M, N), [1, 2])
>>> cg._get_index_shifts(cg)
[0, 2]
Indeed, ``cg`` after the contraction has two dimensions, 0 and 1. They
need to be shifted by 0 and 2 to get the corresponding positions before
the contraction (that is, 0 and 3).
"""
inner_contraction_indices = expr.contraction_indices
all_inner = [j for i in inner_contraction_indices for j in i]
all_inner.sort()
# TODO: add API for total rank and cumulative rank:
total_rank = _get_subrank(expr)
inner_rank = len(all_inner)
outer_rank = total_rank - inner_rank
shifts = [0 for i in range(outer_rank)]
counter = 0
pointer = 0
for i in range(outer_rank):
while pointer < inner_rank and counter >= all_inner[pointer]:
counter += 1
pointer += 1
shifts[i] += pointer
counter += 1
return shifts
@staticmethod
def _convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices):
shifts = ArrayContraction._get_index_shifts(expr)
outer_contraction_indices = tuple(tuple(shifts[j] + j for j in i) for i in outer_contraction_indices)
return outer_contraction_indices
@staticmethod
def _flatten(expr, *outer_contraction_indices):
inner_contraction_indices = expr.contraction_indices
outer_contraction_indices = ArrayContraction._convert_outer_indices_to_inner_indices(expr, *outer_contraction_indices)
contraction_indices = inner_contraction_indices + outer_contraction_indices
return _array_contraction(expr.expr, *contraction_indices)
@classmethod
def _ArrayContraction_denest_ArrayContraction(cls, expr, *contraction_indices):
return cls._flatten(expr, *contraction_indices)
@classmethod
def _ArrayContraction_denest_ZeroArray(cls, expr, *contraction_indices):
contraction_indices_flat = [j for i in contraction_indices for j in i]
shape = [e for i, e in enumerate(expr.shape) if i not in contraction_indices_flat]
return ZeroArray(*shape)
@classmethod
def _ArrayContraction_denest_ArrayAdd(cls, expr, *contraction_indices):
return _array_add(*[_array_contraction(i, *contraction_indices) for i in expr.args])
@classmethod
def _ArrayContraction_denest_PermuteDims(cls, expr, *contraction_indices):
permutation = expr.permutation
plist = permutation.array_form
new_contraction_indices = [tuple(permutation(j) for j in i) for i in contraction_indices]
new_plist = [i for i in plist if not any(i in j for j in new_contraction_indices)]
new_plist = cls._push_indices_up(new_contraction_indices, new_plist)
return _permute_dims(
_array_contraction(expr.expr, *new_contraction_indices),
Permutation(new_plist)
)
@classmethod
def _ArrayContraction_denest_ArrayDiagonal(cls, expr: 'ArrayDiagonal', *contraction_indices):
diagonal_indices = list(expr.diagonal_indices)
down_contraction_indices = expr._push_indices_down(expr.diagonal_indices, contraction_indices, get_rank(expr.expr))
# Flatten diagonally contracted indices:
down_contraction_indices = [[k for j in i for k in (j if isinstance(j, (tuple, Tuple)) else [j])] for i in down_contraction_indices]
new_contraction_indices = []
for contr_indgrp in down_contraction_indices:
ind = contr_indgrp[:]
for j, diag_indgrp in enumerate(diagonal_indices):
if diag_indgrp is None:
continue
if any(i in diag_indgrp for i in contr_indgrp):
ind.extend(diag_indgrp)
diagonal_indices[j] = None
new_contraction_indices.append(sorted(set(ind)))
new_diagonal_indices_down = [i for i in diagonal_indices if i is not None]
new_diagonal_indices = ArrayContraction._push_indices_up(new_contraction_indices, new_diagonal_indices_down)
return _array_diagonal(
_array_contraction(expr.expr, *new_contraction_indices),
*new_diagonal_indices
)
@classmethod
def _sort_fully_contracted_args(cls, expr, contraction_indices):
if expr.shape is None:
return expr, contraction_indices
cumul = list(accumulate([0] + expr.subranks))
index_blocks = [list(range(cumul[i], cumul[i+1])) for i in range(len(expr.args))]
contraction_indices_flat = {j for i in contraction_indices for j in i}
fully_contracted = [all(j in contraction_indices_flat for j in range(cumul[i], cumul[i+1])) for i, arg in enumerate(expr.args)]
new_pos = sorted(range(len(expr.args)), key=lambda x: (0, default_sort_key(expr.args[x])) if fully_contracted[x] else (1,))
new_args = [expr.args[i] for i in new_pos]
new_index_blocks_flat = [j for i in new_pos for j in index_blocks[i]]
index_permutation_array_form = _af_invert(new_index_blocks_flat)
new_contraction_indices = [tuple(index_permutation_array_form[j] for j in i) for i in contraction_indices]
new_contraction_indices = _sort_contraction_indices(new_contraction_indices)
return _array_tensor_product(*new_args), new_contraction_indices
def _get_contraction_tuples(self):
r"""
Return tuples containing the argument index and position within the
argument of the index position.
Examples
========
>>> from sympy import MatrixSymbol
>>> from sympy.abc import N
>>> from sympy.tensor.array import tensorproduct, tensorcontraction
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> cg = tensorcontraction(tensorproduct(A, B), (1, 2))
>>> cg._get_contraction_tuples()
[[(0, 1), (1, 0)]]
Notes
=====
Here the contraction pair `(1, 2)` meaning that the 2nd and 3rd indices
of the tensor product `A\otimes B` are contracted, has been transformed
into `(0, 1)` and `(1, 0)`, identifying the same indices in a different
notation. `(0, 1)` is the second index (1) of the first argument (i.e.
0 or `A`). `(1, 0)` is the first index (i.e. 0) of the second
argument (i.e. 1 or `B`).
"""
mapping = self._mapping
return [[mapping[j] for j in i] for i in self.contraction_indices]
@staticmethod
def _contraction_tuples_to_contraction_indices(expr, contraction_tuples):
# TODO: check that `expr` has `.subranks`:
ranks = expr.subranks
cumulative_ranks = [0] + list(accumulate(ranks))
return [tuple(cumulative_ranks[j]+k for j, k in i) for i in contraction_tuples]
@property
def free_indices(self):
return self._free_indices[:]
@property
def free_indices_to_position(self):
return dict(self._free_indices_to_position)
@property
def expr(self):
return self.args[0]
@property
def contraction_indices(self):
return self.args[1:]
def _contraction_indices_to_components(self):
expr = self.expr
if not isinstance(expr, ArrayTensorProduct):
raise NotImplementedError("only for contractions of tensor products")
ranks = expr.subranks
mapping = {}
counter = 0
for i, rank in enumerate(ranks):
for j in range(rank):
mapping[counter] = (i, j)
counter += 1
return mapping
def sort_args_by_name(self):
"""
Sort arguments in the tensor product so that their order is lexicographical.
Examples
========
>>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
>>> from sympy import MatrixSymbol
>>> from sympy.abc import N
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> C = MatrixSymbol("C", N, N)
>>> D = MatrixSymbol("D", N, N)
>>> cg = convert_matrix_to_array(C*D*A*B)
>>> cg
ArrayContraction(ArrayTensorProduct(A, D, C, B), (0, 3), (1, 6), (2, 5))
>>> cg.sort_args_by_name()
ArrayContraction(ArrayTensorProduct(A, D, B, C), (0, 3), (1, 4), (2, 7))
"""
expr = self.expr
if not isinstance(expr, ArrayTensorProduct):
return self
args = expr.args
sorted_data = sorted(enumerate(args), key=lambda x: default_sort_key(x[1]))
pos_sorted, args_sorted = zip(*sorted_data)
reordering_map = {i: pos_sorted.index(i) for i, arg in enumerate(args)}
contraction_tuples = self._get_contraction_tuples()
contraction_tuples = [[(reordering_map[j], k) for j, k in i] for i in contraction_tuples]
c_tp = _array_tensor_product(*args_sorted)
new_contr_indices = self._contraction_tuples_to_contraction_indices(
c_tp,
contraction_tuples
)
return _array_contraction(c_tp, *new_contr_indices)
def _get_contraction_links(self):
r"""
Returns a dictionary of links between arguments in the tensor product
being contracted.
See the example for an explanation of the values.
Examples
========
>>> from sympy import MatrixSymbol
>>> from sympy.abc import N
>>> from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> C = MatrixSymbol("C", N, N)
>>> D = MatrixSymbol("D", N, N)
Matrix multiplications are pairwise contractions between neighboring
matrices:
`A_{ij} B_{jk} C_{kl} D_{lm}`
>>> cg = convert_matrix_to_array(A*B*C*D)
>>> cg
ArrayContraction(ArrayTensorProduct(B, C, A, D), (0, 5), (1, 2), (3, 6))
>>> cg._get_contraction_links()
{0: {0: (2, 1), 1: (1, 0)}, 1: {0: (0, 1), 1: (3, 0)}, 2: {1: (0, 0)}, 3: {0: (1, 1)}}
This dictionary is interpreted as follows: argument in position 0 (i.e.
matrix `A`) has its second index (i.e. 1) contracted to `(1, 0)`, that
is argument in position 1 (matrix `B`) on the first index slot of `B`,
this is the contraction provided by the index `j` from `A`.
The argument in position 1 (that is, matrix `B`) has two contractions,
the ones provided by the indices `j` and `k`, respectively the first
and second indices (0 and 1 in the sub-dict). The link `(0, 1)` and
`(2, 0)` respectively. `(0, 1)` is the index slot 1 (the 2nd) of
argument in position 0 (that is, `A_{\ldot j}`), and so on.
"""
args, dlinks = _get_contraction_links([self], self.subranks, *self.contraction_indices)
return dlinks
def as_explicit(self):
return tensorcontraction(self.expr.as_explicit(), *self.contraction_indices)
class _ArgE:
"""
The ``_ArgE`` object contains references to the array expression
(``.element``) and a list containing the information about index
contractions (``.indices``).
Index contractions are numbered and contracted indices show the number of
the contraction. Uncontracted indices have ``None`` value.
For example:
``_ArgE(M, [None, 3])``
This object means that expression ``M`` is part of an array contraction
and has two indices, the first is not contracted (value ``None``),
the second index is contracted to the 4th (i.e. number ``3``) group of the
array contraction object.
"""
indices: List[Optional[int]]
def __init__(self, element, indices: Optional[List[Optional[int]]] = None):
self.element = element
if indices is None:
self.indices = [None for i in range(get_rank(element))]
else:
self.indices = indices
def __str__(self):
return "_ArgE(%s, %s)" % (self.element, self.indices)
__repr__ = __str__
class _IndPos:
"""
Index position, requiring two integers in the constructor:
- arg: the position of the argument in the tensor product,
- rel: the relative position of the index inside the argument.
"""
def __init__(self, arg: int, rel: int):
self.arg = arg
self.rel = rel
def __str__(self):
return "_IndPos(%i, %i)" % (self.arg, self.rel)
__repr__ = __str__
def __iter__(self):
yield from [self.arg, self.rel]
class _EditArrayContraction:
"""
Utility class to help manipulate array contraction objects.
This class takes as input an ``ArrayContraction`` object and turns it into
an editable object.
The field ``args_with_ind`` of this class is a list of ``_ArgE`` objects
which can be used to easily edit the contraction structure of the
expression.
Once editing is finished, the ``ArrayContraction`` object may be recreated
by calling the ``.to_array_contraction()`` method.
"""
def __init__(self, base_array: typing.Union[ArrayContraction, ArrayDiagonal, ArrayTensorProduct]):
expr: Basic
diagonalized: tTuple[tTuple[int, ...], ...]
contraction_indices: List[tTuple[int]]
if isinstance(base_array, ArrayContraction):
mapping = _get_mapping_from_subranks(base_array.subranks)
expr = base_array.expr
contraction_indices = base_array.contraction_indices
diagonalized = ()
elif isinstance(base_array, ArrayDiagonal):
if isinstance(base_array.expr, ArrayContraction):
mapping = _get_mapping_from_subranks(base_array.expr.subranks)
expr = base_array.expr.expr
diagonalized = ArrayContraction._push_indices_down(base_array.expr.contraction_indices, base_array.diagonal_indices)
contraction_indices = base_array.expr.contraction_indices
elif isinstance(base_array.expr, ArrayTensorProduct):
mapping = {}
expr = base_array.expr
diagonalized = base_array.diagonal_indices
contraction_indices = []
else:
mapping = {}
expr = base_array.expr
diagonalized = base_array.diagonal_indices
contraction_indices = []
elif isinstance(base_array, ArrayTensorProduct):
expr = base_array
contraction_indices = []
diagonalized = ()
else:
raise NotImplementedError()
if isinstance(expr, ArrayTensorProduct):
args = list(expr.args)
else:
args = [expr]
args_with_ind: List[_ArgE] = [_ArgE(arg) for arg in args]
for i, contraction_tuple in enumerate(contraction_indices):
for j in contraction_tuple:
arg_pos, rel_pos = mapping[j]
args_with_ind[arg_pos].indices[rel_pos] = i
self.args_with_ind: List[_ArgE] = args_with_ind
self.number_of_contraction_indices: int = len(contraction_indices)
self._track_permutation: Optional[List[List[int]]] = None
mapping = _get_mapping_from_subranks(base_array.subranks)
# Trick: add diagonalized indices as negative indices into the editor object:
for i, e in enumerate(diagonalized):
for j in e:
arg_pos, rel_pos = mapping[j]
self.args_with_ind[arg_pos].indices[rel_pos] = -1 - i
def insert_after(self, arg: _ArgE, new_arg: _ArgE):
pos = self.args_with_ind.index(arg)
self.args_with_ind.insert(pos + 1, new_arg)
def get_new_contraction_index(self):
self.number_of_contraction_indices += 1
return self.number_of_contraction_indices - 1
def refresh_indices(self):
updates: tDict[int, int] = {}
for arg_with_ind in self.args_with_ind:
updates.update({i: -1 for i in arg_with_ind.indices if i is not None})
for i, e in enumerate(sorted(updates)):
updates[e] = i
self.number_of_contraction_indices: int = len(updates)
for arg_with_ind in self.args_with_ind:
arg_with_ind.indices = [updates.get(i, None) for i in arg_with_ind.indices]
def merge_scalars(self):
scalars = []
for arg_with_ind in self.args_with_ind:
if len(arg_with_ind.indices) == 0:
scalars.append(arg_with_ind)
for i in scalars:
self.args_with_ind.remove(i)
scalar = Mul.fromiter([i.element for i in scalars])
if len(self.args_with_ind) == 0:
self.args_with_ind.append(_ArgE(scalar))
else:
from sympy.tensor.array.expressions.conv_array_to_matrix import _a2m_tensor_product
self.args_with_ind[0].element = _a2m_tensor_product(scalar, self.args_with_ind[0].element)
def to_array_contraction(self):
# Count the ranks of the arguments:
counter = 0
# Create a collector for the new diagonal indices:
diag_indices = defaultdict(list)
count_index_freq = Counter()
for arg_with_ind in self.args_with_ind:
count_index_freq.update(Counter(arg_with_ind.indices))
free_index_count = count_index_freq[None]
# Construct the inverse permutation:
inv_perm1 = []
inv_perm2 = []
# Keep track of which diagonal indices have already been processed:
done = set([])
# Counter for the diagonal indices:
counter4 = 0
for arg_with_ind in self.args_with_ind:
# If some diagonalization axes have been removed, they should be
# permuted in order to keep the permutation.
# Add permutation here
counter2 = 0 # counter for the indices
for i in arg_with_ind.indices:
if i is None:
inv_perm1.append(counter4)
counter2 += 1
counter4 += 1
continue
if i >= 0:
continue
# Reconstruct the diagonal indices:
diag_indices[-1 - i].append(counter + counter2)
if count_index_freq[i] == 1 and i not in done:
inv_perm1.append(free_index_count - 1 - i)
done.add(i)
elif i not in done:
inv_perm2.append(free_index_count - 1 - i)
done.add(i)
counter2 += 1
# Remove negative indices to restore a proper editor object:
arg_with_ind.indices = [i if i is not None and i >= 0 else None for i in arg_with_ind.indices]
counter += len([i for i in arg_with_ind.indices if i is None or i < 0])
inverse_permutation = inv_perm1 + inv_perm2
permutation = _af_invert(inverse_permutation)
# Get the diagonal indices after the detection of HadamardProduct in the expression:
diag_indices_filtered = [tuple(v) for v in diag_indices.values() if len(v) > 1]
self.merge_scalars()
self.refresh_indices()
args = [arg.element for arg in self.args_with_ind]
contraction_indices = self.get_contraction_indices()
expr = _array_contraction(_array_tensor_product(*args), *contraction_indices)
expr2 = _array_diagonal(expr, *diag_indices_filtered)
if self._track_permutation is not None:
permutation2 = _af_invert([j for i in self._track_permutation for j in i])
expr2 = _permute_dims(expr2, permutation2)
expr3 = _permute_dims(expr2, permutation)
return expr3
def get_contraction_indices(self) -> List[List[int]]:
contraction_indices: List[List[int]] = [[] for i in range(self.number_of_contraction_indices)]
current_position: int = 0
for i, arg_with_ind in enumerate(self.args_with_ind):
for j in arg_with_ind.indices:
if j is not None:
contraction_indices[j].append(current_position)
current_position += 1
return contraction_indices
def get_mapping_for_index(self, ind) -> List[_IndPos]:
if ind >= self.number_of_contraction_indices:
raise ValueError("index value exceeding the index range")
positions: List[_IndPos] = []
for i, arg_with_ind in enumerate(self.args_with_ind):
for j, arg_ind in enumerate(arg_with_ind.indices):
if ind == arg_ind:
positions.append(_IndPos(i, j))
return positions
def get_contraction_indices_to_ind_rel_pos(self) -> List[List[_IndPos]]:
contraction_indices: List[List[_IndPos]] = [[] for i in range(self.number_of_contraction_indices)]
for i, arg_with_ind in enumerate(self.args_with_ind):
for j, ind in enumerate(arg_with_ind.indices):
if ind is not None:
contraction_indices[ind].append(_IndPos(i, j))
return contraction_indices
def count_args_with_index(self, index: int) -> int:
"""
Count the number of arguments that have the given index.
"""
counter: int = 0
for arg_with_ind in self.args_with_ind:
if index in arg_with_ind.indices:
counter += 1
return counter
def get_args_with_index(self, index: int) -> List[_ArgE]:
"""
Get a list of arguments having the given index.
"""
ret: List[_ArgE] = [i for i in self.args_with_ind if index in i.indices]
return ret
@property
def number_of_diagonal_indices(self):
data = set([])
for arg in self.args_with_ind:
data.update({i for i in arg.indices if i is not None and i < 0})
return len(data)
def track_permutation_start(self):
permutation = []
perm_diag = []
counter: int = 0
counter2: int = -1
for arg_with_ind in self.args_with_ind:
perm = []
for i in arg_with_ind.indices:
if i is not None:
if i < 0:
perm_diag.append(counter2)
counter2 -= 1
continue
perm.append(counter)
counter += 1
permutation.append(perm)
max_ind = max([max(i) if i else -1 for i in permutation]) if permutation else -1
perm_diag = [max_ind - i for i in perm_diag]
self._track_permutation = permutation + [perm_diag]
def track_permutation_merge(self, destination: _ArgE, from_element: _ArgE):
index_destination = self.args_with_ind.index(destination)
index_element = self.args_with_ind.index(from_element)
self._track_permutation[index_destination].extend(self._track_permutation[index_element]) # type: ignore
self._track_permutation.pop(index_element) # type: ignore
def get_absolute_free_range(self, arg: _ArgE) -> typing.Tuple[int, int]:
"""
Return the range of the free indices of the arg as absolute positions
among all free indices.
"""
counter = 0
for arg_with_ind in self.args_with_ind:
number_free_indices = len([i for i in arg_with_ind.indices if i is None])
if arg_with_ind == arg:
return counter, counter + number_free_indices
counter += number_free_indices
raise IndexError("argument not found")
def get_absolute_range(self, arg: _ArgE) -> typing.Tuple[int, int]:
"""
Return the absolute range of indices for arg, disregarding dummy
indices.
"""
counter = 0
for arg_with_ind in self.args_with_ind:
number_indices = len(arg_with_ind.indices)
if arg_with_ind == arg:
return counter, counter + number_indices
counter += number_indices
raise IndexError("argument not found")
def get_rank(expr):
if isinstance(expr, (MatrixExpr, MatrixElement)):
return 2
if isinstance(expr, _CodegenArrayAbstract):
return len(expr.shape)
if isinstance(expr, NDimArray):
return expr.rank()
if isinstance(expr, Indexed):
return expr.rank
if isinstance(expr, IndexedBase):
shape = expr.shape
if shape is None:
return -1
else:
return len(shape)
if hasattr(expr, "shape"):
return len(expr.shape)
return 0
def _get_subrank(expr):
if isinstance(expr, _CodegenArrayAbstract):
return expr.subrank()
return get_rank(expr)
def _get_subranks(expr):
if isinstance(expr, _CodegenArrayAbstract):
return expr.subranks
else:
return [get_rank(expr)]
def get_shape(expr):
if hasattr(expr, "shape"):
return expr.shape
return ()
def nest_permutation(expr):
if isinstance(expr, PermuteDims):
return expr.nest_permutation()
else:
return expr
def _array_tensor_product(*args, **kwargs):
return ArrayTensorProduct(*args, canonicalize=True, **kwargs)
def _array_contraction(expr, *contraction_indices, **kwargs):
return ArrayContraction(expr, *contraction_indices, canonicalize=True, **kwargs)
def _array_diagonal(expr, *diagonal_indices, **kwargs):
return ArrayDiagonal(expr, *diagonal_indices, canonicalize=True, **kwargs)
def _permute_dims(expr, permutation, **kwargs):
return PermuteDims(expr, permutation, canonicalize=True, **kwargs)
def _array_add(*args, **kwargs):
return ArrayAdd(*args, canonicalize=True, **kwargs)
|
96dd685071e7f41c2e7b61742de81425d3a11f099ba41647c4a9594564042b70 | import operator
from functools import reduce, singledispatch
from sympy.core.expr import Expr
from sympy.core.singleton import S
from sympy.matrices.expressions.hadamard import HadamardProduct
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices.expressions.matexpr import (MatrixExpr, MatrixSymbol)
from sympy.matrices.expressions.special import Identity
from sympy.matrices.expressions.transpose import Transpose
from sympy.combinatorics.permutations import _af_invert
from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
from sympy.tensor.array.expressions.array_expressions import ZeroArray, ArraySymbol, ArrayTensorProduct, \
ArrayAdd, PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, get_rank, \
get_shape, ArrayContraction, _array_tensor_product, _array_contraction, _array_diagonal, _array_add, _permute_dims
from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
@singledispatch
def array_derive(expr, x):
raise NotImplementedError(f"not implemented for type {type(expr)}")
@array_derive.register(Expr) # type: ignore
def _(expr: Expr, x: Expr):
return ZeroArray(*x.shape) # type: ignore
@array_derive.register(ArrayTensorProduct) # type: ignore
def _(expr: ArrayTensorProduct, x: Expr):
args = expr.args
addend_list = []
for i, arg in enumerate(expr.args):
darg = array_derive(arg, x)
if darg == 0:
continue
args_prev = args[:i]
args_succ = args[i+1:]
shape_prev = reduce(operator.add, map(get_shape, args_prev), ())
shape_succ = reduce(operator.add, map(get_shape, args_succ), ())
addend = _array_tensor_product(*args_prev, darg, *args_succ)
tot1 = len(get_shape(x))
tot2 = tot1 + len(shape_prev)
tot3 = tot2 + len(get_shape(arg))
tot4 = tot3 + len(shape_succ)
perm = [i for i in range(tot1, tot2)] + \
[i for i in range(tot1)] + [i for i in range(tot2, tot3)] + \
[i for i in range(tot3, tot4)]
addend = _permute_dims(addend, _af_invert(perm))
addend_list.append(addend)
if len(addend_list) == 1:
return addend_list[0]
elif len(addend_list) == 0:
return S.Zero
else:
return _array_add(*addend_list)
@array_derive.register(ArraySymbol) # type: ignore
def _(expr: ArraySymbol, x: Expr):
if expr == x:
return _permute_dims(
ArrayTensorProduct.fromiter(Identity(i) for i in expr.shape),
[2*i for i in range(len(expr.shape))] + [2*i+1 for i in range(len(expr.shape))]
)
return ZeroArray(*(x.shape + expr.shape)) # type: ignore
@array_derive.register(MatrixSymbol) # type: ignore
def _(expr: MatrixSymbol, x: Expr):
m, n = expr.shape
if expr == x:
return _permute_dims(
_array_tensor_product(Identity(m), Identity(n)),
[0, 2, 1, 3]
)
return ZeroArray(*(x.shape + expr.shape)) # type: ignore
@array_derive.register(Identity) # type: ignore
def _(expr: Identity, x: Expr):
return ZeroArray(*(x.shape + expr.shape)) # type: ignore
@array_derive.register(Transpose) # type: ignore
def _(expr: Transpose, x: Expr):
# D(A.T, A) ==> (m,n,i,j) ==> D(A_ji, A_mn) = d_mj d_ni
# D(B.T, A) ==> (m,n,i,j) ==> D(B_ji, A_mn)
fd = array_derive(expr.arg, x)
return _permute_dims(fd, [0, 1, 3, 2])
@array_derive.register(Inverse) # type: ignore
def _(expr: Inverse, x: Expr):
mat = expr.I
dexpr = array_derive(mat, x)
tp = _array_tensor_product(-expr, dexpr, expr)
mp = _array_contraction(tp, (1, 4), (5, 6))
pp = _permute_dims(mp, [1, 2, 0, 3])
return pp
@array_derive.register(ElementwiseApplyFunction) # type: ignore
def _(expr: ElementwiseApplyFunction, x: Expr):
assert get_rank(expr) == 2
assert get_rank(x) == 2
fdiff = expr._get_function_fdiff()
dexpr = array_derive(expr.expr, x)
tp = _array_tensor_product(
ElementwiseApplyFunction(fdiff, expr.expr),
dexpr
)
td = _array_diagonal(
tp, (0, 4), (1, 5)
)
return td
@array_derive.register(ArrayElementwiseApplyFunc) # type: ignore
def _(expr: ArrayElementwiseApplyFunc, x: Expr):
fdiff = expr._get_function_fdiff()
subexpr = expr.expr
dsubexpr = array_derive(subexpr, x)
tp = _array_tensor_product(
dsubexpr,
ArrayElementwiseApplyFunc(fdiff, subexpr)
)
b = get_rank(x)
c = get_rank(expr)
diag_indices = [(b + i, b + c + i) for i in range(c)]
return _array_diagonal(tp, *diag_indices)
@array_derive.register(MatrixExpr) # type: ignore
def _(expr: MatrixExpr, x: Expr):
cg = convert_matrix_to_array(expr)
return array_derive(cg, x)
@array_derive.register(HadamardProduct) # type: ignore
def _(expr: HadamardProduct, x: Expr):
raise NotImplementedError()
@array_derive.register(ArrayContraction) # type: ignore
def _(expr: ArrayContraction, x: Expr):
fd = array_derive(expr.expr, x)
rank_x = len(get_shape(x))
contraction_indices = expr.contraction_indices
new_contraction_indices = [tuple(j + rank_x for j in i) for i in contraction_indices]
return _array_contraction(fd, *new_contraction_indices)
@array_derive.register(ArrayDiagonal) # type: ignore
def _(expr: ArrayDiagonal, x: Expr):
dsubexpr = array_derive(expr.expr, x)
rank_x = len(get_shape(x))
diag_indices = [[j + rank_x for j in i] for i in expr.diagonal_indices]
return _array_diagonal(dsubexpr, *diag_indices)
@array_derive.register(ArrayAdd) # type: ignore
def _(expr: ArrayAdd, x: Expr):
return _array_add(*[array_derive(arg, x) for arg in expr.args])
@array_derive.register(PermuteDims) # type: ignore
def _(expr: PermuteDims, x: Expr):
de = array_derive(expr.expr, x)
perm = [0, 1] + [i + 2 for i in expr.permutation.array_form]
return _permute_dims(de, perm)
def matrix_derive(expr, x):
from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
ce = convert_matrix_to_array(expr)
dce = array_derive(ce, x)
return convert_array_to_matrix(dce).doit()
|
e9fc0d936951b517e1d711397ed6f37c5ceee30eeace1742518a71268250341f | from sympy import Lambda, S, Dummy
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.matrices.expressions.hadamard import HadamardProduct, HadamardPower
from sympy.matrices.expressions.special import (Identity, OneMatrix, ZeroMatrix)
from sympy.matrices.expressions.matexpr import MatrixElement
from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
from sympy.tensor.array.expressions.conv_array_to_matrix import _support_function_tp1_recognize, \
_array_diag2contr_diagmatrix, convert_array_to_matrix, _remove_trivial_dims, _array2matrix, \
_combine_removed, identify_removable_identity_matrices, _array_contraction_to_diagonal_multiple_identity
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.combinatorics import Permutation
from sympy.matrices.expressions.diagonal import DiagMatrix, DiagonalMatrix
from sympy.matrices import Trace, MatMul, Transpose
from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, \
ArrayElement, ArraySymbol, ArrayElementwiseApplyFunc, _array_tensor_product, _array_contraction, \
_array_diagonal, _permute_dims, PermuteDims, ArrayAdd, ArrayDiagonal
from sympy.testing.pytest import raises
i, j, k, l, m, n = symbols("i j k l m n")
I = Identity(k)
I1 = Identity(1)
M = MatrixSymbol("M", k, k)
N = MatrixSymbol("N", k, k)
P = MatrixSymbol("P", k, k)
Q = MatrixSymbol("Q", k, k)
A = MatrixSymbol("A", k, k)
B = MatrixSymbol("B", k, k)
C = MatrixSymbol("C", k, k)
D = MatrixSymbol("D", k, k)
X = MatrixSymbol("X", k, k)
Y = MatrixSymbol("Y", k, k)
a = MatrixSymbol("a", k, 1)
b = MatrixSymbol("b", k, 1)
c = MatrixSymbol("c", k, 1)
d = MatrixSymbol("d", k, 1)
x = MatrixSymbol("x", k, 1)
y = MatrixSymbol("y", k, 1)
def test_arrayexpr_convert_array_to_matrix():
cg = _array_contraction(_array_tensor_product(M), (0, 1))
assert convert_array_to_matrix(cg) == Trace(M)
cg = _array_contraction(_array_tensor_product(M, N), (0, 1), (2, 3))
assert convert_array_to_matrix(cg) == Trace(M) * Trace(N)
cg = _array_contraction(_array_tensor_product(M, N), (0, 3), (1, 2))
assert convert_array_to_matrix(cg) == Trace(M * N)
cg = _array_contraction(_array_tensor_product(M, N), (0, 2), (1, 3))
assert convert_array_to_matrix(cg) == Trace(M * N.T)
cg = convert_matrix_to_array(M * N * P)
assert convert_array_to_matrix(cg) == M * N * P
cg = convert_matrix_to_array(M * N.T * P)
assert convert_array_to_matrix(cg) == M * N.T * P
cg = _array_contraction(_array_tensor_product(M,N,P,Q), (1, 2), (5, 6))
assert convert_array_to_matrix(cg) == _array_tensor_product(M * N, P * Q)
cg = _array_contraction(_array_tensor_product(-2, M, N), (1, 2))
assert convert_array_to_matrix(cg) == -2 * M * N
a = MatrixSymbol("a", k, 1)
b = MatrixSymbol("b", k, 1)
c = MatrixSymbol("c", k, 1)
cg = PermuteDims(
_array_contraction(
_array_tensor_product(
a,
ArrayAdd(
_array_tensor_product(b, c),
_array_tensor_product(c, b),
)
), (2, 4)), [0, 1, 3, 2])
assert convert_array_to_matrix(cg) == a * (b.T * c + c.T * b)
za = ZeroArray(m, n)
assert convert_array_to_matrix(za) == ZeroMatrix(m, n)
cg = _array_tensor_product(3, M)
assert convert_array_to_matrix(cg) == 3 * M
# Partial conversion to matrix multiplication:
expr = _array_contraction(_array_tensor_product(M, N, P, Q), (0, 2), (1, 4, 6))
assert convert_array_to_matrix(expr) == _array_contraction(_array_tensor_product(M.T*N, P, Q), (0, 2, 4))
x = MatrixSymbol("x", k, 1)
cg = PermuteDims(
_array_contraction(_array_tensor_product(OneArray(1), x, OneArray(1), DiagMatrix(Identity(1))),
(0, 5)), Permutation(1, 2, 3))
assert convert_array_to_matrix(cg) == x
expr = ArrayAdd(M, PermuteDims(M, [1, 0]))
assert convert_array_to_matrix(expr) == M + Transpose(M)
def test_arrayexpr_convert_array_to_matrix2():
cg = _array_contraction(_array_tensor_product(M, N), (1, 3))
assert convert_array_to_matrix(cg) == M * N.T
cg = PermuteDims(_array_tensor_product(M, N), Permutation([0, 1, 3, 2]))
assert convert_array_to_matrix(cg) == _array_tensor_product(M, N.T)
cg = _array_tensor_product(M, PermuteDims(N, Permutation([1, 0])))
assert convert_array_to_matrix(cg) == _array_tensor_product(M, N.T)
cg = _array_contraction(
PermuteDims(
_array_tensor_product(M, N, P, Q), Permutation([0, 2, 3, 1, 4, 5, 7, 6])),
(1, 2), (3, 5)
)
assert convert_array_to_matrix(cg) == _array_tensor_product(M * P.T * Trace(N), Q.T)
cg = _array_contraction(
_array_tensor_product(M, N, P, PermuteDims(Q, Permutation([1, 0]))),
(1, 5), (2, 3)
)
assert convert_array_to_matrix(cg) == _array_tensor_product(M * P.T * Trace(N), Q.T)
cg = _array_tensor_product(M, PermuteDims(N, [1, 0]))
assert convert_array_to_matrix(cg) == _array_tensor_product(M, N.T)
cg = _array_tensor_product(PermuteDims(M, [1, 0]), PermuteDims(N, [1, 0]))
assert convert_array_to_matrix(cg) == _array_tensor_product(M.T, N.T)
cg = _array_tensor_product(PermuteDims(N, [1, 0]), PermuteDims(M, [1, 0]))
assert convert_array_to_matrix(cg) == _array_tensor_product(N.T, M.T)
cg = _array_contraction(M, (0,), (1,))
assert convert_array_to_matrix(cg) == OneMatrix(1, k)*M*OneMatrix(k, 1)
cg = _array_contraction(x, (0,), (1,))
assert convert_array_to_matrix(cg) == OneMatrix(1, k)*x
Xm = MatrixSymbol("Xm", m, n)
cg = _array_contraction(Xm, (0,), (1,))
assert convert_array_to_matrix(cg) == OneMatrix(1, m)*Xm*OneMatrix(n, 1)
def test_arrayexpr_convert_array_to_diagonalized_vector():
# Check matrix recognition over trivial dimensions:
cg = _array_tensor_product(a, b)
assert convert_array_to_matrix(cg) == a * b.T
cg = _array_tensor_product(I1, a, b)
assert convert_array_to_matrix(cg) == a * b.T
# Recognize trace inside a tensor product:
cg = _array_contraction(_array_tensor_product(A, B, C), (0, 3), (1, 2))
assert convert_array_to_matrix(cg) == Trace(A * B) * C
# Transform diagonal operator to contraction:
cg = _array_diagonal(_array_tensor_product(A, a), (1, 2))
assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(A, OneArray(1), DiagMatrix(a)), (1, 3))
assert convert_array_to_matrix(cg) == A * DiagMatrix(a)
cg = _array_diagonal(_array_tensor_product(a, b), (0, 2))
assert _array_diag2contr_diagmatrix(cg) == _permute_dims(
_array_contraction(_array_tensor_product(DiagMatrix(a), OneArray(1), b), (0, 3)), [1, 2, 0]
)
assert convert_array_to_matrix(cg) == b.T * DiagMatrix(a)
cg = _array_diagonal(_array_tensor_product(A, a), (0, 2))
assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(A, OneArray(1), DiagMatrix(a)), (0, 3))
assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a)
cg = _array_diagonal(_array_tensor_product(I, x, I1), (0, 2), (3, 5))
assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(I, OneArray(1), I1, DiagMatrix(x)), (0, 5))
assert convert_array_to_matrix(cg) == DiagMatrix(x)
cg = _array_diagonal(_array_tensor_product(I, x, A, B), (1, 2), (5, 6))
assert _array_diag2contr_diagmatrix(cg) == _array_diagonal(_array_contraction(_array_tensor_product(I, OneArray(1), A, B, DiagMatrix(x)), (1, 7)), (5, 6))
# TODO: this is returning a wrong result:
# convert_array_to_matrix(cg)
cg = _array_diagonal(_array_tensor_product(I1, a, b), (1, 3, 5))
assert convert_array_to_matrix(cg) == a*b.T
cg = _array_diagonal(_array_tensor_product(I1, a, b), (1, 3))
assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(OneArray(1), a, b, I1), (2, 6))
assert convert_array_to_matrix(cg) == a*b.T
cg = _array_diagonal(_array_tensor_product(x, I1), (1, 2))
assert isinstance(cg, ArrayDiagonal)
assert cg.diagonal_indices == ((1, 2),)
assert convert_array_to_matrix(cg) == x
cg = _array_diagonal(_array_tensor_product(x, I), (0, 2))
assert _array_diag2contr_diagmatrix(cg) == _array_contraction(_array_tensor_product(OneArray(1), I, DiagMatrix(x)), (1, 3))
assert convert_array_to_matrix(cg).doit() == DiagMatrix(x)
raises(ValueError, lambda: _array_diagonal(x, (1,)))
# Ignore identity matrices with contractions:
cg = _array_contraction(_array_tensor_product(I, A, I, I), (0, 2), (1, 3), (5, 7))
assert cg.split_multiple_contractions() == cg
assert convert_array_to_matrix(cg) == Trace(A) * I
cg = _array_contraction(_array_tensor_product(Trace(A) * I, I, I), (1, 5), (3, 4))
assert cg.split_multiple_contractions() == cg
assert convert_array_to_matrix(cg).doit() == Trace(A) * I
# Add DiagMatrix when required:
cg = _array_contraction(_array_tensor_product(A, a), (1, 2))
assert cg.split_multiple_contractions() == cg
assert convert_array_to_matrix(cg) == A * a
cg = _array_contraction(_array_tensor_product(A, a, B), (1, 2, 4))
assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1), B), (1, 2), (3, 5))
assert convert_array_to_matrix(cg) == A * DiagMatrix(a) * B
cg = _array_contraction(_array_tensor_product(A, a, B), (0, 2, 4))
assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1), B), (0, 2), (3, 5))
assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) * B
cg = _array_contraction(_array_tensor_product(A, a, b, a.T, B), (0, 2, 4, 7, 9))
assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1),
DiagMatrix(b), OneArray(1), DiagMatrix(a), OneArray(1), B),
(0, 2), (3, 5), (6, 9), (8, 12))
assert convert_array_to_matrix(cg) == A.T * DiagMatrix(a) * DiagMatrix(b) * DiagMatrix(a) * B.T
cg = _array_contraction(_array_tensor_product(I1, I1, I1), (1, 2, 4))
assert cg.split_multiple_contractions() == _array_contraction(_array_tensor_product(I1, I1, OneArray(1), I1), (1, 2), (3, 5))
assert convert_array_to_matrix(cg) == 1
cg = _array_contraction(_array_tensor_product(I, I, I, I, A), (1, 2, 8), (5, 6, 9))
assert convert_array_to_matrix(cg.split_multiple_contractions()).doit() == A
cg = _array_contraction(_array_tensor_product(A, a, C, a, B), (1, 2, 4), (5, 6, 8))
expected = _array_contraction(_array_tensor_product(A, DiagMatrix(a), OneArray(1), C, DiagMatrix(a), OneArray(1), B), (1, 3), (2, 5), (6, 7), (8, 10))
assert cg.split_multiple_contractions() == expected
assert convert_array_to_matrix(cg) == A * DiagMatrix(a) * C * DiagMatrix(a) * B
cg = _array_contraction(_array_tensor_product(a, I1, b, I1, (a.T*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9))
expected = _array_contraction(_array_tensor_product(a, I1, OneArray(1), b, I1, OneArray(1), (a.T*b).applyfunc(cos)),
(1, 3), (2, 10), (6, 8), (7, 11))
assert cg.split_multiple_contractions().dummy_eq(expected)
assert convert_array_to_matrix(cg).doit().dummy_eq(MatMul(a, (a.T * b).applyfunc(cos), b.T))
def test_arrayexpr_convert_array_contraction_tp_additions():
a = ArrayAdd(
_array_tensor_product(M, N),
_array_tensor_product(N, M)
)
tp = _array_tensor_product(P, a, Q)
expr = _array_contraction(tp, (3, 4))
expected = _array_tensor_product(
P,
ArrayAdd(
_array_contraction(_array_tensor_product(M, N), (1, 2)),
_array_contraction(_array_tensor_product(N, M), (1, 2)),
),
Q
)
assert expr == expected
assert convert_array_to_matrix(expr) == _array_tensor_product(P, M * N + N * M, Q)
expr = _array_contraction(tp, (1, 2), (3, 4), (5, 6))
result = _array_contraction(
_array_tensor_product(
P,
ArrayAdd(
_array_contraction(_array_tensor_product(M, N), (1, 2)),
_array_contraction(_array_tensor_product(N, M), (1, 2)),
),
Q
), (1, 2), (3, 4))
assert expr == result
assert convert_array_to_matrix(expr) == P * (M * N + N * M) * Q
def test_arrayexpr_convert_array_to_implicit_matmul():
# Trivial dimensions are suppressed, so the result can be expressed in matrix form:
cg = _array_tensor_product(a, b)
assert convert_array_to_matrix(cg) == a * b.T
cg = _array_tensor_product(a, b, I)
assert convert_array_to_matrix(cg) == _array_tensor_product(a*b.T, I)
cg = _array_tensor_product(I, a, b)
assert convert_array_to_matrix(cg) == _array_tensor_product(I, a*b.T)
cg = _array_tensor_product(a, I, b)
assert convert_array_to_matrix(cg) == _array_tensor_product(a, I, b)
cg = _array_contraction(_array_tensor_product(I, I), (1, 2))
assert convert_array_to_matrix(cg) == I
cg = PermuteDims(_array_tensor_product(I, Identity(1)), [0, 2, 1, 3])
assert convert_array_to_matrix(cg) == I
def test_arrayexpr_convert_array_to_matrix_remove_trivial_dims():
# Tensor Product:
assert _remove_trivial_dims(_array_tensor_product(a, b)) == (a * b.T, [1, 3])
assert _remove_trivial_dims(_array_tensor_product(a.T, b)) == (a * b.T, [0, 3])
assert _remove_trivial_dims(_array_tensor_product(a, b.T)) == (a * b.T, [1, 2])
assert _remove_trivial_dims(_array_tensor_product(a.T, b.T)) == (a * b.T, [0, 2])
assert _remove_trivial_dims(_array_tensor_product(I, a.T, b.T)) == (_array_tensor_product(I, a * b.T), [2, 4])
assert _remove_trivial_dims(_array_tensor_product(a.T, I, b.T)) == (_array_tensor_product(a.T, I, b.T), [])
assert _remove_trivial_dims(_array_tensor_product(a, I)) == (_array_tensor_product(a, I), [])
assert _remove_trivial_dims(_array_tensor_product(I, a)) == (_array_tensor_product(I, a), [])
assert _remove_trivial_dims(_array_tensor_product(a.T, b.T, c, d)) == (
_array_tensor_product(a * b.T, c * d.T), [0, 2, 5, 7])
assert _remove_trivial_dims(_array_tensor_product(a.T, I, b.T, c, d, I)) == (
_array_tensor_product(a.T, I, b*c.T, d, I), [4, 7])
# Addition:
cg = ArrayAdd(_array_tensor_product(a, b), _array_tensor_product(c, d))
assert _remove_trivial_dims(cg) == (a * b.T + c * d.T, [1, 3])
# Permute Dims:
cg = PermuteDims(_array_tensor_product(a, b), Permutation(3)(1, 2))
assert _remove_trivial_dims(cg) == (a * b.T, [2, 3])
cg = PermuteDims(_array_tensor_product(a, I, b), Permutation(5)(1, 2, 3, 4))
assert _remove_trivial_dims(cg) == (cg, [])
cg = PermuteDims(_array_tensor_product(I, b, a), Permutation(5)(1, 2, 4, 5, 3))
assert _remove_trivial_dims(cg) == (PermuteDims(_array_tensor_product(I, b * a.T), [0, 2, 3, 1]), [4, 5])
# Diagonal:
cg = _array_diagonal(_array_tensor_product(M, a), (1, 2))
assert _remove_trivial_dims(cg) == (cg, [])
# Contraction:
cg = _array_contraction(_array_tensor_product(M, a), (1, 2))
assert _remove_trivial_dims(cg) == (cg, [])
# A few more cases to test the removal and shift of nested removed axes
# with array contractions and array diagonals:
tp = _array_tensor_product(
OneMatrix(1, 1),
M,
x,
OneMatrix(1, 1),
Identity(1),
)
expr = _array_contraction(tp, (1, 8))
rexpr, removed = _remove_trivial_dims(expr)
assert removed == [0, 5, 6, 7]
expr = _array_contraction(tp, (1, 8), (3, 4))
rexpr, removed = _remove_trivial_dims(expr)
assert removed == [0, 3, 4, 5]
expr = _array_diagonal(tp, (1, 8))
rexpr, removed = _remove_trivial_dims(expr)
assert removed == [0, 5, 6, 7, 8]
expr = _array_diagonal(tp, (1, 8), (3, 4))
rexpr, removed = _remove_trivial_dims(expr)
assert removed == [0, 3, 4, 5, 6]
expr = _array_diagonal(_array_contraction(_array_tensor_product(A, x, I, I1), (1, 2, 5)), (1, 4))
rexpr, removed = _remove_trivial_dims(expr)
assert removed == [2, 3]
cg = _array_diagonal(_array_tensor_product(PermuteDims(_array_tensor_product(x, I1), Permutation(1, 2, 3)), (x.T*x).applyfunc(sqrt)), (2, 4), (3, 5))
rexpr, removed = _remove_trivial_dims(cg)
assert removed == [1, 2]
# Contractions with identity matrices need to be followed by a permutation
# in order
cg = _array_contraction(_array_tensor_product(A, B, C, M, I), (1, 8))
ret, removed = _remove_trivial_dims(cg)
assert ret == PermuteDims(_array_tensor_product(A, B, C, M), [0, 2, 3, 4, 5, 6, 7, 1])
assert removed == []
cg = _array_contraction(_array_tensor_product(A, B, C, M, I), (1, 8), (3, 4))
ret, removed = _remove_trivial_dims(cg)
assert ret == PermuteDims(_array_contraction(_array_tensor_product(A, B, C, M), (3, 4)), [0, 2, 3, 4, 5, 1])
assert removed == []
# Trivial matrices are sometimes inserted into MatMul expressions:
cg = _array_tensor_product(b*b.T, a.T*a)
ret, removed = _remove_trivial_dims(cg)
assert ret == b*a.T*a*b.T
assert removed == [2, 3]
Xs = ArraySymbol("X", (3, 2, k))
cg = _array_tensor_product(M, Xs, b.T*c, a*a.T, b*b.T, c.T*d)
ret, removed = _remove_trivial_dims(cg)
assert ret == _array_tensor_product(M, Xs, a*b.T*c*c.T*d*a.T, b*b.T)
assert removed == [5, 6, 11, 12]
cg = _array_diagonal(_array_tensor_product(I, I1, x), (1, 4), (3, 5))
assert _remove_trivial_dims(cg) == (PermuteDims(_array_diagonal(_array_tensor_product(I, x), (1, 2)), Permutation(1, 2)), [1])
expr = _array_diagonal(_array_tensor_product(x, I, y), (0, 2))
assert _remove_trivial_dims(expr) == (PermuteDims(_array_tensor_product(DiagMatrix(x), y), [1, 2, 3, 0]), [0])
expr = _array_diagonal(_array_tensor_product(x, I, y), (0, 2), (3, 4))
assert _remove_trivial_dims(expr) == (expr, [])
def test_arrayexpr_convert_array_to_matrix_diag2contraction_diagmatrix():
cg = _array_diagonal(_array_tensor_product(M, a), (1, 2))
res = _array_diag2contr_diagmatrix(cg)
assert res.shape == cg.shape
assert res == _array_contraction(_array_tensor_product(M, OneArray(1), DiagMatrix(a)), (1, 3))
raises(ValueError, lambda: _array_diagonal(_array_tensor_product(a, M), (1, 2)))
cg = _array_diagonal(_array_tensor_product(a.T, M), (1, 2))
res = _array_diag2contr_diagmatrix(cg)
assert res.shape == cg.shape
assert res == _array_contraction(_array_tensor_product(OneArray(1), M, DiagMatrix(a.T)), (1, 4))
cg = _array_diagonal(_array_tensor_product(a.T, M, N, b.T), (1, 2), (4, 7))
res = _array_diag2contr_diagmatrix(cg)
assert res.shape == cg.shape
assert res == _array_contraction(
_array_tensor_product(OneArray(1), M, N, OneArray(1), DiagMatrix(a.T), DiagMatrix(b.T)), (1, 7), (3, 9))
cg = _array_diagonal(_array_tensor_product(a, M, N, b.T), (0, 2), (4, 7))
res = _array_diag2contr_diagmatrix(cg)
assert res.shape == cg.shape
assert res == _array_contraction(
_array_tensor_product(OneArray(1), M, N, OneArray(1), DiagMatrix(a), DiagMatrix(b.T)), (1, 6), (3, 9))
cg = _array_diagonal(_array_tensor_product(a, M, N, b.T), (0, 4), (3, 7))
res = _array_diag2contr_diagmatrix(cg)
assert res.shape == cg.shape
assert res == _array_contraction(
_array_tensor_product(OneArray(1), M, N, OneArray(1), DiagMatrix(a), DiagMatrix(b.T)), (3, 6), (2, 9))
I1 = Identity(1)
x = MatrixSymbol("x", k, 1)
A = MatrixSymbol("A", k, k)
cg = _array_diagonal(_array_tensor_product(x, A.T, I1), (0, 2))
assert _array_diag2contr_diagmatrix(cg).shape == cg.shape
assert _array2matrix(cg).shape == cg.shape
def test_arrayexpr_convert_array_to_matrix_support_function():
assert _support_function_tp1_recognize([], [2 * k]) == 2 * k
assert _support_function_tp1_recognize([(1, 2)], [A, 2 * k, B, 3]) == 6 * k * A * B
assert _support_function_tp1_recognize([(0, 3), (1, 2)], [A, B]) == Trace(A * B)
assert _support_function_tp1_recognize([(1, 2)], [A, B]) == A * B
assert _support_function_tp1_recognize([(0, 2)], [A, B]) == A.T * B
assert _support_function_tp1_recognize([(1, 3)], [A, B]) == A * B.T
assert _support_function_tp1_recognize([(0, 3)], [A, B]) == A.T * B.T
assert _support_function_tp1_recognize([(1, 2), (5, 6)], [A, B, C, D]) == _array_tensor_product(A * B, C * D)
assert _support_function_tp1_recognize([(1, 4), (3, 6)], [A, B, C, D]) == PermuteDims(
_array_tensor_product(A * C, B * D), [0, 2, 1, 3])
assert _support_function_tp1_recognize([(0, 3), (1, 4)], [A, B, C]) == B * A * C
assert _support_function_tp1_recognize([(9, 10), (1, 2), (5, 6), (3, 4), (7, 8)],
[X, Y, A, B, C, D]) == X * Y * A * B * C * D
assert _support_function_tp1_recognize([(9, 10), (1, 2), (5, 6), (3, 4)],
[X, Y, A, B, C, D]) == _array_tensor_product(X * Y * A * B, C * D)
assert _support_function_tp1_recognize([(1, 7), (3, 8), (4, 11)], [X, Y, A, B, C, D]) == PermuteDims(
_array_tensor_product(X * B.T, Y * C, A.T * D.T), [0, 2, 4, 1, 3, 5]
)
assert _support_function_tp1_recognize([(0, 1), (3, 6), (5, 8)], [X, A, B, C, D]) == PermuteDims(
_array_tensor_product(Trace(X) * A * C, B * D), [0, 2, 1, 3])
assert _support_function_tp1_recognize([(1, 2), (3, 4), (5, 6), (7, 8)], [A, A, B, C, D]) == A ** 2 * B * C * D
assert _support_function_tp1_recognize([(1, 2), (3, 4), (5, 6), (7, 8)], [X, A, B, C, D]) == X * A * B * C * D
assert _support_function_tp1_recognize([(1, 6), (3, 8), (5, 10)], [X, Y, A, B, C, D]) == PermuteDims(
_array_tensor_product(X * B, Y * C, A * D), [0, 2, 4, 1, 3, 5]
)
assert _support_function_tp1_recognize([(1, 4), (3, 6)], [A, B, C, D]) == PermuteDims(
_array_tensor_product(A * C, B * D), [0, 2, 1, 3])
assert _support_function_tp1_recognize([(0, 4), (1, 7), (2, 5), (3, 8)], [X, A, B, C, D]) == C*X.T*B*A*D
assert _support_function_tp1_recognize([(0, 4), (1, 7), (2, 5), (3, 8)], [X, A, B, C, D]) == C*X.T*B*A*D
def test_convert_array_to_hadamard_products():
expr = HadamardProduct(M, N)
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert ret == expr
expr = HadamardProduct(M, N)*P
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert ret == expr
expr = Q*HadamardProduct(M, N)*P
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert ret == expr
expr = Q*HadamardProduct(M, N.T)*P
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert ret == expr
expr = HadamardProduct(M, N)*HadamardProduct(Q, P)
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert expr == ret
expr = P.T*HadamardProduct(M, N)*HadamardProduct(Q, P)
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert expr == ret
# ArrayDiagonal should be converted
cg = _array_diagonal(_array_tensor_product(M, N, Q), (1, 3), (0, 2, 4))
ret = convert_array_to_matrix(cg)
expected = PermuteDims(_array_diagonal(_array_tensor_product(HadamardProduct(M.T, N.T), Q), (1, 2)), [1, 0, 2])
assert expected == ret
# Special case that should return the same expression:
cg = _array_diagonal(_array_tensor_product(HadamardProduct(M, N), Q), (0, 2))
ret = convert_array_to_matrix(cg)
assert ret == cg
# Hadamard products with traces:
expr = Trace(HadamardProduct(M, N))
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert ret == Trace(HadamardProduct(M.T, N.T))
expr = Trace(A*HadamardProduct(M, N))
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert ret == Trace(HadamardProduct(M, N)*A)
expr = Trace(HadamardProduct(A, M)*N)
cg = convert_matrix_to_array(expr)
ret = convert_array_to_matrix(cg)
assert ret == Trace(HadamardProduct(M.T, N)*A)
# These should not be converted into Hadamard products:
cg = _array_diagonal(_array_tensor_product(M, N), (0, 1, 2, 3))
ret = convert_array_to_matrix(cg)
assert ret == cg
cg = _array_diagonal(_array_tensor_product(A), (0, 1))
ret = convert_array_to_matrix(cg)
assert ret == cg
cg = _array_diagonal(_array_tensor_product(M, N, P), (0, 2, 4), (1, 3, 5))
assert convert_array_to_matrix(cg) == HadamardProduct(M, N, P)
cg = _array_diagonal(_array_tensor_product(M, N, P), (0, 3, 4), (1, 2, 5))
assert convert_array_to_matrix(cg) == HadamardProduct(M, P, N.T)
cg = _array_diagonal(_array_tensor_product(I, I1, x), (1, 4), (3, 5))
assert convert_array_to_matrix(cg) == DiagMatrix(x)
def test_identify_removable_identity_matrices():
D = DiagonalMatrix(MatrixSymbol("D", k, k))
cg = _array_contraction(_array_tensor_product(A, B, I), (1, 2, 4, 5))
expected = _array_contraction(_array_tensor_product(A, B), (1, 2))
assert identify_removable_identity_matrices(cg) == expected
cg = _array_contraction(_array_tensor_product(A, B, C, I), (1, 3, 5, 6, 7))
expected = _array_contraction(_array_tensor_product(A, B, C), (1, 3, 5))
assert identify_removable_identity_matrices(cg) == expected
# Tests with diagonal matrices:
cg = _array_contraction(_array_tensor_product(A, B, D), (1, 2, 4, 5))
ret = identify_removable_identity_matrices(cg)
expected = _array_contraction(_array_tensor_product(A, B, D), (1, 4), (2, 5))
assert ret == expected
cg = _array_contraction(_array_tensor_product(A, B, D, M, N), (1, 2, 4, 5, 6, 8))
ret = identify_removable_identity_matrices(cg)
assert ret == cg
def test_combine_removed():
assert _combine_removed(6, [0, 1, 2], [0, 1, 2]) == [0, 1, 2, 3, 4, 5]
assert _combine_removed(8, [2, 5], [1, 3, 4]) == [1, 2, 4, 5, 6]
assert _combine_removed(8, [7], []) == [7]
def test_array_contraction_to_diagonal_multiple_identities():
expr = _array_contraction(_array_tensor_product(A, B, I, C), (1, 2, 4), (5, 6))
assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, [])
assert convert_array_to_matrix(expr) == _array_contraction(_array_tensor_product(A, B, C), (1, 2, 4))
expr = _array_contraction(_array_tensor_product(A, I, I), (1, 2, 4))
assert _array_contraction_to_diagonal_multiple_identity(expr) == (A, [2])
assert convert_array_to_matrix(expr) == A
expr = _array_contraction(_array_tensor_product(A, I, I, B), (1, 2, 4), (3, 6))
assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, [])
expr = _array_contraction(_array_tensor_product(A, I, I, B), (1, 2, 3, 4, 6))
assert _array_contraction_to_diagonal_multiple_identity(expr) == (expr, [])
def test_convert_array_element_to_matrix():
expr = ArrayElement(M, (i, j))
assert convert_array_to_matrix(expr) == MatrixElement(M, i, j)
expr = ArrayElement(_array_contraction(_array_tensor_product(M, N), (1, 3)), (i, j))
assert convert_array_to_matrix(expr) == MatrixElement(M*N.T, i, j)
expr = ArrayElement(_array_tensor_product(M, N), (i, j, m, n))
assert convert_array_to_matrix(expr) == expr
def test_convert_array_elementwise_function_to_matrix():
d = Dummy("d")
expr = ArrayElementwiseApplyFunc(Lambda(d, sin(d)), x.T*y)
assert convert_array_to_matrix(expr) == sin(x.T*y)
expr = ArrayElementwiseApplyFunc(Lambda(d, d**2), x.T*y)
assert convert_array_to_matrix(expr) == (x.T*y)**2
expr = ArrayElementwiseApplyFunc(Lambda(d, sin(d)), x)
assert convert_array_to_matrix(expr).dummy_eq(x.applyfunc(sin))
expr = ArrayElementwiseApplyFunc(Lambda(d, 1 / (2 * sqrt(d))), x)
assert convert_array_to_matrix(expr) == S.Half * HadamardPower(x, -S.Half)
|
33af8609c9398c0df17778449f47301c96543c863fde9fd7d324f2fcd73bfb43 | from sympy.concrete.summations import Sum
from sympy.core.symbol import symbols
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.special import Identity
from sympy.tensor.indexed import IndexedBase
from sympy.combinatorics import Permutation
from sympy.tensor.array.expressions.array_expressions import ArrayContraction, ArrayTensorProduct, \
ArrayDiagonal, ArrayAdd, PermuteDims, ArrayElement, _array_tensor_product, _array_contraction, _array_diagonal, \
_array_add, _permute_dims
from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
from sympy.tensor.array.expressions.conv_indexed_to_array import convert_indexed_to_array, _convert_indexed_to_array
from sympy.testing.pytest import raises
A, B = symbols("A B", cls=IndexedBase)
i, j, k, l, m, n = symbols("i j k l m n")
I = Identity(k)
M = MatrixSymbol("M", k, k)
N = MatrixSymbol("N", k, k)
P = MatrixSymbol("P", k, k)
Q = MatrixSymbol("Q", k, k)
a = MatrixSymbol("a", k, 1)
b = MatrixSymbol("b", k, 1)
c = MatrixSymbol("c", k, 1)
d = MatrixSymbol("d", k, 1)
def test_arrayexpr_convert_index_to_array_support_function():
expr = M[i, j]
assert _convert_indexed_to_array(expr) == (M, (i, j))
expr = M[i, j]*N[k, l]
assert _convert_indexed_to_array(expr) == (ArrayTensorProduct(M, N), (i, j, k, l))
expr = M[i, j]*N[j, k]
assert _convert_indexed_to_array(expr) == (ArrayDiagonal(ArrayTensorProduct(M, N), (1, 2)), (i, k, j))
expr = Sum(M[i, j]*N[j, k], (j, 0, k-1))
assert _convert_indexed_to_array(expr) == (ArrayContraction(ArrayTensorProduct(M, N), (1, 2)), (i, k))
expr = M[i, j] + N[i, j]
assert _convert_indexed_to_array(expr) == (ArrayAdd(M, N), (i, j))
expr = M[i, j] + N[j, i]
assert _convert_indexed_to_array(expr) == (ArrayAdd(M, PermuteDims(N, Permutation([1, 0]))), (i, j))
expr = M[i, j] + M[j, i]
assert _convert_indexed_to_array(expr) == (ArrayAdd(M, PermuteDims(M, Permutation([1, 0]))), (i, j))
expr = (M*N*P)[i, j]
assert _convert_indexed_to_array(expr) == (_array_contraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4)), (i, j))
expr = expr.function # Disregard summation in previous expression
ret1, ret2 = _convert_indexed_to_array(expr)
assert ret1 == ArrayDiagonal(ArrayTensorProduct(M, N, P), (1, 2), (3, 4))
assert str(ret2) == "(i, j, _i_1, _i_2)"
expr = KroneckerDelta(i, j)*M[i, k]
assert _convert_indexed_to_array(expr) == (M, ({i, j}, k))
expr = KroneckerDelta(i, j)*KroneckerDelta(j, k)*M[i, l]
assert _convert_indexed_to_array(expr) == (M, ({i, j, k}, l))
expr = KroneckerDelta(j, k)*(M[i, j]*N[k, l] + N[i, j]*M[k, l])
assert _convert_indexed_to_array(expr) == (_array_diagonal(_array_add(
ArrayTensorProduct(M, N),
_permute_dims(ArrayTensorProduct(M, N), Permutation(0, 2)(1, 3))
), (1, 2)), (i, l, frozenset({j, k})))
expr = KroneckerDelta(j, m)*KroneckerDelta(m, k)*(M[i, j]*N[k, l] + N[i, j]*M[k, l])
assert _convert_indexed_to_array(expr) == (_array_diagonal(_array_add(
ArrayTensorProduct(M, N),
_permute_dims(ArrayTensorProduct(M, N), Permutation(0, 2)(1, 3))
), (1, 2)), (i, l, frozenset({j, m, k})))
expr = KroneckerDelta(i, j)*KroneckerDelta(j, k)*KroneckerDelta(k,m)*M[i, 0]*KroneckerDelta(m, n)
assert _convert_indexed_to_array(expr) == (M, ({i, j, k, m, n}, 0))
expr = M[i, i]
assert _convert_indexed_to_array(expr) == (ArrayDiagonal(M, (0, 1)), (i,))
def test_arrayexpr_convert_indexed_to_array_expression():
s = Sum(A[i]*B[i], (i, 0, 3))
cg = convert_indexed_to_array(s)
assert cg == ArrayContraction(ArrayTensorProduct(A, B), (0, 1))
expr = M*N
result = ArrayContraction(ArrayTensorProduct(M, N), (1, 2))
elem = expr[i, j]
assert convert_indexed_to_array(elem) == result
expr = M*N*M
elem = expr[i, j]
result = _array_contraction(_array_tensor_product(M, M, N), (1, 4), (2, 5))
cg = convert_indexed_to_array(elem)
assert cg == result
cg = convert_indexed_to_array((M * N * P)[i, j])
assert cg == _array_contraction(ArrayTensorProduct(M, N, P), (1, 2), (3, 4))
cg = convert_indexed_to_array((M * N.T * P)[i, j])
assert cg == _array_contraction(ArrayTensorProduct(M, N, P), (1, 3), (2, 4))
expr = -2*M*N
elem = expr[i, j]
cg = convert_indexed_to_array(elem)
assert cg == ArrayContraction(ArrayTensorProduct(-2, M, N), (1, 2))
def test_arrayexpr_convert_indexed_to_array_and_back_to_matrix():
expr = a.T*b
elem = expr[0, 0]
cg = convert_indexed_to_array(elem)
assert cg == ArrayElement(ArrayContraction(ArrayTensorProduct(a, b), (0, 2)), [0, 0])
expr = M[i,j] + N[i,j]
p1, p2 = _convert_indexed_to_array(expr)
assert convert_array_to_matrix(p1) == M + N
expr = M[i,j] + N[j,i]
p1, p2 = _convert_indexed_to_array(expr)
assert convert_array_to_matrix(p1) == M + N.T
expr = M[i,j]*N[k,l] + N[i,j]*M[k,l]
p1, p2 = _convert_indexed_to_array(expr)
assert convert_array_to_matrix(p1) == ArrayAdd(
ArrayTensorProduct(M, N),
ArrayTensorProduct(N, M))
expr = (M*N*P)[i, j]
p1, p2 = _convert_indexed_to_array(expr)
assert convert_array_to_matrix(p1) == M * N * P
expr = Sum(M[i,j]*(N*P)[j,m], (j, 0, k-1))
p1, p2 = _convert_indexed_to_array(expr)
assert convert_array_to_matrix(p1) == M * N * P
expr = Sum((P[j, m] + P[m, j])*(M[i,j]*N[m,n] + N[i,j]*M[m,n]), (j, 0, k-1), (m, 0, k-1))
p1, p2 = _convert_indexed_to_array(expr)
assert convert_array_to_matrix(p1) == M * P * N + M * P.T * N + N * P * M + N * P.T * M
def test_arrayexpr_convert_indexed_to_array_out_of_bounds():
expr = Sum(M[i, i], (i, 0, 4))
raises(ValueError, lambda: convert_indexed_to_array(expr))
expr = Sum(M[i, i], (i, 0, k))
raises(ValueError, lambda: convert_indexed_to_array(expr))
expr = Sum(M[i, i], (i, 1, k-1))
raises(ValueError, lambda: convert_indexed_to_array(expr))
expr = Sum(M[i, j]*N[j,m], (j, 0, 4))
raises(ValueError, lambda: convert_indexed_to_array(expr))
expr = Sum(M[i, j]*N[j,m], (j, 0, k))
raises(ValueError, lambda: convert_indexed_to_array(expr))
expr = Sum(M[i, j]*N[j,m], (j, 1, k-1))
raises(ValueError, lambda: convert_indexed_to_array(expr))
|
af0190ac2926dff9dbdf8b80d92b5c55f08e19e60e8c6943442343d1aad5eec1 | from sympy import Lambda
from sympy.core.symbol import symbols, Dummy
from sympy.matrices.expressions.hadamard import (HadamardPower, HadamardProduct)
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.matpow import MatPow
from sympy.matrices.expressions.special import Identity
from sympy.matrices.expressions.trace import Trace
from sympy.matrices.expressions.transpose import Transpose
from sympy.tensor.array.expressions.array_expressions import ArrayTensorProduct, ArrayContraction, \
PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, _array_contraction, _array_tensor_product
from sympy.tensor.array.expressions.conv_array_to_matrix import convert_array_to_matrix
from sympy.tensor.array.expressions.conv_matrix_to_array import convert_matrix_to_array
i, j, k, l, m, n = symbols("i j k l m n")
I = Identity(k)
M = MatrixSymbol("M", k, k)
N = MatrixSymbol("N", k, k)
P = MatrixSymbol("P", k, k)
Q = MatrixSymbol("Q", k, k)
A = MatrixSymbol("A", k, k)
B = MatrixSymbol("B", k, k)
C = MatrixSymbol("C", k, k)
D = MatrixSymbol("D", k, k)
X = MatrixSymbol("X", k, k)
Y = MatrixSymbol("Y", k, k)
a = MatrixSymbol("a", k, 1)
b = MatrixSymbol("b", k, 1)
c = MatrixSymbol("c", k, 1)
d = MatrixSymbol("d", k, 1)
def test_arrayexpr_convert_matrix_to_array():
expr = M*N
result = ArrayContraction(ArrayTensorProduct(M, N), (1, 2))
assert convert_matrix_to_array(expr) == result
expr = M*N*M
result = _array_contraction(ArrayTensorProduct(M, N, M), (1, 2), (3, 4))
assert convert_matrix_to_array(expr) == result
expr = Transpose(M)
assert convert_matrix_to_array(expr) == PermuteDims(M, [1, 0])
expr = M*Transpose(N)
assert convert_matrix_to_array(expr) == _array_contraction(_array_tensor_product(M, PermuteDims(N, [1, 0])), (1, 2))
expr = 3*M*N
res = convert_matrix_to_array(expr)
rexpr = convert_array_to_matrix(res)
assert expr == rexpr
expr = 3*M + N*M.T*M + 4*k*N
res = convert_matrix_to_array(expr)
rexpr = convert_array_to_matrix(res)
assert expr == rexpr
expr = Inverse(M)*N
rexpr = convert_array_to_matrix(convert_matrix_to_array(expr))
assert expr == rexpr
expr = M**2
rexpr = convert_array_to_matrix(convert_matrix_to_array(expr))
assert expr == rexpr
expr = M*(2*N + 3*M)
res = convert_matrix_to_array(expr)
rexpr = convert_array_to_matrix(res)
assert expr == rexpr
expr = Trace(M)
result = ArrayContraction(M, (0, 1))
assert convert_matrix_to_array(expr) == result
expr = 3*Trace(M)
result = ArrayContraction(ArrayTensorProduct(3, M), (0, 1))
assert convert_matrix_to_array(expr) == result
expr = 3*Trace(Trace(M) * M)
result = ArrayContraction(ArrayTensorProduct(3, M, M), (0, 1), (2, 3))
assert convert_matrix_to_array(expr) == result
expr = 3*Trace(M)**2
result = ArrayContraction(ArrayTensorProduct(3, M, M), (0, 1), (2, 3))
assert convert_matrix_to_array(expr) == result
expr = HadamardProduct(M, N)
result = ArrayDiagonal(ArrayTensorProduct(M, N), (0, 2), (1, 3))
assert convert_matrix_to_array(expr) == result
expr = HadamardProduct(M*N, N*M)
result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, N, M), (1, 2), (5, 6)), (0, 2), (1, 3))
assert convert_matrix_to_array(expr) == result
expr = HadamardPower(M, 2)
result = ArrayDiagonal(ArrayTensorProduct(M, M), (0, 2), (1, 3))
assert convert_matrix_to_array(expr) == result
expr = HadamardPower(M*N, 2)
result = ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, M, N), (1, 2), (5, 6)), (0, 2), (1, 3))
assert convert_matrix_to_array(expr) == result
expr = HadamardPower(M, n)
d0 = Dummy("d0")
result = ArrayElementwiseApplyFunc(Lambda(d0, d0**n), M)
assert convert_matrix_to_array(expr).dummy_eq(result)
expr = M**2
assert isinstance(expr, MatPow)
assert convert_matrix_to_array(expr) == ArrayContraction(ArrayTensorProduct(M, M), (1, 2))
expr = a.T*b
cg = convert_matrix_to_array(expr)
assert cg == ArrayContraction(ArrayTensorProduct(a, b), (0, 2))
|
f77f4b2ab881bb19b5039247858de5ad57a02f31d7a4d4189ac4ce05be1bbd78 | import random
from sympy import tensordiagonal, eye, KroneckerDelta
from sympy.core.symbol import symbols
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.matrices.expressions.diagonal import DiagMatrix
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.special import ZeroMatrix
from sympy.tensor.array.arrayop import (permutedims, tensorcontraction, tensorproduct)
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
from sympy.combinatorics import Permutation
from sympy.tensor.array.expressions.array_expressions import ZeroArray, OneArray, ArraySymbol, ArrayElement, \
PermuteDims, ArrayContraction, ArrayTensorProduct, ArrayDiagonal, \
ArrayAdd, nest_permutation, ArrayElementwiseApplyFunc, _EditArrayContraction, _ArgE, _array_tensor_product, \
_array_contraction, _array_diagonal, _array_add, _permute_dims
from sympy.testing.pytest import raises
i, j, k, l, m, n = symbols("i j k l m n")
M = ArraySymbol("M", (k, k))
N = ArraySymbol("N", (k, k))
P = ArraySymbol("P", (k, k))
Q = ArraySymbol("Q", (k, k))
A = ArraySymbol("A", (k, k))
B = ArraySymbol("B", (k, k))
C = ArraySymbol("C", (k, k))
D = ArraySymbol("D", (k, k))
X = ArraySymbol("X", (k, k))
Y = ArraySymbol("Y", (k, k))
a = ArraySymbol("a", (k, 1))
b = ArraySymbol("b", (k, 1))
c = ArraySymbol("c", (k, 1))
d = ArraySymbol("d", (k, 1))
def test_array_symbol_and_element():
A = ArraySymbol("A", (2,))
A0 = ArrayElement(A, (0,))
A1 = ArrayElement(A, (1,))
assert A.as_explicit() == ImmutableDenseNDimArray([A0, A1])
A2 = tensorproduct(A, A)
assert A2.shape == (2, 2)
# TODO: not yet supported:
# assert A2.as_explicit() == Array([[A[0]*A[0], A[1]*A[0]], [A[0]*A[1], A[1]*A[1]]])
A3 = tensorcontraction(A2, (0, 1))
assert A3.shape == ()
# TODO: not yet supported:
# assert A3.as_explicit() == Array([])
A = ArraySymbol("A", (2, 3, 4))
Ae = A.as_explicit()
assert Ae == ImmutableDenseNDimArray(
[[[ArrayElement(A, (i, j, k)) for k in range(4)] for j in range(3)] for i in range(2)])
p = _permute_dims(A, Permutation(0, 2, 1))
assert isinstance(p, PermuteDims)
def test_zero_array():
assert ZeroArray() == 0
assert ZeroArray().is_Integer
za = ZeroArray(3, 2, 4)
assert za.shape == (3, 2, 4)
za_e = za.as_explicit()
assert za_e.shape == (3, 2, 4)
m, n, k = symbols("m n k")
za = ZeroArray(m, n, k, 2)
assert za.shape == (m, n, k, 2)
raises(ValueError, lambda: za.as_explicit())
def test_one_array():
assert OneArray() == 1
assert OneArray().is_Integer
oa = OneArray(3, 2, 4)
assert oa.shape == (3, 2, 4)
oa_e = oa.as_explicit()
assert oa_e.shape == (3, 2, 4)
m, n, k = symbols("m n k")
oa = OneArray(m, n, k, 2)
assert oa.shape == (m, n, k, 2)
raises(ValueError, lambda: oa.as_explicit())
def test_arrayexpr_contraction_construction():
cg = _array_contraction(A)
assert cg == A
cg = _array_contraction(_array_tensor_product(A, B), (1, 0))
assert cg == _array_contraction(_array_tensor_product(A, B), (0, 1))
cg = _array_contraction(_array_tensor_product(M, N), (0, 1))
indtup = cg._get_contraction_tuples()
assert indtup == [[(0, 0), (0, 1)]]
assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(0, 1)]
cg = _array_contraction(_array_tensor_product(M, N), (1, 2))
indtup = cg._get_contraction_tuples()
assert indtup == [[(0, 1), (1, 0)]]
assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(1, 2)]
cg = _array_contraction(_array_tensor_product(M, M, N), (1, 4), (2, 5))
indtup = cg._get_contraction_tuples()
assert indtup == [[(0, 0), (1, 1)], [(0, 1), (2, 0)]]
assert cg._contraction_tuples_to_contraction_indices(cg.expr, indtup) == [(0, 3), (1, 4)]
# Test removal of trivial contraction:
assert _array_contraction(a, (1,)) == a
assert _array_contraction(
_array_tensor_product(a, b), (0, 2), (1,), (3,)) == _array_contraction(
_array_tensor_product(a, b), (0, 2))
def test_arrayexpr_array_flatten():
# Flatten nested ArrayTensorProduct objects:
expr1 = _array_tensor_product(M, N)
expr2 = _array_tensor_product(P, Q)
expr = _array_tensor_product(expr1, expr2)
assert expr == _array_tensor_product(M, N, P, Q)
assert expr.args == (M, N, P, Q)
# Flatten mixed ArrayTensorProduct and ArrayContraction objects:
cg1 = _array_contraction(expr1, (1, 2))
cg2 = _array_contraction(expr2, (0, 3))
expr = _array_tensor_product(cg1, cg2)
assert expr == _array_contraction(_array_tensor_product(M, N, P, Q), (1, 2), (4, 7))
expr = _array_tensor_product(M, cg1)
assert expr == _array_contraction(_array_tensor_product(M, M, N), (3, 4))
# Flatten nested ArrayContraction objects:
cgnested = _array_contraction(cg1, (0, 1))
assert cgnested == _array_contraction(_array_tensor_product(M, N), (0, 3), (1, 2))
cgnested = _array_contraction(_array_tensor_product(cg1, cg2), (0, 3))
assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 6), (1, 2), (4, 7))
cg3 = _array_contraction(_array_tensor_product(M, N, P, Q), (1, 3), (2, 4))
cgnested = _array_contraction(cg3, (0, 1))
assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 5), (1, 3), (2, 4))
cgnested = _array_contraction(cg3, (0, 3), (1, 2))
assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 7), (1, 3), (2, 4), (5, 6))
cg4 = _array_contraction(_array_tensor_product(M, N, P, Q), (1, 5), (3, 7))
cgnested = _array_contraction(cg4, (0, 1))
assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 2), (1, 5), (3, 7))
cgnested = _array_contraction(cg4, (0, 1), (2, 3))
assert cgnested == _array_contraction(_array_tensor_product(M, N, P, Q), (0, 2), (1, 5), (3, 7), (4, 6))
cg = _array_diagonal(cg4)
assert cg == cg4
assert isinstance(cg, type(cg4))
# Flatten nested ArrayDiagonal objects:
cg1 = _array_diagonal(expr1, (1, 2))
cg2 = _array_diagonal(expr2, (0, 3))
cg3 = _array_diagonal(_array_tensor_product(M, N, P, Q), (1, 3), (2, 4))
cg4 = _array_diagonal(_array_tensor_product(M, N, P, Q), (1, 5), (3, 7))
cgnested = _array_diagonal(cg1, (0, 1))
assert cgnested == _array_diagonal(_array_tensor_product(M, N), (1, 2), (0, 3))
cgnested = _array_diagonal(cg3, (1, 2))
assert cgnested == _array_diagonal(_array_tensor_product(M, N, P, Q), (1, 3), (2, 4), (5, 6))
cgnested = _array_diagonal(cg4, (1, 2))
assert cgnested == _array_diagonal(_array_tensor_product(M, N, P, Q), (1, 5), (3, 7), (2, 4))
cg = _array_add(M, N)
cg2 = _array_add(cg, P)
assert isinstance(cg2, ArrayAdd)
assert cg2.args == (M, N, P)
assert cg2.shape == (k, k)
expr = _array_tensor_product(_array_diagonal(X, (0, 1)), _array_diagonal(A, (0, 1)))
assert expr == _array_diagonal(_array_tensor_product(X, A), (0, 1), (2, 3))
expr1 = _array_diagonal(_array_tensor_product(X, A), (1, 2))
expr2 = _array_tensor_product(expr1, a)
assert expr2 == _permute_dims(_array_diagonal(_array_tensor_product(X, A, a), (1, 2)), [0, 1, 4, 2, 3])
expr1 = _array_contraction(_array_tensor_product(X, A), (1, 2))
expr2 = _array_tensor_product(expr1, a)
assert isinstance(expr2, ArrayContraction)
assert isinstance(expr2.expr, ArrayTensorProduct)
cg = _array_tensor_product(_array_diagonal(_array_tensor_product(A, X, Y), (0, 3), (1, 5)), a, b)
assert cg == _permute_dims(_array_diagonal(_array_tensor_product(A, X, Y, a, b), (0, 3), (1, 5)), [0, 1, 6, 7, 2, 3, 4, 5])
def test_arrayexpr_array_diagonal():
cg = _array_diagonal(M, (1, 0))
assert cg == _array_diagonal(M, (0, 1))
cg = _array_diagonal(_array_tensor_product(M, N, P), (4, 1), (2, 0))
assert cg == _array_diagonal(_array_tensor_product(M, N, P), (1, 4), (0, 2))
cg = _array_diagonal(_array_tensor_product(M, N), (1, 2), (3,), allow_trivial_diags=True)
assert cg == _permute_dims(_array_diagonal(_array_tensor_product(M, N), (1, 2)), [0, 2, 1])
Ax = ArraySymbol("Ax", shape=(1, 2, 3, 4, 3, 5, 6, 2, 7))
cg = _array_diagonal(Ax, (1, 7), (3,), (2, 4), (6,), allow_trivial_diags=True)
assert cg == _permute_dims(_array_diagonal(Ax, (1, 7), (2, 4)), [0, 2, 4, 5, 1, 6, 3])
cg = _array_diagonal(M, (0,), allow_trivial_diags=True)
assert cg == _permute_dims(M, [1, 0])
raises(ValueError, lambda: _array_diagonal(M, (0, 0)))
def test_arrayexpr_array_shape():
expr = _array_tensor_product(M, N, P, Q)
assert expr.shape == (k, k, k, k, k, k, k, k)
Z = MatrixSymbol("Z", m, n)
expr = _array_tensor_product(M, Z)
assert expr.shape == (k, k, m, n)
expr2 = _array_contraction(expr, (0, 1))
assert expr2.shape == (m, n)
expr2 = _array_diagonal(expr, (0, 1))
assert expr2.shape == (m, n, k)
exprp = _permute_dims(expr, [2, 1, 3, 0])
assert exprp.shape == (m, k, n, k)
expr3 = _array_tensor_product(N, Z)
expr2 = _array_add(expr, expr3)
assert expr2.shape == (k, k, m, n)
# Contraction along axes with discordant dimensions:
raises(ValueError, lambda: _array_contraction(expr, (1, 2)))
# Also diagonal needs the same dimensions:
raises(ValueError, lambda: _array_diagonal(expr, (1, 2)))
# Diagonal requires at least to axes to compute the diagonal:
raises(ValueError, lambda: _array_diagonal(expr, (1,)))
def test_arrayexpr_permutedims_sink():
cg = _permute_dims(_array_tensor_product(M, N), [0, 1, 3, 2], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == _array_tensor_product(M, _permute_dims(N, [1, 0]))
cg = _permute_dims(_array_tensor_product(M, N), [1, 0, 3, 2], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == _array_tensor_product(_permute_dims(M, [1, 0]), _permute_dims(N, [1, 0]))
cg = _permute_dims(_array_tensor_product(M, N), [3, 2, 1, 0], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == _array_tensor_product(_permute_dims(N, [1, 0]), _permute_dims(M, [1, 0]))
cg = _permute_dims(_array_contraction(_array_tensor_product(M, N), (1, 2)), [1, 0], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == _array_contraction(_permute_dims(_array_tensor_product(M, N), [[0, 3]]), (1, 2))
cg = _permute_dims(_array_tensor_product(M, N), [1, 0, 3, 2], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == _array_tensor_product(_permute_dims(M, [1, 0]), _permute_dims(N, [1, 0]))
cg = _permute_dims(_array_contraction(_array_tensor_product(M, N, P), (1, 2), (3, 4)), [1, 0], nest_permutation=False)
sunk = nest_permutation(cg)
assert sunk == _array_contraction(_permute_dims(_array_tensor_product(M, N, P), [[0, 5]]), (1, 2), (3, 4))
def test_arrayexpr_push_indices_up_and_down():
indices = list(range(12))
contr_diag_indices = [(0, 6), (2, 8)]
assert ArrayContraction._push_indices_down(contr_diag_indices, indices) == (1, 3, 4, 5, 7, 9, 10, 11, 12, 13, 14, 15)
assert ArrayContraction._push_indices_up(contr_diag_indices, indices) == (None, 0, None, 1, 2, 3, None, 4, None, 5, 6, 7)
assert ArrayDiagonal._push_indices_down(contr_diag_indices, indices, 10) == (1, 3, 4, 5, 7, 9, (0, 6), (2, 8), None, None, None, None)
assert ArrayDiagonal._push_indices_up(contr_diag_indices, indices, 10) == (6, 0, 7, 1, 2, 3, 6, 4, 7, 5, None, None)
contr_diag_indices = [(1, 2), (7, 8)]
assert ArrayContraction._push_indices_down(contr_diag_indices, indices) == (0, 3, 4, 5, 6, 9, 10, 11, 12, 13, 14, 15)
assert ArrayContraction._push_indices_up(contr_diag_indices, indices) == (0, None, None, 1, 2, 3, 4, None, None, 5, 6, 7)
assert ArrayDiagonal._push_indices_down(contr_diag_indices, indices, 10) == (0, 3, 4, 5, 6, 9, (1, 2), (7, 8), None, None, None, None)
assert ArrayDiagonal._push_indices_up(contr_diag_indices, indices, 10) == (0, 6, 6, 1, 2, 3, 4, 7, 7, 5, None, None)
def test_arrayexpr_split_multiple_contractions():
a = MatrixSymbol("a", k, 1)
b = MatrixSymbol("b", k, 1)
A = MatrixSymbol("A", k, k)
B = MatrixSymbol("B", k, k)
C = MatrixSymbol("C", k, k)
X = MatrixSymbol("X", k, k)
cg = _array_contraction(_array_tensor_product(A.T, a, b, b.T, (A*X*b).applyfunc(cos)), (1, 2, 8), (5, 6, 9))
expected = _array_contraction(_array_tensor_product(A.T, DiagMatrix(a), OneArray(1), b, b.T, (A*X*b).applyfunc(cos)), (1, 3), (2, 9), (6, 7, 10))
assert cg.split_multiple_contractions().dummy_eq(expected)
# Check no overlap of lines:
cg = _array_contraction(_array_tensor_product(A, a, C, a, B), (1, 2, 4), (5, 6, 8), (3, 7))
assert cg.split_multiple_contractions() == cg
cg = _array_contraction(_array_tensor_product(a, b, A), (0, 2, 4), (1, 3))
assert cg.split_multiple_contractions() == cg
def test_arrayexpr_nested_permutations():
cg = _permute_dims(_permute_dims(M, (1, 0)), (1, 0))
assert cg == M
times = 3
plist1 = [list(range(6)) for i in range(times)]
plist2 = [list(range(6)) for i in range(times)]
for i in range(times):
random.shuffle(plist1[i])
random.shuffle(plist2[i])
plist1.append([2, 5, 4, 1, 0, 3])
plist2.append([3, 5, 0, 4, 1, 2])
plist1.append([2, 5, 4, 0, 3, 1])
plist2.append([3, 0, 5, 1, 2, 4])
plist1.append([5, 4, 2, 0, 3, 1])
plist2.append([4, 5, 0, 2, 3, 1])
Me = M.subs(k, 3).as_explicit()
Ne = N.subs(k, 3).as_explicit()
Pe = P.subs(k, 3).as_explicit()
cge = tensorproduct(Me, Ne, Pe)
for permutation_array1, permutation_array2 in zip(plist1, plist2):
p1 = Permutation(permutation_array1)
p2 = Permutation(permutation_array2)
cg = _permute_dims(
_permute_dims(
_array_tensor_product(M, N, P),
p1),
p2
)
result = _permute_dims(
_array_tensor_product(M, N, P),
p2*p1
)
assert cg == result
# Check that `permutedims` behaves the same way with explicit-component arrays:
result1 = _permute_dims(_permute_dims(cge, p1), p2)
result2 = _permute_dims(cge, p2*p1)
assert result1 == result2
def test_arrayexpr_contraction_permutation_mix():
Me = M.subs(k, 3).as_explicit()
Ne = N.subs(k, 3).as_explicit()
cg1 = _array_contraction(PermuteDims(_array_tensor_product(M, N), Permutation([0, 2, 1, 3])), (2, 3))
cg2 = _array_contraction(_array_tensor_product(M, N), (1, 3))
assert cg1 == cg2
cge1 = tensorcontraction(permutedims(tensorproduct(Me, Ne), Permutation([0, 2, 1, 3])), (2, 3))
cge2 = tensorcontraction(tensorproduct(Me, Ne), (1, 3))
assert cge1 == cge2
cg1 = _permute_dims(_array_tensor_product(M, N), Permutation([0, 1, 3, 2]))
cg2 = _array_tensor_product(M, _permute_dims(N, Permutation([1, 0])))
assert cg1 == cg2
cg1 = _array_contraction(
_permute_dims(
_array_tensor_product(M, N, P, Q), Permutation([0, 2, 3, 1, 4, 5, 7, 6])),
(1, 2), (3, 5)
)
cg2 = _array_contraction(
_array_tensor_product(M, N, P, _permute_dims(Q, Permutation([1, 0]))),
(1, 5), (2, 3)
)
assert cg1 == cg2
cg1 = _array_contraction(
_permute_dims(
_array_tensor_product(M, N, P, Q), Permutation([1, 0, 4, 6, 2, 7, 5, 3])),
(0, 1), (2, 6), (3, 7)
)
cg2 = _permute_dims(
_array_contraction(
_array_tensor_product(M, P, Q, N),
(0, 1), (2, 3), (4, 7)),
[1, 0]
)
assert cg1 == cg2
cg1 = _array_contraction(
_permute_dims(
_array_tensor_product(M, N, P, Q), Permutation([1, 0, 4, 6, 7, 2, 5, 3])),
(0, 1), (2, 6), (3, 7)
)
cg2 = _permute_dims(
_array_contraction(
_array_tensor_product(_permute_dims(M, [1, 0]), N, P, Q),
(0, 1), (3, 6), (4, 5)
),
Permutation([1, 0])
)
assert cg1 == cg2
def test_arrayexpr_permute_tensor_product():
cg1 = _permute_dims(_array_tensor_product(M, N, P, Q), Permutation([2, 3, 1, 0, 5, 4, 6, 7]))
cg2 = _array_tensor_product(N, _permute_dims(M, [1, 0]),
_permute_dims(P, [1, 0]), Q)
assert cg1 == cg2
# TODO: reverse operation starting with `PermuteDims` and getting down to `bb`...
cg1 = _permute_dims(_array_tensor_product(M, N, P, Q), Permutation([2, 3, 4, 5, 0, 1, 6, 7]))
cg2 = _array_tensor_product(N, P, M, Q)
assert cg1 == cg2
cg1 = _permute_dims(_array_tensor_product(M, N, P, Q), Permutation([2, 3, 4, 6, 5, 7, 0, 1]))
assert cg1.expr == _array_tensor_product(N, P, Q, M)
assert cg1.permutation == Permutation([0, 1, 2, 4, 3, 5, 6, 7])
cg1 = _array_contraction(
_permute_dims(
_array_tensor_product(N, Q, Q, M),
[2, 1, 5, 4, 0, 3, 6, 7]),
[1, 2, 6])
cg2 = _permute_dims(_array_contraction(_array_tensor_product(Q, Q, N, M), (3, 5, 6)), [0, 2, 3, 1, 4])
assert cg1 == cg2
cg1 = _array_contraction(
_array_contraction(
_array_contraction(
_array_contraction(
_permute_dims(
_array_tensor_product(N, Q, Q, M),
[2, 1, 5, 4, 0, 3, 6, 7]),
[1, 2, 6]),
[1, 3, 4]),
[1]),
[0])
cg2 = _array_contraction(_array_tensor_product(M, N, Q, Q), (0, 3, 5), (1, 4, 7), (2,), (6,))
assert cg1 == cg2
def test_arrayexpr_canonicalize_diagonal__permute_dims():
tp = _array_tensor_product(M, Q, N, P)
expr = _array_diagonal(
_permute_dims(tp, [0, 1, 2, 4, 7, 6, 3, 5]), (2, 4, 5), (6, 7),
(0, 3))
result = _array_diagonal(tp, (2, 6, 7), (3, 5), (0, 4))
assert expr == result
tp = _array_tensor_product(M, N, P, Q)
expr = _array_diagonal(_permute_dims(tp, [0, 5, 2, 4, 1, 6, 3, 7]), (1, 2, 6), (3, 4))
result = _array_diagonal(_array_tensor_product(M, P, N, Q), (3, 4, 5), (1, 2))
assert expr == result
def test_arrayexpr_canonicalize_diagonal_contraction():
tp = _array_tensor_product(M, N, P, Q)
expr = _array_contraction(_array_diagonal(tp, (1, 3, 4)), (0, 3))
result = _array_diagonal(_array_contraction(_array_tensor_product(M, N, P, Q), (0, 6)), (0, 2, 3))
assert expr == result
expr = _array_contraction(_array_diagonal(tp, (0, 1, 2, 3, 7)), (1, 2, 3))
result = _array_contraction(_array_tensor_product(M, N, P, Q), (0, 1, 2, 3, 5, 6, 7))
assert expr == result
expr = _array_contraction(_array_diagonal(tp, (0, 2, 6, 7)), (1, 2, 3))
result = _array_diagonal(_array_contraction(tp, (3, 4, 5)), (0, 2, 3, 4))
assert expr == result
td = _array_diagonal(_array_tensor_product(M, N, P, Q), (0, 3))
expr = _array_contraction(td, (2, 1), (0, 4, 6, 5, 3))
result = _array_contraction(_array_tensor_product(M, N, P, Q), (0, 1, 3, 5, 6, 7), (2, 4))
assert expr == result
def test_arrayexpr_array_wrong_permutation_size():
cg = _array_tensor_product(M, N)
raises(ValueError, lambda: _permute_dims(cg, [1, 0]))
raises(ValueError, lambda: _permute_dims(cg, [1, 0, 2, 3, 5, 4]))
def test_arrayexpr_nested_array_elementwise_add():
cg = _array_contraction(_array_add(
_array_tensor_product(M, N),
_array_tensor_product(N, M)
), (1, 2))
result = _array_add(
_array_contraction(_array_tensor_product(M, N), (1, 2)),
_array_contraction(_array_tensor_product(N, M), (1, 2))
)
assert cg == result
cg = _array_diagonal(_array_add(
_array_tensor_product(M, N),
_array_tensor_product(N, M)
), (1, 2))
result = _array_add(
_array_diagonal(_array_tensor_product(M, N), (1, 2)),
_array_diagonal(_array_tensor_product(N, M), (1, 2))
)
assert cg == result
def test_arrayexpr_array_expr_zero_array():
za1 = ZeroArray(k, l, m, n)
zm1 = ZeroMatrix(m, n)
za2 = ZeroArray(k, m, m, n)
zm2 = ZeroMatrix(m, m)
zm3 = ZeroMatrix(k, k)
assert _array_tensor_product(M, N, za1) == ZeroArray(k, k, k, k, k, l, m, n)
assert _array_tensor_product(M, N, zm1) == ZeroArray(k, k, k, k, m, n)
assert _array_contraction(za1, (3,)) == ZeroArray(k, l, m)
assert _array_contraction(zm1, (1,)) == ZeroArray(m)
assert _array_contraction(za2, (1, 2)) == ZeroArray(k, n)
assert _array_contraction(zm2, (0, 1)) == 0
assert _array_diagonal(za2, (1, 2)) == ZeroArray(k, n, m)
assert _array_diagonal(zm2, (0, 1)) == ZeroArray(m)
assert _permute_dims(za1, [2, 1, 3, 0]) == ZeroArray(m, l, n, k)
assert _permute_dims(zm1, [1, 0]) == ZeroArray(n, m)
assert _array_add(za1) == za1
assert _array_add(zm1) == ZeroArray(m, n)
tp1 = _array_tensor_product(MatrixSymbol("A", k, l), MatrixSymbol("B", m, n))
assert _array_add(tp1, za1) == tp1
tp2 = _array_tensor_product(MatrixSymbol("C", k, l), MatrixSymbol("D", m, n))
assert _array_add(tp1, za1, tp2) == _array_add(tp1, tp2)
assert _array_add(M, zm3) == M
assert _array_add(M, N, zm3) == _array_add(M, N)
def test_arrayexpr_array_expr_applyfunc():
A = ArraySymbol("A", (3, k, 2))
aaf = ArrayElementwiseApplyFunc(sin, A)
assert aaf.shape == (3, k, 2)
def test_edit_array_contraction():
cg = _array_contraction(_array_tensor_product(A, B, C, D), (1, 2, 5))
ecg = _EditArrayContraction(cg)
assert ecg.to_array_contraction() == cg
ecg.args_with_ind[1], ecg.args_with_ind[2] = ecg.args_with_ind[2], ecg.args_with_ind[1]
assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, C, B, D), (1, 3, 4))
ci = ecg.get_new_contraction_index()
new_arg = _ArgE(X)
new_arg.indices = [ci, ci]
ecg.args_with_ind.insert(2, new_arg)
assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, C, X, B, D), (1, 3, 6), (4, 5))
assert ecg.get_contraction_indices() == [[1, 3, 6], [4, 5]]
assert [[tuple(j) for j in i] for i in ecg.get_contraction_indices_to_ind_rel_pos()] == [[(0, 1), (1, 1), (3, 0)], [(2, 0), (2, 1)]]
assert [list(i) for i in ecg.get_mapping_for_index(0)] == [[0, 1], [1, 1], [3, 0]]
assert [list(i) for i in ecg.get_mapping_for_index(1)] == [[2, 0], [2, 1]]
raises(ValueError, lambda: ecg.get_mapping_for_index(2))
ecg.args_with_ind.pop(1)
assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, X, B, D), (1, 4), (2, 3))
ecg.args_with_ind[0].indices[1] = ecg.args_with_ind[1].indices[0]
ecg.args_with_ind[1].indices[1] = ecg.args_with_ind[2].indices[0]
assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, X, B, D), (1, 2), (3, 4))
ecg.insert_after(ecg.args_with_ind[1], _ArgE(C))
assert ecg.to_array_contraction() == _array_contraction(_array_tensor_product(A, X, C, B, D), (1, 2), (3, 6))
def test_array_expressions_no_canonicalization():
tp = _array_tensor_product(M, N, P)
# ArrayTensorProduct:
expr = ArrayTensorProduct(tp, N)
assert str(expr) == "ArrayTensorProduct(ArrayTensorProduct(M, N, P), N)"
assert expr.doit() == ArrayTensorProduct(M, N, P, N)
expr = ArrayTensorProduct(ArrayContraction(M, (0, 1)), N)
assert str(expr) == "ArrayTensorProduct(ArrayContraction(M, (0, 1)), N)"
assert expr.doit() == ArrayContraction(ArrayTensorProduct(M, N), (0, 1))
expr = ArrayTensorProduct(ArrayDiagonal(M, (0, 1)), N)
assert str(expr) == "ArrayTensorProduct(ArrayDiagonal(M, (0, 1)), N)"
assert expr.doit() == PermuteDims(ArrayDiagonal(ArrayTensorProduct(M, N), (0, 1)), [2, 0, 1])
expr = ArrayTensorProduct(PermuteDims(M, [1, 0]), N)
assert str(expr) == "ArrayTensorProduct(PermuteDims(M, (0 1)), N)"
assert expr.doit() == PermuteDims(ArrayTensorProduct(M, N), [1, 0, 2, 3])
# ArrayContraction:
expr = ArrayContraction(_array_contraction(tp, (0, 2)), (0, 1))
assert isinstance(expr, ArrayContraction)
assert isinstance(expr.expr, ArrayContraction)
assert str(expr) == "ArrayContraction(ArrayContraction(ArrayTensorProduct(M, N, P), (0, 2)), (0, 1))"
assert expr.doit() == ArrayContraction(tp, (0, 2), (1, 3))
expr = ArrayContraction(ArrayContraction(ArrayContraction(tp, (0, 1)), (0, 1)), (0, 1))
assert expr.doit() == ArrayContraction(tp, (0, 1), (2, 3), (4, 5))
# assert expr._canonicalize() == ArrayContraction(ArrayContraction(tp, (0, 1)), (0, 1), (2, 3))
expr = ArrayContraction(ArrayDiagonal(tp, (0, 1)), (0, 1))
assert str(expr) == "ArrayContraction(ArrayDiagonal(ArrayTensorProduct(M, N, P), (0, 1)), (0, 1))"
assert expr.doit() == ArrayDiagonal(ArrayContraction(ArrayTensorProduct(N, M, P), (0, 1)), (0, 1))
expr = ArrayContraction(PermuteDims(M, [1, 0]), (0, 1))
assert str(expr) == "ArrayContraction(PermuteDims(M, (0 1)), (0, 1))"
assert expr.doit() == ArrayContraction(M, (0, 1))
# ArrayDiagonal:
expr = ArrayDiagonal(ArrayDiagonal(tp, (0, 2)), (0, 1))
assert str(expr) == "ArrayDiagonal(ArrayDiagonal(ArrayTensorProduct(M, N, P), (0, 2)), (0, 1))"
assert expr.doit() == ArrayDiagonal(tp, (0, 2), (1, 3))
expr = ArrayDiagonal(ArrayDiagonal(ArrayDiagonal(tp, (0, 1)), (0, 1)), (0, 1))
assert expr.doit() == ArrayDiagonal(tp, (0, 1), (2, 3), (4, 5))
assert expr._canonicalize() == expr.doit()
expr = ArrayDiagonal(ArrayContraction(tp, (0, 1)), (0, 1))
assert str(expr) == "ArrayDiagonal(ArrayContraction(ArrayTensorProduct(M, N, P), (0, 1)), (0, 1))"
assert expr.doit() == expr
expr = ArrayDiagonal(PermuteDims(M, [1, 0]), (0, 1))
assert str(expr) == "ArrayDiagonal(PermuteDims(M, (0 1)), (0, 1))"
assert expr.doit() == ArrayDiagonal(M, (0, 1))
# ArrayAdd:
expr = ArrayAdd(M)
assert isinstance(expr, ArrayAdd)
assert expr.doit() == M
expr = ArrayAdd(ArrayAdd(M, N), P)
assert str(expr) == "ArrayAdd(ArrayAdd(M, N), P)"
assert expr.doit() == ArrayAdd(M, N, P)
expr = ArrayAdd(M, ArrayAdd(N, ArrayAdd(P, M)))
assert expr.doit() == ArrayAdd(M, N, P, M)
assert expr._canonicalize() == ArrayAdd(M, N, ArrayAdd(P, M))
expr = ArrayAdd(M, ZeroArray(k, k), N)
assert str(expr) == "ArrayAdd(M, ZeroArray(k, k), N)"
assert expr.doit() == ArrayAdd(M, N)
# PermuteDims:
expr = PermuteDims(PermuteDims(M, [1, 0]), [1, 0])
assert str(expr) == "PermuteDims(PermuteDims(M, (0 1)), (0 1))"
assert expr.doit() == M
expr = PermuteDims(PermuteDims(PermuteDims(M, [1, 0]), [1, 0]), [1, 0])
assert expr.doit() == PermuteDims(M, [1, 0])
assert expr._canonicalize() == expr.doit()
def test_array_expr_construction_with_functions():
tp = tensorproduct(M, N)
assert tp == ArrayTensorProduct(M, N)
expr = tensorproduct(A, eye(2))
assert expr == ArrayTensorProduct(A, eye(2))
# Contraction:
expr = tensorcontraction(M, (0, 1))
assert expr == ArrayContraction(M, (0, 1))
expr = tensorcontraction(tp, (1, 2))
assert expr == ArrayContraction(tp, (1, 2))
expr = tensorcontraction(tensorcontraction(tp, (1, 2)), (0, 1))
assert expr == ArrayContraction(tp, (0, 3), (1, 2))
# Diagonalization:
expr = tensordiagonal(M, (0, 1))
assert expr == ArrayDiagonal(M, (0, 1))
expr = tensordiagonal(tensordiagonal(tp, (0, 1)), (0, 1))
assert expr == ArrayDiagonal(tp, (0, 1), (2, 3))
# Permutation of dimensions:
expr = permutedims(M, [1, 0])
assert expr == PermuteDims(M, [1, 0])
expr = permutedims(PermuteDims(tp, [1, 0, 2, 3]), [0, 1, 3, 2])
assert expr == PermuteDims(tp, [1, 0, 3, 2])
def test_array_element_expressions():
# Check commutative property:
assert M[0, 0]*N[0, 0] == N[0, 0]*M[0, 0]
# Check derivatives:
assert M[0, 0].diff(M[0, 0]) == 1
assert M[0, 0].diff(M[1, 0]) == 0
assert M[0, 0].diff(N[0, 0]) == 0
assert M[0, 1].diff(M[i, j]) == KroneckerDelta(i, 0)*KroneckerDelta(j, 1)
assert M[0, 1].diff(N[i, j]) == 0
K4 = ArraySymbol("K4", shape=(k, k, k, k))
assert K4[i, j, k, l].diff(K4[1, 2, 3, 4]) == (
KroneckerDelta(i, 1)*KroneckerDelta(j, 2)*KroneckerDelta(k, 3)*KroneckerDelta(l, 4)
)
|
620b18da15857f8e12a8ade85db36e63a3d7bad2f505796c047b21f48c25df38 | from sympy.core.symbol import symbols
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.special import Identity
from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
from sympy.tensor.array.expressions.array_expressions import ArraySymbol, ArrayTensorProduct, \
PermuteDims, ArrayDiagonal, ArrayElementwiseApplyFunc, ArrayContraction, _permute_dims
from sympy.tensor.array.expressions.arrayexpr_derivatives import array_derive
k = symbols("k")
I = Identity(k)
X = MatrixSymbol("X", k, k)
x = MatrixSymbol("x", k, 1)
A = MatrixSymbol("A", k, k)
B = MatrixSymbol("B", k, k)
C = MatrixSymbol("C", k, k)
D = MatrixSymbol("D", k, k)
A1 = ArraySymbol("A", (3, 2, k))
def test_arrayexpr_derivatives1():
res = array_derive(X, X)
assert res == PermuteDims(ArrayTensorProduct(I, I), [0, 2, 1, 3])
cg = ArrayTensorProduct(A, X, B)
res = array_derive(cg, X)
assert res == _permute_dims(
ArrayTensorProduct(I, A, I, B),
[0, 4, 2, 3, 1, 5, 6, 7])
cg = ArrayContraction(X, (0, 1))
res = array_derive(cg, X)
assert res == ArrayContraction(ArrayTensorProduct(I, I), (1, 3))
cg = ArrayDiagonal(X, (0, 1))
res = array_derive(cg, X)
assert res == ArrayDiagonal(ArrayTensorProduct(I, I), (1, 3))
cg = ElementwiseApplyFunction(sin, X)
res = array_derive(cg, X)
assert res.dummy_eq(ArrayDiagonal(
ArrayTensorProduct(
ElementwiseApplyFunction(cos, X),
I,
I
), (0, 3), (1, 5)))
cg = ArrayElementwiseApplyFunc(sin, X)
res = array_derive(cg, X)
assert res.dummy_eq(ArrayDiagonal(
ArrayTensorProduct(
I,
I,
ArrayElementwiseApplyFunc(cos, X)
), (1, 4), (3, 5)))
res = array_derive(A1, A1)
assert res == PermuteDims(
ArrayTensorProduct(Identity(3), Identity(2), Identity(k)),
[0, 2, 4, 1, 3, 5]
)
cg = ArrayElementwiseApplyFunc(sin, A1)
res = array_derive(cg, A1)
assert res.dummy_eq(ArrayDiagonal(
ArrayTensorProduct(
Identity(3), Identity(2), Identity(k),
ArrayElementwiseApplyFunc(cos, A1)
), (1, 6), (3, 7), (5, 8)
))
|
e8c09e0bd2855df3d76662e690f3554b1df27aac6cb7566649ebff5624496662 | from sympy.assumptions.ask import Q
from sympy.assumptions.refine import refine
from sympy.core.numbers import oo
from sympy.core.relational import Equality, Eq, Ne
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, symbols)
from sympy.functions import Piecewise
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.sets.sets import (Interval, Union)
from sympy.simplify.simplify import simplify
from sympy.logic.boolalg import (
And, Boolean, Equivalent, ITE, Implies, Nand, Nor, Not, Or,
POSform, SOPform, Xor, Xnor, conjuncts, disjuncts,
distribute_or_over_and, distribute_and_over_or,
eliminate_implications, is_nnf, is_cnf, is_dnf, simplify_logic,
to_nnf, to_cnf, to_dnf, to_int_repr, bool_map, true, false,
BooleanAtom, is_literal, term_to_integer,
truth_table, as_Boolean, to_anf, is_anf, distribute_xor_over_and,
anf_coeffs, ANFform, bool_minterm, bool_maxterm, bool_monomial,
_check_pair, _convert_to_varsSOP, _convert_to_varsPOS, Exclusive,)
from sympy.assumptions.cnf import CNF
from sympy.testing.pytest import raises, XFAIL, slow
from itertools import combinations, permutations, product
A, B, C, D = symbols('A:D')
a, b, c, d, e, w, x, y, z = symbols('a:e w:z')
def test_overloading():
"""Test that |, & are overloaded as expected"""
assert A & B == And(A, B)
assert A | B == Or(A, B)
assert (A & B) | C == Or(And(A, B), C)
assert A >> B == Implies(A, B)
assert A << B == Implies(B, A)
assert ~A == Not(A)
assert A ^ B == Xor(A, B)
def test_And():
assert And() is true
assert And(A) == A
assert And(True) is true
assert And(False) is false
assert And(True, True) is true
assert And(True, False) is false
assert And(False, False) is false
assert And(True, A) == A
assert And(False, A) is false
assert And(True, True, True) is true
assert And(True, True, A) == A
assert And(True, False, A) is false
assert And(1, A) == A
raises(TypeError, lambda: And(2, A))
raises(TypeError, lambda: And(A < 2, A))
assert And(A < 1, A >= 1) is false
e = A > 1
assert And(e, e.canonical) == e.canonical
g, l, ge, le = A > B, B < A, A >= B, B <= A
assert And(g, l, ge, le) == And(ge, g)
assert {And(*i) for i in permutations((l,g,le,ge))} == {And(ge, g)}
assert And(And(Eq(a, 0), Eq(b, 0)), And(Ne(a, 0), Eq(c, 0))) is false
def test_Or():
assert Or() is false
assert Or(A) == A
assert Or(True) is true
assert Or(False) is false
assert Or(True, True) is true
assert Or(True, False) is true
assert Or(False, False) is false
assert Or(True, A) is true
assert Or(False, A) == A
assert Or(True, False, False) is true
assert Or(True, False, A) is true
assert Or(False, False, A) == A
assert Or(1, A) is true
raises(TypeError, lambda: Or(2, A))
raises(TypeError, lambda: Or(A < 2, A))
assert Or(A < 1, A >= 1) is true
e = A > 1
assert Or(e, e.canonical) == e
g, l, ge, le = A > B, B < A, A >= B, B <= A
assert Or(g, l, ge, le) == Or(g, ge)
def test_Xor():
assert Xor() is false
assert Xor(A) == A
assert Xor(A, A) is false
assert Xor(True, A, A) is true
assert Xor(A, A, A, A, A) == A
assert Xor(True, False, False, A, B) == ~Xor(A, B)
assert Xor(True) is true
assert Xor(False) is false
assert Xor(True, True) is false
assert Xor(True, False) is true
assert Xor(False, False) is false
assert Xor(True, A) == ~A
assert Xor(False, A) == A
assert Xor(True, False, False) is true
assert Xor(True, False, A) == ~A
assert Xor(False, False, A) == A
assert isinstance(Xor(A, B), Xor)
assert Xor(A, B, Xor(C, D)) == Xor(A, B, C, D)
assert Xor(A, B, Xor(B, C)) == Xor(A, C)
assert Xor(A < 1, A >= 1, B) == Xor(0, 1, B) == Xor(1, 0, B)
e = A > 1
assert Xor(e, e.canonical) == Xor(0, 0) == Xor(1, 1)
def test_rewrite_as_And():
expr = x ^ y
assert expr.rewrite(And) == (x | y) & (~x | ~y)
def test_rewrite_as_Or():
expr = x ^ y
assert expr.rewrite(Or) == (x & ~y) | (y & ~x)
def test_rewrite_as_Nand():
expr = (y & z) | (z & ~w)
assert expr.rewrite(Nand) == ~(~(y & z) & ~(z & ~w))
def test_rewrite_as_Nor():
expr = z & (y | ~w)
assert expr.rewrite(Nor) == ~(~z | ~(y | ~w))
def test_Not():
raises(TypeError, lambda: Not(True, False))
assert Not(True) is false
assert Not(False) is true
assert Not(0) is true
assert Not(1) is false
assert Not(2) is false
def test_Nand():
assert Nand() is false
assert Nand(A) == ~A
assert Nand(True) is false
assert Nand(False) is true
assert Nand(True, True) is false
assert Nand(True, False) is true
assert Nand(False, False) is true
assert Nand(True, A) == ~A
assert Nand(False, A) is true
assert Nand(True, True, True) is false
assert Nand(True, True, A) == ~A
assert Nand(True, False, A) is true
def test_Nor():
assert Nor() is true
assert Nor(A) == ~A
assert Nor(True) is false
assert Nor(False) is true
assert Nor(True, True) is false
assert Nor(True, False) is false
assert Nor(False, False) is true
assert Nor(True, A) is false
assert Nor(False, A) == ~A
assert Nor(True, True, True) is false
assert Nor(True, True, A) is false
assert Nor(True, False, A) is false
def test_Xnor():
assert Xnor() is true
assert Xnor(A) == ~A
assert Xnor(A, A) is true
assert Xnor(True, A, A) is false
assert Xnor(A, A, A, A, A) == ~A
assert Xnor(True) is false
assert Xnor(False) is true
assert Xnor(True, True) is true
assert Xnor(True, False) is false
assert Xnor(False, False) is true
assert Xnor(True, A) == A
assert Xnor(False, A) == ~A
assert Xnor(True, False, False) is false
assert Xnor(True, False, A) == A
assert Xnor(False, False, A) == ~A
def test_Implies():
raises(ValueError, lambda: Implies(A, B, C))
assert Implies(True, True) is true
assert Implies(True, False) is false
assert Implies(False, True) is true
assert Implies(False, False) is true
assert Implies(0, A) is true
assert Implies(1, 1) is true
assert Implies(1, 0) is false
assert A >> B == B << A
assert (A < 1) >> (A >= 1) == (A >= 1)
assert (A < 1) >> (S.One > A) is true
assert A >> A is true
def test_Equivalent():
assert Equivalent(A, B) == Equivalent(B, A) == Equivalent(A, B, A)
assert Equivalent() is true
assert Equivalent(A, A) == Equivalent(A) is true
assert Equivalent(True, True) == Equivalent(False, False) is true
assert Equivalent(True, False) == Equivalent(False, True) is false
assert Equivalent(A, True) == A
assert Equivalent(A, False) == Not(A)
assert Equivalent(A, B, True) == A & B
assert Equivalent(A, B, False) == ~A & ~B
assert Equivalent(1, A) == A
assert Equivalent(0, A) == Not(A)
assert Equivalent(A, Equivalent(B, C)) != Equivalent(Equivalent(A, B), C)
assert Equivalent(A < 1, A >= 1) is false
assert Equivalent(A < 1, A >= 1, 0) is false
assert Equivalent(A < 1, A >= 1, 1) is false
assert Equivalent(A < 1, S.One > A) == Equivalent(1, 1) == Equivalent(0, 0)
assert Equivalent(Equality(A, B), Equality(B, A)) is true
def test_Exclusive():
assert Exclusive(False, False, False) is true
assert Exclusive(True, False, False) is true
assert Exclusive(True, True, False) is false
assert Exclusive(True, True, True) is false
def test_equals():
assert Not(Or(A, B)).equals(And(Not(A), Not(B))) is True
assert Equivalent(A, B).equals((A >> B) & (B >> A)) is True
assert ((A | ~B) & (~A | B)).equals((~A & ~B) | (A & B)) is True
assert (A >> B).equals(~A >> ~B) is False
assert (A >> (B >> A)).equals(A >> (C >> A)) is False
raises(NotImplementedError, lambda: (A & B).equals(A > B))
def test_simplification_boolalg():
"""
Test working of simplification methods.
"""
set1 = [[0, 0, 1], [0, 1, 1], [1, 0, 0], [1, 1, 0]]
set2 = [[0, 0, 0], [0, 1, 0], [1, 0, 1], [1, 1, 1]]
assert SOPform([x, y, z], set1) == Or(And(Not(x), z), And(Not(z), x))
assert Not(SOPform([x, y, z], set2)) == \
Not(Or(And(Not(x), Not(z)), And(x, z)))
assert POSform([x, y, z], set1 + set2) is true
assert SOPform([x, y, z], set1 + set2) is true
assert SOPform([Dummy(), Dummy(), Dummy()], set1 + set2) is true
minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1],
[1, 1, 1, 1]]
dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
assert (
SOPform([w, x, y, z], minterms, dontcares) ==
Or(And(y, z), And(Not(w), Not(x))))
assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
minterms = [1, 3, 7, 11, 15]
dontcares = [0, 2, 5]
assert (
SOPform([w, x, y, z], minterms, dontcares) ==
Or(And(y, z), And(Not(w), Not(x))))
assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
minterms = [1, [0, 0, 1, 1], 7, [1, 0, 1, 1],
[1, 1, 1, 1]]
dontcares = [0, [0, 0, 1, 0], 5]
assert (
SOPform([w, x, y, z], minterms, dontcares) ==
Or(And(y, z), And(Not(w), Not(x))))
assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
minterms = [1, {y: 1, z: 1}]
dontcares = [0, [0, 0, 1, 0], 5]
assert (
SOPform([w, x, y, z], minterms, dontcares) ==
Or(And(y, z), And(Not(w), Not(x))))
assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
minterms = [{y: 1, z: 1}, 1]
dontcares = [[0, 0, 0, 0]]
minterms = [[0, 0, 0]]
raises(ValueError, lambda: SOPform([w, x, y, z], minterms))
raises(ValueError, lambda: POSform([w, x, y, z], minterms))
raises(TypeError, lambda: POSform([w, x, y, z], ["abcdefg"]))
# test simplification
ans = And(A, Or(B, C))
assert simplify_logic(A & (B | C)) == ans
assert simplify_logic((A & B) | (A & C)) == ans
assert simplify_logic(Implies(A, B)) == Or(Not(A), B)
assert simplify_logic(Equivalent(A, B)) == \
Or(And(A, B), And(Not(A), Not(B)))
assert simplify_logic(And(Equality(A, 2), C)) == And(Equality(A, 2), C)
assert simplify_logic(And(Equality(A, 2), A)) is S.false
assert simplify_logic(And(Equality(A, 2), A)) == And(Equality(A, 2), A)
assert simplify_logic(And(Equality(A, B), C)) == And(Equality(A, B), C)
assert simplify_logic(Or(And(Equality(A, 3), B), And(Equality(A, 3), C))) \
== And(Equality(A, 3), Or(B, C))
b = (~x & ~y & ~z) | (~x & ~y & z)
e = And(A, b)
assert simplify_logic(e) == A & ~x & ~y
raises(ValueError, lambda: simplify_logic(A & (B | C), form='blabla'))
assert simplify(Or(x <= y, And(x < y, z))) == (x <= y)
assert simplify(Or(x <= y, And(y > x, z))) == (x <= y)
assert simplify(Or(x >= y, And(y < x, z))) == (x >= y)
# Check that expressions with nine variables or more are not simplified
# (without the force-flag)
a, b, c, d, e, f, g, h, j = symbols('a b c d e f g h j')
expr = a & b & c & d & e & f & g & h & j | \
a & b & c & d & e & f & g & h & ~j
# This expression can be simplified to get rid of the j variables
assert simplify_logic(expr) == expr
# check input
ans = SOPform([x, y], [[1, 0]])
assert SOPform([x, y], [[1, 0]]) == ans
assert POSform([x, y], [[1, 0]]) == ans
raises(ValueError, lambda: SOPform([x], [[1]], [[1]]))
assert SOPform([x], [[1]], [[0]]) is true
assert SOPform([x], [[0]], [[1]]) is true
assert SOPform([x], [], []) is false
raises(ValueError, lambda: POSform([x], [[1]], [[1]]))
assert POSform([x], [[1]], [[0]]) is true
assert POSform([x], [[0]], [[1]]) is true
assert POSform([x], [], []) is false
# check working of simplify
assert simplify((A & B) | (A & C)) == And(A, Or(B, C))
assert simplify(And(x, Not(x))) == False
assert simplify(Or(x, Not(x))) == True
assert simplify(And(Eq(x, 0), Eq(x, y))) == And(Eq(x, 0), Eq(y, 0))
assert And(Eq(x - 1, 0), Eq(x, y)).simplify() == And(Eq(x, 1), Eq(y, 1))
assert And(Ne(x - 1, 0), Ne(x, y)).simplify() == And(Ne(x, 1), Ne(x, y))
assert And(Eq(x - 1, 0), Ne(x, y)).simplify() == And(Eq(x, 1), Ne(y, 1))
assert And(Eq(x - 1, 0), Eq(x, z + y), Eq(y + x, 0)).simplify(
) == And(Eq(x, 1), Eq(y, -1), Eq(z, 2))
assert And(Eq(x - 1, 0), Eq(x + 2, 3)).simplify() == Eq(x, 1)
assert And(Ne(x - 1, 0), Ne(x + 2, 3)).simplify() == Ne(x, 1)
assert And(Eq(x - 1, 0), Eq(x + 2, 2)).simplify() == False
assert And(Ne(x - 1, 0), Ne(x + 2, 2)).simplify(
) == And(Ne(x, 1), Ne(x, 0))
def test_bool_map():
"""
Test working of bool_map function.
"""
minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1],
[1, 1, 1, 1]]
assert bool_map(Not(Not(a)), a) == (a, {a: a})
assert bool_map(SOPform([w, x, y, z], minterms),
POSform([w, x, y, z], minterms)) == \
(And(Or(Not(w), y), Or(Not(x), y), z), {x: x, w: w, z: z, y: y})
assert bool_map(SOPform([x, z, y], [[1, 0, 1]]),
SOPform([a, b, c], [[1, 0, 1]])) != False
function1 = SOPform([x, z, y], [[1, 0, 1], [0, 0, 1]])
function2 = SOPform([a, b, c], [[1, 0, 1], [1, 0, 0]])
assert bool_map(function1, function2) == \
(function1, {y: a, z: b})
assert bool_map(Xor(x, y), ~Xor(x, y)) == False
assert bool_map(And(x, y), Or(x, y)) is None
assert bool_map(And(x, y), And(x, y, z)) is None
# issue 16179
assert bool_map(Xor(x, y, z), ~Xor(x, y, z)) == False
assert bool_map(Xor(a, x, y, z), ~Xor(a, x, y, z)) == False
def test_bool_symbol():
"""Test that mixing symbols with boolean values
works as expected"""
assert And(A, True) == A
assert And(A, True, True) == A
assert And(A, False) is false
assert And(A, True, False) is false
assert Or(A, True) is true
assert Or(A, False) == A
def test_is_boolean():
assert isinstance(True, Boolean) is False
assert isinstance(true, Boolean) is True
assert 1 == True
assert 1 != true
assert (1 == true) is False
assert 0 == False
assert 0 != false
assert (0 == false) is False
assert true.is_Boolean is True
assert (A & B).is_Boolean
assert (A | B).is_Boolean
assert (~A).is_Boolean
assert (A ^ B).is_Boolean
assert A.is_Boolean != isinstance(A, Boolean)
assert isinstance(A, Boolean)
def test_subs():
assert (A & B).subs(A, True) == B
assert (A & B).subs(A, False) is false
assert (A & B).subs(B, True) == A
assert (A & B).subs(B, False) is false
assert (A & B).subs({A: True, B: True}) is true
assert (A | B).subs(A, True) is true
assert (A | B).subs(A, False) == B
assert (A | B).subs(B, True) is true
assert (A | B).subs(B, False) == A
assert (A | B).subs({A: True, B: True}) is true
"""
we test for axioms of boolean algebra
see https://en.wikipedia.org/wiki/Boolean_algebra_(structure)
"""
def test_commutative():
"""Test for commutativity of And and Or"""
A, B = map(Boolean, symbols('A,B'))
assert A & B == B & A
assert A | B == B | A
def test_and_associativity():
"""Test for associativity of And"""
assert (A & B) & C == A & (B & C)
def test_or_assicativity():
assert ((A | B) | C) == (A | (B | C))
def test_double_negation():
a = Boolean()
assert ~(~a) == a
# test methods
def test_eliminate_implications():
assert eliminate_implications(Implies(A, B, evaluate=False)) == (~A) | B
assert eliminate_implications(
A >> (C >> Not(B))) == Or(Or(Not(B), Not(C)), Not(A))
assert eliminate_implications(Equivalent(A, B, C, D)) == \
(~A | B) & (~B | C) & (~C | D) & (~D | A)
def test_conjuncts():
assert conjuncts(A & B & C) == {A, B, C}
assert conjuncts((A | B) & C) == {A | B, C}
assert conjuncts(A) == {A}
assert conjuncts(True) == {True}
assert conjuncts(False) == {False}
def test_disjuncts():
assert disjuncts(A | B | C) == {A, B, C}
assert disjuncts((A | B) & C) == {(A | B) & C}
assert disjuncts(A) == {A}
assert disjuncts(True) == {True}
assert disjuncts(False) == {False}
def test_distribute():
assert distribute_and_over_or(Or(And(A, B), C)) == And(Or(A, C), Or(B, C))
assert distribute_or_over_and(And(A, Or(B, C))) == Or(And(A, B), And(A, C))
assert distribute_xor_over_and(And(A, Xor(B, C))) == Xor(And(A, B), And(A, C))
def test_to_anf():
x, y, z = symbols('x,y,z')
assert to_anf(And(x, y)) == And(x, y)
assert to_anf(Or(x, y)) == Xor(x, y, And(x, y))
assert to_anf(Or(Implies(x, y), And(x, y), y)) == \
Xor(x, True, x & y, remove_true=False)
assert to_anf(Or(Nand(x, y), Nor(x, y), Xnor(x, y), Implies(x, y))) == True
assert to_anf(Or(x, Not(y), Nor(x,z), And(x, y), Nand(y, z))) == \
Xor(True, And(y, z), And(x, y, z), remove_true=False)
assert to_anf(Xor(x, y)) == Xor(x, y)
assert to_anf(Not(x)) == Xor(x, True, remove_true=False)
assert to_anf(Nand(x, y)) == Xor(True, And(x, y), remove_true=False)
assert to_anf(Nor(x, y)) == Xor(x, y, True, And(x, y), remove_true=False)
assert to_anf(Implies(x, y)) == Xor(x, True, And(x, y), remove_true=False)
assert to_anf(Equivalent(x, y)) == Xor(x, y, True, remove_true=False)
assert to_anf(Nand(x | y, x >> y), deep=False) == \
Xor(True, And(Or(x, y), Implies(x, y)), remove_true=False)
assert to_anf(Nor(x ^ y, x & y), deep=False) == \
Xor(True, Or(Xor(x, y), And(x, y)), remove_true=False)
def test_to_nnf():
assert to_nnf(true) is true
assert to_nnf(false) is false
assert to_nnf(A) == A
assert to_nnf(A | ~A | B) is true
assert to_nnf(A & ~A & B) is false
assert to_nnf(A >> B) == ~A | B
assert to_nnf(Equivalent(A, B, C)) == (~A | B) & (~B | C) & (~C | A)
assert to_nnf(A ^ B ^ C) == \
(A | B | C) & (~A | ~B | C) & (A | ~B | ~C) & (~A | B | ~C)
assert to_nnf(ITE(A, B, C)) == (~A | B) & (A | C)
assert to_nnf(Not(A | B | C)) == ~A & ~B & ~C
assert to_nnf(Not(A & B & C)) == ~A | ~B | ~C
assert to_nnf(Not(A >> B)) == A & ~B
assert to_nnf(Not(Equivalent(A, B, C))) == And(Or(A, B, C), Or(~A, ~B, ~C))
assert to_nnf(Not(A ^ B ^ C)) == \
(~A | B | C) & (A | ~B | C) & (A | B | ~C) & (~A | ~B | ~C)
assert to_nnf(Not(ITE(A, B, C))) == (~A | ~B) & (A | ~C)
assert to_nnf((A >> B) ^ (B >> A)) == (A & ~B) | (~A & B)
assert to_nnf((A >> B) ^ (B >> A), False) == \
(~A | ~B | A | B) & ((A & ~B) | (~A & B))
assert ITE(A, 1, 0).to_nnf() == A
assert ITE(A, 0, 1).to_nnf() == ~A
# although ITE can hold non-Boolean, it will complain if
# an attempt is made to convert the ITE to Boolean nnf
raises(TypeError, lambda: ITE(A < 1, [1], B).to_nnf())
def test_to_cnf():
assert to_cnf(~(B | C)) == And(Not(B), Not(C))
assert to_cnf((A & B) | C) == And(Or(A, C), Or(B, C))
assert to_cnf(A >> B) == (~A) | B
assert to_cnf(A >> (B & C)) == (~A | B) & (~A | C)
assert to_cnf(A & (B | C) | ~A & (B | C), True) == B | C
assert to_cnf(A & B) == And(A, B)
assert to_cnf(Equivalent(A, B)) == And(Or(A, Not(B)), Or(B, Not(A)))
assert to_cnf(Equivalent(A, B & C)) == \
(~A | B) & (~A | C) & (~B | ~C | A)
assert to_cnf(Equivalent(A, B | C), True) == \
And(Or(Not(B), A), Or(Not(C), A), Or(B, C, Not(A)))
assert to_cnf(A + 1) == A + 1
def test_issue_18904():
x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15 = symbols('x1:16')
eq = (( x1 & x2 & x3 & x4 & x5 & x6 & x7 & x8 & x9 ) |
( x1 & x2 & x3 & x4 & x5 & x6 & x7 & x10 & x9 ) |
( x1 & x11 & x3 & x12 & x5 & x13 & x14 & x15 & x9 ))
assert is_cnf(to_cnf(eq))
raises(ValueError, lambda: to_cnf(eq, simplify=True))
for f, t in zip((And, Or), (to_cnf, to_dnf)):
eq = f(x1, x2, x3, x4, x5, x6, x7, x8, x9)
raises(ValueError, lambda: to_cnf(eq, simplify=True))
assert t(eq, simplify=True, force=True) == eq
def test_issue_9949():
assert is_cnf(to_cnf((b > -5) | (a > 2) & (a < 4)))
def test_to_CNF():
assert CNF.CNF_to_cnf(CNF.to_CNF(~(B | C))) == to_cnf(~(B | C))
assert CNF.CNF_to_cnf(CNF.to_CNF((A & B) | C)) == to_cnf((A & B) | C)
assert CNF.CNF_to_cnf(CNF.to_CNF(A >> B)) == to_cnf(A >> B)
assert CNF.CNF_to_cnf(CNF.to_CNF(A >> (B & C))) == to_cnf(A >> (B & C))
assert CNF.CNF_to_cnf(CNF.to_CNF(A & (B | C) | ~A & (B | C))) == to_cnf(A & (B | C) | ~A & (B | C))
assert CNF.CNF_to_cnf(CNF.to_CNF(A & B)) == to_cnf(A & B)
def test_to_dnf():
assert to_dnf(~(B | C)) == And(Not(B), Not(C))
assert to_dnf(A & (B | C)) == Or(And(A, B), And(A, C))
assert to_dnf(A >> B) == (~A) | B
assert to_dnf(A >> (B & C)) == (~A) | (B & C)
assert to_dnf(A | B) == A | B
assert to_dnf(Equivalent(A, B), True) == \
Or(And(A, B), And(Not(A), Not(B)))
assert to_dnf(Equivalent(A, B & C), True) == \
Or(And(A, B, C), And(Not(A), Not(B)), And(Not(A), Not(C)))
assert to_dnf(A + 1) == A + 1
def test_to_int_repr():
x, y, z = map(Boolean, symbols('x,y,z'))
def sorted_recursive(arg):
try:
return sorted(sorted_recursive(x) for x in arg)
except TypeError: # arg is not a sequence
return arg
assert sorted_recursive(to_int_repr([x | y, z | x], [x, y, z])) == \
sorted_recursive([[1, 2], [1, 3]])
assert sorted_recursive(to_int_repr([x | y, z | ~x], [x, y, z])) == \
sorted_recursive([[1, 2], [3, -1]])
def test_is_anf():
x, y = symbols('x,y')
assert is_anf(true) is True
assert is_anf(false) is True
assert is_anf(x) is True
assert is_anf(And(x, y)) is True
assert is_anf(Xor(x, y, And(x, y))) is True
assert is_anf(Xor(x, y, Or(x, y))) is False
assert is_anf(Xor(Not(x), y)) is False
def test_is_nnf():
assert is_nnf(true) is True
assert is_nnf(A) is True
assert is_nnf(~A) is True
assert is_nnf(A & B) is True
assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), False) is True
assert is_nnf((A | B) & (~A | ~B)) is True
assert is_nnf(Not(Or(A, B))) is False
assert is_nnf(A ^ B) is False
assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), True) is False
def test_is_cnf():
assert is_cnf(x) is True
assert is_cnf(x | y | z) is True
assert is_cnf(x & y & z) is True
assert is_cnf((x | y) & z) is True
assert is_cnf((x & y) | z) is False
assert is_cnf(~(x & y) | z) is False
def test_is_dnf():
assert is_dnf(x) is True
assert is_dnf(x | y | z) is True
assert is_dnf(x & y & z) is True
assert is_dnf((x & y) | z) is True
assert is_dnf((x | y) & z) is False
assert is_dnf(~(x | y) & z) is False
def test_ITE():
A, B, C = symbols('A:C')
assert ITE(True, False, True) is false
assert ITE(True, True, False) is true
assert ITE(False, True, False) is false
assert ITE(False, False, True) is true
assert isinstance(ITE(A, B, C), ITE)
A = True
assert ITE(A, B, C) == B
A = False
assert ITE(A, B, C) == C
B = True
assert ITE(And(A, B), B, C) == C
assert ITE(Or(A, False), And(B, True), False) is false
assert ITE(x, A, B) == Not(x)
assert ITE(x, B, A) == x
assert ITE(1, x, y) == x
assert ITE(0, x, y) == y
raises(TypeError, lambda: ITE(2, x, y))
raises(TypeError, lambda: ITE(1, [], y))
raises(TypeError, lambda: ITE(1, (), y))
raises(TypeError, lambda: ITE(1, y, []))
assert ITE(1, 1, 1) is S.true
assert isinstance(ITE(1, 1, 1, evaluate=False), ITE)
raises(TypeError, lambda: ITE(x > 1, y, x))
assert ITE(Eq(x, True), y, x) == ITE(x, y, x)
assert ITE(Eq(x, False), y, x) == ITE(~x, y, x)
assert ITE(Ne(x, True), y, x) == ITE(~x, y, x)
assert ITE(Ne(x, False), y, x) == ITE(x, y, x)
assert ITE(Eq(S. true, x), y, x) == ITE(x, y, x)
assert ITE(Eq(S.false, x), y, x) == ITE(~x, y, x)
assert ITE(Ne(S.true, x), y, x) == ITE(~x, y, x)
assert ITE(Ne(S.false, x), y, x) == ITE(x, y, x)
# 0 and 1 in the context are not treated as True/False
# so the equality must always be False since dissimilar
# objects cannot be equal
assert ITE(Eq(x, 0), y, x) == x
assert ITE(Eq(x, 1), y, x) == x
assert ITE(Ne(x, 0), y, x) == y
assert ITE(Ne(x, 1), y, x) == y
assert ITE(Eq(x, 0), y, z).subs(x, 0) == y
assert ITE(Eq(x, 0), y, z).subs(x, 1) == z
raises(ValueError, lambda: ITE(x > 1, y, x, z))
def test_is_literal():
assert is_literal(True) is True
assert is_literal(False) is True
assert is_literal(A) is True
assert is_literal(~A) is True
assert is_literal(Or(A, B)) is False
assert is_literal(Q.zero(A)) is True
assert is_literal(Not(Q.zero(A))) is True
assert is_literal(Or(A, B)) is False
assert is_literal(And(Q.zero(A), Q.zero(B))) is False
assert is_literal(x < 3)
assert not is_literal(x + y < 3)
def test_operators():
# Mostly test __and__, __rand__, and so on
assert True & A == A & True == A
assert False & A == A & False == False
assert A & B == And(A, B)
assert True | A == A | True == True
assert False | A == A | False == A
assert A | B == Or(A, B)
assert ~A == Not(A)
assert True >> A == A << True == A
assert False >> A == A << False == True
assert A >> True == True << A == True
assert A >> False == False << A == ~A
assert A >> B == B << A == Implies(A, B)
assert True ^ A == A ^ True == ~A
assert False ^ A == A ^ False == A
assert A ^ B == Xor(A, B)
def test_true_false():
assert true is S.true
assert false is S.false
assert true is not True
assert false is not False
assert true
assert not false
assert true == True
assert false == False
assert not (true == False)
assert not (false == True)
assert not (true == false)
assert hash(true) == hash(True)
assert hash(false) == hash(False)
assert len({true, True}) == len({false, False}) == 1
assert isinstance(true, BooleanAtom)
assert isinstance(false, BooleanAtom)
# We don't want to subclass from bool, because bool subclasses from
# int. But operators like &, |, ^, <<, >>, and ~ act differently on 0 and
# 1 then we want them to on true and false. See the docstrings of the
# various And, Or, etc. functions for examples.
assert not isinstance(true, bool)
assert not isinstance(false, bool)
# Note: using 'is' comparison is important here. We want these to return
# true and false, not True and False
assert Not(true) is false
assert Not(True) is false
assert Not(false) is true
assert Not(False) is true
assert ~true is false
assert ~false is true
for T, F in product((True, true), (False, false)):
assert And(T, F) is false
assert And(F, T) is false
assert And(F, F) is false
assert And(T, T) is true
assert And(T, x) == x
assert And(F, x) is false
if not (T is True and F is False):
assert T & F is false
assert F & T is false
if F is not False:
assert F & F is false
if T is not True:
assert T & T is true
assert Or(T, F) is true
assert Or(F, T) is true
assert Or(F, F) is false
assert Or(T, T) is true
assert Or(T, x) is true
assert Or(F, x) == x
if not (T is True and F is False):
assert T | F is true
assert F | T is true
if F is not False:
assert F | F is false
if T is not True:
assert T | T is true
assert Xor(T, F) is true
assert Xor(F, T) is true
assert Xor(F, F) is false
assert Xor(T, T) is false
assert Xor(T, x) == ~x
assert Xor(F, x) == x
if not (T is True and F is False):
assert T ^ F is true
assert F ^ T is true
if F is not False:
assert F ^ F is false
if T is not True:
assert T ^ T is false
assert Nand(T, F) is true
assert Nand(F, T) is true
assert Nand(F, F) is true
assert Nand(T, T) is false
assert Nand(T, x) == ~x
assert Nand(F, x) is true
assert Nor(T, F) is false
assert Nor(F, T) is false
assert Nor(F, F) is true
assert Nor(T, T) is false
assert Nor(T, x) is false
assert Nor(F, x) == ~x
assert Implies(T, F) is false
assert Implies(F, T) is true
assert Implies(F, F) is true
assert Implies(T, T) is true
assert Implies(T, x) == x
assert Implies(F, x) is true
assert Implies(x, T) is true
assert Implies(x, F) == ~x
if not (T is True and F is False):
assert T >> F is false
assert F << T is false
assert F >> T is true
assert T << F is true
if F is not False:
assert F >> F is true
assert F << F is true
if T is not True:
assert T >> T is true
assert T << T is true
assert Equivalent(T, F) is false
assert Equivalent(F, T) is false
assert Equivalent(F, F) is true
assert Equivalent(T, T) is true
assert Equivalent(T, x) == x
assert Equivalent(F, x) == ~x
assert Equivalent(x, T) == x
assert Equivalent(x, F) == ~x
assert ITE(T, T, T) is true
assert ITE(T, T, F) is true
assert ITE(T, F, T) is false
assert ITE(T, F, F) is false
assert ITE(F, T, T) is true
assert ITE(F, T, F) is false
assert ITE(F, F, T) is true
assert ITE(F, F, F) is false
assert all(i.simplify(1, 2) is i for i in (S.true, S.false))
def test_bool_as_set():
assert ITE(y <= 0, False, y >= 1).as_set() == Interval(1, oo)
assert And(x <= 2, x >= -2).as_set() == Interval(-2, 2)
assert Or(x >= 2, x <= -2).as_set() == Interval(-oo, -2) + Interval(2, oo)
assert Not(x > 2).as_set() == Interval(-oo, 2)
# issue 10240
assert Not(And(x > 2, x < 3)).as_set() == \
Union(Interval(-oo, 2), Interval(3, oo))
assert true.as_set() == S.UniversalSet
assert false.as_set() is S.EmptySet
assert x.as_set() == S.UniversalSet
assert And(Or(x < 1, x > 3), x < 2).as_set() == Interval.open(-oo, 1)
assert And(x < 1, sin(x) < 3).as_set() == (x < 1).as_set()
raises(NotImplementedError, lambda: (sin(x) < 1).as_set())
# watch for object morph in as_set
assert Eq(-1, cos(2*x)**2/sin(2*x)**2).as_set() is S.EmptySet
@XFAIL
def test_multivariate_bool_as_set():
x, y = symbols('x,y')
assert And(x >= 0, y >= 0).as_set() == Interval(0, oo)*Interval(0, oo)
assert Or(x >= 0, y >= 0).as_set() == S.Reals*S.Reals - \
Interval(-oo, 0, True, True)*Interval(-oo, 0, True, True)
def test_all_or_nothing():
x = symbols('x', extended_real=True)
args = x >= -oo, x <= oo
v = And(*args)
if v.func is And:
assert len(v.args) == len(args) - args.count(S.true)
else:
assert v == True
v = Or(*args)
if v.func is Or:
assert len(v.args) == 2
else:
assert v == True
def test_canonical_atoms():
assert true.canonical == true
assert false.canonical == false
def test_negated_atoms():
assert true.negated == false
assert false.negated == true
def test_issue_8777():
assert And(x > 2, x < oo).as_set() == Interval(2, oo, left_open=True)
assert And(x >= 1, x < oo).as_set() == Interval(1, oo)
assert (x < oo).as_set() == Interval(-oo, oo)
assert (x > -oo).as_set() == Interval(-oo, oo)
def test_issue_8975():
assert Or(And(-oo < x, x <= -2), And(2 <= x, x < oo)).as_set() == \
Interval(-oo, -2) + Interval(2, oo)
def test_term_to_integer():
assert term_to_integer([1, 0, 1, 0, 0, 1, 0]) == 82
assert term_to_integer('0010101000111001') == 10809
def test_issue_21971():
a, b, c, d = symbols('a b c d')
f = a & b & c | a & c
assert f.subs(a & c, d) == b & d | d
assert f.subs(a & b & c, d) == a & c | d
f = (a | b | c) & (a | c)
assert f.subs(a | c, d) == (b | d) & d
assert f.subs(a | b | c, d) == (a | c) & d
f = (a ^ b ^ c) & (a ^ c)
assert f.subs(a ^ c, d) == (b ^ d) & d
assert f.subs(a ^ b ^ c, d) == (a ^ c) & d
def test_truth_table():
assert list(truth_table(And(x, y), [x, y], input=False)) == \
[False, False, False, True]
assert list(truth_table(x | y, [x, y], input=False)) == \
[False, True, True, True]
assert list(truth_table(x >> y, [x, y], input=False)) == \
[True, True, False, True]
assert list(truth_table(And(x, y), [x, y])) == \
[([0, 0], False), ([0, 1], False), ([1, 0], False), ([1, 1], True)]
def test_issue_8571():
for t in (S.true, S.false):
raises(TypeError, lambda: +t)
raises(TypeError, lambda: -t)
raises(TypeError, lambda: abs(t))
# use int(bool(t)) to get 0 or 1
raises(TypeError, lambda: int(t))
for o in [S.Zero, S.One, x]:
for _ in range(2):
raises(TypeError, lambda: o + t)
raises(TypeError, lambda: o - t)
raises(TypeError, lambda: o % t)
raises(TypeError, lambda: o*t)
raises(TypeError, lambda: o/t)
raises(TypeError, lambda: o**t)
o, t = t, o # do again in reversed order
def test_expand_relational():
n = symbols('n', negative=True)
p, q = symbols('p q', positive=True)
r = ((n + q*(-n/q + 1))/(q*(-n/q + 1)) < 0)
assert r is not S.false
assert r.expand() is S.false
assert (q > 0).expand() is S.true
def test_issue_12717():
assert S.true.is_Atom == True
assert S.false.is_Atom == True
def test_as_Boolean():
nz = symbols('nz', nonzero=True)
assert all(as_Boolean(i) is S.true for i in (True, S.true, 1, nz))
z = symbols('z', zero=True)
assert all(as_Boolean(i) is S.false for i in (False, S.false, 0, z))
assert all(as_Boolean(i) == i for i in (x, x < 0))
for i in (2, S(2), x + 1, []):
raises(TypeError, lambda: as_Boolean(i))
def test_binary_symbols():
assert ITE(x < 1, y, z).binary_symbols == {y, z}
for f in (Eq, Ne):
assert f(x, 1).binary_symbols == set()
assert f(x, True).binary_symbols == {x}
assert f(x, False).binary_symbols == {x}
assert S.true.binary_symbols == set()
assert S.false.binary_symbols == set()
assert x.binary_symbols == {x}
assert And(x, Eq(y, False), Eq(z, 1)).binary_symbols == {x, y}
assert Q.prime(x).binary_symbols == set()
assert Q.lt(x, 1).binary_symbols == set()
assert Q.is_true(x).binary_symbols == {x}
assert Q.eq(x, True).binary_symbols == {x}
assert Q.prime(x).binary_symbols == set()
def test_BooleanFunction_diff():
assert And(x, y).diff(x) == Piecewise((0, Eq(y, False)), (1, True))
def test_issue_14700():
A, B, C, D, E, F, G, H = symbols('A B C D E F G H')
q = ((B & D & H & ~F) | (B & H & ~C & ~D) | (B & H & ~C & ~F) |
(B & H & ~D & ~G) | (B & H & ~F & ~G) | (C & G & ~B & ~D) |
(C & G & ~D & ~H) | (C & G & ~F & ~H) | (D & F & H & ~B) |
(D & F & ~G & ~H) | (B & D & F & ~C & ~H) | (D & E & F & ~B & ~C) |
(D & F & ~A & ~B & ~C) | (D & F & ~A & ~C & ~H) |
(A & B & D & F & ~E & ~H))
soldnf = ((B & D & H & ~F) | (D & F & H & ~B) | (B & H & ~C & ~D) |
(B & H & ~D & ~G) | (C & G & ~B & ~D) | (C & G & ~D & ~H) |
(C & G & ~F & ~H) | (D & F & ~G & ~H) | (D & E & F & ~C & ~H) |
(D & F & ~A & ~C & ~H) | (A & B & D & F & ~E & ~H))
solcnf = ((B | C | D) & (B | D | G) & (C | D | H) & (C | F | H) &
(D | G | H) & (F | G | H) & (B | F | ~D | ~H) &
(~B | ~D | ~F | ~H) & (D | ~B | ~C | ~G | ~H) &
(A | H | ~C | ~D | ~F | ~G) & (H | ~C | ~D | ~E | ~F | ~G) &
(B | E | H | ~A | ~D | ~F | ~G))
assert simplify_logic(q, "dnf") == soldnf
assert simplify_logic(q, "cnf") == solcnf
minterms = [[0, 1, 0, 0], [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1],
[0, 0, 1, 1], [1, 0, 1, 1]]
dontcares = [[1, 0, 0, 0], [1, 0, 0, 1], [1, 1, 0, 0], [1, 1, 0, 1]]
assert SOPform([w, x, y, z], minterms) == (x & ~w) | (y & z & ~x)
# Should not be more complicated with don't cares
assert SOPform([w, x, y, z], minterms, dontcares) == \
(x & ~w) | (y & z & ~x)
def test_relational_simplification():
w, x, y, z = symbols('w x y z', real=True)
d, e = symbols('d e', real=False)
# Test all combinations or sign and order
assert Or(x >= y, x < y).simplify() == S.true
assert Or(x >= y, y > x).simplify() == S.true
assert Or(x >= y, -x > -y).simplify() == S.true
assert Or(x >= y, -y < -x).simplify() == S.true
assert Or(-x <= -y, x < y).simplify() == S.true
assert Or(-x <= -y, -x > -y).simplify() == S.true
assert Or(-x <= -y, y > x).simplify() == S.true
assert Or(-x <= -y, -y < -x).simplify() == S.true
assert Or(y <= x, x < y).simplify() == S.true
assert Or(y <= x, y > x).simplify() == S.true
assert Or(y <= x, -x > -y).simplify() == S.true
assert Or(y <= x, -y < -x).simplify() == S.true
assert Or(-y >= -x, x < y).simplify() == S.true
assert Or(-y >= -x, y > x).simplify() == S.true
assert Or(-y >= -x, -x > -y).simplify() == S.true
assert Or(-y >= -x, -y < -x).simplify() == S.true
assert Or(x < y, x >= y).simplify() == S.true
assert Or(y > x, x >= y).simplify() == S.true
assert Or(-x > -y, x >= y).simplify() == S.true
assert Or(-y < -x, x >= y).simplify() == S.true
assert Or(x < y, -x <= -y).simplify() == S.true
assert Or(-x > -y, -x <= -y).simplify() == S.true
assert Or(y > x, -x <= -y).simplify() == S.true
assert Or(-y < -x, -x <= -y).simplify() == S.true
assert Or(x < y, y <= x).simplify() == S.true
assert Or(y > x, y <= x).simplify() == S.true
assert Or(-x > -y, y <= x).simplify() == S.true
assert Or(-y < -x, y <= x).simplify() == S.true
assert Or(x < y, -y >= -x).simplify() == S.true
assert Or(y > x, -y >= -x).simplify() == S.true
assert Or(-x > -y, -y >= -x).simplify() == S.true
assert Or(-y < -x, -y >= -x).simplify() == S.true
# Some other tests
assert Or(x >= y, w < z, x <= y).simplify() == S.true
assert And(x >= y, x < y).simplify() == S.false
assert Or(x >= y, Eq(y, x)).simplify() == (x >= y)
assert And(x >= y, Eq(y, x)).simplify() == Eq(x, y)
assert And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify() == \
(Eq(x, y) & (x >= 1) & (y >= 5) & (y > z))
assert Or(Eq(x, y), x >= y, w < y, z < y).simplify() == \
(x >= y) | (y > z) | (w < y)
assert And(Eq(x, y), x >= y, w < y, y >= z, z < y).simplify() == \
Eq(x, y) & (y > z) & (w < y)
# assert And(Eq(x, y), x >= y, w < y, y >= z, z < y).simplify(relational_minmax=True) == \
# And(Eq(x, y), y > Max(w, z))
# assert Or(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify(relational_minmax=True) == \
# (Eq(x, y) | (x >= 1) | (y > Min(2, z)))
assert And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify() == \
(Eq(x, y) & (x >= 1) & (y >= 5) & (y > z))
assert (Eq(x, y) & Eq(d, e) & (x >= y) & (d >= e)).simplify() == \
(Eq(x, y) & Eq(d, e) & (d >= e))
assert And(Eq(x, y), Eq(x, -y)).simplify() == And(Eq(x, 0), Eq(y, 0))
assert Xor(x >= y, x <= y).simplify() == Ne(x, y)
assert And(x > 1, x < -1, Eq(x, y)).simplify() == S.false
# From #16690
assert And(x >= y, Eq(y, 0)).simplify() == And(x >= 0, Eq(y, 0))
def test_issue_8373():
x = symbols('x', real=True)
assert Or(x < 1, x > -1).simplify() == S.true
assert Or(x < 1, x >= 1).simplify() == S.true
assert And(x < 1, x >= 1).simplify() == S.false
assert Or(x <= 1, x >= 1).simplify() == S.true
def test_issue_7950():
x = symbols('x', real=True)
assert And(Eq(x, 1), Eq(x, 2)).simplify() == S.false
@slow
def test_relational_simplification_numerically():
def test_simplification_numerically_function(original, simplified):
symb = original.free_symbols
n = len(symb)
valuelist = list(set(list(combinations(list(range(-(n-1), n))*n, n))))
for values in valuelist:
sublist = dict(zip(symb, values))
originalvalue = original.subs(sublist)
simplifiedvalue = simplified.subs(sublist)
assert originalvalue == simplifiedvalue, "Original: {}\nand"\
" simplified: {}\ndo not evaluate to the same value for {}"\
"".format(original, simplified, sublist)
w, x, y, z = symbols('w x y z', real=True)
d, e = symbols('d e', real=False)
expressions = (And(Eq(x, y), x >= y, w < y, y >= z, z < y),
And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y),
Or(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y),
And(x >= y, Eq(y, x)),
Or(And(Eq(x, y), x >= y, w < y, Or(y >= z, z < y)),
And(Eq(x, y), x >= 1, 2 < y, y >= -1, z < y)),
(Eq(x, y) & Eq(d, e) & (x >= y) & (d >= e)),
)
for expression in expressions:
test_simplification_numerically_function(expression,
expression.simplify())
def test_relational_simplification_patterns_numerically():
from sympy.core import Wild
from sympy.logic.boolalg import _simplify_patterns_and, \
_simplify_patterns_or, _simplify_patterns_xor
a = Wild('a')
b = Wild('b')
c = Wild('c')
symb = [a, b, c]
patternlists = [[And, _simplify_patterns_and()],
[Or, _simplify_patterns_or()],
[Xor, _simplify_patterns_xor()]]
valuelist = list(set(list(combinations(list(range(-2, 3))*3, 3))))
# Skip combinations of +/-2 and 0, except for all 0
valuelist = [v for v in valuelist if any([w % 2 for w in v]) or not any(v)]
for func, patternlist in patternlists:
for pattern in patternlist:
original = func(*pattern[0].args)
simplified = pattern[1]
for values in valuelist:
sublist = dict(zip(symb, values))
originalvalue = original.xreplace(sublist)
simplifiedvalue = simplified.xreplace(sublist)
assert originalvalue == simplifiedvalue, "Original: {}\nand"\
" simplified: {}\ndo not evaluate to the same value for"\
"{}".format(pattern[0], simplified, sublist)
def test_issue_16803():
n = symbols('n')
# No simplification done, but should not raise an exception
assert ((n > 3) | (n < 0) | ((n > 0) & (n < 3))).simplify() == \
(n > 3) | (n < 0) | ((n > 0) & (n < 3))
def test_issue_17530():
r = {x: oo, y: oo}
assert Or(x + y > 0, x - y < 0).subs(r)
assert not And(x + y < 0, x - y < 0).subs(r)
raises(TypeError, lambda: Or(x + y < 0, x - y < 0).subs(r))
raises(TypeError, lambda: And(x + y > 0, x - y < 0).subs(r))
raises(TypeError, lambda: And(x + y > 0, x - y < 0).subs(r))
def test_anf_coeffs():
assert anf_coeffs([1, 0]) == [1, 1]
assert anf_coeffs([0, 0, 0, 1]) == [0, 0, 0, 1]
assert anf_coeffs([0, 1, 1, 1]) == [0, 1, 1, 1]
assert anf_coeffs([1, 1, 1, 0]) == [1, 0, 0, 1]
assert anf_coeffs([1, 0, 0, 0]) == [1, 1, 1, 1]
assert anf_coeffs([1, 0, 0, 1]) == [1, 1, 1, 0]
assert anf_coeffs([1, 1, 0, 1]) == [1, 0, 1, 1]
def test_ANFform():
x, y = symbols('x,y')
assert ANFform([x], [1, 1]) == True
assert ANFform([x], [0, 0]) == False
assert ANFform([x], [1, 0]) == Xor(x, True, remove_true=False)
assert ANFform([x, y], [1, 1, 1, 0]) == \
Xor(True, And(x, y), remove_true=False)
def test_bool_minterm():
x, y = symbols('x,y')
assert bool_minterm(3, [x, y]) == And(x, y)
assert bool_minterm([1, 0], [x, y]) == And(Not(y), x)
def test_bool_maxterm():
x, y = symbols('x,y')
assert bool_maxterm(2, [x, y]) == Or(Not(x), y)
assert bool_maxterm([0, 1], [x, y]) == Or(Not(y), x)
def test_bool_monomial():
x, y = symbols('x,y')
assert bool_monomial(1, [x, y]) == y
assert bool_monomial([1, 1], [x, y]) == And(x, y)
def test_check_pair():
assert _check_pair([0, 1, 0], [0, 1, 1]) == 2
assert _check_pair([0, 1, 0], [1, 1, 1]) == -1
def test_issue_19114():
expr = (B & C) | (A & ~C) | (~A & ~B)
# Expression is minimal, but there are multiple minimal forms possible
res1 = (A & B) | (C & ~A) | (~B & ~C)
result = to_dnf(expr, simplify=True)
assert result in (expr, res1)
def test_issue_20870():
result = SOPform([a, b, c, d], [1, 2, 3, 4, 5, 6, 8, 9, 11, 12, 14, 15])
expected = ((d & ~b) | (a & b & c) | (a & ~c & ~d) |
(b & ~a & ~c) | (c & ~a & ~d))
assert result == expected
def test_convert_to_varsSOP():
assert _convert_to_varsSOP([0, 1, 0], [x, y, z]) == And(Not(x), y, Not(z))
assert _convert_to_varsSOP([3, 1, 0], [x, y, z]) == And(y, Not(z))
def test_convert_to_varsPOS():
assert _convert_to_varsPOS([0, 1, 0], [x, y, z]) == Or(x, Not(y), z)
assert _convert_to_varsPOS([3, 1, 0], [x, y, z]) == Or(Not(y), z)
def test_refine():
# relational
assert not refine(x < 0, ~(x < 0))
assert refine(x < 0, (x < 0))
assert refine(x < 0, (0 > x)) is S.true
assert refine(x < 0, (y < 0)) == (x < 0)
assert not refine(x <= 0, ~(x <= 0))
assert refine(x <= 0, (x <= 0))
assert refine(x <= 0, (0 >= x)) is S.true
assert refine(x <= 0, (y <= 0)) == (x <= 0)
assert not refine(x > 0, ~(x > 0))
assert refine(x > 0, (x > 0))
assert refine(x > 0, (0 < x)) is S.true
assert refine(x > 0, (y > 0)) == (x > 0)
assert not refine(x >= 0, ~(x >= 0))
assert refine(x >= 0, (x >= 0))
assert refine(x >= 0, (0 <= x)) is S.true
assert refine(x >= 0, (y >= 0)) == (x >= 0)
assert not refine(Eq(x, 0), ~(Eq(x, 0)))
assert refine(Eq(x, 0), (Eq(x, 0)))
assert refine(Eq(x, 0), (Eq(0, x))) is S.true
assert refine(Eq(x, 0), (Eq(y, 0))) == Eq(x, 0)
assert not refine(Ne(x, 0), ~(Ne(x, 0)))
assert refine(Ne(x, 0), (Ne(0, x))) is S.true
assert refine(Ne(x, 0), (Ne(x, 0)))
assert refine(Ne(x, 0), (Ne(y, 0))) == (Ne(x, 0))
# boolean functions
assert refine(And(x > 0, y > 0), (x > 0)) == (y > 0)
assert refine(And(x > 0, y > 0), (x > 0) & (y > 0)) is S.true
# predicates
assert refine(Q.positive(x), Q.positive(x)) is S.true
assert refine(Q.positive(x), Q.negative(x)) is S.false
assert refine(Q.positive(x), Q.real(x)) == Q.positive(x)
def test_relational_threeterm_simplification_patterns_numerically():
from sympy.core import Wild
from sympy.logic.boolalg import _simplify_patterns_and3
a = Wild('a')
b = Wild('b')
c = Wild('c')
symb = [a, b, c]
patternlists = [[And, _simplify_patterns_and3()]]
valuelist = list(set(list(combinations(list(range(-2, 3))*3, 3))))
# Skip combinations of +/-2 and 0, except for all 0
valuelist = [v for v in valuelist if any([w % 2 for w in v]) or not any(v)]
for func, patternlist in patternlists:
for pattern in patternlist:
original = func(*pattern[0].args)
simplified = pattern[1]
for values in valuelist:
sublist = dict(zip(symb, values))
originalvalue = original.xreplace(sublist)
simplifiedvalue = simplified.xreplace(sublist)
assert originalvalue == simplifiedvalue, "Original: {}\nand"\
" simplified: {}\ndo not evaluate to the same value for"\
"{}".format(pattern[0], simplified, sublist)
|
8e5725ea24bc8993d632b35d6cd4f749c72fa202c0bf2de1ec3e0bf4eddac3f5 | from sympy.assumptions import Q
from sympy.core.expr import Expr
from sympy.core.add import Add
from sympy.core.function import Function
from sympy.core.kind import NumberKind, UndefinedKind
from sympy.core.numbers import I, Integer, oo, pi, Rational
from sympy.core.singleton import S
from sympy.core.symbol import Symbol, symbols
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.matrices.common import (ShapeError, NonSquareMatrixError,
_MinimalMatrix, _CastableMatrix, MatrixShaping, MatrixProperties,
MatrixOperations, MatrixArithmetic, MatrixSpecial, MatrixKind)
from sympy.matrices.matrices import MatrixCalculus
from sympy.matrices import (Matrix, diag, eye,
matrix_multiply_elementwise, ones, zeros, SparseMatrix, banded,
MutableDenseMatrix, MutableSparseMatrix, ImmutableDenseMatrix,
ImmutableSparseMatrix)
from sympy.polys.polytools import Poly
from sympy.utilities.iterables import flatten
from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray as Array
from sympy.abc import x, y, z
# classes to test the basic matrix classes
class ShapingOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixShaping):
pass
def eye_Shaping(n):
return ShapingOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Shaping(n):
return ShapingOnlyMatrix(n, n, lambda i, j: 0)
class PropertiesOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixProperties):
pass
def eye_Properties(n):
return PropertiesOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Properties(n):
return PropertiesOnlyMatrix(n, n, lambda i, j: 0)
class OperationsOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixOperations):
pass
def eye_Operations(n):
return OperationsOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Operations(n):
return OperationsOnlyMatrix(n, n, lambda i, j: 0)
class ArithmeticOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixArithmetic):
pass
def eye_Arithmetic(n):
return ArithmeticOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Arithmetic(n):
return ArithmeticOnlyMatrix(n, n, lambda i, j: 0)
class SpecialOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixSpecial):
pass
class CalculusOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixCalculus):
pass
def test__MinimalMatrix():
x = _MinimalMatrix(2, 3, [1, 2, 3, 4, 5, 6])
assert x.rows == 2
assert x.cols == 3
assert x[2] == 3
assert x[1, 1] == 5
assert list(x) == [1, 2, 3, 4, 5, 6]
assert list(x[1, :]) == [4, 5, 6]
assert list(x[:, 1]) == [2, 5]
assert list(x[:, :]) == list(x)
assert x[:, :] == x
assert _MinimalMatrix(x) == x
assert _MinimalMatrix([[1, 2, 3], [4, 5, 6]]) == x
assert _MinimalMatrix(([1, 2, 3], [4, 5, 6])) == x
assert _MinimalMatrix([(1, 2, 3), (4, 5, 6)]) == x
assert _MinimalMatrix(((1, 2, 3), (4, 5, 6))) == x
assert not (_MinimalMatrix([[1, 2], [3, 4], [5, 6]]) == x)
def test_kind():
assert Matrix([[1, 2], [3, 4]]).kind == MatrixKind(NumberKind)
assert Matrix([[0, 0], [0, 0]]).kind == MatrixKind(NumberKind)
assert Matrix(0, 0, []).kind == MatrixKind(NumberKind)
assert Matrix([[x]]).kind == MatrixKind(NumberKind)
assert Matrix([[1, Matrix([[1]])]]).kind == MatrixKind(UndefinedKind)
assert SparseMatrix([[1]]).kind == MatrixKind(NumberKind)
assert SparseMatrix([[1, Matrix([[1]])]]).kind == MatrixKind(UndefinedKind)
# ShapingOnlyMatrix tests
def test_vec():
m = ShapingOnlyMatrix(2, 2, [1, 3, 2, 4])
m_vec = m.vec()
assert m_vec.cols == 1
for i in range(4):
assert m_vec[i] == i + 1
def test_todok():
a, b, c, d = symbols('a:d')
m1 = MutableDenseMatrix([[a, b], [c, d]])
m2 = ImmutableDenseMatrix([[a, b], [c, d]])
m3 = MutableSparseMatrix([[a, b], [c, d]])
m4 = ImmutableSparseMatrix([[a, b], [c, d]])
assert m1.todok() == m2.todok() == m3.todok() == m4.todok() == \
{(0, 0): a, (0, 1): b, (1, 0): c, (1, 1): d}
def test_tolist():
lst = [[S.One, S.Half, x*y, S.Zero], [x, y, z, x**2], [y, -S.One, z*x, 3]]
flat_lst = [S.One, S.Half, x*y, S.Zero, x, y, z, x**2, y, -S.One, z*x, 3]
m = ShapingOnlyMatrix(3, 4, flat_lst)
assert m.tolist() == lst
def test_todod():
m = ShapingOnlyMatrix(3, 2, [[S.One, 0], [0, S.Half], [x, 0]])
dict = {0: {0: S.One}, 1: {1: S.Half}, 2: {0: x}}
assert m.todod() == dict
def test_row_col_del():
e = ShapingOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
raises(IndexError, lambda: e.row_del(5))
raises(IndexError, lambda: e.row_del(-5))
raises(IndexError, lambda: e.col_del(5))
raises(IndexError, lambda: e.col_del(-5))
assert e.row_del(2) == e.row_del(-1) == Matrix([[1, 2, 3], [4, 5, 6]])
assert e.col_del(2) == e.col_del(-1) == Matrix([[1, 2], [4, 5], [7, 8]])
assert e.row_del(1) == e.row_del(-2) == Matrix([[1, 2, 3], [7, 8, 9]])
assert e.col_del(1) == e.col_del(-2) == Matrix([[1, 3], [4, 6], [7, 9]])
def test_get_diag_blocks1():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert a.get_diag_blocks() == [a]
assert b.get_diag_blocks() == [b]
assert c.get_diag_blocks() == [c]
def test_get_diag_blocks2():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
A, B, C, D = diag(a, b, b), diag(a, b, c), diag(a, c, b), diag(c, c, b)
A = ShapingOnlyMatrix(A.rows, A.cols, A)
B = ShapingOnlyMatrix(B.rows, B.cols, B)
C = ShapingOnlyMatrix(C.rows, C.cols, C)
D = ShapingOnlyMatrix(D.rows, D.cols, D)
assert A.get_diag_blocks() == [a, b, b]
assert B.get_diag_blocks() == [a, b, c]
assert C.get_diag_blocks() == [a, c, b]
assert D.get_diag_blocks() == [c, c, b]
def test_shape():
m = ShapingOnlyMatrix(1, 2, [0, 0])
assert m.shape == (1, 2)
def test_reshape():
m0 = eye_Shaping(3)
assert m0.reshape(1, 9) == Matrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
m1 = ShapingOnlyMatrix(3, 4, lambda i, j: i + j)
assert m1.reshape(
4, 3) == Matrix(((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)))
assert m1.reshape(2, 6) == Matrix(((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)))
def test_row_col():
m = ShapingOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
assert m.row(0) == Matrix(1, 3, [1, 2, 3])
assert m.col(0) == Matrix(3, 1, [1, 4, 7])
def test_row_join():
assert eye_Shaping(3).row_join(Matrix([7, 7, 7])) == \
Matrix([[1, 0, 0, 7],
[0, 1, 0, 7],
[0, 0, 1, 7]])
def test_col_join():
assert eye_Shaping(3).col_join(Matrix([[7, 7, 7]])) == \
Matrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[7, 7, 7]])
def test_row_insert():
r4 = Matrix([[4, 4, 4]])
for i in range(-4, 5):
l = [1, 0, 0]
l.insert(i, 4)
assert flatten(eye_Shaping(3).row_insert(i, r4).col(0).tolist()) == l
def test_col_insert():
c4 = Matrix([4, 4, 4])
for i in range(-4, 5):
l = [0, 0, 0]
l.insert(i, 4)
assert flatten(zeros_Shaping(3).col_insert(i, c4).row(0).tolist()) == l
# issue 13643
assert eye_Shaping(6).col_insert(3, Matrix([[2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2]])) == \
Matrix([[1, 0, 0, 2, 2, 0, 0, 0],
[0, 1, 0, 2, 2, 0, 0, 0],
[0, 0, 1, 2, 2, 0, 0, 0],
[0, 0, 0, 2, 2, 1, 0, 0],
[0, 0, 0, 2, 2, 0, 1, 0],
[0, 0, 0, 2, 2, 0, 0, 1]])
def test_extract():
m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)
assert m.extract([0, 1, 3], [0, 1]) == Matrix(3, 2, [0, 1, 3, 4, 9, 10])
assert m.extract([0, 3], [0, 0, 2]) == Matrix(2, 3, [0, 0, 2, 9, 9, 11])
assert m.extract(range(4), range(3)) == m
raises(IndexError, lambda: m.extract([4], [0]))
raises(IndexError, lambda: m.extract([0], [3]))
def test_hstack():
m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)
m2 = ShapingOnlyMatrix(3, 4, lambda i, j: i*3 + j)
assert m == m.hstack(m)
assert m.hstack(m, m, m) == ShapingOnlyMatrix.hstack(m, m, m) == Matrix([
[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[6, 7, 8, 6, 7, 8, 6, 7, 8],
[9, 10, 11, 9, 10, 11, 9, 10, 11]])
raises(ShapeError, lambda: m.hstack(m, m2))
assert Matrix.hstack() == Matrix()
# test regression #12938
M1 = Matrix.zeros(0, 0)
M2 = Matrix.zeros(0, 1)
M3 = Matrix.zeros(0, 2)
M4 = Matrix.zeros(0, 3)
m = ShapingOnlyMatrix.hstack(M1, M2, M3, M4)
assert m.rows == 0 and m.cols == 6
def test_vstack():
m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)
m2 = ShapingOnlyMatrix(3, 4, lambda i, j: i*3 + j)
assert m == m.vstack(m)
assert m.vstack(m, m, m) == ShapingOnlyMatrix.vstack(m, m, m) == Matrix([
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11],
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11],
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11]])
raises(ShapeError, lambda: m.vstack(m, m2))
assert Matrix.vstack() == Matrix()
# PropertiesOnlyMatrix tests
def test_atoms():
m = PropertiesOnlyMatrix(2, 2, [1, 2, x, 1 - 1/x])
assert m.atoms() == {S.One, S(2), S.NegativeOne, x}
assert m.atoms(Symbol) == {x}
def test_free_symbols():
assert PropertiesOnlyMatrix([[x], [0]]).free_symbols == {x}
def test_has():
A = PropertiesOnlyMatrix(((x, y), (2, 3)))
assert A.has(x)
assert not A.has(z)
assert A.has(Symbol)
A = PropertiesOnlyMatrix(((2, y), (2, 3)))
assert not A.has(x)
def test_is_anti_symmetric():
x = symbols('x')
assert PropertiesOnlyMatrix(2, 1, [1, 2]).is_anti_symmetric() is False
m = PropertiesOnlyMatrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0])
assert m.is_anti_symmetric() is True
assert m.is_anti_symmetric(simplify=False) is False
assert m.is_anti_symmetric(simplify=lambda x: x) is False
m = PropertiesOnlyMatrix(3, 3, [x.expand() for x in m])
assert m.is_anti_symmetric(simplify=False) is True
m = PropertiesOnlyMatrix(3, 3, [x.expand() for x in [S.One] + list(m)[1:]])
assert m.is_anti_symmetric() is False
def test_diagonal_symmetrical():
m = PropertiesOnlyMatrix(2, 2, [0, 1, 1, 0])
assert not m.is_diagonal()
assert m.is_symmetric()
assert m.is_symmetric(simplify=False)
m = PropertiesOnlyMatrix(2, 2, [1, 0, 0, 1])
assert m.is_diagonal()
m = PropertiesOnlyMatrix(3, 3, diag(1, 2, 3))
assert m.is_diagonal()
assert m.is_symmetric()
m = PropertiesOnlyMatrix(3, 3, [1, 0, 0, 0, 2, 0, 0, 0, 3])
assert m == diag(1, 2, 3)
m = PropertiesOnlyMatrix(2, 3, zeros(2, 3))
assert not m.is_symmetric()
assert m.is_diagonal()
m = PropertiesOnlyMatrix(((5, 0), (0, 6), (0, 0)))
assert m.is_diagonal()
m = PropertiesOnlyMatrix(((5, 0, 0), (0, 6, 0)))
assert m.is_diagonal()
m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3])
assert m.is_symmetric()
assert not m.is_symmetric(simplify=False)
assert m.expand().is_symmetric(simplify=False)
def test_is_hermitian():
a = PropertiesOnlyMatrix([[1, I], [-I, 1]])
assert a.is_hermitian
a = PropertiesOnlyMatrix([[2*I, I], [-I, 1]])
assert a.is_hermitian is False
a = PropertiesOnlyMatrix([[x, I], [-I, 1]])
assert a.is_hermitian is None
a = PropertiesOnlyMatrix([[x, 1], [-I, 1]])
assert a.is_hermitian is False
def test_is_Identity():
assert eye_Properties(3).is_Identity
assert not PropertiesOnlyMatrix(zeros(3)).is_Identity
assert not PropertiesOnlyMatrix(ones(3)).is_Identity
# issue 6242
assert not PropertiesOnlyMatrix([[1, 0, 0]]).is_Identity
def test_is_symbolic():
a = PropertiesOnlyMatrix([[x, x], [x, x]])
assert a.is_symbolic() is True
a = PropertiesOnlyMatrix([[1, 2, 3, 4], [5, 6, 7, 8]])
assert a.is_symbolic() is False
a = PropertiesOnlyMatrix([[1, 2, 3, 4], [5, 6, x, 8]])
assert a.is_symbolic() is True
a = PropertiesOnlyMatrix([[1, x, 3]])
assert a.is_symbolic() is True
a = PropertiesOnlyMatrix([[1, 2, 3]])
assert a.is_symbolic() is False
a = PropertiesOnlyMatrix([[1], [x], [3]])
assert a.is_symbolic() is True
a = PropertiesOnlyMatrix([[1], [2], [3]])
assert a.is_symbolic() is False
def test_is_upper():
a = PropertiesOnlyMatrix([[1, 2, 3]])
assert a.is_upper is True
a = PropertiesOnlyMatrix([[1], [2], [3]])
assert a.is_upper is False
def test_is_lower():
a = PropertiesOnlyMatrix([[1, 2, 3]])
assert a.is_lower is False
a = PropertiesOnlyMatrix([[1], [2], [3]])
assert a.is_lower is True
def test_is_square():
m = PropertiesOnlyMatrix([[1], [1]])
m2 = PropertiesOnlyMatrix([[2, 2], [2, 2]])
assert not m.is_square
assert m2.is_square
def test_is_symmetric():
m = PropertiesOnlyMatrix(2, 2, [0, 1, 1, 0])
assert m.is_symmetric()
m = PropertiesOnlyMatrix(2, 2, [0, 1, 0, 1])
assert not m.is_symmetric()
def test_is_hessenberg():
A = PropertiesOnlyMatrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]])
assert A.is_upper_hessenberg
A = PropertiesOnlyMatrix(3, 3, [3, 2, 0, 4, 4, 1, 1, 5, 2])
assert A.is_lower_hessenberg
A = PropertiesOnlyMatrix(3, 3, [3, 2, -1, 4, 4, 1, 1, 5, 2])
assert A.is_lower_hessenberg is False
assert A.is_upper_hessenberg is False
A = PropertiesOnlyMatrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]])
assert not A.is_upper_hessenberg
def test_is_zero():
assert PropertiesOnlyMatrix(0, 0, []).is_zero_matrix
assert PropertiesOnlyMatrix([[0, 0], [0, 0]]).is_zero_matrix
assert PropertiesOnlyMatrix(zeros(3, 4)).is_zero_matrix
assert not PropertiesOnlyMatrix(eye(3)).is_zero_matrix
assert PropertiesOnlyMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert PropertiesOnlyMatrix([[x, 1], [0, 0]]).is_zero_matrix == False
a = Symbol('a', nonzero=True)
assert PropertiesOnlyMatrix([[a, 0], [0, 0]]).is_zero_matrix == False
def test_values():
assert set(PropertiesOnlyMatrix(2, 2, [0, 1, 2, 3]
).values()) == {1, 2, 3}
x = Symbol('x', real=True)
assert set(PropertiesOnlyMatrix(2, 2, [x, 0, 0, 1]
).values()) == {x, 1}
# OperationsOnlyMatrix tests
def test_applyfunc():
m0 = OperationsOnlyMatrix(eye(3))
assert m0.applyfunc(lambda x: 2*x) == eye(3)*2
assert m0.applyfunc(lambda x: 0) == zeros(3)
assert m0.applyfunc(lambda x: 1) == ones(3)
def test_adjoint():
dat = [[0, I], [1, 0]]
ans = OperationsOnlyMatrix([[0, 1], [-I, 0]])
assert ans.adjoint() == Matrix(dat)
def test_as_real_imag():
m1 = OperationsOnlyMatrix(2, 2, [1, 2, 3, 4])
m3 = OperationsOnlyMatrix(2, 2,
[1 + S.ImaginaryUnit, 2 + 2*S.ImaginaryUnit,
3 + 3*S.ImaginaryUnit, 4 + 4*S.ImaginaryUnit])
a, b = m3.as_real_imag()
assert a == m1
assert b == m1
def test_conjugate():
M = OperationsOnlyMatrix([[0, I, 5],
[1, 2, 0]])
assert M.T == Matrix([[0, 1],
[I, 2],
[5, 0]])
assert M.C == Matrix([[0, -I, 5],
[1, 2, 0]])
assert M.C == M.conjugate()
assert M.H == M.T.C
assert M.H == Matrix([[ 0, 1],
[-I, 2],
[ 5, 0]])
def test_doit():
a = OperationsOnlyMatrix([[Add(x, x, evaluate=False)]])
assert a[0] != 2*x
assert a.doit() == Matrix([[2*x]])
def test_evalf():
a = OperationsOnlyMatrix(2, 1, [sqrt(5), 6])
assert all(a.evalf()[i] == a[i].evalf() for i in range(2))
assert all(a.evalf(2)[i] == a[i].evalf(2) for i in range(2))
assert all(a.n(2)[i] == a[i].n(2) for i in range(2))
def test_expand():
m0 = OperationsOnlyMatrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]])
# Test if expand() returns a matrix
m1 = m0.expand()
assert m1 == Matrix(
[[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]])
a = Symbol('a', real=True)
assert OperationsOnlyMatrix(1, 1, [exp(I*a)]).expand(complex=True) == \
Matrix([cos(a) + I*sin(a)])
def test_refine():
m0 = OperationsOnlyMatrix([[Abs(x)**2, sqrt(x**2)],
[sqrt(x**2)*Abs(y)**2, sqrt(y**2)*Abs(x)**2]])
m1 = m0.refine(Q.real(x) & Q.real(y))
assert m1 == Matrix([[x**2, Abs(x)], [y**2*Abs(x), x**2*Abs(y)]])
m1 = m0.refine(Q.positive(x) & Q.positive(y))
assert m1 == Matrix([[x**2, x], [x*y**2, x**2*y]])
m1 = m0.refine(Q.negative(x) & Q.negative(y))
assert m1 == Matrix([[x**2, -x], [-x*y**2, -x**2*y]])
def test_replace():
F, G = symbols('F, G', cls=Function)
K = OperationsOnlyMatrix(2, 2, lambda i, j: G(i+j))
M = OperationsOnlyMatrix(2, 2, lambda i, j: F(i+j))
N = M.replace(F, G)
assert N == K
def test_replace_map():
F, G = symbols('F, G', cls=Function)
K = OperationsOnlyMatrix(2, 2, [(G(0), {F(0): G(0)}), (G(1), {F(1): G(1)}), (G(1), {F(1) \
: G(1)}), (G(2), {F(2): G(2)})])
M = OperationsOnlyMatrix(2, 2, lambda i, j: F(i+j))
N = M.replace(F, G, True)
assert N == K
def test_rot90():
A = Matrix([[1, 2], [3, 4]])
assert A == A.rot90(0) == A.rot90(4)
assert A.rot90(2) == A.rot90(-2) == A.rot90(6) == Matrix(((4, 3), (2, 1)))
assert A.rot90(3) == A.rot90(-1) == A.rot90(7) == Matrix(((2, 4), (1, 3)))
assert A.rot90() == A.rot90(-7) == A.rot90(-3) == Matrix(((3, 1), (4, 2)))
def test_simplify():
n = Symbol('n')
f = Function('f')
M = OperationsOnlyMatrix([[ 1/x + 1/y, (x + x*y) / x ],
[ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]])
assert M.simplify() == Matrix([[ (x + y)/(x * y), 1 + y ],
[ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]])
eq = (1 + x)**2
M = OperationsOnlyMatrix([[eq]])
assert M.simplify() == Matrix([[eq]])
assert M.simplify(ratio=oo) == Matrix([[eq.simplify(ratio=oo)]])
# https://github.com/sympy/sympy/issues/19353
m = Matrix([[30, 2], [3, 4]])
assert (1/(m.trace())).simplify() == Rational(1, 34)
def test_subs():
assert OperationsOnlyMatrix([[1, x], [x, 4]]).subs(x, 5) == Matrix([[1, 5], [5, 4]])
assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs([[x, -1], [y, -2]]) == \
Matrix([[-1, 2], [-3, 4]])
assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs([(x, -1), (y, -2)]) == \
Matrix([[-1, 2], [-3, 4]])
assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
assert OperationsOnlyMatrix([[x*y]]).subs({x: y - 1, y: x - 1}, simultaneous=True) == \
Matrix([[(x - 1)*(y - 1)]])
def test_trace():
M = OperationsOnlyMatrix([[1, 0, 0],
[0, 5, 0],
[0, 0, 8]])
assert M.trace() == 14
def test_xreplace():
assert OperationsOnlyMatrix([[1, x], [x, 4]]).xreplace({x: 5}) == \
Matrix([[1, 5], [5, 4]])
assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).xreplace({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
def test_permute():
a = OperationsOnlyMatrix(3, 4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
raises(IndexError, lambda: a.permute([[0, 5]]))
raises(ValueError, lambda: a.permute(Symbol('x')))
b = a.permute_rows([[0, 2], [0, 1]])
assert a.permute([[0, 2], [0, 1]]) == b == Matrix([
[5, 6, 7, 8],
[9, 10, 11, 12],
[1, 2, 3, 4]])
b = a.permute_cols([[0, 2], [0, 1]])
assert a.permute([[0, 2], [0, 1]], orientation='cols') == b ==\
Matrix([
[ 2, 3, 1, 4],
[ 6, 7, 5, 8],
[10, 11, 9, 12]])
b = a.permute_cols([[0, 2], [0, 1]], direction='backward')
assert a.permute([[0, 2], [0, 1]], orientation='cols', direction='backward') == b ==\
Matrix([
[ 3, 1, 2, 4],
[ 7, 5, 6, 8],
[11, 9, 10, 12]])
assert a.permute([1, 2, 0, 3]) == Matrix([
[5, 6, 7, 8],
[9, 10, 11, 12],
[1, 2, 3, 4]])
from sympy.combinatorics import Permutation
assert a.permute(Permutation([1, 2, 0, 3])) == Matrix([
[5, 6, 7, 8],
[9, 10, 11, 12],
[1, 2, 3, 4]])
def test_upper_triangular():
A = OperationsOnlyMatrix([
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]
])
R = A.upper_triangular(2)
assert R == OperationsOnlyMatrix([
[0, 0, 1, 1],
[0, 0, 0, 1],
[0, 0, 0, 0],
[0, 0, 0, 0]
])
R = A.upper_triangular(-2)
assert R == OperationsOnlyMatrix([
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[0, 1, 1, 1]
])
R = A.upper_triangular()
assert R == OperationsOnlyMatrix([
[1, 1, 1, 1],
[0, 1, 1, 1],
[0, 0, 1, 1],
[0, 0, 0, 1]
])
def test_lower_triangular():
A = OperationsOnlyMatrix([
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]
])
L = A.lower_triangular()
assert L == ArithmeticOnlyMatrix([
[1, 0, 0, 0],
[1, 1, 0, 0],
[1, 1, 1, 0],
[1, 1, 1, 1]])
L = A.lower_triangular(2)
assert L == ArithmeticOnlyMatrix([
[1, 1, 1, 0],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]
])
L = A.lower_triangular(-2)
assert L == ArithmeticOnlyMatrix([
[0, 0, 0, 0],
[0, 0, 0, 0],
[1, 0, 0, 0],
[1, 1, 0, 0]
])
# ArithmeticOnlyMatrix tests
def test_abs():
m = ArithmeticOnlyMatrix([[1, -2], [x, y]])
assert abs(m) == ArithmeticOnlyMatrix([[1, 2], [Abs(x), Abs(y)]])
def test_add():
m = ArithmeticOnlyMatrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
assert m + m == ArithmeticOnlyMatrix([[2, 4, 6], [2*x, 2*y, 2*x], [4*y, -100, 2*z*x]])
n = ArithmeticOnlyMatrix(1, 2, [1, 2])
raises(ShapeError, lambda: m + n)
def test_multiplication():
a = ArithmeticOnlyMatrix((
(1, 2),
(3, 1),
(0, 6),
))
b = ArithmeticOnlyMatrix((
(1, 2),
(3, 0),
))
raises(ShapeError, lambda: b*a)
raises(TypeError, lambda: a*{})
c = a*b
assert c[0, 0] == 7
assert c[0, 1] == 2
assert c[1, 0] == 6
assert c[1, 1] == 6
assert c[2, 0] == 18
assert c[2, 1] == 0
try:
eval('c = a @ b')
except SyntaxError:
pass
else:
assert c[0, 0] == 7
assert c[0, 1] == 2
assert c[1, 0] == 6
assert c[1, 1] == 6
assert c[2, 0] == 18
assert c[2, 1] == 0
h = a.multiply_elementwise(c)
assert h == matrix_multiply_elementwise(a, c)
assert h[0, 0] == 7
assert h[0, 1] == 4
assert h[1, 0] == 18
assert h[1, 1] == 6
assert h[2, 0] == 0
assert h[2, 1] == 0
raises(ShapeError, lambda: a.multiply_elementwise(b))
c = b * Symbol("x")
assert isinstance(c, ArithmeticOnlyMatrix)
assert c[0, 0] == x
assert c[0, 1] == 2*x
assert c[1, 0] == 3*x
assert c[1, 1] == 0
c2 = x * b
assert c == c2
c = 5 * b
assert isinstance(c, ArithmeticOnlyMatrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
try:
eval('c = 5 @ b')
except SyntaxError:
pass
else:
assert isinstance(c, ArithmeticOnlyMatrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
# https://github.com/sympy/sympy/issues/22353
A = Matrix(ones(3, 1))
_h = -Rational(1, 2)
B = Matrix([_h, _h, _h])
assert A.multiply_elementwise(B) == Matrix([
[_h],
[_h],
[_h]])
def test_matmul():
a = Matrix([[1, 2], [3, 4]])
assert a.__matmul__(2) == NotImplemented
assert a.__rmatmul__(2) == NotImplemented
#This is done this way because @ is only supported in Python 3.5+
#To check 2@a case
try:
eval('2 @ a')
except SyntaxError:
pass
except TypeError: #TypeError is raised in case of NotImplemented is returned
pass
#Check a@2 case
try:
eval('a @ 2')
except SyntaxError:
pass
except TypeError: #TypeError is raised in case of NotImplemented is returned
pass
def test_non_matmul():
"""
Test that if explicitly specified as non-matrix, mul reverts
to scalar multiplication.
"""
class foo(Expr):
is_Matrix=False
is_MatrixLike=False
shape = (1, 1)
A = Matrix([[1, 2], [3, 4]])
b = foo()
assert b*A == Matrix([[b, 2*b], [3*b, 4*b]])
assert A*b == Matrix([[b, 2*b], [3*b, 4*b]])
def test_power():
raises(NonSquareMatrixError, lambda: Matrix((1, 2))**2)
A = ArithmeticOnlyMatrix([[2, 3], [4, 5]])
assert (A**5)[:] == (6140, 8097, 10796, 14237)
A = ArithmeticOnlyMatrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
assert (A**3)[:] == (290, 262, 251, 448, 440, 368, 702, 954, 433)
assert A**0 == eye(3)
assert A**1 == A
assert (ArithmeticOnlyMatrix([[2]]) ** 100)[0, 0] == 2**100
assert ArithmeticOnlyMatrix([[1, 2], [3, 4]])**Integer(2) == ArithmeticOnlyMatrix([[7, 10], [15, 22]])
A = Matrix([[1,2],[4,5]])
assert A.pow(20, method='cayley') == A.pow(20, method='multiply')
def test_neg():
n = ArithmeticOnlyMatrix(1, 2, [1, 2])
assert -n == ArithmeticOnlyMatrix(1, 2, [-1, -2])
def test_sub():
n = ArithmeticOnlyMatrix(1, 2, [1, 2])
assert n - n == ArithmeticOnlyMatrix(1, 2, [0, 0])
def test_div():
n = ArithmeticOnlyMatrix(1, 2, [1, 2])
assert n/2 == ArithmeticOnlyMatrix(1, 2, [S.Half, S(2)/2])
# SpecialOnlyMatrix tests
def test_eye():
assert list(SpecialOnlyMatrix.eye(2, 2)) == [1, 0, 0, 1]
assert list(SpecialOnlyMatrix.eye(2)) == [1, 0, 0, 1]
assert type(SpecialOnlyMatrix.eye(2)) == SpecialOnlyMatrix
assert type(SpecialOnlyMatrix.eye(2, cls=Matrix)) == Matrix
def test_ones():
assert list(SpecialOnlyMatrix.ones(2, 2)) == [1, 1, 1, 1]
assert list(SpecialOnlyMatrix.ones(2)) == [1, 1, 1, 1]
assert SpecialOnlyMatrix.ones(2, 3) == Matrix([[1, 1, 1], [1, 1, 1]])
assert type(SpecialOnlyMatrix.ones(2)) == SpecialOnlyMatrix
assert type(SpecialOnlyMatrix.ones(2, cls=Matrix)) == Matrix
def test_zeros():
assert list(SpecialOnlyMatrix.zeros(2, 2)) == [0, 0, 0, 0]
assert list(SpecialOnlyMatrix.zeros(2)) == [0, 0, 0, 0]
assert SpecialOnlyMatrix.zeros(2, 3) == Matrix([[0, 0, 0], [0, 0, 0]])
assert type(SpecialOnlyMatrix.zeros(2)) == SpecialOnlyMatrix
assert type(SpecialOnlyMatrix.zeros(2, cls=Matrix)) == Matrix
def test_diag_make():
diag = SpecialOnlyMatrix.diag
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert diag(a, b, b) == Matrix([
[1, 2, 0, 0, 0, 0],
[2, 3, 0, 0, 0, 0],
[0, 0, 3, x, 0, 0],
[0, 0, y, 3, 0, 0],
[0, 0, 0, 0, 3, x],
[0, 0, 0, 0, y, 3],
])
assert diag(a, b, c) == Matrix([
[1, 2, 0, 0, 0, 0, 0],
[2, 3, 0, 0, 0, 0, 0],
[0, 0, 3, x, 0, 0, 0],
[0, 0, y, 3, 0, 0, 0],
[0, 0, 0, 0, 3, x, 3],
[0, 0, 0, 0, y, 3, z],
[0, 0, 0, 0, x, y, z],
])
assert diag(a, c, b) == Matrix([
[1, 2, 0, 0, 0, 0, 0],
[2, 3, 0, 0, 0, 0, 0],
[0, 0, 3, x, 3, 0, 0],
[0, 0, y, 3, z, 0, 0],
[0, 0, x, y, z, 0, 0],
[0, 0, 0, 0, 0, 3, x],
[0, 0, 0, 0, 0, y, 3],
])
a = Matrix([x, y, z])
b = Matrix([[1, 2], [3, 4]])
c = Matrix([[5, 6]])
# this "wandering diagonal" is what makes this
# a block diagonal where each block is independent
# of the others
assert diag(a, 7, b, c) == Matrix([
[x, 0, 0, 0, 0, 0],
[y, 0, 0, 0, 0, 0],
[z, 0, 0, 0, 0, 0],
[0, 7, 0, 0, 0, 0],
[0, 0, 1, 2, 0, 0],
[0, 0, 3, 4, 0, 0],
[0, 0, 0, 0, 5, 6]])
raises(ValueError, lambda: diag(a, 7, b, c, rows=5))
assert diag(1) == Matrix([[1]])
assert diag(1, rows=2) == Matrix([[1, 0], [0, 0]])
assert diag(1, cols=2) == Matrix([[1, 0], [0, 0]])
assert diag(1, rows=3, cols=2) == Matrix([[1, 0], [0, 0], [0, 0]])
assert diag(*[2, 3]) == Matrix([
[2, 0],
[0, 3]])
assert diag(Matrix([2, 3])) == Matrix([
[2],
[3]])
assert diag([1, [2, 3], 4], unpack=False) == \
diag([[1], [2, 3], [4]], unpack=False) == Matrix([
[1, 0],
[2, 3],
[4, 0]])
assert type(diag(1)) == SpecialOnlyMatrix
assert type(diag(1, cls=Matrix)) == Matrix
assert Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3)
assert Matrix.diag([1, 2, 3], unpack=False).shape == (3, 1)
assert Matrix.diag([[1, 2, 3]]).shape == (3, 1)
assert Matrix.diag([[1, 2, 3]], unpack=False).shape == (1, 3)
assert Matrix.diag([[[1, 2, 3]]]).shape == (1, 3)
# kerning can be used to move the starting point
assert Matrix.diag(ones(0, 2), 1, 2) == Matrix([
[0, 0, 1, 0],
[0, 0, 0, 2]])
assert Matrix.diag(ones(2, 0), 1, 2) == Matrix([
[0, 0],
[0, 0],
[1, 0],
[0, 2]])
def test_diagonal():
m = Matrix(3, 3, range(9))
d = m.diagonal()
assert d == m.diagonal(0)
assert tuple(d) == (0, 4, 8)
assert tuple(m.diagonal(1)) == (1, 5)
assert tuple(m.diagonal(-1)) == (3, 7)
assert tuple(m.diagonal(2)) == (2,)
assert type(m.diagonal()) == type(m)
s = SparseMatrix(3, 3, {(1, 1): 1})
assert type(s.diagonal()) == type(s)
assert type(m) != type(s)
raises(ValueError, lambda: m.diagonal(3))
raises(ValueError, lambda: m.diagonal(-3))
raises(ValueError, lambda: m.diagonal(pi))
M = ones(2, 3)
assert banded({i: list(M.diagonal(i))
for i in range(1-M.rows, M.cols)}) == M
def test_jordan_block():
assert SpecialOnlyMatrix.jordan_block(3, 2) == SpecialOnlyMatrix.jordan_block(3, eigenvalue=2) \
== SpecialOnlyMatrix.jordan_block(size=3, eigenvalue=2) \
== SpecialOnlyMatrix.jordan_block(3, 2, band='upper') \
== SpecialOnlyMatrix.jordan_block(
size=3, eigenval=2, eigenvalue=2) \
== Matrix([
[2, 1, 0],
[0, 2, 1],
[0, 0, 2]])
assert SpecialOnlyMatrix.jordan_block(3, 2, band='lower') == Matrix([
[2, 0, 0],
[1, 2, 0],
[0, 1, 2]])
# missing eigenvalue
raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(2))
# non-integral size
raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(3.5, 2))
# size not specified
raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(eigenvalue=2))
# inconsistent eigenvalue
raises(ValueError,
lambda: SpecialOnlyMatrix.jordan_block(
eigenvalue=2, eigenval=4))
# Deprecated feature
with warns_deprecated_sympy():
assert (SpecialOnlyMatrix.jordan_block(cols=3, eigenvalue=2) ==
SpecialOnlyMatrix(3, 3, (2, 1, 0, 0, 2, 1, 0, 0, 2)))
with warns_deprecated_sympy():
assert (SpecialOnlyMatrix.jordan_block(rows=3, eigenvalue=2) ==
SpecialOnlyMatrix(3, 3, (2, 1, 0, 0, 2, 1, 0, 0, 2)))
with warns_deprecated_sympy():
assert SpecialOnlyMatrix.jordan_block(3, 2) == \
SpecialOnlyMatrix.jordan_block(cols=3, eigenvalue=2) == \
SpecialOnlyMatrix.jordan_block(rows=3, eigenvalue=2)
with warns_deprecated_sympy():
assert SpecialOnlyMatrix.jordan_block(
rows=4, cols=3, eigenvalue=2) == \
Matrix([
[2, 1, 0],
[0, 2, 1],
[0, 0, 2],
[0, 0, 0]])
# Using alias keyword
assert SpecialOnlyMatrix.jordan_block(size=3, eigenvalue=2) == \
SpecialOnlyMatrix.jordan_block(size=3, eigenval=2)
def test_orthogonalize():
m = Matrix([[1, 2], [3, 4]])
assert m.orthogonalize(Matrix([[2], [1]])) == [Matrix([[2], [1]])]
assert m.orthogonalize(Matrix([[2], [1]]), normalize=True) == \
[Matrix([[2*sqrt(5)/5], [sqrt(5)/5]])]
assert m.orthogonalize(Matrix([[1], [2]]), Matrix([[-1], [4]])) == \
[Matrix([[1], [2]]), Matrix([[Rational(-12, 5)], [Rational(6, 5)]])]
assert m.orthogonalize(Matrix([[0], [0]]), Matrix([[-1], [4]])) == \
[Matrix([[-1], [4]])]
assert m.orthogonalize(Matrix([[0], [0]])) == []
n = Matrix([[9, 1, 9], [3, 6, 10], [8, 5, 2]])
vecs = [Matrix([[-5], [1]]), Matrix([[-5], [2]]), Matrix([[-5], [-2]])]
assert n.orthogonalize(*vecs) == \
[Matrix([[-5], [1]]), Matrix([[Rational(5, 26)], [Rational(25, 26)]])]
vecs = [Matrix([0, 0, 0]), Matrix([1, 2, 3]), Matrix([1, 4, 5])]
raises(ValueError, lambda: Matrix.orthogonalize(*vecs, rankcheck=True))
vecs = [Matrix([1, 2, 3]), Matrix([4, 5, 6]), Matrix([7, 8, 9])]
raises(ValueError, lambda: Matrix.orthogonalize(*vecs, rankcheck=True))
def test_wilkinson():
wminus, wplus = Matrix.wilkinson(1)
assert wminus == Matrix([
[-1, 1, 0],
[1, 0, 1],
[0, 1, 1]])
assert wplus == Matrix([
[1, 1, 0],
[1, 0, 1],
[0, 1, 1]])
wminus, wplus = Matrix.wilkinson(3)
assert wminus == Matrix([
[-3, 1, 0, 0, 0, 0, 0],
[1, -2, 1, 0, 0, 0, 0],
[0, 1, -1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 1, 2, 1],
[0, 0, 0, 0, 0, 1, 3]])
assert wplus == Matrix([
[3, 1, 0, 0, 0, 0, 0],
[1, 2, 1, 0, 0, 0, 0],
[0, 1, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0],
[0, 0, 0, 1, 1, 1, 0],
[0, 0, 0, 0, 1, 2, 1],
[0, 0, 0, 0, 0, 1, 3]])
# CalculusOnlyMatrix tests
@XFAIL
def test_diff():
x, y = symbols('x y')
m = CalculusOnlyMatrix(2, 1, [x, y])
# TODO: currently not working as ``_MinimalMatrix`` cannot be sympified:
assert m.diff(x) == Matrix(2, 1, [1, 0])
def test_integrate():
x, y = symbols('x y')
m = CalculusOnlyMatrix(2, 1, [x, y])
assert m.integrate(x) == Matrix(2, 1, [x**2/2, y*x])
def test_jacobian2():
rho, phi = symbols("rho,phi")
X = CalculusOnlyMatrix(3, 1, [rho*cos(phi), rho*sin(phi), rho**2])
Y = CalculusOnlyMatrix(2, 1, [rho, phi])
J = Matrix([
[cos(phi), -rho*sin(phi)],
[sin(phi), rho*cos(phi)],
[ 2*rho, 0],
])
assert X.jacobian(Y) == J
m = CalculusOnlyMatrix(2, 2, [1, 2, 3, 4])
m2 = CalculusOnlyMatrix(4, 1, [1, 2, 3, 4])
raises(TypeError, lambda: m.jacobian(Matrix([1, 2])))
raises(TypeError, lambda: m2.jacobian(m))
def test_limit():
x, y = symbols('x y')
m = CalculusOnlyMatrix(2, 1, [1/x, y])
assert m.limit(x, 5) == Matrix(2, 1, [Rational(1, 5), y])
def test_issue_13774():
M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
v = [1, 1, 1]
raises(TypeError, lambda: M*v)
raises(TypeError, lambda: v*M)
def test_companion():
x = Symbol('x')
y = Symbol('y')
raises(ValueError, lambda: Matrix.companion(1))
raises(ValueError, lambda: Matrix.companion(Poly([1], x)))
raises(ValueError, lambda: Matrix.companion(Poly([2, 1], x)))
raises(ValueError, lambda: Matrix.companion(Poly(x*y, [x, y])))
c0, c1, c2 = symbols('c0:3')
assert Matrix.companion(Poly([1, c0], x)) == Matrix([-c0])
assert Matrix.companion(Poly([1, c1, c0], x)) == \
Matrix([[0, -c0], [1, -c1]])
assert Matrix.companion(Poly([1, c2, c1, c0], x)) == \
Matrix([[0, 0, -c0], [1, 0, -c1], [0, 1, -c2]])
def test_issue_10589():
x, y, z = symbols("x, y z")
M1 = Matrix([x, y, z])
M1 = M1.subs(zip([x, y, z], [1, 2, 3]))
assert M1 == Matrix([[1], [2], [3]])
M2 = Matrix([[x, x, x, x, x], [x, x, x, x, x], [x, x, x, x, x]])
M2 = M2.subs(zip([x], [1]))
assert M2 == Matrix([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]])
def test_rmul_pr19860():
class Foo(ImmutableDenseMatrix):
_op_priority = MutableDenseMatrix._op_priority + 0.01
a = Matrix(2, 2, [1, 2, 3, 4])
b = Foo(2, 2, [1, 2, 3, 4])
# This would throw a RecursionError: maximum recursion depth
# since b always has higher priority even after a.as_mutable()
c = a*b
assert isinstance(c, Foo)
assert c == Matrix([[7, 10], [15, 22]])
def test_issue_18956():
A = Array([[1, 2], [3, 4]])
B = Matrix([[1,2],[3,4]])
raises(TypeError, lambda: B + A)
raises(TypeError, lambda: A + B)
def test__eq__():
class My(object):
def __iter__(self):
yield 1
yield 2
return
def __getitem__(self, i):
return list(self)[i]
a = Matrix(2, 1, [1, 2])
assert a != My()
class My_sympy(My):
def _sympy_(self):
return Matrix(self)
assert a == My_sympy()
|
ed8b5b64b7d081e0192fe0accccfd49c3201a2d6022ac35042d89de020febc33 | from sympy.testing.pytest import warns_deprecated_sympy
from sympy.core.symbol import Symbol
from sympy.polys.polytools import Poly
from sympy.matrices import Matrix
from sympy.matrices.normalforms import (
invariant_factors,
smith_normal_form,
hermite_normal_form,
)
from sympy.polys.domains import ZZ, QQ
from sympy.core.numbers import Integer
def test_smith_normal():
m = Matrix([[12,6,4,8],[3,9,6,12],[2,16,14,28],[20,10,10,20]])
smf = Matrix([[1, 0, 0, 0], [0, 10, 0, 0], [0, 0, -30, 0], [0, 0, 0, 0]])
assert smith_normal_form(m) == smf
x = Symbol('x')
with warns_deprecated_sympy():
m = Matrix([[Poly(x-1), Poly(1, x),Poly(-1,x)],
[0, Poly(x), Poly(-1,x)],
[Poly(0,x),Poly(-1,x),Poly(x)]])
invs = 1, x - 1, x**2 - 1
assert invariant_factors(m, domain=QQ[x]) == invs
m = Matrix([[2, 4]])
smf = Matrix([[2, 0]])
assert smith_normal_form(m) == smf
def test_smith_normal_deprecated():
from sympy.polys.solvers import RawMatrix as Matrix
with warns_deprecated_sympy():
m = Matrix([[12, 6, 4,8],[3,9,6,12],[2,16,14,28],[20,10,10,20]])
setattr(m, 'ring', ZZ)
with warns_deprecated_sympy():
smf = Matrix([[1, 0, 0, 0], [0, 10, 0, 0], [0, 0, -30, 0], [0, 0, 0, 0]])
assert smith_normal_form(m) == smf
x = Symbol('x')
with warns_deprecated_sympy():
m = Matrix([[Poly(x-1), Poly(1, x),Poly(-1,x)],
[0, Poly(x), Poly(-1,x)],
[Poly(0,x),Poly(-1,x),Poly(x)]])
setattr(m, 'ring', QQ[x])
invs = (Poly(1, x, domain='QQ'), Poly(x - 1, domain='QQ'), Poly(x**2 - 1, domain='QQ'))
assert invariant_factors(m) == invs
with warns_deprecated_sympy():
m = Matrix([[2, 4]])
setattr(m, 'ring', ZZ)
with warns_deprecated_sympy():
smf = Matrix([[2, 0]])
assert smith_normal_form(m) == smf
def test_hermite_normal():
m = Matrix([[2, 7, 17, 29, 41], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]])
hnf = Matrix([[1, 0, 0], [0, 2, 1], [0, 0, 1]])
assert hermite_normal_form(m) == hnf
tr_hnf = Matrix([[37, 0, 19], [222, -6, 113], [48, 0, 25], [0, 2, 1], [0, 0, 1]])
assert hermite_normal_form(m.transpose()) == tr_hnf
m = Matrix([[8, 28, 68, 116, 164], [3, 11, 19, 31, 43], [5, 13, 23, 37, 47]])
hnf = Matrix([[4, 0, 0], [0, 2, 1], [0, 0, 1]])
assert hermite_normal_form(m) == hnf
assert hermite_normal_form(m, D=8) == hnf
assert hermite_normal_form(m, D=ZZ(8)) == hnf
assert hermite_normal_form(m, D=Integer(8)) == hnf
m = Matrix([[10, 8, 6, 30, 2], [45, 36, 27, 18, 9], [5, 4, 3, 2, 1]])
hnf = Matrix([[26, 2], [0, 9], [0, 1]])
assert hermite_normal_form(m) == hnf
m = Matrix([[2, 7], [0, 0], [0, 0]])
hnf = Matrix(3, 0, [])
assert hermite_normal_form(m) == hnf
|
2f1e436ebb380877293f916b66ffadd193c68e285f6fe884f21589392d45f3a0 | import random
import concurrent.futures
from collections.abc import Hashable
from sympy.core.add import Add
from sympy.core.function import (Function, diff, expand)
from sympy.core.numbers import (E, Float, I, Integer, Rational, nan, oo, pi)
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.core.sympify import sympify
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
from sympy.polys.polytools import (Poly, PurePoly)
from sympy.printing.str import sstr
from sympy.sets.sets import FiniteSet
from sympy.simplify.simplify import (signsimp, simplify)
from sympy.simplify.trigsimp import trigsimp
from sympy.matrices.matrices import (ShapeError, MatrixError,
NonSquareMatrixError, DeferredVector, _find_reasonable_pivot_naive,
_simplify)
from sympy.matrices import (
GramSchmidt, ImmutableMatrix, ImmutableSparseMatrix, Matrix,
SparseMatrix, casoratian, diag, eye, hessian,
matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2,
rot_axis3, wronskian, zeros, MutableDenseMatrix, ImmutableDenseMatrix,
MatrixSymbol, dotprodsimp)
from sympy.matrices.utilities import _dotprodsimp_state
from sympy.core import Tuple, Wild
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.utilities.iterables import flatten, capture, iterable
from sympy.testing.pytest import raises, XFAIL, slow, skip, warns_deprecated_sympy
from sympy.assumptions import Q
from sympy.tensor.array import Array
from sympy.matrices.expressions import MatPow
from sympy.abc import a, b, c, d, x, y, z, t
# don't re-order this list
classes = (Matrix, SparseMatrix, ImmutableMatrix, ImmutableSparseMatrix)
def test_args():
for n, cls in enumerate(classes):
m = cls.zeros(3, 2)
# all should give back the same type of arguments, e.g. ints for shape
assert m.shape == (3, 2) and all(type(i) is int for i in m.shape)
assert m.rows == 3 and type(m.rows) is int
assert m.cols == 2 and type(m.cols) is int
if not n % 2:
assert type(m.flat()) in (list, tuple, Tuple)
else:
assert type(m.todok()) is dict
def test_deprecated_mat_smat():
for cls in Matrix, ImmutableMatrix:
m = cls.zeros(3, 2)
with warns_deprecated_sympy():
mat = m._mat
assert mat == m.flat()
for cls in SparseMatrix, ImmutableSparseMatrix:
m = cls.zeros(3, 2)
with warns_deprecated_sympy():
smat = m._smat
assert smat == m.todok()
def test_division():
v = Matrix(1, 2, [x, y])
assert v/z == Matrix(1, 2, [x/z, y/z])
def test_sum():
m = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
assert m + m == Matrix([[2, 4, 6], [2*x, 2*y, 2*x], [4*y, -100, 2*z*x]])
n = Matrix(1, 2, [1, 2])
raises(ShapeError, lambda: m + n)
def test_abs():
m = Matrix(1, 2, [-3, x])
n = Matrix(1, 2, [3, Abs(x)])
assert abs(m) == n
def test_addition():
a = Matrix((
(1, 2),
(3, 1),
))
b = Matrix((
(1, 2),
(3, 0),
))
assert a + b == a.add(b) == Matrix([[2, 4], [6, 1]])
def test_fancy_index_matrix():
for M in (Matrix, SparseMatrix):
a = M(3, 3, range(9))
assert a == a[:, :]
assert a[1, :] == Matrix(1, 3, [3, 4, 5])
assert a[:, 1] == Matrix([1, 4, 7])
assert a[[0, 1], :] == Matrix([[0, 1, 2], [3, 4, 5]])
assert a[[0, 1], 2] == a[[0, 1], [2]]
assert a[2, [0, 1]] == a[[2], [0, 1]]
assert a[:, [0, 1]] == Matrix([[0, 1], [3, 4], [6, 7]])
assert a[0, 0] == 0
assert a[0:2, :] == Matrix([[0, 1, 2], [3, 4, 5]])
assert a[:, 0:2] == Matrix([[0, 1], [3, 4], [6, 7]])
assert a[::2, 1] == a[[0, 2], 1]
assert a[1, ::2] == a[1, [0, 2]]
a = M(3, 3, range(9))
assert a[[0, 2, 1, 2, 1], :] == Matrix([
[0, 1, 2],
[6, 7, 8],
[3, 4, 5],
[6, 7, 8],
[3, 4, 5]])
assert a[:, [0,2,1,2,1]] == Matrix([
[0, 2, 1, 2, 1],
[3, 5, 4, 5, 4],
[6, 8, 7, 8, 7]])
a = SparseMatrix.zeros(3)
a[1, 2] = 2
a[0, 1] = 3
a[2, 0] = 4
assert a.extract([1, 1], [2]) == Matrix([
[2],
[2]])
assert a.extract([1, 0], [2, 2, 2]) == Matrix([
[2, 2, 2],
[0, 0, 0]])
assert a.extract([1, 0, 1, 2], [2, 0, 1, 0]) == Matrix([
[2, 0, 0, 0],
[0, 0, 3, 0],
[2, 0, 0, 0],
[0, 4, 0, 4]])
def test_multiplication():
a = Matrix((
(1, 2),
(3, 1),
(0, 6),
))
b = Matrix((
(1, 2),
(3, 0),
))
c = a*b
assert c[0, 0] == 7
assert c[0, 1] == 2
assert c[1, 0] == 6
assert c[1, 1] == 6
assert c[2, 0] == 18
assert c[2, 1] == 0
try:
eval('c = a @ b')
except SyntaxError:
pass
else:
assert c[0, 0] == 7
assert c[0, 1] == 2
assert c[1, 0] == 6
assert c[1, 1] == 6
assert c[2, 0] == 18
assert c[2, 1] == 0
h = matrix_multiply_elementwise(a, c)
assert h == a.multiply_elementwise(c)
assert h[0, 0] == 7
assert h[0, 1] == 4
assert h[1, 0] == 18
assert h[1, 1] == 6
assert h[2, 0] == 0
assert h[2, 1] == 0
raises(ShapeError, lambda: matrix_multiply_elementwise(a, b))
c = b * Symbol("x")
assert isinstance(c, Matrix)
assert c[0, 0] == x
assert c[0, 1] == 2*x
assert c[1, 0] == 3*x
assert c[1, 1] == 0
c2 = x * b
assert c == c2
c = 5 * b
assert isinstance(c, Matrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
try:
eval('c = 5 @ b')
except SyntaxError:
pass
else:
assert isinstance(c, Matrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
M = Matrix([[oo, 0], [0, oo]])
assert M ** 2 == M
M = Matrix([[oo, oo], [0, 0]])
assert M ** 2 == Matrix([[nan, nan], [nan, nan]])
def test_power():
raises(NonSquareMatrixError, lambda: Matrix((1, 2))**2)
R = Rational
A = Matrix([[2, 3], [4, 5]])
assert (A**-3)[:] == [R(-269)/8, R(153)/8, R(51)/2, R(-29)/2]
assert (A**5)[:] == [6140, 8097, 10796, 14237]
A = Matrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
assert (A**3)[:] == [290, 262, 251, 448, 440, 368, 702, 954, 433]
assert A**0 == eye(3)
assert A**1 == A
assert (Matrix([[2]]) ** 100)[0, 0] == 2**100
assert eye(2)**10000000 == eye(2)
assert Matrix([[1, 2], [3, 4]])**Integer(2) == Matrix([[7, 10], [15, 22]])
A = Matrix([[33, 24], [48, 57]])
assert (A**S.Half)[:] == [5, 2, 4, 7]
A = Matrix([[0, 4], [-1, 5]])
assert (A**S.Half)**2 == A
assert Matrix([[1, 0], [1, 1]])**S.Half == Matrix([[1, 0], [S.Half, 1]])
assert Matrix([[1, 0], [1, 1]])**0.5 == Matrix([[1.0, 0], [0.5, 1.0]])
from sympy.abc import n
assert Matrix([[1, a], [0, 1]])**n == Matrix([[1, a*n], [0, 1]])
assert Matrix([[b, a], [0, b]])**n == Matrix([[b**n, a*b**(n-1)*n], [0, b**n]])
assert Matrix([
[a**n, a**(n - 1)*n, (a**n*n**2 - a**n*n)/(2*a**2)],
[ 0, a**n, a**(n - 1)*n],
[ 0, 0, a**n]])
assert Matrix([[a, 1, 0], [0, a, 0], [0, 0, b]])**n == Matrix([
[a**n, a**(n-1)*n, 0],
[0, a**n, 0],
[0, 0, b**n]])
A = Matrix([[1, 0], [1, 7]])
assert A._matrix_pow_by_jordan_blocks(S(3)) == A._eval_pow_by_recursion(3)
A = Matrix([[2]])
assert A**10 == Matrix([[2**10]]) == A._matrix_pow_by_jordan_blocks(S(10)) == \
A._eval_pow_by_recursion(10)
# testing a matrix that cannot be jordan blocked issue 11766
m = Matrix([[3, 0, 0, 0, -3], [0, -3, -3, 0, 3], [0, 3, 0, 3, 0], [0, 0, 3, 0, 3], [3, 0, 0, 3, 0]])
raises(MatrixError, lambda: m._matrix_pow_by_jordan_blocks(S(10)))
# test issue 11964
raises(MatrixError, lambda: Matrix([[1, 1], [3, 3]])._matrix_pow_by_jordan_blocks(S(-10)))
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 0]]) # Nilpotent jordan block size 3
assert A**10.0 == Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
raises(ValueError, lambda: A**2.1)
raises(ValueError, lambda: A**Rational(3, 2))
A = Matrix([[8, 1], [3, 2]])
assert A**10.0 == Matrix([[1760744107, 272388050], [817164150, 126415807]])
A = Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 1
assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 2
assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
n = Symbol('n', integer=True)
assert isinstance(A**n, MatPow)
n = Symbol('n', integer=True, negative=True)
raises(ValueError, lambda: A**n)
n = Symbol('n', integer=True, nonnegative=True)
assert A**n == Matrix([
[KroneckerDelta(0, n), KroneckerDelta(1, n), -KroneckerDelta(0, n) - KroneckerDelta(1, n) + 1],
[ 0, KroneckerDelta(0, n), 1 - KroneckerDelta(0, n)],
[ 0, 0, 1]])
assert A**(n + 2) == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
raises(ValueError, lambda: A**Rational(3, 2))
A = Matrix([[0, 0, 1], [3, 0, 1], [4, 3, 1]])
assert A**5.0 == Matrix([[168, 72, 89], [291, 144, 161], [572, 267, 329]])
assert A**5.0 == A**5
A = Matrix([[0, 1, 0],[-1, 0, 0],[0, 0, 0]])
n = Symbol("n")
An = A**n
assert An.subs(n, 2).doit() == A**2
raises(ValueError, lambda: An.subs(n, -2).doit())
assert An * An == A**(2*n)
# concretizing behavior for non-integer and complex powers
A = Matrix([[0,0,0],[0,0,0],[0,0,0]])
n = Symbol('n', integer=True, positive=True)
assert A**n == A
n = Symbol('n', integer=True, nonnegative=True)
assert A**n == diag(0**n, 0**n, 0**n)
assert (A**n).subs(n, 0) == eye(3)
assert (A**n).subs(n, 1) == zeros(3)
A = Matrix ([[2,0,0],[0,2,0],[0,0,2]])
assert A**2.1 == diag (2**2.1, 2**2.1, 2**2.1)
assert A**I == diag (2**I, 2**I, 2**I)
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]])
raises(ValueError, lambda: A**2.1)
raises(ValueError, lambda: A**I)
A = Matrix([[S.Half, S.Half], [S.Half, S.Half]])
assert A**S.Half == A
A = Matrix([[1, 1],[3, 3]])
assert A**S.Half == Matrix ([[S.Half, S.Half], [3*S.Half, 3*S.Half]])
def test_issue_17247_expression_blowup_1():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
with dotprodsimp(True):
assert M.exp().expand() == Matrix([
[ (exp(2*x) + exp(2))/2, (-exp(2*x) + exp(2))/2],
[(-exp(2*x) + exp(2))/2, (exp(2*x) + exp(2))/2]])
def test_issue_17247_expression_blowup_2():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
with dotprodsimp(True):
P, J = M.jordan_form ()
assert P*J*P.inv()
def test_issue_17247_expression_blowup_3():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
with dotprodsimp(True):
assert M**100 == Matrix([
[633825300114114700748351602688*x**100 + 633825300114114700748351602688, 633825300114114700748351602688 - 633825300114114700748351602688*x**100],
[633825300114114700748351602688 - 633825300114114700748351602688*x**100, 633825300114114700748351602688*x**100 + 633825300114114700748351602688]])
def test_issue_17247_expression_blowup_4():
# This matrix takes extremely long on current master even with intermediate simplification so an abbreviated version is used. It is left here for test in case of future optimizations.
# M = Matrix(S('''[
# [ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256, 15/128 - 3*I/32, 19/256 + 551*I/1024],
# [-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096, 129/256 - 549*I/512, 42533/16384 + 29103*I/8192],
# [ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256],
# [ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096],
# [ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128],
# [ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024],
# [ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
# [ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
# [ -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
# [ 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
# [ -4, 9 - 5*I, -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
# [ -2*I, 119/8 + 29*I/4, 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
# assert M**10 == Matrix([
# [ 7*(-221393644768594642173548179825793834595 - 1861633166167425978847110897013541127952*I)/9671406556917033397649408, 15*(31670992489131684885307005100073928751695 + 10329090958303458811115024718207404523808*I)/77371252455336267181195264, 7*(-3710978679372178839237291049477017392703 + 1377706064483132637295566581525806894169*I)/19342813113834066795298816, (9727707023582419994616144751727760051598 - 59261571067013123836477348473611225724433*I)/9671406556917033397649408, (31896723509506857062605551443641668183707 + 54643444538699269118869436271152084599580*I)/38685626227668133590597632, (-2024044860947539028275487595741003997397402 + 130959428791783397562960461903698670485863*I)/309485009821345068724781056, 3*(26190251453797590396533756519358368860907 - 27221191754180839338002754608545400941638*I)/77371252455336267181195264, (1154643595139959842768960128434994698330461 + 3385496216250226964322872072260446072295634*I)/618970019642690137449562112, 3*(-31849347263064464698310044805285774295286 - 11877437776464148281991240541742691164309*I)/77371252455336267181195264, (4661330392283532534549306589669150228040221 - 4171259766019818631067810706563064103956871*I)/1237940039285380274899124224, (9598353794289061833850770474812760144506 + 358027153990999990968244906482319780943983*I)/309485009821345068724781056, (-9755135335127734571547571921702373498554177 - 4837981372692695195747379349593041939686540*I)/2475880078570760549798248448],
# [(-379516731607474268954110071392894274962069 - 422272153179747548473724096872271700878296*I)/77371252455336267181195264, (41324748029613152354787280677832014263339501 - 12715121258662668420833935373453570749288074*I)/1237940039285380274899124224, (-339216903907423793947110742819264306542397 + 494174755147303922029979279454787373566517*I)/77371252455336267181195264, (-18121350839962855576667529908850640619878381 - 37413012454129786092962531597292531089199003*I)/1237940039285380274899124224, (2489661087330511608618880408199633556675926 + 1137821536550153872137379935240732287260863*I)/309485009821345068724781056, (-136644109701594123227587016790354220062972119 + 110130123468183660555391413889600443583585272*I)/4951760157141521099596496896, (1488043981274920070468141664150073426459593 - 9691968079933445130866371609614474474327650*I)/1237940039285380274899124224, 27*(4636797403026872518131756991410164760195942 + 3369103221138229204457272860484005850416533*I)/4951760157141521099596496896, (-8534279107365915284081669381642269800472363 + 2241118846262661434336333368511372725482742*I)/1237940039285380274899124224, (60923350128174260992536531692058086830950875 - 263673488093551053385865699805250505661590126*I)/9903520314283042199192993792, (18520943561240714459282253753348921824172569 + 24846649186468656345966986622110971925703604*I)/4951760157141521099596496896, (-232781130692604829085973604213529649638644431 + 35981505277760667933017117949103953338570617*I)/9903520314283042199192993792],
# [ (8742968295129404279528270438201520488950 + 3061473358639249112126847237482570858327*I)/4835703278458516698824704, (-245657313712011778432792959787098074935273 + 253113767861878869678042729088355086740856*I)/38685626227668133590597632, (1947031161734702327107371192008011621193 - 19462330079296259148177542369999791122762*I)/9671406556917033397649408, (552856485625209001527688949522750288619217 + 392928441196156725372494335248099016686580*I)/77371252455336267181195264, (-44542866621905323121630214897126343414629 + 3265340021421335059323962377647649632959*I)/19342813113834066795298816, (136272594005759723105646069956434264218730 - 330975364731707309489523680957584684763587*I)/38685626227668133590597632, (27392593965554149283318732469825168894401 + 75157071243800133880129376047131061115278*I)/38685626227668133590597632, 7*(-357821652913266734749960136017214096276154 - 45509144466378076475315751988405961498243*I)/309485009821345068724781056, (104485001373574280824835174390219397141149 - 99041000529599568255829489765415726168162*I)/77371252455336267181195264, (1198066993119982409323525798509037696321291 + 4249784165667887866939369628840569844519936*I)/618970019642690137449562112, (-114985392587849953209115599084503853611014 - 52510376847189529234864487459476242883449*I)/77371252455336267181195264, (6094620517051332877965959223269600650951573 - 4683469779240530439185019982269137976201163*I)/1237940039285380274899124224],
# [ (611292255597977285752123848828590587708323 - 216821743518546668382662964473055912169502*I)/77371252455336267181195264, (-1144023204575811464652692396337616594307487 + 12295317806312398617498029126807758490062855*I)/309485009821345068724781056, (-374093027769390002505693378578475235158281 - 573533923565898290299607461660384634333639*I)/77371252455336267181195264, (47405570632186659000138546955372796986832987 - 2837476058950808941605000274055970055096534*I)/1237940039285380274899124224, (-571573207393621076306216726219753090535121 + 533381457185823100878764749236639320783831*I)/77371252455336267181195264, (-7096548151856165056213543560958582513797519 - 24035731898756040059329175131592138642195366*I)/618970019642690137449562112, (2396762128833271142000266170154694033849225 + 1448501087375679588770230529017516492953051*I)/309485009821345068724781056, (-150609293845161968447166237242456473262037053 + 92581148080922977153207018003184520294188436*I)/4951760157141521099596496896, 5*(270278244730804315149356082977618054486347 - 1997830155222496880429743815321662710091562*I)/1237940039285380274899124224, (62978424789588828258068912690172109324360330 + 44803641177219298311493356929537007630129097*I)/2475880078570760549798248448, 19*(-451431106327656743945775812536216598712236 + 114924966793632084379437683991151177407937*I)/1237940039285380274899124224, (63417747628891221594106738815256002143915995 - 261508229397507037136324178612212080871150958*I)/9903520314283042199192993792],
# [ (-2144231934021288786200752920446633703357 + 2305614436009705803670842248131563850246*I)/1208925819614629174706176, (-90720949337459896266067589013987007078153 - 221951119475096403601562347412753844534569*I)/19342813113834066795298816, (11590973613116630788176337262688659880376 + 6514520676308992726483494976339330626159*I)/4835703278458516698824704, 3*(-131776217149000326618649542018343107657237 + 79095042939612668486212006406818285287004*I)/38685626227668133590597632, (10100577916793945997239221374025741184951 - 28631383488085522003281589065994018550748*I)/9671406556917033397649408, 67*(10090295594251078955008130473573667572549 + 10449901522697161049513326446427839676762*I)/77371252455336267181195264, (-54270981296988368730689531355811033930513 - 3413683117592637309471893510944045467443*I)/19342813113834066795298816, (440372322928679910536575560069973699181278 - 736603803202303189048085196176918214409081*I)/77371252455336267181195264, (33220374714789391132887731139763250155295 + 92055083048787219934030779066298919603554*I)/38685626227668133590597632, 5*(-594638554579967244348856981610805281527116 - 82309245323128933521987392165716076704057*I)/309485009821345068724781056, (128056368815300084550013708313312073721955 - 114619107488668120303579745393765245911404*I)/77371252455336267181195264, 21*(59839959255173222962789517794121843393573 + 241507883613676387255359616163487405826334*I)/618970019642690137449562112],
# [ (-13454485022325376674626653802541391955147 + 184471402121905621396582628515905949793486*I)/19342813113834066795298816, (-6158730123400322562149780662133074862437105 - 3416173052604643794120262081623703514107476*I)/154742504910672534362390528, (770558003844914708453618983120686116100419 - 127758381209767638635199674005029818518766*I)/77371252455336267181195264, (-4693005771813492267479835161596671660631703 + 12703585094750991389845384539501921531449948*I)/309485009821345068724781056, (-295028157441149027913545676461260860036601 - 841544569970643160358138082317324743450770*I)/77371252455336267181195264, (56716442796929448856312202561538574275502893 + 7216818824772560379753073185990186711454778*I)/1237940039285380274899124224, 15*(-87061038932753366532685677510172566368387 + 61306141156647596310941396434445461895538*I)/154742504910672534362390528, (-3455315109680781412178133042301025723909347 - 24969329563196972466388460746447646686670670*I)/618970019642690137449562112, (2453418854160886481106557323699250865361849 + 1497886802326243014471854112161398141242514*I)/309485009821345068724781056, (-151343224544252091980004429001205664193082173 + 90471883264187337053549090899816228846836628*I)/4951760157141521099596496896, (1652018205533026103358164026239417416432989 - 9959733619236515024261775397109724431400162*I)/1237940039285380274899124224, 3*(40676374242956907656984876692623172736522006 + 31023357083037817469535762230872667581366205*I)/4951760157141521099596496896],
# [ (-1226990509403328460274658603410696548387 - 4131739423109992672186585941938392788458*I)/1208925819614629174706176, (162392818524418973411975140074368079662703 + 23706194236915374831230612374344230400704*I)/9671406556917033397649408, (-3935678233089814180000602553655565621193 + 2283744757287145199688061892165659502483*I)/1208925819614629174706176, (-2400210250844254483454290806930306285131 - 315571356806370996069052930302295432758205*I)/19342813113834066795298816, (13365917938215281056563183751673390817910 + 15911483133819801118348625831132324863881*I)/4835703278458516698824704, 3*(-215950551370668982657516660700301003897855 + 51684341999223632631602864028309400489378*I)/38685626227668133590597632, (20886089946811765149439844691320027184765 - 30806277083146786592790625980769214361844*I)/9671406556917033397649408, (562180634592713285745940856221105667874855 + 1031543963988260765153550559766662245114916*I)/77371252455336267181195264, (-65820625814810177122941758625652476012867 - 12429918324787060890804395323920477537595*I)/19342813113834066795298816, (319147848192012911298771180196635859221089 - 402403304933906769233365689834404519960394*I)/38685626227668133590597632, (23035615120921026080284733394359587955057 + 115351677687031786114651452775242461310624*I)/38685626227668133590597632, (-3426830634881892756966440108592579264936130 - 1022954961164128745603407283836365128598559*I)/309485009821345068724781056],
# [ (-192574788060137531023716449082856117537757 - 69222967328876859586831013062387845780692*I)/19342813113834066795298816, (2736383768828013152914815341491629299773262 - 2773252698016291897599353862072533475408743*I)/77371252455336267181195264, (-23280005281223837717773057436155921656805 + 214784953368021840006305033048142888879224*I)/19342813113834066795298816, (-3035247484028969580570400133318947903462326 - 2195168903335435855621328554626336958674325*I)/77371252455336267181195264, (984552428291526892214541708637840971548653 - 64006622534521425620714598573494988589378*I)/77371252455336267181195264, (-3070650452470333005276715136041262898509903 + 7286424705750810474140953092161794621989080*I)/154742504910672534362390528, (-147848877109756404594659513386972921139270 - 416306113044186424749331418059456047650861*I)/38685626227668133590597632, (55272118474097814260289392337160619494260781 + 7494019668394781211907115583302403519488058*I)/1237940039285380274899124224, (-581537886583682322424771088996959213068864 + 542191617758465339135308203815256798407429*I)/77371252455336267181195264, (-6422548983676355789975736799494791970390991 - 23524183982209004826464749309156698827737702*I)/618970019642690137449562112, 7*(180747195387024536886923192475064903482083 + 84352527693562434817771649853047924991804*I)/154742504910672534362390528, (-135485179036717001055310712747643466592387031 + 102346575226653028836678855697782273460527608*I)/4951760157141521099596496896],
# [ (3384238362616083147067025892852431152105 + 156724444932584900214919898954874618256*I)/604462909807314587353088, (-59558300950677430189587207338385764871866 + 114427143574375271097298201388331237478857*I)/4835703278458516698824704, (-1356835789870635633517710130971800616227 - 7023484098542340388800213478357340875410*I)/1208925819614629174706176, (234884918567993750975181728413524549575881 + 79757294640629983786895695752733890213506*I)/9671406556917033397649408, (-7632732774935120473359202657160313866419 + 2905452608512927560554702228553291839465*I)/1208925819614629174706176, (52291747908702842344842889809762246649489 - 520996778817151392090736149644507525892649*I)/19342813113834066795298816, (17472406829219127839967951180375981717322 + 23464704213841582137898905375041819568669*I)/4835703278458516698824704, (-911026971811893092350229536132730760943307 + 150799318130900944080399439626714846752360*I)/38685626227668133590597632, (26234457233977042811089020440646443590687 - 45650293039576452023692126463683727692890*I)/9671406556917033397649408, 3*(288348388717468992528382586652654351121357 + 454526517721403048270274049572136109264668*I)/77371252455336267181195264, (-91583492367747094223295011999405657956347 - 12704691128268298435362255538069612411331*I)/19342813113834066795298816, (411208730251327843849027957710164064354221 - 569898526380691606955496789378230959965898*I)/38685626227668133590597632],
# [ (27127513117071487872628354831658811211795 - 37765296987901990355760582016892124833857*I)/4835703278458516698824704, (1741779916057680444272938534338833170625435 + 3083041729779495966997526404685535449810378*I)/77371252455336267181195264, 3*(-60642236251815783728374561836962709533401 - 24630301165439580049891518846174101510744*I)/19342813113834066795298816, 3*(445885207364591681637745678755008757483408 - 350948497734812895032502179455610024541643*I)/38685626227668133590597632, (-47373295621391195484367368282471381775684 + 219122969294089357477027867028071400054973*I)/19342813113834066795298816, (-2801565819673198722993348253876353741520438 - 2250142129822658548391697042460298703335701*I)/77371252455336267181195264, (801448252275607253266997552356128790317119 - 50890367688077858227059515894356594900558*I)/77371252455336267181195264, (-5082187758525931944557763799137987573501207 + 11610432359082071866576699236013484487676124*I)/309485009821345068724781056, (-328925127096560623794883760398247685166830 - 643447969697471610060622160899409680422019*I)/77371252455336267181195264, 15*(2954944669454003684028194956846659916299765 + 33434406416888505837444969347824812608566*I)/1237940039285380274899124224, (-415749104352001509942256567958449835766827 + 479330966144175743357171151440020955412219*I)/77371252455336267181195264, 3*(-4639987285852134369449873547637372282914255 - 11994411888966030153196659207284951579243273*I)/1237940039285380274899124224],
# [ (-478846096206269117345024348666145495601 + 1249092488629201351470551186322814883283*I)/302231454903657293676544, (-17749319421930878799354766626365926894989 - 18264580106418628161818752318217357231971*I)/1208925819614629174706176, (2801110795431528876849623279389579072819 + 363258850073786330770713557775566973248*I)/604462909807314587353088, (-59053496693129013745775512127095650616252 + 78143588734197260279248498898321500167517*I)/4835703278458516698824704, (-283186724922498212468162690097101115349 - 6443437753863179883794497936345437398276*I)/1208925819614629174706176, (188799118826748909206887165661384998787543 + 84274736720556630026311383931055307398820*I)/9671406556917033397649408, (-5482217151670072904078758141270295025989 + 1818284338672191024475557065444481298568*I)/1208925819614629174706176, (56564463395350195513805521309731217952281 - 360208541416798112109946262159695452898431*I)/19342813113834066795298816, 11*(1259539805728870739006416869463689438068 + 1409136581547898074455004171305324917387*I)/4835703278458516698824704, 5*(-123701190701414554945251071190688818343325 + 30997157322590424677294553832111902279712*I)/38685626227668133590597632, (16130917381301373033736295883982414239781 - 32752041297570919727145380131926943374516*I)/9671406556917033397649408, (650301385108223834347093740500375498354925 + 899526407681131828596801223402866051809258*I)/77371252455336267181195264],
# [ (9011388245256140876590294262420614839483 + 8167917972423946282513000869327525382672*I)/1208925819614629174706176, (-426393174084720190126376382194036323028924 + 180692224825757525982858693158209545430621*I)/9671406556917033397649408, (24588556702197802674765733448108154175535 - 45091766022876486566421953254051868331066*I)/4835703278458516698824704, (1872113939365285277373877183750416985089691 + 3030392393733212574744122057679633775773130*I)/77371252455336267181195264, (-222173405538046189185754954524429864167549 - 75193157893478637039381059488387511299116*I)/19342813113834066795298816, (2670821320766222522963689317316937579844558 - 2645837121493554383087981511645435472169191*I)/77371252455336267181195264, 5*(-2100110309556476773796963197283876204940 + 41957457246479840487980315496957337371937*I)/19342813113834066795298816, (-5733743755499084165382383818991531258980593 - 3328949988392698205198574824396695027195732*I)/154742504910672534362390528, (707827994365259025461378911159398206329247 - 265730616623227695108042528694302299777294*I)/77371252455336267181195264, (-1442501604682933002895864804409322823788319 + 11504137805563265043376405214378288793343879*I)/309485009821345068724781056, (-56130472299445561499538726459719629522285 - 61117552419727805035810982426639329818864*I)/9671406556917033397649408, (39053692321126079849054272431599539429908717 - 10209127700342570953247177602860848130710666*I)/1237940039285380274899124224]])
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
[ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
[ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
[ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
[ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M**10 == Matrix(S('''[
[ 7369525394972778926719607798014571861/604462909807314587353088 - 229284202061790301477392339912557559*I/151115727451828646838272, -19704281515163975949388435612632058035/1208925819614629174706176 + 14319858347987648723768698170712102887*I/302231454903657293676544, -3623281909451783042932142262164941211/604462909807314587353088 - 6039240602494288615094338643452320495*I/604462909807314587353088, 109260497799140408739847239685705357695/2417851639229258349412352 - 7427566006564572463236368211555511431*I/2417851639229258349412352, -16095803767674394244695716092817006641/2417851639229258349412352 + 10336681897356760057393429626719177583*I/1208925819614629174706176, -42207883340488041844332828574359769743/2417851639229258349412352 - 182332262671671273188016400290188468499*I/4835703278458516698824704],
[50566491050825573392726324995779608259/1208925819614629174706176 - 90047007594468146222002432884052362145*I/2417851639229258349412352, 74273703462900000967697427843983822011/1208925819614629174706176 + 265947522682943571171988741842776095421*I/1208925819614629174706176, -116900341394390200556829767923360888429/2417851639229258349412352 - 53153263356679268823910621474478756845*I/2417851639229258349412352, 195407378023867871243426523048612490249/1208925819614629174706176 - 1242417915995360200584837585002906728929*I/9671406556917033397649408, -863597594389821970177319682495878193/302231454903657293676544 + 476936100741548328800725360758734300481*I/9671406556917033397649408, -3154451590535653853562472176601754835575/19342813113834066795298816 - 232909875490506237386836489998407329215*I/2417851639229258349412352],
[ -1715444997702484578716037230949868543/302231454903657293676544 + 5009695651321306866158517287924120777*I/302231454903657293676544, -30551582497996879620371947949342101301/604462909807314587353088 - 7632518367986526187139161303331519629*I/151115727451828646838272, 312680739924495153190604170938220575/18889465931478580854784 - 108664334509328818765959789219208459*I/75557863725914323419136, -14693696966703036206178521686918865509/604462909807314587353088 + 72345386220900843930147151999899692401*I/1208925819614629174706176, -8218872496728882299722894680635296519/1208925819614629174706176 - 16776782833358893712645864791807664983*I/1208925819614629174706176, 143237839169380078671242929143670635137/2417851639229258349412352 + 2883817094806115974748882735218469447*I/2417851639229258349412352],
[ 3087979417831061365023111800749855987/151115727451828646838272 + 34441942370802869368851419102423997089*I/604462909807314587353088, -148309181940158040917731426845476175667/604462909807314587353088 - 263987151804109387844966835369350904919*I/9671406556917033397649408, 50259518594816377378747711930008883165/1208925819614629174706176 - 95713974916869240305450001443767979653*I/2417851639229258349412352, 153466447023875527996457943521467271119/2417851639229258349412352 + 517285524891117105834922278517084871349*I/2417851639229258349412352, -29184653615412989036678939366291205575/604462909807314587353088 - 27551322282526322041080173287022121083*I/1208925819614629174706176, 196404220110085511863671393922447671649/1208925819614629174706176 - 1204712019400186021982272049902206202145*I/9671406556917033397649408],
[ -2632581805949645784625606590600098779/151115727451828646838272 - 589957435912868015140272627522612771*I/37778931862957161709568, 26727850893953715274702844733506310247/302231454903657293676544 - 10825791956782128799168209600694020481*I/302231454903657293676544, -1036348763702366164044671908440791295/151115727451828646838272 + 3188624571414467767868303105288107375*I/151115727451828646838272, -36814959939970644875593411585393242449/604462909807314587353088 - 18457555789119782404850043842902832647*I/302231454903657293676544, 12454491297984637815063964572803058647/604462909807314587353088 - 340489532842249733975074349495329171*I/302231454903657293676544, -19547211751145597258386735573258916681/604462909807314587353088 + 87299583775782199663414539883938008933*I/1208925819614629174706176],
[ -40281994229560039213253423262678393183/604462909807314587353088 - 2939986850065527327299273003299736641*I/604462909807314587353088, 331940684638052085845743020267462794181/2417851639229258349412352 - 284574901963624403933361315517248458969*I/1208925819614629174706176, 6453843623051745485064693628073010961/302231454903657293676544 + 36062454107479732681350914931391590957*I/604462909807314587353088, -147665869053634695632880753646441962067/604462909807314587353088 - 305987938660447291246597544085345123927*I/9671406556917033397649408, 107821369195275772166593879711259469423/2417851639229258349412352 - 11645185518211204108659001435013326687*I/302231454903657293676544, 64121228424717666402009446088588091619/1208925819614629174706176 + 265557133337095047883844369272389762133*I/1208925819614629174706176]]'''))
def test_issue_17247_expression_blowup_5():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.charpoly('x') == PurePoly(x**6 + (-6 - 6*I)*x**5 + 36*I*x**4, x, domain='EX')
def test_issue_17247_expression_blowup_6():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.det('bareiss') == 0
def test_issue_17247_expression_blowup_7():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.det('berkowitz') == 0
def test_issue_17247_expression_blowup_8():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.det('lu') == 0
def test_issue_17247_expression_blowup_9():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.rref() == (Matrix([
[1, 0, -1, -2, -3, -4, -5, -6],
[0, 1, 2, 3, 4, 5, 6, 7],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]]), (0, 1))
def test_issue_17247_expression_blowup_10():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.cofactor(0, 0) == 0
def test_issue_17247_expression_blowup_11():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.cofactor_matrix() == Matrix(6, 6, [0]*36)
def test_issue_17247_expression_blowup_12():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
with dotprodsimp(True):
assert M.eigenvals() == {6: 1, 6*I: 1, 0: 4}
def test_issue_17247_expression_blowup_13():
M = Matrix([
[ 0, 1 - x, x + 1, 1 - x],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 1 - x],
[ 0, 0, 1 - x, 0]])
ev = M.eigenvects()
assert ev[0] == (0, 2, [Matrix([0, -1, 0, 1])])
assert ev[1][0] == x - sqrt(2)*(x - 1) + 1
assert ev[1][1] == 1
assert ev[1][2][0].expand(deep=False, numer=True) == Matrix([
[(-x + sqrt(2)*(x - 1) - 1)/(x - 1)],
[-4*x/(x**2 - 2*x + 1) + (x + 1)*(x - sqrt(2)*(x - 1) + 1)/(x**2 - 2*x + 1)],
[(-x + sqrt(2)*(x - 1) - 1)/(x - 1)],
[1]
])
assert ev[2][0] == x + sqrt(2)*(x - 1) + 1
assert ev[2][1] == 1
assert ev[2][2][0].expand(deep=False, numer=True) == Matrix([
[(-x - sqrt(2)*(x - 1) - 1)/(x - 1)],
[-4*x/(x**2 - 2*x + 1) + (x + 1)*(x + sqrt(2)*(x - 1) + 1)/(x**2 - 2*x + 1)],
[(-x - sqrt(2)*(x - 1) - 1)/(x - 1)],
[1]
])
def test_issue_17247_expression_blowup_14():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
with dotprodsimp(True):
assert M.echelon_form() == Matrix([
[x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x],
[ 0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0]])
def test_issue_17247_expression_blowup_15():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
with dotprodsimp(True):
assert M.rowspace() == [Matrix([[x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x]]), Matrix([[0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x]])]
def test_issue_17247_expression_blowup_16():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
with dotprodsimp(True):
assert M.columnspace() == [Matrix([[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x]]), Matrix([[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1]])]
def test_issue_17247_expression_blowup_17():
M = Matrix(8, 8, [x+i for i in range (64)])
with dotprodsimp(True):
assert M.nullspace() == [
Matrix([[1],[-2],[1],[0],[0],[0],[0],[0]]),
Matrix([[2],[-3],[0],[1],[0],[0],[0],[0]]),
Matrix([[3],[-4],[0],[0],[1],[0],[0],[0]]),
Matrix([[4],[-5],[0],[0],[0],[1],[0],[0]]),
Matrix([[5],[-6],[0],[0],[0],[0],[1],[0]]),
Matrix([[6],[-7],[0],[0],[0],[0],[0],[1]])]
def test_issue_17247_expression_blowup_18():
M = Matrix(6, 6, ([1+x, 1-x]*3 + [1-x, 1+x]*3)*3)
with dotprodsimp(True):
assert not M.is_nilpotent()
def test_issue_17247_expression_blowup_19():
M = Matrix(S('''[
[ -3/4, 0, 1/4 + I/2, 0],
[ 0, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 1/2 - I, 0, 0, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert not M.is_diagonalizable()
def test_issue_17247_expression_blowup_20():
M = Matrix([
[x + 1, 1 - x, 0, 0],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 0],
[ 0, 0, 0, x + 1]])
with dotprodsimp(True):
assert M.diagonalize() == (Matrix([
[1, 1, 0, (x + 1)/(x - 1)],
[1, -1, 0, 0],
[1, 1, 1, 0],
[0, 0, 0, 1]]),
Matrix([
[2, 0, 0, 0],
[0, 2*x, 0, 0],
[0, 0, x + 1, 0],
[0, 0, 0, x + 1]]))
def test_issue_17247_expression_blowup_21():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='GE') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_22():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='LU') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_23():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='ADJ').expand() == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_24():
M = SparseMatrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='CH') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_25():
M = SparseMatrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.inv(method='LDL') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_26():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024],
[ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
[ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
[ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
[ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
[ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
[ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.rank() == 4
def test_issue_17247_expression_blowup_27():
M = Matrix([
[ 0, 1 - x, x + 1, 1 - x],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 1 - x],
[ 0, 0, 1 - x, 0]])
with dotprodsimp(True):
P, J = M.jordan_form()
assert P.expand() == Matrix(S('''[
[ 0, 4*x/(x**2 - 2*x + 1), -(-17*x**4 + 12*sqrt(2)*x**4 - 4*sqrt(2)*x**3 + 6*x**3 - 6*x - 4*sqrt(2)*x + 12*sqrt(2) + 17)/(-7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 + 8*x**3 - 2*x**2 + 8*x + 6*sqrt(2)*x - 5*sqrt(2) - 7), -(12*sqrt(2)*x**4 + 17*x**4 - 6*x**3 - 4*sqrt(2)*x**3 - 4*sqrt(2)*x + 6*x - 17 + 12*sqrt(2))/(7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 - 8*x**3 + 2*x**2 - 8*x + 6*sqrt(2)*x - 5*sqrt(2) + 7)],
[x - 1, x/(x - 1) + 1/(x - 1), (-7*x**3 + 5*sqrt(2)*x**3 - x**2 + sqrt(2)*x**2 - sqrt(2)*x - x - 5*sqrt(2) - 7)/(-3*x**3 + 2*sqrt(2)*x**3 - 2*sqrt(2)*x**2 + 3*x**2 + 2*sqrt(2)*x + 3*x - 3 - 2*sqrt(2)), (7*x**3 + 5*sqrt(2)*x**3 + x**2 + sqrt(2)*x**2 - sqrt(2)*x + x - 5*sqrt(2) + 7)/(2*sqrt(2)*x**3 + 3*x**3 - 3*x**2 - 2*sqrt(2)*x**2 - 3*x + 2*sqrt(2)*x - 2*sqrt(2) + 3)],
[ 0, 1, -(-3*x**2 + 2*sqrt(2)*x**2 + 2*x - 3 - 2*sqrt(2))/(-x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x + 1 + sqrt(2)), -(2*sqrt(2)*x**2 + 3*x**2 - 2*x - 2*sqrt(2) + 3)/(x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x - 1 + sqrt(2))],
[1 - x, 0, 1, 1]]''')).expand()
assert J == Matrix(S('''[
[0, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, x - sqrt(2)*(x - 1) + 1, 0],
[0, 0, 0, x + sqrt(2)*(x - 1) + 1]]'''))
def test_issue_17247_expression_blowup_28():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
with dotprodsimp(True):
assert M.singular_values() == S('''[
sqrt(14609315/131072 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2),
sqrt(14609315/131072 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2),
sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2),
sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2)]''')
def test_issue_16823():
# This still needs to be fixed if not using dotprodsimp.
M = Matrix(S('''[
[1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I,15/128-3/32*I,19/256+551/1024*I],
[21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I,129/256-549/512*I,42533/16384+29103/8192*I],
[-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I],
[1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I],
[-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I],
[1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I],
[-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I],
[-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I],
[0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I],
[1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I],
[0,-4*I,0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I],
[0,1/4+1/2*I,1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I]]'''))
with dotprodsimp(True):
assert M.rank() == 8
def test_issue_18531():
# solve_linear_system still needs fixing but the rref works.
M = Matrix([
[1, 1, 1, 1, 1, 0, 1, 0, 0],
[1 + sqrt(2), -1 + sqrt(2), 1 - sqrt(2), -sqrt(2) - 1, 1, 1, -1, 1, 1],
[-5 + 2*sqrt(2), -5 - 2*sqrt(2), -5 - 2*sqrt(2), -5 + 2*sqrt(2), -7, 2, -7, -2, 0],
[-3*sqrt(2) - 1, 1 - 3*sqrt(2), -1 + 3*sqrt(2), 1 + 3*sqrt(2), -7, -5, 7, -5, 3],
[7 - 4*sqrt(2), 4*sqrt(2) + 7, 4*sqrt(2) + 7, 7 - 4*sqrt(2), 7, -12, 7, 12, 0],
[-1 + 3*sqrt(2), 1 + 3*sqrt(2), -3*sqrt(2) - 1, 1 - 3*sqrt(2), 7, -5, -7, -5, 3],
[-3 + 2*sqrt(2), -3 - 2*sqrt(2), -3 - 2*sqrt(2), -3 + 2*sqrt(2), -1, 2, -1, -2, 0],
[1 - sqrt(2), -sqrt(2) - 1, 1 + sqrt(2), -1 + sqrt(2), -1, 1, 1, 1, 1]
])
with dotprodsimp(True):
assert M.rref() == (Matrix([
[1, 0, 0, 0, 0, 0, 0, 0, 1/2],
[0, 1, 0, 0, 0, 0, 0, 0, -1/2],
[0, 0, 1, 0, 0, 0, 0, 0, 1/2],
[0, 0, 0, 1, 0, 0, 0, 0, -1/2],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, -1/2],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, -1/2]]), (0, 1, 2, 3, 4, 5, 6, 7))
def test_creation():
raises(ValueError, lambda: Matrix(5, 5, range(20)))
raises(ValueError, lambda: Matrix(5, -1, []))
raises(IndexError, lambda: Matrix((1, 2))[2])
with raises(IndexError):
Matrix((1, 2))[3] = 5
assert Matrix() == Matrix([]) == Matrix([[]]) == Matrix(0, 0, [])
# anything used to be allowed in a matrix
with warns_deprecated_sympy():
assert Matrix([[[1], (2,)]]).tolist() == [[[1], (2,)]]
with warns_deprecated_sympy():
assert Matrix([[[1], (2,)]]).T.tolist() == [[[1]], [(2,)]]
M = Matrix([[0]])
with warns_deprecated_sympy():
M[0, 0] = S.EmptySet
a = Matrix([[x, 0], [0, 0]])
m = a
assert m.cols == m.rows
assert m.cols == 2
assert m[:] == [x, 0, 0, 0]
b = Matrix(2, 2, [x, 0, 0, 0])
m = b
assert m.cols == m.rows
assert m.cols == 2
assert m[:] == [x, 0, 0, 0]
assert a == b
assert Matrix(b) == b
c23 = Matrix(2, 3, range(1, 7))
c13 = Matrix(1, 3, range(7, 10))
c = Matrix([c23, c13])
assert c.cols == 3
assert c.rows == 3
assert c[:] == [1, 2, 3, 4, 5, 6, 7, 8, 9]
assert Matrix(eye(2)) == eye(2)
assert ImmutableMatrix(ImmutableMatrix(eye(2))) == ImmutableMatrix(eye(2))
assert ImmutableMatrix(c) == c.as_immutable()
assert Matrix(ImmutableMatrix(c)) == ImmutableMatrix(c).as_mutable()
assert c is not Matrix(c)
dat = [[ones(3,2), ones(3,3)*2], [ones(2,3)*3, ones(2,2)*4]]
M = Matrix(dat)
assert M == Matrix([
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[3, 3, 3, 4, 4],
[3, 3, 3, 4, 4]])
assert M.tolist() != dat
# keep block form if evaluate=False
assert Matrix(dat, evaluate=False).tolist() == dat
A = MatrixSymbol("A", 2, 2)
dat = [ones(2), A]
assert Matrix(dat) == Matrix([
[ 1, 1],
[ 1, 1],
[A[0, 0], A[0, 1]],
[A[1, 0], A[1, 1]]])
with warns_deprecated_sympy():
assert Matrix(dat, evaluate=False).tolist() == [[i] for i in dat]
# 0-dim tolerance
assert Matrix([ones(2), ones(0)]) == Matrix([ones(2)])
raises(ValueError, lambda: Matrix([ones(2), ones(0, 3)]))
raises(ValueError, lambda: Matrix([ones(2), ones(3, 0)]))
# mix of Matrix and iterable
M = Matrix([[1, 2], [3, 4]])
M2 = Matrix([M, (5, 6)])
assert M2 == Matrix([[1, 2], [3, 4], [5, 6]])
def test_irregular_block():
assert Matrix.irregular(3, ones(2,1), ones(3,3)*2, ones(2,2)*3,
ones(1,1)*4, ones(2,2)*5, ones(1,2)*6, ones(1,2)*7) == Matrix([
[1, 2, 2, 2, 3, 3],
[1, 2, 2, 2, 3, 3],
[4, 2, 2, 2, 5, 5],
[6, 6, 7, 7, 5, 5]])
def test_tolist():
lst = [[S.One, S.Half, x*y, S.Zero], [x, y, z, x**2], [y, -S.One, z*x, 3]]
m = Matrix(lst)
assert m.tolist() == lst
def test_as_mutable():
assert zeros(0, 3).as_mutable() == zeros(0, 3)
assert zeros(0, 3).as_immutable() == ImmutableMatrix(zeros(0, 3))
assert zeros(3, 0).as_immutable() == ImmutableMatrix(zeros(3, 0))
def test_slicing():
m0 = eye(4)
assert m0[:3, :3] == eye(3)
assert m0[2:4, 0:2] == zeros(2)
m1 = Matrix(3, 3, lambda i, j: i + j)
assert m1[0, :] == Matrix(1, 3, (0, 1, 2))
assert m1[1:3, 1] == Matrix(2, 1, (2, 3))
m2 = Matrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])
assert m2[:, -1] == Matrix(4, 1, [3, 7, 11, 15])
assert m2[-2:, :] == Matrix([[8, 9, 10, 11], [12, 13, 14, 15]])
def test_submatrix_assignment():
m = zeros(4)
m[2:4, 2:4] = eye(2)
assert m == Matrix(((0, 0, 0, 0),
(0, 0, 0, 0),
(0, 0, 1, 0),
(0, 0, 0, 1)))
m[:2, :2] = eye(2)
assert m == eye(4)
m[:, 0] = Matrix(4, 1, (1, 2, 3, 4))
assert m == Matrix(((1, 0, 0, 0),
(2, 1, 0, 0),
(3, 0, 1, 0),
(4, 0, 0, 1)))
m[:, :] = zeros(4)
assert m == zeros(4)
m[:, :] = [(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)]
assert m == Matrix(((1, 2, 3, 4),
(5, 6, 7, 8),
(9, 10, 11, 12),
(13, 14, 15, 16)))
m[:2, 0] = [0, 0]
assert m == Matrix(((0, 2, 3, 4),
(0, 6, 7, 8),
(9, 10, 11, 12),
(13, 14, 15, 16)))
def test_extract():
m = Matrix(4, 3, lambda i, j: i*3 + j)
assert m.extract([0, 1, 3], [0, 1]) == Matrix(3, 2, [0, 1, 3, 4, 9, 10])
assert m.extract([0, 3], [0, 0, 2]) == Matrix(2, 3, [0, 0, 2, 9, 9, 11])
assert m.extract(range(4), range(3)) == m
raises(IndexError, lambda: m.extract([4], [0]))
raises(IndexError, lambda: m.extract([0], [3]))
def test_reshape():
m0 = eye(3)
assert m0.reshape(1, 9) == Matrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
m1 = Matrix(3, 4, lambda i, j: i + j)
assert m1.reshape(
4, 3) == Matrix(((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)))
assert m1.reshape(2, 6) == Matrix(((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)))
def test_applyfunc():
m0 = eye(3)
assert m0.applyfunc(lambda x: 2*x) == eye(3)*2
assert m0.applyfunc(lambda x: 0) == zeros(3)
def test_expand():
m0 = Matrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]])
# Test if expand() returns a matrix
m1 = m0.expand()
assert m1 == Matrix(
[[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]])
a = Symbol('a', real=True)
assert Matrix([exp(I*a)]).expand(complex=True) == \
Matrix([cos(a) + I*sin(a)])
assert Matrix([[0, 1, 2], [0, 0, -1], [0, 0, 0]]).exp() == Matrix([
[1, 1, Rational(3, 2)],
[0, 1, -1],
[0, 0, 1]]
)
def test_refine():
m0 = Matrix([[Abs(x)**2, sqrt(x**2)],
[sqrt(x**2)*Abs(y)**2, sqrt(y**2)*Abs(x)**2]])
m1 = m0.refine(Q.real(x) & Q.real(y))
assert m1 == Matrix([[x**2, Abs(x)], [y**2*Abs(x), x**2*Abs(y)]])
m1 = m0.refine(Q.positive(x) & Q.positive(y))
assert m1 == Matrix([[x**2, x], [x*y**2, x**2*y]])
m1 = m0.refine(Q.negative(x) & Q.negative(y))
assert m1 == Matrix([[x**2, -x], [-x*y**2, -x**2*y]])
def test_random():
M = randMatrix(3, 3)
M = randMatrix(3, 3, seed=3)
assert M == randMatrix(3, 3, seed=3)
M = randMatrix(3, 4, 0, 150)
M = randMatrix(3, seed=4, symmetric=True)
assert M == randMatrix(3, seed=4, symmetric=True)
S = M.copy()
S.simplify()
assert S == M # doesn't fail when elements are Numbers, not int
rng = random.Random(4)
assert M == randMatrix(3, symmetric=True, prng=rng)
# Ensure symmetry
for size in (10, 11): # Test odd and even
for percent in (100, 70, 30):
M = randMatrix(size, symmetric=True, percent=percent, prng=rng)
assert M == M.T
M = randMatrix(10, min=1, percent=70)
zero_count = 0
for i in range(M.shape[0]):
for j in range(M.shape[1]):
if M[i, j] == 0:
zero_count += 1
assert zero_count == 30
def test_inverse():
A = eye(4)
assert A.inv() == eye(4)
assert A.inv(method="LU") == eye(4)
assert A.inv(method="ADJ") == eye(4)
assert A.inv(method="CH") == eye(4)
assert A.inv(method="LDL") == eye(4)
assert A.inv(method="QR") == eye(4)
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
Ainv = A.inv()
assert A*Ainv == eye(3)
assert A.inv(method="LU") == Ainv
assert A.inv(method="ADJ") == Ainv
assert A.inv(method="CH") == Ainv
assert A.inv(method="LDL") == Ainv
assert A.inv(method="QR") == Ainv
AA = Matrix([[0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
[1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0],
[1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
[1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0],
[1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1],
[0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0],
[1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1],
[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0],
[1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1],
[1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0],
[0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0],
[1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1],
[0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1],
[1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0]])
assert AA.inv(method="BLOCK") * AA == eye(AA.shape[0])
# test that immutability is not a problem
cls = ImmutableMatrix
m = cls([[48, 49, 31],
[ 9, 71, 94],
[59, 28, 65]])
assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split())
cls = ImmutableSparseMatrix
m = cls([[48, 49, 31],
[ 9, 71, 94],
[59, 28, 65]])
assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split())
def test_matrix_inverse_mod():
A = Matrix(2, 1, [1, 0])
raises(NonSquareMatrixError, lambda: A.inv_mod(2))
A = Matrix(2, 2, [1, 0, 0, 0])
raises(ValueError, lambda: A.inv_mod(2))
A = Matrix(2, 2, [1, 2, 3, 4])
Ai = Matrix(2, 2, [1, 1, 0, 1])
assert A.inv_mod(3) == Ai
A = Matrix(2, 2, [1, 0, 0, 1])
assert A.inv_mod(2) == A
A = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
raises(ValueError, lambda: A.inv_mod(5))
A = Matrix(3, 3, [5, 1, 3, 2, 6, 0, 2, 1, 1])
Ai = Matrix(3, 3, [6, 8, 0, 1, 5, 6, 5, 6, 4])
assert A.inv_mod(9) == Ai
A = Matrix(3, 3, [1, 6, -3, 4, 1, -5, 3, -5, 5])
Ai = Matrix(3, 3, [4, 3, 3, 1, 2, 5, 1, 5, 1])
assert A.inv_mod(6) == Ai
A = Matrix(3, 3, [1, 6, 1, 4, 1, 5, 3, 2, 5])
Ai = Matrix(3, 3, [6, 0, 3, 6, 6, 4, 1, 6, 1])
assert A.inv_mod(7) == Ai
def test_jacobian_hessian():
L = Matrix(1, 2, [x**2*y, 2*y**2 + x*y])
syms = [x, y]
assert L.jacobian(syms) == Matrix([[2*x*y, x**2], [y, 4*y + x]])
L = Matrix(1, 2, [x, x**2*y**3])
assert L.jacobian(syms) == Matrix([[1, 0], [2*x*y**3, x**2*3*y**2]])
f = x**2*y
syms = [x, y]
assert hessian(f, syms) == Matrix([[2*y, 2*x], [2*x, 0]])
f = x**2*y**3
assert hessian(f, syms) == \
Matrix([[2*y**3, 6*x*y**2], [6*x*y**2, 6*x**2*y]])
f = z + x*y**2
g = x**2 + 2*y**3
ans = Matrix([[0, 2*y],
[2*y, 2*x]])
assert ans == hessian(f, Matrix([x, y]))
assert ans == hessian(f, Matrix([x, y]).T)
assert hessian(f, (y, x), [g]) == Matrix([
[ 0, 6*y**2, 2*x],
[6*y**2, 2*x, 2*y],
[ 2*x, 2*y, 0]])
def test_wronskian():
assert wronskian([cos(x), sin(x)], x) == cos(x)**2 + sin(x)**2
assert wronskian([exp(x), exp(2*x)], x) == exp(3*x)
assert wronskian([exp(x), x], x) == exp(x) - x*exp(x)
assert wronskian([1, x, x**2], x) == 2
w1 = -6*exp(x)*sin(x)*x + 6*cos(x)*exp(x)*x**2 - 6*exp(x)*cos(x)*x - \
exp(x)*cos(x)*x**3 + exp(x)*sin(x)*x**3
assert wronskian([exp(x), cos(x), x**3], x).expand() == w1
assert wronskian([exp(x), cos(x), x**3], x, method='berkowitz').expand() \
== w1
w2 = -x**3*cos(x)**2 - x**3*sin(x)**2 - 6*x*cos(x)**2 - 6*x*sin(x)**2
assert wronskian([sin(x), cos(x), x**3], x).expand() == w2
assert wronskian([sin(x), cos(x), x**3], x, method='berkowitz').expand() \
== w2
assert wronskian([], x) == 1
def test_subs():
assert Matrix([[1, x], [x, 4]]).subs(x, 5) == Matrix([[1, 5], [5, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs([[x, -1], [y, -2]]) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs([(x, -1), (y, -2)]) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([x*y]).subs({x: y - 1, y: x - 1}, simultaneous=True) == \
Matrix([(x - 1)*(y - 1)])
for cls in classes:
assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).subs(1, 2)
def test_xreplace():
assert Matrix([[1, x], [x, 4]]).xreplace({x: 5}) == \
Matrix([[1, 5], [5, 4]])
assert Matrix([[x, 2], [x + y, 4]]).xreplace({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
for cls in classes:
assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).xreplace({1: 2})
def test_simplify():
n = Symbol('n')
f = Function('f')
M = Matrix([[ 1/x + 1/y, (x + x*y) / x ],
[ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]])
M.simplify()
assert M == Matrix([[ (x + y)/(x * y), 1 + y ],
[ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]])
eq = (1 + x)**2
M = Matrix([[eq]])
M.simplify()
assert M == Matrix([[eq]])
M.simplify(ratio=oo)
assert M == Matrix([[eq.simplify(ratio=oo)]])
def test_transpose():
M = Matrix([[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]])
assert M.T == Matrix( [ [1, 1],
[2, 2],
[3, 3],
[4, 4],
[5, 5],
[6, 6],
[7, 7],
[8, 8],
[9, 9],
[0, 0] ])
assert M.T.T == M
assert M.T == M.transpose()
def test_conjugate():
M = Matrix([[0, I, 5],
[1, 2, 0]])
assert M.T == Matrix([[0, 1],
[I, 2],
[5, 0]])
assert M.C == Matrix([[0, -I, 5],
[1, 2, 0]])
assert M.C == M.conjugate()
assert M.H == M.T.C
assert M.H == Matrix([[ 0, 1],
[-I, 2],
[ 5, 0]])
def test_conj_dirac():
raises(AttributeError, lambda: eye(3).D)
M = Matrix([[1, I, I, I],
[0, 1, I, I],
[0, 0, 1, I],
[0, 0, 0, 1]])
assert M.D == Matrix([[ 1, 0, 0, 0],
[-I, 1, 0, 0],
[-I, -I, -1, 0],
[-I, -I, I, -1]])
def test_trace():
M = Matrix([[1, 0, 0],
[0, 5, 0],
[0, 0, 8]])
assert M.trace() == 14
def test_shape():
M = Matrix([[x, 0, 0],
[0, y, 0]])
assert M.shape == (2, 3)
def test_col_row_op():
M = Matrix([[x, 0, 0],
[0, y, 0]])
M.row_op(1, lambda r, j: r + j + 1)
assert M == Matrix([[x, 0, 0],
[1, y + 2, 3]])
M.col_op(0, lambda c, j: c + y**j)
assert M == Matrix([[x + 1, 0, 0],
[1 + y, y + 2, 3]])
# neither row nor slice give copies that allow the original matrix to
# be changed
assert M.row(0) == Matrix([[x + 1, 0, 0]])
r1 = M.row(0)
r1[0] = 42
assert M[0, 0] == x + 1
r1 = M[0, :-1] # also testing negative slice
r1[0] = 42
assert M[0, 0] == x + 1
c1 = M.col(0)
assert c1 == Matrix([x + 1, 1 + y])
c1[0] = 0
assert M[0, 0] == x + 1
c1 = M[:, 0]
c1[0] = 42
assert M[0, 0] == x + 1
def test_zip_row_op():
for cls in classes[:2]: # XXX: immutable matrices don't support row ops
M = cls.eye(3)
M.zip_row_op(1, 0, lambda v, u: v + 2*u)
assert M == cls([[1, 0, 0],
[2, 1, 0],
[0, 0, 1]])
M = cls.eye(3)*2
M[0, 1] = -1
M.zip_row_op(1, 0, lambda v, u: v + 2*u); M
assert M == cls([[2, -1, 0],
[4, 0, 0],
[0, 0, 2]])
def test_issue_3950():
m = Matrix([1, 2, 3])
a = Matrix([1, 2, 3])
b = Matrix([2, 2, 3])
assert not (m in [])
assert not (m in [1])
assert m != 1
assert m == a
assert m != b
def test_issue_3981():
class Index1:
def __index__(self):
return 1
class Index2:
def __index__(self):
return 2
index1 = Index1()
index2 = Index2()
m = Matrix([1, 2, 3])
assert m[index2] == 3
m[index2] = 5
assert m[2] == 5
m = Matrix([[1, 2, 3], [4, 5, 6]])
assert m[index1, index2] == 6
assert m[1, index2] == 6
assert m[index1, 2] == 6
m[index1, index2] = 4
assert m[1, 2] == 4
m[1, index2] = 6
assert m[1, 2] == 6
m[index1, 2] = 8
assert m[1, 2] == 8
def test_evalf():
a = Matrix([sqrt(5), 6])
assert all(a.evalf()[i] == a[i].evalf() for i in range(2))
assert all(a.evalf(2)[i] == a[i].evalf(2) for i in range(2))
assert all(a.n(2)[i] == a[i].n(2) for i in range(2))
def test_is_symbolic():
a = Matrix([[x, x], [x, x]])
assert a.is_symbolic() is True
a = Matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
assert a.is_symbolic() is False
a = Matrix([[1, 2, 3, 4], [5, 6, x, 8]])
assert a.is_symbolic() is True
a = Matrix([[1, x, 3]])
assert a.is_symbolic() is True
a = Matrix([[1, 2, 3]])
assert a.is_symbolic() is False
a = Matrix([[1], [x], [3]])
assert a.is_symbolic() is True
a = Matrix([[1], [2], [3]])
assert a.is_symbolic() is False
def test_is_upper():
a = Matrix([[1, 2, 3]])
assert a.is_upper is True
a = Matrix([[1], [2], [3]])
assert a.is_upper is False
a = zeros(4, 2)
assert a.is_upper is True
def test_is_lower():
a = Matrix([[1, 2, 3]])
assert a.is_lower is False
a = Matrix([[1], [2], [3]])
assert a.is_lower is True
def test_is_nilpotent():
a = Matrix(4, 4, [0, 2, 1, 6, 0, 0, 1, 2, 0, 0, 0, 3, 0, 0, 0, 0])
assert a.is_nilpotent()
a = Matrix([[1, 0], [0, 1]])
assert not a.is_nilpotent()
a = Matrix([])
assert a.is_nilpotent()
def test_zeros_ones_fill():
n, m = 3, 5
a = zeros(n, m)
a.fill( 5 )
b = 5 * ones(n, m)
assert a == b
assert a.rows == b.rows == 3
assert a.cols == b.cols == 5
assert a.shape == b.shape == (3, 5)
assert zeros(2) == zeros(2, 2)
assert ones(2) == ones(2, 2)
assert zeros(2, 3) == Matrix(2, 3, [0]*6)
assert ones(2, 3) == Matrix(2, 3, [1]*6)
a.fill(0)
assert a == zeros(n, m)
def test_empty_zeros():
a = zeros(0)
assert a == Matrix()
a = zeros(0, 2)
assert a.rows == 0
assert a.cols == 2
a = zeros(2, 0)
assert a.rows == 2
assert a.cols == 0
def test_issue_3749():
a = Matrix([[x**2, x*y], [x*sin(y), x*cos(y)]])
assert a.diff(x) == Matrix([[2*x, y], [sin(y), cos(y)]])
assert Matrix([
[x, -x, x**2],
[exp(x), 1/x - exp(-x), x + 1/x]]).limit(x, oo) == \
Matrix([[oo, -oo, oo], [oo, 0, oo]])
assert Matrix([
[(exp(x) - 1)/x, 2*x + y*x, x**x ],
[1/x, abs(x), abs(sin(x + 1))]]).limit(x, 0) == \
Matrix([[1, 0, 1], [oo, 0, sin(1)]])
assert a.integrate(x) == Matrix([
[Rational(1, 3)*x**3, y*x**2/2],
[x**2*sin(y)/2, x**2*cos(y)/2]])
def test_inv_iszerofunc():
A = eye(4)
A.col_swap(0, 1)
for method in "GE", "LU":
assert A.inv(method=method, iszerofunc=lambda x: x == 0) == \
A.inv(method="ADJ")
def test_jacobian_metrics():
rho, phi = symbols("rho,phi")
X = Matrix([rho*cos(phi), rho*sin(phi)])
Y = Matrix([rho, phi])
J = X.jacobian(Y)
assert J == X.jacobian(Y.T)
assert J == (X.T).jacobian(Y)
assert J == (X.T).jacobian(Y.T)
g = J.T*eye(J.shape[0])*J
g = g.applyfunc(trigsimp)
assert g == Matrix([[1, 0], [0, rho**2]])
def test_jacobian2():
rho, phi = symbols("rho,phi")
X = Matrix([rho*cos(phi), rho*sin(phi), rho**2])
Y = Matrix([rho, phi])
J = Matrix([
[cos(phi), -rho*sin(phi)],
[sin(phi), rho*cos(phi)],
[ 2*rho, 0],
])
assert X.jacobian(Y) == J
def test_issue_4564():
X = Matrix([exp(x + y + z), exp(x + y + z), exp(x + y + z)])
Y = Matrix([x, y, z])
for i in range(1, 3):
for j in range(1, 3):
X_slice = X[:i, :]
Y_slice = Y[:j, :]
J = X_slice.jacobian(Y_slice)
assert J.rows == i
assert J.cols == j
for k in range(j):
assert J[:, k] == X_slice
def test_nonvectorJacobian():
X = Matrix([[exp(x + y + z), exp(x + y + z)],
[exp(x + y + z), exp(x + y + z)]])
raises(TypeError, lambda: X.jacobian(Matrix([x, y, z])))
X = X[0, :]
Y = Matrix([[x, y], [x, z]])
raises(TypeError, lambda: X.jacobian(Y))
raises(TypeError, lambda: X.jacobian(Matrix([ [x, y], [x, z] ])))
def test_vec():
m = Matrix([[1, 3], [2, 4]])
m_vec = m.vec()
assert m_vec.cols == 1
for i in range(4):
assert m_vec[i] == i + 1
def test_vech():
m = Matrix([[1, 2], [2, 3]])
m_vech = m.vech()
assert m_vech.cols == 1
for i in range(3):
assert m_vech[i] == i + 1
m_vech = m.vech(diagonal=False)
assert m_vech[0] == 2
m = Matrix([[1, x*(x + y)], [y*x + x**2, 1]])
m_vech = m.vech(diagonal=False)
assert m_vech[0] == y*x + x**2
m = Matrix([[1, x*(x + y)], [y*x, 1]])
m_vech = m.vech(diagonal=False, check_symmetry=False)
assert m_vech[0] == y*x
raises(ShapeError, lambda: Matrix([[1, 3]]).vech())
raises(ValueError, lambda: Matrix([[1, 3], [2, 4]]).vech())
raises(ShapeError, lambda: Matrix([[1, 3]]).vech())
raises(ValueError, lambda: Matrix([[1, 3], [2, 4]]).vech())
def test_diag():
# mostly tested in testcommonmatrix.py
assert diag([1, 2, 3]) == Matrix([1, 2, 3])
m = [1, 2, [3]]
raises(ValueError, lambda: diag(m))
assert diag(m, strict=False) == Matrix([1, 2, 3])
def test_get_diag_blocks1():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert a.get_diag_blocks() == [a]
assert b.get_diag_blocks() == [b]
assert c.get_diag_blocks() == [c]
def test_get_diag_blocks2():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert diag(a, b, b).get_diag_blocks() == [a, b, b]
assert diag(a, b, c).get_diag_blocks() == [a, b, c]
assert diag(a, c, b).get_diag_blocks() == [a, c, b]
assert diag(c, c, b).get_diag_blocks() == [c, c, b]
def test_inv_block():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
A = diag(a, b, b)
assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), b.inv())
A = diag(a, b, c)
assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), c.inv())
A = diag(a, c, b)
assert A.inv(try_block_diag=True) == diag(a.inv(), c.inv(), b.inv())
A = diag(a, a, b, a, c, a)
assert A.inv(try_block_diag=True) == diag(
a.inv(), a.inv(), b.inv(), a.inv(), c.inv(), a.inv())
assert A.inv(try_block_diag=True, method="ADJ") == diag(
a.inv(method="ADJ"), a.inv(method="ADJ"), b.inv(method="ADJ"),
a.inv(method="ADJ"), c.inv(method="ADJ"), a.inv(method="ADJ"))
def test_creation_args():
"""
Check that matrix dimensions can be specified using any reasonable type
(see issue 4614).
"""
raises(ValueError, lambda: zeros(3, -1))
raises(TypeError, lambda: zeros(1, 2, 3, 4))
assert zeros(int(3)) == zeros(3)
assert zeros(Integer(3)) == zeros(3)
raises(ValueError, lambda: zeros(3.))
assert eye(int(3)) == eye(3)
assert eye(Integer(3)) == eye(3)
raises(ValueError, lambda: eye(3.))
assert ones(int(3), Integer(4)) == ones(3, 4)
raises(TypeError, lambda: Matrix(5))
raises(TypeError, lambda: Matrix(1, 2))
raises(ValueError, lambda: Matrix([1, [2]]))
def test_diagonal_symmetrical():
m = Matrix(2, 2, [0, 1, 1, 0])
assert not m.is_diagonal()
assert m.is_symmetric()
assert m.is_symmetric(simplify=False)
m = Matrix(2, 2, [1, 0, 0, 1])
assert m.is_diagonal()
m = diag(1, 2, 3)
assert m.is_diagonal()
assert m.is_symmetric()
m = Matrix(3, 3, [1, 0, 0, 0, 2, 0, 0, 0, 3])
assert m == diag(1, 2, 3)
m = Matrix(2, 3, zeros(2, 3))
assert not m.is_symmetric()
assert m.is_diagonal()
m = Matrix(((5, 0), (0, 6), (0, 0)))
assert m.is_diagonal()
m = Matrix(((5, 0, 0), (0, 6, 0)))
assert m.is_diagonal()
m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3])
assert m.is_symmetric()
assert not m.is_symmetric(simplify=False)
assert m.expand().is_symmetric(simplify=False)
def test_diagonalization():
m = Matrix([[1, 2+I], [2-I, 3]])
assert m.is_diagonalizable()
m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10])
assert not m.is_diagonalizable()
assert not m.is_symmetric()
raises(NonSquareMatrixError, lambda: m.diagonalize())
# diagonalizable
m = diag(1, 2, 3)
(P, D) = m.diagonalize()
assert P == eye(3)
assert D == m
m = Matrix(2, 2, [0, 1, 1, 0])
assert m.is_symmetric()
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
m = Matrix(2, 2, [1, 0, 0, 3])
assert m.is_symmetric()
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
assert P == eye(2)
assert D == m
m = Matrix(2, 2, [1, 1, 0, 0])
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
for i in P:
assert i.as_numer_denom()[1] == 1
m = Matrix(2, 2, [1, 0, 0, 0])
assert m.is_diagonal()
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
assert P == Matrix([[0, 1], [1, 0]])
# diagonalizable, complex only
m = Matrix(2, 2, [0, 1, -1, 0])
assert not m.is_diagonalizable(True)
raises(MatrixError, lambda: m.diagonalize(True))
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
# not diagonalizable
m = Matrix(2, 2, [0, 1, 0, 0])
assert not m.is_diagonalizable()
raises(MatrixError, lambda: m.diagonalize())
m = Matrix(3, 3, [-3, 1, -3, 20, 3, 10, 2, -2, 4])
assert not m.is_diagonalizable()
raises(MatrixError, lambda: m.diagonalize())
# symbolic
a, b, c, d = symbols('a b c d')
m = Matrix(2, 2, [a, c, c, b])
assert m.is_symmetric()
assert m.is_diagonalizable()
def test_issue_15887():
# Mutable matrix should not use cache
a = MutableDenseMatrix([[0, 1], [1, 0]])
assert a.is_diagonalizable() is True
a[1, 0] = 0
assert a.is_diagonalizable() is False
a = MutableDenseMatrix([[0, 1], [1, 0]])
a.diagonalize()
a[1, 0] = 0
raises(MatrixError, lambda: a.diagonalize())
# Test deprecated cache and kwargs
with warns_deprecated_sympy():
a.is_diagonalizable(clear_cache=True)
with warns_deprecated_sympy():
a.is_diagonalizable(clear_subproducts=True)
def test_jordan_form():
m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10])
raises(NonSquareMatrixError, lambda: m.jordan_form())
# diagonalizable
m = Matrix(3, 3, [7, -12, 6, 10, -19, 10, 12, -24, 13])
Jmust = Matrix(3, 3, [-1, 0, 0, 0, 1, 0, 0, 0, 1])
P, J = m.jordan_form()
assert Jmust == J
assert Jmust == m.diagonalize()[1]
# m = Matrix(3, 3, [0, 6, 3, 1, 3, 1, -2, 2, 1])
# m.jordan_form() # very long
# m.jordan_form() #
# diagonalizable, complex only
# Jordan cells
# complexity: one of eigenvalues is zero
m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2])
# The blocks are ordered according to the value of their eigenvalues,
# in order to make the matrix compatible with .diagonalize()
Jmust = Matrix(3, 3, [2, 1, 0, 0, 2, 0, 0, 0, 2])
P, J = m.jordan_form()
assert Jmust == J
# complexity: all of eigenvalues are equal
m = Matrix(3, 3, [2, 6, -15, 1, 1, -5, 1, 2, -6])
# Jmust = Matrix(3, 3, [-1, 0, 0, 0, -1, 1, 0, 0, -1])
# same here see 1456ff
Jmust = Matrix(3, 3, [-1, 1, 0, 0, -1, 0, 0, 0, -1])
P, J = m.jordan_form()
assert Jmust == J
# complexity: two of eigenvalues are zero
m = Matrix(3, 3, [4, -5, 2, 5, -7, 3, 6, -9, 4])
Jmust = Matrix(3, 3, [0, 1, 0, 0, 0, 0, 0, 0, 1])
P, J = m.jordan_form()
assert Jmust == J
m = Matrix(4, 4, [6, 5, -2, -3, -3, -1, 3, 3, 2, 1, -2, -3, -1, 1, 5, 5])
Jmust = Matrix(4, 4, [2, 1, 0, 0,
0, 2, 0, 0,
0, 0, 2, 1,
0, 0, 0, 2]
)
P, J = m.jordan_form()
assert Jmust == J
m = Matrix(4, 4, [6, 2, -8, -6, -3, 2, 9, 6, 2, -2, -8, -6, -1, 0, 3, 4])
# Jmust = Matrix(4, 4, [2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, -2])
# same here see 1456ff
Jmust = Matrix(4, 4, [-2, 0, 0, 0,
0, 2, 1, 0,
0, 0, 2, 0,
0, 0, 0, 2])
P, J = m.jordan_form()
assert Jmust == J
m = Matrix(4, 4, [5, 4, 2, 1, 0, 1, -1, -1, -1, -1, 3, 0, 1, 1, -1, 2])
assert not m.is_diagonalizable()
Jmust = Matrix(4, 4, [1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 4, 1, 0, 0, 0, 4])
P, J = m.jordan_form()
assert Jmust == J
# checking for maximum precision to remain unchanged
m = Matrix([[Float('1.0', precision=110), Float('2.0', precision=110)],
[Float('3.14159265358979323846264338327', precision=110), Float('4.0', precision=110)]])
P, J = m.jordan_form()
for term in J.values():
if isinstance(term, Float):
assert term._prec == 110
def test_jordan_form_complex_issue_9274():
A = Matrix([[ 2, 4, 1, 0],
[-4, 2, 0, 1],
[ 0, 0, 2, 4],
[ 0, 0, -4, 2]])
p = 2 - 4*I;
q = 2 + 4*I;
Jmust1 = Matrix([[p, 1, 0, 0],
[0, p, 0, 0],
[0, 0, q, 1],
[0, 0, 0, q]])
Jmust2 = Matrix([[q, 1, 0, 0],
[0, q, 0, 0],
[0, 0, p, 1],
[0, 0, 0, p]])
P, J = A.jordan_form()
assert J == Jmust1 or J == Jmust2
assert simplify(P*J*P.inv()) == A
def test_issue_10220():
# two non-orthogonal Jordan blocks with eigenvalue 1
M = Matrix([[1, 0, 0, 1],
[0, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1]])
P, J = M.jordan_form()
assert P == Matrix([[0, 1, 0, 1],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]])
assert J == Matrix([
[1, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
def test_jordan_form_issue_15858():
A = Matrix([
[1, 1, 1, 0],
[-2, -1, 0, -1],
[0, 0, -1, -1],
[0, 0, 2, 1]])
(P, J) = A.jordan_form()
assert P.expand() == Matrix([
[ -I, -I/2, I, I/2],
[-1 + I, 0, -1 - I, 0],
[ 0, -S(1)/2 - I/2, 0, -S(1)/2 + I/2],
[ 0, 1, 0, 1]])
assert J == Matrix([
[-I, 1, 0, 0],
[0, -I, 0, 0],
[0, 0, I, 1],
[0, 0, 0, I]])
def test_Matrix_berkowitz_charpoly():
UA, K_i, K_w = symbols('UA K_i K_w')
A = Matrix([[-K_i - UA + K_i**2/(K_i + K_w), K_i*K_w/(K_i + K_w)],
[ K_i*K_w/(K_i + K_w), -K_w + K_w**2/(K_i + K_w)]])
charpoly = A.charpoly(x)
assert charpoly == \
Poly(x**2 + (K_i*UA + K_w*UA + 2*K_i*K_w)/(K_i + K_w)*x +
K_i*K_w*UA/(K_i + K_w), x, domain='ZZ(K_i,K_w,UA)')
assert type(charpoly) is PurePoly
A = Matrix([[1, 3], [2, 0]])
assert A.charpoly() == A.charpoly(x) == PurePoly(x**2 - x - 6)
A = Matrix([[1, 2], [x, 0]])
p = A.charpoly(x)
assert p.gen != x
assert p.as_expr().subs(p.gen, x) == x**2 - 3*x
def test_exp_jordan_block():
l = Symbol('lamda')
m = Matrix.jordan_block(1, l)
assert m._eval_matrix_exp_jblock() == Matrix([[exp(l)]])
m = Matrix.jordan_block(3, l)
assert m._eval_matrix_exp_jblock() == \
Matrix([
[exp(l), exp(l), exp(l)/2],
[0, exp(l), exp(l)],
[0, 0, exp(l)]])
def test_exp():
m = Matrix([[3, 4], [0, -2]])
m_exp = Matrix([[exp(3), -4*exp(-2)/5 + 4*exp(3)/5], [0, exp(-2)]])
assert m.exp() == m_exp
assert exp(m) == m_exp
m = Matrix([[1, 0], [0, 1]])
assert m.exp() == Matrix([[E, 0], [0, E]])
assert exp(m) == Matrix([[E, 0], [0, E]])
m = Matrix([[1, -1], [1, 1]])
assert m.exp() == Matrix([[E*cos(1), -E*sin(1)], [E*sin(1), E*cos(1)]])
def test_log():
l = Symbol('lamda')
m = Matrix.jordan_block(1, l)
assert m._eval_matrix_log_jblock() == Matrix([[log(l)]])
m = Matrix.jordan_block(4, l)
assert m._eval_matrix_log_jblock() == \
Matrix(
[
[log(l), 1/l, -1/(2*l**2), 1/(3*l**3)],
[0, log(l), 1/l, -1/(2*l**2)],
[0, 0, log(l), 1/l],
[0, 0, 0, log(l)]
]
)
m = Matrix(
[[0, 0, 1],
[0, 0, 0],
[-1, 0, 0]]
)
raises(MatrixError, lambda: m.log())
def test_has():
A = Matrix(((x, y), (2, 3)))
assert A.has(x)
assert not A.has(z)
assert A.has(Symbol)
A = A.subs(x, 2)
assert not A.has(x)
def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero1():
# Test if matrices._find_reasonable_pivot_naive()
# finds a guaranteed non-zero pivot when the
# some of the candidate pivots are symbolic expressions.
# Keyword argument: simpfunc=None indicates that no simplifications
# should be performed during the search.
x = Symbol('x')
column = Matrix(3, 1, [x, cos(x)**2 + sin(x)**2, S.Half])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column)
assert pivot_val == S.Half
def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero2():
# Test if matrices._find_reasonable_pivot_naive()
# finds a guaranteed non-zero pivot when the
# some of the candidate pivots are symbolic expressions.
# Keyword argument: simpfunc=_simplify indicates that the search
# should attempt to simplify candidate pivots.
x = Symbol('x')
column = Matrix(3, 1,
[x,
cos(x)**2+sin(x)**2+x**2,
cos(x)**2+sin(x)**2])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column, simpfunc=_simplify)
assert pivot_val == 1
def test_find_reasonable_pivot_naive_simplifies():
# Test if matrices._find_reasonable_pivot_naive()
# simplifies candidate pivots, and reports
# their offsets correctly.
x = Symbol('x')
column = Matrix(3, 1,
[x,
cos(x)**2+sin(x)**2+x,
cos(x)**2+sin(x)**2])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column, simpfunc=_simplify)
assert len(simplified) == 2
assert simplified[0][0] == 1
assert simplified[0][1] == 1+x
assert simplified[1][0] == 2
assert simplified[1][1] == 1
def test_errors():
raises(ValueError, lambda: Matrix([[1, 2], [1]]))
raises(IndexError, lambda: Matrix([[1, 2]])[1.2, 5])
raises(IndexError, lambda: Matrix([[1, 2]])[1, 5.2])
raises(ValueError, lambda: randMatrix(3, c=4, symmetric=True))
raises(ValueError, lambda: Matrix([1, 2]).reshape(4, 6))
raises(ShapeError,
lambda: Matrix([[1, 2], [3, 4]]).copyin_matrix([1, 0], Matrix([1, 2])))
raises(TypeError, lambda: Matrix([[1, 2], [3, 4]]).copyin_list([0,
1], set()))
raises(NonSquareMatrixError, lambda: Matrix([[1, 2, 3], [2, 3, 0]]).inv())
raises(ShapeError,
lambda: Matrix(1, 2, [1, 2]).row_join(Matrix([[1, 2], [3, 4]])))
raises(
ShapeError, lambda: Matrix([1, 2]).col_join(Matrix([[1, 2], [3, 4]])))
raises(ShapeError, lambda: Matrix([1]).row_insert(1, Matrix([[1,
2], [3, 4]])))
raises(ShapeError, lambda: Matrix([1]).col_insert(1, Matrix([[1,
2], [3, 4]])))
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).trace())
raises(TypeError, lambda: Matrix([1]).applyfunc(1))
raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor(4, 5))
raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor_submatrix(4, 5))
raises(TypeError, lambda: Matrix([1, 2, 3]).cross(1))
raises(TypeError, lambda: Matrix([1, 2, 3]).dot(1))
raises(ShapeError, lambda: Matrix([1, 2, 3]).dot(Matrix([1, 2])))
raises(ShapeError, lambda: Matrix([1, 2]).dot([]))
raises(TypeError, lambda: Matrix([1, 2]).dot('a'))
with warns_deprecated_sympy():
Matrix([[1, 2], [3, 4]]).dot(Matrix([[4, 3], [1, 2]]))
raises(ShapeError, lambda: Matrix([1, 2]).dot([1, 2, 3]))
raises(NonSquareMatrixError, lambda: Matrix([1, 2, 3]).exp())
raises(ShapeError, lambda: Matrix([[1, 2], [3, 4]]).normalized())
raises(ValueError, lambda: Matrix([1, 2]).inv(method='not a method'))
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_GE())
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_GE())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_ADJ())
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_ADJ())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_LU())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).is_nilpotent())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).det())
raises(ValueError,
lambda: Matrix([[1, 2], [3, 4]]).det(method='Not a real method'))
raises(ValueError,
lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8],
[9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc="Not function"))
raises(ValueError,
lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8],
[9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc=False))
raises(ValueError,
lambda: hessian(Matrix([[1, 2], [3, 4]]), Matrix([[1, 2], [2, 1]])))
raises(ValueError, lambda: hessian(Matrix([[1, 2], [3, 4]]), []))
raises(ValueError, lambda: hessian(Symbol('x')**2, 'a'))
raises(IndexError, lambda: eye(3)[5, 2])
raises(IndexError, lambda: eye(3)[2, 5])
M = Matrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)))
raises(ValueError, lambda: M.det('method=LU_decomposition()'))
V = Matrix([[10, 10, 10]])
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(ValueError, lambda: M.row_insert(4.7, V))
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(ValueError, lambda: M.col_insert(-4.2, V))
def test_len():
assert len(Matrix()) == 0
assert len(Matrix([[1, 2]])) == len(Matrix([[1], [2]])) == 2
assert len(Matrix(0, 2, lambda i, j: 0)) == \
len(Matrix(2, 0, lambda i, j: 0)) == 0
assert len(Matrix([[0, 1, 2], [3, 4, 5]])) == 6
assert Matrix([1]) == Matrix([[1]])
assert not Matrix()
assert Matrix() == Matrix([])
def test_integrate():
A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2)))
assert A.integrate(x) == \
Matrix(((x, 4*x, x**2/2), (x*y, 2*x, 4*x), (10*x, 5*x, x**3/3)))
assert A.integrate(y) == \
Matrix(((y, 4*y, x*y), (y**2/2, 2*y, 4*y), (10*y, 5*y, y*x**2)))
def test_limit():
A = Matrix(((1, 4, sin(x)/x), (y, 2, 4), (10, 5, x**2 + 1)))
assert A.limit(x, 0) == Matrix(((1, 4, 1), (y, 2, 4), (10, 5, 1)))
def test_diff():
A = MutableDenseMatrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1)))
assert isinstance(A.diff(x), type(A))
assert A.diff(x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert A.diff(y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
assert diff(A, x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert diff(A, y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
A_imm = A.as_immutable()
assert isinstance(A_imm.diff(x), type(A_imm))
assert A_imm.diff(x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert A_imm.diff(y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
assert diff(A_imm, x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert diff(A_imm, y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
def test_diff_by_matrix():
# Derive matrix by matrix:
A = MutableDenseMatrix([[x, y], [z, t]])
assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
assert diff(A, A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
A_imm = A.as_immutable()
assert A_imm.diff(A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
assert diff(A_imm, A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
# Derive a constant matrix:
assert A.diff(a) == MutableDenseMatrix([[0, 0], [0, 0]])
B = ImmutableDenseMatrix([a, b])
assert A.diff(B) == Array.zeros(2, 1, 2, 2)
assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
# Test diff with tuples:
dB = B.diff([[a, b]])
assert dB.shape == (2, 2, 1)
assert dB == Array([[[1], [0]], [[0], [1]]])
f = Function("f")
fxyz = f(x, y, z)
assert fxyz.diff([[x, y, z]]) == Array([fxyz.diff(x), fxyz.diff(y), fxyz.diff(z)])
assert fxyz.diff(([x, y, z], 2)) == Array([
[fxyz.diff(x, 2), fxyz.diff(x, y), fxyz.diff(x, z)],
[fxyz.diff(x, y), fxyz.diff(y, 2), fxyz.diff(y, z)],
[fxyz.diff(x, z), fxyz.diff(z, y), fxyz.diff(z, 2)],
])
expr = sin(x)*exp(y)
assert expr.diff([[x, y]]) == Array([cos(x)*exp(y), sin(x)*exp(y)])
assert expr.diff(y, ((x, y),)) == Array([cos(x)*exp(y), sin(x)*exp(y)])
assert expr.diff(x, ((x, y),)) == Array([-sin(x)*exp(y), cos(x)*exp(y)])
assert expr.diff(((y, x),), [[x, y]]) == Array([[cos(x)*exp(y), -sin(x)*exp(y)], [sin(x)*exp(y), cos(x)*exp(y)]])
# Test different notations:
assert fxyz.diff(x).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[0, 1, 0]
assert fxyz.diff(z).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[2, 1, 0]
assert fxyz.diff([[x, y, z]], ((z, y, x),)) == Array([[fxyz.diff(i).diff(j) for i in (x, y, z)] for j in (z, y, x)])
# Test scalar derived by matrix remains matrix:
res = x.diff(Matrix([[x, y]]))
assert isinstance(res, ImmutableDenseMatrix)
assert res == Matrix([[1, 0]])
res = (x**3).diff(Matrix([[x, y]]))
assert isinstance(res, ImmutableDenseMatrix)
assert res == Matrix([[3*x**2, 0]])
def test_getattr():
A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1)))
raises(AttributeError, lambda: A.nonexistantattribute)
assert getattr(A, 'diff')(x) == Matrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
def test_hessenberg():
A = Matrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]])
assert A.is_upper_hessenberg
A = A.T
assert A.is_lower_hessenberg
A[0, -1] = 1
assert A.is_lower_hessenberg is False
A = Matrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]])
assert not A.is_upper_hessenberg
A = zeros(5, 2)
assert A.is_upper_hessenberg
def test_cholesky():
raises(NonSquareMatrixError, lambda: Matrix((1, 2)).cholesky())
raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky())
raises(ValueError, lambda: Matrix(((5 + I, 0), (0, 1))).cholesky())
raises(ValueError, lambda: Matrix(((1, 5), (5, 1))).cholesky())
raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky(hermitian=False))
assert Matrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([
[sqrt(5 + I), 0], [0, 1]])
A = Matrix(((1, 5), (5, 1)))
L = A.cholesky(hermitian=False)
assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]])
assert L*L.T == A
A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
L = A.cholesky()
assert L * L.T == A
assert L.is_lower
assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]])
A = Matrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11)))
assert A.cholesky().expand() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3)))
raises(NonSquareMatrixError, lambda: SparseMatrix((1, 2)).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky())
raises(ValueError, lambda: SparseMatrix(((5 + I, 0), (0, 1))).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 5), (5, 1))).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky(hermitian=False))
assert SparseMatrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([
[sqrt(5 + I), 0], [0, 1]])
A = SparseMatrix(((1, 5), (5, 1)))
L = A.cholesky(hermitian=False)
assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]])
assert L*L.T == A
A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
L = A.cholesky()
assert L * L.T == A
assert L.is_lower
assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]])
A = SparseMatrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11)))
assert A.cholesky() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3)))
def test_matrix_norm():
# Vector Tests
# Test columns and symbols
x = Symbol('x', real=True)
v = Matrix([cos(x), sin(x)])
assert trigsimp(v.norm(2)) == 1
assert v.norm(10) == Pow(cos(x)**10 + sin(x)**10, Rational(1, 10))
# Test Rows
A = Matrix([[5, Rational(3, 2)]])
assert A.norm() == Pow(25 + Rational(9, 4), S.Half)
assert A.norm(oo) == max(A)
assert A.norm(-oo) == min(A)
# Matrix Tests
# Intuitive test
A = Matrix([[1, 1], [1, 1]])
assert A.norm(2) == 2
assert A.norm(-2) == 0
assert A.norm('frobenius') == 2
assert eye(10).norm(2) == eye(10).norm(-2) == 1
assert A.norm(oo) == 2
# Test with Symbols and more complex entries
A = Matrix([[3, y, y], [x, S.Half, -pi]])
assert (A.norm('fro')
== sqrt(Rational(37, 4) + 2*abs(y)**2 + pi**2 + x**2))
# Check non-square
A = Matrix([[1, 2, -3], [4, 5, Rational(13, 2)]])
assert A.norm(2) == sqrt(Rational(389, 8) + sqrt(78665)/8)
assert A.norm(-2) is S.Zero
assert A.norm('frobenius') == sqrt(389)/2
# Test properties of matrix norms
# https://en.wikipedia.org/wiki/Matrix_norm#Definition
# Two matrices
A = Matrix([[1, 2], [3, 4]])
B = Matrix([[5, 5], [-2, 2]])
C = Matrix([[0, -I], [I, 0]])
D = Matrix([[1, 0], [0, -1]])
L = [A, B, C, D]
alpha = Symbol('alpha', real=True)
for order in ['fro', 2, -2]:
# Zero Check
assert zeros(3).norm(order) is S.Zero
# Check Triangle Inequality for all Pairs of Matrices
for X in L:
for Y in L:
dif = (X.norm(order) + Y.norm(order) -
(X + Y).norm(order))
assert (dif >= 0)
# Scalar multiplication linearity
for M in [A, B, C, D]:
dif = simplify((alpha*M).norm(order) -
abs(alpha) * M.norm(order))
assert dif == 0
# Test Properties of Vector Norms
# https://en.wikipedia.org/wiki/Vector_norm
# Two column vectors
a = Matrix([1, 1 - 1*I, -3])
b = Matrix([S.Half, 1*I, 1])
c = Matrix([-1, -1, -1])
d = Matrix([3, 2, I])
e = Matrix([Integer(1e2), Rational(1, 1e2), 1])
L = [a, b, c, d, e]
alpha = Symbol('alpha', real=True)
for order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity, pi]:
# Zero Check
if order > 0:
assert Matrix([0, 0, 0]).norm(order) is S.Zero
# Triangle inequality on all pairs
if order >= 1: # Triangle InEq holds only for these norms
for X in L:
for Y in L:
dif = (X.norm(order) + Y.norm(order) -
(X + Y).norm(order))
assert simplify(dif >= 0) is S.true
# Linear to scalar multiplication
if order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity]:
for X in L:
dif = simplify((alpha*X).norm(order) -
(abs(alpha) * X.norm(order)))
assert dif == 0
# ord=1
M = Matrix(3, 3, [1, 3, 0, -2, -1, 0, 3, 9, 6])
assert M.norm(1) == 13
def test_condition_number():
x = Symbol('x', real=True)
A = eye(3)
A[0, 0] = 10
A[2, 2] = Rational(1, 10)
assert A.condition_number() == 100
A[1, 1] = x
assert A.condition_number() == Max(10, Abs(x)) / Min(Rational(1, 10), Abs(x))
M = Matrix([[cos(x), sin(x)], [-sin(x), cos(x)]])
Mc = M.condition_number()
assert all(Float(1.).epsilon_eq(Mc.subs(x, val).evalf()) for val in
[Rational(1, 5), S.Half, Rational(1, 10), pi/2, pi, pi*Rational(7, 4) ])
#issue 10782
assert Matrix([]).condition_number() == 0
def test_equality():
A = Matrix(((1, 2, 3), (4, 5, 6), (7, 8, 9)))
B = Matrix(((9, 8, 7), (6, 5, 4), (3, 2, 1)))
assert A == A[:, :]
assert not A != A[:, :]
assert not A == B
assert A != B
assert A != 10
assert not A == 10
# A SparseMatrix can be equal to a Matrix
C = SparseMatrix(((1, 0, 0), (0, 1, 0), (0, 0, 1)))
D = Matrix(((1, 0, 0), (0, 1, 0), (0, 0, 1)))
assert C == D
assert not C != D
def test_col_join():
assert eye(3).col_join(Matrix([[7, 7, 7]])) == \
Matrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[7, 7, 7]])
def test_row_insert():
r4 = Matrix([[4, 4, 4]])
for i in range(-4, 5):
l = [1, 0, 0]
l.insert(i, 4)
assert flatten(eye(3).row_insert(i, r4).col(0).tolist()) == l
def test_col_insert():
c4 = Matrix([4, 4, 4])
for i in range(-4, 5):
l = [0, 0, 0]
l.insert(i, 4)
assert flatten(zeros(3).col_insert(i, c4).row(0).tolist()) == l
def test_normalized():
assert Matrix([3, 4]).normalized() == \
Matrix([Rational(3, 5), Rational(4, 5)])
# Zero vector trivial cases
assert Matrix([0, 0, 0]).normalized() == Matrix([0, 0, 0])
# Machine precision error truncation trivial cases
m = Matrix([0,0,1.e-100])
assert m.normalized(
iszerofunc=lambda x: x.evalf(n=10, chop=True).is_zero
) == Matrix([0, 0, 0])
def test_print_nonzero():
assert capture(lambda: eye(3).print_nonzero()) == \
'[X ]\n[ X ]\n[ X]\n'
assert capture(lambda: eye(3).print_nonzero('.')) == \
'[. ]\n[ . ]\n[ .]\n'
def test_zeros_eye():
assert Matrix.eye(3) == eye(3)
assert Matrix.zeros(3) == zeros(3)
assert ones(3, 4) == Matrix(3, 4, [1]*12)
i = Matrix([[1, 0], [0, 1]])
z = Matrix([[0, 0], [0, 0]])
for cls in classes:
m = cls.eye(2)
assert i == m # but m == i will fail if m is immutable
assert i == eye(2, cls=cls)
assert type(m) == cls
m = cls.zeros(2)
assert z == m
assert z == zeros(2, cls=cls)
assert type(m) == cls
def test_is_zero():
assert Matrix().is_zero_matrix
assert Matrix([[0, 0], [0, 0]]).is_zero_matrix
assert zeros(3, 4).is_zero_matrix
assert not eye(3).is_zero_matrix
assert Matrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert SparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert ImmutableMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert ImmutableSparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert Matrix([[x, 1], [0, 0]]).is_zero_matrix == False
a = Symbol('a', nonzero=True)
assert Matrix([[a, 0], [0, 0]]).is_zero_matrix == False
def test_rotation_matrices():
# This tests the rotation matrices by rotating about an axis and back.
theta = pi/3
r3_plus = rot_axis3(theta)
r3_minus = rot_axis3(-theta)
r2_plus = rot_axis2(theta)
r2_minus = rot_axis2(-theta)
r1_plus = rot_axis1(theta)
r1_minus = rot_axis1(-theta)
assert r3_minus*r3_plus*eye(3) == eye(3)
assert r2_minus*r2_plus*eye(3) == eye(3)
assert r1_minus*r1_plus*eye(3) == eye(3)
# Check the correctness of the trace of the rotation matrix
assert r1_plus.trace() == 1 + 2*cos(theta)
assert r2_plus.trace() == 1 + 2*cos(theta)
assert r3_plus.trace() == 1 + 2*cos(theta)
# Check that a rotation with zero angle doesn't change anything.
assert rot_axis1(0) == eye(3)
assert rot_axis2(0) == eye(3)
assert rot_axis3(0) == eye(3)
def test_DeferredVector():
assert str(DeferredVector("vector")[4]) == "vector[4]"
assert sympify(DeferredVector("d")) == DeferredVector("d")
raises(IndexError, lambda: DeferredVector("d")[-1])
assert str(DeferredVector("d")) == "d"
assert repr(DeferredVector("test")) == "DeferredVector('test')"
def test_DeferredVector_not_iterable():
assert not iterable(DeferredVector('X'))
def test_DeferredVector_Matrix():
raises(TypeError, lambda: Matrix(DeferredVector("V")))
def test_GramSchmidt():
R = Rational
m1 = Matrix(1, 2, [1, 2])
m2 = Matrix(1, 2, [2, 3])
assert GramSchmidt([m1, m2]) == \
[Matrix(1, 2, [1, 2]), Matrix(1, 2, [R(2)/5, R(-1)/5])]
assert GramSchmidt([m1.T, m2.T]) == \
[Matrix(2, 1, [1, 2]), Matrix(2, 1, [R(2)/5, R(-1)/5])]
# from wikipedia
assert GramSchmidt([Matrix([3, 1]), Matrix([2, 2])], True) == [
Matrix([3*sqrt(10)/10, sqrt(10)/10]),
Matrix([-sqrt(10)/10, 3*sqrt(10)/10])]
# https://github.com/sympy/sympy/issues/9488
L = FiniteSet(Matrix([1]))
assert GramSchmidt(L) == [Matrix([[1]])]
def test_casoratian():
assert casoratian([1, 2, 3, 4], 1) == 0
assert casoratian([1, 2, 3, 4], 1, zero=False) == 0
def test_zero_dimension_multiply():
assert (Matrix()*zeros(0, 3)).shape == (0, 3)
assert zeros(3, 0)*zeros(0, 3) == zeros(3, 3)
assert zeros(0, 3)*zeros(3, 0) == Matrix()
def test_slice_issue_2884():
m = Matrix(2, 2, range(4))
assert m[1, :] == Matrix([[2, 3]])
assert m[-1, :] == Matrix([[2, 3]])
assert m[:, 1] == Matrix([[1, 3]]).T
assert m[:, -1] == Matrix([[1, 3]]).T
raises(IndexError, lambda: m[2, :])
raises(IndexError, lambda: m[2, 2])
def test_slice_issue_3401():
assert zeros(0, 3)[:, -1].shape == (0, 1)
assert zeros(3, 0)[0, :] == Matrix(1, 0, [])
def test_copyin():
s = zeros(3, 3)
s[3] = 1
assert s[:, 0] == Matrix([0, 1, 0])
assert s[3] == 1
assert s[3: 4] == [1]
s[1, 1] = 42
assert s[1, 1] == 42
assert s[1, 1:] == Matrix([[42, 0]])
s[1, 1:] = Matrix([[5, 6]])
assert s[1, :] == Matrix([[1, 5, 6]])
s[1, 1:] = [[42, 43]]
assert s[1, :] == Matrix([[1, 42, 43]])
s[0, 0] = 17
assert s[:, :1] == Matrix([17, 1, 0])
s[0, 0] = [1, 1, 1]
assert s[:, 0] == Matrix([1, 1, 1])
s[0, 0] = Matrix([1, 1, 1])
assert s[:, 0] == Matrix([1, 1, 1])
s[0, 0] = SparseMatrix([1, 1, 1])
assert s[:, 0] == Matrix([1, 1, 1])
def test_invertible_check():
# sometimes a singular matrix will have a pivot vector shorter than
# the number of rows in a matrix...
assert Matrix([[1, 2], [1, 2]]).rref() == (Matrix([[1, 2], [0, 0]]), (0,))
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inv())
m = Matrix([
[-1, -1, 0],
[ x, 1, 1],
[ 1, x, -1],
])
assert len(m.rref()[1]) != m.rows
# in addition, unless simplify=True in the call to rref, the identity
# matrix will be returned even though m is not invertible
assert m.rref()[0] != eye(3)
assert m.rref(simplify=signsimp)[0] != eye(3)
raises(ValueError, lambda: m.inv(method="ADJ"))
raises(ValueError, lambda: m.inv(method="GE"))
raises(ValueError, lambda: m.inv(method="LU"))
def test_issue_3959():
x, y = symbols('x, y')
e = x*y
assert e.subs(x, Matrix([3, 5, 3])) == Matrix([3, 5, 3])*y
def test_issue_5964():
assert str(Matrix([[1, 2], [3, 4]])) == 'Matrix([[1, 2], [3, 4]])'
def test_issue_7604():
x, y = symbols("x y")
assert sstr(Matrix([[x, 2*y], [y**2, x + 3]])) == \
'Matrix([\n[ x, 2*y],\n[y**2, x + 3]])'
def test_is_Identity():
assert eye(3).is_Identity
assert eye(3).as_immutable().is_Identity
assert not zeros(3).is_Identity
assert not ones(3).is_Identity
# issue 6242
assert not Matrix([[1, 0, 0]]).is_Identity
# issue 8854
assert SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1}).is_Identity
assert not SparseMatrix(2,3, range(6)).is_Identity
assert not SparseMatrix(3,3, {(0,0):1, (1,1):1}).is_Identity
assert not SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1, (0,1):2, (0,2):3}).is_Identity
def test_dot():
assert ones(1, 3).dot(ones(3, 1)) == 3
assert ones(1, 3).dot([1, 1, 1]) == 3
assert Matrix([1, 2, 3]).dot(Matrix([1, 2, 3])) == 14
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I])) == -5 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=False) == -5 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True) == 13 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True, conjugate_convention="physics") == 13 - I
assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="right") == 4 + 8*I
assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="left") == 4 - 8*I
assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), hermitian=False, conjugate_convention="left") == -5
assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), conjugate_convention="left") == 5
raises(ValueError, lambda: Matrix([1, 2]).dot(Matrix([3, 4]), hermitian=True, conjugate_convention="test"))
def test_dual():
B_x, B_y, B_z, E_x, E_y, E_z = symbols(
'B_x B_y B_z E_x E_y E_z', real=True)
F = Matrix((
( 0, E_x, E_y, E_z),
(-E_x, 0, B_z, -B_y),
(-E_y, -B_z, 0, B_x),
(-E_z, B_y, -B_x, 0)
))
Fd = Matrix((
( 0, -B_x, -B_y, -B_z),
(B_x, 0, E_z, -E_y),
(B_y, -E_z, 0, E_x),
(B_z, E_y, -E_x, 0)
))
assert F.dual().equals(Fd)
assert eye(3).dual().equals(zeros(3))
assert F.dual().dual().equals(-F)
def test_anti_symmetric():
assert Matrix([1, 2]).is_anti_symmetric() is False
m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0])
assert m.is_anti_symmetric() is True
assert m.is_anti_symmetric(simplify=False) is False
assert m.is_anti_symmetric(simplify=lambda x: x) is False
# tweak to fail
m[2, 1] = -m[2, 1]
assert m.is_anti_symmetric() is False
# untweak
m[2, 1] = -m[2, 1]
m = m.expand()
assert m.is_anti_symmetric(simplify=False) is True
m[0, 0] = 1
assert m.is_anti_symmetric() is False
def test_normalize_sort_diogonalization():
A = Matrix(((1, 2), (2, 1)))
P, Q = A.diagonalize(normalize=True)
assert P*P.T == P.T*P == eye(P.cols)
P, Q = A.diagonalize(normalize=True, sort=True)
assert P*P.T == P.T*P == eye(P.cols)
assert P*Q*P.inv() == A
def test_issue_5321():
raises(ValueError, lambda: Matrix([[1, 2, 3], Matrix(0, 1, [])]))
def test_issue_5320():
assert Matrix.hstack(eye(2), 2*eye(2)) == Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2]
])
assert Matrix.vstack(eye(2), 2*eye(2)) == Matrix([
[1, 0],
[0, 1],
[2, 0],
[0, 2]
])
cls = SparseMatrix
assert cls.hstack(cls(eye(2)), cls(2*eye(2))) == Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2]
])
def test_issue_11944():
A = Matrix([[1]])
AIm = sympify(A)
assert Matrix.hstack(AIm, A) == Matrix([[1, 1]])
assert Matrix.vstack(AIm, A) == Matrix([[1], [1]])
def test_cross():
a = [1, 2, 3]
b = [3, 4, 5]
col = Matrix([-2, 4, -2])
row = col.T
def test(M, ans):
assert ans == M
assert type(M) == cls
for cls in classes:
A = cls(a)
B = cls(b)
test(A.cross(B), col)
test(A.cross(B.T), col)
test(A.T.cross(B.T), row)
test(A.T.cross(B), row)
raises(ShapeError, lambda:
Matrix(1, 2, [1, 1]).cross(Matrix(1, 2, [1, 1])))
def test_hash():
for cls in classes[-2:]:
s = {cls.eye(1), cls.eye(1)}
assert len(s) == 1 and s.pop() == cls.eye(1)
# issue 3979
for cls in classes[:2]:
assert not isinstance(cls.eye(1), Hashable)
@XFAIL
def test_issue_3979():
# when this passes, delete this and change the [1:2]
# to [:2] in the test_hash above for issue 3979
cls = classes[0]
raises(AttributeError, lambda: hash(cls.eye(1)))
def test_adjoint():
dat = [[0, I], [1, 0]]
ans = Matrix([[0, 1], [-I, 0]])
for cls in classes:
assert ans == cls(dat).adjoint()
def test_simplify_immutable():
assert simplify(ImmutableMatrix([[sin(x)**2 + cos(x)**2]])) == \
ImmutableMatrix([[1]])
def test_replace():
F, G = symbols('F, G', cls=Function)
K = Matrix(2, 2, lambda i, j: G(i+j))
M = Matrix(2, 2, lambda i, j: F(i+j))
N = M.replace(F, G)
assert N == K
def test_replace_map():
F, G = symbols('F, G', cls=Function)
with warns_deprecated_sympy():
K = Matrix(2, 2, [(G(0), {F(0): G(0)}), (G(1), {F(1): G(1)}),
(G(1), {F(1): G(1)}), (G(2), {F(2): G(2)})])
M = Matrix(2, 2, lambda i, j: F(i+j))
with warns_deprecated_sympy():
N = M.replace(F, G, True)
assert N == K
def test_atoms():
m = Matrix([[1, 2], [x, 1 - 1/x]])
assert m.atoms() == {S.One,S(2),S.NegativeOne, x}
assert m.atoms(Symbol) == {x}
def test_pinv():
# Pseudoinverse of an invertible matrix is the inverse.
A1 = Matrix([[a, b], [c, d]])
assert simplify(A1.pinv(method="RD")) == simplify(A1.inv())
# Test the four properties of the pseudoinverse for various matrices.
As = [Matrix([[13, 104], [2212, 3], [-3, 5]]),
Matrix([[1, 7, 9], [11, 17, 19]]),
Matrix([a, b])]
for A in As:
A_pinv = A.pinv(method="RD")
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
# XXX Pinv with diagonalization makes expression too complicated.
for A in As:
A_pinv = simplify(A.pinv(method="ED"))
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
# XXX Computing pinv using diagonalization makes an expression that
# is too complicated to simplify.
# A1 = Matrix([[a, b], [c, d]])
# assert simplify(A1.pinv(method="ED")) == simplify(A1.inv())
# so this is tested numerically at a fixed random point
from sympy.core.numbers import comp
q = A1.pinv(method="ED")
w = A1.inv()
reps = {a: -73633, b: 11362, c: 55486, d: 62570}
assert all(
comp(i.n(), j.n())
for i, j in zip(q.subs(reps), w.subs(reps))
)
@slow
@XFAIL
def test_pinv_rank_deficient_when_diagonalization_fails():
# Test the four properties of the pseudoinverse for matrices when
# diagonalization of A.H*A fails.
As = [
Matrix([
[61, 89, 55, 20, 71, 0],
[62, 96, 85, 85, 16, 0],
[69, 56, 17, 4, 54, 0],
[10, 54, 91, 41, 71, 0],
[ 7, 30, 10, 48, 90, 0],
[0, 0, 0, 0, 0, 0]])
]
for A in As:
A_pinv = A.pinv(method="ED")
AAp = A * A_pinv
ApA = A_pinv * A
assert AAp.H == AAp
assert ApA.H == ApA
def test_issue_7201():
assert ones(0, 1) + ones(0, 1) == Matrix(0, 1, [])
assert ones(1, 0) + ones(1, 0) == Matrix(1, 0, [])
def test_free_symbols():
for M in ImmutableMatrix, ImmutableSparseMatrix, Matrix, SparseMatrix:
assert M([[x], [0]]).free_symbols == {x}
def test_from_ndarray():
"""See issue 7465."""
try:
from numpy import array
except ImportError:
skip('NumPy must be available to test creating matrices from ndarrays')
assert Matrix(array([1, 2, 3])) == Matrix([1, 2, 3])
assert Matrix(array([[1, 2, 3]])) == Matrix([[1, 2, 3]])
assert Matrix(array([[1, 2, 3], [4, 5, 6]])) == \
Matrix([[1, 2, 3], [4, 5, 6]])
assert Matrix(array([x, y, z])) == Matrix([x, y, z])
raises(NotImplementedError,
lambda: Matrix(array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])))
assert Matrix([array([1, 2]), array([3, 4])]) == Matrix([[1, 2], [3, 4]])
assert Matrix([array([1, 2]), [3, 4]]) == Matrix([[1, 2], [3, 4]])
assert Matrix([array([]), array([])]) == Matrix([])
def test_17522_numpy():
from sympy.matrices.common import _matrixify
try:
from numpy import array, matrix
except ImportError:
skip('NumPy must be available to test indexing matrixified NumPy ndarrays and matrices')
m = _matrixify(array([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
m = _matrixify(matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
def test_17522_mpmath():
from sympy.matrices.common import _matrixify
try:
from mpmath import matrix
except ImportError:
skip('mpmath must be available to test indexing matrixified mpmath matrices')
m = _matrixify(matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
def test_17522_scipy():
from sympy.matrices.common import _matrixify
try:
from scipy.sparse import csr_matrix
except ImportError:
skip('SciPy must be available to test indexing matrixified SciPy sparse matrices')
m = _matrixify(csr_matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
def test_hermitian():
a = Matrix([[1, I], [-I, 1]])
assert a.is_hermitian
a[0, 0] = 2*I
assert a.is_hermitian is False
a[0, 0] = x
assert a.is_hermitian is None
a[0, 1] = a[1, 0]*I
assert a.is_hermitian is False
def test_doit():
a = Matrix([[Add(x,x, evaluate=False)]])
assert a[0] != 2*x
assert a.doit() == Matrix([[2*x]])
def test_issue_9457_9467_9876():
# for row_del(index)
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
M.row_del(1)
assert M == Matrix([[1, 2, 3], [3, 4, 5]])
N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
N.row_del(-2)
assert N == Matrix([[1, 2, 3], [3, 4, 5]])
O = Matrix([[1, 2, 3], [5, 6, 7], [9, 10, 11]])
O.row_del(-1)
assert O == Matrix([[1, 2, 3], [5, 6, 7]])
P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: P.row_del(10))
Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: Q.row_del(-10))
# for col_del(index)
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
M.col_del(1)
assert M == Matrix([[1, 3], [2, 4], [3, 5]])
N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
N.col_del(-2)
assert N == Matrix([[1, 3], [2, 4], [3, 5]])
P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: P.col_del(10))
Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: Q.col_del(-10))
def test_issue_9422():
x, y = symbols('x y', commutative=False)
a, b = symbols('a b')
M = eye(2)
M1 = Matrix(2, 2, [x, y, y, z])
assert y*x*M != x*y*M
assert b*a*M == a*b*M
assert x*M1 != M1*x
assert a*M1 == M1*a
assert y*x*M == Matrix([[y*x, 0], [0, y*x]])
def test_issue_10770():
M = Matrix([])
a = ['col_insert', 'row_join'], Matrix([9, 6, 3])
b = ['row_insert', 'col_join'], a[1].T
c = ['row_insert', 'col_insert'], Matrix([[1, 2], [3, 4]])
for ops, m in (a, b, c):
for op in ops:
f = getattr(M, op)
new = f(m) if 'join' in op else f(42, m)
assert new == m and id(new) != id(m)
def test_issue_10658():
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
assert A.extract([0, 1, 2], [True, True, False]) == \
Matrix([[1, 2], [4, 5], [7, 8]])
assert A.extract([0, 1, 2], [True, False, False]) == Matrix([[1], [4], [7]])
assert A.extract([True, False, False], [0, 1, 2]) == Matrix([[1, 2, 3]])
assert A.extract([True, False, True], [0, 1, 2]) == \
Matrix([[1, 2, 3], [7, 8, 9]])
assert A.extract([0, 1, 2], [False, False, False]) == Matrix(3, 0, [])
assert A.extract([False, False, False], [0, 1, 2]) == Matrix(0, 3, [])
assert A.extract([True, False, True], [False, True, False]) == \
Matrix([[2], [8]])
def test_opportunistic_simplification():
# this test relates to issue #10718, #9480, #11434
# issue #9480
m = Matrix([[-5 + 5*sqrt(2), -5], [-5*sqrt(2)/2 + 5, -5*sqrt(2)/2]])
assert m.rank() == 1
# issue #10781
m = Matrix([[3+3*sqrt(3)*I, -9],[4,-3+3*sqrt(3)*I]])
assert simplify(m.rref()[0] - Matrix([[1, -9/(3 + 3*sqrt(3)*I)], [0, 0]])) == zeros(2, 2)
# issue #11434
ax,ay,bx,by,cx,cy,dx,dy,ex,ey,t0,t1 = symbols('a_x a_y b_x b_y c_x c_y d_x d_y e_x e_y t_0 t_1')
m = Matrix([[ax,ay,ax*t0,ay*t0,0],[bx,by,bx*t0,by*t0,0],[cx,cy,cx*t0,cy*t0,1],[dx,dy,dx*t0,dy*t0,1],[ex,ey,2*ex*t1-ex*t0,2*ey*t1-ey*t0,0]])
assert m.rank() == 4
def test_partial_pivoting():
# example from https://en.wikipedia.org/wiki/Pivot_element
# partial pivoting with back substitution gives a perfect result
# naive pivoting give an error ~1e-13, so anything better than
# 1e-15 is good
mm=Matrix([[0.003, 59.14, 59.17], [5.291, -6.13, 46.78]])
assert (mm.rref()[0] - Matrix([[1.0, 0, 10.0],
[ 0, 1.0, 1.0]])).norm() < 1e-15
# issue #11549
m_mixed = Matrix([[6e-17, 1.0, 4],
[ -1.0, 0, 8],
[ 0, 0, 1]])
m_float = Matrix([[6e-17, 1.0, 4.],
[ -1.0, 0., 8.],
[ 0., 0., 1.]])
m_inv = Matrix([[ 0, -1.0, 8.0],
[1.0, 6.0e-17, -4.0],
[ 0, 0, 1]])
# this example is numerically unstable and involves a matrix with a norm >= 8,
# this comparing the difference of the results with 1e-15 is numerically sound.
assert (m_mixed.inv() - m_inv).norm() < 1e-15
assert (m_float.inv() - m_inv).norm() < 1e-15
def test_iszero_substitution():
""" When doing numerical computations, all elements that pass
the iszerofunc test should be set to numerically zero if they
aren't already. """
# Matrix from issue #9060
m = Matrix([[0.9, -0.1, -0.2, 0],[-0.8, 0.9, -0.4, 0],[-0.1, -0.8, 0.6, 0]])
m_rref = m.rref(iszerofunc=lambda x: abs(x)<6e-15)[0]
m_correct = Matrix([[1.0, 0, -0.301369863013699, 0],[ 0, 1.0, -0.712328767123288, 0],[ 0, 0, 0, 0]])
m_diff = m_rref - m_correct
assert m_diff.norm() < 1e-15
# if a zero-substitution wasn't made, this entry will be -1.11022302462516e-16
assert m_rref[2,2] == 0
def test_issue_11238():
from sympy.geometry.point import Point
xx = 8*tan(pi*Rational(13, 45))/(tan(pi*Rational(13, 45)) + sqrt(3))
yy = (-8*sqrt(3)*tan(pi*Rational(13, 45))**2 + 24*tan(pi*Rational(13, 45)))/(-3 + tan(pi*Rational(13, 45))**2)
p1 = Point(0, 0)
p2 = Point(1, -sqrt(3))
p0 = Point(xx,yy)
m1 = Matrix([p1 - simplify(p0), p2 - simplify(p0)])
m2 = Matrix([p1 - p0, p2 - p0])
m3 = Matrix([simplify(p1 - p0), simplify(p2 - p0)])
# This system has expressions which are zero and
# cannot be easily proved to be such, so without
# numerical testing, these assertions will fail.
Z = lambda x: abs(x.n()) < 1e-20
assert m1.rank(simplify=True, iszerofunc=Z) == 1
assert m2.rank(simplify=True, iszerofunc=Z) == 1
assert m3.rank(simplify=True, iszerofunc=Z) == 1
def test_as_real_imag():
m1 = Matrix(2,2,[1,2,3,4])
m2 = m1*S.ImaginaryUnit
m3 = m1 + m2
for kls in classes:
a,b = kls(m3).as_real_imag()
assert list(a) == list(m1)
assert list(b) == list(m1)
def test_deprecated():
# Maintain tests for deprecated functions. We must capture
# the deprecation warnings. When the deprecated functionality is
# removed, the corresponding tests should be removed.
m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2])
P, Jcells = m.jordan_cells()
assert Jcells[1] == Matrix(1, 1, [2])
assert Jcells[0] == Matrix(2, 2, [2, 1, 0, 2])
with warns_deprecated_sympy():
assert Matrix([[1,2],[3,4]]).dot(Matrix([[1,3],[4,5]])) == [10, 19, 14, 28]
def test_issue_14489():
from sympy.core.mod import Mod
A = Matrix([-1, 1, 2])
B = Matrix([10, 20, -15])
assert Mod(A, 3) == Matrix([2, 1, 2])
assert Mod(B, 4) == Matrix([2, 0, 1])
def test_issue_14943():
# Test that __array__ accepts the optional dtype argument
try:
from numpy import array
except ImportError:
skip('NumPy must be available to test creating matrices from ndarrays')
M = Matrix([[1,2], [3,4]])
assert array(M, dtype=float).dtype.name == 'float64'
def test_case_6913():
m = MatrixSymbol('m', 1, 1)
a = Symbol("a")
a = m[0, 0]>0
assert str(a) == 'm[0, 0] > 0'
def test_issue_11948():
A = MatrixSymbol('A', 3, 3)
a = Wild('a')
assert A.match(a) == {a: A}
def test_gramschmidt_conjugate_dot():
vecs = [Matrix([1, I]), Matrix([1, -I])]
assert Matrix.orthogonalize(*vecs) == \
[Matrix([[1], [I]]), Matrix([[1], [-I]])]
vecs = [Matrix([1, I, 0]), Matrix([I, 0, -I])]
assert Matrix.orthogonalize(*vecs) == \
[Matrix([[1], [I], [0]]), Matrix([[I/2], [S(1)/2], [-I]])]
mat = Matrix([[1, I], [1, -I]])
Q, R = mat.QRdecomposition()
assert Q * Q.H == Matrix.eye(2)
def test_issue_8207():
a = Matrix(MatrixSymbol('a', 3, 1))
b = Matrix(MatrixSymbol('b', 3, 1))
c = a.dot(b)
d = diff(c, a[0, 0])
e = diff(d, a[0, 0])
assert d == b[0, 0]
assert e == 0
def test_func():
from sympy.simplify.simplify import nthroot
A = Matrix([[1, 2],[0, 3]])
assert A.analytic_func(sin(x*t), x) == Matrix([[sin(t), sin(3*t) - sin(t)], [0, sin(3*t)]])
A = Matrix([[2, 1],[1, 2]])
assert (pi * A / 6).analytic_func(cos(x), x) == Matrix([[sqrt(3)/4, -sqrt(3)/4], [-sqrt(3)/4, sqrt(3)/4]])
raises(ValueError, lambda : zeros(5).analytic_func(log(x), x))
raises(ValueError, lambda : (A*x).analytic_func(log(x), x))
A = Matrix([[0, -1, -2, 3], [0, -1, -2, 3], [0, 1, 0, -1], [0, 0, -1, 1]])
assert A.analytic_func(exp(x), x) == A.exp()
raises(ValueError, lambda : A.analytic_func(sqrt(x), x))
A = Matrix([[41, 12],[12, 34]])
assert simplify(A.analytic_func(sqrt(x), x)**2) == A
A = Matrix([[3, -12, 4], [-1, 0, -2], [-1, 5, -1]])
assert simplify(A.analytic_func(nthroot(x, 3), x)**3) == A
A = Matrix([[2, 0, 0, 0], [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 3]])
assert A.analytic_func(exp(x), x) == A.exp()
A = Matrix([[0, 2, 1, 6], [0, 0, 1, 2], [0, 0, 0, 3], [0, 0, 0, 0]])
assert A.analytic_func(exp(x*t), x) == expand(simplify((A*t).exp()))
def test_issue_19809():
def f():
assert _dotprodsimp_state.state == None
m = Matrix([[1]])
m = m * m
return True
with dotprodsimp(True):
with concurrent.futures.ThreadPoolExecutor() as executor:
future = executor.submit(f)
assert future.result()
|
9333dc0d078cdb1a6ec235eea14ac2f6e2a871a73dfef38e52b02986d4b941c1 | from sympy.core.sympify import _sympify
from sympy.core import S, Basic
from sympy.matrices.common import NonSquareMatrixError
from sympy.matrices.expressions.matpow import MatPow
class Inverse(MatPow):
"""
The multiplicative inverse of a matrix expression
This is a symbolic object that simply stores its argument without
evaluating it. To actually compute the inverse, use the ``.inverse()``
method of matrices.
Examples
========
>>> from sympy import MatrixSymbol, Inverse
>>> A = MatrixSymbol('A', 3, 3)
>>> B = MatrixSymbol('B', 3, 3)
>>> Inverse(A)
A**(-1)
>>> A.inverse() == Inverse(A)
True
>>> (A*B).inverse()
B**(-1)*A**(-1)
>>> Inverse(A*B)
(A*B)**(-1)
"""
is_Inverse = True
exp = S.NegativeOne
def __new__(cls, mat, exp=S.NegativeOne):
# exp is there to make it consistent with
# inverse.func(*inverse.args) == inverse
mat = _sympify(mat)
exp = _sympify(exp)
if not mat.is_Matrix:
raise TypeError("mat should be a matrix")
if not mat.is_square:
raise NonSquareMatrixError("Inverse of non-square matrix %s" % mat)
return Basic.__new__(cls, mat, exp)
@property
def arg(self):
return self.args[0]
@property
def shape(self):
return self.arg.shape
def _eval_inverse(self):
return self.arg
def _eval_determinant(self):
from sympy.matrices.expressions.determinant import det
return 1/det(self.arg)
def doit(self, **hints):
if 'inv_expand' in hints and hints['inv_expand'] == False:
return self
arg = self.arg
if hints.get('deep', True):
arg = arg.doit(**hints)
return arg.inverse()
def _eval_derivative_matrix_lines(self, x):
arg = self.args[0]
lines = arg._eval_derivative_matrix_lines(x)
for line in lines:
line.first_pointer *= -self.T
line.second_pointer *= self
return lines
from sympy.assumptions.ask import ask, Q
from sympy.assumptions.refine import handlers_dict
def refine_Inverse(expr, assumptions):
"""
>>> from sympy import MatrixSymbol, Q, assuming, refine
>>> X = MatrixSymbol('X', 2, 2)
>>> X.I
X**(-1)
>>> with assuming(Q.orthogonal(X)):
... print(refine(X.I))
X.T
"""
if ask(Q.orthogonal(expr), assumptions):
return expr.arg.T
elif ask(Q.unitary(expr), assumptions):
return expr.arg.conjugate()
elif ask(Q.singular(expr), assumptions):
raise ValueError("Inverse of singular matrix %s" % expr.arg)
return expr
handlers_dict['Inverse'] = refine_Inverse
|
b18b29b59c55fadb630eb83470fec1a22f595e104efd89388a40d64fe4ce9a77 | from sympy.assumptions.ask import (Q, ask)
from sympy.core import Basic, Add, Mul, S
from sympy.core.sympify import _sympify
from sympy.functions.elementary.complexes import re, im
from sympy.strategies import typed, exhaust, condition, do_one, unpack
from sympy.strategies.traverse import bottom_up
from sympy.utilities.iterables import is_sequence, sift
from sympy.utilities.misc import filldedent
from sympy.matrices import Matrix, ShapeError
from sympy.matrices.common import NonInvertibleMatrixError
from sympy.matrices.expressions.determinant import det, Determinant
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices.expressions.matadd import MatAdd
from sympy.matrices.expressions.matexpr import MatrixExpr, MatrixElement
from sympy.matrices.expressions.matmul import MatMul
from sympy.matrices.expressions.matpow import MatPow
from sympy.matrices.expressions.slice import MatrixSlice
from sympy.matrices.expressions.special import ZeroMatrix, Identity
from sympy.matrices.expressions.trace import trace
from sympy.matrices.expressions.transpose import Transpose, transpose
class BlockMatrix(MatrixExpr):
"""A BlockMatrix is a Matrix comprised of other matrices.
The submatrices are stored in a SymPy Matrix object but accessed as part of
a Matrix Expression
>>> from sympy import (MatrixSymbol, BlockMatrix, symbols,
... Identity, ZeroMatrix, block_collapse)
>>> n,m,l = symbols('n m l')
>>> X = MatrixSymbol('X', n, n)
>>> Y = MatrixSymbol('Y', m, m)
>>> Z = MatrixSymbol('Z', n, m)
>>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]])
>>> print(B)
Matrix([
[X, Z],
[0, Y]])
>>> C = BlockMatrix([[Identity(n), Z]])
>>> print(C)
Matrix([[I, Z]])
>>> print(block_collapse(C*B))
Matrix([[X, Z + Z*Y]])
Some matrices might be comprised of rows of blocks with
the matrices in each row having the same height and the
rows all having the same total number of columns but
not having the same number of columns for each matrix
in each row. In this case, the matrix is not a block
matrix and should be instantiated by Matrix.
>>> from sympy import ones, Matrix
>>> dat = [
... [ones(3,2), ones(3,3)*2],
... [ones(2,3)*3, ones(2,2)*4]]
...
>>> BlockMatrix(dat)
Traceback (most recent call last):
...
ValueError:
Although this matrix is comprised of blocks, the blocks do not fill
the matrix in a size-symmetric fashion. To create a full matrix from
these arguments, pass them directly to Matrix.
>>> Matrix(dat)
Matrix([
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[3, 3, 3, 4, 4],
[3, 3, 3, 4, 4]])
See Also
========
sympy.matrices.matrices.MatrixBase.irregular
"""
def __new__(cls, *args, **kwargs):
from sympy.matrices.immutable import ImmutableDenseMatrix
isMat = lambda i: getattr(i, 'is_Matrix', False)
if len(args) != 1 or \
not is_sequence(args[0]) or \
len({isMat(r) for r in args[0]}) != 1:
raise ValueError(filldedent('''
expecting a sequence of 1 or more rows
containing Matrices.'''))
rows = args[0] if args else []
if not isMat(rows):
if rows and isMat(rows[0]):
rows = [rows] # rows is not list of lists or []
# regularity check
# same number of matrices in each row
blocky = ok = len({len(r) for r in rows}) == 1
if ok:
# same number of rows for each matrix in a row
for r in rows:
ok = len({i.rows for i in r}) == 1
if not ok:
break
blocky = ok
if ok:
# same number of cols for each matrix in each col
for c in range(len(rows[0])):
ok = len({rows[i][c].cols
for i in range(len(rows))}) == 1
if not ok:
break
if not ok:
# same total cols in each row
ok = len({
sum([i.cols for i in r]) for r in rows}) == 1
if blocky and ok:
raise ValueError(filldedent('''
Although this matrix is comprised of blocks,
the blocks do not fill the matrix in a
size-symmetric fashion. To create a full matrix
from these arguments, pass them directly to
Matrix.'''))
raise ValueError(filldedent('''
When there are not the same number of rows in each
row's matrices or there are not the same number of
total columns in each row, the matrix is not a
block matrix. If this matrix is known to consist of
blocks fully filling a 2-D space then see
Matrix.irregular.'''))
mat = ImmutableDenseMatrix(rows, evaluate=False)
obj = Basic.__new__(cls, mat)
return obj
@property
def shape(self):
numrows = numcols = 0
M = self.blocks
for i in range(M.shape[0]):
numrows += M[i, 0].shape[0]
for i in range(M.shape[1]):
numcols += M[0, i].shape[1]
return (numrows, numcols)
@property
def blockshape(self):
return self.blocks.shape
@property
def blocks(self):
return self.args[0]
@property
def rowblocksizes(self):
return [self.blocks[i, 0].rows for i in range(self.blockshape[0])]
@property
def colblocksizes(self):
return [self.blocks[0, i].cols for i in range(self.blockshape[1])]
def structurally_equal(self, other):
return (isinstance(other, BlockMatrix)
and self.shape == other.shape
and self.blockshape == other.blockshape
and self.rowblocksizes == other.rowblocksizes
and self.colblocksizes == other.colblocksizes)
def _blockmul(self, other):
if (isinstance(other, BlockMatrix) and
self.colblocksizes == other.rowblocksizes):
return BlockMatrix(self.blocks*other.blocks)
return self * other
def _blockadd(self, other):
if (isinstance(other, BlockMatrix)
and self.structurally_equal(other)):
return BlockMatrix(self.blocks + other.blocks)
return self + other
def _eval_transpose(self):
# Flip all the individual matrices
matrices = [transpose(matrix) for matrix in self.blocks]
# Make a copy
M = Matrix(self.blockshape[0], self.blockshape[1], matrices)
# Transpose the block structure
M = M.transpose()
return BlockMatrix(M)
def _eval_trace(self):
if self.rowblocksizes == self.colblocksizes:
return Add(*[trace(self.blocks[i, i])
for i in range(self.blockshape[0])])
raise NotImplementedError(
"Can't perform trace of irregular blockshape")
def _eval_determinant(self):
if self.blockshape == (1, 1):
return det(self.blocks[0, 0])
if self.blockshape == (2, 2):
[[A, B],
[C, D]] = self.blocks.tolist()
if ask(Q.invertible(A)):
return det(A)*det(D - C*A.I*B)
elif ask(Q.invertible(D)):
return det(D)*det(A - B*D.I*C)
return Determinant(self)
def as_real_imag(self):
real_matrices = [re(matrix) for matrix in self.blocks]
real_matrices = Matrix(self.blockshape[0], self.blockshape[1], real_matrices)
im_matrices = [im(matrix) for matrix in self.blocks]
im_matrices = Matrix(self.blockshape[0], self.blockshape[1], im_matrices)
return (real_matrices, im_matrices)
def transpose(self):
"""Return transpose of matrix.
Examples
========
>>> from sympy import MatrixSymbol, BlockMatrix, ZeroMatrix
>>> from sympy.abc import m, n
>>> X = MatrixSymbol('X', n, n)
>>> Y = MatrixSymbol('Y', m, m)
>>> Z = MatrixSymbol('Z', n, m)
>>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]])
>>> B.transpose()
Matrix([
[X.T, 0],
[Z.T, Y.T]])
>>> _.transpose()
Matrix([
[X, Z],
[0, Y]])
"""
return self._eval_transpose()
def schur(self, mat = 'A', generalized = False):
"""Return the Schur Complement of the 2x2 BlockMatrix
Parameters
==========
mat : String, optional
The matrix with respect to which the
Schur Complement is calculated. 'A' is
used by default
generalized : bool, optional
If True, returns the generalized Schur
Component which uses Moore-Penrose Inverse
Examples
========
>>> from sympy import symbols, MatrixSymbol, BlockMatrix
>>> m, n = symbols('m n')
>>> A = MatrixSymbol('A', n, n)
>>> B = MatrixSymbol('B', n, m)
>>> C = MatrixSymbol('C', m, n)
>>> D = MatrixSymbol('D', m, m)
>>> X = BlockMatrix([[A, B], [C, D]])
The default Schur Complement is evaluated with "A"
>>> X.schur()
-C*A**(-1)*B + D
>>> X.schur('D')
A - B*D**(-1)*C
Schur complement with non-invertible matrices is not
defined. Instead, the generalized Schur complement can
be calculated which uses the Moore-Penrose Inverse. To
achieve this, `generalized` must be set to `True`
>>> X.schur('B', generalized=True)
C - D*(B.T*B)**(-1)*B.T*A
>>> X.schur('C', generalized=True)
-A*(C.T*C)**(-1)*C.T*D + B
Returns
=======
M : Matrix
The Schur Complement Matrix
Raises
======
ShapeError
If the block matrix is not a 2x2 matrix
NonInvertibleMatrixError
If given matrix is non-invertible
References
==========
.. [1] Wikipedia Article on Schur Component : https://en.wikipedia.org/wiki/Schur_complement
See Also
========
sympy.matrices.matrices.MatrixBase.pinv
"""
if self.blockshape == (2, 2):
[[A, B],
[C, D]] = self.blocks.tolist()
d={'A' : A, 'B' : B, 'C' : C, 'D' : D}
try:
inv = (d[mat].T*d[mat]).inv()*d[mat].T if generalized else d[mat].inv()
if mat == 'A':
return D - C * inv * B
elif mat == 'B':
return C - D * inv * A
elif mat == 'C':
return B - A * inv * D
elif mat == 'D':
return A - B * inv * C
#For matrices where no sub-matrix is square
return self
except NonInvertibleMatrixError:
raise NonInvertibleMatrixError('The given matrix is not invertible. Please set generalized=True \
to compute the generalized Schur Complement which uses Moore-Penrose Inverse')
else:
raise ShapeError('Schur Complement can only be calculated for 2x2 block matrices')
def LDUdecomposition(self):
"""Returns the Block LDU decomposition of
a 2x2 Block Matrix
Returns
=======
(L, D, U) : Matrices
L : Lower Diagonal Matrix
D : Diagonal Matrix
U : Upper Diagonal Matrix
Examples
========
>>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse
>>> m, n = symbols('m n')
>>> A = MatrixSymbol('A', n, n)
>>> B = MatrixSymbol('B', n, m)
>>> C = MatrixSymbol('C', m, n)
>>> D = MatrixSymbol('D', m, m)
>>> X = BlockMatrix([[A, B], [C, D]])
>>> L, D, U = X.LDUdecomposition()
>>> block_collapse(L*D*U)
Matrix([
[A, B],
[C, D]])
Raises
======
ShapeError
If the block matrix is not a 2x2 matrix
NonInvertibleMatrixError
If the matrix "A" is non-invertible
See Also
========
sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition
sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition
"""
if self.blockshape == (2,2):
[[A, B],
[C, D]] = self.blocks.tolist()
try:
AI = A.I
except NonInvertibleMatrixError:
raise NonInvertibleMatrixError('Block LDU decomposition cannot be calculated when\
"A" is singular')
Ip = Identity(B.shape[0])
Iq = Identity(B.shape[1])
Z = ZeroMatrix(*B.shape)
L = BlockMatrix([[Ip, Z], [C*AI, Iq]])
D = BlockDiagMatrix(A, self.schur())
U = BlockMatrix([[Ip, AI*B],[Z.T, Iq]])
return L, D, U
else:
raise ShapeError("Block LDU decomposition is supported only for 2x2 block matrices")
def UDLdecomposition(self):
"""Returns the Block UDL decomposition of
a 2x2 Block Matrix
Returns
=======
(U, D, L) : Matrices
U : Upper Diagonal Matrix
D : Diagonal Matrix
L : Lower Diagonal Matrix
Examples
========
>>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse
>>> m, n = symbols('m n')
>>> A = MatrixSymbol('A', n, n)
>>> B = MatrixSymbol('B', n, m)
>>> C = MatrixSymbol('C', m, n)
>>> D = MatrixSymbol('D', m, m)
>>> X = BlockMatrix([[A, B], [C, D]])
>>> U, D, L = X.UDLdecomposition()
>>> block_collapse(U*D*L)
Matrix([
[A, B],
[C, D]])
Raises
======
ShapeError
If the block matrix is not a 2x2 matrix
NonInvertibleMatrixError
If the matrix "D" is non-invertible
See Also
========
sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition
sympy.matrices.expressions.blockmatrix.BlockMatrix.LUdecomposition
"""
if self.blockshape == (2,2):
[[A, B],
[C, D]] = self.blocks.tolist()
try:
DI = D.I
except NonInvertibleMatrixError:
raise NonInvertibleMatrixError('Block UDL decomposition cannot be calculated when\
"D" is singular')
Ip = Identity(A.shape[0])
Iq = Identity(B.shape[1])
Z = ZeroMatrix(*B.shape)
U = BlockMatrix([[Ip, B*DI], [Z.T, Iq]])
D = BlockDiagMatrix(self.schur('D'), D)
L = BlockMatrix([[Ip, Z],[DI*C, Iq]])
return U, D, L
else:
raise ShapeError("Block UDL decomposition is supported only for 2x2 block matrices")
def LUdecomposition(self):
"""Returns the Block LU decomposition of
a 2x2 Block Matrix
Returns
=======
(L, U) : Matrices
L : Lower Diagonal Matrix
U : Upper Diagonal Matrix
Examples
========
>>> from sympy import symbols, MatrixSymbol, BlockMatrix, block_collapse
>>> m, n = symbols('m n')
>>> A = MatrixSymbol('A', n, n)
>>> B = MatrixSymbol('B', n, m)
>>> C = MatrixSymbol('C', m, n)
>>> D = MatrixSymbol('D', m, m)
>>> X = BlockMatrix([[A, B], [C, D]])
>>> L, U = X.LUdecomposition()
>>> block_collapse(L*U)
Matrix([
[A, B],
[C, D]])
Raises
======
ShapeError
If the block matrix is not a 2x2 matrix
NonInvertibleMatrixError
If the matrix "A" is non-invertible
See Also
========
sympy.matrices.expressions.blockmatrix.BlockMatrix.UDLdecomposition
sympy.matrices.expressions.blockmatrix.BlockMatrix.LDUdecomposition
"""
if self.blockshape == (2,2):
[[A, B],
[C, D]] = self.blocks.tolist()
try:
A = A**0.5
AI = A.I
except NonInvertibleMatrixError:
raise NonInvertibleMatrixError('Block LU decomposition cannot be calculated when\
"A" is singular')
Z = ZeroMatrix(*B.shape)
Q = self.schur()**0.5
L = BlockMatrix([[A, Z], [C*AI, Q]])
U = BlockMatrix([[A, AI*B],[Z.T, Q]])
return L, U
else:
raise ShapeError("Block LU decomposition is supported only for 2x2 block matrices")
def _entry(self, i, j, **kwargs):
# Find row entry
orig_i, orig_j = i, j
for row_block, numrows in enumerate(self.rowblocksizes):
cmp = i < numrows
if cmp == True:
break
elif cmp == False:
i -= numrows
elif row_block < self.blockshape[0] - 1:
# Can't tell which block and it's not the last one, return unevaluated
return MatrixElement(self, orig_i, orig_j)
for col_block, numcols in enumerate(self.colblocksizes):
cmp = j < numcols
if cmp == True:
break
elif cmp == False:
j -= numcols
elif col_block < self.blockshape[1] - 1:
return MatrixElement(self, orig_i, orig_j)
return self.blocks[row_block, col_block][i, j]
@property
def is_Identity(self):
if self.blockshape[0] != self.blockshape[1]:
return False
for i in range(self.blockshape[0]):
for j in range(self.blockshape[1]):
if i==j and not self.blocks[i, j].is_Identity:
return False
if i!=j and not self.blocks[i, j].is_ZeroMatrix:
return False
return True
@property
def is_structurally_symmetric(self):
return self.rowblocksizes == self.colblocksizes
def equals(self, other):
if self == other:
return True
if (isinstance(other, BlockMatrix) and self.blocks == other.blocks):
return True
return super().equals(other)
class BlockDiagMatrix(BlockMatrix):
"""A sparse matrix with block matrices along its diagonals
Examples
========
>>> from sympy import MatrixSymbol, BlockDiagMatrix, symbols
>>> n, m, l = symbols('n m l')
>>> X = MatrixSymbol('X', n, n)
>>> Y = MatrixSymbol('Y', m, m)
>>> BlockDiagMatrix(X, Y)
Matrix([
[X, 0],
[0, Y]])
Notes
=====
If you want to get the individual diagonal blocks, use
:meth:`get_diag_blocks`.
See Also
========
sympy.matrices.dense.diag
"""
def __new__(cls, *mats):
return Basic.__new__(BlockDiagMatrix, *[_sympify(m) for m in mats])
@property
def diag(self):
return self.args
@property
def blocks(self):
from sympy.matrices.immutable import ImmutableDenseMatrix
mats = self.args
data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols)
for j in range(len(mats))]
for i in range(len(mats))]
return ImmutableDenseMatrix(data, evaluate=False)
@property
def shape(self):
return (sum(block.rows for block in self.args),
sum(block.cols for block in self.args))
@property
def blockshape(self):
n = len(self.args)
return (n, n)
@property
def rowblocksizes(self):
return [block.rows for block in self.args]
@property
def colblocksizes(self):
return [block.cols for block in self.args]
def _all_square_blocks(self):
"""Returns true if all blocks are square"""
return all(mat.is_square for mat in self.args)
def _eval_determinant(self):
if self._all_square_blocks():
return Mul(*[det(mat) for mat in self.args])
# At least one block is non-square. Since the entire matrix must be square we know there must
# be at least two blocks in this matrix, in which case the entire matrix is necessarily rank-deficient
return S.Zero
def _eval_inverse(self, expand='ignored'):
if self._all_square_blocks():
return BlockDiagMatrix(*[mat.inverse() for mat in self.args])
# See comment in _eval_determinant()
raise NonInvertibleMatrixError('Matrix det == 0; not invertible.')
def _eval_transpose(self):
return BlockDiagMatrix(*[mat.transpose() for mat in self.args])
def _blockmul(self, other):
if (isinstance(other, BlockDiagMatrix) and
self.colblocksizes == other.rowblocksizes):
return BlockDiagMatrix(*[a*b for a, b in zip(self.args, other.args)])
else:
return BlockMatrix._blockmul(self, other)
def _blockadd(self, other):
if (isinstance(other, BlockDiagMatrix) and
self.blockshape == other.blockshape and
self.rowblocksizes == other.rowblocksizes and
self.colblocksizes == other.colblocksizes):
return BlockDiagMatrix(*[a + b for a, b in zip(self.args, other.args)])
else:
return BlockMatrix._blockadd(self, other)
def get_diag_blocks(self):
"""Return the list of diagonal blocks of the matrix.
Examples
========
>>> from sympy.matrices import BlockDiagMatrix, Matrix
>>> A = Matrix([[1, 2], [3, 4]])
>>> B = Matrix([[5, 6], [7, 8]])
>>> M = BlockDiagMatrix(A, B)
How to get diagonal blocks from the block diagonal matrix:
>>> diag_blocks = M.get_diag_blocks()
>>> diag_blocks[0]
Matrix([
[1, 2],
[3, 4]])
>>> diag_blocks[1]
Matrix([
[5, 6],
[7, 8]])
"""
return self.args
def block_collapse(expr):
"""Evaluates a block matrix expression
>>> from sympy import MatrixSymbol, BlockMatrix, symbols, Identity, ZeroMatrix, block_collapse
>>> n,m,l = symbols('n m l')
>>> X = MatrixSymbol('X', n, n)
>>> Y = MatrixSymbol('Y', m, m)
>>> Z = MatrixSymbol('Z', n, m)
>>> B = BlockMatrix([[X, Z], [ZeroMatrix(m, n), Y]])
>>> print(B)
Matrix([
[X, Z],
[0, Y]])
>>> C = BlockMatrix([[Identity(n), Z]])
>>> print(C)
Matrix([[I, Z]])
>>> print(block_collapse(C*B))
Matrix([[X, Z + Z*Y]])
"""
from sympy.strategies.util import expr_fns
hasbm = lambda expr: isinstance(expr, MatrixExpr) and expr.has(BlockMatrix)
conditioned_rl = condition(
hasbm,
typed(
{MatAdd: do_one(bc_matadd, bc_block_plus_ident),
MatMul: do_one(bc_matmul, bc_dist),
MatPow: bc_matmul,
Transpose: bc_transpose,
Inverse: bc_inverse,
BlockMatrix: do_one(bc_unpack, deblock)}
)
)
rule = exhaust(
bottom_up(
exhaust(conditioned_rl),
fns=expr_fns
)
)
result = rule(expr)
doit = getattr(result, 'doit', None)
if doit is not None:
return doit()
else:
return result
def bc_unpack(expr):
if expr.blockshape == (1, 1):
return expr.blocks[0, 0]
return expr
def bc_matadd(expr):
args = sift(expr.args, lambda M: isinstance(M, BlockMatrix))
blocks = args[True]
if not blocks:
return expr
nonblocks = args[False]
block = blocks[0]
for b in blocks[1:]:
block = block._blockadd(b)
if nonblocks:
return MatAdd(*nonblocks) + block
else:
return block
def bc_block_plus_ident(expr):
idents = [arg for arg in expr.args if arg.is_Identity]
if not idents:
return expr
blocks = [arg for arg in expr.args if isinstance(arg, BlockMatrix)]
if (blocks and all(b.structurally_equal(blocks[0]) for b in blocks)
and blocks[0].is_structurally_symmetric):
block_id = BlockDiagMatrix(*[Identity(k)
for k in blocks[0].rowblocksizes])
rest = [arg for arg in expr.args if not arg.is_Identity and not isinstance(arg, BlockMatrix)]
return MatAdd(block_id * len(idents), *blocks, *rest).doit()
return expr
def bc_dist(expr):
""" Turn a*[X, Y] into [a*X, a*Y] """
factor, mat = expr.as_coeff_mmul()
if factor == 1:
return expr
unpacked = unpack(mat)
if isinstance(unpacked, BlockDiagMatrix):
B = unpacked.diag
new_B = [factor * mat for mat in B]
return BlockDiagMatrix(*new_B)
elif isinstance(unpacked, BlockMatrix):
B = unpacked.blocks
new_B = [
[factor * B[i, j] for j in range(B.cols)] for i in range(B.rows)]
return BlockMatrix(new_B)
return expr
def bc_matmul(expr):
if isinstance(expr, MatPow):
if expr.args[1].is_Integer:
factor, matrices = (1, [expr.args[0]]*expr.args[1])
else:
return expr
else:
factor, matrices = expr.as_coeff_matrices()
i = 0
while (i+1 < len(matrices)):
A, B = matrices[i:i+2]
if isinstance(A, BlockMatrix) and isinstance(B, BlockMatrix):
matrices[i] = A._blockmul(B)
matrices.pop(i+1)
elif isinstance(A, BlockMatrix):
matrices[i] = A._blockmul(BlockMatrix([[B]]))
matrices.pop(i+1)
elif isinstance(B, BlockMatrix):
matrices[i] = BlockMatrix([[A]])._blockmul(B)
matrices.pop(i+1)
else:
i+=1
return MatMul(factor, *matrices).doit()
def bc_transpose(expr):
collapse = block_collapse(expr.arg)
return collapse._eval_transpose()
def bc_inverse(expr):
if isinstance(expr.arg, BlockDiagMatrix):
return expr.inverse()
expr2 = blockinverse_1x1(expr)
if expr != expr2:
return expr2
return blockinverse_2x2(Inverse(reblock_2x2(expr.arg)))
def blockinverse_1x1(expr):
if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (1, 1):
mat = Matrix([[expr.arg.blocks[0].inverse()]])
return BlockMatrix(mat)
return expr
def blockinverse_2x2(expr):
if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (2, 2):
# See: Inverses of 2x2 Block Matrices, Tzon-Tzer Lu and Sheng-Hua Shiou
[[A, B],
[C, D]] = expr.arg.blocks.tolist()
formula = _choose_2x2_inversion_formula(A, B, C, D)
if formula != None:
MI = expr.arg.schur(formula).I
if formula == 'A':
AI = A.I
return BlockMatrix([[AI + AI * B * MI * C * AI, -AI * B * MI], [-MI * C * AI, MI]])
if formula == 'B':
BI = B.I
return BlockMatrix([[-MI * D * BI, MI], [BI + BI * A * MI * D * BI, -BI * A * MI]])
if formula == 'C':
CI = C.I
return BlockMatrix([[-CI * D * MI, CI + CI * D * MI * A * CI], [MI, -MI * A * CI]])
if formula == 'D':
DI = D.I
return BlockMatrix([[MI, -MI * B * DI], [-DI * C * MI, DI + DI * C * MI * B * DI]])
return expr
def _choose_2x2_inversion_formula(A, B, C, D):
"""
Assuming [[A, B], [C, D]] would form a valid square block matrix, find
which of the classical 2x2 block matrix inversion formulas would be
best suited.
Returns 'A', 'B', 'C', 'D' to represent the algorithm involving inversion
of the given argument or None if the matrix cannot be inverted using
any of those formulas.
"""
# Try to find a known invertible matrix. Note that the Schur complement
# is currently not being considered for this
A_inv = ask(Q.invertible(A))
if A_inv == True:
return 'A'
B_inv = ask(Q.invertible(B))
if B_inv == True:
return 'B'
C_inv = ask(Q.invertible(C))
if C_inv == True:
return 'C'
D_inv = ask(Q.invertible(D))
if D_inv == True:
return 'D'
# Otherwise try to find a matrix that isn't known to be non-invertible
if A_inv != False:
return 'A'
if B_inv != False:
return 'B'
if C_inv != False:
return 'C'
if D_inv != False:
return 'D'
return None
def deblock(B):
""" Flatten a BlockMatrix of BlockMatrices """
if not isinstance(B, BlockMatrix) or not B.blocks.has(BlockMatrix):
return B
wrap = lambda x: x if isinstance(x, BlockMatrix) else BlockMatrix([[x]])
bb = B.blocks.applyfunc(wrap) # everything is a block
try:
MM = Matrix(0, sum(bb[0, i].blocks.shape[1] for i in range(bb.shape[1])), [])
for row in range(0, bb.shape[0]):
M = Matrix(bb[row, 0].blocks)
for col in range(1, bb.shape[1]):
M = M.row_join(bb[row, col].blocks)
MM = MM.col_join(M)
return BlockMatrix(MM)
except ShapeError:
return B
def reblock_2x2(expr):
"""
Reblock a BlockMatrix so that it has 2x2 blocks of block matrices. If
possible in such a way that the matrix continues to be invertible using the
classical 2x2 block inversion formulas.
"""
if not isinstance(expr, BlockMatrix) or not all(d > 2 for d in expr.blockshape):
return expr
BM = BlockMatrix # for brevity's sake
rowblocks, colblocks = expr.blockshape
blocks = expr.blocks
for i in range(1, rowblocks):
for j in range(1, colblocks):
# try to split rows at i and cols at j
A = bc_unpack(BM(blocks[:i, :j]))
B = bc_unpack(BM(blocks[:i, j:]))
C = bc_unpack(BM(blocks[i:, :j]))
D = bc_unpack(BM(blocks[i:, j:]))
formula = _choose_2x2_inversion_formula(A, B, C, D)
if formula is not None:
return BlockMatrix([[A, B], [C, D]])
# else: nothing worked, just split upper left corner
return BM([[blocks[0, 0], BM(blocks[0, 1:])],
[BM(blocks[1:, 0]), BM(blocks[1:, 1:])]])
def bounds(sizes):
""" Convert sequence of numbers into pairs of low-high pairs
>>> from sympy.matrices.expressions.blockmatrix import bounds
>>> bounds((1, 10, 50))
[(0, 1), (1, 11), (11, 61)]
"""
low = 0
rv = []
for size in sizes:
rv.append((low, low + size))
low += size
return rv
def blockcut(expr, rowsizes, colsizes):
""" Cut a matrix expression into Blocks
>>> from sympy import ImmutableMatrix, blockcut
>>> M = ImmutableMatrix(4, 4, range(16))
>>> B = blockcut(M, (1, 3), (1, 3))
>>> type(B).__name__
'BlockMatrix'
>>> ImmutableMatrix(B.blocks[0, 1])
Matrix([[1, 2, 3]])
"""
rowbounds = bounds(rowsizes)
colbounds = bounds(colsizes)
return BlockMatrix([[MatrixSlice(expr, rowbound, colbound)
for colbound in colbounds]
for rowbound in rowbounds])
|
8f601db5589c1aa0ec8a493bb71fc380fcbf097070fdc7bf7fc876143a9a292e | from sympy.matrices.expressions.trace import Trace
from sympy.testing.pytest import raises, slow
from sympy.matrices.expressions.blockmatrix import (
block_collapse, bc_matmul, bc_block_plus_ident, BlockDiagMatrix,
BlockMatrix, bc_dist, bc_matadd, bc_transpose, bc_inverse,
blockcut, reblock_2x2, deblock)
from sympy.matrices.expressions import (MatrixSymbol, Identity,
Inverse, trace, Transpose, det, ZeroMatrix)
from sympy.matrices.common import NonInvertibleMatrixError
from sympy.matrices import (
Matrix, ImmutableMatrix, ImmutableSparseMatrix)
from sympy.core import Tuple, symbols, Expr
from sympy.functions import transpose
i, j, k, l, m, n, p = symbols('i:n, p', integer=True)
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, n)
C = MatrixSymbol('C', n, n)
D = MatrixSymbol('D', n, n)
G = MatrixSymbol('G', n, n)
H = MatrixSymbol('H', n, n)
b1 = BlockMatrix([[G, H]])
b2 = BlockMatrix([[G], [H]])
def test_bc_matmul():
assert bc_matmul(H*b1*b2*G) == BlockMatrix([[(H*G*G + H*H*H)*G]])
def test_bc_matadd():
assert bc_matadd(BlockMatrix([[G, H]]) + BlockMatrix([[H, H]])) == \
BlockMatrix([[G+H, H+H]])
def test_bc_transpose():
assert bc_transpose(Transpose(BlockMatrix([[A, B], [C, D]]))) == \
BlockMatrix([[A.T, C.T], [B.T, D.T]])
def test_bc_dist_diag():
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', m, m)
C = MatrixSymbol('C', l, l)
X = BlockDiagMatrix(A, B, C)
assert bc_dist(X+X).equals(BlockDiagMatrix(2*A, 2*B, 2*C))
def test_block_plus_ident():
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, m)
C = MatrixSymbol('C', m, n)
D = MatrixSymbol('D', m, m)
X = BlockMatrix([[A, B], [C, D]])
Z = MatrixSymbol('Z', n + m, n + m)
assert bc_block_plus_ident(X + Identity(m + n) + Z) == \
BlockDiagMatrix(Identity(n), Identity(m)) + X + Z
def test_BlockMatrix():
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', n, k)
C = MatrixSymbol('C', l, m)
D = MatrixSymbol('D', l, k)
M = MatrixSymbol('M', m + k, p)
N = MatrixSymbol('N', l + n, k + m)
X = BlockMatrix(Matrix([[A, B], [C, D]]))
assert X.__class__(*X.args) == X
# block_collapse does nothing on normal inputs
E = MatrixSymbol('E', n, m)
assert block_collapse(A + 2*E) == A + 2*E
F = MatrixSymbol('F', m, m)
assert block_collapse(E.T*A*F) == E.T*A*F
assert X.shape == (l + n, k + m)
assert X.blockshape == (2, 2)
assert transpose(X) == BlockMatrix(Matrix([[A.T, C.T], [B.T, D.T]]))
assert transpose(X).shape == X.shape[::-1]
# Test that BlockMatrices and MatrixSymbols can still mix
assert (X*M).is_MatMul
assert X._blockmul(M).is_MatMul
assert (X*M).shape == (n + l, p)
assert (X + N).is_MatAdd
assert X._blockadd(N).is_MatAdd
assert (X + N).shape == X.shape
E = MatrixSymbol('E', m, 1)
F = MatrixSymbol('F', k, 1)
Y = BlockMatrix(Matrix([[E], [F]]))
assert (X*Y).shape == (l + n, 1)
assert block_collapse(X*Y).blocks[0, 0] == A*E + B*F
assert block_collapse(X*Y).blocks[1, 0] == C*E + D*F
# block_collapse passes down into container objects, transposes, and inverse
assert block_collapse(transpose(X*Y)) == transpose(block_collapse(X*Y))
assert block_collapse(Tuple(X*Y, 2*X)) == (
block_collapse(X*Y), block_collapse(2*X))
# Make sure that MatrixSymbols will enter 1x1 BlockMatrix if it simplifies
Ab = BlockMatrix([[A]])
Z = MatrixSymbol('Z', *A.shape)
assert block_collapse(Ab + Z) == A + Z
def test_block_collapse_explicit_matrices():
A = Matrix([[1, 2], [3, 4]])
assert block_collapse(BlockMatrix([[A]])) == A
A = ImmutableSparseMatrix([[1, 2], [3, 4]])
assert block_collapse(BlockMatrix([[A]])) == A
def test_issue_17624():
a = MatrixSymbol("a", 2, 2)
z = ZeroMatrix(2, 2)
b = BlockMatrix([[a, z], [z, z]])
assert block_collapse(b * b) == BlockMatrix([[a**2, z], [z, z]])
assert block_collapse(b * b * b) == BlockMatrix([[a**3, z], [z, z]])
def test_issue_18618():
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
assert A == Matrix(BlockDiagMatrix(A))
def test_BlockMatrix_trace():
A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']
X = BlockMatrix([[A, B], [C, D]])
assert trace(X) == trace(A) + trace(D)
assert trace(BlockMatrix([ZeroMatrix(n, n)])) == 0
def test_BlockMatrix_Determinant():
A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']
X = BlockMatrix([[A, B], [C, D]])
from sympy.assumptions.ask import Q
from sympy.assumptions.assume import assuming
with assuming(Q.invertible(A)):
assert det(X) == det(A) * det(X.schur('A'))
assert isinstance(det(X), Expr)
assert det(BlockMatrix([A])) == det(A)
assert det(BlockMatrix([ZeroMatrix(n, n)])) == 0
def test_squareBlockMatrix():
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, m)
C = MatrixSymbol('C', m, n)
D = MatrixSymbol('D', m, m)
X = BlockMatrix([[A, B], [C, D]])
Y = BlockMatrix([[A]])
assert X.is_square
Q = X + Identity(m + n)
assert (block_collapse(Q) ==
BlockMatrix([[A + Identity(n), B], [C, D + Identity(m)]]))
assert (X + MatrixSymbol('Q', n + m, n + m)).is_MatAdd
assert (X * MatrixSymbol('Q', n + m, n + m)).is_MatMul
assert block_collapse(Y.I) == A.I
assert isinstance(X.inverse(), Inverse)
assert not X.is_Identity
Z = BlockMatrix([[Identity(n), B], [C, D]])
assert not Z.is_Identity
def test_BlockMatrix_2x2_inverse_symbolic():
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', n, k - m)
C = MatrixSymbol('C', k - n, m)
D = MatrixSymbol('D', k - n, k - m)
X = BlockMatrix([[A, B], [C, D]])
assert X.is_square and X.shape == (k, k)
assert isinstance(block_collapse(X.I), Inverse) # Can't invert when none of the blocks is square
# test code path where only A is invertible
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, m)
C = MatrixSymbol('C', m, n)
D = ZeroMatrix(m, m)
X = BlockMatrix([[A, B], [C, D]])
assert block_collapse(X.inverse()) == BlockMatrix([
[A.I + A.I * B * X.schur('A').I * C * A.I, -A.I * B * X.schur('A').I],
[-X.schur('A').I * C * A.I, X.schur('A').I],
])
# test code path where only B is invertible
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', n, n)
C = ZeroMatrix(m, m)
D = MatrixSymbol('D', m, n)
X = BlockMatrix([[A, B], [C, D]])
assert block_collapse(X.inverse()) == BlockMatrix([
[-X.schur('B').I * D * B.I, X.schur('B').I],
[B.I + B.I * A * X.schur('B').I * D * B.I, -B.I * A * X.schur('B').I],
])
# test code path where only C is invertible
A = MatrixSymbol('A', n, m)
B = ZeroMatrix(n, n)
C = MatrixSymbol('C', m, m)
D = MatrixSymbol('D', m, n)
X = BlockMatrix([[A, B], [C, D]])
assert block_collapse(X.inverse()) == BlockMatrix([
[-C.I * D * X.schur('C').I, C.I + C.I * D * X.schur('C').I * A * C.I],
[X.schur('C').I, -X.schur('C').I * A * C.I],
])
# test code path where only D is invertible
A = ZeroMatrix(n, n)
B = MatrixSymbol('B', n, m)
C = MatrixSymbol('C', m, n)
D = MatrixSymbol('D', m, m)
X = BlockMatrix([[A, B], [C, D]])
assert block_collapse(X.inverse()) == BlockMatrix([
[X.schur('D').I, -X.schur('D').I * B * D.I],
[-D.I * C * X.schur('D').I, D.I + D.I * C * X.schur('D').I * B * D.I],
])
def test_BlockMatrix_2x2_inverse_numeric():
"""Test 2x2 block matrix inversion numerically for all 4 formulas"""
M = Matrix([[1, 2], [3, 4]])
# rank deficient matrices that have full rank when two of them combined
D1 = Matrix([[1, 2], [2, 4]])
D2 = Matrix([[1, 3], [3, 9]])
D3 = Matrix([[1, 4], [4, 16]])
assert D1.rank() == D2.rank() == D3.rank() == 1
assert (D1 + D2).rank() == (D2 + D3).rank() == (D3 + D1).rank() == 2
# Only A is invertible
K = BlockMatrix([[M, D1], [D2, D3]])
assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv()
# Only B is invertible
K = BlockMatrix([[D1, M], [D2, D3]])
assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv()
# Only C is invertible
K = BlockMatrix([[D1, D2], [M, D3]])
assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv()
# Only D is invertible
K = BlockMatrix([[D1, D2], [D3, M]])
assert block_collapse(K.inv()).as_explicit() == K.as_explicit().inv()
@slow
def test_BlockMatrix_3x3_symbolic():
# Only test one of these, instead of all permutations, because it's slow
rowblocksizes = (n, m, k)
colblocksizes = (m, k, n)
K = BlockMatrix([
[MatrixSymbol('M%s%s' % (rows, cols), rows, cols) for cols in colblocksizes]
for rows in rowblocksizes
])
collapse = block_collapse(K.I)
assert isinstance(collapse, BlockMatrix)
def test_BlockDiagMatrix():
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', m, m)
C = MatrixSymbol('C', l, l)
M = MatrixSymbol('M', n + m + l, n + m + l)
X = BlockDiagMatrix(A, B, C)
Y = BlockDiagMatrix(A, 2*B, 3*C)
assert X.blocks[1, 1] == B
assert X.shape == (n + m + l, n + m + l)
assert all(X.blocks[i, j].is_ZeroMatrix if i != j else X.blocks[i, j] in [A, B, C]
for i in range(3) for j in range(3))
assert X.__class__(*X.args) == X
assert X.get_diag_blocks() == (A, B, C)
assert isinstance(block_collapse(X.I * X), Identity)
assert bc_matmul(X*X) == BlockDiagMatrix(A*A, B*B, C*C)
assert block_collapse(X*X) == BlockDiagMatrix(A*A, B*B, C*C)
#XXX: should be == ??
assert block_collapse(X + X).equals(BlockDiagMatrix(2*A, 2*B, 2*C))
assert block_collapse(X*Y) == BlockDiagMatrix(A*A, 2*B*B, 3*C*C)
assert block_collapse(X + Y) == BlockDiagMatrix(2*A, 3*B, 4*C)
# Ensure that BlockDiagMatrices can still interact with normal MatrixExprs
assert (X*(2*M)).is_MatMul
assert (X + (2*M)).is_MatAdd
assert (X._blockmul(M)).is_MatMul
assert (X._blockadd(M)).is_MatAdd
def test_BlockDiagMatrix_nonsquare():
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', k, l)
X = BlockDiagMatrix(A, B)
assert X.shape == (n + k, m + l)
assert X.shape == (n + k, m + l)
assert X.rowblocksizes == [n, k]
assert X.colblocksizes == [m, l]
C = MatrixSymbol('C', n, m)
D = MatrixSymbol('D', k, l)
Y = BlockDiagMatrix(C, D)
assert block_collapse(X + Y) == BlockDiagMatrix(A + C, B + D)
assert block_collapse(X * Y.T) == BlockDiagMatrix(A * C.T, B * D.T)
raises(NonInvertibleMatrixError, lambda: BlockDiagMatrix(A, C.T).inverse())
def test_BlockDiagMatrix_determinant():
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', m, m)
assert det(BlockDiagMatrix()) == 1
assert det(BlockDiagMatrix(A)) == det(A)
assert det(BlockDiagMatrix(A, B)) == det(A) * det(B)
# non-square blocks
C = MatrixSymbol('C', m, n)
D = MatrixSymbol('D', n, m)
assert det(BlockDiagMatrix(C, D)) == 0
def test_BlockDiagMatrix_trace():
assert trace(BlockDiagMatrix()) == 0
assert trace(BlockDiagMatrix(ZeroMatrix(n, n))) == 0
A = MatrixSymbol('A', n, n)
assert trace(BlockDiagMatrix(A)) == trace(A)
B = MatrixSymbol('B', m, m)
assert trace(BlockDiagMatrix(A, B)) == trace(A) + trace(B)
# non-square blocks
C = MatrixSymbol('C', m, n)
D = MatrixSymbol('D', n, m)
assert isinstance(trace(BlockDiagMatrix(C, D)), Trace)
def test_BlockDiagMatrix_transpose():
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', k, l)
assert transpose(BlockDiagMatrix()) == BlockDiagMatrix()
assert transpose(BlockDiagMatrix(A)) == BlockDiagMatrix(A.T)
assert transpose(BlockDiagMatrix(A, B)) == BlockDiagMatrix(A.T, B.T)
def test_issue_2460():
bdm1 = BlockDiagMatrix(Matrix([i]), Matrix([j]))
bdm2 = BlockDiagMatrix(Matrix([k]), Matrix([l]))
assert block_collapse(bdm1 + bdm2) == BlockDiagMatrix(Matrix([i + k]), Matrix([j + l]))
def test_blockcut():
A = MatrixSymbol('A', n, m)
B = blockcut(A, (n/2, n/2), (m/2, m/2))
assert B == BlockMatrix([[A[:n/2, :m/2], A[:n/2, m/2:]],
[A[n/2:, :m/2], A[n/2:, m/2:]]])
M = ImmutableMatrix(4, 4, range(16))
B = blockcut(M, (2, 2), (2, 2))
assert M == ImmutableMatrix(B)
B = blockcut(M, (1, 3), (2, 2))
assert ImmutableMatrix(B.blocks[0, 1]) == ImmutableMatrix([[2, 3]])
def test_reblock_2x2():
B = BlockMatrix([[MatrixSymbol('A_%d%d'%(i,j), 2, 2)
for j in range(3)]
for i in range(3)])
assert B.blocks.shape == (3, 3)
BB = reblock_2x2(B)
assert BB.blocks.shape == (2, 2)
assert B.shape == BB.shape
assert B.as_explicit() == BB.as_explicit()
def test_deblock():
B = BlockMatrix([[MatrixSymbol('A_%d%d'%(i,j), n, n)
for j in range(4)]
for i in range(4)])
assert deblock(reblock_2x2(B)) == B
def test_block_collapse_type():
bm1 = BlockDiagMatrix(ImmutableMatrix([1]), ImmutableMatrix([2]))
bm2 = BlockDiagMatrix(ImmutableMatrix([3]), ImmutableMatrix([4]))
assert bm1.T.__class__ == BlockDiagMatrix
assert block_collapse(bm1 - bm2).__class__ == BlockDiagMatrix
assert block_collapse(Inverse(bm1)).__class__ == BlockDiagMatrix
assert block_collapse(Transpose(bm1)).__class__ == BlockDiagMatrix
assert bc_transpose(Transpose(bm1)).__class__ == BlockDiagMatrix
assert bc_inverse(Inverse(bm1)).__class__ == BlockDiagMatrix
def test_invalid_block_matrix():
raises(ValueError, lambda: BlockMatrix([
[Identity(2), Identity(5)],
]))
raises(ValueError, lambda: BlockMatrix([
[Identity(n), Identity(m)],
]))
raises(ValueError, lambda: BlockMatrix([
[ZeroMatrix(n, n), ZeroMatrix(n, n)],
[ZeroMatrix(n, n - 1), ZeroMatrix(n, n + 1)],
]))
raises(ValueError, lambda: BlockMatrix([
[ZeroMatrix(n - 1, n), ZeroMatrix(n, n)],
[ZeroMatrix(n + 1, n), ZeroMatrix(n, n)],
]))
def test_block_lu_decomposition():
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, m)
C = MatrixSymbol('C', m, n)
D = MatrixSymbol('D', m, m)
X = BlockMatrix([[A, B], [C, D]])
#LDU decomposition
L, D, U = X.LDUdecomposition()
assert block_collapse(L*D*U) == X
#UDL decomposition
U, D, L = X.UDLdecomposition()
assert block_collapse(U*D*L) == X
#LU decomposition
L, U = X.LUdecomposition()
assert block_collapse(L*U) == X
def test_issue_21866():
n = 10
I = Identity(n)
O = ZeroMatrix(n, n)
A = BlockMatrix([[ I, O, O, O ],
[ O, I, O, O ],
[ O, O, I, O ],
[ I, O, O, I ]])
Ainv = block_collapse(A.inv())
AinvT = BlockMatrix([[ I, O, O, O ],
[ O, I, O, O ],
[ O, O, I, O ],
[ -I, O, O, I ]])
assert Ainv == AinvT
|
42eb542adaf7e46099e224b61f5593cccc1ad2302f2f4a6b712f36527b60af99 | from sympy.core import S, symbols
from sympy.matrices import eye, ones, Matrix, ShapeError
from sympy.matrices.expressions import (
Identity, MatrixExpr, MatrixSymbol, Determinant,
det, per, ZeroMatrix, Transpose,
Permanent
)
from sympy.matrices.expressions.special import OneMatrix
from sympy.testing.pytest import raises
from sympy.assumptions.ask import Q
from sympy.assumptions.refine import refine
n = symbols('n', integer=True)
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, n)
C = MatrixSymbol('C', 3, 4)
def test_det():
assert isinstance(Determinant(A), Determinant)
assert not isinstance(Determinant(A), MatrixExpr)
raises(ShapeError, lambda: Determinant(C))
assert det(eye(3)) == 1
assert det(Matrix(3, 3, [1, 3, 2, 4, 1, 3, 2, 5, 2])) == 17
_ = A / det(A) # Make sure this is possible
raises(TypeError, lambda: Determinant(S.One))
assert Determinant(A).arg is A
def test_eval_determinant():
assert det(Identity(n)) == 1
assert det(ZeroMatrix(n, n)) == 0
assert det(OneMatrix(n, n)) == Determinant(OneMatrix(n, n))
assert det(OneMatrix(1, 1)) == 1
assert det(OneMatrix(2, 2)) == 0
assert det(Transpose(A)) == det(A)
def test_refine():
assert refine(det(A), Q.orthogonal(A)) == 1
assert refine(det(A), Q.singular(A)) == 0
assert refine(det(A), Q.unit_triangular(A)) == 1
assert refine(det(A), Q.normal(A)) == det(A)
def test_commutative():
det_a = Determinant(A)
det_b = Determinant(B)
assert det_a.is_commutative
assert det_b.is_commutative
assert det_a * det_b == det_b * det_a
def test_permanent():
assert isinstance(Permanent(A), Permanent)
assert not isinstance(Permanent(A), MatrixExpr)
assert isinstance(Permanent(C), Permanent)
assert Permanent(ones(3, 3)).doit() == 6
_ = C / per(C)
assert per(Matrix(3, 3, [1, 3, 2, 4, 1, 3, 2, 5, 2])) == 103
raises(TypeError, lambda: Permanent(S.One))
assert Permanent(A).arg is A
|
20e8ea541d688207dc59f02333998a1d2b2c1c8d632340ff4a78c3a6359a0982 | from sympy.core import Lambda, S, symbols
from sympy.concrete import Sum
from sympy.functions import adjoint, conjugate, transpose
from sympy.matrices import eye, Matrix, ShapeError, ImmutableMatrix
from sympy.matrices.expressions import (
Adjoint, Identity, FunctionMatrix, MatrixExpr, MatrixSymbol, Trace,
ZeroMatrix, trace, MatPow, MatAdd, MatMul
)
from sympy.matrices.expressions.special import OneMatrix
from sympy.testing.pytest import raises
n = symbols('n', integer=True)
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, n)
C = MatrixSymbol('C', 3, 4)
def test_Trace():
assert isinstance(Trace(A), Trace)
assert not isinstance(Trace(A), MatrixExpr)
raises(ShapeError, lambda: Trace(C))
assert trace(eye(3)) == 3
assert trace(Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])) == 15
assert adjoint(Trace(A)) == trace(Adjoint(A))
assert conjugate(Trace(A)) == trace(Adjoint(A))
assert transpose(Trace(A)) == Trace(A)
_ = A / Trace(A) # Make sure this is possible
# Some easy simplifications
assert trace(Identity(5)) == 5
assert trace(ZeroMatrix(5, 5)) == 0
assert trace(OneMatrix(1, 1)) == 1
assert trace(OneMatrix(2, 2)) == 2
assert trace(OneMatrix(n, n)) == n
assert trace(2*A*B) == 2*Trace(A*B)
assert trace(A.T) == trace(A)
i, j = symbols('i j')
F = FunctionMatrix(3, 3, Lambda((i, j), i + j))
assert trace(F) == (0 + 0) + (1 + 1) + (2 + 2)
raises(TypeError, lambda: Trace(S.One))
assert Trace(A).arg is A
assert str(trace(A)) == str(Trace(A).doit())
assert Trace(A).is_commutative is True
def test_Trace_A_plus_B():
assert trace(A + B) == Trace(A) + Trace(B)
assert Trace(A + B).arg == MatAdd(A, B)
assert Trace(A + B).doit() == Trace(A) + Trace(B)
def test_Trace_MatAdd_doit():
# See issue #9028
X = ImmutableMatrix([[1, 2, 3]]*3)
Y = MatrixSymbol('Y', 3, 3)
q = MatAdd(X, 2*X, Y, -3*Y)
assert Trace(q).arg == q
assert Trace(q).doit() == 18 - 2*Trace(Y)
def test_Trace_MatPow_doit():
X = Matrix([[1, 2], [3, 4]])
assert Trace(X).doit() == 5
q = MatPow(X, 2)
assert Trace(q).arg == q
assert Trace(q).doit() == 29
def test_Trace_MutableMatrix_plus():
# See issue #9043
X = Matrix([[1, 2], [3, 4]])
assert Trace(X) + Trace(X) == 2*Trace(X)
def test_Trace_doit_deep_False():
X = Matrix([[1, 2], [3, 4]])
q = MatPow(X, 2)
assert Trace(q).doit(deep=False).arg == q
q = MatAdd(X, 2*X)
assert Trace(q).doit(deep=False).arg == q
q = MatMul(X, 2*X)
assert Trace(q).doit(deep=False).arg == q
def test_trace_constant_factor():
# Issue 9052: gave 2*Trace(MatMul(A)) instead of 2*Trace(A)
assert trace(2*A) == 2*Trace(A)
X = ImmutableMatrix([[1, 2], [3, 4]])
assert trace(MatMul(2, X)) == 10
def test_rewrite():
assert isinstance(trace(A).rewrite(Sum), Sum)
def test_trace_normalize():
assert Trace(B*A) != Trace(A*B)
assert Trace(B*A)._normalize() == Trace(A*B)
assert Trace(B*A.T)._normalize() == Trace(A*B.T)
def test_trace_as_explicit():
raises(ValueError, lambda: Trace(A).as_explicit())
X = MatrixSymbol("X", 3, 3)
assert Trace(X).as_explicit() == X[0, 0] + X[1, 1] + X[2, 2]
assert Trace(eye(3)).as_explicit() == 3
|
4c78ade26d5b4ae76689721e54e903994a18bf284796effdc77031ed643b2697 | from sympy.core import Basic, Expr
from sympy.core.function import Lambda
from sympy.core.numbers import oo, Infinity, NegativeInfinity, Zero, Integer
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import (Max, Min)
from sympy.sets.fancysets import ImageSet
from sympy.sets.setexpr import set_div
from sympy.sets.sets import Set, Interval, FiniteSet, Union
from sympy.multipledispatch import dispatch
_x, _y = symbols("x y")
@dispatch(Basic, Basic) # type: ignore # noqa:F811
def _set_pow(x, y): # noqa:F811
return None
@dispatch(Set, Set) # type: ignore # noqa:F811
def _set_pow(x, y): # noqa:F811
return ImageSet(Lambda((_x, _y), (_x ** _y)), x, y)
@dispatch(Expr, Expr) # type: ignore # noqa:F811
def _set_pow(x, y): # noqa:F811
return x**y
@dispatch(Interval, Zero) # type: ignore # noqa:F811
def _set_pow(x, z): # noqa:F811
return FiniteSet(S.One)
@dispatch(Interval, Integer) # type: ignore # noqa:F811
def _set_pow(x, exponent): # noqa:F811
"""
Powers in interval arithmetic
https://en.wikipedia.org/wiki/Interval_arithmetic
"""
s1 = x.start**exponent
s2 = x.end**exponent
if ((s2 > s1) if exponent > 0 else (x.end > -x.start)) == True:
left_open = x.left_open
right_open = x.right_open
# TODO: handle unevaluated condition.
sleft = s2
else:
# TODO: `s2 > s1` could be unevaluated.
left_open = x.right_open
right_open = x.left_open
sleft = s1
if x.start.is_positive:
return Interval(
Min(s1, s2),
Max(s1, s2), left_open, right_open)
elif x.end.is_negative:
return Interval(
Min(s1, s2),
Max(s1, s2), left_open, right_open)
# Case where x.start < 0 and x.end > 0:
if exponent.is_odd:
if exponent.is_negative:
if x.start.is_zero:
return Interval(s2, oo, x.right_open)
if x.end.is_zero:
return Interval(-oo, s1, True, x.left_open)
return Union(Interval(-oo, s1, True, x.left_open), Interval(s2, oo, x.right_open))
else:
return Interval(s1, s2, x.left_open, x.right_open)
elif exponent.is_even:
if exponent.is_negative:
if x.start.is_zero:
return Interval(s2, oo, x.right_open)
if x.end.is_zero:
return Interval(s1, oo, x.left_open)
return Interval(0, oo)
else:
return Interval(S.Zero, sleft, S.Zero not in x, left_open)
@dispatch(Interval, Infinity) # type: ignore # noqa:F811
def _set_pow(b, e): # noqa:F811
# TODO: add logic for open intervals?
if b.start.is_nonnegative:
if b.end < 1:
return FiniteSet(S.Zero)
if b.start > 1:
return FiniteSet(S.Infinity)
return Interval(0, oo)
elif b.end.is_negative:
if b.start > -1:
return FiniteSet(S.Zero)
if b.end < -1:
return FiniteSet(-oo, oo)
return Interval(-oo, oo)
else:
if b.start > -1:
if b.end < 1:
return FiniteSet(S.Zero)
return Interval(0, oo)
return Interval(-oo, oo)
@dispatch(Interval, NegativeInfinity) # type: ignore # noqa:F811
def _set_pow(b, e): # noqa:F811
return _set_pow(set_div(S.One, b), oo)
|
612c066ca15b90120c6bd6280e25bec0238a3f31350f6c332032c8028f201b67 | from sympy.core.numbers import oo, Infinity, NegativeInfinity
from sympy.core.singleton import S
from sympy.core.symbol import symbols
from sympy.core import Basic, Expr
from sympy.multipledispatch import dispatch
from sympy.sets import Interval, FiniteSet
# XXX: The functions in this module are clearly not tested and are broken in a
# number of ways.
_x, _y = symbols("x y")
@dispatch(Basic, Basic) # type: ignore # noqa:F811
def _set_add(x, y): # noqa:F811
return None
@dispatch(Expr, Expr) # type: ignore # noqa:F811
def _set_add(x, y): # noqa:F811
return x+y
@dispatch(Interval, Interval) # type: ignore # noqa:F811
def _set_add(x, y): # noqa:F811
"""
Additions in interval arithmetic
https://en.wikipedia.org/wiki/Interval_arithmetic
"""
return Interval(x.start + y.start, x.end + y.end,
x.left_open or y.left_open, x.right_open or y.right_open)
@dispatch(Interval, Infinity) # type: ignore # noqa:F811
def _set_add(x, y): # noqa:F811
if x.start is S.NegativeInfinity:
return Interval(-oo, oo)
return FiniteSet({S.Infinity})
@dispatch(Interval, NegativeInfinity) # type: ignore # noqa:F811
def _set_add(x, y): # noqa:F811
if x.end is S.Infinity:
return Interval(-oo, oo)
return FiniteSet({S.NegativeInfinity})
@dispatch(Basic, Basic) # type: ignore
def _set_sub(x, y): # noqa:F811
return None
@dispatch(Expr, Expr) # type: ignore # noqa:F811
def _set_sub(x, y): # noqa:F811
return x-y
@dispatch(Interval, Interval) # type: ignore # noqa:F811
def _set_sub(x, y): # noqa:F811
"""
Subtractions in interval arithmetic
https://en.wikipedia.org/wiki/Interval_arithmetic
"""
return Interval(x.start - y.end, x.end - y.start,
x.left_open or y.right_open, x.right_open or y.left_open)
@dispatch(Interval, Infinity) # type: ignore # noqa:F811
def _set_sub(x, y): # noqa:F811
if x.start is S.NegativeInfinity:
return Interval(-oo, oo)
return FiniteSet(-oo)
@dispatch(Interval, NegativeInfinity) # type: ignore # noqa:F811
def _set_sub(x, y): # noqa:F811
if x.start is S.NegativeInfinity:
return Interval(-oo, oo)
return FiniteSet(-oo)
|
90b46f14ee6cbc1c8a0ee6e475415f1162f16f67ff4d95f430f8bb2c1d41cbed | from sympy.core.singleton import S
from sympy.sets.sets import Set
from sympy.calculus.singularities import singularities
from sympy.core import Expr, Add
from sympy.core.function import Lambda, FunctionClass, diff, expand_mul
from sympy.core.numbers import Float, oo
from sympy.core.symbol import Dummy, symbols, Wild
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.logic.boolalg import true
from sympy.multipledispatch import dispatch
from sympy.sets import (imageset, Interval, FiniteSet, Union, ImageSet,
Intersection, Range, Complement)
from sympy.sets.sets import EmptySet, is_function_invertible_in_set
from sympy.sets.fancysets import Integers, Naturals, Reals
from sympy.functions.elementary.exponential import match_real_imag
_x, _y = symbols("x y")
FunctionUnion = (FunctionClass, Lambda)
@dispatch(FunctionClass, Set) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
return None
@dispatch(FunctionUnion, FiniteSet) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
return FiniteSet(*map(f, x))
@dispatch(Lambda, Interval) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
from sympy.solvers.solveset import solveset
from sympy.series import limit
# TODO: handle functions with infinitely many solutions (eg, sin, tan)
# TODO: handle multivariate functions
expr = f.expr
if len(expr.free_symbols) > 1 or len(f.variables) != 1:
return
var = f.variables[0]
if not var.is_real:
if expr.subs(var, Dummy(real=True)).is_real is False:
return
if expr.is_Piecewise:
result = S.EmptySet
domain_set = x
for (p_expr, p_cond) in expr.args:
if p_cond is true:
intrvl = domain_set
else:
intrvl = p_cond.as_set()
intrvl = Intersection(domain_set, intrvl)
if p_expr.is_Number:
image = FiniteSet(p_expr)
else:
image = imageset(Lambda(var, p_expr), intrvl)
result = Union(result, image)
# remove the part which has been `imaged`
domain_set = Complement(domain_set, intrvl)
if domain_set is S.EmptySet:
break
return result
if not x.start.is_comparable or not x.end.is_comparable:
return
try:
from sympy.polys.polyutils import _nsort
sing = list(singularities(expr, var, x))
if len(sing) > 1:
sing = _nsort(sing)
except NotImplementedError:
return
if x.left_open:
_start = limit(expr, var, x.start, dir="+")
elif x.start not in sing:
_start = f(x.start)
if x.right_open:
_end = limit(expr, var, x.end, dir="-")
elif x.end not in sing:
_end = f(x.end)
if len(sing) == 0:
soln_expr = solveset(diff(expr, var), var)
if not (isinstance(soln_expr, FiniteSet)
or soln_expr is S.EmptySet):
return
solns = list(soln_expr)
extr = [_start, _end] + [f(i) for i in solns
if i.is_real and i in x]
start, end = Min(*extr), Max(*extr)
left_open, right_open = False, False
if _start <= _end:
# the minimum or maximum value can occur simultaneously
# on both the edge of the interval and in some interior
# point
if start == _start and start not in solns:
left_open = x.left_open
if end == _end and end not in solns:
right_open = x.right_open
else:
if start == _end and start not in solns:
left_open = x.right_open
if end == _start and end not in solns:
right_open = x.left_open
return Interval(start, end, left_open, right_open)
else:
return imageset(f, Interval(x.start, sing[0],
x.left_open, True)) + \
Union(*[imageset(f, Interval(sing[i], sing[i + 1], True, True))
for i in range(0, len(sing) - 1)]) + \
imageset(f, Interval(sing[-1], x.end, True, x.right_open))
@dispatch(FunctionClass, Interval) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
if f == exp:
return Interval(exp(x.start), exp(x.end), x.left_open, x.right_open)
elif f == log:
return Interval(log(x.start), log(x.end), x.left_open, x.right_open)
return ImageSet(Lambda(_x, f(_x)), x)
@dispatch(FunctionUnion, Union) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
return Union(*(imageset(f, arg) for arg in x.args))
@dispatch(FunctionUnion, Intersection) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
# If the function is invertible, intersect the maps of the sets.
if is_function_invertible_in_set(f, x):
return Intersection(*(imageset(f, arg) for arg in x.args))
else:
return ImageSet(Lambda(_x, f(_x)), x)
@dispatch(FunctionUnion, EmptySet) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
return x
@dispatch(FunctionUnion, Set) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
return ImageSet(Lambda(_x, f(_x)), x)
@dispatch(FunctionUnion, Range) # type: ignore # noqa:F811
def _set_function(f, self): # noqa:F811
if not self:
return S.EmptySet
if not isinstance(f.expr, Expr):
return
if self.size == 1:
return FiniteSet(f(self[0]))
if f is S.IdentityFunction:
return self
x = f.variables[0]
expr = f.expr
# handle f that is linear in f's variable
if x not in expr.free_symbols or x in expr.diff(x).free_symbols:
return
if self.start.is_finite:
F = f(self.step*x + self.start) # for i in range(len(self))
else:
F = f(-self.step*x + self[-1])
F = expand_mul(F)
if F != expr:
return imageset(x, F, Range(self.size))
@dispatch(FunctionUnion, Integers) # type: ignore # noqa:F811
def _set_function(f, self): # noqa:F811
expr = f.expr
if not isinstance(expr, Expr):
return
n = f.variables[0]
if expr == abs(n):
return S.Naturals0
# f(x) + c and f(-x) + c cover the same integers
# so choose the form that has the fewest negatives
c = f(0)
fx = f(n) - c
f_x = f(-n) - c
neg_count = lambda e: sum(_.could_extract_minus_sign()
for _ in Add.make_args(e))
if neg_count(f_x) < neg_count(fx):
expr = f_x + c
a = Wild('a', exclude=[n])
b = Wild('b', exclude=[n])
match = expr.match(a*n + b)
if match and match[a] and (
not match[a].atoms(Float) and
not match[b].atoms(Float)):
# canonical shift
a, b = match[a], match[b]
if a in [1, -1]:
# drop integer addends in b
nonint = []
for bi in Add.make_args(b):
if not bi.is_integer:
nonint.append(bi)
b = Add(*nonint)
if b.is_number and a.is_real:
# avoid Mod for complex numbers, #11391
br, bi = match_real_imag(b)
if br and br.is_comparable and a.is_comparable:
br %= a
b = br + S.ImaginaryUnit*bi
elif b.is_number and a.is_imaginary:
br, bi = match_real_imag(b)
ai = a/S.ImaginaryUnit
if bi and bi.is_comparable and ai.is_comparable:
bi %= ai
b = br + S.ImaginaryUnit*bi
expr = a*n + b
if expr != f.expr:
return ImageSet(Lambda(n, expr), S.Integers)
@dispatch(FunctionUnion, Naturals) # type: ignore # noqa:F811
def _set_function(f, self): # noqa:F811
expr = f.expr
if not isinstance(expr, Expr):
return
x = f.variables[0]
if not expr.free_symbols - {x}:
if expr == abs(x):
if self is S.Naturals:
return self
return S.Naturals0
step = expr.coeff(x)
c = expr.subs(x, 0)
if c.is_Integer and step.is_Integer and expr == step*x + c:
if self is S.Naturals:
c += step
if step > 0:
if step == 1:
if c == 0:
return S.Naturals0
elif c == 1:
return S.Naturals
return Range(c, oo, step)
return Range(c, -oo, step)
@dispatch(FunctionUnion, Reals) # type: ignore # noqa:F811
def _set_function(f, self): # noqa:F811
expr = f.expr
if not isinstance(expr, Expr):
return
return _set_function(f, Interval(-oo, oo))
|
b3766bd827375dcfb153eb91aabbd55c8261efdf8f52704991307e54566c0293 | from sympy.core import Basic, Expr
from sympy.core.numbers import oo
from sympy.core.symbol import symbols
from sympy.multipledispatch import dispatch
from sympy.sets.setexpr import set_mul
from sympy.sets.sets import Interval, Set
_x, _y = symbols("x y")
@dispatch(Basic, Basic) # type: ignore # noqa:F811
def _set_mul(x, y): # noqa:F811
return None
@dispatch(Set, Set) # type: ignore # noqa:F811
def _set_mul(x, y): # noqa:F811
return None
@dispatch(Expr, Expr) # type: ignore # noqa:F811
def _set_mul(x, y): # noqa:F811
return x*y
@dispatch(Interval, Interval) # type: ignore # noqa:F811
def _set_mul(x, y): # noqa:F811
"""
Multiplications in interval arithmetic
https://en.wikipedia.org/wiki/Interval_arithmetic
"""
# TODO: some intervals containing 0 and oo will fail as 0*oo returns nan.
comvals = (
(x.start * y.start, bool(x.left_open or y.left_open)),
(x.start * y.end, bool(x.left_open or y.right_open)),
(x.end * y.start, bool(x.right_open or y.left_open)),
(x.end * y.end, bool(x.right_open or y.right_open)),
)
# TODO: handle symbolic intervals
minval, minopen = min(comvals)
maxval, maxopen = max(comvals)
return Interval(
minval,
maxval,
minopen,
maxopen
)
@dispatch(Basic, Basic) # type: ignore # noqa:F811
def _set_div(x, y): # noqa:F811
return None
@dispatch(Expr, Expr) # type: ignore # noqa:F811
def _set_div(x, y): # noqa:F811
return x/y
@dispatch(Set, Set) # type: ignore # noqa:F811 # noqa:F811
def _set_div(x, y): # noqa:F811
return None
@dispatch(Interval, Interval) # type: ignore # noqa:F811
def _set_div(x, y): # noqa:F811
"""
Divisions in interval arithmetic
https://en.wikipedia.org/wiki/Interval_arithmetic
"""
if (y.start*y.end).is_negative:
return Interval(-oo, oo)
if y.start == 0:
s2 = oo
else:
s2 = 1/y.start
if y.end == 0:
s1 = -oo
else:
s1 = 1/y.end
return set_mul(x, Interval(s1, s2, y.right_open, y.left_open))
|
cb31e90fcf780216dac2a041848076068d3ecb4be1d2feb6074b2f0b3f9af948 |
from sympy.core.expr import unchanged
from sympy.sets.contains import Contains
from sympy.sets.fancysets import (ImageSet, Range, normalize_theta_set,
ComplexRegion)
from sympy.sets.sets import (FiniteSet, Interval, Union, imageset,
Intersection, ProductSet)
from sympy.sets.conditionset import ConditionSet
from sympy.simplify.simplify import simplify
from sympy.core.basic import Basic
from sympy.core.containers import Tuple
from sympy.core.function import Lambda
from sympy.core.numbers import (I, Rational, oo, pi)
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol, symbols)
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import (exp, log)
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import (cos, sin, tan)
from sympy.logic.boolalg import And
from sympy.matrices.dense import eye
from sympy.testing.pytest import XFAIL, raises
from sympy.abc import x, y, t, z
from sympy.core.mod import Mod
import itertools
def test_naturals():
N = S.Naturals
assert 5 in N
assert -5 not in N
assert 5.5 not in N
ni = iter(N)
a, b, c, d = next(ni), next(ni), next(ni), next(ni)
assert (a, b, c, d) == (1, 2, 3, 4)
assert isinstance(a, Basic)
assert N.intersect(Interval(-5, 5)) == Range(1, 6)
assert N.intersect(Interval(-5, 5, True, True)) == Range(1, 5)
assert N.boundary == N
assert N.is_open == False
assert N.is_closed == True
assert N.inf == 1
assert N.sup is oo
assert not N.contains(oo)
for s in (S.Naturals0, S.Naturals):
assert s.intersection(S.Reals) is s
assert s.is_subset(S.Reals)
assert N.as_relational(x) == And(Eq(floor(x), x), x >= 1, x < oo)
def test_naturals0():
N = S.Naturals0
assert 0 in N
assert -1 not in N
assert next(iter(N)) == 0
assert not N.contains(oo)
assert N.contains(sin(x)) == Contains(sin(x), N)
def test_integers():
Z = S.Integers
assert 5 in Z
assert -5 in Z
assert 5.5 not in Z
assert not Z.contains(oo)
assert not Z.contains(-oo)
zi = iter(Z)
a, b, c, d = next(zi), next(zi), next(zi), next(zi)
assert (a, b, c, d) == (0, 1, -1, 2)
assert isinstance(a, Basic)
assert Z.intersect(Interval(-5, 5)) == Range(-5, 6)
assert Z.intersect(Interval(-5, 5, True, True)) == Range(-4, 5)
assert Z.intersect(Interval(5, S.Infinity)) == Range(5, S.Infinity)
assert Z.intersect(Interval.Lopen(5, S.Infinity)) == Range(6, S.Infinity)
assert Z.inf is -oo
assert Z.sup is oo
assert Z.boundary == Z
assert Z.is_open == False
assert Z.is_closed == True
assert Z.as_relational(x) == And(Eq(floor(x), x), -oo < x, x < oo)
def test_ImageSet():
raises(ValueError, lambda: ImageSet(x, S.Integers))
assert ImageSet(Lambda(x, 1), S.Integers) == FiniteSet(1)
assert ImageSet(Lambda(x, y), S.Integers) == {y}
assert ImageSet(Lambda(x, 1), S.EmptySet) == S.EmptySet
empty = Intersection(FiniteSet(log(2)/pi), S.Integers)
assert unchanged(ImageSet, Lambda(x, 1), empty) # issue #17471
squares = ImageSet(Lambda(x, x**2), S.Naturals)
assert 4 in squares
assert 5 not in squares
assert FiniteSet(*range(10)).intersect(squares) == FiniteSet(1, 4, 9)
assert 16 not in squares.intersect(Interval(0, 10))
si = iter(squares)
a, b, c, d = next(si), next(si), next(si), next(si)
assert (a, b, c, d) == (1, 4, 9, 16)
harmonics = ImageSet(Lambda(x, 1/x), S.Naturals)
assert Rational(1, 5) in harmonics
assert Rational(.25) in harmonics
assert 0.25 not in harmonics
assert Rational(.3) not in harmonics
assert (1, 2) not in harmonics
assert harmonics.is_iterable
assert imageset(x, -x, Interval(0, 1)) == Interval(-1, 0)
assert ImageSet(Lambda(x, x**2), Interval(0, 2)).doit() == Interval(0, 4)
assert ImageSet(Lambda((x, y), 2*x), {4}, {3}).doit() == FiniteSet(8)
assert (ImageSet(Lambda((x, y), x+y), {1, 2, 3}, {10, 20, 30}).doit() ==
FiniteSet(11, 12, 13, 21, 22, 23, 31, 32, 33))
c = Interval(1, 3) * Interval(1, 3)
assert Tuple(2, 6) in ImageSet(Lambda(((x, y),), (x, 2*y)), c)
assert Tuple(2, S.Half) in ImageSet(Lambda(((x, y),), (x, 1/y)), c)
assert Tuple(2, -2) not in ImageSet(Lambda(((x, y),), (x, y**2)), c)
assert Tuple(2, -2) in ImageSet(Lambda(((x, y),), (x, -2)), c)
c3 = ProductSet(Interval(3, 7), Interval(8, 11), Interval(5, 9))
assert Tuple(8, 3, 9) in ImageSet(Lambda(((t, y, x),), (y, t, x)), c3)
assert Tuple(Rational(1, 8), 3, 9) in ImageSet(Lambda(((t, y, x),), (1/y, t, x)), c3)
assert 2/pi not in ImageSet(Lambda(((x, y),), 2/x), c)
assert 2/S(100) not in ImageSet(Lambda(((x, y),), 2/x), c)
assert Rational(2, 3) in ImageSet(Lambda(((x, y),), 2/x), c)
S1 = imageset(lambda x, y: x + y, S.Integers, S.Naturals)
assert S1.base_pset == ProductSet(S.Integers, S.Naturals)
assert S1.base_sets == (S.Integers, S.Naturals)
# Passing a set instead of a FiniteSet shouldn't raise
assert unchanged(ImageSet, Lambda(x, x**2), {1, 2, 3})
S2 = ImageSet(Lambda(((x, y),), x+y), {(1, 2), (3, 4)})
assert 3 in S2.doit()
# FIXME: This doesn't yet work:
#assert 3 in S2
assert S2._contains(3) is None
raises(TypeError, lambda: ImageSet(Lambda(x, x**2), 1))
def test_image_is_ImageSet():
assert isinstance(imageset(x, sqrt(sin(x)), Range(5)), ImageSet)
def test_halfcircle():
r, th = symbols('r, theta', real=True)
L = Lambda(((r, th),), (r*cos(th), r*sin(th)))
halfcircle = ImageSet(L, Interval(0, 1)*Interval(0, pi))
assert (1, 0) in halfcircle
assert (0, -1) not in halfcircle
assert (0, 0) in halfcircle
assert halfcircle._contains((r, 0)) is None
# This one doesn't work:
#assert (r, 2*pi) not in halfcircle
assert not halfcircle.is_iterable
def test_ImageSet_iterator_not_injective():
L = Lambda(x, x - x % 2) # produces 0, 2, 2, 4, 4, 6, 6, ...
evens = ImageSet(L, S.Naturals)
i = iter(evens)
# No repeats here
assert (next(i), next(i), next(i), next(i)) == (0, 2, 4, 6)
def test_inf_Range_len():
raises(ValueError, lambda: len(Range(0, oo, 2)))
assert Range(0, oo, 2).size is S.Infinity
assert Range(0, -oo, -2).size is S.Infinity
assert Range(oo, 0, -2).size is S.Infinity
assert Range(-oo, 0, 2).size is S.Infinity
def test_Range_set():
empty = Range(0)
assert Range(5) == Range(0, 5) == Range(0, 5, 1)
r = Range(10, 20, 2)
assert 12 in r
assert 8 not in r
assert 11 not in r
assert 30 not in r
assert list(Range(0, 5)) == list(range(5))
assert list(Range(5, 0, -1)) == list(range(5, 0, -1))
assert Range(5, 15).sup == 14
assert Range(5, 15).inf == 5
assert Range(15, 5, -1).sup == 15
assert Range(15, 5, -1).inf == 6
assert Range(10, 67, 10).sup == 60
assert Range(60, 7, -10).inf == 10
assert len(Range(10, 38, 10)) == 3
assert Range(0, 0, 5) == empty
assert Range(oo, oo, 1) == empty
assert Range(oo, 1, 1) == empty
assert Range(-oo, 1, -1) == empty
assert Range(1, oo, -1) == empty
assert Range(1, -oo, 1) == empty
assert Range(1, -4, oo) == empty
ip = symbols('ip', positive=True)
assert Range(0, ip, -1) == empty
assert Range(0, -ip, 1) == empty
assert Range(1, -4, -oo) == Range(1, 2)
assert Range(1, 4, oo) == Range(1, 2)
assert Range(-oo, oo).size == oo
assert Range(oo, -oo, -1).size == oo
raises(ValueError, lambda: Range(-oo, oo, 2))
raises(ValueError, lambda: Range(x, pi, y))
raises(ValueError, lambda: Range(x, y, 0))
assert 5 in Range(0, oo, 5)
assert -5 in Range(-oo, 0, 5)
assert oo not in Range(0, oo)
ni = symbols('ni', integer=False)
assert ni not in Range(oo)
u = symbols('u', integer=None)
assert Range(oo).contains(u) is not False
inf = symbols('inf', infinite=True)
assert inf not in Range(-oo, oo)
raises(ValueError, lambda: Range(0, oo, 2)[-1])
raises(ValueError, lambda: Range(0, -oo, -2)[-1])
assert Range(-oo, 1, 1)[-1] is S.Zero
assert Range(oo, 1, -1)[-1] == 2
assert inf not in Range(oo)
assert Range(1, 10, 1)[-1] == 9
assert all(i.is_Integer for i in Range(0, -1, 1))
it = iter(Range(-oo, 0, 2))
raises(TypeError, lambda: next(it))
assert empty.intersect(S.Integers) == empty
assert Range(-1, 10, 1).intersect(S.Integers) == Range(-1, 10, 1)
assert Range(-1, 10, 1).intersect(S.Naturals) == Range(1, 10, 1)
assert Range(-1, 10, 1).intersect(S.Naturals0) == Range(0, 10, 1)
# test slicing
assert Range(1, 10, 1)[5] == 6
assert Range(1, 12, 2)[5] == 11
assert Range(1, 10, 1)[-1] == 9
assert Range(1, 10, 3)[-1] == 7
raises(ValueError, lambda: Range(oo,0,-1)[1:3:0])
raises(ValueError, lambda: Range(oo,0,-1)[:1])
raises(ValueError, lambda: Range(1, oo)[-2])
raises(ValueError, lambda: Range(-oo, 1)[2])
raises(IndexError, lambda: Range(10)[-20])
raises(IndexError, lambda: Range(10)[20])
raises(ValueError, lambda: Range(2, -oo, -2)[2:2:0])
assert Range(2, -oo, -2)[2:2:2] == empty
assert Range(2, -oo, -2)[:2:2] == Range(2, -2, -4)
raises(ValueError, lambda: Range(-oo, 4, 2)[:2:2])
assert Range(-oo, 4, 2)[::-2] == Range(2, -oo, -4)
raises(ValueError, lambda: Range(-oo, 4, 2)[::2])
assert Range(oo, 2, -2)[::] == Range(oo, 2, -2)
assert Range(-oo, 4, 2)[:-2:-2] == Range(2, 0, -4)
assert Range(-oo, 4, 2)[:-2:2] == Range(-oo, 0, 4)
raises(ValueError, lambda: Range(-oo, 4, 2)[:0:-2])
raises(ValueError, lambda: Range(-oo, 4, 2)[:2:-2])
assert Range(-oo, 4, 2)[-2::-2] == Range(0, -oo, -4)
raises(ValueError, lambda: Range(-oo, 4, 2)[-2:0:-2])
raises(ValueError, lambda: Range(-oo, 4, 2)[0::2])
assert Range(oo, 2, -2)[0::] == Range(oo, 2, -2)
raises(ValueError, lambda: Range(-oo, 4, 2)[0:-2:2])
assert Range(oo, 2, -2)[0:-2:] == Range(oo, 6, -2)
raises(ValueError, lambda: Range(oo, 2, -2)[0:2:])
raises(ValueError, lambda: Range(-oo, 4, 2)[2::-1])
assert Range(-oo, 4, 2)[-2::2] == Range(0, 4, 4)
assert Range(oo, 0, -2)[-10:0:2] == empty
raises(ValueError, lambda: Range(oo, 0, -2)[0])
raises(ValueError, lambda: Range(oo, 0, -2)[-10:10:2])
raises(ValueError, lambda: Range(oo, 0, -2)[0::-2])
assert Range(oo, 0, -2)[0:-4:-2] == empty
assert Range(oo, 0, -2)[:0:2] == empty
raises(ValueError, lambda: Range(oo, 0, -2)[:1:-1])
# test empty Range
assert Range(x, x, y) == empty
assert empty.reversed == empty
assert 0 not in empty
assert list(empty) == []
assert len(empty) == 0
assert empty.size is S.Zero
assert empty.intersect(FiniteSet(0)) is S.EmptySet
assert bool(empty) is False
raises(IndexError, lambda: empty[0])
assert empty[:0] == empty
raises(NotImplementedError, lambda: empty.inf)
raises(NotImplementedError, lambda: empty.sup)
assert empty.as_relational(x) is S.false
AB = [None] + list(range(12))
for R in [
Range(1, 10),
Range(1, 10, 2),
]:
r = list(R)
for a, b, c in itertools.product(AB, AB, [-3, -1, None, 1, 3]):
for reverse in range(2):
r = list(reversed(r))
R = R.reversed
result = list(R[a:b:c])
ans = r[a:b:c]
txt = ('\n%s[%s:%s:%s] = %s -> %s' % (
R, a, b, c, result, ans))
check = ans == result
assert check, txt
assert Range(1, 10, 1).boundary == Range(1, 10, 1)
for r in (Range(1, 10, 2), Range(1, oo, 2)):
rev = r.reversed
assert r.inf == rev.inf and r.sup == rev.sup
assert r.step == -rev.step
builtin_range = range
raises(TypeError, lambda: Range(builtin_range(1)))
assert S(builtin_range(10)) == Range(10)
assert S(builtin_range(1000000000000)) == Range(1000000000000)
# test Range.as_relational
assert Range(1, 4).as_relational(x) == (x >= 1) & (x <= 3) & Eq(Mod(x, 1), 0)
assert Range(oo, 1, -2).as_relational(x) == (x >= 3) & (x < oo) & Eq(Mod(x + 1, -2), 0)
def test_Range_symbolic():
# symbolic Range
xr = Range(x, x + 4, 5)
sr = Range(x, y, t)
i = Symbol('i', integer=True)
ip = Symbol('i', integer=True, positive=True)
ipr = Range(ip)
inr = Range(0, -ip, -1)
ir = Range(i, i + 19, 2)
ir2 = Range(i, i*8, 3*i)
i = Symbol('i', integer=True)
inf = symbols('inf', infinite=True)
raises(ValueError, lambda: Range(inf))
raises(ValueError, lambda: Range(inf, 0, -1))
raises(ValueError, lambda: Range(inf, inf, 1))
raises(ValueError, lambda: Range(1, 1, inf))
# args
assert xr.args == (x, x + 5, 5)
assert sr.args == (x, y, t)
assert ir.args == (i, i + 20, 2)
assert ir2.args == (i, 10*i, 3*i)
# reversed
raises(ValueError, lambda: xr.reversed)
raises(ValueError, lambda: sr.reversed)
assert ipr.reversed.args == (ip - 1, -1, -1)
assert inr.reversed.args == (-ip + 1, 1, 1)
assert ir.reversed.args == (i + 18, i - 2, -2)
assert ir2.reversed.args == (7*i, -2*i, -3*i)
# contains
assert inf not in sr
assert inf not in ir
assert 0 in ipr
assert 0 in inr
raises(TypeError, lambda: 1 in ipr)
raises(TypeError, lambda: -1 in inr)
assert .1 not in sr
assert .1 not in ir
assert i + 1 not in ir
assert i + 2 in ir
raises(TypeError, lambda: x in xr) # XXX is this what contains is supposed to do?
raises(TypeError, lambda: 1 in sr) # XXX is this what contains is supposed to do?
# iter
raises(ValueError, lambda: next(iter(xr)))
raises(ValueError, lambda: next(iter(sr)))
assert next(iter(ir)) == i
assert next(iter(ir2)) == i
assert sr.intersect(S.Integers) == sr
assert sr.intersect(FiniteSet(x)) == Intersection({x}, sr)
raises(ValueError, lambda: sr[:2])
raises(ValueError, lambda: xr[0])
raises(ValueError, lambda: sr[0])
# len
assert len(ir) == ir.size == 10
assert len(ir2) == ir2.size == 3
raises(ValueError, lambda: len(xr))
raises(ValueError, lambda: xr.size)
raises(ValueError, lambda: len(sr))
raises(ValueError, lambda: sr.size)
# bool
assert bool(Range(0)) == False
assert bool(xr)
assert bool(ir)
assert bool(ipr)
assert bool(inr)
raises(ValueError, lambda: bool(sr))
raises(ValueError, lambda: bool(ir2))
# inf
raises(ValueError, lambda: xr.inf)
raises(ValueError, lambda: sr.inf)
assert ipr.inf == 0
assert inr.inf == -ip + 1
assert ir.inf == i
raises(ValueError, lambda: ir2.inf)
# sup
raises(ValueError, lambda: xr.sup)
raises(ValueError, lambda: sr.sup)
assert ipr.sup == ip - 1
assert inr.sup == 0
assert ir.inf == i
raises(ValueError, lambda: ir2.sup)
# getitem
raises(ValueError, lambda: xr[0])
raises(ValueError, lambda: sr[0])
raises(ValueError, lambda: sr[-1])
raises(ValueError, lambda: sr[:2])
assert ir[:2] == Range(i, i + 4, 2)
assert ir[0] == i
assert ir[-2] == i + 16
assert ir[-1] == i + 18
assert ir2[:2] == Range(i, 7*i, 3*i)
assert ir2[0] == i
assert ir2[-2] == 4*i
assert ir2[-1] == 7*i
raises(ValueError, lambda: Range(i)[-1])
assert ipr[0] == ipr.inf == 0
assert ipr[-1] == ipr.sup == ip - 1
assert inr[0] == inr.sup == 0
assert inr[-1] == inr.inf == -ip + 1
raises(ValueError, lambda: ipr[-2])
assert ir.inf == i
assert ir.sup == i + 18
raises(ValueError, lambda: Range(i).inf)
# as_relational
assert ir.as_relational(x) == ((x >= i) & (x <= i + 18) &
Eq(Mod(-i + x, 2), 0))
assert ir2.as_relational(x) == Eq(
Mod(-i + x, 3*i), 0) & (((x >= i) & (x <= 7*i) & (3*i >= 1)) |
((x <= i) & (x >= 7*i) & (3*i <= -1)))
assert Range(i, i + 1).as_relational(x) == Eq(x, i)
assert sr.as_relational(z) == Eq(
Mod(t, 1), 0) & Eq(Mod(x, 1), 0) & Eq(Mod(-x + z, t), 0
) & (((z >= x) & (z <= -t + y) & (t >= 1)) |
((z <= x) & (z >= -t + y) & (t <= -1)))
assert xr.as_relational(z) == Eq(z, x) & Eq(Mod(x, 1), 0)
# symbols can clash if user wants (but it must be integer)
assert xr.as_relational(x) == Eq(Mod(x, 1), 0)
# contains() for symbolic values (issue #18146)
e = Symbol('e', integer=True, even=True)
o = Symbol('o', integer=True, odd=True)
assert Range(5).contains(i) == And(i >= 0, i <= 4)
assert Range(1).contains(i) == Eq(i, 0)
assert Range(-oo, 5, 1).contains(i) == (i <= 4)
assert Range(-oo, oo).contains(i) == True
assert Range(0, 8, 2).contains(i) == Contains(i, Range(0, 8, 2))
assert Range(0, 8, 2).contains(e) == And(e >= 0, e <= 6)
assert Range(0, 8, 2).contains(2*i) == And(2*i >= 0, 2*i <= 6)
assert Range(0, 8, 2).contains(o) == False
assert Range(1, 9, 2).contains(e) == False
assert Range(1, 9, 2).contains(o) == And(o >= 1, o <= 7)
assert Range(8, 0, -2).contains(o) == False
assert Range(9, 1, -2).contains(o) == And(o >= 3, o <= 9)
assert Range(-oo, 8, 2).contains(i) == Contains(i, Range(-oo, 8, 2))
def test_range_range_intersection():
for a, b, r in [
(Range(0), Range(1), S.EmptySet),
(Range(3), Range(4, oo), S.EmptySet),
(Range(3), Range(-3, -1), S.EmptySet),
(Range(1, 3), Range(0, 3), Range(1, 3)),
(Range(1, 3), Range(1, 4), Range(1, 3)),
(Range(1, oo, 2), Range(2, oo, 2), S.EmptySet),
(Range(0, oo, 2), Range(oo), Range(0, oo, 2)),
(Range(0, oo, 2), Range(100), Range(0, 100, 2)),
(Range(2, oo, 2), Range(oo), Range(2, oo, 2)),
(Range(0, oo, 2), Range(5, 6), S.EmptySet),
(Range(2, 80, 1), Range(55, 71, 4), Range(55, 71, 4)),
(Range(0, 6, 3), Range(-oo, 5, 3), S.EmptySet),
(Range(0, oo, 2), Range(5, oo, 3), Range(8, oo, 6)),
(Range(4, 6, 2), Range(2, 16, 7), S.EmptySet),]:
assert a.intersect(b) == r
assert a.intersect(b.reversed) == r
assert a.reversed.intersect(b) == r
assert a.reversed.intersect(b.reversed) == r
a, b = b, a
assert a.intersect(b) == r
assert a.intersect(b.reversed) == r
assert a.reversed.intersect(b) == r
assert a.reversed.intersect(b.reversed) == r
def test_range_interval_intersection():
p = symbols('p', positive=True)
assert isinstance(Range(3).intersect(Interval(p, p + 2)), Intersection)
assert Range(4).intersect(Interval(0, 3)) == Range(4)
assert Range(4).intersect(Interval(-oo, oo)) == Range(4)
assert Range(4).intersect(Interval(1, oo)) == Range(1, 4)
assert Range(4).intersect(Interval(1.1, oo)) == Range(2, 4)
assert Range(4).intersect(Interval(0.1, 3)) == Range(1, 4)
assert Range(4).intersect(Interval(0.1, 3.1)) == Range(1, 4)
assert Range(4).intersect(Interval.open(0, 3)) == Range(1, 3)
assert Range(4).intersect(Interval.open(0.1, 0.5)) is S.EmptySet
# Null Range intersections
assert Range(0).intersect(Interval(0.2, 0.8)) is S.EmptySet
assert Range(0).intersect(Interval(-oo, oo)) is S.EmptySet
def test_range_is_finite_set():
assert Range(-100, 100).is_finite_set is True
assert Range(2, oo).is_finite_set is False
assert Range(-oo, 50).is_finite_set is False
assert Range(-oo, oo).is_finite_set is False
assert Range(oo, -oo).is_finite_set is True
assert Range(0, 0).is_finite_set is True
assert Range(oo, oo).is_finite_set is True
assert Range(-oo, -oo).is_finite_set is True
n = Symbol('n', integer=True)
m = Symbol('m', integer=True)
assert Range(n, n + 49).is_finite_set is True
assert Range(n, 0).is_finite_set is True
assert Range(-3, n + 7).is_finite_set is True
assert Range(n, m).is_finite_set is True
assert Range(n + m, m - n).is_finite_set is True
assert Range(n, n + m + n).is_finite_set is True
assert Range(n, oo).is_finite_set is False
assert Range(-oo, n).is_finite_set is False
assert Range(n, -oo).is_finite_set is True
assert Range(oo, n).is_finite_set is True
def test_Range_is_iterable():
assert Range(-100, 100).is_iterable is True
assert Range(2, oo).is_iterable is False
assert Range(-oo, 50).is_iterable is False
assert Range(-oo, oo).is_iterable is False
assert Range(oo, -oo).is_iterable is True
assert Range(0, 0).is_iterable is True
assert Range(oo, oo).is_iterable is True
assert Range(-oo, -oo).is_iterable is True
n = Symbol('n', integer=True)
m = Symbol('m', integer=True)
p = Symbol('p', integer=True, positive=True)
assert Range(n, n + 49).is_iterable is True
assert Range(n, 0).is_iterable is False
assert Range(-3, n + 7).is_iterable is False
assert Range(-3, p + 7).is_iterable is False # Should work with better __iter__
assert Range(n, m).is_iterable is False
assert Range(n + m, m - n).is_iterable is False
assert Range(n, n + m + n).is_iterable is False
assert Range(n, oo).is_iterable is False
assert Range(-oo, n).is_iterable is False
x = Symbol('x')
assert Range(x, x + 49).is_iterable is False
assert Range(x, 0).is_iterable is False
assert Range(-3, x + 7).is_iterable is False
assert Range(x, m).is_iterable is False
assert Range(x + m, m - x).is_iterable is False
assert Range(x, x + m + x).is_iterable is False
assert Range(x, oo).is_iterable is False
assert Range(-oo, x).is_iterable is False
def test_Integers_eval_imageset():
ans = ImageSet(Lambda(x, 2*x + Rational(3, 7)), S.Integers)
im = imageset(Lambda(x, -2*x + Rational(3, 7)), S.Integers)
assert im == ans
im = imageset(Lambda(x, -2*x - Rational(11, 7)), S.Integers)
assert im == ans
y = Symbol('y')
L = imageset(x, 2*x + y, S.Integers)
assert y + 4 in L
a, b, c = 0.092, 0.433, 0.341
assert a in imageset(x, a + c*x, S.Integers)
assert b in imageset(x, b + c*x, S.Integers)
_x = symbols('x', negative=True)
eq = _x**2 - _x + 1
assert imageset(_x, eq, S.Integers).lamda.expr == _x**2 + _x + 1
eq = 3*_x - 1
assert imageset(_x, eq, S.Integers).lamda.expr == 3*_x + 2
assert imageset(x, (x, 1/x), S.Integers) == \
ImageSet(Lambda(x, (x, 1/x)), S.Integers)
def test_Range_eval_imageset():
a, b, c = symbols('a b c')
assert imageset(x, a*(x + b) + c, Range(3)) == \
imageset(x, a*x + a*b + c, Range(3))
eq = (x + 1)**2
assert imageset(x, eq, Range(3)).lamda.expr == eq
eq = a*(x + b) + c
r = Range(3, -3, -2)
imset = imageset(x, eq, r)
assert imset.lamda.expr != eq
assert list(imset) == [eq.subs(x, i).expand() for i in list(r)]
def test_fun():
assert (FiniteSet(*ImageSet(Lambda(x, sin(pi*x/4)),
Range(-10, 11))) == FiniteSet(-1, -sqrt(2)/2, 0, sqrt(2)/2, 1))
def test_Range_is_empty():
i = Symbol('i', integer=True)
n = Symbol('n', negative=True, integer=True)
p = Symbol('p', positive=True, integer=True)
assert Range(0).is_empty
assert not Range(1).is_empty
assert Range(1, 0).is_empty
assert not Range(-1, 0).is_empty
assert Range(i).is_empty is None
assert Range(n).is_empty
assert Range(p).is_empty is False
assert Range(n, 0).is_empty is False
assert Range(n, p).is_empty is False
assert Range(p, n).is_empty
assert Range(n, -1).is_empty is None
assert Range(p, n, -1).is_empty is False
def test_Reals():
assert 5 in S.Reals
assert S.Pi in S.Reals
assert -sqrt(2) in S.Reals
assert (2, 5) not in S.Reals
assert sqrt(-1) not in S.Reals
assert S.Reals == Interval(-oo, oo)
assert S.Reals != Interval(0, oo)
assert S.Reals.is_subset(Interval(-oo, oo))
assert S.Reals.intersect(Range(-oo, oo)) == Range(-oo, oo)
assert S.ComplexInfinity not in S.Reals
assert S.NaN not in S.Reals
assert x + S.ComplexInfinity not in S.Reals
def test_Complex():
assert 5 in S.Complexes
assert 5 + 4*I in S.Complexes
assert S.Pi in S.Complexes
assert -sqrt(2) in S.Complexes
assert -I in S.Complexes
assert sqrt(-1) in S.Complexes
assert S.Complexes.intersect(S.Reals) == S.Reals
assert S.Complexes.union(S.Reals) == S.Complexes
assert S.Complexes == ComplexRegion(S.Reals*S.Reals)
assert (S.Complexes == ComplexRegion(Interval(1, 2)*Interval(3, 4))) == False
assert str(S.Complexes) == "Complexes"
assert repr(S.Complexes) == "Complexes"
def take(n, iterable):
"Return first n items of the iterable as a list"
return list(itertools.islice(iterable, n))
def test_intersections():
assert S.Integers.intersect(S.Reals) == S.Integers
assert 5 in S.Integers.intersect(S.Reals)
assert 5 in S.Integers.intersect(S.Reals)
assert -5 not in S.Naturals.intersect(S.Reals)
assert 5.5 not in S.Integers.intersect(S.Reals)
assert 5 in S.Integers.intersect(Interval(3, oo))
assert -5 in S.Integers.intersect(Interval(-oo, 3))
assert all(x.is_Integer
for x in take(10, S.Integers.intersect(Interval(3, oo)) ))
def test_infinitely_indexed_set_1():
from sympy.abc import n, m
assert imageset(Lambda(n, n), S.Integers) == imageset(Lambda(m, m), S.Integers)
assert imageset(Lambda(n, 2*n), S.Integers).intersect(
imageset(Lambda(m, 2*m + 1), S.Integers)) is S.EmptySet
assert imageset(Lambda(n, 2*n), S.Integers).intersect(
imageset(Lambda(n, 2*n + 1), S.Integers)) is S.EmptySet
assert imageset(Lambda(m, 2*m), S.Integers).intersect(
imageset(Lambda(n, 3*n), S.Integers)).dummy_eq(
ImageSet(Lambda(t, 6*t), S.Integers))
assert imageset(x, x/2 + Rational(1, 3), S.Integers).intersect(S.Integers) is S.EmptySet
assert imageset(x, x/2 + S.Half, S.Integers).intersect(S.Integers) is S.Integers
# https://github.com/sympy/sympy/issues/17355
S53 = ImageSet(Lambda(n, 5*n + 3), S.Integers)
assert S53.intersect(S.Integers) == S53
def test_infinitely_indexed_set_2():
from sympy.abc import n
a = Symbol('a', integer=True)
assert imageset(Lambda(n, n), S.Integers) == \
imageset(Lambda(n, n + a), S.Integers)
assert imageset(Lambda(n, n + pi), S.Integers) == \
imageset(Lambda(n, n + a + pi), S.Integers)
assert imageset(Lambda(n, n), S.Integers) == \
imageset(Lambda(n, -n + a), S.Integers)
assert imageset(Lambda(n, -6*n), S.Integers) == \
ImageSet(Lambda(n, 6*n), S.Integers)
assert imageset(Lambda(n, 2*n + pi), S.Integers) == \
ImageSet(Lambda(n, 2*n + pi - 2), S.Integers)
def test_imageset_intersect_real():
from sympy.abc import n
assert imageset(Lambda(n, n + (n - 1)*(n + 1)*I), S.Integers).intersect(S.Reals) == FiniteSet(-1, 1)
im = (n - 1)*(n + S.Half)
assert imageset(Lambda(n, n + im*I), S.Integers
).intersect(S.Reals) == FiniteSet(1)
assert imageset(Lambda(n, n + im*(n + 1)*I), S.Naturals0
).intersect(S.Reals) == FiniteSet(1)
assert imageset(Lambda(n, n/2 + im.expand()*I), S.Integers
).intersect(S.Reals) == ImageSet(Lambda(x, x/2), ConditionSet(
n, Eq(n**2 - n/2 - S(1)/2, 0), S.Integers))
assert imageset(Lambda(n, n/(1/n - 1) + im*(n + 1)*I), S.Integers
).intersect(S.Reals) == FiniteSet(S.Half)
assert imageset(Lambda(n, n/(n - 6) +
(n - 3)*(n + 1)*I/(2*n + 2)), S.Integers).intersect(
S.Reals) == FiniteSet(-1)
assert imageset(Lambda(n, n/(n**2 - 9) +
(n - 3)*(n + 1)*I/(2*n + 2)), S.Integers).intersect(
S.Reals) is S.EmptySet
s = ImageSet(
Lambda(n, -I*(I*(2*pi*n - pi/4) + log(Abs(sqrt(-I))))),
S.Integers)
# s is unevaluated, but after intersection the result
# should be canonical
assert s.intersect(S.Reals) == imageset(
Lambda(n, 2*n*pi - pi/4), S.Integers) == ImageSet(
Lambda(n, 2*pi*n + pi*Rational(7, 4)), S.Integers)
def test_imageset_intersect_interval():
from sympy.abc import n
f1 = ImageSet(Lambda(n, n*pi), S.Integers)
f2 = ImageSet(Lambda(n, 2*n), Interval(0, pi))
f3 = ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers)
# complex expressions
f4 = ImageSet(Lambda(n, n*I*pi), S.Integers)
f5 = ImageSet(Lambda(n, 2*I*n*pi + pi/2), S.Integers)
# non-linear expressions
f6 = ImageSet(Lambda(n, log(n)), S.Integers)
f7 = ImageSet(Lambda(n, n**2), S.Integers)
f8 = ImageSet(Lambda(n, Abs(n)), S.Integers)
f9 = ImageSet(Lambda(n, exp(n)), S.Naturals0)
assert f1.intersect(Interval(-1, 1)) == FiniteSet(0)
assert f1.intersect(Interval(0, 2*pi, False, True)) == FiniteSet(0, pi)
assert f2.intersect(Interval(1, 2)) == Interval(1, 2)
assert f3.intersect(Interval(-1, 1)) == S.EmptySet
assert f3.intersect(Interval(-5, 5)) == FiniteSet(pi*Rational(-3, 2), pi/2)
assert f4.intersect(Interval(-1, 1)) == FiniteSet(0)
assert f4.intersect(Interval(1, 2)) == S.EmptySet
assert f5.intersect(Interval(0, 1)) == S.EmptySet
assert f6.intersect(Interval(0, 1)) == FiniteSet(S.Zero, log(2))
assert f7.intersect(Interval(0, 10)) == Intersection(f7, Interval(0, 10))
assert f8.intersect(Interval(0, 2)) == Intersection(f8, Interval(0, 2))
assert f9.intersect(Interval(1, 2)) == Intersection(f9, Interval(1, 2))
def test_imageset_intersect_diophantine():
from sympy.abc import m, n
# Check that same lambda variable for both ImageSets is handled correctly
img1 = ImageSet(Lambda(n, 2*n + 1), S.Integers)
img2 = ImageSet(Lambda(n, 4*n + 1), S.Integers)
assert img1.intersect(img2) == img2
# Empty solution set returned by diophantine:
assert ImageSet(Lambda(n, 2*n), S.Integers).intersect(
ImageSet(Lambda(n, 2*n + 1), S.Integers)) == S.EmptySet
# Check intersection with S.Integers:
assert ImageSet(Lambda(n, 9/n + 20*n/3), S.Integers).intersect(
S.Integers) == FiniteSet(-61, -23, 23, 61)
# Single solution (2, 3) for diophantine solution:
assert ImageSet(Lambda(n, (n - 2)**2), S.Integers).intersect(
ImageSet(Lambda(n, -(n - 3)**2), S.Integers)) == FiniteSet(0)
# Single parametric solution for diophantine solution:
assert ImageSet(Lambda(n, n**2 + 5), S.Integers).intersect(
ImageSet(Lambda(m, 2*m), S.Integers)).dummy_eq(ImageSet(
Lambda(n, 4*n**2 + 4*n + 6), S.Integers))
# 4 non-parametric solution couples for dioph. equation:
assert ImageSet(Lambda(n, n**2 - 9), S.Integers).intersect(
ImageSet(Lambda(m, -m**2), S.Integers)) == FiniteSet(-9, 0)
# Double parametric solution for diophantine solution:
assert ImageSet(Lambda(m, m**2 + 40), S.Integers).intersect(
ImageSet(Lambda(n, 41*n), S.Integers)).dummy_eq(Intersection(
ImageSet(Lambda(m, m**2 + 40), S.Integers),
ImageSet(Lambda(n, 41*n), S.Integers)))
# Check that diophantine returns *all* (8) solutions (permute=True)
assert ImageSet(Lambda(n, n**4 - 2**4), S.Integers).intersect(
ImageSet(Lambda(m, -m**4 + 3**4), S.Integers)) == FiniteSet(0, 65)
assert ImageSet(Lambda(n, pi/12 + n*5*pi/12), S.Integers).intersect(
ImageSet(Lambda(n, 7*pi/12 + n*11*pi/12), S.Integers)).dummy_eq(ImageSet(
Lambda(n, 55*pi*n/12 + 17*pi/4), S.Integers))
# TypeError raised by diophantine (#18081)
assert ImageSet(Lambda(n, n*log(2)), S.Integers).intersection(
S.Integers).dummy_eq(Intersection(ImageSet(
Lambda(n, n*log(2)), S.Integers), S.Integers))
# NotImplementedError raised by diophantine (no solver for cubic_thue)
assert ImageSet(Lambda(n, n**3 + 1), S.Integers).intersect(
ImageSet(Lambda(n, n**3), S.Integers)).dummy_eq(Intersection(
ImageSet(Lambda(n, n**3 + 1), S.Integers),
ImageSet(Lambda(n, n**3), S.Integers)))
def test_infinitely_indexed_set_3():
from sympy.abc import n, m
assert imageset(Lambda(m, 2*pi*m), S.Integers).intersect(
imageset(Lambda(n, 3*pi*n), S.Integers)).dummy_eq(
ImageSet(Lambda(t, 6*pi*t), S.Integers))
assert imageset(Lambda(n, 2*n + 1), S.Integers) == \
imageset(Lambda(n, 2*n - 1), S.Integers)
assert imageset(Lambda(n, 3*n + 2), S.Integers) == \
imageset(Lambda(n, 3*n - 1), S.Integers)
def test_ImageSet_simplification():
from sympy.abc import n, m
assert imageset(Lambda(n, n), S.Integers) == S.Integers
assert imageset(Lambda(n, sin(n)),
imageset(Lambda(m, tan(m)), S.Integers)) == \
imageset(Lambda(m, sin(tan(m))), S.Integers)
assert imageset(n, 1 + 2*n, S.Naturals) == Range(3, oo, 2)
assert imageset(n, 1 + 2*n, S.Naturals0) == Range(1, oo, 2)
assert imageset(n, 1 - 2*n, S.Naturals) == Range(-1, -oo, -2)
def test_ImageSet_contains():
assert (2, S.Half) in imageset(x, (x, 1/x), S.Integers)
assert imageset(x, x + I*3, S.Integers).intersection(S.Reals) is S.EmptySet
i = Dummy(integer=True)
q = imageset(x, x + I*y, S.Integers).intersection(S.Reals)
assert q.subs(y, I*i).intersection(S.Integers) is S.Integers
q = imageset(x, x + I*y/x, S.Integers).intersection(S.Reals)
assert q.subs(y, 0) is S.Integers
assert q.subs(y, I*i*x).intersection(S.Integers) is S.Integers
z = cos(1)**2 + sin(1)**2 - 1
q = imageset(x, x + I*z, S.Integers).intersection(S.Reals)
assert q is not S.EmptySet
def test_ComplexRegion_contains():
r = Symbol('r', real=True)
# contains in ComplexRegion
a = Interval(2, 3)
b = Interval(4, 6)
c = Interval(7, 9)
c1 = ComplexRegion(a*b)
c2 = ComplexRegion(Union(a*b, c*a))
assert 2.5 + 4.5*I in c1
assert 2 + 4*I in c1
assert 3 + 4*I in c1
assert 8 + 2.5*I in c2
assert 2.5 + 6.1*I not in c1
assert 4.5 + 3.2*I not in c1
assert c1.contains(x) == Contains(x, c1, evaluate=False)
assert c1.contains(r) == False
assert c2.contains(x) == Contains(x, c2, evaluate=False)
assert c2.contains(r) == False
r1 = Interval(0, 1)
theta1 = Interval(0, 2*S.Pi)
c3 = ComplexRegion(r1*theta1, polar=True)
assert (0.5 + I*6/10) in c3
assert (S.Half + I*6/10) in c3
assert (S.Half + .6*I) in c3
assert (0.5 + .6*I) in c3
assert I in c3
assert 1 in c3
assert 0 in c3
assert 1 + I not in c3
assert 1 - I not in c3
assert c3.contains(x) == Contains(x, c3, evaluate=False)
assert c3.contains(r + 2*I) == Contains(
r + 2*I, c3, evaluate=False) # is in fact False
assert c3.contains(1/(1 + r**2)) == Contains(
1/(1 + r**2), c3, evaluate=False) # is in fact True
r2 = Interval(0, 3)
theta2 = Interval(pi, 2*pi, left_open=True)
c4 = ComplexRegion(r2*theta2, polar=True)
assert c4.contains(0) == True
assert c4.contains(2 + I) == False
assert c4.contains(-2 + I) == False
assert c4.contains(-2 - I) == True
assert c4.contains(2 - I) == True
assert c4.contains(-2) == False
assert c4.contains(2) == True
assert c4.contains(x) == Contains(x, c4, evaluate=False)
assert c4.contains(3/(1 + r**2)) == Contains(
3/(1 + r**2), c4, evaluate=False) # is in fact True
raises(ValueError, lambda: ComplexRegion(r1*theta1, polar=2))
def test_symbolic_Range():
n = Symbol('n')
raises(ValueError, lambda: Range(n)[0])
raises(IndexError, lambda: Range(n, n)[0])
raises(ValueError, lambda: Range(n, n+1)[0])
raises(ValueError, lambda: Range(n).size)
n = Symbol('n', integer=True)
raises(ValueError, lambda: Range(n)[0])
raises(IndexError, lambda: Range(n, n)[0])
assert Range(n, n+1)[0] == n
raises(ValueError, lambda: Range(n).size)
assert Range(n, n+1).size == 1
n = Symbol('n', integer=True, nonnegative=True)
raises(ValueError, lambda: Range(n)[0])
raises(IndexError, lambda: Range(n, n)[0])
assert Range(n+1)[0] == 0
assert Range(n, n+1)[0] == n
assert Range(n).size == n
assert Range(n+1).size == n+1
assert Range(n, n+1).size == 1
n = Symbol('n', integer=True, positive=True)
assert Range(n)[0] == 0
assert Range(n, n+1)[0] == n
assert Range(n).size == n
assert Range(n, n+1).size == 1
m = Symbol('m', integer=True, positive=True)
assert Range(n, n+m)[0] == n
assert Range(n, n+m).size == m
assert Range(n, n+1).size == 1
assert Range(n, n+m, 2).size == floor(m/2)
m = Symbol('m', integer=True, positive=True, even=True)
assert Range(n, n+m, 2).size == m/2
def test_issue_18400():
n = Symbol('n', integer=True)
raises(ValueError, lambda: imageset(lambda x: x*2, Range(n)))
n = Symbol('n', integer=True, positive=True)
# No exception
assert imageset(lambda x: x*2, Range(n)) == imageset(lambda x: x*2, Range(n))
def test_ComplexRegion_intersect():
# Polar form
X_axis = ComplexRegion(Interval(0, oo)*FiniteSet(0, S.Pi), polar=True)
unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
upper_half_unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True)
upper_half_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True)
lower_half_disk = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True)
right_half_disk = ComplexRegion(Interval(0, oo)*Interval(-S.Pi/2, S.Pi/2), polar=True)
first_quad_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi/2), polar=True)
assert upper_half_disk.intersect(unit_disk) == upper_half_unit_disk
assert right_half_disk.intersect(first_quad_disk) == first_quad_disk
assert upper_half_disk.intersect(right_half_disk) == first_quad_disk
assert upper_half_disk.intersect(lower_half_disk) == X_axis
c1 = ComplexRegion(Interval(0, 4)*Interval(0, 2*S.Pi), polar=True)
assert c1.intersect(Interval(1, 5)) == Interval(1, 4)
assert c1.intersect(Interval(4, 9)) == FiniteSet(4)
assert c1.intersect(Interval(5, 12)) is S.EmptySet
# Rectangular form
X_axis = ComplexRegion(Interval(-oo, oo)*FiniteSet(0))
unit_square = ComplexRegion(Interval(-1, 1)*Interval(-1, 1))
upper_half_unit_square = ComplexRegion(Interval(-1, 1)*Interval(0, 1))
upper_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(0, oo))
lower_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(-oo, 0))
right_half_plane = ComplexRegion(Interval(0, oo)*Interval(-oo, oo))
first_quad_plane = ComplexRegion(Interval(0, oo)*Interval(0, oo))
assert upper_half_plane.intersect(unit_square) == upper_half_unit_square
assert right_half_plane.intersect(first_quad_plane) == first_quad_plane
assert upper_half_plane.intersect(right_half_plane) == first_quad_plane
assert upper_half_plane.intersect(lower_half_plane) == X_axis
c1 = ComplexRegion(Interval(-5, 5)*Interval(-10, 10))
assert c1.intersect(Interval(2, 7)) == Interval(2, 5)
assert c1.intersect(Interval(5, 7)) == FiniteSet(5)
assert c1.intersect(Interval(6, 9)) is S.EmptySet
# unevaluated object
C1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
C2 = ComplexRegion(Interval(-1, 1)*Interval(-1, 1))
assert C1.intersect(C2) == Intersection(C1, C2, evaluate=False)
def test_ComplexRegion_union():
# Polar form
c1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
c2 = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True)
c3 = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True)
c4 = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True)
p1 = Union(Interval(0, 1)*Interval(0, 2*S.Pi), Interval(0, 1)*Interval(0, S.Pi))
p2 = Union(Interval(0, oo)*Interval(0, S.Pi), Interval(0, oo)*Interval(S.Pi, 2*S.Pi))
assert c1.union(c2) == ComplexRegion(p1, polar=True)
assert c3.union(c4) == ComplexRegion(p2, polar=True)
# Rectangular form
c5 = ComplexRegion(Interval(2, 5)*Interval(6, 9))
c6 = ComplexRegion(Interval(4, 6)*Interval(10, 12))
c7 = ComplexRegion(Interval(0, 10)*Interval(-10, 0))
c8 = ComplexRegion(Interval(12, 16)*Interval(14, 20))
p3 = Union(Interval(2, 5)*Interval(6, 9), Interval(4, 6)*Interval(10, 12))
p4 = Union(Interval(0, 10)*Interval(-10, 0), Interval(12, 16)*Interval(14, 20))
assert c5.union(c6) == ComplexRegion(p3)
assert c7.union(c8) == ComplexRegion(p4)
assert c1.union(Interval(2, 4)) == Union(c1, Interval(2, 4), evaluate=False)
assert c5.union(Interval(2, 4)) == Union(c5, ComplexRegion.from_real(Interval(2, 4)))
def test_ComplexRegion_from_real():
c1 = ComplexRegion(Interval(0, 1) * Interval(0, 2 * S.Pi), polar=True)
raises(ValueError, lambda: c1.from_real(c1))
assert c1.from_real(Interval(-1, 1)) == ComplexRegion(Interval(-1, 1) * FiniteSet(0), False)
def test_ComplexRegion_measure():
a, b = Interval(2, 5), Interval(4, 8)
theta1, theta2 = Interval(0, 2*S.Pi), Interval(0, S.Pi)
c1 = ComplexRegion(a*b)
c2 = ComplexRegion(Union(a*theta1, b*theta2), polar=True)
assert c1.measure == 12
assert c2.measure == 9*pi
def test_normalize_theta_set():
# Interval
assert normalize_theta_set(Interval(pi, 2*pi)) == \
Union(FiniteSet(0), Interval.Ropen(pi, 2*pi))
assert normalize_theta_set(Interval(pi*Rational(9, 2), 5*pi)) == Interval(pi/2, pi)
assert normalize_theta_set(Interval(pi*Rational(-3, 2), pi/2)) == Interval.Ropen(0, 2*pi)
assert normalize_theta_set(Interval.open(pi*Rational(-3, 2), pi/2)) == \
Union(Interval.Ropen(0, pi/2), Interval.open(pi/2, 2*pi))
assert normalize_theta_set(Interval.open(pi*Rational(-7, 2), pi*Rational(-3, 2))) == \
Union(Interval.Ropen(0, pi/2), Interval.open(pi/2, 2*pi))
assert normalize_theta_set(Interval(-pi/2, pi/2)) == \
Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi))
assert normalize_theta_set(Interval.open(-pi/2, pi/2)) == \
Union(Interval.Ropen(0, pi/2), Interval.open(pi*Rational(3, 2), 2*pi))
assert normalize_theta_set(Interval(-4*pi, 3*pi)) == Interval.Ropen(0, 2*pi)
assert normalize_theta_set(Interval(pi*Rational(-3, 2), -pi/2)) == Interval(pi/2, pi*Rational(3, 2))
assert normalize_theta_set(Interval.open(0, 2*pi)) == Interval.open(0, 2*pi)
assert normalize_theta_set(Interval.Ropen(-pi/2, pi/2)) == \
Union(Interval.Ropen(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi))
assert normalize_theta_set(Interval.Lopen(-pi/2, pi/2)) == \
Union(Interval(0, pi/2), Interval.open(pi*Rational(3, 2), 2*pi))
assert normalize_theta_set(Interval(-pi/2, pi/2)) == \
Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi))
assert normalize_theta_set(Interval.open(4*pi, pi*Rational(9, 2))) == Interval.open(0, pi/2)
assert normalize_theta_set(Interval.Lopen(4*pi, pi*Rational(9, 2))) == Interval.Lopen(0, pi/2)
assert normalize_theta_set(Interval.Ropen(4*pi, pi*Rational(9, 2))) == Interval.Ropen(0, pi/2)
assert normalize_theta_set(Interval.open(3*pi, 5*pi)) == \
Union(Interval.Ropen(0, pi), Interval.open(pi, 2*pi))
# FiniteSet
assert normalize_theta_set(FiniteSet(0, pi, 3*pi)) == FiniteSet(0, pi)
assert normalize_theta_set(FiniteSet(0, pi/2, pi, 2*pi)) == FiniteSet(0, pi/2, pi)
assert normalize_theta_set(FiniteSet(0, -pi/2, -pi, -2*pi)) == FiniteSet(0, pi, pi*Rational(3, 2))
assert normalize_theta_set(FiniteSet(pi*Rational(-3, 2), pi/2)) == \
FiniteSet(pi/2)
assert normalize_theta_set(FiniteSet(2*pi)) == FiniteSet(0)
# Unions
assert normalize_theta_set(Union(Interval(0, pi/3), Interval(pi/2, pi))) == \
Union(Interval(0, pi/3), Interval(pi/2, pi))
assert normalize_theta_set(Union(Interval(0, pi), Interval(2*pi, pi*Rational(7, 3)))) == \
Interval(0, pi)
# ValueError for non-real sets
raises(ValueError, lambda: normalize_theta_set(S.Complexes))
# NotImplementedError for subset of reals
raises(NotImplementedError, lambda: normalize_theta_set(Interval(0, 1)))
# NotImplementedError without pi as coefficient
raises(NotImplementedError, lambda: normalize_theta_set(Interval(1, 2*pi)))
raises(NotImplementedError, lambda: normalize_theta_set(Interval(2*pi, 10)))
raises(NotImplementedError, lambda: normalize_theta_set(FiniteSet(0, 3, 3*pi)))
def test_ComplexRegion_FiniteSet():
x, y, z, a, b, c = symbols('x y z a b c')
# Issue #9669
assert ComplexRegion(FiniteSet(a, b, c)*FiniteSet(x, y, z)) == \
FiniteSet(a + I*x, a + I*y, a + I*z, b + I*x, b + I*y,
b + I*z, c + I*x, c + I*y, c + I*z)
assert ComplexRegion(FiniteSet(2)*FiniteSet(3)) == FiniteSet(2 + 3*I)
def test_union_RealSubSet():
assert (S.Complexes).union(Interval(1, 2)) == S.Complexes
assert (S.Complexes).union(S.Integers) == S.Complexes
def test_issue_9980():
c1 = ComplexRegion(Interval(1, 2)*Interval(2, 3))
c2 = ComplexRegion(Interval(1, 5)*Interval(1, 3))
R = Union(c1, c2)
assert simplify(R) == ComplexRegion(Union(Interval(1, 2)*Interval(2, 3), \
Interval(1, 5)*Interval(1, 3)), False)
assert c1.func(*c1.args) == c1
assert R.func(*R.args) == R
def test_issue_11732():
interval12 = Interval(1, 2)
finiteset1234 = FiniteSet(1, 2, 3, 4)
pointComplex = Tuple(1, 5)
assert (interval12 in S.Naturals) == False
assert (interval12 in S.Naturals0) == False
assert (interval12 in S.Integers) == False
assert (interval12 in S.Complexes) == False
assert (finiteset1234 in S.Naturals) == False
assert (finiteset1234 in S.Naturals0) == False
assert (finiteset1234 in S.Integers) == False
assert (finiteset1234 in S.Complexes) == False
assert (pointComplex in S.Naturals) == False
assert (pointComplex in S.Naturals0) == False
assert (pointComplex in S.Integers) == False
assert (pointComplex in S.Complexes) == True
def test_issue_11730():
unit = Interval(0, 1)
square = ComplexRegion(unit ** 2)
assert Union(S.Complexes, FiniteSet(oo)) != S.Complexes
assert Union(S.Complexes, FiniteSet(eye(4))) != S.Complexes
assert Union(unit, square) == square
assert Intersection(S.Reals, square) == unit
def test_issue_11938():
unit = Interval(0, 1)
ival = Interval(1, 2)
cr1 = ComplexRegion(ival * unit)
assert Intersection(cr1, S.Reals) == ival
assert Intersection(cr1, unit) == FiniteSet(1)
arg1 = Interval(0, S.Pi)
arg2 = FiniteSet(S.Pi)
arg3 = Interval(S.Pi / 4, 3 * S.Pi / 4)
cp1 = ComplexRegion(unit * arg1, polar=True)
cp2 = ComplexRegion(unit * arg2, polar=True)
cp3 = ComplexRegion(unit * arg3, polar=True)
assert Intersection(cp1, S.Reals) == Interval(-1, 1)
assert Intersection(cp2, S.Reals) == Interval(-1, 0)
assert Intersection(cp3, S.Reals) == FiniteSet(0)
def test_issue_11914():
a, b = Interval(0, 1), Interval(0, pi)
c, d = Interval(2, 3), Interval(pi, 3 * pi / 2)
cp1 = ComplexRegion(a * b, polar=True)
cp2 = ComplexRegion(c * d, polar=True)
assert -3 in cp1.union(cp2)
assert -3 in cp2.union(cp1)
assert -5 not in cp1.union(cp2)
def test_issue_9543():
assert ImageSet(Lambda(x, x**2), S.Naturals).is_subset(S.Reals)
def test_issue_16871():
assert ImageSet(Lambda(x, x), FiniteSet(1)) == {1}
assert ImageSet(Lambda(x, x - 3), S.Integers
).intersection(S.Integers) is S.Integers
@XFAIL
def test_issue_16871b():
assert ImageSet(Lambda(x, x - 3), S.Integers).is_subset(S.Integers)
def test_issue_18050():
assert imageset(Lambda(x, I*x + 1), S.Integers
) == ImageSet(Lambda(x, I*x + 1), S.Integers)
assert imageset(Lambda(x, 3*I*x + 4 + 8*I), S.Integers
) == ImageSet(Lambda(x, 3*I*x + 4 + 2*I), S.Integers)
# no 'Mod' for next 2 tests:
assert imageset(Lambda(x, 2*x + 3*I), S.Integers
) == ImageSet(Lambda(x, 2*x + 3*I), S.Integers)
r = Symbol('r', positive=True)
assert imageset(Lambda(x, r*x + 10), S.Integers
) == ImageSet(Lambda(x, r*x + 10), S.Integers)
# reduce real part:
assert imageset(Lambda(x, 3*x + 8 + 5*I), S.Integers
) == ImageSet(Lambda(x, 3*x + 2 + 5*I), S.Integers)
def test_Rationals():
assert S.Integers.is_subset(S.Rationals)
assert S.Naturals.is_subset(S.Rationals)
assert S.Naturals0.is_subset(S.Rationals)
assert S.Rationals.is_subset(S.Reals)
assert S.Rationals.inf is -oo
assert S.Rationals.sup is oo
it = iter(S.Rationals)
assert [next(it) for i in range(12)] == [
0, 1, -1, S.Half, 2, Rational(-1, 2), -2,
Rational(1, 3), 3, Rational(-1, 3), -3, Rational(2, 3)]
assert Basic() not in S.Rationals
assert S.Half in S.Rationals
assert S.Rationals.contains(0.5) == Contains(0.5, S.Rationals, evaluate=False)
assert 2 in S.Rationals
r = symbols('r', rational=True)
assert r in S.Rationals
raises(TypeError, lambda: x in S.Rationals)
# issue #18134:
assert S.Rationals.boundary == S.Reals
assert S.Rationals.closure == S.Reals
assert S.Rationals.is_open == False
assert S.Rationals.is_closed == False
def test_NZQRC_unions():
# check that all trivial number set unions are simplified:
nbrsets = (S.Naturals, S.Naturals0, S.Integers, S.Rationals,
S.Reals, S.Complexes)
unions = (Union(a, b) for a in nbrsets for b in nbrsets)
assert all(u.is_Union is False for u in unions)
def test_imageset_intersection():
n = Dummy()
s = ImageSet(Lambda(n, -I*(I*(2*pi*n - pi/4) +
log(Abs(sqrt(-I))))), S.Integers)
assert s.intersect(S.Reals) == ImageSet(
Lambda(n, 2*pi*n + pi*Rational(7, 4)), S.Integers)
def test_issue_17858():
assert 1 in Range(-oo, oo)
assert 0 in Range(oo, -oo, -1)
assert oo not in Range(-oo, oo)
assert -oo not in Range(-oo, oo)
def test_issue_17859():
r = Range(-oo,oo)
raises(ValueError,lambda: r[::2])
raises(ValueError, lambda: r[::-2])
r = Range(oo,-oo,-1)
raises(ValueError,lambda: r[::2])
raises(ValueError, lambda: r[::-2])
|
8810b5800620be8b2d4ea8426fef3bb7604efb1ed9493de77f65c638a279b0ec | from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.function import Lambda
from sympy.core.numbers import (Float, I, Rational, nan, oo, pi, zoo)
from sympy.core.power import Pow
from sympy.core.singleton import S
from sympy.core.symbol import (Symbol, symbols)
from sympy.core.sympify import sympify
from sympy.functions.elementary.miscellaneous import (Max, Min, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.logic.boolalg import (false, true)
from sympy.matrices.dense import Matrix
from sympy.polys.rootoftools import rootof
from sympy.sets.contains import Contains
from sympy.sets.fancysets import (ImageSet, Range)
from sympy.sets.sets import (Complement, DisjointUnion, FiniteSet, Intersection, Interval, ProductSet, Set, SymmetricDifference, Union, imageset)
from mpmath import mpi
from sympy.core.expr import unchanged
from sympy.core.relational import Eq, Ne, Le, Lt, LessThan
from sympy.logic import And, Or, Xor
from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy
from sympy.abc import x, y, z, m, n
EmptySet = S.EmptySet
def test_imageset():
ints = S.Integers
assert imageset(x, x - 1, S.Naturals) is S.Naturals0
assert imageset(x, x + 1, S.Naturals0) is S.Naturals
assert imageset(x, abs(x), S.Naturals0) is S.Naturals0
assert imageset(x, abs(x), S.Naturals) is S.Naturals
assert imageset(x, abs(x), S.Integers) is S.Naturals0
# issue 16878a
r = symbols('r', real=True)
assert imageset(x, (x, x), S.Reals)._contains((1, r)) == None
assert imageset(x, (x, x), S.Reals)._contains((1, 2)) == False
assert (r, r) in imageset(x, (x, x), S.Reals)
assert 1 + I in imageset(x, x + I, S.Reals)
assert {1} not in imageset(x, (x,), S.Reals)
assert (1, 1) not in imageset(x, (x,), S.Reals)
raises(TypeError, lambda: imageset(x, ints))
raises(ValueError, lambda: imageset(x, y, z, ints))
raises(ValueError, lambda: imageset(Lambda(x, cos(x)), y))
assert (1, 2) in imageset(Lambda((x, y), (x, y)), ints, ints)
raises(ValueError, lambda: imageset(Lambda(x, x), ints, ints))
assert imageset(cos, ints) == ImageSet(Lambda(x, cos(x)), ints)
def f(x):
return cos(x)
assert imageset(f, ints) == imageset(x, cos(x), ints)
f = lambda x: cos(x)
assert imageset(f, ints) == ImageSet(Lambda(x, cos(x)), ints)
assert imageset(x, 1, ints) == FiniteSet(1)
assert imageset(x, y, ints) == {y}
assert imageset((x, y), (1, z), ints, S.Reals) == {(1, z)}
clash = Symbol('x', integer=true)
assert (str(imageset(lambda x: x + clash, Interval(-2, 1)).lamda.expr)
in ('x0 + x', 'x + x0'))
x1, x2 = symbols("x1, x2")
assert imageset(lambda x, y:
Add(x, y), Interval(1, 2), Interval(2, 3)).dummy_eq(
ImageSet(Lambda((x1, x2), x1 + x2),
Interval(1, 2), Interval(2, 3)))
def test_is_empty():
for s in [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals,
S.UniversalSet]:
assert s.is_empty is False
assert S.EmptySet.is_empty is True
def test_is_finiteset():
for s in [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals,
S.UniversalSet]:
assert s.is_finite_set is False
assert S.EmptySet.is_finite_set is True
assert FiniteSet(1, 2).is_finite_set is True
assert Interval(1, 2).is_finite_set is False
assert Interval(x, y).is_finite_set is None
assert ProductSet(FiniteSet(1), FiniteSet(2)).is_finite_set is True
assert ProductSet(FiniteSet(1), Interval(1, 2)).is_finite_set is False
assert ProductSet(FiniteSet(1), Interval(x, y)).is_finite_set is None
assert Union(Interval(0, 1), Interval(2, 3)).is_finite_set is False
assert Union(FiniteSet(1), Interval(2, 3)).is_finite_set is False
assert Union(FiniteSet(1), FiniteSet(2)).is_finite_set is True
assert Union(FiniteSet(1), Interval(x, y)).is_finite_set is None
assert Intersection(Interval(x, y), FiniteSet(1)).is_finite_set is True
assert Intersection(Interval(x, y), Interval(1, 2)).is_finite_set is None
assert Intersection(FiniteSet(x), FiniteSet(y)).is_finite_set is True
assert Complement(FiniteSet(1), Interval(x, y)).is_finite_set is True
assert Complement(Interval(x, y), FiniteSet(1)).is_finite_set is None
assert Complement(Interval(1, 2), FiniteSet(x)).is_finite_set is False
assert DisjointUnion(Interval(-5, 3), FiniteSet(x, y)).is_finite_set is False
assert DisjointUnion(S.EmptySet, FiniteSet(x, y), S.EmptySet).is_finite_set is True
def test_deprecated_is_EmptySet():
with warns_deprecated_sympy():
S.EmptySet.is_EmptySet
def test_interval_arguments():
assert Interval(0, oo) == Interval(0, oo, False, True)
assert Interval(0, oo).right_open is true
assert Interval(-oo, 0) == Interval(-oo, 0, True, False)
assert Interval(-oo, 0).left_open is true
assert Interval(oo, -oo) == S.EmptySet
assert Interval(oo, oo) == S.EmptySet
assert Interval(-oo, -oo) == S.EmptySet
assert Interval(oo, x) == S.EmptySet
assert Interval(oo, oo) == S.EmptySet
assert Interval(x, -oo) == S.EmptySet
assert Interval(x, x) == {x}
assert isinstance(Interval(1, 1), FiniteSet)
e = Sum(x, (x, 1, 3))
assert isinstance(Interval(e, e), FiniteSet)
assert Interval(1, 0) == S.EmptySet
assert Interval(1, 1).measure == 0
assert Interval(1, 1, False, True) == S.EmptySet
assert Interval(1, 1, True, False) == S.EmptySet
assert Interval(1, 1, True, True) == S.EmptySet
assert isinstance(Interval(0, Symbol('a')), Interval)
assert Interval(Symbol('a', positive=True), 0) == S.EmptySet
raises(ValueError, lambda: Interval(0, S.ImaginaryUnit))
raises(ValueError, lambda: Interval(0, Symbol('z', extended_real=False)))
raises(ValueError, lambda: Interval(x, x + S.ImaginaryUnit))
raises(NotImplementedError, lambda: Interval(0, 1, And(x, y)))
raises(NotImplementedError, lambda: Interval(0, 1, False, And(x, y)))
raises(NotImplementedError, lambda: Interval(0, 1, z, And(x, y)))
def test_interval_symbolic_end_points():
a = Symbol('a', real=True)
assert Union(Interval(0, a), Interval(0, 3)).sup == Max(a, 3)
assert Union(Interval(a, 0), Interval(-3, 0)).inf == Min(-3, a)
assert Interval(0, a).contains(1) == LessThan(1, a)
def test_interval_is_empty():
x, y = symbols('x, y')
r = Symbol('r', real=True)
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
nn = Symbol('nn', nonnegative=True)
assert Interval(1, 2).is_empty == False
assert Interval(3, 3).is_empty == False # FiniteSet
assert Interval(r, r).is_empty == False # FiniteSet
assert Interval(r, r + nn).is_empty == False
assert Interval(x, x).is_empty == False
assert Interval(1, oo).is_empty == False
assert Interval(-oo, oo).is_empty == False
assert Interval(-oo, 1).is_empty == False
assert Interval(x, y).is_empty == None
assert Interval(r, oo).is_empty == False # real implies finite
assert Interval(n, 0).is_empty == False
assert Interval(n, 0, left_open=True).is_empty == False
assert Interval(p, 0).is_empty == True # EmptySet
assert Interval(nn, 0).is_empty == None
assert Interval(n, p).is_empty == False
assert Interval(0, p, left_open=True).is_empty == False
assert Interval(0, p, right_open=True).is_empty == False
assert Interval(0, nn, left_open=True).is_empty == None
assert Interval(0, nn, right_open=True).is_empty == None
def test_union():
assert Union(Interval(1, 2), Interval(2, 3)) == Interval(1, 3)
assert Union(Interval(1, 2), Interval(2, 3, True)) == Interval(1, 3)
assert Union(Interval(1, 3), Interval(2, 4)) == Interval(1, 4)
assert Union(Interval(1, 2), Interval(1, 3)) == Interval(1, 3)
assert Union(Interval(1, 3), Interval(1, 2)) == Interval(1, 3)
assert Union(Interval(1, 3, False, True), Interval(1, 2)) == \
Interval(1, 3, False, True)
assert Union(Interval(1, 3), Interval(1, 2, False, True)) == Interval(1, 3)
assert Union(Interval(1, 2, True), Interval(1, 3)) == Interval(1, 3)
assert Union(Interval(1, 2, True), Interval(1, 3, True)) == \
Interval(1, 3, True)
assert Union(Interval(1, 2, True), Interval(1, 3, True, True)) == \
Interval(1, 3, True, True)
assert Union(Interval(1, 2, True, True), Interval(1, 3, True)) == \
Interval(1, 3, True)
assert Union(Interval(1, 3), Interval(2, 3)) == Interval(1, 3)
assert Union(Interval(1, 3, False, True), Interval(2, 3)) == \
Interval(1, 3)
assert Union(Interval(1, 2, False, True), Interval(2, 3, True)) != \
Interval(1, 3)
assert Union(Interval(1, 2), S.EmptySet) == Interval(1, 2)
assert Union(S.EmptySet) == S.EmptySet
assert Union(Interval(0, 1), *[FiniteSet(1.0/n) for n in range(1, 10)]) == \
Interval(0, 1)
# issue #18241:
x = Symbol('x')
assert Union(Interval(0, 1), FiniteSet(1, x)) == Union(
Interval(0, 1), FiniteSet(x))
assert unchanged(Union, Interval(0, 1), FiniteSet(2, x))
assert Interval(1, 2).union(Interval(2, 3)) == \
Interval(1, 2) + Interval(2, 3)
assert Interval(1, 2).union(Interval(2, 3)) == Interval(1, 3)
assert Union(Set()) == Set()
assert FiniteSet(1) + FiniteSet(2) + FiniteSet(3) == FiniteSet(1, 2, 3)
assert FiniteSet('ham') + FiniteSet('eggs') == FiniteSet('ham', 'eggs')
assert FiniteSet(1, 2, 3) + S.EmptySet == FiniteSet(1, 2, 3)
assert FiniteSet(1, 2, 3) & FiniteSet(2, 3, 4) == FiniteSet(2, 3)
assert FiniteSet(1, 2, 3) | FiniteSet(2, 3, 4) == FiniteSet(1, 2, 3, 4)
assert FiniteSet(1, 2, 3) & S.EmptySet == S.EmptySet
assert FiniteSet(1, 2, 3) | S.EmptySet == FiniteSet(1, 2, 3)
x = Symbol("x")
y = Symbol("y")
z = Symbol("z")
assert S.EmptySet | FiniteSet(x, FiniteSet(y, z)) == \
FiniteSet(x, FiniteSet(y, z))
# Test that Intervals and FiniteSets play nicely
assert Interval(1, 3) + FiniteSet(2) == Interval(1, 3)
assert Interval(1, 3, True, True) + FiniteSet(3) == \
Interval(1, 3, True, False)
X = Interval(1, 3) + FiniteSet(5)
Y = Interval(1, 2) + FiniteSet(3)
XandY = X.intersect(Y)
assert 2 in X and 3 in X and 3 in XandY
assert XandY.is_subset(X) and XandY.is_subset(Y)
raises(TypeError, lambda: Union(1, 2, 3))
assert X.is_iterable is False
# issue 7843
assert Union(S.EmptySet, FiniteSet(-sqrt(-I), sqrt(-I))) == \
FiniteSet(-sqrt(-I), sqrt(-I))
assert Union(S.Reals, S.Integers) == S.Reals
def test_union_iter():
# Use Range because it is ordered
u = Union(Range(3), Range(5), Range(4), evaluate=False)
# Round robin
assert list(u) == [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4]
def test_union_is_empty():
assert (Interval(x, y) + FiniteSet(1)).is_empty == False
assert (Interval(x, y) + Interval(-x, y)).is_empty == None
def test_difference():
assert Interval(1, 3) - Interval(1, 2) == Interval(2, 3, True)
assert Interval(1, 3) - Interval(2, 3) == Interval(1, 2, False, True)
assert Interval(1, 3, True) - Interval(2, 3) == Interval(1, 2, True, True)
assert Interval(1, 3, True) - Interval(2, 3, True) == \
Interval(1, 2, True, False)
assert Interval(0, 2) - FiniteSet(1) == \
Union(Interval(0, 1, False, True), Interval(1, 2, True, False))
# issue #18119
assert S.Reals - FiniteSet(I) == S.Reals
assert S.Reals - FiniteSet(-I, I) == S.Reals
assert Interval(0, 10) - FiniteSet(-I, I) == Interval(0, 10)
assert Interval(0, 10) - FiniteSet(1, I) == Union(
Interval.Ropen(0, 1), Interval.Lopen(1, 10))
assert S.Reals - FiniteSet(1, 2 + I, x, y**2) == Complement(
Union(Interval.open(-oo, 1), Interval.open(1, oo)), FiniteSet(x, y**2),
evaluate=False)
assert FiniteSet(1, 2, 3) - FiniteSet(2) == FiniteSet(1, 3)
assert FiniteSet('ham', 'eggs') - FiniteSet('eggs') == FiniteSet('ham')
assert FiniteSet(1, 2, 3, 4) - Interval(2, 10, True, False) == \
FiniteSet(1, 2)
assert FiniteSet(1, 2, 3, 4) - S.EmptySet == FiniteSet(1, 2, 3, 4)
assert Union(Interval(0, 2), FiniteSet(2, 3, 4)) - Interval(1, 3) == \
Union(Interval(0, 1, False, True), FiniteSet(4))
assert -1 in S.Reals - S.Naturals
def test_Complement():
A = FiniteSet(1, 3, 4)
B = FiniteSet(3, 4)
C = Interval(1, 3)
D = Interval(1, 2)
assert Complement(A, B, evaluate=False).is_iterable is True
assert Complement(A, C, evaluate=False).is_iterable is True
assert Complement(C, D, evaluate=False).is_iterable is None
assert FiniteSet(*Complement(A, B, evaluate=False)) == FiniteSet(1)
assert FiniteSet(*Complement(A, C, evaluate=False)) == FiniteSet(4)
raises(TypeError, lambda: FiniteSet(*Complement(C, A, evaluate=False)))
assert Complement(Interval(1, 3), Interval(1, 2)) == Interval(2, 3, True)
assert Complement(FiniteSet(1, 3, 4), FiniteSet(3, 4)) == FiniteSet(1)
assert Complement(Union(Interval(0, 2), FiniteSet(2, 3, 4)),
Interval(1, 3)) == \
Union(Interval(0, 1, False, True), FiniteSet(4))
assert 3 not in Complement(Interval(0, 5), Interval(1, 4), evaluate=False)
assert -1 in Complement(S.Reals, S.Naturals, evaluate=False)
assert 1 not in Complement(S.Reals, S.Naturals, evaluate=False)
assert Complement(S.Integers, S.UniversalSet) == EmptySet
assert S.UniversalSet.complement(S.Integers) == EmptySet
assert (0 not in S.Reals.intersect(S.Integers - FiniteSet(0)))
assert S.EmptySet - S.Integers == S.EmptySet
assert (S.Integers - FiniteSet(0)) - FiniteSet(1) == S.Integers - FiniteSet(0, 1)
assert S.Reals - Union(S.Naturals, FiniteSet(pi)) == \
Intersection(S.Reals - S.Naturals, S.Reals - FiniteSet(pi))
# issue 12712
assert Complement(FiniteSet(x, y, 2), Interval(-10, 10)) == \
Complement(FiniteSet(x, y), Interval(-10, 10))
A = FiniteSet(*symbols('a:c'))
B = FiniteSet(*symbols('d:f'))
assert unchanged(Complement, ProductSet(A, A), B)
A2 = ProductSet(A, A)
B3 = ProductSet(B, B, B)
assert A2 - B3 == A2
assert B3 - A2 == B3
def test_set_operations_nonsets():
'''Tests that e.g. FiniteSet(1) * 2 raises TypeError'''
ops = [
lambda a, b: a + b,
lambda a, b: a - b,
lambda a, b: a * b,
lambda a, b: a / b,
lambda a, b: a // b,
lambda a, b: a | b,
lambda a, b: a & b,
lambda a, b: a ^ b,
# FiniteSet(1) ** 2 gives a ProductSet
#lambda a, b: a ** b,
]
Sx = FiniteSet(x)
Sy = FiniteSet(y)
sets = [
{1},
FiniteSet(1),
Interval(1, 2),
Union(Sx, Interval(1, 2)),
Intersection(Sx, Sy),
Complement(Sx, Sy),
ProductSet(Sx, Sy),
S.EmptySet,
]
nums = [0, 1, 2, S(0), S(1), S(2)]
for si in sets:
for ni in nums:
for op in ops:
raises(TypeError, lambda : op(si, ni))
raises(TypeError, lambda : op(ni, si))
raises(TypeError, lambda: si ** object())
raises(TypeError, lambda: si ** {1})
def test_complement():
assert Complement({1, 2}, {1}) == {2}
assert Interval(0, 1).complement(S.Reals) == \
Union(Interval(-oo, 0, True, True), Interval(1, oo, True, True))
assert Interval(0, 1, True, False).complement(S.Reals) == \
Union(Interval(-oo, 0, True, False), Interval(1, oo, True, True))
assert Interval(0, 1, False, True).complement(S.Reals) == \
Union(Interval(-oo, 0, True, True), Interval(1, oo, False, True))
assert Interval(0, 1, True, True).complement(S.Reals) == \
Union(Interval(-oo, 0, True, False), Interval(1, oo, False, True))
assert S.UniversalSet.complement(S.EmptySet) == S.EmptySet
assert S.UniversalSet.complement(S.Reals) == S.EmptySet
assert S.UniversalSet.complement(S.UniversalSet) == S.EmptySet
assert S.EmptySet.complement(S.Reals) == S.Reals
assert Union(Interval(0, 1), Interval(2, 3)).complement(S.Reals) == \
Union(Interval(-oo, 0, True, True), Interval(1, 2, True, True),
Interval(3, oo, True, True))
assert FiniteSet(0).complement(S.Reals) == \
Union(Interval(-oo, 0, True, True), Interval(0, oo, True, True))
assert (FiniteSet(5) + Interval(S.NegativeInfinity,
0)).complement(S.Reals) == \
Interval(0, 5, True, True) + Interval(5, S.Infinity, True, True)
assert FiniteSet(1, 2, 3).complement(S.Reals) == \
Interval(S.NegativeInfinity, 1, True, True) + \
Interval(1, 2, True, True) + Interval(2, 3, True, True) +\
Interval(3, S.Infinity, True, True)
assert FiniteSet(x).complement(S.Reals) == Complement(S.Reals, FiniteSet(x))
assert FiniteSet(0, x).complement(S.Reals) == Complement(Interval(-oo, 0, True, True) +
Interval(0, oo, True, True)
, FiniteSet(x), evaluate=False)
square = Interval(0, 1) * Interval(0, 1)
notsquare = square.complement(S.Reals*S.Reals)
assert all(pt in square for pt in [(0, 0), (.5, .5), (1, 0), (1, 1)])
assert not any(
pt in notsquare for pt in [(0, 0), (.5, .5), (1, 0), (1, 1)])
assert not any(pt in square for pt in [(-1, 0), (1.5, .5), (10, 10)])
assert all(pt in notsquare for pt in [(-1, 0), (1.5, .5), (10, 10)])
def test_intersect1():
assert all(S.Integers.intersection(i) is i for i in
(S.Naturals, S.Naturals0))
assert all(i.intersection(S.Integers) is i for i in
(S.Naturals, S.Naturals0))
s = S.Naturals0
assert S.Naturals.intersection(s) is S.Naturals
assert s.intersection(S.Naturals) is S.Naturals
x = Symbol('x')
assert Interval(0, 2).intersect(Interval(1, 2)) == Interval(1, 2)
assert Interval(0, 2).intersect(Interval(1, 2, True)) == \
Interval(1, 2, True)
assert Interval(0, 2, True).intersect(Interval(1, 2)) == \
Interval(1, 2, False, False)
assert Interval(0, 2, True, True).intersect(Interval(1, 2)) == \
Interval(1, 2, False, True)
assert Interval(0, 2).intersect(Union(Interval(0, 1), Interval(2, 3))) == \
Union(Interval(0, 1), Interval(2, 2))
assert FiniteSet(1, 2).intersect(FiniteSet(1, 2, 3)) == FiniteSet(1, 2)
assert FiniteSet(1, 2, x).intersect(FiniteSet(x)) == FiniteSet(x)
assert FiniteSet('ham', 'eggs').intersect(FiniteSet('ham')) == \
FiniteSet('ham')
assert FiniteSet(1, 2, 3, 4, 5).intersect(S.EmptySet) == S.EmptySet
assert Interval(0, 5).intersect(FiniteSet(1, 3)) == FiniteSet(1, 3)
assert Interval(0, 1, True, True).intersect(FiniteSet(1)) == S.EmptySet
assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(1, 2)) == \
Union(Interval(1, 1), Interval(2, 2))
assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(0, 2)) == \
Union(Interval(0, 1), Interval(2, 2))
assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(1, 2, True, True)) == \
S.EmptySet
assert Union(Interval(0, 1), Interval(2, 3)).intersect(S.EmptySet) == \
S.EmptySet
assert Union(Interval(0, 5), FiniteSet('ham')).intersect(FiniteSet(2, 3, 4, 5, 6)) == \
Intersection(FiniteSet(2, 3, 4, 5, 6), Union(FiniteSet('ham'), Interval(0, 5)))
assert Intersection(FiniteSet(1, 2, 3), Interval(2, x), Interval(3, y)) == \
Intersection(FiniteSet(3), Interval(2, x), Interval(3, y), evaluate=False)
assert Intersection(FiniteSet(1, 2), Interval(0, 3), Interval(x, y)) == \
Intersection({1, 2}, Interval(x, y), evaluate=False)
assert Intersection(FiniteSet(1, 2, 4), Interval(0, 3), Interval(x, y)) == \
Intersection({1, 2}, Interval(x, y), evaluate=False)
# XXX: Is the real=True necessary here?
# https://github.com/sympy/sympy/issues/17532
m, n = symbols('m, n', real=True)
assert Intersection(FiniteSet(m), FiniteSet(m, n), Interval(m, m+1)) == \
FiniteSet(m)
# issue 8217
assert Intersection(FiniteSet(x), FiniteSet(y)) == \
Intersection(FiniteSet(x), FiniteSet(y), evaluate=False)
assert FiniteSet(x).intersect(S.Reals) == \
Intersection(S.Reals, FiniteSet(x), evaluate=False)
# tests for the intersection alias
assert Interval(0, 5).intersection(FiniteSet(1, 3)) == FiniteSet(1, 3)
assert Interval(0, 1, True, True).intersection(FiniteSet(1)) == S.EmptySet
assert Union(Interval(0, 1), Interval(2, 3)).intersection(Interval(1, 2)) == \
Union(Interval(1, 1), Interval(2, 2))
def test_intersection():
# iterable
i = Intersection(FiniteSet(1, 2, 3), Interval(2, 5), evaluate=False)
assert i.is_iterable
assert set(i) == {S(2), S(3)}
# challenging intervals
x = Symbol('x', real=True)
i = Intersection(Interval(0, 3), Interval(x, 6))
assert (5 in i) is False
raises(TypeError, lambda: 2 in i)
# Singleton special cases
assert Intersection(Interval(0, 1), S.EmptySet) == S.EmptySet
assert Intersection(Interval(-oo, oo), Interval(-oo, x)) == Interval(-oo, x)
# Products
line = Interval(0, 5)
i = Intersection(line**2, line**3, evaluate=False)
assert (2, 2) not in i
assert (2, 2, 2) not in i
raises(TypeError, lambda: list(i))
a = Intersection(Intersection(S.Integers, S.Naturals, evaluate=False), S.Reals, evaluate=False)
assert a._argset == frozenset([Intersection(S.Naturals, S.Integers, evaluate=False), S.Reals])
assert Intersection(S.Complexes, FiniteSet(S.ComplexInfinity)) == S.EmptySet
# issue 12178
assert Intersection() == S.UniversalSet
# issue 16987
assert Intersection({1}, {1}, {x}) == Intersection({1}, {x})
def test_issue_9623():
n = Symbol('n')
a = S.Reals
b = Interval(0, oo)
c = FiniteSet(n)
assert Intersection(a, b, c) == Intersection(b, c)
assert Intersection(Interval(1, 2), Interval(3, 4), FiniteSet(n)) == EmptySet
def test_is_disjoint():
assert Interval(0, 2).is_disjoint(Interval(1, 2)) == False
assert Interval(0, 2).is_disjoint(Interval(3, 4)) == True
def test_ProductSet__len__():
A = FiniteSet(1, 2)
B = FiniteSet(1, 2, 3)
assert ProductSet(A).__len__() == 2
assert ProductSet(A).__len__() is not S(2)
assert ProductSet(A, B).__len__() == 6
assert ProductSet(A, B).__len__() is not S(6)
def test_ProductSet():
# ProductSet is always a set of Tuples
assert ProductSet(S.Reals) == S.Reals ** 1
assert ProductSet(S.Reals, S.Reals) == S.Reals ** 2
assert ProductSet(S.Reals, S.Reals, S.Reals) == S.Reals ** 3
assert ProductSet(S.Reals) != S.Reals
assert ProductSet(S.Reals, S.Reals) == S.Reals * S.Reals
assert ProductSet(S.Reals, S.Reals, S.Reals) != S.Reals * S.Reals * S.Reals
assert ProductSet(S.Reals, S.Reals, S.Reals) == (S.Reals * S.Reals * S.Reals).flatten()
assert 1 not in ProductSet(S.Reals)
assert (1,) in ProductSet(S.Reals)
assert 1 not in ProductSet(S.Reals, S.Reals)
assert (1, 2) in ProductSet(S.Reals, S.Reals)
assert (1, I) not in ProductSet(S.Reals, S.Reals)
assert (1, 2, 3) in ProductSet(S.Reals, S.Reals, S.Reals)
assert (1, 2, 3) in S.Reals ** 3
assert (1, 2, 3) not in S.Reals * S.Reals * S.Reals
assert ((1, 2), 3) in S.Reals * S.Reals * S.Reals
assert (1, (2, 3)) not in S.Reals * S.Reals * S.Reals
assert (1, (2, 3)) in S.Reals * (S.Reals * S.Reals)
assert ProductSet() == FiniteSet(())
assert ProductSet(S.Reals, S.EmptySet) == S.EmptySet
# See GH-17458
for ni in range(5):
Rn = ProductSet(*(S.Reals,) * ni)
assert (1,) * ni in Rn
assert 1 not in Rn
assert (S.Reals * S.Reals) * S.Reals != S.Reals * (S.Reals * S.Reals)
S1 = S.Reals
S2 = S.Integers
x1 = pi
x2 = 3
assert x1 in S1
assert x2 in S2
assert (x1, x2) in S1 * S2
S3 = S1 * S2
x3 = (x1, x2)
assert x3 in S3
assert (x3, x3) in S3 * S3
assert x3 + x3 not in S3 * S3
raises(ValueError, lambda: S.Reals**-1)
with warns_deprecated_sympy():
ProductSet(FiniteSet(s) for s in range(2))
raises(TypeError, lambda: ProductSet(None))
S1 = FiniteSet(1, 2)
S2 = FiniteSet(3, 4)
S3 = ProductSet(S1, S2)
assert (S3.as_relational(x, y)
== And(S1.as_relational(x), S2.as_relational(y))
== And(Or(Eq(x, 1), Eq(x, 2)), Or(Eq(y, 3), Eq(y, 4))))
raises(ValueError, lambda: S3.as_relational(x))
raises(ValueError, lambda: S3.as_relational(x, 1))
raises(ValueError, lambda: ProductSet(Interval(0, 1)).as_relational(x, y))
Z2 = ProductSet(S.Integers, S.Integers)
assert Z2.contains((1, 2)) is S.true
assert Z2.contains((1,)) is S.false
assert Z2.contains(x) == Contains(x, Z2, evaluate=False)
assert Z2.contains(x).subs(x, 1) is S.false
assert Z2.contains((x, 1)).subs(x, 2) is S.true
assert Z2.contains((x, y)) == Contains((x, y), Z2, evaluate=False)
assert unchanged(Contains, (x, y), Z2)
assert Contains((1, 2), Z2) is S.true
def test_ProductSet_of_single_arg_is_not_arg():
assert unchanged(ProductSet, Interval(0, 1))
assert unchanged(ProductSet, ProductSet(Interval(0, 1)))
def test_ProductSet_is_empty():
assert ProductSet(S.Integers, S.Reals).is_empty == False
assert ProductSet(Interval(x, 1), S.Reals).is_empty == None
def test_interval_subs():
a = Symbol('a', real=True)
assert Interval(0, a).subs(a, 2) == Interval(0, 2)
assert Interval(a, 0).subs(a, 2) == S.EmptySet
def test_interval_to_mpi():
assert Interval(0, 1).to_mpi() == mpi(0, 1)
assert Interval(0, 1, True, False).to_mpi() == mpi(0, 1)
assert type(Interval(0, 1).to_mpi()) == type(mpi(0, 1))
def test_set_evalf():
assert Interval(S(11)/64, S.Half).evalf() == Interval(
Float('0.171875'), Float('0.5'))
assert Interval(x, S.Half, right_open=True).evalf() == Interval(
x, Float('0.5'), right_open=True)
assert Interval(-oo, S.Half).evalf() == Interval(-oo, Float('0.5'))
assert FiniteSet(2, x).evalf() == FiniteSet(Float('2.0'), x)
def test_measure():
a = Symbol('a', real=True)
assert Interval(1, 3).measure == 2
assert Interval(0, a).measure == a
assert Interval(1, a).measure == a - 1
assert Union(Interval(1, 2), Interval(3, 4)).measure == 2
assert Union(Interval(1, 2), Interval(3, 4), FiniteSet(5, 6, 7)).measure \
== 2
assert FiniteSet(1, 2, oo, a, -oo, -5).measure == 0
assert S.EmptySet.measure == 0
square = Interval(0, 10) * Interval(0, 10)
offsetsquare = Interval(5, 15) * Interval(5, 15)
band = Interval(-oo, oo) * Interval(2, 4)
assert square.measure == offsetsquare.measure == 100
assert (square + offsetsquare).measure == 175 # there is some overlap
assert (square - offsetsquare).measure == 75
assert (square * FiniteSet(1, 2, 3)).measure == 0
assert (square.intersect(band)).measure == 20
assert (square + band).measure is oo
assert (band * FiniteSet(1, 2, 3)).measure is nan
def test_is_subset():
assert Interval(0, 1).is_subset(Interval(0, 2)) is True
assert Interval(0, 3).is_subset(Interval(0, 2)) is False
assert Interval(0, 1).is_subset(FiniteSet(0, 1)) is False
assert FiniteSet(1, 2).is_subset(FiniteSet(1, 2, 3, 4))
assert FiniteSet(4, 5).is_subset(FiniteSet(1, 2, 3, 4)) is False
assert FiniteSet(1).is_subset(Interval(0, 2))
assert FiniteSet(1, 2).is_subset(Interval(0, 2, True, True)) is False
assert (Interval(1, 2) + FiniteSet(3)).is_subset(
Interval(0, 2, False, True) + FiniteSet(2, 3))
assert Interval(3, 4).is_subset(Union(Interval(0, 1), Interval(2, 5))) is True
assert Interval(3, 6).is_subset(Union(Interval(0, 1), Interval(2, 5))) is False
assert FiniteSet(1, 2, 3, 4).is_subset(Interval(0, 5)) is True
assert S.EmptySet.is_subset(FiniteSet(1, 2, 3)) is True
assert Interval(0, 1).is_subset(S.EmptySet) is False
assert S.EmptySet.is_subset(S.EmptySet) is True
raises(ValueError, lambda: S.EmptySet.is_subset(1))
# tests for the issubset alias
assert FiniteSet(1, 2, 3, 4).issubset(Interval(0, 5)) is True
assert S.EmptySet.issubset(FiniteSet(1, 2, 3)) is True
assert S.Naturals.is_subset(S.Integers)
assert S.Naturals0.is_subset(S.Integers)
assert FiniteSet(x).is_subset(FiniteSet(y)) is None
assert FiniteSet(x).is_subset(FiniteSet(y).subs(y, x)) is True
assert FiniteSet(x).is_subset(FiniteSet(y).subs(y, x+1)) is False
assert Interval(0, 1).is_subset(Interval(0, 1, left_open=True)) is False
assert Interval(-2, 3).is_subset(Union(Interval(-oo, -2), Interval(3, oo))) is False
n = Symbol('n', integer=True)
assert Range(-3, 4, 1).is_subset(FiniteSet(-10, 10)) is False
assert Range(S(10)**100).is_subset(FiniteSet(0, 1, 2)) is False
assert Range(6, 0, -2).is_subset(FiniteSet(2, 4, 6)) is True
assert Range(1, oo).is_subset(FiniteSet(1, 2)) is False
assert Range(-oo, 1).is_subset(FiniteSet(1)) is False
assert Range(3).is_subset(FiniteSet(0, 1, n)) is None
assert Range(n, n + 2).is_subset(FiniteSet(n, n + 1)) is True
assert Range(5).is_subset(Interval(0, 4, right_open=True)) is False
#issue 19513
assert imageset(Lambda(n, 1/n), S.Integers).is_subset(S.Reals) is None
def test_is_proper_subset():
assert Interval(0, 1).is_proper_subset(Interval(0, 2)) is True
assert Interval(0, 3).is_proper_subset(Interval(0, 2)) is False
assert S.EmptySet.is_proper_subset(FiniteSet(1, 2, 3)) is True
raises(ValueError, lambda: Interval(0, 1).is_proper_subset(0))
def test_is_superset():
assert Interval(0, 1).is_superset(Interval(0, 2)) == False
assert Interval(0, 3).is_superset(Interval(0, 2))
assert FiniteSet(1, 2).is_superset(FiniteSet(1, 2, 3, 4)) == False
assert FiniteSet(4, 5).is_superset(FiniteSet(1, 2, 3, 4)) == False
assert FiniteSet(1).is_superset(Interval(0, 2)) == False
assert FiniteSet(1, 2).is_superset(Interval(0, 2, True, True)) == False
assert (Interval(1, 2) + FiniteSet(3)).is_superset(
Interval(0, 2, False, True) + FiniteSet(2, 3)) == False
assert Interval(3, 4).is_superset(Union(Interval(0, 1), Interval(2, 5))) == False
assert FiniteSet(1, 2, 3, 4).is_superset(Interval(0, 5)) == False
assert S.EmptySet.is_superset(FiniteSet(1, 2, 3)) == False
assert Interval(0, 1).is_superset(S.EmptySet) == True
assert S.EmptySet.is_superset(S.EmptySet) == True
raises(ValueError, lambda: S.EmptySet.is_superset(1))
# tests for the issuperset alias
assert Interval(0, 1).issuperset(S.EmptySet) == True
assert S.EmptySet.issuperset(S.EmptySet) == True
def test_is_proper_superset():
assert Interval(0, 1).is_proper_superset(Interval(0, 2)) is False
assert Interval(0, 3).is_proper_superset(Interval(0, 2)) is True
assert FiniteSet(1, 2, 3).is_proper_superset(S.EmptySet) is True
raises(ValueError, lambda: Interval(0, 1).is_proper_superset(0))
def test_contains():
assert Interval(0, 2).contains(1) is S.true
assert Interval(0, 2).contains(3) is S.false
assert Interval(0, 2, True, False).contains(0) is S.false
assert Interval(0, 2, True, False).contains(2) is S.true
assert Interval(0, 2, False, True).contains(0) is S.true
assert Interval(0, 2, False, True).contains(2) is S.false
assert Interval(0, 2, True, True).contains(0) is S.false
assert Interval(0, 2, True, True).contains(2) is S.false
assert (Interval(0, 2) in Interval(0, 2)) is False
assert FiniteSet(1, 2, 3).contains(2) is S.true
assert FiniteSet(1, 2, Symbol('x')).contains(Symbol('x')) is S.true
assert FiniteSet(y)._contains(x) is None
raises(TypeError, lambda: x in FiniteSet(y))
assert FiniteSet({x, y})._contains({x}) is None
assert FiniteSet({x, y}).subs(y, x)._contains({x}) is True
assert FiniteSet({x, y}).subs(y, x+1)._contains({x}) is False
# issue 8197
from sympy.abc import a, b
assert isinstance(FiniteSet(b).contains(-a), Contains)
assert isinstance(FiniteSet(b).contains(a), Contains)
assert isinstance(FiniteSet(a).contains(1), Contains)
raises(TypeError, lambda: 1 in FiniteSet(a))
# issue 8209
rad1 = Pow(Pow(2, Rational(1, 3)) - 1, Rational(1, 3))
rad2 = Pow(Rational(1, 9), Rational(1, 3)) - Pow(Rational(2, 9), Rational(1, 3)) + Pow(Rational(4, 9), Rational(1, 3))
s1 = FiniteSet(rad1)
s2 = FiniteSet(rad2)
assert s1 - s2 == S.EmptySet
items = [1, 2, S.Infinity, S('ham'), -1.1]
fset = FiniteSet(*items)
assert all(item in fset for item in items)
assert all(fset.contains(item) is S.true for item in items)
assert Union(Interval(0, 1), Interval(2, 5)).contains(3) is S.true
assert Union(Interval(0, 1), Interval(2, 5)).contains(6) is S.false
assert Union(Interval(0, 1), FiniteSet(2, 5)).contains(3) is S.false
assert S.EmptySet.contains(1) is S.false
assert FiniteSet(rootof(x**3 + x - 1, 0)).contains(S.Infinity) is S.false
assert rootof(x**5 + x**3 + 1, 0) in S.Reals
assert not rootof(x**5 + x**3 + 1, 1) in S.Reals
# non-bool results
assert Union(Interval(1, 2), Interval(3, 4)).contains(x) == \
Or(And(S.One <= x, x <= 2), And(S(3) <= x, x <= 4))
assert Intersection(Interval(1, x), Interval(2, 3)).contains(y) == \
And(y <= 3, y <= x, S.One <= y, S(2) <= y)
assert (S.Complexes).contains(S.ComplexInfinity) == S.false
def test_interval_symbolic():
x = Symbol('x')
e = Interval(0, 1)
assert e.contains(x) == And(S.Zero <= x, x <= 1)
raises(TypeError, lambda: x in e)
e = Interval(0, 1, True, True)
assert e.contains(x) == And(S.Zero < x, x < 1)
c = Symbol('c', real=False)
assert Interval(x, x + 1).contains(c) == False
e = Symbol('e', extended_real=True)
assert Interval(-oo, oo).contains(e) == And(
S.NegativeInfinity < e, e < S.Infinity)
def test_union_contains():
x = Symbol('x')
i1 = Interval(0, 1)
i2 = Interval(2, 3)
i3 = Union(i1, i2)
assert i3.as_relational(x) == Or(And(S.Zero <= x, x <= 1), And(S(2) <= x, x <= 3))
raises(TypeError, lambda: x in i3)
e = i3.contains(x)
assert e == i3.as_relational(x)
assert e.subs(x, -0.5) is false
assert e.subs(x, 0.5) is true
assert e.subs(x, 1.5) is false
assert e.subs(x, 2.5) is true
assert e.subs(x, 3.5) is false
U = Interval(0, 2, True, True) + Interval(10, oo) + FiniteSet(-1, 2, 5, 6)
assert all(el not in U for el in [0, 4, -oo])
assert all(el in U for el in [2, 5, 10])
def test_is_number():
assert Interval(0, 1).is_number is False
assert Set().is_number is False
def test_Interval_is_left_unbounded():
assert Interval(3, 4).is_left_unbounded is False
assert Interval(-oo, 3).is_left_unbounded is True
assert Interval(Float("-inf"), 3).is_left_unbounded is True
def test_Interval_is_right_unbounded():
assert Interval(3, 4).is_right_unbounded is False
assert Interval(3, oo).is_right_unbounded is True
assert Interval(3, Float("+inf")).is_right_unbounded is True
def test_Interval_as_relational():
x = Symbol('x')
assert Interval(-1, 2, False, False).as_relational(x) == \
And(Le(-1, x), Le(x, 2))
assert Interval(-1, 2, True, False).as_relational(x) == \
And(Lt(-1, x), Le(x, 2))
assert Interval(-1, 2, False, True).as_relational(x) == \
And(Le(-1, x), Lt(x, 2))
assert Interval(-1, 2, True, True).as_relational(x) == \
And(Lt(-1, x), Lt(x, 2))
assert Interval(-oo, 2, right_open=False).as_relational(x) == And(Lt(-oo, x), Le(x, 2))
assert Interval(-oo, 2, right_open=True).as_relational(x) == And(Lt(-oo, x), Lt(x, 2))
assert Interval(-2, oo, left_open=False).as_relational(x) == And(Le(-2, x), Lt(x, oo))
assert Interval(-2, oo, left_open=True).as_relational(x) == And(Lt(-2, x), Lt(x, oo))
assert Interval(-oo, oo).as_relational(x) == And(Lt(-oo, x), Lt(x, oo))
x = Symbol('x', real=True)
y = Symbol('y', real=True)
assert Interval(x, y).as_relational(x) == (x <= y)
assert Interval(y, x).as_relational(x) == (y <= x)
def test_Finite_as_relational():
x = Symbol('x')
y = Symbol('y')
assert FiniteSet(1, 2).as_relational(x) == Or(Eq(x, 1), Eq(x, 2))
assert FiniteSet(y, -5).as_relational(x) == Or(Eq(x, y), Eq(x, -5))
def test_Union_as_relational():
x = Symbol('x')
assert (Interval(0, 1) + FiniteSet(2)).as_relational(x) == \
Or(And(Le(0, x), Le(x, 1)), Eq(x, 2))
assert (Interval(0, 1, True, True) + FiniteSet(1)).as_relational(x) == \
And(Lt(0, x), Le(x, 1))
assert Or(x < 0, x > 0).as_set().as_relational(x) == \
And((x > -oo), (x < oo), Ne(x, 0))
assert (Interval.Ropen(1, 3) + Interval.Lopen(3, 5)
).as_relational(x) == And((x > 1), (x < 5), Ne(x, 3))
def test_Intersection_as_relational():
x = Symbol('x')
assert (Intersection(Interval(0, 1), FiniteSet(2),
evaluate=False).as_relational(x)
== And(And(Le(0, x), Le(x, 1)), Eq(x, 2)))
def test_Complement_as_relational():
x = Symbol('x')
expr = Complement(Interval(0, 1), FiniteSet(2), evaluate=False)
assert expr.as_relational(x) == \
And(Le(0, x), Le(x, 1), Ne(x, 2))
@XFAIL
def test_Complement_as_relational_fail():
x = Symbol('x')
expr = Complement(Interval(0, 1), FiniteSet(2), evaluate=False)
# XXX This example fails because 0 <= x changes to x >= 0
# during the evaluation.
assert expr.as_relational(x) == \
(0 <= x) & (x <= 1) & Ne(x, 2)
def test_SymmetricDifference_as_relational():
x = Symbol('x')
expr = SymmetricDifference(Interval(0, 1), FiniteSet(2), evaluate=False)
assert expr.as_relational(x) == Xor(Eq(x, 2), Le(0, x) & Le(x, 1))
def test_EmptySet():
assert S.EmptySet.as_relational(Symbol('x')) is S.false
assert S.EmptySet.intersect(S.UniversalSet) == S.EmptySet
assert S.EmptySet.boundary == S.EmptySet
def test_finite_basic():
x = Symbol('x')
A = FiniteSet(1, 2, 3)
B = FiniteSet(3, 4, 5)
AorB = Union(A, B)
AandB = A.intersect(B)
assert A.is_subset(AorB) and B.is_subset(AorB)
assert AandB.is_subset(A)
assert AandB == FiniteSet(3)
assert A.inf == 1 and A.sup == 3
assert AorB.inf == 1 and AorB.sup == 5
assert FiniteSet(x, 1, 5).sup == Max(x, 5)
assert FiniteSet(x, 1, 5).inf == Min(x, 1)
# issue 7335
assert FiniteSet(S.EmptySet) != S.EmptySet
assert FiniteSet(FiniteSet(1, 2, 3)) != FiniteSet(1, 2, 3)
assert FiniteSet((1, 2, 3)) != FiniteSet(1, 2, 3)
# Ensure a variety of types can exist in a FiniteSet
assert FiniteSet((1, 2), Float, A, -5, x, 'eggs', x**2, Interval)
assert (A > B) is False
assert (A >= B) is False
assert (A < B) is False
assert (A <= B) is False
assert AorB > A and AorB > B
assert AorB >= A and AorB >= B
assert A >= A and A <= A
assert A >= AandB and B >= AandB
assert A > AandB and B > AandB
assert FiniteSet(1.0) == FiniteSet(1)
def test_product_basic():
H, T = 'H', 'T'
unit_line = Interval(0, 1)
d6 = FiniteSet(1, 2, 3, 4, 5, 6)
d4 = FiniteSet(1, 2, 3, 4)
coin = FiniteSet(H, T)
square = unit_line * unit_line
assert (0, 0) in square
assert 0 not in square
assert (H, T) in coin ** 2
assert (.5, .5, .5) in (square * unit_line).flatten()
assert ((.5, .5), .5) in square * unit_line
assert (H, 3, 3) in (coin * d6 * d6).flatten()
assert ((H, 3), 3) in coin * d6 * d6
HH, TT = sympify(H), sympify(T)
assert set(coin**2) == {(HH, HH), (HH, TT), (TT, HH), (TT, TT)}
assert (d4*d4).is_subset(d6*d6)
assert square.complement(Interval(-oo, oo)*Interval(-oo, oo)) == Union(
(Interval(-oo, 0, True, True) +
Interval(1, oo, True, True))*Interval(-oo, oo),
Interval(-oo, oo)*(Interval(-oo, 0, True, True) +
Interval(1, oo, True, True)))
assert (Interval(-5, 5)**3).is_subset(Interval(-10, 10)**3)
assert not (Interval(-10, 10)**3).is_subset(Interval(-5, 5)**3)
assert not (Interval(-5, 5)**2).is_subset(Interval(-10, 10)**3)
assert (Interval(.2, .5)*FiniteSet(.5)).is_subset(square) # segment in square
assert len(coin*coin*coin) == 8
assert len(S.EmptySet*S.EmptySet) == 0
assert len(S.EmptySet*coin) == 0
raises(TypeError, lambda: len(coin*Interval(0, 2)))
def test_real():
x = Symbol('x', real=True)
I = Interval(0, 5)
J = Interval(10, 20)
A = FiniteSet(1, 2, 30, x, S.Pi)
B = FiniteSet(-4, 0)
C = FiniteSet(100)
D = FiniteSet('Ham', 'Eggs')
assert all(s.is_subset(S.Reals) for s in [I, J, A, B, C])
assert not D.is_subset(S.Reals)
assert all((a + b).is_subset(S.Reals) for a in [I, J, A, B, C] for b in [I, J, A, B, C])
assert not any((a + D).is_subset(S.Reals) for a in [I, J, A, B, C, D])
assert not (I + A + D).is_subset(S.Reals)
def test_supinf():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
assert (Interval(0, 1) + FiniteSet(2)).sup == 2
assert (Interval(0, 1) + FiniteSet(2)).inf == 0
assert (Interval(0, 1) + FiniteSet(x)).sup == Max(1, x)
assert (Interval(0, 1) + FiniteSet(x)).inf == Min(0, x)
assert FiniteSet(5, 1, x).sup == Max(5, x)
assert FiniteSet(5, 1, x).inf == Min(1, x)
assert FiniteSet(5, 1, x, y).sup == Max(5, x, y)
assert FiniteSet(5, 1, x, y).inf == Min(1, x, y)
assert FiniteSet(5, 1, x, y, S.Infinity, S.NegativeInfinity).sup == \
S.Infinity
assert FiniteSet(5, 1, x, y, S.Infinity, S.NegativeInfinity).inf == \
S.NegativeInfinity
assert FiniteSet('Ham', 'Eggs').sup == Max('Ham', 'Eggs')
def test_universalset():
U = S.UniversalSet
x = Symbol('x')
assert U.as_relational(x) is S.true
assert U.union(Interval(2, 4)) == U
assert U.intersect(Interval(2, 4)) == Interval(2, 4)
assert U.measure is S.Infinity
assert U.boundary == S.EmptySet
assert U.contains(0) is S.true
def test_Union_of_ProductSets_shares():
line = Interval(0, 2)
points = FiniteSet(0, 1, 2)
assert Union(line * line, line * points) == line * line
def test_Interval_free_symbols():
# issue 6211
assert Interval(0, 1).free_symbols == set()
x = Symbol('x', real=True)
assert Interval(0, x).free_symbols == {x}
def test_image_interval():
x = Symbol('x', real=True)
a = Symbol('a', real=True)
assert imageset(x, 2*x, Interval(-2, 1)) == Interval(-4, 2)
assert imageset(x, 2*x, Interval(-2, 1, True, False)) == \
Interval(-4, 2, True, False)
assert imageset(x, x**2, Interval(-2, 1, True, False)) == \
Interval(0, 4, False, True)
assert imageset(x, x**2, Interval(-2, 1)) == Interval(0, 4)
assert imageset(x, x**2, Interval(-2, 1, True, False)) == \
Interval(0, 4, False, True)
assert imageset(x, x**2, Interval(-2, 1, True, True)) == \
Interval(0, 4, False, True)
assert imageset(x, (x - 2)**2, Interval(1, 3)) == Interval(0, 1)
assert imageset(x, 3*x**4 - 26*x**3 + 78*x**2 - 90*x, Interval(0, 4)) == \
Interval(-35, 0) # Multiple Maxima
assert imageset(x, x + 1/x, Interval(-oo, oo)) == Interval(-oo, -2) \
+ Interval(2, oo) # Single Infinite discontinuity
assert imageset(x, 1/x + 1/(x-1)**2, Interval(0, 2, True, False)) == \
Interval(Rational(3, 2), oo, False) # Multiple Infinite discontinuities
# Test for Python lambda
assert imageset(lambda x: 2*x, Interval(-2, 1)) == Interval(-4, 2)
assert imageset(Lambda(x, a*x), Interval(0, 1)) == \
ImageSet(Lambda(x, a*x), Interval(0, 1))
assert imageset(Lambda(x, sin(cos(x))), Interval(0, 1)) == \
ImageSet(Lambda(x, sin(cos(x))), Interval(0, 1))
def test_image_piecewise():
f = Piecewise((x, x <= -1), (1/x**2, x <= 5), (x**3, True))
f1 = Piecewise((0, x <= 1), (1, x <= 2), (2, True))
assert imageset(x, f, Interval(-5, 5)) == Union(Interval(-5, -1), Interval(Rational(1, 25), oo))
assert imageset(x, f1, Interval(1, 2)) == FiniteSet(0, 1)
@XFAIL # See: https://github.com/sympy/sympy/pull/2723#discussion_r8659826
def test_image_Intersection():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
assert imageset(x, x**2, Interval(-2, 0).intersect(Interval(x, y))) == \
Interval(0, 4).intersect(Interval(Min(x**2, y**2), Max(x**2, y**2)))
def test_image_FiniteSet():
x = Symbol('x', real=True)
assert imageset(x, 2*x, FiniteSet(1, 2, 3)) == FiniteSet(2, 4, 6)
def test_image_Union():
x = Symbol('x', real=True)
assert imageset(x, x**2, Interval(-2, 0) + FiniteSet(1, 2, 3)) == \
(Interval(0, 4) + FiniteSet(9))
def test_image_EmptySet():
x = Symbol('x', real=True)
assert imageset(x, 2*x, S.EmptySet) == S.EmptySet
def test_issue_5724_7680():
assert I not in S.Reals # issue 7680
assert Interval(-oo, oo).contains(I) is S.false
def test_boundary():
assert FiniteSet(1).boundary == FiniteSet(1)
assert all(Interval(0, 1, left_open, right_open).boundary == FiniteSet(0, 1)
for left_open in (true, false) for right_open in (true, false))
def test_boundary_Union():
assert (Interval(0, 1) + Interval(2, 3)).boundary == FiniteSet(0, 1, 2, 3)
assert ((Interval(0, 1, False, True)
+ Interval(1, 2, True, False)).boundary == FiniteSet(0, 1, 2))
assert (Interval(0, 1) + FiniteSet(2)).boundary == FiniteSet(0, 1, 2)
assert Union(Interval(0, 10), Interval(5, 15), evaluate=False).boundary \
== FiniteSet(0, 15)
assert Union(Interval(0, 10), Interval(0, 1), evaluate=False).boundary \
== FiniteSet(0, 10)
assert Union(Interval(0, 10, True, True),
Interval(10, 15, True, True), evaluate=False).boundary \
== FiniteSet(0, 10, 15)
@XFAIL
def test_union_boundary_of_joining_sets():
""" Testing the boundary of unions is a hard problem """
assert Union(Interval(0, 10), Interval(10, 15), evaluate=False).boundary \
== FiniteSet(0, 15)
def test_boundary_ProductSet():
open_square = Interval(0, 1, True, True) ** 2
assert open_square.boundary == (FiniteSet(0, 1) * Interval(0, 1)
+ Interval(0, 1) * FiniteSet(0, 1))
second_square = Interval(1, 2, True, True) * Interval(0, 1, True, True)
assert (open_square + second_square).boundary == (
FiniteSet(0, 1) * Interval(0, 1)
+ FiniteSet(1, 2) * Interval(0, 1)
+ Interval(0, 1) * FiniteSet(0, 1)
+ Interval(1, 2) * FiniteSet(0, 1))
def test_boundary_ProductSet_line():
line_in_r2 = Interval(0, 1) * FiniteSet(0)
assert line_in_r2.boundary == line_in_r2
def test_is_open():
assert Interval(0, 1, False, False).is_open is False
assert Interval(0, 1, True, False).is_open is False
assert Interval(0, 1, True, True).is_open is True
assert FiniteSet(1, 2, 3).is_open is False
def test_is_closed():
assert Interval(0, 1, False, False).is_closed is True
assert Interval(0, 1, True, False).is_closed is False
assert FiniteSet(1, 2, 3).is_closed is True
def test_closure():
assert Interval(0, 1, False, True).closure == Interval(0, 1, False, False)
def test_interior():
assert Interval(0, 1, False, True).interior == Interval(0, 1, True, True)
def test_issue_7841():
raises(TypeError, lambda: x in S.Reals)
def test_Eq():
assert Eq(Interval(0, 1), Interval(0, 1))
assert Eq(Interval(0, 1), Interval(0, 2)) == False
s1 = FiniteSet(0, 1)
s2 = FiniteSet(1, 2)
assert Eq(s1, s1)
assert Eq(s1, s2) == False
assert Eq(s1*s2, s1*s2)
assert Eq(s1*s2, s2*s1) == False
assert unchanged(Eq, FiniteSet({x, y}), FiniteSet({x}))
assert Eq(FiniteSet({x, y}).subs(y, x), FiniteSet({x})) is S.true
assert Eq(FiniteSet({x, y}), FiniteSet({x})).subs(y, x) is S.true
assert Eq(FiniteSet({x, y}).subs(y, x+1), FiniteSet({x})) is S.false
assert Eq(FiniteSet({x, y}), FiniteSet({x})).subs(y, x+1) is S.false
assert Eq(ProductSet({1}, {2}), Interval(1, 2)) is S.false
assert Eq(ProductSet({1}), ProductSet({1}, {2})) is S.false
assert Eq(FiniteSet(()), FiniteSet(1)) is S.false
assert Eq(ProductSet(), FiniteSet(1)) is S.false
i1 = Interval(0, 1)
i2 = Interval(x, y)
assert unchanged(Eq, ProductSet(i1, i1), ProductSet(i2, i2))
def test_SymmetricDifference():
A = FiniteSet(0, 1, 2, 3, 4, 5)
B = FiniteSet(2, 4, 6, 8, 10)
C = Interval(8, 10)
assert SymmetricDifference(A, B, evaluate=False).is_iterable is True
assert SymmetricDifference(A, C, evaluate=False).is_iterable is None
assert FiniteSet(*SymmetricDifference(A, B, evaluate=False)) == \
FiniteSet(0, 1, 3, 5, 6, 8, 10)
raises(TypeError,
lambda: FiniteSet(*SymmetricDifference(A, C, evaluate=False)))
assert SymmetricDifference(FiniteSet(0, 1, 2, 3, 4, 5), \
FiniteSet(2, 4, 6, 8, 10)) == FiniteSet(0, 1, 3, 5, 6, 8, 10)
assert SymmetricDifference(FiniteSet(2, 3, 4), FiniteSet(2, 3, 4 ,5)) \
== FiniteSet(5)
assert FiniteSet(1, 2, 3, 4, 5) ^ FiniteSet(1, 2, 5, 6) == \
FiniteSet(3, 4, 6)
assert Set(S(1), S(2), S(3)) ^ Set(S(2), S(3), S(4)) == Union(Set(S(1), S(2), S(3)) - Set(S(2), S(3), S(4)), \
Set(S(2), S(3), S(4)) - Set(S(1), S(2), S(3)))
assert Interval(0, 4) ^ Interval(2, 5) == Union(Interval(0, 4) - \
Interval(2, 5), Interval(2, 5) - Interval(0, 4))
def test_issue_9536():
from sympy.functions.elementary.exponential import log
a = Symbol('a', real=True)
assert FiniteSet(log(a)).intersect(S.Reals) == Intersection(S.Reals, FiniteSet(log(a)))
def test_issue_9637():
n = Symbol('n')
a = FiniteSet(n)
b = FiniteSet(2, n)
assert Complement(S.Reals, a) == Complement(S.Reals, a, evaluate=False)
assert Complement(Interval(1, 3), a) == Complement(Interval(1, 3), a, evaluate=False)
assert Complement(Interval(1, 3), b) == \
Complement(Union(Interval(1, 2, False, True), Interval(2, 3, True, False)), a)
assert Complement(a, S.Reals) == Complement(a, S.Reals, evaluate=False)
assert Complement(a, Interval(1, 3)) == Complement(a, Interval(1, 3), evaluate=False)
def test_issue_9808():
# See https://github.com/sympy/sympy/issues/16342
assert Complement(FiniteSet(y), FiniteSet(1)) == Complement(FiniteSet(y), FiniteSet(1), evaluate=False)
assert Complement(FiniteSet(1, 2, x), FiniteSet(x, y, 2, 3)) == \
Complement(FiniteSet(1), FiniteSet(y), evaluate=False)
def test_issue_9956():
assert Union(Interval(-oo, oo), FiniteSet(1)) == Interval(-oo, oo)
assert Interval(-oo, oo).contains(1) is S.true
def test_issue_Symbol_inter():
i = Interval(0, oo)
r = S.Reals
mat = Matrix([0, 0, 0])
assert Intersection(r, i, FiniteSet(m), FiniteSet(m, n)) == \
Intersection(i, FiniteSet(m))
assert Intersection(FiniteSet(1, m, n), FiniteSet(m, n, 2), i) == \
Intersection(i, FiniteSet(m, n))
assert Intersection(FiniteSet(m, n, x), FiniteSet(m, z), r) == \
Intersection(Intersection({m, z}, {m, n, x}), r)
assert Intersection(FiniteSet(m, n, 3), FiniteSet(m, n, x), r) == \
Intersection(FiniteSet(3, m, n), FiniteSet(m, n, x), r, evaluate=False)
assert Intersection(FiniteSet(m, n, 3), FiniteSet(m, n, 2, 3), r) == \
Intersection(FiniteSet(3, m, n), r)
assert Intersection(r, FiniteSet(mat, 2, n), FiniteSet(0, mat, n)) == \
Intersection(r, FiniteSet(n))
assert Intersection(FiniteSet(sin(x), cos(x)), FiniteSet(sin(x), cos(x), 1), r) == \
Intersection(r, FiniteSet(sin(x), cos(x)))
assert Intersection(FiniteSet(x**2, 1, sin(x)), FiniteSet(x**2, 2, sin(x)), r) == \
Intersection(r, FiniteSet(x**2, sin(x)))
def test_issue_11827():
assert S.Naturals0**4
def test_issue_10113():
f = x**2/(x**2 - 4)
assert imageset(x, f, S.Reals) == Union(Interval(-oo, 0), Interval(1, oo, True, True))
assert imageset(x, f, Interval(-2, 2)) == Interval(-oo, 0)
assert imageset(x, f, Interval(-2, 3)) == Union(Interval(-oo, 0), Interval(Rational(9, 5), oo))
def test_issue_10248():
raises(
TypeError, lambda: list(Intersection(S.Reals, FiniteSet(x)))
)
A = Symbol('A', real=True)
assert list(Intersection(S.Reals, FiniteSet(A))) == [A]
def test_issue_9447():
a = Interval(0, 1) + Interval(2, 3)
assert Complement(S.UniversalSet, a) == Complement(
S.UniversalSet, Union(Interval(0, 1), Interval(2, 3)), evaluate=False)
assert Complement(S.Naturals, a) == Complement(
S.Naturals, Union(Interval(0, 1), Interval(2, 3)), evaluate=False)
def test_issue_10337():
assert (FiniteSet(2) == 3) is False
assert (FiniteSet(2) != 3) is True
raises(TypeError, lambda: FiniteSet(2) < 3)
raises(TypeError, lambda: FiniteSet(2) <= 3)
raises(TypeError, lambda: FiniteSet(2) > 3)
raises(TypeError, lambda: FiniteSet(2) >= 3)
def test_issue_10326():
bad = [
EmptySet,
FiniteSet(1),
Interval(1, 2),
S.ComplexInfinity,
S.ImaginaryUnit,
S.Infinity,
S.NaN,
S.NegativeInfinity,
]
interval = Interval(0, 5)
for i in bad:
assert i not in interval
x = Symbol('x', real=True)
nr = Symbol('nr', extended_real=False)
assert x + 1 in Interval(x, x + 4)
assert nr not in Interval(x, x + 4)
assert Interval(1, 2) in FiniteSet(Interval(0, 5), Interval(1, 2))
assert Interval(-oo, oo).contains(oo) is S.false
assert Interval(-oo, oo).contains(-oo) is S.false
def test_issue_2799():
U = S.UniversalSet
a = Symbol('a', real=True)
inf_interval = Interval(a, oo)
R = S.Reals
assert U + inf_interval == inf_interval + U
assert U + R == R + U
assert R + inf_interval == inf_interval + R
def test_issue_9706():
assert Interval(-oo, 0).closure == Interval(-oo, 0, True, False)
assert Interval(0, oo).closure == Interval(0, oo, False, True)
assert Interval(-oo, oo).closure == Interval(-oo, oo)
def test_issue_8257():
reals_plus_infinity = Union(Interval(-oo, oo), FiniteSet(oo))
reals_plus_negativeinfinity = Union(Interval(-oo, oo), FiniteSet(-oo))
assert Interval(-oo, oo) + FiniteSet(oo) == reals_plus_infinity
assert FiniteSet(oo) + Interval(-oo, oo) == reals_plus_infinity
assert Interval(-oo, oo) + FiniteSet(-oo) == reals_plus_negativeinfinity
assert FiniteSet(-oo) + Interval(-oo, oo) == reals_plus_negativeinfinity
def test_issue_10931():
assert S.Integers - S.Integers == EmptySet
assert S.Integers - S.Reals == EmptySet
def test_issue_11174():
soln = Intersection(Interval(-oo, oo), FiniteSet(-x), evaluate=False)
assert Intersection(FiniteSet(-x), S.Reals) == soln
soln = Intersection(S.Reals, FiniteSet(x), evaluate=False)
assert Intersection(FiniteSet(x), S.Reals) == soln
def test_issue_18505():
assert ImageSet(Lambda(n, sqrt(pi*n/2 - 1 + pi/2)), S.Integers).contains(0) == \
Contains(0, ImageSet(Lambda(n, sqrt(pi*n/2 - 1 + pi/2)), S.Integers))
def test_finite_set_intersection():
# The following should not produce recursion errors
# Note: some of these are not completely correct. See
# https://github.com/sympy/sympy/issues/16342.
assert Intersection(FiniteSet(-oo, x), FiniteSet(x)) == FiniteSet(x)
assert Intersection._handle_finite_sets([FiniteSet(-oo, x), FiniteSet(0, x)]) == FiniteSet(x)
assert Intersection._handle_finite_sets([FiniteSet(-oo, x), FiniteSet(x)]) == FiniteSet(x)
assert Intersection._handle_finite_sets([FiniteSet(2, 3, x, y), FiniteSet(1, 2, x)]) == \
Intersection._handle_finite_sets([FiniteSet(1, 2, x), FiniteSet(2, 3, x, y)]) == \
Intersection(FiniteSet(1, 2, x), FiniteSet(2, 3, x, y)) == \
Intersection(FiniteSet(1, 2, x), FiniteSet(2, x, y))
assert FiniteSet(1+x-y) & FiniteSet(1) == \
FiniteSet(1) & FiniteSet(1+x-y) == \
Intersection(FiniteSet(1+x-y), FiniteSet(1), evaluate=False)
assert FiniteSet(1) & FiniteSet(x) == FiniteSet(x) & FiniteSet(1) == \
Intersection(FiniteSet(1), FiniteSet(x), evaluate=False)
assert FiniteSet({x}) & FiniteSet({x, y}) == \
Intersection(FiniteSet({x}), FiniteSet({x, y}), evaluate=False)
def test_union_intersection_constructor():
# The actual exception does not matter here, so long as these fail
sets = [FiniteSet(1), FiniteSet(2)]
raises(Exception, lambda: Union(sets))
raises(Exception, lambda: Intersection(sets))
raises(Exception, lambda: Union(tuple(sets)))
raises(Exception, lambda: Intersection(tuple(sets)))
raises(Exception, lambda: Union(i for i in sets))
raises(Exception, lambda: Intersection(i for i in sets))
# Python sets are treated the same as FiniteSet
# The union of a single set (of sets) is the set (of sets) itself
assert Union(set(sets)) == FiniteSet(*sets)
assert Intersection(set(sets)) == FiniteSet(*sets)
assert Union({1}, {2}) == FiniteSet(1, 2)
assert Intersection({1, 2}, {2, 3}) == FiniteSet(2)
def test_Union_contains():
assert zoo not in Union(
Interval.open(-oo, 0), Interval.open(0, oo))
@XFAIL
def test_issue_16878b():
# in intersection_sets for (ImageSet, Set) there is no code
# that handles the base_set of S.Reals like there is
# for Integers
assert imageset(x, (x, x), S.Reals).is_subset(S.Reals**2) is True
def test_DisjointUnion():
assert DisjointUnion(FiniteSet(1, 2, 3), FiniteSet(1, 2, 3), FiniteSet(1, 2, 3)).rewrite(Union) == (FiniteSet(1, 2, 3) * FiniteSet(0, 1, 2))
assert DisjointUnion(Interval(1, 3), Interval(2, 4)).rewrite(Union) == Union(Interval(1, 3) * FiniteSet(0), Interval(2, 4) * FiniteSet(1))
assert DisjointUnion(Interval(0, 5), Interval(0, 5)).rewrite(Union) == Union(Interval(0, 5) * FiniteSet(0), Interval(0, 5) * FiniteSet(1))
assert DisjointUnion(Interval(-1, 2), S.EmptySet, S.EmptySet).rewrite(Union) == Interval(-1, 2) * FiniteSet(0)
assert DisjointUnion(Interval(-1, 2)).rewrite(Union) == Interval(-1, 2) * FiniteSet(0)
assert DisjointUnion(S.EmptySet, Interval(-1, 2), S.EmptySet).rewrite(Union) == Interval(-1, 2) * FiniteSet(1)
assert DisjointUnion(Interval(-oo, oo)).rewrite(Union) == Interval(-oo, oo) * FiniteSet(0)
assert DisjointUnion(S.EmptySet).rewrite(Union) == S.EmptySet
assert DisjointUnion().rewrite(Union) == S.EmptySet
raises(TypeError, lambda: DisjointUnion(Symbol('n')))
x = Symbol("x")
y = Symbol("y")
z = Symbol("z")
assert DisjointUnion(FiniteSet(x), FiniteSet(y, z)).rewrite(Union) == (FiniteSet(x) * FiniteSet(0)) + (FiniteSet(y, z) * FiniteSet(1))
def test_DisjointUnion_is_empty():
assert DisjointUnion(S.EmptySet).is_empty is True
assert DisjointUnion(S.EmptySet, S.EmptySet).is_empty is True
assert DisjointUnion(S.EmptySet, FiniteSet(1, 2, 3)).is_empty is False
def test_DisjointUnion_is_iterable():
assert DisjointUnion(S.Integers, S.Naturals, S.Rationals).is_iterable is True
assert DisjointUnion(S.EmptySet, S.Reals).is_iterable is False
assert DisjointUnion(FiniteSet(1, 2, 3), S.EmptySet, FiniteSet(x, y)).is_iterable is True
assert DisjointUnion(S.EmptySet, S.EmptySet).is_iterable is False
def test_DisjointUnion_contains():
assert (0, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (0, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (0, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (1, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (1, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (1, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (2, 0) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (2, 1) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (2, 2) in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (0, 1, 2) not in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (0, 0.5) not in DisjointUnion(FiniteSet(0.5))
assert (0, 5) not in DisjointUnion(FiniteSet(0, 1, 2), FiniteSet(0, 1, 2), FiniteSet(0, 1, 2))
assert (x, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
assert (y, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
assert (z, 0) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
assert (y, 2) in DisjointUnion(FiniteSet(x, y, z), S.EmptySet, FiniteSet(y))
assert (0.5, 0) in DisjointUnion(Interval(0, 1), Interval(0, 2))
assert (0.5, 1) in DisjointUnion(Interval(0, 1), Interval(0, 2))
assert (1.5, 0) not in DisjointUnion(Interval(0, 1), Interval(0, 2))
assert (1.5, 1) in DisjointUnion(Interval(0, 1), Interval(0, 2))
def test_DisjointUnion_iter():
D = DisjointUnion(FiniteSet(3, 5, 7, 9), FiniteSet(x, y, z))
it = iter(D)
L1 = [(x, 1), (y, 1), (z, 1)]
L2 = [(3, 0), (5, 0), (7, 0), (9, 0)]
nxt = next(it)
assert nxt in L2
L2.remove(nxt)
nxt = next(it)
assert nxt in L1
L1.remove(nxt)
nxt = next(it)
assert nxt in L2
L2.remove(nxt)
nxt = next(it)
assert nxt in L1
L1.remove(nxt)
nxt = next(it)
assert nxt in L2
L2.remove(nxt)
nxt = next(it)
assert nxt in L1
L1.remove(nxt)
nxt = next(it)
assert nxt in L2
L2.remove(nxt)
raises(StopIteration, lambda: next(it))
raises(ValueError, lambda: iter(DisjointUnion(Interval(0, 1), S.EmptySet)))
def test_DisjointUnion_len():
assert len(DisjointUnion(FiniteSet(3, 5, 7, 9), FiniteSet(x, y, z))) == 7
assert len(DisjointUnion(S.EmptySet, S.EmptySet, FiniteSet(x, y, z), S.EmptySet)) == 3
raises(ValueError, lambda: len(DisjointUnion(Interval(0, 1), S.EmptySet)))
def test_issue_20089():
B = FiniteSet(FiniteSet(1, 2), FiniteSet(1))
assert 1 not in B
assert 1.0 not in B
assert not Eq(1, FiniteSet(1, 2))
assert FiniteSet(1) in B
A = FiniteSet(1, 2)
assert A in B
assert B.issubset(B)
assert not A.issubset(B)
assert 1 in A
C = FiniteSet(FiniteSet(1, 2), FiniteSet(1), 1, 2)
assert A.issubset(C)
assert B.issubset(C)
def test_issue_19378():
a = FiniteSet(1, 2)
b = ProductSet(a, a)
c = FiniteSet((1, 1), (1, 2), (2, 1), (2, 2))
assert b.is_subset(c) is True
d = FiniteSet(1)
assert b.is_subset(d) is False
assert Eq(c, b).simplify() is S.true
assert Eq(a, c).simplify() is S.false
assert Eq({1}, {x}).simplify() == Eq({1}, {x})
def test_intersection_symbolic():
n = Symbol('n')
# These should not throw an error
assert isinstance(Intersection(Range(n), Range(100)), Intersection)
assert isinstance(Intersection(Range(n), Interval(1, 100)), Intersection)
assert isinstance(Intersection(Range(100), Interval(1, n)), Intersection)
@XFAIL
def test_intersection_symbolic_failing():
n = Symbol('n', integer=True, positive=True)
assert Intersection(Range(10, n), Range(4, 500, 5)) == Intersection(
Range(14, n), Range(14, 500, 5))
assert Intersection(Interval(10, n), Range(4, 500, 5)) == Intersection(
Interval(14, n), Range(14, 500, 5))
def test_issue_20379():
#https://github.com/sympy/sympy/issues/20379
x = pi - 3.14159265358979
assert FiniteSet(x).evalf(2) == FiniteSet(Float('3.23108914886517e-15', 2))
def test_finiteset_simplify():
S = FiniteSet(1, cos(1)**2 + sin(1)**2)
assert S.simplify() == {1}
|
831a4fc2fa2b7d85a8bb6bc2bbef4fefdb4179fd2ea210e65cf5e234cc7ab45d | import os
from tempfile import TemporaryDirectory
from sympy.concrete.summations import Sum
from sympy.core.numbers import (I, oo, pi)
from sympy.core.relational import Ne
from sympy.core.symbol import Symbol
from sympy.functions.elementary.exponential import (LambertW, exp, exp_polar, log)
from sympy.functions.elementary.miscellaneous import (real_root, sqrt)
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import (cos, sin)
from sympy.functions.special.hyper import meijerg
from sympy.integrals.integrals import Integral
from sympy.logic.boolalg import And
from sympy.core.singleton import S
from sympy.core.sympify import sympify
from sympy.external import import_module
from sympy.plotting.plot import (
Plot, plot, plot_parametric, plot3d_parametric_line, plot3d,
plot3d_parametric_surface)
from sympy.plotting.plot import (
unset_show, plot_contour, PlotGrid, DefaultBackend, MatplotlibBackend,
TextBackend, BaseBackend)
from sympy.testing.pytest import skip, raises, warns
from sympy.utilities import lambdify as lambdify_
unset_show()
matplotlib = import_module(
'matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
class DummyBackendNotOk(BaseBackend):
""" Used to verify if users can create their own backends.
This backend is meant to raise NotImplementedError for methods `show`,
`save`, `close`.
"""
pass
class DummyBackendOk(BaseBackend):
""" Used to verify if users can create their own backends.
This backend is meant to pass all tests.
"""
def show(self):
pass
def save(self):
pass
def close(self):
pass
def test_plot_and_save_1():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
y = Symbol('y')
with TemporaryDirectory(prefix='sympy_') as tmpdir:
###
# Examples from the 'introduction' notebook
###
p = plot(x, legend=True, label='f1')
p = plot(x*sin(x), x*cos(x), label='f2')
p.extend(p)
p[0].line_color = lambda a: a
p[1].line_color = 'b'
p.title = 'Big title'
p.xlabel = 'the x axis'
p[1].label = 'straight line'
p.legend = True
p.aspect_ratio = (1, 1)
p.xlim = (-15, 20)
filename = 'test_basic_options_and_colors.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
p.extend(plot(x + 1))
p.append(plot(x + 3, x**2)[1])
filename = 'test_plot_extend_append.png'
p.save(os.path.join(tmpdir, filename))
p[2] = plot(x**2, (x, -2, 3))
filename = 'test_plot_setitem.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
p = plot(sin(x), (x, -2*pi, 4*pi))
filename = 'test_line_explicit.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
p = plot(sin(x))
filename = 'test_line_default_range.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
p = plot((x**2, (x, -5, 5)), (x**3, (x, -3, 3)))
filename = 'test_line_multiple_range.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
raises(ValueError, lambda: plot(x, y))
#Piecewise plots
p = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1))
filename = 'test_plot_piecewise.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
p = plot(Piecewise((x, x < 1), (x**2, True)), (x, -3, 3))
filename = 'test_plot_piecewise_2.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
# test issue 7471
p1 = plot(x)
p2 = plot(3)
p1.extend(p2)
filename = 'test_horizontal_line.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
# test issue 10925
f = Piecewise((-1, x < -1), (x, And(-1 <= x, x < 0)), \
(x**2, And(0 <= x, x < 1)), (x**3, x >= 1))
p = plot(f, (x, -3, 3))
filename = 'test_plot_piecewise_3.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
def test_plot_and_save_2():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
with TemporaryDirectory(prefix='sympy_') as tmpdir:
#parametric 2d plots.
#Single plot with default range.
p = plot_parametric(sin(x), cos(x))
filename = 'test_parametric.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
#Single plot with range.
p = plot_parametric(
sin(x), cos(x), (x, -5, 5), legend=True, label='parametric_plot')
filename = 'test_parametric_range.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
#Multiple plots with same range.
p = plot_parametric((sin(x), cos(x)), (x, sin(x)))
filename = 'test_parametric_multiple.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
#Multiple plots with different ranges.
p = plot_parametric(
(sin(x), cos(x), (x, -3, 3)), (x, sin(x), (x, -5, 5)))
filename = 'test_parametric_multiple_ranges.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
#depth of recursion specified.
p = plot_parametric(x, sin(x), depth=13)
filename = 'test_recursion_depth.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
#No adaptive sampling.
p = plot_parametric(cos(x), sin(x), adaptive=False, nb_of_points=500)
filename = 'test_adaptive.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
#3d parametric plots
p = plot3d_parametric_line(
sin(x), cos(x), x, legend=True, label='3d_parametric_plot')
filename = 'test_3d_line.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
p = plot3d_parametric_line(
(sin(x), cos(x), x, (x, -5, 5)), (cos(x), sin(x), x, (x, -3, 3)))
filename = 'test_3d_line_multiple.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
p = plot3d_parametric_line(sin(x), cos(x), x, nb_of_points=30)
filename = 'test_3d_line_points.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
# 3d surface single plot.
p = plot3d(x * y)
filename = 'test_surface.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
# Multiple 3D plots with same range.
p = plot3d(-x * y, x * y, (x, -5, 5))
filename = 'test_surface_multiple.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
# Multiple 3D plots with different ranges.
p = plot3d(
(x * y, (x, -3, 3), (y, -3, 3)), (-x * y, (x, -3, 3), (y, -3, 3)))
filename = 'test_surface_multiple_ranges.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
# Single Parametric 3D plot
p = plot3d_parametric_surface(sin(x + y), cos(x - y), x - y)
filename = 'test_parametric_surface.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
# Multiple Parametric 3D plots.
p = plot3d_parametric_surface(
(x*sin(z), x*cos(z), z, (x, -5, 5), (z, -5, 5)),
(sin(x + y), cos(x - y), x - y, (x, -5, 5), (y, -5, 5)))
filename = 'test_parametric_surface.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
# Single Contour plot.
p = plot_contour(sin(x)*sin(y), (x, -5, 5), (y, -5, 5))
filename = 'test_contour_plot.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
# Multiple Contour plots with same range.
p = plot_contour(x**2 + y**2, x**3 + y**3, (x, -5, 5), (y, -5, 5))
filename = 'test_contour_plot.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
# Multiple Contour plots with different range.
p = plot_contour(
(x**2 + y**2, (x, -5, 5), (y, -5, 5)),
(x**3 + y**3, (x, -3, 3), (y, -3, 3)))
filename = 'test_contour_plot.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
def test_plot_and_save_3():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
with TemporaryDirectory(prefix='sympy_') as tmpdir:
###
# Examples from the 'colors' notebook
###
p = plot(sin(x))
p[0].line_color = lambda a: a
filename = 'test_colors_line_arity1.png'
p.save(os.path.join(tmpdir, filename))
p[0].line_color = lambda a, b: b
filename = 'test_colors_line_arity2.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
p = plot(x*sin(x), x*cos(x), (x, 0, 10))
p[0].line_color = lambda a: a
filename = 'test_colors_param_line_arity1.png'
p.save(os.path.join(tmpdir, filename))
p[0].line_color = lambda a, b: a
filename = 'test_colors_param_line_arity1.png'
p.save(os.path.join(tmpdir, filename))
p[0].line_color = lambda a, b: b
filename = 'test_colors_param_line_arity2b.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
p = plot3d_parametric_line(sin(x) + 0.1*sin(x)*cos(7*x),
cos(x) + 0.1*cos(x)*cos(7*x),
0.1*sin(7*x),
(x, 0, 2*pi))
p[0].line_color = lambdify_(x, sin(4*x))
filename = 'test_colors_3d_line_arity1.png'
p.save(os.path.join(tmpdir, filename))
p[0].line_color = lambda a, b: b
filename = 'test_colors_3d_line_arity2.png'
p.save(os.path.join(tmpdir, filename))
p[0].line_color = lambda a, b, c: c
filename = 'test_colors_3d_line_arity3.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
p = plot3d(sin(x)*y, (x, 0, 6*pi), (y, -5, 5))
p[0].surface_color = lambda a: a
filename = 'test_colors_surface_arity1.png'
p.save(os.path.join(tmpdir, filename))
p[0].surface_color = lambda a, b: b
filename = 'test_colors_surface_arity2.png'
p.save(os.path.join(tmpdir, filename))
p[0].surface_color = lambda a, b, c: c
filename = 'test_colors_surface_arity3a.png'
p.save(os.path.join(tmpdir, filename))
p[0].surface_color = lambdify_((x, y, z), sqrt((x - 3*pi)**2 + y**2))
filename = 'test_colors_surface_arity3b.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
p = plot3d_parametric_surface(x * cos(4 * y), x * sin(4 * y), y,
(x, -1, 1), (y, -1, 1))
p[0].surface_color = lambda a: a
filename = 'test_colors_param_surf_arity1.png'
p.save(os.path.join(tmpdir, filename))
p[0].surface_color = lambda a, b: a*b
filename = 'test_colors_param_surf_arity2.png'
p.save(os.path.join(tmpdir, filename))
p[0].surface_color = lambdify_((x, y, z), sqrt(x**2 + y**2 + z**2))
filename = 'test_colors_param_surf_arity3.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
def test_plot_and_save_4():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
y = Symbol('y')
###
# Examples from the 'advanced' notebook
###
# XXX: This raises the warning "The evaluation of the expression is
# problematic. We are trying a failback method that may still work. Please
# report this as a bug." It has to use the fallback because using evalf()
# is the only way to evaluate the integral. We should perhaps just remove
# that warning.
with TemporaryDirectory(prefix='sympy_') as tmpdir:
with warns(
UserWarning,
match="The evaluation of the expression is problematic"):
i = Integral(log((sin(x)**2 + 1)*sqrt(x**2 + 1)), (x, 0, y))
p = plot(i, (y, 1, 5))
filename = 'test_advanced_integral.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
def test_plot_and_save_5():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
y = Symbol('y')
with TemporaryDirectory(prefix='sympy_') as tmpdir:
s = Sum(1/x**y, (x, 1, oo))
p = plot(s, (y, 2, 10))
filename = 'test_advanced_inf_sum.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
p = plot(Sum(1/x, (x, 1, y)), (y, 2, 10), show=False)
p[0].only_integers = True
p[0].steps = True
filename = 'test_advanced_fin_sum.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
def test_plot_and_save_6():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
with TemporaryDirectory(prefix='sympy_') as tmpdir:
filename = 'test.png'
###
# Test expressions that can not be translated to np and generate complex
# results.
###
p = plot(sin(x) + I*cos(x))
p.save(os.path.join(tmpdir, filename))
p = plot(sqrt(sqrt(-x)))
p.save(os.path.join(tmpdir, filename))
p = plot(LambertW(x))
p.save(os.path.join(tmpdir, filename))
p = plot(sqrt(LambertW(x)))
p.save(os.path.join(tmpdir, filename))
#Characteristic function of a StudentT distribution with nu=10
x1 = 5 * x**2 * exp_polar(-I*pi)/2
m1 = meijerg(((1 / 2,), ()), ((5, 0, 1 / 2), ()), x1)
x2 = 5*x**2 * exp_polar(I*pi)/2
m2 = meijerg(((1/2,), ()), ((5, 0, 1/2), ()), x2)
expr = (m1 + m2) / (48 * pi)
p = plot(expr, (x, 1e-6, 1e-2))
p.save(os.path.join(tmpdir, filename))
def test_plotgrid_and_save():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
y = Symbol('y')
with TemporaryDirectory(prefix='sympy_') as tmpdir:
p1 = plot(x)
p2 = plot_parametric((sin(x), cos(x)), (x, sin(x)), show=False)
p3 = plot_parametric(
cos(x), sin(x), adaptive=False, nb_of_points=500, show=False)
p4 = plot3d_parametric_line(sin(x), cos(x), x, show=False)
# symmetric grid
p = PlotGrid(2, 2, p1, p2, p3, p4)
filename = 'test_grid1.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
# grid size greater than the number of subplots
p = PlotGrid(3, 4, p1, p2, p3, p4)
filename = 'test_grid2.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
p5 = plot(cos(x),(x, -pi, pi), show=False)
p5[0].line_color = lambda a: a
p6 = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1), show=False)
p7 = plot_contour(
(x**2 + y**2, (x, -5, 5), (y, -5, 5)),
(x**3 + y**3, (x, -3, 3), (y, -3, 3)), show=False)
# unsymmetric grid (subplots in one line)
p = PlotGrid(1, 3, p5, p6, p7)
filename = 'test_grid3.png'
p.save(os.path.join(tmpdir, filename))
p._backend.close()
def test_append_issue_7140():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
p1 = plot(x)
p2 = plot(x**2)
plot(x + 2)
# append a series
p2.append(p1[0])
assert len(p2._series) == 2
with raises(TypeError):
p1.append(p2)
with raises(TypeError):
p1.append(p2._series)
def test_issue_15265():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
eqn = sin(x)
p = plot(eqn, xlim=(-S.Pi, S.Pi), ylim=(-1, 1))
p._backend.close()
p = plot(eqn, xlim=(-1, 1), ylim=(-S.Pi, S.Pi))
p._backend.close()
p = plot(eqn, xlim=(-1, 1), ylim=(sympify('-3.14'), sympify('3.14')))
p._backend.close()
p = plot(eqn, xlim=(sympify('-3.14'), sympify('3.14')), ylim=(-1, 1))
p._backend.close()
raises(ValueError,
lambda: plot(eqn, xlim=(-S.ImaginaryUnit, 1), ylim=(-1, 1)))
raises(ValueError,
lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.ImaginaryUnit)))
raises(ValueError,
lambda: plot(eqn, xlim=(S.NegativeInfinity, 1), ylim=(-1, 1)))
raises(ValueError,
lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.Infinity)))
def test_empty_Plot():
if not matplotlib:
skip("Matplotlib not the default backend")
# No exception showing an empty plot
plot()
p = Plot()
p.show()
def test_issue_17405():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
f = x**0.3 - 10*x**3 + x**2
p = plot(f, (x, -10, 10), show=False)
# Random number of segments, probably more than 100, but we want to see
# that there are segments generated, as opposed to when the bug was present
assert len(p[0].get_data()[0]) >= 30
def test_logplot_PR_16796():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
p = plot(x, (x, .001, 100), xscale='log', show=False)
# Random number of segments, probably more than 100, but we want to see
# that there are segments generated, as opposed to when the bug was present
assert len(p[0].get_data()[0]) >= 30
assert p[0].end == 100.0
assert p[0].start == .001
def test_issue_16572():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
p = plot(LambertW(x), show=False)
# Random number of segments, probably more than 50, but we want to see
# that there are segments generated, as opposed to when the bug was present
assert len(p[0].get_data()[0]) >= 30
def test_issue_11865():
if not matplotlib:
skip("Matplotlib not the default backend")
k = Symbol('k', integer=True)
f = Piecewise((-I*exp(I*pi*k)/k + I*exp(-I*pi*k)/k, Ne(k, 0)), (2*pi, True))
p = plot(f, show=False)
# Random number of segments, probably more than 100, but we want to see
# that there are segments generated, as opposed to when the bug was present
# and that there are no exceptions.
assert len(p[0].get_data()[0]) >= 30
def test_issue_11461():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
p = plot(real_root((log(x/(x-2))), 3), show=False)
# Random number of segments, probably more than 100, but we want to see
# that there are segments generated, as opposed to when the bug was present
# and that there are no exceptions.
assert len(p[0].get_data()[0]) >= 30
def test_issue_11764():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
p = plot_parametric(cos(x), sin(x), (x, 0, 2 * pi), aspect_ratio=(1,1), show=False)
assert p.aspect_ratio == (1, 1)
# Random number of segments, probably more than 100, but we want to see
# that there are segments generated, as opposed to when the bug was present
assert len(p[0].get_data()[0]) >= 30
def test_issue_13516():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
pm = plot(sin(x), backend="matplotlib", show=False)
assert pm.backend == MatplotlibBackend
assert len(pm[0].get_data()[0]) >= 30
pt = plot(sin(x), backend="text", show=False)
assert pt.backend == TextBackend
assert len(pt[0].get_data()[0]) >= 30
pd = plot(sin(x), backend="default", show=False)
assert pd.backend == DefaultBackend
assert len(pd[0].get_data()[0]) >= 30
p = plot(sin(x), show=False)
assert p.backend == DefaultBackend
assert len(p[0].get_data()[0]) >= 30
def test_plot_limits():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
p = plot(x, x**2, (x, -10, 10))
backend = p._backend
xmin, xmax = backend.ax[0].get_xlim()
assert abs(xmin + 10) < 2
assert abs(xmax - 10) < 2
ymin, ymax = backend.ax[0].get_ylim()
assert abs(ymin + 10) < 10
assert abs(ymax - 100) < 10
def test_plot3d_parametric_line_limits():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
v1 = (2*cos(x), 2*sin(x), 2*x, (x, -5, 5))
v2 = (sin(x), cos(x), x, (x, -5, 5))
p = plot3d_parametric_line(v1, v2)
backend = p._backend
xmin, xmax = backend.ax[0].get_xlim()
assert abs(xmin + 2) < 1e-2
assert abs(xmax - 2) < 1e-2
ymin, ymax = backend.ax[0].get_ylim()
assert abs(ymin + 2) < 1e-2
assert abs(ymax - 2) < 1e-2
zmin, zmax = backend.ax[0].get_zlim()
assert abs(zmin + 10) < 1e-2
assert abs(zmax - 10) < 1e-2
p = plot3d_parametric_line(v2, v1)
backend = p._backend
xmin, xmax = backend.ax[0].get_xlim()
assert abs(xmin + 2) < 1e-2
assert abs(xmax - 2) < 1e-2
ymin, ymax = backend.ax[0].get_ylim()
assert abs(ymin + 2) < 1e-2
assert abs(ymax - 2) < 1e-2
zmin, zmax = backend.ax[0].get_zlim()
assert abs(zmin + 10) < 1e-2
assert abs(zmax - 10) < 1e-2
def test_plot_size():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
p1 = plot(sin(x), backend="matplotlib", size=(8, 4))
s1 = p1._backend.fig.get_size_inches()
assert (s1[0] == 8) and (s1[1] == 4)
p2 = plot(sin(x), backend="matplotlib", size=(5, 10))
s2 = p2._backend.fig.get_size_inches()
assert (s2[0] == 5) and (s2[1] == 10)
p3 = PlotGrid(2, 1, p1, p2, size=(6, 2))
s3 = p3._backend.fig.get_size_inches()
assert (s3[0] == 6) and (s3[1] == 2)
with raises(ValueError):
plot(sin(x), backend="matplotlib", size=(-1, 3))
def test_issue_20113():
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
# verify the capability to use custom backends
with raises(TypeError):
plot(sin(x), backend=Plot, show=False)
p2 = plot(sin(x), backend=MatplotlibBackend, show=False)
assert p2.backend == MatplotlibBackend
assert len(p2[0].get_data()[0]) >= 30
p3 = plot(sin(x), backend=DummyBackendOk, show=False)
assert p3.backend == DummyBackendOk
assert len(p3[0].get_data()[0]) >= 30
# test for an improper coded backend
p4 = plot(sin(x), backend=DummyBackendNotOk, show=False)
assert p4.backend == DummyBackendNotOk
assert len(p4[0].get_data()[0]) >= 30
with raises(NotImplementedError):
p4.show()
with raises(NotImplementedError):
p4.save("test/path")
with raises(NotImplementedError):
p4._backend.close()
def test_custom_coloring():
x = Symbol('x')
y = Symbol('y')
plot(cos(x), line_color=lambda a: a)
plot(cos(x), line_color=1)
plot(cos(x), line_color="r")
plot_parametric(cos(x), sin(x), line_color=lambda a: a)
plot_parametric(cos(x), sin(x), line_color=1)
plot_parametric(cos(x), sin(x), line_color="r")
plot3d_parametric_line(cos(x), sin(x), x, line_color=lambda a: a)
plot3d_parametric_line(cos(x), sin(x), x, line_color=1)
plot3d_parametric_line(cos(x), sin(x), x, line_color="r")
plot3d_parametric_surface(cos(x + y), sin(x - y), x - y,
(x, -5, 5), (y, -5, 5),
surface_color=lambda a, b: a**2 + b**2)
plot3d_parametric_surface(cos(x + y), sin(x - y), x - y,
(x, -5, 5), (y, -5, 5),
surface_color=1)
plot3d_parametric_surface(cos(x + y), sin(x - y), x - y,
(x, -5, 5), (y, -5, 5),
surface_color="r")
plot3d(x*y, (x, -5, 5), (y, -5, 5),
surface_color=lambda a, b: a**2 + b**2)
plot3d(x*y, (x, -5, 5), (y, -5, 5), surface_color=1)
plot3d(x*y, (x, -5, 5), (y, -5, 5), surface_color="r")
|
f82c23ba9df7cad716c69e8306ab0be8e4d2f7d9ec32021354eadb0a3b921ab4 | #!/usr/bin/env python
"""Distutils based setup script for SymPy.
This uses Distutils (https://python.org/sigs/distutils-sig/) the standard
python mechanism for installing packages. Optionally, you can use
Setuptools (https://setuptools.readthedocs.io/en/latest/)
to automatically handle dependencies. For the easiest installation
just type the command (you'll probably need root privileges for that):
python setup.py install
This will install the library in the default location. For instructions on
how to customize the install procedure read the output of:
python setup.py --help install
In addition, there are some other commands:
python setup.py clean -> will clean all trash (*.pyc and stuff)
python setup.py test -> will run the complete test suite
python setup.py bench -> will run the complete benchmark suite
python setup.py audit -> will run pyflakes checker on source code
To get a full list of available commands, read the output of:
python setup.py --help-commands
Or, if all else fails, feel free to write to the sympy list at
[email protected] and ask for help.
"""
import sys
import os
import shutil
import glob
import subprocess
from distutils.command.sdist import sdist
min_mpmath_version = '0.19'
# This directory
dir_setup = os.path.dirname(os.path.realpath(__file__))
extra_kwargs = {}
try:
from setuptools import setup, Command
extra_kwargs['zip_safe'] = False
extra_kwargs['entry_points'] = {
'console_scripts': [
'isympy = isympy:main',
]
}
except ImportError:
from distutils.core import setup, Command
extra_kwargs['scripts'] = ['bin/isympy']
# handle mpmath deps in the hard way:
from sympy.external.importtools import version_tuple
try:
import mpmath
if version_tuple(mpmath.__version__) < version_tuple(min_mpmath_version):
raise ImportError
except ImportError:
print("Please install the mpmath package with a version >= %s"
% min_mpmath_version)
sys.exit(-1)
if sys.version_info < (3, 7):
print("SymPy requires Python 3.7 or newer. Python %d.%d detected"
% sys.version_info[:2])
sys.exit(-1)
# Check that this list is uptodate against the result of the command:
# python bin/generate_module_list.py
modules = [
'sympy.algebras',
'sympy.assumptions',
'sympy.assumptions.handlers',
'sympy.assumptions.predicates',
'sympy.assumptions.relation',
'sympy.benchmarks',
'sympy.calculus',
'sympy.categories',
'sympy.codegen',
'sympy.combinatorics',
'sympy.concrete',
'sympy.core',
'sympy.core.benchmarks',
'sympy.crypto',
'sympy.diffgeom',
'sympy.discrete',
'sympy.external',
'sympy.functions',
'sympy.functions.combinatorial',
'sympy.functions.elementary',
'sympy.functions.elementary.benchmarks',
'sympy.functions.special',
'sympy.functions.special.benchmarks',
'sympy.geometry',
'sympy.holonomic',
'sympy.integrals',
'sympy.integrals.benchmarks',
'sympy.integrals.rubi',
'sympy.integrals.rubi.parsetools',
'sympy.integrals.rubi.rubi_tests',
'sympy.integrals.rubi.rules',
'sympy.interactive',
'sympy.liealgebras',
'sympy.logic',
'sympy.logic.algorithms',
'sympy.logic.utilities',
'sympy.matrices',
'sympy.matrices.benchmarks',
'sympy.matrices.expressions',
'sympy.multipledispatch',
'sympy.ntheory',
'sympy.parsing',
'sympy.parsing.autolev',
'sympy.parsing.autolev._antlr',
'sympy.parsing.c',
'sympy.parsing.fortran',
'sympy.parsing.latex',
'sympy.parsing.latex._antlr',
'sympy.physics',
'sympy.physics.continuum_mechanics',
'sympy.physics.control',
'sympy.physics.hep',
'sympy.physics.mechanics',
'sympy.physics.optics',
'sympy.physics.quantum',
'sympy.physics.units',
'sympy.physics.units.definitions',
'sympy.physics.units.systems',
'sympy.physics.vector',
'sympy.plotting',
'sympy.plotting.intervalmath',
'sympy.plotting.pygletplot',
'sympy.polys',
'sympy.polys.agca',
'sympy.polys.benchmarks',
'sympy.polys.domains',
'sympy.polys.matrices',
'sympy.polys.numberfields',
'sympy.printing',
'sympy.printing.pretty',
'sympy.sandbox',
'sympy.series',
'sympy.series.benchmarks',
'sympy.sets',
'sympy.sets.handlers',
'sympy.simplify',
'sympy.solvers',
'sympy.solvers.benchmarks',
'sympy.solvers.diophantine',
'sympy.solvers.ode',
'sympy.stats',
'sympy.stats.sampling',
'sympy.strategies',
'sympy.strategies.branch',
'sympy.tensor',
'sympy.tensor.array',
'sympy.tensor.array.expressions',
'sympy.testing',
'sympy.unify',
'sympy.utilities',
'sympy.utilities._compilation',
'sympy.utilities.mathml',
'sympy.vector',
]
class audit(Command):
"""Audits SymPy's source code for following issues:
- Names which are used but not defined or used before they are defined.
- Names which are redefined without having been used.
"""
description = "Audit SymPy source with PyFlakes"
user_options = []
def initialize_options(self):
self.all = None
def finalize_options(self):
pass
def run(self):
try:
import pyflakes.scripts.pyflakes as flakes
except ImportError:
print("In order to run the audit, you need to have PyFlakes installed.")
sys.exit(-1)
dirs = (os.path.join(*d) for d in (m.split('.') for m in modules))
warns = 0
for dir in dirs:
for filename in os.listdir(dir):
if filename.endswith('.py') and filename != '__init__.py':
warns += flakes.checkPath(os.path.join(dir, filename))
if warns > 0:
print("Audit finished with total %d warnings" % warns)
class clean(Command):
"""Cleans *.pyc and debian trashs, so you should get the same copy as
is in the VCS.
"""
description = "remove build files"
user_options = [("all", "a", "the same")]
def initialize_options(self):
self.all = None
def finalize_options(self):
pass
def run(self):
curr_dir = os.getcwd()
for root, dirs, files in os.walk(dir_setup):
for file in files:
if file.endswith('.pyc') and os.path.isfile:
os.remove(os.path.join(root, file))
os.chdir(dir_setup)
names = ["python-build-stamp-2.4", "MANIFEST", "build",
"dist", "doc/_build", "sample.tex"]
for f in names:
if os.path.isfile(f):
os.remove(f)
elif os.path.isdir(f):
shutil.rmtree(f)
for name in glob.glob(os.path.join(dir_setup, "doc", "src", "modules",
"physics", "vector", "*.pdf")):
if os.path.isfile(name):
os.remove(name)
os.chdir(curr_dir)
class test_sympy(Command):
"""Runs all tests under the sympy/ folder
"""
description = "run all tests and doctests; also see bin/test and bin/doctest"
user_options = [] # distutils complains if this is not here.
def __init__(self, *args):
self.args = args[0] # so we can pass it to other classes
Command.__init__(self, *args)
def initialize_options(self): # distutils wants this
pass
def finalize_options(self): # this too
pass
def run(self):
from sympy.utilities import runtests
runtests.run_all_tests()
class run_benchmarks(Command):
"""Runs all SymPy benchmarks"""
description = "run all benchmarks"
user_options = [] # distutils complains if this is not here.
def __init__(self, *args):
self.args = args[0] # so we can pass it to other classes
Command.__init__(self, *args)
def initialize_options(self): # distutils wants this
pass
def finalize_options(self): # this too
pass
# we use py.test like architecture:
#
# o collector -- collects benchmarks
# o runner -- executes benchmarks
# o presenter -- displays benchmarks results
#
# this is done in sympy.utilities.benchmarking on top of py.test
def run(self):
from sympy.utilities import benchmarking
benchmarking.main(['sympy'])
class antlr(Command):
"""Generate code with antlr4"""
description = "generate parser code from antlr grammars"
user_options = [] # distutils complains if this is not here.
def __init__(self, *args):
self.args = args[0] # so we can pass it to other classes
Command.__init__(self, *args)
def initialize_options(self): # distutils wants this
pass
def finalize_options(self): # this too
pass
def run(self):
from sympy.parsing.latex._build_latex_antlr import build_parser
if not build_parser():
sys.exit(-1)
class sdist_sympy(sdist):
def run(self):
# Fetch git commit hash and write down to commit_hash.txt before
# shipped in tarball.
commit_hash = None
commit_hash_filepath = 'doc/commit_hash.txt'
try:
commit_hash = \
subprocess.check_output(['git', 'rev-parse', 'HEAD'])
commit_hash = commit_hash.decode('ascii')
commit_hash = commit_hash.rstrip()
print('Commit hash found : {}.'.format(commit_hash))
print('Writing it to {}.'.format(commit_hash_filepath))
except:
pass
if commit_hash:
with open(commit_hash_filepath, 'w') as f:
f.write(commit_hash)
super(sdist_sympy, self).run()
try:
os.remove(commit_hash_filepath)
print(
'Successfully removed temporary file {}.'
.format(commit_hash_filepath))
except OSError as e:
print("Error deleting %s - %s." % (e.filename, e.strerror))
# Check that this list is uptodate against the result of the command:
# python bin/generate_test_list.py
tests = [
'sympy.algebras.tests',
'sympy.assumptions.tests',
'sympy.calculus.tests',
'sympy.categories.tests',
'sympy.codegen.tests',
'sympy.combinatorics.tests',
'sympy.concrete.tests',
'sympy.core.tests',
'sympy.crypto.tests',
'sympy.diffgeom.tests',
'sympy.discrete.tests',
'sympy.external.tests',
'sympy.functions.combinatorial.tests',
'sympy.functions.elementary.tests',
'sympy.functions.special.tests',
'sympy.geometry.tests',
'sympy.holonomic.tests',
'sympy.integrals.rubi.parsetools.tests',
'sympy.integrals.rubi.rubi_tests.tests',
'sympy.integrals.rubi.tests',
'sympy.integrals.tests',
'sympy.interactive.tests',
'sympy.liealgebras.tests',
'sympy.logic.tests',
'sympy.matrices.expressions.tests',
'sympy.matrices.tests',
'sympy.multipledispatch.tests',
'sympy.ntheory.tests',
'sympy.parsing.tests',
'sympy.physics.continuum_mechanics.tests',
'sympy.physics.control.tests',
'sympy.physics.hep.tests',
'sympy.physics.mechanics.tests',
'sympy.physics.optics.tests',
'sympy.physics.quantum.tests',
'sympy.physics.tests',
'sympy.physics.units.tests',
'sympy.physics.vector.tests',
'sympy.plotting.intervalmath.tests',
'sympy.plotting.pygletplot.tests',
'sympy.plotting.tests',
'sympy.polys.agca.tests',
'sympy.polys.domains.tests',
'sympy.polys.matrices.tests',
'sympy.polys.numberfields.tests',
'sympy.polys.tests',
'sympy.printing.pretty.tests',
'sympy.printing.tests',
'sympy.sandbox.tests',
'sympy.series.tests',
'sympy.sets.tests',
'sympy.simplify.tests',
'sympy.solvers.diophantine.tests',
'sympy.solvers.ode.tests',
'sympy.solvers.tests',
'sympy.stats.sampling.tests',
'sympy.stats.tests',
'sympy.strategies.branch.tests',
'sympy.strategies.tests',
'sympy.tensor.array.expressions.tests',
'sympy.tensor.array.tests',
'sympy.tensor.tests',
'sympy.testing.tests',
'sympy.unify.tests',
'sympy.utilities._compilation.tests',
'sympy.utilities.tests',
'sympy.vector.tests',
]
with open(os.path.join(dir_setup, 'sympy', 'release.py')) as f:
# Defines __version__
exec(f.read())
if __name__ == '__main__':
setup(name='sympy',
version=__version__,
description='Computer algebra system (CAS) in Python',
author='SymPy development team',
author_email='[email protected]',
license='BSD',
keywords="Math CAS",
url='https://sympy.org',
py_modules=['isympy'],
packages=['sympy'] + modules + tests,
ext_modules=[],
package_data={
'sympy.utilities.mathml': ['data/*.xsl'],
'sympy.logic.benchmarks': ['input/*.cnf'],
'sympy.parsing.autolev': [
'*.g4', 'test-examples/*.al', 'test-examples/*.py',
'test-examples/pydy-example-repo/*.al',
'test-examples/pydy-example-repo/*.py',
'test-examples/README.txt',
],
'sympy.parsing.latex': ['*.txt', '*.g4'],
'sympy.integrals.rubi.parsetools': ['header.py.txt'],
'sympy.plotting.tests': ['test_region_*.png'],
},
data_files=[('share/man/man1', ['doc/man/isympy.1'])],
cmdclass={'test': test_sympy,
'bench': run_benchmarks,
'clean': clean,
'audit': audit,
'antlr': antlr,
'sdist': sdist_sympy,
},
python_requires='>=3.7',
classifiers=[
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Scientific/Engineering :: Physics',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
],
install_requires=[
'mpmath>=%s' % min_mpmath_version,
],
**extra_kwargs
)
|
f0b129fa8ad93769fc898003a3dc738ae9f25e1e42770c595c9a5ddad758df51 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A tool to generate AUTHORS. We started tracking authors before moving to git,
so we have to do some manual rearrangement of the git history authors in order
to get the order in AUTHORS. bin/mailmap_check.py should be run before
committing the results.
See here for instructions on using this script:
https://github.com/sympy/sympy/wiki/Development-workflow#update-mailmap
"""
from __future__ import unicode_literals
from __future__ import print_function
import sys
import os
from pathlib import Path
from subprocess import run, PIPE
from collections import OrderedDict, defaultdict
from argparse import ArgumentParser
if sys.version_info < (3, 7):
sys.exit("This script requires Python 3.7 or newer")
def sympy_dir():
return Path(__file__).resolve().parent.parent
# put sympy on the path
sys.path.insert(0, str(sympy_dir()))
import sympy
from sympy.utilities.misc import filldedent
from sympy.external.importtools import version_tuple
def main(*args):
parser = ArgumentParser(description='Update the .mailmap and/or AUTHORS files')
parser.add_argument('--update-authors', action='store_true',
help=filldedent("""
Also update the AUTHORS file. Note that it
should only necessary for the release manager to do this as part of
the release process for SymPy."""))
args = parser.parse_args(args)
if not check_git_version():
return 1
# find who git knows ahout
try:
git_people = get_authors_from_git()
except AssertionError as msg:
print(red(msg))
return 1
lines_mailmap = read_lines(mailmap_path())
def key(line):
# return lower case first address on line or
# raise an error if not an entry
if '#' in line:
line = line.split('#')[0]
L, R = line.count("<"), line.count(">")
assert L == R and L in (1, 2)
return line.split(">", 1)[0].split("<")[1].lower()
who = OrderedDict()
for i, line in enumerate(lines_mailmap):
try:
who.setdefault(key(line), []).append(line)
except AssertionError:
who[i] = [line]
problems = False
missing = False
ambiguous = False
dups = defaultdict(list)
for person in git_people:
email = key(person)
dups[email].append(person)
if email not in who:
print(red("This author is not included in the .mailmap file:"))
print(person)
missing = True
elif not any(p.startswith(person) for p in who[email]):
print(red("Ambiguous names in .mailmap"))
print(red("This email address appears for multiple entries:"))
print('Person:', person)
print('Mailmap entries:')
for line in who[email]:
print(line)
ambiguous = True
if missing:
print(red(filldedent("""
The .mailmap file needs to be updated because there are commits with
unrecognised author/email metadata.
""")))
problems = True
if ambiguous:
print(red(filldedent("""
Lines should be added to .mailmap to indicate the correct name and
email aliases for all commits.
""")))
problems = True
for email, commitauthors in dups.items():
if len(commitauthors) > 2:
print(red(filldedent("""
The following commits are recorded with different metadata but the
same/ambiguous email address. The .mailmap file will need to be
updated.""")))
for author in commitauthors:
print(author)
problems = True
lines_mailmap_sorted = sort_lines_mailmap(lines_mailmap)
write_lines(mailmap_path(), lines_mailmap_sorted)
if lines_mailmap_sorted != lines_mailmap:
problems = True
print(red("The mailmap file was reordered"))
if problems:
print(red(filldedent("""
For instructions on updating the .mailmap file see:
https://github.com/sympy/sympy/wiki/Development-workflow#update-mailmap""")))
else:
print(green("No changes needed in .mailmap"))
# Check if changes to AUTHORS file are also needed
lines_authors = make_authors_file_lines(git_people)
old_lines_authors = read_lines(authors_path())
update_authors_file(lines_authors, old_lines_authors, args.update_authors)
return int(problems)
def update_authors_file(lines, old_lines, update_yesno):
if old_lines == lines:
print(green('No changes needed in AUTHORS.'))
return 0
# Actually write changes to the file?
if update_yesno:
write_lines(authors_path(), lines)
print(red("Changes were made in the authors file"))
# check for new additions
new_authors = []
for i in sorted(set(lines) - set(old_lines)):
try:
author_name(i)
new_authors.append(i)
except AssertionError:
continue
if new_authors:
if update_yesno:
print(yellow("The following authors were added to AUTHORS."))
else:
print(green(filldedent("""
The following authors will be added to the AUTHORS file at the
time of the next SymPy release.""")))
print()
for i in sorted(new_authors, key=lambda x: x.lower()):
print('\t%s' % i)
def check_git_version():
# check git version
minimal = '1.8.4.2'
git_ver = run(['git', '--version'], stdout=PIPE, encoding='utf-8').stdout[12:]
if version_tuple(git_ver) < version_tuple(minimal):
print(yellow("Please use a git version >= %s" % minimal))
return False
else:
return True
def authors_path():
return sympy_dir() / 'AUTHORS'
def mailmap_path():
return sympy_dir() / '.mailmap'
def red(text):
return "\033[31m%s\033[0m" % text
def yellow(text):
return "\033[33m%s\033[0m" % text
def green(text):
return "\033[32m%s\033[0m" % text
def author_name(line):
assert line.count("<") == line.count(">") == 1
assert line.endswith(">")
return line.split("<", 1)[0].strip()
def get_authors_from_git():
git_command = ["git", "log", "--topo-order", "--reverse", "--format=%aN <%aE>"]
git_people = run(git_command, stdout=PIPE, encoding='utf-8').stdout.strip().split("\n")
# remove duplicates, keeping the original order
git_people = list(OrderedDict.fromkeys(git_people))
# Do the few changes necessary in order to reproduce AUTHORS:
def move(l, i1, i2, who):
x = l.pop(i1)
# this will fail if the .mailmap is not right
assert who == author_name(x), \
'%s was not found at line %i' % (who, i1)
l.insert(i2, x)
move(git_people, 2, 0, 'Ondřej Čertík')
move(git_people, 42, 1, 'Fabian Pedregosa')
move(git_people, 22, 2, 'Jurjen N.E. Bos')
git_people.insert(4, "*Marc-Etienne M.Leveille <[email protected]>")
move(git_people, 10, 5, 'Brian Jorgensen')
git_people.insert(11, "*Ulrich Hecht <[email protected]>")
# this will fail if the .mailmap is not right
assert 'Kirill Smelkov' == author_name(git_people.pop(12)
), 'Kirill Smelkov was not found at line 12'
move(git_people, 12, 32, 'Sebastian Krämer')
move(git_people, 227, 35, 'Case Van Horsen')
git_people.insert(43, "*Dan <[email protected]>")
move(git_people, 57, 59, 'Aaron Meurer')
move(git_people, 58, 57, 'Andrew Docherty')
move(git_people, 67, 66, 'Chris Smith')
move(git_people, 79, 76, 'Kevin Goodsell')
git_people.insert(84, "*Chu-Ching Huang <[email protected]>")
move(git_people, 93, 92, 'James Pearson')
# this will fail if the .mailmap is not right
assert 'Sergey B Kirpichev' == author_name(git_people.pop(226)
), 'Sergey B Kirpichev was not found at line 226.'
index = git_people.index(
"azure-pipelines[bot] " +
"<azure-pipelines[bot]@users.noreply.github.com>")
git_people.pop(index)
index = git_people.index(
"whitesource-bolt-for-github[bot] " +
"<whitesource-bolt-for-github[bot]@users.noreply.github.com>")
git_people.pop(index)
return git_people
def make_authors_file_lines(git_people):
# define new lines for the file
header = filldedent("""
All people who contributed to SymPy by sending at least a patch or
more (in the order of the date of their first contribution), except
those who explicitly didn't want to be mentioned. People with a * next
to their names are not found in the metadata of the git history. This
file is generated automatically by running `./bin/authors_update.py`.
""").lstrip()
header_extra = f"There are a total of {len(git_people)} authors."""
lines = header.splitlines()
lines.append('')
lines.append(header_extra)
lines.append('')
lines.extend(git_people)
return lines
def sort_lines_mailmap(lines):
for n, line in enumerate(lines):
if not line.startswith('#'):
header_end = n
break
header = lines[:header_end]
mailmap_lines = lines[header_end:]
return header + sorted(mailmap_lines)
def read_lines(path):
with open(path) as fin:
return [line.strip() for line in fin.readlines()]
def write_lines(path, lines):
with open(path, 'w') as fout:
fout.write('\n'.join(lines))
fout.write('\n')
if __name__ == "__main__":
import sys
sys.exit(main(*sys.argv[1:]))
|
3f589029f5e5ec8bade99e58f7b4261abfd4aa2019eaa47e7a844cb5869c19f0 | """
This module exports all latin and greek letters as Symbols, so you can
conveniently do
>>> from sympy.abc import x, y
instead of the slightly more clunky-looking
>>> from sympy import symbols
>>> x, y = symbols('x y')
Caveats
=======
1. As of the time of writing this, the names ``O``, ``S``, ``I``, ``N``,
``E``, and ``Q`` are colliding with names defined in SymPy. If you import them
from both ``sympy.abc`` and ``sympy``, the second import will "win".
This is an issue only for * imports, which should only be used for short-lived
code such as interactive sessions and throwaway scripts that do not survive
until the next SymPy upgrade, where ``sympy`` may contain a different set of
names.
2. This module does not define symbol names on demand, i.e.
``from sympy.abc import foo`` will be reported as an error because
``sympy.abc`` does not contain the name ``foo``. To get a symbol named ``foo``,
you still need to use ``Symbol('foo')`` or ``symbols('foo')``.
You can freely mix usage of ``sympy.abc`` and ``Symbol``/``symbols``, though
sticking with one and only one way to get the symbols does tend to make the code
more readable.
The module also defines some special names to help detect which names clash
with the default SymPy namespace.
``_clash1`` defines all the single letter variables that clash with
SymPy objects; ``_clash2`` defines the multi-letter clashing symbols;
and ``_clash`` is the union of both. These can be passed for ``locals``
during sympification if one desires Symbols rather than the non-Symbol
objects for those names.
Examples
========
>>> from sympy import S
>>> from sympy.abc import _clash1, _clash2, _clash
>>> S("Q & C", locals=_clash1)
C & Q
>>> S('pi(x)', locals=_clash2)
pi(x)
>>> S('pi(C, Q)', locals=_clash)
pi(C, Q)
"""
from typing import Any, Dict as tDict
import string
from .core import Symbol, symbols
from .core.alphabets import greeks
from sympy.parsing.sympy_parser import null
##### Symbol definitions #####
# Implementation note: The easiest way to avoid typos in the symbols()
# parameter is to copy it from the left-hand side of the assignment.
a, b, c, d, e, f, g, h, i, j = symbols('a, b, c, d, e, f, g, h, i, j')
k, l, m, n, o, p, q, r, s, t = symbols('k, l, m, n, o, p, q, r, s, t')
u, v, w, x, y, z = symbols('u, v, w, x, y, z')
A, B, C, D, E, F, G, H, I, J = symbols('A, B, C, D, E, F, G, H, I, J')
K, L, M, N, O, P, Q, R, S, T = symbols('K, L, M, N, O, P, Q, R, S, T')
U, V, W, X, Y, Z = symbols('U, V, W, X, Y, Z')
alpha, beta, gamma, delta = symbols('alpha, beta, gamma, delta')
epsilon, zeta, eta, theta = symbols('epsilon, zeta, eta, theta')
iota, kappa, lamda, mu = symbols('iota, kappa, lamda, mu')
nu, xi, omicron, pi = symbols('nu, xi, omicron, pi')
rho, sigma, tau, upsilon = symbols('rho, sigma, tau, upsilon')
phi, chi, psi, omega = symbols('phi, chi, psi, omega')
##### Clashing-symbols diagnostics #####
# We want to know which names in SymPy collide with those in here.
# This is mostly for diagnosing SymPy's namespace during SymPy development.
_latin = list(string.ascii_letters)
# QOSINE should not be imported as they clash; gamma, pi and zeta clash, too
_greek = list(greeks) # make a copy, so we can mutate it
# Note: We import lamda since lambda is a reserved keyword in Python
_greek.remove("lambda")
_greek.append("lamda")
ns: tDict[str, Any] = {}
exec('from sympy import *', ns)
_clash1: tDict[str, Any] = {}
_clash2: tDict[str, Any] = {}
while ns:
_k, _ = ns.popitem()
if _k in _greek:
_clash2[_k] = null
_greek.remove(_k)
elif _k in _latin:
_clash1[_k] = null
_latin.remove(_k)
_clash = {}
_clash.update(_clash1)
_clash.update(_clash2)
del _latin, _greek, Symbol, _k, null
|
c9c4bf20298628fd5b77622b945e19bca4bd723fccf0644ed15c1cd204eeb9bd | #
# SymPy documentation build configuration file, created by
# sphinx-quickstart.py on Sat Mar 22 19:34:32 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
#
# All configuration values have a default value; values that are commented out
# serve to show the default value.
import sys
import inspect
import os
import subprocess
from datetime import datetime
# Make sure we import sympy from git
sys.path.insert(0, os.path.abspath('../..'))
import sympy
# If your extensions are in another directory, add it here.
sys.path = ['ext'] + sys.path
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.addons.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.linkcode', 'sphinx_math_dollar',
'sphinx.ext.mathjax', 'numpydoc', 'sympylive', 'sphinx_reredirects',
'sphinx.ext.graphviz', 'matplotlib.sphinxext.plot_directive',
'myst_parser'
]
redirects = {
"install.rst": "guides/getting_started/install.html",
"documentation-style-guide.rst": "guides/contributing/documentation-style-guide.html",
"gotchas.rst": "explanation/gotchas.html",
"special_topics/classification.rst": "explanation/classification.html",
"special_topics/finite_diff_derivatives.rst": "explanation/finite_diff_derivatives.html",
"special_topics/intro.rst": "explanation/index.html",
"special_topics/index.rst": "explanation/index.html",
"modules/index.rst": "reference/public/index.html",
"modules/physics/index.rst": "reference/physics/index.html",
}
# Use this to use pngmath instead
#extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode', 'sphinx.ext.pngmath', ]
# Enable warnings for all bad cross references. These are turned into errors
# with the -W flag in the Makefile.
nitpicky = True
nitpick_ignore = [
('py:class', 'sympy.logic.boolalg.Boolean')
]
# To stop docstrings inheritance.
autodoc_inherit_docstrings = False
# See https://www.sympy.org/sphinx-math-dollar/
mathjax3_config = {
"tex": {
"inlineMath": [['\\(', '\\)']],
"displayMath": [["\\[", "\\]"]],
}
}
# Myst configuration (for .md files). See
# https://myst-parser.readthedocs.io/en/latest/syntax/optional.html
myst_enable_extensions = ["dollarmath", "linkify"]
myst_heading_anchors = 2
# myst_update_mathjax = False
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
suppress_warnings = ['ref.citation', 'ref.footnote']
# General substitutions.
project = 'SymPy'
copyright = '{} SymPy Development Team'.format(datetime.utcnow().year)
# The default replacements for |version| and |release|, also used in various
# other places throughout the built documents.
#
# The short X.Y version.
version = sympy.__version__
# The full version, including alpha/beta/rc tags.
release = version
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# Don't show the source code hyperlinks when using matplotlib plot directive.
plot_html_show_source_link = False
# Options for HTML output
# -----------------------
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
html_style = 'default.css'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# was classic
html_theme = "classic"
html_logo = '_static/sympylogo.png'
html_favicon = '../_build/logo/sympy-notailtext-favicon.ico'
# See http://www.sphinx-doc.org/en/master/theming.html#builtin-themes
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Content template for the index page.
#html_index = ''
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
html_domain_indices = ['py-modindex']
# If true, the reST sources are included in the HTML build as _sources/<name>.
#html_copy_source = True
# Output file base name for HTML help builder.
htmlhelp_basename = 'SymPydoc'
language = 'en'
# Options for LaTeX output
# ------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual], toctree_only).
# toctree_only is set to True so that the start file document itself is not included in the
# output, only the documents referenced by it via TOC trees. The extra stuff in the master
# document is intended to show up in the HTML, but doesn't really belong in the LaTeX output.
latex_documents = [('index', 'sympy-%s.tex' % release, 'SymPy Documentation',
'SymPy Development Team', 'manual', True)]
# Additional stuff for the LaTeX preamble.
# Tweaked to work with XeTeX.
latex_elements = {
'babel': '',
'fontenc': r'''
% Define version of \LaTeX that is usable in math mode
\let\OldLaTeX\LaTeX
\renewcommand{\LaTeX}{\text{\OldLaTeX}}
\usepackage{bm}
\usepackage{amssymb}
\usepackage{fontspec}
\usepackage[english]{babel}
\defaultfontfeatures{Mapping=tex-text}
\setmainfont{DejaVu Serif}
\setsansfont{DejaVu Sans}
\setmonofont{DejaVu Sans Mono}
''',
'fontpkg': '',
'inputenc': '',
'utf8extra': '',
'preamble': r'''
'''
}
# SymPy logo on title page
html_logo = '_static/sympylogo.png'
latex_logo = '_static/sympylogo_big.png'
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# Show page numbers next to internal references
latex_show_pagerefs = True
# We use False otherwise the module index gets generated twice.
latex_use_modindex = False
default_role = 'math'
pngmath_divpng_args = ['-gamma 1.5', '-D 110']
# Note, this is ignored by the mathjax extension
# Any \newcommand should be defined in the file
pngmath_latex_preamble = '\\usepackage{amsmath}\n' \
'\\usepackage{bm}\n' \
'\\usepackage{amsfonts}\n' \
'\\usepackage{amssymb}\n' \
'\\setlength{\\parindent}{0pt}\n'
texinfo_documents = [
(master_doc, 'sympy', 'SymPy Documentation', 'SymPy Development Team',
'SymPy', 'Computer algebra system (CAS) in Python', 'Programming', 1),
]
# Use svg for graphviz
graphviz_output_format = 'svg'
# Requried for linkcode extension.
# Get commit hash from the external file.
commit_hash_filepath = '../commit_hash.txt'
commit_hash = None
if os.path.isfile(commit_hash_filepath):
with open(commit_hash_filepath) as f:
commit_hash = f.readline()
# Get commit hash from the external file.
if not commit_hash:
try:
commit_hash = subprocess.check_output(['git', 'rev-parse', 'HEAD'])
commit_hash = commit_hash.decode('ascii')
commit_hash = commit_hash.rstrip()
except:
import warnings
warnings.warn(
"Failed to get the git commit hash as the command " \
"'git rev-parse HEAD' is not working. The commit hash will be " \
"assumed as the SymPy master, but the lines may be misleading " \
"or nonexistent as it is not the correct branch the doc is " \
"built with. Check your installation of 'git' if you want to " \
"resolve this warning.")
commit_hash = 'master'
fork = 'sympy'
blobpath = \
"https://github.com/{}/sympy/blob/{}/sympy/".format(fork, commit_hash)
def linkcode_resolve(domain, info):
"""Determine the URL corresponding to Python object."""
if domain != 'py':
return
modname = info['module']
fullname = info['fullname']
submod = sys.modules.get(modname)
if submod is None:
return
obj = submod
for part in fullname.split('.'):
try:
obj = getattr(obj, part)
except Exception:
return
# strip decorators, which would resolve to the source of the decorator
# possibly an upstream bug in getsourcefile, bpo-1764286
try:
unwrap = inspect.unwrap
except AttributeError:
pass
else:
obj = unwrap(obj)
try:
fn = inspect.getsourcefile(obj)
except Exception:
fn = None
if not fn:
return
try:
source, lineno = inspect.getsourcelines(obj)
except Exception:
lineno = None
if lineno:
linespec = "#L%d-L%d" % (lineno, lineno + len(source) - 1)
else:
linespec = ""
fn = os.path.relpath(fn, start=os.path.dirname(sympy.__file__))
return blobpath + fn + linespec
|
b103de241b7e9ee0d7c41cd26d30ee18b7d62b1a3afe10f802c1223a9a44e5e9 | import random
import itertools
from typing import (Sequence as tSequence, Union as tUnion, List as tList,
Tuple as tTuple, Set as tSet)
from sympy.concrete.summations import Sum
from sympy.core.add import Add
from sympy.core.basic import Basic
from sympy.core.cache import cacheit
from sympy.core.containers import Tuple
from sympy.core.expr import Expr
from sympy.core.function import (Function, Lambda)
from sympy.core.mul import Mul
from sympy.core.numbers import (Integer, Rational, igcd, oo, pi)
from sympy.core.relational import (Eq, Ge, Gt, Le, Lt, Ne)
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, Symbol)
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.integers import ceiling
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.special.gamma_functions import gamma
from sympy.logic.boolalg import (And, Not, Or)
from sympy.matrices.common import NonSquareMatrixError
from sympy.matrices.dense import (Matrix, eye, ones, zeros)
from sympy.matrices.expressions.blockmatrix import BlockMatrix
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.special import Identity
from sympy.matrices.immutable import ImmutableMatrix
from sympy.sets.conditionset import ConditionSet
from sympy.sets.contains import Contains
from sympy.sets.fancysets import Range
from sympy.sets.sets import (FiniteSet, Intersection, Interval, Set, Union)
from sympy.solvers.solveset import linsolve
from sympy.tensor.indexed import (Indexed, IndexedBase)
from sympy.core.relational import Relational
from sympy.logic.boolalg import Boolean
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.utilities.iterables import strongly_connected_components
from sympy.stats.joint_rv import JointDistribution
from sympy.stats.joint_rv_types import JointDistributionHandmade
from sympy.stats.rv import (RandomIndexedSymbol, random_symbols, RandomSymbol,
_symbol_converter, _value_check, pspace, given,
dependent, is_random, sample_iter, Distribution,
Density)
from sympy.stats.stochastic_process import StochasticPSpace
from sympy.stats.symbolic_probability import Probability, Expectation
from sympy.stats.frv_types import Bernoulli, BernoulliDistribution, FiniteRV
from sympy.stats.drv_types import Poisson, PoissonDistribution
from sympy.stats.crv_types import Normal, NormalDistribution, Gamma, GammaDistribution
from sympy.core.sympify import _sympify, sympify
EmptySet = S.EmptySet
__all__ = [
'StochasticProcess',
'DiscreteTimeStochasticProcess',
'DiscreteMarkovChain',
'TransitionMatrixOf',
'StochasticStateSpaceOf',
'GeneratorMatrixOf',
'ContinuousMarkovChain',
'BernoulliProcess',
'PoissonProcess',
'WienerProcess',
'GammaProcess'
]
@is_random.register(Indexed)
def _(x):
return is_random(x.base)
@is_random.register(RandomIndexedSymbol) # type: ignore
def _(x):
return True
def _set_converter(itr):
"""
Helper function for converting list/tuple/set to Set.
If parameter is not an instance of list/tuple/set then
no operation is performed.
Returns
=======
Set
The argument converted to Set.
Raises
======
TypeError
If the argument is not an instance of list/tuple/set.
"""
if isinstance(itr, (list, tuple, set)):
itr = FiniteSet(*itr)
if not isinstance(itr, Set):
raise TypeError("%s is not an instance of list/tuple/set."%(itr))
return itr
def _state_converter(itr: tSequence) -> tUnion[Tuple, Range]:
"""
Helper function for converting list/tuple/set/Range/Tuple/FiniteSet
to tuple/Range.
"""
itr_ret: tUnion[Tuple, Range]
if isinstance(itr, (Tuple, set, FiniteSet)):
itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr))
elif isinstance(itr, (list, tuple)):
# check if states are unique
if len(set(itr)) != len(itr):
raise ValueError('The state space must have unique elements.')
itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr))
elif isinstance(itr, Range):
# the only ordered set in SymPy I know of
# try to convert to tuple
try:
itr_ret = Tuple(*(sympify(i) if isinstance(i, str) else i for i in itr))
except (TypeError, ValueError):
itr_ret = itr
else:
raise TypeError("%s is not an instance of list/tuple/set/Range/Tuple/FiniteSet." % (itr))
return itr_ret
def _sym_sympify(arg):
"""
Converts an arbitrary expression to a type that can be used inside SymPy.
As generally strings are unwise to use in the expressions,
it returns the Symbol of argument if the string type argument is passed.
Parameters
=========
arg: The parameter to be converted to be used in SymPy.
Returns
=======
The converted parameter.
"""
if isinstance(arg, str):
return Symbol(arg)
else:
return _sympify(arg)
def _matrix_checks(matrix):
if not isinstance(matrix, (Matrix, MatrixSymbol, ImmutableMatrix)):
raise TypeError("Transition probabilities either should "
"be a Matrix or a MatrixSymbol.")
if matrix.shape[0] != matrix.shape[1]:
raise NonSquareMatrixError("%s is not a square matrix"%(matrix))
if isinstance(matrix, Matrix):
matrix = ImmutableMatrix(matrix.tolist())
return matrix
class StochasticProcess(Basic):
"""
Base class for all the stochastic processes whether
discrete or continuous.
Parameters
==========
sym: Symbol or str
state_space: Set
The state space of the stochastic process, by default S.Reals.
For discrete sets it is zero indexed.
See Also
========
DiscreteTimeStochasticProcess
"""
index_set = S.Reals
def __new__(cls, sym, state_space=S.Reals, **kwargs):
sym = _symbol_converter(sym)
state_space = _set_converter(state_space)
return Basic.__new__(cls, sym, state_space)
@property
def symbol(self):
return self.args[0]
@property
def state_space(self) -> tUnion[FiniteSet, Range]:
if not isinstance(self.args[1], (FiniteSet, Range)):
assert isinstance(self.args[1], Tuple)
return FiniteSet(*self.args[1])
return self.args[1]
def _deprecation_warn_distribution(self):
SymPyDeprecationWarning(
feature="Calling distribution with RandomIndexedSymbol",
useinstead="distribution with just timestamp as argument",
issue=20078,
deprecated_since_version="1.7.1"
).warn()
def distribution(self, key=None):
if key is None:
self._deprecation_warn_distribution()
return Distribution()
def density(self, x):
return Density()
def __call__(self, time):
"""
Overridden in ContinuousTimeStochasticProcess.
"""
raise NotImplementedError("Use [] for indexing discrete time stochastic process.")
def __getitem__(self, time):
"""
Overridden in DiscreteTimeStochasticProcess.
"""
raise NotImplementedError("Use () for indexing continuous time stochastic process.")
def probability(self, condition):
raise NotImplementedError()
def joint_distribution(self, *args):
"""
Computes the joint distribution of the random indexed variables.
Parameters
==========
args: iterable
The finite list of random indexed variables/the key of a stochastic
process whose joint distribution has to be computed.
Returns
=======
JointDistribution
The joint distribution of the list of random indexed variables.
An unevaluated object is returned if it is not possible to
compute the joint distribution.
Raises
======
ValueError: When the arguments passed are not of type RandomIndexSymbol
or Number.
"""
args = list(args)
for i, arg in enumerate(args):
if S(arg).is_Number:
if self.index_set.is_subset(S.Integers):
args[i] = self.__getitem__(arg)
else:
args[i] = self.__call__(arg)
elif not isinstance(arg, RandomIndexedSymbol):
raise ValueError("Expected a RandomIndexedSymbol or "
"key not %s"%(type(arg)))
if args[0].pspace.distribution == Distribution():
return JointDistribution(*args)
density = Lambda(tuple(args),
expr=Mul.fromiter(arg.pspace.process.density(arg) for arg in args))
return JointDistributionHandmade(density)
def expectation(self, condition, given_condition):
raise NotImplementedError("Abstract method for expectation queries.")
def sample(self):
raise NotImplementedError("Abstract method for sampling queries.")
class DiscreteTimeStochasticProcess(StochasticProcess):
"""
Base class for all discrete stochastic processes.
"""
def __getitem__(self, time):
"""
For indexing discrete time stochastic processes.
Returns
=======
RandomIndexedSymbol
"""
time = sympify(time)
if not time.is_symbol and time not in self.index_set:
raise IndexError("%s is not in the index set of %s"%(time, self.symbol))
idx_obj = Indexed(self.symbol, time)
pspace_obj = StochasticPSpace(self.symbol, self, self.distribution(time))
return RandomIndexedSymbol(idx_obj, pspace_obj)
class ContinuousTimeStochasticProcess(StochasticProcess):
"""
Base class for all continuous time stochastic process.
"""
def __call__(self, time):
"""
For indexing continuous time stochastic processes.
Returns
=======
RandomIndexedSymbol
"""
time = sympify(time)
if not time.is_symbol and time not in self.index_set:
raise IndexError("%s is not in the index set of %s"%(time, self.symbol))
func_obj = Function(self.symbol)(time)
pspace_obj = StochasticPSpace(self.symbol, self, self.distribution(time))
return RandomIndexedSymbol(func_obj, pspace_obj)
class TransitionMatrixOf(Boolean):
"""
Assumes that the matrix is the transition matrix
of the process.
"""
def __new__(cls, process, matrix):
if not isinstance(process, DiscreteMarkovChain):
raise ValueError("Currently only DiscreteMarkovChain "
"support TransitionMatrixOf.")
matrix = _matrix_checks(matrix)
return Basic.__new__(cls, process, matrix)
process = property(lambda self: self.args[0])
matrix = property(lambda self: self.args[1])
class GeneratorMatrixOf(TransitionMatrixOf):
"""
Assumes that the matrix is the generator matrix
of the process.
"""
def __new__(cls, process, matrix):
if not isinstance(process, ContinuousMarkovChain):
raise ValueError("Currently only ContinuousMarkovChain "
"support GeneratorMatrixOf.")
matrix = _matrix_checks(matrix)
return Basic.__new__(cls, process, matrix)
class StochasticStateSpaceOf(Boolean):
def __new__(cls, process, state_space):
if not isinstance(process, (DiscreteMarkovChain, ContinuousMarkovChain)):
raise ValueError("Currently only DiscreteMarkovChain and ContinuousMarkovChain "
"support StochasticStateSpaceOf.")
state_space = _state_converter(state_space)
if isinstance(state_space, Range):
ss_size = ceiling((state_space.stop - state_space.start) / state_space.step)
else:
ss_size = len(state_space)
state_index = Range(ss_size)
return Basic.__new__(cls, process, state_index)
process = property(lambda self: self.args[0])
state_index = property(lambda self: self.args[1])
class MarkovProcess(StochasticProcess):
"""
Contains methods that handle queries
common to Markov processes.
"""
@property
def number_of_states(self) -> tUnion[Integer, Symbol]:
"""
The number of states in the Markov Chain.
"""
return _sympify(self.args[2].shape[0]) # type: ignore
@property
def _state_index(self):
"""
Returns state index as Range.
"""
return self.args[1]
@classmethod
def _sanity_checks(cls, state_space, trans_probs):
# Try to never have None as state_space or trans_probs.
# This helps a lot if we get it done at the start.
if (state_space is None) and (trans_probs is None):
_n = Dummy('n', integer=True, nonnegative=True)
state_space = _state_converter(Range(_n))
trans_probs = _matrix_checks(MatrixSymbol('_T', _n, _n))
elif state_space is None:
trans_probs = _matrix_checks(trans_probs)
state_space = _state_converter(Range(trans_probs.shape[0]))
elif trans_probs is None:
state_space = _state_converter(state_space)
if isinstance(state_space, Range):
_n = ceiling((state_space.stop - state_space.start) / state_space.step)
else:
_n = len(state_space)
trans_probs = MatrixSymbol('_T', _n, _n)
else:
state_space = _state_converter(state_space)
trans_probs = _matrix_checks(trans_probs)
# Range object doesn't want to give a symbolic size
# so we do it ourselves.
if isinstance(state_space, Range):
ss_size = ceiling((state_space.stop - state_space.start) / state_space.step)
else:
ss_size = len(state_space)
if ss_size != trans_probs.shape[0]:
raise ValueError('The size of the state space and the number of '
'rows of the transition matrix must be the same.')
return state_space, trans_probs
def _extract_information(self, given_condition):
"""
Helper function to extract information, like,
transition matrix/generator matrix, state space, etc.
"""
if isinstance(self, DiscreteMarkovChain):
trans_probs = self.transition_probabilities
state_index = self._state_index
elif isinstance(self, ContinuousMarkovChain):
trans_probs = self.generator_matrix
state_index = self._state_index
if isinstance(given_condition, And):
gcs = given_condition.args
given_condition = S.true
for gc in gcs:
if isinstance(gc, TransitionMatrixOf):
trans_probs = gc.matrix
if isinstance(gc, StochasticStateSpaceOf):
state_index = gc.state_index
if isinstance(gc, Relational):
given_condition = given_condition & gc
if isinstance(given_condition, TransitionMatrixOf):
trans_probs = given_condition.matrix
given_condition = S.true
if isinstance(given_condition, StochasticStateSpaceOf):
state_index = given_condition.state_index
given_condition = S.true
return trans_probs, state_index, given_condition
def _check_trans_probs(self, trans_probs, row_sum=1):
"""
Helper function for checking the validity of transition
probabilities.
"""
if not isinstance(trans_probs, MatrixSymbol):
rows = trans_probs.tolist()
for row in rows:
if (sum(row) - row_sum) != 0:
raise ValueError("Values in a row must sum to %s. "
"If you are using Float or floats then please use Rational."%(row_sum))
def _work_out_state_index(self, state_index, given_condition, trans_probs):
"""
Helper function to extract state space if there
is a random symbol in the given condition.
"""
# if given condition is None, then there is no need to work out
# state_space from random variables
if given_condition != None:
rand_var = list(given_condition.atoms(RandomSymbol) -
given_condition.atoms(RandomIndexedSymbol))
if len(rand_var) == 1:
state_index = rand_var[0].pspace.set
# `not None` is `True`. So the old test fails for symbolic sizes.
# Need to build the statement differently.
sym_cond = not self.number_of_states.is_Integer
cond1 = not sym_cond and len(state_index) != trans_probs.shape[0]
if cond1:
raise ValueError("state space is not compatible with the transition probabilities.")
if not isinstance(trans_probs.shape[0], Symbol):
state_index = FiniteSet(*[i for i in range(trans_probs.shape[0])])
return state_index
@cacheit
def _preprocess(self, given_condition, evaluate):
"""
Helper function for pre-processing the information.
"""
is_insufficient = False
if not evaluate: # avoid pre-processing if the result is not to be evaluated
return (True, None, None, None)
# extracting transition matrix and state space
trans_probs, state_index, given_condition = self._extract_information(given_condition)
# given_condition does not have sufficient information
# for computations
if trans_probs is None or \
given_condition is None:
is_insufficient = True
else:
# checking transition probabilities
if isinstance(self, DiscreteMarkovChain):
self._check_trans_probs(trans_probs, row_sum=1)
elif isinstance(self, ContinuousMarkovChain):
self._check_trans_probs(trans_probs, row_sum=0)
# working out state space
state_index = self._work_out_state_index(state_index, given_condition, trans_probs)
return is_insufficient, trans_probs, state_index, given_condition
def replace_with_index(self, condition):
if isinstance(condition, Relational):
lhs, rhs = condition.lhs, condition.rhs
if not isinstance(lhs, RandomIndexedSymbol):
lhs, rhs = rhs, lhs
condition = type(condition)(self.index_of.get(lhs, lhs),
self.index_of.get(rhs, rhs))
return condition
def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
"""
Handles probability queries for Markov process.
Parameters
==========
condition: Relational
given_condition: Relational/And
Returns
=======
Probability
If the information is not sufficient.
Expr
In all other cases.
Note
====
Any information passed at the time of query overrides
any information passed at the time of object creation like
transition probabilities, state space.
Pass the transition matrix using TransitionMatrixOf,
generator matrix using GeneratorMatrixOf and state space
using StochasticStateSpaceOf in given_condition using & or And.
"""
check, mat, state_index, new_given_condition = \
self._preprocess(given_condition, evaluate)
rv = list(condition.atoms(RandomIndexedSymbol))
symbolic = False
for sym in rv:
if sym.key.is_symbol:
symbolic = True
break
if check:
return Probability(condition, new_given_condition)
if isinstance(self, ContinuousMarkovChain):
trans_probs = self.transition_probabilities(mat)
elif isinstance(self, DiscreteMarkovChain):
trans_probs = mat
condition = self.replace_with_index(condition)
given_condition = self.replace_with_index(given_condition)
new_given_condition = self.replace_with_index(new_given_condition)
if isinstance(condition, Relational):
if isinstance(new_given_condition, And):
gcs = new_given_condition.args
else:
gcs = (new_given_condition, )
min_key_rv = list(new_given_condition.atoms(RandomIndexedSymbol))
if len(min_key_rv):
min_key_rv = min_key_rv[0]
for r in rv:
if min_key_rv.key.is_symbol or r.key.is_symbol:
continue
if min_key_rv.key > r.key:
return Probability(condition)
else:
min_key_rv = None
return Probability(condition)
if symbolic:
return self._symbolic_probability(condition, new_given_condition, rv, min_key_rv)
if len(rv) > 1:
rv[0] = condition.lhs
rv[1] = condition.rhs
if rv[0].key < rv[1].key:
rv[0], rv[1] = rv[1], rv[0]
if isinstance(condition, Gt):
condition = Lt(condition.lhs, condition.rhs)
elif isinstance(condition, Lt):
condition = Gt(condition.lhs, condition.rhs)
elif isinstance(condition, Ge):
condition = Le(condition.lhs, condition.rhs)
elif isinstance(condition, Le):
condition = Ge(condition.lhs, condition.rhs)
s = Rational(0, 1)
n = len(self.state_space)
if isinstance(condition, (Eq, Ne)):
for i in range(0, n):
s += self.probability(Eq(rv[0], i), Eq(rv[1], i)) * self.probability(Eq(rv[1], i), new_given_condition)
return s if isinstance(condition, Eq) else 1 - s
else:
upper = 0
greater = False
if isinstance(condition, (Ge, Lt)):
upper = 1
if isinstance(condition, (Ge, Gt)):
greater = True
for i in range(0, n):
if i <= n//2:
for j in range(0, i + upper):
s += self.probability(Eq(rv[0], i), Eq(rv[1], j)) * self.probability(Eq(rv[1], j), new_given_condition)
else:
s += self.probability(Eq(rv[0], i), new_given_condition)
for j in range(i + upper, n):
s -= self.probability(Eq(rv[0], i), Eq(rv[1], j)) * self.probability(Eq(rv[1], j), new_given_condition)
return s if greater else 1 - s
rv = rv[0]
states = condition.as_set()
prob, gstate = dict(), None
for gc in gcs:
if gc.has(min_key_rv):
if gc.has(Probability):
p, gp = (gc.rhs, gc.lhs) if isinstance(gc.lhs, Probability) \
else (gc.lhs, gc.rhs)
gr = gp.args[0]
gset = Intersection(gr.as_set(), state_index)
gstate = list(gset)[0]
prob[gset] = p
else:
_, gstate = (gc.lhs.key, gc.rhs) if isinstance(gc.lhs, RandomIndexedSymbol) \
else (gc.rhs.key, gc.lhs)
if not all(k in self.index_set for k in (rv.key, min_key_rv.key)):
raise IndexError("The timestamps of the process are not in it's index set.")
states = Intersection(states, state_index) if not isinstance(self.number_of_states, Symbol) else states
for state in Union(states, FiniteSet(gstate)):
if not state.is_Integer or Ge(state, mat.shape[0]) is True:
raise IndexError("No information is available for (%s, %s) in "
"transition probabilities of shape, (%s, %s). "
"State space is zero indexed."
%(gstate, state, mat.shape[0], mat.shape[1]))
if prob:
gstates = Union(*prob.keys())
if len(gstates) == 1:
gstate = list(gstates)[0]
gprob = list(prob.values())[0]
prob[gstates] = gprob
elif len(gstates) == len(state_index) - 1:
gstate = list(state_index - gstates)[0]
gprob = S.One - sum(prob.values())
prob[state_index - gstates] = gprob
else:
raise ValueError("Conflicting information.")
else:
gprob = S.One
if min_key_rv == rv:
return sum([prob[FiniteSet(state)] for state in states])
if isinstance(self, ContinuousMarkovChain):
return gprob * sum([trans_probs(rv.key - min_key_rv.key).__getitem__((gstate, state))
for state in states])
if isinstance(self, DiscreteMarkovChain):
return gprob * sum([(trans_probs**(rv.key - min_key_rv.key)).__getitem__((gstate, state))
for state in states])
if isinstance(condition, Not):
expr = condition.args[0]
return S.One - self.probability(expr, given_condition, evaluate, **kwargs)
if isinstance(condition, And):
compute_later, state2cond, conds = [], dict(), condition.args
for expr in conds:
if isinstance(expr, Relational):
ris = list(expr.atoms(RandomIndexedSymbol))[0]
if state2cond.get(ris, None) is None:
state2cond[ris] = S.true
state2cond[ris] &= expr
else:
compute_later.append(expr)
ris = []
for ri in state2cond:
ris.append(ri)
cset = Intersection(state2cond[ri].as_set(), state_index)
if len(cset) == 0:
return S.Zero
state2cond[ri] = cset.as_relational(ri)
sorted_ris = sorted(ris, key=lambda ri: ri.key)
prod = self.probability(state2cond[sorted_ris[0]], given_condition, evaluate, **kwargs)
for i in range(1, len(sorted_ris)):
ri, prev_ri = sorted_ris[i], sorted_ris[i-1]
if not isinstance(state2cond[ri], Eq):
raise ValueError("The process is in multiple states at %s, unable to determine the probability."%(ri))
mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat)
prod *= self.probability(state2cond[ri], state2cond[prev_ri]
& mat_of
& StochasticStateSpaceOf(self, state_index),
evaluate, **kwargs)
for expr in compute_later:
prod *= self.probability(expr, given_condition, evaluate, **kwargs)
return prod
if isinstance(condition, Or):
return sum([self.probability(expr, given_condition, evaluate, **kwargs)
for expr in condition.args])
raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been "
"implemented yet."%(condition, given_condition))
def _symbolic_probability(self, condition, new_given_condition, rv, min_key_rv):
#Function to calculate probability for queries with symbols
if isinstance(condition, Relational):
curr_state = new_given_condition.rhs if isinstance(new_given_condition.lhs, RandomIndexedSymbol) \
else new_given_condition.lhs
next_state = condition.rhs if isinstance(condition.lhs, RandomIndexedSymbol) \
else condition.lhs
if isinstance(condition, (Eq, Ne)):
if isinstance(self, DiscreteMarkovChain):
P = self.transition_probabilities**(rv[0].key - min_key_rv.key)
else:
P = exp(self.generator_matrix*(rv[0].key - min_key_rv.key))
prob = P[curr_state, next_state] if isinstance(condition, Eq) else 1 - P[curr_state, next_state]
return Piecewise((prob, rv[0].key > min_key_rv.key), (Probability(condition), True))
else:
upper = 1
greater = False
if isinstance(condition, (Ge, Lt)):
upper = 0
if isinstance(condition, (Ge, Gt)):
greater = True
k = Dummy('k')
condition = Eq(condition.lhs, k) if isinstance(condition.lhs, RandomIndexedSymbol)\
else Eq(condition.rhs, k)
total = Sum(self.probability(condition, new_given_condition), (k, next_state + upper, self.state_space._sup))
return Piecewise((total, rv[0].key > min_key_rv.key), (Probability(condition), True)) if greater\
else Piecewise((1 - total, rv[0].key > min_key_rv.key), (Probability(condition), True))
else:
return Probability(condition, new_given_condition)
def expectation(self, expr, condition=None, evaluate=True, **kwargs):
"""
Handles expectation queries for markov process.
Parameters
==========
expr: RandomIndexedSymbol, Relational, Logic
Condition for which expectation has to be computed. Must
contain a RandomIndexedSymbol of the process.
condition: Relational, Logic
The given conditions under which computations should be done.
Returns
=======
Expectation
Unevaluated object if computations cannot be done due to
insufficient information.
Expr
In all other cases when the computations are successful.
Note
====
Any information passed at the time of query overrides
any information passed at the time of object creation like
transition probabilities, state space.
Pass the transition matrix using TransitionMatrixOf,
generator matrix using GeneratorMatrixOf and state space
using StochasticStateSpaceOf in given_condition using & or And.
"""
check, mat, state_index, condition = \
self._preprocess(condition, evaluate)
if check:
return Expectation(expr, condition)
rvs = random_symbols(expr)
if isinstance(expr, Expr) and isinstance(condition, Eq) \
and len(rvs) == 1:
# handle queries similar to E(f(X[i]), Eq(X[i-m], <some-state>))
condition=self.replace_with_index(condition)
state_index=self.replace_with_index(state_index)
rv = list(rvs)[0]
lhsg, rhsg = condition.lhs, condition.rhs
if not isinstance(lhsg, RandomIndexedSymbol):
lhsg, rhsg = (rhsg, lhsg)
if rhsg not in state_index:
raise ValueError("%s state is not in the state space."%(rhsg))
if rv.key < lhsg.key:
raise ValueError("Incorrect given condition is given, expectation "
"time %s < time %s"%(rv.key, rv.key))
mat_of = TransitionMatrixOf(self, mat) if isinstance(self, DiscreteMarkovChain) else GeneratorMatrixOf(self, mat)
cond = condition & mat_of & \
StochasticStateSpaceOf(self, state_index)
func = lambda s: self.probability(Eq(rv, s), cond) * expr.subs(rv, self._state_index[s])
return sum([func(s) for s in state_index])
raise NotImplementedError("Mechanism for handling (%s, %s) queries hasn't been "
"implemented yet."%(expr, condition))
class DiscreteMarkovChain(DiscreteTimeStochasticProcess, MarkovProcess):
"""
Represents a finite discrete time-homogeneous Markov chain.
This type of Markov Chain can be uniquely characterised by
its (ordered) state space and its one-step transition probability
matrix.
Parameters
==========
sym:
The name given to the Markov Chain
state_space:
Optional, by default, Range(n)
trans_probs:
Optional, by default, MatrixSymbol('_T', n, n)
Examples
========
>>> from sympy.stats import DiscreteMarkovChain, TransitionMatrixOf, P, E
>>> from sympy import Matrix, MatrixSymbol, Eq, symbols
>>> T = Matrix([[0.5, 0.2, 0.3],[0.2, 0.5, 0.3],[0.2, 0.3, 0.5]])
>>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
>>> YS = DiscreteMarkovChain("Y")
>>> Y.state_space
{0, 1, 2}
>>> Y.transition_probabilities
Matrix([
[0.5, 0.2, 0.3],
[0.2, 0.5, 0.3],
[0.2, 0.3, 0.5]])
>>> TS = MatrixSymbol('T', 3, 3)
>>> P(Eq(YS[3], 2), Eq(YS[1], 1) & TransitionMatrixOf(YS, TS))
T[0, 2]*T[1, 0] + T[1, 1]*T[1, 2] + T[1, 2]*T[2, 2]
>>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2)
0.36
Probabilities will be calculated based on indexes rather
than state names. For example, with the Sunny-Cloudy-Rainy
model with string state names:
>>> from sympy.core.symbol import Str
>>> Y = DiscreteMarkovChain("Y", [Str('Sunny'), Str('Cloudy'), Str('Rainy')], T)
>>> P(Eq(Y[3], 2), Eq(Y[1], 1)).round(2)
0.36
This gives the same answer as the ``[0, 1, 2]`` state space.
Currently, there is no support for state names within probability
and expectation statements. Here is a work-around using ``Str``:
>>> P(Eq(Str('Rainy'), Y[3]), Eq(Y[1], Str('Cloudy'))).round(2)
0.36
Symbol state names can also be used:
>>> sunny, cloudy, rainy = symbols('Sunny, Cloudy, Rainy')
>>> Y = DiscreteMarkovChain("Y", [sunny, cloudy, rainy], T)
>>> P(Eq(Y[3], rainy), Eq(Y[1], cloudy)).round(2)
0.36
Expectations will be calculated as follows:
>>> E(Y[3], Eq(Y[1], cloudy))
0.38*Cloudy + 0.36*Rainy + 0.26*Sunny
Probability of expressions with multiple RandomIndexedSymbols
can also be calculated provided there is only 1 RandomIndexedSymbol
in the given condition. It is always better to use Rational instead
of floating point numbers for the probabilities in the
transition matrix to avoid errors.
>>> from sympy import Gt, Le, Rational
>>> T = Matrix([[Rational(5, 10), Rational(3, 10), Rational(2, 10)], [Rational(2, 10), Rational(7, 10), Rational(1, 10)], [Rational(3, 10), Rational(3, 10), Rational(4, 10)]])
>>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
>>> P(Eq(Y[3], Y[1]), Eq(Y[0], 0)).round(3)
0.409
>>> P(Gt(Y[3], Y[1]), Eq(Y[0], 0)).round(2)
0.36
>>> P(Le(Y[15], Y[10]), Eq(Y[8], 2)).round(7)
0.6963328
Symbolic probability queries are also supported
>>> from sympy import symbols, Matrix, Rational, Eq, Gt
>>> from sympy.stats import P, DiscreteMarkovChain
>>> a, b, c, d = symbols('a b c d')
>>> T = Matrix([[Rational(1, 10), Rational(4, 10), Rational(5, 10)], [Rational(3, 10), Rational(4, 10), Rational(3, 10)], [Rational(7, 10), Rational(2, 10), Rational(1, 10)]])
>>> Y = DiscreteMarkovChain("Y", [0, 1, 2], T)
>>> query = P(Eq(Y[a], b), Eq(Y[c], d))
>>> query.subs({a:10, b:2, c:5, d:1}).round(4)
0.3096
>>> P(Eq(Y[10], 2), Eq(Y[5], 1)).evalf().round(4)
0.3096
>>> query_gt = P(Gt(Y[a], b), Eq(Y[c], d))
>>> query_gt.subs({a:21, b:0, c:5, d:0}).evalf().round(5)
0.64705
>>> P(Gt(Y[21], 0), Eq(Y[5], 0)).round(5)
0.64705
There is limited support for arbitrarily sized states:
>>> n = symbols('n', nonnegative=True, integer=True)
>>> T = MatrixSymbol('T', n, n)
>>> Y = DiscreteMarkovChain("Y", trans_probs=T)
>>> Y.state_space
Range(0, n, 1)
>>> query = P(Eq(Y[a], b), Eq(Y[c], d))
>>> query.subs({a:10, b:2, c:5, d:1})
(T**5)[1, 2]
References
==========
.. [1] https://en.wikipedia.org/wiki/Markov_chain#Discrete-time_Markov_chain
.. [2] https://www.dartmouth.edu/~chance/teaching_aids/books_articles/probability_book/Chapter11.pdf
"""
index_set = S.Naturals0
def __new__(cls, sym, state_space=None, trans_probs=None):
sym = _symbol_converter(sym)
state_space, trans_probs = MarkovProcess._sanity_checks(state_space, trans_probs)
obj = Basic.__new__(cls, sym, state_space, trans_probs) # type: ignore
indices = dict()
if isinstance(obj.number_of_states, Integer):
for index, state in enumerate(obj._state_index):
indices[state] = index
obj.index_of = indices
return obj
@property
def transition_probabilities(self):
"""
Transition probabilities of discrete Markov chain,
either an instance of Matrix or MatrixSymbol.
"""
return self.args[2]
def communication_classes(self) -> tList[tTuple[tList[Basic], Boolean, Integer]]:
"""
Returns the list of communication classes that partition
the states of the markov chain.
A communication class is defined to be a set of states
such that every state in that set is reachable from
every other state in that set. Due to its properties
this forms a class in the mathematical sense.
Communication classes are also known as recurrence
classes.
Returns
=======
classes
The ``classes`` are a list of tuples. Each
tuple represents a single communication class
with its properties. The first element in the
tuple is the list of states in the class, the
second element is whether the class is recurrent
and the third element is the period of the
communication class.
Examples
========
>>> from sympy.stats import DiscreteMarkovChain
>>> from sympy import Matrix
>>> T = Matrix([[0, 1, 0],
... [1, 0, 0],
... [1, 0, 0]])
>>> X = DiscreteMarkovChain('X', [1, 2, 3], T)
>>> classes = X.communication_classes()
>>> for states, is_recurrent, period in classes:
... states, is_recurrent, period
([1, 2], True, 2)
([3], False, 1)
From this we can see that states ``1`` and ``2``
communicate, are recurrent and have a period
of 2. We can also see state ``3`` is transient
with a period of 1.
Notes
=====
The algorithm used is of order ``O(n**2)`` where
``n`` is the number of states in the markov chain.
It uses Tarjan's algorithm to find the classes
themselves and then it uses a breadth-first search
algorithm to find each class's periodicity.
Most of the algorithm's components approach ``O(n)``
as the matrix becomes more and more sparse.
References
==========
.. [1] http://www.columbia.edu/~ww2040/4701Sum07/4701-06-Notes-MCII.pdf
.. [2] http://cecas.clemson.edu/~shierd/Shier/markov.pdf
.. [3] https://ujcontent.uj.ac.za/vital/access/services/Download/uj:7506/CONTENT1
.. [4] https://www.mathworks.com/help/econ/dtmc.classify.html
"""
n = self.number_of_states
T = self.transition_probabilities
if isinstance(T, MatrixSymbol):
raise NotImplementedError("Cannot perform the operation with a symbolic matrix.")
# begin Tarjan's algorithm
V = Range(n)
# don't use state names. Rather use state
# indexes since we use them for matrix
# indexing here and later onward
E = [(i, j) for i in V for j in V if T[i, j] != 0]
classes = strongly_connected_components((V, E))
# end Tarjan's algorithm
recurrence = []
periods = []
for class_ in classes:
# begin recurrent check (similar to self._check_trans_probs())
submatrix = T[class_, class_] # get the submatrix with those states
is_recurrent = S.true
rows = submatrix.tolist()
for row in rows:
if (sum(row) - 1) != 0:
is_recurrent = S.false
break
recurrence.append(is_recurrent)
# end recurrent check
# begin breadth-first search
non_tree_edge_values: tSet[int] = set()
visited = {class_[0]}
newly_visited = {class_[0]}
level = {class_[0]: 0}
current_level = 0
done = False # imitate a do-while loop
while not done: # runs at most len(class_) times
done = len(visited) == len(class_)
current_level += 1
# this loop and the while loop above run a combined len(class_) number of times.
# so this triple nested loop runs through each of the n states once.
for i in newly_visited:
# the loop below runs len(class_) number of times
# complexity is around about O(n * avg(len(class_)))
newly_visited = {j for j in class_ if T[i, j] != 0}
new_tree_edges = newly_visited.difference(visited)
for j in new_tree_edges:
level[j] = current_level
new_non_tree_edges = newly_visited.intersection(visited)
new_non_tree_edge_values = {level[i]-level[j]+1 for j in new_non_tree_edges}
non_tree_edge_values = non_tree_edge_values.union(new_non_tree_edge_values)
visited = visited.union(new_tree_edges)
# igcd needs at least 2 arguments
positive_ntev = {val_e for val_e in non_tree_edge_values if val_e > 0}
if len(positive_ntev) == 0:
periods.append(len(class_))
elif len(positive_ntev) == 1:
periods.append(positive_ntev.pop())
else:
periods.append(igcd(*positive_ntev))
# end breadth-first search
# convert back to the user's state names
classes = [[_sympify(self._state_index[i]) for i in class_] for class_ in classes]
return list(zip(classes, recurrence, map(Integer,periods)))
def fundamental_matrix(self):
"""
Each entry fundamental matrix can be interpreted as
the expected number of times the chains is in state j
if it started in state i.
References
==========
.. [1] https://lips.cs.princeton.edu/the-fundamental-matrix-of-a-finite-markov-chain/
"""
_, _, _, Q = self.decompose()
if Q.shape[0] > 0: # if non-ergodic
I = eye(Q.shape[0])
if (I - Q).det() == 0:
raise ValueError("The fundamental matrix doesn't exist.")
return (I - Q).inv().as_immutable()
else: # if ergodic
P = self.transition_probabilities
I = eye(P.shape[0])
w = self.fixed_row_vector()
W = Matrix([list(w) for i in range(0, P.shape[0])])
if (I - P + W).det() == 0:
raise ValueError("The fundamental matrix doesn't exist.")
return (I - P + W).inv().as_immutable()
def absorbing_probabilities(self):
"""
Computes the absorbing probabilities, i.e.,
the ij-th entry of the matrix denotes the
probability of Markov chain being absorbed
in state j starting from state i.
"""
_, _, R, _ = self.decompose()
N = self.fundamental_matrix()
if R is None or N is None:
return None
return N*R
def absorbing_probabilites(self):
SymPyDeprecationWarning(
feature="absorbing_probabilites",
useinstead="absorbing_probabilities",
issue=20042,
deprecated_since_version="1.7"
).warn()
return self.absorbing_probabilities()
def is_regular(self):
tuples = self.communication_classes()
if len(tuples) == 0:
return S.false # not defined for a 0x0 matrix
classes, _, periods = list(zip(*tuples))
return And(len(classes) == 1, periods[0] == 1)
def is_ergodic(self):
tuples = self.communication_classes()
if len(tuples) == 0:
return S.false # not defined for a 0x0 matrix
classes, _, _ = list(zip(*tuples))
return S(len(classes) == 1)
def is_absorbing_state(self, state):
trans_probs = self.transition_probabilities
if isinstance(trans_probs, ImmutableMatrix) and \
state < trans_probs.shape[0]:
return S(trans_probs[state, state]) is S.One
def is_absorbing_chain(self):
states, A, B, C = self.decompose()
r = A.shape[0]
return And(r > 0, A == Identity(r).as_explicit())
def stationary_distribution(self, condition_set=False) -> tUnion[ImmutableMatrix, ConditionSet, Lambda]:
r"""
The stationary distribution is any row vector, p, that solves p = pP,
is row stochastic and each element in p must be nonnegative.
That means in matrix form: :math:`(P-I)^T p^T = 0` and
:math:`(1, \dots, 1) p = 1`
where ``P`` is the one-step transition matrix.
All time-homogeneous Markov Chains with a finite state space
have at least one stationary distribution. In addition, if
a finite time-homogeneous Markov Chain is irreducible, the
stationary distribution is unique.
Parameters
==========
condition_set : bool
If the chain has a symbolic size or transition matrix,
it will return a ``Lambda`` if ``False`` and return a
``ConditionSet`` if ``True``.
Examples
========
>>> from sympy.stats import DiscreteMarkovChain
>>> from sympy import Matrix, S
An irreducible Markov Chain
>>> T = Matrix([[S(1)/2, S(1)/2, 0],
... [S(4)/5, S(1)/5, 0],
... [1, 0, 0]])
>>> X = DiscreteMarkovChain('X', trans_probs=T)
>>> X.stationary_distribution()
Matrix([[8/13, 5/13, 0]])
A reducible Markov Chain
>>> T = Matrix([[S(1)/2, S(1)/2, 0],
... [S(4)/5, S(1)/5, 0],
... [0, 0, 1]])
>>> X = DiscreteMarkovChain('X', trans_probs=T)
>>> X.stationary_distribution()
Matrix([[8/13 - 8*tau0/13, 5/13 - 5*tau0/13, tau0]])
>>> Y = DiscreteMarkovChain('Y')
>>> Y.stationary_distribution()
Lambda((wm, _T), Eq(wm*_T, wm))
>>> Y.stationary_distribution(condition_set=True)
ConditionSet(wm, Eq(wm*_T, wm))
References
==========
.. [1] https://www.probabilitycourse.com/chapter11/11_2_6_stationary_and_limiting_distributions.php
.. [2] https://galton.uchicago.edu/~yibi/teaching/stat317/2014/Lectures/Lecture4_6up.pdf
See Also
========
sympy.stats.DiscreteMarkovChain.limiting_distribution
"""
trans_probs = self.transition_probabilities
n = self.number_of_states
if n == 0:
return ImmutableMatrix(Matrix([[]]))
# symbolic matrix version
if isinstance(trans_probs, MatrixSymbol):
wm = MatrixSymbol('wm', 1, n)
if condition_set:
return ConditionSet(wm, Eq(wm * trans_probs, wm))
else:
return Lambda((wm, trans_probs), Eq(wm * trans_probs, wm))
# numeric matrix version
a = Matrix(trans_probs - Identity(n)).T
a[0, 0:n] = ones(1, n) # type: ignore
b = zeros(n, 1)
b[0, 0] = 1
soln = list(linsolve((a, b)))[0]
return ImmutableMatrix([[sol for sol in soln]])
def fixed_row_vector(self):
"""
A wrapper for ``stationary_distribution()``.
"""
return self.stationary_distribution()
@property
def limiting_distribution(self):
"""
The fixed row vector is the limiting
distribution of a discrete Markov chain.
"""
return self.fixed_row_vector()
def decompose(self) -> tTuple[tList[Basic], ImmutableMatrix, ImmutableMatrix, ImmutableMatrix]:
"""
Decomposes the transition matrix into submatrices with
special properties.
The transition matrix can be decomposed into 4 submatrices:
- A - the submatrix from recurrent states to recurrent states.
- B - the submatrix from transient to recurrent states.
- C - the submatrix from transient to transient states.
- O - the submatrix of zeros for recurrent to transient states.
Returns
=======
states, A, B, C
``states`` - a list of state names with the first being
the recurrent states and the last being
the transient states in the order
of the row names of A and then the row names of C.
``A`` - the submatrix from recurrent states to recurrent states.
``B`` - the submatrix from transient to recurrent states.
``C`` - the submatrix from transient to transient states.
Examples
========
>>> from sympy.stats import DiscreteMarkovChain
>>> from sympy import Matrix, S
One can decompose this chain for example:
>>> T = Matrix([[S(1)/2, S(1)/2, 0, 0, 0],
... [S(2)/5, S(1)/5, S(2)/5, 0, 0],
... [0, 0, 1, 0, 0],
... [0, 0, S(1)/2, S(1)/2, 0],
... [S(1)/2, 0, 0, 0, S(1)/2]])
>>> X = DiscreteMarkovChain('X', trans_probs=T)
>>> states, A, B, C = X.decompose()
>>> states
[2, 0, 1, 3, 4]
>>> A # recurrent to recurrent
Matrix([[1]])
>>> B # transient to recurrent
Matrix([
[ 0],
[2/5],
[1/2],
[ 0]])
>>> C # transient to transient
Matrix([
[1/2, 1/2, 0, 0],
[2/5, 1/5, 0, 0],
[ 0, 0, 1/2, 0],
[1/2, 0, 0, 1/2]])
This means that state 2 is the only absorbing state
(since A is a 1x1 matrix). B is a 4x1 matrix since
the 4 remaining transient states all merge into reccurent
state 2. And C is the 4x4 matrix that shows how the
transient states 0, 1, 3, 4 all interact.
See Also
========
sympy.stats.DiscreteMarkovChain.communication_classes
sympy.stats.DiscreteMarkovChain.canonical_form
References
==========
.. [1] https://en.wikipedia.org/wiki/Absorbing_Markov_chain
.. [2] http://people.brandeis.edu/~igusa/Math56aS08/Math56a_S08_notes015.pdf
"""
trans_probs = self.transition_probabilities
classes = self.communication_classes()
r_states = []
t_states = []
for states, recurrent, period in classes:
if recurrent:
r_states += states
else:
t_states += states
states = r_states + t_states
indexes = [self.index_of[state] for state in states] # type: ignore
A = Matrix(len(r_states), len(r_states),
lambda i, j: trans_probs[indexes[i], indexes[j]])
B = Matrix(len(t_states), len(r_states),
lambda i, j: trans_probs[indexes[len(r_states) + i], indexes[j]])
C = Matrix(len(t_states), len(t_states),
lambda i, j: trans_probs[indexes[len(r_states) + i], indexes[len(r_states) + j]])
return states, A.as_immutable(), B.as_immutable(), C.as_immutable()
def canonical_form(self) -> tTuple[tList[Basic], ImmutableMatrix]:
"""
Reorders the one-step transition matrix
so that recurrent states appear first and transient
states appear last. Other representations include inserting
transient states first and recurrent states last.
Returns
=======
states, P_new
``states`` is the list that describes the order of the
new states in the matrix
so that the ith element in ``states`` is the state of the
ith row of A.
``P_new`` is the new transition matrix in canonical form.
Examples
========
>>> from sympy.stats import DiscreteMarkovChain
>>> from sympy import Matrix, S
You can convert your chain into canonical form:
>>> T = Matrix([[S(1)/2, S(1)/2, 0, 0, 0],
... [S(2)/5, S(1)/5, S(2)/5, 0, 0],
... [0, 0, 1, 0, 0],
... [0, 0, S(1)/2, S(1)/2, 0],
... [S(1)/2, 0, 0, 0, S(1)/2]])
>>> X = DiscreteMarkovChain('X', list(range(1, 6)), trans_probs=T)
>>> states, new_matrix = X.canonical_form()
>>> states
[3, 1, 2, 4, 5]
>>> new_matrix
Matrix([
[ 1, 0, 0, 0, 0],
[ 0, 1/2, 1/2, 0, 0],
[2/5, 2/5, 1/5, 0, 0],
[1/2, 0, 0, 1/2, 0],
[ 0, 1/2, 0, 0, 1/2]])
The new states are [3, 1, 2, 4, 5] and you can
create a new chain with this and its canonical
form will remain the same (since it is already
in canonical form).
>>> X = DiscreteMarkovChain('X', states, new_matrix)
>>> states, new_matrix = X.canonical_form()
>>> states
[3, 1, 2, 4, 5]
>>> new_matrix
Matrix([
[ 1, 0, 0, 0, 0],
[ 0, 1/2, 1/2, 0, 0],
[2/5, 2/5, 1/5, 0, 0],
[1/2, 0, 0, 1/2, 0],
[ 0, 1/2, 0, 0, 1/2]])
This is not limited to absorbing chains:
>>> T = Matrix([[0, 5, 5, 0, 0],
... [0, 0, 0, 10, 0],
... [5, 0, 5, 0, 0],
... [0, 10, 0, 0, 0],
... [0, 3, 0, 3, 4]])/10
>>> X = DiscreteMarkovChain('X', trans_probs=T)
>>> states, new_matrix = X.canonical_form()
>>> states
[1, 3, 0, 2, 4]
>>> new_matrix
Matrix([
[ 0, 1, 0, 0, 0],
[ 1, 0, 0, 0, 0],
[ 1/2, 0, 0, 1/2, 0],
[ 0, 0, 1/2, 1/2, 0],
[3/10, 3/10, 0, 0, 2/5]])
See Also
========
sympy.stats.DiscreteMarkovChain.communication_classes
sympy.stats.DiscreteMarkovChain.decompose
References
==========
.. [1] https://onlinelibrary.wiley.com/doi/pdf/10.1002/9780470316887.app1
.. [2] http://www.columbia.edu/~ww2040/6711F12/lect1023big.pdf
"""
states, A, B, C = self.decompose()
O = zeros(A.shape[0], C.shape[1])
return states, BlockMatrix([[A, O], [B, C]]).as_explicit()
def sample(self):
"""
Returns
=======
sample: iterator object
iterator object containing the sample
"""
if not isinstance(self.transition_probabilities, (Matrix, ImmutableMatrix)):
raise ValueError("Transition Matrix must be provided for sampling")
Tlist = self.transition_probabilities.tolist()
samps = [random.choice(list(self.state_space))]
yield samps[0]
time = 1
densities = {}
for state in self.state_space:
states = list(self.state_space)
densities[state] = {states[i]: Tlist[state][i]
for i in range(len(states))}
while time < S.Infinity:
samps.append((next(sample_iter(FiniteRV("_", densities[samps[time - 1]])))))
yield samps[time]
time += 1
class ContinuousMarkovChain(ContinuousTimeStochasticProcess, MarkovProcess):
"""
Represents continuous time Markov chain.
Parameters
==========
sym: Symbol/str
state_space: Set
Optional, by default, S.Reals
gen_mat: Matrix/ImmutableMatrix/MatrixSymbol
Optional, by default, None
Examples
========
>>> from sympy.stats import ContinuousMarkovChain, P
>>> from sympy import Matrix, S, Eq, Gt
>>> G = Matrix([[-S(1), S(1)], [S(1), -S(1)]])
>>> C = ContinuousMarkovChain('C', state_space=[0, 1], gen_mat=G)
>>> C.limiting_distribution()
Matrix([[1/2, 1/2]])
>>> C.state_space
{0, 1}
>>> C.generator_matrix
Matrix([
[-1, 1],
[ 1, -1]])
Probability queries are supported
>>> P(Eq(C(1.96), 0), Eq(C(0.78), 1)).round(5)
0.45279
>>> P(Gt(C(1.7), 0), Eq(C(0.82), 1)).round(5)
0.58602
Probability of expressions with multiple RandomIndexedSymbols
can also be calculated provided there is only 1 RandomIndexedSymbol
in the given condition. It is always better to use Rational instead
of floating point numbers for the probabilities in the
generator matrix to avoid errors.
>>> from sympy import Gt, Le, Rational
>>> G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]])
>>> C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G)
>>> P(Eq(C(3.92), C(1.75)), Eq(C(0.46), 0)).round(5)
0.37933
>>> P(Gt(C(3.92), C(1.75)), Eq(C(0.46), 0)).round(5)
0.34211
>>> P(Le(C(1.57), C(3.14)), Eq(C(1.22), 1)).round(4)
0.7143
Symbolic probability queries are also supported
>>> from sympy import S, symbols, Matrix, Rational, Eq, Gt
>>> from sympy.stats import P, ContinuousMarkovChain
>>> a,b,c,d = symbols('a b c d')
>>> G = Matrix([[-S(1), Rational(1, 10), Rational(9, 10)], [Rational(2, 5), -S(1), Rational(3, 5)], [Rational(1, 2), Rational(1, 2), -S(1)]])
>>> C = ContinuousMarkovChain('C', state_space=[0, 1, 2], gen_mat=G)
>>> query = P(Eq(C(a), b), Eq(C(c), d))
>>> query.subs({a:3.65, b:2, c:1.78, d:1}).evalf().round(10)
0.4002723175
>>> P(Eq(C(3.65), 2), Eq(C(1.78), 1)).round(10)
0.4002723175
>>> query_gt = P(Gt(C(a), b), Eq(C(c), d))
>>> query_gt.subs({a:43.2, b:0, c:3.29, d:2}).evalf().round(10)
0.6832579186
>>> P(Gt(C(43.2), 0), Eq(C(3.29), 2)).round(10)
0.6832579186
References
==========
.. [1] https://en.wikipedia.org/wiki/Markov_chain#Continuous-time_Markov_chain
.. [2] http://u.math.biu.ac.il/~amirgi/CTMCnotes.pdf
"""
index_set = S.Reals
def __new__(cls, sym, state_space=None, gen_mat=None):
sym = _symbol_converter(sym)
state_space, gen_mat = MarkovProcess._sanity_checks(state_space, gen_mat)
obj = Basic.__new__(cls, sym, state_space, gen_mat)
indices = dict()
if isinstance(obj.number_of_states, Integer):
for index, state in enumerate(obj.state_space):
indices[state] = index
obj.index_of = indices
return obj
@property
def generator_matrix(self):
return self.args[2]
@cacheit
def transition_probabilities(self, gen_mat=None):
t = Dummy('t')
if isinstance(gen_mat, (Matrix, ImmutableMatrix)) and \
gen_mat.is_diagonalizable():
# for faster computation use diagonalized generator matrix
Q, D = gen_mat.diagonalize()
return Lambda(t, Q*exp(t*D)*Q.inv())
if gen_mat != None:
return Lambda(t, exp(t*gen_mat))
def limiting_distribution(self):
gen_mat = self.generator_matrix
if gen_mat is None:
return None
if isinstance(gen_mat, MatrixSymbol):
wm = MatrixSymbol('wm', 1, gen_mat.shape[0])
return Lambda((wm, gen_mat), Eq(wm*gen_mat, wm))
w = IndexedBase('w')
wi = [w[i] for i in range(gen_mat.shape[0])]
wm = Matrix([wi])
eqs = (wm*gen_mat).tolist()[0]
eqs.append(sum(wi) - 1)
soln = list(linsolve(eqs, wi))[0]
return ImmutableMatrix([[sol for sol in soln]])
class BernoulliProcess(DiscreteTimeStochasticProcess):
"""
The Bernoulli process consists of repeated
independent Bernoulli process trials with the same parameter `p`.
It's assumed that the probability `p` applies to every
trial and that the outcomes of each trial
are independent of all the rest. Therefore Bernoulli Processs
is Discrete State and Discrete Time Stochastic Process.
Parameters
==========
sym: Symbol/str
success: Integer/str
The event which is considered to be success, by default is 1.
failure: Integer/str
The event which is considered to be failure, by default is 0.
p: Real Number between 0 and 1
Represents the probability of getting success.
Examples
========
>>> from sympy.stats import BernoulliProcess, P, E
>>> from sympy import Eq, Gt
>>> B = BernoulliProcess("B", p=0.7, success=1, failure=0)
>>> B.state_space
{0, 1}
>>> (B.p).round(2)
0.70
>>> B.success
1
>>> B.failure
0
>>> X = B[1] + B[2] + B[3]
>>> P(Eq(X, 0)).round(2)
0.03
>>> P(Eq(X, 2)).round(2)
0.44
>>> P(Eq(X, 4)).round(2)
0
>>> P(Gt(X, 1)).round(2)
0.78
>>> P(Eq(B[1], 0) & Eq(B[2], 1) & Eq(B[3], 0) & Eq(B[4], 1)).round(2)
0.04
>>> B.joint_distribution(B[1], B[2])
JointDistributionHandmade(Lambda((B[1], B[2]), Piecewise((0.7, Eq(B[1], 1)),
(0.3, Eq(B[1], 0)), (0, True))*Piecewise((0.7, Eq(B[2], 1)), (0.3, Eq(B[2], 0)),
(0, True))))
>>> E(2*B[1] + B[2]).round(2)
2.10
>>> P(B[1] < 1).round(2)
0.30
References
==========
.. [1] https://en.wikipedia.org/wiki/Bernoulli_process
.. [2] https://mathcs.clarku.edu/~djoyce/ma217/bernoulli.pdf
"""
index_set = S.Naturals0
def __new__(cls, sym, p, success=1, failure=0):
_value_check(p >= 0 and p <= 1, 'Value of p must be between 0 and 1.')
sym = _symbol_converter(sym)
p = _sympify(p)
success = _sym_sympify(success)
failure = _sym_sympify(failure)
return Basic.__new__(cls, sym, p, success, failure)
@property
def symbol(self):
return self.args[0]
@property
def p(self):
return self.args[1]
@property
def success(self):
return self.args[2]
@property
def failure(self):
return self.args[3]
@property
def state_space(self):
return _set_converter([self.success, self.failure])
def distribution(self, key=None):
if key is None:
self._deprecation_warn_distribution()
return BernoulliDistribution(self.p)
return BernoulliDistribution(self.p, self.success, self.failure)
def simple_rv(self, rv):
return Bernoulli(rv.name, p=self.p,
succ=self.success, fail=self.failure)
def expectation(self, expr, condition=None, evaluate=True, **kwargs):
"""
Computes expectation.
Parameters
==========
expr: RandomIndexedSymbol, Relational, Logic
Condition for which expectation has to be computed. Must
contain a RandomIndexedSymbol of the process.
condition: Relational, Logic
The given conditions under which computations should be done.
Returns
=======
Expectation of the RandomIndexedSymbol.
"""
return _SubstituteRV._expectation(expr, condition, evaluate, **kwargs)
def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
"""
Computes probability.
Parameters
==========
condition: Relational
Condition for which probability has to be computed. Must
contain a RandomIndexedSymbol of the process.
given_condition: Relational/And
The given conditions under which computations should be done.
Returns
=======
Probability of the condition.
"""
return _SubstituteRV._probability(condition, given_condition, evaluate, **kwargs)
def density(self, x):
return Piecewise((self.p, Eq(x, self.success)),
(1 - self.p, Eq(x, self.failure)),
(S.Zero, True))
class _SubstituteRV:
"""
Internal class to handle the queries of expectation and probability
by substitution.
"""
@staticmethod
def _rvindexed_subs(expr, condition=None):
"""
Substitutes the RandomIndexedSymbol with the RandomSymbol with
same name, distribution and probability as RandomIndexedSymbol.
Parameters
==========
expr: RandomIndexedSymbol, Relational, Logic
Condition for which expectation has to be computed. Must
contain a RandomIndexedSymbol of the process.
condition: Relational, Logic
The given conditions under which computations should be done.
"""
rvs_expr = random_symbols(expr)
if len(rvs_expr) != 0:
swapdict_expr = {}
for rv in rvs_expr:
if isinstance(rv, RandomIndexedSymbol):
newrv = rv.pspace.process.simple_rv(rv) # substitute with equivalent simple rv
swapdict_expr[rv] = newrv
expr = expr.subs(swapdict_expr)
rvs_cond = random_symbols(condition)
if len(rvs_cond)!=0:
swapdict_cond = {}
for rv in rvs_cond:
if isinstance(rv, RandomIndexedSymbol):
newrv = rv.pspace.process.simple_rv(rv)
swapdict_cond[rv] = newrv
condition = condition.subs(swapdict_cond)
return expr, condition
@classmethod
def _expectation(self, expr, condition=None, evaluate=True, **kwargs):
"""
Internal method for computing expectation of indexed RV.
Parameters
==========
expr: RandomIndexedSymbol, Relational, Logic
Condition for which expectation has to be computed. Must
contain a RandomIndexedSymbol of the process.
condition: Relational, Logic
The given conditions under which computations should be done.
Returns
=======
Expectation of the RandomIndexedSymbol.
"""
new_expr, new_condition = self._rvindexed_subs(expr, condition)
if not is_random(new_expr):
return new_expr
new_pspace = pspace(new_expr)
if new_condition is not None:
new_expr = given(new_expr, new_condition)
if new_expr.is_Add: # As E is Linear
return Add(*[new_pspace.compute_expectation(
expr=arg, evaluate=evaluate, **kwargs)
for arg in new_expr.args])
return new_pspace.compute_expectation(
new_expr, evaluate=evaluate, **kwargs)
@classmethod
def _probability(self, condition, given_condition=None, evaluate=True, **kwargs):
"""
Internal method for computing probability of indexed RV
Parameters
==========
condition: Relational
Condition for which probability has to be computed. Must
contain a RandomIndexedSymbol of the process.
given_condition: Relational/And
The given conditions under which computations should be done.
Returns
=======
Probability of the condition.
"""
new_condition, new_givencondition = self._rvindexed_subs(condition, given_condition)
if isinstance(new_givencondition, RandomSymbol):
condrv = random_symbols(new_condition)
if len(condrv) == 1 and condrv[0] == new_givencondition:
return BernoulliDistribution(self._probability(new_condition), 0, 1)
if any(dependent(rv, new_givencondition) for rv in condrv):
return Probability(new_condition, new_givencondition)
else:
return self._probability(new_condition)
if new_givencondition is not None and \
not isinstance(new_givencondition, (Relational, Boolean)):
raise ValueError("%s is not a relational or combination of relationals"
% (new_givencondition))
if new_givencondition == False or new_condition == False:
return S.Zero
if new_condition == True:
return S.One
if not isinstance(new_condition, (Relational, Boolean)):
raise ValueError("%s is not a relational or combination of relationals"
% (new_condition))
if new_givencondition is not None: # If there is a condition
# Recompute on new conditional expr
return self._probability(given(new_condition, new_givencondition, **kwargs), **kwargs)
result = pspace(new_condition).probability(new_condition, **kwargs)
if evaluate and hasattr(result, 'doit'):
return result.doit()
else:
return result
def get_timerv_swaps(expr, condition):
"""
Finds the appropriate interval for each time stamp in expr by parsing
the given condition and returns intervals for each timestamp and
dictionary that maps variable time-stamped Random Indexed Symbol to its
corresponding Random Indexed variable with fixed time stamp.
Parameters
==========
expr: SymPy Expression
Expression containing Random Indexed Symbols with variable time stamps
condition: Relational/Boolean Expression
Expression containing time bounds of variable time stamps in expr
Examples
========
>>> from sympy.stats.stochastic_process_types import get_timerv_swaps, PoissonProcess
>>> from sympy import symbols, Contains, Interval
>>> x, t, d = symbols('x t d', positive=True)
>>> X = PoissonProcess("X", 3)
>>> get_timerv_swaps(x*X(t), Contains(t, Interval.Lopen(0, 1)))
([Interval.Lopen(0, 1)], {X(t): X(1)})
>>> get_timerv_swaps((X(t)**2 + X(d)**2), Contains(t, Interval.Lopen(0, 1))
... & Contains(d, Interval.Ropen(1, 4))) # doctest: +SKIP
([Interval.Ropen(1, 4), Interval.Lopen(0, 1)], {X(d): X(3), X(t): X(1)})
Returns
=======
intervals: list
List of Intervals/FiniteSet on which each time stamp is defined
rv_swap: dict
Dictionary mapping variable time Random Indexed Symbol to constant time
Random Indexed Variable
"""
if not isinstance(condition, (Relational, Boolean)):
raise ValueError("%s is not a relational or combination of relationals"
% (condition))
expr_syms = list(expr.atoms(RandomIndexedSymbol))
if isinstance(condition, (And, Or)):
given_cond_args = condition.args
else: # single condition
given_cond_args = (condition, )
rv_swap = {}
intervals = []
for expr_sym in expr_syms:
for arg in given_cond_args:
if arg.has(expr_sym.key) and isinstance(expr_sym.key, Symbol):
intv = _set_converter(arg.args[1])
diff_key = intv._sup - intv._inf
if diff_key == oo:
raise ValueError("%s should have finite bounds" % str(expr_sym.name))
elif diff_key == S.Zero: # has singleton set
diff_key = intv._sup
rv_swap[expr_sym] = expr_sym.subs({expr_sym.key: diff_key})
intervals.append(intv)
return intervals, rv_swap
class CountingProcess(ContinuousTimeStochasticProcess):
"""
This class handles the common methods of the Counting Processes
such as Poisson, Wiener and Gamma Processes
"""
index_set = _set_converter(Interval(0, oo))
@property
def symbol(self):
return self.args[0]
def expectation(self, expr, condition=None, evaluate=True, **kwargs):
"""
Computes expectation
Parameters
==========
expr: RandomIndexedSymbol, Relational, Logic
Condition for which expectation has to be computed. Must
contain a RandomIndexedSymbol of the process.
condition: Relational, Boolean
The given conditions under which computations should be done, i.e,
the intervals on which each variable time stamp in expr is defined
Returns
=======
Expectation of the given expr
"""
if condition is not None:
intervals, rv_swap = get_timerv_swaps(expr, condition)
# they are independent when they have non-overlapping intervals
if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet
for intv_comb in itertools.combinations(intervals, 2)):
if expr.is_Add:
return Add.fromiter(self.expectation(arg, condition)
for arg in expr.args)
expr = expr.subs(rv_swap)
else:
return Expectation(expr, condition)
return _SubstituteRV._expectation(expr, evaluate=evaluate, **kwargs)
def _solve_argwith_tworvs(self, arg):
if arg.args[0].key >= arg.args[1].key or isinstance(arg, Eq):
diff_key = abs(arg.args[0].key - arg.args[1].key)
rv = arg.args[0]
arg = arg.__class__(rv.pspace.process(diff_key), 0)
else:
diff_key = arg.args[1].key - arg.args[0].key
rv = arg.args[1]
arg = arg.__class__(rv.pspace.process(diff_key), 0)
return arg
def _solve_numerical(self, condition, given_condition=None):
if isinstance(condition, And):
args_list = list(condition.args)
else:
args_list = [condition]
if given_condition is not None:
if isinstance(given_condition, And):
args_list.extend(list(given_condition.args))
else:
args_list.extend([given_condition])
# sort the args based on timestamp to get the independent increments in
# each segment using all the condition args as well as given_condition args
args_list = sorted(args_list, key=lambda x: x.args[0].key)
result = []
cond_args = list(condition.args) if isinstance(condition, And) else [condition]
if args_list[0] in cond_args and not (is_random(args_list[0].args[0])
and is_random(args_list[0].args[1])):
result.append(_SubstituteRV._probability(args_list[0]))
if is_random(args_list[0].args[0]) and is_random(args_list[0].args[1]):
arg = self._solve_argwith_tworvs(args_list[0])
result.append(_SubstituteRV._probability(arg))
for i in range(len(args_list) - 1):
curr, nex = args_list[i], args_list[i + 1]
diff_key = nex.args[0].key - curr.args[0].key
working_set = curr.args[0].pspace.process.state_space
if curr.args[1] > nex.args[1]: #impossible condition so return 0
result.append(0)
break
if isinstance(curr, Eq):
working_set = Intersection(working_set, Interval.Lopen(curr.args[1], oo))
else:
working_set = Intersection(working_set, curr.as_set())
if isinstance(nex, Eq):
working_set = Intersection(working_set, Interval(-oo, nex.args[1]))
else:
working_set = Intersection(working_set, nex.as_set())
if working_set == EmptySet:
rv = Eq(curr.args[0].pspace.process(diff_key), 0)
result.append(_SubstituteRV._probability(rv))
else:
if working_set.is_finite_set:
if isinstance(curr, Eq) and isinstance(nex, Eq):
rv = Eq(curr.args[0].pspace.process(diff_key), len(working_set))
result.append(_SubstituteRV._probability(rv))
elif isinstance(curr, Eq) ^ isinstance(nex, Eq):
result.append(Add.fromiter(_SubstituteRV._probability(Eq(
curr.args[0].pspace.process(diff_key), x))
for x in range(len(working_set))))
else:
n = len(working_set)
result.append(Add.fromiter((n - x)*_SubstituteRV._probability(Eq(
curr.args[0].pspace.process(diff_key), x)) for x in range(n)))
else:
result.append(_SubstituteRV._probability(
curr.args[0].pspace.process(diff_key) <= working_set._sup - working_set._inf))
return Mul.fromiter(result)
def probability(self, condition, given_condition=None, evaluate=True, **kwargs):
"""
Computes probability.
Parameters
==========
condition: Relational
Condition for which probability has to be computed. Must
contain a RandomIndexedSymbol of the process.
given_condition: Relational, Boolean
The given conditions under which computations should be done, i.e,
the intervals on which each variable time stamp in expr is defined
Returns
=======
Probability of the condition
"""
check_numeric = True
if isinstance(condition, (And, Or)):
cond_args = condition.args
else:
cond_args = (condition, )
# check that condition args are numeric or not
if not all(arg.args[0].key.is_number for arg in cond_args):
check_numeric = False
if given_condition is not None:
check_given_numeric = True
if isinstance(given_condition, (And, Or)):
given_cond_args = given_condition.args
else:
given_cond_args = (given_condition, )
# check that given condition args are numeric or not
if given_condition.has(Contains):
check_given_numeric = False
# Handle numerical queries
if check_numeric and check_given_numeric:
res = []
if isinstance(condition, Or):
res.append(Add.fromiter(self._solve_numerical(arg, given_condition)
for arg in condition.args))
if isinstance(given_condition, Or):
res.append(Add.fromiter(self._solve_numerical(condition, arg)
for arg in given_condition.args))
if res:
return Add.fromiter(res)
return self._solve_numerical(condition, given_condition)
# No numeric queries, go by Contains?... then check that all the
# given condition are in form of `Contains`
if not all(arg.has(Contains) for arg in given_cond_args):
raise ValueError("If given condition is passed with `Contains`, then "
"please pass the evaluated condition with its corresponding information "
"in terms of intervals of each time stamp to be passed in given condition.")
intervals, rv_swap = get_timerv_swaps(condition, given_condition)
# they are independent when they have non-overlapping intervals
if len(intervals) == 1 or all(Intersection(*intv_comb) == EmptySet
for intv_comb in itertools.combinations(intervals, 2)):
if isinstance(condition, And):
return Mul.fromiter(self.probability(arg, given_condition)
for arg in condition.args)
elif isinstance(condition, Or):
return Add.fromiter(self.probability(arg, given_condition)
for arg in condition.args)
condition = condition.subs(rv_swap)
else:
return Probability(condition, given_condition)
if check_numeric:
return self._solve_numerical(condition)
return _SubstituteRV._probability(condition, evaluate=evaluate, **kwargs)
class PoissonProcess(CountingProcess):
"""
The Poisson process is a counting process. It is usually used in scenarios
where we are counting the occurrences of certain events that appear
to happen at a certain rate, but completely at random.
Parameters
==========
sym: Symbol/str
lamda: Positive number
Rate of the process, ``lamda > 0``
Examples
========
>>> from sympy.stats import PoissonProcess, P, E
>>> from sympy import symbols, Eq, Ne, Contains, Interval
>>> X = PoissonProcess("X", lamda=3)
>>> X.state_space
Naturals0
>>> X.lamda
3
>>> t1, t2 = symbols('t1 t2', positive=True)
>>> P(X(t1) < 4)
(9*t1**3/2 + 9*t1**2/2 + 3*t1 + 1)*exp(-3*t1)
>>> P(Eq(X(t1), 2) | Ne(X(t1), 4), Contains(t1, Interval.Ropen(2, 4)))
1 - 36*exp(-6)
>>> P(Eq(X(t1), 2) & Eq(X(t2), 3), Contains(t1, Interval.Lopen(0, 2))
... & Contains(t2, Interval.Lopen(2, 4)))
648*exp(-12)
>>> E(X(t1))
3*t1
>>> E(X(t1)**2 + 2*X(t2), Contains(t1, Interval.Lopen(0, 1))
... & Contains(t2, Interval.Lopen(1, 2)))
18
>>> P(X(3) < 1, Eq(X(1), 0))
exp(-6)
>>> P(Eq(X(4), 3), Eq(X(2), 3))
exp(-6)
>>> P(X(2) <= 3, X(1) > 1)
5*exp(-3)
Merging two Poisson Processes
>>> Y = PoissonProcess("Y", lamda=4)
>>> Z = X + Y
>>> Z.lamda
7
Splitting a Poisson Process into two independent Poisson Processes
>>> N, M = Z.split(l1=2, l2=5)
>>> N.lamda, M.lamda
(2, 5)
References
==========
.. [1] https://www.probabilitycourse.com/chapter11/11_0_0_intro.php
.. [2] https://en.wikipedia.org/wiki/Poisson_point_process
"""
def __new__(cls, sym, lamda):
_value_check(lamda > 0, 'lamda should be a positive number.')
sym = _symbol_converter(sym)
lamda = _sympify(lamda)
return Basic.__new__(cls, sym, lamda)
@property
def lamda(self):
return self.args[1]
@property
def state_space(self):
return S.Naturals0
def distribution(self, key):
if isinstance(key, RandomIndexedSymbol):
self._deprecation_warn_distribution()
return PoissonDistribution(self.lamda*key.key)
return PoissonDistribution(self.lamda*key)
def density(self, x):
return (self.lamda*x.key)**x / factorial(x) * exp(-(self.lamda*x.key))
def simple_rv(self, rv):
return Poisson(rv.name, lamda=self.lamda*rv.key)
def __add__(self, other):
if not isinstance(other, PoissonProcess):
raise ValueError("Only instances of Poisson Process can be merged")
return PoissonProcess(Dummy(self.symbol.name + other.symbol.name),
self.lamda + other.lamda)
def split(self, l1, l2):
if _sympify(l1 + l2) != self.lamda:
raise ValueError("Sum of l1 and l2 should be %s" % str(self.lamda))
return PoissonProcess(Dummy("l1"), l1), PoissonProcess(Dummy("l2"), l2)
class WienerProcess(CountingProcess):
"""
The Wiener process is a real valued continuous-time stochastic process.
In physics it is used to study Brownian motion and therefore also known as
Brownian Motion.
Parameters
==========
sym: Symbol/str
Examples
========
>>> from sympy.stats import WienerProcess, P, E
>>> from sympy import symbols, Contains, Interval
>>> X = WienerProcess("X")
>>> X.state_space
Reals
>>> t1, t2 = symbols('t1 t2', positive=True)
>>> P(X(t1) < 7).simplify()
erf(7*sqrt(2)/(2*sqrt(t1)))/2 + 1/2
>>> P((X(t1) > 2) | (X(t1) < 4), Contains(t1, Interval.Ropen(2, 4))).simplify()
-erf(1)/2 + erf(2)/2 + 1
>>> E(X(t1))
0
>>> E(X(t1) + 2*X(t2), Contains(t1, Interval.Lopen(0, 1))
... & Contains(t2, Interval.Lopen(1, 2)))
0
References
==========
.. [1] https://www.probabilitycourse.com/chapter11/11_4_0_brownian_motion_wiener_process.php
.. [2] https://en.wikipedia.org/wiki/Wiener_process
"""
def __new__(cls, sym):
sym = _symbol_converter(sym)
return Basic.__new__(cls, sym)
@property
def state_space(self):
return S.Reals
def distribution(self, key):
if isinstance(key, RandomIndexedSymbol):
self._deprecation_warn_distribution()
return NormalDistribution(0, sqrt(key.key))
return NormalDistribution(0, sqrt(key))
def density(self, x):
return exp(-x**2/(2*x.key)) / (sqrt(2*pi)*sqrt(x.key))
def simple_rv(self, rv):
return Normal(rv.name, 0, sqrt(rv.key))
class GammaProcess(CountingProcess):
"""
A Gamma process is a random process with independent gamma distributed
increments. It is a pure-jump increasing Levy process.
Parameters
==========
sym: Symbol/str
lamda: Positive number
Jump size of the process, ``lamda > 0``
gamma: Positive number
Rate of jump arrivals, ``gamma > 0``
Examples
========
>>> from sympy.stats import GammaProcess, E, P, variance
>>> from sympy import symbols, Contains, Interval, Not
>>> t, d, x, l, g = symbols('t d x l g', positive=True)
>>> X = GammaProcess("X", l, g)
>>> E(X(t))
g*t/l
>>> variance(X(t)).simplify()
g*t/l**2
>>> X = GammaProcess('X', 1, 2)
>>> P(X(t) < 1).simplify()
lowergamma(2*t, 1)/gamma(2*t)
>>> P(Not((X(t) < 5) & (X(d) > 3)), Contains(t, Interval.Ropen(2, 4)) &
... Contains(d, Interval.Lopen(7, 8))).simplify()
-4*exp(-3) + 472*exp(-8)/3 + 1
>>> E(X(2) + x*E(X(5)))
10*x + 4
References
==========
.. [1] https://en.wikipedia.org/wiki/Gamma_process
"""
def __new__(cls, sym, lamda, gamma):
_value_check(lamda > 0, 'lamda should be a positive number')
_value_check(gamma > 0, 'gamma should be a positive number')
sym = _symbol_converter(sym)
gamma = _sympify(gamma)
lamda = _sympify(lamda)
return Basic.__new__(cls, sym, lamda, gamma)
@property
def lamda(self):
return self.args[1]
@property
def gamma(self):
return self.args[2]
@property
def state_space(self):
return _set_converter(Interval(0, oo))
def distribution(self, key):
if isinstance(key, RandomIndexedSymbol):
self._deprecation_warn_distribution()
return GammaDistribution(self.gamma*key.key, 1/self.lamda)
return GammaDistribution(self.gamma*key, 1/self.lamda)
def density(self, x):
k = self.gamma*x.key
theta = 1/self.lamda
return x**(k - 1) * exp(-x/theta) / (gamma(k)*theta**k)
def simple_rv(self, rv):
return Gamma(rv.name, self.gamma*rv.key, 1/self.lamda)
|
d5e59ee019303254e4353ae167fedfe176401e056c9721b1b706418e1705dfa8 | """
Generating and counting primes.
"""
import random
from bisect import bisect
from itertools import count
# Using arrays for sieving instead of lists greatly reduces
# memory consumption
from array import array as _array
from sympy.core.function import Function
from sympy.core.singleton import S
from .primetest import isprime
from sympy.utilities.misc import as_int
def _azeros(n):
return _array('l', [0]*n)
def _aset(*v):
return _array('l', v)
def _arange(a, b):
return _array('l', range(a, b))
class Sieve:
"""An infinite list of prime numbers, implemented as a dynamically
growing sieve of Eratosthenes. When a lookup is requested involving
an odd number that has not been sieved, the sieve is automatically
extended up to that number.
Examples
========
>>> from sympy import sieve
>>> sieve._reset() # this line for doctest only
>>> 25 in sieve
False
>>> sieve._list
array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23])
"""
# data shared (and updated) by all Sieve instances
def __init__(self):
self._n = 6
self._list = _aset(2, 3, 5, 7, 11, 13) # primes
self._tlist = _aset(0, 1, 1, 2, 2, 4) # totient
self._mlist = _aset(0, 1, -1, -1, 0, -1) # mobius
assert all(len(i) == self._n for i in (self._list, self._tlist, self._mlist))
def __repr__(self):
return ("<%s sieve (%i): %i, %i, %i, ... %i, %i\n"
"%s sieve (%i): %i, %i, %i, ... %i, %i\n"
"%s sieve (%i): %i, %i, %i, ... %i, %i>") % (
'prime', len(self._list),
self._list[0], self._list[1], self._list[2],
self._list[-2], self._list[-1],
'totient', len(self._tlist),
self._tlist[0], self._tlist[1],
self._tlist[2], self._tlist[-2], self._tlist[-1],
'mobius', len(self._mlist),
self._mlist[0], self._mlist[1],
self._mlist[2], self._mlist[-2], self._mlist[-1])
def _reset(self, prime=None, totient=None, mobius=None):
"""Reset all caches (default). To reset one or more set the
desired keyword to True."""
if all(i is None for i in (prime, totient, mobius)):
prime = totient = mobius = True
if prime:
self._list = self._list[:self._n]
if totient:
self._tlist = self._tlist[:self._n]
if mobius:
self._mlist = self._mlist[:self._n]
def extend(self, n):
"""Grow the sieve to cover all primes <= n (a real number).
Examples
========
>>> from sympy import sieve
>>> sieve._reset() # this line for doctest only
>>> sieve.extend(30)
>>> sieve[10] == 29
True
"""
n = int(n)
if n <= self._list[-1]:
return
# We need to sieve against all bases up to sqrt(n).
# This is a recursive call that will do nothing if there are enough
# known bases already.
maxbase = int(n**0.5) + 1
self.extend(maxbase)
# Create a new sieve starting from sqrt(n)
begin = self._list[-1] + 1
newsieve = _arange(begin, n + 1)
# Now eliminate all multiples of primes in [2, sqrt(n)]
for p in self.primerange(maxbase):
# Start counting at a multiple of p, offsetting
# the index to account for the new sieve's base index
startindex = (-begin) % p
for i in range(startindex, len(newsieve), p):
newsieve[i] = 0
# Merge the sieves
self._list += _array('l', [x for x in newsieve if x])
def extend_to_no(self, i):
"""Extend to include the ith prime number.
Parameters
==========
i : integer
Examples
========
>>> from sympy import sieve
>>> sieve._reset() # this line for doctest only
>>> sieve.extend_to_no(9)
>>> sieve._list
array('l', [2, 3, 5, 7, 11, 13, 17, 19, 23])
Notes
=====
The list is extended by 50% if it is too short, so it is
likely that it will be longer than requested.
"""
i = as_int(i)
while len(self._list) < i:
self.extend(int(self._list[-1] * 1.5))
def primerange(self, a, b=None):
"""Generate all prime numbers in the range [2, a) or [a, b).
Examples
========
>>> from sympy import sieve, prime
All primes less than 19:
>>> print([i for i in sieve.primerange(19)])
[2, 3, 5, 7, 11, 13, 17]
All primes greater than or equal to 7 and less than 19:
>>> print([i for i in sieve.primerange(7, 19)])
[7, 11, 13, 17]
All primes through the 10th prime
>>> list(sieve.primerange(prime(10) + 1))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
if b is None:
b = as_int(ceiling(a))
a = 2
else:
a = max(2, as_int(ceiling(a)))
b = as_int(ceiling(b))
if a >= b:
return
self.extend(b)
i = self.search(a)[1]
maxi = len(self._list) + 1
while i < maxi:
p = self._list[i - 1]
if p < b:
yield p
i += 1
else:
return
def totientrange(self, a, b):
"""Generate all totient numbers for the range [a, b).
Examples
========
>>> from sympy import sieve
>>> print([i for i in sieve.totientrange(7, 18)])
[6, 4, 6, 4, 10, 4, 12, 6, 8, 8, 16]
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
a = max(1, as_int(ceiling(a)))
b = as_int(ceiling(b))
n = len(self._tlist)
if a >= b:
return
elif b <= n:
for i in range(a, b):
yield self._tlist[i]
else:
self._tlist += _arange(n, b)
for i in range(1, n):
ti = self._tlist[i]
startindex = (n + i - 1) // i * i
for j in range(startindex, b, i):
self._tlist[j] -= ti
if i >= a:
yield ti
for i in range(n, b):
ti = self._tlist[i]
for j in range(2 * i, b, i):
self._tlist[j] -= ti
if i >= a:
yield ti
def mobiusrange(self, a, b):
"""Generate all mobius numbers for the range [a, b).
Parameters
==========
a : integer
First number in range
b : integer
First number outside of range
Examples
========
>>> from sympy import sieve
>>> print([i for i in sieve.mobiusrange(7, 18)])
[-1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1]
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
a = max(1, as_int(ceiling(a)))
b = as_int(ceiling(b))
n = len(self._mlist)
if a >= b:
return
elif b <= n:
for i in range(a, b):
yield self._mlist[i]
else:
self._mlist += _azeros(b - n)
for i in range(1, n):
mi = self._mlist[i]
startindex = (n + i - 1) // i * i
for j in range(startindex, b, i):
self._mlist[j] -= mi
if i >= a:
yield mi
for i in range(n, b):
mi = self._mlist[i]
for j in range(2 * i, b, i):
self._mlist[j] -= mi
if i >= a:
yield mi
def search(self, n):
"""Return the indices i, j of the primes that bound n.
If n is prime then i == j.
Although n can be an expression, if ceiling cannot convert
it to an integer then an n error will be raised.
Examples
========
>>> from sympy import sieve
>>> sieve.search(25)
(9, 10)
>>> sieve.search(23)
(9, 9)
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
test = as_int(ceiling(n))
n = as_int(n)
if n < 2:
raise ValueError("n should be >= 2 but got: %s" % n)
if n > self._list[-1]:
self.extend(n)
b = bisect(self._list, n)
if self._list[b - 1] == test:
return b, b
else:
return b, b + 1
def __contains__(self, n):
try:
n = as_int(n)
assert n >= 2
except (ValueError, AssertionError):
return False
if n % 2 == 0:
return n == 2
a, b = self.search(n)
return a == b
def __iter__(self):
for n in count(1):
yield self[n]
def __getitem__(self, n):
"""Return the nth prime number"""
if isinstance(n, slice):
self.extend_to_no(n.stop)
# Python 2.7 slices have 0 instead of None for start, so
# we can't default to 1.
start = n.start if n.start is not None else 0
if start < 1:
# sieve[:5] would be empty (starting at -1), let's
# just be explicit and raise.
raise IndexError("Sieve indices start at 1.")
return self._list[start - 1:n.stop - 1:n.step]
else:
if n < 1:
# offset is one, so forbid explicit access to sieve[0]
# (would surprisingly return the last one).
raise IndexError("Sieve indices start at 1.")
n = as_int(n)
self.extend_to_no(n)
return self._list[n - 1]
# Generate a global object for repeated use in trial division etc
sieve = Sieve()
def prime(nth):
r""" Return the nth prime, with the primes indexed as prime(1) = 2,
prime(2) = 3, etc.... The nth prime is approximately $n\log(n)$.
Logarithmic integral of $x$ is a pretty nice approximation for number of
primes $\le x$, i.e.
li(x) ~ pi(x)
In fact, for the numbers we are concerned about( x<1e11 ),
li(x) - pi(x) < 50000
Also,
li(x) > pi(x) can be safely assumed for the numbers which
can be evaluated by this function.
Here, we find the least integer m such that li(m) > n using binary search.
Now pi(m-1) < li(m-1) <= n,
We find pi(m - 1) using primepi function.
Starting from m, we have to find n - pi(m-1) more primes.
For the inputs this implementation can handle, we will have to test
primality for at max about 10**5 numbers, to get our answer.
Examples
========
>>> from sympy import prime
>>> prime(10)
29
>>> prime(1)
2
>>> prime(100000)
1299709
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
primepi : Return the number of primes less than or equal to n
References
==========
.. [1] https://en.wikipedia.org/wiki/Prime_number_theorem#Table_of_.CF.80.28x.29.2C_x_.2F_log_x.2C_and_li.28x.29
.. [2] https://en.wikipedia.org/wiki/Prime_number_theorem#Approximations_for_the_nth_prime_number
.. [3] https://en.wikipedia.org/wiki/Skewes%27_number
"""
n = as_int(nth)
if n < 1:
raise ValueError("nth must be a positive integer; prime(1) == 2")
if n <= len(sieve._list):
return sieve[n]
from sympy.functions.special.error_functions import li
from sympy.functions.elementary.exponential import log
a = 2 # Lower bound for binary search
b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
while a < b:
mid = (a + b) >> 1
if li(mid) > n:
b = mid
else:
a = mid + 1
n_primes = primepi(a - 1)
while n_primes < n:
if isprime(a):
n_primes += 1
a += 1
return a - 1
class primepi(Function):
r""" Represents the prime counting function pi(n) = the number
of prime numbers less than or equal to n.
Algorithm Description:
In sieve method, we remove all multiples of prime p
except p itself.
Let phi(i,j) be the number of integers 2 <= k <= i
which remain after sieving from primes less than
or equal to j.
Clearly, pi(n) = phi(n, sqrt(n))
If j is not a prime,
phi(i,j) = phi(i, j - 1)
if j is a prime,
We remove all numbers(except j) whose
smallest prime factor is j.
Let $x= j \times a$ be such a number, where $2 \le a \le i / j$
Now, after sieving from primes $\le j - 1$,
a must remain
(because x, and hence a has no prime factor $\le j - 1$)
Clearly, there are phi(i / j, j - 1) such a
which remain on sieving from primes $\le j - 1$
Now, if a is a prime less than equal to j - 1,
$x= j \times a$ has smallest prime factor = a, and
has already been removed(by sieving from a).
So, we don't need to remove it again.
(Note: there will be pi(j - 1) such x)
Thus, number of x, that will be removed are:
phi(i / j, j - 1) - phi(j - 1, j - 1)
(Note that pi(j - 1) = phi(j - 1, j - 1))
$\Rightarrow$ phi(i,j) = phi(i, j - 1) - phi(i / j, j - 1) + phi(j - 1, j - 1)
So,following recursion is used and implemented as dp:
phi(a, b) = phi(a, b - 1), if b is not a prime
phi(a, b) = phi(a, b-1)-phi(a / b, b-1) + phi(b-1, b-1), if b is prime
Clearly a is always of the form floor(n / k),
which can take at most $2\sqrt{n}$ values.
Two arrays arr1,arr2 are maintained
arr1[i] = phi(i, j),
arr2[i] = phi(n // i, j)
Finally the answer is arr2[1]
Examples
========
>>> from sympy import primepi, prime, prevprime, isprime
>>> primepi(25)
9
So there are 9 primes less than or equal to 25. Is 25 prime?
>>> isprime(25)
False
It isn't. So the first prime less than 25 must be the
9th prime:
>>> prevprime(25) == prime(9)
True
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
prime : Return the nth prime
"""
@classmethod
def eval(cls, n):
if n is S.Infinity:
return S.Infinity
if n is S.NegativeInfinity:
return S.Zero
try:
n = int(n)
except TypeError:
if n.is_real == False or n is S.NaN:
raise ValueError("n must be real")
return
if n < 2:
return S.Zero
if n <= sieve._list[-1]:
return S(sieve.search(n)[0])
lim = int(n ** 0.5)
lim -= 1
lim = max(lim, 0)
while lim * lim <= n:
lim += 1
lim -= 1
arr1 = [0] * (lim + 1)
arr2 = [0] * (lim + 1)
for i in range(1, lim + 1):
arr1[i] = i - 1
arr2[i] = n // i - 1
for i in range(2, lim + 1):
# Presently, arr1[k]=phi(k,i - 1),
# arr2[k] = phi(n // k,i - 1)
if arr1[i] == arr1[i - 1]:
continue
p = arr1[i - 1]
for j in range(1, min(n // (i * i), lim) + 1):
st = i * j
if st <= lim:
arr2[j] -= arr2[st] - p
else:
arr2[j] -= arr1[n // st] - p
lim2 = min(lim, i * i - 1)
for j in range(lim, lim2, -1):
arr1[j] -= arr1[j // i] - p
return S(arr2[1])
def nextprime(n, ith=1):
""" Return the ith prime greater than n.
i must be an integer.
Notes
=====
Potential primes are located at 6*j +/- 1. This
property is used during searching.
>>> from sympy import nextprime
>>> [(i, nextprime(i)) for i in range(10, 15)]
[(10, 11), (11, 13), (12, 13), (13, 17), (14, 17)]
>>> nextprime(2, ith=2) # the 2nd prime after 2
5
See Also
========
prevprime : Return the largest prime smaller than n
primerange : Generate all primes in a given range
"""
n = int(n)
i = as_int(ith)
if i > 1:
pr = n
j = 1
while 1:
pr = nextprime(pr)
j += 1
if j > i:
break
return pr
if n < 2:
return 2
if n < 7:
return {2: 3, 3: 5, 4: 5, 5: 7, 6: 7}[n]
if n <= sieve._list[-2]:
l, u = sieve.search(n)
if l == u:
return sieve[u + 1]
else:
return sieve[u]
nn = 6*(n//6)
if nn == n:
n += 1
if isprime(n):
return n
n += 4
elif n - nn == 5:
n += 2
if isprime(n):
return n
n += 4
else:
n = nn + 5
while 1:
if isprime(n):
return n
n += 2
if isprime(n):
return n
n += 4
def prevprime(n):
""" Return the largest prime smaller than n.
Notes
=====
Potential primes are located at 6*j +/- 1. This
property is used during searching.
>>> from sympy import prevprime
>>> [(i, prevprime(i)) for i in range(10, 15)]
[(10, 7), (11, 7), (12, 11), (13, 11), (14, 13)]
See Also
========
nextprime : Return the ith prime greater than n
primerange : Generates all primes in a given range
"""
from sympy.functions.elementary.integers import ceiling
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
n = as_int(ceiling(n))
if n < 3:
raise ValueError("no preceding primes")
if n < 8:
return {3: 2, 4: 3, 5: 3, 6: 5, 7: 5}[n]
if n <= sieve._list[-1]:
l, u = sieve.search(n)
if l == u:
return sieve[l-1]
else:
return sieve[l]
nn = 6*(n//6)
if n - nn <= 1:
n = nn - 1
if isprime(n):
return n
n -= 4
else:
n = nn + 1
while 1:
if isprime(n):
return n
n -= 2
if isprime(n):
return n
n -= 4
def primerange(a, b=None):
""" Generate a list of all prime numbers in the range [2, a),
or [a, b).
If the range exists in the default sieve, the values will
be returned from there; otherwise values will be returned
but will not modify the sieve.
Examples
========
>>> from sympy import primerange, prime
All primes less than 19:
>>> list(primerange(19))
[2, 3, 5, 7, 11, 13, 17]
All primes greater than or equal to 7 and less than 19:
>>> list(primerange(7, 19))
[7, 11, 13, 17]
All primes through the 10th prime
>>> list(primerange(prime(10) + 1))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
The Sieve method, primerange, is generally faster but it will
occupy more memory as the sieve stores values. The default
instance of Sieve, named sieve, can be used:
>>> from sympy import sieve
>>> list(sieve.primerange(1, 30))
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Notes
=====
Some famous conjectures about the occurrence of primes in a given
range are [1]:
- Twin primes: though often not, the following will give 2 primes
an infinite number of times:
primerange(6*n - 1, 6*n + 2)
- Legendre's: the following always yields at least one prime
primerange(n**2, (n+1)**2+1)
- Bertrand's (proven): there is always a prime in the range
primerange(n, 2*n)
- Brocard's: there are at least four primes in the range
primerange(prime(n)**2, prime(n+1)**2)
The average gap between primes is log(n) [2]; the gap between
primes can be arbitrarily large since sequences of composite
numbers are arbitrarily large, e.g. the numbers in the sequence
n! + 2, n! + 3 ... n! + n are all composite.
See Also
========
prime : Return the nth prime
nextprime : Return the ith prime greater than n
prevprime : Return the largest prime smaller than n
randprime : Returns a random prime in a given range
primorial : Returns the product of primes based on condition
Sieve.primerange : return range from already computed primes
or extend the sieve to contain the requested
range.
References
==========
.. [1] https://en.wikipedia.org/wiki/Prime_number
.. [2] http://primes.utm.edu/notes/gaps.html
"""
from sympy.functions.elementary.integers import ceiling
if b is None:
a, b = 2, a
if a >= b:
return
# if we already have the range, return it
if b <= sieve._list[-1]:
yield from sieve.primerange(a, b)
return
# otherwise compute, without storing, the desired range.
# wrapping ceiling in as_int will raise an error if there was a problem
# determining whether the expression was exactly an integer or not
a = as_int(ceiling(a)) - 1
b = as_int(ceiling(b))
while 1:
a = nextprime(a)
if a < b:
yield a
else:
return
def randprime(a, b):
""" Return a random prime number in the range [a, b).
Bertrand's postulate assures that
randprime(a, 2*a) will always succeed for a > 1.
Examples
========
>>> from sympy import randprime, isprime
>>> randprime(1, 30) #doctest: +SKIP
13
>>> isprime(randprime(1, 30))
True
See Also
========
primerange : Generate all primes in a given range
References
==========
.. [1] https://en.wikipedia.org/wiki/Bertrand's_postulate
"""
if a >= b:
return
a, b = map(int, (a, b))
n = random.randint(a - 1, b)
p = nextprime(n)
if p >= b:
p = prevprime(b)
if p < a:
raise ValueError("no primes exist in the specified range")
return p
def primorial(n, nth=True):
"""
Returns the product of the first n primes (default) or
the primes less than or equal to n (when ``nth=False``).
Examples
========
>>> from sympy.ntheory.generate import primorial, primerange
>>> from sympy import factorint, Mul, primefactors, sqrt
>>> primorial(4) # the first 4 primes are 2, 3, 5, 7
210
>>> primorial(4, nth=False) # primes <= 4 are 2 and 3
6
>>> primorial(1)
2
>>> primorial(1, nth=False)
1
>>> primorial(sqrt(101), nth=False)
210
One can argue that the primes are infinite since if you take
a set of primes and multiply them together (e.g. the primorial) and
then add or subtract 1, the result cannot be divided by any of the
original factors, hence either 1 or more new primes must divide this
product of primes.
In this case, the number itself is a new prime:
>>> factorint(primorial(4) + 1)
{211: 1}
In this case two new primes are the factors:
>>> factorint(primorial(4) - 1)
{11: 1, 19: 1}
Here, some primes smaller and larger than the primes multiplied together
are obtained:
>>> p = list(primerange(10, 20))
>>> sorted(set(primefactors(Mul(*p) + 1)).difference(set(p)))
[2, 5, 31, 149]
See Also
========
primerange : Generate all primes in a given range
"""
if nth:
n = as_int(n)
else:
n = int(n)
if n < 1:
raise ValueError("primorial argument must be >= 1")
p = 1
if nth:
for i in range(1, n + 1):
p *= prime(i)
else:
for i in primerange(2, n + 1):
p *= i
return p
def cycle_length(f, x0, nmax=None, values=False):
"""For a given iterated sequence, return a generator that gives
the length of the iterated cycle (lambda) and the length of terms
before the cycle begins (mu); if ``values`` is True then the
terms of the sequence will be returned instead. The sequence is
started with value ``x0``.
Note: more than the first lambda + mu terms may be returned and this
is the cost of cycle detection with Brent's method; there are, however,
generally less terms calculated than would have been calculated if the
proper ending point were determined, e.g. by using Floyd's method.
>>> from sympy.ntheory.generate import cycle_length
This will yield successive values of i <-- func(i):
>>> def iter(func, i):
... while 1:
... ii = func(i)
... yield ii
... i = ii
...
A function is defined:
>>> func = lambda i: (i**2 + 1) % 51
and given a seed of 4 and the mu and lambda terms calculated:
>>> next(cycle_length(func, 4))
(6, 2)
We can see what is meant by looking at the output:
>>> n = cycle_length(func, 4, values=True)
>>> list(ni for ni in n)
[17, 35, 2, 5, 26, 14, 44, 50, 2, 5, 26, 14]
There are 6 repeating values after the first 2.
If a sequence is suspected of being longer than you might wish, ``nmax``
can be used to exit early (and mu will be returned as None):
>>> next(cycle_length(func, 4, nmax = 4))
(4, None)
>>> [ni for ni in cycle_length(func, 4, nmax = 4, values=True)]
[17, 35, 2, 5]
Code modified from:
https://en.wikipedia.org/wiki/Cycle_detection.
"""
nmax = int(nmax or 0)
# main phase: search successive powers of two
power = lam = 1
tortoise, hare = x0, f(x0) # f(x0) is the element/node next to x0.
i = 0
while tortoise != hare and (not nmax or i < nmax):
i += 1
if power == lam: # time to start a new power of two?
tortoise = hare
power *= 2
lam = 0
if values:
yield hare
hare = f(hare)
lam += 1
if nmax and i == nmax:
if values:
return
else:
yield nmax, None
return
if not values:
# Find the position of the first repetition of length lambda
mu = 0
tortoise = hare = x0
for i in range(lam):
hare = f(hare)
while tortoise != hare:
tortoise = f(tortoise)
hare = f(hare)
mu += 1
if mu:
mu -= 1
yield lam, mu
def composite(nth):
""" Return the nth composite number, with the composite numbers indexed as
composite(1) = 4, composite(2) = 6, etc....
Examples
========
>>> from sympy import composite
>>> composite(36)
52
>>> composite(1)
4
>>> composite(17737)
20000
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
primepi : Return the number of primes less than or equal to n
prime : Return the nth prime
compositepi : Return the number of positive composite numbers less than or equal to n
"""
n = as_int(nth)
if n < 1:
raise ValueError("nth must be a positive integer; composite(1) == 4")
composite_arr = [4, 6, 8, 9, 10, 12, 14, 15, 16, 18]
if n <= 10:
return composite_arr[n - 1]
a, b = 4, sieve._list[-1]
if n <= b - primepi(b) - 1:
while a < b - 1:
mid = (a + b) >> 1
if mid - primepi(mid) - 1 > n:
b = mid
else:
a = mid
if isprime(a):
a -= 1
return a
from sympy.functions.special.error_functions import li
from sympy.functions.elementary.exponential import log
a = 4 # Lower bound for binary search
b = int(n*(log(n) + log(log(n)))) # Upper bound for the search.
while a < b:
mid = (a + b) >> 1
if mid - li(mid) - 1 > n:
b = mid
else:
a = mid + 1
n_composites = a - primepi(a) - 1
while n_composites > n:
if not isprime(a):
n_composites -= 1
a -= 1
if isprime(a):
a -= 1
return a
def compositepi(n):
""" Return the number of positive composite numbers less than or equal to n.
The first positive composite is 4, i.e. compositepi(4) = 1.
Examples
========
>>> from sympy import compositepi
>>> compositepi(25)
15
>>> compositepi(1000)
831
See Also
========
sympy.ntheory.primetest.isprime : Test if n is prime
primerange : Generate all primes in a given range
prime : Return the nth prime
primepi : Return the number of primes less than or equal to n
composite : Return the nth composite number
"""
n = int(n)
if n < 4:
return 0
return n - primepi(n) - 1
|
2701b8379dd57d5d06167cdf69e3326d416b3907dad005dacc582e385fa4b8b9 | """
Integer factorization
"""
from collections import defaultdict
import random
import math
from sympy.core import sympify
from sympy.core.containers import Dict
from sympy.core.evalf import bitcount
from sympy.core.expr import Expr
from sympy.core.function import Function
from sympy.core.logic import fuzzy_and
from sympy.core.mul import Mul, prod
from sympy.core.numbers import igcd, ilcm, Rational, Integer
from sympy.core.power import integer_nthroot, Pow, integer_log
from sympy.core.singleton import S
from sympy.external.gmpy import SYMPY_INTS
from .primetest import isprime
from .generate import sieve, primerange, nextprime
from .digits import digits
from sympy.utilities.iterables import flatten
from sympy.utilities.misc import as_int, filldedent
from .ecm import _ecm_one_factor
# Note: This list should be updated whenever new Mersenne primes are found.
# Refer: https://www.mersenne.org/
MERSENNE_PRIME_EXPONENTS = (2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607, 1279, 2203,
2281, 3217, 4253, 4423, 9689, 9941, 11213, 19937, 21701, 23209, 44497, 86243, 110503, 132049,
216091, 756839, 859433, 1257787, 1398269, 2976221, 3021377, 6972593, 13466917, 20996011, 24036583,
25964951, 30402457, 32582657, 37156667, 42643801, 43112609, 57885161, 74207281, 77232917, 82589933)
# compute more when needed for i in Mersenne prime exponents
PERFECT = [6] # 2**(i-1)*(2**i-1)
MERSENNES = [3] # 2**i - 1
def _ismersenneprime(n):
global MERSENNES
j = len(MERSENNES)
while n > MERSENNES[-1] and j < len(MERSENNE_PRIME_EXPONENTS):
# conservatively grow the list
MERSENNES.append(2**MERSENNE_PRIME_EXPONENTS[j] - 1)
j += 1
return n in MERSENNES
def _isperfect(n):
global PERFECT
if n % 2 == 0:
j = len(PERFECT)
while n > PERFECT[-1] and j < len(MERSENNE_PRIME_EXPONENTS):
# conservatively grow the list
t = 2**(MERSENNE_PRIME_EXPONENTS[j] - 1)
PERFECT.append(t*(2*t - 1))
j += 1
return n in PERFECT
small_trailing = [0] * 256
for j in range(1,8):
small_trailing[1<<j::1<<(j+1)] = [j] * (1<<(7-j))
def smoothness(n):
"""
Return the B-smooth and B-power smooth values of n.
The smoothness of n is the largest prime factor of n; the power-
smoothness is the largest divisor raised to its multiplicity.
Examples
========
>>> from sympy.ntheory.factor_ import smoothness
>>> smoothness(2**7*3**2)
(3, 128)
>>> smoothness(2**4*13)
(13, 16)
>>> smoothness(2)
(2, 2)
See Also
========
factorint, smoothness_p
"""
if n == 1:
return (1, 1) # not prime, but otherwise this causes headaches
facs = factorint(n)
return max(facs), max(m**facs[m] for m in facs)
def smoothness_p(n, m=-1, power=0, visual=None):
"""
Return a list of [m, (p, (M, sm(p + m), psm(p + m)))...]
where:
1. p**M is the base-p divisor of n
2. sm(p + m) is the smoothness of p + m (m = -1 by default)
3. psm(p + m) is the power smoothness of p + m
The list is sorted according to smoothness (default) or by power smoothness
if power=1.
The smoothness of the numbers to the left (m = -1) or right (m = 1) of a
factor govern the results that are obtained from the p +/- 1 type factoring
methods.
>>> from sympy.ntheory.factor_ import smoothness_p, factorint
>>> smoothness_p(10431, m=1)
(1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
>>> smoothness_p(10431)
(-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
>>> smoothness_p(10431, power=1)
(-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
If visual=True then an annotated string will be returned:
>>> print(smoothness_p(21477639576571, visual=1))
p**i=4410317**1 has p-1 B=1787, B-pow=1787
p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
This string can also be generated directly from a factorization dictionary
and vice versa:
>>> factorint(17*9)
{3: 2, 17: 1}
>>> smoothness_p(_)
'p**i=3**2 has p-1 B=2, B-pow=2\\np**i=17**1 has p-1 B=2, B-pow=16'
>>> smoothness_p(_)
{3: 2, 17: 1}
The table of the output logic is:
====== ====== ======= =======
| Visual
------ ----------------------
Input True False other
====== ====== ======= =======
dict str tuple str
str str tuple dict
tuple str tuple str
n str tuple tuple
mul str tuple tuple
====== ====== ======= =======
See Also
========
factorint, smoothness
"""
# visual must be True, False or other (stored as None)
if visual in (1, 0):
visual = bool(visual)
elif visual not in (True, False):
visual = None
if isinstance(n, str):
if visual:
return n
d = {}
for li in n.splitlines():
k, v = [int(i) for i in
li.split('has')[0].split('=')[1].split('**')]
d[k] = v
if visual is not True and visual is not False:
return d
return smoothness_p(d, visual=False)
elif not isinstance(n, tuple):
facs = factorint(n, visual=False)
if power:
k = -1
else:
k = 1
if isinstance(n, tuple):
rv = n
else:
rv = (m, sorted([(f,
tuple([M] + list(smoothness(f + m))))
for f, M in [i for i in facs.items()]],
key=lambda x: (x[1][k], x[0])))
if visual is False or (visual is not True) and (type(n) in [int, Mul]):
return rv
lines = []
for dat in rv[1]:
dat = flatten(dat)
dat.insert(2, m)
lines.append('p**i=%i**%i has p%+i B=%i, B-pow=%i' % tuple(dat))
return '\n'.join(lines)
def trailing(n):
"""Count the number of trailing zero digits in the binary
representation of n, i.e. determine the largest power of 2
that divides n.
Examples
========
>>> from sympy import trailing
>>> trailing(128)
7
>>> trailing(63)
0
"""
n = abs(int(n))
if not n:
return 0
low_byte = n & 0xff
if low_byte:
return small_trailing[low_byte]
# 2**m is quick for z up through 2**30
z = bitcount(n) - 1
if isinstance(z, SYMPY_INTS):
if n == 1 << z:
return z
if z < 300:
# fixed 8-byte reduction
t = 8
n >>= 8
while not n & 0xff:
n >>= 8
t += 8
return t + small_trailing[n & 0xff]
# binary reduction important when there might be a large
# number of trailing 0s
t = 0
p = 8
while not n & 1:
while not n & ((1 << p) - 1):
n >>= p
t += p
p *= 2
p //= 2
return t
def multiplicity(p, n):
"""
Find the greatest integer m such that p**m divides n.
Examples
========
>>> from sympy import multiplicity, Rational
>>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]]
[0, 1, 2, 3, 3]
>>> multiplicity(3, Rational(1, 9))
-2
Note: when checking for the multiplicity of a number in a
large factorial it is most efficient to send it as an unevaluated
factorial or to call ``multiplicity_in_factorial`` directly:
>>> from sympy.ntheory import multiplicity_in_factorial
>>> from sympy import factorial
>>> p = factorial(25)
>>> n = 2**100
>>> nfac = factorial(n, evaluate=False)
>>> multiplicity(p, nfac)
52818775009509558395695966887
>>> _ == multiplicity_in_factorial(p, n)
True
"""
from sympy.functions.combinatorial.factorials import factorial
try:
p, n = as_int(p), as_int(n)
except ValueError:
if all(isinstance(i, (SYMPY_INTS, Rational)) for i in (p, n)):
p = Rational(p)
n = Rational(n)
if p.q == 1:
if n.p == 1:
return -multiplicity(p.p, n.q)
return multiplicity(p.p, n.p) - multiplicity(p.p, n.q)
elif p.p == 1:
return multiplicity(p.q, n.q)
else:
like = min(
multiplicity(p.p, n.p),
multiplicity(p.q, n.q))
cross = min(
multiplicity(p.q, n.p),
multiplicity(p.p, n.q))
return like - cross
elif (isinstance(p, (SYMPY_INTS, Integer)) and
isinstance(n, factorial) and
isinstance(n.args[0], Integer) and
n.args[0] >= 0):
return multiplicity_in_factorial(p, n.args[0])
raise ValueError('expecting ints or fractions, got %s and %s' % (p, n))
if n == 0:
raise ValueError('no such integer exists: multiplicity of %s is not-defined' %(n))
if p == 2:
return trailing(n)
if p < 2:
raise ValueError('p must be an integer, 2 or larger, but got %s' % p)
if p == n:
return 1
m = 0
n, rem = divmod(n, p)
while not rem:
m += 1
if m > 5:
# The multiplicity could be very large. Better
# to increment in powers of two
e = 2
while 1:
ppow = p**e
if ppow < n:
nnew, rem = divmod(n, ppow)
if not rem:
m += e
e *= 2
n = nnew
continue
return m + multiplicity(p, n)
n, rem = divmod(n, p)
return m
def multiplicity_in_factorial(p, n):
"""return the largest integer ``m`` such that ``p**m`` divides ``n!``
without calculating the factorial of ``n``.
Examples
========
>>> from sympy.ntheory import multiplicity_in_factorial
>>> from sympy import factorial
>>> multiplicity_in_factorial(2, 3)
1
An instructive use of this is to tell how many trailing zeros
a given factorial has. For example, there are 6 in 25!:
>>> factorial(25)
15511210043330985984000000
>>> multiplicity_in_factorial(10, 25)
6
For large factorials, it is much faster/feasible to use
this function rather than computing the actual factorial:
>>> multiplicity_in_factorial(factorial(25), 2**100)
52818775009509558395695966887
"""
p, n = as_int(p), as_int(n)
if p <= 0:
raise ValueError('expecting positive integer got %s' % p )
if n < 0:
raise ValueError('expecting non-negative integer got %s' % n )
factors = factorint(p)
# keep only the largest of a given multiplicity since those
# of a given multiplicity will be goverened by the behavior
# of the largest factor
test = defaultdict(int)
for k, v in factors.items():
test[v] = max(k, test[v])
keep = set(test.values())
# remove others from factors
for k in list(factors.keys()):
if k not in keep:
factors.pop(k)
mp = S.Infinity
for i in factors:
# multiplicity of i in n! is
mi = (n - (sum(digits(n, i)) - i))//(i - 1)
# multiplicity of p in n! depends on multiplicity
# of prime `i` in p, so we floor divide by factors[i]
# and keep it if smaller than the multiplicity of p
# seen so far
mp = min(mp, mi//factors[i])
return mp
def perfect_power(n, candidates=None, big=True, factor=True):
"""
Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a unique
perfect power with ``e > 1``, else ``False`` (e.g. 1 is not a
perfect power). A ValueError is raised if ``n`` is not Rational.
By default, the base is recursively decomposed and the exponents
collected so the largest possible ``e`` is sought. If ``big=False``
then the smallest possible ``e`` (thus prime) will be chosen.
If ``factor=True`` then simultaneous factorization of ``n`` is
attempted since finding a factor indicates the only possible root
for ``n``. This is True by default since only a few small factors will
be tested in the course of searching for the perfect power.
The use of ``candidates`` is primarily for internal use; if provided,
False will be returned if ``n`` cannot be written as a power with one
of the candidates as an exponent and factoring (beyond testing for
a factor of 2) will not be attempted.
Examples
========
>>> from sympy import perfect_power, Rational
>>> perfect_power(16)
(2, 4)
>>> perfect_power(16, big=False)
(4, 2)
Negative numbers can only have odd perfect powers:
>>> perfect_power(-4)
False
>>> perfect_power(-8)
(-2, 3)
Rationals are also recognized:
>>> perfect_power(Rational(1, 2)**3)
(1/2, 3)
>>> perfect_power(Rational(-3, 2)**3)
(-3/2, 3)
Notes
=====
To know whether an integer is a perfect power of 2 use
>>> is2pow = lambda n: bool(n and not n & (n - 1))
>>> [(i, is2pow(i)) for i in range(5)]
[(0, False), (1, True), (2, True), (3, False), (4, True)]
It is not necessary to provide ``candidates``. When provided
it will be assumed that they are ints. The first one that is
larger than the computed maximum possible exponent will signal
failure for the routine.
>>> perfect_power(3**8, [9])
False
>>> perfect_power(3**8, [2, 4, 8])
(3, 8)
>>> perfect_power(3**8, [4, 8], big=False)
(9, 4)
See Also
========
sympy.core.power.integer_nthroot
sympy.ntheory.primetest.is_square
"""
if isinstance(n, Rational) and not n.is_Integer:
p, q = n.as_numer_denom()
if p is S.One:
pp = perfect_power(q)
if pp:
pp = (n.func(1, pp[0]), pp[1])
else:
pp = perfect_power(p)
if pp:
num, e = pp
pq = perfect_power(q, [e])
if pq:
den, _ = pq
pp = n.func(num, den), e
return pp
n = as_int(n)
if n < 0:
pp = perfect_power(-n)
if pp:
b, e = pp
if e % 2:
return -b, e
return False
if n <= 3:
# no unique exponent for 0, 1
# 2 and 3 have exponents of 1
return False
logn = math.log(n, 2)
max_possible = int(logn) + 2 # only check values less than this
not_square = n % 10 in [2, 3, 7, 8] # squares cannot end in 2, 3, 7, 8
min_possible = 2 + not_square
if not candidates:
candidates = primerange(min_possible, max_possible)
else:
candidates = sorted([i for i in candidates
if min_possible <= i < max_possible])
if n%2 == 0:
e = trailing(n)
candidates = [i for i in candidates if e%i == 0]
if big:
candidates = reversed(candidates)
for e in candidates:
r, ok = integer_nthroot(n, e)
if ok:
return (r, e)
return False
def _factors():
rv = 2 + n % 2
while True:
yield rv
rv = nextprime(rv)
for fac, e in zip(_factors(), candidates):
# see if there is a factor present
if factor and n % fac == 0:
# find what the potential power is
if fac == 2:
e = trailing(n)
else:
e = multiplicity(fac, n)
# if it's a trivial power we are done
if e == 1:
return False
# maybe the e-th root of n is exact
r, exact = integer_nthroot(n, e)
if not exact:
# Having a factor, we know that e is the maximal
# possible value for a root of n.
# If n = fac**e*m can be written as a perfect
# power then see if m can be written as r**E where
# gcd(e, E) != 1 so n = (fac**(e//E)*r)**E
m = n//fac**e
rE = perfect_power(m, candidates=divisors(e, generator=True))
if not rE:
return False
else:
r, E = rE
r, e = fac**(e//E)*r, E
if not big:
e0 = primefactors(e)
if e0[0] != e:
r, e = r**(e//e0[0]), e0[0]
return r, e
# Weed out downright impossible candidates
if logn/e < 40:
b = 2.0**(logn/e)
if abs(int(b + 0.5) - b) > 0.01:
continue
# now see if the plausible e makes a perfect power
r, exact = integer_nthroot(n, e)
if exact:
if big:
m = perfect_power(r, big=big, factor=factor)
if m:
r, e = m[0], e*m[1]
return int(r), e
return False
def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None):
r"""
Use Pollard's rho method to try to extract a nontrivial factor
of ``n``. The returned factor may be a composite number. If no
factor is found, ``None`` is returned.
The algorithm generates pseudo-random values of x with a generator
function, replacing x with F(x). If F is not supplied then the
function x**2 + ``a`` is used. The first value supplied to F(x) is ``s``.
Upon failure (if ``retries`` is > 0) a new ``a`` and ``s`` will be
supplied; the ``a`` will be ignored if F was supplied.
The sequence of numbers generated by such functions generally have a
a lead-up to some number and then loop around back to that number and
begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 -- this leader
and loop look a bit like the Greek letter rho, and thus the name, 'rho'.
For a given function, very different leader-loop values can be obtained
so it is a good idea to allow for retries:
>>> from sympy.ntheory.generate import cycle_length
>>> n = 16843009
>>> F = lambda x:(2048*pow(x, 2, n) + 32767) % n
>>> for s in range(5):
... print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s)))
...
loop length = 2489; leader length = 42
loop length = 78; leader length = 120
loop length = 1482; leader length = 99
loop length = 1482; leader length = 285
loop length = 1482; leader length = 100
Here is an explicit example where there is a two element leadup to
a sequence of 3 numbers (11, 14, 4) that then repeat:
>>> x=2
>>> for i in range(9):
... x=(x**2+12)%17
... print(x)
...
16
13
11
14
4
11
14
4
11
>>> next(cycle_length(lambda x: (x**2+12)%17, 2))
(3, 2)
>>> list(cycle_length(lambda x: (x**2+12)%17, 2, values=True))
[16, 13, 11, 14, 4]
Instead of checking the differences of all generated values for a gcd
with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd,
2nd and 4th, 3rd and 6th until it has been detected that the loop has been
traversed. Loops may be many thousands of steps long before rho finds a
factor or reports failure. If ``max_steps`` is specified, the iteration
is cancelled with a failure after the specified number of steps.
Examples
========
>>> from sympy import pollard_rho
>>> n=16843009
>>> F=lambda x:(2048*pow(x,2,n) + 32767) % n
>>> pollard_rho(n, F=F)
257
Use the default setting with a bad value of ``a`` and no retries:
>>> pollard_rho(n, a=n-2, retries=0)
If retries is > 0 then perhaps the problem will correct itself when
new values are generated for a:
>>> pollard_rho(n, a=n-2, retries=1)
257
References
==========
.. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
A Computational Perspective", Springer, 2nd edition, 229-231
"""
n = int(n)
if n < 5:
raise ValueError('pollard_rho should receive n > 4')
prng = random.Random(seed + retries)
V = s
for i in range(retries + 1):
U = V
if not F:
F = lambda x: (pow(x, 2, n) + a) % n
j = 0
while 1:
if max_steps and (j > max_steps):
break
j += 1
U = F(U)
V = F(F(V)) # V is 2x further along than U
g = igcd(U - V, n)
if g == 1:
continue
if g == n:
break
return int(g)
V = prng.randint(0, n - 1)
a = prng.randint(1, n - 3) # for x**2 + a, a%n should not be 0 or -2
F = None
return None
def pollard_pm1(n, B=10, a=2, retries=0, seed=1234):
"""
Use Pollard's p-1 method to try to extract a nontrivial factor
of ``n``. Either a divisor (perhaps composite) or ``None`` is returned.
The value of ``a`` is the base that is used in the test gcd(a**M - 1, n).
The default is 2. If ``retries`` > 0 then if no factor is found after the
first attempt, a new ``a`` will be generated randomly (using the ``seed``)
and the process repeated.
Note: the value of M is lcm(1..B) = reduce(ilcm, range(2, B + 1)).
A search is made for factors next to even numbers having a power smoothness
less than ``B``. Choosing a larger B increases the likelihood of finding a
larger factor but takes longer. Whether a factor of n is found or not
depends on ``a`` and the power smoothness of the even number just less than
the factor p (hence the name p - 1).
Although some discussion of what constitutes a good ``a`` some
descriptions are hard to interpret. At the modular.math site referenced
below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1
for every prime power divisor of N. But consider the following:
>>> from sympy.ntheory.factor_ import smoothness_p, pollard_pm1
>>> n=257*1009
>>> smoothness_p(n)
(-1, [(257, (1, 2, 256)), (1009, (1, 7, 16))])
So we should (and can) find a root with B=16:
>>> pollard_pm1(n, B=16, a=3)
1009
If we attempt to increase B to 256 we find that it doesn't work:
>>> pollard_pm1(n, B=256)
>>>
But if the value of ``a`` is changed we find that only multiples of
257 work, e.g.:
>>> pollard_pm1(n, B=256, a=257)
1009
Checking different ``a`` values shows that all the ones that didn't
work had a gcd value not equal to ``n`` but equal to one of the
factors:
>>> from sympy import ilcm, igcd, factorint, Pow
>>> M = 1
>>> for i in range(2, 256):
... M = ilcm(M, i)
...
>>> set([igcd(pow(a, M, n) - 1, n) for a in range(2, 256) if
... igcd(pow(a, M, n) - 1, n) != n])
{1009}
But does aM % d for every divisor of n give 1?
>>> aM = pow(255, M, n)
>>> [(d, aM%Pow(*d.args)) for d in factorint(n, visual=True).args]
[(257**1, 1), (1009**1, 1)]
No, only one of them. So perhaps the principle is that a root will
be found for a given value of B provided that:
1) the power smoothness of the p - 1 value next to the root
does not exceed B
2) a**M % p != 1 for any of the divisors of n.
By trying more than one ``a`` it is possible that one of them
will yield a factor.
Examples
========
With the default smoothness bound, this number cannot be cracked:
>>> from sympy.ntheory import pollard_pm1
>>> pollard_pm1(21477639576571)
Increasing the smoothness bound helps:
>>> pollard_pm1(21477639576571, B=2000)
4410317
Looking at the smoothness of the factors of this number we find:
>>> from sympy.ntheory.factor_ import smoothness_p, factorint
>>> print(smoothness_p(21477639576571, visual=1))
p**i=4410317**1 has p-1 B=1787, B-pow=1787
p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
The B and B-pow are the same for the p - 1 factorizations of the divisors
because those factorizations had a very large prime factor:
>>> factorint(4410317 - 1)
{2: 2, 617: 1, 1787: 1}
>>> factorint(4869863-1)
{2: 1, 2434931: 1}
Note that until B reaches the B-pow value of 1787, the number is not cracked;
>>> pollard_pm1(21477639576571, B=1786)
>>> pollard_pm1(21477639576571, B=1787)
4410317
The B value has to do with the factors of the number next to the divisor,
not the divisors themselves. A worst case scenario is that the number next
to the factor p has a large prime divisisor or is a perfect power. If these
conditions apply then the power-smoothness will be about p/2 or p. The more
realistic is that there will be a large prime factor next to p requiring
a B value on the order of p/2. Although primes may have been searched for
up to this level, the p/2 is a factor of p - 1, something that we do not
know. The modular.math reference below states that 15% of numbers in the
range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6
will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the
percentages are nearly reversed...but in that range the simple trial
division is quite fast.
References
==========
.. [1] Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
A Computational Perspective", Springer, 2nd edition, 236-238
.. [2] http://modular.math.washington.edu/edu/2007/spring/ent/ent-html/node81.html
.. [3] https://www.cs.toronto.edu/~yuvalf/Factorization.pdf
"""
n = int(n)
if n < 4 or B < 3:
raise ValueError('pollard_pm1 should receive n > 3 and B > 2')
prng = random.Random(seed + B)
# computing a**lcm(1,2,3,..B) % n for B > 2
# it looks weird, but it's right: primes run [2, B]
# and the answer's not right until the loop is done.
for i in range(retries + 1):
aM = a
for p in sieve.primerange(2, B + 1):
e = int(math.log(B, p))
aM = pow(aM, pow(p, e), n)
g = igcd(aM - 1, n)
if 1 < g < n:
return int(g)
# get a new a:
# since the exponent, lcm(1..B), is even, if we allow 'a' to be 'n-1'
# then (n - 1)**even % n will be 1 which will give a g of 0 and 1 will
# give a zero, too, so we set the range as [2, n-2]. Some references
# say 'a' should be coprime to n, but either will detect factors.
a = prng.randint(2, n - 2)
def _trial(factors, n, candidates, verbose=False):
"""
Helper function for integer factorization. Trial factors ``n`
against all integers given in the sequence ``candidates``
and updates the dict ``factors`` in-place. Returns the reduced
value of ``n`` and a flag indicating whether any factors were found.
"""
if verbose:
factors0 = list(factors.keys())
nfactors = len(factors)
for d in candidates:
if n % d == 0:
m = multiplicity(d, n)
n //= d**m
factors[d] = m
if verbose:
for k in sorted(set(factors).difference(set(factors0))):
print(factor_msg % (k, factors[k]))
return int(n), len(factors) != nfactors
def _check_termination(factors, n, limitp1, use_trial, use_rho, use_pm1,
verbose):
"""
Helper function for integer factorization. Checks if ``n``
is a prime or a perfect power, and in those cases updates
the factorization and raises ``StopIteration``.
"""
if verbose:
print('Check for termination')
# since we've already been factoring there is no need to do
# simultaneous factoring with the power check
p = perfect_power(n, factor=False)
if p is not False:
base, exp = p
if limitp1:
limit = limitp1 - 1
else:
limit = limitp1
facs = factorint(base, limit, use_trial, use_rho, use_pm1,
verbose=False)
for b, e in facs.items():
if verbose:
print(factor_msg % (b, e))
factors[b] = exp*e
raise StopIteration
if isprime(n):
factors[int(n)] = 1
raise StopIteration
if n == 1:
raise StopIteration
trial_int_msg = "Trial division with ints [%i ... %i] and fail_max=%i"
trial_msg = "Trial division with primes [%i ... %i]"
rho_msg = "Pollard's rho with retries %i, max_steps %i and seed %i"
pm1_msg = "Pollard's p-1 with smoothness bound %i and seed %i"
ecm_msg = "Elliptic Curve with B1 bound %i, B2 bound %i, num_curves %i"
factor_msg = '\t%i ** %i'
fermat_msg = 'Close factors satisying Fermat condition found.'
complete_msg = 'Factorization is complete.'
def _factorint_small(factors, n, limit, fail_max):
"""
Return the value of n and either a 0 (indicating that factorization up
to the limit was complete) or else the next near-prime that would have
been tested.
Factoring stops if there are fail_max unsuccessful tests in a row.
If factors of n were found they will be in the factors dictionary as
{factor: multiplicity} and the returned value of n will have had those
factors removed. The factors dictionary is modified in-place.
"""
def done(n, d):
"""return n, d if the sqrt(n) wasn't reached yet, else
n, 0 indicating that factoring is done.
"""
if d*d <= n:
return n, d
return n, 0
d = 2
m = trailing(n)
if m:
factors[d] = m
n >>= m
d = 3
if limit < d:
if n > 1:
factors[n] = 1
return done(n, d)
# reduce
m = 0
while n % d == 0:
n //= d
m += 1
if m == 20:
mm = multiplicity(d, n)
m += mm
n //= d**mm
break
if m:
factors[d] = m
# when d*d exceeds maxx or n we are done; if limit**2 is greater
# than n then maxx is set to zero so the value of n will flag the finish
if limit*limit > n:
maxx = 0
else:
maxx = limit*limit
dd = maxx or n
d = 5
fails = 0
while fails < fail_max:
if d*d > dd:
break
# d = 6*i - 1
# reduce
m = 0
while n % d == 0:
n //= d
m += 1
if m == 20:
mm = multiplicity(d, n)
m += mm
n //= d**mm
break
if m:
factors[d] = m
dd = maxx or n
fails = 0
else:
fails += 1
d += 2
if d*d > dd:
break
# d = 6*i - 1
# reduce
m = 0
while n % d == 0:
n //= d
m += 1
if m == 20:
mm = multiplicity(d, n)
m += mm
n //= d**mm
break
if m:
factors[d] = m
dd = maxx or n
fails = 0
else:
fails += 1
# d = 6*(i + 1) - 1
d += 4
return done(n, d)
def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True,
use_ecm=True, verbose=False, visual=None, multiple=False):
r"""
Given a positive integer ``n``, ``factorint(n)`` returns a dict containing
the prime factors of ``n`` as keys and their respective multiplicities
as values. For example:
>>> from sympy.ntheory import factorint
>>> factorint(2000) # 2000 = (2**4) * (5**3)
{2: 4, 5: 3}
>>> factorint(65537) # This number is prime
{65537: 1}
For input less than 2, factorint behaves as follows:
- ``factorint(1)`` returns the empty factorization, ``{}``
- ``factorint(0)`` returns ``{0:1}``
- ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n``
Partial Factorization:
If ``limit`` (> 3) is specified, the search is stopped after performing
trial division up to (and including) the limit (or taking a
corresponding number of rho/p-1 steps). This is useful if one has
a large number and only is interested in finding small factors (if
any). Note that setting a limit does not prevent larger factors
from being found early; it simply means that the largest factor may
be composite. Since checking for perfect power is relatively cheap, it is
done regardless of the limit setting.
This number, for example, has two small factors and a huge
semi-prime factor that cannot be reduced easily:
>>> from sympy.ntheory import isprime
>>> a = 1407633717262338957430697921446883
>>> f = factorint(a, limit=10000)
>>> f == {991: 1, int(202916782076162456022877024859): 1, 7: 1}
True
>>> isprime(max(f))
False
This number has a small factor and a residual perfect power whose
base is greater than the limit:
>>> factorint(3*101**7, limit=5)
{3: 1, 101: 7}
List of Factors:
If ``multiple`` is set to ``True`` then a list containing the
prime factors including multiplicities is returned.
>>> factorint(24, multiple=True)
[2, 2, 2, 3]
Visual Factorization:
If ``visual`` is set to ``True``, then it will return a visual
factorization of the integer. For example:
>>> from sympy import pprint
>>> pprint(factorint(4200, visual=True))
3 1 2 1
2 *3 *5 *7
Note that this is achieved by using the evaluate=False flag in Mul
and Pow. If you do other manipulations with an expression where
evaluate=False, it may evaluate. Therefore, you should use the
visual option only for visualization, and use the normal dictionary
returned by visual=False if you want to perform operations on the
factors.
You can easily switch between the two forms by sending them back to
factorint:
>>> from sympy import Mul
>>> regular = factorint(1764); regular
{2: 2, 3: 2, 7: 2}
>>> pprint(factorint(regular))
2 2 2
2 *3 *7
>>> visual = factorint(1764, visual=True); pprint(visual)
2 2 2
2 *3 *7
>>> print(factorint(visual))
{2: 2, 3: 2, 7: 2}
If you want to send a number to be factored in a partially factored form
you can do so with a dictionary or unevaluated expression:
>>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form
{2: 10, 3: 3}
>>> factorint(Mul(4, 12, evaluate=False))
{2: 4, 3: 1}
The table of the output logic is:
====== ====== ======= =======
Visual
------ ----------------------
Input True False other
====== ====== ======= =======
dict mul dict mul
n mul dict dict
mul mul dict dict
====== ====== ======= =======
Notes
=====
Algorithm:
The function switches between multiple algorithms. Trial division
quickly finds small factors (of the order 1-5 digits), and finds
all large factors if given enough time. The Pollard rho and p-1
algorithms are used to find large factors ahead of time; they
will often find factors of the order of 10 digits within a few
seconds:
>>> factors = factorint(12345678910111213141516)
>>> for base, exp in sorted(factors.items()):
... print('%s %s' % (base, exp))
...
2 2
2507191691 1
1231026625769 1
Any of these methods can optionally be disabled with the following
boolean parameters:
- ``use_trial``: Toggle use of trial division
- ``use_rho``: Toggle use of Pollard's rho method
- ``use_pm1``: Toggle use of Pollard's p-1 method
``factorint`` also periodically checks if the remaining part is
a prime number or a perfect power, and in those cases stops.
For unevaluated factorial, it uses Legendre's formula(theorem).
If ``verbose`` is set to ``True``, detailed progress is printed.
See Also
========
smoothness, smoothness_p, divisors
"""
if isinstance(n, Dict):
n = dict(n)
if multiple:
fac = factorint(n, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose, visual=False, multiple=False)
factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p])
for p in sorted(fac)), [])
return factorlist
factordict = {}
if visual and not isinstance(n, (Mul, dict)):
factordict = factorint(n, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose, visual=False)
elif isinstance(n, Mul):
factordict = {int(k): int(v) for k, v in
n.as_powers_dict().items()}
elif isinstance(n, dict):
factordict = n
if factordict and isinstance(n, (Mul, dict)):
# check it
for key in list(factordict.keys()):
if isprime(key):
continue
e = factordict.pop(key)
d = factorint(key, limit=limit, use_trial=use_trial, use_rho=use_rho,
use_pm1=use_pm1, verbose=verbose, visual=False)
for k, v in d.items():
if k in factordict:
factordict[k] += v*e
else:
factordict[k] = v*e
if visual or (type(n) is dict and
visual is not True and
visual is not False):
if factordict == {}:
return S.One
if -1 in factordict:
factordict.pop(-1)
args = [S.NegativeOne]
else:
args = []
args.extend([Pow(*i, evaluate=False)
for i in sorted(factordict.items())])
return Mul(*args, evaluate=False)
elif isinstance(n, (dict, Mul)):
return factordict
assert use_trial or use_rho or use_pm1 or use_ecm
from sympy.functions.combinatorial.factorials import factorial
if isinstance(n, factorial):
x = as_int(n.args[0])
if x >= 20:
factors = {}
m = 2 # to initialize the if condition below
for p in sieve.primerange(2, x + 1):
if m > 1:
m, q = 0, x // p
while q != 0:
m += q
q //= p
factors[p] = m
if factors and verbose:
for k in sorted(factors):
print(factor_msg % (k, factors[k]))
if verbose:
print(complete_msg)
return factors
else:
# if n < 20!, direct computation is faster
# since it uses a lookup table
n = n.func(x)
n = as_int(n)
if limit:
limit = int(limit)
use_ecm = False
# special cases
if n < 0:
factors = factorint(
-n, limit=limit, use_trial=use_trial, use_rho=use_rho,
use_pm1=use_pm1, verbose=verbose, visual=False)
factors[-1] = 1
return factors
if limit and limit < 2:
if n == 1:
return {}
return {n: 1}
elif n < 10:
# doing this we are assured of getting a limit > 2
# when we have to compute it later
return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1},
{2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n]
factors = {}
# do simplistic factorization
if verbose:
sn = str(n)
if len(sn) > 50:
print('Factoring %s' % sn[:5] + \
'..(%i other digits)..' % (len(sn) - 10) + sn[-5:])
else:
print('Factoring', n)
if use_trial:
# this is the preliminary factorization for small factors
small = 2**15
fail_max = 600
small = min(small, limit or small)
if verbose:
print(trial_int_msg % (2, small, fail_max))
n, next_p = _factorint_small(factors, n, small, fail_max)
else:
next_p = 2
if factors and verbose:
for k in sorted(factors):
print(factor_msg % (k, factors[k]))
if next_p == 0:
if n > 1:
factors[int(n)] = 1
if verbose:
print(complete_msg)
return factors
# continue with more advanced factorization methods
# first check if the simplistic run didn't finish
# because of the limit and check for a perfect
# power before exiting
try:
if limit and next_p > limit:
if verbose:
print('Exceeded limit:', limit)
_check_termination(factors, n, limit, use_trial, use_rho, use_pm1,
verbose)
if n > 1:
factors[int(n)] = 1
return factors
else:
# Before quitting (or continuing on)...
# ...do a Fermat test since it's so easy and we need the
# square root anyway. Finding 2 factors is easy if they are
# "close enough." This is the big root equivalent of dividing by
# 2, 3, 5.
sqrt_n = integer_nthroot(n, 2)[0]
a = sqrt_n + 1
a2 = a**2
b2 = a2 - n
for i in range(3):
b, fermat = integer_nthroot(b2, 2)
if fermat:
break
b2 += 2*a + 1 # equiv to (a + 1)**2 - n
a += 1
if fermat:
if verbose:
print(fermat_msg)
if limit:
limit -= 1
for r in [a - b, a + b]:
facs = factorint(r, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose)
for k, v in facs.items():
factors[k] = factors.get(k, 0) + v
raise StopIteration
# ...see if factorization can be terminated
_check_termination(factors, n, limit, use_trial, use_rho, use_pm1,
verbose)
except StopIteration:
if verbose:
print(complete_msg)
return factors
# these are the limits for trial division which will
# be attempted in parallel with pollard methods
low, high = next_p, 2*next_p
limit = limit or sqrt_n
# add 1 to make sure limit is reached in primerange calls
limit += 1
iteration = 0
while 1:
try:
high_ = high
if limit < high_:
high_ = limit
# Trial division
if use_trial:
if verbose:
print(trial_msg % (low, high_))
ps = sieve.primerange(low, high_)
n, found_trial = _trial(factors, n, ps, verbose)
if found_trial:
_check_termination(factors, n, limit, use_trial, use_rho,
use_pm1, verbose)
else:
found_trial = False
if high > limit:
if verbose:
print('Exceeded limit:', limit)
if n > 1:
factors[int(n)] = 1
raise StopIteration
# Only used advanced methods when no small factors were found
if not found_trial:
if (use_pm1 or use_rho):
high_root = max(int(math.log(high_**0.7)), low, 3)
# Pollard p-1
if use_pm1:
if verbose:
print(pm1_msg % (high_root, high_))
c = pollard_pm1(n, B=high_root, seed=high_)
if c:
# factor it and let _trial do the update
ps = factorint(c, limit=limit - 1,
use_trial=use_trial,
use_rho=use_rho,
use_pm1=use_pm1,
use_ecm=use_ecm,
verbose=verbose)
n, _ = _trial(factors, n, ps, verbose=False)
_check_termination(factors, n, limit, use_trial,
use_rho, use_pm1, verbose)
# Pollard rho
if use_rho:
max_steps = high_root
if verbose:
print(rho_msg % (1, max_steps, high_))
c = pollard_rho(n, retries=1, max_steps=max_steps,
seed=high_)
if c:
# factor it and let _trial do the update
ps = factorint(c, limit=limit - 1,
use_trial=use_trial,
use_rho=use_rho,
use_pm1=use_pm1,
use_ecm=use_ecm,
verbose=verbose)
n, _ = _trial(factors, n, ps, verbose=False)
_check_termination(factors, n, limit, use_trial,
use_rho, use_pm1, verbose)
except StopIteration:
if verbose:
print(complete_msg)
return factors
#Use subexponential algorithms if use_ecm
#Use pollard algorithms for finding small factors for 3 iterations
#if after small factors the number of digits of n is >= 20 then use ecm
iteration += 1
if use_ecm and iteration >= 3 and len(str(n)) >= 25:
break
low, high = high, high*2
B1 = 10000
B2 = 100*B1
num_curves = 50
while(1):
if verbose:
print(ecm_msg % (B1, B2, num_curves))
while(1):
try:
factor = _ecm_one_factor(n, B1, B2, num_curves)
ps = factorint(factor, limit=limit - 1,
use_trial=use_trial,
use_rho=use_rho,
use_pm1=use_pm1,
use_ecm=use_ecm,
verbose=verbose)
n, _ = _trial(factors, n, ps, verbose=False)
_check_termination(factors, n, limit, use_trial,
use_rho, use_pm1, verbose)
except ValueError:
break
except StopIteration:
if verbose:
print(complete_msg)
return factors
B1 *= 5
B2 = 100*B1
num_curves *= 4
def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True,
verbose=False, visual=None, multiple=False):
r"""
Given a Rational ``r``, ``factorrat(r)`` returns a dict containing
the prime factors of ``r`` as keys and their respective multiplicities
as values. For example:
>>> from sympy import factorrat, S
>>> factorrat(S(8)/9) # 8/9 = (2**3) * (3**-2)
{2: 3, 3: -2}
>>> factorrat(S(-1)/987) # -1/789 = -1 * (3**-1) * (7**-1) * (47**-1)
{-1: 1, 3: -1, 7: -1, 47: -1}
Please see the docstring for ``factorint`` for detailed explanations
and examples of the following keywords:
- ``limit``: Integer limit up to which trial division is done
- ``use_trial``: Toggle use of trial division
- ``use_rho``: Toggle use of Pollard's rho method
- ``use_pm1``: Toggle use of Pollard's p-1 method
- ``verbose``: Toggle detailed printing of progress
- ``multiple``: Toggle returning a list of factors or dict
- ``visual``: Toggle product form of output
"""
if multiple:
fac = factorrat(rat, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose, visual=False, multiple=False)
factorlist = sum(([p] * fac[p] if fac[p] > 0 else [S.One/p]*(-fac[p])
for p, _ in sorted(fac.items(),
key=lambda elem: elem[0]
if elem[1] > 0
else 1/elem[0])), [])
return factorlist
f = factorint(rat.p, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose).copy()
f = defaultdict(int, f)
for p, e in factorint(rat.q, limit=limit,
use_trial=use_trial,
use_rho=use_rho,
use_pm1=use_pm1,
verbose=verbose).items():
f[p] += -e
if len(f) > 1 and 1 in f:
del f[1]
if not visual:
return dict(f)
else:
if -1 in f:
f.pop(-1)
args = [S.NegativeOne]
else:
args = []
args.extend([Pow(*i, evaluate=False)
for i in sorted(f.items())])
return Mul(*args, evaluate=False)
def primefactors(n, limit=None, verbose=False):
"""Return a sorted list of n's prime factors, ignoring multiplicity
and any composite factor that remains if the limit was set too low
for complete factorization. Unlike factorint(), primefactors() does
not return -1 or 0.
Examples
========
>>> from sympy.ntheory import primefactors, factorint, isprime
>>> primefactors(6)
[2, 3]
>>> primefactors(-5)
[5]
>>> sorted(factorint(123456).items())
[(2, 6), (3, 1), (643, 1)]
>>> primefactors(123456)
[2, 3, 643]
>>> sorted(factorint(10000000001, limit=200).items())
[(101, 1), (99009901, 1)]
>>> isprime(99009901)
False
>>> primefactors(10000000001, limit=300)
[101]
See Also
========
divisors
"""
n = int(n)
factors = sorted(factorint(n, limit=limit, verbose=verbose).keys())
s = [f for f in factors[:-1:] if f not in [-1, 0, 1]]
if factors and isprime(factors[-1]):
s += [factors[-1]]
return s
def _divisors(n, proper=False):
"""Helper function for divisors which generates the divisors."""
factordict = factorint(n)
ps = sorted(factordict.keys())
def rec_gen(n=0):
if n == len(ps):
yield 1
else:
pows = [1]
for j in range(factordict[ps[n]]):
pows.append(pows[-1] * ps[n])
for q in rec_gen(n + 1):
for p in pows:
yield p * q
if proper:
for p in rec_gen():
if p != n:
yield p
else:
yield from rec_gen()
def divisors(n, generator=False, proper=False):
r"""
Return all divisors of n sorted from 1..n by default.
If generator is ``True`` an unordered generator is returned.
The number of divisors of n can be quite large if there are many
prime factors (counting repeated factors). If only the number of
factors is desired use divisor_count(n).
Examples
========
>>> from sympy import divisors, divisor_count
>>> divisors(24)
[1, 2, 3, 4, 6, 8, 12, 24]
>>> divisor_count(24)
8
>>> list(divisors(120, generator=True))
[1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120]
Notes
=====
This is a slightly modified version of Tim Peters referenced at:
https://stackoverflow.com/questions/1010381/python-factorization
See Also
========
primefactors, factorint, divisor_count
"""
n = as_int(abs(n))
if isprime(n):
if proper:
return [1]
return [1, n]
if n == 1:
if proper:
return []
return [1]
if n == 0:
return []
rv = _divisors(n, proper)
if not generator:
return sorted(rv)
return rv
def divisor_count(n, modulus=1, proper=False):
"""
Return the number of divisors of ``n``. If ``modulus`` is not 1 then only
those that are divisible by ``modulus`` are counted. If ``proper`` is True
then the divisor of ``n`` will not be counted.
Examples
========
>>> from sympy import divisor_count
>>> divisor_count(6)
4
>>> divisor_count(6, 2)
2
>>> divisor_count(6, proper=True)
3
See Also
========
factorint, divisors, totient, proper_divisor_count
"""
if not modulus:
return 0
elif modulus != 1:
n, r = divmod(n, modulus)
if r:
return 0
if n == 0:
return 0
n = Mul(*[v + 1 for k, v in factorint(n).items() if k > 1])
if n and proper:
n -= 1
return n
def proper_divisors(n, generator=False):
"""
Return all divisors of n except n, sorted by default.
If generator is ``True`` an unordered generator is returned.
Examples
========
>>> from sympy import proper_divisors, proper_divisor_count
>>> proper_divisors(24)
[1, 2, 3, 4, 6, 8, 12]
>>> proper_divisor_count(24)
7
>>> list(proper_divisors(120, generator=True))
[1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60]
See Also
========
factorint, divisors, proper_divisor_count
"""
return divisors(n, generator=generator, proper=True)
def proper_divisor_count(n, modulus=1):
"""
Return the number of proper divisors of ``n``.
Examples
========
>>> from sympy import proper_divisor_count
>>> proper_divisor_count(6)
3
>>> proper_divisor_count(6, modulus=2)
1
See Also
========
divisors, proper_divisors, divisor_count
"""
return divisor_count(n, modulus=modulus, proper=True)
def _udivisors(n):
"""Helper function for udivisors which generates the unitary divisors."""
factorpows = [p**e for p, e in factorint(n).items()]
for i in range(2**len(factorpows)):
d, j, k = 1, i, 0
while j:
if (j & 1):
d *= factorpows[k]
j >>= 1
k += 1
yield d
def udivisors(n, generator=False):
r"""
Return all unitary divisors of n sorted from 1..n by default.
If generator is ``True`` an unordered generator is returned.
The number of unitary divisors of n can be quite large if there are many
prime factors. If only the number of unitary divisors is desired use
udivisor_count(n).
Examples
========
>>> from sympy.ntheory.factor_ import udivisors, udivisor_count
>>> udivisors(15)
[1, 3, 5, 15]
>>> udivisor_count(15)
4
>>> sorted(udivisors(120, generator=True))
[1, 3, 5, 8, 15, 24, 40, 120]
See Also
========
primefactors, factorint, divisors, divisor_count, udivisor_count
References
==========
.. [1] https://en.wikipedia.org/wiki/Unitary_divisor
.. [2] http://mathworld.wolfram.com/UnitaryDivisor.html
"""
n = as_int(abs(n))
if isprime(n):
return [1, n]
if n == 1:
return [1]
if n == 0:
return []
rv = _udivisors(n)
if not generator:
return sorted(rv)
return rv
def udivisor_count(n):
"""
Return the number of unitary divisors of ``n``.
Parameters
==========
n : integer
Examples
========
>>> from sympy.ntheory.factor_ import udivisor_count
>>> udivisor_count(120)
8
See Also
========
factorint, divisors, udivisors, divisor_count, totient
References
==========
.. [1] http://mathworld.wolfram.com/UnitaryDivisorFunction.html
"""
if n == 0:
return 0
return 2**len([p for p in factorint(n) if p > 1])
def _antidivisors(n):
"""Helper function for antidivisors which generates the antidivisors."""
for d in _divisors(n):
y = 2*d
if n > y and n % y:
yield y
for d in _divisors(2*n-1):
if n > d >= 2 and n % d:
yield d
for d in _divisors(2*n+1):
if n > d >= 2 and n % d:
yield d
def antidivisors(n, generator=False):
r"""
Return all antidivisors of n sorted from 1..n by default.
Antidivisors [1]_ of n are numbers that do not divide n by the largest
possible margin. If generator is True an unordered generator is returned.
Examples
========
>>> from sympy.ntheory.factor_ import antidivisors
>>> antidivisors(24)
[7, 16]
>>> sorted(antidivisors(128, generator=True))
[3, 5, 15, 17, 51, 85]
See Also
========
primefactors, factorint, divisors, divisor_count, antidivisor_count
References
==========
.. [1] definition is described in https://oeis.org/A066272/a066272a.html
"""
n = as_int(abs(n))
if n <= 2:
return []
rv = _antidivisors(n)
if not generator:
return sorted(rv)
return rv
def antidivisor_count(n):
"""
Return the number of antidivisors [1]_ of ``n``.
Parameters
==========
n : integer
Examples
========
>>> from sympy.ntheory.factor_ import antidivisor_count
>>> antidivisor_count(13)
4
>>> antidivisor_count(27)
5
See Also
========
factorint, divisors, antidivisors, divisor_count, totient
References
==========
.. [1] formula from https://oeis.org/A066272
"""
n = as_int(abs(n))
if n <= 2:
return 0
return divisor_count(2*n - 1) + divisor_count(2*n + 1) + \
divisor_count(n) - divisor_count(n, 2) - 5
class totient(Function):
r"""
Calculate the Euler totient function phi(n)
``totient(n)`` or `\phi(n)` is the number of positive integers `\leq` n
that are relatively prime to n.
Parameters
==========
n : integer
Examples
========
>>> from sympy.ntheory import totient
>>> totient(1)
1
>>> totient(25)
20
>>> totient(45) == totient(5)*totient(9)
True
See Also
========
divisor_count
References
==========
.. [1] https://en.wikipedia.org/wiki/Euler%27s_totient_function
.. [2] http://mathworld.wolfram.com/TotientFunction.html
"""
@classmethod
def eval(cls, n):
n = sympify(n)
if n.is_Integer:
if n < 1:
raise ValueError("n must be a positive integer")
factors = factorint(n)
return cls._from_factors(factors)
elif not isinstance(n, Expr) or (n.is_integer is False) or (n.is_positive is False):
raise ValueError("n must be a positive integer")
def _eval_is_integer(self):
return fuzzy_and([self.args[0].is_integer, self.args[0].is_positive])
@classmethod
def _from_distinct_primes(self, *args):
"""Subroutine to compute totient from the list of assumed
distinct primes
Examples
========
>>> from sympy.ntheory.factor_ import totient
>>> totient._from_distinct_primes(5, 7)
24
"""
from functools import reduce
return reduce(lambda i, j: i * (j-1), args, 1)
@classmethod
def _from_factors(self, factors):
"""Subroutine to compute totient from already-computed factors
Examples
========
>>> from sympy.ntheory.factor_ import totient
>>> totient._from_factors({5: 2})
20
"""
t = 1
for p, k in factors.items():
t *= (p - 1) * p**(k - 1)
return t
class reduced_totient(Function):
r"""
Calculate the Carmichael reduced totient function lambda(n)
``reduced_totient(n)`` or `\lambda(n)` is the smallest m > 0 such that
`k^m \equiv 1 \mod n` for all k relatively prime to n.
Examples
========
>>> from sympy.ntheory import reduced_totient
>>> reduced_totient(1)
1
>>> reduced_totient(8)
2
>>> reduced_totient(30)
4
See Also
========
totient
References
==========
.. [1] https://en.wikipedia.org/wiki/Carmichael_function
.. [2] http://mathworld.wolfram.com/CarmichaelFunction.html
"""
@classmethod
def eval(cls, n):
n = sympify(n)
if n.is_Integer:
if n < 1:
raise ValueError("n must be a positive integer")
factors = factorint(n)
return cls._from_factors(factors)
@classmethod
def _from_factors(self, factors):
"""Subroutine to compute totient from already-computed factors
"""
t = 1
for p, k in factors.items():
if p == 2 and k > 2:
t = ilcm(t, 2**(k - 2))
else:
t = ilcm(t, (p - 1) * p**(k - 1))
return t
@classmethod
def _from_distinct_primes(self, *args):
"""Subroutine to compute totient from the list of assumed
distinct primes
"""
args = [p - 1 for p in args]
return ilcm(*args)
def _eval_is_integer(self):
return fuzzy_and([self.args[0].is_integer, self.args[0].is_positive])
class divisor_sigma(Function):
r"""
Calculate the divisor function `\sigma_k(n)` for positive integer n
``divisor_sigma(n, k)`` is equal to ``sum([x**k for x in divisors(n)])``
If n's prime factorization is:
.. math ::
n = \prod_{i=1}^\omega p_i^{m_i},
then
.. math ::
\sigma_k(n) = \prod_{i=1}^\omega (1+p_i^k+p_i^{2k}+\cdots
+ p_i^{m_ik}).
Parameters
==========
n : integer
k : integer, optional
power of divisors in the sum
for k = 0, 1:
``divisor_sigma(n, 0)`` is equal to ``divisor_count(n)``
``divisor_sigma(n, 1)`` is equal to ``sum(divisors(n))``
Default for k is 1.
Examples
========
>>> from sympy.ntheory import divisor_sigma
>>> divisor_sigma(18, 0)
6
>>> divisor_sigma(39, 1)
56
>>> divisor_sigma(12, 2)
210
>>> divisor_sigma(37)
38
See Also
========
divisor_count, totient, divisors, factorint
References
==========
.. [1] https://en.wikipedia.org/wiki/Divisor_function
"""
@classmethod
def eval(cls, n, k=1):
n = sympify(n)
k = sympify(k)
if n.is_prime:
return 1 + n**k
if n.is_Integer:
if n <= 0:
raise ValueError("n must be a positive integer")
elif k.is_Integer:
k = int(k)
return Integer(prod(
(p**(k*(e + 1)) - 1)//(p**k - 1) if k != 0
else e + 1 for p, e in factorint(n).items()))
else:
return Mul(*[(p**(k*(e + 1)) - 1)/(p**k - 1) if k != 0
else e + 1 for p, e in factorint(n).items()])
if n.is_integer: # symbolic case
args = []
for p, e in (_.as_base_exp() for _ in Mul.make_args(n)):
if p.is_prime and e.is_positive:
args.append((p**(k*(e + 1)) - 1)/(p**k - 1) if
k != 0 else e + 1)
else:
return
return Mul(*args)
def core(n, t=2):
r"""
Calculate core(n, t) = `core_t(n)` of a positive integer n
``core_2(n)`` is equal to the squarefree part of n
If n's prime factorization is:
.. math ::
n = \prod_{i=1}^\omega p_i^{m_i},
then
.. math ::
core_t(n) = \prod_{i=1}^\omega p_i^{m_i \mod t}.
Parameters
==========
n : integer
t : integer
core(n, t) calculates the t-th power free part of n
``core(n, 2)`` is the squarefree part of ``n``
``core(n, 3)`` is the cubefree part of ``n``
Default for t is 2.
Examples
========
>>> from sympy.ntheory.factor_ import core
>>> core(24, 2)
6
>>> core(9424, 3)
1178
>>> core(379238)
379238
>>> core(15**11, 10)
15
See Also
========
factorint, sympy.solvers.diophantine.diophantine.square_factor
References
==========
.. [1] https://en.wikipedia.org/wiki/Square-free_integer#Squarefree_core
"""
n = as_int(n)
t = as_int(t)
if n <= 0:
raise ValueError("n must be a positive integer")
elif t <= 1:
raise ValueError("t must be >= 2")
else:
y = 1
for p, e in factorint(n).items():
y *= p**(e % t)
return y
class udivisor_sigma(Function):
r"""
Calculate the unitary divisor function `\sigma_k^*(n)` for positive integer n
``udivisor_sigma(n, k)`` is equal to ``sum([x**k for x in udivisors(n)])``
If n's prime factorization is:
.. math ::
n = \prod_{i=1}^\omega p_i^{m_i},
then
.. math ::
\sigma_k^*(n) = \prod_{i=1}^\omega (1+ p_i^{m_ik}).
Parameters
==========
k : power of divisors in the sum
for k = 0, 1:
``udivisor_sigma(n, 0)`` is equal to ``udivisor_count(n)``
``udivisor_sigma(n, 1)`` is equal to ``sum(udivisors(n))``
Default for k is 1.
Examples
========
>>> from sympy.ntheory.factor_ import udivisor_sigma
>>> udivisor_sigma(18, 0)
4
>>> udivisor_sigma(74, 1)
114
>>> udivisor_sigma(36, 3)
47450
>>> udivisor_sigma(111)
152
See Also
========
divisor_count, totient, divisors, udivisors, udivisor_count, divisor_sigma,
factorint
References
==========
.. [1] http://mathworld.wolfram.com/UnitaryDivisorFunction.html
"""
@classmethod
def eval(cls, n, k=1):
n = sympify(n)
k = sympify(k)
if n.is_prime:
return 1 + n**k
if n.is_Integer:
if n <= 0:
raise ValueError("n must be a positive integer")
else:
return Mul(*[1+p**(k*e) for p, e in factorint(n).items()])
class primenu(Function):
r"""
Calculate the number of distinct prime factors for a positive integer n.
If n's prime factorization is:
.. math ::
n = \prod_{i=1}^k p_i^{m_i},
then ``primenu(n)`` or `\nu(n)` is:
.. math ::
\nu(n) = k.
Examples
========
>>> from sympy.ntheory.factor_ import primenu
>>> primenu(1)
0
>>> primenu(30)
3
See Also
========
factorint
References
==========
.. [1] http://mathworld.wolfram.com/PrimeFactor.html
"""
@classmethod
def eval(cls, n):
n = sympify(n)
if n.is_Integer:
if n <= 0:
raise ValueError("n must be a positive integer")
else:
return len(factorint(n).keys())
class primeomega(Function):
r"""
Calculate the number of prime factors counting multiplicities for a
positive integer n.
If n's prime factorization is:
.. math ::
n = \prod_{i=1}^k p_i^{m_i},
then ``primeomega(n)`` or `\Omega(n)` is:
.. math ::
\Omega(n) = \sum_{i=1}^k m_i.
Examples
========
>>> from sympy.ntheory.factor_ import primeomega
>>> primeomega(1)
0
>>> primeomega(20)
3
See Also
========
factorint
References
==========
.. [1] http://mathworld.wolfram.com/PrimeFactor.html
"""
@classmethod
def eval(cls, n):
n = sympify(n)
if n.is_Integer:
if n <= 0:
raise ValueError("n must be a positive integer")
else:
return sum(factorint(n).values())
def mersenne_prime_exponent(nth):
"""Returns the exponent ``i`` for the nth Mersenne prime (which
has the form `2^i - 1`).
Examples
========
>>> from sympy.ntheory.factor_ import mersenne_prime_exponent
>>> mersenne_prime_exponent(1)
2
>>> mersenne_prime_exponent(20)
4423
"""
n = as_int(nth)
if n < 1:
raise ValueError("nth must be a positive integer; mersenne_prime_exponent(1) == 2")
if n > 51:
raise ValueError("There are only 51 perfect numbers; nth must be less than or equal to 51")
return MERSENNE_PRIME_EXPONENTS[n - 1]
def is_perfect(n):
"""Returns True if ``n`` is a perfect number, else False.
A perfect number is equal to the sum of its positive, proper divisors.
Examples
========
>>> from sympy.ntheory.factor_ import is_perfect, divisors, divisor_sigma
>>> is_perfect(20)
False
>>> is_perfect(6)
True
>>> 6 == divisor_sigma(6) - 6 == sum(divisors(6)[:-1])
True
References
==========
.. [1] http://mathworld.wolfram.com/PerfectNumber.html
.. [2] https://en.wikipedia.org/wiki/Perfect_number
"""
n = as_int(n)
if _isperfect(n):
return True
# all perfect numbers for Mersenne primes with exponents
# less than or equal to 43112609 are known
iknow = MERSENNE_PRIME_EXPONENTS.index(43112609)
if iknow <= len(PERFECT) - 1 and n <= PERFECT[iknow]:
# there may be gaps between this and larger known values
# so only conclude in the range for which all values
# are known
return False
if n%2 == 0:
last2 = n % 100
if last2 != 28 and last2 % 10 != 6:
return False
r, b = integer_nthroot(1 + 8*n, 2)
if not b:
return False
m, x = divmod(1 + r, 4)
if x:
return False
e, b = integer_log(m, 2)
if not b:
return False
else:
if n < 10**2000: # http://www.lirmm.fr/~ochem/opn/
return False
if n % 105 == 0: # not divis by 105
return False
if not any(n%m == r for m, r in [(12, 1), (468, 117), (324, 81)]):
return False
# there are many criteria that the factor structure of n
# must meet; since we will have to factor it to test the
# structure we will have the factors and can then check
# to see whether it is a perfect number or not. So we
# skip the structure checks and go straight to the final
# test below.
rv = divisor_sigma(n) - n
if rv == n:
if n%2 == 0:
raise ValueError(filldedent('''
This even number is perfect and is associated with a
Mersenne Prime, 2^%s - 1. It should be
added to SymPy.''' % (e + 1)))
else:
raise ValueError(filldedent('''In 1888, Sylvester stated: "
...a prolonged meditation on the subject has satisfied
me that the existence of any one such [odd perfect number]
-- its escape, so to say, from the complex web of conditions
which hem it in on all sides -- would be little short of a
miracle." I guess SymPy just found that miracle and it
factors like this: %s''' % factorint(n)))
def is_mersenne_prime(n):
"""Returns True if ``n`` is a Mersenne prime, else False.
A Mersenne prime is a prime number having the form `2^i - 1`.
Examples
========
>>> from sympy.ntheory.factor_ import is_mersenne_prime
>>> is_mersenne_prime(6)
False
>>> is_mersenne_prime(127)
True
References
==========
.. [1] http://mathworld.wolfram.com/MersennePrime.html
"""
n = as_int(n)
if _ismersenneprime(n):
return True
if not isprime(n):
return False
r, b = integer_log(n + 1, 2)
if not b:
return False
raise ValueError(filldedent('''
This Mersenne Prime, 2^%s - 1, should
be added to SymPy's known values.''' % r))
def abundance(n):
"""Returns the difference between the sum of the positive
proper divisors of a number and the number.
Examples
========
>>> from sympy.ntheory import abundance, is_perfect, is_abundant
>>> abundance(6)
0
>>> is_perfect(6)
True
>>> abundance(10)
-2
>>> is_abundant(10)
False
"""
return divisor_sigma(n, 1) - 2 * n
def is_abundant(n):
"""Returns True if ``n`` is an abundant number, else False.
A abundant number is smaller than the sum of its positive proper divisors.
Examples
========
>>> from sympy.ntheory.factor_ import is_abundant
>>> is_abundant(20)
True
>>> is_abundant(15)
False
References
==========
.. [1] http://mathworld.wolfram.com/AbundantNumber.html
"""
n = as_int(n)
if is_perfect(n):
return False
return n % 6 == 0 or bool(abundance(n) > 0)
def is_deficient(n):
"""Returns True if ``n`` is a deficient number, else False.
A deficient number is greater than the sum of its positive proper divisors.
Examples
========
>>> from sympy.ntheory.factor_ import is_deficient
>>> is_deficient(20)
False
>>> is_deficient(15)
True
References
==========
.. [1] http://mathworld.wolfram.com/DeficientNumber.html
"""
n = as_int(n)
if is_perfect(n):
return False
return bool(abundance(n) < 0)
def is_amicable(m, n):
"""Returns True if the numbers `m` and `n` are "amicable", else False.
Amicable numbers are two different numbers so related that the sum
of the proper divisors of each is equal to that of the other.
Examples
========
>>> from sympy.ntheory.factor_ import is_amicable, divisor_sigma
>>> is_amicable(220, 284)
True
>>> divisor_sigma(220) == divisor_sigma(284)
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Amicable_numbers
"""
if m == n:
return False
a, b = map(lambda i: divisor_sigma(i), (m, n))
return a == b == (m + n)
def dra(n, b):
"""
Returns the additive digital root of a natural number ``n`` in base ``b``
which is a single digit value obtained by an iterative process of summing
digits, on each iteration using the result from the previous iteration to
compute a digit sum.
Examples
========
>>> from sympy.ntheory.factor_ import dra
>>> dra(3110, 12)
8
References
==========
.. [1] https://en.wikipedia.org/wiki/Digital_root
"""
num = abs(as_int(n))
b = as_int(b)
if b <= 1:
raise ValueError("Base should be an integer greater than 1")
if num == 0:
return 0
return (1 + (num - 1) % (b - 1))
def drm(n, b):
"""
Returns the multiplicative digital root of a natural number ``n`` in a given
base ``b`` which is a single digit value obtained by an iterative process of
multiplying digits, on each iteration using the result from the previous
iteration to compute the digit multiplication.
Examples
========
>>> from sympy.ntheory.factor_ import drm
>>> drm(9876, 10)
0
>>> drm(49, 10)
8
References
==========
.. [1] http://mathworld.wolfram.com/MultiplicativeDigitalRoot.html
"""
n = abs(as_int(n))
b = as_int(b)
if b <= 1:
raise ValueError("Base should be an integer greater than 1")
while n > b:
mul = 1
while n > 1:
n, r = divmod(n, b)
if r == 0:
return 0
mul *= r
n = mul
return n
|
ca5fff2e0ca3013af8ea6e51462a2f4c7dfe33981e92bc7d334bfe0ff99ae72e | from mpmath.libmp import (fzero, from_int, from_rational,
fone, fhalf, bitcount, to_int, to_str, mpf_mul, mpf_div, mpf_sub,
mpf_add, mpf_sqrt, mpf_pi, mpf_cosh_sinh, mpf_cos, mpf_sin)
from sympy.core.numbers import igcd
from .residue_ntheory import (_sqrt_mod_prime_power,
legendre_symbol, jacobi_symbol, is_quad_residue)
import math
def _pre():
maxn = 10**5
global _factor
global _totient
_factor = [0]*maxn
_totient = [1]*maxn
lim = int(maxn**0.5) + 5
for i in range(2, lim):
if _factor[i] == 0:
for j in range(i*i, maxn, i):
if _factor[j] == 0:
_factor[j] = i
for i in range(2, maxn):
if _factor[i] == 0:
_factor[i] = i
_totient[i] = i-1
continue
x = _factor[i]
y = i//x
if y % x == 0:
_totient[i] = _totient[y]*x
else:
_totient[i] = _totient[y]*(x - 1)
def _a(n, k, prec):
""" Compute the inner sum in HRR formula [1]_
References
==========
.. [1] http://msp.org/pjm/1956/6-1/pjm-v6-n1-p18-p.pdf
"""
if k == 1:
return fone
k1 = k
e = 0
p = _factor[k]
while k1 % p == 0:
k1 //= p
e += 1
k2 = k//k1 # k2 = p^e
v = 1 - 24*n
pi = mpf_pi(prec)
if k1 == 1:
# k = p^e
if p == 2:
mod = 8*k
v = mod + v % mod
v = (v*pow(9, k - 1, mod)) % mod
m = _sqrt_mod_prime_power(v, 2, e + 3)[0]
arg = mpf_div(mpf_mul(
from_int(4*m), pi, prec), from_int(mod), prec)
return mpf_mul(mpf_mul(
from_int((-1)**e*jacobi_symbol(m - 1, m)),
mpf_sqrt(from_int(k), prec), prec),
mpf_sin(arg, prec), prec)
if p == 3:
mod = 3*k
v = mod + v % mod
if e > 1:
v = (v*pow(64, k//3 - 1, mod)) % mod
m = _sqrt_mod_prime_power(v, 3, e + 1)[0]
arg = mpf_div(mpf_mul(from_int(4*m), pi, prec),
from_int(mod), prec)
return mpf_mul(mpf_mul(
from_int(2*(-1)**(e + 1)*legendre_symbol(m, 3)),
mpf_sqrt(from_int(k//3), prec), prec),
mpf_sin(arg, prec), prec)
v = k + v % k
if v % p == 0:
if e == 1:
return mpf_mul(
from_int(jacobi_symbol(3, k)),
mpf_sqrt(from_int(k), prec), prec)
return fzero
if not is_quad_residue(v, p):
return fzero
_phi = p**(e - 1)*(p - 1)
v = (v*pow(576, _phi - 1, k))
m = _sqrt_mod_prime_power(v, p, e)[0]
arg = mpf_div(
mpf_mul(from_int(4*m), pi, prec),
from_int(k), prec)
return mpf_mul(mpf_mul(
from_int(2*jacobi_symbol(3, k)),
mpf_sqrt(from_int(k), prec), prec),
mpf_cos(arg, prec), prec)
if p != 2 or e >= 3:
d1, d2 = igcd(k1, 24), igcd(k2, 24)
e = 24//(d1*d2)
n1 = ((d2*e*n + (k2**2 - 1)//d1)*
pow(e*k2*k2*d2, _totient[k1] - 1, k1)) % k1
n2 = ((d1*e*n + (k1**2 - 1)//d2)*
pow(e*k1*k1*d1, _totient[k2] - 1, k2)) % k2
return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
if e == 2:
n1 = ((8*n + 5)*pow(128, _totient[k1] - 1, k1)) % k1
n2 = (4 + ((n - 2 - (k1**2 - 1)//8)*(k1**2)) % 4) % 4
return mpf_mul(mpf_mul(
from_int(-1),
_a(n1, k1, prec), prec),
_a(n2, k2, prec))
n1 = ((8*n + 1)*pow(32, _totient[k1] - 1, k1)) % k1
n2 = (2 + (n - (k1**2 - 1)//8) % 2) % 2
return mpf_mul(_a(n1, k1, prec), _a(n2, k2, prec), prec)
def _d(n, j, prec, sq23pi, sqrt8):
"""
Compute the sinh term in the outer sum of the HRR formula.
The constants sqrt(2/3*pi) and sqrt(8) must be precomputed.
"""
j = from_int(j)
pi = mpf_pi(prec)
a = mpf_div(sq23pi, j, prec)
b = mpf_sub(from_int(n), from_rational(1, 24, prec), prec)
c = mpf_sqrt(b, prec)
ch, sh = mpf_cosh_sinh(mpf_mul(a, c), prec)
D = mpf_div(
mpf_sqrt(j, prec),
mpf_mul(mpf_mul(sqrt8, b), pi), prec)
E = mpf_sub(mpf_mul(a, ch), mpf_div(sh, c, prec), prec)
return mpf_mul(D, E)
def npartitions(n, verbose=False):
"""
Calculate the partition function P(n), i.e. the number of ways that
n can be written as a sum of positive integers.
P(n) is computed using the Hardy-Ramanujan-Rademacher formula [1]_.
The correctness of this implementation has been tested through $10^10$.
Examples
========
>>> from sympy.ntheory import npartitions
>>> npartitions(25)
1958
References
==========
.. [1] http://mathworld.wolfram.com/PartitionFunctionP.html
"""
n = int(n)
if n < 0:
return 0
if n <= 5:
return [1, 1, 2, 3, 5, 7][n]
if '_factor' not in globals():
_pre()
# Estimate number of bits in p(n). This formula could be tidied
pbits = int((
math.pi*(2*n/3.)**0.5 -
math.log(4*n))/math.log(10) + 1) * \
math.log(10, 2)
prec = p = int(pbits*1.1 + 100)
s = fzero
M = max(6, int(0.24*n**0.5 + 4))
if M > 10**5:
raise ValueError("Input too big") # Corresponds to n > 1.7e11
sq23pi = mpf_mul(mpf_sqrt(from_rational(2, 3, p), p), mpf_pi(p), p)
sqrt8 = mpf_sqrt(from_int(8), p)
for q in range(1, M):
a = _a(n, q, p)
d = _d(n, q, p, sq23pi, sqrt8)
s = mpf_add(s, mpf_mul(a, d), prec)
if verbose:
print("step", q, "of", M, to_str(a, 10), to_str(d, 10))
# On average, the terms decrease rapidly in magnitude.
# Dynamically reducing the precision greatly improves
# performance.
p = bitcount(abs(to_int(d))) + 50
return int(to_int(mpf_add(s, fhalf, prec)))
__all__ = ['npartitions']
|
7a6a98e38be43defbc204b90a35e82e058de7ea4c064857bd361e4720b181c15 | from sympy.core.random import randrange, choice
from math import log
from sympy.ntheory import primefactors
from sympy.core.symbol import Symbol
from sympy.ntheory.factor_ import (factorint, multiplicity)
from sympy.combinatorics import Permutation
from sympy.combinatorics.permutations import (_af_commutes_with, _af_invert,
_af_rmul, _af_rmuln, _af_pow, Cycle)
from sympy.combinatorics.util import (_check_cycles_alt_sym,
_distribute_gens_by_base, _orbits_transversals_from_bsgs,
_handle_precomputed_bsgs, _base_ordering, _strong_gens_from_distr,
_strip, _strip_af)
from sympy.core import Basic
from sympy.functions.combinatorial.factorials import factorial
from sympy.ntheory import sieve
from sympy.utilities.iterables import has_variety, is_sequence, uniq
from sympy.core.random import _randrange
from itertools import islice
from sympy.core.sympify import _sympify
rmul = Permutation.rmul_with_af
_af_new = Permutation._af_new
class PermutationGroup(Basic):
r"""The class defining a Permutation group.
Explanation
===========
``PermutationGroup([p1, p2, ..., pn])`` returns the permutation group
generated by the list of permutations. This group can be supplied
to Polyhedron if one desires to decorate the elements to which the
indices of the permutation refer.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.polyhedron import Polyhedron
>>> from sympy.combinatorics.perm_groups import PermutationGroup
The permutations corresponding to motion of the front, right and
bottom face of a $2 \times 2$ Rubik's cube are defined:
>>> F = Permutation(2, 19, 21, 8)(3, 17, 20, 10)(4, 6, 7, 5)
>>> R = Permutation(1, 5, 21, 14)(3, 7, 23, 12)(8, 10, 11, 9)
>>> D = Permutation(6, 18, 14, 10)(7, 19, 15, 11)(20, 22, 23, 21)
These are passed as permutations to PermutationGroup:
>>> G = PermutationGroup(F, R, D)
>>> G.order()
3674160
The group can be supplied to a Polyhedron in order to track the
objects being moved. An example involving the $2 \times 2$ Rubik's cube is
given there, but here is a simple demonstration:
>>> a = Permutation(2, 1)
>>> b = Permutation(1, 0)
>>> G = PermutationGroup(a, b)
>>> P = Polyhedron(list('ABC'), pgroup=G)
>>> P.corners
(A, B, C)
>>> P.rotate(0) # apply permutation 0
>>> P.corners
(A, C, B)
>>> P.reset()
>>> P.corners
(A, B, C)
Or one can make a permutation as a product of selected permutations
and apply them to an iterable directly:
>>> P10 = G.make_perm([0, 1])
>>> P10('ABC')
['C', 'A', 'B']
See Also
========
sympy.combinatorics.polyhedron.Polyhedron,
sympy.combinatorics.permutations.Permutation
References
==========
.. [1] Holt, D., Eick, B., O'Brien, E.
"Handbook of Computational Group Theory"
.. [2] Seress, A.
"Permutation Group Algorithms"
.. [3] https://en.wikipedia.org/wiki/Schreier_vector
.. [4] https://en.wikipedia.org/wiki/Nielsen_transformation#Product_replacement_algorithm
.. [5] Frank Celler, Charles R.Leedham-Green, Scott H.Murray,
Alice C.Niemeyer, and E.A.O'Brien. "Generating Random
Elements of a Finite Group"
.. [6] https://en.wikipedia.org/wiki/Block_%28permutation_group_theory%29
.. [7] http://www.algorithmist.com/index.php/Union_Find
.. [8] https://en.wikipedia.org/wiki/Multiply_transitive_group#Multiply_transitive_groups
.. [9] https://en.wikipedia.org/wiki/Center_%28group_theory%29
.. [10] https://en.wikipedia.org/wiki/Centralizer_and_normalizer
.. [11] http://groupprops.subwiki.org/wiki/Derived_subgroup
.. [12] https://en.wikipedia.org/wiki/Nilpotent_group
.. [13] http://www.math.colostate.edu/~hulpke/CGT/cgtnotes.pdf
.. [14] https://www.gap-system.org/Manuals/doc/ref/manual.pdf
"""
is_group = True
def __new__(cls, *args, dups=True, **kwargs):
"""The default constructor. Accepts Cycle and Permutation forms.
Removes duplicates unless ``dups`` keyword is ``False``.
"""
if not args:
args = [Permutation()]
else:
args = list(args[0] if is_sequence(args[0]) else args)
if not args:
args = [Permutation()]
if any(isinstance(a, Cycle) for a in args):
args = [Permutation(a) for a in args]
if has_variety(a.size for a in args):
degree = kwargs.pop('degree', None)
if degree is None:
degree = max(a.size for a in args)
for i in range(len(args)):
if args[i].size != degree:
args[i] = Permutation(args[i], size=degree)
if dups:
args = list(uniq([_af_new(list(a)) for a in args]))
if len(args) > 1:
args = [g for g in args if not g.is_identity]
return Basic.__new__(cls, *args, **kwargs)
def __init__(self, *args, **kwargs):
self._generators = list(self.args)
self._order = None
self._center = []
self._is_abelian = None
self._is_transitive = None
self._is_sym = None
self._is_alt = None
self._is_primitive = None
self._is_nilpotent = None
self._is_solvable = None
self._is_trivial = None
self._transitivity_degree = None
self._max_div = None
self._is_perfect = None
self._is_cyclic = None
self._r = len(self._generators)
self._degree = self._generators[0].size
# these attributes are assigned after running schreier_sims
self._base = []
self._strong_gens = []
self._strong_gens_slp = []
self._basic_orbits = []
self._transversals = []
self._transversal_slp = []
# these attributes are assigned after running _random_pr_init
self._random_gens = []
# finite presentation of the group as an instance of `FpGroup`
self._fp_presentation = None
def __getitem__(self, i):
return self._generators[i]
def __contains__(self, i):
"""Return ``True`` if *i* is contained in PermutationGroup.
Examples
========
>>> from sympy.combinatorics import Permutation, PermutationGroup
>>> p = Permutation(1, 2, 3)
>>> Permutation(3) in PermutationGroup(p)
True
"""
if not isinstance(i, Permutation):
raise TypeError("A PermutationGroup contains only Permutations as "
"elements, not elements of type %s" % type(i))
return self.contains(i)
def __len__(self):
return len(self._generators)
def equals(self, other):
"""Return ``True`` if PermutationGroup generated by elements in the
group are same i.e they represent the same PermutationGroup.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> p = Permutation(0, 1, 2, 3, 4, 5)
>>> G = PermutationGroup([p, p**2])
>>> H = PermutationGroup([p**2, p])
>>> G.generators == H.generators
False
>>> G.equals(H)
True
"""
if not isinstance(other, PermutationGroup):
return False
set_self_gens = set(self.generators)
set_other_gens = set(other.generators)
# before reaching the general case there are also certain
# optimisation and obvious cases requiring less or no actual
# computation.
if set_self_gens == set_other_gens:
return True
# in the most general case it will check that each generator of
# one group belongs to the other PermutationGroup and vice-versa
for gen1 in set_self_gens:
if not other.contains(gen1):
return False
for gen2 in set_other_gens:
if not self.contains(gen2):
return False
return True
def __mul__(self, other):
"""
Return the direct product of two permutation groups as a permutation
group.
Explanation
===========
This implementation realizes the direct product by shifting the index
set for the generators of the second group: so if we have ``G`` acting
on ``n1`` points and ``H`` acting on ``n2`` points, ``G*H`` acts on
``n1 + n2`` points.
Examples
========
>>> from sympy.combinatorics.named_groups import CyclicGroup
>>> G = CyclicGroup(5)
>>> H = G*G
>>> H
PermutationGroup([
(9)(0 1 2 3 4),
(5 6 7 8 9)])
>>> H.order()
25
"""
if isinstance(other, Permutation):
return Coset(other, self, dir='+')
gens1 = [perm._array_form for perm in self.generators]
gens2 = [perm._array_form for perm in other.generators]
n1 = self._degree
n2 = other._degree
start = list(range(n1))
end = list(range(n1, n1 + n2))
for i in range(len(gens2)):
gens2[i] = [x + n1 for x in gens2[i]]
gens2 = [start + gen for gen in gens2]
gens1 = [gen + end for gen in gens1]
together = gens1 + gens2
gens = [_af_new(x) for x in together]
return PermutationGroup(gens)
def _random_pr_init(self, r, n, _random_prec_n=None):
r"""Initialize random generators for the product replacement algorithm.
Explanation
===========
The implementation uses a modification of the original product
replacement algorithm due to Leedham-Green, as described in [1],
pp. 69-71; also, see [2], pp. 27-29 for a detailed theoretical
analysis of the original product replacement algorithm, and [4].
The product replacement algorithm is used for producing random,
uniformly distributed elements of a group `G` with a set of generators
`S`. For the initialization ``_random_pr_init``, a list ``R`` of
`\max\{r, |S|\}` group generators is created as the attribute
``G._random_gens``, repeating elements of `S` if necessary, and the
identity element of `G` is appended to ``R`` - we shall refer to this
last element as the accumulator. Then the function ``random_pr()``
is called ``n`` times, randomizing the list ``R`` while preserving
the generation of `G` by ``R``. The function ``random_pr()`` itself
takes two random elements ``g, h`` among all elements of ``R`` but
the accumulator and replaces ``g`` with a randomly chosen element
from `\{gh, g(~h), hg, (~h)g\}`. Then the accumulator is multiplied
by whatever ``g`` was replaced by. The new value of the accumulator is
then returned by ``random_pr()``.
The elements returned will eventually (for ``n`` large enough) become
uniformly distributed across `G` ([5]). For practical purposes however,
the values ``n = 50, r = 11`` are suggested in [1].
Notes
=====
THIS FUNCTION HAS SIDE EFFECTS: it changes the attribute
self._random_gens
See Also
========
random_pr
"""
deg = self.degree
random_gens = [x._array_form for x in self.generators]
k = len(random_gens)
if k < r:
for i in range(k, r):
random_gens.append(random_gens[i - k])
acc = list(range(deg))
random_gens.append(acc)
self._random_gens = random_gens
# handle randomized input for testing purposes
if _random_prec_n is None:
for i in range(n):
self.random_pr()
else:
for i in range(n):
self.random_pr(_random_prec=_random_prec_n[i])
def _union_find_merge(self, first, second, ranks, parents, not_rep):
"""Merges two classes in a union-find data structure.
Explanation
===========
Used in the implementation of Atkinson's algorithm as suggested in [1],
pp. 83-87. The class merging process uses union by rank as an
optimization. ([7])
Notes
=====
THIS FUNCTION HAS SIDE EFFECTS: the list of class representatives,
``parents``, the list of class sizes, ``ranks``, and the list of
elements that are not representatives, ``not_rep``, are changed due to
class merging.
See Also
========
minimal_block, _union_find_rep
References
==========
.. [1] Holt, D., Eick, B., O'Brien, E.
"Handbook of computational group theory"
.. [7] http://www.algorithmist.com/index.php/Union_Find
"""
rep_first = self._union_find_rep(first, parents)
rep_second = self._union_find_rep(second, parents)
if rep_first != rep_second:
# union by rank
if ranks[rep_first] >= ranks[rep_second]:
new_1, new_2 = rep_first, rep_second
else:
new_1, new_2 = rep_second, rep_first
total_rank = ranks[new_1] + ranks[new_2]
if total_rank > self.max_div:
return -1
parents[new_2] = new_1
ranks[new_1] = total_rank
not_rep.append(new_2)
return 1
return 0
def _union_find_rep(self, num, parents):
"""Find representative of a class in a union-find data structure.
Explanation
===========
Used in the implementation of Atkinson's algorithm as suggested in [1],
pp. 83-87. After the representative of the class to which ``num``
belongs is found, path compression is performed as an optimization
([7]).
Notes
=====
THIS FUNCTION HAS SIDE EFFECTS: the list of class representatives,
``parents``, is altered due to path compression.
See Also
========
minimal_block, _union_find_merge
References
==========
.. [1] Holt, D., Eick, B., O'Brien, E.
"Handbook of computational group theory"
.. [7] http://www.algorithmist.com/index.php/Union_Find
"""
rep, parent = num, parents[num]
while parent != rep:
rep = parent
parent = parents[rep]
# path compression
temp, parent = num, parents[num]
while parent != rep:
parents[temp] = rep
temp = parent
parent = parents[temp]
return rep
@property
def base(self):
r"""Return a base from the Schreier-Sims algorithm.
Explanation
===========
For a permutation group `G`, a base is a sequence of points
`B = (b_1, b_2, \dots, b_k)` such that no element of `G` apart
from the identity fixes all the points in `B`. The concepts of
a base and strong generating set and their applications are
discussed in depth in [1], pp. 87-89 and [2], pp. 55-57.
An alternative way to think of `B` is that it gives the
indices of the stabilizer cosets that contain more than the
identity permutation.
Examples
========
>>> from sympy.combinatorics import Permutation, PermutationGroup
>>> G = PermutationGroup([Permutation(0, 1, 3)(2, 4)])
>>> G.base
[0, 2]
See Also
========
strong_gens, basic_transversals, basic_orbits, basic_stabilizers
"""
if self._base == []:
self.schreier_sims()
return self._base
def baseswap(self, base, strong_gens, pos, randomized=False,
transversals=None, basic_orbits=None, strong_gens_distr=None):
r"""Swap two consecutive base points in base and strong generating set.
Explanation
===========
If a base for a group `G` is given by `(b_1, b_2, \dots, b_k)`, this
function returns a base `(b_1, b_2, \dots, b_{i+1}, b_i, \dots, b_k)`,
where `i` is given by ``pos``, and a strong generating set relative
to that base. The original base and strong generating set are not
modified.
The randomized version (default) is of Las Vegas type.
Parameters
==========
base, strong_gens
The base and strong generating set.
pos
The position at which swapping is performed.
randomized
A switch between randomized and deterministic version.
transversals
The transversals for the basic orbits, if known.
basic_orbits
The basic orbits, if known.
strong_gens_distr
The strong generators distributed by basic stabilizers, if known.
Returns
=======
(base, strong_gens)
``base`` is the new base, and ``strong_gens`` is a generating set
relative to it.
Examples
========
>>> from sympy.combinatorics.named_groups import SymmetricGroup
>>> from sympy.combinatorics.testutil import _verify_bsgs
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> S = SymmetricGroup(4)
>>> S.schreier_sims()
>>> S.base
[0, 1, 2]
>>> base, gens = S.baseswap(S.base, S.strong_gens, 1, randomized=False)
>>> base, gens
([0, 2, 1],
[(0 1 2 3), (3)(0 1), (1 3 2),
(2 3), (1 3)])
check that base, gens is a BSGS
>>> S1 = PermutationGroup(gens)
>>> _verify_bsgs(S1, base, gens)
True
See Also
========
schreier_sims
Notes
=====
The deterministic version of the algorithm is discussed in
[1], pp. 102-103; the randomized version is discussed in [1], p.103, and
[2], p.98. It is of Las Vegas type.
Notice that [1] contains a mistake in the pseudocode and
discussion of BASESWAP: on line 3 of the pseudocode,
`|\beta_{i+1}^{\left\langle T\right\rangle}|` should be replaced by
`|\beta_{i}^{\left\langle T\right\rangle}|`, and the same for the
discussion of the algorithm.
"""
# construct the basic orbits, generators for the stabilizer chain
# and transversal elements from whatever was provided
transversals, basic_orbits, strong_gens_distr = \
_handle_precomputed_bsgs(base, strong_gens, transversals,
basic_orbits, strong_gens_distr)
base_len = len(base)
degree = self.degree
# size of orbit of base[pos] under the stabilizer we seek to insert
# in the stabilizer chain at position pos + 1
size = len(basic_orbits[pos])*len(basic_orbits[pos + 1]) \
//len(_orbit(degree, strong_gens_distr[pos], base[pos + 1]))
# initialize the wanted stabilizer by a subgroup
if pos + 2 > base_len - 1:
T = []
else:
T = strong_gens_distr[pos + 2][:]
# randomized version
if randomized is True:
stab_pos = PermutationGroup(strong_gens_distr[pos])
schreier_vector = stab_pos.schreier_vector(base[pos + 1])
# add random elements of the stabilizer until they generate it
while len(_orbit(degree, T, base[pos])) != size:
new = stab_pos.random_stab(base[pos + 1],
schreier_vector=schreier_vector)
T.append(new)
# deterministic version
else:
Gamma = set(basic_orbits[pos])
Gamma.remove(base[pos])
if base[pos + 1] in Gamma:
Gamma.remove(base[pos + 1])
# add elements of the stabilizer until they generate it by
# ruling out member of the basic orbit of base[pos] along the way
while len(_orbit(degree, T, base[pos])) != size:
gamma = next(iter(Gamma))
x = transversals[pos][gamma]
temp = x._array_form.index(base[pos + 1]) # (~x)(base[pos + 1])
if temp not in basic_orbits[pos + 1]:
Gamma = Gamma - _orbit(degree, T, gamma)
else:
y = transversals[pos + 1][temp]
el = rmul(x, y)
if el(base[pos]) not in _orbit(degree, T, base[pos]):
T.append(el)
Gamma = Gamma - _orbit(degree, T, base[pos])
# build the new base and strong generating set
strong_gens_new_distr = strong_gens_distr[:]
strong_gens_new_distr[pos + 1] = T
base_new = base[:]
base_new[pos], base_new[pos + 1] = base_new[pos + 1], base_new[pos]
strong_gens_new = _strong_gens_from_distr(strong_gens_new_distr)
for gen in T:
if gen not in strong_gens_new:
strong_gens_new.append(gen)
return base_new, strong_gens_new
@property
def basic_orbits(self):
r"""
Return the basic orbits relative to a base and strong generating set.
Explanation
===========
If `(b_1, b_2, \dots, b_k)` is a base for a group `G`, and
`G^{(i)} = G_{b_1, b_2, \dots, b_{i-1}}` is the ``i``-th basic stabilizer
(so that `G^{(1)} = G`), the ``i``-th basic orbit relative to this base
is the orbit of `b_i` under `G^{(i)}`. See [1], pp. 87-89 for more
information.
Examples
========
>>> from sympy.combinatorics.named_groups import SymmetricGroup
>>> S = SymmetricGroup(4)
>>> S.basic_orbits
[[0, 1, 2, 3], [1, 2, 3], [2, 3]]
See Also
========
base, strong_gens, basic_transversals, basic_stabilizers
"""
if self._basic_orbits == []:
self.schreier_sims()
return self._basic_orbits
@property
def basic_stabilizers(self):
r"""
Return a chain of stabilizers relative to a base and strong generating
set.
Explanation
===========
The ``i``-th basic stabilizer `G^{(i)}` relative to a base
`(b_1, b_2, \dots, b_k)` is `G_{b_1, b_2, \dots, b_{i-1}}`. For more
information, see [1], pp. 87-89.
Examples
========
>>> from sympy.combinatorics.named_groups import AlternatingGroup
>>> A = AlternatingGroup(4)
>>> A.schreier_sims()
>>> A.base
[0, 1]
>>> for g in A.basic_stabilizers:
... print(g)
...
PermutationGroup([
(3)(0 1 2),
(1 2 3)])
PermutationGroup([
(1 2 3)])
See Also
========
base, strong_gens, basic_orbits, basic_transversals
"""
if self._transversals == []:
self.schreier_sims()
strong_gens = self._strong_gens
base = self._base
if not base: # e.g. if self is trivial
return []
strong_gens_distr = _distribute_gens_by_base(base, strong_gens)
basic_stabilizers = []
for gens in strong_gens_distr:
basic_stabilizers.append(PermutationGroup(gens))
return basic_stabilizers
@property
def basic_transversals(self):
"""
Return basic transversals relative to a base and strong generating set.
Explanation
===========
The basic transversals are transversals of the basic orbits. They
are provided as a list of dictionaries, each dictionary having
keys - the elements of one of the basic orbits, and values - the
corresponding transversal elements. See [1], pp. 87-89 for more
information.
Examples
========
>>> from sympy.combinatorics.named_groups import AlternatingGroup
>>> A = AlternatingGroup(4)
>>> A.basic_transversals
[{0: (3), 1: (3)(0 1 2), 2: (3)(0 2 1), 3: (0 3 1)}, {1: (3), 2: (1 2 3), 3: (1 3 2)}]
See Also
========
strong_gens, base, basic_orbits, basic_stabilizers
"""
if self._transversals == []:
self.schreier_sims()
return self._transversals
def composition_series(self):
r"""
Return the composition series for a group as a list
of permutation groups.
Explanation
===========
The composition series for a group `G` is defined as a
subnormal series `G = H_0 > H_1 > H_2 \ldots` A composition
series is a subnormal series such that each factor group
`H(i+1) / H(i)` is simple.
A subnormal series is a composition series only if it is of
maximum length.
The algorithm works as follows:
Starting with the derived series the idea is to fill
the gap between `G = der[i]` and `H = der[i+1]` for each
`i` independently. Since, all subgroups of the abelian group
`G/H` are normal so, first step is to take the generators
`g` of `G` and add them to generators of `H` one by one.
The factor groups formed are not simple in general. Each
group is obtained from the previous one by adding one
generator `g`, if the previous group is denoted by `H`
then the next group `K` is generated by `g` and `H`.
The factor group `K/H` is cyclic and it's order is
`K.order()//G.order()`. The series is then extended between
`K` and `H` by groups generated by powers of `g` and `H`.
The series formed is then prepended to the already existing
series.
Examples
========
>>> from sympy.combinatorics.named_groups import SymmetricGroup
>>> from sympy.combinatorics.named_groups import CyclicGroup
>>> S = SymmetricGroup(12)
>>> G = S.sylow_subgroup(2)
>>> C = G.composition_series()
>>> [H.order() for H in C]
[1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1]
>>> G = S.sylow_subgroup(3)
>>> C = G.composition_series()
>>> [H.order() for H in C]
[243, 81, 27, 9, 3, 1]
>>> G = CyclicGroup(12)
>>> C = G.composition_series()
>>> [H.order() for H in C]
[12, 6, 3, 1]
"""
der = self.derived_series()
if not all(g.is_identity for g in der[-1].generators):
raise NotImplementedError('Group should be solvable')
series = []
for i in range(len(der)-1):
H = der[i+1]
up_seg = []
for g in der[i].generators:
K = PermutationGroup([g] + H.generators)
order = K.order() // H.order()
down_seg = []
for p, e in factorint(order).items():
for _ in range(e):
down_seg.append(PermutationGroup([g] + H.generators))
g = g**p
up_seg = down_seg + up_seg
H = K
up_seg[0] = der[i]
series.extend(up_seg)
series.append(der[-1])
return series
def coset_transversal(self, H):
"""Return a transversal of the right cosets of self by its subgroup H
using the second method described in [1], Subsection 4.6.7
"""
if not H.is_subgroup(self):
raise ValueError("The argument must be a subgroup")
if H.order() == 1:
return self._elements
self._schreier_sims(base=H.base) # make G.base an extension of H.base
base = self.base
base_ordering = _base_ordering(base, self.degree)
identity = Permutation(self.degree - 1)
transversals = self.basic_transversals[:]
# transversals is a list of dictionaries. Get rid of the keys
# so that it is a list of lists and sort each list in
# the increasing order of base[l]^x
for l, t in enumerate(transversals):
transversals[l] = sorted(t.values(),
key = lambda x: base_ordering[base[l]^x])
orbits = H.basic_orbits
h_stabs = H.basic_stabilizers
g_stabs = self.basic_stabilizers
indices = [x.order()//y.order() for x, y in zip(g_stabs, h_stabs)]
# T^(l) should be a right transversal of H^(l) in G^(l) for
# 1<=l<=len(base). While H^(l) is the trivial group, T^(l)
# contains all the elements of G^(l) so we might just as well
# start with l = len(h_stabs)-1
if len(g_stabs) > len(h_stabs):
T = g_stabs[len(h_stabs)]._elements
else:
T = [identity]
l = len(h_stabs)-1
t_len = len(T)
while l > -1:
T_next = []
for u in transversals[l]:
if u == identity:
continue
b = base_ordering[base[l]^u]
for t in T:
p = t*u
if all(base_ordering[h^p] >= b for h in orbits[l]):
T_next.append(p)
if t_len + len(T_next) == indices[l]:
break
if t_len + len(T_next) == indices[l]:
break
T += T_next
t_len += len(T_next)
l -= 1
T.remove(identity)
T = [identity] + T
return T
def _coset_representative(self, g, H):
"""Return the representative of Hg from the transversal that
would be computed by ``self.coset_transversal(H)``.
"""
if H.order() == 1:
return g
# The base of self must be an extension of H.base.
if not(self.base[:len(H.base)] == H.base):
self._schreier_sims(base=H.base)
orbits = H.basic_orbits[:]
h_transversals = [list(_.values()) for _ in H.basic_transversals]
transversals = [list(_.values()) for _ in self.basic_transversals]
base = self.base
base_ordering = _base_ordering(base, self.degree)
def step(l, x):
gamma = sorted(orbits[l], key = lambda y: base_ordering[y^x])[0]
i = [base[l]^h for h in h_transversals[l]].index(gamma)
x = h_transversals[l][i]*x
if l < len(orbits)-1:
for u in transversals[l]:
if base[l]^u == base[l]^x:
break
x = step(l+1, x*u**-1)*u
return x
return step(0, g)
def coset_table(self, H):
"""Return the standardised (right) coset table of self in H as
a list of lists.
"""
# Maybe this should be made to return an instance of CosetTable
# from fp_groups.py but the class would need to be changed first
# to be compatible with PermutationGroups
from itertools import chain, product
if not H.is_subgroup(self):
raise ValueError("The argument must be a subgroup")
T = self.coset_transversal(H)
n = len(T)
A = list(chain.from_iterable((gen, gen**-1)
for gen in self.generators))
table = []
for i in range(n):
row = [self._coset_representative(T[i]*x, H) for x in A]
row = [T.index(r) for r in row]
table.append(row)
# standardize (this is the same as the algorithm used in coset_table)
# If CosetTable is made compatible with PermutationGroups, this
# should be replaced by table.standardize()
A = range(len(A))
gamma = 1
for alpha, a in product(range(n), A):
beta = table[alpha][a]
if beta >= gamma:
if beta > gamma:
for x in A:
z = table[gamma][x]
table[gamma][x] = table[beta][x]
table[beta][x] = z
for i in range(n):
if table[i][x] == beta:
table[i][x] = gamma
elif table[i][x] == gamma:
table[i][x] = beta
gamma += 1
if gamma >= n-1:
return table
def center(self):
r"""
Return the center of a permutation group.
Explanation
===========
The center for a group `G` is defined as
`Z(G) = \{z\in G | \forall g\in G, zg = gz \}`,
the set of elements of `G` that commute with all elements of `G`.
It is equal to the centralizer of `G` inside `G`, and is naturally a
subgroup of `G` ([9]).
Examples
========
>>> from sympy.combinatorics.named_groups import DihedralGroup
>>> D = DihedralGroup(4)
>>> G = D.center()
>>> G.order()
2
See Also
========
centralizer
Notes
=====
This is a naive implementation that is a straightforward application
of ``.centralizer()``
"""
return self.centralizer(self)
def centralizer(self, other):
r"""
Return the centralizer of a group/set/element.
Explanation
===========
The centralizer of a set of permutations ``S`` inside
a group ``G`` is the set of elements of ``G`` that commute with all
elements of ``S``::
`C_G(S) = \{ g \in G | gs = sg \forall s \in S\}` ([10])
Usually, ``S`` is a subset of ``G``, but if ``G`` is a proper subgroup of
the full symmetric group, we allow for ``S`` to have elements outside
``G``.
It is naturally a subgroup of ``G``; the centralizer of a permutation
group is equal to the centralizer of any set of generators for that
group, since any element commuting with the generators commutes with
any product of the generators.
Parameters
==========
other
a permutation group/list of permutations/single permutation
Examples
========
>>> from sympy.combinatorics.named_groups import (SymmetricGroup,
... CyclicGroup)
>>> S = SymmetricGroup(6)
>>> C = CyclicGroup(6)
>>> H = S.centralizer(C)
>>> H.is_subgroup(C)
True
See Also
========
subgroup_search
Notes
=====
The implementation is an application of ``.subgroup_search()`` with
tests using a specific base for the group ``G``.
"""
if hasattr(other, 'generators'):
if other.is_trivial or self.is_trivial:
return self
degree = self.degree
identity = _af_new(list(range(degree)))
orbits = other.orbits()
num_orbits = len(orbits)
orbits.sort(key=lambda x: -len(x))
long_base = []
orbit_reps = [None]*num_orbits
orbit_reps_indices = [None]*num_orbits
orbit_descr = [None]*degree
for i in range(num_orbits):
orbit = list(orbits[i])
orbit_reps[i] = orbit[0]
orbit_reps_indices[i] = len(long_base)
for point in orbit:
orbit_descr[point] = i
long_base = long_base + orbit
base, strong_gens = self.schreier_sims_incremental(base=long_base)
strong_gens_distr = _distribute_gens_by_base(base, strong_gens)
i = 0
for i in range(len(base)):
if strong_gens_distr[i] == [identity]:
break
base = base[:i]
base_len = i
for j in range(num_orbits):
if base[base_len - 1] in orbits[j]:
break
rel_orbits = orbits[: j + 1]
num_rel_orbits = len(rel_orbits)
transversals = [None]*num_rel_orbits
for j in range(num_rel_orbits):
rep = orbit_reps[j]
transversals[j] = dict(
other.orbit_transversal(rep, pairs=True))
trivial_test = lambda x: True
tests = [None]*base_len
for l in range(base_len):
if base[l] in orbit_reps:
tests[l] = trivial_test
else:
def test(computed_words, l=l):
g = computed_words[l]
rep_orb_index = orbit_descr[base[l]]
rep = orbit_reps[rep_orb_index]
im = g._array_form[base[l]]
im_rep = g._array_form[rep]
tr_el = transversals[rep_orb_index][base[l]]
# using the definition of transversal,
# base[l]^g = rep^(tr_el*g);
# if g belongs to the centralizer, then
# base[l]^g = (rep^g)^tr_el
return im == tr_el._array_form[im_rep]
tests[l] = test
def prop(g):
return [rmul(g, gen) for gen in other.generators] == \
[rmul(gen, g) for gen in other.generators]
return self.subgroup_search(prop, base=base,
strong_gens=strong_gens, tests=tests)
elif hasattr(other, '__getitem__'):
gens = list(other)
return self.centralizer(PermutationGroup(gens))
elif hasattr(other, 'array_form'):
return self.centralizer(PermutationGroup([other]))
def commutator(self, G, H):
"""
Return the commutator of two subgroups.
Explanation
===========
For a permutation group ``K`` and subgroups ``G``, ``H``, the
commutator of ``G`` and ``H`` is defined as the group generated
by all the commutators `[g, h] = hgh^{-1}g^{-1}` for ``g`` in ``G`` and
``h`` in ``H``. It is naturally a subgroup of ``K`` ([1], p.27).
Examples
========
>>> from sympy.combinatorics.named_groups import (SymmetricGroup,
... AlternatingGroup)
>>> S = SymmetricGroup(5)
>>> A = AlternatingGroup(5)
>>> G = S.commutator(S, A)
>>> G.is_subgroup(A)
True
See Also
========
derived_subgroup
Notes
=====
The commutator of two subgroups `H, G` is equal to the normal closure
of the commutators of all the generators, i.e. `hgh^{-1}g^{-1}` for `h`
a generator of `H` and `g` a generator of `G` ([1], p.28)
"""
ggens = G.generators
hgens = H.generators
commutators = []
for ggen in ggens:
for hgen in hgens:
commutator = rmul(hgen, ggen, ~hgen, ~ggen)
if commutator not in commutators:
commutators.append(commutator)
res = self.normal_closure(commutators)
return res
def coset_factor(self, g, factor_index=False):
"""Return ``G``'s (self's) coset factorization of ``g``
Explanation
===========
If ``g`` is an element of ``G`` then it can be written as the product
of permutations drawn from the Schreier-Sims coset decomposition,
The permutations returned in ``f`` are those for which
the product gives ``g``: ``g = f[n]*...f[1]*f[0]`` where ``n = len(B)``
and ``B = G.base``. f[i] is one of the permutations in
``self._basic_orbits[i]``.
If factor_index==True,
returns a tuple ``[b[0],..,b[n]]``, where ``b[i]``
belongs to ``self._basic_orbits[i]``
Examples
========
>>> from sympy.combinatorics import Permutation, PermutationGroup
>>> a = Permutation(0, 1, 3, 7, 6, 4)(2, 5)
>>> b = Permutation(0, 1, 3, 2)(4, 5, 7, 6)
>>> G = PermutationGroup([a, b])
Define g:
>>> g = Permutation(7)(1, 2, 4)(3, 6, 5)
Confirm that it is an element of G:
>>> G.contains(g)
True
Thus, it can be written as a product of factors (up to
3) drawn from u. See below that a factor from u1 and u2
and the Identity permutation have been used:
>>> f = G.coset_factor(g)
>>> f[2]*f[1]*f[0] == g
True
>>> f1 = G.coset_factor(g, True); f1
[0, 4, 4]
>>> tr = G.basic_transversals
>>> f[0] == tr[0][f1[0]]
True
If g is not an element of G then [] is returned:
>>> c = Permutation(5, 6, 7)
>>> G.coset_factor(c)
[]
See Also
========
sympy.combinatorics.util._strip
"""
if isinstance(g, (Cycle, Permutation)):
g = g.list()
if len(g) != self._degree:
# this could either adjust the size or return [] immediately
# but we don't choose between the two and just signal a possible
# error
raise ValueError('g should be the same size as permutations of G')
I = list(range(self._degree))
basic_orbits = self.basic_orbits
transversals = self._transversals
factors = []
base = self.base
h = g
for i in range(len(base)):
beta = h[base[i]]
if beta == base[i]:
factors.append(beta)
continue
if beta not in basic_orbits[i]:
return []
u = transversals[i][beta]._array_form
h = _af_rmul(_af_invert(u), h)
factors.append(beta)
if h != I:
return []
if factor_index:
return factors
tr = self.basic_transversals
factors = [tr[i][factors[i]] for i in range(len(base))]
return factors
def generator_product(self, g, original=False):
r'''
Return a list of strong generators `[s1, \dots, sn]`
s.t `g = sn \times \dots \times s1`. If ``original=True``, make the
list contain only the original group generators
'''
product = []
if g.is_identity:
return []
if g in self.strong_gens:
if not original or g in self.generators:
return [g]
else:
slp = self._strong_gens_slp[g]
for s in slp:
product.extend(self.generator_product(s, original=True))
return product
elif g**-1 in self.strong_gens:
g = g**-1
if not original or g in self.generators:
return [g**-1]
else:
slp = self._strong_gens_slp[g]
for s in slp:
product.extend(self.generator_product(s, original=True))
l = len(product)
product = [product[l-i-1]**-1 for i in range(l)]
return product
f = self.coset_factor(g, True)
for i, j in enumerate(f):
slp = self._transversal_slp[i][j]
for s in slp:
if not original:
product.append(self.strong_gens[s])
else:
s = self.strong_gens[s]
product.extend(self.generator_product(s, original=True))
return product
def coset_rank(self, g):
"""rank using Schreier-Sims representation.
Explanation
===========
The coset rank of ``g`` is the ordering number in which
it appears in the lexicographic listing according to the
coset decomposition
The ordering is the same as in G.generate(method='coset').
If ``g`` does not belong to the group it returns None.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation(0, 1, 3, 7, 6, 4)(2, 5)
>>> b = Permutation(0, 1, 3, 2)(4, 5, 7, 6)
>>> G = PermutationGroup([a, b])
>>> c = Permutation(7)(2, 4)(3, 5)
>>> G.coset_rank(c)
16
>>> G.coset_unrank(16)
(7)(2 4)(3 5)
See Also
========
coset_factor
"""
factors = self.coset_factor(g, True)
if not factors:
return None
rank = 0
b = 1
transversals = self._transversals
base = self._base
basic_orbits = self._basic_orbits
for i in range(len(base)):
k = factors[i]
j = basic_orbits[i].index(k)
rank += b*j
b = b*len(transversals[i])
return rank
def coset_unrank(self, rank, af=False):
"""unrank using Schreier-Sims representation
coset_unrank is the inverse operation of coset_rank
if 0 <= rank < order; otherwise it returns None.
"""
if rank < 0 or rank >= self.order():
return None
base = self.base
transversals = self.basic_transversals
basic_orbits = self.basic_orbits
m = len(base)
v = [0]*m
for i in range(m):
rank, c = divmod(rank, len(transversals[i]))
v[i] = basic_orbits[i][c]
a = [transversals[i][v[i]]._array_form for i in range(m)]
h = _af_rmuln(*a)
if af:
return h
else:
return _af_new(h)
@property
def degree(self):
"""Returns the size of the permutations in the group.
Explanation
===========
The number of permutations comprising the group is given by
``len(group)``; the number of permutations that can be generated
by the group is given by ``group.order()``.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation([1, 0, 2])
>>> G = PermutationGroup([a])
>>> G.degree
3
>>> len(G)
1
>>> G.order()
2
>>> list(G.generate())
[(2), (2)(0 1)]
See Also
========
order
"""
return self._degree
@property
def identity(self):
'''
Return the identity element of the permutation group.
'''
return _af_new(list(range(self.degree)))
@property
def elements(self):
"""Returns all the elements of the permutation group as a set
Examples
========
>>> from sympy.combinatorics import Permutation, PermutationGroup
>>> p = PermutationGroup(Permutation(1, 3), Permutation(1, 2))
>>> p.elements
{(1 2 3), (1 3 2), (1 3), (2 3), (3), (3)(1 2)}
"""
return set(self._elements)
@property
def _elements(self):
"""Returns all the elements of the permutation group as a list
Examples
========
>>> from sympy.combinatorics import Permutation, PermutationGroup
>>> p = PermutationGroup(Permutation(1, 3), Permutation(1, 2))
>>> p._elements
[(3), (3)(1 2), (1 3), (2 3), (1 2 3), (1 3 2)]
"""
return list(islice(self.generate(), None))
def derived_series(self):
r"""Return the derived series for the group.
Explanation
===========
The derived series for a group `G` is defined as
`G = G_0 > G_1 > G_2 > \ldots` where `G_i = [G_{i-1}, G_{i-1}]`,
i.e. `G_i` is the derived subgroup of `G_{i-1}`, for
`i\in\mathbb{N}`. When we have `G_k = G_{k-1}` for some
`k\in\mathbb{N}`, the series terminates.
Returns
=======
A list of permutation groups containing the members of the derived
series in the order `G = G_0, G_1, G_2, \ldots`.
Examples
========
>>> from sympy.combinatorics.named_groups import (SymmetricGroup,
... AlternatingGroup, DihedralGroup)
>>> A = AlternatingGroup(5)
>>> len(A.derived_series())
1
>>> S = SymmetricGroup(4)
>>> len(S.derived_series())
4
>>> S.derived_series()[1].is_subgroup(AlternatingGroup(4))
True
>>> S.derived_series()[2].is_subgroup(DihedralGroup(2))
True
See Also
========
derived_subgroup
"""
res = [self]
current = self
nxt = self.derived_subgroup()
while not current.is_subgroup(nxt):
res.append(nxt)
current = nxt
nxt = nxt.derived_subgroup()
return res
def derived_subgroup(self):
r"""Compute the derived subgroup.
Explanation
===========
The derived subgroup, or commutator subgroup is the subgroup generated
by all commutators `[g, h] = hgh^{-1}g^{-1}` for `g, h\in G` ; it is
equal to the normal closure of the set of commutators of the generators
([1], p.28, [11]).
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation([1, 0, 2, 4, 3])
>>> b = Permutation([0, 1, 3, 2, 4])
>>> G = PermutationGroup([a, b])
>>> C = G.derived_subgroup()
>>> list(C.generate(af=True))
[[0, 1, 2, 3, 4], [0, 1, 3, 4, 2], [0, 1, 4, 2, 3]]
See Also
========
derived_series
"""
r = self._r
gens = [p._array_form for p in self.generators]
set_commutators = set()
degree = self._degree
rng = list(range(degree))
for i in range(r):
for j in range(r):
p1 = gens[i]
p2 = gens[j]
c = list(range(degree))
for k in rng:
c[p2[p1[k]]] = p1[p2[k]]
ct = tuple(c)
if ct not in set_commutators:
set_commutators.add(ct)
cms = [_af_new(p) for p in set_commutators]
G2 = self.normal_closure(cms)
return G2
def generate(self, method="coset", af=False):
"""Return iterator to generate the elements of the group.
Explanation
===========
Iteration is done with one of these methods::
method='coset' using the Schreier-Sims coset representation
method='dimino' using the Dimino method
If ``af = True`` it yields the array form of the permutations
Examples
========
>>> from sympy.combinatorics import PermutationGroup
>>> from sympy.combinatorics.polyhedron import tetrahedron
The permutation group given in the tetrahedron object is also
true groups:
>>> G = tetrahedron.pgroup
>>> G.is_group
True
Also the group generated by the permutations in the tetrahedron
pgroup -- even the first two -- is a proper group:
>>> H = PermutationGroup(G[0], G[1])
>>> J = PermutationGroup(list(H.generate())); J
PermutationGroup([
(0 1)(2 3),
(1 2 3),
(1 3 2),
(0 3 1),
(0 2 3),
(0 3)(1 2),
(0 1 3),
(3)(0 2 1),
(0 3 2),
(3)(0 1 2),
(0 2)(1 3)])
>>> _.is_group
True
"""
if method == "coset":
return self.generate_schreier_sims(af)
elif method == "dimino":
return self.generate_dimino(af)
else:
raise NotImplementedError('No generation defined for %s' % method)
def generate_dimino(self, af=False):
"""Yield group elements using Dimino's algorithm.
If ``af == True`` it yields the array form of the permutations.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation([0, 2, 1, 3])
>>> b = Permutation([0, 2, 3, 1])
>>> g = PermutationGroup([a, b])
>>> list(g.generate_dimino(af=True))
[[0, 1, 2, 3], [0, 2, 1, 3], [0, 2, 3, 1],
[0, 1, 3, 2], [0, 3, 2, 1], [0, 3, 1, 2]]
References
==========
.. [1] The Implementation of Various Algorithms for Permutation Groups in
the Computer Algebra System: AXIOM, N.J. Doye, M.Sc. Thesis
"""
idn = list(range(self.degree))
order = 0
element_list = [idn]
set_element_list = {tuple(idn)}
if af:
yield idn
else:
yield _af_new(idn)
gens = [p._array_form for p in self.generators]
for i in range(len(gens)):
# D elements of the subgroup G_i generated by gens[:i]
D = element_list[:]
N = [idn]
while N:
A = N
N = []
for a in A:
for g in gens[:i + 1]:
ag = _af_rmul(a, g)
if tuple(ag) not in set_element_list:
# produce G_i*g
for d in D:
order += 1
ap = _af_rmul(d, ag)
if af:
yield ap
else:
p = _af_new(ap)
yield p
element_list.append(ap)
set_element_list.add(tuple(ap))
N.append(ap)
self._order = len(element_list)
def generate_schreier_sims(self, af=False):
"""Yield group elements using the Schreier-Sims representation
in coset_rank order
If ``af = True`` it yields the array form of the permutations
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation([0, 2, 1, 3])
>>> b = Permutation([0, 2, 3, 1])
>>> g = PermutationGroup([a, b])
>>> list(g.generate_schreier_sims(af=True))
[[0, 1, 2, 3], [0, 2, 1, 3], [0, 3, 2, 1],
[0, 1, 3, 2], [0, 2, 3, 1], [0, 3, 1, 2]]
"""
n = self._degree
u = self.basic_transversals
basic_orbits = self._basic_orbits
if len(u) == 0:
for x in self.generators:
if af:
yield x._array_form
else:
yield x
return
if len(u) == 1:
for i in basic_orbits[0]:
if af:
yield u[0][i]._array_form
else:
yield u[0][i]
return
u = list(reversed(u))
basic_orbits = basic_orbits[::-1]
# stg stack of group elements
stg = [list(range(n))]
posmax = [len(x) for x in u]
n1 = len(posmax) - 1
pos = [0]*n1
h = 0
while 1:
# backtrack when finished iterating over coset
if pos[h] >= posmax[h]:
if h == 0:
return
pos[h] = 0
h -= 1
stg.pop()
continue
p = _af_rmul(u[h][basic_orbits[h][pos[h]]]._array_form, stg[-1])
pos[h] += 1
stg.append(p)
h += 1
if h == n1:
if af:
for i in basic_orbits[-1]:
p = _af_rmul(u[-1][i]._array_form, stg[-1])
yield p
else:
for i in basic_orbits[-1]:
p = _af_rmul(u[-1][i]._array_form, stg[-1])
p1 = _af_new(p)
yield p1
stg.pop()
h -= 1
@property
def generators(self):
"""Returns the generators of the group.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation([0, 2, 1])
>>> b = Permutation([1, 0, 2])
>>> G = PermutationGroup([a, b])
>>> G.generators
[(1 2), (2)(0 1)]
"""
return self._generators
def contains(self, g, strict=True):
"""Test if permutation ``g`` belong to self, ``G``.
Explanation
===========
If ``g`` is an element of ``G`` it can be written as a product
of factors drawn from the cosets of ``G``'s stabilizers. To see
if ``g`` is one of the actual generators defining the group use
``G.has(g)``.
If ``strict`` is not ``True``, ``g`` will be resized, if necessary,
to match the size of permutations in ``self``.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation(1, 2)
>>> b = Permutation(2, 3, 1)
>>> G = PermutationGroup(a, b, degree=5)
>>> G.contains(G[0]) # trivial check
True
>>> elem = Permutation([[2, 3]], size=5)
>>> G.contains(elem)
True
>>> G.contains(Permutation(4)(0, 1, 2, 3))
False
If strict is False, a permutation will be resized, if
necessary:
>>> H = PermutationGroup(Permutation(5))
>>> H.contains(Permutation(3))
False
>>> H.contains(Permutation(3), strict=False)
True
To test if a given permutation is present in the group:
>>> elem in G.generators
False
>>> G.has(elem)
False
See Also
========
coset_factor, sympy.core.basic.Basic.has, __contains__
"""
if not isinstance(g, Permutation):
return False
if g.size != self.degree:
if strict:
return False
g = Permutation(g, size=self.degree)
if g in self.generators:
return True
return bool(self.coset_factor(g.array_form, True))
@property
def is_perfect(self):
"""Return ``True`` if the group is perfect.
A group is perfect if it equals to its derived subgroup.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation(1,2,3)(4,5)
>>> b = Permutation(1,2,3,4,5)
>>> G = PermutationGroup([a, b])
>>> G.is_perfect
False
"""
if self._is_perfect is None:
self._is_perfect = self.equals(self.derived_subgroup())
return self._is_perfect
@property
def is_abelian(self):
"""Test if the group is Abelian.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation([0, 2, 1])
>>> b = Permutation([1, 0, 2])
>>> G = PermutationGroup([a, b])
>>> G.is_abelian
False
>>> a = Permutation([0, 2, 1])
>>> G = PermutationGroup([a])
>>> G.is_abelian
True
"""
if self._is_abelian is not None:
return self._is_abelian
self._is_abelian = True
gens = [p._array_form for p in self.generators]
for x in gens:
for y in gens:
if y <= x:
continue
if not _af_commutes_with(x, y):
self._is_abelian = False
return False
return True
def abelian_invariants(self):
"""
Returns the abelian invariants for the given group.
Let ``G`` be a nontrivial finite abelian group. Then G is isomorphic to
the direct product of finitely many nontrivial cyclic groups of
prime-power order.
Explanation
===========
The prime-powers that occur as the orders of the factors are uniquely
determined by G. More precisely, the primes that occur in the orders of the
factors in any such decomposition of ``G`` are exactly the primes that divide
``|G|`` and for any such prime ``p``, if the orders of the factors that are
p-groups in one such decomposition of ``G`` are ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``,
then the orders of the factors that are p-groups in any such decomposition of ``G``
are ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``.
The uniquely determined integers ``p^{t_1} >= p^{t_2} >= ... p^{t_r}``, taken
for all primes that divide ``|G|`` are called the invariants of the nontrivial
group ``G`` as suggested in ([14], p. 542).
Notes
=====
We adopt the convention that the invariants of a trivial group are [].
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation([0, 2, 1])
>>> b = Permutation([1, 0, 2])
>>> G = PermutationGroup([a, b])
>>> G.abelian_invariants()
[2]
>>> from sympy.combinatorics.named_groups import CyclicGroup
>>> G = CyclicGroup(7)
>>> G.abelian_invariants()
[7]
"""
if self.is_trivial:
return []
gns = self.generators
inv = []
G = self
H = G.derived_subgroup()
Hgens = H.generators
for p in primefactors(G.order()):
ranks = []
while True:
pows = []
for g in gns:
elm = g**p
if not H.contains(elm):
pows.append(elm)
K = PermutationGroup(Hgens + pows) if pows else H
r = G.order()//K.order()
G = K
gns = pows
if r == 1:
break
ranks.append(multiplicity(p, r))
if ranks:
pows = [1]*ranks[0]
for i in ranks:
for j in range(0, i):
pows[j] = pows[j]*p
inv.extend(pows)
inv.sort()
return inv
def is_elementary(self, p):
"""Return ``True`` if the group is elementary abelian. An elementary
abelian group is a finite abelian group, where every nontrivial
element has order `p`, where `p` is a prime.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation([0, 2, 1])
>>> G = PermutationGroup([a])
>>> G.is_elementary(2)
True
>>> a = Permutation([0, 2, 1, 3])
>>> b = Permutation([3, 1, 2, 0])
>>> G = PermutationGroup([a, b])
>>> G.is_elementary(2)
True
>>> G.is_elementary(3)
False
"""
return self.is_abelian and all(g.order() == p for g in self.generators)
def _eval_is_alt_sym_naive(self, only_sym=False, only_alt=False):
"""A naive test using the group order."""
if only_sym and only_alt:
raise ValueError(
"Both {} and {} cannot be set to True"
.format(only_sym, only_alt))
n = self.degree
sym_order = 1
for i in range(2, n+1):
sym_order *= i
order = self.order()
if order == sym_order:
self._is_sym = True
self._is_alt = False
if only_alt:
return False
return True
elif 2*order == sym_order:
self._is_sym = False
self._is_alt = True
if only_sym:
return False
return True
return False
def _eval_is_alt_sym_monte_carlo(self, eps=0.05, perms=None):
"""A test using monte-carlo algorithm.
Parameters
==========
eps : float, optional
The criterion for the incorrect ``False`` return.
perms : list[Permutation], optional
If explicitly given, it tests over the given candidats
for testing.
If ``None``, it randomly computes ``N_eps`` and chooses
``N_eps`` sample of the permutation from the group.
See Also
========
_check_cycles_alt_sym
"""
if perms is None:
n = self.degree
if n < 17:
c_n = 0.34
else:
c_n = 0.57
d_n = (c_n*log(2))/log(n)
N_eps = int(-log(eps)/d_n)
perms = (self.random_pr() for i in range(N_eps))
return self._eval_is_alt_sym_monte_carlo(perms=perms)
for perm in perms:
if _check_cycles_alt_sym(perm):
return True
return False
def is_alt_sym(self, eps=0.05, _random_prec=None):
r"""Monte Carlo test for the symmetric/alternating group for degrees
>= 8.
Explanation
===========
More specifically, it is one-sided Monte Carlo with the
answer True (i.e., G is symmetric/alternating) guaranteed to be
correct, and the answer False being incorrect with probability eps.
For degree < 8, the order of the group is checked so the test
is deterministic.
Notes
=====
The algorithm itself uses some nontrivial results from group theory and
number theory:
1) If a transitive group ``G`` of degree ``n`` contains an element
with a cycle of length ``n/2 < p < n-2`` for ``p`` a prime, ``G`` is the
symmetric or alternating group ([1], pp. 81-82)
2) The proportion of elements in the symmetric/alternating group having
the property described in 1) is approximately `\log(2)/\log(n)`
([1], p.82; [2], pp. 226-227).
The helper function ``_check_cycles_alt_sym`` is used to
go over the cycles in a permutation and look for ones satisfying 1).
Examples
========
>>> from sympy.combinatorics.named_groups import DihedralGroup
>>> D = DihedralGroup(10)
>>> D.is_alt_sym()
False
See Also
========
_check_cycles_alt_sym
"""
if _random_prec is not None:
N_eps = _random_prec['N_eps']
perms= (_random_prec[i] for i in range(N_eps))
return self._eval_is_alt_sym_monte_carlo(perms=perms)
if self._is_sym or self._is_alt:
return True
if self._is_sym is False and self._is_alt is False:
return False
n = self.degree
if n < 8:
return self._eval_is_alt_sym_naive()
elif self.is_transitive():
return self._eval_is_alt_sym_monte_carlo(eps=eps)
self._is_sym, self._is_alt = False, False
return False
@property
def is_nilpotent(self):
"""Test if the group is nilpotent.
Explanation
===========
A group `G` is nilpotent if it has a central series of finite length.
Alternatively, `G` is nilpotent if its lower central series terminates
with the trivial group. Every nilpotent group is also solvable
([1], p.29, [12]).
Examples
========
>>> from sympy.combinatorics.named_groups import (SymmetricGroup,
... CyclicGroup)
>>> C = CyclicGroup(6)
>>> C.is_nilpotent
True
>>> S = SymmetricGroup(5)
>>> S.is_nilpotent
False
See Also
========
lower_central_series, is_solvable
"""
if self._is_nilpotent is None:
lcs = self.lower_central_series()
terminator = lcs[len(lcs) - 1]
gens = terminator.generators
degree = self.degree
identity = _af_new(list(range(degree)))
if all(g == identity for g in gens):
self._is_solvable = True
self._is_nilpotent = True
return True
else:
self._is_nilpotent = False
return False
else:
return self._is_nilpotent
def is_normal(self, gr, strict=True):
"""Test if ``G=self`` is a normal subgroup of ``gr``.
Explanation
===========
G is normal in gr if
for each g2 in G, g1 in gr, ``g = g1*g2*g1**-1`` belongs to G
It is sufficient to check this for each g1 in gr.generators and
g2 in G.generators.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation([1, 2, 0])
>>> b = Permutation([1, 0, 2])
>>> G = PermutationGroup([a, b])
>>> G1 = PermutationGroup([a, Permutation([2, 0, 1])])
>>> G1.is_normal(G)
True
"""
if not self.is_subgroup(gr, strict=strict):
return False
d_self = self.degree
d_gr = gr.degree
if self.is_trivial and (d_self == d_gr or not strict):
return True
if self._is_abelian:
return True
new_self = self.copy()
if not strict and d_self != d_gr:
if d_self < d_gr:
new_self = PermGroup(new_self.generators + [Permutation(d_gr - 1)])
else:
gr = PermGroup(gr.generators + [Permutation(d_self - 1)])
gens2 = [p._array_form for p in new_self.generators]
gens1 = [p._array_form for p in gr.generators]
for g1 in gens1:
for g2 in gens2:
p = _af_rmuln(g1, g2, _af_invert(g1))
if not new_self.coset_factor(p, True):
return False
return True
def is_primitive(self, randomized=True):
r"""Test if a group is primitive.
Explanation
===========
A permutation group ``G`` acting on a set ``S`` is called primitive if
``S`` contains no nontrivial block under the action of ``G``
(a block is nontrivial if its cardinality is more than ``1``).
Notes
=====
The algorithm is described in [1], p.83, and uses the function
minimal_block to search for blocks of the form `\{0, k\}` for ``k``
ranging over representatives for the orbits of `G_0`, the stabilizer of
``0``. This algorithm has complexity `O(n^2)` where ``n`` is the degree
of the group, and will perform badly if `G_0` is small.
There are two implementations offered: one finds `G_0`
deterministically using the function ``stabilizer``, and the other
(default) produces random elements of `G_0` using ``random_stab``,
hoping that they generate a subgroup of `G_0` with not too many more
orbits than `G_0` (this is suggested in [1], p.83). Behavior is changed
by the ``randomized`` flag.
Examples
========
>>> from sympy.combinatorics.named_groups import DihedralGroup
>>> D = DihedralGroup(10)
>>> D.is_primitive()
False
See Also
========
minimal_block, random_stab
"""
if self._is_primitive is not None:
return self._is_primitive
if self.is_transitive() is False:
return False
if randomized:
random_stab_gens = []
v = self.schreier_vector(0)
for _ in range(len(self)):
random_stab_gens.append(self.random_stab(0, v))
stab = PermutationGroup(random_stab_gens)
else:
stab = self.stabilizer(0)
orbits = stab.orbits()
for orb in orbits:
x = orb.pop()
if x != 0 and any(e != 0 for e in self.minimal_block([0, x])):
self._is_primitive = False
return False
self._is_primitive = True
return True
def minimal_blocks(self, randomized=True):
'''
For a transitive group, return the list of all minimal
block systems. If a group is intransitive, return `False`.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> from sympy.combinatorics.named_groups import DihedralGroup
>>> DihedralGroup(6).minimal_blocks()
[[0, 1, 0, 1, 0, 1], [0, 1, 2, 0, 1, 2]]
>>> G = PermutationGroup(Permutation(1,2,5))
>>> G.minimal_blocks()
False
See Also
========
minimal_block, is_transitive, is_primitive
'''
def _number_blocks(blocks):
# number the blocks of a block system
# in order and return the number of
# blocks and the tuple with the
# reordering
n = len(blocks)
appeared = {}
m = 0
b = [None]*n
for i in range(n):
if blocks[i] not in appeared:
appeared[blocks[i]] = m
b[i] = m
m += 1
else:
b[i] = appeared[blocks[i]]
return tuple(b), m
if not self.is_transitive():
return False
blocks = []
num_blocks = []
rep_blocks = []
if randomized:
random_stab_gens = []
v = self.schreier_vector(0)
for i in range(len(self)):
random_stab_gens.append(self.random_stab(0, v))
stab = PermutationGroup(random_stab_gens)
else:
stab = self.stabilizer(0)
orbits = stab.orbits()
for orb in orbits:
x = orb.pop()
if x != 0:
block = self.minimal_block([0, x])
num_block, _ = _number_blocks(block)
# a representative block (containing 0)
rep = {j for j in range(self.degree) if num_block[j] == 0}
# check if the system is minimal with
# respect to the already discovere ones
minimal = True
blocks_remove_mask = [False] * len(blocks)
for i, r in enumerate(rep_blocks):
if len(r) > len(rep) and rep.issubset(r):
# i-th block system is not minimal
blocks_remove_mask[i] = True
elif len(r) < len(rep) and r.issubset(rep):
# the system being checked is not minimal
minimal = False
break
# remove non-minimal representative blocks
blocks = [b for i, b in enumerate(blocks) if not blocks_remove_mask[i]]
num_blocks = [n for i, n in enumerate(num_blocks) if not blocks_remove_mask[i]]
rep_blocks = [r for i, r in enumerate(rep_blocks) if not blocks_remove_mask[i]]
if minimal and num_block not in num_blocks:
blocks.append(block)
num_blocks.append(num_block)
rep_blocks.append(rep)
return blocks
@property
def is_solvable(self):
"""Test if the group is solvable.
``G`` is solvable if its derived series terminates with the trivial
group ([1], p.29).
Examples
========
>>> from sympy.combinatorics.named_groups import SymmetricGroup
>>> S = SymmetricGroup(3)
>>> S.is_solvable
True
See Also
========
is_nilpotent, derived_series
"""
if self._is_solvable is None:
if self.order() % 2 != 0:
return True
ds = self.derived_series()
terminator = ds[len(ds) - 1]
gens = terminator.generators
degree = self.degree
identity = _af_new(list(range(degree)))
if all(g == identity for g in gens):
self._is_solvable = True
return True
else:
self._is_solvable = False
return False
else:
return self._is_solvable
def is_subgroup(self, G, strict=True):
"""Return ``True`` if all elements of ``self`` belong to ``G``.
If ``strict`` is ``False`` then if ``self``'s degree is smaller
than ``G``'s, the elements will be resized to have the same degree.
Examples
========
>>> from sympy.combinatorics import Permutation, PermutationGroup
>>> from sympy.combinatorics.named_groups import (SymmetricGroup,
... CyclicGroup)
Testing is strict by default: the degree of each group must be the
same:
>>> p = Permutation(0, 1, 2, 3, 4, 5)
>>> G1 = PermutationGroup([Permutation(0, 1, 2), Permutation(0, 1)])
>>> G2 = PermutationGroup([Permutation(0, 2), Permutation(0, 1, 2)])
>>> G3 = PermutationGroup([p, p**2])
>>> assert G1.order() == G2.order() == G3.order() == 6
>>> G1.is_subgroup(G2)
True
>>> G1.is_subgroup(G3)
False
>>> G3.is_subgroup(PermutationGroup(G3[1]))
False
>>> G3.is_subgroup(PermutationGroup(G3[0]))
True
To ignore the size, set ``strict`` to ``False``:
>>> S3 = SymmetricGroup(3)
>>> S5 = SymmetricGroup(5)
>>> S3.is_subgroup(S5, strict=False)
True
>>> C7 = CyclicGroup(7)
>>> G = S5*C7
>>> S5.is_subgroup(G, False)
True
>>> C7.is_subgroup(G, 0)
False
"""
if isinstance(G, SymmetricPermutationGroup):
if self.degree != G.degree:
return False
return True
if not isinstance(G, PermutationGroup):
return False
if self == G or self.generators[0]==Permutation():
return True
if G.order() % self.order() != 0:
return False
if self.degree == G.degree or \
(self.degree < G.degree and not strict):
gens = self.generators
else:
return False
return all(G.contains(g, strict=strict) for g in gens)
@property
def is_polycyclic(self):
"""Return ``True`` if a group is polycyclic. A group is polycyclic if
it has a subnormal series with cyclic factors. For finite groups,
this is the same as if the group is solvable.
Examples
========
>>> from sympy.combinatorics import Permutation, PermutationGroup
>>> a = Permutation([0, 2, 1, 3])
>>> b = Permutation([2, 0, 1, 3])
>>> G = PermutationGroup([a, b])
>>> G.is_polycyclic
True
"""
return self.is_solvable
def is_transitive(self, strict=True):
"""Test if the group is transitive.
Explanation
===========
A group is transitive if it has a single orbit.
If ``strict`` is ``False`` the group is transitive if it has
a single orbit of length different from 1.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation([0, 2, 1, 3])
>>> b = Permutation([2, 0, 1, 3])
>>> G1 = PermutationGroup([a, b])
>>> G1.is_transitive()
False
>>> G1.is_transitive(strict=False)
True
>>> c = Permutation([2, 3, 0, 1])
>>> G2 = PermutationGroup([a, c])
>>> G2.is_transitive()
True
>>> d = Permutation([1, 0, 2, 3])
>>> e = Permutation([0, 1, 3, 2])
>>> G3 = PermutationGroup([d, e])
>>> G3.is_transitive() or G3.is_transitive(strict=False)
False
"""
if self._is_transitive: # strict or not, if True then True
return self._is_transitive
if strict:
if self._is_transitive is not None: # we only store strict=True
return self._is_transitive
ans = len(self.orbit(0)) == self.degree
self._is_transitive = ans
return ans
got_orb = False
for x in self.orbits():
if len(x) > 1:
if got_orb:
return False
got_orb = True
return got_orb
@property
def is_trivial(self):
"""Test if the group is the trivial group.
This is true if the group contains only the identity permutation.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> G = PermutationGroup([Permutation([0, 1, 2])])
>>> G.is_trivial
True
"""
if self._is_trivial is None:
self._is_trivial = len(self) == 1 and self[0].is_Identity
return self._is_trivial
def lower_central_series(self):
r"""Return the lower central series for the group.
The lower central series for a group `G` is the series
`G = G_0 > G_1 > G_2 > \ldots` where
`G_k = [G, G_{k-1}]`, i.e. every term after the first is equal to the
commutator of `G` and the previous term in `G1` ([1], p.29).
Returns
=======
A list of permutation groups in the order `G = G_0, G_1, G_2, \ldots`
Examples
========
>>> from sympy.combinatorics.named_groups import (AlternatingGroup,
... DihedralGroup)
>>> A = AlternatingGroup(4)
>>> len(A.lower_central_series())
2
>>> A.lower_central_series()[1].is_subgroup(DihedralGroup(2))
True
See Also
========
commutator, derived_series
"""
res = [self]
current = self
nxt = self.commutator(self, current)
while not current.is_subgroup(nxt):
res.append(nxt)
current = nxt
nxt = self.commutator(self, current)
return res
@property
def max_div(self):
"""Maximum proper divisor of the degree of a permutation group.
Explanation
===========
Obviously, this is the degree divided by its minimal proper divisor
(larger than ``1``, if one exists). As it is guaranteed to be prime,
the ``sieve`` from ``sympy.ntheory`` is used.
This function is also used as an optimization tool for the functions
``minimal_block`` and ``_union_find_merge``.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> G = PermutationGroup([Permutation([0, 2, 1, 3])])
>>> G.max_div
2
See Also
========
minimal_block, _union_find_merge
"""
if self._max_div is not None:
return self._max_div
n = self.degree
if n == 1:
return 1
for x in sieve:
if n % x == 0:
d = n//x
self._max_div = d
return d
def minimal_block(self, points):
r"""For a transitive group, finds the block system generated by
``points``.
Explanation
===========
If a group ``G`` acts on a set ``S``, a nonempty subset ``B`` of ``S``
is called a block under the action of ``G`` if for all ``g`` in ``G``
we have ``gB = B`` (``g`` fixes ``B``) or ``gB`` and ``B`` have no
common points (``g`` moves ``B`` entirely). ([1], p.23; [6]).
The distinct translates ``gB`` of a block ``B`` for ``g`` in ``G``
partition the set ``S`` and this set of translates is known as a block
system. Moreover, we obviously have that all blocks in the partition
have the same size, hence the block size divides ``|S|`` ([1], p.23).
A ``G``-congruence is an equivalence relation ``~`` on the set ``S``
such that ``a ~ b`` implies ``g(a) ~ g(b)`` for all ``g`` in ``G``.
For a transitive group, the equivalence classes of a ``G``-congruence
and the blocks of a block system are the same thing ([1], p.23).
The algorithm below checks the group for transitivity, and then finds
the ``G``-congruence generated by the pairs ``(p_0, p_1), (p_0, p_2),
..., (p_0,p_{k-1})`` which is the same as finding the maximal block
system (i.e., the one with minimum block size) such that
``p_0, ..., p_{k-1}`` are in the same block ([1], p.83).
It is an implementation of Atkinson's algorithm, as suggested in [1],
and manipulates an equivalence relation on the set ``S`` using a
union-find data structure. The running time is just above
`O(|points||S|)`. ([1], pp. 83-87; [7]).
Examples
========
>>> from sympy.combinatorics.named_groups import DihedralGroup
>>> D = DihedralGroup(10)
>>> D.minimal_block([0, 5])
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
>>> D.minimal_block([0, 1])
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
See Also
========
_union_find_rep, _union_find_merge, is_transitive, is_primitive
"""
if not self.is_transitive():
return False
n = self.degree
gens = self.generators
# initialize the list of equivalence class representatives
parents = list(range(n))
ranks = [1]*n
not_rep = []
k = len(points)
# the block size must divide the degree of the group
if k > self.max_div:
return [0]*n
for i in range(k - 1):
parents[points[i + 1]] = points[0]
not_rep.append(points[i + 1])
ranks[points[0]] = k
i = 0
len_not_rep = k - 1
while i < len_not_rep:
gamma = not_rep[i]
i += 1
for gen in gens:
# find has side effects: performs path compression on the list
# of representatives
delta = self._union_find_rep(gamma, parents)
# union has side effects: performs union by rank on the list
# of representatives
temp = self._union_find_merge(gen(gamma), gen(delta), ranks,
parents, not_rep)
if temp == -1:
return [0]*n
len_not_rep += temp
for i in range(n):
# force path compression to get the final state of the equivalence
# relation
self._union_find_rep(i, parents)
# rewrite result so that block representatives are minimal
new_reps = {}
return [new_reps.setdefault(r, i) for i, r in enumerate(parents)]
def conjugacy_class(self, x):
r"""Return the conjugacy class of an element in the group.
Explanation
===========
The conjugacy class of an element ``g`` in a group ``G`` is the set of
elements ``x`` in ``G`` that are conjugate with ``g``, i.e. for which
``g = xax^{-1}``
for some ``a`` in ``G``.
Note that conjugacy is an equivalence relation, and therefore that
conjugacy classes are partitions of ``G``. For a list of all the
conjugacy classes of the group, use the conjugacy_classes() method.
In a permutation group, each conjugacy class corresponds to a particular
`cycle structure': for example, in ``S_3``, the conjugacy classes are:
* the identity class, ``{()}``
* all transpositions, ``{(1 2), (1 3), (2 3)}``
* all 3-cycles, ``{(1 2 3), (1 3 2)}``
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy.combinatorics.named_groups import SymmetricGroup
>>> S3 = SymmetricGroup(3)
>>> S3.conjugacy_class(Permutation(0, 1, 2))
{(0 1 2), (0 2 1)}
Notes
=====
This procedure computes the conjugacy class directly by finding the
orbit of the element under conjugation in G. This algorithm is only
feasible for permutation groups of relatively small order, but is like
the orbit() function itself in that respect.
"""
# Ref: "Computing the conjugacy classes of finite groups"; Butler, G.
# Groups '93 Galway/St Andrews; edited by Campbell, C. M.
new_class = {x}
last_iteration = new_class
while len(last_iteration) > 0:
this_iteration = set()
for y in last_iteration:
for s in self.generators:
conjugated = s * y * (~s)
if conjugated not in new_class:
this_iteration.add(conjugated)
new_class.update(last_iteration)
last_iteration = this_iteration
return new_class
def conjugacy_classes(self):
r"""Return the conjugacy classes of the group.
Explanation
===========
As described in the documentation for the .conjugacy_class() function,
conjugacy is an equivalence relation on a group G which partitions the
set of elements. This method returns a list of all these conjugacy
classes of G.
Examples
========
>>> from sympy.combinatorics import SymmetricGroup
>>> SymmetricGroup(3).conjugacy_classes()
[{(2)}, {(0 1 2), (0 2 1)}, {(0 2), (1 2), (2)(0 1)}]
"""
identity = _af_new(list(range(self.degree)))
known_elements = {identity}
classes = [known_elements.copy()]
for x in self.generate():
if x not in known_elements:
new_class = self.conjugacy_class(x)
classes.append(new_class)
known_elements.update(new_class)
return classes
def normal_closure(self, other, k=10):
r"""Return the normal closure of a subgroup/set of permutations.
Explanation
===========
If ``S`` is a subset of a group ``G``, the normal closure of ``A`` in ``G``
is defined as the intersection of all normal subgroups of ``G`` that
contain ``A`` ([1], p.14). Alternatively, it is the group generated by
the conjugates ``x^{-1}yx`` for ``x`` a generator of ``G`` and ``y`` a
generator of the subgroup ``\left\langle S\right\rangle`` generated by
``S`` (for some chosen generating set for ``\left\langle S\right\rangle``)
([1], p.73).
Parameters
==========
other
a subgroup/list of permutations/single permutation
k
an implementation-specific parameter that determines the number
of conjugates that are adjoined to ``other`` at once
Examples
========
>>> from sympy.combinatorics.named_groups import (SymmetricGroup,
... CyclicGroup, AlternatingGroup)
>>> S = SymmetricGroup(5)
>>> C = CyclicGroup(5)
>>> G = S.normal_closure(C)
>>> G.order()
60
>>> G.is_subgroup(AlternatingGroup(5))
True
See Also
========
commutator, derived_subgroup, random_pr
Notes
=====
The algorithm is described in [1], pp. 73-74; it makes use of the
generation of random elements for permutation groups by the product
replacement algorithm.
"""
if hasattr(other, 'generators'):
degree = self.degree
identity = _af_new(list(range(degree)))
if all(g == identity for g in other.generators):
return other
Z = PermutationGroup(other.generators[:])
base, strong_gens = Z.schreier_sims_incremental()
strong_gens_distr = _distribute_gens_by_base(base, strong_gens)
basic_orbits, basic_transversals = \
_orbits_transversals_from_bsgs(base, strong_gens_distr)
self._random_pr_init(r=10, n=20)
_loop = True
while _loop:
Z._random_pr_init(r=10, n=10)
for _ in range(k):
g = self.random_pr()
h = Z.random_pr()
conj = h^g
res = _strip(conj, base, basic_orbits, basic_transversals)
if res[0] != identity or res[1] != len(base) + 1:
gens = Z.generators
gens.append(conj)
Z = PermutationGroup(gens)
strong_gens.append(conj)
temp_base, temp_strong_gens = \
Z.schreier_sims_incremental(base, strong_gens)
base, strong_gens = temp_base, temp_strong_gens
strong_gens_distr = \
_distribute_gens_by_base(base, strong_gens)
basic_orbits, basic_transversals = \
_orbits_transversals_from_bsgs(base,
strong_gens_distr)
_loop = False
for g in self.generators:
for h in Z.generators:
conj = h^g
res = _strip(conj, base, basic_orbits,
basic_transversals)
if res[0] != identity or res[1] != len(base) + 1:
_loop = True
break
if _loop:
break
return Z
elif hasattr(other, '__getitem__'):
return self.normal_closure(PermutationGroup(other))
elif hasattr(other, 'array_form'):
return self.normal_closure(PermutationGroup([other]))
def orbit(self, alpha, action='tuples'):
r"""Compute the orbit of alpha `\{g(\alpha) | g \in G\}` as a set.
Explanation
===========
The time complexity of the algorithm used here is `O(|Orb|*r)` where
`|Orb|` is the size of the orbit and ``r`` is the number of generators of
the group. For a more detailed analysis, see [1], p.78, [2], pp. 19-21.
Here alpha can be a single point, or a list of points.
If alpha is a single point, the ordinary orbit is computed.
if alpha is a list of points, there are three available options:
'union' - computes the union of the orbits of the points in the list
'tuples' - computes the orbit of the list interpreted as an ordered
tuple under the group action ( i.e., g((1,2,3)) = (g(1), g(2), g(3)) )
'sets' - computes the orbit of the list interpreted as a sets
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation([1, 2, 0, 4, 5, 6, 3])
>>> G = PermutationGroup([a])
>>> G.orbit(0)
{0, 1, 2}
>>> G.orbit([0, 4], 'union')
{0, 1, 2, 3, 4, 5, 6}
See Also
========
orbit_transversal
"""
return _orbit(self.degree, self.generators, alpha, action)
def orbit_rep(self, alpha, beta, schreier_vector=None):
"""Return a group element which sends ``alpha`` to ``beta``.
Explanation
===========
If ``beta`` is not in the orbit of ``alpha``, the function returns
``False``. This implementation makes use of the schreier vector.
For a proof of correctness, see [1], p.80
Examples
========
>>> from sympy.combinatorics.named_groups import AlternatingGroup
>>> G = AlternatingGroup(5)
>>> G.orbit_rep(0, 4)
(0 4 1 2 3)
See Also
========
schreier_vector
"""
if schreier_vector is None:
schreier_vector = self.schreier_vector(alpha)
if schreier_vector[beta] is None:
return False
k = schreier_vector[beta]
gens = [x._array_form for x in self.generators]
a = []
while k != -1:
a.append(gens[k])
beta = gens[k].index(beta) # beta = (~gens[k])(beta)
k = schreier_vector[beta]
if a:
return _af_new(_af_rmuln(*a))
else:
return _af_new(list(range(self._degree)))
def orbit_transversal(self, alpha, pairs=False):
r"""Computes a transversal for the orbit of ``alpha`` as a set.
Explanation
===========
For a permutation group `G`, a transversal for the orbit
`Orb = \{g(\alpha) | g \in G\}` is a set
`\{g_\beta | g_\beta(\alpha) = \beta\}` for `\beta \in Orb`.
Note that there may be more than one possible transversal.
If ``pairs`` is set to ``True``, it returns the list of pairs
`(\beta, g_\beta)`. For a proof of correctness, see [1], p.79
Examples
========
>>> from sympy.combinatorics.named_groups import DihedralGroup
>>> G = DihedralGroup(6)
>>> G.orbit_transversal(0)
[(5), (0 1 2 3 4 5), (0 5)(1 4)(2 3), (0 2 4)(1 3 5), (5)(0 4)(1 3), (0 3)(1 4)(2 5)]
See Also
========
orbit
"""
return _orbit_transversal(self._degree, self.generators, alpha, pairs)
def orbits(self, rep=False):
"""Return the orbits of ``self``, ordered according to lowest element
in each orbit.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation(1, 5)(2, 3)(4, 0, 6)
>>> b = Permutation(1, 5)(3, 4)(2, 6, 0)
>>> G = PermutationGroup([a, b])
>>> G.orbits()
[{0, 2, 3, 4, 6}, {1, 5}]
"""
return _orbits(self._degree, self._generators)
def order(self):
"""Return the order of the group: the number of permutations that
can be generated from elements of the group.
The number of permutations comprising the group is given by
``len(group)``; the length of each permutation in the group is
given by ``group.size``.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation([1, 0, 2])
>>> G = PermutationGroup([a])
>>> G.degree
3
>>> len(G)
1
>>> G.order()
2
>>> list(G.generate())
[(2), (2)(0 1)]
>>> a = Permutation([0, 2, 1])
>>> b = Permutation([1, 0, 2])
>>> G = PermutationGroup([a, b])
>>> G.order()
6
See Also
========
degree
"""
if self._order is not None:
return self._order
if self._is_sym:
n = self._degree
self._order = factorial(n)
return self._order
if self._is_alt:
n = self._degree
self._order = factorial(n)/2
return self._order
basic_transversals = self.basic_transversals
m = 1
for x in basic_transversals:
m *= len(x)
self._order = m
return m
def index(self, H):
"""
Returns the index of a permutation group.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation(1,2,3)
>>> b =Permutation(3)
>>> G = PermutationGroup([a])
>>> H = PermutationGroup([b])
>>> G.index(H)
3
"""
if H.is_subgroup(self):
return self.order()//H.order()
@property
def is_symmetric(self):
"""Return ``True`` if the group is symmetric.
Examples
========
>>> from sympy.combinatorics.named_groups import SymmetricGroup
>>> g = SymmetricGroup(5)
>>> g.is_symmetric
True
>>> from sympy.combinatorics import Permutation, PermutationGroup
>>> g = PermutationGroup(
... Permutation(0, 1, 2, 3, 4),
... Permutation(2, 3))
>>> g.is_symmetric
True
Notes
=====
This uses a naive test involving the computation of the full
group order.
If you need more quicker taxonomy for large groups, you can use
:meth:`PermutationGroup.is_alt_sym`.
However, :meth:`PermutationGroup.is_alt_sym` may not be accurate
and is not able to distinguish between an alternating group and
a symmetric group.
See Also
========
is_alt_sym
"""
_is_sym = self._is_sym
if _is_sym is not None:
return _is_sym
n = self.degree
if n >= 8:
if self.is_transitive():
_is_alt_sym = self._eval_is_alt_sym_monte_carlo()
if _is_alt_sym:
if any(g.is_odd for g in self.generators):
self._is_sym, self._is_alt = True, False
return True
self._is_sym, self._is_alt = False, True
return False
return self._eval_is_alt_sym_naive(only_sym=True)
self._is_sym, self._is_alt = False, False
return False
return self._eval_is_alt_sym_naive(only_sym=True)
@property
def is_alternating(self):
"""Return ``True`` if the group is alternating.
Examples
========
>>> from sympy.combinatorics.named_groups import AlternatingGroup
>>> g = AlternatingGroup(5)
>>> g.is_alternating
True
>>> from sympy.combinatorics import Permutation, PermutationGroup
>>> g = PermutationGroup(
... Permutation(0, 1, 2, 3, 4),
... Permutation(2, 3, 4))
>>> g.is_alternating
True
Notes
=====
This uses a naive test involving the computation of the full
group order.
If you need more quicker taxonomy for large groups, you can use
:meth:`PermutationGroup.is_alt_sym`.
However, :meth:`PermutationGroup.is_alt_sym` may not be accurate
and is not able to distinguish between an alternating group and
a symmetric group.
See Also
========
is_alt_sym
"""
_is_alt = self._is_alt
if _is_alt is not None:
return _is_alt
n = self.degree
if n >= 8:
if self.is_transitive():
_is_alt_sym = self._eval_is_alt_sym_monte_carlo()
if _is_alt_sym:
if all(g.is_even for g in self.generators):
self._is_sym, self._is_alt = False, True
return True
self._is_sym, self._is_alt = True, False
return False
return self._eval_is_alt_sym_naive(only_alt=True)
self._is_sym, self._is_alt = False, False
return False
return self._eval_is_alt_sym_naive(only_alt=True)
@classmethod
def _distinct_primes_lemma(cls, primes):
"""Subroutine to test if there is only one cyclic group for the
order."""
primes = sorted(primes)
l = len(primes)
for i in range(l):
for j in range(i+1, l):
if primes[j] % primes[i] == 1:
return None
return True
@property
def is_cyclic(self):
r"""
Return ``True`` if the group is Cyclic.
Examples
========
>>> from sympy.combinatorics.named_groups import AbelianGroup
>>> G = AbelianGroup(3, 4)
>>> G.is_cyclic
True
>>> G = AbelianGroup(4, 4)
>>> G.is_cyclic
False
Notes
=====
If the order of a group $n$ can be factored into the distinct
primes $p_1, p_2, \dots , p_s$ and if
.. math::
\forall i, j \in \{1, 2, \dots, s \}:
p_i \not \equiv 1 \pmod {p_j}
holds true, there is only one group of the order $n$ which
is a cyclic group [1]_. This is a generalization of the lemma
that the group of order $15, 35, \dots$ are cyclic.
And also, these additional lemmas can be used to test if a
group is cyclic if the order of the group is already found.
- If the group is abelian and the order of the group is
square-free, the group is cyclic.
- If the order of the group is less than $6$ and is not $4$, the
group is cyclic.
- If the order of the group is prime, the group is cyclic.
References
==========
.. [1] 1978: John S. Rose: A Course on Group Theory,
Introduction to Finite Group Theory: 1.4
"""
if self._is_cyclic is not None:
return self._is_cyclic
if len(self.generators) == 1:
self._is_cyclic = True
self._is_abelian = True
return True
if self._is_abelian is False:
self._is_cyclic = False
return False
order = self.order()
if order < 6:
self._is_abelian = True
if order != 4:
self._is_cyclic = True
return True
factors = factorint(order)
if all(v == 1 for v in factors.values()):
if self._is_abelian:
self._is_cyclic = True
return True
primes = list(factors.keys())
if PermutationGroup._distinct_primes_lemma(primes) is True:
self._is_cyclic = True
self._is_abelian = True
return True
for p in factors:
pgens = []
for g in self.generators:
pgens.append(g**p)
if self.index(self.subgroup(pgens)) != p:
self._is_cyclic = False
return False
self._is_cyclic = True
self._is_abelian = True
return True
def pointwise_stabilizer(self, points, incremental=True):
r"""Return the pointwise stabilizer for a set of points.
Explanation
===========
For a permutation group `G` and a set of points
`\{p_1, p_2,\ldots, p_k\}`, the pointwise stabilizer of
`p_1, p_2, \ldots, p_k` is defined as
`G_{p_1,\ldots, p_k} =
\{g\in G | g(p_i) = p_i \forall i\in\{1, 2,\ldots,k\}\}` ([1],p20).
It is a subgroup of `G`.
Examples
========
>>> from sympy.combinatorics.named_groups import SymmetricGroup
>>> S = SymmetricGroup(7)
>>> Stab = S.pointwise_stabilizer([2, 3, 5])
>>> Stab.is_subgroup(S.stabilizer(2).stabilizer(3).stabilizer(5))
True
See Also
========
stabilizer, schreier_sims_incremental
Notes
=====
When incremental == True,
rather than the obvious implementation using successive calls to
``.stabilizer()``, this uses the incremental Schreier-Sims algorithm
to obtain a base with starting segment - the given points.
"""
if incremental:
base, strong_gens = self.schreier_sims_incremental(base=points)
stab_gens = []
degree = self.degree
for gen in strong_gens:
if [gen(point) for point in points] == points:
stab_gens.append(gen)
if not stab_gens:
stab_gens = _af_new(list(range(degree)))
return PermutationGroup(stab_gens)
else:
gens = self._generators
degree = self.degree
for x in points:
gens = _stabilizer(degree, gens, x)
return PermutationGroup(gens)
def make_perm(self, n, seed=None):
"""
Multiply ``n`` randomly selected permutations from
pgroup together, starting with the identity
permutation. If ``n`` is a list of integers, those
integers will be used to select the permutations and they
will be applied in L to R order: make_perm((A, B, C)) will
give CBA(I) where I is the identity permutation.
``seed`` is used to set the seed for the random selection
of permutations from pgroup. If this is a list of integers,
the corresponding permutations from pgroup will be selected
in the order give. This is mainly used for testing purposes.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a, b = [Permutation([1, 0, 3, 2]), Permutation([1, 3, 0, 2])]
>>> G = PermutationGroup([a, b])
>>> G.make_perm(1, [0])
(0 1)(2 3)
>>> G.make_perm(3, [0, 1, 0])
(0 2 3 1)
>>> G.make_perm([0, 1, 0])
(0 2 3 1)
See Also
========
random
"""
if is_sequence(n):
if seed is not None:
raise ValueError('If n is a sequence, seed should be None')
n, seed = len(n), n
else:
try:
n = int(n)
except TypeError:
raise ValueError('n must be an integer or a sequence.')
randomrange = _randrange(seed)
# start with the identity permutation
result = Permutation(list(range(self.degree)))
m = len(self)
for _ in range(n):
p = self[randomrange(m)]
result = rmul(result, p)
return result
def random(self, af=False):
"""Return a random group element
"""
rank = randrange(self.order())
return self.coset_unrank(rank, af)
def random_pr(self, gen_count=11, iterations=50, _random_prec=None):
"""Return a random group element using product replacement.
Explanation
===========
For the details of the product replacement algorithm, see
``_random_pr_init`` In ``random_pr`` the actual 'product replacement'
is performed. Notice that if the attribute ``_random_gens``
is empty, it needs to be initialized by ``_random_pr_init``.
See Also
========
_random_pr_init
"""
if self._random_gens == []:
self._random_pr_init(gen_count, iterations)
random_gens = self._random_gens
r = len(random_gens) - 1
# handle randomized input for testing purposes
if _random_prec is None:
s = randrange(r)
t = randrange(r - 1)
if t == s:
t = r - 1
x = choice([1, 2])
e = choice([-1, 1])
else:
s = _random_prec['s']
t = _random_prec['t']
if t == s:
t = r - 1
x = _random_prec['x']
e = _random_prec['e']
if x == 1:
random_gens[s] = _af_rmul(random_gens[s], _af_pow(random_gens[t], e))
random_gens[r] = _af_rmul(random_gens[r], random_gens[s])
else:
random_gens[s] = _af_rmul(_af_pow(random_gens[t], e), random_gens[s])
random_gens[r] = _af_rmul(random_gens[s], random_gens[r])
return _af_new(random_gens[r])
def random_stab(self, alpha, schreier_vector=None, _random_prec=None):
"""Random element from the stabilizer of ``alpha``.
The schreier vector for ``alpha`` is an optional argument used
for speeding up repeated calls. The algorithm is described in [1], p.81
See Also
========
random_pr, orbit_rep
"""
if schreier_vector is None:
schreier_vector = self.schreier_vector(alpha)
if _random_prec is None:
rand = self.random_pr()
else:
rand = _random_prec['rand']
beta = rand(alpha)
h = self.orbit_rep(alpha, beta, schreier_vector)
return rmul(~h, rand)
def schreier_sims(self):
"""Schreier-Sims algorithm.
Explanation
===========
It computes the generators of the chain of stabilizers
`G > G_{b_1} > .. > G_{b1,..,b_r} > 1`
in which `G_{b_1,..,b_i}` stabilizes `b_1,..,b_i`,
and the corresponding ``s`` cosets.
An element of the group can be written as the product
`h_1*..*h_s`.
We use the incremental Schreier-Sims algorithm.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> a = Permutation([0, 2, 1])
>>> b = Permutation([1, 0, 2])
>>> G = PermutationGroup([a, b])
>>> G.schreier_sims()
>>> G.basic_transversals
[{0: (2)(0 1), 1: (2), 2: (1 2)},
{0: (2), 2: (0 2)}]
"""
if self._transversals:
return
self._schreier_sims()
return
def _schreier_sims(self, base=None):
schreier = self.schreier_sims_incremental(base=base, slp_dict=True)
base, strong_gens = schreier[:2]
self._base = base
self._strong_gens = strong_gens
self._strong_gens_slp = schreier[2]
if not base:
self._transversals = []
self._basic_orbits = []
return
strong_gens_distr = _distribute_gens_by_base(base, strong_gens)
basic_orbits, transversals, slps = _orbits_transversals_from_bsgs(base,\
strong_gens_distr, slp=True)
# rewrite the indices stored in slps in terms of strong_gens
for i, slp in enumerate(slps):
gens = strong_gens_distr[i]
for k in slp:
slp[k] = [strong_gens.index(gens[s]) for s in slp[k]]
self._transversals = transversals
self._basic_orbits = [sorted(x) for x in basic_orbits]
self._transversal_slp = slps
def schreier_sims_incremental(self, base=None, gens=None, slp_dict=False):
"""Extend a sequence of points and generating set to a base and strong
generating set.
Parameters
==========
base
The sequence of points to be extended to a base. Optional
parameter with default value ``[]``.
gens
The generating set to be extended to a strong generating set
relative to the base obtained. Optional parameter with default
value ``self.generators``.
slp_dict
If `True`, return a dictionary `{g: gens}` for each strong
generator `g` where `gens` is a list of strong generators
coming before `g` in `strong_gens`, such that the product
of the elements of `gens` is equal to `g`.
Returns
=======
(base, strong_gens)
``base`` is the base obtained, and ``strong_gens`` is the strong
generating set relative to it. The original parameters ``base``,
``gens`` remain unchanged.
Examples
========
>>> from sympy.combinatorics.named_groups import AlternatingGroup
>>> from sympy.combinatorics.testutil import _verify_bsgs
>>> A = AlternatingGroup(7)
>>> base = [2, 3]
>>> seq = [2, 3]
>>> base, strong_gens = A.schreier_sims_incremental(base=seq)
>>> _verify_bsgs(A, base, strong_gens)
True
>>> base[:2]
[2, 3]
Notes
=====
This version of the Schreier-Sims algorithm runs in polynomial time.
There are certain assumptions in the implementation - if the trivial
group is provided, ``base`` and ``gens`` are returned immediately,
as any sequence of points is a base for the trivial group. If the
identity is present in the generators ``gens``, it is removed as
it is a redundant generator.
The implementation is described in [1], pp. 90-93.
See Also
========
schreier_sims, schreier_sims_random
"""
if base is None:
base = []
if gens is None:
gens = self.generators[:]
degree = self.degree
id_af = list(range(degree))
# handle the trivial group
if len(gens) == 1 and gens[0].is_Identity:
if slp_dict:
return base, gens, {gens[0]: [gens[0]]}
return base, gens
# prevent side effects
_base, _gens = base[:], gens[:]
# remove the identity as a generator
_gens = [x for x in _gens if not x.is_Identity]
# make sure no generator fixes all base points
for gen in _gens:
if all(x == gen._array_form[x] for x in _base):
for new in id_af:
if gen._array_form[new] != new:
break
else:
assert None # can this ever happen?
_base.append(new)
# distribute generators according to basic stabilizers
strong_gens_distr = _distribute_gens_by_base(_base, _gens)
strong_gens_slp = []
# initialize the basic stabilizers, basic orbits and basic transversals
orbs = {}
transversals = {}
slps = {}
base_len = len(_base)
for i in range(base_len):
transversals[i], slps[i] = _orbit_transversal(degree, strong_gens_distr[i],
_base[i], pairs=True, af=True, slp=True)
transversals[i] = dict(transversals[i])
orbs[i] = list(transversals[i].keys())
# main loop: amend the stabilizer chain until we have generators
# for all stabilizers
i = base_len - 1
while i >= 0:
# this flag is used to continue with the main loop from inside
# a nested loop
continue_i = False
# test the generators for being a strong generating set
db = {}
for beta, u_beta in list(transversals[i].items()):
for j, gen in enumerate(strong_gens_distr[i]):
gb = gen._array_form[beta]
u1 = transversals[i][gb]
g1 = _af_rmul(gen._array_form, u_beta)
slp = [(i, g) for g in slps[i][beta]]
slp = [(i, j)] + slp
if g1 != u1:
# test if the schreier generator is in the i+1-th
# would-be basic stabilizer
y = True
try:
u1_inv = db[gb]
except KeyError:
u1_inv = db[gb] = _af_invert(u1)
schreier_gen = _af_rmul(u1_inv, g1)
u1_inv_slp = slps[i][gb][:]
u1_inv_slp.reverse()
u1_inv_slp = [(i, (g,)) for g in u1_inv_slp]
slp = u1_inv_slp + slp
h, j, slp = _strip_af(schreier_gen, _base, orbs, transversals, i, slp=slp, slps=slps)
if j <= base_len:
# new strong generator h at level j
y = False
elif h:
# h fixes all base points
y = False
moved = 0
while h[moved] == moved:
moved += 1
_base.append(moved)
base_len += 1
strong_gens_distr.append([])
if y is False:
# if a new strong generator is found, update the
# data structures and start over
h = _af_new(h)
strong_gens_slp.append((h, slp))
for l in range(i + 1, j):
strong_gens_distr[l].append(h)
transversals[l], slps[l] =\
_orbit_transversal(degree, strong_gens_distr[l],
_base[l], pairs=True, af=True, slp=True)
transversals[l] = dict(transversals[l])
orbs[l] = list(transversals[l].keys())
i = j - 1
# continue main loop using the flag
continue_i = True
if continue_i is True:
break
if continue_i is True:
break
if continue_i is True:
continue
i -= 1
strong_gens = _gens[:]
if slp_dict:
# create the list of the strong generators strong_gens and
# rewrite the indices of strong_gens_slp in terms of the
# elements of strong_gens
for k, slp in strong_gens_slp:
strong_gens.append(k)
for i in range(len(slp)):
s = slp[i]
if isinstance(s[1], tuple):
slp[i] = strong_gens_distr[s[0]][s[1][0]]**-1
else:
slp[i] = strong_gens_distr[s[0]][s[1]]
strong_gens_slp = dict(strong_gens_slp)
# add the original generators
for g in _gens:
strong_gens_slp[g] = [g]
return (_base, strong_gens, strong_gens_slp)
strong_gens.extend([k for k, _ in strong_gens_slp])
return _base, strong_gens
def schreier_sims_random(self, base=None, gens=None, consec_succ=10,
_random_prec=None):
r"""Randomized Schreier-Sims algorithm.
Explanation
===========
The randomized Schreier-Sims algorithm takes the sequence ``base``
and the generating set ``gens``, and extends ``base`` to a base, and
``gens`` to a strong generating set relative to that base with
probability of a wrong answer at most `2^{-consec\_succ}`,
provided the random generators are sufficiently random.
Parameters
==========
base
The sequence to be extended to a base.
gens
The generating set to be extended to a strong generating set.
consec_succ
The parameter defining the probability of a wrong answer.
_random_prec
An internal parameter used for testing purposes.
Returns
=======
(base, strong_gens)
``base`` is the base and ``strong_gens`` is the strong generating
set relative to it.
Examples
========
>>> from sympy.combinatorics.testutil import _verify_bsgs
>>> from sympy.combinatorics.named_groups import SymmetricGroup
>>> S = SymmetricGroup(5)
>>> base, strong_gens = S.schreier_sims_random(consec_succ=5)
>>> _verify_bsgs(S, base, strong_gens) #doctest: +SKIP
True
Notes
=====
The algorithm is described in detail in [1], pp. 97-98. It extends
the orbits ``orbs`` and the permutation groups ``stabs`` to
basic orbits and basic stabilizers for the base and strong generating
set produced in the end.
The idea of the extension process
is to "sift" random group elements through the stabilizer chain
and amend the stabilizers/orbits along the way when a sift
is not successful.
The helper function ``_strip`` is used to attempt
to decompose a random group element according to the current
state of the stabilizer chain and report whether the element was
fully decomposed (successful sift) or not (unsuccessful sift). In
the latter case, the level at which the sift failed is reported and
used to amend ``stabs``, ``base``, ``gens`` and ``orbs`` accordingly.
The halting condition is for ``consec_succ`` consecutive successful
sifts to pass. This makes sure that the current ``base`` and ``gens``
form a BSGS with probability at least `1 - 1/\text{consec\_succ}`.
See Also
========
schreier_sims
"""
if base is None:
base = []
if gens is None:
gens = self.generators
base_len = len(base)
n = self.degree
# make sure no generator fixes all base points
for gen in gens:
if all(gen(x) == x for x in base):
new = 0
while gen._array_form[new] == new:
new += 1
base.append(new)
base_len += 1
# distribute generators according to basic stabilizers
strong_gens_distr = _distribute_gens_by_base(base, gens)
# initialize the basic stabilizers, basic transversals and basic orbits
transversals = {}
orbs = {}
for i in range(base_len):
transversals[i] = dict(_orbit_transversal(n, strong_gens_distr[i],
base[i], pairs=True))
orbs[i] = list(transversals[i].keys())
# initialize the number of consecutive elements sifted
c = 0
# start sifting random elements while the number of consecutive sifts
# is less than consec_succ
while c < consec_succ:
if _random_prec is None:
g = self.random_pr()
else:
g = _random_prec['g'].pop()
h, j = _strip(g, base, orbs, transversals)
y = True
# determine whether a new base point is needed
if j <= base_len:
y = False
elif not h.is_Identity:
y = False
moved = 0
while h(moved) == moved:
moved += 1
base.append(moved)
base_len += 1
strong_gens_distr.append([])
# if the element doesn't sift, amend the strong generators and
# associated stabilizers and orbits
if y is False:
for l in range(1, j):
strong_gens_distr[l].append(h)
transversals[l] = dict(_orbit_transversal(n,
strong_gens_distr[l], base[l], pairs=True))
orbs[l] = list(transversals[l].keys())
c = 0
else:
c += 1
# build the strong generating set
strong_gens = strong_gens_distr[0][:]
for gen in strong_gens_distr[1]:
if gen not in strong_gens:
strong_gens.append(gen)
return base, strong_gens
def schreier_vector(self, alpha):
"""Computes the schreier vector for ``alpha``.
Explanation
===========
The Schreier vector efficiently stores information
about the orbit of ``alpha``. It can later be used to quickly obtain
elements of the group that send ``alpha`` to a particular element
in the orbit. Notice that the Schreier vector depends on the order
in which the group generators are listed. For a definition, see [3].
Since list indices start from zero, we adopt the convention to use
"None" instead of 0 to signify that an element doesn't belong
to the orbit.
For the algorithm and its correctness, see [2], pp.78-80.
Examples
========
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> from sympy.combinatorics.permutations import Permutation
>>> a = Permutation([2, 4, 6, 3, 1, 5, 0])
>>> b = Permutation([0, 1, 3, 5, 4, 6, 2])
>>> G = PermutationGroup([a, b])
>>> G.schreier_vector(0)
[-1, None, 0, 1, None, 1, 0]
See Also
========
orbit
"""
n = self.degree
v = [None]*n
v[alpha] = -1
orb = [alpha]
used = [False]*n
used[alpha] = True
gens = self.generators
r = len(gens)
for b in orb:
for i in range(r):
temp = gens[i]._array_form[b]
if used[temp] is False:
orb.append(temp)
used[temp] = True
v[temp] = i
return v
def stabilizer(self, alpha):
r"""Return the stabilizer subgroup of ``alpha``.
Explanation
===========
The stabilizer of `\alpha` is the group `G_\alpha =
\{g \in G | g(\alpha) = \alpha\}`.
For a proof of correctness, see [1], p.79.
Examples
========
>>> from sympy.combinatorics.named_groups import DihedralGroup
>>> G = DihedralGroup(6)
>>> G.stabilizer(5)
PermutationGroup([
(5)(0 4)(1 3)])
See Also
========
orbit
"""
return PermGroup(_stabilizer(self._degree, self._generators, alpha))
@property
def strong_gens(self):
r"""Return a strong generating set from the Schreier-Sims algorithm.
Explanation
===========
A generating set `S = \{g_1, g_2, \dots, g_t\}` for a permutation group
`G` is a strong generating set relative to the sequence of points
(referred to as a "base") `(b_1, b_2, \dots, b_k)` if, for
`1 \leq i \leq k` we have that the intersection of the pointwise
stabilizer `G^{(i+1)} := G_{b_1, b_2, \dots, b_i}` with `S` generates
the pointwise stabilizer `G^{(i+1)}`. The concepts of a base and
strong generating set and their applications are discussed in depth
in [1], pp. 87-89 and [2], pp. 55-57.
Examples
========
>>> from sympy.combinatorics.named_groups import DihedralGroup
>>> D = DihedralGroup(4)
>>> D.strong_gens
[(0 1 2 3), (0 3)(1 2), (1 3)]
>>> D.base
[0, 1]
See Also
========
base, basic_transversals, basic_orbits, basic_stabilizers
"""
if self._strong_gens == []:
self.schreier_sims()
return self._strong_gens
def subgroup(self, gens):
"""
Return the subgroup generated by `gens` which is a list of
elements of the group
"""
if not all(g in self for g in gens):
raise ValueError("The group doesn't contain the supplied generators")
G = PermutationGroup(gens)
return G
def subgroup_search(self, prop, base=None, strong_gens=None, tests=None,
init_subgroup=None):
"""Find the subgroup of all elements satisfying the property ``prop``.
Explanation
===========
This is done by a depth-first search with respect to base images that
uses several tests to prune the search tree.
Parameters
==========
prop
The property to be used. Has to be callable on group elements
and always return ``True`` or ``False``. It is assumed that
all group elements satisfying ``prop`` indeed form a subgroup.
base
A base for the supergroup.
strong_gens
A strong generating set for the supergroup.
tests
A list of callables of length equal to the length of ``base``.
These are used to rule out group elements by partial base images,
so that ``tests[l](g)`` returns False if the element ``g`` is known
not to satisfy prop base on where g sends the first ``l + 1`` base
points.
init_subgroup
if a subgroup of the sought group is
known in advance, it can be passed to the function as this
parameter.
Returns
=======
res
The subgroup of all elements satisfying ``prop``. The generating
set for this group is guaranteed to be a strong generating set
relative to the base ``base``.
Examples
========
>>> from sympy.combinatorics.named_groups import (SymmetricGroup,
... AlternatingGroup)
>>> from sympy.combinatorics.testutil import _verify_bsgs
>>> S = SymmetricGroup(7)
>>> prop_even = lambda x: x.is_even
>>> base, strong_gens = S.schreier_sims_incremental()
>>> G = S.subgroup_search(prop_even, base=base, strong_gens=strong_gens)
>>> G.is_subgroup(AlternatingGroup(7))
True
>>> _verify_bsgs(G, base, G.generators)
True
Notes
=====
This function is extremely lengthy and complicated and will require
some careful attention. The implementation is described in
[1], pp. 114-117, and the comments for the code here follow the lines
of the pseudocode in the book for clarity.
The complexity is exponential in general, since the search process by
itself visits all members of the supergroup. However, there are a lot
of tests which are used to prune the search tree, and users can define
their own tests via the ``tests`` parameter, so in practice, and for
some computations, it's not terrible.
A crucial part in the procedure is the frequent base change performed
(this is line 11 in the pseudocode) in order to obtain a new basic
stabilizer. The book mentiones that this can be done by using
``.baseswap(...)``, however the current implementation uses a more
straightforward way to find the next basic stabilizer - calling the
function ``.stabilizer(...)`` on the previous basic stabilizer.
"""
# initialize BSGS and basic group properties
def get_reps(orbits):
# get the minimal element in the base ordering
return [min(orbit, key = lambda x: base_ordering[x]) \
for orbit in orbits]
def update_nu(l):
temp_index = len(basic_orbits[l]) + 1 -\
len(res_basic_orbits_init_base[l])
# this corresponds to the element larger than all points
if temp_index >= len(sorted_orbits[l]):
nu[l] = base_ordering[degree]
else:
nu[l] = sorted_orbits[l][temp_index]
if base is None:
base, strong_gens = self.schreier_sims_incremental()
base_len = len(base)
degree = self.degree
identity = _af_new(list(range(degree)))
base_ordering = _base_ordering(base, degree)
# add an element larger than all points
base_ordering.append(degree)
# add an element smaller than all points
base_ordering.append(-1)
# compute BSGS-related structures
strong_gens_distr = _distribute_gens_by_base(base, strong_gens)
basic_orbits, transversals = _orbits_transversals_from_bsgs(base,
strong_gens_distr)
# handle subgroup initialization and tests
if init_subgroup is None:
init_subgroup = PermutationGroup([identity])
if tests is None:
trivial_test = lambda x: True
tests = []
for i in range(base_len):
tests.append(trivial_test)
# line 1: more initializations.
res = init_subgroup
f = base_len - 1
l = base_len - 1
# line 2: set the base for K to the base for G
res_base = base[:]
# line 3: compute BSGS and related structures for K
res_base, res_strong_gens = res.schreier_sims_incremental(
base=res_base)
res_strong_gens_distr = _distribute_gens_by_base(res_base,
res_strong_gens)
res_generators = res.generators
res_basic_orbits_init_base = \
[_orbit(degree, res_strong_gens_distr[i], res_base[i])\
for i in range(base_len)]
# initialize orbit representatives
orbit_reps = [None]*base_len
# line 4: orbit representatives for f-th basic stabilizer of K
orbits = _orbits(degree, res_strong_gens_distr[f])
orbit_reps[f] = get_reps(orbits)
# line 5: remove the base point from the representatives to avoid
# getting the identity element as a generator for K
orbit_reps[f].remove(base[f])
# line 6: more initializations
c = [0]*base_len
u = [identity]*base_len
sorted_orbits = [None]*base_len
for i in range(base_len):
sorted_orbits[i] = basic_orbits[i][:]
sorted_orbits[i].sort(key=lambda point: base_ordering[point])
# line 7: initializations
mu = [None]*base_len
nu = [None]*base_len
# this corresponds to the element smaller than all points
mu[l] = degree + 1
update_nu(l)
# initialize computed words
computed_words = [identity]*base_len
# line 8: main loop
while True:
# apply all the tests
while l < base_len - 1 and \
computed_words[l](base[l]) in orbit_reps[l] and \
base_ordering[mu[l]] < \
base_ordering[computed_words[l](base[l])] < \
base_ordering[nu[l]] and \
tests[l](computed_words):
# line 11: change the (partial) base of K
new_point = computed_words[l](base[l])
res_base[l] = new_point
new_stab_gens = _stabilizer(degree, res_strong_gens_distr[l],
new_point)
res_strong_gens_distr[l + 1] = new_stab_gens
# line 12: calculate minimal orbit representatives for the
# l+1-th basic stabilizer
orbits = _orbits(degree, new_stab_gens)
orbit_reps[l + 1] = get_reps(orbits)
# line 13: amend sorted orbits
l += 1
temp_orbit = [computed_words[l - 1](point) for point
in basic_orbits[l]]
temp_orbit.sort(key=lambda point: base_ordering[point])
sorted_orbits[l] = temp_orbit
# lines 14 and 15: update variables used minimality tests
new_mu = degree + 1
for i in range(l):
if base[l] in res_basic_orbits_init_base[i]:
candidate = computed_words[i](base[i])
if base_ordering[candidate] > base_ordering[new_mu]:
new_mu = candidate
mu[l] = new_mu
update_nu(l)
# line 16: determine the new transversal element
c[l] = 0
temp_point = sorted_orbits[l][c[l]]
gamma = computed_words[l - 1]._array_form.index(temp_point)
u[l] = transversals[l][gamma]
# update computed words
computed_words[l] = rmul(computed_words[l - 1], u[l])
# lines 17 & 18: apply the tests to the group element found
g = computed_words[l]
temp_point = g(base[l])
if l == base_len - 1 and \
base_ordering[mu[l]] < \
base_ordering[temp_point] < base_ordering[nu[l]] and \
temp_point in orbit_reps[l] and \
tests[l](computed_words) and \
prop(g):
# line 19: reset the base of K
res_generators.append(g)
res_base = base[:]
# line 20: recalculate basic orbits (and transversals)
res_strong_gens.append(g)
res_strong_gens_distr = _distribute_gens_by_base(res_base,
res_strong_gens)
res_basic_orbits_init_base = \
[_orbit(degree, res_strong_gens_distr[i], res_base[i]) \
for i in range(base_len)]
# line 21: recalculate orbit representatives
# line 22: reset the search depth
orbit_reps[f] = get_reps(orbits)
l = f
# line 23: go up the tree until in the first branch not fully
# searched
while l >= 0 and c[l] == len(basic_orbits[l]) - 1:
l = l - 1
# line 24: if the entire tree is traversed, return K
if l == -1:
return PermutationGroup(res_generators)
# lines 25-27: update orbit representatives
if l < f:
# line 26
f = l
c[l] = 0
# line 27
temp_orbits = _orbits(degree, res_strong_gens_distr[f])
orbit_reps[f] = get_reps(temp_orbits)
# line 28: update variables used for minimality testing
mu[l] = degree + 1
temp_index = len(basic_orbits[l]) + 1 - \
len(res_basic_orbits_init_base[l])
if temp_index >= len(sorted_orbits[l]):
nu[l] = base_ordering[degree]
else:
nu[l] = sorted_orbits[l][temp_index]
# line 29: set the next element from the current branch and update
# accordingly
c[l] += 1
if l == 0:
gamma = sorted_orbits[l][c[l]]
else:
gamma = computed_words[l - 1]._array_form.index(sorted_orbits[l][c[l]])
u[l] = transversals[l][gamma]
if l == 0:
computed_words[l] = u[l]
else:
computed_words[l] = rmul(computed_words[l - 1], u[l])
@property
def transitivity_degree(self):
r"""Compute the degree of transitivity of the group.
Explanation
===========
A permutation group `G` acting on `\Omega = \{0, 1, \dots, n-1\}` is
``k``-fold transitive, if, for any `k` points
`(a_1, a_2, \dots, a_k) \in \Omega` and any `k` points
`(b_1, b_2, \dots, b_k) \in \Omega` there exists `g \in G` such that
`g(a_1) = b_1, g(a_2) = b_2, \dots, g(a_k) = b_k`
The degree of transitivity of `G` is the maximum ``k`` such that
`G` is ``k``-fold transitive. ([8])
Examples
========
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> from sympy.combinatorics.permutations import Permutation
>>> a = Permutation([1, 2, 0])
>>> b = Permutation([1, 0, 2])
>>> G = PermutationGroup([a, b])
>>> G.transitivity_degree
3
See Also
========
is_transitive, orbit
"""
if self._transitivity_degree is None:
n = self.degree
G = self
# if G is k-transitive, a tuple (a_0,..,a_k)
# can be brought to (b_0,...,b_(k-1), b_k)
# where b_0,...,b_(k-1) are fixed points;
# consider the group G_k which stabilizes b_0,...,b_(k-1)
# if G_k is transitive on the subset excluding b_0,...,b_(k-1)
# then G is (k+1)-transitive
for i in range(n):
orb = G.orbit(i)
if len(orb) != n - i:
self._transitivity_degree = i
return i
G = G.stabilizer(i)
self._transitivity_degree = n
return n
else:
return self._transitivity_degree
def _p_elements_group(self, p):
'''
For an abelian p-group, return the subgroup consisting of
all elements of order p (and the identity)
'''
gens = self.generators[:]
gens = sorted(gens, key=lambda x: x.order(), reverse=True)
gens_p = [g**(g.order()/p) for g in gens]
gens_r = []
for i in range(len(gens)):
x = gens[i]
x_order = x.order()
# x_p has order p
x_p = x**(x_order/p)
if i > 0:
P = PermutationGroup(gens_p[:i])
else:
P = PermutationGroup(self.identity)
if x**(x_order/p) not in P:
gens_r.append(x**(x_order/p))
else:
# replace x by an element of order (x.order()/p)
# so that gens still generates G
g = P.generator_product(x_p, original=True)
for s in g:
x = x*s**-1
x_order = x_order/p
# insert x to gens so that the sorting is preserved
del gens[i]
del gens_p[i]
j = i - 1
while j < len(gens) and gens[j].order() >= x_order:
j += 1
gens = gens[:j] + [x] + gens[j:]
gens_p = gens_p[:j] + [x] + gens_p[j:]
return PermutationGroup(gens_r)
def _sylow_alt_sym(self, p):
'''
Return a p-Sylow subgroup of a symmetric or an
alternating group.
Explanation
===========
The algorithm for this is hinted at in [1], Chapter 4,
Exercise 4.
For Sym(n) with n = p^i, the idea is as follows. Partition
the interval [0..n-1] into p equal parts, each of length p^(i-1):
[0..p^(i-1)-1], [p^(i-1)..2*p^(i-1)-1]...[(p-1)*p^(i-1)..p^i-1].
Find a p-Sylow subgroup of Sym(p^(i-1)) (treated as a subgroup
of ``self``) acting on each of the parts. Call the subgroups
P_1, P_2...P_p. The generators for the subgroups P_2...P_p
can be obtained from those of P_1 by applying a "shifting"
permutation to them, that is, a permutation mapping [0..p^(i-1)-1]
to the second part (the other parts are obtained by using the shift
multiple times). The union of this permutation and the generators
of P_1 is a p-Sylow subgroup of ``self``.
For n not equal to a power of p, partition
[0..n-1] in accordance with how n would be written in base p.
E.g. for p=2 and n=11, 11 = 2^3 + 2^2 + 1 so the partition
is [[0..7], [8..9], {10}]. To generate a p-Sylow subgroup,
take the union of the generators for each of the parts.
For the above example, {(0 1), (0 2)(1 3), (0 4), (1 5)(2 7)}
from the first part, {(8 9)} from the second part and
nothing from the third. This gives 4 generators in total, and
the subgroup they generate is p-Sylow.
Alternating groups are treated the same except when p=2. In this
case, (0 1)(s s+1) should be added for an appropriate s (the start
of a part) for each part in the partitions.
See Also
========
sylow_subgroup, is_alt_sym
'''
n = self.degree
gens = []
identity = Permutation(n-1)
# the case of 2-sylow subgroups of alternating groups
# needs special treatment
alt = p == 2 and all(g.is_even for g in self.generators)
# find the presentation of n in base p
coeffs = []
m = n
while m > 0:
coeffs.append(m % p)
m = m // p
power = len(coeffs)-1
# for a symmetric group, gens[:i] is the generating
# set for a p-Sylow subgroup on [0..p**(i-1)-1]. For
# alternating groups, the same is given by gens[:2*(i-1)]
for i in range(1, power+1):
if i == 1 and alt:
# (0 1) shouldn't be added for alternating groups
continue
gen = Permutation([(j + p**(i-1)) % p**i for j in range(p**i)])
gens.append(identity*gen)
if alt:
gen = Permutation(0, 1)*gen*Permutation(0, 1)*gen
gens.append(gen)
# the first point in the current part (see the algorithm
# description in the docstring)
start = 0
while power > 0:
a = coeffs[power]
# make the permutation shifting the start of the first
# part ([0..p^i-1] for some i) to the current one
for _ in range(a):
shift = Permutation()
if start > 0:
for i in range(p**power):
shift = shift(i, start + i)
if alt:
gen = Permutation(0, 1)*shift*Permutation(0, 1)*shift
gens.append(gen)
j = 2*(power - 1)
else:
j = power
for i, gen in enumerate(gens[:j]):
if alt and i % 2 == 1:
continue
# shift the generator to the start of the
# partition part
gen = shift*gen*shift
gens.append(gen)
start += p**power
power = power-1
return gens
def sylow_subgroup(self, p):
'''
Return a p-Sylow subgroup of the group.
The algorithm is described in [1], Chapter 4, Section 7
Examples
========
>>> from sympy.combinatorics.named_groups import DihedralGroup
>>> from sympy.combinatorics.named_groups import SymmetricGroup
>>> from sympy.combinatorics.named_groups import AlternatingGroup
>>> D = DihedralGroup(6)
>>> S = D.sylow_subgroup(2)
>>> S.order()
4
>>> G = SymmetricGroup(6)
>>> S = G.sylow_subgroup(5)
>>> S.order()
5
>>> G1 = AlternatingGroup(3)
>>> G2 = AlternatingGroup(5)
>>> G3 = AlternatingGroup(9)
>>> S1 = G1.sylow_subgroup(3)
>>> S2 = G2.sylow_subgroup(3)
>>> S3 = G3.sylow_subgroup(3)
>>> len1 = len(S1.lower_central_series())
>>> len2 = len(S2.lower_central_series())
>>> len3 = len(S3.lower_central_series())
>>> len1 == len2
True
>>> len1 < len3
True
'''
from sympy.combinatorics.homomorphisms import (
orbit_homomorphism, block_homomorphism)
from sympy.ntheory.primetest import isprime
if not isprime(p):
raise ValueError("p must be a prime")
def is_p_group(G):
# check if the order of G is a power of p
# and return the power
m = G.order()
n = 0
while m % p == 0:
m = m/p
n += 1
if m == 1:
return True, n
return False, n
def _sylow_reduce(mu, nu):
# reduction based on two homomorphisms
# mu and nu with trivially intersecting
# kernels
Q = mu.image().sylow_subgroup(p)
Q = mu.invert_subgroup(Q)
nu = nu.restrict_to(Q)
R = nu.image().sylow_subgroup(p)
return nu.invert_subgroup(R)
order = self.order()
if order % p != 0:
return PermutationGroup([self.identity])
p_group, n = is_p_group(self)
if p_group:
return self
if self.is_alt_sym():
return PermutationGroup(self._sylow_alt_sym(p))
# if there is a non-trivial orbit with size not divisible
# by p, the sylow subgroup is contained in its stabilizer
# (by orbit-stabilizer theorem)
orbits = self.orbits()
non_p_orbits = [o for o in orbits if len(o) % p != 0 and len(o) != 1]
if non_p_orbits:
G = self.stabilizer(list(non_p_orbits[0]).pop())
return G.sylow_subgroup(p)
if not self.is_transitive():
# apply _sylow_reduce to orbit actions
orbits = sorted(orbits, key=len)
omega1 = orbits.pop()
omega2 = orbits[0].union(*orbits)
mu = orbit_homomorphism(self, omega1)
nu = orbit_homomorphism(self, omega2)
return _sylow_reduce(mu, nu)
blocks = self.minimal_blocks()
if len(blocks) > 1:
# apply _sylow_reduce to block system actions
mu = block_homomorphism(self, blocks[0])
nu = block_homomorphism(self, blocks[1])
return _sylow_reduce(mu, nu)
elif len(blocks) == 1:
block = list(blocks)[0]
if any(e != 0 for e in block):
# self is imprimitive
mu = block_homomorphism(self, block)
if not is_p_group(mu.image())[0]:
S = mu.image().sylow_subgroup(p)
return mu.invert_subgroup(S).sylow_subgroup(p)
# find an element of order p
g = self.random()
g_order = g.order()
while g_order % p != 0 or g_order == 0:
g = self.random()
g_order = g.order()
g = g**(g_order // p)
if order % p**2 != 0:
return PermutationGroup(g)
C = self.centralizer(g)
while C.order() % p**n != 0:
S = C.sylow_subgroup(p)
s_order = S.order()
Z = S.center()
P = Z._p_elements_group(p)
h = P.random()
C_h = self.centralizer(h)
while C_h.order() % p*s_order != 0:
h = P.random()
C_h = self.centralizer(h)
C = C_h
return C.sylow_subgroup(p)
def _block_verify(self, L, alpha):
delta = sorted(list(self.orbit(alpha)))
# p[i] will be the number of the block
# delta[i] belongs to
p = [-1]*len(delta)
blocks = [-1]*len(delta)
B = [[]] # future list of blocks
u = [0]*len(delta) # u[i] in L s.t. alpha^u[i] = B[0][i]
t = L.orbit_transversal(alpha, pairs=True)
for a, beta in t:
B[0].append(a)
i_a = delta.index(a)
p[i_a] = 0
blocks[i_a] = alpha
u[i_a] = beta
rho = 0
m = 0 # number of blocks - 1
while rho <= m:
beta = B[rho][0]
for g in self.generators:
d = beta^g
i_d = delta.index(d)
sigma = p[i_d]
if sigma < 0:
# define a new block
m += 1
sigma = m
u[i_d] = u[delta.index(beta)]*g
p[i_d] = sigma
rep = d
blocks[i_d] = rep
newb = [rep]
for gamma in B[rho][1:]:
i_gamma = delta.index(gamma)
d = gamma^g
i_d = delta.index(d)
if p[i_d] < 0:
u[i_d] = u[i_gamma]*g
p[i_d] = sigma
blocks[i_d] = rep
newb.append(d)
else:
# B[rho] is not a block
s = u[i_gamma]*g*u[i_d]**(-1)
return False, s
B.append(newb)
else:
for h in B[rho][1:]:
if h^g not in B[sigma]:
# B[rho] is not a block
s = u[delta.index(beta)]*g*u[i_d]**(-1)
return False, s
rho += 1
return True, blocks
def _verify(H, K, phi, z, alpha):
'''
Return a list of relators ``rels`` in generators ``gens`_h` that
are mapped to ``H.generators`` by ``phi`` so that given a finite
presentation <gens_k | rels_k> of ``K`` on a subset of ``gens_h``
<gens_h | rels_k + rels> is a finite presentation of ``H``.
Explanation
===========
``H`` should be generated by the union of ``K.generators`` and ``z``
(a single generator), and ``H.stabilizer(alpha) == K``; ``phi`` is a
canonical injection from a free group into a permutation group
containing ``H``.
The algorithm is described in [1], Chapter 6.
Examples
========
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.homomorphisms import homomorphism
>>> from sympy.combinatorics.free_groups import free_group
>>> from sympy.combinatorics.fp_groups import FpGroup
>>> H = PermutationGroup(Permutation(0, 2), Permutation (1, 5))
>>> K = PermutationGroup(Permutation(5)(0, 2))
>>> F = free_group("x_0 x_1")[0]
>>> gens = F.generators
>>> phi = homomorphism(F, H, F.generators, H.generators)
>>> rels_k = [gens[0]**2] # relators for presentation of K
>>> z= Permutation(1, 5)
>>> check, rels_h = H._verify(K, phi, z, 1)
>>> check
True
>>> rels = rels_k + rels_h
>>> G = FpGroup(F, rels) # presentation of H
>>> G.order() == H.order()
True
See also
========
strong_presentation, presentation, stabilizer
'''
orbit = H.orbit(alpha)
beta = alpha^(z**-1)
K_beta = K.stabilizer(beta)
# orbit representatives of K_beta
gammas = [alpha, beta]
orbits = list({tuple(K_beta.orbit(o)) for o in orbit})
orbit_reps = [orb[0] for orb in orbits]
for rep in orbit_reps:
if rep not in gammas:
gammas.append(rep)
# orbit transversal of K
betas = [alpha, beta]
transversal = {alpha: phi.invert(H.identity), beta: phi.invert(z**-1)}
for s, g in K.orbit_transversal(beta, pairs=True):
if s not in transversal:
transversal[s] = transversal[beta]*phi.invert(g)
union = K.orbit(alpha).union(K.orbit(beta))
while (len(union) < len(orbit)):
for gamma in gammas:
if gamma in union:
r = gamma^z
if r not in union:
betas.append(r)
transversal[r] = transversal[gamma]*phi.invert(z)
for s, g in K.orbit_transversal(r, pairs=True):
if s not in transversal:
transversal[s] = transversal[r]*phi.invert(g)
union = union.union(K.orbit(r))
break
# compute relators
rels = []
for b in betas:
k_gens = K.stabilizer(b).generators
for y in k_gens:
new_rel = transversal[b]
gens = K.generator_product(y, original=True)
for g in gens[::-1]:
new_rel = new_rel*phi.invert(g)
new_rel = new_rel*transversal[b]**-1
perm = phi(new_rel)
try:
gens = K.generator_product(perm, original=True)
except ValueError:
return False, perm
for g in gens:
new_rel = new_rel*phi.invert(g)**-1
if new_rel not in rels:
rels.append(new_rel)
for gamma in gammas:
new_rel = transversal[gamma]*phi.invert(z)*transversal[gamma^z]**-1
perm = phi(new_rel)
try:
gens = K.generator_product(perm, original=True)
except ValueError:
return False, perm
for g in gens:
new_rel = new_rel*phi.invert(g)**-1
if new_rel not in rels:
rels.append(new_rel)
return True, rels
def strong_presentation(self):
'''
Return a strong finite presentation of group. The generators
of the returned group are in the same order as the strong
generators of group.
The algorithm is based on Sims' Verify algorithm described
in [1], Chapter 6.
Examples
========
>>> from sympy.combinatorics.named_groups import DihedralGroup
>>> P = DihedralGroup(4)
>>> G = P.strong_presentation()
>>> P.order() == G.order()
True
See Also
========
presentation, _verify
'''
from sympy.combinatorics.fp_groups import (FpGroup,
simplify_presentation)
from sympy.combinatorics.free_groups import free_group
from sympy.combinatorics.homomorphisms import (block_homomorphism,
homomorphism, GroupHomomorphism)
strong_gens = self.strong_gens[:]
stabs = self.basic_stabilizers[:]
base = self.base[:]
# injection from a free group on len(strong_gens)
# generators into G
gen_syms = [('x_%d'%i) for i in range(len(strong_gens))]
F = free_group(', '.join(gen_syms))[0]
phi = homomorphism(F, self, F.generators, strong_gens)
H = PermutationGroup(self.identity)
while stabs:
alpha = base.pop()
K = H
H = stabs.pop()
new_gens = [g for g in H.generators if g not in K]
if K.order() == 1:
z = new_gens.pop()
rels = [F.generators[-1]**z.order()]
intermediate_gens = [z]
K = PermutationGroup(intermediate_gens)
# add generators one at a time building up from K to H
while new_gens:
z = new_gens.pop()
intermediate_gens = [z] + intermediate_gens
K_s = PermutationGroup(intermediate_gens)
orbit = K_s.orbit(alpha)
orbit_k = K.orbit(alpha)
# split into cases based on the orbit of K_s
if orbit_k == orbit:
if z in K:
rel = phi.invert(z)
perm = z
else:
t = K.orbit_rep(alpha, alpha^z)
rel = phi.invert(z)*phi.invert(t)**-1
perm = z*t**-1
for g in K.generator_product(perm, original=True):
rel = rel*phi.invert(g)**-1
new_rels = [rel]
elif len(orbit_k) == 1:
# `success` is always true because `strong_gens`
# and `base` are already a verified BSGS. Later
# this could be changed to start with a randomly
# generated (potential) BSGS, and then new elements
# would have to be appended to it when `success`
# is false.
success, new_rels = K_s._verify(K, phi, z, alpha)
else:
# K.orbit(alpha) should be a block
# under the action of K_s on K_s.orbit(alpha)
check, block = K_s._block_verify(K, alpha)
if check:
# apply _verify to the action of K_s
# on the block system; for convenience,
# add the blocks as additional points
# that K_s should act on
t = block_homomorphism(K_s, block)
m = t.codomain.degree # number of blocks
d = K_s.degree
# conjugating with p will shift
# permutations in t.image() to
# higher numbers, e.g.
# p*(0 1)*p = (m m+1)
p = Permutation()
for i in range(m):
p *= Permutation(i, i+d)
t_img = t.images
# combine generators of K_s with their
# action on the block system
images = {g: g*p*t_img[g]*p for g in t_img}
for g in self.strong_gens[:-len(K_s.generators)]:
images[g] = g
K_s_act = PermutationGroup(list(images.values()))
f = GroupHomomorphism(self, K_s_act, images)
K_act = PermutationGroup([f(g) for g in K.generators])
success, new_rels = K_s_act._verify(K_act, f.compose(phi), f(z), d)
for n in new_rels:
if n not in rels:
rels.append(n)
K = K_s
group = FpGroup(F, rels)
return simplify_presentation(group)
def presentation(self, eliminate_gens=True):
'''
Return an `FpGroup` presentation of the group.
The algorithm is described in [1], Chapter 6.1.
'''
from sympy.combinatorics.fp_groups import (FpGroup,
simplify_presentation)
from sympy.combinatorics.coset_table import CosetTable
from sympy.combinatorics.free_groups import free_group
from sympy.combinatorics.homomorphisms import homomorphism
from itertools import product
if self._fp_presentation:
return self._fp_presentation
def _factor_group_by_rels(G, rels):
if isinstance(G, FpGroup):
rels.extend(G.relators)
return FpGroup(G.free_group, list(set(rels)))
return FpGroup(G, rels)
gens = self.generators
len_g = len(gens)
if len_g == 1:
order = gens[0].order()
# handle the trivial group
if order == 1:
return free_group([])[0]
F, x = free_group('x')
return FpGroup(F, [x**order])
if self.order() > 20:
half_gens = self.generators[0:(len_g+1)//2]
else:
half_gens = []
H = PermutationGroup(half_gens)
H_p = H.presentation()
len_h = len(H_p.generators)
C = self.coset_table(H)
n = len(C) # subgroup index
gen_syms = [('x_%d'%i) for i in range(len(gens))]
F = free_group(', '.join(gen_syms))[0]
# mapping generators of H_p to those of F
images = [F.generators[i] for i in range(len_h)]
R = homomorphism(H_p, F, H_p.generators, images, check=False)
# rewrite relators
rels = R(H_p.relators)
G_p = FpGroup(F, rels)
# injective homomorphism from G_p into self
T = homomorphism(G_p, self, G_p.generators, gens)
C_p = CosetTable(G_p, [])
C_p.table = [[None]*(2*len_g) for i in range(n)]
# initiate the coset transversal
transversal = [None]*n
transversal[0] = G_p.identity
# fill in the coset table as much as possible
for i in range(2*len_h):
C_p.table[0][i] = 0
gamma = 1
for alpha, x in product(range(0, n), range(2*len_g)):
beta = C[alpha][x]
if beta == gamma:
gen = G_p.generators[x//2]**((-1)**(x % 2))
transversal[beta] = transversal[alpha]*gen
C_p.table[alpha][x] = beta
C_p.table[beta][x + (-1)**(x % 2)] = alpha
gamma += 1
if gamma == n:
break
C_p.p = list(range(n))
beta = x = 0
while not C_p.is_complete():
# find the first undefined entry
while C_p.table[beta][x] == C[beta][x]:
x = (x + 1) % (2*len_g)
if x == 0:
beta = (beta + 1) % n
# define a new relator
gen = G_p.generators[x//2]**((-1)**(x % 2))
new_rel = transversal[beta]*gen*transversal[C[beta][x]]**-1
perm = T(new_rel)
nxt = G_p.identity
for s in H.generator_product(perm, original=True):
nxt = nxt*T.invert(s)**-1
new_rel = new_rel*nxt
# continue coset enumeration
G_p = _factor_group_by_rels(G_p, [new_rel])
C_p.scan_and_fill(0, new_rel)
C_p = G_p.coset_enumeration([], strategy="coset_table",
draft=C_p, max_cosets=n, incomplete=True)
self._fp_presentation = simplify_presentation(G_p)
return self._fp_presentation
def polycyclic_group(self):
"""
Return the PolycyclicGroup instance with below parameters:
Explanation
===========
* ``pc_sequence`` : Polycyclic sequence is formed by collecting all
the missing generators between the adjacent groups in the
derived series of given permutation group.
* ``pc_series`` : Polycyclic series is formed by adding all the missing
generators of ``der[i+1]`` in ``der[i]``, where ``der`` represents
the derived series.
* ``relative_order`` : A list, computed by the ratio of adjacent groups in
pc_series.
"""
from sympy.combinatorics.pc_groups import PolycyclicGroup
if not self.is_polycyclic:
raise ValueError("The group must be solvable")
der = self.derived_series()
pc_series = []
pc_sequence = []
relative_order = []
pc_series.append(der[-1])
der.reverse()
for i in range(len(der)-1):
H = der[i]
for g in der[i+1].generators:
if g not in H:
H = PermutationGroup([g] + H.generators)
pc_series.insert(0, H)
pc_sequence.insert(0, g)
G1 = pc_series[0].order()
G2 = pc_series[1].order()
relative_order.insert(0, G1 // G2)
return PolycyclicGroup(pc_sequence, pc_series, relative_order, collector=None)
def _orbit(degree, generators, alpha, action='tuples'):
r"""Compute the orbit of alpha `\{g(\alpha) | g \in G\}` as a set.
Explanation
===========
The time complexity of the algorithm used here is `O(|Orb|*r)` where
`|Orb|` is the size of the orbit and ``r`` is the number of generators of
the group. For a more detailed analysis, see [1], p.78, [2], pp. 19-21.
Here alpha can be a single point, or a list of points.
If alpha is a single point, the ordinary orbit is computed.
if alpha is a list of points, there are three available options:
'union' - computes the union of the orbits of the points in the list
'tuples' - computes the orbit of the list interpreted as an ordered
tuple under the group action ( i.e., g((1, 2, 3)) = (g(1), g(2), g(3)) )
'sets' - computes the orbit of the list interpreted as a sets
Examples
========
>>> from sympy.combinatorics import Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup, _orbit
>>> a = Permutation([1, 2, 0, 4, 5, 6, 3])
>>> G = PermutationGroup([a])
>>> _orbit(G.degree, G.generators, 0)
{0, 1, 2}
>>> _orbit(G.degree, G.generators, [0, 4], 'union')
{0, 1, 2, 3, 4, 5, 6}
See Also
========
orbit, orbit_transversal
"""
if not hasattr(alpha, '__getitem__'):
alpha = [alpha]
gens = [x._array_form for x in generators]
if len(alpha) == 1 or action == 'union':
orb = alpha
used = [False]*degree
for el in alpha:
used[el] = True
for b in orb:
for gen in gens:
temp = gen[b]
if used[temp] == False:
orb.append(temp)
used[temp] = True
return set(orb)
elif action == 'tuples':
alpha = tuple(alpha)
orb = [alpha]
used = {alpha}
for b in orb:
for gen in gens:
temp = tuple([gen[x] for x in b])
if temp not in used:
orb.append(temp)
used.add(temp)
return set(orb)
elif action == 'sets':
alpha = frozenset(alpha)
orb = [alpha]
used = {alpha}
for b in orb:
for gen in gens:
temp = frozenset([gen[x] for x in b])
if temp not in used:
orb.append(temp)
used.add(temp)
return {tuple(x) for x in orb}
def _orbits(degree, generators):
"""Compute the orbits of G.
If ``rep=False`` it returns a list of sets else it returns a list of
representatives of the orbits
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy.combinatorics.perm_groups import _orbits
>>> a = Permutation([0, 2, 1])
>>> b = Permutation([1, 0, 2])
>>> _orbits(a.size, [a, b])
[{0, 1, 2}]
"""
orbs = []
sorted_I = list(range(degree))
I = set(sorted_I)
while I:
i = sorted_I[0]
orb = _orbit(degree, generators, i)
orbs.append(orb)
# remove all indices that are in this orbit
I -= orb
sorted_I = [i for i in sorted_I if i not in orb]
return orbs
def _orbit_transversal(degree, generators, alpha, pairs, af=False, slp=False):
r"""Computes a transversal for the orbit of ``alpha`` as a set.
Explanation
===========
generators generators of the group ``G``
For a permutation group ``G``, a transversal for the orbit
`Orb = \{g(\alpha) | g \in G\}` is a set
`\{g_\beta | g_\beta(\alpha) = \beta\}` for `\beta \in Orb`.
Note that there may be more than one possible transversal.
If ``pairs`` is set to ``True``, it returns the list of pairs
`(\beta, g_\beta)`. For a proof of correctness, see [1], p.79
if ``af`` is ``True``, the transversal elements are given in
array form.
If `slp` is `True`, a dictionary `{beta: slp_beta}` is returned
for `\beta \in Orb` where `slp_beta` is a list of indices of the
generators in `generators` s.t. if `slp_beta = [i_1 \dots i_n]`
`g_\beta = generators[i_n] \times \dots \times generators[i_1]`.
Examples
========
>>> from sympy.combinatorics.named_groups import DihedralGroup
>>> from sympy.combinatorics.perm_groups import _orbit_transversal
>>> G = DihedralGroup(6)
>>> _orbit_transversal(G.degree, G.generators, 0, False)
[(5), (0 1 2 3 4 5), (0 5)(1 4)(2 3), (0 2 4)(1 3 5), (5)(0 4)(1 3), (0 3)(1 4)(2 5)]
"""
tr = [(alpha, list(range(degree)))]
slp_dict = {alpha: []}
used = [False]*degree
used[alpha] = True
gens = [x._array_form for x in generators]
for x, px in tr:
px_slp = slp_dict[x]
for gen in gens:
temp = gen[x]
if used[temp] == False:
slp_dict[temp] = [gens.index(gen)] + px_slp
tr.append((temp, _af_rmul(gen, px)))
used[temp] = True
if pairs:
if not af:
tr = [(x, _af_new(y)) for x, y in tr]
if not slp:
return tr
return tr, slp_dict
if af:
tr = [y for _, y in tr]
if not slp:
return tr
return tr, slp_dict
tr = [_af_new(y) for _, y in tr]
if not slp:
return tr
return tr, slp_dict
def _stabilizer(degree, generators, alpha):
r"""Return the stabilizer subgroup of ``alpha``.
Explanation
===========
The stabilizer of `\alpha` is the group `G_\alpha =
\{g \in G | g(\alpha) = \alpha\}`.
For a proof of correctness, see [1], p.79.
degree : degree of G
generators : generators of G
Examples
========
>>> from sympy.combinatorics.perm_groups import _stabilizer
>>> from sympy.combinatorics.named_groups import DihedralGroup
>>> G = DihedralGroup(6)
>>> _stabilizer(G.degree, G.generators, 5)
[(5)(0 4)(1 3), (5)]
See Also
========
orbit
"""
orb = [alpha]
table = {alpha: list(range(degree))}
table_inv = {alpha: list(range(degree))}
used = [False]*degree
used[alpha] = True
gens = [x._array_form for x in generators]
stab_gens = []
for b in orb:
for gen in gens:
temp = gen[b]
if used[temp] is False:
gen_temp = _af_rmul(gen, table[b])
orb.append(temp)
table[temp] = gen_temp
table_inv[temp] = _af_invert(gen_temp)
used[temp] = True
else:
schreier_gen = _af_rmuln(table_inv[temp], gen, table[b])
if schreier_gen not in stab_gens:
stab_gens.append(schreier_gen)
return [_af_new(x) for x in stab_gens]
PermGroup = PermutationGroup
class SymmetricPermutationGroup(Basic):
"""
The class defining the lazy form of SymmetricGroup.
deg : int
"""
def __new__(cls, deg):
deg = _sympify(deg)
obj = Basic.__new__(cls, deg)
return obj
def __init__(self, *args, **kwargs):
self._deg = self.args[0]
self._order = None
def __contains__(self, i):
"""Return ``True`` if *i* is contained in SymmetricPermutationGroup.
Examples
========
>>> from sympy.combinatorics import Permutation, SymmetricPermutationGroup
>>> G = SymmetricPermutationGroup(4)
>>> Permutation(1, 2, 3) in G
True
"""
if not isinstance(i, Permutation):
raise TypeError("A SymmetricPermutationGroup contains only Permutations as "
"elements, not elements of type %s" % type(i))
return i.size == self.degree
def order(self):
"""
Return the order of the SymmetricPermutationGroup.
Examples
========
>>> from sympy.combinatorics import SymmetricPermutationGroup
>>> G = SymmetricPermutationGroup(4)
>>> G.order()
24
"""
if self._order is not None:
return self._order
n = self._deg
self._order = factorial(n)
return self._order
@property
def degree(self):
"""
Return the degree of the SymmetricPermutationGroup.
Examples
========
>>> from sympy.combinatorics import SymmetricPermutationGroup
>>> G = SymmetricPermutationGroup(4)
>>> G.degree
4
"""
return self._deg
@property
def identity(self):
'''
Return the identity element of the SymmetricPermutationGroup.
Examples
========
>>> from sympy.combinatorics import SymmetricPermutationGroup
>>> G = SymmetricPermutationGroup(4)
>>> G.identity()
(3)
'''
return _af_new(list(range(self._deg)))
class Coset(Basic):
"""A left coset of a permutation group with respect to an element.
Parameters
==========
g : Permutation
H : PermutationGroup
dir : "+" or "-", If not specified by default it will be "+"
here ``dir`` specified the type of coset "+" represent the
right coset and "-" represent the left coset.
G : PermutationGroup, optional
The group which contains *H* as its subgroup and *g* as its
element.
If not specified, it would automatically become a symmetric
group ``SymmetricPermutationGroup(g.size)`` and
``SymmetricPermutationGroup(H.degree)`` if ``g.size`` and ``H.degree``
are matching.``SymmetricPermutationGroup`` is a lazy form of SymmetricGroup
used for representation purpose.
"""
def __new__(cls, g, H, G=None, dir="+"):
g = _sympify(g)
if not isinstance(g, Permutation):
raise NotImplementedError
H = _sympify(H)
if not isinstance(H, PermutationGroup):
raise NotImplementedError
if G is not None:
G = _sympify(G)
if not isinstance(G, (PermutationGroup, SymmetricPermutationGroup)):
raise NotImplementedError
if not H.is_subgroup(G):
raise ValueError("{} must be a subgroup of {}.".format(H, G))
if g not in G:
raise ValueError("{} must be an element of {}.".format(g, G))
else:
g_size = g.size
h_degree = H.degree
if g_size != h_degree:
raise ValueError(
"The size of the permutation {} and the degree of "
"the permutation group {} should be matching "
.format(g, H))
G = SymmetricPermutationGroup(g.size)
if isinstance(dir, str):
dir = Symbol(dir)
elif not isinstance(dir, Symbol):
raise TypeError("dir must be of type basestring or "
"Symbol, not %s" % type(dir))
if str(dir) not in ('+', '-'):
raise ValueError("dir must be one of '+' or '-' not %s" % dir)
obj = Basic.__new__(cls, g, H, G, dir)
return obj
def __init__(self, *args, **kwargs):
self._dir = self.args[3]
@property
def is_left_coset(self):
"""
Check if the coset is left coset that is ``gH``.
Examples
========
>>> from sympy.combinatorics import Permutation, PermutationGroup, Coset
>>> a = Permutation(1, 2)
>>> b = Permutation(0, 1)
>>> G = PermutationGroup([a, b])
>>> cst = Coset(a, G, dir="-")
>>> cst.is_left_coset
True
"""
return str(self._dir) == '-'
@property
def is_right_coset(self):
"""
Check if the coset is right coset that is ``Hg``.
Examples
========
>>> from sympy.combinatorics import Permutation, PermutationGroup, Coset
>>> a = Permutation(1, 2)
>>> b = Permutation(0, 1)
>>> G = PermutationGroup([a, b])
>>> cst = Coset(a, G, dir="+")
>>> cst.is_right_coset
True
"""
return str(self._dir) == '+'
def as_list(self):
"""
Return all the elements of coset in the form of list.
"""
g = self.args[0]
H = self.args[1]
cst = []
if str(self._dir) == '+':
for h in H.elements:
cst.append(h*g)
else:
for h in H.elements:
cst.append(g*h)
return cst
|
9c39d28a1f1bdab2e4819f1f9f1c98a0ba951f95a10586ffeaa9936f47ced21a | import random
from collections import defaultdict
from collections.abc import Iterable
from functools import reduce
from sympy.core.parameters import global_parameters
from sympy.core.basic import Atom
from sympy.core.expr import Expr
from sympy.core.numbers import Integer
from sympy.core.sympify import _sympify
from sympy.matrices import zeros
from sympy.polys.polytools import lcm
from sympy.utilities.iterables import (flatten, has_variety, minlex,
has_dups, runs, is_sequence)
from sympy.utilities.misc import as_int
from mpmath.libmp.libintmath import ifac
from sympy.multipledispatch import dispatch
def _af_rmul(a, b):
"""
Return the product b*a; input and output are array forms. The ith value
is a[b[i]].
Examples
========
>>> from sympy.combinatorics.permutations import _af_rmul, Permutation
>>> a, b = [1, 0, 2], [0, 2, 1]
>>> _af_rmul(a, b)
[1, 2, 0]
>>> [a[b[i]] for i in range(3)]
[1, 2, 0]
This handles the operands in reverse order compared to the ``*`` operator:
>>> a = Permutation(a)
>>> b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]
See Also
========
rmul, _af_rmuln
"""
return [a[i] for i in b]
def _af_rmuln(*abc):
"""
Given [a, b, c, ...] return the product of ...*c*b*a using array forms.
The ith value is a[b[c[i]]].
Examples
========
>>> from sympy.combinatorics.permutations import _af_rmul, Permutation
>>> a, b = [1, 0, 2], [0, 2, 1]
>>> _af_rmul(a, b)
[1, 2, 0]
>>> [a[b[i]] for i in range(3)]
[1, 2, 0]
This handles the operands in reverse order compared to the ``*`` operator:
>>> a = Permutation(a); b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]
See Also
========
rmul, _af_rmul
"""
a = abc
m = len(a)
if m == 3:
p0, p1, p2 = a
return [p0[p1[i]] for i in p2]
if m == 4:
p0, p1, p2, p3 = a
return [p0[p1[p2[i]]] for i in p3]
if m == 5:
p0, p1, p2, p3, p4 = a
return [p0[p1[p2[p3[i]]]] for i in p4]
if m == 6:
p0, p1, p2, p3, p4, p5 = a
return [p0[p1[p2[p3[p4[i]]]]] for i in p5]
if m == 7:
p0, p1, p2, p3, p4, p5, p6 = a
return [p0[p1[p2[p3[p4[p5[i]]]]]] for i in p6]
if m == 8:
p0, p1, p2, p3, p4, p5, p6, p7 = a
return [p0[p1[p2[p3[p4[p5[p6[i]]]]]]] for i in p7]
if m == 1:
return a[0][:]
if m == 2:
a, b = a
return [a[i] for i in b]
if m == 0:
raise ValueError("String must not be empty")
p0 = _af_rmuln(*a[:m//2])
p1 = _af_rmuln(*a[m//2:])
return [p0[i] for i in p1]
def _af_parity(pi):
"""
Computes the parity of a permutation in array form.
Explanation
===========
The parity of a permutation reflects the parity of the
number of inversions in the permutation, i.e., the
number of pairs of x and y such that x > y but p[x] < p[y].
Examples
========
>>> from sympy.combinatorics.permutations import _af_parity
>>> _af_parity([0, 1, 2, 3])
0
>>> _af_parity([3, 2, 0, 1])
1
See Also
========
Permutation
"""
n = len(pi)
a = [0] * n
c = 0
for j in range(n):
if a[j] == 0:
c += 1
a[j] = 1
i = j
while pi[i] != j:
i = pi[i]
a[i] = 1
return (n - c) % 2
def _af_invert(a):
"""
Finds the inverse, ~A, of a permutation, A, given in array form.
Examples
========
>>> from sympy.combinatorics.permutations import _af_invert, _af_rmul
>>> A = [1, 2, 0, 3]
>>> _af_invert(A)
[2, 0, 1, 3]
>>> _af_rmul(_, A)
[0, 1, 2, 3]
See Also
========
Permutation, __invert__
"""
inv_form = [0] * len(a)
for i, ai in enumerate(a):
inv_form[ai] = i
return inv_form
def _af_pow(a, n):
"""
Routine for finding powers of a permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation, _af_pow
>>> p = Permutation([2, 0, 3, 1])
>>> p.order()
4
>>> _af_pow(p._array_form, 4)
[0, 1, 2, 3]
"""
if n == 0:
return list(range(len(a)))
if n < 0:
return _af_pow(_af_invert(a), -n)
if n == 1:
return a[:]
elif n == 2:
b = [a[i] for i in a]
elif n == 3:
b = [a[a[i]] for i in a]
elif n == 4:
b = [a[a[a[i]]] for i in a]
else:
# use binary multiplication
b = list(range(len(a)))
while 1:
if n & 1:
b = [b[i] for i in a]
n -= 1
if not n:
break
if n % 4 == 0:
a = [a[a[a[i]]] for i in a]
n = n // 4
elif n % 2 == 0:
a = [a[i] for i in a]
n = n // 2
return b
def _af_commutes_with(a, b):
"""
Checks if the two permutations with array forms
given by ``a`` and ``b`` commute.
Examples
========
>>> from sympy.combinatorics.permutations import _af_commutes_with
>>> _af_commutes_with([1, 2, 0], [0, 2, 1])
False
See Also
========
Permutation, commutes_with
"""
return not any(a[b[i]] != b[a[i]] for i in range(len(a) - 1))
class Cycle(dict):
"""
Wrapper around dict which provides the functionality of a disjoint cycle.
Explanation
===========
A cycle shows the rule to use to move subsets of elements to obtain
a permutation. The Cycle class is more flexible than Permutation in
that 1) all elements need not be present in order to investigate how
multiple cycles act in sequence and 2) it can contain singletons:
>>> from sympy.combinatorics.permutations import Perm, Cycle
A Cycle will automatically parse a cycle given as a tuple on the rhs:
>>> Cycle(1, 2)(2, 3)
(1 3 2)
The identity cycle, Cycle(), can be used to start a product:
>>> Cycle()(1, 2)(2, 3)
(1 3 2)
The array form of a Cycle can be obtained by calling the list
method (or passing it to the list function) and all elements from
0 will be shown:
>>> a = Cycle(1, 2)
>>> a.list()
[0, 2, 1]
>>> list(a)
[0, 2, 1]
If a larger (or smaller) range is desired use the list method and
provide the desired size -- but the Cycle cannot be truncated to
a size smaller than the largest element that is out of place:
>>> b = Cycle(2, 4)(1, 2)(3, 1, 4)(1, 3)
>>> b.list()
[0, 2, 1, 3, 4]
>>> b.list(b.size + 1)
[0, 2, 1, 3, 4, 5]
>>> b.list(-1)
[0, 2, 1]
Singletons are not shown when printing with one exception: the largest
element is always shown -- as a singleton if necessary:
>>> Cycle(1, 4, 10)(4, 5)
(1 5 4 10)
>>> Cycle(1, 2)(4)(5)(10)
(1 2)(10)
The array form can be used to instantiate a Permutation so other
properties of the permutation can be investigated:
>>> Perm(Cycle(1, 2)(3, 4).list()).transpositions()
[(1, 2), (3, 4)]
Notes
=====
The underlying structure of the Cycle is a dictionary and although
the __iter__ method has been redefined to give the array form of the
cycle, the underlying dictionary items are still available with the
such methods as items():
>>> list(Cycle(1, 2).items())
[(1, 2), (2, 1)]
See Also
========
Permutation
"""
def __missing__(self, arg):
"""Enter arg into dictionary and return arg."""
return as_int(arg)
def __iter__(self):
yield from self.list()
def __call__(self, *other):
"""Return product of cycles processed from R to L.
Examples
========
>>> from sympy.combinatorics.permutations import Cycle as C
>>> C(1, 2)(2, 3)
(1 3 2)
An instance of a Cycle will automatically parse list-like
objects and Permutations that are on the right. It is more
flexible than the Permutation in that all elements need not
be present:
>>> a = C(1, 2)
>>> a(2, 3)
(1 3 2)
>>> a(2, 3)(4, 5)
(1 3 2)(4 5)
"""
rv = Cycle(*other)
for k, v in zip(list(self.keys()), [rv[self[k]] for k in self.keys()]):
rv[k] = v
return rv
def list(self, size=None):
"""Return the cycles as an explicit list starting from 0 up
to the greater of the largest value in the cycles and size.
Truncation of trailing unmoved items will occur when size
is less than the maximum element in the cycle; if this is
desired, setting ``size=-1`` will guarantee such trimming.
Examples
========
>>> from sympy.combinatorics.permutations import Cycle
>>> p = Cycle(2, 3)(4, 5)
>>> p.list()
[0, 1, 3, 2, 5, 4]
>>> p.list(10)
[0, 1, 3, 2, 5, 4, 6, 7, 8, 9]
Passing a length too small will trim trailing, unchanged elements
in the permutation:
>>> Cycle(2, 4)(1, 2, 4).list(-1)
[0, 2, 1]
"""
if not self and size is None:
raise ValueError('must give size for empty Cycle')
if size is not None:
big = max([i for i in self.keys() if self[i] != i] + [0])
size = max(size, big + 1)
else:
size = self.size
return [self[i] for i in range(size)]
def __repr__(self):
"""We want it to print as a Cycle, not as a dict.
Examples
========
>>> from sympy.combinatorics import Cycle
>>> Cycle(1, 2)
(1 2)
>>> print(_)
(1 2)
>>> list(Cycle(1, 2).items())
[(1, 2), (2, 1)]
"""
if not self:
return 'Cycle()'
cycles = Permutation(self).cyclic_form
s = ''.join(str(tuple(c)) for c in cycles)
big = self.size - 1
if not any(i == big for c in cycles for i in c):
s += '(%s)' % big
return 'Cycle%s' % s
def __str__(self):
"""We want it to be printed in a Cycle notation with no
comma in-between.
Examples
========
>>> from sympy.combinatorics import Cycle
>>> Cycle(1, 2)
(1 2)
>>> Cycle(1, 2, 4)(5, 6)
(1 2 4)(5 6)
"""
if not self:
return '()'
cycles = Permutation(self).cyclic_form
s = ''.join(str(tuple(c)) for c in cycles)
big = self.size - 1
if not any(i == big for c in cycles for i in c):
s += '(%s)' % big
s = s.replace(',', '')
return s
def __init__(self, *args):
"""Load up a Cycle instance with the values for the cycle.
Examples
========
>>> from sympy.combinatorics.permutations import Cycle
>>> Cycle(1, 2, 6)
(1 2 6)
"""
if not args:
return
if len(args) == 1:
if isinstance(args[0], Permutation):
for c in args[0].cyclic_form:
self.update(self(*c))
return
elif isinstance(args[0], Cycle):
for k, v in args[0].items():
self[k] = v
return
args = [as_int(a) for a in args]
if any(i < 0 for i in args):
raise ValueError('negative integers are not allowed in a cycle.')
if has_dups(args):
raise ValueError('All elements must be unique in a cycle.')
for i in range(-len(args), 0):
self[args[i]] = args[i + 1]
@property
def size(self):
if not self:
return 0
return max(self.keys()) + 1
def copy(self):
return Cycle(self)
class Permutation(Atom):
r"""
A permutation, alternatively known as an 'arrangement number' or 'ordering'
is an arrangement of the elements of an ordered list into a one-to-one
mapping with itself. The permutation of a given arrangement is given by
indicating the positions of the elements after re-arrangement [2]_. For
example, if one started with elements ``[x, y, a, b]`` (in that order) and
they were reordered as ``[x, y, b, a]`` then the permutation would be
``[0, 1, 3, 2]``. Notice that (in SymPy) the first element is always referred
to as 0 and the permutation uses the indices of the elements in the
original ordering, not the elements ``(a, b, ...)`` themselves.
>>> from sympy.combinatorics import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
Permutations Notation
=====================
Permutations are commonly represented in disjoint cycle or array forms.
Array Notation and 2-line Form
------------------------------------
In the 2-line form, the elements and their final positions are shown
as a matrix with 2 rows:
[0 1 2 ... n-1]
[p(0) p(1) p(2) ... p(n-1)]
Since the first line is always ``range(n)``, where n is the size of p,
it is sufficient to represent the permutation by the second line,
referred to as the "array form" of the permutation. This is entered
in brackets as the argument to the Permutation class:
>>> p = Permutation([0, 2, 1]); p
Permutation([0, 2, 1])
Given i in range(p.size), the permutation maps i to i^p
>>> [i^p for i in range(p.size)]
[0, 2, 1]
The composite of two permutations p*q means first apply p, then q, so
i^(p*q) = (i^p)^q which is i^p^q according to Python precedence rules:
>>> q = Permutation([2, 1, 0])
>>> [i^p^q for i in range(3)]
[2, 0, 1]
>>> [i^(p*q) for i in range(3)]
[2, 0, 1]
One can use also the notation p(i) = i^p, but then the composition
rule is (p*q)(i) = q(p(i)), not p(q(i)):
>>> [(p*q)(i) for i in range(p.size)]
[2, 0, 1]
>>> [q(p(i)) for i in range(p.size)]
[2, 0, 1]
>>> [p(q(i)) for i in range(p.size)]
[1, 2, 0]
Disjoint Cycle Notation
-----------------------
In disjoint cycle notation, only the elements that have shifted are
indicated.
For example, [1, 3, 2, 0] can be represented as (0, 1, 3)(2).
This can be understood from the 2 line format of the given permutation.
In the 2-line form,
[0 1 2 3]
[1 3 2 0]
The element in the 0th position is 1, so 0 -> 1. The element in the 1st
position is three, so 1 -> 3. And the element in the third position is again
0, so 3 -> 0. Thus, 0 -> 1 -> 3 -> 0, and 2 -> 2. Thus, this can be represented
as 2 cycles: (0, 1, 3)(2).
In common notation, singular cycles are not explicitly written as they can be
inferred implicitly.
Only the relative ordering of elements in a cycle matter:
>>> Permutation(1,2,3) == Permutation(2,3,1) == Permutation(3,1,2)
True
The disjoint cycle notation is convenient when representing
permutations that have several cycles in them:
>>> Permutation(1, 2)(3, 5) == Permutation([[1, 2], [3, 5]])
True
It also provides some economy in entry when computing products of
permutations that are written in disjoint cycle notation:
>>> Permutation(1, 2)(1, 3)(2, 3)
Permutation([0, 3, 2, 1])
>>> _ == Permutation([[1, 2]])*Permutation([[1, 3]])*Permutation([[2, 3]])
True
Caution: when the cycles have common elements between them then the order
in which the permutations are applied matters. This module applies
the permutations from *left to right*.
>>> Permutation(1, 2)(2, 3) == Permutation([(1, 2), (2, 3)])
True
>>> Permutation(1, 2)(2, 3).list()
[0, 3, 1, 2]
In the above case, (1,2) is computed before (2,3).
As 0 -> 0, 0 -> 0, element in position 0 is 0.
As 1 -> 2, 2 -> 3, element in position 1 is 3.
As 2 -> 1, 1 -> 1, element in position 2 is 1.
As 3 -> 3, 3 -> 2, element in position 3 is 2.
If the first and second elements had been
swapped first, followed by the swapping of the second
and third, the result would have been [0, 2, 3, 1].
If, you want to apply the cycles in the conventional
right to left order, call the function with arguments in reverse order
as demonstrated below:
>>> Permutation([(1, 2), (2, 3)][::-1]).list()
[0, 2, 3, 1]
Entering a singleton in a permutation is a way to indicate the size of the
permutation. The ``size`` keyword can also be used.
Array-form entry:
>>> Permutation([[1, 2], [9]])
Permutation([0, 2, 1], size=10)
>>> Permutation([[1, 2]], size=10)
Permutation([0, 2, 1], size=10)
Cyclic-form entry:
>>> Permutation(1, 2, size=10)
Permutation([0, 2, 1], size=10)
>>> Permutation(9)(1, 2)
Permutation([0, 2, 1], size=10)
Caution: no singleton containing an element larger than the largest
in any previous cycle can be entered. This is an important difference
in how Permutation and Cycle handle the ``__call__`` syntax. A singleton
argument at the start of a Permutation performs instantiation of the
Permutation and is permitted:
>>> Permutation(5)
Permutation([], size=6)
A singleton entered after instantiation is a call to the permutation
-- a function call -- and if the argument is out of range it will
trigger an error. For this reason, it is better to start the cycle
with the singleton:
The following fails because there is no element 3:
>>> Permutation(1, 2)(3)
Traceback (most recent call last):
...
IndexError: list index out of range
This is ok: only the call to an out of range singleton is prohibited;
otherwise the permutation autosizes:
>>> Permutation(3)(1, 2)
Permutation([0, 2, 1, 3])
>>> Permutation(1, 2)(3, 4) == Permutation(3, 4)(1, 2)
True
Equality testing
----------------
The array forms must be the same in order for permutations to be equal:
>>> Permutation([1, 0, 2, 3]) == Permutation([1, 0])
False
Identity Permutation
--------------------
The identity permutation is a permutation in which no element is out of
place. It can be entered in a variety of ways. All the following create
an identity permutation of size 4:
>>> I = Permutation([0, 1, 2, 3])
>>> all(p == I for p in [
... Permutation(3),
... Permutation(range(4)),
... Permutation([], size=4),
... Permutation(size=4)])
True
Watch out for entering the range *inside* a set of brackets (which is
cycle notation):
>>> I == Permutation([range(4)])
False
Permutation Printing
====================
There are a few things to note about how Permutations are printed.
1) If you prefer one form (array or cycle) over another, you can set
``init_printing`` with the ``perm_cyclic`` flag.
>>> from sympy import init_printing
>>> p = Permutation(1, 2)(4, 5)(3, 4)
>>> p
Permutation([0, 2, 1, 4, 5, 3])
>>> init_printing(perm_cyclic=True, pretty_print=False)
>>> p
(1 2)(3 4 5)
2) Regardless of the setting, a list of elements in the array for cyclic
form can be obtained and either of those can be copied and supplied as
the argument to Permutation:
>>> p.array_form
[0, 2, 1, 4, 5, 3]
>>> p.cyclic_form
[[1, 2], [3, 4, 5]]
>>> Permutation(_) == p
True
3) Printing is economical in that as little as possible is printed while
retaining all information about the size of the permutation:
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> Permutation([1, 0, 2, 3])
Permutation([1, 0, 2, 3])
>>> Permutation([1, 0, 2, 3], size=20)
Permutation([1, 0], size=20)
>>> Permutation([1, 0, 2, 4, 3, 5, 6], size=20)
Permutation([1, 0, 2, 4, 3], size=20)
>>> p = Permutation([1, 0, 2, 3])
>>> init_printing(perm_cyclic=True, pretty_print=False)
>>> p
(3)(0 1)
>>> init_printing(perm_cyclic=False, pretty_print=False)
The 2 was not printed but it is still there as can be seen with the
array_form and size methods:
>>> p.array_form
[1, 0, 2, 3]
>>> p.size
4
Short introduction to other methods
===================================
The permutation can act as a bijective function, telling what element is
located at a given position
>>> q = Permutation([5, 2, 3, 4, 1, 0])
>>> q.array_form[1] # the hard way
2
>>> q(1) # the easy way
2
>>> {i: q(i) for i in range(q.size)} # showing the bijection
{0: 5, 1: 2, 2: 3, 3: 4, 4: 1, 5: 0}
The full cyclic form (including singletons) can be obtained:
>>> p.full_cyclic_form
[[0, 1], [2], [3]]
Any permutation can be factored into transpositions of pairs of elements:
>>> Permutation([[1, 2], [3, 4, 5]]).transpositions()
[(1, 2), (3, 5), (3, 4)]
>>> Permutation.rmul(*[Permutation([ti], size=6) for ti in _]).cyclic_form
[[1, 2], [3, 4, 5]]
The number of permutations on a set of n elements is given by n! and is
called the cardinality.
>>> p.size
4
>>> p.cardinality
24
A given permutation has a rank among all the possible permutations of the
same elements, but what that rank is depends on how the permutations are
enumerated. (There are a number of different methods of doing so.) The
lexicographic rank is given by the rank method and this rank is used to
increment a permutation with addition/subtraction:
>>> p.rank()
6
>>> p + 1
Permutation([1, 0, 3, 2])
>>> p.next_lex()
Permutation([1, 0, 3, 2])
>>> _.rank()
7
>>> p.unrank_lex(p.size, rank=7)
Permutation([1, 0, 3, 2])
The product of two permutations p and q is defined as their composition as
functions, (p*q)(i) = q(p(i)) [6]_.
>>> p = Permutation([1, 0, 2, 3])
>>> q = Permutation([2, 3, 1, 0])
>>> list(q*p)
[2, 3, 0, 1]
>>> list(p*q)
[3, 2, 1, 0]
>>> [q(p(i)) for i in range(p.size)]
[3, 2, 1, 0]
The permutation can be 'applied' to any list-like object, not only
Permutations:
>>> p(['zero', 'one', 'four', 'two'])
['one', 'zero', 'four', 'two']
>>> p('zo42')
['o', 'z', '4', '2']
If you have a list of arbitrary elements, the corresponding permutation
can be found with the from_sequence method:
>>> Permutation.from_sequence('SymPy')
Permutation([1, 3, 2, 0, 4])
Checking if a Permutation is contained in a Group
=================================================
Generally if you have a group of permutations G on n symbols, and
you're checking if a permutation on less than n symbols is part
of that group, the check will fail.
Here is an example for n=5 and we check if the cycle
(1,2,3) is in G:
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=True, pretty_print=False)
>>> from sympy.combinatorics import Cycle, Permutation
>>> from sympy.combinatorics.perm_groups import PermutationGroup
>>> G = PermutationGroup(Cycle(2, 3)(4, 5), Cycle(1, 2, 3, 4, 5))
>>> p1 = Permutation(Cycle(2, 5, 3))
>>> p2 = Permutation(Cycle(1, 2, 3))
>>> a1 = Permutation(Cycle(1, 2, 3).list(6))
>>> a2 = Permutation(Cycle(1, 2, 3)(5))
>>> a3 = Permutation(Cycle(1, 2, 3),size=6)
>>> for p in [p1,p2,a1,a2,a3]: p, G.contains(p)
((2 5 3), True)
((1 2 3), False)
((5)(1 2 3), True)
((5)(1 2 3), True)
((5)(1 2 3), True)
The check for p2 above will fail.
Checking if p1 is in G works because SymPy knows
G is a group on 5 symbols, and p1 is also on 5 symbols
(its largest element is 5).
For ``a1``, the ``.list(6)`` call will extend the permutation to 5
symbols, so the test will work as well. In the case of ``a2`` the
permutation is being extended to 5 symbols by using a singleton,
and in the case of ``a3`` it's extended through the constructor
argument ``size=6``.
There is another way to do this, which is to tell the ``contains``
method that the number of symbols the group is on doesn't need to
match perfectly the number of symbols for the permutation:
>>> G.contains(p2,strict=False)
True
This can be via the ``strict`` argument to the ``contains`` method,
and SymPy will try to extend the permutation on its own and then
perform the containment check.
See Also
========
Cycle
References
==========
.. [1] Skiena, S. 'Permutations.' 1.1 in Implementing Discrete Mathematics
Combinatorics and Graph Theory with Mathematica. Reading, MA:
Addison-Wesley, pp. 3-16, 1990.
.. [2] Knuth, D. E. The Art of Computer Programming, Vol. 4: Combinatorial
Algorithms, 1st ed. Reading, MA: Addison-Wesley, 2011.
.. [3] Wendy Myrvold and Frank Ruskey. 2001. Ranking and unranking
permutations in linear time. Inf. Process. Lett. 79, 6 (September 2001),
281-284. DOI=10.1016/S0020-0190(01)00141-7
.. [4] D. L. Kreher, D. R. Stinson 'Combinatorial Algorithms'
CRC Press, 1999
.. [5] Graham, R. L.; Knuth, D. E.; and Patashnik, O.
Concrete Mathematics: A Foundation for Computer Science, 2nd ed.
Reading, MA: Addison-Wesley, 1994.
.. [6] https://en.wikipedia.org/wiki/Permutation#Product_and_inverse
.. [7] https://en.wikipedia.org/wiki/Lehmer_code
"""
is_Permutation = True
_array_form = None
_cyclic_form = None
_cycle_structure = None
_size = None
_rank = None
def __new__(cls, *args, size=None, **kwargs):
"""
Constructor for the Permutation object from a list or a
list of lists in which all elements of the permutation may
appear only once.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
Permutations entered in array-form are left unaltered:
>>> Permutation([0, 2, 1])
Permutation([0, 2, 1])
Permutations entered in cyclic form are converted to array form;
singletons need not be entered, but can be entered to indicate the
largest element:
>>> Permutation([[4, 5, 6], [0, 1]])
Permutation([1, 0, 2, 3, 5, 6, 4])
>>> Permutation([[4, 5, 6], [0, 1], [19]])
Permutation([1, 0, 2, 3, 5, 6, 4], size=20)
All manipulation of permutations assumes that the smallest element
is 0 (in keeping with 0-based indexing in Python) so if the 0 is
missing when entering a permutation in array form, an error will be
raised:
>>> Permutation([2, 1])
Traceback (most recent call last):
...
ValueError: Integers 0 through 2 must be present.
If a permutation is entered in cyclic form, it can be entered without
singletons and the ``size`` specified so those values can be filled
in, otherwise the array form will only extend to the maximum value
in the cycles:
>>> Permutation([[1, 4], [3, 5, 2]], size=10)
Permutation([0, 4, 3, 5, 1, 2], size=10)
>>> _.array_form
[0, 4, 3, 5, 1, 2, 6, 7, 8, 9]
"""
if size is not None:
size = int(size)
#a) ()
#b) (1) = identity
#c) (1, 2) = cycle
#d) ([1, 2, 3]) = array form
#e) ([[1, 2]]) = cyclic form
#f) (Cycle) = conversion to permutation
#g) (Permutation) = adjust size or return copy
ok = True
if not args: # a
return cls._af_new(list(range(size or 0)))
elif len(args) > 1: # c
return cls._af_new(Cycle(*args).list(size))
if len(args) == 1:
a = args[0]
if isinstance(a, cls): # g
if size is None or size == a.size:
return a
return cls(a.array_form, size=size)
if isinstance(a, Cycle): # f
return cls._af_new(a.list(size))
if not is_sequence(a): # b
if size is not None and a + 1 > size:
raise ValueError('size is too small when max is %s' % a)
return cls._af_new(list(range(a + 1)))
if has_variety(is_sequence(ai) for ai in a):
ok = False
else:
ok = False
if not ok:
raise ValueError("Permutation argument must be a list of ints, "
"a list of lists, Permutation or Cycle.")
# safe to assume args are valid; this also makes a copy
# of the args
args = list(args[0])
is_cycle = args and is_sequence(args[0])
if is_cycle: # e
args = [[int(i) for i in c] for c in args]
else: # d
args = [int(i) for i in args]
# if there are n elements present, 0, 1, ..., n-1 should be present
# unless a cycle notation has been provided. A 0 will be added
# for convenience in case one wants to enter permutations where
# counting starts from 1.
temp = flatten(args)
if has_dups(temp) and not is_cycle:
raise ValueError('there were repeated elements.')
temp = set(temp)
if not is_cycle:
if temp != set(range(len(temp))):
raise ValueError('Integers 0 through %s must be present.' %
max(temp))
if size is not None and temp and max(temp) + 1 > size:
raise ValueError('max element should not exceed %s' % (size - 1))
if is_cycle:
# it's not necessarily canonical so we won't store
# it -- use the array form instead
c = Cycle()
for ci in args:
c = c(*ci)
aform = c.list()
else:
aform = list(args)
if size and size > len(aform):
# don't allow for truncation of permutation which
# might split a cycle and lead to an invalid aform
# but do allow the permutation size to be increased
aform.extend(list(range(len(aform), size)))
return cls._af_new(aform)
@classmethod
def _af_new(cls, perm):
"""A method to produce a Permutation object from a list;
the list is bound to the _array_form attribute, so it must
not be modified; this method is meant for internal use only;
the list ``a`` is supposed to be generated as a temporary value
in a method, so p = Perm._af_new(a) is the only object
to hold a reference to ``a``::
Examples
========
>>> from sympy.combinatorics.permutations import Perm
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> a = [2, 1, 3, 0]
>>> p = Perm._af_new(a)
>>> p
Permutation([2, 1, 3, 0])
"""
p = super().__new__(cls)
p._array_form = perm
p._size = len(perm)
return p
def _hashable_content(self):
# the array_form (a list) is the Permutation arg, so we need to
# return a tuple, instead
return tuple(self.array_form)
@property
def array_form(self):
"""
Return a copy of the attribute _array_form
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([[2, 0], [3, 1]])
>>> p.array_form
[2, 3, 0, 1]
>>> Permutation([[2, 0, 3, 1]]).array_form
[3, 2, 0, 1]
>>> Permutation([2, 0, 3, 1]).array_form
[2, 0, 3, 1]
>>> Permutation([[1, 2], [4, 5]]).array_form
[0, 2, 1, 3, 5, 4]
"""
return self._array_form[:]
def list(self, size=None):
"""Return the permutation as an explicit list, possibly
trimming unmoved elements if size is less than the maximum
element in the permutation; if this is desired, setting
``size=-1`` will guarantee such trimming.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation(2, 3)(4, 5)
>>> p.list()
[0, 1, 3, 2, 5, 4]
>>> p.list(10)
[0, 1, 3, 2, 5, 4, 6, 7, 8, 9]
Passing a length too small will trim trailing, unchanged elements
in the permutation:
>>> Permutation(2, 4)(1, 2, 4).list(-1)
[0, 2, 1]
>>> Permutation(3).list(-1)
[]
"""
if not self and size is None:
raise ValueError('must give size for empty Cycle')
rv = self.array_form
if size is not None:
if size > self.size:
rv.extend(list(range(self.size, size)))
else:
# find first value from rhs where rv[i] != i
i = self.size - 1
while rv:
if rv[-1] != i:
break
rv.pop()
i -= 1
return rv
@property
def cyclic_form(self):
"""
This is used to convert to the cyclic notation
from the canonical notation. Singletons are omitted.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 3, 1, 2])
>>> p.cyclic_form
[[1, 3, 2]]
>>> Permutation([1, 0, 2, 4, 3, 5]).cyclic_form
[[0, 1], [3, 4]]
See Also
========
array_form, full_cyclic_form
"""
if self._cyclic_form is not None:
return list(self._cyclic_form)
array_form = self.array_form
unchecked = [True] * len(array_form)
cyclic_form = []
for i in range(len(array_form)):
if unchecked[i]:
cycle = []
cycle.append(i)
unchecked[i] = False
j = i
while unchecked[array_form[j]]:
j = array_form[j]
cycle.append(j)
unchecked[j] = False
if len(cycle) > 1:
cyclic_form.append(cycle)
assert cycle == list(minlex(cycle))
cyclic_form.sort()
self._cyclic_form = cyclic_form[:]
return cyclic_form
@property
def full_cyclic_form(self):
"""Return permutation in cyclic form including singletons.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation([0, 2, 1]).full_cyclic_form
[[0], [1, 2]]
"""
need = set(range(self.size)) - set(flatten(self.cyclic_form))
rv = self.cyclic_form + [[i] for i in need]
rv.sort()
return rv
@property
def size(self):
"""
Returns the number of elements in the permutation.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation([[3, 2], [0, 1]]).size
4
See Also
========
cardinality, length, order, rank
"""
return self._size
def support(self):
"""Return the elements in permutation, P, for which P[i] != i.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> p = Permutation([[3, 2], [0, 1], [4]])
>>> p.array_form
[1, 0, 3, 2, 4]
>>> p.support()
[0, 1, 2, 3]
"""
a = self.array_form
return [i for i, e in enumerate(a) if a[i] != i]
def __add__(self, other):
"""Return permutation that is other higher in rank than self.
The rank is the lexicographical rank, with the identity permutation
having rank of 0.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> I = Permutation([0, 1, 2, 3])
>>> a = Permutation([2, 1, 3, 0])
>>> I + a.rank() == a
True
See Also
========
__sub__, inversion_vector
"""
rank = (self.rank() + other) % self.cardinality
rv = self.unrank_lex(self.size, rank)
rv._rank = rank
return rv
def __sub__(self, other):
"""Return the permutation that is other lower in rank than self.
See Also
========
__add__
"""
return self.__add__(-other)
@staticmethod
def rmul(*args):
"""
Return product of Permutations [a, b, c, ...] as the Permutation whose
ith value is a(b(c(i))).
a, b, c, ... can be Permutation objects or tuples.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> a, b = [1, 0, 2], [0, 2, 1]
>>> a = Permutation(a); b = Permutation(b)
>>> list(Permutation.rmul(a, b))
[1, 2, 0]
>>> [a(b(i)) for i in range(3)]
[1, 2, 0]
This handles the operands in reverse order compared to the ``*`` operator:
>>> a = Permutation(a); b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]
Notes
=====
All items in the sequence will be parsed by Permutation as
necessary as long as the first item is a Permutation:
>>> Permutation.rmul(a, [0, 2, 1]) == Permutation.rmul(a, b)
True
The reverse order of arguments will raise a TypeError.
"""
rv = args[0]
for i in range(1, len(args)):
rv = args[i]*rv
return rv
@classmethod
def rmul_with_af(cls, *args):
"""
same as rmul, but the elements of args are Permutation objects
which have _array_form
"""
a = [x._array_form for x in args]
rv = cls._af_new(_af_rmuln(*a))
return rv
def mul_inv(self, other):
"""
other*~self, self and other have _array_form
"""
a = _af_invert(self._array_form)
b = other._array_form
return self._af_new(_af_rmul(a, b))
def __rmul__(self, other):
"""This is needed to coerce other to Permutation in rmul."""
cls = type(self)
return cls(other)*self
def __mul__(self, other):
"""
Return the product a*b as a Permutation; the ith value is b(a(i)).
Examples
========
>>> from sympy.combinatorics.permutations import _af_rmul, Permutation
>>> a, b = [1, 0, 2], [0, 2, 1]
>>> a = Permutation(a); b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]
This handles operands in reverse order compared to _af_rmul and rmul:
>>> al = list(a); bl = list(b)
>>> _af_rmul(al, bl)
[1, 2, 0]
>>> [al[bl[i]] for i in range(3)]
[1, 2, 0]
It is acceptable for the arrays to have different lengths; the shorter
one will be padded to match the longer one:
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> b*Permutation([1, 0])
Permutation([1, 2, 0])
>>> Permutation([1, 0])*b
Permutation([2, 0, 1])
It is also acceptable to allow coercion to handle conversion of a
single list to the left of a Permutation:
>>> [0, 1]*a # no change: 2-element identity
Permutation([1, 0, 2])
>>> [[0, 1]]*a # exchange first two elements
Permutation([0, 1, 2])
You cannot use more than 1 cycle notation in a product of cycles
since coercion can only handle one argument to the left. To handle
multiple cycles it is convenient to use Cycle instead of Permutation:
>>> [[1, 2]]*[[2, 3]]*Permutation([]) # doctest: +SKIP
>>> from sympy.combinatorics.permutations import Cycle
>>> Cycle(1, 2)(2, 3)
(1 3 2)
"""
from sympy.combinatorics.perm_groups import PermutationGroup, Coset
if isinstance(other, PermutationGroup):
return Coset(self, other, dir='-')
a = self.array_form
# __rmul__ makes sure the other is a Permutation
b = other.array_form
if not b:
perm = a
else:
b.extend(list(range(len(b), len(a))))
perm = [b[i] for i in a] + b[len(a):]
return self._af_new(perm)
def commutes_with(self, other):
"""
Checks if the elements are commuting.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> a = Permutation([1, 4, 3, 0, 2, 5])
>>> b = Permutation([0, 1, 2, 3, 4, 5])
>>> a.commutes_with(b)
True
>>> b = Permutation([2, 3, 5, 4, 1, 0])
>>> a.commutes_with(b)
False
"""
a = self.array_form
b = other.array_form
return _af_commutes_with(a, b)
def __pow__(self, n):
"""
Routine for finding powers of a permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> p = Permutation([2, 0, 3, 1])
>>> p.order()
4
>>> p**4
Permutation([0, 1, 2, 3])
"""
if isinstance(n, Permutation):
raise NotImplementedError(
'p**p is not defined; do you mean p^p (conjugate)?')
n = int(n)
return self._af_new(_af_pow(self.array_form, n))
def __rxor__(self, i):
"""Return self(i) when ``i`` is an int.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> p = Permutation(1, 2, 9)
>>> 2^p == p(2) == 9
True
"""
if int(i) == i:
return self(i)
else:
raise NotImplementedError(
"i^p = p(i) when i is an integer, not %s." % i)
def __xor__(self, h):
"""Return the conjugate permutation ``~h*self*h` `.
Explanation
===========
If ``a`` and ``b`` are conjugates, ``a = h*b*~h`` and
``b = ~h*a*h`` and both have the same cycle structure.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation(1, 2, 9)
>>> q = Permutation(6, 9, 8)
>>> p*q != q*p
True
Calculate and check properties of the conjugate:
>>> c = p^q
>>> c == ~q*p*q and p == q*c*~q
True
The expression q^p^r is equivalent to q^(p*r):
>>> r = Permutation(9)(4, 6, 8)
>>> q^p^r == q^(p*r)
True
If the term to the left of the conjugate operator, i, is an integer
then this is interpreted as selecting the ith element from the
permutation to the right:
>>> all(i^p == p(i) for i in range(p.size))
True
Note that the * operator as higher precedence than the ^ operator:
>>> q^r*p^r == q^(r*p)^r == Permutation(9)(1, 6, 4)
True
Notes
=====
In Python the precedence rule is p^q^r = (p^q)^r which differs
in general from p^(q^r)
>>> q^p^r
(9)(1 4 8)
>>> q^(p^r)
(9)(1 8 6)
For a given r and p, both of the following are conjugates of p:
~r*p*r and r*p*~r. But these are not necessarily the same:
>>> ~r*p*r == r*p*~r
True
>>> p = Permutation(1, 2, 9)(5, 6)
>>> ~r*p*r == r*p*~r
False
The conjugate ~r*p*r was chosen so that ``p^q^r`` would be equivalent
to ``p^(q*r)`` rather than ``p^(r*q)``. To obtain r*p*~r, pass ~r to
this method:
>>> p^~r == r*p*~r
True
"""
if self.size != h.size:
raise ValueError("The permutations must be of equal size.")
a = [None]*self.size
h = h._array_form
p = self._array_form
for i in range(self.size):
a[h[i]] = h[p[i]]
return self._af_new(a)
def transpositions(self):
"""
Return the permutation decomposed into a list of transpositions.
Explanation
===========
It is always possible to express a permutation as the product of
transpositions, see [1]
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([[1, 2, 3], [0, 4, 5, 6, 7]])
>>> t = p.transpositions()
>>> t
[(0, 7), (0, 6), (0, 5), (0, 4), (1, 3), (1, 2)]
>>> print(''.join(str(c) for c in t))
(0, 7)(0, 6)(0, 5)(0, 4)(1, 3)(1, 2)
>>> Permutation.rmul(*[Permutation([ti], size=p.size) for ti in t]) == p
True
References
==========
.. [1] https://en.wikipedia.org/wiki/Transposition_%28mathematics%29#Properties
"""
a = self.cyclic_form
res = []
for x in a:
nx = len(x)
if nx == 2:
res.append(tuple(x))
elif nx > 2:
first = x[0]
for y in x[nx - 1:0:-1]:
res.append((first, y))
return res
@classmethod
def from_sequence(self, i, key=None):
"""Return the permutation needed to obtain ``i`` from the sorted
elements of ``i``. If custom sorting is desired, a key can be given.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation.from_sequence('SymPy')
(4)(0 1 3)
>>> _(sorted("SymPy"))
['S', 'y', 'm', 'P', 'y']
>>> Permutation.from_sequence('SymPy', key=lambda x: x.lower())
(4)(0 2)(1 3)
"""
ic = list(zip(i, list(range(len(i)))))
if key:
ic.sort(key=lambda x: key(x[0]))
else:
ic.sort()
return ~Permutation([i[1] for i in ic])
def __invert__(self):
"""
Return the inverse of the permutation.
A permutation multiplied by its inverse is the identity permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> p = Permutation([[2, 0], [3, 1]])
>>> ~p
Permutation([2, 3, 0, 1])
>>> _ == p**-1
True
>>> p*~p == ~p*p == Permutation([0, 1, 2, 3])
True
"""
return self._af_new(_af_invert(self._array_form))
def __iter__(self):
"""Yield elements from array form.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> list(Permutation(range(3)))
[0, 1, 2]
"""
yield from self.array_form
def __repr__(self):
from sympy.printing.repr import srepr
return srepr(self)
def __call__(self, *i):
"""
Allows applying a permutation instance as a bijective function.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([[2, 0], [3, 1]])
>>> p.array_form
[2, 3, 0, 1]
>>> [p(i) for i in range(4)]
[2, 3, 0, 1]
If an array is given then the permutation selects the items
from the array (i.e. the permutation is applied to the array):
>>> from sympy.abc import x
>>> p([x, 1, 0, x**2])
[0, x**2, x, 1]
"""
# list indices can be Integer or int; leave this
# as it is (don't test or convert it) because this
# gets called a lot and should be fast
if len(i) == 1:
i = i[0]
if not isinstance(i, Iterable):
i = as_int(i)
if i < 0 or i > self.size:
raise TypeError(
"{} should be an integer between 0 and {}"
.format(i, self.size-1))
return self._array_form[i]
# P([a, b, c])
if len(i) != self.size:
raise TypeError(
"{} should have the length {}.".format(i, self.size))
return [i[j] for j in self._array_form]
# P(1, 2, 3)
return self*Permutation(Cycle(*i), size=self.size)
def atoms(self):
"""
Returns all the elements of a permutation
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation([0, 1, 2, 3, 4, 5]).atoms()
{0, 1, 2, 3, 4, 5}
>>> Permutation([[0, 1], [2, 3], [4, 5]]).atoms()
{0, 1, 2, 3, 4, 5}
"""
return set(self.array_form)
def apply(self, i):
r"""Apply the permutation to an expression.
Parameters
==========
i : Expr
It should be an integer between $0$ and $n-1$ where $n$
is the size of the permutation.
If it is a symbol or a symbolic expression that can
have integer values, an ``AppliedPermutation`` object
will be returned which can represent an unevaluated
function.
Notes
=====
Any permutation can be defined as a bijective function
$\sigma : \{ 0, 1, \dots, n-1 \} \rightarrow \{ 0, 1, \dots, n-1 \}$
where $n$ denotes the size of the permutation.
The definition may even be extended for any set with distinctive
elements, such that the permutation can even be applied for
real numbers or such, however, it is not implemented for now for
computational reasons and the integrity with the group theory
module.
This function is similar to the ``__call__`` magic, however,
``__call__`` magic already has some other applications like
permuting an array or attatching new cycles, which would
not always be mathematically consistent.
This also guarantees that the return type is a SymPy integer,
which guarantees the safety to use assumptions.
"""
i = _sympify(i)
if i.is_integer is False:
raise NotImplementedError("{} should be an integer.".format(i))
n = self.size
if (i < 0) == True or (i >= n) == True:
raise NotImplementedError(
"{} should be an integer between 0 and {}".format(i, n-1))
if i.is_Integer:
return Integer(self._array_form[i])
return AppliedPermutation(self, i)
def next_lex(self):
"""
Returns the next permutation in lexicographical order.
If self is the last permutation in lexicographical order
it returns None.
See [4] section 2.4.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([2, 3, 1, 0])
>>> p = Permutation([2, 3, 1, 0]); p.rank()
17
>>> p = p.next_lex(); p.rank()
18
See Also
========
rank, unrank_lex
"""
perm = self.array_form[:]
n = len(perm)
i = n - 2
while perm[i + 1] < perm[i]:
i -= 1
if i == -1:
return None
else:
j = n - 1
while perm[j] < perm[i]:
j -= 1
perm[j], perm[i] = perm[i], perm[j]
i += 1
j = n - 1
while i < j:
perm[j], perm[i] = perm[i], perm[j]
i += 1
j -= 1
return self._af_new(perm)
@classmethod
def unrank_nonlex(self, n, r):
"""
This is a linear time unranking algorithm that does not
respect lexicographic order [3].
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> Permutation.unrank_nonlex(4, 5)
Permutation([2, 0, 3, 1])
>>> Permutation.unrank_nonlex(4, -1)
Permutation([0, 1, 2, 3])
See Also
========
next_nonlex, rank_nonlex
"""
def _unrank1(n, r, a):
if n > 0:
a[n - 1], a[r % n] = a[r % n], a[n - 1]
_unrank1(n - 1, r//n, a)
id_perm = list(range(n))
n = int(n)
r = r % ifac(n)
_unrank1(n, r, id_perm)
return self._af_new(id_perm)
def rank_nonlex(self, inv_perm=None):
"""
This is a linear time ranking algorithm that does not
enforce lexicographic order [3].
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.rank_nonlex()
23
See Also
========
next_nonlex, unrank_nonlex
"""
def _rank1(n, perm, inv_perm):
if n == 1:
return 0
s = perm[n - 1]
t = inv_perm[n - 1]
perm[n - 1], perm[t] = perm[t], s
inv_perm[n - 1], inv_perm[s] = inv_perm[s], t
return s + n*_rank1(n - 1, perm, inv_perm)
if inv_perm is None:
inv_perm = (~self).array_form
if not inv_perm:
return 0
perm = self.array_form[:]
r = _rank1(len(perm), perm, inv_perm)
return r
def next_nonlex(self):
"""
Returns the next permutation in nonlex order [3].
If self is the last permutation in this order it returns None.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> p = Permutation([2, 0, 3, 1]); p.rank_nonlex()
5
>>> p = p.next_nonlex(); p
Permutation([3, 0, 1, 2])
>>> p.rank_nonlex()
6
See Also
========
rank_nonlex, unrank_nonlex
"""
r = self.rank_nonlex()
if r == ifac(self.size) - 1:
return None
return self.unrank_nonlex(self.size, r + 1)
def rank(self):
"""
Returns the lexicographic rank of the permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.rank()
0
>>> p = Permutation([3, 2, 1, 0])
>>> p.rank()
23
See Also
========
next_lex, unrank_lex, cardinality, length, order, size
"""
if self._rank is not None:
return self._rank
rank = 0
rho = self.array_form[:]
n = self.size - 1
size = n + 1
psize = int(ifac(n))
for j in range(size - 1):
rank += rho[j]*psize
for i in range(j + 1, size):
if rho[i] > rho[j]:
rho[i] -= 1
psize //= n
n -= 1
self._rank = rank
return rank
@property
def cardinality(self):
"""
Returns the number of all possible permutations.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.cardinality
24
See Also
========
length, order, rank, size
"""
return int(ifac(self.size))
def parity(self):
"""
Computes the parity of a permutation.
Explanation
===========
The parity of a permutation reflects the parity of the
number of inversions in the permutation, i.e., the
number of pairs of x and y such that ``x > y`` but ``p[x] < p[y]``.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.parity()
0
>>> p = Permutation([3, 2, 0, 1])
>>> p.parity()
1
See Also
========
_af_parity
"""
if self._cyclic_form is not None:
return (self.size - self.cycles) % 2
return _af_parity(self.array_form)
@property
def is_even(self):
"""
Checks if a permutation is even.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.is_even
True
>>> p = Permutation([3, 2, 1, 0])
>>> p.is_even
True
See Also
========
is_odd
"""
return not self.is_odd
@property
def is_odd(self):
"""
Checks if a permutation is odd.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.is_odd
False
>>> p = Permutation([3, 2, 0, 1])
>>> p.is_odd
True
See Also
========
is_even
"""
return bool(self.parity() % 2)
@property
def is_Singleton(self):
"""
Checks to see if the permutation contains only one number and is
thus the only possible permutation of this set of numbers
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation([0]).is_Singleton
True
>>> Permutation([0, 1]).is_Singleton
False
See Also
========
is_Empty
"""
return self.size == 1
@property
def is_Empty(self):
"""
Checks to see if the permutation is a set with zero elements
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation([]).is_Empty
True
>>> Permutation([0]).is_Empty
False
See Also
========
is_Singleton
"""
return self.size == 0
@property
def is_identity(self):
return self.is_Identity
@property
def is_Identity(self):
"""
Returns True if the Permutation is an identity permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([])
>>> p.is_Identity
True
>>> p = Permutation([[0], [1], [2]])
>>> p.is_Identity
True
>>> p = Permutation([0, 1, 2])
>>> p.is_Identity
True
>>> p = Permutation([0, 2, 1])
>>> p.is_Identity
False
See Also
========
order
"""
af = self.array_form
return not af or all(i == af[i] for i in range(self.size))
def ascents(self):
"""
Returns the positions of ascents in a permutation, ie, the location
where p[i] < p[i+1]
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([4, 0, 1, 3, 2])
>>> p.ascents()
[1, 2]
See Also
========
descents, inversions, min, max
"""
a = self.array_form
pos = [i for i in range(len(a) - 1) if a[i] < a[i + 1]]
return pos
def descents(self):
"""
Returns the positions of descents in a permutation, ie, the location
where p[i] > p[i+1]
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([4, 0, 1, 3, 2])
>>> p.descents()
[0, 3]
See Also
========
ascents, inversions, min, max
"""
a = self.array_form
pos = [i for i in range(len(a) - 1) if a[i] > a[i + 1]]
return pos
def max(self):
"""
The maximum element moved by the permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([1, 0, 2, 3, 4])
>>> p.max()
1
See Also
========
min, descents, ascents, inversions
"""
max = 0
a = self.array_form
for i in range(len(a)):
if a[i] != i and a[i] > max:
max = a[i]
return max
def min(self):
"""
The minimum element moved by the permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 4, 3, 2])
>>> p.min()
2
See Also
========
max, descents, ascents, inversions
"""
a = self.array_form
min = len(a)
for i in range(len(a)):
if a[i] != i and a[i] < min:
min = a[i]
return min
def inversions(self):
"""
Computes the number of inversions of a permutation.
Explanation
===========
An inversion is where i > j but p[i] < p[j].
For small length of p, it iterates over all i and j
values and calculates the number of inversions.
For large length of p, it uses a variation of merge
sort to calculate the number of inversions.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3, 4, 5])
>>> p.inversions()
0
>>> Permutation([3, 2, 1, 0]).inversions()
6
See Also
========
descents, ascents, min, max
References
==========
.. [1] http://www.cp.eng.chula.ac.th/~piak/teaching/algo/algo2008/count-inv.htm
"""
inversions = 0
a = self.array_form
n = len(a)
if n < 130:
for i in range(n - 1):
b = a[i]
for c in a[i + 1:]:
if b > c:
inversions += 1
else:
k = 1
right = 0
arr = a[:]
temp = a[:]
while k < n:
i = 0
while i + k < n:
right = i + k * 2 - 1
if right >= n:
right = n - 1
inversions += _merge(arr, temp, i, i + k, right)
i = i + k * 2
k = k * 2
return inversions
def commutator(self, x):
"""Return the commutator of ``self`` and ``x``: ``~x*~self*x*self``
If f and g are part of a group, G, then the commutator of f and g
is the group identity iff f and g commute, i.e. fg == gf.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> p = Permutation([0, 2, 3, 1])
>>> x = Permutation([2, 0, 3, 1])
>>> c = p.commutator(x); c
Permutation([2, 1, 3, 0])
>>> c == ~x*~p*x*p
True
>>> I = Permutation(3)
>>> p = [I + i for i in range(6)]
>>> for i in range(len(p)):
... for j in range(len(p)):
... c = p[i].commutator(p[j])
... if p[i]*p[j] == p[j]*p[i]:
... assert c == I
... else:
... assert c != I
...
References
==========
.. [1] https://en.wikipedia.org/wiki/Commutator
"""
a = self.array_form
b = x.array_form
n = len(a)
if len(b) != n:
raise ValueError("The permutations must be of equal size.")
inva = [None]*n
for i in range(n):
inva[a[i]] = i
invb = [None]*n
for i in range(n):
invb[b[i]] = i
return self._af_new([a[b[inva[i]]] for i in invb])
def signature(self):
"""
Gives the signature of the permutation needed to place the
elements of the permutation in canonical order.
The signature is calculated as (-1)^<number of inversions>
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2])
>>> p.inversions()
0
>>> p.signature()
1
>>> q = Permutation([0,2,1])
>>> q.inversions()
1
>>> q.signature()
-1
See Also
========
inversions
"""
if self.is_even:
return 1
return -1
def order(self):
"""
Computes the order of a permutation.
When the permutation is raised to the power of its
order it equals the identity permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> p = Permutation([3, 1, 5, 2, 4, 0])
>>> p.order()
4
>>> (p**(p.order()))
Permutation([], size=6)
See Also
========
identity, cardinality, length, rank, size
"""
return reduce(lcm, [len(cycle) for cycle in self.cyclic_form], 1)
def length(self):
"""
Returns the number of integers moved by a permutation.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation([0, 3, 2, 1]).length()
2
>>> Permutation([[0, 1], [2, 3]]).length()
4
See Also
========
min, max, support, cardinality, order, rank, size
"""
return len(self.support())
@property
def cycle_structure(self):
"""Return the cycle structure of the permutation as a dictionary
indicating the multiplicity of each cycle length.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation(3).cycle_structure
{1: 4}
>>> Permutation(0, 4, 3)(1, 2)(5, 6).cycle_structure
{2: 2, 3: 1}
"""
if self._cycle_structure:
rv = self._cycle_structure
else:
rv = defaultdict(int)
singletons = self.size
for c in self.cyclic_form:
rv[len(c)] += 1
singletons -= len(c)
if singletons:
rv[1] = singletons
self._cycle_structure = rv
return dict(rv) # make a copy
@property
def cycles(self):
"""
Returns the number of cycles contained in the permutation
(including singletons).
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation([0, 1, 2]).cycles
3
>>> Permutation([0, 1, 2]).full_cyclic_form
[[0], [1], [2]]
>>> Permutation(0, 1)(2, 3).cycles
2
See Also
========
sympy.functions.combinatorial.numbers.stirling
"""
return len(self.full_cyclic_form)
def index(self):
"""
Returns the index of a permutation.
The index of a permutation is the sum of all subscripts j such
that p[j] is greater than p[j+1].
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([3, 0, 2, 1, 4])
>>> p.index()
2
"""
a = self.array_form
return sum([j for j in range(len(a) - 1) if a[j] > a[j + 1]])
def runs(self):
"""
Returns the runs of a permutation.
An ascending sequence in a permutation is called a run [5].
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([2, 5, 7, 3, 6, 0, 1, 4, 8])
>>> p.runs()
[[2, 5, 7], [3, 6], [0, 1, 4, 8]]
>>> q = Permutation([1,3,2,0])
>>> q.runs()
[[1, 3], [2], [0]]
"""
return runs(self.array_form)
def inversion_vector(self):
"""Return the inversion vector of the permutation.
The inversion vector consists of elements whose value
indicates the number of elements in the permutation
that are lesser than it and lie on its right hand side.
The inversion vector is the same as the Lehmer encoding of a
permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([4, 8, 0, 7, 1, 5, 3, 6, 2])
>>> p.inversion_vector()
[4, 7, 0, 5, 0, 2, 1, 1]
>>> p = Permutation([3, 2, 1, 0])
>>> p.inversion_vector()
[3, 2, 1]
The inversion vector increases lexicographically with the rank
of the permutation, the -ith element cycling through 0..i.
>>> p = Permutation(2)
>>> while p:
... print('%s %s %s' % (p, p.inversion_vector(), p.rank()))
... p = p.next_lex()
(2) [0, 0] 0
(1 2) [0, 1] 1
(2)(0 1) [1, 0] 2
(0 1 2) [1, 1] 3
(0 2 1) [2, 0] 4
(0 2) [2, 1] 5
See Also
========
from_inversion_vector
"""
self_array_form = self.array_form
n = len(self_array_form)
inversion_vector = [0] * (n - 1)
for i in range(n - 1):
val = 0
for j in range(i + 1, n):
if self_array_form[j] < self_array_form[i]:
val += 1
inversion_vector[i] = val
return inversion_vector
def rank_trotterjohnson(self):
"""
Returns the Trotter Johnson rank, which we get from the minimal
change algorithm. See [4] section 2.4.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.rank_trotterjohnson()
0
>>> p = Permutation([0, 2, 1, 3])
>>> p.rank_trotterjohnson()
7
See Also
========
unrank_trotterjohnson, next_trotterjohnson
"""
if self.array_form == [] or self.is_Identity:
return 0
if self.array_form == [1, 0]:
return 1
perm = self.array_form
n = self.size
rank = 0
for j in range(1, n):
k = 1
i = 0
while perm[i] != j:
if perm[i] < j:
k += 1
i += 1
j1 = j + 1
if rank % 2 == 0:
rank = j1*rank + j1 - k
else:
rank = j1*rank + k - 1
return rank
@classmethod
def unrank_trotterjohnson(cls, size, rank):
"""
Trotter Johnson permutation unranking. See [4] section 2.4.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> Permutation.unrank_trotterjohnson(5, 10)
Permutation([0, 3, 1, 2, 4])
See Also
========
rank_trotterjohnson, next_trotterjohnson
"""
perm = [0]*size
r2 = 0
n = ifac(size)
pj = 1
for j in range(2, size + 1):
pj *= j
r1 = (rank * pj) // n
k = r1 - j*r2
if r2 % 2 == 0:
for i in range(j - 1, j - k - 1, -1):
perm[i] = perm[i - 1]
perm[j - k - 1] = j - 1
else:
for i in range(j - 1, k, -1):
perm[i] = perm[i - 1]
perm[k] = j - 1
r2 = r1
return cls._af_new(perm)
def next_trotterjohnson(self):
"""
Returns the next permutation in Trotter-Johnson order.
If self is the last permutation it returns None.
See [4] section 2.4. If it is desired to generate all such
permutations, they can be generated in order more quickly
with the ``generate_bell`` function.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> p = Permutation([3, 0, 2, 1])
>>> p.rank_trotterjohnson()
4
>>> p = p.next_trotterjohnson(); p
Permutation([0, 3, 2, 1])
>>> p.rank_trotterjohnson()
5
See Also
========
rank_trotterjohnson, unrank_trotterjohnson, sympy.utilities.iterables.generate_bell
"""
pi = self.array_form[:]
n = len(pi)
st = 0
rho = pi[:]
done = False
m = n-1
while m > 0 and not done:
d = rho.index(m)
for i in range(d, m):
rho[i] = rho[i + 1]
par = _af_parity(rho[:m])
if par == 1:
if d == m:
m -= 1
else:
pi[st + d], pi[st + d + 1] = pi[st + d + 1], pi[st + d]
done = True
else:
if d == 0:
m -= 1
st += 1
else:
pi[st + d], pi[st + d - 1] = pi[st + d - 1], pi[st + d]
done = True
if m == 0:
return None
return self._af_new(pi)
def get_precedence_matrix(self):
"""
Gets the precedence matrix. This is used for computing the
distance between two permutations.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> p = Permutation.josephus(3, 6, 1)
>>> p
Permutation([2, 5, 3, 1, 4, 0])
>>> p.get_precedence_matrix()
Matrix([
[0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 1, 0],
[1, 1, 0, 1, 1, 1],
[1, 1, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 0],
[1, 1, 0, 1, 1, 0]])
See Also
========
get_precedence_distance, get_adjacency_matrix, get_adjacency_distance
"""
m = zeros(self.size)
perm = self.array_form
for i in range(m.rows):
for j in range(i + 1, m.cols):
m[perm[i], perm[j]] = 1
return m
def get_precedence_distance(self, other):
"""
Computes the precedence distance between two permutations.
Explanation
===========
Suppose p and p' represent n jobs. The precedence metric
counts the number of times a job j is preceded by job i
in both p and p'. This metric is commutative.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([2, 0, 4, 3, 1])
>>> q = Permutation([3, 1, 2, 4, 0])
>>> p.get_precedence_distance(q)
7
>>> q.get_precedence_distance(p)
7
See Also
========
get_precedence_matrix, get_adjacency_matrix, get_adjacency_distance
"""
if self.size != other.size:
raise ValueError("The permutations must be of equal size.")
self_prec_mat = self.get_precedence_matrix()
other_prec_mat = other.get_precedence_matrix()
n_prec = 0
for i in range(self.size):
for j in range(self.size):
if i == j:
continue
if self_prec_mat[i, j] * other_prec_mat[i, j] == 1:
n_prec += 1
d = self.size * (self.size - 1)//2 - n_prec
return d
def get_adjacency_matrix(self):
"""
Computes the adjacency matrix of a permutation.
Explanation
===========
If job i is adjacent to job j in a permutation p
then we set m[i, j] = 1 where m is the adjacency
matrix of p.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation.josephus(3, 6, 1)
>>> p.get_adjacency_matrix()
Matrix([
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0]])
>>> q = Permutation([0, 1, 2, 3])
>>> q.get_adjacency_matrix()
Matrix([
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]])
See Also
========
get_precedence_matrix, get_precedence_distance, get_adjacency_distance
"""
m = zeros(self.size)
perm = self.array_form
for i in range(self.size - 1):
m[perm[i], perm[i + 1]] = 1
return m
def get_adjacency_distance(self, other):
"""
Computes the adjacency distance between two permutations.
Explanation
===========
This metric counts the number of times a pair i,j of jobs is
adjacent in both p and p'. If n_adj is this quantity then
the adjacency distance is n - n_adj - 1 [1]
[1] Reeves, Colin R. Landscapes, Operators and Heuristic search, Annals
of Operational Research, 86, pp 473-490. (1999)
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 3, 1, 2, 4])
>>> q = Permutation.josephus(4, 5, 2)
>>> p.get_adjacency_distance(q)
3
>>> r = Permutation([0, 2, 1, 4, 3])
>>> p.get_adjacency_distance(r)
4
See Also
========
get_precedence_matrix, get_precedence_distance, get_adjacency_matrix
"""
if self.size != other.size:
raise ValueError("The permutations must be of the same size.")
self_adj_mat = self.get_adjacency_matrix()
other_adj_mat = other.get_adjacency_matrix()
n_adj = 0
for i in range(self.size):
for j in range(self.size):
if i == j:
continue
if self_adj_mat[i, j] * other_adj_mat[i, j] == 1:
n_adj += 1
d = self.size - n_adj - 1
return d
def get_positional_distance(self, other):
"""
Computes the positional distance between two permutations.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 3, 1, 2, 4])
>>> q = Permutation.josephus(4, 5, 2)
>>> r = Permutation([3, 1, 4, 0, 2])
>>> p.get_positional_distance(q)
12
>>> p.get_positional_distance(r)
12
See Also
========
get_precedence_distance, get_adjacency_distance
"""
a = self.array_form
b = other.array_form
if len(a) != len(b):
raise ValueError("The permutations must be of the same size.")
return sum([abs(a[i] - b[i]) for i in range(len(a))])
@classmethod
def josephus(cls, m, n, s=1):
"""Return as a permutation the shuffling of range(n) using the Josephus
scheme in which every m-th item is selected until all have been chosen.
The returned permutation has elements listed by the order in which they
were selected.
The parameter ``s`` stops the selection process when there are ``s``
items remaining and these are selected by continuing the selection,
counting by 1 rather than by ``m``.
Consider selecting every 3rd item from 6 until only 2 remain::
choices chosen
======== ======
012345
01 345 2
01 34 25
01 4 253
0 4 2531
0 25314
253140
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation.josephus(3, 6, 2).array_form
[2, 5, 3, 1, 4, 0]
References
==========
.. [1] https://en.wikipedia.org/wiki/Flavius_Josephus
.. [2] https://en.wikipedia.org/wiki/Josephus_problem
.. [3] http://www.wou.edu/~burtonl/josephus.html
"""
from collections import deque
m -= 1
Q = deque(list(range(n)))
perm = []
while len(Q) > max(s, 1):
for dp in range(m):
Q.append(Q.popleft())
perm.append(Q.popleft())
perm.extend(list(Q))
return cls(perm)
@classmethod
def from_inversion_vector(cls, inversion):
"""
Calculates the permutation from the inversion vector.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> Permutation.from_inversion_vector([3, 2, 1, 0, 0])
Permutation([3, 2, 1, 0, 4, 5])
"""
size = len(inversion)
N = list(range(size + 1))
perm = []
try:
for k in range(size):
val = N[inversion[k]]
perm.append(val)
N.remove(val)
except IndexError:
raise ValueError("The inversion vector is not valid.")
perm.extend(N)
return cls._af_new(perm)
@classmethod
def random(cls, n):
"""
Generates a random permutation of length ``n``.
Uses the underlying Python pseudo-random number generator.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.random(2) in (Permutation([1, 0]), Permutation([0, 1]))
True
"""
perm_array = list(range(n))
random.shuffle(perm_array)
return cls._af_new(perm_array)
@classmethod
def unrank_lex(cls, size, rank):
"""
Lexicographic permutation unranking.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> from sympy import init_printing
>>> init_printing(perm_cyclic=False, pretty_print=False)
>>> a = Permutation.unrank_lex(5, 10)
>>> a.rank()
10
>>> a
Permutation([0, 2, 4, 1, 3])
See Also
========
rank, next_lex
"""
perm_array = [0] * size
psize = 1
for i in range(size):
new_psize = psize*(i + 1)
d = (rank % new_psize) // psize
rank -= d*psize
perm_array[size - i - 1] = d
for j in range(size - i, size):
if perm_array[j] > d - 1:
perm_array[j] += 1
psize = new_psize
return cls._af_new(perm_array)
def resize(self, n):
"""Resize the permutation to the new size ``n``.
Parameters
==========
n : int
The new size of the permutation.
Raises
======
ValueError
If the permutation cannot be resized to the given size.
This may only happen when resized to a smaller size than
the original.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
Increasing the size of a permutation:
>>> p = Permutation(0, 1, 2)
>>> p = p.resize(5)
>>> p
(4)(0 1 2)
Decreasing the size of the permutation:
>>> p = p.resize(4)
>>> p
(3)(0 1 2)
If resizing to the specific size breaks the cycles:
>>> p.resize(2)
Traceback (most recent call last):
...
ValueError: The permutation cannot be resized to 2 because the
cycle (0, 1, 2) may break.
"""
aform = self.array_form
l = len(aform)
if n > l:
aform += list(range(l, n))
return Permutation._af_new(aform)
elif n < l:
cyclic_form = self.full_cyclic_form
new_cyclic_form = []
for cycle in cyclic_form:
cycle_min = min(cycle)
cycle_max = max(cycle)
if cycle_min <= n-1:
if cycle_max > n-1:
raise ValueError(
"The permutation cannot be resized to {} "
"because the cycle {} may break."
.format(n, tuple(cycle)))
new_cyclic_form.append(cycle)
return Permutation(new_cyclic_form)
return self
# XXX Deprecated flag
print_cyclic = None
def _merge(arr, temp, left, mid, right):
"""
Merges two sorted arrays and calculates the inversion count.
Helper function for calculating inversions. This method is
for internal use only.
"""
i = k = left
j = mid
inv_count = 0
while i < mid and j <= right:
if arr[i] < arr[j]:
temp[k] = arr[i]
k += 1
i += 1
else:
temp[k] = arr[j]
k += 1
j += 1
inv_count += (mid -i)
while i < mid:
temp[k] = arr[i]
k += 1
i += 1
if j <= right:
k += right - j + 1
j += right - j + 1
arr[left:k + 1] = temp[left:k + 1]
else:
arr[left:right + 1] = temp[left:right + 1]
return inv_count
Perm = Permutation
_af_new = Perm._af_new
class AppliedPermutation(Expr):
"""A permutation applied to a symbolic variable.
Parameters
==========
perm : Permutation
x : Expr
Examples
========
>>> from sympy import Symbol
>>> from sympy.combinatorics import Permutation
Creating a symbolic permutation function application:
>>> x = Symbol('x')
>>> p = Permutation(0, 1, 2)
>>> p.apply(x)
AppliedPermutation((0 1 2), x)
>>> _.subs(x, 1)
2
"""
def __new__(cls, perm, x, evaluate=None):
if evaluate is None:
evaluate = global_parameters.evaluate
perm = _sympify(perm)
x = _sympify(x)
if not isinstance(perm, Permutation):
raise ValueError("{} must be a Permutation instance."
.format(perm))
if evaluate:
if x.is_Integer:
return perm.apply(x)
obj = super().__new__(cls, perm, x)
return obj
@dispatch(Permutation, Permutation)
def _eval_is_eq(lhs, rhs):
if lhs._size != rhs._size:
return None
return lhs._array_form == rhs._array_form
|
60508fdfd14fd506b17bbe424581427227886eb3747a61daef395d55855ced63 | from typing import Tuple as tTuple
from sympy.calculus.singularities import is_decreasing
from sympy.calculus.accumulationbounds import AccumulationBounds
from .expr_with_intlimits import ExprWithIntLimits
from .expr_with_limits import AddWithLimits
from .gosper import gosper_sum
from sympy.core.expr import Expr
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.function import Derivative, expand
from sympy.core.mul import Mul
from sympy.core.numbers import Float
from sympy.core.relational import Eq
from sympy.core.singleton import S
from sympy.core.sorting import ordered
from sympy.core.symbol import Dummy, Wild, Symbol, symbols
from sympy.functions.combinatorial.factorials import factorial
from sympy.functions.combinatorial.numbers import bernoulli, harmonic
from sympy.functions.elementary.exponential import exp, log
from sympy.functions.elementary.piecewise import Piecewise
from sympy.functions.elementary.trigonometric import cot, csc
from sympy.functions.special.hyper import hyper
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.functions.special.zeta_functions import zeta
from sympy.integrals.integrals import Integral
from sympy.logic.boolalg import And
from sympy.polys.partfrac import apart
from sympy.polys.polyerrors import PolynomialError, PolificationFailed
from sympy.polys.polytools import parallel_poly_from_expr, Poly, factor
from sympy.polys.rationaltools import together
from sympy.series.limitseq import limit_seq
from sympy.series.order import O
from sympy.series.residues import residue
from sympy.sets.sets import FiniteSet, Interval
from sympy.simplify.combsimp import combsimp
from sympy.simplify.hyperexpand import hyperexpand
from sympy.simplify.powsimp import powsimp
from sympy.simplify.radsimp import denom, fraction
from sympy.simplify.simplify import (factor_sum, sum_combine, simplify,
nsimplify, hypersimp)
from sympy.solvers.solvers import solve
from sympy.solvers.solveset import solveset
from sympy.utilities.iterables import sift
import itertools
class Sum(AddWithLimits, ExprWithIntLimits):
r"""
Represents unevaluated summation.
Explanation
===========
``Sum`` represents a finite or infinite series, with the first argument
being the general form of terms in the series, and the second argument
being ``(dummy_variable, start, end)``, with ``dummy_variable`` taking
all integer values from ``start`` through ``end``. In accordance with
long-standing mathematical convention, the end term is included in the
summation.
Finite sums
===========
For finite sums (and sums with symbolic limits assumed to be finite) we
follow the summation convention described by Karr [1], especially
definition 3 of section 1.4. The sum:
.. math::
\sum_{m \leq i < n} f(i)
has *the obvious meaning* for `m < n`, namely:
.. math::
\sum_{m \leq i < n} f(i) = f(m) + f(m+1) + \ldots + f(n-2) + f(n-1)
with the upper limit value `f(n)` excluded. The sum over an empty set is
zero if and only if `m = n`:
.. math::
\sum_{m \leq i < n} f(i) = 0 \quad \mathrm{for} \quad m = n
Finally, for all other sums over empty sets we assume the following
definition:
.. math::
\sum_{m \leq i < n} f(i) = - \sum_{n \leq i < m} f(i) \quad \mathrm{for} \quad m > n
It is important to note that Karr defines all sums with the upper
limit being exclusive. This is in contrast to the usual mathematical notation,
but does not affect the summation convention. Indeed we have:
.. math::
\sum_{m \leq i < n} f(i) = \sum_{i = m}^{n - 1} f(i)
where the difference in notation is intentional to emphasize the meaning,
with limits typeset on the top being inclusive.
Examples
========
>>> from sympy.abc import i, k, m, n, x
>>> from sympy import Sum, factorial, oo, IndexedBase, Function
>>> Sum(k, (k, 1, m))
Sum(k, (k, 1, m))
>>> Sum(k, (k, 1, m)).doit()
m**2/2 + m/2
>>> Sum(k**2, (k, 1, m))
Sum(k**2, (k, 1, m))
>>> Sum(k**2, (k, 1, m)).doit()
m**3/3 + m**2/2 + m/6
>>> Sum(x**k, (k, 0, oo))
Sum(x**k, (k, 0, oo))
>>> Sum(x**k, (k, 0, oo)).doit()
Piecewise((1/(1 - x), Abs(x) < 1), (Sum(x**k, (k, 0, oo)), True))
>>> Sum(x**k/factorial(k), (k, 0, oo)).doit()
exp(x)
Here are examples to do summation with symbolic indices. You
can use either Function of IndexedBase classes:
>>> f = Function('f')
>>> Sum(f(n), (n, 0, 3)).doit()
f(0) + f(1) + f(2) + f(3)
>>> Sum(f(n), (n, 0, oo)).doit()
Sum(f(n), (n, 0, oo))
>>> f = IndexedBase('f')
>>> Sum(f[n]**2, (n, 0, 3)).doit()
f[0]**2 + f[1]**2 + f[2]**2 + f[3]**2
An example showing that the symbolic result of a summation is still
valid for seemingly nonsensical values of the limits. Then the Karr
convention allows us to give a perfectly valid interpretation to
those sums by interchanging the limits according to the above rules:
>>> S = Sum(i, (i, 1, n)).doit()
>>> S
n**2/2 + n/2
>>> S.subs(n, -4)
6
>>> Sum(i, (i, 1, -4)).doit()
6
>>> Sum(-i, (i, -3, 0)).doit()
6
An explicit example of the Karr summation convention:
>>> S1 = Sum(i**2, (i, m, m+n-1)).doit()
>>> S1
m**2*n + m*n**2 - m*n + n**3/3 - n**2/2 + n/6
>>> S2 = Sum(i**2, (i, m+n, m-1)).doit()
>>> S2
-m**2*n - m*n**2 + m*n - n**3/3 + n**2/2 - n/6
>>> S1 + S2
0
>>> S3 = Sum(i, (i, m, m-1)).doit()
>>> S3
0
See Also
========
summation
Product, sympy.concrete.products.product
References
==========
.. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
Volume 28 Issue 2, April 1981, Pages 305-350
http://dl.acm.org/citation.cfm?doid=322248.322255
.. [2] https://en.wikipedia.org/wiki/Summation#Capital-sigma_notation
.. [3] https://en.wikipedia.org/wiki/Empty_sum
"""
__slots__ = ('is_commutative',)
limits: tTuple[tTuple[Symbol, Expr, Expr]]
def __new__(cls, function, *symbols, **assumptions):
obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
if not hasattr(obj, 'limits'):
return obj
if any(len(l) != 3 or None in l for l in obj.limits):
raise ValueError('Sum requires values for lower and upper bounds.')
return obj
def _eval_is_zero(self):
# a Sum is only zero if its function is zero or if all terms
# cancel out. This only answers whether the summand is zero; if
# not then None is returned since we don't analyze whether all
# terms cancel out.
if self.function.is_zero or self.has_empty_sequence:
return True
def _eval_is_extended_real(self):
if self.has_empty_sequence:
return True
return self.function.is_extended_real
def _eval_is_positive(self):
if self.has_finite_limits and self.has_reversed_limits is False:
return self.function.is_positive
def _eval_is_negative(self):
if self.has_finite_limits and self.has_reversed_limits is False:
return self.function.is_negative
def _eval_is_finite(self):
if self.has_finite_limits and self.function.is_finite:
return True
def doit(self, **hints):
if hints.get('deep', True):
f = self.function.doit(**hints)
else:
f = self.function
# first make sure any definite limits have summation
# variables with matching assumptions
reps = {}
for xab in self.limits:
d = _dummy_with_inherited_properties_concrete(xab)
if d:
reps[xab[0]] = d
if reps:
undo = {v: k for k, v in reps.items()}
did = self.xreplace(reps).doit(**hints)
if isinstance(did, tuple): # when separate=True
did = tuple([i.xreplace(undo) for i in did])
elif did is not None:
did = did.xreplace(undo)
else:
did = self
return did
if self.function.is_Matrix:
expanded = self.expand()
if self != expanded:
return expanded.doit()
return _eval_matrix_sum(self)
for n, limit in enumerate(self.limits):
i, a, b = limit
dif = b - a
if dif == -1:
# Any summation over an empty set is zero
return S.Zero
if dif.is_integer and dif.is_negative:
a, b = b + 1, a - 1
f = -f
newf = eval_sum(f, (i, a, b))
if newf is None:
if f == self.function:
zeta_function = self.eval_zeta_function(f, (i, a, b))
if zeta_function is not None:
return zeta_function
return self
else:
return self.func(f, *self.limits[n:])
f = newf
if hints.get('deep', True):
# eval_sum could return partially unevaluated
# result with Piecewise. In this case we won't
# doit() recursively.
if not isinstance(f, Piecewise):
return f.doit(**hints)
return f
def eval_zeta_function(self, f, limits):
"""
Check whether the function matches with the zeta function.
If it matches, then return a `Piecewise` expression because
zeta function does not converge unless `s > 1` and `q > 0`
"""
i, a, b = limits
w, y, z = Wild('w', exclude=[i]), Wild('y', exclude=[i]), Wild('z', exclude=[i])
result = f.match((w * i + y) ** (-z))
if result is not None and b is S.Infinity:
coeff = 1 / result[w] ** result[z]
s = result[z]
q = result[y] / result[w] + a
return Piecewise((coeff * zeta(s, q), And(q > 0, s > 1)), (self, True))
def _eval_derivative(self, x):
"""
Differentiate wrt x as long as x is not in the free symbols of any of
the upper or lower limits.
Explanation
===========
Sum(a*b*x, (x, 1, a)) can be differentiated wrt x or b but not `a`
since the value of the sum is discontinuous in `a`. In a case
involving a limit variable, the unevaluated derivative is returned.
"""
# diff already confirmed that x is in the free symbols of self, but we
# don't want to differentiate wrt any free symbol in the upper or lower
# limits
# XXX remove this test for free_symbols when the default _eval_derivative is in
if isinstance(x, Symbol) and x not in self.free_symbols:
return S.Zero
# get limits and the function
f, limits = self.function, list(self.limits)
limit = limits.pop(-1)
if limits: # f is the argument to a Sum
f = self.func(f, *limits)
_, a, b = limit
if x in a.free_symbols or x in b.free_symbols:
return None
df = Derivative(f, x, evaluate=True)
rv = self.func(df, limit)
return rv
def _eval_difference_delta(self, n, step):
k, _, upper = self.args[-1]
new_upper = upper.subs(n, n + step)
if len(self.args) == 2:
f = self.args[0]
else:
f = self.func(*self.args[:-1])
return Sum(f, (k, upper + 1, new_upper)).doit()
def _eval_simplify(self, **kwargs):
# split the function into adds
terms = Add.make_args(expand(self.function))
s_t = [] # Sum Terms
o_t = [] # Other Terms
for term in terms:
if term.has(Sum):
# if there is an embedded sum here
# it is of the form x * (Sum(whatever))
# hence we make a Mul out of it, and simplify all interior sum terms
subterms = Mul.make_args(expand(term))
out_terms = []
for subterm in subterms:
# go through each term
if isinstance(subterm, Sum):
# if it's a sum, simplify it
out_terms.append(subterm._eval_simplify())
else:
# otherwise, add it as is
out_terms.append(subterm)
# turn it back into a Mul
s_t.append(Mul(*out_terms))
else:
o_t.append(term)
# next try to combine any interior sums for further simplification
result = Add(sum_combine(s_t), *o_t)
return factor_sum(result, limits=self.limits)
def is_convergent(self):
r"""
Checks for the convergence of a Sum.
Explanation
===========
We divide the study of convergence of infinite sums and products in
two parts.
First Part:
One part is the question whether all the terms are well defined, i.e.,
they are finite in a sum and also non-zero in a product. Zero
is the analogy of (minus) infinity in products as
:math:`e^{-\infty} = 0`.
Second Part:
The second part is the question of convergence after infinities,
and zeros in products, have been omitted assuming that their number
is finite. This means that we only consider the tail of the sum or
product, starting from some point after which all terms are well
defined.
For example, in a sum of the form:
.. math::
\sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b}
where a and b are numbers. The routine will return true, even if there
are infinities in the term sequence (at most two). An analogous
product would be:
.. math::
\prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}}
This is how convergence is interpreted. It is concerned with what
happens at the limit. Finding the bad terms is another independent
matter.
Note: It is responsibility of user to see that the sum or product
is well defined.
There are various tests employed to check the convergence like
divergence test, root test, integral test, alternating series test,
comparison tests, Dirichlet tests. It returns true if Sum is convergent
and false if divergent and NotImplementedError if it cannot be checked.
References
==========
.. [1] https://en.wikipedia.org/wiki/Convergence_tests
Examples
========
>>> from sympy import factorial, S, Sum, Symbol, oo
>>> n = Symbol('n', integer=True)
>>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
True
>>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
False
>>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
False
>>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
True
See Also
========
Sum.is_absolutely_convergent()
sympy.concrete.products.Product.is_convergent()
"""
p, q, r = symbols('p q r', cls=Wild)
sym = self.limits[0][0]
lower_limit = self.limits[0][1]
upper_limit = self.limits[0][2]
sequence_term = self.function.simplify()
if len(sequence_term.free_symbols) > 1:
raise NotImplementedError("convergence checking for more than one symbol "
"containing series is not handled")
if lower_limit.is_finite and upper_limit.is_finite:
return S.true
# transform sym -> -sym and swap the upper_limit = S.Infinity
# and lower_limit = - upper_limit
if lower_limit is S.NegativeInfinity:
if upper_limit is S.Infinity:
return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
lower_limit = -upper_limit
upper_limit = S.Infinity
sym_ = Dummy(sym.name, integer=True, positive=True)
sequence_term = sequence_term.xreplace({sym: sym_})
sym = sym_
interval = Interval(lower_limit, upper_limit)
# Piecewise function handle
if sequence_term.is_Piecewise:
for func, cond in sequence_term.args:
# see if it represents something going to oo
if cond == True or cond.as_set().sup is S.Infinity:
s = Sum(func, (sym, lower_limit, upper_limit))
return s.is_convergent()
return S.true
### -------- Divergence test ----------- ###
try:
lim_val = limit_seq(sequence_term, sym)
if lim_val is not None and lim_val.is_zero is False:
return S.false
except NotImplementedError:
pass
try:
lim_val_abs = limit_seq(abs(sequence_term), sym)
if lim_val_abs is not None and lim_val_abs.is_zero is False:
return S.false
except NotImplementedError:
pass
order = O(sequence_term, (sym, S.Infinity))
### --------- p-series test (1/n**p) ---------- ###
p_series_test = order.expr.match(sym**p)
if p_series_test is not None:
if p_series_test[p] < -1:
return S.true
if p_series_test[p] >= -1:
return S.false
### ------------- comparison test ------------- ###
# 1/(n**p*log(n)**q*log(log(n))**r) comparison
n_log_test = order.expr.match(1/(sym**p*log(sym)**q*log(log(sym))**r))
if n_log_test is not None:
if (n_log_test[p] > 1 or
(n_log_test[p] == 1 and n_log_test[q] > 1) or
(n_log_test[p] == n_log_test[q] == 1 and n_log_test[r] > 1)):
return S.true
return S.false
### ------------- Limit comparison test -----------###
# (1/n) comparison
try:
lim_comp = limit_seq(sym*sequence_term, sym)
if lim_comp is not None and lim_comp.is_number and lim_comp > 0:
return S.false
except NotImplementedError:
pass
### ----------- ratio test ---------------- ###
next_sequence_term = sequence_term.xreplace({sym: sym + 1})
ratio = combsimp(powsimp(next_sequence_term/sequence_term))
try:
lim_ratio = limit_seq(ratio, sym)
if lim_ratio is not None and lim_ratio.is_number:
if abs(lim_ratio) > 1:
return S.false
if abs(lim_ratio) < 1:
return S.true
except NotImplementedError:
lim_ratio = None
### ---------- Raabe's test -------------- ###
if lim_ratio == 1: # ratio test inconclusive
test_val = sym*(sequence_term/
sequence_term.subs(sym, sym + 1) - 1)
test_val = test_val.gammasimp()
try:
lim_val = limit_seq(test_val, sym)
if lim_val is not None and lim_val.is_number:
if lim_val > 1:
return S.true
if lim_val < 1:
return S.false
except NotImplementedError:
pass
### ----------- root test ---------------- ###
# lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity)
try:
lim_evaluated = limit_seq(abs(sequence_term)**(1/sym), sym)
if lim_evaluated is not None and lim_evaluated.is_number:
if lim_evaluated < 1:
return S.true
if lim_evaluated > 1:
return S.false
except NotImplementedError:
pass
### ------------- alternating series test ----------- ###
dict_val = sequence_term.match(S.NegativeOne**(sym + p)*q)
if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
return S.true
### ------------- integral test -------------- ###
check_interval = None
maxima = solveset(sequence_term.diff(sym), sym, interval)
if not maxima:
check_interval = interval
elif isinstance(maxima, FiniteSet) and maxima.sup.is_number:
check_interval = Interval(maxima.sup, interval.sup)
if (check_interval is not None and
(is_decreasing(sequence_term, check_interval) or
is_decreasing(-sequence_term, check_interval))):
integral_val = Integral(
sequence_term, (sym, lower_limit, upper_limit))
try:
integral_val_evaluated = integral_val.doit()
if integral_val_evaluated.is_number:
return S(integral_val_evaluated.is_finite)
except NotImplementedError:
pass
### ----- Dirichlet and bounded times convergent tests ----- ###
# TODO
#
# Dirichlet_test
# https://en.wikipedia.org/wiki/Dirichlet%27s_test
#
# Bounded times convergent test
# It is based on comparison theorems for series.
# In particular, if the general term of a series can
# be written as a product of two terms a_n and b_n
# and if a_n is bounded and if Sum(b_n) is absolutely
# convergent, then the original series Sum(a_n * b_n)
# is absolutely convergent and so convergent.
#
# The following code can grows like 2**n where n is the
# number of args in order.expr
# Possibly combined with the potentially slow checks
# inside the loop, could make this test extremely slow
# for larger summation expressions.
if order.expr.is_Mul:
args = order.expr.args
argset = set(args)
### -------------- Dirichlet tests -------------- ###
m = Dummy('m', integer=True)
def _dirichlet_test(g_n):
try:
ing_val = limit_seq(Sum(g_n, (sym, interval.inf, m)).doit(), m)
if ing_val is not None and ing_val.is_finite:
return S.true
except NotImplementedError:
pass
### -------- bounded times convergent test ---------###
def _bounded_convergent_test(g1_n, g2_n):
try:
lim_val = limit_seq(g1_n, sym)
if lim_val is not None and (lim_val.is_finite or (
isinstance(lim_val, AccumulationBounds)
and (lim_val.max - lim_val.min).is_finite)):
if Sum(g2_n, (sym, lower_limit, upper_limit)).is_absolutely_convergent():
return S.true
except NotImplementedError:
pass
for n in range(1, len(argset)):
for a_tuple in itertools.combinations(args, n):
b_set = argset - set(a_tuple)
a_n = Mul(*a_tuple)
b_n = Mul(*b_set)
if is_decreasing(a_n, interval):
dirich = _dirichlet_test(b_n)
if dirich is not None:
return dirich
bc_test = _bounded_convergent_test(a_n, b_n)
if bc_test is not None:
return bc_test
_sym = self.limits[0][0]
sequence_term = sequence_term.xreplace({sym: _sym})
raise NotImplementedError("The algorithm to find the Sum convergence of %s "
"is not yet implemented" % (sequence_term))
def is_absolutely_convergent(self):
"""
Checks for the absolute convergence of an infinite series.
Same as checking convergence of absolute value of sequence_term of
an infinite series.
References
==========
.. [1] https://en.wikipedia.org/wiki/Absolute_convergence
Examples
========
>>> from sympy import Sum, Symbol, oo
>>> n = Symbol('n', integer=True)
>>> Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent()
False
>>> Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent()
True
See Also
========
Sum.is_convergent()
"""
return Sum(abs(self.function), self.limits).is_convergent()
def euler_maclaurin(self, m=0, n=0, eps=0, eval_integral=True):
"""
Return an Euler-Maclaurin approximation of self, where m is the
number of leading terms to sum directly and n is the number of
terms in the tail.
With m = n = 0, this is simply the corresponding integral
plus a first-order endpoint correction.
Returns (s, e) where s is the Euler-Maclaurin approximation
and e is the estimated error (taken to be the magnitude of
the first omitted term in the tail):
>>> from sympy.abc import k, a, b
>>> from sympy import Sum
>>> Sum(1/k, (k, 2, 5)).doit().evalf()
1.28333333333333
>>> s, e = Sum(1/k, (k, 2, 5)).euler_maclaurin()
>>> s
-log(2) + 7/20 + log(5)
>>> from sympy import sstr
>>> print(sstr((s.evalf(), e.evalf()), full_prec=True))
(1.26629073187415, 0.0175000000000000)
The endpoints may be symbolic:
>>> s, e = Sum(1/k, (k, a, b)).euler_maclaurin()
>>> s
-log(a) + log(b) + 1/(2*b) + 1/(2*a)
>>> e
Abs(1/(12*b**2) - 1/(12*a**2))
If the function is a polynomial of degree at most 2n+1, the
Euler-Maclaurin formula becomes exact (and e = 0 is returned):
>>> Sum(k, (k, 2, b)).euler_maclaurin()
(b**2/2 + b/2 - 1, 0)
>>> Sum(k, (k, 2, b)).doit()
b**2/2 + b/2 - 1
With a nonzero eps specified, the summation is ended
as soon as the remainder term is less than the epsilon.
"""
m = int(m)
n = int(n)
f = self.function
if len(self.limits) != 1:
raise ValueError("More than 1 limit")
i, a, b = self.limits[0]
if (a > b) == True:
if a - b == 1:
return S.Zero, S.Zero
a, b = b + 1, a - 1
f = -f
s = S.Zero
if m:
if b.is_Integer and a.is_Integer:
m = min(m, b - a + 1)
if not eps or f.is_polynomial(i):
for k in range(m):
s += f.subs(i, a + k)
else:
term = f.subs(i, a)
if term:
test = abs(term.evalf(3)) < eps
if test == True:
return s, abs(term)
elif not (test == False):
# a symbolic Relational class, can't go further
return term, S.Zero
s += term
for k in range(1, m):
term = f.subs(i, a + k)
if abs(term.evalf(3)) < eps and term != 0:
return s, abs(term)
s += term
if b - a + 1 == m:
return s, S.Zero
a += m
x = Dummy('x')
I = Integral(f.subs(i, x), (x, a, b))
if eval_integral:
I = I.doit()
s += I
def fpoint(expr):
if b is S.Infinity:
return expr.subs(i, a), 0
return expr.subs(i, a), expr.subs(i, b)
fa, fb = fpoint(f)
iterm = (fa + fb)/2
g = f.diff(i)
for k in range(1, n + 2):
ga, gb = fpoint(g)
term = bernoulli(2*k)/factorial(2*k)*(gb - ga)
if k > n:
break
if eps and term:
term_evalf = term.evalf(3)
if term_evalf is S.NaN:
return S.NaN, S.NaN
if abs(term_evalf) < eps:
break
s += term
g = g.diff(i, 2, simplify=False)
return s + iterm, abs(term)
def reverse_order(self, *indices):
"""
Reverse the order of a limit in a Sum.
Explanation
===========
``reverse_order(self, *indices)`` reverses some limits in the expression
``self`` which can be either a ``Sum`` or a ``Product``. The selectors in
the argument ``indices`` specify some indices whose limits get reversed.
These selectors are either variable names or numerical indices counted
starting from the inner-most limit tuple.
Examples
========
>>> from sympy import Sum
>>> from sympy.abc import x, y, a, b, c, d
>>> Sum(x, (x, 0, 3)).reverse_order(x)
Sum(-x, (x, 4, -1))
>>> Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(x, y)
Sum(x*y, (x, 6, 0), (y, 7, -1))
>>> Sum(x, (x, a, b)).reverse_order(x)
Sum(-x, (x, b + 1, a - 1))
>>> Sum(x, (x, a, b)).reverse_order(0)
Sum(-x, (x, b + 1, a - 1))
While one should prefer variable names when specifying which limits
to reverse, the index counting notation comes in handy in case there
are several symbols with the same name.
>>> S = Sum(x**2, (x, a, b), (x, c, d))
>>> S
Sum(x**2, (x, a, b), (x, c, d))
>>> S0 = S.reverse_order(0)
>>> S0
Sum(-x**2, (x, b + 1, a - 1), (x, c, d))
>>> S1 = S0.reverse_order(1)
>>> S1
Sum(x**2, (x, b + 1, a - 1), (x, d + 1, c - 1))
Of course we can mix both notations:
>>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1)
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
>>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x)
Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
See Also
========
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index, reorder_limit,
sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder
References
==========
.. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
Volume 28 Issue 2, April 1981, Pages 305-350
http://dl.acm.org/citation.cfm?doid=322248.322255
"""
l_indices = list(indices)
for i, indx in enumerate(l_indices):
if not isinstance(indx, int):
l_indices[i] = self.index(indx)
e = 1
limits = []
for i, limit in enumerate(self.limits):
l = limit
if i in l_indices:
e = -e
l = (limit[0], limit[2] + 1, limit[1] - 1)
limits.append(l)
return Sum(e * self.function, *limits)
def _eval_rewrite_as_Product(self, *args, **kwargs):
from sympy.concrete.products import Product
if self.function.is_extended_real:
return log(Product(exp(self.function), *self.limits))
def summation(f, *symbols, **kwargs):
r"""
Compute the summation of f with respect to symbols.
Explanation
===========
The notation for symbols is similar to the notation used in Integral.
summation(f, (i, a, b)) computes the sum of f with respect to i from a to b,
i.e.,
::
b
____
\ `
summation(f, (i, a, b)) = ) f
/___,
i = a
If it cannot compute the sum, it returns an unevaluated Sum object.
Repeated sums can be computed by introducing additional symbols tuples::
Examples
========
>>> from sympy import summation, oo, symbols, log
>>> i, n, m = symbols('i n m', integer=True)
>>> summation(2*i - 1, (i, 1, n))
n**2
>>> summation(1/2**i, (i, 0, oo))
2
>>> summation(1/log(n)**n, (n, 2, oo))
Sum(log(n)**(-n), (n, 2, oo))
>>> summation(i, (i, 0, n), (n, 0, m))
m**3/6 + m**2/2 + m/3
>>> from sympy.abc import x
>>> from sympy import factorial
>>> summation(x**n/factorial(n), (n, 0, oo))
exp(x)
See Also
========
Sum
Product, sympy.concrete.products.product
"""
return Sum(f, *symbols, **kwargs).doit(deep=False)
def telescopic_direct(L, R, n, limits):
"""
Returns the direct summation of the terms of a telescopic sum
Explanation
===========
L is the term with lower index
R is the term with higher index
n difference between the indexes of L and R
Examples
========
>>> from sympy.concrete.summations import telescopic_direct
>>> from sympy.abc import k, a, b
>>> telescopic_direct(1/k, -1/(k+2), 2, (k, a, b))
-1/(b + 2) - 1/(b + 1) + 1/(a + 1) + 1/a
"""
(i, a, b) = limits
s = 0
for m in range(n):
s += L.subs(i, a + m) + R.subs(i, b - m)
return s
def telescopic(L, R, limits):
'''
Tries to perform the summation using the telescopic property.
Return None if not possible.
'''
(i, a, b) = limits
if L.is_Add or R.is_Add:
return None
# We want to solve(L.subs(i, i + m) + R, m)
# First we try a simple match since this does things that
# solve doesn't do, e.g. solve(f(k+m)-f(k), m) fails
k = Wild("k")
sol = (-R).match(L.subs(i, i + k))
s = None
if sol and k in sol:
s = sol[k]
if not (s.is_Integer and L.subs(i, i + s) == -R):
# sometimes match fail(f(x+2).match(-f(x+k))->{k: -2 - 2x}))
s = None
# But there are things that match doesn't do that solve
# can do, e.g. determine that 1/(x + m) = 1/(1 - x) when m = 1
if s is None:
m = Dummy('m')
try:
sol = solve(L.subs(i, i + m) + R, m) or []
except NotImplementedError:
return None
sol = [si for si in sol if si.is_Integer and
(L.subs(i, i + si) + R).expand().is_zero]
if len(sol) != 1:
return None
s = sol[0]
if s < 0:
return telescopic_direct(R, L, abs(s), (i, a, b))
elif s > 0:
return telescopic_direct(L, R, s, (i, a, b))
def eval_sum(f, limits):
(i, a, b) = limits
if f.is_zero:
return S.Zero
if i not in f.free_symbols:
return f*(b - a + 1)
if a == b:
return f.subs(i, a)
if isinstance(f, Piecewise):
if not any(i in arg.args[1].free_symbols for arg in f.args):
# Piecewise conditions do not depend on the dummy summation variable,
# therefore we can fold: Sum(Piecewise((e, c), ...), limits)
# --> Piecewise((Sum(e, limits), c), ...)
newargs = []
for arg in f.args:
newexpr = eval_sum(arg.expr, limits)
if newexpr is None:
return None
newargs.append((newexpr, arg.cond))
return f.func(*newargs)
if f.has(KroneckerDelta):
from .delta import deltasummation, _has_simple_delta
f = f.replace(
lambda x: isinstance(x, Sum),
lambda x: x.factor()
)
if _has_simple_delta(f, limits[0]):
return deltasummation(f, limits)
dif = b - a
definite = dif.is_Integer
# Doing it directly may be faster if there are very few terms.
if definite and (dif < 100):
return eval_sum_direct(f, (i, a, b))
if isinstance(f, Piecewise):
return None
# Try to do it symbolically. Even when the number of terms is known,
# this can save time when b-a is big.
# We should try to transform to partial fractions
value = eval_sum_symbolic(f.expand(), (i, a, b))
if value is not None:
return value
# Do it directly
if definite:
return eval_sum_direct(f, (i, a, b))
def eval_sum_direct(expr, limits):
"""
Evaluate expression directly, but perform some simple checks first
to possibly result in a smaller expression and faster execution.
"""
(i, a, b) = limits
dif = b - a
# Linearity
if expr.is_Mul:
# Try factor out everything not including i
without_i, with_i = expr.as_independent(i)
if without_i != 1:
s = eval_sum_direct(with_i, (i, a, b))
if s:
r = without_i*s
if r is not S.NaN:
return r
else:
# Try term by term
L, R = expr.as_two_terms()
if not L.has(i):
sR = eval_sum_direct(R, (i, a, b))
if sR:
return L*sR
if not R.has(i):
sL = eval_sum_direct(L, (i, a, b))
if sL:
return sL*R
try:
expr = apart(expr, i) # see if it becomes an Add
except PolynomialError:
pass
if expr.is_Add:
# Try factor out everything not including i
without_i, with_i = expr.as_independent(i)
if without_i != 0:
s = eval_sum_direct(with_i, (i, a, b))
if s:
r = without_i*(dif + 1) + s
if r is not S.NaN:
return r
else:
# Try term by term
L, R = expr.as_two_terms()
lsum = eval_sum_direct(L, (i, a, b))
rsum = eval_sum_direct(R, (i, a, b))
if None not in (lsum, rsum):
r = lsum + rsum
if r is not S.NaN:
return r
return Add(*[expr.subs(i, a + j) for j in range(dif + 1)])
def eval_sum_symbolic(f, limits):
f_orig = f
(i, a, b) = limits
if not f.has(i):
return f*(b - a + 1)
# Linearity
if f.is_Mul:
# Try factor out everything not including i
without_i, with_i = f.as_independent(i)
if without_i != 1:
s = eval_sum_symbolic(with_i, (i, a, b))
if s:
r = without_i*s
if r is not S.NaN:
return r
else:
# Try term by term
L, R = f.as_two_terms()
if not L.has(i):
sR = eval_sum_symbolic(R, (i, a, b))
if sR:
return L*sR
if not R.has(i):
sL = eval_sum_symbolic(L, (i, a, b))
if sL:
return sL*R
try:
f = apart(f, i) # see if it becomes an Add
except PolynomialError:
pass
if f.is_Add:
L, R = f.as_two_terms()
lrsum = telescopic(L, R, (i, a, b))
if lrsum:
return lrsum
# Try factor out everything not including i
without_i, with_i = f.as_independent(i)
if without_i != 0:
s = eval_sum_symbolic(with_i, (i, a, b))
if s:
r = without_i*(b - a + 1) + s
if r is not S.NaN:
return r
else:
# Try term by term
lsum = eval_sum_symbolic(L, (i, a, b))
rsum = eval_sum_symbolic(R, (i, a, b))
if None not in (lsum, rsum):
r = lsum + rsum
if r is not S.NaN:
return r
# Polynomial terms with Faulhaber's formula
n = Wild('n')
result = f.match(i**n)
if result is not None:
n = result[n]
if n.is_Integer:
if n >= 0:
if (b is S.Infinity and a is not S.NegativeInfinity) or \
(a is S.NegativeInfinity and b is not S.Infinity):
return S.Infinity
return ((bernoulli(n + 1, b + 1) - bernoulli(n + 1, a))/(n + 1)).expand()
elif a.is_Integer and a >= 1:
if n == -1:
return harmonic(b) - harmonic(a - 1)
else:
return harmonic(b, abs(n)) - harmonic(a - 1, abs(n))
if not (a.has(S.Infinity, S.NegativeInfinity) or
b.has(S.Infinity, S.NegativeInfinity)):
# Geometric terms
c1 = Wild('c1', exclude=[i])
c2 = Wild('c2', exclude=[i])
c3 = Wild('c3', exclude=[i])
wexp = Wild('wexp')
# Here we first attempt powsimp on f for easier matching with the
# exponential pattern, and attempt expansion on the exponent for easier
# matching with the linear pattern.
e = f.powsimp().match(c1 ** wexp)
if e is not None:
e_exp = e.pop(wexp).expand().match(c2*i + c3)
if e_exp is not None:
e.update(e_exp)
p = (c1**c3).subs(e)
q = (c1**c2).subs(e)
r = p*(q**a - q**(b + 1))/(1 - q)
l = p*(b - a + 1)
return Piecewise((l, Eq(q, S.One)), (r, True))
r = gosper_sum(f, (i, a, b))
if isinstance(r, (Mul,Add)):
non_limit = r.free_symbols - Tuple(*limits[1:]).free_symbols
den = denom(together(r))
den_sym = non_limit & den.free_symbols
args = []
for v in ordered(den_sym):
try:
s = solve(den, v)
m = Eq(v, s[0]) if s else S.false
if m != False:
args.append((Sum(f_orig.subs(*m.args), limits).doit(), m))
break
except NotImplementedError:
continue
args.append((r, True))
return Piecewise(*args)
if r not in (None, S.NaN):
return r
h = eval_sum_hyper(f_orig, (i, a, b))
if h is not None:
return h
r = eval_sum_residue(f_orig, (i, a, b))
if r is not None:
return r
factored = f_orig.factor()
if factored != f_orig:
return eval_sum_symbolic(factored, (i, a, b))
def _eval_sum_hyper(f, i, a):
""" Returns (res, cond). Sums from a to oo. """
if a != 0:
return _eval_sum_hyper(f.subs(i, i + a), i, 0)
if f.subs(i, 0) == 0:
if simplify(f.subs(i, Dummy('i', integer=True, positive=True))) == 0:
return S.Zero, True
return _eval_sum_hyper(f.subs(i, i + 1), i, 0)
hs = hypersimp(f, i)
if hs is None:
return None
if isinstance(hs, Float):
hs = nsimplify(hs)
numer, denom = fraction(factor(hs))
top, topl = numer.as_coeff_mul(i)
bot, botl = denom.as_coeff_mul(i)
ab = [top, bot]
factors = [topl, botl]
params = [[], []]
for k in range(2):
for fac in factors[k]:
mul = 1
if fac.is_Pow:
mul = fac.exp
fac = fac.base
if not mul.is_Integer:
return None
p = Poly(fac, i)
if p.degree() != 1:
return None
m, n = p.all_coeffs()
ab[k] *= m**mul
params[k] += [n/m]*mul
# Add "1" to numerator parameters, to account for implicit n! in
# hypergeometric series.
ap = params[0] + [1]
bq = params[1]
x = ab[0]/ab[1]
h = hyper(ap, bq, x)
f = combsimp(f)
return f.subs(i, 0)*hyperexpand(h), h.convergence_statement
def eval_sum_hyper(f, i_a_b):
i, a, b = i_a_b
if (b - a).is_Integer:
# We are never going to do better than doing the sum in the obvious way
return None
old_sum = Sum(f, (i, a, b))
if b != S.Infinity:
if a is S.NegativeInfinity:
res = _eval_sum_hyper(f.subs(i, -i), i, -b)
if res is not None:
return Piecewise(res, (old_sum, True))
else:
res1 = _eval_sum_hyper(f, i, a)
res2 = _eval_sum_hyper(f, i, b + 1)
if res1 is None or res2 is None:
return None
(res1, cond1), (res2, cond2) = res1, res2
cond = And(cond1, cond2)
if cond == False:
return None
return Piecewise((res1 - res2, cond), (old_sum, True))
if a is S.NegativeInfinity:
res1 = _eval_sum_hyper(f.subs(i, -i), i, 1)
res2 = _eval_sum_hyper(f, i, 0)
if res1 is None or res2 is None:
return None
res1, cond1 = res1
res2, cond2 = res2
cond = And(cond1, cond2)
if cond == False or cond.as_set() == S.EmptySet:
return None
return Piecewise((res1 + res2, cond), (old_sum, True))
# Now b == oo, a != -oo
res = _eval_sum_hyper(f, i, a)
if res is not None:
r, c = res
if c == False:
if r.is_number:
f = f.subs(i, Dummy('i', integer=True, positive=True) + a)
if f.is_positive or f.is_zero:
return S.Infinity
elif f.is_negative:
return S.NegativeInfinity
return None
return Piecewise(res, (old_sum, True))
def eval_sum_residue(f, i_a_b):
r"""Compute the infinite summation with residues
Notes
=====
If $f(n), g(n)$ are polynomials with $\deg(g(n)) - \deg(f(n)) \ge 2$,
some infinite summations can be computed by the following residue
evaluations.
.. math::
\sum_{n=-\infty, g(n) \ne 0}^{\infty} \frac{f(n)}{g(n)} =
-\pi \sum_{\alpha|g(\alpha)=0}
\text{Res}(\cot(\pi x) \frac{f(x)}{g(x)}, \alpha)
.. math::
\sum_{n=-\infty, g(n) \ne 0}^{\infty} (-1)^n \frac{f(n)}{g(n)} =
-\pi \sum_{\alpha|g(\alpha)=0}
\text{Res}(\csc(\pi x) \frac{f(x)}{g(x)}, \alpha)
Examples
========
>>> from sympy import Sum, oo, Symbol
>>> x = Symbol('x')
Doubly infinite series of rational functions.
>>> Sum(1 / (x**2 + 1), (x, -oo, oo)).doit()
pi/tanh(pi)
Doubly infinite alternating series of rational functions.
>>> Sum((-1)**x / (x**2 + 1), (x, -oo, oo)).doit()
pi/sinh(pi)
Infinite series of even rational functions.
>>> Sum(1 / (x**2 + 1), (x, 0, oo)).doit()
1/2 + pi/(2*tanh(pi))
Infinite series of alternating even rational functions.
>>> Sum((-1)**x / (x**2 + 1), (x, 0, oo)).doit()
pi/(2*sinh(pi)) + 1/2
This also have heuristics to transform arbitrarily shifted summand or
arbitrarily shifted summation range to the canonical problem the
formula can handle.
>>> Sum(1 / (x**2 + 2*x + 2), (x, -1, oo)).doit()
1/2 + pi/(2*tanh(pi))
>>> Sum(1 / (x**2 + 4*x + 5), (x, -2, oo)).doit()
1/2 + pi/(2*tanh(pi))
>>> Sum(1 / (x**2 + 1), (x, 1, oo)).doit()
-1/2 + pi/(2*tanh(pi))
>>> Sum(1 / (x**2 + 1), (x, 2, oo)).doit()
-1 + pi/(2*tanh(pi))
References
==========
.. [#] http://www.supermath.info/InfiniteSeriesandtheResidueTheorem.pdf
.. [#] Asmar N.H., Grafakos L. (2018) Residue Theory.
In: Complex Analysis with Applications.
Undergraduate Texts in Mathematics. Springer, Cham.
https://doi.org/10.1007/978-3-319-94063-2_5
"""
i, a, b = i_a_b
def is_even_function(numer, denom):
"""Test if the rational function is an even function"""
numer_even = all(i % 2 == 0 for (i,) in numer.monoms())
denom_even = all(i % 2 == 0 for (i,) in denom.monoms())
numer_odd = all(i % 2 == 1 for (i,) in numer.monoms())
denom_odd = all(i % 2 == 1 for (i,) in denom.monoms())
return (numer_even and denom_even) or (numer_odd and denom_odd)
def match_rational(f, i):
numer, denom = f.as_numer_denom()
try:
(numer, denom), opt = parallel_poly_from_expr((numer, denom), i)
except (PolificationFailed, PolynomialError):
return None
return numer, denom
def get_poles(denom):
roots = denom.sqf_part().all_roots()
roots = sift(roots, lambda x: x.is_integer)
if None in roots:
return None
int_roots, nonint_roots = roots[True], roots[False]
return int_roots, nonint_roots
def get_shift(denom):
n = denom.degree(i)
a = denom.coeff_monomial(i**n)
b = denom.coeff_monomial(i**(n-1))
shift = - b / a / n
return shift
def get_residue_factor(numer, denom, alternating):
if not alternating:
residue_factor = (numer.as_expr() / denom.as_expr()) * cot(S.Pi * i)
else:
residue_factor = (numer.as_expr() / denom.as_expr()) * csc(S.Pi * i)
return residue_factor
# We don't know how to deal with symbolic constants in summand
if f.free_symbols - set([i]):
return None
if not (a.is_Integer or a in (S.Infinity, S.NegativeInfinity)):
return None
if not (b.is_Integer or b in (S.Infinity, S.NegativeInfinity)):
return None
# Quick exit heuristic for the sums which doesn't have infinite range
if a != S.NegativeInfinity and b != S.Infinity:
return None
match = match_rational(f, i)
if match:
alternating = False
numer, denom = match
else:
match = match_rational(f / S.NegativeOne**i, i)
if match:
alternating = True
numer, denom = match
else:
return None
if denom.degree(i) - numer.degree(i) < 2:
return None
if (a, b) == (S.NegativeInfinity, S.Infinity):
poles = get_poles(denom)
if poles is None:
return None
int_roots, nonint_roots = poles
if int_roots:
return None
residue_factor = get_residue_factor(numer, denom, alternating)
residues = [residue(residue_factor, i, root) for root in nonint_roots]
return -S.Pi * sum(residues)
if not (a.is_finite and b is S.Infinity):
return None
if not is_even_function(numer, denom):
# Try shifting summation and check if the summand can be made
# and even function from the origin.
# Sum(f(n), (n, a, b)) => Sum(f(n + s), (n, a - s, b - s))
shift = get_shift(denom)
if not shift.is_Integer:
return None
if shift == 0:
return None
numer = numer.shift(shift)
denom = denom.shift(shift)
if not is_even_function(numer, denom):
return None
if alternating:
f = S.NegativeOne**i * (S.NegativeOne**shift * numer.as_expr() / denom.as_expr())
else:
f = numer.as_expr() / denom.as_expr()
return eval_sum_residue(f, (i, a-shift, b-shift))
poles = get_poles(denom)
if poles is None:
return None
int_roots, nonint_roots = poles
if int_roots:
int_roots = [int(root) for root in int_roots]
int_roots_max = max(int_roots)
int_roots_min = min(int_roots)
# Integer valued poles must be next to each other
# and also symmetric from origin (Because the function is even)
if not len(int_roots) == int_roots_max - int_roots_min + 1:
return None
# Check whether the summation indices contain poles
if a <= max(int_roots):
return None
residue_factor = get_residue_factor(numer, denom, alternating)
residues = [residue(residue_factor, i, root) for root in int_roots + nonint_roots]
full_sum = -S.Pi * sum(residues)
if not int_roots:
# Compute Sum(f, (i, 0, oo)) by adding a extraneous evaluation
# at the origin.
half_sum = (full_sum + f.xreplace({i: 0})) / 2
# Add and subtract extraneous evaluations
extraneous_neg = [f.xreplace({i: i0}) for i0 in range(int(a), 0)]
extraneous_pos = [f.xreplace({i: i0}) for i0 in range(0, int(a))]
result = half_sum + sum(extraneous_neg) - sum(extraneous_pos)
return result
# Compute Sum(f, (i, min(poles) + 1, oo))
half_sum = full_sum / 2
# Subtract extraneous evaluations
extraneous = [f.xreplace({i: i0}) for i0 in range(max(int_roots) + 1, int(a))]
result = half_sum - sum(extraneous)
return result
def _eval_matrix_sum(expression):
f = expression.function
for n, limit in enumerate(expression.limits):
i, a, b = limit
dif = b - a
if dif.is_Integer:
if (dif < 0) == True:
a, b = b + 1, a - 1
f = -f
newf = eval_sum_direct(f, (i, a, b))
if newf is not None:
return newf.doit()
def _dummy_with_inherited_properties_concrete(limits):
"""
Return a Dummy symbol that inherits as many assumptions as possible
from the provided symbol and limits.
If the symbol already has all True assumption shared by the limits
then return None.
"""
x, a, b = limits
l = [a, b]
assumptions_to_consider = ['extended_nonnegative', 'nonnegative',
'extended_nonpositive', 'nonpositive',
'extended_positive', 'positive',
'extended_negative', 'negative',
'integer', 'rational', 'finite',
'zero', 'real', 'extended_real']
assumptions_to_keep = {}
assumptions_to_add = {}
for assum in assumptions_to_consider:
assum_true = x._assumptions.get(assum, None)
if assum_true:
assumptions_to_keep[assum] = True
elif all(getattr(i, 'is_' + assum) for i in l):
assumptions_to_add[assum] = True
if assumptions_to_add:
assumptions_to_keep.update(assumptions_to_add)
return Dummy('d', **assumptions_to_keep)
|
640c55b35137f10963960933086b6de1e44bb1a70a82b2c8d2136fa96dd502c7 | from sympy.core.basic import Basic
from sympy.core.cache import cacheit
from sympy.core.containers import Tuple
from sympy.core.decorators import call_highest_priority
from sympy.core.parameters import global_parameters
from sympy.core.function import AppliedUndef
from sympy.core.mul import Mul
from sympy.core.numbers import Integer
from sympy.core.relational import Eq
from sympy.core.singleton import S, Singleton
from sympy.core.sorting import ordered
from sympy.core.symbol import Dummy, Symbol, Wild
from sympy.core.sympify import sympify
from sympy.polys import lcm, factor
from sympy.sets.sets import Interval, Intersection
from sympy.simplify import simplify
from sympy.tensor.indexed import Idx
from sympy.utilities.iterables import flatten, is_sequence, iterable
from sympy.core.function import expand
###############################################################################
# SEQUENCES #
###############################################################################
class SeqBase(Basic):
"""Base class for sequences"""
is_commutative = True
_op_priority = 15
@staticmethod
def _start_key(expr):
"""Return start (if possible) else S.Infinity.
adapted from Set._infimum_key
"""
try:
start = expr.start
except (NotImplementedError,
AttributeError, ValueError):
start = S.Infinity
return start
def _intersect_interval(self, other):
"""Returns start and stop.
Takes intersection over the two intervals.
"""
interval = Intersection(self.interval, other.interval)
return interval.inf, interval.sup
@property
def gen(self):
"""Returns the generator for the sequence"""
raise NotImplementedError("(%s).gen" % self)
@property
def interval(self):
"""The interval on which the sequence is defined"""
raise NotImplementedError("(%s).interval" % self)
@property
def start(self):
"""The starting point of the sequence. This point is included"""
raise NotImplementedError("(%s).start" % self)
@property
def stop(self):
"""The ending point of the sequence. This point is included"""
raise NotImplementedError("(%s).stop" % self)
@property
def length(self):
"""Length of the sequence"""
raise NotImplementedError("(%s).length" % self)
@property
def variables(self):
"""Returns a tuple of variables that are bounded"""
return ()
@property
def free_symbols(self):
"""
This method returns the symbols in the object, excluding those
that take on a specific value (i.e. the dummy symbols).
Examples
========
>>> from sympy import SeqFormula
>>> from sympy.abc import n, m
>>> SeqFormula(m*n**2, (n, 0, 5)).free_symbols
{m}
"""
return ({j for i in self.args for j in i.free_symbols
.difference(self.variables)})
@cacheit
def coeff(self, pt):
"""Returns the coefficient at point pt"""
if pt < self.start or pt > self.stop:
raise IndexError("Index %s out of bounds %s" % (pt, self.interval))
return self._eval_coeff(pt)
def _eval_coeff(self, pt):
raise NotImplementedError("The _eval_coeff method should be added to"
"%s to return coefficient so it is available"
"when coeff calls it."
% self.func)
def _ith_point(self, i):
"""Returns the i'th point of a sequence.
Explanation
===========
If start point is negative infinity, point is returned from the end.
Assumes the first point to be indexed zero.
Examples
=========
>>> from sympy import oo
>>> from sympy.series.sequences import SeqPer
bounded
>>> SeqPer((1, 2, 3), (-10, 10))._ith_point(0)
-10
>>> SeqPer((1, 2, 3), (-10, 10))._ith_point(5)
-5
End is at infinity
>>> SeqPer((1, 2, 3), (0, oo))._ith_point(5)
5
Starts at negative infinity
>>> SeqPer((1, 2, 3), (-oo, 0))._ith_point(5)
-5
"""
if self.start is S.NegativeInfinity:
initial = self.stop
else:
initial = self.start
if self.start is S.NegativeInfinity:
step = -1
else:
step = 1
return initial + i*step
def _add(self, other):
"""
Should only be used internally.
Explanation
===========
self._add(other) returns a new, term-wise added sequence if self
knows how to add with other, otherwise it returns ``None``.
``other`` should only be a sequence object.
Used within :class:`SeqAdd` class.
"""
return None
def _mul(self, other):
"""
Should only be used internally.
Explanation
===========
self._mul(other) returns a new, term-wise multiplied sequence if self
knows how to multiply with other, otherwise it returns ``None``.
``other`` should only be a sequence object.
Used within :class:`SeqMul` class.
"""
return None
def coeff_mul(self, other):
"""
Should be used when ``other`` is not a sequence. Should be
defined to define custom behaviour.
Examples
========
>>> from sympy import SeqFormula
>>> from sympy.abc import n
>>> SeqFormula(n**2).coeff_mul(2)
SeqFormula(2*n**2, (n, 0, oo))
Notes
=====
'*' defines multiplication of sequences with sequences only.
"""
return Mul(self, other)
def __add__(self, other):
"""Returns the term-wise addition of 'self' and 'other'.
``other`` should be a sequence.
Examples
========
>>> from sympy import SeqFormula
>>> from sympy.abc import n
>>> SeqFormula(n**2) + SeqFormula(n**3)
SeqFormula(n**3 + n**2, (n, 0, oo))
"""
if not isinstance(other, SeqBase):
raise TypeError('cannot add sequence and %s' % type(other))
return SeqAdd(self, other)
@call_highest_priority('__add__')
def __radd__(self, other):
return self + other
def __sub__(self, other):
"""Returns the term-wise subtraction of ``self`` and ``other``.
``other`` should be a sequence.
Examples
========
>>> from sympy import SeqFormula
>>> from sympy.abc import n
>>> SeqFormula(n**2) - (SeqFormula(n))
SeqFormula(n**2 - n, (n, 0, oo))
"""
if not isinstance(other, SeqBase):
raise TypeError('cannot subtract sequence and %s' % type(other))
return SeqAdd(self, -other)
@call_highest_priority('__sub__')
def __rsub__(self, other):
return (-self) + other
def __neg__(self):
"""Negates the sequence.
Examples
========
>>> from sympy import SeqFormula
>>> from sympy.abc import n
>>> -SeqFormula(n**2)
SeqFormula(-n**2, (n, 0, oo))
"""
return self.coeff_mul(-1)
def __mul__(self, other):
"""Returns the term-wise multiplication of 'self' and 'other'.
``other`` should be a sequence. For ``other`` not being a
sequence see :func:`coeff_mul` method.
Examples
========
>>> from sympy import SeqFormula
>>> from sympy.abc import n
>>> SeqFormula(n**2) * (SeqFormula(n))
SeqFormula(n**3, (n, 0, oo))
"""
if not isinstance(other, SeqBase):
raise TypeError('cannot multiply sequence and %s' % type(other))
return SeqMul(self, other)
@call_highest_priority('__mul__')
def __rmul__(self, other):
return self * other
def __iter__(self):
for i in range(self.length):
pt = self._ith_point(i)
yield self.coeff(pt)
def __getitem__(self, index):
if isinstance(index, int):
index = self._ith_point(index)
return self.coeff(index)
elif isinstance(index, slice):
start, stop = index.start, index.stop
if start is None:
start = 0
if stop is None:
stop = self.length
return [self.coeff(self._ith_point(i)) for i in
range(start, stop, index.step or 1)]
def find_linear_recurrence(self,n,d=None,gfvar=None):
r"""
Finds the shortest linear recurrence that satisfies the first n
terms of sequence of order `\leq` ``n/2`` if possible.
If ``d`` is specified, find shortest linear recurrence of order
`\leq` min(d, n/2) if possible.
Returns list of coefficients ``[b(1), b(2), ...]`` corresponding to the
recurrence relation ``x(n) = b(1)*x(n-1) + b(2)*x(n-2) + ...``
Returns ``[]`` if no recurrence is found.
If gfvar is specified, also returns ordinary generating function as a
function of gfvar.
Examples
========
>>> from sympy import sequence, sqrt, oo, lucas
>>> from sympy.abc import n, x, y
>>> sequence(n**2).find_linear_recurrence(10, 2)
[]
>>> sequence(n**2).find_linear_recurrence(10)
[3, -3, 1]
>>> sequence(2**n).find_linear_recurrence(10)
[2]
>>> sequence(23*n**4+91*n**2).find_linear_recurrence(10)
[5, -10, 10, -5, 1]
>>> sequence(sqrt(5)*(((1 + sqrt(5))/2)**n - (-(1 + sqrt(5))/2)**(-n))/5).find_linear_recurrence(10)
[1, 1]
>>> sequence(x+y*(-2)**(-n), (n, 0, oo)).find_linear_recurrence(30)
[1/2, 1/2]
>>> sequence(3*5**n + 12).find_linear_recurrence(20,gfvar=x)
([6, -5], 3*(5 - 21*x)/((x - 1)*(5*x - 1)))
>>> sequence(lucas(n)).find_linear_recurrence(15,gfvar=x)
([1, 1], (x - 2)/(x**2 + x - 1))
"""
from sympy.matrices import Matrix
x = [simplify(expand(t)) for t in self[:n]]
lx = len(x)
if d is None:
r = lx//2
else:
r = min(d,lx//2)
coeffs = []
for l in range(1, r+1):
l2 = 2*l
mlist = []
for k in range(l):
mlist.append(x[k:k+l])
m = Matrix(mlist)
if m.det() != 0:
y = simplify(m.LUsolve(Matrix(x[l:l2])))
if lx == l2:
coeffs = flatten(y[::-1])
break
mlist = []
for k in range(l,lx-l):
mlist.append(x[k:k+l])
m = Matrix(mlist)
if m*y == Matrix(x[l2:]):
coeffs = flatten(y[::-1])
break
if gfvar is None:
return coeffs
else:
l = len(coeffs)
if l == 0:
return [], None
else:
n, d = x[l-1]*gfvar**(l-1), 1 - coeffs[l-1]*gfvar**l
for i in range(l-1):
n += x[i]*gfvar**i
for j in range(l-i-1):
n -= coeffs[i]*x[j]*gfvar**(i+j+1)
d -= coeffs[i]*gfvar**(i+1)
return coeffs, simplify(factor(n)/factor(d))
class EmptySequence(SeqBase, metaclass=Singleton):
"""Represents an empty sequence.
The empty sequence is also available as a singleton as
``S.EmptySequence``.
Examples
========
>>> from sympy import EmptySequence, SeqPer
>>> from sympy.abc import x
>>> EmptySequence
EmptySequence
>>> SeqPer((1, 2), (x, 0, 10)) + EmptySequence
SeqPer((1, 2), (x, 0, 10))
>>> SeqPer((1, 2)) * EmptySequence
EmptySequence
>>> EmptySequence.coeff_mul(-1)
EmptySequence
"""
@property
def interval(self):
return S.EmptySet
@property
def length(self):
return S.Zero
def coeff_mul(self, coeff):
"""See docstring of SeqBase.coeff_mul"""
return self
def __iter__(self):
return iter([])
class SeqExpr(SeqBase):
"""Sequence expression class.
Various sequences should inherit from this class.
Examples
========
>>> from sympy.series.sequences import SeqExpr
>>> from sympy.abc import x
>>> from sympy.core.containers import Tuple
>>> s = SeqExpr(Tuple(1, 2, 3), Tuple(x, 0, 10))
>>> s.gen
(1, 2, 3)
>>> s.interval
Interval(0, 10)
>>> s.length
11
See Also
========
sympy.series.sequences.SeqPer
sympy.series.sequences.SeqFormula
"""
@property
def gen(self):
return self.args[0]
@property
def interval(self):
return Interval(self.args[1][1], self.args[1][2])
@property
def start(self):
return self.interval.inf
@property
def stop(self):
return self.interval.sup
@property
def length(self):
return self.stop - self.start + 1
@property
def variables(self):
return (self.args[1][0],)
class SeqPer(SeqExpr):
"""
Represents a periodic sequence.
The elements are repeated after a given period.
Examples
========
>>> from sympy import SeqPer, oo
>>> from sympy.abc import k
>>> s = SeqPer((1, 2, 3), (0, 5))
>>> s.periodical
(1, 2, 3)
>>> s.period
3
For value at a particular point
>>> s.coeff(3)
1
supports slicing
>>> s[:]
[1, 2, 3, 1, 2, 3]
iterable
>>> list(s)
[1, 2, 3, 1, 2, 3]
sequence starts from negative infinity
>>> SeqPer((1, 2, 3), (-oo, 0))[0:6]
[1, 2, 3, 1, 2, 3]
Periodic formulas
>>> SeqPer((k, k**2, k**3), (k, 0, oo))[0:6]
[0, 1, 8, 3, 16, 125]
See Also
========
sympy.series.sequences.SeqFormula
"""
def __new__(cls, periodical, limits=None):
periodical = sympify(periodical)
def _find_x(periodical):
free = periodical.free_symbols
if len(periodical.free_symbols) == 1:
return free.pop()
else:
return Dummy('k')
x, start, stop = None, None, None
if limits is None:
x, start, stop = _find_x(periodical), 0, S.Infinity
if is_sequence(limits, Tuple):
if len(limits) == 3:
x, start, stop = limits
elif len(limits) == 2:
x = _find_x(periodical)
start, stop = limits
if not isinstance(x, (Symbol, Idx)) or start is None or stop is None:
raise ValueError('Invalid limits given: %s' % str(limits))
if start is S.NegativeInfinity and stop is S.Infinity:
raise ValueError("Both the start and end value"
"cannot be unbounded")
limits = sympify((x, start, stop))
if is_sequence(periodical, Tuple):
periodical = sympify(tuple(flatten(periodical)))
else:
raise ValueError("invalid period %s should be something "
"like e.g (1, 2) " % periodical)
if Interval(limits[1], limits[2]) is S.EmptySet:
return S.EmptySequence
return Basic.__new__(cls, periodical, limits)
@property
def period(self):
return len(self.gen)
@property
def periodical(self):
return self.gen
def _eval_coeff(self, pt):
if self.start is S.NegativeInfinity:
idx = (self.stop - pt) % self.period
else:
idx = (pt - self.start) % self.period
return self.periodical[idx].subs(self.variables[0], pt)
def _add(self, other):
"""See docstring of SeqBase._add"""
if isinstance(other, SeqPer):
per1, lper1 = self.periodical, self.period
per2, lper2 = other.periodical, other.period
per_length = lcm(lper1, lper2)
new_per = []
for x in range(per_length):
ele1 = per1[x % lper1]
ele2 = per2[x % lper2]
new_per.append(ele1 + ele2)
start, stop = self._intersect_interval(other)
return SeqPer(new_per, (self.variables[0], start, stop))
def _mul(self, other):
"""See docstring of SeqBase._mul"""
if isinstance(other, SeqPer):
per1, lper1 = self.periodical, self.period
per2, lper2 = other.periodical, other.period
per_length = lcm(lper1, lper2)
new_per = []
for x in range(per_length):
ele1 = per1[x % lper1]
ele2 = per2[x % lper2]
new_per.append(ele1 * ele2)
start, stop = self._intersect_interval(other)
return SeqPer(new_per, (self.variables[0], start, stop))
def coeff_mul(self, coeff):
"""See docstring of SeqBase.coeff_mul"""
coeff = sympify(coeff)
per = [x * coeff for x in self.periodical]
return SeqPer(per, self.args[1])
class SeqFormula(SeqExpr):
"""
Represents sequence based on a formula.
Elements are generated using a formula.
Examples
========
>>> from sympy import SeqFormula, oo, Symbol
>>> n = Symbol('n')
>>> s = SeqFormula(n**2, (n, 0, 5))
>>> s.formula
n**2
For value at a particular point
>>> s.coeff(3)
9
supports slicing
>>> s[:]
[0, 1, 4, 9, 16, 25]
iterable
>>> list(s)
[0, 1, 4, 9, 16, 25]
sequence starts from negative infinity
>>> SeqFormula(n**2, (-oo, 0))[0:6]
[0, 1, 4, 9, 16, 25]
See Also
========
sympy.series.sequences.SeqPer
"""
def __new__(cls, formula, limits=None):
formula = sympify(formula)
def _find_x(formula):
free = formula.free_symbols
if len(free) == 1:
return free.pop()
elif not free:
return Dummy('k')
else:
raise ValueError(
" specify dummy variables for %s. If the formula contains"
" more than one free symbol, a dummy variable should be"
" supplied explicitly e.g., SeqFormula(m*n**2, (n, 0, 5))"
% formula)
x, start, stop = None, None, None
if limits is None:
x, start, stop = _find_x(formula), 0, S.Infinity
if is_sequence(limits, Tuple):
if len(limits) == 3:
x, start, stop = limits
elif len(limits) == 2:
x = _find_x(formula)
start, stop = limits
if not isinstance(x, (Symbol, Idx)) or start is None or stop is None:
raise ValueError('Invalid limits given: %s' % str(limits))
if start is S.NegativeInfinity and stop is S.Infinity:
raise ValueError("Both the start and end value "
"cannot be unbounded")
limits = sympify((x, start, stop))
if Interval(limits[1], limits[2]) is S.EmptySet:
return S.EmptySequence
return Basic.__new__(cls, formula, limits)
@property
def formula(self):
return self.gen
def _eval_coeff(self, pt):
d = self.variables[0]
return self.formula.subs(d, pt)
def _add(self, other):
"""See docstring of SeqBase._add"""
if isinstance(other, SeqFormula):
form1, v1 = self.formula, self.variables[0]
form2, v2 = other.formula, other.variables[0]
formula = form1 + form2.subs(v2, v1)
start, stop = self._intersect_interval(other)
return SeqFormula(formula, (v1, start, stop))
def _mul(self, other):
"""See docstring of SeqBase._mul"""
if isinstance(other, SeqFormula):
form1, v1 = self.formula, self.variables[0]
form2, v2 = other.formula, other.variables[0]
formula = form1 * form2.subs(v2, v1)
start, stop = self._intersect_interval(other)
return SeqFormula(formula, (v1, start, stop))
def coeff_mul(self, coeff):
"""See docstring of SeqBase.coeff_mul"""
coeff = sympify(coeff)
formula = self.formula * coeff
return SeqFormula(formula, self.args[1])
def expand(self, *args, **kwargs):
return SeqFormula(expand(self.formula, *args, **kwargs), self.args[1])
class RecursiveSeq(SeqBase):
"""
A finite degree recursive sequence.
Explanation
===========
That is, a sequence a(n) that depends on a fixed, finite number of its
previous values. The general form is
a(n) = f(a(n - 1), a(n - 2), ..., a(n - d))
for some fixed, positive integer d, where f is some function defined by a
SymPy expression.
Parameters
==========
recurrence : SymPy expression defining recurrence
This is *not* an equality, only the expression that the nth term is
equal to. For example, if :code:`a(n) = f(a(n - 1), ..., a(n - d))`,
then the expression should be :code:`f(a(n - 1), ..., a(n - d))`.
yn : applied undefined function
Represents the nth term of the sequence as e.g. :code:`y(n)` where
:code:`y` is an undefined function and `n` is the sequence index.
n : symbolic argument
The name of the variable that the recurrence is in, e.g., :code:`n` if
the recurrence function is :code:`y(n)`.
initial : iterable with length equal to the degree of the recurrence
The initial values of the recurrence.
start : start value of sequence (inclusive)
Examples
========
>>> from sympy import Function, symbols
>>> from sympy.series.sequences import RecursiveSeq
>>> y = Function("y")
>>> n = symbols("n")
>>> fib = RecursiveSeq(y(n - 1) + y(n - 2), y(n), n, [0, 1])
>>> fib.coeff(3) # Value at a particular point
2
>>> fib[:6] # supports slicing
[0, 1, 1, 2, 3, 5]
>>> fib.recurrence # inspect recurrence
Eq(y(n), y(n - 2) + y(n - 1))
>>> fib.degree # automatically determine degree
2
>>> for x in zip(range(10), fib): # supports iteration
... print(x)
(0, 0)
(1, 1)
(2, 1)
(3, 2)
(4, 3)
(5, 5)
(6, 8)
(7, 13)
(8, 21)
(9, 34)
See Also
========
sympy.series.sequences.SeqFormula
"""
def __new__(cls, recurrence, yn, n, initial=None, start=0):
if not isinstance(yn, AppliedUndef):
raise TypeError("recurrence sequence must be an applied undefined function"
", found `{}`".format(yn))
if not isinstance(n, Basic) or not n.is_symbol:
raise TypeError("recurrence variable must be a symbol"
", found `{}`".format(n))
if yn.args != (n,):
raise TypeError("recurrence sequence does not match symbol")
y = yn.func
k = Wild("k", exclude=(n,))
degree = 0
# Find all applications of y in the recurrence and check that:
# 1. The function y is only being used with a single argument; and
# 2. All arguments are n + k for constant negative integers k.
prev_ys = recurrence.find(y)
for prev_y in prev_ys:
if len(prev_y.args) != 1:
raise TypeError("Recurrence should be in a single variable")
shift = prev_y.args[0].match(n + k)[k]
if not (shift.is_constant() and shift.is_integer and shift < 0):
raise TypeError("Recurrence should have constant,"
" negative, integer shifts"
" (found {})".format(prev_y))
if -shift > degree:
degree = -shift
if not initial:
initial = [Dummy("c_{}".format(k)) for k in range(degree)]
if len(initial) != degree:
raise ValueError("Number of initial terms must equal degree")
degree = Integer(degree)
start = sympify(start)
initial = Tuple(*(sympify(x) for x in initial))
seq = Basic.__new__(cls, recurrence, yn, n, initial, start)
seq.cache = {y(start + k): init for k, init in enumerate(initial)}
seq.degree = degree
return seq
@property
def _recurrence(self):
"""Equation defining recurrence."""
return self.args[0]
@property
def recurrence(self):
"""Equation defining recurrence."""
return Eq(self.yn, self.args[0])
@property
def yn(self):
"""Applied function representing the nth term"""
return self.args[1]
@property
def y(self):
"""Undefined function for the nth term of the sequence"""
return self.yn.func
@property
def n(self):
"""Sequence index symbol"""
return self.args[2]
@property
def initial(self):
"""The initial values of the sequence"""
return self.args[3]
@property
def start(self):
"""The starting point of the sequence. This point is included"""
return self.args[4]
@property
def stop(self):
"""The ending point of the sequence. (oo)"""
return S.Infinity
@property
def interval(self):
"""Interval on which sequence is defined."""
return (self.start, S.Infinity)
def _eval_coeff(self, index):
if index - self.start < len(self.cache):
return self.cache[self.y(index)]
for current in range(len(self.cache), index + 1):
# Use xreplace over subs for performance.
# See issue #10697.
seq_index = self.start + current
current_recurrence = self._recurrence.xreplace({self.n: seq_index})
new_term = current_recurrence.xreplace(self.cache)
self.cache[self.y(seq_index)] = new_term
return self.cache[self.y(self.start + current)]
def __iter__(self):
index = self.start
while True:
yield self._eval_coeff(index)
index += 1
def sequence(seq, limits=None):
"""
Returns appropriate sequence object.
Explanation
===========
If ``seq`` is a SymPy sequence, returns :class:`SeqPer` object
otherwise returns :class:`SeqFormula` object.
Examples
========
>>> from sympy import sequence
>>> from sympy.abc import n
>>> sequence(n**2, (n, 0, 5))
SeqFormula(n**2, (n, 0, 5))
>>> sequence((1, 2, 3), (n, 0, 5))
SeqPer((1, 2, 3), (n, 0, 5))
See Also
========
sympy.series.sequences.SeqPer
sympy.series.sequences.SeqFormula
"""
seq = sympify(seq)
if is_sequence(seq, Tuple):
return SeqPer(seq, limits)
else:
return SeqFormula(seq, limits)
###############################################################################
# OPERATIONS #
###############################################################################
class SeqExprOp(SeqBase):
"""
Base class for operations on sequences.
Examples
========
>>> from sympy.series.sequences import SeqExprOp, sequence
>>> from sympy.abc import n
>>> s1 = sequence(n**2, (n, 0, 10))
>>> s2 = sequence((1, 2, 3), (n, 5, 10))
>>> s = SeqExprOp(s1, s2)
>>> s.gen
(n**2, (1, 2, 3))
>>> s.interval
Interval(5, 10)
>>> s.length
6
See Also
========
sympy.series.sequences.SeqAdd
sympy.series.sequences.SeqMul
"""
@property
def gen(self):
"""Generator for the sequence.
returns a tuple of generators of all the argument sequences.
"""
return tuple(a.gen for a in self.args)
@property
def interval(self):
"""Sequence is defined on the intersection
of all the intervals of respective sequences
"""
return Intersection(*(a.interval for a in self.args))
@property
def start(self):
return self.interval.inf
@property
def stop(self):
return self.interval.sup
@property
def variables(self):
"""Cumulative of all the bound variables"""
return tuple(flatten([a.variables for a in self.args]))
@property
def length(self):
return self.stop - self.start + 1
class SeqAdd(SeqExprOp):
"""Represents term-wise addition of sequences.
Rules:
* The interval on which sequence is defined is the intersection
of respective intervals of sequences.
* Anything + :class:`EmptySequence` remains unchanged.
* Other rules are defined in ``_add`` methods of sequence classes.
Examples
========
>>> from sympy import EmptySequence, oo, SeqAdd, SeqPer, SeqFormula
>>> from sympy.abc import n
>>> SeqAdd(SeqPer((1, 2), (n, 0, oo)), EmptySequence)
SeqPer((1, 2), (n, 0, oo))
>>> SeqAdd(SeqPer((1, 2), (n, 0, 5)), SeqPer((1, 2), (n, 6, 10)))
EmptySequence
>>> SeqAdd(SeqPer((1, 2), (n, 0, oo)), SeqFormula(n**2, (n, 0, oo)))
SeqAdd(SeqFormula(n**2, (n, 0, oo)), SeqPer((1, 2), (n, 0, oo)))
>>> SeqAdd(SeqFormula(n**3), SeqFormula(n**2))
SeqFormula(n**3 + n**2, (n, 0, oo))
See Also
========
sympy.series.sequences.SeqMul
"""
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get('evaluate', global_parameters.evaluate)
# flatten inputs
args = list(args)
# adapted from sympy.sets.sets.Union
def _flatten(arg):
if isinstance(arg, SeqBase):
if isinstance(arg, SeqAdd):
return sum(map(_flatten, arg.args), [])
else:
return [arg]
if iterable(arg):
return sum(map(_flatten, arg), [])
raise TypeError("Input must be Sequences or "
" iterables of Sequences")
args = _flatten(args)
args = [a for a in args if a is not S.EmptySequence]
# Addition of no sequences is EmptySequence
if not args:
return S.EmptySequence
if Intersection(*(a.interval for a in args)) is S.EmptySet:
return S.EmptySequence
# reduce using known rules
if evaluate:
return SeqAdd.reduce(args)
args = list(ordered(args, SeqBase._start_key))
return Basic.__new__(cls, *args)
@staticmethod
def reduce(args):
"""Simplify :class:`SeqAdd` using known rules.
Iterates through all pairs and ask the constituent
sequences if they can simplify themselves with any other constituent.
Notes
=====
adapted from ``Union.reduce``
"""
new_args = True
while new_args:
for id1, s in enumerate(args):
new_args = False
for id2, t in enumerate(args):
if id1 == id2:
continue
new_seq = s._add(t)
# This returns None if s does not know how to add
# with t. Returns the newly added sequence otherwise
if new_seq is not None:
new_args = [a for a in args if a not in (s, t)]
new_args.append(new_seq)
break
if new_args:
args = new_args
break
if len(args) == 1:
return args.pop()
else:
return SeqAdd(args, evaluate=False)
def _eval_coeff(self, pt):
"""adds up the coefficients of all the sequences at point pt"""
return sum(a.coeff(pt) for a in self.args)
class SeqMul(SeqExprOp):
r"""Represents term-wise multiplication of sequences.
Explanation
===========
Handles multiplication of sequences only. For multiplication
with other objects see :func:`SeqBase.coeff_mul`.
Rules:
* The interval on which sequence is defined is the intersection
of respective intervals of sequences.
* Anything \* :class:`EmptySequence` returns :class:`EmptySequence`.
* Other rules are defined in ``_mul`` methods of sequence classes.
Examples
========
>>> from sympy import EmptySequence, oo, SeqMul, SeqPer, SeqFormula
>>> from sympy.abc import n
>>> SeqMul(SeqPer((1, 2), (n, 0, oo)), EmptySequence)
EmptySequence
>>> SeqMul(SeqPer((1, 2), (n, 0, 5)), SeqPer((1, 2), (n, 6, 10)))
EmptySequence
>>> SeqMul(SeqPer((1, 2), (n, 0, oo)), SeqFormula(n**2))
SeqMul(SeqFormula(n**2, (n, 0, oo)), SeqPer((1, 2), (n, 0, oo)))
>>> SeqMul(SeqFormula(n**3), SeqFormula(n**2))
SeqFormula(n**5, (n, 0, oo))
See Also
========
sympy.series.sequences.SeqAdd
"""
def __new__(cls, *args, **kwargs):
evaluate = kwargs.get('evaluate', global_parameters.evaluate)
# flatten inputs
args = list(args)
# adapted from sympy.sets.sets.Union
def _flatten(arg):
if isinstance(arg, SeqBase):
if isinstance(arg, SeqMul):
return sum(map(_flatten, arg.args), [])
else:
return [arg]
elif iterable(arg):
return sum(map(_flatten, arg), [])
raise TypeError("Input must be Sequences or "
" iterables of Sequences")
args = _flatten(args)
# Multiplication of no sequences is EmptySequence
if not args:
return S.EmptySequence
if Intersection(*(a.interval for a in args)) is S.EmptySet:
return S.EmptySequence
# reduce using known rules
if evaluate:
return SeqMul.reduce(args)
args = list(ordered(args, SeqBase._start_key))
return Basic.__new__(cls, *args)
@staticmethod
def reduce(args):
"""Simplify a :class:`SeqMul` using known rules.
Explanation
===========
Iterates through all pairs and ask the constituent
sequences if they can simplify themselves with any other constituent.
Notes
=====
adapted from ``Union.reduce``
"""
new_args = True
while new_args:
for id1, s in enumerate(args):
new_args = False
for id2, t in enumerate(args):
if id1 == id2:
continue
new_seq = s._mul(t)
# This returns None if s does not know how to multiply
# with t. Returns the newly multiplied sequence otherwise
if new_seq is not None:
new_args = [a for a in args if a not in (s, t)]
new_args.append(new_seq)
break
if new_args:
args = new_args
break
if len(args) == 1:
return args.pop()
else:
return SeqMul(args, evaluate=False)
def _eval_coeff(self, pt):
"""multiplies the coefficients of all the sequences at point pt"""
val = 1
for a in self.args:
val *= a.coeff(pt)
return val
|
306cc97e8dd7b75b38d42bc99f8e159a2c5c92650597a73bbc269c1296749cc3 | """Fourier Series"""
from sympy.core.numbers import (oo, pi)
from sympy.core.symbol import Wild
from sympy.core.expr import Expr
from sympy.core.add import Add
from sympy.core.containers import Tuple
from sympy.core.singleton import S
from sympy.core.symbol import Dummy, Symbol
from sympy.core.sympify import sympify
from sympy.functions.elementary.trigonometric import sin, cos, sinc
from sympy.series.series_class import SeriesBase
from sympy.series.sequences import SeqFormula
from sympy.sets.sets import Interval
from sympy.simplify.fu import TR2, TR1, TR10, sincos_to_sum
from sympy.utilities.iterables import is_sequence
def fourier_cos_seq(func, limits, n):
"""Returns the cos sequence in a Fourier series"""
from sympy.integrals import integrate
x, L = limits[0], limits[2] - limits[1]
cos_term = cos(2*n*pi*x / L)
formula = 2 * cos_term * integrate(func * cos_term, limits) / L
a0 = formula.subs(n, S.Zero) / 2
return a0, SeqFormula(2 * cos_term * integrate(func * cos_term, limits)
/ L, (n, 1, oo))
def fourier_sin_seq(func, limits, n):
"""Returns the sin sequence in a Fourier series"""
from sympy.integrals import integrate
x, L = limits[0], limits[2] - limits[1]
sin_term = sin(2*n*pi*x / L)
return SeqFormula(2 * sin_term * integrate(func * sin_term, limits)
/ L, (n, 1, oo))
def _process_limits(func, limits):
"""
Limits should be of the form (x, start, stop).
x should be a symbol. Both start and stop should be bounded.
Explanation
===========
* If x is not given, x is determined from func.
* If limits is None. Limit of the form (x, -pi, pi) is returned.
Examples
========
>>> from sympy.series.fourier import _process_limits as pari
>>> from sympy.abc import x
>>> pari(x**2, (x, -2, 2))
(x, -2, 2)
>>> pari(x**2, (-2, 2))
(x, -2, 2)
>>> pari(x**2, None)
(x, -pi, pi)
"""
def _find_x(func):
free = func.free_symbols
if len(free) == 1:
return free.pop()
elif not free:
return Dummy('k')
else:
raise ValueError(
" specify dummy variables for %s. If the function contains"
" more than one free symbol, a dummy variable should be"
" supplied explicitly e.g. FourierSeries(m*n**2, (n, -pi, pi))"
% func)
x, start, stop = None, None, None
if limits is None:
x, start, stop = _find_x(func), -pi, pi
if is_sequence(limits, Tuple):
if len(limits) == 3:
x, start, stop = limits
elif len(limits) == 2:
x = _find_x(func)
start, stop = limits
if not isinstance(x, Symbol) or start is None or stop is None:
raise ValueError('Invalid limits given: %s' % str(limits))
unbounded = [S.NegativeInfinity, S.Infinity]
if start in unbounded or stop in unbounded:
raise ValueError("Both the start and end value should be bounded")
return sympify((x, start, stop))
def finite_check(f, x, L):
def check_fx(exprs, x):
return x not in exprs.free_symbols
def check_sincos(_expr, x, L):
if isinstance(_expr, (sin, cos)):
sincos_args = _expr.args[0]
if sincos_args.match(a*(pi/L)*x + b) is not None:
return True
else:
return False
_expr = sincos_to_sum(TR2(TR1(f)))
add_coeff = _expr.as_coeff_add()
a = Wild('a', properties=[lambda k: k.is_Integer, lambda k: k != S.Zero, ])
b = Wild('b', properties=[lambda k: x not in k.free_symbols, ])
for s in add_coeff[1]:
mul_coeffs = s.as_coeff_mul()[1]
for t in mul_coeffs:
if not (check_fx(t, x) or check_sincos(t, x, L)):
return False, f
return True, _expr
class FourierSeries(SeriesBase):
r"""Represents Fourier sine/cosine series.
Explanation
===========
This class only represents a fourier series.
No computation is performed.
For how to compute Fourier series, see the :func:`fourier_series`
docstring.
See Also
========
sympy.series.fourier.fourier_series
"""
def __new__(cls, *args):
args = map(sympify, args)
return Expr.__new__(cls, *args)
@property
def function(self):
return self.args[0]
@property
def x(self):
return self.args[1][0]
@property
def period(self):
return (self.args[1][1], self.args[1][2])
@property
def a0(self):
return self.args[2][0]
@property
def an(self):
return self.args[2][1]
@property
def bn(self):
return self.args[2][2]
@property
def interval(self):
return Interval(0, oo)
@property
def start(self):
return self.interval.inf
@property
def stop(self):
return self.interval.sup
@property
def length(self):
return oo
@property
def L(self):
return abs(self.period[1] - self.period[0]) / 2
def _eval_subs(self, old, new):
x = self.x
if old.has(x):
return self
def truncate(self, n=3):
"""
Return the first n nonzero terms of the series.
If ``n`` is None return an iterator.
Parameters
==========
n : int or None
Amount of non-zero terms in approximation or None.
Returns
=======
Expr or iterator :
Approximation of function expanded into Fourier series.
Examples
========
>>> from sympy import fourier_series, pi
>>> from sympy.abc import x
>>> s = fourier_series(x, (x, -pi, pi))
>>> s.truncate(4)
2*sin(x) - sin(2*x) + 2*sin(3*x)/3 - sin(4*x)/2
See Also
========
sympy.series.fourier.FourierSeries.sigma_approximation
"""
if n is None:
return iter(self)
terms = []
for t in self:
if len(terms) == n:
break
if t is not S.Zero:
terms.append(t)
return Add(*terms)
def sigma_approximation(self, n=3):
r"""
Return :math:`\sigma`-approximation of Fourier series with respect
to order n.
Explanation
===========
Sigma approximation adjusts a Fourier summation to eliminate the Gibbs
phenomenon which would otherwise occur at discontinuities.
A sigma-approximated summation for a Fourier series of a T-periodical
function can be written as
.. math::
s(\theta) = \frac{1}{2} a_0 + \sum _{k=1}^{m-1}
\operatorname{sinc} \Bigl( \frac{k}{m} \Bigr) \cdot
\left[ a_k \cos \Bigl( \frac{2\pi k}{T} \theta \Bigr)
+ b_k \sin \Bigl( \frac{2\pi k}{T} \theta \Bigr) \right],
where :math:`a_0, a_k, b_k, k=1,\ldots,{m-1}` are standard Fourier
series coefficients and
:math:`\operatorname{sinc} \Bigl( \frac{k}{m} \Bigr)` is a Lanczos
:math:`\sigma` factor (expressed in terms of normalized
:math:`\operatorname{sinc}` function).
Parameters
==========
n : int
Highest order of the terms taken into account in approximation.
Returns
=======
Expr :
Sigma approximation of function expanded into Fourier series.
Examples
========
>>> from sympy import fourier_series, pi
>>> from sympy.abc import x
>>> s = fourier_series(x, (x, -pi, pi))
>>> s.sigma_approximation(4)
2*sin(x)*sinc(pi/4) - 2*sin(2*x)/pi + 2*sin(3*x)*sinc(3*pi/4)/3
See Also
========
sympy.series.fourier.FourierSeries.truncate
Notes
=====
The behaviour of
:meth:`~sympy.series.fourier.FourierSeries.sigma_approximation`
is different from :meth:`~sympy.series.fourier.FourierSeries.truncate`
- it takes all nonzero terms of degree smaller than n, rather than
first n nonzero ones.
References
==========
.. [1] https://en.wikipedia.org/wiki/Gibbs_phenomenon
.. [2] https://en.wikipedia.org/wiki/Sigma_approximation
"""
terms = [sinc(pi * i / n) * t for i, t in enumerate(self[:n])
if t is not S.Zero]
return Add(*terms)
def shift(self, s):
"""
Shift the function by a term independent of x.
Explanation
===========
f(x) -> f(x) + s
This is fast, if Fourier series of f(x) is already
computed.
Examples
========
>>> from sympy import fourier_series, pi
>>> from sympy.abc import x
>>> s = fourier_series(x**2, (x, -pi, pi))
>>> s.shift(1).truncate()
-4*cos(x) + cos(2*x) + 1 + pi**2/3
"""
s, x = sympify(s), self.x
if x in s.free_symbols:
raise ValueError("'%s' should be independent of %s" % (s, x))
a0 = self.a0 + s
sfunc = self.function + s
return self.func(sfunc, self.args[1], (a0, self.an, self.bn))
def shiftx(self, s):
"""
Shift x by a term independent of x.
Explanation
===========
f(x) -> f(x + s)
This is fast, if Fourier series of f(x) is already
computed.
Examples
========
>>> from sympy import fourier_series, pi
>>> from sympy.abc import x
>>> s = fourier_series(x**2, (x, -pi, pi))
>>> s.shiftx(1).truncate()
-4*cos(x + 1) + cos(2*x + 2) + pi**2/3
"""
s, x = sympify(s), self.x
if x in s.free_symbols:
raise ValueError("'%s' should be independent of %s" % (s, x))
an = self.an.subs(x, x + s)
bn = self.bn.subs(x, x + s)
sfunc = self.function.subs(x, x + s)
return self.func(sfunc, self.args[1], (self.a0, an, bn))
def scale(self, s):
"""
Scale the function by a term independent of x.
Explanation
===========
f(x) -> s * f(x)
This is fast, if Fourier series of f(x) is already
computed.
Examples
========
>>> from sympy import fourier_series, pi
>>> from sympy.abc import x
>>> s = fourier_series(x**2, (x, -pi, pi))
>>> s.scale(2).truncate()
-8*cos(x) + 2*cos(2*x) + 2*pi**2/3
"""
s, x = sympify(s), self.x
if x in s.free_symbols:
raise ValueError("'%s' should be independent of %s" % (s, x))
an = self.an.coeff_mul(s)
bn = self.bn.coeff_mul(s)
a0 = self.a0 * s
sfunc = self.args[0] * s
return self.func(sfunc, self.args[1], (a0, an, bn))
def scalex(self, s):
"""
Scale x by a term independent of x.
Explanation
===========
f(x) -> f(s*x)
This is fast, if Fourier series of f(x) is already
computed.
Examples
========
>>> from sympy import fourier_series, pi
>>> from sympy.abc import x
>>> s = fourier_series(x**2, (x, -pi, pi))
>>> s.scalex(2).truncate()
-4*cos(2*x) + cos(4*x) + pi**2/3
"""
s, x = sympify(s), self.x
if x in s.free_symbols:
raise ValueError("'%s' should be independent of %s" % (s, x))
an = self.an.subs(x, x * s)
bn = self.bn.subs(x, x * s)
sfunc = self.function.subs(x, x * s)
return self.func(sfunc, self.args[1], (self.a0, an, bn))
def _eval_as_leading_term(self, x, logx=None, cdir=0):
for t in self:
if t is not S.Zero:
return t
def _eval_term(self, pt):
if pt == 0:
return self.a0
return self.an.coeff(pt) + self.bn.coeff(pt)
def __neg__(self):
return self.scale(-1)
def __add__(self, other):
if isinstance(other, FourierSeries):
if self.period != other.period:
raise ValueError("Both the series should have same periods")
x, y = self.x, other.x
function = self.function + other.function.subs(y, x)
if self.x not in function.free_symbols:
return function
an = self.an + other.an
bn = self.bn + other.bn
a0 = self.a0 + other.a0
return self.func(function, self.args[1], (a0, an, bn))
return Add(self, other)
def __sub__(self, other):
return self.__add__(-other)
class FiniteFourierSeries(FourierSeries):
r"""Represents Finite Fourier sine/cosine series.
For how to compute Fourier series, see the :func:`fourier_series`
docstring.
Parameters
==========
f : Expr
Expression for finding fourier_series
limits : ( x, start, stop)
x is the independent variable for the expression f
(start, stop) is the period of the fourier series
exprs: (a0, an, bn) or Expr
a0 is the constant term a0 of the fourier series
an is a dictionary of coefficients of cos terms
an[k] = coefficient of cos(pi*(k/L)*x)
bn is a dictionary of coefficients of sin terms
bn[k] = coefficient of sin(pi*(k/L)*x)
or exprs can be an expression to be converted to fourier form
Methods
=======
This class is an extension of FourierSeries class.
Please refer to sympy.series.fourier.FourierSeries for
further information.
See Also
========
sympy.series.fourier.FourierSeries
sympy.series.fourier.fourier_series
"""
def __new__(cls, f, limits, exprs):
f = sympify(f)
limits = sympify(limits)
exprs = sympify(exprs)
if not (isinstance(exprs, Tuple) and len(exprs) == 3): # exprs is not of form (a0, an, bn)
# Converts the expression to fourier form
c, e = exprs.as_coeff_add()
rexpr = c + Add(*[TR10(i) for i in e])
a0, exp_ls = rexpr.expand(trig=False, power_base=False, power_exp=False, log=False).as_coeff_add()
x = limits[0]
L = abs(limits[2] - limits[1]) / 2
a = Wild('a', properties=[lambda k: k.is_Integer, lambda k: k is not S.Zero, ])
b = Wild('b', properties=[lambda k: x not in k.free_symbols, ])
an = dict()
bn = dict()
# separates the coefficients of sin and cos terms in dictionaries an, and bn
for p in exp_ls:
t = p.match(b * cos(a * (pi / L) * x))
q = p.match(b * sin(a * (pi / L) * x))
if t:
an[t[a]] = t[b] + an.get(t[a], S.Zero)
elif q:
bn[q[a]] = q[b] + bn.get(q[a], S.Zero)
else:
a0 += p
exprs = Tuple(a0, an, bn)
return Expr.__new__(cls, f, limits, exprs)
@property
def interval(self):
_length = 1 if self.a0 else 0
_length += max(set(self.an.keys()).union(set(self.bn.keys()))) + 1
return Interval(0, _length)
@property
def length(self):
return self.stop - self.start
def shiftx(self, s):
s, x = sympify(s), self.x
if x in s.free_symbols:
raise ValueError("'%s' should be independent of %s" % (s, x))
_expr = self.truncate().subs(x, x + s)
sfunc = self.function.subs(x, x + s)
return self.func(sfunc, self.args[1], _expr)
def scale(self, s):
s, x = sympify(s), self.x
if x in s.free_symbols:
raise ValueError("'%s' should be independent of %s" % (s, x))
_expr = self.truncate() * s
sfunc = self.function * s
return self.func(sfunc, self.args[1], _expr)
def scalex(self, s):
s, x = sympify(s), self.x
if x in s.free_symbols:
raise ValueError("'%s' should be independent of %s" % (s, x))
_expr = self.truncate().subs(x, x * s)
sfunc = self.function.subs(x, x * s)
return self.func(sfunc, self.args[1], _expr)
def _eval_term(self, pt):
if pt == 0:
return self.a0
_term = self.an.get(pt, S.Zero) * cos(pt * (pi / self.L) * self.x) \
+ self.bn.get(pt, S.Zero) * sin(pt * (pi / self.L) * self.x)
return _term
def __add__(self, other):
if isinstance(other, FourierSeries):
return other.__add__(fourier_series(self.function, self.args[1],\
finite=False))
elif isinstance(other, FiniteFourierSeries):
if self.period != other.period:
raise ValueError("Both the series should have same periods")
x, y = self.x, other.x
function = self.function + other.function.subs(y, x)
if self.x not in function.free_symbols:
return function
return fourier_series(function, limits=self.args[1])
def fourier_series(f, limits=None, finite=True):
r"""Computes the Fourier trigonometric series expansion.
Explanation
===========
Fourier trigonometric series of $f(x)$ over the interval $(a, b)$
is defined as:
.. math::
\frac{a_0}{2} + \sum_{n=1}^{\infty}
(a_n \cos(\frac{2n \pi x}{L}) + b_n \sin(\frac{2n \pi x}{L}))
where the coefficients are:
.. math::
L = b - a
.. math::
a_0 = \frac{2}{L} \int_{a}^{b}{f(x) dx}
.. math::
a_n = \frac{2}{L} \int_{a}^{b}{f(x) \cos(\frac{2n \pi x}{L}) dx}
.. math::
b_n = \frac{2}{L} \int_{a}^{b}{f(x) \sin(\frac{2n \pi x}{L}) dx}
The condition whether the function $f(x)$ given should be periodic
or not is more than necessary, because it is sufficient to consider
the series to be converging to $f(x)$ only in the given interval,
not throughout the whole real line.
This also brings a lot of ease for the computation because
you don't have to make $f(x)$ artificially periodic by
wrapping it with piecewise, modulo operations,
but you can shape the function to look like the desired periodic
function only in the interval $(a, b)$, and the computed series will
automatically become the series of the periodic version of $f(x)$.
This property is illustrated in the examples section below.
Parameters
==========
limits : (sym, start, end), optional
*sym* denotes the symbol the series is computed with respect to.
*start* and *end* denotes the start and the end of the interval
where the fourier series converges to the given function.
Default range is specified as $-\pi$ and $\pi$.
Returns
=======
FourierSeries
A symbolic object representing the Fourier trigonometric series.
Examples
========
Computing the Fourier series of $f(x) = x^2$:
>>> from sympy import fourier_series, pi
>>> from sympy.abc import x
>>> f = x**2
>>> s = fourier_series(f, (x, -pi, pi))
>>> s1 = s.truncate(n=3)
>>> s1
-4*cos(x) + cos(2*x) + pi**2/3
Shifting of the Fourier series:
>>> s.shift(1).truncate()
-4*cos(x) + cos(2*x) + 1 + pi**2/3
>>> s.shiftx(1).truncate()
-4*cos(x + 1) + cos(2*x + 2) + pi**2/3
Scaling of the Fourier series:
>>> s.scale(2).truncate()
-8*cos(x) + 2*cos(2*x) + 2*pi**2/3
>>> s.scalex(2).truncate()
-4*cos(2*x) + cos(4*x) + pi**2/3
Computing the Fourier series of $f(x) = x$:
This illustrates how truncating to the higher order gives better
convergence.
.. plot::
:context: reset
:format: doctest
:include-source: True
>>> from sympy import fourier_series, pi, plot
>>> from sympy.abc import x
>>> f = x
>>> s = fourier_series(f, (x, -pi, pi))
>>> s1 = s.truncate(n = 3)
>>> s2 = s.truncate(n = 5)
>>> s3 = s.truncate(n = 7)
>>> p = plot(f, s1, s2, s3, (x, -pi, pi), show=False, legend=True)
>>> p[0].line_color = (0, 0, 0)
>>> p[0].label = 'x'
>>> p[1].line_color = (0.7, 0.7, 0.7)
>>> p[1].label = 'n=3'
>>> p[2].line_color = (0.5, 0.5, 0.5)
>>> p[2].label = 'n=5'
>>> p[3].line_color = (0.3, 0.3, 0.3)
>>> p[3].label = 'n=7'
>>> p.show()
This illustrates how the series converges to different sawtooth
waves if the different ranges are specified.
.. plot::
:context: close-figs
:format: doctest
:include-source: True
>>> s1 = fourier_series(x, (x, -1, 1)).truncate(10)
>>> s2 = fourier_series(x, (x, -pi, pi)).truncate(10)
>>> s3 = fourier_series(x, (x, 0, 1)).truncate(10)
>>> p = plot(x, s1, s2, s3, (x, -5, 5), show=False, legend=True)
>>> p[0].line_color = (0, 0, 0)
>>> p[0].label = 'x'
>>> p[1].line_color = (0.7, 0.7, 0.7)
>>> p[1].label = '[-1, 1]'
>>> p[2].line_color = (0.5, 0.5, 0.5)
>>> p[2].label = '[-pi, pi]'
>>> p[3].line_color = (0.3, 0.3, 0.3)
>>> p[3].label = '[0, 1]'
>>> p.show()
Notes
=====
Computing Fourier series can be slow
due to the integration required in computing
an, bn.
It is faster to compute Fourier series of a function
by using shifting and scaling on an already
computed Fourier series rather than computing
again.
e.g. If the Fourier series of ``x**2`` is known
the Fourier series of ``x**2 - 1`` can be found by shifting by ``-1``.
See Also
========
sympy.series.fourier.FourierSeries
References
==========
.. [1] https://mathworld.wolfram.com/FourierSeries.html
"""
f = sympify(f)
limits = _process_limits(f, limits)
x = limits[0]
if x not in f.free_symbols:
return f
if finite:
L = abs(limits[2] - limits[1]) / 2
is_finite, res_f = finite_check(f, x, L)
if is_finite:
return FiniteFourierSeries(f, limits, res_f)
n = Dummy('n')
center = (limits[1] + limits[2]) / 2
if center.is_zero:
neg_f = f.subs(x, -x)
if f == neg_f:
a0, an = fourier_cos_seq(f, limits, n)
bn = SeqFormula(0, (1, oo))
return FourierSeries(f, limits, (a0, an, bn))
elif f == -neg_f:
a0 = S.Zero
an = SeqFormula(0, (1, oo))
bn = fourier_sin_seq(f, limits, n)
return FourierSeries(f, limits, (a0, an, bn))
a0, an = fourier_cos_seq(f, limits, n)
bn = fourier_sin_seq(f, limits, n)
return FourierSeries(f, limits, (a0, an, bn))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.