container.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. #ifndef root_container_hpp
  2. #define root_container_hpp
  3. #include <iostream>
  4. #include <utility>
  5. #include <map>
  6. #include "TROOT.h"
  7. #include "TFile.h"
  8. #include "TCanvas.h"
  9. #include "TGraph.h"
  10. #include "TH1.h"
  11. #include "TH2.h"
  12. #include "TMVA/Factory.h"
  13. #include "TMVA/DataLoader.h"
  14. #include "TMVA/DataSetInfo.h"
  15. #include "filval/container.hpp"
  16. namespace fv::root::util{
  17. /**
  18. * Save a TObject. The TObject will typically be a Histogram or Graph object,
  19. * but can really be any TObject. The SaveOption can be used to specify how to
  20. * save the file.
  21. */
  22. void save_as(TObject* container, const std::string& fname, const SaveOption& option = SaveOption::PNG) {
  23. auto save_img = [](TObject* container, const std::string& fname){
  24. TCanvas* c1 = new TCanvas("c1");
  25. container->Draw();
  26. c1->Draw();
  27. c1->SaveAs(fname.c_str());
  28. delete c1;
  29. };
  30. auto save_bin = [](TObject* container){
  31. INFO("Saving object: " << container->GetName() << " into file " << gDirectory->GetName());
  32. container->Write(container->GetName(), TObject::kOverwrite);
  33. };
  34. switch(option){
  35. case PNG:
  36. save_img(container, fname+".png"); break;
  37. case PDF:
  38. save_img(container, fname+".pdf"); break;
  39. case ROOT:
  40. save_bin(container); break;
  41. default:
  42. break;
  43. }
  44. }
  45. /**
  46. * Saves an STL container into a ROOT file. ROOT knows how to serialize STL
  47. * containers, but it needs the *name* of the type of the container, eg.
  48. * std::map<int,int> to be able to do this. In order to generate this name at
  49. * run-time, the fv::util::get_type_name function uses RTTI to get type info
  50. * and use it to look up the proper name.
  51. *
  52. * For nexted containers, it is necessary to generate the CLING dictionaries
  53. * for each type at compile time to enable serialization. To do this, add the
  54. * type definition into the LinkDef.hpp header file.
  55. */
  56. void save_as_stl(void* container, const std::string& type_name,
  57. const std::string& obj_name,
  58. const SaveOption& option = SaveOption::PNG) {
  59. switch(option){
  60. case PNG:
  61. INFO("Cannot save STL container " << type_name <<" as png");
  62. break;
  63. case PDF:
  64. INFO("Cannot save STL container " << type_name <<" as pdf");
  65. break;
  66. case ROOT:
  67. gDirectory->WriteObjectAny(container, type_name.c_str(), obj_name.c_str());
  68. break;
  69. default:
  70. break;
  71. }
  72. }
  73. }
  74. namespace fv::root {
  75. template <typename V>
  76. class _ContainerTH1 : public Container<TH1,V>{
  77. private:
  78. void _fill(){
  79. if (this->container == nullptr){
  80. if (this->value == nullptr){
  81. CRITICAL("Container: \"" << this->get_name() << "\" has a null Value object. "
  82. << "Probably built with imcompatible type",-1);
  83. }
  84. this->container = new TH1D(this->get_name().c_str(), this->title.c_str(),
  85. this->nbins, this->low, this->high);
  86. this->container->SetXTitle(label_x.c_str());
  87. this->container->SetYTitle(label_y.c_str());
  88. }
  89. _do_fill();
  90. }
  91. protected:
  92. std::string title;
  93. std::string label_x;
  94. std::string label_y;
  95. int nbins;
  96. double low;
  97. double high;
  98. virtual void _do_fill() = 0;
  99. public:
  100. explicit _ContainerTH1(const std::string &name, const std::string& title, Value<V>* value,
  101. int nbins, double low, double high,
  102. const std::string& label_x = "",
  103. const std::string& label_y = "")
  104. :Container<TH1,V>(name, value),
  105. title(title), nbins(nbins), low(low), high(high),
  106. label_x(label_x), label_y(label_y) { }
  107. void save_as(const std::string& fname, const SaveOption& option = SaveOption::PNG) {
  108. util::save_as(this->get_container(), fname, option);
  109. }
  110. };
  111. template <typename V>
  112. class ContainerTH1 : public _ContainerTH1<V>{
  113. using _ContainerTH1<V>::_ContainerTH1;
  114. void _do_fill(){
  115. this->container->Fill(this->value->get_value());
  116. }
  117. };
  118. template <typename V>
  119. class ContainerTH1Many : public _ContainerTH1<std::vector<V>>{
  120. using _ContainerTH1<std::vector<V>>::_ContainerTH1;
  121. void _do_fill(){
  122. for(V x : this->value->get_value())
  123. this->container->Fill(x);
  124. }
  125. };
  126. template <typename V>
  127. class _ContainerTH2 : public Container<TH2,std::pair<V,V>>{
  128. private:
  129. void _fill(){
  130. if (this->container == nullptr){
  131. if (this->value == nullptr){
  132. CRITICAL("Container: \"" << this->get_name() << "\" has a null Value object. "
  133. << "Probably built with imcompatible type",-1);
  134. }
  135. this->container = new TH2D(this->get_name().c_str(), this->title.c_str(),
  136. this->nbins_x, this->low_x, this->high_x,
  137. this->nbins_y, this->low_y, this->high_y);
  138. this->container->SetXTitle(label_x.c_str());
  139. this->container->SetYTitle(label_y.c_str());
  140. }
  141. _do_fill(this->value->get_value());
  142. }
  143. protected:
  144. std::string title;
  145. std::string label_x;
  146. std::string label_y;
  147. int nbins_x;
  148. int nbins_y;
  149. double low_x;
  150. double low_y;
  151. double high_x;
  152. double high_y;
  153. virtual void _do_fill(std::pair<V,V>& val) = 0;
  154. public:
  155. explicit _ContainerTH2(const std::string& name, const std::string& title,
  156. Value<std::pair<V, V>>* value,
  157. int nbins_x, double low_x, double high_x,
  158. int nbins_y, double low_y, double high_y,
  159. const std::string& label_x = "",
  160. const std::string& label_y = "")
  161. :Container<TH2,std::pair<V,V>>(name, value),
  162. title(title),
  163. nbins_x(nbins_x), low_x(low_x), high_x(high_x),
  164. nbins_y(nbins_y), low_y(low_y), high_y(high_y),
  165. label_x(label_x), label_y(label_y) { }
  166. void save_as(const std::string& fname, const SaveOption& option = SaveOption::PNG) {
  167. util::save_as(this->get_container(), fname, option);
  168. }
  169. };
  170. template <typename V>
  171. class ContainerTH2 : public _ContainerTH2<V>{
  172. using _ContainerTH2<V>::_ContainerTH2;
  173. void _do_fill(std::pair<V,V>& val){
  174. this->container->Fill(val.first,val.second);
  175. }
  176. };
  177. template <typename V>
  178. class ContainerTH2Many : public _ContainerTH2<std::vector<V>>{
  179. using _ContainerTH2<std::vector<V>>::_ContainerTH2;
  180. void _do_fill(std::pair<std::vector<V>,std::vector<V>>& val){
  181. int min_size = std::min(val.first.size(), val.second.size());
  182. for(int i=0; i<min_size; i++)
  183. this->container->Fill(val.first[i],val.second[i]);
  184. }
  185. };
  186. template <typename V>
  187. class ContainerTGraph : public Container<TGraph,std::pair<V,V>>{
  188. private:
  189. std::vector<V> x_data;
  190. std::vector<V> y_data;
  191. std::string title;
  192. bool data_modified;
  193. void _fill(){
  194. auto val = this->value->get_value();
  195. x_data.push_back(val.first);
  196. y_data.push_back(val.second);
  197. data_modified = true;
  198. }
  199. public:
  200. ContainerTGraph(const std::string& name, const std::string& title, Value<std::pair<V, V>>* value)
  201. :Container<TGraph,std::pair<V,V>>(name, value),
  202. data_modified(false){
  203. this->container = new TGraph();
  204. }
  205. TGraph* get_container(){
  206. if (data_modified){
  207. delete this->container;
  208. this->container = new TGraph(x_data.size(), x_data.data(), y_data.data());
  209. this->container->SetName(this->get_name().c_str());
  210. this->container->SetTitle(title.c_str());
  211. data_modified = false;
  212. }
  213. return this->container;
  214. }
  215. void save_as(const std::string& fname, const SaveOption& option = SaveOption::PNG) {
  216. util::save_as(get_container(), fname, option);
  217. }
  218. };
  219. template <typename T>
  220. class Vector : public Container<std::vector<T>,T>{
  221. private:
  222. void _fill(){
  223. this->container->push_back(this->value->get_value());
  224. }
  225. public:
  226. Vector(const std::string& name, Value<T>* value)
  227. :Container<std::vector<T>,T>(name, value){
  228. this->container = new std::vector<T>;
  229. }
  230. void save_as(const std::string& fname, const SaveOption& option = SaveOption::PNG) {
  231. std::string type_name = "std::vector<"+fv::util::get_type_name(typeid(T))+">";
  232. util::save_as_stl(this->get_container(), type_name, this->get_name(), option);
  233. }
  234. };
  235. template <typename V, typename D>
  236. class _Counter : public Container<std::map<D,int>,V>{
  237. public:
  238. explicit _Counter(const std::string& name, Value<V>* value)
  239. :Container<std::map<D,int>,V>(name, value) {
  240. this->container = new std::map<D,int>;
  241. }
  242. void save_as(const std::string& fname, const SaveOption& option = SaveOption::PNG) {
  243. std::string type_name = "std::map<"+fv::util::get_type_name(typeid(D))+",int>";
  244. util::save_as_stl(this->get_container(), type_name, this->get_name(), option);
  245. }
  246. };
  247. /**
  248. * A Counter that keeps a mapping of the number of occurances of each input
  249. * value.
  250. */
  251. template <typename V>
  252. class Counter : public _Counter<V,V>{
  253. using _Counter<V,V>::_Counter;
  254. void _fill(){
  255. (*this->container)[this->value->get_value()]++;
  256. }
  257. };
  258. /**
  259. * Same as Counter but accepts multiple values per fill.
  260. */
  261. template <typename V>
  262. class CounterMany : public _Counter<std::vector<V>,V>{
  263. using _Counter<std::vector<V>,V>::_Counter;
  264. void _fill(){
  265. for(V& val : this->value->get_value())
  266. (*this->container)[val]++;
  267. }
  268. };
  269. template <typename... ArgTypes>
  270. class MVA : public Container<TMVA::DataLoader,typename MVAData<ArgTypes...>::type>{
  271. private:
  272. std::vector<std::pair<std::string,std::string>> methods;
  273. TCut cut;
  274. TString opt;
  275. void _fill(){
  276. std::tuple<ArgTypes...> t;
  277. typename MVAData<ArgTypes...>::type& event = this->value->get_value();
  278. bool is_training, is_signal;
  279. double weight;
  280. std::tie(is_training, is_signal, weight, t) = event;
  281. std::vector<double> v = t2v<double>(t);
  282. if (is_signal){
  283. if (is_training){
  284. this->container->AddSignalTrainingEvent(v, weight);
  285. } else {
  286. this->container->AddSignalTestEvent(v, weight);
  287. }
  288. } else {
  289. if (is_training){
  290. this->container->AddBackgroundTrainingEvent(v, weight);
  291. } else {
  292. this->container->AddBackgroundTestEvent(v, weight);
  293. }
  294. }
  295. }
  296. public:
  297. MVA(const std::string& name, MVAData<ArgTypes...>* value, const std::string& cut = "", const std::string& opt = "")
  298. :Container<TMVA::DataLoader,typename MVAData<ArgTypes...>::type>(name, value),
  299. cut(cut.c_str()), opt(opt.c_str()) {
  300. this->container = new TMVA::DataLoader(name);
  301. for (std::pair<std::string,char>& p : value->get_label_types()){
  302. this->container->AddVariable(p.first, p.second);
  303. }
  304. }
  305. void add_method(const std::string& method_name, const std::string& method_params) {
  306. methods.push_back(std::make_pair(method_name, method_params));
  307. }
  308. void save_as(const std::string& fname, const SaveOption& option = SaveOption::PNG) {
  309. TFile* outputFile = gDirectory->GetFile();
  310. this->container->PrepareTrainingAndTestTree(cut, opt);
  311. TMVA::Factory *factory = new TMVA::Factory("TMVAClassification", outputFile,
  312. "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification");
  313. TMVA::Types& types = TMVA::Types::Instance();
  314. for(auto& p : methods){
  315. std::string method_name, method_params;
  316. std::tie(method_name, method_params) = p;
  317. TMVA::Types::EMVA method_type = types.GetMethodType(method_name);
  318. factory->BookMethod(this->container, method_type, method_name, method_params);
  319. }
  320. // Train MVAs using the set of training events
  321. factory->TrainAllMethods();
  322. // Evaluate all MVAs using the set of test events
  323. factory->TestAllMethods();
  324. // Evaluate and compare performance of all configured MVAs
  325. factory->EvaluateAllMethods();
  326. delete factory;
  327. }
  328. };
  329. }
  330. #endif // root_container_hpp