Problem with read a external mesh

Hi everyone.

I’m trying to read a mesh generated by Ansys in FEniCSx. The mesh is in .msh. I change the format with

meshio convert fluent.msh venturi_1600.xdmf

but when I try to open

import dolfinx

##########################################################################################################3

    # Read the mesh
    
with dolfinx.io.XDMFFile(MPI.COMM_WORLD, "venturi_1600.xdmf", "r") as xdmf:
    domain = xdmf.read_mesh(name='Grid')

I obtain

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
Cell In[2], line 5
      1 import dolfinx
      4 with dolfinx.io.XDMFFile(MPI.COMM_WORLD, "venturi_1600.xdmf", "r") as xdmf:
----> 5     domain = xdmf.read_mesh(name='Grid')
      7 tdim = domain.topology.dim
      8 tree = dolfinx.geometry.BoundingBoxTree(domain, tdim)

File /usr/lib/petsc/lib/python3/dist-packages/dolfinx/io/utils.py:154, in XDMFFile.read_mesh(self, ghost_mode, name, xpath)
    152 def read_mesh(self, ghost_mode=GhostMode.shared_facet, name="mesh", xpath="/Xdmf/Domain") -> Mesh:
    153     """Read mesh data from file"""
--> 154     cell_shape, cell_degree = super().read_cell_type(name, xpath)
    155     cells = super().read_topology_data(name, xpath)
    156     x = super().read_geometry_data(name, xpath)

RuntimeError: Cannot recognise cell type. Unknown value: mixed

but the mesh has a unique element (Quadrilateral).

I can export the mesh with different formats:

The mesh is in this folder:

Does anyone has a idea to solve?

Thank you so much!

See: Can dolfinx read a GMSH file containing 1D mesh of an ellipse? - #2 by dokken

I have tried that code with the following change:

meshio.write("venturi_1600.xdmf, create_mesh, (mesh, "quadrilateral", True))

and I get the next error

KeyError: 'quadrilateral'

I find the name of elements here:
https://fenicsproject.org/olddocs/dolfinx/dev/python/generated/dolfinx.cpp.mesh.html

This does not make sense, it should be:
meshio.write("venturi_1600.xdmf, create_mesh(mesh, "quad", True))
if mesh is a meshio mesh.
See https://github.com/nschloe/meshio/blob/0138cc8692b806b44b32d344f7961e8370121ff7/src/meshio/_mesh.py#L14

Thank you @dokken, but now I try


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)
    points = mesh.points[:,:2] if prune_z else mesh.points
    out_mesh = meshio.Mesh(points=points, cells={cell_type: cells}, cell_data = {"name_to_read": [cell_data]})
    return out_mesh

mesh = meshio.read("fluent.msh")

meshio.write("venturi_1600.xdmf", create_mesh(mesh,"quad", True))

and obtain:

KeyError                                  Traceback (most recent call last)
Cell In[1], line 36
     32     return out_mesh
     34 mesh = meshio.read("fluent.msh")
---> 36 meshio.write("venturi_1600.xdmf", create_mesh(mesh,"quad", True))

Cell In[1], line 29, in create_mesh(mesh, cell_type, prune_z)
     27 def create_mesh(mesh, cell_type, prune_z=False):
     28     cells = mesh.get_cells_type(cell_type)
---> 29     cell_data = mesh.get_cell_data("gmsh:physical", cell_type)
     30     points = mesh.points[:,:2] if prune_z else mesh.points
     31     out_mesh = meshio.Mesh(points=points, cells={cell_type: cells}, cell_data = {"name_to_read": [cell_data]})

File ~/.local/lib/python3.10/site-packages/meshio/_mesh.py:250, in Mesh.get_cell_data(self, name, cell_type)
    248 def get_cell_data(self, name: str, cell_type: str):
    249     return np.concatenate(
--> 250         [d for c, d in zip(self.cells, self.cell_data[name]) if c.type == cell_type]
    251     )

KeyError: 'gmsh:physical'

I try

print(mesh.cell_data)

and obtain

{}

I think you need to remove the cell_data part and try like -

def create_mesh(mesh, cell_type, prune_z=False):
    cells = mesh.get_cells_type(cell_type)
    points = mesh.points[:,:2] if prune_z else mesh.points
    out_mesh = meshio.Mesh(points=points, cells={cell_type: cells})
    return out_mesh

mesh = meshio.read("fluent.msh")

meshio.write("venturi_1600.xdmf", create_mesh(mesh,"quad", True))
1 Like

sorry for the delay. When I run it, I get this error.

Warnig: py.warning:/urs/local/lib/python3.10/dist-packages/h5py/__init__.py:36 UserWarning: h5py is running against HDF5 1.10.7 when it was bulit against 1.12.2, this may cause problems

and the kernel dies…

I tried to install these version but I get the same error…

See The kernel appears to have died. It will restart automatically - #13 by dokken

I followed the steps, uninstalled h5py and ran in terminalI followed the steps, uninstalled h5py and ran in terminal

python3 -m pip install --no-binary=h5py h5py meshio

and I get

Defaulting to user installation because normal site-packages is not writeable
Collecting h5py
  Using cached h5py-3.9.0.tar.gz (402 kB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
  Installing backend dependencies ... done
  Preparing metadata (pyproject.toml) ... done
Requirement already satisfied: meshio in ./.local/lib/python3.10/site-packages (5.3.4)
Requirement already satisfied: numpy>=1.17.3 in /usr/lib/python3/dist-packages (from h5py) (1.21.5)
Requirement already satisfied: rich in ./.local/lib/python3.10/site-packages (from meshio) (13.3.4)
Requirement already satisfied: pygments<3.0.0,>=2.13.0 in ./.local/lib/python3.10/site-packages (from rich->meshio) (2.15.0)
Requirement already satisfied: markdown-it-py<3.0.0,>=2.2.0 in ./.local/lib/python3.10/site-packages (from rich->meshio) (2.2.0)
Requirement already satisfied: mdurl~=0.1 in ./.local/lib/python3.10/site-packages (from markdown-it-py<3.0.0,>=2.2.0->rich->meshio) (0.1.2)
Building wheels for collected packages: h5py
  Building wheel for h5py (pyproject.toml) ... error
  error: subprocess-exited-with-error
  
  × Building wheel for h5py (pyproject.toml) did not run successfully.
  │ exit code: 1
  ╰─> [89 lines of output]
      running bdist_wheel
      running build
      running build_ext
      
      Error compiling Cython file:
      ------------------------------------------------------------
      ...
      
      cdef struct err_data_t:
          H5E_error_t err
          int n
      
      cdef herr_t walk_cb(unsigned int n, const H5E_error_t *desc, void *e) nogil noexcept:
                                                                                 ^
      ------------------------------------------------------------
      
      h5py/_errors.pyx:97:76: Syntax error in C variable declaration
      Loading library to get build settings and version: /usr/lib/x86_64-linux-gnu/hdf5/openmpi/libhdf5.so
      ********************************************************************************
                             Summary of the h5py configuration
      
        HDF5 include dirs: [
        '/usr/include/hdf5/openmpi'
        '/usr/lib/x86_64-linux-gnu/openmpi/include'
        '/usr/lib/x86_64-linux-gnu/openmpi/include/openmpi'
      ]
        HDF5 library dirs: [
        '/usr/lib/x86_64-linux-gnu/hdf5/openmpi'
        '/usr/lib/x86_64-linux-gnu/openmpi/lib'
      ]
             HDF5 Version: (1, 10, 7)
              MPI Enabled: False
         ROS3 VFD Enabled: True
       DIRECT VFD Enabled: False
         Rebuild Required: True
           MS-MPI Enabled: False
      MS-MPI include dirs: []
      MS-MPI library dirs: []
      
      ********************************************************************************
      Executing api_gen rebuild of defs
      Updated /tmp/pip-install-mz8ute5r/h5py_7dbb00c2e84c4528a56317c969e584e7/h5py/config.pxi
      Executing cythonize()
      [ 1/24] Cythonizing /tmp/pip-install-mz8ute5r/h5py_7dbb00c2e84c4528a56317c969e584e7/h5py/_conv.pyx
      [ 2/24] Cythonizing /tmp/pip-install-mz8ute5r/h5py_7dbb00c2e84c4528a56317c969e584e7/h5py/_errors.pyx
      Traceback (most recent call last):
        File "/usr/lib/python3/dist-packages/pip/_vendor/pep517/in_process/_in_process.py", line 363, in <module>
          main()
        File "/usr/lib/python3/dist-packages/pip/_vendor/pep517/in_process/_in_process.py", line 345, in main
          json_out['return_val'] = hook(**hook_input['kwargs'])
        File "/usr/lib/python3/dist-packages/pip/_vendor/pep517/in_process/_in_process.py", line 261, in build_wheel
          return _build_backend().build_wheel(wheel_directory, config_settings,
        File "/usr/lib/python3/dist-packages/setuptools/build_meta.py", line 230, in build_wheel
          return self._build_with_temp_dir(['bdist_wheel'], '.whl',
        File "/usr/lib/python3/dist-packages/setuptools/build_meta.py", line 215, in _build_with_temp_dir
          self.run_setup()
        File "/usr/lib/python3/dist-packages/setuptools/build_meta.py", line 158, in run_setup
          exec(compile(code, __file__, 'exec'), locals())
        File "setup.py", line 68, in <module>
          setup(
        File "/usr/lib/python3/dist-packages/setuptools/__init__.py", line 153, in setup
          return distutils.core.setup(**attrs)
        File "/usr/lib/python3/dist-packages/setuptools/_distutils/core.py", line 148, in setup
          return run_commands(dist)
        File "/usr/lib/python3/dist-packages/setuptools/_distutils/core.py", line 163, in run_commands
          dist.run_commands()
        File "/usr/lib/python3/dist-packages/setuptools/_distutils/dist.py", line 967, in run_commands
          self.run_command(cmd)
        File "/usr/lib/python3/dist-packages/setuptools/_distutils/dist.py", line 986, in run_command
          cmd_obj.run()
        File "/usr/lib/python3/dist-packages/wheel/bdist_wheel.py", line 299, in run
          self.run_command('build')
        File "/usr/lib/python3/dist-packages/setuptools/_distutils/cmd.py", line 313, in run_command
          self.distribution.run_command(command)
        File "/usr/lib/python3/dist-packages/setuptools/_distutils/dist.py", line 986, in run_command
          cmd_obj.run()
        File "/usr/lib/python3/dist-packages/setuptools/_distutils/command/build.py", line 135, in run
          self.run_command(cmd_name)
        File "/usr/lib/python3/dist-packages/setuptools/_distutils/cmd.py", line 313, in run_command
          self.distribution.run_command(command)
        File "/usr/lib/python3/dist-packages/setuptools/_distutils/dist.py", line 986, in run_command
          cmd_obj.run()
        File "/tmp/pip-install-mz8ute5r/h5py_7dbb00c2e84c4528a56317c969e584e7/setup_build.py", line 171, in run
          self.extensions = cythonize(self._make_extensions(config),
        File "/usr/lib/python3/dist-packages/Cython/Build/Dependencies.py", line 1127, in cythonize
          cythonize_one(*args)
        File "/usr/lib/python3/dist-packages/Cython/Build/Dependencies.py", line 1250, in cythonize_one
          raise CompileError(None, pyx_file)
      Cython.Compiler.Errors.CompileError: /tmp/pip-install-mz8ute5r/h5py_7dbb00c2e84c4528a56317c969e584e7/h5py/_errors.pyx
      [end of output]
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
  ERROR: Failed building wheel for h5py
Failed to build h5py
ERROR: Could not build wheels for h5py, which is required to install pyproject.toml-based projects

Could you check what cython version you have on your system, as they just released a new version 2 days ago (it might be that you need to pin it to an earlier version of cython).

I have
Cython version 0.29.28

What system are you running on?
Can you produce an environment that reproduces this error (say with docker)?

I use Ubuntu 22.04.2 LTS.

I have never used docker. how can I do it?

How did you install dolfinx? Through apt-Get?

with this

add-apt-repository ppa:fenics-packages/fenics
apt update
apt install fenicsx

I cannot reproduce this error with a clean ubuntu system:
Dockerfile:

FROM ubuntu:22.04

ENV DEBIAN_FRONTEND=noninteractive
RUN apt-get update && \
    apt-get install -y software-properties-common && \
    add-apt-repository ppa:fenics-packages/fenics && \
    apt-get install -y fenicsx python3-pip

RUN python3 -m pip install --no-binary=h5py h5py meshio

built with:

docker build -t dx_meshio .

Do you have any suggestions?
I just need to transform the mesh and do the rest in my original code.

Its hard when I cant reproduce the error. What happens if you use the Gmsh Python interface to read the msh file and use dolfinx.io.gmshio.read_from_msh or dolfinx.io.gmshio.model_to_mesh?

If I use

mesh = dolfinx.io.gmshio.read_from_msh("fluent.msh", MPI.COMM_WORLD,gdim=2)   

I get

Error   : 'fluent.msh', line 1: syntax error (()
---------------------------------------------------------------------------
Exception                                 Traceback (most recent call last)
Cell In[4], line 27
     22 import meshio
     23 ##########################################################################################################3
     24 
     25     # Read the mesh    
---> 27 mesh = dolfinx.io.gmshio.read_from_msh("fluent.msh", MPI.COMM_WORLD,gdim=2)    
     29 def create_mesh(mesh, cell_type, prune_z=False):
     30     cells = mesh.get_cells_type(cell_type)

File /usr/lib/petsc/lib/python3/dist-packages/dolfinx/io/gmshio.py:306, in read_from_msh(filename, comm, rank, gdim, partitioner)
    304 gmsh.initialize()
    305 gmsh.model.add("Mesh from file")
--> 306 gmsh.merge(filename)
    307 msh = model_to_mesh(gmsh.model, comm, rank, gdim=gdim, partitioner=partitioner)
    308 gmsh.finalize()

File /usr/local/lib/python3.10/dist-packages/gmsh.py:354, in merge(fileName)
    350 lib.gmshMerge(
    351     c_char_p(fileName.encode()),
    352     byref(ierr))
    353 if ierr.value != 0:
--> 354     raise Exception(logger.getLastError())

Exception: 'fluent.msh', line 1: syntax error (()

and with

mesh, cell_markers, facet_markers = dolfinx.io.gmshio.model_to_mesh("fluent.msh", MPI.COMM_WORLD, 0 ,gdim=2)  
AttributeError                            Traceback (most recent call last)
Cell In[7], line 27
     22 import meshio
     23 ##########################################################################################################3
     24 
     25     # Read the mesh    
---> 27 mesh, cell_markers, facet_markers = dolfinx.io.gmshio.model_to_mesh("fluent.msh", MPI.COMM_WORLD, 0 ,gdim=2)    
     29 def create_mesh(mesh, cell_type, prune_z=False):
     30     cells = mesh.get_cells_type(cell_type)

File /usr/lib/petsc/lib/python3/dist-packages/dolfinx/io/gmshio.py:199, in model_to_mesh(model, comm, rank, gdim, partitioner)
    173 """Given a Gmsh model, take all physical entities of the highest
    174 topological dimension and create the corresponding DOLFINx mesh.
    175 
   (...)
    194     if found in Gmsh model.
    195 """
    197 if comm.rank == rank:
    198     # Get mesh geometry and mesh topology for each element
--> 199     x = extract_geometry(model)
    200     topologies = extract_topology_and_markers(model)
    202     # Extract Gmsh cell id, dimension of cell and number of
    203     # nodes to cell for each

File /usr/lib/petsc/lib/python3/dist-packages/dolfinx/io/gmshio.py:153, in extract_geometry(model, name)
    149     model.setCurrent(name)
    151 # Get the unique tag and coordinates for nodes
    152 # in mesh
--> 153 indices, points, _ = model.mesh.getNodes()
    154 points = points.reshape(-1, 3)
    156 # Gmsh indices starts at 1. We therefore subtract one to use
    157 # zero-based numbering

AttributeError: 'str' object has no attribute 'mesh'

I have tried a somewhat rough solution. I have downloaded a dolfinx image for docker

docker run -ti dolfinx/dolfinx:stable

and copied the .msh file to that container.

if I use this version of the code,

import dolfinx
from mpi4py import MPI
import numpy as np


from dolfinx import geometry
from dolfinx import io
import meshio
##########################################################################################################3

    # Read the mesh    

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)
    points = mesh.points
    #points = mesh.points[:,:2] if prune_z else mesh.points
    if prune_z:
        points = mesh.points[:,:2]
    out_mesh = meshio.Mesh(points=points, cells={cell_type: cells}, cell_data={"name_to_read": [cell_data]})
    #out_mesh = meshio.Mesh(points=points, cells={cell_type: cells})
    return out_mesh

mesh = meshio.read("fluent.msh")

meshio.write("venturi_1600.xdmf", create_mesh(mesh,"quad", True))

I get

Traceback (most recent call last):
  File "/root/Venuri_fenicsx2D_m1600.py", line 33, in <module>
    meshio.write("venturi_1600.xdmf", create_mesh(mesh,"quad", True))
  File "/root/Venuri_fenicsx2D_m1600.py", line 22, in create_mesh
    cell_data = mesh.get_cell_data( "gmsh:physical", cell_type)
  File "/usr/local/lib/python3.10/dist-packages/meshio/_mesh.py", line 250, in get_cell_data
    [d for c, d in zip(self.cells, self.cell_data[name]) if c.type == cell_type]
KeyError: 'gmsh:physical'

with this version, using a previous suggestion.

import dolfinx
from mpi4py import MPI
from petsc4py import PETSc
import numpy as np
from petsc4py.PETSc import ScalarType

from dolfinx import geometry
from dolfinx import io
import meshio
##########################################################################################################3

    # Read the mesh    

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)
    points = mesh.points
    #points = mesh.points[:,:2] if prune_z else mesh.points
    if prune_z:
        points = mesh.points[:,:2]
    #out_mesh = meshio.Mesh(points=points, cells={cell_type: cells}, cell_data={"name_to_read": [cell_data]})
    out_mesh = meshio.Mesh(points=points, cells={cell_type: cells})
    return out_mesh

mesh = meshio.read("fluent.msh")

meshio.write("venturi_1600.xdmf", create_mesh(mesh,"quad", True))

seems to work…

But, when I open the .xdmf file with paraview nothing appears, but in information it does appear in number of points and dimensions.

If I try to define a function with that mesh and open it with paraview, it appears completely empty.