Logo ROOT   6.14/05
Reference Guide
df012_DefinesAndFiltersAsStrings.py
Go to the documentation of this file.
1 ## \file
2 ## \ingroup tutorial_dataframe
3 ## \notebook -nodraw
4 ##
5 ## This tutorial illustrates how to use jit-compiling features of RDataFrame
6 ## to define data using C++ code in a Python script
7 ##
8 ## \macro_code
9 ##
10 ## \date October 2017
11 ## \author Guilherme Amadio
12 
13 import ROOT
14 
15 ## We will inefficiently calculate an approximation of pi by generating
16 ## some data and doing very simple filtering and analysis on it.
17 
18 ## We start by creating an empty dataframe where we will insert 10 million
19 ## random points in a square of side 2.0 (that is, with an inscribed unit
20 ## circle).
21 
22 npoints = 10000000
23 tdf = ROOT.ROOT.RDataFrame(npoints)
24 
25 ## Define what data we want inside the dataframe. We do not need to define p
26 ## as an array, but we do it here to demonstrate how to use jitting with RDataFrame
27 
28 pidf = tdf.Define("x", "gRandom->Uniform(-1.0, 1.0)") \
29  .Define("y", "gRandom->Uniform(-1.0, 1.0)") \
30  .Define("p", "std::array<double, 2> v{x, y}; return v;") \
31  .Define("r", "double r2 = 0.0; for (auto&& w : p) r2 += w*w; return sqrt(r2);")
32 
33 ## Now we have a dataframe with columns x, y, p (which is a point based on x
34 ## and y), and the radius r = sqrt(x*x + y*y). In order to approximate pi, we
35 ## need to know how many of our data points fall inside the circle of radius
36 ## one compared with the total number of points. The ratio of the areas is
37 ##
38 ## A_circle / A_square = pi r*r / l * l, where r = 1.0, and l = 2.0
39 ##
40 ## Therefore, we can approximate pi with 4 times the number of points inside
41 ## the unit circle over the total number of points:
42 
43 incircle = pidf.Filter("r <= 1.0").Count().GetValue()
44 
45 pi_approx = 4.0 * incircle / npoints
46 
47 print("pi is approximately equal to %g" % (pi_approx))