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

Dump solution data in .txt file

0 votes

Hi, I am solving linear elasticity problem. I want to save displacement (solution) in txt file for all the nodes. any idea.
Thanks in advance

from dolfin import *
mesh = UnitSquareMesh(2,2)
E, nu = Constant(10.0), Constant(0.3)
plot(mesh, title = 'mesh', interactive = True)
ndim = mesh.geometry().dim()
def eps(v):
    return sym(grad(v))
def eps_dev(du):
    return dev(eps(du))
zero_v=Constant((0.,)*ndim)   
f=zero_v
V = VectorFunctionSpace(mesh, 'Lagrange', 1)
u = TrialFunction(V)
v = TestFunction(V)
du = Function(V)

mu    = E/(2.0*(1.0 + nu))
lmbda = E*nu/((1.0 + nu )*(1.0-2.0*nu))
EDef = ( mu*tr(eps(du)*eps(du)) + 0.5*lmbda*tr(eps(du))**2 )*dx - dot(f,du)*dx
EDer = derivative(EDef,du,v)
J = derivative(EDer,du,u)
class top(SubDomain):
       def inside(self,x,on_boundary):
            tol = 1e-10
            return abs(x[1]-1.0) < tol and on_boundary

class bottom(SubDomain):
       def inside(self,x,on_boundary):
             tol = 1e-10
             return abs(x[1]) < tol and on_boundary
Top = top()
Bottom = bottom()
bclx= DirichletBC(V.sub(0), Constant(0.0), Bottom)
bcly = DirichletBC(V.sub(1), Constant(0.0), Bottom)
bcty = DirichletBC(V.sub(1), Constant(1.0), Top)
bc_u = [bclx, bcly, bcty]

solve(EDer==0,du, J = J, bcs=bc_u)
asked May 22, 2017 by hirshikesh FEniCS User (1,890 points)

1 Answer

0 votes
 
Best answer

Try something like:

import numpy as np

# Tabulate dof coordinates
x = V.tabulate_dof_coordinates(mesh)
x = x.reshape((-1, mesh.geometry().dim()))

# Save solution
np.savetxt("mysol.txt", zip(x[:,0], x[:,1], du.vector()[:]))

With this approach the solution will be exported in the format (x,y,z,du)

answered May 22, 2017 by hernan_mella FEniCS Expert (19,460 points)
selected May 23, 2017 by hirshikesh

Hi, after doing this i am getting this error.

x = V.tabulate_dof_coordinates(mesh)
AttributeError: 'VectorFunctionSpace' object has no attribute 'tabulate_dof_coordinates'

Thanks for the help.

Which version of fenics are you using?

The syntax used in my answer would works in fenics 2016.2 (see here).

I am using 1.6.0 , I have checked like this dolfin-version.

In your version of fenics change the second line by

x = V.dofmap().tabulate_all_coordinates(mesh)

Now I got an error in the third line I could not figure it out how to rectify this.

Value error: total size of the new array must be changed.

Thanks for the help.

I have edited my answer (the third line was wrong. Sorry for that)

Thank you for your help, it is working fine.

...