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

how to use the MeshFunction.set_values() method in python?

0 votes

Hello everyone,

I have question concerning the use of mesh functions in python. Usually, when assigning values to a mesh function in python, I do something like the following:

f = MeshFunction('bool', mesh, 2)
for T in cells(mesh):
    f[T] = some_array[T.index()]

Unfortunately, at some Point this loop starts taking forever (when the number of unknowns is very high) and takes much longer than solving the linear Systems. (Maybe I am already doing something wrong to cause this?)

So I noticed that MeshFunction has a method set_values() which should hopefully (please correct me in case I am wrong) be a "vectorized" version of the above for-loop and therefore faster. So I want to do something like

f.set_values(some_array)

But how do I use this set_value() method? According to the docstring it takes a "std::vector" as Input but this is a C++ Data Type and I have no idea what this translates to in python. What do I need to pass to the method?

I would be grateful for any help on this matter and clarification on how to interpret the docstring and why the for-loop is so slow.

regards

asked May 18, 2015 by multigrid202 FEniCS User (3,780 points)

1 Answer

0 votes
 
Best answer

Just use the NumPy view of the data directly.

f = MeshFunction('bool', mesh, 2)
f.array()[:] = some_array
answered May 19, 2015 by johanhake FEniCS Expert (22,480 points)
selected May 19, 2015 by multigrid202

Thanks a lot for your quick reply. Could I ask you a follow-up question? Why does this method work on a MeshFunction and not on vec in

u = Function(...)
Constants = FunctionSpace(mesh, 'DG', 0)
w = TestFunction(Constants) 
form = inner(grad(u), grad(u))*w*dx

vec = assemble(form)

The docstrings for the two array() methods are not the same, but they are at least similar in a way to suggest that they can be used in a similar manner.

Is there any other source of documentation on this kind of problem? Often I see a method with a name that sounds like what I am looking for but I don't know what to do with it and I wouldn't like to bother people each time I don't know how to use it (i.e. what arguments to pass etc.)

Just bother the forum with any questions!

The difference in the docstrings do point to the actual differences, but I give you that it is not that explicit.

The docstring of MeshFunction.array says it is a 'view' which means that changing that will change the actual values.

The docstring of Vector.array says it is a 'representation'. That is somewhat uninformal. It is actually a copy of the values. This is because dolfin does not owe the actual data, but rather the linear algebra backend. So we are not able to alter the data directly. But that you could not know :)

So the devil is indeed in the details :)
Thanks for the clarification.

...