def update_polynomial_coefficients(list_x):
    matrix_A = sm.matrix(
        [[x**k for k in range(len(list_x)-1)] + [ 0 if j==0 else (-1)**j ]  \
               for j,x in enumerate(list_x)])

    vector_b = sm.matrix([sm.sin(x) for x in list_x])

    u = sm.lu_solve(matrix_A, vector_b)

    # a[0],...,a[n], d
    return u[:-1], u[u.rows - 1]
예제 #2
0
def update_polynomial_coefficients(list_x):
    matrix_A = sm.matrix(
        [[x**k for k in range(len(list_x)-1)] + [ 0 if j==0 else (-1)**j ]  \
               for j,x in enumerate(list_x)])

    vector_b = sm.matrix([sm.sin(x) for x in list_x])

    u = sm.lu_solve(matrix_A, vector_b)

    # a[0],...,a[n], d
    return u[:-1], u[u.rows-1]
예제 #3
0
파일: mpmat.py 프로젝트: bayao/qml
def test_msvd():
    output("""\
    msvd_:{[b;x]
        $[3<>count usv:.qml.msvd x;::;
          not (.qml.mdim[u:usv 0]~2#d 0) and (.qml.mdim[v:usv 2]~2#d 1) and
            .qml.mdim[s:usv 1]~d:.qml.mdim x;::;
          not mortho[u] and mortho[v] and
            all[0<=f:.qml.mdiag s] and mzero s _'til d 0;::;
          not mzero x-.qml.mm[u] .qml.mm[s] flip v;::;
          b;1b;(p*/:m#/:u;m#m#/:s;
              (p:(f>.qml.eps*f[0]*max d)*1-2*0>m#u 0)*/:(m:min d)#/:v)]};""")

    for A in subjects:
        U, S, V = map(mp.matrix, mp.svd(mp.matrix(A)))
        m = min(A.rows, A.cols)
        p = mp.diag([mp.sign(s * u) for s, u in zip(mp.chop(S), U[0, :])])
        U *= p
        S = mp.diag(S)
        V = V.T * p
        test("msvd_[0b", A, (U, S, V))

    reps(250)
    for Aq in large_subjects:
        test("msvd_[1b", qstr(Aq), qstr("1b"))
    reps(10000)
예제 #4
0
def test_nstr():
    m = matrix([[0.75, 0.190940654, -0.0299195971],
                [0.190940654, 0.65625, 0.205663228],
                [-0.0299195971, 0.205663228, 0.64453125e-20]])
    assert nstr(m, 4, min_fixed=-inf) == \
    '''[    0.75  0.1909                    -0.02992]
[  0.1909  0.6563                      0.2057]
[-0.02992  0.2057  0.000000000000000000006445]'''
    assert nstr(m, 4) == \
    '''[    0.75  0.1909   -0.02992]
예제 #5
0
def test_nstr():
    m = matrix([[0.75, 0.190940654, -0.0299195971],
                [0.190940654, 0.65625, 0.205663228],
                [-0.0299195971, 0.205663228, 0.64453125e-20]])
    assert nstr(m, 4, min_fixed=-inf) == \
    '''[    0.75  0.1909                    -0.02992]
[  0.1909  0.6563                      0.2057]
[-0.02992  0.2057  0.000000000000000000006445]'''
    assert nstr(m, 4) == \
    '''[    0.75  0.1909   -0.02992]
예제 #6
0
def mc_compute_stationary(P, precision=None, tol=None):
    n = P.shape[0]

    if precision is None:
        # Compute eigenvalues and eigenvectors
        eigvals, eigvecs = la.eig(P, left=True, right=False)

        # Find the index for unit eigenvalues
        index = np.where(abs(eigvals - 1.) < 1e-12)[0]

        # Pull out the eigenvectors that correspond to unit eig-vals
        uniteigvecs = eigvecs[:, index]

        stationary_dists = uniteigvecs / np.sum(uniteigvecs, axis=0)

    else:
        # Create a list to store eigvals
        stationary_dists_list = []
        if tol is None:
            # If tolerance isn't specified then use 2*precision
            tol = mp.mpf(2 * 10**(-precision + 1))

        with mp.workdps(precision):
            eigvals, eigvecs = mp.eig(mp.matrix(P), left=True, right=False)

            for ind, el in enumerate(eigvals):
                if el >= (mp.mpf(1) - mp.mpf(tol)) and el <= (mp.mpf(1) +
                                                              mp.mpf(tol)):
                    stationary_dists_list.append(eigvecs[ind, :])

            stationary_dists = np.asarray(stationary_dists_list).T
            stationary_dists = (stationary_dists /
                                sum(stationary_dists)).astype(np.float)

    # Check to make sure all of the elements of invar_dist are positive
    if np.any(stationary_dists < -1e-16):
        warn("Elements of your invariant distribution were negative; " +
             "Re-trying with additional precision")

        if precision is None:
            stationary_dists = mc_compute_stationary(P, precision=18, tol=tol)

        elif precision is not None:
            raise ValueError("Elements of your stationary distribution were" +
                             "negative.  Try computing with higher precision")

    # Since we will be accessing the columns of this matrix, we
    # might consider adding .astype(np.float, order='F') to make it
    # column major at beginning
    return stationary_dists.squeeze()
예제 #7
0
def mc_compute_stationary(P, precision=None, tol=None):
    n = P.shape[0]

    if precision is None:
        # Compute eigenvalues and eigenvectors
        eigvals, eigvecs = la.eig(P, left=True, right=False)

        # Find the index for unit eigenvalues
        index = np.where(abs(eigvals - 1.) < 1e-12)[0]

        # Pull out the eigenvectors that correspond to unit eig-vals
        uniteigvecs = eigvecs[:, index]

        stationary_dists = uniteigvecs/np.sum(uniteigvecs, axis=0)

    else:
        # Create a list to store eigvals
        stationary_dists_list = []
        if tol is None:
            # If tolerance isn't specified then use 2*precision
            tol = mp.mpf(2 * 10**(-precision + 1))

        with mp.workdps(precision):
            eigvals, eigvecs = mp.eig(mp.matrix(P), left=True, right=False)

            for ind, el in enumerate(eigvals):
                if el>=(mp.mpf(1)-mp.mpf(tol)) and el<=(mp.mpf(1)+mp.mpf(tol)):
                    stationary_dists_list.append(eigvecs[ind, :])

            stationary_dists = np.asarray(stationary_dists_list).T
            stationary_dists = (stationary_dists/sum(stationary_dists)).astype(np.float)


    # Check to make sure all of the elements of invar_dist are positive
    if np.any(stationary_dists < -1e-16):
        warn("Elements of your invariant distribution were negative; " +
              "Re-trying with additional precision")

        if precision is None:
            stationary_dists = mc_compute_stationary(P, precision=18, tol=tol)

        elif precision is not None:
            raise ValueError("Elements of your stationary distribution were" +
                             "negative.  Try computing with higher precision")

    # Since we will be accessing the columns of this matrix, we
    # might consider adding .astype(np.float, order='F') to make it
    # column major at beginning
    return stationary_dists.squeeze()
예제 #8
0
파일: mpmat.py 프로젝트: bayao/qml
def test_mev():
    output("""\
    reim:{$[0>type x;1 0*x;2=count x;x;'`]};
    mc:{((x[0]*y 0)-x[1]*y 1;(x[0]*y 1)+x[1]*y 0)};
    mmc:{((.qml.mm[x 0]y 0)-.qml.mm[x 1]y 1;(.qml.mm[x 0]y 1)+.qml.mm[x 1]y 0)};
    mev_:{[b;x]
        if[2<>count wv:.qml.mev x;'`length];
        if[not all over prec>=abs
            mmc[flip vc;flip(flip')(reim'')flip x]-
            flip(w:reim'[wv 0])mc'vc:(flip')(reim'')(v:wv 1);'`check];
        / Normalize sign; LAPACK already normalized to real
        v*:1-2*0>{x a?max a:abs x}each vc[;0];
        (?'[prec>=abs w[;1];w[;0];w];?'[b;v;0n])};""")

    for A in eigenvalue_subjects:
        if A.rows <= 3:
            V = []
            for w, n, r in A.eigenvects():
                w = sp.simplify(sp.expand_complex(w))
                if len(r) == 1:
                    r = r[0]
                    r = sp.simplify(sp.expand_complex(r))
                    r = r.normalized() / sp.sign(max(r, key=abs))
                    r = sp.simplify(sp.expand_complex(r))
                else:
                    r = None
                V.extend([(w, r)]*n)
            V.sort(key=lambda (x, _): (-abs(x), -sp.im(x)))
        else:
            Am = mp.matrix(A)
            # extra precision for complex pairs to be equal in sort
            with mp.extradps(mp.mp.dps):
                W, R = mp.eig(Am)
            V = []
            for w, r in zip(W, (R.column(i) for i in range(R.cols))):
                w = mp.chop(w)
                with mp.extradps(mp.mp.dps):
                    _, S, _ = mp.svd(Am - w*mp.eye(A.rows))
                if sum(x == 0 for x in mp.chop(S)) == 1:
                    # nullity 1, so normalized eigenvector is unique
                    r /= mp.norm(r) * mp.sign(max(r, key=abs))
                    r = mp.chop(r)
                else:
                    r = None
                V.append((w, r))
            V.sort(key=lambda (x, _): (-abs(x), -x.imag))
        W, R = zip(*V)
        test("mev_[%sb" % "".join("0" if r is None else "1" for r in R), A,
             (W, [r if r is None else list(r) for r in R]), complex_pair=True)
예제 #9
0
def diag(diagonal):
    mat = mp.matrix(np.eye(len(diagonal)))
    for i, value in enumerate(diagonal):
        mat[i, i] = value
    return mat
예제 #10
0
from scipy.linalg import toeplitz
import sympy.mpmath as mp
import numpy as np

n = 25
A = toeplitz(np.r_[2, 1, np.zeros(n)])

# Numpy ---
lmbda, U = np.linalg.eig(A)
Lmbda = np.diag(lmbda)
print np.linalg.norm(A - U.dot(Lmbda.dot(U.T)))

# Mpmath
def diag(diagonal):
    mat = mp.matrix(np.eye(len(diagonal)))
    for i, value in enumerate(diagonal):
        mat[i, i] = value
    return mat

A = mp.matrix(A.tolist())
E, Q = mp.eigsy(A)
E = diag(E)

# Sort for comparison
Lmbda = np.diag(np.sort(np.diagonal(Lmbda)))
print np.linalg.norm(Lmbda - np.array(E.tolist(), dtype=float))
예제 #11
0
파일: mpmat.py 프로젝트: bayao/qml
def N(A):
    for r in A.atoms(sp.Pow):
        if r.exp == S(1)/2 and r.base.is_Rational and r.base > 1000000000:
            return mp.matrix(A.evalf(mp.mp.dps))
    return A