Ejemplo n.º 1
0
Archivo: peaks.C Proyecto: Y--/root
void peaks(Int_t np=10) {
   npeaks = TMath::Abs(np);
   TH1F *h = new TH1F("h","test",500,0,1000);
   //generate n peaks at random
   Double_t par[3000];
   par[0] = 0.8;
   par[1] = -0.6/1000;
   Int_t p;
   for (p=0;p<npeaks;p++) {
      par[3*p+2] = 1;
      par[3*p+3] = 10+gRandom->Rndm()*980;
      par[3*p+4] = 3+2*gRandom->Rndm();
   }
   TF1 *f = new TF1("f",fpeaks,0,1000,2+3*npeaks);
   f->SetNpx(1000);
   f->SetParameters(par);
   TCanvas *c1 = new TCanvas("c1","c1",10,10,1000,900);
   c1->Divide(1,2);
   c1->cd(1);
   h->FillRandom("f",200000);
   h->Draw();
   TH1F *h2 = (TH1F*)h->Clone("h2");
   //Use TSpectrum to find the peak candidates
   TSpectrum *s = new TSpectrum(2*npeaks);
   Int_t nfound = s->Search(h,2,"",0.10);
   printf("Found %d candidate peaks to fit\n",nfound);
   //Estimate background using TSpectrum::Background
   TH1 *hb = s->Background(h,20,"same");
   if (hb) c1->Update();
   if (np <0) return;

   //estimate linear background using a fitting method
   c1->cd(2);
   TF1 *fline = new TF1("fline","pol1",0,1000);
   h->Fit("fline","qn");
   //Loop on all found peaks. Eliminate peaks at the background level
   par[0] = fline->GetParameter(0);
   par[1] = fline->GetParameter(1);
   npeaks = 0;
   Double_t *xpeaks = s->GetPositionX();
   for (p=0;p<nfound;p++) {
      Double_t xp = xpeaks[p];
      Int_t bin = h->GetXaxis()->FindBin(xp);
      Double_t yp = h->GetBinContent(bin);
      if (yp-TMath::Sqrt(yp) < fline->Eval(xp)) continue;
      par[3*npeaks+2] = yp;
      par[3*npeaks+3] = xp;
      par[3*npeaks+4] = 3;
      npeaks++;
   }
   printf("Found %d useful peaks to fit\n",npeaks);
   printf("Now fitting: Be patient\n");
   TF1 *fit = new TF1("fit",fpeaks,0,1000,2+3*npeaks);
   //we may have more than the default 25 parameters
   TVirtualFitter::Fitter(h2,10+3*npeaks);
   fit->SetParameters(par);
   fit->SetNpx(1000);
   h2->Fit("fit");
}
Ejemplo n.º 2
0
void solveNumerically()
{
  
  Double_t n0=1.35;
  Double_t m=-1*(1.78-1.35)/140;
  Double_t z0=-100;
  Double_t dMax=n0+m*z0;


  TCanvas *can = new TCanvas("can","can",600,400);
  // TF1 *lefty = new TF1("lefty",strangeLeft,0,dMax,5);
  // lefty->SetParameters(n0,m,z0,40,-30);
  // lefty->SetLineColor(8);
  // lefty->SetLineStyle(1);
  // lefty->SetNpx(1000);
  // lefty->Draw("");

  // TF1 *righty = new TF1("righty",strangeRight,0,dMax,5);
  // righty->SetParameters(n0,m,z0,40,-30);
  // righty->SetLineColor(kViolet);
  // righty->SetLineStyle(1);
  // righty->SetNpx(1000);
  // righty->Draw("same");


  TH1F*framey = can->DrawFrame(0,-50,dMax*1.1,0);
  TF1 *endy = new TF1("endy",strangeZ,0.02,dMax,4);
  endy->SetParameters(n0,m,z0,200);
  endy->SetLineColor(kViolet);
  endy->SetLineStyle(1);
  endy->SetNpx(1000);
  endy->Draw("same");

}
Ejemplo n.º 3
0
void draw()
{
  TF1* f = new TF1("f",_gaussCrystalball,0,5,8);
  f->SetParameters(39,1.42,0.22,172,2.506,0.14,0.64,1.7);
  f->SetNpx(500);
  f->Draw();
}
Ejemplo n.º 4
0
void example(double E0 = 50, int nevents = 100000)
{
   TStopwatch timer;

   // 12C* -> 3(4He)
   // compound nucleus = carbon
   KVNucleus CN(6, 12);
   CN.SetExcitEnergy(E0);

   // decay products
   KVEvent decay;
   KVNucleus* n = decay.AddParticle();
   n->SetZandA(2, 4);
   n = decay.AddParticle();
   n->SetZandA(2, 4);
   n = decay.AddParticle();
   n->SetZandA(2, 4);

   MicroStat::mdweight gps;
   Double_t etot = E0 + decay.GetChannelQValue();

   if (etot <= 0) {
      printf("Break-up channel is not allowed\n");
      return;
   }
   gps.SetWeight(&decay, etot);
   gps.initGenerateEvent(&decay);

   TH1F* h1 = new TH1F("h1", "Kinetic energy of alpha particle 3", 200, 0, etot * 2. / 3.);
   h1->Sumw2();

   KVEvent event;

   while (nevents--) {
      gps.GenerateEvent(&decay, &event);
      h1->Fill(event.GetParticle(3)->GetKE());
      gps.resetGenerateEvent();
   }

   h1->Draw();
   TF1* EDis = new TF1("EDis", edist, 0., etot, 3);
   EDis->SetNpx(500);
   EDis->SetParLimits(0, 0, 1.e+08);
   EDis->SetParLimits(1, 0, 2 * etot);
   EDis->FixParameter(2, 3);
   gStyle->SetOptFit(1);
   h1->Fit(EDis, "EM");

   timer.Print();
}
Ejemplo n.º 5
0
void wilenbrock_pseudoscalar()
{

  setTDRStyle();

  TCanvas* c = new TCanvas();
  TF1* func = new TF1("Signal + Interferences",Somme,350,900,1);
  func->SetTitle("Scalar : Signal + interferences");
  func->SetMinimum(-9e-9);
  //func->GetXaxis()->SetTitle("m_{t#bar{t}}");
  double m=400;
  func->SetParameter(0,m);
  func->SetLineColor(TColor::GetColor("#542437"));
  func->SetLineWidth(2);
  func->SetNpx(500);
  func->Draw();
  func->GetXaxis()->SetTitle("m_{t#bar{t}}");
  func->GetYaxis()->SetTitle("#sigma(#hat{s}) - #sigma_{QCD}(#hat{s})");
  TF1* func2 = new TF1("Signal + Interferences",Somme,350,900,1);
  m=500;
  func2->SetParameter(0,m);
  func2->SetLineColor(TColor::GetColor("#C02942"));
  func2->SetLineWidth(2);
  func2->SetNpx(500);
  func2->Draw("SAME");
  TF1* func3 = new TF1("Signal + Interferences",Somme,350,900,1);
  m=600;
  func3->SetParameter(0,m);
  func3->SetLineColor(TColor::GetColor("#53777A"));
  func3->SetLineWidth(2);
  func3->SetNpx(500);
  func3->Draw("SAME");
  TF1* func4 = new TF1("Signal + Interferences",Somme,350,900,1);
  m=700;
  func4->SetParameter(0,m);
  func4->SetLineColor(TColor::GetColor("#D95B43"));
  func4->SetLineWidth(2);
  func4->SetNpx(500);
  func4->Draw("SAME");
  TF1* func5 = new TF1("Signal + Interferences",Somme,350,900,1);
  m=800;
  func5->SetParameter(0,m);
  func5->SetLineColor(TColor::GetColor("#ECD078"));
  func5->SetLineWidth(2);
  func5->SetNpx(500);
  func5->Draw("SAME");

  c->SaveAs("pseudoscalar.pdf");
}
void FindPeak(TH1 *hm, int * i, char * namefile){
  int np =5, p, max = 0;
  int npeaks = TMath::Abs(np);
  double par[3000];
  par[0] = 0.8;
  par[1] = -0.6/1000;

  for (p=0;p<npeaks;p++) {
    par[3*p+2] = 1;
    par[3*p+3] = 10+gRandom->Rndm()*980;
    par[3*p+4] = 3+2*gRandom->Rndm();
  }
 
  TSpectrum *s = new TSpectrum(2*npeaks,1);
  int nfound = s->Search(hm,2,"",0.10);
  printf("Found %d candidate peaks to fit\n",nfound);

  TH1 *hb = s->Background(hm,20,"same");
  if (np <0) return;

  // loope over peaks
  TF1 *fline = new TF1("fline","pol1",0,1000);
  hm->Fit("fline","qn");
  par[0] = fline->GetParameter(0);
  par[1] = fline->GetParameter(1);
  npeaks = 0;
  float *xpeaks = s->GetPositionX();
  for (p=0;p<nfound;p++) {
    float xp = xpeaks[p];
    int bin = hm->GetXaxis()->FindBin(xp);
    float yp = hm->GetBinContent(bin);
    if (yp-TMath::Sqrt(yp) < fline->Eval(xp)) continue;
    par[3*npeaks+2] = yp;
    par[3*npeaks+3] = xp;
    par[3*npeaks+4] = 3;
    npeaks++;
  }
  printf("Found %d useful peaks to fit\n",npeaks); 
  printf("Now fitting: Be patient\n");
  if (max < npeaks) max = npeaks;
  TF1 *fit = new TF1("fit",fpeaks,0,1000,2+3*npeaks);
  TVirtualFitter::Fitter(hm,10+3*npeaks);
  fit->SetParameters(par);
  fit->SetNpx(1000);
  hm->Fit("fit"); 
}
Ejemplo n.º 7
0
void drawShapes (TGraph ** tg_sample_par, int Npar)
  {
    TGraph * log_tg_sample_par0 = makeLog (tg_sample_par[0]) ;
    //PG loop on candidate masses
    for (double mass = 300 ; mass < 1100 ; mass += 25)
      {
        TF1 * func = new TF1 ("func",crystalBallLowHigh, 200, 2000, 7) ;
        func->SetParameter (0, TMath::Exp (log_tg_sample_par0->Eval (mass))) ;
        for (int iPar = 1 ; iPar < Npar ; ++iPar)
          func->SetParameter (iPar, tg_sample_par[iPar]->Eval (mass)) ;
        func->SetLineWidth (1) ;
        func->SetLineColor (kBlue + 1) ;
        func->SetNpx (10000) ;
        func->Draw ("same") ;
      } //PG loop on candidate masses
    return ;
  }
Ejemplo n.º 8
0
void drawOriginals (TGraph ** tg_sample_par, int color, int Npar)
  {
    //PG loop on candidate masses
    double masses[5] = {350, 500, 650, 800, 1000} ;
    for (int i = 0 ; i < 5 ; ++i)
      {
        mass = masses[i] ;
        TF1 * func = new TF1 ("func",crystalBallLowHigh, 200, 2000, 7) ;
        for (int iPar = 0 ; iPar < Npar ; ++iPar)
          func->SetParameter (iPar, tg_sample_par[iPar]->Eval (mass)) ;
        func->SetLineWidth (1) ;
        func->SetLineColor (color) ;
        func->SetNpx (10000) ;
        func->Draw ("same") ;
      } //PG loop on candidate masses
    return ;
  }
Ejemplo n.º 9
0
void GetRandomTest(){
	double k0=1.39;
	double k1 = 0.425;
	double theta0 = 3.41;
	double theta1 = 1.30;
	int iNpart=2;
	double k_=k0+k1*(iNpart-2);
        double theta_=theta0+theta1*TMath::Log(iNpart-1);
	TF1 *f = new TF1("f","TMath::GammaDist(x,[0],0,[1])",0,200);
	f->SetParameters(k1,theta_);
	cout<<"Value at 0 = "<<f->Eval(0)<<endl;
	cout<<"Value at 1e-11 = "<<f->Eval(1e-11)<<endl;
	cout<<"Integral 1= "<<f->Integral(f->GetXmin(),f->GetXmax())<<endl;
	f->SetRange(1e-12,200);
	cout<<"Integral 2= "<<f->Integral(f->GetXmin(),f->GetXmax())<<endl;
	cout<<"fXmin = "<<f->GetXmin()<<"\tfXmax = "<<f->GetXmax()<<"\tfNpx = "<<f->GetNpx()<<endl;
	f->SetNpx(1e5);
	TCanvas *c1 = new TCanvas();
	c1->SetLogy();
	cout<<"f mean = "<<f->Mean(0,200)<<endl;
	cout<<"math mean = "<<f->GetParameter(0)*f->GetParameter(1)<<endl;
	TH1D* h = new TH1D("h","h",1000,0,200);
	for(int i=0;i<1e6;i++){
		double para = f->GetRandom();
		h->Fill(para);
	}
	h->Scale(1.0/h->Integral()*1000/200);
	h->GetYaxis()->SetRangeUser(1e-10,1);
	h->SetMarkerStyle(24);
	h->SetMarkerColor(4);
	h->SetMarkerSize(1.1);
	TLegend *leg = new TLegend(0.6,0.7,0.8,0.9);
        leg->SetFillColor(0);
        leg->SetFillStyle(0);
        leg->SetBorderSize(0);
        leg->SetTextFont(42);
        leg->SetTextSize(0.03);
        leg->AddEntry(f,"function","lp");
        leg->AddEntry(h,"filled histogram","lp");
	h->Draw("P");
	f->Draw("same");
        leg->Draw("same");
	cout<<"h mean = "<<h->GetMean(1)<<endl;
	c1->Print("TestGetRandom.png");
	}
Ejemplo n.º 10
0
Double_t fitfulllang( char* hs ) {

  TH1 *h = (TH1*)gDirectory->Get(hs);

  if( h == NULL ){
    cout << hs << " does not exist\n";
    return 0;
  }

  double aa = h->GetEntries();//normalization

  // find peak:
  int ipk = h->GetMaximumBin();
  double xpk = h->GetBinCenter(ipk);
  double sm = xpk / 9; // sigma
  double ns = sm; // noise

  // fit range:
  int ib0 = ipk/2;
  int ib9 = h->GetNbinsX() - 1;

  double x0 = h->GetBinLowEdge(ib0);
  double x9 = h->GetBinLowEdge(ib9) + h->GetBinWidth(ib9);

  // create a TF1 with the range from x0 to x9 and 4 parameters
  TF1 *fitFcn = new TF1( "fitFcn", fitLandauGauss, x0, x9, 4 );

  fitFcn->SetParName( 0, "peak" );
  fitFcn->SetParName( 1, "sigma" );
  fitFcn->SetParName( 2, "area" );
  fitFcn->SetParName( 3, "smear" );

  fitFcn->SetNpx(500);
  fitFcn->SetLineWidth(4);
  fitFcn->SetLineColor(kMagenta);

  // set start values:
  fitFcn->SetParameter( 0, xpk ); // peak position, defined above
  fitFcn->SetParameter( 1, sm ); // width
  fitFcn->SetParameter( 2, aa ); // area
  fitFcn->SetParameter( 3, ns ); // noise

  h->Fit("fitFcn", "NQR", "ep" );// R = range from fitFcn
  return fitFcn->GetParameter(0);
}
Ejemplo n.º 11
0
void v()
{

    TF1 *signal = new TF1("DGauss", DGauss, 0, 800, 7);
    signal->SetParameter(0, 50);
    signal->SetParameter(1, 1);
    signal->SetParameter(2, 2);
    signal->SetParameter(3, 100);
    signal->SetParameter(4, -20);

    signal->SetParameter(5, 22.374);
    signal->SetParameter(6, 5.55);
    signal->SetNpx(10000);


    signal->Draw();

}
Ejemplo n.º 12
0
// This is the main program
void slits() {
  float r,ns;

  // request user input
  cout << "slit width / g ? ";
  scanf("%f",&r);
  cout << "# of slits? ";
  scanf("%f",&ns);
  cout <<"interference pattern for "<< ns
       <<" slits, width/distance: "<<r<<endl;

  // define function and set options
  TF1 *Fnslit  = new TF1("Fnslit",nslit,-5.001,5.,2);
  Fnslit->SetNpx(500);
    
  // set parameters, as read in above
  Fnslit->SetParameter(0,r);
  Fnslit->SetParameter(1,ns);
    
  // draw the interference pattern for a grid with n slits
  Fnslit->Draw();
}
Ejemplo n.º 13
0
void fitmmp(TH1 *hmmp, bool verbose = false) {
  TString options;
  if (verbose) options = "";
  else options = "Q";
  TF1 *fbg = f_pol4("fbg",0.4,2,true);
  hmmp->Fit(fbg,options.Data(),"",0.42,2);
  //printf("%s\n",gMinuit->fCstatu.Data());
  if (true) { //gMinuit->fCstatu.Contains("CONVER")) {
    TF1 *fbg2 = f_pol4("fbg",0.4,2,false);
    fbg2->SetParameters(fbg->GetParameters());
    //fbg2->Draw("same");
    fbg2->SetParameter(5,0);
    fbg2->SetParameter(6,0);
    TH1 *htmp = (TH1*)hmmp->Clone("hmmp_bgsub");
    htmp->Add(fbg2,-1);
    //htmp->Draw();
    TF1 *fgaus = new TF1("fgaus","gaus",0.4,2);
    htmp->Fit(fgaus,options.Data(),"",0.74,0.85);
    TF1 *f = f_pol4gaus("f",0.4,2,fbg2,fgaus);
    f->SetNpx(500);
    hmmp->Fit(f,options.Data(),"",0.42,2);
    fgaus->SetRange(0.4,2);
    for (int i = 0; i < 3; i++) fgaus->SetParameter(i,f->GetParameter(i+5));
    for (int i = 0; i < 5; i++) fbg2->SetParameter(i,f->GetParameter(i));
    fbg2->SetLineStyle(2);
    fbg2->SetLineColor(kRed+1);
    fgaus->SetLineStyle(2);
    fgaus->SetLineColor(kGreen+1);
    hmmp->GetListOfFunctions()->Add(fbg2->Clone());
    hmmp->GetListOfFunctions()->Add(fgaus->Clone());
    delete fbg2;
    delete htmp;
    delete fgaus;
    delete f;
  } else hmmp->GetListOfFunctions()->Delete();
  delete fbg;
}
Ejemplo n.º 14
0
void doCoinc3(const char *fileIn="SAVO-01-SAVO-02-SAVO-03-2016-01-26.root"){
  Int_t adayMin = (yearRange[0]-2007) * 1000 + monthRange[0]*50 + dayRange[0];
  Int_t adayMax = (yearRange[1]-2007) * 1000 + monthRange[1]*50 + dayRange[1];

  // define some histos
  TH1F *hDeltaTheta12 = new TH1F("hDeltaTheta12","#Delta#theta_{12} below the peak (500 ns);#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhi12 = new TH1F("hDeltaPhi12","#Delta#phi_{12} below the peak (500 ns);#Delta#phi (#circ)",200,-360,360);
  TH1F *hDeltaThetaBack12 = new TH1F("hDeltaThetaBack12","#Delta#theta_{12} out of the peak (> 1000 ns) - normalized;#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhiBack12 = new TH1F("hDeltaPhiBack12","#Delta#phi_{12} out of the peak (> 1000 ns)  - normalized;#Delta#phi (#circ)",200,-360,360);
  TH1F *hThetaRel12 = new TH1F("hThetaRel12","#theta_{rel}_{12} below the peak (500 ns);#theta_{rel} (#circ)",100,0,120);
  TH1F *hThetaRelBack12 = new TH1F("hThetaRelBack12","#theta_{rel}_{12} out of the peak (> 1000 ns)  - normalized;#theta_{rel} (#circ)",100,0,120);

  TH1F *hDeltaTheta13 = new TH1F("hDeltaTheta13","#Delta#theta_{13} below the peak (500 ns);#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhi13 = new TH1F("hDeltaPhi13","#Delta#phi_{13} below the peak (500 ns);#Delta#phi (#circ)",200,-360,360);
  TH1F *hDeltaThetaBack13 = new TH1F("hDeltaThetaBack13","#Delta#theta_{13} out of the peak (> 1000 ns) - normalized;#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhiBack13 = new TH1F("hDeltaPhiBack13","#Delta#phi_{13} out of the peak (> 1000 ns)  - normalized;#Delta#phi (#circ)",200,-360,360);
  TH1F *hThetaRel13 = new TH1F("hThetaRel13","#theta_{rel}_{13} below the peak (500 ns);#theta_{rel} (#circ)",100,0,120);
  TH1F *hThetaRelBack13 = new TH1F("hThetaRelBack13","#theta_{rel}_{13} out of the peak (> 1000 ns)  - normalized;#theta_{rel} (#circ)",100,0,120);


  TFile *f = new TFile(fileIn);
  TTree *t = (TTree *) f->Get("tree");
  
  TTree *tel[3];
  tel[0] = (TTree *) f->Get("treeTel1");
  tel[1] = (TTree *) f->Get("treeTel2");
  tel[2] = (TTree *) f->Get("treeTel3");
  
  TTree *telC = (TTree *) f->Get("treeTimeCommon");
  
  // quality info of runs
  Bool_t runstatus[3][10][12][31][500]; //#telescope, year-2007, month, day, run
  
  if(tel[0] && tel[1] && tel[2]){
    for(Int_t i=0;i < 3;i++){ // loop on telescopes
      for(Int_t j=0;j < tel[i]->GetEntries();j++){ // loop on runs
	tel[i]->GetEvent(j);
	Int_t aday = (tel[i]->GetLeaf("year")->GetValue()-2007) * 1000 + tel[i]->GetLeaf("month")->GetValue()*50 + tel[i]->GetLeaf("day")->GetValue();

	if(aday < adayMin || aday > adayMax) continue;
	if(tel[i]->GetLeaf("FractionGoodTrack")->GetValue() < fracGT[i]) continue; // cut on fraction of good track
	if(tel[i]->GetLeaf("timeduration")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue() < hitevents[i]) continue; // cut on the number of event
	if(tel[i]->GetLeaf("ratePerRun")->GetValue() < rateMin[i] || tel[i]->GetLeaf("ratePerRun")->GetValue() > rateMax[i]) continue; // cut on the rate
	if(tel[i]->GetLeaf("run")->GetValue() > 499) continue; // run < 500

	Float_t missinghitfrac = (tel[i]->GetLeaf("ratePerRun")->GetValue()-tel[i]->GetLeaf("rateHitPerRun")->GetValue()-2)/(tel[i]->GetLeaf("ratePerRun")->GetValue()-2);
	if(missinghitfrac < minmissingHitFrac[i] || missinghitfrac > maxmissingHitFrac[i]) continue;

	
	runstatus[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2007][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = kTRUE;
	
      }
    }
  }
  else{
    telC = NULL;
  }
  
  Int_t n = t->GetEntries();

  // counter for seconds
  Int_t nsec = 0;
  Int_t nsecGR = 0; // for good runs
  Int_t isec = -1; // used only in case the tree with time info is not available

  if(telC){
    for(Int_t i=0; i < telC->GetEntries();i++){
      telC->GetEvent(i);
      nsec += telC->GetLeaf("timeduration")->GetValue(); 
      
      
      
      if(telC->GetLeaf("run")->GetValue() > 499 || telC->GetLeaf("run2")->GetValue() > 499 || telC->GetLeaf("run3")->GetValue() > 499) continue;
      
      if(!runstatus[0][Int_t(telC->GetLeaf("year")->GetValue())-2007][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())]) continue;
      
      if(!runstatus[1][Int_t(telC->GetLeaf("year")->GetValue())-2007][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run2")->GetValue())]) continue;

      if(!runstatus[2][Int_t(telC->GetLeaf("year")->GetValue())-2007][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run2")->GetValue())]) continue;
      
      nsecGR += telC->GetLeaf("timeduration")->GetValue(); 
    }
  }
  
  char title[600];
  TH1F *h;
  TH2F *h2;

  sprintf(title,"correction assuming #Delta#phi_{12} = %4.2f, #DeltaL_{12} = %.1f m, #Delta#phi_{13} = %4.2f, #DeltaL_{13} = %.1f m;#Deltat_{13} (ns) when |#Deltat_{12}| < %i ns;entries",angle12,distance12,angle13,distance13,timeCutOn12);
  h = new TH1F("hCoinc",title,nbint,tmin,tmax);
  sprintf(title,"correction assuming #Delta#phi_{12} = %4.2f, #DeltaL_{12} = %.1f m, #Delta#phi_{13} = %4.2f, #DeltaL_{13} = %.1f m;#Deltat_{12} (ns);#Deltat_{13} (ns);entries",angle12,distance12,angle13,distance13,timeCutOn12);
  h2 = new TH2F("hCoinc2D",title,nbint,tmin,tmax,nbint,tmin,tmax);
  
  Float_t DeltaT12,DeltaT13;
  Float_t phiAv,thetaAv,corr12,corr13;
  
  Float_t Theta1,Theta2,Theta3;
  Float_t Phi1,Phi2,Phi3;
  
  Float_t v1[3],v2[3],v3[3],vSP12,vSP13; // variable to recompute ThetaRel on the fly
  
  for(Int_t i=0;i<n;i++){
    t->GetEvent(i);
    
    // if(t->GetLeaf("RunNumber1") && (t->GetLeaf("RunNumber1")->GetValue() > 499 || t->GetLeaf("RunNumber2")->GetValue() > 499) || t->GetLeaf("RunNumber3")->GetValue() > 499)) continue;
  
    // if(tel[0] && !runstatus[0][Int_t(t->GetLeaf("year")->GetValue())-2007][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())]) continue;
    
    // if(tel[1] && !runstatus[1][Int_t(t->GetLeaf("year")->GetValue())-2007][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())]) continue;
  
    // if(tel[2] && !runstatus[2][Int_t(t->GetLeaf("year")->GetValue())-2007][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())]) continue;
    
    Int_t timec = t->GetLeaf("ctime1")->GetValue();
    
    if(! telC){
      if(isec == -1) isec = timec;
      
      if(timec != isec){
	if(timec - isec < 20){
	  //	printf("diff = %i\n",timec-isec);
	  nsec +=(timec - isec);
	  nsecGR +=(timec - isec);
	}
	isec = timec;
      }
    }

    Float_t thetarel12 = t->GetLeaf("ThetaRel12")->GetValue();
    Float_t thetarel13 = t->GetLeaf("ThetaRel13")->GetValue();
    Theta1 = t->GetLeaf("Theta1")->GetValue()*TMath::DegToRad();
    Theta2 = t->GetLeaf("Theta2")->GetValue()*TMath::DegToRad();
    Theta3 = t->GetLeaf("Theta3")->GetValue()*TMath::DegToRad();
    Phi1 = t->GetLeaf("Phi1")->GetValue()*TMath::DegToRad();
    Phi2 = t->GetLeaf("Phi2")->GetValue()*TMath::DegToRad();
    Phi3 = t->GetLeaf("Phi3")->GetValue()*TMath::DegToRad();
    
    if(recomputeThetaRel){ // recompute ThetaRel applying corrections
      Phi1 -= phi1Corr*TMath::DegToRad();
      Phi2 -= phi2Corr*TMath::DegToRad();
      Phi3 -= phi3Corr*TMath::DegToRad();
      if(Phi1 > 2*TMath::Pi()) Phi1 -= 2*TMath::Pi();
      if(Phi1 < 0) Phi1 += 2*TMath::Pi();
      if(Phi2 > 2*TMath::Pi()) Phi2 -= 2*TMath::Pi();
      if(Phi2 < 0) Phi2 += 2*TMath::Pi();
      if(Phi3 > 2*TMath::Pi()) Phi3 -= 2*TMath::Pi();
      if(Phi3 < 0) Phi3 += 2*TMath::Pi();
      
      v1[0] = TMath::Sin(Theta1)*TMath::Cos(Phi1);
      v1[1] = TMath::Sin(Theta1)*TMath::Sin(Phi1);
      v1[2] = TMath::Cos(Theta1);
      v2[0] = TMath::Sin(Theta2)*TMath::Cos(Phi2);
      v2[1] = TMath::Sin(Theta2)*TMath::Sin(Phi2);
      v2[2] = TMath::Cos(Theta2);
      v3[0] = TMath::Sin(Theta3)*TMath::Cos(Phi3);
      v3[1] = TMath::Sin(Theta3)*TMath::Sin(Phi3);
      v3[2] = TMath::Cos(Theta3);
      
      v2[0] *= v1[0];
      v2[1] *= v1[1];
      v2[2] *= v1[2];
      v3[0] *= v1[0];
      v3[1] *= v1[1];
      v3[2] *= v1[2];
      
      vSP12 = v2[0] + v2[1] + v2[2];
      vSP13 = v3[0] + v3[1] + v3[2];
      
      thetarel12 = TMath::ACos(vSP12)*TMath::RadToDeg();
      thetarel13 = TMath::ACos(vSP13)*TMath::RadToDeg();
    }
    
    // cuts
    if(thetarel12 > maxthetarel) continue;
    if(thetarel13 > maxthetarel) continue;
    if(t->GetLeaf("ChiSquare1")->GetValue() > maxchisquare) continue;
    if(t->GetLeaf("ChiSquare2")->GetValue() > maxchisquare) continue;
    if(t->GetLeaf("ChiSquare3")->GetValue() > maxchisquare) continue;
    
    DeltaT12 = t->GetLeaf("DiffTime12")->GetValue();
    DeltaT13 = t->GetLeaf("DiffTime13")->GetValue();
    
    // get primary direction
    if(TMath::Abs(Phi1-Phi2) < TMath::Pi()) phiAv = (Phi1+Phi2)*0.5;
    else phiAv = (Phi1+Phi2)*0.5 + TMath::Pi();
    if(TMath::Abs(phiAv-Phi3) < TMath::Pi()) phiAv = (phiAv*2+Phi2)*0.33333333333;
    else if(phiAv > Phi3) phiAv = (phiAv*2+Phi3+2*TMath::Pi())*0.33333333333;
    else phiAv = (phiAv*2+4*TMath::Pi()+Phi3)*0.33333333333;


    thetaAv = (Theta1+Theta2+Theta3)*0.333333333333;
    
    // extra cuts if needed
    //    if(TMath::Cos(Phi1-Phi2) < 0.) continue;
    
    corr12 = distance12 * TMath::Sin(thetaAv)*TMath::Cos(phiAv-angle12)/2.99792458000000039e-01 + deltatCorr12;
    corr13 = distance13 * TMath::Sin(thetaAv)*TMath::Cos(phiAv-angle13)/2.99792458000000039e-01 + deltatCorr13;
    
    if(TMath::Abs(DeltaT12-corr12) < timeCutOn12) h->Fill(DeltaT13-corr13);
    h2->Fill(DeltaT12-corr12,DeltaT13-corr13);

    if(TMath::Abs(DeltaT12-corr12) < 500){
      hDeltaTheta12->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhi12->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRel12->Fill(thetarel12);
    }
    else if(TMath::Abs(DeltaT12-corr12) > 1000 && TMath::Abs(DeltaT12-corr12) < 6000){
      hDeltaThetaBack12->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhiBack12->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRelBack12->Fill(thetarel12);
    }

    if(TMath::Abs(DeltaT13-corr13) < 500){
      hDeltaTheta13->Fill((Theta1-Theta3)*TMath::RadToDeg());
      hDeltaPhi13->Fill((Phi1-Phi3)*TMath::RadToDeg());
      hThetaRel13->Fill(thetarel13);
    }
    else if(TMath::Abs(DeltaT13-corr13) > 1000 && TMath::Abs(DeltaT13-corr13) < 6000){
      hDeltaThetaBack13->Fill((Theta1-Theta3)*TMath::RadToDeg());
      hDeltaPhiBack13->Fill((Phi1-Phi3)*TMath::RadToDeg());
      hThetaRelBack13->Fill(thetarel13);
    }
  }
  
  h->SetStats(0);

  hDeltaThetaBack12->Sumw2();
  hDeltaPhiBack12->Sumw2();
  hThetaRelBack12->Sumw2();
  hDeltaThetaBack12->Scale(0.1);
  hDeltaPhiBack12->Scale(0.1);
  hThetaRelBack12->Scale(0.1);
  hDeltaThetaBack13->Sumw2();
  hDeltaPhiBack13->Sumw2();
  hThetaRelBack13->Sumw2();
  hDeltaThetaBack13->Scale(0.1);
  hDeltaPhiBack13->Scale(0.1);
  hThetaRelBack13->Scale(0.1);

  Float_t val,eval;
  TCanvas *c1=new TCanvas();
  TF1 *ff = new TF1("ff","[0]*[4]/[2]/sqrt(2*TMath::Pi())*TMath::Exp(-(x-[1])*(x-[1])*0.5/[2]/[2]) + [3]*[4]/6/[2]");
  ff->SetParName(0,"signal");
  ff->SetParName(1,"mean");
  ff->SetParName(2,"sigma");
  ff->SetParName(3,"background");
  ff->SetParName(4,"bin width");
  ff->SetParameter(0,42369);
  ff->SetParameter(1,0);
  ff->SetParLimits(2,10,1000);
  ff->SetParameter(2,150); // fix witdh if needed
  ff->SetParameter(3,319);
  ff->FixParameter(4,20000./nbint); // bin width
  
  ff->SetNpx(1000);
  
  h->Fit(ff);
  
  val = ff->GetParameter(2);
  eval = ff->GetParError(2);
  
  printf("significance = %f\n",ff->GetParameter(0)/sqrt(ff->GetParameter(0) + ff->GetParameter(3)));

  h->Draw();
  
  TF1 *func1 = (TF1 *)  h->GetListOfFunctions()->At(0);
  
  func1->SetLineColor(2);
  h->SetLineColor(4);
  
  TPaveText *text = new TPaveText(1500,(h->GetMinimum()+(h->GetMaximum()-h->GetMinimum())*0.6),9500,h->GetMaximum());
  text->SetFillColor(0);
  sprintf(title,"width = %5.1f #pm %5.1f",func1->GetParameter(2),func1->GetParError(2));
  text->AddText(title);
  sprintf(title,"signal (S) = %5.1f #pm %5.1f",func1->GetParameter(0),func1->GetParError(0));
  text->AddText(title);
  sprintf(title,"background (B) (3#sigma) = %5.1f #pm %5.1f",func1->GetParameter(3),func1->GetParError(3));
  text->AddText(title);
  sprintf(title,"significance (S/#sqrt{S+B}) = %5.1f",func1->GetParameter(0)/sqrt(func1->GetParameter(0)+func1->GetParameter(3)));
  text->AddText(title);
  
  text->SetFillStyle(0);
  text->SetBorderSize(0);
  
  text->Draw("SAME");
  
  printf("n_day = %f\nn_dayGR = %f\n",nsec*1./86400,nsecGR*1./86400);

  text->AddText(Form("rate = %f #pm %f per day",func1->GetParameter(0)*86400/nsecGR,func1->GetParError(0)*86400/nsecGR));

  TFile *fo = new TFile("output-SAVO-010203.root","RECREATE");
  h->Write();
  h2->Write();
  hDeltaTheta12->Write();
  hDeltaPhi12->Write();
  hThetaRel12->Write();
  hDeltaThetaBack12->Write();
  hDeltaPhiBack12->Write();
  hThetaRelBack12->Write();
  hDeltaTheta13->Write();
  hDeltaPhi13->Write();
  hThetaRel13->Write();
  hDeltaThetaBack13->Write();
  hDeltaPhiBack13->Write();
  hThetaRelBack13->Write();
  fo->Close();
  
}
Ejemplo n.º 15
0
void proc_pileup(const AliVdMMetaData& vdmMetaData,
                 AliVdMScanData& allData,
                 const char* classAC,
                 const char* classAnotC,
                 const char* classCnotA,
                 const std::vector<Double_t>& par0)
{
  typedef std::map<Short_t, TGraphErrors> map_t; // BCID -> TGraphErrors
  map_t gAnotC, gCnotA;  // one-arm/two-arm ratios

  // (1) fill one-arm/two-arm ratio graphs for all BCIDs
  for (Int_t iScan=0; iScan<4; ++iScan) {
    AliVdMTree& vtAND   = allData.GetMap(iScan)[classAC];
    AliVdMTree& vtAnotC = allData.GetMap(iScan)[classAnotC];
    AliVdMTree& vtCnotA = allData.GetMap(iScan)[classCnotA];
    vtAND.Zip3([&gAnotC,&gCnotA](const AliVdMTree::DefaultBranchData& d,
                                 AliVdMTree::branchMap_t& mapAC,
                                 AliVdMTree::branchMap_t& mapAnotC,
                                 AliVdMTree::branchMap_t& mapCnotA)
               {
                 AliVdMTree::ValErr v1 = mapAnotC["rate"];
                 v1 /= mapAC["rate"];
                 // v1 /= mapAC["relBkgd"];
                 v1 *= mapAnotC["relBkgd"];
                 if (!v1.isInf() && v1.val()) {
                   const Int_t m1 = gAnotC[d.BCID()].GetN();
                   gAnotC[d.BCID()].SetPoint     (m1, mapAC["mu"].val(), v1.val());
                   gAnotC[d.BCID()].SetPointError(m1, mapAC["mu"].err(), v1.err());
                 }
                 AliVdMTree::ValErr v2 = mapCnotA["rate"];
                 v2 /= mapAC["rate"];
                 // v2 /= mapAC["relBkgd"];
                 v2 *= mapCnotA["relBkgd"];
                 if (!v2.isInf() && v2.val()) {
                   const Int_t m2 = gCnotA[d.BCID()].GetN();
                   gCnotA[d.BCID()].SetPoint     (m2, mapAC["mu"].val(), v2.val());
                   gCnotA[d.BCID()].SetPointError(m2, mapAC["mu"].err(), v2.err());
                 }
               },
               vtAnotC, vtCnotA);
  }

  // (2) fit model
  AliVdMPileup pileupModel;

  TString pn = TString::Format("pileup_%s.pdf", classAC);
  TCanvas *c1 = new TCanvas;
  c1->SaveAs(pn+"[");

  const AliTriggerBCMask& bcMask = vdmMetaData.GetTriggerBCMask();
  const Int_t             nBCs   = bcMask.GetNUnmaskedBCs();

  TH1 *hPar[5] = {
    SetAttr(new TH1D("hrA",      ";BCID;r_{A}",           nBCs,0,nBCs), kRed),
    SetAttr(new TH1D("hrC",      ";BCID;r_{C}",           nBCs,0,nBCs), kBlue),
    SetAttr(new TH1D("hbkgdA",   ";BCID;bkgd_{A}",        nBCs,0,nBCs), kRed),
    SetAttr(new TH1D("hbkgdC",   ";BCID;bkgd_{C}",        nBCs,0,nBCs), kBlue),
    SetAttr(new TH1D("hChi2NDF", ";BCID;#chi^{2}/n.d.f.", nBCs,0,nBCs), kBlue)
  };

  for (Int_t bc=0, counter=0; bc<3564; ++bc) {
    if (bcMask.GetMask(bc))
      continue;

    const TString binLabel = TString::Format("%d", bc);
    for (Int_t i=0; i<5; ++i)
      hPar[i]->GetXaxis()->SetBinLabel(1+counter, binLabel);

    c1->Clear();
    c1->SetLogx();
    c1->SetLogy();
    TH1 *hf = c1->DrawFrame(1e-6, 0.01, 0.5, 20);
    hf->SetTitle(TString::Format("BCID=%d %s;two-arm #mu;one-arm/two-arm", bc, classAC));
    pileupModel.DoFit(&gAnotC[bc], &gCnotA[bc], &par0[0]);

    SetAttr(&gAnotC[bc], kBlue);
    SetAttr(&gCnotA[bc], kRed);
    gAnotC[bc].Draw("PE");
    gCnotA[bc].Draw("PE");

    TF1 *fAnotC = SetAttr(new TF1("fAnotC", &pileupModel, &AliVdMPileup::fcnAnotC, 1e-6, 0.5, 5), kBlue);
    fAnotC->SetParameters(pileupModel.GetPar());
    fAnotC->SetNpx(1000);
    fAnotC->Draw("same");

    TF1 *fCnotA = SetAttr(new TF1("fCnotA", &pileupModel, &AliVdMPileup::fcnCnotA, 1e-6, 0.5, 5), kRed);
    fCnotA->SetParameters(pileupModel.GetPar());
    fCnotA->SetNpx(1000);
    fCnotA->Draw("same");

    TLegend *leg = new TLegend(0.6, 0.75, 0.9, 0.9);
    leg->AddEntry(&gCnotA[bc], "AnotC/AandC", "PEL");
    leg->AddEntry(&gAnotC[bc], "CnotA/AandC", "PEL");
    leg->Draw();

    TPaveText *pt = new TPaveText(0.6, 0.4, 0.9, 0.7, "NDC NB");
    pt->SetFillStyle(0);
    pt->AddText(TString::Format("#chi^{2}/n.d.f = %.0f/%.0f = %.2f", pileupModel.GetChi2(), pileupModel.GetNDF(), pileupModel.GetChi2()/pileupModel.GetNDF()));
    {
      double curval,err, lowlim, uplim;
      int iuint;
      TString name;
      for (Int_t ivar=0; ivar<4; ++ivar) {
        gMinuit->mnpout(ivar, name, curval, err, lowlim, uplim,iuint);
        hPar[ivar]->SetBinContent(1+counter, curval);
        hPar[ivar]->SetBinError(1+counter, err);
        if (ivar==0) {
          hf->SetMinimum(0.5*curval);
        }
        if (ivar==1) {
          hf->SetMinimum(TMath::Min(hf->GetMinimum(), 0.5*curval));
        }
        if (ivar < 2)
          pt->AddText(TString::Format("%s = %.4f#pm%.4f", name.Data(), curval, err));
        else
          pt->AddText(TString::Format("%s = %.1e#pm%.1e", name.Data(), curval, err));
        pt->GetLine(1+ivar)->SetTextColor(ivar%2 ? kRed : kBlue);
      }
      hPar[4]->SetBinContent(1+counter, pileupModel.GetChi2()/pileupModel.GetNDF());
    }
    pt->Draw();
    c1->SaveAs(pn);
    Printf("%f / %f", pileupModel.GetChi2(), pileupModel.GetNDF());
    ++counter;
  }
  gStyle->SetOptStat("n");
  gStyle->SetOptFit(111);
  TCanvas *c2 = new TCanvas;
  for (Int_t i=0; i<4; ++i) {
    FitPol0(hPar[i])->Draw();
    c2->SaveAs(pn);
  }
  hPar[4]->SetMinimum(0);
  hPar[4]->Draw();
  c2->SaveAs(pn+")");
}
Ejemplo n.º 16
0
void bToDRawYield()
{
	gStyle->SetTextSize(0.05);
	gStyle->SetTextFont(42);
	gStyle->SetPadRightMargin(0.04);
	gStyle->SetPadLeftMargin(0.14);
	gStyle->SetPadTopMargin(0.1);
	gStyle->SetPadBottomMargin(0.14);
	gStyle->SetTitleX(.0f);
	gStyle->SetOptFit(1111);
	gStyle->SetOptStat(0);
	gStyle->SetOptTitle(0);

	TCanvas* c4 = new TCanvas("c4","",800,600);
	c4->Divide(2,2);

	TCanvas* c2 = new TCanvas("c2","",400,600);
	c2->Divide(1,2);

	TCanvas* c1 = new TCanvas();

	TCanvas* c15 = new TCanvas("c15","",810,1000);
	c15->Divide(3,5);

	TFile* fPbPb = new TFile("bFeedDownPbPb.hist.root");
	TFile* fPbPbMB = new TFile("bFeedDownPbPbMB.hist.root");
	TFile* fPbPbMC = new TFile("bFeedDownPbPbMC.hist.root");
	TFile* fPbPbMBMC = new TFile("bFeedDownPbPbMBMC.hist.root");

	TH3D* hDataPbPb = (TH3D*)fPbPb->Get("hData");
	TH3D* hSidebandPbPb = (TH3D*)fPbPb->Get("hSideband");
	TH3D* hDataPbPbMB = (TH3D*)fPbPbMB->Get("hData");
	TH3D* hSidebandPbPbMB = (TH3D*)fPbPbMB->Get("hSideband");
	TH3D* hPtMD0DcaPbPb = (TH3D*)fPbPb->Get("hPtMD0Dca");
	TH3D* hPtMD0DcaPbPbMB = (TH3D*)fPbPbMB->Get("hPtMD0Dca");

	TH3D* hMCPSignalPbPb = (TH3D*)fPbPbMC->Get("hMCPSignal");
	TH3D* hMCNPSignalPbPb = (TH3D*)fPbPbMC->Get("hMCNPSignal");
	TH3D* hMCPSignalPbPbMB = (TH3D*)fPbPbMBMC->Get("hMCPSignal");
	TH3D* hMCNPSignalPbPbMB = (TH3D*)fPbPbMBMC->Get("hMCNPSignal");
	TH3D* hPtMD0DcaMCPSignalPbPb = (TH3D*)fPbPbMC->Get("hPtMD0DcaMCPSignal");
	TH3D* hPtMD0DcaMCPSwappedPbPb = (TH3D*)fPbPbMC->Get("hPtMD0DcaMCPSwapped");
	TH3D* hPtMD0DcaMCPSignalPbPbMB =(TH3D*)fPbPbMBMC->Get("hPtMD0DcaMCPSignal");
	TH3D* hPtMD0DcaMCPSwappedPbPbMB = (TH3D*)fPbPbMBMC->Get("hPtMD0DcaMCPSwapped");

	TH3D* hData = (TH3D*)hDataPbPb->Clone("hData");
	hData->Sumw2();
	hData->Add(hDataPbPbMB);

	TH3D* hSideband = (TH3D*)hSidebandPbPb->Clone("hSideband");
	hSideband->Sumw2();
	hSideband->Add(hSidebandPbPbMB);

	TH3D* hPtMD0Dca = (TH3D*)hPtMD0DcaPbPb->Clone("hPtMD0Dca");
	hPtMD0Dca->Sumw2();
	hPtMD0Dca->Add(hPtMD0DcaPbPbMB);

	TH3D* hMCPSignal = (TH3D*)hMCPSignalPbPb->Clone("hMCPSignal");
	hMCPSignal->Sumw2();
	hMCPSignal->Add(hMCPSignalPbPbMB);

	TH3D* hMCNPSignal = (TH3D*)hMCNPSignalPbPb->Clone("hMCNPSignal");
	hMCNPSignal->Sumw2();
	hMCNPSignal->Add(hMCNPSignalPbPbMB);

	TH3D* hPtMD0DcaMCPSignal = (TH3D*)hPtMD0DcaMCPSignalPbPb->Clone("hPtMD0DcaMCPSignal");
	hPtMD0DcaMCPSignal->Sumw2();
	hPtMD0DcaMCPSignal->Add(hPtMD0DcaMCPSignalPbPbMB);

	TH3D* hPtMD0DcaMCPSwapped =(TH3D*)hPtMD0DcaMCPSwappedPbPb->Clone("hPtMD0DcaMCPSwapped");
	hPtMD0DcaMCPSwapped->Sumw2();
	hPtMD0DcaMCPSwapped->Add(hPtMD0DcaMCPSwappedPbPbMB);

	TLatex* texCms = new TLatex(0.18,0.93, "#scale[1.25]{CMS} Preliminary");
	texCms->SetNDC();
	texCms->SetTextAlign(12);
	texCms->SetTextSize(0.06);
	texCms->SetTextFont(42);

	TLatex* texCol = new TLatex(0.96,0.93, "PbPb #sqrt{s_{NN}} = 5.02 TeV");
	texCol->SetNDC();
	texCol->SetTextAlign(32);
	texCol->SetTextSize(0.06);
	texCol->SetTextFont(42);

	const int nPtBins = 14;
	float ptBins[nPtBins+1] = {2.,3.,4.,5.,6.,8.,10.,12.5,15.0,20.,25.,30.,40.,60.,100};

	float pts[nPtBins];
	float ptErrors[nPtBins];
	float promptFraction[nPtBins];
	float totalYield[nPtBins];
	float totalYieldInvMassFit[nPtBins];
	float totalYieldInvMassFitError[nPtBins];
	float bToDYield[nPtBins];
	float bToDYieldError[nPtBins];
	float bToDYieldErrorDataOnly[nPtBins];
	float promptDYield[nPtBins];
	float promptDYieldError[nPtBins];
	float promptDYieldErrorDataOnly[nPtBins];

	const int nBinY = 14;
	Float_t binsY[nBinY+1];
	float firstBinYWidth = 0.001;
	float binYWidthRatio = 1.27;
	binsY[0]=0;
	for(int i=1; i<=nBinY; i++)
		binsY[i] = binsY[i-1]+firstBinYWidth*pow(binYWidthRatio,i-1);
	cout<<"last y bin: "<<binsY[nBinY]<<endl;

	//  for(int i=1; i<=nPtBins; i++)
	for(int i =7; i<=7; i++)
	{
		pts[i-1] = 0.5*(ptBins[i-1]+ptBins[i]);
		ptErrors[i-1] = 0.5*(ptBins[i]-ptBins[i-1]);
		float ptLow = ptBins[i-1];
		float ptHigh = ptBins[i];
		cout<<endl<<"======================================="<<endl;
		cout<<"pT range: "<<ptLow<<" "<<ptHigh<<endl;

		TLatex* texPtY = new TLatex(0.32,0.82,Form("%.1f < p_{T} < %.1f GeV/c      |y| < 1.0",ptLow,ptHigh));
		texPtY->SetNDC();
		texPtY->SetTextFont(42);
		texPtY->SetTextSize(0.06);
		texPtY->SetLineWidth(2);

		TLatex* texPt = new TLatex(0.18,0.82,Form("%.1f < p_{T} < %.1f GeV/c",ptLow,ptHigh));
		texPt->SetNDC();
		texPt->SetTextFont(42);
		texPt->SetTextSize(0.06);
		texPt->SetLineWidth(2);

		TLatex* texY = new TLatex(0.18,0.74,Form("|y| < 1.0"));
		texY->SetNDC();
		texY->SetTextFont(42);
		texY->SetTextSize(0.06);
		texY->SetLineWidth(2);

		c2->cd(1);

		hPtMD0Dca->GetZaxis()->SetRange(1,100);
		hPtMD0Dca->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hPtMD0DcaMCPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hPtMD0DcaMCPSwapped->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		TH1D* hMData = (TH1D*)hPtMD0Dca->Project3D("y")->Clone(Form("hM_%1.1f_%1.1f", ptLow, ptHigh));
		TH1D* hMMCSignal = (TH1D*)hPtMD0DcaMCPSignal->Project3D("y");
		TH1D* hMMCSwapped = (TH1D*)hPtMD0DcaMCPSwapped->Project3D("y");

		setColorTitleLabel(hMData);
		setColorTitleLabel(hMMCSignal);
		setColorTitleLabel(hMMCSwapped);

		TF1* fMass = fitMass(hMData, hMMCSignal, hMMCSwapped);

		texCms->Draw();
		texCol->Draw();
		texPt->Draw();
		texY->Draw();

		TF1* fSignalAndSwapped = new TF1("fSignalAndSwapped","[0]*([3]*([5]*Gaus(x,[1],[2]*(1+[7]))/(sqrt(2*3.1415927)*[2]*(1+[7]))+(1-[5])*Gaus(x,[1],[6]*(1+[7]))/(sqrt(2*3.1415927)*[6]*(1+[7])))+(1-[3])*Gaus(x,[1],[4]*(1+[7]))/(sqrt(2*3.1415927)*[4]*(1+[7])))", 1.7, 2.0);      
		fSignalAndSwapped->SetParameter(0,fMass->GetParameter(0));
		fSignalAndSwapped->SetParameter(1,fMass->GetParameter(1));
		fSignalAndSwapped->SetParameter(2,fMass->GetParameter(2));
		fSignalAndSwapped->SetParameter(3,fMass->GetParameter(7));
		fSignalAndSwapped->SetParameter(4,fMass->GetParameter(8));
		fSignalAndSwapped->SetParameter(5,fMass->GetParameter(9));
		fSignalAndSwapped->SetParameter(6,fMass->GetParameter(10));
		fSignalAndSwapped->SetParameter(7,fMass->GetParameter(11));

		TF1* background = new TF1("fBackground","[0]+[1]*x+[2]*x*x+[3]*x*x*x");
		background->SetParameter(0,fMass->GetParameter(3));
		background->SetParameter(1,fMass->GetParameter(4));
		background->SetParameter(2,fMass->GetParameter(5));
		background->SetParameter(3,fMass->GetParameter(6));

		cout<<"MC signal width: "<<fMass->GetParameter(2)<<"   "<<fMass->GetParameter(10)<<endl;
		cout<<"MC swapped width: "<<fMass->GetParameter(8)<<endl;

		float massD = 1.8649;
		float massSignal1 = massD-0.025;
		float massSignal2 = massD+0.025;
		float massSideBand1 = massD-0.1;
		float massSideBand2 = massD-0.075;
		float massSideBand3 = massD+0.075;
		float massSideBand4 = massD+0.1;

		float scaleSideBandBackground = background->Integral(massSignal1, massSignal2)/(background->Integral(massSideBand1, massSideBand2)+background->Integral(massSideBand3, massSideBand4));
		cout<<"scaleSideBandBackground: "<<scaleSideBandBackground<<endl;
		totalYieldInvMassFit[i-1] = fMass->GetParameter(0)*fMass->GetParameter(7)/hMData->GetBinWidth(1);
		totalYieldInvMassFitError[i-1] = fMass->GetParError(0)*fMass->GetParameter(7)/hMData->GetBinWidth(1);
		cout<<"totalYieldInvMassFit: "<<totalYieldInvMassFit[i-1]<<" +- "<<totalYieldInvMassFitError[i-1]<<endl;
		float scaleSideBandMethodSignal = fSignalAndSwapped->GetParameter(0)*fSignalAndSwapped->GetParameter(3) / (fSignalAndSwapped->Integral(massSignal1, massSignal2)-fSignalAndSwapped->Integral(massSideBand1, massSideBand2)-fSignalAndSwapped->Integral(massSideBand3, massSideBand4));
		cout<<"scaleSideBandMethodSignal: "<<scaleSideBandMethodSignal<<endl;

		TLatex* texScale = new TLatex(0.18,0.66,Form("side band bg scale: %1.3f", scaleSideBandBackground));
		texScale->SetNDC();
		texScale->SetTextFont(42);
		texScale->SetTextSize(0.06);
		texScale->SetLineWidth(2);
		texScale->Draw();

		TLine* lineSignal1 = new TLine(massSignal1, 0, massSignal1, hMData->GetMaximum()*0.5);
		TLine* lineSignal2 = new TLine(massSignal2, 0, massSignal2, hMData->GetMaximum()*0.5);
		TLine* lineSideBand1 = new TLine(massSideBand1, 0, massSideBand1, hMData->GetMaximum()*0.5);
		TLine* lineSideBand2 = new TLine(massSideBand2, 0, massSideBand2, hMData->GetMaximum()*0.5);
		TLine* lineSideBand3 = new TLine(massSideBand3, 0, massSideBand3, hMData->GetMaximum()*0.5);
		TLine* lineSideBand4 = new TLine(massSideBand4, 0, massSideBand4, hMData->GetMaximum()*0.5);
		lineSignal1->Draw();
		lineSignal2->Draw();
		lineSideBand1->Draw();
		lineSideBand2->Draw();
		lineSideBand3->Draw();
		lineSideBand4->Draw();

		c2->cd(2);
		gPad->SetLogy();

		hData->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hSideband->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hMCPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);
		hMCNPSignal->GetXaxis()->SetRangeUser(ptLow+0.001,ptHigh-0.001);

		TH1D* hD0DcaData0 = (TH1D*)hData->Project3D("y")->Clone("hD0DcaData0");
		TH1D* hD0DcaSideband = (TH1D*)hSideband->Project3D("y")->Clone("hD0DcaSideband");
		TH1D* hD0DcaMCPSignal0 = (TH1D*)hMCPSignal->Project3D("y")->Clone("hD0DcaMCPSignal0");
		TH1D* hD0DcaMCNPSignal0 = (TH1D*)hMCNPSignal->Project3D("y")->Clone("hD0DcaMCNPSignal0");

		float integralRawYieldMCP = hD0DcaMCPSignal0->Integral();
		float integralRawYieldMCNP = hD0DcaMCNPSignal0->Integral();
		cout<<"integralRawYieldMCP: "<<integralRawYieldMCP<<endl;
		cout<<"integralRawYieldMCNP: "<<integralRawYieldMCNP<<endl;

		hD0DcaMCPSignal = hD0DcaMCPSignal0;
		hD0DcaMCNPSignal = hD0DcaMCNPSignal0;

		divideBinWidth(hD0DcaData0);
		divideBinWidth(hD0DcaSideband);
		setColorTitleLabel(hD0DcaData0, 1);
		hD0DcaData0->GetXaxis()->SetRangeUser(0,0.07);
		hD0DcaData0->GetYaxis()->SetTitle("counts per cm");

		TH1D* hD0DcaSideband0 = (TH1D*)hD0DcaSideband->Clone("hD0DcaSideband0");
		hD0DcaSideband->Scale(scaleSideBandBackground);

		TH1D* hD0DcaDataSubSideBand = (TH1D*)hD0DcaData0->Clone("hD0DcaDataSubSideBand");
		hD0DcaDataSubSideBand->Add(hD0DcaSideband,-1);
		hD0DcaDataSubSideBand->Scale(scaleSideBandMethodSignal);

		hD0DcaData0->SetMarkerSize(0.6);
		hD0DcaData0->Draw();
		hD0DcaSideband->Draw("hsame");
		hD0DcaSideband0->SetLineStyle(2);
		hD0DcaSideband0->Draw("hsame");

		TLegend* leg1 = new TLegend(0.44,0.6,0.90,0.76,NULL,"brNDC");
		leg1->SetBorderSize(0);
		leg1->SetTextSize(0.06);
		leg1->SetTextFont(42);
		leg1->SetFillStyle(0);
		leg1->AddEntry(hD0DcaData0,"D^{0} candidate","pl");
		leg1->AddEntry(hD0DcaSideband,"side band","l");
		leg1->AddEntry(hD0DcaSideband0,"side band unscaled","l");
		leg1->Draw("same");

		texCms->Draw();
		texCol->Draw();
		texPtY->Draw();

		c2->SaveAs(Form("plots/PbPb_%.0f_%.0f_sideBand.pdf",ptLow,ptHigh));

		c2->cd(1);
		hMMCSignal->Draw();
		texCms->Draw();
		texCol->Draw();
		texPt->Draw();
		texY->Draw();

		c2->cd(2);
		gPad->SetLogy(0);
		hMMCSwapped->Draw();
		texCms->Draw();
		texCol->Draw();
		texPt->Draw();
		texY->Draw();

		c2->SaveAs(Form("plots/PbPb_%.0f_%.0f_McInvMassFit.pdf",ptLow,ptHigh));

		c15->cd(1);

		fitMass(hMData, hMMCSignal, hMMCSwapped);

		texPt->Draw();
		texY->Draw();

		TH1D* hD0DcaDataFit = new TH1D("hD0DcaDataFit", ";D^{0} DCA (cm);dN / d(D^{0} DCA) (cm^{-1})", nBinY, binsY);

		for(int j=1; j<=14; j++)
		{
			c15->cd(j+1);
			hPtMD0Dca->GetZaxis()->SetRange(j,j);
			float D0DcaLow = hPtMD0Dca->GetZaxis()->GetBinLowEdge(j);
			float D0DcaHigh = hPtMD0Dca->GetZaxis()->GetBinUpEdge(j);
			TH1D* hMData_D0Dca = (TH1D*)hPtMD0Dca->Project3D("y")->Clone(Form("hM_pt_%1.1f_%1.1f_D0Dca_%1.4f_%1.4f", ptLow, ptHigh, D0DcaLow, D0DcaHigh));
			setColorTitleLabel(hMData_D0Dca);
			fMass = fitMass(hMData_D0Dca, hMMCSignal, hMMCSwapped);

			float yield = fMass->GetParameter(0)*fMass->GetParameter(7)/hMData_D0Dca->GetBinWidth(1);
			float yieldError = fMass->GetParError(0)*fMass->GetParameter(7)/hMData_D0Dca->GetBinWidth(1);

			hD0DcaDataFit->SetBinContent(j, yield);
			hD0DcaDataFit->SetBinError(j, yieldError);

			TLatex* texD0Dca = new TLatex(0.18,0.82,Form("D^{0} DCA: %1.4f - %1.4f",D0DcaLow,D0DcaHigh));
			texD0Dca->SetNDC();
			texD0Dca->SetTextFont(42);
			texD0Dca->SetTextSize(0.06);
			texD0Dca->SetLineWidth(2);
			texD0Dca->Draw();

			TLatex* texYield = new TLatex(0.18,0.74,Form("D^{0} yield: %1.0f #pm %1.0f",yield,yieldError));
			texYield->SetNDC();
			texYield->SetTextFont(42);
			texYield->SetTextSize(0.06);
			texYield->SetLineWidth(2);
			texYield->Draw();
		}

		c15->SaveAs(Form("plots/PbPb_%.0f_%.0f_invMassFit.pdf",ptLow,ptHigh));

		divideBinWidth(hD0DcaDataFit);

		c4->cd(1);
		gPad->SetLogy();

		normalize(hD0DcaMCPSignal);
		setColorTitleLabel(hD0DcaMCPSignal, 2);
		hD0DcaMCPSignal->GetXaxis()->SetRangeUser(0,0.07);

		normalize(hD0DcaMCNPSignal);
		setColorTitleLabel(hD0DcaMCNPSignal, 4);
		hD0DcaMCNPSignal->GetXaxis()->SetRangeUser(0,0.07);
		hD0DcaMCNPSignal->GetYaxis()->SetTitle("dN / d(D^{0} DCA) (cm^{-1})");
		hD0DcaMCNPSignal->GetXaxis()->SetTitle("D^{0} DCA (cm)");
		hD0DcaMCNPSignal->SetMaximum(hD0DcaMCPSignal->GetMaximum()*3.);

		hD0DcaMCNPSignal->Draw("");
		hD0DcaMCPSignal->Draw("same");

		TLegend* leg2 = new TLegend(0.54,0.72,0.90,0.88,NULL,"brNDC");
		leg2->SetBorderSize(0);
		leg2->SetTextSize(0.06);
		leg2->SetTextFont(42);
		leg2->SetFillStyle(0);
		leg2->AddEntry(hD0DcaMCPSignal,"MC Prompt D^{0}","pl");
		leg2->AddEntry(hD0DcaMCNPSignal,"MC Non-prompt D^{0}","pl");
		leg2->Draw("same");

		c4->cd(2);
		gPad->SetLogy();

		TH1D* hD0DcaData = hD0DcaDataFit;
		if(pts[i-1]>20) hD0DcaData = hD0DcaDataSubSideBand;

		setColorTitleLabel(hD0DcaData, 1);

		double integralTotalYield = hD0DcaData->Integral(1,hD0DcaData->GetXaxis()->GetNbins(),"width");
		cout<<"integralTotalYield: "<<integralTotalYield<<endl;

		TF1* fMix = new TF1("fMix",&funMix, 0., 0.5, 2);
		fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
		fMix->SetParLimits(0,0,2*integralTotalYield);
		fMix->SetParLimits(1,0,2*integralTotalYield);

		fMix->SetLineColor(2);
		fMix->SetFillColor(kRed-9);
		fMix->SetFillStyle(1001);

		float fitRangeL = 0;
		float fitRangeH = 0.08;

		hD0DcaData->GetXaxis()->SetRangeUser(0,0.07);
		hD0DcaData->Draw();
		int fitStatus = 1;
		TFitResultPtr fitResult;
		double fitPrecision = 1.e-6;
		while(fitStatus)
		{
			TFitter::SetPrecision(fitPrecision);
			fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
			fMix->SetParError(0,0.1*integralTotalYield);
			fMix->SetParError(1,0.1*integralTotalYield);
			fitResult = hD0DcaData->Fit("fMix","E SNQ0", "", fitRangeL, fitRangeH);
			fitStatus = fitResult->Status();
			cout<<"fit precision: "<<TFitter::GetPrecision()<<"   status: "<<fitStatus<<endl;
			if(fitStatus)
				fitPrecision *= 10;
		}
		cout<<"============== do main fit ============"<<endl;
		fMix->SetParameters(integralTotalYield,0.9);
		fMix->SetParError(0,0.1*integralTotalYield);
		fMix->SetParError(1,0.1);
		fMix->SetNpx(10000);
		fitResult = hD0DcaData->Fit("fMix","E S0", "", fitRangeL, fitRangeH);
		hD0DcaData->GetFunction("fMix")->Draw("flsame");
		fitStatus = fitResult->Status();
		cout<<"fit precision: "<<TFitter::GetPrecision()<<"   status: "<<fitStatus<<endl;

		TF1* fNP = new TF1("fNP",&funNonPrompt, 0., 0.5, 2);
		fNP->SetParameters(fMix->GetParameter(0),fMix->GetParameter(1));
		fNP->SetRange(fitRangeL,fitRangeH);
		fNP->SetLineColor(4);
		fNP->SetFillStyle(1001);
		fNP->SetFillColor(kBlue-9);
		fNP->SetNpx(10000);
		fNP->Draw("same");  

		hD0DcaData->Draw("same");

		promptDYield[i-1] = fMix->GetParameter(0);
		promptDYieldErrorDataOnly[i-1] = fMix->GetParError(0);
		bToDYield[i-1] = fMix->GetParameter(1);
		bToDYieldErrorDataOnly[i-1] = fMix->GetParError(1);
		totalYield[i-1] = promptDYield[i-1]+bToDYield[i-1];
		promptFraction[i-1] = promptDYield[i-1]/totalYield[i-1];

		cout<<"chi2 / NDF: "<<fitResult->Chi2()<<" / "<<fitResult->Ndf()<<endl;

		texCms->Draw();
		texCol->Draw();
		texPtY->Draw();

		TLatex* texPrompt = new TLatex(0.4,0.73,Form("Prompt D^{0} yield : %.0f #pm %.0f",fMix->GetParameter(0),fMix->GetParError(0)));
		texPrompt->SetNDC();
		texPrompt->SetTextFont(42);
		texPrompt->SetTextSize(0.06);
		texPrompt->SetLineWidth(2);
		texPrompt->Draw();

		TLatex* texNonPrompt = new TLatex(0.4,0.65,Form("B to D^{0} yield : %.0f #pm %.0f",fMix->GetParameter(1),fMix->GetParError(1)));
		texNonPrompt->SetNDC();
		texNonPrompt->SetTextFont(42);
		texNonPrompt->SetTextSize(0.06);
		texNonPrompt->SetLineWidth(2);
		texNonPrompt->Draw();

		TLegend* leg4 = new TLegend(0.56,0.38,0.90,0.62);
		leg4->SetBorderSize(0);
		leg4->SetTextSize(0.06);
		leg4->SetTextFont(42);
		leg4->SetFillStyle(0);
		leg4->AddEntry(hD0DcaData,"Data","pl");
		leg4->AddEntry(fMix,"Prompt D^{0}","f");
		leg4->AddEntry(fNP,"B to D^{0}","f");
		leg4->Draw("same");

		//smear MC smaple with the error, to simulate the MC statistic error effect.
		c4->cd(3);

		hD0DcaMCPSignal = (TH1D*)hD0DcaMCPSignal0->Clone("hMCPSignal");
		hD0DcaMCNPSignal = (TH1D*)hD0DcaMCNPSignal0->Clone("hMCNPSignal");

		TH1D* hNPYield = new TH1D("hNPYield", ";hNPYield", 100, 0., 1.1*(fMix->GetParameter(0)+fMix->GetParameter(1)));
		TH1D* hPYield = new TH1D("hPYield", ";hPYield", 100, 0., 1.1*(fMix->GetParameter(0)+fMix->GetParameter(1)));
		setColorTitleLabel(hNPYield, 1);
		setColorTitleLabel(hPYield, 1);

		int nSmear = 1000;

		for(int j=0; j<nSmear; j++)
		{
			RandomSmear(hD0DcaMCPSignal0, hD0DcaMCPSignal);
			RandomSmear(hD0DcaMCNPSignal0, hD0DcaMCNPSignal);
			fMix->SetParameters(0.5*integralTotalYield,0.5*integralTotalYield);
			fMix->SetParError(0,0.1*integralTotalYield);
			fMix->SetParError(1,0.1*integralTotalYield);

			hD0DcaData->Fit("fMix","E QN0");

			hPYield->Fill(fMix->GetParameter(0));
			hNPYield->Fill(fMix->GetParameter(1));
		}

		hPYield->GetXaxis()->SetTitle("prompt D^{0} yield");
		hPYield->GetYaxis()->SetTitle("counts");
		hPYield->GetYaxis()->SetRangeUser(0.5, 1.4*hPYield->GetMaximum());
		hPYield->SetMarkerStyle(20);
		hPYield->SetStats(0);
		hPYield->Draw("e");
		hPYield->Fit("gaus");

		TLatex* texGaussMeanSigmaP = new TLatex(0.27,0.83,Form("#mu: %.0f              #sigma: %.0f",hPYield->GetFunction("gaus")->GetParameter(1),hPYield->GetFunction("gaus")->GetParameter(2)));
		texGaussMeanSigmaP->SetNDC();
		texGaussMeanSigmaP->SetTextFont(42);
		texGaussMeanSigmaP->SetTextSize(0.06);
		texGaussMeanSigmaP->SetLineWidth(2);
		texGaussMeanSigmaP->Draw();

		float promptYieldErrorMc = hPYield->GetFunction("gaus")->GetParameter(2);
		promptDYieldError[i-1] = sqrt(pow(promptDYieldErrorDataOnly[i-1],2)+pow(promptYieldErrorMc,2));

		c4->cd(4);

		hNPYield->GetXaxis()->SetTitle("B to D^{0} yield");
		hNPYield->GetYaxis()->SetTitle("counts");
		hNPYield->GetYaxis()->SetRangeUser(0.5, 1.4*hNPYield->GetMaximum());
		hNPYield->SetMarkerStyle(20);
		hNPYield->SetStats(0);
		hNPYield->Draw("e");
		hNPYield->Fit("gaus");

		TLatex* texGaussMeanSigmaNP = new TLatex(0.27,0.83,Form("#mu: %.0f              #sigma: %.0f",hNPYield->GetFunction("gaus")->GetParameter(1),hNPYield->GetFunction("gaus")->GetParameter(2)));
		texGaussMeanSigmaNP->SetNDC();
		texGaussMeanSigmaNP->SetTextFont(42);
		texGaussMeanSigmaNP->SetTextSize(0.06);
		texGaussMeanSigmaNP->SetLineWidth(2);
		texGaussMeanSigmaNP->Draw();

		float bToDYieldErrorMc = hNPYield->GetFunction("gaus")->GetParameter(2);
		bToDYieldError[i-1] = sqrt(pow(bToDYieldErrorDataOnly[i-1],2)+pow(bToDYieldErrorMc,2));

		cout<<"prompt D yield: "<<promptDYield[i-1]<<" +- "<<promptDYieldError[i-1]<<" (+- "<<promptDYieldErrorDataOnly[i-1]<<" +- "<<promptYieldErrorMc<<" )"<<endl;
		cout<<"B to D yield: "<<bToDYield[i-1]<<" +- "<<bToDYieldError[i-1]<<" (+- "<<bToDYieldErrorDataOnly[i-1]<<" +- "<<bToDYieldErrorMc<<" )"<<endl;
		cout<<"total yield: "<<totalYield[i-1]<<endl;
		cout<<"prompt fraction: "<<promptFraction[i-1]<<endl;

		float promptMCScale = promptDYield[i-1]/integralRawYieldMCP;
		float nonPromptMCScale = bToDYield[i-1]/integralRawYieldMCNP;

		cout<<"promptMCScale: "<<promptMCScale<<endl;
		cout<<"nonPromptMCScale: "<<nonPromptMCScale<<endl;

		//restore original unsmeared histograms before saving plots
		delete hD0DcaMCPSignal;
		delete hD0DcaMCNPSignal;
		hD0DcaMCPSignal = hD0DcaMCPSignal0;
		hD0DcaMCNPSignal = hD0DcaMCNPSignal0;
		hD0DcaData->Fit("fMix","E QN0");

		c4->SaveAs(Form("plots/PbPb_%.0f_%.0f_fit.pdf",ptLow,ptHigh));

		c1->cd();

		TH1D* hD0DcaDataOverFit = (TH1D*)hD0DcaData->Clone("hD0DcaDataOverFit");
		hD0DcaDataOverFit->Divide(fMix);
		hD0DcaDataOverFit->GetYaxis()->SetTitle("data / fit");
		hD0DcaDataOverFit->GetYaxis()->SetRangeUser(0,5);
		hD0DcaDataOverFit->GetXaxis()->SetRangeUser(0,0.07);
		setColorTitleLabel(hD0DcaDataOverFit, 1);
		hD0DcaDataOverFit->Draw("e");

		TF1* fLine1 = new TF1("fLine1", "1", 0,1);
		fLine1->Draw("same");
		hD0DcaDataOverFit->Draw("esame");

		c1->SaveAs(Form("plots/dataOverFit_%.0f_%.0f_fit.pdf",ptLow,ptHigh));

		delete hD0DcaMCPSignal;
		delete hD0DcaMCNPSignal;

	} // end for i ptbins
	c1->cd();

	TH1D* hStupidJie = new TH1D("hStupidJie", "", 100, 0, 100);
	hStupidJie->GetYaxis()->SetRangeUser(0,1);
	hStupidJie->GetXaxis()->SetTitle("p_{T} (GeV/c)");
	hStupidJie->GetYaxis()->SetTitle("prompt fraction");
	hStupidJie->SetStats(0);
	hStupidJie->Draw();
	TGraph* grFraction = new TGraph(nPtBins, pts, promptFraction);
	grFraction->SetName("grPromptFraction");
	grFraction->SetMarkerStyle(20);
	grFraction->Draw("psame");

	c1->SaveAs("promptFraction.pdf");

	c1->SetLogy();

	TH1D* hBtoDRawYield = new TH1D("hBtoDRawYield", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
	for(int i=1; i<=nPtBins; i++)
	{
		if(bToDYield[i-1] <= 0) continue;
		hBtoDRawYield->SetBinContent(i, bToDYield[i-1]);
		hBtoDRawYield->SetBinError(i, bToDYieldError[i-1]);
	}
	divideBinWidth(hBtoDRawYield);
	setColorTitleLabel(hBtoDRawYield, 1);
	c1->SetBottomMargin(0.14);
	hBtoDRawYield->Draw("p");
	c1->SaveAs("BtoD.pdf");

	TH1D* hPromptDRawYield = new TH1D("hPromptDRawYield", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
	for(int i=1; i<=nPtBins; i++)
	{
		if(promptDYield[i-1] <= 0) continue;
		hPromptDRawYield->SetBinContent(i, promptDYield[i-1]);
		hPromptDRawYield->SetBinError(i, promptDYieldError[i-1]);
	}
	divideBinWidth(hPromptDRawYield);
	setColorTitleLabel(hPromptDRawYield, 1);
	c1->SetBottomMargin(0.14);
	hPromptDRawYield->Draw("p");
	c1->SaveAs("promptD.pdf");

	TH1D* hTotalDYieldInvMassFit = new TH1D("hTotalDYieldInvMassFit", ";p_{T} (GeV/c);dN/dp_{T} ((GeV/c)^{-1})", nPtBins, ptBins);
	for(int i=1; i<=nPtBins; i++)
	{
		if(totalYieldInvMassFit[i-1] <= 0) continue;
		hTotalDYieldInvMassFit->SetBinContent(i, totalYieldInvMassFit[i-1]);
		hTotalDYieldInvMassFit->SetBinError(i, totalYieldInvMassFitError[i-1]);
	}
	divideBinWidth(hTotalDYieldInvMassFit);
	setColorTitleLabel(hTotalDYieldInvMassFit, 1);
	hTotalDYieldInvMassFit->Draw("p");
	c1->SaveAs("totalDInvMassFit.pdf");

	TFile* fOut = new TFile("bFeedDownResult.root", "recreate");
	fOut->WriteTObject(grFraction);
	fOut->WriteTObject(hBtoDRawYield);
	fOut->WriteTObject(hPromptDRawYield);
	fOut->WriteTObject(hTotalDYieldInvMassFit);
	fOut->Write();
	fOut->Close();
}
Ejemplo n.º 17
0
void Example07()
{
  // Fit function
  
  TF1 *fPulseShape = new TF1("fPulseShape", funcPulseShape, -500, 500, 3);
  fPulseShape->SetNpx(1000);

  // Get one event with samples

  //  TFile *file2 = new TFile("data/samples_qie25_signal_10GeV_pu_0.root");
  //  TFile *file2 = new TFile("data/samples_signal_10GeV_pu_0.root");
  //  TFile *file2 = new TFile("data/samples_signal_10GeV_eta_0.0_pu_140.root");
  TFile *file2 = new TFile("data/samples_test.root");

  double samples[NSAMPLES];
  double amplitudeTruth;
  TTree *tree = (TTree*)file2->Get("Samples");
  tree->SetBranchAddress("amplitudeTruth",      &amplitudeTruth);
  tree->SetBranchAddress("samples",             samples);

  tree->GetEntry(10);

  // Create TGraphErrors with the pulse to fit
  
  TGraphErrors *gr = new TGraphErrors();
  for(int i=0; i<NSAMPLES; i++){
    double x = i * NFREQ;  
    gr->SetPoint(i, x, samples[i]);
    gr->SetPointError(i, 0., 0.044);  // 44 MeV for all samples
  }

  // Fit 
  
  fPulseShape->SetParameters(70., 0., amplitudeTruth);
  fPulseShape->SetLineColor(2);
  gr->Fit("fPulseShape","E");
  gr->Draw("AP");
  

  // Reconstructed amplitude and timing
  vector<double> resultsA;
  vector<double> resultsT;

  int nentries = tree->GetEntries();
  for(int ievt=0; ievt<nentries; ievt++){
    tree->GetEntry(ievt);
    TGraphErrors *gr = new TGraphErrors();
    for(int i=0; i<NSAMPLES; i++){
      double x = i * NFREQ;  
      gr->SetPoint(i, x, samples[i]);
      gr->SetPointError(i, 0., 0.044);  // 44 MeV for all samples
    }
    fPulseShape->SetParameters(70., 0., amplitudeTruth);
    gr->Fit("fPulseShape","QE");
    resultsA.push_back(fPulseShape->GetParameter(2)-amplitudeTruth);
    resultsT.push_back(fPulseShape->GetParameter(0));
  }

  if(resultsA.size()>0){
    pair<double,double> effA = effectiveSigma(resultsA);
    double avgValue = 0.5 * (effA.first + effA.second);
    double sigValue = 0.5 * fabs(effA.second - effA.first) ;
    double avgError = sigValue / sqrt(double(resultsA.size()));
    double sigError = sigValue / sqrt(2.0 * double(resultsA.size()));
    cout << " Mean of amplitude      " << avgValue << " +- " << avgError << " GeV" << endl;
    cout << " Sigma_eff of amplitude " << sigValue << " +- " << sigError << " GeV" << endl;
  }

  if(resultsT.size()>0){
    pair<double,double> effT = effectiveSigma(resultsT);
    double avgValue = 0.5 * (effT.first + effT.second);
    double sigValue = 0.5 * fabs(effT.second - effT.first) ;
    double avgError = sigValue / sqrt(double(resultsT.size()));
    double sigError = sigValue / sqrt(2.0 * double(resultsT.size()));
    cout << " Mean of timing      " << avgValue << " +- " << avgError << " ns" << endl;
    cout << " Sigma_eff of timing " << sigValue << " +- " << sigError << " ns" << endl;
  }

  
}
Ejemplo n.º 18
0
void toyMC_bkgTemp(int runIeta=-1, int runIpt=-1) {

    cout << "ROOT version = " << gROOT->GetVersion() << endl;
    //   gSystem->mkdir("toysPlot");
    char tmp[1000];


    TH1D* htoyResult_pull[nEtaBin][nPtBin];
    TH1D* htoyResult_bias[nEtaBin][nPtBin];

    TFile *fsumFile = new TFile("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/proj_comb_comb3Iso_template.root");
    TFile* finFile = new TFile("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/template_comb3Iso_template.root");
    TFile* zeeFile = new TFile("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/anadipho_Zee_Vg_3pb.root");
    TH1D* hTemplate = (TH1D*)finFile->FindObjectAny("h_EB_comb3Iso_EGdata_pt21");
    hTemplate->Reset();


    char* dec[2] = {"EB","EE"};
    for(int ieta=0; ieta<nEtaBin; ieta++) {
        for(int ipt=0; ipt < nPtBin; ipt++) {

            htoyResult_pull[ieta][ipt] = new TH1D(Form("hpull_%s_pt_%d",
                                                  dec[ieta],
                                                  (int)fBinsPt[ipt]),
                                                  "",50,-5.0,5.0);


            htoyResult_bias[ieta][ipt] = new TH1D(Form("hbias_%s_pt_%d",
                                                  dec[ieta],
                                                  (int)fBinsPt[ipt]),
                                                  "",100,-0.5,0.5);


        }
    }



    TH1D* hfit_sig;
    TH1D* hfit_bkg;

    TH1D* hTemplate_S[nEtaBin][nPtBin];
    TH1D* hTemplate_B[nEtaBin][nPtBin];
    TH1D* hZeeTemplate_S[nEtaBin];
    TH1D* hdata_data[nEtaBin][nPtBin];
    TH1D* htemp;
    TH1D* hTemplate_ShiftB[nEtaBin][nPtBin];

    for(int ieta=0; ieta< nEtaBin; ieta++) {

        // getting a different signal template
        if(ieta==0) {
            sprintf(tmp,"h_%s_combIso",dec[ieta]);
            cout << "looking for histogram " << tmp << " in file " <<
                 zeeFile->GetName() << endl;
            hZeeTemplate_S[ieta]= (TH1D*)zeeFile->FindObjectAny(tmp);
            hZeeTemplate_S[ieta]->Rebin(REBINNINGS_TEMP);
        }
        else {
            sprintf(tmp,"h_%s_comb3Iso_sig_sum_SIG",dec[ieta]); //no pt dep.
            cout << "looking for histogram " << tmp << " in file " <<
                 fsumFile->GetName() << endl;
            hZeeTemplate_S[ieta]= (TH1D*)fsumFile->FindObjectAny(tmp);
            hZeeTemplate_S[ieta]->Rebin(REBINNINGS_TEMP);
        }

        for(int ipt=0; ipt < nPtBin; ipt++) {

            if(runIeta>=0 && ieta!=runIeta)continue;
            if(runIpt>=0 && ipt!=runIpt)continue;

            // getting histograms from data root file
            sprintf(tmp,"h_%s_comb3Iso_EGdata_pt%d",dec[ieta],(int)fBinsPt[ipt]);
            cout << "looking for histogram " << tmp << " in file " <<
                 finFile->GetName() << endl;
            hdata_data[ieta][ipt] = (TH1D*)finFile->FindObjectAny(tmp);
            hdata_data[ieta][ipt]->Rebin(REBINNINGS_DATA);

            // filling unbinned data
            htemp = (TH1D*)hdata_data[ieta][ipt]->Clone("htemp");
            htemp->Reset();


            sprintf(tmp,"h_%s_comb3Iso_sig_pt%d",dec[ieta],(int)fBinsPt[ipt]);
            cout << "looking for histogram " << tmp << " in file " <<
                 finFile->GetName() << endl;
            hTemplate_S[ieta][ipt] = (TH1D*)finFile->FindObjectAny(tmp);
            hTemplate_S[ieta][ipt]->Rebin(REBINNINGS_TEMP);

            if(ieta==0 && fBinsPt[ipt]>=50)
                sprintf(tmp,"h_%s_comb3Iso_bkg_pt%d",dec[ieta],50);
            else if(ieta==0 )
                sprintf(tmp,"h_%s_comb3Iso_bkg_pt%d",dec[ieta],(int)fBinsPt[ipt]);
            else if(ieta==1 && fBinsPt[ipt]>=60)
                sprintf(tmp,"h_%s_comb3IsoSB_EGdata_pt%d",dec[ieta],60);
            else if(ieta==1)
                sprintf(tmp,"h_%s_comb3IsoSB_EGdata_pt%d",dec[ieta],(int)fBinsPt[ipt]);
            cout << "looking for histogram " << tmp << " in file " <<
                 finFile->GetName() << endl;
            hTemplate_B[ieta][ipt] = (TH1D*)finFile->FindObjectAny(tmp);
            hTemplate_B[ieta][ipt]->Rebin(REBINNINGS_TEMP);

            // getting a different background template
            if(ieta==0 && fBinsPt[ipt]>=50)
                sprintf(tmp,"h_%s_comb3IsoSB_EGdata_pt%d",dec[ieta],50);
            else if(ieta==0 )
                sprintf(tmp,"h_%s_comb3IsoSB_EGdata_pt%d",dec[ieta],(int)fBinsPt[ipt]);
            else if(ieta==1 && fBinsPt[ipt]>=60)
                sprintf(tmp,"h_%s_comb3Iso_bkg_pt%d",dec[ieta],60);
            else if(ieta==1)
                sprintf(tmp,"h_%s_comb3Iso_bkg_pt%d",dec[ieta],(int)fBinsPt[ipt]);
            cout << "looking for histogram " << tmp << " in file " <<
                 finFile->GetName() << endl;
            hTemplate_ShiftB[ieta][ipt] = (TH1D*)finFile->FindObjectAny(tmp);

            hTemplate_ShiftB[ieta][ipt]->Rebin(REBINNINGS_TEMP);



            const int NRETURN = 3*NPAR;
            Double_t myFitPar[NRETURN]= {0};
            Double_t* FuncFitResult;
            FuncFitResult = Ifit("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/EGdata_comb3Iso_et.dat",
                                 hZeeTemplate_S[ieta],hTemplate_ShiftB[ieta][ipt],
                                 hdata_data[ieta][ipt], myFitPar,
                                 (int)fBinsPt[ipt], dec[ieta],2);

            Double_t nsig_input    = FuncFitResult[0];
            Double_t nsigerr_input = FuncFitResult[1];
            Double_t nbkg_input    = FuncFitResult[2];
            Double_t nbkgerr_input = FuncFitResult[3];
            Double_t nsig_input5GeV = FuncFitResult[4];
            Double_t nsigerr_input5GeV = FuncFitResult[5];

            // force the parameters since EE pt=40 fails
            if(ieta==1 && ipt==5)
            {
                nsig_input = 3172.0;
                nbkg_input = 10031.0;
                nsig_input5GeV = 3158.7;

                Double_t tempPar[NRETURN]= {
                    22517.049862,
                    0.900766,
                    0.044772,
                    0.191920,
                    313.878244,
                    -0.545069,
                    -0.281830,
                    0.026143,
                    2.549494,
                    0.,
                    0.,
                    22517.049862,
                    0.900766,
                    0.044772,
                    0.191920,
                    313.878244,
                    -0.545069,
                    -0.281830,
                    0.026143,
                    2.549494,
                    0.,
                    0.,
                    22517.049862,
                    0.900766,
                    0.044772,
                    0.191920,
                    313.878244,
                    -0.545069,
                    -0.281830,
                    0.026143,
                    2.549494,
                    0.,
                    0.
                };

                for(int ipar=0; ipar <NRETURN; ipar++)
                    myFitPar[ipar] = tempPar[ipar];
            } // end if EE, Et=40 GeV


            Double_t sigFitPar[NPAR]= {0};
            for(int ipar=0; ipar<NPAR; ipar++)
                sigFitPar[ipar] = myFitPar[ipar];

            Double_t bkgFitPar[NPAR]= {0};
            for(int ipar=0; ipar<NPAR; ipar++)
                bkgFitPar[ipar] = myFitPar[ipar+NPAR];


            Double_t sumFitPar[NPAR]= {0};
            for(int ipar=0; ipar<NPAR; ipar++)
                sumFitPar[ipar] = myFitPar[ipar+NPAR*2];


            TF1* fsig = new TF1("fsig", exp_conv, fit_lo, fit_hi, 11);
            fsig->SetParameters(sigFitPar);
            fsig->SetParameter(0,1.0);


            mySigPDFnorm = fsig->Integral(fit_lo,fit_hi);
            cout << "mySigPDFnorm = " << mySigPDFnorm << endl;

            TF1* fbkg = new TF1("fbkg", expinv_power, fit_lo, fit_hi, 11);
            fbkg->SetParameters(bkgFitPar);
            fbkg->SetParameter(4,1.0);
            cout << "Current parameter = " << fbkg->GetParameter(5) << endl;

            myBkgPDFnorm = fbkg->Integral(fit_lo, fit_hi);
            cout << "myBkgPDFnorm = " << myBkgPDFnorm << endl;

            TF1* fsum = new TF1("fsum",mysum_norm, fit_lo, fit_hi,11);
            fsum->SetParameters(sumFitPar);


            nsig_input = fNsigPt[ieta][ipt];

            cout << "Using nsig_input = " << nsig_input << endl;
            cout << "Using nbkg_input = " << nbkg_input << endl;
            cout << "Using nsig_input5GeV = " << nsig_input5GeV << endl;

            fsum->SetParameter(0, nsig_input*hdata_data[ieta][ipt]->GetBinWidth(2));
            fsum->SetParameter(4, nbkg_input*hdata_data[ieta][ipt]->GetBinWidth(2));
            fsum->SetLineColor(2);
            fsum->SetNpx(2500);

            //        cout << "fsum integral = " << fsum->Integral(fit_lo,fit_hi) << endl;
            //        for(int ipar=0; ipar<NPAR; ipar++)cout << "fsum par " << ipar << " = " << fsum->GetParameter(ipar) << endl;

//       FILE *infile =  fopen("/afs/cern.ch/user/s/syu/scratch0/LxplusArea/EGdata_comb3Iso_et.dat","r");
//       Double_t xdata, xdata1, xdata2; // combined isolation, pt, eta
//       int flag = 1;
//       while (flag!=-1){
// 	flag =fscanf(infile,"%f %f %f",&xdata, &xdata1, &xdata2);
// 	if( xdata1 >= fBinsPt[ipt] && xdata1 < fBinsPt[ipt+1] && xdata<20.) {
// 	  if((ieta==0 && TMath::Abs(xdata2)<1.5) ||
// 	     (ieta==1 && TMath::Abs(xdata2)>1.5) ) {
// 	    htemp->Fill(xdata);
// 	  }
// 	}
//       }// keep reading files as long as text exists


//       TCanvas* myCanvas = new TCanvas("myCanvas","myCanvas");
//       htemp->Draw();
//       fsum->Draw("same");


            //        // loops over toys
            for(int iexp=0; iexp<NEXP; iexp++) {

                TH1D* htoyMC_data = (TH1D*)hdata_data[ieta][ipt]->Clone("htoyMC_data");
                htoyMC_data->Reset();

                TH1D* htoyMC_sig  = (TH1D*)hZeeTemplate_S[ieta]->Clone("htoyMC_sig");

                TH1D* htoyMC_bkg  = (TH1D*)hTemplate_B[ieta][ipt]->Clone("htoyMC_bkg");




                UInt_t nowSeed = (unsigned long)gSystem->Now();
                gRandom->SetSeed(nowSeed);
                int nsiggen  = gRandom->Poisson(nsig_input);
                int nbkggen  = gRandom->Poisson(nbkg_input);
                int ndata = nsiggen + nbkggen;

                // reset toy MC data
                htoyMC_data->Reset();
                ofstream fout;
                std::string toyData = Form("/tmp/syu/changeBkgTemptoy_%d_%d.dat",ieta,ipt);

                fout.open(toyData.data());
                for(int ieve=0; ieve < nsiggen; ieve++)
                {
                    Double_t xvalue = fsig->GetRandom(fit_lo,fit_hi);
                    fout << xvalue << " " <<
                         0.5*(fBinsPt[ipt]+fBinsPt[ipt+1]) << " " << fBinsEta[ieta] << endl;
                    htoyMC_data->Fill(xvalue);
                }

                for(int ieve=0; ieve < nbkggen; ieve++)
                {
                    Double_t xvalue = fbkg->GetRandom(fit_lo,fit_hi);
                    fout << xvalue << " " <<
                         0.5*(fBinsPt[ipt]+fBinsPt[ipt+1]) << " " << fBinsEta[ieta] << endl;
                    htoyMC_data->Fill(xvalue);
                }

                fout.close();


                Double_t* toyFitResult;
                Double_t toyMyFitPar[NRETURN]= {0};

                toyFitResult =  Ifit(toyData.data(),
                                     htoyMC_sig, htoyMC_bkg,
                                     htoyMC_data, toyMyFitPar,
                                     (int)fBinsPt[ipt], dec[ieta],2);

                Double_t nsigtoyfit    = toyFitResult[0];
                Double_t errnsigtoyfit = toyFitResult[1];
                Double_t nbkgtoyfit    = toyFitResult[2];
                Double_t errnbkgtoyfit = toyFitResult[3];
                Double_t nsigtoyfit_5GeV = toyFitResult[4];
                Double_t errnsigtoyfit_5GeV = toyFitResult[5];


                if(errnsigtoyfit < 1e-6 || errnbkgtoyfit < 1e-6 ||
                        nsigtoyfit < 1e-6 || nbkgtoyfit < 1e-6 ||
                        nsig_input < 1e-6 || fabs(nsigtoyfit - nsig_input)<1e-4)continue;


                Double_t toySumFitPar[NPAR]= {0};
                for(int ipar=0; ipar<NPAR; ipar++)
                    toySumFitPar[ipar] = toyMyFitPar[ipar+NPAR*2];


//  	fsum->SetParameters(toySumFitPar);
//  	fsum->SetParameter(0, nsigtoyfit*hdata_data[ieta][ipt]->GetBinWidth(2));
//  	fsum->SetParameter(4, nbkgtoyfit*hdata_data[ieta][ipt]->GetBinWidth(2));
                fsum->SetParameter(0, (Double_t)nsiggen*hdata_data[ieta][ipt]->GetBinWidth(2));
                fsum->SetParameter(4, (Double_t)nbkggen*hdata_data[ieta][ipt]->GetBinWidth(2));

                // 	if(iexp%20==0){
                TCanvas* myCanvas = new TCanvas("myCanvas","SHIT");
                htoyMC_data->SetMaximum(htoyMC_data->GetMaximum()*1.5);
                htoyMC_data->Draw();
                fsum->Draw("same");
// 	 	  myCanvas->Print(Form("toysPlot/fit_%03i.gif",iexp));
// 	 	  delete myCanvas;
                // 	}

                // 	 cout << "fsum integral = " << fsum->Integral(-1,20) << endl;
                // 	 for(int ipar=0; ipar<NPAR; ipar++)cout << "fsum par " << ipar << " = " << fsum->GetParameter(ipar) << endl;


                Double_t pull = (nsigtoyfit - nsig_input)/errnsigtoyfit;
                Double_t bias = (nsigtoyfit - nsig_input)/nsig_input;


                htoyResult_pull[ieta][ipt]->Fill(pull);
                htoyResult_bias[ieta][ipt]->Fill(bias);


            } // end loops of toys

            delete fsig;
            delete fbkg;


        } // end of loop over pt bins


    }


    TFile* outFile = new TFile(Form("changBkgTemp_%s_pt%d.root",
                                    dec[runIeta], (int)fBinsPt[runIpt]),
                               "recreate");

    for(int ieta=0; ieta < nEtaBin; ieta++) {
        for(int ipt=0; ipt < nPtBin; ipt++) {

            if(htoyResult_pull[ieta][ipt]->GetEntries()>0)
                htoyResult_pull[ieta][ipt]->Write();

            if(htoyResult_bias[ieta][ipt]->GetEntries()>0)
                htoyResult_bias[ieta][ipt]->Write();
        }
    }

    outFile->Close();

}
//*************************************************************
std::pair<std::pair<Double_t,Double_t>, std::pair<Double_t,Double_t>  > fitResidualsCB(TH1 *hist)
//*************************************************************
{
  
  //hist->Rebin(2);

  float mean  = hist->GetMean();
  float sigma = hist->GetRMS();
  //int   nbinsX   = hist->GetNbinsX();
  float nentries = hist->GetEntries();
  float meanerr  = sigma/TMath::Sqrt(nentries);
  float sigmaerr = TMath::Sqrt(sigma*sigma*TMath::Sqrt(2/nentries));

  float lowBound  = hist->GetXaxis()->GetBinLowEdge(1);
  float highBound = hist->GetXaxis()->GetBinLowEdge(hist->GetNbinsX()+1);

  if(TMath::IsNaN(mean) || TMath::IsNaN(sigma)){  
    mean=0;
    sigma= - lowBound + highBound;
  }
  
  TF1 func("tmp", "gaus", mean - 1.*sigma, mean + 1.*sigma); 
  if (0 == hist->Fit(&func,"QNR")) { // N: do not blow up file by storing fit!
    mean  = func.GetParameter(1);
    sigma = func.GetParameter(2);
  }
  
  // first round
  TF1 *doubleCB = new TF1("myDoubleCB",DoubleSidedCB,lowBound,highBound,7);
  doubleCB->SetParameters(mean,sigma,1.5,1.5,2.5,2.5,100);
  doubleCB->SetParLimits(0,mean-meanerr,mean+meanerr);
  doubleCB->SetParLimits(1,0.,sigma+2*sigmaerr);
  doubleCB->SetParLimits(2,0.,30.);
  doubleCB->SetParLimits(3,0.,30.);
  doubleCB->SetParLimits(4,0.,50.);
  doubleCB->SetParLimits(5,0.,50.);
  doubleCB->SetParLimits(6,0.,100*nentries);

  doubleCB->SetParNames("#mu","#sigma","#alpha_{L}","#alpha_{R}","n_{L}","n_{R}","N");
  doubleCB->SetLineColor(kRed);
  doubleCB->SetNpx(1000);
  // doubleCB->SetRange(0.8*lowBound,0.8*highBound);

  hist->Fit(doubleCB,"QM");

  // second round

  float p0 = doubleCB->GetParameter(0);
  float p1 = doubleCB->GetParameter(1);
  float p2 = doubleCB->GetParameter(2);
  float p3 = doubleCB->GetParameter(3);
  float p4 = doubleCB->GetParameter(4);
  float p5 = doubleCB->GetParameter(5);
  float p6 = doubleCB->GetParameter(6);
  
  float p0err = doubleCB->GetParError(0);
  float p1err = doubleCB->GetParError(1);
  float p2err = doubleCB->GetParError(2);
  float p3err = doubleCB->GetParError(3);
  float p4err = doubleCB->GetParError(4);
  float p5err = doubleCB->GetParError(5);
  float p6err = doubleCB->GetParError(6);

  if( (doubleCB->GetChisquare()/doubleCB->GetNDF()) >5){

    std::cout<<"------------------------"<<std::endl;
    std::cout<<"chi2 1st:"<<doubleCB->GetChisquare()<<std::endl;

    //std::cout<<"p0: "<<p0<<"+/-"<<p0err<<std::endl;
    //std::cout<<"p1: "<<p1<<"+/-"<<p1err<<std::endl;
    //std::cout<<"p2: "<<p2<<"+/-"<<p2err<<std::endl;
    //std::cout<<"p3: "<<p3<<"+/-"<<p3err<<std::endl;
    //std::cout<<"p4: "<<p4<<"+/-"<<p4err<<std::endl;
    //std::cout<<"p5: "<<p5<<"+/-"<<p5err<<std::endl;
    //std::cout<<"p6: "<<p6<<"+/-"<<p6err<<std::endl;

    doubleCB->SetParameters(p0,p1,3,3,6,6,p6);
    doubleCB->SetParLimits(0,p0-2*p0err,p0+2*p0err);
    doubleCB->SetParLimits(1,p1-2*p1err,p0+2*p1err);
    doubleCB->SetParLimits(2,p2-2*p2err,p0+2*p2err);
    doubleCB->SetParLimits(3,p3-2*p3err,p0+2*p3err);
    doubleCB->SetParLimits(4,p4-2*p4err,p0+2*p4err);
    doubleCB->SetParLimits(5,p5-2*p5err,p0+2*p5err);
    doubleCB->SetParLimits(6,p6-2*p6err,p0+2*p6err);

    hist->Fit(doubleCB,"MQ");

    //gMinuit->Command("SCAn 1");
    //TGraph *gr = (TGraph*)gMinuit->GetPlot();
    //gr->SetMarkerStyle(21);
    //gr->Draw("alp"); 

    std::cout<<"chi2 2nd:"<<doubleCB->GetChisquare()<<std::endl;
    
  }

  float res_mean  = doubleCB->GetParameter(0);
  float res_width = doubleCB->GetParameter(1);
  
  float res_mean_err  = doubleCB->GetParError(0);
  float res_width_err = doubleCB->GetParError(1);

  std::pair<Double_t,Double_t> resultM;
  std::pair<Double_t,Double_t> resultW;

  resultM = std::make_pair(res_mean,res_mean_err);
  resultW = std::make_pair(res_width,res_width_err);

  std::pair<std::pair<Double_t,Double_t>, std::pair<Double_t,Double_t>  > result;
  
  result = std::make_pair(resultM,resultW);
  return result;

}
Ejemplo n.º 20
0
void SiCalibrator::MatchPeaks() {
	Load();
	char tmpname[255];
	sprintf(tmpname,"/SumCalData_th%dd%ds%dt%d.root",thresh,decay,shaping,top);
	std::string fname = tmpname;
	std::string filename = mypath;
	filename.append(fname);
	TFile *myfile = new TFile(filename.c_str(),"RECREATE");
	int nbins;
	for (int src=0; src < CalData.size(); src++) {
		if (CalData[src].hSource != 0) {
			CalData[src].hSource->SetDirectory(myfile);
			CalData[src].hSource->Write();
			for (int ch=0; ch<CalData[src].sourcedata.size(); ch++) {
				TH1D* hbi = CalData[src].hSource->ProjectionY("hb",ch+1,ch+1);
				nbins = hbi->GetNbinsX();
				CalData[src].sourcedata[ch].fpol1 = 0;
				if (hbi->Integral(1,nbins) > 0) {
					sprintf(tmpname,"fs%dch%d",src,ch);
					TF1* f = new TF1(tmpname,fitf,0,16000,4);
					CalData[src].sourcedata[ch].fpol1 = f;
					// Build spectrum fit function
					f->FixParameter(0,src);
					f->FixParameter(1,0);
					//f->SetParLimits(1,-30,30);
					f->SetParameter(2,0.2);
					f->SetParameter(3,1);
					f->SetNpx(1000);
					double scale = hbi->GetMaximum()/f->GetMaximum();
					f->FixParameter(3,scale);
					f->SetParameter(2,minimize(f,hbi,2,0.1,0.3));
					//f->ReleaseParameter(2);
					//f->ReleaseParameter(1);
					//hbi->Draw();
					//hbi->Fit(f,"LL","",thresh+50,16000);
					//cout << f->GetChisquare()/f->GetNDF() << endl;
					//f->FixParameter(1,f->GetParameter(1));
					//f->FixParameter(2,f->GetParameter(2));
					//f->SetParameter(3,minimize(f,hbi,3,scale*0.1,scale*5));
					//f->ReleaseParameter(3);
					//f->SetParLimits(3,scale*0.1,scale*5);
					/*
					double slope = f->GetParameter(2);
					if (slope < 0.2 || slope > 0.25) {
						cout << "src " << src;
						cout << " ch " << ch;
						cout << " cnts " << hbi->Integral(1,nbins);
						cout << " pol1" << slope << endl;
						//hbi->Draw();
						//return;
					}
					*/
				//hbi->Fit(f,"LL","",thresh+50,16000);
				//cout << f->GetChisquare()/f->GetNDF() << endl;
				//hbi->Fit(f,"","",150,16000);
				//f->Draw("same");
				/*
					if (src == 1 && ch==13) {
						hbi->Draw();
						f->Draw("same");
						return;
					}
				*/
					f->Write();
				}
			}
		}
	}
	for (int src=0; src < CalData.size(); src++) {
		if (CalData[src].hSource != 0) {
			sprintf(tmpname,"hp1_%d",src);
			CalData[src].hp1 = new TH1D(tmpname,tmpname,CalData[src].sourcedata.size(),0,CalData[src].sourcedata.size());
			for (int ch=0; ch<CalData[src].sourcedata.size(); ch++) {
				if (CalData[src].sourcedata[ch].fpol1 != 0) {
					TF1* f = CalData[src].sourcedata[ch].fpol1;
					CalData[src].hp1->SetBinContent(ch+1,f->GetParameter(2));
				}
			}
			CalData[src].hp1->Write();
			/*
			TCanvas* c = new TCanvas();
			c->Divide(1,2);
			c->cd(1);
			CalData[src].hSource->Draw("COLZ");
			c->cd(2);
			CalData[src].hp1->Draw();
			*/
		}
	}
	myfile->Close();
	delete myfile;
}
Ejemplo n.º 21
0
int EffAndCross(char* name)
{
 
  char line[1000];
  TFile *file = new TFile("cross.root","recreate");


  ifstream inbescross("cross.txt_665p01");
  double xbes[22];
  double xebes[22];
  double ybes[22];
  double yebes[22];
  inbescross.getline(line,1000);
  int idbes=0;
  while (!inbescross.eof() && idbes<21){
    double tmpe, tmpeff, tmpcross, tmpcrosse, tmp;
    inbescross >> tmpe >> tmp >> tmp>> tmpeff >> tmp >> tmp >> tmpcross >> tmpcrosse >> tmp >> tmp >> tmp ;
    xbes[idbes] = tmpe;
    xebes[idbes] = 0;
    ybes[idbes] = tmpcross;
    yebes[idbes] = tmpcrosse;
    idbes++;
  }

  TGraphErrors *gbes = new TGraphErrors(idbes,xbes,ybes,xebes,yebes);
  gbes->SetLineColor(2);
  gbes->SetMarkerColor(2);
  gbes->SetFillColor(0);
  //gbes->Draw("P");








  double xx[1000];
  double xxe[1000];
  double yy[1000];
  double yye[1000];
  double emat[1000][1000];

  int n2=0;
  ifstream infile2("KKBabar.txt");
  if (!infile2.is_open()) return -100;
  while (!infile2.eof())
  { 
    double energy1, energy2;
    double obs, obse;

    infile2.getline(line,1000);
    istringstream iss;
    iss.str(line);
  //if (iss.peek()<48 || iss.peek()>57) // not a number
  //{
  //  continue;  
  //}
    //else 
    {
      char a;
      iss >> energy1 >> a >> energy2;
      iss >> obs >> obse;
    }
    //std::cout<<"E1: "<< energy1 << "\tE2: "<< energy2 << "\tsigma: "<< obs <<"\terr: "<<obse<<std::endl;

    xx[n2] = (energy2+energy1)/2.;
    xxe[n2] = (energy2-energy1)/2.;
    yy[n2] = obs;
    yye[n2] = 0;
    n2 ++;
  }

  ifstream infile3("epapsFileKpKm.txt");
  if (!infile3.is_open()) return -200;
  int xid=0,yid=0;
  while(!infile3.eof())
  {
    infile3.getline(line,1000);
    istringstream iss;
    iss.str(line);
    if ((iss.peek()<48 || iss.peek()>57) && iss.peek()!='-') // not a number
    {
      continue;  
     }
    iss >> emat[xid][yid];
    yid++;
     if (yid==159){
      xid++;
      yid=0;
    }
    if (xid==159) break;
  }
  //std::cout<<"xid: "<<xid<<"\tyid: "<<yid<<std::endl;
  for (int i=0; i<159;i++)
  {
    yye[i] = sqrt(emat[i][i]);
  }

  //---------------------------
  //add bes result
  for (int i=0;i<21;i++){
    xx[n2] = xbes[i];
    xxe[n2] = 0.001;
    yy[n2] = ybes[i];
    yye[n2] = yebes[i];
    n2 ++; 
  }
  //----------------------------

  TCanvas *c2 = new TCanvas();
  TGraphErrors *graph1 = new TGraphErrors(n2,xx,yy,xxe,yye);
  graph1->GetXaxis()->SetTitle("#sqrt{s} (GeV)");
  graph1->GetYaxis()->SetTitle("#sigma (nb)");
  graph1->SetTitle("Cross section");
  //graph1->SetMarkerStyle(5);
  graph1->SetFillColor(0);
  graph1->Draw("AP");

  ofstream fitxs("fitxsbabar.txt");
  double gap = 0.01;
  TF1 *fit;
  for (int i=0; xx[i]<1.1-0.0000001;i++){
    double xs = yy[i];
    //fitxs<<xx[i]<<"\t"<<xs<<"\t"<<0<<endl;
    fitxs << "xx.push_back(" << xx[i] << ");\tyy.push_back("<< yy[i] << ");\t er.push_back(0);" <<endl;
  }
 
//fit = new TF1("f0","[0]/(pow(x-[1],2)+pow([2],2))",0.99,1.05);
//fit->SetParameter(0,1.0);
//fit->SetParameter(1,1.02);
//fit->SetParameter(2,0.005);
//graph1->Fit(fit,"R","",0.99,1.05);
//for (double x=0.99; x<1.05-0.0000001;x+=gap){
//  double xs = fit->Eval(x);
//  fitxs << "xx.push_back(" << x << ");\tyy.push_back("<< xs << ");\t er.push_back(0);" <<endl;
//}


  fit = new TF1("f1","pol2",1.1,1.6);
  graph1->Fit(fit,"R+","",1.1,1.6);
  for (double x=1.1; x<1.6-0.0000001;x+=gap){
    double xs = fit->Eval(x);
    //fitxs<<x<<"\t"<<xs<<"\t"<<0<<endl;
    fitxs << "xx.push_back(" << x << ");\tyy.push_back("<< xs << ");\t er.push_back(0);" <<endl;
  }
  
  fit = new TF1("f2","pol2",1.6,1.76);
  graph1->Fit(fit,"R+","",1.6,1.779);
  for (double x=1.6; x<1.779-0.0000001;x+=gap){
    double xs = fit->Eval(x);
    //fitxs<<x<<"\t"<<xs<<"\t"<<0<<endl;
    fitxs << "xx.push_back(" << x << ");\tyy.push_back("<< xs << ");\t er.push_back(0);" <<endl;
  }
  
//fit = new TF1("f3","pol2",1.8,2.16);
//graph1->Fit(fit,"R+","",1.8,2.16);
//for (double x=1.8; x<2.16-0.0000001;x+=gap){
//  double xs = fit->Eval(x);
//  fitxs<<x<<"\t"<<xs<<"\t"<<0<<endl;
//  //fitxs << "xx.push_back(" << x << ");\tyy.push_back("<< xs << ");\t er.push_back(0);" <<endl;
//}
  
  
//
//fit = new TF1("f4","gaus",2.16,2.35);
//graph1->Fit(fit,"R+","",2.16,2.4);
//for (double x=2.16; x<2.4-0.0000001;x+=gap){
//  double xs = fit->Eval(x);
//  fitxs<<x<<"\t"<<xs<<"\t"<<0<<endl;
//  //fitxs << "xx.push_back(" << x << ");\tyy.push_back("<< xs << ");\t er.push_back(0);" <<endl;
//}
//
//fit = new TF1("f5","expo",2.35,5);
//graph1->Fit(fit,"R+","",2.4,5);
//for (double x=2.4; x<5-0.0000001;x+=gap){
//  double xs = fit->Eval(x);
//  fitxs<<x<<"\t"<<xs<<"\t"<<0<<endl;
//  //fitxs << "xx.push_back(" << x << ");\tyy.push_back("<< xs << ");\t er.push_back(0);" <<endl;
//}
  
//fit = new TF1("f4",GausInvx,2.,5,6);
//fit->SetNpx(1000);
//fit->SetParameters(1,2.25,0.05,0.03,1.8,1.5);
//fit->SetParLimits(0, 0.1,  10);
//fit->SetParLimits(1, 2.2,  2.4);
//fit->SetParLimits(2, 0.03, 0.05);
//fit->SetParLimits(3, 0.02,  10);
//fit->SetParLimits(4, 1.5,    2);
//fit->SetParLimits(5, 1,    2);
  
//fit = new TF1("f4",DGausInvx,2.,5,9);
//fit->SetNpx(1000);
//fit->SetParameters(0.2,   2.25, 0.05,
//                   0.03,  1.8,  5,
//                   0.1,   2.0,  0.05);
//
//fit->SetParLimits(0, 0.1,  10);
//fit->SetParLimits(1, 2.2,  2.3);
//fit->SetParLimits(2, 0.03, 0.05);
//
//fit->SetParLimits(3, 0.02, 10);
//fit->SetParLimits(4, -1,    2);
//fit->SetParLimits(5, 5,    20);
//
//fit->SetParLimits(6, 0.1,  0.2);
//fit->SetParLimits(7, 1.9,  2.05);
//fit->SetParLimits(8, 0.04, 0.08);
//graph1->Fit(fit,"R+","",1.8,5);

//fit = new TF1("f4",DGausExp,2.,5,8);
//fit->SetNpx(1000);
//fit->SetParameters(0.2,   2.25, 0.05,
//                   0.1,   2.0,  0.06,
//                   0.03,  1.8);
//
//fit->SetParLimits(0, 0.1,  10);
//fit->SetParLimits(1, 2.2,  2.4);
//fit->SetParLimits(2, 0.03, 0.052);
//
//fit->SetParLimits(3, 0.1,  1.0);
//fit->SetParLimits(4, 1.9,    2.0);
//fit->SetParLimits(5, 0.06,   0.1);
//
//fit->SetParLimits(6, 0.02,  9);
//fit->SetParLimits(7, 0,    1.8);
//
//graph1->Fit(fit,"R+","",1.75,5);
 
//fit = new TF1("f4",TGaus,2.,5,9);
//fit->SetNpx(1000);
//fit->SetParameters(0.2,   2.25, 0.05,
//                   0.1,   2.0,  0.06,
//                   0.03,  1.8,  1.0);
//
//fit->SetParLimits(0, 0.1,  10);
//fit->SetParLimits(1, 2.2,  2.4);
//fit->SetParLimits(2, 0.03, 0.052);
//
//fit->SetParLimits(3, 0.1,  1.0);
//fit->SetParLimits(4, 1.9,    2.0);
//fit->SetParLimits(5, 0.06,   0.1);
//
//fit->SetParLimits(6, 0.02,  90);
////fit->SetParLimits(7, -10,    2);
//fit->SetParLimits(7, -10,    2.4);
//fit->SetParLimits(8, 0.2,    2);
  
//fit = new TF1("f4",DGausAExp,2.,5,9);
//fit->SetNpx(1000);
//fit->SetParameters(0.5,   2.2,  30,
//                   0.1,   2.0,  0.06,
//                   0.03,  1.8,  1.0);
//
//fit->SetParLimits(0, 0.1,  100);
//fit->SetParLimits(1, 2.1,  2.3);
//fit->SetParLimits(2, 10,   60);
//
//fit->SetParLimits(3, 0.1,  1.0);
//fit->SetParLimits(4, 1.9,    2.0);
//fit->SetParLimits(5, 0.06,   0.1);
//
//fit->SetParLimits(6, 0.02,  90);
//fit->SetParLimits(7, -10,    2.4);
//fit->SetParLimits(8, 0.2,    2);
 
  fit = new TF1("f4",AGausDExp,2.,5,9);
  fit->SetNpx(1000);
  fit->SetParameters(50,   2.2,  30,
                     0.1,  2.0,  0.06,
                     0.1,  2.2,  1.8);
  
  fit->SetParLimits(0, 0.1,  100);
  fit->SetParLimits(1, 2.1,  2.3);
  fit->SetParLimits(2, 10,   60);
  
  fit->SetParLimits(3, 0.1,  1.0);
  fit->SetParLimits(4, 1.9,    2.1);
  fit->SetParLimits(5, 0.06,   0.1);
  
  fit->SetParLimits(6, 0.02,  90);
  fit->SetParLimits(7, -10,    2.4);
  fit->SetParLimits(8, 0.2,    2);
  
  graph1->Fit(fit,"R+","",1.77,5);



  for (double x=1.77; x<5-0.0000001;x+=gap){
    double xs = fit->Eval(x);
    //fitxs<<x<<"\t"<<xs<<"\t"<<0<<endl;
    fitxs << "xx.push_back(" << x << ");\tyy.push_back("<< xs << ");\t er.push_back(0);" <<endl;
  }

  gbes->Draw("P");


  file->WriteTObject(c2);
  graph1->GetXaxis()->SetRangeUser(1.6,3.5);
  graph1->GetYaxis()->SetRangeUser(0,0.5);
  c2->Print("cross.pdf");

  return 0;
}
Ejemplo n.º 22
0
int main(int ac, char *av[]) {
  gROOT->SetStyle("Plain");

  try {
    typedef funct::FunctExpression Expr;
    typedef fit::HistoChiSquare<funct::FunctExpression> ExprChi2;
    typedef fit::MultiHistoChiSquare<ExprChi2, ExprChi2, ExprChi2, ExprChi2, ExprChi2> ChiSquared;
    double fMin, fMax;
    string ext;
    po::options_description desc("Allowed options");
    desc.add_options()
      ("help,h", "produce help message")
      ("input-file,i", po::value< vector<string> >(), "input file")
      ("min,m", po::value<double>(&fMin)->default_value(60), "minimum value for fit range")
      ("max,M", po::value<double>(&fMax)->default_value(120), "maximum value for fit range")
      ("plot-format,p", po::value<string>(&ext)->default_value("eps"), 
       "output plot format");
    
    po::positional_options_description p;
    p.add("input-file", -1);
    
    po::variables_map vm;
    po::store(po::command_line_parser(ac, av).
	    options(desc).positional(p).run(), vm);
    po::notify(vm);
    
    if (vm.count("help")) {
      cout << "Usage: options_description [options]\n";
      cout << desc;
      return 0;
    }
    
    fit::RootMinuitCommands<ChiSquared> commands("zFitToyMc.txt");

    cout << "minuit command file completed" << endl;
    const unsigned int rebinMuMuNoIso = 2,rebinMuMu = 1, rebinMuMu1HLT = 1, rebinMuMu2HLT = 1, rebinMuTk = 2, rebinMuSa = 10;
    // assume that the bin size is 1 GeV!!!
    funct::Constant rebinMuMuNoIsoConst(rebinMuMuNoIso), rebinMuMuConst(rebinMuMu), 
      rebinMuMu1HLTConst(rebinMuMu1HLT), rebinMuMu2HLTConst(rebinMuMu2HLT), 
      rebinMuTkConst(rebinMuTk), rebinMuSaConst(rebinMuSa);

    if (vm.count("input-file")) {
      cout << "Input files are: " 
	   << vm["input-file"].as< vector<string> >() << "\n";
      vector<string> v_file = vm["input-file"].as< vector<string> >();
      for(vector<string>::const_iterator it = v_file.begin(); 
	  it != v_file.end(); ++it) {
	TFile * root_file = new TFile(it->c_str(), "read");
	TH1 * histoZMuMuNoIso = getHisto(root_file, "nonIsolatedZToMuMuPlots/zMass_noIso",rebinMuMuNoIso);
	TH1 * histoZMuMu = getHisto(root_file, "goodZToMuMuPlots/zMass_golden",rebinMuMu);
	TH1 * histoZMuMu1HLT = getHisto(root_file, "goodZToMuMu1HLTPlots/zMass_1hlt", rebinMuMu1HLT);
	TH1 * histoZMuMu2HLT = getHisto(root_file, "goodZToMuMu2HLTPlots/zMass_2hlt", rebinMuMu2HLT);
	TH1 * histoZMuTk = getHisto(root_file, "goodZToMuMuOneTrackPlots/zMass_tk", rebinMuTk);
	TH1 * histoZMuSa = getHisto(root_file, "goodZToMuMuOneStandAloneMuonPlots/zMass_sa", rebinMuSa);
	TH1 * histoZMuSaFromMuMu = getHisto(root_file, "zmumuSaMassHistogram/zMass_safromGolden", rebinMuSa);


	cout << ">>> histogram loaded\n";
	string f_string = *it;
	replace(f_string.begin(), f_string.end(), '.', '_');
	replace(f_string.begin(), f_string.end(), '/', '_');
	string plot_string = f_string + "." + ext;
	cout << ">>> Input files loaded\n";
	
	const char * kYieldZMuMu = "YieldZMuMu";
	const char * kEfficiencyTk = "EfficiencyTk";
	const char * kEfficiencySa = "EfficiencySa";
	const char * kEfficiencyIso = "EfficiencyIso";
	const char * kEfficiencyHLT = "EfficiencyHLT"; 
	const char * kYieldBkgZMuTk = "YieldBkgZMuTk"; 
	const char * kYieldBkgZMuSa = "YieldBkgZMuSa"; 
	const char * kYieldBkgZMuMuNotIso = "YieldBkgZMuMuNotIso";
	const char * kAlpha = "Alpha";
	const char * kBeta = "Beta";
	const char * kLambda = "Lambda";
	const char * kA0 = "A0"; 
	const char * kA1 = "A1"; 
	const char * kA2 = "A2"; 
	const char * kB0 = "B0"; 
	const char * kB1 = "B1"; 
	const char * kB2 = "B2"; 
	
	funct::Parameter yieldZMuMu(kYieldZMuMu, commands.par(kYieldZMuMu));
	funct::Parameter effTk(kEfficiencyTk, commands.par(kEfficiencyTk)); 
	funct::Parameter effSa(kEfficiencySa, commands.par(kEfficiencySa)); 
	funct::Parameter effIso(kEfficiencyIso, commands.par(kEfficiencyIso)); 
	funct::Parameter effHLT(kEfficiencyHLT, commands.par(kEfficiencyHLT)); 
	funct::Parameter yieldBkgZMuTk(kYieldBkgZMuTk, commands.par(kYieldBkgZMuTk));
	funct::Parameter yieldBkgZMuSa(kYieldBkgZMuSa, commands.par(kYieldBkgZMuSa));
	funct::Parameter yieldBkgZMuMuNotIso(kYieldBkgZMuMuNotIso, commands.par(kYieldBkgZMuMuNotIso));
	funct::Parameter alpha(kAlpha, commands.par(kAlpha));
	funct::Parameter beta(kBeta, commands.par(kBeta));
	funct::Parameter lambda(kLambda, commands.par(kLambda));
	funct::Parameter a0(kA0, commands.par(kA0));
	funct::Parameter a1(kA1, commands.par(kA1));
	funct::Parameter a2(kA2, commands.par(kA2));
	funct::Parameter b0(kB0, commands.par(kB0));
	funct::Parameter b1(kB1, commands.par(kB1));
	funct::Parameter b2(kB2, commands.par(kB2));
	funct::Constant cFMin(fMin), cFMax(fMax);

	// count ZMuMu Yield
	double nZMuMu = 0, nZMuMu1HLT = 0, nZMuMu2HLT = 0;
	{
	  unsigned int nBins = histoZMuMu->GetNbinsX();
	  double xMin = histoZMuMu->GetXaxis()->GetXmin();
	  double xMax = histoZMuMu->GetXaxis()->GetXmax();
	  double deltaX =(xMax - xMin) / nBins;
	  for(unsigned int i = 0; i < nBins; ++i) { 
	    double x = xMin + (i +.5) * deltaX;
	    if(x > fMin && x < fMax){
	      nZMuMu += histoZMuMu->GetBinContent(i+1);
	      nZMuMu1HLT += histoZMuMu1HLT->GetBinContent(i+1);
	      nZMuMu2HLT += histoZMuMu2HLT->GetBinContent(i+1);
	    }
	  }
	}
	// aggiungi 1HLT 2HLT
	cout << ">>> count of ZMuMu yield in the range [" << fMin << ", " << fMax << "]: " << nZMuMu << endl;
	cout << ">>> count of ZMuMu (1HLT) yield in the range [" << fMin << ", " << fMax << "]: "  << nZMuMu1HLT << endl;
	cout << ">>> count of ZMuMu (2HLT) yield in the range [" << fMin << ", " << fMax << "]: "  << nZMuMu2HLT << endl;
	funct::RootHistoPdf zPdfMuMuNonIso(*histoZMuMu, fMin, fMax);//imposto le pdf a quella di ZMuMu
	funct::RootHistoPdf zPdfMuTk = zPdfMuMuNonIso;
	funct::RootHistoPdf zPdfMuMu1HLT = zPdfMuMuNonIso;
	funct::RootHistoPdf zPdfMuMu2HLT = zPdfMuMuNonIso;
	funct::RootHistoPdf zPdfMuSa(*histoZMuSaFromMuMu, fMin, fMax);
	zPdfMuMuNonIso.rebin(rebinMuMuNoIso/rebinMuMu);
	zPdfMuTk.rebin(rebinMuTk/rebinMuMu);
	zPdfMuMu1HLT.rebin(rebinMuMu1HLT/rebinMuMu);
	zPdfMuMu2HLT.rebin(rebinMuMu2HLT/rebinMuMu);

	funct::Numerical<2> _2;
	funct::Numerical<1> _1;

	//Efficiency term
	Expr zMuMuEff1HLTTerm = _2 * (effTk ^ _2) *  (effSa ^ _2) * (effIso ^ _2) * effHLT * (_1 - effHLT); 
	Expr zMuMuEff2HLTTerm = (effTk ^ _2) *  (effSa ^ _2) * (effIso ^ _2) * (effHLT ^ _2) ; 
	Expr zMuMuNoIsoEffTerm = (effTk ^ _2) * (effSa ^ _2) * (_1 - (effIso ^ _2)) * (_1 - ((_1 - effHLT)^_2));
	Expr zMuTkEffTerm = _2 * (effTk ^ _2) * effSa * (_1 - effSa) * (effIso ^ _2) * effHLT;
	Expr zMuSaEffTerm = _2 * (effSa ^ _2) * effTk * (_1 - effTk) * (effIso ^ _2) * effHLT;

	Expr zMuMu1HLT = rebinMuMu1HLTConst * zMuMuEff1HLTTerm * yieldZMuMu;
	Expr zMuMu2HLT = rebinMuMu2HLTConst * zMuMuEff2HLTTerm * yieldZMuMu;

	Expr zMuTkBkg = yieldBkgZMuTk * funct::Exponential(lambda)* funct::Polynomial<2>(a0, a1, a2);
	Expr zMuTkBkgScaled = rebinMuTkConst * zMuTkBkg;
	Expr zMuTk = rebinMuTkConst * (zMuTkEffTerm * yieldZMuMu * zPdfMuTk + zMuTkBkg);

	Expr zMuMuNoIsoBkg = yieldBkgZMuMuNotIso * funct::Exponential(alpha)* funct::Polynomial<2>(b0, b1, b2);
	Expr zMuMuNoIsoBkgScaled = rebinMuMuNoIsoConst * zMuMuNoIsoBkg;
	Expr zMuMuNoIso = rebinMuMuNoIsoConst * (zMuMuNoIsoEffTerm * yieldZMuMu * zPdfMuMuNonIso + zMuMuNoIsoBkg);

	Expr zMuSa = rebinMuSaConst * (zMuSaEffTerm * yieldZMuMu * zPdfMuSa); // + (yieldBkgZMuSa * funct::Exponential(beta) )); 

	TH1D histoZCount1HLT("histoZCount1HLT", "", 1, fMin, fMax);
	histoZCount1HLT.Fill(100, nZMuMu1HLT);
	TH1D histoZCount2HLT("histoZCount2HLT", "", 1, fMin, fMax);
	histoZCount2HLT.Fill(100, nZMuMu2HLT);
				       
	ChiSquared chi2(zMuMu1HLT, & histoZCount1HLT,
			zMuMu2HLT, & histoZCount2HLT,
			zMuTk, histoZMuTk, 
			zMuSa, histoZMuSa, 
			zMuMuNoIso,histoZMuMuNoIso,
			fMin, fMax);
	fit::RootMinuit<ChiSquared> minuit(chi2, true);
	commands.add(minuit, yieldZMuMu);
	commands.add(minuit, effTk);
	commands.add(minuit, effSa);
	commands.add(minuit, effIso);
	commands.add(minuit, effHLT);
	commands.add(minuit, yieldBkgZMuTk);
	commands.add(minuit, yieldBkgZMuSa);
	commands.add(minuit, yieldBkgZMuMuNotIso);
	commands.add(minuit, lambda);
	commands.add(minuit, alpha);
	commands.add(minuit, beta);
	commands.add(minuit, a0);
	commands.add(minuit, a1);
	commands.add(minuit, a2);
	commands.add(minuit, b0);
	commands.add(minuit, b1);
	commands.add(minuit, b2);
	commands.run(minuit);
	const unsigned int nPar = 17;//WARNIG: this must be updated manually for now
	ROOT::Math::SMatrix<double, nPar, nPar, ROOT::Math::MatRepSym<double, nPar> > err;
	minuit.getErrorMatrix(err);

	std::cout << "error matrix:" << std::endl;
	for(unsigned int i = 0; i < nPar; ++i) {
	  for(unsigned int j = 0; j < nPar; ++j) {
	    std::cout << err(i, j) << "\t";
	  }
	  std::cout << std::endl;
	} 
	minuit.printFitResults();
	ofstream myfile;
	myfile.open ("fitResult.txt", ios::out | ios::app);
	myfile<<"\n";
        double Y =  minuit.getParameterError("YieldZMuMu");
        double dY = minuit.getParameterError("YieldZMuMu", Y);
        double tk_eff =  minuit.getParameterError("EfficiencyTk");
        double dtk_eff = minuit.getParameterError("EfficiencyTk", tk_eff);
        double sa_eff =  minuit.getParameterError("EfficiencySa");
        double dsa_eff = minuit.getParameterError("EfficiencySa", sa_eff);
        double iso_eff =  minuit.getParameterError("EfficiencyIso");
        double diso_eff = minuit.getParameterError("EfficiencyIso", iso_eff);
        double hlt_eff =  minuit.getParameterError("EfficiencyHLT");
        double dhlt_eff = minuit.getParameterError("EfficiencyHLT",hlt_eff);
	myfile<< Y <<" "<< dY <<" "<< tk_eff <<" "<< dtk_eff <<" "<< sa_eff << " " << dsa_eff << " " << iso_eff <<" " << diso_eff<< " " << hlt_eff << " " << dhlt_eff << " " <<chi2()/(chi2.numberOfBins()- minuit.numberOfFreeParameters());

	myfile.close();

	//Plot
	double s;
	s = 0;
	for(int i = 1; i <= histoZMuMuNoIso->GetNbinsX(); ++i)
	  s += histoZMuMuNoIso->GetBinContent(i);
	histoZMuMuNoIso->SetEntries(s);
	s = 0;
	for(int i = 1; i <= histoZMuMu->GetNbinsX(); ++i)
	  s += histoZMuMu->GetBinContent(i);
	histoZMuMu->SetEntries(s);
	s = 0;
	for(int i = 1; i <= histoZMuMu1HLT->GetNbinsX(); ++i)
	  s += histoZMuMu1HLT->GetBinContent(i);
	histoZMuMu1HLT->SetEntries(s);
	s = 0;
	for(int i = 1; i <= histoZMuMu2HLT->GetNbinsX(); ++i)
	  s += histoZMuMu2HLT->GetBinContent(i);
	histoZMuMu2HLT->SetEntries(s);
	s = 0;
	for(int i = 1; i <= histoZMuTk->GetNbinsX(); ++i)
	  s += histoZMuTk->GetBinContent(i);
	histoZMuTk->SetEntries(s);
	s = 0;
	for(int i = 1; i <= histoZMuSa->GetNbinsX(); ++i)
	  s += histoZMuSa->GetBinContent(i);
	histoZMuSa->SetEntries(s);

	string ZMuMu1HLTPlot = "ZMuMu1HLTFit_" + plot_string;
	root::plot<Expr>(ZMuMu1HLTPlot.c_str(), *histoZMuMu1HLT, zMuMu1HLT, fMin, fMax, 
			  effTk, effSa, effIso, effHLT, yieldZMuMu, 
			  kRed, 2, kDashed, 100, 
			  "Z -> #mu #mu mass", "#mu #mu invariant mass (GeV/c^{2})", 
			  "Events");

	string ZMuMu2HLTPlot = "ZMuMu2HLTFit_" + plot_string;
	root::plot<Expr>(ZMuMu2HLTPlot.c_str(), *histoZMuMu2HLT, zMuMu2HLT, fMin, fMax, 
			  effTk, effSa, effIso, effHLT, yieldZMuMu, 
			  kRed, 2, kDashed, 100, 
			  "Z -> #mu #mu mass", "#mu #mu invariant mass (GeV/c^{2})", 
			  "Events");

	
	string ZMuMuNoIsoPlot = "ZMuMuNoIsoFit_" + plot_string;
	root::plot<Expr>(ZMuMuNoIsoPlot.c_str(), *histoZMuMuNoIso, zMuMuNoIso, fMin, fMax, 
			 effTk, effSa, effIso, effHLT, yieldZMuMu,
			 kRed, 2, kDashed, 100, 
			 "Z -> #mu #mu Not Iso mass", "#mu #mu invariant mass (GeV/c^{2})", 
			 "Events");	
	
	string ZMuTkPlot = "ZMuTkFit_X_" + plot_string;
	root::plot<Expr>(ZMuTkPlot.c_str(), *histoZMuTk, zMuTk, fMin, fMax,
			 effTk, effSa, effIso, effHLT, yieldZMuMu,
			 yieldBkgZMuTk, lambda, a0, a1, a2,
			 kRed, 2, kDashed, 100,
                         "Z -> #mu + (unmatched) track mass", "#mu #mu invariant mass (GeV/c^{2})",
                         "Events");
	ZMuTkPlot = "ZMuTkFit_" + plot_string;
	TF1 funZMuTk = root::tf1_t<sig_tag, Expr>("ZMuTkFunction", zMuTk, fMin, fMax, 
						  effTk, effSa, effIso, effHLT, yieldZMuMu, 
						  yieldBkgZMuTk, lambda, a0, a1, a2);
	funZMuTk.SetLineColor(kRed);
	funZMuTk.SetLineWidth(2);
	funZMuTk.SetLineStyle(kDashed);
	funZMuTk.SetNpx(10000);
	TF1 funZMuTkBkg = root::tf1_t<bkg_tag, Expr>("ZMuTkBack", zMuTkBkgScaled, fMin, fMax, 
						     yieldBkgZMuTk, lambda, a0, a1, a2);
	funZMuTkBkg.SetLineColor(kGreen);
	funZMuTkBkg.SetLineWidth(2);
	funZMuTkBkg.SetLineStyle(kDashed);
	funZMuTkBkg.SetNpx(10000);
	histoZMuTk->SetTitle("Z -> #mu + (unmatched) track mass");
	histoZMuTk->SetXTitle("#mu + (unmatched) track invariant mass (GeV/c^{2})");
	histoZMuTk->SetYTitle("Events");
	TCanvas *canvas = new TCanvas("canvas");
	histoZMuTk->Draw("e");
	funZMuTkBkg.Draw("same");
	funZMuTk.Draw("same");
	canvas->SaveAs(ZMuTkPlot.c_str());
	canvas->SetLogy();
	string logZMuTkPlot = "log_" + ZMuTkPlot;
	canvas->SaveAs(logZMuTkPlot.c_str());
	string ZMuSaPlot = "ZMuSaFit_" + plot_string;
	root::plot<Expr>(ZMuSaPlot.c_str(), *histoZMuSa, zMuSa, fMin, fMax, 
			 effSa, effTk, effIso,
			 yieldZMuMu, yieldBkgZMuSa, 
			 kRed, 2, kDashed, 10000, 
			 "Z -> #mu + (unmatched) standalone mass", 
			 "#mu + (unmatched) standalone invariant mass (GeV/c^{2})", 
			 "Events");
      }
    }
  }
  catch(std::exception& e) {
    cerr << "error: " << e.what() << "\n";
    return 1;
  }
  catch(...) {
    cerr << "Exception of unknown type!\n";
  }

  return 0;
}
Ejemplo n.º 23
0
bool FitPeak(Double_t *par, TH1 *h, Float_t &area, Float_t &darea){

   Double_t binWidth = h->GetXaxis()->GetBinWidth(1000);//Need to find the bin widths so that the integral makes sense
   Int_t rw = binWidth*20;  //This number may change depending on the source used   
   //Set the number of iterations. The code is pretty quick, so having a lot isn't an issue	
   TVirtualFitter::SetMaxIterations(4999);
   Int_t xp = par[1];

   //Define the fit function and the range of the fit
   TF1 *pp = new TF1("photopeak",fitFunction,xp-rw,xp+rw,10);

   //Name the parameters so it is easy to see what the code is doing
   pp->SetParName(0,"Height");
   pp->SetParName(1,"centroid");
   pp->SetParName(2,"sigma");
   pp->SetParName(3,"beta");
   pp->SetParName(4,"R");
   pp->SetParName(5,"step");
   pp->SetParName(6,"A");
   pp->SetParName(7,"B");
   pp->SetParName(8,"C");
   pp->SetParName(9,"bg offset");

   //Set some physical limits for parameters
   pp->SetParLimits(1,xp-rw,xp+rw);
   pp->SetParLimits(3,0,30);
   pp->SetParLimits(4,0,10);
   pp->SetParLimits(5,0.000,1000000);
   pp->SetParLimits(9,xp-20,xp+20);

   //Actually set the parameters in the photopeak function
   pp->SetParameters(par);

//   pp->FixParameter(4,0);
 //  pp->FixParameter(5,0);

   pp->SetNpx(1000); //Draws a nice smooth function on the graph
   TFitResultPtr fitres = h->Fit("photopeak","RFS");
   pp->Draw("same");      

   pp->GetParameters(&par[0]); 
   TF1 *photopeak = new TF1("photopeak",photo_peak,xp-rw,xp+rw,10);
   photopeak->SetParameters(par);

   Double_t integral = photopeak->Integral(xp-rw,xp+rw)/binWidth;

   std::cout << "FIT RESULT CHI2 " << fitres->Chi2() << std::endl;

   std::cout << "FWHM = " << 2.35482*fitres->Parameter(2)/binWidth <<"(" << fitres->ParError(2)/binWidth << ")" << std::endl;
   std::cout << "NDF: " << fitres->Ndf() << std::endl;
   std::cout << "X sq./v = " << fitres->Chi2()/fitres->Ndf() << std::endl;

   TVirtualFitter *fitter = TVirtualFitter::GetFitter();

   assert(fitter != 0); //make sure something was actually fit
   Double_t * covMatrix = fitres->GetCovarianceMatrix(); //This allows us to find the uncertainty in the integral

   Double_t sigma_integral = photopeak->IntegralError(xp-rw,xp+rw)/binWidth;

   std::cout << "Integral = " << integral << " +/- " << sigma_integral << std::endl;

   area = integral;
   darea = sigma_integral;

   if(fitres->Chi2()/fitres->Ndf() > 5.0)
      return false;

   return true;

//   myFitResult.fIntegral = integral;


 //  return photopeak;

}
Ejemplo n.º 24
0
//________________________________________________________________________________
void peaks(TH1* h, Int_t np=10, Int_t ij=0) {
  if (! h) return;
  npeaks = TMath::Abs(np);
  if (! c1)  c1 = new TCanvas();
  else       c1->Clear();
  if (c2 && ij > 0) {c2->cd(ij); h->Draw(); c2->Update();}
  c1->Divide(1,2);
  c1->cd(1);
  h->Draw();
  TH1F *h2 = (TH1F*)h->Clone("h2");
  //Use TSpectrum to find the peak candidates
  TSpectrum *s = new TSpectrum(2*npeaks);
  Int_t nfound = s->Search(h,5,"",0.05);
  printf("Found %d candidate peaks to fit\n",nfound);
  if (! nfound) return;
  //Estimate background using TSpectrum::Background
  TH1 *hb = s->Background(h,20,"same");
  hb->Draw("same");
  c1->Update();
  if (c2 && ij > 0) {c2->cd(ij); h->Draw(); c2->Update();}
  if (np <0) return;

  //estimate linear background using a fitting method
  c1->cd(2);
  TF1 *fline = new TF1("fline","pol1",0,1000);
  fline->FixParameter(1,0.);
  h->Fit("fline","qnlw");
  if (c2 && ij > 0) {c2->cd(ij+1); h->Draw(); c2->Update(); c1->cd(2);}
  //Loop on all found peaks. Eliminate peaks at the background level
  Double_t par[3000];
  par[0] = fline->GetParameter(0);
  par[1] = fline->GetParameter(1);
  npeaks = 0;
  Float_t *xpeaks = s->GetPositionX();
  Float_t ymax = 0;
  for (Int_t p=0;p<nfound;p++) {
    Float_t xp = xpeaks[p];
    Int_t bin = h->GetXaxis()->FindBin(xp);
    Float_t yp = h->GetBinContent(bin);
    if (yp-3*TMath::Sqrt(yp) < fline->Eval(xp)) continue;
    par[3*npeaks+2] = yp;
    if (yp > ymax) ymax = yp;
    par[3*npeaks+3] = xp;
    par[3*npeaks+4] = 3;
    npeaks++;
  }
  cout << "Found " << npeaks << " useful peaks to fit" << endl;
  Int_t NP = 0;
  Int_t nbad = 0;
  TString LineH("  {\"");  LineH +=  h->GetName(); LineH += "\"";
  TString Line("");
  struct ParErr_t {Double_t par, err;};
  ParErr_t parErr[10];
  TF1 *fit = 0;
  if (ymax > 2*par[0]) {
    cout << "Now fitting: Be patient" << endl;
    fit = new TF1("fit",fpeaks,0,1000,2+3*npeaks);
    TVirtualFitter::Fitter(h2,10+3*npeaks); //we may have more than the default 25 parameters
    fit->SetParameter(0,par[0]);
    fit->FixParameter(1,0.);
    for (Int_t p = 0; p < npeaks; p++) {
      fit->SetParName(3*p+2,Form("A%i",p));
      fit->SetParLimits(3*p+2,0,1e6);
      fit->SetParameter(3*p+2,par[3*p+2]);
      fit->SetParName(3*p+3,Form("#mu%i",p));
      fit->SetParLimits(3*p+3,TMath::Max(0.,par[3*p+3]-2), TMath::Min(240.,par[3*p+3]+2));
      fit->SetParameter(3*p+3,par[3*p+3]);
      fit->SetParName(3*p+4,Form("#sigma%i",p));
      fit->SetParLimits(3*p+4,0.01,20);
      fit->SetParameter(3*p+4,par[3*p+4]);
    }
    fit->SetNpx(1000);
    h2->SetStats(0);
    h2->Fit("fit","l");
    if (c2 && ij > 0) {c2->cd(ij); h2->Draw("same"); c2->Update(); c1->cd(2);}
    fit->GetParameters(par);
    for (Int_t p = 0; p<np;p++) {
      if (p < npeaks && par[3*p+2] > 5*fit->GetParError(3*p+2) && 
	  par[3*p+2] > par[0]) {
	if (TMath::Abs(par[3*p+4]) > 5.0) nbad++;
	//      Line += Form(",%f,%f,%7.2f,%5.2f",par[3*p+2],fit->GetParError(3*p+2),par[3*p+3],TMath::Abs(par[3*p+4]));
	parErr[NP].par = par[3*p+3];
	parErr[NP].err = TMath::Abs(par[3*p+4]);
	for (Int_t i = 0; i < NP; i++) {
	  if (parErr[i].par > parErr[NP].par) {
	    ParErr_t temp = parErr[i];
	    parErr[i] = parErr[NP];
	    parErr[NP] = temp;
	  }
	}
	NP++;
      } 
    }
  }
  for (Int_t p = 0; p < np; p++) {
    if (p < NP) Line += Form(",%7.2f,%5.2f",parErr[p].par,parErr[p].err);
    else  Line += ",0,0";
  }
  Line += "},";
  if (nbad > 1) NP = -NP; // reject whole hybrid
  LineH +=  Form(",%3i",NP);
  cout << LineH << Line << endl;
  out  << LineH << Line << endl;
  c1->Update();
  if (c2) c2->Update();
  delete fit;
  delete s;
}
Ejemplo n.º 25
0
void toymc(double ptmin = 290., double ptmax = 320., double lumi = 0,
	   double *nevts = 0, double *mean = 0, double *err = 0) {

  gStyle->SetOptStat(1110);
  gStyle->SetOptFit();

  TF1 *cb1 = new TF1("cb1",crystal_ball, 0., 2., 5);
  TF1 *cb1x = new TF1("cb1x",crystal_ball_x, 0., 2., 5);
  TF1 *g = new TF1("g","gaus",0.,2.);
  TF1 *cb2 = new TF1("cb2",crystal_ball, 0., 2., 5);
  TF1 *cb2x = new TF1("cb2x",crystal_ball_x, 0., 2., 5);
  TF1 *cb3 = new TF1("cb3",crystal_ball, 0., 2., 5);
  TF1 *cb3x = new TF1("cb3x",crystal_ball_x, 0., 2., 5);
  TF1 *cb4 = new TF1("cb4",crystal_dipole, 0., 2., 5);
  TF1 *cb4x = new TF1("cb4x",crystal_dipole_x, 0., 2., 5);

  double mu = 0.70; // mu1*mu2
  double mu1 = 0.95;
  double mu2 = mu/0.95;
  double mu3 = 1.00;
  double mu4 = 1.00;
  // Sigmas are relative widths so remember to multiply by mean
  double sig = 0.12; // sqrt(sig1**2 + sig2**2)
  double sig1 = 0.06;
  double sig2 = sqrt(sig*sig-sig1*sig1);
  double sig3 = 0.025;
  double sig4 = 0.030;
  double a1 = 0.7;//1.2;
  double n1 = 15.;
  double a2 = 1.7;
  double n2 = 15.;
  double a3 = 1.0;
  double n3 = 25.;
  double a4 = 0.8;
  double n4 = 35.;

  const bool photbin = false;//true; // Bin in calo photon pT, not parton pT
  double binmin = ptmin;//290;
  double binmax = ptmax;//320;
  double genmin = binmin*0.93;//0.9;
  double genmax = binmax*1.40;//1.20;

  //TF1 *xsec = new TF1("xsec","7.729e+10*pow(x,-3.104)*exp(-0.003991*x)",
  TF1 *xsec = new TF1("xsec", cross_section, 0., 14000., 5);
  xsec->SetParameters(7.729e+10, -3.104, -0.003991, genmin, genmax);
  xsec->SetNpx(1000);

  // Estimate average pT and number of events in bin
  TF1 *xsec_x = new TF1("xsec_x", cross_section_x, 0., 14000., 5);
  xsec_x->SetParameters(7.729e+10, -3.104, -0.003991, genmin, genmax);
  xsec_x->SetNpx(1000);
  double pt = xsec_x->Integral(binmin,binmax) / xsec->Integral(binmin,binmax);
  double nev = xsec->Integral(binmin, binmax) * lumi;
  if (nev==0) {
    nev = 5000000;
    lumi = nev / xsec->Integral(binmin, binmax);
  }
  cout << Form("Processing bin %1.0f-%1.0f with average pT=%1.0f"
	       " and lumi=%1.1f pb-1 (nev=%1.3g)",
	       binmin, binmax, pt, lumi, nev) << endl;

  cb1->SetParameters(1., mu1, sig1*mu1, a1, n1); // Gen/Part
  cb1x->SetParameters(1., mu1, sig1*mu1, a1, n1); // Gen/Part
  //g->SetParameters(1., mu2, sig2*mu2); // Calo/Gen
  cb2->SetParameters(1., mu2, sig2*mu2, a2, n2); // Calo/Part
  cb2x->SetParameters(1., mu2, sig2*mu2, a2, n2); // Calo/Part
  cb3->SetParameters(1., mu3, sig3*mu3, a3, n3); // Calo/Phot
  cb3x->SetParameters(1., mu3, sig3*mu3, a3, n3); // Calo/Phot
  cb4->SetParameters(1., mu4, sig4*mu4, a4, n4); // Part/Part
  cb4x->SetParameters(1., mu4, sig4*mu4, a4, n4); // Part/Part

  double mu1x = cb1x->Integral(0.,2.) / cb1->Integral(0.,2.);
  double mu2x = cb2x->Integral(0.,2.) / cb2->Integral(0.,2.);
  double mu3x = cb3x->Integral(0.,2.) / cb3->Integral(0.,2.);
  double mu4x = cb4x->Integral(0.,2.) / cb4->Integral(0.,2.);

  TH1D *xsec0 = new TH1D("xsec0","PtHat",1000,0.7*genmin,1.3*genmax);
  TH1D *xsec1 = new TH1D("xsec1","PartPtPho",1000,0.7*genmin,1.3*genmax);
  TH1D *xsec2 = new TH1D("xsec2","PhotPt",1000,0.7*genmin,1.3*genmax);
  TH1D *xsec3 = new TH1D("xsec3","PhotPt",1000,0.7*genmin,1.3*genmax);
  TH1D *h1 = new TH1D("h1","GenPart",400,0.,2.);
  TH1D *h2 = new TH1D("h2","CaloGen",400,0.,2.);
  TH1D *h3 = new TH1D("h3","Phot",400,0.,2.);
  TH1D *h4 = new TH1D("h4","Part",400,0.,2.);
  TH1D *h12 = new TH1D("h12","CaloPart",400,0.,2.);
  TH1D *h123 = new TH1D("h123","CaloPhot",400,0.,2.);
  TH1D *h1234 = new TH1D("h1234","RmeasSig",400,0.,2.);

  const double pthat0 = 300.;
  const int nit = 5000000;
  for (int i = 0; i != nit; ++i) {

    double pthat = pthat0;
    //if (photbin) 
    pthat = xsec->GetRandom(genmin, genmax);

    // Is the parton balancing model ok?
    // Should we rather simulate a "second jet", which either
    // the photon or jet can loose? (No gains allowed vs pthat)

    // parton balance
    double part = cb4->GetRandom();

    // jet side
    //double part1 = cb4->GetRandom();
    //double partpt1 = part1 * pthat;
    double partpt1 = (1.+min(part-1.,0.)) * pthat;
    double genpart = cb1->GetRandom();
    double genpt = genpart * partpt1;
    //double calogen = g->GetRandom();
    double calogen = cb2->GetRandom();
    double calopt = calogen * genpt;
    double calpart = calopt / partpt1;

    // photon side
    //double part2 = cb4->GetRandom();
    //double partpt2 = part2 * pthat;
    double partpt2 = (1.+min(1.-part,0.)) * pthat;
    double phot = cb3->GetRandom();
    double photpt1 = phot * partpt1; // parton pT's perfectly balanced
    double calphot1 = calopt / photpt1; // parton pT's perfectly balanced
    double photpt2 = phot * partpt2; // account for parton imbalance
    double calphot2 = calopt / photpt2; // account for parton imbalance

    xsec0->Fill(pthat);
    xsec1->Fill(partpt2);
    xsec2->Fill(photpt2);
    //if (photbin && 
    if (photpt2 >= binmin && photpt2 < binmax) {
      //if (true) {
      xsec3->Fill(photpt2);

      h1->Fill(genpart);
      h2->Fill(calogen);
      h3->Fill(phot);
      h4->Fill(partpt1/partpt2);//part2);
      h12->Fill(calpart);
      h123->Fill(calphot1);
      h1234->Fill(calphot2);
    }
  }

  double m1 = h1->GetMean();
  double m2 = h2->GetMean();
  double m3 = h3->GetMean();
  double m4 = h4->GetMean();
  double m12 = h12->GetMean();
  double m123 = h123->GetMean();
  double m1234 = h1234->GetMean();
  double s12 = h12->GetRMS() / m12;
  double s123 = h123->GetRMS() / m123;
  double s1234 = h1234->GetRMS() / m1234;

  g->SetRange(mu1*(1.-sig1),mu1*(1+sig1));
  h1->Fit(g, "QR");
  double p1 = g->GetParameter(1);

  g->SetRange(mu2*(1.-sig2),mu2*(1+sig2));
  h2->Fit(g, "QR");
  double p2 = g->GetParameter(1);

  g->SetRange(mu3*(1.-sig3),mu3*(1+sig3));
  h3->Fit(g, "QR");
  double p3 = g->GetParameter(1);

  g->SetRange(mu4*(1.-sig4),mu4*(1+sig4));
  h4->Fit(g, "QR");
  double p4 = g->GetParameter(1);

  g->SetRange(m12*(1.-s12),m12*(1+s12));
  h12->Fit(g, "QRN");
  g->SetRange(g->GetParameter(1)-g->GetParameter(2),
	      g->GetParameter(1)+g->GetParameter(2));
  h12->Fit(g, "QR");
  double p12 = g->GetParameter(1);

  g->SetRange(m123*(1.-s123),m123*(1+s123));
  h123->Fit(g, "QRN");
  g->SetRange(g->GetParameter(1)-g->GetParameter(2),
	      g->GetParameter(1)+g->GetParameter(2));
  h123->Fit(g, "QR");
  double p123 = g->GetParameter(1);

  g->SetRange(m1234*(1.-s1234),m1234*(1+s1234));
  h1234->Fit(g, "QRN");
  g->SetRange(g->GetParameter(1)-g->GetParameter(2),
	      g->GetParameter(1)+g->GetParameter(2));
  h1234->Fit(g, "QR");
  double p1234 = g->GetParameter(1);

  cout << Form("for GenPart,\n"
	       "mean_in = %1.3g, peak_in = %1.3g, diff = %+1.3f%%\n"
	       "mean_mc = %1.3g, peak_mc = %1.3g, diff = %+1.3f%%\n"
	       "diff  = %+1.3f%%, diff  = %+1.3f%%,(diff = %+1.3f%%)\n",
	       mu1x,              mu1,              100.*(mu1x/mu1-1.),
	       m1,                p1,               100.*(m1/p1-1.),
	       100.*(m1/mu1x-1.), 100.*(p1/mu1-1.), 100.*(p1/mu1x-1.))
       << endl;

  cout << Form("for CaloGen,\n"
	       "mean_in = %1.3g, peak_in = %1.3g, diff = %+1.3f%%\n"
	       "mean_mc = %1.3g, peak_mc = %1.3g, diff = %+1.3f%%\n"
	       "diff  = %+1.3f%%, diff  = %+1.3f%%,(diff = %+1.3f%%)\n",
	       mu2x,              mu2,              100.*(mu2x/mu2-1.),
	       m2,                p2,               100.*(m2/p2-1.),
	       100.*(m2/mu2x-1.), 100.*(p2/mu2-1.), 100.*(p2/mu2x-1.))
       << endl;

  double mean_in = mu1x*mu2x;
  double peak_in = mu1*mu2;
  cout << Form("for CaloPart,\n"
	       "mean_in = %1.3g, peak_in = %01.03g, diff = %+1.3f%%\n"
	       "mean_mc = %1.3g, peak_mc = %01.03g, diff = %+1.3f%%\n"
	       "diff  = %+1.3f%%, diff  = %+1.3f%%,(diff = %+1.3f%%)\n",
	       mean_in,           peak_in,    100.*(mean_in/peak_in-1.),
	       m12,               p12,        100.*(m12/p12-1.),
	       100.*(m12/mean_in-1.), 100.*(p12/peak_in-1.),
	       100.*(p12/mean_in-1.)) << endl;

  cout << "-------------------------------------" << endl << endl;

  cout << Form("for Phot,\n"
	       "mean_in = %1.3g, peak_in = %1.3g, diff = %+1.3f%%\n"
	       "mean_mc = %1.3g, peak_mc = %1.3g, diff = %+1.3f%%\n"
	       "diff  = %+1.3f%%, diff  = %+1.3f%%,(diff = %+1.3f%%)\n",
	       mu3x,              mu3,              100.*(mu3x/mu3-1.),
	       m3,                p3,               100.*(m3/p3-1.),
	       100.*(m3/mu3x-1.),100.*(p3/mu3-1.), 100.*(p3/mu3x-1.))
       << endl;

  mean_in = mu1x*mu2x/mu3x;
  peak_in = mu1*mu2/mu3;
  cout << Form("for CaloPhot,\n"
	       "mean_in = %1.3g, peak_in = %01.03g, diff = %+1.3f%%\n"
	       "mean_mc = %1.3g, peak_mc = %01.03g, diff = %+1.3f%%\n"
	       "diff  = %+1.3f%%, diff  = %+1.3f%%,(diff = %+1.3f%%)\n",
	       mean_in,           peak_in,    100.*(mean_in/peak_in-1.),
	       m123,              p123,       100.*(m123/p123-1.),
	       100.*(m123/mean_in-1.), 100.*(p123/peak_in-1.),
	       100.*(p123/mean_in-1.)) << endl;

  cout << "-------------------------------------" << endl << endl;

  cout << Form("for Part,\n"
	       "mean_in = %1.3g, peak_in = %1.3g, diff = %+1.3f%%\n"
	       "mean_mc = %1.3g, peak_mc = %1.3g, diff = %+1.3f%%\n"
	       "diff  = %+1.3f%%, diff  = %+1.3f%%,(diff = %+1.3f%%)\n",
	       mu4x,              mu4,              100.*(mu4x/mu4-1.),
	       m4,                p4,               100.*(m4/p4-1.),
	       100.*(m4/mu4x-1.),100.*(p4/mu4-1.), 100.*(p4/mu4x-1.))
       << endl;

  mean_in = mu1x*mu2x/(mu3x*mu4x);
  peak_in = mu1*mu2/(mu3/mu4);
  cout << Form("for RmeasSig,\n"
	       "mean_in = %1.3g, peak_in = %01.03g, diff = %+1.3f%%\n"
	       "mean_mc = %1.3g, peak_mc = %01.03g, diff = %+1.3f%%\n"
	       "diff  = %+1.3f%%, diff  = %+1.3f%%,(diff = %+1.3f%%)\n",
	       mean_in,           peak_in,    100.*(mean_in/peak_in-1.),
	       m1234,             p1234,      100.*(m1234/p1234-1.),
	       100.*(m1234/mean_in-1.), 100.*(p1234/peak_in-1.),
	       100.*(p1234/mean_in-1.)) << endl;

  //cout << Form("m1 = %1.3g, m2 = %1.3g", m1, m2) << endl;
  //cout << Form("m12 = %1.3g, mu = %1.3g, rel.diff = %1.3g%%",
  //       m12, mu, 100.*(m12/mu - 1.)) << endl;

  TCanvas *c = (TCanvas*)gROOT->FindObject("c1");
  if (c) delete c;
  c = new TCanvas("c1","c1",900,900);
  c->Divide(3,3);
  c->cd(1);
  gPad->SetLogy();
  h2->Draw();
  c->cd(2);
  gPad->SetLogy();
  h1->Draw();
  c->cd(3);
  gPad->SetLogy();
  h12->Draw();
  c->cd(4);
  gPad->SetLogy();
  xsec0->SetLineColor(kBlack);
  xsec0->Draw();
  xsec1->SetLineColor(kBlue);
  xsec1->Draw("SAME");
  xsec2->SetLineColor(kRed);
  xsec2->Draw("SAME");
  c->cd(5);
  gPad->SetLogy();
  h3->Draw();
  c->cd(6);
  gPad->SetLogy();
  h123->Draw();
  c->cd(7);
  TH1D *xsec1r = (TH1D*)xsec1->Clone("xsec1r");
  xsec1r->Divide(xsec1,xsec0);
  xsec1r->Draw();
  xsec1r->SetMaximum(1.1);
  TH1D *xsec2r1 = (TH1D*)xsec2->Clone("xsec2r1");
  xsec2r1->Divide(xsec2,xsec1);
  xsec2r1->Draw("SAME");
  TH1D *xsec2r0 = (TH1D*)xsec2->Clone("xsec2r0");
  xsec2r0->SetLineColor(kBlack);
  xsec2r0->Divide(xsec2,xsec0);
  xsec2r0->Draw("SAME");
  TH1D *xsec3r0 = (TH1D*)xsec3->Clone("xsec3r0");
  xsec3r0->Divide(xsec3,xsec0);
  xsec3r0->SetFillStyle(3001);
  xsec3r0->SetFillColor(kRed);
  xsec3r0->Draw("SAME");
  c->cd(8);
  gPad->SetLogy();
  h4->Draw();
  c->cd(9);
  gPad->SetLogy();
  h1234->Draw();
  c->cd(0);
  
}
Ejemplo n.º 26
0
void pc3fit(){
	gStyle->SetErrorX(0);
	gStyle->SetOptStat(0);
	gStyle->SetOptFit(1);
	TFile *f = TFile::Open("merged_Anappmb.root");
	TString charge;
	ofstream fout("Run15pppc3dphidzcalib.dat");
	fout<<"double dphishift[2][2][50];"<<endl;
	fout<<"double dzshift[2][2][50];"<<endl;
	fout<<"double dphisigma[2][2][50];"<<endl;
	fout<<"double dzsigma[2][2][50];"<<endl;
	TCanvas *c1 = new TCanvas("c1","c1",500,500);
	TCanvas *c2 = new TCanvas("c2","c2",500,500);
	for(int ipt=0; ipt<50; ipt++){
	for(int iarm=0; iarm<2; iarm++){
	for(int ich=0; ich<2; ich++){
	if(ich==0) charge = "pos";
	else if(ich==1) charge = "neg";
	//if(iarm!=0 || ich!=1 || ipt !=1) continue;
	TH2F *pc3dphidz = (TH2F*)f->Get(Form("pc3dphidz_arm%d_%s_%d",iarm,charge.Data(),ipt));
	if(pc3dphidz->Integral()==0){
		fout<<"dphishift["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<-0.0<<";  ";
		fout<<"dzshift["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<-0.0<<";  ";
		fout<<"dphisigma["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<-0.0<<";  ";
		fout<<"dzsigma["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<-0.0<<";  ";
		continue;
	}
	TH1F* pc3dphi = (TH1F*)pc3dphidz->ProjectionX(Form("pc3dphi_%d_%d_%d",iarm,ich,ipt),0,-1);
	TH1F* pc3dz = (TH1F*)pc3dphidz->ProjectionY(Form("pc3dz_%d_%d_%d",iarm,ich,ipt),0,-1);
	//pc3dphi->Rebin(4);
	pc3dz->Rebin(5);
	pc3dphi->Scale(1./pc3dphi->Integral());
	pc3dz->Scale(1./pc3dz->Integral());
	TF1 *fphi = new TF1("fphi","gaus(0)+gaus(3)",-0.1,0.1);
	fphi->SetNpx(10000);
	//TF1 *fphi = new TF1("fphi","[0]*([1]*exp(-(x-[2])**2/[3]/[3])+(1-[1])*exp(-(x-[4])**2/[5]/[5]))",-0.1,0.1);
	fphi->SetParameters(1e-1,0,1e-3,1e-3,0,1e-2);
	//fphi->SetParameters(4.79253e-02,9.25529e-01,-8.56488e-05,-7.46701e-03,-5.37828e-04,5.99178e-0);
	SetStyle(*pc3dphi,0.8,1,20,0,0);
	c1->cd();
        c1->SetLogy();
        pc3dphi->Draw("P");
	pc3dphi->Fit("fphi","RQ");
	pc3dphi->Fit("fphi","RQ");
	double par[6];
	fphi->GetParameters(par);
	TF1 *fphi1 = new TF1("fphi1","gaus",-0.1,0.1);
	fphi1->SetNpx(10000);
	fphi1->SetParameters(par);
	TF1 *fphi2 = new TF1("fphi2","gaus",-0.1,0.1);
	fphi2->SetNpx(10000);
	fphi2->SetParameters(&par[3]);
	fphi1->SetLineColor(4);
	fphi1->Draw("same");
	fphi2->SetLineColor(6);
	fphi2->Draw("same");
	fout<<"dphishift["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<par[1]<<";  ";
	fout<<"dphisigma["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<par[2]<<";  ";
	if(par[1]>1) cout<<"Problem!: dphi: "<<"iarm = "<<iarm<<" ich = "<<ich<<" ipt = "<<ipt<<endl;
	c1->Print(Form("fig/pc3matching/dphi_%d_%d_%d.png",iarm,ich,ipt));
		
	TF1 *fz = new TF1("fz","gaus(0)+gaus(3)",-10,10);
	//fz->SetParameters(3.02349e+07,8.32462e-01,2.39187e+00,2.17631e+07,6.35460e-01,8.09821e+00);
	fz->SetParameters(1e-1,0,2,1e-3,0,8);
	SetStyle(*pc3dz,0.8,1,20,0,0);
	c2->cd();
        pc3dz->Draw("P");
	pc3dz->Fit("fz","RQ");
	fz->GetParameters(par);
	TF1 *fz1 = new TF1("fz1","gaus",-10,10);
	fz1->SetNpx(10000);
	fz1->SetParameters(par);
	TF1 *fz2 = new TF1("fz2","gaus",-10,10);
	fz2->SetNpx(10000);
	fz2->SetParameters(&par[3]);
	fz1->SetLineColor(4);
	//fz1->Draw("same");
	fz2->SetLineColor(6);
	//fz2->Draw("same");
	fout<<"dzshift["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<par[1]<<";  ";
	fout<<"dzsigma["<<iarm<<"]["<<ich<<"]["<<ipt<<"] = "<<par[2]<<";  ";
	if(par[1]>10) cout<<"Problem! dz: "<<"iarm = "<<iarm<<" ich = "<<ich<<" ipt = "<<ipt<<endl;
	c2->Print(Form("fig/pc3matching/dz_%d_%d_%d.png",iarm,ich,ipt));

	}
	}
	fout<<endl;
}
}
//___________________________________________________________________________
Double_t* Ifit(int shift, Double_t& dataResult, Double_t& dataErr, std::string dataFile, 
	       TH1D* hsig, TH1D* hbkg, TH1D* hEGdata, Double_t* FitPar,
	       int ptbin=30, char EBEE[10]="EB", int fit_data=2)
{
  
  printf(" *** calling Ifit for %s , ptbin %d *** \n\n", EBEE,ptbin);

  cout << "The number of bins are: " << endl;
  cout << "hdata nbins = " << hEGdata->GetNbinsX() << endl;
  cout << "hsig nbins = " << hsig->GetNbinsX() << endl;
  cout << "hbkg nbins = " << hbkg->GetNbinsX() << endl;
  

  TCanvas *c1 = new TCanvas("HF1", "Histos1", 0, 0, 600, 600);
  gStyle->SetOptFit(0);

  if(fit_data != 3) dataColl.clear();
  sigColl.clear();
  bkgColl.clear();

  totalColl.clear();
  ctauColl.clear();
  Para.clear();
  Para_err.clear();

  info.clear();
  info_err.clear();

  float ptmax=0.;  
  if(ptbin== 21) ptmax= 23;
  if(ptbin== 23) ptmax= 26;
  if(ptbin== 26) ptmax= 30;
  if(ptbin== 30) ptmax= 35;
  if(ptbin== 35) ptmax= 40;
  if(ptbin== 40) ptmax= 45;
  if(ptbin== 45) ptmax= 50;
  if(ptbin== 50) ptmax= 60;
  if(ptbin== 60) ptmax= 85;
  if(ptbin== 85) ptmax= 120;
  if(ptbin== 120) ptmax= 300;
  if(ptbin== 300) ptmax= 500;



  Double_t* fitted = new Double_t[6];
  fitted[0] = 0.;    fitted[1] = 0.;    fitted[2] = 0.;    fitted[3] = 0.;
  fitted[4] = 0.;    fitted[5] = 0.;

  char hname[30];


  hsig->SetLineColor(1);
  hbkg->SetLineColor(1);
  hsig->SetNdivisions(505,"XY");
  hbkg->SetNdivisions(505,"XY");
  hsig->SetTitle("");
  hbkg->SetTitle("");
  hsig->SetXTitle("combined ISO (GeV)");
  hbkg->SetXTitle("combined ISO (GeV)");

  TH1F *hsum = (TH1F*)hsig->Clone();  
  hsum->Add(hbkg,1);
  float ntemplate = 1.;
  if (hsum->Integral()>1.) ntemplate = hsum->Integral();
  float sigfrac = hsig->Integral()/ntemplate*0.8;

  TH1F *hsum_norm = (TH1F*)hsum->Clone();  
  hsum_norm->Scale(1./hsum->Integral());

  TH1F *hdata = new TH1F();
  int ndata=0;
  if ( fit_data==1 ) {
    hdata = (TH1F*)hEGdata->Clone();
    ndata = (int)hdata->Integral();    
    for(int ibin=1; ibin<=hdata->GetNbinsX(); ibin++){
      for(int ipoint=0; ipoint<hdata->GetBinContent(ibin); ipoint++) {
	dataColl.push_back(hdata->GetBinCenter(ibin));
      }
    }
    ndata = dataColl.size();
  }else if (fit_data==2 ){
      hdata = (TH1F*)hEGdata->Clone();
    hdata -> Reset();
    dataColl.clear();
    FILE *infile =  fopen(dataFile.data(),"r");  
    float xdata, xdata1, xdata2; // combined isolation, pt, eta

    int flag = 1;
    while (flag!=-1){
      flag =fscanf(infile,"%f %f %f",&xdata, &xdata1, &xdata2);
      if( xdata1 >= ptbin && xdata1 < ptmax && xdata<20.) {
	if((strcmp(EBEE,"EB")==0 && TMath::Abs(xdata2)<1.45) ||
	   (strcmp(EBEE,"EE")==0 && TMath::Abs(xdata2)<2.5 && TMath::Abs(xdata2)>1.7) ) {
 	  dataColl.push_back(xdata);
	  hdata->Fill(xdata);
 	}
      } 
    }// keep reading files as long as text exists
    ndata = dataColl.size();

    printf("test print data 2 %2.3f \n", dataColl[2]);    
//     cout << "ndata in dataColl = " << ndata << endl;
    if ( ndata == 0 ) {
      printf(" no data to fit \n");
      return fitted;
    }
  }

  if(ndata==0) {
    printf(" ---  no events in the fit \n");
    return fitted;
  }
    
  //test fit the template and get PDFs
  TCanvas *c10 = new TCanvas("c10","c10",1000,500);
  c10->Divide(2,1);
  c10->cd(1);

  double par[20] = {hsig->GetMaximum(), 1., 0.6, 0.3,
		    hbkg->GetMaximum(), -.45, -0.05, 0.03, 1., 1., 1., 1.};

  if(strcmp(EBEE,"EE")==0) { par[2]=-0.1, par[3]=0.2; par[6]=-0.15; par[7]=0.02; };
  int fit_status;

  TF1 *f1 = new TF1("f1", exp_conv, -1., 20., 11);
  TF1 *fmcsigfit = new TF1("fmcsigfit", exp_conv, -1., 20., 11);
  fmcsigfit->SetLineColor(4);
  fmcsigfit->SetLineWidth(2);

  f1->SetNpx(10000);
  f1->SetParameters(par);
  f1->SetLineWidth(2);
  c10->cd(1);
  fit_status = hsig->Fit(f1,"","",-1., 5.);

  hsig->Draw();
  f1->Draw("same");
  if ( fit_status > 0 ) {
     printf("fit signal template failed. QUIT \n");
     return fitted;
  }
  if(para_index>0 && para_index<4){
    double tmppar = f1->GetParameter(para_index);
    f1->SetParameter(para_index, tmppar+para_sigma*f1->GetParError(para_index));
  }

  TF1 *fmcsig = (TF1*)f1->Clone();
  TF1 *fmcsigcorr = (TF1*)f1->Clone();
  fmcsig->SetNpx(10000);
  fmcsigcorr->SetNpx(10000);
  fmcsigfit->SetNpx(10000);
  
  TCanvas *c101 = new TCanvas("c101","c101",1000,500);
  c101->Divide(2,1);
  c101->cd(1);

  fmcsig->SetLineColor(1);
//   fmcsig->Draw();
//   f1->Draw("same");
  TH1F *htmp1 = (TH1F*)fmcsig->GetHistogram();
//   TH1F *htmp2 = (TH1F*)fmcsigcorr->GetHistogram();
  
  TH2F *htmp2 = new TH2F("htmp2","",210, -1., 20., 100, 0., htmp1->GetMaximum()*1.25);

  htmp2->SetNdivisions(505,"XY");
  htmp2->SetXTitle("Iso");
  htmp2->SetYTitle("A.U.");
  htmp2->SetLineColor(1);

//   htmp2->Draw();
//   htmp1->Draw("same");
//   htmp2->Add(htmp1,-1);
//   htmp2->Divide(htmp1);
  htmp2->GetXaxis()->SetRangeUser(-1., 10.);
  htmp2->SetMinimum(-1.);
  //htmp2->SetMaximum(1.5);
  htmp2->Draw();
  fmcsig->Draw("same");
//   fmcsigcorr->Draw("same");
  
  TLegend *tleg1 = new TLegend(0.5, 0.7, 0.93, 0.92);
  tleg1->SetHeader("");
  tleg1->SetFillColor(0);
  tleg1->SetShadowColor(0);
  tleg1->SetBorderSize(0);
  tleg1->AddEntry(fmcsig,"Zee data","l");
  //tleg1->AddEntry(fmcsigcorr,"corrected shape","l");
  tleg1->AddEntry(fmcsigfit,"shape from data","l");
  tleg1->Draw();

  //return fitted;
       
  SigPDFnorm = f1->Integral(-1.,20.);
  printf("status %d, sig area %3.3f \n", fit_status,f1->Integral(-1., 20.));


  f1->SetParameter(2,f1->GetParameter(2)+0.2);
  f1->SetParameter(3,f1->GetParameter(3)+0.1);

  Para.push_back(f1->GetParameter(0));
  Para.push_back(f1->GetParameter(1));
  Para.push_back(f1->GetParameter(2));
  Para.push_back(f1->GetParameter(3));

  Para_err.push_back(f1->GetParError(0));
  Para_err.push_back(f1->GetParError(1));
  Para_err.push_back(f1->GetParError(2));
  Para_err.push_back(f1->GetParError(3));

  c10->cd(2);
  TF1 *fbkgfit = new TF1("fbkgfit", expinv_power, -1., 20., 11);  

  TF1 *f3 = new TF1("f3", expinv_power, -1., 20., 11);
  fbkgfit->SetNpx(10000);  
  fbkgfit->SetLineColor(4);
  fbkgfit->SetLineWidth(2);

  f3->SetNpx(10000);
  f3->SetLineWidth(2);
  f3->SetParameters(f1->GetParameters());
    
  f3->SetParLimits(5,-5.,0.);
  f3->SetParLimits(6,-0.5,0.);
  f3->SetParLimits(7,0.001,0.2);
  f3->SetParLimits(8,0.5,5.);
  if ( strcmp(EBEE,"EB")==0 ){  
//     f3->FixParameter(8,1.);
//     f3->FixParameter(6,-0.1);
    f3->SetParLimits(8,1.,1.5);
  }

  float bkg_bend_power = 1.;
  if ( ptbin==21 ) bkg_bend_power = 4.5;
  if ( ptbin==23 ) bkg_bend_power = 4.;
  if ( ptbin==26 ) bkg_bend_power = 3.5;
  if ( ptbin==30 ) bkg_bend_power = 2.6;
  if ( ptbin==35 ) bkg_bend_power = 2.2;
  if ( ptbin==40 ) bkg_bend_power = 2.;
  if ( ptbin==45 ) bkg_bend_power = 2.;
  if ( ptbin==50 ) bkg_bend_power = 1.8;
  if ( ptbin==60 ) bkg_bend_power = 1.5;
  if ( ptbin==85 ) bkg_bend_power = 1.;
  if ( ptbin==120 ) bkg_bend_power = 1.;


  if ( strcmp(EBEE,"EE")==0 ){  
    f3->SetParameter(8,bkg_bend_power);
    f3->SetParLimits(8,bkg_bend_power-1., bkg_bend_power+1.);
  }

  f3->FixParameter(0,f3->GetParameter(0));
  f3->FixParameter(1,f3->GetParameter(1));
  f3->FixParameter(2,f3->GetParameter(2));
  f3->FixParameter(3,f3->GetParameter(3));

  hbkg->SetMaximum(hbkg->GetMaximum()*3.);
  fit_status = hbkg->Fit(f3,"b","",-1., 20.);
  hbkg->Draw();
  if ( fit_status > 0 ) {
    printf("fit background template failed. QUIT \n");    
    return fitted;
  }else {
    f3->Draw("same");
  }

  TF1 *fmcbkg = (TF1*)f3->Clone();
  fmcbkg->SetLineColor(1);
  c101->cd(2);

  htmp1 = (TH1F*)fmcbkg->GetHistogram();
  htmp2 = new TH2F("htmp2","",210, -1., 20., 100, 0., htmp1->GetMaximum()*1.25);

  htmp2->SetNdivisions(505,"XY");
  htmp2->SetXTitle("Iso");
  htmp2->SetYTitle("A.U.");
  htmp2->SetLineColor(1);

  htmp2->GetXaxis()->SetRangeUser(-1., 20.);
  htmp2->SetMinimum(-1.);
  htmp2->SetMaximum(1.5);
  htmp2->Draw();
  fmcbkg->Draw("same");

  TLegend *tleg2 = new TLegend(0.25, 0.2, 0.6, 0.42);
  tleg2->SetHeader("");
  tleg2->SetFillColor(0);
  tleg2->SetShadowColor(0);
  tleg2->SetBorderSize(0);
  if ( strcmp(EBEE,"EB")==0 ){  
    tleg2->AddEntry(fmcbkg,"MC shape","l");
  }else {
    tleg2->AddEntry(fmcbkg,"Data SB shape","l");
  }
  tleg2->AddEntry(fbkgfit,"shape from data","l");
  tleg2->Draw();
  
  if(para_index>4){
    double tmppar = f3->GetParameter(para_index);
    f3->SetParameter(para_index, tmppar+para_sigma*f3->GetParError(para_index));
  }

//   f3->SetParameter(5,-0.5);
//   f3->SetParameter(6,-0.05);
//   f3->SetParameter(7,0.02);
//   f3->SetParameter(8,1.);

  Para.push_back(f3->GetParameter(4));
  Para.push_back(f3->GetParameter(5));
  Para.push_back(f3->GetParameter(6));
  Para.push_back(f3->GetParameter(7)); 
  Para.push_back(f3->GetParameter(8)); 

  Para_err.push_back(f3->GetParError(4));
  Para_err.push_back(f3->GetParError(5));
  Para_err.push_back(f3->GetParError(6));
  Para_err.push_back(f3->GetParError(7));
  Para_err.push_back(f3->GetParError(8));

  BkgPDFnorm = f3->Integral(-1., 20.);
  printf("status %d, bkg area %3.3f \n", fit_status,f3->Integral(-1., 20.)/hdata->GetBinWidth(2));

  //test PDFs
  TCanvas *c11 = new TCanvas("c11","c11",1000,500);
  c11->Divide(2,1);
  c11->cd(1);
  TF1 *f11 = new TF1("f11",exp_conv_norm, -1., 20., 11);
  f11->SetNpx(10000);
  f11->SetParameters(f3->GetParameters());
  f11->Draw();
  printf(" SIG PDF area %2.3f \n", f11->Integral(-1., 20.));

  c11->cd(2);
  TF1 *f12 = new TF1("f12",expinv_power_norm, -1., 20., 11);
  f12->SetNpx(10000);
  f12->SetParameters(f3->GetParameters());
  f12->Draw();
  printf(" BKG PDF area %2.3f \n", f12->Integral(-1., 20.));

  //c1->cd();

  printf(" --------- before the fit ------------- \n");
  printf("Nsig %2.3f, Nbg %2.3f, Ntemplate %3.3f \n", hsig->Integral(), hbkg->Integral(), ntemplate);
  printf("Purity %2.3f, init size %4.3f,  fit sample size %4d\n", hsig->Integral()/hsum->Integral(), hsum->Integral(), ndata);
  printf(" -------------------------------------- \n");



  printf( " -----  Got %d, %d, %d events for fit ----- \n ", dataColl.size(),
	  sigColl.size(), bkgColl.size() );  

  //--------------------------------------------------
  //init parameters for fit
  Double_t vstart[11] = {1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.};
  vstart[0] = sigfrac*ndata;
  vstart[1] = (1-sigfrac)*ndata;
  for (int ii=0; ii<9; ii++) {    
    vstart[ii+2] = Para[ii]; //8 shape parameters
  }
  TMinuit *gMinuit = new TMinuit(NPAR);  
  gMinuit->Command("SET STR 1");
  gMinuit->SetFCN(fcn);
  Double_t arglist[11];
  Int_t ierflg = 0;
  
  arglist[0] = 1;
  gMinuit->mnexcm("SET ERR", arglist ,1,ierflg);
  arglist[0] = 1;
  gMinuit->mnexcm("SET PRINT", arglist ,1,ierflg);

  Double_t step[] = { 1.,1.,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,0.01,};

  for ( int ii=0; ii<9; ii++){
    printf(" para %d, %.5f, err %.5f \n", ii, Para[ii], Para_err[ii]);
  }

  float sigma = 3.;
  gMinuit->mnparm(0,  "Signal yield"  , vstart[0],  step[0], 0., ndata*2.  , ierflg);
  gMinuit->mnparm(1,  "background yield"  , vstart[1],  step[1], 0., ndata*2. , ierflg);

//   gMinuit->mnparm(2,  "constant"     , Para[0],  0.00,  Para[0], Para[0] , ierflg);
//   gMinuit->mnparm(3,  "exp tail"     , Para[1],  0.01,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg);
//   gMinuit->mnparm(4,  "exg mean"     , Para[2],  0.01,  Para[2]-sigma*Para_err[2], Para[2]+sigma*Para_err[2], ierflg);
//   gMinuit->mnparm(5,  "exg width"    , Para[3],  0.01,  Para[3]-sigma*Para_err[3], Para[3]+sigma*Para_err[3], ierflg);
//   gMinuit->mnparm(6,  "constant"     , Para[4],  0.00,  Para[4]                  , Para[4]                  , ierflg);
//   gMinuit->mnparm(7,  "bg exp turnon", Para[5],  0.01,  Para[5]-sigma*Para_err[5], Para[5]+sigma*Para_err[5], ierflg);
//   gMinuit->mnparm(8,  "bg x offset  ", Para[6],  0.01,  Para[6]-sigma*Para_err[6], Para[6]+sigma*Para_err[6], ierflg);
//   gMinuit->mnparm(9,  "bg bend slope", Para[7],  0.01,  0.001                    , 0.1                      , ierflg);
// //   gMinuit->mnparm(10, "bg bend power", Para[8],  0.01,  Para[8]-sigma*Para_err[8], Para[8]+sigma*Para_err[8], ierflg);
//   gMinuit->mnparm(10, "bg bend power", Para[8],  0.01,  0.5                       , 5.                       , ierflg);

//   gMinuit->mnparm(2,  "constant"     , Para[0], TMath::Abs(Para[0]*0.0) ,  Para[0], Para[0], ierflg);
//   gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.01) ,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg); 
// //   gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.1) ,  0.8    , 1.3    , ierflg);
//   gMinuit->mnparm(4,  "exg mean"     , Para[2], TMath::Abs(Para[2]*0.1) ,  0.5    , 1.0    , ierflg);
//   gMinuit->mnparm(5,  "exg width"    , Para[3], TMath::Abs(Para[3]*0.1) ,  0.25   , 0.5    , ierflg);
//   gMinuit->mnparm(6,  "constant"     , Para[4], TMath::Abs(Para[4]*0.0) ,  Para[4], Para[4], ierflg);
//   gMinuit->mnparm(7,  "bg exp turnon", Para[5], TMath::Abs(Para[5]*0.1) ,  -0.7   , -0.3   , ierflg);
//   gMinuit->mnparm(8,  "bg x offset  ", Para[6], TMath::Abs(Para[6]*0.0) ,  -0.15  , -0.05  , ierflg);
//   gMinuit->mnparm(9,  "bg bend slope", Para[7], TMath::Abs(Para[7]*0.1) ,  0.01   , 0.05   , ierflg);
//   gMinuit->mnparm(10, "bg bend power", Para[8], TMath::Abs(Para[8]*0.1) ,  0.5    , 1.5    , ierflg);

  gMinuit->mnparm(2,  "constant"     , Para[0],  0.00,  Para[0], Para[0] , ierflg);
  gMinuit->mnparm(3,  "exp tail"     , Para[1],  0.00,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg);
  gMinuit->mnparm(4,  "exg mean"     , Para[2],  0.00,  Para[2]-sigma*Para_err[2], Para[2]+sigma*Para_err[2], ierflg);
  gMinuit->mnparm(5,  "exg width"    , Para[3],  0.00,  Para[3]-sigma*Para_err[3], Para[3]+sigma*Para_err[3], ierflg);
  gMinuit->mnparm(6,  "constant"     , Para[4],  0.00,  Para[4]                  , Para[4]                  , ierflg);
  gMinuit->mnparm(7,  "bg exp turnon", Para[5],  0.00,  Para[5]-sigma*Para_err[5], Para[5]+sigma*Para_err[5], ierflg);
  gMinuit->mnparm(8,  "bg x offset  ", Para[6],  0.00,  Para[6]-sigma*Para_err[6], Para[6]+sigma*Para_err[6], ierflg);
  gMinuit->mnparm(9,  "bg bend slope", Para[7],  0.00,  0.001                    , 0.1                      , ierflg);
  gMinuit->mnparm(10, "bg bend power", Para[8],  0.00,  Para[8]-sigma*Para_err[8], Para[8]+sigma*Para_err[8], ierflg);
  
  printf(" --------------------------------------------------------- \n");
  printf(" Now ready for minimization step \n --------------------------------------------------------- \n");
  
  arglist[0] = 500; // number of iteration
  gMinuit->mnexcm("MIGRAD", arglist,1,ierflg);
  //can do scan
//   arglist[0] = 0;
//   gMinuit->mnexcm("SCAN", arglist,1,ierflg);

  printf (" -------------------------------------------- \n");
  printf("Finished.  ierr = %d \n", ierflg);

  double para[NPAR+1],errpara[NPAR+1];

  double tmp_errpara[NPAR+1];

  for(int j=0; j<=NPAR-1;j++) { tmp_errpara[j]=0.1; }
  for(int j=2; j<=NPAR-1;j++) { 
    if(Para_err[j-2]!=0.) tmp_errpara[j]=TMath::Abs(Para_err[j-2]); 
  }
  
  int ni=6;       if ( strcmp(EBEE,"EE")==0 ) { ni=6; }//if(ptbin==21) ni=0;}
  
  if ( ierflg == 0 ) {
    for(int i=0; i<ni; i++) {
      float istep[10] = {0.,0.,0.,0.,0.,0.,0.};
      if (i<(ni-1)) {
	istep[i] = 0.001;
      }else {
	for (int j=0; j<ni-1; j++) {istep[j] = 0.001;}
      }

      for(int j=0; j<=NPAR-1;j++) {
	gMinuit->GetParameter(j, para[j], errpara[j]);
	if (errpara[j] != 0. ) {
	  tmp_errpara[j] = TMath::Abs(errpara[j]);
	}
      }

      if ( strcmp(EBEE,"EB")==0 ) {

	sigma = 10.;

 	if ( i==(ni-1) ) { sigma=5.;istep[1]=istep[4]=0.; }
	if ( ptbin==21 && i==1 ){ sigma=3.; }
 	if ( ptbin==21 && i==(ni-1) ){ sigma=20.; }
	if ( ptbin==23 && i==0 ){ para[7]=-0.5; }
	if ( ptbin==23 && i==1 ){ istep[1]=0.; istep[3]=0.01; }
 	if ( ptbin==23 && i==3 ){ istep[1]=0.01; istep[3]=0.0; }
	if ( ptbin==23 && i==(ni-1) ){ sigma=20.; }
 	if ( ptbin==26 && i==1 ){ sigma=5.; }	
	if ( ptbin==26 && i==(ni-1) ){ sigma=20.; }
	if ( ptbin==30 && i==(ni-1) ){ sigma=3.; }
 	if ( ptbin==35 && i==(ni-1) ) { sigma=10.; }
 	if ( ptbin==40 && i==(ni-1) ) { sigma=5.; istep[4]=0.01; }
 	if ( ptbin==45 && i==(ni-1) ) { sigma=10.; }
	if ( ptbin==60 && i==0 ) { para[3]=1.; para[4]=0.6; para[5]=0.32; para[7]=-0.45; para[9]=0.025; para[10] = 1.;}
 	if ( ptbin==60 && i==(ni-1) ) { sigma=5.; istep[4]=0.01;}
	if ( ptbin>=85 && i==(ni-1) ){ sigma=3.; }
	if ( ptbin==300 ) { istep[2]=istep[3]=istep[4]=0.; }// para[7] = -5.11907e-02; istep[1]=0.; }
	float tmp8=0.;
	
// 	if( i!= (ni-1) ) {
	  gMinuit->mnparm(0,  "Signal yield"  ,   para[0],  1., para[0]-100.*tmp_errpara[0], para[0]+100.*tmp_errpara[0], ierflg);
	  gMinuit->mnparm(1,  "background yield", para[1],  1., para[1]-100.*tmp_errpara[1], para[1]+100.*tmp_errpara[1], ierflg);
	  gMinuit->mnparm(2,  "constant"     , para[2],  0., para[2]-100.*tmp_errpara[2], para[2]+100.*tmp_errpara[2], ierflg);
	  gMinuit->mnparm(6,  "constant"     , para[6],  0., para[6]-100.*tmp_errpara[6], para[6]+100.*tmp_errpara[6], ierflg);
	  gMinuit->mnparm(3,  "exp tail"     , para[3],  istep[4],  para[3]-sigma*tmp_errpara[3], para[3]+sigma*tmp_errpara[3], ierflg);
	  gMinuit->mnparm(4,  "exg mean"     , para[4],  istep[3],  para[4]-sigma*tmp_errpara[4], para[4]+sigma*tmp_errpara[4], ierflg);
	  gMinuit->mnparm(5,  "exg width"    , para[5],  istep[2],  para[5]-sigma*tmp_errpara[5], para[5]+sigma*tmp_errpara[5], ierflg);
	  gMinuit->mnparm(7,  "bg exp turnon", para[7],  istep[1],  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);
	  gMinuit->mnparm(8,  "bg x offset  ", para[8],  tmp8    ,  para[8]-sigma*tmp_errpara[8], para[8]+sigma*tmp_errpara[8], ierflg);
	  gMinuit->mnparm(9,  "bg bend slope", para[9],  istep[0],  para[9]-sigma*tmp_errpara[9], para[9]+sigma*tmp_errpara[9], ierflg);      
	  float sigma10=5.;
	  if ( para[10]-sigma10*tmp_errpara[10] < 1. )// && i!=(ni-1))
	    gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], 1.,  para[10]+sigma10*tmp_errpara[10], ierflg);      
	  else
	    gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], para[10]-sigma10*tmp_errpara[10],  para[10]+sigma10*tmp_errpara[10], ierflg);      
// 	}else {
// 	  gMinuit->mnparm(2,  "constant"     , Para[0], TMath::Abs(Para[0]*0.0) ,  Para[0], Para[0], ierflg);
// 	  //gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.01) ,  Para[1]-sigma*Para_err[1], Para[1]+sigma*Para_err[1], ierflg); 
// 	  gMinuit->mnparm(3,  "exp tail"     , Para[1], TMath::Abs(Para[1]*0.0) ,  0.8    , 1.3    , ierflg);
// 	  gMinuit->mnparm(4,  "exg mean"     , Para[2], TMath::Abs(Para[2]*0.1) ,  0.5    , 1.0    , ierflg);
// 	  gMinuit->mnparm(5,  "exg width"    , Para[3], TMath::Abs(Para[3]*0.1) ,  0.25   , 0.5    , ierflg);
// 	  gMinuit->mnparm(6,  "constant"     , Para[4], TMath::Abs(Para[4]*0.0) ,  Para[4], Para[4], ierflg);
// 	  gMinuit->mnparm(7,  "bg exp turnon", Para[5], TMath::Abs(Para[5]*0.0) ,  -0.7   , -0.3   , ierflg);
// 	  gMinuit->mnparm(8,  "bg x offset  ", Para[6], TMath::Abs(Para[6]*0.0) ,  -0.15  , -0.05  , ierflg);
// 	  gMinuit->mnparm(9,  "bg bend slope", Para[7], TMath::Abs(Para[7]*0.1) ,  0.01   , 0.05   , ierflg);
// 	  gMinuit->mnparm(10, "bg bend power", Para[8], TMath::Abs(Para[8]*0.1) ,  0.5    , 1.5    , ierflg);
// 	}


	if( ptbin >=300 ) { 
	  gMinuit->mnparm(3,  "exp tail"  , 1.257281,  0.0,  para[1]-3.*tmp_errpara[1], para[1]+3.*tmp_errpara[1], ierflg);
	  gMinuit->mnparm(4,  "exg mean"  , 0.856906,  0.0,  para[2]-3.*tmp_errpara[2], para[2]+3.*tmp_errpara[2], ierflg);
	  gMinuit->mnparm(5,  "exg width" , 0.320847,  0.0,  para[3]-3.*tmp_errpara[3], para[3]+3.*tmp_errpara[3], ierflg);
	}      

    }else{	

	sigma=10.;
	if ( i==0 ) { para[10] = bkg_bend_power; tmp_errpara[10] = 0.3; }
 	if ( i==(ni-1) ) { sigma=3.;istep[1]=istep[4]=0.; } //test of not changing signal template
     	if ( i==(ni-1) ) { istep[4]=0.;}

   	if ( ptbin==21 && i==(ni-1) ) { sigma=20.;}
  	if ( ptbin==23 && i==0 ) { sigma=5.;}
  	if ( ptbin==23 && i==(ni-1) ) { sigma=10.;}
	if ( ptbin<30 && ptbin>21 && i==1 ){ istep[1]=0.; istep[3]=0.01; }
 	if ( ptbin<30 && ptbin>21 && i==3 ){ istep[1]=0.01; istep[3]=0.0; }
	if ( ptbin==26 && i==1 ) { para[7] = -0.8; }
	if ( ptbin==26 && i==(ni-1) ) { sigma=10.; }
  	if ( ptbin==30 && i==(ni-1) ) { sigma=10.; }
 	if ( ptbin==35) {para[7] = -0.75;}
 	if ( ptbin==40 && i==0) {para[7] = -0.65; para[10] = 2.;}
	if ( ptbin==45 && i==(ni-1) ) {sigma=5.;}
	if ( ptbin==85 && i==(ni-1) ) {sigma=10.; istep[4]=0.01;}
	if (ptbin >= 85 ) { para[10] = bkg_bend_power; tmp_errpara[10] = 1.; }

	if ( ptbin==120 ) { para[7] = -0.615255; istep[1]=0.;}

	
//     	if ( ptbin==120 && i==0 ) { 
// 	  para[3] = 1.446454; para[4]=-0.016373; para[5]=0.163238;
// 	  istep[2]=istep[3]=istep[4]=0.; sigma=5.; tmp_errpara[10]=0.2;
// 	}
//     	if ( ptbin==120 && i==(ni-1) ) { istep[2]=istep[3]=istep[4]=0.; sigma=5.;}

	gMinuit->mnparm(0,  "Signal yield"  ,   para[0],  1., para[0]-100.*tmp_errpara[0], para[0]+100.*tmp_errpara[0], ierflg);
	gMinuit->mnparm(1,  "background yield", para[1],  1., para[1]-100.*tmp_errpara[1], para[1]+100.*tmp_errpara[1], ierflg);
	gMinuit->mnparm(2,  "constant"     , para[2],  0.,  para[2], para[2] , ierflg);
	gMinuit->mnparm(6,  "constant"     , para[6],  0.,  para[6], para[6], ierflg);	
	gMinuit->mnparm(3,  "exp tail"     , para[3],  istep[4],  para[3]-sigma*tmp_errpara[3], para[3]+sigma*tmp_errpara[3], ierflg);
	gMinuit->mnparm(4,  "exg mean"     , para[4],  istep[3],  para[4]-sigma*tmp_errpara[4], para[4]+sigma*tmp_errpara[4], ierflg);
	gMinuit->mnparm(5,  "exg width"    , para[5],  istep[2],  para[5]-sigma*tmp_errpara[5], para[5]+sigma*tmp_errpara[5], ierflg);
	gMinuit->mnparm(7,  "bg exp turnon", para[7],  istep[1],  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);
	gMinuit->mnparm(8,  "bg x offset  ", para[8],  0.00,      para[8]-sigma*tmp_errpara[8], para[8]+sigma*tmp_errpara[8], ierflg);
	gMinuit->mnparm(9,  "bg bend slope", para[9],  istep[0],  para[9]-sigma*tmp_errpara[9], para[9]+sigma*tmp_errpara[9], ierflg);	
  
	float minerr=1.;
	//if ( tmp_errpara[10] > 0.5) tmp_errpara[10] = 0.5;
	float sigma10=5.;
	if ( para[10]-sigma10*tmp_errpara[10] < 1. ) 
	  gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], minerr,  para[10]+sigma10*tmp_errpara[10], ierflg);
	else 
	  gMinuit->mnparm(10, "bg bend power", para[10],  istep[0], para[10]-sigma10*tmp_errpara[10],  para[10]+sigma10*tmp_errpara[10], ierflg);

      }
      printf(" ************ \n");
      printf("  do %d th fit  \n", i);
      if(i==5 && dataFile.find("toy")    != std::string::npos)
	{
	  cout << "dataResult = " << dataResult << "\t dataErr = " << dataErr << endl;
	  // fixed turn on at +- 1 sigma
	  gMinuit->mnparm(7,  "bg exp turnon", dataResult-(float)shift*dataErr,  0.00,  para[7]-sigma*tmp_errpara[7], para[7]+sigma*tmp_errpara[7], ierflg);

	}
      else if(dataFile.find("toy")    == std::string::npos)
	{
	  dataResult = para[7];
	  dataErr    = tmp_errpara[7];
	}
      arglist[0] = 500; // number of iteration
      gMinuit->mnexcm("MIGRAD", arglist ,1,ierflg);      
      if ( ierflg != 0 ) {
  	printf("fit failed at %d iteration \n", i);
  	c1->cd();	c1->Draw();  	hdata->Draw("phe");
  	return fitted;
      }
    }
  }
 
  Double_t amin,edm,errdef; 
  if ( ierflg == 0 ) {
    for(int j=0; j<=NPAR-1;j++) {
      gMinuit->GetParameter(j, para[j],errpara[j]);
      info.push_back(para[j]);
      info_err.push_back(errpara[j]);
      printf("Parameter  %d = %f +- %f\n",j,para[j],errpara[j]);	
    }
    para[NPAR] = dataColl.size();
    printf(" fitted yield %2.3f \n", (para[0]+para[1])/ndata );
    
    info.push_back(sigColl.size());
    
    for(int j=0; j<=NPAR-1;j++) {
      tmp_errpara[j] = errpara[j];
      if( tmp_errpara[j] == 0. ) tmp_errpara[j] = par[j]*.1;      
    }
    //do minos if fit sucessed.

  }
  if (ierflg != 0 )  {
    printf(" *********** Fit failed! ************\n");
    gMinuit->GetParameter(0, para[0],errpara[0]);
    gMinuit->GetParameter(1, para[1],errpara[1]);
    para[0]=0.; errpara[0]=0.;

    c1->cd();
    c1->Draw();  
    //gPad->SetLogy();
    hdata->SetNdivisions(505,"XY");
    hdata->SetXTitle("comb. ISO (GeV)");
    hdata->SetYTitle("Entries");
    hdata->SetTitle("");
    hdata->SetMarkerStyle(8);
    hdata->SetMinimum(0.);
    if ( hdata->GetMaximum()<10.) hdata->SetMaximum(15.);
    else hdata->SetMaximum(hdata->GetMaximum()*1.25);
    if ( strcmp(EBEE,"EE")==0 &&ptbin == 15 ) hdata->SetMaximum(hdata->GetMaximum()*1.25);
   
    hdata->Draw("phe");  

    return fitted;    
  }

  
  // Print results
//   Double_t amin,edm,errdef;
  Int_t nvpar,nparx,icstat;
  gMinuit->mnstat(amin,edm,errdef,nvpar,nparx,icstat);
  gMinuit->mnprin(1,amin);  
  gMinuit->mnmatu(1);
  printf(" ========= happy ending !? =========================== \n");
  
  printf("FCN =  %3.3f \n", amin);

  //use new PDF form
  double tmppar[12];
  for(int ii=0; ii<9; ii++){
    tmppar[ii] = para[ii+2];
    fmcsigfit->SetParameter(ii,tmppar[ii]);
    fbkgfit->SetParameter(ii,tmppar[ii]);
  }

  c101->cd(1);
  
  //fmcsigfit->SetParameters(tmppar);
  //fmcsigfit->SetParameter(2,0.1);
  //fmcsigfit->SetLineStyle(2);

  fmcsigfit->Draw("same");
  c101->cd(2);

  fbkgfit->SetParameter(4,fbkgfit->GetParameter(4)*fmcbkg->Integral(-1., 20.)/fbkgfit->Integral(-1., 20.));
  fbkgfit->Draw("same");

  char fname[100];
  sprintf(fname,"plots/template_Ifit%s_%d.pdf",EBEE,ptbin);
  c101->SaveAs(fname);


  f11->SetParameters(tmppar);
  SigPDFnorm = f11->Integral(-1., 20.);
  f12->SetParameters(tmppar);
  BkgPDFnorm = f12->Integral(-1., 20.);


  // plot
  c1->cd();
  c1->Draw();  
  //gPad->SetLogy();
   hdata->SetNdivisions(505,"XY");
   hdata->SetXTitle("comb. ISO (GeV)");
   hdata->SetYTitle("Entries");
   hdata->SetTitle("");
   hdata->SetMarkerStyle(8);
   hdata->SetMinimum(0.);
   if ( hdata->GetMaximum()<10.) hdata->SetMaximum(15.);
   else hdata->SetMaximum(hdata->GetMaximum()*1.5);
   if ( strcmp(EBEE,"EE")==0 &&ptbin == 15 ) hdata->SetMaximum(hdata->GetMaximum()*1.2);

   hdata->Draw("p e ");

  f11->SetParameter(0, para[0]*f11->GetParameter(0)/f11->Integral(-1., 20.)*hdata->GetBinWidth(2));
//   f11->SetFillColor(5);
  f11->SetLineColor(4);
  //f11->SetFillColor(603);
  f11->SetLineWidth(2);
//   f11->SetFillStyle(3001);
  f11->Draw("same");

  f12->SetParameter(4, para[1]*f12->GetParameter(4)/f12->Integral(-1., 20.)*hdata->GetBinWidth(2));
//   f12->SetFillColor(8);
  f12->SetLineColor(2);
  //f12->SetFillColor(603);
  f12->SetLineWidth(2);
//   f12->SetFillStyle(3013);
  f12->Draw("same");

  TF1 *f13 = new TF1("f13",sum_norm, -1., 20 ,11);
  f13->SetNpx(10000);
  f13->SetParameters(f12->GetParameters());
  f13->SetParameter(0, para[0]*f11->GetParameter(0)/f11->Integral(-1., 20.)*hdata->GetBinWidth(2));
  f13->SetParameter(4, para[1]*f12->GetParameter(4)/f12->Integral(-1., 20.)*hdata->GetBinWidth(2));  
  f13->SetLineWidth(2);
  f13->SetLineColor(1);
  f13->Draw("same");
  f11->Draw("same");
  hdata->Draw("pe same");

//   cout << "The number of bins are: " << endl;
//   cout << "hdata nbins = " << hdata->GetNbinsX() << endl;
//   cout << "hsig nbins = " << hsig->GetNbinsX() << endl;
//   cout << "hbkg nbins = " << hbkg->GetNbinsX() << endl;

  // get chi2/NDF
  double chi2ForThisBin=0;
  int nbinForThisBin=0;
  chi2Nbins(f13, hdata, chi2ForThisBin, nbinForThisBin);
  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f11 parameter " << epar << " = " << 
// 	f11->GetParameter(epar) << endl;
      FitPar[epar] = f11->GetParameter(epar);
    }

  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f12 parameter " << epar << " = " << 
// 	f12->GetParameter(epar) << endl;
      FitPar[epar+11] = f12->GetParameter(epar);
    }

  for(int epar=0; epar < 11; epar++)
    {
//       cout << "f13 parameter " << epar << " = " << 
// 	f13->GetParameter(epar) << endl;
      FitPar[epar+22] = f13->GetParameter(epar);

    }

//   cout << "hdata integral = " << hdata->Integral() << endl;
//   cout << endl;

//   printf("fit area %3.2f; sig area %3.2f; bg area %3.2f\n", f13->Integral(-1., 20.)/hdata->GetBinWidth(2),  f11->Integral(-1., 20.)/hdata->GetBinWidth(2),f12->Integral(-1., 20.)/hdata->GetBinWidth(2));

//   for(int i=0; i<12; i++){
//     printf(" fit para %d = %4.3f \n", i, f13->GetParameter(i));
//   }

   TLegend *tleg = new TLegend(0.5, 0.7, 0.93, 0.92);
   char text[50];
   sprintf(text,"%s Pt %d ~ %.0f GeV",EBEE, ptbin, ptmax);
   tleg->SetHeader(text);
   tleg->SetFillColor(0);
   tleg->SetShadowColor(0);
   tleg->SetBorderSize(0);
   sprintf(text,"#chi^{2}/NDF = %.1f/%d",chi2ForThisBin,nbinForThisBin);
   tleg->AddEntry(hdata,text,"");
   sprintf(text,"Data %.1f events",hdata->Integral());
   tleg->AddEntry(hdata,text,"pl");
   sprintf(text,"Fitted %.1f events",para[0]+para[1]);//f13->Integral(-1., 20.)/hdata->GetBinWidth(2));
   tleg->AddEntry(f13,text,"l");
   sprintf(text,"SIG %.1f #pm %.1f events",para[0], errpara[0]);
   tleg->AddEntry(f11,text,"f");
   sprintf(text,"BKG %.1f #pm %.1f events",para[1], errpara[1]);
   tleg->AddEntry(f12,text,"f");
   tleg->Draw();


   gPad->RedrawAxis();

   printf("%s, ptbin %d, Data %.1f events \n",EBEE, ptbin, hdata->Integral());
   printf("Fitted %.1f (in 5GeV) %.1f events \n",para[0]+para[1],f13->Integral(-1.,5.));
   printf("SIG %.1f #pm %.1f events \n",para[0], errpara[0]);
   printf("SIG (in 5GeV) %.1f #pm %.1f events \n",f11->Integral(-1.,5.)/hdata->GetBinWidth(2), f11->Integral(-1.,5.)*errpara[0]/para[0]/hdata->GetBinWidth(2));
   printf("BKG %.1f #pm %.1f events \n",para[1], errpara[1]);
   printf("BKG (in 5GeV) %.1f #pm %.1f events \n",f12->Integral(-1.,5.)/hdata->GetBinWidth(2), f12->Integral(-1.,5.)*errpara[1]/para[1]/hdata->GetBinWidth(2));
   
   float purity = f11->Integral(-1.,5.)/hdata->GetBinWidth(2)/(f11->Integral(-1.,5.)/hdata->GetBinWidth(2)+f12->Integral(-1.,5.)/hdata->GetBinWidth(2));
   float purity_err = purity*errpara[0]/para[0];
   printf("Purity (in 5GeV) %.3f #pm %.3f  \n", purity, purity_err);


//   hsig->Scale(para[0]/hsig->Integral());
//   hbkg->Scale(para[1]/hbkg->Integral());
//   hbkg->Add(hsig);

//   hsig->SetLineColor(1);
//   hsig->SetFillColor(5);
//   hsig->SetFillStyle(3001);

//   hbkg->SetLineWidth(2);


//   hsig->Draw("same");
//   hbkg->Draw("same");


  sprintf(fname,"plots/unbinned_free_Ifit%s_%d.pdf",EBEE,ptbin);
  if (para_index>0) sprintf(fname,"plots/unbinned_Ifit%s_%d_para%d_sigma%1.0f.pdf",EBEE,ptbin,para_index,para_sigma);
  if(Opt_SavePDF == 1) {
    c1->SaveAs(fname);


  } else {

   c1->Close();
   c10->Close();
   c101->Close();
   c11->Close();

  }

  printf("----- fit results with signal projection   ----------- \n");

  fitted[0] = para[0];
  fitted[1] = errpara[0];
  fitted[2] = para[1];
  fitted[3] = errpara[1];
  fitted[4] = f11->Integral(-1.,5.)/hdata->GetBinWidth(2);
  fitted[5] = f11->Integral(-1.,5.)*errpara[0]/para[0]/hdata->GetBinWidth(2);

  return fitted;
}
Ejemplo n.º 28
0
int fitfunc(int *energy, int *gopt, int append, char* addname){
  if(setlogy==0){
    //double labelx[6]={380,800,1200,1700,2400,5000}, labely[6]={80,45,25,21,25,15}; //Position
  }else{
    //double labelx[6]={300,750,1400,1800,2700,5000}, labely[6]={130,75,50,30,25,5}; //Position
  }

  //void fitfunc(int energy[5], int gopt[5]){
  for(int i=0; i<6; i++){
    cout<<energy[i]<<" "<<gopt[i]<<endl;
  }
  
  if(histname=="p2p"){
    char* dirsim = "../output/rec";
  }else if(histname=="p3p"){
    //char* dirsim = "../output/rec_p3p";
    char* dirsim = "../output/rec";
    //char* direxp = "../expout/Feb12/h_SpectrumMINOS_wAdBk.root";
    //char* outname = Form("../output/fit/%i%i%i%i%i_%s%i",gopt[0],gopt[1],gopt[2],gopt[3],gopt[4],histname,energy[4]); // .pdf .png .C .root will be created
  }else{// if(histname=="h23"){
    char* dirsim = "../output/rec";
    //char* direxp = "../expout/Feb12/h_SpectrumMINOS_wAdBk.root";
    //char* outname = Form("../output/fit/%i%i%i%i%i_%s%i",gopt[0],gopt[1],gopt[2],gopt[3],gopt[4],histname,energy[4]); // .pdf .png .C .root will be created
  }

  char* outname = Form("../output/fit/%s_%i_%i_%i_%i_%i_%i%s",histname, energy[0],energy[1],energy[2],energy[3],energy[4],energy[5],addname); // .pdf .png .C .root will be created


  ofstream fpara(Form("%s_fitresult.txt",outname));
  if(append == 1){
    ofstream fitlist(Form("../output/fit/fitlist_%s%s.csv",histname,addname),ios_base::app);
  }else{
    ofstream fitlist(Form("../output/fit/fitlist_%s%s.csv",histname,addname));    
  fitlist<<"E0, E1, E2, E3, E4, E5, CS0, CS1, CS2, CS3, CS4, CS5, ER0, ER1, ER2, ER3, ER4, ER5, Chi-sq"<<endl;
  }
  
  gStyle->SetOptStat(kFALSE);
  
  gROOT->ProcessLine( ".L fit78Ni.h" );
  gStyle->SetOptStat(kFALSE);
  gStyle->SetPadGridX(false);
  gStyle->SetPadGridY(false);
  //gStyle->SetOptLogy(1);

  char temp[300];
  int minBin = 0;
  //int maxBin = 5500;
  int maxBin = 6000;
  int binning = 100;
  int numBin = (maxBin-minBin)/binning;
  
  //Id starts with one!!!
  int daliIDMin = 1;
  int daliIDMax = 186;

  //****************************************************************************
  // The simulated peaks
  TFile *sim[6];
  for(int i=0; i<6; i++){
    if(energy[i]>0){
      sim[i] = new TFile(Form("%s/%ikeV.root",dirsim,energy[i]));
    }else{
      sim[i] = new TFile(Form("%s/%ikeV.root",dirsim,2620));//dummy
      gopt[i] = 0;
    }
  }

  //The experimental data:
  TFile *exp[1];
  //exp[0] = new TFile(Form("%s/MINOStest.root",direxp));
  exp[0] = new TFile(direxp);

  TCanvas *fCanvas=new TCanvas("Canvas","Response function",700,700);
  fCanvas->SetBorderSize(0);
  fCanvas->SetBorderMode(0);
  fCanvas->SetFrameBorderMode(0);
  fCanvas->SetFrameFillColor(0);
  fCanvas->SetBottomMargin(0.15);
  fCanvas->SetLeftMargin(0.15);
  fCanvas->cd();

  TFile *fout = new TFile(Form("%s.root",outname),"RECREATE");
  fout->cd();

  // Main
  TPad *c_m = new TPad("c_m", "c_m",0.0,0.0,1.0,1.0);
  c_m->Draw();
  c_m->cd();
  c_m->SetFillColor(0);
  //c_m->SetFillStyle(0);
  c_m->SetBorderSize(0);
  c_m->SetRightMargin(0.05);
  c_m->SetTopMargin(0.03);
  c_m->SetBottomMargin(0.15);
  c_m->SetLeftMargin(0.15);
  if(setlogy>0) c_m->SetLogy();
  fCanvas->cd();

  //****************************************************************************
  //The simulated spectra:
  TH1F *hsim[6];
  for(int i=0;i<6;i++) {
    sprintf(temp,"hsim[%i]",i);  
    hsim[i] = new TH1F(temp,temp,numBin,minBin,maxBin);
    hsim[i] = (TH1F*)sim[i]->Get("h_doppler_addback[0]");
  }
  /*
  hsim[0] = (TH1F*)sim[0]->Get("h_doppler_addback[0]");
  hsim[1] = (TH1F*)sim[1]->Get("h_doppler_addback[0]");
  hsim[2] = (TH1F*)sim[2]->Get("h_doppler_addback[0]");
  hsim[3] = (TH1F*)sim[3]->Get("h_doppler_addback[0]");
  hsim[4] = (TH1F*)sim[4]->Get("h_doppler_addback[0]");
  */

  //The experimental spectra:
  TH1F *hexp[1];
  for(int i=0;i<1;i++) {
    sprintf(temp,"hexp[%i]",i);  
    hexp[i] = new TH1F(temp,temp,numBin,minBin,maxBin);
  }

  //Getting the experimental spectrum
  //78Ni
  hexp[0] = (TH1F*)exp[0]->Get(histname);
  //hexp[0] = (TH1F*)exp[0]->Get("h23;1");
  //hexp[0]->Rebin(2);

  
  for(int i=0;i<1;i++) {
    hexp[i]->SetStats(0);
    hexp[i]->SetFillColor(0);
    hexp[i]->SetLineColor(kBlue);
    hexp[i]->SetLineStyle(0);
    
    //hexp[i]->GetXaxis()->SetRangeUser(0,maxBin);
    hexp[i]->GetXaxis()->SetRangeUser(minBin,maxBin);
    //hexp[i]->GetXaxis()->SetRangeUser(0,6000);
    if(setlogy==0){
      hexp[i]->GetYaxis()->SetRangeUser(0,yrangemax);
    }else {
      hexp[i]->GetYaxis()->SetRangeUser(0.5,yrangemax);
    }

    hexp[i]->GetXaxis()->SetNdivisions(305);
    hexp[i]->GetYaxis()->SetNdivisions(305);
  
    hexp[i]->GetYaxis()->SetTitle(Form("Counts / %i keV",binning));
     hexp[i]->GetXaxis()->SetTitle("Energy (keV)");
    
    hexp[i]->GetXaxis()->SetTitleOffset(0.9);  
    hexp[i]->GetYaxis()->SetTitleOffset(0.9);
    
    hexp[i]->GetXaxis()->SetTitleFont(132);
    hexp[i]->GetYaxis()->SetTitleFont(132);
    
    /*
    hexp[i]->GetXaxis()->SetTitleSize(0.08);
    hexp[i]->GetYaxis()->SetTitleSize(0.08);
    
    hexp[i]->GetXaxis()->SetLabelSize(0.08);
    hexp[i]->GetYaxis()->SetLabelSize(0.08);
    */
    hexp[i]->GetXaxis()->SetTitleSize(0.05);
    hexp[i]->GetYaxis()->SetTitleSize(0.05);
    
    hexp[i]->GetXaxis()->SetLabelSize(0.05);
    hexp[i]->GetYaxis()->SetLabelSize(0.05);

    //How to get error bar for each bin
    hexp[i]->SetDefaultSumw2(kTRUE);
    

    hexp[i]->SetTitle("");
  }   
   
  //*****************************************************************************
  peak1g = new TGraph(hsim[0]);
  peak2g = new TGraph(hsim[1]);
  peak3g = new TGraph(hsim[2]);
  peak4g = new TGraph(hsim[3]);
  peak5g = new TGraph(hsim[4]);
  peak6g = new TGraph(hsim[5]);
  /*TGraph *peak1g = new TGraph(hsim[0]);
  TGraph *peak2g = new TGraph(hsim[1]);
  TGraph *peak3g = new TGraph(hsim[2]);
  TGraph *peak4g = new TGraph(hsim[3]);
  TGraph *peak5g = new TGraph(hsim[4]);
  */
  //******************Function Definition****************************************
  //*****************************************************************************
  const Double_t fitmin=300.;
  const Double_t fitmax=(Double_t)maxBin;//4000.;
   
  c_m->cd();
  TF1 *whole = new TF1( "whole", ex_respf,fitmin,fitmax,10);
  whole->SetParameters(0.0001,0.01,0.00,0.0001,0.001,0.001,3.,-1e-03,3,-1.e-3);
  //whole->SetParameters(0.0001,0.0001,0.0001, 5.9,-0.00080 );

  for(int i=0; i<6; i++){
    if(gopt[i]==1){
      whole->SetParLimits(i,0.0,parlimit[i]);
    }else{
      whole->FixParameter(i,0.0);
    }
  }
  whole->SetParLimits(6,0,10);
  whole->SetParLimits(7,-1e-02,0.);
  whole->SetParLimits(8,0,5);
  whole->SetParLimits(9,-1e-02,-1e-5);
  //whole->FixParameter(8,1.426);
  //whole->FixParameter(9,-8.1e-5);
  whole->SetLineColor(1);
  whole->SetLineWidth(2);
  whole->SetNpx(200); 
  hexp[0]->Fit(whole,"R LL");
  //hexp[0]->Fit(whole,"");
  //cout<<"test"<<endl;
  //hexp[0]->Draw("");

  //hexp[0]->GetXaxis()->SetRangeUser(0,5000);


  //fCanvas->Print(Form("%s.png",outname));

  fpara<<"Chisquare\t"<< whole->GetChisquare()<<endl;
  fpara<<"para\tvalue\terror\tfilename"<<endl;
  for(int para=0;para<10;para++){
    fpara<<para<<"\t"<<whole->GetParameter(para)<<"\t"<<whole->GetParError(para);
    if(para<6) {
      string strenergy =sim[para]->GetName();
      int itr = strenergy.find_last_of("/");
      strenergy.erase(0,itr+1);
      fpara<<"\t"<<strenergy;
    }
    fpara<<endl;
  }
  
  // fitlist<<"E0, E1, E2, E3, E4, CS0, CS1, CS2, CS3, CS4, ER0, ER1, ER2, ER3, ER4, Chi-sq"<<endl;
  for(int i=0; i<6; i++) gopt[i]==1? fitlist<<energy[i]<<", ": fitlist<<"0, ";
  for(int i=0; i<6; i++) gopt[i]==1? fitlist<<genevts*whole->GetParameter(i)*CSincl/tot78Ni<<", ": fitlist<<"0, ";
  for(int i=0; i<6; i++){gopt[i]==1?
      fitlist<<sqrt(pow(whole->GetParError(i)*CSincl,2.) //Error from fitting
		    //+whole->GetParameter(i)*pow(CSincl,2) //Statistical error for the events (included?
		    //+pow(whole->GetParameter(i)*CSinclerr,2) // Inclusive cross section error
		    )*genevts/tot78Ni<<", " 
      :fitlist<<"0, ";
      }
  fitlist<<whole->GetChisquare()<<endl;

  //RT end


  TF1 *peak1f= new TF1( "peak1f", resp1,fitmin,fitmax,1);
  peak1f->SetParameter(0,whole->GetParameter(0) );
  peak1f->SetLineColor(2);
  peak1f->SetLineWidth(2);
  peak1f->SetLineStyle(9);
  peak1f->Draw("same");

  TF1 *peak2f= new TF1( "peak2f", resp2,fitmin,fitmax,1);
  peak2f->SetParameter(0,whole->GetParameter(1) );
  peak2f->SetLineColor(2);
  peak2f->SetLineWidth(2);
  peak2f->SetLineStyle(9);
  peak2f->Draw("same");

  //
  TF1 *peak3f= new TF1( "peak3f", resp3,fitmin,fitmax,1);
  peak3f->SetParameter(0,whole->GetParameter(2) );
  peak3f->SetLineColor(2);
  peak3f->SetLineWidth(2);
  peak3f->SetLineStyle(9);
  peak3f->Draw("same");
  
  TF1 *peak4f= new TF1( "peak4f", resp4,fitmin,fitmax,1);
  peak4f->SetParameter(0,whole->GetParameter(3) );
  peak4f->SetLineColor(2);
  peak4f->SetLineWidth(2);
  peak4f->SetLineStyle(9);
  peak4f->Draw("same");
  
  TF1 *peak5f= new TF1( "peak5f", resp5,fitmin,fitmax,1);
  peak5f->SetParameter(0,whole->GetParameter(4) );
  peak5f->SetLineColor(2);
  peak5f->SetLineWidth(2);
  peak5f->SetLineStyle(9);
  peak5f->Draw("same");

  TF1 *peak6f= new TF1( "peak6f", resp6,fitmin,fitmax,1);
  peak6f->SetParameter(0,whole->GetParameter(5) );
  peak6f->SetLineColor(2);
  peak6f->SetLineWidth(2);
  peak6f->SetLineStyle(9);
  peak6f->Draw("same");


  TF1 *expon= new TF1( "expon",expf ,fitmin,fitmax,4);
  //expon->SetParameters(whole->GetParameter(5),whole->GetParameter(6),whole->GetParameter(7),whole->GetParameter(8));
  expon->SetParameters(whole->GetParameter(6),whole->GetParameter(7),whole->GetParameter(8),whole->GetParameter(9));
  expon->SetLineColor(4);
  expon->SetLineWidth(2);
  expon->SetLineStyle(7);
  expon->Draw("same");

  //hexp[0]->Draw("same");
  hexp[0]->Draw("EL same");
  
  /*TLatex *tex = new TLatex(2000,setlogy?130:60,Form("^{78}Ni (%s)",histname));
  tex->SetTextFont(132);
  tex->SetTextSize(0.07);
  tex->SetLineWidth(2);
  tex->Draw();
  */
  /*TLatex *tex = new TLatex(2700,setlogy?80:55,Form("Incl: %2.1f mbarn for %d cnts", CSincl, (int)tot78Ni));
  tex->SetTextFont(132);
  tex->SetTextSize(0.04);
  tex->SetLineWidth(2);
  tex->Draw();
  */
  for(int i =0; i<6; i++){
  if(gopt[i]==1){
    TLatex *tex = new TLatex(labelx[i],labely[i],
			     //Form("#splitline{%d keV }{%2.2f mbarn (%3.1f cnts)}",energy[i], genevts*whole->GetParameter(i)*CSincl/tot78Ni, genevts*whole->GetParameter(i)));
			     Form("%d keV",energy[i]));
    tex->SetTextFont(132);
    tex->SetTextSize(0.05);
    tex->SetLineWidth(2);
    tex->Draw();
    }
  }
    
  fCanvas->Print(Form("%s.C",outname));
  fCanvas->Print(Form("%s.png",outname));
  fCanvas->Print(Form("%s.pdf",outname));
  
  fCanvas->Write();
  hexp[0]->Write();
  fout->Write();
  fout->Close();

}
Ejemplo n.º 29
0
void compareGen(std::string mcfile1, std::string mcfile2, 
		std::string var1, std::string var2="",
		std::string xtitle, 
		std::string output="test",
		std::string header="Z(#rightarrow ee)+#geq 1 jet",
		std::string mcName1="Data",
		std::string mcName2="Madgraph",
		float xmin=-9999.0, float xmax=-9999.0,
		bool logScale=true
		)
{
  
  setTDRStyle();
  gStyle->SetOptStat(0);

  TH1F* h1;
  TH1F* h2;

  char tempName[300];
  if(var2 ==  "" )var2=var1;
  
  // first get the histogram files
  TFile *fmc1 = TFile::Open(mcfile1.data());
  TFile *fmc2   = TFile::Open(mcfile2.data());

  h1  = (TH1F*)(fmc1->Get(var1.data()));
  h2    = (TH1F*)(fmc2->Get(var2.data()));

  TH1D* hscale =(TH1D*) h1->Clone("hscale");
  hscale->SetYTitle(Form("%s/%s",mcName1.data(),mcName2.data()));

  h1->GetXaxis()->SetNdivisions(5);
  h1->GetYaxis()->SetDecimals();

  h2->GetXaxis()->SetNdivisions(5);
  h2->GetYaxis()->SetDecimals();

  hscale->GetXaxis()->SetNdivisions(5);
  hscale->GetYaxis()->SetDecimals();


  h1->SetLineColor(2);
  h1->SetMarkerColor(2);
  h1->SetMarkerSize(1);
  h1->SetMarkerStyle(24);


  h2->SetLineColor(4);
  h2->SetMarkerColor(4);
  h2->SetMarkerSize(1);
  h2->SetMarkerStyle(21);

  // if normalizing to the same area, set the scale 

  int binLo = -1;
  int binHi = -1;
  int nbins = h1->GetNbinsX();
  if(xmin>-9999.0 && xmax>-9999.0)
    {

      binLo = h1->FindBin(xmin);
      binHi = h1->FindBin(xmax)-1;

    }

  else
    {
      binLo = 1;
      binHi = nbins;
      xmin = h1->GetBinLowEdge(1);
      xmax = h1->GetBinLowEdge(nbins+1);
    }


  float scale_mc = (float)h1->Integral(binLo,binHi)/(float)h2->Integral(binLo,binHi);
//   cout << "binLo = " << binLo << ", binHi = " << binHi << endl;
//    cout << "xmin = " << xmin << "xmax = " << xmax << endl;

//   h2->Sumw2();
// //   scale_mc = 1000.0*4.890*3048.0/2.29809910000000000e+07;
//   h2->Scale(scale_mc);

  cout << "h2 integral = " << h2->Integral() << endl;
  cout << "h1 integral = "   << h1->Integral() << endl;;

  // get the ratio
  double chi2 = 0;
  int realbin = 0;
  for(int i=1;i<= nbins;i++){

    double nmc=h2->GetBinContent(i);
    double ndata=h1->GetBinContent(i); 
    double nmcerr=h2->GetBinError(i);
    double ndataerr=h1->GetBinError(i); 
    
    if(nmc<0 || ndata<0)continue;    
    
    if(nmcerr==0 && ndataerr==0)continue;

    if(nmc==0 && ndata==0)continue;

    double chi2ndef = (nmc-ndata)*(nmc-ndata)/
      ( nmcerr*nmcerr+ ndataerr*ndataerr);
    chi2 += chi2ndef;
    realbin++;

    cout << "Bin " << i << " : " << ndata << ", " << nmc;
    cout << " " << chi2ndef << endl;


    // now calculate the ratio
    if(nmc==0 || nmcerr==0 || ndata==0 || ndataerr==0)
      {
	hscale->SetBinContent(i,-9999);
	hscale->SetBinError(i,1e-4);
	continue;
      }

    cout << "Bin " << i << " ratio = " << ndata/nmc << endl;
    hscale->SetBinContent(i,ndata/nmc);
    double err = 0;
    err=
      (ndata/nmc)*sqrt(pow(nmcerr/nmc,2)+pow(ndataerr/ndata,2));
    hscale->SetBinError(i,err);

  }

  for(int i=1;i<=hscale->GetNbinsX();i++)
    cout << i << ": " << hscale->GetBinContent(i) << endl;

  h1->GetXaxis()->SetRangeUser(xmin,xmax);
  h2->GetXaxis()->SetRangeUser(xmin,xmax);
  hscale->GetXaxis()->SetRangeUser(xmin,xmax);


  TCanvas* c1 = new TCanvas("c1","",700,1000);  
  c1->Divide(1,2,0.01,0);
  c1->cd(1);
  if(logScale)
    gPad->SetLogy(1);
  gPad->SetTopMargin(0.01);
  gPad->SetBottomMargin(0);
  gPad->SetRightMargin(0.04);

  
  float max_data  = h1->GetBinError(h1->GetMaximumBin()) + h1->GetMaximum();
  float max_mc    = h2->GetBinError(h2->GetMaximumBin()) + h2->GetMaximum();

  if(max_data > max_mc)
    {
      h1->Draw("e");
      h2->Draw("hesame");
    }
  else
    { h2->Draw("he");
      h1->Draw("esame");
    }


  float x1NDC = 0.725;
  float y1NDC = 0.615;
  float x2NDC = 0.928;
  float y2NDC = 0.951;

  TLegend* leg = new TLegend(x1NDC,y1NDC,x2NDC,y2NDC);
  
  leg->SetHeader(header.data());
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->SetTextSize(0.04);
  leg->SetBorderSize(0);
  leg->AddEntry(h1, mcName1.data());
  leg->AddEntry(h2, mcName2.data());
  leg->Draw("same");



  c1->cd(2);
  gStyle->SetStatW       (0.3);
  gStyle->SetStatH       (0.3);
  gStyle->SetStatX       (0.879447);
  gStyle->SetStatY       (0.939033);
  gStyle->SetStatFontSize(0.05);
  gStyle->SetStatBorderSize(0);
  gPad->SetRightMargin(0.04);
  gPad->SetTopMargin(0);
  gPad->SetBottomMargin(0.2);
  gPad->SetTickx();
  gStyle->SetOptFit(1);
  hscale->SetTitle("");
  hscale->GetXaxis()->SetTitle(xtitle.data());
//   hscale->SetMaximum(3.0);
//   hscale->SetMinimum(0.1);
  hscale->SetMaximum(2.0);
  hscale->SetMinimum(0.5);
  hscale->SetTitleOffset(1.2,"Y");
  hscale->Draw("e1");
  TF1* fline = new TF1("fline","pol1");
  TLine* l2 = new TLine(xmin,1.,xmax,1.);
  l2->SetLineColor(4);
  l2->SetLineStyle(3);
  fline->SetLineWidth(3);
  fline->SetLineColor(6);
  fline->SetNpx(2500);
//   hscale->Fit("fline","","");
  l2->Draw("same");


  string dirName = "compareGen";
  gSystem->mkdir(dirName.data());

  std::string filename;
  std::string psname = dirName + "/" + var1;
  if(output !="test")
    psname = dirName+ "/" + output;
  else
    psname = dirName+ "/" + var1;
  filename = psname + ".eps";
  c1->Print(filename.data());
  filename = psname + ".gif";
  c1->Print(filename.data());
  filename = psname + ".pdf";
  c1->Print(filename.data());
  //   c1->Close();
}
Ejemplo n.º 30
0
Float_t doCoinc(const char *fileIn="coincCERN_0102n.root",TCanvas *cout=NULL,Float_t &rate,Float_t &rateErr){

  // Print settings
  printf("SETTINGS\nAnalyze output from new Analyzer\n");
  printf("Input file = %s\n",fileIn);
  printf("School distance = %f m, angle = %f deg\n",distance,angle);
  printf("School orientation: tel1=%f deg, tel2=%f deg\n",phi1Corr,phi2Corr);
  printf("Max Chi2 = %f\n",maxchisquare);
  printf("Theta Rel Range = %f - %f deg\n",minthetarel,maxthetarel);
  printf("Range for N sattellite in each run = (tel1) %f - %f, (tel2) %f - %f \n",minAvSat[0],maxAvSat[0],minAvSat[1],maxAvSat[1]);
  printf("Min N satellite in a single event = %i\n",satEventThr);

  Int_t adayMin = (yearRange[0]-2014) * 1000 + monthRange[0]*50 + dayRange[0];
  Int_t adayMax = (yearRange[1]-2014) * 1000 + monthRange[1]*50 + dayRange[1];

  Float_t nsigPeak=0;
  Float_t nbackPeak=0;

  angle *= TMath::DegToRad();

  // define some histos
  TH1F *hDeltaTheta = new TH1F("hDeltaTheta","#Delta#theta below the peak (500 ns);#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhi = new TH1F("hDeltaPhi","#Delta#phi below the peak (500 ns);#Delta#phi (#circ)",200,-360,360);
  TH1F *hDeltaThetaBack = new TH1F("hDeltaThetaBack","#Delta#theta out of the peak (> 1000 ns) - normalized;#Delta#theta (#circ)",100,-60,60);
  TH1F *hDeltaPhiBack = new TH1F("hDeltaPhiBack","#Delta#phi out of the peak (> 1000 ns)  - normalized;#Delta#phi (#circ)",200,-360,360);
  TH1F *hThetaRel = new TH1F("hThetaRel","#theta_{rel} below the peak (500 ns);#theta_{rel} (#circ)",100,0,120);
  TH1F *hThetaRelBack = new TH1F("hThetaRelBack","#theta_{rel} out of the peak (> 1000 ns)  - normalized;#theta_{rel} (#circ)",100,0,120);

  TH2F *hAngle = new TH2F("hAngle",";#Delta#theta (#circ);#Delta#phi (#circ}",20,-60,60,20,-360,360);
  TH2F *hAngleBack = new TH2F("hAngleBack",";#Delta#theta (#circ);#Delta#phi (#circ}",20,-60,60,20,-360,360);

  TProfile *hModulation = new  TProfile("hModulation","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulation2 = new  TProfile("hModulation2","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulationAv = new  TProfile("hModulationAv","#theta^{rel} < 10#circ;#phi - #alpha;dist (m)",50,0,360);
  TProfile *hModulationAvCorr = new  TProfile("hModulationAvCorr","#theta^{rel} < 10#circ;#phi - #alpha;diff (ns)",50,0,360);

  TH1F *hnsigpeak = new TH1F("hnsigpeak","",50,0,360);
  TH1F *hnbackpeak = new TH1F("hnbackpeak","",50,0,360);

  TProfile *hSinTheta = new  TProfile("hSinTheta",";#phi - #alpha;sin(#theta)",50,0,360);
  TProfile *hSinTheta2 = new  TProfile("hSinTheta2",";#phi - #alpha;sin(#theta)",50,0,360);

  TH1F *hRunCut[2];
  hRunCut[0] = new TH1F("hRunCut1","Reason for Run Rejection Tel-1;Reason;runs rejected",11,0,11);
  hRunCut[1] = new TH1F("hRunCut2","Reason for Run Rejection Tel-2;Reason;runs rejected",11,0,11);

  for(Int_t i=0;i<2;i++){
    hRunCut[i]->Fill("DateRange",0);
    hRunCut[i]->Fill("LowFractionGT",0);
    hRunCut[i]->Fill("TimeDuration",0);
    hRunCut[i]->Fill("rateGT",0);
    hRunCut[i]->Fill("RunNumber",0);
    hRunCut[i]->Fill("MissingHitFrac",0);
    hRunCut[i]->Fill("DeadStripBot",0);
    hRunCut[i]->Fill("DeadStripMid",0);
    hRunCut[i]->Fill("DeadStripTop",0);
    hRunCut[i]->Fill("NSatellites",0);
    hRunCut[i]->Fill("NoGoodWeather",0);  
  }

  TFile *f = new TFile(fileIn);
  TTree *t = (TTree *) f->Get("tree");
  
  TTree *tel[2];
  tel[0] = (TTree *) f->Get("treeTel1");
  tel[1] = (TTree *) f->Get("treeTel2");

  TTree *telC = (TTree *) f->Get("treeTimeCommon");
  
  // quality info of runs
  const Int_t nyearmax = 5;
  Bool_t runstatus[2][nyearmax][12][31][500]; //#telescope, year-2014, month, day, run
  Float_t effTel[2][nyearmax][12][31][500];
  Int_t nStripDeadBot[2][nyearmax][12][31][500];
  Int_t nStripDeadMid[2][nyearmax][12][31][500];
  Int_t nStripDeadTop[2][nyearmax][12][31][500];

  Float_t nstripDeadB[2]={0,0},nstripDeadM[2]={0,0},nstripDeadT[2]={0,0};

  // sat info
  Float_t NsatAv[2][nyearmax][12][31][500];

  // weather info
  Float_t pressureTel[2][nyearmax][12][31][500];
  Float_t TempInTel[2][nyearmax][12][31][500];
  Float_t TempOutTel[2][nyearmax][12][31][500];
  Float_t timeWeath[2][nyearmax][12][31][500];

  Float_t rateGT;

  Float_t phirelative;
  Float_t phirelative2;
  Float_t phirelativeAv;

  printf("Check Run quality\n");

  if(tel[0] && tel[1]){
    for(Int_t i=0;i < 2;i++){ // loop on telescopes
      printf("Tel-%i\n",i+1);
      for(Int_t j=0;j < tel[i]->GetEntries();j++){ // loop on runs
	tel[i]->GetEvent(j);
	rateGT = tel[i]->GetLeaf("FractionGoodTrack")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue();

	Int_t aday = (tel[i]->GetLeaf("year")->GetValue()-2014) * 1000 + tel[i]->GetLeaf("month")->GetValue()*50 + tel[i]->GetLeaf("day")->GetValue();

        if(i==1) printf("%f %f\n",rateGT , rateMin[i]);

	if(aday < adayMin || aday > adayMax){
	  hRunCut[i]->Fill("DateRange",1); continue;}
	if(tel[i]->GetLeaf("FractionGoodTrack")->GetValue() < fracGT[i]){
	  hRunCut[i]->Fill("LowFractionGT",1); continue;} // cut on fraction of good track
	if(tel[i]->GetLeaf("timeduration")->GetValue()*tel[i]->GetLeaf("rateHitPerRun")->GetValue() < hitevents[i]){
	  hRunCut[i]->Fill("TimeDuration",1); continue;} // cut on the number of event
	if(rateGT < rateMin[i] || rateGT > rateMax[i]){
	  hRunCut[i]->Fill("rateGT",1); continue;} // cut on the rate
	if(tel[i]->GetLeaf("run")->GetValue() > 499){
	  hRunCut[i]->Fill("RunNumber",1); continue;} // run < 500

        if(i==1) printf("GR\n");

	Float_t missinghitfrac = (tel[i]->GetLeaf("ratePerRun")->GetValue()-tel[i]->GetLeaf("rateHitPerRun")->GetValue()-2)/(tel[i]->GetLeaf("ratePerRun")->GetValue()-2);
	if(missinghitfrac < minmissingHitFrac[i] || missinghitfrac > maxmissingHitFrac[i]){
	  hRunCut[i]->Fill("MissingHitFrac",1); continue;}
		
	// active strip maps
	if(tel[i]->GetLeaf("maskB")) nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskB")->GetValue()));
	if(tel[i]->GetLeaf("maskM")) nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskM")->GetValue()));
	if(tel[i]->GetLeaf("maskT")) nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = countBits(Int_t(tel[i]->GetLeaf("maskT")->GetValue()));

	if(nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadBotMax[i] || nStripDeadBot[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadBotMin[i]) {
	  hRunCut[i]->Fill("DeadStripBot",1); continue;}
	if(nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadMidMax[i] || nStripDeadMid[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadMidMin[i]){
	  hRunCut[i]->Fill("DeadStripMid",1); continue;}
	if(nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > ndeadTopMax[i] || nStripDeadTop[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < ndeadTopMin[i]){
	  hRunCut[i]->Fill("DeadStripTop",1); continue;}
     
	// nsat averaged  per run
	if(tel[i]->GetLeaf("nSat")) NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("nSat")->GetValue();


	if(NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < minAvSat[i] || NsatAv[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > maxAvSat[i]){
	 hRunCut[i]->Fill("NSatellites",1); continue;}

	// weather info
	if(tel[i]->GetLeaf("Pressure")) pressureTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("Pressure")->GetValue();
	if(tel[i]->GetLeaf("IndoorTemperature")) TempInTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("IndoorTemperature")->GetValue();
	if(tel[i]->GetLeaf("OutdoorTemperature")) TempOutTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("OutdoorTemperature")->GetValue();
	if(tel[i]->GetLeaf("TimeWeatherUpdate")) timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = tel[i]->GetLeaf("TimeWeatherUpdate")->GetValue();

	if(timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] < minWeathTimeDelay[i] ||  timeWeath[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] > maxWeathTimeDelay[i]){ hRunCut[i]->Fill("NoGoodWeather",1); continue;	}

	// Set good runs
	runstatus[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = kTRUE;
	effTel[i][Int_t(tel[i]->GetLeaf("year")->GetValue())-2014][Int_t(tel[i]->GetLeaf("month")->GetValue())][Int_t(tel[i]->GetLeaf("day")->GetValue())][Int_t(tel[i]->GetLeaf("run")->GetValue())] = 1;//rateGT/refRate[i];

      }
    }
  }
  else{
    telC = NULL;
  }

  printf("Start to process correlations\n");
  Int_t n = t->GetEntries();
  // counter for seconds
  Int_t nsec = 0;
  Int_t nsecGR = 0; // for good runs
  Int_t isec = -1; // used only in case the tree with time info is not available

  Float_t neventsGR = 0;
  Float_t neventsGRandSat = 0;

  if(telC){
    for(Int_t i=0; i < telC->GetEntries();i++){
      telC->GetEvent(i);
      nsec += telC->GetLeaf("timeduration")->GetValue(); 
      
      
      
      if(telC->GetLeaf("run")->GetValue() > 499 || telC->GetLeaf("run2")->GetValue() > 499) continue;
      
      if(!runstatus[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())]) continue;
      
      if(!runstatus[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run2")->GetValue())]) continue;
      
      nsecGR += telC->GetLeaf("timeduration")->GetValue(); 
      nstripDeadB[0] += countBits(nStripDeadBot[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadM[0] += countBits(nStripDeadMid[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadT[0] += countBits(nStripDeadTop[0][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();

      nstripDeadB[1] += countBits(nStripDeadBot[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadM[1] += countBits(nStripDeadMid[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
      nstripDeadT[1] += countBits(nStripDeadTop[1][Int_t(telC->GetLeaf("year")->GetValue())-2014][Int_t(telC->GetLeaf("month")->GetValue())][Int_t(telC->GetLeaf("day")->GetValue())][Int_t(telC->GetLeaf("run")->GetValue())])*telC->GetLeaf("timeduration")->GetValue();
    }
    nstripDeadB[0] /= nsecGR;
    nstripDeadM[0] /= nsecGR;
    nstripDeadT[0] /= nsecGR;

    nstripDeadB[1] /= nsecGR;
    nstripDeadM[1] /= nsecGR;
    nstripDeadT[1] /= nsecGR;

    printf("Dead channel tel1 = %f - %f - %f\n",nstripDeadB[0],nstripDeadM[0],nstripDeadT[0]);
    printf("Dead channel tel2 = %f - %f - %f\n",nstripDeadB[1],nstripDeadM[1],nstripDeadT[1]);
  }
  
  char title[300];
  TH1F *h;
  
  sprintf(title,"correction assuming #Delta#phi = %4.2f, #DeltaL = %.1f m;#Deltat (ns);entries",angle,distance);
  
  h = new TH1F("hCoinc",title,nbint,tmin,tmax);
  
  Float_t DeltaT;
  Float_t phiAv,thetaAv,corr;
  
  Float_t Theta1,Theta2;
  Float_t Phi1,Phi2;
  Int_t nsatel1cur,nsatel2cur,ntrack1,ntrack2;

  Float_t v1[3],v2[3],vSP; // variable to recompute ThetaRel on the fly
  Float_t eff = 1; 
  
  for(Int_t i=0;i<n;i++){
    t->GetEvent(i);
    
    if(t->GetLeaf("RunNumber1") && (t->GetLeaf("RunNumber1")->GetValue() > 499 || t->GetLeaf("RunNumber2")->GetValue() > 499)) continue;
  
    if(tel[0] && !runstatus[0][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())]) continue;
    
    if(tel[1] && !runstatus[1][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())]) continue;


    eff = effTel[0][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber1")->GetValue())];
    eff *= effTel[1][Int_t(t->GetLeaf("year")->GetValue())-2014][Int_t(t->GetLeaf("month")->GetValue())][Int_t(t->GetLeaf("day")->GetValue())][Int_t(t->GetLeaf("RunNumber2")->GetValue())];
    
    Int_t timec = t->GetLeaf("ctime1")->GetValue();
    
    if(! telC){
      if(isec == -1) isec = timec;
      
      if(timec != isec){
	if(timec - isec < 20){
	  //	printf("diff = %i\n",timec-isec);
	  nsec +=(timec - isec);
	  nsecGR +=(timec - isec);
	}
	isec = timec;
    }
    }

    Float_t thetarel = t->GetLeaf("ThetaRel")->GetValue();
    Theta1 = (t->GetLeaf("Theta1")->GetValue())*TMath::DegToRad();
    Theta2 = t->GetLeaf("Theta2")->GetValue()*TMath::DegToRad();
    Phi1 = t->GetLeaf("Phi1")->GetValue()*TMath::DegToRad();
    Phi2 = t->GetLeaf("Phi2")->GetValue()*TMath::DegToRad();
    
    nsatel1cur = t->GetLeaf("Nsatellite1")->GetValue();
    nsatel2cur = t->GetLeaf("Nsatellite2")->GetValue();
    ntrack1 = t->GetLeaf("Ntracks1")->GetValue();
    ntrack2 = t->GetLeaf("Ntracks2")->GetValue();

    if(recomputeThetaRel){ // recompute ThetaRel applying corrections
      Phi1 += phi1Corr*TMath::DegToRad();
      Phi2 += phi2Corr*TMath::DegToRad();
      if(Phi1 > 2*TMath::Pi()) Phi1 -= 2*TMath::Pi();
      if(Phi1 < 0) Phi1 += 2*TMath::Pi();
      if(Phi2 > 2*TMath::Pi()) Phi2 -= 2*TMath::Pi();
      if(Phi2 < 0) Phi2 += 2*TMath::Pi();
      
      v1[0] = TMath::Sin(Theta1)*TMath::Cos(Phi1);
      v1[1] = TMath::Sin(Theta1)*TMath::Sin(Phi1);
      v1[2] = TMath::Cos(Theta1);
      v2[0] = TMath::Sin(Theta2)*TMath::Cos(Phi2);
      v2[1] = TMath::Sin(Theta2)*TMath::Sin(Phi2);
      v2[2] = TMath::Cos(Theta2);
      
      v1[0] *= v2[0];
      v1[1] *= v2[1];
      v1[2] *= v2[2];
      
      vSP = v1[0] + v1[1] + v1[2];
      
      thetarel = TMath::ACos(vSP)*TMath::RadToDeg();
    }
    
    // cuts
    if(thetarel < minthetarel) continue;
    if(thetarel > maxthetarel) continue;
    if(t->GetLeaf("ChiSquare1")->GetValue() > maxchisquare) continue;
    if(t->GetLeaf("ChiSquare2")->GetValue() > maxchisquare) continue;
    

    neventsGR++;

    // reject events with not enough satellites
    if(nsatel1cur < satEventThr || nsatel1cur < satEventThr) continue;

    neventsGRandSat++;
    
    DeltaT = t->GetLeaf("DiffTime")->GetValue();
    
    // get primary direction
    if(TMath::Abs(Phi1-Phi2) < TMath::Pi()) phiAv = (Phi1+Phi2)*0.5;
    else phiAv = (Phi1+Phi2)*0.5 + TMath::Pi();

    thetaAv = (Theta1+Theta2)*0.5;
    
    // extra cuts if needed
    //    if(TMath::Cos(Phi1-Phi2) < 0.) continue;
    
    Float_t resFactor = 1;
    if(thetarel > 10 ) resFactor *= 0.5;
    if(thetarel > 20 ) resFactor *= 0.5;
    if(thetarel > 30 ) resFactor *= 0.5;

    corr = distance * TMath::Sin(thetaAv)*TMath::Cos(phiAv-angle)/2.99792458000000039e-01 + deltatCorr;

    phirelative = (Phi1-angle)*TMath::RadToDeg();
    if(phirelative < 0) phirelative += 360;
    if(phirelative < 0) phirelative += 360;
    if(phirelative > 360) phirelative -= 360;
    if(phirelative > 360) phirelative -= 360;

    phirelative2 = (Phi2-angle)*TMath::RadToDeg();
    if(phirelative2 < 0) phirelative2 += 360;
    if(phirelative2 < 0) phirelative2 += 360;
    if(phirelative2 > 360) phirelative2 -= 360;
    if(phirelative2 > 360) phirelative2 -= 360;

    phirelativeAv = (phiAv-angle)*TMath::RadToDeg();
    if(phirelativeAv < 0) phirelativeAv += 360;
    if(phirelativeAv < 0) phirelativeAv += 360;
    if(phirelativeAv > 360) phirelativeAv -= 360;
    if(phirelativeAv > 360) phirelativeAv -= 360;


    // if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment){
      
    // }

    if(thetarel < 10){//cos(thetarel*TMath::DegToRad())>0.98 && sin(thetaAv)>0.1){
      if(TMath::Abs(DeltaT- corr) < windowAlignment)
	hModulationAvCorr->Fill(phirelativeAv,DeltaT-corr);
      if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment){
	hModulation->Fill(phirelative,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hModulation2->Fill(phirelative2,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hModulationAv->Fill(phirelativeAv,(DeltaT-deltatCorr)/sin(thetaAv)*2.99792458000000039e-01);
	hSinTheta->Fill(phirelative,sin(thetaAv));
	hSinTheta2->Fill(phirelative2,sin(thetaAv));
	nsigPeak++;
	hnsigpeak->Fill(phirelativeAv);
      }
      else if(TMath::Abs(DeltaT- deltatCorr) < windowAlignment*10){
	nbackPeak++;
	hnbackpeak->Fill(phirelativeAv);
      }
    }

    h->Fill(DeltaT-corr,1./eff);
    if(TMath::Abs(DeltaT-corr) < windowAlignment){
      hDeltaTheta->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhi->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRel->Fill(thetarel);
      hAngle->Fill((Theta1-Theta2)*TMath::RadToDeg(),(Phi1-Phi2)*TMath::RadToDeg());
    }
    else if(TMath::Abs(DeltaT-corr) > windowAlignment*2 && TMath::Abs(DeltaT-corr) < windowAlignment*12){
      hDeltaThetaBack->Fill((Theta1-Theta2)*TMath::RadToDeg());
      hDeltaPhiBack->Fill((Phi1-Phi2)*TMath::RadToDeg());
      hThetaRelBack->Fill(thetarel);
      hAngleBack->Fill((Theta1-Theta2)*TMath::RadToDeg(),(Phi1-Phi2)*TMath::RadToDeg());
    }
  }
  
  // compute (S+B)/S
  for(Int_t i=1;i<=50;i++){
    Float_t corrfactorPeak = 1;
    if(nsigPeak-nbackPeak*0.1 > 0)
      corrfactorPeak = hnsigpeak->GetBinContent(i)/(hnsigpeak->GetBinContent(i)-hnbackpeak->GetBinContent(i)*0.1);
    else
      printf("bin %i) not enough statistics\n",i);
    hnsigpeak->SetBinContent(i,corrfactorPeak);
  }

  TF1 *fpol0 = new TF1("fpol0","pol0");
  hnsigpeak->Fit(fpol0);

  hModulation->Scale(fpol0->GetParameter(0));
  hModulation2->Scale(fpol0->GetParameter(0));
  hModulationAv->Scale(fpol0->GetParameter(0));
  hModulationAvCorr->Scale(fpol0->GetParameter(0));
  
  TF1 *fmod = new TF1("fmod","[0] + [1]*cos((x-[2])*TMath::DegToRad())"); 
  hModulationAv->Fit(fmod); 

  printf("Estimates from time delay: Distance = %f +/- %f m -- Angle = %f +/- %f deg\n",fmod->GetParameter(1),fmod->GetParError(1),fmod->GetParameter(2),fmod->GetParError(2));

  h->SetStats(0);

  hDeltaThetaBack->Sumw2();
  hDeltaPhiBack->Sumw2();
  hThetaRelBack->Sumw2();
  hDeltaThetaBack->Scale(0.1);
  hDeltaPhiBack->Scale(0.1);
  hThetaRelBack->Scale(0.1);
  hAngleBack->Scale(0.1);
  hAngle->Add(hAngleBack,-1);

  printf("bin counting: SIGNAL = %f +/- %f\n",hDeltaPhi->Integral()-hDeltaPhiBack->Integral(),sqrt(hDeltaPhi->Integral()));
  rate = (hDeltaPhi->Integral()-hDeltaPhiBack->Integral())/nsecGR*86400;
  rateErr = sqrt(hDeltaPhi->Integral())/nsecGR*86400;


  Float_t val,eval;
  TCanvas *c1=new TCanvas();
  TF1 *ff = new TF1("ff","[0]*[4]/[2]/sqrt(2*TMath::Pi())*TMath::Exp(-(x-[1])*(x-[1])*0.5/[2]/[2]) + [3]*[4]/6/[2]");
  ff->SetParName(0,"signal");
  ff->SetParName(1,"mean");
  ff->SetParName(2,"sigma");
  ff->SetParName(3,"background");
  ff->SetParName(4,"bin width");
  ff->SetParameter(0,42369);
  ff->SetParameter(1,0);
  ff->SetParLimits(2,10,maxwidth);
  ff->SetParameter(2,350); // fix witdh if needed
  ff->SetParameter(3,319);
  ff->FixParameter(4,(tmax-tmin)/nbint); // bin width

  ff->SetNpx(1000);
  
  if(cout) cout->cd();
  h->Fit(ff,"EI","",-10000,10000);
  
  val = ff->GetParameter(2);
  eval = ff->GetParError(2);
  
  printf("significance = %f\n",ff->GetParameter(0)/sqrt(ff->GetParameter(0) + ff->GetParameter(3)));

  h->Draw();
  
  new TCanvas;

  TF1 *func1 = (TF1 *)  h->GetListOfFunctions()->At(0);
  
  func1->SetLineColor(2);
  h->SetLineColor(4);
  
  TPaveText *text = new TPaveText(1500,(h->GetMinimum()+(h->GetMaximum()-h->GetMinimum())*0.6),9500,h->GetMaximum());
  text->SetFillColor(0);
  sprintf(title,"width = %5.1f #pm %5.1f",func1->GetParameter(2),func1->GetParError(2));
  text->AddText(title);
  sprintf(title,"signal (S) = %5.1f #pm %5.1f",func1->GetParameter(0),func1->GetParError(0));
  text->AddText(title);
  sprintf(title,"background (B) (3#sigma) = %5.1f #pm %5.1f",func1->GetParameter(3),func1->GetParError(3));
  text->AddText(title);
  sprintf(title,"significance (S/#sqrt{S+B}) = %5.1f",func1->GetParameter(0)/sqrt(func1->GetParameter(0)+func1->GetParameter(3)));
  text->AddText(title);
  
  text->SetFillStyle(0);
  text->SetBorderSize(0);
  
  text->Draw("SAME");
  
  // correct nsecGR for the event rejected because of the number of satellites (event by event cut)
  nsecGR *= neventsGRandSat/neventsGR;

  printf("n_day = %f\nn_dayGR = %f\n",nsec*1./86400,nsecGR*1./86400);

  text->AddText(Form("rate = %f #pm %f per day",func1->GetParameter(0)*86400/nsecGR,func1->GetParError(0)*86400/nsecGR));

  TFile *fo = new TFile("outputCERN-01-02.root","RECREATE");
  h->Write();
  hDeltaTheta->Write();
  hDeltaPhi->Write();
  hThetaRel->Write();
  hDeltaThetaBack->Write();
  hDeltaPhiBack->Write();
  hThetaRelBack->Write();
  hAngle->Write();
  hModulation->Write();
  hModulation2->Write();
  hModulationAv->Write();
  hModulationAvCorr->Write();
  hSinTheta->Write();
  hSinTheta2->Write();
  hnsigpeak->Write();
  hRunCut[0]->Write();
  hRunCut[1]->Write();
  fo->Close();

  return nsecGR*1./86400;
  
}