Exemple #1
0
def run_test():
    #meshfile = expanduser(join(mfem_path, 'data', 'semi_circle.mesh'))
    meshfile = "../data/amr-quad.mesh"
    mesh = mfem.Mesh(meshfile, 1, 1)
    dim = mesh.Dimension()
    sdim = mesh.SpaceDimension()
    fec = mfem.H1_FECollection(1, dim)
    fespace = mfem.FiniteElementSpace(mesh, fec, 1)
    print('Number of finite element unknowns: ' + str(fespace.GetTrueVSize()))

    c = mfem.ConstantCoefficient(1.0)
    gf = mfem.GridFunction(fespace)
    gf.ProjectCoefficient(c)

    print("write mesh to STDOUT")
    mesh.Print(mfem.STDOUT)
    print("creat VTK file to file")
    mesh.PrintVTK('mesh.vtk', 1)
    print("creat VTK to STDOUT")
    mesh.PrintVTK(mfem.STDOUT, 1)
    print("save GridFunction to file")
    gf.Save('out_test_gridfunc.gf')
    gf.SaveVTK(mfem.wFILE('out_test_gridfunc1.vtk'), 'data', 1)
    print("save GridFunction to file in VTK format")
    gf.SaveVTK('out_test_gridfunc2.vtk', 'data', 1)
    print("Gridfunction to STDOUT")
    gf.Save(mfem.STDOUT)

    o = io.StringIO()
    count = gf.Save(o)
    count2 = gf.SaveVTK(o, 'data', 1)
    print("length of data ", count, count2)
    print('result: ', o.getvalue())
Exemple #2
0
def run_test():
    meshfile = expanduser(join(mfem_path, 'data', 'beam-tri.mesh'))
    mesh = mfem.Mesh(meshfile, 1, 1)
    fec = mfem.H1_FECollection(1, 1)
    fespace = mfem.FiniteElementSpace(mesh, fec)

    fespace.Save()
Exemple #3
0
def run_test():
    #meshfile =expanduser(join(mfem_path, 'data', 'beam-tri.mesh'))
    meshfile = expanduser(join(mfem_path, 'data', 'semi_circle.mesh'))
    mesh = mfem.Mesh(meshfile, 1, 1)
    dim = mesh.Dimension()
    sdim = mesh.SpaceDimension()
    fec = mfem.H1_FECollection(1, dim)
    fespace = mfem.FiniteElementSpace(mesh, fec, 1)
    print('Number of finite element unknowns: ' + str(fespace.GetTrueVSize()))

    c = mfem.ConstantCoefficient(1.0)
    gf = mfem.GridFunction(fespace)
    gf.ProjectCoefficient(c)

    gf.Save('out_test_gridfunc.gf')
Exemple #4
0
    mesh.SetCurvature(2)

mesh.EnsureNCMesh()
for l in range(ref_levels):
    mesh.UniformRefinement()

# 5. Define a parallel mesh by partitioning the serial mesh.  Once the
#    parallel mesh is defined, the serial mesh can be deleted.
pmesh = mfem.ParMesh(MPI.COMM_WORLD, mesh)
del mesh
ess_bdr = mfem.intArray(pmesh.bdr_attributes.Max())
ess_bdr.Assign(1)

# 6. Define a finite element space on the mesh. The polynomial order is one
#   (linear) by default, but this can be changed on the command line.
fec = mfem.H1_FECollection(order, dim)
fespace = mfem.ParFiniteElementSpace(pmesh, fec)

# 7. As in Example 1p, we set up bilinear and linear forms corresponding to
#    the Laplace problem -\Delta u = 1. We don't assemble the discrete
#    problem yet, this will be done in the inner loop.
a = mfem.ParBilinearForm(fespace)
b = mfem.ParLinearForm(fespace)

one = mfem.ConstantCoefficient(1.0)
bdr = BdrCoefficient()
rhs = RhsCoefficient()

integ = mfem.DiffusionIntegrator(one)
a.AddDomainIntegrator(integ)
b.AddDomainIntegrator(mfem.DomainLFIntegrator(rhs))
Exemple #5
0
#      degree may depend on the spatial dimension of the domain, the type of
#      the mesh and the trial space order.
trial_order = order
trace_order = order - 1
test_order = order  # reduced order, full order is (order + dim - 1)

if (dim == 2
        and (order % 2 == 0 or (pmesh.MeshGenerator() & 2 and order > 1))):
    test_order = test_order + 1
if (test_order < trial_order):
    if myid == 0:
        print(
            "Warning, test space not enriched enough to handle primal trial space"
        )

x0_fec = mfem.H1_FECollection(trial_order, dim)
xhat_fec = mfem.RT_Trace_FECollection(trace_order, dim)
test_fec = mfem.L2_FECollection(test_order, dim)

x0_space = mfem.ParFiniteElementSpace(pmesh, x0_fec)
xhat_space = mfem.ParFiniteElementSpace(pmesh, xhat_fec)
test_space = mfem.ParFiniteElementSpace(pmesh, test_fec)

glob_true_s0 = x0_space.GlobalTrueVSize()
glob_true_s1 = xhat_space.GlobalTrueVSize()
glob_true_s_test = test_space.GlobalTrueVSize()

if myid == 0:
    print('\n'.join([
        "nNumber of Unknowns", " Trial space,     X0   : " +
        str(glob_true_s0) + " (order " + str(trial_order) + ")",
Exemple #6
0
        mesh.AddTriangle(tri_e[j], j + 1)
    mesh.FinalizeTriMesh(1, 1, True)
else:
    quad_v = [[-1, -1, -1], [+1, -1, -1], [+1, +1, -1], [-1, +1, -1],
              [-1, -1, +1], [+1, -1, +1], [+1, +1, +1], [-1, +1, +1]]

    quad_e = [[3, 2, 1, 0], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6],
              [3, 0, 4, 7], [4, 5, 6, 7]]
    for j in range(Nvert):
        mesh.AddVertex(quad_v[j])
    for j in range(Nelem):
        mesh.AddQuad(quad_e[j], j + 1)
    mesh.FinalizeQuadMesh(1, 1, True)

#  Set the space for the high-order mesh nodes.
fec = mfem.H1_FECollection(order, mesh.Dimension())
nodal_fes = mfem.FiniteElementSpace(mesh, fec, mesh.SpaceDimension())
mesh.SetNodalFESpace(nodal_fes)


def SnapNodes(mesh):
    nodes = mesh.GetNodes()
    node = mfem.Vector(mesh.SpaceDimension())

    for i in np.arange(nodes.FESpace().GetNDofs()):
        for d in np.arange(mesh.SpaceDimension()):
            node[d] = nodes[nodes.FESpace().DofToVDof(i, d)]

        node /= node.Norml2()
        for d in range(mesh.SpaceDimension()):
            nodes[nodes.FESpace().DofToVDof(i, d)] = node[d]
Exemple #7
0
#    we do 'ser_ref_levels' of uniform refinement, where 'ser_ref_levels' is
#    a command-line parameter.
for lev in range(ser_ref_levels):
    mesh.UniformRefinement()

# 6. Define a parallel mesh by a partitioning of the serial mesh. Refine
#    this mesh further in parallel to increase the resolution. Once the
#    parallel mesh is defined, the serial mesh can be deleted.
pmesh = mfem.ParMesh(MPI.COMM_WORLD, mesh)
del mesh
for x in range(par_ref_levels):
    pmesh.UniformRefinement()

# 7. Define the vector finite element space representing the current and the
#    initial temperature, u_ref.
fe_coll = mfem.H1_FECollection(order, dim)
fespace = mfem.ParFiniteElementSpace(pmesh, fe_coll)

fe_size = fespace.GlobalTrueVSize()
if myid == 0:
    print("Number of temperature unknowns: " + str(fe_size))
u_gf = mfem.ParGridFunction(fespace)

# 8. Set the initial conditions for u. All boundaries are considered
#    natural.
u_0 = InitialTemperature()
u_gf.ProjectCoefficient(u_0)
u = mfem.Vector()
u_gf.GetTrueDofs(u)

# 9. Initialize the conduction operator and the visualization.
Exemple #8
0
def run(order = 1, static_cond = False,
        meshfile = def_meshfile, visualization = False,
        use_strumpack = False):

   mesh = mfem.Mesh(meshfile, 1,1)
   dim = mesh.Dimension()

   ref_levels = int(np.floor(np.log(10000./mesh.GetNE())/np.log(2.)/dim))
   for x in range(ref_levels):
      mesh.UniformRefinement();
   mesh.ReorientTetMesh();
   pmesh = mfem.ParMesh(MPI.COMM_WORLD, mesh)
   del mesh

   par_ref_levels = 2
   for l in range(par_ref_levels):
       pmesh.UniformRefinement();

   if order > 0:
       fec = mfem.H1_FECollection(order, dim)
   elif mesh.GetNodes():
       fec = mesh.GetNodes().OwnFEC()
       print( "Using isoparametric FEs: " + str(fec.Name()));
   else:
       order = 1
       fec = mfem.H1_FECollection(order, dim)

   fespace =mfem.ParFiniteElementSpace(pmesh, fec)
   fe_size = fespace.GlobalTrueVSize()

   if (myid == 0):
      print('Number of finite element unknowns: '+  str(fe_size))

   ess_tdof_list = mfem.intArray()
   if pmesh.bdr_attributes.Size()>0:
       ess_bdr = mfem.intArray(pmesh.bdr_attributes.Max())
       ess_bdr.Assign(1)
       fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list)

   #   the basis functions in the finite element fespace.
   b = mfem.ParLinearForm(fespace)
   one = mfem.ConstantCoefficient(1.0)
   b.AddDomainIntegrator(mfem.DomainLFIntegrator(one))
   b.Assemble();

   x = mfem.ParGridFunction(fespace);
   x.Assign(0.0)

   a = mfem.ParBilinearForm(fespace);
   a.AddDomainIntegrator(mfem.DiffusionIntegrator(one))

   if static_cond: a.EnableStaticCondensation()
   a.Assemble();

   A = mfem.HypreParMatrix()
   B = mfem.Vector()
   X = mfem.Vector()
   a.FormLinearSystem(ess_tdof_list, x, b, A, X, B)

   if (myid == 0):
      print("Size of linear system: " + str(x.Size()))
      print("Size of linear system: " + str(A.GetGlobalNumRows()))

   if use_strumpack:
       import mfem.par.strumpack as strmpk
       Arow = strmpk.STRUMPACKRowLocMatrix(A)
       args = ["--sp_hss_min_sep_size", "128", "--sp_enable_hss"]
       strumpack = strmpk.STRUMPACKSolver(args, MPI.COMM_WORLD)
       strumpack.SetPrintFactorStatistics(True)
       strumpack.SetPrintSolveStatistics(False)
       strumpack.SetKrylovSolver(strmpk.KrylovSolver_DIRECT);
       strumpack.SetReorderingStrategy(strmpk.ReorderingStrategy_METIS)
       strumpack.SetMC64Job(strmpk.MC64Job_NONE)
       # strumpack.SetSymmetricPattern(True)
       strumpack.SetOperator(Arow)
       strumpack.SetFromCommandLine()
       strumpack.Mult(B, X);

   else:
       amg = mfem.HypreBoomerAMG(A)
       cg = mfem.CGSolver(MPI.COMM_WORLD)
       cg.SetRelTol(1e-12)
       cg.SetMaxIter(200)
       cg.SetPrintLevel(1)
       cg.SetPreconditioner(amg)
       cg.SetOperator(A)
       cg.Mult(B, X);


   a.RecoverFEMSolution(X, b, x)

   smyid = '{:0>6d}'.format(myid)
   mesh_name  =  "mesh."+smyid
   sol_name   =  "sol."+smyid

   pmesh.Print(mesh_name, 8)
   x.Save(sol_name, 8)
Exemple #9
0
def ex19_main(args):
    ser_ref_levels = args.refine_serial
    par_ref_levels = args.refine_parallel
    order = args.order
    visualization = args.visualization
    mu = args.shear_modulus
    newton_rel_tol = args.relative_tolerance
    newton_abs_tol = args.absolute_tolerance
    newton_iter = args.newton_iterations

    if myid == 0: parser.print_options(args)

    meshfile = expanduser(join(path, 'data', args.mesh))
    mesh = mfem.Mesh(meshfile, 1, 1)
    dim = mesh.Dimension()

    for lev in range(ser_ref_levels):
        mesh.UniformRefinement()

    pmesh = mfem.ParMesh(MPI.COMM_WORLD, mesh)
    del mesh
    for lev in range(par_ref_levels):
        pmesh.UniformRefinement()

    #  4. Define the shear modulus for the incompressible Neo-Hookean material
    c_mu = mfem.ConstantCoefficient(mu)

    #  5. Define the finite element spaces for displacement and pressure
    #     (Taylor-Hood elements). By default, the displacement (u/x) is a second
    #     order vector field, while the pressure (p) is a linear scalar function.
    quad_coll = mfem.H1_FECollection(order, dim)
    lin_coll = mfem.H1_FECollection(order - 1, dim)

    R_space = mfem.ParFiniteElementSpace(pmesh, quad_coll, dim,
                                         mfem.Ordering.byVDIM)
    W_space = mfem.ParFiniteElementSpace(pmesh, lin_coll)

    spaces = [R_space, W_space]
    glob_R_size = R_space.GlobalTrueVSize()
    glob_W_size = W_space.GlobalTrueVSize()

    #   6. Define the Dirichlet conditions (set to boundary attribute 1 and 2)
    ess_bdr_u = mfem.intArray(R_space.GetMesh().bdr_attributes.Max())
    ess_bdr_p = mfem.intArray(W_space.GetMesh().bdr_attributes.Max())
    ess_bdr_u.Assign(0)
    ess_bdr_u[0] = 1
    ess_bdr_u[1] = 1
    ess_bdr_p.Assign(0)
    ess_bdr = [ess_bdr_u, ess_bdr_p]

    if myid == 0:
        print("***********************************************************")
        print("dim(u) = " + str(glob_R_size))
        print("dim(p) = " + str(glob_W_size))
        print("dim(u+p) = " + str(glob_R_size + glob_W_size))
        print("***********************************************************")

    block_offsets = intArray([0, R_space.TrueVSize(), W_space.TrueVSize()])
    block_offsets.PartialSum()
    xp = mfem.BlockVector(block_offsets)

    #  9. Define grid functions for the current configuration, reference
    #     configuration, final deformation, and pressure
    x_gf = mfem.ParGridFunction(R_space)
    x_ref = mfem.ParGridFunction(R_space)
    x_def = mfem.ParGridFunction(R_space)
    p_gf = mfem.ParGridFunction(W_space)

    #x_gf.MakeRef(R_space, xp.GetBlock(0), 0)
    #p_gf.MakeRef(W_space, xp.GetBlock(1), 0)

    deform = InitialDeformation(dim)
    refconfig = ReferenceConfiguration(dim)

    x_gf.ProjectCoefficient(deform)
    x_ref.ProjectCoefficient(refconfig)
    p_gf.Assign(0.0)

    #  12. Set up the block solution vectors
    x_gf.GetTrueDofs(xp.GetBlock(0))
    p_gf.GetTrueDofs(xp.GetBlock(1))

    #  13. Initialize the incompressible neo-Hookean operator
    oper = RubberOperator(spaces, ess_bdr, block_offsets, newton_rel_tol,
                          newton_abs_tol, newton_iter, mu)
    #  14. Solve the Newton system
    oper.Solve(xp)

    #  15. Distribute the shared degrees of freedom
    x_gf.Distribute(xp.GetBlock(0))
    p_gf.Distribute(xp.GetBlock(1))

    #  16. Compute the final deformation
    mfem.subtract_vector(x_gf, x_ref, x_def)

    #  17. Visualize the results if requested
    if (visualization):
        vis_u = mfem.socketstream("localhost", 19916)
        visualize(vis_u, pmesh, x_gf, x_def, "Deformation", True)
        MPI.COMM_WORLD.Barrier()
        vis_p = mfem.socketstream("localhost", 19916)
        visualize(vis_p, pmesh, x_gf, p_gf, "Deformation", True)

    #  14. Save the displaced mesh, the final deformation, and the pressure
    nodes = x_gf
    owns_nodes = 0
    nodes, owns_nodes = pmesh.SwapNodes(nodes, owns_nodes)

    smyid = '.' + '{:0>6d}'.format(myid)
    pmesh.PrintToFile('deformed.mesh' + smyid, 8)
    p_gf.SaveToFile('pressure.sol' + smyid, 8)
    x_def.SaveToFile("deformation.sol" + smyid, 8)
Exemple #10
0
def run_test():
    #meshfile = expanduser(join(mfem_path, 'data', 'semi_circle.mesh'))
    meshfile = "../data/amr-quad.mesh"
    mesh = mfem.Mesh(meshfile, 1, 1)
    dim = mesh.Dimension()
    sdim = mesh.SpaceDimension()
    fec = mfem.H1_FECollection(1, dim)
    fespace = mfem.FiniteElementSpace(mesh, fec, 1)
    print('Number of finite element unknowns: ' + str(fespace.GetTrueVSize()))

    c = mfem.ConstantCoefficient(1.0)
    gf = mfem.GridFunction(fespace)
    gf.ProjectCoefficient(c)

    odata = gf.GetDataArray().copy()

    gf.Save("out_test_gz.gf")
    gf2 = mfem.GridFunction(mesh, "out_test_gz.gf")
    odata2 = gf2.GetDataArray().copy()
    check(odata, odata2, "text file does not agree with original")

    gf.Save("out_test_gz.gz")
    gf2.Assign(0.0)
    gf2 = mfem.GridFunction(mesh, "out_test_gz.gz")
    odata2 = gf2.GetDataArray().copy()
    check(odata, odata2, ".gz file does not agree with original")

    gf.Print("out_test_gz.dat")
    gf2.Assign(0.0)
    gf2.Load("out_test_gz.dat", gf.Size())
    odata2 = gf2.GetDataArray().copy()
    check(odata, odata2, ".dat file does not agree with original")

    gf.Print("out_test_gz.dat.gz")
    gf2.Assign(0.0)
    gf2.Load("out_test_gz.dat.gz", gf.Size())
    odata2 = gf2.GetDataArray().copy()
    check(odata, odata2, ".dat file does not agree with original (gz)")

    import gzip
    import io
    gf.Print("out_test_gz.dat2.gz")
    with gzip.open("out_test_gz.dat2.gz", 'rt') as f:
        sio = io.StringIO(f.read())
    gf3 = mfem.GridFunction(fespace)
    gf3.Load(sio, gf.Size())
    odata3 = gf3.GetDataArray().copy()
    check(odata, odata3, ".dat file does not agree with original(gz-io)")

    c = mfem.ConstantCoefficient(2.0)
    gf.ProjectCoefficient(c)
    odata = gf.GetDataArray().copy()

    o = io.StringIO()
    gf.Print(o)
    gf2.Load(o, gf.Size())
    odata2 = gf2.GetDataArray().copy()
    check(odata, odata2, "StringIO does not agree with original")

    print("GridFunction .gf, .gz .dat and StringIO agree with original")

    mesh2 = mfem.Mesh()
    mesh.Print("out_test_gz.mesh")
    mesh2.Load("out_test_gz.mesh")
    check_mesh(mesh, mesh2, ".mesh does not agree with original")

    mesh2 = mfem.Mesh()
    mesh.Print("out_test_gz.mesh.gz")
    mesh2.Load("out_test_gz.mesh.gz")

    check_mesh(mesh, mesh2, ".mesh.gz does not agree with original")

    mesh3 = mfem.Mesh()
    mesh.PrintGZ("out_test_gz3.mesh")
    mesh3.Load("out_test_gz3.mesh")
    check_mesh(mesh, mesh3,
               ".mesh (w/o .gz exntension) does not agree with original")

    o = io.StringIO()
    mesh2 = mfem.Mesh()
    mesh.Print(o)
    mesh2.Load(o)
    check_mesh(mesh, mesh2, ".mesh.gz does not agree with original")

    print("Mesh .mesh, .mesh.gz and StringIO agree with original")

    print("PASSED")
Exemple #11
0
def run(order = 1, static_cond = False,
        meshfile = def_meshfile, visualization = False):

   mesh = mfem.Mesh(meshfile, 1,1)
   dim = mesh.Dimension()

   ref_levels = int(np.floor(np.log(10000./mesh.GetNE())/np.log(2.)/dim))
   for x in range(ref_levels):
      mesh.UniformRefinement();
   mesh.ReorientTetMesh();
   pmesh = mfem.ParMesh(MPI.COMM_WORLD, mesh)
   del mesh

   par_ref_levels = 2
   for l in range(par_ref_levels):
       pmesh.UniformRefinement();

   if order > 0:
       fec = mfem.H1_FECollection(order, dim)
   elif mesh.GetNodes():
       fec = mesh.GetNodes().OwnFEC()
       prinr( "Using isoparametric FEs: " + str(fec.Name()));
   else:
       order = 1
       fec = mfem.H1_FECollection(order, dim)

   fespace =mfem.ParFiniteElementSpace(pmesh, fec)
   fe_size = fespace.GlobalTrueVSize()

   if (myid == 0):
      print('Number of finite element unknowns: '+  str(fe_size))

   ess_tdof_list = mfem.intArray()
   if pmesh.bdr_attributes.Size()>0:
       ess_bdr = mfem.intArray(pmesh.bdr_attributes.Max())
       ess_bdr.Assign(1)
       fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list)

   #   the basis functions in the finite element fespace.
   b = mfem.ParLinearForm(fespace)
   one = mfem.ConstantCoefficient(1.0)
   b.AddDomainIntegrator(mfem.DomainLFIntegrator(one))
   b.Assemble();

   x = mfem.ParGridFunction(fespace);
   x.Assign(0.0)

   a = mfem.ParBilinearForm(fespace);
   a.AddDomainIntegrator(mfem.DiffusionIntegrator(one))

   if static_cond: a.EnableStaticCondensation()
   a.Assemble();

   A = mfem.HypreParMatrix()
   B = mfem.Vector()
   X = mfem.Vector()
   a.FormLinearSystem(ess_tdof_list, x, b, A, X, B)

   if (myid == 0):
      print("Size of linear system: " + str(x.Size()))
      print("Size of linear system: " + str(A.GetGlobalNumRows()))

   amg = mfem.HypreBoomerAMG(A)
   pcg = mfem.HyprePCG(A)
   pcg.SetTol(1e-12)
   pcg.SetMaxIter(200)
   pcg.SetPrintLevel(2)
   pcg.SetPreconditioner(amg)
   pcg.Mult(B, X);


   a.RecoverFEMSolution(X, b, x)

   smyid = '{:0>6d}'.format(myid)
   mesh_name  =  "mesh."+smyid
   sol_name   =  "sol."+smyid

   pmesh.PrintToFile(mesh_name, 8)
   x.SaveToFile(sol_name, 8)
Exemple #12
0
def run_test():
    #meshfile = expanduser(join(mfem_path, 'data', 'semi_circle.mesh'))
    mesh = mfem.Mesh(3, 3, 3, "TETRAHEDRON")
    mesh.ReorientTetMesh()

    order = 1

    dim = mesh.Dimension()
    sdim = mesh.SpaceDimension()
    fec1 = mfem.H1_FECollection(order, dim)
    fespace1 = mfem.FiniteElementSpace(mesh, fec1, 1)

    fec2 = mfem.ND_FECollection(order, dim)
    fespace2 = mfem.FiniteElementSpace(mesh, fec2, 1)

    print("Element order :", order)

    print('Number of H1 finite element unknowns: ' +
          str(fespace1.GetTrueVSize()))
    print('Number of ND finite element unknowns: ' +
          str(fespace2.GetTrueVSize()))

    print("Checking scalar")

    gf = mfem.GridFunction(fespace1)
    c1 = mfem.NumbaFunction(s_func, sdim).GenerateCoefficient()
    c2 = s_coeff()

    gf.Assign(0.0)
    start = time.time()
    gf.ProjectCoefficient(c1)
    end = time.time()
    data1 = gf.GetDataArray().copy()
    print("Numba time (scalar)", end - start)

    gf.Assign(0.0)
    start = time.time()
    gf.ProjectCoefficient(c2)
    end = time.time()
    data2 = gf.GetDataArray().copy()
    print("Python time (scalar)", end - start)

    check(data1, data2, "scalar coefficient does not agree with original")

    print("Checking vector")
    gf = mfem.GridFunction(fespace2)
    c3 = mfem.VectorNumbaFunction(v_func, sdim, dim).GenerateCoefficient()
    c4 = v_coeff(dim)

    gf.Assign(0.0)
    start = time.time()
    gf.ProjectCoefficient(c3)
    end = time.time()
    data1 = gf.GetDataArray().copy()
    print("Numba time (vector)", end - start)

    gf.Assign(0.0)
    start = time.time()
    gf.ProjectCoefficient(c4)
    end = time.time()
    data2 = gf.GetDataArray().copy()
    print("Python time (vector)", end - start)

    check(data1, data2, "vector coefficient does not agree with original")

    print("Checking matrix")
    a1 = mfem.BilinearForm(fespace2)
    a2 = mfem.BilinearForm(fespace2)
    c4 = mfem.MatrixNumbaFunction(m_func, sdim, dim).GenerateCoefficient()
    c5 = m_coeff(dim)

    a1.AddDomainIntegrator(mfem.VectorFEMassIntegrator(c4))
    a2.AddDomainIntegrator(mfem.VectorFEMassIntegrator(c5))

    start = time.time()
    a1.Assemble()
    end = time.time()
    a1.Finalize()
    M1 = a1.SpMat()

    print("Numba time (matrix)", end - start)

    start = time.time()
    a2.Assemble()
    end = time.time()
    a2.Finalize()
    M2 = a2.SpMat()
    print("Python time (matrix)", end - start)

    #from mfem.commmon.sparse_utils import sparsemat_to_scipycsr
    #csr1 = sparsemat_to_scipycsr(M1, float)
    #csr2 = sparsemat_to_scipycsr(M2, float)

    check(M1.GetDataArray(), M2.GetDataArray(),
          "matrix coefficient does not agree with original")
    check(M1.GetIArray(), M2.GetIArray(),
          "matrix coefficient does not agree with original")
    check(M1.GetJArray(), M2.GetJArray(),
          "matrix coefficient does not agree with original")

    print("PASSED")
Exemple #13
0
    def initialize(self, inMeshObj=None, inMeshFile=None):
        # 2. Problem initialization
        self.parser = ArgParser(description='Based on MFEM Ex16p')
        self.parser.add_argument('-m',
                                 '--mesh',
                                 default='beam-tet.mesh',
                                 action='store',
                                 type=str,
                                 help='Mesh file to use.')
        self.parser.add_argument('-rs',
                                 '--refine-serial',
                                 action='store',
                                 default=1,
                                 type=int,
                                 help="Number of times to refine the mesh \
                    uniformly in serial")
        self.parser.add_argument('-rp',
                                 '--refine-parallel',
                                 action='store',
                                 default=0,
                                 type=int,
                                 help="Number of times to refine the mesh \
            uniformly in parallel")
        self.parser.add_argument('-o',
                                 '--order',
                                 action='store',
                                 default=1,
                                 type=int,
                                 help="Finite element order (polynomial \
                    degree)")
        self.parser.add_argument(
            '-s',
            '--ode-solver',
            action='store',
            default=3,
            type=int,
            help='\n'.join([
                "ODE solver: 1 - Backward Euler, 2 - SDIRK2, \
              3 - SDIRK3", "\t\t 11 - Forward Euler, \
              12 - RK2, 13 - RK3 SSP, 14 - RK4."
            ]))
        self.parser.add_argument('-t',
                                 '--t-final',
                                 action='store',
                                 default=20.,
                                 type=float,
                                 help="Final time; start time is 0.")
        self.parser.add_argument("-dt",
                                 "--time-step",
                                 action='store',
                                 default=5e-3,
                                 type=float,
                                 help="Time step.")
        self.parser.add_argument("-v",
                                 "--viscosity",
                                 action='store',
                                 default=0.00,
                                 type=float,
                                 help="Viscosity coefficient.")
        self.parser.add_argument('-L',
                                 '--lmbda',
                                 action='store',
                                 default=1.e0,
                                 type=float,
                                 help='Lambda of Hooks law')
        self.parser.add_argument('-mu',
                                 '--shear-modulus',
                                 action='store',
                                 default=1.e0,
                                 type=float,
                                 help='Shear modulus for Hooks law')
        self.parser.add_argument('-rho',
                                 '--density',
                                 action='store',
                                 default=1.0,
                                 type=float,
                                 help='mass density')
        self.parser.add_argument('-vis',
                                 '--visualization',
                                 action='store_true',
                                 help='Enable GLVis visualization')
        self.parser.add_argument('-vs',
                                 '--visualization-steps',
                                 action='store',
                                 default=25,
                                 type=int,
                                 help="Visualize every n-th timestep.")
        args = self.parser.parse_args()
        self.ser_ref_levels = args.refine_serial
        self.par_ref_levels = args.refine_parallel
        self.order = args.order
        self.dt = args.time_step
        self.visc = args.viscosity
        self.t_final = args.t_final
        self.lmbda = args.lmbda
        self.mu = args.shear_modulus
        self.rho = args.density
        self.visualization = args.visualization
        self.ti = 1
        self.vis_steps = args.visualization_steps
        self.ode_solver_type = args.ode_solver
        self.t = 0.0
        self.last_step = False
        if self.myId == 0: self.parser.print_options(args)

        # 3. Reading mesh
        if inMeshObj is None:
            self.meshFile = inMeshFile
            if self.meshFile is None:
                self.meshFile = args.mesh
            self.mesh = mfem.Mesh(self.meshFile, 1, 1)
        else:
            self.mesh = inMeshObj
        self.dim = self.mesh.Dimension()
        print("Mesh dimension: %d" % self.dim)
        print("Number of vertices in the mesh: %d " % self.mesh.GetNV())
        print("Number of elements in the mesh: %d " % self.mesh.GetNE())

        # 4. Define the ODE solver used for time integration.
        #    Several implicit singly diagonal implicit
        #    Runge-Kutta (SDIRK) methods, as well as
        #    explicit Runge-Kutta methods are available.
        if self.ode_solver_type == 1:
            self.ode_solver = BackwardEulerSolver()
        elif self.ode_solver_type == 2:
            self.ode_solver = mfem.SDIRK23Solver(2)
        elif self.ode_solver_type == 3:
            self.ode_solver = mfem.SDIRK33Solver()
        elif self.ode_solver_type == 11:
            self.ode_solver = ForwardEulerSolver()
        elif self.ode_solver_type == 12:
            self.ode_solver = mfem.RK2Solver(0.5)
        elif self.ode_solver_type == 13:
            self.ode_solver = mfem.RK3SSPSolver()
        elif self.ode_solver_type == 14:
            self.ode_solver = mfem.RK4Solver()
        elif self.ode_solver_type == 22:
            self.ode_solver = mfem.ImplicitMidpointSolver()
        elif self.ode_solver_type == 23:
            self.ode_solver = mfem.SDIRK23Solver()
        elif self.ode_solver_type == 24:
            self.ode_solver = mfem.SDIRK34Solver()
        else:
            print("Unknown ODE solver type: " + str(self.ode_solver_type))
            exit

        # 5. Refine the mesh in serial to increase the
        #    resolution. In this example we do
        #    'ser_ref_levels' of uniform refinement, where
        #    'ser_ref_levels' is a command-line parameter.
        for lev in range(self.ser_ref_levels):
            self.mesh.UniformRefinement()

        # 6. Define a parallel mesh by a partitioning of
        #    the serial mesh. Refine this mesh further
        #    in parallel to increase the resolution. Once the
        #    parallel mesh is defined, the serial mesh can
        #    be deleted.
        self.pmesh = mfem.ParMesh(MPI.COMM_WORLD, self.mesh)
        for lev in range(self.par_ref_levels):
            self.pmesh.UniformRefinement()

        # 7. Define the vector finite element space
        #    representing the current and the
        #    initial temperature, u_ref.
        self.fe_coll = mfem.H1_FECollection(self.order, self.dim)
        self.fespace = mfem.ParFiniteElementSpace(self.pmesh, self.fe_coll,
                                                  self.dim)
        self.fe_size = self.fespace.GlobalTrueVSize()
        if self.myId == 0:
            print("FE Number of unknowns: " + str(self.fe_size))
        true_size = self.fespace.TrueVSize()
        self.true_offset = mfem.intArray(3)
        self.true_offset[0] = 0
        self.true_offset[1] = true_size
        self.true_offset[2] = 2 * true_size
        self.vx = mfem.BlockVector(self.true_offset)
        self.v_gf = mfem.ParGridFunction(self.fespace)
        self.v_gfbnd = mfem.ParGridFunction(self.fespace)
        self.x_gf = mfem.ParGridFunction(self.fespace)
        self.x_gfbnd = mfem.ParGridFunction(self.fespace)
        self.x_ref = mfem.ParGridFunction(self.fespace)
        self.pmesh.GetNodes(self.x_ref)

        # 8. Set the initial conditions for u.
        #self.velo = InitialVelocity(self.dim)
        self.velo = velBCs(self.dim)
        #self.deform =  InitialDeformation(self.dim)
        self.deform = defBCs(self.dim)
        self.v_gf.ProjectCoefficient(self.velo)
        self.v_gfbnd.ProjectCoefficient(self.velo)
        self.x_gf.ProjectCoefficient(self.deform)
        self.x_gfbnd.ProjectCoefficient(self.deform)
        #self.v_gf.GetTrueDofs(self.vx.GetBlock(0));
        #self.x_gf.GetTrueDofs(self.vx.GetBlock(1));

        # setup boundary-conditions
        self.xess_bdr = mfem.intArray(
            self.fespace.GetMesh().bdr_attributes.Max())
        self.xess_bdr.Assign(0)
        self.xess_bdr[0] = 1
        self.xess_bdr[1] = 1
        self.xess_tdof_list = intArray()
        self.fespace.GetEssentialTrueDofs(self.xess_bdr, self.xess_tdof_list)
        #print('True x essential BCs are')
        #self.xess_tdof_list.Print()

        self.vess_bdr = mfem.intArray(
            self.fespace.GetMesh().bdr_attributes.Max())
        self.vess_bdr.Assign(0)
        self.vess_bdr[0] = 1
        self.vess_bdr[1] = 1
        self.vess_tdof_list = intArray()
        self.fespace.GetEssentialTrueDofs(self.vess_bdr, self.vess_tdof_list)
        #print('True v essential BCs are')
        #self.vess_tdof_list.Print()

        # 9. Initialize the stiffness operator
        self.oper = StiffnessOperator(self.fespace, self.lmbda, self.mu,
                                      self.rho, self.visc, self.vess_tdof_list,
                                      self.vess_bdr, self.xess_tdof_list,
                                      self.xess_bdr, self.v_gfbnd,
                                      self.x_gfbnd, self.deform, self.velo,
                                      self.vx)

        # 10. Setting up file output
        self.smyid = '{:0>2d}'.format(self.myId)

        # initializing ode solver
        self.ode_solver.Init(self.oper)
Exemple #14
0
def run_test():
    print("Test complex_operator module")
    Nvert = 6
    Nelem = 8
    Nbelem = 2

    mesh = mfem.Mesh(2, Nvert, Nelem, 2, 3)
    tri_v = [[1., 0., 0.], [0., 1., 0.], [-1., 0., 0.], [0., -1., 0.],
             [0., 0., 1.], [0., 0., -1.]]
    tri_e = [[0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4], [1, 0, 5], [2, 1, 5],
             [3, 2, 5], [0, 3, 5]]
    tri_l = [[1, 4], [1, 2]]

    for j in range(Nvert):
        mesh.AddVertex(tri_v[j])
    for j in range(Nelem):
        mesh.AddTriangle(tri_e[j], 1)
    for j in range(Nbelem):
        mesh.AddBdrSegment(tri_l[j], 1)

    mesh.FinalizeTriMesh(1, 1, True)
    dim = mesh.Dimension()
    order = 1
    fec = mfem.H1_FECollection(order, dim)

    if use_parallel:
        mesh = mfem.ParMesh(MPI.COMM_WORLD, mesh)
        fes = mfem.ParFiniteElementSpace(mesh, fec)
        a1 = mfem.ParBilinearForm(fes)
        a2 = mfem.ParBilinearForm(fes)
    else:
        fes = mfem.FiniteElementSpace(mesh, fec)
        a1 = mfem.BilinearForm(fes)
        a2 = mfem.BilinearForm(fes)
    one = mfem.ConstantCoefficient(1.0)
    a1.AddDomainIntegrator(mfem.DiffusionIntegrator(one))
    a1.Assemble()
    a1.Finalize()

    a2.AddDomainIntegrator(mfem.DiffusionIntegrator(one))
    a2.Assemble()
    a2.Finalize()

    if use_parallel:
        M1 = a1.ParallelAssemble()
        M2 = a2.ParallelAssemble()
        M1.Print('M1')
        width = fes.GetTrueVSize()
        #X = mfem.HypreParVector(fes)
        #Y = mfem.HypreParVector(fes)
        #X.SetSize(fes.TrueVSize())
        #Y.SetSize(fes.TrueVSize())
        #from mfem.common.parcsr_extra import ToScipyCoo
        #MM1 = ToScipyCoo(M1)
        #print(MM1.toarray())
        #print(MM1.dot(np.ones(6)))
    else:
        M1 = a1.SpMat()
        M2 = a2.SpMat()
        M1.Print('M1')
        width = fes.GetVSize()

        #X = mfem.Vector()
        #Y = mfem.Vector()
        #X.SetSize(M1.Width())
        #Y.SetSize(M1.Height())
        #from mfem.common.sparse_utils import sparsemat_to_scipycsr
        #MM1 = sparsemat_to_scipycsr(M1, np.float)
        #print(MM1.toarray())
        #print(MM1.dot(np.ones(6)))
    #X.Assign(0.0)
    #X[0] = 1.0
    #M1.Mult(X, Y)
    #print(Y.GetDataArray())

    Mc = mfem.ComplexOperator(M1, M2, hermitan=True)
    offsets = mfem.intArray([0, width, width])
    offsets.PartialSum()

    x = mfem.BlockVector(offsets)
    y = mfem.BlockVector(offsets)

    x.GetBlock(0).Assign(0)
    if myid == 0:
        x.GetBlock(0)[0] = 1.0
    x.GetBlock(1).Assign(0)
    if myid == 0:
        x.GetBlock(1)[0] = 1.0

    Mc.Mult(x, y)
    print("x", x.GetDataArray())
    print("y", y.GetDataArray())

    if myid == 0:
        x.GetBlock(1)[0] = -1.0

    x.Print()
    Mc.Mult(x, y)
    print("x", x.GetDataArray())
    print("y", y.GetDataArray())
def do_integration(expr, solvars, phys, mesh, kind, attrs,
                   order, num):
    from petram.helper.variables import (Variable,
                                         var_g,
                                         NativeCoefficientGenBase,
                                         CoefficientVariable)
    from petram.phys.coefficient import SCoeff

    st = parser.expr(expr)
    code= st.compile('<string>')
    names = code.co_names

    g = {}
    #print solvars.keys()
    for key in phys._global_ns.keys():
       g[key] = phys._global_ns[key]
    for key in solvars.keys():
       g[key] = solvars[key]

    l = var_g.copy()

    ind_vars = ','.join(phys.get_independent_variables())

    if kind == 'Domain':
        size = max(max(mesh.attributes.ToList()), max(attrs))
    else:
        size = max(max(mesh.bdr_attributes.ToList()), max(attrs))
        
    arr = [0]*(size)
    for k in attrs:
        arr[k-1] = 1
    flag = mfem.intArray(arr)

    s = SCoeff(expr, ind_vars, l, g, return_complex=False)

    ## note L2 does not work for boundary....:D
    if kind == 'Domain':
        fec = mfem.L2_FECollection(order, mesh.Dimension())
    else:
        fec = mfem.H1_FECollection(order, mesh.Dimension())

    fes = mfem.FiniteElementSpace(mesh, fec)
    one = mfem.ConstantCoefficient(1)

    gf = mfem.GridFunction(fes)
    gf.Assign(0.0)

    if kind == 'Domain':
        gf.ProjectCoefficient(mfem.RestrictedCoefficient(s, flag))
    else:
        gf.ProjectBdrCoefficient(mfem.RestrictedCoefficient(s, flag), flag)

    b = mfem.LinearForm(fes)
    one = mfem.ConstantCoefficient(1)
    if kind == 'Domain':
        itg = mfem.DomainLFIntegrator(one)
        b.AddDomainIntegrator(itg)
    else:
        itg = mfem.BoundaryLFIntegrator(one)
        b.AddBoundaryIntegrator(itg)

    b.Assemble()

    from petram.engine import SerialEngine
    en = SerialEngine()
    ans = mfem.InnerProduct(en.x2X(gf), en.b2B(b))
    
    if not np.isfinite(ans):
        print("not finite", ans, arr)
        print(size, mesh.bdr_attributes.ToList())
        from mfem.common.chypre import LF2PyVec, PyVec2PyMat, Array2PyVec, IdentityPyMat
        #print(list(gf.GetDataArray()))
        print(len(gf.GetDataArray()), np.sum(gf.GetDataArray()))
        print(np.sum(list(b.GetDataArray())))
    return ans