How to write mesh tags to an XDMF file?


import numpy as np
from mpi4py import MPI
import ufl
import dolfinx.io 
from dolfinx import fem, mesh
import dolfinx.fem.petsc


L = 5.0
H = 1.0
Nx = 20
Ny = 5
domain = mesh.create_rectangle(
    MPI.COMM_WORLD,
    [(0.0, -H / 2), (L, H / 2)],
    (Nx, Ny),
    diagonal=mesh.DiagonalType.crossed,
)


E = fem.Constant(domain, 1e5)
nu = fem.Constant(domain, 0.3)
mu = E / 2 / (1 + nu)
lmbda = E * nu / (1 + nu) / (1 - 2 * nu)


def eps(v):
    return ufl.sym(ufl.grad(v))


def sigma(v):
    return lmbda * ufl.tr(eps(v)) * ufl.Identity(2) + 2.0 * mu * eps(v)

fx = 0.1
fy = -1.0
f = fem.Constant(domain, (fx, fy))

V = fem.functionspace(domain, ("P", 2, (2,)))
du = ufl.TrialFunction(V)
u_ = ufl.TestFunction(V)
a = ufl.inner(sigma(du), eps(u_)) * ufl.dx
l = ufl.inner(f, u_) * ufl.dx

def left(x):
    return np.isclose(x[0], 0.0)

fdim = domain.topology.dim - 1

# Locate facets on the boundary
facets = mesh.locate_entities_boundary(domain, fdim, left)

# Create the MeshTags object
values = np.full(len(facets), 1, dtype=np.int32)
adjacency_list = dolfinx.graph.adjacencylist(np.array(facets, dtype=np.int32))
# Convert the adjacency list to a NumPy array
entities = np.asarray(adjacency_list.array, dtype=np.int32)
facet_tags = dolfinx.mesh.meshtags(domain, fdim, entities, values)
facet_tags.name = "Facet Tags"


# Get the geometry of the mesh
x = domain.geometry.x

with dolfinx.io.XDMFFile(MPI.COMM_WORLD, "output.xdmf", "w") as xdmf:
    # Write the Mesh object to the file
    xdmf.write_mesh(domain)
    # Write the MeshTags object to the file
    xdmf.write_meshtags(facet_tags, x)

Traceback:::


Traceback (most recent call last):
  File "/home/prusso/dolfinx-demos/HowToCreateMeshTags2.py", line 68, in <module>
    xdmf.write_meshtags(facet_tags, x)
  File "/home/prusso/spack/var/spack/environments/fenicsx-env/.spack-env/view/lib/python3.11/site-packages/dolfinx/io/utils.py", line 233, in write_meshtags
    super().write_meshtags(tags._cpp_object, x, geometry_xpath, xpath)
TypeError: write_meshtags(): incompatible function arguments. The following argument types are supported:
    1. write_meshtags(self, meshtags: dolfinx.cpp.mesh.MeshTags_int32, x: dolfinx.cpp.mesh.Geometry_float32, geometry_xpath: str, xpath: str = '/Xdmf/Domain') -> None
    2. write_meshtags(self, meshtags: dolfinx.cpp.mesh.MeshTags_int32, x: dolfinx.cpp.mesh.Geometry_float64, geometry_xpath: str, xpath: str = '/Xdmf/Domain') -> None

Invoked with types: dolfinx.io.utils.XDMFFile, dolfinx.cpp.mesh.MeshTags_int32, ndarray, str, str

There seems to be some type of difficulty writing the XDMF file. Any way to get a traceback like this to resolve?

Last input argument to xdmf.write_meshtags should be domain.geometry, not domain.geometry.x.

2 Likes