def Stokes(V, Q, F, params, boundaries, domains, mesh): parameters['reorder_dofs_serial'] = False W = FunctionSpace(mesh, MixedElement([V, Q])) IS = MO.IndexSet(W) mesh = W.mesh() (u, p) = TrialFunctions(W) (v, q) = TestFunctions(W) n = FacetNormal(W.mesh()) a11 = params[2]*inner(grad(v), grad(u))*dx('everywhere') a12 = -div(v)*p*dx('everywhere') a21 = -div(u)*q*dx('everywhere') a = a11+a12+a21 L = inner(v, F)*dx('everywhere') #+ inner(gradu0,v)*ds(2) def boundary(x, on_boundary): return on_boundary bcu1 = DirichletBC(W.sub(0), Expression(("0.0","0.0"), degree=4), boundaries, 1) bcu2 = DirichletBC(W.sub(0), Expression(("1.0","0.0"), degree=4), boundaries, 2) bcu = [bcu1, bcu2] A, b = assemble_system(a, L, bcu) A, b = CP.Assemble(A, b) pp = params[2]*inner(grad(v), grad(u))*dx + (1./params[2])*p*q*dx P, Pb = assemble_system(pp, L, bcu) P, Pb = CP.Assemble(P, Pb) u = b.duplicate() ksp = PETSc.KSP().create() ksp.setTolerances(1e-8) ksp.max_it = 200 pc = ksp.getPC() pc.setType(PETSc.PC.Type.PYTHON) ksp.setType('minres') pc.setPythonContext(StokesPrecond.Approx(W, 1)) ksp.setOperators(A,P) scale = b.norm() b = b/scale ksp.setOperators(A,A) del A start_time = time.time() ksp.solve(b,u) print ("{:40}").format("Stokes solve, time: "), " ==> ",("{:4f}").format(time.time() - start_time),("{:9}").format(" Its: "), ("{:4}").format(ksp.its), ("{:9}").format(" time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5]) u = u*scale u_k = Function(FunctionSpace(mesh, V)) p_k = Function(FunctionSpace(mesh, Q)) u_k.vector()[:] = u.getSubVector(IS[0]).array p_k.vector()[:] = u.getSubVector(IS[1]).array ones = Function(FunctionSpace(mesh, Q)) ones.vector()[:]=(0*ones.vector().array()+1) p_k.vector()[:] += -assemble(p_k*dx("everywhere"))/assemble(ones*dx("everywhere")) return u_k, p_k
def eigensApprox(A, W, PCD, KSPL, MX, FX): IS = IndexSet(W) Ct = A.getSubMatrix(IS[0], IS[1]) Dt = A.getSubMatrix(IS[1], IS[3]) Bt = A.getSubMatrix(IS[0], IS[2]) L = KSPL.getOperators() MX = CP.PETSc2Scipy(MX) FX = CP.PETSc2Scipy(FX) Ct = CP.PETSc2Scipy(Ct) Dt = CP.PETSc2Scipy(Dt) Bt = CP.PETSc2Scipy(Bt) L = CP.PETSc2Scipy(L[0]) Ap = CP.PETSc2Scipy(PCD[0]) Mp = CP.PETSc2Scipy(PCD[1]) Fp = CP.PETSc2Scipy(PCD[2]) A = CP.PETSc2Scipy(A) Fpinv = sp.linalg.inv(Fp) PCD = Mp * Fpinv * Ap # print P.toarray() # print P.shape # P = P.tocsc() P = sp.bmat([[FX, Ct, Bt, None], [None, MX, None, None], [None, None, -PCD, None], [None, None, None, L]]) return A, P
def FluidLinearSetup(Pressure, mu, mesh): MO.PrintStr("Preconditioning Fluid linear setup", 3, "=", "\n\n") # parameters['linear_algebra_backend'] = 'uBLAS' q = TrialFunction(Pressure) p = TestFunction(Pressure) tic() L = assemble(mu * inner(grad(q), grad(p)) * dx, form_compiler_parameters=ffc_options) L = CP.Assemble(L) print("{:40}").format("CG scalar Laplacian assemble, time: "), " ==> ", ( "{:4f}").format(toc()), ("{:9}").format(" time: "), ("{:4}").format( time.strftime('%X %x %Z')[0:5]) tic() Q = assemble((1. / mu) * inner(p, q) * dx, form_compiler_parameters=ffc_options) Q = CP.Assemble(Q) print( "{:40}").format("DG scalar mass matrix assemble, time: "), " ==> ", ( "{:4f}").format( toc()), ("{:9}").format(" time: "), ("{:4}").format( time.strftime('%X %x %Z')[0:5]) tic() kspL, kspQ = NSprecondSetup.PCDKSPlinear(L, Q) print("{:40}").format("Linear fluid precond setup, time: "), " ==> ", ( "{:4f}").format(toc()), ("{:9}").format(" time: "), ("{:4}").format( time.strftime('%X %x %Z')[0:5]) return [kspL, kspQ], [L, Q]
def FluidLinearSetup(Pressure,mu,mesh, boundaries, domains): MO.PrintStr("Preconditioning Fluid linear setup",3,"=","\n\n") # parameters['linear_algebra_backend'] = 'uBLAS' q = TrialFunction(Pressure) p = TestFunction(Pressure) dx = Measure('dx', domain=mesh, subdomain_data=domains) ds = Measure('ds', domain=mesh, subdomain_data=boundaries) N = FacetNormal(Pressure.mesh()) h = CellSize(Pressure.mesh()) h_avg =avg(h) alpha = 10.0 gamma =10.0 tic() if Pressure.__str__().find("CG") == -1: L = assemble(mu*(jump(q)*jump(p)*dx(Pressure.mesh()))) else: L = assemble(mu*(inner(grad(q), grad(p))*dx(Pressure.mesh())))# + inner(grad(q),N)*p*ds(2)) L = CP.Assemble(L) print ("{:40}").format("CG scalar Laplacian assemble, time: "), " ==> ",("{:4f}").format(toc()), ("{:9}").format(" time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5]) tic() Q = assemble((1./mu)*inner(p,q)*dx) Q = CP.Assemble(Q) print ("{:40}").format("DG scalar mass matrix assemble, time: "), " ==> ",("{:4f}").format(toc()), ("{:9}").format(" time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5]) tic() kspA, ksp = NSprecondSetup.PCDKSPlinear(Q, L) print ("{:40}").format("Linear fluid precond setup, time: "), " ==> ",("{:4f}").format(toc()), ("{:9}").format(" time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5]) return [kspA,ksp], [L,Q]
def MagneticSetup(Magnetic, Lagrange, u0, p0, CGtol,params): MO.PrintStr("Preconditioning Magnetic setup",3,"=") # parameters['linear_algebra_backend'] = 'uBLAS' if Magnetic.__str__().find("N1curl2") == -1: C, P = HiptmairSetup.HiptmairMatrixSetupBoundary(Magnetic.mesh(), Magnetic.dim(), Lagrange.dim(),Magnetic.mesh().geometry().dim()) G, P = HiptmairSetup.HiptmairBCsetupBoundary(C,P,Magnetic.mesh()) else: G = None P = None u = TrialFunction(Magnetic) v = TestFunction(Magnetic) p = TrialFunction(Lagrange) q = TestFunction(Lagrange) def boundary(x, on_boundary): return on_boundary bcp = DirichletBC(Lagrange, p0, boundary) bcu = DirichletBC(Magnetic, u0, boundary) tic() ScalarLaplacian, b1 = assemble_system(inner(grad(p),grad(q))*dx,inner(p0,q)*dx,bcp) VectorLaplacian, b2 = assemble_system(inner(grad(p),grad(q))*dx+inner(p,q)*dx,inner(p0,q)*dx,bcp) del b1, b2 print ("{:40}").format("Hiptmair Laplacians BC assembled, time: "), " ==> ",("{:4f}").format(toc()), ("{:9}").format(" time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5]) tic() VectorLaplacian = CP.Assemble(VectorLaplacian) ScalarLaplacian = CP.Assemble(ScalarLaplacian) print ("{:40}").format("PETSc Laplacians assembled, time: "), " ==> ",("{:4f}").format(toc()), ("{:9}").format(" time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5]) tic() if params[0] == 0: CurlCurlShift, b2 = assemble_system(params[1]*inner(curl(u),curl(v))*dx+inner(u,v)*dx,inner(u0,v)*dx,bcu) else: CurlCurlShift, b2 = assemble_system(params[0]*params[1]*inner(curl(u),curl(v))*dx+inner(u,v)*dx,inner(u0,v)*dx,bcu) CurlCurlShift = CP.Assemble(CurlCurlShift) print ("{:40}").format("Shifted Curl-Curl assembled, time: "), " ==> ",("{:4f}").format(toc()), ("{:9}").format(" time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5]) tic() kspVector, kspScalar, kspCGScalar, diag = HiptmairSetup.HiptmairKSPsetup(VectorLaplacian, ScalarLaplacian, CurlCurlShift, CGtol) del VectorLaplacian, ScalarLaplacian print ("{:40}").format("Hiptmair Setup time:"), " ==> ",("{:4f}").format(toc()), ("{:9}").format(" time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5]) return [G, P, kspVector, kspScalar, kspCGScalar, diag, CurlCurlShift]
def FluidNonLinearSetup(Pressure,mu, u_k): MO.PrintStr("Preconditioning Fluid linear setup",3,"=") # parameters['linear_algebra_backend'] = 'uBLAS' p = TrialFunction(Pressure) q = TestFunction(Pressure) mesh = Pressure.mesh() N = FacetNormal(Pressure.mesh()) h = CellSize(Pressure.mesh()) h_avg =avg(h) alpha = 10.0 gamma =10.0 tic() if Pressure.__str__().find("CG") == -1: Fp = assemble(mu*(jump(q)*jump(p)*dx(mesh)) \ + inner(inner(grad(p),u_k),q)*dx(mesh)- (1./2)*inner(u_k,N)*inner(q,p)*ds(mesh) \ -(1./2)*(inner(u_k('+'),N('+'))+inner(u_k('-'),N('-')))*avg(inner(q,p))*ds(mesh) \ -dot(avg(q),dot(outer(p('+'),N('+'))+outer(p('-'),N('-')),avg(u_k)))*dS(Pressure.mesh())) else: if mesh.topology().dim() == 2: Fp = assemble(mu*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)) else: Fp = assemble(mu*inner(grad(q), grad(p))*dx(mesh)+inner((u_k[0]*grad(p)[0]+u_k[1]*grad(p)[1]+u_k[2]*grad(p)[2]),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]+u_k[2]*N[2])*inner(p,q)*ds(mesh))# + (-mu*inner(grad(q),N)*p + inner(u_k, N)*q*p)*ds(2)) Fp = CP.Assemble(Fp) print ("{:40}").format("DG convection-diffusion assemble, time: "), " ==> ",("{:4f}").format(toc()), ("{:9}").format(" time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5]) tic() kspFp= NSprecondSetup.PCDKSPnonlinear(Fp) print ("{:40}").format("Non-linear fluid precond, time: "), " ==> ",("{:4f}").format(toc()), ("{:9}").format(" time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5]) print "\n\n" return kspFp, Fp
def Maxwell(V, Q, F, b0, r0, params, boundaries,HiptmairMatrices, Hiptmairtol): parameters['reorder_dofs_serial'] = False W = V*Q IS = MO.IndexSet(W) (b, r) = TrialFunctions(W) (c, s) = TestFunctions(W) a11 = params[1]*params[2]*inner(curl(b), curl(c))*dx('everywhere') a21 = inner(b,grad(s))*dx('everywhere') a12 = inner(c,grad(r))*dx('everywhere') L = inner(c, F)*dx('everywhere') a = a11+a12+a21 def boundary(x, on_boundary): return on_boundary bcb = DirichletBC(W.sub(0), b0, boundary) bcr = DirichletBC(W.sub(1), r0, boundary) bc = [bcb, bcr] A, b = assemble_system(a, L, bc) A, b = CP.Assemble(A, b) u = b.duplicate() ksp = PETSc.KSP() ksp.create(comm=PETSc.COMM_WORLD) pc = ksp.getPC() ksp.setType('preonly') pc.setType('lu') OptDB = PETSc.Options() if __version__ != '1.6.0': OptDB['pc_factor_mat_solver_package'] = "mumps" OptDB['pc_factor_mat_ordering_type'] = "rcm" ksp.setFromOptions() # ksp = PETSc.KSP().create() # ksp.setTolerances(1e-8) # ksp.max_it = 200 # pc = ksp.getPC() # pc.setType(PETSc.PC.Type.PYTHON) # ksp.setType('minres') # pc.setPythonContext(MP.Hiptmair(W, HiptmairMatrices[3], HiptmairMatrices[4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6],Hiptmairtol)) scale = b.norm() b = b/scale ksp.setOperators(A,A) del A start_time = time.time() ksp.solve(b,u) print ("{:40}").format("Maxwell solve, time: "), " ==> ",("{:4f}").format(time.time() - start_time),("{:9}").format(" Its: "), ("{:4}").format(ksp.its), ("{:9}").format(" time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5]) u = u*scale b_k = Function(V) r_k = Function(Q) b_k.vector()[:] = u.getSubVector(IS[0]).array r_k.vector()[:] = u.getSubVector(IS[1]).array return b_k, r_k
def Stokes(V, Q, F, u0, p0, gradu0, params, boundaries, domains): parameters['reorder_dofs_serial'] = False W = V * Q IS = MO.IndexSet(W) mesh = W.mesh() ds = Measure('ds', domain=mesh, subdomain_data=boundaries) dx = Measure('dx', domain=mesh) (u, p) = TrialFunctions(W) (v, q) = TestFunctions(W) n = FacetNormal(W.mesh()) a11 = params[2] * inner(grad(v), grad(u)) * dx('everywhere') a12 = -div(v) * p * dx('everywhere') a21 = -div(u) * q * dx('everywhere') a = a11 + a12 + a21 L = inner(v, F) * dx('everywhere') #+ inner(gradu0,v)*ds(2) def boundary(x, on_boundary): return on_boundary bcu = DirichletBC(W.sub(0), u0, boundary) A, b = assemble_system(a, L, bcu) A, b = CP.Assemble(A, b) # print b.array # sss u = b.duplicate() ksp = PETSc.KSP() ksp.create(comm=PETSc.COMM_WORLD) pc = ksp.getPC() ksp.setType('preonly') pc.setType('lu') OptDB = PETSc.Options() if __version__ != '1.6.0': OptDB['pc_factor_mat_solver_package'] = "mumps" OptDB['pc_factor_mat_ordering_type'] = "rcm" ksp.setFromOptions() # print b.array # bbb scale = b.norm() b = b / scale ksp.setOperators(A, A) del A ksp.solve(b, u) # Mits +=dodim u = u * scale u_k = Function(V) p_k = Function(Q) u_k.vector()[:] = u.getSubVector(IS[0]).array p_k.vector()[:] = u.getSubVector(IS[1]).array ones = Function(Q) ones.vector()[:] = (0 * ones.vector().array() + 1) p_k.vector()[:] += -assemble(p_k * dx('everywhere')) / assemble( ones * dx('everywhere')) return u_k, p_k
def HiptmairAnyOrder(Magnetic, Lagrange): mesh = Magnetic.mesh() VecLagrange = VectorFunctionSpace( mesh, "CG", Magnetic.__dict__['_FunctionSpace___degree']) def boundary(x, on_boundary): return on_boundary dim = mesh.geometry().dim() u0 = [] for i in range(dim): u0.append('0.0') u0 = Expression(u0) VecBC = DirichletBC(VecLagrange, u0, boundary) BCb = DirichletBC(Magnetic, u0, boundary) BCr = DirichletBC(Lagrange, Expression(('0.0')), boundary) p = TestFunction(Lagrange) q = TrialFunction(Lagrange) u = TestFunction(Magnetic) v = TrialFunction(Magnetic) Vu = TestFunction(VecLagrange) Vv = TrialFunction(VecLagrange) M = assemble(inner(u, v) * dx) # BCb.apply(M) B = assemble(inner(v, grad(p)) * dx) L = assemble(inner(grad(Vu), grad(Vv)) * dx + inner(Vu, Vv) * dx) l = assemble(inner(grad(p), grad(q)) * dx) VecBC.apply(L) BCr.apply(l) L = CP.Scipy2PETSc(L.sparray()) B = CP.Scipy2PETSc(B.sparray()) M = CP.Scipy2PETSc(M.sparray()) l = CP.Scipy2PETSc(l.sparray()) ksp = PETSc.KSP() ksp.create(comm=PETSc.COMM_WORLD) pc = ksp.getPC() ksp.setType('cg') pc.setType('bjacobi') ksp.setOperators(M, M) ksp.setTolerances(1e-8) return VecLagrange, ksp, L, l, B, [BCb, BCr, VecBC]
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 TensorMass(b_k, params, FS): MO.PrintStr("Tensor Mass matrix construction", 5, "=", "\n", "\n") b_t = TestFunction(FS) c_t = TrialFunction(FS) dim = FS.mesh().geometry().dim() def boundary(x, on_boundary): return on_boundary if dim == 2: u = Expression(("0.0", "0.0")) 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]]]) else: u = Expression(("0.0", "0.0", "0.0")) 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] ]]) bc = DirichletBC(FS, u, boundary) if FS.dolfin_element().signature().find("Lagrange") == -1: tic() # a = params[2]*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 ShiftedMass = assemble(a + params[0] * params[0] / params[2] * inner(mat * b_t, c_t) * dx) bc.apply(ShiftedMass) print( "{:40}").format("Magnetic mass construction, time: "), " ==> ", ( "{:4f}").format( toc()), ("{:9}").format(" time: "), ("{:4}").format( time.strftime('%X %x %Z')[0:5]) else: tic() ShiftedMass = assemble(params[0] / params[1] * inner(mat * b_t, c_t) * dx) bc.apply(ShiftedMass) print( "{:40}").format("Magnetic mass construction, time: "), " ==> ", ( "{:4f}").format( toc()), ("{:9}").format(" time: "), ("{:4}").format( time.strftime('%X %x %Z')[0:5]) print "\n\n" FF = CP.Assemble(ShiftedMass) return FF
def Maxwell(V, Q, F, b0, r0, params, boundaries): parameters['reorder_dofs_serial'] = False W = V*Q IS = MO.IndexSet(W) mesh = W.mesh() # dx = Measure('dx', domain=mesh) print params (u, p) = TrialFunctions(W) (v, q) = TestFunctions(W) n = FacetNormal(W.mesh()) a11 = params[1]*params[2]*inner(curl(v), curl(u))*dx('everywhere') a21 = inner(u,grad(q))*dx('everywhere') a12 = inner(v,grad(p))*dx('everywhere') L = inner(v, F)*dx('everywhere') a = a11+a12+a21 def boundary(x, on_boundary): return on_boundary bcb = DirichletBC(W.sub(0), b0, boundaries, 1) bcr = DirichletBC(W.sub(1), r0, boundaries, 1) bc = [bcb, bcr] A, b = assemble_system(a, L, bc) A, b = CP.Assemble(A, b) u = b.duplicate() 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 u_k = Function(V) p_k = Function(Q) u_k.vector()[:] = u.getSubVector(IS[0]).array p_k.vector()[:] = u.getSubVector(IS[1]).array # print u_k.vector().array() # sss return u_k, p_k
def Maxwell(V, Q, F, b0, r0, params, boundaries): parameters['reorder_dofs_serial'] = False W = V*Q IS = MO.IndexSet(W) mesh = W.mesh() # dx = Measure('dx', domain=mesh) print params (b, r) = TrialFunctions(W) (c, s) = TestFunctions(W) a11 = params[1]*params[2]*inner(curl(b), curl(c))*dx('everywhere') a21 = inner(b,grad(s))*dx('everywhere') a12 = inner(c,grad(r))*dx('everywhere') L = inner(curl(c), F)*dx('everywhere') a = a11+a12+a21 def boundary(x, on_boundary): return on_boundary bcb1 = DirichletBC(W.sub(0), b0, boundary) bcr = DirichletBC(W.sub(1), r0, boundary) bc = [bcb1, bcr] A, b = assemble_system(a, L, bc) # MO.StoreMatrix(A.sparray(),"A"+str(W.dim())) A, b = CP.Assemble(A, b) u = b.duplicate() ksp = PETSc.KSP() ksp.create(comm=PETSc.COMM_WORLD) pc = ksp.getPC() ksp.setType('preonly') pc.setType('lu') OptDB = PETSc.Options() if __version__ != '1.6.0': 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) u = u*scale b_k = Function(V) r_k = Function(Q) b_k.vector()[:] = u.getSubVector(IS[0]).array r_k.vector()[:] = u.getSubVector(IS[1]).array return b_k, r_k
def Maxwell(V, Q, F, params, HiptmairMatrices, Hiptmairtol, mesh): parameters['reorder_dofs_serial'] = False W = FunctionSpace(mesh, MixedElement([V, Q])) IS = MO.IndexSet(W) print params (b, r) = TrialFunctions(W) (c, s) = TestFunctions(W) a11 = params[1]*params[2]*inner(curl(b), curl(c))*dx('everywhere') a21 = inner(b,grad(s))*dx('everywhere') a12 = inner(c,grad(r))*dx('everywhere') L = inner(c, F)*dx('everywhere') a = a11+a12+a21 def boundary(x, on_boundary): return on_boundary bcb = DirichletBC(W.sub(0), Expression(("1.0","0.0"), degree=4), boundary) bcr = DirichletBC(W.sub(1), Expression(("0.0"), degree=4), boundary) bc = [bcb, bcr] A, b = assemble_system(a, L, bc) A, b = CP.Assemble(A, b) u = b.duplicate() ksp = PETSc.KSP().create() ksp.setTolerances(1e-8) ksp.max_it = 200 pc = ksp.getPC() pc.setType(PETSc.PC.Type.PYTHON) ksp.setType('minres') pc.setPythonContext(MP.Hiptmair(W, HiptmairMatrices[3], HiptmairMatrices[4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6],Hiptmairtol)) scale = b.norm() b = b/scale ksp.setOperators(A,A) del A start_time = time.time() ksp.solve(b,u) print ("{:40}").format("Maxwell solve, time: "), " ==> ",("{:4f}").format(time.time() - start_time),("{:9}").format(" Its: "), ("{:4}").format(ksp.its), ("{:9}").format(" time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5]) u = u*scale b_k = Function(FunctionSpace(mesh, V)) r_k = Function(FunctionSpace(mesh, Q)) b_k.vector()[:] = u.getSubVector(IS[0]).array r_k.vector()[:] = u.getSubVector(IS[1]).array return b_k, r_k
def Masstest(Lagrange, p0, tol): parameters['linear_algebra_backend'] = 'uBLAS' p = TrialFunction(Lagrange) q = TestFunction(Lagrange) def boundary(x, on_boundary): return on_boundary bc = DirichletBC(Lagrange, p0, boundary) Mass = assemble(inner(p, q) * dx) bc.apply(Mass) Mass = CP.Assemble(Mass) ksp = PETSc.KSP() ksp.create(comm=PETSc.COMM_WORLD) pc = ksp.getPC() ksp.setType('cg') pc.setType('bjacobi') ksp.setTolerances(tol) ksp.setOperators(Mass, Mass) return ksp
def eigens(A, W, PCD, L): IS = IndexSet(W) F = A.getSubMatrix(IS[0], IS[0]) Ct = A.getSubMatrix(IS[0], IS[1]) Dt = A.getSubMatrix(IS[1], IS[3]) M = A.getSubMatrix(IS[1], IS[1]) Bt = A.getSubMatrix(IS[0], IS[2]) C = A.getSubMatrix(IS[2], IS[2]) F = CP.PETSc2Scipy(F) Ct = CP.PETSc2Scipy(Ct) Dt = CP.PETSc2Scipy(Dt) Bt = CP.PETSc2Scipy(Bt) L = CP.PETSc2Scipy(L) M = CP.PETSc2Scipy(M) Ap = CP.PETSc2Scipy(PCD[0]) Mp = CP.PETSc2Scipy(PCD[1]) Fp = CP.PETSc2Scipy(PCD[2]) A = CP.PETSc2Scipy(A) C = CP.PETSc2Scipy(C) MO.StoreMatrix(Dt, "D") ssss Fpinv = sp.linalg.inv(Fp) Linv = sp.linalg.inv(L) MX = M + Dt * Linv * Dt.transpose() MXinv = sp.linalg.inv(MX) FX = F + Ct * MXinv * Ct.transpose() PCD = Mp * Fpinv * Ap Finv = sp.linalg.inv(F) PCD = -C + Bt.transpose() * Finv * Bt # print P.toarray() # print P.shape # P = P.tocsc() P = sp.bmat([[FX, Ct, Bt, None], [None, MX, None, None], [None, None, -PCD, None], [None, None, None, L]]) return A, P
bcr = DirichletBC(W.sub(3), Expression("0.0"), boundary) bcs = [bcu, bcb, bcr] # if iter == 1: # , L A, b = assemble_system(a, L, bcs) # AA = assemble(a) # bb = assemble(L) # for bc in bcs: # bc.apply(AA,bb) # print A.sparray().todense() # MO.StoreMatrix(A.sparray(),'name') A, b = CP.Assemble(A, b) u = b.duplicate() # print b.array # ssss # L = assemble(L) # print L.array() # for bc in bcs: # bc.apply(L) # print L.array() # 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
NS_is = PETSc.IS().createGeneral(range(Velocity.dim() + Pressure.dim())) M_is = PETSc.IS().createGeneral( range(Velocity.dim() + Pressure.dim(), W.dim())) PP, Pb = assemble_system(p, Lns, bcs) if IterType == "Full" or IterType == "MD": (pQ) = TrialFunction(Pressure) (qQ) = TestFunction(Pressure) print MU Q = assemble(inner(pQ, qQ) * dx) L = assemble(inner(grad(pQ), grad(qQ)) * dx) n = FacetNormal(mesh) fp = MU * inner(grad(qQ), grad(pQ)) * dx + inner( (u_k[0] * grad(pQ)[0] + u_k[1] * grad(pQ)[1]), qQ) * dx + (1 / 2) * div(u_k) * inner(pQ, qQ) * dx - (1 / 2) * ( u_k[0] * n[0] + u_k[1] * n[1]) * inner(pQ, qQ) * ds L = CP.Assemble(L) if IterType == "CD": AA, bb = assemble_system(maxwell + ns + CoupleTerm, (Lmaxwell + Lns) - RHSform, bcs) A, b = CP.Assemble(AA, bb) # del AA, bb P = CP.Assemble(PP) u = b.duplicate() NSits = 0 Mits = 0 TotalStart = t.clock() while eps > tol and iter < maxiter: iter += 1 if IterType == "CD":
(v) = TrialFunction(V) (u) = TestFunction(V) (uMix,pMix) = TrialFunctions(W) (vMix,qMix) = TestFunctions(W) CurlCurl = Expression(("-6*x[1]+2","-6*x[0]+2"))+b0 f = CurlCurl m = inner(u,v)*dx b = inner(vMix,grad(pMix))*dx parameters['linear_algebra_backend'] = 'uBLAS' M = assemble(m) # bcb.apply(A) # bcb.apply(M) M = CP.Assemble(M) # B = assemble(b) # B = B.sparray()[W.dim()-V.dim():,W.dim()-Q.dim():] # ksp = PETSc.KSP().create() # ksp.setOperators(M) # x = M.getVecLeft() # ksp.setFromOptions() # ksp.setType(ksp.Type.CG) # ksp.setTolerances(1e-1) # ksp.pc.setType(ksp.pc.Type.BJACOBI) # OptDB = PETSc.Options()
# u = b.duplicate() # P = CP.Assemble(PP) while eps > tol and iter < maxiter: iter += 1 if IterType == "CD": bb = assemble((Lmaxwell + Lns) - RHSform) # for bc in bcs: # bc.apply(bb) # A,b = CP.Assemble(AA,bb) # u = b.duplicate() else: AA, bb = assemble_system(maxwell + ns + CoupleTerm, (Lmaxwell + Lns) - RHSform, bcs) A, b = CP.Assemble(AA, bb) u = b.duplicate() ksp = PETSc.KSP().create() pc = ksp.getPC() #.PC().create() ksp.setOperators(A) OptDB = PETSc.Options() OptDB["ksp_type"] = "preonly" OptDB["pc_type"] = "lu" OptDB["pc_factor_mat_ordering_type"] = "amd" OptDB["pc_factor_mat_solver_package"] = "mumps" # OptDB["pc_factor_shift_amount"] = 2
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()
MO.PrintStr("Fluid coupling test: Dirichlet only", 2, "=", "\n\n", "\n") bcu = DirichletBC(W.sub(0), u0, boundary) bcb = DirichletBC(W.sub(1), b0, boundary) bc = [bcu, bcb] A = assemble(CoupleT + Couple) b_d = assemble(L_D) b_n = assemble(L_N) for bcs in bc: bcs.apply(A) bcs.apply(b_d) # print A.array() # print b_n.array() # print A.array() - b_d.array() A, b = CP.Assemble(A, b_n) u = arrayToVec( np.concatenate((u0.vector().array(), b0.vector().array()), axis=1)) print "norm(A*u-f) ", np.linalg.norm((A * u - b).array) print(A * u).array - b.array C = A.getSubMatrix(b_is, u_is) Ct = A.getSubMatrix(u_is, b_is) f_u = b.getSubVector(u_is) f_b = b.getSubVector(b_is) print "norm(Ct*b-f) ", np.linalg.norm((Ct * b_solution - f_u).array) print "norm(C*u-f): ", np.linalg.norm((C * u_solution - f_b).array) print(Ct * b_solution).array - f_u.array print(C * u_solution - f_b).array
DoF = np.zeros((m-1,1)) Vdim = np.zeros((m-1,1)) Qdim = np.zeros((m-1,1)) Wdim = np.zeros((m-1,1)) l2uorder = np.zeros((m-1,1)) l2porder = np.zeros((m-1,1)) nonlinear = np.zeros((m-1,1)) AvIt = np.zeros((m-1,1)) nn = 2 dim = 2 Solver = 'PCD' Saving = 'no' case = 1 # parameters['linear_algebra_backend'] = 'uBLAS' parameters = CP.ParameterSetup() def LOG(arg): if INFO: print(arg) for xx in xrange(1,m): print xx nn = 2**(xx) # Create mesh and define function space nn = int(nn) # print nn NN[xx-1] = nn
print " Lapl-gradient test: ", Laplgrad[xx - 1] print "========================================" # # Grad = AA. # Grad.zero() # bcu.apply(Grad) G = PETSc.Mat().createAIJ(size=C.shape, csr=(C.indptr, C.indices, C.data)) a = inner(curl(u), curl(v)) * dx + inner(u, v) * dx L1 = inner(v, CurlMass) * dx tic() Acurl, b = assemble_system(a, L1, bc) print "System assembled, time: ", toc() tic() A, b = CP.Assemble(Acurl, b) x = b.duplicate() print "PETSc system assembled, time: ", toc() tic() ScalarLaplacian = assemble(inner(grad(p), grad(q)) * dx) VectorLaplacian = assemble(inner(grad(p), grad(q)) * dx + inner(p, q) * dx) print "Hiptmair Laplacians assembled, time: ", toc() # tic() # Pxx = Px # Pyy = Py # ii,jj = Px[:,BC].nonzero() # Px[ii,jj] = 0 # ii,jj = Px[:,BC].nonzero() # Py[ii,jj] = 0 # print toc()
r21 = div(u_k) * q * dx RHSform = r11 - r12 - r21 p11 = inner(u, v) * dx # p12 = div(v)*p*dx # p21 = div(u)*q*dx p22 = inner(p, q) * dx prec = p11 + p22 bc = DirichletBC(W.sub(0), Expression(("0", "0")), boundary) bcs = [bc] eps = 1.0 # error measure ||u-u_k|| tol = 1.0E-5 # tolerance iter = 0 # iteration counter maxiter = 10 # max no of iterations allowed parameters = CP.ParameterSetup() outerit = 0 parameters['linear_algebra_backend'] = 'uBLAS' BQB = assemble(inner(u, v) * dx - div(v) * p * dx - div(u) * q * dx) bc.apply(BQB) BQB = BQB.sparray() X = BQB[0:V.dim(), 0:V.dim()] Xdiag = X.diagonal() # Xdiag = X.sum(0)[0] # print Xdiag B = BQB[V.dim():W.dim(), 0:V.dim()] Bt = BQB[0:V.dim(), V.dim():W.dim()] d = spdiags(1.0 / Xdiag, 0, len(Xdiag), len(Xdiag)) L = B * d * Bt Bd = B * d
eps = 1.0 # error measure ||u-u_k|| tol = 1.0E-7 # tolerance iter = 0 # iteration counter maxiter = 40 # max no of iterations allowed SolutionTime = 0 outer = 0 parameters['linear_algebra_backend'] = 'uBLAS' p = forms.Preconditioner(mesh,W, u_k,b_k, params,IterType) PP,Pb = assemble_system(p, Lns,bcs) if IterType == "CD": AA, bb = assemble_system(maxwell+ns+CoupleTerm, (Lmaxwell + Lns) - RHSform, bcs) A,b = CP.Assemble(AA,bb) u = b.duplicate() P = CP.Assemble(PP) while eps > tol and iter < maxiter: iter += 1 if IterType == "CD": bb = assemble((Lmaxwell + Lns) - RHSform) for bc in bcs: bc.apply(bb) A,b = CP.Assemble(AA,bb) u = b.duplicate() else: AA, bb = assemble_system(maxwell+ns+CoupleTerm, (Lmaxwell + Lns) - RHSform, bcs) A,b = CP.Assemble(AA,bb)
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 eigensORIG(A, AA, W, PCD, L): IS = IndexSet(W) F = A.getSubMatrix(IS[0], IS[0]) Ct = A.getSubMatrix(IS[0], IS[1]) Dt = A.getSubMatrix(IS[1], IS[3]) M = A.getSubMatrix(IS[1], IS[1]) Bt = A.getSubMatrix(IS[0], IS[2]) C = A.getSubMatrix(IS[2], IS[2]) F = CP.PETSc2Scipy(F) Ct = CP.PETSc2Scipy(Ct) Dt = CP.PETSc2Scipy(Dt) Bt = CP.PETSc2Scipy(Bt) L = CP.PETSc2Scipy(L) M = CP.PETSc2Scipy(M) Ap = CP.PETSc2Scipy(PCD[0]) Mp = CP.PETSc2Scipy(PCD[1]) Fp = CP.PETSc2Scipy(PCD[2]) A = CP.PETSc2Scipy(A) C = CP.PETSc2Scipy(C) Fpinv = sp.linalg.inv(Fp) Linv = sp.linalg.inv(L) MO.StoreMatrix(L, "L") MX = M + Dt * Linv * Dt.transpose() MXinv = sp.linalg.inv(MX) FX = F + Ct * MXinv * Ct.transpose() PCD = Mp * Fpinv * Ap #Finv = sp.linalg.inv(F) #PCD = -C + Bt.transpose()*Finv*Bt MO.StoreMatrix(Dt, "Dt") MO.StoreMatrix(L, "L") MO.StoreMatrix(Ct, "Ct") MO.StoreMatrix(MX, "MX") A = sp.bmat([[F, Bt, Ct, None], [Bt.transpose(), C, None, None], [-Ct.transpose(), None, M, Dt], [None, None, Dt.transpose(), None]]) P = sp.bmat([[F, Bt, Ct, None], [None, -PCD, None, None], [-Ct.transpose(), None, MX, None], [None, None, None, L]]) Pinner = sp.bmat([[F, Bt, None, None], [None, -PCD, None, None], [None, None, MX, None], [None, None, None, L]]) Papprox = sp.bmat([[FX, Bt, Ct, None], [None, -PCD, None, None], [None, None, MX, None], [None, None, None, L]]) return A, P, Pinner, Papprox
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()
def SaveMatrices(W, level, A, Fluid, Magnetic): u_is = PETSc.IS().createGeneral(W.sub(0).dofmap().dofs()) p_is = PETSc.IS().createGeneral(W.sub(1).dofmap().dofs()) b_is = PETSc.IS().createGeneral(W.sub(2).dofmap().dofs()) r_is = PETSc.IS().createGeneral(W.sub(3).dofmap().dofs()) F = CP.PETSc2Scipy(A.getSubMatrix(u_is, u_is)) B = CP.PETSc2Scipy(A.getSubMatrix(u_is, p_is)) C = -CP.PETSc2Scipy(A.getSubMatrix(u_is, b_is)) M = CP.PETSc2Scipy(A.getSubMatrix(b_is, b_is)) D = CP.PETSc2Scipy(A.getSubMatrix(b_is, r_is)) Stab = CP.PETSc2Scipy(A.getSubMatrix(r_is, r_is)) Fp = CP.PETSc2Scipy(Fluid['Fp']) Ap = CP.PETSc2Scipy(Fluid['Ap']) Qp = CP.PETSc2Scipy(Fluid['Qp']) Fs = CP.PETSc2Scipy(Fluid['Fs']) Lp = CP.PETSc2Scipy(Magnetic['Lp']) MX = CP.PETSc2Scipy(Magnetic['MX']) os.chdir( "/Users/michaelwathen/Desktop/PhD/MHD/FEniCS/MHD/Stabilised/SaddlePointForm/Test/SplitMatrix/ScottTest/Hartman2D/matrix1" ) StoreMatrix(F, "F_" + str(level)) StoreMatrix(B, "B_" + str(level)) StoreMatrix(C, "C_" + str(level)) StoreMatrix(M, "M_" + str(level)) StoreMatrix(D, "D_" + str(level)) StoreMatrix(Stab, "Stab_" + str(level)) StoreMatrix(Fp, "Fp_" + str(level)) StoreMatrix(Ap, "Ap_" + str(level)) StoreMatrix(Qp, "Qp_" + str(level)) StoreMatrix(Fs, "Fs_" + str(level)) StoreMatrix(Lp, "Lp_" + str(level)) StoreMatrix(MX, "MX_" + str(level)) os.chdir( "/Users/michaelwathen/Desktop/PhD/MHD/FEniCS/MHD/Stabilised/SaddlePointForm/Test/SplitMatrix/ScottTest/Hartman2D" )