Example #1
0
def prepare_ho_node(mesh):
    import mfem.ser as mfem
    nfec = mfem.H1_FECollection(2,
                                mesh.Dimension())
    # mfem.BasisType.ClosedUniform)
    nfes = mfem.FiniteElementSpace(mesh,
                                   nfec,
                                   mesh.SpaceDimension(),
                                   mfem.Ordering.byVDIM)
    mesh.SetNodalFESpace(nfes)
    mesh._linked_obj = (nfes, nfec)
Example #2
0
def run_test():    
    mesh = mfem.Mesh(10, 10, "TRIANGLE")

    fec = mfem.H1_FECollection(1, mesh.Dimension())
    fespace = mfem.FiniteElementSpace(mesh, fec)

    gf = mfem.GridFunction(fespace)
    gf.Assign(1.0)
    odata = gf.GetDataArray().copy()

    visit_dc = mfem.VisItDataCollection("test_gf", mesh)
    visit_dc.RegisterField("gf", gf)
    visit_dc.Save()

    mesh2 = mfem.Mesh("test_gf_000000/mesh.000000")
    check_mesh(mesh, mesh2, ".mesh2 does not agree with original")

    gf2 = mfem.GridFunction(mesh2, "test_gf_000000/gf.000000")
    odata2 = gf2.GetDataArray().copy()
    check(odata, odata2, "odata2 file does not agree with original")

    visit_dc = mfem.VisItDataCollection("test_gf_gz", mesh)
    visit_dc.SetCompression(True)
    visit_dc.RegisterField("gf", gf)
    visit_dc.Save()

    with gzip.open("test_gf_gz_000000/mesh.000000", 'rt') as f:
       sio = io.StringIO(f.read())
    mesh3 = mfem.Mesh(sio)
    check_mesh(mesh, mesh3, ".mesh3 does not agree with original")

    with gzip.open("test_gf_gz_000000/gf.000000", 'rt') as f:
       sio = io.StringIO(f.read())

    # This is where the error is:
    gf3 = mfem.GridFunction(mesh3, sio)
    odata3 = gf3.GetDataArray()
    check(odata, odata3, "gf3 file does not agree with original")

    mesh4 = mfem.Mesh("test_gf_gz_000000/mesh.000000")
    check_mesh(mesh, mesh4, ".mesh4 does not agree with original")

    gf4 = mfem.GridFunction(mesh3, "test_gf_gz_000000/gf.000000")
    odata4 = gf4.GetDataArray()

    check(odata, odata4, "gf3 file does not agree with original")

    print("PASSED")    
Example #3
0
    sys.exit()

# 3. Refine the mesh to increase the resolution.
ref_levels = int(np.floor(np.log(5000./mesh.GetNE())/np.log(2.)/dim))
for x in range(ref_levels):
   mesh.UniformRefinement();

# Since NURBS meshes do not support DG integrators, we convert them to
# regular polynomial mesh of the specified (solution) order.
if (mesh.NURBSext):  mesh.SetCurvature(order)

# 4. Define a DG vector finite element space on the mesh. Here, we use
#    Gauss-Lobatto nodal basis because it gives rise to a sparser matrix
#    compared to the default Gauss-Legendre nodal basis.
fec = mfem.DG_FECollection(order, dim, mfem.BasisType.GaussLobatto)
fespace = mfem.FiniteElementSpace(mesh, fec, dim)
print('Number of finite element unknowns: '+ str(fespace.GetVSize()))
print('Assembling:')

# 5. In this example, the Dirichlet boundary conditions are defined by
#    marking boundary attributes 1 and 2 in the marker Array 'dir_bdr'.
#    These b.c. are imposed weakly, by adding the appropriate boundary
#    integrators over the marked 'dir_bdr' to the bilinear and linear forms.
#    With this DG formulation, there are no essential boundary conditions.
ess_tdof_list = intArray()
dir_bdr = intArray(mesh.bdr_attributes.Max())
dir_bdr.Assign(0)
dir_bdr[0] = 1 # boundary attribute 1 is Dirichlet
dir_bdr[1] = 1 # boundary attribute 2 is Dirichlet

# 6. Define the DG solution vector 'x' as a finite element grid function
Example #4
0
import mfem.ser as mfem
import io

mesh = mfem.Mesh(3)
fec = mfem.H1_FECollection(1)
fes = mfem.FiniteElementSpace(mesh, fec)
x = mfem.GridFunction(fes)
x.Assign(0.0)

o = io.StringIO()
l1 = mesh.WriteToStream(o)
l2 = x.WriteToStream(o)

v = mfem.Vector([1, 2, 3])
l3 = v.WriteToStream(o)

print("result length: ", l1, " ", l2)
print('result: ', o.getvalue())
Example #5
0
order = 1
static_cond = False
meshfile = expanduser(join(path, 'data', 'star.mesh'))
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()

hdiv_coll = mfem.RT_FECollection(order, dim)
l2_coll = mfem.L2_FECollection(order, dim)

R_space = mfem.FiniteElementSpace(mesh, hdiv_coll)
W_space = mfem.FiniteElementSpace(mesh, l2_coll)

dimR = R_space.GetVSize()
dimW = W_space.GetVSize()

print("***********************************************************")
print("dim(R) = " + str(dimR))
print("dim(W) = " + str(dimW))
print("dim(R+W) = " + str(dimR + dimW))
print("***********************************************************")

block_offsets = intArray([0, dimR, dimW])
block_offsets.PartialSum()

k = mfem.ConstantCoefficient(1.0)
Example #6
0
        temp = 1 + 2 * kappa * kappa

        F0 = temp * cos(kappa * x) * sin(kappa * y)
        F1 = temp * cos(kappa * y) * sin(kappa * x)
        if dim == 3:
            return (F0, F1, 0.0)
        else:
            return (F0, F1)


ref_levels = int(np.floor(np.log(25000. / mesh.GetNE()) / np.log(2.) / dim))
for x in range(ref_levels):
    mesh.UniformRefinement()

fec = mfem.RT_FECollection(order - 1, dim)
fespace = mfem.FiniteElementSpace(mesh, fec)

print("Number of finite element unknows : " + str(fespace.GetTrueVSize()))

ess_tdof_list = intArray()
if mesh.bdr_attributes.Size():
    ess_bdr = intArray(mesh.bdr_attributes.Max())
    if set_bc: ess_bdr.Assign(1)
    else: ess_bdr.Assign(0)
    fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list)

b = mfem.LinearForm(fespace)
f = f_exact()
dd = mfem.VectorFEDomainLFIntegrator(f)
b.AddDomainIntegrator(dd)
b.Assemble()
Example #7
0
def run(order=1,
        static_cond=False,
        meshfile=def_meshfile,
        visualization=False):

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

    #   3. Refine the mesh to increase the resolution. In this example we do
    #      'ref_levels' of uniform refinement. We choose 'ref_levels' to be the
    #      largest number that gives a final mesh with no more than 50,000
    #      elements.
    ref_levels = int(np.floor(
        np.log(50000. / mesh.GetNE()) / np.log(2.) / dim))
    for x in range(ref_levels):
        mesh.UniformRefinement()

    #5. Define a finite element space on the mesh. Here we use vector finite
    #   elements, i.e. dim copies of a scalar finite element space. The vector
    #   dimension is specified by the last argument of the FiniteElementSpace
    #   constructor. For NURBS meshes, we use the (degree elevated) NURBS space
    #   associated with the mesh nodes.
    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.FiniteElementSpace(mesh, fec)
    print('Number of finite element unknowns: ' + str(fespace.GetTrueVSize()))
    # 5. Determine the list of true (i.e. conforming) essential boundary dofs.
    #    In this example, the boundary conditions are defined by marking all
    #    the boundary attributes from the mesh as essential (Dirichlet) and
    #    converting them to a list of true dofs.
    ess_tdof_list = mfem.intArray()
    if mesh.bdr_attributes.Size() > 0:
        ess_bdr = mfem.intArray([1] * mesh.bdr_attributes.Max())
        ess_bdr = mfem.intArray(mesh.bdr_attributes.Max())
        ess_bdr.Assign(1)
        fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list)
    #6. Set up the linear form b(.) which corresponds to the right-hand side of
    #   the FEM linear system, which in this case is (1,phi_i) where phi_i are
    #   the basis functions in the finite element fespace.
    b = mfem.LinearForm(fespace)
    one = mfem.ConstantCoefficient(1.0)
    b.AddDomainIntegrator(mfem.DomainLFIntegrator(one))
    b.Assemble()
    #7. Define the solution vector x as a finite element grid function
    #   corresponding to fespace. Initialize x with initial guess of zero,
    #   which satisfies the boundary conditions.
    x = mfem.GridFunction(fespace)
    x.Assign(0.0)
    #8. Set up the bilinear form a(.,.) on the finite element space
    #   corresponding to the Laplacian operator -Delta, by adding the Diffusion
    #   domain integrator.
    a = mfem.BilinearForm(fespace)
    a.AddDomainIntegrator(mfem.DiffusionIntegrator(one))
    #9. Assemble the bilinear form and the corresponding linear system,
    #   applying any necessary transformations such as: eliminating boundary
    #   conditions, applying conforming constraints for non-conforming AMR,
    #   static condensation, etc.
    if static_cond: a.EnableStaticCondensation()
    a.Assemble()

    A = mfem.OperatorPtr()
    B = mfem.Vector()
    X = mfem.Vector()

    a.FormLinearSystem(ess_tdof_list, x, b, A, X, B)
    print("Size of linear system: " + str(A.Height()))

    # 10. Solve
    AA = mfem.OperatorHandle2SparseMatrix(A)
    M = mfem.GSSmoother(AA)
    mfem.PCG(AA, M, B, X, 1, 200, 1e-12, 0.0)

    # 11. Recover the solution as a finite element grid function.
    a.RecoverFEMSolution(X, b, x)
    # 12. Save the refined mesh and the solution. This output can be viewed later
    #     using GLVis: "glvis -m refined.mesh -g sol.gf".
    mesh.Print('refined.mesh', 8)
    x.Save('sol.gf', 8)

    #13. Send the solution by socket to a GLVis server.
    if (visualization):
        sol_sock = mfem.socketstream("localhost", 19916)
        sol_sock.precision(8)
        sol_sock.send_solution(mesh, x)
Example #8
0
dim = mesh.Dimension()
sdim = mesh.SpaceDimension()

# 3. Since a NURBS mesh can currently only be refined uniformly, we need to
#    convert it to a piecewise-polynomial curved mesh. First we refine the
#    NURBS mesh a bit more and then project the curvature to quadratic Nodes.
if (mesh.NURBSext):
    for i in range(2):
        mesh.UniformRefinement()
    mesh.SetCurvature(2)

# 4. 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.FiniteElementSpace(mesh, fec)

# 5. As in Example 1, 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 main loop.
a = mfem.BilinearForm(fespace)
b = mfem.LinearForm(fespace)

one = mfem.ConstantCoefficient(1.0)
zero = mfem.ConstantCoefficient(0.0)

integ = mfem.DiffusionIntegrator(one)
a.AddDomainIntegrator(integ)
b.AddDomainIntegrator(mfem.DomainLFIntegrator(one))

# 6. The solution vector x and the associated finite element grid function
Example #9
0
def ex19_main(args):
    ref_levels = args.refine
    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

    parser.print_options(args)

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

    for lev in range(ref_levels):
        mesh.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.FiniteElementSpace(mesh, quad_coll, dim,
                                      mfem.Ordering.byVDIM)
    W_space = mfem.FiniteElementSpace(mesh, lin_coll)

    spaces = [R_space, W_space]
    R_size = R_space.GetVSize()
    W_size = W_space.GetVSize()

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

    print("***********************************************************")
    print("dim(u) = " + str(R_size))
    print("dim(p) = " + str(W_size))
    print("dim(u+p) = " + str(R_size + W_size))
    print("***********************************************************")

    block_offsets = intArray([0, R_size, W_size])
    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.GridFunction(R_space)
    x_ref = mfem.GridFunction(R_space)
    x_def = mfem.GridFunction(R_space)
    p_gf = mfem.GridFunction(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)

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

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

    #  13. Visualize the results if requested
    if (visualization):
        vis_u = mfem.socketstream("localhost", 19916)
        visualize(vis_u, mesh, x_gf, x_def, "Deformation", True)
        vis_p = mfem.socketstream("localhost", 19916)
        visualize(vis_p, mesh, 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 = mesh.SwapNodes(nodes, owns_nodes)

    mesh.Print('deformed.mesh', 8)
    p_gf.Save('pressure.sol', 8)
    x_def.Save("deformation.sol", 8)
Example #10
0
else:
    print("Unknown ODE solver type: " + str(ode_solver_type))
    exit

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

# 5. Define the discontinuous DG finite element space of the given
#    polynomial order on the refined mesh.

fec = mfem.DG_FECollection(order, dim)
# Finite element space for a scalar (thermodynamic quantity)
fes = mfem.FiniteElementSpace(mesh, fec)
# Finite element space for a mesh-dim vector quantity (momentum)
dfes = mfem.FiniteElementSpace(mesh, fec, dim, mfem.Ordering.byNODES)
# Finite element space for all variables together (total thermodynamic state)
vfes = mfem.FiniteElementSpace(mesh, fec, num_equation, mfem.Ordering.byNODES)

assert fes.GetOrdering() == mfem.Ordering.byNODES, "Ordering must be byNODES"
print("Number of unknowns: " + str(vfes.GetVSize()))

# 6. Define the initial conditions, save the corresponding mesh and grid
#    functions to a file. This can be opened with GLVis with the -gc option.
#    The solution u has components {density, x-momentum, y-momentum, energy}.
#    These are stored contiguously in the BlockVector u_block.

offsets = [k * vfes.GetNDofs() for k in range(num_equation + 1)]
offsets = mfem.intArray(offsets)
Example #11
0
#   3. Refine the mesh to increase the resolution. In this example we do
#      'ref_levels' of uniform refinement. We choose 'ref_levels' to be the
#      largest number that gives a final mesh with no more than 50,000
#      elements.

ref_levels = int(np.floor(np.log(5000. / mesh.GetNE()) / np.log(2.) / dim))
for x in range(ref_levels):
    mesh.UniformRefinement()

#5. Define a finite element space on the mesh. Here we use vector finite
#   elements, i.e. dim copies of a scalar finite element space. The vector
#   dimension is specified by the last argument of the FiniteElementSpace
#   constructor. For NURBS meshes, we use the (degree elevated) NURBS space
#   associated with the mesh nodes.
fec = mfem.H1_FECollection(order, dim)
fespace = mfem.FiniteElementSpace(mesh, fec, dim)

print("Number of finite element unknowns: " + str(fespace.GetTrueVSize()))

# 6. Determine the list of true (i.e. conforming) essential boundary dofs.
#    In this example, the boundary conditions are defined by marking only
#    boundary attribute 1 from the mesh as essential and converting it to a
#    list of true dofs.
ess_tdof_list = intArray()
ess_bdr = intArray([1] + [0] * (mesh.bdr_attributes.Max() - 1))
fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list)
# 7. Set up the linear form b(.) which corresponds to the right-hand side of
#    the FEM linear system. In this case, b_i equals the boundary integral
#    of f*phi_i where f represents a "pull down" force on the Neumann part
#    of the boundary and phi_i are the basis functions in the finite element
#    fespace. The force is defined by the VectorArrayCoefficient object f,
Example #12
0
elif ode_solver_type == 14: ode_solver = mfem.RK4Solver()
elif ode_solver_type == 22: ode_solver = mfem.ImplicitMidpointSolver()
elif ode_solver_type == 23: ode_solver = mfem.SDIRK23Solver()
elif ode_solver_type == 24: ode_solver = mfem.SDIRK34Solver()
else:
    print("Unknown ODE solver type: " + str(ode_solver_type))
    exit
# 4. Refine the mesh to increase the resolution. In this example we do
#    'ref_levels' of uniform refinement, where 'ref_levels' is a
#    command-line parameter.
for lev in range(ref_levels):
    mesh.UniformRefinement()
# 5. Define the vector finite element space representing the current and the
#    initial temperature, u_ref.
fe_coll = mfem.H1_FECollection(order, dim)
fespace = mfem.FiniteElementSpace(mesh, fe_coll)
fe_size = fespace.GetTrueVSize()
print("Number of temperature unknowns: " + str(fe_size))
u_gf = mfem.GridFunction(fespace)

# 6. 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)

# 7. Initialize the conduction operator and the visualization.
oper = ConductionOperator(fespace, alpha, kappa, u)
u_gf.SetFromTrueDofs(u)
Example #13
0
#       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 (mesh.MeshGenerator() & 2 and order > 1))):
    test_order = test_order + 1
if (test_order < trial_order):
    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.FiniteElementSpace(mesh, x0_fec)
xhat_space = mfem.FiniteElementSpace(mesh, xhat_fec)
test_space = mfem.FiniteElementSpace(mesh, test_fec)

# 5. Define the block structure of the problem, by creating the offset
#    variables. Also allocate two BlockVector objects to store the solution
#    and rhs.

x0_var = 0;  xhat_var = 1;  NVAR = 2

s0 = x0_space.GetVSize()
s1 = xhat_space.GetVSize()
s_test = test_space.GetVSize()

offsets = mfem.intArray([0, s0, s0+s1])
offsets_test = mfem.intArray([0, s_test])
Example #14
0
    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]