def PicardToleranceDecouple(x,U,FSpaces,dim,NormType,iter): X = IO.vecToArray(x) uu = X[0:dim[0]] pp = X[dim[0]:dim[0]+dim[1]-1] bb = X[dim[0]+dim[1]-1:dim[0]+dim[1]+dim[2]-1] rr = X[dim[0]+dim[1]+dim[2]-1:] u = Function(FSpaces[0]) u.vector()[:] = uu diffu = u.vector().array() p = Function(FSpaces[1]) n = pp.shape p.vector()[:] = np.insert(pp,n,0) # ones = Function(FSpaces[1]) # ones.vector()[:]=(0*ones.vector().array()+1) # pp = Function(FSpaces[1]) # p.vector()[:] = p.vector().array()- assemble(p*dx)/assemble(ones*dx) b = Function(FSpaces[2]) b.vector()[:] = bb diffb = b.vector().array() r = Function(FSpaces[3]) print r.vector().array().shape print rr.shape r.vector()[:] = rr if (NormType == '2'): epsu = splin.norm(diffu)/sqrt(dim[0]) epsp = splin.norm(p.vector().array())/sqrt(dim[1]) epsb = splin.norm(diffb)/sqrt(dim[2]) epsr = splin.norm(r.vector().array())/sqrt(dim[3]) elif (NormType == 'inf'): epsu = splin.norm(diffu, ord=np.Inf) epsp = splin.norm(p.vector().array(),ord=np.inf) epsb = splin.norm(diffb, ord=np.Inf) epsr = splin.norm(r.vector().array(),ord=np.inf) else: print "NormType must be 2 or inf" quit() RHS = IO.vecToArray(U) u.vector()[:] = uu + RHS[0:dim[0]] p.vector()[:] = p.vector().array() + U.array[dim[0]:dim[0]+dim[1]] b.vector()[:] = bb + RHS[dim[0]+dim[1]:dim[0]+dim[1]+dim[2]] r.vector()[:] = rr + RHS[dim[0]+dim[1]+dim[2]:] print 'iter=%d:\n u-norm=%g p-norm=%g \n b-norm=%g r-norm=%g' % (iter, epsu,epsp,epsb,epsr), '\n\n\n' return u,p,b,r,epsu+epsp+epsb+epsr
def RemoveRowCol(AA,bb,VelPres): As = AA.sparray() As.eliminate_zeros() Adelete = remove_ij(As,VelPres-1,VelPres-1) A = PETSc.Mat().createAIJ(size=Adelete.shape,csr=(Adelete.indptr, Adelete.indices, Adelete.data)) # StoreMatrix(Adelete, "As") b = np.delete(bb,VelPres-1,0) zeros = 0*b bb= IO.arrayToVec(b) x = IO.arrayToVec(zeros) return A,bb,x
def PicardTolerance(x,u_k,b_k,FSpaces,dim,NormType,iter): X = IO.vecToArray(x) uu = X[0:dim[0]] bb = X[dim[0]+dim[1]:dim[0]+dim[1]+dim[2]] u = Function(FSpaces[0]) u.vector()[:] = u.vector()[:] + uu diffu = u.vector().array() - u_k.vector().array() b = Function(FSpaces[2]) b.vector()[:] = b.vector()[:] + bb diffb = b.vector().array() - b_k.vector().array() if (NormType == '2'): epsu = splin.norm(diffu)/sqrt(dim[0]) epsb = splin.norm(diffb)/sqrt(dim[0]) elif (NormType == 'inf'): epsu = splin.norm(diffu, ord=np.Inf) epsb = splin.norm(diffb, ord=np.Inf) else: print "NormType must be 2 or inf" quit() print 'iter=%d: u-norm=%g b-norm=%g ' % (iter, epsu,epsb) u_k.assign(u) b_k.assign(b) return u_k,b_k,epsu,epsb
def SchurPCD(Mass,L,F, backend): Mass = Mass.sparray() F = F.sparray() F = F + 1e-10*sp.identity(Mass.shape[0]) F = PETSc.Mat().createAIJ(size=F.shape,csr=(F.indptr, F.indices, F.data)) Mass.tocsc() Schur = sp.rand(Mass.shape[0], Mass.shape[0], density=0.00, format='csr') ksp = PETSc.KSP().create() pc = ksp.getPC() ksp.setOperators(F,F) ksp.setType('preonly') pc.setType('lu') OptDB = PETSc.Options() OptDB['pc_factor_shift_amount'] = "0.1" # OptDB['pc_factor_shift_type'] = 'POSITIVE_DEFINITE' OptDB['pc_factor_mat_ordering_type'] = 'amd' # OptDB['rtol'] = 1e-8 # ksp.max_it = 5 ksp.setFromOptions() for i in range(0,Mass.shape[0]): Col = Mass.getcol(i) Col = Col.toarray() Col = IO.arrayToVec(Col) u = Col.duplicate() ksp.solve(Col,u) C = u.duplicate() L.mult(u,C) # print C.array Schur[i,:] = C.array if backend == "PETSc": return PETSc.Mat().createAIJ(size=Schur.transpose().shape,csr=(Schur.transpose().indptr, Schur.transpose().indices, Schur.transpose().data)) else: return Schur.transpose()
def PicardTolerance(x, u_k, b_k, FSpaces, dim, NormType, iter): X = IO.vecToArray(x) uu = X[0:dim[0]] bb = X[dim[0] + dim[1]:dim[0] + dim[1] + dim[2]] u = Function(FSpaces[0]) u.vector()[:] = u.vector()[:] + uu diffu = u.vector().array() - u_k.vector().array() b = Function(FSpaces[2]) b.vector()[:] = b.vector()[:] + bb diffb = b.vector().array() - b_k.vector().array() if (NormType == '2'): epsu = splin.norm(diffu) / sqrt(dim[0]) epsb = splin.norm(diffb) / sqrt(dim[0]) elif (NormType == 'inf'): epsu = splin.norm(diffu, ord=np.Inf) epsb = splin.norm(diffb, ord=np.Inf) else: print "NormType must be 2 or inf" quit() print 'iter=%d: u-norm=%g b-norm=%g ' % (iter, epsu, epsb) u_k.assign(u) b_k.assign(b) return u_k, b_k, epsu, epsb
def SystemAssemble(W, A, b, SetupType, IterType): tic() if SetupType == 'Matrix': for i in range(len(A)): if A[i] != None: A[i].eliminate_zeros() if IterType == 'Full': A = CP.Scipy2PETSc( bmat([[A[0], A[2].T, -A[1].T, None], [A[2], A[5], None, None], [A[1], None, A[3], A[4]], [None, None, A[4].T, A[6]]])) else: A = CP.Scipy2PETSc( bmat([[A[0], A[2].T, None, None], [A[2], A[5], None, None], [None, None, A[3], A[4]], [None, None, A[4].T, A[6]]])) b = IO.arrayToVec(b) MO.StrTimePrint("MHD system assemble, time: ", toc()) return A, b else: for i in range(len(A)): if A[i] != None: A[i] = CP.Scipy2PETSc(A[i]) if IterType == 'Full': P = PETSc.Mat().createPython([ W[0].dim() + W[1].dim() + W[2].dim() + W[3].dim(), W[0].dim() + W[1].dim() + W[2].dim() + W[3].dim() ]) P.setType('python') p = MHDmulti.MHDmat(W, A) P.setPythonContext(p) else: MatFluid = PETSc.Mat().createPython( [W[0].dim() + W[1].dim(), W[0].dim() + W[1].dim()]) MatFluid.setType('python') pFluid = MHDmulti.MatFluid([W[0], W[1]], A) MatFluid.setPythonContext(pFluid) MatMag = PETSc.Mat().createPython( [W[2].dim() + W[3].dim(), W[2].dim() + W[3].dim()]) MatMag.setType('python') pMag = MHDmulti.MatMag([W[2], W[3]], A) MatMag.setPythonContext(pMag) P = [MatFluid, MatMag] b = IO.arrayToVec(b) MO.StrTimePrint("MHD mult-class setup, time: ", toc()) return P, b
def Assemble(W, NS, Maxwell, Couple, L_ns, L_m, RHSform, BC, Type, IterType): tic() if Type == 'NonLinear': F = assemble(NS[0]) BC[0].apply(F) F = F.sparray() if IterType == 'Full': C = assemble(Couple[0]) C = BC[4] * C.sparray() * BC[3] else: C = None bu = assemble(L_ns - RHSform[0]) bp = assemble(-RHSform[1]) bb = assemble(L_m - RHSform[2]) br = assemble(-RHSform[3]) BC[0].apply(bu) BC[1].apply(bb) BC[2].apply(br) b = np.concatenate((bu.array(), bp.array(), bb.array(), br.array()), axis=0) MO.StrTimePrint("MHD non-linear matrix assembled, time: ", toc()) return [F, C], b elif Type == 'Linear': M = assemble(Maxwell[0]) D = assemble(Maxwell[2]) SS = assemble(Maxwell[3]) B = assemble(NS[2]) S = assemble(NS[3]) SS = 0 * SS BC[1].apply(M) BC[2].apply(SS) B = B.sparray() * BC[3] S = S.sparray() M = M.sparray() D = BC[4] * D.sparray() * BC[5] SS = SS.sparray() MO.StrTimePrint("MHD linear matrix assembled, time: ", toc()) return [B, M, D, S, SS] else: bu = assemble(L_ns - RHSform[0]) bp = assemble(-RHSform[1]) bb = assemble(L_m - RHSform[2]) br = assemble(-RHSform[3]) BC[0].apply(bu) BC[1].apply(bb) BC[2].apply(br) b = np.concatenate((bu.array(), bp.array(), bb.array(), br.array()), axis=0) return IO.arrayToVec(b)
def BCapply(V, BC, x, opt="PETSc"): v = Function(V) v.vector()[:] = x.array BC.apply(v.vector()) if opt == "PETSc": x = IO.arrayToVec(v.vector().array()) return x else: return v
def Assemble(W, NS, Maxwell, Couple, L_ns, L_m, RHSform, BC, Type, IterType): tic() if Type == 'NonLinear': F = assemble(NS[0]) BC[0].apply(F) F = F.sparray() if IterType == 'Full': C = assemble(Couple[0]) C = BC[4]*C.sparray()*BC[3] else: C = None bu = assemble(L_ns-RHSform[0]) bp = assemble(-RHSform[1]) bb = assemble(L_m-RHSform[2]) br = assemble(-RHSform[3]) BC[0].apply(bu) BC[1].apply(bb) BC[2].apply(br) b = np.concatenate((bu.array(),bp.array(),bb.array(),br.array()),axis = 0) MO.StrTimePrint("MHD non-linear matrix assembled, time: ",toc()) return [F, C],b elif Type == 'Linear': M = assemble(Maxwell[0]) D = assemble(Maxwell[2]) SS = assemble(Maxwell[3]) B = assemble(NS[2]) S = assemble(NS[3]) SS = 0*SS BC[1].apply(M) BC[2].apply(SS) B = B.sparray()*BC[3] S = S.sparray() M = M.sparray() D = BC[4]*D.sparray()*BC[5] SS = SS.sparray() MO.StrTimePrint("MHD linear matrix assembled, time: ",toc()) return [B,M,D,S,SS] else: bu = assemble(L_ns-RHSform[0]) bp = assemble(-RHSform[1]) bb = assemble(L_m-RHSform[2]) br = assemble(-RHSform[3]) BC[0].apply(bu) BC[1].apply(bb) BC[2].apply(br) b = np.concatenate((bu.array(),bp.array(),bb.array(),br.array()),axis = 0) return IO.arrayToVec(b)
def BCapply(V,BC,x,opt = "PETSc"): v = Function(V) v.vector()[:] = x.array BC.apply(v.vector()) if opt == "PETSc": x = IO.arrayToVec(v.vector().array()) return x else: return v
def SystemAssemble(W,A,b,SetupType,IterType): tic() if SetupType == 'Matrix': for i in range(len(A)): if A[i] != None: A[i].eliminate_zeros() if IterType == 'Full': A = CP.Scipy2PETSc(bmat([[A[0],A[2].T,-A[1].T,None], [A[2],A[5],None,None], [A[1],None,A[3],A[4]], [None,None,A[4].T,A[6]]])) else: A = CP.Scipy2PETSc(bmat([[A[0],A[2].T,None,None], [A[2],A[5],None,None], [None,None,A[3],A[4]], [None,None,A[4].T,A[6]]])) b = IO.arrayToVec(b) MO.StrTimePrint("MHD system assemble, time: ",toc()) return A,b else: for i in range(len(A)): if A[i] != None: A[i] = CP.Scipy2PETSc(A[i]) if IterType == 'Full': P = PETSc.Mat().createPython([W[0].dim()+W[1].dim()+W[2].dim()+W[3].dim(),W[0].dim()+W[1].dim()+W[2].dim()+W[3].dim()]) P.setType('python') p = MHDmulti.MHDmat(W,A) P.setPythonContext(p) else: MatFluid = PETSc.Mat().createPython([W[0].dim()+W[1].dim(), W[0].dim()+W[1].dim()]) MatFluid.setType('python') pFluid = MHDmulti.MatFluid([W[0],W[1]],A) MatFluid.setPythonContext(pFluid) MatMag = PETSc.Mat().createPython([W[2].dim()+W[3].dim(), W[2].dim()+W[3].dim()]) MatMag.setType('python') pMag = MHDmulti.MatMag([W[2],W[3]],A) MatMag.setPythonContext(pMag) P = [MatFluid,MatMag] b = IO.arrayToVec(b) MO.StrTimePrint("MHD mult-class setup, time: ",toc()) return P,b
def SchurPCD(Mass, L, F, backend): Mass = Mass.sparray() F = F.sparray() F = F + 1e-10 * sp.identity(Mass.shape[0]) F = PETSc.Mat().createAIJ(size=F.shape, csr=(F.indptr, F.indices, F.data)) Mass.tocsc() Schur = sp.rand(Mass.shape[0], Mass.shape[0], density=0.00, format='csr') ksp = PETSc.KSP().create() pc = ksp.getPC() ksp.setOperators(F, F) ksp.setType('preonly') pc.setType('lu') OptDB = PETSc.Options() OptDB['pc_factor_shift_amount'] = "0.1" # OptDB['pc_factor_shift_type'] = 'POSITIVE_DEFINITE' OptDB['pc_factor_mat_ordering_type'] = 'amd' # OptDB['rtol'] = 1e-8 # ksp.max_it = 5 ksp.setFromOptions() for i in range(0, Mass.shape[0]): Col = Mass.getcol(i) Col = Col.toarray() Col = IO.arrayToVec(Col) u = Col.duplicate() ksp.solve(Col, u) C = u.duplicate() L.mult(u, C) # print C.array Schur[i, :] = C.array if backend == "PETSc": return PETSc.Mat().createAIJ(size=Schur.transpose().shape, csr=(Schur.transpose().indptr, Schur.transpose().indices, Schur.transpose().data)) else: return Schur.transpose()
del A,P if (Solving == 'Iterative' or Solving == 'Direct'): ue = u0 pe = p0 Ve = FunctionSpace(mesh,"N1curl",6) u = interpolate(ue,Ve) Qe = FunctionSpace(mesh,"CG",6) p = interpolate(pe,Qe) X = IO.vecToArray(x) x = X[0:V.dim()] ua = Function(V) ua.vector()[:] = x pp = X[V.dim():] pa = Function(Q) pa.vector()[:] = pp parameters["form_compiler"]["quadrature_degree"] = 16 ErrorB = Function(V) ErrorR = Function(Q) ErrorB = u-ua
OptDB = PETSc.Options() ksp.setFromOptions() C = sparse.csr_matrix((V.dim(),Q.dim())) tic() for i in range(0,Q.dim()): uOut = Function(V) uu = Function(Q) x = M.getVecRight() zero = np.zeros((Q.dim(),1))[:,0] zero[i] = 1 uu.vector()[:] = zero L = assemble(inner(u, grad(uu))*dx) # bcb.apply(L) rhs = IO.arrayToVec(L.array()) ksp.solve(rhs,x) # x = project(grad(uu),V) P = x.array uOut.vector()[:] = P low_values_indices = np.abs(P) < 1e-3 P[low_values_indices] = 0 #P=np.around(P) pn = P.nonzero()[0] for j in range(0,len(pn)): C[pn[j],i] = P[pn[j]] del uu print toc() pathToGrad = "/home/mwathen/Dropbox/MastersResearch/MHD/FEniCS/GradMatrices/" name = pathToGrad+"UnitSquareCrossed_m="+str(nn)
bc = DirichletBC(W.sub(0), u0, boundary) bcs = [bc] (u, p) = TrialFunctions(W) (v, q) = TestFunctions(W) mu = Constant(1e0) n = FacetNormal(mesh) h = CellSize(mesh) h_avg = avg(h) d = 0 u_k, p_k = common.Stokes(V, Q, u0, Expression(("0", "0")), [1, 1, mu]) p_k.vector()[:] = p_k.vector().array() - np.max(p_k.vector().array()) uOld = np.concatenate((u_k.vector().array(), p_k.vector().array()), axis=0) r = IO.arrayToVec(uOld[:-1]) a11 = mu * inner(grad(v), grad(u)) * dx + inner( (grad(u) * u_k), v) * dx + (1 / 2) * div(u_k) * inner( u, v) * dx - (1 / 2) * inner(u_k, n) * inner(u, v) * ds a12 = div(v) * p * dx a21 = div(u) * q * dx L1 = inner(v, f) * dx a = a11 - a12 - a21 r11 = mu * inner(grad(v), grad(u_k)) * dx + inner( (grad(u_k) * u_k), v) * dx + (1 / 2) * div(u_k) * inner( u_k, v) * dx - (1 / 2) * inner(u_k, n) * inner(u_k, v) * ds r12 = div(v) * p_k * dx r21 = div(u_k) * q * dx RHSform = r11 - r12 - r21
def solve(A, b, u, params, Fspace, SolveType, IterType, OuterTol, InnerTol, HiptmairMatrices, Hiptmairtol, KSPlinearfluids, Fp, kspF): if SolveType == "Direct": ksp = PETSc.KSP() ksp.create(comm=PETSc.COMM_WORLD) pc = ksp.getPC() ksp.setType('preonly') pc.setType('lu') OptDB = PETSc.Options() OptDB['pc_factor_mat_solver_package'] = "pastix" OptDB['pc_factor_mat_ordering_type'] = "rcm" ksp.setFromOptions() scale = b.norm() b = b/scale ksp.setOperators(A, A) del A ksp.solve(b, u) # Mits +=dodim u = u*scale MO.PrintStr("Number iterations = "+str(ksp.its), 60, "+", "\n\n", "\n\n") return u, ksp.its, 0 elif SolveType == "Direct-class": ksp = PETSc.KSP() ksp.create(comm=PETSc.COMM_WORLD) pc = ksp.getPC() ksp.setType('gmres') pc.setType('none') ksp.setFromOptions() scale = b.norm() b = b/scale ksp.setOperators(A, A) del A ksp.solve(b, u) # Mits +=dodim u = u*scale MO.PrintStr("Number iterations = "+str(ksp.its), 60, "+", "\n\n", "\n\n") return u, ksp.its, 0 else: # u = b.duplicate() if IterType == "Full": ksp = PETSc.KSP() ksp.create(comm=PETSc.COMM_WORLD) pc = ksp.getPC() ksp.setType('gmres') pc.setType('python') OptDB = PETSc.Options() OptDB['ksp_gmres_restart'] = 100 # FSpace = [Velocity,Magnetic,Pressure,Lagrange] reshist = {} def monitor(ksp, its, fgnorm): reshist[its] = fgnorm print its, " OUTER:", fgnorm # ksp.setMonitor(monitor) ksp.max_it = 100 ksp.setTolerances(OuterTol) W = Fspace FFSS = [W.sub(0), W.sub(1), W.sub(2), W.sub(3)] #pc.setPythonContext(MHDprec.BlkInvA(FFSS, kspF, KSPlinearfluids[0], KSPlinearfluids[1], Fp, HiptmairMatrices[ # 3], HiptmairMatrices[4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6], Hiptmairtol)) pc.setPythonContext(MHDprec.ApproxInv(FFSS, kspF, KSPlinearfluids[0], KSPlinearfluids[1], Fp, HiptmairMatrices[ 3], HiptmairMatrices[4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6], Hiptmairtol)) # OptDB = PETSc.Options() # OptDB['pc_factor_mat_solver_package'] = "umfpack" # OptDB['pc_factor_mat_ordering_type'] = "rcm" ksp.setFromOptions() scale = b.norm() b = b/scale ksp.setOperators(A, A) del A ksp.solve(b, u) # Mits +=dodim u = u*scale MO.PrintStr("Number iterations = "+str(ksp.its), 60, "+", "\n\n", "\n\n") return u, ksp.its, 0 IS = MO.IndexSet(Fspace, '2by2') M_is = IS[1] NS_is = IS[0] kspNS = PETSc.KSP().create() kspM = PETSc.KSP().create() kspNS.setTolerances(OuterTol) kspNS.setOperators(A[0]) kspM.setOperators(A[1]) # print P.symmetric if IterType == "MD": kspNS.setType('gmres') kspNS.max_it = 500 pcNS = kspNS.getPC() pcNS.setType(PETSc.PC.Type.PYTHON) pcNS.setPythonContext(NSpreconditioner.NSPCD(MixedFunctionSpace( [Fspace.sub(0), Fspace.sub(1)]), kspF, KSPlinearfluids[0], KSPlinearfluids[1], Fp)) elif IterType == "CD": kspNS.setType('minres') pcNS = kspNS.getPC() pcNS.setType(PETSc.PC.Type.PYTHON) Q = KSPlinearfluids[1].getOperators()[0] Q = 1./params[2]*Q KSPlinearfluids[1].setOperators(Q, Q) pcNS.setPythonContext(StokesPrecond.MHDApprox(MixedFunctionSpace( [Fspace.sub(0), Fspace.sub(1)]), kspF, KSPlinearfluids[1])) reshist = {} def monitor(ksp, its, fgnorm): reshist[its] = fgnorm print fgnorm # kspNS.setMonitor(monitor) uNS = u.getSubVector(NS_is) bNS = b.getSubVector(NS_is) # print kspNS.view() scale = bNS.norm() bNS = bNS/scale print bNS.norm() kspNS.solve(bNS, uNS) uNS = uNS*scale NSits = kspNS.its kspNS.destroy() # for line in reshist.values(): # print line kspM.setFromOptions() kspM.setType(kspM.Type.MINRES) kspM.setTolerances(InnerTol) pcM = kspM.getPC() pcM.setType(PETSc.PC.Type.PYTHON) pcM.setPythonContext(MP.Hiptmair(MixedFunctionSpace([Fspace.sub(2), Fspace.sub(3)]), HiptmairMatrices[3], HiptmairMatrices[ 4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6], Hiptmairtol)) uM = u.getSubVector(M_is) bM = b.getSubVector(M_is) scale = bM.norm() bM = bM/scale print bM.norm() kspM.solve(bM, uM) uM = uM*scale Mits = kspM.its kspM.destroy() u = IO.arrayToVec(np.concatenate([uNS.array, uM.array])) MO.PrintStr("Number of M iterations = " + str(Mits), 60, "+", "\n\n", "\n\n") MO.PrintStr("Number of NS/S iterations = " + str(NSits), 60, "+", "\n\n", "\n\n") return u, NSits, Mits
def foo(): m = 7 errL2u =np.zeros((m-1,1)) errH1u =np.zeros((m-1,1)) errL2p =np.zeros((m-1,1)) errL2b =np.zeros((m-1,1)) errCurlb =np.zeros((m-1,1)) errL2r =np.zeros((m-1,1)) errH1r =np.zeros((m-1,1)) l2uorder = np.zeros((m-1,1)) H1uorder =np.zeros((m-1,1)) l2porder = np.zeros((m-1,1)) l2border = np.zeros((m-1,1)) Curlborder =np.zeros((m-1,1)) l2rorder = np.zeros((m-1,1)) H1rorder = np.zeros((m-1,1)) NN = np.zeros((m-1,1)) DoF = np.zeros((m-1,1)) Velocitydim = np.zeros((m-1,1)) Magneticdim = np.zeros((m-1,1)) Pressuredim = np.zeros((m-1,1)) Lagrangedim = np.zeros((m-1,1)) Wdim = np.zeros((m-1,1)) iterations = np.zeros((m-1,1)) SolTime = np.zeros((m-1,1)) udiv = np.zeros((m-1,1)) MU = np.zeros((m-1,1)) level = np.zeros((m-1,1)) NSave = np.zeros((m-1,1)) Mave = np.zeros((m-1,1)) TotalTime = np.zeros((m-1,1)) nn = 2 dim = 2 ShowResultPlots = 'yes' split = 'Linear' kappa = 0.01 for yy in xrange(1,5): kappa = kappa*10 for xx in xrange(1,m): print xx level[xx-1] = xx+ 2 nn = 2**(level[xx-1]) # Create mesh and define function space nn = int(nn) NN[xx-1] = nn/2 # parameters["form_compiler"]["quadrature_degree"] = 6 # parameters = CP.ParameterSetup() mesh = UnitSquareMesh(nn,nn) order = 1 parameters['reorder_dofs_serial'] = False Velocity = VectorFunctionSpace(mesh, "CG", order) Pressure = FunctionSpace(mesh, "DG", order-1) Magnetic = FunctionSpace(mesh, "N1curl", order) Lagrange = FunctionSpace(mesh, "CG", order) W = MixedFunctionSpace([Velocity, Pressure, Magnetic,Lagrange]) # W = Velocity*Pressure*Magnetic*Lagrange Velocitydim[xx-1] = Velocity.dim() Pressuredim[xx-1] = Pressure.dim() Magneticdim[xx-1] = Magnetic.dim() Lagrangedim[xx-1] = Lagrange.dim() Wdim[xx-1] = W.dim() print "\n\nW: ",Wdim[xx-1],"Velocity: ",Velocitydim[xx-1],"Pressure: ",Pressuredim[xx-1],"Magnetic: ",Magneticdim[xx-1],"Lagrange: ",Lagrangedim[xx-1],"\n\n" dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(), Lagrange.dim()] def boundary(x, on_boundary): return on_boundary u0, p0,b0, r0, Laplacian, Advection, gradPres,CurlCurl, gradR, NS_Couple, M_Couple = ExactSol.MHD2D(4,1) bcu = DirichletBC(W.sub(0),u0, boundary) bcb = DirichletBC(W.sub(2),b0, boundary) bcr = DirichletBC(W.sub(3),r0, boundary) # bc = [u0,p0,b0,r0] bcs = [bcu,bcb,bcr] FSpaces = [Velocity,Pressure,Magnetic,Lagrange] (u, b, p, r) = TrialFunctions(W) (v, c, q, s) = TestFunctions(W) #kappa = 1.0 MU = 1.0 Mu_m =1e1 IterType = 'Combined' F_NS = -MU*Laplacian+Advection+gradPres-kappa*NS_Couple if kappa == 0: F_M = Mu_m*CurlCurl+gradR -kappa*M_Couple else: F_M = Mu_m*kappa*CurlCurl+gradR -kappa*M_Couple params = [kappa,Mu_m,MU] # MO.PrintStr("Preconditioning MHD setup",5,"+","\n\n","\n\n") Hiptmairtol = 1e-5 HiptmairMatrices = PrecondSetup.MagneticSetup(Magnetic, Lagrange, b0, r0, Hiptmairtol, params) MO.PrintStr("Setting up MHD initial guess",5,"+","\n\n","\n\n") u_k,p_k,b_k,r_k = common.InitialGuess(FSpaces,[u0,p0,b0,r0],[F_NS,F_M],params,HiptmairMatrices,1e-6,Neumann=Expression(("0","0")),options ="New", FS = "DG") #plot(p_k, interactive = True) b_t = TrialFunction(Velocity) c_t = TestFunction(Velocity) #print assemble(inner(b,c)*dx).array().shape #print mat #ShiftedMass = assemble(inner(mat*b,c)*dx) #as_vector([inner(b,c)[0]*b_k[0],inner(b,c)[1]*(-b_k[1])]) ones = Function(Pressure) ones.vector()[:]=(0*ones.vector().array()+1) # pConst = - assemble(p_k*dx)/assemble(ones*dx) p_k.vector()[:] += - assemble(p_k*dx)/assemble(ones*dx) x = Iter.u_prev(u_k,p_k,b_k,r_k) KSPlinearfluids, MatrixLinearFluids = PrecondSetup.FluidLinearSetup(Pressure, MU) kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) #plot(b_k) ns,maxwell,CoupleTerm,Lmaxwell,Lns = forms.MHD2D(mesh, W,F_M,F_NS, u_k,b_k,params,IterType,"DG") RHSform = forms.PicardRHS(mesh, W, u_k, p_k, b_k, r_k, params,"DG") bcu = DirichletBC(W.sub(0),Expression(("0.0","0.0")), boundary) bcb = DirichletBC(W.sub(2),Expression(("0.0","0.0")), boundary) bcr = DirichletBC(W.sub(3),Expression(("0.0")), boundary) bcs = [bcu,bcb,bcr] eps = 1.0 # error measure ||u-u_k|| tol = 1.0E-4 # tolerance iter = 0 # iteration counter maxiter = 40 # max no of iterations allowed SolutionTime = 0 outer = 0 # parameters['linear_algebra_backend'] = 'uBLAS' # FSpaces = [Velocity,Magnetic,Pressure,Lagrange] if IterType == "CD": AA, bb = assemble_system(maxwell+ns, (Lmaxwell + Lns) - RHSform, bcs) A,b = CP.Assemble(AA,bb) # u = b.duplicate() # P = CP.Assemble(PP) u_is = PETSc.IS().createGeneral(range(Velocity.dim())) NS_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim())) M_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim(),W.dim())) OuterTol = 1e-5 InnerTol = 1e-5 NSits =0 Mits =0 TotalStart =time.time() SolutionTime = 0 while eps > tol and iter < maxiter: iter += 1 MO.PrintStr("Iter "+str(iter),7,"=","\n\n","\n\n") tic() if IterType == "CD": bb = assemble((Lmaxwell + Lns) - RHSform) for bc in bcs: bc.apply(bb) FF = AA.sparray()[0:dim[0],0:dim[0]] A,b = CP.Assemble(AA,bb) # if iter == 1 if iter == 1: u = b.duplicate() F = A.getSubMatrix(u_is,u_is) kspF = NSprecondSetup.LSCKSPnonlinear(F) else: AA, bb = assemble_system(maxwell+ns+CoupleTerm, (Lmaxwell + Lns) - RHSform, bcs) A,b = CP.Assemble(AA,bb) # if iter == 1: if iter == 1: u = b.duplicate() print ("{:40}").format("MHD assemble, time: "), " ==> ",("{:4f}").format(toc()), ("{:9}").format(" time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5]) kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) print "Inititial guess norm: ", u.norm() #A,Q if IterType == 'Combined': n = FacetNormal(mesh) mat = as_matrix([[b_k[1]*b_k[1],-b_k[1]*b_k[0]],[-b_k[1]*b_k[0],b_k[0]*b_k[0]]]) F = A.getSubMatrix(u_is,u_is) a = params[2]*inner(grad(b_t), grad(c_t))*dx(W.mesh()) + inner((grad(b_t)*u_k),c_t)*dx(W.mesh()) +(1/2)*div(u_k)*inner(c_t,b_t)*dx(W.mesh()) - (1/2)*inner(u_k,n)*inner(c_t,b_t)*ds(W.mesh())+kappa/Mu_m*inner(mat*b_t,c_t)*dx(W.mesh()) ShiftedMass = assemble(a) bcu.apply(ShiftedMass) kspF = NSprecondSetup.LSCKSPnonlinear(F) else: F = A.getSubMatrix(u_is,u_is) kspF = NSprecondSetup.LSCKSPnonlinear(F) stime = time.time() u, mits,nsits = S.solve(A,b,u,params,W,IterType,OuterTol,InnerTol,HiptmairMatrices,Hiptmairtol,KSPlinearfluids, Fp,kspF) Soltime = time.time()- stime Mits += mits NSits += nsits SolutionTime += Soltime u1, p1, b1, r1, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter) p1.vector()[:] += - assemble(p1*dx)/assemble(ones*dx) u_k.assign(u1) p_k.assign(p1) b_k.assign(b1) r_k.assign(r1) uOld= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0) x = IO.arrayToVec(uOld) XX= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0) SolTime[xx-1] = SolutionTime/iter NSave[xx-1] = (float(NSits)/iter) Mave[xx-1] = (float(Mits)/iter) iterations[xx-1] = iter TotalTime[xx-1] = time.time() - TotalStart dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(),Lagrange.dim()] # # ExactSolution = [u0,p0,b0,r0] # errL2u[xx-1], errH1u[xx-1], errL2p[xx-1], errL2b[xx-1], errCurlb[xx-1], errL2r[xx-1], errH1r[xx-1] = Iter.Errors(XX,mesh,FSpaces,ExactSolution,order,dim, "DG") # # if xx > 1: # l2uorder[xx-1] = np.abs(np.log2(errL2u[xx-2]/errL2u[xx-1])) # H1uorder[xx-1] = np.abs(np.log2(errH1u[xx-2]/errH1u[xx-1])) # # l2porder[xx-1] = np.abs(np.log2(errL2p[xx-2]/errL2p[xx-1])) # # l2border[xx-1] = np.abs(np.log2(errL2b[xx-2]/errL2b[xx-1])) # Curlborder[xx-1] = np.abs(np.log2(errCurlb[xx-2]/errCurlb[xx-1])) # # l2rorder[xx-1] = np.abs(np.log2(errL2r[xx-2]/errL2r[xx-1])) # H1rorder[xx-1] = np.abs(np.log2(errH1r[xx-2]/errH1r[xx-1])) import pandas as pd # LatexTitles = ["l","DoFu","Dofp","V-L2","L2-order","V-H1","H1-order","P-L2","PL2-order"] # LatexValues = np.concatenate((level,Velocitydim,Pressuredim,errL2u,l2uorder,errH1u,H1uorder,errL2p,l2porder), axis=1) # LatexTable = pd.DataFrame(LatexValues, columns = LatexTitles) # pd.set_option('precision',3) # LatexTable = MO.PandasFormat(LatexTable,"V-L2","%2.4e") # LatexTable = MO.PandasFormat(LatexTable,'V-H1',"%2.4e") # LatexTable = MO.PandasFormat(LatexTable,"H1-order","%1.2f") # LatexTable = MO.PandasFormat(LatexTable,'L2-order',"%1.2f") # LatexTable = MO.PandasFormat(LatexTable,"P-L2","%2.4e") # LatexTable = MO.PandasFormat(LatexTable,'PL2-order',"%1.2f") # print LatexTable # # # print "\n\n Magnetic convergence" # MagneticTitles = ["l","B DoF","R DoF","B-L2","L2-order","B-Curl","HCurl-order"] # MagneticValues = np.concatenate((level,Magneticdim,Lagrangedim,errL2b,l2border,errCurlb,Curlborder),axis=1) # MagneticTable= pd.DataFrame(MagneticValues, columns = MagneticTitles) # pd.set_option('precision',3) # MagneticTable = MO.PandasFormat(MagneticTable,"B-Curl","%2.4e") # MagneticTable = MO.PandasFormat(MagneticTable,'B-L2',"%2.4e") # MagneticTable = MO.PandasFormat(MagneticTable,"L2-order","%1.2f") # MagneticTable = MO.PandasFormat(MagneticTable,'HCurl-order',"%1.2f") # print MagneticTable # # # # # import pandas as pd # print "\n\n Iteration table" if IterType == "Full": IterTitles = ["l","DoF","AV solve Time","Total picard time","picard iterations","Av Outer its","Av Inner its",] else: IterTitles = ["l","DoF","AV solve Time","Total picard time","picard iterations","Av NS iters","Av M iters"] IterValues = np.concatenate((level,Wdim,SolTime,TotalTime,iterations,Mave,NSave),axis=1) IterTable= pd.DataFrame(IterValues, columns = IterTitles) if IterType == "Full": IterTable = MO.PandasFormat(IterTable,'Av Outer its',"%2.1f") IterTable = MO.PandasFormat(IterTable,'Av Inner its',"%2.1f") else: IterTable = MO.PandasFormat(IterTable,'Av NS iters',"%2.1f") IterTable = MO.PandasFormat(IterTable,'Av M iters',"%2.1f") print IterTable print " \n Outer Tol: ",OuterTol, "Inner Tol: ", InnerTol IterTable.to_latex('Tables/IterType='+IterType+'_n='+str(m)+'_mu='+str(MU)+'_kappa='+str(kappa)+'_mu_m='+str(Mu_m)+'.tex') # # # if (ShowResultPlots == 'yes'): # plot(u_k) # plot(interpolate(u0,Velocity)) # # plot(p_k) # # plot(interpolate(p0,Pressure)) # # plot(b_k) # plot(interpolate(b0,Magnetic)) # # plot(r_k) # plot(interpolate(r0,Lagrange)) # # interactive() interactive()
n = FacetNormal(mesh) h = CellSize(mesh) h_avg =avg(h) d = 0 u_k,p_k = common.Stokes(V,Q,u0,f,[1,1,MU]) # p_k.vector()[:] = p_k.vector().array() pConst = - assemble(p_k*dx)/assemble(ones*dx) p_k.vector()[:] += pConst # u_k = Function(V) # p_k = Function(Q) # plot(u_k) # plot(p_k) uOld = np.concatenate((u_k.vector().array(),p_k.vector().array()), axis=0) r = IO.arrayToVec(uOld) a11 = MU*inner(grad(v), grad(u))*dx + inner((grad(u)*u_k),v)*dx + (1/2)*div(u_k)*inner(u,v)*dx - (1/2)*inner(u_k,n)*inner(u,v)*ds a12 = div(v)*p*dx a21 = div(u)*q*dx L1 = inner(v, f)*dx a = a11-a12-a21 r11 = MU*inner(grad(v), grad(u_k))*dx + inner((grad(u_k)*u_k),v)*dx + (1/2)*div(u_k)*inner(u_k,v)*dx - (1/2)*inner(u_k,n)*inner(u_k,v)*ds r12 = div(v)*p_k*dx r21 = div(u_k)*q*dx RHSform = r11-r12-r21 # RHSform = 0
def foo(): m = 6 mm = 4 errL2u = np.zeros((m - 1, 1)) errH1u = np.zeros((m - 1, 1)) errL2p = np.zeros((m - 1, 1)) errL2b = np.zeros((m - 1, 1)) errCurlb = np.zeros((m - 1, 1)) errL2r = np.zeros((m - 1, 1)) errH1r = np.zeros((m - 1, 1)) l2uorder = np.zeros((m - 1, 1)) H1uorder = np.zeros((m - 1, 1)) l2porder = np.zeros((m - 1, 1)) l2border = np.zeros((m - 1, 1)) Curlborder = np.zeros((m - 1, 1)) l2rorder = np.zeros((m - 1, 1)) H1rorder = np.zeros((m - 1, 1)) NN = np.zeros((m - 1, 1)) DoF = np.zeros((m - 1, 1)) Velocitydim = np.zeros((m - 1, 1)) Magneticdim = np.zeros((m - 1, 1)) Pressuredim = np.zeros((m - 1, 1)) Lagrangedim = np.zeros((m - 1, 1)) Wdim = np.zeros((m - 1, 1)) iterations = np.zeros((m - 1, 1)) SolTime = np.zeros((m - 1, 1)) udiv = np.zeros((m - 1, 1)) MU = np.zeros((m - 1, 1)) level = np.zeros((m - 1, 1)) NSave = np.zeros((m - 1, 1)) Mave = np.zeros((m - 1, 1)) TotalTime = np.zeros((m - 1, 1)) kappaSave = np.zeros((1, 3 * (mm))) KappaIts = np.zeros((m - 1, 3 * (mm))) nn = 2 dim = 2 ShowResultPlots = 'yes' split = 'Linear' MU[0] = 1e0 ITERTYPE = ['Full', 'MD', 'CD'] kappa = 0.01 for xx in xrange(1, m): kk = 0 kappa = 0.01 for yy in xrange(1, mm + 1): kappa = kappa * 10 for jj in range(3): IterType = ITERTYPE[jj] print xx level[xx - 1] = xx + 2 nn = 2**(level[xx - 1]) # Create mesh and define function space nn = int(nn) NN[xx - 1] = nn / 2 # parameters["form_compiler"]["quadrature_degree"] = 6 # parameters = CP.ParameterSetup() mesh = UnitSquareMesh(nn, nn) order = 1 parameters['reorder_dofs_serial'] = False Velocity = VectorFunctionSpace(mesh, "CG", order + 1) Pressure = FunctionSpace(mesh, "CG", order) Magnetic = FunctionSpace(mesh, "N1curl", order) Lagrange = FunctionSpace(mesh, "CG", order) W = MixedFunctionSpace( [Velocity, Pressure, Magnetic, Lagrange]) # W = Velocity*Pressure*Magnetic*Lagrange Velocitydim[xx - 1] = Velocity.dim() Pressuredim[xx - 1] = Pressure.dim() Magneticdim[xx - 1] = Magnetic.dim() Lagrangedim[xx - 1] = Lagrange.dim() Wdim[xx - 1] = W.dim() print "\n\nW: ", Wdim[xx - 1], "Velocity: ", Velocitydim[ xx - 1], "Pressure: ", Pressuredim[ xx - 1], "Magnetic: ", Magneticdim[ xx - 1], "Lagrange: ", Lagrangedim[xx - 1], "\n\n" dim = [ Velocity.dim(), Pressure.dim(), Magnetic.dim(), Lagrange.dim() ] def boundary(x, on_boundary): return on_boundary u0, p0, b0, r0, Laplacian, Advection, gradPres, CurlCurl, gradR, NS_Couple, M_Couple = ExactSol.MHD2D( 4, 1) bcu = DirichletBC(Velocity, u0, boundary) bcb = DirichletBC(Magnetic, b0, boundary) bcr = DirichletBC(Lagrange, r0, boundary) # bc = [u0,p0,b0,r0] bcs = [bcu, bcb, bcr] FSpaces = [Velocity, Pressure, Magnetic, Lagrange] (u, b, p, r) = TrialFunctions(W) (v, c, q, s) = TestFunctions(W) Mu_m = 10.0 MU = 1.0 # IterType = 'Full' Split = "No" Saddle = "No" Stokes = "No" SetupType = 'Matrix' F_NS = -MU * Laplacian + Advection + gradPres - kappa * NS_Couple if kappa == 0: F_M = Mu_m * CurlCurl + gradR - kappa * M_Couple else: F_M = Mu_m * kappa * CurlCurl + gradR - kappa * M_Couple params = [kappa, Mu_m, MU] MO.PrintStr("Seting up initial guess matricies", 2, "=", "\n\n", "\n") BCtime = time.time() BC = MHDsetup.BoundaryIndices(FSpaces) MO.StrTimePrint("BC index function, time: ", time.time() - BCtime) Hiptmairtol = 1e-5 HiptmairMatrices = PrecondSetup.MagneticSetup( Magnetic, Lagrange, b0, r0, Hiptmairtol, params) print HiptmairMatrices MO.PrintStr("Setting up MHD initial guess", 5, "+", "\n\n", "\n\n") u_k, p_k, b_k, r_k = common.InitialGuess(FSpaces, [u0, p0, b0, r0], [F_NS, F_M], params, HiptmairMatrices, 1e-10, Neumann=Expression( ("0", "0")), options="New") b_t = TrialFunction(Velocity) c_t = TestFunction(Velocity) ones = Function(Pressure) ones.vector()[:] = (0 * ones.vector().array() + 1) # pConst = - assemble(p_k*dx)/assemble(ones*dx) p_k.vector()[:] += -assemble(p_k * dx) / assemble(ones * dx) x = Iter.u_prev(u_k, p_k, b_k, r_k) KSPlinearfluids, MatrixLinearFluids = PrecondSetup.FluidLinearSetup( Pressure, MU) kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) #plot(b_k) ns, maxwell, CoupleTerm, Lmaxwell, Lns = forms.MHD2D( mesh, W, F_M, F_NS, u_k, b_k, params, IterType, "CG", Saddle, Stokes) RHSform = forms.PicardRHS(mesh, W, u_k, p_k, b_k, r_k, params, "CG", Saddle, Stokes) bcu = DirichletBC(FSpaces[0], Expression(("0.0", "0.0")), boundary) bcb = DirichletBC(FSpaces[2], Expression(("0.0", "0.0")), boundary) bcr = DirichletBC(FSpaces[3], Expression(("0.0")), boundary) bcs = [bcu, bcb, bcr] parameters['linear_algebra_backend'] = 'uBLAS' eps = 1.0 # error measure ||u-u_k|| tol = 1.0E-4 # tolerance iter = 0 # iteration counter maxiter = 20 # max no of iterations allowed SolutionTime = 0 outer = 0 # parameters['linear_algebra_backend'] = 'uBLAS' # FSpaces = [Velocity,Magnetic,Pressure,Lagrange] # if IterType == "CD": # MO.PrintStr("Setting up PETSc "+SetupType,2,"=","\n","\n") # Alin = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "Linear",IterType) # Fnlin,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType) # A = Fnlin+Alin # A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType) # u = b.duplicate() u_is = PETSc.IS().createGeneral(range(Velocity.dim())) NS_is = PETSc.IS().createGeneral( range(Velocity.dim() + Pressure.dim())) M_is = PETSc.IS().createGeneral( range(Velocity.dim() + Pressure.dim(), W.dim())) OuterTol = 1e-5 InnerTol = 1e-5 NSits = 0 Mits = 0 TotalStart = time.time() SolutionTime = 0 while eps > tol and iter < maxiter: iter += 1 MO.PrintStr("Iter " + str(iter), 7, "=", "\n\n", "\n\n") AssembleTime = time.time() # if IterType == "CD": # MO.StrTimePrint("MHD CD RHS assemble, time: ", time.time()-AssembleTime) # b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "CD",IterType) # else: MO.PrintStr("Setting up PETSc " + SetupType, 2, "=", "\n", "\n") if Split == "Yes": if iter == 1: Fnlin, b, bc = MHDsetup.Assemble( W, ns, maxwell, CoupleTerm, Lns, Lmaxwell, RHSform, bcs + BC, "NonLinear", IterType) BC[0] = bc Alin = MHDsetup.Assemble(W, ns, maxwell, CoupleTerm, Lns, Lmaxwell, RHSform, bcs + BC, "Linear", IterType) A = Fnlin + Alin A, b = MHDsetup.SystemAssemble( FSpaces, A, b, SetupType, IterType) u = b.duplicate() else: Fnline, b, bc = MHDsetup.Assemble( W, ns, maxwell, CoupleTerm, Lns, Lmaxwell, RHSform, bcs + BC, "NonLinear", IterType) A = Fnlin + Alin A, b = MHDsetup.SystemAssemble( FSpaces, A, b, SetupType, IterType) else: AA, bb = assemble_system(maxwell + ns + CoupleTerm, (Lmaxwell + Lns) - RHSform, bcs) A, b = CP.Assemble(AA, bb) # if iter == 1: MO.StrTimePrint("MHD total assemble, time: ", time.time() - AssembleTime) u = b.duplicate() kspFp, Fp = PrecondSetup.FluidNonLinearSetup( Pressure, MU, u_k) print "Inititial guess norm: ", u.norm( PETSc.NormType.NORM_INFINITY) #A,Q # if IterType == 'Full': # n = FacetNormal(mesh) # mat = as_matrix([[b_k[1]*b_k[1],-b_k[1]*b_k[0]],[-b_k[1]*b_k[0],b_k[0]*b_k[0]]]) # a = params[2]*inner(grad(b_t), grad(c_t))*dx(W.mesh()) + inner((grad(b_t)*u_k),c_t)*dx(W.mesh()) +(1./2)*div(u_k)*inner(c_t,b_t)*dx(W.mesh()) - (1./2)*inner(u_k,n)*inner(c_t,b_t)*ds(W.mesh())+kappa/Mu_m*inner(mat*b_t,c_t)*dx(W.mesh()) # ShiftedMass = assemble(a) # bcu.apply(ShiftedMass) # ShiftedMass = CP.Assemble(ShiftedMass) # kspF = NSprecondSetup.LSCKSPnonlinear(ShiftedMass) # else: # F = A.getSubMatrix(u_is,u_is) # kspF = NSprecondSetup.LSCKSPnonlinear(F) stime = time.time() u, mits, nsits = S.solve(A, b, u, params, W, 'Direct', IterType, OuterTol, InnerTol, HiptmairMatrices, Hiptmairtol, KSPlinearfluids, Fp, 0) Soltime = time.time() - stime MO.StrTimePrint("MHD solve, time: ", Soltime) Mits += mits NSits += nsits SolutionTime += Soltime u1, p1, b1, r1, eps = Iter.PicardToleranceDecouple( u, x, FSpaces, dim, "2", iter) if eps > 1e8 and iter > 2: iter = 0 break p1.vector()[:] += -assemble(p1 * dx) / assemble(ones * dx) u_k.assign(u1) p_k.assign(p1) b_k.assign(b1) r_k.assign(r1) uOld = np.concatenate( (u_k.vector().array(), p_k.vector().array(), b_k.vector().array(), r_k.vector().array()), axis=0) x = IO.arrayToVec(uOld) print yy, jj print kk KappaIts[xx - 1, kk] = iter kappaSave[0, kk] = kappa kk += 1 # XX= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0) # SolTime[xx-1] = SolutionTime/iter # NSave[xx-1] = (float(NSits)/iter) # Mave[xx-1] = (float(Mits)/iter) # iterations[xx-1] = iter # TotalTime[xx-1] = time.time() - TotalStart print kappaSave print KappaIts # dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(),Lagrange.dim()] # # ExactSolution = [u0,p0,b0,r0] # errL2u[xx-1], errH1u[xx-1], errL2p[xx-1], errL2b[xx-1], errCurlb[xx-1], errL2r[xx-1], errH1r[xx-1] = Iter.Errors(XX,mesh,FSpaces,ExactSolution,order,dim, "DG") # # if xx > 1: # l2uorder[xx-1] = np.abs(np.log2(errL2u[xx-2]/errL2u[xx-1])) # H1uorder[xx-1] = np.abs(np.log2(errH1u[xx-2]/errH1u[xx-1])) # # l2porder[xx-1] = np.abs(np.log2(errL2p[xx-2]/errL2p[xx-1])) # # l2border[xx-1] = np.abs(np.log2(errL2b[xx-2]/errL2b[xx-1])) # Curlborder[xx-1] = np.abs(np.log2(errCurlb[xx-2]/errCurlb[xx-1])) # # l2rorder[xx-1] = np.abs(np.log2(errL2r[xx-2]/errL2r[xx-1])) # H1rorder[xx-1] = np.abs(np.log2(errH1r[xx-2]/errH1r[xx-1])) # # # # # import pandas as pd # # # # LatexTitles = ["l","DoFu","Dofp","V-L2","L2-order","V-H1","H1-order","P-L2","PL2-order"] # LatexValues = np.concatenate((level,Velocitydim,Pressuredim,errL2u,l2uorder,errH1u,H1uorder,errL2p,l2porder), axis=1) # LatexTable = pd.DataFrame(LatexValues, columns = LatexTitles) # pd.set_option('precision',3) # LatexTable = MO.PandasFormat(LatexTable,"V-L2","%2.4e") # LatexTable = MO.PandasFormat(LatexTable,'V-H1',"%2.4e") # LatexTable = MO.PandasFormat(LatexTable,"H1-order","%1.2f") # LatexTable = MO.PandasFormat(LatexTable,'L2-order',"%1.2f") # LatexTable = MO.PandasFormat(LatexTable,"P-L2","%2.4e") # LatexTable = MO.PandasFormat(LatexTable,'PL2-order',"%1.2f") # print LatexTable # # # print "\n\n Magnetic convergence" # MagneticTitles = ["l","B DoF","R DoF","B-L2","L2-order","B-Curl","HCurl-order"] # MagneticValues = np.concatenate((level,Magneticdim,Lagrangedim,errL2b,l2border,errCurlb,Curlborder),axis=1) # MagneticTable= pd.DataFrame(MagneticValues, columns = MagneticTitles) # pd.set_option('precision',3) # MagneticTable = MO.PandasFormat(MagneticTable,"B-Curl","%2.4e") # MagneticTable = MO.PandasFormat(MagneticTable,'B-L2',"%2.4e") # MagneticTable = MO.PandasFormat(MagneticTable,"L2-order","%1.2f") # MagneticTable = MO.PandasFormat(MagneticTable,'HCurl-order',"%1.2f") # print MagneticTable import pandas as pd print "\n\n Iteration table" LatexTitles = ["l", "DoF"] for x in xrange(1, mm + 1): LatexTitles.extend(["Full", "MD", "CD"]) pd.set_option('precision', 3) LatexValues = np.concatenate((level, Wdim, KappaIts), axis=1) title = np.concatenate((np.array([[0, 0]]), kappaSave), axis=1) MU = ["0", "0"] for x in xrange(1, mm + 1): MU.extend(["Full", "MD", "CD"]) LatexValues = np.vstack((title, LatexValues)) LatexTable = pd.DataFrame(LatexValues, columns=LatexTitles) # name = "Output/"+IterType+"mutest" # LatexTable.to_csv(name) print LatexTable.to_latex() tableName = "2d_nu=" + str(MU) + "_nu_m=" + str(Mu_m) + "_kappa=" + str( kappa) + ".tex" IterTable.to_latex(tableName) # # # if (ShowResultPlots == 'yes'): # plot(u_k) # plot(interpolate(u0,Velocity)) # # plot(p_k) # # plot(interpolate(p0,Pressure)) # # plot(b_k) # plot(interpolate(b0,Magnetic)) # # plot(r_k) # plot(interpolate(r0,Lagrange)) # # interactive() interactive()
C=c) a11 = inner(curl(v), curl(u)) * dx a12 = inner(v, grad(p)) * dx a21 = inner(u, grad(q)) * dx L1 = inner(v, f) * dx a = a11 + a12 + a21 tic() AA, bb = assemble_system(a, L1, bcs) A, b = CP.Assemble(AA, bb) print toc() b = bb.array() zeros = 0 * b del bb bb = IO.arrayToVec(b) x = IO.arrayToVec(zeros) p11 = inner(curl(v), curl(u)) * dx + inner(u, v) * dx p22 = inner(grad(p), grad(q)) * dx pp = p11 + p22 PP, Pb = assemble_system(pp, L1, bcs) P = CP.Assemble(PP) if (Solving == 'Direct'): ksp = PETSc.KSP().create() ksp.setOperators(A) ksp.setFromOptions() ksp.setType(ksp.Type.MINRES)
(u, p) = TrialFunctions(W) (v, q) = TestFunctions(W) f = -MU*Laplacian+gradPres n = FacetNormal(mesh) h = CellSize(mesh) h_avg =avg(h) d = 0 u_k,p_k = common.Stokes(V,Q,u0,f,[1,1,MU]) uOld = np.concatenate((u_k.vector().array(),p_k.vector().array()), axis=0) r = IO.arrayToVec(uOld) a11 = MU*inner(grad(v), grad(u))*dx + inner((grad(u)*u_k),v)*dx + (1/2)*div(u_k)*inner(u,v)*dx- (1/2)*inner(u_k,n)*inner(u,v)*ds a12 = div(v)*p*dx a21 = div(u)*q*dx L1 = inner(v, f)*dx a = a11-a12-a21 r11 = MU*inner(grad(v), grad(u_k))*dx + inner((grad(u_k)*u_k),v)*dx + (1/2)*div(u_k)*inner(u_k,v)*dx- (1/2)*inner(u_k,n)*inner(u_k,v)*ds r12 = div(v)*p_k*dx r21 = div(u_k)*q*dx RHSform = r11-r12-r21 p11 = inner(u,v)*dx
ksp = PETSc.KSP().create() pc = PETSc.PC().create() ksp.setOperators(A,P) while eps > tol and iter < maxiter: iter += 1 uu = Function(W) if IterType == "CD": bb = assemble((Lmaxwell + Lns) - RHSform) for bc in bcs: bc.apply(bb) zeros = 0*bb.array() b= as_backend_type(bb).vec() u = IO.arrayToVec(zeros) else: AA, bb = assemble_system(maxwell+ns+CoupleTerm, (Lmaxwell + Lns) - RHSform, bcs) A = as_backend_type(AA).mat() zeros = 0*bb.array() b= as_backend_type(bb).vec() u = IO.arrayToVec(zeros) ksp = PETSc.KSP().create() pc = PETSc.PC().create() ksp.setOperators(A,P) if IterType == "Full": pass
f = -MU*Laplacian+Advection+gradPres n = FacetNormal(mesh) h = CellSize(mesh) h_avg =avg(h) d = 0 u_k,p_k = common.Stokes(V,Q,u0,f,[1,1,MU]) # p_k.vector()[:] = p_k.vector().array() # u_k = Function(V) # p_k = Function(Q) uOld = np.concatenate((u_k.vector().array(),p_k.vector().array()), axis=0) r = IO.arrayToVec(uOld) a11 = MU*inner(grad(v), grad(u))*dx + inner((grad(u)*u_k),v)*dx + (1/2)*div(u_k)*inner(u,v)*dx- (1/2)*inner(u_k,n)*inner(u,v)*ds a12 = div(v)*p*dx a21 = div(u)*q*dx L1 = inner(v, f)*dx a = a11-a12-a21 r11 = MU*inner(grad(v), grad(u_k))*dx + inner((grad(u_k)*u_k),v)*dx + (1/2)*div(u_k)*inner(u_k,v)*dx- (1/2)*inner(u_k,n)*inner(u_k,v)*ds r12 = div(v)*p_k*dx r21 = div(u_k)*q*dx RHSform = r11-r12-r21 p11 = inner(u,v)*dx
def Assemble(W, NS, Maxwell, Couple, L_ns, L_m, RHSform, BC, Type, IterType): tic() if Type == 'NonLinear': F = assemble(NS[0]) BC[0].apply(F) F = F.sparray() dim = W.mesh().geometry().dim() Vboundary = np.ones(W.sub(0).dim()) Vboundary[F.diagonal() == 1] = 0 # if dim == 3: # VelocityBoundary = np.concatenate((Vboundary,Vboundary,Vboundary),axis=1) # else: # VelocityBoundary = np.concatenate((Vboundary,Vboundary),axis=1) BC[3] = spdiags(Vboundary,0,W.sub(0).dim(),W.sub(0).dim()) if IterType == 'Full': C = assemble(Couple[0]) C = BC[4]*C.sparray()*BC[3] else: C = None if RHSform == 0: bu = assemble(L_ns) bp = Function(W[1]).vector() print bp.array() bb = assemble(L_m) br = Function(W[3]).vector() BC[0].apply(bu) BC[1].apply(bb) BC[2].apply(br) else: bu = assemble(L_ns-RHSform[0]) bp = assemble(-RHSform[1]) bb = assemble(L_m-RHSform[2]) br = assemble(-RHSform[3]) BC[0].apply(bu) BC[1].apply(bb) BC[2].apply(br) b = np.concatenate((bu.array(),bp.array(),bb.array(),br.array()),axis = 0) MO.StrTimePrint("MHD non-linear matrix assembled, time: ",toc()) return [F, C],b, BC[3] elif Type == 'Linear': M = assemble(Maxwell[0]) D = assemble(Maxwell[2]) SS = assemble(Maxwell[3]) B = assemble(NS[2]) if NS[3] != None: S = assemble(NS[3]) S = S.sparray() else: S = None SS = 0*SS BC[1].apply(M) BC[2].apply(SS) B = B.sparray()*BC[3] M = M.sparray() D = BC[4]*D.sparray()*BC[5] SS = SS.sparray() MO.StrTimePrint("MHD linear matrix assembled, time: ",toc()) return [B,M,D,S,SS] else: bu = assemble(L_ns-RHSform[0]) bp = assemble(-RHSform[1]) bb = assemble(L_m-RHSform[2]) br = assemble(-RHSform[3]) BC[0].apply(bu) BC[1].apply(bb) BC[2].apply(br) b = np.concatenate((bu.array(),bp.array(),bb.array(),br.array()),axis = 0) return IO.arrayToVec(b)
ksp.solve(b,u) Soltime = time.time()- stime NSits += ksp.its # Mits +=dodim u = u*scale SolutionTime = SolutionTime +Soltime MO.PrintStr("Number of iterations ="+str(ksp.its),60,"+","\n\n","\n\n") u1, p1, b1, r1, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter, SaddlePoint = "Yes") p1.vector()[:] += - assemble(p1*dx)/assemble(ones*dx) u_k.assign(u1) p_k.assign(p1) b_k.assign(b1) r_k.assign(r1) uOld= np.concatenate((u_k.vector().array(),b_k.vector().array(),p_k.vector().array(),r_k.vector().array()), axis=0) x = IO.arrayToVec(uOld) #F = IO.matToSparse(HiptmairMatrices[6]).tocsr() #Finv = sp.linalg.inv(F) #Finv = PETSc.Mat().createAIJ(size=Finv.shape,csr=(Finv.indptr, Finv.indices, Finv.data)) #Ct = A.getSubMatrix(u_is,b_is) #C = A.getSubMatrix(b_is,u_is) #print Ct.size #Schur = A.getSubMatrix(u_is,u_is)-Ct*Finv*C Schur = pc.getPythonContext().ExactReturn() os.chdir(path) ShiftedMass = ShiftedMass.sparray() MO.StoreMatrix(ShiftedMass,"mass_"+str(iter)+"_"+str(nn)) MO.StoreMatrix(IO.matToSparse(Schur).tocsr(),"Schur_"+str(iter)+"_"+str(nn))
def foo(): m = 6 errL2u =np.zeros((m-1,1)) errH1u =np.zeros((m-1,1)) errL2p =np.zeros((m-1,1)) errL2b =np.zeros((m-1,1)) errCurlb =np.zeros((m-1,1)) errL2r =np.zeros((m-1,1)) errH1r =np.zeros((m-1,1)) l2uorder = np.zeros((m-1,1)) H1uorder =np.zeros((m-1,1)) l2porder = np.zeros((m-1,1)) l2border = np.zeros((m-1,1)) Curlborder =np.zeros((m-1,1)) l2rorder = np.zeros((m-1,1)) H1rorder = np.zeros((m-1,1)) NN = np.zeros((m-1,1)) DoF = np.zeros((m-1,1)) Velocitydim = np.zeros((m-1,1)) Magneticdim = np.zeros((m-1,1)) Pressuredim = np.zeros((m-1,1)) Lagrangedim = np.zeros((m-1,1)) Wdim = np.zeros((m-1,1)) iterations = np.zeros((m-1,1)) SolTime = np.zeros((m-1,1)) udiv = np.zeros((m-1,1)) MU = np.zeros((m-1,1)) level = np.zeros((m-1,1)) NSave = np.zeros((m-1,1)) Mave = np.zeros((m-1,1)) TotalTime = np.zeros((m-1,1)) nn = 2 dim = 2 ShowResultPlots = 'yes' split = 'Linear' MU[0]= 1e0 for xx in xrange(1,m): print xx level[xx-1] = xx + 0 nn = 2**(level[xx-1]) # Create mesh and define function space nn = int(nn) NN[xx-1] = nn/2 # parameters["form_compiler"]["quadrature_degree"] = 6 # parameters = CP.ParameterSetup() mesh = UnitSquareMesh(nn,nn) order = 2 parameters['reorder_dofs_serial'] = False Velocity = VectorFunctionSpace(mesh, "CG", order) Pressure = FunctionSpace(mesh, "CG", order-1) Magnetic = FunctionSpace(mesh, "N1curl", order-1) Lagrange = FunctionSpace(mesh, "CG", order-1) W = MixedFunctionSpace([Velocity, Pressure, Magnetic,Lagrange]) # W = Velocity*Pressure*Magnetic*Lagrange Velocitydim[xx-1] = Velocity.dim() Pressuredim[xx-1] = Pressure.dim() Magneticdim[xx-1] = Magnetic.dim() Lagrangedim[xx-1] = Lagrange.dim() Wdim[xx-1] = W.dim() print "\n\nW: ",Wdim[xx-1],"Velocity: ",Velocitydim[xx-1],"Pressure: ",Pressuredim[xx-1],"Magnetic: ",Magneticdim[xx-1],"Lagrange: ",Lagrangedim[xx-1],"\n\n" dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(), Lagrange.dim()] def boundary(x, on_boundary): return on_boundary u0, p0,b0, r0, Laplacian, Advection, gradPres,CurlCurl, gradR, NS_Couple, M_Couple = ExactSol.MHD2D(4,1, mesh) bcu = DirichletBC(Velocity,u0, boundary) bcb = DirichletBC(Magnetic,b0, boundary) bcr = DirichletBC(Lagrange,r0, boundary) # bc = [u0,p0,b0,r0] bcs = [bcu,bcb,bcr] FSpaces = [Velocity,Pressure,Magnetic,Lagrange] (u, b, p, r) = TrialFunctions(W) (v, c, q, s) = TestFunctions(W) kappa = 10.0 Mu_m =10.0 MU = 1.0/1 IterType = 'Full' Split = "No" Saddle = "No" Stokes = "No" SetupType = 'python-class' F_NS = -MU*Laplacian+Advection+gradPres-kappa*NS_Couple if kappa == 0: F_M = Mu_m*CurlCurl+gradR -kappa*M_Couple else: F_M = Mu_m*kappa*CurlCurl+gradR -kappa*M_Couple params = [kappa,Mu_m,MU] MO.PrintStr("Seting up initial guess matricies",2,"=","\n\n","\n") BCtime = time.time() BC = MHDsetup.BoundaryIndices(mesh) MO.StrTimePrint("BC index function, time: ", time.time()-BCtime) Hiptmairtol = 1e-4 HiptmairMatrices = PrecondSetup.MagneticSetup(Magnetic, Lagrange, b0, r0, Hiptmairtol, params) MO.PrintStr("Setting up MHD initial guess",5,"+","\n\n","\n\n") u_k,p_k,b_k,r_k = common.InitialGuess(FSpaces,[u0,p0,b0,r0],[F_NS,F_M],params,HiptmairMatrices,1e-10,Neumann=Expression(("0","0")),options ="New") b_t = TrialFunction(Velocity) c_t = TestFunction(Velocity) ones = Function(Pressure) ones.vector()[:]=(0*ones.vector().array()+1) # pConst = - assemble(p_k*dx)/assemble(ones*dx) p_k.vector()[:] += - assemble(p_k*dx)/assemble(ones*dx) x = Iter.u_prev(u_k,p_k,b_k,r_k) KSPlinearfluids, MatrixLinearFluids = PrecondSetup.FluidLinearSetup(Pressure, MU) kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) #plot(b_k) ns,maxwell,CoupleTerm,Lmaxwell,Lns = forms.MHD2D(mesh, W,F_M,F_NS, u_k,b_k,params,IterType,"CG",Saddle,Stokes) RHSform = forms.PicardRHS(mesh, W, u_k, p_k, b_k, r_k, params,"CG",Saddle,Stokes) bcu = DirichletBC(W.sub(0),Expression(("0.0","0.0")), boundary) bcb = DirichletBC(W.sub(2),Expression(("0.0","0.0")), boundary) bcr = DirichletBC(W.sub(3),Expression(("0.0")), boundary) bcs = [bcu,bcb,bcr] parameters['linear_algebra_backend'] = 'uBLAS' eps = 1.0 # error measure ||u-u_k|| tol = 1.0E-4 # tolerance iter = 0 # iteration counter maxiter = 10 # max no of iterations allowed SolutionTime = 0 outer = 0 # parameters['linear_algebra_backend'] = 'uBLAS' # FSpaces = [Velocity,Magnetic,Pressure,Lagrange] if IterType == "CD": MO.PrintStr("Setting up PETSc "+SetupType,2,"=","\n","\n") Alin = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "Linear",IterType) Fnlin,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType) A = Fnlin+Alin A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType) u = b.duplicate() u_is = PETSc.IS().createGeneral(range(Velocity.dim())) NS_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim())) M_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim(),W.dim())) OuterTol = 1e-5 InnerTol = 1e-5 NSits =0 Mits =0 TotalStart =time.time() SolutionTime = 0 while eps > tol and iter < maxiter: iter += 1 MO.PrintStr("Iter "+str(iter),7,"=","\n\n","\n\n") AssembleTime = time.time() if IterType == "CD": MO.StrTimePrint("MHD CD RHS assemble, time: ", time.time()-AssembleTime) b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "CD",IterType) else: MO.PrintStr("Setting up PETSc "+SetupType,2,"=","\n","\n") if Split == "Yes": if iter == 1: Alin = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "Linear",IterType) Fnlin,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType) A = Fnlin+Alin A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType) u = b.duplicate() else: Fnline,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType) A = Fnlin+Alin A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType) else: AA, bb = assemble_system(maxwell+ns+CoupleTerm, (Lmaxwell + Lns) - RHSform, bcs) A,b = CP.Assemble(AA,bb) # if iter == 1: MO.StrTimePrint("MHD total assemble, time: ", time.time()-AssembleTime) u = b.duplicate() kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) print "Inititial guess norm: ", u.norm(PETSc.NormType.NORM_INFINITY) #A,Q if IterType == 'Full': n = FacetNormal(mesh) mat = as_matrix([[b_k[1]*b_k[1],-b_k[1]*b_k[0]],[-b_k[1]*b_k[0],b_k[0]*b_k[0]]]) a = params[2]*inner(grad(b_t), grad(c_t))*dx(W.mesh()) + inner((grad(b_t)*u_k),c_t)*dx(W.mesh()) +(1./2)*div(u_k)*inner(c_t,b_t)*dx(W.mesh()) - (1./2)*inner(u_k,n)*inner(c_t,b_t)*ds(W.mesh())+kappa/Mu_m*inner(mat*b_t,c_t)*dx(W.mesh()) ShiftedMass = assemble(a) bcu.apply(ShiftedMass) S = ShiftedMass.sparray() ShiftedMass = CP.Assemble(ShiftedMass) kspF = NSprecondSetup.LSCKSPnonlinear(ShiftedMass) else: F = A.getSubMatrix(u_is,u_is) kspF = NSprecondSetup.LSCKSPnonlinear(F) p = TrialFunction(Pressure) q = TestFunction(Pressure) Xs = assemble(p*q*dx) Xs = CP.Assemble(Xs) n = FacetNormal(mesh) Fp = assemble(inner(grad(q), grad(p))*dx(mesh)+inner((u_k[0]*grad(p)[0]+u_k[1]*grad(p)[1]),q)*dx(mesh) + (1./2)*div(u_k)*inner(p,q)*dx(mesh) - (1./2)*(u_k[0]*n[0]+u_k[1]*n[1])*inner(p,q)*ds(mesh)+p*q*dx ) Fp = CP.Assemble(Fp) # Bt = assemble(div(b_t)*q*dx).sparray() # IS = MO.IndexSet(W) # # Bt = A.getSubMatrix(IS[1],IS[0]) # # Bt = PETSc2Scipy(Bt) # # BFsB = Scipy2PETSc(Bt*sp.linalg.inv(S)*Bt.T) # X = assemble(inner(c_t,b_t)*dx) # bcu.apply(X) # X = X.sparray() # # print Bt*sp.diags(1/X.diagonal(),0)*S*sp.diags(1/X.diagonal(),0)*Bt.T # FF = Scipy2PETSc(Bt*sp.diags(1/X.diagonal(),0)*S*sp.diags(1/X.diagonal(),0)*Bt.T) # LL = Scipy2PETSc(Bt*sp.diags(1/X.diagonal(),0)*Bt.T) kspBFsB = PETSc.KSP() kspBFsB.create(comm=PETSc.COMM_WORLD) pcBFsB = kspBFsB.getPC() kspBFsB.setType('preonly') pcBFsB.setType('cholesky') kspBFsB.setOperators(Xs,Xs) OptDB = PETSc.Options() OptDB["pc_factor_mat_ordering_type"] = "rcm" OptDB["pc_factor_mat_solver_package"] = "mumps" kspBFsB.setFromOptions() kspMX = PETSc.KSP() kspMX.create(comm=PETSc.COMM_WORLD) pcMX = kspMX.getPC() kspMX.setType('preonly') pcMX.setType('lu') kspMX.setOperators(HiptmairMatrices[6],HiptmairMatrices[6]) OptDB = PETSc.Options() OptDB["pc_factor_mat_ordering_type"] = "rcm" OptDB["pc_factor_mat_solver_package"] = "mumps" kspMX.setFromOptions() stime = time.time() ksp = PETSc.KSP() ksp.create(comm=PETSc.COMM_WORLD) pc = ksp.getPC() ksp.setType('gmres') pc.setType('python') ksp.setTolerances(1e-6) pc.setType(PETSc.PC.Type.PYTHON) OptDB = PETSc.Options() OptDB['ksp_gmres_restart'] = 200 reshist = {} def monitor(ksp, its, fgnorm): reshist[its] = fgnorm print its," OUTER:", fgnorm ksp.max_it = 1000 # ksp.setFromOptions() pc.setPythonContext(MHDpreconditioner.ApproxInverse( W, kspF, kspBFsB, kspMX,HiptmairMatrices[3], Fp)) scale = b.norm() b = b/scale ksp.setOperators(A,A) del A ksp.solve(b,u) u = u*scale # print b.array MO.PrintStr("Number iterations = "+str(ksp.its),60,"+","\n\n","\n\n") Soltime = time.time()- stime MO.StrTimePrint("MHD solve, time: ", Soltime) SolutionTime += Soltime Mits += ksp.its u1, p1, b1, r1, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter) p1.vector()[:] += - assemble(p1*dx)/assemble(ones*dx) u_k.assign(u1) p_k.assign(p1) b_k.assign(b1) r_k.assign(r1) uOld= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0) x = IO.arrayToVec(uOld) XX= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0) SolTime[xx-1] = SolutionTime/iter NSave[xx-1] = (float(NSits)/iter) Mave[xx-1] = (float(Mits)/iter) iterations[xx-1] = iter TotalTime[xx-1] = time.time() - TotalStart dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(),Lagrange.dim()] ExactSolution = [u0,p0,b0,r0] errL2u[xx-1], errH1u[xx-1], errL2p[xx-1], errL2b[xx-1], errCurlb[xx-1], errL2r[xx-1], errH1r[xx-1] = Iter.Errors(XX,mesh,FSpaces,ExactSolution,order,dim, "DG") if xx > 1: l2uorder[xx-1] = np.abs(np.log2(errL2u[xx-2]/errL2u[xx-1])) H1uorder[xx-1] = np.abs(np.log2(errH1u[xx-2]/errH1u[xx-1])) l2porder[xx-1] = np.abs(np.log2(errL2p[xx-2]/errL2p[xx-1])) l2border[xx-1] = np.abs(np.log2(errL2b[xx-2]/errL2b[xx-1])) Curlborder[xx-1] = np.abs(np.log2(errCurlb[xx-2]/errCurlb[xx-1])) l2rorder[xx-1] = np.abs(np.log2(errL2r[xx-2]/errL2r[xx-1])) H1rorder[xx-1] = np.abs(np.log2(errH1r[xx-2]/errH1r[xx-1])) import pandas as pd LatexTitles = ["l","DoFu","Dofp","V-L2","L2-order","V-H1","H1-order","P-L2","PL2-order"] LatexValues = np.concatenate((level,Velocitydim,Pressuredim,errL2u,l2uorder,errH1u,H1uorder,errL2p,l2porder), axis=1) LatexTable = pd.DataFrame(LatexValues, columns = LatexTitles) pd.set_option('precision',3) LatexTable = MO.PandasFormat(LatexTable,"V-L2","%2.4e") LatexTable = MO.PandasFormat(LatexTable,'V-H1',"%2.4e") LatexTable = MO.PandasFormat(LatexTable,"H1-order","%1.2f") LatexTable = MO.PandasFormat(LatexTable,'L2-order',"%1.2f") LatexTable = MO.PandasFormat(LatexTable,"P-L2","%2.4e") LatexTable = MO.PandasFormat(LatexTable,'PL2-order',"%1.2f") print LatexTable print "\n\n Magnetic convergence" MagneticTitles = ["l","B DoF","R DoF","B-L2","L2-order","B-Curl","HCurl-order"] MagneticValues = np.concatenate((level,Magneticdim,Lagrangedim,errL2b,l2border,errCurlb,Curlborder),axis=1) MagneticTable= pd.DataFrame(MagneticValues, columns = MagneticTitles) pd.set_option('precision',3) MagneticTable = MO.PandasFormat(MagneticTable,"B-Curl","%2.4e") MagneticTable = MO.PandasFormat(MagneticTable,'B-L2',"%2.4e") MagneticTable = MO.PandasFormat(MagneticTable,"L2-order","%1.2f") MagneticTable = MO.PandasFormat(MagneticTable,'HCurl-order',"%1.2f") print MagneticTable print "\n\n Lagrange convergence" LagrangeTitles = ["l","B DoF","R DoF","R-L2","L2-order","R-H1","H1-order"] LagrangeValues = np.concatenate((level,Lagrangedim,Lagrangedim,errL2r,l2rorder,errH1r,H1rorder),axis=1) LagrangeTable= pd.DataFrame(LagrangeValues, columns = LagrangeTitles) pd.set_option('precision',3) LagrangeTable = MO.PandasFormat(LagrangeTable,"R-L2","%2.4e") LagrangeTable = MO.PandasFormat(LagrangeTable,'R-H1',"%2.4e") LagrangeTable = MO.PandasFormat(LagrangeTable,"L2-order","%1.2f") LagrangeTable = MO.PandasFormat(LagrangeTable,'H1-order',"%1.2f") print LagrangeTable import pandas as pd print "\n\n Iteration table" if IterType == "Full": IterTitles = ["l","DoF","AV solve Time","Total picard time","picard iterations","Av Outer its","Av Inner its",] else: IterTitles = ["l","DoF","AV solve Time","Total picard time","picard iterations","Av NS iters","Av M iters"] IterValues = np.concatenate((level,Wdim,SolTime,TotalTime,iterations,Mave,NSave),axis=1) IterTable= pd.DataFrame(IterValues, columns = IterTitles) if IterType == "Full": IterTable = MO.PandasFormat(IterTable,'Av Outer its',"%2.1f") IterTable = MO.PandasFormat(IterTable,'Av Inner its',"%2.1f") else: IterTable = MO.PandasFormat(IterTable,'Av NS iters',"%2.1f") IterTable = MO.PandasFormat(IterTable,'Av M iters',"%2.1f") print IterTable print " \n Outer Tol: ",OuterTol, "Inner Tol: ", InnerTol # tableName = "2d_nu="+str(MU)+"_nu_m="+str(Mu_m)+"_kappa="+str(kappa)+"_l="+str(np.min(level))+"-"+str(np.max(level))+".tex" # IterTable.to_latex(tableName) # # # if (ShowResultPlots == 'yes'): # plot(u_k) # plot(interpolate(u0,Velocity)) # # plot(p_k) # # plot(interpolate(p0,Pressure)) # # plot(b_k) # plot(interpolate(b0,Magnetic)) # # plot(r_k) # plot(interpolate(r0,Lagrange)) # # interactive() interactive()
def PicardToleranceDecouple(x,U,FSpaces,dim,NormType,iter,SaddlePoint = "No"): X = IO.vecToArray(x) uu = X[0:dim[0]] if SaddlePoint == "Yes": bb = X[dim[0]:dim[0]+dim[1]] pp = X[dim[0]+dim[1]:dim[0]+dim[1]+dim[2]] else: pp = X[dim[0]:dim[0]+dim[1]] bb = X[dim[0]+dim[1]:dim[0]+dim[1]+dim[2]] rr = X[dim[0]+dim[1]+dim[2]:] u = Function(FSpaces[0]) u.vector()[:] = uu u_ = assemble(inner(u,u)*dx) diffu = u.vector().array() # if SaddlePoint == "Yes": # p = Function(FSpaces[2]) # p.vector()[:] = pp # ones = Function(FSpaces[2]) # ones.vector()[:]=(0*ones.vector().array()+1) # pp = Function(FSpaces[2]) # print ones # pp.vector()[:] = p.vector().array()- assemble(p*dx)/assemble(ones*dx) # p = pp.vector().array() # b = Function(FSpaces[1]) # b.vector()[:] = bb # diffb = b.vector().array() # else: print pp.shape p = Function(FSpaces[1]) print FSpaces[1].dim() p.vector()[:] = pp p_ = assemble(p*p*dx) ones = Function(FSpaces[1]) ones.vector()[:]=(0*ones.vector().array()+1) pp = Function(FSpaces[1]) pp.vector()[:] = p.vector().array() - assemble(p*dx)/assemble(ones*dx) p_ = assemble(pp*pp*dx) p = pp.vector().array() b = Function(FSpaces[2]) b.vector()[:] = bb b_ = assemble(inner(b,b)*dx) diffb = b.vector().array() r = Function(FSpaces[3]) r.vector()[:] = rr r_ = assemble(r*r*dx) # print diffu if (NormType == '2'): epsu = splin.norm(diffu)/sqrt(dim[0]) epsp = splin.norm(pp.vector().array())/sqrt(dim[1]) epsb = splin.norm(diffb)/sqrt(dim[2]) epsr = splin.norm(r.vector().array())/sqrt(dim[3]) elif (NormType == 'inf'): epsu = splin.norm(diffu, ord=np.Inf) epsp = splin.norm(pp.vector().array(),ord=np.inf) epsb = splin.norm(diffb, ord=np.Inf) epsr = splin.norm(r.vector().array(),ord=np.inf) else: print "NormType must be 2 or inf" quit() # U.axpy(1,x) p = Function(FSpaces[1]) RHS = IO.vecToArray(U+x) if SaddlePoint == "Yes": u.vector()[:] = RHS[0:dim[0]] p.vector()[:] = pp.vector().array()+U.array[dim[0]+dim[1]:dim[0]+dim[1]+dim[2]] b.vector()[:] = RHS[dim[0]:dim[0]+dim[1]] r.vector()[:] = RHS[dim[0]+dim[1]+dim[2]:] else: u.vector()[:] = RHS[0:dim[0]] p.vector()[:] = pp.vector().array()+U.array[dim[0]:dim[0]+dim[1]] b.vector()[:] = RHS[dim[0]+dim[1]:dim[0]+dim[1]+dim[2]] r.vector()[:] = RHS[dim[0]+dim[1]+dim[2]:] # print diffu.dot(diffu) + pp.dot(pp) + diffb.dot(diffb) + r.dot(r) # epsu = sqrt(u_)/sqrt(dim[0]) # epsp = sqrt(p_)/sqrt(dim[1]) # epsb = sqrt(b_)/sqrt(dim[2]) # epsr = sqrt(r_)/sqrt(dim[3]) # uOld = np.concatenate((diffu, pp.vector().array(), diffb, r.vector().array()), axis=0) # print np.linalg.norm(uOld)/sum(dim) print 'u-norm=%g p-norm=%g \n b-norm=%g r-norm=%g' % (epsu,epsp,epsb,epsr), '\n\n\n' print 'u-norm=%g p-norm=%g \n b-norm=%g r-norm=%g' % (sqrt(u_), sqrt(p_), sqrt(b_), sqrt(r_)), '\n\n\n' return u,p,b,r,epsu+epsp+epsb+epsr
maxiter = 100 # max no of iterations allowed while eps > tol and iter < maxiter: iter += 1 x = Function(W) uu = Function(W) tic() AA, bb = assemble_system(a, L1, bcs) A = as_backend_type(AA).mat() print toc() b = bb.array() zeros = 0*b bb = IO.arrayToVec(b) x = IO.arrayToVec(zeros) tic() u_is = PETSc.IS().createGeneral(range(V.dim())) p_is = PETSc.IS().createGeneral(range(V.dim(),V.dim()+Q.dim())) ksp = PETSc.KSP().create() ksp.setOperators(A,A) ksp.setTolerances(1e-6) ksp.setType('gmres') pc = ksp.getPC() pc.setType(pc.Type.FIELDSPLIT) fields = [ ("field1", u_is), ("field2", p_is)] pc.setFieldSplitIS(*fields) pc.setFieldSplitType(0)
def u_prev(u,p,b,r): uOld = np.concatenate((u.vector().array(),p.vector().array(),b.vector().array(),r.vector().array()), axis=0) x = IO.arrayToVec(uOld) return x
iter = 0 # iteration counter maxiter = 100 # max no of iterations allowed while eps > tol and iter < maxiter: iter += 1 x = Function(W) uu = Function(W) tic() AA, bb = assemble_system(a, L1, bcs) A = as_backend_type(AA).mat() print toc() b = bb.array() zeros = 0 * b bb = IO.arrayToVec(b) x = IO.arrayToVec(zeros) tic() u_is = PETSc.IS().createGeneral(range(V.dim())) p_is = PETSc.IS().createGeneral(range(V.dim(), V.dim() + Q.dim())) ksp = PETSc.KSP().create() ksp.setOperators(A, A) ksp.setTolerances(1e-6) ksp.setType('gmres') pc = ksp.getPC() pc.setType(pc.Type.FIELDSPLIT) fields = [("field1", u_is), ("field2", p_is)] pc.setFieldSplitIS(*fields) pc.setFieldSplitType(0)
def foo(): m = 6 errL2u =np.zeros((m-1,1)) errH1u =np.zeros((m-1,1)) errL2p =np.zeros((m-1,1)) errL2b =np.zeros((m-1,1)) errCurlb =np.zeros((m-1,1)) errL2r =np.zeros((m-1,1)) errH1r =np.zeros((m-1,1)) l2uorder = np.zeros((m-1,1)) H1uorder =np.zeros((m-1,1)) l2porder = np.zeros((m-1,1)) l2border = np.zeros((m-1,1)) Curlborder =np.zeros((m-1,1)) l2rorder = np.zeros((m-1,1)) H1rorder = np.zeros((m-1,1)) NN = np.zeros((m-1,1)) DoF = np.zeros((m-1,1)) Velocitydim = np.zeros((m-1,1)) Magneticdim = np.zeros((m-1,1)) Pressuredim = np.zeros((m-1,1)) Lagrangedim = np.zeros((m-1,1)) Wdim = np.zeros((m-1,1)) iterations = np.zeros((m-1,1)) SolTime = np.zeros((m-1,1)) udiv = np.zeros((m-1,1)) MU = np.zeros((m-1,1)) level = np.zeros((m-1,1)) NSave = np.zeros((m-1,1)) Mave = np.zeros((m-1,1)) TotalTime = np.zeros((m-1,1)) nn = 2 dim = 2 ShowResultPlots = 'yes' split = 'Linear' MU[0]= 1e0 for xx in xrange(1,m): print xx level[xx-1] = xx+ 0 nn = 2**(level[xx-1]) # Create mesh and define function space nn = int(nn) NN[xx-1] = nn/2 # parameters["form_compiler"]["quadrature_degree"] = 6 # parameters = CP.ParameterSetup() mesh = UnitCubeMesh(nn,nn,nn) order = 2 parameters['reorder_dofs_serial'] = False Velocity = VectorFunctionSpace(mesh, "CG", order) Pressure = FunctionSpace(mesh, "CG", order-1) Magnetic = FunctionSpace(mesh, "N1curl", order) Lagrange = FunctionSpace(mesh, "CG", order) W = MixedFunctionSpace([Velocity, Pressure, Magnetic,Lagrange]) # W = Velocity*Pressure*Magnetic*Lagrange Velocitydim[xx-1] = Velocity.dim() Pressuredim[xx-1] = Pressure.dim() Magneticdim[xx-1] = Magnetic.dim() Lagrangedim[xx-1] = Lagrange.dim() Wdim[xx-1] = W.dim() print "\n\nW: ",Wdim[xx-1],"Velocity: ",Velocitydim[xx-1],"Pressure: ",Pressuredim[xx-1],"Magnetic: ",Magneticdim[xx-1],"Lagrange: ",Lagrangedim[xx-1],"\n\n" dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(), Lagrange.dim()] def boundary(x, on_boundary): return on_boundary u0, p0,b0, r0, Laplacian, Advection, gradPres,CurlCurl, gradR, NS_Couple, M_Couple = ExactSol.MHD3D(4,1) bcu = DirichletBC(Velocity,u0, boundary) bcb = DirichletBC(Magnetic,b0, boundary) bcr = DirichletBC(Lagrange,r0, boundary) # bc = [u0,p0,b0,r0] bcs = [bcu,bcb,bcr] FSpaces = [Velocity,Pressure,Magnetic,Lagrange] (u, b, p, r) = TrialFunctions(W) (v, c, q, s) = TestFunctions(W) kappa = 1.0 Mu_m =10.0 MU = 1.0/1 IterType = 'Full' Split = "No" Saddle = "No" Stokes = "No" SetupType = 'python-class' F_NS = -MU*Laplacian+Advection+gradPres-kappa*NS_Couple if kappa == 0: F_M = Mu_m*CurlCurl+gradR -kappa*M_Couple else: F_M = Mu_m*kappa*CurlCurl+gradR -kappa*M_Couple params = [kappa,Mu_m,MU] MO.PrintStr("Seting up initial guess matricies",2,"=","\n\n","\n") BCtime = time.time() BC = MHDsetup.BoundaryIndices(mesh) MO.StrTimePrint("BC index function, time: ", time.time()-BCtime) Hiptmairtol = 1e-5 HiptmairMatrices = PrecondSetup.MagneticSetup(Magnetic, Lagrange, b0, r0, Hiptmairtol, params) MO.PrintStr("Setting up MHD initial guess",5,"+","\n\n","\n\n") u_k,p_k,b_k,r_k = common.InitialGuess(FSpaces,[u0,p0,b0,r0],[F_NS,F_M],params,HiptmairMatrices,1e-10,Neumann=Expression(("0","0")),options ="New") b_t = TrialFunction(Velocity) c_t = TestFunction(Velocity) ones = Function(Pressure) ones.vector()[:]=(0*ones.vector().array()+1) # pConst = - assemble(p_k*dx)/assemble(ones*dx) p_k.vector()[:] += - assemble(p_k*dx)/assemble(ones*dx) x = Iter.u_prev(u_k,p_k,b_k,r_k) KSPlinearfluids, MatrixLinearFluids = PrecondSetup.FluidLinearSetup(Pressure, MU) kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) #plot(b_k) ns,maxwell,CoupleTerm,Lmaxwell,Lns = forms.MHD2D(mesh, W,F_M,F_NS, u_k,b_k,params,IterType,"CG",Saddle,Stokes) RHSform = forms.PicardRHS(mesh, W, u_k, p_k, b_k, r_k, params,"CG",Saddle,Stokes) bcu = DirichletBC(W.sub(0),Expression(("0.0","0.0","0.0")), boundary) bcb = DirichletBC(W.sub(2),Expression(("0.0","0.0","0.0")), boundary) bcr = DirichletBC(W.sub(3),Expression(("0.0")), boundary) bcs = [bcu,bcb,bcr] parameters['linear_algebra_backend'] = 'uBLAS' eps = 1.0 # error measure ||u-u_k|| tol = 1.0E-4 # tolerance iter = 0 # iteration counter maxiter = 10 # max no of iterations allowed SolutionTime = 0 outer = 0 # parameters['linear_algebra_backend'] = 'uBLAS' # FSpaces = [Velocity,Magnetic,Pressure,Lagrange] if IterType == "CD": MO.PrintStr("Setting up PETSc "+SetupType,2,"=","\n","\n") Alin = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "Linear",IterType) Fnlin,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType) A = Fnlin+Alin A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType) u = b.duplicate() u_is = PETSc.IS().createGeneral(range(Velocity.dim())) NS_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim())) M_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim(),W.dim())) OuterTol = 1e-5 InnerTol = 1e-5 NSits =0 Mits =0 TotalStart =time.time() SolutionTime = 0 while eps > tol and iter < maxiter: iter += 1 MO.PrintStr("Iter "+str(iter),7,"=","\n\n","\n\n") AssembleTime = time.time() if IterType == "CD": MO.StrTimePrint("MHD CD RHS assemble, time: ", time.time()-AssembleTime) b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "CD",IterType) else: MO.PrintStr("Setting up PETSc "+SetupType,2,"=","\n","\n") if Split == "Yes": if iter == 1: Alin = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "Linear",IterType) Fnlin,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType) A = Fnlin+Alin A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType) u = b.duplicate() else: Fnline,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType) A = Fnlin+Alin A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType) else: AA, bb = assemble_system(maxwell+ns+CoupleTerm, (Lmaxwell + Lns) - RHSform, bcs) A,b = CP.Assemble(AA,bb) # if iter == 1: MO.StrTimePrint("MHD total assemble, time: ", time.time()-AssembleTime) u = b.duplicate() kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) print "Inititial guess norm: ", u.norm(PETSc.NormType.NORM_INFINITY) #A,Q if IterType == 'Full': n = FacetNormal(mesh) mat = as_matrix([[b_k[2]*b_k[2]+b[1]*b[1],-b_k[1]*b_k[0],-b_k[0]*b_k[2]], [-b_k[1]*b_k[0],b_k[0]*b_k[0]+b_k[2]*b_k[2],-b_k[2]*b_k[1]], [-b_k[0]*b_k[2],-b_k[1]*b_k[2],b_k[0]*b_k[0]+b_k[1]*b_k[1]]]) a = params[2]*inner(grad(b_t), grad(c_t))*dx(W.mesh()) + inner((grad(b_t)*u_k),c_t)*dx(W.mesh()) +(1./2)*div(u_k)*inner(c_t,b_t)*dx(W.mesh()) - (1./2)*inner(u_k,n)*inner(c_t,b_t)*ds(W.mesh())+kappa/Mu_m*inner(mat*b_t,c_t)*dx(W.mesh()) ShiftedMass = assemble(a) bcu.apply(ShiftedMass) ShiftedMass = CP.Assemble(ShiftedMass) kspF = NSprecondSetup.LSCKSPnonlinear(ShiftedMass) else: F = A.getSubMatrix(u_is,u_is) kspF = NSprecondSetup.LSCKSPnonlinear(F) stime = time.time() u, mits,nsits = S.solve(A,b,u,params,W,'Directclase',IterType,OuterTol,InnerTol,HiptmairMatrices,Hiptmairtol,KSPlinearfluids, Fp,kspF) Soltime = time.time()- stime MO.StrTimePrint("MHD solve, time: ", Soltime) Mits += mits NSits += nsits SolutionTime += Soltime u1, p1, b1, r1, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter) p1.vector()[:] += - assemble(p1*dx)/assemble(ones*dx) u_k.assign(u1) p_k.assign(p1) b_k.assign(b1) r_k.assign(r1) uOld= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0) x = IO.arrayToVec(uOld) XX= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0) SolTime[xx-1] = SolutionTime/iter NSave[xx-1] = (float(NSits)/iter) Mave[xx-1] = (float(Mits)/iter) iterations[xx-1] = iter TotalTime[xx-1] = time.time() - TotalStart # dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(),Lagrange.dim()] # # ExactSolution = [u0,p0,b0,r0] # errL2u[xx-1], errH1u[xx-1], errL2p[xx-1], errL2b[xx-1], errCurlb[xx-1], errL2r[xx-1], errH1r[xx-1] = Iter.Errors(XX,mesh,FSpaces,ExactSolution,order,dim, "DG") # # if xx > 1: # l2uorder[xx-1] = np.abs(np.log2(errL2u[xx-2]/errL2u[xx-1])) # H1uorder[xx-1] = np.abs(np.log2(errH1u[xx-2]/errH1u[xx-1])) # # l2porder[xx-1] = np.abs(np.log2(errL2p[xx-2]/errL2p[xx-1])) # # l2border[xx-1] = np.abs(np.log2(errL2b[xx-2]/errL2b[xx-1])) # Curlborder[xx-1] = np.abs(np.log2(errCurlb[xx-2]/errCurlb[xx-1])) # # l2rorder[xx-1] = np.abs(np.log2(errL2r[xx-2]/errL2r[xx-1])) # H1rorder[xx-1] = np.abs(np.log2(errH1r[xx-2]/errH1r[xx-1])) # # # # # import pandas as pd # # # # LatexTitles = ["l","DoFu","Dofp","V-L2","L2-order","V-H1","H1-order","P-L2","PL2-order"] # LatexValues = np.concatenate((level,Velocitydim,Pressuredim,errL2u,l2uorder,errH1u,H1uorder,errL2p,l2porder), axis=1) # LatexTable = pd.DataFrame(LatexValues, columns = LatexTitles) # pd.set_option('precision',3) # LatexTable = MO.PandasFormat(LatexTable,"V-L2","%2.4e") # LatexTable = MO.PandasFormat(LatexTable,'V-H1',"%2.4e") # LatexTable = MO.PandasFormat(LatexTable,"H1-order","%1.2f") # LatexTable = MO.PandasFormat(LatexTable,'L2-order',"%1.2f") # LatexTable = MO.PandasFormat(LatexTable,"P-L2","%2.4e") # LatexTable = MO.PandasFormat(LatexTable,'PL2-order',"%1.2f") # print LatexTable # # # print "\n\n Magnetic convergence" # MagneticTitles = ["l","B DoF","R DoF","B-L2","L2-order","B-Curl","HCurl-order"] # MagneticValues = np.concatenate((level,Magneticdim,Lagrangedim,errL2b,l2border,errCurlb,Curlborder),axis=1) # MagneticTable= pd.DataFrame(MagneticValues, columns = MagneticTitles) # pd.set_option('precision',3) # MagneticTable = MO.PandasFormat(MagneticTable,"B-Curl","%2.4e") # MagneticTable = MO.PandasFormat(MagneticTable,'B-L2',"%2.4e") # MagneticTable = MO.PandasFormat(MagneticTable,"L2-order","%1.2f") # MagneticTable = MO.PandasFormat(MagneticTable,'HCurl-order',"%1.2f") # print MagneticTable import pandas as pd print "\n\n Iteration table" if IterType == "Full": IterTitles = ["l","DoF","AV solve Time","Total picard time","picard iterations","Av Outer its","Av Inner its",] else: IterTitles = ["l","DoF","AV solve Time","Total picard time","picard iterations","Av NS iters","Av M iters"] IterValues = np.concatenate((level,Wdim,SolTime,TotalTime,iterations,Mave,NSave),axis=1) IterTable= pd.DataFrame(IterValues, columns = IterTitles) if IterType == "Full": IterTable = MO.PandasFormat(IterTable,'Av Outer its',"%2.1f") IterTable = MO.PandasFormat(IterTable,'Av Inner its',"%2.1f") else: IterTable = MO.PandasFormat(IterTable,'Av NS iters',"%2.1f") IterTable = MO.PandasFormat(IterTable,'Av M iters',"%2.1f") print IterTable print " \n Outer Tol: ",OuterTol, "Inner Tol: ", InnerTol IterTable.to_latex("3d.tex") # # # if (ShowResultPlots == 'yes'): # plot(u_k) # plot(interpolate(u0,Velocity)) # # plot(p_k) # # plot(interpolate(p0,Pressure)) # # plot(b_k) # plot(interpolate(b0,Magnetic)) # # plot(r_k) # plot(interpolate(r0,Lagrange)) # # interactive() interactive()
def FuncToPETSc(x): return IO.arrayToVec(x.vector().array())
def foo(): m = 6 errL2u = np.zeros((m - 1, 1)) errH1u = np.zeros((m - 1, 1)) errL2p = np.zeros((m - 1, 1)) errL2b = np.zeros((m - 1, 1)) errCurlb = np.zeros((m - 1, 1)) errL2r = np.zeros((m - 1, 1)) errH1r = np.zeros((m - 1, 1)) l2uorder = np.zeros((m - 1, 1)) H1uorder = np.zeros((m - 1, 1)) l2porder = np.zeros((m - 1, 1)) l2border = np.zeros((m - 1, 1)) Curlborder = np.zeros((m - 1, 1)) l2rorder = np.zeros((m - 1, 1)) H1rorder = np.zeros((m - 1, 1)) NN = np.zeros((m - 1, 1)) DoF = np.zeros((m - 1, 1)) Velocitydim = np.zeros((m - 1, 1)) Magneticdim = np.zeros((m - 1, 1)) Pressuredim = np.zeros((m - 1, 1)) Lagrangedim = np.zeros((m - 1, 1)) Wdim = np.zeros((m - 1, 1)) iterations = np.zeros((m - 1, 1)) SolTime = np.zeros((m - 1, 1)) udiv = np.zeros((m - 1, 1)) MU = np.zeros((m - 1, 1)) level = np.zeros((m - 1, 1)) NSave = np.zeros((m - 1, 1)) Mave = np.zeros((m - 1, 1)) TotalTime = np.zeros((m - 1, 1)) nn = 2 dim = 2 ShowResultPlots = 'yes' split = 'Linear' kappa = 0.01 for yy in xrange(1, 5): kappa = kappa * 10 for xx in xrange(1, m): print xx level[xx - 1] = xx + 2 nn = 2**(level[xx - 1]) # Create mesh and define function space nn = int(nn) NN[xx - 1] = nn / 2 # parameters["form_compiler"]["quadrature_degree"] = 6 # parameters = CP.ParameterSetup() mesh = UnitSquareMesh(nn, nn) order = 1 parameters['reorder_dofs_serial'] = False Velocity = VectorFunctionSpace(mesh, "CG", order) Pressure = FunctionSpace(mesh, "DG", order - 1) Magnetic = FunctionSpace(mesh, "N1curl", order) Lagrange = FunctionSpace(mesh, "CG", order) W = MixedFunctionSpace([Velocity, Pressure, Magnetic, Lagrange]) # W = Velocity*Pressure*Magnetic*Lagrange Velocitydim[xx - 1] = Velocity.dim() Pressuredim[xx - 1] = Pressure.dim() Magneticdim[xx - 1] = Magnetic.dim() Lagrangedim[xx - 1] = Lagrange.dim() Wdim[xx - 1] = W.dim() print "\n\nW: ", Wdim[xx - 1], "Velocity: ", Velocitydim[ xx - 1], "Pressure: ", Pressuredim[ xx - 1], "Magnetic: ", Magneticdim[ xx - 1], "Lagrange: ", Lagrangedim[xx - 1], "\n\n" dim = [ Velocity.dim(), Pressure.dim(), Magnetic.dim(), Lagrange.dim() ] def boundary(x, on_boundary): return on_boundary u0, p0, b0, r0, Laplacian, Advection, gradPres, CurlCurl, gradR, NS_Couple, M_Couple = ExactSol.MHD2D( 4, 1) bcu = DirichletBC(W.sub(0), u0, boundary) bcb = DirichletBC(W.sub(2), b0, boundary) bcr = DirichletBC(W.sub(3), r0, boundary) # bc = [u0,p0,b0,r0] bcs = [bcu, bcb, bcr] FSpaces = [Velocity, Pressure, Magnetic, Lagrange] (u, b, p, r) = TrialFunctions(W) (v, c, q, s) = TestFunctions(W) #kappa = 1.0 MU = 1.0 Mu_m = 1e1 IterType = 'Combined' F_NS = -MU * Laplacian + Advection + gradPres - kappa * NS_Couple if kappa == 0: F_M = Mu_m * CurlCurl + gradR - kappa * M_Couple else: F_M = Mu_m * kappa * CurlCurl + gradR - kappa * M_Couple params = [kappa, Mu_m, MU] # MO.PrintStr("Preconditioning MHD setup",5,"+","\n\n","\n\n") Hiptmairtol = 1e-5 HiptmairMatrices = PrecondSetup.MagneticSetup( Magnetic, Lagrange, b0, r0, Hiptmairtol, params) MO.PrintStr("Setting up MHD initial guess", 5, "+", "\n\n", "\n\n") u_k, p_k, b_k, r_k = common.InitialGuess(FSpaces, [u0, p0, b0, r0], [F_NS, F_M], params, HiptmairMatrices, 1e-6, Neumann=Expression( ("0", "0")), options="New", FS="DG") #plot(p_k, interactive = True) b_t = TrialFunction(Velocity) c_t = TestFunction(Velocity) #print assemble(inner(b,c)*dx).array().shape #print mat #ShiftedMass = assemble(inner(mat*b,c)*dx) #as_vector([inner(b,c)[0]*b_k[0],inner(b,c)[1]*(-b_k[1])]) ones = Function(Pressure) ones.vector()[:] = (0 * ones.vector().array() + 1) # pConst = - assemble(p_k*dx)/assemble(ones*dx) p_k.vector()[:] += -assemble(p_k * dx) / assemble(ones * dx) x = Iter.u_prev(u_k, p_k, b_k, r_k) KSPlinearfluids, MatrixLinearFluids = PrecondSetup.FluidLinearSetup( Pressure, MU) kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) #plot(b_k) ns, maxwell, CoupleTerm, Lmaxwell, Lns = forms.MHD2D( mesh, W, F_M, F_NS, u_k, b_k, params, IterType, "DG") RHSform = forms.PicardRHS(mesh, W, u_k, p_k, b_k, r_k, params, "DG") bcu = DirichletBC(W.sub(0), Expression(("0.0", "0.0")), boundary) bcb = DirichletBC(W.sub(2), Expression(("0.0", "0.0")), boundary) bcr = DirichletBC(W.sub(3), Expression(("0.0")), boundary) bcs = [bcu, bcb, bcr] eps = 1.0 # error measure ||u-u_k|| tol = 1.0E-4 # tolerance iter = 0 # iteration counter maxiter = 40 # max no of iterations allowed SolutionTime = 0 outer = 0 # parameters['linear_algebra_backend'] = 'uBLAS' # FSpaces = [Velocity,Magnetic,Pressure,Lagrange] if IterType == "CD": AA, bb = assemble_system(maxwell + ns, (Lmaxwell + Lns) - RHSform, bcs) A, b = CP.Assemble(AA, bb) # u = b.duplicate() # P = CP.Assemble(PP) u_is = PETSc.IS().createGeneral(range(Velocity.dim())) NS_is = PETSc.IS().createGeneral( range(Velocity.dim() + Pressure.dim())) M_is = PETSc.IS().createGeneral( range(Velocity.dim() + Pressure.dim(), W.dim())) OuterTol = 1e-5 InnerTol = 1e-5 NSits = 0 Mits = 0 TotalStart = time.time() SolutionTime = 0 while eps > tol and iter < maxiter: iter += 1 MO.PrintStr("Iter " + str(iter), 7, "=", "\n\n", "\n\n") tic() if IterType == "CD": bb = assemble((Lmaxwell + Lns) - RHSform) for bc in bcs: bc.apply(bb) FF = AA.sparray()[0:dim[0], 0:dim[0]] A, b = CP.Assemble(AA, bb) # if iter == 1 if iter == 1: u = b.duplicate() F = A.getSubMatrix(u_is, u_is) kspF = NSprecondSetup.LSCKSPnonlinear(F) else: AA, bb = assemble_system(maxwell + ns + CoupleTerm, (Lmaxwell + Lns) - RHSform, bcs) A, b = CP.Assemble(AA, bb) # if iter == 1: if iter == 1: u = b.duplicate() print("{:40}").format("MHD assemble, time: "), " ==> ", ( "{:4f}").format( toc()), ("{:9}").format(" time: "), ("{:4}").format( time.strftime('%X %x %Z')[0:5]) kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) print "Inititial guess norm: ", u.norm() #A,Q if IterType == 'Combined': n = FacetNormal(mesh) mat = as_matrix([[b_k[1] * b_k[1], -b_k[1] * b_k[0]], [-b_k[1] * b_k[0], b_k[0] * b_k[0]]]) F = A.getSubMatrix(u_is, u_is) a = params[2] * inner(grad(b_t), grad(c_t)) * dx( W.mesh()) + inner((grad(b_t) * u_k), c_t) * dx( W.mesh()) + (1 / 2) * div(u_k) * inner( c_t, b_t) * dx(W.mesh()) - (1 / 2) * inner( u_k, n) * inner(c_t, b_t) * ds( W.mesh()) + kappa / Mu_m * inner( mat * b_t, c_t) * dx(W.mesh()) ShiftedMass = assemble(a) bcu.apply(ShiftedMass) kspF = NSprecondSetup.LSCKSPnonlinear(F) else: F = A.getSubMatrix(u_is, u_is) kspF = NSprecondSetup.LSCKSPnonlinear(F) stime = time.time() u, mits, nsits = S.solve(A, b, u, params, W, IterType, OuterTol, InnerTol, HiptmairMatrices, Hiptmairtol, KSPlinearfluids, Fp, kspF) Soltime = time.time() - stime Mits += mits NSits += nsits SolutionTime += Soltime u1, p1, b1, r1, eps = Iter.PicardToleranceDecouple( u, x, FSpaces, dim, "2", iter) p1.vector()[:] += -assemble(p1 * dx) / assemble(ones * dx) u_k.assign(u1) p_k.assign(p1) b_k.assign(b1) r_k.assign(r1) uOld = np.concatenate( (u_k.vector().array(), p_k.vector().array(), b_k.vector().array(), r_k.vector().array()), axis=0) x = IO.arrayToVec(uOld) XX = np.concatenate((u_k.vector().array(), p_k.vector().array(), b_k.vector().array(), r_k.vector().array()), axis=0) SolTime[xx - 1] = SolutionTime / iter NSave[xx - 1] = (float(NSits) / iter) Mave[xx - 1] = (float(Mits) / iter) iterations[xx - 1] = iter TotalTime[xx - 1] = time.time() - TotalStart dim = [ Velocity.dim(), Pressure.dim(), Magnetic.dim(), Lagrange.dim() ] # # ExactSolution = [u0,p0,b0,r0] # errL2u[xx-1], errH1u[xx-1], errL2p[xx-1], errL2b[xx-1], errCurlb[xx-1], errL2r[xx-1], errH1r[xx-1] = Iter.Errors(XX,mesh,FSpaces,ExactSolution,order,dim, "DG") # # if xx > 1: # l2uorder[xx-1] = np.abs(np.log2(errL2u[xx-2]/errL2u[xx-1])) # H1uorder[xx-1] = np.abs(np.log2(errH1u[xx-2]/errH1u[xx-1])) # # l2porder[xx-1] = np.abs(np.log2(errL2p[xx-2]/errL2p[xx-1])) # # l2border[xx-1] = np.abs(np.log2(errL2b[xx-2]/errL2b[xx-1])) # Curlborder[xx-1] = np.abs(np.log2(errCurlb[xx-2]/errCurlb[xx-1])) # # l2rorder[xx-1] = np.abs(np.log2(errL2r[xx-2]/errL2r[xx-1])) # H1rorder[xx-1] = np.abs(np.log2(errH1r[xx-2]/errH1r[xx-1])) import pandas as pd # LatexTitles = ["l","DoFu","Dofp","V-L2","L2-order","V-H1","H1-order","P-L2","PL2-order"] # LatexValues = np.concatenate((level,Velocitydim,Pressuredim,errL2u,l2uorder,errH1u,H1uorder,errL2p,l2porder), axis=1) # LatexTable = pd.DataFrame(LatexValues, columns = LatexTitles) # pd.set_option('precision',3) # LatexTable = MO.PandasFormat(LatexTable,"V-L2","%2.4e") # LatexTable = MO.PandasFormat(LatexTable,'V-H1',"%2.4e") # LatexTable = MO.PandasFormat(LatexTable,"H1-order","%1.2f") # LatexTable = MO.PandasFormat(LatexTable,'L2-order',"%1.2f") # LatexTable = MO.PandasFormat(LatexTable,"P-L2","%2.4e") # LatexTable = MO.PandasFormat(LatexTable,'PL2-order',"%1.2f") # print LatexTable # # # print "\n\n Magnetic convergence" # MagneticTitles = ["l","B DoF","R DoF","B-L2","L2-order","B-Curl","HCurl-order"] # MagneticValues = np.concatenate((level,Magneticdim,Lagrangedim,errL2b,l2border,errCurlb,Curlborder),axis=1) # MagneticTable= pd.DataFrame(MagneticValues, columns = MagneticTitles) # pd.set_option('precision',3) # MagneticTable = MO.PandasFormat(MagneticTable,"B-Curl","%2.4e") # MagneticTable = MO.PandasFormat(MagneticTable,'B-L2',"%2.4e") # MagneticTable = MO.PandasFormat(MagneticTable,"L2-order","%1.2f") # MagneticTable = MO.PandasFormat(MagneticTable,'HCurl-order',"%1.2f") # print MagneticTable # # # # # import pandas as pd # print "\n\n Iteration table" if IterType == "Full": IterTitles = [ "l", "DoF", "AV solve Time", "Total picard time", "picard iterations", "Av Outer its", "Av Inner its", ] else: IterTitles = [ "l", "DoF", "AV solve Time", "Total picard time", "picard iterations", "Av NS iters", "Av M iters" ] IterValues = np.concatenate( (level, Wdim, SolTime, TotalTime, iterations, Mave, NSave), axis=1) IterTable = pd.DataFrame(IterValues, columns=IterTitles) if IterType == "Full": IterTable = MO.PandasFormat(IterTable, 'Av Outer its', "%2.1f") IterTable = MO.PandasFormat(IterTable, 'Av Inner its', "%2.1f") else: IterTable = MO.PandasFormat(IterTable, 'Av NS iters', "%2.1f") IterTable = MO.PandasFormat(IterTable, 'Av M iters', "%2.1f") print IterTable print " \n Outer Tol: ", OuterTol, "Inner Tol: ", InnerTol IterTable.to_latex('Tables/IterType=' + IterType + '_n=' + str(m) + '_mu=' + str(MU) + '_kappa=' + str(kappa) + '_mu_m=' + str(Mu_m) + '.tex') # # # if (ShowResultPlots == 'yes'): # plot(u_k) # plot(interpolate(u0,Velocity)) # # plot(p_k) # # plot(interpolate(p0,Pressure)) # # plot(b_k) # plot(interpolate(b0,Magnetic)) # # plot(r_k) # plot(interpolate(r0,Lagrange)) # # interactive() interactive()
# <codecell> C = sparse.csr_matrix((V.dim(),Q.dim())) (v) = TrialFunction(V) (u) = TestFunction(V) tic() for i in range(0,Q.dim()): uOut = Function(V) uu = Function(Q) x = M.getVecRight() zero = np.zeros((Q.dim(),1))[:,0] zero[i] = 1 uu.vector()[:] = zero L = assemble(inner(u, grad(uu))*dx) rhs = IO.arrayToVec(B[:,i].toarray()) ksp.solve(rhs,x) # x = project(grad(uu),V) P = x.array uOut.vector()[:] = P low_values_indices = np.abs(P) < 1e-3 P[low_values_indices] = 0 P=np.around(P) pn = P.nonzero()[0] for j in range(0,len(pn)): C[pn[j],i] = P[pn[j]] del uu print toc() print C.todense() # C = sparse.csr_matrix((Magnetic.dim(),Lagrange.dim())) # Mmap = Magnetic.dofmap()
def setUp(self, pc): A, P = pc.getOperators() print A.size self.Ct = A.getSubMatrix(self.u_is,self.b_is) self.C = A.getSubMatrix(self.b_is,self.u_is) self.D = A.getSubMatrix(self.r_is,self.b_is) self.Bt = A.getSubMatrix(self.u_is,self.p_is) self.B = A.getSubMatrix(self.p_is,self.u_is) self.Dt = A.getSubMatrix(self.b_is,self.r_is) # print self.Ct.view() F = IO.matToSparse(A.getSubMatrix(self.u_is,self.u_is)).tocsr() Finv = sp.linalg.inv(F) Finv = PETSc.Mat().createAIJ(size=Finv.shape,csr=(Finv.indptr, Finv.indices, Finv.data)) #CFC = sp.csr_matrix( (data,(row,column)), shape=(self.W[1].dim(),self.W[1].dim()) ) #print CFC.shape #CFC = PETSc.Mat().createAIJ(size=CFC.shape,csr=(CFC.indptr, CFC.indices, CFC.data)) #print CFC.size, self.AA.size #MX = self.AA+self.F MX = self.AA - self.C*Finv*self.Ct self.FF = - self.C*Finv*self.Ct # MO.StoreMatrix(B,"A") # print FC.todense() self.kspF.setType('preonly') self.kspF.getPC().setType('lu') self.kspF.setFromOptions() self.kspF.setPCSide(0) self.kspA.setType('preonly') self.kspA.getPC().setType('lu') self.kspA.setFromOptions() self.kspA.setPCSide(0) self.kspQ.setType('preonly') self.kspQ.getPC().setType('lu') self.kspQ.setFromOptions() self.kspQ.setPCSide(0) self.kspScalar.setType('preonly') self.kspScalar.getPC().setType('lu') self.kspScalar.setFromOptions() self.kspScalar.setPCSide(0) kspMX = PETSc.KSP() kspMX.create(comm=PETSc.COMM_WORLD) pcMX = kspMX.getPC() kspMX.setType('preonly') pcMX.setType('lu') kspMX.setOperators(MX,MX) OptDB = PETSc.Options() #OptDB["pc_factor_mat_ordering_type"] = "rcm" #OptDB["pc_factor_mat_solver_package"] = "mumps" kspMX.setFromOptions() self.kspMX = kspMX # self.kspCGScalar.setType('preonly') # self.kspCGScalar.getPC().setType('lu') # self.kspCGScalar.setFromOptions() # self.kspCGScalar.setPCSide(0) self.kspVector.setType('preonly') self.kspVector.getPC().setType('lu') self.kspVector.setFromOptions() self.kspVector.setPCSide(0) print "setup"
# Options = 'p4' # PCD.check(MU, u_k, p_k, mesh, boundaries, domains) # Fluid = {'Fp': Fp, 'Ap': MatrixLinearFluids[0], 'Qp': MatrixLinearFluids[1], 'Fs': ShiftedMass} # Maxwell = {'MX': HiptmairMatrices[6], 'Lp': HiptmairMatrices[3].getOperators()[0]} # SaveMatrix.SaveMatrices(W, int(level[xx-1][0]), A, Fluid, Maxwell) FSpaces = [Velocity, Pressure, Magnetic, Lagrange] u_is = PETSc.IS().createGeneral(W.sub(0).dofmap().dofs()) b_is = PETSc.IS().createGeneral(W.sub(1).dofmap().dofs()) p_is = PETSc.IS().createGeneral(W.sub(2).dofmap().dofs()) r_is = PETSc.IS().createGeneral(W.sub(3).dofmap().dofs()) u = IO.arrayToVec( np.concatenate( (u.getSubVector(u_is).array, u.getSubVector(p_is).array, u.getSubVector(b_is).array, u.getSubVector(r_is).array))) stime = time.time() Soltime = time.time() - stime MO.StrTimePrint("MHD solve, time: ", Soltime) MO.PrintStr("MHD iterations " + str(ksp.its), 7, "=", "\n\n", "\n\n") Mits += ksp.its NSits += 1 SolutionTime += Soltime # u = IO.arrayToVec( u) u1, p1, b1, r1, eps = Iter.PicardToleranceDecouple( u, x, FSpaces, dim, "2", iter) p1.vector()[:] += -assemble(p1 * dx(0)) / assemble(ones * dx(0)) u_k.assign(u1)
f = -MU*Laplacian+Advection+gradPres n = FacetNormal(mesh) h = CellSize(mesh) h_avg =avg(h) d = 0 u_k,p_k = common.Stokes(V,Q,u0,Laplacian+gradPres,[1,1,MU]) # p_k.vector()[:] = p_k.vector().array() # u_k = Function(V) # p_k = Function(Q) uOld = np.concatenate((u_k.vector().array(),p_k.vector().array()), axis=0) r = IO.arrayToVec(uOld) a11 = MU*inner(grad(v), grad(u))*dx + inner((grad(u)*u_k),v)*dx + (1/2)*div(u_k)*inner(u,v)*dx- (1/2)*inner(u_k,n)*inner(u,v)*ds a12 = div(v)*p*dx a21 = div(u)*q*dx L1 = inner(v, f)*dx a = a11-a12-a21 r11 = MU*inner(grad(v), grad(u_k))*dx + inner((grad(u_k)*u_k),v)*dx + (1/2)*div(u_k)*inner(u_k,v)*dx- (1/2)*inner(u_k,n)*inner(u_k,v)*ds r12 = div(v)*p_k*dx r21 = div(u_k)*q*dx RHSform = r11-r12-r21 p11 = MU*inner(grad(v), grad(u))*dx + inner((grad(u)*u_k),v)*dx + (1/2)*div(u_k)*inner(u,v)*dx- (1/2)*inner(u_k,n)*inner(u,v)*ds
def solve(A, b, u, params, Fspace, SolveType, IterType, OuterTol, InnerTol, HiptmairMatrices, Hiptmairtol, KSPlinearfluids, Fp, kspF): if SolveType == "Direct": ksp = PETSc.KSP() ksp.create(comm=PETSc.COMM_WORLD) pc = ksp.getPC() ksp.setType('preonly') pc.setType('lu') OptDB = PETSc.Options() OptDB['pc_factor_mat_solver_package'] = "mumps" OptDB['pc_factor_mat_ordering_type'] = "rcm" ksp.setFromOptions() scale = b.norm() b = b / scale ksp.setOperators(A, A) del A ksp.solve(b, u) # Mits +=dodim u = u * scale MO.PrintStr("Number iterations = " + str(ksp.its), 60, "+", "\n\n", "\n\n") return u, ksp.its, 0 elif SolveType == "Direct-class": ksp = PETSc.KSP() ksp.create(comm=PETSc.COMM_WORLD) pc = ksp.getPC() ksp.setType('gmres') pc.setType('none') ksp.setFromOptions() scale = b.norm() b = b / scale ksp.setOperators(A, A) del A ksp.solve(b, u) # Mits +=dodim u = u * scale MO.PrintStr("Number iterations = " + str(ksp.its), 60, "+", "\n\n", "\n\n") return u, ksp.its, 0 else: # u = b.duplicate() if IterType == "Full": ksp = PETSc.KSP() ksp.create(comm=PETSc.COMM_WORLD) pc = ksp.getPC() ksp.setType('fgmres') pc.setType('python') OptDB = PETSc.Options() OptDB['ksp_gmres_restart'] = 200 # FSpace = [Velocity,Magnetic,Pressure,Lagrange] reshist = {} def monitor(ksp, its, fgnorm): reshist[its] = fgnorm print its, " OUTER:", fgnorm # ksp.setMonitor(monitor) ksp.max_it = 1000 W = Fspace FFSS = [W.sub(0), W.sub(1), W.sub(2), W.sub(3)] pc.setPythonContext( MHDprec.InnerOuterMAGNETICapprox( FFSS, kspF, KSPlinearfluids[0], KSPlinearfluids[1], Fp, HiptmairMatrices[3], HiptmairMatrices[4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6], Hiptmairtol)) #OptDB = PETSc.Options() # OptDB['pc_factor_mat_solver_package'] = "mumps" # OptDB['pc_factor_mat_ordering_type'] = "rcm" # ksp.setFromOptions() scale = b.norm() b = b / scale ksp.setOperators(A, A) del A ksp.solve(b, u) # Mits +=dodim u = u * scale MO.PrintStr("Number iterations = " + str(ksp.its), 60, "+", "\n\n", "\n\n") return u, ksp.its, 0 IS = MO.IndexSet(Fspace, '2by2') M_is = IS[1] NS_is = IS[0] kspNS = PETSc.KSP().create() kspM = PETSc.KSP().create() kspNS.setTolerances(OuterTol) kspNS.setOperators(A[0]) kspM.setOperators(A[1]) # print P.symmetric if IterType == "MD": kspNS.setType('gmres') kspNS.max_it = 500 pcNS = kspNS.getPC() pcNS.setType(PETSc.PC.Type.PYTHON) pcNS.setPythonContext( NSpreconditioner.NSPCD( MixedFunctionSpace([Fspace.sub(0), Fspace.sub(1)]), kspF, KSPlinearfluids[0], KSPlinearfluids[1], Fp)) elif IterType == "CD": kspNS.setType('minres') pcNS = kspNS.getPC() pcNS.setType(PETSc.PC.Type.PYTHON) Q = KSPlinearfluids[1].getOperators()[0] Q = 1. / params[2] * Q KSPlinearfluids[1].setOperators(Q, Q) pcNS.setPythonContext( StokesPrecond.MHDApprox( MixedFunctionSpace([Fspace.sub(0), Fspace.sub(1)]), kspF, KSPlinearfluids[1])) reshist = {} def monitor(ksp, its, fgnorm): reshist[its] = fgnorm print fgnorm # kspNS.setMonitor(monitor) uNS = u.getSubVector(NS_is) bNS = b.getSubVector(NS_is) # print kspNS.view() scale = bNS.norm() bNS = bNS / scale print bNS.norm() kspNS.solve(bNS, uNS) uNS = uNS * scale NSits = kspNS.its kspNS.destroy() # for line in reshist.values(): # print line kspM.setFromOptions() kspM.setType(kspM.Type.MINRES) kspM.setTolerances(InnerTol) pcM = kspM.getPC() pcM.setType(PETSc.PC.Type.PYTHON) pcM.setPythonContext( MP.Hiptmair(MixedFunctionSpace([Fspace.sub(2), Fspace.sub(3)]), HiptmairMatrices[3], HiptmairMatrices[4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6], Hiptmairtol)) uM = u.getSubVector(M_is) bM = b.getSubVector(M_is) scale = bM.norm() bM = bM / scale print bM.norm() kspM.solve(bM, uM) uM = uM * scale Mits = kspM.its kspM.destroy() u = IO.arrayToVec(np.concatenate([uNS.array, uM.array])) MO.PrintStr("Number of M iterations = " + str(Mits), 60, "+", "\n\n", "\n\n") MO.PrintStr("Number of NS/S iterations = " + str(NSits), 60, "+", "\n\n", "\n\n") return u, NSits, Mits
if (Solving == 'Iterative' or Solving == 'Direct'): if case == 1: ue = Expression(("x[0]*x[0]*(x[0]-1)", "x[1]*x[1]*(x[1]-1)")) elif case == 2: ue = Expression(("sin(2*pi*x[1])*cos(2*pi*x[0])", "-sin(2*pi*x[0])*cos(2*pi*x[1])")) elif case == 3: ue = Expression(("-sin(2*pi*x[0])*cos(2*pi*x[1]) ", "sin(2*pi*x[1])*cos(2*pi*x[0]) ")) Ve = FunctionSpace(mesh, "N1curl", 4) u = interpolate(ue, Ve) Nv = u.vector().array().shape print Nv X = IO.vecToArray(x) x = X[0:Nv[0]] ua = Function(V) ua.vector()[:] = x # parameters["form_compiler"]["quadrature_degree"] = 4 # parameters["form_compiler"]["optimize"] = True ErrorB = Function(V) ErrorB = u - ua #interpolate(ue,Ve).vector().array()-ua.vector().array() errL2b[xx - 1] = sqrt(assemble(inner(ErrorB, ErrorB) * dx)) errCurlb[xx - 1] = sqrt( assemble(inner(curl(ErrorB), curl(ErrorB)) * dx))
time = toc() print time SolutionTime = SolutionTime +time del ksp, pc u, p, b, r, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter) p.vector()[:] += - assemble(p*dx)/assemble(ones*dx) u_k.assign(u) p_k.assign(p) b_k.assign(b) r_k.assign(r) # plot(u_k) # plot(p_k) # t.sleep(1) uOld= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0) x = IO.arrayToVec(uOld) # u_k,b_k,epsu,epsb=Iter.PicardTolerance(x,u_k,b_k,FSpaces,dim,"inf",iter) MUit[xx-1,yy-1]= iter # SolTime[xx-1] = SolutionTime/iter ue =u0 pe = p0 be = b0 re = r0
a = dot(curl(u), curl(v)) * dx + c * inner(u, v) * dx L1 = inner(v, f) * dx tic() AA, bb = assemble_system(a, L1, bcs) As = AA.sparray() StoreMatrix(As, 'A') A = PETSc.Mat().createAIJ(size=As.shape, csr=(As.indptr, As.indices, As.data)) # exit # A = as_backend_type(AA).mat() print toc() b = bb.array() zeros = 0 * b x = IO.arrayToVec(zeros) bb = IO.arrayToVec(b) if (Solving == 'Direct'): ksp = PETSc.KSP().create() ksp.setOperators(A) ksp.setFromOptions() ksp.setType(ksp.Type.PREONLY) ksp.pc.setType(ksp.pc.Type.LU) # print 'Solving with:', ksp.getType() # Solve! tic() ksp.solve(bb, x) SolTime[xx - 1] = toc()
def foo(): m = 6 mm = 5 errL2u =np.zeros((m-1,1)) errH1u =np.zeros((m-1,1)) errL2p =np.zeros((m-1,1)) errL2b =np.zeros((m-1,1)) errCurlb =np.zeros((m-1,1)) errL2r =np.zeros((m-1,1)) errH1r =np.zeros((m-1,1)) l2uorder = np.zeros((m-1,1)) H1uorder =np.zeros((m-1,1)) l2porder = np.zeros((m-1,1)) l2border = np.zeros((m-1,1)) Curlborder =np.zeros((m-1,1)) l2rorder = np.zeros((m-1,1)) H1rorder = np.zeros((m-1,1)) NN = np.zeros((m-1,1)) DoF = np.zeros((m-1,1)) Velocitydim = np.zeros((m-1,1)) Magneticdim = np.zeros((m-1,1)) Pressuredim = np.zeros((m-1,1)) Lagrangedim = np.zeros((m-1,1)) Wdim = np.zeros((m-1,1)) iterations = np.zeros((m-1,3*(mm-1))) SolTime = np.zeros((m-1,1)) udiv = np.zeros((m-1,1)) MU = np.zeros((m-1,1)) level = np.zeros((m-1,1)) NSave = np.zeros((m-1,1)) Mave = np.zeros((m-1,1)) TotalTime = np.zeros((m-1,1)) KappaSave = np.zeros((mm-1,1)) nn = 2 dim = 2 ShowResultPlots = 'yes' split = 'Linear' qq = -1 MU[0]= 1e0 kappa = 0.01 qq = -1 for yy in xrange(1,mm): kappa = kappa*10 KappaSave[yy-1] = kappa IterTypes = ['Full','MD','CD'] for kk in range(len(IterTypes)): qq += 1 for xx in xrange(1,m): print xx level[xx-1] = xx+ 2 nn = 2**(level[xx-1]) # Create mesh and define function space nn = int(nn) NN[xx-1] = nn/2 # parameters["form_compiler"]["quadrature_degree"] = 6 # parameters = CP.ParameterSetup() mesh = UnitSquareMesh(nn,nn) order = 1 parameters['reorder_dofs_serial'] = False Velocity = VectorFunctionSpace(mesh, "CG", order+1) Pressure = FunctionSpace(mesh, "CG", order) Magnetic = FunctionSpace(mesh, "N1curl", order) Lagrange = FunctionSpace(mesh, "CG", order) W = MixedFunctionSpace([Velocity, Pressure, Magnetic,Lagrange]) # W = Velocity*Pressure*Magnetic*Lagrange Velocitydim[xx-1] = Velocity.dim() Pressuredim[xx-1] = Pressure.dim() Magneticdim[xx-1] = Magnetic.dim() Lagrangedim[xx-1] = Lagrange.dim() Wdim[xx-1] = W.dim() print "\n\nW: ",Wdim[xx-1],"Velocity: ",Velocitydim[xx-1],"Pressure: ",Pressuredim[xx-1],"Magnetic: ",Magneticdim[xx-1],"Lagrange: ",Lagrangedim[xx-1],"\n\n" dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(), Lagrange.dim()] def boundary(x, on_boundary): return on_boundary u0, p0,b0, r0, Laplacian, Advection, gradPres,CurlCurl, gradR, NS_Couple, M_Couple = ExactSol.MHD2D(4,1) bcu = DirichletBC(W.sub(0),u0, boundary) bcb = DirichletBC(W.sub(2),b0, boundary) bcr = DirichletBC(W.sub(3),r0, boundary) # bc = [u0,p0,b0,r0] bcs = [bcu,bcb,bcr] FSpaces = [Velocity,Pressure,Magnetic,Lagrange] (u, b, p, r) = TrialFunctions(W) (v, c, q, s) = TestFunctions(W) Mu_m =1e1 MU = 1.0/1 IterType = IterTypes[kk] Split = "No" Saddle = "No" Stokes = "No" F_NS = -MU*Laplacian+Advection+gradPres-kappa*NS_Couple if kappa == 0: F_M = Mu_m*CurlCurl+gradR -kappa*M_Couple else: F_M = Mu_m*kappa*CurlCurl+gradR -kappa*M_Couple params = [kappa,Mu_m,MU] # MO.PrintStr("Preconditioning MHD setup",5,"+","\n\n","\n\n") Hiptmairtol = 1e-5 HiptmairMatrices = PrecondSetup.MagneticSetup(Magnetic, Lagrange, b0, r0, Hiptmairtol, params) MO.PrintStr("Setting up MHD initial guess",5,"+","\n\n","\n\n") u_k,p_k,b_k,r_k = common.InitialGuess(FSpaces,[u0,p0,b0,r0],[F_NS,F_M],params,HiptmairMatrices,1e-6,Neumann=Expression(("0","0")),options ="New", FS = "DG") #plot(p_k, interactive = True) b_t = TrialFunction(Velocity) c_t = TestFunction(Velocity) #print assemble(inner(b,c)*dx).array().shape #print mat #ShiftedMass = assemble(inner(mat*b,c)*dx) #as_vector([inner(b,c)[0]*b_k[0],inner(b,c)[1]*(-b_k[1])]) ones = Function(Pressure) ones.vector()[:]=(0*ones.vector().array()+1) # pConst = - assemble(p_k*dx)/assemble(ones*dx) p_k.vector()[:] += - assemble(p_k*dx)/assemble(ones*dx) x = Iter.u_prev(u_k,p_k,b_k,r_k) KSPlinearfluids, MatrixLinearFluids = PrecondSetup.FluidLinearSetup(Pressure, MU) kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) #plot(b_k) ns,maxwell,CoupleTerm,Lmaxwell,Lns = forms.MHD2D(mesh, W,F_M,F_NS, u_k,b_k,params,IterType,"DG",Saddle,Stokes) RHSform = forms.PicardRHS(mesh, W, u_k, p_k, b_k, r_k, params,"DG",Saddle,Stokes) bcu = DirichletBC(Velocity,Expression(("0.0","0.0")), boundary) bcb = DirichletBC(Magnetic,Expression(("0.0","0.0")), boundary) bcr = DirichletBC(Lagrange,Expression(("0.0")), boundary) bcs = [bcu,bcb,bcr] parameters['linear_algebra_backend'] = 'uBLAS' SetupType = 'Matrix' BC = MHDsetup.BoundaryIndices(mesh) eps = 1.0 # error measure ||u-u_k|| tol = 1.0E-4 # tolerance iter = 0 # iteration counter maxiter = 40 # max no of iterations allowed SolutionTime = 0 outer = 0 # parameters['linear_algebra_backend'] = 'uBLAS' # FSpaces = [Velocity,Magnetic,Pressure,Lagrange] if IterType == "CD": MO.PrintStr("Setting up PETSc "+SetupType,2,"=","\n","\n") Alin = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "Linear",IterType) Fnlin,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType) A = Fnlin+Alin A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType) u = b.duplicate() u_is = PETSc.IS().createGeneral(range(Velocity.dim())) NS_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim())) M_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim(),W.dim())) OuterTol = 1e-5 InnerTol = 1e-5 NSits =0 Mits =0 TotalStart =time.time() SolutionTime = 0 while eps > tol and iter < maxiter: iter += 1 MO.PrintStr("Iter "+str(iter),7,"=","\n\n","\n\n") AssembleTime = time.time() if IterType == "CD": MO.StrTimePrint("MHD CD RHS assemble, time: ", time.time()-AssembleTime) b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "CD",IterType) else: MO.PrintStr("Setting up PETSc "+SetupType,2,"=","\n","\n") # if iter == 1: # Alin = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "Linear",IterType) # Fnlin,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType) # A = Fnlin+Alin # A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType) # u = b.duplicate() # else: # Fnline,b = MHDsetup.Assemble(W,ns,maxwell,CoupleTerm,Lns,Lmaxwell,RHSform,bcs+BC, "NonLinear",IterType) # A = Fnlin+Alin # A,b = MHDsetup.SystemAssemble(FSpaces,A,b,SetupType,IterType) AA, bb = assemble_system(maxwell+ns+CoupleTerm, (Lmaxwell + Lns) - RHSform, bcs) A,b = CP.Assemble(AA,bb) # if iter == 1: MO.StrTimePrint("MHD total assemble, time: ", time.time()-AssembleTime) u = b.duplicate() #A,Q kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) print "Inititial guess norm: ", u.norm() if u.norm()>1e50: iter = 10000 break stime = time.time() kspF = 0 u, mits,nsits = S.solve(A,b,u,params,W,'Direct',IterType,OuterTol,InnerTol,HiptmairMatrices,Hiptmairtol,KSPlinearfluids, Fp,kspF) Soltime = time.time()- stime Mits += mits NSits += nsits SolutionTime += Soltime u1, p1, b1, r1, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter) p1.vector()[:] += - assemble(p1*dx)/assemble(ones*dx) u_k.assign(u1) p_k.assign(p1) b_k.assign(b1) r_k.assign(r1) uOld= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0) x = IO.arrayToVec(uOld) XX= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0) iterations[xx-1,qq] = iter dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(),Lagrange.dim()] # # ExactSolution = [u0,p0,b0,r0] # errL2u[xx-1], errH1u[xx-1], errL2p[xx-1], errL2b[xx-1], errCurlb[xx-1], errL2r[xx-1], errH1r[xx-1] = Iter.Errors(XX,mesh,FSpaces,ExactSolution,order,dim, "DG") # # if xx > 1: # l2uorder[xx-1] = np.abs(np.log2(errL2u[xx-2]/errL2u[xx-1])) # H1uorder[xx-1] = np.abs(np.log2(errH1u[xx-2]/errH1u[xx-1])) # # l2porder[xx-1] = np.abs(np.log2(errL2p[xx-2]/errL2p[xx-1])) # # l2border[xx-1] = np.abs(np.log2(errL2b[xx-2]/errL2b[xx-1])) # Curlborder[xx-1] = np.abs(np.log2(errCurlb[xx-2]/errCurlb[xx-1])) # # l2rorder[xx-1] = np.abs(np.log2(errL2r[xx-2]/errL2r[xx-1])) # H1rorder[xx-1] = np.abs(np.log2(errH1r[xx-2]/errH1r[xx-1])) # # # # # import pandas as pd # # # # LatexTitles = ["l","DoFu","Dofp","V-L2","L2-order","V-H1","H1-order","P-L2","PL2-order"] # LatexValues = np.concatenate((level,Velocitydim,Pressuredim,errL2u,l2uorder,errH1u,H1uorder,errL2p,l2porder), axis=1) # LatexTable = pd.DataFrame(LatexValues, columns = LatexTitles) # pd.set_option('precision',3) # LatexTable = MO.PandasFormat(LatexTable,"V-L2","%2.4e") # LatexTable = MO.PandasFormat(LatexTable,'V-H1',"%2.4e") # LatexTable = MO.PandasFormat(LatexTable,"H1-order","%1.2f") # LatexTable = MO.PandasFormat(LatexTable,'L2-order',"%1.2f") # LatexTable = MO.PandasFormat(LatexTable,"P-L2","%2.4e") # LatexTable = MO.PandasFormat(LatexTable,'PL2-order',"%1.2f") # print LatexTable # # # print "\n\n Magnetic convergence" # MagneticTitles = ["l","B DoF","R DoF","B-L2","L2-order","B-Curl","HCurl-order"] # MagneticValues = np.concatenate((level,Magneticdim,Lagrangedim,errL2b,l2border,errCurlb,Curlborder),axis=1) # MagneticTable= pd.DataFrame(MagneticValues, columns = MagneticTitles) # pd.set_option('precision',3) # MagneticTable = MO.PandasFormat(MagneticTable,"B-Curl","%2.4e") # MagneticTable = MO.PandasFormat(MagneticTable,'B-L2',"%2.4e") # MagneticTable = MO.PandasFormat(MagneticTable,"L2-order","%1.2f") # MagneticTable = MO.PandasFormat(MagneticTable,'HCurl-order',"%1.2f") # print MagneticTable # import pandas as pd print iterations.shape[1] iter = ["P","MD","CD"] IterTitles = ["l","DoF"] for i in range(iterations.shape[1]/3): IterTitles += iter print IterTitles IterValues = np.concatenate((level,Wdim,iterations),axis=1) IterTable= pd.DataFrame(IterValues, columns = IterTitles) print IterTable.to_latex() print " \n Outer Tol: ",OuterTol, "Inner Tol: ", InnerTol print KappaSave # # # if (ShowResultPlots == 'yes'): # plot(u_k) # plot(interpolate(u0,Velocity)) # # plot(p_k) # # plot(interpolate(p0,Pressure)) # # plot(b_k) # plot(interpolate(b0,Magnetic)) # # plot(r_k) # plot(interpolate(r0,Lagrange)) # # interactive() interactive()
a21 = -div(u)*q*dx L1 = inner(v, f)*dx a = a11+a12+a21 i = (1/mu)*p*q*dx tic() AA, bb = assemble_system(a, L1, bcs) As = AA.sparray() A = PETSc.Mat().createAIJ(size=As.shape,csr=(As.indptr, As.indices, As.data)) print toc() b = bb.array() zeros = 0*b del bb bb = IO.arrayToVec(b) x = IO.arrayToVec(zeros) PP, Pb = assemble_system(a11+i,L1,bcs) Ps = PP.sparray() P = PETSc.Mat().createAIJ(size=Ps.shape,csr=(Ps.indptr, Ps.indices, Ps.data)) if (SavePrecond == 'yes'): PP, Pb = assemble_system(a11+i,L1,bcs) Ps = PP.sparray()[0:-1,0:-1] Wstring = str(int(Wdim[xx-1][0]-1)) nameA ="".join(['eigenvalues/A',Wstring,".mat"]) scipy.io.savemat(nameA, mdict={'A': As},oned_as='row') nameP ="".join(['eigenvalues/P',Wstring,".mat"]) scipy.io.savemat(nameP, mdict={'P': Ps},oned_as='row') del PP,Pb,Ps,AA,As
def setUp(self, pc): A, P = pc.getOperators() print A.size self.Ct = A.getSubMatrix(self.u_is, self.b_is) self.C = A.getSubMatrix(self.b_is, self.u_is) self.D = A.getSubMatrix(self.r_is, self.b_is) self.Bt = A.getSubMatrix(self.u_is, self.p_is) self.B = A.getSubMatrix(self.p_is, self.u_is) self.Dt = A.getSubMatrix(self.b_is, self.r_is) # print self.Ct.view() F = IO.matToSparse(A.getSubMatrix(self.u_is, self.u_is)).tocsr() Finv = sp.linalg.inv(F) Finv = PETSc.Mat().createAIJ(size=Finv.shape, csr=(Finv.indptr, Finv.indices, Finv.data)) #CFC = sp.csr_matrix( (data,(row,column)), shape=(self.W[1].dim(),self.W[1].dim()) ) #print CFC.shape #CFC = PETSc.Mat().createAIJ(size=CFC.shape,csr=(CFC.indptr, CFC.indices, CFC.data)) #print CFC.size, self.AA.size #MX = self.AA+self.F MX = self.AA - self.C * Finv * self.Ct self.FF = -self.C * Finv * self.Ct # MO.StoreMatrix(B,"A") # print FC.todense() self.kspF.setType('preonly') self.kspF.getPC().setType('lu') self.kspF.setFromOptions() self.kspF.setPCSide(0) self.kspA.setType('preonly') self.kspA.getPC().setType('lu') self.kspA.setFromOptions() self.kspA.setPCSide(0) self.kspQ.setType('preonly') self.kspQ.getPC().setType('lu') self.kspQ.setFromOptions() self.kspQ.setPCSide(0) self.kspScalar.setType('preonly') self.kspScalar.getPC().setType('lu') self.kspScalar.setFromOptions() self.kspScalar.setPCSide(0) kspMX = PETSc.KSP() kspMX.create(comm=PETSc.COMM_WORLD) pcMX = kspMX.getPC() kspMX.setType('preonly') pcMX.setType('lu') kspMX.setOperators(MX, MX) OptDB = PETSc.Options() #OptDB["pc_factor_mat_ordering_type"] = "rcm" #OptDB["pc_factor_mat_solver_package"] = "mumps" kspMX.setFromOptions() self.kspMX = kspMX # self.kspCGScalar.setType('preonly') # self.kspCGScalar.getPC().setType('lu') # self.kspCGScalar.setFromOptions() # self.kspCGScalar.setPCSide(0) self.kspVector.setType('preonly') self.kspVector.getPC().setType('lu') self.kspVector.setFromOptions() self.kspVector.setPCSide(0) print "setup"
OptDB = PETSc.Options() ksp.setFromOptions() C = sparse.csr_matrix((V.dim(), Q.dim())) tic() for i in range(0, Q.dim()): uOut = Function(V) uu = Function(Q) x = M.getVecRight() zero = np.zeros((Q.dim(), 1))[:, 0] zero[i] = 1 uu.vector()[:] = zero L = assemble(inner(u, grad(uu)) * dx) # bcb.apply(L) rhs = IO.arrayToVec(L.array()) ksp.solve(rhs, x) # x = project(grad(uu),V) P = x.array uOut.vector()[:] = P low_values_indices = np.abs(P) < 1e-3 P[low_values_indices] = 0 #P=np.around(P) pn = P.nonzero()[0] for j in range(0, len(pn)): C[pn[j], i] = P[pn[j]] del uu print toc() pathToGrad = "/home/mwathen/Dropbox/MastersResearch/MHD/FEniCS/GradMatrices/" name = pathToGrad + "UnitSquareCrossed_m=" + str(nn)
n = FacetNormal(mesh) h = CellSize(mesh) h_avg =avg(h) d = 0 u_k,p_k = common.Stokes(V,Q,u0,f,[1,1,MU], FS = "DG",InitialTol = 1e-6) # p_k.vector()[:] = p_k.vector().array() pConst = - assemble(p_k*dx)/assemble(ones*dx) p_k.vector()[:] += pConst # u_k = Function(V) # p_k = Function(Q) # plot(u_k) # plot(p_k) uOld = np.concatenate((u_k.vector().array(),p_k.vector().array()), axis=0) r = IO.arrayToVec(uOld) a11 = MU*inner(grad(v), grad(u))*dx(mesh) + inner((grad(u)*u_k),v)*dx(mesh) + (1./2)*div(u_k)*inner(u,v)*dx(mesh) - (1./2)*inner(u_k,n)*inner(u,v)*ds(mesh) a12 = div(v)*p*dx a21 = div(u)*q*dx a22 = 0.1*h_avg*jump(p)*jump(q)*dS # L1 = inner(v-0.1*h*h*grad(q), f)*dx print inner(v, f).shape() L1 = inner(v, f)*dx a = a11-a12-a21 r11 = MU*inner(grad(v), grad(u_k))*dx(mesh) + inner((grad(u_k)*u_k),v)*dx(mesh) + (1./2)*div(u_k)*inner(u_k,v)*dx(mesh) - (1./2)*inner(u_k,n)*inner(u_k,v)*ds(mesh) r12 = div(v)*p_k*dx r21 = div(u_k)*q*dx r22 = 0.1*h_avg*jump(p_k)*jump(q)*dS
def foo(): m = 4 errL2u = np.zeros((m - 1, 1)) errH1u = np.zeros((m - 1, 1)) errL2p = np.zeros((m - 1, 1)) errL2b = np.zeros((m - 1, 1)) errCurlb = np.zeros((m - 1, 1)) errL2r = np.zeros((m - 1, 1)) errH1r = np.zeros((m - 1, 1)) l2uorder = np.zeros((m - 1, 1)) H1uorder = np.zeros((m - 1, 1)) l2porder = np.zeros((m - 1, 1)) l2border = np.zeros((m - 1, 1)) Curlborder = np.zeros((m - 1, 1)) l2rorder = np.zeros((m - 1, 1)) H1rorder = np.zeros((m - 1, 1)) NN = np.zeros((m - 1, 1)) DoF = np.zeros((m - 1, 1)) Velocitydim = np.zeros((m - 1, 1)) Magneticdim = np.zeros((m - 1, 1)) Pressuredim = np.zeros((m - 1, 1)) Lagrangedim = np.zeros((m - 1, 1)) Wdim = np.zeros((m - 1, 1)) iterations = np.zeros((m - 1, 1)) SolTime = np.zeros((m - 1, 1)) udiv = np.zeros((m - 1, 1)) MU = np.zeros((m - 1, 1)) level = np.zeros((m - 1, 1)) NSave = np.zeros((m - 1, 1)) Mave = np.zeros((m - 1, 1)) TotalTime = np.zeros((m - 1, 1)) nn = 2 dim = 2 ShowResultPlots = 'yes' split = 'Linear' MU[0] = 1e0 for xx in xrange(1, m): print xx level[xx - 1] = xx + 0 nn = 2**(level[xx - 1]) # Create mesh and define function space nn = int(nn) NN[xx - 1] = nn / 2 # parameters["form_compiler"]["quadrature_degree"] = 6 # parameters = CP.ParameterSetup() mesh = UnitSquareMesh(nn, nn) order = 2 parameters['reorder_dofs_serial'] = False Velocity = VectorFunctionSpace(mesh, "CG", order) Pressure = FunctionSpace(mesh, "CG", order - 1) Magnetic = FunctionSpace(mesh, "N1curl", order - 1) Lagrange = FunctionSpace(mesh, "CG", order - 1) W = MixedFunctionSpace([Velocity, Pressure, Magnetic, Lagrange]) # W = Velocity*Pressure*Magnetic*Lagrange Velocitydim[xx - 1] = Velocity.dim() Pressuredim[xx - 1] = Pressure.dim() Magneticdim[xx - 1] = Magnetic.dim() Lagrangedim[xx - 1] = Lagrange.dim() Wdim[xx - 1] = W.dim() print "\n\nW: ", Wdim[xx - 1], "Velocity: ", Velocitydim[ xx - 1], "Pressure: ", Pressuredim[xx - 1], "Magnetic: ", Magneticdim[ xx - 1], "Lagrange: ", Lagrangedim[xx - 1], "\n\n" dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(), Lagrange.dim()] def boundary(x, on_boundary): return on_boundary u0, p0, b0, r0, Laplacian, Advection, gradPres, CurlCurl, gradR, NS_Couple, M_Couple = ExactSol.MHD2D( 4, 1, mesh) bcu = DirichletBC(Velocity, u0, boundary) bcb = DirichletBC(Magnetic, b0, boundary) bcr = DirichletBC(Lagrange, r0, boundary) # bc = [u0,p0,b0,r0] bcs = [bcu, bcb, bcr] FSpaces = [Velocity, Pressure, Magnetic, Lagrange] (u, b, p, r) = TrialFunctions(W) (v, c, q, s) = TestFunctions(W) kappa = 10.0 Mu_m = 10.0 MU = 1.0 / 1 IterType = 'Full' Split = "No" Saddle = "No" Stokes = "No" SetupType = 'python-class' F_NS = -MU * Laplacian + Advection + gradPres - kappa * NS_Couple if kappa == 0: F_M = Mu_m * CurlCurl + gradR - kappa * M_Couple else: F_M = Mu_m * kappa * CurlCurl + gradR - kappa * M_Couple params = [kappa, Mu_m, MU] MO.PrintStr("Seting up initial guess matricies", 2, "=", "\n\n", "\n") BCtime = time.time() BC = MHDsetup.BoundaryIndices(mesh) MO.StrTimePrint("BC index function, time: ", time.time() - BCtime) Hiptmairtol = 1e-6 HiptmairMatrices = PrecondSetup.MagneticSetup(Magnetic, Lagrange, b0, r0, Hiptmairtol, params) MO.PrintStr("Setting up MHD initial guess", 5, "+", "\n\n", "\n\n") u_k, p_k, b_k, r_k = common.InitialGuess(FSpaces, [u0, p0, b0, r0], [F_NS, F_M], params, HiptmairMatrices, 1e-10, Neumann=Expression( ("0", "0")), options="New") b_t = TrialFunction(Velocity) c_t = TestFunction(Velocity) ones = Function(Pressure) ones.vector()[:] = (0 * ones.vector().array() + 1) # pConst = - assemble(p_k*dx)/assemble(ones*dx) p_k.vector()[:] += -assemble(p_k * dx) / assemble(ones * dx) x = Iter.u_prev(u_k, p_k, b_k, r_k) KSPlinearfluids, MatrixLinearFluids = PrecondSetup.FluidLinearSetup( Pressure, MU) kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) #plot(b_k) ns, maxwell, CoupleTerm, Lmaxwell, Lns = forms.MHD2D( mesh, W, F_M, F_NS, u_k, b_k, params, IterType, "CG", Saddle, Stokes) RHSform = forms.PicardRHS(mesh, W, u_k, p_k, b_k, r_k, params, "CG", Saddle, Stokes) bcu = DirichletBC(W.sub(0), Expression(("0.0", "0.0")), boundary) bcb = DirichletBC(W.sub(2), Expression(("0.0", "0.0")), boundary) bcr = DirichletBC(W.sub(3), Expression(("0.0")), boundary) bcs = [bcu, bcb, bcr] parameters['linear_algebra_backend'] = 'uBLAS' eps = 1.0 # error measure ||u-u_k|| tol = 1.0E-4 # tolerance iter = 0 # iteration counter maxiter = 10 # max no of iterations allowed SolutionTime = 0 outer = 0 # parameters['linear_algebra_backend'] = 'uBLAS' # FSpaces = [Velocity,Magnetic,Pressure,Lagrange] if IterType == "CD": MO.PrintStr("Setting up PETSc " + SetupType, 2, "=", "\n", "\n") Alin = MHDsetup.Assemble(W, ns, maxwell, CoupleTerm, Lns, Lmaxwell, RHSform, bcs + BC, "Linear", IterType) Fnlin, b = MHDsetup.Assemble(W, ns, maxwell, CoupleTerm, Lns, Lmaxwell, RHSform, bcs + BC, "NonLinear", IterType) A = Fnlin + Alin A, b = MHDsetup.SystemAssemble(FSpaces, A, b, SetupType, IterType) u = b.duplicate() u_is = PETSc.IS().createGeneral(range(Velocity.dim())) NS_is = PETSc.IS().createGeneral(range(Velocity.dim() + Pressure.dim())) M_is = PETSc.IS().createGeneral( range(Velocity.dim() + Pressure.dim(), W.dim())) OuterTol = 1e-5 InnerTol = 1e-5 NSits = 0 Mits = 0 TotalStart = time.time() SolutionTime = 0 while eps > tol and iter < maxiter: iter += 1 MO.PrintStr("Iter " + str(iter), 7, "=", "\n\n", "\n\n") AssembleTime = time.time() if IterType == "CD": MO.StrTimePrint("MHD CD RHS assemble, time: ", time.time() - AssembleTime) b = MHDsetup.Assemble(W, ns, maxwell, CoupleTerm, Lns, Lmaxwell, RHSform, bcs + BC, "CD", IterType) else: MO.PrintStr("Setting up PETSc " + SetupType, 2, "=", "\n", "\n") if Split == "Yes": if iter == 1: Alin = MHDsetup.Assemble(W, ns, maxwell, CoupleTerm, Lns, Lmaxwell, RHSform, bcs + BC, "Linear", IterType) Fnlin, b = MHDsetup.Assemble(W, ns, maxwell, CoupleTerm, Lns, Lmaxwell, RHSform, bcs + BC, "NonLinear", IterType) A = Fnlin + Alin A, b = MHDsetup.SystemAssemble(FSpaces, A, b, SetupType, IterType) u = b.duplicate() else: Fnline, b = MHDsetup.Assemble(W, ns, maxwell, CoupleTerm, Lns, Lmaxwell, RHSform, bcs + BC, "NonLinear", IterType) A = Fnlin + Alin A, b = MHDsetup.SystemAssemble(FSpaces, A, b, SetupType, IterType) else: AA, bb = assemble_system(maxwell + ns + CoupleTerm, (Lmaxwell + Lns) - RHSform, bcs) A, b = CP.Assemble(AA, bb) # if iter == 1: MO.StrTimePrint("MHD total assemble, time: ", time.time() - AssembleTime) u = b.duplicate() kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) print "Inititial guess norm: ", u.norm( PETSc.NormType.NORM_INFINITY) #A,Q if IterType == 'Full': n = FacetNormal(mesh) mat = as_matrix([[b_k[1] * b_k[1], -b_k[1] * b_k[0]], [-b_k[1] * b_k[0], b_k[0] * b_k[0]]]) a = params[2] * inner(grad(b_t), grad(c_t)) * dx( W.mesh()) + inner((grad(b_t) * u_k), c_t) * dx(W.mesh( )) + (1. / 2) * div(u_k) * inner(c_t, b_t) * dx( W.mesh()) - (1. / 2) * inner(u_k, n) * inner( c_t, b_t) * ds(W.mesh()) + kappa / Mu_m * inner( mat * b_t, c_t) * dx(W.mesh()) ShiftedMass = assemble(a) bcu.apply(ShiftedMass) ShiftedMass = CP.Assemble(ShiftedMass) kspF = NSprecondSetup.LSCKSPnonlinear(ShiftedMass) else: F = A.getSubMatrix(u_is, u_is) kspF = NSprecondSetup.LSCKSPnonlinear(F) aVec, L_M, L_NS, Bt, CoupleT = forms.MHDmatvec(mesh, W, Laplacian, Laplacian, u_k, b_k, u, b, p, r, params, "Full", "CG", SaddlePoint="No") bcu = DirichletBC(Velocity, u0, boundary) PrecondTmult = {'Bt': Bt, 'Ct': CoupleT, 'BC': bcu} FS = { 'velocity': Velocity, 'pressure': Pressure, 'magnetic': Magnetic, 'multiplier': Lagrange } P = PETSc.Mat().createPython([W.dim(), W.dim()]) P.setType('python') aa = MHDmulti.PetscMatVec(FS, aVec, bcs, PrecondTmult) P.setPythonContext(aa) P.setUp() stime = time.time() u, mits, nsits = S.solve(A, P, b, u, params, W, 'Directsss', IterType, OuterTol, InnerTol, HiptmairMatrices, Hiptmairtol, KSPlinearfluids, Fp, kspF) Soltime = time.time() - stime MO.StrTimePrint("MHD solve, time: ", Soltime) Mits += mits NSits += nsits SolutionTime += Soltime u1, p1, b1, r1, eps = Iter.PicardToleranceDecouple( u, x, FSpaces, dim, "2", iter) p1.vector()[:] += -assemble(p1 * dx) / assemble(ones * dx) u_k.assign(u1) p_k.assign(p1) b_k.assign(b1) r_k.assign(r1) uOld = np.concatenate((u_k.vector().array(), p_k.vector().array(), b_k.vector().array(), r_k.vector().array()), axis=0) x = IO.arrayToVec(uOld) XX = np.concatenate((u_k.vector().array(), p_k.vector().array(), b_k.vector().array(), r_k.vector().array()), axis=0) SolTime[xx - 1] = SolutionTime / iter NSave[xx - 1] = (float(NSits) / iter) Mave[xx - 1] = (float(Mits) / iter) iterations[xx - 1] = iter TotalTime[xx - 1] = time.time() - TotalStart # dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(),Lagrange.dim()] # ExactSolution = [u0,p0,b0,r0] # errL2u[xx-1], errH1u[xx-1], errL2p[xx-1], errL2b[xx-1], errCurlb[xx-1], errL2r[xx-1], errH1r[xx-1] = Iter.Errors(XX,mesh,FSpaces,ExactSolution,order,dim, "DG") # if xx > 1: # l2uorder[xx-1] = np.abs(np.log2(errL2u[xx-2]/errL2u[xx-1])) # H1uorder[xx-1] = np.abs(np.log2(errH1u[xx-2]/errH1u[xx-1])) # l2porder[xx-1] = np.abs(np.log2(errL2p[xx-2]/errL2p[xx-1])) # l2border[xx-1] = np.abs(np.log2(errL2b[xx-2]/errL2b[xx-1])) # Curlborder[xx-1] = np.abs(np.log2(errCurlb[xx-2]/errCurlb[xx-1])) # l2rorder[xx-1] = np.abs(np.log2(errL2r[xx-2]/errL2r[xx-1])) # H1rorder[xx-1] = np.abs(np.log2(errH1r[xx-2]/errH1r[xx-1])) # import pandas as pd # LatexTitles = ["l","DoFu","Dofp","V-L2","L2-order","V-H1","H1-order","P-L2","PL2-order"] # LatexValues = np.concatenate((level,Velocitydim,Pressuredim,errL2u,l2uorder,errH1u,H1uorder,errL2p,l2porder), axis=1) # LatexTable = pd.DataFrame(LatexValues, columns = LatexTitles) # pd.set_option('precision',3) # LatexTable = MO.PandasFormat(LatexTable,"V-L2","%2.4e") # LatexTable = MO.PandasFormat(LatexTable,'V-H1',"%2.4e") # LatexTable = MO.PandasFormat(LatexTable,"H1-order","%1.2f") # LatexTable = MO.PandasFormat(LatexTable,'L2-order',"%1.2f") # LatexTable = MO.PandasFormat(LatexTable,"P-L2","%2.4e") # LatexTable = MO.PandasFormat(LatexTable,'PL2-order',"%1.2f") # print LatexTable # print "\n\n Magnetic convergence" # MagneticTitles = ["l","B DoF","R DoF","B-L2","L2-order","B-Curl","HCurl-order"] # MagneticValues = np.concatenate((level,Magneticdim,Lagrangedim,errL2b,l2border,errCurlb,Curlborder),axis=1) # MagneticTable= pd.DataFrame(MagneticValues, columns = MagneticTitles) # pd.set_option('precision',3) # MagneticTable = MO.PandasFormat(MagneticTable,"B-Curl","%2.4e") # MagneticTable = MO.PandasFormat(MagneticTable,'B-L2',"%2.4e") # MagneticTable = MO.PandasFormat(MagneticTable,"L2-order","%1.2f") # MagneticTable = MO.PandasFormat(MagneticTable,'HCurl-order',"%1.2f") # print MagneticTable # print "\n\n Lagrange convergence" # LagrangeTitles = ["l","B DoF","R DoF","R-L2","L2-order","R-H1","H1-order"] # LagrangeValues = np.concatenate((level,Lagrangedim,Lagrangedim,errL2r,l2rorder,errH1r,H1rorder),axis=1) # LagrangeTable= pd.DataFrame(LagrangeValues, columns = LagrangeTitles) # pd.set_option('precision',3) # LagrangeTable = MO.PandasFormat(LagrangeTable,"R-L2","%2.4e") # LagrangeTable = MO.PandasFormat(LagrangeTable,'R-H1',"%2.4e") # LagrangeTable = MO.PandasFormat(LagrangeTable,"L2-order","%1.2f") # LagrangeTable = MO.PandasFormat(LagrangeTable,'H1-order',"%1.2f") # print LagrangeTable import pandas as pd print "\n\n Iteration table" if IterType == "Full": IterTitles = [ "l", "DoF", "AV solve Time", "Total picard time", "picard iterations", "Av Outer its", "Av Inner its", ] else: IterTitles = [ "l", "DoF", "AV solve Time", "Total picard time", "picard iterations", "Av NS iters", "Av M iters" ] IterValues = np.concatenate( (level, Wdim, SolTime, TotalTime, iterations, Mave, NSave), axis=1) IterTable = pd.DataFrame(IterValues, columns=IterTitles) if IterType == "Full": IterTable = MO.PandasFormat(IterTable, 'Av Outer its', "%2.1f") IterTable = MO.PandasFormat(IterTable, 'Av Inner its', "%2.1f") else: IterTable = MO.PandasFormat(IterTable, 'Av NS iters', "%2.1f") IterTable = MO.PandasFormat(IterTable, 'Av M iters', "%2.1f") print IterTable print " \n Outer Tol: ", OuterTol, "Inner Tol: ", InnerTol # tableName = "2d_nu="+str(MU)+"_nu_m="+str(Mu_m)+"_kappa="+str(kappa)+"_l="+str(np.min(level))+"-"+str(np.max(level))+".tex" # IterTable.to_latex(tableName) # # # if (ShowResultPlots == 'yes'): # plot(u_k) # plot(interpolate(u0,Velocity)) # # plot(p_k) # # plot(interpolate(p0,Pressure)) # # plot(b_k) # plot(interpolate(b0,Magnetic)) # # plot(r_k) # plot(interpolate(r0,Lagrange)) # # interactive() interactive()
def PicardToleranceDecouple(x, U, FSpaces, dim, NormType, iter, SaddlePoint="No"): X = IO.vecToArray(x) uu = X[0:dim[0]] if SaddlePoint == "Yes": bb = X[dim[0]:dim[0] + dim[1]] pp = X[dim[0] + dim[1]:dim[0] + dim[1] + dim[2]] else: pp = X[dim[0]:dim[0] + dim[1]] bb = X[dim[0] + dim[1]:dim[0] + dim[1] + dim[2]] rr = X[dim[0] + dim[1] + dim[2]:] u = Function(FSpaces[0]) u.vector()[:] = uu u_ = assemble(inner(u, u) * dx) diffu = u.vector().array() # if SaddlePoint == "Yes": # p = Function(FSpaces[2]) # p.vector()[:] = pp # ones = Function(FSpaces[2]) # ones.vector()[:]=(0*ones.vector().array()+1) # pp = Function(FSpaces[2]) # print ones # pp.vector()[:] = p.vector().array()- assemble(p*dx)/assemble(ones*dx) # p = pp.vector().array() # b = Function(FSpaces[1]) # b.vector()[:] = bb # diffb = b.vector().array() # else: print pp.shape p = Function(FSpaces[1]) print FSpaces[1].dim() p.vector()[:] = pp p_ = assemble(p * p * dx) ones = Function(FSpaces[1]) ones.vector()[:] = (0 * ones.vector().array() + 1) pp = Function(FSpaces[1]) pp.vector( )[:] = p.vector().array() - assemble(p * dx) / assemble(ones * dx) p_ = assemble(pp * pp * dx) p = pp.vector().array() b = Function(FSpaces[2]) b.vector()[:] = bb b_ = assemble(inner(b, b) * dx) diffb = b.vector().array() r = Function(FSpaces[3]) r.vector()[:] = rr r_ = assemble(r * r * dx) # print diffu if (NormType == '2'): epsu = splin.norm(diffu) / sqrt(dim[0]) epsp = splin.norm(pp.vector().array()) / sqrt(dim[1]) epsb = splin.norm(diffb) / sqrt(dim[2]) epsr = splin.norm(r.vector().array()) / sqrt(dim[3]) elif (NormType == 'inf'): epsu = splin.norm(diffu, ord=np.Inf) epsp = splin.norm(pp.vector().array(), ord=np.inf) epsb = splin.norm(diffb, ord=np.Inf) epsr = splin.norm(r.vector().array(), ord=np.inf) else: print "NormType must be 2 or inf" quit() # U.axpy(1,x) p = Function(FSpaces[1]) RHS = IO.vecToArray(U + x) if SaddlePoint == "Yes": u.vector()[:] = RHS[0:dim[0]] p.vector()[:] = pp.vector().array() + U.array[dim[0] + dim[1]:dim[0] + dim[1] + dim[2]] b.vector()[:] = RHS[dim[0]:dim[0] + dim[1]] r.vector()[:] = RHS[dim[0] + dim[1] + dim[2]:] else: u.vector()[:] = RHS[0:dim[0]] p.vector()[:] = pp.vector().array() + U.array[dim[0]:dim[0] + dim[1]] b.vector()[:] = RHS[dim[0] + dim[1]:dim[0] + dim[1] + dim[2]] r.vector()[:] = RHS[dim[0] + dim[1] + dim[2]:] # print diffu.dot(diffu) + pp.dot(pp) + diffb.dot(diffb) + r.dot(r) # epsu = sqrt(u_)/sqrt(dim[0]) # epsp = sqrt(p_)/sqrt(dim[1]) # epsb = sqrt(b_)/sqrt(dim[2]) # epsr = sqrt(r_)/sqrt(dim[3]) # uOld = np.concatenate((diffu, pp.vector().array(), diffb, r.vector().array()), axis=0) # print np.linalg.norm(uOld)/sum(dim) print 'u-norm=%g p-norm=%g \n b-norm=%g r-norm=%g' % ( epsu, epsp, epsb, epsr), '\n\n\n' print 'u-norm=%g p-norm=%g \n b-norm=%g r-norm=%g' % ( sqrt(u_), sqrt(p_), sqrt(b_), sqrt(r_)), '\n\n\n' return u, p, b, r, epsu + epsp + epsb + epsr
u, mits,nsits = S.solve(A,b,u,params,W,'Direct',IterType,OuterTol,InnerTol,HiptmairMatrices,Hiptmairtol,KSPlinearfluids, Fp,kspF) U = u Soltime = time.time() - stime MO.StrTimePrint("MHD solve, time: ", Soltime) Mits += mits NSits += mits SolutionTime += Soltime # u = IO.arrayToVec(u) f = Function(W) f.vector()[:] = u.array f = f.vector() for bc in bcs: bc.apply(f) u = IO.arrayToVec(f.array()) u1 = Function(VelocityF) p1 = Function(PressureF) b1 = Function(MagneticF) r1 = Function(LagrangeF) u1.vector()[:] = u.getSubVector(u_is).array p1.vector()[:] = u.getSubVector(p_is).array b1.vector()[:] = u.getSubVector(b_is).array r1.vector()[:] = u.getSubVector(r_is).array p1.vector()[:] += - assemble(p1*dx)/assemble(ones*dx) u_k.assign(u1) p_k.assign(p1) b_k.assign(b1)
def u_prev(u, p, b, r): uOld = np.concatenate((u.vector().array(), p.vector().array(), b.vector().array(), r.vector().array()), axis=0) x = IO.arrayToVec(uOld) return x
ksp.solve(b,u) Soltime = time.time()- stime NSits += ksp.its # Mits +=dodim u = u*scale SolutionTime = SolutionTime +Soltime MO.PrintStr("Number of iterations ="+str(ksp.its),60,"+","\n\n","\n\n") u1, p1, b1, r1, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter, SaddlePoint = "Yes") p1.vector()[:] += - assemble(p1*dx)/assemble(ones*dx) u_k.assign(u1) p_k.assign(p1) b_k.assign(b1) r_k.assign(r1) uOld= np.concatenate((u_k.vector().array(),b_k.vector().array(),p_k.vector().array(),r_k.vector().array()), axis=0) x = IO.arrayToVec(uOld) XX= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0) SolTime[xx-1] = SolutionTime/iter NSave[xx-1] = (float(NSits)/iter) Mave[xx-1] = (float(Mits)/iter) iterations[xx-1] = iter TotalTime[xx-1] = time.time() - TotalStart print SolTime import pandas as pd
def foo(): m = 2 errL2u =np.zeros((m-1,1)) errH1u =np.zeros((m-1,1)) errL2p =np.zeros((m-1,1)) errL2b =np.zeros((m-1,1)) errCurlb =np.zeros((m-1,1)) errL2r =np.zeros((m-1,1)) errH1r =np.zeros((m-1,1)) l2uorder = np.zeros((m-1,1)) H1uorder =np.zeros((m-1,1)) l2porder = np.zeros((m-1,1)) l2border = np.zeros((m-1,1)) Curlborder =np.zeros((m-1,1)) l2rorder = np.zeros((m-1,1)) H1rorder = np.zeros((m-1,1)) NN = np.zeros((m-1,1)) DoF = np.zeros((m-1,1)) Velocitydim = np.zeros((m-1,1)) Magneticdim = np.zeros((m-1,1)) Pressuredim = np.zeros((m-1,1)) Lagrangedim = np.zeros((m-1,1)) Wdim = np.zeros((m-1,1)) iterations = np.zeros((m-1,1)) SolTime = np.zeros((m-1,1)) udiv = np.zeros((m-1,1)) MU = np.zeros((m-1,1)) level = np.zeros((m-1,1)) NSave = np.zeros((m-1,1)) Mave = np.zeros((m-1,1)) TotalTime = np.zeros((m-1,1)) nn = 2 dim = 2 ShowResultPlots = 'yes' split = 'Linear' MU[0]= 1e0 for xx in xrange(1,m): print xx level[xx-1] = xx+ 10 nn = 2**(level[xx-1]) # Create mesh and define function space nn = int(nn) NN[xx-1] = nn/2 # parameters["form_compiler"]["quadrature_degree"] = 6 # parameters = CP.ParameterSetup() mesh = UnitSquareMesh(nn,nn) order = 1 parameters['reorder_dofs_serial'] = False Velocity = VectorFunctionSpace(mesh, "CG", order) Pressure = FunctionSpace(mesh, "DG", order-1) Magnetic = FunctionSpace(mesh, "N1curl", order) Lagrange = FunctionSpace(mesh, "CG", order) W = MixedFunctionSpace([Velocity,Magnetic, Pressure, Lagrange]) # W = Velocity*Pressure*Magnetic*Lagrange Velocitydim[xx-1] = Velocity.dim() Pressuredim[xx-1] = Pressure.dim() Magneticdim[xx-1] = Magnetic.dim() Lagrangedim[xx-1] = Lagrange.dim() Wdim[xx-1] = W.dim() print "\n\nW: ",Wdim[xx-1],"Velocity: ",Velocitydim[xx-1],"Pressure: ",Pressuredim[xx-1],"Magnetic: ",Magneticdim[xx-1],"Lagrange: ",Lagrangedim[xx-1],"\n\n" dim = [Velocity.dim(), Magnetic.dim(), Pressure.dim(), Lagrange.dim()] def boundary(x, on_boundary): return on_boundary u0, p0,b0, r0, Laplacian, Advection, gradPres,CurlCurl, gradR, NS_Couple, M_Couple = ExactSol.MHD2D(4,1) bcu = DirichletBC(W.sub(0),u0, boundary) bcb = DirichletBC(W.sub(1),b0, boundary) bcr = DirichletBC(W.sub(3),r0, boundary) # bc = [u0,p0,b0,r0] bcs = [bcu,bcb,bcr] FSpaces = [Velocity,Pressure,Magnetic,Lagrange] (u, b, p, r) = TrialFunctions(W) (v, c, q, s) = TestFunctions(W) kappa = 1.0 Mu_m =1e1 MU = 1.0/1 IterType = 'Full' F_NS = -MU*Laplacian+Advection+gradPres-kappa*NS_Couple if kappa == 0: F_M = Mu_m*CurlCurl+gradR -kappa*M_Couple else: F_M = Mu_m*kappa*CurlCurl+gradR -kappa*M_Couple params = [kappa,Mu_m,MU] # MO.PrintStr("Preconditioning MHD setup",5,"+","\n\n","\n\n") HiptmairMatrices = PrecondSetup.MagneticSetup(Magnetic, Lagrange, b0, r0, 1e-5, params) MO.PrintStr("Setting up MHD initial guess",5,"+","\n\n","\n\n") u_k,p_k,b_k,r_k = common.InitialGuess(FSpaces,[u0,p0,b0,r0],[F_NS,F_M],params,HiptmairMatrices,1e-6,Neumann=Expression(("0","0")),options ="New", FS = "DG") #plot(p_k, interactive = True) b_t = TrialFunction(Velocity) c_t = TestFunction(Velocity) #print assemble(inner(b,c)*dx).array().shape #print mat #ShiftedMass = assemble(inner(mat*b,c)*dx) #as_vector([inner(b,c)[0]*b_k[0],inner(b,c)[1]*(-b_k[1])]) ones = Function(Pressure) ones.vector()[:]=(0*ones.vector().array()+1) # pConst = - assemble(p_k*dx)/assemble(ones*dx) p_k.vector()[:] += - assemble(p_k*dx)/assemble(ones*dx) x = Iter.u_prev(u_k,b_k,p_k,r_k) KSPlinearfluids, MatrixLinearFluids = PrecondSetup.FluidLinearSetup(Pressure, MU) kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) #plot(b_k) ns,maxwell,CoupleTerm,Lmaxwell,Lns = forms.MHD2D(mesh, W,F_M,F_NS, u_k,b_k,params,IterType,"DG", SaddlePoint = "Yes") RHSform = forms.PicardRHS(mesh, W, u_k, p_k, b_k, r_k, params,"DG",SaddlePoint = "Yes") bcu = DirichletBC(W.sub(0),Expression(("0.0","0.0")), boundary) bcb = DirichletBC(W.sub(1),Expression(("0.0","0.0")), boundary) bcr = DirichletBC(W.sub(3),Expression(("0.0")), boundary) bcs = [bcu,bcb,bcr] eps = 1.0 # error measure ||u-u_k|| tol = 1.0E-4 # tolerance iter = 0 # iteration counter maxiter = 40 # max no of iterations allowed SolutionTime = 0 outer = 0 # parameters['linear_algebra_backend'] = 'uBLAS' # FSpaces = [Velocity,Magnetic,Pressure,Lagrange] if IterType == "CD": AA, bb = assemble_system(maxwell+ns, (Lmaxwell + Lns) - RHSform, bcs) A,b = CP.Assemble(AA,bb) # u = b.duplicate() # P = CP.Assemble(PP) u_is = PETSc.IS().createGeneral(range(Velocity.dim())) NS_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim())) M_is = PETSc.IS().createGeneral(range(Velocity.dim()+Pressure.dim(),W.dim())) OuterTol = 1e-5 InnerTol = 1e-3 NSits =0 Mits =0 TotalStart =time.time() SolutionTime = 0 while eps > tol and iter < maxiter: iter += 1 MO.PrintStr("Iter "+str(iter),7,"=","\n\n","\n\n") tic() if IterType == "CD": bb = assemble((Lmaxwell + Lns) - RHSform) for bc in bcs: bc.apply(bb) FF = AA.sparray()[0:dim[0],0:dim[0]] A,b = CP.Assemble(AA,bb) # if iter == 1 if iter == 1: u = b.duplicate() F = A.getSubMatrix(u_is,u_is) kspF = NSprecondSetup.LSCKSPnonlinear(F) else: AA, bb = assemble_system(maxwell+ns+CoupleTerm, (Lmaxwell + Lns) - RHSform, bcs) A,b = CP.Assemble(AA,bb) del AA, bb n = FacetNormal(mesh) mat = as_matrix([[b_k[1]*b_k[1],-b_k[1]*b_k[0]],[-b_k[1]*b_k[0],b_k[0]*b_k[0]]]) F = A.getSubMatrix(u_is,u_is) a = params[2]*inner(grad(b_t), grad(c_t))*dx(W.mesh()) + inner((grad(b_t)*u_k),c_t)*dx(W.mesh()) +(1/2)*div(u_k)*inner(c_t,b_t)*dx(W.mesh()) - (1/2)*inner(u_k,n)*inner(c_t,b_t)*ds(W.mesh())+kappa/Mu_m*inner(mat*b_t,c_t)*dx(W.mesh()) ShiftedMass = assemble(a) bcu.apply(ShiftedMass) #MO.StoreMatrix(AA.sparray()[0:dim[0],0:dim[0]]+ShiftedMass.sparray(),"A") kspF = NSprecondSetup.LSCKSPnonlinear(F) # if iter == 1: if iter == 1: u = b.duplicate() print ("{:40}").format("MHD assemble, time: "), " ==> ",("{:4f}").format(toc()), ("{:9}").format(" time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5]) kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k) print "Inititial guess norm: ", u.norm() solver = 'Schur' if solver == 'Schur': FF = CP.Assemble(ShiftedMass) kspF = NSprecondSetup.LSCKSPnonlinear(FF) ksp = PETSc.KSP() ksp.create(comm=PETSc.COMM_WORLD) pc = ksp.getPC() ksp.setType('fgmres') pc.setType('python') pc.setType(PETSc.PC.Type.PYTHON) # FSpace = [Velocity,Magnetic,Pressure,Lagrange] reshist = {} def monitor(ksp, its, fgnorm): reshist[its] = fgnorm print its," OUTER:", fgnorm # ksp.setMonitor(monitor) ksp.max_it = 1000 FFSS = [Velocity,Magnetic,Pressure,Lagrange] pc.setPythonContext(MHDpreconditioner.InnerOuterMAGNETICapprox(FFSS,kspF, KSPlinearfluids[0], KSPlinearfluids[1],Fp, HiptmairMatrices[3], HiptmairMatrices[4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6],1e-5,FF)) #OptDB = PETSc.Options() # OptDB['pc_factor_mat_solver_package'] = "mumps" # OptDB['pc_factor_mat_ordering_type'] = "rcm" # ksp.setFromOptions() scale = b.norm() b = b/scale ksp.setOperators(A,A) del A stime = time.time() ksp.solve(b,u) Soltime = time.time()- stime NSits += ksp.its Mits += ksp.its # Mits +=dodim u = u*scale SolutionTime = SolutionTime +Soltime MO.PrintStr("Number iterations ="+str(ksp.its),60,"+","\n\n","\n\n") MO.PrintStr("Time: "+str(Soltime),60,"+","\n\n","\n\n") else: kspOuter = PETSc.KSP() kspOuter.create(comm=PETSc.COMM_WORLD) FFSS = [Velocity,Magnetic,Pressure,Lagrange] kspOuter.setType('fgmres') kspOuter.setOperators(A,A) pcOuter = kspOuter.getPC() pcOuter.setType(PETSc.PC.Type.KSP) kspInner = pcOuter.getKSP() kspInner.setType('gmres') pcInner = kspInner.getPC() # FSpace = [Velocity,Magnetic,Pressure,Lagrange] reshist = {} def monitor(ksp, its, fgnorm): reshist[its] = fgnorm print its," OUTER:", fgnorm kspOuter.setMonitor(monitor) kspOuter.max_it = 500 kspInner.max_it = 100 kspOuter.setTolerances(OuterTol) kspInner.setTolerances(InnerTol) pcInner.setType('python') pcInner.setPythonContext(MHDpreconditioner.InnerOuter(A,FFSS,kspF, KSPlinearfluids[0], KSPlinearfluids[1],Fp, HiptmairMatrices[3], HiptmairMatrices[4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6],1e-4,F)) # OptDB = PETSc.Options() PP = PETSc.Mat().create() PP.setSizes([A.size[0], A.size[0]]) #PP = PETSc.Mat().createPython([A.size[0], A.size[0]]) PP.setType('python') pp = MHDmulti.P(FFSS,A,MatrixLinearFluids[1],MatrixLinearFluids[0],kspFp,HiptmairMatrices[6]) PP.setPythonContext(pp) PP.setUp() kspInner.setOperators(PP,PP) kspInner.setFromOptions() scale = b.norm() b = b/scale del A stime = time.time() kspOuter.solve(b,u) Soltime = time.time()- stime NSits += kspOuter.its Mits += kspInner.its u = u*scale SolutionTime = SolutionTime +Soltime MO.PrintStr("Number of outer iterations ="+str(kspOuter.its),60,"+","\n\n","\n\n") MO.PrintStr("Number of inner iterations ="+str(kspInner.its),60,"+","\n\n","\n\n") u1, p1, b1, r1, eps= Iter.PicardToleranceDecouple(u,x,FSpaces,dim,"2",iter, SaddlePoint = "Yes") p1.vector()[:] += - assemble(p1*dx)/assemble(ones*dx) u_k.assign(u1) p_k.assign(p1) b_k.assign(b1) r_k.assign(r1) uOld= np.concatenate((u_k.vector().array(),b_k.vector().array(),p_k.vector().array(),r_k.vector().array()), axis=0) x = IO.arrayToVec(uOld) XX= np.concatenate((u_k.vector().array(),p_k.vector().array(),b_k.vector().array(),r_k.vector().array()), axis=0) SolTime[xx-1] = SolutionTime/iter NSave[xx-1] = (float(NSits)/iter) Mave[xx-1] = (float(Mits)/iter) iterations[xx-1] = iter TotalTime[xx-1] = time.time() - TotalStart dim = [Velocity.dim(), Pressure.dim(), Magnetic.dim(),Lagrange.dim()] # # ExactSolution = [u0,p0,b0,r0] # errL2u[xx-1], errH1u[xx-1], errL2p[xx-1], errL2b[xx-1], errCurlb[xx-1], errL2r[xx-1], errH1r[xx-1] = Iter.Errors(XX,mesh,FSpaces,ExactSolution,order,dim, "DG") # # if xx > 1: # l2uorder[xx-1] = np.abs(np.log2(errL2u[xx-2]/errL2u[xx-1])) # H1uorder[xx-1] = np.abs(np.log2(errH1u[xx-2]/errH1u[xx-1])) # # l2porder[xx-1] = np.abs(np.log2(errL2p[xx-2]/errL2p[xx-1])) # # l2border[xx-1] = np.abs(np.log2(errL2b[xx-2]/errL2b[xx-1])) # Curlborder[xx-1] = np.abs(np.log2(errCurlb[xx-2]/errCurlb[xx-1])) # # l2rorder[xx-1] = np.abs(np.log2(errL2r[xx-2]/errL2r[xx-1])) # H1rorder[xx-1] = np.abs(np.log2(errH1r[xx-2]/errH1r[xx-1])) import pandas as pd # LatexTitles = ["l","DoFu","Dofp","V-L2","L2-order","V-H1","H1-order","P-L2","PL2-order"] # LatexValues = np.concatenate((level,Velocitydim,Pressuredim,errL2u,l2uorder,errH1u,H1uorder,errL2p,l2porder), axis=1) # LatexTable = pd.DataFrame(LatexValues, columns = LatexTitles) # pd.set_option('precision',3) # LatexTable = MO.PandasFormat(LatexTable,"V-L2","%2.4e") # LatexTable = MO.PandasFormat(LatexTable,'V-H1',"%2.4e") # LatexTable = MO.PandasFormat(LatexTable,"H1-order","%1.2f") # LatexTable = MO.PandasFormat(LatexTable,'L2-order',"%1.2f") # LatexTable = MO.PandasFormat(LatexTable,"P-L2","%2.4e") # LatexTable = MO.PandasFormat(LatexTable,'PL2-order',"%1.2f") # print LatexTable # # # print "\n\n Magnetic convergence" # MagneticTitles = ["l","B DoF","R DoF","B-L2","L2-order","B-Curl","HCurl-order"] # MagneticValues = np.concatenate((level,Magneticdim,Lagrangedim,errL2b,l2border,errCurlb,Curlborder),axis=1) # MagneticTable= pd.DataFrame(MagneticValues, columns = MagneticTitles) # pd.set_option('precision',3) # MagneticTable = MO.PandasFormat(MagneticTable,"B-Curl","%2.4e") # MagneticTable = MO.PandasFormat(MagneticTable,'B-L2',"%2.4e") # MagneticTable = MO.PandasFormat(MagneticTable,"L2-order","%1.2f") # MagneticTable = MO.PandasFormat(MagneticTable,'HCurl-order',"%1.2f") # print MagneticTable # # # # # import pandas as pd # print "\n\n Iteration table" if IterType == "Full": IterTitles = ["l","DoF","AV solve Time","Total picard time","picard iterations","Av Outer its","Av Inner its",] else: IterTitles = ["l","DoF","AV solve Time","Total picard time","picard iterations","Av NS iters","Av M iters"] IterValues = np.concatenate((level,Wdim,SolTime,TotalTime,iterations,NSave,Mave),axis=1) IterTable= pd.DataFrame(IterValues, columns = IterTitles) if IterType == "Full": IterTable = MO.PandasFormat(IterTable,'Av Outer its',"%2.1f") IterTable = MO.PandasFormat(IterTable,'Av Inner its',"%2.1f") else: IterTable = MO.PandasFormat(IterTable,'Av NS iters',"%2.1f") IterTable = MO.PandasFormat(IterTable,'Av M iters',"%2.1f") print IterTable.to_latex() print " \n Outer Tol: ",OuterTol, "Inner Tol: ", InnerTol # # # if (ShowResultPlots == 'yes'): # plot(u_k) # plot(interpolate(u0,Velocity)) # # plot(p_k) # # plot(interpolate(p0,Pressure)) # # plot(b_k) # plot(interpolate(b0,Magnetic)) # # plot(r_k) # plot(interpolate(r0,Lagrange)) # # interactive() interactive()