示例#1
0
文件: MHD.py 项目: daveb-dev/UBC
        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(2,2)
        # plot(interpolate(u0,Velocity))

        p0 = interpolate(p0,Pressure)
        p0.vector()[:] -= np.max(p0.vector().array() )/2
        # plot(interpolate(p0,Pressure))

        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]

示例#2
0
文件: MHDkappa.py 项目: daveb-dev/UBC
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()
示例#3
0
文件: MHDkappa.py 项目: daveb-dev/UBC
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()
示例#4
0
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()
示例#5
0
文件: MHDfluid.py 项目: daveb-dev/UBC
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()
示例#6
0
文件: PETSc.py 项目: daveb-dev/UBC
Massgrad = numpy.zeros((m - 1, 1))
Laplgrad = numpy.zeros((m - 1, 1))
InterpError = numpy.zeros((m - 1, 1))
InterpOrder = numpy.zeros((m - 1, 1))

dim = 2

for xx in xrange(1, m):
    NN[xx - 1] = xx + 0
    nn = int(2**(NN[xx - 1][0]))
    omega = 1
    if dim == 2:
        # mesh = UnitSquareMesh(int(nn),int(nn))
        mesh = RectangleMesh(0.0, 0.0, 1.0, 1.0, int(nn), int(nn), 'left')
        u0, p0, CurlCurl, gradPres, CurlMass = ExactSol.M2D(2,
                                                            Show="yes",
                                                            Mass=omega)
    else:
        mesh = UnitCubeMesh(int(nn), int(nn), int(nn))
        u0, p0, CurlCurl, gradPres, CurlMass = ExactSol.M3D(1,
                                                            Show="yes",
                                                            Mass=omega)
    parameters["form_compiler"]["quadrature_degree"] = -1
    order = 1
    parameters['reorder_dofs_serial'] = False
    Magnetic = FunctionSpace(mesh, "N1curl", order)
    Lagrange = FunctionSpace(mesh, "CG", order)
    VLagrange = VectorFunctionSpace(mesh, "CG", order)
    parameters['reorder_dofs_serial'] = False

    W = Magnetic * Lagrange
示例#7
0
文件: test.py 项目: daveb-dev/UBC
def foo():
    m = 10
    errL2u = np.zeros((m - 1, 1))
    errL2p = np.zeros((m - 1, 1))
    l2uorder = np.zeros((m - 1, 1))
    l2porder = np.zeros((m - 1, 1))
    NN = np.zeros((m - 1, 1))
    DoF = np.zeros((m - 1, 1))
    Vdim = np.zeros((m - 1, 1))
    Qdim = 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))
    nn = 2

    dim = 2
    Solving = 'Direct'
    ShowResultPlots = 'no'
    ShowErrorPlots = 'no'
    EigenProblem = 'no'
    SavePrecond = 'no'
    case = 1
    parameters['linear_algebra_backend'] = 'uBLAS'

    for xx in xrange(1, m):
        print xx
        nn = 2**(xx + 0)
        # Create mesh and define function space
        nn = int(nn)
        NN[xx - 1] = nn

        mesh = UnitSquareMesh(nn, nn)
        parameters['reorder_dofs_serial'] = False
        V = VectorFunctionSpace(mesh, "CG", 2)

        def boundary(x, on_boundary):
            return on_boundary

        print " DOFs              ", V.dim()

        u0, p0, b0, r0, Laplacian, Advection, gradPres, CurlCurl, gradR, NS_Couple, M_Couple = ExactSol.MHD2D(
            4, 1, mesh)

        bc = DirichletBC(V, u0, boundary)

        u = TrialFunction(V)
        v = TestFunction(V)

        N = FacetNormal(mesh)
        h = CellSize(mesh)
        h_avg = avg(h)
        alpha = 10.0
        gamma = 10.0
        n = FacetNormal(mesh)
        h = CellSize(mesh)
        h_avg = avg(h)
        d = 0
        a = inner(grad(v), grad(u)) * dx
        L = inner(Laplacian, v) * dx
        # A = assemble(a)

        b_k = Function(V)
        # print bb.array
        b_k.vector()[:] = np.random.rand(V.dim())
        bc.apply(b_k.vector())
        bb = arrayToVec(b_k.vector().array())

        tic()
        AA = assemble(a)
        bc.apply(AA)
        A = CP.Assemble(AA)
        # bb.set(1)
        for i in range(50):
            # A = CP.Assemble(A)
            u = A * bb
        print '                                      ', toc()

        # print b_k.vector().array()
        a = inner(grad(v), grad(b_k)) * dx
        tic()
        for i in range(50):
            A = assemble(a)
            # print A.array()
            bc.apply(A)
            A = arrayToVec(A.array())
            # print A.array()
        print '                                      ', toc()
        print np.linalg.norm(u.array - A.array)
示例#8
0
文件: MHDfluid.py 项目: daveb-dev/UBC
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()
示例#9
0
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 + 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)
        # mesh = RectangleMesh(0,0,2*np.pi,2*np.pi,nn,nn)
        order = 1
        parameters['reorder_dofs_serial'] = False
        Velocity = VectorFunctionSpace(mesh, "CG", order)
        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, Expression(('0', '0')), boundary)
        bcr = DirichletBC(Lagrange, Expression(('0')), 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-5
        HiptmairMatrices = PrecondSetup.MagneticSetup(Magnetic, Lagrange, b0,
                                                      r0, Hiptmairtol, params)
        print HiptmairMatrices
        C = CP.PETSc2Scipy(HiptmairMatrices[0])
        Px = CP.PETSc2Scipy(HiptmairMatrices[1][0])
        Py = CP.PETSc2Scipy(HiptmairMatrices[1][1])

        # VecV = VectorFunctionSpace(mesh,"CG",1)

        # f = Expression(('sin(x[0])','sin(x[1])'))
        # F = interpolate(f,VecV)
        # Fvec = F
        # bcrVec = DirichletBC(VecV,Expression(('0','0')), boundary)

        # bcrVec.apply(F.vector())

        # Fmag = interpolate(F,Magnetic)
        # bcb.apply(Fmag.vector())
        # print Fmag.vector().array()
        # print bmat([[Px,Py]]).shape
        # print bmat([[Px,Py]])*F.vector().array()
        # FmagP = bmat([[Px,Py]])*F.vector().array()
        # print np.max(abs(bmat([[Px,Py]])*F.vector().array()-Fmag.vector().array()))

        # print "\n\n\n\n"
        # Fmag = interpolate(f,Magnetic)
        # # plot(Fmag)
        # bcb.apply(Fmag.vector())
        # Forig = interpolate(Fmag,VecV)
        # # plot(Forig)
        # bcrVec.apply(Forig.vector())
        # print Forig.vector().array()
        # print "\n\n"
        # # print Fmag.vector().array()
        # print (bmat([[Px,Py]]).T*Fmag.vector().array())
        # print "\n\n\n\n"
        # print np.max(abs(bmat([[Px,Py]]).T*Fmag.vector().array()-Forig.vector().array()))

        u = TrialFunction(Magnetic)
        v = TestFunction(Magnetic)
        f = Expression('(x[0])')
        F = interpolate(f, Lagrange)
        # f = np.zeros(Lagrange.dim())
        f = np.zeros((Lagrange.dim(), 1))[:, 0]
        f[0] = 1.0
        F = Function(Lagrange)
        F.vector()[:] = f
        # bcrVec = DirichletBC(VecV,Expression(('0','0')), boundary)

        bcr.apply(F.vector())

        M = (inner(u, v) * dx)
        B = (inner(v, grad(F)) * dx)

        u = Function(Magnetic)
        solve(M == B, u, bcb)
        projection = project(grad(F), Magnetic, solver_type="lu")
        print projection
        u = bcb.apply(projection.vector())
        print projection.vector().array()
        print C * F.vector().array()
        print "\n\n\n"
        print abs(C * F.vector().array() - projection.vector().array()) < 1e-6
        print np.max(abs(projection.vector().array() -
                         C * F.vector().array()))  #,

        f = Expression(('(x[0])', '(x[1])'))
        F = interpolate(f, Magnetic)
        bcb.apply(F.vector())
        print F.vector().array()
        projection = project(div((F)), Lagrange, solver_type="lu")
        bcr.apply(projection.vector())
        print projection.vector().array()
        print C.T * F.vector().array()
        print "\n\n\n"
        print abs(C.T * F.vector().array() - projection.vector().array())
        print np.max(
            abs(projection.vector().array() - C.T * F.vector().array()))  #,

    interactive()
示例#10
0
def foo():
    m = 5
    errL2u = np.zeros((m - 1, 1))
    errL2p = np.zeros((m - 1, 1))
    l2uorder = np.zeros((m - 1, 1))
    l2porder = np.zeros((m - 1, 1))
    NN = np.zeros((m - 1, 1))
    DoF = np.zeros((m - 1, 1))
    Vdim = np.zeros((m - 1, 1))
    Qdim = 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))
    nn = 2

    dim = 2
    Solving = 'Direct'
    ShowResultPlots = 'no'
    ShowErrorPlots = 'no'
    EigenProblem = 'no'
    SavePrecond = 'no'
    case = 1
    parameters['linear_algebra_backend'] = 'uBLAS'

    for xx in xrange(1, m):
        print xx
        nn = 2**(xx + 0)
        # Create mesh and define function space
        nn = int(nn)
        NN[xx - 1] = nn

        # mesh = UnitSquareMesh(nn,nn)
        mesh = UnitCubeMesh(nn, nn, nn)
        parameters['reorder_dofs_serial'] = False
        V = VectorFunctionSpace(mesh, "CG", 2)
        Q = FunctionSpace(mesh, "CG", 1)
        C = FunctionSpace(mesh, "N1curl", 1)
        S = FunctionSpace(mesh, "CG", 1)
        W = MixedFunctionSpace([V, Q, C, S])

        def boundary(x, on_boundary):
            return on_boundary

        print "               DOFs              ", W.dim()
        u0, p0, b0, r0, Laplacian, Advection, gradPres, CurlCurl, gradR, NS_Couple, M_Couple = ExactSol.MHD3D(
            4, 1, mesh)
        dim = Laplacian.shape()[0]

        n = FacetNormal(mesh)
        bcu = DirichletBC(V, u0, boundary)
        bcb = DirichletBC(C, b0, boundary)
        bcr = DirichletBC(S, r0, boundary)

        u_k = Function(V)
        u_k.vector()[:] = np.random.rand(V.dim())
        bcu.apply(u_k.vector())
        p_k = Function(Q)
        p_k.vector()[:] = np.random.rand(Q.dim())
        b_k = Function(C)
        b_k.vector()[:] = np.random.rand(C.dim())
        bcb.apply(b_k.vector())
        r_k = Function(S)
        r_k.vector()[:] = np.random.rand(S.dim())
        bcr.apply(r_k.vector())

        B = np.concatenate((u_k.vector().array(), p_k.vector().array(),
                            b_k.vector().array(), r_k.vector().array()),
                           axis=0)
        x = arrayToVec(B)

        u = TrialFunction(V)
        b = TrialFunction(C)
        p = TrialFunction(Q)
        r = TrialFunction(S)
        v = TestFunction(V)
        c = TestFunction(C)
        q = TestFunction(Q)
        s = TestFunction(S)

        mm11 = inner(curl(b_k), curl(c)) * dx
        mm21 = inner(c, grad(r_k)) * dx
        mm12 = inner(b_k, grad(s)) * dx

        aa11 = 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)
        aa12 = -div(v) * p_k * dx
        aa21 = -div(u_k) * q * dx

        if dim == 2:
            CCoupleT = (v[0] * b_k[1] - v[1] * b_k[0]) * curl(b_k) * dx
            CCouple = -(u_k[0] * b_k[1] - u_k[1] * b_k[0]) * curl(c) * dx
        elif dim == 3:
            CCoupleT = inner(cross(v, b_k), curl(b_k)) * dx
            CCouple = -inner(cross(u_k, b_k), curl(c)) * dx

        (u, p, b, r) = TrialFunctions(W)
        (v, q, c, s) = TestFunctions(W)

        m11 = inner(curl(b), curl(c)) * dx
        m22 = inner(r, s) * dx
        m21 = inner(c, grad(r)) * dx
        m12 = inner(b, grad(s)) * dx
        # Lmaxwell  = inner(c, F_M)*dx

        a11 = 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
        # Lns  = inner(v, F_NS)*dx

        if dim == 2:
            CoupleT = (v[0] * b_k[1] - v[1] * b_k[0]) * curl(b) * dx
            Couple = -(u[0] * b_k[1] - u[1] * b_k[0]) * curl(c) * dx
        elif dim == 3:
            CoupleT = inner(cross(v, b_k), curl(b)) * dx
            Couple = -inner(cross(u, b_k), curl(c)) * dx

        a = m11 + m12 + m21 + a11 + a12 + a21 + Couple + CoupleT

        aVec = {
            'velocity': [aa11, aa12, CCoupleT],
            'pressure': [aa21],
            'magnetic': [CCouple, mm11, mm21],
            'multiplier': [mm12]
        }
        bcs = {'velocity': bcu, 'magnetic': bcb, 'multiplier': bcr}
        tic()
        a
        P = PETSc.Mat().createPython([W.dim(), W.dim()])
        P.setType('python')
        aa = MHDmult.SplitMatVec(W, aVec, bcs)
        P.setPythonContext(aa)
        P.setUp()
        for i in range(50):
            # U = assemble(aa11)+assemble(aa12)+assemble(CCoupleT)
            # bcu.apply(U)
            # P = assemble(aa21)
            # B = assemble(CCouple)+assemble(mm11)+assemble(mm21)
            # bcb.apply(B)
            # R = assemble(mm12)
            # bcr.apply(R)

            # B = np.concatenate((U.array(),P.array(),B.array(),R.array()), axis=0)
            # P = arrayToVec(B)
            # print A.array()
            v = x.duplicate()
            P.mult(x, v)

        print '                                      ', toc()

        bcu = DirichletBC(W.sub(0), u0, boundary)
        bcb = DirichletBC(W.sub(2), b0, boundary)
        bcr = DirichletBC(W.sub(3), r0, boundary)
        bcs = [bcu, bcb, bcr]

        tic()
        AA = assemble(a)
        for bc in bcs:
            bc.apply(AA)
        # bc.apply(AA)
        A = CP.Assemble(AA)
        # bb.set(1)
        for i in range(50):
            # A = CP.Assemble(A)
            for bc in bcs:
                bc.apply(AA)
            u = x.duplicate()
            A.mult(x, u)

        print '                                      ', toc()

        # print b_k.vector().array()
        # a = inner(grad(v), grad(b_k))*dx
        print np.linalg.norm(u.array - v.array, ord=np.inf)
示例#11
0
文件: MHD.py 项目: daveb-dev/UBC
    Lagrange = FiniteElement("CG", mesh.ufl_cell(), order)
    MagneticF = FunctionSpace(mesh, "N1curl", order)
    LagrangeF = FunctionSpace(mesh, "CG", order)

    Magneticdim[xx - 1] = MagneticF.dim()
    print "Magnetic:  ", Magneticdim[xx - 1]

    def boundary(x, on_boundary):
        return on_boundary

    (b) = TrialFunction(MagneticF)
    (c) = TestFunction(MagneticF)
    (r) = TrialFunction(LagrangeF)
    (s) = TestFunction(LagrangeF)

    b0, r0, CurlCurl, gradPres, CurlMass = ExactSol.M2D(1, Mass=1)

    bc = DirichletBC(MagneticF, b0, boundary)

    a = inner(curl(b), curl(c)) * dx + inner(b, c) * dx
    t1 = inner(grad(b), grad(c)) * dx + inner(b, c) * dx
    a1 = inner(curl(b), curl(c)) * dx
    z = inner(b, c) * dx + inner(div(b), div(c)) * dx
    m = inner(b, c) * dx
    t2 = inner(curl(b), curl(c)) * dx + inner(b, c) * dx + inner(
        div(b), div(c)) * dx
    L = inner(CurlMass, c) * dx

    X = assemble(inner(r, s) * dx)
    X = CP.Assemble(X)