Why to write adjoint code?
When you write code for variable objects in ADMB, all the derivatives are calculated for you. To accomplish this, ADMB must save derivative information for variable objects, which can take a lot of memory and be time consuming for functions that are called many times. The purpose of writing adjoint code is to reduce the amount of derivative information that must be calculated and stored in order to speed up the process.
Approach for simple functions
Chapter 13 of the ADMB manual describes how to write and debug adjoint code for simple functions that take between 1 and 4 independent variables. The .tpl files are included below.
Structured approach for more complex functions
For more complicated functions the previous approach becomes untenable and a more structured approach to calculate the derivatives is taken in the following example. Notice that to calculate the derivatives, every line of code in the function is repeated in the opposite order and the corresponding derivatives are calculated.
General adjoint code
In the previous examples the adjoint code has been used for a simple function which has from 1 to 4 independent variables. When functions can take any number of independent variables and return any number of dependent variables a more general approach is required. Steve Martell provided an example of writing adjoint code to numerically solve the Baranov catch equation and both its .tpl and its documentation are included below.