Exemple #1
0
def Stokes(V, Q, F, params, boundaries, domains, mesh):
    parameters['reorder_dofs_serial'] = False

    W = FunctionSpace(mesh, MixedElement([V, Q]))

    IS = MO.IndexSet(W)

    mesh = W.mesh()
    (u, p) = TrialFunctions(W)
    (v, q) = TestFunctions(W)
    n = FacetNormal(W.mesh())

    a11 = params[2]*inner(grad(v), grad(u))*dx('everywhere')
    a12 = -div(v)*p*dx('everywhere')
    a21 = -div(u)*q*dx('everywhere')
    a = a11+a12+a21

    L = inner(v, F)*dx('everywhere') #+ inner(gradu0,v)*ds(2)

    def boundary(x, on_boundary):
        return on_boundary

    bcu1 = DirichletBC(W.sub(0), Expression(("0.0","0.0"), degree=4), boundaries, 1)
    bcu2 = DirichletBC(W.sub(0), Expression(("1.0","0.0"), degree=4), boundaries, 2)
    bcu = [bcu1, bcu2]

    A, b = assemble_system(a, L, bcu)
    A, b = CP.Assemble(A, b)
    pp = params[2]*inner(grad(v), grad(u))*dx + (1./params[2])*p*q*dx
    P, Pb = assemble_system(pp, L, bcu)
    P, Pb = CP.Assemble(P, Pb)

    u = b.duplicate()

    ksp = PETSc.KSP().create()
    ksp.setTolerances(1e-8)
    ksp.max_it = 200
    pc = ksp.getPC()
    pc.setType(PETSc.PC.Type.PYTHON)
    ksp.setType('minres')
    pc.setPythonContext(StokesPrecond.Approx(W, 1))
    ksp.setOperators(A,P)

    scale = b.norm()
    b = b/scale
    ksp.setOperators(A,A)
    del A
    start_time = time.time()
    ksp.solve(b,u)
    print ("{:40}").format("Stokes solve, time: "), " ==>  ",("{:4f}").format(time.time() - start_time),("{:9}").format("   Its: "), ("{:4}").format(ksp.its),  ("{:9}").format("   time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5])

    u = u*scale
    u_k = Function(FunctionSpace(mesh, V))
    p_k = Function(FunctionSpace(mesh, Q))
    u_k.vector()[:] = u.getSubVector(IS[0]).array
    p_k.vector()[:] = u.getSubVector(IS[1]).array
    ones = Function(FunctionSpace(mesh, Q))
    ones.vector()[:]=(0*ones.vector().array()+1)
    p_k.vector()[:] += -assemble(p_k*dx("everywhere"))/assemble(ones*dx("everywhere"))
    return u_k, p_k
Exemple #2
0
def solve(A, b, u, params, Fspace, SolveType, IterType, OuterTol, InnerTol,
          HiptmairMatrices, Hiptmairtol, KSPlinearfluids, Fp, kspF):

    if SolveType == "Direct":
        ksp = PETSc.KSP()
        ksp.create(comm=PETSc.COMM_WORLD)
        pc = ksp.getPC()
        ksp.setType('preonly')
        pc.setType('lu')
        OptDB = PETSc.Options()
        OptDB['pc_factor_mat_solver_package'] = "mumps"
        OptDB['pc_factor_mat_ordering_type'] = "rcm"
        ksp.setFromOptions()
        scale = b.norm()
        b = b / scale
        ksp.setOperators(A, A)
        del A
        ksp.solve(b, u)
        # Mits +=dodim
        u = u * scale
        MO.PrintStr("Number iterations = " + str(ksp.its), 60, "+", "\n\n",
                    "\n\n")
        return u, ksp.its, 0
    elif SolveType == "Direct-class":
        ksp = PETSc.KSP()
        ksp.create(comm=PETSc.COMM_WORLD)
        pc = ksp.getPC()
        ksp.setType('gmres')
        pc.setType('none')
        ksp.setFromOptions()
        scale = b.norm()
        b = b / scale
        ksp.setOperators(A, A)
        del A
        ksp.solve(b, u)
        # Mits +=dodim
        u = u * scale
        MO.PrintStr("Number iterations = " + str(ksp.its), 60, "+", "\n\n",
                    "\n\n")
        return u, ksp.its, 0

    else:

        # u = b.duplicate()
        if IterType == "Full":
            ksp = PETSc.KSP()
            ksp.create(comm=PETSc.COMM_WORLD)
            pc = ksp.getPC()
            ksp.setType('fgmres')
            pc.setType('python')
            OptDB = PETSc.Options()
            OptDB['ksp_gmres_restart'] = 200
            # FSpace = [Velocity,Magnetic,Pressure,Lagrange]
            reshist = {}

            def monitor(ksp, its, fgnorm):
                reshist[its] = fgnorm
                print its, "    OUTER:", fgnorm

            # ksp.setMonitor(monitor)
            ksp.max_it = 1000
            W = Fspace
            FFSS = [W.sub(0), W.sub(1), W.sub(2), W.sub(3)]
            pc.setPythonContext(
                MHDprec.InnerOuterMAGNETICapprox(
                    FFSS, kspF, KSPlinearfluids[0], KSPlinearfluids[1], Fp,
                    HiptmairMatrices[3], HiptmairMatrices[4],
                    HiptmairMatrices[2], HiptmairMatrices[0],
                    HiptmairMatrices[1], HiptmairMatrices[6], Hiptmairtol))
            #OptDB = PETSc.Options()

            # OptDB['pc_factor_mat_solver_package']  = "mumps"
            # OptDB['pc_factor_mat_ordering_type']  = "rcm"
            # ksp.setFromOptions()
            scale = b.norm()
            b = b / scale
            ksp.setOperators(A, A)
            del A
            ksp.solve(b, u)
            # Mits +=dodim
            u = u * scale
            MO.PrintStr("Number iterations = " + str(ksp.its), 60, "+", "\n\n",
                        "\n\n")
            return u, ksp.its, 0

        IS = MO.IndexSet(Fspace, '2by2')
        M_is = IS[1]
        NS_is = IS[0]
        kspNS = PETSc.KSP().create()
        kspM = PETSc.KSP().create()
        kspNS.setTolerances(OuterTol)

        kspNS.setOperators(A[0])
        kspM.setOperators(A[1])
        # print P.symmetric
        if IterType == "MD":
            kspNS.setType('gmres')
            kspNS.max_it = 500

            pcNS = kspNS.getPC()
            pcNS.setType(PETSc.PC.Type.PYTHON)
            pcNS.setPythonContext(
                NSpreconditioner.NSPCD(
                    MixedFunctionSpace([Fspace.sub(0),
                                        Fspace.sub(1)]), kspF,
                    KSPlinearfluids[0], KSPlinearfluids[1], Fp))
        elif IterType == "CD":
            kspNS.setType('minres')
            pcNS = kspNS.getPC()
            pcNS.setType(PETSc.PC.Type.PYTHON)
            Q = KSPlinearfluids[1].getOperators()[0]
            Q = 1. / params[2] * Q
            KSPlinearfluids[1].setOperators(Q, Q)
            pcNS.setPythonContext(
                StokesPrecond.MHDApprox(
                    MixedFunctionSpace([Fspace.sub(0),
                                        Fspace.sub(1)]), kspF,
                    KSPlinearfluids[1]))
        reshist = {}

        def monitor(ksp, its, fgnorm):
            reshist[its] = fgnorm
            print fgnorm

        # kspNS.setMonitor(monitor)

        uNS = u.getSubVector(NS_is)
        bNS = b.getSubVector(NS_is)
        # print kspNS.view()
        scale = bNS.norm()
        bNS = bNS / scale
        print bNS.norm()
        kspNS.solve(bNS, uNS)
        uNS = uNS * scale
        NSits = kspNS.its
        kspNS.destroy()
        # for line in reshist.values():
        #     print line
        kspM.setFromOptions()
        kspM.setType(kspM.Type.MINRES)
        kspM.setTolerances(InnerTol)
        pcM = kspM.getPC()
        pcM.setType(PETSc.PC.Type.PYTHON)
        pcM.setPythonContext(
            MP.Hiptmair(MixedFunctionSpace([Fspace.sub(2),
                                            Fspace.sub(3)]),
                        HiptmairMatrices[3], HiptmairMatrices[4],
                        HiptmairMatrices[2], HiptmairMatrices[0],
                        HiptmairMatrices[1], HiptmairMatrices[6], Hiptmairtol))

        uM = u.getSubVector(M_is)
        bM = b.getSubVector(M_is)
        scale = bM.norm()
        bM = bM / scale
        print bM.norm()
        kspM.solve(bM, uM)
        uM = uM * scale
        Mits = kspM.its
        kspM.destroy()
        u = IO.arrayToVec(np.concatenate([uNS.array, uM.array]))

        MO.PrintStr("Number of M iterations = " + str(Mits), 60, "+", "\n\n",
                    "\n\n")
        MO.PrintStr("Number of NS/S iterations = " + str(NSits), 60, "+",
                    "\n\n", "\n\n")
        return u, NSits, Mits
Exemple #3
0
def Stokes(V, Q, F, u0, p0, gradu0, params, boundaries, domains, mesh):
    parameters['reorder_dofs_serial'] = False

    W = FunctionSpace(mesh, MixedElement([V, Q]))

    IS = MO.IndexSet(W)
    ds = Measure('ds', domain=mesh, subdomain_data=boundaries)
    dx = Measure('dx', domain=mesh)
    (u, p) = TrialFunctions(W)
    (v, q) = TestFunctions(W)
    n = FacetNormal(W.mesh())

    a11 = params[2] * inner(grad(v), grad(u)) * dx('everywhere')
    a12 = -div(v) * p * dx('everywhere')
    a21 = -div(u) * q * dx('everywhere')
    a = a11 + a12 + a21

    L = inner(v, F) * dx('everywhere')  #+ inner(gradu0,v)*ds(2)

    pp = params[2] * inner(grad(v),
                           grad(u)) * dx(0) + (1. / params[2]) * p * q * dx(0)

    def boundary(x, on_boundary):
        return on_boundary

    # bcu = DirichletBC(W.sub(0), u0, boundaries, 1)
    bcu = DirichletBC(W.sub(0), u0, boundary)
    # bcu = [bcu1, bcu2]
    A, b = assemble_system(a, L, bcu)
    A, b = CP.Assemble(A, b)
    C = A.getSubMatrix(IS[1], IS[1])
    u = b.duplicate()
    P, Pb = assemble_system(pp, L, bcu)
    P, Pb = CP.Assemble(P, Pb)

    # ksp = PETSc.KSP()
    # ksp.create(comm=PETSc.COMM_WORLD)
    # pc = ksp.getPC()
    # ksp.setType('preonly')
    # pc.setType('lu')
    # OptDB = PETSc.Options()
    # # if __version__ != '1.6.0':
    # OptDB['pc_factor_mat_solver_package']  = "pastix"
    # OptDB['pc_factor_mat_ordering_type']  = "rcm"
    # ksp.setFromOptions()
    # ksp.setOperators(A,A)

    ksp = PETSc.KSP().create()
    ksp.setTolerances(1e-8)
    ksp.max_it = 200
    pc = ksp.getPC()
    pc.setType(PETSc.PC.Type.PYTHON)
    ksp.setType('minres')
    pc.setPythonContext(StokesPrecond.Approx(W, 1))
    ksp.setOperators(A, P)

    scale = b.norm()
    b = b / scale
    del A
    start_time = time.time()
    ksp.solve(b, u)
    # Mits +=dodim
    u = u * scale
    print("{:40}").format("Stokes solve, time: "), " ==>  ", (
        "{:4f}").format(time.time() - start_time), (
            "{:9}").format("   Its: "), ("{:4}").format(
                ksp.its), ("{:9}").format("   time: "), ("{:4}").format(
                    time.strftime('%X %x %Z')[0:5])
    # Mits +=dodim
    u_k = Function(FunctionSpace(mesh, V))
    p_k = Function(FunctionSpace(mesh, Q))
    u_k.vector()[:] = u.getSubVector(IS[0]).array
    p_k.vector()[:] = u.getSubVector(IS[1]).array
    ones = Function(FunctionSpace(mesh, Q))
    ones.vector()[:] = (0 * ones.vector().array() + 1)
    p_k.vector()[:] += -assemble(p_k * dx('everywhere')) / assemble(
        ones * dx('everywhere'))
    return u_k, p_k
Exemple #4
0
    # pc = ksp.getPC()
    # ksp.setType('minres')
    # pc.setType('lu')
    # OptDB = PETSc.Options()
    # # if __version__ != '1.6.0':
    # # OptDB['pc_factor_mat_solver_package']  = "umfpack"
    # # OptDB['pc_factor_mat_ordering_type']  = "rcm"
    # ksp.setFromOptions()

    ksp = PETSc.KSP().create()
    ksp.setTolerances(1e-8)
    ksp.max_it = 200
    pc = ksp.getPC()
    pc.setType(PETSc.PC.Type.PYTHON)
    ksp.setType('minres')
    pc.setPythonContext(StokesPrecond.Approx(W, 1))
    scale = b.norm()
    b = b / scale
    ksp.setOperators(A, P)
    del A
    start_time = time.time()
    ksp.solve(b, x)
    print("{:40}").format("Stokes solve, time: "), " ==>  ", (
        "{:4f}").format(time.time() - start_time), (
            "{:9}").format("   Its: "), ("{:4}").format(
                ksp.its), ("{:9}").format("   time: "), ("{:4}").format(
                    time.strftime('%X %x %Z')[0:5])
    x = x * scale

    b_k = Function(Velocity)
    r_k = Function(Pressure)
Exemple #5
0
def Stokes(V, Q, F, u0, pN, params, boundaries, domains):
    parameters['reorder_dofs_serial'] = False

    W = V * Q
    IS = MO.IndexSet(W)
    mesh = W.mesh()
    ds = Measure('ds', domain=mesh, subdomain_data=boundaries)
    dx = Measure('dx', domain=mesh)
    (u, p) = TrialFunctions(W)
    (v, q) = TestFunctions(W)
    n = FacetNormal(W.mesh())

    a11 = params[2] * inner(grad(v), grad(u)) * dx('everywhere')
    a12 = -div(v) * p * dx('everywhere')
    a21 = -div(u) * q * dx('everywhere')
    a = a11 + a12 + a21

    L = inner(v, F) * dx('everywhere')  #+ inner(pN*n,v)*ds(1)

    pp = params[2] * inner(grad(v), grad(u)) * dx('everywhere') + (
        1. / params[2]) * p * q * dx('everywhere')

    def boundary(x, on_boundary):
        return on_boundary

    bcu = DirichletBC(W.sub(0), u0, boundary)
    #bcr = DirichletBC(W.sub(1), Expression(("0.0")), boundary)

    A, b = assemble_system(a, L, bcu)
    A, b = CP.Assemble(A, b)
    C = A.getSubMatrix(IS[1], IS[1])
    u = b.duplicate()

    P, Pb = assemble_system(pp, L, bcu)
    # MO.StoreMatrix(P.sparray(),"P"+str(W.dim()))
    P = CP.Assemble(P)
    M = P.getSubMatrix(IS[1], IS[1])
    # print M
    #    ksp = PETSc.KSP()
    #    ksp.create(comm=PETSc.COMM_WORLD)
    #    pc = ksp.getPC()
    #    ksp.setType('preonly')
    #    pc.setType('lu')
    #    OptDB = PETSc.Options()
    #    if __version__ != '1.6.0':
    #        OptDB['pc_factor_mat_solver_package']  = "mumps"
    #    OptDB['pc_factor_mat_ordering_type']  = "rcm"
    #    ksp.setFromOptions()
    #    ksp.setOperators(A,A)

    ksp = PETSc.KSP().create()
    pc = ksp.getPC()

    ksp.setType(ksp.Type.MINRES)
    ksp.setTolerances(1e-8)
    ksp.max_it = 500
    #ksp.max_it = 2
    pc.setType(PETSc.PC.Type.PYTHON)
    pc.setPythonContext(SP.Approx(W, M))
    ksp.setOperators(A, P)

    scale = b.norm()
    b = b / scale
    del A
    start_time = time.time()
    ksp.solve(b, u)
    print 333
    # Mits +=dodim
    u = u * scale
    print("{:40}").format("Stokes solve, time: "), " ==>  ", (
        "{:4f}").format(time.time() - start_time), (
            "{:9}").format("   Its: "), ("{:4}").format(
                ksp.its), ("{:9}").format("   time: "), ("{:4}").format(
                    time.strftime('%X %x %Z')[0:5])
    u_k = Function(V)
    p_k = Function(Q)
    u_k.vector()[:] = u.getSubVector(IS[0]).array
    p_k.vector()[:] = u.getSubVector(IS[1]).array
    # ones = Function(Q)
    # ones.vector()[:]=(0*ones.vector().array()+1)
    # p_k.vector()[:] += -assemble(p_k*dx('everywhere'))/assemble(ones*dx('everywhere'))
    return u_k, p_k
Exemple #6
0
def solve(A,b,u,IS,Fspace,IterType,OuterTol,InnerTol,HiptmairMatrices,KSPlinearfluids,kspF,Fp,MatrixLinearFluids,kspFp):

    if IterType == "Full":
        kspOuter = PETSc.KSP().create()
        kspOuter.setTolerances(OuterTol)
        kspOuter.setType('fgmres')

        u_is = PETSc.IS().createGeneral(range(Fspace[0].dim()))
        p_is = PETSc.IS().createGeneral(range(Fspace[0].dim(),Fspace[0].dim()+Fspace[1].dim()))
        Bt = A.getSubMatrix(u_is,p_is)

        reshist = {}
        def monitor(ksp, its, fgnorm):
            reshist[its] = fgnorm
            print "OUTER:", fgnorm
        kspOuter.setMonitor(monitor)
        pcOutter = kspOuter.getPC()
        pcOutter.setType(PETSc.PC.Type.KSP)

        kspOuter.setOperators(A,A)
        kspOuter.max_it = 500

        kspInner = pcOutter.getKSP()
        kspInner.max_it = 100

        kspInner.max_it = 100
        reshist1 = {}
        def monitor(ksp, its, fgnorm):
            reshist1[its] = fgnorm
            print "INNER:", fgnorm
        # kspInner.setMonitor(monitor)

        kspInner.setType('gmres')
        kspInner.setTolerances(InnerTol)

        pcInner = kspInner.getPC()
        pcInner.setType(PETSc.PC.Type.PYTHON)
        pcInner.setPythonContext(MHDstabPrecond.InnerOuterWITHOUT(Fspace,kspF, KSPlinearfluids[0], KSPlinearfluids[1],Fp, HiptmairMatrices[3], HiptmairMatrices[4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6],1e-6,A))

        PP = PETSc.Mat().createPython([A.size[0], A.size[0]])
        PP.setType('python')
        p = PrecondMulti.MultiApply(Fspace,A,HiptmairMatrices[6],MatrixLinearFluids[1],MatrixLinearFluids[0],kspFp, HiptmairMatrices[3])

        PP.setPythonContext(p)
        kspInner.setOperators(PP)

        tic()
        scale = b.norm()
        b = b/scale
        print b.norm()
        kspOuter.solve(b, u)
        u = u*scale
        print toc()

        # print s.getvalue()
        NSits = kspOuter.its
        del kspOuter
        Mits = kspInner.its
        del kspInner
        # print u.array
        return u,NSits,Mits

    NS_is = IS[0]
    M_is = IS[1]
    kspNS = PETSc.KSP().create()
    kspM = PETSc.KSP().create()
    kspNS.setTolerances(OuterTol)

    kspNS.setOperators(A.getSubMatrix(NS_is,NS_is))
    kspM.setOperators(A.getSubMatrix(M_is,M_is))
    del A

    uNS = u.getSubVector(NS_is)
    bNS = b.getSubVector(NS_is)
    kspNS.setType('gmres')
    pcNS = kspNS.getPC()
    kspNS.setTolerances(OuterTol)
    pcNS.setType(PETSc.PC.Type.PYTHON)
    if IterType == "MD":
        pcNS.setPythonContext(NSpreconditioner.NSPCD(MixedFunctionSpace([Fspace[0],Fspace[1]]), kspF, KSPlinearfluids[0], KSPlinearfluids[1],Fp))
    else:
        pcNS.setPythonContext(StokesPrecond.MHDApprox(MixedFunctionSpace([Fspace[0],Fspace[1]]), kspF, KSPlinearfluids[1]))

    scale = bNS.norm()
    bNS = bNS/scale
    start_time = time.time()
    kspNS.solve(bNS, uNS)
    print ("{:25}").format("NS, time: "), " ==>  ",("{:4f}").format(time.time() - start_time),("{:9}").format("   Its: "), ("{:4}").format(kspNS.its),  ("{:9}").format("   time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5])
    uNS = scale*uNS

    NSits = kspNS.its
    # kspNS.destroy()
    # for line in reshist.values():
    #     print line

    kspM.setFromOptions()
    kspM.setType(kspM.Type.MINRES)
    kspM.setTolerances(InnerTol)
    pcM = kspM.getPC()
    pcM.setType(PETSc.PC.Type.PYTHON)
    pcM.setPythonContext(MP.Hiptmair(MixedFunctionSpace([Fspace[2],Fspace[3]]), HiptmairMatrices[3], HiptmairMatrices[4], HiptmairMatrices[2], HiptmairMatrices[0], HiptmairMatrices[1], HiptmairMatrices[6],1e-6))


    # x = x*scale
    uM = u.getSubVector(M_is)
    bM = b.getSubVector(M_is)

    scale = bM.norm()
    bM = bM/scale
    start_time = time.time()
    kspM.solve(bM, uM)
    print ("{:25}").format("Maxwell solve, time: "), " ==>  ",("{:4f}").format(time.time() - start_time),("{:9}").format("   Its: "), ("{:4}").format(kspM.its),  ("{:9}").format("   time: "), ("{:4}").format(time.strftime('%X %x %Z')[0:5])
    uM = uM*scale

    Mits = kspM.its
    kspM.destroy()
    u = IO.arrayToVec(np.concatenate([uNS.array, uM.array]))

    return u,NSits,Mits
Exemple #7
0
def solve(A,
          b,
          u,
          P,
          IS,
          Fspace,
          IterType,
          OuterTol,
          InnerTol,
          Mass=0,
          L=0,
          F=0):

    # u = b.duplicate()
    if IterType == "Full":

        kspOuter = PETSc.KSP().create()
        kspOuter.setTolerances(OuterTol)
        kspOuter.setType('fgmres')

        reshist = {}

        def monitor(ksp, its, fgnorm):
            reshist[its] = fgnorm
            print "OUTER:", fgnorm

        kspOuter.setMonitor(monitor)
        pcOutter = kspOuter.getPC()
        pcOutter.setType(PETSc.PC.Type.KSP)

        kspOuter.setOperators(A)

        kspOuter.max_it = 500

        kspInner = pcOutter.getKSP()
        kspInner.max_it = 100

        reshist1 = {}

        def monitor(ksp, its, fgnorm):
            reshist1[its] = fgnorm
            print "INNER:", fgnorm

        # kspInner.setMonitor(monitor)

        kspInner.setType('gmres')
        kspInner.setTolerances(InnerTol)

        pcInner = kspInner.getPC()
        pcInner.setType(PETSc.PC.Type.PYTHON)
        pcInner.setPythonContext(MHDprecond.D(Fspace, P, Mass, F, L))

        PP = PETSc.Mat().createPython([A.size[0], A.size[0]])
        PP.setType('python')
        p = PrecondMulti.P(Fspace, P, Mass, L, F)

        PP.setPythonContext(p)
        kspInner.setOperators(PP)

        tic()
        scale = b.norm()
        b = b / scale
        print b.norm()
        kspOuter.solve(b, u)
        u = u * scale
        print toc()

        # print s.getvalue()
        NSits = kspOuter.its
        del kspOuter
        Mits = kspInner.its
        del kspInner
        # print u.array
        return u, NSits, Mits

    NS_is = IS[0]
    M_is = IS[1]
    kspNS = PETSc.KSP().create()
    kspM = PETSc.KSP().create()
    kspNS.setTolerances(OuterTol)

    kspNS.setOperators(A.getSubMatrix(NS_is, NS_is),
                       P.getSubMatrix(NS_is, NS_is))
    kspM.setOperators(A.getSubMatrix(M_is, M_is), P.getSubMatrix(M_is, M_is))
    # print P.symmetric
    A.destroy()
    P.destroy()
    if IterType == "MD":
        kspNS.setType('gmres')
        kspNS.max_it = 500

        pcNS = kspNS.getPC()
        pcNS.setType(PETSc.PC.Type.PYTHON)
        pcNS.setPythonContext(
            NSprecond.PCDdirect(MixedFunctionSpace([Fspace[0], Fspace[1]]),
                                Mass, F, L))
    elif IterType == "CD":
        kspNS.setType('minres')
        pcNS = kspNS.getPC()
        pcNS.setType(PETSc.PC.Type.PYTHON)
        pcNS.setPythonContext(
            StokesPrecond.Approx(MixedFunctionSpace([Fspace[0], Fspace[1]])))
    reshist = {}

    def monitor(ksp, its, fgnorm):
        reshist[its] = fgnorm
        print fgnorm

    # kspNS.setMonitor(monitor)

    uNS = u.getSubVector(NS_is)
    bNS = b.getSubVector(NS_is)
    # print kspNS.view()
    scale = bNS.norm()
    bNS = bNS / scale
    print bNS.norm()
    kspNS.solve(bNS, uNS)
    uNS = uNS * scale
    NSits = kspNS.its
    kspNS.destroy()
    # for line in reshist.values():
    #     print line
    kspM.setFromOptions()
    kspM.setType(kspM.Type.MINRES)
    kspM.setTolerances(InnerTol)
    pcM = kspM.getPC()
    pcM.setType(PETSc.PC.Type.PYTHON)
    pcM.setPythonContext(MP.Direct(MixedFunctionSpace([Fspace[2], Fspace[3]])))

    uM = u.getSubVector(M_is)
    bM = b.getSubVector(M_is)
    scale = bM.norm()
    bM = bM / scale
    print bM.norm()
    kspM.solve(bM, uM)
    uM = uM * scale
    Mits = kspM.its
    kspM.destroy()
    u = IO.arrayToVec(np.concatenate([uNS.array, uM.array]))
    return u, NSits, Mits
Exemple #8
0
def Stokes(V, Q, BC, f, params, FS, InitialTol, Neumann=None, A=0, b=0):
    if A == 0:
        # parameters['linear_algebra_backend'] = 'uBLAS'

        # parameters = CP.ParameterSetup()
        # parameters["form_compiler"]["quadrature_degree"] = 6
        parameters['reorder_dofs_serial'] = False
        Split = 'No'
        if Split == 'No':
            W = V * Q

            (u, p) = TrialFunctions(W)
            (v, q) = TestFunctions(W)
            print FS

            def boundary(x, on_boundary):
                return on_boundary

            bcu = DirichletBC(W.sub(0), BC, boundary)
            u_k = Function(V)

            if FS == "DG":
                h = CellSize(V.mesh())
                h_avg = avg(h)
                a11 = inner(grad(v), grad(u)) * dx
                a12 = div(v) * p * dx
                a21 = div(u) * q * dx
                a22 = 0.1 * h_avg * jump(p) * jump(q) * dS
                L1 = inner(v, f) * dx
                a = params[2] * a11 - a12 - a21 - a22
            else:
                if W.sub(0).__str__().find("Bubble") == -1 and W.sub(
                        0).__str__().find("CG1") != -1:

                    print "Bubble Bubble Bubble Bubble Bubble"
                    a11 = inner(grad(v), grad(u)) * dx
                    a12 = div(v) * p * dx
                    a21 = div(u) * q * dx
                    h = CellSize(V.mesh())
                    beta = 0.2
                    delta = beta * h * h
                    a22 = delta * inner(grad(p), grad(q)) * dx
                    a = params[2] * a11 - a12 - a21 - a22

                    L1 = inner(v - delta * grad(q), f) * dx
                else:
                    a11 = inner(grad(v), grad(u)) * dx
                    a12 = div(v) * p * dx
                    a21 = div(u) * q * dx
                    L1 = inner(v, f) * dx
                    a = params[2] * a11 - a12 - a21

            tic()
            AA, bb = assemble_system(a, L1, bcu)
            A, b = CP.Assemble(AA, bb)
            del AA
            x = b.duplicate()

            pp = params[2] * inner(
                grad(v), grad(u)) * dx + (1. / params[2]) * p * q * dx
            PP, Pb = assemble_system(pp, L1, bcu)
            P = CP.Assemble(PP)
            del PP
        else:
            u = TrialFunction(V)
            v = TestFunction(V)
            p = TrialFunction(Q)
            q = TestFunction(Q)

            def boundary(x, on_boundary):
                return on_boundary

            W = V * Q
            bcu = DirichletBC(V, BC, boundary)
            u_k = Function(V)

            if FS == "DG":
                h = CellSize(V.mesh())
                h_avg = avg(h)
                a11 = inner(grad(v), grad(u)) * dx
                a12 = div(v) * p * dx
                a21 = div(u) * q * dx
                a22 = 0.1 * h_avg * jump(p) * jump(q) * dS
                L1 = inner(v, f) * dx
            else:
                if V.__str__().find(
                        "Bubble") == -1 and V.__str__().find("CG1") != -1:
                    a11 = params[2] * inner(grad(v), grad(u)) * dx
                    a12 = -div(v) * p * dx
                    a21 = div(u) * q * dx
                    L1 = inner(v, f) * dx
                    h = CellSize(V.mesh())
                    beta = 0.2
                    delta = beta * h * h
                    a22 = delta * inner(grad(p), grad(q)) * dx
                else:
                    a11 = params[2] * inner(grad(v), grad(u)) * dx
                    a12 = -div(v) * p * dx
                    a21 = div(u) * q * dx
                    L1 = inner(v, f) * dx

            AA = assemble(a11)
            bcu.apply(AA)
            b = assemble(L1)
            bcu.apply(b)

            AA, b = assemble_system(a11, L1, bcu)
            BB = assemble(a12)
            AAA = AA
            AA = AA.sparray()
            mesh = V.mesh()
            dim = mesh.geometry().dim()
            LagrangeBoundary = np.zeros(dim * mesh.num_vertices())
            Row = (AA.sum(0)[0, :dim * mesh.num_vertices()] -
                   AA.diagonal()[:dim * mesh.num_vertices()])
            VelocityBoundary = np.abs(Row.A1) > 1e-4
            LagrangeBoundary[VelocityBoundary] = 1
            BubbleDOF = np.ones(dim * mesh.num_cells())
            VelocityBoundary = np.concatenate((LagrangeBoundary, BubbleDOF),
                                              axis=1)
            BC = sp.spdiags(VelocityBoundary, 0, V.dim(), V.dim())
            B = BB.sparray().T * BC
            A = CP.Scipy2PETSc(sp.bmat([[AA, B.T], [B, None]]))
            io.savemat("A.mat", {"A": sp.bmat([[AA, B.T], [B, None]])})
            b = IO.arrayToVec(
                np.concatenate((b.array(), np.zeros(Q.dim())), axis=0))

            mass = (1. / params[2]) * p * q * dx
            mass1 = assemble(mass).sparray()
            mass2 = assemble(mass)
            W = V * Q
            io.savemat("P.mat", {"P": sp.bmat([[AA, None], [None, (mass1)]])})
            P = CP.Scipy2PETSc(sp.bmat([[AA, None], [None, (mass1)]]))
    else:
        W = V * Q

        (u, p) = TrialFunctions(W)
        (v, q) = TestFunctions(W)
        print FS

        def boundary(x, on_boundary):
            return on_boundary

        bcu = DirichletBC(W.sub(0), BC, boundary)
        u_k = Function(V)

        pp = params[2] * inner(grad(v),
                               grad(u)) * dx + (1. / params[2]) * p * q * dx
        P = assemble(pp)
        bcu.apply(P)
        P = CP.Assemble(P)

    ksp = PETSc.KSP().create()
    pc = ksp.getPC()

    ksp.setType(ksp.Type.MINRES)
    ksp.setTolerances(InitialTol)
    pc.setType(PETSc.PC.Type.PYTHON)

    if Split == "Yes":
        A = PETSc.Mat().createPython([W.dim(), W.dim()])
        A.setType('python')
        print AAA
        a = MM.Mat2x2multi(W, [CP.Assemble(AAA), CP.Scipy2PETSc(B)])
        A.setPythonContext(a)
        pc.setPythonContext(
            SP.ApproxSplit(W, CP.Assemble(AAA), CP.Assemble(mass2)))
    else:
        pc.setPythonContext(SP.Approx(W, P))

    ksp.setOperators(A, P)
    x = b.duplicate()
    tic()
    ksp.solve(b, x)
    print("{:40}").format("Stokes solve, time: "), " ==>  ", ("{:4f}").format(
        toc()), ("{:9}").format("   Its: "), ("{:4}").format(
            ksp.its), ("{:9}").format("   time: "), ("{:4}").format(
                time.strftime('%X %x %Z')[0:5])
    X = x.array
    print np.linalg.norm(x)
    # print X
    ksp.destroy()
    x = X[0:V.dim()]
    p = X[V.dim():]
    # x =
    u = Function(V)
    u.vector()[:] = x
    # print u.vector().array()
    pp = Function(Q)
    n = p.shape
    pp.vector()[:] = p

    ones = Function(Q)
    ones.vector()[:] = (0 * ones.vector().array() + 1)
    pp.vector()[:] += -assemble(pp * dx) / assemble(ones * dx)

    #
    #    PP = io.loadmat('Ptrue.mat')["Ptrue"]
    #    PP = CP.Scipy2PETSc(PP)
    #    x = IO.arrayToVec(np.random.rand(W.dim()))
    #    y = x.duplicate()
    #    yy = x.duplicate()
    #    SP.ApproxFunc(W,PP,x,y)
    #    SP.ApproxSplitFunc(W,CP.Scipy2PETSc(AA),CP.Scipy2PETSc(mass),x,yy)
    #    print np.linalg.norm(y.array-yy.array)
    #    sssss

    return u, pp