コード例 #1
0
ファイル: test_commonmatrix.py プロジェクト: JonB14/sympy
def test_echelon_form():
    # echelon form is not unique, but the result
    # must be row-equivalent to the original matrix
    # and it must be in echelon form.

    a = zeros_Reductions(3)
    e = eye_Reductions(3)

    # we can assume the zero matrix and the identity matrix shouldn't change
    assert a.echelon_form() == a
    assert e.echelon_form() == e

    a = ReductionsOnlyMatrix(0, 0, [])
    assert a.echelon_form() == a

    a = ReductionsOnlyMatrix(1, 1, [5])
    assert a.echelon_form() == a

    # now we get to the real tests

    def verify_row_null_space(mat, rows, nulls):
        for v in nulls:
            assert all(t.is_zero for t in a_echelon * v)
        for v in rows:
            if not all(t.is_zero for t in v):
                assert not all(t.is_zero for t in a_echelon * v.transpose())

    a = ReductionsOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
    nulls = [Matrix([[1], [-2], [1]])]
    rows = [a[i, :] for i in range(a.rows)]
    a_echelon = a.echelon_form()
    assert a_echelon.is_echelon
    verify_row_null_space(a, rows, nulls)

    a = ReductionsOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 8])
    nulls = []
    rows = [a[i, :] for i in range(a.rows)]
    a_echelon = a.echelon_form()
    assert a_echelon.is_echelon
    verify_row_null_space(a, rows, nulls)

    a = ReductionsOnlyMatrix(3, 3, [2, 1, 3, 0, 0, 0, 2, 1, 3])
    nulls = [Matrix([[-1 / 2], [1], [0]]), Matrix([[-3 / 2], [0], [1]])]
    rows = [a[i, :] for i in range(a.rows)]
    a_echelon = a.echelon_form()
    assert a_echelon.is_echelon
    verify_row_null_space(a, rows, nulls)

    # this one requires a row swap
    a = ReductionsOnlyMatrix(3, 3, [2, 1, 3, 0, 0, 0, 1, 1, 3])
    nulls = [Matrix([[0], [-3], [1]])]
    rows = [a[i, :] for i in range(a.rows)]
    a_echelon = a.echelon_form()
    assert a_echelon.is_echelon
    verify_row_null_space(a, rows, nulls)

    a = ReductionsOnlyMatrix(3, 3, [0, 3, 3, 0, 2, 2, 0, 1, 1])
    nulls = [Matrix([[1], [0], [0]]), Matrix([[0], [-1], [1]])]
    rows = [a[i, :] for i in range(a.rows)]
    a_echelon = a.echelon_form()
    assert a_echelon.is_echelon
    verify_row_null_space(a, rows, nulls)

    a = ReductionsOnlyMatrix(2, 3, [2, 2, 3, 3, 3, 0])
    nulls = [Matrix([[-1], [1], [0]])]
    rows = [a[i, :] for i in range(a.rows)]
    a_echelon = a.echelon_form()
    assert a_echelon.is_echelon
    verify_row_null_space(a, rows, nulls)
コード例 #2
0
    def __init__(self):
        # Create symbols for joint variables
        q1, q2, q3, q4, q5, q6, q7 = symbols('q1:8')  # theta_i
        theta = [q1, q2, q3, q4, q5, q6]
        d1, d2, d3, d4, d5, d6, d7 = symbols('d1:8')
        a0, a1, a2, a3, a4, a5, a6 = symbols('a0:7')
        alpha0, alpha1, alpha2, alpha3, alpha4, alpha5, alpha6 = symbols(
            'alpha0:7')

        # DH parameters
        s = {
            alpha0: 0,
            a0: 0,
            d1: 0.75,
            alpha1: -pi / 2,
            a1: 0.35,
            d2: 0,
            q2: q2 - pi / 2,
            alpha2: 0,
            a2: 1.25,
            d3: 0,
            alpha3: -pi / 2,
            a3: -0.054,
            d4: 1.50,
            alpha4: pi / 2,
            a4: 0,
            d5: 0,
            alpha5: -pi / 2,
            a5: 0,
            d6: 0,
            alpha6: 0,
            a6: 0,
            d7: 0.303,
            q7: 0
        }

        # Individual homogeneous transforms
        T0_1 = Matrix([[cos(q1), -sin(q1), 0, a0],
                       [
                           sin(q1) * cos(alpha0),
                           cos(q1) * cos(alpha0), -sin(alpha0),
                           -sin(alpha0) * d1
                       ],
                       [
                           sin(q1) * sin(alpha0),
                           cos(q1) * sin(alpha0),
                           cos(alpha0),
                           cos(alpha0) * d1
                       ], [0, 0, 0, 1]])
        T0_1 = T0_1.subs(s)
        T1_2 = Matrix([[cos(q2), -sin(q2), 0, a1],
                       [
                           sin(q2) * cos(alpha1),
                           cos(q2) * cos(alpha1), -sin(alpha1),
                           -sin(alpha1) * d2
                       ],
                       [
                           sin(q2) * sin(alpha1),
                           cos(q2) * sin(alpha1),
                           cos(alpha1),
                           cos(alpha1) * d2
                       ], [0, 0, 0, 1]])
        T1_2 = T1_2.subs(s)
        T2_3 = Matrix([[cos(q3), -sin(q3), 0, a2],
                       [
                           sin(q3) * cos(alpha2),
                           cos(q3) * cos(alpha2), -sin(alpha2),
                           -sin(alpha2) * d3
                       ],
                       [
                           sin(q3) * sin(alpha2),
                           cos(q3) * sin(alpha2),
                           cos(alpha2),
                           cos(alpha2) * d3
                       ], [0, 0, 0, 1]])
        T2_3 = T2_3.subs(s)
        T3_4 = Matrix([[cos(q4), -sin(q4), 0, a3],
                       [
                           sin(q4) * cos(alpha3),
                           cos(q4) * cos(alpha3), -sin(alpha3),
                           -sin(alpha3) * d4
                       ],
                       [
                           sin(q4) * sin(alpha3),
                           cos(q4) * sin(alpha3),
                           cos(alpha3),
                           cos(alpha3) * d4
                       ], [0, 0, 0, 1]])
        T3_4 = T3_4.subs(s)
        T4_5 = Matrix([[cos(q5), -sin(q5), 0, a4],
                       [
                           sin(q5) * cos(alpha4),
                           cos(q5) * cos(alpha4), -sin(alpha4),
                           -sin(alpha4) * d5
                       ],
                       [
                           sin(q5) * sin(alpha4),
                           cos(q5) * sin(alpha4),
                           cos(alpha4),
                           cos(alpha4) * d5
                       ], [0, 0, 0, 1]])
        T4_5 = T4_5.subs(s)
        T5_6 = Matrix([[cos(q6), -sin(q6), 0, a5],
                       [
                           sin(q6) * cos(alpha5),
                           cos(q6) * cos(alpha5), -sin(alpha5),
                           -sin(alpha5) * d6
                       ],
                       [
                           sin(q6) * sin(alpha5),
                           cos(q6) * sin(alpha5),
                           cos(alpha5),
                           cos(alpha5) * d6
                       ], [0, 0, 0, 1]])
        T5_6 = T5_6.subs(s)
        T6_G = Matrix([[cos(q7), -sin(q7), 0, a6],
                       [
                           sin(q7) * cos(alpha6),
                           cos(q7) * cos(alpha6), -sin(alpha6),
                           -sin(alpha6) * d7
                       ],
                       [
                           sin(q7) * sin(alpha6),
                           cos(q7) * sin(alpha6),
                           cos(alpha6),
                           cos(alpha6) * d7
                       ], [0, 0, 0, 1]])
        T6_G = T6_G.subs(s)

        # Correction needed to cccount of orientation difference between definition of
        # gripper_link in URDF versus DH convention
        R_z = Matrix([[cos(pi), -sin(pi), 0, 0], [sin(pi),
                                                  cos(pi), 0, 0], [0, 0, 1, 0],
                      [0, 0, 0, 1]])
        R_y = Matrix([[cos(-pi / 2), 0, sin(-pi / 2), 0], [0, 1, 0, 0],
                      [-sin(-pi / 2), 0, cos(-pi / 2), 0], [0, 0, 0, 1]])
        T_gripper_corr = R_z * R_y

        # Correction needed to account of position difference between definition of
        # joint_1, joint_4, and joint_6 in URDF versus DH convention
        T_1_corr = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, -0.42],
                           [0, 0, 0, 1]])
        T_4_corr = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, -0.54],
                           [0, 0, 0, 1]])
        T_6_corr = Matrix([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0.193],
                           [0, 0, 0, 1]])

        # Composition of Homogeneous Transforms
        T0_2 = simplify(T0_1 * T1_2)
        T0_3 = simplify(T0_2 * T2_3)
        T0_4 = simplify(T0_3 * T3_4)
        T0_5 = simplify(T0_4 * T4_5)
        T0_6 = simplify(T0_5 * T5_6)
        T0_G = simplify(T0_6 * T6_G)

        # Apply correction transforms
        T0_1 = simplify(T0_1 * T_1_corr)
        T0_4 = simplify(T0_4 * T_4_corr)
        T0_6 = simplify(T0_6 * T_6_corr)
        T0_G = simplify(T0_G * T_gripper_corr)

        # Use autowrap to compile and wrap a binary python function
        # The compiled binary can achieve better performance than SymPy’s .evalf()
        self.T0_1 = autowrap(T0_1, args=theta)
        self.T0_2 = autowrap(T0_2, args=theta)
        self.T0_3 = autowrap(T0_3, args=theta)
        self.T0_4 = autowrap(T0_4, args=theta)
        self.T0_5 = autowrap(T0_5, args=theta)
        self.T0_6 = autowrap(T0_6, args=theta)
        self.T0_G = autowrap(T0_G, args=theta)
コード例 #3
0
ファイル: dfp.py プロジェクト: kasymova/conjdirmethod
from sympy import symbols, diff
from sympy.abc import s
from sympy.matrices import Matrix, eye
from sympy.parsing.sympy_parser import parse_expr

ROUNDING_NUMBER = 3  # число знаков, до которого округлять (только при выводе, считает точно)

NUMBER_OF_VARS = 2  # число переменных
x_vars = symbols('x1:%d' % (NUMBER_OF_VARS + 1))  # создаем эти переменные

func = 'x1**2 + 2*x2**2 + x1*x2 - 7*x1 - 7*x2'  # исходная функция
func = parse_expr(func)

init_vector = [-1, 0]  # начальный вектор
init_vector = Matrix(init_vector)

EPS = 0.01  # погрешность


def gradient(f, p):
    return Matrix(
        [diff(f, x_vars[i]).subs({x_vars[i]: p[i] for i in range(NUMBER_OF_VARS)}) for i in range(NUMBER_OF_VARS)])


def rounding_vectors(vector):  # Функция для округления векторов (только при выводе)
    vector = list(vector.evalf())
    return [round(el, ROUNDING_NUMBER) for el in vector]


def f_s(point, f):  # функция для подстановки аргумента в одномерную функцию
コード例 #4
0
    a6: 0,
    d7: 0.303,
    q7: 0
}

t1 = int(round(time.time() * 1000)) - start
print("t1: %d  ms" % t1)

### Homogenous Transforms
# base_link to link_1
T0_1 = Matrix([[cos(q1), -sin(q1), 0, a0],
               [
                   sin(q1) * cos(alpha0),
                   cos(q1) * cos(alpha0), -sin(alpha0), -sin(alpha0) * d1
               ],
               [
                   sin(q1) * sin(alpha0),
                   cos(q1) * sin(alpha0),
                   cos(alpha0),
                   cos(alpha0) * d1
               ], [0, 0, 0, 1]])
T0_1 = T0_1.subs(s)
# link_1 to link_2
T1_2 = Matrix([[cos(q2), -sin(q2), 0, a1],
               [
                   sin(q2) * cos(alpha1),
                   cos(q2) * cos(alpha1), -sin(alpha1), -sin(alpha1) * d2
               ],
               [
                   sin(q2) * sin(alpha1),
                   cos(q2) * sin(alpha1),
コード例 #5
0
ファイル: test_matexpr.py プロジェクト: xrmx/sympy
def test_issue_2749():
    A = MatrixSymbol("A", 5, 2)
    assert (A.T * A).I.as_explicit() == Matrix([[(A.T * A).I[0, 0], (A.T * A).I[0, 1]], \
    [(A.T * A).I[1, 0], (A.T * A).I[1, 1]]])
コード例 #6
0
def test_QR_trivial():
    # Rank deficient matrices
    A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    Q, R = A.QRdecomposition()
    assert Q.T * Q == eye(Q.cols)
    assert R.is_upper
    assert A == Q * R

    A = Matrix([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]])
    Q, R = A.QRdecomposition()
    assert Q.T * Q == eye(Q.cols)
    assert R.is_upper
    assert A == Q * R

    A = Matrix([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]).T
    Q, R = A.QRdecomposition()
    assert Q.T * Q == eye(Q.cols)
    assert R.is_upper
    assert A == Q * R

    # Zero rank matrices
    A = Matrix([[0, 0, 0]])
    Q, R = A.QRdecomposition()
    assert Q.T * Q == eye(Q.cols)
    assert R.is_upper
    assert A == Q * R

    A = Matrix([[0, 0, 0]]).T
    Q, R = A.QRdecomposition()
    assert Q.T * Q == eye(Q.cols)
    assert R.is_upper
    assert A == Q * R

    A = Matrix([[0, 0, 0], [0, 0, 0]])
    Q, R = A.QRdecomposition()
    assert Q.T * Q == eye(Q.cols)
    assert R.is_upper
    assert A == Q * R

    A = Matrix([[0, 0, 0], [0, 0, 0]]).T
    Q, R = A.QRdecomposition()
    assert Q.T * Q == eye(Q.cols)
    assert R.is_upper
    assert A == Q * R

    # Rank deficient matrices with zero norm from beginning columns
    A = Matrix([[0, 0, 0], [1, 2, 3]]).T
    Q, R = A.QRdecomposition()
    assert Q.T * Q == eye(Q.cols)
    assert R.is_upper
    assert A == Q * R

    A = Matrix([[0, 0, 0, 0], [1, 2, 3, 4], [0, 0, 0, 0]]).T
    Q, R = A.QRdecomposition()
    assert Q.T * Q == eye(Q.cols)
    assert R.is_upper
    assert A == Q * R

    A = Matrix([[0, 0, 0, 0], [1, 2, 3, 4], [0, 0, 0, 0], [2, 4, 6, 8]]).T
    Q, R = A.QRdecomposition()
    assert Q.T * Q == eye(Q.cols)
    assert R.is_upper
    assert A == Q * R

    A = Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 2, 3]]).T
    Q, R = A.QRdecomposition()
    assert Q.T * Q == eye(Q.cols)
    assert R.is_upper
    assert A == Q * R
コード例 #7
0
def test_LUdecomp():
    testmat = Matrix([[0, 2, 5, 3], [3, 3, 7, 4], [8, 4, 0, 2], [-2, 6, 3, 4]])
    L, U, p = testmat.LUdecomposition()
    assert L.is_lower
    assert U.is_upper
    assert (L * U).permute_rows(p, 'backward') - testmat == zeros(4)

    testmat = Matrix([[6, -2, 7, 4], [0, 3, 6, 7], [1, -2, 7, 4],
                      [-9, 2, 6, 3]])
    L, U, p = testmat.LUdecomposition()
    assert L.is_lower
    assert U.is_upper
    assert (L * U).permute_rows(p, 'backward') - testmat == zeros(4)

    # non-square
    testmat = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
    L, U, p = testmat.LUdecomposition(rankcheck=False)
    assert L.is_lower
    assert U.is_upper
    assert (L * U).permute_rows(p, 'backward') - testmat == zeros(4, 3)

    # square and singular
    testmat = Matrix([[1, 2, 3], [2, 4, 6], [4, 5, 6]])
    L, U, p = testmat.LUdecomposition(rankcheck=False)
    assert L.is_lower
    assert U.is_upper
    assert (L * U).permute_rows(p, 'backward') - testmat == zeros(3)

    M = Matrix(((1, x, 1), (2, y, 0), (y, 0, z)))
    L, U, p = M.LUdecomposition()
    assert L.is_lower
    assert U.is_upper
    assert (L * U).permute_rows(p, 'backward') - M == zeros(3)

    mL = Matrix((
        (1, 0, 0),
        (2, 3, 0),
    ))
    assert mL.is_lower is True
    assert mL.is_upper is False
    mU = Matrix((
        (1, 2, 3),
        (0, 4, 5),
    ))
    assert mU.is_lower is False
    assert mU.is_upper is True

    # test FF LUdecomp
    M = Matrix([[1, 3, 3], [3, 2, 6], [3, 2, 2]])
    P, L, Dee, U = M.LUdecompositionFF()
    assert P * M == L * Dee.inv() * U

    M = Matrix([[1, 2, 3, 4], [3, -1, 2, 3], [3, 1, 3, -2], [6, -1, 0, 2]])
    P, L, Dee, U = M.LUdecompositionFF()
    assert P * M == L * Dee.inv() * U

    M = Matrix([[0, 0, 1], [2, 3, 0], [3, 1, 4]])
    P, L, Dee, U = M.LUdecompositionFF()
    assert P * M == L * Dee.inv() * U

    # issue 15794
    M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    raises(ValueError, lambda: M.LUdecomposition_Simple(rankcheck=True))
コード例 #8
0
ファイル: test_lambdify.py プロジェクト: varunjha089/sympy
def test_lambdify_cse():
    def dummy_cse(exprs):
        return (), exprs

    def minmem(exprs):
        from sympy.simplify.cse_main import cse_release_variables, cse
        return cse(exprs, postprocess=cse_release_variables)

    class Case:
        def __init__(self, *, args, exprs, num_args, requires_numpy=False):
            self.args = args
            self.exprs = exprs
            self.num_args = num_args
            subs_dict = dict(zip(self.args, self.num_args))
            self.ref = [e.subs(subs_dict).evalf() for e in exprs]
            self.requires_numpy = requires_numpy

        def lambdify(self, *, cse):
            return lambdify(self.args, self.exprs, cse=cse)

        def assertAllClose(self, result, *, abstol=1e-15, reltol=1e-15):
            if self.requires_numpy:
                assert all(
                    numpy.allclose(result[i],
                                   numpy.asarray(r, dtype=float),
                                   rtol=reltol,
                                   atol=abstol)
                    for i, r in enumerate(self.ref))
                return

            for i, r in enumerate(self.ref):
                abs_err = abs(result[i] - r)
                if r == 0:
                    assert abs_err < abstol
                else:
                    assert abs_err / abs(r) < reltol

    cases = [
        Case(args=(x, y, z),
             exprs=[
                 x + y + z,
                 x + y - z,
                 2 * x + 2 * y - z,
                 (x + y)**2 + (y + z)**2,
             ],
             num_args=(2., 3., 4.)),
        Case(args=(x, y, z),
             exprs=[
                 x + sympy.Heaviside(x), y + sympy.Heaviside(x),
                 z + sympy.Heaviside(x, 1), z / sympy.Heaviside(x, 1)
             ],
             num_args=(0., 3., 4.)),
        Case(args=(x, y, z),
             exprs=[x + sinc(y), y + sinc(y), z - sinc(y)],
             num_args=(0.1, 0.2, 0.3)),
        Case(args=(x, y, z),
             exprs=[
                 Matrix([[x, x * y], [sin(z) + 4, x**z]]),
                 x * y + sin(z) - x**z,
                 Matrix([x * x, sin(z), x**z])
             ],
             num_args=(1., 2., 3.),
             requires_numpy=True),
        Case(args=(x, y),
             exprs=[(x + y - 1)**2,
                    x, x + y, (x + y) / (2 * x + 1) + (x + y - 1)**2,
                    (2 * x + 1)**(x + y)],
             num_args=(1, 2))
    ]
    for case in cases:
        if not numpy and case.requires_numpy:
            continue
        for cse in [False, True, minmem, dummy_cse]:
            f = case.lambdify(cse=cse)
            result = f(*case.num_args)
            case.assertAllClose(result)
コード例 #9
0
ファイル: test_lambdify.py プロジェクト: varunjha089/sympy
def test_numpy_transpose():
    if not numpy:
        skip("numpy not installed.")
    A = Matrix([[1, x], [0, 1]])
    f = lambdify((x), A.T, modules="numpy")
    numpy.testing.assert_array_equal(f(2), numpy.array([[1, 0], [2, 1]]))
コード例 #10
0
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 = Rational(1, 2)
    p1 = Point(x1, x2)
    p2 = Point(y1, y2)
    p3 = Point(0, 0)
    p4 = Point(1, 1)
    p5 = Point(0, 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 p4 * 5 == Point(5, 5)
    assert -p2 == Point(-y1, -y2)
    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 Point.distance(p3, p4) == sqrt(2)
    assert Point.distance(p1, p1) == 0
    assert Point.distance(p3, p2) == sqrt(p2.x**2 + p2.y**2)

    assert Point.taxicab_distance(p4, p3) == 2

    assert Point.canberra_distance(p4, p5) == 1

    p1_1 = Point(x1, x1)
    p1_2 = Point(y2, y2)
    p1_3 = Point(x1 + 1, x1)
    assert Point.is_collinear(p3)

    with warnings.catch_warnings(record=True) as w:
        assert Point.is_collinear(p3, Point(p3, dim=4))
        assert len(w) == 1
    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
    line = Line(Point(1, 0), slope=1)
    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) == []

    x_pos = Symbol('x', real=True, positive=True)
    p2_1 = Point(x_pos, 0)
    p2_2 = Point(0, x_pos)
    p2_3 = Point(-x_pos, 0)
    p2_4 = Point(0, -x_pos)
    p2_5 = Point(x_pos, 5)
    assert Point.is_concyclic(p2_1)
    assert Point.is_concyclic(p2_1, p2_2)
    assert Point.is_concyclic(p2_1, p2_2, p2_3, p2_4)
    for pts in permutations((p2_1, p2_2, p2_3, p2_5)):
        assert Point.is_concyclic(*pts) is False
    assert Point.is_concyclic(p4, p4 * 2, p4 * 3) is False
    assert Point(0, 0).is_concyclic((1, 1), (2, 2), (2, 1)) is False

    assert 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)

    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 = Rational(1, 2), Rational(1, 3)
    assert Point(a, b).evalf(2) == \
        Point(a.n(2), b.n(2))
    raises(ValueError, lambda: Point(1, 2) + 1)

    # 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]])))
コード例 #11
0
def test_PermutationMatrix_basic():
    p = Permutation([1, 0])
    assert unchanged(PermutationMatrix, p)
    raises(ValueError, lambda: PermutationMatrix((0, 1, 2)))
    assert PermutationMatrix(p).as_explicit() == Matrix([[0, 1], [1, 0]])
    assert isinstance(PermutationMatrix(p) * MatrixSymbol("A", 2, 2), MatMul)
コード例 #12
0
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 = Rational(1, 2)
    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 p4 * 5 == Point3D(5, 5, 5)
    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)

    raises(ValueError, lambda: Point3D(0, 0, 0) + 10)

    # 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 = Rational(1, 2), Rational(1, 3)
    assert Point(a, b).evalf(2) == \
        Point(a.n(2), b.n(2))
    raises(ValueError, lambda: Point(1, 2) + 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 warnings.catch_warnings(record=True) as w:
        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 warnings.catch_warnings(record=True) as w:
        assert p - p_4d == Point(1, 1, 1, -1)
        assert len(w) == 1
    p_4d3d = Point(0, 0, 1, 0)
    with warnings.catch_warnings(record=True) as w:
        assert p - p_4d3d == Point(1, 1, 0, 0)
        assert len(w) == 1
コード例 #13
0
    F3D, dzeta3D, u3D, rho

from SymbolicCollisions.core.cm_symbols import rho, moments_dict
import time

lattice = 'D2Q9'
ccmt = ContinuousCMTransforms(dzeta3D, u3D, F3D, rho)

start = time.process_time()

print('\n\n// === continous cm === \n ')

# to calculate particular moment
row = moments_dict['D2Q9'][0]
moment = ccmt.get_cm(row, ccmt.get_Maxwellian_DF)
print_as_vector(Matrix([moment]), 'particular_moment')

print('\n//Force -> Force_cm - from continous definition: \n'
      'k_mn = integrate(fun, (x, -oo, oo), (y, -oo, oo)) \n'
      'where fun = forceM(rho,u,x,y) *(x-ux)^m *(y-uy)^n *(z-uz)^o ')
F_cm = get_mom_vector_from_continuous_def(
    ccmt.get_force_He_MB,
    continuous_transformation=ccmt.get_cm,
    moments_order=moments_dict[lattice])
print_as_vector(F_cm, 'F_cm')

print('\n//population_eq -> cm_eq - from continous definition: \n'
      'k_mn = integrate(fun, (x, -oo, oo), (y, -oo, oo)) \n'
      'where fun = fM(rho,u,x,y) *(x-ux)^m *(y-uy)^n *(z-uz)^o ')
cm_eq = get_mom_vector_from_continuous_def(
    ccmt.get_Maxwellian_DF,
コード例 #14
0
ファイル: test_sparse.py プロジェクト: zohamid/sympy
def test_sparse_matrix():
    def sparse_eye(n):
        return SparseMatrix.eye(n)

    def sparse_zeros(n):
        return SparseMatrix.zeros(n)

    # creation args
    raises(TypeError, lambda: SparseMatrix(1, 2))

    a = SparseMatrix(((1, 0), (0, 1)))
    assert SparseMatrix(a) == a

    from sympy.matrices import MutableSparseMatrix, MutableDenseMatrix
    a = MutableSparseMatrix([])
    b = MutableDenseMatrix([1, 2])
    assert a.row_join(b) == b
    assert a.col_join(b) == b
    assert type(a.row_join(b)) == type(a)
    assert type(a.col_join(b)) == type(a)

    # test element assignment
    a = SparseMatrix(((1, 0), (0, 1)))

    a[3] = 4
    assert a[1, 1] == 4
    a[3] = 1

    a[0, 0] = 2
    assert a == SparseMatrix(((2, 0), (0, 1)))
    a[1, 0] = 5
    assert a == SparseMatrix(((2, 0), (5, 1)))
    a[1, 1] = 0
    assert a == SparseMatrix(((2, 0), (5, 0)))
    assert a._smat == {(0, 0): 2, (1, 0): 5}

    # test_multiplication
    a = SparseMatrix((
        (1, 2),
        (3, 1),
        (0, 6),
    ))

    b = SparseMatrix((
        (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

    x = Symbol("x")

    c = b * Symbol("x")
    assert isinstance(c, SparseMatrix)
    assert c[0, 0] == x
    assert c[0, 1] == 2 * x
    assert c[1, 0] == 3 * x
    assert c[1, 1] == 0

    c = 5 * b
    assert isinstance(c, SparseMatrix)
    assert c[0, 0] == 5
    assert c[0, 1] == 2 * 5
    assert c[1, 0] == 3 * 5
    assert c[1, 1] == 0

    #test_power
    A = SparseMatrix([[2, 3], [4, 5]])
    assert (A**5)[:] == [6140, 8097, 10796, 14237]
    A = SparseMatrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
    assert (A**3)[:] == [290, 262, 251, 448, 440, 368, 702, 954, 433]

    # test_creation
    x = Symbol("x")
    a = SparseMatrix([[x, 0], [0, 0]])
    m = a
    assert m.cols == m.rows
    assert m.cols == 2
    assert m[:] == [x, 0, 0, 0]
    b = SparseMatrix(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
    S = sparse_eye(3)
    S.row_del(1)
    assert S == SparseMatrix([[1, 0, 0], [0, 0, 1]])
    S = sparse_eye(3)
    S.col_del(1)
    assert S == SparseMatrix([[1, 0], [0, 0], [0, 1]])
    S = SparseMatrix.eye(3)
    S[2, 1] = 2
    S.col_swap(1, 0)
    assert S == SparseMatrix([[0, 1, 0], [1, 0, 0], [2, 0, 1]])

    a = SparseMatrix(1, 2, [1, 2])
    b = a.copy()
    c = a.copy()
    assert a[0] == 1
    a.row_del(0)
    assert a == SparseMatrix(0, 2, [])
    b.col_del(1)
    assert b == SparseMatrix(1, 1, [1])

    # test_determinant
    x, y = Symbol('x'), Symbol('y')

    assert SparseMatrix(1, 1, [0]).det() == 0

    assert SparseMatrix([[1]]).det() == 1

    assert SparseMatrix(((-3, 2), (8, -5))).det() == -1

    assert SparseMatrix(((x, 1), (y, 2 * y))).det() == 2 * x * y - y

    assert SparseMatrix(((1, 1, 1), (1, 2, 3), (1, 3, 6))).det() == 1

    assert SparseMatrix(((3, -2, 0, 5), (-2, 1, -2, 2), (0, -2, 5, 0),
                         (5, 0, 3, 4))).det() == -289

    assert SparseMatrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12),
                         (13, 14, 15, 16))).det() == 0

    assert SparseMatrix(((3, 2, 0, 0, 0), (0, 3, 2, 0, 0), (0, 0, 3, 2, 0),
                         (0, 0, 0, 3, 2), (2, 0, 0, 0, 3))).det() == 275

    assert SparseMatrix(((1, 0, 1, 2, 12), (2, 0, 1, 1, 4), (2, 1, 1, -1, 3),
                         (3, 2, -1, 1, 8), (1, 1, 1, 0, 6))).det() == -55

    assert SparseMatrix(((-5, 2, 3, 4, 5), (1, -4, 3, 4, 5), (1, 2, -3, 4, 5),
                         (1, 2, 3, -2, 5), (1, 2, 3, 4, -1))).det() == 11664

    assert SparseMatrix(((2, 7, -1, 3, 2), (0, 0, 1, 0, 1), (-2, 0, 7, 0, 2),
                         (-3, -2, 4, 5, 3), (1, 0, 0, 0, 1))).det() == 123

    # test_slicing
    m0 = sparse_eye(4)
    assert m0[:3, :3] == sparse_eye(3)
    assert m0[2:4, 0:2] == sparse_zeros(2)

    m1 = SparseMatrix(3, 3, lambda i, j: i + j)
    assert m1[0, :] == SparseMatrix(1, 3, (0, 1, 2))
    assert m1[1:3, 1] == SparseMatrix(2, 1, (2, 3))

    m2 = SparseMatrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11],
                       [12, 13, 14, 15]])
    assert m2[:, -1] == SparseMatrix(4, 1, [3, 7, 11, 15])
    assert m2[-2:, :] == SparseMatrix([[8, 9, 10, 11], [12, 13, 14, 15]])

    assert SparseMatrix([[1, 2], [3, 4]])[[1], [1]] == Matrix([[4]])

    # test_submatrix_assignment
    m = sparse_zeros(4)
    m[2:4, 2:4] = sparse_eye(2)
    assert m == SparseMatrix([(0, 0, 0, 0), (0, 0, 0, 0), (0, 0, 1, 0),
                              (0, 0, 0, 1)])
    assert len(m._smat) == 2
    m[:2, :2] = sparse_eye(2)
    assert m == sparse_eye(4)
    m[:, 0] = SparseMatrix(4, 1, (1, 2, 3, 4))
    assert m == SparseMatrix([(1, 0, 0, 0), (2, 1, 0, 0), (3, 0, 1, 0),
                              (4, 0, 0, 1)])
    m[:, :] = sparse_zeros(4)
    assert m == sparse_zeros(4)
    m[:, :] = ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))
    assert m == SparseMatrix(
        ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)))
    m[:2, 0] = [0, 0]
    assert m == SparseMatrix(
        ((0, 2, 3, 4), (0, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)))

    # test_reshape
    m0 = sparse_eye(3)
    assert m0.reshape(1, 9) == SparseMatrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
    m1 = SparseMatrix(3, 4, lambda i, j: i + j)
    assert m1.reshape(4, 3) == \
        SparseMatrix([(0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)])
    assert m1.reshape(2, 6) == \
        SparseMatrix([(0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)])

    # test_applyfunc
    m0 = sparse_eye(3)
    assert m0.applyfunc(lambda x: 2 * x) == sparse_eye(3) * 2
    assert m0.applyfunc(lambda x: 0) == sparse_zeros(3)

    # test_LUdecomp
    testmat = SparseMatrix([[0, 2, 5, 3], [3, 3, 7, 4], [8, 4, 0, 2],
                            [-2, 6, 3, 4]])
    L, U, p = testmat.LUdecomposition()
    assert L.is_lower
    assert U.is_upper
    assert (L * U).permute_rows(p, 'backward') - testmat == sparse_zeros(4)

    testmat = SparseMatrix([[6, -2, 7, 4], [0, 3, 6, 7], [1, -2, 7, 4],
                            [-9, 2, 6, 3]])
    L, U, p = testmat.LUdecomposition()
    assert L.is_lower
    assert U.is_upper
    assert (L * U).permute_rows(p, 'backward') - testmat == sparse_zeros(4)

    x, y, z = Symbol('x'), Symbol('y'), Symbol('z')
    M = Matrix(((1, x, 1), (2, y, 0), (y, 0, z)))
    L, U, p = M.LUdecomposition()
    assert L.is_lower
    assert U.is_upper
    assert (L * U).permute_rows(p, 'backward') - M == sparse_zeros(3)

    # test_LUsolve
    A = SparseMatrix([[2, 3, 5], [3, 6, 2], [8, 3, 6]])
    x = SparseMatrix(3, 1, [3, 7, 5])
    b = A * x
    soln = A.LUsolve(b)
    assert soln == x
    A = SparseMatrix([[0, -1, 2], [5, 10, 7], [8, 3, 4]])
    x = SparseMatrix(3, 1, [-1, 2, 5])
    b = A * x
    soln = A.LUsolve(b)
    assert soln == x

    # test_inverse
    A = sparse_eye(4)
    assert A.inv() == sparse_eye(4)
    assert A.inv(method="CH") == sparse_eye(4)
    assert A.inv(method="LDL") == sparse_eye(4)

    A = SparseMatrix([[2, 3, 5], [3, 6, 2], [7, 2, 6]])
    Ainv = SparseMatrix(Matrix(A).inv())
    assert A * Ainv == sparse_eye(3)
    assert A.inv(method="CH") == Ainv
    assert A.inv(method="LDL") == Ainv

    A = SparseMatrix([[2, 3, 5], [3, 6, 2], [5, 2, 6]])
    Ainv = SparseMatrix(Matrix(A).inv())
    assert A * Ainv == sparse_eye(3)
    assert A.inv(method="CH") == Ainv
    assert A.inv(method="LDL") == Ainv

    # test_cross
    v1 = Matrix(1, 3, [1, 2, 3])
    v2 = Matrix(1, 3, [3, 4, 5])
    assert v1.cross(v2) == Matrix(1, 3, [-2, 4, -2])
    assert v1.norm(2)**2 == 14

    # conjugate
    a = SparseMatrix(((1, 2 + I), (3, 4)))
    assert a.C == SparseMatrix([[1, 2 - I], [3, 4]])

    # mul
    assert a * Matrix(2, 2, [1, 0, 0, 1]) == a
    assert a + Matrix(2, 2, [1, 1, 1, 1]) == SparseMatrix([[2, 3 + I], [4, 5]])

    # col join
    assert a.col_join(sparse_eye(2)) == SparseMatrix([[1, 2 + I], [3, 4],
                                                      [1, 0], [0, 1]])

    # symmetric
    assert not a.is_symmetric(simplify=False)

    # test_cofactor
    assert sparse_eye(3) == sparse_eye(3).cofactor_matrix()
    test = SparseMatrix([[1, 3, 2], [2, 6, 3], [2, 3, 6]])
    assert test.cofactor_matrix() == \
        SparseMatrix([[27, -6, -6], [-12, 2, 3], [-3, 1, 0]])
    test = SparseMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    assert test.cofactor_matrix() == \
        SparseMatrix([[-3, 6, -3], [6, -12, 6], [-3, 6, -3]])

    # test_jacobian
    x = Symbol('x')
    y = Symbol('y')
    L = SparseMatrix(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 = SparseMatrix(1, 2, [x, x**2 * y**3])
    assert L.jacobian(syms) == SparseMatrix([[1, 0],
                                             [2 * x * y**3, x**2 * 3 * y**2]])

    # test_QR
    A = Matrix([[1, 2], [2, 3]])
    Q, S = A.QRdecomposition()
    R = Rational
    assert Q == Matrix([[5**R(-1, 2), (R(2) / 5) * (R(1) / 5)**R(-1, 2)],
                        [2 * 5**R(-1, 2), (-R(1) / 5) * (R(1) / 5)**R(-1, 2)]])
    assert S == Matrix([[5**R(1, 2), 8 * 5**R(-1, 2)],
                        [0, (R(1) / 5)**R(1, 2)]])
    assert Q * S == A
    assert Q.T * Q == sparse_eye(2)

    R = Rational
    # test nullspace
    # first test reduced row-ech form

    M = SparseMatrix([[5, 7, 2, 1], [1, 6, 2, -1]])
    out, tmp = M.rref()
    assert out == Matrix([[1, 0, -R(2) / 23, R(13) / 23],
                          [0, 1, R(8) / 23, R(-6) / 23]])

    M = SparseMatrix([[1, 3, 0, 2, 6, 3, 1], [-2, -6, 0, -2, -8, 3, 1],
                      [3, 9, 0, 0, 6, 6, 2], [-1, -3, 0, 1, 0, 9, 3]])

    out, tmp = M.rref()
    assert out == Matrix([[1, 3, 0, 0, 2, 0, 0], [0, 0, 0, 1, 2, 0, 0],
                          [0, 0, 0, 0, 0, 1, R(1) / 3], [0, 0, 0, 0, 0, 0, 0]])
    # now check the vectors
    basis = M.nullspace()
    assert basis[0] == Matrix([-3, 1, 0, 0, 0, 0, 0])
    assert basis[1] == Matrix([0, 0, 1, 0, 0, 0, 0])
    assert basis[2] == Matrix([-2, 0, 0, -2, 1, 0, 0])
    assert basis[3] == Matrix([0, 0, 0, 0, 0, R(-1) / 3, 1])

    # test eigen
    x = Symbol('x')
    y = Symbol('y')
    sparse_eye3 = sparse_eye(3)
    assert sparse_eye3.charpoly(x) == PurePoly(((x - 1)**3))
    assert sparse_eye3.charpoly(y) == PurePoly(((y - 1)**3))

    # test values
    M = Matrix([(0, 1, -1), (1, 1, 0), (-1, 0, 1)])
    vals = M.eigenvals()
    assert sorted(vals.keys()) == [-1, 1, 2]

    R = Rational
    M = Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
    assert M.eigenvects() == [
        (1, 3, [Matrix([1, 0, 0]),
                Matrix([0, 1, 0]),
                Matrix([0, 0, 1])])
    ]
    M = Matrix([[5, 0, 2], [3, 2, 0], [0, 0, 1]])
    assert M.eigenvects() == [(1, 1, [Matrix([R(-1) / 2,
                                              R(3) / 2, 1])]),
                              (2, 1, [Matrix([0, 1, 0])]),
                              (5, 1, [Matrix([1, 1, 0])])]

    assert M.zeros(3, 5) == SparseMatrix(3, 5, {})
    A = SparseMatrix(
        10, 10, {
            (0, 0): 18,
            (0, 9): 12,
            (1, 4): 18,
            (2, 7): 16,
            (3, 9): 12,
            (4, 2): 19,
            (5, 7): 16,
            (6, 2): 12,
            (9, 7): 18
        })
    assert A.row_list() == [(0, 0, 18), (0, 9, 12), (1, 4, 18), (2, 7, 16),
                            (3, 9, 12), (4, 2, 19), (5, 7, 16), (6, 2, 12),
                            (9, 7, 18)]
    assert A.col_list() == [(0, 0, 18), (4, 2, 19), (6, 2, 12), (1, 4, 18),
                            (2, 7, 16), (5, 7, 16), (9, 7, 18), (0, 9, 12),
                            (3, 9, 12)]
    assert SparseMatrix.eye(2).nnz() == 2
コード例 #15
0
ファイル: systems.py プロジェクト: xushiwei/sympy
def matrix_exp_jordan_form(A, t):
    r"""
    Matrix exponential $\exp(A*t)$ for the matrix *A* and scalar *t*.

    Explanation
    ===========

    Returns the Jordan form of the $\exp(A*t)$ along with the matrix $P$ such that:

    .. math::
        \exp(A*t) = P * expJ * P^{-1}

    Examples
    ========

    >>> from sympy import Matrix, Symbol
    >>> from sympy.solvers.ode.systems import matrix_exp, matrix_exp_jordan_form
    >>> t = Symbol('t')

    We will consider a 2x2 defective matrix. This shows that our method
    works even for defective matrices.

    >>> A = Matrix([[1, 1], [0, 1]])

    It can be observed that this function gives us the Jordan normal form
    and the required invertible matrix P.

    >>> P, expJ = matrix_exp_jordan_form(A, t)

    Here, it is shown that P and expJ returned by this function is correct
    as they satisfy the formula: P * expJ * P_inverse = exp(A*t).

    >>> P * expJ * P.inv() == matrix_exp(A, t)
    True

    Parameters
    ==========

    A : Matrix
        The matrix $A$ in the expression $\exp(A*t)$
    t : Symbol
        The independent variable

    References
    ==========

    .. [1] https://en.wikipedia.org/wiki/Defective_matrix
    .. [2] https://en.wikipedia.org/wiki/Jordan_matrix
    .. [3] https://en.wikipedia.org/wiki/Jordan_normal_form

    """

    N, M = A.shape
    if N != M:
        raise ValueError('Needed square matrix but got shape (%s, %s)' % (N, M))
    elif A.has(t):
        raise ValueError('Matrix A should not depend on t')

    def jordan_chains(A):
        '''Chains from Jordan normal form analogous to M.eigenvects().
        Returns a dict with eignevalues as keys like:
            {e1: [[v111,v112,...], [v121, v122,...]], e2:...}
        where vijk is the kth vector in the jth chain for eigenvalue i.
        '''
        P, blocks = A.jordan_cells()
        basis = [P[:,i] for i in range(P.shape[1])]
        n = 0
        chains = {}
        for b in blocks:
            eigval = b[0, 0]
            size = b.shape[0]
            if eigval not in chains:
                chains[eigval] = []
            chains[eigval].append(basis[n:n+size])
            n += size
        return chains

    eigenchains = jordan_chains(A)

    # Needed for consistency across Python versions:
    eigenchains_iter = sorted(eigenchains.items(), key=default_sort_key)
    isreal = not A.has(I)

    blocks = []
    vectors = []
    seen_conjugate = set()
    for e, chains in eigenchains_iter:
        for chain in chains:
            n = len(chain)
            if isreal and e != e.conjugate() and e.conjugate() in eigenchains:
                if e in seen_conjugate:
                    continue
                seen_conjugate.add(e.conjugate())
                exprt = exp(re(e) * t)
                imrt = im(e) * t
                imblock = Matrix([[cos(imrt), sin(imrt)],
                                  [-sin(imrt), cos(imrt)]])
                expJblock2 = Matrix(n, n, lambda i,j:
                        imblock * t**(j-i) / factorial(j-i) if j >= i
                        else zeros(2, 2))
                expJblock = Matrix(2*n, 2*n, lambda i,j: expJblock2[i//2,j//2][i%2,j%2])

                blocks.append(exprt * expJblock)
                for i in range(n):
                    vectors.append(re(chain[i]))
                    vectors.append(im(chain[i]))
            else:
                vectors.extend(chain)
                fun = lambda i,j: t**(j-i)/factorial(j-i) if j >= i else 0
                expJblock = Matrix(n, n, fun)
                blocks.append(exp(e * t) * expJblock)

    expJ = Matrix.diag(*blocks)
    P = Matrix(N, N, lambda i,j: vectors[j][i])

    return P, expJ
コード例 #16
0
ファイル: test_lambdify.py プロジェクト: varunjha089/sympy
def test_numpy_inverse():
    if not numpy:
        skip("numpy not installed.")
    A = Matrix([[1, x], [0, 1]])
    f = lambdify((x), A**-1, modules="numpy")
    numpy.testing.assert_array_equal(f(2), numpy.array([[1, -2], [0, 1]]))
コード例 #17
0
ファイル: str.py プロジェクト: srijan-deepsource/sympy
 def _print_SparseMatrix(self, expr):
     from sympy.matrices import Matrix
     return self._print(Matrix(expr))
コード例 #18
0
def linodesolve(A, t, b=None, B=None, type="auto", doit=False):
    r"""
    System of n equations linear first-order differential equations

    Explanation
    ===========

    This solver solves the system of ODEs of the follwing form:

    .. math::
        X'(t) = A(t) X(t) +  b(t)

    Here, $A(t)$ is the coefficient matrix, $X(t)$ is the vector of n independent variables,
    $b(t)$ is the non-homogeneous term and $X'(t)$ is the derivative of $X(t)$

    Depending on the properties of $A(t)$ and $b(t)$, this solver evaluates the solution
    differently.

    When $A(t)$ is constant coefficient matrix and $b(t)$ is zero vector i.e. system is homogeneous,
    the solution is:

    .. math::
        X(t) = \exp(A t) C

    Here, $C$ is a vector of constants and $A$ is the constant coefficient matrix.

    When $A(t)$ is constant coefficient matrix and $b(t)$ is non-zero i.e. system is non-homogeneous,
    the solution is:

    .. math::
        X(t) = e^{A t} ( \int e^{- A t} b \,dt + C)

    When $A(t)$ is coefficient matrix such that its commutative with its antiderivative $B(t)$ and
    $b(t)$ is a zero vector i.e. system is homogeneous, the solution is:

    .. math::
        X(t) = \exp(B(t)) C

    When $A(t)$ is commutative with its antiderivative $B(t)$ and $b(t)$ is non-zero i.e. system is
    non-homogeneous, the solution is:

    .. math::
        X(t) =  e^{B(t)} ( \int e^{-B(t)} b(t) \,dt + C)

    The final solution is the general solution for all the four equations since a constant coefficient
    matrix is always commutative with its antidervative.

    Parameters
    ==========

    A : Matrix
        Coefficient matrix of the system of linear first order ODEs.
    t : Symbol
        Independent variable in the system of ODEs.
    b : Matrix or None
        Non-homogeneous term in the system of ODEs. If None is passed,
        a homogeneous system of ODEs is assumed.
    B : Matrix or None
        Antiderivative of the coefficient matrix. If the antiderivative
        is not passed and the solution requires the term, then the solver
        would compute it internally.
    type : String
        Type of the system of ODEs passed. Depending on the type, the
        solution is evaluated. The type values allowed and the corresponding
        system it solves are: "type1" for constant coefficient homogeneous
        "type2" for constant coefficient non-homogeneous, "type3" for non-constant
        coefficient homogeneous and "type4" for non-constant coefficient non-homogeneous.
        The default value is "auto" which will let the solver decide the correct type of
        the system passed.
    doit : Boolean
        Evaluate the solution if True, default value is False

    Examples
    ========

    To solve the system of ODEs using this function directly, several things must be
    done in the right order. Wrong inputs to the function will lead to incorrect results.

    >>> from sympy import symbols, Function, Eq
    >>> from sympy.solvers.ode.systems import canonical_odes, linear_ode_to_matrix, linodesolve, linodesolve_type
    >>> from sympy.solvers.ode.subscheck import checksysodesol
    >>> f, g = symbols("f, g", cls=Function)
    >>> x, a = symbols("x, a")
    >>> funcs = [f(x), g(x)]
    >>> eqs = [Eq(f(x).diff(x) - f(x), a*g(x) + 1), Eq(g(x).diff(x) + g(x), a*f(x))]

    Here, it is important to note that before we derive the coefficient matrix, it is
    important to get the system of ODEs into the desired form. For that we will use
    :obj:`sympy.solvers.ode.systems.canonical_odes()`.

    >>> eqs = canonical_odes(eqs, funcs, x)
    >>> eqs
    [Eq(Derivative(f(x), x), a*g(x) + f(x) + 1), Eq(Derivative(g(x), x), a*f(x) - g(x))]

    Now, we will use :obj:`sympy.solvers.ode.systems.linear_ode_to_matrix()` to get the coefficient matrix and the
    non-homogeneous term if it is there.

    >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1)
    >>> A = -A0

    We have the coefficient matrices and the non-homogeneous term ready. Now, we can use
    :obj:`sympy.solvers.ode.systems.linodesolve_type()` to get the information for the system of ODEs
    to finally pass it to the solver.

    >>> system_info = linodesolve_type(A, x, b=b)
    >>> sol_vector = linodesolve(A, x, b=b, B=system_info['antiderivative'], type=system_info['type'])

    Now, we can prove if the solution is correct or not by using :obj:`sympy.solvers.ode.subscheck.checksysodesol()`

    >>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
    >>> checksysodesol(eqs, sol)
    (True, [0, 0])

    We can also use the doit method to evaluate the solutions passed by the function.

    >>> sol_vector_evaluated = linodesolve(A, x, b=b, type="type2", doit=True)

    Now, we will look at a system of ODEs which is non-constant.

    >>> eqs = [Eq(f(x).diff(x), f(x) + x*g(x)), Eq(g(x).diff(x), -x*f(x) + g(x))]

    The system defined above is already in the desired form, so we don't have to convert it.

    >>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1)
    >>> A = -A0

    A user can also pass the commutative antidervative required for type3 and type4 system of ODEs.
    Passing an incorrect one will lead to incorrect results. If the coefficient matrix is not commutative
    with its antiderivative, then :obj:`sympy.solvers.ode.systems.linodesolve_type()` raises a NotImplementedError.
    If it does have a commutative antiderivative, then the function just returns the information about the system.

    >>> system_info = linodesolve_type(A, x, b=b)

    Now, we can pass the antiderivative as an argument to get the solution. If the system information is not
    passed, then the solver will compute the required arguments internally.

    >>> sol_vector = linodesolve(A, x, b=b)

    Once again, we can verify the solution obtained.

    >>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
    >>> checksysodesol(eqs, sol)
    (True, [0, 0])

    Returns
    =======

    List

    Raises
    ======

    ValueError
        This error is raised when the coefficient matrix, non-homogeneous term
        or the antiderivative, if passed, aren't a matrix or
        don't have correct dimensions
    NonSquareMatrixError
        When the coefficient matrix or its antiderivative, if passed isn't a square
        matrix
    NotImplementedError
        If the coefficient matrix doesn't have a commutative antiderivative

    See Also
    ========

    linear_ode_to_matrix: Coefficient matrix computation function
    canonical_odes: System of ODEs representation change
    linodesolve_type: Getting information about systems of ODEs to pass in this solver

    """

    if not isinstance(A, MatrixBase):
        raise ValueError(filldedent('''\
            The coefficients of the system of ODEs should be of type Matrix
        '''))

    if not A.is_square:
        raise NonSquareMatrixError(filldedent('''\
            The coefficient matrix must be a square
        '''))

    if b is not None:
        if not isinstance(b, MatrixBase):
            raise ValueError(filldedent('''\
                The non-homogeneous terms of the system of ODEs should be of type Matrix
            '''))

        if A.rows != b.rows:
            raise ValueError(filldedent('''\
                The system of ODEs should have the same number of non-homogeneous terms and the number of
                equations
            '''))

    if B is not None:
        if not isinstance(B, MatrixBase):
            raise ValueError(filldedent('''\
                The antiderivative of coefficients of the system of ODEs should be of type Matrix
            '''))

        if not B.is_square:
            raise NonSquareMatrixError(filldedent('''\
                The antiderivative of the coefficient matrix must be a square
            '''))

        if A.rows != B.rows:
            raise ValueError(filldedent('''\
                        The coefficient matrix and its antiderivative should have same dimensions
                    '''))

    if not any(type == "type{}".format(i) for i in range(1, 5)) and not type == "auto":
        raise ValueError(filldedent('''\
                    The input type should be a valid one
                '''))

    n = A.rows

    # constants = numbered_symbols(prefix='C', cls=Dummy, start=const_idx+1)
    Cvect = Matrix(list(Dummy() for _ in range(n)))

    if (type == "type2" or type == "type4") and b is None:
        b = zeros(n, 1)

    if type == "auto":
        system_info = linodesolve_type(A, t, b=b)
        type = system_info["type"]
        B = system_info["antiderivative"]

    if type == "type1" or type == "type2":
        P, J = matrix_exp_jordan_form(A, t)
        P = simplify(P)

        if type == "type1":
            sol_vector = P * (J * Cvect)
        else:
            sol_vector = P * J * ((J.inv() * P.inv() * b).applyfunc(lambda x: Integral(x, t)) + Cvect)

    else:
        if B is None:
            B, _ = _is_commutative_anti_derivative(A, t)

        if type == "type3":
            sol_vector = B.exp() * Cvect
        else:
            sol_vector = B.exp() * (((-B).exp() * b).applyfunc(lambda x: Integral(x, t)) + Cvect)

    gens = sol_vector.atoms(exp)

    if type != "type1":
        sol_vector = [expand_mul(s) for s in sol_vector]

    sol_vector = [collect(s, ordered(gens), exact=True) for s in sol_vector]

    if doit:
        sol_vector = [s.doit() for s in sol_vector]

    return sol_vector
コード例 #19
0
def test_LDLdecomposition():
    raises(NonSquareMatrixError, lambda: Matrix((1, 2)).LDLdecomposition())
    raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).LDLdecomposition())
    raises(ValueError, lambda: Matrix(((5 + I, 0), (0, 1))).LDLdecomposition())
    raises(ValueError, lambda: Matrix(((1, 5), (5, 1))).LDLdecomposition())
    raises(ValueError, lambda: Matrix(
        ((1, 2), (3, 4))).LDLdecomposition(hermitian=False))
    A = Matrix(((1, 5), (5, 1)))
    L, D = A.LDLdecomposition(hermitian=False)
    assert L * D * L.T == A
    A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
    L, D = A.LDLdecomposition()
    assert L * D * L.T == A
    assert L.is_lower
    assert L == Matrix([[1, 0, 0], [Rational(3, 5), 1, 0],
                        [Rational(-1, 5), Rational(1, 3), 1]])
    assert D.is_diagonal()
    assert D == Matrix([[25, 0, 0], [0, 9, 0], [0, 0, 9]])
    A = Matrix(
        ((4, -2 * I, 2 + 2 * I), (2 * I, 2, -1 + I), (2 - 2 * I, -1 - I, 11)))
    L, D = A.LDLdecomposition()
    assert expand_mul(L * D * L.H) == A
    assert L == Matrix(((1, 0, 0), (I / 2, 1, 0), (S.Half - I / 2, 0, 1)))
    assert D == Matrix(((4, 0, 0), (0, 1, 0), (0, 0, 9)))

    raises(NonSquareMatrixError, lambda: SparseMatrix(
        (1, 2)).LDLdecomposition())
    raises(ValueError, lambda: SparseMatrix(((1, 2),
                                             (3, 4))).LDLdecomposition())
    raises(ValueError, lambda: SparseMatrix(((5 + I, 0),
                                             (0, 1))).LDLdecomposition())
    raises(ValueError, lambda: SparseMatrix(((1, 5),
                                             (5, 1))).LDLdecomposition())
    raises(
        ValueError, lambda: SparseMatrix(
            ((1, 2), (3, 4))).LDLdecomposition(hermitian=False))
    A = SparseMatrix(((1, 5), (5, 1)))
    L, D = A.LDLdecomposition(hermitian=False)
    assert L * D * L.T == A
    A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
    L, D = A.LDLdecomposition()
    assert L * D * L.T == A
    assert L.is_lower
    assert L == Matrix([[1, 0, 0], [Rational(3, 5), 1, 0],
                        [Rational(-1, 5), Rational(1, 3), 1]])
    assert D.is_diagonal()
    assert D == Matrix([[25, 0, 0], [0, 9, 0], [0, 0, 9]])
    A = SparseMatrix(
        ((4, -2 * I, 2 + 2 * I), (2 * I, 2, -1 + I), (2 - 2 * I, -1 - I, 11)))
    L, D = A.LDLdecomposition()
    assert expand_mul(L * D * L.H) == A
    assert L == Matrix(((1, 0, 0), (I / 2, 1, 0), (S.Half - I / 2, 0, 1)))
    assert D == Matrix(((4, 0, 0), (0, 1, 0), (0, 0, 9)))
コード例 #20
0
ファイル: test_joint_rv.py プロジェクト: varunjha089/sympy
def test_Normal():
    m = Normal('A', [1, 2], [[1, 0], [0, 1]])
    A = MultivariateNormal('A', [1, 2], [[1, 0], [0, 1]])
    assert m == A
    assert density(m)(1, 2) == 1 / (2 * pi)
    assert m.pspace.distribution.set == ProductSet(S.Reals, S.Reals)
    raises(ValueError, lambda: m[2])
    n = Normal('B', [1, 2, 3], [[1, 0, 0], [0, 1, 0], [0, 0, 1]])
    p = Normal('C', Matrix([1, 2]), Matrix([[1, 0], [0, 1]]))
    assert density(m)(x, y) == density(p)(x, y)
    assert marginal_distribution(n, 0, 1)(1, 2) == 1 / (2 * pi)
    raises(ValueError, lambda: marginal_distribution(m))
    assert integrate(density(m)(x, y), (x, -oo, oo), (y, -oo, oo)).evalf() == 1
    N = Normal('N', [1, 2], [[x, 0], [0, y]])
    assert density(N)(0, 0) == exp(-((4 * x + y) /
                                     (2 * x * y))) / (2 * pi * sqrt(x * y))

    raises(ValueError, lambda: Normal('M', [1, 2], [[1, 1], [1, -1]]))
    # symbolic
    n = symbols('n', natural=True)
    mu = MatrixSymbol('mu', n, 1)
    sigma = MatrixSymbol('sigma', n, n)
    X = Normal('X', mu, sigma)
    assert density(X) == MultivariateNormalDistribution(mu, sigma)
    raises(NotImplementedError, lambda: median(m))
    # Below tests should work after issue #17267 is resolved
    # assert E(X) == mu
    # assert variance(X) == sigma

    # test symbolic multivariate normal densities
    n = 3

    Sg = MatrixSymbol('Sg', n, n)
    mu = MatrixSymbol('mu', n, 1)
    obs = MatrixSymbol('obs', n, 1)

    X = MultivariateNormal('X', mu, Sg)
    density_X = density(X)

    eval_a = density_X(obs).subs({
        Sg: eye(3),
        mu: Matrix([0, 0, 0]),
        obs: Matrix([0, 0, 0])
    }).doit()
    eval_b = density_X(0, 0, 0).subs({
        Sg: eye(3),
        mu: Matrix([0, 0, 0])
    }).doit()

    assert eval_a == sqrt(2) / (4 * pi**Rational(3 / 2))
    assert eval_b == sqrt(2) / (4 * pi**Rational(3 / 2))

    n = symbols('n', natural=True)

    Sg = MatrixSymbol('Sg', n, n)
    mu = MatrixSymbol('mu', n, 1)
    obs = MatrixSymbol('obs', n, 1)

    X = MultivariateNormal('X', mu, Sg)
    density_X_at_obs = density(X)(obs)

    expected_density = MatrixElement(
        exp((S(1)/2) * (mu.T - obs.T) * Sg**(-1) * (-mu + obs)) / \
        sqrt((2*pi)**n * Determinant(Sg)), 0, 0)

    assert density_X_at_obs == expected_density
コード例 #21
0
    a4: 0,
    d5: 0,
    al5: -pi / 2,
    a5: 0,
    d6: 0,
    al6: 0,
    a6: 0,
    d7: 0.303,
    q7: 0
}

#Transforms
T0_1 = Matrix(
    [[cos(q1), -sin(q1), 0, a0],
     [sin(q1) * cos(al0),
      cos(q1) * cos(al0), -sin(al0), -sin(al0) * d1],
     [sin(q1) * sin(al0),
      cos(q1) * sin(al0),
      cos(al0),
      cos(al0) * d1], [0, 0, 0, 1]])
T0_1 = T0_1.subs(s)

T1_2 = Matrix(
    [[cos(q2), -sin(q2), 0, a1],
     [sin(q2) * cos(al1),
      cos(q2) * cos(al1), -sin(al1), -sin(al1) * d2],
     [sin(q2) * sin(al1),
      cos(q2) * sin(al1),
      cos(al1),
      cos(al1) * d2], [0, 0, 0, 1]])
T1_2 = T1_2.subs(s)
コード例 #22
0
def block_collapse(expr):
    """Evaluates a block matrix expression

    >>> from sympy import MatrixSymbol, BlockMatrix, symbols, Identity, Matrix, 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
    [X, Z]
    [0, Y]

    >>> C = BlockMatrix([[Identity(n), Z]])
    >>> print C
    [I, Z]

    >>> print block_collapse(C*B)
    [X, Z + Z*Y]
    """
    if expr.__class__ in [tuple, list, set, frozenset]:
        return expr.__class__([block_collapse(arg) for arg in expr])
    if expr.__class__ in [Tuple, FiniteSet]:
        return expr.__class__(*[block_collapse(arg) for arg in expr])

    if not expr.is_Matrix or (not expr.is_Add and not expr.is_Mul
            and not expr.is_Transpose and not expr.is_Pow
            and not expr.is_Inverse):
        return expr

    if expr.is_Transpose:
        expr = Transpose(block_collapse(expr.arg))
        if expr.is_Transpose and expr.arg.is_BlockMatrix:
            expr = expr.arg._eval_transpose()
        return expr

    if expr.is_Inverse:
        return Inverse(block_collapse(expr.arg))

    # Recurse on the subargs
    args = list(expr.args)
    for i in range(len(args)):
        arg = args[i]
        newarg = block_collapse(arg)
        while(newarg != arg): # Repeat until no new changes
            arg = newarg
            newarg = block_collapse(arg)
        args[i] = newarg

    if tuple(args) != expr.args:
        expr = expr.__class__(*args)

    # Turn  -[X, Y] into [-X, -Y]
    if (expr.is_Mul and len(expr.args)==2 and not expr.args[0].is_Matrix
            and expr.args[1].is_BlockMatrix):
        if expr.args[1].is_BlockDiagMatrix:
            return BlockDiagMatrix(
                    *[expr.args[0]*arg for arg in expr.args[1].diag])
        else:
            return BlockMatrix(expr.args[0]*expr.args[1]._mat)

    if expr.is_Add:
        nonblocks = [arg for arg in expr.args if not arg.is_BlockMatrix]
        blocks = [arg for arg in expr.args if arg.is_BlockMatrix]
        if not blocks:
            return MatAdd(*nonblocks)
        block = blocks[0]
        for b in blocks[1:]:
            block = block._blockadd(b)
        if block.blockshape == (1,1):
            # Bring all the non-blocks into the block_matrix
            mat = Matrix(1, 1, (block.blocks[0,0] + MatAdd(*nonblocks), ))
            return BlockMatrix(mat)
        # Add identities to the blocks as block identities
        for i, mat in enumerate(nonblocks):
            c, M = mat.as_coeff_Mul()
            if M.is_Identity and block.is_structurally_symmetric:
                block_id = BlockDiagMatrix(
                        *[c*Identity(k) for k in block.rowblocksizes])
                nonblocks.pop(i)
                block = block._blockadd(block_id)


        return MatAdd(*(nonblocks+[block]))

    if expr.is_Mul:
        nonmatrices = [arg for arg in expr.args if not arg.is_Matrix]
        matrices = [arg for arg in expr.args if arg.is_Matrix]
        i = 0
        while (i+1 < len(matrices)):
            A, B = matrices[i:i+2]
            if A.is_BlockMatrix and B.is_BlockMatrix:
                matrices[i] = A._blockmul(B)
                matrices.pop(i+1)
            else:
                i+=1
        return MatMul(*(nonmatrices + matrices))

    if expr.is_Pow:
        rv = expr.base
        for i in range(1, expr.exp):
            rv = rv._blockmul(expr.base)
        return rv
コード例 #23
0
ファイル: test_matexpr.py プロジェクト: xrmx/sympy
def test_dense_conversion():
    X = MatrixSymbol('X', 2, 2)
    assert ImmutableMatrix(X) == ImmutableMatrix(2, 2, lambda i, j: X[i, j])
    assert Matrix(X) == Matrix(2, 2, lambda i, j: X[i, j])
コード例 #24
0
def test_Matrices_1x7():
    gl = glsl_code
    A = Matrix([1, 2, 3, 4, 5, 6, 7])
    assert gl(A) == 'float[7](1, 2, 3, 4, 5, 6, 7)'
    assert gl(A.transpose()) == 'float[7](1, 2, 3, 4, 5, 6, 7)'
コード例 #25
0
ファイル: test_matexpr.py プロジェクト: xrmx/sympy
def test_issue_2750():
    x = MatrixSymbol('x', 1, 1)
    assert (x.T * x).as_explicit()**-1 == Matrix([[x[0, 0]**(-2)]])
コード例 #26
0
def test_misc_mats():

    mat = Matrix([[0]])

    gl = '''0'''
    glTransposed = '''0'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1]])

    gl = '''vec2(0, 1)'''
    glTransposed = '''vec2(0, 1)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2]])

    gl = '''vec3(0, 1, 2)'''
    glTransposed = '''vec3(0, 1, 2)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3]])

    gl = '''vec4(0, 1, 2, 3)'''
    glTransposed = '''vec4(0, 1, 2, 3)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3, 4]])

    gl = '''float[5](0, 1, 2, 3, 4)'''
    glTransposed = '''float[5](0, 1, 2, 3, 4)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0], [1]])

    gl = '''vec2(0, 1)'''
    glTransposed = '''vec2(0, 1)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1], [2, 3]])

    gl = '''mat2(0, 1, 2, 3)'''
    glTransposed = '''mat2(0, 2, 1, 3)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2], [3, 4, 5]])

    gl = '''mat3x2(0, 1, 2, 3, 4, 5)'''
    glTransposed = '''mat2x3(0, 3, 1, 4, 2, 5)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3], [4, 5, 6, 7]])

    gl = '''mat4x2(0, 1, 2, 3, 4, 5, 6, 7)'''
    glTransposed = '''mat2x4(0, 4, 1, 5, 2, 6, 3, 7)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]])

    gl = '''float[10](
   0, 1, 2, 3, 4,
   5, 6, 7, 8, 9
) /* a 2x5 matrix */'''
    glTransposed = '''float[10](
   0, 5,
   1, 6,
   2, 7,
   3, 8,
   4, 9
) /* a 5x2 matrix */'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed
    glNested = '''float[2][5](
   float[](0, 1, 2, 3, 4),
   float[](5, 6, 7, 8, 9)
)'''
    glNestedTransposed = '''float[5][2](
   float[](0, 5),
   float[](1, 6),
   float[](2, 7),
   float[](3, 8),
   float[](4, 9)
)'''

    assert glsl_code(mat, mat_nested=True) == glNested
    assert glsl_code(mat, mat_nested=True,
                     mat_transpose=True) == glNestedTransposed

    mat = Matrix([[0], [1], [2]])

    gl = '''vec3(0, 1, 2)'''
    glTransposed = '''vec3(0, 1, 2)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1], [2, 3], [4, 5]])

    gl = '''mat2x3(0, 1, 2, 3, 4, 5)'''
    glTransposed = '''mat3x2(0, 2, 4, 1, 3, 5)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8]])

    gl = '''mat3(0, 1, 2, 3, 4, 5, 6, 7, 8)'''
    glTransposed = '''mat3(0, 3, 6, 1, 4, 7, 2, 5, 8)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])

    gl = '''mat4x3(0, 1,  2,  3, 4, 5,  6,  7, 8, 9, 10, 11)'''
    glTransposed = '''mat3x4(0, 4,  8, 1, 5,  9, 2, 6, 10, 3, 7, 11)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14]])

    gl = '''float[15](
   0,  1,  2,  3,  4,
   5,  6,  7,  8,  9,
   10, 11, 12, 13, 14
) /* a 3x5 matrix */'''
    glTransposed = '''float[15](
   0, 5, 10,
   1, 6, 11,
   2, 7, 12,
   3, 8, 13,
   4, 9, 14
) /* a 5x3 matrix */'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed
    glNested = '''float[3][5](
   float[]( 0,  1,  2,  3,  4),
   float[]( 5,  6,  7,  8,  9),
   float[](10, 11, 12, 13, 14)
)'''
    glNestedTransposed = '''float[5][3](
   float[](0, 5, 10),
   float[](1, 6, 11),
   float[](2, 7, 12),
   float[](3, 8, 13),
   float[](4, 9, 14)
)'''

    assert glsl_code(mat, mat_nested=True) == glNested
    assert glsl_code(mat, mat_nested=True,
                     mat_transpose=True) == glNestedTransposed

    mat = Matrix([[0], [1], [2], [3]])

    gl = '''vec4(0, 1, 2, 3)'''
    glTransposed = '''vec4(0, 1, 2, 3)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1], [2, 3], [4, 5], [6, 7]])

    gl = '''mat2x4(0, 1, 2, 3, 4, 5, 6, 7)'''
    glTransposed = '''mat4x2(0, 2, 4, 6, 1, 3, 5, 7)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])

    gl = '''mat3x4(0,  1,  2, 3,  4,  5, 6,  7,  8, 9, 10, 11)'''
    glTransposed = '''mat4x3(0, 3, 6,  9, 1, 4, 7, 10, 2, 5, 8, 11)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14,
                                                               15]])

    gl = '''mat4( 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15)'''
    glTransposed = '''mat4(0, 4,  8, 12, 1, 5,  9, 13, 2, 6, 10, 14, 3, 7, 11, 15)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14],
                  [15, 16, 17, 18, 19]])

    gl = '''float[20](
   0,  1,  2,  3,  4,
   5,  6,  7,  8,  9,
   10, 11, 12, 13, 14,
   15, 16, 17, 18, 19
) /* a 4x5 matrix */'''
    glTransposed = '''float[20](
   0, 5, 10, 15,
   1, 6, 11, 16,
   2, 7, 12, 17,
   3, 8, 13, 18,
   4, 9, 14, 19
) /* a 5x4 matrix */'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed
    glNested = '''float[4][5](
   float[]( 0,  1,  2,  3,  4),
   float[]( 5,  6,  7,  8,  9),
   float[](10, 11, 12, 13, 14),
   float[](15, 16, 17, 18, 19)
)'''
    glNestedTransposed = '''float[5][4](
   float[](0, 5, 10, 15),
   float[](1, 6, 11, 16),
   float[](2, 7, 12, 17),
   float[](3, 8, 13, 18),
   float[](4, 9, 14, 19)
)'''

    assert glsl_code(mat, mat_nested=True) == glNested
    assert glsl_code(mat, mat_nested=True,
                     mat_transpose=True) == glNestedTransposed

    mat = Matrix([[0], [1], [2], [3], [4]])

    gl = '''float[5](0, 1, 2, 3, 4)'''
    glTransposed = '''float[5](0, 1, 2, 3, 4)'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed

    mat = Matrix([[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]])

    gl = '''float[10](
   0, 1,
   2, 3,
   4, 5,
   6, 7,
   8, 9
) /* a 5x2 matrix */'''
    glTransposed = '''float[10](
   0, 2, 4, 6, 8,
   1, 3, 5, 7, 9
) /* a 2x5 matrix */'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed
    glNested = '''float[5][2](
   float[](0, 1),
   float[](2, 3),
   float[](4, 5),
   float[](6, 7),
   float[](8, 9)
)'''
    glNestedTransposed = '''float[2][5](
   float[](0, 2, 4, 6, 8),
   float[](1, 3, 5, 7, 9)
)'''

    assert glsl_code(mat, mat_nested=True) == glNested
    assert glsl_code(mat, mat_nested=True,
                     mat_transpose=True) == glNestedTransposed

    mat = Matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], [12, 13, 14]])

    gl = '''float[15](
   0,  1,  2,
   3,  4,  5,
   6,  7,  8,
   9, 10, 11,
   12, 13, 14
) /* a 5x3 matrix */'''
    glTransposed = '''float[15](
   0, 3, 6,  9, 12,
   1, 4, 7, 10, 13,
   2, 5, 8, 11, 14
) /* a 3x5 matrix */'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed
    glNested = '''float[5][3](
   float[]( 0,  1,  2),
   float[]( 3,  4,  5),
   float[]( 6,  7,  8),
   float[]( 9, 10, 11),
   float[](12, 13, 14)
)'''
    glNestedTransposed = '''float[3][5](
   float[](0, 3, 6,  9, 12),
   float[](1, 4, 7, 10, 13),
   float[](2, 5, 8, 11, 14)
)'''

    assert glsl_code(mat, mat_nested=True) == glNested
    assert glsl_code(mat, mat_nested=True,
                     mat_transpose=True) == glNestedTransposed

    mat = Matrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15],
                  [16, 17, 18, 19]])

    gl = '''float[20](
   0,  1,  2,  3,
   4,  5,  6,  7,
   8,  9, 10, 11,
   12, 13, 14, 15,
   16, 17, 18, 19
) /* a 5x4 matrix */'''
    glTransposed = '''float[20](
   0, 4,  8, 12, 16,
   1, 5,  9, 13, 17,
   2, 6, 10, 14, 18,
   3, 7, 11, 15, 19
) /* a 4x5 matrix */'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed
    glNested = '''float[5][4](
   float[]( 0,  1,  2,  3),
   float[]( 4,  5,  6,  7),
   float[]( 8,  9, 10, 11),
   float[](12, 13, 14, 15),
   float[](16, 17, 18, 19)
)'''
    glNestedTransposed = '''float[4][5](
   float[](0, 4,  8, 12, 16),
   float[](1, 5,  9, 13, 17),
   float[](2, 6, 10, 14, 18),
   float[](3, 7, 11, 15, 19)
)'''

    assert glsl_code(mat, mat_nested=True) == glNested
    assert glsl_code(mat, mat_nested=True,
                     mat_transpose=True) == glNestedTransposed

    mat = Matrix([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9], [10, 11, 12, 13, 14],
                  [15, 16, 17, 18, 19], [20, 21, 22, 23, 24]])

    gl = '''float[25](
   0,  1,  2,  3,  4,
   5,  6,  7,  8,  9,
   10, 11, 12, 13, 14,
   15, 16, 17, 18, 19,
   20, 21, 22, 23, 24
) /* a 5x5 matrix */'''
    glTransposed = '''float[25](
   0, 5, 10, 15, 20,
   1, 6, 11, 16, 21,
   2, 7, 12, 17, 22,
   3, 8, 13, 18, 23,
   4, 9, 14, 19, 24
) /* a 5x5 matrix */'''

    assert glsl_code(mat) == gl
    assert glsl_code(mat, mat_transpose=True) == glTransposed
    glNested = '''float[5][5](
   float[]( 0,  1,  2,  3,  4),
   float[]( 5,  6,  7,  8,  9),
   float[](10, 11, 12, 13, 14),
   float[](15, 16, 17, 18, 19),
   float[](20, 21, 22, 23, 24)
)'''
    glNestedTransposed = '''float[5][5](
   float[](0, 5, 10, 15, 20),
   float[](1, 6, 11, 16, 21),
   float[](2, 7, 12, 17, 22),
   float[](3, 8, 13, 18, 23),
   float[](4, 9, 14, 19, 24)
)'''

    assert glsl_code(mat, mat_nested=True) == glNested
    assert glsl_code(mat, mat_nested=True,
                     mat_transpose=True) == glNestedTransposed
コード例 #27
0
    def are_collinear(*points):
        """Is a sequence of points collinear?

        Test whether or not a set of points are collinear. Returns True if
        the set of points are collinear, or False otherwise.

        Parameters
        ==========

        points : sequence of Point

        Returns
        =======

        are_collinear : boolean

        See Also
        ========

        sympy.geometry.line3d.Line3D

        Examples
        ========

        >>> from sympy import Point3D, Matrix
        >>> from sympy.abc import x
        >>> p1, p2 = Point3D(0, 0, 0), Point3D(1, 1, 1)
        >>> p3, p4, p5 = Point3D(2, 2, 2), Point3D(x, x, x), Point3D(1, 2, 6)
        >>> Point3D.are_collinear(p1, p2, p3, p4)
        True
        >>> Point3D.are_collinear(p1, p2, p3, p5)
        False
        """
        # Coincident points are irrelevant and can confuse this algorithm.
        # Use only unique points.
        points = list(set(points))
        if not all(isinstance(p, Point3D) for p in points):
            raise TypeError('Must pass only 3D Point objects')

        if len(points) < 2:
            return False
        if len(points) == 2:
            return True  # two points always form a line
        if len(points) == 3:
            a = (points[0].direction_cosine(points[1]))
            b = (points[0].direction_cosine(points[2]))
            a = [abs(i) for i in a]
            b = [abs(i) for i in b]
            if a == b:
                return True
            else:
                return False
        # XXX Cross product is used now,
        # If the concept needs to extend to more than three
        # dimensions then another method would have to be used
        for i in range(len(points) - 2):
            pv1 = [j - k for j, k in zip(points[i].args,   \
                points[i + 1].args)]
            pv2 = [
                j - k for j, k in zip(points[i + 1].args, points[i + 2].args)
            ]
            rank = Matrix([pv1, pv2]).rank()
            if (rank != 1):
                return False
        return True
コード例 #28
0
ファイル: test_transforms.py プロジェクト: nwilding/sympy
def test_laplace_transform():
    from sympy import fresnels, fresnelc
    LT = laplace_transform
    a, b, c, = symbols('a b c', positive=True)
    t = symbols('t')
    w = Symbol("w")
    f = Function("f")

    # Test unevaluated form
    assert laplace_transform(f(t), t, w) == LaplaceTransform(f(t), t, w)
    assert inverse_laplace_transform(
        f(w), w, t, plane=0) == InverseLaplaceTransform(f(w), w, t, 0)

    # test a bug
    spos = symbols('s', positive=True)
    assert LT(exp(t), t, spos)[:2] == (1/(spos - 1), True)

    # basic tests from wikipedia

    assert LT((t - a)**b*exp(-c*(t - a))*Heaviside(t - a), t, s) == \
        ((s + c)**(-b - 1)*exp(-a*s)*gamma(b + 1), -c, True)
    assert LT(t**a, t, s) == (s**(-a - 1)*gamma(a + 1), 0, True)
    assert LT(Heaviside(t), t, s) == (1/s, 0, True)
    assert LT(Heaviside(t - a), t, s) == (exp(-a*s)/s, 0, True)
    assert LT(1 - exp(-a*t), t, s) == (a/(s*(a + s)), 0, True)

    assert LT((exp(2*t) - 1)*exp(-b - t)*Heaviside(t)/2, t, s, noconds=True) \
        == exp(-b)/(s**2 - 1)

    assert LT(exp(t), t, s)[:2] == (1/(s - 1), 1)
    assert LT(exp(2*t), t, s)[:2] == (1/(s - 2), 2)
    assert LT(exp(a*t), t, s)[:2] == (1/(s - a), a)

    assert LT(log(t/a), t, s) == ((log(a*s) + EulerGamma)/s/-1, 0, True)

    assert LT(erf(t), t, s) == ((-erf(s/2) + 1)*exp(s**2/4)/s, 0, True)

    assert LT(sin(a*t), t, s) == (a/(a**2 + s**2), 0, True)
    assert LT(cos(a*t), t, s) == (s/(a**2 + s**2), 0, True)
    # TODO would be nice to have these come out better
    assert LT(
        exp(-a*t)*sin(b*t), t, s) == (b/(b**2 + (a + s)**2), -a, True)
    assert LT(exp(-a*t)*cos(b*t), t, s) == \
        ((a + s)/(b**2 + (a + s)**2), -a, True)

    assert LT(besselj(0, t), t, s) == (1/sqrt(1 + s**2), 0, True)
    assert LT(besselj(1, t), t, s) == (1 - 1/sqrt(1 + 1/s**2), 0, True)
    # TODO general order works, but is a *mess*
    # TODO besseli also works, but is an even greater mess

    # test a bug in conditions processing
    # TODO the auxiliary condition should be recognised/simplified
    assert LT(exp(t)*cos(t), t, s)[:-1] in [
        ((s - 1)/(s**2 - 2*s + 2), -oo),
        ((s - 1)/((s - 1)**2 + 1), -oo),
    ]

    # Fresnel functions
    assert laplace_transform(fresnels(t), t, s) == \
        ((-sin(s**2/(2*pi))*fresnels(s/pi) + sin(s**2/(2*pi))/2 -
            cos(s**2/(2*pi))*fresnelc(s/pi) + cos(s**2/(2*pi))/2)/s, 0, True)
    assert laplace_transform(fresnelc(t), t, s) == (
        (sin(s**2/(2*pi))*fresnelc(s/pi)/s - cos(s**2/(2*pi))*fresnels(s/pi)/s
        + sqrt(2)*cos(s**2/(2*pi) + pi/4)/(2*s), 0, True))

    assert LT(Matrix([[exp(t), t*exp(-t)], [t*exp(-t), exp(t)]]), t, s) ==\
        Matrix([
            [(1/(s - 1), 1, True), ((s + 1)**(-2), 0, True)],
            [((s + 1)**(-2), 0, True), (1/(s - 1), 1, True)]
        ])
コード例 #29
0
ファイル: dfp.py プロジェクト: kasymova/conjdirmethod
def gradient(f, p):
    return Matrix(
        [diff(f, x_vars[i]).subs({x_vars[i]: p[i] for i in range(NUMBER_OF_VARS)}) for i in range(NUMBER_OF_VARS)])
コード例 #30
0
ファイル: test_commonmatrix.py プロジェクト: JonB14/sympy
def test_col_op():
    e = eye_Reductions(3)

    raises(ValueError, lambda: e.elementary_col_op("abc"))
    raises(ValueError, lambda: e.elementary_col_op())
    raises(ValueError, lambda: e.elementary_col_op('n->kn', col=5, k=5))
    raises(ValueError, lambda: e.elementary_col_op('n->kn', col=-5, k=5))
    raises(ValueError, lambda: e.elementary_col_op('n<->m', col1=1, col2=5))
    raises(ValueError, lambda: e.elementary_col_op('n<->m', col1=5, col2=1))
    raises(ValueError, lambda: e.elementary_col_op('n<->m', col1=-5, col2=1))
    raises(ValueError, lambda: e.elementary_col_op('n<->m', col1=1, col2=-5))
    raises(ValueError,
           lambda: e.elementary_col_op('n->n+km', col1=1, col2=5, k=5))
    raises(ValueError,
           lambda: e.elementary_col_op('n->n+km', col1=5, col2=1, k=5))
    raises(ValueError,
           lambda: e.elementary_col_op('n->n+km', col1=-5, col2=1, k=5))
    raises(ValueError,
           lambda: e.elementary_col_op('n->n+km', col1=1, col2=-5, k=5))
    raises(ValueError,
           lambda: e.elementary_col_op('n->n+km', col1=1, col2=1, k=5))

    # test various ways to set arguments
    assert e.elementary_col_op("n->kn", 0, 5) == Matrix([[5, 0, 0], [0, 1, 0],
                                                         [0, 0, 1]])
    assert e.elementary_col_op("n->kn", 1, 5) == Matrix([[1, 0, 0], [0, 5, 0],
                                                         [0, 0, 1]])
    assert e.elementary_col_op("n->kn", col=1, k=5) == Matrix([[1, 0, 0],
                                                               [0, 5, 0],
                                                               [0, 0, 1]])
    assert e.elementary_col_op("n->kn", col1=1, k=5) == Matrix([[1, 0, 0],
                                                                [0, 5, 0],
                                                                [0, 0, 1]])
    assert e.elementary_col_op("n<->m", 0, 1) == Matrix([[0, 1, 0], [1, 0, 0],
                                                         [0, 0, 1]])
    assert e.elementary_col_op("n<->m", col1=0, col2=1) == Matrix([[0, 1, 0],
                                                                   [1, 0, 0],
                                                                   [0, 0, 1]])
    assert e.elementary_col_op("n<->m", col=0, col2=1) == Matrix([[0, 1, 0],
                                                                  [1, 0, 0],
                                                                  [0, 0, 1]])
    assert e.elementary_col_op("n->n+km", 0, 5, 1) == Matrix([[1, 0, 0],
                                                              [5, 1, 0],
                                                              [0, 0, 1]])
    assert e.elementary_col_op("n->n+km", col=0, k=5,
                               col2=1) == Matrix([[1, 0, 0], [5, 1, 0],
                                                  [0, 0, 1]])
    assert e.elementary_col_op("n->n+km", col1=0, k=5,
                               col2=1) == Matrix([[1, 0, 0], [5, 1, 0],
                                                  [0, 0, 1]])

    # make sure the matrix doesn't change size
    a = ReductionsOnlyMatrix(2, 3, [0] * 6)
    assert a.elementary_col_op("n->kn", 1, 5) == Matrix(2, 3, [0] * 6)
    assert a.elementary_col_op("n<->m", 0, 1) == Matrix(2, 3, [0] * 6)
    assert a.elementary_col_op("n->n+km", 0, 5, 1) == Matrix(2, 3, [0] * 6)