Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
vo003_LogicalOperations.C
Go to the documentation of this file.
1 /// \file
2 /// \ingroup tutorial_vecops
3 /// \notebook -nodraw
4 /// In this tutorial we learn how the RVec class can be used to
5 /// express logical operations.
6 ///
7 /// \macro_code
8 /// \macro_output
9 ///
10 /// \date May 2018
11 /// \author Danilo Piparo
12 
13 using namespace ROOT::VecOps;
14 
15 void vo003_LogicalOperations()
16 {
17 
18  // Logical operations on RVec instances are made to be very easy to use.
19  RVec<double> v1{1., 2., 3.};
20  RVec<double> v2{3., 2., 1.};
21 
22  // Let's start with operations which act element by element. In this case
23  // we expext a RVec which holds {1. > 3., 2. > 2., 3. > 1.}, i.e. {1, 0, 0}:
24  auto v1_gr_v2 = v1 > v2;
25  std::cout << v1 << " > " << v2 << " = " << v1_gr_v2 << std::endl;
26 
27  // Other logical operations are supported, of course:
28  auto v1_noteq_v2 = v1 != v2;
29  std::cout << v1 << " != " << v2 << " = " << v1_noteq_v2 << std::endl;
30 
31  // All returns true if all of the elements equate to true, return false otherwise.
32  // Any returns true if any of the elements equates to true, return false otherwise.
33  auto all_true = v1 > .5 * v2;
34  std::cout << std::boolalpha;
35  std::cout << "All( " << v1 << " > .5 * " << v2 << " ) = " << All(all_true) << std::endl;
36  std::cout << "Any( " << v1 << " > " << v2 << " ) = " << Any(v1_noteq_v2) << std::endl;
37 
38  // Selections on the RVec contents can be applied with the "square brackets" operator,
39  // which is not only a way to access the content of the RVec.
40  // This operation can change the size of the RVec.
41  RVec<double> v{1., 2., 3., 4., 5.};
42  auto v_filtered = v[v > 3.];
43  std::cout << "v = " << v << ". v[ v > 3. ] = " << v_filtered << std::endl;
44 
45  // This filtering operation can be particularely useful when cleaning collections of
46  // objects coming from HEP events. For example:
47  RVec<double> mu_pt{15., 12., 10.6, 2.3, 4., 3.};
48  RVec<double> mu_eta{1.2, -0.2, 4.2, -5.3, 0.4, -2.};
49 
50  // Suppose the pts of the muons with a pt greater than 10 and eta smaller than 2.1 are needed:
51  auto good_mu_pt = mu_pt[mu_pt > 10 && abs(mu_eta) < 2.1];
52  std::cout << "mu_pt = " << mu_pt << " mu_pt[ mu_pt > 10 && abs(mu_eta) < 2.1] = " << good_mu_pt << std::endl;
53 
54  // Advanced logical operations with masking can be performed with the Where helper.
55  auto masked_mu_pt = Where(abs(mu_eta) < 2., mu_pt, -999.);
56  std::cout << "mu_pt if abs(mu_eta) < 2 else -999 = " << masked_mu_pt << std::endl;
57 }