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

How to get numpy array of a Tensor

+1 vote

If there is a vector u I can get the numpy array with

u.vector().array()

How can I get this Information out of a tensor e.g.

sigma = 2*mu*sym(grad(u)) + lamda*tr(grad(u))*Identity(w.cell().d)

I need this for computing the von Mises stress.
My second question is, how can I change a tensor at a single point?

asked Jul 7, 2014 by andrew2748 FEniCS Novice (220 points)

What kind of function space do you have in mind for the tensor?

Ok I see my problem. For my vector I have the function space

V = VectorFunctionSpace(mesh, "Lagrange", 2)
u = Function(V)

But I don't have a function space for my tensor. Can I create it with e.g.

V_tensor = TensorFunctionSpace(mesh, "Lagrange", 2)
sigma = Function(V_tensor)

?

Yes, that is correct

from dolfin import *

mesh = UnitSquareMesh(2, 2)

V = VectorFunctionSpace(mesh, 'CG', 1)
u = interpolate(Expression(('x[0]', 'x[1]')), V)

T = TensorFunctionSpace(mesh, 'CG', 1)
t = project(grad(u), T)

You can then do

values = t.vector().array()

Ok, that works. Thank you!

I detected that the array is no pointer at the tensor. Is there a way to interpolate the array back at the tensor, after I changed the array?

Yes there is. Try

import numpy as np

print t.vector().norm('l2')

t_array = t.vector().array()
t_array += np.random.rand(len(t_array))
t.vector()[:] = t_array

print t.vector().norm('l2')

Thank you. I think that was all I needed.

Hi andrew2748, It's been long since your last post, but can you pls. post the final code where your stress tensor can be viewed. I tried on my elasticity code but keep getting an error. Thanks!

...