REST-for-Physics  v2.3
Rare Event Searches ToolKit for Physics
TRestDataSetPlot.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
293
294#include "TRestDataSetPlot.h"
295
296#include "TCanvas.h"
297#include "TDirectory.h"
298#include "TRestTools.h"
299#include "TStyle.h"
300
301ClassImp(TRestDataSetPlot);
302
307
311TRestDataSetPlot::TRestDataSetPlot(const char* configFilename, std::string name)
312 : TRestMetadata(configFilename) {
313 Initialize();
316}
317
322
327void TRestDataSetPlot::Initialize() { SetSectionName(this->ClassName()); }
328
334
335 if (fDataSetName == "") fDataSetName = GetParameter("inputFileName", "");
336 if (fOutputFileName == "") fOutputFileName = GetParameter("outputFileName", "");
337
338 fCut = ReadCut(fCut);
339
340 ReadPlotInfo();
342}
343
350TRestCut* TRestDataSetPlot::ReadCut(TRestCut* cut, TiXmlElement* ele) {
351 TiXmlElement* cutele = GetElement("addCut", ele);
352 while (cutele != nullptr) {
353 std::string cutName = GetParameter("name", cutele, "");
354 if (!cutName.empty()) {
355 if (cut == nullptr) {
356 cut = (TRestCut*)InstantiateChildMetadata("TRestCut", cutName);
357 } else {
358 cut->AddCut((TRestCut*)InstantiateChildMetadata("TRestCut", cutName));
359 }
360 }
361 cutele = GetNextElement(cutele);
362 }
363
364 return cut;
365}
366
372 if (!fPanels.empty()) {
373 RESTWarning << "Plot metadata already initialized" << RESTendl;
374 }
375
376 TiXmlElement* panelele = GetElement("panel");
377 while (panelele != nullptr) {
378 std::string active = GetParameter("value", panelele, "ON");
379 if (ToUpper(active) != "ON") continue;
380
381 PanelInfo panel;
382 panel.font_size = StringToDouble(GetParameter("font_size", panelele, "0.1"));
383 panel.precision = StringToInteger(GetParameter("precision", panelele, "2"));
384 panel.delimiter = GetParameter("delimiter", panelele, ": ");
385
386 panel.panelCut = ReadCut(panel.panelCut, panelele);
387
388 TiXmlElement* labelele = GetElement("variable", panelele);
389 while (labelele != nullptr) {
390 std::array<std::string, 3> label;
391 label[0] = GetParameter("value", labelele, "");
392 label[1] = GetParameter("label", labelele, "");
393 label[2] = GetParameter("units", labelele, "");
394 double posX = StringToDouble(GetParameter("x", labelele, "0.1"));
395 double posY = StringToDouble(GetParameter("y", labelele, "0.1"));
396
397 panel.variablePos.push_back(std::make_pair(label, TVector2(posX, posY)));
398
399 labelele = GetNextElement(labelele);
400 }
401 TiXmlElement* metadata = GetElement("metadata", panelele);
402 while (metadata != nullptr) {
403 std::array<std::string, 3> label;
404 label[0] = GetParameter("value", metadata, "");
405 label[1] = GetParameter("label", metadata, "");
406 label[2] = GetParameter("units", metadata, "");
407 double posX = StringToDouble(GetParameter("x", metadata, "0.1"));
408 double posY = StringToDouble(GetParameter("y", metadata, "0.1"));
409
410 panel.metadataPos.push_back(std::make_pair(label, TVector2(posX, posY)));
411
412 metadata = GetNextElement(metadata);
413 }
414 TiXmlElement* observable = GetElement("observable", panelele);
415 while (observable != nullptr) {
416 std::array<std::string, 3> label;
417 label[0] = GetParameter("value", observable, "");
418 label[1] = GetParameter("label", observable, "");
419 label[2] = GetParameter("units", observable, "");
420 double posX = StringToDouble(GetParameter("x", observable, "0.1"));
421 double posY = StringToDouble(GetParameter("y", observable, "0.1"));
422
423 panel.obsPos.push_back(std::make_pair(label, TVector2(posX, posY)));
424
425 observable = GetNextElement(observable);
426 }
427 TiXmlElement* expression = GetElement("expression", panelele);
428 while (expression != nullptr) {
429 std::array<std::string, 4> label;
430 label[0] = GetParameter("value", expression, "");
431 label[1] = GetParameter("label", expression, "");
432 label[2] = GetParameter("units", expression, "");
433 label[3] = GetParameter("precision", expression, IntegerToString(panel.precision));
434 double posX = StringToDouble(GetParameter("x", expression, "0.1"));
435 double posY = StringToDouble(GetParameter("y", expression, "0.1"));
436
437 panel.expPos.push_back(std::make_pair(label, TVector2(posX, posY)));
438
439 expression = GetNextElement(expression);
440 }
441
442 fPanels.push_back(panel);
443 panelele = GetNextElement(panelele);
444 }
445}
446
452 if (!fPlots.empty()) {
453 RESTWarning << "Plot metadata already initialized" << RESTendl;
454 return;
455 }
456
457 TiXmlElement* plotele = GetElement("plot");
458 while (plotele != nullptr) {
459 std::string active = GetParameter("value", plotele, "ON");
460 if (ToUpper(active) != "ON") continue;
461 int N = fPlots.size();
462 PlotInfo plot;
463 plot.name = RemoveWhiteSpaces(GetParameter("name", plotele, "plot_" + ToString(N)));
464 plot.title = GetParameter("title", plotele, plot.name);
465 plot.logX = StringToBool(GetParameter("logX", plotele, "false"));
466 plot.logY = StringToBool(GetParameter("logY", plotele, "false"));
467 plot.logZ = StringToBool(GetParameter("logZ", plotele, "false"));
468 plot.gridY = StringToBool(GetParameter("gridY", plotele, "false"));
469 plot.gridX = StringToBool(GetParameter("gridX", plotele, "false"));
470 plot.normalize = StringToDouble(GetParameter("norm", plotele, ""));
471 plot.scale = GetParameter("scale", plotele, "");
472 plot.labelX = GetParameter("xlabel", plotele, "");
473 plot.labelY = GetParameter("ylabel", plotele, "");
474 plot.marginBottom = StringToDouble(GetParameter("marginBottom", plotele, "0.15"));
475 plot.marginTop = StringToDouble(GetParameter("marginTop", plotele, "0.07"));
476 plot.marginLeft = StringToDouble(GetParameter("marginLeft", plotele, "0.25"));
477 plot.marginRight = StringToDouble(GetParameter("marginRight", plotele, "0.1"));
478 plot.legendOn = StringToBool(GetParameter("legend", plotele, "OFF"));
479 plot.stackDrawOption = GetParameter("stackOption", plotele, "nostack");
480 // plot.annotationOn = StringToBool(GetParameter("annotation", plotele, "OFF"));
481 plot.xOffset = StringToDouble(GetParameter("xOffset", plotele, "0"));
482 plot.yOffset = StringToDouble(GetParameter("yOffset", plotele, "0"));
483 plot.timeDisplay = StringToBool(GetParameter("timeDisplay", plotele, "OFF"));
484 plot.save = RemoveWhiteSpaces(GetParameter("save", plotele, ""));
485
486 TiXmlElement* histele = GetElement("histo", plotele);
487 if (histele == nullptr) {
488 histele = plotele;
489 }
490 while (histele != nullptr) {
491 HistoInfo hist;
492 hist.name = RemoveWhiteSpaces(GetParameter("name", histele, plot.name));
493 hist.drawOption = GetParameter("option", histele, "colz");
494 TiXmlElement* varele = GetElement("variable", histele);
495 while (varele != nullptr) {
496 hist.variable.push_back(GetParameter("name", varele));
497 std::string rangeStr = GetParameter("range", varele);
498 hist.range.push_back(StringTo2DVector(rangeStr));
499 hist.nBins.push_back(StringToInteger(GetParameter("nbins", varele)));
500 varele = GetNextElement(varele);
501 }
502
503 hist.lineColor = GetIDFromMapString(ColorIdMap, GetParameter("lineColor", histele, "602"));
504 hist.lineWidth = StringToInteger(GetParameter("lineWidth", histele, "1"));
505 hist.lineStyle = GetIDFromMapString(LineStyleMap, GetParameter("lineStyle", histele, "1"));
506 hist.fillStyle = GetIDFromMapString(FillStyleMap, GetParameter("fillStyle", histele, "1001"));
507 hist.fillColor = GetIDFromMapString(ColorIdMap, GetParameter("fillColor", histele, "0"));
508 hist.statistics = StringToBool(GetParameter("stats", histele, "OFF"));
509 // hist.weight = GetParameter("weight", histele, "");
510 hist.histoCut = ReadCut(hist.histoCut, histele);
511 plot.histos.push_back(hist);
512
513 if (histele == plotele) {
514 break;
515 }
516 histele = GetNextElement(histele);
517 }
518
519 fPlots.push_back(plot);
520 plotele = GetNextElement(plotele);
521 }
522}
523
530 std::vector<std::string> obsList;
531
532 // Add obserbables from global cut
533 if (fCut != nullptr) {
534 const auto paramCut = fCut->GetParamCut();
535 for (const auto& [param, condition] : paramCut) {
536 obsList.push_back(param);
537 }
538 }
539
540 // Add obserbables from plot info, both variables and cuts
541 for (const auto& plots : fPlots) {
542 for (const auto& hist : plots.histos) {
543 for (const auto& var : hist.variable) {
544 obsList.push_back(var);
545 }
546 if (hist.histoCut == nullptr) continue;
547 const auto paramCut = hist.histoCut->GetParamCut();
548 for (const auto& [param, condition] : paramCut) {
549 obsList.push_back(param);
550 }
551 }
552 }
553
554 std::map<std::string, TRestDataSet::RelevantQuantity> quantity;
555
556 for (auto& panel : fPanels) {
557 // Add metadata and observables from expression key from panel info
558 for (auto& [key, posLabel] : panel.expPos) {
559 // look for metadata which are surrounded by [] but not [[]] (variables)
560 auto&& [exp, label, units, precision] = key;
561 std::string text = exp;
562 while (text.find_last_of('[') != std::string::npos) {
563 int squareBracketCorrector = 0;
564 size_t posOpen = text.find_last_of('[');
565 size_t posClose = text.find_first_of(']', posOpen);
566 if (posOpen != 0) {
567 if (text[posOpen - 1] == '[') {
568 squareBracketCorrector = 1;
569 }
570 }
571 std::string varOrMeta = text.substr(posOpen - squareBracketCorrector,
572 posClose + 1 - posOpen + 2 * squareBracketCorrector);
573 if (squareBracketCorrector == 0) {
574 // Here varOrMeta is a metadata
575 // Add metadata to relevant quantity from the panel info
577 quant.metadata = varOrMeta;
578 quant.strategy = "unique";
579 quantity[label] = quant;
580 }
581 text = Replace(text, varOrMeta, "1");
582 }
583
584 // look for observables (characterized by having a _ in the name)
585 while (text.find("_") != std::string::npos) {
586 size_t pos_ = text.find("_");
587 size_t beginning = text.find_last_of(" -+*/)(^%", pos_) + 1;
588 size_t end = text.find_first_of(" -+*/)(^%", pos_);
589 std::string obs = text.substr(beginning, end - beginning);
590 text = Replace(text, obs, "1");
591 obsList.push_back(obs);
592 }
593
594 if (!(isAExpression(text) || isANumber(text)))
595 RESTWarning << "The expression " << exp
596 << " has not been correctly parsed into variables, metadata and observables"
597 << RESTendl;
598 }
599
600 // Add observables from observable key of panel info
601 for (auto& [key, posLabel] : panel.obsPos) {
602 auto&& [obs, label, units] = key;
603 obsList.push_back(obs);
604 }
605 // Add relevant quantity to metadata from the panel info
606 for (auto& [key, posLabel] : panel.metadataPos) {
607 auto&& [metadata, label, units] = key;
609 quant.metadata = metadata;
610 quant.strategy = "unique";
611 quantity[label] = quant;
612 }
613 }
614
615 // Remove duplicated observables if any
616 std::sort(obsList.begin(), obsList.end());
617 obsList.erase(std::unique(obsList.begin(), obsList.end()), obsList.end());
618 dataSet.SetFilePattern(fDataSetName);
619 dataSet.SetObservablesList(obsList);
620 dataSet.SetQuantity(quantity);
621 dataSet.GenerateDataSet();
622}
623
629 TRestDataSet dataSet;
630 dataSet.EnableMultiThreading(true);
631
632 // Import dataSet
633 dataSet.Import(fDataSetName);
634
635 // If dataSet is not valid, try to generate it, but note that this is deprecated
636 if (dataSet.GetTree() == nullptr) {
637 RESTWarning << "Cannot import dataSet, trying to generate it with pattern " << fDataSetName
638 << RESTendl;
639 RESTWarning << "Note that the generation of a dataSet inside TRestDataSetPlot is deplecated. Check "
640 "TRestDataSet documentation to generate a dataSet"
641 << RESTendl;
643 if (dataSet.GetTree() == nullptr) {
644 RESTError << "Cannot generate dataSet " << RESTendl;
645 exit(1);
646 }
647 }
648
649 // Perform the global cut over the dataSet
650 dataSet.SetDataFrame(dataSet.MakeCut(fCut));
651
652 TCanvas combinedCanvas(this->GetName(), this->GetName(), 0, 0, fCanvasSize.X(), fCanvasSize.Y());
653 combinedCanvas.Divide((Int_t)fCanvasDivisions.X(), (Int_t)fCanvasDivisions.Y(),
654 fCanvasDivisionMargins.X(), fCanvasDivisionMargins.Y());
655
656 gStyle->SetPalette(fPaletteStyle);
657
658 const double duration = dataSet.GetTotalTimeInSeconds();
659 const double startTime = dataSet.GetStartTime();
660 const double endTime = dataSet.GetEndTime();
661
662 // Fill general variables for the panel
663 std::map<std::string, std::string> paramMap;
664 paramMap["[[startTime]]"] = ToDateTimeString(startTime);
665 paramMap["[[endTime]]"] = ToDateTimeString(endTime);
666
667 // DataSet quantity is used to replace metadata parameters
668 const auto quantity = dataSet.GetQuantity();
669
670 int canvasIndex = 1;
671
672 for (auto& panel : fPanels) {
673 combinedCanvas.cd(canvasIndex);
674 // Gets a dataFrame with the panel cut
675 auto dataFrame = dataSet.MakeCut(panel.panelCut);
676 const int entries = *dataFrame.Count();
677 const double meanRate = entries / duration;
678 const double runLength = duration / 3600.;
679 paramMap["[[runLength]]"] = DoubleToString(runLength, "%.9e");
680 paramMap["[[entries]]"] = IntegerToString(entries);
681 paramMap["[[meanRate]]"] = DoubleToString(meanRate, "%.9e");
682
683 paramMap["[[cutNames]]"] = "";
684 paramMap["[[cuts]]"] = "";
685 if (fCut) {
686 for (const auto& cut : fCut->GetCuts()) {
687 if (paramMap["[[cutNames]]"].empty())
688 paramMap["[[cutNames]]"] += cut.GetName();
689 else
690 paramMap["[[cutNames]]"] += "," + (std::string)cut.GetName();
691 if (paramMap["[[cuts]]"].empty())
692 paramMap["[[cuts]]"] += cut.GetTitle();
693 else
694 paramMap["[[cuts]]"] += " && " + (std::string)cut.GetTitle();
695 }
696 }
697
698 paramMap["[[panelCutNames]]"] = "";
699 paramMap["[[panelCuts]]"] = "";
700 if (panel.panelCut) {
701 for (const auto& cut : panel.panelCut->GetCuts()) {
702 if (paramMap["[[panelCutNames]]"].empty())
703 paramMap["[[panelCutNames]]"] += cut.GetName();
704 else
705 paramMap["[[panelCutNames]]"] += "," + (std::string)cut.GetName();
706 if (paramMap["[[panelCuts]]"].empty())
707 paramMap["[[panelCuts]]"] += cut.GetTitle();
708 else
709 paramMap["[[panelCuts]]"] += " && " + (std::string)cut.GetTitle();
710 }
711 }
712
713 RESTInfo << "Global cuts: " << paramMap["[[cuts]]"] << RESTendl;
714 if (!paramMap["[[panelCuts]]"].empty())
715 RESTInfo << "Additional panel cuts: " << paramMap["[[panelCuts]]"] << RESTendl;
716
717 // Replace panel variables and generate a TLatex label
718 for (const auto& [key, posLabel] : panel.variablePos) {
719 auto&& [variable, label, units] = key;
720 bool found = false;
721 std::string var = variable;
722 if (!var.empty()) {
723 for (const auto& [param, val] : paramMap) {
724 if (var == param) {
725 size_t pos = 0;
726 var = Replace(var, param, val, pos);
727 found = true;
728 break;
729 }
730 }
731 if (!found) RESTWarning << "Variable " << variable << " not found" << RESTendl;
732 }
733 if (isANumber(var)) { // if it is a number, convert it to number to apply precision
734 if (var.find('.') == std::string::npos) {
735 int dblVar = StringToInteger(var);
736 var = StringWithPrecision(dblVar, panel.precision);
737 } else {
738 double dblVar = StringToDouble(var);
739 var = StringWithPrecision(dblVar, panel.precision);
740 }
741 }
742 std::string lab =
743 label + panel.delimiter.Data() + StringWithPrecision(var, panel.precision) + " " + units;
744 panel.text.emplace_back(new TLatex(posLabel.X(), posLabel.Y(), lab.c_str()));
745 }
746
747 // Replace metadata variables and generate a TLatex label
748 for (const auto& [key, posLabel] : panel.metadataPos) {
749 auto&& [metadata, label, units] = key;
750 std::string value = "";
751
752 for (const auto& [name, quant] : quantity) {
753 if (quant.metadata == metadata) value = quant.value;
754 }
755
756 if (value.empty()) {
757 RESTWarning << "Metadata quantity " << metadata << " not found in dataSet" << RESTendl;
758 continue;
759 }
760
761 std::string lab =
762 label + panel.delimiter.Data() + StringWithPrecision(value, panel.precision) + " " + units;
763 panel.text.emplace_back(new TLatex(posLabel.X(), posLabel.Y(), lab.c_str()));
764 }
765
766 // Replace observable variables and generate a TLatex label
767 for (const auto& [key, posLabel] : panel.obsPos) {
768 auto&& [obs, label, units] = key;
769 auto value = *dataFrame.Mean(obs);
770
771 std::string lab =
772 label + panel.delimiter.Data() + StringWithPrecision(value, panel.precision) + " " + units;
773 panel.text.emplace_back(new TLatex(posLabel.X(), posLabel.Y(), lab.c_str()));
774 }
775
776 // Replace any expression and generate TLatex label
777 for (const auto& [key, posLabel] : panel.expPos) {
778 auto&& [text, label, units, precision] = key;
779 std::string var = text;
780
781 // find and split the text into subtexts which are surrounded by {}
782 std::vector<std::string> subtexts;
783 while (var.find_last_of('{') != std::string::npos) {
784 size_t posOpen = var.find_last_of('{');
785 size_t posClose = var.find_first_of('}', posOpen);
786 if (posClose == std::string::npos) {
787 RESTWarning << "Unmatched { in expression: " << var << RESTendl;
788 break;
789 }
790 std::string subtext = var.substr(posOpen + 1, posClose - posOpen - 1);
791 subtexts.push_back(subtext);
792 // get rid of "{"+subtext+"}" from the var
793 var.erase(posOpen, posClose - posOpen + 1);
794 }
795 var = text; // reset var to the original text
796
797 // get precision formatting
798 std::vector<std::string> precisionParts;
799 for (const auto& part : Split(precision, ",", false, true)) {
800 precisionParts.push_back(part);
801 }
802 if (precisionParts.size() != subtexts.size()) {
803 RESTDebug << "Not enough precision values provided for the expression: `" << text
804 << "`. Using " << precisionParts.back() << " for last subtexts." << RESTendl;
805 precisionParts.resize(subtexts.size(), precisionParts.back()); // fill with last value
806 }
807
808 size_t precisionIndex = precisionParts.size() - 1;
809 for (const auto& subtext : subtexts) {
810 std::string subVar = subtext;
811 // replace variables
812 for (const auto& [param, val] : paramMap) {
813 subVar = Replace(subVar, param, val);
814 }
815 // replace metadata
816 for (const auto& [name, quant] : quantity) {
817 subVar = Replace(subVar, "[" + name + "]", quant.value); // metadata are surrounded by []
818 subVar = Replace(subVar, name, quant.value); // just in case ?
819 }
820 // replace observables
821 for (const auto& obs : dataFrame.GetColumnNames()) {
822 if (var.find(obs) == std::string::npos) continue;
823 // here there should be a checking that the mean(obs) can be calculated
824 // (checking obs data type?)
825 double value = *dataFrame.Mean(obs);
826 subVar = Replace(subVar, obs, DoubleToString(value));
827 }
828 subVar = Replace(subVar, "[", "(");
829 subVar = Replace(subVar, "]", ")");
830 subVar = EvaluateExpression(subVar);
831 if (isANumber(subVar)) {
832 double value = StringToDouble(subVar);
833 std::string prec = precisionParts[precisionIndex--];
834 if (prec.find('%') != std::string::npos) { // it is a format e.g. %.2f
835 subVar = DoubleToString(value, prec);
836 } else if (isANumber(prec)) { // it is a number
837 subVar = StringWithPrecision(value, StringToInteger(prec));
838 } else {
839 RESTWarning << "Unknown precision format: " << prec
840 << ". Using panels precision: " << panel.precision << RESTendl;
841 subVar = StringWithPrecision(value, panel.precision);
842 }
843 }
844 var = Replace(var, "{" + subtext + "}", subVar);
845 }
846
847 std::string lab = label + panel.delimiter.Data() + var + " " + units;
848 panel.text.emplace_back(new TLatex(posLabel.X(), posLabel.Y(), lab.c_str()));
849 }
850
851 // Draw the labels inside the pad
852 for (const auto& text : panel.text) {
853 text->SetTextColor(1);
854 text->SetTextSize(panel.font_size);
855 text->Draw("same");
856 }
857 canvasIndex++;
858 }
859
860 for (auto& plots : fPlots) {
861 // Histograms are added to a THStack and will be ploted later on
862 combinedCanvas.cd(canvasIndex);
863 plots.hs = new THStack(plots.name.c_str(), plots.title.c_str());
864 if (plots.legendOn) plots.legend = new TLegend(fLegendX1, fLegendY1, fLegendX2, fLegendY2);
866 for (auto& hist : plots.histos) {
867 auto dataFrame = dataSet.MakeCut(hist.histoCut);
868 if (hist.variable.front() == "timeStamp") {
869 hist.range.front().SetX(startTime);
870 hist.range.front().SetY(endTime);
871 }
872 // 1-D Histograms
873 if (hist.variable.size() == 1) {
874 auto histo = dataFrame.Histo1D({hist.name.c_str(), hist.name.c_str(), hist.nBins.front(),
875 hist.range.front().X(), hist.range.front().Y()},
876 hist.variable.front());
877 hist.histo = static_cast<TH1*>(histo->DrawClone());
878 // 2-D Histograms
879 } else if (hist.variable.size() == 2) {
880 auto histo = dataFrame.Histo2D(
881 {hist.name.c_str(), hist.name.c_str(), hist.nBins.front(), hist.range.front().X(),
882 hist.range.front().Y(), hist.nBins.back(), hist.range.back().X(), hist.range.back().Y()},
883 hist.variable.front(), hist.variable.back());
884 hist.histo = static_cast<TH1*>(histo->DrawClone());
885 } else {
886 RESTError << "Only 1D or 2D histograms are supported " << RESTendl;
887 continue;
888 }
889 hist.histo->SetLineColor(hist.lineColor);
890 hist.histo->SetLineWidth(hist.lineWidth);
891 hist.histo->SetLineStyle(hist.lineStyle);
892 hist.histo->SetFillColor(hist.fillColor);
893 hist.histo->SetFillStyle(hist.fillStyle);
894 // If stats are on histos must we drawn
895 if (hist.statistics) {
896 hist.histo->SetStats(true);
897 hist.histo->Draw();
898 combinedCanvas.Update();
899 } else {
900 hist.histo->SetStats(false);
901 }
902 // Normalize histos
903 if (plots.normalize > 0) {
904 const double integral = hist.histo->Integral();
905 if (integral > 0) hist.histo->Scale(plots.normalize / integral);
906 }
907 // Scale histos
908 if (plots.scale != "") {
909 std::string inputScale = plots.scale;
910 double binSize = hist.histo->GetXaxis()->GetBinWidth(1);
911 double entries = hist.histo->GetEntries();
912 double runLength = dataSet.GetTotalTimeInSeconds() / 3600.; // in hours
913 double integral = hist.histo->Integral("width");
914
915 inputScale = Replace(inputScale, "binSize", DoubleToString(binSize));
916 inputScale = Replace(inputScale, "entries", DoubleToString(entries));
917 inputScale = Replace(inputScale, "runLength", DoubleToString(runLength));
918 inputScale = Replace(inputScale, "integral", DoubleToString(integral));
919
920 std::string scale = "1./(" + inputScale + ")";
921 hist.histo->Scale(StringToDouble(EvaluateExpression(scale))); // -1 if 'scale' isn't valid
922 }
923
924 // Add histos to the THStack
925 plots.hs->Add(hist.histo, hist.drawOption.c_str());
926 // Add histos to the legend
927 if (plots.legend != nullptr) plots.legend->AddEntry(hist.histo, hist.histo->GetName(), "lf");
928 }
929 }
930
931 // This function do the actual drawing of the THStack with the different options
932 for (auto& plots : fPlots) {
933 if (plots.hs == nullptr) continue;
934 // TPad parameters
935 TPad* targetPad = (TPad*)combinedCanvas.cd(canvasIndex);
936 targetPad->SetLogx(plots.logX);
937 targetPad->SetLogy(plots.logY);
938 targetPad->SetLogz(plots.logZ);
939 targetPad->SetGridx(plots.gridX);
940 targetPad->SetGridy(plots.gridY);
941 targetPad->SetLeftMargin(plots.marginLeft);
942 targetPad->SetRightMargin(plots.marginRight);
943 targetPad->SetBottomMargin(plots.marginBottom);
944 targetPad->SetTopMargin(plots.marginTop);
945
946 // HStack draw parameters
947 plots.hs->Draw(plots.stackDrawOption.c_str());
948 plots.hs->GetXaxis()->SetTitle(plots.labelX.c_str());
949 plots.hs->GetYaxis()->SetTitle(plots.labelY.c_str());
950 plots.hs->GetXaxis()->SetLabelSize(1.1 * plots.hs->GetXaxis()->GetLabelSize());
951 plots.hs->GetYaxis()->SetLabelSize(1.1 * plots.hs->GetYaxis()->GetLabelSize());
952 plots.hs->GetXaxis()->SetTitleSize(1.1 * plots.hs->GetXaxis()->GetTitleSize());
953 plots.hs->GetYaxis()->SetTitleSize(1.1 * plots.hs->GetYaxis()->GetTitleSize());
954
955 if (plots.timeDisplay) plots.hs->GetXaxis()->SetTimeDisplay(1);
956 if (plots.legend != nullptr) plots.legend->Draw();
957
958 targetPad->Update();
959 combinedCanvas.Update();
960 canvasIndex++;
961 }
962
963 // Preview plot. User can make some changed before saving
964 if (!REST_Display_CompatibilityMode && fPreviewPlot) {
965 combinedCanvas.Resize();
966 GetChar();
967 }
968
969 // Save single pads if save is marked
970 for (auto& plots : fPlots) {
971 if (plots.save.empty()) continue;
972 std::unique_ptr<TCanvas> canvas(new TCanvas());
973 canvas->SetLogx(plots.logX);
974 canvas->SetLogy(plots.logY);
975 canvas->SetLogz(plots.logZ);
976 canvas->SetGridx(plots.gridX);
977 canvas->SetGridy(plots.gridY);
978 canvas->SetLeftMargin(plots.marginLeft);
979 canvas->SetRightMargin(plots.marginRight);
980 canvas->SetBottomMargin(plots.marginBottom);
981 canvas->SetTopMargin(plots.marginTop);
982 plots.hs->Draw(plots.stackDrawOption.c_str());
983 canvas->Print(plots.save.c_str());
984 }
985
986 // Save combined canvas
987 if (!fOutputFileName.empty()) {
988 for (const auto& [name, quant] : quantity) {
989 size_t pos = 0;
990 fOutputFileName = Replace(fOutputFileName, quant.metadata, quant.value, pos);
991 }
992 combinedCanvas.Print(fOutputFileName.c_str());
993 // In case of root file save also the histograms
995 auto file = TRestRootFileHandle::Open(fOutputFileName, TRestRootFileMode::Update);
996 if (!file) {
997 RESTError << file.Error() << RESTendl;
998 return;
999 }
1000 for (auto& plots : fPlots) {
1001 for (auto& hist : plots.histos) {
1002 hist.histo->Write();
1003 }
1004 }
1005 this->Write();
1006 if (!file.Close()) RESTError << file.Error() << RESTendl;
1007 }
1008 }
1009
1010 CleanUp();
1011}
1012
1018 for (auto& plots : fPlots) {
1019 for (auto& hist : plots.histos) {
1020 delete hist.histo;
1021 }
1022 delete plots.hs;
1023 delete plots.legend;
1024 }
1025
1026 for (auto& panel : fPanels) {
1027 for (auto& text : panel.text) {
1028 delete text;
1029 }
1030 panel.text.clear();
1031 }
1032}
1033
1039Int_t TRestDataSetPlot::GetIDFromMapString(const std::map<std::string, int>& mapStr, const std::string& in) {
1040 if (in.find_first_not_of("0123456789") == std::string::npos) {
1041 return StringToInteger(in);
1042 }
1043 auto it = mapStr.find(in);
1044 if (it != mapStr.end()) {
1045 return it->second;
1046 } else {
1047 RESTWarning << "cannot find ID with name \"" << in << "\"" << RESTendl;
1048 }
1049 return -1;
1050}
1051
1057
1058 RESTMetadata << "DataSet name: " << fDataSetName << RESTendl;
1059 RESTMetadata << "PaletteStyle: " << fPaletteStyle << RESTendl;
1060 if (fPreviewPlot) RESTMetadata << "Preview plot is ACTIVE" << RESTendl;
1061 RESTMetadata << "Canvas size: (" << fCanvasSize.X() << " ," << fCanvasSize.Y() << ")" << RESTendl;
1062 RESTMetadata << "Canvas divisions: (" << fCanvasDivisions.X() << " ," << fCanvasDivisions.Y() << ")"
1063 << RESTendl;
1064 RESTMetadata << "-------------------" << RESTendl;
1065 for (const auto& plot : fPlots) {
1066 RESTMetadata << "-------------------" << RESTendl;
1067 RESTMetadata << "Plot name/title: " << plot.name << " " << plot.title << RESTendl;
1068 RESTMetadata << "Save string: " << plot.save << RESTendl;
1069 RESTMetadata << "Set log X,Y,Z: " << plot.logX << ", " << plot.logY << ", " << plot.logZ << RESTendl;
1070 RESTMetadata << "Stack draw Option: " << plot.stackDrawOption << RESTendl;
1071 if (plot.legend) RESTMetadata << "Legend is ON" << RESTendl;
1072 if (plot.timeDisplay) RESTMetadata << "Time display is ON" << RESTendl;
1073 RESTMetadata << "Labels X,Y: " << plot.labelX << ", " << plot.labelY << RESTendl;
1074 for (const auto& hist : plot.histos) {
1075 RESTMetadata << "****************" << RESTendl;
1076 RESTMetadata << "Histo name: " << hist.name << RESTendl;
1077 RESTMetadata << "Draw Option: " << hist.drawOption << RESTendl;
1078 RESTMetadata << "Histogram size: " << hist.variable.size() << " with parameters:" << RESTendl;
1079 for (size_t i = 0; i < hist.variable.size(); i++) {
1080 RESTMetadata << "\t" << i << " " << hist.variable[i] << ", " << hist.nBins[i] << ", "
1081 << hist.range[i].X() << ", " << hist.range[i].Y() << RESTendl;
1082 }
1083 RESTMetadata << "****************" << RESTendl;
1084 }
1085 }
1086 RESTMetadata << "-------------------" << RESTendl;
1087 for (auto& panel : fPanels) {
1088 RESTMetadata << "-------------------" << RESTendl;
1089 RESTMetadata << "Panel font size/precision " << panel.font_size << ", " << panel.precision
1090 << RESTendl;
1091 RESTMetadata << "****************" << RESTendl;
1092 for (auto& [key, posLabel] : panel.variablePos) {
1093 auto&& [obs, label, units] = key;
1094 RESTMetadata << "Label variable " << obs << ", label " << label << ", units " << units << " Pos ("
1095 << posLabel.X() << ", " << posLabel.Y() << ")" << RESTendl;
1096 }
1097 RESTMetadata << "****************" << RESTendl;
1098 for (auto& [key, posLabel] : panel.metadataPos) {
1099 auto&& [obs, label, units] = key;
1100 RESTMetadata << "Label metadata " << obs << ", label " << label << ", units " << units << " Pos ("
1101 << posLabel.X() << ", " << posLabel.Y() << ")" << RESTendl;
1102 }
1103 RESTMetadata << "****************" << RESTendl;
1104 for (auto& [key, posLabel] : panel.obsPos) {
1105 auto&& [obs, label, units] = key;
1106 RESTMetadata << "Label Observable " << obs << ", label " << label << ", units " << units
1107 << " Pos (" << posLabel.X() << ", " << posLabel.Y() << ")" << RESTendl;
1108 }
1109 RESTMetadata << "****************" << RESTendl;
1110 for (auto& [key, posLabel] : panel.expPos) {
1111 auto&& [obs, label, units, precision] = key;
1112 RESTMetadata << "Label Expression " << obs << ", label " << label << ", units " << units
1113 << ", precision " << precision << " Pos (" << posLabel.X() << ", " << posLabel.Y()
1114 << ")" << RESTendl;
1115 }
1116 RESTMetadata << "****************" << RESTendl;
1117 }
1118 RESTMetadata << "-------------------" << RESTendl;
1119
1120 RESTMetadata << RESTendl;
1121}
A class to help on cuts definitions. To be used with TRestAnalysisTree.
Definition: TRestCut.h:31
Perform the plot over datasets.
Int_t GetIDFromMapString(const std::map< std::string, int > &mapStr, const std::string &in)
This functions gets the ID from a map string that is passed by reference. It is used to translate col...
std::vector< PanelInfo > fPanels
Vector with panels/label options.
TRestCut * ReadCut(TRestCut *cut, TiXmlElement *ele=nullptr)
this function is used to add the different cuts provided in different metadata sections,...
void Initialize() override
Function to initialize input/output event members and define the section name.
void PlotCombinedCanvas()
This functions performs the plot of the combined canvas with the different panels and plots.
const std::map< std::string, int > LineStyleMap
LineStyleMap as enum "ELineStyle" defined in TAttLine.h.
std::string fDataSetName
Name of the dataset to be imported.
void ReadPlotInfo()
This function reads the config file plot info and stores it in a vector of PlotInfo.
void ReadPanelInfo()
This function reads the config file panel info and stores it in a vector of PanelInfo.
void GenerateDataSetFromFilePattern(TRestDataSet &dataSet)
This functions generates a dataSet based on the information of the rml file. A TRestDataSet is pased ...
Int_t fPaletteStyle
Palette style.
const std::map< std::string, int > FillStyleMap
FillStyleMap as enum "EFillStyle" defined in TAttFill.h.
TRestDataSetPlot()
Default constructor.
TRestCut * fCut
Global cut for the entire dataSet.
Bool_t fPreviewPlot
Preview plot.
const std::map< std::string, int > ColorIdMap
Maps for internal use only.
void PrintMetadata() override
Prints on screen the information about the metadata members of TRestDataSetPlot.
TVector2 fCanvasSize
Canvas options, size, divisions and margins.
std::string fOutputFileName
OutputFileName.
~TRestDataSetPlot()
Default destructor.
Double_t fLegendX1
Legend position and size.
std::vector< PlotInfo > fPlots
Vector with plots/pads options.
void InitFromConfigFile() override
Initialization of specific TRestDataSetPlot members through an RML file.
void CleanUp()
Clean up histos and text but note that the metadata is unchanged.
It allows to group a number of runs that satisfy given metadata conditions.
Definition: TRestDataSet.h:34
void Import(const std::string &fileName)
This function imports metadata from a root file it import metadata info from the previous dataSet whi...
Double_t GetTotalTimeInSeconds() const
It returns the accumulated run time in seconds.
Definition: TRestDataSet.h:163
ROOT::RDF::RNode MakeCut(const TRestCut *cut)
This function applies 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 ...
TTree * GetTree() const
Gives access to the tree.
Definition: TRestDataSet.h:135
A base class for any REST metadata class.
Definition: TRestMetadata.h:74
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
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.
std::string GetParameter(std::string parName, TiXmlElement *e, TString defaultValue=PARAMETER_NOT_FOUND_STR)
Returns the value for the parameter named parName in the given section.
static TRestRootFileHandle Open(const std::string &filename, TRestRootFileMode mode)
Definition: TRestTools.cxx:597
@ REST_Info
+show most of the information for each steps
static std::string GetFileNameExtension(const std::string &fullname)
Gets the file extension as the substring found after the latest ".".
Int_t GetChar(std::string hint="Press a KEY to continue ...")
Helps to pause the program, printing a message before pausing.
std::string IntegerToString(Int_t n, std::string format="%d")
Gets a string from an integer.
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 ToUpper(std::string in)
Convert string to its upper case. Alternative of TString::ToUpper.
Int_t StringToInteger(std::string in)
Gets an integer from a string.
Int_t isAExpression(const std::string &in)
Returns 1 only if valid mathematical expression keywords (or numbers) are found in the string in....
std::string DoubleToString(Double_t d, std::string format="%8.6e")
Gets a string from a double.
TVector2 StringTo2DVector(std::string in)
Gets a 2D-vector from a string.
std::string EvaluateExpression(std::string exp)
Evaluates a complex numerical expression and returns the resulting value using TFormula.
Int_t isANumber(std::string in)
Returns 1 only if a valid number is found in the string in. If not it returns 0.
std::string RemoveWhiteSpaces(std::string in)
Returns the input string removing all white spaces.
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 any occurences of thisSring by byThisString inside string in.
Nested classes for internal use only.
Auxiliary class for panels/labels.
Auxiliary struct for plots/pads.
std::string metadata
The associated metadata member used to register the relevant quantity.
Definition: TRestDataSet.h:38
std::string strategy
It determines how to produce the relevant quantity (accumulate/unique/last/max/min)
Definition: TRestDataSet.h:41