Exemple #1
0
def generate_linear_instance(num_var, num_pieces, seed=None):
    A = [
        sp.randMatrix(num_var, min=_min, max=_max, seed=seed)
        for _ in range(num_pieces)
    ]
    v = [
        sp.randMatrix(num_var, c=1, min=_min, max=_max, seed=seed)
        for _ in range(num_pieces - 1)
    ]
    x = sp.randMatrix(num_var, c=1, min=_min, max=_max, seed=seed)
    return A, x, v
Exemple #2
0
    def test_siso_place(self):

        n = 6
        A = sp.randMatrix(n, n, seed=1648, min=-10, max=10)
        b = sp.randMatrix(n, 1, seed=1649, min=-10, max=10)
        ev = np.sort(np.random.random(n) * 10)

        f = st.siso_place(A, b, ev)

        A2 = st.to_np(A + b * f.T)
        ev2 = np.sort(np.linalg.eigvals(A2))

        diff = np.sum(np.abs((ev - ev2) / ev))
        self.assertTrue(diff < 1e-6)
Exemple #3
0
    def test_siso_place2(self):

        n = 4
        A = sp.randMatrix(n, n, seed=1648, min=-10, max=10)
        b = sp.randMatrix(n, 1, seed=1649, min=-10, max=10)

        omega = np.pi * 2 / 2.0
        ev = np.sort([1j * omega, -1j * omega, -2, -3])
        f = st.siso_place(A, b, ev)

        A2 = st.to_np(A + b * f.T)
        ev2 = np.sort(np.linalg.eigvals(A2))
        diff = np.sum(np.abs((ev - ev2) / ev))

        self.assertTrue(diff < 1e-6)
Exemple #4
0
    def setUp(self):
        n = 5
        self.ev = sp.randMatrix(n, 1, seed=1631)
        d = sp.diag(*self.ev)

        self.T = T = sp.randMatrix(n, n, seed=1632)
        assert not T.det() == 0
        self.M1 = T * d * T.inv()

        self.ev_sorted = list(self.ev)
        self.ev_sorted.sort(reverse=True)

        # #

        self.M2 = sp.Matrix([[0, 1], [-1, 0]])
Exemple #5
0
    def test_solve_linear_system1(self):
        M = sp.randMatrix(3, 8, seed=1131)
        xx = sp.Matrix(sp.symbols('x1:9'))
        bb = sp.Matrix(sp.symbols('b1:4'))

        eqns = M * xx + bb

        sol1 = sp.solve(eqns, xx)
        sol2 = st.solve_linear_system(eqns, xx)

        self.assertEqual(xx.subs(sol1) - xx.subs(sol2), xx * 0)

        # symbolic coefficient matrix
        # this is (currently) not possible with sp.solve
        # (additionally add a zero line)
        M2 = st.symbMatrix(4, 8)
        bb2 = sp.Matrix(sp.symbols('b1:5'))
        eqns = M2 * xx + bb2

        eqns[-1, :] *= 0
        sol3 = st.solve_linear_system(eqns, xx)

        res = eqns.subs(sol3)
        res.simplify()

        self.assertEqual(res, res * 0)
Exemple #6
0
def get_random_A(dim=3, valid=True, diagonal=True, ints=True, max_val=1e+3):
    """

    :param dim: dimension of A
    :param valid: True iff A's eigenvalues are all negative
    :param diagonal: if True, A will be diagonal
    :param ints: A will have only integer elements
    :param max_val: max value of A if diagonal, else the square of the max value
    :return: A
    """
    max_val = int(max_val)
    sgn = -1 if valid else 1
    r = random.randint if ints else random.uniform
    diag = set()
    # generate n unique numbers
    for x in itertools.takewhile(lambda x: len(diag) < dim, _grand(r, 1, max_val, int=ints)):
        diag.add(sgn * x)
    D = sp.diag(*diag)
    if not diagonal:
        M = sp.Matrix([[sp.nan]])
        while any(x == sp.nan for x in M):  # avoid nan (due to X)
            X = sp.randMatrix(dim, dim, min=-max_val, max=max_val, seed=int(time.time() * 1000))
            # eigenvals from D: det(XDX^-1 -tI) = det(X(D-tI)X^-1) = det(D-tI)
            M = X * D * (X ** -1)
        return M
    else:
        return D  # diagonal matrix with -r values
Exemple #7
0
def validate_dba_db(dba_db, exp, log, dim, a=None, b=None):
    if not a:
        a = sy.randMatrix(dim, 1, -1e6, 1e6) * 1e-6
    if not b:
        b = sy.randMatrix(dim, 1, -1e6, 1e6) * 1e-6

    numeric = sy.zeros(dim, dim)

    for i in range(dim):
        dx = sy.zeros(dim, 1)
        dx[i] = 1e-6

        w1 = log(exp(a)**-1 * exp(b))
        w2 = log(exp(a)**-1 * exp(dx) * exp(b))

        numeric[:, i] = (w2 - w1) / 1e-6

    symbolic = dba_db(a, b)

    check_matrices(numeric, symbolic, a, b)
Exemple #8
0
    def test_create_simfunction2(self):
        x1, x2, x3, x4 = xx = sp.Matrix(sp.symbols("x1, x2, x3, x4"))
        u1, u2 = uu = sp.Matrix(sp.symbols("u1, u2"))  # inputs
        p1, p2, p3, p4 = pp = sp.Matrix(
            sp.symbols("p1, p2, p3, p4"))  # parameter
        t = sp.Symbol('t')

        A = A0 = sp.randMatrix(len(xx), len(xx), -10, 10, seed=704)
        B = B0 = sp.randMatrix(len(xx), len(uu), -10, 10, seed=705)

        v1 = A[0, 0]
        A[0, 0] = p1
        v2 = A[2, -1]
        A[2, -1] = p2
        v3 = B[3, 0]
        B[3, 0] = p3
        v4 = B[2, 1]
        B[2, 1] = p4

        par_vals = lzip(pp, [v1, v2, v3, v4])

        f = A * xx
        G = B

        fxu = (f + G * uu).subs(par_vals)

        # some random initial values
        x0 = st.to_np(sp.randMatrix(len(xx), 1, -10, 10, seed=706)).squeeze()
        u0 = st.to_np(sp.randMatrix(len(uu), 1, -10, 10, seed=2257)).squeeze()

        # create the model and the rhs-function
        mod = st.SimulationModel(f, G, xx, par_vals)
        rhs_xx_uu = mod.create_simfunction(free_input_args=True)

        res0_1 = rhs_xx_uu(x0, u0, 0)
        dres0_1 = st.to_np(fxu.subs(lzip(xx, x0) + lzip(uu, u0))).squeeze()

        bin_res01 = np.isclose(res0_1, dres0_1)  # binary array
        self.assertTrue(np.all(bin_res01))
Exemple #9
0
    def test_num_trajectory_compatibility_test(self):
        x1, x2, x3, x4 = xx = sp.Matrix(sp.symbols("x1, x2, x3, x4"))
        u1, u2 = uu = sp.Matrix(sp.symbols("u1, u2"))  # inputs

        t = sp.Symbol('t')

        # we want to create a random but stable matrix

        np.random.seed(2805)
        diag = np.diag(np.random.random(len(xx)) * -10)
        T = sp.randMatrix(len(xx), len(xx), -10, 10, seed=704)
        Tinv = T.inv()

        A = Tinv * diag * T

        B = B0 = sp.randMatrix(len(xx), len(uu), -10, 10, seed=705)

        x0 = st.to_np(sp.randMatrix(len(xx), 1, -10, 10, seed=706)).squeeze()
        tt = np.linspace(0, 5, 2000)

        des_input = st.piece_wise((2 - t, t <= 1), (t, t < 2),
                                  (2 * t - 2, t < 3), (4, True))
        des_input_func_vec = st.expr_to_func(t,
                                             sp.Matrix([des_input, des_input]))

        mod2 = st.SimulationModel(A * xx, B, xx)
        rhs3 = mod2.create_simfunction(input_function=des_input_func_vec)
        XX = sc.integrate.odeint(rhs3, x0, tt)
        UU = des_input_func_vec(tt)

        res1 = mod2.num_trajectory_compatibility_test(tt, XX, UU)
        self.assertTrue(res1)

        # slightly different input signal -> other results
        res2 = mod2.num_trajectory_compatibility_test(tt, XX, UU * 1.1)
        self.assertFalse(res2)
Exemple #10
0
    def test_partial_trace2(self):
        import sympy as sp
        dm = sp.randMatrix(2**4, 2**4)
        dm1 = partial_trace(dm, 4, [0, 2, 3])
        dm2 = partial_trace(dm, 4, [0, 1, 2])
        dm3 = partial_trace(dm, 4, [0, 2])

        T1_0 = dm1[0, 0]
        T3_0 = dm2[0, 0]
        T13_00 = dm3[0, 0]
        T13_01 = dm3[1, 1]
        T13_10 = dm3[2, 2]
        T13_11 = dm3[3, 3]

        self.assertEqual(T1_0, T13_00 + T13_01)
        self.assertEqual(T3_0, T13_00 + T13_10)
Exemple #11
0
def validate_dw_dw(dw_dw, exp, log, dim, w=None):
    if not w:
        w = sy.randMatrix(dim, 1, -1e6, 1e6) * 1e-6

    numeric = sy.zeros(dim, dim)

    for i in range(dim):
        dx = sy.zeros(dim, 1)
        dx[i] = 1e-6

        w2 = log(exp(dx) * exp(w))

        numeric[:, i] = (w2 - w) / 1e-6

    symbolic = dw_dw(w)

    check_matrices(numeric, symbolic, w, None)
Exemple #12
0
def test_random():
    M = randMatrix(3, 3)
    M = randMatrix(3, 3, seed=3)
    M = randMatrix(3, 4, 0, 150)
Exemple #13
0
#!/usr/bin/env python

from random import randrange
from sympy import Matrix, pprint, randMatrix, N, eye
from sympy.printing.str import StrPrinter
from sympy.abc import x

filename = "test_nml_mat_lup_solve.data"

num_tests = 400
min_M_cols = 1
min_M_rows = 1
max_M_cols = 25
max_M_rows = 25
min_val = 0
max_val = 100

fs = open(filename, "w")

fs.write("{}".format(num_tests))

for i in range(num_tests):
    M_dim = randrange(min_M_cols, max_M_cols)
    M = randMatrix(M_dim, M_dim, min=min_val, max=max_val, percent=100)
    print("Creating test case: ", i)
    fs.write("\n{} {}\n".format(M_dim, M_dim))
    fs.write(M.table(StrPrinter(), rowstart="", rowend="", colsep="\t"))

fs.close()
Exemple #14
0
import sympy as sp
import numpy as np
quat_vars = sp.symbols('q:4')
theta_vars = sp.symbols('theta:3')

g = sp.Quaternion(*quat_vars) * sp.Quaternion(1, *theta_vars)
g_mat = sp.Matrix([getattr(g, att) for att in 'abcd'])
G = g_mat.jacobian(theta_vars)

for i in range(1):
    quat_this = sp.Quaternion(*np.random.uniform(-1, 1, 4)).normalize()
    subdict = dict(zip(quat_vars, [getattr(quat_this, att) for att in 'abcd']))
    G_this = G.subs(subdict)
    P_this = sp.randMatrix(3, 3)
    P_this = P_this * P_this.T
    Pq = G_this * sp.randMatrix(3, 3) * G_this.T
Exemple #15
0
    def test_create_simfunction(self):
        x1, x2, x3, x4 = xx = sp.Matrix(sp.symbols("x1, x2, x3, x4"))
        u1, u2 = uu = sp.Matrix(sp.symbols("u1, u2"))  # inputs
        p1, p2, p3, p4 = pp = sp.Matrix(
            sp.symbols("p1, p2, p3, p4"))  # parameter
        t = sp.Symbol('t')

        A = A0 = sp.randMatrix(len(xx), len(xx), -10, 10, seed=704)
        B = B0 = sp.randMatrix(len(xx), len(uu), -10, 10, seed=705)

        v1 = A[0, 0]
        A[0, 0] = p1
        v2 = A[2, -1]
        A[2, -1] = p2
        v3 = B[3, 0]
        B[3, 0] = p3
        v4 = B[2, 1]
        B[2, 1] = p4

        par_vals = lzip(pp, [v1, v2, v3, v4])

        f = A * xx
        G = B

        fxu = (f + G * uu).subs(par_vals)

        # some random initial values
        x0 = st.to_np(sp.randMatrix(len(xx), 1, -10, 10, seed=706)).squeeze()

        # Test handling of unsubstituted parameters
        mod = st.SimulationModel(f, G, xx, model_parameters=par_vals[1:])
        with self.assertRaises(ValueError) as cm:
            rhs0 = mod.create_simfunction()

        self.assertTrue("unexpected symbols" in cm.exception.args[0])

        # create the model and the rhs-function
        mod = st.SimulationModel(f, G, xx, par_vals)
        rhs0 = mod.create_simfunction()
        self.assertFalse(mod.compiler_called)
        self.assertFalse(mod.use_sp2c)

        res0_1 = rhs0(x0, 0)
        dres0_1 = st.to_np(fxu.subs(lzip(xx, x0) + st.zip0(uu))).squeeze()

        bin_res01 = np.isclose(res0_1, dres0_1)  # binary array
        self.assertTrue(np.all(bin_res01))

        # difference should be [0, 0, ..., 0]
        self.assertFalse(np.any(rhs0(x0, 0) - rhs0(x0, 3.7)))

        # simulate
        tt = np.linspace(0, 0.5,
                         100)  # simulation should be short due to instability
        res1 = sc.integrate.odeint(rhs0, x0, tt)

        # create and try sympy_to_c bridge (currently only works on linux
        # and if sympy_to_c is installed (e.g. with `pip install sympy_to_c`))
        # until it is not available for windows we do not want it as a requirement
        # see also https://stackoverflow.com/a/10572833/333403

        try:
            import sympy_to_c
        except ImportError:
            # noinspection PyUnusedLocal
            sympy_to_c = None
            sp2c_available = False
        else:
            sp2c_available = True

        if sp2c_available:

            rhs0_c = mod.create_simfunction(use_sp2c=True)
            self.assertTrue(mod.compiler_called)
            res1_c = sc.integrate.odeint(rhs0_c, x0, tt)
            self.assertTrue(np.all(np.isclose(res1_c, res1)))

            mod.compiler_called = None
            rhs0_c = mod.create_simfunction(use_sp2c=True)
            self.assertTrue(mod.compiler_called is None)

        # proof calculation
        # x(t) = x0*exp(A*t)
        Anum = st.to_np(A.subs(par_vals))
        Bnum = st.to_np(G.subs(par_vals))
        # noinspection PyUnresolvedReferences
        xt = [np.dot(sc.linalg.expm(Anum * T), x0) for T in tt]
        xt = np.array(xt)

        # test whether numeric results are close within given tolerance
        bin_res1 = np.isclose(res1, xt, rtol=2e-5)  # binary array

        self.assertTrue(np.all(bin_res1))

        # test handling of parameter free models:

        mod2 = st.SimulationModel(Anum * xx, Bnum, xx)
        rhs2 = mod2.create_simfunction()
        res2 = sc.integrate.odeint(rhs2, x0, tt)
        self.assertTrue(np.allclose(res1, res2))

        # test input functions
        des_input = st.piece_wise((0, t <= 1), (t, t < 2), (0.5, t < 3),
                                  (1, True))
        des_input_func_scalar = st.expr_to_func(t, des_input)
        des_input_func_vec = st.expr_to_func(t,
                                             sp.Matrix([des_input, des_input]))

        # noinspection PyUnusedLocal
        with self.assertRaises(TypeError) as cm:
            mod2.create_simfunction(input_function=des_input_func_scalar)

        rhs3 = mod2.create_simfunction(input_function=des_input_func_vec)
        # noinspection PyUnusedLocal
        res3_0 = rhs3(x0, 0)

        rhs4 = mod2.create_simfunction(input_function=des_input_func_vec,
                                       time_direction=-1)
        res4_0 = rhs4(x0, 0)

        self.assertTrue(np.allclose(res3_0, np.array([119., -18., -36.,
                                                      -51.])))
        self.assertTrue(np.allclose(res4_0, -res3_0))
Exemple #16
0
from AntColonyOptimizer import AntColonyOptimizer
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import time
import warnings
import sympy
np.random.seed(0)

dist = sympy.randMatrix(r=100, c=100, min=1, max=99, symmetric=True, seed=0)
# sympy 의 인덱스 접근은 [r][c] 형식이 아닌 [r,c]형식

for i in range(100):
    dist[i, i] = 0

dist = np.array(dist, dtype='float64')
print(dist)
optimizer = AntColonyOptimizer(ants=100,
                               evaporation_rate=.1,
                               intensification=2,
                               alpha=1,
                               beta=1,
                               beta_evaporation_rate=0,
                               choose_best=.1)

best = optimizer.fit(dist, 100)
optimizer.plot()
Exemple #17
0
def test_random():
    M = randMatrix(3,3)
    M = randMatrix(3,3,seed=3)
    M = randMatrix(3,4,0,150)
Exemple #18
0
filename = "test_nml_mat_rref.data"

num_tests = 400
min_M_cols = 1
min_M_rows = 1
max_M_cols = 15
max_M_rows = 15
min_val = 0
max_val = 15
percent_min = 90
percent_max = 100

fs = open(filename, "w")

fs.write("{}\n\n".format(num_tests))

for i in range(num_tests):
    M_rows = randrange(min_M_rows, max_M_rows)
    M_cols = randrange(min_M_cols, max_M_cols)
    M = randMatrix(M_rows, M_cols, min=0, max=10, percent=randrange(percent_min, percent_max))
    MRREF = M.rref()[0].applyfunc(N)
    print("Creating test cases: ", i)
    fs.write("{} {}\n".format(M_rows, M_cols))
    fs.write(M.table(StrPrinter(), rowstart="", rowend="", colsep="\t"))
    fs.write("\n")
    fs.write("{} {}\n".format(M_rows, M_cols))
    fs.write(MRREF.table(StrPrinter(), rowstart="", rowend="", colsep="\t"))
    fs.write("\n")


fs.close()