fun_from_json_xam.py#

View page source

Python from_json: Example and Test#

def from_json_xam() :
   #
   import numpy
   import cppad_py
   import math
   #
   # initialize return variable
   ok = True
   # ---------------------------------------------------------------------
   # AD graph repersentation of f(x) = sin(x) / cos(x)
   #
   # node_1 : x[0]
   # node_2 : sin( x[0] )
   # node_3 : cos( x[0] )
   # node_4 : sin( x[0] ) / cos( x[0] )
   # y[0]   = sin( x[0] ) / cos( x[0] )
   json = '''
      {
         "function_name" : "tangent function",
         "op_define_vec" : [ 3, [
            { "op_code":1, "name":"sin", "n_arg":1 } ,
            { "op_code":2, "name":"cos", "n_arg":1 } ,
            { "op_code":3, "name":"div", "n_arg":2 } ]
         ],
         "n_dynamic_ind"  : 0,
         "n_variable_ind" : 1,
         "constant_vec"   : [ 0, [ ] ],
         "op_usage_vec"   : [ 3, [
            [ 1, 1 ]   ,
            [ 2, 1 ]   ,
            [ 3, 2, 3] ]
         ],
         "dependent_vec" : [ 1, [4] ]
      };
   '''
   # convert json to a fucntion object
   f = cppad_py.d_fun();
   f.from_json(json);
   #
   # compute y = f(x)
   x  = numpy.array( [ 1.0 ] );
   y  = f.forward(0, x);
   #
   # check the function value
   eps99     = 99.0 * numpy.finfo(float).eps
   check     = math.tan(x[0]);
   rel_error = y[0] / check - 1.0;
   ok       &= abs( rel_error ) < eps99;
   #
   return ok