DAS  3.0
Das Analysis System
Darwin::Tools Namespace Reference

Classes

class  ChainSlice
 
class  Flow
 
class  Looper
 
class  MetaInfo
 
class  Options
 
class  SlicedFriendElement
 
class  UserInfo
 

Typedefs

typedef std::pair< unsigned, unsigned > Slice
 

Enumerations

enum  BranchMode { mandatory, facultative, mandatory, facultative }
 
enum  Mode {
  none = 0b000000, config = 0b000001, split = 0b000010, fill = 0b000100,
  Friend = 0b001000, syst = 0b010000, verbose = 0b100000, none = 0b000000,
  config = 0b000001, split = 0b000010, fill = 0b000100, Friend = 0b001000,
  syst = 0b010000, verbose = 0b100000
}
 
enum  BranchMode { mandatory, facultative, mandatory, facultative }
 
enum  Mode {
  none = 0b000000, config = 0b000001, split = 0b000010, fill = 0b000100,
  Friend = 0b001000, syst = 0b010000, verbose = 0b100000, none = 0b000000,
  config = 0b000001, split = 0b000010, fill = 0b000100, Friend = 0b001000,
  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, const int steering)
 
void printDarwinSoftwareVersion ()
 
void printEntries (vector< fs::path > inputs, const int steering)
 
void CollectFriends (const TTree *tree, set< string > &printed, const int steering, string indent="")
 
void CollectChainFriends (const TChain *chain, set< string > &printed, const int steering, string indent="")
 
void printFriends (vector< fs::path > inputs, const int steering)
 
void printHist (vector< fs::path > inputs, const pt::ptree &config, const int steering)
 
int printMetaInfo (vector< fs::path > inputs, const pt::ptree &config)
 
void StandardInit ()
 
std::vector< std::filesystem::path > GetROOTfiles (std::vector< std::filesystem::path > inputs)
 
template<typename THX = TH1>
std::unique_ptr< THX > GetHist (std::vector< std::filesystem::path > inputs, const std::string &name="h")
 
std::string GetFirstTreeLocation (const std::filesystem::path &input)
 
std::shared_ptr< TFile > GetOutputFile (const std::filesystem::path &, const std::source_location=std::source_location::current())
 
std::ostream & operator<< (std::ostream &Stream, const Darwin::Tools::Slice &slice)
 
static std::ostream dev_null (nullptr)
 
std::unique_ptr< TFile > GetOutput (std::filesystem::path output, const std::string &name)
 
std::vector< const char * > tokenize (const char *str)
 
static std::ostream dev_null (nullptr)
 

Detailed Description

Classes and functions related to the framework.

Utilities enabling better support for friend chains in a TTree.

SPDX-License-Idendifier: GPL-3.0-or-later SPDX-FileCopyrightText: Louis Moureaux louis.nosp@m..mou.nosp@m.reaux.nosp@m.@cer.nosp@m.n.ch

Typedef Documentation

◆ Slice

typedef std::pair< unsigned, unsigned > Slice

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

Enumeration Type Documentation

◆ BranchMode [1/2]

enum BranchMode
Enumerator
mandatory 

mounting branch is mandatory

facultative 

mounting branch is facultative

mandatory 

mounting branch is mandatory

facultative 

mounting branch is facultative

29  {
30  mandatory ,
32 };

◆ BranchMode [2/2]

enum BranchMode
Enumerator
mandatory 

mounting branch is mandatory

facultative 

mounting branch is facultative

mandatory 

mounting branch is mandatory

facultative 

mounting branch is facultative

29  {
30  mandatory ,
32 };

◆ Mode [1/2]

enum Mode
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)

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)

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

◆ Mode [2/2]

enum Mode
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)

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)

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

Function Documentation

◆ CollectChainFriends()

void Darwin::Tools::CollectChainFriends ( const TChain *  chain,
set< string > &  printed,
const int  steering,
string  indent = "" 
)

Retrieve and prints the elements in the chain and their friends recursively.

Parameters
chainchain to collect friends from
printedfiles already printed
steeringbitfield from `Options::steering()`
indentspaces to show the distance from the original tree
33 {
34  for (const auto &obj : *chain->GetListOfFiles()) {
35  auto element = dynamic_cast<TChainElement*>(obj);
36 
37  // TChain::Add format: filename.root?#tree
38  auto full_name = element->GetTitle() + string("?#") + element->GetName();
39 
40  // [chain] filename.root?#tree
41  cout << indent << "[chain] " << full_name;
42 
43  // try to open the file and fetch the tree to check for more friends
44  // print extra info if the tree isn't available
45  TTree *tree = nullptr;
46  unique_ptr<TFile> file(TFile::Open(element->GetTitle()));
47  if (file && !file->IsZombie()) {
48  tree = file->Get<TTree>(element->GetName());
49  if (!tree)
50  BOOST_THROW_EXCEPTION(Exceptions::BadInput(
51  Form("Tree %s not found", element->GetName()), file));
52  } else
53  BOOST_THROW_EXCEPTION(Exceptions::BadInput("File not found", file));
54  cout << endl;
55 
56  // recurse only if we haven't seen this file yet
57  if (printed.count(full_name) == 0) {
58  printed.insert(full_name);
59  CollectFriends(tree, printed, steering, indent + " ");
60  } else
61  cout << indent << " [see above]" << endl;
62  }
63 }

◆ CollectFriends()

void CollectFriends ( const TTree *  tree,
set< string > &  printed,
const int  steering,
string  indent 
)

Retrieve and prints the name and the friends.

When called on a long chain of friends, the output can include a very large number of files. To avoid printing too many lines, each file is printed only once. The printed argument keeps track of files already printed.

Parameters
treetree (or chain) to collect friends from
printedfiles already printed
steeringbitflied from `Options::steering()`
indentspaces to show the distance from the original tree
76 {
77  // If `tree` is actually a chain, we go through the files in the chain.
78  // There are two reasons to this:
79  // - A chain depends on each file in the chain, and we want to display this
80  // information
81  // - Each tree in the chain can have its own set of friends independently
82  // from the chain's friends. We also want to print those.
83  if (const auto chain = dynamic_cast<const TChain*>(tree); chain)
84  CollectChainFriends(chain, printed, steering, indent);
85 
86  auto friends = tree->GetListOfFriends();
87 
88  // if the tree had no friend, the list does not exist
89  if (friends == nullptr) return;
90 
91  if (steering & verbose) friends->Print();
92 
93  // a priori we only expect one friend, but nothing speaks against more
94  for (TObject * obj: *friends) {
95  auto buddy = dynamic_cast<TFriendElement*>(obj);
96 
97  cout << indent << "[friend] ";
98  if (auto sliced = dynamic_cast<SlicedFriendElement*>(obj); sliced)
99  // [friend] alias[50:100]
100  cout << buddy->GetName()
101  << "[" << sliced->GetBegin() << ":" << sliced->GetEnd() << "]";
102  else
103  // [friend] filename.root alias
104  cout << buddy->GetTitle() << " " << buddy->GetName();
105 
106  cout << endl;
107 
108  // recurse
109  CollectFriends(buddy->GetTree(), printed, steering, indent + " ");
110  }
111 }

◆ 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 }

◆ 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
65 {
66  unique_ptr<TFile> fIn(TFile::Open(input.c_str(), "READ"));
67  if (!fIn || !fIn->IsOpen() || fIn->IsZombie() || !fs::exists(input))
68  BOOST_THROW_EXCEPTION( fs::filesystem_error("Failed to open input file",
69  input, make_error_code(std::errc::io_error)) );
70 
71  function<string(TDirectory *)> loop;
72  loop = [&loop](TDirectory * d) -> string {
73 
74  // look for a `TTree` in the current `TDirectory`
75  for (const auto&& obj: *(d->GetListOfKeys())) {
76  auto const key = dynamic_cast<TKey*>(obj);
77  if (dynamic_cast<TTree *>(key->ReadObj()) == nullptr) continue;
78  return obj->GetName();
79  }
80 
81  // if not found, check all sub`TDirectory`s
82  for (const auto&& obj: *(d->GetListOfKeys())) {
83  auto const key = dynamic_cast<TKey*>(obj);
84  auto dd = dynamic_cast<TDirectory *>(key->ReadObj());
85  if (dd == nullptr) continue;
86  if (auto location = loop(dd); !location.empty())
87  return Form("%s/%s", dd->GetName(), location.c_str());
88  }
89 
90  // if nothing was found at this stage, return empty string
91  return string();
92  };
93  string location = loop(fIn.get());
94  if (location.empty())
95  BOOST_THROW_EXCEPTION( DE::BadInput("No `TTree` could be found in the input file.", fIn) );
96  return location;
97 }

◆ GetHist()

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

Load a histogram from a list of files.

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

◆ 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 {
30 
31  const size_t N = inputs.size();
32  hash<UserInfo> Hash;
33  vector<size_t> hashes(N,0);
34 
35  const string location = GetFirstTreeLocation(inputs.front());
36 
37  // looping over files
38  for (size_t i = 0; i < N; ++i) {
39 
40  // opening file
41  unique_ptr<TFile> fIn(TFile::Open(inputs[i].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 mi(t, false);
52  hashes[i] = Hash(mi);
53 
54  // print (only the first time---the next rounds, we only check the hash)
55  bool found = false;
56  if (found) continue;
57  mi.Write(output);
58  found = true;
59  }
60 
61  // check the hash
62  bool identical = true;
63  stringstream ss;
64  for (size_t i = 0; i < N; ++i) {
65  ss << inputs[i] << '\t' << hex << hashes[i] << '\n';
66  if (i == 0) continue;
67  identical &= hashes[i-1] == hashes[i];
68  }
69 
70  if (identical) return EXIT_SUCCESS;
71  cerr << red << ss.str() << def;
72  return EXIT_FAILURE;
73 }

◆ GetOutput()

std::unique_ptr<TFile> Darwin::Tools::GetOutput ( std::filesystem::path  output,
const std::string &  name 
)
19 {
20  const auto fname = output;
21  output += "?reproducible="; output += name;
22  std::unique_ptr<TFile> f(TFile::Open(output.c_str(), "RECREATE"));
23  if (!f || !f->IsOpen() || f->IsZombie() || !fs::exists(fname))
24  BOOST_THROW_EXCEPTION( fs::filesystem_error("Failed to open output file",
25  output, make_error_code(std::errc::io_error)) );
26  return f;
27 }

◆ GetOutputFile()

std::shared_ptr< TFile > GetOutputFile ( const std::filesystem::path &  ,
const std::source_location  = std::source_location::current() 
)

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

upstream function

Parameters
outputfile location
101 {
102  string title = fs::path(location.file_name()).stem();
103  auto output_rep = output.string() + "?reproducible="s + title;
104  auto fOut = make_shared<TFile>(output_rep.c_str(), "RECREATE");
105  if (!fOut->IsOpen() || fOut->IsZombie() || !fs::exists(output)) {
106  fOut.reset();
107  BOOST_THROW_EXCEPTION( fs::filesystem_error("Failed to open output file",
108  output, make_error_code(errc::io_error)) );
109  }
110  fOut->SetTitle(title.c_str());
111  return fOut;
112 }

◆ 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
38 {
39  vector<fs::path> root_inputs;
40  root_inputs.reserve(inputs.size());
41 
42  for (auto input: inputs) {
43  input = fs::absolute(input);
44  if (fs::is_directory(input)) {
45  for (const auto &entry : fs::recursive_directory_iterator(
46  input, fs::directory_options::follow_directory_symlink)) {
47  if (fs::is_regular_file(entry) && entry.path().extension() == ".root") {
48  root_inputs.push_back(entry);
49  }
50  }
51  }
52  else if (input.extension() == ".root")
53  root_inputs.push_back(input);
54  }
55 
56  sort(root_inputs.begin(), root_inputs.end(),
57  [](const fs::path& a, const fs::path& b) {
58  return strnatcmp(a.c_str(), b.c_str()) < 0;
59  });
60  return root_inputs;
61 }

◆ 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`
nIndentlevel of indentation
66 {
67  size_t n = branches->GetEntries();
68  Long64_t total = 0;
69  for (size_t i = 0; i < n; ++i) {
70  auto br = dynamic_cast<TBranch*>(branches->At(i));
71  Long64_t size = GetSize(br);
72 
73  string branchname(nIndent, ' ');
74  branchname += br->GetName();
75  cout << left << setw(40) << branchname
76  << right << setw(10) << GetHumanReadableSize(size * factor) << endl;
77 
78  TObjArray * subbranches = br->GetListOfBranches();
79  size += loopBranches(subbranches, factor, nIndent + 1);
80  total += size;
81  }
82  return total;
83 }

◆ operator<<()

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

Prints the current slice and the total number of slices.

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

◆ printBranches()

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

Adapted from ROOT example

Parameters
inputsinput ROOT files
steeringbitfield from `Options::steering()`
89 {
91  size_t factor = inputs.size();
92  string location = GetFirstTreeLocation(inputs.front());
93  Flow flow(steering, inputs);
94  auto tIn = flow.GetInputTree();
95  TObjArray * branches = tIn->GetListOfBranches();
96  size_t size = loopBranches(branches, factor);
97  cout << right << setw(50) << GetHumanReadableSize(size * factor) << endl;
98 }

◆ 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,
const int  steering 
)

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

Parameters
inputsinput ROOT files
steeringbitfield from `Options::steering()`
24  {
26  string location = GetFirstTreeLocation(inputs.front());
27  Flow flow(steering, inputs);
28  auto tIn = flow.GetInputTree({1, 0}, location);
29  cout << tIn->GetEntries() << endl;
30 }
31 catch (boost::wrapexcept<std::invalid_argument>& e) {
32  cout << 0 << endl;
33 }

◆ 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()`
117 {
119  string location = GetFirstTreeLocation(inputs.front());
120 
121  Flow flow(steering, inputs);
122  auto chain = flow.GetInputTree({1, 0}, location);
123 
124  set<string> printed;
125  CollectChainFriends(chain, printed, steering);
126 }

◆ printHist()

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

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`
steeringbitfield from `Options::steering()`
29 {
30  Flow flow(steering, inputs);
31  auto h = flow.GetInputHist(config.get<string>("hist"));
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."

30 {
31  gROOT->SetBatch();
32  TH1::SetDefaultSumw2();
33  TH1::AddDirectory(kFALSE);
34 }

◆ 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:64
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::mandatory
@ mandatory
mounting branch is mandatory
Definition: Flow.h:30
Darwin::Tools::fill
@ fill
activate -f to fill the tree
Definition: Options.h:27
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
Darwin::Tools::CollectChainFriends
void CollectChainFriends(const TChain *chain, set< string > &printed, const int steering, string indent="")
Retrieve and prints the elements in the chain and their friends recursively.
Definition: printFriends.cc:29
Step::verbose
static bool verbose
Definition: Step.h:40
Step::def
static const char * def
Definition: Step.h:36
Darwin::Tools::Friend
@ Friend
activate -F to only fill the new branches
Definition: Options.h:28
Ntupliser_cfg.args
args
Definition: Ntupliser_cfg.py:11
Darwin::Tools::CollectFriends
void CollectFriends(const TTree *tree, set< string > &printed, const int steering, string indent="")
Definition: printFriends.cc:72
Darwin::Tools::split
@ split
activate -k and -j to define slice
Definition: Options.h:26
Ntupliser_cfg.f
f
Definition: Ntupliser_cfg.py:256
Darwin::Tools::syst
@ syst
activate -s to systematic uncertainties
Definition: Options.h:29
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::none
@ none
default (for simple executables)
Definition: Options.h:24
Darwin::Exceptions
Handling of exceptions.
Definition: darwin.h:36
Step::red
static const char * red
Definition: Step.h:34
cmd
cmd
Definition: Core-cfgcmd.txt:1
Darwin::Tools::verbose
@ verbose
bit for debug mode (-v is always available)
Definition: Options.h:30
Ntupliser_cfg.config
config
Definition: Ntupliser_cfg.py:264
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
Ntupliser_cfg.indent
indent
Definition: Ntupliser_cfg.py:256
Darwin::Tools::GetROOTfiles
std::vector< std::filesystem::path > GetROOTfiles(std::vector< std::filesystem::path > inputs)
ROOT files or directories.
Definition: FileUtils.cc:37
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::Exceptions::BadInput
Generic exception for ill-defined input (before the event loop).
Definition: exceptions.h:83
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::facultative
@ facultative
mounting branch is facultative
Definition: Flow.h:31
Darwin::Tools::getBool
optional< bool > getBool(string s)
Translates a string into a boolean if possible.
Definition: forceMetaInfo.cc:32
Darwin::Tools::config
@ config
activate -c option to provide config file
Definition: Options.h:25
Step::bold
static const char * bold
Definition: Step.h:35