예제 #1
0
void reweight_eta_1d(TH1F* weight_eta,TH1F* weight_etao,TH2F*weight_etan,TH2F* weight_eta2o,TH2F* weight_etanr,TH2F*weight_eta2,RooDataSet **dset, RooDataSet *dsetdestination, int numvar){

  if (!(*dset)) return;

  TH1F *hnum = new TH1F("hnum","hnum",n_etabins_forreweighting,etabins_forreweighting);
 TH1F *hden = new TH1F("hden","hden",n_etabins_forreweighting,etabins_forreweighting);
//  TH1F *hnum = new TH1F("hnum","hnum",25,0.,2.5);
//  TH1F *hden = new TH1F("hden","hden",25,0.,2.5);
  hnum->Sumw2();
  hden->Sumw2();

  const char* etaname=Form("rooeta%d",numvar);

  for (int i=0; i<(*dset)->numEntries(); i++){
    hden->Fill(fabs((*dset)->get(i)->getRealValue(etaname)),(*dset)->store()->weight(i));
  }
  for (int i=0; i<dsetdestination->numEntries(); i++){
    hnum->Fill(fabs(dsetdestination->get(i)->getRealValue(etaname)),dsetdestination->store()->weight(i));
  }
  hnum->Scale(1.0/hnum->Integral());
  hden->Scale(1.0/hden->Integral());

  hnum->Divide(hden);
  TH1F *h = hnum;

  RooDataSet *newdset = new RooDataSet(**dset,Form("%s_etarew",(*dset)->GetName()));
  newdset->reset();
  for (int i=0; i<(*dset)->numEntries(); i++){
    RooArgSet args = *((*dset)->get(i));
    float oldw = (*dset)->store()->weight(i);
    float eta = args.getRealValue(etaname);
    float neww = oldw*h->GetBinContent(h->FindBin(fabs(eta)));
    if(debug){ 
		weight_eta->Fill(neww);	
		weight_etao->Fill(oldw);
		weight_etan->Fill(h->FindBin(fabs(eta)),neww);	
		weight_eta2o->Fill(h->FindBin(fabs(eta)),oldw);
		if(oldw!=0 && neww!=0)weight_etanr->Fill(h->FindBin(fabs(eta)),oldw/neww);
		else {weight_etanr->Fill(-10,1);}
	   // weight_pt2->Fill(pt,neww/oldw);
	   if(oldw!=0 && neww!=0)weight_eta2->Fill(fabs(eta),oldw/neww);
	   else {weight_eta2->Fill(-10,1);}
	}  
	  newdset->add(args,neww);
	  
	  }


  newdset->SetName((*dset)->GetName());
  newdset->SetTitle((*dset)->GetTitle());
  delete hnum; delete hden;

  RooDataSet *old_dset = *dset;
  *dset=newdset;
  std::cout << "Eta 1d rew: norm from " << old_dset->sumEntries() << " to " << newdset->sumEntries() << std::endl;

  delete old_dset;

};
void makeDataset( TString fname, TString tname, TString outfname ) {

  RooWorkspace *w = new RooWorkspace("w","w");

  w->factory( "Dst_M[1950.,2070.]" );
  w->factory( "D0_M[1810.,1920.]" );
  w->factory( "D0_LTIME_ps[0.00,5.]" );

  RooArgSet *observables = new RooArgSet();
  observables->add( *w->var("Dst_M") );
  observables->add( *w->var("D0_M") );
  observables->add( *w->var("D0_LTIME_ps") );
  w->defineSet("observables", *observables);

  w->var("Dst_M")->setBins(240);
  w->var("D0_M")->setBins(220);
  w->var("D0_LTIME_ps")->setBins(200);

  double Dst_M = -999.;
  double D0_M = -999.;
  double D0_LTIME_ps = -999.;

  TFile *tf = TFile::Open(fname);
  TTree *tree = (TTree*)tf->Get(tname);

  tree->SetBranchAddress( "Dst_M", &Dst_M );
  tree->SetBranchAddress( "D0_M" , &D0_M );
  tree->SetBranchAddress( "D0_LTIME_ps", &D0_LTIME_ps );

  RooDataSet *data = new RooDataSet("Data","Data",*observables);
  RooDataHist *dataH = new RooDataHist("DataHist","Data",*observables);

  for ( int ev=0; ev<tree->GetEntries(); ev++) {

    tree->GetEntry(ev);

    if ( ev%10000 == 0 ) cout << ev << " / " << tree->GetEntries() << endl;

    if ( Dst_M < w->var("Dst_M")->getMin() || Dst_M > w->var("Dst_M")->getMax() ) continue;
    if ( D0_M < w->var("D0_M")->getMin() || D0_M > w->var("D0_M")->getMax() ) continue;
    if ( D0_LTIME_ps < w->var("D0_LTIME_ps")->getMin() || D0_LTIME_ps > w->var("D0_LTIME_ps")->getMax() ) continue;

    w->var("Dst_M")->setVal(Dst_M);
    w->var("D0_M")->setVal(D0_M);
    w->var("D0_LTIME_ps")->setVal(D0_LTIME_ps);

    data->add( *observables );
    dataH->add( *observables );

  }
  tf->Close();

  w->import(*data);
  w->import(*dataH);

  w->writeToFile(outfname);

}
예제 #3
0
void reweight_diphotonpt_1d(TH1F*weight_diphopt,TH1F*weight_diphopto,TH2F*weight_diphoptn,TH2F*weight_diphopt2o,TH2F*weight_diphoptnr, TH2F* weight_diphopt2,RooDataSet **dset, RooDataSet *dsetdestination){

  if (!(*dset)) return;
  if (!(dsetdestination)) return;
///numerator and denominator
  TH1F *hnum = new TH1F("hnum","hnum",n_diphoptbins_forreweighting,diphoptbins_forreweighting);
  TH1F *hden = new TH1F("hden","hden",n_diphoptbins_forreweighting,diphoptbins_forreweighting);
  hnum->Sumw2();
  hden->Sumw2();

     
// RooAbsData->get*() Load a given row of data

 //getRealValue Get value of a RooAbsReal stored in set with given name. If none is found, value of defVal is returned.
 for (int i=0; i<(*dset)->numEntries(); i++){
      hden->Fill(fabs((*dset)->get(i)->getRealValue("roodiphopt")),(*dset)->store()->weight(i));
  }
  for (int i=0; i<dsetdestination->numEntries(); i++){
    hnum->Fill(fabs(dsetdestination->get(i)->getRealValue("roodiphopt")),dsetdestination->store()->weight(i));
  }
 //normalize to one 
  hnum->Scale(1.0/hnum->Integral());
  hden->Scale(1.0/hden->Integral());
  hnum->Divide(hden);
  TH1F *h = hnum;
  RooDataSet *newdset = new RooDataSet(**dset,Form("%s_diphoptrew",(*dset)->GetName()));
  newdset->reset();
  assert(newdset);
  for (int i=0; i<(*dset)->numEntries(); i++){
    RooArgSet args = *((*dset)->get(i));
    float oldw = (*dset)->store()->weight(i);
    float diphopt = fabs((*dset)->get(i)->getRealValue("roodiphopt"));
    float neww = oldw*h->GetBinContent(h->FindBin(fabs(diphopt)));
    newdset->add(args,neww);
    if(debug){
		weight_diphopt->Fill(neww);
		weight_diphopto->Fill(oldw);
		weight_diphopt2o->Fill((h->FindBin(fabs(diphopt))),oldw);	
		weight_diphoptn->Fill((h->FindBin(fabs(diphopt))),neww);	
		if(oldw!=0)weight_diphoptnr->Fill(h->FindBin(fabs(diphopt)),oldw/neww);
		else {weight_diphoptnr->Fill(-10,1);}//cout << "dipho weight old 0" << endl;}
		if(oldw!=0)weight_diphopt2->Fill(diphopt,oldw/neww);
		else {weight_diphopt2->Fill(-10,1);}//cout << "dipho weight old 0" << endl;}
	 }
		}

  newdset->SetName((*dset)->GetName());
  newdset->SetTitle((*dset)->GetTitle());
  delete hnum; delete hden;
 
  RooDataSet *old_dset = *dset;
  *dset=newdset;
  std::cout << "Diphoton Pt 1d rew: norm from " << old_dset->sumEntries() << " to " << newdset->sumEntries() << std::endl;

  delete old_dset;

};
예제 #4
0
//2d reweighting of rho and its sigma
void reweight_rhosigma(TH1F* weight_rho, TH1F* weight_rhoo,TH2F*weight_rhon,TH2F*weight_rho2o,TH2F* weight_rhonr, TH2F* weight_rho2,TH2F*weight_sigman,TH2F*weight_sigma2o,TH2F* weight_sigmanr, TH2F* weight_sigma2,RooDataSet **dset, RooDataSet *dsetdestination, bool deleteold){
  if (!(*dset)) return;
//  TH2F *hnum = new TH2F("hnum","hnum",n_rhobins_forreweighting,rhobins_forreweighting,n_sigmabins_forreweighting,sigmabins_forreweighting);
//  TH2F *hden = new TH2F("hden","hden",n_rhobins_forreweighting,rhobins_forreweighting,n_sigmabins_forreweighting,sigmabins_forreweighting);
  TH2F *hnum = new TH2F("hnum","hnum",100,0,100,20,0,20);
  TH2F *hden = new TH2F("hden","hden",100,0,100,20,0,20);
  hnum->Sumw2();
  hden->Sumw2();
  for (int i=0; i<(*dset)->numEntries(); i++){
    hden->Fill(fabs((*dset)->get(i)->getRealValue("roorho")),fabs((*dset)->get(i)->getRealValue("roosigma")),(*dset)->store()->weight(i));
  }
  for (int i=0; i<dsetdestination->numEntries(); i++){
    hnum->Fill(fabs(dsetdestination->get(i)->getRealValue("roorho")),fabs(dsetdestination->get(i)->getRealValue("roosigma")),dsetdestination->store()->weight(i));
  }

  hnum->Scale(1.0/hnum->Integral());
  hden->Scale(1.0/hden->Integral());
//data/MC
  hnum->Divide(hden);
  TH2F *h = hnum;

  RooDataSet *newdset = new RooDataSet(**dset,Form("%s_rhosigmarew",(*dset)->GetName()));
  newdset->reset();
  for (int i=0; i<(*dset)->numEntries(); i++){
    RooArgSet args = *((*dset)->get(i));
    float oldw = (*dset)->store()->weight(i);
    float rho = args.getRealValue("roorho");
    float sigma = args.getRealValue("roosigma");
    float neww = oldw*h->GetBinContent(h->FindBin(rho,sigma));
	if(debug){
		weight_rho->Fill(neww);
		weight_rhoo->Fill(oldw);
		weight_rho2o->Fill(h->GetXaxis()->FindBin(rho),oldw);	
		weight_rhon->Fill(h->GetXaxis()->FindBin(rho),neww);	
		if(oldw!=0)weight_rhonr->Fill(h->GetXaxis()->FindBin(rho),oldw/neww);
		else {weight_rhonr->Fill(-10,1);}//cout << "dipho weight old 0" << endl;}
		if(oldw!=0)weight_rho2->Fill(rho,oldw/neww);
		weight_sigma2o->Fill(h->GetYaxis()->FindBin(sigma),oldw);	
		weight_sigman->Fill(h->GetYaxis()->FindBin(sigma),neww);	
		if(oldw!=0)weight_sigmanr->Fill(h->GetYaxis()->FindBin(sigma),oldw/neww);
		else {weight_sigmanr->Fill(-10,1);}//cout << "dipho weight old 0" << endl;}
		if(oldw!=0)weight_sigma2->Fill(sigma,oldw/neww);
	}
		newdset->add(args,neww);
	  }
	  newdset->SetName((*dset)->GetName());
	  newdset->SetTitle((*dset)->GetTitle());
	  delete hnum; delete hden;
	  RooDataSet *old_dset = *dset;
	  *dset=newdset;
	  std::cout << "RhoSigma2D rew: norm from " << old_dset->sumEntries() << " to " << newdset->sumEntries() << std::endl;
	  if (deleteold) delete old_dset;
	};
예제 #5
0
파일: RA4abcd.C 프로젝트: wa01/usercode
//
// single measurement (LM0 or LM1)
//
void RA4Single (StatMethod method, double* sig, double* bkg) {

  // RooWorkspace* wspace = createWorkspace();
  RA4WorkSpace ra4WSpace("wspace",true,true,true);
  ra4WSpace.addChannel(RA4WorkSpace::MuChannel);
  ra4WSpace.finalize();

  double lm0_mc[4] = { 1.09, 7.68, 3.78, 21.13 };
  double lm1_mc[4] = { 0.05 , 0.34 , 1.12 , 3.43 };
  double* lm_mc = sig ? sig : lm0_mc;

  double bkg_mc[4] = {  14.73, 18.20, 8.48, 10.98 };

  ra4WSpace.setBackground(RA4WorkSpace::MuChannel,bkg_mc[0],bkg_mc[1],bkg_mc[2],bkg_mc[3]);
  ra4WSpace.setSignal(RA4WorkSpace::MuChannel,lm_mc[0],lm_mc[1],lm_mc[2],lm_mc[3],1.,1.,1.,1.);
  
  // setBackgrounds(wspace,bkg);
  // setSignal(wspace,lm_mc);

  RooWorkspace* wspace = ra4WSpace.workspace();
  // wspace->Print("v");
  // RooArgSet allVars = wspace->allVars();
  // // allVars.printLatex(std::cout,1);
  // TIterator* it = allVars.createIterator();
  // RooRealVar* var;
  // while ( var=(RooRealVar*)it->Next() ) {
  //   var->Print("v");
  //   var->printValue(std::cout);
  // }

  ////////////////////////////////////////////////////////////
  // Generate toy data
  // generate toy data assuming current value of the parameters
  // import into workspace. 
  // add Verbose() to see how it's being generated
  // wspace->var("s")->setVal(0.);
  // RooDataSet* data =   wspace->pdf("model")->generate(*wspace->set("obs"),1);
  // data->Print("v");
  // // wspace->import(*data);
  // wspace->var("s")->setVal(lm_mc[3]);
  RooDataSet* data = new RooDataSet("data","data",*wspace->set("obs"));
  data->add(*wspace->set("obs"));
  data->Print("v");

  MyLimit limit = computeLimit(wspace,data,method,true);
  std::cout << "Limit [ " << limit.lowerLimit << " , "
	    << limit.upperLimit << " ] ; isIn = " << limit.isInInterval << std::endl;
}
예제 #6
0
RooDataSet *th22dataset(TH2F *hist){
  RooRealVar *v1 = new RooRealVar("constTerm","",0.01,0,0.02);
  RooRealVar *v2 = new RooRealVar("alpha","",0.0,0,0.2);
  RooRealVar *nll = new RooRealVar("nll",0,0,1e20);
  RooArgSet argSet(*v1,*v2, *nll);
  RooDataSet *dataset = new RooDataSet(TString(hist->GetName())+"_dataset", "", argSet,"nll");
  
  for(Int_t iBinX=1; iBinX <= hist->GetNbinsX(); iBinX++){
    for(Int_t iBinY=1; iBinY <= hist->GetNbinsY(); iBinY++){
      Double_t binContent=hist->GetBinContent(iBinX, iBinY);
      if(binContent!=0){
	v1->setVal(hist->GetXaxis()->GetBinCenter(iBinX));
	v2->setVal(hist->GetYaxis()->GetBinCenter(iBinY));
	nll->setVal(binContent);
	dataset->add(argSet);
      }
    }
  }
  return dataset;
}
예제 #7
0
RooDataSet* makeFakeDataXY()
{
   RooRealVar x("x","x",-10,10) ;
   RooRealVar y("y","y",-10,10) ;
   RooArgSet coord(x,y) ;

   RooDataSet* d = new RooDataSet("d","d",RooArgSet(x,y)) ;

   for (int i=0 ; i<10000 ; i++) {
      Double_t tmpy = gRandom->Gaus(0,10) ;
      Double_t tmpx = gRandom->Gaus(0.5*tmpy,1) ;
      if (fabs(tmpy)<10 && fabs(tmpx)<10) {
      x = tmpx ;
      y = tmpy ;
      d->add(coord) ;
      }

   }

   return d ;
}
예제 #8
0
    void ztonunu1() {

    // RooMsgService::instance().addStream(DEBUG,Topic(Tracing),ClassName("RooPoisson"),OutputFile("debug.log")) ;

       float acc_mm_mean( 0.98 ) ; float acc_mm_err(  0.02 ) ;
       float acc_ee_mean( 0.98 ) ; float acc_ee_err(  0.02 ) ;
       float eff_mm_mean( 0.77 ) ; float eff_mm_err(  0.08 ) ;
       float eff_ee_mean( 0.76 ) ; float eff_ee_err(  0.08 ) ;


       RooRealVar* rv_Nsbee  = new RooRealVar( "Nsbee"  ,"Nsbee"  , 0., 100. ) ;
       RooRealVar* rv_Nsbmm  = new RooRealVar( "Nsbmm"  ,"Nsbmm"  , 0., 100. ) ;
       RooRealVar* rv_Nsigee = new RooRealVar( "Nsigee" ,"Nsigee" , 0., 100. ) ;
       RooRealVar* rv_Nsigmm = new RooRealVar( "Nsigmm" ,"Nsigmm" , 0., 100. ) ;

       rv_Nsbee->setVal( 5 ) ;
       rv_Nsbmm->setVal( 3 ) ;

       rv_Nsigee->setVal( 4 ) ;
       rv_Nsigmm->setVal( 3 ) ;


       RooRealVar* rv_mu_Znnsb  = new RooRealVar( "mu_Znnsb"  , "mu_Znnsb"  , 0., 100. ) ;
       RooRealVar* rv_mu_Znnsig = new RooRealVar( "mu_Znnsig" , "mu_Znnsig" , 0., 100. ) ;


       rv_mu_Znnsb->setVal( 37 ) ; // starting value
       rv_mu_Znnsig->setVal( 17. ) ; // starting value

       RooRealVar* rv_bfRatio = new RooRealVar( "bfRatio", "bfRatio", 0., 10. ) ;

       rv_bfRatio->setVal( 5.95 ) ;
       rv_bfRatio->setConstant( kTRUE ) ;

       RooRealVar* rv_acc_mm = new RooRealVar( "acc_mm", "acc_mm", 0.001, 1.000 ) ;
       RooRealVar* rv_acc_ee = new RooRealVar( "acc_ee", "acc_ee", 0.001, 1.000 ) ;

       RooRealVar* rv_eff_mm = new RooRealVar( "eff_mm", "eff_mm", 0.001, 1.000 ) ;
       RooRealVar* rv_eff_ee = new RooRealVar( "eff_ee", "eff_ee", 0.001, 1.000 ) ;

       rv_acc_mm->setVal( acc_mm_mean ) ;
       rv_acc_ee->setVal( acc_ee_mean ) ;
       rv_eff_mm->setVal( eff_mm_mean ) ;
       rv_eff_ee->setVal( eff_ee_mean ) ;

       RooRealVar* rv_lumi_ratio = new RooRealVar( "lumi_ratio", "lumi_ratio", 0., 10. ) ;

       rv_lumi_ratio -> setVal( 686./869. ) ;
       rv_lumi_ratio -> setConstant( kTRUE) ;



       RooFormulaVar* rv_mu_Zeesb = new RooFormulaVar( "mu_Zeesb",
                       "mu_Znnsb * ( acc_ee * eff_ee / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsb, *rv_acc_ee, *rv_eff_ee, *rv_bfRatio, *rv_lumi_ratio ) ) ;

       RooFormulaVar* rv_mu_Zmmsb = new RooFormulaVar( "mu_Zmmsb",
                       "mu_Znnsb * ( acc_mm * eff_mm / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsb, *rv_acc_mm, *rv_eff_mm, *rv_bfRatio, *rv_lumi_ratio ) ) ;

       RooFormulaVar* rv_mu_Zeesig = new RooFormulaVar( "mu_Zeesig",
                       "mu_Znnsig * ( acc_ee * eff_ee / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsig, *rv_acc_ee, *rv_eff_ee, *rv_bfRatio, *rv_lumi_ratio ) ) ;

       RooFormulaVar* rv_mu_Zmmsig = new RooFormulaVar( "mu_Zmmsig",
                       "mu_Znnsig * ( acc_mm * eff_mm / (bfRatio*lumi_ratio) )",
                       RooArgSet( *rv_mu_Znnsig, *rv_acc_mm, *rv_eff_mm, *rv_bfRatio, *rv_lumi_ratio ) ) ;



       RooFormulaVar* rv_n_sbee  = new RooFormulaVar( "n_sbee"  , "mu_Zeesb"  , RooArgSet( *rv_mu_Zeesb  ) ) ;
       RooFormulaVar* rv_n_sbmm  = new RooFormulaVar( "n_sbmm"  , "mu_Zmmsb"  , RooArgSet( *rv_mu_Zmmsb  ) ) ;
       RooFormulaVar* rv_n_sigee = new RooFormulaVar( "n_sigee" , "mu_Zeesig" , RooArgSet( *rv_mu_Zeesig ) ) ;
       RooFormulaVar* rv_n_sigmm = new RooFormulaVar( "n_sigmm" , "mu_Zmmsig" , RooArgSet( *rv_mu_Zmmsig ) ) ;



       RooGaussian* pdf_acc_mm = new RooGaussian( "pdf_acc_mm", "Gaussian pdf for Z to mumu acceptance",
                       *rv_acc_mm, RooConst( acc_mm_mean ), RooConst( acc_mm_err ) ) ;


       RooGaussian* pdf_acc_ee = new RooGaussian( "pdf_acc_ee", "Gaussian pdf for Z to ee acceptance",
                       *rv_acc_ee, RooConst( acc_ee_mean ), RooConst( acc_ee_err ) ) ;




       RooGaussian* pdf_eff_mm = new RooGaussian( "pdf_eff_mm", "Gaussian pdf for Z to mumu efficiency",
                       *rv_eff_mm, RooConst( eff_mm_mean ), RooConst( eff_mm_err ) ) ;



       RooGaussian* pdf_eff_ee = new RooGaussian( "pdf_eff_ee", "Gaussian pdf for Z to ee efficiency",
                       *rv_eff_ee, RooConst( eff_ee_mean ), RooConst( eff_ee_err ) ) ;



       RooPoisson* pdf_Nsbee   = new RooPoisson( "pdf_Nsbee"  , "Nsb , Z to ee Poisson PDF", *rv_Nsbee  , *rv_n_sbee  ) ;
       RooPoisson* pdf_Nsbmm   = new RooPoisson( "pdf_Nsbmm"  , "Nsb , Z to mm Poisson PDF", *rv_Nsbmm  , *rv_n_sbmm  ) ;
       RooPoisson* pdf_Nsigee  = new RooPoisson( "pdf_Nsigee" , "Nsig, Z to ee Poisson PDF", *rv_Nsigee , *rv_n_sigee ) ;
       RooPoisson* pdf_Nsigmm  = new RooPoisson( "pdf_Nsigmm" , "Nsig, Z to mm Poisson PDF", *rv_Nsigmm , *rv_n_sigmm ) ;

       RooArgSet pdflist ;
       pdflist.add( *pdf_acc_mm ) ;
       pdflist.add( *pdf_acc_ee ) ;
       pdflist.add( *pdf_eff_mm ) ;
       pdflist.add( *pdf_eff_ee ) ;
       pdflist.add( *pdf_Nsbee  ) ;
       pdflist.add( *pdf_Nsbmm  ) ;
       pdflist.add( *pdf_Nsigee  ) ;
       pdflist.add( *pdf_Nsigmm  ) ;

       RooProdPdf* znnLikelihood = new RooProdPdf( "znnLikelihood", "Z to nunu likelihood", pdflist ) ;


       RooArgSet observedParametersList ;
       observedParametersList.add( *rv_Nsbee ) ;
       observedParametersList.add( *rv_Nsbmm ) ;
       observedParametersList.add( *rv_Nsigee ) ;
       observedParametersList.add( *rv_Nsigmm ) ;

       RooDataSet* dsObserved = new RooDataSet( "ztonn_rds", "Z to nunu dataset", observedParametersList ) ;
       dsObserved->add( observedParametersList ) ;
       //// RooDataSet* dsObserved = znnLikelihood->generate( observedParametersList, 1) ;

       RooWorkspace* znnWorkspace = new RooWorkspace("ztonn_ws") ;
       znnWorkspace->import( *znnLikelihood ) ;
       znnWorkspace->import( *dsObserved ) ;

       znnWorkspace->Print() ;

       dsObserved->printMultiline(cout, 1, kTRUE, "") ;
       RooFitResult* fitResult = znnLikelihood->fitTo( *dsObserved, Verbose(true), Save(true) ) ;

       printf("\n\n----- Constant parameters:\n") ;
       RooArgList constPars = fitResult->constPars() ;
       for ( int pi=0; pi<constPars.getSize(); pi++ ) {
          constPars[pi].Print() ;
       } // pi.

       printf("\n\n----- Floating parameters:\n") ;
       RooArgList floatPars = fitResult->floatParsFinal() ;
       for ( int pi=0; pi<floatPars.getSize(); pi++ ) {
          floatPars[pi].Print() ;
       } // pi.
       printf("\n\n") ;



       ProfileLikelihoodCalculator plc_znn_sb(  *dsObserved, *znnLikelihood, RooArgSet( *rv_mu_Znnsb ) ) ;
       ProfileLikelihoodCalculator plc_znn_sig( *dsObserved, *znnLikelihood, RooArgSet( *rv_mu_Znnsig ) ) ;

       plc_znn_sb.SetTestSize(0.32) ;
       plc_znn_sig.SetTestSize(0.32) ;

       ConfInterval* sb_znn_interval = plc_znn_sb.GetInterval() ;
       float sbZnnLow  = ((LikelihoodInterval*) sb_znn_interval)->LowerLimit(*rv_mu_Znnsb) ;
       float sbZnnHigh = ((LikelihoodInterval*) sb_znn_interval)->UpperLimit(*rv_mu_Znnsb) ;
       printf("\n\n znn SB interval %6.1f to %6.1f\n", sbZnnLow, sbZnnHigh ) ;

       ConfInterval* sig_znn_interval = plc_znn_sig.GetInterval() ;
       float sigZnnLow  = ((LikelihoodInterval*) sig_znn_interval)->LowerLimit(*rv_mu_Znnsig) ;
       float sigZnnHigh = ((LikelihoodInterval*) sig_znn_interval)->UpperLimit(*rv_mu_Znnsig) ;
       printf("\n\n znn SIG interval %6.1f to %6.1f\n", sigZnnLow, sigZnnHigh ) ;



       TCanvas* c_prof_sb = new TCanvas("c_prof_sb","SB Z to nunu profile") ;
       LikelihoodIntervalPlot plot_znn_sb((LikelihoodInterval*)sb_znn_interval) ;
       plot_znn_sb.Draw() ;
       c_prof_sb->SaveAs("znn_sb_profile.png") ;

       TCanvas* c_prof_sig = new TCanvas("c_prof_sig","sig Z to nunu profile") ;
       LikelihoodIntervalPlot plot_znn_sig((LikelihoodInterval*)sig_znn_interval) ;
       plot_znn_sig.Draw() ;
       c_prof_sig->SaveAs("znn_sig_profile.png") ;


    }
예제 #9
0
// The actual job
void backgroundFits_qqzz_1Dw(int channel, int sqrts, int VBFtag)
{
  if(sqrts==7)return;
  TString schannel;
  if      (channel == 1) schannel = "4mu";
  else if (channel == 2) schannel = "4e";
  else if (channel == 3) schannel = "2e2mu";
  else cout << "Not a valid channel: " << schannel << endl;

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

  cout << "schannel = " << schannel << "  sqrts = " << sqrts << " VBFtag = " << VBFtag << endl;

  TString outfile;
  if(VBFtag<2) outfile = "CardFragments/qqzzBackgroundFit_" + ssqrts + "_" + schannel + "_" + Form("%d",int(VBFtag)) + ".txt";
  if(VBFtag==2) outfile = "CardFragments/qqzzBackgroundFit_" + ssqrts + "_" + schannel + ".txt";
  ofstream of(outfile,ios_base::out);
  of << "### background functions ###" << endl;


  gSystem->AddIncludePath("-I$ROOFITSYS/include");
  gROOT->ProcessLine(".L ../CreateDatacards/include/tdrstyle.cc");
  setTDRStyle(false);
  gStyle->SetPadLeftMargin(0.16);

  TString filepath;
  if (sqrts==7) {
    filepath = filePath7TeV;
  } else if (sqrts==8) {
    filepath = filePath8TeV;
  }

  TChain* tree = new TChain("SelectedTree");
  tree->Add( filepath+ "/" + (schannel=="2e2mu"?"2mu2e":schannel) + "/HZZ4lTree_ZZTo*.root");


  RooRealVar* MC_weight = new RooRealVar("MC_weight","MC_weight",0.,2.) ; 
  RooRealVar* ZZMass = new RooRealVar("ZZMass","ZZMass",100.,1000.);
  RooRealVar* NJets30 = new RooRealVar("NJets30","NJets30",0.,100.);
  RooArgSet ntupleVarSet(*ZZMass,*NJets30,*MC_weight);
  RooDataSet *set = new RooDataSet("set","set",ntupleVarSet,WeightVar("MC_weight"));

  Float_t myMC,myMass;
  Short_t myNJets;
  int nentries = tree->GetEntries();

  tree->SetBranchAddress("ZZMass",&myMass);
  tree->SetBranchAddress("MC_weight",&myMC);
  tree->SetBranchAddress("NJets30",&myNJets);

  for(int i =0;i<nentries;i++) {
    tree->GetEntry(i);
    if(VBFtag==1 && myNJets<2)continue;
    if(VBFtag==0 && myNJets>1)continue;

    ntupleVarSet.setRealValue("ZZMass",myMass);
    ntupleVarSet.setRealValue("MC_weight",myMC);
    ntupleVarSet.setRealValue("NJets30",(double)myNJets);

    set->add(ntupleVarSet, myMC);
  }

  double totalweight = 0.;
  double totalweight_z = 0.;
  for (int i=0 ; i<set->numEntries() ; i++) { 
    //set->get(i) ; 
    RooArgSet* row = set->get(i) ;
    //row->Print("v");
    totalweight += set->weight();
    if (row->getRealValue("ZZMass") < 200) totalweight_z += set->weight();
  } 
  cout << "nEntries: " << set->numEntries() << ", totalweight: " << totalweight << ", totalweight_z: " << totalweight_z << endl;

  gSystem->Load("libHiggsAnalysisCombinedLimit.so");
	
  //// ---------------------------------------
  //Background
  RooRealVar CMS_qqzzbkg_a0("CMS_qqzzbkg_a0","CMS_qqzzbkg_a0",115.3,0.,200.);
  RooRealVar CMS_qqzzbkg_a1("CMS_qqzzbkg_a1","CMS_qqzzbkg_a1",21.96,0.,200.);
  RooRealVar CMS_qqzzbkg_a2("CMS_qqzzbkg_a2","CMS_qqzzbkg_a2",122.8,0.,200.);
  RooRealVar CMS_qqzzbkg_a3("CMS_qqzzbkg_a3","CMS_qqzzbkg_a3",0.03479,0.,1.);
  RooRealVar CMS_qqzzbkg_a4("CMS_qqzzbkg_a4","CMS_qqzzbkg_a4",185.5,0.,200.);
  RooRealVar CMS_qqzzbkg_a5("CMS_qqzzbkg_a5","CMS_qqzzbkg_a5",12.67,0.,200.);
  RooRealVar CMS_qqzzbkg_a6("CMS_qqzzbkg_a6","CMS_qqzzbkg_a6",34.81,0.,100.);
  RooRealVar CMS_qqzzbkg_a7("CMS_qqzzbkg_a7","CMS_qqzzbkg_a7",0.1393,0.,1.);
  RooRealVar CMS_qqzzbkg_a8("CMS_qqzzbkg_a8","CMS_qqzzbkg_a8",66.,0.,200.);
  RooRealVar CMS_qqzzbkg_a9("CMS_qqzzbkg_a9","CMS_qqzzbkg_a9",0.07191,0.,1.);
  RooRealVar CMS_qqzzbkg_a10("CMS_qqzzbkg_a10","CMS_qqzzbkg_a10",94.11,0.,200.);
  RooRealVar CMS_qqzzbkg_a11("CMS_qqzzbkg_a11","CMS_qqzzbkg_a11",-5.111,-100.,100.);
  RooRealVar CMS_qqzzbkg_a12("CMS_qqzzbkg_a12","CMS_qqzzbkg_a12",4834,0.,10000.);
  RooRealVar CMS_qqzzbkg_a13("CMS_qqzzbkg_a13","CMS_qqzzbkg_a13",0.2543,0.,1.);
	
  if (channel == 1){
    ///* 4mu
    CMS_qqzzbkg_a0.setVal(103.854);
    CMS_qqzzbkg_a1.setVal(10.0718);
    CMS_qqzzbkg_a2.setVal(117.551);
    CMS_qqzzbkg_a3.setVal(0.0450287);
    CMS_qqzzbkg_a4.setVal(185.262);
    CMS_qqzzbkg_a5.setVal(7.99428);
    CMS_qqzzbkg_a6.setVal(39.7813);
    CMS_qqzzbkg_a7.setVal(0.0986891);
    CMS_qqzzbkg_a8.setVal(49.1325);
    CMS_qqzzbkg_a9.setVal(0.0389984);
    CMS_qqzzbkg_a10.setVal(98.6645);
    CMS_qqzzbkg_a11.setVal(-7.02043);
    CMS_qqzzbkg_a12.setVal(5694.66);
    CMS_qqzzbkg_a13.setVal(0.0774525);
    //*/
  }
  else if (channel == 2){
    ///* 4e
    CMS_qqzzbkg_a0.setVal(111.165);
    CMS_qqzzbkg_a1.setVal(19.8178);
    CMS_qqzzbkg_a2.setVal(120.89);
    CMS_qqzzbkg_a3.setVal(0.0546639);
    CMS_qqzzbkg_a4.setVal(184.878);
    CMS_qqzzbkg_a5.setVal(11.7041);
    CMS_qqzzbkg_a6.setVal(33.2659);
    CMS_qqzzbkg_a7.setVal(0.140858);
    CMS_qqzzbkg_a8.setVal(56.1226);
    CMS_qqzzbkg_a9.setVal(0.0957699);
    CMS_qqzzbkg_a10.setVal(98.3662);
    CMS_qqzzbkg_a11.setVal(-6.98701);
    CMS_qqzzbkg_a12.setVal(10.0536);
    CMS_qqzzbkg_a13.setVal(0.110576);
    //*/
  }
  else if (channel == 3){
    ///* 2e2mu
    CMS_qqzzbkg_a0.setVal(110.293);
    CMS_qqzzbkg_a1.setVal(11.8334);
    CMS_qqzzbkg_a2.setVal(116.91);
    CMS_qqzzbkg_a3.setVal(0.0433151);
    CMS_qqzzbkg_a4.setVal(185.817);
    CMS_qqzzbkg_a5.setVal(10.5945);
    CMS_qqzzbkg_a6.setVal(29.6208);
    CMS_qqzzbkg_a7.setVal(0.0826);
    CMS_qqzzbkg_a8.setVal(53.1346);
    CMS_qqzzbkg_a9.setVal(0.0882081);
    CMS_qqzzbkg_a10.setVal(85.3776);
    CMS_qqzzbkg_a11.setVal(-13.3836);
    CMS_qqzzbkg_a12.setVal(7587.95);
    CMS_qqzzbkg_a13.setVal(0.325621);
    //*/
  }
  else {
    cout << "disaster" << endl;
  }
    
  RooqqZZPdf_v2* bkg_qqzz = new RooqqZZPdf_v2("bkg_qqzz","bkg_qqzz",*ZZMass,
					      CMS_qqzzbkg_a0,CMS_qqzzbkg_a1,CMS_qqzzbkg_a2,CMS_qqzzbkg_a3,CMS_qqzzbkg_a4,
					      CMS_qqzzbkg_a5,CMS_qqzzbkg_a6,CMS_qqzzbkg_a7,CMS_qqzzbkg_a8,
					      CMS_qqzzbkg_a9,CMS_qqzzbkg_a10,CMS_qqzzbkg_a11,CMS_qqzzbkg_a12,CMS_qqzzbkg_a13);
  RooArgSet myASet(*ZZMass, CMS_qqzzbkg_a0,CMS_qqzzbkg_a1,CMS_qqzzbkg_a2,CMS_qqzzbkg_a3,CMS_qqzzbkg_a4,
		   CMS_qqzzbkg_a5,CMS_qqzzbkg_a6,CMS_qqzzbkg_a7);
  myASet.add(CMS_qqzzbkg_a8);
  myASet.add(CMS_qqzzbkg_a9);
  myASet.add(CMS_qqzzbkg_a10);
  myASet.add(CMS_qqzzbkg_a11);
  myASet.add(CMS_qqzzbkg_a12);
  myASet.add(CMS_qqzzbkg_a13);
 
  RooFitResult *r1 = bkg_qqzz->fitTo( *set, Save(kTRUE), SumW2Error(kTRUE) );//, Save(kTRUE), SumW2Error(kTRUE)) ;

  cout << endl;
  cout << "------- Parameters for " << schannel << " sqrts=" << sqrts << endl;
  cout << "  a0_bkgd = " << CMS_qqzzbkg_a0.getVal() << endl;
  cout << "  a1_bkgd = " << CMS_qqzzbkg_a1.getVal() << endl;
  cout << "  a2_bkgd = " << CMS_qqzzbkg_a2.getVal() << endl;
  cout << "  a3_bkgd = " << CMS_qqzzbkg_a3.getVal() << endl;
  cout << "  a4_bkgd = " << CMS_qqzzbkg_a4.getVal() << endl;
  cout << "  a5_bkgd = " << CMS_qqzzbkg_a5.getVal() << endl;
  cout << "  a6_bkgd = " << CMS_qqzzbkg_a6.getVal() << endl;
  cout << "  a7_bkgd = " << CMS_qqzzbkg_a7.getVal() << endl;
  cout << "  a8_bkgd = " << CMS_qqzzbkg_a8.getVal() << endl;
  cout << "  a9_bkgd = " << CMS_qqzzbkg_a9.getVal() << endl;
  cout << "  a10_bkgd = " << CMS_qqzzbkg_a10.getVal() << endl;
  cout << "  a11_bkgd = " << CMS_qqzzbkg_a11.getVal() << endl;
  cout << "  a12_bkgd = " << CMS_qqzzbkg_a12.getVal() << endl;
  cout << "  a13_bkgd = " << CMS_qqzzbkg_a13.getVal() << endl;
  cout << "}" << endl;
  cout << "---------------------------" << endl;


  of << "qqZZshape a0_bkgd   " << CMS_qqzzbkg_a0.getVal() << endl;
  of << "qqZZshape a1_bkgd   " << CMS_qqzzbkg_a1.getVal() << endl;
  of << "qqZZshape a2_bkgd   " << CMS_qqzzbkg_a2.getVal() << endl;
  of << "qqZZshape a3_bkgd   " << CMS_qqzzbkg_a3.getVal() << endl;
  of << "qqZZshape a4_bkgd   " << CMS_qqzzbkg_a4.getVal() << endl;
  of << "qqZZshape a5_bkgd   " << CMS_qqzzbkg_a5.getVal() << endl;
  of << "qqZZshape a6_bkgd   " << CMS_qqzzbkg_a6.getVal() << endl;
  of << "qqZZshape a7_bkgd   " << CMS_qqzzbkg_a7.getVal() << endl;
  of << "qqZZshape a8_bkgd   " << CMS_qqzzbkg_a8.getVal() << endl;
  of << "qqZZshape a9_bkgd   " << CMS_qqzzbkg_a9.getVal() << endl;
  of << "qqZZshape a10_bkgd  " << CMS_qqzzbkg_a10.getVal() << endl;
  of << "qqZZshape a11_bkgd  " << CMS_qqzzbkg_a11.getVal() << endl;
  of << "qqZZshape a12_bkgd  " << CMS_qqzzbkg_a12.getVal() << endl;
  of << "qqZZshape a13_bkgd  " << CMS_qqzzbkg_a13.getVal() << endl;
  of << endl << endl;
  of.close();

  cout << endl << "Output written to: " << outfile << endl;
  
    
  double qqzznorm;
  if (channel == 1) qqzznorm = 20.5836;
  else if (channel == 2) qqzznorm = 13.8871;
  else if (channel == 3) qqzznorm = 32.9883;
  else { cout << "disaster!" << endl; }

  ZZMass->setRange("fullrange",100.,1000.);
  ZZMass->setRange("largerange",100.,600.);
  ZZMass->setRange("zoomrange",100.,200.);
    
  double rescale = qqzznorm/totalweight;
  double rescale_z = qqzznorm/totalweight_z;
  cout << "rescale: " << rescale << ", rescale_z: " << rescale_z << endl;


  // Plot m4l and
  RooPlot* frameM4l = ZZMass->frame(Title("M4L"),Range(100,600),Bins(250)) ;
  set->plotOn(frameM4l, MarkerStyle(20), Rescale(rescale)) ;
  
  //set->plotOn(frameM4l) ;
  RooPlot* frameM4lz = ZZMass->frame(Title("M4L"),Range(100,200),Bins(100)) ;
  set->plotOn(frameM4lz, MarkerStyle(20), Rescale(rescale)) ;


  int iLineColor = 1;
  string lab = "blah";
  if (channel == 1) { iLineColor = 2; lab = "4#mu"; }
  if (channel == 3) { iLineColor = 4; lab = "2e2#mu"; }
  if (channel == 2) { iLineColor = 6; lab = "4e"; }

  bkg_qqzz->plotOn(frameM4l,LineColor(iLineColor),NormRange("largerange")) ;
  bkg_qqzz->plotOn(frameM4lz,LineColor(iLineColor),NormRange("zoomrange")) ;
    
//second shape to compare with (if previous comparison code unceommented)
  //bkg_qqzz_bkgd->plotOn(frameM4l,LineColor(1),NormRange("largerange")) ;
  //bkg_qqzz_bkgd->plotOn(frameM4lz,LineColor(1),NormRange("zoomrange")) ;
    
  
  double normalizationBackground_qqzz = bkg_qqzz->createIntegral( RooArgSet(*ZZMass), Range("fullrange") )->getVal();
  cout << "Norm all = " << normalizationBackground_qqzz << endl;
    
  frameM4l->GetXaxis()->SetTitle("m_{4l} [GeV]");
  frameM4l->GetYaxis()->SetTitle("a.u.");
  frameM4lz->GetXaxis()->SetTitle("m_{4l} [GeV]");
  frameM4lz->GetYaxis()->SetTitle("a.u.");

  char lname[192];
  sprintf(lname,"qq #rightarrow ZZ #rightarrow %s", lab.c_str() );
  char lname2[192];
  sprintf(lname2,"Shape Model, %s", lab.c_str() );
  // dummy!
  TF1* dummyF = new TF1("dummyF","1",0.,1.);
  TH1F* dummyH = new TH1F("dummyH","",1, 0.,1.);
  dummyF->SetLineColor( iLineColor );
  dummyF->SetLineWidth( 2 );

  dummyH->SetLineColor( kBlue );
  TLegend * box2 = new TLegend(0.4,0.70,0.80,0.90);
  box2->SetFillColor(0);
  box2->SetBorderSize(0);
  box2->AddEntry(dummyH,"Simulation (POWHEG+Pythia)  ","pe");
  box2->AddEntry(dummyH,lname,"");
  box2->AddEntry(dummyH,"","");
  box2->AddEntry(dummyF,lname2,"l");
    
  TPaveText *pt = new TPaveText(0.15,0.955,0.4,0.99,"NDC");
  pt->SetFillColor(0);
  pt->SetBorderSize(0);
  pt->AddText("CMS Preliminary 2012");
  TPaveText *pt2 = new TPaveText(0.84,0.955,0.99,0.99,"NDC");
  pt2->SetFillColor(0);
  pt2->SetBorderSize(0);
  TString entag;entag.Form("#sqrt{s} = %d TeV",sqrts);
  pt2->AddText(entag.Data());

  TCanvas *c = new TCanvas("c","c",800,600);
  c->cd();
  frameM4l->Draw();
  frameM4l->GetYaxis()->SetRangeUser(0,0.4);
  if(channel == 3)frameM4l->GetYaxis()->SetRangeUser(0,0.7);
  box2->Draw();
  pt->Draw();
  pt2->Draw();
  TString outputPath = "bkgFigs";
  outputPath = outputPath+ (long) sqrts + "TeV/";
  TString outputName;
  if(VBFtag<2) outputName =  outputPath + "bkgqqzz_" + schannel + "_" + Form("%d",int(VBFtag));
  if(VBFtag==2) outputName =  outputPath + "bkgqqzz_" + schannel;
  c->SaveAs(outputName + ".eps");
  c->SaveAs(outputName + ".png");
    
  TCanvas *c2 = new TCanvas("c2","c2",1000,500);
  c2->Divide(2,1);
  c2->cd(1);
  frameM4l->Draw();
  box2->Draw("same");
  c2->cd(2);
  frameM4lz->Draw();
  box2->Draw("same");
  
  if (VBFtag<2) outputName = outputPath + "bkgqqzz_" + schannel + "_z" + "_" + Form("%d",int(VBFtag));
  if (VBFtag==2) outputName = outputPath + "bkgqqzz_" + schannel + "_z";
  c2->SaveAs(outputName + ".eps");
  c2->SaveAs(outputName + ".png");

  /* TO make the ratio btw 2 shapes, if needed for compairson
  TCanvas *c3 = new TCanvas("c3","c3",1000,500);
   if(sqrts==7)
    sprintf(outputName, "bkgFigs7TeV/bkgqqzz_%s_ratio.eps",schannel.c_str());
  else if(sqrts==8)
    sprintf(outputName, "bkgFigs8TeV/bkgqqzz_%s_ratio.eps",schannel.c_str());

   const int nPoints = 501.;
  double masses[nPoints] ;
  int j=0;
  for (int i=100; i<601; i++){
    masses[j] = i;
    j++;
  }
  cout<<j<<endl;
  double effDiff[nPoints];
  for (int i = 0; i < nPoints; i++){
    ZZMass->setVal(masses[i]);
    double eval = (bkg_qqzz_bkgd->getVal(otherASet)-bkg_qqzz->getVal(myASet))/(bkg_qqzz->getVal(myASet));
    //cout<<bkg_qqzz_bkgd->getVal(otherASet)<<" "<<bkg_qqzz->getVal(myASet)<<" "<<eval<<endl;
    effDiff[i]=eval;
  }
  TGraph* grEffDiff = new TGraph( nPoints, masses, effDiff );
  grEffDiff->SetMarkerStyle(20);
  grEffDiff->Draw("AL");

  //c3->SaveAs(outputName);
  */

  if (VBFtag<2) outputName = outputPath + "bkgqqzz_" + schannel + "_z" + "_" + Form("%d",int(VBFtag)) + ".root";
  if (VBFtag==2) outputName = outputPath + "bkgqqzz_" + schannel + "_z" + ".root";
  TFile* outF = new TFile(outputName,"RECREATE");
  outF->cd();
  c2->Write();
  frameM4l->Write();
  frameM4lz->Write();	
  outF->Close();


  delete c;
  delete c2;
}
예제 #10
0
// implementation
void TwoBinInstructional( void ){
  
  // let's time this example
  TStopwatch t;
  t.Start();

  // set RooFit random seed for reproducible results
  RooRandom::randomGenerator()->SetSeed(4357);

  // make model
  RooWorkspace * pWs = new RooWorkspace("ws");

  // derived from data
  pWs->factory("xsec[0.2,0,2]"); // POI
  pWs->factory("bg_b[10,0,50]");    // data driven nuisance

  // predefined nuisances
  pWs->factory("lumi[100,0,1000]");
  pWs->factory("eff_a[0.2,0,1]");
  pWs->factory("eff_b[0.05,0,1]");
  pWs->factory("tau[0,1]");
  pWs->factory("xsec_bg_a[0.05]"); // constant
  pWs->var("xsec_bg_a")->setConstant(1);

  // channel a (signal): lumi*xsec*eff_a + lumi*bg_a + tau*bg_b
  pWs->factory("prod::sig_a(lumi,xsec,eff_a)");
  pWs->factory("prod::bg_a(lumi,xsec_bg_a)");
  pWs->factory("prod::tau_bg_b(tau, bg_b)");
  pWs->factory("Poisson::pdf_a(na[14,0,100],sum::mu_a(sig_a,bg_a,tau_bg_b))");

  // channel b (control): lumi*xsec*eff_b + bg_b
  pWs->factory("prod::sig_b(lumi,xsec,eff_b)");
  pWs->factory("Poisson::pdf_b(nb[11,0,100],sum::mu_b(sig_b,bg_b))");

  // nuisance constraint terms (systematics)
  pWs->factory("Lognormal::l_lumi(lumi,nom_lumi[100,0,1000],sum::kappa_lumi(1,d_lumi[0.1]))");
  pWs->factory("Lognormal::l_eff_a(eff_a,nom_eff_a[0.20,0,1],sum::kappa_eff_a(1,d_eff_a[0.05]))");
  pWs->factory("Lognormal::l_eff_b(eff_b,nom_eff_b[0.05,0,1],sum::kappa_eff_b(1,d_eff_b[0.05]))");
  pWs->factory("Lognormal::l_tau(tau,nom_tau[0.50,0,1],sum::kappa_tau(1,d_tau[0.05]))");
  //pWs->factory("Lognormal::l_bg_a(bg_a,nom_bg_a[0.05,0,1],sum::kappa_bg_a(1,d_bg_a[0.10]))");

  // complete model PDF
  pWs->factory("PROD::model(pdf_a,pdf_b,l_lumi,l_eff_a,l_eff_b,l_tau)");

  // Now create sets of variables. Note that we could use the factory to
  // create sets but in that case many of the sets would be duplicated
  // when the ModelConfig objects are imported into the workspace. So,
  // we create the sets outside the workspace, and only the needed ones
  // will be automatically imported by ModelConfigs

  // observables
  RooArgSet obs(*pWs->var("na"), *pWs->var("nb"), "obs");

  // global observables
  RooArgSet globalObs(*pWs->var("nom_lumi"), *pWs->var("nom_eff_a"), *pWs->var("nom_eff_b"), 
		      *pWs->var("nom_tau"),
		      "global_obs");

  // parameters of interest
  RooArgSet poi(*pWs->var("xsec"), "poi");

  // nuisance parameters
  RooArgSet nuis(*pWs->var("lumi"), *pWs->var("eff_a"), *pWs->var("eff_b"), *pWs->var("tau"), "nuis");

  // priors (for Bayesian calculation)
  pWs->factory("Uniform::prior_xsec(xsec)"); // for parameter of interest
  pWs->factory("Uniform::prior_bg_b(bg_b)"); // for data driven nuisance parameter
  pWs->factory("PROD::prior(prior_xsec,prior_bg_b)"); // total prior

  // create data
  pWs->var("na")->setVal(14);
  pWs->var("nb")->setVal(11);
  RooDataSet * pData = new RooDataSet("data","",obs);
  pData->add(obs);
  pWs->import(*pData);
  //pData->Print();

  // signal+background model
  ModelConfig * pSbModel = new ModelConfig("SbModel");
  pSbModel->SetWorkspace(*pWs);
  pSbModel->SetPdf(*pWs->pdf("model"));
  pSbModel->SetPriorPdf(*pWs->pdf("prior"));
  pSbModel->SetParametersOfInterest(poi);
  pSbModel->SetNuisanceParameters(nuis);
  pSbModel->SetObservables(obs);
  pSbModel->SetGlobalObservables(globalObs);

  // set all but obs, poi and nuisance to const
  SetConstants(pWs, pSbModel);
  pWs->import(*pSbModel);


  // background-only model
  // use the same PDF as s+b, with xsec=0
  // POI value under the background hypothesis
  Double_t poiValueForBModel = 0.0;
  ModelConfig* pBModel = new ModelConfig(*(RooStats::ModelConfig *)pWs->obj("SbModel"));
  pBModel->SetName("BModel");
  pBModel->SetWorkspace(*pWs);
  pWs->import(*pBModel);


  // find global maximum with the signal+background model
  // with conditional MLEs for nuisance parameters
  // and save the parameter point snapshot in the Workspace
  //  - safer to keep a default name because some RooStats calculators
  //    will anticipate it
  RooAbsReal * pNll = pSbModel->GetPdf()->createNLL(*pData);
  RooAbsReal * pProfile = pNll->createProfile(RooArgSet());
  pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
  RooArgSet * pPoiAndNuisance = new RooArgSet();
  if(pSbModel->GetNuisanceParameters())
    pPoiAndNuisance->add(*pSbModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pSbModel->GetParametersOfInterest());
  cout << "\nWill save these parameter points that correspond to the fit to data" << endl;
  pPoiAndNuisance->Print("v");
  pSbModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;

  // Find a parameter point for generating pseudo-data
  // with the background-only data.
  // Save the parameter point snapshot in the Workspace
  pNll = pBModel->GetPdf()->createNLL(*pData);
  pProfile = pNll->createProfile(poi);
  ((RooRealVar *)poi.first())->setVal(poiValueForBModel);
  pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
  pPoiAndNuisance = new RooArgSet();
  if(pBModel->GetNuisanceParameters())
    pPoiAndNuisance->add(*pBModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pBModel->GetParametersOfInterest());
  cout << "\nShould use these parameter points to generate pseudo data for bkg only" << endl;
  pPoiAndNuisance->Print("v");
  pBModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;

  // inspect workspace
  pWs->Print();

  // save workspace to file
  pWs->writeToFile("ws_twobin.root");

  // clean up
  delete pWs;
  delete pData;
  delete pSbModel;
  delete pBModel;

} // ----- end of tutorial ----------------------------------------
예제 #11
0
void MakeWorkspace( void ){
  //
  // this function implements a RooFit model for a counting experiment
  //

  // create workspace
  RooWorkspace * pWs = new RooWorkspace("myWS");
  
  // observable: number of events
  pWs->factory( "n[0.0]" );

  // integrated luminosity with systematics
  pWs->factory( "lumi_nom[5000.0, 4000.0, 6000.0]" );
  pWs->factory( "lumi_kappa[1.045]" );
  pWs->factory( "cexpr::alpha_lumi('pow(lumi_kappa,beta_lumi)',lumi_kappa,beta_lumi[0,-5,5])" );
  pWs->factory( "prod::lumi(lumi_nom,alpha_lumi)" );
  pWs->factory( "Gaussian::constr_lumi(beta_lumi,glob_lumi[0,-5,5],1)" );

  // cross section - parameter of interest
  pWs->factory( "xsec[0.001,0.0,0.1]" );

  // selection efficiency * acceptance with systematics
  pWs->factory( "efficiency_nom[0.1, 0.05, 0.15]" );
  pWs->factory( "efficiency_kappa[1.10]" );
  pWs->factory( "cexpr::alpha_efficiency('pow(efficiency_kappa,beta_efficiency)',efficiency_kappa,beta_efficiency[0,-5,5])" );
  pWs->factory( "prod::efficiency(efficiency_nom,alpha_efficiency)" );
  pWs->factory( "Gaussian::constr_efficiency(beta_efficiency,glob_efficiency[0,-5,5],1)" );

  // signal yield
  pWs->factory( "prod::nsig(lumi,xsec,efficiency)" );

  // background yield with systematics
  pWs->factory( "nbkg_nom[10.0, 5.0, 15.0]" );
  pWs->factory( "nbkg_kappa[1.10]" );
  pWs->factory( "cexpr::alpha_nbkg('pow(nbkg_kappa,beta_nbkg)',nbkg_kappa,beta_nbkg[0,-5,5])" );
  pWs->factory( "prod::nbkg(nbkg_nom,alpha_lumi,alpha_nbkg)" );
  pWs->factory( "Gaussian::constr_nbkg(beta_nbkg,glob_nbkg[0,-5,5],1)" );

  // full event yield
  pWs->factory("sum::yield(nsig,nbkg)");

  // Core model: Poisson probability with mean signal+bkg
  pWs->factory( "Poisson::model_core(n,yield)" );

  // define Bayesian prior PDF for POI
  pWs->factory( "Uniform::prior(xsec)" );

  // model with systematics
  pWs->factory( "PROD::model(model_core,constr_lumi,constr_efficiency,constr_nbkg)" );

  // create set of observables (will need it for datasets and ModelConfig later)
  RooRealVar * pObs = pWs->var("n"); // get the pointer to the observable
  RooArgSet obs("observables");
  obs.add(*pObs);

  // create the dataset
  pObs->setVal(11); // this is your observed data: we counted ten events
  RooDataSet * data = new RooDataSet("data", "data", obs);
  data->add( *pObs );

  // import dataset into workspace
  pWs->import(*data);

  // create set of global observables (need to be defined as constants)
  pWs->var("glob_lumi")->setConstant(true);
  pWs->var("glob_efficiency")->setConstant(true);
  pWs->var("glob_nbkg")->setConstant(true);
  RooArgSet globalObs("global_obs");
  globalObs.add( *pWs->var("glob_lumi") );
  globalObs.add( *pWs->var("glob_efficiency") );
  globalObs.add( *pWs->var("glob_nbkg") );

  // create set of parameters of interest (POI)
  RooArgSet poi("poi");
  poi.add( *pWs->var("xsec") );
  
  // create set of nuisance parameters
  RooArgSet nuis("nuis");
  nuis.add( *pWs->var("beta_lumi") );
  nuis.add( *pWs->var("beta_efficiency") );
  nuis.add( *pWs->var("beta_nbkg") );

  // create signal+background Model Config
  RooStats::ModelConfig sbHypo("SbHypo");
  sbHypo.SetWorkspace( *pWs );
  sbHypo.SetPdf( *pWs->pdf("model") );
  sbHypo.SetObservables( obs );
  sbHypo.SetGlobalObservables( globalObs );
  sbHypo.SetParametersOfInterest( poi );
  sbHypo.SetNuisanceParameters( nuis );
  sbHypo.SetPriorPdf( *pWs->pdf("prior") ); // this is optional

  // fix all other variables in model:
  // everything except observables, POI, and nuisance parameters
  // must be constant
  pWs->var("lumi_nom")->setConstant(true);
  pWs->var("efficiency_nom")->setConstant(true);
  pWs->var("nbkg_nom")->setConstant(true);
  pWs->var("lumi_kappa")->setConstant(true);
  pWs->var("efficiency_kappa")->setConstant(true);
  pWs->var("nbkg_kappa")->setConstant(true);
  RooArgSet fixed("fixed");
  fixed.add( *pWs->var("lumi_nom") );
  fixed.add( *pWs->var("efficiency_nom") );
  fixed.add( *pWs->var("nbkg_nom") );
  fixed.add( *pWs->var("lumi_kappa") );
  fixed.add( *pWs->var("efficiency_kappa") );
  fixed.add( *pWs->var("nbkg_kappa") );
  
  // set parameter snapshot that corresponds to the best fit to data
  RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data );
  RooAbsReal * pProfile = pNll->createProfile( globalObs ); // do not profile global observables
  pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
  RooArgSet * pPoiAndNuisance = new RooArgSet("poiAndNuisance");
  pPoiAndNuisance->add(*sbHypo.GetNuisanceParameters());
  pPoiAndNuisance->add(*sbHypo.GetParametersOfInterest());
  sbHypo.SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;

  // import S+B ModelConfig into workspace
  pWs->import( sbHypo );

  // create background-only Model Config from the S+B one
  RooStats::ModelConfig bHypo = sbHypo;
  bHypo.SetName("BHypo");
  bHypo.SetWorkspace(*pWs);

  // set parameter snapshot for bHypo, setting xsec=0
  // it is useful to understand how this block of code works
  // but you can also use it as a recipe to make a parameter snapshot
  pNll = bHypo.GetPdf()->createNLL( *data );
  RooArgSet poiAndGlobalObs("poiAndGlobalObs");
  poiAndGlobalObs.add( poi );
  poiAndGlobalObs.add( globalObs );
  pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables
  ((RooRealVar *)poi.first())->setVal( 0 );  // set xsec=0 here
  pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
  pPoiAndNuisance = new RooArgSet( "poiAndNuisance" );
  pPoiAndNuisance->add( nuis );
  pPoiAndNuisance->add( poi );
  bHypo.SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;

  // import model config into workspace
  pWs->import( bHypo );

  // print out the workspace contents
  pWs->Print();

  // save workspace to file
  pWs -> SaveAs("workspace.root");

  return;
}
예제 #12
0
파일: ToyIter.C 프로젝트: pellicci/UserCode
int main(int argc, char* argv[])
{
  char *filename;
  Int_t nexp = 0, nev = 0, SEED = 0;
  Double_t c1val = 0., c2val = 0.;
  Double_t c1pval = 0., c2pval = 0.;
  Double_t c1mval = 0., c2mval = 0.;

  for(Int_t i=1;i<argc;i++){
    char *pchar = argv[i];

    switch(pchar[0]){

    case '-':{

      switch(pchar[1]){
      case 'f':
	filename = argv[i+1];
	cout << "File name used in this toy " << filename << endl;
	break;

      case 'e':
	nexp = atoi(argv[i+1]);
	cout << "Number of experiments " << nexp << endl;
	break;

      case 'n':
	nev = atoi(argv[i+1]);
	cout << "Number of events per experiment " << nev << endl;
	break;

      case 's':
        SEED = atoi(argv[i+1]);
        break;

      case '1':
	c1pval = atof(argv[i+1]);
	cout << "The c1 value is " << c1pval << endl;
        break;

      case '2':
	c1mval = atof(argv[i+1]);
	cout << "The c1 value is " << c1mval << endl;
        break;

      case '3':
        c2pval = atof(argv[i+1]);
	cout << "The c2 values is " << c2pval << endl;
        break;

     case '4':
        c2mval = atof(argv[i+1]);
	cout << "The c2 values is " << c2mval << endl;
        break;

      case 'x':
        c1val = atof(argv[i+1]);
	cout << "The c1 value is " << c1pval << endl;
        break;

      case 'y':
        c2val = atof(argv[i+1]);
        cout << "The c2 values is " << c2pval << endl;
        break;
      }
    }
    }

  }

  //set the seed and the generator used by EvtGen
  RooRandom::randomGenerator()->SetSeed(SEED);
  cout << "  Toy seed ............. " << (RooRandom::randomGenerator()->GetSeed()) << endl;

  //define DalitzSpace for generation
  EvtPDL pdl;
  pdl.readPDT("evt.pdl");
  EvtDecayMode mode("D0 -> K- pi+ pi0");
  EvtDalitzPlot dalitzSpace(mode);

  Bool_t doGen = kFALSE;
  Bool_t doFit = kTRUE;
  Bool_t extract = kFALSE;

  RooRealVar tau("tau","tau",0.4099);
  RooRealVar m2Kpi_d0mass("m2Kpi_d0mass","m2Kpi_d0mass",1.,dalitzSpace.qAbsMin(EvtCyclic3::AB),dalitzSpace.qAbsMax(EvtCyclic3::AB));
  RooRealVar m2Kpi0_d0mass("m2Kpi0_d0mass","m2Kpi0_d0mass",1.,dalitzSpace.qAbsMin(EvtCyclic3::AC),dalitzSpace.qAbsMax(EvtCyclic3::AC));
  RooRealVar d0Lifetime("d0Lifetime","d0Lifetime",-2.,4.);
  RooRealVar d0LifetimeErr("d0LifetimeErr","d0LifetimeErr",0.0000001,0.5);
  RooCategory D0flav("D0flav","D0flav");
  D0flav.defineType("D0",-1);
  D0flav.defineType("antiD0",1);

  RooRealVar scalefact1("scalefact1","scalefact1",3.20);
  RooRealVar scalefact2("scalefact2","scalefact2",1.42);
  RooRealVar scalefact3("scalefact3","scalefact3",0.94);

  RooRealVar c1("c1","c1",c1val,-3.,3.);
  RooRealVar c2("c2","c2",c2val,-3.,3.);
  RooRealVar c1p("c1p","c1p",c1pval,-3.,3.);
  RooRealVar c2p("c2p","c2p",c2pval,-3.,3.);
  RooRealVar c1m("c1m","c1m",c1mval,-3.,3.);
  RooRealVar c2m("c2m","c2m",c2mval,-3.,3.);

  c1p.setConstant(kTRUE);
  c2p.setConstant(kTRUE);

  m2Kpi_d0mass.setBins(10);
  m2Kpi0_d0mass.setBins(10);
  d0Lifetime.setBins(8);
  d0LifetimeErr.setBins(10);

  //Construct signal pdf
  RooRealVar bias("bias","bias",0.0047);
  RooRealVar one("one","one",1.);

  //consider the resolution or the truth model
  RooGaussModel gm1("gm1","gauss model 1",d0Lifetime,bias,d0LifetimeErr,one,scalefact1) ;
  RooGaussModel gm2("gm2","gauss model 2",d0Lifetime,bias,d0LifetimeErr,one,scalefact2) ;
  RooGaussModel gm3("gm3","gauss model 3",d0Lifetime,bias,d0LifetimeErr,one,scalefact3) ;
  //RooTruthModel gm("gm","truth model",d0Lifetime);

  RooRealVar N1("N1","N1",0.0052);
  RooRealVar N2("N2","N2",0.179);

  RooFormulaVar f2("f2","f2","(1-@0)*@1",RooArgList(N1,N2));
  RooFormulaVar f3("f3","f3","(1-@0)*(1-@1)",RooArgList(N1,N2));
  RooAddModel gm("gm","gm",RooArgList(gm2,gm3,gm1),RooArgList(f2,f3));

  string dirname = "configmaps/effmapping_std/";

  RooTimepdf TOTsigD0("TOTsigD0","TOTsigD0",d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass,gm,&dalitzSpace,tau,c1p,c2p,-1,dirname);
  RooTimepdf TOTsigantiD0("TOTsigantiD0","TOTsigantiD0",d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass,gm,&dalitzSpace,tau,c1p,c2p,-1,dirname);
 
  RooSimultaneous TOTTime("TOTTime","TOTTime",D0flav);
  TOTTime.addPdf(TOTsigD0,"D0");
  TOTTime.addPdf(TOTsigantiD0,"antiD0");

  //////////////////////////
  // BACKGROUND
  /////////////////////////

  TFile RSfile("DataSet_out_reduced_RS.root");
  gROOT->cd();
  RooDataSet *RSdata = (RooDataSet*)RSfile.Get("fulldata");

  m2Kpi_d0mass.setBins(150);
  m2Kpi0_d0mass.setBins(150);
  d0Lifetime.setBins(70);
  d0LifetimeErr.setBins(20);
  /*
  TH3F *mis_h = m2Kpi_d0mass.createHistogram("mis_h",m2Kpi0_d0mass,d0Lifetime,"");
  RSdata->fillHistogram(mis_h,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime));
  mis_h->Sumw2();
  RooDataHist *mis_hist = new RooDataHist("mis_hist","mis_hist",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),mis_h);
  RooHistPdf Tot_mis("Tot_mis","Tot_mis",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),*mis_hist);
  */
  TH3F *mis_hp = m2Kpi_d0mass.createHistogram("mis_hp",m2Kpi0_d0mass,d0Lifetime,"");
  RSdata->fillHistogram(mis_hp,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),"D0flav == 1");
  mis_hp->Sumw2();
  RooDataHist *mis_histp = new RooDataHist("mis_histp","mis_histp",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),mis_hp);
  RooHistPdf Tot_misp("Tot_misp","Tot_misp",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),*mis_histp);

  TH3F *mis_hm = m2Kpi_d0mass.createHistogram("mis_hm",m2Kpi0_d0mass,d0Lifetime,"");
  RSdata->fillHistogram(mis_hm,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),"D0flav == -1");
  mis_hm->Sumw2();
  RooDataHist *mis_histm = new RooDataHist("mis_histm","mis_histm",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),mis_hm);
  RooHistPdf Tot_mism("Tot_mism","Tot_mism",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),*mis_histm);

  RooSimultaneous Tot_mis("Tot_mis","Tot_mis",D0flav);
  Tot_mis.addPdf(Tot_misp,"D0");
  Tot_mis.addPdf(Tot_mism,"antiD0");

  cout << "///////////////" << endl;
  cout << "Sample of D0bar RS : " << mis_histp->numEntries(kTRUE) << endl;
  cout << "Sample of D0 RS : " << mis_histm->numEntries(kTRUE) << endl;
  cout << "///////////////" << endl;

  m2Kpi_d0mass.setBins(10);
  m2Kpi0_d0mass.setBins(10);
  d0Lifetime.setBins(8);
  d0LifetimeErr.setBins(10);

  RooArgSet observ(d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass);
  RooArgSet tot_var(d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass,d0LifetimeErr,D0flav);

  TFile WSfile("DataSet_out_reduced_WS.root");
  gROOT->cd();
  RooDataSet *databkg = (RooDataSet*)WSfile.Get("fulldata");
  RooDataSet *leftdata = (RooDataSet*)databkg->reduce("d0Mass > 1.74 && d0Mass < 1.78");
  RooDataSet *rightdata = (RooDataSet*)databkg->reduce("d0Mass > 1.94 && d0Mass < 1.98");
  databkg->setWeightVar(0);
  rightdata->setWeightVar(0);
  leftdata->setWeightVar(0);

  TH3F *lefth = m2Kpi_d0mass.createHistogram("lefth",m2Kpi0_d0mass,d0Lifetime,"");
  leftdata->fillHistogram(lefth,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime));
  TH3F *righth = m2Kpi_d0mass.createHistogram("righth",m2Kpi0_d0mass,d0Lifetime,"");
  rightdata->fillHistogram(righth,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime));
  righth->Scale(lefth->Integral()/righth->Integral());
  lefth->Sumw2();
  righth->Sumw2();
  lefth->Add(righth);
  lefth->Sumw2();

  RooDataHist *lefthist = new RooDataHist("lefthist","lefthist",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),lefth);
  RooHistPdf Tot_comb("Tot_comb","Tot_comb",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),*lefthist);

  Float_t totnonorm = 1508. + 791. + 663. + 47.;
  Float_t ratio = nev/totnonorm;

  RooRealVar Nsig("Nsig","Nsig",1508.*ratio);
  RooRealVar Nmis("Nmis","Nmis",791.*ratio);
  RooRealVar Ncomb("Ncomb","Ncomb",(663. + 47.)*ratio);

  d0LifetimeErr.setBins(100);
  RooDataSet *ProtoData_err = (RooDataSet*)RSdata->reduce(RooArgSet(d0LifetimeErr));
  TH1F *err_sig_h = (TH1F*)d0LifetimeErr.createHistogram("err_sig_h");
  ProtoData_err->fillHistogram(err_sig_h,RooArgSet(d0LifetimeErr));
  RooDataHist terr_sig("terr_sig","terr_sig",RooArgSet(d0LifetimeErr),err_sig_h);
  RooHistPdf terr_sig_pdf("terr_sig_pdf","terr_sig_pdf",RooArgSet(d0LifetimeErr),terr_sig,3);
  d0LifetimeErr.setBins(10);

  RooDataSet *ProtoData_bkg = (RooDataSet*)databkg->reduce(RooArgSet(d0LifetimeErr));
  TH1F *err_bkg_h = (TH1F*)d0LifetimeErr.createHistogram("err_bkg_h");
  ProtoData_bkg->fillHistogram(err_bkg_h,RooArgSet(d0LifetimeErr));
  err_bkg_h->Scale(err_sig_h->Integral()/err_bkg_h->Integral());
  RooDataHist terr_bkg("terr_bkg","terr_bkg",RooArgSet(d0LifetimeErr),err_bkg_h);
  RooHistPdf terr_bkg_pdf("terr_bkg_pdf","terr_bkg_pdf",RooArgSet(d0LifetimeErr),terr_bkg,3);

  RooDataSet *ProtoData_flav_1 = (RooDataSet*)RSdata->reduce(RooArgSet(D0flav));
  RooDataSet *ProtoData_flav = (RooDataSet*)ProtoData_flav_1->reduce(EventRange(1,(Int_t)((1508 + 791)*ratio)));
  //RooDataHist flav_sig("flav_sig","flav_sig",RooArgSet(D0flav),*ProtoData_flav);
  //RooHistPdf flav_sig_pdf("flav_sig_pdf","flav_sig_pdf",RooArgSet(D0flav),flav_sig);

  RooDataSet *ProtoData_flav_bkg_1 = (RooDataSet*)databkg->reduce(RooArgSet(D0flav));
  RooDataSet *ProtoData_flav_bkg = (RooDataSet*)ProtoData_flav_bkg_1->reduce(EventRange(1,(Int_t)((663 + 47)*ratio)));
  //RooDataHist flav_bkg("flav_bkg","flav_bkg",RooArgSet(D0flav),*ProtoData_flav_bkg);
  //RooHistPdf flav_bkg_pdf("flav_bkg_pdf","flav_bkg_pdf",RooArgSet(D0flav),flav_bkg);

  ProtoData_flav->append(*ProtoData_flav_bkg);

  RooProdPdf totsig_norm("totsig_norm","totsig_norm",RooArgSet(terr_sig_pdf),Conditional(TOTTime,observ));
  RooProdPdf totmis_norm("totmis_norm","totmis_norm",RooArgSet(terr_sig_pdf),Conditional(Tot_mis,observ));
  RooProdPdf totbkg_norm("totbkg_norm","totbkg_norm",RooArgSet(terr_bkg_pdf),Conditional(Tot_comb,observ));
  /*
  RooProdPdf totsig_norm("totsig_norm","totsig_norm",RooArgSet(terr_sig_pdf),Conditional(TOTsigD0,observ));
  RooProdPdf totmis_norm("totmis_norm","totmis_norm",RooArgSet(terr_sig_pdf),Conditional(Tot_mis,observ));
  RooProdPdf totbkg_norm("totbkg_norm","totbkg_norm",RooArgSet(terr_bkg_pdf),Conditional(Tot_comb,observ));
  */
  //Signal + background
  RooAddPdf TOTpdf("TOTpdf","TOTpdf",RooArgList(totsig_norm,totmis_norm,totbkg_norm),RooArgList(Nsig,Nmis,Ncomb));

  RooMCStudy mgr(totsig_norm,tot_var,FitOptions(Save(1),Extended(0),Minos(0)),Extended(0),ConditionalObservables(D0flav),RooFit::ProtoData(*ProtoData_flav,1));
  //RooMCStudy mgr(totsig_norm,tot_var,FitOptions(ConditionalObservables(RooArgSet(D0flav)),Save(1),Extended(0)),Extended(0),RooFit::ProtoData(*ConditDataset,1));

  TString dataname(filename);
  dataname.Append(".dat");
  TString toyname(filename);
  toyname.Append("_fixed.root");

  if(doGen && !doFit) mgr.generate(nexp,nev,kFALSE,dataname);
  if(doFit && !doGen) mgr.fit(nexp,dataname);
  if(doGen && doFit) mgr.generateAndFit(nexp,nev,kFALSE,dataname);

  if(doFit){
  TFile f(toyname,"RECREATE");
  f.cd();
  (RooFitResult*)mgr.fitResult(0)->Write();
  mgr.fitParDataSet().tree().Write();
  f.Close();
  }

  if(extract){

  RooFitResult *theRes = (RooFitResult*)mgr.fitResult(0);

    RooRealVar myc1("myc1","myc1",-10.,10.);
    RooRealVar myc2("myc2","myc2",-10.,10.);
    RooRealVar myratio("myratio","myratio",0.,0.,1.);
    RooRealVar myx("myx","myx",0.,-1.,1.);
    RooRealVar myy("myy","myy",0.,-1.,1.);

    Double_t NrsNws = 2760./1198329;
    Double_t ratioerr = sqrt(pow(96.,2.) + pow(NrsNws,2.)*pow(2760.,2.))/1198329.;
    RooDataSet *parFloat = new RooDataSet("parFloat","parFloat",RooArgList(myratio,myx,myy));

    RooTimepdf mysigD0("mysigD0","mysigD0",d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass,gm,&dalitzSpace,tau,c1,c2,-1,dirname);
    Double_t myDenom = mysigD0.createIntegral(RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime))->getVal();

    cout << "x' " << c2.getVal()*sqrt(NrsNws/myDenom) << endl;
    cout << "y' " << c1.getVal()*sqrt(NrsNws/myDenom) << endl;
    cout << "r0^2 " << NrsNws/myDenom << endl;

    for(Int_t j=0;j<1000;j++){
      cout << "Performing step number " << j << endl;
      RooArgList floated = theRes->randomizePars();
      myc1.setVal(((RooAbsReal*)floated.find("c1"))->getVal());
      myc2.setVal(((RooAbsReal*)floated.find("c2"))->getVal());

      Double_t myDenom = mysigD0.createIntegral(RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime))->getVal();
      Double_t myNum = RooRandom::randomGenerator()->Gaus(NrsNws,ratioerr);

      myratio.setVal(myNum/myDenom);
      myx.setVal(myc2.getVal()*sqrt((myNum/myDenom)));
      myy.setVal(myc1.getVal()*sqrt((myNum/myDenom)));

      parFloat->add(RooArgSet(myratio,myx,myy));
    }

    TString floatname(filename);
    floatname.Append("_float.root");

    TFile *f1 = new TFile(floatname,"RECREATE");
    f1->cd();
    parFloat->Write();
    f1->Close();
  }

  return 0;
}
int main(int argc, char *argv[]){

	OptionParser(argc,argv);
	

	RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);
	RooMsgService::instance().setSilentMode(true);


  
	system(Form("mkdir -p %s",outdir_.c_str()));

	vector<string> procs;
	split(infilenames_,infilenamesStr_,boost::is_any_of(","));
  
   TPython::Exec("import os,imp,re");
    const char * env = gSystem->Getenv("CMSSW_BASE") ; 
      std::string globeRt = env;
      TPython::Exec(Form("buildSMHiggsSignalXSBR = imp.load_source('*', '%s/src/flashggFinalFit/Signal/python/buildSMHiggsSignalXSBR.py')",globeRt.c_str()));
      TPython::Eval(Form("buildSMHiggsSignalXSBR.Init%dTeV()", 13));
   for (unsigned int i =0 ; i<infilenames_.size() ; i++){
	    int mH  =(int) TPython::Eval(Form("int(re.search('_M(.+?)_','%s').group(1))",infilenames_[i].c_str())); 
	   double WH_XS  =  (double)TPython::Eval(Form("buildSMHiggsSignalXSBR.getXS(%d,'%s')",mH,"WH"));
	   double ZH_XS  =  (double)TPython::Eval(Form("buildSMHiggsSignalXSBR.getXS(%d,'%s')",mH,"ZH"));
     float tot_XS = WH_XS + ZH_XS;
     float wFrac=  WH_XS /tot_XS ;
     float zFrac=  ZH_XS /tot_XS ;
      std::cout << "mass "<< mH << " wh fraction "<< WH_XS /tot_XS << ", zh fraction "<< ZH_XS /tot_XS <<std::endl; 
     TFile *infile =  TFile::Open(infilenames_[i].c_str());
	   string outname  =(string) TPython::Eval(Form("'%s'.split(\"/\")[-1].replace(\"VH\",\"WH_VH\")",infilenames_[i].c_str())); 
     TFile *outfile = TFile::Open(outname.c_str(),"RECREATE") ;
    TDirectory* saveDir = outfile->mkdir("tagsDumper");
    saveDir->cd();

    RooWorkspace *inWS = (RooWorkspace*) infile->Get("tagsDumper/cms_hgg_13TeV");
    RooRealVar *intLumi = (RooRealVar*)inWS->var("IntLumi");
    RooWorkspace *outWS = new RooWorkspace("cms_hgg_13TeV");
    outWS->import(*intLumi);
    std::list<RooAbsData*> data =  (inWS->allData()) ;
    std::cout <<" [INFO] Reading WS dataset contents: "<< std::endl;
        for (std::list<RooAbsData*>::const_iterator iterator = data.begin(), end = data.end(); iterator != end; ++iterator )  {
              RooDataSet *dataset = dynamic_cast<RooDataSet *>( *iterator );
              if (dataset) {
	            string zhname  =(string) TPython::Eval(Form("'%s'.replace(\"wzh\",\"zh\")",dataset->GetName())); 
	            string whname  =(string) TPython::Eval(Form("'%s'.replace(\"wzh\",\"wh\")",dataset->GetName())); 
              RooDataSet *datasetZH = (RooDataSet*) dataset->emptyClone(zhname.c_str(),zhname.c_str());
              RooDataSet *datasetWH = (RooDataSet*) dataset->emptyClone(whname.c_str(),whname.c_str());
                TRandom3 r;
                r.Rndm();
                double x[dataset->numEntries()];
                r.RndmArray(dataset->numEntries(),x);
                for (int j =0; j < dataset->numEntries() ; j++){
                    
                    if( x[j] < wFrac){
                    dataset->get(j);
                    datasetWH->add(*(dataset->get(j)),dataset->weight());
                    } else{
                    dataset->get(j);
                    datasetZH->add(*(dataset->get(j)),dataset->weight());
                    }
                }
              float w =datasetWH->sumEntries();
              float z =datasetZH->sumEntries();
           if(verbose_){
              std::cout << "Original dataset " << *dataset <<std::endl;
              std::cout << "WH       dataset " << *datasetWH <<std::endl;
              std::cout << "ZH       dataset " << *datasetZH <<std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "WH fraction (obs) : WH " << w/(w+z) <<",   ZH "<< z/(w+z) << std::endl;
              std::cout << "WH fraction (exp) : WH " << wFrac <<",   ZH "<< zFrac << std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "********************************************" <<std::endl;
              }
               outWS->import(*datasetWH);
               outWS->import(*datasetZH);
                }
             RooDataHist *datahist = dynamic_cast<RooDataHist *>( *iterator );

              if (datahist) {
	            string zhname  =(string) TPython::Eval(Form("'%s'.replace(\"wzh\",\"zh\")",datahist->GetName())); 
	            string whname  =(string) TPython::Eval(Form("'%s'.replace(\"wzh\",\"wh\")",datahist->GetName())); 
              RooDataHist *datahistZH = (RooDataHist*) datahist->emptyClone(zhname.c_str(),zhname.c_str());
              RooDataHist *datahistWH = (RooDataHist*) datahist->emptyClone(whname.c_str(),whname.c_str());
                TRandom3 r;
                r.Rndm();
                double x[datahist->numEntries()];
                r.RndmArray(datahist->numEntries(),x);
                for (int j =0; j < datahist->numEntries() ; j++){
                    
                    datahistWH->add(*(datahist->get(j)),datahist->weight()*wFrac);
                    datahistZH->add(*(datahist->get(j)),datahist->weight()*zFrac);
                }
              float w =datahistWH->sumEntries();
              float z =datahistZH->sumEntries();
           if(verbose_){
              std::cout << "Original datahist " << *datahist <<std::endl;
              std::cout << "WH       datahist " << *datahistWH <<std::endl;
              std::cout << "ZH       datahist " << *datahistZH <<std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "WH fraction (obs) : WH " << w/(w+z) <<",   ZH "<< z/(w+z) << std::endl;
              std::cout << "WH fraction (exp) : WH " << wFrac <<",   ZH "<< zFrac << std::endl;
              std::cout << "********************************************" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "" <<std::endl;
              std::cout << "********************************************" <<std::endl;
              }
               outWS->import(*datahistWH);
               outWS->import(*datahistZH);
                }
                  }
   saveDir->cd();
   outWS->Write();
   outfile->Close();
   infile->Close();
   }
}
///
/// Perform the 1d Prob scan.
/// Saves chi2 values and the prob-Scan p-values in a root tree
/// For the datasets stuff, we do not yet have a MethodDatasetsProbScan class, so we do it all in
/// MethodDatasetsProbScan
/// \param nRun Part of the root tree file name to facilitate parallel production.
///
int MethodDatasetsProbScan::scan1d(bool fast, bool reverse)
{
	if (fast) return 0; // tmp

	if ( arg->debug ) cout << "MethodDatasetsProbScan::scan1d() : starting ... " << endl;

    // Set limit to all parameters.
    this->loadParameterLimits(); /// Default is "free", if not changed by cmd-line parameter


    // Define scan parameter and scan range.
    RooRealVar *parameterToScan = w->var(scanVar1);
    float parameterToScan_min = hCL->GetXaxis()->GetXmin();
    float parameterToScan_max = hCL->GetXaxis()->GetXmax();

		// do a free fit
		RooFitResult *result = this->loadAndFit(this->pdf); // fit on data
		assert(result);
    RooSlimFitResult *slimresult = new RooSlimFitResult(result,true);
		slimresult->setConfirmed(true);
		solutions.push_back(slimresult);
		double freeDataFitValue = w->var(scanVar1)->getVal();

    // Define outputfile
    system("mkdir -p root");
    TString probResName = Form("root/scan1dDatasetsProb_" + this->pdf->getName() + "_%ip" + "_" + scanVar1 + ".root", arg->npoints1d);
    TFile* outputFile = new TFile(probResName, "RECREATE");

    // Set up toy root tree
    this->probScanTree = new ToyTree(this->pdf, arg);
    this->probScanTree->init();
    this->probScanTree->nrun = -999; //\todo: why does this branch even exist in the output tree of the prob scan?

    // Save parameter values that were active at function
    // call. We'll reset them at the end to be transparent
    // to the outside.
    RooDataSet* parsFunctionCall = new RooDataSet("parsFunctionCall", "parsFunctionCall", *w->set(pdf->getParName()));
    parsFunctionCall->add(*w->set(pdf->getParName()));

    // start scan
    cout << "MethodDatasetsProbScan::scan1d_prob() : starting ... with " << nPoints1d << " scanpoints..." << endl;
    ProgressBar progressBar(arg, nPoints1d);
    for ( int i = 0; i < nPoints1d; i++ )
    {
        progressBar.progress();
        // scanpoint is calculated using min, max, which are the hCL x-Axis limits set in this->initScan()
        // this uses the "scan" range, as expected
        // don't add half the bin size. try to solve this within plotting method

        float scanpoint = parameterToScan_min + (parameterToScan_max - parameterToScan_min) * (double)i / ((double)nPoints1d - 1);
				if (arg->debug) cout << "DEBUG in MethodDatasetsProbScan::scan1d_prob() " << scanpoint << " " << parameterToScan_min << " " << parameterToScan_max << endl;

        this->probScanTree->scanpoint = scanpoint;

        if (arg->debug) cout << "DEBUG in MethodDatasetsProbScan::scan1d_prob() - scanpoint in step " << i << " : " << scanpoint << endl;

        // don't scan in unphysical region
        // by default this means checking against "free" range
        if ( scanpoint < parameterToScan->getMin() || scanpoint > parameterToScan->getMax() + 2e-13 ) {
            cout << "it seems we are scanning in an unphysical region: " << scanpoint << " < " << parameterToScan->getMin() << " or " << scanpoint << " > " << parameterToScan->getMax() + 2e-13 << endl;
            exit(EXIT_FAILURE);
        }

        // FIT TO REAL DATA WITH FIXED HYPOTHESIS(=SCANPOINT).
        // THIS GIVES THE NUMERATOR FOR THE PROFILE LIKELIHOOD AT THE GIVEN HYPOTHESIS
        // THE RESULTING NUISANCE PARAMETERS TOGETHER WITH THE GIVEN HYPOTHESIS ARE ALSO
        // USED WHEN SIMULATING THE TOY DATA FOR THE FELDMAN-COUSINS METHOD FOR THIS HYPOTHESIS(=SCANPOINT)
        // Here the scanvar has to be fixed -> this is done once per scanpoint
        // and provides the scanner with the DeltaChi2 for the data as reference
        // additionally the nuisances are set to the resulting fit values

        parameterToScan->setVal(scanpoint);
        parameterToScan->setConstant(true);

        RooFitResult *result = this->loadAndFit(this->pdf); // fit on data
        assert(result);

        if (arg->debug) {
            cout << "DEBUG in MethodDatasetsProbScan::scan1d_prob() - minNll data scan at scan point " << scanpoint << " : " << 2 * result->minNll() << ": "<< 2 * pdf->getMinNll() << endl;
        }
        this->probScanTree->statusScanData = result->status();

        // set chi2 of fixed fit: scan fit on data
        // CAVEAT: chi2min from fitresult gives incompatible results to chi2min from pdf
        // this->probScanTree->chi2min           = 2 * result->minNll();
        this->probScanTree->chi2min           = 2 * pdf->getMinNll();
        this->probScanTree->covQualScanData   = result->covQual();
        this->probScanTree->scanbest  = freeDataFitValue;

        // After doing the fit with the parameter of interest constrained to the scanpoint,
        // we are now saving the fit values of the nuisance parameters. These values will be
        // used to generate toys according to the PLUGIN method.
        this->probScanTree->storeParsScan(); // \todo : figure out which one of these is semantically the right one

        this->pdf->deleteNLL();

        // also save the chi2 of the free data fit to the tree:
        this->probScanTree->chi2minGlobal = this->getChi2minGlobal();
        this->probScanTree->chi2minBkg = this->getChi2minBkg();

        this->probScanTree->genericProbPValue = this->getPValueTTestStatistic(this->probScanTree->chi2min - this->probScanTree->chi2minGlobal);
        this->probScanTree->fill();

        if(arg->debug && pdf->getBkgPdf())
        {
            float pval_cls = this->getPValueTTestStatistic(this->probScanTree->chi2min - this->probScanTree->chi2minBkg, true);
            cout << "DEBUG in MethodDatasetsProbScan::scan1d() - p value CLs: " << pval_cls << endl;
        }


        // reset
        setParameters(w, pdf->getParName(), parsFunctionCall->get(0));
        //setParameters(w, pdf->getObsName(), obsDataset->get(0));
    } // End of npoints loop
    probScanTree->writeToFile();
    if (bkgOnlyFitResult) bkgOnlyFitResult->Write();
    if (dataFreeFitResult) dataFreeFitResult->Write();
    outputFile->Close();
    std::cout << "Wrote ToyTree to file" << std::endl;
    delete parsFunctionCall;

    // This is kind of a hack. The effect is supposed to be the same as callincg
    // this->sethCLFromProbScanTree(); here, but the latter gives a segfault somehow....
    // \todo: use this->sethCLFromProbScanTree() directly after figuring out the cause of the segfault.
    this->loadScanFromFile();

    return 0;
}
예제 #15
0
void embeddedToysVBF_1DKD(int nEvts=50, int nToys=100,
		  sample mySample = kScalar_fa3_0){
  

  RooRealVar* kd = new RooRealVar("psMELA","psMELA",0,1);
  kd->setBins(50);
  RooPlot* kdframe1 = kd->frame();
  
  // 0- template
  TFile f1("ggH2j_KDdistribution_ps.root", "READ"); 
  TH2F *h_KD_ps = (TH2F*)f1.Get("h_KD");
  h_KD_ps->SetName("h_KD_ps");
  RooDataHist rdh_KD_ps("rdh_KD_ps","rdh_KD_ps",RooArgList(*kd),h_KD_ps);
  RooHistPdf pdf_KD_ps("pdf_KD_ps","pdf_KD_ps",RooArgList(*kd),rdh_KD_ps); 

  // 0+ template
  TFile f2("ggH2j_KDdistribution_sm.root", "READ"); 
  TH2F *h_KD_sm = (TH2F*)f2.Get("h_KD");
  h_KD_sm->SetName("h_KD_sm");
  RooDataHist rdh_KD_sm("rdh_KD_sm","rdh_KD_sm",RooArgList(*kd),h_KD_sm);
  RooHistPdf pdf_KD_sm("pdf_KD_sm","pdf_KD_sm",RooArgList(*kd),rdh_KD_sm); 

  RooRealVar rrv_fa3("fa3","fa3",0.5,0.,1.);  //free parameter of the model
  RooAddPdf model("model","ps+sm",pdf_KD_ps,pdf_KD_sm,rrv_fa3);  
  rrv_fa3.setConstant(kFALSE);

 TCanvas* c = new TCanvas("modelPlot","modelPlot",400,400);
  rdh_KD_ps.plotOn(kdframe1,LineColor(kBlack));
  pdf_KD_ps.plotOn(kdframe1,LineColor(kBlack));
  rdh_KD_sm.plotOn(kdframe1,LineColor(kBlue));
  pdf_KD_sm.plotOn(kdframe1,LineColor(kBlue));
  model.plotOn(kdframe1,LineColor(kRed));
  kdframe1->Draw();
  c->SaveAs("model1DPlot.png");
  c->SaveAs("model1DPlot.eps");

  double fa3Val=-99;
  if (mySample == kScalar_fa3_0)
    fa3Val=0.;
  else if (mySample == kScalar_fa3_1)
    fa3Val=1;
  else{
    cout<<"fa3Val not correct!"<<endl;
      return 0;
  }

  TCanvas* c = new TCanvas("modelPlot","modelPlot",400,400);
  rdh_KD_ps.plotOn(kdframe1,LineColor(kBlack));
  pdf_KD_ps.plotOn(kdframe1,LineColor(kBlack));
  rdh_KD_sm.plotOn(kdframe1,LineColor(kBlue));
  pdf_KD_sm.plotOn(kdframe1,LineColor(kBlue));
  model.plotOn(kdframe1,LineColor(kRed));
  kdframe1->Draw();

  
  TChain* myChain = new TChain("newTree");
  myChain->Add(inputFileNames[mySample]);
  
  if(!myChain || myChain->GetEntries()<=0) {
    cout<<"error in the tree"<<endl;
    return 0;
  }
  
   RooDataSet* data = new RooDataSet("data","data",myChain,RooArgSet(*kd),"");

    cout << "Number of events in data: " << data->numEntries() << endl;
  
  // initialize tree to save toys to 
  TTree* results = new TTree("results","toy results");
  
  double fa3,fa3Error, fa3Pull;
  double fa2,fa2Error, fa2Pull;
  double phia2, phia2Error, phia2Pull;
  double phia3, phia3Error, phia3Pull;

  results->Branch("fa3",&fa3,"fa3/D");
  results->Branch("fa3Error",&fa3Error,"fa3Error/D");
  results->Branch("fa3Pull",&fa3Pull,"fa3Pull/D");

  //---------------------------------

  RooDataSet* toyData;
  int embedTracker=0;
  RooArgSet *tempEvent;

  RooFitResult *toyfitresults;
  RooRealVar *r_fa3;

  for(int i = 0 ; i<nToys ; i++){
    cout <<i<<"<-----------------------------"<<endl;
    //if(toyData) delete toyData;
    toyData = new RooDataSet("toyData","toyData",RooArgSet(*kd));

    if(nEvts+embedTracker > data->sumEntries()){
      cout << "Playground::generate() - ERROR!!! Playground::data does not have enough events to fill toy!!!!  bye :) " << endl;
      toyData = NULL;
      abort();
      return 0;
    }

    for(int iEvent=0; iEvent<nEvts; iEvent++){
      if(iEvent==1)
	cout << "generating event: " << iEvent << " embedTracker: " << embedTracker << endl;
      tempEvent = (RooArgSet*) data->get(embedTracker);
      toyData->add(*tempEvent);
      embedTracker++;
    }

    toyfitresults =model.fitTo(*toyData,Save());
    cout<<toyfitresults<<endl;
    r_fa3 = (RooRealVar *) toyfitresults->floatParsFinal().find("fa3");

    fa3 = r_fa3->getVal();
    fa3Error = r_fa3->getError();
    fa3Pull = (r_fa3->getVal() - fa3Val) / r_fa3->getError();

    // fill TTree
    results->Fill();
    //model.clear();
  }

  char nEvtsString[100];
  sprintf(nEvtsString,"_%iEvts",nEvts);

  // write tree to output file (ouputFileName set at top)
  TFile *outputFile = new TFile("embeddedToysVBF_fa3Corr_"+sampleName[mySample]+nEvtsString+".root","RECREATE");
  results->Write();
  outputFile->Close();

}
예제 #16
0
void KinZfitter::MakeModel(/*RooWorkspace &w,*/ KinZfitter::FitInput &input, KinZfitter::FitOutput &output) {

     //lep
     RooRealVar pTRECO1_lep("pTRECO1_lep", "pTRECO1_lep", input.pTRECO1_lep, 5, 500);
     RooRealVar pTRECO2_lep("pTRECO2_lep", "pTRECO2_lep", input.pTRECO2_lep, 5, 500);
     RooRealVar pTMean1_lep("pTMean1_lep", "pTMean1_lep", 
                            input.pTRECO1_lep, max(5.0, input.pTRECO1_lep-2*input.pTErr1_lep), input.pTRECO1_lep+2*input.pTErr1_lep);
     RooRealVar pTMean2_lep("pTMean2_lep", "pTMean2_lep", 
                            input.pTRECO2_lep, max(5.0, input.pTRECO2_lep-2*input.pTErr2_lep), input.pTRECO2_lep+2*input.pTErr2_lep);
     RooRealVar pTSigma1_lep("pTSigma1_lep", "pTSigma1_lep", input.pTErr1_lep);
     RooRealVar pTSigma2_lep("pTSigma2_lep", "pTSigma2_lep", input.pTErr2_lep);
     RooRealVar theta1_lep("theta1_lep", "theta1_lep", input.theta1_lep);
     RooRealVar theta2_lep("theta2_lep", "theta2_lep", input.theta2_lep);
     RooRealVar phi1_lep("phi1_lep", "phi1_lep", input.phi1_lep);
     RooRealVar phi2_lep("phi2_lep", "phi2_lep", input.phi2_lep);
     RooRealVar m1("m1", "m1", input.m1);
     RooRealVar m2("m2", "m2", input.m2);

     //gamma
     RooRealVar pTRECO1_gamma("pTRECO1_gamma", "pTRECO1_gamma", input.pTRECO1_gamma, 5, 500);
     RooRealVar pTRECO2_gamma("pTRECO2_gamma", "pTRECO2_gamma", input.pTRECO2_gamma, 5, 500);
     RooRealVar pTMean1_gamma("pTMean1_gamma", "pTMean1_gamma", 
                              input.pTRECO1_gamma, max(0.5, input.pTRECO1_gamma-2*input.pTErr1_gamma), input.pTRECO1_gamma+2*input.pTErr1_gamma);
     RooRealVar pTMean2_gamma("pTMean2_gamma", "pTMean2_gamma", 
                              input.pTRECO2_gamma, max(0.5, input.pTRECO2_gamma-2*input.pTErr2_gamma), input.pTRECO2_gamma+2*input.pTErr2_gamma);
     RooRealVar pTSigma1_gamma("pTSigma1_gamma", "pTSigma1_gamma", input.pTErr1_gamma);
     RooRealVar pTSigma2_gamma("pTSigma2_gamma", "pTSigma2_gamma", input.pTErr2_gamma);
     RooRealVar theta1_gamma("theta1_gamma", "theta1_gamma", input.theta1_gamma);
     RooRealVar theta2_gamma("theta2_gamma", "theta2_gamma", input.theta2_gamma);
     RooRealVar phi1_gamma("phi1_gamma", "phi1_gamma", input.phi1_gamma);
     RooRealVar phi2_gamma("phi2_gamma", "phi2_gamma", input.phi2_gamma);

     //gauss
     RooGaussian gauss1_lep("gauss1_lep", "gauss1_lep", pTRECO1_lep, pTMean1_lep, pTSigma1_lep);
     RooGaussian gauss2_lep("gauss2_lep", "gauss2_lep", pTRECO2_lep, pTMean2_lep, pTSigma2_lep);
     RooGaussian gauss1_gamma("gauss1_gamma", "gauss1_gamma", pTRECO1_gamma, pTMean1_gamma, pTSigma1_gamma);
     RooGaussian gauss2_gamma("gauss2_gamma", "gauss2_gamma", pTRECO2_gamma, pTMean2_gamma, pTSigma2_gamma);


     TString makeE_lep = "TMath::Sqrt((@0*@0)/((TMath::Sin(@1))*(TMath::Sin(@1)))+@2*@2)";
     RooFormulaVar E1_lep("E1_lep", makeE_lep, RooArgList(pTMean1_lep, theta1_lep, m1));  //w.import(E1_lep);
     RooFormulaVar E2_lep("E2_lep", makeE_lep, RooArgList(pTMean2_lep, theta2_lep, m2));  //w.import(E2_lep);

     TString makeE_gamma = "TMath::Sqrt((@0*@0)/((TMath::Sin(@1))*(TMath::Sin(@1))))";
     RooFormulaVar E1_gamma("E1_gamma", makeE_gamma, RooArgList(pTMean1_gamma, theta1_gamma));  //w.import(E1_gamma);
     RooFormulaVar E2_gamma("E2_gamma", makeE_gamma, RooArgList(pTMean2_gamma, theta2_gamma));  //w.import(E2_gamma);

     //dotProduct 3d
     TString dotProduct_3d = "@0*@1*( ((TMath::Cos(@2))*(TMath::Cos(@3)))/((TMath::Sin(@2))*(TMath::Sin(@3)))+(TMath::Cos(@4-@5)))";
     RooFormulaVar p1v3D2("p1v3D2", dotProduct_3d, RooArgList(pTMean1_lep, pTMean2_lep, theta1_lep, theta2_lep, phi1_lep, phi2_lep));
     RooFormulaVar p1v3Dph1("p1v3Dph1", dotProduct_3d, RooArgList(pTMean1_lep, pTMean1_gamma, theta1_lep, theta1_gamma, phi1_lep, phi1_gamma));
     RooFormulaVar p2v3Dph1("p2v3Dph1", dotProduct_3d, RooArgList(pTMean2_lep, pTMean1_gamma, theta2_lep, theta1_gamma, phi2_lep, phi1_gamma));
     RooFormulaVar p1v3Dph2("p1v3Dph2", dotProduct_3d, RooArgList(pTMean1_lep, pTMean2_gamma, theta1_lep, theta2_gamma, phi1_lep, phi2_gamma));
     RooFormulaVar p2v3Dph2("p2v3Dph2", dotProduct_3d, RooArgList(pTMean2_lep, pTMean2_gamma, theta2_lep, theta2_gamma, phi2_lep, phi2_gamma));
     RooFormulaVar ph1v3Dph2("ph1v3Dph2", dotProduct_3d, RooArgList(pTMean1_gamma, pTMean2_gamma, theta1_gamma, theta2_gamma, phi1_gamma, phi2_gamma));

     TString dotProduct_4d = "@0*@1-@2";
     RooFormulaVar p1D2("p1D2", dotProduct_4d, RooArgList(E1_lep, E2_lep, p1v3D2));  //w.import(p1D2);
     RooFormulaVar p1Dph1("p1Dph1", dotProduct_4d, RooArgList(E1_lep, E1_gamma, p1v3Dph1));//  w.import(p1Dph1);
     RooFormulaVar p2Dph1("p2Dph1", dotProduct_4d, RooArgList(E2_lep, E1_gamma, p2v3Dph1)); // w.import(p2Dph1);
     RooFormulaVar p1Dph2("p1Dph2", dotProduct_4d, RooArgList(E1_lep, E2_gamma, p1v3Dph2));  //w.import(p1Dph2);
     RooFormulaVar p2Dph2("p2Dph2", dotProduct_4d, RooArgList(E2_lep, E2_gamma, p2v3Dph2));  //w.import(p2Dph2);
     RooFormulaVar ph1Dph2("ph1Dph2", dotProduct_4d, RooArgList(E1_gamma, E2_gamma, ph1v3Dph2)); // w.import(ph1Dph2);

     RooRealVar bwMean("bwMean", "m_{Z^{0}}", 91.187); //w.import(bwMean);
     RooRealVar bwGamma("bwGamma", "#Gamma", 2.5); 


     RooProdPdf* PDFRelBW;  
     RooFormulaVar* mZ;
     RooGenericPdf* RelBW;

     //mZ
     mZ = new RooFormulaVar("mZ", "TMath::Sqrt(2*@0+@1*@1+@2*@2)", RooArgList(p1D2, m1, m2));
     RelBW = new RooGenericPdf("RelBW","1/( pow(mZ*mZ-bwMean*bwMean,2)+pow(mZ,4)*pow(bwGamma/bwMean,2) )", RooArgSet(*mZ,bwMean,bwGamma) );
     PDFRelBW = new RooProdPdf("PDFRelBW", "PDFRelBW", RooArgList(gauss1_lep, gauss2_lep, *RelBW));     

     if (input.nFsr == 1) {

        mZ = new RooFormulaVar("mZ", "TMath::Sqrt(2*@0+2*@1+2*@2+@3*@3+@4*@4)", RooArgList(p1D2, p1Dph1, p2Dph1, m1, m2));
        RelBW = new RooGenericPdf("RelBW","1/( pow(mZ*mZ-bwMean*bwMean,2)+pow(mZ,4)*pow(bwGamma/bwMean,2) )", RooArgSet(*mZ,bwMean,bwGamma) );
//        PDFRelBW = new RooProdPdf("PDFRelBW", "PDFRelBW", RooArgList(gauss1_lep, gauss2_lep, gauss1_gamma, *RelBW));

        } 

     if (input.nFsr == 2) {

        mZ = new RooFormulaVar("mZ", "TMath::Sqrt(2*@0+2*@1+2*@2+2*@3+2*@4+2*@5+@6*@6+@7*@7)", RooArgList(p1D2,p1Dph1,p2Dph1,p1Dph2,p2Dph2,ph1Dph2, m1, m2));
        RelBW = new RooGenericPdf("RelBW","1/( pow(mZ*mZ-bwMean*bwMean,2)+pow(mZ,4)*pow(bwGamma/bwMean,2) )", RooArgSet(*mZ,bwMean,bwGamma) );
//        PDFRelBW = new RooProdPdf("PDFRelBW", "PDFRelBW", RooArgList(gauss1_lep, gauss2_lep, gauss1_gamma, gauss2_gamma, *RelBW));

        }

     //true shape
     RooRealVar sg("sg", "sg", sgVal_);
     RooRealVar a("a", "a", aVal_);
     RooRealVar n("n", "n", nVal_);

     RooCBShape CB("CB","CB",*mZ,bwMean,sg,a,n);
     RooRealVar f("f","f", fVal_);

     RooRealVar mean("mean","mean",meanVal_);
     RooRealVar sigma("sigma","sigma",sigmaVal_);
     RooRealVar f1("f1","f1",f1Val_);

     RooAddPdf *RelBWxCB;
     RelBWxCB = new RooAddPdf("RelBWxCB","RelBWxCB", *RelBW, CB, f);
     RooGaussian *gauss;
     gauss = new RooGaussian("gauss","gauss",*mZ,mean,sigma);
     RooAddPdf *RelBWxCBxgauss;
     RelBWxCBxgauss = new RooAddPdf("RelBWxCBxgauss","RelBWxCBxgauss", *RelBWxCB, *gauss, f1);

     RooProdPdf *PDFRelBWxCBxgauss;
     PDFRelBWxCBxgauss = new RooProdPdf("PDFRelBWxCBxgauss","PDFRelBWxCBxgauss", 
                                     RooArgList(gauss1_lep, gauss2_lep, *RelBWxCBxgauss) );


    //make fit
    RooArgSet *rastmp;
    rastmp = new RooArgSet(pTRECO1_lep, pTRECO2_lep);
/*
    if(input.nFsr == 1) {
      rastmp = new RooArgSet(pTRECO1_lep, pTRECO2_lep, pTRECO1_gamma);
      }

    if(input.nFsr == 2) {
      rastmp = new RooArgSet(pTRECO1_lep, pTRECO2_lep, pTRECO1_gamma, pTRECO2_gamma);
      }
*/
    RooDataSet* pTs = new RooDataSet("pTs","pTs", *rastmp);
    pTs->add(*rastmp);

    RooFitResult* r;
    if (mass4lRECO_ > 140) {

       r = PDFRelBW->fitTo(*pTs,RooFit::Save(),RooFit::PrintLevel(-1));

       } else {

              r = PDFRelBWxCBxgauss->fitTo(*pTs,RooFit::Save(),RooFit::PrintLevel(-1));

              }
    //save fit result
    const TMatrixDSym& covMatrix = r->covarianceMatrix();
    const RooArgList& finalPars = r->floatParsFinal();

    for (int i=0 ; i<finalPars.getSize(); i++){
 
        TString name = TString(((RooRealVar*)finalPars.at(i))->GetName());
        if(debug_) cout<<"name list of RooRealVar for covariance matrix "<<name<<endl;

    }

    int size = covMatrix.GetNcols();
    output.covMatrixZ.ResizeTo(size,size);
    output.covMatrixZ = covMatrix;
    
    output.pT1_lep = pTMean1_lep.getVal();
    output.pT2_lep = pTMean2_lep.getVal();
    output.pTErr1_lep = pTMean1_lep.getError();
    output.pTErr2_lep = pTMean2_lep.getError();
/*
    if (input.nFsr >= 1) {

       output.pT1_gamma = pTMean1_gamma.getVal();
       output.pTErr1_gamma = pTMean1_gamma.getError();
    
       }

    if (input.nFsr == 2) {

       output.pT2_gamma = pTMean2_gamma.getVal();
       output.pTErr2_gamma = pTMean2_gamma.getError();

       }
*/
    delete rastmp;
    delete pTs;
    delete PDFRelBW;
    delete mZ;
    delete RelBW;
    delete RelBWxCB;
    delete gauss;
    delete RelBWxCBxgauss;
    delete PDFRelBWxCBxgauss;
}
예제 #17
0
void createWorkspace(const std::string &infilename, int nState, bool correctCtau, bool drawRapPt2D) {
    gROOT->SetStyle("Plain");
    gStyle->SetTitleBorderSize(0);

    delete gRandom;
    gRandom = new TRandom3(23101987);

    // Set some strings
    const std::string workspacename = "ws_masslifetime",
                      treename = "selectedData";

    // Get the tree from the data file
    TFile *f = TFile::Open(infilename.c_str());
    TTree *tree = (TTree*)f->Get(treename.c_str());

    // Set branch addresses in tree to be able to import tree to roofit
    TLorentzVector* chic = new TLorentzVector;
    tree->SetBranchAddress("chic",&chic);
    TLorentzVector* chic_rf = new TLorentzVector;
    tree->SetBranchAddress("chic_rf",&chic_rf);
    TLorentzVector* jpsi = new TLorentzVector;
    tree->SetBranchAddress("jpsi",&jpsi);
    double lifetime = 0;
    tree->SetBranchAddress("Jpsict",&lifetime);
    double lifetimeErr = 0;
    tree->SetBranchAddress("JpsictErr",&lifetimeErr);

    char lifetimeTitle[200];

    sprintf(lifetimeTitle,"l^{#psi} [mm]");
    if(correctCtau) sprintf(lifetimeTitle,"l^{#chi} [mm]");

    // define variables necessary for J/Psi(Psi(2S)) mass,lifetime fit
    RooRealVar* JpsiMass =
        new RooRealVar("JpsiMass", "M^{#psi} [GeV]", onia::massMin, onia::massMax);
    RooRealVar* JpsiPt =
        new RooRealVar("JpsiPt", "p^{#psi}_{T} [GeV]", 0. ,1000.);
    RooRealVar* JpsiRap =
        new RooRealVar("JpsiRap", "y^{#psi}", -2., 2.);
    RooRealVar* chicMass =
        new RooRealVar("chicMass", "M^{#chi} [GeV]", onia::chimassMin, onia::chimassMax);
    RooRealVar* chicRap =
        new RooRealVar("chicRap", "y^{#chi}", -onia::chirap, onia::chirap);
    RooRealVar* chicPt =
        new RooRealVar("chicPt", "p^{#chi}_{T} [GeV]", 0. ,100.);
    RooRealVar* Jpsict =
        new RooRealVar("Jpsict", lifetimeTitle, onia::ctVarMin, onia::ctVarMax);
    RooRealVar* JpsictErr =
        new RooRealVar("JpsictErr", Form("Error on %s",lifetimeTitle), 0.0001, 1.);

    // Set bins
    Jpsict->setBins(10000,"cache");
    JpsiMass->setBins(10000,"cache");
    JpsiPt->setBins(100);
    JpsiRap->setBins(10000,"cache");
    chicMass->setBins(10000,"cache");
    //JpsictErr->setBins(100);
    JpsictErr->setBins(10000,"cache");

    // The list of data variables
    RooArgList dataVars(*JpsiMass,*JpsiPt,*JpsiRap,*chicMass,*chicRap,*chicPt,*Jpsict,*JpsictErr);

    // construct dataset to contain events
    RooDataSet* fullData = new RooDataSet("fullData","The Full Data From the Input ROOT Trees",dataVars);

    int entries = tree->GetEntries();
    cout << "entries " << entries << endl;

    int numEntriesTotal=0;
    int numEntriesInAnalysis=0;
    int numEntriesNotInAnalysis=0;



    /*
    	/// Read in 2011 data ctauErr-histos

    	char saveDir[200];
    	char PlotID[200];
    	char savename[200];
    	sprintf(saveDir,"/afs/hephy.at/scratch/k/knuenz/ChicPol/macros/polFit/Figures/CtauErrModel");
    	gSystem->mkdir(saveDir);
    	sprintf(PlotID,"2014May26_MoreLbins");
    	sprintf(saveDir,"%s/%s",saveDir,PlotID);
    	gSystem->mkdir(saveDir);
    	sprintf(savename,"%s/CtauErrModel_histograms.root",saveDir);

    	TFile *infile = new TFile(savename,"READ");
    	cout<<"opened file"<<endl;

    	const int nPT=5;
    	const int nRAP=2;
    	const int nL=15;

    	const double bordersPT[nPT+1] = {0., 12., 16., 20., 30., 100.};
    	const double bordersRAP[nRAP+1] = {0., 0.6, 2.};
    	const double bordersL[nL+1] = {onia::ctVarMin, -0.05, -0.03, -0.02, -0.015, -0.01, -0.005,  0., 0.005, 0.01, 0.015, 0.02, 0.03, 0.05, 0.1, onia::ctVarMax};

    	TH1D* h_ctauerr_2011[nRAP+1][nPT+1][nL+1];
    	TH1D* h_ctauerr_2012[nRAP+1][nPT+1][nL+1];

    	for(int iRAP = 0; iRAP < nRAP+1; iRAP++){
    		for(int iPT = 0; iPT < nPT+1; iPT++){
    			for(int iL = 0; iL < nL+1; iL++){

    				h_ctauerr_2011[iRAP][iPT][iL] = (TH1D*)infile->Get(Form("h_ctauerr_2011_rap%d_pt%d_l%d",iRAP, iPT, iL));
    				h_ctauerr_2012[iRAP][iPT][iL] = (TH1D*)infile->Get(Form("h_ctauerr_2012_rap%d_pt%d_l%d",iRAP, iPT, iL));

    			}
    		}
    	}
    	cout<<"opened hists"<<endl;

    	/// Finished reading in 2011 data ctauErr-histos
    */


    // loop through events in tree and save them to dataset
    for (int ientries = 0; ientries < entries; ientries++) {
        numEntriesTotal++;
        if (ientries%10000==0) std::cout << "event " << ientries << " of " << entries <<  std::endl;

        tree->GetEntry(ientries);

        double M_jpsi =jpsi->M();
        double pt_jpsi =jpsi->Pt();
        double y_jpsi =jpsi->Rapidity();
        double M =chic_rf->M();
        //double M =chic->M()-jpsi->M()+onia::MpsiPDG;
        double y=chic->Rapidity();
        double pt=chic->Pt();

        //if (ientries%3==0){
        //	M_jpsi = gRandom->Uniform(JpsiMass->getMin(), JpsiMass->getMax());
        //}


        //double JpsictErrRand = h_JpsictErr->GetRandom();
        //double JpsictErrRand2 = h_JpsictErr->GetRandom();
        //double JpsictMeanRand=0.;
        ////double pTcorrection=(pt-20.)*0.002;
        //
        ////JpsictErrRand-=pTcorrection;
        //if(JpsictErrRand<0) JpsictErrRand=0.001;
        ////JpsictErrRand2-=pTcorrection;
        //if(JpsictErrRand2<0) JpsictErrRand2=0.001;
        //
        //if (ientries%1000000==0){
        //	double exponent=0.4;
        //	JpsictMeanRand=gRandom->Exp(exponent);
        //}
        //
        //
        //lifetime = gRandom->Gaus(JpsictMeanRand,0.8*JpsictErrRand);
        //lifetimeErr = JpsictErrRand2;
        //if (ientries%3==0){
        //	lifetime = gRandom->Gaus(JpsictMeanRand,1.5*JpsictErrRand);
        //}
        //

        //double resCorrFactor=1.08;
        //if(lifetime<0)
        //	lifetimeErr/=resCorrFactor;


        /*
        		int iRAPindex=0;
        		int iPTindex=0;
        		int iLindex=0;

        		for(int iRAP = 1; iRAP < nRAP+1; iRAP++){
        			for(int iPT = 1; iPT < nPT+1; iPT++){
        				for(int iL = 1; iL < nL+1; iL++){

        					Double_t ptMin = bordersPT[iPT-1];;
        					Double_t ptMax = bordersPT[iPT];;
        					Double_t rapMin = bordersRAP[iRAP-1];;
        					Double_t rapMax = bordersRAP[iRAP];  ;
        					Double_t lMin = bordersL[iL-1];;
        					Double_t lMax = bordersL[iL];  ;

        					if(pt_jpsi>ptMin && pt_jpsi<ptMax && TMath::Abs(y_jpsi)>rapMin && TMath::Abs(y_jpsi)<rapMax && lifetime>lMin && lifetime<lMax){
        						iRAPindex=iRAP;
        						iPTindex=iPT;
        						iLindex=iL;
        					}

        				}

        			}
        		}

        		double lifetimeErrRand = h_ctauerr_2011[iRAPindex][iPTindex][iLindex]->GetRandom();

        		lifetimeErr = lifetimeErrRand;
        		if (ientries%10000==0){
        			std::cout << "Test output: lifetimeErr " << lifetimeErr << " randomly drawn from from " << h_ctauerr_2011[iRAPindex][iPTindex][iLindex]->GetName() <<  std::endl;
        		}

        */

        if (
            M > chicMass->getMin() && M < chicMass->getMax()
            && pt > chicPt->getMin() && pt < chicPt->getMax()
            && y > chicRap->getMin() && y < chicRap->getMax()
            && M_jpsi > JpsiMass->getMin() && M_jpsi < JpsiMass->getMax()
            && pt_jpsi > JpsiPt->getMin() && pt_jpsi < JpsiPt->getMax()
            && y_jpsi > JpsiRap->getMin() && y_jpsi < JpsiRap->getMax()
            && lifetime > Jpsict->getMin() && lifetime < Jpsict->getMax()
            && lifetimeErr > JpsictErr->getMin() && lifetimeErr < JpsictErr->getMax()
        ) {

            chicPt      ->setVal(pt);
            chicRap     ->setVal(y);
            chicMass    ->setVal(M);
            JpsiMass    ->setVal(M_jpsi);
            JpsiPt    	->setVal(pt_jpsi);
            JpsiRap     ->setVal(y_jpsi);
            Jpsict      ->setVal(lifetime);
            JpsictErr   ->setVal(lifetimeErr);

            //cout<<"JpsiRap->getVal() "<<JpsiRap->getVal()<<endl;

            fullData->add(dataVars);
            numEntriesInAnalysis++;
        }
        else {
            numEntriesNotInAnalysis++;
            //if (M < chicMass->getMin() || M > chicMass->getMax()) cout << "M " << M << endl;
            //if (pt < chicPt->getMin() || pt > chicPt->getMax()) cout << "pt " << pt << endl;
            //if (y < chicRap->getMin() || y > chicRap->getMax()) cout << "y " << y << endl;
            //if (lifetime < Jpsict->getMin() || lifetime > Jpsict->getMax()) cout << "lifetime " << lifetime << endl;
            //if (lifetimeErr < JpsictErr->getMin() || lifetimeErr > JpsictErr->getMax()) cout << "lifetimeErr " << lifetimeErr << endl;
            //cout << "M " << M << endl;
            //cout << "pt " << pt << endl;
            //cout << "y " << y << endl;
            //cout << "lifetime " << lifetime << endl;
            //cout << "lifetimeErr " << lifetimeErr << endl;
            //cout << " " << endl;

        }

    }//ientries

    //infile->Close();

    cout << "entries entering all bins " << fullData->sumEntries() << endl;
    cout << "numEntriesTotal " << numEntriesTotal << endl;
    cout << "numEntriesInAnalysis " << numEntriesInAnalysis << endl;
    cout << "numEntriesNotInAnalysis " << numEntriesNotInAnalysis << endl;

    //------------------------------------------------------------------------------------------------------------------
    // Define workspace and import datasets

    ////Get datasets binned in pT an y

    for(int iRap = 0; iRap <= onia::kNbRapForPTBins; iRap++) {

        Double_t yMin;
        Double_t yMax;
        if(iRap==0) {
            yMin = onia::rapForPTRange[0];
            yMax = onia::rapForPTRange[onia::kNbRapForPTBins];
        } else {
            yMin = onia::rapForPTRange[iRap-1];
            yMax = onia::rapForPTRange[iRap];
        }

        for(int iPT = 0; iPT <= onia::kNbPTBins[iRap]; iPT++) {
            //for(int iPT = 0; iPT <= 0; iPT++)

            Double_t ptMin;
            Double_t ptMax;
            if(iPT==0) {
                ptMin = onia::pTRange[iRap][0];
                ptMax = onia::pTRange[iRap][onia::kNbPTBins[0]];
            } else {
                ptMin = onia::pTRange[iRap][iPT-1];
                ptMax = onia::pTRange[iRap][iPT];
            }

            // output file name and workspace
            std::stringstream outfilename;
            outfilename << "tmpFiles/backupWorkSpace/ws_createWorkspace_Chi_rap" << iRap << "_pt" << iPT << ".root";
            RooWorkspace* ws = new RooWorkspace(workspacename.c_str());

            // define pt and y cuts on dataset
            std::stringstream cutString;

            if(onia::KinParticleChi && !onia::KinParticleChiButJpsiRap) {
                cutString << "(chicPt >= " << ptMin << " && chicPt < "<< ptMax << ") && "
                          << "(TMath::Abs(chicRap) >= " << yMin << " && TMath::Abs(chicRap) < " << yMax << ")";
            }
            if(!onia::KinParticleChi) {
                cutString << "(JpsiPt >= " << ptMin << " && JpsiPt < "<< ptMax << ") && "
                          << "(TMath::Abs(JpsiRap) >= " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";
            }
            if(onia::KinParticleChi && onia::KinParticleChiButJpsiRap) {
                cutString << "(chicPt >= " << ptMin << " && chicPt < "<< ptMax << ") && "
                          << "(TMath::Abs(JpsiRap) >= " << yMin << " && TMath::Abs(JpsiRap) < " << yMax << ")";
            }


            cout << "cutString: " << cutString.str().c_str() << endl;

            // get the dataset for the fit
            RooDataSet* binData = (RooDataSet*)fullData->reduce(cutString.str().c_str());
            std::stringstream name;
            name << "jpsi_data_rap" << iRap << "_pt" << iPT;
            binData->SetNameTitle(name.str().c_str(), "Data For Fitting");

            cout << "numEvents = " << binData->sumEntries() << endl;

            double chicMeanPt = binData->mean(*chicPt);
            RooRealVar var_chicMeanPt("var_chicMeanPt","var_chicMeanPt",chicMeanPt);
            if(!ws->var("var_chicMeanPt")) ws->import(var_chicMeanPt);
            else ws->var("var_chicMeanPt")->setVal(chicMeanPt);
            cout << "chicMeanPt = " << chicMeanPt << endl;

            double jpsiMeanPt = binData->mean(*JpsiPt);
            RooRealVar var_jpsiMeanPt("var_jpsiMeanPt","var_jpsiMeanPt",jpsiMeanPt);
            if(!ws->var("var_jpsiMeanPt")) ws->import(var_jpsiMeanPt);
            else ws->var("var_jpsiMeanPt")->setVal(jpsiMeanPt);
            cout << "jpsiMeanPt = " << jpsiMeanPt << endl;

            std::stringstream cutStringPosRapChic;
            cutStringPosRapChic << "chicRap > 0";
            RooDataSet* binDataPosRapChic = (RooDataSet*)binData->reduce(cutStringPosRapChic.str().c_str());
            double chicMeanAbsRap = binDataPosRapChic->mean(*chicRap);
            cout << "chicMeanAbsRap = " << chicMeanAbsRap << endl;
            RooRealVar var_chicMeanAbsRap("var_chicMeanAbsRap","var_chicMeanAbsRap",chicMeanAbsRap);
            if(!ws->var("var_chicMeanAbsRap")) ws->import(var_chicMeanAbsRap);
            else ws->var("var_chicMeanAbsRap")->setVal(chicMeanAbsRap);

            std::stringstream cutStringPosRapJpsi;
            cutStringPosRapJpsi << "JpsiRap > 0";
            RooDataSet* binDataPosRapJpsi = (RooDataSet*)binData->reduce(cutStringPosRapJpsi.str().c_str());
            double jpsiMeanAbsRap = binDataPosRapJpsi->mean(*JpsiRap);
            cout << "jpsiMeanAbsRap = " << jpsiMeanAbsRap << endl;
            RooRealVar var_jpsiMeanAbsRap("var_jpsiMeanAbsRap","var_jpsiMeanAbsRap",jpsiMeanAbsRap);
            if(!ws->var("var_jpsiMeanAbsRap")) ws->import(var_jpsiMeanAbsRap);
            else ws->var("var_jpsiMeanAbsRap")->setVal(jpsiMeanAbsRap);

            // Import variables to workspace
            ws->import(*binData);
            ws->writeToFile(outfilename.str().c_str());
        }//iPT
    }//iRap

    ////---------------------------------------------------------------
    ////--Integrating rapidity and pt bins, in +/- 3*sigma mass window
    ////---------------------------------------------------------------
    if(drawRapPt2D) {
        double yMin = onia::rapForPTRange[0];
        double yMax = 1.6;//onia::rapForPTRange[onia::kNbRapForPTBins];
        double ptMin =  onia::pTRange[0][0];
        double ptMax =  onia::pTRange[0][onia::kNbPTBins[0]];

        std::stringstream cutRapPt;
        cutRapPt << "(chicPt > " << ptMin << " && chicPt < "<< ptMax << ") && "
                 << "(TMath::Abs(chicRap) > " << yMin << " && TMath::Abs(chicRap) < " << yMax << ")";
        cout<<"cutRapPt: "<<cutRapPt.str().c_str()<<endl;

        RooDataSet* rapPtData = (RooDataSet*)fullData->reduce(cutRapPt.str().c_str());
        std::stringstream nameRapPt;
        nameRapPt << "data_rap0_pt0";
        rapPtData->SetNameTitle(nameRapPt.str().c_str(), "Data For full rap and pt");

        // output file name and workspace
        std::stringstream outfilename;
        outfilename << "tmpFiles/backupWorkSpace/ws_createWorkspace_Chi_rap0_pt0.root";
        RooWorkspace* ws_RapPt = new RooWorkspace(workspacename.c_str());
        //Import variables to workspace
        ws_RapPt->import(*rapPtData);
        ws_RapPt->writeToFile(outfilename.str().c_str());

        TH2D* rapPt;
        TH1D* rap1p2;
        double MassMin;
        double MassMax;

        rap1p2 = new TH1D("rap1p2","rap1p2",30,1.2, 1.8);
        if(nState==4) {
            rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72);
            MassMin=3.011;//massPsi1S-onia::nSigMass*sigma1S;
            MassMax=3.174;//massPsi1S+onia::nSigMass*sigma1S;
            // sigma  27.2 MeV
            // mean 3.093 GeV
        }
        if(nState==5) {
            rapPt = new TH2D( "rapPt", "rapPt", 64,-1.6,1.6,144,0,72); //  rap<1.5
            //rapPt = new TH2D( "rapPt", "rapPt", 52,-1.3,1.3,144,0,72); //  rap<1.2
            MassMin=3.576;//massPsi2S-onia::nSigMass*sigma2S;
            MassMax=3.786;//massPsi2S+onia::nSigMass*sigma2S;
            // sigma 34.9 MeV // pT > 7
            // sigma 34.3 MeV // pT > 10
            // mean 3.681 GeV
        }

        cout<<"Plotting rap-Pt for Psi"<<nState-3<<"S"<<endl;
        cout<<"MassMin for rap-Pt plot = "<<MassMin<<endl;
        cout<<"MassMax for rap-Pt plot = "<<MassMax<<endl;

        TTree *rapPtTree = (TTree*)rapPtData->tree();
        std::stringstream cutMass;
        cutMass<<"(chicMass > " << MassMin << " && chicMass < "<< MassMax << ")";
        //following two methods can only be used in root_v30, 34 does not work
        rapPtTree->Draw("chicPt:chicRap>>rapPt",cutMass.str().c_str(),"colz");
        cout<<"debug"<<endl;
        rapPtTree->Draw("TMath::Abs(chicRap)>>rap1p2",cutMass.str().c_str());

        TCanvas* c2 = new TCanvas("c2","c2",1200,1500);
        rapPt->SetYTitle("p_{T}(#mu#mu) [GeV]");
        rapPt->SetXTitle("y(#mu#mu)");
        gStyle->SetPalette(1);
        gPad->SetFillColor(kWhite);
        rapPt->SetTitle(0);
        rapPt->SetStats(0);
        gPad->SetLeftMargin(0.15);
        gPad->SetRightMargin(0.17);
        rapPt->GetYaxis()->SetTitleOffset(1.5);

        rapPt->Draw("colz");

        TLine* rapPtLine;

        for(int iRap=0; iRap<onia::kNbRapForPTBins+1; iRap++) {
            rapPtLine= new TLine( -onia::rapForPTRange[iRap], onia::pTRange[0][0], -onia::rapForPTRange[iRap], onia::pTRange[0][onia::kNbPTBins[iRap]] );
            rapPtLine->SetLineWidth( 2 );
            rapPtLine->SetLineStyle( 1 );
            rapPtLine->SetLineColor( kWhite );
            rapPtLine->Draw();
            rapPtLine= new TLine( onia::rapForPTRange[iRap], onia::pTRange[0][0], onia::rapForPTRange[iRap], onia::pTRange[0][onia::kNbPTBins[iRap]] );
            rapPtLine->SetLineWidth( 2 );
            rapPtLine->SetLineStyle( 1 );
            rapPtLine->SetLineColor( kWhite );
            rapPtLine->Draw();

            int pTBegin = 0;
            if(nState==5) pTBegin = 1;
            for(int iPt=pTBegin; iPt<onia::kNbPTBins[iRap+1]+1; iPt++) {
                rapPtLine= new TLine( -onia::rapForPTRange[onia::kNbRapForPTBins], onia::pTRange[0][iPt], onia::rapForPTRange[onia::kNbRapForPTBins], onia::pTRange[0][iPt] );
                rapPtLine->SetLineWidth( 2 );
                rapPtLine->SetLineStyle( 1 );
                rapPtLine->SetLineColor( kWhite );
                rapPtLine->Draw();
            }
        }

        char savename[200];
        sprintf(savename,"Figures/rapPt_Chi.pdf");
        c2->SaveAs(savename);

        TCanvas* c3 = new TCanvas("c3","c3",1500,1200);
        rap1p2->SetYTitle("Events");
        rap1p2->SetXTitle("y(#mu#mu)");
        rap1p2->SetTitle(0);
        rap1p2->SetStats(0);
        rap1p2->GetYaxis()->SetTitleOffset(1.2);
        rap1p2->Draw();
        sprintf(savename,"Figures/rap_Chi_1p2.pdf");
        c3->SaveAs(savename);
    }

    f->Close();
}
void embeddedToysWithBackgDetEffects_1DKD(int nEvts=600, int nToys=3000,
					  sample mySample = kScalar_fa3p5, 
					  bool bkg, bool sigFloating, int counter){
  
  RooRealVar* kd = new RooRealVar("psMELA","psMELA",0,1);
  kd->setBins(1000);
  RooPlot* kdframe1 = kd->frame();
  
  // 0- template
  TFile f1("KDdistribution_ps_analytical_detEff.root", "READ"); 
  TH1F *h_KD_ps = (TH1F*)f1.Get("h_KD");
  h_KD_ps->SetName("h_KD_ps");
  RooDataHist rdh_KD_ps("rdh_KD_ps","rdh_KD_ps",RooArgList(*kd),h_KD_ps);
  RooHistPdf pdf_KD_ps("pdf_KD_ps","pdf_KD_ps",RooArgList(*kd),rdh_KD_ps); 

  // 0+ template
  TFile f2("KDdistribution_sm_analytical_detEff.root", "READ"); 
  TH1F *h_KD_sm = (TH1F*)f2.Get("h_KD");
  h_KD_sm->SetName("h_KD_sm");
  RooDataHist rdh_KD_sm("rdh_KD_sm","rdh_KD_sm",RooArgList(*kd),h_KD_sm);
  RooHistPdf pdf_KD_sm("pdf_KD_sm","pdf_KD_sm",RooArgList(*kd),rdh_KD_sm); 

  // backg template
  TFile f3("KDdistribution_bkg_analytical_detEff.root", "READ"); 
  TH1F *h_KD_bkg = (TH1F*)f3.Get("h_KD");
  h_KD_bkg->SetName("h_KD_bkg");
  RooDataHist rdh_KD_bkg("rdh_KD_bkg","rdh_KD_bkg",RooArgList(*kd),h_KD_bkg);
  RooHistPdf pdf_KD_bkg("pdf_KD_bkg","pdf_KD_bkg",RooArgList(*kd),rdh_KD_bkg); 

  //Define signal model with 0+, 0- mixture
  RooRealVar rrv_fa3("fa3","fa3",0.5,0.,1.);  //free parameter of the model
  RooFormulaVar rfv_fa3Obs("fa3obs","1/ (1 + (1/@0 - 1)*0.99433)",RooArgList(rrv_fa3));
  RooAddPdf modelSignal("modelSignal","ps+sm",pdf_KD_ps,pdf_KD_sm,rfv_fa3Obs);  
  rrv_fa3.setConstant(kFALSE);
  
  //Define signal+bakground model
  RooRealVar rrv_BoverTOT("BoverTOT","BoverTOT",1/(3.75+1),0.,10.);  
  RooAddPdf model("model","background+modelSignal",pdf_KD_bkg,modelSignal,rrv_BoverTOT);  
  if(sigFloating)
    rrv_BoverTOT.setConstant(kFALSE);
  else
    rrv_BoverTOT.setConstant(kTRUE);

  //Set the values of free parameters to compute pulls
  double fa3Val=-99;
  if (mySample == kScalar_fa3p0)
    fa3Val=0.;
  else if (mySample == kScalar_fa3p1)
    fa3Val=0.1;
  else if (mySample == kScalar_fa3p5 || mySample == kScalar_fa3p5phia390)
    fa3Val=0.5;
  else if (mySample == kScalar_fa3p25)
    fa3Val=0.25;
  else{
    cout<<"fa3Val not correct!"<<endl;
      return 0;
  }
  double sigFracVal=1 - 1/(3.75+1);

  //Plot the models
  TCanvas* c = new TCanvas("modelPlot_detBkg","modelPlot_detBkg",400,400);
  rdh_KD_ps.plotOn(kdframe1,LineColor(kBlack),MarkerColor(kBlack));
  pdf_KD_ps.plotOn(kdframe1,LineColor(kBlack),RooFit::Name("pseudo"));
  //rdh_KD_sm.plotOn(kdframe1,LineColor(kBlue),MarkColor(kBlue));
  pdf_KD_sm.plotOn(kdframe1,LineColor(kBlue),RooFit::Name("SM"));
  //rdh_KD_bkg.plotOn(kdframe1,LineColor(kGreen),LineColor(kGreen));
  pdf_KD_bkg.plotOn(kdframe1,LineColor(kGreen),RooFit::Name("bkg"));
  modelSignal.plotOn(kdframe1,LineColor(kRed),RooFit::Name("signal_fa3p5"));
  model.plotOn(kdframe1,LineColor(kOrange),RooFit::Name("signal+background"));
  TLegend *leg = new TLegend (0.7,0.6,0.95,0.8);
  leg->AddEntry(kdframe1->findObject("pseudo"),"0-","L");
  leg->AddEntry(kdframe1->findObject("SM"),"0+","L");
  leg->AddEntry(kdframe1->findObject("bkg"),"bkg","L");
  leg->AddEntry(kdframe1->findObject("signal_fa3p5"),"signal fa3=0.5","L");
  leg->AddEntry(kdframe1->findObject("signal+background"),"signal + bkg","L");
  kdframe1->Draw();
  leg->SetFillColor(kWhite);
  leg->Draw("same");
  c->SaveAs("modelPlot_detBkg.eps");
  c->SaveAs("modelPlot_detBkg.png");

  
  //Load the trees into the datasets
  TChain* myChain = new TChain("SelectedTree");
  myChain->Add(inputFileNames[mySample]);
  if(!myChain || myChain->GetEntries()<=0) {
    cout<<"error in the tree"<<endl;
    return 0;
  }
  RooDataSet* data = new RooDataSet("data","data",myChain,RooArgSet(*kd),"");

  TChain* myChain_bkg = new TChain("SelectedTree");
  myChain_bkg->Add("samples/analyticalpsMELA/withResolution/pwgevents_mllCut10_smeared_withDiscriminants_2e2mu_cutDetector.root");
  myChain_bkg->Add("samples/analyticalpsMELA/withResolution/pwgevents_mllCut4_wResolution_withDiscriminants_cutDetector.root");
  if(!myChain_bkg || myChain_bkg->GetEntries()<=0) {
    cout<<"error in the tree"<<endl;
    return 0;
  }
  RooDataSet* data_bkg = new RooDataSet("data_bkg","data_bkg",myChain_bkg,RooArgSet(*kd),"");

  cout << "Number of events in data sig: " << data->numEntries() << endl;
  cout << "Number of events in data bkg: " << data_bkg->numEntries() << endl;
  
  // Initialize tree to save toys to 
  TTree* results = new TTree("results","toy results");
  
  double fa3,fa3Error, fa3Pull;
  double sigFrac,sigFracError, sigFracPull;
  double significance;

  results->Branch("fa3",&fa3,"fa3/D");
  results->Branch("fa3Error",&fa3Error,"fa3Error/D");
  results->Branch("fa3Pull",&fa3Pull,"fa3Pull/D");
  results->Branch("sigFrac",&sigFrac,"sigFrac/D");
  results->Branch("sigFracError",&sigFracError,"sigFracError/D");
  results->Branch("sigFracPull",&sigFracPull,"sigFracPull/D");
  results->Branch("significance",&significance,"significance/D");

  //---------------------------------

  RooDataSet* toyData;
  RooDataSet* toyData_bkgOnly;
  int embedTracker=nEvts*counter;
  int embedTracker_bkg=TMath::Ceil(nEvts/3.75*counter);
  RooArgSet *tempEvent;

  RooFitResult *toyfitresults;
  RooFitResult *toyfitresults_sigBkg;
  RooFitResult *toyfitresults_bkgOnly;
  RooRealVar *r_fa3;
  RooRealVar *r_sigFrac;

  for(int i = 0 ; i<nToys ; i++){
    cout <<i<<"<-----------------------------"<<endl;
    //if(toyData) delete toyData;
    toyData = new RooDataSet("toyData","toyData",RooArgSet(*kd));
    toyData_bkgOnly = new RooDataSet("toyData_bkgOnly","toyData_bkgOnly",RooArgSet(*kd));

    if(nEvts+embedTracker > data->sumEntries()){
      cout << "Playground::generate() - ERROR!!! Playground::data does not have enough events to fill toy!!!!  bye :) " << endl;
      toyData = NULL;
      abort();
      return 0;
    }
    if(nEvts+embedTracker_bkg > data_bkg->sumEntries()){
      cout << "Playground::generate() - ERROR!!! Playground::data does not have enough events to fill toy!!!!  bye :) " << endl;
      toyData = NULL;
      abort();
      return 0;
    }

    for(int iEvent=0; iEvent<nEvts; iEvent++){
      if(iEvent==1)
	cout << "generating event: " << iEvent << " embedTracker: " << embedTracker << endl;
      tempEvent = (RooArgSet*) data->get(embedTracker);
      toyData->add(*tempEvent);
      embedTracker++;
    }
    if(bkg){
      for(int iEvent=0; iEvent<nEvts/3.75; iEvent++){
	if(iEvent==1)
	  cout << "generating bkg event: " << iEvent << " embedTracker bkg: " << embedTracker_bkg << endl;
	tempEvent = (RooArgSet*) data_bkg->get(embedTracker_bkg);
	toyData->add(*tempEvent);
	toyData_bkgOnly->add(*tempEvent);
	embedTracker_bkg++;
      }
    }

    if(bkg)
      toyfitresults =model.fitTo(*toyData,Save());
    else
      toyfitresults =modelSignal.fitTo(*toyData,Save());

    //cout<<toyfitresults<<endl;
    r_fa3 = (RooRealVar *) toyfitresults->floatParsFinal().find("fa3");

    fa3 = r_fa3->getVal();
    fa3Error = r_fa3->getError();
    fa3Pull = (r_fa3->getVal() - fa3Val) / r_fa3->getError();
    if(sigFloating){
      r_sigFrac = (RooRealVar *) toyfitresults->floatParsFinal().find("BoverTOT");
      sigFrac = 1-r_sigFrac->getVal();
      sigFracError = r_sigFrac->getError();
      sigFracPull = (1-r_sigFrac->getVal() - sigFracVal) / r_sigFrac->getError();
    }
    // fill TTree
    results->Fill();
  }

  char nEvtsString[100];
  sprintf(nEvtsString,"_%iEvts_%iiter",nEvts, counter);

  // write tree to output file (ouputFileName set at top)
  TFile *outputFile = new TFile("embeddedToys1DKD_fa3Corr_WithBackgDetEffects_"+sampleName[mySample]+nEvtsString+".root","RECREATE");
  results->Write();
  outputFile->Close();

}
예제 #19
0
파일: Pull.C 프로젝트: magania/b_fitter
Pull(){
	TFile *root_file = new TFile("toymc.root");

	RooWorkspace *ws2 = new RooWorkspace();

        ws2->factory("{DG[0.09,-0.1,0.3],tau[1.5,1.2,1.7],beta[0.25,0.0,0.5],delta_l[0.2,-2,2],delta_p[2.95,1,5.0],delta_s[0.2,-2,2],fs[0.2,0,0.4],s[1.0,0.8,1.2]}");
        ws2->factory("{A02[0.6,0.5,0.7],Al2[0.3,0.2,0.4]}");

	RooDataSet* data = new RooDataSet("data","data", ws2->argSet("DG,tau,beta,delta_l,delta_p,delta_s,fs,s,A02,Al2"));

	for(int i=0; i<10; i++){
		TString fit_name = "fit_";
		fit_name+=i;

		RooFitResult *fit_result = (RooFitResult*) root_file->Get(fit_name);
		if (fit_result->status() != 0){
			cout << fit_result->status() << endl;
			continue;
		}
		//cout << fit_result->minNll() << endl;
//		if ( fit_result->minNll() < 17500 )
			data->add(fit_result->floatParsFinal());
	}

        gROOT->SetStyle("Plain");

	ws2->factory("Gaussian::A02_gauss(A02,mean_A02[0.6,0.5,0.7],sigma_A02[0.15,0.0001,1.0])");
	ws2->pdf("A02_gauss")->fitTo(*data, RooFit::PrintLevel(-1));	

	TCanvas *canvas_A02 = new TCanvas("canvas_A02", "canvas_A02", 600,600);
	RooPlot *A02_plot = ws2->var("A02")->frame();
	data->plotOn(A02_plot,RooFit::MarkerSize(0.3));
//	ws2->pdf("A02_gauss")->plotOn(A02_plot);
//	ws2->pdf("A02_gauss")->paramOn(A02_plot);
	A02_plot->Draw();

        ws2->factory("Gaussian::Al2_gauss(Al2,mean_Al2[0.3,0.2,0.4],sigma_Al2[0.15,0.001,1.0])");
        ws2->pdf("Al2_gauss")->fitTo(*data, RooFit::PrintLevel(-1));

        TCanvas *canvas_Al2 = new TCanvas("canvas_Al2", "canvas_Al2", 600,600);
        RooPlot *Al2_plot = ws2->var("Al2")->frame();
        data->plotOn(Al2_plot,RooFit::MarkerSize(0.3));
//        ws2->pdf("Al2_gauss")->plotOn(Al2_plot);
//        ws2->pdf("Al2_gauss")->paramOn(Al2_plot);
        Al2_plot->Draw();


        ws2->factory("Gaussian::DG_gauss(DG,mean_DG[0.09,0.0,0.2],sigma_DG[0.15,0.01,1.0])");
        ws2->pdf("DG_gauss")->fitTo(*data, RooFit::PrintLevel(-1));

        TCanvas *canvas_DG = new TCanvas("canvas_DG", "canvas_DG", 600,600);
        RooPlot *DG_plot = ws2->var("DG")->frame();
        data->plotOn(DG_plot,RooFit::MarkerSize(0.3));
//        ws2->pdf("DG_gauss")->plotOn(DG_plot);
//        ws2->pdf("DG_gauss")->paramOn(DG_plot);
        DG_plot->Draw();

        ws2->factory("Gaussian::beta_gauss(beta,mean_beta[0.25,0.2,0.3],sigma_beta[0.15,0.001,1.0])");
        ws2->pdf("beta_gauss")->fitTo(*data, RooFit::PrintLevel(-1));

        TCanvas *canvas_beta = new TCanvas("canvas_beta", "canvas_beta", 600,600);
        RooPlot *beta_plot = ws2->var("beta")->frame();
        data->plotOn(beta_plot,RooFit::MarkerSize(0.3));
//        ws2->pdf("beta_gauss")->plotOn(beta_plot);
//        ws2->pdf("beta_gauss")->paramOn(beta_plot);
        beta_plot->Draw();


        ws2->factory("Gaussian::tau_gauss(tau,mean_tau[1.5,1,2],sigma_tau[0.1,0.01,1.0])");
        ws2->pdf("tau_gauss")->fitTo(*data, RooFit::PrintLevel(-1));

        TCanvas *canvas_tau = new TCanvas("canvas_tau", "canvas_tau", 600,600);
        RooPlot *tau_plot = ws2->var("tau")->frame();
        data->plotOn(tau_plot,RooFit::MarkerSize(0.3));
//        ws2->pdf("tau_gauss")->plotOn(tau_plot);
//        ws2->pdf("tau_gauss")->paramOn(tau_plot);
        tau_plot->Draw();

        ws2->factory("Gaussian::s_gauss(s,mean_s[1,0,2],sigma_s[0.15,0.01,1.0])");
        ws2->pdf("s_gauss")->fitTo(*data, RooFit::PrintLevel(-1));

        TCanvas *canvas_s = new TCanvas("canvas_s", "canvas_s", 600,600);
        RooPlot *s_plot = ws2->var("s")->frame();
        data->plotOn(s_plot,RooFit::MarkerSize(0.3));
//        ws2->pdf("s_gauss")->plotOn(s_plot);
//        ws2->pdf("s_gauss")->paramOn(s_plot);
       	s_plot->Draw();

        ws2->factory("Gaussian::fs_gauss(fs,mean_fs[0.2,0,2],sigma_fs[0.15,0.01,1.0])");
        ws2->pdf("fs_gauss")->fitTo(*data, RooFit::PrintLevel(-1));

        TCanvas *canvas_fs = new TCanvas("canvas_fs", "canvas_fs", 600,600);
        RooPlot *fs_plot = ws2->var("fs")->frame();
        data->plotOn(fs_plot,RooFit::MarkerSize(0.3));
//        ws2->pdf("fs_gauss")->plotOn(fs_plot);
//       ws2->pdf("fs_gauss")->paramOn(fs_plot);
        fs_plot->Draw();

//        ws2->factory("Gaussian::delta_s_gauss(delta_s,mean_delta_s[0.2,0,2],sigma_delta_s[0.15,0.1,1.0])");
//        ws2->pdf("delta_s_gauss")->fitTo(*data, RooFit::PrintLevel(-1));

        TCanvas *canvas_delta_s = new TCanvas("canvas_delta_s", "canvas_delta_s", 600,600);
        RooPlot *delta_s_plot = ws2->var("delta_s")->frame();
        data->plotOn(delta_s_plot,RooFit::MarkerSize(0.3));
//        ws2->pdf("delta_s_gauss")->plotOn(delta_s_plot);
//        ws2->pdf("delta_s_gauss")->paramOn(delta_s_plot);
        delta_s_plot->Draw();

//        ws2->factory("Gaussian::delta_p_gauss(delta_p,mean_delta_p[2.95,0,4],sigma_delta_p[0.15,0.1,1.0])");
//        ws2->pdf("delta_p_gauss")->fitTo(*data, RooFit::PrintLevel(-1));

        TCanvas *canvas_delta_p = new TCanvas("canvas_delta_p", "canvas_delta_p", 600,600);
        RooPlot *delta_p_plot = ws2->var("delta_p")->frame();
        data->plotOn(delta_p_plot,RooFit::MarkerSize(0.3));
//        ws2->pdf("delta_p_gauss")->plotOn(delta_p_plot);
//        ws2->pdf("delta_p_gauss")->paramOn(delta_p_plot);
        delta_p_plot->Draw();


//       ws2->factory("Gaussian::delta_l_gauss(delta_l,mean_delta_l[1,0,2],sigma_delta_l[0.25,0.2,2.0])");
//        ws2->pdf("delta_l_gauss")->fitTo(*data, RooFit::PrintLevel(-1));

        TCanvas *canvas_delta_l = new TCanvas("canvas_delta_l", "canvas_delta_l", 600,600);
        RooPlot *delta_l_plot = ws2->var("delta_l")->frame();
        data->plotOn(delta_l_plot,RooFit::MarkerSize(0.3));
//        ws2->pdf("delta_l_gauss")->plotOn(delta_l_plot);
//        ws2->pdf("delta_l_gauss")->paramOn(delta_l_plot);
        delta_l_plot->Draw();
}
void makejpsifit(string inputFilename, string outFilename, 
		 Int_t ptBin, Int_t etaBin,
		 double minMass, double maxMass, 
		 double mean_bw, double gamma_bw, double cutoff_cb, double power_cb, 
		 const char* plotOpt, const int nbins, Int_t isMC) {

  TStyle *mystyle = RooHZZStyle("ZZ");
  mystyle->cd();

  //Create Data Set
  RooRealVar mass("zmass","m(e^{+}e^{-})",minMass,maxMass,"GeV/c^{2}");

  // Reading everything from root tree instead
  TFile *tfile = TFile::Open(inputFilename.c_str());
  TTree *ttree = (TTree*)tfile->Get("zeetree/probe_tree");
  hzztree *zeeTree = new hzztree(ttree);

  RooArgSet zMassArgSet(mass);
  RooDataSet* data = new RooDataSet("data", "ntuple parameters", zMassArgSet);

  for (int i = 0; i < zeeTree->fChain->GetEntries(); i++) {
    if(i%100000==0) cout << "Processing Event " << i << endl;
    zeeTree->fChain->GetEntry(i);

    //*************************************************************************
    //Electron Selection
    //*************************************************************************
    // already passed for this tree

    //*************************************************************************
    //Compute electron four vector;
    //*************************************************************************
    double ele1pt = zeeTree->l1pt;
    double ele2pt = zeeTree->l2pt;

    double ELECTRONMASS = 0.51e-3;
    TLorentzVector ele1FourVector;
    ele1FourVector.SetPtEtaPhiM(zeeTree->l1pt, zeeTree->l1eta, zeeTree->l1phi, ELECTRONMASS);
    TLorentzVector ele2FourVector;
    ele2FourVector.SetPtEtaPhiM(zeeTree->l2pt, zeeTree->l2eta, zeeTree->l2phi, ELECTRONMASS);

    
    //*************************************************************************
    //pt and eta cuts on electron
    //*************************************************************************
    if (! (ele1pt > 7 && ele2pt > 7
           && fabs( zeeTree->l1eta) < 2.5 
           && fabs( zeeTree->l2eta) < 2.5 )) continue;

    //*************************************************************************
    //pt bins and eta bins
    //*************************************************************************
    Int_t Ele1PtBin = -1;
    Int_t Ele1EtaBin = -1;
    Int_t Ele2PtBin = -1;
    Int_t Ele2EtaBin = -1;
    if (ele1pt > 7 && ele1pt < 10) Ele1PtBin = 0;
    else if (ele1pt < 20) Ele1PtBin = 1;
    else Ele1PtBin = 2;
    if (ele2pt > 7 && ele2pt < 10) Ele2PtBin = 0;
    else if (ele2pt < 20) Ele2PtBin = 1;
    else Ele2PtBin = 2;
    if (fabs(zeeTree->l1sceta) < 1.479) Ele1EtaBin = 0;
    else Ele1EtaBin = 1;
    if (fabs(zeeTree->l2sceta) < 1.479) Ele2EtaBin = 0;
    else Ele2EtaBin = 1;

    if (!(Ele1PtBin == ptBin || Ele2PtBin == ptBin)) continue; 
    if (!(Ele1EtaBin == etaBin && Ele2EtaBin == etaBin)) continue; 
    
    //*************************************************************************
    // restrict range of mass
    //*************************************************************************
    double zMass = (ele1FourVector+ele2FourVector).M();
    if (zMass < minMass || zMass > maxMass) continue;

    //*************************************************************************
    //set mass variable
    //*************************************************************************
    zMassArgSet.setRealValue("zmass", zMass);    

    data->add(zMassArgSet);
  }

  // do binned fit to gain time...
  mass.setBins(nbins);
  RooDataHist *bdata = new RooDataHist("data_binned","data_binned", zMassArgSet, *data);

  cout << "dataset size: " << data->numEntries() << endl;

//   // Closing file
//   treeFile->Close();
  //====================== Parameters===========================

  //Crystal Ball parameters
//   RooRealVar cbBias ("#Deltam_{CB}", "CB Bias", -.01, -10, 10, "GeV/c^{2}");
//   RooRealVar cbSigma("sigma_{CB}", "CB Width", 1.7, 0.8, 5.0, "GeV/c^{2}");
//   RooRealVar cbCut  ("a_{CB}","CB Cut", 1.05, 1.0, 3.0);
//   RooRealVar cbPower("n_{CB}","CB Order", 2.45, 0.1, 20.0);
  RooRealVar cbBias ("#Deltam_{CB}", "CB Bias", -.01, -10, 10, "GeV/c^{2}");
  RooRealVar cbSigma("#sigma_{CB}", "CB Width", 1.5, 0.01, 5.0, "GeV/c^{2}");
  RooRealVar cbCut  ("a_{CB}","CB Cut", 1.0, 1.0, 3.0);
  RooRealVar cbPower("n_{CB}","CB Order", 2.5, 0.1, 20.0);
  cbCut.setVal(cutoff_cb);
  cbPower.setVal(power_cb);

  // Just checking
  //cbCut.Print();
  //cbPower.Print();

  //Breit_Wigner parameters
  RooRealVar bwMean("m_{JPsi}","BW Mean", 3.096916, "GeV/c^{2}");
  bwMean.setVal(mean_bw);
  RooRealVar bwWidth("#Gamma_{JPsi}", "BW Width", 92.9e-6, "GeV/c^{2}");
  bwWidth.setVal(gamma_bw);

  // Fix the Breit-Wigner parameters to PDG values
  bwMean.setConstant(kTRUE);
  bwWidth.setConstant(kTRUE);

  // Exponential Background parameters
  RooRealVar expRate("#lambda_{exp}", "Exponential Rate", -0.064, -1, 1);
  RooRealVar c0("c_{0}", "c0", 1., 0., 50.);

  //Number of Signal and Background events
  RooRealVar nsig("N_{S}", "# signal events", 524, 0.1, 10000000000.);
  RooRealVar nbkg("N_{B}", "# background events", 43, 1., 10000000.);

  //============================ P.D.F.s=============================

  // Mass signal for two decay electrons p.d.f.
  RooBreitWigner bw("bw", "bw", mass, bwMean, bwWidth);
  RooCBShape  cball("cball", "Crystal Ball", mass, cbBias, cbSigma, cbCut, cbPower);
  RooFFTConvPdf BWxCB("BWxCB", "bw X crystal ball", mass, bw, cball);

  // Mass background p.d.f.
  RooExponential bg("bg", "exp. background", mass, expRate);

  // Mass model for signal electrons p.d.f.
  RooAddPdf model("model", "signal", RooArgList(BWxCB), RooArgList(nsig));

  TStopwatch t ;
  t.Start() ;
  double fitmin, fitmax;
  if(isMC) {
    fitmin = (etaBin==0) ? 3.00 : 2.7;
    fitmax = (etaBin==0) ? 3.20 : 3.4;
  } else {
    fitmin = (etaBin==0) ? ( (ptBin>=2) ? 3.01 : 3.02 ) : 2.7;
    fitmax = (etaBin==0) ? ( (ptBin==3) ? 3.23 : 3.22 ) : 3.4;
  }
  RooFitResult *fitres = model.fitTo(*bdata,Range(fitmin,fitmax),Hesse(1),Minos(1),Timer(1),Save(1));
  fitres->SetName("fitres");
  t.Print() ;

  TCanvas* c = new TCanvas("c","Unbinned Invariant Mass Fit", 0,0,800,600);

  //========================== Plotting  ============================
  //Create a frame
  RooPlot* plot = mass.frame(Range(minMass,maxMass),Bins(nbins));
  // Add data and model to canvas
  int col = (isMC ? kAzure+4 : kGreen+1);
  data->plotOn(plot);
  model.plotOn(plot,LineColor(col));
  data->plotOn(plot);
  model.paramOn(plot, Format(plotOpt, AutoPrecision(1)), Parameters(RooArgSet(cbBias, cbSigma, cbCut, cbPower, bwMean, bwWidth, expRate, nsig, nbkg)), Layout(0.15,0.45,0.80));
  plot->getAttText()->SetTextSize(.03);
  plot->SetTitle("");
  plot->Draw();

  // Print Fit Values
  TLatex *tex = new TLatex();
  tex->SetNDC();
  tex->SetTextSize(.1);
  tex->SetTextFont(132);
  //  tex->Draw();
  tex->SetTextSize(0.057);
  if(isMC) tex->DrawLatex(0.65, 0.75, "J/#psi #rightarrow e^{+}e^{-} MC");
  else tex->DrawLatex(0.65, 0.75, "J/#psi #rightarrow e^{+}e^{-} data");
  tex->SetTextSize(0.030);
  tex->DrawLatex(0.645, 0.65, Form("BW Mean = %.2f GeV/c^{2}", bwMean.getVal()));
  tex->DrawLatex(0.645, 0.60, Form("BW #sigma = %.2f GeV/c^{2}", bwWidth.getVal()));
  c->Update();
  c->SaveAs((outFilename + ".pdf").c_str());
  c->SaveAs((outFilename + ".png").c_str());

  // tablefile << Form(Outfile + "& $ %f $ & $ %f $ & $ %f $\\ \hline",cbBias.getVal(), cbSigma.getVal(), cbCut.getVal());
  // Output workspace with model and data

  RooWorkspace *w = new RooWorkspace("JPsieeMassScaleAndResolutionFit");
  w->import(model);
  w->import(*bdata);
  w->writeToFile((outFilename + ".root").c_str());  

  TFile *tfileo = TFile::Open((outFilename + ".root").c_str(),"update");
  fitres->Write();
  tfileo->Close();

}
예제 #21
0
// The actual job
void backgroundFits_ggzz_1Dw(int channel, int sqrts, int VBFtag)
{
  TString schannel;
  if      (channel == 1) schannel = "4mu";
  else if (channel == 2) schannel = "4e";
  else if (channel == 3) schannel = "2e2mu";
  else cout << "Not a valid channel: " << schannel << endl;

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

  cout << "schannel = " << schannel << "  sqrts = " << sqrts << " VBFtag = "<< VBFtag << endl;

  TString outfile;
  outfile = "CardFragments/ggzzBackgroundFit_" + ssqrts + "_" + schannel + "_" + Form("%d",int(VBFtag)) + ".txt";
  ofstream of(outfile,ios_base::out);

  gSystem->AddIncludePath("-I$ROOFITSYS/include");
  gROOT->ProcessLine(".L ../CreateDatacards/include/tdrstyle.cc");
  setTDRStyle(false);
  gStyle->SetPadLeftMargin(0.16);
	
  TString filepath;filepath.Form("AAAOK/ZZ%s/ZZ4lAnalysis.root",schannel.Data());
  TFile *f = TFile::Open(filepath);
  TTree *tree = f->Get("ZZTree/candTree");

  RooRealVar* MC_weight = new RooRealVar("MC_weight","MC_weight",0.,2.) ; 
  RooRealVar* ZZMass = new RooRealVar("ZZMass","ZZMass",100,100.,1000.);
  RooRealVar* NJets30 = new RooRealVar("NJets30","NJets30",0.,5.);
  RooArgSet ntupleVarSet(*ZZMass,*NJets30,*MC_weight);
  RooDataSet *set = new RooDataSet("set","set",ntupleVarSet,WeightVar("MC_weight"));
  //RooArgSet ntupleVarSet(*ZZMass,*NJets30);  
  //RooDataSet *set = new RooDataSet("set","set",ntupleVarSet);

  Float_t myMC,myMass;
  Int_t myNJets;
  int nentries = tree->GetEntries();

  Float_t myPt,myJetPt,myJetEta,myJetPhi,myJetMass,myFisher;
  Int_t myExtralep,myBJets;
  tree->SetBranchAddress("ZZMass",&myMass);
  tree->SetBranchAddress("genHEPMCweight",&myMC);
  tree->SetBranchAddress("nCleanedJetsPt30",&myNJets);
  tree->SetBranchAddress("ZZPt",&myPt);
  tree->SetBranchAddress("nExtraLep",&myExtralep);
  tree->SetBranchAddress("nCleanedJetsPt30BTagged",&myBJets);
  tree->SetBranchAddress("DiJetDEta",&myFisher);

  for(int i =0;i<nentries;i++) {
    tree->GetEntry(i);
    if(myMass<100.)continue;
    int cat = category(myExtralep,myPt, myMass,myNJets, myBJets,/* jetpt, jeteta, jetphi, jetmass,*/myFisher);
    if(VBFtag != cat )continue;

    ntupleVarSet.setRealValue("ZZMass",myMass);
    ntupleVarSet.setRealValue("MC_weight",myMC);
    ntupleVarSet.setRealValue("NJets30",(double)cat);

    set->add(ntupleVarSet, myMC);
  }

  //RooRealVar* ZZLD = new RooRealVar("ZZLD","ZZLD",0.,1.);
  //char cut[10];
  //sprintf(cut,"ZZLD>0.5");
  //RooDataSet* set = new RooDataSet("set","set",tree,RooArgSet(*ZZMass,*MC_weight,*ZZLD),cut,"MC_weight");

  double totalweight = 0.;
  for (int i=0 ; i<set->numEntries() ; i++) { 
    set->get(i) ; 
    totalweight += set->weight();
    //cout << CMS_zz4l_mass->getVal() << " = " << set->weight() << endl ; 
  } 
  cout << "nEntries: " << set->numEntries() << ", totalweight: " << totalweight << endl;
		
  gSystem->Load("libHiggsAnalysisCombinedLimit.so");
	
  //// ---------------------------------------
  //Background
  RooRealVar CMS_qqzzbkg_a0("CMS_qqzzbkg_a0","CMS_qqzzbkg_a0",115.3,0.,200.);
  RooRealVar CMS_qqzzbkg_a1("CMS_qqzzbkg_a1","CMS_qqzzbkg_a1",21.96,0.,200.);
  RooRealVar CMS_qqzzbkg_a2("CMS_qqzzbkg_a2","CMS_qqzzbkg_a2",122.8,0.,200.);
  RooRealVar CMS_qqzzbkg_a3("CMS_qqzzbkg_a3","CMS_qqzzbkg_a3",0.03479,0.,1.);
  RooRealVar CMS_qqzzbkg_a4("CMS_qqzzbkg_a4","CMS_qqzzbkg_a4",185.5,0.,200.);
  RooRealVar CMS_qqzzbkg_a5("CMS_qqzzbkg_a5","CMS_qqzzbkg_a5",12.67,0.,200.);
  RooRealVar CMS_qqzzbkg_a6("CMS_qqzzbkg_a6","CMS_qqzzbkg_a6",34.81,0.,100.);
  RooRealVar CMS_qqzzbkg_a7("CMS_qqzzbkg_a7","CMS_qqzzbkg_a7",0.1393,0.,1.);
  RooRealVar CMS_qqzzbkg_a8("CMS_qqzzbkg_a8","CMS_qqzzbkg_a8",66.,0.,200.);
  RooRealVar CMS_qqzzbkg_a9("CMS_qqzzbkg_a9","CMS_qqzzbkg_a9",0.07191,0.,1.);
	
  RooggZZPdf_v2* bkg_ggzz = new RooggZZPdf_v2("bkg_ggzz","bkg_ggzz",*ZZMass,
					      CMS_qqzzbkg_a0,CMS_qqzzbkg_a1,CMS_qqzzbkg_a2,CMS_qqzzbkg_a3,CMS_qqzzbkg_a4,
					      CMS_qqzzbkg_a5,CMS_qqzzbkg_a6,CMS_qqzzbkg_a7,CMS_qqzzbkg_a8,CMS_qqzzbkg_a9);
	
  //// ---------------------------------------
	
  RooFitResult *r1 = bkg_ggzz->fitTo( *set, Save(kTRUE), SumW2Error(kTRUE) );//, Save(kTRUE), SumW2Error(kTRUE)) ;

  cout << endl;
  cout << "------- Parameters for " << schannel << " sqrts=" << sqrts << endl;
  cout << "  a0_bkgd = " << CMS_qqzzbkg_a0.getVal() << endl;
  cout << "  a1_bkgd = " << CMS_qqzzbkg_a1.getVal() << endl;
  cout << "  a2_bkgd = " << CMS_qqzzbkg_a2.getVal() << endl;
  cout << "  a3_bkgd = " << CMS_qqzzbkg_a3.getVal() << endl;
  cout << "  a4_bkgd = " << CMS_qqzzbkg_a4.getVal() << endl;
  cout << "  a5_bkgd = " << CMS_qqzzbkg_a5.getVal() << endl;
  cout << "  a6_bkgd = " << CMS_qqzzbkg_a6.getVal() << endl;
  cout << "  a7_bkgd = " << CMS_qqzzbkg_a7.getVal() << endl;
  cout << "  a8_bkgd = " << CMS_qqzzbkg_a8.getVal() << endl;
  cout << "  a9_bkgd = " << CMS_qqzzbkg_a9.getVal() << endl;
  cout << "---------------------------" << endl << endl;  

  of << "ggZZshape a0_bkgd  " << CMS_qqzzbkg_a0.getVal() << endl;
  of << "ggZZshape a1_bkgd  " << CMS_qqzzbkg_a1.getVal() << endl;
  of << "ggZZshape a2_bkgd  " << CMS_qqzzbkg_a2.getVal() << endl;
  of << "ggZZshape a3_bkgd  " << CMS_qqzzbkg_a3.getVal() << endl;
  of << "ggZZshape a4_bkgd  " << CMS_qqzzbkg_a4.getVal() << endl;
  of << "ggZZshape a5_bkgd  " << CMS_qqzzbkg_a5.getVal() << endl;
  of << "ggZZshape a6_bkgd  " << CMS_qqzzbkg_a6.getVal() << endl;
  of << "ggZZshape a7_bkgd  " << CMS_qqzzbkg_a7.getVal() << endl;
  of << "ggZZshape a8_bkgd  " << CMS_qqzzbkg_a8.getVal() << endl;
  of << "ggZZshape a9_bkgd  " << CMS_qqzzbkg_a9.getVal() << endl;
  of << endl;
  of.close();

  cout << endl << "Output written to: " << outfile << endl;

  int iLineColor = 1;
  string lab = "blah";
  if (channel == 1) { iLineColor = 2; lab = "4#mu"; }
  if (channel == 3) { iLineColor = 4; lab = "2e2#mu"; }
  if (channel == 2) { iLineColor = 6; lab = "4e"; }
  char lname[192];
  sprintf(lname,"gg #rightarrow ZZ #rightarrow %s", lab.c_str() );
  char lname2[192];
  sprintf(lname2,"Shape Model, %s", lab.c_str() );
  // dummy!                                                                                                                                               
  TF1* dummyF = new TF1("dummyF","1",0.,1.);
  TH1F* dummyH = new TH1F("dummyH","",1, 0.,1.);
  dummyF->SetLineColor( iLineColor );
  dummyF->SetLineWidth( 2 );
  
  TLegend * box2 = new TLegend(0.5,0.70,0.90,0.90);
  box2->SetFillColor(0);
  box2->SetBorderSize(0);
  box2->AddEntry(dummyH,"Simulation (GG2ZZ)  ","pe");
  box2->AddEntry(dummyH,lname,"");
  box2->AddEntry(dummyH,"","");
  box2->AddEntry(dummyF,lname2,"l");

  TPaveText *pt = new TPaveText(0.15,0.955,0.4,0.99,"NDC");
  pt->SetFillColor(0);
  pt->SetBorderSize(0);
  pt->AddText("CMS Preliminary 2012");
  TPaveText *pt2 = new TPaveText(0.84,0.955,0.99,0.99,"NDC");
  pt2->SetFillColor(0);
  pt2->SetBorderSize(0);

  // Plot m4l and 
  RooPlot* frameM4l = ZZMass->frame(Title("M4L"),Bins(200)) ;
  set->plotOn(frameM4l, MarkerStyle(24)) ;
  bkg_ggzz->plotOn(frameM4l,LineColor(iLineColor)) ;
  set->plotOn(frameM4l) ;

  //comaprison with different shape, if needed (uncommenting also the code above)
  //bkg_ggzz_bkgd->plotOn(frameM4l,LineColor(1),NormRange("largerange")) ;

  frameM4l->GetXaxis()->SetTitle("m_{4l} [GeV]");
  frameM4l->GetYaxis()->SetTitle("a.u.");
  //frameM4l->GetYaxis()->SetRangeUser(0,0.03);
  //if(channel == 3)frameM4l->GetYaxis()->SetRangeUser(0,0.05);
  //if(VBFtag<2){
  //  if(channel == 3)frameM4l->GetYaxis()->SetRangeUser(0,0.01);
  //  else frameM4l->GetYaxis()->SetRangeUser(0,0.005);
  //}
  frameM4l->GetXaxis()->SetRangeUser(100,1000);
  TCanvas *c = new TCanvas("c","c",800,600);
  c->cd();
  frameM4l->Draw();
  box2->Draw();
  pt->Draw();
  pt2->Draw();

  TString outputPath = "bkgFigs";
  outputPath = outputPath+ (long) sqrts + "TeV/";
  TString outputName;
  outputName =  outputPath + "bkgggzz_" + schannel + "_" + Form("%d",int(VBFtag));
  c->SaveAs(outputName + ".eps");
  c->SaveAs(outputName + ".png");
  c->SaveAs(outputName + ".root");
  delete c;

  frameM4l->GetXaxis()->SetRangeUser(100,200);
  TCanvas *c = new TCanvas("c","c",800,600);
  c->cd();
  frameM4l->Draw();
  box2->Draw();
  pt->Draw();
  pt2->Draw();

  TString outputPath = "bkgFigs";
  outputPath = outputPath+ (long) sqrts + "TeV/";
  TString outputName;
  outputName =  outputPath + "bkgggzz_lowZoom_" + schannel + "_" + Form("%d",int(VBFtag));
  c->SaveAs(outputName + ".eps");
  c->SaveAs(outputName + ".png");
  c->SaveAs(outputName + ".root");
  delete c;
} 
예제 #22
0
///
/// Find the global minimum in a more thorough way.
/// First fit with external start parameters, then
/// for each parameter that starts with "d" or "r" (typically angles and ratios):
///   - at upper scan range, rest at start parameters
///   - at lower scan range, rest at start parameters
/// This amounts to a maximum of 1+2^n fits, where n is the number
/// of parameters to be varied.
///
/// \param w Workspace holding the pdf.
/// \param name Name of the pdf without leading "pdf_".
/// \param forceVariables Apply the force method for these variables only. Format
/// "var1,var2,var3," (list must end with comma). Default is to apply for all angles,
/// all ratios except rD_k3pi and rD_kpi, and the k3pi coherence factor.
///
RooFitResult* Utils::fitToMinForce(RooWorkspace *w, TString name, TString forceVariables)
{
	bool debug = true;

	TString parsName = "par_"+name;
	TString obsName  = "obs_"+name;
	TString pdfName  = "pdf_"+name;
	RooFitResult *r = 0;
	int printlevel = -1;
	RooMsgService::instance().setGlobalKillBelow(ERROR);

	// save start parameters
	if ( !w->set(parsName) ){
		cout << "MethodProbScan::scan2d() : ERROR : parsName not found: " << parsName << endl;
		exit(1);
	}
	RooDataSet *startPars = new RooDataSet("startParsForce", "startParsForce", *w->set(parsName));
	startPars->add(*w->set(parsName));

	// set up parameters and ranges
	RooArgList *varyPars = new RooArgList();
	TIterator* it = w->set(parsName)->createIterator();
	while ( RooRealVar* p = (RooRealVar*)it->Next() )
	{
		if ( p->isConstant() ) continue;
		if ( forceVariables=="" && ( false
					|| TString(p->GetName()).BeginsWith("d") ///< use these variables
					// || TString(p->GetName()).BeginsWith("r")
					|| TString(p->GetName()).BeginsWith("k")
					|| TString(p->GetName()) == "g"
					) && ! (
						TString(p->GetName()) == "rD_k3pi"  ///< don't use these
						|| TString(p->GetName()) == "rD_kpi"
						// || TString(p->GetName()) == "dD_kpi"
						|| TString(p->GetName()) == "d_dk"
						|| TString(p->GetName()) == "d_dsk"
						))
		{
			varyPars->add(*p);
		}
		else if ( forceVariables.Contains(TString(p->GetName())+",") )
		{
			varyPars->add(*p);
		}
	}
	delete it;
	int nPars = varyPars->getSize();
	if ( debug ) cout << "Utils::fitToMinForce() : nPars = " << nPars << " => " << pow(2.,nPars) << " fits" << endl;
	if ( debug ) cout << "Utils::fitToMinForce() : varying ";
	if ( debug ) varyPars->Print();

	//////////

	r = fitToMinBringBackAngles(w->pdf(pdfName), false, printlevel);

	//////////

	int nErrors = 0;

	// We define a binary mask where each bit corresponds
	// to parameter at max or at min.
	for ( int i=0; i<pow(2.,nPars); i++ )
	{
		if ( debug ) cout << "Utils::fitToMinForce() : fit " << i << "        \r" << flush;
		setParameters(w, parsName, startPars->get(0));

		for ( int ip=0; ip<nPars; ip++ )
		{
			RooRealVar *p = (RooRealVar*)varyPars->at(ip);
			float oldMin = p->getMin();
			float oldMax = p->getMax();
			setLimit(w, p->GetName(), "force");
			if ( i/(int)pow(2.,ip) % 2==0 ) { p->setVal(p->getMin()); }
			if ( i/(int)pow(2.,ip) % 2==1 ) { p->setVal(p->getMax()); }
			p->setRange(oldMin, oldMax);
		}

		// check if start parameters are sensible, skip if they're not
		double startParChi2 = getChi2(w->pdf(pdfName));
		if ( startParChi2>2000 ){
			nErrors += 1;
			continue;
		}

		// refit
		RooFitResult *r2 = fitToMinBringBackAngles(w->pdf(pdfName), false, printlevel);

		// In case the initial fit failed, accept the second one.
		// If both failed, still select the second one and hope the
		// next fit succeeds.
		if ( !(r->edm()<1 && r->covQual()==3) ){
			delete r;
			r = r2;
		}
		else if ( r2->edm()<1 && r2->covQual()==3 && r2->minNll()<r->minNll() ){
			// better minimum found!
			delete r;
			r = r2;
		}
		else{
			delete r2;
		}
	}

	if ( debug ) cout << endl;
	if ( debug ) cout << "Utils::fitToMinForce() : nErrors = " << nErrors << endl;

	RooMsgService::instance().setGlobalKillBelow(INFO);

	// (re)set to best parameters
	setParameters(w, parsName, r);

	delete startPars;
	return r;
}
예제 #23
0
void fitSingleMass( const std::string& basedir, float mass, const std::string&  width, TGraphErrors* gr_mean, TGraphErrors* gr_sigma, TGraphErrors* gr_width, TGraphErrors* gr_alpha1, TGraphErrors* gr_n1, TGraphErrors* gr_alpha2, TGraphErrors* gr_n2 ) {


  std::string outdir = "genSignalShapes";
  system( Form("mkdir -p %s", outdir.c_str()) );


  std::string dataset( Form( "GluGluSpin0ToZGamma_ZToLL_W_%s_M_%.0f_TuneCUEP8M1_13TeV_pythia8", width.c_str(), mass ) );
  std::cout << "-> Starting: " << dataset << std::endl;

  system( Form("ls %s/%s/crab_%s/*/0000/genAna_1.root >> toBeAdded.txt", basedir.c_str(), dataset.c_str(), dataset.c_str() ) );
  TChain* tree = new TChain("mt2");
  ifstream ifs("toBeAdded.txt");
  while( ifs.good() ) {
    std::string fileName;
    ifs >> fileName;
    TString fileName_tstr(fileName);
    if( !fileName_tstr.Contains("pnfs") ) continue;
    tree->Add(Form("$DCAP/%s/mt2", fileName.c_str()) );
  }
  system( "rm toBeAdded.txt" );

  if( tree->GetEntries()==0 ) return;

  int ngenPart;
  tree->SetBranchAddress( "ngenPart", &ngenPart );
  float genPart_pt[100];
  tree->SetBranchAddress( "genPart_pt", genPart_pt );
  float genPart_eta[100];
  tree->SetBranchAddress( "genPart_eta", genPart_eta );
  float genPart_phi[100];
  tree->SetBranchAddress( "genPart_phi", genPart_phi );
  float genPart_mass[100];
  tree->SetBranchAddress( "genPart_mass", genPart_mass );
  int genPart_pdgId[100];
  tree->SetBranchAddress( "genPart_pdgId", genPart_pdgId );
  int genPart_motherId[100];
  tree->SetBranchAddress( "genPart_motherId", genPart_motherId );
  int genPart_status[100];
  tree->SetBranchAddress( "genPart_status", genPart_status );



  RooRealVar* x = new RooRealVar("boss_mass", "boss_mass", mass, 0.5*mass, 1.5*mass );

  RooDataSet* data = new RooDataSet( "data", "data", RooArgSet(*x) );



  int nentries = tree->GetEntries();


  for( int iEntry = 0; iEntry<nentries; ++iEntry ) {

    if( iEntry % 25000 == 0 ) std::cout << "  Entry: " << iEntry << " / " << nentries << std::endl;

    tree->GetEntry(iEntry);

    TLorentzVector leptPlus;
    TLorentzVector leptMinus;
    TLorentzVector photon;
    bool foundLeptPlus = false;
    bool foundLeptMinus = false;
    bool foundPhoton = false;
    bool tauEvent = false;

    for( int iPart=0; iPart<ngenPart; ++iPart ) {

      if( genPart_status[iPart]!=1 ) continue;

      if( abs(genPart_pdgId[iPart])==15 ) {
        tauEvent = true;
        break;
      }

      if( (genPart_pdgId[iPart]==+11 || genPart_pdgId[iPart]==+13) && genPart_motherId[iPart]==23 ) {
        leptMinus.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] );
        foundLeptMinus = true;
      }
      if( (genPart_pdgId[iPart]==-11 || genPart_pdgId[iPart]==-13) && genPart_motherId[iPart]==23 ) {
        leptPlus.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] );
        foundLeptPlus = true;
      }
      if( genPart_pdgId[iPart]==22 && genPart_motherId[iPart]==25 ) {
        photon.SetPtEtaPhiM( genPart_pt[iPart], genPart_eta[iPart], genPart_phi[iPart], genPart_mass[iPart] );
        foundPhoton = true;
      }

    } // for genparts

    if( tauEvent ) continue;
    if( !foundLeptPlus || !foundLeptMinus || !foundPhoton ) continue;


    if( photon.Pt() < 40. ) continue;
    float ptMax = TMath::Max( leptPlus.Pt(), leptMinus.Pt() );
    float ptMin = TMath::Min( leptPlus.Pt(), leptMinus.Pt() );
    if( ptMax<25. ) continue;
    if( ptMin<20. ) continue;
    if( fabs( photon.Eta() ) > 2.5 ) continue;
    if( fabs( photon.Eta())>1.44 && fabs( photon.Eta())<1.57 ) continue;
    if( fabs( leptPlus.Eta() ) > 2.4 ) continue;
    if( fabs( leptMinus.Eta() ) > 2.4 ) continue;
    if( photon.DeltaR( leptPlus  ) < 0.4 ) continue;
    if( photon.DeltaR( leptMinus ) < 0.4 ) continue;

    TLorentzVector zBoson = leptPlus + leptMinus;
    if( zBoson.M() < 50. ) continue;

    TLorentzVector boss = zBoson + photon;
    if( boss.M() < 200. ) continue;

    if( photon.Pt()/boss.M()< 40./150. ) continue;

    x->setVal(boss.M());

    data->add(RooArgSet(*x));

  }


  //RooRealVar* bw_mean  = new RooRealVar( "bw_mean", "Breit-Wigner Mean" , mass, 0.2*mass, 1.8*mass );
  //RooRealVar* bw_gamma = new RooRealVar( "bw_gamma", "Breit-Wigner Width", 0.01*mass, 0., 0.3*mass );
  //RooBreitWigner* model = new RooBreitWigner( "bw", "Breit-Wigner", *x, *bw_mean, *bw_gamma);

  // Crystal-Ball
  RooRealVar mean( "mean", "mean", mass, 0.9*mass, 1.1*mass );
  RooRealVar sigma( "sigma", "sigma", 0.015*mass, 0., 0.07*mass );
  RooRealVar alpha1( "alpha1", "alpha1", 1.2, 0., 2.5 );
  RooRealVar n1( "n1", "n1", 3., 0., 5. );
  RooRealVar alpha2( "alpha2", "alpha2", 1.2, 0., 2.5 );
  RooRealVar n2( "n2", "n2", 3., 0., 10. );
  RooDoubleCBShape* model = new RooDoubleCBShape( "cb", "cb", *x, mean, sigma, alpha1, n1, alpha2, n2 );

  model->fitTo( *data );

  int npoints = gr_mean->GetN();
  gr_mean  ->SetPoint( npoints, mass, mean.getVal() );
  gr_sigma ->SetPoint( npoints, mass, sigma.getVal() );
  gr_width ->SetPoint( npoints, mass, sigma.getVal()/mean.getVal() );
  gr_alpha1->SetPoint( npoints, mass, alpha1.getVal() );
  gr_alpha2->SetPoint( npoints, mass, alpha2.getVal() );
  gr_n1    ->SetPoint( npoints, mass, n1.getVal() );
  gr_n2    ->SetPoint( npoints, mass, n2.getVal() );

  gr_mean  ->SetPointError( npoints, 0., mean.getError() );
  gr_sigma ->SetPointError( npoints, 0., sigma.getError() );
  gr_width ->SetPointError( npoints, 0., sigma.getError()/mean.getVal() );
  gr_alpha1->SetPointError( npoints, 0., alpha1.getError() );
  gr_alpha2->SetPointError( npoints, 0., alpha2.getError() );
  gr_n1    ->SetPointError( npoints, 0., n1.getError() );
  gr_n2    ->SetPointError( npoints, 0., n2.getError() );

  //gr_mean ->SetPoint     ( npoints, mass, bw_mean->getVal() );
  //gr_gamma->SetPoint     ( npoints, mass, bw_gamma->getVal() );
  //gr_width->SetPoint     ( npoints, mass, bw_gamma->getVal()/bw_mean->getVal() );
  //gr_mean ->SetPointError( npoints,   0., bw_mean->getError() );
  //gr_gamma->SetPointError( npoints,   0., bw_gamma->getError()/bw_mean->getVal() );
  //gr_width->SetPointError( npoints,   0., bw_gamma->getError()/bw_mean->getVal() );

  RooPlot* plot = x->frame();
  data->plotOn(plot);
  model->plotOn(plot);

  TCanvas* c1 = new TCanvas( "c1", "", 600, 600 );
  c1->cd();

  plot->Draw();
    
  c1->SaveAs( Form("%s/fit_m%.0f_%s.eps", outdir.c_str(), mass, width.c_str()) );
  c1->SaveAs( Form("%s/fit_m%.0f_%s.pdf", outdir.c_str(), mass, width.c_str()) );

  c1->SetLogy();

  c1->SaveAs( Form("%s/fit_m%.0f_%s_log.eps", outdir.c_str(), mass, width.c_str()) );
  c1->SaveAs( Form("%s/fit_m%.0f_%s_log.pdf", outdir.c_str(), mass, width.c_str()) );


  //delete bw_mean;
  //delete bw_gamma;

  delete c1;
  delete data;
  delete model;
  delete plot;
  delete x;

}
예제 #24
0
void fitMass1(int iCharge,double iEtaMin,double iEtaMax,double iPhiMin,double iPhiMax,double &iRes,double &iShift,double &iResErr,double &iShiftErr) { 
  Prep();
  RooRealVar l1Sigma("sigma1","sigma1",1.7 ,0.,15.);  //l1Sigma.setConstant(kTRUE);
  RooRealVar l2Sigma("sigma2","sigma2",1.15,0.,15.);  l2Sigma.setConstant(kTRUE);
  RooRealVar l3Sigma("sigma3","sigma3",2.8,0.,35.);   l3Sigma.setConstant(kTRUE);
  RooRealVar lN     ("n"     ,"n"     ,1.5,-15,15.);  lN.setConstant(kTRUE);
  RooRealVar lExp   ("exp"   ,"exp"   ,-0.003,-15,15.); //lExp.setConstant(kTRUE);
  RooRealVar lR1Mean("mean","mean",90.8,60,150);   //lR1Mean.setConstant(kTRUE);
  RooRealVar lRXVar("XVar","mass(GeV/c^{2})",90,60,120); //lRXVar.setBins(500);
  RooRealVar lRYield("Yield","mass(GeV/c^{2})",10000,0,20000);
  RooVoigtianShape     lGAdd("Add","Add",lRXVar,lR1Mean,l1Sigma,l2Sigma,lN,l3Sigma,true);
  //RooExtendPdf lGEx("Ex","Ex",lGAdd,lRYield);
  //RooAddPdf      lGAdd("XAdd","XAdd",lGAdd1,lExpF,lCFrac);
  RooDataSet *lData = new RooDataSet("crap"  ,"crap",RooArgSet(lRXVar)); 
  RooDataSet *lXData = new RooDataSet("xcrap","xcrap",RooArgSet(lRXVar)); 
  RooDataSet *lYData = new RooDataSet("ycrap","ycrap",RooArgSet(lRXVar)); 
  TFile *lFile = new TFile("../Efficiency/Data/mTPNT8_v1.root");//G39TP.root");
  //TFile *lFile = new TFile("../Efficiency/Data/ZTP8_v2.root");//G39TP.root");
  TTree *lTree = (TTree*) lFile->FindObjectAny("WNtupleIdEffNT");
  float lMt   = 0;  lTree->SetBranchAddress("mt"    ,&lMt);
  int lCharge = 0;  lTree->SetBranchAddress("charge",&lCharge);
  float lEta  = 0;  lTree->SetBranchAddress("eta"   ,&lEta);
  float lPhi  = 0;  lTree->SetBranchAddress("phi"   ,&lPhi);
  float lPt   = 0;  lTree->SetBranchAddress("pt"    ,&lPt);
  float lOPt  = 0;  lTree->SetBranchAddress("jetpt" ,&lOPt);
  float lOPhi  = 0; lTree->SetBranchAddress("jetphi",&lOPhi);
  float lOEta  = 0; lTree->SetBranchAddress("jeteta",&lOEta);
  float lTrkIso   = 0; lTree->SetBranchAddress("trkiso",&lTrkIso);
  float lEcalIso  = 0; lTree->SetBranchAddress("ecaliso",&lEcalIso);
  float lHcalIso  = 0; lTree->SetBranchAddress("hcaliso",&lHcalIso);
  float lChi2     = 0; lTree->SetBranchAddress("chi2"   ,&lChi2);
  int   lNHit     = 0; lTree->SetBranchAddress("nhit"   ,&lNHit);
  Muon  lMuon;         lTree->SetBranchAddress("muon"   ,&lMuon);
  for(int i0 = 0; i0 < lTree->GetEntries();i0++) { 
    if(i0 > 200000) break;
    lTree->GetEntry(i0);
    if(fabs(lPt) < 25 || fabs(lOPt) < 25) continue; 
    if(lMt < 60) continue;
    if(lChi2 > 10) continue;
    if(lNHit < 10) continue;
    if(lMuon.NSeg < 2) continue;
    if(lMuon.NPixel == 0) continue;
    if(lMuon.NValid == 0) continue;
    if(lMuon.Type   != 3) continue;
    if((lTrkIso+lEcalIso+lHcalIso)/lPt > 0.15) continue;
    if(lCharge > 0 && iCharge < 0) continue;
    if(lCharge < 0 && iCharge > 0) continue;
    //if(lEta < iEtaMin || lEta > iEtaMax) continue;
    if(lPhi < iPhiMin || lPhi > iPhiMax) continue;
    //if(lEta < iPhiMin || lEta > iPhiMax) continue;
    if(lCharge > 0) lRXVar.setVal(correct(lMt,lPhi,lOPhi,lEta,lOEta));
    if(lCharge < 0) lRXVar.setVal(correct(lMt,lOPhi,lPhi,lOEta,lEta));
    //cout << "====> " << lMt << " ---> " << lRXVar.getVal() << " --- " << endl;
    //lXData->add(RooArgSet(lRXVar));
    //lRXVar.setVal(fabs(lMt));
    lYData->add(RooArgSet(lRXVar));
  }
  /*
    RooHistPdf  *lMYPdf  = new RooHistPdf ("MY","MY",RooArgList(lRXVar),*lYData->binnedClone()); 
    TFile *lQFile = new TFile("../Efficiency/Data/mTPNT8_v1.root");//G39TP.root");
    TTree *lQTree = (TTree*) lQFile->FindObjectAny("WNtupleIdEffNT");
    lQTree->SetBranchAddress("mt"    ,&lMt);
    lQTree->SetBranchAddress("charge",&lCharge);
    lQTree->SetBranchAddress("eta"   ,&lEta);
    lQTree->SetBranchAddress("phi"   ,&lPhi);
    lQTree->SetBranchAddress("pt"    ,&lPt);
    lQTree->SetBranchAddress("jetpt" ,&lOPt);
    lQTree->SetBranchAddress("jetphi",&lOPhi);
    lQTree->SetBranchAddress("jeteta",&lOEta);
    for(int i0 = 0; i0 < lQTree->GetEntries();i0++) { 
    lQTree->GetEntry(i0);
    //if(lOPt*lPt < 0) continue;
    if(lMt < 60) continue;
    // if(lCharge > 0 && iCharge < 0) continue;
    //if(lCharge < 0 && iCharge > 0) continue;
    //if(lEta < iEtaMin || lEta > iEtaMax) continue;
    //if(lPhi < iPhiMin || lPhi > iPhiMax) continue;
    if(lCharge > 0) lRXVar.setVal(correct(lMt,lPhi,lOPhi,lEta,lOEta));
    if(lCharge < 0) lRXVar.setVal(correct(lMt,lOPhi,lPhi,lOEta,lEta));
    lXData->add(RooArgSet(lRXVar));
    lRXVar.setVal(lMt);
    lData->add(RooArgSet(lRXVar));
  }
  RooHistPdf  *lMPdf   = new RooHistPdf ("MH","MH",RooArgList(lRXVar),*lXData->binnedClone()); 
  */
  lGAdd.fitTo(*lYData,Strategy(1),Minos());
  if(lR1Mean.getError() < 0.01) lGAdd.fitTo(*lYData,Strategy(2),Minos());
  lRXVar.setBins(60);
  iShift = 1./(lR1Mean.getVal()/91.2); iShiftErr = lR1Mean.getError()*91.2/lR1Mean.getVal()/lR1Mean.getVal();
  iRes   = l1Sigma.getVal(); iResErr   = l1Sigma.getError();
  return;
  
  TH1F *lH0 = new TH1F("A","A",1,-5,5); lH0->SetMarkerStyle(21); 
  TH1F *lH1 = new TH1F("B","B",1,-5,5); lH1->SetLineColor(kRed);
  TH1F *lH2 = new TH1F("C","C",1,-5,5); lH2->SetLineColor(kBlue);
  TLegend *lL = new TLegend(0.5,0.5,0.8,0.8); lL->SetFillColor(0); lL->SetBorderSize(0);
  lL->AddEntry(lH0,"data"         ,"lp");
  lL->AddEntry(lH1,"MC-corrected" ,"l");
  lL->AddEntry(lH2,"MC"           ,"l");

  RooPlot *lFrame1 = lRXVar.frame(RooFit::Title("XXX")) ;
  lYData->plotOn(lFrame1);
  lGAdd.plotOn(lFrame1);
  //lXData->plotOn(lFrame1,MarkerColor(kRed));
  //lMPdf->plotOn(lFrame1,LineColor(kRed));
  //lMYPdf->plotOn(lFrame1,LineColor(kBlue));
  TCanvas *iC =new TCanvas("A","A",800,600);
  iC->cd(); lFrame1->Draw();
  //lL->Draw();
  iC->SaveAs("Crap.png");
  //cin.get();
  
}
예제 #25
0
//put very small data entries in a binned dataset to avoid unphysical pdfs, specifically for H->ZZ->4l
RooDataSet* makeData(RooDataSet* orig, RooSimultaneous* simPdf, const RooArgSet* observables, RooRealVar* firstPOI, double mass, double& mu_min)
{

  double max_soverb = 0;

  mu_min = -10e9;

  map<string, RooDataSet*> data_map;
  firstPOI->setVal(0);
  RooCategory* cat = (RooCategory*)&simPdf->indexCat();
  TList* datalist = orig->split(*(RooAbsCategory*)cat, true);
  TIterator* dataItr = datalist->MakeIterator();
  RooAbsData* ds;
  RooRealVar* weightVar = new RooRealVar("weightVar","weightVar",1);
  while ((ds = (RooAbsData*)dataItr->Next()))
  {
    string typeName(ds->GetName());
    cat->setLabel(typeName.c_str());
    RooAbsPdf* pdf = simPdf->getPdf(typeName.c_str());
    cout << "pdf: " << pdf << endl;
    RooArgSet* obs = pdf->getObservables(observables);
    cout << "obs: " << obs << endl;

    RooArgSet obsAndWeight(*obs, *weightVar);
    obsAndWeight.add(*cat);
    stringstream datasetName;
    datasetName << "newData_" << typeName;
    RooDataSet* thisData = new RooDataSet(datasetName.str().c_str(),datasetName.str().c_str(), obsAndWeight, WeightVar(*weightVar));

    RooRealVar* firstObs = (RooRealVar*)obs->first();
    //int ibin = 0;
    int nrEntries = ds->numEntries();
    for (int ib=0;ib<nrEntries;ib++)
    {
      const RooArgSet* event = ds->get(ib);
      const RooRealVar* thisObs = (RooRealVar*)event->find(firstObs->GetName());
      firstObs->setVal(thisObs->getVal());

      firstPOI->setVal(0);
      double b = pdf->expectedEvents(*firstObs)*pdf->getVal(obs);
      firstPOI->setVal(1);
      double s = pdf->expectedEvents(*firstObs)*pdf->getVal(obs) - b;

      if (s > 0)
      {
	mu_min = max(mu_min, -b/s);
	double soverb = s/b;
	if (soverb > max_soverb)
	{
	  max_soverb = soverb;
	  cout << "Found new max s/b: " << soverb << " in pdf " << pdf->GetName() << " at m = " << thisObs->getVal() << endl;
	}
      }

      if (b == 0 && s != 0)
      {
	cout << "Expecting non-zero signal and zero bg at m=" << firstObs->getVal() << " in pdf " << pdf->GetName() << endl;
      }
      if (s+b <= 0) 
      {
	cout << "expecting zero" << endl;
	continue;
      }


      double weight = ds->weight();
      if ((typeName.find("ATLAS_H_4mu") != string::npos || 
	   typeName.find("ATLAS_H_4e") != string::npos ||
	   typeName.find("ATLAS_H_2mu2e") != string::npos ||
	   typeName.find("ATLAS_H_2e2mu") != string::npos) && fabs(firstObs->getVal() - mass) < 10 && weight == 0)
      {
	cout << "adding event: " << firstObs->getVal() << endl;
	thisData->add(*event, pow(10., -9.));
      }
      else
      {
	//weight = max(pow(10.0, -9), weight);
	thisData->add(*event, weight);
      }
    }



    data_map[string(ds->GetName())] = (RooDataSet*)thisData;
  }

  
  RooDataSet* newData = new RooDataSet("newData","newData",RooArgSet(*observables, *weightVar), 
				       Index(*cat), Import(data_map), WeightVar(*weightVar));

  orig->Print();
  newData->Print();
  //newData->tree()->Scan("*");
  return newData;

}
예제 #26
0
void fitMass2(int iCharge,double iEtaMin,double iEtaMax,double iPhiMin,double iPhiMax,double &iRes,double &iShift,double &iResErr,double &iShiftErr) { 
  Prep();
  RooRealVar    lXVar  ("XVar","mass(GeV/c^{2})",60,60,120); lXVar.setBins(1000);
  RooRealVar    lSPar  ("SPar","SPar", 1.,0., 2.);
  RooFormulaVar lXShift("uparshift","@0*@1",RooArgList(lXVar,lSPar));
  TFile *lMCFile = new TFile("../Efficiency/Data/ZTP8_v2.root");
  TTree *lMCTree = (TTree*) lMCFile->FindObjectAny("WNtupleIdEffNT"); 
  TH1F *lMass = new TH1F("M","M",100,60,120); 
  int   lCharge = 0;   lMCTree->SetBranchAddress("charge",&lCharge);
  float lEta    = 0;   lMCTree->SetBranchAddress("eta"   ,&lEta);
  float lPhi    = 0;   lMCTree->SetBranchAddress("phi"   ,&lPhi);
  float lMt     = 0;   lMCTree->SetBranchAddress("mt"    ,&lMt);
  float lPt     = 0;   lMCTree->SetBranchAddress("pt"    ,&lPt);
  float lOPt    = 0;   lMCTree->SetBranchAddress("jetpt" ,&lOPt);
  float lOEta   = 0;   lMCTree->SetBranchAddress("jeteta",&lOEta);
  float lOPhi   = 0;   lMCTree->SetBranchAddress("jetphi",&lOPhi);
  float lTrkIso   = 0; lMCTree->SetBranchAddress("trkiso",&lTrkIso);
  float lEcalIso  = 0; lMCTree->SetBranchAddress("ecaliso",&lEcalIso);
  float lHcalIso  = 0; lMCTree->SetBranchAddress("hcaliso",&lHcalIso);
  float lChi2     = 0; lMCTree->SetBranchAddress("chi2"   ,&lChi2);
  unsigned int   lNHit     = 0; lMCTree->SetBranchAddress("nhit"   ,&lNHit);
  Muon  lMuon;         lMCTree->SetBranchAddress("muon"   ,&lMuon);
  double lVPt   = 0; double lEt = 0; double lPx = 0; double lPy = 0;
  for(int i0 = 0; i0 < lMCTree->GetEntries(); i0++) {
    lMCTree->GetEntry(i0);
    if(lMt < 60)          continue;
    if(lChi2 > 10)        continue;
    if(lNHit < 10)        continue;
    if(lMuon.NSeg < 2)    continue;
    if(lMuon.NPixel == 0) continue;
    if(lMuon.NValid == 0) continue;
    if(lMuon.Type   != 3) continue;
    if((lTrkIso+lEcalIso+lHcalIso)/lPt > 0.15) continue;
    //if(lCharge > 0 && iCharge < 0) continue;
    //if(lCharge < 0 && iCharge > 0) continue;
    //if(lEta < iPhiMin || lEta > iPhiMax) continue;
    //if(fabs(lEta) < 1.2) continue;
    //if(lEta < iEtaMin || lEta > iEtaMax) continue;
    //if(lPhi*lOPhi > 0 || lEta*lOEta > 0) continue;
    if(lPhi < iPhiMin || lPhi > iPhiMax) continue;
    lEt = lOPt + lPt; lPx = fabs(lPt)*cos(lPhi) + fabs(lOPt)*cos(lOPhi); lPy = fabs(lPt)*sin(lPhi) + fabs(lOPt)*sin(lOPhi);
    lVPt = sqrt(lPx*lPx + lPy*lPy);
    //if(lVPt < iPhiMin || lVPt > iPhiMax) continue;
    lMass->Fill(fabs(lMt));     //lMass->Fill(lPt);
  }
  RooDataHist *lMHist = new RooDataHist("M" ,"M" ,RooArgSet(lXVar),lMass);
  RooHistPdf  *lMPdf  = new RooHistPdf ("MH","MH",lXShift,lXVar,*lMHist,5); 
  RooRealVar l1Sigma("sigma1","sigma1",0.2,0.,15.);  //l1Sigma.setConstant(kTRUE);
  RooRealVar lR0Mean("xmean","xmean",0,-10,10);    lR0Mean.setConstant(kTRUE);
  RooRealVar lExp   ("exp"   ,"exp"   ,-0.006,-15,15.); //lExp.setConstant(kTRUE);
  RooRealVar lFrac  ("frac","frac"    ,0.9,0.,1);
  RooGaussian   lGaus1("gaus1","gaus1",lXVar,lR0Mean,l1Sigma);
  RooExponential lExpF("Exp","Exp"  ,lXVar,lExp);
  RooFFTConvPdf  lConv("Conv","Conv",lXVar,*lMPdf,lGaus1); //lConv.setBufferStrategy(RooFFTConvPdf::Flat);
  RooAddPdf      lGAdd("Add","Add"  ,lConv,lExpF,lFrac);
  RooDataSet *lData = new RooDataSet("crap","crap",RooArgSet(lXVar)); 
  TFile *lFile = new TFile("../Efficiency/Data/mTPNT8_v1.root");
  TTree *lTree = (TTree*) lFile->FindObjectAny("WNtupleIdEffNT");
  lTree->SetBranchAddress("charge",&lCharge);
  lTree->SetBranchAddress("eta"   ,&lEta);
  lTree->SetBranchAddress("phi"   ,&lPhi);
  lTree->SetBranchAddress("mt"    ,&lMt);
  lTree->SetBranchAddress("pt"    ,&lPt);
  lTree->SetBranchAddress("jetpt" ,&lOPt);
  lTree->SetBranchAddress("jeteta",&lOEta);
  lTree->SetBranchAddress("jetphi",&lOPhi);
  lTree->SetBranchAddress("trkiso",&lTrkIso);
  lTree->SetBranchAddress("ecaliso",&lEcalIso);
  lTree->SetBranchAddress("hcaliso",&lHcalIso);
  lTree->SetBranchAddress("chi2"   ,&lChi2);
  lTree->SetBranchAddress("nhit"   ,&lNHit);
  lTree->SetBranchAddress("muon"   ,&lMuon);
  for(int i0 = 0; i0 < lTree->GetEntries();i0++) { 
    lTree->GetEntry(i0);
    if(lMt < 60)                   continue;
    if(lCharge > 0 && iCharge < 0) continue;
    if(lCharge < 0 && iCharge > 0) continue;
    if(lChi2 > 10) continue;
    if(lNHit < 10) continue;
    if(lMuon.NSeg < 2) continue;
    if(lMuon.NPixel == 0) continue;
    if(lMuon.NValid == 0) continue;
    if(lMuon.Type   != 3) continue;
    if((lTrkIso+lEcalIso+lHcalIso)/lPt > 0.15) continue;
    //if(fabs(lEta) < 1.2) continue;
    //if(lPhi*lOPhi > 0 || lEta*lOEta > 0) continue;
    //if(lEta < iPhiMin || lEta > iPhiMax) continue;
    if(lPhi < iPhiMin || lPhi > iPhiMax) continue;
    lEt = lOPt + lPt; lPx = fabs(lPt)*cos(lPhi) + fabs(lOPt)*cos(lOPhi); lPy = fabs(lPt)*sin(lPhi) + fabs(lOPt)*sin(lOPhi);
    lVPt = sqrt(lPx*lPx + lPy*lPy);
    //if(lVPt < iPhiMin || lVPt > iPhiMax) continue;
    lXVar.setVal(fabs(lMt));
    if(lCharge > 0) lXVar.setVal(correct(lMt,lPhi,lOPhi,lEta,lOEta));
    if(lCharge < 0) lXVar.setVal(correct(lMt,lOPhi,lPhi,lOEta,lEta));
    lData->add(RooArgSet(lXVar));
  }
  /*
  TFile *lQFile = new TFile("");
  TTree *lQTree = (TTree*) lQFile->FindObjectAny("WNtupleIdEffNT");
  lQTree->SetBranchAddress("mt"    ,&lMt);
  lQTree->SetBranchAddress("charge",&lCharge);
  lQTree->SetBranchAddress("eta"   ,&lEta);
  lQTree->SetBranchAddress("phi"   ,&lPhi);
  for(int i0 = 0; i0 < lQTree->GetEntries();i0++) { 
    lQTree->GetEntry(i0);
    if(lMt < 60) continue;
    if(lCharge > 0 && iCharge < 0) continue;
    if(lCharge < 0 && iCharge > 0) continue;
    if(lEta < iEtaMin || lEta > iEtaMax) continue;
    if(lPhi < iPhiMin || lPhi > iPhiMax) continue;
    lXVar.setVal(lMt);
    //lData->add(RooArgSet(lXVar));
  }
  */
  lConv.fitTo(*lData,Strategy(1));
  if(l1Sigma.getError() > 1) lConv.fitTo(*lData,Strategy(2));
  lXVar.setBins(60);
  RooPlot *lFrame1 = lXVar.frame(RooFit::Title("XXX")) ;
  lData->plotOn(lFrame1);
  lConv.plotOn(lFrame1);
  //lGAdd.plotOn(lFrame1,Components("Exp"),LineColor(kRed));
  TCanvas *iC =new TCanvas("A","A",800,600);
  iC->cd(); lFrame1->Draw();
  iC->SaveAs("Crap.png");
  //cin.get();
  iRes = l1Sigma.getVal(); iResErr   = l1Sigma.getError();
  iShift = lSPar.getVal(); iShiftErr = lSPar.getError();
}
예제 #27
0
int main (int argc, char **argv)
{
  const char* chInFile = "ws.root";
  const char* chOutFile = "ws_data.root";
  const char* chRootFile = "BDT20.root";
  const char* chCut = "";

  char option_char;
  while ( (option_char = getopt(argc,argv, "i:o:r:c:")) != EOF )
    switch (option_char)
      {
         case 'i': chInFile = optarg; break;
         case 'o': chOutFile = optarg; break;
         case 'r': chRootFile = optarg; break;
         case 'c': chCut = optarg; break;
         case '?': fprintf (stderr,
                            "usage: %s [i<input file> o<output file>]\n", argv[0]);
      }

  cout << "In  Ws = " << chInFile << endl;
  cout << "Out Ws = " << chOutFile << endl;
  cout << "Data From = " << chRootFile << endl;
  cout << "Extra Cut = " << chCut << endl;


   TFile* in_file = new TFile(chInFile);
   RooWorkspace *rws = (RooWorkspace*) in_file->Get("rws");

   TFile* tree_file = new TFile(chRootFile);
   TTree* tree = (TTree*) tree_file->Get("tree");

   TFile* out_file = new TFile(chOutFile, "RECREATE");

   RooArgSet allVars(*rws->var("m"),*rws->var("t"),*rws->var("et"),*rws->var("cpsi"),*rws->var("ctheta"),*rws->var("phi"),*rws->var("d"));
   RooDataSet* data = new RooDataSet("data","data",allVars);
   RooDataSet* dataBkg = new RooDataSet("dataBkg","dataBkg",allVars);

   TCut* cut = new TCut("5.17<bs_mass && bs_mass<5.57 && bs_epdl<0.02 && bs_pdl<0.40 && bs_pdl>-0.15 && 1.01<phi_mass && phi_mass<1.03");
   *cut += chCut;
   tree->Draw(">>entry_list", *cut, "entrylist");
   TEntryList* event_list = (TEntryList*) out_file->Get("entry_list");

   Double_t dM, dT, dEt, dCpsi, dCtheta, dPhi, dd;
   Int_t ddDefined;
   tree->SetBranchAddress("bs_mass", &dM);
   tree->SetBranchAddress("bs_pdl", &dT);
   tree->SetBranchAddress("bs_epdl", &dEt);
   tree->SetBranchAddress("bs_angle_cpsi", &dCpsi);
   tree->SetBranchAddress("bs_angle_ctheta", &dCtheta);
   tree->SetBranchAddress("bs_angle_phi", &dPhi);
   tree->SetBranchAddress("newtag_ost", &dd);
   tree->SetBranchAddress("newtag_ost_defined", &ddDefined);


   for (Long_t i=0; i<event_list->GetN(); i++){
     tree->GetEntry(event_list->GetEntry(i));

       *rws->var("m")=dM;
       *rws->var("t")=dT/0.0299792458;
       *rws->var("et")=dEt/0.0299792458;
       *rws->var("cpsi")=dCpsi;
       *rws->var("ctheta")=dCtheta;
       *rws->var("phi")=dPhi;

       *rws->var("d")=0;
       ////rws->cat("dilution")->setIndex(0);
       if ( ddDefined==1 ){
    	   ////rws->cat("dilution")->setIndex(1);
    	   *rws->var("d")=dd;
       }

       data->add(allVars);
       if (dM<5.29 || dM>5.44)
           dataBkg->add(allVars);
   }

   rws->import(*data);
   rws->import(*dataBkg);
   rws->Write("rws");
   out_file->Close();
   in_file->Close();
   tree_file->Close();

   cout << endl << "Done." << endl;
}
예제 #28
0
void testConditional() { 
  RooRealVar lRXVar("XVar","XVar",90,60,120); lRXVar.setBins(2000);
  RooRealVar lSPar0("spar0","spar0",1.,0,10);  //lSPar0.setConstant(kTRUE);
  RooRealVar lS1Par0("s1par0","s1par0",1.0   ,0,10);  //lSPar0.setConstant(kTRUE);
  RooRealVar lS1Par1("s1par1","s1par1",0.02 ,-5,5); //lSPar1.setConstant(kTRUE);
  RooRealVar lS1Par2("s1par2","s1par2",-0.05,-5,5); //lSPar2.setConstant(kTRUE);
  RooRealVar lS1Par3("s1par3","s1par3", 0.0 ,-5,5);  //lSPar3.setConstant(kTRUE);
  RooRealVar lS1Par4("s1par4","s1par4",0.06,-5,5);   //lSPar4.setConstant(kTRUE);
  
  RooRealVar lS2Par0("s2par0","s2par0",1.26979,0,10);  //lSPar0.setConstant(kTRUE);
  RooRealVar lS2Par1("s2par1","s2par1",0.0127 ,-5,5); //lSPar1.setConstant(kTRUE);
  RooRealVar lS2Par2("s2par2","s2par2",-0.057,-5,5); //lSPar2.setConstant(kTRUE);
  RooRealVar lS2Par3("s2par3","s2par3",-0.19 ,-5,5);   //lSPar3.setConstant(kTRUE);
  RooRealVar lS2Par4("s2par4","s2par4",0.06  ,-5,5);    //SPar4.setConstant(kTRUE);
  
  RooRealVar lMPar0("mpar0","mpar0",0.,-5,5);
  RooRealVar lMPar1("mpar1","mpar1",0.,-5,5);
  RooRealVar lMPar2("mpar2","mpar2",0.,-5,5); //lMPar2.setConstant(kTRUE);
  RooRealVar lMPar3("mpar3","mpar3",0.,-5,5);
  RooRealVar lMPar4("mpar4","mpar4",0.,-5,5);// lMPar4.setConstant(kTRUE);
  RooRealVar lMPar5("mpar5","mpar5",0.,-5,5);
  RooRealVar lMPar6("mpar6","mpar6",0.,-5,5);
  RooRealVar lRPhi ("phi","phi"  ,0,-3.14,3.14);
  RooRealVar lRPhi2("phi2","phi2"  ,0,-3.14,3.14); 
  RooFormulaVar l1SigmaEta1("sigma1eta1","(@0+@1*@5+@2*@5*@5+@3*@5*@5*@5+@4*@5*@5*@5*@5)",RooArgList(lS1Par0,lS1Par1,lS1Par2,lS1Par3,lS1Par4,lRPhi));//,lSPar3,lSPar4,lRPhi2));    
  RooFormulaVar l1SigmaEta2("sigma1eta2","(@0+@1*@5+@2*@5*@5+@3*@5*@5*@5+@4*@5*@5*@5*@5)",RooArgList(lS1Par0,lS1Par1,lS1Par2,lS1Par3,lS1Par4,lRPhi2));//,lSPar3,lSPar4,lRPhi2));  
  //RooFormulaVar l1Sigma     ("sigma1"   ,"sqrt(@0*@0+@1*@1)"                             ,RooArgList(l1SigmaEta1,l1SigmaEta2));
  RooRealVar l1Sigma("sigma1","sigma1",1.47,0.,3.);    l1Sigma.setConstant(kTRUE);
  RooRealVar l2Sigma("sigma2","sigma2",1.1 ,0.,3.);    l2Sigma.setConstant(kTRUE);
  RooRealVar l3Sigma("sigma3","sigma3",2.8,0.,15.);    l3Sigma.setConstant(kTRUE);
  RooRealVar lN     ("n"     ,"n"     ,1.5,-15,15.);   lN.setConstant(kTRUE);
  //RooRealVar lR1Mean("mean","mean",91.2,60,250);   lR1Mean.setConstant(kTRUE);
  //RooFormulaVar lR1Mean("mean","91.2*sqrt((1+@1*sin(@3+@2))*(1+@1*sin(@6+@2)))+@0",RooArgList(lMPar0,lMPar1,lMPar2,lRPhi,lMPar3,lMPar4,lRPhi2));  //l1Sigma.setConstant(kTRUE);
  RooFormulaVar lR1Mean("mean","91.2*sqrt((1+@1*sin(@3+@2))*(1+@4*sin(@6+@5)))+@0",RooArgList(lMPar0,lMPar1,lMPar2,lRPhi,lMPar3,lMPar4,lRPhi2));  //l1Sigma.setConstant(kTRUE);
  //RooFormulaVar lR1Mean("mean","91.2*sqrt((1+@1*@3+@2*@3*@3+@7*@3*@3*@3)*(1+@4*@6+@5*@6*@6+@8*@6*@6*@6))+@0",RooArgList(lMPar0,lMPar1,lMPar2,lRPhi,lMPar3,lMPar4,lRPhi2,lMPar5,lMPar6));  //l1Sigma.setConstant(kTRUE);
  RooVoigtianShape     lConv("XXX","XXX",lRXVar,lR1Mean,l1Sigma,l2Sigma,lN,l3Sigma,false);
  RooDataSet     *lData = new RooDataSet("crap","crap",RooArgSet(lRXVar,lRPhi,lRPhi2)); 

  TFile *lFile = new TFile("../Efficiency/Data/mTPNT8_v1.root");
  //TFile *lFile = new TFile("../Efficiency/Data/ZTP8_v2.root");
  TTree *lTree = (TTree*) lFile->FindObjectAny("WNtupleIdEffNT");
  float lMt   = 0; lTree->SetBranchAddress("mt"    ,&lMt);
  int lCharge = 0; lTree->SetBranchAddress("charge",&lCharge);
  float lEta  = 0; lTree->SetBranchAddress("eta"   ,&lEta);
  float lPhi  = 0; lTree->SetBranchAddress("phi"   ,&lPhi);
  float lPt   = 0; lTree->SetBranchAddress("pt"    ,&lPt);
  float lOPt  = 0; lTree->SetBranchAddress("jetpt" ,&lOPt);
  float lOPhi = 0; lTree->SetBranchAddress("jetphi",&lOPhi);
  float lOEta = 0; lTree->SetBranchAddress("jeteta",&lOEta);
  float lTrkIso   = 0; lTree->SetBranchAddress("trkiso",&lTrkIso);
  float lEcalIso  = 0; lTree->SetBranchAddress("ecaliso",&lEcalIso);
  float lHcalIso  = 0; lTree->SetBranchAddress("hcaliso",&lHcalIso);
  float lChi2     = 0; lTree->SetBranchAddress("chi2"   ,&lChi2);
  int   lNHit     = 0; lTree->SetBranchAddress("nhit"   ,&lNHit);
  Muon  lMuon;         lTree->SetBranchAddress("muon"   ,&lMuon);
  for(int i0 = 0; i0 < lTree->GetEntries();i0++) { 
    if(i0 > 50000) continue;
    lTree->GetEntry(i0);
    if(lMt < 60) continue;
    if(lChi2 > 10) continue;
    if(lNHit < 10) continue;
    if(lMuon.NSeg < 2) continue;
    if(lMuon.NPixel == 0) continue;
    if(lMuon.NValid == 0) continue;
    if(lMuon.Type   != 3) continue;
    if((lTrkIso+lEcalIso+lHcalIso)/lPt > 0.15) continue;
    if(lMt < 60 || fabs(lEta) > 2.1 || fabs(lOEta) > 2.1 || fabs(lPt) < 25 || fabs(lOPt) < 25)  continue;
    lRXVar.setVal(lMt);

    //if(lCharge > 0) lRXVar.setVal(correct(lMt,lPhi,lOPhi,0,0));//lEta ,lOEta));
    //if(lCharge < 0) lRXVar.setVal(correct(lMt,lOPhi,lPhi,0,0));//lOEta,lEta));
    //lRPhi.setVal(lEta);  lRPhi2.setVal(lOEta);
    //if(lCharge < 0) {lRPhi.setVal(lOEta); lRPhi2.setVal(lEta);}
    lRPhi.setVal(lPhi);  lRPhi2.setVal(lOPhi);
    if(lCharge < 0) {lRPhi.setVal(lOPhi); lRPhi2.setVal(lPhi);}
    lData->add(RooArgSet(lRXVar,lRPhi,lRPhi2));//,lRPhi2));
  }
  lConv.fitTo(*lData,ConditionalObservables(RooArgSet(lRXVar,lRPhi,lRPhi2)),Strategy(1),Minos());
  //lConv.fitTo(*lData,Strategy(1));
  lRXVar.setBins(50);
  RooPlot *lFrame1 = lRXVar.frame(RooFit::Title("XXX")) ;
  lData->plotOn(lFrame1);
  lConv.plotOn(lFrame1);
  TCanvas *iC =new TCanvas("A","A",800,600);
  iC->cd(); lFrame1->Draw();
  iC->SaveAs("Crap.png");
}
예제 #29
0
int KinZfitter::PerZ1Likelihood(double & l1, double & l2, double & lph1, double & lph2)
{

    l1= 1.0; l2 = 1.0;
    lph1 = 1.0; lph2 = 1.0;

    if(debug_) cout<<"start Z1 refit"<<endl;

    TLorentzVector Z1_1 = p4sZ1_[0]; TLorentzVector Z1_2 = p4sZ1_[1];

    double RECOpT1 = Z1_1.Pt(); double RECOpT2 = Z1_2.Pt();
    double pTerrZ1_1 = pTerrsZ1_[0]; double pTerrZ1_2 = pTerrsZ1_[1];

    if(debug_)cout<<"pT1 "<<RECOpT1<<" pTerrZ1_1 "<<pTerrZ1_1<<endl;
    if(debug_)cout<<"pT2 "<<RECOpT2<<" pTerrZ1_2 "<<pTerrZ1_2<<endl;

    //////////////

    TLorentzVector Z1_ph1, Z1_ph2;
    double pTerrZ1_ph1, pTerrZ1_ph2;
    double RECOpTph1, RECOpTph2;

    TLorentzVector nullFourVector(0, 0, 0, 0);
    Z1_ph1=nullFourVector; Z1_ph2=nullFourVector;
    RECOpTph1 = 0; RECOpTph2 = 0;
    pTerrZ1_ph1 = 0; pTerrZ1_ph2 = 0;

    if(p4sZ1ph_.size()>=1){

      Z1_ph1 = p4sZ1ph_[0]; pTerrZ1_ph1 = pTerrsZ1ph_[0];
      RECOpTph1 = Z1_ph1.Pt();
      if(debug_) cout<<"put in Z1 fsr photon 1 pT "<<RECOpTph1<<" pT err "<<pTerrZ1_ph1<<endl; 
    }
    if(p4sZ1ph_.size()==2){
      //if(debug_) cout<<"put in Z1 fsr photon 2"<<endl;
      Z1_ph2 = p4sZ1ph_[1]; pTerrZ1_ph2 = pTerrsZ1ph_[1];
      RECOpTph2 = Z1_ph2.Pt();     
    }

    RooRealVar* pT1RECO = new RooRealVar("pT1RECO","pT1RECO", RECOpT1, 5, 500);
    RooRealVar* pT2RECO = new RooRealVar("pT2RECO","pT2RECO", RECOpT2, 5, 500);
   
    double RECOpT1min = max(5.0, RECOpT1-2*pTerrZ1_1);
    double RECOpT2min = max(5.0, RECOpT2-2*pTerrZ1_2);

    RooRealVar* pTph1RECO = new RooRealVar("pTph1RECO","pTph1RECO", RECOpTph1, 5, 500);
    RooRealVar* pTph2RECO = new RooRealVar("pTph2RECO","pTph2RECO", RECOpTph2, 5, 500);

    double RECOpTph1min = max(0.5, RECOpTph1-2*pTerrZ1_ph1);
    double RECOpTph2min = max(0.5, RECOpTph2-2*pTerrZ1_ph2);

    // observables pT1,2,ph1,ph2
    RooRealVar* pT1 = new RooRealVar("pT1", "pT1FIT", RECOpT1, RECOpT1min, RECOpT1+2*pTerrZ1_1 );
    RooRealVar* pT2 = new RooRealVar("pT2", "pT2FIT", RECOpT2, RECOpT2min, RECOpT2+2*pTerrZ1_2 );

    RooRealVar* m1 = new RooRealVar("m1","m1", Z1_1.M());
    RooRealVar* m2 = new RooRealVar("m2","m2", Z1_2.M());

    if(debug_) cout<<"m1 "<<m1->getVal()<<" m2 "<<m2->getVal()<<endl;

    double Vtheta1, Vphi1, Vtheta2, Vphi2;
    Vtheta1 = (Z1_1).Theta(); Vtheta2 = (Z1_2).Theta();
    Vphi1 = (Z1_1).Phi(); Vphi2 = (Z1_2).Phi();

    RooRealVar* theta1 = new RooRealVar("theta1","theta1",Vtheta1);
    RooRealVar* phi1   = new RooRealVar("phi1","phi1",Vphi1);
    RooRealVar* theta2 = new RooRealVar("theta2","theta2",Vtheta2);
    RooRealVar* phi2   = new RooRealVar("phi2","phi2",Vphi2);

    // dot product to calculate (p1+p2+ph1+ph2).M()
    RooFormulaVar E1("E1","TMath::Sqrt((@0*@0)/((TMath::Sin(@1))*(TMath::Sin(@1)))+@2*@2)",
                          RooArgList(*pT1,*theta1,*m1));
    RooFormulaVar E2("E2","TMath::Sqrt((@0*@0)/((TMath::Sin(@1))*(TMath::Sin(@1)))+@2*@2)",
                          RooArgList(*pT2,*theta2,*m2));
    if(debug_) cout<<"E1 "<<E1.getVal()<<"; E2 "<<E2.getVal()<<endl;

    /////

    RooRealVar* pTph1 = new RooRealVar("pTph1", "pTph1FIT", RECOpTph1, RECOpTph1min, RECOpTph1+2*pTerrZ1_ph1 );
    RooRealVar* pTph2 = new RooRealVar("pTph2", "pTph2FIT", RECOpTph2, RECOpTph2min, RECOpTph2+2*pTerrZ1_ph2 );

    double Vthetaph1, Vphiph1, Vthetaph2, Vphiph2;
    Vthetaph1 = (Z1_ph1).Theta(); Vthetaph2 = (Z1_ph2).Theta();
    Vphiph1 = (Z1_ph1).Phi(); Vphiph2 = (Z1_ph2).Phi();

    RooRealVar* thetaph1 = new RooRealVar("thetaph1","thetaph1",Vthetaph1);
    RooRealVar* phiph1   = new RooRealVar("phiph1","phiph1",Vphiph1);
    RooRealVar* thetaph2 = new RooRealVar("thetaph2","thetaph2",Vthetaph2);
    RooRealVar* phiph2   = new RooRealVar("phiph2","phi2",Vphiph2);

    RooFormulaVar Eph1("Eph1","TMath::Sqrt((@0*@0)/((TMath::Sin(@1))*(TMath::Sin(@1))))", 
                              RooArgList(*pTph1,*thetaph1));
    RooFormulaVar Eph2("Eph2","TMath::Sqrt((@0*@0)/((TMath::Sin(@1))*(TMath::Sin(@1))))", 
                              RooArgList(*pTph2,*thetaph2));

    //// dot products of 4-vectors

    // 3-vector DOT
    RooFormulaVar* p1v3D2 = new RooFormulaVar("p1v3D2",
         "@0*@1*( ((TMath::Cos(@2))*(TMath::Cos(@3)))/((TMath::Sin(@2))*(TMath::Sin(@3)))+(TMath::Cos(@4-@5)))",
         RooArgList(*pT1,*pT2,*theta1,*theta2,*phi1,*phi2));    
    if(debug_) cout<<"p1 DOT p2 is "<<p1v3D2->getVal()<<endl;
    // 4-vector DOT metric 1 -1 -1 -1
    RooFormulaVar p1D2("p1D2","@0*@1-@2",RooArgList(E1,E2,*p1v3D2));

    //lep DOT fsrPhoton1

    // 3-vector DOT
    RooFormulaVar* p1v3Dph1 = new RooFormulaVar("p1v3Dph1",
         "@0*@1*( (TMath::Cos(@2)*TMath::Cos(@3))/(TMath::Sin(@2)*TMath::Sin(@3))+TMath::Cos(@4-@5))",
         RooArgList(*pT1,*pTph1,*theta1,*thetaph1,*phi1,*phiph1));

    // 4-vector DOT metric 1 -1 -1 -1
    RooFormulaVar p1Dph1("p1Dph1","@0*@1-@2",RooArgList(E1,Eph1,*p1v3Dph1));

    // 3-vector DOT
    RooFormulaVar* p2v3Dph1 = new RooFormulaVar("p2v3Dph1",
         "@0*@1*( (TMath::Cos(@2)*TMath::Cos(@3))/(TMath::Sin(@2)*TMath::Sin(@3))+TMath::Cos(@4-@5))",
         RooArgList(*pT2,*pTph1,*theta2,*thetaph1,*phi2,*phiph1));
    // 4-vector DOT metric 1 -1 -1 -1
    RooFormulaVar p2Dph1("p2Dph1","@0*@1-@2",RooArgList(E2,Eph1,*p2v3Dph1));

    // lep DOT fsrPhoton2 

    // 3-vector DOT
    RooFormulaVar* p1v3Dph2 = new RooFormulaVar("p1v3Dph2",
         "@0*@1*( (TMath::Cos(@2)*TMath::Cos(@3))/(TMath::Sin(@2)*TMath::Sin(@3))+TMath::Cos(@4-@5))",
         RooArgList(*pT1,*pTph2,*theta1,*thetaph2,*phi1,*phiph2));

    // 4-vector DOT metric 1 -1 -1 -1
    RooFormulaVar p1Dph2("p1Dph2","@0*@1-@2",RooArgList(E1,Eph2,*p1v3Dph2));

    // 3-vector DOT
    RooFormulaVar* p2v3Dph2 = new RooFormulaVar("p2v3Dph2",
         "@0*@1*( (TMath::Cos(@2)*TMath::Cos(@3))/(TMath::Sin(@2)*TMath::Sin(@3))+TMath::Cos(@4-@5))",
         RooArgList(*pT2,*pTph2,*theta2,*thetaph2,*phi2,*phiph2));
    // 4-vector DOT metric 1 -1 -1 -1
    RooFormulaVar p2Dph2("p2Dph2","@0*@1-@2",RooArgList(E2,Eph2,*p2v3Dph2));

    // fsrPhoton1 DOT fsrPhoton2

    // 3-vector DOT
    RooFormulaVar* ph1v3Dph2 = new RooFormulaVar("ph1v3Dph2",
         "@0*@1*( (TMath::Cos(@2)*TMath::Cos(@3))/(TMath::Sin(@2)*TMath::Sin(@3))+TMath::Cos(@4-@5))",
         RooArgList(*pTph1,*pTph2,*thetaph1,*thetaph2,*phiph1,*phiph2));    
    // 4-vector DOT metric 1 -1 -1 -1
    RooFormulaVar ph1Dph2("ph1Dph2","@0*@1-@2",RooArgList(Eph1,Eph2,*ph1v3Dph2));

    // mZ1

    RooFormulaVar* mZ1;
    mZ1 = new RooFormulaVar("mZ1","TMath::Sqrt(2*@0+@1*@1+@2*@2)",RooArgList(p1D2,*m1,*m2));
    if(p4sZ1ph_.size()==1)
      mZ1 = new RooFormulaVar("mZ1","TMath::Sqrt(2*@0+2*@1+2*@2+@3*@3+@4*@4)",
                                    RooArgList(p1D2, p1Dph1, p2Dph1, *m1,*m2));
    if(p4sZ1ph_.size()==2)
      mZ1 = new RooFormulaVar("mZ1","TMath::Sqrt(2*@0+2*@1+2*@2+2*@3+2*@4+2*@5+@6*@6+@7*@7)",
                              RooArgList(p1D2,p1Dph1,p2Dph1,p1Dph2,p2Dph2,ph1Dph2, *m1,*m2));

    if(debug_) cout<<"mZ1 is "<<mZ1->getVal()<<endl;

    // pTerrs, 1,2,ph1,ph2
    RooRealVar sigmaZ1_1("sigmaZ1_1", "sigmaZ1_1", pTerrZ1_1);
    RooRealVar sigmaZ1_2("sigmaZ1_2", "sigmaZ1_2", pTerrZ1_2);

    RooRealVar sigmaZ1_ph1("sigmaZ1_ph1", "sigmaZ1_ph1", pTerrZ1_ph1);
    RooRealVar sigmaZ1_ph2("sigmaZ1_ph2", "sigmaZ1_ph2", pTerrZ1_ph2);

    // resolution for decay products
    RooGaussian gauss1("gauss1","gaussian PDF", *pT1RECO, *pT1, sigmaZ1_1);
    RooGaussian gauss2("gauss2","gaussian PDF", *pT2RECO, *pT2, sigmaZ1_2);

    RooGaussian gaussph1("gaussph1","gaussian PDF", *pTph1RECO, *pTph1, sigmaZ1_ph1);
    RooGaussian gaussph2("gaussph2","gaussian PDF", *pTph2RECO, *pTph2, sigmaZ1_ph2);

    RooRealVar bwMean("bwMean", "m_{Z^{0}}", 91.187);
    RooRealVar bwGamma("bwGamma", "#Gamma", 2.5);

    RooRealVar sg("sg", "sg", sgVal_);
    RooRealVar a("a", "a", aVal_);
    RooRealVar n("n", "n", nVal_);

    RooCBShape CB("CB","CB",*mZ1,bwMean,sg,a,n);
    RooRealVar f("f","f", fVal_);

    RooRealVar mean("mean","mean",meanVal_);
    RooRealVar sigma("sigma","sigma",sigmaVal_);
    RooRealVar f1("f1","f1",f1Val_);

    RooGenericPdf RelBW("RelBW","1/( pow(mZ1*mZ1-bwMean*bwMean,2)+pow(mZ1,4)*pow(bwGamma/bwMean,2) )", RooArgSet(*mZ1,bwMean,bwGamma) );

    RooAddPdf RelBWxCB("RelBWxCB","RelBWxCB", RelBW, CB, f);
    RooGaussian gauss("gauss","gauss",*mZ1,mean,sigma);
    RooAddPdf RelBWxCBxgauss("RelBWxCBxgauss","RelBWxCBxgauss", RelBWxCB, gauss, f1);

    RooProdPdf *PDFRelBWxCBxgauss;
    PDFRelBWxCBxgauss = new RooProdPdf("PDFRelBWxCBxgauss","PDFRelBWxCBxgauss", 
                                     RooArgList(gauss1, gauss2, RelBWxCBxgauss) );
    if(p4sZ1ph_.size()==1)    
      PDFRelBWxCBxgauss = new RooProdPdf("PDFRelBWxCBxgauss","PDFRelBWxCBxgauss", 
                                     RooArgList(gauss1, gauss2, gaussph1, RelBWxCBxgauss) );
    if(p4sZ1ph_.size()==2)
      PDFRelBWxCBxgauss = new RooProdPdf("PDFRelBWxCBxgauss","PDFRelBWxCBxgauss", 
                                     RooArgList(gauss1, gauss2, gaussph1, gaussph2, RelBWxCBxgauss) );

    // observable set
    RooArgSet *rastmp;
      rastmp = new RooArgSet(*pT1RECO,*pT2RECO);
    if(p4sZ1ph_.size()==1)
      rastmp = new RooArgSet(*pT1RECO,*pT2RECO,*pTph1RECO);
    if(p4sZ1ph_.size()>=2)
      rastmp = new RooArgSet(*pT1RECO,*pT2RECO,*pTph1RECO,*pTph2RECO);

    RooDataSet* pTs = new RooDataSet("pTs","pTs", *rastmp);
    pTs->add(*rastmp); 

    //RooAbsReal* nll;
    //nll = PDFRelBWxCBxgauss->createNLL(*pTs);
    //RooMinuit(*nll).migrad();

    RooFitResult* r = PDFRelBWxCBxgauss->fitTo(*pTs,RooFit::Save(),RooFit::PrintLevel(-1));
    const TMatrixDSym& covMatrix = r->covarianceMatrix();
   
    const RooArgList& finalPars = r->floatParsFinal();
    for (int i=0 ; i<finalPars.getSize(); i++){
        TString name = TString(((RooRealVar*)finalPars.at(i))->GetName());

        if(debug_) cout<<"name list of RooRealVar for covariance matrix "<<name<<endl;

    }

    int size = covMatrix.GetNcols();
    //TMatrixDSym covMatrixTest_(size);
    covMatrixZ1_.ResizeTo(size,size);
    covMatrixZ1_ = covMatrix;   

    if(debug_) cout<<"save the covariance matrix"<<endl;
    
    l1 = pT1->getVal()/RECOpT1; l2 = pT2->getVal()/RECOpT2;
    double pTerrZ1REFIT1 = pT1->getError(); double pTerrZ1REFIT2 = pT2->getError();

    pTerrsZ1REFIT_.push_back(pTerrZ1REFIT1);
    pTerrsZ1REFIT_.push_back(pTerrZ1REFIT2);

    if(p4sZ1ph_.size()>=1){

      if(debug_) cout<<"set refit result for Z1 fsr photon 1"<<endl;

      lph1 = pTph1->getVal()/RECOpTph1;
      double pTerrZ1phREFIT1 = pTph1->getError();
      if(debug_) cout<<"scale "<<lph1<<" pterr "<<pTerrZ1phREFIT1<<endl;  
   
      pTerrsZ1phREFIT_.push_back(pTerrZ1phREFIT1);

    } 
    if(p4sZ1ph_.size()==2){

      lph2 = pTph2->getVal()/RECOpTph2;
      double pTerrZ1phREFIT2 = pTph2->getError();
      pTerrsZ1phREFIT_.push_back(pTerrZ1phREFIT2);

    }

    //delete nll;
    delete r;
    delete mZ1;
    delete pT1; delete pT2; delete pTph1; delete pTph2;
    delete pT1RECO; delete pT2RECO; delete pTph1RECO; delete pTph2RECO;
    delete ph1v3Dph2; delete p1v3Dph1; delete p2v3Dph1; delete p1v3Dph2; delete p2v3Dph2;
    delete PDFRelBWxCBxgauss;
    delete pTs;
    delete rastmp;

    if(debug_) cout<<"end Z1 refit"<<endl;

    return 0;

}
예제 #30
0
void new_RA4(){
  
  // let's time this challenging example
  TStopwatch t;
  t.Start();

  // set RooFit random seed for reproducible results
  RooRandom::randomGenerator()->SetSeed(4357);

  // make model
  RooWorkspace* wspace = new RooWorkspace("wspace");

  wspace->factory("Gaussian::sigCons(prime_SigEff[0,-5,5], nom_SigEff[0,-5,5], 1)");
  wspace->factory("expr::SigEff('1.0*pow(1.20,@0)',prime_SigEff)"); // // 1+-20%, 1.20=exp(20%)

  wspace->factory("Poisson::on(non[0,50], sum::splusb(prod::SigUnc(s[0,0,50],SigEff),mainb[8.8,0,50],dilep[0.9,0,20],tau[2.3,0,20],QCD[0.,0,10],MC[0.1,0,4]))");

  wspace->factory("Gaussian::mcCons(prime_rho[0,-5,5], nom_rho[0,-5,5], 1)");
  wspace->factory("expr::rho('1.0*pow(1.39,@0)',prime_rho)"); // // 1+-39%
  wspace->factory("Poisson::off(noff[0,200], prod::rhob(mainb,rho,mu_plus_e[0.74,0.01,10],1.08))");
  wspace->factory("Gaussian::mcCons2(mu_plus_enom[0.74,0.01,4], mu_plus_e, sigmatwo[.05])");

  wspace->factory("Gaussian::dilep_pred(dilep_nom[0.9,0,20], dilep, sigma3[2.2])");
  wspace->factory("Gaussian::tau_pred(tau_nom[2.3,0,20], tau, sigma4[0.5])");
  wspace->factory("Gaussian::QCD_pred(QCD_nom[0.0,0,10], QCD, sigma5[1.0])");
  wspace->factory("Gaussian::MC_pred(MC_nom[0.1,0.01,4], MC, sigma7[0.14])");

  wspace->factory("PROD::model(on,off,mcCons,mcCons2,sigCons,dilep_pred,tau_pred,QCD_pred,MC_pred)");

  RooArgSet obs(*wspace->var("non"), *wspace->var("noff"), *wspace->var("mu_plus_enom"), *wspace->var("dilep_nom"), *wspace->var("tau_nom"), "obs");
  obs.add(*wspace->var("QCD_nom"));  obs.add(*wspace->var("MC_nom"));
  RooArgSet globalObs(*wspace->var("nom_SigEff"), *wspace->var("nom_rho"), "global_obs");
  // fix global observables to their nominal values
  wspace->var("nom_SigEff")->setConstant();
  wspace->var("nom_rho")->setConstant();

  RooArgSet poi(*wspace->var("s"), "poi");
  RooArgSet nuis(*wspace->var("mainb"), *wspace->var("prime_rho"), *wspace->var("prime_SigEff"), *wspace->var("mu_plus_e"), *wspace->var("dilep"), *wspace->var("tau"), "nuis");
  nuis.add(*wspace->var("QCD"));  nuis.add(*wspace->var("MC"));


  wspace->factory("Uniform::prior_poi({s})");
  wspace->factory("Uniform::prior_nuis({mainb,mu_plus_e,dilep,tau,QCD,MC})");
  wspace->factory("PROD::prior(prior_poi,prior_nuis)");

  wspace->var("non")->setVal(8); //observed
  //wspace->var("non")->setVal(12); //expected observation
  wspace->var("noff")->setVal(7); //observed events in control region
  wspace->var("mu_plus_enom")->setVal(0.74);
  wspace->var("dilep_nom")->setVal(0.9);
  wspace->var("tau_nom")->setVal(2.3);
  wspace->var("QCD")->setVal(0.0);
  wspace->var("MC")->setVal(0.1);


  RooDataSet * data = new RooDataSet("data","",obs);
  data->add(obs);
  wspace->import(*data);


  /////////////////////////////////////////////////////
  // Now the statistical tests
  // model config
  ModelConfig* pSbModel = new ModelConfig("SbModel");
  pSbModel->SetWorkspace(*wspace);
  pSbModel->SetPdf(*wspace->pdf("model"));
  pSbModel->SetPriorPdf(*wspace->pdf("prior"));
  pSbModel->SetParametersOfInterest(poi);
  pSbModel->SetNuisanceParameters(nuis);
  pSbModel->SetObservables(obs);
  pSbModel->SetGlobalObservables(globalObs);
  wspace->import(*pSbModel);

  // set all but obs, poi and nuisance to const
  SetConstants(wspace, pSbModel);
  wspace->import(*pSbModel);


  Double_t poiValueForBModel = 0.0;
  ModelConfig* pBModel = new ModelConfig(*(RooStats::ModelConfig *)wspace->obj("SbModel"));
  pBModel->SetName("BModel");
  pBModel->SetWorkspace(*wspace);
  wspace->import(*pBModel);


  RooAbsReal * pNll = pSbModel->GetPdf()->createNLL(*data);
  RooAbsReal * pProfile = pNll->createProfile(RooArgSet());
  pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
  RooArgSet * pPoiAndNuisance = new RooArgSet();
  //if(pSbModel->GetNuisanceParameters())
  //  pPoiAndNuisance->add(*pSbModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pSbModel->GetParametersOfInterest());
  cout << "\nWill save these parameter points that correspond to the fit to data" << endl;
  pPoiAndNuisance->Print("v");
  pSbModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;


  pNll = pBModel->GetPdf()->createNLL(*data);
  pProfile = pNll->createProfile(poi);
  ((RooRealVar *)poi.first())->setVal(poiValueForBModel);
  pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
  pPoiAndNuisance = new RooArgSet();
  //if(pBModel->GetNuisanceParameters())
  //  pPoiAndNuisance->add(*pBModel->GetNuisanceParameters());
  pPoiAndNuisance->add(*pBModel->GetParametersOfInterest());
  cout << "\nShould use these parameter points to generate pseudo data for bkg only" << endl;
  pPoiAndNuisance->Print("v");
  pBModel->SetSnapshot(*pPoiAndNuisance);
  delete pProfile;
  delete pNll;
  delete pPoiAndNuisance;


  // inspect workspace
  wspace->Print();

  // save workspace to file
  wspace->writeToFile("tight.root");
  //wspace->writeToFile("tight_median.root");


  // clean up
  delete wspace;
  delete data;
  delete pSbModel;
  delete pBModel;

}