# How to get adjoint solution from compute\_gradient()

**URL:** <https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488>\
**Category:** dolfin-adjoint\
**Created:** [June 9, 2022, 5:18am UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488 "2022-06-09T05:18:57Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![carolina\_jauregui](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/carolina_jauregui/32/3483_2.png) [@carolina\_jauregui](https://fenicsproject.discourse.group/u/carolina_jauregui)\
**Post date:** [June 9, 2022, 5:18am UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/1 "2022-06-09T05:18:57Z")

</div>

Hello, I would like to be able to access the adjoint variable (solution of the adjoint system).

I calculate the gradient \frac{dJ}{dm} by using the command `compute_gradient(J, m)`. I’m assuming that the gradient calculation is done using the adjoint approach, so following the notation in the [dolfin-adjoint mathematical background of adjoints](https://www.dolfin-adjoint.org/en/latest/documentation/maths/3-gradients.html#the-adjoint-approach), the adjoint equation is solved (\frac{\partial F(u,m)}{\partial u})^\* \lambda=\frac{\partial J}{\partial u}^\* and the result is used to calculate \frac{dJ}{dm}^\* = -\frac{\partial F}{\partial m}^\* \lambda + \frac{\partial J}{\partial m}^\*. I’d like to be able to get the variable \lambda.

I’ve tried using `J.block_variable.adj_value`, but I’m not sure that I’m using it correctly because I get back a value of 1, when it should be a vector.

In this simple example, I’m using dolfin-adjoint 2019.1.0 and solving a linear elasticity pde.

```auto
from fenics import *
from fenics_adjoint import *
import numpy as np
from ufl import nabla_div

# Define parameters
nelx = 30
nely = 15
nelz = 15
lx = float(nelx)
ly = float(nely)
lz = float(nelz)
E = 1
v = 0.3
mu = Constant(E / (2*(1+v)))
lmbda = Constant(E*v / ((1+v)*(1-2*v)))

# Create a mesh
mesh = BoxMesh.create(
    [Point(0.0, 0.0, 0.0), Point(lx, ly, lz)], # define opposing corners
    [nelx, nely, nelz], # number of elements in each direction
    CellType.Type.hexahedron)
mesh = Mesh(mesh)

# FE function space and functions
V = VectorFunctionSpace(mesh, "CG", 1)
D = FunctionSpace(mesh, "DG", 0)
u = TrialFunction(V)
v = TestFunction(V)
u_sol = Function(V) # function for storing the solution
density = Function(D) # density field

# Bounday condition
class Left(SubDomain):
    def inside(self, x, on_boundary):
        return near(x[0], 0.)
left = Left()
bc = DirichletBC(V, Constant((0., 0., 0.)), left)

# Stress and strain functions
def sigma(u):
    n = len(u) # size of u
    return lmbda*nabla_div(u)*Identity(n) + 2*mu*epsilon(u)

def epsilon(u):
    return 0.5*(nabla_grad(u) + nabla_grad(u).T)

# Define density field
density.vector()[:] = np.ones(nelx*nely*nelz)

# Define forms
f = Constant((0., 0., -1.))
L = dot(f, v) * dx
a = inner(density*sigma(u), nabla_grad(v)) * dx

# Solve
A, b = assemble_system(a, L, bc)
solver = KrylovSolver("cg", "ilu")
solver.solve(A, u_sol.vector(), b)

# Get derivative
J = assemble(action(L, u_sol)) # define compliance
m = Control(density) # define density as the design variable
dJ_dm = compute_gradient(J, m)

# Get adjoint solution
adjoint_sol = J.block_variable.adj_value
print(type(adjoint_sol))
print('adjoint value:', adjoint_sol)

```

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [June 9, 2022, 8:37am UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/2 "2022-06-09T08:37:33Z")

</div>

As each block has an adjoint (not just the solve block), you need to access the correct one.  
I think you want:

```python
print(u_sol.block_variable.adj_value[:])

```

---

<div class="post-metadata">

**Author:** ![carolina\_jauregui](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/carolina_jauregui/32/3483_2.png) [@carolina\_jauregui](https://fenicsproject.discourse.group/u/carolina_jauregui)\
**Post date:** [June 10, 2022, 8:07am UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/3 "2022-06-10T08:07:03Z")

</div>

Thank you so much. I do think that is the adjoint I want, however, I am a bit surprised by the result.

The function J that I’m using is actually self-adjoint, so if you calculate \frac{dJ}{dm} using the adjoint approach you’d find that \lambda=-u where u is the solution to the pde. However, the values that I get from `u_sol.block_variable.adj_value[:]` are quite different than the solution values `u_sol.vector()[:]`. Do you have any idea why this discrepancy would be occuring?

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [June 10, 2022, 9:10am UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/4 "2022-06-10T09:10:21Z")

</div>

Shouldn’t you actually get that \lambda=u  
as J=\int\_\Omega f \cdot u \mathrm{d} x , thus \frac{\partial J}{\partial u}[v]=\int\_{\Omega} f\cdot v~\mathrm{dx} which is equal to the LHS of your original problem?  
To get this, you can add the following code:

```python
tape = get_working_tape()
solve_block = tape.get_blocks()[1]
print(solve_block.adj_sol.vector()[:])

```

---

<div class="post-metadata">

**Author:** ![carolina\_jauregui](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/carolina_jauregui/32/3483_2.png) [@carolina\_jauregui](https://fenicsproject.discourse.group/u/carolina_jauregui)\
**Post date:** [June 10, 2022, 8:35pm UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/5 "2022-06-10T20:35:32Z")

</div>

Yes, you’re right, it should be that \lambda = u. The negative sign was my mistake.

Thank you so much for your help, that last bit of code did the trick.

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [February 26, 2024, 7:46pm UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/7 "2024-02-26T19:46:11Z")

</div>

What version of dolfin, dolfin-adjoint and pyadjoint are you using?

---

<div class="post-metadata">

**Author:** ![Sparrow\_Captain](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/sparrow_captain/32/5614_2.png) [@Sparrow\_Captain](https://fenicsproject.discourse.group/u/Sparrow_Captain)\
**Post date:** [February 26, 2024, 8:00pm UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/8 "2024-02-26T20:00:05Z")

</div>

![image](https://global.discourse-cdn.com/free1/uploads/fenicsproject1/original/2X/7/7519f591af3602fdb4a1ecf4518fdd7bba7d0320.png)

---

<div class="post-metadata">

**Author:** ![Sparrow\_Captain](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/sparrow_captain/32/5614_2.png) [@Sparrow\_Captain](https://fenicsproject.discourse.group/u/Sparrow_Captain)\
**Post date:** [February 26, 2024, 9:02pm UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/9 "2024-02-26T21:02:08Z")

</div>

Maybe I need to install a depricated version of those 3 lib ?

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [February 27, 2024, 7:29am UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/10 "2024-02-27T07:29:52Z")

</div>

I cannot reproduce the issue with `quay.io/fenicsproject/stable:latest` (dolfin 2019.1.0)  
and `dolfin_adjoint` 2023.0.0 (same version for pyadjoint).  
It can also not be reproduced with `ghcr.io/scientificcomputing/fenics:2023-04-21` which is a slightly more up to date version of dolfin than 2019.1.0 (it includes patches up to 21.04.2023).  
Please copy-paste the complete code that you are running into a post with 3x` encapsulation, i.e.

````python
```python
# add code here
```

````

and add the full stack trace in similar encapsulation

````bash
```bash
add stack trace here
```

````

---

<div class="post-metadata">

**Author:** ![Sparrow\_Captain](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/sparrow_captain/32/5614_2.png) [@Sparrow\_Captain](https://fenicsproject.discourse.group/u/Sparrow_Captain)\
**Post date:** [April 3, 2024, 10:07pm UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/12 "2024-04-03T22:07:27Z")

</div>

Hello @dokken,

I have a question on a point you said once.

 ![image](https://global.discourse-cdn.com/free1/uploads/fenicsproject1/original/2X/2/2060e5735d66df635e75894b9f6db1de45ea1401.png)

In the [dolfin-adjoint mathematical background of adjoints](https://www.dolfin-adjoint.org/en/latest/documentation/maths/3-gradients.html#the-adjoint-approach) we can see that **∂J/∂u** is the source term, which is included in the **λ** (the adjoint variable associated with u).

Does this mean that in the adjoint solution, we should see the effect of the sources ?

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [April 4, 2024, 7:11am UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/13 "2024-04-04T07:11:04Z")

</div>

You will see some influence of the sources, as you end up with using a rhs that depend on the point source, but it isn’t equivalent to the rhs being a point source.

---

<div class="post-metadata">

**Author:** ![Sparrow\_Captain](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/sparrow_captain/32/5614_2.png) [@Sparrow\_Captain](https://fenicsproject.discourse.group/u/Sparrow_Captain)\
**Post date:** [April 4, 2024, 11:24am UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/14 "2024-04-04T11:24:32Z")

</div>

> a rhs that depend on the point source

You mean **∂J/∂u** , right ?

> isn’t equivalent to the rhs being a point source

You mean that : **∂J/∂u** ≠ source term **f** , right ?

**Conclusion :** There is no point of asking if we can get the **∂J/∂u** values, since they do not represent the adjoint of the source term **f**.

Thank you for the time.

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [April 4, 2024, 2:00pm UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/15 "2024-04-04T14:00:56Z")

</div>

If your `J` is \int\_\Omega f \cdot u~\mathrm{dx}

then \frac{\partial J}{\partial u}[\delta u]= \int\_\Omega f \cdot \delta u ~ \mathrm{d}x.  
Thus if f is your point-source, then it will be reflected in dJ/du.

---

<div class="post-metadata">

**Author:** ![Sparrow\_Captain](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/sparrow_captain/32/5614_2.png) [@Sparrow\_Captain](https://fenicsproject.discourse.group/u/Sparrow_Captain)\
**Post date:** [April 4, 2024, 10:05pm UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/16 "2024-04-04T22:05:01Z")

</div>

But if **J** doesn’t include **f**? i.e :

![image](https://global.discourse-cdn.com/free1/uploads/fenicsproject1/original/2X/d/d08476d38df466f5b9f4563329992f95eb7b46c1.png)

Then in compute\_gradient, we pass the source term **f** as a control parameter, and this is why we see a reflection of the source term in **∂J/∂u**?

**PS :** Maybe I am confused because **f** in carolina\_jauregui example is a force per unit of volume (elasticity pde), and I am trying to do an analogy with poisson pde problem where **f** is a source term ?

---

<div class="post-metadata">

**Author:** ![dokken](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/dokken/32/1560_2.png) [@dokken](https://fenicsproject.discourse.group/u/dokken)\
**Post date:** [April 5, 2024, 1:56am UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/17 "2024-04-05T01:56:57Z")

</div>

As you correctly summarizes, the problem depends on how you define J. It is easy to compute dJ/du in your case as well, and there you will see that the point sources do not explicitly appear in the variational form.

---

<div class="post-metadata">

**Author:** ![Sparrow\_Captain](https://yyz2.discourse-cdn.com/free1/user_avatar/fenicsproject.discourse.group/sparrow_captain/32/5614_2.png) [@Sparrow\_Captain](https://fenicsproject.discourse.group/u/Sparrow_Captain)\
**Post date:** [April 5, 2024, 2:10am UTC](https://fenicsproject.discourse.group/t/how-to-get-adjoint-solution-from-compute-gradient/8488/18 "2024-04-05T02:10:37Z")

</div>

Thank you, it’s clear for me now 🙂 !
