This is a read only copy of the old FEniCS QA forum. Please visit the new QA forum to ask questions

read in mesh and functins from XDMF file

+1 vote

Hi all,

I've output results into time-series xdmf files, and now wish to read the data (mesh and functions) back for further use. I am using Fenics 1.60
Here's an example of output:

from dolfin import *
import numpy
parameters["allow_extrapolation"]=True
mesh=UnitSquareMesh(10,10)
V=FunctionSpace(mesh,'CG',1)
U = Function(V)
U.interpolate(Expression(('0.25*x[0]')))
# as_backend_type(U.vector()).update_ghost_values()
file = File('mesh.xdmf')# << U
file << (U , 1.0)
#ALE.move(mesh, Constant((1, 1)))
V = VectorFunctionSpace(mesh, 'CG', 1)
# Shear displacement
u = interpolate(Expression(('0.25*x[1]', '0')), V)
mesh.move (u)
file << (U,2.0)
plot(U)
interactive()

and what I am looking for is:

file = File('mesh.xdmf')
file >> U
file >> mesh

Any suggestions how do this?
Thanks.

asked Oct 11, 2016 by qiangzini FEniCS Novice (760 points)

1 Answer

0 votes

You will need to make use of the XDMFFile class,

from dolfin import *
mesh = Mesh()
filename = "mesh.xdmf"
f = XDMFFile(mpi_comm_world(), filename)
f.read(mesh, True)
plot(mesh)

It looks like you can only read the first mesh function from the file at the moment, someone with more expertise can confirm/deny.

Edited to use corrected code - Thanks to Eleanora

answered Oct 11, 2016 by varnis FEniCS Novice (390 points)
edited Oct 12, 2016 by varnis

Yes, I agree with you but it seems to me the syntax is not really correct.
To read a mesh from file I would rather do:

from dolfin import *
mesh = Mesh()
filename = "mesh.xdmf"
f = XDMFFile(mpi_comm_world(), filename)
f.read(mesh, True)
plot(mesh)

Thanks.

I notice that I could not load functions from XDMFFiles. In the end, I decided to output data in both hdf5 and XDMF files, and the first format for later use, and second for visualisation.

Output use:

HDF5File Out_Electric(comm, "Out_Electric.h5", "w" );
Out_Electric.write(mesh_elec, "Electrical_mesh");
HDF5File Out_Mechanic(comm, "Out_Mechanic.h5", "w" );
Out_Mechanic.write(mesh_mech, "Mechanical_mesh");

and read back:

from dolfin import *
import numpy
# Extrapolation needed to avoid errors beacuse each process looks for the point even if it does not own it
parameters["allow_extrapolation"]=True

#electrical data
mesh_elec= Mesh(mpi_comm_world())
hdf = HDF5File(mpi_comm_world(), "Out_Electric.h5", "r")

hdf.read(mesh_elec, 'Electrical_mesh', False)

V = FunctionSpace(mesh_elec,'CG',1)
F_elec = Function(V)
hdf.read(F_elec, 'Electric/vector_2')
...