Loading [MathJax]/extensions/tex2jax.js
Logo ROOT   6.10/09
Reference Guide
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
tdf006_ranges.py
Go to the documentation of this file.
1 ## \file
2 ## \ingroup tutorial_tdataframe
3 ## \notebook -nodraw
4 ## This tutorial shows how to express the concept of ranges when working with the TDataFrame.
5 ## \macro_code
6 ##
7 ## \date March 2017
8 ## \author Danilo Piparo
9 
10 import ROOT
11 
12 fill_tree_code = '''
13 void fill_tree(const char *filename, const char *treeName)
14 {
15  TFile f(filename, "RECREATE");
16  TTree t(treeName, treeName);
17  int b1;
18  float b2;
19  t.Branch("b1", &b1);
20  t.Branch("b2", &b2);
21  for (int i = 0; i < 100; ++i) {
22  b1 = i;
23  b2 = i * i;
24  t.Fill();
25  }
26  t.Write();
27  f.Close();
28  return;
29 }
30 '''
31 
32 # We prepare an input tree to run on
33 fileName = "tdf006_ranges_py.root"
34 treeName = "myTree"
35 ROOT.gInterpreter.Declare(fill_tree_code)
36 ROOT.fill_tree(fileName, treeName)
37 
38 # We read the tree from the file and create a TDataFrame.
39 TDF = ROOT.ROOT.Experimental.TDataFrame
40 d = TDF(treeName, fileName)
41 
42 # ## Usage of ranges
43 # Now we'll count some entries using ranges
44 c_all = d.Count()
45 
46 # This is how you can express a range of the first 30 entries
47 d_0_30 = d.Range(0, 30)
48 c_0_30 = d_0_30.Count()
49 
50 # This is how you pick all entries from 15 onwards
51 d_15_end = d.Range(15, 0)
52 c_15_end = d_15_end.Count()
53 
54 # We can use a stride too, in this case we pick an event every 3
55 d_15_end_3 = d.Range(15, 0, 3)
56 c_15_end_3 = d_15_end_3.Count()
57 
58 # The Range is a 1st class citizen in the TDataFrame graph:
59 # not only actions (like Count) but also filters and new columns can be added to it.
60 d_0_50 = d.Range(0, 50)
61 c_0_50_odd_b1 = d_0_50.Filter("1 == b1 % 2").Count()
62 
63 # An important thing to notice is that the counts of a filter are relative to the
64 # number of entries a filter "sees". Therefore, if a Range depends on a filter,
65 # the Range will act on the entries passing the filter only.
66 c_0_3_after_even_b1 = d.Filter("0 == b1 % 2").Range(0, 3).Count()
67 
68 # Ok, time to wrap up: let's print all counts!
69 print("Usage of ranges:")
70 print(" - All entries:", c_all.GetValue())
71 print(" - Entries from 0 to 30:", c_0_30.GetValue())
72 print(" - Entries from 15 onwards:", c_15_end.GetValue())
73 print(" - Entries from 15 onwards in steps of 3:", c_15_end_3.GetValue())
74 print(" - Entries from 0 to 50, odd only:", c_0_50_odd_b1.GetValue())
75 print(" - First three entries of all even entries:", c_0_3_after_even_b1.GetValue())
Ta Range(0, 0, 1, 1)