Example #1
0
def FreeFermions(eigvec, subsystem, FermiVector):
	r=range(FermiVector)
	Cij=mp.matrix([[mp.fsum([eigvec[i,k]*eigvec[j,k] for k in r]) for i in subsystem] for j in subsystem])
	C_eigval=mp.eigsy(Cij, eigvals_only=True)
	EH_eigval=mp.matrix([mp.log(mp.fdiv(mp.fsub(mp.mpf(1.0),x),x)) for x in C_eigval])
	S=mp.re(mp.fsum([mp.log(mp.mpf(1.0)+mp.exp(-x))+mp.fdiv(x,mp.exp(x)+mp.mpf(1.0)) for x in EH_eigval]))
	return(S)
Example #2
0
def test_eig():
    v = 0
    AS = []

    A = mp.matrix([[2, 1, 0],  # jordan block of size 3
                   [0, 2, 1],
                   [0, 0, 2]])
    AS.append(A)
    AS.append(A.transpose())

    A = mp.matrix([[2, 0, 0],  # jordan block of size 2
                   [0, 2, 1],
                   [0, 0, 2]])
    AS.append(A)
    AS.append(A.transpose())

    A = mp.matrix([[2, 0, 1],  # jordan block of size 2
                   [0, 2, 0],
                   [0, 0, 2]])
    AS.append(A)
    AS.append(A.transpose())

    A=  mp.matrix([[0, 0, 1],  # cyclic
                   [1, 0, 0],
                   [0, 1, 0]])
    AS.append(A)
    AS.append(A.transpose())

    for A in AS:
        run_hessenberg(A, verbose = v)
        run_schur(A, verbose = v)
        run_eig(A, verbose = v)
Example #3
0
def entropy_pf(Lph,Tph,meas,G,prec=15,q=2,dps=200):
    
    # setting digit precision
    mp.dps = dps
    
    # =============================================================================
    # Evaluation of the entropy using partition function
    # Lph,Tph -- physical size (number of qubits) and time (circuit depth)
    # G -- (large) parameter controling the gap between relevant and irrelevant states
    # prec -- number of digits in the answer
    # q -- qudit dimension
    # =============================================================================
    
    # -- define effective inverse temperature
    beta = mp.log((q**2+1)/q)
    # -- dimension of the effective lattice
    L,T = int(Lph/2)+(Lph+1)%2,Tph+1
    # -- corresponding couplings for the numerator and denominator 
    J_matrix1,J_matrix2 = generate_lattice_couplings(L,T,meas,G,beta)
    # -- including the temperature
    J_matrix1 = -beta*mp.matrix(J_matrix1.tolist())
    J_matrix2 = -beta*mp.matrix(J_matrix2.tolist())
    # -- evaluation of the entropy
    entropy = -log_partition_function(J_matrix1,L,T).real\
              +log_partition_function(J_matrix2,L,T).real
    
    return mp.nstr(entropy,prec)
Example #4
0
def _compute_roots(w, x, use_mp):
    # Cf.:
    # Knockaert, L. (2008). A simple and accurate algorithm for barycentric
    # rational interpolation. IEEE Signal processing letters, 15, 154-157.
    #
    # This version requires solving only a standard eigenvalue problem, but
    # has troubles when the polynomial has leading 0 coefficients.
    if _is_mp_array(w) or _is_mp_array(x):
        use_mp = True

    if use_mp:
        assert mpmath, 'mpmath package is not installed'
        ak = mp.matrix(w)
        ak /= sum(ak)
        bk = mp.matrix(x)

        M = mp.diag(bk)
        for i in range(M.rows):
            for j in range(M.cols):
                M[i, j] -= ak[i] * bk[j]
        lam = np.array(mp.eig(M, left=False, right=False))
        # remove one simple root
        lam = np.delete(lam, np.argmin(abs(lam)))
        return lam
    else:
        # the same procedure in standard double precision
        ak = w / w.sum()
        M = np.diag(x) - np.outer(ak, x)
        lam = scipy.linalg.eigvals(M)
        # remove one simple root
        lam = np.delete(lam, np.argmin(abs(lam)))
        return np.real_if_close(lam)
Example #5
0
def test_svd_test_case():
    # a test case from Golub and Reinsch
    #  (see wilkinson/reinsch: handbook for auto. comp., vol ii-linear algebra, 134-151(1971).)

    eps = mp.exp(0.8 * mp.log(mp.eps))

    a = [[22, 10,  2,   3,  7],
         [14,  7, 10,   0,  8],
         [-1, 13, -1, -11,  3],
         [-3, -2, 13,  -2,  4],
         [ 9,  8,  1,  -2,  4],
         [ 9,  1, -7,   5, -1],
         [ 2, -6,  6,   5,  1],
         [ 4,  5,  0,  -2,  2]]

    a = mp.matrix(a)
    b = mp.matrix([mp.sqrt(1248), 20, mp.sqrt(384), 0, 0])

    S = mp.svd_r(a, compute_uv = False)
    S -= b
    assert mp.mnorm(S) < eps

    S = mp.svd_c(a, compute_uv = False)
    S -= b
    assert mp.mnorm(S) < eps
Example #6
0
def test_eig():
  v = 0
  AS = []

  A = mp.matrix([[2, 1, 0],  # jordan block of size 3
                 [0, 2, 1],
                 [0, 0, 2]])
  AS.append(A)
  AS.append(A.transpose())

  A = mp.matrix([[2, 0, 0],  # jordan block of size 2
                 [0, 2, 1],
                 [0, 0, 2]])
  AS.append(A)
  AS.append(A.transpose())

  A = mp.matrix([[2, 0, 1],  # jordan block of size 2
                 [0, 2, 0],
                 [0, 0, 2]])
  AS.append(A)
  AS.append(A.transpose())

  A=  mp.matrix([[0, 0, 1],  # cyclic
                 [1, 0, 0],
                 [0, 1, 0]])
  AS.append(A)
  AS.append(A.transpose())

  for A in AS:
      run_hessenberg(A, verbose = v)
      run_schur(A, verbose = v)
      run_eig(A, verbose = v)
Example #7
0
def _compute_roots(w, x, use_mp):
    # Cf.:
    # Knockaert, L. (2008). A simple and accurate algorithm for barycentric
    # rational interpolation. IEEE Signal processing letters, 15, 154-157.
    if use_mp:
        from mpmath import mp
        if use_mp is True:
            use_mp = 100
        mp.dps = use_mp

        ak = mp.matrix(w)
        ak /= sum(ak)
        bk = mp.matrix(x)

        M = mp.diag(bk)
        for i in range(M.rows):
            for j in range(M.cols):
                M[i, j] -= ak[i] * bk[j]
        lam = mp.eig(M, left=False, right=False)
        lam = np.array(lam, dtype=complex)
    else:
        # the same procedure in standard double precision
        ak = w / w.sum()
        M = np.diag(x) - np.outer(ak, x)
        lam = scipy.linalg.eigvals(M)

    # remove one simple root
    lam = np.delete(lam, np.argmin(abs(lam)))
    return np.real_if_close(lam)
Example #8
0
def gauss_laguerre(n):
    d = mp.matrix(mp.arange(1, 2 * n, 2))
    e = mp.matrix(mp.arange(-1, -n - 1, -1))
    z = mp.eye(n)[0, :]

    tridiag_eigen(mp, d, e, z)
    z = z.apply(lambda x: x**2)
    return d, z.T
Example #9
0
def run_gauss(qtype, a, b):
    eps = 1e-5

    d, e = mp.gauss_quadrature(len(a), qtype)
    d -= mp.matrix(a)
    e -= mp.matrix(b)

    assert mp.mnorm(d) < eps
    assert mp.mnorm(e) < eps
Example #10
0
def run_gauss(qtype, a, b):
    eps = 1e-5

    d, e = mp.gauss_quadrature(len(a), qtype)
    d -= mp.matrix(a)
    e -= mp.matrix(b)

    assert mp.mnorm(d) < eps
    assert mp.mnorm(e) < eps
Example #11
0
def gauss_genlaguerre(n, alpha):
    d = mp.matrix([i + alpha for i in mp.arange(1, 2 * n, 2)])
    e = [-mp.sqrt(k * (k + alpha)) for k in mp.arange(1, n)]
    e.append(mp.mpf('0.0'))
    e = mp.matrix(e)
    z = mp.eye(n)[0, :]

    tridiag_eigen(mp, d, e, z)
    z = mp.gamma(alpha + 1) * z.apply(lambda x: x**2)
    return d, z.T
Example #12
0
def gauss_legendre(n):
    d = mp.matrix([mp.mpf('0.0') for _ in range(n)])
    e = [k / mp.sqrt(4 * k**2 - 1) for k in mp.arange(1, n)]
    e.append(mp.mpf('0.0'))
    e = mp.matrix(e)
    z = mp.eye(n)[0, :]

    tridiag_eigen(mp, d, e, z)
    z = 2 * z.apply(lambda x: x**2)
    return d, z.T
Example #13
0
def gauss_hermite(n):
    d = mp.matrix([mp.mpf('0.0') for _ in range(n)])
    e = [mp.sqrt(k / 2) for k in mp.arange(1, n)]
    e.append(mp.mpf('0.0'))
    e = mp.matrix(e)
    z = mp.eye(n)[0, :]

    tridiag_eigen(mp, d, e, z)
    z = mp.sqrt(mp.pi) * z.apply(lambda x: x**2)
    return d, z.T
Example #14
0
def FreeFermions(subsystem, C):
    C = mp.matrix([[C[x, y] for x in subsystem] for y in subsystem])
    C_eigval = mp.eigh(C, eigvals_only=True)
    EH_eigval = mp.matrix(
        [mp.log(mp.fdiv(mp.fsub(mp.mpf(1.0), x), x)) for x in C_eigval])
    S = mp.re(
        mp.fsum([
            mp.log(mp.mpf(1.0) + mp.exp(-x)) + mp.fdiv(x,
                                                       mp.exp(x) + mp.mpf(1.0))
            for x in EH_eigval
        ]))
    return (S)
def test_eigsy_fixed_matrix():
    A = mp.matrix([[2, 3], [3, 5]])
    run_eigsy(A)

    A = mp.matrix([[7, -11], [-11, 13]])
    run_eigsy(A)

    A = mp.matrix([[2, 11, 7], [11, 3, 13], [7, 13, 5]])
    run_eigsy(A)

    A = mp.matrix([[2, 0, 7], [0, 3, 1], [7, 1, 5]])
    run_eigsy(A)
Example #16
0
def inverse(M, A, indices_from, indices_to):
    t = time.time()
    b = mp.matrix(M, len(indices_to))
    for j in range(len(indices_to)):
        b[indices_to[j], j] = 1
    x = solve_multiprecision(M, A, b)
    answer = mp.matrix(len(indices_from), len(indices_to))
    for i in range(len(indices_from)):
        for j in range(len(indices_to)):
            answer[i, j] = x[indices_from[i], j]
    print("inverse runtime was %f" % (time.time() - t))
    return answer
Example #17
0
def Construct_Dm(Phi, Psi, Omega, tt):

    Cos = mp.matrix([[
        mp.cos(eigvalst[i] * tt) if i == j else mp.mpf(0.0) for j in range(L)
    ] for i in range(L)])
    Sin = mp.matrix([[
        mp.sin(eigvalst[i] * tt) if i == j else mp.mpf(0.0) for j in range(L)
    ] for i in range(L)])

    OmegaSinCos = Sin * Omega * Cos

    Dm = -Psi * (OmegaSinCos - OmegaSinCos.T) * Psi.T
    return (Dm)
Example #18
0
def FROM_NUMPY(foo):
    try:
        return mp.matrix(foo)
    except TypeError:
        pass
    rows, cols = foo.shape
    m = mp.matrix(rows, cols)
    col = 0
    for j in range(len(foo.data)):
        while foo.indptr[col + 1] <= j:
            col += 1
        m[foo.indices[j], col] = foo.data[j]
    return m
Example #19
0
def Construct_Dp(Phi, Psi, Omega, tt):

    Cos = mp.matrix([[
        mp.cos(eigvalst[i] * tt) if i == j else mp.mpf(0.0) for j in range(L)
    ] for i in range(L)])
    Sin = mp.matrix([[
        mp.sin(eigvalst[i] * tt) if i == j else mp.mpf(0.0) for j in range(L)
    ] for i in range(L)])

    OmegaCosSin = Cos * Omega * Sin

    Dp = -Phi * (OmegaCosSin.T - OmegaCosSin) * Phi.T
    return (Dp)
Example #20
0
def FreeFermions(subsystem,
                 C_t):  #implements free fermion technique by peschel
    C = mp.matrix([[C_t[x, y] for x in subsystem] for y in subsystem])
    C_eigval = mp.eigh(C, eigvals_only=True)
    EH_eigval = mp.matrix(
        [mp.log(mp.fdiv(mp.fsub(mp.mpf(1.0), x), x)) for x in C_eigval])
    S = mp.re(
        mp.fsum([
            mp.log(mp.mpf(1.0) + mp.exp(-x)) + mp.fdiv(x,
                                                       mp.exp(x) + mp.mpf(1.0))
            for x in EH_eigval
        ]))
    return (S)
Example #21
0
def Construct_K(Phi, Psi, Omega, tt):

    Cos = mp.matrix([[
        mp.cos(eigvalst[i] * tt) if i == j else mp.mpf(0.0) for j in range(L)
    ] for i in range(L)])
    Sin = mp.matrix([[
        mp.sin(eigvalst[i] * tt) if i == j else mp.mpf(0.0) for j in range(L)
    ] for i in range(L)])

    OmegaCos = Cos * Omega * Cos
    OmegaSin = Sin * Omega * Sin

    Kmatrix = -Phi * (OmegaCos + OmegaSin.T) * Psi.T
    return (Kmatrix)
Example #22
0
def gauss_gegenbauer(n, alpha):
    d = mp.matrix([mp.mpf('0.0') for _ in range(n)])
    e = [
        mp.sqrt(k * (k + 2 * alpha - 1) / ((2 * k + 2 * alpha - 1)**2 - 1))
        for k in mp.arange(1, n)
    ]
    e.append(mp.mpf('0.0'))
    e = mp.matrix(e)
    z = mp.eye(n)[0, :]

    tridiag_eigen(mp, d, e, z)
    z = 2**(2 * alpha) * mp.beta(alpha + 1 / 2,
                                 alpha + 1 / 2) * z.apply(lambda x: x**2)
    return d, z.T
Example #23
0
def form_square_block_matrix(mat1, mat2):
    """
    forms an amalgamated square block matrix out of square matrices mat1 and mat2
    if mat1 is mxm and mat2 is nxn, the returned matrix is (m+n)x(m+n) with mat1 and mat2 on the block diagonal
    if mat1 is mx1 and mat2 is nx1, the returned vector is (m+n)x1 with mat1 and mat2 stacked together
    """
    if mat1.cols == 1:
        mat3 = mp.matrix(mat1.rows + mat2.rows, 1)
        mat3[:mat1.rows] = mat1[:]
        mat3[mat1.rows:mat3.rows] = mat2[:]
    else:
        mat3 = mp.matrix(mat1.rows + mat2.rows, mat1.rows + mat2.rows)
        mat3[:mat1.rows, :mat1.rows] = mat1[:, :]
        mat3[mat1.rows:mat3.rows, mat1.rows:mat3.rows] = mat2[:, :]
    return mat3
Example #24
0
def phi2(x0, *, dps):  # (exp(x) - 1 - x) / (x * x), |x| > 1e-32 -> dps > 40
    with mp.workdps(dps):
        y = mp.matrix([
            mp.fdiv(mp.fsub(mp.expm1(x), x), mp.fmul(x, x))
            if x != 0.0 else mpf(1) / mpf(2) for x in x0
        ])
        return np.array(y.tolist(), dtype=x0.dtype)[:, 0]
Example #25
0
def get_ZTT_mineig_grad(ZTT, gradZTT):
    eigw, eigv = mp.eigh(ZTT)
    eiggrad = mp.matrix(len(gradZTT), 1)

    for i in range(len(eiggrad)):
        eiggrad[i] = mp.re(mp_conjdot(eigv[:, 0], gradZTT[i] * eigv[:, 0]))
    return eiggrad
Example #26
0
def create_simple_lattice(L, T, kind='rnd'):

    #--------------------------------------------------------------------------
    # forming adjacency matrix
    basis_x = np.tile(np.arange(L), T)
    basis_y = np.repeat(np.arange(T), L)
    X, Y = np.meshgrid(basis_x, basis_y)
    adj_matrix = AND(np.abs(X - X.T) == 1, np.abs(Y - Y.T) == 0)
    adj_matrix += AND(np.abs(X - X.T) == 0, np.abs(Y - Y.T) == 1)
    adj_matrix += np.triu((X - X.T) * (Y - Y.T) == 1 * (2 * (Y % 2) - 1))
    adj_matrix = adj_matrix + adj_matrix.T

    #--------------------------------------------------------------------------
    # setting couplings matrix
    if kind == 'rnd':
        R = np.random.normal(0, 1, size=(L * T, L * T))
        J_matrix = np.float_(adj_matrix) * (R + R.T) + 0j
    if kind == 'frm':
        J_matrix = -1.0 * np.float_(adj_matrix) + 0j
    if kind == 'afm':
        J_matrix = +1.0 * np.float_(adj_matrix) + 0j

    #--------------------------------------------------------------------------
    # transformation to j_i = exp(-J_i), in mpc format
    E = mp.mpc(0)
    j_matrix = mp.matrix(np.exp(-J_matrix).tolist())

    return E, j_matrix
Example #27
0
def _mp_svd(A, full_matrices=True):
    """Convenience wrapper for mpmath high-precision SVD."""
    assert mpmath, 'mpmath package is not installed'
    AA = mp.matrix(A.tolist())
    U, Sigma, VT = mp.svd(AA, full_matrices=full_matrices)
    return np.array(U.tolist()), np.array(Sigma.tolist()).ravel(), np.array(
        VT.tolist())
Example #28
0
def make_hamiltonian(dx, V, units, boundary='hard_wall', Bfield=None, prec=None):
    """Construct Hamiltonian matrix using a finite difference scheme.
    
    Input
        dx : float
            grid spacing
        V : np.array(len(x))
            potential energy funciton
        units : class
            class whose attributes are the fundamental constants hbar, e, m, c.
        boundary : string
            describes boundary conditions. Options are
                hard_wall
                periodic
        Bfield : np.float
            magnetic field strength
        prec : int
            desired decimal precision.
            
    Output
        H : np.array((len(x), len(x)))
    """
    
    # Assert that 'boundary' is one of the two valid options
    assert boundary is 'hard_wall' or boundary is 'periodic', "Invalid boundary condition specified."
    
    # Determine number of points representing position space:
    N = len(V)
    
    # Construct operator representations in position space:
    Top = _make_kinetic_energy(dx, N, units, boundary)
    Vop = _make_potential_energy(V, boundary)

    if Bfield != None:
        U_magnetic = _make_magnetic_dipole_energy(Bfield, dx, N, units)
    else:
        U_magnetic = np.zeros(Top.shape)
    
    if prec != None:
        from mpmath import mp
        from sympy import sympify
        mp.dps = prec
        H_ = mp.matrix(Top)+mp.matrix(Vop)
        H = np.array(sympify(H_.tolist()))
        return H_
    else:
        return Top + Vop + U_magnetic 
Example #29
0
def mmul(A, x):
    d, (r, c) = A
    z = mp.matrix(x.rows, x.cols)
    for j in range(len(d)):
        for i in range(x.cols):
            if x[c[j], i] != 0:
                z[r[j], i] += d[j] * x[c[j], i]
    return z
Example #30
0
 def two_body_reference(self, t1, num_1 = 0, num_2 = 1):
     """ reference notations are same as Yoel's notes
     using a precision of 64 digits for max accuracy """
     mp.dps = 64
     self.load_data()
     t1 = mp.mpf(t1)
     m_1 = mp.mpf(self.planet_lst[num_1].mass)
     m_2 = mp.mpf(self.planet_lst[num_2].mass)
     x1_0 = mp.matrix(self.planet_lst[num_1].loc)
     x2_0 = mp.matrix(self.planet_lst[num_2].loc)
     v1_0 = mp.matrix(self.planet_lst[num_1].v)
     v2_0 = mp.matrix(self.planet_lst[num_2].v)
     M = m_1 + m_2
     x_cm = (1/M)*((m_1*x1_0)+(m_2*x2_0))
     v_cm = (1/M)*((m_1*v1_0)+(m_2*v2_0))
     u1_0 = v1_0 - v_cm
     w = x1_0 - x_cm
     r_0 = mp.norm(w)
     alpha = mp.acos((np.inner(u1_0,w))/(mp.norm(u1_0)*mp.norm(w)))
     K = mp.mpf(self.G) * (m_2**3)/(M**2)
     u1_0 = mp.norm(u1_0)
     L = r_0 * u1_0 * mp.sin(alpha)
     cosgamma = ((L**2)/(K*r_0)) - 1
     singamma = -((L*u1_0*mp.cos(alpha))/K)
     gamma = mp.atan2(singamma, cosgamma)
     e = mp.sqrt(((r_0*(u1_0**2)*(mp.sin(alpha)**2)/K)-1)**2 + \
              (((r_0**2)*(u1_0**4)*(mp.sin(alpha)**2)*(mp.cos(alpha)**2))/(K**2)) )        
     r_theta = lambda theta: (L**2)/(K*(1+(e*mp.cos(theta - gamma))))
     f = lambda x: r_theta(x)**2/L
     curr_theta = 0
     max_it = 30
     it = 1
     converged = 0
     while ((it < max_it) & (converged != 1)):
         t_val = mp.quad(f,[0,curr_theta]) - t1
         dt_val = f(curr_theta)
         delta = t_val/dt_val
         if (abs(delta)<1.0e-6):
             converged = 1
         curr_theta -= delta
         it += 1 
     x1_new = mp.matrix([r_theta(curr_theta)*mp.cos(curr_theta), r_theta(curr_theta)*mp.sin(curr_theta)]) 
     # x2_new = -(m_1/m_2)*(x1_new) +(x_cm + v_cm*t1)
     x1_new = x1_new + (x_cm + v_cm*t1)
     return x1_new
Example #31
0
def test_eighe_fixed_matrix():
    A = mp.matrix([[2, 3], [3, 5]])
    run_eigsy(A)
    run_eighe(A)

    A = mp.matrix([[7, -11], [-11, 13]])
    run_eigsy(A)
    run_eighe(A)

    A = mp.matrix([[2, 11, 7], [11, 3, 13], [7, 13, 5]])
    run_eigsy(A)
    run_eighe(A)

    A = mp.matrix([[2, 0, 7], [0, 3, 1], [7, 1, 5]])
    run_eigsy(A)
    run_eighe(A)

    #

    A = mp.matrix([[2, 3 + 7j], [3 - 7j, 5]])
    run_eighe(A)

    A = mp.matrix([[2, -11j, 0], [+11j, 3, 29j], [0, -29j, 5]])
    run_eighe(A)

    A = mp.matrix([[2, 11 + 17j, 7 + 19j], [11 - 17j, 3, -13 + 23j],
                   [7 - 19j, -13 - 23j, 5]])
    run_eighe(A)
Example #32
0
def test_eighe_fixed_matrix():
    A = mp.matrix([[2, 3], [3, 5]])
    run_eigsy(A)
    run_eighe(A)

    A = mp.matrix([[7, -11], [-11, 13]])
    run_eigsy(A)
    run_eighe(A)

    A = mp.matrix([[2, 11, 7], [11, 3, 13], [7, 13, 5]])
    run_eigsy(A)
    run_eighe(A)

    A = mp.matrix([[2, 0, 7], [0, 3, 1], [7, 1, 5]])
    run_eigsy(A)
    run_eighe(A)

    #

    A = mp.matrix([[2, 3+7j], [3-7j, 5]])
    run_eighe(A)

    A = mp.matrix([[2, -11j, 0], [+11j, 3, 29j], [0, -29j, 5]])
    run_eighe(A)

    A = mp.matrix([[2, 11 + 17j, 7 + 19j], [11 - 17j, 3, -13 + 23j], [7 - 19j, -13 - 23j, 5]])
    run_eighe(A)
Example #33
0
def get_inc_ZTT_mineig(incLags,
                       include,
                       Olist,
                       UPlistlist,
                       eigvals_only=False):
    Lags = np.zeros(len(include), dtype=type(mp.one))
    Lags[include] = np.squeeze(incLags.tolist())
    Lags = mp.matrix(Lags)
    return get_ZTT_mineig(Lags, Olist, UPlistlist, eigvals_only=eigvals_only)
Example #34
0
def irandmatrix(n, range=10):
    """
    random matrix with integer entries
    """
    A = mp.matrix(n, n)
    for i in xrange(n):
        for j in xrange(n):
            A[i, j] = int((2 * mp.rand() - 1) * range)
    return A
Example #35
0
def irandmatrix(n, range = 10):
    """
    random matrix with integer entries
    """
    A = mp.matrix(n, n)
    for i in xrange(n):
        for j in xrange(n):
            A[i,j]=int( (2 * mp.rand() - 1) * range)
    return A
Example #36
0
def NWsc(M, object=False):
    W = np.array(MPDBsc((mp.matrix(M))).tolist(),dtype=np.float64)
    X = np.copy(M)
    dM = spl.det(M)**(1.0/2)
    ras = result()
    for i in range(1,31):
        uk = np.abs(spl.det(X)/dM)**(-1.0/i)
        X = (0.5)*(uk*X + (uk**(-1))*spl.inv(X).dot(M))
        print (spl.norm(X-W)/spl.norm(W))
        ras.res.append((spl.norm(X-W)/spl.norm(W)))
    ras.iter = i
    ras.ris = X

    return (ras if object else X)
Example #37
0
def to_mpmath_matrix(data, **kwargs):
    def mpmath_matrix_data(m):
        if not m.has_form('List', None):
            return None
        if not all(leaf.has_form('List', None) for leaf in m.leaves):
            return None
        return [[str(item) for item in row.leaves] for row in m.leaves]

    if not isinstance(data, list):
        data = mpmath_matrix_data(data)
    try:
        return mp.matrix(data)
    except (TypeError, AssertionError, ValueError):
        return None
Example #38
0
def DBsc(M, object=False):
    W = np.array(MPDBsc((mp.matrix(M))).tolist(),dtype=np.float64)
    ras = result()
    Xk = np.copy(M)
    Yk = np.eye(M.shape[0])
    dA = spl.det(M)**(1.0/2)
    for i in range(1,31):
        uk = np.abs(spl.det(Xk)/dA)**(-1.0/i)
        Xk1 = (Xk*uk + (uk**-1)*np.linalg.inv(Yk))/2
        Yk1 = (Yk*uk + (uk**-1)*np.linalg.inv(Xk))/2
        Xk = Xk1
        Yk = Yk1
        ras.res.append((spl.norm(Xk-W)/spl.norm(W)))
    ras.iter = i
    ras.ris = Xk

    return (ras if object else Xk)
Example #39
0
def productDBsc(A, object=False):
    W = np.array(MPDBsc((mp.matrix(A))).tolist(),dtype=np.float64)
    ras = result()
    M = np.copy(A)
    Xk = np.copy(A)
    Yk = np.eye(A.shape[0])
    I = np.eye(M.shape[0])
    for i in range(1,31):
        uk = np.abs(spl.det(M))**(-1.0/(2*i))
        Xk = (0.5)*(uk)*(Xk).dot(I + ((uk**-2)*(np.linalg.inv(M))))
        Yk = (0.5)*(uk)*(Yk).dot(I + ((uk**-2)*(np.linalg.inv(M))))
        M  = (0.5)*( I + ((uk**2)*M + ((uk**-2)*np.linalg.inv(M)))/2.0)
        ras.res.append(spl.norm(Xk-W)/spl.norm(W))
    ras.iter = i
    ras.ris = Xk

    return (ras if object else Xk)
Example #40
0
def INsc1(A, object=False):
    X = np.copy(A)
    E = 0.5*(np.eye(A.shape[0])-A)
    dA = spl.det(A)**(0.5)
    ras = result()
    W = np.array(MPDBsc((mp.matrix(A))).tolist(),dtype=np.float64)
    for i in range (1,31):
        print i
        detX =  spl.det(X)
        uk = np.abs(detX/dA)**(-1.0/i)
        Etk = (uk**(-1))*(E + (0.5*X)) - (0.5)*uk*X
        X = uk*X + Etk
        E = (-0.5)*(Etk.dot(spl.inv(X))).dot(Etk)
        ras.res.append(spl.norm(X-W)/spl.norm(W))
        print ras.res
    ras.iter = i
    ras.ris = X
    return (ras if object else X)
gammac	= np.sqrt(1j*omega*mu0*sigma);

# shortcuts
i0 = lambda x: mp.besseli(0,x)
i1 = lambda x: mp.besseli(1,x)
k0 = lambda x: mp.besselk(0,x)
k1 = lambda x: mp.besselk(1,x)

# Zap	= etac/(2*math.pi*a)*(sp.iv(0,gammac*a) / sp.iv(1,gammac*a)); 
ZapA = etac/(2*math.pi*a)

#Zbp	= etac/(2*math.pi*b)* (sp.iv(0,gammac*b) * sp.kv(1,gammac*c) + sp.kv(0,gammac*b) * sp.iv(1,gammac*c)) /  (sp.iv(1,gammac*b)*sp.kv(1,gammac*b) - sp.iv(1,gammac*b)*sp.kv(1,gammac*b))
ZbpA = etac/(2*math.pi*b)


ZL = mp.matrix(f.size, 1)
YC = mp.matrix(f.size, 1)
Zap = mp.matrix(f.size, 1)
Zbp = mp.matrix(f.size, 1)
Zp = mp.matrix(f.size, 1)
Yp = mp.matrix(f.size, 1)
Zc = mp.matrix(f.size, 1)
A = np.ndarray(f.size)
R = np.ndarray(f.size)
I = np.ndarray(f.size)
Gr = np.ndarray(f.size)
Gi = np.ndarray(f.size)

for n in range(f.size):
    Zap[n] = ZapA[n]*( i0(gammac[n]*a) / i1(gammac[n]*a) )
    Zbp[n] = ZbpA[n] * ((i0(gammac[n]*b) * k1(gammac[n]*c) + k0(gammac[n]*b)*i1(gammac[n]*c)) / ( i1(gammac[n]*c)*k1(gammac[n]*b) - i1(gammac[n]*b)*k1(gammac[n]*c) ) )
Example #42
0
import numpy as np
import scipy.linalg as spl
from mpmath import mp,workdps
import matplotlib.pyplot as plt

#mp.dps = 33
mp.dps = 128
matr = mp.matrix(
[[ '115.80200375',  '22.80402473',   '13.69453064',   '54.28049263',    '58.26628814'],
[  '22.80402473',   '86.14887381',   '53.79999432',   '42.78548627',    '37.16598947'],
[  '13.69453064',   '53.79999432',  '110.9695448' ,   '37.24270321',    '59.04033897'],
[  '54.28049263',   '42.78548627',   '37.24270321',   '95.79388469',    '27.90238338'],
[  '58.26628814',   '37.16598947',   '59.04033897',   '27.90238338',    '87.42667939']])

matr1 = np.array(
[[ 115.80200375,  22.80402473,   13.69453064,   54.28049263,  58.26628814],
[  22.80402473,   86.14887381,   53.79999432,   42.78548627, 37.16598947],
[  13.69453064,   53.79999432,  110.9695448 ,   37.24270321, 59.04033897],
[  54.28049263,   42.78548627,   37.24270321,   95.79388469, 27.90238338],
[  58.26628814,   37.16598947,   59.04033897,   27.90238338, 87.42667939]])



class result:
    def __init__(self,iter=0,ris=None, res=[]):
        self.iter = 0
        self.ris = 0
        self.res = []

#Multiple Precision DB Iteration