\(\newcommand{\B}[1]{ {\bf #1} }\) \(\newcommand{\R}[1]{ {\rm #1} }\)
cppad_py_gradient.py¶
View page sourceCalculate Gradient Using cppad_py¶
Syntax¶
cmpad.cppad_py.gradient ( algo )setup ( option )Purpose¶
This uses cppad_py to implement a py_fun_obj that computes the gradient of the last component of values computed by algo .
algo¶
This is a py_fun_obj where the
input and output vectors have type numpy.array with cppad_py.a_double elements .
The last range space component, computed by algo ,
defines the scalar function that the gradient is for.
grad¶
This is a py_fun_obj where the input and output vectors
have elements of type float .
x¶
This is a numpy vector of float with length option [ 'n_arg' ] .
It is the argument value at which to compute the gradient.
g¶
This is a numpy vector of float with length option [ 'n_arg' ] .
It is the value of the gradient ad x .
Example¶
The file xam_grad_cppad_py.py contains an example and test using this class.
Source Code¶
#
# imports
import numpy
import cppad_py
#
# gradient
class gradient :
#
def __init__(self, algo) :
self.algo = algo
self.option = None
#
def option(self) :
return self.optiion
#
def domain(self) :
return self.option['n_arg']
#
def range(self) :
return self.option['n_arg']
#
#
def setup(self, option) :
assert type(option) == dict
assert 'n_arg' in option
#
# self.option
self.option = option
#
# self.algo
self.algo.setup(option)
#
# n
n = self.algo.domain()
#
# self.w
self.w = numpy.empty( (1, 1), dtype=float )
self.w[0, 0] = 1.0
#
# self.tape
x = numpy.zeros(n, dtype=float)
ay = numpy.empty(1, dtype=cppad_py.a_double)
ax = cppad_py.independent(x)
az = self.algo(ax)
ay[0] = az[-1]
self.tape = cppad_py.d_fun(ax, ay)
if not option['time_setup'] :
self.tape.optimize()
#
# call
def __call__(self, x) :
self.tape.forward(0, x)
g = self.tape.reverse(1, self.w)
return g