DAS  3.0
Das Analysis System
Darwin::Tools Namespace Reference

Classes

class  Looper
 
class  MetaInfo
 
class  Options
 
class  UserInfo
 

Typedefs

typedef std::pair< unsigned, unsigned > Slice
 

Enumerations

enum  {
  none = 0b000000, config = 0b000001, split = 0b000010, fill = 0b000100,
  Friend = 0b001100, syst = 0b010000, verbose = 0b100000
}
 
enum  {
  none = 0b000000, config = 0b000001, split = 0b000010, fill = 0b000100,
  Friend = 0b001100, syst = 0b010000, verbose = 0b100000
}
 

Functions

optional< bool > getBool (string s)
 
template<typename ... Args>
void FromPT2MetaInfo (const pt::ptree &elements, const MetaInfo &metainfo, ostream &cout, Args... args)
 
void forceMetaInfo (const fs::path &input, const fs::path &output, const int steering)
 
int getMetaInfo (vector< fs::path > inputs, const fs::path &output)
 
int initMetaInfo (const pt::ptree &config)
 
template<int thousand = 1024>
const char * GetHumanReadableSize (long double size)
 
Long64_t GetSize (TBranch *br)
 
Long64_t loopBranches (TObjArray *branches, size_t factor, int nIndent=0)
 
void printBranches (vector< fs::path > inputs)
 
void printDarwinSoftwareVersion ()
 
void printEntries (vector< fs::path > inputs)
 
void PrintCloseFriend (TList *friends, const int steering, string offset="")
 
void printFriends (vector< fs::path > inputs, const int steering)
 
void printHist (vector< fs::path > inputs, const pt::ptree &config)
 
int printMetaInfo (vector< fs::path > inputs, const pt::ptree &config)
 
std::unique_ptr< TFile > GetOutput (std::filesystem::path output, const char *name)
 
void StandardInit ()
 
std::vector< std::filesystem::path > GetROOTfiles (std::vector< std::filesystem::path > inputs)
 
std::unique_ptr< TChain > GetChain (std::vector< std::filesystem::path > inputs, const char *name="events")
 
template<typename THX = TH1>
std::unique_ptr< THX > GetHist (std::vector< std::filesystem::path > inputs, const char *name="h")
 
std::string GetFirstTreeLocation (const std::filesystem::path &input)
 
std::unique_ptr< TTree > NewTree (const std::unique_ptr< TChain > &chain, const bool makeFriend, const char *thisFunc)
 
std::ostream & operator<< (std::ostream &Stream, const Darwin::Tools::Slice &slice)
 
static std::ostream dev_null (nullptr)
 
std::vector< const char * > tokenize (const char *str)
 
static std::ostream dev_null (nullptr)
 

Detailed Description

Classes and functions related to the framework.

Typedef Documentation

◆ Slice

typedef std::pair< unsigned, unsigned > Slice

current slice (>=0) / total number of slices (>0)

Enumeration Type Documentation

◆ anonymous enum

anonymous enum
Enumerator
none 

default (for simple executables)

config 

activate -c option to provide config file

split 

activate -k and -j to define slice

fill 

activate -f to fill the tree

Friend 

activate -F to only fill the new branches

syst 

activate -s to systematic uncertainties

verbose 

bit for debug mode (-v is always available)

24  {
25  none = 0b000000,
26  config = 0b000001,
27  split = 0b000010,
28  fill = 0b000100,
29  Friend = 0b001100,
30  syst = 0b010000,
31  verbose = 0b100000
32 };

◆ anonymous enum

anonymous enum
Enumerator
none 

default (for simple executables)

config 

activate -c option to provide config file

split 

activate -k and -j to define slice

fill 

activate -f to fill the tree

Friend 

activate -F to only fill the new branches

syst 

activate -s to systematic uncertainties

verbose 

bit for debug mode (-v is always available)

24  {
25  none = 0b000000,
26  config = 0b000001,
27  split = 0b000010,
28  fill = 0b000100,
29  Friend = 0b001100,
30  syst = 0b010000,
31  verbose = 0b100000
32 };

Function Documentation

◆ dev_null() [1/2]

static std::ostream Darwin::Tools::dev_null ( nullptr  )
static

to redirect output stream to nowhere

◆ dev_null() [2/2]

static std::ostream Darwin::Tools::dev_null ( nullptr  )
static

to redirect output stream to nowhere

◆ forceMetaInfo()

void Darwin::Tools::forceMetaInfo ( const fs::path &  input,
const fs::path &  output,
const int  steering 
)

Force content of all TTree::UserInfo() and TList found in the topmost directory of the root file. This method is to be used as a last resort, and certainly not in the context of reproducible results.

Parameters
inputinput config file (INFO, JSON, XML)
outputROOT file
steeringparameters obtained from explicit options
96 {
97  pt::ptree config;
98  if (input.extension() == ".json")
99  pt::read_json(input, config);
100  else if (input.extension() == ".xml")
101  pt::read_xml(input, config);
102  else
103  pt::read_info(input, config);
104 
105  const string location = GetFirstTreeLocation(output);
106  unique_ptr<TFile> fOut(TFile::Open(output.c_str(), "UPDATE"));
107  auto t = unique_ptr<TTree>(fOut->Get<TTree>(location.c_str()));
108  if (!t)
109  BOOST_THROW_EXCEPTION(DE::BadInput("The tree can't be found in this file.", fOut));
110 
111  t->GetUserInfo()->Clear();
112 
113  static auto& cout = (steering & verbose) == verbose ? ::cout : dev_null;
114  MetaInfo metainfo(t, false);
115  FromPT2MetaInfo(config, metainfo, cout);
116  metainfo.Set<bool>("git", "reproducible", false);
117  if (metainfo.Find("history")) {
118  TList * history = metainfo.List("history");
119  metainfo.List()->Remove(history);
120  }
121  t->Write();
122 }

◆ FromPT2MetaInfo()

void Darwin::Tools::FromPT2MetaInfo ( const pt::ptree &  elements,
const MetaInfo metainfo,
ostream &  cout,
Args...  args 
)

Sets whatever is in the input config file into the metainfo of a TTree.

Parameters
elementsfrom config file
metainfotarget metainfo (will be modified)
coutoverrides standard output
argskey chain
55 {
56  if constexpr (sizeof...(Args) < 10) // max depth
57  for (const auto& element: elements) {
58  const char * key = element.first.c_str();
59  const auto& value = element.second.get_value<string>();
60 
61  cout << bold;
62  if constexpr (sizeof...(Args) > 0)
63  (cout << ... << args) << ' ';
64  cout << def << key << " \"" << value << '"' << endl;
65 
66  FromPT2MetaInfo(element.second, metainfo, cout, args..., key);
67 
68  auto match = [&value](const string& reg) {
69  return regex_match( value, regex(reg) );
70  };
71  if (auto isBool = getBool(value); isBool)
72  metainfo.Set<bool>(args..., key, *isBool);
73  else if (match("-?[0-9]+")) // integer
74  metainfo.Set<int>(args..., key, stoi(value));
75  else if (match("-?[0-9]+([\\.][0-9]+)?")) // floating number
76  metainfo.Set<float>(args..., key, stof(value));
77  else if (element.second.size() == 0) { // string
78  if (value.empty()) {
79  if constexpr (sizeof...(Args) > 0)
80  metainfo.Set<string>(args..., string(key));
81  }
82  else
83  metainfo.Set<string>(args..., key, value);
84  }
85  }
86 }

◆ getBool()

optional<bool> Darwin::Tools::getBool ( string  s)

Translates a string into a boolean if possible.

33 {
34  al::to_lower(s);
35  al::trim(s);
36  static const array<string,4> trueStr {"true", "on", "ktrue", "yes"},
37  falseStr {"false", "off", "kfalse", "no"};
38  if (auto it = find(trueStr.begin(), trueStr.end(), s);
39  it != trueStr.end())
40  return make_optional<bool>(true);
41  if (auto it = find(falseStr.begin(), falseStr.end(), s);
42  it != falseStr.end())
43  return make_optional<bool>(false);
44  return {};
45 }

◆ GetChain()

std::unique_ptr< TChain > GetChain ( std::vector< std::filesystem::path >  inputs,
const char *  name = "events" 
)

Load chain from a list of files.

internal path to TTree

Parameters
inputsROOT files or directories
nameinternal path to `TTree`
69 {
70  using namespace std;
71  namespace fs = filesystem;
72 
73  unique_ptr<TChain> chain = make_unique<TChain>(name);
75  for (auto const& input: inputs) {
76  int code = chain->Add(input.c_str(), 0); // "If nentries<=0 and wildcarding is not used,
77  // returns 1 if the file exists and contains
78  // the correct tree and 0 otherwise"
79  if (code == 1) continue; // i.e. the tree was found successfully
80  auto fIn = make_unique<TFile>(input.c_str(), "READ");
81  namespace DE = Darwin::Exceptions;
82  BOOST_THROW_EXCEPTION(DE::BadInput("The tree cannot be "
83  "found in (one of) the input file(s).", fIn));
84  }
85  if (chain->GetEntries() == 0)
86  BOOST_THROW_EXCEPTION(std::invalid_argument("Empty trees in input!"));
87  return chain;
88 }

◆ GetFirstTreeLocation()

std::string GetFirstTreeLocation ( const std::filesystem::path &  input)

one input ROOT file

Look for a tree in the input file (stop at the first found one).

NOTE: in principle, we take the risk of not looking at the same TTree as all other executables, but this is unlikely in practice

Parameters
inputone input ROOT file
92 {
93  using namespace std;
94  namespace fs = filesystem;
95  namespace DE = Darwin::Exceptions;
96 
97  unique_ptr<TFile> fIn(TFile::Open(input.c_str(), "READ"));
98  if (!fIn || !fIn->IsOpen() || fIn->IsZombie() || !fs::exists(input))
99  BOOST_THROW_EXCEPTION( fs::filesystem_error("Failed to open input file",
100  input, make_error_code(std::errc::io_error)) );
101 
102  function<string(TDirectory *)> loop;
103  loop = [&loop](TDirectory * d) -> string {
104 
105  // look for a `TTree` in the current `TDirectory`
106  for (const auto&& obj: *(d->GetListOfKeys())) {
107  auto const key = dynamic_cast<TKey*>(obj);
108  if (dynamic_cast<TTree *>(key->ReadObj()) == nullptr) continue;
109  return obj->GetName();
110  }
111 
112  // if not found, check all sub`TDirectory`s
113  for (const auto&& obj: *(d->GetListOfKeys())) {
114  auto const key = dynamic_cast<TKey*>(obj);
115  auto dd = dynamic_cast<TDirectory *>(key->ReadObj());
116  if (dd == nullptr) continue;
117  if (auto location = loop(dd); !location.empty())
118  return Form("%s/%s", dd->GetName(), location.c_str());
119  }
120 
121  // if nothing was found at this stage, return empty string
122  return string();
123  };
124  string location = loop(fIn.get());
125  if (location.empty())
126  BOOST_THROW_EXCEPTION( DE::BadInput("No `TTree` could be found in the input file.", fIn) );
127  return location;
128 }

◆ GetHist()

std::unique_ptr< THX > GetHist ( std::vector< std::filesystem::path >  inputs,
const char *  name = "h" 
)
inline

Load a histogram from a list of files.

Parameters
inputsROOT files or directories
nameinternal path to ROOT histogram
48 {
49  using namespace std;
50  namespace fs = filesystem;
51 
52  unique_ptr<THX> sum;
54  for (auto const& input: inputs) {
55  auto fIn = make_unique<TFile>(input.c_str(), "READ");
56  // TODO: what if the file had already been opened?? will it be closed prematurely?
57  unique_ptr<THX> h(fIn->Get<THX>(name));
58  if (!h) {
59  namespace DE = Darwin::Exceptions;
60  BOOST_THROW_EXCEPTION(DE::BadInput(Form("`%s` cannot be found in (one of) the "
61  " file(s).", name), fIn));
62  }
63  if (sum)
64  sum->Add(h.get());
65  else {
66  sum = move(h);
67  sum->SetDirectory(nullptr);
68  }
69  }
70  return sum;
71 }

◆ GetHumanReadableSize()

const char* Darwin::Tools::GetHumanReadableSize ( long double  size)

From an absolute number of bytes to human readable size in KB, MB, GB, etc.

< https://en.wikipedia.org/wiki/Byte

Parameters
sizesize in bytes
30 {
31  static const array levels = {'\0', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'};
32  auto level = levels.begin();
33  while (level != prev(levels.end())
34  && size > static_cast<long double>(thousand)) {
35  ++level;
36  size /= thousand;
37  }
38  return Form("%.0Lf%c", size, *level);
39 }

◆ getMetaInfo()

int Darwin::Tools::getMetaInfo ( vector< fs::path >  inputs,
const fs::path &  output 
)

Print content of the first TTree::UserInfo() found in the root file.

Parameters
inputsinput ROOT files
outputoutput config file (INFO, JSON, XML)
28 {
29  const size_t N = inputs.size();
30  hash<UserInfo> Hash;
31  vector<size_t> hashes(N,0);
32 
34  const string location = GetFirstTreeLocation(inputs.front());
35 
36  // looping over files
37  for (size_t i = 0; i < N; ++i) {
38 
39  // opening file
40  unique_ptr<TFile> fIn(TFile::Open(inputs[i].c_str(), "READ"));
41  if (fIn->IsZombie())
42  BOOST_THROW_EXCEPTION(DE::BadInput("Can't open the file.", fIn));
43 
44  // fetch tree
45  auto t = unique_ptr<TTree>(dynamic_cast<TTree*>(fIn->Get<TTree>(location.c_str())));
46  if (!t)
47  BOOST_THROW_EXCEPTION(DE::BadInput("The tree can't be found in this file.", fIn));
48 
49  // open metainfo
50  MetaInfo mi(t, false);
51  hashes[i] = Hash(mi);
52 
53  // print (only the first time---the next rounds, we only check the hash)
54  bool found = false;
55  if (found) continue;
56  mi.Write(output);
57  found = true;
58  }
59 
60  // check the hash
61  bool identical = true;
62  stringstream ss;
63  for (size_t i = 0; i < N; ++i) {
64  ss << inputs[i] << '\t' << hex << hashes[i] << '\n';
65  if (i == 0) continue;
66  identical &= hashes[i-1] == hashes[i];
67  }
68 
69  if (identical) return EXIT_SUCCESS;
70  cerr << red << ss.str() << def;
71  return EXIT_FAILURE;
72 }

◆ GetOutput()

std::unique_ptr< TFile > GetOutput ( std::filesystem::path  output,
const char *  name 
)

Shortcut to create a reproducible output file (see ROOT Doxygen for details)

15 {
16  const auto fname = output;
17  output += "?reproducible="; output += name;
18  std::unique_ptr<TFile> f(TFile::Open(output.c_str(), "RECREATE"));
19  if (!f || !f->IsOpen() || f->IsZombie() || !fs::exists(fname))
20  BOOST_THROW_EXCEPTION( fs::filesystem_error("Failed to open output file",
21  output, make_error_code(std::errc::io_error)) );
22  return f;
23 }

◆ GetROOTfiles()

std::vector< std::filesystem::path > GetROOTfiles ( std::vector< std::filesystem::path >  inputs)

ROOT files or directories.

In case directories are given as inputs, instead of files, this function looks for all ROOT files in those directories (and subdirectories, iteratively).

Parameters
inputsROOT files or directories
34 {
35  using namespace std;
36  namespace fs = filesystem;
37 
38  if (inputs.size() == 0)
39  BOOST_THROW_EXCEPTION(fs::filesystem_error("No input was found!",
40  make_error_code(errc::no_such_file_or_directory)));
41 
42  vector<fs::path> root_inputs;
43  root_inputs.reserve(inputs.size());
44 
45  for (auto input: inputs) {
46  input = fs::absolute(input);
47  if (fs::is_directory(input)) {
48  for (const auto &entry : fs::recursive_directory_iterator(
49  input, fs::directory_options::follow_directory_symlink)) {
50  if (fs::is_regular_file(entry) && entry.path().extension() == ".root") {
51  root_inputs.push_back(entry);
52  }
53  }
54  }
55  else if (input.extension() == ".root")
56  root_inputs.push_back(input);
57  }
58 
59  sort(root_inputs.begin(), root_inputs.end(),
60  [](const fs::path& a, const fs::path& b) {
61  return strnatcmp(a.c_str(), b.c_str()) < 0;
62  });
63  return root_inputs;
64 }

◆ GetSize()

Long64_t Darwin::Tools::GetSize ( TBranch *  br)

Adapted from ROOT example

44 {
45  TMemFile f("buffer", "CREATE");
46  auto fcurrent = br->GetTree()->GetCurrentFile();
47  if (fcurrent) {
48  auto settings = fcurrent->GetCompressionSettings();
49  f.SetCompressionSettings(settings);
50  }
51  f.WriteObject(br, "thisbranch");
52  TKey * key = f.GetKey("thisbranch");
53  Long64_t size = key->GetNbytes();
54 
55  Long64_t basket = br->GetZipBytes();
56  if (basket == 0) basket = br->GetTotBytes();
57 
58  return basket + size;
59 }

◆ initMetaInfo()

int Darwin::Tools::initMetaInfo ( const pt::ptree &  config)

Writes a minimal MetaInfo to standard output.

Parameters
configconfig, with `flags` and `corrections` at least
23 {
24  auto formatStr = config.get<string>("format");
25  MetaInfo::Format format;
26  if (formatStr == "info")
27  format = MetaInfo::INFO;
28  else if (formatStr == "json")
29  format = MetaInfo::JSON;
30  else if (formatStr == "xml")
31  format = MetaInfo::XML;
32  else
33  BOOST_THROW_EXCEPTION( std::invalid_argument(
34  "Unknown MetaInfo format \"" + formatStr + "\"") );
35 
36  MetaInfo(MetaInfo::IKnowWhatIAmDoing{}).Write(cout, format);
37 
38  return EXIT_SUCCESS;
39 }

◆ loopBranches()

Long64_t Darwin::Tools::loopBranches ( TObjArray *  branches,
size_t  factor,
int  nIndent = 0 
)

Adapted from ROOT example

Parameters
brancheslist of (sub)branches
factorcorrection factor for #files in `TChain`
67 {
68  size_t n = branches->GetEntries();
69  Long64_t total = 0;
70  for (size_t i = 0; i < n; ++i) {
71  auto br = dynamic_cast<TBranch*>(branches->At(i));
72  Long64_t size = GetSize(br);
73 
74  string branchname(nIndent, ' ');
75  branchname += br->GetName();
76  cout << left << setw(40) << branchname
77  << right << setw(10) << GetHumanReadableSize(size * factor) << endl;
78 
79  TObjArray * subbranches = br->GetListOfBranches();
80  size += loopBranches(subbranches, factor, nIndent + 1);
81  total += size;
82  }
83  return total;
84 }

◆ NewTree()

std::unique_ptr< TTree > NewTree ( const std::unique_ptr< TChain > &  chain,
const bool  makeFriend,
const char *  thisFunc 
)

name of present exec

Either clone the input TChain or define the input TChain as a friend of the new TTree.

The title of the TTree is used to store (retrieve) the name of the present (previous) command. Different names are indeed necessary to distinguish the same branch in a TTree and its friend(s).

TODO: TTree::BuildIndex() to preserve the association despite skipped events?

Parameters
chaininput
makeFriendsteering containing the option
thisFuncname of present exec
133 {
134  using namespace std;
135  namespace DT = Darwin::Tools;
136  namespace DE = Darwin::Exceptions;
137  unique_ptr<TTree> tOut;
138  if (makeFriend) {
139  tOut = make_unique<TTree>("events", thisFunc);
140  chain->GetEntry(0); // necessary to load a(ny) TTree
141 
142  // find the name of the previous command
143  TString lastFunc = chain->GetTree()->GetTitle(); // this is supposed to store the name of the last command
144  if (lastFunc == "" || lastFunc == chain->GetTree()->GetName()) {
145  cerr << orange << "Unable to identify the command used to obtain the input from the title.\n" << def;
146  lastFunc = "previous";
147  }
148 
149  // add friend
150  tOut->AddFriend(chain.get(), lastFunc);
151 
152  // copy metainfo
153  TList * userinfo = chain->GetTree()->GetUserInfo();
154  tOut->GetUserInfo()->AddAll(userinfo);
155  userinfo->Clear(); // necessary to prevent the TTree destructor from deleting
156  // all elements in the list (avoid double deletion)
157  }
158  else {
159  tOut = unique_ptr<TTree>(chain->CloneTree(0));
160  tOut->SetTitle(thisFunc);
161  }
162  return tOut;
163 }

◆ operator<<()

std::ostream & operator<< ( std::ostream &  Stream,
const Darwin::Tools::Slice slice 
)

Prints the current slice and the total number of slices.

26 {
27  Stream << slice.second << '/' << slice.first;
28  return Stream;
29 }

◆ printBranches()

void Darwin::Tools::printBranches ( vector< fs::path >  inputs)

Adapted from ROOT example

Parameters
inputsinput ROOT files
90 {
92  size_t factor = inputs.size();
93  string location = GetFirstTreeLocation(inputs.front());
94  unique_ptr<TChain> tIn = GetChain(inputs, location.c_str());
95  TObjArray * branches = tIn->GetListOfBranches();
96  size_t size = loopBranches(branches, factor);
97  cout << right << setw(50) << GetHumanReadableSize(size * factor) << endl;
98 }

◆ PrintCloseFriend()

void Darwin::Tools::PrintCloseFriend ( TList *  friends,
const int  steering,
string  offset = "" 
)

Retrieve and prints the name and the friends.

Parameters
friendsobtained from `TTree::GetListOfFriends()`
steeringbitflied from `Options::steering()`
offsetspaces to show the distance from the original tree
27 {
28  // if the tree had no friend, the list does not exist
29  if (friends == nullptr) return;
30 
31  if (steering & verbose) friends->Print();
32 
33  // a priori we only expect one friend, but nothing speaks against more
34  for (TObject * obj: *friends) {
35  auto buddy = dynamic_cast<TFriendElement*>(obj);
36  cout << offset << buddy->GetName()
37  << ' ' << buddy->GetFile()->GetName()
38  << ':' << buddy->GetTreeName() << endl;
39 
40  TList * comrades = buddy->GetTree()->GetListOfFriends();
41  offset += " ";
42  PrintCloseFriend(comrades, steering, offset);
43  }
44 }

◆ printDarwinSoftwareVersion()

void Darwin::Tools::printDarwinSoftwareVersion ( )

Print the versions of the various pieces of software. Each software appears on a new line. Tought for exception handling in Python code and for Doxygen.

16 {
17  // TODO: use accumulate
18  for (auto const& v: MetaInfo::versions)
19  cout << v.first << ' ' << v.second << '\n';
20  cout << flush;
21 }

◆ printEntries()

void Darwin::Tools::printEntries ( vector< fs::path >  inputs)

Get total number of entries in input ROOT file(s) or directory, and prints it directly to the terminal.

Parameters
inputsinput ROOT files
24 {
25  try {
27  string location = GetFirstTreeLocation(inputs.front());
28  unique_ptr<TChain> tIn = GetChain(inputs, location.c_str());
29  cout << tIn->GetEntries() << endl;
30  }
31  catch (boost::wrapexcept<std::invalid_argument>& e) {
32  cout << 0 << endl;
33  }
34 }

◆ printFriends()

void Darwin::Tools::printFriends ( vector< fs::path >  inputs,
const int  steering 
)

Prints the recursive list of friends to the input n-tuple.

Parameters
inputsinput ROOT files
steeringbitfield from `Options::steering()`
51 {
53  string location = GetFirstTreeLocation(inputs.front());
54  unique_ptr<TChain> chain = GetChain(inputs, location.c_str());
55  chain->GetEntry(0);
56  TList * friends = chain->GetTree()->GetListOfFriends();
57  PrintCloseFriend(friends, steering);
58 }

◆ printHist()

void Darwin::Tools::printHist ( vector< fs::path >  inputs,
const pt::ptree &  config 
)

Print the content of a 1D histogram in columns.

Convention: index lowEdge upEdge content error

Parameters
inputsinput ROOT files
configconfig handled with `Darwin::Tools::options`
29 {
30  auto histname = config.get<string>("hist").c_str();
31  auto h = GetHist<TH1>({inputs}, histname);
32  if (h->GetDimension() > 1)
33  BOOST_THROW_EXCEPTION( DE::BadInput("The desired histogram is not 1D",
34  TFile(inputs.front().c_str()) ));
35  int N = h->GetNbinsX();
36  for (int i = 0; i <= N+1; ++i) {
37  double low = h->GetBinLowEdge(i),
38  up = h->GetBinLowEdge(i+1),
39  content = h->GetBinContent(i),
40  error = h->GetBinError(i);
41  if (error == 0 && content == 0) continue;
42 
43  // index
44  cout << setw(10);
45  if (i == 0) cout << "underflow";
46  else if (i == N+1) cout << "overflow";
47  else cout << i;
48 
49  // low edge
50  cout << setw(15);
51  if (i == 0) cout << "-inf";
52  else cout << low;
53  cout << setw(10);
54 
55  // upper edge
56  if (i > N) cout << "+inf";
57  else cout << up;
58 
59  // bin content and error
60  cout << setw(15) << content
61  << setw(15) << error
62  << '\n';
63  }
64  cout << flush;
65 }

◆ printMetaInfo()

int Darwin::Tools::printMetaInfo ( vector< fs::path >  inputs,
const pt::ptree &  config 
)

Print the value(s) corresponding to a given key in the first given input ROOT file.

If no value / subtree is found, the command fails and exits. If multiple entries are found, they are all printed. Only the first subtree is displayed.

The INFO format allows a key to have a value and a child. Since the JSON format does not allow that, we assume here that this case does not happen.

Parameters
inputsinput ROOT files
configconfig, with `flags` and `corrections` at least
36 {
38  const string location = GetFirstTreeLocation(inputs.front());
39 
40  // opening first file
41  unique_ptr<TFile> fIn(TFile::Open(inputs.front().c_str(), "READ"));
42  if (fIn->IsZombie())
43  BOOST_THROW_EXCEPTION(DE::BadInput("Can't open the file.", fIn));
44 
45  // fetch tree
46  auto t = unique_ptr<TTree>(dynamic_cast<TTree*>(fIn->Get<TTree>(location.c_str())));
47  if (!t)
48  BOOST_THROW_EXCEPTION(DE::BadInput("The tree can't be found in this file.", fIn));
49 
50  // open metainfo
51  MetaInfo metainfo(t, false);
52  auto ptree = metainfo.MkPtree();
53  auto key = config.get<string>("path");
54 
55  auto value = ptree.get<string>(key);
56  if (!value.empty()) {
57  cout << value << endl;
58  return EXIT_SUCCESS;
59  }
60 
61  auto child = ptree.get_child_optional(key);
62  if (child) {
63  for (auto& el: *child) {
64  string key = el.first,
65  val = el.second.get_value<string>();
66  if (!key.empty()) cout << key << ' ';
67  if (!val.empty()) cout << val;
68  cout << '\n';
69  }
70  cout << flush;
71  return EXIT_SUCCESS;
72  }
73 
74  return EXIT_FAILURE;
75 }

◆ StandardInit()

void StandardInit ( )

Standard initialisation for ROOT.

"Now you own all histogram objects and you will need to delete them, for in- stance through the use of std::unique_ptr. You can still set the directory of a histogram by calling SetDirectory() once it has been created."

26 {
27  gROOT->SetBatch();
28  TH1::SetDefaultSumw2();
29  TH1::AddDirectory(kFALSE);
30 }

◆ tokenize()

std::vector<const char *> Darwin::Tools::tokenize ( const char *  str)
inline

Tokenize a C-style string into a vector of C-style string with space as delimiter. It is especially useful in tests where the command is hard-coded.

16  {
17  std::cout << "\e[1m" << str << "\e[0m" << std::endl;
18 
19  // convert from `const char *` to `char *`
20  char * cmd = new char[strlen(str)+1];
21  strcpy(cmd, str);
22 
23  // tokenize
24  std::vector<const char *> args;
25  for (char * arg = strtok(cmd, " ");
26  arg != nullptr;
27  arg = strtok(NULL, " "))
28  args.push_back(std::move(arg));
29 
30  //free(cmd); // do NOT free the memory
31  return args;
32  }
Darwin::Tools::GetFirstTreeLocation
std::string GetFirstTreeLocation(const std::filesystem::path &input)
one input ROOT file
Definition: FileUtils.cc:91
DYToLL_M-50_13TeV_pythia8_cff_GEN_SIM_RECOBEFMIX_DIGI_L1_DIGI2RAW_L1Reco_RECO.name
name
Definition: DYToLL_M-50_13TeV_pythia8_cff_GEN_SIM_RECOBEFMIX_DIGI_L1_DIGI2RAW_L1Reco_RECO.py:48
Ntupliser_cfg.cerr
cerr
Definition: Ntupliser_cfg.py:93
jercExample.fname
fname
Definition: jercExample.py:88
Darwin::Tools::PrintCloseFriend
void PrintCloseFriend(TList *friends, const int steering, string offset="")
Retrieve and prints the name and the friends.
Definition: printFriends.cc:24
Darwin::Tools::syst
@ syst
activate -s to systematic uncertainties
Definition: Options.h:30
Darwin::Tools::GetHumanReadableSize
const char * GetHumanReadableSize(long double size)
From an absolute number of bytes to human readable size in KB, MB, GB, etc.
Definition: printBranches.cc:28
Step::verbose
static bool verbose
Definition: Step.h:40
Darwin::Tools::verbose
@ verbose
bit for debug mode (-v is always available)
Definition: Options.h:31
Step::def
static const char * def
Definition: Step.h:36
Darwin::Tools::none
@ none
default (for simple executables)
Definition: Options.h:25
Ntupliser_cfg.args
args
Definition: Ntupliser_cfg.py:11
Darwin::Tools::GetChain
std::unique_ptr< TChain > GetChain(std::vector< std::filesystem::path > inputs, const char *name="events")
Load chain from a list of files.
Definition: FileUtils.cc:67
Ntupliser_cfg.f
f
Definition: Ntupliser_cfg.py:255
Darwin::Tools::GetSize
Long64_t GetSize(TBranch *br)
Adapted from ROOT example
Definition: printBranches.cc:43
jercExample.key
string key
Definition: jercExample.py:109
Darwin::Tools::fill
@ fill
activate -f to fill the tree
Definition: Options.h:28
Darwin::Exceptions
Handling of exceptions.
Definition: darwin.h:34
Step::red
static const char * red
Definition: Step.h:34
cmd
cmd
Definition: Core-cfgcmd.txt:1
Darwin::Tools::split
@ split
activate -k and -j to define slice
Definition: Options.h:27
Ntupliser_cfg.config
config
Definition: Ntupliser_cfg.py:263
orange
static const char * orange
Definition: colours.h:6
DYToLL_M-50_13TeV_pythia8_cff_GEN_SIM_RECOBEFMIX_DIGI_L1_DIGI2RAW_L1Reco_RECO.input
input
Definition: DYToLL_M-50_13TeV_pythia8_cff_GEN_SIM_RECOBEFMIX_DIGI_L1_DIGI2RAW_L1Reco_RECO.py:35
Darwin::Tools::config
@ config
activate -c option to provide config file
Definition: Options.h:26
Darwin::Tools
Classes and functions related to the framework.
Definition: forceMetaInfo.cc:28
Darwin::Tools::GetROOTfiles
std::vector< std::filesystem::path > GetROOTfiles(std::vector< std::filesystem::path > inputs)
ROOT files or directories.
Definition: FileUtils.cc:33
jercExample.inputs
def inputs
Definition: jercExample.py:118
DAS::Normalisation::match
DAS::FourVector match(const DAS::FourVector &jet, const std::vector< DAS::FourVector > *hltJets)
Definition: match.h:7
Darwin::Tools::dev_null
static std::ostream dev_null(nullptr)
to redirect output stream to nowhere
Darwin::Tools::loopBranches
Long64_t loopBranches(TObjArray *branches, size_t factor, int nIndent=0)
Adapted from ROOT example
Definition: printBranches.cc:63
Darwin::Tools::Friend
@ Friend
activate -F to only fill the new branches
Definition: Options.h:29
Darwin::Exceptions::BadInput
Generic exception for ill-defined input (before the event loop).
Definition: exceptions.h:68
Darwin::Tools::FromPT2MetaInfo
void FromPT2MetaInfo(const pt::ptree &elements, const MetaInfo &metainfo, ostream &cout, Args... args)
Sets whatever is in the input config file into the metainfo of a TTree.
Definition: forceMetaInfo.cc:50
Darwin::Tools::getBool
optional< bool > getBool(string s)
Translates a string into a boolean if possible.
Definition: forceMetaInfo.cc:32
Step::bold
static const char * bold
Definition: Step.h:35