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

loading functions from a file

+2 votes

I have an xdmf file containing a time series of u which is generated like so

mesh = UnitSquareMesh(32, 32)
V = VectorFunctionSpace(mesh, "CG", 1, dim=2)
u  = Function(V)
u0 = Function(V)
# define some problem and solver
...

file = File("u_file.xdmf")

while t < T:
    u0.vector()[:] = u.vector()  # save solution from previous step
    solver.solve()  # solve for u
    file << u          # save u

Now suppose this code finished running and I wanted to load u and u0 at a particular time step, how can I do that?

asked May 4, 2014 by bshankar FEniCS Novice (790 points)

1 Answer

+6 votes

That is not straight forward. Using xdmf the result is stored as a vertex function and not with the regular function space. As long as you are still using a CG 1 space, though, it can be retrieved quite easily like this:

# Need the h5py module
import h5py

# Create a Function to read the solution into
u0 = Function(V)

# Open the result file for reading
fl = h5py.File("u_file.h5", "r")

# Choose the first time step
vec = fl["/VisualisationVector/0"]

# Scalar FunctionSpace Q is required for mapping vertices to dofs 
Q = FunctionSpace(mesh, 'CG', 1)
q = Function(Q)
v2d = vertex_to_dof_map(Q)
# Now map vertexfunction to the V function space
for i in range(2):
    q.vector()[v2d] = vec[:, i]
    assign(u0.sub(i), q)
answered May 4, 2014 by mikael-mortensen FEniCS Expert (29,340 points)

Thanks. Actually, I also need to load from a CG 2 space. So, there's no easy way to do this?

There is no way with xdmf since the CG2 is stored as a vertex function as well. You have to use HDF5File to save and retrieve CG2.

...