13.2.3. Macro “howtoLoadFunction.py”

13.2.3.1. Objective

The goal of this macro is only to show how to load a C++ function in python as this could be of use for instance when producing a surrogate model (all of them can be exported in C++ and even though the recommended way to handle these is through the Uranie classes, it might happen that one wants to put one’s hand on it).

Our example is taken from the UserFunction.C file provided with the Uranie sources (look for it in the the "$URANIESYS/share/uranie/macros" folder). The operation function only compute the product, ratio, sum and difference between two provided inputs (just checking for consistency that the denominator of the ratio is not equal to zero). The code is shown here for illustration purpose.

void operation(double *x, Double_t *y)
{
  Double_t x1 = x[0], x2 = x[1];
  // product
  y[0] = x1 * x2;
  // divide
  y[1] = ((x2!=0) ? x1 / x2 : -999);
  // sum
  y[2] = x1 + x2;
  // diff
  y[3] = x1 - x2;  
}

13.2.3.2. Macro Uranie

"""
Example of C++ function in python
"""
import numpy as np
import ROOT

# Loading a function
ROOT.gROOT.LoadMacro("UserFunctions.C")

# Preparing inputs and outputs
inp = np.array([1.2, 0.8])  # input values
out = np.zeros(4)  # output values initialise with 4 zeros

# Call the method, through the ROOT interface
ROOT.operation(inp, out)

# Print the result
print("Results are")
print(out)

The first block simply loads the input file UserFunctions.C through the ROOT’s interface.

ROOT.gROOT.LoadMacro("UserFunctions.C")

Once done, the input and output np.array object are created, the former with provided values to be tested, the latter only filled with zeros. Calling the function is simply done by providing input and output arrays to the function operator that is now stored within ROOT by doing:

ROOT.operation(inp, out)

The output of this macro is shown in Console.

13.2.3.3. Console

Results are
[0.96 1.5  2.   0.4 ]