Ejemplo n.º 1
0
    def solve_nonlinear(self, inputs, outputs):
        """
        Use numpy to solve Ax=b for x.

        Parameters
        ----------
        inputs : Vector
            unscaled, dimensional input variables read via inputs[key]
        outputs : Vector
            unscaled, dimensional output variables read via outputs[key]
        """
        vec_size = self.options['vec_size']
        vec_size_A = self.vec_size_A

        # lu factorization for use with solve_linear
        self._lup = []
        if vec_size > 1:
            for j in range(vec_size_A):
                lhs = inputs['A'][j] if vec_size_A > 1 else inputs['A']
                self._lup.append(linalg.lu_factor(lhs))

            for j in range(vec_size):
                idx = j if vec_size_A > 1 else 0
                outputs['x'][j] = linalg.lu_solve(self._lup[idx], inputs['b'][j])
        else:
            self._lup = linalg.lu_factor(inputs['A'])
            outputs['x'] = linalg.lu_solve(self._lup, inputs['b'])
Ejemplo n.º 2
0
def dampnewton(x,F,DF,q=0.5,tol=1e-10):
    cvg = []
    lup = lu_factor(DF(x))
    s = lu_solve(lup,F(x))
    xn = x-s
    lam = 1
    st = lu_solve(lup,F(xn)) # simplified Newton
    while norm(st) > tol*norm(xn):
        while norm(st) > (1-lam*0.5)*norm(s):
            lam *= 0.5
            if lam < 1e-10:
                cvg = -1
                print 'Failure of convergence'
                return x, cvg
            xn = x-lam*s
            st = lu_solve(lup,F(xn)) # simplified Newton
        cvg += [[lam, norm(xn), norm(F(xn))]]
        x = xn
        lup = lu_factor(DF(x))
        s = lu_solve(lup,F(x))
        lam = min(lam/q, 1.) # Wozu dieser Test?
        xn = x-lam*s
        st = lu_solve(lup,F(xn)) # simplified Newton
    x = xn
    return x, array(cvg)
 def updatedata(self, A):
     if self.update:
         if self.corr:
             self.data.B = self.data.w*(linalg.norm(A,1)/linalg.norm(self.data.w,1))
             self.data.C = self.data.v*(linalg.norm(A,Inf)/linalg.norm(self.data.v,1))
         else:
             # Note: Problem when singular vectors switch smallest singular value (See NewLorenz).
             #       To overcome this, I have implemented a 1e-8 random nudge.
             try:
                 ALU = linalg.lu_factor(A)
                 BC = linalg.lu_solve(ALU, c_[linalg.lu_solve(ALU, self.data.B + 1e-8*self.data.Brand), \
                                      self.data.C + 1e-8*self.data.Crand], trans=1)
                 C = linalg.lu_solve(ALU, BC[:,-1*self.data.q:])
                 B = BC[:,0:self.data.p]
             except:
                 if self.C.verbosity >= 1:
                     print 'Warning: Problem updating border vectors.  Using svd...'
                 U, S, Vh = linalg.svd(A)
                 B = U[:,-1*self.data.p:]
                 C = num_transpose(Vh)[:,-1*self.data.q:]
         
             bmult = cmult = 1
             if matrixmultiply(transpose(self.data.B), B) < 0:
                 bmult = -1
             if matrixmultiply(transpose(self.data.C), C) < 0:
                 cmult = -1
             self.data.B = bmult*B*(linalg.norm(A,1)/linalg.norm(B))
             self.data.C = cmult*C*(linalg.norm(A,Inf)/linalg.norm(C))
Ejemplo n.º 4
0
def time_LU():
    """Print the times it takes to solve a system of equations using
    LU decomposition and (A^-1)B where A is 1000x1000 and B is 1000x500."""
    A = np.random.random((1000,1000))
    b = np.random.random((1000,500))
    start = time.time()
    L = la.lu_factor(A)
    a = time.time() - start
    start = time.time()
    A_inv = la.inv(A)
    a2 = time.time() - start
    start = time.time()
    la.lu_solve(L,b)
    a3 = time.time() - start
    start = time.time()
    np.dot(A_inv, b)
    a4 = time.time() - start

    
    time_lu_factor = a  # set this to the time it takes to perform la.lu_factor(A)
    time_inv = a2 # set this to the time it takes to take the inverse of A
    time_lu_solve = a3  # set this to the time it takes to perform la.lu_solve()
    time_inv_solve = a4  # set this to the time it take to perform (A^-1)B


    print "LU solve: " + str(time_lu_factor + time_lu_solve)
    print "Inv solve: " + str(time_inv + time_inv_solve)
    
    # What can you conclude about the more efficient way to solve linear systems?
    print "Better to use LU decomposition than inverse, cause it is NEVER a good idea to calculate an inerse"  # print your answer here.
 def updatedata(self, A):
     # Update b, c
     try:
         ALU = linalg.lu_factor(A)
         BC = linalg.lu_solve(ALU, c_[linalg.lu_solve(ALU, self.data.b + 1e-8*self.data.Brand[:,:1]), \
                              self.data.c + 1e-8*self.data.Crand[:,:1]], trans=1)
         C = linalg.lu_solve(ALU, BC[:,-1:])
         B = BC[:,:1]
     except:
         if self.C.verbosity >= 1:
             print 'Warning: Problem updating border vectors.  Using svd...'
         U, S, Vh = linalg.svd(A)
         B = U[:,-1:]
         C = num_transpose(Vh)[:,-1:]
 
     bmult = cmult = 1
     if matrixmultiply(transpose(self.data.b), B) < 0:
         bmult = -1
     if matrixmultiply(transpose(self.data.c), C) < 0:
         cmult = -1
     self.data.b = bmult*B*(linalg.norm(A,1)/linalg.norm(B))
     self.data.c = cmult*C*(linalg.norm(A,Inf)/linalg.norm(C))
     
     # Update
     if self.update:
         self.data.B[:,0] = self.data.b*(linalg.norm(A,1)/linalg.norm(self.data.b))
         self.data.C[:,0] = self.data.c*(linalg.norm(A,Inf)/linalg.norm(self.data.c))
         
         self.data.B[:,1] = self.data.w[:,2]*(linalg.norm(A,1)/linalg.norm(self.data.w,1))
         self.data.C[:,1] = self.data.v[:,2]*(linalg.norm(A,Inf)/linalg.norm(self.data.v,1))
         
         self.data.D[0,1] = self.data.g[0,1]
         self.data.D[1,0] = self.data.g[1,0]
 def getVW(self, A):
     # V --> m, W --> n
     #print self.data
     MLU = linalg.lu_factor(c_[r_[A,transpose(self.data.C)], r_[self.data.B,self.data.D]])
     V = linalg.lu_solve(MLU,r_[zeros((self.data.n,self.data.q), Float), eye(self.data.q)])
     W = linalg.lu_solve(MLU,r_[zeros((self.data.m,self.data.p), Float), eye(self.data.p)],trans=1)
     
     return V, W
Ejemplo n.º 7
0
def solveLoop(A,LU,B,f):
    if f==True:
        # the fast way
        for i in xrange(B.shape[0]):
            la.lu_solve(LU,B[i])
    else:
        # the slow way
        for i in xrange(B.shape[0]):
            la.solve(A,B[i])
def Solve():
    # the students should have code to generate the random matrices, inverse, LU, and solve
    A = np.random.rand(1000,1000)
    B = np.random.rand(1000,500)
    Ai = la.inv(A)
    (lu,piv) = la.lu_factor(A)
    
    # the students should report the time for the following operations
    np.dot(Ai,B)
    la.lu_solve((lu,piv),B)
Ejemplo n.º 9
0
 def test(self, p):
     """ Determine which quadrilateral(s) each point is in
     Args:
         p: the points to test
     
     Returns:
         A N x len(p) boolean array, where N is the number of quadrilaterals
     """
     p1 = np.vstack((p.T, np.ones(len(p)))) # set up the points for the barycentric calculation
     bary1 = np.array(map(lambda lup: sl.lu_solve(lup, p1), self.lup1)) # calculate the barycentric coords for the first set of triangles
     bary2 = np.array(map(lambda lup: sl.lu_solve(lup, p1), self.lup2)) # ... and the second
     in1 = np.all((bary1 >=0) * (bary1 <=1), axis=1) # test that they are all in [0,1]
     in2 = np.all((bary2 >=0) * (bary2 <=1), axis=1)
     return in1+in2 # + is "or"
Ejemplo n.º 10
0
def do_problem_5(datafile):
    print_arr = lambda x,y: \
                print("{} =\n{}".format(y,
                                        np.array2string(x,precision = 6,
                                                        suppress_small = True,
                                                        separator=',')))
    np.set_printoptions(precision=6)
    A = loadtxt(datafile)
    (n,m) = A.shape
    (LU,p) = lup_decomp(A)
    (LU_control,p_control) = la.lu_factor(A)
    ## Check that my LU is equal to the actual LU, with a small
    ## tolerence for floating point rouding errors
    assert(np.allclose(LU,LU_control));
    
    L = np.tril(LU)
    U = np.triu(LU)
    P = np.zeros((n,n))
    for i in range(n):
        L[i,i] = 1
        P[i,p[i]] = 1
    print("Problem 5:")
    print("LUP decomposition")
    print_arr(L,"L")
    print_arr(U,"U")
    print_arr(P,"P")
    print("Solving Ax = b for various values of b")
    
    b1 = array([2,3,-1,5,7],dtype=float)
    x1 = lup_solve(LU,p,b1)
    x1_control = la.lu_solve((LU_control,p_control),b1)
    assert(np.allclose(x1,x1_control));
    print_arr(b1,"b1")
    print_arr(x1,"x1")
    
    b2 = array([15,29,8,4,-49],dtype=float)
    x2 = lup_solve(LU,p,b2)
    x2_control = la.lu_solve((LU_control,p_control),b2)
    assert(np.allclose(x2,x2_control));
    print_arr(b2,"b2")
    print_arr(x2,"x2")

    b3 = array([8,-11,3,-8,-32],dtype=float)
    x3 = lup_solve(LU,p,b3)
    x3_control = la.lu_solve((LU_control,p_control),b3 )
    assert(np.allclose(x3,x3_control));
    print_arr(b3,"b3")
    print_arr(x3,"x3")
Ejemplo n.º 11
0
    def solve_transpose(self, din):
        from scipy.linalg import lu_solve
        nrows = self.Alu.mshape[0]
        nblock = self.Alu.blockshape[0] #assume a square block!

        d = din.reshape((nrows,nblock))
        x = zeros(d.shape, dtype=self.Alu.dtype)
        
        #Forward substitution pass
        # b[0].T dnew[0] = d[0]
        # b[i].T dnew[i] = d[i] - c[i-1].T dnew[i-1]
        x[0] = d[0]
        for row in range(0,nrows):
            if row>0:
                x[row] = d[row] - dot(self.Alu.get_raw_block(row-1,2).T, x[row-1])
            if any(isnan(x[row])) or any(isinf(x[row])):
                print row, x[row]
            x[row] = lu_solve((self.Alu.get_raw_block(row,1),self.pivots[row]),\
                     x[row], trans=1)

        #Backward substitution
        # x[i] = d[i] - anew[i+1] x[i+1]
        for row in range(nrows-2,-1,-1):
            x[row] -= dot(self.Alu.get_raw_block(row+1,0).T, x[row+1])

        return x.reshape(din.shape)
Ejemplo n.º 12
0
    def solve_overlap(self, b):
	"""
	x = solve_overlap(b)

	Solve for the overlap matrix: S x = b.

	Parameters
	----------
	b : 1D complex array.
	
	Returns
	-------
	x : 1D complex array.
	"""
	x = zeros(self.basis_size, dtype=complex)
	
	for i in range(self.el_basis_size):
	    
	    #Indices of a submatrix.
	    my_slice = slice(i*self.vib_basis_size, (i+1)*self.vib_basis_size)
	    
	    #Solve for the B-spline overlap matrix.
	    x[my_slice] = lu_solve(self.overlap_fact, b[my_slice])
	
	return x
Ejemplo n.º 13
0
    def SolveNextTime(self):
        r"""
        Calculate the next time (factorization)
        and update the time stack grids
        """
        
        try:
            self.tstep += 1
        except :
            self.tstep = 0
            self.LinearSystem()
            # gets the m factor from the solved system
            self.mUtfactor = ln.lu_factor(self.mUt)

        self.Source(self.tstep)
        # in time
        # As t is in [0, 1, 2] (2nd order)
        # time t in this case is Utime[2]
        v = self.Independent()
        result = ln.lu_solve(self.mUtfactor, v)
        # reshape the vector to became a matrix again
        self.Ufuture = result
        # make the update in the time stack
        # before [t-2, t-1,  t]
        # after  [t-1, t,  t+1]
        # so t-2 receive t-1 and etc.
        self.Uprevious = self.Ucurrent 
        self.Ucurrent = self.Ufuture
        
        return self.Ufuture
Ejemplo n.º 14
0
def factiz(K):
    """
    Helper function to behave the same way scipy.sparse.factorized does, but
    for dense matrices.
    """
    luf = lu_factor(K)
    return lambda x: matrix(lu_solve(luf, x))
Ejemplo n.º 15
0
def invpower(e,A,B=None):
	if B is None:
		B = eye(len(A))
	K = A - B*e
	G = lu_factor(K)
	x = ones([len(A),1],complex)/len(A)
	iter = 0
	error = 10
	#for i in range(8):
	while error > 1e-8 and iter < 20:
		try:
			x = lu_solve(G,x)
		    
		except:
			print 'LU Exception'
			x = solve(K,x)
		    
		x = x/norm(x,ord=inf)
		error = norm(dot(A,x)-e*dot(B,x))
		iter = iter +1
		print 'invpower error = ',error
	x = x*conj(x[0])
	print 'Eval = ',e
	print 'Evect Real = ',norm(real(x))
	print 'Evect Imag = ',norm(imag(x))
	return x
Ejemplo n.º 16
0
def lnlike(h, X, y, covfunc):
    y = np.matrix(np.array(y).flatten()).T
    K = covfunc(X, X, h, wn = True)
    sign, logdetK = np.linalg.slogdet(K)
    alpha = np.mat(la.lu_solve(la.lu_factor(K),y))
    logL = -0.5*y.T * alpha - 0.5*logdetK - (y.size/2.)*np.log(2)
    return np.array(logL).flatten()
Ejemplo n.º 17
0
    def hotCmntsForTest(self, postId, nCmnts = 5):
        self.buildgraph(postId)
        
        testsizes = [shape(self.prg)[0], 800, 600, 400, 200]
        
        for size in testsizes:
            
            self.prg = self.prg[0:size,0:size]
            lil = lil_matrix(self.prg)
            
            start = clock()
            #eig  = eigs(self.prg, k=1, return_eigenvectors =False)
            eig = eigs(lil, return_eigenvectors =False, maxiter=10, tol=1E-5)
            eig = eig[0].real
            eig = 1/eig
            eigTime = clock() - start            
            print 'test_size:',size, 'eigTime:',eigTime        

            one = ones(size)
            m = eye(size) - eig*lil  
            
            start = clock()
            cmnts_ranking = lu_solve((m, one), one)
            solveTime = clock() - start
            
            print 'test_size:',size, 'solveTime:',solveTime
Ejemplo n.º 18
0
    def SolveNextTime(self):
        r"""
        Calculate the next time (factorization)
        and update the time stack grids
        """

        try:
            self.tstep += 1
        except :
            self.tstep = 0
            self.LinearSystem()
            # gets the m factor from the solved system
            self.mUtfactor = ln.lu_factor(self.mUt)

        # As t is in [0, 1, 2] (2nd order)
        # time t in this case is Utime[2]
        # the independent term of the matrix, due the pressure field
        v = self.Independent()

        result = ln.lu_solve(self.mUtfactor, v)
        # reshape the vector to become a matrix again
        self.Ufuture = np.reshape(result, (self.Nz, self.Nx))

        # make the update in the time stack
        # before [t-2, t-1,  t]
        # after  [t-1, t,  t+1]
        # so t-2 receive t-1 and etc.
        # make the update in the time stack
        self.Uprevious[:][:] = self.Ucurrent[:][:]
        self.Ucurrent[:][:] = self.Ufuture[:][:]        
        
        return self.Ufuture
Ejemplo n.º 19
0
    def solve_linear(self, d_outputs, d_residuals, mode):
        r"""
        Back-substitution to solve the derivatives of the linear system.

        If mode is:
            'fwd': d_residuals \|-> d_outputs

            'rev': d_outputs \|-> d_residuals

        Parameters
        ----------
        d_outputs : Vector
            unscaled, dimensional quantities read via d_outputs[key]
        d_residuals : Vector
            unscaled, dimensional quantities read via d_residuals[key]
        mode : str
            either 'fwd' or 'rev'
        """
        if mode == 'fwd':
            sol_vec, forces_vec = d_outputs, d_residuals
            t = 0
        else:
            sol_vec, forces_vec = d_residuals, d_outputs
            t = 1

        sol_vec['disp_aug'] = linalg.lu_solve(self._lup, forces_vec['disp_aug'], trans=t)
Ejemplo n.º 20
0
def marglike(x, y, hyper, white_noise = False): # FIXME: build optional white noise into this kernel

    # Calculate covariance matrix
    K = matrifysquare(hyper, x, 0)
    K = 0.5* ( K + K.T) # Forces K to be perfectly symmetric

    # Calculate derivatives
    # dKdsigma = matrifysquare(hyper, x, 1) # Derivative w.r.t. log(sigma)
    # dKdlambda1 = matrifysquare(hyper, x, 2) # Derivative w.r.t. log(lambda1)
    # dKdh1 = matrifysquare(hyper, x, 3) # Derivative w.r.t. log(h1)

    sign, logdetK = np.linalg.slogdet(K)
    
    invKy = -0.5 * y.T *  np.mat(la.lu_solve(la.lu_factor(K),y)) \
        - 0.5 * logdetK - (y.size/2.) * np.log(2*np.pi)
    
    U = np.linalg.cholesky(K)

    n = len(x)
    L = - sum(np.log(np.diag(U))) -0.5 * y * invKy - n*0.5*np.log(2*np.pi)
    # dLdsigma = 0.5 * sum(np.diag(invKy*invKy.T*dKdsigma - (np.linalg.solve(K, dKdsigma)) ))
    # dLdlambda1 = 0.5 * sum(np.diag(invKy*invKy.T*dKdlambda1 - (np.linalg.solve(K, dKdlambda1)) ))
    # dKdh1 = 0.5 * sum(np.diag(invKy*invKy.T*dKdh1 - (np.linalg.solve(K, dKdh1)) ))

    return -L #, [-dKdsigma, -dKdlambda1, -dKdh1]
def root_finding_newton(u, m, alpha, V, Sigma, U, G, Cov, dw):
	"""
	:param u: initial vector of u
	:param m: vector of default model for the Lehmann spectral function
	:param alpha: scalar value, controls the relative weight of maximizing entropie and minimizing kind. of least squares fit.
	:param V: part of singular SVD of K, K = V*Sigma*U.T
	:param Sigma: part of singular SVD of K, K = V*Sigma*U.T
	:param U: part of singular SVD of K, K = V*Sigma*U.T
	:param G: Vector of all average values of the Greensfunction for each time step
	:param Cov: Vector with variance of the re-binned, gaussian distributed QMC approximations for the different time-steps
	:param dw: omega step size
	:return:
	"""

	s=len(u)
	max_val = np.sum(m)
	K_s = np.dot(V,np.dot(Sigma,U.T))
	diff = 1.
	count1 = 1
	max_iter = 1000

	while diff > 1e-8 and count1 <= max_iter:
		print(count1)
		A_appr = m * np.exp(np.dot(U,u))
		A_old = A_appr
		inv_cov = (1. / np.diagonal(Cov)**2)
		inv_cov_mat = np.diag(inv_cov)
		dLdF = - inv_cov * (G - np.dot(K_s, A_appr))
		F_u = - alpha * u - np.dot(Sigma,np.dot(V.T,dLdF))
		M = np.dot(Sigma,np.dot(V.T,np.dot(inv_cov_mat,np.dot(V,Sigma))))
		T = np.dot(U.T,np.dot(np.diag(A_appr),U))
		J = alpha * np.diag(np.ones((s))) + np.dot(M,T)
		lu_and_piv = lu_factor(J)
		delta_u = lu_solve(lu_and_piv,F_u)
		A_appr = m * np.exp(np.dot(U,u + delta_u))
		count2 = 1
		while np.linalg.norm(A_appr - A_old) > max_val and count2 <= max_iter:
			J = (alpha+count2*1e10) * np.diag(np.ones((s))) + np.dot(M,T)
			lu_and_piv = lu_factor(J)
			delta_u = lu_solve(lu_and_piv,F_u)
			A_appr = m * np.exp(np.dot(U,u + delta_u))
			count2 +=1
		u_old = u 
		u = u + delta_u
		diff = np.abs(np.sum(u-u_old))
		count1 += 1
	return u	
def max_likelihood_estimate(G,V_singular,U_singular,Sigma_singular):
	"""
	:param G: Vector of all average values of the Greensfunction for each time step
	:param V_singular: part of the SVD of K , K = V*Sigma.T*U.T which contains only the components for non zero singular values.
	:param U_singular: part of the SVD of K , K = V*Sigma.T*U.T which contains only the components for non zero singular values.
	:param Sigma_singular: part of the SVD of K , K = V*Sigma.T*U.T which contains only the components for non zero singular values.
	:return: Maximum likelihood estimate of the Lehmann spectral function A.
	"""

	inv_Sigma_singular = np.linalg.inv(Sigma_singular)

	inv_K_singular = np.dot(U_singular,np.dot(inv_Sigma_singular,V_singular.T))

	return np.dot(inv_K_singular,G)


	s=len(u)
	max_val = np.sum(m)
	K_s = np.dot(V,np.dot(Sigma,U.T))
	diff = 1.
	count1 = 1
	max_iter = 1000

	while diff > 1e-8 and count1 <= max_iter:
		A_appr = m * np.exp(np.dot(U,u))
		inv_cov = (1. / np.diagonal(Cov)**2)
		inv_cov_mat = np.diag(inv_cov)
		dLdF = - inv_cov * (G - np.dot(K_s, A_appr))
		F_u = - alpha * u - np.dot(Sigma,np.dot(V.T,dLdF))
		M = np.dot(Sigma,np.dot(V.T,np.dot(inv_cov_mat,np.dot(V,Sigma))))
		T = np.dot(U.T,np.dot(np.diag(A_appr),U))
		J = alpha * np.diag(np.ones((s))) + np.dot(M,T)
		lu_and_piv = lu_factor(J)
		delta_u = lu_solve(lu_and_piv,F_u)
		count2 = 1
		h = np.abs(np.dot(F_u.T,F_u))/np.abs(np.dot(F_u.T,np.dot(Jac,F_u)))
		mu = 1./h
		while np.dot(delta_u.T,np.dot(T,delta_u.T)) > max_val and count2 <= max_iter:
			J = (alpha+count2*mu) * np.diag(np.ones((s))) + np.dot(M,T)
			lu_and_piv = lu_factor(J)
			delta_u = lu_solve(lu_and_piv,F_u)
			count2 +=1
		u_old = u 
		u = u + delta_u
		diff = np.abs(np.sum(u-u_old))
		count1 += 1
	return u
Ejemplo n.º 23
0
Archivo: gpr.py Proyecto: B-Rich/PyMVPA
    def _predict(self, data):
        """
        Predict the output for the provided data.
        """
        retrainable = self.params.retrainable
        ca = self.ca

        if not retrainable or self._changedData['testdata'] \
               or self._km_train_test is None:
            if __debug__:
                debug('GPR', "Computing train test kernel matrix")
            self.__kernel.compute(self._train_fv, data)
            km_train_test = asarray(self.__kernel)
            if retrainable:
                self._km_train_test = km_train_test
                ca.repredicted = False
        else:
            if __debug__:
                debug('GPR', "Not recomputing train test kernel matrix")
            km_train_test = self._km_train_test
            ca.repredicted = True


        predictions = Ndot(km_train_test.transpose(), self._alpha)

        if ca.is_enabled('predicted_variances'):
            # do computation only if conditional attribute was enabled
            if not retrainable or self._km_test_test is None \
                   or self._changedData['testdata']:
                if __debug__:
                    debug('GPR', "Computing test test kernel matrix")
                self.__kernel.compute(data)
                km_test_test = asarray(self.__kernel)
                if retrainable:
                    self._km_test_test = km_test_test
            else:
                if __debug__:
                    debug('GPR', "Not recomputing test test kernel matrix")
                km_test_test = self._km_test_test

            if __debug__:
                debug("GPR", "Computing predicted variances")
            L = self._L
            # v = NLAsolve(L, km_train_test)
            # Faster:
            piv = np.arange(L.shape[0])
            v = SL.lu_solve((L.T, piv), km_train_test, trans=1)
            # self.predicted_variances = \
            #     Ndiag(km_test_test - Ndot(v.T, v)) \
            #     + self.sigma_noise**2
            # Faster formula: np.diag(Ndot(v.T, v)) = (v**2).sum(0):
            ca.predicted_variances = Ndiag(km_test_test) - (v ** 2).sum(0) \
                                       + self.params.sigma_noise ** 2
            pass

        if __debug__:
            debug("GPR", "Done predicting")
        ca.estimates = predictions
        return predictions
Ejemplo n.º 24
0
def prob4(N=11):
    """Time different scipy.linalg functions for solving square linear systems.
    Plot the system size versus the execution times. Use log scales if needed.
    """
    domain = 2**np.arange(1,N+1)
    inv, solve, lu_factor, lu_solve = [], [], [], []

    for n in domain:
        A = np.random.random((n,n))
        b = np.random.random(n)

        start = time()
        la.inv(A).dot(b)
        inv.append(time()-start)

        start = time()
        la.solve(A, b)
        solve.append(time()-start)

        start = time()
        x = la.lu_factor(A)
        la.lu_solve(x, b)
        lu_factor.append(time()-start)

        start = time()
        la.lu_solve(x, b)
        lu_solve.append(time()-start)

    plt.subplot(121)
    plt.plot(domain, inv, '.-', lw=2, label="la.inv()")
    plt.plot(domain, solve, '.-', lw=2, label="la.solve()")
    plt.plot(domain, lu_factor, '.-', lw=2,
                                    label="la.lu_factor() and la.lu_solve()")
    plt.plot(domain, lu_solve, '.-', lw=2, label="la.lu_solve() alone")
    plt.xlabel("n"); plt.ylabel("Seconds")
    plt.legend(loc="upper left")

    plt.subplot(122)
    plt.loglog(domain, inv, '.-', basex=2, basey=2, lw=2)
    plt.loglog(domain, solve, '.-', basex=2, basey=2, lw=2)
    plt.loglog(domain, lu_factor, '.-', basex=2, basey=2, lw=2)
    plt.loglog(domain, lu_solve, '.-', basex=2, basey=2, lw=2)
    plt.xlabel("n")

    plt.suptitle("Problem 4 Solution")
    plt.show()
Ejemplo n.º 25
0
 def get_adjoint_voltages(self, d):
     """
     Return adjoint voltages for sensitivity calculations
 
     d: rhs vector
     """
     # solve transposed linear system
     return linalg.lu_solve(self._LUpiv, d, trans = 1)
Ejemplo n.º 26
0
    def solve_nonlinear(self, params, unknowns, resids):
        """ Use numpy to solve Ax=b for x.
        """

        # lu factorization for use with solve_linear
        self.lup = linalg.lu_factor(params['A'])

        unknowns['x'] = linalg.lu_solve(self.lup, params['b'])
        resids['x'] = params['A'].dot(unknowns['x']) - params['b']
Ejemplo n.º 27
0
 def interpolate(self, v):
     """ Find all the triangles that each v is in, then average the linear interpolation of the phases"""
     v1 = np.vstack((v.T, np.ones(len(v)))) # set up the points for the barycentric calculation
     bary1 = np.array(map(lambda lup: sl.lu_solve(lup, v1), self.lup1)) # calculate the barycentric coords for the first set of triangles
     bary2 = np.array(map(lambda lup: sl.lu_solve(lup, v1), self.lup2)) # ... and the second
     in1 = np.all((bary1 >=0) * (bary1 <=1), axis=1) # test that they are all in [0,1]
     in2 = np.all((bary2 >=0) * (bary2 <=1), axis=1)
     nTris = np.sum(in1,axis=0) + np.sum(in2, axis=0)
     vfound = nTris > 0
     phases = np.zeros((len(v), self.plen))
     phi = np.zeros((len(v)))
     for tidx,vidx in zip(*in1.nonzero()):
         phases[vidx] += np.dot(self.ptri1[tidx], bary1[tidx, :, vidx])
         phi[vidx] += np.dot(self.phitri1[tidx], bary1[tidx, :, vidx]) 
     for tidx,vidx in zip(*in2.nonzero()):
         phases[vidx] += np.dot(self.ptri2[tidx], bary2[tidx, :, vidx]) 
         phi[vidx] += np.dot(self.phitri2[tidx], bary2[tidx, :, vidx]) 
     return vfound, phases[vfound] / nTris[vfound].reshape(-1,1), phi[vfound] / nTris[vfound]        
Ejemplo n.º 28
0
    def __call__(self, u, b):
        if len(u.shape) == 3:
            Ny, Nz = u.shape[1:]
            if self.solver == "scipy":
                for i in range(Ny):
                    for j in range(Nz):
                        u[:-4:2, i, j] = lu_solve(self.Le[i][j], b[:-4:2, i, j])
                        u[1:-4:2, i, j] = lu_solve(self.Lo[i][j], b[1:-4:2, i, j])
            else:
                SFTc.Solve_Biharmonic_3D_n(b, u, self.u0, self.u1, self.u2, self.l0, self.l1, self.ak, self.bk, self.a0)
        else:
            if self.solver == "scipy":
                u[:-4:2] = lu_solve(self.Le, b[:-4:2])
                u[1:-4:2] = lu_solve(self.Lo, b[1:-4:2])
            else:
                SFTc.Solve_Biharmonic_1D(b, u, self.u0, self.u1, self.u2, self.l0, self.l1, self.ak, self.bk, self.a0)

        return u
Ejemplo n.º 29
0
    def solve_nonlinear(self, params, unknowns, resids):
        """ Use np to solve Ax=b for x.
        """

        # lu factorization for use with solve_linear
        self.lup = lu_factor(params['K'])

        unknowns['disp_aug'] = lu_solve(self.lup, params['forces'])
        resids['disp_aug'] = params['K'].dot(unknowns['disp_aug']) - params['forces']
Ejemplo n.º 30
0
    def solve(self, rhs_mat, system, mode):
        """ Solves the linear system for the problem in self.system. The
        full solution vector is returned.

        Args
        ----
        rhs_mat : dict of ndarray
            Dictionary containing one ndarry per top level quantity of
            interest. Each array contains the right-hand side for the linear
            solve.

        system : `System`
            Parent `System` object.

        mode : string
            Derivative mode, can be 'fwd' or 'rev'.

        Returns
        -------
        dict of ndarray : Solution vectors
        """

        self.system = system

        if self.mode is None:
            self.mode = mode

        sol_buf = OrderedDict()

        for voi, rhs in rhs_mat.items():
            self.voi = None

            if system._jacobian_changed:
                method = self.options['jacobian_method']

                # Must clear the jacobian if we switch modes
                if method == 'assemble' and self.mode != mode:
                    self.setup(system)
                self.mode = mode

                self.jacobian, _ = system.assemble_jacobian(mode=mode, method=method,
                                                            mult=self.mult)
                system._jacobian_changed = False

                if self.options['solve_method'] == 'LU':
                    self.lup = lu_factor(self.jacobian)

            if self.options['solve_method'] == 'LU':
                deriv = lu_solve(self.lup, rhs)
            else:
                deriv = np.linalg.solve(self.jacobian, rhs)

            self.system = None
            sol_buf[voi] = deriv

        return sol_buf
Ejemplo n.º 31
0
    def inv_free_pred_f(self, r, t):
        """ Avoid inverse computation by solving the linear system with precomputed LU decomp.
            The const is 2n^2 for each function evaluation compared to an initial n^3
            inverse computation and an n^2 cost afterward for each function evaluation.

            This method is to be used when there are frequent updates to the Ybar and Hbar
            matrixes and repeated inverse computation is undesireable.
        """
        u_hat = self.Ybar @ lu_solve(self.W_out_factors, r)
        return self.gamma * (
            -1 * r +
            self.activ_f(self.res @ r + self.sigma * self.W_in @ u_hat))
Ejemplo n.º 32
0
def iteration_solve(G,source,x,x_old_iter,x_old_time,VA,VB,epsilon,node_max,iC,method,h):
    cnt = 0
    x_old_iter[:] = 100
    while (max(abs(x_old_iter-x))>epsilon) and (cnt<100):
        x_old_iter = x
        node = node_max
        G,source = read_netlist(netlist,total_list,node,G,source,x,x_old_time,VA,VB,iC,method,h,0)
        A, s = update_G(G,source,x,method,node_max)
        lu, piv = linalg.lu_factor(A)
        x = linalg.lu_solve((lu,piv),s)     
        cnt += 1
    return x,cnt
Ejemplo n.º 33
0
def inverse_iteration_lu(lu, piv, lambda_, niter, y0=None, random_state=None):
    """von Wielandt inverse iteration method with pre-calculated LU decomposition. Definition 5.14."""
    y0 = random.get_start_vector(d=lu.shape[0],
                                 y0=y0,
                                 random_state=random_state)
    x0 = normalise(y0)
    for _ in range(niter):
        y0 = lu_solve((lu, piv), x0)
        sigma = -1 if np.dot(y0, x0) < 0 else 1
        y0 *= sigma
        x0 = normalise(y0)
    return lambda_ + 1 / la.norm(y0)
Ejemplo n.º 34
0
 def kriging_estimation(self, xs, nfg=-1):
     if nfg >= 0:
         self.nfg = nfg
     xs0 = (xs - self.xmin)/(self.xmax - self.xmin)
     xstheta = np.sqrt(self.theta[self.nfg,:self.nx])*xs0
     r = np.exp(-distance.cdist(xstheta.reshape([1,len(xstheta)]), self.xtheta[:,:,self.nfg])**2.0).reshape(self.ns)
     f = self.mu[self.nfg] + np.dot(r, self.Rifm[:,self.nfg])
     Rir = linalg.lu_solve(self.Ri[self.nfg], r)
     ones = np.ones(len(self.Rifm[:,0]))
     s = self.sigma[self.nfg]*(1.0 - np.dot(r,Rir) + ((1.0-np.dot(ones,Rir))**2.0)/np.dot(ones,self.Ri1[:,self.nfg]))
     s = np.sqrt(np.max([s, 0.0]))
     return f, s
Ejemplo n.º 35
0
def smallest_eval(A, n_max=500):
    LUP = lu_factor(A)
    n = 0
    z = np.random.rand((A.shape[0]))
    z /= np.linalg.norm(z)

    while n < n_max:
        w = lu_solve(LUP, z)
        z = w / np.linalg.norm(w)
        n += 1

    return z, np.dot(np.conj(z), np.matmul(A, z))
def iteration_solve_init(G, source, x, x_old, epsilon, node_max, iC, method):
    cnt = 0
    while (max((abs(x_old - x))) > epsilon and (cnt < 100)):
        x_old = x
        node = node_max
        G, source = read_netlist_init(netlist, total_list, node, G, source, x,
                                      iC, method)
        A, s = update_G(G, source, x, method, node_max)
        lu, piv = linalg.lu_factor(A)
        x = linalg.lu_solve((lu, piv), s)
        cnt += 1
    return x, cnt
Ejemplo n.º 37
0
    def phi_newtonstep(self, t0, y0, initVal, luFactor):
        """
        Еще одна магия

        :param t0:
        :param y0:
        :param initVal:
        :param luFactor:
        :return:
        """
        d = linalg.lu_solve(luFactor, -self.F(initVal.flatten(), t0, y0))
        return initVal.flatten() + d, norm(d)
Ejemplo n.º 38
0
    def get_chord_deltax(self, sV, iVec=None):
        """
        Get deltax for sV, iVec using existing factored Jacobian

        Requires matrix previously decomposed with factor_and_solve()

        Useful for the first iteration of transient analysis. If iVec
        not given the stored value is used.
        """
        if iVec == None:
            iVec = self.iVec
        return linalg.lu_solve(self._LUpiv, sV - iVec)
Ejemplo n.º 39
0
    def solve_linear(self, d_outputs, d_residuals, mode):
        r"""
        Back-substitution to solve the derivatives of the linear system.

        If mode is:
            'fwd': d_residuals \|-> d_outputs

            'rev': d_outputs \|-> d_residuals

        Parameters
        ----------
        d_outputs : Vector
            unscaled, dimensional quantities read via d_outputs[key]
        d_residuals : Vector
            unscaled, dimensional quantities read via d_residuals[key]
        mode : str
            either 'fwd' or 'rev'
        """
        vec_size = self.options['vec_size']
        vec_size_A = self.vec_size_A

        if mode == 'fwd':
            if vec_size > 1:
                for j in range(vec_size):
                    idx = j if vec_size_A > 1 else 0
                    d_outputs['disp_aug'][j] = linalg.lu_solve(
                        self._lup[idx], d_residuals['disp_aug'][j], trans=0)
            else:
                d_outputs['disp_aug'] = linalg.lu_solve(
                    self._lup, d_residuals['disp_aug'], trans=0)

        else:  # rev
            if vec_size > 1:
                for j in range(vec_size):
                    idx = j if vec_size_A > 1 else 0
                    d_residuals['disp_aug'][j] = linalg.lu_solve(
                        self._lup[idx], d_outputs['disp_aug'][j], trans=1)
            else:
                d_residuals['disp_aug'] = linalg.lu_solve(
                    self._lup, d_outputs['disp_aug'], trans=1)
    def solve(self, q, transposed=False):
        """
        Solve B @ v = q efficiently using factorization
        """
        if not self.ops_list:
            # before any updates, solve according to Equation 5.2
            v = lu_solve(self.plu, q, trans=transposed)
        else:
            if not transposed:
                q = q[self.pi]  # paper skips this by making
                # "inessential assumption" of no permutation

                # Equation 5.16
                t = solve_triangular(self.L,
                                     q,
                                     lower=True,
                                     check_finite=False,
                                     unit_diagonal=True)

                # Equation 5.17
                temp = t
                for ops in self.ops_list:
                    perform_ops(self, temp, ops)  # modifies temp in place
                w = temp

                # Equation 5.18
                # Faster to use U.T and set trans=True due to array order
                v = solve_triangular(self.U.T,
                                     w,
                                     lower=True,
                                     trans=True,
                                     check_finite=False)

            else:  # do everything transposed and in reverse order
                t = solve_triangular(self.U.T,
                                     q,
                                     lower=True,
                                     trans=False,
                                     check_finite=False)
                temp = t
                for ops in reversed(self.ops_list):
                    perform_ops(self, temp, ops, rev=True)  # mod in place
                w = temp
                v = solve_triangular(self.L,
                                     w,
                                     lower=True,
                                     trans=True,
                                     check_finite=False,
                                     unit_diagonal=True)
                v = v[self.pit]

        return v
Ejemplo n.º 41
0
    def __init__(self, *args, **kwargs):
        # `args` can be a variable number of arrays; we flatten them and store
        # them as a single 2-D array `xi` of shape (n_args-1, array_size),
        # plus a 1-D array `di` for the values.
        # All arrays must have the same number of elements
        self.xi = np.asarray(
            [np.asarray(a, dtype=np.float_).flatten() for a in args[:-1]])
        self.N = self.xi.shape[-1]

        self.mode = kwargs.pop('mode', '1-D')

        if self.mode == '1-D':
            self.di = np.asarray(args[-1]).flatten()
            self._target_dim = 1
        elif self.mode == 'N-D':
            self.di = np.asarray(args[-1])
            self._target_dim = self.di.shape[-1]
        else:
            raise ValueError("Mode has to be 1-D or N-D.")

        if not all([x.size == self.di.shape[0] for x in self.xi]):
            raise ValueError("All arrays must be equal length.")

        self.norm = kwargs.pop('norm', 'euclidean')
        self.epsilon = kwargs.pop('epsilon', None)
        if self.epsilon is None:
            # default epsilon is the "the average distance between nodes" based
            # on a bounding hypercube
            ximax = np.amax(self.xi, axis=1)
            ximin = np.amin(self.xi, axis=1)
            edges = ximax - ximin
            edges = edges[np.nonzero(edges)]
            self.epsilon = np.power(np.prod(edges) / self.N, 1.0 / edges.size)

        self.smooth = kwargs.pop('smooth', 0.0)
        self.function = kwargs.pop('function', 'multiquadric')

        # attach anything left in kwargs to self for use by any user-callable
        # function or to save on the object returned.
        for item, value in kwargs.items():
            setattr(self, item, value)

        # Compute weights
        if self._target_dim > 1:  # If we have more than one target dimension,
            # we first factorize the matrix
            self.nodes = np.zeros((self.N, self._target_dim),
                                  dtype=self.di.dtype)
            lu, piv = linalg.lu_factor(self.A)
            for i in range(self._target_dim):
                self.nodes[:, i] = linalg.lu_solve((lu, piv), self.di[:, i])
        else:
            self.nodes = linalg.solve(self.A, self.di)
Ejemplo n.º 42
0
    def residuals(self):
        """Calculate the residual terms of a pair of sites."""

        if np.size(self.iceicehorizons_depth1) > 0:
            resi_iceice = (self.site1.fct_age(self.iceicehorizons_depth1)-\
                           self.site2.fct_age(self.iceicehorizons_depth2))/self.iceicehorizons_sigma
            if self.iceicehorizons_correlation_bool:
                resi_iceice = lu_solve(self.iceicehorizons_lu_piv, resi_iceice)
            resi = [resi_iceice]
        else:
            resi = [np.array([])]

        if self.site1.archive == 'icecore' and self.site2.archive == 'icecore' and \
            np.size(self.airairhorizons_depth1) > 0:
            resi_airair = (self.site1.fct_airage(self.airairhorizons_depth1)-\
                          self.site2.fct_airage(self.airairhorizons_depth2))/\
                          self.airairhorizons_sigma
            if self.airairhorizons_correlation_bool:
                resi_airair = lu_solve(self.airairhorizons_lu_piv, resi_airair)
            resi.append(resi_airair)

        if self.site2.archive == 'icecore' and np.size(
                self.iceairhorizons_depth1) > 0:
            resi_iceair = (self.site1.fct_age(self.iceairhorizons_depth1)-\
                          self.site2.fct_airage(self.iceairhorizons_depth2))/\
                          self.iceairhorizons_sigma
            if self.iceairhorizons_correlation_bool:
                resi_iceair = lu_solve(self.iceairhorizons_lu_piv, resi_iceair)
            resi.append(resi_iceair)

        if self.site1.archive == 'icecore' and np.size(
                self.airicehorizons_depth1) > 0:
            resi_airice = (self.site1.fct_airage(self.airicehorizons_depth1)-\
                           self.site2.fct_age(self.airicehorizons_depth2))/self.airicehorizons_sigma
            if self.airicehorizons_correlation_bool:
                resi_airice = lu_solve(self.airicehorizons_lu_piv, resi_airice)
            resi.append(resi_airice)

        return np.concatenate(resi)
Ejemplo n.º 43
0
def fastbroyd(x0, F, J, tol=1e-12, maxit=20):
    
    x = x0.copy()
    DF = J(x)
    lup = lu_factor(DF) #LU decomposition of J
    k = 0; s = lu_solve(lup,F(x)) #linear system can be solved faster with LU deco
    x -= s; f = F(x); sn = dot(s,s) #step, sn is the squared norm of the correction
    
    #containers for storing s and sn:
    dx = zeros((maxit,len(x)))
    dxn = zeros(maxit)
    dx[k] = s; dxn[k] = sn
    k += 1; #k is the number of the iteration
    
    w = lu_solve(lup,f) #f = F(starting value) (see above)
    
    #now we perform the iteration
    
    f = F(x)
    
    while sn > tol and k < maxit:
        
        w = lu_solve(lup,f) #f = F(starting value) (see above)
        #now we update the correction for the k-th step
        #using the sherman morrison woodbury formel
        
        for r in range(1,k):
            w += dx[r]*( dot(dx[r-1],w) )/dxn[r-1]
            
        z = dot(s,w)
        s = (1+z/(sn-z))*w
        sn = dot(s,s)
        dx[k] = s
        dxn[k] = sn
        x -= s
        f = F(x)
        k+=1 #update x and iteration number k
    
    return x, k
Ejemplo n.º 44
0
def correlated_gaussian_loglikelihood(xs, means, cov):
    """Returns the likelihood for data xs, assumed to be multivariate
    Gaussian with the given means and covariance."""
    lu, piv = sl.lu_factor(cov)

    lambdas = np.diag(lu)

    ndim = xs.shape[0]

    ds = (xs - means) * sl.lu_solve((lu, piv), xs - means) / 2.0

    return -np.log(2.0 * np.pi) * (ndim / 2.0) - 0.5 * np.sum(
        np.log(lambdas)) - np.sum(ds)
Ejemplo n.º 45
0
def invert_lu(A):
    """
  Invert a given matrix A through LU decomposition
  Assumption: matrix A is square, symmetric 
  """
    id = np.zeros(shape=(A.shape[0], A.shape[1]))
    for i in range(A.shape[0]):
        id[i, i] = 1.0
    Ainv = np.empty(shape=(A.shape[0], A.shape[1]))
    lu = linalg.lu_factor(A)
    for i in range(A.shape[0]):
        Ainv[:, i] = linalg.lu_solve(lu, id[:, i])
    return Ainv
Ejemplo n.º 46
0
 def calculate_next_step(self, counter):
     for k in range(self.__n_x * self.__n_y):
         j = math.floor(k / self.__n_x)
         i = k - j * self.__n_x
         if i == 0 or i == self.__n_x - 1 or j == 0 or j == self.__n_y - 1:
             self.__b[k] = 0
         else:
             self.__b[k] = self.__parameter_f * self.__u_actual[k] - self.__parameter_g * self.__u_previous[k] + self.__parameter_h * (self.__u_previous[k + 1] + self.__u_previous[k - 1]) + self.__parameter_j * (self.__u_previous[k + self.__n_x] + self.__u_previous[k - self.__n_x]) + self.__parameter_k * (self.__u_actual[k + 1] + self.__u_actual[k - 1]) + self.__parameter_l * (self.__u_actual[k + self.__n_x] + self.__u_actual[k - self.__n_x])
             if self.__forcing_term_check:
                 self.__b[k] += self.__calculate_m(counter, k, self.__n_x, self.__delta_x, self.__delta_y, self.__delta_t, self.__parameter_a, self.__parameter_b, self.__beta, self.__x_f, self.__y_f, self.__t_f, self.__sigma)
     self.__u_next = lu_solve((self.__lu, self.__piv), self.__b)
     self.__u_previous = self.__u_actual
     self.__u_actual = self.__u_next
Ejemplo n.º 47
0
def LU():
    import scipy.linalg as linalg
    import numpy as np
    import scipy

    nums = input(
        "Escreva os valores da primeira linha separado por espaco:").split()
    num = []
    for i in nums:
        num.append(int(i))

    nums1 = input(
        "Escreva os valores da segunda linha separado por espaco:").split()
    nu = []
    for i in nums1:
        nu.append(int(i))

    nums2 = input(
        "Escreva os valores da terceira linha separado por espaco:").split()
    n = []
    for i in nums2:
        n.append(int(i))

    A = np.array([[num], [nu], [n]])
    A = np.reshape(A, (3, 3))

    y = input("Escreva os valores da coluna separado por espaco:").split()
    z = []
    for i in y:
        z.append(int(i))

    B = np.array([y])
    B = np.reshape(B, (3, 1))

    LU = linalg.lu_factor(A)

    x = linalg.lu_solve(LU, B)
    print("Solutions:\n", x)

    P, L, U = scipy.linalg.lu(A)
    print("A= ", A)
    print("\n")

    print("P= ", P)
    print("\n")

    print("L= ", L)
    print("\n")

    print("U= ", U)
    print("\n")
Ejemplo n.º 48
0
def linear(mesh, BCs, MaterialSets):
    """
    Linear solver.

    """

    # Initializing arrays
    systemDofs = mesh.dofsNode * len(mesh.points)
    K = np.zeros(shape=(systemDofs, systemDofs), dtype=np.float32)
    F = np.zeros(shape=(systemDofs, 1), dtype=np.float32)

    print("Assemblying global stiffness matrix...")

    start_a = time.time()

    for e in range(len(mesh.elements)):

        k = FEM_engine.stiffness_matrix(e, mesh, MaterialSets)

        # Get global dof associate with element e.
        dof = FEM_engine.DofMap(e, mesh)

        # Assemble the e-th local matrix into the global one.
        K = FEM_engine.assemble(K, k, dof)

    end_a = time.time()

    print("Global stiffness matrix assembled in {}s".format(end_a - start_a))

    Kr = K.copy()

    (Kr, F) = BCs.apply(Kr, F, mesh)
    print("Solving F = Ku...")

    start_s = time.time()

    LU = linalg.lu_factor(Kr)
    del Kr
    U = linalg.lu_solve(LU, F)
    del LU

    end_s = time.time()
    print("\nLU solver: {}s".format(end_s - start_s))

    R = np.matmul(K, U)

    end_s = time.time()

    print("Linear system solved in {}s".format(end_s - start_s))

    return U, R, K
Ejemplo n.º 49
0
    def __call__(self, A, shift=0):
        from scipy.linalg import lu_factor, lu_solve
        nrows = A.mshape[0]
        nblock = A.blockshape[0]  #assume a square block!

        assert A.bandwidth == 3, "Matrix bust be tridiagonal block matrix"

        #Overwrite current matrix?
        if self.overwrite:
            self.Alu = A

        #Create new internal matrix if none
        elif not hasattr(self, 'Alu'):
            logging.debug("Creating new internal LU matrix")
            self.Alu = BlockArray(A.mshape, A.blockshape, dtype=A.dtype)

        #Create new internal matrix if A is different shape
        elif (self.Alu.mshape != A.mshape) or (self.Alu.blockshape !=
                                               A.blockshape):
            logging.debug(
                "Internal LU matrix incorrect shape; creating new one")
            del self.Alu
            self.Alu = BlockArray(A.mshape, A.blockshape, dtype=A.dtype)

        #Vector for pivots
        self.shift = shift
        self.pivots = zeros((nrows, nblock), dtype=A.dtype)
        piv = 0

        Ishift = shift * eye(nblock)
        self.Alu.set_raw_block(0, 1, A.get_raw_block(0, 1) - Ishift)
        bnew = self.Alu.get_raw_block(0, 1)
        for row in range(0, nrows - 1):
            a = A.get_raw_block(row + 1, 0)
            b = bnew
            c = A.get_raw_block(row, 2)

            b, self.pivots[row] = lu_factor(b)
            # anew = a inv(b)
            anew = lu_solve((b, self.pivots[row]), a.T, trans=1).T
            bnew = A.get_raw_block(row + 1, 1) - Ishift - dot(anew, c)

            self.Alu.set_raw_block(row, 1, b)  #blu
            self.Alu.set_raw_block(row + 1, 0, anew)  #b anew = a

            if not self.overwrite:  #Copy over block c, if not overwriting
                self.Alu.set_raw_block(row, 2, c)

        #Final LU decomp of last block
        b, self.pivots[nrows - 1] = lu_factor(bnew)
        self.Alu.set_raw_block(nrows - 1, 1, b)
Ejemplo n.º 50
0
def main() -> None:
    N: int = 10
    h: float = 1 / N
    alpha: float = 0
    beta: float = 0
    p = np.full(N, 1, dtype='float64')
    q = np.full(N, 0, dtype='float64')
    r = np.full(N, -1, dtype='float64')

    df_eq = np.zeros((N, N), dtype='float64')
    for i in range(len(df_eq)):
        for j in range(len(df_eq)):
            if i == j:
                df_eq[i][j] = h**2 * q[i] - 2
            elif i + 1 == j:
                df_eq[i][j] = 1 + (h * p[i]) / 2
            elif i - 1 == j:
                df_eq[i][j] = 1 - (h * p[i]) / 2
    df_eq[-1][-1] = 1
    df_eq[-1][-2] = -1

    ans_vector = np.zeros(N, dtype='float64')
    for i in range(len(ans_vector)):
        if i == 0:
            ans_vector[i] = h**2 * r[i] - alpha * (1 - (h * p[i]) / 2)
        elif i == len(ans_vector) - 1:
            ans_vector[i] = h * beta
        else:
            ans_vector[i] = h**2 * r[i]
    print(df_eq)
    print(ans_vector)

    lu_facotr = linalg.lu_factor(df_eq)
    y = linalg.lu_solve(lu_facotr, ans_vector)
    y = np.insert(y, 0, alpha)

    x = np.linspace(0, 1, N + 1)
    xx = np.linspace(0, 1)
    # plt.plot(xx, analysis(xx), color='r')
    plt.plot(x, y, color='b')
    title: str = 'TPBVP N = %d' % N
    plt.title(title)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.show()

    error1: float = np.amax(abs(y - analysis(x)))
    error2: float = abs(y[-1] - analysis(1))
    print('error1 = %.3e' % error1)
    print('error2 = %.3e' % error2)
    print('Y_N ~ %.8e' % y[-1])
Ejemplo n.º 51
0
def time_LU():
    """Print the times it takes to solve a system of equations using
    LU decomposition and (A^-1)B where A is 1000x1000 and B is 1000x500."""

    A = np.random.rand(1000, 1000)
    B = np.random.rand(1000, 500)
    start_time = time.time()
    C = la.lu_factor(A)
    end_time = time.time()

    start_time2 = time.time()
    D = la.inv(A)
    end_time2 = time.time()

    start_time3 = time.time()
    la.lu_solve(C, B)
    end_time3 = time.time()

    start_time4 = time.time()
    np.dot(D, B)
    end_time4 = time.time()

    time_lu_factor = (
        end_time - start_time
    )  # set this to the time it takes to perform la.lu_factor(A)
    time_inv = (end_time2 - start_time2
                )  # set this to the time it takes to take the inverse of A
    time_lu_solve = (
        end_time3 - start_time3
    )  # set this to the time it takes to perform la.lu_solve()
    time_inv_solve = (end_time4 - start_time4
                      )  # set this to the time it take to perform (A^-1)B

    print "LU solve: " + str(time_lu_factor + time_lu_solve)
    print "Inv solve: " + str(time_inv + time_inv_solve)

    # What can you conclude about the more efficient way to solve linear systems?
    print "LU solve was faster than Inv Solve so that is the more efficient way to solve linear systems"  # print your answer here."""
Ejemplo n.º 52
0
    def solve_nonlinear(self, inputs, outputs):
        """
        Use numpy to solve Ax=b for x.

        Parameters
        ----------
        inputs : Vector
            unscaled, dimensional input variables read via inputs[key]
        outputs : Vector
            unscaled, dimensional output variables read via outputs[key]
        """
        # lu factorization for use with solve_linear
        self._lup = linalg.lu_factor(inputs['AIC'])
        outputs['circulations'] = linalg.lu_solve(self._lup, inputs['rhs'])
Ejemplo n.º 53
0
    def _solve(self):
        """Solve the system of equations for unknown displacements and loads after sorting."""
        # extract sub matrices for readability
        f_f = self._f_f
        K_F = self._K_F
        K_EF = self._K_EF
        u_e = self._u_e

        # solve for the unknown displacements using LU decompsition
        u_f = lu_solve(lu_factor(K_F), f_f - transpose(K_EF).dot(u_e))
        self._u[self._ndef_u:] = u_f

        # calculate unknown loads
        self._calc_f()
Ejemplo n.º 54
0
def LUdecomp(b,n): #LU-Decomposition algorithm
    A = zeros((n,n)) #Make A nxn-matrix
    A[0,0] = 2; A[0,1] = -1; #Set first row of A
    for i in range(1,n-1): #Set middle of A
        A[i,i-1] = -1 #Lower diagonal
        A[i,i] = 2 #Main diagonal
        A[i,i+1] = -1 #Upper diagonal
    A[n-1,n-1] = 2; A[n-1,n-2] = -1 #Set last row of A
    start_time = float(time.perf_counter())
    lu, piv = lu_factor(A) #LU-foctorize A
    v = lu_solve((lu,piv),b[1:-1]) #Solve matrix equation
    elapsed_time = time.perf_counter() - start_time
    print("(n = "+str(n)+")[LU-Decomp], CPU Time: "+str(elapsed_time))
    return v
Ejemplo n.º 55
0
def rayleigh_iteration(A, lambda_, niter, y0=None, random_state=None):
    """Rayleigh inverse iteration method. Algorithm 11."""
    y0 = random.get_start_vector(d=A.shape[0],
                                 y0=y0,
                                 random_state=random_state)
    x0 = normalise(y0)
    for _ in range(niter):
        lu, piv = lu_factor(A - lambda_ * np.eye(A.shape[0]))
        y0 = lu_solve((lu, piv), x0)
        sigma = -1 if np.dot(y0, x0) < 0 else 1
        y0 *= sigma
        x0 = normalise(y0)
        lambda_ = x0.T @ A @ x0
    return lambda_ + 1 / la.norm(y0)
Ejemplo n.º 56
0
    def get_Ginv(self, energy):
        # """The inverse of the retarded surface Green function"""
        z = energy - self.bias + self.eta * 1.j

        v_00 = z * self.s_ii.T.conj() - self.h_ii.T.conj()
        v_11 = v_00.copy()
        v_10 = z * self.s_ij - self.h_ij
        v_01 = z * self.s_ij.T.conj() - self.h_ij.T.conj()

        delta = self.conv + 1
        while delta > self.conv:
            lu, piv = la.lu_factor(v_11)
            a = la.lu_solve((lu, piv), v_01)
            b = la.lu_solve((lu, piv), v_10)
            v_01_dot_b = np.dot(v_01, b)
            v_00 -= v_01_dot_b
            v_11 -= np.dot(v_10, a)
            v_11 -= v_01_dot_b
            v_01 = -np.dot(v_01, a)
            v_10 = -np.dot(v_10, b)
            delta = abs(v_01).max()

        return v_00
Ejemplo n.º 57
0
def test2():
    print("\ntest2")
    """
    (3 1 1)(x) (1)
    (1 2 1)(y)=(2)
    (0-1 1)(z) (3) solve x,y,z
    """
    a = np.array([[3, 1, 1], [1, 2, 1], [0, -1, 1]])
    b = np.array([1, 2, 3])
    print("\na=", a)
    print("b=", b)
    lu, p = linalg.lu_factor(a)
    print("lu, p = linalg.lu_factor(a)")
    print("x,y,z=linalg.lu_solve((lu, p), b)", linalg.lu_solve((lu, p), b))
Ejemplo n.º 58
0
 def _fit(self, a, b):
     m = (a+b)/2.0
     if self.verbose:
         print('[', a, ',', b, ']')
     _, x = get_chebyshev_nodes(a, b, self.n)
     coefs = lu_solve(self.VLU, self.f(x))
     tail_energy = np.abs(coefs[-2:]).max()/max(1, np.abs(coefs[0]))
     if tail_energy < self.tol or b-a < self.mw:
         self.lbs.append(a)
         self.ubs.append(b)
         self.coefs.append(coefs)
     else:
         self._fit(a, m)
         self._fit(m, b)
Ejemplo n.º 59
0
def inverse_power_iteration(A, u, max_iters, epsilon):
    v0 = np.identity(A.shape[0])[0]
    AuI = A - u * np.identity(A.shape[0])
    lupiv = linalg.lu_factor(AuI)
    for i in range(max_iters):
        v = v0
        w = linalg.lu_solve(lupiv, v)
        v = w / np.linalg.norm(w)
        if np.linalg.norm(v - v0) < epsilon or np.linalg.norm(v +
                                                              v0) < epsilon:
            print("Iterations: " + str(i))
            return u, v
        u = v.T @ A @ v
        v0 = v
Ejemplo n.º 60
0
 def update(self, n, dx, dq):
     if self.iteration == 0:
         self.etas = np.zeros((self._max_iterations, self.coeff.shape[0]),
                              dtype=np.double,
                              order='C')
     row1, row2 = get_rows(n - 1, n, self.row_order, self.iteration)
     vec = get_new_col(self.coeff, self.var_nums, self.var_names, n, row1,
                       row2, dx, dq)
     self.coeff[:, n] = vec
     vec1 = lu_solve(self.lu, vec, check_finite=False)
     ftran2eta(vec1, self.etas, self.pivot_idxs, self.iteration, n)
     ftran(self.solution[:, 1], self.etas[self.iteration, :], n)
     self.iteration += 1
     return self.solution[:, 1].copy()