My colleague Marc Henrard has been writing about Algorithmic Differentiation (AD) for some time now. Any formula, no matter how complex, can be split into a list of simple mathematical operations that a computer understands, and (importantly) have known, analytic derivatives. AD is nothing more than a system for bookkeeping while applying the chain rule. We’ve implemented AD in the OpenGamma Analytics Library manually and seen considerable performance gains as a result.

Soon after Marc introduced me to AD, I started thinking about the possibility of doing AD automatically. The result of this thought process is Deriva, a Clojure implementation of AD (with a DSL for Java), designed to automate the tedious process of coding AD manually, which gets hard and time consuming with higher-order derivatives. I haven’t been able to find another, satisfactory Java-based solution for multi-dimensional AD.

### Quick background on AD

According to the Wikipedia definition, Algorithmic (or Automatic) Differentiation is

"[…] a set of techniques to numerically evaluate the derivative of a function specified by a computer program. Automatic differentiation is not:

- Symbolic differentiation, or
- Numerical differentiation (the method of finite differences).
These classical methods run into problems: symbolic differentiation leads to inefficient code (unless carefully done) and faces the difficulty of converting a computer program into a single expression, while numerical differentiation can introduce round-off errors in the discretization process and cancellation. Both classical methods have problems with calculating higher derivatives, where the complexity and errors increase. Finally, both classical methods are slow at computing the partial derivatives of a function with respect to many inputs, as is needed for gradient-based optimization algorithms. Automatic differentiation solves all of these problems."

### Meet Deriva

Deriva is a Clojure implementation of AD with a DSL for Java. The client of the library defines symbolic expressions using either regular Lisp s-forms or the Java builder pattern. Beside closed-form expressions, Deriva provides support for non-analytic functions (case functions) and for incorporating regular Java code into its symbolic expression trees.

### Installation

#### Leiningen

Add the following to your `:dependencies`

:

```
[deriva "0.1.0-SNAPSHOT"]
```

#### Maven

```
<dependency>
<groupId>deriva</groupId>
<artifactId>deriva</artifactId>
<version>0.1.0-SNAPSHOT</version>
</dependency>
```

The jar is hosted in a Clojars.org repository, so if you haven't already added it to your Maven repositories, you can do it by adding the following section to your pom.xml inside the `<repositories>`

tag:

```
<repository>
<id>clojars</id>
<url>https://clojars.org/repo/</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
```

#### GitHub

### Some examples

#### Simple example - sine function

To use the Deriva Java DSL simply add the following lines to your code:

```
import com.lambder.deriva.*;
import static com.lambder.deriva.Deriva.*;
```

Now we can define sine expression, simply as:

```
Expression expr = sin('x');
```

Such expressions can be used as sub-expressions to build more complex mathematical formulae. We’ll look at a more complex example later on. Now let’s see how we can use an Expression. To execute the expression we need to create a function from it:

```
Function fun = expr.function('x');
```

Here we see that we use the `'x'`

symbol (represented here by a single character, but regular Strings will do as well) to define mapping of symbols to the arguments of a function. Placing a symbol in a given place indicates which argument it will map to. It will become more clear, when we see function invocation:

```
double result = fun.execute(Math.PI / 6);
```

Here `execute`

takes `double`

parameters (in our case one such parameter) and substitutes them into the underlying expression in accordance with the mapping defined when we called `function`

. So in this case it replaces all occurrences of [ x ] with [ pi/6 ], making our original expression render [sin(pi/6)].

Now to derivatives. In order to calculate a derivative of a given expression in respect to a given symbol, in Java we do:

```
Expression expr_d_1 = d(expr, 'x');
```

We can then use the expression, representing first order derivative on sine function [ ∂/(∂x) sin(x) ] , to obtain its value at point [t] by:

```
double slope = expr_d_1.function('x').execute(t);
```

#### More fun - gradients of multivariate functions

The real benefits of algorithmic differentiation come when we work with multivariate functions. The code that calculates a gradient - that is, a vector of partial derivatives in respect to all variables - requires fewer operations than calculating these partial derivatives separately.

As an example let's take [ sin(x^2 y^2) RR^2 => RR ] function.

To get its gradient we do:

```
Expression expr = sin(mul(sq('x'), sq('y')));
Function1D fun = d(expr, 'x', 'y').function('x', 'y'); // (1)
double[] result = fun.execute(1.0, 2.0);
System.out.println(Arrays.toString(result));
```

which prints:

```
[-5.2291489669088955, -2.6145744834544478]
```

The result is an array of doubles of length n+1, whose elements are values of corresponding to partial derivatives in the order defined in `function`

(1) call.

The order of partial derivatives is unlimited, and we can achieve this by nesting the derivative operator, e.g. d( d( d(expr,'x')'x')'x'). For convenience, there are aliases of 2nd, 3rd, and 4th order e.g. dd( exp, 'x') , ddd( exp, 'x'), dddd( exp, 'x').

#### How does it work?

Deriva doesn’t follow directly any of the classic methods described in the Wikipedia article^{1}, but rather it is a combination of symbolic transformation, operations generation and eventually bytecode generation. The symbolic transformation simply uses differentiation rules to transform one expression into another - for example to transform [ ∂/(∂x) sin(x) ] into [ cos(x) ]. One can even add such custom rules on an application level at runtime.

The second phase, generation of elementary operations, flattens the expression tree (or trees in case of gradient) into one list of variable substitutions. During that operation the index of all sub-expressions is used in order to eliminate using the same expressions twice. The final phase uses another set of rules, which define a given mathematical operation will be reflected as a working bytecode. E.g. operation `sin('x')`

is defined as `Math.sin(x)`

.

The workings of Deriva can be observed with the help of `describe`

method:

```
Expression expr = sin(mul(sq('x'), sq('y')));
System.out.println(expr.describe());
```

which displays:

```
Expression:
(sin (mul (sq x) (sq y)))
gets turned into:
(sin (* (sq x) (sq y)))
and into:
final double G__6 = y; // y
final double G__5 = sq( G__6 ); // (sq y)
final double G__4 = x; // x
final double G__3 = sq( G__4 ); // (sq x)
final double G__2 = G__3 * G__5; // (* (sq x) (sq y))
final double G__1 = sin( G__2 ); // (sin (* (sq x) (sq y)))
```

Here we see that the code which calculates [ sin(x^2 y^2) ] requires, as one would expect, three multiplications and one sin function call.

The workings of the gradient generation can be shown as:

Here we see 2 trigonometric function calls and 9 multiplications, as opposed to 3 trigonometric function calls and 17 multiplications which one could expect from calculating: [ { sin(x^2 y^2) , 2 x y^2 cos(x^2 y^2), 2 x^2 y cos(x^2 y^2) } ].

This effect is more profound as the expressions get more complicated or the number of dimensions grows.

#### How about non-analytic functions?

Some functions, despite having no analytical definition, are still differentiable at whole domain. As an example consider the [ f(x)={(e^(-1/x),if x>0),(text{0},if x<=0):} ] which looks like:

For this purpose Deriva offers a special `when`

expression, accompanied by logic operators `and`

, `or`

, `not`

, `gt`

, `lt`

and `eq`

. Let’s see it in action:

```
Function fun = when(
gt('x', 0), // when x is greather than 0
exp( // e^(-1/x)
neg(
div(1, 'x'))),
0) // otherwise 0
.function('x');
```

#### How this stuff looks like in Clojure

The namespace we are using is `com.lambder.deriva.core`

```
(use 'com.lambder.deriva.core)
```

##### Simple expression:

```
(def f (function (sin x)))
(f 1) ;=> 0.8414709848078965
(def g (function (∂ (sin x) x))
(g 1) ;=> 0.5403023058681398
```

#### More involved example - Black model^{2} with greeks

Black model as defined on Wikipedia:

call price: %% c = e^(-rT)(FN(d1)-KN(d2)) %%

put price: %% p = e^(-rT)(FN(-d2)-KN(-d1)) %%

where

[ d_1 = (ln(F//K)+(sigma^2//2)T)/(sigma*sqrt(T)) ]

[ d_2 = (ln(F//K)-(sigma^2//2)T)/(sigma*sqrt(T)) ]

[ N(x) = int_-oo^x (1/(2sqrt(pi))e^-(t^2/2) ) dt ~~ 1/(e^(-0.07056 * x^3 -1.5976*x) + 1) ]

and the Clojure equivalent: