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")
def write_ho_tet_mesh(filename, reader, ho_thre=1e-20): import mfem.ser as mfem @jit(numba.int64(numba.float64[:], numba.float64[:, :]), cache=False) def find_closest0(ptx, grids): x1 = ptx[0] y1 = ptx[1] z1 = ptx[2] for jj in range(10): d2 = ((x1 - grids[jj, 0])**2 + (y1 - grids[jj, 1])**2 + (z1 - grids[jj, 2])**2) if d2 < ho_thre: return jj assert(False) return -1 @jit(parallel=True, cache=False) def find_closest_tet_ptx(ptx, grids): idx = np.empty(10, dtype=numba.int64) for jj in prange(10): idx[jj] = find_closest0(ptx[jj], grids) return idx mesh = mfem.Mesh(filename) prepare_ho_node(mesh) n = mesh.GetNE() node_gf = mesh.GetNodes() nfes = node_gf.FESpace() nodes = node_gf.GetDataArray().copy() node_gf2 = mfem.GridFunction(mesh._linked_obj[0]) nodes2 = node_gf2.GetDataArray() grid_all = reader.dataset['GRIDS'] i_tetra = reader.dataset["ELEMS_HO"]["TETRA"] for i in range(n): # for i in [0]: vdofs = nfes.GetElementVDofs(i) ptx = nodes[vdofs].reshape(3, -1).transpose() grids = grid_all[i_tetra[i]] new_grids = linearized_grids(grids) idx = find_closest_tet_ptx(ptx, new_grids) tmp = grids[idx] data = np.hstack((tmp[:, 0], tmp[:, 1], tmp[:, 2])) nodes2[vdofs] = data if (i % 50000) == 0: print("processing elements "+str(i) + "/" + str(n)) node_gf.Assign(nodes2) filename2 = filename[:-5]+"_order2.mesh" mesh.Save(filename2)
def __init__(self, solfiles, refine=0): def fname2idx(t): i = int(os.path.basename(t).split('.')[0].split('_')[-1]) return i solfiles = solfiles.set object.__init__(self) self.set = [] import mfem.ser as mfem for meshes, solf, in solfiles: idx = [fname2idx(x) for x in meshes] meshes = { i: mfem.Mesh(str(x), 1, refine) for i, x in zip(idx, meshes) } meshes = MeshDict(meshes) # to make dict weakref-able ### what is this refine = 0 !? for i in idx: meshes[i].ReorientTetMesh() meshes[i]._emesh_idx = i s = {} for key in six.iterkeys(solf): fr, fi = solf[key] i = fname2idx(fr) m = meshes[i] solr = (mfem.GridFunction(m, str(fr)) if fr is not None else None) soli = (mfem.GridFunction(m, str(fi)) if fi is not None else None) if solr is not None: solr._emesh_idx = i if soli is not None: soli._emesh_idx = i s[key] = (solr, soli) self.set.append((meshes, s))
def load_sol( solfiles, fesvar, refine=0, ): ''' read sol files in directory path. it reads only a file for the certain FES variable given by fesvar ''' from petram.sol.solsets import find_solfiles, MeshDict # solfiles = find_solfiles(path) def fname2idx(t): i = int(os.path.basename(t).split('.')[0].split('_')[-1]) return i solfiles = solfiles.set solset = [] for meshes, solf, in solfiles: s = {} for key in six.iterkeys(solf): name = key.split('_')[0] if name != fesvar: continue idx_to_read = int(key.split('_')[1]) break for meshes, solf, in solfiles: idx = [fname2idx(x) for x in meshes] meshes = { i: mfem.Mesh(str(x), 1, refine) for i, x in zip(idx, meshes) if i == idx_to_read } meshes = MeshDict(meshes) # to make dict weakref-able ### what is this refine = 0 !? for i in meshes.keys(): meshes[i].ReorientTetMesh() meshes[i]._emesh_idx = i s = {} for key in six.iterkeys(solf): name = key.split('_')[0] if name != fesvar: continue fr, fi = solf[key] i = fname2idx(fr) m = meshes[i] solr = (mfem.GridFunction(m, str(fr)) if fr is not None else None) soli = (mfem.GridFunction(m, str(fi)) if fi is not None else None) if solr is not None: solr._emesh_idx = i if soli is not None: soli._emesh_idx = i s[name] = (solr, soli) solset.append((meshes, s)) return solset
action = 'store_true', help='Enable GLVis visualization') args = parser.parse_args() ref_levels = args.refine order = args.order alpha = args.alpha; kappa = args.kappa; visualization = args.visualization if (kappa < 0): kappa = (order+1.)*(order+1.) args.kappa = kappa parser.print_options(args) # 2. Read the mesh from the given mesh file. meshfile =expanduser(join(path, 'data', args.mesh)) mesh = mfem.Mesh(meshfile, 1,1) dim = mesh.Dimension() if (mesh.attributes.Max() < 2 or mesh.bdr_attributes.Max() < 2): print("\n".join(["Input mesh should have at least two materials and ", "two boundary attributes! (See schematic in ex17.cpp)\n"])) 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)
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())
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)
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)
''' import mfem.ser as mfem import numpy as np class sigma(mfem.MatrixPyCoefficient): def __init__(self, dim): mfem.MatrixPyCoefficient.__init__(self, dim) def EvalValue(self, x): return np.array([[0.1, 0.], [0., 10.]]) # create sample mesh for square shape mesh = mfem.Mesh(10, 10, "TRIANGLE") # create finite element function space fec = mfem.H1_FECollection(1, mesh.Dimension()) # H1 order=1 fespace = mfem.FiniteElementSpace(mesh, fec) # ess_tdof_list = mfem.intArray() ess_bdr = mfem.intArray([1] * mesh.bdr_attributes.Size()) fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list) # constant coefficient one = mfem.ConstantCoefficient(1.0) # define Bilinear and Linear operator a = mfem.BilinearForm(fespace)
import mfem.ser as mfem from petram.mesh.partial_mesh import * from petram.mesh.mesh_utils import get_extended_connectivity mesh = mfem.Mesh('cone_edge.mesh') get_extended_connectivity(mesh) print(mesh.extended_connectivity) from petram.mesh.read_mfemmesh1 import extract_refined_mesh_data1 print("edge", mesh.GetNEdges()) print(extract_refined_mesh_data1(mesh, 3))
from numpy import sin, cos, exp elem_type = 1 ref_levels = 2 amr = 0 order = 2 always_snap = False if elem_type == 1: Nvert = 8 Nelem = 6 else: Nvert = 6 Nelem = 8 mesh = mfem.Mesh(2, Nvert, Nelem, 0, 3) if elem_type == 0: 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]] for j in range(Nvert): mesh.AddVertex(tri_v[j]) for j in range(Nelem): 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]]
def RequestData(self, request, inInfo, outInfo): output = dsa.WrapDataObject(vtkUnstructuredGrid.GetData(outInfo)) import os import json import mfem.ser as mfem _, ext = os.path.splitext(self._filename) cwd = os.path.dirname(self._filename) if ext == ".mfem_root": with open(self._filename) as f: root = json.load(f) cycle = int(root['dsets']['main']['cycle']) mesh_filename = root['dsets']['main']['mesh']['path'] mesh_filename = format(mesh_filename % cycle) mesh_filename = os.path.join(cwd, mesh_filename) else: mesh_filename = self._filename mesh = mfem.Mesh(mesh_filename) dim = mesh.SpaceDimension() nelem = mesh.GetNE() # Points mesh_fes = mesh.GetNodalFESpace() nodes = mesh.GetNodes() if nodes is None: nnode = mesh.GetNV() points = np.array(mesh.GetVertexArray()) else: nnode = mesh.GetNodes().Size() // dim points = np.array(mesh.GetNodes().GetDataArray()) if mesh_fes.GetOrdering() == 0: points = points.reshape((dim, nnode)).T elif mesh_fes.GetOrdering() == 1: points = points.reshape((nnode, dim)) else: raise NotImplementedError if dim == 1: points = np.hstack([points, np.zeros((nnode, 2))]) elif dim == 2: points = np.hstack([points, np.zeros((nnode, 1))]) output.SetPoints(points) # Cells cell_attributes = np.empty((nelem), dtype=int) cell_types = np.empty((nelem), dtype=np.ubyte) cell_offsets = np.empty((nelem), dtype=int) cell_conn = [] offset = 0 if nodes is None: for i in range(nelem): v = mesh.GetElementVertices(i) geom = mesh.GetElementBaseGeometry(i) perm = VTKGeometry_VertexPermutation[geom] if perm: v = [v[i] for i in perm] cell_types[i] = VTKGeometry_Map[geom] cell_offsets[i] = offset offset += len(v) + 1 cell_conn.append(len(v)) cell_conn.extend(v) else: for i in range(nelem): v = mesh_fes.GetElementDofs(i) geom = mesh.GetElementBaseGeometry(i) order = mesh_fes.GetOrder(i) if order == 1: perm = VTKGeometry_VertexPermutation[geom] cell_types[i] = VTKGeometry_Map[geom] elif order == 2: perm = VTKGeometry_QuadraticVertexPermutation[geom] cell_types[i] = VTKGeometry_QuadraticMap[geom] else: # FIXME: this needs more work... # See CreateVTKMesh for reading VTK Lagrange elements and # invert that process to create VTK Lagrange elements. # https://github.com/mfem/mfem/blob/master/mesh/mesh_readers.cpp parray = mfem.intArray() mfem.CreateVTKElementConnectivity(parray, geom, order) perm = parray.ToList() cell_types[i] = VTKGeometry_HighOrderMap[geom] if perm: v = [v[i] for i in perm] cell_offsets[i] = offset offset += len(v) + 1 cell_conn.append(len(v)) cell_conn.extend(v) output.SetCells(cell_types, cell_offsets, cell_conn) # Attributes for i in range(nelem): cell_attributes[i] = mesh.GetAttribute(i) output.CellData.append(cell_attributes, "attribute") # Read fields if ext == ".mfem_root": fields = root['dsets']['main']['fields'] for name, prop in fields.items(): filename = prop['path'] filename = format(filename % cycle) filename = os.path.join(cwd, filename) gf = mfem.GridFunction(mesh, filename) gf_fes = gf.FESpace() gf_vdim = gf.VectorDim() gf_nnode = gf_fes.GetNDofs() // gf_vdim gf_nelem = gf_fes.GetNBE() data = np.array(gf.GetDataArray()) if prop['tags']['assoc'] == 'nodes': assert gf_nnode == nnode, "Mesh and grid function have different number of nodes" if gf_fes.GetOrdering() == 0: data = data.reshape((gf_vdim, gf_nnode)).T elif gf_fes.GetOrdering() == 1: data = data.reshape((gf_nnode, gf_vdim)) else: raise NotImplementedError output.PointData.append(data, name) elif prop['tags']['assoc'] == 'elements': assert gf_nelem == nelem, "Mesh and grid function have different number of elements" if gf_fes.GetOrdering() == 0: data = data.reshape((gf_vdim, gf_nelem)).T elif gf_fes.GetOrdering() == 1: data = data.reshape((gf_nelem, gf_vdim)) else: raise NotImplementedError output.CellData.append(data, name) else: raise NotImplementedError("assoc: '{}'".format( prop['tags']['assoc'])) return 1