Plotting multiple functions in same XDMF file

Hello, I am trying to write out multiple functions in the same file in dolfinx XDMFFile format. Please find MWE below. When I open the XDMF file in Paraview 5.12, I am only able to see the second function being plotted, (array for function 1 not available). I also tried the “Filters → Extract block” as suggested here: multiple functions but still only able to visualize function 1.

from mpi4py import MPI
import dolfinx as dlx
import numpy as np

comm = MPI.COMM_WORLD
rank = comm.rank
nproc = comm.size

msh = dlx.mesh.create_unit_square(comm, 10, 10, dlx.mesh.CellType.quadrilateral)
Vh_m = dlx.fem.FunctionSpace(msh, ("Lagrange", 1))

f1 = dlx.fem.Function(Vh_m,name='f1')
f1.interpolate(
    lambda x: np.log(2 + 7 * (((x[0] - 0.5) ** 2 + (x[1] - 0.5) ** 2) ** 0.5 > 0.2))
)
f1.x.scatter_forward()


f2 = dlx.fem.Function(Vh_m,name='f2')
f2.interpolate(
    lambda x: np.log(10 + 3* (((x[0] - 0.5) ** 2 + (x[1] - 0.5) ** 2) ** 0.5 > 0.2))
)
f2.x.scatter_forward()

with dlx.io.XDMFFile(
    msh.comm,
    "output.xdmf".format(nproc),
    "w",
) as file:
    file.write_mesh(msh)
    file.write_function(f1, 0)
    file.write_function(f2, 1)

Some other links which may have relevant information but I am not able to get it to work:

Time dependent: Time-dependent mesh using XDMF File in DOLFINx - #10 by rsz7ncf24p

Hi.

Welcome to the FEniCS community!

Changing file.write_function(f2, 1) by file.write_function(f2, 0) gives the desired result.

Consider the following MWE (adapted from your code):

from mpi4py import MPI
import dolfinx as dlx
import numpy as np

comm = MPI.COMM_WORLD
rank = comm.rank
nproc = comm.size

msh = dlx.mesh.create_unit_square(comm, 10, 10, dlx.mesh.CellType.quadrilateral)
Vh_m = dlx.fem.FunctionSpace(msh, ("Lagrange", 1))

f1 = dlx.fem.Function(Vh_m,name='f1')
f1.interpolate(
    lambda x: np.sin(x[0]*x[1])
)
f1.x.scatter_forward()


f2 = dlx.fem.Function(Vh_m,name='f2')
f2.interpolate(
    lambda x: 1/np.sqrt((x[0]-0.5)**2 + (x[1]-0.5)**2 + 1.)
)
f2.x.scatter_forward()

with dlx.io.XDMFFile(
    msh.comm,
    "outputmutiple.xdmf".format(nproc),
    "w",
) as file:
    file.write_mesh(msh)
    file.write_function(f1, 0)
    file.write_function(f2, 0)

Which produces

1 Like

Thank you so much for the quick help. It works now.