void DeconvolutionRL_wide() { Int_t i; const Int_t nbins = 256; Double_t xmin = 0; Double_t xmax = nbins; Double_t source[nbins]; Double_t response[nbins]; gROOT->ForceStyle(); TString dir = gROOT->GetTutorialsDir(); TString file = dir+"/spectrum/TSpectrum.root"; TFile *f = new TFile(file.Data()); h = (TH1F*) f->Get("decon3"); h->SetTitle("Deconvolution of closely positioned overlapping peaks using Richardson-Lucy deconvolution method"); d = (TH1F*) f->Get("decon_response_wide"); for (i = 0; i < nbins; i++) source[i]=h->GetBinContent(i + 1); for (i = 0; i < nbins; i++) response[i]=d->GetBinContent(i + 1); h->SetMaximum(30000); h->Draw("L"); TSpectrum *s = new TSpectrum(); s->DeconvolutionRL(source,response,256,10000,1,1); for (i = 0; i < nbins; i++) d->SetBinContent(i + 1,source[i]); d->SetLineColor(kRed); d->Draw("SAME L"); }
int e428ana1::MakePara(Double_t thr){ int npeak,nlap; double threshol,thrmin,thrmax; TSpectrum *spec; for (int i=0; i<4; i++) { for (int j=0; j<127; j++) { npeak=0;nlap=0; threshol=thr; thrmax=1;thrmin=0; while (npeak!=4 && nlap<100){ spec = new TSpectrum(10); npeak = spec->Search(hdssd[i][j],2,"",threshol); if (npeak >3) { thrmin=threshol; }else thrmax=threshol; threshol=(thrmax-thrmin)/2; nlap++; // printf("Npeak %d %d %d %f\n",i,j,npeak,threshol); } float *xpeak=spec->GetPositionX(); float *ypeak=spec->GetPositionY(); printf("Npeak %d %d %d",i,j,npeak); for (int i1=0; i1<npeak; i1++) { printf(" %f %f",xpeak[i1],ypeak[i1]); } printf("\n"); } } return 0; }
void Deconvolution_wide_boost() { Int_t i; const Int_t nbins = 256; Double_t xmin = 0; Double_t xmax = nbins; Double_t source[nbins]; Double_t response[nbins]; gROOT->ForceStyle(); TH1F *h = new TH1F("h","Deconvolution",nbins,xmin,xmax); TH1F *d = new TH1F("d","",nbins,xmin,xmax); TString dir = gROOT->GetTutorialDir(); TString file = dir+"/spectrum/TSpectrum.root"; TFile *f = new TFile(file.Data()); h = (TH1F*) f->Get("decon3"); h->SetTitle("Deconvolution of closely positioned overlapping peaks using boosted Gold deconvolution method"); d = (TH1F*) f->Get("decon_response_wide"); for (i = 0; i < nbins; i++) source[i]=h->GetBinContent(i + 1); for (i = 0; i < nbins; i++) response[i]=d->GetBinContent(i + 1); h->SetMaximum(200000); h->Draw("L"); TSpectrum *s = new TSpectrum(); s->Deconvolution(source,response,256,200,50,1.2); for (i = 0; i < nbins; i++) d->SetBinContent(i + 1,source[i]); d->SetLineColor(kRed); d->Draw("SAME L"); }
TGraph* autogain152(TH1 *hist) { hist->GetXaxis()->SetRangeUser(200.,16000.); TSpectrum *s = new TSpectrum(); Int_t nfound = s->Search(hist,6,"",0.08); //This will be dependent on the source used. printf("Found %d candidate peaks to fit\n",nfound); if(nfound > 6) nfound = 6; std::vector<float> vec; for(int x=0;x<nfound;x++) vec.push_back(s->GetPositionX()[x]); std::sort(vec.begin(),vec.end()); Float_t energies[] = {121.7830, 244.6920, 344.276, 778.903, 964.131, 1408.011}; TGraph* slopefit = new TGraph(nfound, &(vec[0]), energies); printf("Now fitting: Be patient\n"); slopefit->Fit("pol1"); if(slopefit->GetFunction("pol1")->GetChisquare() > 10.) { slopefit->RemovePoint(slopefit->GetN()-1); slopefit->Fit("pol1"); } TChannel *chan = 0; slopefit->Draw("AC*"); return slopefit; }
void peaks(Int_t np=10) { npeaks = TMath::Abs(np); TH1F *h = new TH1F("h","test",500,0,1000); //generate n peaks at random Double_t par[3000]; par[0] = 0.8; par[1] = -0.6/1000; Int_t p; for (p=0;p<npeaks;p++) { par[3*p+2] = 1; par[3*p+3] = 10+gRandom->Rndm()*980; par[3*p+4] = 3+2*gRandom->Rndm(); } TF1 *f = new TF1("f",fpeaks,0,1000,2+3*npeaks); f->SetNpx(1000); f->SetParameters(par); TCanvas *c1 = new TCanvas("c1","c1",10,10,1000,900); c1->Divide(1,2); c1->cd(1); h->FillRandom("f",200000); h->Draw(); TH1F *h2 = (TH1F*)h->Clone("h2"); //Use TSpectrum to find the peak candidates TSpectrum *s = new TSpectrum(2*npeaks); Int_t nfound = s->Search(h,2,"",0.10); printf("Found %d candidate peaks to fit\n",nfound); //Estimate background using TSpectrum::Background TH1 *hb = s->Background(h,20,"same"); if (hb) c1->Update(); if (np <0) return; //estimate linear background using a fitting method c1->cd(2); TF1 *fline = new TF1("fline","pol1",0,1000); h->Fit("fline","qn"); //Loop on all found peaks. Eliminate peaks at the background level par[0] = fline->GetParameter(0); par[1] = fline->GetParameter(1); npeaks = 0; Double_t *xpeaks = s->GetPositionX(); for (p=0;p<nfound;p++) { Double_t xp = xpeaks[p]; Int_t bin = h->GetXaxis()->FindBin(xp); Double_t yp = h->GetBinContent(bin); if (yp-TMath::Sqrt(yp) < fline->Eval(xp)) continue; par[3*npeaks+2] = yp; par[3*npeaks+3] = xp; par[3*npeaks+4] = 3; npeaks++; } printf("Found %d useful peaks to fit\n",npeaks); printf("Now fitting: Be patient\n"); TF1 *fit = new TF1("fit",fpeaks,0,1000,2+3*npeaks); //we may have more than the default 25 parameters TVirtualFitter::Fitter(h2,10+3*npeaks); fit->SetParameters(par); fit->SetNpx(1000); h2->Fit("fit"); }
void Background_order() { Int_t i; const Int_t nbins = 4096; Double_t xmin = 0; Double_t xmax = 4096; Double_t source[nbins]; gROOT->ForceStyle(); TH1F *d1 = new TH1F("d1","",nbins,xmin,xmax); TH1F *d2 = new TH1F("d2","",nbins,xmin,xmax); TH1F *d3 = new TH1F("d3","",nbins,xmin,xmax); TH1F *d4 = new TH1F("d4","",nbins,xmin,xmax); TString dir = gROOT->GetTutorialsDir(); TString file = dir+"/spectrum/TSpectrum.root"; TFile *f = new TFile(file.Data()); TH1F *back = (TH1F*) f->Get("back2"); back->SetTitle("Influence of clipping filter difference order on the estimated background"); back->SetAxisRange(1220,1460); back->SetMaximum(3000); back->Draw("L"); TSpectrum *s = new TSpectrum(); for (i = 0; i < nbins; i++) source[i]=back->GetBinContent(i + 1); s->Background(source,nbins,40,TSpectrum::kBackDecreasingWindow, TSpectrum::kBackOrder2,kFALSE, TSpectrum::kBackSmoothing3,kFALSE); for (i = 0; i < nbins; i++) d1->SetBinContent(i + 1,source[i]); d1->SetLineColor(kRed); d1->Draw("SAME L"); for (i = 0; i < nbins; i++) source[i]=back->GetBinContent(i + 1); s->Background(source,nbins,40,TSpectrum::kBackDecreasingWindow, TSpectrum::kBackOrder4,kFALSE, TSpectrum::kBackSmoothing3,kFALSE); for (i = 0; i < nbins; i++) d2->SetBinContent(i + 1,source[i]); d2->SetLineColor(kBlue); d2->Draw("SAME L"); for (i = 0; i < nbins; i++) source[i]=back->GetBinContent(i + 1); s->Background(source,nbins,40,TSpectrum::kBackDecreasingWindow, TSpectrum::kBackOrder6,kFALSE, TSpectrum::kBackSmoothing3,kFALSE); for (i = 0; i < nbins; i++) d3->SetBinContent(i + 1,source[i]); d3->SetLineColor(kGreen); d3->Draw("SAME L"); for (i = 0; i < nbins; i++) source[i]=back->GetBinContent(i + 1); s->Background(source,nbins,40,TSpectrum::kBackDecreasingWindow, TSpectrum::kBackOrder8,kFALSE, TSpectrum::kBackSmoothing3,kFALSE); for (i = 0; i < nbins; i++) d4->SetBinContent(i + 1,source[i]); d4->SetLineColor(kMagenta); d4->Draw("SAME L"); }
TGraph* autogain(TH1 *hist,TNucleus *nuc) { //Display The fits on a TPad if(!hist || !nuc) return 0; nuc->SetSourceData(); if(nuc->GetA() == 152) { return autogain152(hist); } // Search hist->GetXaxis()->SetRangeUser(200.,16000.); TSpectrum *s = new TSpectrum(); Int_t nfound = s->Search(hist,6,"",0.1); //This will be dependent on the source used. printf("Found %d candidate peaks to fit\n",nfound); // Match nuc->TransitionList.Sort(); std::vector<float> engvec; TIter iter(&(nuc->TransitionList)); TObject* obj; while(obj = iter.Next()) { if(!obj->InheritsFrom("TGRSITransition")) continue; TGRSITransition *tran = (TGRSITransition*)obj; engvec.push_back(static_cast<float>(tran->energy)); if(engvec.size() == nfound) break; } if(nfound != engvec.size()) return 0; Float_t *posPeaks = s->GetPositionX(); Float_t *energies = &(engvec[0]); for(int x=0;x<nfound;x++) { printf("posPeaks[%i] = %f\t\tenrgies[%i] = %f\n",x,posPeaks[x],x,energies[x]); } TGraph *slopefit = new TGraph(nfound,posPeaks,energies ); printf("Now fitting: Be patient\n"); slopefit->Fit("pol1"); slopefit->Draw("AC*"); return slopefit; }
//______________________________________________________________________________ void Fit(Int_t run) { // Perform fit. Char_t tmp[256]; // delete old function if (gFitFunc) delete gFitFunc; // create fitting function if (gFitFunc) delete gFitFunc; sprintf(tmp, "fGauss_%d", run); gFitFunc = new TF1(tmp, "expo(0)+gaus(2)"); gFitFunc->SetLineColor(2); // estimate peak position TSpectrum s; s.Search(gH, 10, "goff nobackground", 0.05); Double_t peak = TMath::MaxElement(s.GetNPeaks(), s.GetPositionX()); // prepare fitting function gFitFunc->SetRange(gMin, gMax); gFitFunc->SetParameter(2, gH->GetXaxis()->FindBin(peak)); gFitFunc->SetParLimits(2, 0, 100000); gFitFunc->SetParameter(3, peak); gFitFunc->SetParameter(4, 20); gFitFunc->SetParLimits(4, 18, 100); for (Int_t i = 0; i < 10; i++) if (!gH->Fit(gFitFunc, "RBQ0")) break; // get peak peak = gFitFunc->GetParameter(3); // indicator line gLine->SetX1(peak); gLine->SetX2(peak); gLine->SetY1(0); gLine->SetY2(gH->GetMaximum()); // draw gCFit->cd(); gH->GetXaxis()->SetRangeUser(0, 2000); gH->Draw(); gFitFunc->Draw("same"); gLine->Draw("same"); // fill overview histogram gHOverview->SetBinContent(run+1, peak); gHOverview->SetBinError(run+1, 0.0001); }
//Given an input histogram and TSpectrum returns a numeric value based on the input keyword; supported keywords are "AMPLITUDE,MEAN,PEAK,SIGMA" float AnalyzeResponseUniformity::getValByKeyword(string strInputKeyword, shared_ptr<TH1F> hInput, TSpectrum &specInput){ //Try to automatically assign a value if (0 == strInputKeyword.compare("AMPLITUDE") ) { //Case: Histo Amplitude return hInput->GetBinContent( hInput->GetMaximumBin() ); } //End Case: Histo Amplitude else if (0 == strInputKeyword.compare("MEAN") ) { //Case: Histo Mean return hInput->GetMean(); } //End Case: Histo Mean else if ( 0 == strInputKeyword.compare("PEAK") ){ //Case: Histo Peak Double_t *dPeakPos = specInput.GetPositionX(); return dPeakPos[0]; } //End Case: Histo Peak else if (0 == strInputKeyword.compare("SIGMA") ) { //Case: Histo RMS return hInput->GetRMS(); } //End Case: Histo RMS else{ //Case: manual assignment printClassMethodMsg("AnalyzeResponseUniformity","getValByKeyword","Error! Input Keyword Not Recognized"); printClassMethodMsg("AnalyzeResponseUniformity","getValByKeyword", ("\tGiven: " + strInputKeyword ).c_str() ); printClassMethodMsg("AnalyzeResponseUniformity","getValByKeyword","\tRecognized Keywords:\n"); for (int i=0; i < vec_strSupportedKeywords.size(); ++i) { printClassMethodMsg("AnalyzeResponseUniformity","getValByKeyword", vec_strSupportedKeywords[i].c_str() ); } printClassMethodMsg("AnalyzeResponseUniformity","getValByKeyword","\tUndefined Behavior May Occur"); return -1e12; } //End Case: manual assignment } //End AnalyzeResponseUniformity::getValByKeyword()
void MSSM_spectrum_plotter::write_spectrum(const TSpectrum& spectrum, std::ofstream& filestr) const { for (std::size_t s = 0; s < spectrum.size(); ++s) { if (!filestr.good()) { ERROR("MSSM_spectrum_plotter::write_spectrum: " "file stream is corrupted"); break; } const std::string& name = spectrum[s].name; const std::string& latex_name = spectrum[s].latex_name; const std::valarray<double>& masses = spectrum[s].masses; const std::size_t multiplicity = masses.size(); filestr << std::left << "# " << name << '\n'; for (std::size_t i = 0; i < multiplicity; ++i) { std::string lname("$" + latex_name + "$"); std::stringstream lname_with_index; lname_with_index << "$" << latex_name; if (multiplicity > 1) lname_with_index << "_{" << (i+1) << "}"; lname_with_index << "$"; filestr << std::left << std::setw(width) << s << std::left << std::setw(width) << masses[i] << std::left << std::setw(width) << name << std::left << std::setw(2*width) << lname << std::left << std::setw(2*width) << lname_with_index.str() << '\n'; } } }
void FindPeak(TH1 *hm, int * i, char * namefile){ int np =5, p, max = 0; int npeaks = TMath::Abs(np); double par[3000]; par[0] = 0.8; par[1] = -0.6/1000; for (p=0;p<npeaks;p++) { par[3*p+2] = 1; par[3*p+3] = 10+gRandom->Rndm()*980; par[3*p+4] = 3+2*gRandom->Rndm(); } TSpectrum *s = new TSpectrum(2*npeaks,1); int nfound = s->Search(hm,2,"",0.10); printf("Found %d candidate peaks to fit\n",nfound); TH1 *hb = s->Background(hm,20,"same"); if (np <0) return; // loope over peaks TF1 *fline = new TF1("fline","pol1",0,1000); hm->Fit("fline","qn"); par[0] = fline->GetParameter(0); par[1] = fline->GetParameter(1); npeaks = 0; float *xpeaks = s->GetPositionX(); for (p=0;p<nfound;p++) { float xp = xpeaks[p]; int bin = hm->GetXaxis()->FindBin(xp); float yp = hm->GetBinContent(bin); if (yp-TMath::Sqrt(yp) < fline->Eval(xp)) continue; par[3*npeaks+2] = yp; par[3*npeaks+3] = xp; par[3*npeaks+4] = 3; npeaks++; } printf("Found %d useful peaks to fit\n",npeaks); printf("Now fitting: Be patient\n"); if (max < npeaks) max = npeaks; TF1 *fit = new TF1("fit",fpeaks,0,1000,2+3*npeaks); TVirtualFitter::Fitter(hm,10+3*npeaks); fit->SetParameters(par); fit->SetNpx(1000); hm->Fit("fit"); }
//// This version needs thought void SiCalibrator::FindPeaks() { Load(); int iterate = 25; int nbins; TSpectrum* spec = new TSpectrum(10); avesigma = 0; int nsigma = 0; for (int src=0; src < CalData.size(); src++) { if (CalData[src].hSource != 0) { for (int ch=0; ch<CalData[src].sourcedata.size(); ch++) { TH1D* hbi = CalData[src].hSource->ProjectionY("hb",ch+1,ch+1); nbins = hbi->GetNbinsX(); TH1D* hbk1 = (TH1D*) spec->Background(hbi,iterate); hbi->Add(hbk1,-1); //Estimate parameters double lim = 5; double max = 0; double peak = 0; int i = nbins - 1; while (hbi->GetBinContent(i) < lim && i > 0) { max = i; i--; } double sigma = (max/CalibSource::sourcelist[src].betas.back().E)*2; //2 keV if (sigma > 1) { avesigma += sigma; nsigma++; } gErrorIgnoreLevel = kError; int npeaks = spec->Search(hbi,sigma,"nodraw ",0.001); float* adc = spec->GetPositionX(); float* amp = spec->GetPositionY(); for (int i=0; i<npeaks; i++) { CalData[src].sourcedata[ch].ADC.push_back(adc[i]); CalData[src].sourcedata[ch].Amp.push_back(amp[i]); } } } } avesigma = avesigma/nsigma; }
/* Finds peak in timing difference spectrum */ double DiffPeak(TTree *&tree, TString pidcut = "PID>1000") { TSpectrum *spec = new TSpectrum(10); // peak finder TH1D *diff = new TH1D("diff","diff",200,-5,5); tree->Project("diff","diff",pidcut.Data()); spec->Search(diff,2,"nodraw",0.7); double diffpeak = spec->GetPositionX()[0]; // testing //TCanvas *c_tmp = new TCanvas(); //diff->Draw(); //c_tmp->WaitPrimitive(); //delete c_tmp; delete diff; delete spec; return diffpeak; } // end DiffPeak()
void draw_ToF_Calib_Tower() { ofstream fout("ToF_Calib_Tower.txt"); TFile* f = new TFile("/phenix/plhf/zji/taxi/Run13pp510MinBias/8328/data/total.root"); TH2I* h_hitmap_tof_energy_PbSc = (TH2I*)f->Get("hitmap_tof_energy_PbSc"); TH2I* h_hitmap_tof_energy_PbGl = (TH2I*)f->Get("hitmap_tof_energy_PbGl"); TH2I* h_hitmap_tof_tower = (TH2I*)f->Get("hitmap_tof_tower"); TCanvas* c = new TCanvas("c", "Canvas", 1800, 600); gStyle->SetOptStat(1); gStyle->SetOptFit(1); c->Divide(3,1); c->cd(1); h_hitmap_tof_energy_PbSc->Draw("colz"); c->cd(2); h_hitmap_tof_energy_PbGl->Draw("colz"); c->cd(3); fout << "towerid ToF peak" << endl; for(Int_t id=0; id<25000; id++) { TH1D* hp_hitmap_tof_tower = (TH1D*)h_hitmap_tof_tower->ProjectionY("_py",id+1,id+1); TSpectrum* peak = new TSpectrum(); Int_t nfound = peak->Search(hp_hitmap_tof_tower,2.,"nodraw"); if(nfound) { Float_t peakX = *peak->GetPositionX(); hp_hitmap_tof_tower->Fit("gaus","Q0","",peakX-3.,peakX+3.); TF1* f_hitmap_tof_tower = hp_hitmap_tof_tower->GetFunction("gaus"); Double_t mean_hitmap_tof_tower = f_hitmap_tof_tower->GetParameter(1); fout << id << " " << mean_hitmap_tof_tower << endl; f_hitmap_tof_tower->Delete(); } else { fout << id << " " << "-100." << endl; } delete peak; hp_hitmap_tof_tower->Delete(); } fout.close(); TH1D* hp_hitmap_tof_tower = (TH1D*)h_hitmap_tof_tower->ProjectionY("_py",100,100); TSpectrum* peak = new TSpectrum(); peak->Search(hp_hitmap_tof_tower,2.,"nodraw"); Float_t peakX = *peak->GetPositionX(); hp_hitmap_tof_tower->Fit("gaus","","",peakX-3.,peakX+3.); TF1* f_hitmap_tof_tower = hp_hitmap_tof_tower->GetFunction("gaus"); Double_t mean_hitmap_tof_tower = f_hitmap_tof_tower->GetParameter(1); cout << "peakX=" << peakX << endl; cout << "ToF mean=" << mean_hitmap_tof_tower << endl; c->Print("ToF_Calib_Tower.pdf"); }
//________________________________________________________________________________ void peaks(TH1* h, Int_t np=10, Int_t ij=0) { if (! h) return; npeaks = TMath::Abs(np); if (! c1) c1 = new TCanvas(); else c1->Clear(); if (c2 && ij > 0) {c2->cd(ij); h->Draw(); c2->Update();} c1->Divide(1,2); c1->cd(1); h->Draw(); TH1F *h2 = (TH1F*)h->Clone("h2"); //Use TSpectrum to find the peak candidates TSpectrum *s = new TSpectrum(2*npeaks); Int_t nfound = s->Search(h,5,"",0.05); printf("Found %d candidate peaks to fit\n",nfound); if (! nfound) return; //Estimate background using TSpectrum::Background TH1 *hb = s->Background(h,20,"same"); hb->Draw("same"); c1->Update(); if (c2 && ij > 0) {c2->cd(ij); h->Draw(); c2->Update();} if (np <0) return; //estimate linear background using a fitting method c1->cd(2); TF1 *fline = new TF1("fline","pol1",0,1000); fline->FixParameter(1,0.); h->Fit("fline","qnlw"); if (c2 && ij > 0) {c2->cd(ij+1); h->Draw(); c2->Update(); c1->cd(2);} //Loop on all found peaks. Eliminate peaks at the background level Double_t par[3000]; par[0] = fline->GetParameter(0); par[1] = fline->GetParameter(1); npeaks = 0; Float_t *xpeaks = s->GetPositionX(); Float_t ymax = 0; for (Int_t p=0;p<nfound;p++) { Float_t xp = xpeaks[p]; Int_t bin = h->GetXaxis()->FindBin(xp); Float_t yp = h->GetBinContent(bin); if (yp-3*TMath::Sqrt(yp) < fline->Eval(xp)) continue; par[3*npeaks+2] = yp; if (yp > ymax) ymax = yp; par[3*npeaks+3] = xp; par[3*npeaks+4] = 3; npeaks++; } cout << "Found " << npeaks << " useful peaks to fit" << endl; Int_t NP = 0; Int_t nbad = 0; TString LineH(" {\""); LineH += h->GetName(); LineH += "\""; TString Line(""); struct ParErr_t {Double_t par, err;}; ParErr_t parErr[10]; TF1 *fit = 0; if (ymax > 2*par[0]) { cout << "Now fitting: Be patient" << endl; fit = new TF1("fit",fpeaks,0,1000,2+3*npeaks); TVirtualFitter::Fitter(h2,10+3*npeaks); //we may have more than the default 25 parameters fit->SetParameter(0,par[0]); fit->FixParameter(1,0.); for (Int_t p = 0; p < npeaks; p++) { fit->SetParName(3*p+2,Form("A%i",p)); fit->SetParLimits(3*p+2,0,1e6); fit->SetParameter(3*p+2,par[3*p+2]); fit->SetParName(3*p+3,Form("#mu%i",p)); fit->SetParLimits(3*p+3,TMath::Max(0.,par[3*p+3]-2), TMath::Min(240.,par[3*p+3]+2)); fit->SetParameter(3*p+3,par[3*p+3]); fit->SetParName(3*p+4,Form("#sigma%i",p)); fit->SetParLimits(3*p+4,0.01,20); fit->SetParameter(3*p+4,par[3*p+4]); } fit->SetNpx(1000); h2->SetStats(0); h2->Fit("fit","l"); if (c2 && ij > 0) {c2->cd(ij); h2->Draw("same"); c2->Update(); c1->cd(2);} fit->GetParameters(par); for (Int_t p = 0; p<np;p++) { if (p < npeaks && par[3*p+2] > 5*fit->GetParError(3*p+2) && par[3*p+2] > par[0]) { if (TMath::Abs(par[3*p+4]) > 5.0) nbad++; // Line += Form(",%f,%f,%7.2f,%5.2f",par[3*p+2],fit->GetParError(3*p+2),par[3*p+3],TMath::Abs(par[3*p+4])); parErr[NP].par = par[3*p+3]; parErr[NP].err = TMath::Abs(par[3*p+4]); for (Int_t i = 0; i < NP; i++) { if (parErr[i].par > parErr[NP].par) { ParErr_t temp = parErr[i]; parErr[i] = parErr[NP]; parErr[NP] = temp; } } NP++; } } } for (Int_t p = 0; p < np; p++) { if (p < NP) Line += Form(",%7.2f,%5.2f",parErr[p].par,parErr[p].err); else Line += ",0,0"; } Line += "},"; if (nbad > 1) NP = -NP; // reject whole hybrid LineH += Form(",%3i",NP); cout << LineH << Line << endl; out << LineH << Line << endl; c1->Update(); if (c2) c2->Update(); delete fit; delete s; }
void fit_double_gaussian(TH1F*& hrsp) { if (0==hrsp) { cout<<"ERROR: Empty pointer to fit_double_gaussian()"<<endl;return; } string histname = hrsp->GetName(); double mean = hrsp->GetMean(); double rms = hrsp->GetRMS(); TSpectrum *spec = new TSpectrum(10); int nfound = spec->Search(hrsp,1,"new"); if(nfound!=2)return; double *xpeaks = spec->GetPositionX(); double peak1 = xpeaks[0]; double bin1 = hrsp->FindBin(peak1); double norm1 = hrsp->GetBinContent(bin1); double sigma1 = 0.2; double peak2 = xpeaks[1]; double bin2 = hrsp->FindBin(peak2); double norm2 = hrsp->GetBinContent(bin2); double sigma2 = 0.3; cout << " Mean : " << mean << " \t RMS : " << rms << endl; cout << " norm1 : " << norm1 << " \t norm2 : " << norm2 << endl; cout << " peak1 : " << peak1 << " \t sig1 : " << sigma1 << endl; cout << " peak2 : " << peak2 << " \t sig2 : " << sigma2 << endl; double fitrange_min = 0.2; double fitrange_max = 1.7; TF1* fitfnc(0); int fitstatus(-1); TF1 *fitg1(0), *fitg2(0); fitfnc = new TF1("fdgaus","gaus(0)+gaus(3)",fitrange_min,fitrange_max); fitfnc->SetLineColor(1); fitfnc->SetLineStyle(2); fitfnc->SetLineWidth(2); fitfnc->SetParNames("N_{1}", "#mu_{1}", "#sigma_{1}", "N_{2}", "#mu_{2}", "#sigma_{2}"); fitfnc->SetParameters(norm1, peak1, sigma1, norm2, peak2, sigma2); //fitfnc->SetParLimits(0,0.0,2.0*norm1); //fitfnc->SetParLimits(1,peak1-3*sigma1,peak1+3*sigma1); //fitfnc->SetParLimits(2,0.1,1.0); //fitfnc->SetParLimits(3,0.0,1.5*norm2); //fitfnc->SetParLimits(4,peak2-3*sigma2,peak2+3*sigma2); //fitfnc->SetParLimits(5,0.01,1.0); fitstatus = hrsp->Fit(fitfnc,"RQ"); // if (0!=fitstatus){ // fitfnc->SetParLimits(4,0.2,1.7); // fitfnc->SetParLimits(5,2.0,10.0); // //cout <<" Not able to Fit this pt bin " << hrsp->GetName() << endl; // } fitstatus = hrsp->Fit(fitfnc,"RQ"); hrsp->SetMaximum(norm1+0.2*norm1); fitg1 = new TF1("fg1","gaus(0)",fitrange_min,fitrange_max); fitg1->SetParameters(fitfnc->GetParameter(0), fitfnc->GetParameter(1), fitfnc->GetParameter(2)); fitg1->SetLineColor(2); fitg1->SetLineStyle(2); hrsp->GetListOfFunctions()->Add(fitg1); fitg2 = new TF1("fg2","gaus(0)",fitrange_min,fitrange_max); fitg2->SetParameters(fitfnc->GetParameter(3), fitfnc->GetParameter(4), fitfnc->GetParameter(5)); fitg2->SetLineColor(4); fitg2->SetLineStyle(4); hrsp->GetListOfFunctions()->Add(fitg2); if(hrsp->GetFunction("fdgaus")==0){ cout << "No function recorded in histogram " << hrsp->GetName() << endl; } if (0!=fitstatus){ cout<<"fit_double_gaussian() to "<<hrsp->GetName() <<" failed. Fitstatus: "<<fitstatus <<" - FNC deleted."<<endl; hrsp->GetListOfFunctions()->Delete(); } }
I2GFvalues I2GFmainLoop(TH1F *htemp, int N_iter, float N_sigma_range, bool ShowFit) //Arguments: (histo to be fit, N iterations to find peak using gaus fit, fit range param., do or do not plot fit on histo) { I2GFvalues myI2GFvalues; //Set initial values...(in case fit fails) myI2GFvalues.rchi2 = -100; myI2GFvalues.mean = -100; myI2GFvalues.mean_err = -100; myI2GFvalues.sigma = -100; myI2GFvalues.sigma_err = -100; TSpectrum *s = new TSpectrum(); //TSpectrum(1,1)->Argument: (Number of peaks to find, Distance to neighboring peak: "1"-->3sigma) Int_t NPeaks; Float_t *Peak; //TSpectrum *s = new TSpectrum(); --> No warning message Float_t *PeakAmp; float peak_pos = 0; float peak_pos_amp = 0; //Initial value, assuming positive going peaks int peak_pos_bin = 0; int binMaxCnt = 0; float binMaxCnt_value = 0; int binMaxCnt_counts = 0; int Nbins = 0; Int_t zero_value_bin = 0; float low_limit = 0; float high_limit = 0; float peak_pos_count = 0; float zero_bin_value = 0; float max_bin_value = 0; TF1 *func; TF1 *func1; TF1 *func2; TF1 *func3; float Chi2; int NDF = 1; float f_RChi2 = 1; float f_const = 1; float f_mean = 1; float f_mean_err = 1; float f_sigma = 1; float f_sigma_err = 1; float peak = 1; float f_const2 = 1; float f_mean2 = 1; float f_mean_err2 = 1; float f_sigma2 = 1; float f_sigma_err2 = 1; //---------Basic Histo Peak Finding Parameters---------- binMaxCnt = htemp->GetMaximumBin(); //Finds bin w/ max counts (can be dubious, so use TSpectrum) binMaxCnt_value = (Double_t) htemp->GetXaxis()->GetBinCenter(binMaxCnt); //if the bin number is known and the bin value (in x-axis units) is wanted binMaxCnt_counts = (Int_t) htemp->GetBinContent(binMaxCnt); //Finds counts within particular bin //---------TSpectrum Peak Finding Parameters-------- if (ShowFit) NPeaks = s->Search(htemp, 2, "goff", 0.5); //opens a canvas (one time in a loop), even with: s->Search(htemp, 2, "nodraw", 0.9); //else NPeaks = s->Search(htemp, 2, "", 0.5); //s->Search(htemp, 2, "nodraw", 0.9); //Npeaks = s->GetNPeaks(); //If using this, need pointer in declaration above: Int_t *NPeaks //N_peaks = Npeaks[0]; Peak = s->GetPositionX(); PeakAmp = s->GetPositionY(); for (int i=0; i<NPeaks; i++) { if (peak_pos_amp < PeakAmp[i]) { peak_pos_amp = PeakAmp[i]; //TSpectrum finds peak counts peak_pos = Peak[i]; //TSpectrum finds pos. of peak in x-axis units } } peak_pos_bin = htemp->GetXaxis()->FindBin(peak_pos); //if the bin value (in x-axis units) is known and the bin number is wanted peak_pos_count = htemp->GetBinContent(peak_pos_bin); //counts in particular bin //------------------------------------------------------------------------------------------------------------------ zero_value_bin = htemp->GetXaxis()->FindBin(0.0); //if the bin value (in x-axis units) is known and the bin number is wanted Nbins = htemp->GetSize() - 2; //total number of bins in histo zero_bin_value = htemp->GetXaxis()->GetBinCenter(0); //if the bin number is known and the bin value (in x-axis units) is wanted. max_bin_value = htemp->GetXaxis()->GetBinCenter(Nbins); //if the bin number is known and the bin value (in x-axis units) is wanted. int TS = 0; if (peak_pos >= zero_bin_value && peak_pos <= max_bin_value) //Make sure that TSpectrum peak is within histo range { //if not, use Par initial values from Basic Histo Peak Find TS=1; //for cout below low_limit = peak_pos - (0.1 * abs(max_bin_value-zero_bin_value)); //peakpos-10% of full range of histo high_limit = peak_pos + (0.1 * abs(max_bin_value-zero_bin_value)); //peakpos+10% of full range of histo func = new TF1("func", "gaus"); //func->FixParameter(1,0); //func->SetParLimits(0, 0, 1000000); func->SetParameter(0, peak_pos_count); func->SetParameter(1, peak_pos); } else { low_limit = binMaxCnt_value - (0.1 * abs(max_bin_value-zero_bin_value)); //peakpos-10% of full range of histo high_limit = binMaxCnt_value + (0.1 * abs(max_bin_value-zero_bin_value)); //peakpos+10% of full range of histo func = new TF1("func", "gaus"); //func->SetParLimits(0, 0, 1000000); func->SetParameter(0, binMaxCnt_counts); func->SetParameter(1, binMaxCnt_value); } htemp->Fit("gaus", "Q0", "", low_limit, high_limit); //low_limit, high_limit); // To Show fit: htemp->Fit("gaus"); //better fit?-> Fit("gaus", "MQ", "", "", ""); func = htemp->GetFunction("gaus"); Chi2 = func->GetChisquare(); NDF = func->GetNDF(); if (NDF != 0) f_RChi2 = Chi2/NDF; f_const = func->GetParameter(0); f_mean = func->GetParameter(1); f_mean_err = func->GetParError(1); f_sigma = func->GetParameter(2); f_sigma_err = func->GetParError(2); /* if (N_sigma_range == 7) { cout<<""<<endl; cout<<"---Basic Histo Peak Find---"<<endl; cout<<"binMaxCnt: "<<binMaxCnt<<endl; cout<<"binMaxCnt_value: "<<binMaxCnt_value<<endl; cout<<"binMaxCnt_counts: "<<binMaxCnt_counts<<endl; cout<<""<<endl; if (TS == 1) cout<<"---TSpectrum Peak Find: Succeeded!---"<<endl; else cout<<"---TSpectrum Peak Find: Failed!---"<<endl; cout<<"NPeaks: "<<NPeaks<<endl; cout<<"peak_pos (find max peak): "<<peak_pos<<endl; cout<<"peak_pos_amp (eval. amp of max peak) : "<<peak_pos_amp<<endl; cout<<""<<endl; cout<<"----------------------------------------"<<endl; cout<<"peak_pos_bin: "<<peak_pos_bin<<endl; cout<<"peak_pos_count: "<<peak_pos_count<<endl; cout<<"zero_value_bin: "<<zero_value_bin<<", Nbins: "<<Nbins<<endl; cout<<"zero_bin_value: "<<zero_bin_value<<", max_bin_value: "<<max_bin_value<<endl; cout<<"low, high limit: "<<low_limit<<", "<<high_limit<<endl; } */ //for (int i=0; i< (N_iter - 1); i++) for (int i=0; i< 2; i++) //8 seems to work well, so let's keep it constant here. { //htemp->Fit("gaus", "", "",(f_mean - (N_sigma_range*f_sigma)), (f_mean + (N_sigma_range*f_sigma) ) ); //show fit htemp->Fit("gaus", "Q0", "",(f_mean - (N_sigma_range*f_sigma)), (f_mean + (N_sigma_range*f_sigma) ) ); //don't show fit func = htemp->GetFunction("gaus"); Chi2 = func->GetChisquare(); NDF = func->GetNDF(); if (NDF != 0) f_RChi2 = Chi2/NDF; f_const = func->GetParameter(0); f_mean = func->GetParameter(1); f_mean_err = func->GetParError(1); f_sigma = func->GetParameter(2); cout << " sigma " << f_sigma << endl; f_sigma_err = func->GetParError(2); } peak = func->GetParameter(0); //Amplitude float bgd_h = 0.25; //background height ~ bgd_h*gaus_amp func1 = new TF1("func1", "gaus"); //-----------Fit Parameter constraints not needed here (see below): //func1->SetParLimits(0, 0, 1000000); //func1->SetParameters(f_const, f_mean, f_sigma); //Here: (Par1 initial value, Par2 initial value, Par3 initial value, etc) //func1->SetParameter(0, 200); //Here: Initial value of Par 0 = 200 //func1->SetParLimits(0, f_const*(1-bgd_h-0.2),f_const*(1-bgd_h+0.2) ); //Here: (Par_lower limit, Par upper limit) //func1->SetParLimits(1, f_mean-(f_sigma/2),f_mean+(f_sigma/2) ); //func1->SetParLimits(2, f_sigma-(f_sigma/2),f_sigma+(f_sigma/2) ); func2 = new TF1("func2", "gaus"); //-----------Fit Parameter constraints not needed here (see below): //func2->SetParameters(f_const/10, f_mean, 4*f_sigma); //(const, mean, sigma) //func2->SetParLimits(0,-1,(0.1*peak_pos_amp) ); //(const) //func2->SetParameters(1, f_mean, 4*f_sigma); //(mean) //func2->SetParameters(2, 4*f_sigma); //(sigma) //func2->SetParLimits(0, 0, f_const*(0.1) ); //func2->SetParLimits(1, f_mean-(4*f_sigma),f_mean+(4*f_sigma) ); //func2->SetParLimits(2, f_sigma-(10*f_sigma),f_sigma+(10*f_sigma) ); //func2->FixParameter(0, 40); //Test //cout<<"peak amp: "<<0.1*peak_pos_amp<<endl; //func2 = new TF1("func2", "pol2"); func3 = new TF1("func3", "func1 + func2", (f_mean - 3*f_sigma), (f_mean + 3*f_sigma) ); //-----------Fit Parameter constraints: func3->SetParameters(f_const, f_mean, f_sigma, f_const/10, f_mean, 4*f_sigma); //Set Initial Valules //func3->SetParLimits(0, 0, 1000000); //func3->SetParLimits(1, 0, 1000000); //func3->SetParLimits(2, 0, 1000000); func3->SetParLimits(3, 0, (0.05*peak_pos_amp) ); //Max=5% of peak amp //************Set peak limit of background sigma************* //func3->SetParLimits(4, 0, 1000000); //func3->SetParLimits(5, 0, 1000000); //htemp->Fit("func3");//, "", "",(f_mean - (N_sigma_range*f_sigma)), (f_mean + (N_sigma_range*f_sigma) ) ); //Show Fit htemp->Fit("func3", "Q0"); //Don't show fit func = htemp->GetFunction("func3"); Chi2 = func3->GetChisquare(); NDF = func->GetNDF(); if (NDF != 0) f_RChi2 = Chi2/NDF; f_const = func3->GetParameter(0); f_mean = func3->GetParameter(1); f_mean_err = func3->GetParError(1); f_sigma = func3->GetParameter(2); f_sigma_err = func3->GetParError(2); f_const2 = func3->GetParameter(3); f_mean2 = func3->GetParameter(4); f_mean_err2 = func3->GetParError(4); f_sigma2 = func3->GetParameter(5); f_sigma_err2 = func3->GetParError(5); func3->SetParNames("Primary Constant", "Primary Mean", "Primary Sigma", "Background Constant", "Background Mean", "Background Sigma"); //for (int j=0; j< (N_iter - 1); j++) for (int j=0; j<4; j++) { func3->SetParameters(f_const, f_mean, f_sigma, f_const2, f_mean2, f_sigma2); //htemp->Fit("func3", "Q", "", "",(f_mean - (N_sigma_range*f_sigma)), (f_mean + (N_sigma_range*f_sigma) ) ); //----------------Show or don't show fit----------------- if (ShowFit) htemp->Fit("func3", "Q");//*************Show Histo & Fit in quiet mode else htemp->Fit("func3", "Q0"); //*****************Don't show Histo & Fit in quiet mode //------------------------------------------------------- func3 = htemp->GetFunction("func3"); func3->SetLineColor(2); //htemp->SetLineColor(2); Chi2 = func3->GetChisquare(); NDF = func3->GetNDF(); if (NDF != 0) f_RChi2 = Chi2/NDF; f_const = func3->GetParameter(0); f_mean = func3->GetParameter(1); f_mean_err = func3->GetParError(1); f_sigma = func3->GetParameter(2); f_sigma_err = func3->GetParError(2); f_const2 = func3->GetParameter(3); f_mean2 = func3->GetParameter(4); f_mean_err2 = func3->GetParError(4); f_sigma2 = func3->GetParameter(5); f_sigma_err2 = func3->GetParError(5); } //gStyle->SetOptFit(kTRUE); //if (f_const > f_const2) if (abs(f_const-peak) < abs(f_const2-peak)) { myI2GFvalues.rchi2 = f_RChi2; myI2GFvalues.mean = f_mean; myI2GFvalues.mean_err = f_mean_err; myI2GFvalues.sigma = abs(f_sigma); myI2GFvalues.sigma_err = f_sigma_err; //myI2GFvalues.fit_func = new TF1("fit_func", "func3"); //not needed } else { myI2GFvalues.rchi2 = f_RChi2; myI2GFvalues.mean = f_mean2; myI2GFvalues.mean_err = f_mean_err2; myI2GFvalues.sigma = abs(f_sigma2); myI2GFvalues.sigma_err = f_sigma_err2; //myI2GFvalues.fit_func = new TF1("fit_func", "func3"); //not needed } return myI2GFvalues; delete s; delete func; delete func1; delete func2; delete func3; }
int main(int argc, char *argv[]) { cout.setf(ios::fixed, ios::floatfield); cout.precision(12); // Prompt for filename of run numbers int iXeRunPeriod; cout << "Enter Xenon run period: " << endl; cin >> iXeRunPeriod; cout << endl; /*bool allResponseClasses = true; int numResponseClasses = 0; vector <int> responseClasses; cout << "All Response Classes? (true=1/false=0): " << endl; cin >> allResponseClasses; cout << endl; if (!allResponseClasses) { cout << "Enter number of response classes: " << endl; cin >> numResponseClasses; cout << endl; if (numResponseClasses<1 || numResponseClasses>9) { cout << "Bad number of response classes to include!!\n"; exit(1); } responseClasses.resize(numResponseClasses,0); char quest[30]; for (int i=0; i<numResponseClasses; i++) { sprintf(quest,"Enter class #%i: ",i+1); cout << quest; cin >> responseClasses[i]; cout << endl; if (responseClasses[i]<0 || responseClasses[i]>8) { cout << "You entered a non-existent response class!\n"; exit(1); } } }*/ int nRuns = 0; int runList[500]; char temp[500]; sprintf(temp, "%s/run_lists/Xenon_Calibration_Run_Period_%i.dat", getenv("ANALYSIS_CODE"),iXeRunPeriod); ifstream fileRuns(temp); int ii = 0; while (fileRuns >> runList[ii]) { ii++; nRuns++; } cout << "... Number of runs: " << nRuns << endl; for (int i=0; i<nRuns; i++) { cout << runList[i] << endl; } double xyBinWidth = 5.; //2.5; PositionMap posmap(xyBinWidth,50.); posmap.setRCflag(false); //telling the position map to not use the RC choices Int_t nBinsXY = posmap.getNbinsXY(); // Open output ntuple string tempOutBase; string tempOut; //sprintf(tempOut, "position_map_%s.root", argv[1]); tempOutBase = "position_map_" + itos(iXeRunPeriod); /*if (!allResponseClasses) { tempOutBase+="_RC_"; for (int i=0; i< numResponseClasses; i++) { tempOutBase+=itos(responseClasses[i]); } }*/ tempOut = getenv("POSITION_MAPS")+tempOutBase+"_"+ftos(xyBinWidth)+"mm.root"; TFile *fileOut = new TFile(tempOut.c_str(),"RECREATE"); // Output histograms int nPMT = 8; int nBinHist = 4100;//1025; TH1D *hisxy[nPMT][nBinsXY][nBinsXY]; char *hisxyName = new char[10]; for (int p=0; p<nPMT; p++) { for (int i=0; i<posmap.getNbinsXY(); i++) { for (int j=0; j<posmap.getNbinsXY(); j++) { if (p == 0) sprintf(hisxyName, "e0_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j)); if (p == 1) sprintf(hisxyName, "e1_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j)); if (p == 2) sprintf(hisxyName, "e2_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j)); if (p == 3) sprintf(hisxyName, "e3_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j)); if (p == 4) sprintf(hisxyName, "w0_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j)); if (p == 5) sprintf(hisxyName, "w1_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j)); if (p == 6) sprintf(hisxyName, "w2_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j)); if (p == 7) sprintf(hisxyName, "w3_%0.0f_%0.0f", posmap.getBinCenter(i), posmap.getBinCenter(j)); hisxy[p][i][j] = new TH1D(hisxyName, "", nBinHist,-100.,4000.0); } } } // Loop through input ntuples char tempIn[500]; for (int i=0; i<nRuns; i++) { // Open input ntuple sprintf(tempIn, "%s/replay_pass2_%i.root",getenv("REPLAY_PASS2"), runList[i]); DataTree *t = new DataTree(); t->setupInputTree(std::string(tempIn),"pass2"); if ( !t->inputTreeIsGood() ) { std::cout << "Skipping " << tempIn << "... Doesn't exist or couldn't be opened.\n"; continue; } int nEvents = t->getEntries(); cout << "Processing " << runList[i] << " ... " << endl; cout << "... nEvents = " << nEvents << endl; // Loop over events for (int i=0; i<nEvents; i++) { t->getEvent(i); // Select Type 0 events if (t->PID != 1) continue; if (t->Type != 0) continue; //Cut out clipped events if ( t->Side==0 && ( t->xE.nClipped>0 || t->yE.nClipped>0 || t->xeRC<1 || t->xeRC>4 || t->yeRC<1 || t->yeRC>4 ) ) continue; else if ( t->Side==1 && ( t->xW.nClipped>0 || t->yW.nClipped>0 || t->xwRC<1 || t->xwRC>4 || t->ywRC<1 || t->ywRC>4) ) continue; /*bool moveOnX = true, moveOnY=true; // Determining if the event is of the correct response class in x and y //Swank addition: Wire Chamber Response class. for (int j=0; j<numResponseClasses; j++) { if (t->xeRC == responseClasses[j]) {moveOnX=false;} if (t->yeRC == responseClasses[j]) {moveOnY=false;} } if (moveOnX || moveOnY) continue;*/ // Type 0 East Trigger int intBinX, intBinY; if (t->Side == 0) { intBinX = posmap.getBinNumber(t->xE.center); intBinY = posmap.getBinNumber(t->yE.center); // Fill PMT histograms if (intBinX>-1 && intBinY>-1) hisxy[0][intBinX][intBinY]->Fill(t->ScintE.q1); if (intBinX>-1 && intBinY>-1) hisxy[1][intBinX][intBinY]->Fill(t->ScintE.q2); if (intBinX>-1 && intBinY>-1) hisxy[2][intBinX][intBinY]->Fill(t->ScintE.q3); if (intBinX>-1 && intBinY>-1) hisxy[3][intBinX][intBinY]->Fill(t->ScintE.q4); } // Type 0 West Trigger //moveOnX=moveOnY=true; else if (t->Side == 1) { //Swank Only Allow triangles!!! //for (int j=0; j<numResponseClasses; j++) { // if (t->xwRC == responseClasses[j]) {moveOnX=false;} // if (t->ywRC == responseClasses[j]) {moveOnY=false;} //} //if (moveOnX || moveOnY) continue; intBinX = posmap.getBinNumber(t->xW.center); intBinY = posmap.getBinNumber(t->yW.center); // Fill PMT histograms if (intBinX>-1 && intBinY>-1) hisxy[4][intBinX][intBinY]->Fill(t->ScintW.q1); if (intBinX>-1 && intBinY>-1) hisxy[5][intBinX][intBinY]->Fill(t->ScintW.q2); if (intBinX>-1 && intBinY>-1) hisxy[6][intBinX][intBinY]->Fill(t->ScintW.q3); if (intBinX>-1 && intBinY>-1) hisxy[7][intBinX][intBinY]->Fill(t->ScintW.q4); } } // Close input ntuple delete t; } //Rebinning the histograms based on the mean value... for (int p=0; p<nPMT; p++) { for (int i=0; i<nBinsXY; i++) { for (int j=0; j<nBinsXY; j++) { hisxy[p][i][j]->GetXaxis()->SetRange(1,nBinHist); Double_t mean = hisxy[p][i][j]->GetMean(); hisxy[p][i][j]->GetXaxis()->SetRange(0,nBinHist); double nGroup = 4.*mean/200.; nGroup = nGroup>1. ? nGroup : 1.; hisxy[p][i][j]->Rebin((int)nGroup); } } } // Extracting mean from 200 keV peak // Define fit ranges double xLowBin[nPMT][nBinsXY][nBinsXY]; double xHighBin[nPMT][nBinsXY][nBinsXY]; double xLow[nPMT][nBinsXY][nBinsXY]; double xHigh[nPMT][nBinsXY][nBinsXY]; int maxBin[nPMT][nBinsXY][nBinsXY]; double maxCounts[nPMT][nBinsXY][nBinsXY]; double binCenterMax[nPMT][nBinsXY][nBinsXY]; double meanVal[nPMT][nBinsXY][nBinsXY]; // Holds the mean of the distribution as defined by first fitting the peak double fitMean[nPMT][nBinsXY][nBinsXY]; // Holds the mean of the low energy peak double fitSigma[nPMT][nBinsXY][nBinsXY]; // Holds the sigma of the low energy peak double endpoint[nPMT][nBinsXY][nBinsXY]; // Holds the endpoint /////// First determine roughly where the low energy peak is TSpectrum *spec; for (int p=0; p<nPMT; p++) { for (int i=0; i<nBinsXY; i++) { for (int j=0; j<nBinsXY; j++) { double r = sqrt(power(posmap.getBinCenter(j),2)+power(posmap.getBinCenter(i),2)); // Find bin with maximum content hisxy[p][i][j]->GetXaxis()->SetRange(2,nBinHist); maxBin[p][i][j] = hisxy[p][i][j]->GetMaximumBin(); maxCounts[p][i][j] = hisxy[p][i][j]->GetBinContent(maxBin[p][i][j]); binCenterMax[p][i][j] = hisxy[p][i][j]->GetBinCenter(maxBin[p][i][j]); if (r<=(50.+2*xyBinWidth)) { spec = new TSpectrum(20); Int_t npeaks = spec->Search(hisxy[p][i][j],1.5,"",0.5); if (npeaks==0) { cout << "No peaks identified at PMT" << p << " position " << posmap.getBinCenter(i) << ", " << posmap.getBinCenter(j) << endl; } else { Float_t *xpeaks = spec->GetPositionX(); // Note that newer versions of ROOT return a pointer to double... TAxis *xaxis = (TAxis*)(hisxy[p][i][j]->GetXaxis()); Int_t peakBin=0; Double_t BinSum=0.; Double_t BinSumHold = 0.; Int_t maxPeak=0.; for (int pk=0;pk<npeaks;pk++) { peakBin = xaxis->FindBin(xpeaks[pk]); //Sum over 3 center bins of peak and compare to previos BinSum to see which peak is higher BinSum = hisxy[p][i][j]->GetBinContent(peakBin) + hisxy[p][i][j]->GetBinContent(peakBin-1) + hisxy[p][i][j]->GetBinContent(peakBin+1); if (BinSum>BinSumHold) { BinSumHold=BinSum; maxPeak=pk; } } binCenterMax[p][i][j] = xpeaks[maxPeak]; } delete spec; } xLow[p][i][j] = binCenterMax[p][i][j]*2./3.; xHigh[p][i][j] = 1.5*binCenterMax[p][i][j]; } } } //////// Now fit the histograms for the peak for (int p=0; p<nPMT; p++) { for (int i=0; i<nBinsXY; i++) { for (int j=0; j<nBinsXY; j++) { if ( hisxy[p][i][j]->Integral() > 500.) {// && r<=(50.+2*xBinWidth)) { SinglePeakHist sing(hisxy[p][i][j], xLow[p][i][j], xHigh[p][i][j], true, 5, 0.8, 1.); if (sing.isGoodFit() && sing.ReturnMean()>xLow[p][i][j] && sing.ReturnMean()<xHigh[p][i][j]) { fitMean[p][i][j] = sing.ReturnMean(); fitSigma[p][i][j] = sing.ReturnSigma(); } else { cout << "Can't converge on peak in PMT " << p << " at (" << posmap.getBinCenter(i) << ", " << posmap.getBinCenter(j) << "). Trying one more time......" << endl; sing.SetRangeMin(xLow[p][i][j]); sing.SetRangeMax(xHigh[p][i][j]); sing.FitHist((double)maxBin[p][i][j], hisxy[p][i][j]->GetMean()/5., hisxy[p][i][j]->GetBinContent(maxBin[p][i][j])); if (sing.isGoodFit() && sing.ReturnMean()>xLow[p][i][j] && sing.ReturnMean()<xHigh[p][i][j]) { fitMean[p][i][j] = sing.ReturnMean(); fitSigma[p][i][j] = sing.ReturnSigma(); } else { fitMean[p][i][j] = hisxy[p][i][j]->GetMean()/1.8; int meanBin = hisxy[p][i][j]->GetXaxis()->FindBin(fitMean[p][i][j]); int counts_check = hisxy[p][i][j]->GetBinContent(meanBin); int counts = counts_check; int bin=0; if ( counts_check > 10 ) { while (counts>0.6*counts_check) { bin++; counts = hisxy[p][i][j]->GetBinContent(meanBin+bin); } } xHighBin[p][i][j] = (meanBin+bin) < hisxy[p][i][j]->GetNbinsX()/3 ? (meanBin+bin): meanBin; fitSigma[p][i][j] = hisxy[p][i][j]->GetBinCenter(xHighBin[p][i][j]) - fitMean[p][i][j]; cout << "Can't converge on peak in PMT " << p << " at bin (" << posmap.getBinCenter(i) << ", " << posmap.getBinCenter(j) << "). "; cout << "**** replaced fit mean with hist_mean/1.8 " << fitMean[p][i][j] << endl; } } } else { fitMean[p][i][j] = hisxy[p][i][j]->GetMean()/1.8; //if ( fitMean[p][i][j]>xLow[p][i][j] && fitMean[p][i][j]<xHigh[p][i][j] ) cout << "**** replaced fit mean with hist_mean/1.8 " << fitMean[p][i][j] << endl; //else { //fitMean[p][i][j] = binCenterMax[p][i][j]; //cout << "**** replaced fit mean with binCenterMax " << fitMean[p][i][j] << endl; //} int meanBin = hisxy[p][i][j]->GetXaxis()->FindBin(fitMean[p][i][j]); int counts_check = hisxy[p][i][j]->GetBinContent(meanBin); int counts = counts_check; int bin=0; double frac = exp(-1/2.); // This should be the fraction of events for a gaussian at 1 sigma if ( counts_check > 10 ) { while (counts>frac*counts_check) { bin++; counts = hisxy[p][i][j]->GetBinContent(meanBin+bin); } } xHighBin[p][i][j] = (meanBin+bin) < hisxy[p][i][j]->GetNbinsX()/3 ? (meanBin+bin): meanBin; fitSigma[p][i][j] = hisxy[p][i][j]->GetBinCenter(xHighBin[p][i][j]) - fitMean[p][i][j]; } } } } fileOut->Write(); // Writing the histograms with the peaks to file ////////// Now determine the mean of the Xe distribution in every position bin above the peak to avoid ////////// trigger effects double nSigmaFromMean = 1.5; // This is how far over from the peak we are starting the sum of the spectra for (int p=0; p<nPMT; p++) { for (int i=0; i<nBinsXY; i++) { for (int j=0; j<nBinsXY; j++) { hisxy[p][i][j]->GetXaxis()->SetRange(hisxy[p][i][j]->GetXaxis()->FindBin(fitMean[p][i][j]+nSigmaFromMean*fitSigma[p][i][j]), hisxy[p][i][j]->GetNbinsX()-1); meanVal[p][i][j] = hisxy[p][i][j]->GetMean(); hisxy[p][i][j]->GetXaxis()->SetRange(0, hisxy[p][i][j]->GetNbinsX()); // Set the range back to the full range } } } ////////// Now determine the endpoint of the Xe distribution in every position bin double lowerBoundMult = 1.; double upperBoundMult = 2.; TFile *epfile = new TFile(TString::Format("%s/%s_%smm_endpoints.root",getenv("POSITION_MAPS"),tempOutBase.c_str(),ftos(xyBinWidth).c_str()),"RECREATE"); TGraphErrors epgraph; KurieFitter kf; for (int p=0; p<nPMT; p++) { for (int i=0; i<nBinsXY; i++) { for (int j=0; j<nBinsXY; j++) { kf.FitSpectrum(hisxy[p][i][j], lowerBoundMult*meanVal[p][i][j], upperBoundMult*meanVal[p][i][j], 1.); endpoint[p][i][j] = kf.returnK0(); epgraph = kf.returnKuriePlot(); epgraph.SetName(TString::Format("pmt%i_x%0.1f_y%0.1f",p,posmap.getBinCenter(i), posmap.getBinCenter(j))); epgraph.Write(); } } } delete epfile; delete fileOut; ///////////////////////// Extract position maps for meanVal /////////////////////////////// double norm[nPMT]; for (int p=0; p<nPMT; p++) { norm[p] = meanVal[p][nBinsXY/2][nBinsXY/2]; cout << norm[p] << endl; } //Checking for weird outliers for (int p=0; p<nPMT; p++) { for (int i=0; i<nBinsXY; i++) { for (int j=0; j<nBinsXY; j++) { if ( meanVal[p][i][j]<(0.1*norm[p]) || meanVal[p][i][j]>(8.*norm[p]) ) meanVal[p][i][j] = (0.1*norm[p]); } } } double positionMap[nPMT][nBinsXY][nBinsXY]; for (int p=0; p<nPMT; p++) { for (int i=0; i<nBinsXY; i++) { for (int j=0; j<nBinsXY; j++) { positionMap[p][i][j] = meanVal[p][i][j] / norm[p]; } } } // Write position maps to file TString mapFile = TString::Format("%s/%s_%0.1fmm.dat", getenv("POSITION_MAPS"),tempOutBase.c_str(),xyBinWidth); ofstream outMap(mapFile.Data()); for (int i=0; i<nBinsXY; i++) { for (int j=0; j<nBinsXY; j++) { outMap << posmap.getBinCenter(i) << " " << posmap.getBinCenter(j) << " " << positionMap[0][i][j] << " " << positionMap[1][i][j] << " " << positionMap[2][i][j] << " " << positionMap[3][i][j] << " " << positionMap[4][i][j] << " " << positionMap[5][i][j] << " " << positionMap[6][i][j] << " " << positionMap[7][i][j] << endl; } } outMap.close(); // Write norms to file TString normFile = TString::Format("%s/norm_%s_%0.1fmm.dat", getenv("POSITION_MAPS"),tempOutBase.c_str(),xyBinWidth); ofstream outNorm(normFile.Data()); for (int p=0; p<nPMT; p++) { outNorm << norm[p] << endl; } outNorm.close(); ///////////////////////// Extract position maps for peaks /////////////////////////////// for (int p=0; p<nPMT; p++) { norm[p] = fitMean[p][nBinsXY/2][nBinsXY/2]; cout << norm[p] << endl; } //Checking for weird outliers for (int p=0; p<nPMT; p++) { for (int i=0; i<nBinsXY; i++) { for (int j=0; j<nBinsXY; j++) { if ( fitMean[p][i][j]<(0.1*norm[p]) || fitMean[p][i][j]>(8.*norm[p]) ) fitMean[p][i][j] = (0.1*norm[p]); } } } for (int p=0; p<nPMT; p++) { for (int i=0; i<nBinsXY; i++) { for (int j=0; j<nBinsXY; j++) { positionMap[p][i][j] = fitMean[p][i][j] / norm[p]; } } } // Write position maps to file mapFile = TString::Format("%s/%s_%0.1fmm_peakFits.dat", getenv("POSITION_MAPS"),tempOutBase.c_str(),xyBinWidth); outMap.open(mapFile.Data()); for (int i=0; i<nBinsXY; i++) { for (int j=0; j<nBinsXY; j++) { outMap << posmap.getBinCenter(i) << " " << posmap.getBinCenter(j) << " " << positionMap[0][i][j] << " " << positionMap[1][i][j] << " " << positionMap[2][i][j] << " " << positionMap[3][i][j] << " " << positionMap[4][i][j] << " " << positionMap[5][i][j] << " " << positionMap[6][i][j] << " " << positionMap[7][i][j] << endl; } } outMap.close(); ///////////////////////// Extract position maps for endpoints /////////////////////////////// for (int p=0; p<nPMT; p++) { norm[p] = endpoint[p][nBinsXY/2][nBinsXY/2]; cout << norm[p] << endl; } //Checking for weird outliers for (int p=0; p<nPMT; p++) { for (int i=0; i<nBinsXY; i++) { for (int j=0; j<nBinsXY; j++) { if ( endpoint[p][i][j]<(0.1*norm[p]) || endpoint[p][i][j]>(8.*norm[p]) ) endpoint[p][i][j] = (0.1*norm[p]); } } } for (int p=0; p<nPMT; p++) { for (int i=0; i<nBinsXY; i++) { for (int j=0; j<nBinsXY; j++) { positionMap[p][i][j] = endpoint[p][i][j] / norm[p]; } } } // Write position maps to file mapFile = TString::Format("%s/%s_%0.1fmm_endpoints.dat", getenv("POSITION_MAPS"),tempOutBase.c_str(),xyBinWidth); outMap.open(mapFile.Data()); for (int i=0; i<nBinsXY; i++) { for (int j=0; j<nBinsXY; j++) { outMap << posmap.getBinCenter(i) << " " << posmap.getBinCenter(j) << " " << positionMap[0][i][j] << " " << positionMap[1][i][j] << " " << positionMap[2][i][j] << " " << positionMap[3][i][j] << " " << positionMap[4][i][j] << " " << positionMap[5][i][j] << " " << positionMap[6][i][j] << " " << positionMap[7][i][j] << endl; } } outMap.close(); return 0; }
void fit(){ int range = 1e4; TFile *f = new TFile("hgrroot.root"); TCanvas *ca = new TCanvas("ca","ca",0,0,1400,900); ca->Divide(4,4); TH1F* h[7][4]; TF1* fu[7][4][2]; TF1* fus[7][4][2][3]; double res[7*4]; double det[7*4]; double slope[7*4]; double offset[7*4]; double resolution =5; TEnv* output = new TEnv("corecal.dat"); for(int d=0;d<7;d++){ for(int c=0;c<4;c++){ h[d][c] = (TH1F*)f->Get(Form("htraceen_b%d_c%d_cr%d_d%d",0,9,c,d+1)); ca->cd(1+c*4); //h[d][c]->GetXaxis()->SetRangeUser(100,4000); TSpectrum *sp = new TSpectrum(2,resolution); sp->SetResolution(resolution); Int_t nfound = 0; nfound = sp->Search(h[d][c],resolution,"nobackground",0.5); Float_t *xpeaks = sp->GetPositionX(); Float_t *ypeaks = sp->GetPositionY(); // for(int p=0;p<nfound;p++){ // cout << xpeaks[p] << "\t" << ypeaks[p] << endl; // } if(nfound!=2){ cout << "Found " << nfound << " peaks in spectrum, too many, aborting" << endl; continue; } h[d][c]->DrawCopy(); //check if first peak is lower in energy, otherwise swap them if(xpeaks[0]>xpeaks[1]){ Float_t temp = xpeaks[1]; xpeaks[1] = xpeaks[0]; xpeaks[0] = temp; temp = ypeaks[1]; ypeaks[1] = ypeaks[0]; ypeaks[0] = temp; } for(int p=0;p<nfound;p++){ ca->cd(1+c*4+1+p); h[d][c]->GetXaxis()->SetRangeUser(xpeaks[p]-range,xpeaks[p]+range); h[d][c]->DrawCopy(); fu[d][c][p] = new TF1(Form("fcore_d%d_c%d_p%d",d,c,p),fgammagaussbg,xpeaks[p]-range,xpeaks[p]+range,6); fu[d][c][p]->SetLineColor(3); fu[d][c][p]->SetLineWidth(1); fu[d][c][p]->SetParameter(0,0);//bg const fu[d][c][p]->SetParameter(1,0);//bg slope fu[d][c][p]->SetParameter(2,h[d][c]->Integral(xpeaks[p]-range,xpeaks[p]+range));//norm fu[d][c][p]->SetParameter(3,xpeaks[p]);//mean fu[d][c][p]->SetParLimits(3,xpeaks[p]-500,xpeaks[p]+500);//mean fu[d][c][p]->SetParameter(4,100);//sigma fu[d][c][p]->SetParLimits(4,0.001,1000);//sigma fu[d][c][p]->SetParameter(5,h[d][c]->GetBinContent(h[d][c]->FindBin(xpeaks[p]-range)));//step h[d][c]->Fit(fu[d][c][p],"Rqn"); fu[d][c][p]->Draw("same"); fus[d][c][p][0] = new TF1(Form("fcore_d%d_c%d_p%d_bg",d,c,p),fgammabg,xpeaks[p]-range,xpeaks[p]+range,6); fus[d][c][p][1] = new TF1(Form("fcore_d%d_c%d_p%d_st",d,c,p),fgammastep,xpeaks[p]-range,xpeaks[p]+range,6); fus[d][c][p][2] = new TF1(Form("fcore_d%d_c%d_p%d_ga",d,c,p),fgammagaus,xpeaks[p]-range,xpeaks[p]+range,6); fus[d][c][p][0]->SetLineColor(5); fus[d][c][p][1]->SetLineColor(4); fus[d][c][p][2]->SetLineColor(2); for(int k=0;k<3;k++){ fus[d][c][p][k]->SetLineWidth(1); for(int l=0;l<6;l++) fus[d][c][p][k]->SetParameter(l,fu[d][c][p]->GetParameter(l)); fus[d][c][p][k]->Draw("same"); } }//peaks //res[d*4+c] = 2.35*fu[d][c][1]->GetParameter(4)*(1332.492-1173.228)/(fu[d][c][1]->GetParameter(3)-fu[d][c][0]->GetParameter(3)); slope[d*4+c] = (1332.492-1173.228)/(fu[d][c][1]->GetParameter(3)-fu[d][c][0]->GetParameter(3)); offset[d*4+c] = (1332.492+1173.228)-slope[d*4+c]*(fu[d][c][1]->GetParameter(3)+fu[d][c][0]->GetParameter(3)); offset[d*4+c]*=0.5; //cout << fu[d][c][0]->GetParameter(3)*slope[d*4+c] + offset[d*4+c] << "\t" << fu[d][c][1]->GetParameter(3)*slope[d*4+c] + offset[d*4+c] << endl; res[d*4+c] = fu[d][c][1]->GetParameter(2); det[d*4+c] = d*5+c; output->SetValue(Form("Slope.d%d.c%d",d,c),slope[d*4+c]); output->SetValue(Form("Offset.d%d.c%d",d,c),offset[d*4+c]); //cout << det[d*4+c] <<"\t" << res[d*4+c] << endl; //cout << fu[d][c][0]->GetParameter(4) <<"\t" << fu[d][c][1]->GetParameter(4) << endl; //ca->cd(1+c*4+3); TPad *p1 = (TPad *)(ca->cd(1+c*4+3)); p1->SetLogy(); h[d][c]->GetXaxis()->SetRangeUser((int)xpeaks[0]-range,(int)xpeaks[1]+range); h[d][c]->DrawCopy(); for(int p=0;p<nfound;p++){ fu[d][c][p]->Draw("same"); for(int k=0;k<3;k++){ fus[d][c][p][k]->Draw("same"); } } }//crystals if(d==0) ca->SaveAs("corefits.ps("); else ca->SaveAs("corefits.ps"); }//detectors output->SaveLevel(kEnvLocal); //TGraph *gres = new TGraph(7*4,det,res); TGraph *gres = new TGraph(7*4,slope,offset); TCanvas *ca2 = new TCanvas("ca2","ca2",0,0,1400,900); ca2->cd(); gres->Draw("AP"); gres->SetMarkerStyle(20); ca2->SaveAs("corefits.ps)"); }
void laserCalibration( char* filename = "frascatirun", //input file int filenum = 1081, //file number int channel = 3, //trace channel int flagChannel = 5, //laser flag channel Double_t entriesN = 10, //number of entries for prcessing int sleep = 10, //sleep time between 2 processed entries, helpful for viewing traces bool gui = true //enable or disable trace visualization ) { caen_5742 caen; Int_t nbins = 1024; Double_t entries = entriesN; Int_t bin; TCanvas *c1 = new TCanvas("c1","frascatirun",900,700); c1->Divide(1,2); c1->cd(1); TGraph* g = new TGraph(); TH1F* lmPeaks = new TH1F("lm","Peaks Ratio", 1000, 0, 5000); TH1F* d = new TH1F("d","",nbins,0,nbins); TH1F* back = new TH1F("Back","",nbins,0,nbins); // input file char fname[100]=0; sprintf(fname,"%s_0%i.root",filename,filenum); TFile* infile = new TFile(fname); TTree *t = (TTree*) infile->Get("t"); t->SetBranchAddress("caen_5742", &caen.system_clock); t->Print(); if(entriesN<=0) entries = t->GetEntries(); //out file char foutname[100]=0; int lm=0; if (channel ==3)lm=1; if (channel ==4)lm=2; sprintf(foutname,"./calibration/LM%i_out_0%i.root",lm,filenum); outfile = new TFile(foutname,"RECREATE"); outTree = new TTree("LM","frascatirun output"); calibTree = new TTree("LM_cal","frascatirun output"); outTree->Branch("LM_PX1",&fPositionX1,"PX1/D"); outTree->Branch("LM_PX2",&fPositionX2,"PX2/D"); outTree->Branch("LM_PY1",&fPositionY1,"PY1/D"); outTree->Branch("LM_PY2",&fPositionY2,"PY2/D"); //outTree->Branch("baseline",baseline,"baseline[1024]/F"); outTree->Branch("time",&timeline,"time/D"); outTree->Branch("LM_P2_Integral",&integralP2,"IP2/D"); calibTree->Branch("LM_P2_Integral_mean",&integralP2_mean,"IP2_mean/D"); calibTree->Branch("LM_P2_Integral_mean_error",&integralP2_mean_error,"IP2_mean_error/D"); calibTree->Branch("LM_P2_Integral_sigma",&integralP2_sigma,"IP2_sigma/D"); calibTree->Branch("LM_P2_Integral_sigma_error",&integralP2_sigma_error,"IP2_sigma_error/D"); /************************************** * read entries ************************************** */ for (int j = 0; j < entries; ++j){ gSystem->Sleep (sleep); t->GetEntry(j); //TRIGGER SELECTION if(caen.trace[flagChannel][400]>1000 && caen.trace[flagChannel][800]<3000){ timeline = caen.system_clock; /************************************** * Peaks estimation ************************************** */ for (int i = 0; i < nbins; ++i){ g->SetPoint(i, i, caen.trace[channel][i]); } Double_t y_max = TMath::MaxElement(g->GetN(),g->GetY()); Float_t * source = new Float_t[nbins]; Float_t * dest = new Float_t[nbins]; for (int i = 0; i < nbins; ++i){ source[i]=y_max-caen.trace[channel][i]; g->SetPoint(i, i, source[i]); } //Use TSpectrum to find the peak candidates TSpectrum *s = new TSpectrum(); Int_t nfound = s->SearchHighRes(source, dest, nbins, 3, 2, kTRUE, 2, kFALSE, 5); /************************************** * Background estimation ************************************** */ Int_t ssize = nbins; Int_t numberIterations = 20; Int_t direction = s->kBackIncreasingWindow; Int_t filterOrder = s->kBackOrder2; bool smoothing = kFALSE; Int_t smoothWindow = s->kBackSmoothing3; bool compton = kFALSE; for (int i = 0; i < nbins; ++i) baseline[i] = source[i]; s->Background(baseline, ssize, numberIterations, direction, filterOrder, smoothing, smoothWindow, compton); /************************************** * Peaks and integral estimation ************************************** */ Double_t px[2], py[2]; for (int i = 0; i < nbins; ++i) dest[i] = source[i]-baseline[i]; if(nfound==2){ bin = s->GetPositionX()[0]; fPositionX1 = bin; fPositionY1 = dest[bin]; px[0] = bin; py[0] = dest[bin]; bin = s->GetPositionX()[1]; fPositionX2 = bin; fPositionY2 = dest[bin]; px[1] = bin; py[1] = dest[bin]; } int posxa=6; int posxb=9; switch (filenum){ case 1081: posxa=6; posxb=9; break; case 1082: posxa=5; posxb=7; break; case 1083: posxa=5; posxb=8; break; case 1084: posxa=5; posxb=7; break; case 1085: posxa=5; posxb=7; break; case 1086: posxa=5; posxb=5; break; case 1087: posxa=4; posxb=4; break; case 1088: posxa=3; posxb=4; break; case 1089: posxa=3; posxb=3; break; default: posxa=6; posxb=9; } integralP2 = g->Integral (fPositionX2-posxa,fPositionX2+posxb); /************************************** * print and update the canvas ************************************** */ if(gui==true){ TH1F* gh = g->GetHistogram(); gh->FillN(nbins,g->GetX(),g->GetY()); g->Draw(); TPolyMarker* pm = (TPolyMarker*)gh->GetListOfFunctions()->FindObject("TPolyMarker"); if (pm) { gh->GetListOfFunctions()->Remove(pm); delete pm; } pm = new TPolyMarker(nfound, px, py); gh->GetListOfFunctions()->Add(pm); pm->SetMarkerStyle(23); pm->SetMarkerColor(kBlue); pm->SetMarkerSize(1.3); for (i = 0; i < nbins; i++) d->SetBinContent(i,dest[i]); d->SetLineColor(kRed); d->Draw("SAME"); for (i = 0; i < nbins; i++) back->SetBinContent(i,baseline[i]); back->SetLineColor(kGreen); back->Draw("SAME"); c1->Update(); } /************************************** * Fill tree and peaks data Histogram ************************************** */ if(nfound==2) { lmPeaks->Fill(integralP2); outTree->Fill(); } //printf("time= %d, posx1= %d, posy1= %d\n",time, fPositionX1, fPositionY1); //printf("time= %d, posx2= %d, posy2= %d\n",time, fPositionX2, fPositionY2); //for (int i=0;i<nbins;i++) printf("time = %d\n",baseline[i]); } } /************************************** * switch to the bottom pan and Draw Histogram ************************************** */ c1->cd(2); //lmPeaks->SetAxisRange(TMath::MinElement(entries,binmin),TMath::MaxElement(entries,binmax)+100); //lmPeaks->SetAxisRange(0,3000); lmPeaks->Fit("gaus"); integralP2_mean = lmPeaks->GetFunction("gaus")->GetParameter(1); integralP2_sigma = lmPeaks->GetFunction("gaus")->GetParameter(2); integralP2_mean_error = lmPeaks->GetFunction("gaus")->GetParError(1); integralP2_sigma_error = lmPeaks->GetFunction("gaus")->GetParError(2); //printf("mean = %f\n",integralP2_mean); //printf("sigma = %f\n",integralP2_sigma); calibTree->Fill(); lmPeaks->Draw(); c1->Update(); outfile->cd(); gROOT->GetList()->Write(); outTree->Write(); calibTree->Write(); outfile->Close(); }
//------------------------------------------------------------------------ void DrawWalk() { Int_t npeaks = 20; Int_t sigma=3.; Bool_t down = false; Int_t index[20]; Char_t buf1[10], buf2[10]; TCanvas *c1 = new TCanvas("c1", "c1",0,48,1280,951); gStyle->SetOptStat(0); c1->Divide(4,3); for (Int_t i=0; i<12; i++) { c1->cd(i+1); sprintf(buf1,"T0_C_%i_CFD",i+1); sprintf(buf2,"CFDvsQTC%i",i+1); cout<<buf1<<" "<<buf2<<endl; TH2F *qtc_cfd = (TH2F*) gFile->Get(buf2); TH1F *cfd = (TH1F*) gFile->Get(buf1); // cfd->Draw(); TSpectrum *s = new TSpectrum(2*npeaks,1); Int_t nfound = s->Search(cfd,sigma," ",0.05); cout<<"Found "<<nfound<<" peaks sigma "<<sigma<<endl;; if(nfound!=0){ Float_t *xpeak = s->GetPositionX(); TMath::Sort(nfound, xpeak, index,down); Float_t xp = xpeak[index[0]]; Int_t xbin = cfd->GetXaxis()->FindBin(xp); Float_t yp = cfd->GetBinContent(xbin); cout<<"xbin = "<<xbin<<"\txpeak = "<<xpeak[1]<<"\typeak = "<<yp<<endl; Float_t hmax = xp+10*sigma; Float_t hmin = xp-10*sigma; cout<<hmin<< " "<<hmax<<endl; // cfd->GetXaxis()->SetRange(hmin,hmax); // TF1 *g1 = new TF1("g1", "gaus", hmin, hmax); // cfd->Fit("g1","R"); Int_t hminbin= qtc_cfd->GetXaxis()->GetFirst(); Int_t hmaxbin= qtc_cfd->GetXaxis()->GetLast(); Int_t nbins= qtc_cfd->GetXaxis()->GetNbins(); cout<<" qtc_cfd "<<hminbin<<" "<<hmaxbin<<" "<<nbins<<endl; // qtc_cfd->Draw(); TProfile *pr_y = qtc_cfd->ProfileX(); Float_t maxHr=pr_y->GetBinCenter(hmaxbin); pr_y->SetMaximum(hmax); pr_y->SetMinimum(hmin); Int_t np=nbins/20; Double_t *xx = new Double_t[np]; Double_t *yy = new Double_t[np]; Int_t ng=0; Double_t yg=0; for (Int_t ip=1; ip<nbins; ip++) { if(ip%20 != 0 ) { if (pr_y->GetBinContent(ip) !=0) yg +=pr_y->GetBinContent(ip); // cout<<ng<<" "<<pr_y->GetBinContent(ip)<<" "<<yg<<endl; ng++;} else { xx[ip/20] = Float_t (pr_y->GetBinCenter(ip)); yy[ip/20] = yg/ng; yg=0; ng=0; cout<<ip<<" "<<ip/20<<" "<< xx[ip/20]<<" "<< yy[ip/20]<<endl; } } TH2F *hr = new TH2F("hr"," ",np,0,maxHr, np, hmin, hmax); hr->Draw(); TGraph *gr = new TGraph(np,xx,yy); gr->SetMinimum(hmin); gr->SetMaximum(hmax); gr->SetMarkerStyle(20); gr->Draw("P"); // delete [] xx; // delete [] yy; // pr_y->Rebin(10); // pr_y->Draw(); } } }
//------------------------------------------------------------------------ void DrawLEDminCFD() { Int_t npeaks = 10; Int_t sigma=10.; Bool_t down=false; Int_t index[20]; TCanvas *c1 = new TCanvas("c1", " LED-CFD C side",0,48,1280,951); c1->Divide(4,3); Char_t buf1[20]; for (Int_t i=0; i<12; i++) { c1->cd(i+1); sprintf(buf1,"LEDminCFD%i",i+1); TH1F *cfd = (TH1F*) gFile->Get(buf1); cfd->Draw(); TSpectrum *s = new TSpectrum(2*npeaks,1); Int_t nfound = s->Search(cfd,sigma," ",0.2); cout<<"Found "<<nfound<<" peaks sigma "<<sigma<<endl;; if(nfound!=0) { Float_t *xpeak = s->GetPositionX(); TMath::Sort(nfound, xpeak, index,down); Float_t xp = xpeak[index[0]]; Int_t xbin = cfd->GetXaxis()->FindBin(xp); Float_t yp = cfd->GetBinContent(xbin); cout<<"xbin = "<<xbin<<"\txpeak = "<<xpeak[index[0]]<<"\typeak = "<<yp<<endl; Float_t hmin=xp-3*sigma; Float_t hmax =xp+3*sigma; cfd->GetXaxis()->SetRange(hmin,hmax); TF1 *g1 = new TF1("g1", "gaus", hmin, hmax); cfd->Fit("g1","RQ"); } } TCanvas *c2 = new TCanvas("c2", "LED-CFD A side",0,48,1280,951); c2->Divide(4,3); Char_t buf1[20]; for (Int_t i=12; i<24; i++) { c2->cd(i+1-12); sprintf(buf1,"LEDminCFD%i",i+1); TH1F *cfd = (TH1F*) gFile->Get(buf1); cfd->Draw(); TSpectrum *s = new TSpectrum(2*npeaks,1); Int_t nfound = s->Search(cfd,sigma," ",0.2); cout<<"Found "<<nfound<<" peaks sigma "<<sigma<<endl;; if(nfound!=0) { Float_t *xpeak = s->GetPositionX(); TMath::Sort(nfound, xpeak, index,down); Float_t xp = xpeak[index[0]]; Int_t xbin = cfd->GetXaxis()->FindBin(xp); Float_t yp = cfd->GetBinContent(xbin); cout<<"xbin = "<<xbin<<"\txpeak = "<<xpeak[index[0]]<<"\typeak = "<<yp<<endl; Float_t hmin=xp-3*sigma; Float_t hmax =xp+3*sigma; cfd->GetXaxis()->SetRange(hmin,hmax); TF1 *g1 = new TF1("g1", "gaus", hmin, hmax); cfd->Fit("g1","RQ"); } } /* TCanvas *c1 = new TCanvas("c1", "c1",0,48,1280,951); c1->Divide(2,2); Char_t buf1[10]; for (Int_t i=0; i<4; i++) { c1->cd(i+1); sprintf(buf1,"LED-CFD%i",i+1); TH1F *cfd = (TH1F*) file->Get(buf1); // cout<<buf1<<" "<<cfd<<endl; // cfd->Draw(); // cfd->GetXaxis()->SetRange(0,100); Float_t mean = cfd->GetMean(); Float_t rms = cfd->GetRMS(); Float_t hmin=mean - 3*rms; Float_t hmax =mean + 3*rms; cfd->GetXaxis()->SetRange(hmin-10,hmax+10); cout<<" cfd range "<<mean<<" rms "<<rms<<" "<<hmin<<" "<<hmax<<endl; // TF1 *g1 = new TF1("g1", "gaus", hmin, hmax); // cfd->Fit("g1","RQ"); cfd->Draw(); } */ }
//------------------------------------------------------------------------ void DrawCFD() { Int_t npeaks = 20; Int_t sigma=3.; Bool_t down=false; Int_t index[20]; TCanvas *c1 = new TCanvas("c1", "CFD C side",0,48,1280,951); c1->Divide(4,3); gStyle->SetOptFit(1111); //c1->Divide(2,2); Char_t buf1[10]; for (Int_t i=0; i<12; i++) { c1->cd(i+1); sprintf(buf1,"T0_C_%i_CFD",i+1); TH1F *cfd = (TH1F*) gFile->Get(buf1); // cfd->Draw(); TSpectrum *s = new TSpectrum(2*npeaks,1); Int_t nfound = s->Search(cfd,sigma," ",0.05); cout<<"Found "<<nfound<<" peaks sigma "<<sigma<<endl;; if(nfound!=0){ Float_t *xpeak = s->GetPositionX(); TMath::Sort(nfound, xpeak, index,down); Float_t xp = xpeak[index[0]]; cout<<" index[0] "<<index[0]<<endl; // Float_t xp = xpeak[1]; Int_t xbin = cfd->GetXaxis()->FindBin(xp); Float_t yp = cfd->GetBinContent(xbin); cout<<"xbin = "<<xbin<<"\txpeak = "<<xpeak[1]<<"\typeak = "<<yp<<endl; Float_t hmax = xp+3*sigma; Float_t hmin = xp-3*sigma; cout<<hmin<< " "<<hmax<<endl; cfd->GetXaxis()->SetRange(hmin-10,hmax+10); cout<<" cfd range "<<hmin-10<<" "<<hmax+10<<endl; cfd->GetXaxis()->SetLabelSize(0.03); TF1 *g1 = new TF1("g1", "gaus", hmin, hmax); cfd->Fit("g1","R"); // cfd->Draw(); } } TCanvas *c2 = new TCanvas("c2", "CFD A side",0,48,1280,951); c2->Divide(4,3); gStyle->SetOptFit(1111); //c1->Divide(2,2); Char_t buf1[10]; for (Int_t i=0; i<12; i++) { c2->cd(i+1); sprintf(buf1,"T0_A_%i_CFD",i+1); TH1F *cfd = (TH1F*) gFile->Get(buf1); // cfd->Draw(); TSpectrum *s = new TSpectrum(2*npeaks,1); Int_t nfound = s->Search(cfd,sigma," ",0.05); cout<<"Found "<<nfound<<" peaks sigma "<<sigma<<endl;; if(nfound!=0){ Float_t *xpeak = s->GetPositionX(); TMath::Sort(nfound, xpeak, index,down); Float_t xp = xpeak[index[0]]; cout<<" index[0] "<<index[0]<<endl; // Float_t xp = xpeak[1]; Int_t xbin = cfd->GetXaxis()->FindBin(xp); Float_t yp = cfd->GetBinContent(xbin); cout<<"xbin = "<<xbin<<"\txpeak = "<<xpeak[1]<<"\typeak = "<<yp<<endl; Float_t hmax = xp+3*sigma; Float_t hmin = xp-3*sigma; cout<<hmin<< " "<<hmax<<endl; cfd->GetXaxis()->SetRange(hmin-10,hmax+10); cout<<" cfd range "<<hmin-10<<" "<<hmax+10<<endl; cfd->GetXaxis()->SetLabelSize(0.03); TF1 *g1 = new TF1("g1", "gaus", hmin, hmax); cfd->Fit("g1","R"); // cfd->Draw(); } } }
//------------------------------------------------------------------------ void DrawCFDvsLED() { Int_t runNumber=1098; Int_t npeaks = 20; Int_t sigma=2.; Char_t buf1[10], buf2[10]; TCanvas *c1 = new TCanvas("c1", "c1",0,48,1280,951); gStyle->SetOptStat(0); c1->Divide(4,3); for (Int_t i=0; i<12; i++) { c1->cd(i+1); sprintf(buf1,"T0_C_%i_CFD",i+1); sprintf(buf2,"CFDvsLED%i",i+1); TH2F *qtc_cfd = (TH2F*) gFile->Get(buf2); //qtc_cfd->Draw(); TH1F *cfd = (TH1F*) gFile->Get(buf1); // cfd->Draw(); TSpectrum *s = new TSpectrum(2*npeaks,1); Int_t nfound = s->Search(cfd,sigma," ",0.05); cout<<"Found "<<nfound<<" peaks sigma "<<sigma<<endl;; if(nfound!=0){ Double_t max=0.0; Double_t tabmax[2] = {0.0, 0.0}; Float_t *xpeak = s->GetPositionX(); for(Int_t k=0; k<1 ;k++) { Float_t xp = xpeak[k]; Int_t xbin = cfd->GetXaxis()->FindBin(xp); Float_t yp = cfd->GetBinContent(xbin); cout<<"xbin = "<<xbin<<"\txpeak = "<<xpeak[k]<<"\typeak = "<<yp<<endl; } Float_t hmin=xp-10*sigma; Float_t hmax =xp+10*sigma; cout<<hmin<< " "<<hmax<<endl; // cfd->GetXaxis()->SetRange(hmin,hmax); // TF1 *g1 = new TF1("g1", "gaus", hmin, hmax); // cfd->Fit("g1","R"); Int_t hminbin= qtc_cfd->GetXaxis()->GetFirst(); Int_t hmaxbin= qtc_cfd->GetXaxis()->GetLast(); Int_t nbins= qtc_cfd->GetXaxis()->GetNbins(); cout<<" qtc_cfd "<<hminbin<<" "<<hmaxbin<<" "<<nbins<<endl; qtc_cfd->Draw(); /*TProfile *pr_y = qtc_cfd->ProfileX(); pr_y->SetMaximum(hmax); pr_y->SetMinimum(hmin); Int_t np=nbins/20; Double_t *xx = new Double_t[np]; Double_t *yy = new Double_t[np]; Int_t ng=0; Double_t yg=0; for (Int_t ip=1; ip<nbins; ip++) { if(ip%20 != 0 ) { if (pr_y->GetBinContent(ip) !=0) yg +=pr_y->GetBinContent(ip); // cout<<ng<<" "<<pr_y->GetBinContent(ip)<<" "<<yg<<endl; ng++;} else { xx[ip/20] = Float_t (ip); yy[ip/20] = yg/ng; yg=0; ng=0; cout<<ip<<" "<<ip/20<<" "<< xx[ip/20]<<" "<< yy[ip/20]<<endl; } } TH2F *hr = new TH2F("hr"," ",np,0,nbins, np, hmin, hmax); hr->Draw(); TGraph *gr = new TGraph(np,xx,yy); gr->SetMinimum(hmin); gr->SetMaximum(hmax); gr->Draw("P"); delete [] xx; delete [] yy; // pr_y->Rebin(10); // pr_y->Draw(); */ } } }
void cal(TString inputFile_30,TString inputFile_300, Int_t np=4) { gROOT->SetStyle("Default"); //gStyle->SetOptTitle(0); gStyle->SetOptStat(0); gStyle->SetOptFit(0); ofstream fitParFile; fitParFile.open("fitPars_pulser.txt"); TFile *file1 = TFile::Open(inputFile_30); TFile *file2 = TFile::Open(inputFile_300); //HISTOGRAMS DEFINITION char histitle[100]; TH1F** hEnergy_30 = new TH1F*[128]; for(Int_t i=0;i<128;i++) { sprintf(histitle,"%s%i","hEnergy_30_",i); hEnergy_30[i] = new TH1F(histitle,histitle,20000,10000,30000); } TH1F** hEnergy_300 = new TH1F*[128]; for(Int_t i=0;i<128;i++) { sprintf(histitle,"%s%i","hEnergy_300_",i); hEnergy_300[i] = new TH1F(histitle,histitle,2000,1000,3000); } TTree* caloTree = (TTree*)file1->Get("cbmsim"); TTree* caloTree2 = (TTree*)file2->Get("cbmsim"); //Raw Hits (input) TClonesArray* rawHitCA; R3BCaloRawHit** rawHit; rawHitCA = new TClonesArray("R3BCaloRawHit",5); TBranch *branchRawHit = caloTree->GetBranch("CaloRawHit"); if(branchRawHit) branchRawHit->SetAddress(&rawHitCA); Long64_t nevents = caloTree->GetEntries(); Int_t rawHitsPerEvent =0; for(Int_t i=0;i<nevents;i++){ if(i%100000 == 0) printf("Event:%i\n",i); rawHitCA->Clear(); caloTree->GetEvent(i); rawHitsPerEvent = rawHitCA->GetEntries(); if(rawHitsPerEvent>0) { rawHit = new R3BCaloRawHit*[rawHitsPerEvent]; for(Int_t j=0;j<rawHitsPerEvent;j++){ rawHit[j] = (R3BCaloRawHit*) rawHitCA->At(j); } } //filling info if(rawHitsPerEvent>0) { for(Int_t h=0;h<rawHitsPerEvent;h++){ hEnergy_30[rawHit[h]->GetCrystalId()]->Fill(rawHit[h]->GetEnergy()); } } if(rawHitsPerEvent) delete [] rawHit; } //SECOND TREE nevents = caloTree2->GetEntries(); rawHitsPerEvent =0; TBranch *branchRawHit2 = caloTree2->GetBranch("CaloRawHit"); if(branchRawHit2) branchRawHit2->SetAddress(&rawHitCA); for(Int_t i=0;i<nevents;i++){ if(i%100000 == 0) printf("Event:%i\n",i); rawHitCA->Clear(); caloTree2->GetEvent(i); rawHitsPerEvent = rawHitCA->GetEntries(); if(rawHitsPerEvent>0) { rawHit = new R3BCaloRawHit*[rawHitsPerEvent]; for(Int_t j=0;j<rawHitsPerEvent;j++){ rawHit[j] = (R3BCaloRawHit*) rawHitCA->At(j); } } //filling info if(rawHitsPerEvent>0) { for(Int_t h=0;h<rawHitsPerEvent;h++){ hEnergy_300[rawHit[h]->GetCrystalId()]->Fill(rawHit[h]->GetEnergy()); } } if(rawHitsPerEvent) delete [] rawHit; } Double_t par[3000]; par[0] = 0.8; par[1] = -0.6/1000; //CANVAS DEFINITION char canvastitle[100]; TCanvas** canv_30 = new TCanvas*[8]; for(Int_t i=0;i<8;i++) { sprintf(canvastitle,"%s%i","Raw_FEBEX_30_",i); canv_30[i] = new TCanvas(canvastitle,canvastitle,0,0,1220,900); canv_30[i]->SetFillColor(0); canv_30[i]->SetFrameFillColor(0); canv_30[i]->Divide(4,4); } TCanvas** canv_300 = new TCanvas*[8]; for(Int_t i=0;i<8;i++) { sprintf(canvastitle,"%s%i","Raw_FEBEX_300_",i); canv_300[i] = new TCanvas(canvastitle,canvastitle,0,0,1220,900); canv_300[i]->SetFillColor(0); canv_300[i]->SetFrameFillColor(0); canv_300[i]->Divide(4,4); } TF1** myfit_30 = new TF1*[512]; TF1** myfit_300 = new TF1*[512]; Int_t nfound; TSpectrum *s = new TSpectrum(2*npeaks); //TH1F** hEnergy2_30 = new TH1F*[128]; //TH1F** hEnergy2_300 = new TH1F*[128]; TF1 *fline = new TF1("fline","pol1",0,1000); Float_t *xpeaks; Float_t xp=0; Int_t bin=0; Float_t yp=0; for(Int_t i=0;i<128;i++) { //sprintf(canvastitle,"%s%i","hEnergy2_30_",i); //TH1F *hEnergy2_30 = (TH1F*)hEnergy_30[i]->Clone(canvastitle); //sprintf(canvastitle,"%s%i","hEnergy2_300_",i); //TH1F *hEnergy2_300 = (TH1F*)hEnergy_300[i]->Clone(canvastitle); if(i<16) canv_30[0]->cd(i+1); else if(i>15 &&i<32) canv_30[1]->cd(i-15); else if(i>31 &&i<48) canv_30[2]->cd(i-31); else if(i>47 &&i<64) canv_30[3]->cd(i-47); else if(i>63 &&i<80) canv_30[4]->cd(i-63); else if(i>79 &&i<96) canv_30[5]->cd(i-79); else if(i>95 &&i<112) canv_30[6]->cd(i-95); else if(i>111 &&i<128) canv_30[7]->cd(i-111); hEnergy_30[i]->Draw(); //Use TSpectrum to find the peak candidates nfound = s->Search(hEnergy_30[i],20,"new"); xpeaks = s->GetPositionX(); for (Int_t poo=0;poo<nfound;poo++) { Float_t xp = xpeaks[poo]; cout << " pos[" << poo << "]=" << xp; sprintf(canvastitle,"%s%i%s%i","myfit_30_",i,"_",poo); myfit_30[i*poo] = new TF1(canvastitle,"[0] / sqrt(2.0 * TMath::Pi()) / [2] * exp(-(x-[1])*(x-[1])/2./[2]/[2]) + [3]",xpeaks[poo]-25,xpeaks[poo]+25); myfit_30[i*poo]->SetParameter(0, 500); myfit_30[i*poo]->SetParameter(1, xpeaks[poo]); myfit_30[i*poo]->SetParameter(2, 20); myfit_30[i*poo]->SetParameter(3, 0); myfit_30[i*poo]->SetLineColor(2); myfit_30[i*poo]->SetLineWidth(1); hEnergy_30[i]->Fit(canvastitle,"R"); fitParFile << myfit_30[i*poo]->GetParameter(0) << " " << myfit_30[i*poo]->GetParameter(1) << " " << myfit_30[i*poo]->GetParameter(2) << " " << myfit_30[i*poo]->GetParameter(3) << endl; } cout << endl; if(i<16) canv_300[0]->cd(i+1); else if(i>15 &&i<32) canv_300[1]->cd(i-15); else if(i>31 &&i<48) canv_300[2]->cd(i-31); else if(i>47 &&i<64) canv_300[3]->cd(i-47); else if(i>63 &&i<80) canv_300[4]->cd(i-63); else if(i>79 &&i<96) canv_300[5]->cd(i-79); else if(i>95 &&i<112) canv_300[6]->cd(i-95); else if(i>111 &&i<128) canv_300[7]->cd(i-111); hEnergy_300[i]->Draw(); //Use TSpectrum to find the peak candidates nfound = s->Search(hEnergy_300[i],20,"new"); xpeaks = s->GetPositionX(); for (poo=0;poo<nfound;poo++) { Float_t xp = xpeaks[poo]; cout << " pos[" << poo << "]=" << xp; sprintf(canvastitle,"%s%i%s%i","myfit_300_",i,"_",poo); myfit_300[i*poo] = new TF1(canvastitle,"[0] / sqrt(2.0 * TMath::Pi()) / [2] * exp(-(x-[1])*(x-[1])/2./[2]/[2]) + [3]",xpeaks[poo]-20,xpeaks[poo]+20); myfit_300[i*poo]->SetParameter(0, 500); myfit_300[i*poo]->SetParameter(1, xpeaks[poo]); myfit_300[i*poo]->SetParameter(2, 20); myfit_300[i*poo]->SetParameter(3, 0); myfit_300[i*poo]->SetLineColor(2); myfit_300[i*poo]->SetLineWidth(1); hEnergy_300[i]->Fit(canvastitle,"R"); fitParFile << myfit_300[i*poo]->GetParameter(0) << " " << myfit_300[i*poo]->GetParameter(1) << " " << myfit_300[i*poo]->GetParameter(2) << " " << myfit_300[i*poo]->GetParameter(3) << endl; } cout << endl; } for(Int_t i=0;i<8;i++) { canv_30[i]->Update(); canv_300[i]->Update(); } fitParFile.close(); }
//-------------------------------------- //function to calculate sampling factors std::pair<Double_t,Double_t> g4_sample(int snum, Double_t energy, bool do_pion, bool do_show, bool do_print=false, bool set_val=true){ Sample* sp = sample_map[snum]; if(!sp) { std::cout << "Sample " << snum << " is not loaded." << std::endl; return std::pair<Double_t,Double_t>(0.,0.); } //select correct file std::string fpre = sp->fpre; if(do_pion) fpre += "_pion"; else fpre += "_elec"; //make filenames std::stringstream drawname, fname, piname; fname << sp->dir << "/" << fpre << "_" << energy << "gev_10k.root"; if(do_pion) piname << "#pi^{-} " << energy << " GeV"; else piname << "e^{-} " << energy << " GeV"; //open file and tree TFile* _file; _file = TFile::Open((fname.str()).c_str()); TTree* totalTree = (TTree*)_file->Get("Total"); //get histo from tree (no display) //define mip as sam_ecal*ecal < 1 gev = 1000 mev (for pions in HCAL) if(sp->det==Hcal) drawname << "(hcal+" << sp->zeroWt << "*zero)/1000>>hsam(200)"; else drawname << "(ecal)/1000>>hsam(200)"; totalTree->Draw((drawname.str()).c_str(),"","hist goff"); TH1F* hsam = (TH1F*)gDirectory->Get("hsam"); //use parameters from histo to start fit TSpectrum* spec = new TSpectrum(5); spec->Search(hsam,5,"nodraw goff"); Float_t* xpos = spec->GetPositionX(); Float_t* ypos = spec->GetPositionY(); Double_t m = xpos[0]; Double_t me = hsam->GetMeanError(); Double_t N = hsam->GetEntries(); std::stringstream s_mean; s_mean.precision(3); Double_t f = energy/m; Double_t f_err = energy*(me/(m*m)); s_mean << f << " #pm " << f_err; TPolyMarker* pm = new TPolyMarker(1, xpos, ypos); hsam->GetListOfFunctions()->Add(pm); pm->SetMarkerStyle(23); pm->SetMarkerColor(kRed); pm->SetMarkerSize(1.3); std::cout.precision(6); std::cout << "f_" << (do_pion ? "pion" : "elec") << " = " << f << " +/- " << f_err << std::endl; //plotting and printing if (do_show){ TCanvas* can = new TCanvas("sample","sample",700,500); can->cd(); TPad* pad = new TPad("graph","",0,0,1,1); pad->SetMargin(0.12,0.05,0.15,0.05); pad->Draw(); pad->cd(); //formatting hsam->SetTitle(""); hsam->GetXaxis()->SetTitle("Energy [GeV]"); //hsam->SetStats(kTRUE); //gStyle->SetOptStat("mr"); hsam->SetLineWidth(2); hsam->SetLineColor(kBlack); hsam->GetYaxis()->SetTitleSize(32/(pad->GetWh()*pad->GetAbsHNDC())); hsam->GetYaxis()->SetLabelSize(28/(pad->GetWh()*pad->GetAbsHNDC())); hsam->GetXaxis()->SetTitleSize(32/(pad->GetWh()*pad->GetAbsHNDC())); hsam->GetXaxis()->SetLabelSize(28/(pad->GetWh()*pad->GetAbsHNDC())); hsam->GetYaxis()->SetTickLength(12/(pad->GetWh()*pad->GetAbsHNDC())); hsam->GetXaxis()->SetTickLength(12/(pad->GetWh()*pad->GetAbsHNDC())); hsam->Draw(); std::stringstream Nname; Nname << "N = " << N; //determine placing of pave Double_t xmin; if (m/((hsam->GetXaxis()->GetXmax() + hsam->GetXaxis()->GetXmin())/2) < 1) xmin = 0.65; else xmin = 0.2; //legend TPaveText *pave = new TPaveText(xmin,0.65,xmin+0.2,0.85,"NDC"); pave->AddText((piname.str()).c_str()); pave->AddText((Nname.str()).c_str()); pave->AddText("Peak sampling factor:"); pave->AddText((s_mean.str()).c_str()); pave->SetFillColor(0); pave->SetBorderSize(0); pave->SetTextFont(42); pave->SetTextSize(0.05); pave->Draw("same"); if(do_print) { std::stringstream oname; oname << pdir << "/" << fpre << "_sample_" << energy << "gev_peak.png"; can->Print((oname.str()).c_str(),"png"); } } else _file->Close(); //store value in sample if(set_val){ if(do_pion) sp->sam_pion = f; else sp->sam_elec = f; } return std::pair<Double_t,Double_t>(f,f_err); }
//------------------------------------ //function to fit energy distributions energyRes* get_res(int snum, Double_t energy, bool do_pion, bool use_f_pion, bool do_fit, bool do_show, bool do_print=false, bool do_batch=false){ Sample* sp = sample_map[snum]; if(!sp) { std::cout << "Sample " << snum << " is not loaded." << std::endl; energyRes* theRes = new energyRes(0,0); return theRes; } //select correct file std::string fpre = sp->fpre; if(do_pion) fpre += "_pion"; else fpre += "_elec"; //make filenames std::stringstream drawname, fname, piname; fname << sp->dir << "/" << fpre << "_" << energy << "gev_10k.root"; if(do_pion) piname << "#pi^{-} " << energy << " GeV"; else piname << "e^{-} " << energy << " GeV"; //open file and tree TFile* _file; _file = TFile::Open((fname.str()).c_str()); TTree* totalTree = (TTree*)_file->Get("Total"); //default histo settings //double Emin = 0.1*energies[num]; //lower cut to remove weird peaks near E=zero double Emin = 0; double Emax = 2*energy; int nbins = 100; //ecal & hcal energies need to be calibrated get_sampling_factors(snum); //make tree drawing expressions //define mip as ecal < 1 gev = 1000 mev if(use_f_pion) drawname << sp->sam_pion; else drawname << sp->sam_elec; if(sp->det==Hcal) drawname << "*(hcal+" << sp->zeroWt << "*zero)/1000"; else drawname << "*ecal/1000"; drawname << ">>htemp(" << nbins << "," << Emin << "," << Emax << ")"; //std::cout << drawname.str() << std::endl; TH1F* h_res; //to store histos drawn from tree TF1* gfit; TF1* gsnL; TF1* gsnR; //plotting variables TCanvas* can; TPad* pad; TLegend* leg; TPaveText* pave; TPaveText* pave_par; TLine *aLline; TLine *aRline; //create instance of energyRes object energyRes* theRes = new energyRes(energy,2); //draw w/ appropriate cut totalTree->Draw((drawname.str()).c_str(),"","hist goff"); h_res = (TH1F*)gDirectory->Get("htemp"); h_res->SetTitle(""); h_res->GetXaxis()->SetTitle("Energy [GeV]"); h_res->SetLineWidth(2); h_res->SetLineColor(kBlack); //names std::string ofit; if(do_fit) ofit = "fit"; else ofit = "nofit"; std::stringstream oname; oname << pdir << "/" << fpre; if(use_f_pion) oname << "_fpion"; oname << "_response_" << ofit << "_" << energy << "gev"; //get values from histo Double_t m = h_res->GetMean(); Double_t me = h_res->GetMeanError(); //Double_t m = h_res->GetBinCenter(h_res->GetMaximumBin()); //peak Double_t s = h_res->GetRMS(); Double_t se = h_res->GetRMSError(); Int_t N = h_res->GetEntries(); std::vector<Double_t> stats(3,0); std::vector<Double_t> stat_err(3,0); stats[0] = N; stat_err[0] = 0; stats[1] = m; stat_err[1] = me; stats[2] = s; stat_err[2] = se; //find peak TSpectrum *spec = new TSpectrum(5); if(nbins < 100) spec->Search(h_res,6,"nobackground nodraw goff"); //turn off background removal when nbins too small else spec->Search(h_res,6,"nodraw goff"); Float_t* xpos = spec->GetPositionX(); Float_t* ypos = spec->GetPositionY(); Double_t p = xpos[0]; Double_t ph = ypos[0]; if(do_show) std::cout << "peak: " << p << std::endl; //setup fitting function & do fit if (do_fit){ gfit = new TF1("resp","gaus",0,h_res->GetXaxis()->GetXmax()); //if(do_jet){ // gfit->SetParameters(ph,p,s); // if(m > p) gfit->SetRange(p-1.5*s,p+1.0*s); //high tail // else gfit->SetRange(p-1.0*s,p+1.5*s); //low tail //} //else{ gfit->SetParameters((Double_t)N,m,s); gfit->SetRange(m-2*s,m+1*s); //fit within 2 std devs //if(m > p) gfit->SetRange(p-2*s,p+1*s); //high tail //else gfit->SetRange(p-1*s,p+2*s); //low tail //} //formatting gfit->SetLineColor(kRed); gfit->SetMarkerColor(kRed); gfit->SetLineWidth(2); //fit h_res->Fit(gfit,"LNQR"); } //store parameters theRes->setStats(stats,stat_err); if(do_fit) theRes->setFit(gfit); //store histo h_res->SetDirectory(0); theRes->setHist(h_res); std::stringstream muname, signame, musigname, aLname, nLname, aRname, nRname, Nname, chiname; muname.precision(2); signame.precision(2); musigname.precision(3); aLname.precision(2); nLname.precision(2); aRname.precision(2); nRname.precision(2); chiname.precision(5); if (do_fit) { muname << fixed << "#mu = " << gfit->GetParameter(1) << " #pm " << gfit->GetParError(1); signame << fixed << "#sigma = " << gfit->GetParameter(2) << " #pm " << gfit->GetParError(2); musigname << fixed << "#sigma/#mu = " << gfit->GetParameter(2)/gfit->GetParameter(1) << " #pm " << gfit->GetParameter(2)/gfit->GetParameter(1) * sqrt( Power(gfit->GetParError(1),2)/Power(gfit->GetParameter(1),2) + Power(gfit->GetParError(2),2)/Power(gfit->GetParameter(2),2) ); //aLname << fixed << "a_{L} = " << gfit->GetParameter(3) << " #pm " << gfit->GetParError(3); //nLname << fixed << "n_{L} = " << gfit->GetParameter(4) << " #pm " << gfit->GetParError(4); //aRname << fixed << "a_{R} = " << gfit->GetParameter(5) << " #pm " << gfit->GetParError(5); //nRname << fixed << "n_{R} = " << gfit->GetParameter(6) << " #pm " << gfit->GetParError(6); chiname << fixed << "#chi^{2}/ndf = " << gfit->GetChisquare()/gfit->GetNDF(); } else { muname << fixed << "Mean = " << m << " #pm " << me; signame << fixed << "RMS = " << s << " #pm " << se; musigname << fixed << "RMS/Mean = " << s/m << " #pm " << s/m*sqrt((me*me)/(m*m)+(se*se)/(s*s)); } Nname << "N = " << N; //plotting if (do_show){ can = new TCanvas((oname.str()).c_str(),(oname.str()).c_str(),700,500); can->cd(); pad = new TPad("graph","",0,0,1,1); pad->SetMargin(0.12,0.05,0.15,0.05); pad->Draw(); pad->cd(); //formatting h_res->SetStats(kTRUE); gStyle->SetOptStat("mr"); h_res->GetYaxis()->SetTitleSize(32/(pad->GetWh()*pad->GetAbsHNDC())); h_res->GetYaxis()->SetLabelSize(28/(pad->GetWh()*pad->GetAbsHNDC())); h_res->GetXaxis()->SetTitleSize(32/(pad->GetWh()*pad->GetAbsHNDC())); h_res->GetXaxis()->SetLabelSize(28/(pad->GetWh()*pad->GetAbsHNDC())); h_res->GetYaxis()->SetTickLength(12/(pad->GetWh()*pad->GetAbsHNDC())); h_res->GetXaxis()->SetTickLength(12/(pad->GetWh()*pad->GetAbsHNDC())); //plot histo and fit h_res->Draw("hist"); if(do_fit) gfit->Draw("same"); //determine placing of legend and paves - par pave goes on side with more space Double_t xmin; if (m/((h_res->GetXaxis()->GetXmax() + h_res->GetXaxis()->GetXmin())/2) < 1) xmin = 0.65; else xmin = 0.2; if(do_fit) { //legend leg = new TLegend(xmin,0.78,xmin+0.2,0.88); leg->AddEntry(h_res,"Standalone"); leg->AddEntry(gfit,"Fit"); leg->SetFillColor(0); leg->SetBorderSize(0); leg->SetTextSize(0.05); leg->SetTextFont(42); leg->Draw("same"); can->Update(); /* //left line Double_t bndL = gfit->GetParameter(1) - gfit->GetParameter(2)*gfit->GetParameter(3); aLline = new TLine(bndL,pad->GetUymin(),bndL,pad->GetUymax()); aLline->SetLineStyle(2); aLline->SetLineWidth(3); aLline->SetLineColor(kBlue); aLline->Draw("same"); //left gaussian gsnL = new TF1("gsn","gaus",Emin,bndL); gsnL->SetParameters(gfit->GetParameter(0),gfit->GetParameter(1),gfit->GetParameter(2)); gsnL->SetLineColor(kRed); gsnL->SetMarkerColor(kRed); gsnL->SetLineWidth(2); gsnL->SetLineStyle(2); gsnL->Draw("same"); //line Double_t bndR = gfit->GetParameter(1) + gfit->GetParameter(2)*gfit->GetParameter(5); aRline = new TLine(bndR,pad->GetUymin(),bndR,pad->GetUymax()); aRline->SetLineStyle(2); aRline->SetLineWidth(3); aRline->SetLineColor(kBlue); aRline->Draw("same"); //right gaussian gsnR = new TF1("gsn","gaus",bndR,Emax); gsnR->SetParameters(gfit->GetParameter(0),gfit->GetParameter(1),gfit->GetParameter(2)); gsnR->SetLineColor(kRed); gsnR->SetMarkerColor(kRed); gsnR->SetLineWidth(2); gsnR->SetLineStyle(2); gsnR->Draw("same"); */ } //pave pave = new TPaveText(xmin,0.68,xmin+0.2,0.78,"NDC"); pave->AddText(sp->name.c_str()); pave->AddText((piname.str()).c_str()); pave->SetFillColor(0); pave->SetBorderSize(0); pave->SetTextFont(42); pave->SetTextSize(0.05); pave->Draw("same"); //par pave Double_t ymin1; //if(do_fit) ymin1 = 0.26; //else ymin1 = 0.51; ymin1 = 0.47; pave_par = new TPaveText(xmin,ymin1,xmin+0.2,ymin1+0.05*4,"NDC"); pave_par->AddText((Nname.str()).c_str()); pave_par->AddText((muname.str()).c_str()); pave_par->AddText((signame.str()).c_str()); pave_par->AddText((musigname.str()).c_str()); //if(do_fit){ // pave_par->AddText((aLname.str()).c_str()); // pave_par->AddText((nLname.str()).c_str()); // pave_par->AddText((aRname.str()).c_str()); // pave_par->AddText((nRname.str()).c_str()); // pave_par->AddText((chiname.str()).c_str()); //} pave_par->SetFillColor(0); pave_par->SetBorderSize(0); pave_par->SetTextFont(42); pave_par->SetTextSize(0.05); pave_par->Draw("same"); std::cout << "response:" << std::endl; std::cout << Nname.str() << std::endl; std::cout << muname.str() << std::endl; std::cout << signame.str() << std::endl; std::cout << musigname.str() << std::endl; if(do_fit){ // std::cout << "aL = " << gfit->GetParameter(3) << " +/- " << gfit->GetParError(3) << std::endl; // std::cout << "nL = " << gfit->GetParameter(4) << " +/- " << gfit->GetParError(4) << std::endl; // std::cout << "aR = " << gfit->GetParameter(5) << " +/- " << gfit->GetParError(5) << std::endl; // std::cout << "nR = " << gfit->GetParameter(6) << " +/- " << gfit->GetParError(6) << std::endl; std::cout << "chi^2/ndf = " << gfit->GetChisquare()/gfit->GetNDF() << std::endl; } if(do_print) can->Print((oname.str()+"."+pformat).c_str(),pformat.c_str()); if(do_batch) _file->Close(); } else { _file->Close(); } //return data structure with relevant info return theRes; }
void Play() { //gSystem->Load("libRooFit"); //using namespace RooFit; TChain* S = new TChain("mjdTree"); //Look at COPPI calibration data from Nov 2013 S->Add("/project/projectdirs/majorana/data/mjd/surfprot/data/gatified/P3AKF/mjd_run40001923.root"); S->Add("/project/projectdirs/majorana/data/mjd/surfprot/data/gatified/P3AKF/mjd_run40001924.root"); S->Add("/project/projectdirs/majorana/data/mjd/surfprot/data/gatified/P3AKF/mjd_run40001925.root"); S->Add("/project/projectdirs/majorana/data/mjd/surfprot/data/gatified/P3AKF/mjd_run40001926.root"); S->Add("/project/projectdirs/majorana/data/mjd/surfprot/data/gatified/P3AKF/mjd_run40001927.root"); S->Add("/project/projectdirs/majorana/data/mjd/surfprot/data/gatified/P3AKF/mjd_run40001928.root"); S->Print(); //S->Add("COPPIsA__run1131.root"); TH1D *hc146 = new TH1D("hc146","Channel 146", 2000, 0, 800E3 ); TH1D *hc147 = new TH1D("hc147","Channel 147", 2000, 0, 800E3 ); TCanvas* c1 = new TCanvas("c1","",1500,800); TCanvas* c2 = new TCanvas("c2","",1500,800); TCanvas* c3 = new TCanvas("c3","",1500,800); c1->Divide(1,2); c2->Divide(1,2); c3->Divide(1,2); // --- Find Peaks in Spectrum --- c1->cd(1); S->Draw("energy>>hc146","channel==146"); c1->cd(2); S->Draw("energy>>hc147","channel==147"); // we calibrate with 133Ba and 60Co so let's build TSpectrum and look for those peaks // let's focus on the highest intensity lines: // 30.973 0.628 // 356.0129 0.6205 // 30.625 0.34 // 80.9979 0.329 // // 1332.492 0.999826 // 1173.228 0.9985 // 8.26-8.33 0.0000136 // 7.46-7.48 0.000098 //Use a gaussian to fit each of the peaks. TF1* tgaus = new TF1("tgaus","gaus",0,900E3); c1->cd(1); TSpectrum *s = new TSpectrum(12); Int_t nfound = s->Search(hc146,3,"",0.05); vector<calData> x146; //TSpectrum guess printf("Found %d candidate peaks to fit in channel 146 spectrum:\n",nfound); TH1 *hb = s->Background(hc146,20,"same"); TH1D* hc146bf = (TH1D*)hc146->Clone("hc146bf"); hc146bf->Add(hb,-1); if (hb) c1->Update(); c2->cd(1); hc146bf->Draw();; Float_t *xpeaks = s->GetPositionX(); calData d; for (int i = 0; i < nfound; i++) { //printf("%f : %f \n",s->GetPositionX()[i],s->GetPositionY()[i]); d.adc=s->GetPositionX()[i]; x146.push_back(d); } sort(x146.begin(),x146.end(),CompareByadc); for(std::vector<calData>::iterator it=x146.begin(); it!=x146.end(); ++it) { tgaus->SetParameter(1,(*it).adc); TFitResultPtr r = hc146bf->Fit(tgaus,"SQ+","",(*it).adc-0.02*((*it).adc),(*it).adc+0.02*((*it).adc)); (*it).fadc=r->Parameter(1); (*it).efadc=r->ParError(1); } cout << " Ts X \t\t Fit X \t\t\t err(x) " << endl; for(int i = 0; i < nfound; i++) { printf("%f \t %f \t +/- \t %f \n",x146[i].adc,x146[i].fadc,x146[i].efadc); } c1->cd(2); nfound = s->Search(hc147,3,"",0.05); vector<calData> x147; //TSpectrum guess printf("Found %d candidate peaks to fit in channel 147 spectrum:\n",nfound); TH1 *hb147 = s->Background(hc147,20,"same"); TH1D* hc147bf = (TH1D*)hc147->Clone("hc147bf"); hc147bf->Add(hb147,-1); if (hb147) c1->Update(); c2->cd(2); hc147bf->Draw();; xpeaks = s->GetPositionX(); for (int i = 0; i < nfound; i++) { //printf("%f : %f \n",s->GetPositionX()[i],s->GetPositionY()[i]); d.adc=s->GetPositionX()[i]; x147.push_back(d); } sort(x147.begin(),x147.end(),CompareByadc); for(std::vector<calData>::iterator it=x147.begin(); it!=x147.end(); ++it) { tgaus->SetParameter(1,(*it).adc); TFitResultPtr r = hc147bf->Fit(tgaus,"SQ+","",(*it).adc-0.02*((*it).adc),(*it).adc+0.02*((*it).adc)); (*it).fadc=r->Parameter(1); (*it).efadc=r->ParError(1); } cout << " Ts X \t\t Fit X \t\t\t err(x) " << endl; for(int i = 0; i < nfound; i++) { printf("%f \t %f \t +/- \t %f \n",x147[i].adc,x147[i].fadc,x147[i].efadc); } // --- Estimate Intensities // --- Fit centroids of peaks with linear function // --- Build Calibration Curve // We calibrated with 133Ba and 60Co Float_t BaCoHG[] = {383.8485,356.01,302.8508,276.3989,80.9979,79.6142,53.1622}; Float_t BaCo[] = {1332.492,1173.228,1332.492-511,1173-511,356.01,30.973}; c3->cd(1); //channel 146 is high gain vector<Float_t> cELT(BaCoHG,BaCoHG+sizeof(BaCoHG)/sizeof(Float_t)); TGraphErrors* cal146 = ExtractCalCurve(x146,cELT); cal146->Draw("AP"); c3->cd(2); //channel 147 is normal gain vector<Float_t> cE(BaCo,BaCo+sizeof(BaCo)/sizeof(Float_t)); TGraphErrors* cal147 = ExtractCalCurve(x147,cE); cal147->Draw("AP"); }
void calibraPlastico(char* filename, int channel=4) { FILE *outfile[2]; outfile[0] = fopen("Chi2_511","w"); outfile[1] = fopen("Chi2_1275","w"); Int_t number_of_loop=0; Int_t i, j, k, i_sm, rsen[2]; Float_t r, alpha, energia; Int_t b_altezza; // energies Float_t E_peak[NUMENERGIES]; Float_t E_compton[NUMENERGIES]; E_peak[0] = 511.; E_peak[1] = 1275.; for (i=0; i<NUMENERGIES; i++) { E_compton[i] = 2*E_peak[i]*E_peak[i]/(511+2*E_peak[i]); printf("E_compton[%d] = %f;\n",i,E_compton[i]); } TTimer *timer = new TTimer("gSystem->ProcessEvents();", 50, kFALSE); TCanvas *c0 = new TCanvas("c0"); c0->cd(); h_ideal = new TH1F("h_ideal","Compton ideale",NBINS,0,MAXHISTONRG); // check file existance f_smearings = new TFile("smearings.root","UPDATE"); // check smearing samples existance for(i=0; i<NUMENERGIES; i++) { sprintf(smoothName,"smooth_%.1f_%d;1",E_peak[i],NSMEARINGS-2); if (!f_smearings->Get(smoothName)) { cout << smoothName << " " << f_smearings->FindObject(smoothName) << endl; // smearing for that energy do not exist printf("Non esistono.\n"); // ideal compton histogram for (j=0; j<NBINS; j++) { if (j>h_ideal->FindBin(50) && j<h_ideal->FindBin(E_compton[i])) { r = h_ideal->GetBinCenter(j)/E_peak[i]; alpha = E_peak[i]/511.0; energia = KN_NORM * (2+r*r/(alpha*alpha*(1-r)*(1-r))+r/(1-r) * (r-2/alpha)); h_ideal->SetBinContent(j,energia); } else { h_ideal->SetBinContent(j,0); } } h_ideal->Draw(); c0->Update(); timer->TurnOn(); timer->Reset(); timer->TurnOff(); // creazione spettri smussati for (i_sm=1; i_sm<NSMEARINGS; i_sm++) { sprintf(smoothName,"smooth_%.1f_%d",E_peak[i],i_sm); printf("Creo '%s': ",smoothName); h_smooth = new TH1F(smoothName,"Smooth",NBINS,0,MAXHISTONRG); // istogramma in energia for (j=1; j<h_ideal->FindBin(E_compton[i]); j++) { b_altezza = h_ideal->GetBinContent(j); for (k=1; k<b_altezza; k++){ h_smooth->Fill(gRandom->Gaus(h_ideal->GetBinCenter(j),i_sm)); } printf("."); } printf("\n"); h_smooth->Write(); } } } // ok, we've got the smearings! f_smearings->Close(); f_smearings = new TFile("smearings.root","READ"); // ---------------------------------- // retrieving "raw" histogram // ---------------------------------- TFile *infile = new TFile(filename); TTree *tree= (TTree*)infile->Get("acq_tree_0"); TBranch *branch = tree->GetBranch(Form("acq_ch%d",channel)); branch->SetAddress(&inc_data.timetag); TH1F *h_raw = new TH1F("h_raw","Acquisizione",NBINS,0,MAXHISTOCHN); UInt_t toentry=branch->GetEntries(); printf("getHistoFromFile: There are %d entries in the branch\n",toentry); for(i=0; i<toentry; i++) { branch->GetEntry(i); h_raw->Fill(inc_data.qlong); } h_raw->Draw(); TSpectrum *s = new TSpectrum(10); Int_t e, nPeaks, bTemp, bFirstPeak = 9999; Float_t *xPeaks; // trovo il primo picco nPeaks = s->Search(h_raw->Rebin(2, "h_raw_rebinned")); if (nPeaks>0) { xPeaks = s->GetPositionX(); // loop sui picchi per trovare il primo for (i=0;i<nPeaks;i++) { bTemp = h_raw->GetXaxis()->FindBin(xPeaks[i]); if (bTemp<bFirstPeak) { bFirstPeak = bTemp; } } } else { bFirstPeak = 0; } // sottraggo il fondo Compton Float_t *bgBins = new Float_t[NBINS]; TH1F *h_filtered = new TH1F("h_filtered","Picchi",NBINS,0,MAXHISTOCHN); /*for (i = 0; i < bFirstPeak; i++) { bgBins[i]=h_raw->GetBinContent(i+1); } s->Background(bgBins,bFirstPeak,20,TSpectrum::kBackDecreasingWindow,TSpectrum::kBackOrder2,kFALSE,TSpectrum::kBackSmoothing15,kFALSE); for (i = 0; i < bFirstPeak; i++) { h_filtered->SetBinContent(i+1, (h_raw->GetBinContent(i+1)-bgBins[i])); } for (i = 0; i < NBINS-bFirstPeak; i++) { bgBins[i]=h_raw->GetBinContent(bFirstPeak+i+1); } s->Background(bgBins,NBINS-bFirstPeak,20,TSpectrum::kBackDecreasingWindow,TSpectrum::kBackOrder2,kFALSE,TSpectrum::kBackSmoothing15,kFALSE); for (i = bFirstPeak; i < NBINS; i++) { h_filtered->SetBinContent(i+1, (h_raw->GetBinContent(i+1)-bgBins[i-bFirstPeak])); } //TCanvas * background = new TCanvas("background","Estimation of bg",10,10,1000,700);*/ for (i = 0; i < NBINS; i++) { bgBins[i]=h_raw->GetBinContent(i+1); } s->Background(bgBins, NBINS, 20, TSpectrum::kBackDecreasingWindow, TSpectrum::kBackOrder2, kFALSE, TSpectrum::kBackSmoothing15, kFALSE); for (i = 0; i < NBINS; i++) { h_filtered->SetBinContent(i+1, (h_raw->GetBinContent(i+1)-bgBins[i])); } h_raw->Draw("L"); h_filtered->SetLineColor(kRed); h_filtered->Draw("SAME L"); c0->Update(); // trovo i picchi e calibro nPeaks = s->Search(h_filtered->Rebin(2, "h_filtered_rebinned"),2,"",0.05); xPeaks = s->GetPositionX(); // sigma_fall[0] = 100; timer->TurnOn(); timer->Reset(); timer->TurnOff(); if (nPeaks<NUMENERGIES) { // trovati troppi pochi picchi printf("EPIC FAIL while calibrating - too few peaks!\n"); } else { // possiamo calibrare TGraphErrors *graphErr; TF1 *fitMeasPeaks, *fitfun; Float_t nrg[NUMENERGIES], shift[NUMENERGIES], sigma_fall[NUMENERGIES], a, b, bPeak, cPeak, nrgPeak, chi2, fondo, xmin, xmax, chi2min; // fitto i due picchi, mi servono le sigma... for (e=0; e<NUMENERGIES; e++) { xmin = xPeaks[e] - (0.5*xPeaks[e]); // fit left margin xmax = xPeaks[e] + (0.5*xPeaks[e]); // fit right margin fitMeasPeaks = new TF1("fitMeasPeaks","gaus",xmin,xmax); fitMeasPeaks->SetNpx(1000); fitMeasPeaks->SetParameters(1,xPeaks[e]); h_filtered->Fit("fitMeasPeaks","QNO","",xmin,xmax); sigma_fall[e] = fitMeasPeaks->GetParameter(2); printf("%f - %f - %f Sigma_fall[%d]: %f\n",xmin,xPeaks[e],xmax,e,sigma_fall[e]); // inizializzazione shift[e]=0; nrg[e]=E_compton[e]; } fitfun = new TF1("calfitfun","pol1",xPeaks[0],xPeaks[NUMENERGIES-1]); // costruiamo uno spettro sperimentale calibrato h_calib = (TH1F*)h_raw->Clone(); h_calib->SetNameTitle("h_calib","Acquisiz. calibrata"); Int_t debug = 0; Int_t loop_flag = 1; // do..while shift begin while(loop_flag) { number_of_loop++; loop_flag = 0; for (e=0; e<NUMENERGIES; e++) { // energie aggiornate nrg[e] = nrg[e]-shift[e]; printf("xPeaks[%d] = %f\tshift[%d] = %f\tnrg[%d] = %f\n",e,xPeaks[e],e,shift[e],e,nrg[e]); } // calibrazione fitfun->SetParLimits(0,-100,100); fitfun->SetParLimits(1,0.,1.); graphErr = new TGraphErrors(NUMENERGIES,xPeaks,nrg); graphErr->Fit(fitfun,"RN"); a = fitfun->GetParameter(1); b = fitfun->GetParameter(0);// graphErr->Delete(); printf("intercetta=%f pendenza=%f\n",b,a); h_calib->GetXaxis()->SetLimits(b,h_raw->GetBinCenter(NBINS)*a+b); h_calib->Draw(); c0->Update(); timer->TurnOn(); timer->Reset(); timer->TurnOff(); for (e=0; e<NUMENERGIES; e++) { chi2min = 9999999; printf("Looppo sull'energia %.1f\n",nrg[e]); // loop on smearings for (i_sm=19; i_sm<NSMEARINGS; i_sm++) { sprintf(smoothName,"smooth_%.1f_%d",E_peak[e],i_sm); h_smooth = (TH1F*)f_smearings->Get(smoothName); if (debug) printf("Recupero l'histo %s\n",smoothName); //h_smooth->Draw(); // momentaneamente assumiamo che il CE sia: bPeak = h_smooth->GetMaximumBin(); if (debug) printf("bPeak = %f\n",bPeak); nrgPeak = bPeak*MAXHISTONRG/NBINS; if (debug) printf("nrgPeak = %f\n",nrgPeak); t_shift = nrg[e]-nrgPeak; if (debug) printf("t_shift = %f\n",t_shift); cPeak = h_calib->FindBin(a*xPeaks[e]+b); if (debug) printf("peak calib: %.1f\n",cPeak); max_calib = h_calib->GetBinContent(cPeak); if (debug) printf("max_calib = %f\n",max_calib); max_smooth = h_smooth->GetBinContent(bPeak); if (debug) printf("max_smooth = %f\n",max_smooth); if (debug) printf("sigma_fall[%d] = %f\n",e,sigma_fall[e]); if (debug) printf("a*sigma_fall[%d] = %f\n",e,a*sigma_fall[e]); // definisco la funzione per il fit TF1 *f_smear_profile = new TF1("f_smear_profile",f_profile,nrgPeak-a*sigma_fall[e],nrgPeak+a*sigma_fall[e]*3,1); f_smear_profile->SetParameters(0,300); h_calib->Fit("f_smear_profile","QON","",a*xPeaks[e]+b-a*sigma_fall[e],a*xPeaks[e]+b+a*sigma_fall[e]*3); chi2 = f_smear_profile->GetChisquare(); if (debug) printf("i_sm: %i\tchiquadro: %f\n",i_sm,chi2); fondo = f_smear_profile->GetParameter(0); if (debug) printf("fondo = %f\n",fondo); if (debug) printf("i_sm: %d\tchi2min vs. chi2: %f %f\n",i_sm,chi2min,chi2); if (number_of_loop==1) {fprintf(outfile[e],"%i\t%f\t%f\n",i_sm,chi2, fondo);} if (chi2<chi2min) { chi2min = chi2; shift[e] = t_shift; rsen[e]=i_sm;} } // loop on smearings ends here if (debug) printf("shift[%d]: %f\n",e,t_shift); if (shift[e]>THRSHIFT) { loop_flag++; } if (number_of_loop==1) {fclose(outfile[e]);} } // end loop on energies } // while shift ends here printf("Esco con shift[0]=%.1f e shift[1]=%.1f\n",shift[0],shift[1]); cout << "Esco con risoluzione[0] = " << rsen[0] << " keV (" << rsen[0]*100/E_compton[0] << "%)"; cout << " e risoluzione[1] = " << rsen[1] << " keV (" << rsen[1]*100/E_compton[1] << "%)" << endl; printf("\nRESULTS: nrg1 = %f\tnrg2 = %f\n",nrg[0],nrg[1]); printf("RESULTS: m = %f\t q = %f\n",a,b); } // end if enough peaks infile->Close(); //f_smearings->Close(); }