コード例 #1
0
void RA2bHypoTestInvDemo(const char * fileName =0,
			 const char * wsName = "combined",
			 const char * modelSBName = "ModelConfig",
			 const char * modelBName = "",
			 const char * dataName = "obsData",                 
			 int calculatorType = 0,
			 int testStatType = 3, 
			 bool useCls = true ,  
			 int npoints = 5,   
			 double poimin = 0,  
			 double poimax = 5, 
			 int ntoys=1000,
			 int mgl = -1,
			 int mlsp = -1,
			 const char * outFileName = "test")    
{
/*

   Other Parameter to pass in tutorial
   apart from standard for filename, ws, modelconfig and data

    type = 0 Freq calculator 
    type = 1 Hybrid 

    testStatType = 0 LEP
                 = 1 Tevatron 
                 = 2 Profile Likelihood
                 = 3 Profile Likelihood one sided (i.e. = 0 if mu < mu_hat)

    useCLs          scan for CLs (otherwise for CLs+b)    

    npoints:        number of points to scan , for autoscan set npoints = -1 

    poimin,poimax:  min/max value to scan in case of fixed scans 
                    (if min >= max, try to find automatically)                           

    ntoys:         number of toys to use 

    extra options are available as global paramters of the macro. They are: 

    plotHypoTestResult   plot result of tests at each point (TS distributions) 
    useProof = true;
    writeResult = true;
    nworkers = 4;


   */

   if (fileName==0) { 
      fileName = "results/example_combined_GaussExample_model.root";
      std::cout << "Use standard file generated with HistFactory :" << fileName << std::endl;
   }
   TFile * file = new TFile(fileName); 

   RooWorkspace * w = dynamic_cast<RooWorkspace*>( file->Get(wsName) );
   HypoTestInverterResult * r = 0; 
   std::cout << w << "\t" << fileName << std::endl;
   if (w != NULL) {
      r = RunInverter(w, modelSBName, modelBName, dataName, calculatorType, testStatType, npoints, poimin, poimax,  ntoys, useCls );    
      if (!r) { 
         std::cerr << "Error running the HypoTestInverter - Exit " << std::endl;
         return;          
      }
   }
   else 
   { 
      // case workspace is not present look for the inverter result
      std::cout << "Reading an HypoTestInverterResult with name " << wsName << " from file " << fileName << std::endl;
      r = dynamic_cast<HypoTestInverterResult*>( file->Get(wsName) ); //
      if (!r) { 
         std::cerr << "File " << fileName << " does not contain a workspace or an HypoTestInverterResult - Exit " 
                   << std::endl;
         file->ls();
         return; 
      }
   }		
      		


   printf("\n\n") ;
   HypoTestResult* htr = r->GetResult(0) ;
   printf("  Data value for test stat : %7.3f\n", htr->GetTestStatisticData() ) ;
   printf("  CLsplusb : %9.4f\n", r->CLsplusb(0) ) ;
   printf("  CLb      : %9.4f\n", r->CLb(0) ) ;
   printf("  CLs      : %9.4f\n", r->CLs(0) ) ;
   printf("\n\n") ;
   cout << flush ;

   double upperLimit = r->UpperLimit();
   double ulError = r->UpperLimitEstimatedError();


   std::cout << "The computed upper limit is: " << upperLimit << " +/- " << ulError << std::endl;
 
   const int nEntries = r->ArraySize();


   const char *  typeName = (calculatorType == 0) ? "Frequentist" : "Hybrid";
   const char * resultName = (w) ? w->GetName() : r->GetName();
   TString plotTitle = TString::Format("%s CL Scan for workspace %s",typeName,resultName);
   HypoTestInverterPlot *plot = new HypoTestInverterPlot("HTI_Result_Plot",plotTitle,r);
   TCanvas* c1 = new TCanvas() ;
   plot->Draw("CLb 2CL");  // plot all and Clb
   c1->Update() ;
   c1->SaveAs("cls-canv1.png") ;
   c1->SaveAs("cls-canv1.pdf") ;

   if (plotHypoTestResult) { 
      TCanvas * c2 = new TCanvas();
      c2->Divide( 2, TMath::Ceil(nEntries/2));
      for (int i=0; i<nEntries; i++) {
         c2->cd(i+1);
         SamplingDistPlot * pl = plot->MakeTestStatPlot(i);
         pl->SetLogYaxis(true);
         pl->Draw();
      }
      c2->Update() ;
      c2->SaveAs("cls-canv2.png") ;
      c2->SaveAs("cls-canv2.pdf") ;
   }


   std::cout << " expected limit (median) " <<  r->GetExpectedUpperLimit(0) << std::endl;
   std::cout << " expected limit (-1 sig) " << r->GetExpectedUpperLimit(-1) << std::endl;
   std::cout << " expected limit (+1 sig) " << r->GetExpectedUpperLimit(1) << std::endl;


   // save 2d histograms bin to file

   TH2F *result = new TH2F("result","result",22,100,1200,23,50,1200); 
   TH2F *exp_res = new TH2F("exp_res","exp_res",22,100,1200,23,50,1200); 
   TH2F *exp_res_minus = new TH2F("exp_res_minus","exp_res_minus",22,100,1200,23,50,1200); 
   TH2F *exp_res_plus = new TH2F("exp_res_plus","exp_res_plus",22,100,1200,23,50,1200); 

   result->Fill(mgl,mlsp,upperLimit);
   exp_res->Fill(mgl,mlsp,r->GetExpectedUpperLimit(0));
   exp_res_minus->Fill(mgl,mlsp,r->GetExpectedUpperLimit(-1));
   exp_res_plus->Fill(mgl,mlsp,r->GetExpectedUpperLimit(1));


   TFile *f = new TFile(outFileName,"RECREATE");
   f->cd();

   result->Write();
   exp_res->Write();
   exp_res_minus->Write();
   exp_res_plus->Write();

   f->Close();


   if (w != NULL && writeResult) {

      // write to a file the results
      const char *  calcType = (calculatorType == 0) ? "Freq" : "Hybr";
      const char *  limitType = (useCls) ? "CLs" : "Cls+b";
      const char * scanType = (npoints < 0) ? "auto" : "grid";
      TString resultFileName = TString::Format("%s_%s_%s_ts%d_",calcType,limitType,scanType,testStatType);      
      resultFileName += fileName;
      
      TFile * fileOut = new TFile(resultFileName,"RECREATE");
      r->Write();
      fileOut->Close();                                                                     
   }   

}
コード例 #2
0
ファイル: CreateMuonFakeRateMap.C プロジェクト: sixie/CMSAna
void FitLeptonResponseModels(const string Label = "ZZ", Int_t Option = 0, Int_t PtBin = -1, Int_t EtaBin = -1) {

  string label = Label;
  if (Label != "") label = "_" + Label;
  TFile *fileInput = new TFile(("FakeRate" + label + ".root").c_str(), "READ");

  //********************************************************
  // Bins
  //********************************************************
  const UInt_t NPtBins = 4;
  const UInt_t NEtaBins = 3;
  double ptBins[NPtBins+1] = { 5, 7, 10, 15, 25 };
  double etaBins[NEtaBins+1] = { 0.0, 1.2, 2.2, 2.4 };

  
  //********************************************************
  // Output
  //********************************************************
  TFile *fileOutput = new TFile(("FakeMuonPtResolutionModel" + label + ".root").c_str(), "UPDATE");
  
  TH2F* GaussParamArray_Muons_mean = (TH2F*)fileOutput->Get("GaussParamArray_Muons_mean");
  TH2F* GaussParamArray_Muons_sigma = (TH2F*)fileOutput->Get("GaussParamArray_Muons_sigma");


  if (!GaussParamArray_Muons_mean) {
    GaussParamArray_Muons_mean = new TH2F( "GaussParamArray_Muons_mean", "", NPtBins, 0, NPtBins, NEtaBins, 0, NEtaBins);
    for (uint i=0; i < NPtBins+2; ++i) {
      for (uint j=0; j < NEtaBins+2; ++j) {
        GaussParamArray_Muons_mean->SetBinContent(i,j,0.0);
      }
    }
  }
  if (!GaussParamArray_Muons_sigma) {
    GaussParamArray_Muons_sigma = new TH2F( "GaussParamArray_Muons_sigma", "", NPtBins, 0, NPtBins, NEtaBins, 0, NEtaBins);
    for (uint i=0; i < NPtBins+2; ++i) {
      for (uint j=0; j < NEtaBins+2; ++j) {
        GaussParamArray_Muons_sigma->SetBinContent(i,j,0.0);
      }
    }
  }

  for (uint i=0; i < NPtBins+2; ++i) {
    for (uint j=0; j < NEtaBins+2; ++j) {
      if (i >= 1 && ( j >= 1 && j <= NEtaBins )) {
      } else {
        GaussParamArray_Muons_mean->SetBinContent(i,j,0);
        GaussParamArray_Muons_sigma->SetBinContent(i,j,0);        
      }
    }
  }

  //********************************************************
  // Fit for resolution function 
  //******************************************************** 
  for (uint i=0; i < NPtBins+2; ++i) {
    for (uint j=0; j < NEtaBins+2; ++j) {

      if (PtBin >= 0 && EtaBin >= 0) {
        if (!(i==PtBin && j==EtaBin)) continue;
      }
      
      TH1F* hist = (TH1F*)fileInput->Get(Form("LeptonPtResolution_Muons_PtBin%d_EtaBin%d",i,j));
      assert(hist);

      RooRealVar leptonPtRes("leptonPtRes","leptonPtRes",-1.0,0.25);
      leptonPtRes.setRange("range",-1.00,0.25);
      leptonPtRes.setBins(100);
      RooDataHist *data=0;
      data = new RooDataHist("data","data",RooArgSet(leptonPtRes),hist);

      RooRealVar     *mean  = new RooRealVar("mean","mean",-0.25,-10,10);
      RooRealVar     *sigma = new RooRealVar("sigma","sigma",0.05,0.00001,0.5);

      RooGaussian *model = new RooGaussian("LeptonPtResModel","LeptonPtResModel",leptonPtRes,*mean,*sigma);

      RooFitResult *fitResult=0;
      fitResult = model->fitTo(*data,
                               RooFit::Binned(true),
                               RooFit::Strategy(1),
                               RooFit::Save());

      cout << "Fitted parameters\n";
      cout << mean->getVal() << endl;
      cout << sigma->getVal() << endl;
     
      if (i >= 1 && ( j >= 1 && j <= NEtaBins )) {
        GaussParamArray_Muons_mean->SetBinContent(i,j,mean->getVal());
        GaussParamArray_Muons_sigma->SetBinContent(i,j,sigma->getVal());
      } else {
        GaussParamArray_Muons_mean->SetBinContent(i,j,0);
        GaussParamArray_Muons_sigma->SetBinContent(i,j,0);        
      }




      //Save Workspace
      RooWorkspace *w = new RooWorkspace(Form("LeptonPtResolutionModel_Muons_PtBin%d_EtaBin%d",i,j),Form("LeptonPtResolutionModel_Muons_PtBin%d_EtaBin%d",i,j));
      w->import(*model);
      w->import(*data);
      //w->Print();

      //Make Plot
      RooPlot *frame = leptonPtRes.frame(RooFit::Bins(100));
      data->plotOn(frame,RooFit::MarkerStyle(kFullCircle),RooFit::MarkerSize(0.8),RooFit::DrawOption("ZP"));    
      model->plotOn(frame);

      TCanvas *cv = new TCanvas("cv","cv",800,600);
      
      frame->Draw();
      cv->SaveAs(Form("LeptonPtResolution_Muons%s_PtBin%d_EtaBin%d.gif",label.c_str(),i,j)); 

      fileOutput->WriteTObject(model, Form("LeptonPtResolutionModel_Muons_PtBin%d_EtaBin%d",i,j), "WriteDelete");
      fileOutput->WriteTObject(cv, Form("LeptonPtResolutionFit_Muons_PtBin%d_EtaBin%d",i,j), "WriteDelete");
      fileOutput->WriteTObject(w, w->GetName(), "WriteDelete");

      fileOutput->WriteTObject(GaussParamArray_Muons_mean, "GaussParamArray_Muons_mean", "WriteDelete");
      fileOutput->WriteTObject(GaussParamArray_Muons_sigma, "GaussParamArray_Muons_sigma", "WriteDelete");


    }
  }

  //********************************************************
  // Produce output lookup table
  //******************************************************** 
  ofstream outf_e("FakeMuonResponseMap.h");

  outf_e << "UInt_t FindFakeMuonResponseBin( double value, double bins[], UInt_t nbins) {" << endl;
  outf_e << "  UInt_t nbinboundaries = nbins+1;" << endl;
  outf_e << "  UInt_t bin = 0;" << endl;
  outf_e << "  for (uint i=0; i < nbinboundaries; ++i) {" << endl;
  outf_e << "    if (i < nbinboundaries-1) {" << endl;
  outf_e << "      if (value >= bins[i] && value < bins[i+1]) {" << endl;
  outf_e << "        bin = i+1;" << endl;
  outf_e << "        break;" << endl;
  outf_e << "      }" << endl;
  outf_e << "    } else if (i == nbinboundaries-1) {" << endl;
  outf_e << "      if (value >= bins[i]) {" << endl;
  outf_e << "        bin = nbinboundaries;" << endl;
  outf_e << "        break;" << endl;
  outf_e << "      }" << endl;
  outf_e << "    }    " << endl;
  outf_e << "  }" << endl;
  outf_e << "  return bin;" << endl;
  outf_e << "}" << endl;

  outf_e << endl;
  outf_e << endl;

  outf_e << "Double_t GetMuonResponseMeanPtEta(Double_t Pt, Double_t Eta) {" << endl;

  outf_e << endl;
  outf_e << "  Double_t ptBins[" << NPtBins+1 << "] = {";
  for (uint i=0; i < NPtBins+1; ++i) {
    outf_e << ptBins[i];
    if (i < NPtBins) {
      outf_e << ",";
    }
  }
  outf_e << "};\n";

  outf_e << "  Double_t etaBins[" << NEtaBins+1 << "] = {";
  for (uint i=0; i < NEtaBins+1; ++i) {
    outf_e << etaBins[i];
    if (i < NEtaBins) {
      outf_e << ",";
    }
  }
  outf_e << "};\n";


  outf_e << endl;
  outf_e << endl;

  outf_e << "  Double_t ResponseMean[" << NPtBins+2 << "][" << NEtaBins+2 << "] = {";
  outf_e << endl;

  for (uint i=0; i < NPtBins+2; ++i) {
    outf_e << "    {";
    for (uint j=0; j < NEtaBins+2; ++j) {
      outf_e << GaussParamArray_Muons_mean->GetBinContent(i,j);
      if (j< NEtaBins+1) {
        outf_e << ",";
      }
    }
    if (i< NPtBins+1) {
      outf_e << "    },";
    } else {
      outf_e << "}";
    }
    outf_e << endl;
  }
  
  outf_e << "  };" << endl;

  outf_e << endl;
  outf_e << endl;

  outf_e << "  Int_t tmpPtBin = FindFakeMuonResponseBin( Pt , ptBins, " << NPtBins << ");" << endl;
  outf_e << "  Int_t tmpEtaBin = FindFakeMuonResponseBin( Eta , etaBins, " << NEtaBins << ");" << endl;
  outf_e << "  return ResponseMean[tmpPtBin][tmpEtaBin];" << endl;
  outf_e << "}" << endl;

  outf_e << endl;
  outf_e << endl;

  outf_e << "Double_t GetMuonResponseSigmaPtEta(Double_t Pt, Double_t Eta) {" << endl;

  outf_e << endl;
  outf_e << "  Double_t ptBins[" << NPtBins+1 << "] = {";
  for (uint i=0; i < NPtBins+1; ++i) {
    outf_e << ptBins[i];
    if (i < NPtBins) {
      outf_e << ",";
    }
  }
  outf_e << "};\n";

  outf_e << "  Double_t etaBins[" << NEtaBins+1 << "] = {";
  for (uint i=0; i < NEtaBins+1; ++i) {
    outf_e << etaBins[i];
    if (i < NEtaBins) {
      outf_e << ",";
    }
  }
  outf_e << "};\n";


  outf_e << endl;
  outf_e << endl;

  outf_e << "  Double_t ResponseSigma[" << NPtBins+2 << "][" << NEtaBins+2 << "] = {";
  outf_e << endl;

  for (uint i=0; i < NPtBins+2; ++i) {
    outf_e << "    {";
    for (uint j=0; j < NEtaBins+2; ++j) {
      outf_e << GaussParamArray_Muons_sigma->GetBinContent(i,j);
      if (j< NEtaBins+1) {
        outf_e << ",";
      }
    }
    if (i< NPtBins+1) {
      outf_e << "    },";
    } else {
      outf_e << "}";
    }
    outf_e << endl;
  }
  
  outf_e << "  };" << endl;

  outf_e << endl;
  outf_e << endl;

  outf_e << "  Int_t tmpPtBin = FindFakeMuonResponseBin( Pt , ptBins, " << NPtBins << ");" << endl;
  outf_e << "  Int_t tmpEtaBin = FindFakeMuonResponseBin( Eta , etaBins, " << NEtaBins << ");" << endl;
  outf_e << "  return ResponseSigma[tmpPtBin][tmpEtaBin];" << endl;
  outf_e << "}" << endl;


  outf_e.close();


  fileInput->Close();
  delete fileInput;
  fileOutput->Close();

  gBenchmark->Show("WWTemplate");       
}