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)
 
int printMetaInfo (vector< fs::path > inputs, const pt::ptree &config)
 
std::unique_ptr< TFile > GetOutput (std::filesystem::path output, const std::string &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 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::unique_ptr< TTree > NewTree (const std::unique_ptr< TChain > &chain, const std::string &thisFunc)
 
std::ostream & operator<< (std::ostream &Stream, const Darwin::Tools::Slice &slice)
 
static std::ostream dev_null (nullptr)
 
std::unique_ptr< TTree > NewTree (const std::unique_ptr< ChainSlice > &chain, const std::string &thisFunc)
 
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

27  {
28  mandatory ,
30 };

◆ 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

27  {
28  mandatory ,
30 };

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

◆ GetChain()

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

internal path to TTree

Load chain from a list of files.

Only for backward compatibility.

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

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

◆ 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
58 {
59  using namespace std;
60  namespace fs = filesystem;
61 
62  unique_ptr<THX> sum;
64  for (auto const& input: inputs) {
65  auto fIn = make_unique<TFile>(input.c_str(), "READ");
67  unique_ptr<THX> h(fIn->Get<THX>(name.c_str()));
68  if (!h) {
69  namespace DE = Darwin::Exceptions;
70  BOOST_THROW_EXCEPTION(DE::BadInput(Form("`%s` cannot be found in (one of) the "
71  " file(s).", name.c_str()), fIn));
72  }
73  if (sum)
74  sum->Add(h.get());
75  else {
76  sum = std::move(h);
77  sum->SetDirectory(nullptr);
78  }
79  }
80  return sum;
81 }

◆ 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 > GetOutput ( std::filesystem::path  output,
const std::string &  name 
)

Shortcut to create a reproducible output file

See also
The ROOT documentation for TFile::kReproducible
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
126 {
127  string title = fs::path(location.file_name()).stem();
128  auto output_rep = output.string() + "?reproducible="s + title;
129  auto fOut = make_shared<TFile>(output_rep.c_str(), "RECREATE");
130  if (!fOut->IsOpen() || fOut->IsZombie() || !fs::exists(output)) {
131  fOut.reset();
132  BOOST_THROW_EXCEPTION( fs::filesystem_error("Failed to open output file",
133  output, make_error_code(errc::io_error)) );
134  }
135  fOut->SetTitle(title.c_str());
136  return fOut;
137 }

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

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

◆ NewTree() [1/2]

std::unique_ptr<TTree> Darwin::Tools::NewTree ( const std::unique_ptr< ChainSlice > &  chain,
const std::string &  thisFunc 
)
Parameters
chaininput
thisFuncname of present exec
141 {
142  auto tOut = unique_ptr<TTree>(chain->CloneTree(0));
143  tOut->SetTitle(thisFunc.c_str());
144  return tOut;
145 }

◆ NewTree() [2/2]

std::unique_ptr< TTree > NewTree ( const std::unique_ptr< TChain > &  chain,
const std::string &  thisFunc 
)

name of present exec

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

Only for backward compatibility.

Parameters
chaininput

◆ 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);
94  auto tIn = flow.GetInputTree(inputs, {1, 0});
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);
28  auto tIn = flow.GetInputTree(inputs, {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);
122  auto chain = flow.GetInputTree(inputs, {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 
)

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

◆ 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:89
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:28
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:252
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:260
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:252
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:29
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