void KVElasticCountRates::PrintResults(Double_t beam_intensity)
{
   // Print mean energy deposit & counting rate for given beam intensity in particles per second

   TIter it(&fHistos);
   TH1F* h;
   fRates.clear();

   std::vector<count_rate> count_rates;

   while ((h = (TH1F*)it())) {
      TString name = h->GetName();
      if (!name.EndsWith("_dW") && !name.EndsWith("_map")) {
         TH2F* map = (TH2F*)fHistos.FindObject(name + "_map");
         double rate = h->Integral() * fAtomicDensity * beam_intensity * fVolume / fNtirages;
         double emean = h->GetMean();
         KVDetector* det = gMultiDetArray->GetDetector(name);
         double fluence = rate / det->GetEntranceWindowSurfaceArea();
         double dissipation = emean * rate / det->GetEntranceWindowSurfaceArea();
         count_rates.push_back(
            count_rate(name, rate, emean, map->GetMean(), map->GetMean(2), fluence, dissipation)
         );
         fRates[name.Data()] = KVElasticCountRate(rate, emean, fluence, dissipation);
      }
   }
   std::sort(count_rates.begin(), count_rates.end(), compare_count_rates);

   for (std::vector<count_rate>::iterator it = count_rates.begin(); it != count_rates.end(); ++it) {
      it->print();
   }
}
Example #2
0
int main(int argc, char** argv){

 ///==================================================
 ///==== Draw Distribution with and without scale ====
 ///==================================================

 ///===============================================================================
 gROOT->Reset();
 gROOT->SetStyle("Plain");
 gStyle->SetPalette(1);
 gStyle->SetOptStat(0);
 gStyle->SetOptFit(0);

 const Int_t __NRGBs = 5;
 const Int_t __NCont = 76;
 Double_t __stops[__NRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 };
 Double_t __red[__NRGBs]   = { 0.00, 0.00, 0.87, 1.00, 0.51 };
 Double_t __green[__NRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 };
 Double_t __blue[__NRGBs]  = { 0.51, 1.00, 0.12, 0.00, 0.00 };

 TColor::CreateGradientColorTable(__NRGBs, __stops, __red, __green, __blue, __NCont);
 gStyle->SetNumberContours(__NCont);
 ///===============================================================================
 

 if(argc != 2)
 {
  std::cerr << ">>>>> analysis.cpp::usage: " << argv[0] << " configFileName" << std::endl ;
  return 1;
 }

 // Parse the config file
 parseConfigFile (argv[1]) ;

 std::string treeNameDATA  = gConfigParser -> readStringOption("InputDATA::treeName");
 std::string inputFileDATA = gConfigParser -> readStringOption("InputDATA::inputFile");
 double luminosity = gConfigParser -> readDoubleOption("InputDATA::luminosity");
 std::cout << ">>>>> InputDATA::treeName   " << treeNameDATA  << std::endl;
 std::cout << ">>>>> InputDATA::inputFile  " << inputFileDATA  << std::endl;
 std::cout << ">>>>> InputDATA::luminosity " << luminosity  << std::endl;

 std::string treeNameMC  = gConfigParser -> readStringOption("InputMC::treeName");
 std::vector< std::string > inputFileMC = gConfigParser -> readStringListOption("InputMC::inputFile");
 std::vector< std::string > inputSampleMC = gConfigParser -> readStringListOption("InputMC::nameSample");
 std::vector< double > xSecAndEfficiency = gConfigParser -> readDoubleListOption("InputMC::xsecEff");

 std::cout << ">>>>> InputMC::treeName  " << treeNameMC  << std::endl;
 std::cout << ">>>>> InputMC::inputFile size " << inputFileMC.size()  << std::endl;
 if (inputFileMC.size() != xSecAndEfficiency.size() || inputFileMC.size() != inputSampleMC.size()) {
     std::cerr << " >>>> Error: different number of samples and cross sections" << std::endl;
     return 0;
    }
 int nMC = inputFileMC.size();
 for (int iMC = 0; iMC < nMC; iMC++) {
    std::cout << ">>>>> InputMC::inputFile[" << iMC << "] = " << inputSampleMC.at(iMC) << " => " << inputFileMC.at(iMC)  << " : " << xSecAndEfficiency.at(iMC) << " : " << luminosity * xSecAndEfficiency.at(iMC) << std::endl;
 }


 int binX = gConfigParser -> readIntOption("Options::binX");
 double minX = gConfigParser -> readDoubleOption("Options::minX");
 double maxX = gConfigParser -> readDoubleOption("Options::maxX");
 std::string variableX = gConfigParser -> readStringOption("Options::variableX");
 std::cout << ">>>>> Options::binX      " << binX  << std::endl;
 std::cout << ">>>>> Options::minX      " << minX  << std::endl;
 std::cout << ">>>>> Options::maxX      " << maxX  << std::endl;
 std::cout << ">>>>> Options::variableX " << variableX.c_str() << std::endl;

 int binY = gConfigParser -> readIntOption("Options::binY");
 double minY = gConfigParser -> readDoubleOption("Options::minY");
 double maxY = gConfigParser -> readDoubleOption("Options::maxY");
 std::string variableY = gConfigParser -> readStringOption("Options::variableY");
 std::cout << ">>>>> Options::binY      " << binY  << std::endl;
 std::cout << ">>>>> Options::minY      " << minY  << std::endl;
 std::cout << ">>>>> Options::maxY      " << maxY  << std::endl;
 std::cout << ">>>>> Options::variableY " << variableY.c_str() << std::endl;
 
 int binRatio = gConfigParser -> readIntOption("Options::binRatio");
 double minRatio = gConfigParser -> readDoubleOption("Options::minRatio");
 double maxRatio = gConfigParser -> readDoubleOption("Options::maxRatio");
 std::cout << ">>>>> Options::minRatio      " << minRatio  << std::endl;
 std::cout << ">>>>> Options::maxRatio      " << maxRatio  << std::endl;
 
 
 std::string outputFile = gConfigParser -> readStringOption("Output::outputFile");
 std::cout << ">>>>> Output::outputFile  " << outputFile  << std::endl;


//  TString AdditionalCut = Form("eta > 1.5");// || eta < -1.5)");// && eleFBrem<0.5");
 TString AdditionalCut = Form("eta < -1.5");// || eta < -1.5)");// && eleFBrem<0.5");
//  TString AdditionalCut = Form("(eta > 1.5 || eta < -1.5)");// && abs(eleFBrem)<1");
 
 
 
 EColor vColor[100] = {
  kBlue,(EColor)(kBlue+1),(EColor) (kBlue+2),
  kRed,(EColor) (kRed+1),(EColor) (kRed+2),
  kGreen,(EColor) (kGreen+1),(EColor) (kGreen+2),
  kTeal,(EColor) (kTeal+1),
  kOrange,(EColor) (kOrange+1),
  kMagenta,(EColor) (kMagenta+1),(EColor) (kViolet),(EColor) (kYellow),(EColor) (kGray)};
 
 ///==== DATA ====
 TFile* fileInDATA = new TFile(inputFileDATA.c_str(),"READ");

 ///==== W ====
 TFile* fileInMC[nMC];
 for (int iMC = 0; iMC < nMC; iMC++) {
    fileInMC[iMC] = new TFile(inputFileMC.at(iMC).c_str(),"READ");
 }

 ///==== output ====
 TFile* outFile = new TFile(outputFile.c_str(),"RECREATE");
 outFile->cd();


 ///==== Prepare input trees ====
 TLegend* leg = new TLegend(0.55,0.7,0.95,0.95);
 leg->SetFillColor(0);

 TLegend* legDown = new TLegend(0.55,0.1,0.95,0.35);
 legDown->SetFillColor(0);

 TTree* MyTreeDATA = (TTree*) fileInDATA->Get(treeNameDATA.c_str());
 int initialNumber;
 TH2F* HistoDATA = new TH2F("DATA","DATA",binX,minX,maxX,binY,minY,maxY);
 TH1F* HistoRatioDATA = new TH1F("RatioDATA","RatioDATA",binRatio,minRatio,maxRatio);
 TString DrawDATA = Form("%s:%s >> DATA",variableY.c_str(),variableX.c_str());
 MyTreeDATA->Draw(DrawDATA.Data(),AdditionalCut.Data());
 HistoDATA->SetMarkerSize(1);
 HistoDATA->SetMarkerStyle(20); 
 HistoDATA->GetXaxis()->SetTitle(variableX.c_str());
 HistoDATA->GetYaxis()->SetTitle(variableY.c_str());
 leg->AddEntry(HistoDATA,HistoDATA->GetTitle(),"p");
 legDown->AddEntry(HistoDATA,HistoDATA->GetTitle(),"p");

 DrawDATA = Form("(%s) / (%s) >> RatioDATA",variableY.c_str(),variableX.c_str());
 MyTreeDATA->Draw(DrawDATA.Data(),AdditionalCut.Data());
 HistoRatioDATA->SetMarkerSize(1);
 HistoRatioDATA->SetMarkerStyle(20); 
 HistoRatioDATA->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str()));
 
 TH2F* HistoMC[nMC];
 TH1F* HistoRatioMC[nMC];

 TH2F* HistoMC_SUM = new TH2F("HistoMC_SUM","HistoMC_SUM",binX,minX,maxX,binY,minY,maxY);
 TH1F* HistoRatioMC_SUM = new TH1F("HistoRatioMC_SUM","HistoRatioMC_SUM",binRatio,minRatio,maxRatio);
 
 SetColorAndStyleHisto(*(HistoRatioMC_SUM),kBlue); 
 
 TTree* MyTreeMC[nMC];
 THStack* hsMC = new THStack("hsMC","hsMC");
 
 double MC_Expected = 0;
 
 for (int iMC = 0; iMC < nMC; iMC++) {
// for (int iMC = nMC-1; iMC >= 0; iMC--) {
  MyTreeMC[iMC] = (TTree*) fileInMC[iMC]->Get(treeNameMC.c_str());
  MyTreeMC[iMC]->SetBranchAddress("initialNumber",&initialNumber);
  MyTreeMC[iMC]->GetEntry(0);
  xSecAndEfficiency.at(iMC) = xSecAndEfficiency.at(iMC) / initialNumber; ///==== normalize to initial number of events
  HistoMC[iMC] = new TH2F(inputSampleMC.at(iMC).c_str(),inputSampleMC.at(iMC).c_str(),binX,minX,maxX,binY,minY,maxY);
  HistoRatioMC[iMC] = new TH1F(Form("%s_Ratio",inputSampleMC.at(iMC).c_str()),Form("%s_Ratio",inputSampleMC.at(iMC).c_str()),binRatio,minRatio,maxRatio);
  
  TString Draw = Form("%s:%s >> %s",variableY.c_str(),variableX.c_str(),inputSampleMC.at(iMC).c_str());
  MyTreeMC[iMC]->Draw(Draw.Data(),AdditionalCut.Data());

  Draw = Form("(%s) / (%s) >> %s",variableY.c_str(),variableX.c_str(),Form("%s_Ratio",inputSampleMC.at(iMC).c_str()));
  MyTreeMC[iMC]->Draw(Draw.Data(),AdditionalCut.Data());  
  HistoRatioMC[iMC]->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str()));
  
  std::cout << ">>>>>> " << inputSampleMC.at(iMC) << " : " << xSecAndEfficiency.at(iMC) << " : " << luminosity << " : " << HistoMC[iMC]->GetEntries() << " = " << luminosity * xSecAndEfficiency.at(iMC) * HistoMC[iMC]->GetEntries() << std::endl;
  std::cout << "    >> " << Draw.Data() << std::endl;
  std::cout << "    >> " << HistoMC[iMC]->GetEntries() << " Entries" << std::endl;
 
  MC_Expected += luminosity * xSecAndEfficiency.at(iMC) * HistoMC[iMC]->GetEntries();
  
  HistoMC[iMC]->Scale(luminosity * xSecAndEfficiency.at(iMC)); // / HistoMC[iMC]->GetEntries());
  HistoRatioMC[iMC]->Scale(luminosity * xSecAndEfficiency.at(iMC)); // / HistoMC[iMC]->GetEntries());
  
  SetColorAndStyleHisto(*(HistoMC[iMC]),vColor[iMC]);
  SetColorAndStyleHisto(*(HistoRatioMC[iMC]),vColor[iMC]);
  
  HistoMC[iMC]->GetXaxis()->SetTitle(variableX.c_str());
  HistoMC[iMC]->GetYaxis()->SetTitle(variableY.c_str());
  
  HistoMC_SUM->Add(HistoMC[iMC]);
  HistoMC_SUM->GetXaxis()->SetTitle(variableX.c_str());
  HistoMC_SUM->GetYaxis()->SetTitle(variableY.c_str());
  
  HistoRatioMC_SUM->Add(HistoRatioMC[iMC]);
  HistoRatioMC_SUM->GetXaxis()->SetTitle(Form("(%s)/(%s)",variableY.c_str(),variableX.c_str()));
  
  hsMC->Add(HistoMC[iMC]);
  if (iMC == 0) hsMC->Add(HistoMC[iMC]);
  leg->AddEntry(HistoMC[iMC],HistoMC[iMC]->GetTitle(),"f");
  legDown->AddEntry(HistoMC[iMC],HistoMC[iMC]->GetTitle(),"f");
 }
  
  
 ///==== make fit ====
 
 TH1D* htemp_prof = smartGausProfileXSQRTN(HistoDATA,2);  
 TGraphErrors grH = buildGEfromH_Personalized(*htemp_prof);
 grH.SetMarkerStyle(22);
 grH.SetMarkerSize(0.7);
 grH.SetMarkerColor(kBlue);
 grH.SetFillColor(kBlue);
 grH.SetFillStyle(3335);
 grH.SetLineWidth(1);
 grH.SetLineColor(kBlue);
 grH.GetXaxis()->SetTitle(variableX.c_str());
 grH.GetYaxis()->SetTitle(variableY.c_str());
 

 ///----------------------
 ///---- Plot results ----
 ///----------------------
 std::cerr << " MC expected : DATA = " << MC_Expected << " : " << HistoDATA->GetEntries() << std::endl;
 
 std::cerr << " HistoDATA->GetMaximum() = " << HistoDATA->GetMaximum() << std::endl;
 std::cerr << " HistoDATA->GetEntries() = " << HistoDATA->GetEntries() << std::endl;
 outFile->cd();
 
 TCanvas cResultDistro("cResultDistro","cResultDistro",900,900);
 cResultDistro.Divide(2,2);
 cResultDistro.cd(1);
 HistoDATA->DrawClone("colz");
 gPad->SetGrid();
 TString tLumiName = Form("#int L = %.4f pb^{-1}",luminosity);
 TLatex tLumi(1.5 * HistoDATA->GetMean(1),0.2 * HistoDATA->GetMaximum(),tLumiName.Data());
 tLumi.DrawClone();
 
 
 cResultDistro.cd(2);
 HistoRatioMC_SUM->Draw();
 HistoRatioDATA->Draw("E1same");
 TString tEleName = Form("%d electrons",(int) HistoDATA->GetEntries());
 TLatex tEle(2.0 * HistoRatioDATA->GetMean(1),0.3 * HistoRatioDATA->GetMaximum(),tEleName.Data());
 tEle.DrawClone();
 gPad->SetGrid();

 
 cResultDistro.cd(3);
 grH.Draw("APL");
 double minFit = gConfigParser -> readDoubleOption("Options::minFit");
 double maxFit = gConfigParser -> readDoubleOption("Options::maxFit");
 std::cout << ">>>>> Options::minFit      " << minFit  << std::endl;
 std::cout << ">>>>> Options::maxFit      " << maxFit  << std::endl;
 
 TF1* funz = new TF1 ("funz","pol1",minFit,maxFit);
//  funz->FixParameter(0,0);
 funz->SetParameter(0,0);
 funz->SetParameter(1,1);
 grH.Fit("funz","RMQ");
 std::cerr << " Y = [0] + [1] * X " << std::endl;
 std::cerr << " [0] = " << funz->GetParameter(0) << " +/- " << funz->GetParError(0) << std::endl;
 std::cerr << " [1] = " << funz->GetParameter(1) << " +/- " << funz->GetParError(1) << std::endl;
 double coeffDATA = funz->GetParameter(1);
 double errCoeffDATA = funz->GetParError(1);
 
 gPad->SetGrid();
 
 
 cResultDistro.cd(4);
 HistoRatioMC_SUM->Draw();
 HistoRatioDATA->Draw("E1same");
 tEle.DrawClone();
 gPad->SetGrid();
 gPad->SetLogy();
 
 
 TString nameImage = Form("%s_%s_%d.png",variableY.c_str(),variableX.c_str(),1);
 cResultDistro.SaveAs(nameImage.Data());
 TString nameImageRoot = Form("%s_%s_%d.root",variableY.c_str(),variableX.c_str(),1);
 cResultDistro.SaveAs(nameImageRoot.Data());

 
 
 TCanvas cResultDistroMC("cResultDistroMC","cResultDistroMC",800,800);
 cResultDistroMC.Divide(2,2);
 
 //  cResultDistroMC.Divide(2,nMC);
//  for (int iMC = 0; iMC < nMC; iMC++) {
//   cResultDistroMC.cd(2*iMC+1);
//   HistoMC[iMC]->DrawClone("colz");
//   HistoDATA->DrawClone("BOXsame");
//   cResultDistroMC.cd(2*iMC+2);
//   HistoRatioMC[iMC]->DrawNormalized("");
//   HistoRatioDATA->DrawNormalized("E1same");  
//  }

 cResultDistroMC.cd(1);
 HistoMC_SUM->DrawClone("colz");
 HistoDATA->DrawClone("BOXsame");
 gPad->SetGrid();
 
 ///==== make fit ====
 
 cResultDistroMC.cd(3);
 
 TH1D* MChtemp_prof = smartGausProfileXSQRTN(HistoMC_SUM,2);  
 TGraphErrors MCgrH = buildGEfromH_Personalized(*MChtemp_prof);
 MCgrH.SetMarkerStyle(22);
 MCgrH.SetMarkerSize(0.7);
 MCgrH.SetMarkerColor(kRed);
 MCgrH.SetFillColor(kRed);
 MCgrH.SetFillStyle(3335);
 MCgrH.SetLineWidth(1);
 MCgrH.SetLineColor(kRed);
 MCgrH.GetXaxis()->SetTitle(variableX.c_str());
 MCgrH.GetYaxis()->SetTitle(variableY.c_str());
 
 funz->SetParameter(0,0);
 funz->SetParameter(1,1);
 MCgrH.Fit("funz","RMQ");
 
 std::cerr << " ================= " << std::endl;
 std::cerr << " ======= MC ====== " << std::endl;
 std::cerr << " Y = [0] + [1] * X " << std::endl;
 std::cerr << " [0] = " << funz->GetParameter(0) << " +/- " << funz->GetParError(0) << std::endl;
 std::cerr << " [1] = " << funz->GetParameter(1) << " +/- " << funz->GetParError(1) << std::endl;
 double coeffMC = funz->GetParameter(1);
 double errCoeffMC = funz->GetParError(1);
 
 MCgrH.Draw("APL");
 gPad->SetGrid();
 
 
 cResultDistroMC.cd(4);
 MCgrH.Draw("APL");
 grH.Draw("PLSAME");
 gPad->SetGrid();
 
 
 TString nameImageLog = Form("%s_%s_%d_MC.png",variableY.c_str(),variableX.c_str(),1);
 cResultDistroMC.SaveAs(nameImageLog.Data());
  
 
 std::cerr << " 1 - alpha = " << coeffDATA / coeffMC 
           << " +/- " << sqrt( (errCoeffDATA/coeffMC)*(errCoeffDATA/coeffMC) + (errCoeffMC*coeffDATA/coeffMC/coeffMC)*(errCoeffMC*coeffDATA/coeffMC/coeffMC) )
           << std::endl;


 std::cerr << " alpha = " << 1-coeffDATA / coeffMC 
	   << " +/- " << sqrt( (errCoeffDATA/coeffMC)*(errCoeffDATA/coeffMC) + (errCoeffMC*coeffDATA/coeffMC/coeffMC)*(errCoeffMC*coeffDATA/coeffMC/coeffMC) )
	   << std::endl;
   
   

//  TCanvas cResultDistro_1("cResultDistro_1","cResultDistro_1",800,800);
//  HistoRatioMC_SUM->Draw();
//  HistoRatioDATA->Draw("E1same");
//  tEle.DrawClone();
//  gPad->SetGrid();
//  gPad->SetLogy();
   
}
Example #3
0
void keys(TString sam="0", TString smooth = "100") {
  gSystem->Load("libHtml");
  gSystem->Load("libMinuit");
  gSystem->Load("libRooFitCore.so");
  gSystem->Load("libRooFitModels.so");
  using namespace RooFit;
  time_t start,end;
  time (&start);
  double dif;
  RooRealVar mmiss2("candM2","candM2",-4,12);
  RooRealVar pstarl("candPstarLep","candPstarLep",0.,2.4);

  RooArgSet myVars(mmiss2,pstarl);

  TString inputfile = "fitSamples/pdfSample"; inputfile += sam; inputfile += ".root";
  cout << "File = " << inputfile << endl;	
  TChain c("ntp1");
  c.Add(inputfile);
  RooDataSet  data("data","data",myVars);

  Int_t MCType,MCSubmode,MCDssmode,MCD,MCPions,MCCombB,MCCombDs,MCDoubleSL,
    candTruLep,candDstarType,isBzero,isSP6,MCTaumode,trueLepCharge;
  Float_t candM2,candPstarLep;
  Float_t truePPi0,trueDssPPi0,CTL,CTV,Chi,Q2,trueDmass;
  c.SetBranchAddress("MCType",&MCType);
  c.SetBranchAddress("MCSubmode",&MCSubmode);
  c.SetBranchAddress("MCDssmode",&MCDssmode);
  c.SetBranchAddress("MCD",&MCD);
  c.SetBranchAddress("MCPions",&MCPions);
  c.SetBranchAddress("MCCombB",&MCCombB);
  c.SetBranchAddress("MCCombDs",&MCCombDs);
  c.SetBranchAddress("MCDoubleSL",&MCDoubleSL);
  c.SetBranchAddress("candLepTru",&candTruLep);
  c.SetBranchAddress("candDstarType",&candDstarType);
  c.SetBranchAddress("isBzero",&isBzero);
  c.SetBranchAddress("isSP6",&isSP6);
  c.SetBranchAddress("MCTaumode",&MCTaumode);
  c.SetBranchAddress("truePPi0",&truePPi0);
  c.SetBranchAddress("trueDssPPi0",&trueDssPPi0);
  c.SetBranchAddress("trueCTL",&CTL);
  c.SetBranchAddress("trueCTV",&CTV);
  c.SetBranchAddress("trueChi",&Chi);
  c.SetBranchAddress("trueQ2",&Q2);
  c.SetBranchAddress("trueLepCharge",&trueLepCharge);
  c.SetBranchAddress("trueDmass",&trueDmass);
  c.SetBranchAddress("candM2",&candM2);
  c.SetBranchAddress("candPstarLep",&candPstarLep);
  TRandom3 rand; int ran;
  int transform = 1;
  TCanvas mm("mm","KEYS fits to mmiss-pstarl",1200,800);
  gStyle->SetPalette(1);
  double All = 8;
  TH2F rotated("rotated","Rotated m^{2}_{miss}-p*_{l}",200,-All,All,200,-All,All);
  TH2F ori("ori","Original m^{2}_{miss}-p*_{l}",200,-All,All,200,-All,All);
  //TH2F totcov("ori2","Original m^{2}_{miss}-p*_{l}",200,-All,All,200,-All,All);
  double r11, r12, Xmean, Ymean;
  double x[] = {-2,-1,1,2};
  double y[] = {-4,-2,2,4};
  if(transform ==1){
    c.Draw("candPstarLep:candM2>>cov(200,-4,12,200,0,2.4)","","contz");
    TH2F *totcov = (TH2F*)gDirectory->Get("cov");
    //for(int i=0;i<4;i++)totcov.Fill(x[i],y[i]);
    double xx = totcov->GetRMS(1); xx = xx*xx;
    double yy = totcov->GetRMS(2); yy = yy*yy;
    double xy = totcov->GetCovariance();
    Xmean = totcov->GetMean(1);
    Ymean = totcov->GetMean(2);
    double lambda = (-sqrt(xx*xx-2*xx*yy+4*xy*xy+yy*yy)+xx+yy)/2;
    double lambda2 = (sqrt(xx*xx-2*xx*yy+4*xy*xy+yy*yy)+xx+yy)/2;
    if(lambda2>lambda) lambda = lambda2;
    r11 = (lambda-yy)/xy;
    r12 = -1/sqrt(r11*r11+1);
    r11 = -r11/sqrt(r11*r11+1);
    if(r12*r11>0&&r12<0 || r12*r11<0&&r11<0){
      r12 = -r12;
      r11 = -r11;
    }
    cout<<"RMSx "<<xx<<", RMSy "<<yy<<", lambda "<<lambda<<" and covariance "<<xy<<endl;
  }
  double mmp, plp;
  double entries = c.GetEntries();
  //entries = 4;
  for (int evt = 0 ; evt < entries; evt ++) {
    ran = rand.Uniform(entries);
    //c.GetEvent(ran);
    c.GetEvent(evt);
    double Mx = candM2-Xmean, Py = candPstarLep-Ymean;
    mmp = r11*(Mx)+r12*(Py);
    plp = -r12*(Mx)+r11*(Py);
    ori.Fill(Mx,Py);
    rotated.Fill(mmp,plp);
    mmiss2.setVal(candM2);
    pstarl.setVal(candPstarLep);
//     if (MCType == 0)
//       totWeight.setVal(myWM->getCombWeight(MCCombB,MCCombDs,MCDoubleSL,candTruLep));
//     else
//       totWeight.setVal(myWM->getEventWeight(candType,candDstarType,MCType,MCSubmode,MCDssmode,MCD,MCPions,
// 					    isBzero,isSP6,MCTaumode,truePPi0,trueDmass,CTL,CTV,Chi,Q2,
// 					    trueLepCharge,candM2));
    data.add(RooArgSet(mmiss2,pstarl));
  }
  //data.setWeightVar(totWeight);
  ori.Draw("contz");
  mm.SaveAs("original.eps");
  rotated.Draw("contz");
  mm.SaveAs("rotated.eps");
  cout<<"("<<r11<<", "<<r12<<") and covariance "<<rotated.GetCovariance()<<endl;
  return;

  double smoo = smooth.Atof()/100.;
  Roo2DKeysPdf DPpdf("DPpdf","DPpdf",mmiss2,pstarl,data,"av",smoo);
  time (&end);dif = difftime (end,start);
  cout<<dif<<" seconds after finding the KEYS function"<<endl;
  time (&start);
  int ntotbin = 800;
  TH2F *h2 = new TH2F("h2","KEYS",ntotbin,-4,12,ntotbin,0,2.4);
  DPpdf.fillHistogram(h2,RooArgList(mmiss2,pstarl));
  TString hname = "AWG82/results/keys/root/hKeys"; hname += sam; hname += "_"; hname += smooth; hname += ".root";
  TFile* hfile = new TFile(hname,"RECREATE"); 
  h2->Write();
  hfile->Close();
  cout<<"KEYS histogram saved in "<<hname<<endl;
  RooDataHist* Rdh2 = new RooDataHist("Rdh2","KEYS",RooArgList(mmiss2,pstarl),h2);
  RooHistPdf* Rh2 = new RooHistPdf("Rh2","KEYS",RooArgList(mmiss2,pstarl),*Rdh2,2);
  time (&end);dif = difftime (end,start);
  cout<<dif<<" seconds after making histogram"<<endl;
  time (&start);

  Float_t xlow,xhigh;
  Int_t nbinx,nbiny,Sam = sam.Atoi();
  xlow = -4;
  xhigh = 12;
  nbinx = 80;
  nbiny = 80;
  if (Sam==0 || Sam==2 || Sam==10 || Sam==12 || Sam == 20 || Sam == 23 || Sam == 26 || Sam == 29) {
    xlow = -2; xhigh = 4;
    if (Sam > 12) {nbinx = 40; nbiny = 40;}
  }
  else if (Sam==1 || Sam==11) {
    xlow = -2; xhigh = 6;
  }
  if (Sam==6 || Sam==7 || Sam==16 || Sam==17) {
    nbinx = 40; nbiny = 40;
  }
  if (Sam==8 || Sam==18) {
    xhigh = 4; nbinx = 40; nbiny = 40;
  }
  if (Sam==9 || Sam==19) {
    nbinx = 40; nbiny = 40;
  }
  if (Sam==21 || Sam==22 || Sam==24 || Sam==25 || Sam==27 || Sam==28 || Sam==30 || Sam==31) {
    xhigh = 8; nbinx = 40; nbiny = 20;
  }
  if (Sam > 31) {
    nbinx = 40; nbiny = 20;
  }

  TString M2titles[] = {"0 < p*_{l} < 1 GeV","1 < p*_{l} < 1.4 GeV","1.4 < p*_{l} < 1.8 GeV",
		      "1.8 < p*_{l} < 2.4 GeV","0 < p*_{l} < 2.4 GeV"};
  TString Pltitles[] = {"-4 < m^{2}_{miss} < 1.5 GeV^{2}","1.5 < m^{2}_{miss} < 12 GeV^{2}",
			"-4 < m^{2}_{miss} < 12 GeV^{2}"};
  TString M2cuts[] = {"candPstarLep<1","candPstarLep>1&&candPstarLep<1.4",
		      "candPstarLep>1.4&&candPstarLep<1.8","candPstarLep>1.8&&candPstarLep<2.4", ""};
  TString Plcuts[] = {"candM2<1.5","candM2>=1.5",""};
  double limits[] = {0, 1, 1.4, 1.8, 2.4};
  int binlim[5];
  for(int i=0;i<5;i++) binlim[i] = limits[i]/2.4*ntotbin;

  TString psname = "AWG82/results/keys/eps/eps2Keys"; psname+=sam; psname+="_";
  psname += smooth; psname += ".ps";
  double tot = 0;
  mm.Print(psname+"[");
  TH1F *hm2[5], *m2[5], *hpl[3], *pl[3];
  TString M2names[5], Plnames[3];
  for(int i=0;i<5;i++){
    M2names[i] = "hm2_"; M2names[i] += i;
    hm2[i] = new TH1F(M2names[i],M2titles[i],ntotbin,-4,12); 
    if(i<3) {
      Plnames[i] = "hpl_"; Plnames[i] += i;
      hpl[i] = new TH1F(Plnames[i],Pltitles[i],ntotbin,0,2.4); 
    }
  }    
  for(int i=0;i<5;i++){
    TString hname = "m2"; hname += i;
    TString vari = "candM2>>"; vari+=hname; vari+="("; vari+= nbinx; vari+=",";vari+= xlow; 
    vari+=",";vari+= xhigh; vari+=")";
    c.Draw(vari,M2cuts[i]);
    m2[i] = (TH1F*)gDirectory->Get(hname);
    m2[i]->SetXTitle("m^{2}_{miss} [GeV^{2}]");
    m2[i]->SetTitle(M2titles[i]);
    m2[i]->Sumw2();
    m2[i]->SetMarkerStyle(20);
    m2[i]->SetMarkerSize(1);
    gStyle->SetOptStat(0);
    if(i<4){
      for(int j=1; j<ntotbin+1; j++){
	double binVal = 0;
	for(int binp = binlim[i]+1; binp < binlim[i+1]+1; binp++){
	  binVal += h2->GetBinContent(j,binp)*entries*ntotbin*(xhigh-xlow)/nbinx/16;	
	}
	hm2[i]->SetBinContent(j,binVal);
      }
    } 
    hm2[i]->SetLineColor(4);
    hm2[i]->SetLineWidth(2);
    if(i<4) hm2[4]->Add(hm2[i]);
  }
  int plbinlim[3] = {0,ntotbin*5.5/16,ntotbin};
  for(int i=0;i<3;i++){
    TString hname = "pl"; hname += i;
    TString vari = "candPstarLep>>"; vari+=hname; vari+="("; vari+= nbiny; vari+=",0,2.4)";
    c.Draw(vari,Plcuts[i]);
    pl[i] = (TH1F*)gDirectory->Get(hname);
    pl[i]->SetXTitle("p*_{l} [GeV]");
    pl[i]->SetTitle(Pltitles[i]);
    pl[i]->Sumw2();
    pl[i]->SetMarkerStyle(20);
    pl[i]->SetMarkerSize(1);
    gStyle->SetOptStat(0);
    if(i<2){
      for(int j=1; j<ntotbin+1; j++){
	double binVal = 0;
	for(int binp = plbinlim[i]+1; binp < plbinlim[i+1]+1; binp++){
	  binVal += h2->GetBinContent(binp,j)*entries*ntotbin/nbiny;	
	}
	hpl[i]->SetBinContent(j,binVal);
      }
    }
    hpl[i]->SetLineColor(4);
    hpl[i]->SetLineWidth(2);
    if(i<2) hpl[2]->Add(hpl[i]);
  }
  m2[4]->Draw("e1"); hm2[4]->Draw("c same"); mm.Print(psname);
  pl[2]->Draw("e1"); hpl[2]->Draw("c same"); mm.Print(psname);
  for(int i=0;i<4;i++){
    m2[i]->Draw("e1"); hm2[i]->Draw("c same"); mm.Print(psname);
  }
  for(int i=0;i<2;i++){
    pl[i]->Draw("e1"); hpl[i]->Draw("c same"); mm.Print(psname);
  }
  mm.Print(psname+"]");
  time (&end);dif = difftime (end,start);
  cout<<dif<<" seconds after plotting data. Written "<<psname<<endl;
  return; 

} 
Example #4
0
/// plots the beam profiles in (x1,x2) and (x,x') planes
void display_beamprofile(float s, string filename="data/LHCB1IR5_v6.500.tfs", char * ipname = "IP5", int side = 1, char * title ="", unsigned int NParticle=1000, const int crang_sign=-1, const bool save=false, char * outfilename="") {
	/// @param s : distance from IP [m]
	/// @param filename : optics source file
	/// @param ipname : string identifier for the IP position
	/// @param side : direction of propagation (forward 1, backward -1)
	/// @param title : for the graph
	/// @param NParticle : beam content
	/// @param crang_sign : direction for the (half) crossing angle at IP
	/// @param save : boolean
	/// @param outfilename: file to be written


// note : beam 1 forward  : side = 1  crang_sign =-1
// note : beam 1 backward : side = -1 crang_sign = 1
// note : beam 2 forward  : side = -1 crang_sign =-1
// note : beam 2 backward : side = 1  crang_sign = 1

	extern bool relative_energy;
	relative_energy = false;
	if(relative_energy) {
		cout << "You should be in absolute energy" << endl;
		return;
	}

        extern int kickers_on;
        kickers_on = 1;

	
	int max = (crang_sign>0)?100:-95;
	int min = (crang_sign<0)?-100:95;
	TH2F * hp  = new TH2F("Positions","",100,min,max,100,-2.5,2.5);
	TH2F * ha  = new TH2F("Angles","",100,-50,50,100,-50,50);
	TH2F * hax  = new TH2F("Phase_x","",100,min,max,100,-50,50);
	TH2F * hay  = new TH2F("Phase_y","",100,-2.5,2.5,100,-50,50);
	float draftx[NParticle], drafty[NParticle], drafttx[NParticle], draftty[NParticle];
//	float rmsx=0, rmsy=0, angle=0;
	TMultiGraph * profile = new TMultiGraph("prof","");

        H_BeamLine* beamline = new H_BeamLine(side,s+0.1);
        beamline->fill(filename,-1*side*crang_sign,ipname);
	beamline->offsetElements(120,0.097*crang_sign);

//	extern int kickers_on;
//	kickers_on = 1;

	for (unsigned int i=0; i<NParticle ; i++) {
		H_BeamParticle p1;
		p1.smearPos();
		p1.smearAng();
		p1.setPosition(p1.getX()-500.,p1.getY(),p1.getTX()+crang_sign*CRANG,p1.getTY(),0);
		p1.computePath(beamline);
		p1.propagate(beamline);
		p1.propagate(s);
		hp->Fill(p1.getX()/1000.,p1.getY()/1000.);
		ha->Fill(p1.getTX(),p1.getTY());
		hax->Fill(p1.getX()/1000.,p1.getTX());
		hay->Fill(p1.getY()/1000.,p1.getTY());
		draftx[i]=p1.getX()/1000.;
		drafty[i]=p1.getY()/1000.;
		drafttx[i]=p1.getTX();
		draftty[i]=p1.getTY();
		TGraph * path = p1.getPath(0,1);
		profile->Add(path);
	}

	TCanvas * can = new TCanvas;
	can->cd();
	hp->SetTitle(title);
	hp->Draw();	
	hp->GetXaxis()->SetTitle("x (mm)");
	hp->GetYaxis()->SetTitleOffset(1.2);
	hp->GetYaxis()->SetTitle("y (mm)");
	TEllipse * ellipse = new TEllipse(hp->GetMean(1),hp->GetMean(2),3*(hp->GetRMS(1)),3*(hp->GetRMS(2)));
	cout << "mean = " << hp->GetMean(1) << " " << hp->GetMean(2) << endl;
	ellipse->SetLineColor(kRed);
	ellipse->Draw();
	
	TCanvas * ca2 = new TCanvas;
	ca2->cd();
	profile->Draw("ACP");

	TCanvas *ca3 = new TCanvas;
	ca3->cd();
	ha->SetTitle(title);
	ha->Draw();
	ha->GetXaxis()->SetTitle("#theta_{x} (#murad)");
	ha->GetYaxis()->SetTitle("#theta_{y} (#murad)");
	TEllipse * ellips2 = new TEllipse(ha->GetMean(1),ha->GetMean(2),3*(ha->GetRMS(1)),3*(ha->GetRMS(2)));
	ellips2->SetLineColor(kRed);
	ellips2->Draw();

	TCanvas *ca4 = new TCanvas;
	ca4->cd();
	hax->SetTitle(title);
	hax->Draw();
	hax->SetStats(0);
	hax->GetXaxis()->SetTitle("x (mm)");
	hax->GetYaxis()->SetTitle("#theta_{x} (#murad)");
//	getEllipseParameters(draftx,drafttx,NParticle,rmsx,rmsy,angle);
//	ca4->cd();
//	cout << rmsx << " " << rmsy << " " << angle << endl;
//	TEllipse * ellips3 = new TEllipse(hp->GetMean(1),ha->GetMean(1),3*rmsx,3*rmsy);
//	ellips3->SetTheta(angle);
//	ellips3->SetLineColor(kRed);
//	ellips3->Draw();

	TCanvas *ca5 = new TCanvas;
	ca5->cd();
	hay->SetTitle(title);
	hay->Draw();
	hay->SetStats(0);
	hay->GetXaxis()->SetTitle("y (mm)");
	hay->GetYaxis()->SetTitle("#theta_{y} (#murad)");
//	getEllipseParameters(drafty,draftty,NParticle,rmsx,rmsy,angle);
//	ca5->cd();
//	cout << rmsx << " " << rmsy << " " << angle << endl;
//	TEllipse * ellips4 = new TEllipse(hp->GetMean(2),ha->GetMean(2),3*rmsx,3*rmsy);
//	ellips4->SetTheta(angle);
//	ellips4->SetLineColor(kRed);
//	ellips4->Draw();

	if(save) {
		char filetitle_pos[50], filetitle_ang[50], filetitle_phasex[50], filetitle_phasey[50];
		sprintf(filetitle_pos,"%s_pos.eps",outfilename);
		cout << filetitle_pos << endl;
		can->Print(filetitle_pos,"eps");
		sprintf(filetitle_ang,"%s_ang.eps",outfilename);
		cout << filetitle_ang << endl;
		ca3->Print(filetitle_ang,"eps");
		sprintf(filetitle_phasex,"%s_px.eps",outfilename);
		cout << filetitle_phasex << endl;
		ca4->Print(filetitle_phasex,"eps");
		sprintf(filetitle_phasey,"%s_py.eps",outfilename);
		cout << filetitle_phasey << endl;
		ca5->Print(filetitle_phasey,"eps");
		delete can;
		delete ca2;
		delete ca3;
		delete ca4;
		delete ca5;
		delete hp;
		delete ha;
		delete hax;
		delete hay;
		delete profile;
		delete beamline;
		delete ellipse;
		delete ellips2;
//		delete ellips3;
//		delete ellips4;
	}

}
int main() {
    Int_t nbins = 800, j;
    char name[20], title[100];
    TStopwatch t;
    TFile f1("/home/marko/Desktop/H4Analysis/ntuples/analysis_3898.root"); //Run 3898 ntuple
    TFile f2("/home/marko/Desktop/H4Analysis/ntuples/analysis_3902.root"); //Run 3902 ntuple
    TFile f3("/home/marko/Desktop/H4Analysis/ntuples/analysis_3905.root"); //Run 3905 ntuple
    TTree* h4_3898 = (TTree*) f1.Get("h4");
    TTree* h4_3902 = (TTree*) f2.Get("h4");
    TTree* h4_3905 = (TTree*) f3.Get("h4");
    TFile outputfile("AllPedestalEventFFTs.root", "recreate"); //individual event noise spectra
    Int_t nentries1 = h4_3898->GetEntries("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");
    Int_t nentries2 = h4_3902->GetEntries("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");
    Int_t nentries3 = h4_3905->GetEntries("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");
    Int_t entriestotal = nentries1 + nentries2 + nentries3;
    Int_t nspill = 15; //how many spills will be analyzed (not all spills necessarily have data)
    TH1F *HistoEvent[entriestotal];
    for (Int_t z=0;z<entriestotal;z++) {
        sprintf(name,"HistoEvent%d",z);
        sprintf(title,"Event%d Histo", z);
        HistoEvent[z] = new TH1F(name,title,nbins, -0.1, 159.9);
    }
    TH1F *NewHistoEvent[entriestotal];
    for (Int_t z=0;z<entriestotal;z++) {
        sprintf(name,"NewHistoEvent%d",z);
        sprintf(title,"Event%d Histo", z);
        NewHistoEvent[z] = new TH1F(name,title,nbins, -0.1, 159.9);
    }
    TH1F *NewHistoEventFFT[entriestotal];
    for (Int_t z=0;z<entriestotal;z++) {
        sprintf(name,"NewHistoEventFFT%d",z);
        sprintf(title,"Event%d Histo", z);
        NewHistoEventFFT[z] = new TH1F(name,title,nbins, 0, 5);
    }
    TH1F* NormNoiseFFT = new TH1F ("NormNoiseFFT", "Normalized Noise FFT", nbins, 0, 5);
    Int_t count = 0;
    t.Start();
    for (Int_t spill=0;spill<nspill;spill++) {
        cout << "Run 3898 Spill " << spill << endl;
        h4_3898->SetEntryList(0);
        TString listcut = "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 && spill==";
        listcut += spill;
        TString spillcut = "spill==";
        spillcut += spill;
        h4_3898->Draw(">>myList", listcut, "entrylist");
        TEntryList *myList = (TEntryList*) gDirectory->Get("myList");
        h4_3898->SetEntryList(myList);
        Int_t entriesperspill = myList->GetN();
        h4_3898->Draw("event", spillcut, "goff");
        Double_t *vTemp = h4_3898->GetV1();
        Double_t *vEvent = new Double_t[entriesperspill];
        for (int iEntry = 0; iEntry<entriesperspill; iEntry++){
            vEvent[iEntry] = vTemp[iEntry];
        }
        Double_t mean. rms;
        TString plot, cut;
        for (j=0;j<entriesperspill;j++) {
            TString histoname = "Run3898TempHisto_";
            histoname += spill;
            histoname += "_";
            histoname += j;
            TH2F* TempHisto = new TH2F (histoname, "Temp Histo", nbins, -0.1, 159.9, 1000, -15, 15);
            plot = "WF_val:WF_time>>";
            plot += histoname;
            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 && spill==";
            cut += spill;
            cut += " && event==";
            cut += vEvent[j];
            h4_3898->Draw(plot, cut, "goff");
            TempHisto = (TH2F*) gDirectory->Get(histoname);
            if (TempHisto->GetMaximum() == 0) {
                continue;
            }
            HistoEvent[count] = transform2Dto1D(TempHisto);
            mean = TempHisto->GetMean(2);
            rms = TempHisto->GetRMS(2);
            for (Int_t q=0;q<nbins;q++) {
                NewHistoEvent[count]->SetBinContent(q+1, HistoEvent[count]->GetBinContent(q+1)-mean); //centering the pedestal at <y> = 0
            }
            NewHistoEvent[count]->Scale(1/rms); //dividing by RMS of pedestal event, later undone when the filter is applied to the wave pulses
            NewHistoEvent[count]->FFT(NewHistoEventFFT[count], "MAG"); //noise power spectrum (frequency domain)
            NormNoiseFFT->Add(NormNoiseFFT, NewHistoEventFFT[count]);
            NewHistoEventFFT[count]->Write();
            cout << "Event " << count+1 << " out of " << entriestotal << endl;
            count += 1;
            delete TempHisto;
        }
    }
    for (Int_t spill=0;spill<nspill;spill++) {
        cout << "Run 3902 Spill " << spill << endl;
        h4_3902->SetEntryList(0);
        TString listcut = "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 && spill==";
        listcut += spill;
        TString spillcut = "spill==";
        spillcut += spill;
        h4_3902->Draw(">>myList", listcut, "entrylist");
        TEntryList *myList = (TEntryList*) gDirectory->Get("myList");
        h4_3902->SetEntryList(myList);
        Int_t entriesperspill = myList->GetN();
        h4_3902->Draw("event", spillcut, "goff");
        Double_t *vTemp = h4_3902->GetV1();
        Double_t *vEvent = new Double_t[entriesperspill];
        for (int iEntry = 0; iEntry<entriesperspill; iEntry++){
            vEvent[iEntry] = vTemp[iEntry];
        }
        Double_t mean, rms;
        TString plot, cut;
        for (j=0;j<entriesperspill;j++) {
            TString histoname = "Run3902TempHisto_";
            histoname += spill;
            histoname += "_";
            histoname += j;
            TH2F* TempHisto = new TH2F (histoname, "Temp Histo", nbins, -0.1, 159.9, 1000, -15, 15);
            plot = "WF_val:WF_time>>";
            plot += histoname;
            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 && spill==";
            cut += spill;
            cut += " && event==";
            cut += vEvent[j];
            h4_3902->Draw(plot, cut, "goff");
            TempHisto = (TH2F*) gDirectory->Get(histoname);
            if (TempHisto->GetMaximum() == 0) {
                continue;
            }
            HistoEvent[count] = transform2Dto1D(TempHisto);
            mean = TempHisto->GetMean(2);
            rms = TempHisto->GetRMS(2);
            for (Int_t q=0;q<nbins;q++) {
                NewHistoEvent[count]->SetBinContent(q+1, HistoEvent[count]->GetBinContent(q+1)-mean);
            }
            NewHistoEvent[count]->Scale(1/rms);
            NewHistoEvent[count]->FFT(NewHistoEventFFT[count], "MAG");
            NormNoiseFFT->Add(NormNoiseFFT, NewHistoEventFFT[count]);
            NewHistoEventFFT[count]->Write();
            cout << "Event " << count+1 << " out of " << entriestotal << endl;
            count += 1;
            delete TempHisto;
        }
    }
    for (Int_t spill=1;spill<2;spill++) {
        cout << "Run 3905 Spill " << spill << endl;
        h4_3905->SetEntryList(0);
        TString listcut = "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 && spill==";
        listcut += spill;
        TString spillcut = "spill==";
        spillcut += spill;
        h4_3905->Draw(">>myList", listcut, "entrylist");
        TEntryList *myList = (TEntryList*) gDirectory->Get("myList");
        h4_3905->SetEntryList(myList);
        Int_t entriesperspill = myList->GetN();
        h4_3905->Draw("event", spillcut, "goff");
        Double_t *vTemp = h4_3905->GetV1();
        Double_t *vEvent = new Double_t[entriesperspill];
        for (int iEntry = 0; iEntry<entriesperspill; iEntry++){
            vEvent[iEntry] = vTemp[iEntry];
        }
        Double_t mean, rms;
        TString plot, cut;
        for (j=0;j<entriesperspill;j++) {
            TString histoname = "Run3905TempHisto_";
            histoname += spill;
            histoname += "_";
            histoname += j;
            TH2F* TempHisto = new TH2F (histoname, "Temp Histo", nbins, -0.1, 159.9, 1000, -15, 15);
            plot = "WF_val:WF_time>>";
            plot += histoname;
            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 && spill==";
            cut += spill;
            cut += " && event==";
            cut += vEvent[j];
            h4_3905->Draw(plot, cut, "goff");
            TempHisto = (TH2F*) gDirectory->Get(histoname);
            if (TempHisto->GetMaximum() == 0) {
                continue;
            }
            HistoEvent[count] = transform2Dto1D(TempHisto);
            mean = TempHisto->GetMean(2);
            rms = TempHisto->GetRMS(2);
            for (Int_t q=0;q<nbins;q++) {
                NewHistoEvent[count]->SetBinContent(q+1, HistoEvent[count]->GetBinContent(q+1)-mean);
            }
            NewHistoEvent[count]->Scale(1/rms);
            NewHistoEvent[count]->FFT(NewHistoEventFFT[count], "MAG");
            NormNoiseFFT->Add(NormNoiseFFT, NewHistoEventFFT[count]);
            HistoEvent[count]->Write();
            NewHistoEventFFT[count]->Write();
            cout << "Event " << count+1 << " out of " << entriestotal << endl;
            count += 1;
            delete TempHisto;
        }
    }
    TFile out("AllNormalizedNoiseFFT.root", "recreate");
    NormNoiseFFT->Scale(1./count);
    NormNoiseFFT->Write();
    t.Stop();
    t.Print();
}