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

Problem with bc.apply and copy

+1 vote

Hello,
I wrote a code where I solve many times some PDEs using the same bilinear form but the boundary conditions and right-hand side keep changing. So I thought I could speed up the process by assembling once the matrix corresponding to this bilinear form, then save it and reuse it applying each iteration the new boundary conditions.

Let's say I take the following bilinear form for instance:

a  = inner(grad(u), grad(v))*dx

then assemble the matrix

M = assemble(a)

Then save the matrix

M_copy = M

Then apply boundary conditions to the copy

bc.apply(M_copy)

but here the problem is that the function "apply" modifies M_copy but also modifies M. Then I tried to do

M_copy = copy.copy(M)

but the problem is the same. Can someone explain me why M is also modified and how to avoid this? And also, if I succeed, can I really speed up the computation by doing so?

asked Jul 11, 2014 by Antoine FEniCS Novice (810 points)

1 Answer

+1 vote

If you apply boundary conditions at different dofs, you will need to use a "clean" matrix, as there is no way to "unapply" boundary conditions. In that case, saving the matrix M rather than reassembling it will be preferrable.

If the boundary conditions are applied to the same dofs (i.e. only the values change), you don't need to apply the boundary conditions to the matrix more than once.

Both your attempts to copy create a shallow copy of M, and therefore it points to the same underlying data. To (deep-)copy the matrix, use Matrix.copy or the copy constructor:

M_copy = M.copy()
# or
M_copy = Matrix(M)
answered Jul 11, 2014 by Øyvind Evju FEniCS Expert (17,700 points)
...