Exemplo n.º 1
0
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)
Exemplo n.º 2
0
Arquivo: mpmat.py Projeto: zholos/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)
Exemplo n.º 3
0
    def test_for_spec_a(self):
        n = 2
        A = mpmath.matrix([[0j, 1 + 0j], [1 + 0j, 0j]])
        vs, Q = takagi_fact.symmetric_svd(A)

        diag = mpmath.diag(vs)
        qtaq = Q.T * A * Q

        unit = mpmath.diag([1 for _ in range(n)])
        qdaq = Q.H * Q

        for i, j in itertools.product(range(n), repeat=2):
            self.assertAlmostEqual(diag[i, j], qtaq[i, j])
            self.assertAlmostEqual(unit[i, j], qdaq[i, j])
Exemplo n.º 4
0
def Propagate_trunc2(M, p, dt, ddt=1):

    E, EL, ER = mp.eig(M.T, left=True, right=True)
    E, EL, ER = mp.eig_sort(E, EL, ER)
    times = np.arange(0, dt, ddt) + dt
    N = int(dt / ddt)
    if len(p) == 1:
        intermediate_populations = [p for i in range(N)]
        return intermediate_populations
    else:
        R = [[0 for i in range(len(p))] for j in range(N)]
        for i in range(N):
            R[i][-2] = mp.exp(E[-2] * times[i])
            R[i][-1] = 1
        # print(M)
        # print(ER)
        print(E)
        # print(R)
        # print(EL)
        # print(p)
        # print(ER*mp.diag(R[0])*EL*p)
        intermediate_populations = []
        for i in range(N):
            # print(mp.diag(R[i]))
            A = ER * mp.diag(R[i]) * EL * p
            intermediate_populations.append(
                np.array((A.T).apply(mp.re).tolist()[0], dtype=float))
        print(intermediate_populations)
        return intermediate_populations
Exemplo n.º 5
0
def Propagate_stationary(M, p, dt, ddt=1):
    syst1 = time.time()

    E, EL, ER = mp.eig(M.T, left=True, right=True)
    E, EL, ER = mp.eig_sort(E, EL, ER)
    times = range(ddt, dt + ddt, ddt)
    UR = ER**-1
    R = [0] * (len(E) - 1)
    R.append(1)
    # print(M.T)
    # print(E)
    intermediate_populations = []
    print(time.time() - syst1)
    # print(np.exp(time*np.diag(e)))
    # E = np.real(np.dot(np.dot(U, np.diag(R)), Uinv))
    for i in range(len(times)):
        # print(mp.diag(R[i]))
        A = ER * mp.diag(R) * UR * p
        intermediate_populations.append(
            np.array((A.T).apply(mp.re).tolist()[0], dtype=float))
    # print(intermediate_populations)
    print(time.time() - syst1)
    # intermediate_populations = [np.array(((ER*mp.diag(R)*EL*p).T).apply(mp.re).tolist()[0], dtype=float) for t in times]
    # print(intermediate_populations)
    return intermediate_populations
Exemplo n.º 6
0
def subspace_angle_V_M_mp(mu, lam, dps=100):
    r"""Multiprecision implementation computing the subspace angle between V(mu) and M(lam) 
	"""
    n = len(mu)
    lam = np.atleast_1d(lam)
    m = len(lam)

    with mp.workdps(dps):
        mu = mp.matrix(mu)
        lam = mp.matrix(lam)

        # Construct the Cauchy mass matrix
        #M = mp.zeros(n,n)
        #for i,j in 	product(range(n), range(n)):
        #	M[i,j] = (mu[i] + mu[j].conjugate())**(-1)
        #ewL, QL = mp.eighe(M)
        ewL, QL = cauchy_eigen(mu, dps)

        # Construct the right hand side Mhat matrix
        Mhat = mp.zeros(2 * m, 2 * m)
        for i, j in product(range(m), range(m)):
            Mhat[i, j] = (-lam[i] - lam[j].conjugate())**(-1)
            Mhat[i, m + j] = (-lam[i] - lam[j].conjugate())**(-2)
            Mhat[m + i, j] = (-lam[i] - lam[j].conjugate())**(-2).conjugate()
            Mhat[m + i, m + j] = 2 * (-lam[i] - lam[j].conjugate())**(-3)

        # Construct the interior matrix
        A = mp.zeros(n, 2 * m)
        for i, j in product(range(n), range(m)):
            A[i, j] = (mu[i] - lam[j])**(-1)
            A[i, m + j] = (mu[i] - lam[j])**(-2)

        ewR, QR = mp.eighe(Mhat)

        AA = mp.diag([1 / mp.sqrt(ewL[i])
                      for i in range(n)]) * (QL.H * A * QR) * mp.diag(
                          [1 / mp.sqrt(ewR[i]) for i in range(2 * m)])
        U, s, VH = mp.svd(AA)
        phi = np.array([float(mp.acos(si)) for si in s])
        return phi
Exemplo n.º 7
0
def multivariate_normalization(data, variables_size):
    mpmath.mp.dps = 20
    for j in range(0, len(data[0])):
        means = []
        ts_s = []
        for u in range(0, variables_size):
            means.append(numpy.mean(data[u][j]))
            ts_s.append(data[u][j])
        covariance_matrix = mpmath.matrix(numpy.cov(ts_s))
        w, v = mpmath.eig(covariance_matrix)
        diagonal = mpmath.diag(w)

        try:
            result = mpmath.sqrtm(diagonal)
        except ZeroDivisionError as error:
            print("j: ", j)
            print("ts:", ts_s)
            print("not invertible sqrtm")
            print("covariance_matrix:", covariance_matrix)
            sys.exit()

        B = v * result
        try:
            inverse_B = B**-1
        except ZeroDivisionError as error:
            # Not invertible. Skip this one.
            # Non invertable cases Uwave
            print("j: ", j)
            print("ts:", ts_s)
            print("not invertible")
            print("covariance_matrix:", covariance_matrix)
            sys.exit()
        except Exception as exception:
            # Not invertible. Skip this one.
            print("j: ", j)
            print("ts:", ts_s)
            print("not invertible")
            print("covariance_matrix:", covariance_matrix)
            sys.exit()
        for i in range(0, len(data[0][j])):
            atributes_together = []
            for u in range(0, variables_size):
                atributes_together.append(data[u][j][i])
            atributes_together = mpmath.matrix(atributes_together)
            result = atributes_together - mpmath.matrix(means)
            result = inverse_B * result
            for u in range(0, variables_size):
                if type(result[u]) is mpmath.mpc:
                    data[u][j][i] = result[u].real
                else:
                    data[u][j][i] = result[u]
    return data
Exemplo n.º 8
0
    def test_takagi_fact(self):
        N_REPEAT = 1000
        N_DIM_UPPER = 2
        for _ in range(N_REPEAT):
            for n in range(2, N_DIM_UPPER + 1):
                ar = mpmath.randmatrix(n)
                ai = mpmath.randmatrix(n)
                a = ar + 1j * ai
                A = a + a.T

                vs, Q = takagi_fact.takagi_fact(A)

                diag = mpmath.diag(vs)
                qtaq = Q.T * A * Q

                unit = mpmath.diag([1 for _ in range(n)])
                qdaq = Q.H * Q

                for i, j in itertools.product(range(n), repeat=2):
                    self.assertAlmostEqual(mpmath.im(diag[i, j]), 0)
                    self.assertAlmostEqual(diag[i, j], qtaq[i, j])
                    self.assertAlmostEqual(unit[i, j], qdaq[i, j])
Exemplo n.º 9
0
			def psolve(M, b):
				U, S, V = mp.svd(M)

				if False:
					print("V")
					testHermitian(V)
					print("U")
					testHermitian(U)
					sys.exit(1)

				Mpinv = V.transpose_conj() * (mp.diag(S)**(-1)) * U.transpose_conj()
				ws = Mpinv*mp.matrix(b)
				return [ws[i] for i in range(len(ws))]
Exemplo n.º 10
0
			def testHermitian(M):
				T = M * (M.transpose_conj()) - mp.diag([1.0 for i in range(max(M.rows, M.cols))])
				#printM(T)

				maxvalre = 0
				maxvalim = 0
				for j in range(T.rows):
					for i in range(T.cols):
						x = T[j,i]
						maxvalre = max(abs(x.real), maxvalre)
						maxvalim = max(abs(x.imag), maxvalim)

				print("maxvalre: "+str(float(maxvalre)))
				print("maxvalim: "+str(float(maxvalim)))
Exemplo n.º 11
0
def Propagate(M, p, dt, ddt=1):
    E, EL, ER = mp.eig(M.T, left=True, right=True)
    UR = ER**-1
    # E, EL, ER = mp.eig_sort(E, EL, ER)   # time_series = np.arange(0, dt, ddt) + dt
    # print(mp.nstr(EL*ER, n=3))
    times = range(ddt, dt + ddt, ddt)
    # print(E)
    intermediate_populations = []
    # print(np.exp(time*np.diag(e)))
    # E = np.real(np.dot(np.dot(U, np.diag(R)), Uinv))
    for i in range(len(times)):
        R = [mp.exp(E[j] * times[i]) for j in range(len(E))]
        # R = [mp.exp(E[j]*0) for j in range(len(E))]
        A = ER * mp.diag(R) * UR * p
        # print(R)
        intermediate_populations.append(
            np.array((A.T).apply(mp.re).tolist()[0], dtype=float))
    # print(p)
    # print(intermediate_populations[-1])
    # intermediate_populations = [np.array(((ER*mp.diag(R)*EL*p).T).apply(mp.re).tolist()[0], dtype=float) for t in times]
    # print(intermediate_populations)
    return intermediate_populations
Exemplo n.º 12
0
def solve_svd_mp(A, b):
    """
    solve a linear system using svd decomposition using mpmath

    :param ndarray A: The linear system
    :param ndarray b: The right hand side
    :return: ndarray
    """
    A_mp = mpmath.matrix([list(row) for row in A])
    b_mp = mpmath.matrix([list(row) for row in b])

    u, s, v = svd_r(A_mp)

    # x = V*((U'.b)./ diag(S))
    # x = V*(  c   ./ diag(S))
    # x = V*(       g        )

    c = u.T * b_mp
    w = mpmath.lu_solve(mpmath.diag(s), c)
    x_mp = v.T * w
    x = numpy.array(x_mp.tolist(), 'f8')

    return x
Exemplo n.º 13
0
def eqn42_solve( geom, Nmax ):
    # eqn 4.2 
    NMAX = Nmax         # where to truncate the infinite system of eqns
    S = geom['S']
    distanceqp = geom['distanceqp']
    thetaqp = geom['thetaqp']
    phiqp = geom['phiqp']
    radii = geom['radii']

    # coefficient matrix
    if USEMPMATH:
        CM = mpmath.zeros( S*NMAX*(2*NMAX+1) )
    else:
        CM = np.zeros( (S*NMAX*(2*NMAX+1), S*NMAX*(2*NMAX+1)) )

    for sprimei,sprime in enumerate(range(S)):
        for nprimei,nprime in enumerate(range(NMAX)):
            for mprimei,mprime in enumerate(range(-nprime,nprime+1)):

                # row index
                ri = sprimei*NMAX*(2*NMAX+1) + nprimei*(2*NMAX+1) + mprimei
                # row prefactors
                prefac = (-1)**(nprime+mprime) * radii[sprimei]**(nprime+1) \
                         * 1./factorial(nprime+mprime)

                for si,s in enumerate(range(S)):
                    if sprimei != si:
                        for ni,n in enumerate(range(NMAX)):
                            for mi,m in enumerate(range(-n,n+1)):

                                # column index
                                ci = si*NMAX*(2*NMAX+1) + ni*(2*NMAX+1) + mi

                                f1 = distanceqp[sprimei,si]**(-(n+1))
                                f2 = (radii[sprimei]/distanceqp[sprimei,si])**nprime
                                f3 = factorial(n-m+nprime+mprime)/factorial(n-m)
                                if USEMPMATH:
                                    f4 = mpmath.legenp( n+nprime, m-mprime, \
                                                        np.cos(thetaqp[sprimei,si]) )
                                else:
                                    f4 = scipy.special.lpmv( m-mprime, n+nprime, \
                                                             np.cos(thetaqp[sprimei,si]) )
                                f5 = np.exp( 1j*(m-mprime)*phiqp[sprimei,si] )

                                CM[ri,ci] = prefac*f1*f2*f3*f4*f5


    if USEMPMATH:
        CM += mpmath.diag(np.ones(S*NMAX*(2*NMAX+1)))
        Qs = mpmath.zeros(S)
    else:
        CM += np.diag(np.ones(S*NMAX*(2*NMAX+1)))
        Qs = np.zeros((S,S))              


    for si in range(S):
        if USEMPMATH:
            rhs = mpmath.zeros( S*NMAX*(2*NMAX+1), 1 )
        else:          
            rhs = np.zeros((CM.shape[0],))
        rhs[si*NMAX*(2*NMAX+1):(si*NMAX+1)*(2*NMAX+1)] = radii[si]
        if USEMPMATH:     
            sol = mpmath.lu_solve( CM, rhs )
        else:
            sol = np.linalg.solve( CM, rhs )
        #print sol[::(NMAX*(2*NMAX+1))]
        Qs[si,:] = sol[::(NMAX*(2*NMAX+1))]
    
    return Qs
Exemplo n.º 14
0
 def get_unary(self, item):
     return {
         **{
             k: calc2.UnaryOperator(s, f, 80)
             for k, s, f in [
                 ('abs', 'abs', abs),
                 ('fac', 'fac', mpmath.factorial),
                 ('sqrt', 'sqrt', mpmath.sqrt),
                 ('_/', 'sqrt', mpmath.sqrt),
                 ('√', 'sqrt', mpmath.sqrt),
                 ('ln', 'ln', mpmath.ln),
                 ('lg', 'log10', mpmath.log10),
                 ('exp', 'e^', mpmath.exp),
                 ('floor', 'floor', mpmath.floor),
                 ('ceil', 'ceil', mpmath.ceil),
                 ('det', 'det', mpmath.det),
             ]
         }, 'pcn':
         calc2.UnaryOperator('a%', lambda x: x / 100, 80),
         '+':
         calc2.UnaryOperator('(+)', lambda x: x, 0),
         '-':
         calc2.UnaryOperator('+/-', lambda x: -x, 80),
         'conj':
         calc2.UnaryOperator(
             'conj', lambda x: x.conjugate()
             if isinstance(x, mpmath.matrix) else mpmath.conj(x), 80),
         '~':
         calc2.UnaryOperator(
             'conj', lambda x: x.conjugate()
             if isinstance(x, mpmath.matrix) else mpmath.conj(x), 80),
         'O':
         calc2.UnaryOperator(
             '[O]', lambda x: mpmath.zeros(*OpList.__analyse_as_pair(x)),
             80),
         'I':
         calc2.UnaryOperator(
             '[I]', lambda x: mpmath.ones(*OpList.__analyse_as_pair(x)),
             80),
         'E':
         calc2.UnaryOperator('[E]', lambda x: mpmath.eye(int(x)), 80),
         'diag':
         calc2.UnaryOperator(
             '[diag]', lambda x: mpmath.diag(OpList.__analyse_list(x)), 80),
         'log':
         calc2.UnaryOperator(
             'logbA', lambda x: OpList.__log(*OpList.__analyse_pair(x)),
             80),
         'tran':
         calc2.UnaryOperator(
             '[T]', lambda x: x.transpose()
             if isinstance(x, mpmath.matrix) else x, 80),
         **{
             k: calc2.UnaryOperator(k, (lambda u: lambda x: u(self._drg2r(x)))(v), 80)
             for k, v in {
                 'sin': mpmath.sinpi,
                 'cos': mpmath.cospi,
                 'tan': lambda x: mpmath.sinpi(x) / mpmath.cospi(x),
                 'cot': lambda x: mpmath.cospi(x) / mpmath.sinpi(x),
                 'sec': lambda x: 1 / mpmath.cospi(x),
                 'csc': lambda x: 1 / mpmath.sinpi(x),
             }.items()
         },
         **{
             k: calc2.UnaryOperator(k, (lambda u: lambda x: self._r2drg(1 / v(x)))(v), 80)
             for k, v in {
                 'asin': mpmath.asin,
                 'acos': mpmath.acos,
                 'atan': mpmath.atan,
                 'acot': mpmath.acot,
                 'asec': mpmath.asec,
                 'acsc': mpmath.acsc
             }.items()
         },
         **{
             k: calc2.UnaryOperator(k, v, 80)
             for k, v in {
                 'sinh': mpmath.sinh,
                 'cosh': mpmath.cosh,
                 'tanh': mpmath.tanh,
                 'coth': mpmath.coth,
                 'sech': mpmath.sech,
                 'csch': mpmath.csch,
                 'asinh': mpmath.asinh,
                 'acosh': mpmath.acosh,
                 'atanh': mpmath.atanh,
                 'acoth': mpmath.acoth,
                 'asech': mpmath.asech,
                 'acsch': mpmath.acsch
             }.items()
         }
     }[item]
Exemplo n.º 15
0
    ],
    'agm': [
        'primitive',
        [lambda x, y: mp.agm(x) if y is None else mp.agm(x, y[0]), None]
    ],
    #
    'matrix': [
        'primitive',
        [
            lambda x, y: mp.matrix(x) if isa(x, Vector) else mp.matrix(x)
            if y is None else mp.matrix(x, y[0]), None
        ]
    ],
    'matrix-ref': ['primitive', [lambda x, y: x[y[0], y[1], [0]], None]],
    'matrix-set': [
        'primitive',
        [lambda x, y: matrix_set(x, y[0], y[1][0], y[1][1][0]), None]
    ],
    'zeros': ['primitive', [lambda x, y: mp.zeros(x), None]],
    'ones': ['primitive', [lambda x, y: mp.ones(x), None]],
    'eye': ['primitive', [lambda x, y: mp.eye(x), None]],
    'diag': ['primitive', [lambda x, y: mp.diag(x), None]],
    'randmatrix': ['primitive', [lambda x, y: mp.randmatrix(x), None]],
    'matrix-inv': ['primitive', [lambda x, y: x**(-1), None]],
    'norm': [
        'primitive',
        [lambda x, y: mp.norm(x) if y is None else mp.norm(x, y[0]), None]
    ],
    'mnorm': ['primitive', [lambda x, y: mp.mnorm(x, y[0]), None]],
}