# Compute derivatives in FEniCSX

Hi all! I am doing the sensitivity analysis and I have several questions about FEniCSX.

Question 1

Take the classical demo Hyperelasticity — FEniCSx tutorial (jorgensd.github.io) as an example. Now we assume the elasticity parameter `mu` is a cell-wise constant instead of a constant on the whole mesh.

``````S = dolfinx.FunctionSpace(mesh, ('DG', 0))
mu = dolfinx.Function(S)
``````

And we can set some arbitrary values to `mu`

``````import numpy as np
NElem = mesh.topology.index_map(mesh.topology.dim).size_local # number of elements
with mu.vector.localForm() as mu_loc:
mu_loc.setValues(np.arange(NElem).tolist(), np.arange(NElem).tolist())
``````

How can I output the values of `mu` ? In this case it should be `np.arange(NElem).tolist()`.

Question 2

Now we want to compute the derivative of `F` with respect to the parameter `mu` of each element

``````F = ufl.inner(ufl.grad(v), P)*dx - ufl.inner(v, B)*dx - ufl.inner(v, T)*ds(2)
dFdmu1 = ufl.diff(F, mu1)
dFdmu2 = ufl.diff(F, mu2)
dFdmu3 = ufl.diff(F, mu3)
...
``````

This process should be equivalent to compute cell-wise integrals as (since `mu1`, `mu2`, and `mu3` are independent variables):

``````dFdmu1 = ufl.diff(F, mu) # take the integral on element 1
dFdmu2 = ufl.diff(F, mu) # take the integral on element 2
dFdmu3 = ufl.diff(F, mu) # take the integral on element 3
...
``````

So is it possible to compute these derivatives conveniently in FEniCSX? I think it is doable with for-loops, but it will be very slow if we have a larger mesh.

Question 3
Finally, I want to assemble these vectors:

``````R1 = dolfinx.fem.assemble_vector(dFdmu1) # vector 1
R2 = dolfinx.fem.assemble_vector(dFdmu2) # vector 2
R3 = dolfinx.fem.assemble_vector(dFdmu2) # vector 3
``````

Is there some way to assemble multiple vectors simultaneously to improve computational efficiency? It might be something like

``````dolfinx.fem.assemble_vector([dFdmu1, dFdmu2, dFdmu3])
``````

and then we will obtain a matrix containing the assembled vectors.

Thanks!

As `mu` is a `dolfinx.Function`, you can print the values using `mu.vector.array`

For your other questions, you need to provide minimal working code examples, as you have not defined `mu1`-`mu3`, and I do not understand what you are trying to do.

1 Like