Writing vector filed components in XDMF

Here’s a simple example of Dolfin-X code that produces vector field:

import ufl
from mpi4py import MPI
import numpy
import dolfinx
import dolfinx.io

mesh = dolfinx.generation.UnitCubeMesh(MPI.COMM_WORLD, 11, 11, 11)    # 3D mesh

P1 = ufl.FiniteElement('Lagrange', mesh.ufl_cell(), 1)

Vs = dolfinx.fem.FunctionSpace(mesh, P1)                          # scalar space
Vv = dolfinx.fem.FunctionSpace(mesh, ufl.MixedElement(P1, P1, P1))  # vector space

# scalar space
us = ufl.TrialFunction(Vs)
vs = ufl.TestFunction(Vs)
xs = ufl.SpatialCoordinate(Vs)

# $a={u_s}\cdot{v_s}$
# $L=100\left(x^2+y^3\right)\cdot{v_s}$
a_p = (ufl.inner(us, vs) * ufl.dx)
L_p = (100*ufl.inner(xs[0]**2+xs[1]**3, vs) * ufl.dx)
projection = dolfinx.fem.LinearProblem(a_p, L_p)
initial = projection.solve()

fle = dolfinx.io.XDMFFile(MPI.COMM_WORLD, '/tmp/field.xdmf', 'w')
fle.write_mesh(mesh)                                # mesh
fle.write_function(initial)                         # initial field distribution

# vector space
uv = ufl.TrialFunction(Vv)
vv = ufl.TestFunction(Vv)
xv = ufl.SpatialCoordinate(Vv)

# $a={u_v}\cdot{v_v}$
# $L=\left(\nabla{f_{init}}\right)\cdot{v_v}$
a_p = (ufl.inner(uv, vv) * ufl.dx)
L_p = (ufl.inner(ufl.grad(initial), vv) * ufl.dx)
projection = dolfinx.fem.LinearProblem(a_p, L_p)
u = projection.solve()
ux, uy, uz = u.split()

fle.write_function(ux)                                                # field Fx
fle.write_function(uy)                                                # field Fy
fle.write_function(uz)                                                # field Fx

I used dolfinx.io.XDMFFile.write_function to write field components to the XDMF file. Then I tried to visualize a vector field in paraview using this method. However, it didn’t produce any results.

I’ve asked paraview community about this problem and I was told that field components need to be in the same data block in order to be combined into vector field.

Is it possible to write field components into the same data block in XDMF file? Alternitevly, is there any other way to combine vector field components into the vector filed in paraview?

You should use a VectorElement, and not a mixed element, if you want to visualize a vector quantity.

1 Like

It did the trick. Thanks!

A follow up question. Should I use different XDMF file for each produced field? Glyph filter seem to work properly only if there’s no extra fields in the data set and only if the particular XDMF reader is used. Otherwise I get two arrows at each point:

You can use Filters->Extract Block as described in: Using Paraview for visualization — FEniCSx tutorial

1 Like

Thanks again! Sorry for not reading tutorial more thoroughly.