Esempio n. 1
0
/*
   * From here on, the code can also be used as a macro
   * Note though, that CINT may report errors where there are none
     in C++. E.g. this happens here where CINT says that f1 is
     out of scope ...

     ==>>  put your code here
      (remember to update the name of you Macro in the
       lines above if you intend to comile the code)
                                                                     */
void ExampleMacro() {
  // Create a histogram, fill it with random gaussian numbers
  TH1F *h = new TH1F ("h", "example histogram", 100, -5.,5.);
  h->FillRandom("gaus",1000);

  // draw the histogram
  h->DrawClone();

/* - Create a new ROOT file for output
   - Note that this file may contain any kind of ROOT objects, histograms,
     pictures, graphics objects etc.
   - the new file is now becoming the current directory */
  TFile *f1 = new TFile("ExampleMacro.root","RECREATE","ExampleMacro");

  // write Histogram to current directory (i.e. the file just opened)
  h->Write();

  // Close the file.
  //   (You may inspect your histogram in the file using the TBrowser class)
  f1->Close();
}
Esempio n. 2
0
void SPEFit(char * fLEDname, char * fPEDname, int run, int LED_amp, double cutmax = 250.0)
{

  //set plotting styles
  gStyle->SetCanvasColor(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);

    //set file names
    stringstream out_fname;
    stringstream out_fname1;
    out_fname<<"SPEconstants_Run_"<<run<<".txt";
    out_fname1<<"SPEspec_Run_"<<run<<".txt";

    ofstream  constants_file(out_fname.str().c_str(),ios_base::trunc); 
    //ofstream  constants_file1(out_fname1.str().c_str(),ios_base::trunc); 
    constants_file<<"Run "<<run<<endl;
    constants_file<<"type SPE"<<endl;
    constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl;

    constants_file<<endl<<"LED_amplitude Depth Phi Eta Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;

    out_fname.str("");
    out_fname<<"SPEdistributions_Run_"<<run<<".txt";

    out_fname.str("");
    out_fname<<"SPEextra_Run_"<<run<<".txt";
    //ofstream  extra_file(out_fname.str().c_str(),ios_base::trunc); 


    double scale = 1.0;
    scale = 2.6; //Need to scale up HF charge
    double fC2electrons = 6240.; //convert fC to #electrons

    char spename[128], pedname[128], spehistname[128];
 
    TFile *tfLED = new TFile(fLEDname);
    TFile *tfPED = new TFile(fPEDname);
    


    //const int NnewBins = 106;
    //double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};

    const int NnewBins = 80;
    double binsX[NnewBins] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60,63,66,69,72,75,78,81,84,87,90,93,96,99,102,105,108,111,114,117,120,123,126,129,132,135,138,141,144,147,150,153,156,159,162,165,168,171,174,177,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	  
    TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX);


    int NDepth = 2; //number of depths
    int MinDepth = 1;
    int MaxDepth = 2;
    int MinEta = 29; 
    int MaxEta = 41;
    int MinPhi = 41;
    int MaxPhi = 53;
   
 
    TCanvas *Carray[NDepth+1][MaxPhi+1];
    bool drawflag[NDepth+1][MaxPhi+1];  
    TH1F *LED[NDepth+1][MaxEta+1][MaxPhi+1];
    TH1F *PED[NDepth+1][MaxEta+1][MaxPhi+1];

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){

	bool nonNull = false;

	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  LED[iDepth][iEta][iPhi]=(TH1F *)tfLED->Get(spename);
	  if(LED[iDepth][iEta][iPhi]) nonNull = true;
      
	  sprintf(spename,"Analyzer/CommonDir/ResPlotDir/Histo_for_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  PED[iDepth][iEta][iPhi]=(TH1F *)tfPED->Get(spename);
	}

	drawflag[iDepth][iPhi] = false;
	char canvname[16];
	sprintf(canvname, "c_%d_%d", iDepth,iPhi);
	if(nonNull){ //only create canvas if distributions exist
	  Carray[iDepth][iPhi] = new TCanvas(canvname,canvname,1200,700);
	  Carray[iDepth][iPhi]->Divide(5,3);
	}

      }
    }



    int HV=0;

    for(int iDepth = MinDepth; iDepth <= MaxDepth; iDepth++){
      for(int iPhi = MinPhi; iPhi <= MaxPhi; iPhi++){
	for(int iEta = MinEta; iEta <= MaxEta; iEta++){

	  //cout<<iDepth<<" "<<iPhi<<" "<<iEta<<endl;

	  if(!LED[iDepth][iEta][iPhi]) continue;

	  sprintf(spehistname,"led %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hspe_temp = (TH1F *)LED[iDepth][iEta][iPhi]->Clone(spehistname);
	  sprintf(spehistname,"ped %d %d %d",iDepth,iEta,iPhi);
	  TH1F *hped = (TH1F *)PED[iDepth][iEta][iPhi]->Clone(spehistname);
	  hspe->Reset();
	  sprintf (spehistname, "SumLED_Depth_%d_Eta_%d_Phi_%d",iDepth,iEta,iPhi);
	  hspe->SetTitle(spehistname);

	  //combine bins of original SPE histogram
	  for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) {
	    double bin_center = hspe_temp->GetBinCenter(ib);
	    if(bin_center>hspe->GetXaxis()->GetXmax()) continue;
	    int newbin = hspe->FindBin(bin_center);
	    double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib);
	    double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2));
	    hspe->SetBinContent(newbin,new_content);
	    hspe->SetBinError(newbin,new_error);
	  }
	  TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled");
	  //renormalize bins of new SPE histogram
	  for(int ib=1; ib<=hspe->GetNbinsX(); ib++) {
	    double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	    hspe->SetBinContent(ib,new_content);
	    hspe->SetBinError(ib,new_error);
	  }
	  
	  if(hspe_temp->Integral()==0) continue;
	  else drawflag[iDepth][iPhi] = true;	  

	  Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); 
	  TF1 *fped = new TF1("fped","gaus",0, 80);
	  hped->Fit(fped,"NQR");
	  double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2);
	  hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth);  
	  
	  //estimate SPE peak location
	  int max_SPE_bin, maxbin, Nbins;
	  double max_SPE_height=0, minheight, max_SPE_location;
	  bool minflag = false;
	  maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak
	  minheight=hspe->GetBinContent(maxbin); //initialize minheight
	  Nbins = hspe->GetNbinsX();
	  for(int j=maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins
	    if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true
	    if(hspe->GetBinContent(j) < minheight )  minheight = hspe->GetBinContent(j);
	    if(minflag && hspe->GetBinContent(j) > max_SPE_height){
	      max_SPE_bin = j;
	      max_SPE_location = hspe->GetBinCenter(max_SPE_bin);
	      max_SPE_height = hspe->GetBinContent(j);
	    }
	  } //start from pedestal peak and loop through bins
	  //find minimum bin between pedestal and SPE peaks
	  hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin);
	  int minbin = hspe->GetMinimumBin(); 
	  double minbin_location = hspe->GetBinCenter(minbin);
	  hspe->GetXaxis()->SetRange(1,Nbins);	    
	  
	  TF1 *fit = new TF1("fit", FitFun, 0, 500, 5);
	    
	  double mu = - log(fped->Integral(0,100)/Nev);
	  if(mu<0) mu=0.01;
	  double gain_est = max_SPE_location-1.0*fped->GetParameter(1);
	  if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, gain_est*0.5);
	  else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 10); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak
	  fit->SetParLimits(0, 0, 10);
	  fit->FixParameter(1, fped->GetParameter(1));
	  fit->FixParameter(2, fped->GetParameter(2));
	  fit->SetParLimits(3, fped->GetParameter(2)*2, 350);
	  fit->SetParLimits(4, fped->GetParameter(2)*1.01, 250);
	  

	  double maxfitrange = 500.;    
	  double minfitrange = 0.;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);
	  maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+fit->GetParameter(4);
	  if(500<maxfitrange) maxfitrange = 500;
	  hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);

	  //calculate NDOF of fit excluding bins with 0 entries
	  int myNDOF=-3; //three free parameters
	  for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins
	    if(hspe->GetBinContent(j)) myNDOF++;
	  } //loop through fitted spe bins


	  //calculate means and integrals of the fit and data
	  double fint, fint_error, hint, favg, havg;
	  int temp_lowbin, temp_highbin;
	  temp_lowbin = hspe->FindBin(minfitrange);
	  temp_highbin = hspe->FindBin(maxfitrange);
	  hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange);
	  havg = hspe_unscaled->GetMean();
	  hint = hspe->Integral(temp_lowbin,temp_highbin,"width");
	  double min_frange = hspe->GetBinLowEdge(temp_lowbin);
	  favg = fit->Mean(min_frange, maxfitrange);
	  fint = fit->Integral(min_frange, maxfitrange);
	  //fint_error = fit->IntegralError(min_frange, maxfitrange);
	  
	  double PE5int = 0; //integral of events with >=5 PE
	  double PE5loc =  fped->GetParameter(1)+ 5*fit->GetParameter(3);
	  if(PE5loc>500) PE5int = 0;
	  else {
	    int PE5bin =  hspe_temp->FindBin(PE5loc);
	    temp_highbin = hspe_temp->FindBin(maxfitrange)-1;
	    PE5int =  hspe_temp->Integral(PE5bin,temp_highbin,"width");
	  }
	  int PE5flag = 0;
	  if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE
	//=========================================    
	  //for(int i1=1;i1<hspe->GetNbinsX();i1++){
	    //constants_file1<<HV<<"\t"<<iDepth<<"\t"<<iEta<<"\t"<<iPhi<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n";
          //}
        //=========================================    

	  //printf("%d\n",myNDOF);
	  //output calibrations constants
	  //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
	  constants_file<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	    

	  /*
	  if(iDepth==2 && iPhi==53 && iEta==36){
	    cout<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<gain_est<<" "<<fit->GetParameter(3)<<endl;
	    cout<<LED_amp<<" "<<iDepth<<" "<<iPhi<<" "<<iEta<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;
	  }
	  */

	  Carray[iDepth][iPhi]->cd(iEta-MinEta+1);
	  gPad->SetBorderMode(0);
	  gPad->SetBorderSize(0);
	  gPad->SetRightMargin(0.01);
	  gPad->SetBottomMargin(0.1);
	  gPad->SetLogy(true);
	  hspe->GetXaxis()->SetRangeUser(0, 200 /*300*//*508*/);
	  hspe->SetLineColor(kBlue);
	  hspe->DrawClone("hist");
	  fit->SetLineWidth(2);
	  fit->Draw("same");

	}
    
	if(drawflag[iDepth][iPhi]) { //draw plots of fit if data for the HV is present
	  stringstream plot_name;
	  plot_name<<"Plots/SPEFits_Run_"<<run<<"_Depth"<<iDepth<<"_Phi"<<iPhi<<".pdf";
	  Carray[iDepth][iPhi]->SaveAs(plot_name.str().c_str());
	  plot_name.str( std::string() );
	}

      }
    }

    constants_file.close();
    //constants_file1.close();
}
Esempio n. 3
0
void analysis() {
    Int_t nbins = 800;
    Int_t j;
    char name[20];
    char title[100];
    TH1F *HistoEvent[2214];
    for (Int_t z=0;z<2214;z++) {
        sprintf(name,"HistoEvent%d",z-1);
        sprintf(title,"Event%d Histo", z-1);
        HistoEvent[z] = new TH1F(name,title,nbins, -0.1, 159.9);
    }
    TH1F *NewHistoEvent[2214];
    for (Int_t z=0;z<2214;z++) {
        sprintf(name,"NewHistoEvent%d",z-1);
        sprintf(title,"Event%d Histo", z-1);
        NewHistoEvent[z] = new TH1F(name,title,nbins, -0.1, 159.9);
    }
    TH1F *NewHistoEventFFT[2214];
    for (Int_t z=0;z<2214;z++) {
        sprintf(name,"NewHistoEventFFT%d",z-1);
        sprintf(title,"Event%d Histo", z-1);
        NewHistoEventFFT[z] = new TH1F(name,title,nbins, 0, 5);
    }
    Double_t mean;
    Double_t rms;
    Double_t meansum = 0;
    Double_t count = 0;
    Double_t meanrms = 0;
	TFile f("/home/marko/H4Analysis/ntuples/analysis_4443.root"); //ntuple generated by H4Analysis tool
	TFile f1("/home/marko/H4Analysis/ntuples/analysis_3905.root");
    TFile f2("/home/marko/Desktop/TB Timing Res/NormalizedSignalNoise.root", "read");
    TH1F* BestSignal = (TH1F*) f2.Get("BetterSignal");
    TFile outputfile("myoutput.root", "recreate");
    TCanvas* TimeandFreq = new TCanvas("TimeandFreq","Time and Frequency",1500,900);
    TCanvas* Freq = new TCanvas("Freq","Frequency",800,1200);
    TCanvas* TimeSignal = new TCanvas("TimeSignal","Pure Signal",800,1200);
	TimeandFreq->Divide(2,2);
	TTree* h4 = (TTree*) f.Get("h4");
    TTree* h4_2 = (TTree*) f1.Get("h4");
    TString plot;
    TString cut;
	TH2F* WavePulse = new TH2F ("WavePulse", "Wave Pulse", nbins, -0.1, 159.9, 850, -50, 800);
    TH2F* NoisePulse = new TH2F ("NoisePulse", "Noise", nbins, -0.1, 159.9, 100, -50, 50);
    TH1F* PulseTime = new TH1F ("PulseTime", "Original Wave Pulse", nbins, -0.1, 159.9); //nanoseconds
    TH2F* TempHisto = new TH2F ("TempHisto", "Temp Histo", nbins, -0.1, 159.9, 1000, -15, 15); //nanoseconds
	h4->Draw("WF_val:WF_time>>WavePulse", "WF_ch==2 && event==1 && spill==1");
    h4_2->Draw("WF_val:WF_time>>NoisePulse","WF_ch==APD1 && amp_max[APD3]<25 && b_rms[APD3]<5. && charge_tot[APD3]<20000 &&  amp_max[APD5]<25 && b_rms[APD5]<5. &&  amp_max[APD6]<25 && b_rms[APD6]<5. &&  amp_max[APD4]<25 && b_rms[APD4]<5. && amp_max[SiPM1]<20 && amp_max[SiPM2]<20 && amp_max[APD1]<40 && amp_max[APD2]<40 && b_rms[APD1]<5. && b_rms[APD2]<5. && WF_time<160");
    for (Int_t i=0; i<nbins; i++) {
		for (Int_t k=0; k<4096; k++) {
			if (WavePulse->GetBinContent(i+1, k) != 0) {
				PulseTime->SetBinContent(i+1,k-50);
			}
		}
	}
    TH1F *NoiseTime = new TH1F ("NoiseTime", "Noise", nbins, -0.1, 159.9);
    for (Int_t i=0; i<nbins; i++) {
        for (Int_t k=0; k<4096; k++) {
            if (NoisePulse->GetBinContent(i+1, k) != 0) {
                NoiseTime->SetBinContent(i+1,k-62.9087);
            }
        }
    }
    //TH1F* NormNoiseFFT = new TH1F ("NormNoiseFFT", "Normalized Noise FFT", nbins, 0, 5);
    //TStopwatch t;
    //t.Start(); //1 hour runtime
    //for (j=10;j<20;j++) {
    //    plot = "WF_val:WF_time>>TempHisto";
    //    cut = "WF_ch==APD1 && amp_max[APD3]<25 && b_rms[APD3]<5. && charge_tot[APD3]<20000 &&  amp_max[APD5]<25 && b_rms[APD5]<5. &&  amp_max[APD6]<25 && b_rms[APD6]<5. &&  amp_max[APD4]<25 && b_rms[APD4]<5. && amp_max[SiPM1]<20 && amp_max[SiPM2]<20 && amp_max[APD1]<40 && amp_max[APD2]<40 && b_rms[APD1]<5. && b_rms[APD2]<5. && WF_time<160 && event==";
    //    cut += j;
    //    h4_2->Draw(plot, cut, "goff");
    //    if (TempHisto->GetMaximum() == 0) {
    //        delete HistoEvent[j+1];
    //        continue;
    //    }
    //    for (Int_t i=0; i<nbins; i++) {
    //        for (Int_t k=0; k<1000; k++) {
    //            if (TempHisto->GetBinContent(i+1, k) != 0) {
    //                HistoEvent[j+1]->SetBinContent(i+1,k*0.03-15);
    //            }
    //        }
    //    }
    //    mean = TempHisto->GetMean(2);
    //    rms = TempHisto->GetRMS(2);
    //    for (Int_t q=0;q<nbins;q++) {
    //        NewHistoEvent[j+1]->SetBinContent(q+1, HistoEvent[j+1]->GetBinContent(q+1)-mean);
    //    }
    //    NewHistoEvent[j+1]->Scale(1/rms);
    //    NewHistoEvent[j+1]->FFT(NewHistoEventFFT[j+1], "MAG");
    //    NormNoiseFFT->Add(NormNoiseFFT, NewHistoEventFFT[j+1]);
    //    TempHisto->Write();
    //    NewHistoEvent[j+1]->Write();
    //    NewHistoEventFFT[j+1]->Write();
    //    cout << "Event " << j << ", Mean = " << mean << ", RMS = " << rms << endl;
    //    count += 1;
    //}
    //NormNoiseFFT->Scale(1/count);
    //NormNoiseFFT->Write();
    //t.Stop();
    //t.Print();
	new TFile("/home/marko/H4Analysis/ntuples/analysis_4443.root"); // ignore this reloading of the same file, it is required or else the plots do not show up (when I tried)
    TimeandFreq->cd(1);
    PulseTime->GetXaxis()->SetTitle("Time (ns)");
    PulseTime->GetYaxis()->SetTitle("Amplitude");
    PulseTime->DrawClone(); //Wave Pulse in Time domain
    TimeandFreq->cd(2);
    TH1F* PulseFreq = new TH1F ("PulseFreq", "Pulse FFT", nbins, 0, 5);
    TH1F* PulsePhase = new TH1F ("PulsePhase", "Pulse Phase", nbins, -0.1, 799.9);
    PulseTime->FFT(PulseFreq, "MAG");
    PulseTime->FFT(PulsePhase, "PH");
    PulseFreq->SetLineColor(kRed);
    PulseFreq->GetXaxis()->SetTitle("Frequency (GHz)");
    PulseFreq->GetYaxis()->SetTitle("Amplitude");
    PulseFreq->DrawClone(); //Wave Pulse in Frequency domain
    gPad->SetLogy();
    TimeandFreq->cd(3);
    NoiseTime->GetXaxis()->SetTitle("Time (ns)");
    NoiseTime->GetYaxis()->SetTitle("Amplitude");
    NoiseTime->DrawClone(); // Noise from pedestal in Time domain
    TimeandFreq->cd(4);
    TH1F* NoiseFreq = new TH1F ("NoiseFreq", "Noise FFT", nbins, 0, 5);
    NoiseTime->FFT(NoiseFreq, "MAG");
    NoiseFreq->GetXaxis()->SetTitle("Frequency (GHz)");
    NoiseFreq->GetYaxis()->SetTitle("Amplitude");
    NoiseFreq->Draw(); // Noise from pedestal in Frequency domain
    gPad->SetLogy();
    Freq->Divide(1,3);
    Freq->cd(1);
    PulseFreq->DrawClone();
    gPad->SetLogy();
    Freq->cd(2);
    NoiseFreq->DrawClone();
    gPad->SetLogy();
    Freq->cd(3);
    PulseFreq->SetTitle("Pulse and Noise FFT Comparison");
    PulseFreq->Draw();
    NoiseFreq->Draw("same");
    gPad->SetLogy();
    TH1F* UnscaledSignalFreq = new TH1F ("UnscaledSignalFreq", "Unscaled Signal Frequency", nbins, -0.1, 799.9);
    for (Int_t l=0; l<nbins; l++) {
        UnscaledSignalFreq->SetBinContent(l+1, (PulseFreq->GetBinContent(l+1)-NoiseFreq->GetBinContent(l+1))/PulseFreq->GetBinContent(l+1));
    }
    TH1F* SignalFreq = new TH1F ("SignalFreq", "Signal Frequency", nbins, 0, 799.9);
    for (Int_t m=0; m<nbins; m++) {
        SignalFreq->SetBinContent(m+1, UnscaledSignalFreq->GetBinContent(m+1)*PulseFreq->GetBinContent(m+1));
    }
    Double_t *re_full = new Double_t[nbins];
    Double_t *im_full = new Double_t[nbins];
    for (Int_t n=0; n<nbins; n++) {
        (re_full)[n]=(SignalFreq->GetBinContent(n+1)*cos(PulsePhase->GetBinContent(n+1)));
        (im_full)[n]=(SignalFreq->GetBinContent(n+1)*sin(PulsePhase->GetBinContent(n+1)));
    }
    TVirtualFFT *invFFT = TVirtualFFT::FFT(1, &nbins, "C2R M K");
    invFFT->SetPointsComplex(re_full, im_full);
    invFFT->Transform();
    TH1 *Signal = 0;
    Signal = TH1::TransformHisto(invFFT,Signal,"Re");
    Signal->SetTitle("Recovered Signal 'S'");
    TH1F* BetterSignal = new TH1F ("BetterSignal", "Recovered Signal", nbins, -0.1, 159.9);
    for (Int_t p=0; p<nbins; p++) {
        BetterSignal->SetBinContent(p+1, Signal->GetBinContent(p+1)/nbins);
    }
    TimeSignal->Divide(1,2);
    TimeSignal->cd(1);
    PulseTime->DrawClone(); //Original Wave Pulse
    TimeSignal->cd(2);
    BetterSignal->GetXaxis()->SetTitle("Time (ns)");
    BetterSignal->GetYaxis()->SetTitle("Amplitude");
    BetterSignal->SetLineColor(kRed);
    //BetterSignal->Draw(); // Recovered Wave Pulse with decreased contribution from background noise
    BestSignal->SetLineColor(kGreen);
    BestSignal->DrawClone("same");
    PulseTime->DrawClone("same");
}
Esempio n. 4
0
void SPEFit(char * fname, int run, int LED_amp, double cutmax = 250.0)
{

  //set plotting styles
  gStyle->SetCanvasColor(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetFrameBorderMode(0);
  gStyle->SetStatColor(0);
  gStyle->SetPadTickX(1);
  gStyle->SetPadTickY(1);

    //set file names
    stringstream out_fname;
    stringstream out_fname1;
    out_fname<<"SPEconstants_Run_"<<run<<".txt";
    out_fname1<<"SPEspec_Run_"<<run<<".txt";

    ofstream  constants_file(out_fname.str().c_str(),ios_base::trunc); 
    ofstream  constants_file1(out_fname1.str().c_str(),ios_base::trunc);
    constants_file<<"Run "<<run<<endl;
    constants_file<<"type SPE"<<endl;
    constants_file<<"LED_amplitude "<<LED_amp<<endl<<endl;

    //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
    constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag Polya_shape Polya_shape_err Polya_mode"<<endl;

    out_fname.str("");
    out_fname<<"SPEdistributions_Run_"<<run<<".txt";


    out_fname.str("");
    out_fname<<"SPEextra_Run_"<<run<<".txt";
    //ofstream  extra_file(out_fname.str().c_str(),ios_base::trunc); 

    //extra_file<<endl<<"LED_amplitude HV Spigot Channel PedSubtracted_mean Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;


    double scale = 1.0;
    scale = 2.6; //Need to scale up HF charge
    double fC2electrons = 6240.; //convert fC to #electrons

    char spename[128], pedname[128], spehistname[128];
    bool drawflag;   
 
    TFile *tf = new TFile(fname);
    
    TCanvas *c1 = new TCanvas("c1","c1",1200,700);
    c1->Divide(6,4);
    c1->SetBorderMode(0);
    c1->SetBorderSize(0);
    TCanvas *c2 = new TCanvas("c2","c2",1200,700);
    c2->Divide(6,4);
    c2->SetBorderMode(0);
    c2->SetBorderSize(0);  
    TCanvas *c3 = new TCanvas("c3","c3",1200,700);
    c3->Divide(6,4);
    c3->SetBorderMode(0);
    c3->SetBorderSize(0);

    const int NnewBins = 106;
    double binsX[NnewBins] = {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126,128,130,132,134,136,138,140,142,144,146,148,150,152,154,156,158,160,162,164,166,168,170,180,190,200,210,220,230,240,250,266,282,298,316,336,356,378,404,430,456,482,500};	  
    TH1F* hspe = new TH1F("hspe","hspe",NnewBins-1,binsX);

    int Npoints;
    TH2D *tmp;
    for(Npoints=0;Npoints<10;Npoints++){
      sprintf(spename,"spetest/spigot_%d/bb_%d/LED_HVset_%d_sp_%d_BB_%d",0,1,Npoints,0,1);
      tmp=(TH2D *)tf->Get(spename);
      if(tmp==0) break;
    }
    TH2D *LED[3][3][20];
    TH2D *PED[3][3];
    for(int iSpig = 0; iSpig < 3; iSpig++)for(int bb = 1; bb < 4; bb++){
        for(int ii=0; ii<Npoints; ii++){
           sprintf(spename,"spetest/spigot_%d/bb_%d/LED_HVset_%d_sp_%d_BB_%d",iSpig,bb,ii,iSpig,bb);
           LED[iSpig][bb-1][ii]=(TH2D *)tf->Get(spename);
        }
        sprintf(spename,"spetest/spigot_%d/bb_%d/PED_sp_%d_BB_%d",iSpig,bb,iSpig,bb);
        PED[iSpig][bb-1]=(TH2D *)tf->Get(spename);
    }


    for(int ii=0; ii<Npoints; ii++) {
      drawflag=false;
      int HV=0;
      for (int iSpig = 0; iSpig < 3; iSpig++) {
	for(int i = 0; i < 24; i++) {
            int bb=BB_MAP[i];
            int pmt=PMT_MAP[i];
            sprintf(spehistname,"led %d %d %d",ii,iSpig,i);
            TH1D *hspe_temp = (TH1D *)LED[iSpig][bb-1][ii]->ProjectionX(spehistname,pmt,pmt,"")->Clone();
            sprintf(spehistname,"ped %d %d %d",ii,iSpig,i);
            TH1D *hped = (TH1D *)PED[iSpig][bb-1]->ProjectionX(spehistname,pmt,pmt,"")->Clone();
            sscanf(&hspe_temp->GetTitle()[7],"%d",&HV);
	    hspe->Reset();
            sprintf (spehistname, "SumLED%d_sp_%d_ch_%d", HV, iSpig, i);
	    hspe->SetTitle(spehistname);

	    //combine bins of original SPE histogram
	    for(int ib=1; ib<=hspe_temp->GetNbinsX(); ib++) {
	      double bin_center = hspe_temp->GetBinCenter(ib);
	      if(bin_center>hspe->GetXaxis()->GetXmax()) continue;
	      int newbin = hspe->FindBin(bin_center);
	      double new_content = hspe->GetBinContent(newbin) + hspe_temp->GetBinContent(ib);
	      double new_error = sqrt(pow(hspe->GetBinError(newbin),2)+pow(hspe_temp->GetBinError(ib),2));
	      hspe->SetBinContent(newbin,new_content);
	      hspe->SetBinError(newbin,new_error);
	    }
	    TH1F* hspe_unscaled = (TH1F*)hspe->Clone("hspe_unscaled");

	    //renormalize bins of new SPE histogram
	    for(int ib=1; ib<=hspe->GetNbinsX(); ib++) {
	      double new_content = hspe->GetBinContent(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	      double new_error = hspe->GetBinError(ib)/hspe->GetXaxis()->GetBinWidth(ib)*hspe_temp->GetXaxis()->GetBinWidth(1);
	      hspe->SetBinContent(ib,new_content);
	      hspe->SetBinError(ib,new_error);
	    }
	    
	    if(hspe_temp->Integral()==0) continue;
	    else drawflag=true;	  
    
            Nev = hspe_temp->Integral()*hspe_temp->GetXaxis()->GetBinWidth(1); 
	    
	    TF1 *fped = new TF1("fped","gaus",0, 80);
	    hped->Fit(fped,"NQR");
	    double pploc = fped->GetParameter(1), ppwidth = fped->GetParameter(2);
	    //cout<<"Ped only: ped mean "<<fped->GetParameter(1)<<", ped width "<<fped->GetParameter(2)<<" normalization "<<fped->GetParameter(0)<<endl;
	    hspe->Fit(fped, "NQ", "", pploc - 3*ppwidth, pploc + ppwidth);
	    //cout<<"SPE distribution: ped mean "<<fped->GetParameter(1)<<", ped width "<<fped->GetParameter(2)<<" normalization "<<fped->GetParameter(0)<<endl;
	    
	    
	    //estimate SPE peak location
	    int max_SPE_bin, maxbin, Nbins;
	    double max_SPE_height=0, minheight, max_SPE_location;
	    bool minflag = false;
	    maxbin=hspe->FindBin(fped->GetParameter(1)); //location of pedestal peak
	    minheight=hspe->GetBinContent(maxbin); //initialize minheight
	    /*
	    int maxped_bin = hspe->GetMaximumBin();
	    int maxped_binheight = hspe->GetBinContent(maxped_bin);
	    minheight = maxped_binheight;
	    */
	    Nbins = hspe->GetNbinsX();
	    for(int j=/*maxped_bin*/maxbin+1; j<Nbins-1; j++) { //start from pedestal peak and loop through bins
	      if(hspe->GetBinContent(j) > minheight && !minflag) minflag=true; //only look for SPE peak when minflag=true
	      if(hspe->GetBinContent(j) < minheight )  minheight = hspe->GetBinContent(j);
	      if(minflag && hspe->GetBinContent(j) > max_SPE_height){
		max_SPE_bin = j;
		max_SPE_location = hspe->GetBinCenter(max_SPE_bin);
		max_SPE_height = hspe->GetBinContent(j);
	      }
	    } //start from pedestal peak and loop through bins
	    //find minimum bin between pedestal and SPE peaks
	    hspe->GetXaxis()->SetRange(maxbin,max_SPE_bin);
	    int minbin = hspe->GetMinimumBin(); 
	    double minbin_location = hspe->GetBinCenter(minbin);
	    hspe->GetXaxis()->SetRange(1,Nbins);
	    
	    
	    TF1 *fit = new TF1("fit", FitFun, 0, 500, 5);
	    
	    double mu = - log(fped->Integral(0,100)/Nev);
	    if(mu<0) mu=0.01;
	    double gain_est = max_SPE_location-1.0*fped->GetParameter(1);
	    if(max_SPE_bin > (minbin+1)) fit->SetParameters(mu, 20, 1, gain_est, 3.0);
	    else fit->SetParameters(mu, 20, 1, 2.1*fped->GetParameter(2), 3.0); //case of no clear minimum; start looking for SPE peak at 2sigma away from pedestal peak
	    fit->SetParLimits(0, 0, 10);
	    fit->FixParameter(1, fped->GetParameter(1));
	    fit->FixParameter(2, fped->GetParameter(2));
	    fit->SetParLimits(3, fped->GetParameter(2)*2, 350);
	    fit->SetParLimits(4, 1.01, 100.);


	    double maxfitrange = 500.;    
	    double minfitrange = 0.;
	    hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);
	    double rms_estimate = fit->GetParameter(3)/sqrt(fit->GetParameter(4));
            maxfitrange = fped->GetParameter(1)+4*fit->GetParameter(3)+rms_estimate;

 //  cout<<"estimate of gain "<<gain_est<<", fit "<<fit->GetParameter(3)<<endl;
 //  cout<<"Shape Parameter "<<fit->GetParameter(4)<<endl;
 //  cout<<"SPE width "<<rms_estimate<<endl;
 //  cout<<"maxfitrange "<<maxfitrange<<endl;

            if(500<maxfitrange) maxfitrange = 500;
	    hspe->Fit(fit, "MNQL", "", minfitrange, maxfitrange);

	    //calculate NDOF of fit excluding bins with 0 entries
	    int myNDOF=-3; //three free parameters
	    for(int j=hspe->FindBin(minfitrange); j<=hspe->FindBin(maxfitrange); j++) { //loop through fitted spe bins
	      if(hspe->GetBinContent(j)) myNDOF++;
            } //loop through fitted spe bins


//	    cout<<"estimate of gain "<<gain_est<<", fit "<<fit->GetParameter(3)<<endl;
//	    cout<<"Shape Parameter "<<fit->GetParameter(4)<<endl;
//	    double SPE_rms = fit->GetParameter(3)/sqrt(fit->GetParameter(4));
//	    cout<<"SPE width "<<SPE_rms<<endl;

	    //cout<<"SPE width "<<fit->GetParameter(4)<<endl;
	    //cout<<"Fit normalization constant: estimate "<<mu<<" fit "<<fit->GetParameter(0)<<endl;
	    //cout<<spename<<endl;


	    //calculate means and integrals of the fit and data
	    double fint, fint_error, hint, favg, havg;
	    int temp_lowbin, temp_highbin;
	    temp_lowbin = hspe->FindBin(minfitrange);
	    temp_highbin = hspe->FindBin(maxfitrange);
	    hspe_unscaled->GetXaxis()->SetRangeUser(minfitrange, maxfitrange);
	    havg = hspe_unscaled->GetMean();
	    hint = hspe->Integral(temp_lowbin,temp_highbin,"width");
	    double min_frange = hspe->GetBinLowEdge(temp_lowbin);
	    favg = fit->Mean(min_frange, maxfitrange);
	    fint = fit->Integral(min_frange, maxfitrange);
	    //fint_error = fit->IntegralError(min_frange, maxfitrange);
	    
	    double PE5int = 0; //integral of events with >=5 PE
	    double PE5loc =  fped->GetParameter(1)+ 5*fit->GetParameter(3);
	    if(PE5loc>500) PE5int = 0;
	    else {
	      int PE5bin =  hspe_temp->FindBin(PE5loc);
	      temp_highbin = hspe_temp->FindBin(maxfitrange)-1;
	      PE5int =  hspe_temp->Integral(PE5bin,temp_highbin,"width");
	    }
	    int PE5flag = 0;
	    if(PE5int/hint>0.05) PE5flag = 1; //set flag if more than 5% of events in the fit correspond to >=5PE
        //=========================================    
            for(int i1=1;i1<hspe->GetNbinsX();i1++){
constants_file1<<HV<<"\t"<<iSpig<<"\t"<<i<<"\t"<<2.6*hspe->GetBinCenter(i1)<<"\t"<<hspe->GetBinContent(i1)<<"\t"<<fit->Eval(hspe->GetBinCenter(i1))<<"\n";
            }
        //=========================================    


	    //output calibrations constants
	    //constants_file<<endl<<"LED_amplitude HV Spigot Channel Ped_mean Ped_mean_err Ped_RMS  Ped_RMS_err SPEPeak_RMS SPEPeak_RMS_err Gain Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag Polya_shape Polya_shape_err Polya_mode"<<endl;
	    constants_file<<LED_amp<<" "<<HV<<" "<<iSpig<<" "<<(bb-1)*8+pmt<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(3)/sqrt(fit->GetParameter(4))<<" "<<0<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/myNDOF/*fit->GetNDF()*/<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<" "<<fit->GetParameter(4)<<" "<<fit->GetParError(4)<<" "<<scale*(fit->GetParameter(4)-1.0)/fit->GetParameter(4)*fit->GetParameter(3)*fC2electrons<<endl;



//	    cout<<LED_amp<<" "<<HV<<" "<<iSpig<<" "<<QIECh[i]<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParError(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fped->GetParError(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParError(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<scale*fit->GetParError(3)*fC2electrons<<" "<<fit->GetChisquare()/fit->GetNDF()<<" "<<fit->GetChisquare()<<" "<<fit->GetNDF()<<" "<<myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<endl;
	   
	    //extra_file<<endl<<"LED_amplitude HV Spigot Channel SignalAvg_inFitRange FitAvg_inFitRange SignalInt_inFitRange FitInt_inFitRange PEge5Int Gain(fC) Gain_err Normalized_Chi2 MeanPE_fit MeanPE_fit_err MeanPE_estimate PE5flag"<<endl;
	    //extra_file<<LED_amp<<" "<<HV<<" "<<iSpig<<" "<<QIECh[i]<<" "<<scale*havg<<" "<<scale*favg<<" "<<hint<<" "<<fint<<" "<<PE5int<<" "<<scale*fit->GetParameter(3)<<" "<<scale*fit->GetParError(3)<<" "<<fit->GetChisquare()/myNDOF<<" "<<fit->GetParameter(0)<<" "<<fit->GetParError(0)<<" "<<mu<<" "<<PE5flag<<endl;


	    //cout<<"# Spigot Channel Ped_mean Ped_RMS SPE_PeakRMS Gain Normalized_Chi2 Avg_PE"<<endl;
	    //cout<<iSpig<<" "<<i<<" "<<scale*fped->GetParameter(1)<<" "<<scale*fped->GetParameter(2)<<" "<<scale*fit->GetParameter(4)<<" "<<scale*fit->GetParameter(3)*fC2electrons<<" "<<fit->GetChisquare()/fit->GetNDF()<<" "<<fit->GetParameter(0)<<endl<<endl;
	    
	    
	  
	    if(iSpig==0) c1->cd(i+1);
	    else if(iSpig==1) c2->cd(i+1);
            else if(iSpig==2) c3->cd(i+1);
	    gPad->SetBorderMode(0);
	    gPad->SetBorderSize(0);
	    gPad->SetRightMargin(0.01);
	    gPad->SetBottomMargin(0.1);
	    gPad->SetLogy(true);
	    hspe->GetXaxis()->SetRangeUser(0, /*300*/508);
	    hspe->SetLineColor(kBlue);
	    hspe->DrawClone("hist");
	    fit->SetLineWidth(2);
	    fit->Draw("same");
	   
	  }
      }

      if(drawflag) { //draw plots of fit if data for the HV is present
        stringstream plot_name;
        //plot_name<<"Plots/SPEFits_Spigot0_Run_"<<run<<"_HV"<<HV<<".pdf";
        plot_name<<"Plots/SPEFits_Spigot0_Run_"<<run<<"_HV"<<HV<<"_config"<<ii<<".pdf";
        c1->SaveAs(plot_name.str().c_str());
        plot_name.str( std::string() );
        //plot_name<<"Plots/SPEFits_Spigot1_Run_"<<run<<"_HV"<<HV<<".pdf";
        plot_name<<"Plots/SPEFits_Spigot1_Run_"<<run<<"_HV"<<HV<<"_config"<<ii<<".pdf";
        c2->SaveAs(plot_name.str().c_str());
        plot_name.str( std::string() );
        //plot_name<<"Plots/SPEFits_Spigot2_Run_"<<run<<"_HV"<<HV<<".pdf";
        plot_name<<"Plots/SPEFits_Spigot2_Run_"<<run<<"_HV"<<HV<<"_config"<<ii<<".pdf";
        c3->SaveAs(plot_name.str().c_str());
      }

    } //HV loop

    constants_file.close();
    constants_file1.close();
}
void readTree_background() {
  Char_t *filename = "Background.root";
  // Retrieve the TTree
  TFile* myFile = TFile::Open(filename);
  TTree* tree = (TTree*)(myFile->Get("tree"));
  Double_t Et1, eta1, phi1, Et2, eta2, phi2;
  tree->SetBranchAddress("Et1" ,&Et1 );
  tree->SetBranchAddress("eta1",&eta1);
  tree->SetBranchAddress("phi1",&phi1);
  tree->SetBranchAddress("Et2" ,&Et2 );
  tree->SetBranchAddress("eta2",&eta2);
  tree->SetBranchAddress("phi2",&phi2);
  // Book histograms
  TH1F* hmass = new TH1F("hmass","m_{#gamma#gamma}",60,100.,160.);
  hmass->GetXaxis()->SetTitle("Invariant mass [GeV]");
  hmass->GetYaxis()->SetTitle("Events");
  // Loop over the events
  Long64_t events = tree->GetEntries();  
  for (int i=0; i<events; i++) {
    tree->GetEntry(i);
    TLorentzVector g1,g2;
    g1.SetPtEtaPhiM(Et1,eta1,phi1,0.);
    g2.SetPtEtaPhiM(Et2,eta2,phi2,0.);
    TLorentzVector gg=g1+g2;
    hmass->Fill( gg.M() );
  }
  // Test of different background options
  hmass->DrawClone("e");
  TCanvas* myCanvas = new TCanvas("myCanvas","Background fits",800,800);
  myCanvas->Divide(2,2);
  // Linear background
  TF1* myBack1 = new TF1("myBack1","[0]+[1]*x",100.,160.);
  myBack1->SetParameter(0,events);
  myBack1->SetParameter(1,-100.);
  myCanvas->cd(1);
  hmass->Fit(myBack1);
  hmass->DrawClone("e");
  EvaluatePvalue(myBack1);
  // Quadratic background
  TF1* myBack2 = new TF1("myBack2","[0]+[1]*x+[2]*x**2",100.,160.);
  myBack2->SetParameter(0,events);
  myBack2->SetParameter(1,-100.);
  myBack2->SetParameter(1,0.);
  myCanvas->cd(2);
  hmass->Fit(myBack2);
  hmass->DrawClone("e");
  EvaluatePvalue(myBack2);
  // Exponential background
  TF1* myBack3 = new TF1("myBack3","[0]*exp(-x/[1])",100.,160.);
  myBack3->SetParameter(0,events);
  myBack3->SetParameter(1,100.);
  myCanvas->cd(3);
  hmass->Fit(myBack3);
  hmass->DrawClone("e");
  EvaluatePvalue(myBack3);
  // Cubic background
  TF1* myBack4 = new TF1("myBack4","[0]+[1]*x+[2]*x**2+[3]*x**3",100.,160.);
  myBack4->SetParameter(0,0.);
  myBack4->SetParameter(1,0.);
  myBack4->SetParameter(2,0.);
  myBack4->SetParameter(3,0.);
  myCanvas->cd(4);
  TFitResultPtr fit4 = hmass->Fit(myBack4,"S");
  hmass->DrawClone("e");
  EvaluatePvalue(myBack4);
}
int main() {
	Int_t nbins = 800, count = 0;
    Double_t integral;
	TFile *input = new TFile("FilterRMSComparison.root");
    TFile *templatefile = new TFile("/home/marko/Desktop/H4Analysis/ntuples/Templates_APDs.old.root");
	TTree *MyTree = (TTree*) input->Get("RMS");
    TCanvas *can1 = new TCanvas("can1", "canvas", 1200,900);
    TCanvas *can2 = new TCanvas("can2", "canvas", 1200,1200);
    TCanvas *can3 = new TCanvas("can3", "canvas", 1200,1200);
    can1->Divide(1,3);
    can2->Divide(1,2);
    can3->Divide(1,2);
    MyTree->SetEntryList(0);
    TString listcut = "abs(unfilteredbslope)<6 && unfilteredampfit>700";
    MyTree->Draw(">>myList", listcut, "entrylist");
    TEntryList *myList = (TEntryList*) gDirectory->Get("myList");
    MyTree->SetEntryList(myList);
    Int_t nevents = myList->GetN();
	MyTree->Draw("unfilteredevent", "abs(unfilteredbslope)<6 && unfilteredampfit>700", "goff");
    Double_t *vTemp = MyTree->GetV1();
    Int_t *vEvent = new Int_t[nevents];
    for (int iEntry = 0; iEntry<nevents; iEntry++) {
        vEvent[iEntry] = vTemp[iEntry];
    }
	TString plot, plot2, cut;
	char name[50];
    TH1F *histoave = new TH1F("histoave","Wave Pulse Average", nbins, -40, 120);
    TH1F *histoavefft = new TH1F("histoavefft","Wave Pulse Average FFT", nbins, 0, 5);
    TH1F *histoaveph = new TH1F("histoaveph","Wave Pulse Average Phase", nbins, 0, 800);
    TH1F *originaltemplate = (TH1F*) templatefile->Get("APD2_E50_G50_prof");
    originaltemplate->Rebin(16);
    TH1F *templatehisto = new TH1F("templatehisto", "Template = Green, Average = Red", nbins, -40, 120); 
    TH1F *difference = new TH1F("difference","Template vs. Average Difference", nbins, -40, 120);
    TH1F *percentdifference = new TH1F("percentdifference","Template vs. Average Percent Difference", nbins, -40, 120);
    for (Int_t i=0;i<nbins;i++) {
        templatehisto->SetBinContent(i+1, originaltemplate->GetBinContent(i+1));
    }
    templatehisto->SetLineColor(kGreen+3);
    templatehisto->SetLineWidth(4);
    can2->cd(2);
    histoave->GetYaxis()->SetRangeUser(-.120,1.2);
    //templatehisto->Draw();
    histoave->SetStats(0);
    histoave->Draw();
	for (Int_t i=0;i<nevents;i++) {
    //for (Int_t i=0;i<10;i++) {
        if (vEvent[i]==513) continue; //event for which electronics die out for a bit halfway through
		TString histoname = "TempHisto_";
        histoname += i;
        TString histoname2 = "TempHisto2_";
        histoname2 += i;
        TH2F* TempHisto = new TH2F (histoname, "Temp Histo", nbins, -40, 120, 1000, -120, 800); //nanoseconds
        TH2F* TempHisto2 = new TH2F (histoname2, "Temp Histo", nbins, -40, 120, 1000, -120, 800); //nanoseconds
        TString h1name = "h1001_";
        h1name += i;
        TString h1name2 = "h1002_";
        h1name2 += i;
        TString h1name2fft = "h1002fft_";
        h1name2 += i;
        TString h1name2ph = "h1002ph_";
        h1name2 += i;
        TString h1name3 = "h1003_";
        h1name3 += i;
        TString h1name4 = "h1004_";
        h1name4 += i;
        TH1F *h1001 = new TH1F(h1name,"Red = Unfiltered, Blue = Filtered", nbins, -40, 120);
        TH1F *h1002 = new TH1F(h1name2,"h1002", nbins, -40, 120);
        TH1F *h1002fft = new TH1F(h1name2fft,"h1002fft", nbins, 0, 5);
        TH1F *h1002ph = new TH1F(h1name2ph,"h1002ph", nbins, 0, 800);
        TH1F *h1003 = new TH1F(h1name3,"Filtered WF - Unfiltered WF", nbins, -40, 120);
        TH1F *h1004 = new TH1F(h1name4,"Percent Change in Filtered WF - Unfiltered WF", nbins, -40, 120);
        plot = "unfilteredwfval:(unfilteredwftime-unfilteredtimeref)>>";
        plot += histoname;
        plot2 = "filteredwfval:(filteredwftime-filteredtimeref)>>";
        plot2 += histoname2;
        cut = "abs(unfilteredbslope)<6 && unfilteredampfit>700 && unfilteredevent==";
        cut += vEvent[i];
        MyTree->Draw(plot, cut, "goff");
        TempHisto = (TH2F*) gDirectory->Get(histoname);
        h1001 = transform2Dto1D(TempHisto);
        MyTree->Draw(plot2, cut, "goff");
        TempHisto2 = (TH2F*) gDirectory->Get(histoname2);
        h1002 = transform2Dto1D(TempHisto2);
        if (h1002->GetBinCenter(h1002->GetMaximumBin()) < 30) continue;
        sprintf(name, "Good Events/Event%d", vEvent[i]);
        strcat(name, ".png");
        h1001->SetLineColor(kRed);
        h1002->SetLineColor(kBlue);
        h1001->SetStats(0);
        h1002->SetStats(0);
        //can1->cd(1);
        can1->cd();
        h1001->GetXaxis()->SetTitle("Time (ns)");
        h1001->GetYaxis()->SetTitle("Amplitude");
        h1001->Draw();
        h1002->Draw("same");
        //for (Int_t i=0;i<nbins;i++) {
        //    h1003->SetBinContent(i+1, (h1002->GetBinContent(i+1))-(h1001->GetBinContent(i+1)));
        //    if (h1001->GetBinContent(i+1) != 0) h1004->SetBinContent(i+1, ((h1002->GetBinContent(i+1))-(h1001->GetBinContent(i+1)))/(h1001->GetBinContent(i+1)));
        //    else h1004->SetBinContent(i+1, 0);
        //}
        //can1->cd(2);
        //h1003->Draw();
        //can1->cd(3);
        //h1004->Draw();
        //h1004->GetYaxis()->SetRangeUser(-0.1,0.1);
        //gPad->SetGrid();
        can1->SaveAs(name);
        //h1002->FFT(h1002fft, "MAG");
        //h1002->FFT(h1002ph, "PH");
        //histoavefft->Add(histoavefft, h1002fft);
        //histoaveph->Add(histoaveph, h1002ph);
        histoave->Add(histoave, h1002);
        can2->cd(2);
        h1002->Scale(1./(h1002->GetMaximum()));
        h1002->Draw("same");
        count++;
        delete TempHisto, TempHisto2, h1001, h1002, h1003, h1004, histoname, histoname2, h1name, h1name2, h1name3, h1name4;
        gDirectory->Clear();
	}
    can2->cd(1);
    //histoavefft->Scale(1./count);
    //histoaveph->Scale(1./count);
    histoave->Scale(1./count);
    
    //Double_t *re_full = new Double_t[nbins];
    //Double_t *im_full = new Double_t[nbins];
    //TH1 *Throwaway = 0;
    //TH1F *invhistoave = new TH1F(invhistoave, "Average Pulse", nbins, -40, 120);
    //TVirtualFFT *invFFT = TVirtualFFT::FFT(1, &nbins, "C2R M K");
    //for (Int_t n=0; n<nbins; n++) {
    //    (re_full)[n]=(histoavefft->GetBinContent(n+1)*cos(histoaveph->GetBinContent(n+1)));
    //    (im_full)[n]=(histoavefft->GetBinContent(n+1)*sin(histoaveph->GetBinContent(n+1)));
    //}
    //invFFT->SetPointsComplex(re_full, im_full);
    //invFFT->Transform();
    //Throwaway = TH1::TransformHisto(invFFT, Throwaway, "Re");
    //for (Int_t p=0; p<nbins; p++) {
    //    histoave->SetBinContent(p+1, Throwaway->GetBinContent(p+1)/nbins);
    //}
    histoave->Scale(1./(histoave->GetMaximum()));
    histoave->SetLineColor(kRed);
    histoave->SetLineWidth(4);
    integral = templatehisto->Integral();
    templatehisto->Scale(1./integral);
    templatehisto->SetStats(0);
    templatehisto->Draw();
    integral = histoave->Integral();
    histoave->Scale(1./integral);
    histoave->DrawClone("same");
    histoave->Scale(integral);
    can2->cd(2);
    histoave->GetXaxis()->SetTitle("Time (ns)");
    histoave->GetYaxis()->SetTitle("Normalized Amplitude");
    histoave->DrawClone("same");
    can2->SaveAs("AmpSpread.png");
    can2->SaveAs("AmpSpreadRoot.root");
    TFile *output = new TFile("Alignment.root", "recreate");
    output->cd();
    originaltemplate->Write();
    histoave->Write();
    templatehisto->Write();
    output->Close();
    can3->cd(1);
    histoave->Scale(1./integral);
    for (int i=0;i<nbins;i++) {
        difference->SetBinContent(i+1, histoave->GetBinContent(i+1) - templatehisto->GetBinContent(i+1));
        if (templatehisto->GetBinContent(i+1) != 0) percentdifference->SetBinContent(i+1, (histoave->GetBinContent(i+1) - templatehisto->GetBinContent(i+1))/templatehisto->GetBinContent(i+1));
        else percentdifference->SetBinContent(i+1, 0);
    }
    difference->GetXaxis()->SetTitle("Time (ns)");
    difference->GetYaxis()->SetTitle("Average - Template");
    difference->SetStats(0);
    difference->Draw();
    can3->cd(2);
    percentdifference->GetXaxis()->SetTitle("Time (ns)");
    percentdifference->GetYaxis()->SetTitle("Percent Difference Average - Template");
    percentdifference->SetStats(0);
    percentdifference->Draw();
    percentdifference->GetYaxis()->SetRangeUser(-0.1,0.1);
    gPad->SetGrid();
    can3->SaveAs("Difference.png");
    can3->SaveAs("Difference.root");
}