18#include <FairRootFileSink.h>
19#include <FairRunOnline.h>
20#include <FairRuntimeDb.h>
22#include <TDirectory.h>
26#include <fmt/chrono.h>
28#include <fmt/format.h>
35 auto create_datatime_rootfile(std::string_view base_filename) -> std::unique_ptr<TFile>
37 auto time = std::chrono::system_clock::now();
38 const auto file_name = fmt::format(
"{}-{:%Y-%m-%d-%Hh-%Mm-%Ss}.root", base_filename, time);
39 auto* root_file = TFile::Open(file_name.data(),
"RECREATE");
40 return std::unique_ptr<TFile>{ root_file };
51 return hist->second.get();
53 throw R3B::logic_error(fmt::format(
"Histogram with the name {} doesn't exist!", histName));
60 return canvas->second;
62 throw R3B::logic_error(fmt::format(
"Canvas with the name {} doesn't exist!", histName));
68 auto* new_dir = folderName.empty() ? hist_dir : hist_dir->mkdir(folderName.data(),
"",
true);
69 if (new_dir ==
nullptr)
72 fmt::format(
"Failed to create a sub directory {} for the histrogams!", folderName));
75 fmt::format(
"Saving figures to the directory {:?} in the root file {:?}",
77 new_dir->GetFile()->GetName()));
85 auto* rootSinkFile =
dynamic_cast<FairRootFileSink*
>(sinkFile);
86 if (rootSinkFile ==
nullptr)
88 throw R3B::logic_error(
"Cannot save the histograms as the output file is not a root file!");
90 auto* rootFile = rootSinkFile->GetRootFile();
92 if (hist_dir ==
nullptr)
101 for (
auto& [canvas_name, canvas] :
canvases_)
109 if (
auto* run_online =
dynamic_cast<FairRunOnline*
>(run); run_online !=
nullptr)
113 run_online->AddObject(canvas.get_canvas());
128 if (filename.empty())
132 auto rootfile = create_datatime_rootfile(filename);
133 R3BLOG(info, fmt::format(
"Saving histograms to {}", rootfile->GetName()));
141 if (hist->GetEntries() == 0)
143 R3BLOG(warn, fmt::format(
"Histogram {} is empty while written to the file!", hist->GetName()));
145 dir->WriteObject(hist.get(), hist->GetName());
147 for (
auto& [name, graph] :
graphs_)
149 dir->WriteObject(graph.get(), graph->GetName(),
"overwrite");
#define R3BLOG(severity, x)
void write_all(TDirectory *dir)
std::map< std::string, std::unique_ptr< TH1 > > histograms_
std::string save_filename_
void save_to_sink(std::string_view folderName="", FairSink *sinkFile=FairRun::Instance() ->GetSink())
void register_canvases(FairRun *run)
std::map< std::string, DataMonitorCanvas > canvases_
std::map< std::string, std::unique_ptr< TGraph > > graphs_
static auto get_hist_dir(FairSink *sinkFile) -> TDirectory *
void save_to_file(std::string_view filename="")
auto get_canvas(const std::string &histName) -> DataMonitorCanvas &
auto get(const std::string &histName) -> TH1 *
constexpr auto DEFAULT_HIST_MONITOR_DIR