container.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. /* DEBUG("Writing object \"" << obj_name << "\" of type \"" << type_name << "\"\n"); */
  68. gDirectory->WriteObjectAny(container, type_name.c_str(), obj_name.c_str());
  69. break;
  70. default:
  71. break;
  72. }
  73. }
  74. }
  75. namespace fv::root {
  76. template <typename V>
  77. class _ContainerTH1 : public Container<TH1,V>{
  78. private:
  79. void _fill(){
  80. if (this->container == nullptr){
  81. if (this->value == nullptr){
  82. CRITICAL("Container: \"" << this->get_name() << "\" has a null Value object. "
  83. << "Probably built with imcompatible type",-1);
  84. }
  85. this->container = new TH1D(this->get_name().c_str(), this->title.c_str(),
  86. this->nbins, this->low, this->high);
  87. this->container->SetXTitle(label_x.c_str());
  88. this->container->SetYTitle(label_y.c_str());
  89. }
  90. _do_fill();
  91. }
  92. protected:
  93. std::string title;
  94. std::string label_x;
  95. std::string label_y;
  96. int nbins;
  97. double low;
  98. double high;
  99. virtual void _do_fill() = 0;
  100. public:
  101. explicit _ContainerTH1(const std::string &name, const std::string& title, Value<V>* value,
  102. int nbins, double low, double high,
  103. const std::string& label_x = "",
  104. const std::string& label_y = "")
  105. :Container<TH1,V>(name, value),
  106. title(title), nbins(nbins), low(low), high(high),
  107. label_x(label_x), label_y(label_y) { }
  108. void save_as(const std::string& fname, const SaveOption& option = SaveOption::PNG) {
  109. util::save_as(this->get_container(), fname, option);
  110. }
  111. };
  112. template <typename V>
  113. class ContainerTH1 : public _ContainerTH1<V>{
  114. using _ContainerTH1<V>::_ContainerTH1;
  115. void _do_fill(){
  116. this->container->Fill(this->value->get_value());
  117. }
  118. };
  119. template <typename V>
  120. class ContainerTH1Many : public _ContainerTH1<std::vector<V>>{
  121. using _ContainerTH1<std::vector<V>>::_ContainerTH1;
  122. void _do_fill(){
  123. for(V x : this->value->get_value())
  124. this->container->Fill(x);
  125. }
  126. };
  127. template <typename V>
  128. class _ContainerTH2 : public Container<TH2,std::pair<V,V>>{
  129. private:
  130. void _fill(){
  131. if (this->container == nullptr){
  132. if (this->value == nullptr){
  133. CRITICAL("Container: \"" << this->get_name() << "\" has a null Value object. "
  134. << "Probably built with imcompatible type",-1);
  135. }
  136. this->container = new TH2D(this->get_name().c_str(), this->title.c_str(),
  137. this->nbins_x, this->low_x, this->high_x,
  138. this->nbins_y, this->low_y, this->high_y);
  139. this->container->SetXTitle(label_x.c_str());
  140. this->container->SetYTitle(label_y.c_str());
  141. }
  142. _do_fill(this->value->get_value());
  143. }
  144. protected:
  145. std::string title;
  146. std::string label_x;
  147. std::string label_y;
  148. int nbins_x;
  149. int nbins_y;
  150. double low_x;
  151. double low_y;
  152. double high_x;
  153. double high_y;
  154. virtual void _do_fill(std::pair<V,V>& val) = 0;
  155. public:
  156. explicit _ContainerTH2(const std::string& name, const std::string& title,
  157. Value<std::pair<V, V>>* value,
  158. int nbins_x, double low_x, double high_x,
  159. int nbins_y, double low_y, double high_y,
  160. const std::string& label_x = "",
  161. const std::string& label_y = "")
  162. :Container<TH2,std::pair<V,V>>(name, value),
  163. title(title),
  164. nbins_x(nbins_x), low_x(low_x), high_x(high_x),
  165. nbins_y(nbins_y), low_y(low_y), high_y(high_y),
  166. label_x(label_x), label_y(label_y) { }
  167. void save_as(const std::string& fname, const SaveOption& option = SaveOption::PNG) {
  168. util::save_as(this->get_container(), fname, option);
  169. }
  170. };
  171. template <typename V>
  172. class ContainerTH2 : public _ContainerTH2<V>{
  173. using _ContainerTH2<V>::_ContainerTH2;
  174. void _do_fill(std::pair<V,V>& val){
  175. this->container->Fill(val.first,val.second);
  176. }
  177. };
  178. template <typename V>
  179. class ContainerTH2Many : public _ContainerTH2<std::vector<V>>{
  180. using _ContainerTH2<std::vector<V>>::_ContainerTH2;
  181. void _do_fill(std::pair<std::vector<V>,std::vector<V>>& val){
  182. int min_size = std::min(val.first.size(), val.second.size());
  183. for(int i=0; i<min_size; i++)
  184. this->container->Fill(val.first[i],val.second[i]);
  185. }
  186. };
  187. template <typename V>
  188. class ContainerTGraph : public Container<TGraph,std::pair<V,V>>{
  189. private:
  190. std::vector<V> x_data;
  191. std::vector<V> y_data;
  192. std::string title;
  193. bool data_modified;
  194. void _fill(){
  195. auto val = this->value->get_value();
  196. x_data.push_back(val.first);
  197. y_data.push_back(val.second);
  198. data_modified = true;
  199. }
  200. public:
  201. ContainerTGraph(const std::string& name, const std::string& title, Value<std::pair<V, V>>* value)
  202. :Container<TGraph,std::pair<V,V>>(name, value),
  203. data_modified(false){
  204. this->container = new TGraph();
  205. }
  206. TGraph* get_container(){
  207. if (data_modified){
  208. delete this->container;
  209. this->container = new TGraph(x_data.size(), x_data.data(), y_data.data());
  210. this->container->SetName(this->get_name().c_str());
  211. this->container->SetTitle(title.c_str());
  212. data_modified = false;
  213. }
  214. return this->container;
  215. }
  216. void save_as(const std::string& fname, const SaveOption& option = SaveOption::PNG) {
  217. util::save_as(get_container(), fname, option);
  218. }
  219. };
  220. template <typename T>
  221. class Vector : public Container<std::vector<T>,T>{
  222. private:
  223. void _fill(){
  224. this->container->push_back(this->value->get_value());
  225. }
  226. public:
  227. Vector(const std::string& name, Value<T>* value)
  228. :Container<std::vector<T>,T>(name, value){
  229. this->container = new std::vector<T>;
  230. }
  231. void save_as(const std::string& fname, const SaveOption& option = SaveOption::PNG) {
  232. std::string type_name = "std::vector<"+fv::util::get_type_name(typeid(T))+">";
  233. util::save_as_stl(this->get_container(), type_name, this->get_name(), option);
  234. }
  235. };
  236. template <typename V, typename D>
  237. class _Counter : public Container<std::map<D,int>,V>{
  238. public:
  239. explicit _Counter(const std::string& name, Value<V>* value)
  240. :Container<std::map<D,int>,V>(name, value) {
  241. this->container = new std::map<D,int>;
  242. }
  243. void save_as(const std::string& fname, const SaveOption& option = SaveOption::PNG) {
  244. std::string type_name = "std::map<"+fv::util::get_type_name(typeid(D))+",int>";
  245. util::save_as_stl(this->get_container(), type_name, this->get_name(), option);
  246. }
  247. };
  248. /**
  249. * A Counter that keeps a mapping of the number of occurances of each input
  250. * value.
  251. */
  252. template <typename V>
  253. class Counter : public _Counter<V,V>{
  254. using _Counter<V,V>::_Counter;
  255. void _fill(){
  256. (*this->container)[this->value->get_value()]++;
  257. }
  258. };
  259. /**
  260. * Same as Counter but accepts multiple values per fill.
  261. */
  262. template <typename V>
  263. class CounterMany : public _Counter<std::vector<V>,V>{
  264. using _Counter<std::vector<V>,V>::_Counter;
  265. void _fill(){
  266. for(V& val : this->value->get_value())
  267. (*this->container)[val]++;
  268. }
  269. };
  270. class PassCount : public Container<int,bool>{
  271. private:
  272. void _fill(){
  273. if(this->value->get_value()){
  274. (*this->container)++;
  275. }
  276. }
  277. public:
  278. PassCount(const std::string& name, Value<bool>* value)
  279. :Container<int,bool>(name, value){
  280. this->container = new int(0);
  281. }
  282. void save_as(const std::string& fname, const SaveOption& option = SaveOption::PNG) {
  283. //ROOT(hilariously) cannot serialize basic data types, we wrap this
  284. //in a vector.
  285. std::vector<int> v({*this->get_container()});
  286. util::save_as_stl(&v, "std::vector<int>", this->get_name(), option);
  287. }
  288. };
  289. template <typename... ArgTypes>
  290. class MVA : public Container<TMVA::DataLoader,typename MVAData<ArgTypes...>::type>{
  291. private:
  292. std::vector<std::pair<std::string,std::string>> methods;
  293. TCut cut;
  294. TString opt;
  295. void _fill(){
  296. std::tuple<ArgTypes...> t;
  297. typename MVAData<ArgTypes...>::type& event = this->value->get_value();
  298. bool is_training, is_signal;
  299. double weight;
  300. std::tie(is_training, is_signal, weight, t) = event;
  301. std::vector<double> v = t2v<double>(t);
  302. if (is_signal){
  303. if (is_training){
  304. this->container->AddSignalTrainingEvent(v, weight);
  305. } else {
  306. this->container->AddSignalTestEvent(v, weight);
  307. }
  308. } else {
  309. if (is_training){
  310. this->container->AddBackgroundTrainingEvent(v, weight);
  311. } else {
  312. this->container->AddBackgroundTestEvent(v, weight);
  313. }
  314. }
  315. }
  316. public:
  317. MVA(const std::string& name, MVAData<ArgTypes...>* value, const std::string& cut = "", const std::string& opt = "")
  318. :Container<TMVA::DataLoader,typename MVAData<ArgTypes...>::type>(name, value),
  319. cut(cut.c_str()), opt(opt.c_str()) {
  320. this->container = new TMVA::DataLoader(name);
  321. for (std::pair<std::string,char>& p : value->get_label_types()){
  322. this->container->AddVariable(p.first, p.second);
  323. }
  324. }
  325. void add_method(const std::string& method_name, const std::string& method_params) {
  326. methods.push_back(std::make_pair(method_name, method_params));
  327. }
  328. void save_as(const std::string& fname, const SaveOption& option = SaveOption::PNG) {
  329. TFile* outputFile = gDirectory->GetFile();
  330. this->container->PrepareTrainingAndTestTree(cut, opt);
  331. TMVA::Factory *factory = new TMVA::Factory("TMVAClassification", outputFile,
  332. "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification");
  333. TMVA::Types& types = TMVA::Types::Instance();
  334. for(auto& p : methods){
  335. std::string method_name, method_params;
  336. std::tie(method_name, method_params) = p;
  337. TMVA::Types::EMVA method_type = types.GetMethodType(method_name);
  338. factory->BookMethod(this->container, method_type, method_name, method_params);
  339. }
  340. // Train MVAs using the set of training events
  341. factory->TrainAllMethods();
  342. // Evaluate all MVAs using the set of test events
  343. factory->TestAllMethods();
  344. // Evaluate and compare performance of all configured MVAs
  345. factory->EvaluateAllMethods();
  346. delete factory;
  347. }
  348. };
  349. }
  350. #endif // root_container_hpp