def UpdateAlpha(self): BB = SeparatedArray(self.__B + self.__D - self.__A * self.__Xbc) alpha = sp.c_[linalg.solve(self.calcMat_Alpha(self.__X), self.SecTerm_Alpha(self.__X, BB))] # alpha = self.solve_Alpha(self.__X,SeparatedArray(self.__B - self.__A*self.__Xbc)) self.__X.data[0] = sp.tile( alpha.T, (self.__ProblemDimension[0], 1)) * self.__X.data[0]
def linsolve(M, b): A = aslinearoperator(M) v, info = solve(A, b, x0=b, tol=1e-6) if info == 0: return v elif info < 0: raise Exception('Breakdown or bad input with code %d' % info) else: raise Exception('Non-convergence after %d iterations' % info)
def fit(self, xyzk, uvk=None): if (not self.postAssembly) and (uvk is None): print("You must run updateMatrix before!") return if (not self.postAssembly) and (uvk is not None): self.Dt, self.Mat = self.updateMatrix(uvk) self.postAssembly = True self.updateGlobalSystem() from scipy.sparse.linalg import cg as solve N_ini = self.system.shape[0] N_final = N_ini + self.nConstraints # print "N_ini ", N_ini # print "N_final ", N_final # print "nconstraints ", self.nConstraints cxyz = [] # xk is a list of arrays. one array per patch for i, xk in enumerate(xyzk): # print "==== i "+str(i)+" ===" x = np.zeros(N_final) # we must transform xk into one single array _xk = np.concatenate(xk) # print "xk ", len(_xk) # print "Dt ", self.Dt.shape x[:N_ini] = self.Dt * _xk # ... update with rhs for some Constraints x += np.asarray(self.RHS[i]) # ... # np.savetxt("x"+str(id(xk))+".txt", x) Cx = solve(self.Mat, x)[0] cx = Cx[:N_ini] # np.savetxt("xk"+str(i)+".txt", _xk) # np.savetxt("x"+str(i)+".txt", x) # np.savetxt("xa"+str(i)+".txt", x[:81]) # np.savetxt("xb"+str(i)+".txt", x[81:]) # np.savetxt("cx"+str(i)+".txt", cx) # print ">> x " # print x # print "---" # print "---" # print cx # print "---" cxyz.append(cx) # from scipy.linalg import det # print "det = ", det(self.Mat.todense()) # print "---" # print ">> xk " # print xk # print "---" # print ">> self.Dt " # print self.Dt # print "---" # print self.Mat return cxyz
def solve_batch(covariance_r, covariance_i, steering_r, steering_i): covariance = covariance_r + 1j * covariance_i steering = steering_r + 1j * steering_i global N_BLOCKS global N_DOP global N_CHAN global TDOF adaptive_weights = zeros((N_BLOCKS*N_DOP*N_STEERING, N_CHAN*TDOF), dtype=complex64) for block in range(N_BLOCKS): for dop in range(N_DOP): problem_id = dop + block*N_DOP mat = covariance[(N_CHAN*TDOF)*problem_id:(N_CHAN*TDOF)*(problem_id+1),:] aw = linalg.solve(mat, steering.T) adaptive_weights[(N_STEERING)*problem_id:(N_STEERING)*(problem_id+1),:] = aw.T return real(adaptive_weights), imag(adaptive_weights)
def dF_with_distance(G, src_a=None, src_b=None): allnodes = G.nodes() shortest_pathlengths = nx.single_source_shortest_path_length(G, src_a) shortest_pathlengths_ordered = [ shortest_pathlengths[node] for node in allnodes ] source_vector = csr_matrix((G.number_of_nodes(), 1)) src_a_ind = allnodes.index(src_a) source_vector[src_a_ind] = 1 if src_b: src_b_ind = allnodes.index(src_b) if src_b else None source_vector[src_b_ind] = -1 return shortest_pathlengths_ordered, solve(G.loopy_laplacian(), source_vector)
def solver_BE_simple(I, a, L, Nx, Fo, T): """ Simplest expression of the computational algorithm for the Backward Euler method, using explicit Python loops and a dense matrix format for the coefficient matrix. """ import time t0 = time.clock() x = linspace(0, L, Nx + 1) # mesh points in space dx = x[1] - x[0] dt = Fo * dx**2 / a Nt = int(round(T / float(dt))) t = linspace(0, T, Nt + 1) # mesh points in time u = zeros(Nx + 1) u_1 = zeros(Nx + 1) # Data structures for the linear system A = zeros((Nx + 1, Nx + 1)) b = zeros(Nx + 1) for i in range(1, Nx): A[i, i - 1] = -Fo A[i, i + 1] = -Fo A[i, i] = 1 + 2 * Fo A[0, 0] = A[Nx, Nx] = 1 # Set initial condition u(x,0) = I(x) for i in range(0, Nx + 1): u_1[i] = I(x[i]) for n in range(0, Nt): # Compute b and solve linear system for i in range(1, Nx): b[i] = -u_1[i] b[0] = b[Nx] = 0 u[:] = linalg.solve(A, b) # Update u_1 before next step #u_1[:]= u u_1, u = u, u_1 t1 = time.clock() return u, x, t, t1 - t0
def solver_BE_simple(I, a, L, Nx, F, T): """ Simplest expression of the computational algorithm for the Backward Euler method, using explicit Python loops and a dense matrix format for the coefficient matrix. """ import time t0 = time.clock() x = linspace(0, L, Nx+1) # mesh points in space dx = x[1] - x[0] dt = F*dx**2/a Nt = int(round(T/float(dt))) t = linspace(0, T, Nt+1) # mesh points in time u = zeros(Nx+1) u_1 = zeros(Nx+1) # Data structures for the linear system A = zeros((Nx+1, Nx+1)) b = zeros(Nx+1) for i in range(1, Nx): A[i,i-1] = -F A[i,i+1] = -F A[i,i] = 1 + 2*F A[0,0] = A[Nx,Nx] = 1 # Set initial condition u(x,0) = I(x) for i in range(0, Nx+1): u_1[i] = I(x[i]) for n in range(0, Nt): # Compute b and solve linear system for i in range(1, Nx): b[i] = -u_1[i] b[0] = b[Nx] = 0 u[:] = linalg.solve(A, b) # Update u_1 before next step #u_1[:]= u u_1, u = u, u_1 t1 = time.clock() return u, x, t, t1-t0
def fit(self, xyzk, uk=None): if (not self.postAssembly) and (uk is None): print("You must run updateMatrix before!") return if (not self.postAssembly) and (uk is not None): self.Dt, self.Mat = self.updateMatrix(uk) self.updateGlobalSystem() self.postAssembly = True from scipy.sparse.linalg import cg as solve N_ini = self.system.shape[0] N_final = N_ini + self.nConstraints cxyz = [] for i, xk in enumerate(xyzk): x = np.zeros(N_final) x[:N_ini] = self.Dt * xk # ... update with rhs for some Constraints x += np.asarray(self.RHS[i]) # ... # np.savetxt("x"+str(id(xk))+".txt", x) Cx = solve(self.Mat, x)[0] cx = Cx[:N_ini] cxyz.append(cx) # from scipy.linalg import det # print "det = ", det(self.Mat.todense()) # print "---" # print ">> xk " # print xk # print "---" # print ">> self.Dt " # print self.Dt # print "---" # print ">> x " # print x # print "---" # print self.Mat # print "---" # print Cx # print "---" return cxyz
mesh.printBoundaries() n = 10 m = np.zeros((n + 1, n + 1)) b = np.zeros((n + 1)) g = lambda x: x * np.sin(x) # def f(x): # return x * np.sin(x) for i in range(n): ele = mesh.elements[i, :] x = mesh.nodes[ele, :] h = x[1] - x[0] hm = np.array([[h / 3, h / 6], [h / 6, h / 3]]) for j in range(2): for v in range(2): m[ele[j], ele[v]] += hm[j, v] hb = np.array([[g(x[0]) * h / 2], [g(x[1]) * h / 2]]) for u in range(2): b[ele[u]] += hb[u] # print(m) # print(b) Pf = linalg.solve(m, b) print(Pf) plt.plot(mesh.nodes, Pf, 'r-o') # plt.plot(x, y) plt.show()
';' + 'C,' * 26 + 'B,A,B' + ',C' * 19 + ';' + 'C,' * 27 + 'B,A,B' + ',C' * 18 + ';' + 'C,' * 28 + 'B,A,B' + ',C' * 17 + ';' + 'C,' * 29 + 'B,A,B' + ',C' * 16 + ';' + 'C,' * 30 + 'B,A,B' + ',C' * 15 + ';' + 'C,' * 31 + 'B,A,B' + ',C' * 14 + ';' + 'C,' * 32 + 'B,A,B' + ',C' * 13 + ';' + 'C,' * 33 + 'B,A,B' + ',C' * 12 + ';' + 'C,' * 34 + 'B,A,B' + ',C' * 11 + ';' + 'C,' * 35 + 'B,A,B' + ',C' * 10 + ';' + 'C,' * 36 + 'B,A,B' + ',C' * 9 + ';' + 'C,' * 37 + 'B,A,B' + ',C' * 8 + ';' + 'C,' * 38 + 'B,A,B' + ',C' * 7 + ';' + 'C,' * 39 + 'B,A,B' + ',C' * 6 + ';' + 'C,' * 40 + 'B,A,B' + ',C' * 5 + ';' + 'C,' * 41 + 'B,A,B' + ',C' * 4 + ';' + 'C,' * 42 + 'B,A,B' + ',C' * 3 + ';' + 'C,' * 43 + 'B,A,B' + ',C' * 2 + ';' + 'C,' * 44 + 'B,A,B' + ',C' * 1 + ';' + 'C,' * 45 + 'B,A,B' + ';' + 'C,' * 46 + 'B,A') #------------------------------ #test case for solver: testmat = np.bmat([[A, B, C], [B, A, B], [C, B, A]]) testb = [25, 50, 150, 0, 0, 50, 0, 0, 25] #sols [18.75, 37.5, 56.25, 12.5, 25. ,37.5, 6.25, 12.5,18.75] #------------------------------ #Computing Potentials plt.imshow(phi, cmap='hot') plt.colorbar() plt.show() sol = solve(pmat, rho.flatten())[0] phi = np.reshape(sol, (12, 12)) plt.imshow(phi, cmap='hot') plt.colorbar() plt.show()
def get_v(w,rho): """compute velocities""" ll=lhs(w) rr=rhs(w,rho) return solve(ll,rr)
for ii in range(3): x[ii] = p[0, ele[ii] - 1] y[ii] = p[1, ele[ii] - 1] S = area3(x, y) MK = np.array([[2, 1, 1], [1, 2, 1], [1, 1, 2]]) for j in range(3): for v in range(3): M[ele[j] - 1, ele[v] - 1] += MK[j, v] * S / 12 hK = np.array([[fun(x[0], y[0]) / 3], [fun(x[1], y[1]) / 3], [fun(x[2], y[2]) / 3]]) for u in range(3): b[ele[u] - 1] += hK[u] * S Pf = linalg.solve(M, b) print(Pf) # 生成网格的结点坐标,三角单元和区域边界 # m,n分别为x,y的划分,[a,b]和[c,d]分别为x,y的取值范围 def NODES1(m, n, a, b, c, d): nodes1 = np.zeros(((m + 1) * (n + 1), 2)) # 结点坐标 for i in range(n + 1): for j in range(m + 1): nodes1[i * (m + 1) + j, 0] = j nodes1[i * (m + 1) + j, 1] = i for iii in range((m + 1) * (n + 1)): nodes1[iii, 0] = nodes1[iii, 0] * (b - a) / m + a nodes1[iii, 1] = nodes1[iii, 1] * (d - c) / n + c
mesh.printBoundaries() a = lambda x: 0.1 * (5 - 0.6 * x) f = lambda x: 0.03 * (x - 6)**4 for i in range(n): ele = mesh.elements[i, :] x = mesh.nodes[ele, :] h = x[1] - x[0] x_mid = (x[1] + x[0]) / 2 hm = np.array([[1, -1], [-1, 1]]) for j in range(2): for v in range(2): A[ele[j], ele[v]] += hm[j, v] * a(x_mid) / h A[0, 0] += kappa[0] A[n, n] += kappa[1] hb = np.array([[f(x[0]) * h / 2], [f(x[1]) * h / 2]]) for u in range(2): b[ele[u]] += hb[u] b[0] += kappa[0] * g[0] b[n] += kappa[1] * g[1] u = linalg.solve(A, b) print(u) # plt.figure() plt.plot(mesh.nodes, u, 'r-') # plt.plot(x, y) plt.show()
def FiniteElem3D(degree, dim, my_f): cheb = lf.chebyshev_nodes(degree+1) #Lista nodi chebichev n = degree + 1 # Dim poly space q,w = leggauss(n) # Gauss between -1 and 1 q = (q+1)/2 # to go back to 0,1 w = w/2 lag_bas=[] lag_bas_deriv=[] #lagrangian base per i punti chebichev for i in range(len(cheb)): lag_bas.append(lf.lagrange_basis(cheb,i)) lag_bas_deriv.append(lf.lagrange_basis_derivatives(cheb,i)) Vq = zeros((n, len(q))) Vpq = zeros((n, len(q))) #Le righe di Vq sono le funzioni di base calcolate sui punti di quadratura for i in range(n): Vq[i] = lag_bas[i](q) Vpq[i] = lag_bas_deriv[i](q) # ------------------------------------------------- latticeq_points = array([[[[qx,qy,qz] for qz in q] for qy in q ] for qx in q]) latticeq_points = latticeq_points.reshape(len(q)*len(q)*len(q),dim) lpoint_x = array([latticeq_points[i,0] for i in range(len(latticeq_points))]) lpoint_y = array([latticeq_points[i,1] for i in range(len(latticeq_points))]) lpoint_z = array([latticeq_points[i,2] for i in range(len(latticeq_points))]) # ------------------------------------------------- print "Starting einsum A and M..." Atmp = einsum('jq, iq, q -> ji', Vpq, Vpq, w, optimize=True) Mtmp = einsum('jq, iq, q -> ji', Vq, Vq, w, optimize=True) A = einsum('il, jm, kn -> ijklmn', Atmp, Mtmp, Mtmp, optimize=True) A += einsum('il, jm, kn -> ijklmn', Mtmp, Atmp, Mtmp, optimize=True) A += einsum('il, jm, kn -> ijklmn', Mtmp, Mtmp, Atmp, optimize=True) M = einsum('il, jm, kn -> ijklmn', Mtmp, Mtmp, Mtmp, optimize=True) # ------------------------------------------------- print "Starting einsum rhs..." my_f = array(my_f(lpoint_x,lpoint_y,lpoint_z)).reshape(n,n,n) rhs = einsum('ijk, li, i -> jkl', my_f, Vq, w, optimize=True) rhs = einsum('ijk, li, i -> jkl', rhs, Vq, w, optimize=True) rhs = einsum('ijk, li, i -> jkl', rhs, Vq, w, optimize=True) # ------------------------------------------------- A = A.reshape(n**3,n**3) M = M.reshape(n**3,n**3) rhs = rhs.reshape(n**3) #---------- Direct Method ------------------------- print "Direct Method ..." start = time.time() u_fe_dir = linalg.solve( A + M, rhs) end = time.time() time_dir = end - start t_dir.append(time_dir) # ---------- Iterative Conjugate Gradient without Prec---------- print "Iteractive Method without Preconditioner..." start = time.time() u_fe_iter_noprec = scipy.sparse.linalg.cg( A + M, rhs, M = identity(len(A)), tol = 1e-10) end = time.time() time_iter_noprec = end - start t_iter_noprec.append(time_iter_noprec) u_fe_iter_noprec = array(u_fe_iter_noprec[0]) # ---------- Iterative Conjugate Gradient with Prec ---------- print "Iteractive Method with Preconditioner..." start = time.time() invP = diag(1./diag(A + M)) u_fe_iter_prec = scipy.sparse.linalg.cg( A + M, rhs, M = invP, tol = 1e-10) end = time.time() time_iter_prec = end - start t_iter_prec.append(time_iter_prec) u_fe_iter_prec = array(u_fe_iter_prec[0]) # ------------------------------------------------- Vcheb = zeros((n, len(cheb))) for j in range(degree + 1): Vcheb[j] = lag_bas[j](cheb) C = einsum('is, jk, nm -> skmijn', Vcheb, Vcheb, Vcheb, optimize=True) sol_dir = einsum('skmijn, ijn', C, u_fe_dir.reshape((n, n, n)), optimize=True) sol_iter_prec = einsum('skmijn, ijn', C, u_fe_iter_prec.reshape((n, n, n)), optimize=True) sol_iter_noprec = einsum('skmijn, ijn', C, u_fe_iter_noprec.reshape((n, n, n)), optimize=True) return sol_dir.reshape(n,n,n), sol_iter_prec.reshape(n,n,n), sol_iter_noprec.reshape(n,n,n)
ix = 0 # index, counter for N in nrange: m = m1 * ones([N]) kvec = [0, 0, k] rfile = '../shape/sphere_' + str(nrange[ix]) + '.txt' # S = load(rfile) S = array(load_dipole_file(rfile)) r = d * asarray([S[:, 0], S[:, 1], S[:, 2]], dtype=numpy.complex128).T Ei = E_inc(E0, kvec, r) alph = polarizability_LDR(d, m, kvec, E0) A = interaction_A(k, r, alph) if iterative == 0: P, dummy = linalg.solve(A, Ei) elif iterative == 1: P, dummy = scipy.sparse.linalg.gmres(A, Ei) elif iterative == 2: P, dummy = scipy.sparse.linalg.minres(A, Ei) elif iterative == 3: P, dummy = scipy.sparse.linalg.qmr(A, Ei) Cext[ix] = C_ext(k, E0, Ei, P) Cabs[ix] = C_abs(k, E0, Ei, P, alph) Cscat[ix] = Cext[ix] - Cabs[ix] ix += 1 print(time.time() - tic) # the interaction matrix may take up a lot of memory so it can be cleared