#include "TFile.h" #include "TTree.h" #include "TH1.h" #include "TCanvas.h" #include void sumhist() { // List of ROOT file names const int nFiles = 8; // Update this to the actual number of files you have const char* filenames[nFiles] = {"file1.root", "file2.root", "file3.root", "file4.root", "file5.root", "file6.root", "file7.root", "file8.root"}; TH1 *h_sum = nullptr; for (int i = 0; i < nFiles; i++) { std::cout << "Processing file: " << filenames[i] << std::endl; TFile *f = TFile::Open(filenames[i]); if (!f || f->IsZombie()) { std::cerr << "Error opening file: " << filenames[i] << std::endl; continue; } TTree *tree = (TTree*) f->Get("outTree"); if (!tree) { std::cerr << "TTree 'outTree' not found in file: " << filenames[i] << std::endl; f->Close(); continue; } // Create histogram from the tree data tree->Draw("Ener1>>h_temp(8192,0,1000)", "", "goff"); TH1 *h_temp = (TH1*) gDirectory->Get("h_temp"); if (!h_temp) { std::cerr << "Failed to create histogram in file: " << filenames[i] << std::endl; f->Close(); continue; } // Debug: print entries in the temporary histogram std::cout << "File " << filenames[i] << ": h_temp entries = " << h_temp->GetEntries() << std::endl; // Clone the histogram and detach it from the file TH1 *h_temp_clone = (TH1*) h_temp->Clone(); h_temp_clone->SetDirectory(0); // Sum the histogram with previous ones if (h_sum == nullptr) { h_sum = (TH1*) h_temp_clone->Clone("h_sum"); } else { h_sum->Add(h_temp_clone); } // Clean up the temporary clone delete h_temp_clone; f->Close(); } // Check and draw the summed histogram if (h_sum) { std::cout << "Final summed histogram entries: " << h_sum->GetEntries() << std::endl; TCanvas *c = new TCanvas("c", "Summed Histogram", 800, 600); h_sum->Draw(); c->Update(); c->SaveAs("summed_histogram.png"); } else { std::cerr << "No histograms were summed." << std::endl; } }