[fenics-support] Error involving dolfin.cpp.mesh.Mesh' object has no attribute '_ad_will_add_as_dependency'

Hello,

I am currently working in Fenics and trying to set up the time dependency to my heat equation.

I am having some errors involving AttributeError and the dolfin.cpp.mesh.Mesh. I have my code along with the errors below.

Thanks

Code:

"""
FEniCS tutorial demo program: Diffusion of a Gaussian hill.

u'= Laplace(u) + f  in a square domain
u = u_D             on the boundary
u = u_0             at t = 0

u_D = f = 0

The initial condition u_0 is chosen as a Gaussian hill.
"""

from dolfin import *
from mshr import *
from fenics import *
import time
from dolfin import *
from matplotlib.pyplot import show
from dolfin_adjoint import *
from firedrake import *



# Define variational problem
u = TrialFunction(V)
v = TestFunction(V)
f = Constant(0)

# Solution at the previous time level
u_old = Function(V)


T_initial = 0.0 # initial time
T_final = 2 # final time
num_steps = 50     # number of time steps
dt = ( T_final - T_initial ) / num_steps # time step size


#Making a cylindrical geometry 10 cm radius and 15 cm height in S.I

cylinder = Cylinder(Point(0, 0, -7.5), Point(0, 0, 7.5), 5, 5)
domain = cylinder


u_n = interpolate(u_0, V)

# Making Mesh ( THe value corresponds to the mesh density)
mesh = generate_mesh(domain, 15) # generates 3D model of the cylindrical geometry in x, y, and z         
axes. 
V = FunctionSpace(mesh, 'P', 1)


# Define boundary condition
def boundary(x, on_boundary):
return on_boundary

# Boundary Conditions 
bc = DirichletBC(V, Constant(0), boundary)

# Definining the intial condition 300 K
#u_0 = Constant('300')
u_0 = Expression('exp(-a*pow(x[0], 2) - a*pow(x[1], 2))',
         degree=2, a=5)
g = u_0

# Formula 
F = u*v*dx + dt*dot(grad(u), grad(v))*dx - (u_n + dt*f)*v*dx
a, L = lhs(F), rhs(F)

#time-dependent forward problem.

fwd_timer = Timer("Forward run")
fwd_time = 0

u_pvd = File("output/u.pvd")

# Execute the time loop
u_old.assign(g, annotate=True)
while T_initial <= T_final:
T_initial += num_steps

fwd_timer.start()
solve(F == 0, u)
u_old.assign(u)
fwd_time += fwd_timer.stop()

u_pvd << u

J = assemble(inner(u, u) * dx)
m = Control(g)

adj_timer = Timer("Adjoint run")
dJdm = compute_gradient(J, m, options={"riesz_representation": "L2"})
adj_time = adj_timer.stop()
# Create VTK file for saving solution
vtkfile = File('heat_gaussian/solution.pvd')

File("output/dJdm.pvd") << dJdm
plot(dJdm, title="Sensitivity of ||u(t=%f)||_L2 with respect to u(t=0)." % t)
show()

print("Forward time: ", fwd_time)
print("Adjoint time: ", adj_time)
print("Adjoint to forward runtime ratio: ", adj_time / fwd_time)


# Time-stepping
u = Function(V)
T_inital = 0
for n in range(num_steps):

# Update current time
T_inital += dt

# Compute solution
solve(a == L, u, bc)

# Save to file and plot solution
vtkfile << (u, T_inital)
plot(u)

# Update previous solution
u_n.assign(u)

import matplotlib.pyplot as plt

plt.show()
 
 AttributeError                            Traceback (most recent call last)
<ipython-input-26-dd82e33d996a> in <module>
 80 
 81     fwd_timer.start()
---> 82     solve(F == 0, u)
 83     u_old.assign(u)
 84     fwd_time += fwd_timer.stop()

 ~/.local/lib/python3.8/site-packages/fenics_adjoint/solving.py in solve(*args, **kwargs)
 46         sb_kwargs = SolveBlock.pop_kwargs(kwargs)
 47         sb_kwargs.update(kwargs)
 ---> 48         block = SolveBlock(*args, **sb_kwargs)
 49         tape.add_block(block)
 50 

 ~/.local/lib/python3.8/site-packages/fenics_adjoint/solving.py in __init__(self, *args, **kwargs)
 80         else:
 81             mesh = self.lhs.ufl_domain()
 ---> 82         self.add_dependency(mesh)
 83 
 84     def __str__(self):

~/.local/lib/python3.8/site-packages/pyadjoint/block.py in add_dependency(self, dep, no_duplicates)
 49         """
 50         if not no_duplicates or dep.block_variable not in self._dependencies:
 ---> 51             dep._ad_will_add_as_dependency()
 52             self._dependencies.append(dep.block_variable)
 53 

AttributeError: 'dolfin.cpp.mesh.Mesh' object has no attribute '_ad_will_add_as_dependency'

Here you are combining alot of different modules, dolfin, dolfin_adjoint and firedrake. I would start with removing the import of firedrake and dolfin_adjoint, along with the lines

As this is related to optimization of a functional, Which is not in your interest.

1 Like

Hi, thanks for the suggestions. I went ahead made the edits and it’s given me this error.


TypeError                                 Traceback (most recent call last)
<ipython-input-63-689c861eb28c> in <module>
 74 
 75 # Execute the time loop
 ---> 76 u_old.assign(g, annotate=True)
 77 while T_initial <= T_final:
 78     T_initial += num_steps

TypeError: assign() got an unexpected keyword argument 'annotate'

Remove the annotate keyword argument.

1 Like

I am getting a runtime error. Any ideas? Tx

RuntimeError                              Traceback (most recent call last)
<ipython-input-70-d160ba6b5624> in <module>
 79 
 80 fwd_timer.start()
---> 81 solve(F == 0, u)
 82 u_old.assign(u)
 83 fwd_time += fwd_timer.stop()

/usr/lib/python3/dist-packages/dolfin/fem/solving.py in solve(*args, **kwargs)
218     # tolerance)
219     elif isinstance(args[0], ufl.classes.Equation):
--> 220         _solve_varproblem(*args, **kwargs)
221 
222     # Default case, just call the wrapped C++ solve function

/usr/lib/python3/dist-packages/dolfin/fem/solving.py in _solve_varproblem(*args, **kwargs)
233     # Extract arguments
234     eq, u, bcs, J, tol, M, form_compiler_parameters, solver_parameters \
--> 235         = _extract_args(*args, **kwargs)
236 
237     # Solve linear variational problem

/usr/lib/python3/dist-packages/dolfin/fem/solving.py in _extract_args(*args, **kwargs)
333 
334     # Extract solution function
--> 335     u = _extract_u(args[1])
336 
337     # Extract boundary conditions

/usr/lib/python3/dist-packages/dolfin/fem/solving.py in _extract_u(u)
383         return u
384 
--> 385     raise RuntimeError("Expecting second argument to be a Function.")
386     # cpp.dolfin_error("solving.py",
387     #                      "solve variational problem",

RuntimeError: Expecting second argument to be a Function.

u should be a function not a TrialFunction

When you mean remove the annotate keyword is this what you meant ? u_old.assign(g, True) or u_old.assign(g) ?

I meant this. The error message is quite straightforward

I did that and this is what I am getting.

AttributeError                            Traceback (most recent call last)
<ipython-input-85-ecafad3c0014> in <module>
 73 
 74 # Execute the time loop
---> 75 u_old.assign(g)
 76 while T_initial <= T_final:
 77     T_initial += num_steps

AttributeError: 'Argument' object has no attribute 'assign'

Please supply the full code , encapsulated with ``` for us to be of any more help.

Hey Dokken i needed to find the time independent not the time dependent this was a mistake.

I have the same error, after all the changes the following appears:

AttributeError: ‘Function’ object has no attribute ‘block_variable’

Did you manage to solve your problem?

Please supply a minimal code example.