示例#1
0
void draw() {

  gStyle->SetOptStat(0000);

  TGraphErrors* gr = new TGraphErrors("papel_um.txt", "%lg %lg %lg %lg");
  gr->Draw("A");

  gr->GetXaxis()->SetTitle("Diametro (mm)");
  gr->GetYaxis()->SetTitle("Massa (u.m.)");
  gr->SetTitle("Dimensao Fractal - Papel");
  gr->SetMarkerStyle(20);
  gr->SetMarkerSize(gr->GetMarkerSize()/2.);

  TCanvas* c1 = new TCanvas();
  gr->Draw("AP");
  c1->Print("gr1.png");


  TGraphErrors* grlog = new TGraphErrors();
  for (int i=0; i<gr->GetN(); i++) {
    grlog->SetPoint(i, TMath::Log(gr->GetX()[i]), TMath::Log(gr->GetY()[i]));
    grlog->SetPointError(i, gr->GetEX()[i]/gr->GetX()[i], 0.0);
  }
  grlog->Draw("A");
  grlog->GetXaxis()->SetTitle("Logaritmo do diametro (diametro em mm)");
  grlog->GetYaxis()->SetTitle("Logaritmo da massa (massa em unidade arbitraria)");
  grlog->SetTitle("Dimensao Fractal - Papel");
  grlog->SetMarkerStyle(20);
  //  grlog->SetMarkerSize(gr->GetMarkerSize()/2.);
  grlog->Fit("pol1");
  TCanvas* c2 = new TCanvas();
  grlog->Draw("AP");
  c2->Print("gr2.png");

}
示例#2
0
void DrawClus(bool Flag_err,TTree* tree,Double_t *errx,char* varToPlot, char* cond, Int_t kColor, Int_t kMarker, char* Title,char* xTitle,char* yTitle, TLegend *leg, char* cLeg,Double_t downlim,Double_t uplim){
  TGraphErrors* g;
  
  tree->Draw(varToPlot, cond,"goff");
  cout << tree->GetSelectedRows() << endl;
  if(tree->GetSelectedRows()){
    if(Flag_err)
      g=new TGraphErrors(tree->GetSelectedRows(),tree->GetV1(),tree->GetV2(),errx,tree->GetV3());
    else
      g=new TGraphErrors(tree->GetSelectedRows(),tree->GetV1(),tree->GetV2(),errx,errx);
    g->SetMarkerStyle(kMarker);
    g->SetMarkerSize(0.9);
    g->SetMarkerColor(kColor);
    g->SetTitle(Title);
    g->GetXaxis()->SetTitle(xTitle);
    g->GetXaxis()->CenterTitle();
    g->GetYaxis()->SetTitle(yTitle);
    g->GetYaxis()->CenterTitle();
    g->GetYaxis()->SetRangeUser(downlim,uplim);
    g->Draw("Ap");
    leg->AddEntry(g, cLeg,"p");
  }else{
    cout << "NO rows selected for leave " << varToPlot << endl;
  }
}
//______________________________________________________________________________
// Construct a graph from vectors and y error vector
TGraphErrors *LoadGraphFromVectorsWithError(vector<double> xVector, vector<double> yVector, vector<double> yErrorVector, string xTitle, string yTitle)
{
	int n = xVector.size();

	if ((xVector.size() == yVector.size()) &&
		(yVector.size() == yErrorVector.size()))
	{
		//Create a graph
		TGraphErrors *gr = new TGraphErrors(n, &xVector[0], &yVector[0], 0, &yErrorVector[0]);
		gr->SetTitle("");
		gr->SetMarkerStyle(20);
		gr->SetMarkerSize(1.2);
		gr->SetLineWidth(2);
		gr->GetXaxis()->SetTitle(xTitle.c_str());
		gr->GetXaxis()->CenterTitle();
		gr->GetYaxis()->SetTitle(yTitle.c_str());
		gr->GetYaxis()->CenterTitle();
		return gr;
		delete gr;
	}
	else
	{
		TGraphErrors *gr0 = new TGraphErrors();
		return gr0;
		delete gr0;
	}
}
void Draw_CMS_Y1S_RaaVsRap(TLegend *lgd)
{
  const int nbinsRap=6;

  Double_t RapCMS[nbinsRap]={0.2,0.6,1.0,1.4,1.8,2.2};
  Double_t ErrRapCMS[nbinsRap]={0};
  
  Double_t RaaRapCMS[nbinsRap] = {0.402,0.377,0.452,0.461,0.466,0.35}; 
  Double_t RaaRapStatErrCMS[nbinsRap] = {0.025,0.025,0.030,0.034,0.039,0.053};
  Double_t RaaRapSystErrCMS[nbinsRap] = {0.0404,0.038,0.046,0.0466,0.0484,0.0373};
  
  TGraphErrors *grRaaRapCMS = new TGraphErrors(nbinsRap, RapCMS, RaaRapCMS, ErrRapCMS, RaaRapStatErrCMS);  
  grRaaRapCMS->SetMarkerStyle(20);
  grRaaRapCMS->SetMarkerColor(4);
  grRaaRapCMS->GetYaxis()->SetRangeUser(0,3.0);
  grRaaRapCMS->GetXaxis()->SetTitle("p_{T}(GeV/c)");
  grRaaRapCMS->GetYaxis()->SetTitle("R_{AA}");
   
  TAxis *Xaxis2 = grRaaRapCMS->GetXaxis();
  Xaxis2->SetLimits(0.,2.4);
  
  grRaaRapCMS->Draw("AP");
  
  TLine *lh4 = new TLine(0.0,1.0,20.0,1.0);
  lh4->SetLineColor(1);
  lh4->SetLineStyle(1);
  lh4->SetLineWidth(2);
  lh4->Draw("same");


  TLatex *tb= new TLatex;
  tb->SetNDC(); 
  tb->SetTextAlign(12);
  tb->SetTextColor(1);
  tb->SetTextSize(0.040);
  //tb->DrawLatex(0.55,0.22,"PbPb #sqrt{s_{NN}} = 2.76 TeV");
  //tb->DrawLatex(0.55,0.16,"#varUpsilon #rightarrow #mu^{+} #mu^{-}, p_{T}^{#varUpsilon} > 0.0 GeV/c");  
  
  TBox *RaaRapCMSSys[nbinsRap];
  for(int j=0;j<nbinsRap;j++){
    RaaRapCMSSys[j] = new TBox(RapCMS[j]-0.1,  RaaRapCMS[j]-RaaRapSystErrCMS[j], RapCMS[j]+0.1,  RaaRapCMS[j]+RaaRapSystErrCMS[j]);
  }
  
  for(int j=0;j<nbinsRap;j++){
    RaaRapCMSSys[j]->SetFillStyle(0000);
    RaaRapCMSSys[j]->SetLineColor(4);
    RaaRapCMSSys[j]->Draw("same"); 
  }
    
  TBox *CMSGlobalSysRap;
  CMSGlobalSysRap = new TBox(18-0.2, 1 - 0.083, 18+0.2, 1 + 0.083);
  CMSGlobalSysRap->SetFillStyle(3001);
  CMSGlobalSysRap->SetLineColor(4);
  CMSGlobalSysRap->SetFillColor(4);
  //CMSGlobalSysRap->Draw("same"); 
    
  lgd->AddEntry(grRaaRapCMS,"CMS Data", "P");  

  }
示例#5
0
void Draw_ALICEFor_JPsi_RaaVsNpart(TLegend *lgd)
{
  int nbinsALICE=9;
  Double_t NPartALICE[10]={357,262,187,128,86,53,30,16,8};
  Double_t ErrNPartALICE[10]={0};
  Double_t RaaALICE[10] = {0.47,0.48,0.51,0.51,0.52,0.61,0.70,0.74,0.94}; 
  Double_t SystErrALICE[10] = {0.03,0.02,0.02,0.02,0.03,0.05,0.06,0.09,0.1};
  
  TGraphErrors *grRaaALICE = new TGraphErrors(nbinsALICE, NPartALICE, RaaALICE, ErrNPartALICE, SystErrALICE);  
  grRaaALICE->SetMarkerStyle(20);
  grRaaALICE->SetMarkerColor(4);
  grRaaALICE->GetYaxis()->SetRangeUser(0,1.7);
  
  TAxis *Xaxis2 = grRaaALICE->GetXaxis();
  Xaxis2->SetLimits(0.,430.0);
  
  grRaaALICE->GetXaxis()->SetTitle("N_{Part}");
  grRaaALICE->GetYaxis()->SetTitle("R_{AA}");

  grRaaALICE->Draw("AP");
 
  TLine *lh3 = new TLine(0.0,1.0,420,1.0);
  lh3->SetLineColor(1);
  lh3->SetLineStyle(1);
  lh3->SetLineWidth(1.5);
  lh3->Draw("same");
 
  //TLatex *tb= new TLatex;
  //tb->SetNDC(); 
  //tb->SetTextAlign(12);
  //tb->SetTextColor(1);
  //tb->SetTextSize(0.040);
  //tb->DrawLatex(0.22,0.22,"PbPb #sqrt{s_{NN}} = 2.76 TeV");
  //tb->DrawLatex(0.22,0.16,"J/#psi #rightarrow #mu^{+} #mu^{-}, p_{T}^{J/#psi} > 0.0 GeV/c");  
   
  
  TBox *RaaJPsiALICESys[12];
  for(int j=0;j<9;j++){
    RaaJPsiALICESys[j] = new TBox(NPartALICE[j]-3,  RaaALICE[j]-SystErrALICE[j], NPartALICE[j]+3, RaaALICE[j]+SystErrALICE[j]);
  }
  
  for(int j=0;j<9;j++){
    RaaJPsiALICESys[j]->SetFillStyle(0000);
    RaaJPsiALICESys[j]->SetLineColor(4);
    RaaJPsiALICESys[j]->Draw("same"); 
  }
  
  TBox *ALICEGlobalSysJPsi;
  ALICEGlobalSysJPsi = new TBox(400-5, 1 - 0.14, 400+5, 1 + 0.14);
  ALICEGlobalSysJPsi->SetFillStyle(3001);
  ALICEGlobalSysJPsi->SetLineColor(4);
  ALICEGlobalSysJPsi->SetFillColor(4);
  ALICEGlobalSysJPsi->Draw("same"); 

  Draw_ALICEMid_JPsi_RaaVsNpart(lgd);

  lgd->AddEntry(grRaaALICE,"ALICE Data p_{T}^{J/#psi} > 0.0 GeV/c, 2.5 #leq y^{J/#psi} #leq 4.0","P");

}
示例#6
0
void Draw_ALICEMid_JPsi_RaaVsNpart(TLegend *lgd)
{
  //ALICE MID rapidity
  int nbinsALICEMid=3;
  Double_t NPartALICEMid[3]={357,193,46};
  Double_t ErrNPartALICEMid[3]={0};
  Double_t RaaALICEMid[3] = {0.82,0.65,0.73}; 
  Double_t SystErrALICEMid[3] = {0.15,0.10,0.16};
  
  TGraphErrors *grRaaALICEMid = new TGraphErrors(nbinsALICEMid, NPartALICEMid, RaaALICEMid, ErrNPartALICEMid, SystErrALICEMid);  
  grRaaALICEMid->SetMarkerStyle(20);
  grRaaALICEMid->SetMarkerColor(2);
  //grRaaALICEMid->SetLineColor(2);
  grRaaALICEMid->GetYaxis()->SetRangeUser(0,1.5);
  
  TAxis *Xaxis = grRaaALICEMid->GetXaxis();
  Xaxis->SetLimits(0.,430.0);
  grRaaALICEMid->GetXaxis()->SetTitle("N_{Part}");
  grRaaALICEMid->GetYaxis()->SetTitle("R_{AA}");
  
  grRaaALICEMid->Draw("Psame");
  
  //TLatex *tb= new TLatex;
  //tb->SetNDC(); 
  //tb->SetTextAlign(12);
  //tb->SetTextColor(1);
  //tb->SetTextSize(0.040);
  //tb->DrawLatex(0.55,0.90,"PbPb #sqrt{s_{NN}} = 2.76 TeV");
  //tb->DrawLatex(0.22,0.16,"J/#psi #rightarrow #mu^{+} #mu^{-}, p_{T}^{J/#psi} > 0.0 GeV/c");  
  //tb->DrawLatex(0.55,0.85,"p_{T}^{J/#psi} > 0.0 GeV/c");  
  
  TLine *lh3 = new TLine(0.0,1.0,420,1.0);
  lh3->SetLineColor(1);
  lh3->SetLineStyle(1);
  lh3->SetLineWidth(1.5);
  lh3->Draw("same");
    
  TBox *RaaJPsiALICEMidSys[12];
  for(int j=0;j<3;j++){
    RaaJPsiALICEMidSys[j] = new TBox(NPartALICEMid[j]-3,  RaaALICEMid[j]-SystErrALICEMid[j], NPartALICEMid[j]+3, RaaALICEMid[j]+SystErrALICEMid[j]);
  }
  
  for(int j=0;j<3;j++){
    RaaJPsiALICEMidSys[j]->SetFillStyle(0000);
    RaaJPsiALICEMidSys[j]->SetLineColor(2);
    RaaJPsiALICEMidSys[j]->Draw("same"); 
  }
  
  TBox *ALICEMidGlobalSysJPsi;
  ALICEMidGlobalSysJPsi = new TBox(385-5, 1 - 0.26, 385+5, 1 + 0.26);
  
  ALICEMidGlobalSysJPsi->SetFillStyle(3001);
  ALICEMidGlobalSysJPsi->SetLineColor(2);
  ALICEMidGlobalSysJPsi->SetFillColor(2);
  ALICEMidGlobalSysJPsi->Draw("same"); 

  lgd->AddEntry(grRaaALICEMid,"ALICE Data p_{T}^{J/#psi} > 0.0 GeV/c, |y^{J/#psi}| #leq 1.0","P");
  
}
示例#7
0
void Draw_CMS_JPsi_RaaVsRap(TLegend *lgd)
{
  //=============== CMS Raa Vs Rap Data ===============================================================//
  //AvpT 10.92,9.65,8.92
  int nbinsRapCMS=3;
  Double_t RapCMSD[3]={0.6,1.4,2.0};
  Double_t ErrRapCMS[3]={0.6,0.2,0.4};
  Double_t RaaRapCMS[3] = {0.31,0.33,0.36}; 
  Double_t RaaRapStatErrCMS[3] = {0.02,0.03,0.03};
  Double_t RaaRapSystErrCMS[3] = {0.03,0.04,0.04};

  TGraphErrors *grRaaRapCMS = new TGraphErrors(nbinsRapCMS, RapCMSD, RaaRapCMS, ErrRapCMS, RaaRapStatErrCMS);  
  grRaaRapCMS->SetMarkerStyle(20);
  grRaaRapCMS->SetMarkerColor(2);
  grRaaRapCMS->GetYaxis()->SetRangeUser(0,1.5);
  grRaaRapCMS->GetXaxis()->SetTitle("|y|");
  grRaaRapCMS->GetYaxis()->SetTitle("R_{AA}");
  
  TAxis *XaxisgrRaaRapCMS = grRaaRapCMS->GetXaxis();
  XaxisgrRaaRapCMS->SetLimits(0.0,2.4);
  
  grRaaRapCMS->Draw("AP"); 

  TLine *lh_grRaaRapCMS = new TLine(0.0,1.0,2.4,1.0);
  lh_grRaaRapCMS->SetLineColor(1);
  lh_grRaaRapCMS->SetLineStyle(1);
  lh_grRaaRapCMS->SetLineWidth(1.5);
  lh_grRaaRapCMS->Draw("same");

  TLatex *tb= new TLatex;
  tb->SetNDC(); 
  tb->SetTextAlign(12);
  tb->SetTextColor(1);
  tb->SetTextSize(0.040);
  tb->DrawLatex(0.20,0.20,"Pb+Pb #sqrt{s_{NN}} = 2.76 TeV");
  tb->DrawLatex(0.20,0.15,"J/#psi #rightarrow #mu^{+} #mu^{-}, p_{T}^{J/#psi} > 6.5 GeV/c");  
  
  TBox *RaaRapJPsiCMSSys[4];
  for(int j=0;j<3;j++){
    RaaRapJPsiCMSSys[j] = new TBox(RapCMSD[j]-0.05,  RaaRapCMS[j]-RaaRapSystErrCMS[j], RapCMSD[j]+0.05,  RaaRapCMS[j]+RaaRapSystErrCMS[j]);
  }
  
  for(int j=0;j<3;j++){
    RaaRapJPsiCMSSys[j]->SetFillStyle(0000);
    RaaRapJPsiCMSSys[j]->SetLineColor(2);
    RaaRapJPsiCMSSys[j]->Draw("same"); 
  }
  
  TBox *CMSGlobalSysJPsiRap;
  CMSGlobalSysJPsiRap = new TBox(0.2-0.05, 1 - 0.05, 0.2+0.05, 1 + 0.05);
  CMSGlobalSysJPsiRap->SetFillStyle(3001);
  CMSGlobalSysJPsiRap->SetLineColor(2);
  CMSGlobalSysJPsiRap->SetFillColor(2);
  CMSGlobalSysJPsiRap->Draw("same"); 


  lgd->AddEntry(grRaaRapCMS,"CMS Data", "P");
}
示例#8
0
void plot_mc(string name="g", double q2=1.9, Int_t n=0)
{
//    SetAtlasStyle();
    TGraphErrors *p;

    TString nn;
    nn.Form("ave_%s_vs_x_for_Q2=%g",name.c_str(),q2);
    gDirectory->GetObject(nn,p);

//    p->Print();

    Double_t ratsize = 0.0;

    TCanvas *c = new TCanvas("PDF","pdf",600,600);
    TPad *pad1 = new TPad("pad1","pad1",0.,ratsize,1.,1.);
    pad1->SetLogx();
    pad1->Draw();
    pad1->cd();
    p->GetXaxis()->Set(101,0.0001,1.);
    p->SetFillColor(kRed-2);
    p->SetFillStyle(3001);
    p->SetLineWidth(1);
    p->SetLineColor(kRed);
    p->GetYaxis()->SetTitle(name.c_str());

    p->GetYaxis()->SetTitleSize(0.06);
    p->GetYaxis()->SetTitleOffset(1.);
    p->GetXaxis()->Set(101,0.0001,1.);
    p->Draw("ALE3");

    Double_t av = 0;
    Double_t av2 = 0;

    for (Int_t i = 1; i<n+1 ; i++) {
        nn.Form("%s_vs_x_for_Q^{2}=%g_%i",name.c_str(),q2,i);
        TGraph *pp = NULL;
        gDirectory->GetObject(nn,pp);
        if (pp != NULL) {
            pp->SetLineColor(kGreen);
            pp->Draw("L");

            av  += pp->GetY()[0];
            av2 += pp->GetY()[0]*pp->GetY()[0];
            cout << i << " "<<pp->GetY()[0] << endl;


        }
    }

    av  /= n;
    av2 = sqrt(av2/n - av*av);
//    cout << n << " "<<av << " "<< av2<<endl;


    p->Draw("E3C");


}
示例#9
0
TGraphErrors g(TTree *tree, TString alphaName, TString constTermName){
  Double_t alpha, constTerm;
  alphaName.ReplaceAll("-","_");
  constTermName.ReplaceAll("-","_");

  tree->SetBranchAddress(alphaName,&alpha);
  tree->SetBranchAddress(constTermName,&constTerm);

  //Long64_t nEntries=genTree->GetEntries();

  TGraphErrors graph;
  Int_t iPoint=0;

  tree->GetEntry(0);
  std::cout << alpha << "\t" << constTerm << std::endl;
  Double_t alpha2=alpha*alpha;
  Double_t const2=constTerm*constTerm;
  for(Double_t energy=20; energy<150; energy+=10){
    Double_t addSmearing = (sqrt(alpha2/energy+const2));
    
    graph.SetPoint(iPoint, energy, addSmearing);
    graph.SetPointError(iPoint,0, 0);
    iPoint++;
  }

  graph.Set(iPoint);
  tree->ResetBranchAddresses();
  graph.Draw("A L");
  graph.SetFillColor(kBlue);
  graph.SetLineColor(kYellow);
  graph.GetXaxis()->SetTitle("Energy [GeV]");
  graph.GetYaxis()->SetTitle("Additional smearing [%]");
  return graph;
}
示例#10
0
TGraphErrors g(TTree *genTree, TString constTermName=""){
  Double_t alpha, constTerm;
  genTree->SetBranchAddress("alpha",&alpha);
  genTree->SetBranchAddress("constTerm",&constTerm);

  Long64_t nEntries=genTree->GetEntries();

  TH1F h("smearingHist","",10000,0,0.1);
  TGraphErrors graph;
  Int_t iPoint=0;
  for(Double_t energy=20; energy<150; energy+=10){
    h.Reset();
    for(Long64_t jentry=0; jentry<nEntries; jentry++){
      genTree->GetEntry(jentry);
      h.Fill(sqrt(alpha*alpha/energy+constTerm*constTerm));
    }
    graph.SetPoint(iPoint, energy, h.GetMean());
    graph.SetPointError(iPoint,0, h.GetRMS());
    iPoint++;
  }
  h.SetTitle(constTermName);
  h.SaveAs("tmp/h-"+constTermName+".root");
  graph.Set(iPoint);
  genTree->ResetBranchAddresses();
  graph.Draw("A L3");
  graph.SetFillColor(kBlue);
  graph.SetLineColor(kYellow);
  graph.GetXaxis()->SetTitle("Energy [GeV]");
  graph.GetYaxis()->SetTitle("Additional smearing [%]");
  return graph;
}
示例#11
0
void DrawFunction(TCanvas *c,char* varToPlot, char* cond, Int_t kColor, char* Title, TLegend *leg, char* cLeg){
  c->cd();
  // TRACE
  TGraphErrors *g;
  TIFTree->Draw(varToPlot,cond,"goff");
  
  Int_t nSel=TIFTree->GetSelectedRows();
  if ( nSel ) {
    
    Double_t *ErrX= new Double_t[nSel];
    for ( Int_t i=0; i<nSel; i++) ErrX[i]=0;
    
    g = new TGraphErrors(TIFTree->GetSelectedRows(), TIFTree->GetV1(),  TIFTree->GetV2(), ErrX, TIFTree->GetV3());
    
    g->SetMarkerStyle(21);
    g->SetMarkerSize(0.5);
    g->SetMarkerColor(kColor);
    g->SetLineColor(kColor);
    g->Draw("Ap"); //draw graph in current pad
    
    g->SetTitle(Title);
    g->GetXaxis()->SetTitle("run");
    g->GetYaxis()->SetTitle(Title);
    //    g->GetYaxis()->SetRangeUser(40., 100.);
    
    leg->AddEntry(g, cLeg);
   delete[] ErrX;
  }
  else {
    cout << "NO rows selected " << endl;
  }

}
示例#12
0
//______________________________________________________________________________
TGraphErrors *GraphRatio(TGraphErrors *g1,TGraphErrors *g2)
{
  Int_t n = g1->GetN();
  if (n != g2->GetN()) {
    Printf("!!!!!!!!!!!!!!!!");
    return 0;
  }

  TGraphErrors *g = new TGraphErrors(n);
  g->SetMarkerStyle(20);
  g->GetXaxis()->SetTitle("p_{t}, GeV/c");
  g->SetTitle(Form("#frac{%s}{%s}", g1->GetTitle(), g2->GetTitle()));
  Double_t x, y1, y2;
  Double_t c0, c1, c12, e0, e1;
  Double_t *ex = g1->GetEX();
  Double_t *ey = g1->GetEY();
  for (Int_t i = 0; i < n; i++) {
    g1->GetPoint(i, x, y1);
    g2->GetPoint(i, x, y2);
    if (TMath::Abs(y2) < 1.E-12) y2 = 1.0;
    c0 = y1;
    c1 = y2;
    c12 = c1*c1;
    e0  = g1->GetErrorY(i);
    e1  = g2->GetErrorY(i);
    g->SetPoint(i, x, y1/y2);
    g->SetPointError(i, ex[i], (e0*e0*c1*c1 + e1*e1*c0*c0)/(c12*c12));
  }

  return g;
}
makePlot_check_all()
{

  gStyle->SetOptStat(0);

  vector< TString > v_infile;
  //  v_infile.push_back( TString("output/fitResults_run001_1layer_sheath.root") );
  //  v_infile.push_back( TString("output/fitResults_run002_1layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run003_1layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run004_2layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run005_2layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run006_3layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run007_4layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run008_2layer_cylinder.root") );
  v_infile.push_back( TString("output/fitResults_run009_2layer_cylinder.root") );
  //  v_infile.push_back( TString("output/fitResults_run010_1layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run011_1layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run012_1layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run013_1layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run014_1layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run015_1layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run016_1layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run017_2layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run018_1layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run019_1layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run020_1layer_sheath.root") );
  v_infile.push_back( TString("output/fitResults_run021_1layer.root") );
  for ( unsigned f = 0; f < v_infile.size(); f++ )
    {
      cout << "Plot " << v_infile.at(f) << endl;

      TCanvas *c0 = new TCanvas();

      TFile *fin = new TFile( v_infile.at(f) );
      TTree *tin = (TTree*)fin->Get("fitResults");
      tin->Draw("bshield:bext:bshield_err:bext_err");

      TGraphErrors *gshield = new TGraphErrors( tin->GetEntries(), tin->GetV2(), tin->GetV1(), tin->GetV4(), tin->GetV3() );
      gshield->SetTitle(v_infile.at(f));
      gshield->GetXaxis()->SetTitle("B_{ext} [mT]");
      gshield->GetYaxis()->SetTitle("B_{shield} [mT]");

      gshield->Draw("AP");

      fin->Close();

      if ( f == 0 )
        c0->Print("plot_check_all.ps(");
      else if ( f == v_infile.size() - 1 )
        c0->Print("plot_check_all.ps)");
      else
        c0->Print("plot_check_all.ps");

    }



}
示例#14
0
void Draw_CMS_JPsi_RaaVsNpart(TLegend *lgd)
{

int nbins = 12;
  Double_t RaaCMS[20]={0.23,0.24,0.29,0.33,0.38,0.40,0.45,0.41,0.52,0.52,0.64,0.64};
  Double_t StatErrCMS[20]={0.01,0.01,0.02,0.02,0.02,0.03,0.03,0.03,0.04,0.04,0.05,0.05};
  Double_t SystErrCMS[20]={0.02,0.03,0.03,0.03,0.04,0.04,0.05,0.04,0.05,0.05,0.07,0.13};
  Double_t NPartCMS[20]={Npart(0,2),Npart(2,4),Npart(4,6),Npart(6,8),Npart(8,10),Npart(10,12),
			 Npart(12,14),Npart(14,16),Npart(16,18),Npart(18,20),Npart(20,24),
			 Npart(24,40)};
  Double_t ErrNPartCMS[20]={0};
  
  TGraphErrors *grRaaCMS = new TGraphErrors(nbins, NPartCMS, RaaCMS, ErrNPartCMS, StatErrCMS);  
  grRaaCMS->SetMarkerStyle(21);
  grRaaCMS->SetMarkerColor(2);
  grRaaCMS->GetYaxis()->SetRangeUser(0,1.7);
  grRaaCMS->GetXaxis()->SetTitle("N_{Part}");
  grRaaCMS->GetYaxis()->SetTitle("R_{AA}");
  
  grRaaCMS->Draw("AP");
  TBox *RaaJPsiSys[12];
  for(int j=0;j<12;j++){
    RaaJPsiSys[j] = new TBox(NPartCMS[j]-3,  RaaCMS[j]-SystErrCMS[j], NPartCMS[j]+3, RaaCMS[j]+SystErrCMS[j]);
  }
  
  for(int j=0;j<12;j++){
    RaaJPsiSys[j]->SetFillStyle(0000);
    RaaJPsiSys[j]->SetLineColor(6);
    RaaJPsiSys[j]->Draw("same"); 
  }
  
  TLine *lh2 = new TLine(0.0,1.0,400,1.0);
  lh2->SetLineColor(1);
  lh2->SetLineStyle(1);
  lh2->SetLineWidth(2);
  lh2->Draw("same");
  
  TBox *GlobalSysJPsi;
  GlobalSysJPsi = new TBox(400-5, 1 - 0.06, 400+5, 1 + 0.06);
  GlobalSysJPsi->SetFillStyle(3001);
  GlobalSysJPsi->SetLineColor(6);
  GlobalSysJPsi->SetFillColor(6);
  GlobalSysJPsi->Draw("same"); 
  
  TLatex *tb= new TLatex;
  tb->SetNDC(); 
  tb->SetTextAlign(12);
  tb->SetTextColor(1);
  tb->SetTextSize(0.040);
  tb->DrawLatex(0.17,0.23,"PbPb #sqrt{s_{NN}} = 2.76 TeV");
  tb->DrawLatex(0.17,0.17,"p_{T}^{J/#psi} > 6.5 GeV/c");

  lgd->AddEntry(grRaaCMS,"CMS Data", "P");

}
///
/// Plot the discrepancy between the observable and the predicted
/// observable when making predictions about observables by scanning
/// them. This checks if the chi2 term of the observable is tight enough.
/// This only works for 1D scans for now.
///
void ParameterEvolutionPlotter::plotObsScanCheck()
{
	vector<RooSlimFitResult*> results = curveResults;

	cout << "ParameterEvolutionPlotter::plotObsScanCheck() : plotting ..." << endl;
	TCanvas *c2 = newNoWarnTCanvas("plotObsScanCheck"+getUniqueRootName(), title, 800,600);
	c2->SetLeftMargin(0.2);

	// get observable
	TGraphErrors *g = new TGraphErrors(results.size());
	int iGraph = 0;

	for ( int i=0; i<results.size(); i++ ){
		assert(results[i]);
		// get value of observable
		float obsValue = results[i]->getParVal(scanVar1);
		float obsError = w->var(scanVar1)->getError();

		// get value of theory prediction
		setParameters(w,parsName,results[i]);
		TString thName = scanVar1;
		thName.ReplaceAll("_obs","_th");
		if ( !w->function(thName) ){
			cout << "ParameterEvolutionPlotter::plotObsScanCheck() : ERROR : theory value not found: " << thName << endl;
			continue;
		}
		float thValue = w->function(thName)->getVal();
		g->SetPoint(iGraph, iGraph, obsValue-thValue);
		g->SetPointError(iGraph, 0., obsError);
		iGraph++;
	}

	g->SetTitle(scanVar1);
	g->GetXaxis()->SetTitle("scan step");
	g->GetYaxis()->SetTitleSize(0.06);
	g->GetYaxis()->SetLabelSize(0.04);
	g->GetYaxis()->SetTitleOffset(1.5);
	g->GetYaxis()->SetTitle(scanVar1);
	Int_t ci = 927;
	TColor *col = new TColor(ci, 0, 0, 1, " ", 0.5);
	g->SetFillColor(ci);
	g->SetFillStyle(1001);
	g->Draw("a3");
	g->Draw("lxsame");
	c2->Update();

	savePlot(c2, "parEvolutionObsSanCheck_"+name+"_"+scanVar1);
}
示例#16
0
TGraphErrors* PlotLightYieldGraph()
{
  string filename;
  vector<double> x,y,ex,ey;
  while(1){
    cout<<"\n\nEnter next file to process; <enter> to finish."<<endl;
    getline(cin, filename);
    if(filename=="")
      break;
    
    //load the tree
    TTree* Events = GetEventsTree(filename.c_str());
    if(!Events)
      continue;
    gROOT->ProcessLine(".x analysis/Aliases.C");
    double start = Events->GetMinimum("timestamp");
    double end = Events->GetMaximum("timestamp");
    double error = 0;
    TString title = TString("Na22 Spectrum, ") + 
      TString(filename)(TRegexp("Run......"));
    TH1F* hist = new TH1F("Na22Spec",title,200,1000,2500);
    Events->Draw("sumspec >> Na22Spec","min > 0","e");
    double yield = Fit511Photopeak(hist,&error);
    
    x.push_back((start+end)/2.);
    ex.push_back((end-start)/2.);
    y.push_back(yield);
    ey.push_back(error);
  }
  if(x.size() == 0){
    cerr<<"No valid points found!"<<endl;
    return 0;
  }
  TGraphErrors* graph = new TGraphErrors(x.size(),&x[0],&y[0],&ex[0],&ey[0]);
  graph->Draw("ape");
  TAxis* xax = graph->GetXaxis();
  xax->SetTitle("Run Time");
  xax->SetTimeDisplay(1);
  xax->SetTimeFormat("%Y/%m/%d");
  xax->SetTimeOffset(1,"gmt");
  TAxis* yax = graph->GetYaxis();
  yax->SetTitle("511 keV Light Yield [pe/keV]");
  graph->Draw("ape");
  return graph;
}
示例#17
0
TGraphErrors* diffTGraph(TGraphErrors* g1, TGraphErrors *g2, char* title, char* xtitle, char* ytitle){

  Double_t* x1  = g1->GetX();
  Double_t* y1  = g1->GetY();
  Double_t* ex1 = g1->GetEX();
  Double_t* ey1 = g1->GetEY();
  Int_t n1      = g1->GetN();
  
  Double_t* x2  = g2->GetX();
  Double_t* y2  = g2->GetY();
  Double_t* ex2 = g2->GetEX();
  Double_t* ey2 = g2->GetEY();
  Int_t n2      = g2->GetN();

  assert(n1 == n2);
  
  Double_t* x  = new Double_t[n1];
  Double_t* y  = new Double_t[n1];
  Double_t* ex = new Double_t[n1];
  Double_t* ey = new Double_t[n1];

  for(int i = 0 ; i < n1 ; i++){

    x[i]  = 0.5 * ( x1[i] + x2[i] );
    ex[i] = 0.5 * sqrt( pow(ex1[i],2) + pow(ex2[i],2) );

    ey[i] = sqrt( pow(ey1[i],2) + pow(ey2[i],2) );
    y[i]  = y2[i] - y1[i];

  }



  TGraphErrors *g = new TGraphErrors(n1,x,y,ex,ey);
  g->SetTitle(title);
  g->GetYaxis()->SetTitle(ytitle);
  g->GetXaxis()->SetTitle(xtitle);
  g -> SetMarkerStyle(8);
  g -> SetMarkerSize(0.5);
  return g;
}
示例#18
0
TGraphErrors* getDataMcResponseRatio(TGraphErrors* gData, TGraphErrors* gMc, int aNumberOfPtBins, string XTitle) {
  Double_t x[aNumberOfPtBins];
  Double_t ex[aNumberOfPtBins];
  for(int j=0;j<aNumberOfPtBins; j++) {
    ex[j] = 0.;
  }
  Double_t xratio[aNumberOfPtBins];
  Double_t ydata[aNumberOfPtBins];
  Double_t ymc[aNumberOfPtBins];
  Double_t yr[aNumberOfPtBins];
  Double_t eydata[aNumberOfPtBins];
  Double_t eymc[aNumberOfPtBins];
  Double_t eyr[aNumberOfPtBins];

  int nBins = 0;
  for(int i=0; i<aNumberOfPtBins; i++) {
    gMc->GetPoint(i,x[i],ymc[i]);
    gData->GetPoint(i,x[i],ydata[i]);
    eymc[i] = gMc->GetErrorY(i);
    eydata[i] = gData->GetErrorY(i);
    if (ymc[i] == 0 || ydata[i] == 0)
      continue;
    xratio[nBins] = x[i];
    yr[nBins] = ydata[i]/ymc[i];
    std::cout << yr[nBins] << std::endl;
    eyr[nBins] = sqrt(pow(eydata[i]/ymc[i],2)+pow(eymc[i]*ydata[i]/(pow(ymc[i],2)),2));
    nBins++;
  }

  TGraphErrors *gDataMcResponseratio = new TGraphErrors(nBins,xratio,yr,ex,eyr);
  gDataMcResponseratio->SetMarkerStyle(20);
  gDataMcResponseratio->SetMarkerColor(1);
  gDataMcResponseratio->SetLineColor(1);
  gDataMcResponseratio->SetMarkerSize(1.0);
  //gDataMcResponseratio->SetMaximum(1.08);
  //gDataMcResponseratio->SetMinimum(0.90);
  gDataMcResponseratio->GetXaxis()->SetTitle(XTitle.c_str());

  return gDataMcResponseratio;
}
示例#19
0
TGraphErrors g(Double_t alpha, Double_t constTerm){
  TGraphErrors graph;
  Int_t iPoint=0;

  //  std::cout << alpha << "\t" << constTerm << std::endl;
  Double_t alpha2=alpha*alpha;
  Double_t const2=constTerm*constTerm;
  for(Double_t energy=20; energy<150; energy+=10){
    Double_t addSmearing = (sqrt(alpha2/energy+const2));
    
    graph.SetPoint(iPoint, energy, addSmearing);
    graph.SetPointError(iPoint,0, 0);
    iPoint++;
  }

  graph.Set(iPoint);
  graph.Draw("A L");
  graph.SetFillColor(kBlue);
  graph.SetLineColor(kYellow);
  graph.GetXaxis()->SetTitle("Energy [GeV]");
  graph.GetYaxis()->SetTitle("Additional smearing [%]");
  return graph;
}
示例#20
0
void PlotParValVsLabelWithErr(TFile* f, TTree* tr, TString strMillepedeRes, TString strOutdir)
{
 
  f->cd();
  TString canvName="c_";
  canvName+=strMillepedeRes;
  canvName+="_";
  canvName+=StrPlotType(PARSwithERRvsLABEL);
  canvName.ReplaceAll(".res","");

  TCanvas* canv = new TCanvas(canvName,canvName,900,600);
  canv->Divide(3,2);

  for (int ind=1; ind<=6; ind++){
    canv->cd(ind);
    TPad* pad = (TPad*)canv->GetPad(ind);
    TString strCut="((label%20-1)%9+1)==";
    strCut+=ind;
    int n = tr->Draw("label%700000:10000*parVal:10000*parErr:0.01*(label%700000)",strCut,"goff");
    TGraphErrors *gr = new TGraphErrors(n,tr->GetV1(),tr->GetV2(),tr->GetV4(),tr->GetV3());
    gr->SetMarkerStyle(20);
    gr->SetLineWidth(2);
    for (int i=0; i<n; i++){
      std::cout<<tr->GetV1()[i]<<" "<<tr->GetV2()[i]<<"+-"<<tr->GetV3()[i]<<std::endl;
    }
    gr->SetTitle(StrPar(ind)+TString(", 10000*(par+-err)"));
    gr->GetXaxis()->SetTitle("label%700000");
    gr->Draw("AP");
  }// end of loop over ind
  canvName+=".png";
  TString saveName=strOutdir+canvName;
  canv->SaveAs(saveName);
  saveName.ReplaceAll(".png",".pdf");
  canv->SaveAs(saveName);

}// end of PlotParValVsLabelWithErr
示例#21
0
void plotNsig(){

  vector<RooWorkspace*> w (13);
  vector<string> limits (14);
  vector<TFile*> f(13);
  Double_t* nsig = new Double_t[13];
  Double_t* err_nsig = new Double_t[13];
  Double_t* pt = new Double_t[13];
  Double_t* err_pt = new Double_t[13];
  Double_t* norm_lumi = new Double_t[13];
  Double_t* scale_fact = new Double_t[13];

  norm_lumi[0]=2.831017;
  norm_lumi[1]=2.831017;
  norm_lumi[2]=22.020492;
  norm_lumi[3]=22.020492;
  norm_lumi[4]=132.115;
  norm_lumi[5]=132.115;
  norm_lumi[6]=132.115;
  norm_lumi[7]=276.515;
  norm_lumi[9]=276.515;
  norm_lumi[8]=276.515;
  norm_lumi[10]=276.515;
  norm_lumi[11]=276.515;
  norm_lumi[12]=276.515;

  pt[0]=43.5;
  pt[1]=56.;
  pt[2]=69.;
  pt[3]=81.5;
  pt[4]=92.;
  pt[5]=96.5;
  pt[6]=102.;
  pt[7]=107.5;
  pt[8]=113.5;
  pt[9]=121.5;
  pt[10]=132.5;
  pt[11]=151.;
  pt[12]=210.;

  err_pt[0]=3.5;
  err_pt[1]=8.;
  err_pt[2]=4.;
  err_pt[3]=8.5;
  err_pt[4]=2.;
  err_pt[5]=2.5;
  err_pt[6]=3.;
  err_pt[7]=2.5;
  err_pt[8]=3.5;
  err_pt[9]=4.5;
  err_pt[10]=6.5;
  err_pt[11]=12.;
  err_pt[12]=47.;
  
  limits[0]="40";
  limits[1]="47";
  limits[2]="65";
  limits[3]="73";
  limits[4]="90";
  limits[5]="94";
  limits[6]="99";
  limits[7]="105";
  limits[8]="110";
  limits[9]="117";
  limits[10]="126";
  limits[11]="139";
  limits[12]="163";
  limits[13]="1000";

  scale_fact[0]=   0.997614 * 0.989847; //scF_presel * sc_F_sel_okMVA005  
  scale_fact[1]=   0.999025 * 0.993679; //scF_presel * sc_F_sel_okMVA005
  scale_fact[2]=   0.999965 * 0.993734; //scF_presel * sc_F_sel_okMVA005
  scale_fact[3]=   1.00087  * 0.993787; //scF_presel * sc_F_sel_okMVA005
  scale_fact[4]=   1.00163  * 0.993832; //scF_presel * sc_F_sel_okMVA005
  scale_fact[5]=   1.00195  * 0.993851; //scF_presel * sc_F_sel_okMVA005
  scale_fact[6]=   1.00235  * 0.993875; //scF_presel * sc_F_sel_okMVA005
  scale_fact[7]=   1.00275  * 0.993898; //scF_presel * sc_F_sel_okMVA005
  scale_fact[8]=   1.00318  * 0.993924; //scF_presel * sc_F_sel_okMVA005
  scale_fact[9]=   1.00376  * 0.993958; //scF_presel * sc_F_sel_okMVA005
  scale_fact[10]=  1.00401  * 0.993973; //scF_presel * sc_F_sel_okMVA005
  scale_fact[11]=  1.00401  * 0.993973; //scF_presel * sc_F_sel_okMVA005
  scale_fact[12]=  1.00401  * 0.993973; //scF_presel * sc_F_sel_okMVA005

  

  for(int i=0; i<w.size(); i++){
    f[i] = new TFile(("workspace_fit_EB_data_WP095_pt"+limits[i]+"_"+limits[i+1]+".root").c_str(), "READ");
    w[i] =(RooWorkspace*)f[i]->Get("w_data");
    nsig[i] = (((RooRealVar*)w[i]->var("N_sig_real"))->getVal())/(2.*err_pt[i]*norm_lumi[i]*scale_fact[i]);
    err_nsig[i] = (((RooRealVar*)w[i]->var("N_sig_real"))->getError())/(2.*err_pt[i]*norm_lumi[i]*scale_fact[i]);
  }

  TGraphErrors* g = new TGraphErrors(13, pt, nsig, err_pt, err_nsig);
  g->GetXaxis()->SetTitle("p_{T}^{#gamma} [GeV]");
  g->GetYaxis()->SetTitle("d #sigma/d p_{T}^{#gamma} (ev[pb])/[GeV]");

  TCanvas* c = new TCanvas("","", 1);
  g->Draw("ap");
  TLatex* tex_m = new TLatex();
  tex_m->SetNDC();
  tex_m->SetTextAlign(12);
  tex_m->SetTextSize(0.037);
  tex_m->SetLineWidth(2);
  tex_m->DrawLatex(0.25,0.94,"CMS Preliminary 8 TeV");
  c->SaveAs("plotNsig.png");
  c->SaveAs("plotNsig.pdf");

  c->SetLogy();
  c->SaveAs("plotNsig_log.png");
  c->SaveAs("plotNsig_log.pdf");

}
示例#22
0
void all(int channels=0, int categ=-1, int sample=2012 /*,bool doSfLepton=true*/){

  double bwSigma[40];
  int mass[40]; int id[40]; double xLow[40]; double xHigh[40];  
  int maxMassBin;

    float masses[1] = {125};
    for(int i=0;i<1;++i) {
      mass[i] = masses[i]; 
      id[i]=masses[i]; 
      xLow[i] = 105.; // getFitEdge(masses[i],width,true); 
      xHigh[i] = 140.; // getFitEdge(masses[i],width,false); 
      //cout << "For mass = " << masses[i] << " width = " << width << "; => Fit Range = [" << xLow[i] << "," << xHigh[i] << "]" << endl;
      bwSigma[i] = 0.004;
    }
    maxMassBin = 1;   // 29;
  // -----------------------



  double massV[40],massE[40];
  for(int i=0; i<maxMassBin;++i){
    massV[i]=mass[i];
    massE[i]=0;
  }
  double A1Val[40],A1Err[40];
  double A2Val[40],A2Err[40];
  double a1Val[40],a1Err[40];
  double a2Val[40],a2Err[40];
  double n1Val[40],n1Err[40];
  double n2Val[40],n2Err[40];
  double meanCBVal[40],meanCBErr[40];
  double sigmaCBVal[40],sigmaCBErr[40];
  double meanBWVal[40],meanBWErr[40];
  double covQualVal[40];

  double fitValues[10];
  double fitErrors[10];
  double covQual[1];

  
  for(int i=0; i<maxMassBin;++i){
    fitSignalShapeW(mass[i],id[i],channels,categ, sample,/* 10.,doSfLepton,*/xLow[i],xHigh[i],bwSigma[i],
		    fitValues,fitErrors,covQual);  

    cout << "a1 value,error: " << fitValues[0] << " , " << fitErrors[0] << endl; 
    a1Val[i]=fitValues[0]; a1Err[i]=fitErrors[0];

    cout << "a2 value,error: " << fitValues[1] << " , " << fitErrors[1] << endl; 
    a2Val[i]=fitValues[1]; a2Err[i]=fitErrors[1];

    cout << "n1 value,error: " << fitValues[4] << " , " << fitErrors[4] << endl; 
    n1Val[i]=fitValues[4]; n1Err[i]=fitErrors[4];

    cout << "n2 value,error: " << fitValues[5] << " , " << fitErrors[5] << endl; 
    n2Val[i]=fitValues[5]; n2Err[i]=fitErrors[5];

    cout << "meanCB value,error: " << fitValues[2] << " , " << fitErrors[2] << endl;
    meanCBVal[i]=fitValues[2]; meanCBErr[i]=fitErrors[2];
    
    cout << "sigmaCB value,error: " << fitValues[6] << " , " << fitErrors[6] << endl; 
    sigmaCBVal[i]=fitValues[6]; sigmaCBErr[i]=fitErrors[6];

    cout << "meanBW value,error: " << fitValues[3] << " , " << fitErrors[3] << endl; 
    meanBWVal[i]=fitValues[3]; meanBWErr[i]=fitErrors[3];

    cout << "A1 value,error: " << fitValues[7] << " , " << fitErrors[7] << endl;
    A1Val[i]=fitValues[7]; A1Err[i]=fitErrors[7];

    cout << "A2 value,error: " << fitValues[8] << " , " << fitErrors[8] << endl;
    A2Val[i]=fitValues[8]; A2Err[i]=fitErrors[8];

    cout << "covQual of the fit: " << covQual[0] << endl;
    covQualVal[i] = covQual[0];

  }
  

  stringstream namefile;
  namefile << "parameters_channel" << channels<< categ << ".root";
  TFile *resultfile = TFile::Open(namefile.str().c_str(),"RECREATE");
 
  TGraphErrors* gA1 = new TGraphErrors(maxMassBin,massV,a1Val,massE,a1Err);
  TGraphErrors* gA2 = new TGraphErrors(maxMassBin,massV,a2Val,massE,a2Err);
  TGraphErrors* gN1 = new TGraphErrors(maxMassBin,massV,n1Val,massE,n1Err);
  TGraphErrors* gN2 = new TGraphErrors(maxMassBin,massV,n2Val,massE,n2Err);
  TGraphErrors* gMeanCB = new TGraphErrors(maxMassBin,massV,meanCBVal,massE,meanCBErr);
  TGraphErrors* gSigmaCB = new TGraphErrors(maxMassBin,massV,sigmaCBVal,massE,sigmaCBErr);
  TGraphErrors* gMeanBW = new TGraphErrors(maxMassBin,massV,meanBWVal,massE,meanBWErr);
  TGraphErrors* gAA1 = new TGraphErrors(maxMassBin,massV,A1Val,massE,A1Err);
  TGraphErrors* gAA2 = new TGraphErrors(maxMassBin,massV,A2Val,massE,A2Err);
  TGraph* gCovQual = new TGraph(maxMassBin,massV,covQualVal);

  gA1->SetName("gA1");  gA1->SetMarkerStyle(20);   gA1->SetMarkerSize(1);
  gA2->SetName("gA2");  gA2->SetMarkerStyle(20);   gA2->SetMarkerSize(1);
  gN1->SetName("gN1");  gN1->SetMarkerStyle(20);   gN1->SetMarkerSize(1);
  gN2->SetName("gN2");  gN2->SetMarkerStyle(20);   gN2->SetMarkerSize(1);
  gMeanCB->SetName("gMeanCB"); gMeanCB->SetMarkerStyle(20);   gMeanCB->SetMarkerSize(1);
  gSigmaCB->SetName("gSigmaCB"); gSigmaCB->SetMarkerStyle(20);   gSigmaCB->SetMarkerSize(1);
  gMeanBW->SetName("gMeanBW"); gMeanBW->SetMarkerStyle(20);   gMeanBW->SetMarkerSize(1);
  gAA1->SetName("gAA1");  gAA1->SetMarkerStyle(20);   gAA1->SetMarkerSize(1);
  gAA2->SetName("gAA2");  gAA2->SetMarkerStyle(20);   gAA2->SetMarkerSize(1);

  gCovQual->SetName("gCovQual"); gCovQual->SetMarkerStyle(20);   gCovQual->SetMarkerSize(1);
  
  gA1->SetTitle("");
  gA1->GetXaxis()->SetTitle("mass (GeV)");
  gA1->GetYaxis()->SetTitle("CB a-parameter");

  gA2->SetTitle("");
  gA2->GetXaxis()->SetTitle("mass (GeV)");
  gA2->GetYaxis()->SetTitle("CB a-parameter");

  gN1->SetTitle("");
  gN1->GetXaxis()->SetTitle("mass (GeV)");
  gN1->GetYaxis()->SetTitle("CB n-parameter");

  gN2->SetTitle("");
  gN2->GetXaxis()->SetTitle("mass (GeV)");
  gN2->GetYaxis()->SetTitle("CB n-parameter");

  gMeanCB->SetTitle("");
  gMeanCB->GetXaxis()->SetTitle("mass (GeV)");
  gMeanCB->GetYaxis()->SetTitle("CB mean");

  gSigmaCB->SetTitle("");
  gSigmaCB->GetXaxis()->SetTitle("mass (GeV)");
  gSigmaCB->GetYaxis()->SetTitle("CB sigma");

  gMeanBW->SetTitle("");
  gMeanBW->GetXaxis()->SetTitle("mass (GeV)");
  gMeanBW->GetYaxis()->SetTitle("BW mean");

  gAA1->SetTitle("");
  gAA1->GetXaxis()->SetTitle("mass (GeV)");
  gAA1->GetYaxis()->SetTitle("Chebyshev a1-parameter");

  gAA2->SetTitle("");
  gAA2->GetXaxis()->SetTitle("mass (GeV)");
  gAA2->GetYaxis()->SetTitle("Chebyshev a2-parameter");


  gCovQual->SetTitle("");
  gCovQual->GetXaxis()->SetTitle("mass (GeV)");
  gCovQual->GetYaxis()->SetTitle("cov. matrix qual.");
  
  resultfile->cd();
  gA1->Fit("pol0"); gA1->Draw("Ap"); gA1->Write();
  gA2->Fit("pol0"); gA2->Draw("Ap"); gA2->Write();
  gN1->Fit("pol1"); gN1->Draw("Ap"); gN1->Write();
  gN2->Fit("pol1"); gN2->Draw("Ap"); gN2->Write();
  gMeanCB->Fit("pol1"); gMeanCB->Draw("Ap"); gMeanCB->Write();
  gSigmaCB->Fit("pol1"); gSigmaCB->Draw("Ap"); gSigmaCB->Write();
  gAA1->Fit("pol0"); gAA1->Draw("Ap"); gAA1->Write();
  gAA2->Fit("pol0"); gAA2->Draw("Ap"); gAA2->Write(); 
  gCovQual->Write();

  resultfile->Close();

}
示例#23
0
// The actual job
void signalEfficiency_w(int channel, double sqrts, int process, double JES, ofstream* txtYields) 
{
  TString schannel;
  if      (channel == 1) schannel = "4mu";
  else if (channel == 2) schannel = "4e";
  else if (channel == 3) schannel = "2e2mu";
  else cout << "Not a valid channel: " << channel << endl;

  TString schannelFilename = (schannel=="2e2mu"?"2mu2e":schannel); // adapt to naming convention of tree files

  TString sprocess;
  if      (process == ggH) sprocess = "ggH";
  else if (process == qqH) sprocess = "qqH";
  else if (process == ZH) sprocess = "ZH";
  else if (process == WH) sprocess = "WH";
  else if (process == ttH) sprocess = "ttH";
  else cout << "Not a valid channel: " << process << endl;  

  TString sjes;
  if      (JES==0.) sjes="";
  else if (JES>0.)  sjes="_up";
  else if (JES<0.)  sjes="_down";

  TString ssqrts = (long) sqrts + TString("TeV");


  // Print table with yields
  (*txtYields) << endl << endl 
	       << left << setw(7) << "*** Summary: " << sprocess << " process, sqrts = " << fixed << setprecision(0) <<sqrts << " TeV, channel = " << schannel << " ***" << endl << endl;
  (*txtYields) << left << setw(7) << "mH" << setw(13) << "XS*BR" << setw(13) 
	       << "Eff unt" << setw(13) << "Yield unt" << setw(13) << "Eff tag" 
	       << setw(13) << "Yield tag" << setw(13) << "Eff TOT" << setw(13) << "Yield TOT" 
	       << setw(13) << "Eff unt" << setw(13) << "Yield unt" << setw(13) << "Eff tag" 
	       << setw(13) << "Yield tag" << setw(13) << "Eff TOT" << setw(13) << "Yield TOT" 
	       << setw(13) << "n. raw" << setw(13) << "n. W pwg" << setw(13) << "n. W PU" 
	       << setw(13) << "n. W eff" << setw(13) 
	       << endl << left << setw(7) << " " << setw(13) << " " << setw(13)
	       << "(in MW)" << setw(13) << "(in MW)" << setw(13) << "(in MW)" 
	       << setw(13) << "(in MW)" << setw(13) << "(in MW)" << setw(13) << "(in MW)" 
	       << setw(13) << "(full)" << setw(13) << "(full)" << setw(13) << "(full)" 
	       << setw(13) << "(full)" << setw(13) << "(full)" << setw(13) << "(full)" 
	       << setw(13) << "(full U+T)" << setw(13) << "(full U+T)" << setw(13) << "(full U+T)" << setw(13) << "(full U+T)" 
	       << endl << endl;

  cout << "process = " << sprocess << " schannel = " << schannel << "  sqrts = " << sqrts << " JES = " << JES <<endl;

  TString totoutfile = "CardFragments/signalEfficiency_"  + ssqrts + "_" + schannel + sjes + ".txt";
  TString ratiooutfile = "CardFragments/signalEfficiency_" + ssqrts + "_" + schannel + sjes + "_ratio.txt";
  TString jetyieldoutfile = "CardFragments/signalEfficiency_"  + ssqrts + "_" + schannel + sjes + "_jetyields.txt";

  // Create card fragments using new powheg samples
  ofstream oftot;
  ofstream ofrat;

  if (process==ggH) {
    oftot.open(totoutfile,ios_base::out);
    ofrat.open(ratiooutfile,ios_base::out);
  } else {
    oftot.open(totoutfile,ios_base::out | ios_base::app);
    ofrat.open(ratiooutfile,ios_base::out | ios_base::app);
  }

  ftot = new TFile("sigFigs" + ssqrts +"/eff_" + sprocess + "_" + schannel + sjes + (useNewGGHPowheg ? ".root" : "_oldPwg.root"),"RECREATE");
  fratio = new TFile("sigFigs" + ssqrts +"/eff_" + sprocess + "_" + schannel + sjes + (useNewGGHPowheg ? "_ratio.root" : "_ratio_oldPwg.root"),"RECREATE");

  gSystem->AddIncludePath("-I$ROOFITSYS/include");
  setTDRStyle(false);
  gStyle->SetStatX(-0.5);

  int nPoints=0;
  int* masses=0;
  double* mHVal=0;

  // Pick the correct set of mass points, set subpath
  TString filepath;
  if (process==ggH){
    if (useNewGGHPowheg) {
      if (sqrts==7) {
	nPoints = nPoints7TeV_p15;
	masses  = masses7TeV_p15;
	mHVal   = mHVal7TeV_p15;
	filepath = filePath7TeV;
      } else if (sqrts==8) {
	nPoints = nPoints8TeV_p15;
	masses  = masses8TeV_p15;
	mHVal   = mHVal8TeV_p15;
	filepath = filePath8TeV;
      }
    } else { // OLD powheg samples
      if (sqrts==7) {
	nPoints = nPoints7TeV;
	masses  = masses7TeV;
	mHVal   = mHVal7TeV;
	filepath = filePath7TeV;
      } else if (sqrts==8) {
	nPoints = nPoints8TeV;
	masses  = masses8TeV;
	mHVal   = mHVal8TeV;
	filepath = filePath8TeV;
      }
    }
  } else if (process==qqH) {
    if (sqrts==7) {
      nPoints = nVBFPoints7TeV;
      masses  = VBFmasses7TeV;
      mHVal   = mHVBFVal7TeV;
      filepath = filePath7TeV;
    } else if (sqrts==8) {
      nPoints = nVBFPoints8TeV;
      masses  = VBFmasses8TeV;
      mHVal   = mHVBFVal8TeV;
      filepath = filePath8TeV;
    }
  } else if (process==ZH || process==WH || process==ttH) {
    if (sqrts==7) {
      nPoints = nVHPoints7TeV;
      masses  = VHmasses7TeV;
      mHVal   = mHVHVal7TeV;
      filepath = filePath7TeV;
    } else if (sqrts==8) {
      nPoints = nVHPoints8TeV;
      masses  = VHmasses8TeV;
      mHVal   = mHVHVal8TeV;
      filepath = filePath8TeV;
    }
  }  


  float xMax = masses[nPoints-1]+10;


  const int arraySize=200;
  assert (arraySize>=nPoints);
  double totefficiencyVal[arraySize];
  double totefficiencyErr[arraySize];
  double dijetratioVal[arraySize];
  double dijetratioErr[arraySize];
  double totefficiencyValInMW[arraySize];
  double totefficiencyErrInMW[arraySize];
  double dijetratioValInMW[arraySize];
  double dijetratioErrInMW[arraySize];


  // Define the object to compute XS and BRs
  HiggsCSandWidth *myCSW = new HiggsCSandWidth(gSystem->ExpandPathName("$CMSSW_BASE/src/Higgs/Higgs_CS_and_Width/txtFiles/"));
	
  TString infile;

  TGraph gJys(nPoints);

  for (int i = 0; i < nPoints; i++){

    // Compute XS and BR
    double xsTimesBR = 0.;
    double BRH4e = myCSW->HiggsBR(12,masses[i]);
    double BRH2e2mu = myCSW->HiggsBR(13,masses[i]);
    double BRHZZ = myCSW->HiggsBR(11,masses[i]);
    double BR = BRHZZ;
    if (process==ggH || process==qqH) { 
      if (channel==fs4mu || channel==fs4e) BR = BRH4e;
      else BR = BRH2e2mu;
    }

    if (process==ggH)      xsTimesBR = BR*myCSW->HiggsCS(1,masses[i],sqrts);
    else if (process==qqH) xsTimesBR = BR*myCSW->HiggsCS(2,masses[i],sqrts);
    else if (process==ZH)  xsTimesBR = BR*myCSW->HiggsCS(3,masses[i],sqrts);
    else if (process==WH)  xsTimesBR = BR*myCSW->HiggsCS(4,masses[i],sqrts);
    else if (process==ttH) xsTimesBR = BR*myCSW->HiggsCS(5,masses[i],sqrts); 


    if (process==ggH) {
      if (useNewGGHPowheg){ 
	infile = filepath+ "/" + schannelFilename + "/HZZ4lTree_powheg15" + (masses[i]>200?"H":"jhuGenV3H") + (long)masses[i] + ".root";
      } else {
	infile = filepath+ "/" + schannelFilename + "/HZZ4lTree_H" + (long)masses[i] + ".root";
      }
    }
    
    else if (process==qqH) infile = filepath+ "/" + schannelFilename + "/HZZ4lTree_VBFH" + (long)masses[i] + ".root";
    else if (process==WH || process==ZH || process==ttH) infile = filepath+ "/" + schannelFilename + "/HZZ4lTree_" + sprocess + (long)masses[i] + ".root";    

    TFile *f = TFile::Open(infile) ;
    TTree *t1 = (TTree*) f->Get("SelectedTree");
    float MC_weight_norm, MC_weight_PUWeight, MC_weight_powhegWeight,  MC_weight_dataMC;
    float MC_weight_noxsec;
    float GenHPt;
    //int NJets;
    short genProcessId=0;
    //    short NJets30;
    vector<double> *JetPt=0;
    vector<double> *JetSigma=0;
    float ZZMass;
    t1->SetBranchAddress("MC_weight_norm",&MC_weight_norm); // For efficiency vs "proper" final state
    t1->SetBranchAddress("MC_weight_noxsec",&MC_weight_noxsec); // For efficiency vs all gen events
    t1->SetBranchAddress("MC_weight_powhegWeight",&MC_weight_powhegWeight);
    t1->SetBranchAddress("MC_weight_PUWeight",&MC_weight_PUWeight);
    t1->SetBranchAddress("MC_weight_dataMC",&MC_weight_dataMC);
    //t1->SetBranchAddress("NJets",&NJets);
    t1->SetBranchAddress("genProcessId",&genProcessId);
    t1->SetBranchAddress("JetPt",&JetPt);
    t1->SetBranchAddress("JetSigma",&JetSigma);
    //    t1->SetBranchAddress("NJets30",&NJets30);
    t1->SetBranchAddress("GenHPt",&GenHPt);
    t1->SetBranchAddress("ZZMass",&ZZMass);

    //Initialize counters for non-dijet events
    Counts* untagInMW = new Counts(); Counts* untagAll = new Counts();
    Counts* dijetInMW = new Counts(); Counts* dijetAll = new Counts();

    // Find window width // FIXME move to external function
    double valueWidth = myCSW->HiggsWidth(0,masses[i]);
    double windowVal = max(valueWidth,1.);
    
    double lowside = 100.;
    double highside = 1000.0;
      
    if (masses[i] >= 275){
      lowside = 180.0;
      highside = 650.0;
    }
    if (masses[i] >= 350){
      lowside = 200.0;
      highside = 900.0;
    }
    if (masses[i] >= 500){
      lowside = 250.0;
      highside = 1000.0;
    }
    if (masses[i] >= 700){
      lowside = 350.0;
      highside = 1400.0;
    }
    double low_M = max( (masses[i] - 20.*windowVal), lowside);
    double high_M = min((masses[i] + 15.*windowVal), highside);


    // // Load Higgs pT weights for old powheg
    //     TFile* fW; TH1D* h_HPtWeight; 
    //     TString fW_str = "./HPtWeights/weight_";
    //     fW_str += (long)masses[i];
    //     fW_str += (TString)".root";
    //     cout << fW_str << endl;
    //     if (process==ggH) {
    //       fW = TFile::Open(fW_str,"READ");
    //       h_HPtWeight = (TH1D*)fW->Get("h_weight");
    //     }


    for (int a = 0; a < t1->GetEntries(); a++){ 
      t1->GetEntry(a);
      // Skip VH events that do not belong to the right gen prod mechanism. This is no longer necessary with the proper VH samples
      if ((process==ZH && genProcessId!=24) || (process==WH && genProcessId!=26) || (process==ttH && (genProcessId!=121 && genProcessId!=122))) continue; 


      // We use the efficiency vs. generated events in the proper FS for ggH, VBF, and the efficiency vs all generated events for VH, ttH
      float effw = MC_weight_norm;
      if (process==ZH) {
	effw = MC_weight_noxsec*filter_eff_ZH_8TeV;
      }
      else if (process==WH){
	effw = MC_weight_noxsec*filter_eff_WH_8TeV;
      }
      else if (process==ttH){
	effw = MC_weight_noxsec*filter_eff_ttH_8TeV;
      }      

//       double HPtWeight = 1.;
//       if (process==ggH) HPtWeight = h_HPtWeight->GetBinContent(h_HPtWeight->FindBin(GenHPt));
//       //cout << "Higgs pT weight = " << HPtWeight << endl;
//       effw*=HPtWeight;
      

      int NJets=0;
      double jetptc=0;
      for (unsigned int j=0; j<JetPt->size();j++){
	if (JES==0.) jetptc=JetPt->at(j);
	else if (JES!=0.) jetptc=JetPt->at(j)*(1+JES*JetSigma->at(j));
	if (jetptc>30.) NJets++;
      }

      // Untagged
      if (NJets<2){
	untagAll->incrCounters(effw, MC_weight_PUWeight, MC_weight_powhegWeight, MC_weight_dataMC);
	if ( (ZZMass>low_M && ZZMass<high_M) ) untagInMW->incrCounters(effw, MC_weight_PUWeight, MC_weight_powhegWeight, MC_weight_dataMC);
      }
      else{ // Dijet
	dijetAll->incrCounters(effw, MC_weight_PUWeight, MC_weight_powhegWeight, MC_weight_dataMC);
	if ( (ZZMass>low_M && ZZMass<high_M) ) dijetInMW->incrCounters(effw, MC_weight_PUWeight, MC_weight_powhegWeight, MC_weight_dataMC);
      }
      
    }

    // FIXME: the 7TeV old samples are assumed to have the ad-hoc correction factor for the mll>12 gen cut,
    // except for the 124,125,126 new samples. As this factor is accounted for in the x-section, we have to 
    // apply it here.
    float m = masses[i];
    if (!useNewGGHPowheg && process==ggH && sqrts==7 && m>=123.9 &&  m<=126.1) {
      float mllCorr = 0.5 + 0.5*erf((m-80.85)/50.42);
      untagAll->totalCtr = untagAll->totalCtr/mllCorr;
      untagAll->eff_noweight=untagAll->eff_noweight/mllCorr;
      untagInMW->totalCtr = untagInMW->totalCtr/mllCorr;
      untagInMW->eff_noweight=untagInMW->eff_noweight/mllCorr;
      dijetAll->totalCtr = dijetAll->totalCtr/mllCorr;
      dijetAll->eff_noweight=dijetAll->eff_noweight/mllCorr;
      dijetInMW->totalCtr = dijetInMW->totalCtr/mllCorr;
      dijetInMW->eff_noweight=dijetInMW->eff_noweight/mllCorr;
    }

    if (verbose) {
      cout << " m = " << masses[i] 
	   << " :" <<endl;
      cout << "Selected non-dijet events (all) = " << untagAll->numEventsRaw 
	   << " Powheg Wtd= " << untagAll->numEventsPowheg
	   << " PU Wtd= " << untagAll->numEventsPU
	   << " Data/MC Wtd= " << untagAll->numEventsDataMC
	   << " Efficiency= " << untagAll->totalCtr
	   << endl;
      cout << "Selected non-dijet events (in mass window) = " << untagInMW->numEventsRaw 
	   << " Powheg Wtd= " << untagInMW->numEventsPowheg
	   << " PU Wtd= " << untagInMW->numEventsPU
	   << " Data/MC Wtd= " << untagInMW->numEventsDataMC
	   << " Efficiency= " << untagInMW->totalCtr
	   << endl;
      cout << "Selected dijet events (all) = " << dijetAll->numEventsRaw 
	   << " Powheg Wtd= " << dijetAll->numEventsPowheg
	   << " PU Wtd= " << dijetAll->numEventsPU
	   << " Data/MC Wtd= " << dijetAll->numEventsDataMC
	   << " Efficiency= " << dijetAll->totalCtr
	   << endl;
      cout << "Selected dijet events (in mass window) = " << dijetInMW->numEventsRaw 
	   << " Powheg Wtd= " << dijetInMW->numEventsPowheg
	   << " PU Wtd= " << dijetInMW->numEventsPU
	   << " Data/MC Wtd= " << dijetInMW->numEventsDataMC
	   << " Efficiency= " << dijetInMW->totalCtr
	   << endl;
    }

    // All events
    totefficiencyVal[i] = untagAll->totalCtr + dijetAll->totalCtr;
    cout << "All events:            " << sprocess << " " << m << " " << totefficiencyVal[i]<<endl;
    totefficiencyErr[i] = sqrt(untagAll->sumw2 + dijetAll->sumw2);
    dijetratioVal[i]=dijetAll->totalCtr/totefficiencyVal[i];
    dijetratioErr[i]=sqrt(pow(untagAll->totalCtr,2)*dijetAll->sumw2 + pow(dijetAll->totalCtr,2)*untagAll->sumw2)/pow(totefficiencyVal[i],2); // FIXME: misses 1 term 

    // Events inside the mass window
    totefficiencyValInMW[i] = untagInMW->totalCtr + dijetInMW->totalCtr;
    cout << "Events in mass window: " << sprocess << " " << m << " " << totefficiencyValInMW[i]<<endl;
    totefficiencyErrInMW[i] = sqrt(untagInMW->sumw2 + dijetInMW->sumw2);
    dijetratioValInMW[i]=dijetInMW->totalCtr/totefficiencyValInMW[i];
    dijetratioErrInMW[i]=sqrt(pow(untagInMW->totalCtr,2)*dijetInMW->sumw2 + pow(dijetInMW->totalCtr,2)*untagInMW->sumw2)/pow(totefficiencyValInMW[i],2);
    
    
    // Write yields to output file
    double lumi = -1.;
    sqrts == 7 ? lumi = lumi7TeV*1000 : lumi = lumi8TeV*1000;
    double yieldTot = xsTimesBR*lumi*totefficiencyVal[i];
    double yieldTag = xsTimesBR*lumi*dijetratioVal[i]*totefficiencyVal[i];
    double yieldUnt = xsTimesBR*lumi*untagAll->totalCtr;
    double yieldTotInMW = xsTimesBR*lumi*totefficiencyValInMW[i];
    double yieldTagInMW = xsTimesBR*lumi*dijetratioValInMW[i]*totefficiencyValInMW[i];
    double yieldUntInMW = xsTimesBR*lumi*untagInMW->totalCtr;

    int prec = 3;
    if (process>=3) prec=5;
    (*txtYields) << left << setw(7) << fixed << setprecision(0) << masses[i] << setw(13) << fixed << setprecision(7) << xsTimesBR 
		 << setw(13) << fixed << setprecision(prec) << untagInMW->totalCtr << setw(13) << yieldUntInMW << setw(13) << dijetratioValInMW[i]*totefficiencyValInMW[i] 
		 << setw(13) << yieldTagInMW << setw(13) << fixed << setprecision(prec) << totefficiencyValInMW[i] << setw(13) << yieldTotInMW 
		 << setw(13) << fixed << setprecision(prec) << untagAll->totalCtr << setw(13) << yieldUnt << setw(13) << dijetratioVal[i]*totefficiencyVal[i] 
		 << setw(13) << yieldTag << setw(13) << totefficiencyVal[i] << setw(13) << yieldTot 
		 << setw(13) << fixed << setprecision(0) << untagAll->numEventsRaw + dijetAll->numEventsRaw
		 << setw(13) << fixed << setprecision(2) << untagAll->numEventsRaw + dijetAll->numEventsPowheg
		 << setw(13) << untagAll->numEventsPU + dijetAll->numEventsPU
		 << setw(13) << untagAll->numEventsDataMC + dijetAll->numEventsDataMC
		 << endl;
     
  
    f->Close();
    gJys.SetPoint(i,masses[i],yieldTagInMW/yieldUntInMW);
  }  
  TF1 *fitJys = new TF1("fitJys","pol3",100,1000);
  gJys.Fit(fitJys);

  (*txtYields) << endl << endl << endl;
	
  TGraphErrors* totgrEff;
  TGraphErrors* ratgrEff;

  if (process==ggH || process==qqH){
    totgrEff = new TGraphErrors( nPoints, mHVal, totefficiencyVal, 0, totefficiencyErr);
    ratgrEff = new TGraphErrors( nPoints, mHVal, dijetratioVal, 0, dijetratioErr);
  }
  else {
    totgrEff = new TGraphErrors( nPoints, mHVal, totefficiencyValInMW, 0, totefficiencyErrInMW);
    ratgrEff = new TGraphErrors( nPoints, mHVal, dijetratioValInMW, 0, dijetratioErrInMW);
  }
  totgrEff->SetMarkerStyle(20);
  ratgrEff->SetMarkerStyle(20);

  //ICHEP parametrization	
  //TF1 *polyFunc= new TF1("polyFunc","([0]+[1]*TMath::Erf( (x-[2])/[3] ))*([4]+[5]*x+[6]*x*x)", 110., xMax);
  //polyFunc->SetParameters(-4.42749e+00,4.61212e+0,-6.21611e+01,1.13168e+02,2.14321e+00,1.04083e-03,4.89570e-07);


  TF1 *polyFunctot= new TF1("polyFunctot","([0]+[1]*TMath::Erf( (x-[2])/[3] ))*([4]+[5]*x+[6]*x*x)+[7]*TMath::Gaus(x,[8],[9])", 110., xMax);
  polyFunctot->SetParameters(-4.42749e+00,4.61212e+0,-6.21611e+01,1.13168e+02,2.14321e+00,1.04083e-03,4.89570e-07, 0.03, 200, 30);
  polyFunctot->SetParLimits(7,0,0.2);
  polyFunctot->SetParLimits(8,160,210);
  polyFunctot->SetParLimits(9,10,70);

  if (process!=ggH && process!=qqH) {
    polyFunctot->FixParameter(7,0);
    polyFunctot->FixParameter(8,0);
    polyFunctot->FixParameter(9,1);
  }

//   if (channel==fs4mu && sqrts==7) {    
//     polyFunctot->SetParLimits(7,0,0.035);
//     polyFunctot->SetParLimits(8,160,210);
//     polyFunctot->SetParLimits(9,30,50);
//   }

  polyFunctot->SetLineColor(4);      
  TString cname = "eff" + sprocess + ssqrts + "_" + schannel;
  TCanvas *ctot = new TCanvas(cname,cname);
  ctot->SetGrid();

  TString outname = "sigFigs" + ssqrts +"/eff_" + sprocess + "_" + schannel + "_" + sjes;
  if (!useNewGGHPowheg) outname+="_oldPwg";

  totgrEff->Fit(polyFunctot,"Rt"); 
  TString xaxisText = "m_{" + schannel + "}";
  totgrEff->GetXaxis()->SetTitle(xaxisText);
  TString yaxisText = "Efficiency, " + sprocess + ", " + schannel;
  totgrEff->GetYaxis()->SetTitle(yaxisText);
  totgrEff->SetMinimum(0.0);
  totgrEff->SetMaximum(1.0);
  if (process>=3) totgrEff->SetMaximum(0.0035);
  totgrEff->Draw("AP");
  polyFunctot->Draw("sames");
  ctot->Print(outname+".eps");
  //ctot->Print(outname+".png"); // Does not work in batch?
  ctot->Print(outname+".pdf"); 
  //ctot->Print(outname+".root"); 
  ftot->cd();
  totgrEff->Write("TotalEfficiency");
  ftot->Close();

  cout << endl;
  cout << "------- Parameters for " << sprocess << " " << schannel << " sqrts=" << sqrts << endl;
  cout << "   a1 = " << polyFunctot->GetParameter(0) << endl;
  cout << "   a2 = " << polyFunctot->GetParameter(1) << endl;
  cout << "   a3 = " << polyFunctot->GetParameter(2) << endl;
  cout << "   a4 = " << polyFunctot->GetParameter(3) << endl;
  cout << "   b1 = " << polyFunctot->GetParameter(4) << endl;
  cout << "   b2 = " << polyFunctot->GetParameter(5) << endl;
  cout << "   b3 = " << polyFunctot->GetParameter(6) << endl;
  cout << "   g1 = " << polyFunctot->GetParameter(7) << endl;
  cout << "   g2 = " << polyFunctot->GetParameter(8) << endl;
  cout << "   g3 = " << polyFunctot->GetParameter(9) << endl;
  cout << "---------------------------" << endl << endl;


  // Create card fragments using new powheg samples
  string oftotprocess;
  if (process==ggH) oftotprocess="";
  else oftotprocess=sprocess;

  if (process==ggH) {
    oftot << endl;
    oftot << "## signal efficiency ##" << endl;
  }
  oftot << "signalEff " << oftotprocess << "a1  " << polyFunctot->GetParameter(0) << endl;
  oftot << "signalEff " << oftotprocess << "a2  " << polyFunctot->GetParameter(1) << endl;
  oftot << "signalEff " << oftotprocess << "a3  " << polyFunctot->GetParameter(2) << endl;
  oftot << "signalEff " << oftotprocess << "a4  " << polyFunctot->GetParameter(3) << endl;
  oftot << "signalEff " << oftotprocess << "b1  " << polyFunctot->GetParameter(4) << endl;
  oftot << "signalEff " << oftotprocess << "b2  " << polyFunctot->GetParameter(5) << endl;
  oftot << "signalEff " << oftotprocess << "b3  " << polyFunctot->GetParameter(6) << endl;
  oftot << "signalEff " << oftotprocess << "g1  " << polyFunctot->GetParameter(7) << endl;
  oftot << "signalEff " << oftotprocess << "g2  " << polyFunctot->GetParameter(8) << endl;
  oftot << "signalEff " << oftotprocess << "g3  " << polyFunctot->GetParameter(9) << endl;
  oftot << endl;
  oftot.close();

  
  cname = "eff" + sprocess + ssqrts + "_" + schannel + "_ratio";
  TCanvas *crat = new TCanvas(cname,cname);
  crat->SetGrid();

  outname = "sigFigs" + ssqrts +"/eff_" + sprocess + "_" + schannel + "_" + sjes + "_ratio";
  if (!useNewGGHPowheg) outname+="_oldPwg";

  TF1 *ratiofit=0;
  if (process==ggH || process==qqH) ratiofit = new TF1("ratiofit","([0]+[1]*x+[2]*x*x)",110.,xMax);
  if (process==ZH || process==WH || process==ttH ) ratiofit = new TF1("ratiofit","([0]+[1]*x)",110.,xMax);

  ratgrEff->Fit(ratiofit,"Rt");
  ratgrEff->GetXaxis()->SetTitle(xaxisText);
  TString yaxisratio = "Dijet ratio, " + sprocess + ", " + schannel;
  ratgrEff->GetYaxis()->SetTitle(yaxisratio);
  ratgrEff->SetMinimum(0.0);
  ratgrEff->SetMaximum(1.0);
  ratgrEff->Draw("AP");
  crat->Print(outname+".eps");
  //crat->Print(outname+".png"); // Does not work in batch?
  crat->Print(outname+".pdf");
  //crat->Print(outname+".root");
  fratio->cd();
  ratgrEff->Write("Ratio");
  fratio->Close();
  
  cout << endl;
  cout << "------- Parameters for " << sprocess << " " << schannel << " sqrts=" << sqrts << endl;
  cout << "   a1 = " << ratiofit->GetParameter(0) << endl;
  cout << "   a2 = " << ratiofit->GetParameter(1) << endl;
  if (process==ggH || process==qqH) cout << "   a3 = " << ratiofit->GetParameter(2) << endl;
  cout << "---------------------------" << endl << endl;

  if (process==ggH) {
    ofrat<<"## jet tagged/untagged ratio"<<endl;
    ofrat<<"jetYieldRatio "<<fitJys->GetParameter(0)<<"+("<<fitJys->GetParameter(1)<<"*@0)+("<<fitJys->GetParameter(2)<<"*@0*@0)+("<<fitJys->GetParameter(3)<<"*@0*@0*@0)"<< endl <<endl;
    ofrat << "## signal efficiency ratios ##" << endl;
  }
  ofrat << "signalEff tagged_" << sprocess << "_ratio " << ratiofit->GetParameter(0) << "+(" << ratiofit->GetParameter(1) << "*@0)";
  if (process==ggH || process==qqH) ofrat << "+(" << ratiofit->GetParameter(2) << "*@0*@0)" << endl;
  else if (process==ZH || process==WH ) ofrat << endl;
  else if (process==ttH) ofrat << endl << endl;
  ofrat.close();

  // deviations
  cout << "Deviations..." << endl;
  double maxResidual=0;
  for (int i = 0; i < nPoints; i++){
    double eval = polyFunctot->Eval(masses[i]);
    double residual = (eval - totefficiencyVal[i]);
    maxResidual = max(maxResidual,fabs(residual));
    if (verbose)    cout << "For mass, " << masses[i] << ": measured value is " << totefficiencyVal[i] << " and difference from function is " << residual <<endl;
  }
  cout << "Largest residual= " << maxResidual << endl;

  delete fitJys;
  delete myCSW;
  delete polyFunctot;
  delete ratiofit;
}
示例#24
0
void rateStudy() {
  const int NRUNS = 25;
  const int NCH = 32;
  const int NBINS = 32;

  TCanvas* c1 = new TCanvas("c1", "c1", 800, 600);

  TMultiGraph *mg = new TMultiGraph();

  TLegend *legend=new TLegend(0.65,0.15,0.88,0.55);
  legend->SetNColumns(4);
  legend->SetFillColor(0);

  TH1F* hRate = new TH1F("hRate", "hist", 32.0, 0, 8.0);

  //Color buffer
  const int NCOLORS = 32;
  int color[NCOLORS] = {73, 2, 3, 4, 99, 6, 7, 8, 9, 12, 28, 32, 34,
                        28, 50, 51, 56, 58, 88, 99, 1, 208, 209,
                        218, 212, 210, 221, 224, 225, 226, 227, 228 };

  ifstream fin;
  //fin.open("runlist.txt");
  fin.open("filter_runlist.txt");

  string line = "";

  TFile* out = new TFile("outtemp.root", "REACREATE");
  TH1F* h = new TH1F("h","hist", NBINS, 0, NBINS);
  TF1* pois = new TF1("pois","[0]*TMath::Poisson(x,[1])",0,50);
  TF1* ppp = new TF1("ppp","[0]*TMath::Power(0.5,x*[1])",0.01,1.0);


  for (int ch = 0; ch < NCH; ++ch) {

    //if ( ch==26 || ch==27 )
    //continue;

    //Graph points and errors
    Double_t x[NRUNS];
    Double_t y[NRUNS];
    Double_t errX[NRUNS] = {0};
    Double_t errY[NRUNS] = {0};

    int fileCounter = 0;
    while(getline(fin, line)) {
      vector<double> data = parse(line);
      stringstream filePath;
      filePath << "pmtratestudy/run" << data[0] << "*.root";
      cout << "opening file at " << filePath.str() << endl;
      cout << "file counter: " << fileCounter << " channel=" << ch << endl;
      //TFile* f = new TFile(filePath.str().c_str());
      //TTree* t = (TTree *)f->Get("eventtree");
      TChain* t = new TChain("eventtree");
      t->Add( filePath.str().c_str() );
      out->cd();

      x[fileCounter] = data[1];

      int nfires[NCH] = {0};
      int samples = 0;
      float chmax = 0.0;
      t->SetBranchAddress("nfires", &nfires);
      t->SetBranchAddress("samples", &samples);
      t->SetBranchAddress("chmax", &chmax);
      
      h->Reset();
      
      int nentries = t->GetEntries();
      for (int entry = 0; entry < nentries; ++entry) {
        t->GetEntry(entry);
        if (chmax < 100.0) {
          h->Fill(nfires[ch]);
        }
      }


      
      pois->SetParameter(0,1);
      pois->SetParameter(1, h->GetMean());

      h->Fit(pois,"RQ","",0,50);
      //TF1 *myfit = (TF1 *)h->GetFunction("pois");
      TF1 *myfit = (TF1 *)pois;
      Double_t lambda = myfit->GetParameter(1);  
      h->Draw();
      stringstream histFileName;
      histFileName << "hist/h" << data[0] << "_ch" << ch << ".png";
      c1->SaveAs(histFileName.str().c_str());
      //Graph with poisson method
#if 1
      y[fileCounter] = lambda / ((samples - 1) * 15.625E-6);
      errY[fileCounter] = myfit->GetParError(1) / ((samples - 1) * 15.625E-6);
#endif
      //Graph with mean method
#if 0
      y[fileCounter] = h->GetMean() / ((samples - 1) * 15.625E-6);
      errY[fileCounter] = h->GetMeanError() / ((samples - 1) * 15.625E-6);
#endif
      cout << x[fileCounter] << ", " << y[fileCounter] 
           << " | " << (samples - 1) << endl;
      delete t;
      //f->Close();
      fileCounter++;
    } 

    ppp->SetParameter(0,1);
    ppp->SetParameter(1,0.4);
     
    TGraphErrors* gr = new TGraphErrors(NRUNS, x, y, errX, errY);
    gr->SetLineColor(color[ch % NCOLORS]);
    cout << "color: " << color[ch % NCOLORS] << endl;
    gr->SetLineWidth(2);
    gr->SetMarkerStyle(7);
    gr->Fit("ppp","R0","Q0",0.045,2.0);
    TF1 *afit = (TF1 *)gr->GetFunction("ppp");
    Double_t aRate = 1/afit->GetParameter(1);  
    if (aRate > 0) {
      hRate->Fill(aRate);
    }
    gr->GetXaxis()->SetTitle("Run Date");
    gr->GetYaxis()->SetTitle("Rate [kHz]");

    stringstream entryName, fileName;
    entryName << "Channel" << ch;
    gr->SetTitle(entryName.str().c_str());
    fileName << "plots/" << ch << ".png";
    legend->AddEntry(gr, entryName.str().c_str());
    gr->Draw("alp");
    c1->SaveAs(fileName.str().c_str());
    mg->Add(gr);
    cout << "added plot to mg\n";
    fin.clear();
    fin.seekg(0, ios::beg);
  } // loop over channel
  hRate->Draw();
  hRate->Fit("gaus");
  c1->SaveAs("hrate.pdf");
  mg->Draw("alp");
  mg->GetXaxis()->SetTitle("Days since first run");
  mg->GetYaxis()->SetTitle("Rate [kHz]");
  mg->SetTitle("All channels: Rate vs. Days since first Run");

  legend->Draw();
  c1->SaveAs("mg.pdf");
  
}
void howManyPe7_17_evening(){
  cout << "Starting" << endl;
  const int numRuns = 6;
  const char* files[numRuns] = {
				"../../crunchedFiles/run_00480_crunched.root",
				"../../crunchedFiles/run_00481_crunched.root",
				"../../crunchedFiles/run_00482_crunched.root",
				"../../crunchedFiles/run_00483_crunched.root",
				"../../crunchedFiles/run_00484_crunched.root",
				"../../crunchedFiles/run_00485_crunched.root",
				};

				
  
  gStyle->SetOptFit(1);
  gStyle->SetOptStat(0);
  
  double pes[16];
  double peErrors[16];
  double gains[16];
  double gainErrors[16];
  
  TCanvas* c1 = new TCanvas();
  
  cout << "starting loop " << endl;

  for(int row = 2; row < 6; ++row){
    for(int col = 2; col < 6; ++col){
    
      vector<double> means;
      vector<double> sigs;
      vector<double> meanErrs;
      vector<double> sigErrs;
      for (int i = 0; i < numRuns; ++i){
	TFile* f = new TFile(files[i]);
	TTree* t = (TTree*) f->Get("t");
	t->Draw(Form("sipm%i%i.energy>>histo%i%i", row,col,row,col),Form("sipm%i%i.valid",row,col));

	TH1F* h = (TH1F*) gROOT->FindObject(Form("histo%i%i",row,col));
	h->Fit("gaus","0q");
	if(h->GetFunction("gaus")->GetParameter(1)>250){
	  means.push_back(h->GetFunction("gaus")->GetParameter(1));
	  sigs.push_back(h->GetFunction("gaus")->GetParameter(2));
	  meanErrs.push_back(h->GetFunction("gaus")->GetParError(1));
	  sigErrs.push_back(h->GetFunction("gaus")->GetParError(2));
	}

      }
  
      vector<double> variances;
      vector<double> varianceErrors;
  
      for(int i = 0; i < means.size(); ++i){
	variances.push_back(sigs[i]*sigs[i]);
	varianceErrors.push_back(2*sigs[i]*sigErrs[i]);
      }

    
      if(means.size() > 1){

	TGraphErrors* linGraph = new TGraphErrors(means.size(), &means[0], &variances[0], 
						&meanErrs[0], &varianceErrors[0]);
	TGraphErrors* quadGraph = new TGraphErrors(means.size(), &means[0], &variances[0], 
						 &meanErrs[0], &varianceErrors[0]);
      

	linGraph->SetMarkerStyle(20);
	linGraph->Fit("pol1","q");
	linGraph->SetTitle(Form("SiPM %i%i", row, col));
	linGraph->GetFunction("pol1")->SetLineColor(kBlue);
	linGraph->GetXaxis()->SetTitle("Mean");
	linGraph->GetYaxis()->SetTitle("#sigma^{2}");
	quadGraph->SetMarkerStyle(20);
	quadGraph->Fit("pol2","q");
	quadGraph->GetFunction("pol2")->SetLineColor(kRed);
       
	linGraph->Draw("ap");
	quadGraph->Draw("psame");

	UInt_t index = (row-2)*4 + (col-2);
    
	pes[index] = 1.0/linGraph->GetFunction("pol1")->GetParameter(1)*means[0];
	gains[index] = linGraph->GetFunction("pol1")->GetParameter(1);
	gainErrors[index] = linGraph->GetFunction("pol1")->GetParError(1);
	peErrors[index] = TMath::Sqrt((1/gains[index]*meanErrs[0])*(1/gains[index]*meanErrs[0])+
				      (means[0]/(gains[index]*gains[index])*gainErrors[index])*(means[0]/(gains[index]*gains[index])*gainErrors[index]));

/*
	pes[drs] = 1.0/quadGraph->GetFunction("pol2")->GetParameter(1)*means[0];
	gains[drs] = quadGraph->GetFunction("pol2")->GetParameter(1);
	gainErrors[drs] = quadGraph->GetFunction("pol2")->GetParError(1);
	peErrors[drs] = TMath::Sqrt((1/gains[drs]*meanErrs[0])*(1/gains[drs]*meanErrs[0])+
	(means[0]/(gains[drs]*gains[drs])*gainErrors[drs])*(means[0]/(gains[drs]*gains[drs])*gainErrors[drs]));
*/	


	  delete linGraph;
	  delete quadGraph;
      }

      else if (means.size()==1){
	UInt_t index = (row-2)*4 + (col-2);
	UInt_t mean = means[0];
	UInt_t sig = sigs[0];
	UInt_t meanErr = meanErrs[0];
	UInt_t sigErr = sigErrs[0];
	
	pes[index] = mean*mean/sig/sig;
	gains[index] = mean/pes[index];
	gainErrors[index] = TMath::Sqrt((2*sig/mean*sigErr)*(2*sig/mean*sigErr)+(sig*sig/mean/mean*meanErr)*(sig*sig/mean/mean*meanErr));
	peErrors[index] = TMath::Sqrt((2*mean/sig/sig*sigErr)*(2*mean/sig/sig*sigErr)+(2*mean*mean/sig/sig/sig*sigErr)*(2*mean*mean/sig/sig/sig*sigErr));
      }
      
      else{
	UInt_t index = (row-2)*4 + (col-2);
	pes[index] = -1;
	gains[index] = -1;
	peErrors[index] = -1;
	gainErrors[index] = -1;
      }
       
    }
  }
	


  for(int i = 0; i <16; ++i){
    cout << "SiPM " << 2+i/4 << 2+i%4 << " --- " 
	 << "p1 : " << gains[i] << ", "
	 << pes[i] << " photoelectrons at open filter, " << gains[i]*pes[i] << "calibration constant." << endl;
  }

  
  TGraphErrors* peGainGraph = new TGraphErrors(16, gains, pes, gainErrors, peErrors);

  peGainGraph->SetMarkerStyle(20);  
  peGainGraph->GetXaxis()->SetTitle("gain");
  peGainGraph->GetYaxis()->SetTitle("PE at open filter");
  c1->SetGridx();
  c1->SetGridy();
  peGainGraph->Draw("ap");
  cout << "drew graph " << endl;

  TCanvas* c2 = new TCanvas();
  TH2F* peMap = new TH2F("pes","PE Map", 4,0,4,4,0,4);
  for(int i = 0; i < 16; ++i){
    peMap->Fill(.5+i%4, 3.5-i/4, pes[i]);
  }
  peMap->GetXaxis()->SetLabelOffset(99);
  peMap->GetYaxis()->SetLabelOffset(99);
  c2->SetTickx(0);
  c2->SetTicky(0);
  
  peMap->Draw("TEXT");

  TCanvas* c3 = new TCanvas();
  TH2F* gainMap = new TH2F("gains","Gain Map", 4,0,4,4,0,4);
  for(int i = 0; i < 16; ++i){
    gainMap->Fill(.5+i%4, 3.5-i/4, gains[i]);
  }
    
  gainMap->GetXaxis()->SetLabelOffset(99);
  gainMap->GetYaxis()->SetLabelOffset(99);
  gainMap->Draw("TEXT");

}
示例#26
0
void profileDistributions(TString dist)
{
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);
  gStyle->SetPalette(1);

  TFile *inF=TFile::Open("~/work/top_539/plotter.root");
  TFile *inSystF=TFile::Open("~/work/top_539/plotter_syst.root");

  bool isPhi(dist.Contains("phi"));
  TString profs[]={dist,
		   dist+"toward",
		   dist+"transverse",
		   dist+"away"};
  const size_t nprofs= isPhi ? 1 : sizeof(profs)/sizeof(TString);


  Int_t colors[]={1,kBlue,kRed,kGreen-3};

  TString cats[]={"inclusive","away","transverse","toward"};

  /*
  TFile *inNomF=inF;
  TString nomTTbar="t#bar{t}";
  TString nomTTbarTitle="MG+PY";
  
  //TString systList[]={"t#bar{t}systmcatnlo"};
  //TString systLabels[]={"MC@NLO+HW"};
  
  //TString systList[]={"t#bar{t}systq2down","t#bar{t}systq2up"};
  //TString systLabels[]={"-Q^{2}","+Q^{2}"};

  //TString systList[]={"t#bar{t}systmepsdown","t#bar{t}systmepsup"};
  // TString systLabels[]={"-ME-PS","+ME-PS"};
  */

  TFile *inNomF=inSystF;
  TString nomTTbar="t#bar{t}systtunep11";
  TString nomTTbarTitle="P11";
  TString systList[]={"t#bar{t}systtunep11nocr","t#bar{t}systtunep11tev"};
  TString systLabels[]={"P11-noCR","P11TeV"};


  Int_t systColors[]={1,kAzure,kRed-6,kGreen+3};

  const size_t nSysts=sizeof(systList)/sizeof(TString);

  TString ch[]={"emu"};
  const size_t nch=sizeof(ch)/sizeof(TString);
  
  for(size_t ich=0; ich<nch; ich++)
    {
      TCanvas *c=new TCanvas("c"+ch[ich]+dist,"c"+ch[ich]+dist,800,800); c->SetTopMargin(0); c->SetBottomMargin(0);
      c->Divide(1,nprofs);
      
      TCanvas *cratios=new TCanvas("cratios"+ch[ich]+dist,"cratios"+ch[ich]+dist,800,800); cratios->SetTopMargin(0); cratios->SetBottomMargin(0);
      cratios->Divide(1,nprofs);

      TCanvas *cproj=new TCanvas("cproj"+ch[ich]+dist,"cproj"+ch[ich]+dist,600,600);
      TLegend *dataprojLeg=new TLegend(0.5,0.9,0.6,0.7,"Data","brNDC");
      TLegend *mcprojLeg=new TLegend(0.7,0.9,0.92,0.7,"MC","brNDC");
      
      for(size_t i=0; i<nprofs; i++)
	{
	  TH2 *bckgMC   = (TH2 *) inF->Get("Z#rightarrow ll/"+ch[ich]+"_"+profs[i]); 
	  bckgMC->Add( (TH2 *) inF->Get("VV/"+ch[ich]+"_"+profs[i]) );
	  bckgMC->Add( (TH2 *) inF->Get("Single top/"+ch[ich]+"_"+profs[i]) );
	  bckgMC->Add( (TH2 *) inF->Get("W+jets-multijets/"+ch[ich]+"_"+profs[i]) );
	  
	  //build the total MC with signal alternatives
	  TH2 *MC = (TH2 *) inNomF->Get(nomTTbar+"/"+ch[ich]+"_"+profs[i]) ; 
	  Double_t totalTTbar(MC->Integral());
	  MC->Add(bckgMC);
	  MC->SetDirectory(0);
	  MC->Sumw2();	  
	  
	  std::vector<TH2 *> systMC;
	  for(size_t isyst=0; isyst<nSysts; isyst++)
	    {
	      TH2F *h=(TH2F *)inSystF->Get(systList[isyst]+"/"+ch[ich]+"_"+profs[i]) ;
	      h->Scale(totalTTbar/h->Integral());
	      h->Add(bckgMC);
	      h->Sumw2();
	      h->SetDirectory(0);
	      systMC.push_back(h);
	    }
		

	  //get the data
	  TH2 *Data = (TH2 *) inF->Get("data/"+ch[ich]+"_"+profs[i]);            
	  Data->SetDirectory(0);
	  Data->Sumw2();

	  TGraphErrors *MCProf   = new TGraphErrors(MC->ProfileX());    MCProf->SetMarkerStyle(24);   MCProf->SetFillStyle(0); MCProf->SetName(ch[ich]+profs[i]+"mc");
	  TGraphErrors *DataProf = new TGraphErrors(Data->ProfileX());  DataProf->SetMarkerStyle(20); DataProf->SetFillStyle(0); DataProf->SetName(ch[ich]+profs[i]+"data");
	  
	  //build data/MC scale factors
	  std::vector<TGraphErrors *> data2mcProfs;
	  for(size_t isyst=0; isyst<=systMC.size(); isyst++)
	    {
	      TGraphErrors *prof= (isyst==0 ? MCProf : new TGraphErrors(systMC[isyst-1]->ProfileX()));
	      TString baseName(ch[ich]+profs[i]);
	      if(isyst) baseName += systList[isyst];
	      prof = (TGraphErrors *) prof->Clone(baseName+"data2mc");
	      for(int ip=0; ip<DataProf->GetN(); ip++)
		{
		  Double_t x,y,ydata,y_err,ydata_err;
		  prof->GetPoint(ip,x,y);         y_err=prof->GetErrorY(ip);
		  DataProf->GetPoint(ip,x,ydata); ydata_err=DataProf->GetErrorY(ip);
		  if(y<=0) continue;
		  prof->SetPoint(ip,x,ydata/y);
		  prof->SetPointError(ip,0,sqrt(pow(ydata*y_err,2)+pow(ydata_err*y,2))/pow(y,2));
		}
	      prof->SetFillColor(systColors[isyst]);
	      prof->SetFillStyle(3001+isyst%2);
	      prof->SetTitle( isyst==0 ? nomTTbarTitle : systLabels[isyst-1] );
	      //prof->SetMarkerStyle(24);   prof->SetFillStyle(3001); prof->SetMarkerColor(1+isyst); prof->SetMarkerColor(1+isyst); prof->SetLineColor(1+isyst);
	      data2mcProfs.push_back(prof);
	    }

	  
	  TH1D *MCProjY=MC->ProjectionY();
	  MCProjY->Scale(1./MCProjY->Integral()); 
	  TGraphErrors *MCProj   = new TGraphErrors(MCProjY);    MCProj->SetMarkerStyle(24); MCProj->SetFillStyle(0);  MCProj->SetName(ch[ich]+profs[i]+"projmc");
	  TH1D *DataProjY=Data->ProjectionY();
	  DataProjY->Scale(1./DataProjY->Integral());
	  TGraphErrors *DataProj = new TGraphErrors(DataProjY);  DataProj->SetMarkerStyle(20); DataProj->SetFillStyle(0); DataProj->SetName(ch[ich]+profs[i]+"projdata");
	  MCProj->SetLineColor(colors[i]);   MCProj->SetMarkerColor(colors[i]);   MCProj->SetFillColor(colors[i]); MCProj->SetFillStyle(1001);
	  DataProj->SetLineColor(colors[i]); DataProj->SetMarkerColor(colors[i]);   DataProj->SetFillColor(colors[i]);
	  
	  TPad *p=(TPad *)cproj->cd();
	  p->SetLeftMargin(0.15);
	  p->SetRightMargin(0.02);
	  p->SetTopMargin(0.05);
	  p->SetLogy();
	  MCProj->SetFillStyle(0);
	  MCProj->Draw(i==0 ? "al3" : "l3");
	  MCProj->GetYaxis()->SetRangeUser(1e-5,1.0);
	  MCProj->GetXaxis()->SetTitle( MC->GetYaxis()->GetTitle() );
	  MCProj->GetYaxis()->SetTitle( "1/N dN/dx" );
	  MCProj->GetYaxis()->SetTitleOffset(1.8);
	  DataProj->Draw("p");
	  std::pair<float,int> chi2=computeChiSquareFor(DataProj,MCProj);
	  char buf[200];
	  sprintf(buf,"#scale[0.7]{#chi^{2}/ndof=%3.1f}", chi2.first/chi2.second );
	  dataprojLeg->AddEntry(DataProj,buf,"p");
	  mcprojLeg->AddEntry(MCProj,cats[i],"l");
	  if(i==0) drawCMSHeader(ch[ich]);
	  

	  p=(TPad *)c->cd(i+1);
	  if(i<nprofs-1) p->SetBottomMargin(0.01);
	  if(i>0) p->SetTopMargin(0);
	  if(i==0)p->SetTopMargin(0.1);
	  if(i==nprofs-1) p->SetBottomMargin(0.15);
	  TGraphErrors *frame=DataProf;
	  frame->Draw("ap");
	  //frame->GetYaxis()->SetRangeUser(0.54,1.46);
	  frame->GetXaxis()->SetTitle(MC->GetXaxis()->GetTitle());
	  //frame->GetXaxis()->SetRangeUser(0,4.75);
	  TString yTit("<"); yTit+=MC->GetYaxis()->GetTitle(); yTit +=">";
	  frame->GetYaxis()->SetTitle(yTit);
	  frame->GetYaxis()->SetLabelSize(0.07);
	  frame->GetYaxis()->SetTitleSize(0.09);
	  frame->GetYaxis()->SetTitleOffset(0.5);
	  frame->GetXaxis()->SetLabelSize(0.07);
	  frame->GetXaxis()->SetTitleSize(0.09);
	  frame->GetXaxis()->SetTitleOffset(0.7);
	  //p->SetGridy();
	  //DataProf->Draw("p");
	  MCProf->Draw("p");
	  if(i==0)
	    {
	      drawCMSHeader(ch[ich],0.08);

	      TLegend *leg=new TLegend(0.6,0.95,1.0,0.99);
	      leg->SetBorderSize(0);
	      leg->SetFillStyle(0);
	      leg->SetTextFont(42);
	      leg->SetTextSize(0.09);
	      leg->AddEntry(DataProf,"data","p");
	      leg->AddEntry(MCProf,"simulation","p");
	      leg->SetNColumns(2);
	      leg->Draw();
	    }

	  TPaveText *pt=new TPaveText(0.15,0.5,0.8,0.85,"brNDC");
	  pt->SetBorderSize(0);
	  pt->SetFillStyle(0);
	  pt->SetTextAlign(13);
	  pt->SetTextFont(42);
	  pt->SetTextColor(kBlue);
	  pt->SetTextSize(0.08);
	  pt->AddText("[ "+cats[i]+" ]");
	  if(i==0)
	    {
	      pt->AddText("p_{T}>0.5 GeV");
	      pt->AddText("|#eta|<2.1");
	    }
	  pt->Draw();


	  p=(TPad *) cratios->cd(i+1);
	  if(i<nprofs-1) p->SetBottomMargin(0.01);
	  if(i>0) p->SetTopMargin(0);
	  if(i==0)p->SetTopMargin(0.1);
	  if(i==nprofs-1) p->SetBottomMargin(0.15);
	  frame=data2mcProfs[0];
	  frame->Draw("a3");
	  TLine *l=new TLine(frame->GetXaxis()->GetXmin(),1,frame->GetXaxis()->GetXmax(),1);
	  l->Draw();
	  frame->GetYaxis()->SetRangeUser(0.54,1.46);
	  frame->GetXaxis()->SetTitle(MC->GetXaxis()->GetTitle());
	  frame->GetYaxis()->SetTitle("Data/Simulation");
	  frame->GetYaxis()->SetLabelSize(0.07);
	  frame->GetYaxis()->SetTitleSize(0.09);
	  frame->GetYaxis()->SetTitleOffset(0.5);
	  frame->GetXaxis()->SetLabelSize(0.07);
	  frame->GetXaxis()->SetTitleSize(0.09);
	  frame->GetXaxis()->SetTitleOffset(0.7);
	  //p->SetGridy();
	  for(size_t ip=1; ip<data2mcProfs.size(); ip++) data2mcProfs[ip]->Draw("3");
	  if(i==0)
	    {
	      drawCMSHeader(ch[ich],0.08);

	      TLegend *leg=new TLegend(0.6,0.94,1.0,0.98);
	      leg->SetBorderSize(0);
	      leg->SetFillStyle(0);
	      leg->SetTextFont(42);
	      leg->SetTextSize(0.09);
	      leg->SetNColumns(data2mcProfs.size());
	      for(size_t ip=0; ip<data2mcProfs.size(); ip++)
		leg->AddEntry(data2mcProfs[ip],data2mcProfs[ip]->GetTitle(),"f");
	      leg->Draw();
	    }
	  
	  pt=new TPaveText(0.12,0.65,0.8,0.9,"brNDC");
	  pt->SetBorderSize(0);
	  pt->SetFillStyle(0);
	  pt->SetTextAlign(13);
	  pt->SetTextFont(42);
	  pt->SetTextColor(kBlue);
	  pt->SetTextSize(0.08);
	  pt->AddText("[ "+cats[i]+" ]");
	  if(i==0)
	    {
	      pt->AddText("p_{T}>0.5 GeV");
	      pt->AddText("|#eta|<2.1");
	    }
	  pt->Draw();
	}

      cproj->cd();
      dataprojLeg->SetFillStyle(0);
      dataprojLeg->SetBorderSize(0);
      dataprojLeg->SetTextFont(42);
      dataprojLeg->SetTextSize(0.03);
      dataprojLeg->Draw();
      mcprojLeg->SetFillStyle(0);
      mcprojLeg->SetBorderSize(0);
      mcprojLeg->SetTextFont(42);
      mcprojLeg->SetTextSize(0.03);
      mcprojLeg->Draw();


      TString pf(".png");
      c->SaveAs(outDir+c->GetName()+pf);
      cproj->SaveAs(outDir+cproj->GetName()+pf);
      cratios->SaveAs(outDir+cratios->GetName()+pf);

    }

  inF->Close();
  inSystF->Close();
}
示例#27
0
map<int,vector<double> > RPCChambersCluster::getReconstructedHits(vector<unsigned> vectorOfReferenceChambers, const int & timeWindow,const int & timeReference,bool & isVerticalTrack,map<int,double> & scintilatorsCoordinates,const bool & keepRecoTrack,TFile * fileForRecoTracks,const int & eventNum,const double & correlationFactor, const ESiteFileType & fileType){
  
  // 
  
  map<int,vector<double> > mapOfHits; //
  // the default value for Chi2goodness is 20 
  //double best_chi2goodnes_value = Chi2goodness+10 ; // this variable is used as reference so that it holds the best chi2 found for a track, so its used only a track with better chi2 to be accepted
  double currentBestCorrFact = -2;
  
  int lastFitPoint = 0;
  
  for (int i = 0 ; i < this->getNumberOfChambers() ; i++){
    this->getChamberNumber(i+1)->findAllClustersForTriggerTimeReferenceAndTimeWindow(timeReference,timeWindow,5);
    //cout  << "Chamber is " << i+1 << endl;
  }
  
  vector<vector<int> > vectorOfClusterNumberCombinations;  
  
  if (fileType == kIsCERNrawFile ){
    
    assert(vectorOfReferenceChambers.size() == 3 );
    
    lastFitPoint = 9;
    
    for ( int i = 0 ; i < this->getChamberNumber(vectorOfReferenceChambers[0])->getNumberOfClusters() ; i++ ){
      for( int j = 0 ; j < this->getChamberNumber(vectorOfReferenceChambers[1])->getNumberOfClusters() ; j++ ){
	for( int k = 0 ; k < this->getChamberNumber(vectorOfReferenceChambers[vectorOfReferenceChambers.size()-1])->getNumberOfClusters() ; k++ ){
	  
	  vector<int> singleCombination;
	  
	  singleCombination.push_back(i+1);
	  singleCombination.push_back(j+1);
	  singleCombination.push_back(k+1);
	  
	  for (int f = 0 ; f < singleCombination.size() ; f++){	  
	    if(this->getChamberNumber(vectorOfReferenceChambers[f])->getSizeOfCluster(singleCombination.at(f)) > 5 ) continue;	  
	    // don't insert combination if there is too big cluster. 
	  }
	  
	  vectorOfClusterNumberCombinations.push_back(singleCombination);
	  
	}
      }
    }
  }
  
  if (fileType == kIsBARCrawFile || fileType == kIsGENTrawFile ){
    // add implementation for BARC and Ghent stand . 
    lastFitPoint = 5;
    
    assert(vectorOfReferenceChambers.size() == 2);
    
    for ( int i = 0 ; i < this->getChamberNumber(vectorOfReferenceChambers[0])->getNumberOfClusters() ; i++ ){
      for( int j = 0 ; j < this->getChamberNumber(vectorOfReferenceChambers[1])->getNumberOfClusters() ; j++ ){
      
	vector<int> singleCombination;
	singleCombination.push_back(i+1);
	singleCombination.push_back(j+1);
	
	for (int f = 0 ; f < singleCombination.size() ; f++){
	  if(this->getChamberNumber(vectorOfReferenceChambers[f])->getSizeOfCluster(singleCombination.at(f)) > 5 ) continue;
	  // don't insert combination if there is too big cluster. 
	}
	
	vectorOfClusterNumberCombinations.push_back(singleCombination);
      
      }
    }
  }
  
  string topScintToString, botScintToString;
  
  for (int combinationsVectorElement = 0 ; combinationsVectorElement < vectorOfClusterNumberCombinations.size() ; combinationsVectorElement ++){
    
    // the partition logic start  here - track could pass more than one partition
    
    int direction = 0 ; // direction should describe how the partition changes from one reference chamber to another. It 
    vector<int> RefChamberClusterPartition;
    bool positive = false;
    bool negative = false;
    int partitionPenetrated = 1;
    
    // the Y coordinate is the partition number (1 2 or 3 - A B or C)
    
    vector<int> clusterNum = vectorOfClusterNumberCombinations.at(combinationsVectorElement);
    
    for (int ii = 0; ii < clusterNum.size() ; ii++){
      RefChamberClusterPartition.push_back(this->getChamberNumber(vectorOfReferenceChambers[ii])->getXYCoordinatesOfCluster(clusterNum.at(ii)).at(1));
    }
    
    isVerticalTrack = true;
    
    for ( int ii = 0; ii < RefChamberClusterPartition.size() - 1 ; ii++ ){
      direction = (RefChamberClusterPartition.at(ii) - RefChamberClusterPartition.at(ii+1));
      if (direction != 0) { 
	direction = direction/abs(direction); 
	partitionPenetrated++;
      } // get only the sign ( +1 or -1)
      if (direction && direction == -1)  { positive = true; isVerticalTrack = false; }
      if (direction && direction == 1 )  { negative = true; isVerticalTrack = false; }
    }
    
    if ( positive && negative ) continue;
    // cannot have a track that goes in both direction
    
    /*
    TH1F * histXZ = new TH1F("fitHistogram","XZ plane",110,0,11);
    histXZ->GetYaxis()->SetRangeUser(-20,52);
    histXZ->SetMarkerColor(kBlue);
    histXZ->SetMarkerStyle(kCircle);
    histXZ->GetXaxis()->SetTitle("Shelf number");
    histXZ->GetYaxis()->SetTitle("Channel number");
    */
    
    TF1 * fitfunc = new TF1("FitTrack","[0]+x*[1]",0,lastFitPoint+1);
    
    TGraphErrors * graphXZ = new TGraphErrors();
    graphXZ->GetXaxis()->SetTitle("Shelf number");
    graphXZ->GetYaxis()->SetTitle("Channel number");
    //graphXZ->SetLineColor(0);
    graphXZ->SetMarkerColor(kBlack);
    graphXZ->SetMarkerStyle(kFullCircle);
    graphXZ->SetName("fit graph");
    graphXZ->SetTitle("XZ plane");
    graphXZ->GetXaxis()->SetTitle("Muon station");
    graphXZ->GetYaxis()->SetTitle("Channel number");
    
    fitfunc->SetLineColor(kBlue);        
    
    vector<double> coordinates;
    double xCoordinate = 0;
    int yCoordinate = 0;
    int zCoorinate = 0;
    
    
    for (int ii=0 ; ii < vectorOfReferenceChambers.size() ; ii++){
      
      coordinates = this->getChamberNumber(vectorOfReferenceChambers[ii])->getXYCoordinatesOfCluster(clusterNum[ii]);
      xCoordinate = coordinates.at(0);
      yCoordinate = coordinates.at(1);
      zCoorinate = 10*vectorOfReferenceChambers[ii];
      Double_t errorValue = this->getChamberNumber(vectorOfReferenceChambers[ii])->getSizeOfCluster(clusterNum[ii]);
//       histXZ->SetBinContent(zCoorinate,xCoordinate);  
//       histXZ->SetBinError(zCoorinate,errorValue/2);
      //cout << xCoordinate << " " << yCoordinate << endl;
      graphXZ->SetPoint(ii,vectorOfReferenceChambers[ii],xCoordinate);
      graphXZ->SetPointError(ii,0,errorValue/2);
    }
    
    Double_t params[2];
    graphXZ->Fit(fitfunc,"RFQ");
    fitfunc->GetParameters(params);
    
    //cout << "par1 " << params[0] << " par2 " << params[1] << " chi2 " << fitfunc->GetChisquare() << endl;
    // The resudials - difference between estimated fit value and the middle of the nearest cluster
    
    int prevReference = 0 , nextReference = 0 , prevReferencePartition = 0 , nextReferencePartition = 0; 
    bool currentChamberIsReference = false;
    int startCounter = 0, endCounter = 0;
    
    if ( abs(graphXZ->GetCorrelationFactor()) >= correlationFactor && abs(graphXZ->GetCorrelationFactor()) > currentBestCorrFact ) {
      // in case of only one partition, get the partition number of the first reference point
      currentBestCorrFact = abs(graphXZ->GetCorrelationFactor());
      
      int referenceChambersIncrementor = 0;
      bool negativeChannelNumberIsFound = false;
      
      // ---------
            
      for ( int currentChNumber = 0 ; currentChNumber < this->getNumberOfChambers() ; currentChNumber++ ) {
	// check where the chamber is according to the reference chambers
	vector<double> vectorOfpartitionsAndHit;
	double channelNum = fitfunc->Eval(currentChNumber+1);

	/** four cases 1. the chamber is before the first reference 2. the chamber is after the last reference 3. the chamber is between two references 4. the chamber is a reference */
	
	for(int refCheck = 0 ; refCheck < vectorOfReferenceChambers.size(); refCheck++){
	  // find the surounding references
	  if (currentChNumber+1 == vectorOfReferenceChambers.at(refCheck)){
	    currentChamberIsReference = true;
	    break;
	  }
	  if ( vectorOfReferenceChambers.at(refCheck) > currentChNumber+1 && refCheck == 0 ){
	    // its before the first reference chamber
	    nextReference = vectorOfReferenceChambers.at(refCheck);
	    nextReferencePartition = this->getChamberNumber(nextReference)->getXYCoordinatesOfCluster(clusterNum[refCheck]).at(1);
	    break;
	    
	  }
	  
	  if ( vectorOfReferenceChambers.at(refCheck) < currentChNumber+1 && refCheck == vectorOfReferenceChambers.size() - 1 ){
	    // its after the last chamber
	    prevReference = vectorOfReferenceChambers.at(refCheck);
	    prevReferencePartition = this->getChamberNumber(prevReference)->getXYCoordinatesOfCluster(clusterNum[refCheck]).at(1);
	    break;    
	  }
	  if ( vectorOfReferenceChambers.at(refCheck) < currentChNumber+1 && vectorOfReferenceChambers.at(refCheck+1) > currentChNumber+1 ){
	    // its between two references
	    prevReference = vectorOfReferenceChambers.at(refCheck) ;
	    nextReference = vectorOfReferenceChambers.at(refCheck+1);
	    prevReferencePartition = this->getChamberNumber(prevReference)->getXYCoordinatesOfCluster(clusterNum[refCheck]).at(1);
	    nextReferencePartition = this->getChamberNumber(nextReference)->getXYCoordinatesOfCluster(clusterNum[refCheck+1]).at(1);
	    break;    
	  }
	}
	
	// end of partition possibilities
	
	if(!currentChamberIsReference){
	  
	  if (nextReference && prevReference == 0){
	    if (positive){
	      prevReferencePartition = 1;      
	    }
	    if(negative){
	      prevReferencePartition = this->getChamberNumber(1)->getClones();      
	    }    
	  }
	  
	  if (prevReferencePartition && nextReferencePartition == 0){
	    if (positive){
	      nextReferencePartition = this->getChamberNumber(1)->getClones();      
	    }
	    if(negative){
	      nextReferencePartition = 1;      
	    }    
	  }
	  
	  if (partitionPenetrated == 1 ){
	    prevReferencePartition = yCoordinate;
	    nextReferencePartition = yCoordinate;    
	    
	    int firstRef = vectorOfReferenceChambers.at(0);
	    int lastRef = vectorOfReferenceChambers.at(vectorOfReferenceChambers.size() - 1);
	    int ccham =  currentChNumber+1;
	    
	    if(! (lastRef > ccham && firstRef < ccham) ){
	      // all partitions are possible, chambers are out of the reference scope
	      prevReferencePartition = this->getChamberNumber(1)->getClones(); 
	      nextReferencePartition = 1; // 3 in case of ecap chamber      
	    }
	  }
	  
	  if (positive){ startCounter = prevReferencePartition; endCounter = nextReferencePartition; }
	  else { startCounter = nextReferencePartition ; endCounter = prevReferencePartition ; }
	  
	  for (int currentCounter = startCounter ; currentCounter <= endCounter; currentCounter ++ ){
	    assert(currentCounter > 0 && currentCounter < 4);
	    vectorOfpartitionsAndHit.push_back(currentCounter);    
	  }
	}
	
	else{
	  vectorOfpartitionsAndHit.push_back(this->getChamberNumber(currentChNumber+1)->getXYCoordinatesOfCluster(clusterNum[referenceChambersIncrementor]).at(1));
	  referenceChambersIncrementor ++;
	}
	
	prevReference = 0 ; nextReference = 0 ; prevReferencePartition = 0 ; nextReferencePartition = 0; currentChamberIsReference = false;
	//cout << "Chamber " << l+1 << " " <<  coordinates.at(1) << " " << fitfunc->Eval(l+1) << " " << endl;
	
	int channelNumberToStore = channelNum;
	if (channelNumberToStore < 96/this->getChamberNumber(1)->getClones()){
	  channelNumberToStore += 1;
	} // add one to represent the fired channel, or none if the channel is on the right border
	
	vectorOfpartitionsAndHit.push_back(channelNumberToStore); // the last element is the number of the channel
	
	// Debug lines
	/**
	cout << "Chamber is " << currentChNumber+1 << " partitions " ;
	for (int thesize = 0 ; thesize < vectorOfpartitionsAndHit.size() - 1; thesize++){
	  cout << vectorOfpartitionsAndHit.at(thesize) << " " ;
	}
	
	cout << "channel " << vectorOfpartitionsAndHit.at(vectorOfpartitionsAndHit.size()-1) << endl;
	*/
	
	mapOfHits[currentChNumber+1] = vectorOfpartitionsAndHit;
	
      }      
      
      // ---------- scintilators coordinates estimate
      
      for (int scintNum = 0 ; scintNum < 31 ; scintNum++){
	if(this->getTriggerObjectNumber(1)->getChannel(scintNum+1)->hasHit() && vectorOfClusterNumberCombinations.size() == 1 ) {
	  if (scintNum < 10) { scintilatorsCoordinates[scintNum+1] = graphXZ->Eval(0); topScintToString = boost::lexical_cast<string>(scintNum+1); }
	  else { scintilatorsCoordinates[scintNum+1] = graphXZ->Eval(lastFitPoint+1); botScintToString = boost::lexical_cast<string>(scintNum+1); }
	}
      }      
    }
    
    // get only vertical tracks from the A partition if there are only two scint hits
    if (keepRecoTrack && isVerticalTrack && !mapOfHits.empty() && scintilatorsCoordinates.size() == 2){
      
      graphXZ->SetName(boost::lexical_cast<string>(eventNum).c_str());
      string partition;
      if (mapOfHits.find(vectorOfReferenceChambers.at(0))->second.at(0) == 1) partition = "A";
      else if (mapOfHits.find(vectorOfReferenceChambers.at(0))->second.at(0) == 2) partition = "B";
      else partition = "C";
      
      graphXZ->SetTitle(("Correlation factor is "+boost::lexical_cast<string>(graphXZ->GetCorrelationFactor()) + " trigger channels top: " + topScintToString + " bottom: " + botScintToString ).c_str());
      if(abs(graphXZ->GetCorrelationFactor()) >= correlationFactor) {
	
	string scintCombination="_"+topScintToString+"_"+botScintToString+"_"+partition;
	TDirectory * dir = fileForRecoTracks->GetDirectory(scintCombination.c_str(),true);
	
	if(!dir) {  
	  //fileForRecoTracks->ls();
	  fileForRecoTracks->mkdir(scintCombination.c_str()) ;
	  fileForRecoTracks->cd("");
	} 
	
	fileForRecoTracks->cd(scintCombination.c_str());
	//cout << fileForRecoTracks->GetPath() << endl;
      }
      else{ fileForRecoTracks->cd("") ; fileForRecoTracks->cd("badTracks") ; }
      
      graphXZ->Write(graphXZ->GetName(),TObject::kOverwrite);
      fileForRecoTracks->cd("");
      //fileForRecoTracks->Write(graphXZ->GetName(),TObject::kOverwrite);
    }
    
    fitfunc->Delete();
    //histXZ->Delete();
    graphXZ->Delete();
    
  }  
  
  return mapOfHits;
}
示例#28
0
void BDT_cuts_norm(){
    
    
    gROOT->ProcessLine(".L ~/cern/project/lhcbStyle.C");
    lhcbStyle();
    
    const std::string filename("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/normalisation_samples/Lb2JpsipK_2011_2012_signal_withbdt.root");
    const std::string treename = "withbdt";
    
    const std::string filenameMC("/afs/cern.ch/work/a/apmorris/private/cern/ntuples/new_tuples/normalisation_samples/Lb2JpsipK_MC_2011_2012_norm_withbdt.root");
    
    TFile* file = TFile::Open( filename.c_str() );
    if( !file ) std::cout << "file " << filename << " does not exist" << std::endl;
    TTree* tree = (TTree*)file->Get( treename.c_str() );
    if( !tree ) std::cout << "tree " << treename << " does not exist" << std::endl;
    
    TFile* fileMC = TFile::Open( filenameMC.c_str() );
    if( !fileMC ) std::cout << "file " << filenameMC << " does not exist" << std::endl;
    TTree* treeMC = (TTree*)fileMC->Get( treename.c_str() );
    if( !treeMC ) std::cout << "tree " << treename << " does not exist" << std::endl;
    
    
    // -- signal, mass shape
    RooRealVar Lambda_b0_DTF_MASS_constr1("Lambda_b0_DTF_MASS_constr1","m(J/#psi pK^{-})", 5550., 5700., "MeV/c^{2}"); 
    RooRealVar Jpsi_M("Jpsi_M","m(#mu#mu)", 3000., 3200., "MeV/c^{2}"); 
    RooRealVar chi_c_M("chi_c_M","m(J/#psi#gamma)", 3400., 3700., "MeV/c^{2}"); 
    RooRealVar mean("mean","mean", 5630., 5610., 5650.);
    RooRealVar sigma1("sigma1","sigma1", 10., 1., 100.);
    RooRealVar sigma2("sigma2","sigma2", 30.0, 5.0, 300.0);
    RooRealVar alpha1("alpha1","alpha1", 1.0, 0.5, 5.0);
    RooRealVar n1("n1","n1", 1.8, 0.2, 15.0);
    RooRealVar alpha2("alpha2","alpha2", -0.5, -5.5, 0.0);
    RooRealVar n2("n2","n2", 0.7, 0.2, 10.0);
    //RooRealVar bkgcat_chic("bkgcat_chic","bkgcat_chic", 0, 100);
    RooRealVar bdtg3("bdtg3", "bdtg3", -1.0, 1.0);
    RooRealVar frac2("frac2","frac2", 0.3, 0., 1.);
    
    RooGaussian gauss1("gauss1","gauss1", Lambda_b0_DTF_MASS_constr1, mean, sigma1);
    RooGaussian gauss2("gauss2","gauss2", Lambda_b0_DTF_MASS_constr1, mean, sigma2);
    RooCBShape cb1("cb1","cb1", Lambda_b0_DTF_MASS_constr1, mean, sigma1, alpha1, n1); 
    RooCBShape cb2("cb2","cb2", Lambda_b0_DTF_MASS_constr1, mean, sigma2, alpha2, n2); 
    RooAddPdf sig("sig", "sig", RooArgList(cb1, cb2), RooArgList( frac2 ));
    RooRealVar cbRatio("cbRatio","cb Ratio", 0.8, 0.1, 1.0);
    RooRealVar sigYield("sigYield","sig Yield", 4e2, 1e0, 1e6);
    RooRealVar bgYield("bgYield","bg Yield", 1e4, 1e0, 1e6);
    
    
    
    //put in values from fit_MC here <<--- DON'T FORGET TO CHANGE THESE IF THE FIT CHANGES!!!
    /*
    EXT PARAMETER                                INTERNAL      INTERNAL
  NO.   NAME      VALUE            ERROR       STEP SIZE       VALUE
   1  alpha1       2.18020e+00   2.85078e-02   1.38432e-04  -2.56034e-01
   2  alpha2      -2.79102e+00   6.74385e-02   1.51818e-04  -1.49177e-02
   3  cbRatio      3.07172e-01   1.49204e-02   1.72642e-04  -5.69984e-01
   4  mean         5.61985e+03   9.58397e-03   5.56682e-05  -9.66293e-02
   5  n1           1.49358e+00   8.14447e-02   2.09300e-04  -9.70542e-01
   6  n2           1.45276e+00   1.09864e-01   2.59028e-04  -8.39538e-01
   7  sigma1       8.46303e+00   1.32851e-01   2.86985e-05  -1.01453e+00
   8  sigma2       4.93976e+00   3.42842e-02   5.03572e-06  -1.44512e+00
    */
    alpha1.setVal( 2.18020e+00 );
    alpha2.setVal( -2.79102e+00 );
    n1.setVal( 1.49358e+00 );
    n2.setVal( 1.45276e+00 );
    frac2.setVal( 3.07172e-01 );
    sigma1.setVal( 8.46303e+00 );
    sigma2.setVal( 4.93976e+00 );
    
    alpha1.setConstant( true );
    alpha2.setConstant( true );
    frac2.setConstant( true );
    n1.setConstant( true );
    n2.setConstant( true );
    sigma1.setConstant( true );
    sigma2.setConstant( true );
    
    // -- bg, mass shape
    RooRealVar a1("a1","a1", -0.1, -0.5, 0.5);
    RooChebychev comb("comb","comb", Lambda_b0_DTF_MASS_constr1, a1);
    RooRealVar mean3("mean3","mean3", 5560., 5500., 5600.);
    RooRealVar sigma3("sigma3","sigma3", 5., 1., 10.);
    RooRealVar frac3("frac3","frac", 0.2, 0.0, 0.3);
    RooGaussian gauss3("gauss3","gauss3", Lambda_b0_DTF_MASS_constr1, mean3, sigma3);
    //RooAddPdf bg("bg","bg", RooArgList(comb), RooArgList(frac3));
    
    // -- add signal & bg
    RooAddPdf pdf("pdf", "pdf", RooArgList(sig, comb), RooArgList( sigYield, bgYield));  
    
    
    double efficiencies1[40];
    double efficiencies1_error[40];
    double bdt_cuts[40];
    double efficiencies2[40];
    double efficiencies2_error[40];
    double sideband_bg_val[40];
    
    double MC_pre = treeMC->GetEntries();
    
    double effvals[40];
    
    
    //loop starting here
    for(int i=0; i < 40; i=i+1) {
        double cut_val = -1.0 + i*0.05;
        //double cut_val = -1.0; // testing
        bdt_cuts[i] = cut_val;
        
        std::stringstream c;
        c << "bdtg3" << " >= " << cut_val;
        const std::string cut = c.str();
        
        //std::cout << cut;
    
        RooArgSet obs;
        obs.add(Lambda_b0_DTF_MASS_constr1);
        //obs.add(chi_c_Mp);
        //obs.add(mass_pK);
        obs.add(Jpsi_M);
        obs.add(chi_c_M);
        obs.add(bdtg3); 
    
        RooDataSet ds("ds","ds", obs, RooFit::Import(*tree), RooFit::Cut(cut.c_str())); 
    
        RooPlot* plot = Lambda_b0_DTF_MASS_constr1.frame();
    
        RooFitResult * result = pdf.fitTo( ds, RooFit::Extended() );
        
        double sig_val = sigYield.getVal();
        double bg_val = bgYield.getVal();
        double sig_error = sigYield.getError();
        double bg_error = bgYield.getError();
        
        double efficiency1 = (sig_val)/(sqrt(sig_val + bg_val));
        efficiencies1[i] = efficiency1;
        
        double efficiency1_error_sq = (pow(sig_error,2)/(sig_val+bg_val) + (pow(sig_val,2)*(pow(sig_error,2)+pow(bg_error,2))/(4*pow((sig_val+bg_val),3))));
        
        double efficiency1_error = sqrt(efficiency1_error_sq);
        efficiencies1_error[i] = efficiency1_error;
        
        /*
        double MC_post = treeMC->GetEntries(cut.c_str());
        
        double eff_val = MC_post/MC_pre; 
        
        //something here to get the sideband background count
        
        
        Lambda_b0_DTF_MASS_constr1.setRange("R", 5650., 5700.);
        RooFitResult * sideband = bg.fitTo( ds, RooFit::Range("R") );
        sideband->Print();
        
        Lambda_b0_DTF_MASS_constr1.setRange("R", 5650., 5700.);
        RooAbsReal* integral = pdf.createIntegral(Lambda_b0_DTF_MASS_constr1, RooFit::Range("R"));
        //std::cout << integral->getVal() << std::endl;
        //std::cout << integral->getError() << std::endl;
        //Double_t sideband_bg_val = integral->getVal();
        //double sideband_bg_error = integral->getError();
        
        std::stringstream r;
        r << "bdtg3" << " >= " << cut_val << " && Lambda_b0_DTF_MASS_constr1 >= 5650 && Lambda_b0_DTF_MASS_constr1 <= 5700";
        const std::string cut2 = r.str();
        
        double integ = tree->GetEntries(cut2.c_str());
        //double integ = integral->getVal();
        
        double efficiency2 = eff_val/(5./2. + sqrt(integ));
        efficiencies2[i] = efficiency2;
        
        effvals[i]=eff_val;
        
        
        std::cout << "\n" << integ << std::endl;
        std::cout << "\n" << eff_val << std::endl;
        std::cout << "\n" << efficiency2 << std::endl;
        */
        
        //double efficiency2_error = efficiency2*sqrt(pow(eff_error/eff_val,2)+(1/(4*sideband_bg_val))*pow(sideband_bg_error/(5/2+sideband_bg_val),2));
        
        //std::cout << "\n\n" << "BDT cut value = " << cut_val << "\n" ;
        //std::cout << "S = " << sig_val << " +/- " << sig_error << "\n" ;
        //std::cout << "B = " << bg_val << " +/- " << bg_error << "\n" ;
        //std::cout << "S/sqrt(S+B) = " << efficiency << " +/- " << efficiency_error << "\n\n" ;
        
        //ds.plotOn( plot );
        //pdf.plotOn( plot );
        
        //RooPlot* plotPullMass = mass.frame();
        
        //plotPullMass->addPlotable( plot->pullHist() );
        //plotPullMass->SetMinimum();
        //plotPullMass->SetMaximum();
        
        //std::cout << cut_val;
    }
    
    
    TCanvas *c1 = new TCanvas(); 
    
    //double zeros[20];
    //for (i=0, i<20, i++) zeros[i]=0.0;
    
    TGraphErrors* graph = new TGraphErrors(40, bdt_cuts, efficiencies1, 0, efficiencies1_error);
    
    graph->SetTitle("S/sqrt(S+B) vs BDTG3 cut");
    //graph->SetMarkerColor(4);
    //graph->SetMarkerStyle(20);
    //graph->SetMarkerSize(1.0);
    graph->GetXaxis()->SetTitle("BDTG3 cut (>)");
    graph->GetXaxis()->SetRangeUser(-1.0,1.0);
    graph->GetYaxis()->SetTitle("S/sqrt(S+B)");
    //graph->Fit("pol5"); 
    graph->Draw("AP");
    c1->SaveAs("~/cern/plots/bdt_cuts_norm/Lb2JpsipK_2011_2012_BDTG3_cuts_S_sqrtS+B.pdf");
    //return c1;
    
    //std::cout << efficiencies1_error[5] << std::endl;
    
    //gStyle->SetOptFit(1011);
    /*TCanvas *c2 = new TCanvas();
    
    TGraph* graph2 = new TGraph(40, bdt_cuts, efficiencies2);
    
    graph2->SetTitle("eff/[5/2+sqrt(B)] vs BDTG3 cut");
    graph2->SetMarkerColor(4);
    graph2->SetMarkerStyle(20);
    graph2->SetMarkerSize(1.0);
    graph2->GetXaxis()->SetTitle("BDTG3 cut (>)");
    graph2->GetXaxis()->SetRangeUser(-1.0,1.0);
    graph2->GetYaxis()->SetTitle("eff/[5/2+sqrt(B)]");
    //graph2->Fit("pol7"); 
    graph2->Draw("AP");
    c2->SaveAs("~/cern/plots/bdt_cuts_norm/Lb2JpsipK_2011_2012_BDTG3_cuts_Punzi.png");
    //return c2;
    */
    
    
    
    /*
    TCanvas* c = new TCanvas();
    
    TPad* pad1 = new TPad("pad1","pad1", 0, 0.3, 1, 1.0);
    pad1->SetBottomMargin(0.1);
    pad1->SetTopMargin(0.1);
    pad1->Draw();
    c->cd();
    TPad* pad2 = new TPad("pad2","pad2", 0, 0, 1, 0.3);
    pad2->SetBottomMargin(0.1);
    pad2->SetTopMargin(0.0);
    pad2->Draw();
    
    
    //pdf.plotOn( plot, RooFit::Components( DfbPdf ), RooFit::LineColor( kRed ), RooFit::LineStyle(kDashed) );
    //pdf.plotOn( plot, RooFit::Components( promptPdf ), RooFit::LineColor( kBlue ), RooFit::LineStyle(kDotted) );
    //pdf.plotOn( plot, RooFit::Components( bgPdf ), RooFit::LineColor( kOrange ), RooFit::LineStyle(kDashDotted) );
    
    pad1->cd();
    plot->Draw();
    
    pad2->cd();
    plotPullMass->Draw("AP");
    
    c->SaveAs(out_file_mass);
    
    RooStats::SPlot* sData = new RooStats::SPlot("sData","An SPlot",
            ds, &pdf, RooArgList(sigYield, bgYield) );
    
    
    RooDataSet * dataw_z = new RooDataSet(ds.GetName(),ds.GetTitle(),&ds,*(ds.get()),0,"sigYield_sw") ;
    */
    /*   
    TCanvas* d = new TCanvas();
    RooPlot* w_mass_chicp = mass_chicp.frame();
    dataw_z->plotOn(w_mass_chicp, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_chicp->Draw();
    d->SaveAs("m_chicp_sweighted.png");
    
    TCanvas* e = new TCanvas();
    RooPlot* w_mass_pK = mass_pK.frame();
    dataw_z->plotOn(w_mass_pK, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_pK->Draw();
    e->SaveAs("m_pK_sweighted.png");
    */
    /*
    TCanvas* f = new TCanvas();
    RooPlot* w_mass_Jpsi = mass_Jpsi.frame();
    dataw_z->plotOn(w_mass_Jpsi, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_Jpsi->Draw();
    f->SaveAs("m_Jpsi_sweighted.png");
    
    TCanvas* g = new TCanvas();
    RooPlot* w_mass_Chic = mass_Chic.frame();
    dataw_z->plotOn(w_mass_Chic, RooFit::DataError(RooAbsData::SumW2), RooFit::Binning(20)) ;
    w_mass_Chic->Draw();
    g->SaveAs("m_Chic_sweighted.png");
    */
    
    
}
示例#29
0
void AnalyzeData(char *DataFile = "drs4_peds_5buffers.dat", Int_t nevt,
		Int_t startEv = 1, char *PedFile, Int_t DrawExtraGraphs = 0) {


	// Redefine DOMINO Depth in ADC counts
	const Float_t DominoDepthADC = pow(2, DOMINO_DEPTH);

	// open file

	FILE *fdata = OpenDataFile(DataFile);
	struct channel_struct *p;
	struct channel_struct *dep;

	// create histograms
	// create list of histograms for channels and distribution

	TList *DistChList = new TList();
	TH1F *distch; // histo with distribution of cell-charge, for each channel

	TList *DistChSubList = new TList();
	TH1F *distchsub; // histo with distribution of cell-charge, pedestals subtracted, for each channel

	TList *DistCh0SubList = new TList();
	TH1F *distch0sub; // histo with distribution of cell-charge, pedestals subtracted,
	// channel 0 subtracted for each channel

	TList *grPedList = new TList();
	TGraphErrors *grPed; // for each channel, pedestal value and RMS for each cell is plotted

	TList *hCellList = new TList();
	TH1F *hCell; // charge distribution for each cell (DOMINO_NCELL x DOMINO_NCH histos)
	TList *hCellSubList = new TList();
	TH1F *hCellSub; // charge distribution for each cell (DOMINO_NCELL x DOMINO_NCH histos), pedestal subtracted

	TList *hRMSList = new TList();
	TH1F *hRMSdist; // histo with RMS distribution (statistical RMS of distribution)
	TList *hRMSFitList = new TList();
	TH1F *hRMSFitdist; // histo with RMS distribution (RMS of Gaussian fit)

	TList *grDataList = new TList();
	TGraphErrors *grData; // charge-cell and RMS for each cell is plotted

	TList *grDataSubList = new TList();
	TGraphErrors *grDataSub; // pedestal subtracted charge-cell and RMS for each cell is plotted


	for (int h = 0; h < DOMINO_NCH; h++) {
		//
		TString title = "Data Dist channel";
		title += h;
		distch = new TH1F(title, title, DominoDepthADC, 0., DominoDepthADC);
		DistChList->Add(distch);
		//
		TString title = "Data Dist Ped Sub channel";
		title += h;
		distchsub = new TH1F(title, title, DominoDepthADC, -DominoDepthADC/2, DominoDepthADC/2);
		DistChSubList->Add(distchsub);
		//
		TString title = "Data Dist Ped Ch0 Sub channel";
		title += h;
		distch0sub = new TH1F(title, title, DominoDepthADC, -DominoDepthADC/2, DominoDepthADC/2);
		DistCh0SubList->Add(distch0sub);
		//
		TString title = "Pedestal ch";
		title += h;
		grPed = new TGraphErrors(DOMINO_NCELL);
		grPed->SetTitle(title);
		grPedList->Add(grPed);
		//
		TString title = "Data ch";
		title += h;
		grData = new TGraphErrors(DOMINO_NCELL);
		grData->SetTitle(title);
		grDataList->Add(grData);
		//
		// Mean data and RMS for each channel and cell
		TString title = "Data PedSubtracted ch";
		title += h;
		grDataSub = new TGraphErrors(DOMINO_NCELL);
		grDataSub->SetTitle(title);
		grDataSubList->Add(grDataSub);
		//
		for (int ch = 0; ch < DOMINO_NCELL; ch++) {
			// data distribution histos
			TString title = "Data ch";
			title += h;
			title += " cell";
			title += ch;
			hCell = new TH1F(title, title, DominoDepthADC, 0., DominoDepthADC);
			hCellList->Add(hCell);
			// data (ped subtracted) distribution histos
			TString title = "Data PedSub ch";
			title += h;
			title += " cell ";
			title += ch;
			hCellSub = new TH1F(title, title, 2 * DominoDepthADC, -1
					* DominoDepthADC, DominoDepthADC);
			hCellSubList->Add(hCellSub);
		}
		// Data-RMS distribution histos
		TString title = "RMSDist channel";
		title += h;
		hRMSdist = new TH1F(title, title, 100, 0, 20.);
		hRMSList->Add(hRMSdist);
		// Data-RMS (calculated through a fit) distribution histos
		TString title = "RMSFitDist channel";
		title += h;
		hRMSFitdist = new TH1F(title, title, 100, 0, 20.);
		hRMSFitList->Add(hRMSFitdist);
	}
	//--------------
	//
	// calculate or read pedestals from file
	grPedList = OpenPedestals(PedFile);

	//    return;
	//
	// ====== Read data file and subtract the pedestals
	//
	// Count number of events in data file
	int nevtDataMax = 0;
	while (!feof(fdata)) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		nevtDataMax++;
	}
	printf("nevtDataMax: %d\n", nevtDataMax);

	if (nevt > (nevtDataMax - startEv) || nevt == 0)
		nevt = nevtDataMax - startEv;
	cout << endl << "==>> Processing " << nevt << " events from file "
			<< DataFile << endl;

	rewind(fdata);

	Int_t ievt = 1;
	// go to first event (startEv)
	while (ievt < startEv) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		if (feof(fdata))
			break;
		ievt++;
	}
	// filling
	ievt = 1;
	Int_t flagEnd = 0;
	Double_t chtmp;
	Double_t PedVal, itmp, Ch0Val;
	// loop on events
	cout << endl << " --- read DATA file:" << fdata << endl;
	while (ievt <= nevt && !flagEnd) {
		fread((void *) &event_data, 1, sizeof(event_data), fdata);
		if (feof(fdata))
			flagEnd = 1;
		if (ievt % (nevt / 10 + 1) == 0)
			cout << "*" << endl;
		p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data
		dep = (struct channel_struct *) &event_data.ch[1]; // read bunch of data

		TGraphErrors *grCh0 = new TGraphErrors(DOMINO_NCELL);

		// loop on channels
		for (int h = 0; h < DOMINO_NCH; h++) {
			// loop on cells
			distch = (TH1F *) DistChList->At(h);
			distchsub = (TH1F *) DistChSubList->At(h);
			grPed = (TGraphErrors *) grPedList->At(h);
			distch0sub = (TH1F *) DistCh0SubList->At(h);
			if(h==0) {
				for(i = 0; i < DOMINO_NCELL;i++) {
					grPed->GetPoint(i, itmp, PedVal);
					chtmp = (Double_t)(p->data[i]);
					chtmp = chtmp - PedVal;
					grCh0->SetPoint(i,itmp, chtmp);
				}
			}
			for (int i = 0; i < DOMINO_NCELL; i++) {
				// Read pedestal value for this cell
				grPed->GetPoint(i, itmp, PedVal);
				grCh0->GetPoint(i, itmp, Ch0Val);
				//                cout << itmp << ", " << PedVal << endl;
				// Read calibration correction for this cell
				//                CalFact =

				//charge distribution for each cell, pedestal subtracted
				chtmp = (Double_t)(p->data[i]); // data value
				//                cout  << "tcell, tcell, depth: " << chtmp << ","  << p->data[i] << "," << deptmp << endl;
				distch->Fill(chtmp);
				// Check data value: must be within DOMINO Depth
				//                if(chtmp > DominoDepthADC)
				//                    cout << " === WARNING!!! Channel " << h << " Cell " << i << " has value " << chtmp << endl;
				//                cout << "Charge: " << p->data[i] << endl;
				((TH1 *) hCellList->At(h * DOMINO_NCELL + i))->Fill(chtmp);
				// Now the pedestal is subtracted
				chtmp = chtmp - PedVal;
				distchsub->Fill(chtmp);
				((TH1 *) hCellSubList->At(h * DOMINO_NCELL + i))->Fill(chtmp);
				chtmp = chtmp - Ch0Val;
				distch0sub->Fill(chtmp);
			}
			p++; // next channel
		}
		ievt++; // next event
	}
	cout << endl;

	// now mean and RMS for each cell are computed and save in histos and graphs
	cout << " --- filling data histos and grphs " << endl;
	TF1 *fgauss = new TF1("fgauss", Gauss, -10., 10., 3);
	fgauss->SetParLimits(0, 0.1, 10000.);
	fgauss->SetParLimits(1, 0., 4096.);
	fgauss->SetParLimits(2, 0.1, 20.);
	Float_t mean, rms, meansub, rmssub;
	for (int h = 0; h < DOMINO_NCH; h++) {
		//        for (int h=5; h<6; h++){
		cout << " Channel:" << h << endl;
		hRMSdist = (TH1F *) hRMSList->At(h);
		hRMSFitdist = (TH1F *) hRMSFitList->At(h);
		grData = (TGraphErrors *) grDataList->At(h);
		grDataSub = (TGraphErrors *) grDataSubList->At(h);
		for (int ch = 0; ch < DOMINO_NCELL; ch++) {
			// data distribution histos
			//            cout << "cell:" << ch << " index:" << h*DOMINO_NCELL+ch << " Mean,RMS:"<<hCell->GetMean()<< "," << hCell->GetRMS()<<endl;
			hCell = (TH1F *) hCellList->At(h * DOMINO_NCELL + ch);
			mean = hCell->GetMean();
			rms = hCell->GetRMS();
			hCellSub = (TH1F *) hCellSubList->At(h * DOMINO_NCELL + ch);
			meansub = hCellSub->GetMean();
			rmssub = hCellSub->GetRMS();
			fgauss->SetParameter(0, (Double_t) nevt / 4.);
			fgauss->SetParameter(1, mean);
			fgauss->SetParameter(2, rms);
			//            hCell->Fit("fgauss","QN0");
			grData->SetPoint(ch, ch, mean);
			grData->SetPointError(ch, 0, rms);
			grDataSub->SetPoint(ch, ch, meansub);
			//            grDataSub->SetPointError(ch,0.5,rmssub);
			grDataSub->SetPointError(ch, 0.5, 2.1);
			hRMSdist->Fill(rms);
			hRMSFitdist->Fill(fgauss->GetParameter(2));
			//           cout << "cell:" << ch << " index:" << h*DOMINO_NCELL+ch << " Mean,RMS:"<< mean << "," << rms<<endl;
		}
	}

	Double_t x, y, chtmp, x1, x2, y1, y2;

	/*TList *grCellCalibList = OpenCalibFile("CalibrationData1000events.root");

	TGraphErrors *grCellCalib;
	TGraphErrors *grDataSubCalib = new TGraphErrors(DOMINO_NCELL);
	grDataSubCalib->SetTitle("Data after calibration correction");
	grDataSub = (TGraphErrors *) grDataSubList->At(anaChannel);


	for(ch = 0; ch < DOMINO_NCELL; ch++) {
		grCellCalib = ((TGraphErrors *) grCellCalibList->At(ch));
		grCellCalib->Fit("pol3", "Q");
		TF1 *pol3fit = ((TF1 *) grCellCalib->GetFunction("pol3"));
		grDataSub->GetPoint(ch, x, y);
		chtmp = y - (Double_t)(pol3fit->Eval(y/3.25));
		grDataSubCalib->SetPoint(ch, x, chtmp);
	}

	TCanvas *cGrTest = new TCanvas("grTest", "test per vedere i dati", 1000,1000);

	grDataSubCalib->Draw("APEL");*/


	TString Title = "Charge Distribution per channel";
	gStyle->SetOptFit(111);
	TCanvas *cdistch = new TCanvas("cdistch", Title, 1000, 1000);
	cdistch->Divide(3, 3);
	for (int i = 0; i < DOMINO_NCH; i++) {
		cdistch->cd(i + 1);
		TH1 *dhist = (TH1 *) DistChList->At(i);
		dhist->DrawCopy();
		dhist->SetLineWidth(1);
		dhist->Fit("gaus", "Q");
		dhist->GetFunction("gaus")->SetLineColor(4);
		dhist->GetFunction("gaus")->SetLineWidth(2);
	}

	TString Title = "Charge Distribution Pedestals Subtracted per channel";
	TCanvas *cdistchsub = new TCanvas("cdistchsub", Title, 1000, 1000);
	cdistchsub->Divide(3, 3);
	for (int i = 0; i < DOMINO_NCH; i++) {
		cdistchsub->cd(i + 1);
		TH1 *dsubhist = (TH1 *) DistChSubList->At(i);
		dsubhist->DrawCopy();
		dsubhist->SetLineWidth(1);
		dsubhist->Fit("gaus", "Q");
		dsubhist->GetFunction("gaus")->SetLineColor(4);
		dsubhist->GetFunction("gaus")->SetLineWidth(2);
	}

	TString Title = "Charge Distribution Pedestals and Ch0 Subtracted per channel";
	TCanvas *cdistch0sub = new TCanvas("cdistch0sub", Title, 1000, 1000);
	cdistch0sub->Divide(3, 3);
	for (int i = 0; i < DOMINO_NCH; i++) {
		cdistch0sub->cd(i + 1);
		TH1 *dch0subhist = (TH1 *) DistCh0SubList->At(i);
		dch0subhist->DrawCopy();
		dch0subhist->SetLineWidth(1);
		dch0subhist->Fit("gaus", "Q");
		dch0subhist->GetFunction("gaus")->SetLineColor(4);
		dch0subhist->GetFunction("gaus")->SetLineWidth(2);
	}

	TCanvas *cDataSubTest = new TCanvas("cDataSubTest", "Data after pedestal subtraction", 1000, 1000);
	cDataSubTest->Divide(1,8);
	for (h = 0; h< DOMINO_NCH; h++) {
		grDataSub = (TGraphErrors *) grDataSubList->At(h);
		cDataSubTest->cd(h+1);
		grDataSub->GetYaxis()->SetLabelSize(0.06);
		grDataSub->GetXaxis()->SetLabelSize(0.06);
		grDataSub->Draw("APE");
	}

	TCanvas *cDataSubTestCh5 = new TCanvas("cDataSubTestCh5", "Data after pedestal subtraction Ch5", 1200, 800);
	grDataSub = (TGraphErrors *) grDataSubList->At(anaChannel);
	grDataSub->GetYaxis()->SetLabelSize(0.06);
	grDataSub->GetYaxis()->SetTitle("ADC Counts");
	grDataSub->GetXaxis()->SetTitle("Cell");
	grDataSub->GetXaxis()->SetLabelSize(0.06);
	TLine *refval = new TLine(0,350,1024,350);
	refval->SetLineWidth(3);
	refval->SetLineStyle(2);
	refval->SetLineColor(2);
	TLine *i1 = new TLine(121,-50,121,800);
	i1->SetLineStyle(2);
	TLine *i2 = new TLine(291,-50,291,800);
	i2->SetLineStyle(2);
	TLine *i3 = new TLine(461,-50,461,800);
	i3->SetLineStyle(2);
	TLine *i4 = new TLine(632,-50,632,800);
	i4->SetLineStyle(2);
	TLine *i5 = new TLine(803,-50,803,800);
	i5->SetLineStyle(2);
	TLine *i6 = new TLine(975,-50,975,800);
	i6->SetLineStyle(2);
	TLine *ireal1 = new TLine(121+20,600,121+20,800);
	ireal1->SetLineWidth(3);
	ireal1->SetLineColor(4);
	TLine *ireal2 = new TLine(291-20,600,291-20,800);
	ireal2->SetLineWidth(3);
	ireal2->SetLineColor(4);
	TLine *ireal3 = new TLine(461+20,600,461+20,800);
	ireal3->SetLineWidth(3);
	ireal3->SetLineColor(4);
	TLine *ireal4 = new TLine(632-20,600,632-20,800);
	ireal4->SetLineWidth(3);
	ireal4->SetLineColor(4);
	TLine *ireal5 = new TLine(803+20,600,803+20,800);
	ireal5->SetLineWidth(3);
	ireal5->SetLineColor(4);
	TLine *ireal6 = new TLine(975-20,600,975-20,800);
	ireal6->SetLineWidth(3);
	ireal6->SetLineColor(4);
	grDataSub->Draw("APE");
	refval->Draw("SAME");
	i1->Draw("SAME");
	i2->Draw("SAME");
	i3->Draw("SAME");
	i4->Draw("SAME");
	i5->Draw("SAME");
	i6->Draw("SAME");
	ireal1->Draw("SAME");
	ireal2->Draw("SAME");
	ireal3->Draw("SAME");
	ireal4->Draw("SAME");
	ireal5->Draw("SAME");
	ireal6->Draw("SAME");


	TCanvas *cDataTest = new TCanvas("cDataTest", "Raw Data", 1000,1000);
	cDataTest->Divide(1,8);
	for(h = 0; h < DOMINO_NCH; h++) {
		cDataTest->cd(h+1);
		grData = (TGraphErrors *) grDataList->At(h);
		grData->SetMarkerStyle(20);
		grData->SetMarkerSize(0.5);
		grData->Draw("APE");

	}

	// save root file with graph containing channel 5 data after pedestals subtraction.
	/*
	cout << "test" << endl;

	TString OutFile = DataSubFile;
	TFile *f = new TFile(OutFile,"RECREATE");
	int h = anaChannel;
	TString key="DataSubGraph";
	key += h;
	((TGraphErrors*)grDataSubList->At(h))->Write(key);
	f->Close();
	cout << " ---- Write data on file " << endl;
	 */

	// =======================================================//
	// =====================Matteo's Code=====================//
	// =======================================================//
	/*
	Int_t cht, incCht, decCht, xflag, nPeriods, iMax, iMin;
	Double_t xdiff, incDiff, decDiff, incDiffTemp, decDiffTemp, incXDiff, decXDiff;
	Double_t fitMax, fitMin, fitPeriod, chisquare;
	Double_t DominoXval[DOMINO_NCELL];
	Double_t DominoYval[DOMINO_NCELL];
	Double_t FitXval[DOMINO_NCELL];
	Double_t FitYval[DOMINO_NCELL];


        // opens grDataSub.root

        TString FileName = DataSubFile;
        TGraphErrors *grDataSub;
        int h = anaChannel;
        TFile *f = new TFile(FileName);
        TString key = "DataSubGraph";
        key += h;
        grDataSub = (TGraphErrors *) f->Get(key);
        f->Close();


	// Create a new graph with channel 5 data
	TGraphErrors *grDataSubAnaCh;
	int h = anaChannel;
	grDataSubAnaCh = (TGraphErrors *) grDataSubList->At(h);

	TGraphErrors *grDataSubFix = grDataSubAnaCh->Clone();
	TGraphErrors *grRes = new TGraphErrors(DOMINO_NCELL);
	TList *grResPeriodList = new TList();



	Double_t xtemp, ytemp, DominoMax, DominoMin;

	for (int ch = 0; ch < DOMINO_NCELL; ch++){
		// get domino-output point and save in array
		grDataSubAnaCh->GetPoint(ch, DominoXval[ch], DominoYval[ch]);
	}

	// find the domino point with max y-value
	iMax = 0;
	for(int ch = 0; ch < DOMINO_NCELL; ch++) {
		if(DominoYval[ch] > DominoYval[iMax]) {
			DominoMax = DominoYval[ch];
			iMax = ch;
		}
	}

	cout << "DominoMax e': " << DominoMax << endl;

	// find the domino point with min y-value
	iMin = 0;
	for (int ch = 0; ch < DOMINO_NCELL; ch++) {
		if(DominoYval[ch] < DominoYval[iMin]) {
			DominoMin = DominoYval[ch];
			iMin = ch;
		}
	}

	cout << "DominoMin e': " << DominoMin << endl;

	// remove points from the graph that will be used for fit
	for (int ch = 0; ch < DOMINO_NCELL; ch++){
		grDataSubFix->GetPoint(ch, xtemp, ytemp);
		if(ytemp > 0.8*DominoMax || ytemp < 0.2*DominoMin)
			grDataSubFix->RemovePoint(ch);
	}


	TF1 *fsin = new TF1("fsin", sigSin, 0., 1024., 4);
	fsin->SetParameters(600., DOMINO_NCELL / 4., 150., 150.);
	fsin->SetParNames("amplitude", "Period", "Phase", "DC-Offset");
	grDataSubFix->Fit("fsin");
	TF1 *fsinFit = grDataSubFix->GetFunction("fsin");
	fsinFit->SetParNames("amplitude", "Period", "Phase", "DC-Offset");
	chisquare = grDataSub->Chisquare(fsinFit);
	cout << "il chi quadro della funzione di fit e' : " << chisquare << endl;

	for (int ch = 0; ch < DOMINO_NCELL; ch++) {
		// get Fit-value and save in array
		FitXval[ch] = DominoXval[ch];
		FitYval[ch] = fsinFit->Eval(FitXval[ch]);
	}

	fitPeriod = fsinFit->GetParameter("Period");
	cout << "il periodo della funzione e': " << fitPeriod << endl;

	nPeriods = (Int_t) (DOMINO_NCELL/fitPeriod);
	cout << "il numero di periodi della funzione e': " << nPeriods << endl;

	fitMax = fsinFit->GetMaximum();
	cout << "il massimo della funzione e': " << fitMax << endl;

	fitMin = fsinFit->GetMinimum();
	cout << "il minimo della funzione e': " << fitMin << endl;




	// computes the y difference between the ch-domino point and the i-fit point
	// and stops when the difference changes sign
	//
	// first and last points are not included in the cicle
	//
	// if the fit point y-value is bigger or smaller than the fit function max*0.8 or min*0.2
	// the point is removed

	for (int ch = 1; ch < DOMINO_NCELL - 1; ch++) {

		if(FitYval[ch] > 0.8*fitMax || FitYval[ch] < 0.2*fitMin) {
			grRes->RemovePoint(ch);
			continue;
		}

		incDiff = DominoYval[ch] - FitYval[ch];
		incDiffTemp = DominoYval[ch] - FitYval[ch + 1];

		decDiff = DominoYval[ch] - FitYval[ch];
		decDiffTemp = DominoYval[ch] - FitYval[ch - 1];

		if(abs(incDiffTemp) < abs(incDiff) || (sign(incDiff) != sign(incDiffTemp) && abs(decDiffTemp) > abs(decDiff))) {
			for (int i = ch; i < DOMINO_NCELL; i++, incDiff = incDiffTemp) {
				incDiffTemp = DominoYval[ch] - FitYval[i];

				if (sign(incDiff) != sign(incDiffTemp)) {
					if(abs(incDiffTemp) < abs(incDiff))
						incCht = i;
					else
						incCht = i - 1;
					break;
				}
			}
			xflag = 1;
		}
		else if(abs(decDiffTemp) < abs(decDiff) || (sign(decDiff) != sign(decDiffTemp) && abs(incDiffTemp) > abs(incDiff))) {
			for (int j = ch; j >= 0 ; j--, decDiff = decDiffTemp) {
				decDiffTemp = DominoYval[ch] - FitYval[j];

				if (sign(decDiff) != sign(decDiffTemp)) {
					if(abs(decDiffTemp) < abs(decDiff))
						decCht = j;
					else
						decCht = j + 1;
					break;
				}
			}
			xflag = -1;
		}

		if(xflag == 1)
			xdiff = FitXval[incCht] - DominoXval[ch];
		else
			xdiff = FitXval[decCht] - DominoXval[ch];

		grRes->SetPoint(ch, (Double_t) ch, xdiff);
	}

	cout << "Draw Time Residuals" << endl;
	TString Title = "Time Residuals";
	TCanvas *timeres = new TCanvas("timeres", Title, 1200, 780);
	grRes->SetMarkerStyle(20);
	grRes->SetMarkerSize(0.3);
	grRes->GetYaxis()->SetLabelSize(0.12);
	grRes->GetXaxis()->SetLabelSize(0.12);
	grRes->Draw("APE");


	// The previous graph is now split in N graphs, where N is the number of fit periods

	// this will be needed to set the function phase
	//
    //    iMax = 0;
	//
    //    for(ch = 0; ch < fitPeriod - 1; ch++) {
    //            if(FitYval[ch] > FitYval[iMax]) iMax = ch;
    //    }

	cout << "il primo massimo ha l'indice : " << iMax << endl;

	for (i = 0; i < nPeriods; i++) {
		TGraphErrors *grResPeriod = new TGraphErrors((Int_t) fitPeriod);
		grResPeriodList->Add(grResPeriod);

		for(ch = i*fitPeriod + 1; ch < fitPeriod + (i*fitPeriod); ch++) {

			if(FitYval[ch] > 0.8*fitMax || FitYval[ch] < 0.2*fitMin) {
				grResPeriod->RemovePoint(ch);
				continue;
			}

			incDiff = DominoYval[ch] - FitYval[ch];
			incDiffTemp = DominoYval[ch] - FitYval[ch + 1];

			decDiff = DominoYval[ch] - FitYval[ch];
			decDiffTemp = DominoYval[ch] - FitYval[ch - 1];

			if(abs(incDiffTemp) < abs(incDiff) || (sign(incDiff) != sign(incDiffTemp) && abs(decDiffTemp) > abs(decDiff))) {
				for (int k = ch; k < k*fitPeriod + fitPeriod; k++, incDiff = incDiffTemp) {
					incDiffTemp = DominoYval[ch] - FitYval[k];

					if (sign(incDiff) != sign(incDiffTemp)) {
						if(abs(incDiffTemp) < abs(incDiff))
							incCht = k;
						else
							incCht = k - 1;
						break;
					}
				}
				xflag = 1;
			}
			else if(abs(decDiffTemp) < abs(decDiff) || (sign(decDiff) != sign(decDiffTemp) && abs(incDiffTemp) > abs(incDiff))) {
				for (int j = ch; j > i*fitPeriod; j--, decDiff = decDiffTemp) {
					decDiffTemp = DominoYval[ch] - FitYval[j];

					if (sign(decDiff) != sign(decDiffTemp)) {
						if(abs(decDiffTemp) < abs(decDiff))
							decCht = j;
						else
							decCht = j + 1;
						break;
					}
				}
				xflag = -1;
			}

			if(xflag == 1)
				xdiff = FitXval[incCht] - DominoXval[ch];
			else
				xdiff = FitXval[decCht] - DominoXval[ch];

			grResPeriod->SetPoint(ch - i*fitPeriod, (Double_t) (ch - i*fitPeriod), xdiff);
		}
	}

	TCanvas *timeresperiod = new TCanvas("timeresperiod", "Time Residuals Period", 1200, 780);
	for(i = 0; i < nPeriods; i++) {
		grResPeriod = ((TGraphErrors *) grResPeriodList->At(i));
		grResPeriod->SetMarkerStyle(20);
		grResPeriod->SetMarkerSize(0.3);
		grResPeriod->GetYaxis()->SetLabelSize(0.12);
		grResPeriod->GetXaxis()->SetLabelSize(0.12);
		grResPeriod->Draw("APEsame");
	}

	cout << "Draw Data - Pedestals Subtracted" << endl;
	TString Title = "Average Charge - Pedestal subtracted";
	TCanvas *csubdata = new TCanvas("csubdata", Title, 1200, 780);
	grDataSubAnaCh->SetMarkerStyle(20);
	grDataSubAnaCh->SetMarkerSize(0.3);
	grDataSubAnaCh->GetYaxis()->SetLabelSize(0.12);
	grDataSubAnaCh->GetXaxis()->SetLabelSize(0.12);
	grDataSubAnaCh->Draw("APE");
	fsinFit->Draw("same");
	 */
	// draw extra graphs
	if (DrawExtraGraphs == 1) {
		cout << " ----- DRAW Results ------" << endl;
		//================ DRAW Results ==================

		TCanvas *c = new TCanvas("ctmp", "test", 800, 800);
		c->Divide(3, 3);
		for (int pad = 1; pad < 10; pad++) {
			c->cd(pad);
			((TH1 *) hCellList->At(pad * 512 + 219))->DrawCopy();
			hCellSub = (TH1F *) hCellSubList->At(pad * 512 + 219);
			hCellSub->SetLineColor(2);
			hCellSub->DrawCopy("same");
		}

		cout << "Draw RMS distributions" << endl;
		TString Title = "RMS distributions per channel";
		TCanvas *c4 = new TCanvas("c4", Title, 700, 700);
		c4->Divide(3, 3);
		for (int i = 0; i < DOMINO_NCH; i++) {
			c4->cd(i + 2);
			hRMSdist = (TH1F *) hRMSList->At(i);
			hRMSFitdist = (TH1F *) hRMSFitList->At(i);
			hRMSFitdist->SetLineColor(2);
			hRMSFitdist->DrawCopy();
			hRMSdist->DrawCopy("same");
		}


		TList *grDataCh0SubList = new TList();
		TGraphErrors *grDataCh0Sub;
		for(h = 0; h< DOMINO_NCELL; h++) {
			grDataCh0Sub = new TGraphErrors(DOMINO_NCELL);
			grDataCh0SubList->Add(grDataCh0Sub);
		}

		TGraphErrors *grDataSubCh0 = (TGraphErrors *) grDataSubList->At(6);
		for(h = 0; h < DOMINO_NCH; h++) {
			grDataSub = (TGraphErrors *) grDataSubList->At(h);
			grDataCh0Sub = (TGraphErrors *) grDataCh0SubList->At(h);
			for(ch = 0; ch < DOMINO_NCELL; ch++) {
				grDataSubCh0->GetPoint(ch, x1, y1);
				grDataSub->GetPoint(ch, x2, y2);
				grDataCh0Sub->SetPoint(ch, x1 , y2 - y1);
			}
		}

		TCanvas *cDataCH0Sub = new TCanvas("cDataCH0Sub","cDataCH0Sub", 1000,1000);
		cDataCH0Sub->Divide(1,8);
		for(h = 0; h < DOMINO_NCH; h++) {
			cDataCH0Sub->cd(h+1);
			grDataCh0Sub = (TGraphErrors *) grDataCh0SubList->At(h);
			grDataCh0Sub->GetYaxis()->SetLabelSize(0.12);
			grDataCh0Sub->GetXaxis()->SetLabelSize(0.12);
			grDataCh0Sub->Draw("APEL");
		}



		cout << "Draw Data - Pedestals Subtracted" << endl;
		TString Title = "Average Charge - Pedestal subtracted";
		TCanvas *csubdata = new TCanvas("csubdata", Title, 1000, 1000);
		csubdata->Divide(3,3);

		for(h = 0; h < DOMINO_NCH; h++) {
			csubdata->cd(h+1);
			TString title = "DataSub channel ";
			title += h;
			TH1F *hCellDataSub = new TH1F(title, title, 100, -20, 20);
			grDataSub = (TGraphErrors *) grDataSubList->At(h);
			for(ch = 0; ch < DOMINO_NCELL; ch++) {
				grDataSub->GetPoint(ch, x, y);
				hCellDataSub->Fill(y);
			}
			hCellDataSub->Fit("gaus", "Q");
			hCellDataSub->GetXaxis()->SetTitle("ADC Counts");
			hCellDataSub->GetFunction("gaus")->SetLineColor(4);
			hCellDataSub->DrawCopy();
		}

		cout << "breakpoint" << endl;
		TCanvas *csubdata2 = new TCanvas("csubdata2", "DataSub for every channel", 1000, 1000);
		TString title = "DataSub every channel ";
		TH1F *hCellChDataSubTot = new TH1F(title, title, 100, -20, 20);
		for(h = 0; h < DOMINO_NCH; h++) {
			grDataSub = (TGraphErrors *) grDataSubList->At(h);
			for(ch = 0; ch < DOMINO_NCELL; ch++) {
				grDataSub->GetPoint(ch, x, y);
				hCellChDataSubTot->Fill(y);
			}
			hCellChDataSubTot->Fit("gaus", "Q");
			hCellChDataSubTot->GetXaxis()->SetTitle("ADC Counts");
			hCellChDataSubTot->GetFunction("gaus")->SetLineColor(4);
			hCellChDataSubTot->Draw();
		}

		cout << "Draw Pedestals" << endl;
		TString Title = "Pedestals";
		TCanvas *c2 = new TCanvas("c2", Title, 1050, 780);
		c2->SetBorderMode(0);
		c2->SetBorderSize(0.);
		c2->Divide(1, 8);
		//    gStyle->SetCanvasBorderMode(0.);
		//    gStyle->SetCanvasBorderSize(0.);
		Double_t x, y;
		for (int h = 0; h < DOMINO_NCH; h++) {
			c2->cd(h + 1);
			grPed = ((TGraphErrors *) grPedList->At(h));
			grPed->SetMarkerStyle(20);
			grPed->SetMarkerSize(0.5);
			grPed->GetYaxis()->SetLabelSize(0.12);
			grPed->GetXaxis()->SetLabelSize(0.12);
			//        cout <<  " err:" << grPed->GetErrorY(102) << " " ;
			//        cout << x << "--" << y << endl;
			grPed->Draw("APE");
		}

		cout << "Draw Data - Average charge" << endl;
		TString Title = "Average_Charge";
		TCanvas *cdata = new TCanvas("cdata", Title, 1050, 780);
		cdata->Divide(1, 8);
		Double_t x, y;
		for (int h = 0; h < DOMINO_NCH; h++) {
			cdata->cd(h + 1);
			grData = ((TGraphErrors *) grDataList->At(h));
			grData->SetMarkerStyle(20);
			grData->SetMarkerSize(0.3);
			grData->GetYaxis()->SetLabelSize(0.12);
			grData->GetXaxis()->SetLabelSize(0.12);
			grData->GetPoint(10, x, y);
			//        cout << x << "-" << y << endl;
			grData->Draw("APE");
		}

		cout << "Draw Data - Pedestals Subtracted" << endl;
		TString Title = "Average Charge - Pedestal subtracted";
		TCanvas *csubdata = new TCanvas("csubdata", Title, 1200, 780);
		csubdata->Divide(1, 8);
		TF1 *fsin = new TF1("fsin", sigSin, 0., 1024., 4);
		TH1D *resDist = new TH1D("resDist", "Residuals Signal", 100, -100., 100.);

		cout << "Draw Data - Pedestals Subtracted" << endl;
		TString Title = "Residuals";
		TCanvas *residuals = new TCanvas("residuals", Title, 1200, 780);
		resDist->DrawCopy();

	}

	fclose(fdata);

	hCellList->Delete();
	hCellSubList->Delete();
	hRMSList->Delete();
	hRMSFitList->Delete();
}
void makePlots(vector<inputValues> b, vector<inputValues> t, vector<outputValues> o, double cut) {

    // Plot output values vs pulse width
    TGraphErrors * eLPlot   = new TGraphErrors();
    TGraphErrors  * ePsiPlot = new TGraphErrors ();
    eLPlot->SetTitle("Average Number of LED-induced Photoelectrons per Trigger");
    ePsiPlot->SetTitle("Single-photoelectron Response Mean Amplitude");

    eLPlot->SetMarkerColor(4);
    ePsiPlot->SetMarkerColor(4);
    eLPlot->SetMarkerStyle(21);
    ePsiPlot->SetMarkerStyle(21);

    for (int i = 0; i < b.size(); i++) {
        for (int j = 0; j < t.size(); j++) {
            eLPlot->SetPoint((i+1)*j, t[j].pw, o[(i+1)*j].eL);
            eLPlot->SetPointError((i+1)*j, 0.02, sqrt(o[(i+1)*j].v_eL));
            ePsiPlot->SetPoint((i+1)*j, t[j].pw, o[(i+1)*j].ePsi);
            ePsiPlot->SetPointError((i+1)*j, 0.02, sqrt(o[(i+1)*j].v_ePsi));
	    }
    }

    TCanvas * eL_c = new TCanvas("eL_c", "eL Canvas", 200, 10, 700, 500);
    eLPlot->GetXaxis()->SetTitle("LED Pulse Width / (ns)");
    eLPlot->GetYaxis()->SetTitle("Photoelectrons / Trigger");
    eLPlot->Draw("AP");

    TCanvas * ePsi_c = new TCanvas("ePsi_c", "ePsi Canvas", 200, 10, 700, 500);
    ePsiPlot->GetXaxis()->SetTitle("LED Pulse Width / (ns)");
    ePsiPlot->GetYaxis()->SetTitle("Mean Amplitude / (mV)");
    ePsiPlot->GetYaxis()->SetRangeUser(0.3, 1.6);
    ePsiPlot->Draw("AP");
    TF1 * fit = new TF1("fit", "[0]", 0, 10);
    ePsiPlot->Fit(fit);

    // Plot spectra
    TCanvas * spectra_c = new TCanvas("spectra_c", "Spectra Canvas", 200, 10, 700, 500);
    spectra_c->SetLogy();
    for (int i = t.size() - 1; i >= 0; i--) {
        t[i].h->SetLineColor(i+2);
        t[i].h->SetLineWidth(2);
        t[i].h->Draw("SAME");
        t[i].h->SetStats(0);
        t[i].h->SetTitle("PMT Spectra of Pulsed LED w/ Varying Pulse Width");
        t[i].h->GetXaxis()->SetTitle("Amplitude / (mV)");
        t[i].h->GetYaxis()->SetTitle("Events");
        t[i].h->GetYaxis()->SetRangeUser(0.5, 20000);
    }
    b[0].h->SetLineColor(1);
    b[0].h->SetLineWidth(2);
    b[0].h->Draw("SAME");
    b[0].h->SetStats(0);
    TLine * cutLine_t = new TLine(-1*cut, 0.0, -1*cut, 20000.0);
    cutLine_t->SetLineWidth(2);
    cutLine_t->SetLineColor(1);
    cutLine_t->SetLineStyle(2);
    cutLine_t->Draw();
    TLine * meanLine_t = new TLine(b[0].e + 0.89, 0.0, b[0].e + 0.89, 20000.0);
    meanLine_t->SetLineWidth(2);
    meanLine_t->SetLineColor(2);
    meanLine_t->SetLineStyle(2);
    meanLine_t->Draw();

    // Add legend
    //TLegend * leg = new TLegend(0.1, 0.7, 0.48, 0.9);
    //leg->SetHeader("Legend");
    //leg->AddEntry(t[0].h, "

    // Plot background
    //TCanvas * b_c = new TCanvas("b_c", "Background Canvas", 200, 10, 700, 500);
    //b_c->SetLogy();
    ////b[0].h->Sumw2();
    ////b[0].h->Draw();
    //b[0].h->GetYaxis()->SetRangeUser(1.0, 100000.0);
    //b[0].h->SetTitle("Background PMT Spectrum");
    //b[0].h->GetXaxis()->SetTitle("Amplitude / (mV)");
    //b[0].h->GetYaxis()->SetTitle("Events");
    //TLine * cutLine_b = new TLine(cut, 0.0, cut, 1000000.0);
    //cutLine_b->SetLineWidth(2);
    //cutLine_b->Draw();
}