Need help converting GMSH to FEniCS

Hi there! I am new to GMSH and FEniCS. My apologies if the below question is a trivial one. But I tried many of the suggestions listed in the discourse site but nothing seems to work. Need help with this.
I am using Dolfin version 2019.2.0 and GMSH 3.0.1.
I created a .geo and .msh file in GMSH and converted it to xdmf using the command
dolfin-convert annulusgeometry.msh annulusgeometry.xdmf

Then in the FEniCS script, I plugged in the following set of commands (from one of the suggested solution in the site):

import meshio
msh = meshio.read(“annulusgeometry.msh”)

meshio.write(“mf.xdmf”, meshio.Mesh(points=msh.points, cells={“triangle”: msh.cells[“triangle”]},
cell_data={“triangle”: {“name_to_read”: msh.cell_data[“triangle”][“gmsh:physical”]}}))
meshio.write(“cf.xdmf”, meshio.Mesh(
points=msh.points, cells={“tetra”: msh.cells[“tetra”]},
cell_data={“tetra”: {“name_to_read”:
msh.cell_data[“tetra”][“gmsh:physical”]}}))

from dolfin import *
mesh = Mesh()
with XDMFFile(“mesh.xdmf”) as infile:
infile.read(mesh)
mvc = MeshValueCollection(“size_t”, mesh, 2)
with XDMFFile(“mf.xdmf”) as infile:
infile.read(mvc, “name_to_read”)
mf = cpp.mesh.MeshFunctionSizet(mesh, mvc)

mvc = MeshValueCollection(“size_t”, mesh, 3)
with XDMFFile(“cf.xdmf”) as infile:
infile.read(mvc, “name_to_read”)
cf = cpp.mesh.MeshFunctionSizet(mesh, mvc)

ds_custom = Measure(“ds”, domain=mesh, subdomain_data=mf)

When executing, I am getting the error No module named ‘h5py’
I installed h5py and executed the program. Then I got a gigantic error message which started with
h5py is running against HDF5 1.10.4 when it was built against 1.12.0, this may cause problems

How to overcome this?

Follow for instance:

i.e.:

pip3 uninstall h5py
pip3 install --no-binary=h5py h5py --user

Hi dokken!

Thanks for your response. I tried the code as suggested, but it’s giving me the following error code:

ERROR: Failed building wheel for h5py
Failed to build h5py
ERROR: Could not build wheels for h5py which use PEP 517 and cannot be installed directly

Have you tried: python - Can't install h5py - Stack Overflow

For more specific help, it would help to know more about how you installed dolfin.

  1. What system are you using
  2. Did you use docker, conda or installed from source?

If you simply need a container for converting a gmsh msh file to xdmf, you can use the docker container: dokken92/pygmsh as it contains meshio and h5py. For more details about that approach see: Mesh generation and conversion with GMSH and PYGMSH | Jørgen S. Dokken

I am using Windows10, 64 bit.
I am using the Dolfin that is already installed in my University server and I access it using SSH terminals.

So I guess your university server is Linux based?
Then I would suggest trying the stack overflow link above.

Yes, it is Linux based. I tried the link and that did the job. Thank you so much.

Now I have a coding problem:

My geometry is a 2-D annulus meshed using triangles. While executing the following code

import meshio
msh = meshio.read(“annulusgeometry.msh”)

meshio.write(“mesh.xdmf”, meshio.Mesh(points=msh.points, cells={“tetra”: msh.cells[“tetra”]}))
meshio.write(“mf.xdmf”, meshio.Mesh(points=msh.points, cells={“triangle”: msh.cells[“triangle”]},
cell_data={“triangle”: {“name_to_read”: msh.cell_data[“triangle”][“gmsh:physical”]}}))
meshio.write(“cf.xdmf”, meshio.Mesh(
points=msh.points, cells={“tetra”: msh.cells[“tetra”]},
cell_data={“tetra”: {“name_to_read”:
msh.cell_data[“tetra”][“gmsh:physical”]}}))

there is an error message:
meshio.write(“mesh.xdmf”, meshio.Mesh(points=msh.points, cells={“tetra”: msh.cells[“tetra”]}))
KeyError: ‘tetra’

How to solve this and what does it mean?

So since you have a 2D mesh, you should not try to save a mesh with tetrahedrons.
You should change the keyword “tetra” to “triangle”, and similarly change “triangle” to “line” in the writing of “mf.xdmf”.

I would strongly encourage you to use the following function for writing a mesh given a cell type:

import numpy
def create_mesh(mesh, cell_type, prune_z=False):
    cells = mesh.get_cells_type(cell_type)
    cell_data = mesh.get_cell_data("gmsh:physical", cell_type)
    out_mesh = meshio.Mesh(points=mesh.points, cells={cell_type: cells}, cell_data={"name_to_read":[cell_data]})
    if prune_z:
        out_mesh.prune_z_0()
    return out_mesh

whose explanation can be found at

The change from “tetra” to “triangles” and “triangles” to “line” solved the problem partially. With this change, the only problem that remains to be solved is that it imports the structure and the mesh from the GMSH but I think it doesn’t import the physical tags for when I apply a traction of 1 unit (Neumann BC) on the inner circle and 0 traction on the outer circle, the execution simply returns the structure without any deformation. But importing the structure from GMSH seems to work fine.

With the other code that you suggested (from your site), I plugged in the following commands:

import meshio
mesh_from_file = meshio.read(“annulusgeometry.msh”)

import numpy
def create_mesh(mesh, cell_type, prune_z=False):
cells = mesh.get_cells_type(cell_type)
cell_data = mesh.get_cell_data(“gmsh:physical”, cell_type)
out_mesh = meshio.Mesh(points=mesh.points, cells={cell_type: cells}, cell_data={“name_to_read”:[cell_data]})
if prune_z:
out_mesh.prune_z_0()
return out_mesh

line_mesh = create_mesh(mesh_from_file, “line”, prune_z=True)
meshio.write(“facet_mesh.xdmf”, line_mesh)

triangle_mesh = create_mesh(mesh_from_file, “triangle”, prune_z=True)
meshio.write(“mesh.xdmf”, triangle_mesh)

ds_custom = Measure(“ds”, domain=mesh, subdomain_data=mf)

This reports the error:
File “annulus2.py”, line 27, in
line_mesh = create_mesh(mesh_from_file, “line”, prune_z=True)
File “annulus2.py”, line 20, in create_mesh
cells = mesh.get_cells_type(cell_type)
AttributeError: ‘Mesh’ object has no attribute ‘get_cells_type’

Sorry to bother you with repeated questions. I am new to FEniCS and GMSH (it has not been even 1 week that I am into this new platform for computations), and there is no one to help me with this. So I am on my own. But your patience and quick responses are much much appreciated.

Which version of meshio are you using?
The function meshio.get_cells_type exists in meshio 4.0 (using pip3 install meshio you should get 4.3.10)

I am using an older version 3.2.7.
Should I do
pip3 uninstall meshio
pip3 install meshio==4.0

I’m getting the same error even after installing meshio 4.0. Here it is:

Successfully installed meshio-4.0.0
avishmj@math-alfred:~ cd examples avishmj@math-alfred:~/examples python3 annulus2.py
Traceback (most recent call last):
File “annulus2.py”, line 27, in
line_mesh = create_mesh(mesh_from_file, “line”, prune_z=True)
File “annulus2.py”, line 20, in create_mesh
cells = mesh.get_cells_type(cell_type)
AttributeError: ‘Mesh’ object has no attribute ‘get_cells_type’

You can install the latest release of meshio using pip3 install --upgrade meshio, although any release after 4.0 should have the get_cells_type method.

In general, you can use the help function in python to view the method resolution order. For instance, it should look something like this:

Help on Mesh in module meshio._mesh object:

class Mesh(builtins.object)
 |  Mesh(points, cells, point_data=None, cell_data=None, field_data=None, point_sets=None, cell_sets=None, gmsh_periodic=None, info=None)
 |
 |  Methods defined here:
 |
 |  __init__(self, points, cells, point_data=None, cell_data=None, field_data=None, point_sets=None, cell_sets=None, gmsh_periodic=None, info=None)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __repr__(self)
 |      Return repr(self).
 |
 |  get_cell_data(self, name: str, cell_type: str)
 |
 |  get_cells_type(self, cell_type: str)
 |
 |  int_data_to_sets(self)
 |      Convert all int data to {point,cell}_sets, where possible.
 |
 |  prune(self)
 |
 |  prune_z_0(self, tol: float = 1e-13)
 |      Remove third (z) component of points if it is 0 everywhere (up to a
 |      tolerance).
 |
 |  remove_lower_dimensional_cells(self)
 |      Remove all cells of topological dimension lower than the max dimension in the
 |      mesh, i.e., in a mesh that contains tetrahedra, remove triangles, lines, etc.
 |
 |  remove_orphaned_nodes(self)
 |      Remove nodes which don't belong to any cell.
 |
 |  sets_to_int_data(self)
 |
 |  write(self, path_or_buf, file_format: Union[str, NoneType] = None, **kwargs)
 |
 |  ----------------------------------------------------------------------

This, however, is not limited to FEniCS and can be used for just about any object in python. :slight_smile:

1 Like

Thanks bhaveshshrimali. I upgraded meshio to 4.3.10. That worked. However, I have another question on the following code:

import numpy
def create_mesh(mesh, cell_type, prune_z=False):
    cells = mesh.get_cells_type(cell_type)
    cell_data = mesh.get_cell_data("gmsh:physical", cell_type)
    out_mesh = meshio.Mesh(points=mesh.points, cells={cell_type: cells}, cell_data={"name_to_read":[cell_data]})
    if prune_z:
        out_mesh.prune_z_0()
    return out_mesh

line_mesh = create_mesh(mesh_from_file, "line", prune_z=True)
meshio.write("facet_mesh.xdmf", line_mesh)
triangle_mesh = create_mesh(mesh_from_file, "triangle", prune_z=True)
meshio.write("mesh.xdmf", triangle_mesh)
ds_custom = Measure("ds", domain=triangle_mesh, subdomain_data=line_mesh)

This code gives me the following error:

Invalid cell < meshio mesh object >

  Number of points: 983
  Number of cells:
    triangle: 1787
  Cell data: name_to_read.
Traceback (most recent call last):
  File "annulus2.py", line 35, in <module>
    ds_custom = Measure("ds", domain=triangle_mesh, subdomain_data=line_mesh)
  File "/usr/lib/python3/dist-packages/ufl/measure.py", line 145, in __init__
    self._domain = None if domain is None else as_domain(domain)
  File "/usr/lib/python3/dist-packages/ufl/domain.py", line 284, in as_domain
    cell = as_cell(domain)
  File "/usr/lib/python3/dist-packages/ufl/cell.py", line 316, in as_cell
    error("Invalid cell %s." % cell)
  File "/usr/lib/python3/dist-packages/ufl/log.py", line 158, in error
    raise self._exception_type(self._format_raw(*message))
ufl.log.UFLException: Invalid cell < meshio mesh object>
  Number of points: 983
  Number of cells:
    triangle: 1787
  Cell data: name_to_read.

What’s wrong in here?

Please properly format your code using ``` and preserve indentation.
Similarly, wrap additional statements such as output in a similar fashion.

Hi dokken! I installed meshio 4.3.10. But there seems to be a problem with the following set of codes:

import meshio
msh = meshio.read("annulusgeometry.msh")

meshio.write("mesh.xdmf", meshio.Mesh(points=msh.points, cells={"triangle": msh.cells["triangle"]}))
meshio.write("mf.xdmf", meshio.Mesh(points=msh.points, cells={"line": msh.cells["line"]},
                                    cell_data={"line": {"name_to_read": msh.cell_data["line"]["gmsh:physical"]}}))
meshio.write("cf.xdmf", meshio.Mesh(
    points=msh.points, cells={"triangle": msh.cells["triangle"]},
      cell_data={"triangle": {"name_to_read":
                            msh.cell_data["triangle"]["gmsh:physical"]}}))


from dolfin import * 
mesh = Mesh()
with XDMFFile("mesh.xdmf") as infile:
    infile.read(mesh)
mvc = MeshValueCollection("size_t", mesh, 3) 
with XDMFFile("mf.xdmf") as infile:
    infile.read(mvc, "name_to_read")
mf = cpp.mesh.MeshFunctionSizet(mesh, mvc)

mvc = MeshValueCollection("size_t", mesh, 3)
with XDMFFile("cf.xdmf") as infile:
    infile.read(mvc, "name_to_read")
cf = cpp.mesh.MeshFunctionSizet(mesh, mvc)

ds_custom = Measure("ds", domain=mesh, subdomain_data=mf, subdomain_id=12)

The error reads:

    meshio.write("mesh.xdmf", meshio.Mesh(points=msh.points, cells={"triangle": msh.cells["triangle"]}))
    TypeError: list indices must be integers or slices, not str

Is this error generated because of the version of meshio? With version 3.2.7, this error didn’t show up.

Please use the code I supplied to you above for writing the mesh and markers to xdmf:

import meshio
msh = meshio.read("name_of_mesh_file.msh")
triangle_mesh = create_mesh(msh, "triangle", True)
line_mesh = create_mesh(msh, "line", True)
meshio.write("mesh.xdmf", triangle_mesh)
meshio.write("mf.xdmf", line_mesh) 
from dolfin import *
mesh = Mesh()
mvc = MeshValueCollection("size_t", mesh, mesh.topology().dim())
with XDMFFile("mesh.xdmf") as infile:
   infile.read(mesh)
   infile.read(mvc, "name_to_read")
cf = cpp.mesh.MeshFunctionSizet(mesh, mvc)

mvc = MeshValueCollection("size_t", mesh, mesh.topology().dim()-1)
with XDMFFile("mf.xdmf") as infile:
    infile.read(mvc, "name_to_read")
mf = cpp.mesh.MeshFunctionSizet(mesh, mvc)
ds_custom = Measure("ds", domain=mesh, subdomain_data=mf, subdomain_id=12)

Here’s the error message with this:

SyntaxError: Non-UTF-8 code starting with '\x93' in file annulus2.py on line 31, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

and line 31 is

mvc = MeshValueCollection(“size_t”, mesh, mesh.topology().dim())

I went to the website but didn’t find anything that helped!

This was due to the fact that I copied your code that wasn’t properly formatted. I have modified my code above, so you should not experience that error any longer if you try to copy it

I am getting the same error (I copied the entire code from above)
SyntaxError: Non-UTF-8 code starting with '\x93' in file annulus2.py on line 33, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

but this time it’s with the part of the code (line 33), which is:
infile.read(mvc, “name_to_read”)