Example #1
0
 def test_creation_from_matrix(self):
     A = ImmutableMatrix(1, 1, [1])
     B = ImmutableMatrix(1, 1, [1])
     D = A*B
     C = CompartmentalMatrix(D)
     print(C, type(C))
     self.assertEqual(type(C), CompartmentalMatrix)
Example #2
0
    def positive_root_coeffcients(self):
        # first, we look for all the positive roots
        current_roots = [None] * self.rank
        for i in xrange(self.rank):
            cm = ImmutableMatrix([[0] * i + [1] + [0] * (self.rank - 1 - i)])
            cm2 = (2 * cm).as_immutable()
            current_roots[i] = Root(cm2, cm, self.cartan_matrix)

        positive_roots = [x.coeff for x in current_roots]
        levels = [1] * self.rank
        level = 1

        while True:
            level += 1
            ancestors = {}
            for root in current_roots:
                for w, i, qi in root.ancestors():
                    if w in ancestors:
                        ancestors[w][i] = qi
                    else:
                        ancestors[w] = ([0] * i + [qi] + [0] *
                                        (self.rank - 1 - i))

            if not ancestors:
                break

            current_roots = [None] * len(ancestors)
            for i, w in enumerate(ancestors):
                positive_roots.append(w)
                levels.append(level)
                current_roots[i] = Root(ImmutableMatrix([ancestors[w]]), w,
                                        self.cartan_matrix)

        return (positive_roots, levels)
Example #3
0
def test_function_return_types():
    # Lets ensure that decompositions of immutable matrices remain immutable
    # I.e. do MatrixBase methods return the correct class?
    X = ImmutableMatrix([[1, 2], [3, 4]])
    Y = ImmutableMatrix([[1], [0]])
    q, r = X.QRdecomposition()
    assert (type(q), type(r)) == (ImmutableMatrix, ImmutableMatrix)

    assert type(X.LUsolve(Y)) == ImmutableMatrix
    assert type(X.QRsolve(Y)) == ImmutableMatrix

    X = ImmutableMatrix([[1, 2], [2, 1]])
    assert X.T == X
    assert X.is_symmetric
    assert type(X.cholesky()) == ImmutableMatrix
    L, D = X.LDLdecomposition()
    assert (type(L), type(D)) == (ImmutableMatrix, ImmutableMatrix)

    assert X.is_diagonalizable()
    assert X.berkowitz_det() == -3
    assert X.norm(2) == 3

    assert type(X.eigenvects()[0][2][0]) == ImmutableMatrix

    assert type(zeros(3, 3).as_immutable().nullspace()[0]) == ImmutableMatrix

    X = ImmutableMatrix([[1, 0], [2, 1]])
    assert type(X.lower_triangular_solve(Y)) == ImmutableMatrix
    assert type(X.T.upper_triangular_solve(Y)) == ImmutableMatrix

    assert type(X.minorMatrix(0, 0)) == ImmutableMatrix
Example #4
0
def lm_coeffs_to_sym(coeffs, variables):
    """Create a symbolic matrix linear w.r.t. variables given a list of
    numerical coefficient matrices"""
    lm = ImmutableMatrix(coeffs[1])
    for i, x in enumerate(variables):
        lm += x * ImmutableMatrix(coeffs[0][i])

    return lm
Example #5
0
def test_immutable_evaluation():
    X = ImmutableMatrix(eye(3))
    A = ImmutableMatrix(3, 3, range(9))
    assert isinstance(X + A, ImmutableMatrix)
    assert isinstance(X * A, ImmutableMatrix)
    assert isinstance(X * 2, ImmutableMatrix)
    assert isinstance(2 * X, ImmutableMatrix)
    assert isinstance(A**2, ImmutableMatrix)
Example #6
0
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 ValueError("%s is not a square matrix" % (matrix))
    if isinstance(matrix, Matrix):
        matrix = ImmutableMatrix(matrix.tolist())
    return matrix
Example #7
0
def test_subs():
    A = ImmutableMatrix([[1, 2], [3, 4]])
    B = ImmutableMatrix([[1, 2], [x, 4]])
    C = ImmutableMatrix([[-x, x * y], [-(x + y), y**2]])
    assert B.subs(x, 3) == A
    assert (x * B).subs(x, 3) == 3 * A
    assert (x * eye(2) + B).subs(x, 3) == 3 * eye(2) + A
    assert C.subs([[x, -1], [y, -2]]) == A
    assert C.subs([(x, -1), (y, -2)]) == A
    assert C.subs({x: -1, y: -2}) == A
    assert C.subs({x: y - 1, y: x - 1}, simultaneous=True) == \
        ImmutableMatrix([[1 - y, (x - 1)*(y - 1)], [2 - x - y, (x - 1)**2]])
Example #8
0
def smooth_reservoir_model_from_input_tuple_and_matrix(
    u: InputTuple,
    B: CompartmentalMatrix,
    time_symbol: TimeSymbol,
    state_variable_tuple: StateVariableTuple,
) -> SmoothReservoirModel:
    return SmoothReservoirModel.from_B_u(
        state_vector=ImmutableMatrix(state_variable_tuple),
        time_symbol=time_symbol,
        B=B,
        u=ImmutableMatrix(u),
    )
Example #9
0
def lm_sym_expanded(linear_matrix, variables):
    """Return matrix in the form of sum of coefficent matrices times varibles.
    """
    if S(linear_matrix).free_symbols & set(variables):
        coeffs, const = lm_sym_to_coeffs(linear_matrix, variables)
        terms = []
        for i, v in enumerate(variables):
            terms.append(MatMul(ImmutableMatrix(coeffs[i]), v))
        if const.any():
            terms.append(ImmutableMatrix(const))
        return MatAdd(*terms)
    else:
        return linear_matrix
Example #10
0
def test_Equality():
    assert Equality(IM, IM) is S.true
    assert Unequality(IM, IM) is S.false
    assert Equality(IM, IM.subs(1, 2)) is S.false
    assert Unequality(IM, IM.subs(1, 2)) is S.true
    assert Equality(IM, 2) is S.false
    assert Unequality(IM, 2) is S.true
    M = ImmutableMatrix([x, y])
    assert Equality(M, IM) is S.false
    assert Unequality(M, IM) is S.true
    assert Equality(M, M.subs(x, 2)).subs(x, 2) is S.true
    assert Unequality(M, M.subs(x, 2)).subs(x, 2) is S.false
    assert Equality(M, M.subs(x, 2)).subs(x, 3) is S.false
    assert Unequality(M, M.subs(x, 2)).subs(x, 3) is S.true
Example #11
0
def test_representations():
    A = ImmutableMatrix([
        [-1,0,0, 0],
        [0,-1,0, 0],
        [0,0,-1, 0],
        [0, 1, 1, 0],
    ])
    b = ImmutableMatrix([0,0,0,1])
    V, S = V_representation(A, b)
    assert V == {ImmutableMatrix([0,0,0,0]), ImmutableMatrix([0,1,0,0]), ImmutableMatrix([0,0,1,0])}
    assert S == {ImmutableMatrix([1,0,0,0]), ImmutableMatrix([0,0,0,1]), ImmutableMatrix([0,0,0,-1])}
    A_H, b_H = H_representation(V, S)
    V_H, S_H = V_representation(A_H, b_H)
    assert set(map(lambda x: ImmutableMatrix(x[:4]), V_H)) == V
    assert set(map(lambda x: ImmutableMatrix(x[:4]), S_H)) == S
Example #12
0
def python_string_to_sympy(string_expression: tuple_of(tuple_of(str)), x_symb: (Matrix, MatrixSymbol, None), mu_symb: (Matrix, MatrixSymbol, None)):
    assert all([len(si) == len(string_expression[0]) for si in string_expression[1:]])
    sympy_expression = zeros(len(string_expression), len(string_expression[0]))
    for (i, si) in enumerate(string_expression):
        for (j, sij) in enumerate(si):
            sympy_expression[i, j] = sympify(sij, locals={"x": x_symb, "mu": mu_symb})
    return ImmutableMatrix(sympy_expression)
Example #13
0
def python_string_to_sympy(string_expression: tuple_of(str),
                           x_symb: (Matrix, MatrixSymbol, None),
                           mu_symb: (Matrix, MatrixSymbol, None)):
    sympy_expression = zeros(len(string_expression), 1)
    for (i, si) in enumerate(string_expression):
        sympy_expression[i] = sympify(si, locals={"x": x_symb, "mu": mu_symb})
    return ImmutableMatrix(sympy_expression)
    def myhash(self):
        """
        Compute a hash considering SOME but NOT ALL properties of a
        model run. The function's main use is to detect saved state transition
        operator cashes that are no longer compatible with the model run object
        that wants to use them. This check is useful but NOT COMPREHENSIVE.
        """
        times = self.times

        def make_hash_sha256(o):
            hasher = hashlib.sha256()
#            hasher.update(repr(make_hashable(o)).encode())
            hasher.update(repr(o).encode())
            return base64.b64encode(hasher.digest()).decode()

        return make_hash_sha256(
            (
                frozendict(self.model.input_fluxes),
                frozendict(self.model.internal_fluxes),
                frozendict(self.model.output_fluxes),
                ImmutableMatrix(self.model.state_vector),
                self.parameter_dicts,
                self.start_values,
                (times[0], times[-1]),
                tuple(self.disc_times)
            )
        )
Example #15
0
def test_ContinuousMarkovChain():
    T1 = Matrix([[S(-2), S(2), S.Zero],
                 [S.Zero, S.NegativeOne, S.One],
                 [Rational(3, 2), Rational(3, 2), S(-3)]])
    C1 = ContinuousMarkovChain('C', [0, 1, 2], T1)
    assert C1.limiting_distribution() == ImmutableMatrix([[Rational(3, 19), Rational(12, 19), Rational(4, 19)]])

    T2 = Matrix([[-S.One, S.One, S.Zero], [S.One, -S.One, S.Zero], [S.Zero, S.One, -S.One]])
    C2 = ContinuousMarkovChain('C', [0, 1, 2], T2)
    A, t = C2.generator_matrix, symbols('t', positive=True)
    assert C2.transition_probabilities(A)(t) == Matrix([[S.Half + exp(-2*t)/2, S.Half - exp(-2*t)/2, 0],
                                                       [S.Half - exp(-2*t)/2, S.Half + exp(-2*t)/2, 0],
                                                       [S.Half - exp(-t) + exp(-2*t)/2, S.Half - exp(-2*t)/2, exp(-t)]])
    with ignore_warnings(UserWarning): ### TODO: Restore tests once warnings are removed
        assert P(Eq(C2(1), 1), Eq(C2(0), 1), evaluate=False) == Probability(Eq(C2(1), 1), Eq(C2(0), 1))
    assert P(Eq(C2(1), 1), Eq(C2(0), 1)) == exp(-2)/2 + S.Half
    assert P(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 1),
                Eq(P(Eq(C2(1), 0)), S.Half)) == (Rational(1, 4) - exp(-2)/4)*(exp(-2)/2 + S.Half)
    assert P(Not(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)) |
                (Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)),
                Eq(P(Eq(C2(1), 0)), Rational(1, 4)) & Eq(P(Eq(C2(1), 1)), Rational(1, 4))) is S.One
    assert E(C2(Rational(3, 2)), Eq(C2(0), 2)) == -exp(-3)/2 + 2*exp(Rational(-3, 2)) + S.Half
    assert variance(C2(Rational(3, 2)), Eq(C2(0), 1)) == ((S.Half - exp(-3)/2)**2*(exp(-3)/2 + S.Half)
                                                    + (Rational(-1, 2) - exp(-3)/2)**2*(S.Half - exp(-3)/2))
    raises(KeyError, lambda: P(Eq(C2(1), 0), Eq(P(Eq(C2(1), 1)), S.Half)))
    assert P(Eq(C2(1), 0), Eq(P(Eq(C2(5), 1)), S.Half)) == Probability(Eq(C2(1), 0))
    TS1 = MatrixSymbol('G', 3, 3)
    CS1 = ContinuousMarkovChain('C', [0, 1, 2], TS1)
    A = CS1.generator_matrix
    assert CS1.transition_probabilities(A)(t) == exp(t*A)

    C3 = ContinuousMarkovChain('C', [Symbol('0'), Symbol('1'), Symbol('2')], T2)
    assert P(Eq(C3(1), 1), Eq(C3(0), 1)) == exp(-2)/2 + S.Half
    assert P(Eq(C3(1), Symbol('1')), Eq(C3(0), Symbol('1'))) == exp(-2)/2 + S.Half
Example #16
0
def test_ContinuousMarkovChain():
    T1 = Matrix([[S(-2), S(2), S(0)],
                 [S(0), S(-1), S(1)],
                 [S(3)/2, S(3)/2, S(-3)]])
    C1 = ContinuousMarkovChain('C', [0, 1, 2], T1)
    assert C1.limiting_distribution() == ImmutableMatrix([[S(3)/19, S(12)/19, S(4)/19]])

    T2 = Matrix([[-S(1), S(1), S(0)], [S(1), -S(1), S(0)], [S(0), S(1), -S(1)]])
    C2 = ContinuousMarkovChain('C', [0, 1, 2], T2)
    A, t = C2.generator_matrix, symbols('t', positive=True)
    assert C2.transition_probabilities(A)(t) == Matrix([[S(1)/2 + exp(-2*t)/2, S(1)/2 - exp(-2*t)/2, 0],
                                                       [S(1)/2 - exp(-2*t)/2, S(1)/2 + exp(-2*t)/2, 0],
                                                       [S(1)/2 - exp(-t) + exp(-2*t)/2, S(1)/2 - exp(-2*t)/2, exp(-t)]])
    assert P(Eq(C2(1), 1), Eq(C2(0), 1), evaluate=False) == Probability(Eq(C2(1), 1))
    assert P(Eq(C2(1), 1), Eq(C2(0), 1)) == exp(-2)/2 + S(1)/2
    assert P(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 1),
                Eq(P(Eq(C2(1), 0)), S(1)/2)) == (S(1)/4 - exp(-2)/4)*(exp(-2)/2 + S(1)/2)
    assert P(Not(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)) |
                (Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)),
                Eq(P(Eq(C2(1), 0)), S(1)/4) & Eq(P(Eq(C2(1), 1)), S(1)/4)) == S(1)
    assert E(C2(S(3)/2), Eq(C2(0), 2)) == -exp(-3)/2 + 2*exp(-S(3)/2) + S(1)/2
    assert variance(C2(S(3)/2), Eq(C2(0), 1)) == ((S(1)/2 - exp(-3)/2)**2*(exp(-3)/2 + S(1)/2)
                                                    + (-S(1)/2 - exp(-3)/2)**2*(S(1)/2 - exp(-3)/2))
    raises(KeyError, lambda: P(Eq(C2(1), 0), Eq(P(Eq(C2(1), 1)), S(1)/2)))
    assert P(Eq(C2(1), 0), Eq(P(Eq(C2(5), 1)), S(1)/2)) == Probability(Eq(C2(1), 0))
    TS1 = MatrixSymbol('G', 3, 3)
    CS1 = ContinuousMarkovChain('C', [0, 1, 2], TS1)
    A = CS1.generator_matrix
    assert CS1.transition_probabilities(A)(t) == exp(t*A)
Example #17
0
    def _transient2absorbing(self):
        """
        Computes the one step probabilities of transient
        states to absorbing states. Used in finding
        fundamental matrix, absorbing probabilties.
        """
        trans_probs = self.transition_probabilities
        if not isinstance(trans_probs, ImmutableMatrix):
            return None

        m, trans_states, absorb_states = \
            trans_probs.shape[0], [], []
        for i in range(m):
            if trans_probs[i, i] == 1:
                absorb_states.append(i)
            else:
                trans_states.append(i)

        if not absorb_states or not trans_states:
            return None

        t2a = [[trans_probs[si, sj] for sj in absorb_states]
               for si in trans_states]

        return ImmutableMatrix(t2a)
Example #18
0
def test_as_immutable():
    data = [[1, 2], [3, 4]]
    X = Matrix(data)
    assert sympify(X) == X.as_immutable() == ImmutableMatrix(data)

    data = {(0, 0): 1, (0, 1): 2, (1, 0): 3, (1, 1): 4}
    X = SparseMatrix(2, 2, data)
    assert sympify(X) == X.as_immutable() == ImmutableSparseMatrix(2, 2, data)
Example #19
0
 def fundamental_matrix(self):
     Q = self._transient2transient()
     if Q == None:
         return None
     I = eye(Q.shape[0])
     if (I - Q).det() == 0:
         raise ValueError("Fundamental matrix doesn't exists.")
     return ImmutableMatrix((I - Q).inv().tolist())
Example #20
0
def wigner_d(J, alpha, beta, gamma):
    u"""Return the Wigner D matrix for angular momentum J.

    INPUT:

    -  ``J`` - An integer, half-integer, or sympy symbol for the total angular
        momentum of the angular momentum space being rotated.

    -  ``alpha``, ``beta``, ``gamma`` - Real numbers representing the Euler
        angles of rotation about the so-called vertical, line of nodes, and
        figure axes. See [Edmonds74]_.

    OUTPUT:

    A matrix representing the corresponding Euler angle rotation( in the basis
    of eigenvectors of `J_z`).

    .. math ::
        \\mathcal{D}_{\\alpha \\beta \\gamma} =
        \\exp\\big( \\frac{i\\alpha}{\\hbar} J_z\\big)
        \\exp\\big( \\frac{i\\beta}{\\hbar} J_y\\big)
        \\exp\\big( \\frac{i\\gamma}{\\hbar} J_z\\big)

    The components are calculated using the general form [Edmonds74]_,
    equation 4.1.12.

    Examples
    ========

    The simplest possible example:

    >>> from sympy.physics.wigner import wigner_d
    >>> from sympy import Integer, symbols, pprint
    >>> from sympy.physics.wigner import wigner_d_small
    >>> half = 1/Integer(2)
    >>> alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
    >>> pprint(wigner_d(half, alpha, beta, gamma), use_unicode=True)
    ⎡  ⅈ⋅α  ⅈ⋅γ             ⅈ⋅α  -ⅈ⋅γ         ⎤
    ⎢  ───  ───             ───  ─────        ⎥
    ⎢   2    2     ⎛β⎞       2     2      ⎛β⎞ ⎥
    ⎢ ℯ   ⋅ℯ   ⋅cos⎜─⎟     ℯ   ⋅ℯ     ⋅sin⎜─⎟ ⎥
    ⎢              ⎝2⎠                    ⎝2⎠ ⎥
    ⎢                                         ⎥
    ⎢  -ⅈ⋅α   ⅈ⋅γ          -ⅈ⋅α   -ⅈ⋅γ        ⎥
    ⎢  ─────  ───          ─────  ─────       ⎥
    ⎢    2     2     ⎛β⎞     2      2      ⎛β⎞⎥
    ⎢-ℯ     ⋅ℯ   ⋅sin⎜─⎟  ℯ     ⋅ℯ     ⋅cos⎜─⎟⎥
    ⎣                ⎝2⎠                   ⎝2⎠⎦

    """
    d = wigner_d_small(J, beta)
    M = [J - i for i in range(2 * J + 1)]
    D = [[
        exp(I * Mi * alpha) * d[i, j] * exp(I * Mj * gamma)
        for j, Mj in enumerate(M)
    ] for i, Mi in enumerate(M)]
    return ImmutableMatrix(D)
Example #21
0
    def test_creation(self):
        a, b, c = symbols('a b c')
        In = VegetationCarbonInputTuple((a, b))
        self.assertEqual(type(In), VegetationCarbonInputTuple)

        J = In.subs({b: c})
        self.assertEqual(type(J), VegetationCarbonInputTuple)

        In = VegetationCarbonInputTuple((1, 1))
        self.assertEqual(type(In), VegetationCarbonInputTuple)

        M = Matrix((1, 1))
        In = VegetationCarbonInputTuple(M)
        self.assertEqual(type(In), VegetationCarbonInputTuple)

        I1 = ImmutableMatrix(2, 1, [1, 3])
        I2 = ImmutableMatrix(2, 1, [1, 3])
        In = VegetationCarbonInputTuple((I1+I2))
        self.assertEqual(type(In), VegetationCarbonInputTuple)
        self.assertEqual(In[0, 0], 2)
        self.assertEqual(In[1, 0], 6)
Example #22
0
    def _check_orthogonality(equations):
        """
        Helper method for _connect_to_cartesian. It checks if
        set of transformation equations create orthogonal curvilinear
        coordinate system

        Parameters
        ==========

        equations : Lambda
            Lambda of transformation equations

        """

        x1, x2, x3 = symbols("x1, x2, x3", cls=Dummy)
        equations = equations(x1, x2, x3)
        v1 = Matrix([diff(equations[0], x1),
                     diff(equations[1], x1), diff(equations[2], x1)])

        v2 = Matrix([diff(equations[0], x2),
                     diff(equations[1], x2), diff(equations[2], x2)])

        v3 = Matrix([diff(equations[0], x3),
                     diff(equations[1], x3), diff(equations[2], x3)])

        if any(simplify(i[0] + i[1] + i[2]) == 0 for i in (v1, v2, v3)):
            return False
        else:
            if simplify(v1.dot(v2)) == 0 and simplify(v2.dot(v3)) == 0 \
                and simplify(v3.dot(v1)) == 0:
                return True
            else:
                return False
Example #23
0
    def _check_orthogonality(self):
        """
        Helper method for _connect_to_cartesian. It checks if
        set of transformation equations create orthogonal curvilinear
        coordinate system

        Parameters
        ==========

        equations : tuple
            Tuple of transformation equations

        """

        eq = self._transformation_equations()

        v1 = Matrix([diff(eq[0], self.x), diff(eq[1], self.x), diff(eq[2], self.x)])
        v2 = Matrix([diff(eq[0], self.y), diff(eq[1], self.y), diff(eq[2], self.y)])
        v3 = Matrix([diff(eq[0], self.z), diff(eq[1], self.z), diff(eq[2], self.z)])

        if any(simplify(i[0] + i[1] + i[2]) == 0 for i in (v1, v2, v3)):
            return False
        else:
            if simplify(v1.dot(v2)) == 0 and simplify(v2.dot(v3)) == 0 and simplify(v3.dot(v1)) == 0:
                return True
            else:
                return False
Example #24
0
    def _check_orthogonality(self):
        """
        Helper method for _connect_to_cartesian. It checks if
        set of transformation equations create orthogonal curvilinear
        coordinate system

        Parameters
        ==========

        equations : tuple
            Tuple of transformation equations

        """

        eq = self._transformation_equations()

        v1 = Matrix([diff(eq[0], self.x), diff(eq[1], self.x), diff(eq[2], self.x)])
        v2 = Matrix([diff(eq[0], self.y), diff(eq[1], self.y), diff(eq[2], self.y)])
        v3 = Matrix([diff(eq[0], self.z), diff(eq[1], self.z), diff(eq[2], self.z)])

        if any(simplify(i[0] + i[1] + i[2]) == 0 for i in (v1, v2, v3)):
            return False
        else:
            if simplify(v1.dot(v2)) == 0 and simplify(v2.dot(v3)) == 0 and simplify(v3.dot(v1)) == 0:
                return True
            else:
                return False
Example #25
0
 def lift(self, M):
     if M.rows == M.cols:
         i = 0
         h = self.as_mutable().col_join(ImmutableMatrix([0]))
         while True:
             h[-1] = i
             echelon_form = M.row_join(h).rref()[0]
             coeffs = echelon_form[:, -1].values()
             if all(val.is_integer for val in coeffs):
                 return BasisElement(h)
             i = i + 1
     else:
         return M * M[:M.cols, :M.cols].solve(self[:M.cols, :M.cols])
Example #26
0
 def limiting_distribution(self):
     gen_mat = self.generator_matrix
     if gen_mat == 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]])
Example #27
0
def test_ContinuousMarkovChain():
    T1 = Matrix([
        [S(-2), S(2), S.Zero],
        [S.Zero, S.NegativeOne, S.One],
        [Rational(3, 2), Rational(3, 2), S(-3)],
    ])
    C1 = ContinuousMarkovChain("C", [0, 1, 2], T1)
    assert C1.limiting_distribution() == ImmutableMatrix(
        [[Rational(3, 19), Rational(12, 19),
          Rational(4, 19)]])

    T2 = Matrix([[-S.One, S.One, S.Zero], [S.One, -S.One, S.Zero],
                 [S.Zero, S.One, -S.One]])
    C2 = ContinuousMarkovChain("C", [0, 1, 2], T2)
    A, t = C2.generator_matrix, symbols("t", positive=True)
    assert C2.transition_probabilities(A)(t) == Matrix([
        [S.Half + exp(-2 * t) / 2, S.Half - exp(-2 * t) / 2, 0],
        [S.Half - exp(-2 * t) / 2, S.Half + exp(-2 * t) / 2, 0],
        [
            S.Half - exp(-t) + exp(-2 * t) / 2, S.Half - exp(-2 * t) / 2,
            exp(-t)
        ],
    ])
    assert P(Eq(C2(1), 1), Eq(C2(0), 1),
             evaluate=False) == Probability(Eq(C2(1), 1))
    assert P(Eq(C2(1), 1), Eq(C2(0), 1)) == exp(-2) / 2 + S.Half
    assert P(
        Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 1),
        Eq(P(Eq(C2(1), 0)),
           S.Half)) == (Rational(1, 4) - exp(-2) / 4) * (exp(-2) / 2 + S.Half)
    assert (P(
        Not(Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2))
        | (Eq(C2(1), 0) & Eq(C2(2), 1) & Eq(C2(3), 2)),
        Eq(P(Eq(C2(1), 0)), Rational(1, 4))
        & Eq(P(Eq(C2(1), 1)), Rational(1, 4)),
    ) is S.One)
    assert (E(C2(Rational(3, 2)),
              Eq(C2(0),
                 2)) == -exp(-3) / 2 + 2 * exp(Rational(-3, 2)) + S.Half)
    assert variance(C2(Rational(3, 2)), Eq(
        C2(0),
        1)) == ((S.Half - exp(-3) / 2)**2 * (exp(-3) / 2 + S.Half) +
                (Rational(-1, 2) - exp(-3) / 2)**2 * (S.Half - exp(-3) / 2))
    raises(KeyError, lambda: P(Eq(C2(1), 0), Eq(P(Eq(C2(1), 1)), S.Half)))
    assert P(Eq(C2(1), 0), Eq(P(Eq(C2(5), 1)),
                              S.Half)) == Probability(Eq(C2(1), 0))
    TS1 = MatrixSymbol("G", 3, 3)
    CS1 = ContinuousMarkovChain("C", [0, 1, 2], TS1)
    A = CS1.generator_matrix
    assert CS1.transition_probabilities(A)(t) == exp(t * A)
Example #28
0
 def fixed_row_vector(self):
     trans_probs = self.transition_probabilities
     if trans_probs == None:
         return None
     if isinstance(trans_probs, MatrixSymbol):
         wm = MatrixSymbol('wm', 1, trans_probs.shape[0])
         return Lambda((wm, trans_probs), Eq(wm * trans_probs, wm))
     w = IndexedBase('w')
     wi = [w[i] for i in range(trans_probs.shape[0])]
     wm = Matrix([wi])
     eqs = (wm * trans_probs - wm).tolist()[0]
     eqs.append(sum(wi) - 1)
     soln = list(linsolve(eqs, wi))[0]
     return ImmutableMatrix([[sol for sol in soln]])
Example #29
0
def input_tuple(
    ifl: InFluxesBySymbol,
    svt: StateVariableTuple
) -> InputTuple:
    in_fluxes_by_index = hr.to_int_keys_1(ifl, svt)
    ks = in_fluxes_by_index.keys()
    v = ImmutableMatrix(
        list(
            map(
                lambda ind: in_fluxes_by_index[ind] if ind in ks else 0,  
                range(len(svt))
            )
        )
    )
    return InputTuple(v)
    def _transient2transient(self):
        """
        Computes the one step probabilities of transient
        states to transient states. Used in finding
        fundamental matrix, absorbing probabilties.
        """
        trans_probs = self.transition_probabilities
        if not isinstance(trans_probs, ImmutableMatrix):
            return None

        m = trans_probs.shape[0]
        trans_states = [i for i in range(m) if trans_probs[i, i] != 1]
        t2t = [[trans_probs[si, sj] for sj in trans_states] for si in trans_states]

        return ImmutableMatrix(t2t)
Example #31
0
def test_block_index():
    I = Identity(3)
    Z = ZeroMatrix(3, 3)
    B = BlockMatrix([[I, I], [I, I]])
    e3 = ImmutableMatrix(eye(3))
    BB = BlockMatrix([[e3, e3], [e3, e3]])
    assert B[0, 0] == B[3, 0] == B[0, 3] == B[3, 3] == 1
    assert B[4, 3] == B[5, 1] == 0

    BB = BlockMatrix([[e3, e3], [e3, e3]])
    assert B.as_explicit() == BB.as_explicit()

    BI = BlockMatrix([[I, Z], [Z, I]])

    assert BI.as_explicit().equals(eye(6))
Example #32
0
def cursor_to_matrix(cursor, mutable=False):
    """ Consume and extract the entire result as a
    `sympy.Matrix <https://docs.sympy.org/latest/tutorial/matrices.html>`_.

    .. note::
       This method requires `sympy` to be installed.

    :param cursor:
    :param mutable:
    :returns: `Matrix
        <https://docs.sympy.org/latest/tutorial/matrices.html>`_ object.
    """
    if mutable:
        return MutableMatrix(list(map(list, cursor)))
    else:
        return ImmutableMatrix(list(map(list, cursor)))
Example #33
0
def test_subs():
    A = ImmutableMatrix([[1, 2], [3, 4]])
    B = ImmutableMatrix([[1, 2], [x, 4]])
    C = ImmutableMatrix([[-x, x*y], [-(x + y), y**2]])
    assert B.subs(x, 3) == A
    assert (x*B).subs(x, 3) == 3*A
    assert (x*eye(2) + B).subs(x, 3) == 3*eye(2) + A
    assert C.subs([[x, -1], [y, -2]]) == A
    assert C.subs([(x, -1), (y, -2)]) == A
    assert C.subs({x: -1, y: -2}) == A
    assert C.subs({x: y - 1, y: x - 1}, simultaneous=True) == \
        ImmutableMatrix([[1 - y, (x - 1)*(y - 1)], [2 - x - y, (x - 1)**2]])
Example #34
0
def test_Equality():
    assert Equality(IM, IM) is S.true
    assert Unequality(IM, IM) is S.false
    assert Equality(IM, IM.subs(1, 2)) is S.false
    assert Unequality(IM, IM.subs(1, 2)) is S.true
    assert Equality(IM, 2) is S.false
    assert Unequality(IM, 2) is S.true
    M = ImmutableMatrix([x, y])
    assert Equality(M, IM) is S.false
    assert Unequality(M, IM) is S.true
    assert Equality(M, M.subs(x, 2)).subs(x, 2) is S.true
    assert Unequality(M, M.subs(x, 2)).subs(x, 2) is S.false
    assert Equality(M, M.subs(x, 2)).subs(x, 3) is S.false
    assert Unequality(M, M.subs(x, 2)).subs(x, 3) is S.true