def compute_z(a,A,b,B,I,w_0):
    # Make sure of column vectors:
    a, b = to_column(a), to_column(b)
    # Compute z:
    denominator = np.sqrt(np.linalg.det((mo.mldivide(A,B)+I)))
    z = (w_0/denominator) * np.exp(-.5*((a-b).T).dot(mo.mldivide((A+B),(a-b))))   
    return(z[0][0])
    def filtering(self, x0, p0, Y):
        # 0. Initiation
        N_TIME_STEPS = len(Y)
        self.X_DIM   = x0.shape[1]
        self.Y_DIM   = Y.shape[1]
        
        x_ = p_ = x__ = p__ = None
        X_ = P_ = X__ = P__ = None
        
        #
        # FILTERING LOOP
        for k in range(0, N_TIME_STEPS): 
            print(str(k) + "/" + str(N_TIME_STEPS))
            #
            # 1. Prediction    
            if(k == 0):
                x__, p__ = x0.T, p0
            else:
                B = self.model.getB(x_, k)
                Q = self.model.Q
                
                x__, p__, _ = self.integrate(x_, p_, self.model.f, k)
                p__         = p__ + B.dot(Q).dot(B.T)
                p__         = symetrize_cov(p__)
            #
            # 2. Update
            G = self.model.getG(x__, k)
            R = self.model.R
            
            mu, S, C = self.integrate(x__, p__, self.model.h, k)
            S        = S + G.dot(R).dot(G.T)
            S        = symetrize_cov(S)
            
            #
            # 3. Get estimates
            eps = Y[k] - to_row(mu)
            eps = to_column(eps)
            
            # TODO: Version with K computed
            # K = mo.mrdivide(C, S)
            # K = C.dot(np.linalg.inv(S))
            # x_ = x__ + K.dot(eps)
            # p_ = p__ - K.dot(S).dot(K.T)
            # p_ = symetrize_cov(p_)

            # TODO: Version without direct computation of K
            x_ = x__ + C.dot(mo.mldivide(S, eps))
            p_ = p__ - C.dot(mo.mrdivide(C,S).T)
            p_ = symetrize_cov(p_)       
            
            #
            # 4. Save results
            X__ = x__.T           if k==0 else np.vstack([X__, x__.T])
            P__ = np.array([p__]) if k==0 else np.vstack([P__, [p__]])
            X_  = x_.T            if k==0 else np.vstack([X_,  x_.T])   
            P_  = np.array([p_])  if k==0 else np.vstack([P_,  [p_]])
            
        return(X_, X__, P_, P__)
 def filtering(self, x0, p0, Y):
     # 0. Initiation
     N_TIME_STEPS = len(Y)
     self.X_DIM   = x0.shape[1]
     self.Y_DIM   = Y.shape[1]
     
     x_ = p_ = x__ = p__ = None
     X_ = P_ = X__ = P__ = None
     
     #
     # FILTERING LOOP
     for k in range(0, N_TIME_STEPS): 
         #
         # 1. Prediction    
         if(k == 0):
             x__, p__ = x0.T, p0
         else:
             B = self.model.getB(x_, k)
             Q = self.model.Q
             
             x__, p__, _ = self.unscented_transform(self.model.f, x_, p_, self.kappa, k=k)
             p__         = p__ + B.dot(Q).dot(B.T)
             p__         = symetrize_cov(p__)
             
         #
         # 2. Update
         G = self.model.getG(x__, k)
         R = self.model.R
         
         mu, S, C = self.unscented_transform(self.model.h, x__, p__, self.kappa, k=k)
         S        = S + G.dot(R).dot(G.T)
         S        = symetrize_cov(S)
         
         #
         # 3. Get estimates
         K = mo.mrdivide(C, S)
         # K = C.dot(np.linalg.inv(S))
         eps = np.array([Y[k]]).T - mu   
         x_ = x__ + K.dot(eps)
         p_ = p__ - K.dot(S).dot(K.T)
         p_ = symetrize_cov(p_)
         
         #
         # 4. Save results
         X__ = x__.T           if k==0 else np.vstack([X__, x__.T])
         P__ = np.array([p__]) if k==0 else np.vstack([P__, [p__]])
         X_  = x_.T            if k==0 else np.vstack([X_,  x_.T])   
         P_  = np.array([p_])  if k==0 else np.vstack([P_,  [p_]])
         
     return(X_, X__, P_, P__)
Example #4
0
# # # print MagneticTable

# # # print "\n\n   Lagrange convergence"
# # # LagrangeTitles = ["Total DoF","R DoF","Soln Time","Iter","R-L2","R-order","R-H1","H1-order"]
# # # LagrangeValues = np.concatenate((Wdim,Qdim,SolTime,OuterIt,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")
# # # print LagrangeTable

LatexTitlesB = ["l","B DoF","R DoF","BB-L2","B-order","BB-Curl","Curl-order"]
LatexValuesB = numpy.concatenate((NN,Vdim,Qdim,errL2b,l2border,errCurlb,Curlborder),axis=1)
LatexTableB= pd.DataFrame(LatexValuesB, columns = LatexTitlesB)
pd.set_option('precision',3)
LatexTableB = MO.PandasFormat(LatexTableB,'BB-Curl',"%2.4e")
LatexTableB = MO.PandasFormat(LatexTableB,'BB-L2',"%2.4e")
LatexTableB = MO.PandasFormat(LatexTableB,'Curl-order',"%2.2f")
LatexTableB = MO.PandasFormat(LatexTableB,'B-order',"%2.2f")
print LatexTableB.to_latex()



LatexTitlesR = ["l","B DoF","R DoF","R-L2","R-order","R-H1","H1-order"]
LatexValuesR = numpy.concatenate((NN,Vdim,Qdim,errL2r,l2rorder,errH1r,H1rorder),axis=1)
LatexTableR= pd.DataFrame(LatexValuesR, columns = LatexTitlesR)
pd.set_option('precision',3)
LatexTableR = MO.PandasFormat(LatexTableR,'R-L2',"%2.4e")
LatexTableR = MO.PandasFormat(LatexTableR,'R-H1',"%2.4e")
LatexTableR = MO.PandasFormat(LatexTableR,'R-order',"%2.2f")
LatexTableR = MO.PandasFormat(LatexTableR,'H1-order',"%2.2f")
Example #5
0
File: MHD.py Project: daveb-dev/UBC
        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



print "\n\n   Velocity convergence"
VelocityTitles = ["Total DoF","V DoF","Picard","Soln Time","V-L2","L2-order","V-H1","H1-order"]
VelocityValues = np.concatenate((Wdim,Velocitydim,TotalIters,SolTime,errL2u,l2uorder,errH1u,H1uorder),axis=1)
VelocityTable= pd.DataFrame(VelocityValues, columns = VelocityTitles)
pd.set_option('precision',3)
VelocityTable = MO.PandasFormat(VelocityTable,"V-L2","%2.4e")
VelocityTable = MO.PandasFormat(VelocityTable,'V-H1',"%2.4e")
VelocityTable = MO.PandasFormat(VelocityTable,"H1-order","%1.2f")
VelocityTable = MO.PandasFormat(VelocityTable,'L2-order',"%1.2f")
print VelocityTable

print "\n\n   Pressure convergence"
PressureTitles = ["Total DoF","P DoF","Picard","Soln Time","P-L2","L2-order"]
PressureValues = np.concatenate((Wdim,Pressuredim,TotalIters,SolTime,errL2p,l2porder),axis=1)
PressureTable= pd.DataFrame(PressureValues, columns = PressureTitles)
pd.set_option('precision',3)
PressureTable = MO.PandasFormat(PressureTable,"P-L2","%2.4e")
PressureTable = MO.PandasFormat(PressureTable,'L2-order',"%1.2f")
print PressureTable

Example #6
0
def foo():
    m = 7

    errL2u = np.zeros((m - 1, 1))
    errH1u = np.zeros((m - 1, 1))
    errL2p = np.zeros((m - 1, 1))
    errL2b = np.zeros((m - 1, 1))
    errCurlb = np.zeros((m - 1, 1))
    errL2r = np.zeros((m - 1, 1))
    errH1r = np.zeros((m - 1, 1))

    l2uorder = np.zeros((m - 1, 1))
    H1uorder = np.zeros((m - 1, 1))
    l2porder = np.zeros((m - 1, 1))
    l2border = np.zeros((m - 1, 1))
    Curlborder = np.zeros((m - 1, 1))
    l2rorder = np.zeros((m - 1, 1))
    H1rorder = np.zeros((m - 1, 1))

    NN = np.zeros((m - 1, 1))
    DoF = np.zeros((m - 1, 1))
    Velocitydim = np.zeros((m - 1, 1))
    Magneticdim = np.zeros((m - 1, 1))
    Pressuredim = np.zeros((m - 1, 1))
    Lagrangedim = np.zeros((m - 1, 1))
    Wdim = np.zeros((m - 1, 1))
    iterations = np.zeros((m - 1, 1))
    SolTime = np.zeros((m - 1, 1))
    udiv = np.zeros((m - 1, 1))
    MU = np.zeros((m - 1, 1))
    level = np.zeros((m - 1, 1))
    NSave = np.zeros((m - 1, 1))
    Mave = np.zeros((m - 1, 1))
    TotalTime = np.zeros((m - 1, 1))

    nn = 2

    dim = 2
    ShowResultPlots = 'yes'
    split = 'Linear'
    MU = 100.0
    for yy in xrange(1, 5):
        MU = MU / 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
            kappa = 1.0
            Mu_m = 1e1
            IterType = 'MD'

            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()

                if iter > 3 and uNorm < u.norm():
                    iter = 100000
                    break
                uNorm = 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()
Example #7
0
    kappa = 1.0
    Mu_m = 10.0
    MU = 1.0 / 1
    IterType = 'Full'
    Split = "No"
    Saddle = "No"
    Stokes = "No"
    SetupType = 'python-class'
    F_NS = -MU * Laplacian + Advection + gradPres - kappa * NS_Couple
    if kappa == 0:
        F_M = Mu_m * CurlCurl + gradR - kappa * M_Couple
    else:
        F_M = Mu_m * kappa * CurlCurl + gradR - kappa * M_Couple
    params = [kappa, Mu_m, MU]

    MO.PrintStr("Seting up initial guess matricies", 2, "=", "\n\n", "\n")
    BCtime = time.time()
    BC = MHDsetup.BoundaryIndices(mesh)
    MO.StrTimePrint("BC index function, time: ", time.time() - BCtime)
    Hiptmairtol = 1e-5
    HiptmairMatrices = PrecondSetup.MagneticSetup(mesh, 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"), degree=4),options ="New")
    domains = CellFunction("size_t", mesh)
    domains.set_all(0)

    boundaries = FacetFunction("size_t", mesh)
    boundaries.set_all(0)
Example #8
0
def MagneticSetup(Magnetic, Lagrange, u0, p0, CGtol, params):
    MO.PrintStr("Preconditioning Magnetic setup", 3, "=")

    #    parameters['linear_algebra_backend'] = 'uBLAS'
    if Magnetic.__str__().find("N1curl2") == -1:
        C, P = HiptmairSetup.HiptmairMatrixSetupBoundary(
            Magnetic.mesh(), Magnetic.dim(), Lagrange.dim(),
            Magnetic.mesh().geometry().dim())
        G, P = HiptmairSetup.HiptmairBCsetupBoundary(C, P, Magnetic.mesh())
    else:
        G = None
        P = None

    u = TrialFunction(Magnetic)
    v = TestFunction(Magnetic)
    p = TrialFunction(Lagrange)
    q = TestFunction(Lagrange)

    def boundary(x, on_boundary):
        return on_boundary

    bcp = DirichletBC(Lagrange, p0, boundary)
    bcu = DirichletBC(Magnetic, u0, boundary)

    tic()
    ScalarLaplacian, b1 = assemble_system(
        inner(grad(p), grad(q)) * dx,
        inner(p0, q) * dx, bcp)
    VectorLaplacian, b2 = assemble_system(
        inner(grad(p), grad(q)) * dx + inner(p, q) * dx,
        inner(p0, q) * dx, bcp)
    del b1, b2
    print("{:40}"
          ).format("Hiptmair Laplacians BC assembled, time: "), " ==>  ", (
              "{:4f}").format(
                  toc()), ("{:9}").format("   time: "), ("{:4}").format(
                      time.strftime('%X %x %Z')[0:5])

    tic()
    VectorLaplacian = PETSc.Mat().createAIJ(
        size=VectorLaplacian.sparray().shape,
        csr=(VectorLaplacian.sparray().indptr,
             VectorLaplacian.sparray().indices,
             VectorLaplacian.sparray().data))
    ScalarLaplacian = PETSc.Mat().createAIJ(
        size=ScalarLaplacian.sparray().shape,
        csr=(ScalarLaplacian.sparray().indptr,
             ScalarLaplacian.sparray().indices,
             ScalarLaplacian.sparray().data))
    print("{:40}").format("PETSc Laplacians assembled, time: "), " ==>  ", (
        "{:4f}").format(toc()), ("{:9}").format("   time: "), ("{:4}").format(
            time.strftime('%X %x %Z')[0:5])

    tic()
    if params[0] == 0:
        CurlCurlShift, b2 = assemble_system(
            params[1] * inner(curl(u), curl(v)) * dx + inner(u, v) * dx,
            inner(u0, v) * dx, bcu)
    else:
        CurlCurlShift, b2 = assemble_system(
            params[0] * params[1] * inner(curl(u), curl(v)) * dx +
            inner(u, v) * dx,
            inner(u0, v) * dx, bcu)
    CurlCurlShift = PETSc.Mat().createAIJ(size=CurlCurlShift.sparray().shape,
                                          csr=(CurlCurlShift.sparray().indptr,
                                               CurlCurlShift.sparray().indices,
                                               CurlCurlShift.sparray().data))
    print("{:40}").format("Shifted Curl-Curl assembled, time: "), " ==>  ", (
        "{:4f}").format(toc()), ("{:9}").format("   time: "), ("{:4}").format(
            time.strftime('%X %x %Z')[0:5])

    tic()
    kspVector, kspScalar, kspCGScalar, diag = HiptmairSetup.HiptmairKSPsetup(
        VectorLaplacian, ScalarLaplacian, CurlCurlShift, CGtol)
    del VectorLaplacian, ScalarLaplacian
    print("{:40}").format("Hiptmair Setup time:"), " ==>  ", ("{:4f}").format(
        toc()), ("{:9}").format("   time: "), ("{:4}").format(
            time.strftime('%X %x %Z')[0:5])

    return [G, P, kspVector, kspScalar, kspCGScalar, diag, CurlCurlShift]
Example #9
0
    IterType = 'Full'
    Split = "No"
    Saddle = "No"
    Stokes = "No"
    SetupType = 'python-class'
    params = [kappa, Mu_m, MU]

    F_M = Expression(("0.0", "0.0"), degree=4)
    F_S = Expression(("0.0", "0.0"), degree=4)

    b0 = Expression(("1.0", "0.0"), degree=4)
    u0 = Expression(("1.0", "0.0"), degree=4)
    r0 = Expression(("0.0"), degree=4)

    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(mesh, Magnetic, Lagrange, b0,
                                                  r0, Hiptmairtol, params)

    MO.PrintStr("Setting up MHD initial guess", 5, "+", "\n\n", "\n\n")
    u_k, p_k = CavityDriven.Stokes(Velocity, Pressure, F_S, params, boundaries,
                                   domains, mesh)
    b_k, r_k = CavityDriven.Maxwell(Magnetic, Lagrange, F_M, params,
                                    HiptmairMatrices, Hiptmairtol, mesh)

    n = FacetNormal(mesh)
    (u, p, b, r) = TrialFunctions(W)
Example #10
0
def Maxwell(V, Q, F, b0, r0, params, mesh, HiptmairMatrices, Hiptmairtol):
    parameters['reorder_dofs_serial'] = False

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

    IS = MO.IndexSet(W)

    (b, r) = TrialFunctions(W)
    (c, s) = TestFunctions(W)
    if params[0] == 0.0:
        a11 = params[1] * inner(curl(b), curl(c)) * dx
    else:
        a11 = params[1] * params[0] * inner(curl(b), curl(c)) * dx
    a21 = inner(b, grad(s)) * dx
    a12 = inner(c, grad(r)) * dx
    # print F
    L = inner(c, F) * dx
    a = a11 + a12 + a21

    def boundary(x, on_boundary):
        return on_boundary

    # class b0(Expression):
    #     def __init__(self):
    #         self.p = 1
    #     def eval_cell(self, values, x, ufc_cell):
    #         values[0] = 0.0
    #         values[1] = 1.0
    #     def value_shape(self):
    #         return (2,)

    bcb = DirichletBC(W.sub(0), b0, boundary)
    bcr = DirichletBC(W.sub(1), r0, boundary)
    bc = [bcb, bcr]

    A, b = assemble_system(a, L, bc)
    A, b = CP.Assemble(A, b)
    u = b.duplicate()

    # ksp = PETSc.KSP()
    # ksp.create(comm=PETSc.COMM_WORLD)
    # pc = ksp.getPC()
    # ksp.setType('preonly')
    # pc.setType('lu')
    # OptDB = PETSc.Options()
    # OptDB['pc_factor_mat_solver_package']  = "pastix"
    # OptDB['pc_factor_mat_ordering_type']  = "rcm"
    # ksp.setFromOptions()

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

    b_k = Function(FunctionSpace(mesh, V))
    r_k = Function(FunctionSpace(mesh, Q))
    b_k.vector()[:] = u.getSubVector(IS[0]).array
    r_k.vector()[:] = u.getSubVector(IS[1]).array

    return b_k, r_k
Example #11
0
    print errL2b[xx - 1]
    print errCurlb[xx - 1]
    print " \n\n\n\n"

import pandas as pd

# plot(xa)
# plot(u)

LatexTitlesB = ["l", "B DoF", "BB-L2", "B-order", "BB-Curl", "Curl-order"]
LatexValuesB = numpy.concatenate(
    (NN, DimSave, errL2b, l2border, errCurlb, Curlborder), axis=1)
LatexTableB = pd.DataFrame(LatexValuesB, columns=LatexTitlesB)
pd.set_option('precision', 3)
LatexTableB = MO.PandasFormat(LatexTableB, 'BB-Curl', "%2.4e")
LatexTableB = MO.PandasFormat(LatexTableB, 'BB-L2', "%2.4e")
LatexTableB = MO.PandasFormat(LatexTableB, 'Curl-order', "%2.2f")
LatexTableB = MO.PandasFormat(LatexTableB, 'B-order', "%2.2f")
print LatexTableB  #.to_latex()

print "\n\n\n"
ItsTitlesB = ["l", "B DoF", "Time", "Iterations"]
ItsValuesB = numpy.concatenate((NN, DimSave, TimeSave, ItsSave), axis=1)
ItsTableB = pd.DataFrame(ItsValuesB, columns=ItsTitlesB)
pd.set_option('precision', 5)
print ItsTableB.to_latex()

interactive()

GradTests = ["l", "B DoF", "$AC$", "$MC-B^T$", "$BC-L$"]
Example #12
0
        OptDB = PETSc.Options()
        ksp.max_it = 1000
        # OptDB['pc_factor_shift_amount'] = 1
        # OptDB['pc_factor_mat_ordering_type'] = 'rcm'
        # OptDB['pc_factor_mat_solver_package']  = 'mumps'
        ksp.setFromOptions()


        x = r

        toc()
        ksp.solve(b, x)

        time = toc()
        print time
        MO.StrTimePrint("Solve time",time)
        SolutionTime = SolutionTime +time
        outerit += ksp.its
        print "==============", ksp.its
        # r = bb.duplicate()
        # A.MUlt(x, r)
        # r.aypx(-1, bb)
        # rnorm = r.norm()
        # PETSc.Sys.Print('error norm = %g' % rnorm,comm=PETSc.COMM_WORLD)

        uu = IO.vecToArray(x)
        UU = uu[0:Vdim[xx-1][0]]
        # time = time+toc()
        u1 = Function(V)
        u1.vector()[:] = UU
def compute_z(a,A,b,B,I,w_0):
    # Make sure of column vectors:
    a, b = to_column(a), to_column(b)
    # Compute z:
    denominator = np.sqrt(np.linalg.det((mo.mldivide(A,B)+I)))
    z = (w_0/denominator) * np.exp(-.5*((a-b).T).dot(mo.mldivide((A+B),(a-b))))   
    return(z[0][0])

# - compute z
z = [compute_z(a, A, x0, p0, I, w_0) for a in X]
z = to_column(np.array(z))

K = gp.kern.K(X)
K = (K.T + K)/2.0

mu = (z.T).dot( mo.mldivide(K, Y) )
W = mo.mrdivide(z.T, K).squeeze().tolist()

_Sigma = None
_CC    = None

for i in range(0,len(z)):
    Y_squared_i = ( to_column(Y[i]-mu) ).dot( to_row(Y[i]-mu) )
    _Sigma       = W[i] * Y_squared_i if i == 0 else _Sigma + W[i] * Y_squared_i
    
    XY_squared_i = ( to_column((X[i]-x0)) ).dot( to_row(Y[i]-mu) )
    _CC           = W[i] * XY_squared_i if i == 0 else _CC + W[i] * XY_squared_i
    
_Sigma = _Sigma + cov_Q 
Sigma = (_Sigma + _Sigma.T)/2.0
CC = _CC
    def integrate(self, m, P, fun, *args):
        ''' Input:
            m - column vector
            P - matrix
            Output:
            x - column vector
            Variables:
            X, Y - matrix of row vectors
            z - column vector
            m, x, mu - row vector
        ''' 
        
        # Initial sample and fitted GP:
        m = to_row(m)
        X = m
        Y = np.apply_along_axis(fun, 1, X, *args)
        gp = self.gp_fit(X,Y)
        
        # Optimization constraints:
        N_SIGMA = 3
        P_diag = np.sqrt(np.diag(P))
        lower_const = (m - N_SIGMA*P_diag)[0].tolist()
        upper_const = (m + N_SIGMA*P_diag)[0].tolist()
        
        # Perform sampling
        for i in range(0, self.N_SAMPLES):
            # Set extra params to pass to optimizer
            user_data  = {"gp":gp, "m":m, "P":P, "grid_search": False}
            
            if (X.shape[1] == 1):
                ''' GRID SEARCH: when we are in 1 dimension '''
                user_data['grid_search'] = True
                X_grid = np.linspace(lower_const[0], upper_const[0], self.opt_par["GRID_SIZE"])
                X_grid = to_column(X_grid)
                
                objective = self.optimization_objective(X_grid, user_data)

                max_ind = objective.index(max(objective))                
                x_star = np.array([X_grid[max_ind]])    
            else:
                ''' OPTIMIZATION: for higher dimensions '''
                x_star, _, _ = solve(self.optimization_objective, lower_const, upper_const, 
                                 user_data=user_data, algmethod = 1, 
                                 maxT = self.opt_par["MAX_T"], 
                                 maxf = self.opt_par["MAX_F"])
            
            x_star = to_row(x_star)                           
            X      = np.vstack((X, x_star))
            Y      = np.apply_along_axis(fun, 1, X, *args)
            gp     = self.gp_fit(X, Y)    
        # Reoptimize GP:                             
        # TODO: Remove unique rows:
        if (len(unique_rows(X)) != len(X)):
            print("Removing duplicated rows")
            X  = unique_rows(X)
            Y  = np.apply_along_axis(fun, 1, X, *args)
            gp = self.gp_fit(X, Y)             
            
        # Compute integral
        # Fitted GP parameters      
        w_0 = gp.rbf.variance.tolist()[0]
        w_d = np.power(gp.rbf.lengthscale.tolist(), 2)
        
        # Prior parameters
        A = np.diag(w_d)
        I = np.eye(self.X_DIM)     
        
        # Compute weigths
        z = [self.compute_z(x, A, m, P, I, w_0) for x in X]
        z = to_column(np.array(z))
        K = gp.kern.K(X); K = (K.T + K)/2.0
        W = (mo.mrdivide(z.T, K).squeeze()).tolist()
        
        # Compute mean, covariance and cross-cov
        mu_ = (z.T).dot( mo.mldivide(K, Y) )
        mu_ = to_row(mu_)
        
        # Initiale Sigma and CC
        Sigma_ = CC_ = None     
        
        # TODO: Sigma computation as closed form
        # Seems to cause problems!
        # Sigma_ = w_0/np.sqrt(np.linalg.det( 2*mo.mldivide(A,P) + I) ) - (z.T).dot(mo.mldivide(K,z))
        
        # Compute cov matrix and cross cov matrix
        for i in range(0,len(W)):
        
            # TODO: Sigma computation as sumation: 
            # Seems to work better for multidimensional problems and doesn't
            # cause problems (might be slower though):
            YY_i   = ( to_column(Y[i]-mu_) ).dot( to_row(Y[i]-mu_) )
            Sigma_ = W[i] * YY_i if i == 0 else Sigma_ + W[i] * YY_i
            
            XY_i = ( to_column(X[i]-m) ).dot( to_row(Y[i]-mu_) )
            CC_  = W[i] * XY_i if i == 0 else CC_ + W[i] * XY_i
        
        mu_    = to_column(mu_)
        Sigma_ = symetrize_cov(Sigma_)
        
        # Return results
        return(mu_, Sigma_, CC_)
Example #15
0
def foo():
    m = 6

    errL2u = np.zeros((m - 1, 1))
    errH1u = np.zeros((m - 1, 1))
    errL2p = np.zeros((m - 1, 1))
    errL2b = np.zeros((m - 1, 1))
    errCurlb = np.zeros((m - 1, 1))
    errL2r = np.zeros((m - 1, 1))
    errH1r = np.zeros((m - 1, 1))

    l2uorder = np.zeros((m - 1, 1))
    H1uorder = np.zeros((m - 1, 1))
    l2porder = np.zeros((m - 1, 1))
    l2border = np.zeros((m - 1, 1))
    Curlborder = np.zeros((m - 1, 1))
    l2rorder = np.zeros((m - 1, 1))
    H1rorder = np.zeros((m - 1, 1))

    NN = np.zeros((m - 1, 1))
    DoF = np.zeros((m - 1, 1))
    Velocitydim = np.zeros((m - 1, 1))
    Magneticdim = np.zeros((m - 1, 1))
    Pressuredim = np.zeros((m - 1, 1))
    Lagrangedim = np.zeros((m - 1, 1))
    Wdim = np.zeros((m - 1, 1))
    iterations = np.zeros((m - 1, 1))
    SolTime = np.zeros((m - 1, 1))
    udiv = np.zeros((m - 1, 1))
    MU = np.zeros((m - 1, 1))
    level = np.zeros((m - 1, 1))
    NSave = np.zeros((m - 1, 1))
    Mave = np.zeros((m - 1, 1))
    TotalTime = np.zeros((m - 1, 1))

    nn = 2

    dim = 2
    ShowResultPlots = 'yes'
    split = 'Linear'

    MU[0] = 1e0
    for xx in xrange(1, m):
        print xx
        level[xx - 1] = xx + 0
        nn = 2**(level[xx - 1])

        # Create mesh and define function space
        nn = int(nn)
        NN[xx - 1] = nn / 2
        # parameters["form_compiler"]["quadrature_degree"] = 6
        # parameters = CP.ParameterSetup()
        mesh = UnitSquareMesh(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, b0, boundary)
        bcr = DirichletBC(Lagrange, r0, boundary)

        # bc = [u0,p0,b0,r0]
        bcs = [bcu, bcb, bcr]
        FSpaces = [Velocity, Pressure, Magnetic, Lagrange]

        (u, b, p, r) = TrialFunctions(W)
        (v, c, q, s) = TestFunctions(W)
        kappa = 1.0
        Mu_m = 10.0
        MU = 1.0 / 1
        IterType = 'Full'
        Split = "No"
        Saddle = "No"
        Stokes = "No"
        SetupType = 'python-class'
        F_NS = -MU * Laplacian + Advection + gradPres - kappa * NS_Couple
        if kappa == 0:
            F_M = Mu_m * CurlCurl + gradR - kappa * M_Couple
        else:
            F_M = Mu_m * kappa * CurlCurl + gradR - kappa * M_Couple
        params = [kappa, Mu_m, MU]

        MO.PrintStr("Seting up initial guess matricies", 2, "=", "\n\n", "\n")
        BCtime = time.time()
        BC = MHDsetup.BoundaryIndices(mesh)
        MO.StrTimePrint("BC index function, time: ", time.time() - BCtime)
        Hiptmairtol = 1e-5
        HiptmairMatrices = PrecondSetup.MagneticSetup(Magnetic, Lagrange, b0,
                                                      r0, Hiptmairtol, params)

        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(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)
            stime = time.time()
            u, mits, nsits = S.solve(A, b, u, params, W, 'Directs', 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


#
#        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

    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()
Example #16
0
def Maxwell(V, Q, F, b0, r0, params, boundaries, bNone, mesh, HiptmairMatrices,
            Hiptmairtol):
    parameters['reorder_dofs_serial'] = False

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

    IS = MO.IndexSet(W)
    print params
    (b, r) = TrialFunctions(W)
    (c, s) = TestFunctions(W)

    a11 = params[1] * params[2] * inner(curl(b), curl(c)) * dx('everywhere')
    a21 = inner(b, grad(s)) * dx('everywhere')
    a12 = inner(c, grad(r)) * dx('everywhere')
    L = inner(c, F) * dx('everywhere')
    a = a11 + a12 + a21

    def boundary(x, on_boundary):
        return on_boundary

    bcb1 = DirichletBC(W.sub(0), b0, boundaries, 1)
    bcb2 = DirichletBC(W.sub(0), Expression(("0.0", "0.0"), degree=3),
                       boundaries, 2)
    bcb3 = DirichletBC(W.sub(0), bNone, boundaries, 2)
    bcb4 = DirichletBC(W.sub(0), b0, boundaries, 2)

    bcr = DirichletBC(W.sub(1), r0, boundary)
    bc = [bcb1, bcb2, bcr]

    A, b = assemble_system(a, L, bc)
    A, b = CP.Assemble(A, b)
    u = b.duplicate()

    # ksp = PETSc.KSP()
    # ksp.create(comm=PETSc.COMM_WORLD)
    # pc = ksp.getPC()
    # ksp.setType('preonly')
    # pc.setType('lu')
    # OptDB = PETSc.Options()
    # OptDB['pc_factor_mat_solver_package']  = "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(
        MP.Hiptmair(W, HiptmairMatrices[3], HiptmairMatrices[4],
                    HiptmairMatrices[2], HiptmairMatrices[0],
                    HiptmairMatrices[1], HiptmairMatrices[6], Hiptmairtol))
    scale = b.norm()
    b = b / scale
    ksp.setOperators(A, A)
    del A
    start_time = time.time()
    ksp.solve(b, u)
    print("{:40}").format("Maxwell solve, time: "), " ==>  ", (
        "{:4f}").format(time.time() - start_time), (
            "{:9}").format("   Its: "), ("{:4}").format(
                ksp.its), ("{:9}").format("   time: "), ("{:4}").format(
                    time.strftime('%X %x %Z')[0:5])
    u = u * scale
    b_k = Function(FunctionSpace(mesh, V))
    r_k = Function(FunctionSpace(mesh, Q))
    b_k.vector()[:] = u.getSubVector(IS[0]).array
    r_k.vector()[:] = u.getSubVector(IS[1]).array

    return b_k, r_k
Example #17
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
# The TestErrors file will be a runnable file
# that demonstrates that the errors written in MatrixExceptions are functioning correctly

from Matrix import Matrix
import MatrixOperations

# creates a Matrix of size 3x3 and initializes it with some basic integers
m = Matrix(3, 3)
MatrixOperations.printout(m)
new_row = [3, 3, 2]
MatrixOperations.replace_row(m, 0, new_row)

MatrixOperations.printout(m)
too_big_row = [1, 2, 3, 4]
MatrixOperations.replace_row(m, 2, too_big_row)

MatrixOperations.printout(m)

Example #19
0
    ErrorU = ua - ue
    errL2u[xx - 1] = sqrt(abs(assemble(inner(ErrorU, ErrorU) * dx)))
    errH1u[xx - 1] = sqrt(abs(assemble(inner(grad(ErrorU), grad(ErrorU)) *
                                       dx)))

    # errL2u[xx-1] = errornorm(ue, ua, norm_type='L2', degree_rise=8)
    # errH1u[xx-1] = errornorm(ue, ua, norm_type='H10', degree_rise=8)

    if xx > 1:
        l2uorder[xx - 1] = np.abs(
            np.log2(errL2u[xx - 2] / errL2u[xx - 1]) /
            np.log2(sqrt(float(Vdim[xx - 1][0]) / Vdim[xx - 2][0])))
        H1uorder[xx - 1] = np.abs(
            np.log2(errH1u[xx - 2] / errH1u[xx - 1]) /
            np.log2(sqrt(float(Vdim[xx - 1][0]) / Vdim[xx - 2][0])))

import pandas as pd

# dplot(ua, interactive=True)

LatexTitles = ["l", "DoFu", "V-L2", "L2-order", "V-H1", "H1-order"]
LatexValues = np.concatenate((level, Vdim, errL2u, l2uorder, errH1u, H1uorder),
                             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")
print LatexTable
Example #20
0

import pandas as pd
# tableTitles = ["Total DoF","V DoF","Q DoF","AvIt","V-L2","V-order","P-L2","P-order"]
# tableValues = np.concatenate((Wdim,Vdim,Qdim,AvIt,errL2u,l2uorder,errL2p,l2porder),axis=1)
# df = pd.DataFrame(tableValues, columns = tableTitles)
# pd.set_option('precision',3)
# print df
# print df.to_latex()

print "\n\n   Velocity convergence"
VelocityTitles = ["Total DoF","V DoF","Soln Time","AvIt","V-L2","L2-order","V-H1","H1-order"]
VelocityValues = np.concatenate((Wdim,Vdim,SolTime,AvIt,errL2u,l2uorder,errH1u,H1uorder),axis=1)
VelocityTable= pd.DataFrame(VelocityValues, columns = VelocityTitles)
pd.set_option('precision',3)
VelocityTable = MO.PandasFormat(VelocityTable,"V-L2","%2.4e")
VelocityTable = MO.PandasFormat(VelocityTable,'V-H1',"%2.4e")
VelocityTable = MO.PandasFormat(VelocityTable,"H1-order","%1.2f")
VelocityTable = MO.PandasFormat(VelocityTable,'L2-order',"%1.2f")
print VelocityTable

print "\n\n   Pressure convergence"
PressureTitles = ["Total DoF","P DoF","Soln Time","AvIt","P-L2","L2-order"]
PressureValues = np.concatenate((Wdim,Qdim,SolTime,AvIt,errL2p,l2porder),axis=1)
PressureTable= pd.DataFrame(PressureValues, columns = PressureTitles)
pd.set_option('precision',3)
PressureTable = MO.PandasFormat(PressureTable,"P-L2","%2.4e")
PressureTable = MO.PandasFormat(PressureTable,'L2-order',"%1.2f")
print PressureTable

Example #21
0
        ksp.setOperators(A)
        OptDB = PETSc.Options()
        ksp.max_it = 1000
        # OptDB['pc_factor_shift_amount'] = 1
        # OptDB['pc_factor_mat_ordering_type'] = 'rcm'
        # OptDB['pc_factor_mat_solver_package']  = 'mumps'
        ksp.setFromOptions()

        x = r

        toc()
        ksp.solve(b, x)

        time = toc()
        print time
        MO.StrTimePrint("Solve time", time)
        SolutionTime = SolutionTime + time
        outerit += ksp.its
        print "==============", ksp.its
        # r = bb.duplicate()
        # A.MUlt(x, r)
        # r.aypx(-1, bb)
        # rnorm = r.norm()
        # PETSc.Sys.Print('error norm = %g' % rnorm,comm=PETSc.COMM_WORLD)

        uu = IO.vecToArray(x)
        UU = uu[0:Vdim[xx - 1][0]]
        # time = time+toc()
        u1 = Function(V)
        u1.vector()[:] = UU
Example #22
0
    # mesh = UnitSquareMesh(nn,nn)
    # set_log_level(WARNING)
    # p = plot(mesh)
    # p.write_png()
    # sss
    parameters['form_compiler']['quadrature_degree'] = -1
    order = 1
    parameters['reorder_dofs_serial'] = False
    Velocity = VectorFunctionSpace(mesh, "CG", 2)
    Pressure = FunctionSpace(mesh, "CG", 1)

    Velocitydim[xx - 1] = Velocity.dim()
    Pressuredim[xx - 1] = Pressure.dim()

    W = Velocity * Pressure
    IS = MO.IndexSet(W)

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

    kappa = 1.0
    Mu_m = float(1e4)
    MU = 1.0
    print v.shape()
    params = [kappa, Mu_m, MU]
    dx = Measure('dx', domain=mesh, subdomain_data=domains)
    ds = Measure('ds', domain=mesh, subdomain_data=boundaries)

    a11 = inner(grad(v), grad(u)) * dx(0)
    a12 = -div(v) * p * dx(0)
    a21 = -div(u) * q * dx(0)
Example #23
0
    u0, p0,b0, r0, Laplacian, Advection, gradPres,CurlCurl, gradR, NS_Couple, M_Couple = ExactSol.MHD2D(4,1)

    kappa = 1.0
    Mu_m =1e1
    MU = 1.0/1

    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-4, params)
    Hiptmairtol = 1e-6

    MO.PrintStr("Setting up MHD initial guess",5,"+","\n\n","\n\n")
    u_k,p_k,b_k,r_k = common.InitialGuess([Velocity, Pressure, Magnetic, Lagrange],[u0,p0,b0,r0],[F_NS,F_M],params,HiptmairMatrices,1e-6,options="New")

    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)

    KSPlinearfluids, MatrixLinearFluids = PrecondSetup.FluidLinearSetup(Pressure, MU)
    kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k)

    ns,maxwell,CoupleTerm,Lmaxwell,Lns = forms.MHD2D(mesh, W,F_M,F_NS, u_k,b_k,params,IterType)
    RHSform = forms.PicardRHS(mesh, W, u_k, p_k, b_k, r_k, params)
Example #24
0
File: MU.py Project: daveb-dev/UBC
            kappa = 1.0
            Mu_m = 10.0
            # MU = 1.0

            N = FacetNormal(mesh)

            # IterType = 'Full'

            params = [kappa,Mu_m,MU]
            n = FacetNormal(mesh)
            trunc = 4
            u0, p0, b0, r0, pN, Laplacian, Advection, gradPres, NScouple, CurlCurl, gradLagr, Mcouple = HartmanChannel.ExactSolution(mesh, params)
            # kappa = 0.0
            # 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(mesh, Magnetic, Lagrange, b0, r0, Hiptmairtol, params)

            MO.PrintStr("Setting up MHD initial guess",5,"+","\n\n","\n\n")
            print params
            F_NS = -MU*Laplacian + Advection + gradPres - kappa*NScouple
            if kappa == 0.0:
                F_M = Mu_m*CurlCurl + gradLagr - kappa*Mcouple
            else:
                F_M = Mu_m*kappa*CurlCurl + gradLagr - kappa*Mcouple
            u_k, p_k = HartmanChannel.Stokes(Velocity, Pressure, F_NS, u0, pN, params, mesh, boundaries, domains)
            b_k, r_k = HartmanChannel.Maxwell(Magnetic, Lagrange, F_M, b0, r0, params, mesh, HiptmairMatrices, Hiptmairtol)
Example #25
0
 def __init__(self, W, A):
     self.W = W
     self.A = A
     IS = MO.IndexSet(W)
     self.u_is = IS[0]
     self.p_is = IS[1]
Example #26
0
def Assemble(W, NS, Maxwell, Couple, L_ns, L_m, RHSform, BC, Type, IterType):
    
    tic() 
    if Type == 'NonLinear':
        F = assemble(NS[0])
        BC[0].apply(F)
        F = F.sparray()
        dim = W.mesh().geometry().dim()
        Vboundary = np.ones(W.sub(0).dim())
        Vboundary[F.diagonal() == 1] = 0
#        if dim == 3:
#            VelocityBoundary = np.concatenate((Vboundary,Vboundary,Vboundary),axis=1)
#        else:
#            VelocityBoundary = np.concatenate((Vboundary,Vboundary),axis=1)
        BC[3] = spdiags(Vboundary,0,W.sub(0).dim(),W.sub(0).dim())
        if IterType == 'Full':
            C = assemble(Couple[0])
            C = BC[4]*C.sparray()*BC[3]
        else:
            C = None
        if RHSform == 0:
            bu = assemble(L_ns)
            bp = Function(W[1]).vector() 
            print bp.array()
            bb = assemble(L_m)
            br = Function(W[3]).vector()
            BC[0].apply(bu)
            BC[1].apply(bb)
            BC[2].apply(br)
        else:
            bu = assemble(L_ns-RHSform[0])
            bp = assemble(-RHSform[1])
            bb = assemble(L_m-RHSform[2])
            br = assemble(-RHSform[3])
            BC[0].apply(bu)
            BC[1].apply(bb)
            BC[2].apply(br)
        b = np.concatenate((bu.array(),bp.array(),bb.array(),br.array()),axis = 0)

        MO.StrTimePrint("MHD non-linear matrix assembled, time: ",toc())
        return [F, C],b, BC[3]
    elif Type == 'Linear':
        

        M = assemble(Maxwell[0])
        D = assemble(Maxwell[2])
        SS = assemble(Maxwell[3])

        B = assemble(NS[2])
        if NS[3] != None:
            S = assemble(NS[3])
            S = S.sparray()
        else:
            S = None

        SS = 0*SS
        BC[1].apply(M)
        BC[2].apply(SS)  

        B = B.sparray()*BC[3]

        M = M.sparray()
        D = BC[4]*D.sparray()*BC[5]
        SS = SS.sparray()
        
        MO.StrTimePrint("MHD linear matrix assembled, time: ",toc())
        return [B,M,D,S,SS]
    else:
        bu = assemble(L_ns-RHSform[0])
        bp = assemble(-RHSform[1])
        bb = assemble(L_m-RHSform[2])
        br = assemble(-RHSform[3])
        BC[0].apply(bu)
        BC[1].apply(bb)
        BC[2].apply(br)
        b = np.concatenate((bu.array(),bp.array(),bb.array(),br.array()),axis = 0)
        return IO.arrayToVec(b)
Example #27
0
    a12 = -div(v) * p * dx
    a21 = -div(u) * q * dx

    a = a11 + a21 + a12

    Lns = inner(v, F_S) * dx  #+ inner(Neumann,v)*ds(2)

    a11 = params[2] * inner(grad(v), grad(u_k)) * dx + inner(
        (grad(u_k) * u_k), v) * dx + (1. / 2) * div(u_k) * inner(
            u_k, v) * dx - (1. / 2) * inner(u_k, n) * inner(u_k, v) * ds
    a12 = -div(v) * p_k * dx
    a21 = -div(u_k) * q * dx

    L = Lns - (a11 + a21 + a12)

    MO.PrintStr("Setting up MHD initial guess", 5, "+", "\n\n", "\n\n")

    ones = Function(Pressure)
    ones.vector()[:] = (0 * ones.vector().array() + 1)
    x = np.concatenate((u_k.vector().array(), p_k.vector().array()), axis=0)

    KSPlinearfluids, MatrixLinearFluids = PrecondSetup.FluidLinearSetup(
        Pressure, MU)
    kspFp, Fp = PrecondSetup.FluidNonLinearSetup(Pressure, MU, u_k)

    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
Example #28
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-4, 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")

    b_t = TrialFunction(Magnetic)
    c_t = TestFunction(Magnetic)
    #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])])
Example #29
0
def MagneticSetup(mesh, Magnetic, Lagrange, u0, p0, CGtol, params):
    MO.PrintStr("Preconditioning Magnetic setup", 3, "=")
    Magnetic = FunctionSpace(mesh, Magnetic)
    Lagrange = FunctionSpace(mesh, Lagrange)

    # parameters['linear_algebra_backend'] = 'uBLAS'
    if Magnetic.__str__().find("N1curl2") == -1:
        G, P = HiptmairSetup.HiptmairMatrixSetupBoundary(
            Magnetic.mesh(), Magnetic.dim(), Lagrange.dim(),
            Magnetic.mesh().geometry().dim())
        G, P = HiptmairSetup.HiptmairBCsetupBoundary(G, P, Magnetic.mesh())
    else:
        G = None
        P = None

    u = TrialFunction(Magnetic)
    v = TestFunction(Magnetic)
    p = TrialFunction(Lagrange)
    q = TestFunction(Lagrange)

    def boundary(x, on_boundary):
        return on_boundary

    bcp = DirichletBC(Lagrange, p0, boundary)
    bcu = DirichletBC(Magnetic, u0, boundary)

    tic()
    ScalarLaplacian, b1 = assemble_system(inner(grad(p), grad(q)) * dx,
                                          inner(p0, q) * dx,
                                          bcp,
                                          form_compiler_parameters=ffc_options)
    VectorLaplacian, b2 = assemble_system(
        (params[0] * params[1] * inner(grad(p), grad(q)) * dx +
         params[0] * params[1] * inner(p, q) * dx),
        inner(p0, q) * dx,
        bcp,
        form_compiler_parameters=ffc_options)
    del b1, b2
    print("{:40}"
          ).format("Hiptmair Laplacians BC assembled, time: "), " ==>  ", (
              "{:4f}").format(
                  toc()), ("{:9}").format("   time: "), ("{:4}").format(
                      time.strftime('%X %x %Z')[0:5])

    tic()
    VectorLaplacian = CP.Assemble(VectorLaplacian)
    ScalarLaplacian = CP.Assemble(ScalarLaplacian)
    print("{:40}").format("PETSc Laplacians assembled, time: "), " ==>  ", (
        "{:4f}").format(toc()), ("{:9}").format("   time: "), ("{:4}").format(
            time.strftime('%X %x %Z')[0:5])

    tic()
    if params[0] == 0:
        CurlCurlShift, b2 = assemble_system(
            params[1] * inner(curl(u), curl(v)) * dx + inner(u, v) * dx,
            inner(u0, v) * dx,
            bcu,
            form_compiler_parameters=ffc_options)
    else:
        CurlCurlShift, b2 = assemble_system(
            params[0] * params[1] * inner(curl(u), curl(v)) * dx +
            inner(u, v) * dx,
            inner(u0, v) * dx,
            bcu,
            form_compiler_parameters=ffc_options)
    CurlCurlShift = CP.Assemble(CurlCurlShift)
    print("{:40}").format("Shifted Curl-Curl assembled, time: "), " ==>  ", (
        "{:4f}").format(toc()), ("{:9}").format("   time: "), ("{:4}").format(
            time.strftime('%X %x %Z')[0:5])

    tic()
    kspVector, kspScalar, kspCGScalar, diag = HiptmairSetup.HiptmairKSPsetup(
        VectorLaplacian, ScalarLaplacian, CurlCurlShift, CGtol, G, mesh)
    del VectorLaplacian, ScalarLaplacian
    print("{:40}").format("Hiptmair Setup time:"), " ==>  ", ("{:4f}").format(
        toc()), ("{:9}").format("   time: "), ("{:4}").format(
            time.strftime('%X %x %Z')[0:5])

    return [G, P, kspVector, kspScalar, kspCGScalar, diag, CurlCurlShift]
Example #30
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
    # F_NS = Expression(('0.0','0.0'))
    # F_M = Expression(('0.0','0.0'))
    params = [kappa, Mu_m, MU]

    MO.PrintStr("Seting up initial guess matricies", 2, "=", "\n\n", "\n")
    BCtime = time.time()
    BC = MHDsetup.BoundaryIndices(mesh)
    MO.StrTimePrint("BC index function, time: ", time.time() - BCtime)
    Hiptmairtol = 1e-5
    HiptmairMatrices = PrecondSetup.MagneticSetup(Magnetic, Lagrange, b0, r0,
                                                  Hiptmairtol, params)

    MO.PrintStr("Setting up MHD initial guess", 5, "+", "\n\n", "\n\n")
    u_k, p_k, b_k, r_k = common.InitialGuess(FSpaces, [u0, p0, b0, r0],
                                             [F_NS, F_M],
                                             params,
                                             HiptmairMatrices,
                                             1e-10,
                                             Neumann=Expression(("0", "0")),
                                             options="New")
Example #31
0
 def __init__(self, W, A, bc):
     self.A = A
     self.IS = MO.IndexSet(W)
     self.bc = bc
Example #32
0
def Assemble(W, NS, Maxwell, Couple, L_ns, L_m, RHSform, BC, Type, IterType):

    tic()
    if Type == 'NonLinear':
        F = assemble(NS[0])
        BC[0].apply(F)
        F = F.sparray()
        if IterType == 'Full':
            C = assemble(Couple[0])
            C = BC[4] * C.sparray() * BC[3]
        else:
            C = None
        if RHSform == 0:
            bu = assemble(L_ns)
            bp = Function(W[1]).vector()
            print bp.array()
            bb = assemble(L_m)
            br = Function(W[3]).vector()
            BC[0].apply(bu)
            BC[1].apply(bb)
            BC[2].apply(br)
        else:
            bu = assemble(L_ns - RHSform[0])
            bp = assemble(-RHSform[1])
            bb = assemble(L_m - RHSform[2])
            br = assemble(-RHSform[3])
            BC[0].apply(bu)
            BC[1].apply(bb)
            BC[2].apply(br)
        b = np.concatenate((bu.array(), bp.array(), bb.array(), br.array()),
                           axis=0)

        MO.StrTimePrint("MHD non-linear matrix assembled, time: ", toc())
        return [F, C], b
    elif Type == 'Linear':

        M = assemble(Maxwell[0])
        D = assemble(Maxwell[2])
        SS = assemble(Maxwell[3])

        B = assemble(NS[2])
        S = assemble(NS[3])

        SS = 0 * SS
        BC[1].apply(M)
        BC[2].apply(SS)

        B = B.sparray() * BC[3]
        S = S.sparray()

        M = M.sparray()
        D = BC[4] * D.sparray() * BC[5]
        SS = SS.sparray()

        MO.StrTimePrint("MHD linear matrix assembled, time: ", toc())
        return [B, M, D, S, SS]
    else:
        bu = assemble(L_ns - RHSform[0])
        bp = assemble(-RHSform[1])
        bb = assemble(L_m - RHSform[2])
        br = assemble(-RHSform[3])
        BC[0].apply(bu)
        BC[1].apply(bb)
        BC[2].apply(br)
        b = np.concatenate((bu.array(), bp.array(), bb.array(), br.array()),
                           axis=0)
        return IO.arrayToVec(b)
Example #33
0
# LagrangeTitles = ["Total DoF","R DoF","Soln Time","Iter","R-L2","R-order","R-H1","H1-order"]
# LagrangeValues = np.concatenate((Wdim,Qdim,SolTime,OuterIt,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")
# print LagrangeTable

LatexTitlesB = [
    "l", "B DoF", "R DoF", "BB-L2", "B-order", "BB-Curl", "Curl-order"
]
LatexValuesB = np.concatenate(
    (NN, Vdim, Qdim, errL2b, l2border, errCurlb, Curlborder), axis=1)
LatexTableB = pd.DataFrame(LatexValuesB, columns=LatexTitlesB)
pd.set_option('precision', 3)
LatexTableB = MO.PandasFormat(LatexTableB, 'BB-Curl', "%2.4e")
LatexTableB = MO.PandasFormat(LatexTableB, 'BB-L2', "%2.4e")
LatexTableB = MO.PandasFormat(LatexTableB, 'Curl-order', "%2.2f")
LatexTableB = MO.PandasFormat(LatexTableB, 'B-order', "%2.2f")
print LatexTableB.to_latex()

LatexTitlesR = ["l", "B DoF", "R DoF", "R-L2", "R-order", "R-H1", "H1-order"]
LatexValuesR = np.concatenate(
    (NN, Vdim, Qdim, errL2r, l2rorder, errH1r, H1rorder), axis=1)
LatexTableR = pd.DataFrame(LatexValuesR, columns=LatexTitlesR)
pd.set_option('precision', 3)
LatexTableR = MO.PandasFormat(LatexTableR, 'R-L2', "%2.4e")
LatexTableR = MO.PandasFormat(LatexTableR, 'R-H1', "%2.4e")
LatexTableR = MO.PandasFormat(LatexTableR, 'R-order', "%2.2f")
LatexTableR = MO.PandasFormat(LatexTableR, 'H1-order', "%2.2f")
print LatexTableR.to_latex()
Example #34
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
Example #35
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'] = "pastix"
        OptDB['pc_factor_mat_ordering_type'] = "rcm"
        ksp.setFromOptions()
        scale = b.norm()
        b = b / scale
        ksp.setOperators(A, A)
        del A
        ksp.solve(b, u)
        # Mits +=dodim
        u = u * scale
        MO.PrintStr("Number iterations = " + str(ksp.its), 60, "+", "\n\n",
                    "\n\n")
        return u, ksp.its, 0
    elif SolveType == "Direct-class":
        ksp = PETSc.KSP()
        ksp.create(comm=PETSc.COMM_WORLD)
        pc = ksp.getPC()
        ksp.setType('gmres')
        pc.setType('none')
        ksp.setFromOptions()
        scale = b.norm()
        b = b / scale
        ksp.setOperators(A, A)
        del A
        ksp.solve(b, u)
        # Mits +=dodim
        u = u * scale
        MO.PrintStr("Number iterations = " + str(ksp.its), 60, "+", "\n\n",
                    "\n\n")
        return u, ksp.its, 0

    else:

        # u = b.duplicate()
        if IterType == "Full":
            ksp = PETSc.KSP()
            ksp.create(comm=PETSc.COMM_WORLD)
            pc = ksp.getPC()
            ksp.setType('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
            W = Fspace
            FFSS = [W.sub(0), W.sub(1), W.sub(2), W.sub(3)]
            pc.setPythonContext(
                MHDprec.InnerOuterMAGNETICinverse(
                    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.getSubMatrix(NS_is, NS_is))
        kspM.setOperators(A.getSubMatrix(M_is, M_is))
        # 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