REST-for-Physics  v2.3
Rare Event Searches ToolKit for Physics
TRestDataSet.cxx
1/*************************************************************************
2 * This file is part of the REST software framework. *
3 * *
4 * Copyright (C) 2016 GIFNA/TREX (University of Zaragoza) *
5 * For more information see https://gifna.unizar.es/trex *
6 * *
7 * REST is free software: you can redistribute it and/or modify *
8 * it under the terms of the GNU General Public License as published by *
9 * the Free Software Foundation, either version 3 of the License, or *
10 * (at your option) any later version. *
11 * *
12 * REST is distributed in the hope that it will be useful, *
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15 * GNU General Public License for more details. *
16 * *
17 * You should have a copy of the GNU General Public License along with *
18 * REST in $REST_PATH/LICENSE. *
19 * If not, see https://www.gnu.org/licenses/. *
20 * For the list of contributors see $REST_PATH/CREDITS. *
21 *************************************************************************/
22
258#include "TRestDataSet.h"
259
260#include "TRestRun.h"
261#include "TRestTools.h"
262
263ClassImp(TRestDataSet);
264
269
284TRestDataSet::TRestDataSet(const char* cfgFileName, const std::string& name) : TRestMetadata(cfgFileName) {
286
288}
289
294
299void TRestDataSet::Initialize() { SetSectionName(this->ClassName()); }
300
306 if (fTree != nullptr) {
307 RESTWarning << "Tree has already been loaded. Skipping TRestDataSet::GenerateDataSet ... "
308 << RESTendl;
309 return;
310 }
311
312 if (fFileSelection.empty()) FileSelection();
313
314 // We are not ready yet
315 if (fFileSelection.empty()) {
316 RESTError << "File selection is empty " << RESTendl;
317 return;
318 }
319
321 TRestRun run(fFileSelection.front());
322 std::vector<std::string> finalList;
323 finalList.push_back("runOrigin");
324 finalList.push_back("eventID");
325 finalList.push_back("timeStamp");
326
327 auto obsNames = run.GetAnalysisTree()->GetObservableNames();
328 for (const auto& obs : fObservablesList) {
329 if (std::find(obsNames.begin(), obsNames.end(), obs) != obsNames.end()) {
330 finalList.push_back(obs);
331 } else {
332 RESTWarning << " Observable " << obs << " not found in observable list, skipping..." << RESTendl;
333 }
334 }
335
336 for (const auto& name : obsNames) {
337 for (const auto& pcs : fProcessObservablesList) {
338 if (name.find(pcs) == 0) finalList.push_back(name);
339 }
340 }
341
342 // Remove duplicated observables if any
343 std::sort(finalList.begin(), finalList.end());
344 finalList.erase(std::unique(finalList.begin(), finalList.end()), finalList.end());
345
346 ROOT::EnableImplicitMT();
347
348 RESTInfo << "Initializing dataset" << RESTendl;
349 fDataSet = ROOT::RDataFrame("AnalysisTree", fFileSelection);
350
351 RESTInfo << "Making cuts" << RESTendl;
353
354 // Adding new user columns added to the dataset
355 for (const auto& [cName, cExpression] : fColumnNameExpressions) {
356 RESTInfo << "Adding column to dataset: " << cName << RESTendl;
357 finalList.emplace_back(cName);
358 fDataSet = DefineColumn(cName, cExpression);
359 }
360
361 RESTInfo << "Generating snapshot." << RESTendl;
362 std::string user = getenv("USER");
363 std::string fOutName = "/tmp/rest_output_" + user + ".root";
364 fDataSet.Snapshot("AnalysisTree", fOutName, finalList);
365
366 RESTInfo << "Re-importing analysis tree." << RESTendl;
367 fDataSet = ROOT::RDataFrame("AnalysisTree", fOutName);
368
369 TFile* f = TFile::Open(fOutName.c_str());
370 fTree = (TChain*)f->Get("AnalysisTree");
371
372 RESTInfo << " - Dataset generated!" << RESTendl;
373}
374
378std::vector<std::string> TRestDataSet::FileSelection() {
379 fFileSelection.clear();
380
381 std::time_t time_stamp_start = REST_StringHelper::StringToTimeStamp(fFilterStartTime);
382 std::time_t time_stamp_end = REST_StringHelper::StringToTimeStamp(fFilterEndTime);
383
384 if (!time_stamp_end || !time_stamp_start) {
385 RESTError << "TRestDataSet::FileSelect. Start or end dates not properly formed. Please, check "
386 "REST_StringHelper::StringToTimeStamp documentation for valid formats"
387 << RESTendl;
388 return fFileSelection;
389 }
390
391 std::vector<std::string> fileNames = TRestTools::GetFilesMatchingPattern(fFilePattern);
392
393 if (!fileNames.empty()) {
394 RESTInfo << "TRestDataSet::FileSelection. Starting file selection." << RESTendl;
395 RESTInfo << "Total files : " << fileNames.size() << RESTendl;
396 RESTInfo << "This process may take long computation time in case there are many files." << RESTendl;
397 }
398
399 fTotalDuration = 0;
400 std::cout << "Total files : " << fileNames.size() << std::endl;
401 std::cout << "Processing file selection .";
402 int cnt = 1;
403 for (const auto& file : fileNames) {
404 if (cnt % 100 == 0) {
405 std::cout << std::endl;
406 std::cout << "Files processed: " << cnt << " ." << std::flush;
407 }
408 cnt++;
409 TRestRun run(file);
410 std::cout << "." << std::flush;
411 double runStart = run.GetStartTimestamp();
412 double runEnd = run.GetEndTimestamp();
413
414 if (runStart < time_stamp_start || runEnd > time_stamp_end) {
415 continue;
416 }
417
418 int n = 0;
419 bool accept = true;
420 for (const auto& md : fFilterMetadata) {
421 std::string mdValue = run.GetMetadataMember(md);
422
423 if (!fFilterContains[n].empty())
424 if (mdValue.find(fFilterContains[n]) == std::string::npos) accept = false;
425
426 if (fFilterGreaterThan[n] != -1) {
427 if (StringToDouble(mdValue) <= fFilterGreaterThan[n]) accept = false;
428 }
429
430 if (fFilterLowerThan[n] != -1)
431 if (StringToDouble(mdValue) >= fFilterLowerThan[n]) accept = false;
432
433 if (fFilterEqualsTo[n] != -1)
434 if (StringToDouble(mdValue) != fFilterEqualsTo[n]) accept = false;
435
436 n++;
437 }
438
439 if (!accept) continue;
440
441 Double_t acc = 0;
442 for (auto& [name, properties] : fQuantity) {
443 std::string value = run.ReplaceMetadataMembers(properties.metadata);
444 const Double_t val = REST_StringHelper::StringToDouble(value);
445
446 if (properties.strategy == "accumulate") {
447 acc += val;
448 properties.value = StringWithPrecision(val, 2);
449 }
450
451 if (properties.strategy == "max")
452 if (properties.value.empty() || REST_StringHelper::StringToDouble(properties.value) < val)
453 properties.value = value;
454
455 if (properties.strategy == "min")
456 if (properties.value.empty() || REST_StringHelper::StringToDouble(properties.value) > val)
457 properties.value = value;
458
459 if (properties.strategy == "unique") {
460 if (properties.value.empty())
461 properties.value = value;
462 else if (properties.value != value) {
463 RESTWarning << "TRestDataSet::FileSelection. Relevant quantity retrieval." << RESTendl;
464 RESTWarning << "A unique metadata member used for the `" << name
465 << "` quantity is not unique!!" << RESTendl;
466 RESTWarning << "Pre-registered value : " << properties.value << " New value : " << value
467 << RESTendl;
468 }
469 }
470
471 if (properties.strategy == "last") properties.value = value;
472 }
473
474 if (run.GetStartTimestamp() < fStartTime) fStartTime = run.GetStartTimestamp();
475
476 if (run.GetEndTimestamp() > fEndTime) fEndTime = run.GetEndTimestamp();
477
478 fTotalDuration += run.GetEndTimestamp() - run.GetStartTimestamp();
479 fFileSelection.push_back(file);
480 }
481 std::cout << std::endl;
482
483 return fFileSelection;
484}
485
492ROOT::RDF::RNode TRestDataSet::MakeCut(const TRestCut* cut) {
493 auto df = fDataSet;
494
495 if (cut == nullptr) return df;
496
497 auto paramCut = cut->GetParamCut();
498 auto obsList = df.GetColumnNames();
499 for (const auto& [param, condition] : paramCut) {
500 if (std::find(obsList.begin(), obsList.end(), param) != obsList.end()) {
501 std::string pCut = param + condition;
502 RESTDebug << "Applying cut " << pCut << RESTendl;
503 df = df.Filter(pCut);
504 } else {
505 RESTWarning << " Cut observable " << param << " not found in observable list, skipping..."
506 << RESTendl;
507 }
508 }
509
510 auto cutString = cut->GetCutStrings();
511 for (const auto& pCut : cutString) {
512 bool added = false;
513 for (const auto& obs : obsList) {
514 if (pCut.find(obs) != std::string::npos) {
515 RESTDebug << "Applying cut " << pCut << RESTendl;
516 df = df.Filter(pCut);
517 added = true;
518 break;
519 }
520 }
521
522 if (!added) {
523 RESTWarning << " Cut string " << pCut << " not found in observable list, skipping..." << RESTendl;
524 }
525 }
526
527 return df;
528}
529
542ROOT::RDF::RNode TRestDataSet::DefineColumn(const std::string& columnName, const std::string& formula) {
543 auto df = fDataSet;
544
545 std::string evalFormula = formula;
546 for (auto const& [name, properties] : fQuantity)
547 evalFormula = REST_StringHelper::Replace(evalFormula, name, properties.value);
548
549 df = df.Define(columnName, evalFormula);
550
551 return df;
552}
553
559
560 RESTMetadata << " - StartTime : " << REST_StringHelper::ToDateTimeString(fStartTime) << RESTendl;
561 RESTMetadata << " - EndTime : " << REST_StringHelper::ToDateTimeString(fEndTime) << RESTendl;
562 RESTMetadata << " - Path : " << TRestTools::SeparatePathAndName(fFilePattern).first << RESTendl;
563 RESTMetadata << " - File pattern : " << TRestTools::SeparatePathAndName(fFilePattern).second << RESTendl;
564 RESTMetadata << " " << RESTendl;
565 RESTMetadata << " - Accumulated run time (seconds) : " << fTotalDuration << RESTendl;
566 RESTMetadata << " - Accumulated run time (hours) : " << fTotalDuration / 3600. << RESTendl;
567 RESTMetadata << " - Accumulated run time (days) : " << fTotalDuration / 3600. / 24. << RESTendl;
568
569 RESTMetadata << " " << RESTendl;
570
571 if (!fObservablesList.empty()) {
572 RESTMetadata << " Single observables added:" << RESTendl;
573 RESTMetadata << " -------------------------" << RESTendl;
574 for (const auto& l : fObservablesList) RESTMetadata << " - " << l << RESTendl;
575
576 RESTMetadata << " " << RESTendl;
577 }
578
579 if (!fProcessObservablesList.empty()) {
580 RESTMetadata << " Process observables added: " << RESTendl;
581 RESTMetadata << " -------------------------- " << RESTendl;
582 for (const auto& l : fProcessObservablesList) RESTMetadata << " - " << l << RESTendl;
583
584 RESTMetadata << " " << RESTendl;
585 }
586
587 if (!fFilterMetadata.empty()) {
588 RESTMetadata << " Metadata filters: " << RESTendl;
589 RESTMetadata << " ----------------- " << RESTendl;
590 RESTMetadata << " - StartTime : " << fFilterStartTime << RESTendl;
591 RESTMetadata << " - EndTime : " << fFilterEndTime << RESTendl;
592 int n = 0;
593 for (const auto& mdFilter : fFilterMetadata) {
594 RESTMetadata << " - " << mdFilter << ".";
595
596 if (!fFilterContains[n].empty()) RESTMetadata << " Contains: " << fFilterContains[n];
597 if (fFilterGreaterThan[n] != -1) RESTMetadata << " Greater than: " << fFilterGreaterThan[n];
598 if (fFilterLowerThan[n] != -1) RESTMetadata << " Lower than: " << fFilterLowerThan[n];
599 if (fFilterEqualsTo[n] != -1) RESTMetadata << " Equals to: " << fFilterEqualsTo[n];
600
601 RESTMetadata << RESTendl;
602 n++;
603 }
604
605 RESTMetadata << " " << RESTendl;
606 }
607
608 if (!fQuantity.empty()) {
609 RESTMetadata << " Relevant quantities: " << RESTendl;
610 RESTMetadata << " -------------------- " << RESTendl;
611
612 for (auto const& [name, properties] : fQuantity) {
613 RESTMetadata << " - Name : " << name << ". Value : " << properties.value
614 << ". Strategy: " << properties.strategy << RESTendl;
615 RESTMetadata << " - Metadata: " << properties.metadata << RESTendl;
616 RESTMetadata << " - Description: " << properties.description << RESTendl;
617 RESTMetadata << " " << RESTendl;
618 }
619 }
620
621 if (!fColumnNameExpressions.empty()) {
622 RESTMetadata << " New columns added to generated dataframe: " << RESTendl;
623 RESTMetadata << " ---------------------------------------- " << RESTendl;
624 for (const auto& [cName, cExpression] : fColumnNameExpressions)
625 RESTMetadata << " - Name : " << cName << " Expression: " << cExpression << RESTendl;
626 }
627
628 if (fMergedDataset) {
629 RESTMetadata << " " << RESTendl;
630 RESTMetadata << "This is a combined dataset." << RESTendl;
631 RESTMetadata << " -------------------- " << RESTendl;
632 RESTMetadata << " - Relevant quantities have been removed!" << RESTendl;
633 RESTMetadata << " - Dataset metadata properties correspond to the first file in the list."
634 << RESTendl;
635 RESTMetadata << " " << RESTendl;
636 RESTMetadata << "List of imported files: " << RESTendl;
637 RESTMetadata << " -------------------- " << RESTendl;
638 for (const auto& fn : fImportedFiles) RESTMetadata << " - " << fn << RESTendl;
639 }
640
641 RESTMetadata << "----" << RESTendl;
642}
643
649
651 TiXmlElement* filterDefinition = GetElement("filter");
652 while (filterDefinition != nullptr) {
653 std::string metadata = GetFieldValue("metadata", filterDefinition);
654 if (metadata.empty() || metadata == "Not defined") {
655 RESTError << "Filter key defined without metadata member!" << RESTendl;
656 exit(1);
657 }
658
659 fFilterMetadata.push_back(metadata);
660
661 std::string contains = GetFieldValue("contains", filterDefinition);
662 if (contains == "Not defined") contains = "";
663 Double_t greaterThan = StringToDouble(GetFieldValue("greaterThan", filterDefinition));
664 Double_t lowerThan = StringToDouble(GetFieldValue("lowerThan", filterDefinition));
665 Double_t equalsTo = StringToDouble(GetFieldValue("equalsTo", filterDefinition));
666
667 fFilterContains.push_back(contains);
668 fFilterGreaterThan.push_back(greaterThan);
669 fFilterLowerThan.push_back(lowerThan);
670 fFilterEqualsTo.push_back(equalsTo);
671
672 filterDefinition = GetNextElement(filterDefinition);
673 }
674
676 TiXmlElement* observablesDefinition = GetElement("observables");
677 while (observablesDefinition != nullptr) {
678 std::string observables = GetFieldValue("list", observablesDefinition);
679 if (observables.empty() || observables == "Not defined") {
680 RESTError << "<observables key does not contain a list!" << RESTendl;
681 exit(1);
682 }
683
684 std::vector<std::string> obsList = REST_StringHelper::Split(observables, ",");
685
686 fObservablesList.insert(fObservablesList.end(), obsList.begin(), obsList.end());
687
688 observablesDefinition = GetNextElement(observablesDefinition);
689 }
690
692 TiXmlElement* obsProcessDefinition = GetElement("processObservables");
693 while (obsProcessDefinition != nullptr) {
694 std::string observables = GetFieldValue("list", obsProcessDefinition);
695 if (observables.empty() || observables == "Not defined") {
696 RESTError << "<processObservables key does not contain a list!" << RESTendl;
697 exit(1);
698 }
699
700 std::vector<std::string> obsList = REST_StringHelper::Split(observables, ",");
701
702 for (const auto& l : obsList) fProcessObservablesList.push_back(l);
703
704 obsProcessDefinition = GetNextElement(obsProcessDefinition);
705 }
706
708 TiXmlElement* quantityDefinition = GetElement("quantity");
709 while (quantityDefinition != nullptr) {
710 std::string name = GetFieldValue("name", quantityDefinition);
711 if (name.empty() || name == "Not defined") {
712 RESTError << "<quantity key does not contain a name!" << RESTendl;
713 exit(1);
714 }
715
716 std::string metadata = GetFieldValue("metadata", quantityDefinition);
717 if (metadata.empty() || metadata == "Not defined") {
718 RESTError << "<quantity key does not contain a metadata value!" << RESTendl;
719 exit(1);
720 }
721
722 std::string strategy = GetFieldValue("strategy", quantityDefinition);
723 if (strategy.empty() || strategy == "Not defined") {
724 strategy = "unique";
725 }
726
727 std::string description = GetFieldValue("description", quantityDefinition);
728
729 RelevantQuantity quantity;
730 quantity.metadata = metadata;
731 quantity.strategy = strategy;
732 quantity.description = description;
733 quantity.value = "";
734
735 fQuantity[name] = quantity;
736
737 quantityDefinition = GetNextElement(quantityDefinition);
738 }
739
741 TiXmlElement* columnDefinition = GetElement("addColumn");
742 while (columnDefinition != nullptr) {
743 std::string name = GetFieldValue("name", columnDefinition);
744 if (name.empty() || name == "Not defined") {
745 RESTError << "<define key does not contain a name name!" << RESTendl;
746 exit(1);
747 }
748
749 std::string expression = GetFieldValue("expression", columnDefinition);
750 if (expression.empty() || expression == "Not defined") {
751 RESTError << "<addColumn key does not contain a expression value!" << RESTendl;
752 exit(1);
753 }
754
755 fColumnNameExpressions.push_back({name, expression});
756
757 columnDefinition = GetNextElement(columnDefinition);
758 }
759
760 fCut = (TRestCut*)InstantiateChildMetadata("TRestCut");
761}
762
776void TRestDataSet::Export(const std::string& filename) {
777 RESTInfo << "Exporting dataset" << RESTendl;
778 if (TRestTools::GetFileNameExtension(filename) == "txt" ||
779 TRestTools::GetFileNameExtension(filename) == "csv") {
780 std::vector<std::string> dataTypes;
781 for (int n = 0; n < fTree->GetListOfBranches()->GetEntries(); n++) {
782 std::string bName = fTree->GetListOfBranches()->At(n)->GetName();
783 std::string type = fTree->GetLeaf((TString)bName)->GetTypeName();
784 dataTypes.push_back(type);
785 if (type != "Double_t" && type != "Int_t") {
786 RESTError << "Branch name : " << bName << " is type : " << type << RESTendl;
787 RESTError << "Only Int_t and Double_t types are allowed for "
788 "exporting to ASCII table"
789 << RESTendl;
790 RESTError << "File will not be generated" << RESTendl;
791 return;
792 }
793 }
794
795 FILE* f = fopen(filename.c_str(), "wt");
797 fprintf(f, "### TRestDataSet generated file\n");
798 fprintf(f, "### \n");
799 fprintf(f, "### StartTime : %s\n", fFilterStartTime.c_str());
800 fprintf(f, "### EndTime : %s\n", fFilterEndTime.c_str());
801 fprintf(f, "###\n");
802 fprintf(f, "### Accumulated run time (seconds) : %lf\n", fTotalDuration);
803 fprintf(f, "### Accumulated run time (hours) : %lf\n", fTotalDuration / 3600.);
804 fprintf(f, "### Accumulated run time (days) : %lf\n", fTotalDuration / 3600. / 24.);
805 fprintf(f, "###\n");
806 fprintf(f, "### Data path : %s\n", TRestTools::SeparatePathAndName(fFilePattern).first.c_str());
807 fprintf(f, "### File pattern : %s\n", TRestTools::SeparatePathAndName(fFilePattern).second.c_str());
808 fprintf(f, "###\n");
809 if (!fFilterMetadata.empty()) {
810 fprintf(f, "### Metadata filters : \n");
811 int n = 0;
812 for (const auto& md : fFilterMetadata) {
813 fprintf(f, "### - %s.", md.c_str());
814 if (!fFilterContains[n].empty()) fprintf(f, " Contains: %s.", fFilterContains[n].c_str());
815 if (fFilterGreaterThan[n] != -1) fprintf(f, " Greater than: %6.3lf.", fFilterGreaterThan[n]);
816 if (fFilterLowerThan[n] != -1) fprintf(f, " Lower than: %6.3lf.", fFilterLowerThan[n]);
817 if (fFilterEqualsTo[n] != -1) fprintf(f, " Equals to: %6.3lf.", fFilterLowerThan[n]);
818 fprintf(f, "\n");
819 n++;
820 }
821 }
822 fprintf(f, "###\n");
823 fprintf(f, "### Relevant quantities: \n");
824 for (auto& [name, properties] : fQuantity) {
825 fprintf(f, "### - %s : %s - %s\n", name.c_str(), properties.value.c_str(),
826 properties.description.c_str());
827 }
828 fprintf(f, "###\n");
829 fprintf(f, "### Observables list: ");
830 for (int n = 0; n < fTree->GetListOfBranches()->GetEntries(); n++) {
831 std::string bName = fTree->GetListOfBranches()->At(n)->GetName();
832 fprintf(f, " %s", bName.c_str());
833 }
834 fprintf(f, "\n");
835 fprintf(f, "###\n");
836 fprintf(f, "### Data starts here\n");
837
838 auto obsNames = fDataSet.GetColumnNames();
839 std::string obsListStr = "";
840 for (const auto& l : obsNames) {
841 if (!obsListStr.empty()) obsListStr += ":";
842 obsListStr += l;
843 }
844
845 // We do this so that later we can recover the values using TTree::GetVal
846 fTree->Draw((TString)obsListStr, "", "goff");
847
848 for (unsigned int n = 0; n < fTree->GetEntries(); n++) {
849 for (unsigned int m = 0; m < GetNumberOfBranches(); m++) {
850 std::string bName = fTree->GetListOfBranches()->At(m)->GetName();
851 if (m > 0) fprintf(f, "\t");
852 if (dataTypes[m] == "Double_t")
853 if (bName == "timeStamp")
854 fprintf(f, "%010.0lf", fTree->GetVal(m)[n]);
855 else
856 fprintf(f, "%05.3e", fTree->GetVal(m)[n]);
857 else
858 fprintf(f, "%06d", (Int_t)fTree->GetVal(m)[n]);
859 }
860 fprintf(f, "\n");
861 }
862 fclose(f);
863
864 return;
865 } else if (TRestTools::GetFileNameExtension(filename) == "root") {
866 fDataSet.Snapshot("AnalysisTree", filename);
867
868 TFile* f = TFile::Open(filename.c_str(), "UPDATE");
869 this->Write();
870 f->Close();
871 } else {
872 RESTWarning << "TRestDataSet::Export. Extension " << TRestTools::GetFileNameExtension(filename)
873 << " not recognized" << RESTendl;
874 }
875}
876
881 SetName(dS.GetName());
882 fFilterStartTime = dS.GetFilterStartTime();
883 fFilterEndTime = dS.GetFilterEndTime();
884 fStartTime = dS.GetStartTime();
885 fEndTime = dS.GetEndTime();
886 fFilePattern = dS.GetFilePattern();
887 fObservablesList = dS.GetObservablesList();
889 fProcessObservablesList = dS.GetProcessObservablesList();
890 fFilterMetadata = dS.GetFilterMetadata();
891 fFilterContains = dS.GetFilterContains();
892 fFilterGreaterThan = dS.GetFilterGreaterThan();
893 fFilterLowerThan = dS.GetFilterLowerThan();
894 fFilterEqualsTo = dS.GetFilterEqualsTo();
895 fQuantity = dS.GetQuantity();
898 fCut = dS.GetCut();
899
900 return *this;
901}
902
908void TRestDataSet::Import(const std::string& fileName) {
909 if (TRestTools::GetFileNameExtension(fileName) != "root") {
910 RESTError << "Datasets can only be imported from root files" << RESTendl;
911 return;
912 }
913
914 TRestDataSet* dS = nullptr;
915 TFile* file = TFile::Open(fileName.c_str(), "READ");
916 if (file != nullptr) {
917 TIter nextkey(file->GetListOfKeys());
918 TKey* key;
919 while ((key = (TKey*)nextkey())) {
920 std::string kName = key->GetClassName();
921 if (REST_Reflection::GetClassQuick(kName.c_str()) != nullptr &&
922 REST_Reflection::GetClassQuick(kName.c_str())->InheritsFrom("TRestDataSet")) {
923 dS = file->Get<TRestDataSet>(key->GetName());
925 dS->PrintMetadata();
926 *this = *dS;
927 }
928 }
929 }
930
931 if (dS == nullptr) {
932 RESTError << fileName << " is not a valid dataSet" << RESTendl;
933 return;
934 }
935
936 ROOT::EnableImplicitMT();
937
938 fDataSet = ROOT::RDataFrame("AnalysisTree", fileName);
939
940 fTree = (TChain*)file->Get("AnalysisTree");
941}
942
952void TRestDataSet::Import(std::vector<std::string> fileNames) {
953 for (const auto& fN : fileNames)
954 if (TRestTools::GetFileNameExtension(fN) != "root") {
955 RESTError << "Datasets can only be imported from root files" << RESTendl;
956 return;
957 }
958
959 if (fileNames.size() == 0) return;
960
961 TFile* file = TFile::Open(fileNames[0].c_str(), "READ");
962 if (file != nullptr) {
963 TIter nextkey(file->GetListOfKeys());
964 TKey* key;
965 while ((key = (TKey*)nextkey())) {
966 std::string kName = key->GetClassName();
967 if (REST_Reflection::GetClassQuick(kName.c_str()) != nullptr &&
968 REST_Reflection::GetClassQuick(kName.c_str())->InheritsFrom("TRestDataSet")) {
969 TRestDataSet* dS = file->Get<TRestDataSet>(key->GetName());
971 dS->PrintMetadata();
972 *this = *dS;
973 }
974 }
975 } else {
976 RESTError << "Cannot open " << fileNames[0] << RESTendl;
977 exit(1);
978 }
979
980 RESTInfo << "Opening list of files. First file: " << fileNames[0] << RESTendl;
981 fDataSet = ROOT::RDataFrame("AnalysisTree", fileNames);
982
983 if (fTree != nullptr) {
984 delete fTree;
985 fTree = nullptr;
986 }
987 fTree = new TChain("AnalysisTree");
988
989 for (const auto& fN : fileNames) fTree->Add((TString)fN);
990
991 fMergedDataset = true;
992 fImportedFiles = fileNames;
993
994 fQuantity.clear();
995}
std::vector< std::string > GetObservableNames()
It returns a vector with strings containing all the observables that exist in the analysis tree.
A class to help on cuts definitions. To be used with TRestAnalysisTree.
Definition: TRestCut.h:31
It allows to group a number of runs that satisfy given metadata conditions.
Definition: TRestDataSet.h:34
std::vector< std::string > fFilterContains
If not empty it will check if the metadata member contains the string.
Definition: TRestDataSet.h:70
virtual std::vector< std::string > FileSelection()
Function to determine the filenames that satisfy the dataset conditions.
std::vector< Double_t > fFilterLowerThan
If the corresponding element is not empty it will check if the metadata member is lower.
Definition: TRestDataSet.h:76
void PrintMetadata() override
Prints on screen the information about the metadata members of TRestDataSet.
TChain * fTree
A pointer to the generated tree.
Definition: TRestDataSet.h:112
std::vector< std::string > fProcessObservablesList
It contains a list of the process where all observables should be added.
Definition: TRestDataSet.h:64
void Import(const std::string &fileName)
This function imports metadata from a root file it import metadata info from the previous dataSet whi...
std::map< std::string, RelevantQuantity > fQuantity
The properties of a relevant quantity that we want to store together with the dataset.
Definition: TRestDataSet.h:82
ROOT::RDF::RNode fDataSet
The resulting RDF::RNode object after initialization.
Definition: TRestDataSet.h:109
std::vector< std::pair< std::string, std::string > > fColumnNameExpressions
A list of new columns together with its corresponding expressions added to the dataset.
Definition: TRestDataSet.h:106
ROOT::RDF::RNode DefineColumn(const std::string &columnName, const std::string &formula)
This function will add a new column to the RDataFrame using the same scheme as the usual RDF::Define ...
Double_t fEndTime
TimeStamp for the end time of the last file.
Definition: TRestDataSet.h:97
size_t GetNumberOfBranches()
Number of variables (or observables)
Definition: TRestDataSet.h:142
TRestDataSet()
Default constructor.
Double_t GetTotalTimeInSeconds() const
It returns the accumulated run time in seconds.
Definition: TRestDataSet.h:148
ROOT::RDF::RNode MakeCut(const TRestCut *cut)
This function apply a TRestCut to the dataframe and returns a dataframe with the applied cuts....
void GenerateDataSet()
This function generates the data frame with the filelist and column names (or observables) that have ...
TRestCut * fCut
Parameter cuts over the selected dataset.
Definition: TRestDataSet.h:85
std::string fFilterStartTime
All the selected runs will have a starting date after fStartTime.
Definition: TRestDataSet.h:52
std::vector< std::string > fFilterMetadata
A list of metadata members where filters will be applied.
Definition: TRestDataSet.h:67
std::vector< std::string > fFileSelection
A list populated by the FileSelection method using the conditions of the dataset.
Definition: TRestDataSet.h:91
std::vector< std::string > GetFileSelection()
It returns a list of the files that have been finally selected.
Definition: TRestDataSet.h:145
std::string fFilterEndTime
All the selected runs will have an ending date before fEndTime.
Definition: TRestDataSet.h:55
Double_t fStartTime
TimeStamp for the start time of the first file.
Definition: TRestDataSet.h:94
std::vector< std::string > fObservablesList
It contains a list of the observables that will be added to the final tree or exported file.
Definition: TRestDataSet.h:61
Bool_t fMergedDataset
It keeps track if the generated dataset is a pure dataset or a merged one.
Definition: TRestDataSet.h:100
void Initialize() override
This function initialize different parameters from the TRestDataSet.
std::vector< std::string > fImportedFiles
The list of dataset files imported.
Definition: TRestDataSet.h:103
Double_t fTotalDuration
The total integrated run time of selected files.
Definition: TRestDataSet.h:88
std::string fFilePattern
A glob file pattern that must be satisfied by all files.
Definition: TRestDataSet.h:58
std::vector< Double_t > fFilterGreaterThan
If the corresponding element is not empty it will check if the metadata member is greater.
Definition: TRestDataSet.h:73
std::vector< Double_t > fFilterEqualsTo
If the corresponding element is not empty it will check if the metadata member is equal.
Definition: TRestDataSet.h:79
void InitFromConfigFile() override
Initialization of specific TRestDataSet members through an RML file.
void Export(const std::string &filename)
It will generate an output file with the dataset compilation. Only the selected branches and the file...
TRestDataSet & operator=(TRestDataSet &dS)
Operator to copy TRestDataSet metadata.
~TRestDataSet()
Default destructor.
A base class for any REST metadata class.
Definition: TRestMetadata.h:70
virtual void PrintMetadata()
Implemented it in the derived metadata class to print out specific metadata information.
endl_t RESTendl
Termination flag object for TRestStringOutput.
TiXmlElement * GetElement(std::string eleDeclare, TiXmlElement *e=nullptr)
Get an xml element from a given parent element, according to its declaration.
Int_t LoadConfigFromFile(const std::string &configFilename, const std::string &sectionName="")
Give the file name, find out the corresponding section. Then call the main starter.
TRestMetadata * InstantiateChildMetadata(int index, std::string pattern="")
This method will retrieve a new TRestMetadata instance of a child element of the present TRestMetadat...
virtual void InitFromConfigFile()
To make settings from rml file. This method must be implemented in the derived class.
TRestStringOutput::REST_Verbose_Level GetVerboseLevel()
returns the verboselevel in type of REST_Verbose_Level enumerator
std::string GetFieldValue(std::string parName, TiXmlElement *e)
Returns the field value of an xml element which has the specified name.
void SetSectionName(std::string sName)
set the section name, clear the section content
std::string fConfigFileName
Full name of the rml file.
virtual Int_t Write(const char *name=nullptr, Int_t option=0, Int_t bufsize=0)
overwriting the write() method with fStore considered
TiXmlElement * GetNextElement(TiXmlElement *e)
Get the next sibling xml element of this element, with same eleDeclare.
Data provider and manager in REST.
Definition: TRestRun.h:18
std::string ReplaceMetadataMembers(const std::string &instr, Int_t precision=8)
It will replace the data members contained inside the string given as input. The data members in the ...
Definition: TRestRun.cxx:1652
@ REST_Info
+show most of the information for each steps
static std::pair< std::string, std::string > SeparatePathAndName(const std::string &fullname)
Separate path and filename in a full path+filename string, returns a pair of string.
Definition: TRestTools.cxx:759
static std::string GetFileNameExtension(const std::string &fullname)
Gets the file extension as the substring found after the latest ".".
Definition: TRestTools.cxx:769
static std::vector< std::string > GetFilesMatchingPattern(std::string pattern)
Returns a list of files whose name match the pattern string. Key word is "*". e.g....
Definition: TRestTools.cxx:918
TClass * GetClassQuick(std::string type)
time_t StringToTimeStamp(std::string time)
A method to convert a date/time formatted string to a timestamp.
std::vector< std::string > Split(std::string in, std::string separator, bool allowBlankString=false, bool removeWhiteSpaces=false, int startPos=-1)
Split the input string according to the given separator. Returning a vector of fragments.
Double_t StringToDouble(std::string in)
Gets a double from a string.
std::string ToDateTimeString(time_t time)
Format time_t into string.
std::string Replace(std::string in, std::string thisString, std::string byThisString, size_t fromPosition=0, Int_t N=0)
Replace every occurences of thisSring by byThisString inside string in.
std::string metadata
The associated metadata member used to register the relevant quantity.
Definition: TRestDataSet.h:38
std::string description
A user given description that can be used to define the relevant quantity.
Definition: TRestDataSet.h:44
std::string strategy
It determines how to produce the relevant quantity (accumulate/unique/last/max/min)
Definition: TRestDataSet.h:41
std::string value
The quantity value.
Definition: TRestDataSet.h:47