Beispiel #1
0
RooFitResult *breakDownFit(RooSimultaneous *m, RooAbsData *d, RooRealVar *mass, bool precondition = false){
	if(precondition){
		 const char *catsName = m->indexCat().GetName();
		 TIterator *it = m->indexCat().typeIterator();
		 while(RooCatType* ci = dynamic_cast<RooCatType*>(it->Next())) {
			 const Text_t *catLabel = ci->GetName();
			 RooAbsPdf *pdf = m->getPdf(Form("%s",catLabel));
			 RooAbsData *reduced = d->reduce(SelectVars(*mass),Cut(Form("%s==%s::%s",catsName, catsName, catLabel)));
			 RooFitResult *r = pdf->fitTo(*reduced,PrintLevel(-1),Save(),
					 Minimizer("Minuit2","migrad"),Strategy(0),Hesse(false),Minos(false),Optimize(false)
					 );
			 cout << catsName << " " << catLabel << " M2migrad0 " << r->status() << endl;
			 if(r->status()!=0){
				 RooFitResult *r = pdf->fitTo(*reduced, PrintLevel(-1), Save());
				 cout << catsName << " " << catLabel << " Mmigrad1 " << r->status() << endl;
			 }
		 }
	}

	RooFitResult *r = m->fitTo(*d, Save(), PrintLevel(-1),
			Strategy(0));
	cout << "Global fit Mmigrad0 " << r->status() << endl;
	if(r->status()!=0){
	 RooFitResult *r = m->fitTo(*d, PrintLevel(-1), Save(),
			 Minimizer("Minuit","minimize"),Strategy(2));
	 cout << "Global fit Mminimize2 " << r->status() << endl;
	 return r;
	}

	return r;
}
//____________________________________
void MakePlots(RooWorkspace* wks) {

  // Make plots of the data and the best fit model in two cases:
  // first the signal+background case
  // second the background-only case.

  // get some things out of workspace
  RooAbsPdf* model = wks->pdf("model");
  RooAbsPdf* sigModel = wks->pdf("sigModel");
  RooAbsPdf* zjjModel = wks->pdf("zjjModel");
  RooAbsPdf* qcdModel = wks->pdf("qcdModel");

  RooRealVar* mu = wks->var("mu");
  RooRealVar* invMass = wks->var("invMass");
  RooAbsData* data = wks->data("data");


  //////////////////////////////////////////////////////////
  // Make plots for the Alternate hypothesis, eg. let mu float

  mu->setConstant(kFALSE);

  model->fitTo(*data,Save(kTRUE),Minos(kFALSE), Hesse(kFALSE),PrintLevel(-1));

  //plot sig candidates, full model, and individual componenets
  new TCanvas();
  RooPlot* frame = invMass->frame() ;
  data->plotOn(frame ) ;
  model->plotOn(frame) ;
  model->plotOn(frame,Components(*sigModel),LineStyle(kDashed), LineColor(kRed)) ;
  model->plotOn(frame,Components(*zjjModel),LineStyle(kDashed),LineColor(kBlack)) ;
  model->plotOn(frame,Components(*qcdModel),LineStyle(kDashed),LineColor(kGreen)) ;

  frame->SetTitle("An example fit to the signal + background model");
  frame->Draw() ;
  //  cdata->SaveAs("alternateFit.gif");

  //////////////////////////////////////////////////////////
  // Do Fit to the Null hypothesis.  Eg. fix mu=0

  mu->setVal(0); // set signal fraction to 0
  mu->setConstant(kTRUE); // set constant

  model->fitTo(*data, Save(kTRUE), Minos(kFALSE), Hesse(kFALSE),PrintLevel(-1));

  // plot signal candidates with background model and components
  new TCanvas();
  RooPlot* xframe2 = invMass->frame() ;
  data->plotOn(xframe2, DataError(RooAbsData::SumW2)) ;
  model->plotOn(xframe2) ;
  model->plotOn(xframe2, Components(*zjjModel),LineStyle(kDashed),LineColor(kBlack)) ;
  model->plotOn(xframe2, Components(*qcdModel),LineStyle(kDashed),LineColor(kGreen)) ;

  xframe2->SetTitle("An example fit to the background-only model");
  xframe2->Draw() ;
  //  cbkgonly->SaveAs("nullFit.gif");

}
Beispiel #3
0
//____________________________________
void DoSPlot(RooWorkspace* ws){
  std::cout << "Calculate sWeights" << std::endl;

  // get what we need out of the workspace to do the fit
  RooAbsPdf* model = ws->pdf("model");
  RooRealVar* zYield = ws->var("zYield");
  RooRealVar* qcdYield = ws->var("qcdYield");
  RooDataSet* data = (RooDataSet*) ws->data("data");

  // fit the model to the data.
  model->fitTo(*data, Extended() );

  // The sPlot technique requires that we fix the parameters
  // of the model that are not yields after doing the fit.
  RooRealVar* sigmaZ = ws->var("sigmaZ");
  RooRealVar* qcdMassDecayConst = ws->var("qcdMassDecayConst");  
  sigmaZ->setConstant();
  qcdMassDecayConst->setConstant();


  RooMsgService::instance().setSilentMode(true);


  // Now we use the SPlot class to add SWeights to our data set
  // based on our model and our yield variables
  RooStats::SPlot* sData = new RooStats::SPlot("sData","An SPlot",
		            *data, model, RooArgList(*zYield,*qcdYield) );


  // Check that our weights have the desired properties

  std::cout << "Check SWeights:" << std::endl;


  std::cout << std::endl <<  "Yield of Z is " 
	    << zYield->getVal() << ".  From sWeights it is "
	    << sData->GetYieldFromSWeight("zYield") << std::endl;


  std::cout << "Yield of QCD is " 
	    << qcdYield->getVal() << ".  From sWeights it is "
	    << sData->GetYieldFromSWeight("qcdYield") << std::endl
	    << std::endl;

  for(Int_t i=0; i < 10; i++)
    {
      std::cout << "z Weight   " << sData->GetSWeight(i,"zYield") 
		<< "   qcd Weight   " << sData->GetSWeight(i,"qcdYield") 
		<< "  Total Weight   " << sData->GetSumOfEventSWeight(i) 
		<< std::endl;
    }

  std::cout << std::endl;

  // import this new dataset with sWeights
 std::cout << "import new dataset with sWeights" << std::endl;
 ws->import(*data, Rename("dataWithSWeights"));


}
RooAbsPdf *MakeModel(RooDataHist *data, RooRealVar *mww, char *name) {
    char *modelName = (char*)calloc(50, sizeof(char));
    strcat(modelName, name);
    strcat(modelName, "model");
    char *signalName = (char*)calloc(50, sizeof(char));
    char *backgroundName = (char*)calloc(50, sizeof(char));
    strcat(signalName, name);
    strcat(signalName, "signal");
    strcat(backgroundName, name);
    strcat(backgroundName, "background");

    char *meanName = (char*)calloc(50, sizeof(char));
    strcat(meanName, name);
    strcat(meanName, "mean");

    char *sigmaName = (char*)calloc(50, sizeof(char));
    strcat(sigmaName, name);
    strcat(sigmaName, "sigma");

    char *decayName = (char*)calloc(50, sizeof(char));
    strcat(decayName, name);
    strcat(decayName, "decay");

    char *weightName = (char*)calloc(50, sizeof(char));
    strcat(weightName, name);
    strcat(weightName, "weight");

    RooRealVar *mean = new RooRealVar(meanName, "mean", 0, 10000, "GeV");
    RooRealVar *sigma = new RooRealVar(sigmaName, "sigma", 0, 3000, "GeV");
    RooGaussian *signal = new RooGaussian(signalName, "signal", *mww, *mean, *sigma);

    RooRealVar *decay = new RooRealVar(decayName, "decay", -10, 10, "GeV");
    RooExponential *background = new RooExponential(backgroundName, "background", *mww, *decay);

    RooRealVar *weight = new RooRealVar("decayweight", "weight", 0, 1.0, "None");

    RooAbsPdf *model = new RooAddPdf(modelName, "model", RooArgList(*signal, *background), RooArgList(*weight), kTRUE);

    model->fitTo(*data);
    mean->setConstant();
    sigma->setConstant();
    weight->setConstant();
    decay->setConstant();
    return model;
}
Beispiel #5
0
void rf510_wsnamedsets()
{
  // C r e a t e   m o d e l   a n d   d a t a s e t
  // -----------------------------------------------

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

  // Exploit convention encoded in named set "parameters" and "observables"
  // to use workspace contents w/o need for introspected
  RooAbsPdf* model = w->pdf("model") ;

  // Generate data from p.d.f. in given observables
  RooDataSet* data = model->generate(*w->set("observables"),1000) ;

  // Fit model to data
  model->fitTo(*data) ;
  
  // Plot fitted model and data on frame of first (only) observable
  RooPlot* frame = ((RooRealVar*)w->set("observables")->first())->frame() ;
  data->plotOn(frame) ;
  model->plotOn(frame) ;

  // Overlay plot with model with reference parameters as stored in snapshots
  w->loadSnapshot("reference_fit") ;
  model->plotOn(frame,LineColor(kRed)) ;
  w->loadSnapshot("reference_fit_bkgonly") ;
  model->plotOn(frame,LineColor(kRed),LineStyle(kDashed)) ;


  // Draw the frame on the canvas
  new TCanvas("rf510_wsnamedsets","rf503_wsnamedsets",600,600) ;
  gPad->SetLeftMargin(0.15) ; frame->GetYaxis()->SetTitleOffset(1.4) ; frame->Draw() ;


  // Print workspace contents
  w->Print() ;


  // Workspace will remain in memory after macro finishes
  gDirectory->Add(w) ;

}
Beispiel #6
0
void MCStudy()
{
    
    string fileName = "h4l_Template_2012_lowmass_unconstrained_new_v00.root";
    
    const char * wsName      = "combined";    //"w";
    const char * modelSBName = "ModelConfig"; //"modelConfig";
    const char * dataName    = dataname.c_str();
    
    TFile* file = TFile::Open(fileName);

    // get the workspace out of file
    RooWorkspace* w = (RooWorkspace*) file->Get(wsName);
    if (!wsName) {
        cout << "workspace not found" << endl;
        return -1.0;
    }
    
    // get the modelConfig out of the file
    ModelConfig* sbModel = (ModelConfig*) w->obj(modelSBName);
    
    // get the data out of file
    //RooAbsData* data = w->data(dataName);
    
    // get toy MC data
    TFile *fhist = new TFile("../ToyMC/toyMC_ggF125.root");
    TH1F *hsum = (TH1F*) fhist->Get("sumtoy1");
    
    RooRealVar m4l("m4l","m4l",120,130);
    RooDataHist* data = new RooDataHist("data","data",x,hsum);
    
    // get pdf
    RooAbsPdf* model = sbModel->GetPdf();
    
    RooPlot* xframe = m4l.frame();
    data->plotOn(xframe);
    model->fitTo(*data);
    model->plotOn(xframe,LineColor(kRed));
    
    TCanvas *c = new TCanvas("c","c");
    xframe->Draw();
    
}
Beispiel #7
0
RooDataSet * getDataAndFrac(TString name, TString q2name, TreeReader * mydata, TCut cut, RooRealVar * MM, double * frac, Str2VarMap jpsiPars, double *outnsig)
{
	RooRealVar * cosThetaL = new RooRealVar("cosThetaL","cosThetaL",0.,-1.,1.);
	RooRealVar * cosThetaB = new RooRealVar("cosThetaB","cosThetaB",0.,-1.,1.);
	TCut massCut = "Lb_MassConsLambda > 5590 && Lb_MassConsLambda < 5650";

	Analysis * ana = new Analysis(name+"_mass"+q2name,"Lb",mydata,&cut,MM);
	ana->AddVariable("J_psi_1S_MM");
	ana->AddVariable(cosThetaL);
	ana->AddVariable(cosThetaB);
	RooAbsPdf * mysig = stringToPdf("Gauss","sig",MM,jpsiPars);
	RooAbsPdf * mybkg = stringToPdf("Exp","bkgM",MM);
	RooRealVar * mynsig = new RooRealVar("mynsig","mynsig",50,0,100000);
	RooRealVar * mynbkg = new RooRealVar("mynbkg","mynbkg",10,0,100000);
	RooAbsPdf * Mmodel = new RooAddPdf("MassModel","MassModel",RooArgSet(*mysig,*mybkg),RooArgSet(*mynsig,*mynbkg));
	ana->applyCuts(&cut);
	RooDataSet * data = ana->GetDataSet("-recalc");
	Mmodel->fitTo(*data,Extended(kTRUE));
	
	double sigBkg = mybkg->createIntegral(*MM,NormSet(*MM),Range("Signal"))->getVal();
	double sig = mysig->createIntegral(*MM,NormSet(*MM),Range("Signal"))->getVal();
	double nsig = mynsig->getVal();
	double nbkg = mynbkg->getVal();
	if(frac)
	{
		frac[0] = nsig*sig/(nsig*sig+nbkg*sigBkg);
		frac[1] = frac[0]*TMath::Sqrt( TMath::Power(mynsig->getError()/nsig,2) + TMath::Power(mynbkg->getError()/nbkg,2) );
	}
	TCut mycut = cut + massCut;
	ana->applyCuts(&mycut);

	TCanvas * cc = new TCanvas();
	GetFrame(MM,Mmodel,data,"-nochi2-plotAllComp",30,NULL,0,"cos#theta_{#Lambda}")->Draw();
	cc->Print("M_"+name+"_"+q2name+".pdf");
	if(*outnsig) *outnsig = nsig;
	return ana->GetDataSet("-recalc");
}
Beispiel #8
0
void rf509_wsinteractive()
{
  // C r e a t e  a n d   f i l l   w o r k s p a c e
  // ------------------------------------------------

  // Create a workspace named 'w'
  // With CINT w could exports its contents to 
  // a same-name C++ namespace in CINT 'namespace w'.
  // but this does not work anymore in CLING. 
  // so this tutorial is an example on how to 
  // change the code
  RooWorkspace* w = new RooWorkspace("w",kTRUE) ;

  // Fill workspace with p.d.f. and data in a separate function
  fillWorkspace(*w) ;

  // Print workspace contents
  w->Print() ;

  // this does not work anymore with CLING 
  // use normal workspace functionality 

 
  // U s e   w o r k s p a c e   c o n t e n t s   
  // ----------------------------------------------


  // Old syntax to use the name space prefix operator to access the workspace contents
  //
  //RooDataSet* d = w::model.generate(w::x,1000) ;
  //RooFitResult* r = w::model.fitTo(*d) ;

  // use normal workspace methods
  RooAbsPdf * model = w->pdf("model");
  RooRealVar * x = w->var("x");

  RooDataSet* d = model->generate(*x,1000) ;
  RooFitResult* r = model->fitTo(*d) ;

  // old syntax to access the variable x
  // RooPlot* frame = w::x.frame() ;

  RooPlot* frame = x->frame() ;
  d->plotOn(frame) ;

  // OLD syntax to ommit x::
  // NB: The 'w::' prefix can be omitted if namespace w is imported in local namespace
  // in the usual C++ way
  //
  // using namespace w;
  // model.plotOn(frame) ;
  // model.plotOn(frame,Components(bkg),LineStyle(kDashed)) ;

  // new correct syntax 
  RooAbsPdf *bkg = w->pdf("bkg");
  model->plotOn(frame);
  model->plotOn(frame,Components(*bkg),LineStyle(kDashed)) ;

  // Draw the frame on the canvas
  new TCanvas("rf509_wsinteractive","rf509_wsinteractive",600,600) ;
  gPad->SetLeftMargin(0.15) ; frame->GetYaxis()->SetTitleOffset(1.4) ; frame->Draw() ;


}
Beispiel #9
0
void FitterUtils::prepare_PDFs(string trigStr, string BDTVar, double BDTcut,
      string signalfile, string partrecofile, string combfile, string JpsiLeakfile,
      double minBMass, double maxBMass,
      string signaltree, string partrecotree, string combtree, string JpsiLeaktree)
{


   //***********Get the datasets
   TFile* fSignal = new TFile(signalfile.c_str());
   TTree* tSignal = (TTree*)fSignal->Get(signaltree.c_str());
   TFile* fPartReco = new TFile(partrecofile.c_str());
   TTree* tPartReco = (TTree*)fPartReco->Get(partrecotree.c_str());
   TFile* fComb = new TFile(combfile.c_str());
   TTree* tComb = (TTree*)fComb->Get(combtree.c_str()); 
   TFile* fJpsiLeak = new TFile(JpsiLeakfile.c_str());
   TTree* tJpsiLeak = (TTree*)fJpsiLeak->Get(JpsiLeaktree.c_str()); 


   //**********Define variables
   RooRealVar trigVar(trigStr.c_str(), trigStr.c_str(), -10, 10);
   RooRealVar BDTRooRealVar(BDTVar.c_str(), BDTVar.c_str(), -1,1);
   RooRealVar B_plus_M("B_plus_M", "M_{visible}", minBMass, maxBMass, "MeV");
   RooRealVar misPT("misPT", "p_{#perp}", 0, 5000, "MeV");
   RooRealVar B_plus_DTFM_M_zero("B_plus_DTFM_M_zero", "M_{constr}", 0, 20000, "MeV"); 
   RooRealVar e_plus_BremMultiplicity("e_plus_BremMultiplicity","e_plus_BremMultiplicity", -1,2);
   RooRealVar e_minus_BremMultiplicity("e_minus_BremMultiplicity","e_minus_BremMultiplicity", -1,2);

   RooRealVar weightPartReco("weightPartReco", "weightPartReco", 0, 10);
   RooRealVar weightLeakage("weightLeakage", "weightLeakage", 0, 10);
   RooRealVar dataMCWeightee("DataMCWeightee", "DataMCWeightee",0, 30);


   //***********Set only variables needed

   tSignal->SetBranchStatus("*", 0); tSignal->SetBranchStatus("B_plus_M", 1); tSignal->SetBranchStatus("misPT", 1); tSignal->SetBranchStatus("B_plus_DTFM_M_zero", 1); tSignal->SetBranchStatus(BDTVar.c_str(),1);
   tSignal->SetBranchStatus("e_plus_BremMultiplicity", 1); tSignal->SetBranchStatus("e_minus_BremMultiplicity", 1); tSignal->SetBranchStatus(trigStr.c_str()); tSignal->SetBranchStatus("DataMCWeightee",1);

   tPartReco->SetBranchStatus("*", 0); tPartReco->SetBranchStatus("B_plus_M", 1); tPartReco->SetBranchStatus("misPT", 1); tPartReco->SetBranchStatus("B_plus_DTFM_M_zero", 1);tPartReco->SetBranchStatus(BDTVar.c_str(),1);
   tPartReco->SetBranchStatus("e_plus_BremMultiplicity", 1); tPartReco->SetBranchStatus("e_minus_BremMultiplicity", 1); tPartReco->SetBranchStatus(trigStr.c_str()); tPartReco->SetBranchStatus("weightPartReco",1);

   tComb->SetBranchStatus("*", 0); tComb->SetBranchStatus("B_plus_M", 1); tComb->SetBranchStatus("misPT", 1); tComb->SetBranchStatus("B_plus_DTFM_M_zero", 1);tComb->SetBranchStatus(BDTVar.c_str(),1);
   tComb->SetBranchStatus("e_plus_BremMultiplicity", 1); tComb->SetBranchStatus("e_minus_BremMultiplicity", 1); tComb->SetBranchStatus(trigStr.c_str());

   tJpsiLeak->SetBranchStatus("*", 0); tJpsiLeak->SetBranchStatus("B_plus_M", 1); tJpsiLeak->SetBranchStatus("misPT", 1); 
   tJpsiLeak->SetBranchStatus("B_plus_DTFM_M_zero", 1);tJpsiLeak->SetBranchStatus(BDTVar.c_str(),1);
   tJpsiLeak->SetBranchStatus("e_plus_BremMultiplicity", 1); tJpsiLeak->SetBranchStatus("e_minus_BremMultiplicity", 1); tJpsiLeak->SetBranchStatus(trigStr.c_str()); 
   tJpsiLeak->SetBranchStatus("weightLeakage",1);


   //***********Set Binning


   RooBinning defaultMBins(floor((maxBMass-minBMass)/(40.)), B_plus_M.getMin(), B_plus_M.getMax() ); 
   RooBinning defaultMisPTBins(floor(40), misPT.getMin(), misPT.getMax()); 
   RooBinning broaderMBins(floor((maxBMass-minBMass)/(80.)), B_plus_M.getMin(), B_plus_M.getMax()); 
   RooBinning broaderMisPTBins(floor(40), misPT.getMin(), misPT.getMax()); 

   B_plus_M.setBinning( defaultMBins);
   misPT.setBinning( defaultMisPTBins );
   B_plus_M.setBinning( broaderMBins, "broaderBins");
   misPT.setBinning( broaderMisPTBins, "broaderBins" );

   B_plus_DTFM_M_zero.setBins(100);

   RooArgSet argset(BDTRooRealVar, B_plus_DTFM_M_zero, misPT,  B_plus_M, trigVar, e_plus_BremMultiplicity, e_minus_BremMultiplicity);
   RooArgSet argsetPartReco(BDTRooRealVar, B_plus_DTFM_M_zero, misPT,  B_plus_M, trigVar, e_plus_BremMultiplicity, e_minus_BremMultiplicity, weightPartReco);
   RooArgSet argsetLeakage(BDTRooRealVar, B_plus_DTFM_M_zero, misPT,  B_plus_M, trigVar, e_plus_BremMultiplicity, e_minus_BremMultiplicity, weightLeakage);
   RooArgSet argsetSignal(BDTRooRealVar, B_plus_DTFM_M_zero, misPT,  B_plus_M, trigVar, e_plus_BremMultiplicity, e_minus_BremMultiplicity, dataMCWeightee);

   cout<<"getting the datasets:"<<endl;

   RooDataSet* dataSetSignalZeroGamma;
   RooDataSet* dataSetSignalOneGamma;
   RooDataSet* dataSetSignalTwoGamma;
   RooDataSet* dataSetPartReco;
   RooDataSet* dataSetJpsiLeak;
   RooDataSet* dataSetComb;

   TFile* fw(NULL);

   string BDTCutString( ("("+BDTVar+">"+d2s(BDTcut)+")").c_str()  );

   dataSetSignalZeroGamma = new RooDataSet("dataSetSignalZeroGamma", "dataSetSignalZeroGamma", argsetSignal, Import(*tSignal), Cut(( " ("+trigStr+"  > 0.9) && "+BDTCutString+" && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) > -0.5) && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) < 0.5) && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("DataMCWeightee")  );

   dataSetSignalOneGamma = new RooDataSet("dataSetSignalOneGamma", "dataSetSignalOneGamma", argsetSignal, Import(*tSignal), Cut(( " ("+trigStr+"  > 0.9) && "+BDTCutString+" && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) > 0.5) && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) < 1.5) && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("DataMCWeightee")  );

   dataSetSignalTwoGamma = new RooDataSet("dataSetSignalTwoGamma", "dataSetSignalTwoGamma", argsetSignal, Import(*tSignal), Cut(( " ("+trigStr+"  > 0.9) && "+BDTCutString+" && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) > 1.5) && ((e_plus_BremMultiplicity+e_minus_BremMultiplicity) < 2.5) && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("DataMCWeightee")  );


   dataSetPartReco = new RooDataSet("dataSetPartReco", "dataSetPartReco",  argsetPartReco, Import(*tPartReco),Cut(("("+trigStr+"  > 0.9) && "+BDTCutString+ " && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("weightPartReco"));

   dataSetJpsiLeak = new RooDataSet("dataSetJpsiLeak", "dataSetJpsiLeak",  argsetLeakage, Import(*tJpsiLeak),Cut(("B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()), WeightVar("weightLeakage"));

    // dataSetComb = new RooDataSet("dataSetComb", "dataSetComb", tComb, argset, ("("+trigStr+"  > 0.9) && (UBDT3R > "+d2s(BDTcut-0.03)+")  && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str());
   dataSetComb = new RooDataSet("dataSetComb", "dataSetComb", tComb, argset, ("("+trigStr+"  > 0.9) && "+BDTCutString+"  && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str());

   cout<<"Number of zero: "<< dataSetSignalZeroGamma->sumEntries()<<endl;
   cout<<"Number of one: "<< dataSetSignalOneGamma->sumEntries()<<endl;
   cout<<"Number of two: "<< dataSetSignalTwoGamma->sumEntries()<<endl;
   cout<<"Number of PartReco: "<< dataSetPartReco->sumEntries()<<endl;
   cout<<"Number of Jpsi leaking:"<< dataSetJpsiLeak->sumEntries()<<endl;
   cout<<"Number of combinatorial events:"<< dataSetComb->sumEntries()<<endl;


   cout<<"binning the datasets:"<<endl;

   RooArgSet argset2(B_plus_M);
   if (fit2D) argset2.add(misPT);

   RooDataHist dataHistSignalZeroGamma("dataHistSignalZeroGamma", "dataHistSignalZeroGamma", argset2, *dataSetSignalZeroGamma); 
   RooDataHist dataHistSignalOneGamma("dataHistSignalOneGamma", "dataHistSignalOneGamma", argset2, *dataSetSignalOneGamma); 
   RooDataHist dataHistSignalTwoGamma("dataHistSignalTwoGamma", "dataHistSignalTwoGamma", argset2, *dataSetSignalTwoGamma); 
   RooDataHist dataHistComb("dataHistComb", "dataHistComb", argset2, *dataSetComb); 
   RooDataHist dataHistPartReco("dataHistPartReco", "dataHistPartReco", argset2, *dataSetPartReco); 
   RooDataHist dataHistJpsiLeak("dataHistJpsiLeak", "dataHistJpsiLeak", argset2, "broaderBins");
   dataHistJpsiLeak.add(*dataSetJpsiLeak); 

   //*************** Compute Error on J/psi leak

   double ErrorJpsi(0);
   if(dataSetJpsiLeak->sumEntries(("("+trigStr+"  > 0.9) && "+BDTCutString+" && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()) > 0) ErrorJpsi = 1./sqrt(dataSetJpsiLeak->sumEntries(("("+trigStr+"  > 0.9) && "+BDTCutString+" && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str()));
   RooRealVar fractionalErrorJpsiLeak("fractionalErrorJpsiLeak", "fractionalErrorJpsiLeak", ErrorJpsi);
   cout<<"JPSI LEAK: "<<dataSetJpsiLeak->sumEntries(("("+trigStr+"  > 0.9) && "+BDTCutString+" && B_plus_M > "+d2s(minBMass)+" && B_plus_M < "+d2s(maxBMass)).c_str());
   cout<<"JPSI LEAK fractional Error: "<<ErrorJpsi<<endl;


   //***************Create 2D histogram estimates from data


   cout<<"Preparing the 3 2D histPdf: 1";
   //   RooArgSet argset2(B_plus_M);
   RooHistPdf histPdfSignalZeroGamma("histPdfSignalZeroGamma", "histPdfSignalZeroGamma", argset2, dataHistSignalZeroGamma,2); cout<<" 2";
   RooHistPdf histPdfSignalOneGamma("histPdfSignalOneGamma", "histPdfSignalOneGamma", argset2, dataHistSignalOneGamma,2); cout<<" 3";
   RooHistPdf histPdfSignalTwoGamma("histPdfSignalTwoGamma", "histPdfSignalTwoGamma", argset2, dataHistSignalTwoGamma,2); cout<<" 4";
   RooHistPdf histPdfPartReco("histPdfPartReco", "histPdfPartReco", argset2, dataHistPartReco,2); cout<<" 5";
   RooHistPdf histPdfJpsiLeak("histPdfJpsiLeak", "histPdfJpsiLeak", argset2, dataHistJpsiLeak,2); cout<<" 6";


   //***************Create combinatorial from fit to data

   RooRealVar expoConst("expoConst", "expoConst", -1e-3, -1, 1);
   RooRealVar T("T", "T", 97, 0, 200);
   RooRealVar n("n", "n", 3.5, 1., 5.5);
   RooAbsPdf *combPDF;

   if (fit2D)
   {  
      combPDF =  new RooPTMVis("PTMVis", "PTMVis", misPT, B_plus_M, T, n, expoConst);
   }
   else
   {
      combPDF =  new RooExponential("histPdfComb", "histPdfComb", B_plus_M, expoConst);
   }



   combPDF->fitTo(*dataSetComb); // 


   if (fit2D)
   {
      T.setConstant(true);
      n.setConstant(true);
      std::cout<<"T generated is: "<<T.getVal()<<std::endl;
   }

   RooRealVar trueExp("trueExp","trueExp", expoConst.getVal(), -1000, 1000);
   trueExp.setError(expoConst.getError());

   RooRealVar trueT("trueT","trueT", T.getVal(), -1000, 1000);
   trueT.setError(T.getError());
   RooRealVar trueN("trueN","trueN", n.getVal(), -1000, 1000);
   trueN.setError(n.getError());


   //***************Save everything on a workspace
   RooWorkspace workspace("workspace", "workspace");
   workspace.import(B_plus_DTFM_M_zero);
   workspace.import(B_plus_M);
   workspace.import(misPT);
   workspace.import(expoConst);
   workspace.import(trueExp);
   workspace.import(T);
   workspace.import(n);
   workspace.import(*dataSetSignalZeroGamma);
   workspace.import(*dataSetSignalOneGamma);
   workspace.import(*dataSetSignalTwoGamma);
   workspace.import(*dataSetPartReco);
   workspace.import(*dataSetComb);
   workspace.import(*dataSetJpsiLeak);
   workspace.import(histPdfSignalZeroGamma);
   workspace.import(histPdfSignalOneGamma);
   workspace.import(histPdfSignalTwoGamma);
   workspace.import(histPdfPartReco);
   workspace.import(histPdfJpsiLeak);
   workspace.import(fractionalErrorJpsiLeak);
   workspace.import(trueT);
   workspace.import(trueN);
   workspace.writeToFile(workspacename.c_str());



   delete fComb;
   delete fSignal;
   delete fPartReco;
   if(fw!=0 && fw != NULL) delete fw;
   delete combPDF;

   delete dataSetSignalZeroGamma; 
   delete dataSetSignalOneGamma;
   delete dataSetSignalTwoGamma;
   delete dataSetPartReco;
   delete dataSetJpsiLeak;
   delete dataSetComb;
}
Beispiel #10
0
float ComputeTestStat(TString wsfile, double mu_susy_sig_val) {

  gROOT->Reset();

  TFile* wstf = new TFile( wsfile ) ;

  RooWorkspace* ws = dynamic_cast<RooWorkspace*>( wstf->Get("ws") );
  ws->Print() ;
  
  ModelConfig* modelConfig = (ModelConfig*) ws->obj( "SbModel" ) ;
  
  modelConfig->Print() ;

  RooDataSet* rds = (RooDataSet*) ws->obj( "ra2b_observed_rds" ) ;
  
  rds->Print() ;
  rds->printMultiline(cout, 1, kTRUE, "") ;
  
  RooAbsPdf* likelihood = modelConfig->GetPdf() ;
  
  RooRealVar* rrv_mu_susy_sig = ws->var("mu_susy_all0lep") ;
  if ( rrv_mu_susy_sig == 0x0 ) {
    printf("\n\n\n *** can't find mu_susy_all0lep in workspace.  Quitting.\n\n\n") ;
    return ;
  } else {
    printf(" current value is : %8.3f\n", rrv_mu_susy_sig->getVal() ) ; cout << flush ;
    rrv_mu_susy_sig->setConstant(kFALSE) ;
  }

  /*
  // check the impact of varying the qcd normalization:

  RooRealVar *rrv_qcd_0lepLDP_ratioH1 = ws->var("qcd_0lepLDP_ratio_H1");
  RooRealVar *rrv_qcd_0lepLDP_ratioH2 = ws->var("qcd_0lepLDP_ratio_H2");
  RooRealVar *rrv_qcd_0lepLDP_ratioH3 = ws->var("qcd_0lepLDP_ratio_H3");
  
  rrv_qcd_0lepLDP_ratioH1->setVal(0.3);
  rrv_qcd_0lepLDP_ratioH2->setVal(0.3);
  rrv_qcd_0lepLDP_ratioH3->setVal(0.3);
  
  rrv_qcd_0lepLDP_ratioH1->setConstant(kTRUE);
  rrv_qcd_0lepLDP_ratioH2->setConstant(kTRUE);
  rrv_qcd_0lepLDP_ratioH3->setConstant(kTRUE);
  */
  
  printf("\n\n\n  ===== Doing a fit with SUSY component floating ====================\n\n") ;

  RooFitResult* fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(0) ) ;
  double logLikelihoodSusyFloat = fitResult->minNll() ;
  
  double logLikelihoodSusyFixed(0.) ;
  double testStatVal(-1.) ;
  if ( mu_susy_sig_val >= 0. ) {
    printf("\n\n\n  ===== Doing a fit with SUSY fixed ====================\n\n") ;
    printf(" fixing mu_susy_sig to %8.2f.\n", mu_susy_sig_val ) ;
    rrv_mu_susy_sig->setVal( mu_susy_sig_val ) ;
    rrv_mu_susy_sig->setConstant(kTRUE) ;
    
    fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(0) ) ;
    logLikelihoodSusyFixed = fitResult->minNll() ;
    testStatVal = 2.*(logLikelihoodSusyFixed - logLikelihoodSusyFloat) ;
    printf("\n\n\n ======= test statistic : -2 * ln (L_fixed / ln L_max) = %8.3f\n\n\n", testStatVal ) ;
  }


  return testStatVal ;

}
   void ws_profile_interval1( const char* wsfile = "ws-test1.root", const char* parName = "mu_susy_sig", double alpha = 0.10, double mu_susy_sig_val = 0., double xmax = -1. ) {




       TFile* wstf = new TFile( wsfile ) ;

       RooWorkspace* ws = dynamic_cast<RooWorkspace*>( wstf->Get("ws") );
       ws->Print() ;






 ////  ModelConfig* modelConfig = (ModelConfig*) ws->obj( "SbModel" ) ;

 ////  printf("\n\n\n  ===== SbModel ====================\n\n") ;
 ////  modelConfig->Print() ;







       RooDataSet* rds = (RooDataSet*) ws->obj( "ra2b_observed_rds" ) ;
       printf("\n\n\n  ===== RooDataSet ====================\n\n") ;

       rds->Print() ;
       rds->printMultiline(cout, 1, kTRUE, "") ;









       printf("\n\n\n  ===== Grabbing %s rrv ====================\n\n", parName ) ;
       RooRealVar* rrv_par = ws->var( parName ) ;
       if ( rrv_par == 0x0 ) {
          printf("\n\n\n *** can't find %s in workspace.  Quitting.\n\n\n", parName ) ; return ;
       } else {
          printf(" current value is : %8.3f\n", rrv_par->getVal() ) ; cout << flush ;
       }
       if ( xmax > 0 ) { rrv_par->setMax( xmax ) ; }

       printf("\n\n\n  ===== Grabbing mu_susy_sig rrv ====================\n\n") ;
       RooRealVar* rrv_mu_susy_sig = ws->var("mu_susy_sig") ;
       if ( rrv_mu_susy_sig == 0x0 ) {
          printf("\n\n\n *** can't find mu_susy_sig in workspace.  Quitting.\n\n\n") ; return ;
       }
       if ( strcmp( parName, "mu_susy_sig" ) != 0 ) {
          if ( mu_susy_sig_val >= 0. ) {
             printf(" current value is : %8.3f\n", rrv_mu_susy_sig->getVal() ) ; cout << flush ;
             printf(" fixing to %8.2f.\n", mu_susy_sig_val ) ;
             rrv_mu_susy_sig->setVal( mu_susy_sig_val ) ;
             rrv_mu_susy_sig->setConstant(kTRUE) ;
          } else {
             printf(" current value is : %8.3f\n", rrv_mu_susy_sig->getVal() ) ; cout << flush ;
             printf(" allowing mu_susy_sig to float.\n") ;
             rrv_mu_susy_sig->setConstant(kFALSE) ;
          }
       } else {
          printf("\n\n profile plot parameter is mu_susy_sig.\n") ;
          rrv_mu_susy_sig->setConstant(kFALSE) ;
       }

       printf("\n\n\n  ===== Grabbing likelihood pdf ====================\n\n") ;
       RooAbsPdf* likelihood = ws->pdf("likelihood") ;
       if ( likelihood == 0x0 ) {
          printf("\n\n\n *** can't find likelihood pdf in workspace.  Quitting.\n\n\n") ; return ;
       } else {
          printf("\n\n likelihood pdf: \n\n") ;
          likelihood->Print() ;
       }












       printf("\n\n\n  ===== Doing a fit ====================\n\n") ;

       likelihood->fitTo( *rds ) ;

       double mlValue = rrv_par->getVal() ;
       printf("  Maximum likelihood value of %s : %8.3f +/- %8.3f\n",
            parName, rrv_par->getVal(), rrv_par->getError() ) ;






       printf("\n\n ========== Creating ProfileLikelihoodCalculator\n\n" ) ; cout << flush ;

    // ProfileLikelihoodCalculator plc( *rds, *modelConfig ) ;
       ProfileLikelihoodCalculator plc( *rds, *likelihood, RooArgSet( *rrv_par ) ) ;

       plc.SetTestSize( alpha ) ;
       ConfInterval* plinterval = plc.GetInterval() ;
       double low  = ((LikelihoodInterval*) plinterval)->LowerLimit(*rrv_par) ;
       double high = ((LikelihoodInterval*) plinterval)->UpperLimit(*rrv_par) ;

       printf("\n\n  Limits: %8.3f,  %8.3f\n\n", low, high ) ;








       printf("\n\n ========= Making profile likelihood plot\n\n") ; cout << flush ;

       LikelihoodIntervalPlot* profPlot = new LikelihoodIntervalPlot((LikelihoodInterval*)plinterval) ;

       TCanvas* cplplot = new TCanvas("cplplot","cplplot", 500, 400) ;
       profPlot->Draw() ;
       gPad->SetGridy(1) ;
       char plotname[10000] ;
       sprintf( plotname, "plplot-%s.png", parName ) ;
       cplplot->SaveAs( plotname ) ;



       if ( alpha > 0.3 ) {
          printf("\n\n\n 1 standard-deviation errors for %s : %8.2f   + %8.2f  - %8.2f\n\n\n",
              parName, mlValue, high-mlValue, mlValue-low ) ;
       }



   }
Beispiel #12
0
void asimov() {


  std::string InputFile = "./data/example.root";

  // Create the measurement
  Measurement meas("meas", "meas");

  meas.SetOutputFilePrefix( "./results/asimov_UsingC" );
  meas.SetPOI( "SigXsecOverSM" );
  meas.AddConstantParam("alpha_syst1");
  meas.AddConstantParam("Lumi");

  meas.SetLumi( 1.0 );
  meas.SetLumiRelErr( 0.10 );
  meas.SetExportOnly( false );
  meas.SetBinHigh( 2 );

  // Create a channel

  Channel chan( "channel1" );
  chan.SetData( "data", InputFile );
  chan.SetStatErrorConfig( 0.05, "Poisson" );

  
  // Now, create some samples


  // Create the signal sample
  Sample signal( "signal", "signal", InputFile );
  signal.AddOverallSys( "syst1",  0.95, 1.05 );
  signal.AddNormFactor( "SigXsecOverSM", 1, 0, 3 );
  chan.AddSample( signal );

  // Background 1
  Sample background1( "background1", "background1", InputFile );
  background1.ActivateStatError( "background1_statUncert", InputFile );
  background1.AddOverallSys( "syst2", 0.95, 1.05  );
  chan.AddSample( background1 );


  // Background 1
  Sample background2( "background2", "background2", InputFile );
  background2.ActivateStatError();
  background2.AddOverallSys( "syst3", 0.95, 1.05  );
  chan.AddSample( background2 );
  

  // Done with this channel
  // Add it to the measurement:
  meas.AddChannel( chan );

  // Collect the histograms from their files,
  // print some output, 
  meas.CollectHistograms();
  //meas.PrintTree();

  // One can print XML code to an
  // output directory:
  // meas.PrintXML( "xmlFromCCode", meas.GetOutputFilePrefix() );

  RooWorkspace* wspace = RooStats::HistFactory::HistoToWorkspaceFactoryFast::MakeCombinedModel(meas);

  // Get the pdf, obs
  RooAbsPdf* pdf = wspace->pdf("simPdf");
  RooDataSet* obsData = (RooDataSet*) wspace->data("obsData");
  RooDataSet* asimovData = (RooDataSet*) wspace->data("asimovData");

  // fit the pdf to the asimov data
  std::cout << "Fitting to Observed Data" << std::endl;
  pdf->fitTo(*obsData);

  std::cout << "Fitting to Asimov Data" << std::endl;
  pdf->fitTo(*asimovData);

  return;

}
void rs603_HLFactoryElaborateExample() {

  // --- Prepare the 2 needed datacards for this example ---

  TString card_name("rs603_card_WsMaker.rs");
  ofstream ofile(card_name);
  ofile << "// The simplest card for combination\n\n";
  ofile << "gauss1 = Gaussian(x[0,100],mean1[50,0,100],4);\n";
  ofile << "flat1 = Polynomial(x,0);\n";
  ofile << "sb_model1 = SUM(nsig1[120,0,300]*gauss1 , nbkg1[100,0,1000]*flat1);\n\n";
  ofile << "echo In the middle!;\n\n";
  ofile << "gauss2 = Gaussian(x,mean2[80,0,100],5);\n";
  ofile << "flat2 = Polynomial(x,0);\n";
  ofile << "sb_model2 = SUM(nsig2[90,0,400]*gauss2 , nbkg2[80,0,1000]*flat2);\n\n";
  ofile << "echo At the end!;\n";
  ofile.close();

  TString card_name2("rs603_card.rs");
  ofstream ofile2(card_name2);
  ofile2 << "// The simplest card for combination\n\n";
  ofile2 << "gauss1 = Gaussian(x[0,100],mean1[50,0,100],4);\n";
  ofile2 << "flat1 = Polynomial(x,0);\n";
  ofile2 << "sb_model1 = SUM(nsig1[120,0,300]*gauss1 , nbkg1[100,0,1000]*flat1);\n\n";
  ofile2 << "echo In the middle!;\n\n";
  ofile2 << "gauss2 = Gaussian(x,mean2[80,0,100],5);\n";
  ofile2 << "flat2 = Polynomial(x,0);\n";
  ofile2 << "sb_model2 = SUM(nsig2[90,0,400]*gauss2 , nbkg2[80,0,1000]*flat2);\n\n";
  ofile2 << "#include rs603_included_card.rs;\n\n";
  ofile2 << "echo At the end!;\n";
  ofile2.close();

  TString card_name3("rs603_included_card.rs");
  ofstream ofile3(card_name3);
  ofile3 << "echo Now reading the included file!;\n\n";
  ofile3 << "echo Including datasets in a Workspace in a Root file...;\n";
  ofile3 << "data1 = import(rs603_infile.root,\n";
  ofile3 << "               rs603_ws,\n";
  ofile3 << "               data1);\n\n";
  ofile3 << "data2 = import(rs603_infile.root,\n";
  ofile3 << "               rs603_ws,\n";
  ofile3 << "               data2);\n";
  ofile3.close();

// --- Produce the two separate datasets into a WorkSpace ---

HLFactory hlf("HLFactoryComplexExample",
              "rs603_card_WsMaker.rs",
              false);

RooRealVar* x = static_cast<RooRealVar*>(hlf.GetWs()->arg("x"));
RooAbsPdf* pdf1 = hlf.GetWs()->pdf("sb_model1");
RooAbsPdf* pdf2 = hlf.GetWs()->pdf("sb_model2");

RooWorkspace w("rs603_ws");

RooDataSet* data1 = pdf1->generate(RooArgSet(*x),Extended());
data1->SetName("data1");
w.import(*data1);

RooDataSet* data2 = pdf2->generate(RooArgSet(*x),Extended());
data2->SetName("data2");
w.import(*data2);

// --- Write the WorkSpace into a rootfile ---

TFile outfile("rs603_infile.root","RECREATE");
w.Write();
outfile.Close();

cout << "-------------------------------------------------------------------\n"
     << " Rootfile and Workspace prepared \n"
     << "-------------------------------------------------------------------\n";


HLFactory hlf_2("HLFactoryElaborateExample",
                "rs603_card.rs",
                false);

x = hlf_2.GetWs()->var("x");
pdf1 = hlf_2.GetWs()->pdf("sb_model1");
pdf2 = hlf_2.GetWs()->pdf("sb_model2");

hlf_2.AddChannel("model1","sb_model1","flat1","data1");
hlf_2.AddChannel("model2","sb_model2","flat2","data2");

RooDataSet* data = hlf_2.GetTotDataSet();
RooAbsPdf* pdf = hlf_2.GetTotSigBkgPdf();
RooCategory* thecat = hlf_2.GetTotCategory();

// --- Perform extended ML fit of composite PDF to toy data ---
pdf->fitTo(*data) ;

// --- Plot toy data and composite PDF overlaid ---
RooPlot* xframe = x->frame() ;

data->plotOn(xframe);
thecat->setIndex(0);
pdf->plotOn(xframe,Slice(*thecat),ProjWData(*thecat,*data)) ;

thecat->setIndex(1);
pdf->plotOn(xframe,Slice(*thecat),ProjWData(*thecat,*data)) ;

gROOT->SetStyle("Plain");

xframe->Draw();

}
Beispiel #14
0
void rf105_funcbinding()
{

   // B i n d   T M a t h : : E r f   C   f u n c t i o n
   // ---------------------------------------------------

   // Bind one-dimensional TMath::Erf function as RooAbsReal function
   RooRealVar x("x","x",-3,3) ;
   RooAbsReal* errorFunc = bindFunction("erf",TMath::Erf,x) ;

   // Print erf definition
   errorFunc->Print() ;

   // Plot erf on frame 
   RooPlot* frame1 = x.frame(Title("TMath::Erf bound as RooFit function")) ;
   errorFunc->plotOn(frame1) ;


   // B i n d   R O O T : : M a t h : : b e t a _ p d f   C   f u n c t i o n
   // -----------------------------------------------------------------------

   // Bind pdf ROOT::Math::Beta with three variables as RooAbsPdf function
   RooRealVar x2("x2","x2",0,0.999) ;
   RooRealVar a("a","a",5,0,10) ;
   RooRealVar b("b","b",2,0,10) ;
   RooAbsPdf* beta = bindPdf("beta",ROOT::Math::beta_pdf,x2,a,b) ;

   // Perf beta definition
   beta->Print() ;

   // Generate some events and fit
   RooDataSet* data = beta->generate(x2,10000) ;
   beta->fitTo(*data) ;

   // Plot data and pdf on frame
   RooPlot* frame2 = x2.frame(Title("ROOT::Math::Beta bound as RooFit pdf")) ;
   data->plotOn(frame2) ;
   beta->plotOn(frame2) ;



   // B i n d   R O O T   T F 1   a s   R o o F i t   f u n c t i o n
   // ---------------------------------------------------------------

   // Create a ROOT TF1 function
   TF1 *fa1 = new TF1("fa1","sin(x)/x",0,10);

   // Create an observable 
   RooRealVar x3("x3","x3",0.01,20) ;

   // Create binding of TF1 object to above observable
   RooAbsReal* rfa1 = bindFunction(fa1,x3) ;

   // Print rfa1 definition
   rfa1->Print() ;

   // Make plot frame in observable, plot TF1 binding function
   RooPlot* frame3 = x3.frame(Title("TF1 bound as RooFit function")) ;
   rfa1->plotOn(frame3) ;



   TCanvas* c = new TCanvas("rf105_funcbinding","rf105_funcbinding",1200,400) ;
   c->Divide(3) ;
   c->cd(1) ; gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.6) ; frame1->Draw() ;
   c->cd(2) ; gPad->SetLeftMargin(0.15) ; frame2->GetYaxis()->SetTitleOffset(1.6) ; frame2->Draw() ;
   c->cd(3) ; gPad->SetLeftMargin(0.15) ; frame3->GetYaxis()->SetTitleOffset(1.6) ; frame3->Draw() ;

}
Beispiel #15
0
void fit2015(
             TString FileName ="/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/ppData/OniaTree_262163_262328.root", 
             int  oniamode  = 2,        // oniamode-> 3: Z,  2: Upsilon and 1: J/Psi
             bool isData    = true,     // isData = false for MC, true for Data
             bool isPbPb    = false,    // isPbPb = false for pp, true for PbPb
	     bool doFit = false ,
             bool inExcStat = true      // if inExcStat is true, then the excited states are fitted
             ) {

  InputOpt opt;
  SetOptions(&opt, isData, isPbPb, oniamode,inExcStat);

  if (isPbPb) {
    FileName = "/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/PbPbData/OniaTree_262548_262893.root";
  } else {
    FileName = "/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/ppData/OniaTree_262163_262328.root";
  }
    
  int nbins = 1; //ceil((opt.dMuon->M->Max - opt.dMuon->M->Min)/binw);
  if (oniamode==1){
    nbins = 140;
  } else if (oniamode==2) {
    nbins = 70; 
  } else if (oniamode==3) {
    nbins = 40;
  } 
 
  RooWorkspace myws;
  TH1F* hDataOS =  new TH1F("hDataOS","hDataOS", nbins, opt.dMuon.M.Min, opt.dMuon.M.Max);
  makeWorkspace2015(myws, FileName, opt, hDataOS);

  RooRealVar* mass      = (RooRealVar*) myws.var("invariantMass"); 
  RooDataSet* dataOS_fit = (RooDataSet*) myws.data("dataOS");
  RooDataSet* dataSS_fit = (RooDataSet*) myws.data("dataSS");
  RooAbsPdf*  pdf = NULL;

  if (oniamode==3) { doFit=false; }
  if (doFit) {
    int sigModel=0, bkgModel=0;  
    if (isData) {
      if (oniamode==1){
        sigModel = inExcStat ? 2 : 3;
        bkgModel = 1;
      } else {
        sigModel = inExcStat ? 1 : 3; // gaussian   
        bkgModel = 2;
      }      
    } else {
      if (oniamode==1){
        sigModel = inExcStat ? 2 : 3; // gaussian   
        bkgModel = 2;
      } else {
        sigModel = inExcStat ? 2 : 3; // gaussian   
        bkgModel = 3;
      }
    }

    if (opt.oniaMode==1) buildModelJpsi2015(myws, sigModel, bkgModel,inExcStat);
    else if (opt.oniaMode==2) buildModelUpsi2015(myws, sigModel, bkgModel,inExcStat);

    pdf       =(RooAbsPdf*)  myws.pdf("pdf");
    RooFitResult* fitObject = pdf->fitTo(*dataOS_fit,Save(),Hesse(kTRUE),Extended(kTRUE)); // Fit
  }

  RooPlot* frame = mass->frame(Bins(nbins),Range(opt.dMuon.M.Min, opt.dMuon.M.Max));  
  RooPlot* frame2 = NULL;
  dataSS_fit->plotOn(frame, Name("dataSS_FIT"), MarkerColor(kRed), LineColor(kRed), MarkerSize(1.2)); 
  dataOS_fit->plotOn(frame, Name("dataOS_FIT"), MarkerColor(kBlue), LineColor(kBlue), MarkerSize(1.2));
  

  if (doFit) {
     pdf->plotOn(frame,Name("thePdf"),Normalization(dataOS_fit->sumEntries(),RooAbsReal::NumEvent));
     RooHist *hpull = frame -> pullHist(0,0,true);
     hpull -> SetName("hpull");
     frame2 = mass->frame(Title("Pull Distribution"),Bins(nbins),Range(opt.dMuon.M.Min,opt.dMuon.M.Max));
     frame2 -> addPlotable(hpull,"PX");  
     } 
  drawPlot(frame,frame2, pdf, opt, doFit,inExcStat);

  TString OutputFileName = "";
  if (isPbPb) {
    FileName = "/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/PbPbData/OniaTree_262548_262893.root";
    opt.RunNb.Start=262548;
    opt.RunNb.End=262893;
    if (oniamode==1) {OutputFileName = (TString)("JPSIPbPbDataset.root");}
    if (oniamode==2) {OutputFileName = (TString)("YPbPbDataset.root");}
    if (oniamode==3) {OutputFileName = (TString)("ZPbPbDataset.root");}
  } else {
    FileName = "/afs/cern.ch/user/a/anstahll/work/public/ExpressStream2015/ppData/OniaTree_262163_262328.root";
    opt.RunNb.Start=262163;
    opt.RunNb.End=262328;
    if (oniamode==1) {OutputFileName = (TString)("JPSIppDataset.root");}
    if (oniamode==2) {OutputFileName = (TString)("YppDataset.root");}
    if (oniamode==3) {OutputFileName = (TString)("ZppDataset.root");}
  }
  
  TFile* oFile =  new TFile(OutputFileName,"RECREATE");
  oFile->cd();
  hDataOS->Write("hDataOS");
  dataOS_fit->Write("dataOS_FIT");
  oFile->Write();
  oFile->Close();

}
   void ws_constrained_profile3D( const char* wsfile = "rootfiles/ws-data-unblind.root",
                                   const char* new_poi_name = "n_M234_H4_3b",
                                   int npoiPoints = 20,
                                   double poiMinVal = 0.,
                                   double poiMaxVal = 20.,
                                   double constraintWidth = 1.5,
                                   double ymax = 10.,
                                   int verbLevel=0 ) {


     gStyle->SetOptStat(0) ;

     //--- make output directory.

     char command[10000] ;
     sprintf( command, "basename %s", wsfile ) ;
     TString wsfilenopath = gSystem->GetFromPipe( command ) ;
     wsfilenopath.ReplaceAll(".root","") ;
     char outputdirstr[1000] ;
     sprintf( outputdirstr, "outputfiles/scans-%s", wsfilenopath.Data() ) ;
     TString outputdir( outputdirstr ) ;


     printf("\n\n Creating output directory: %s\n\n", outputdir.Data() ) ;
     sprintf(command, "mkdir -p %s", outputdir.Data() ) ;
     gSystem->Exec( command ) ;


     //--- Tell RooFit to shut up about anything less important than an ERROR.
      RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR) ;



       if ( verbLevel > 0 ) { printf("\n\n Verbose level : %d\n\n", verbLevel) ; }


       TFile* wstf = new TFile( wsfile ) ;

       RooWorkspace* ws = dynamic_cast<RooWorkspace*>( wstf->Get("ws") );

       if ( verbLevel > 0 ) { ws->Print() ; }






       RooDataSet* rds = (RooDataSet*) ws->obj( "ra2b_observed_rds" ) ;

       if ( verbLevel > 0 ) {
          printf("\n\n\n  ===== RooDataSet ====================\n\n") ;
          rds->Print() ;
          rds->printMultiline(cout, 1, kTRUE, "") ;
       }





       ModelConfig* modelConfig = (ModelConfig*) ws->obj( "SbModel" ) ;
       RooAbsPdf* likelihood = modelConfig->GetPdf() ;

       RooRealVar* rrv_mu_susy_all0lep = ws->var("mu_susy_all0lep") ;
       if ( rrv_mu_susy_all0lep == 0x0 ) {
          printf("\n\n\n *** can't find mu_susy_all0lep in workspace.  Quitting.\n\n\n") ;
          return ;
       }





       //-- do BG only.
       rrv_mu_susy_all0lep->setVal(0.) ;
       rrv_mu_susy_all0lep->setConstant( kTRUE ) ;










       //-- do a prefit.

       printf("\n\n\n ====== Pre fit with unmodified nll var.\n\n") ;

       RooFitResult* dataFitResultSusyFixed = likelihood->fitTo(*rds, Save(true),Hesse(false),Minos(false),Strategy(1),PrintLevel(verbLevel));
       int dataSusyFixedFitCovQual = dataFitResultSusyFixed->covQual() ;
       if ( dataSusyFixedFitCovQual < 2 ) { printf("\n\n\n *** Failed fit!  Cov qual %d.  Quitting.\n\n", dataSusyFixedFitCovQual ) ; return ; }
       double dataFitSusyFixedNll = dataFitResultSusyFixed->minNll() ;

       if ( verbLevel > 0 ) {
          dataFitResultSusyFixed->Print("v") ;
       }

       printf("\n\n Nll value, from fit result : %.3f\n\n", dataFitSusyFixedNll ) ;

       delete dataFitResultSusyFixed ;






       //-- Construct the new POI parameter.
       RooAbsReal* new_poi_rar(0x0) ;

       new_poi_rar = ws->var( new_poi_name ) ;
       if ( new_poi_rar == 0x0 ) {
          printf("\n\n New POI %s is not a variable.  Trying function.\n\n", new_poi_name ) ;
          new_poi_rar = ws->function( new_poi_name ) ;
          if ( new_poi_rar == 0x0 ) {
             printf("\n\n New POI %s is not a function.  I quit.\n\n", new_poi_name ) ;
             return ;
          }
       } else {
          printf("\n\n     New POI %s is a variable with current value %.1f.\n\n", new_poi_name, new_poi_rar->getVal() ) ;
       }








       if ( npoiPoints <=0 ) {
          printf("\n\n Quitting now.\n\n" ) ;
          return ;
       }


       double startPoiVal = new_poi_rar->getVal() ;



      //--- The RooNLLVar is NOT equivalent to what minuit uses.
  //   RooNLLVar* nll = new RooNLLVar("nll","nll", *likelihood, *rds ) ;
  //   printf("\n\n Nll value, from construction : %.3f\n\n", nll->getVal() ) ;

      //--- output of createNLL IS what minuit uses, so use that.
       RooAbsReal* nll = likelihood -> createNLL( *rds, Verbose(true) ) ;

       RooRealVar* rrv_poiValue = new RooRealVar( "poiValue", "poiValue", 0., -10000., 10000. ) ;
   /// rrv_poiValue->setVal( poiMinVal ) ;
   /// rrv_poiValue->setConstant(kTRUE) ;

       RooRealVar* rrv_constraintWidth = new RooRealVar("constraintWidth","constraintWidth", 0.1, 0.1, 1000. ) ;
       rrv_constraintWidth -> setVal( constraintWidth ) ;
       rrv_constraintWidth -> setConstant(kTRUE) ;




       if ( verbLevel > 0 ) {
          printf("\n\n ======= debug likelihood print\n\n") ;
          likelihood->Print("v") ;
          printf("\n\n ======= debug nll print\n\n") ;
          nll->Print("v") ;
       }






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

       RooMinuit* rminuit( 0x0 ) ;


       RooMinuit* rminuit_uc = new RooMinuit( *nll  ) ;

       rminuit_uc->setPrintLevel(verbLevel-1) ;
       rminuit_uc->setNoWarn() ;

       rminuit_uc->migrad() ;
       rminuit_uc->hesse() ;

       RooFitResult* rfr_uc = rminuit_uc->fit("mr") ;

       double floatParInitVal[10000] ;
       char   floatParName[10000][100] ;
       int nFloatParInitVal(0) ;
       RooArgList ral_floats = rfr_uc->floatParsFinal() ;
       TIterator* floatParIter = ral_floats.createIterator() ;
       {
          RooRealVar* par ;
          while ( (par = (RooRealVar*) floatParIter->Next()) ) {
             sprintf( floatParName[nFloatParInitVal], "%s", par->GetName() ) ;
             floatParInitVal[nFloatParInitVal] = par->getVal() ;
             nFloatParInitVal++ ;
          }
       }



     //-------

       printf("\n\n Unbiased best value for new POI %s is : %7.1f\n\n", new_poi_rar->GetName(), new_poi_rar->getVal() ) ;
       double best_poi_val = new_poi_rar->getVal() ;

       char minuit_formula[10000] ;
       sprintf( minuit_formula, "%s+%s*(%s-%s)*(%s-%s)",
         nll->GetName(),
         rrv_constraintWidth->GetName(),
         new_poi_rar->GetName(), rrv_poiValue->GetName(),
         new_poi_rar->GetName(), rrv_poiValue->GetName()
          ) ;

       printf("\n\n Creating new minuit variable with formula: %s\n\n", minuit_formula ) ;
       RooFormulaVar* new_minuit_var = new RooFormulaVar("new_minuit_var", minuit_formula,
           RooArgList( *nll,
                       *rrv_constraintWidth,
                       *new_poi_rar, *rrv_poiValue,
                       *new_poi_rar, *rrv_poiValue
                       ) ) ;

       printf("\n\n Current value is %.2f\n\n",
            new_minuit_var->getVal() ) ;

       rminuit = new RooMinuit( *new_minuit_var ) ;


       RooAbsReal* plot_var = nll ;

       printf("\n\n Current value is %.2f\n\n",
            plot_var->getVal() ) ;




       rminuit->setPrintLevel(verbLevel-1) ;
       if ( verbLevel <=0 ) { rminuit->setNoWarn() ; }

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

       //-- If POI range is -1 to -1, automatically determine the range using the set value.

       if ( poiMinVal < 0. && poiMaxVal < 0. ) {

          printf("\n\n Automatic determination of scan range.\n\n") ;

          if ( startPoiVal <= 0. ) {
             printf("\n\n *** POI starting value zero or negative %g.  Quit.\n\n\n", startPoiVal ) ;
             return ;
          }

          poiMinVal = startPoiVal - 3.5 * sqrt(startPoiVal) ;
          poiMaxVal = startPoiVal + 6.0 * sqrt(startPoiVal) ;

          if ( poiMinVal < 0. ) { poiMinVal = 0. ; }

          printf("    Start val = %g.   Scan range:   %g  to  %g\n\n", startPoiVal, poiMinVal, poiMaxVal ) ;


       }



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


       double poiVals_scanDown[1000] ;
       double nllVals_scanDown[1000] ;

       //-- Do scan down from best value.

       printf("\n\n +++++ Starting scan down from best value.\n\n") ;

       double minNllVal(1.e9) ;

       for ( int poivi=0; poivi < npoiPoints/2 ; poivi++ ) {

          ////double poiValue = poiMinVal + poivi*(poiMaxVal-poiMinVal)/(1.*(npoiPoints-1)) ;
          double poiValue = best_poi_val - poivi*(best_poi_val-poiMinVal)/(1.*(npoiPoints/2-1)) ;

          rrv_poiValue -> setVal( poiValue ) ;
          rrv_poiValue -> setConstant( kTRUE ) ;


       //+++++++++++++++++++++++++++++++++++

          rminuit->migrad() ;
          rminuit->hesse() ;
          RooFitResult* rfr = rminuit->save() ;

       //+++++++++++++++++++++++++++++++++++


          if ( verbLevel > 0 ) { rfr->Print("v") ; }


          float fit_minuit_var_val = rfr->minNll() ;

          printf(" %02d : poi constraint = %.2f : allvars : MinuitVar, createNLL, PV, POI :    %.5f   %.5f   %.5f   %.5f\n",
                poivi, rrv_poiValue->getVal(), fit_minuit_var_val, nll->getVal(), plot_var->getVal(), new_poi_rar->getVal() ) ;
          cout << flush ;



          poiVals_scanDown[poivi] = new_poi_rar->getVal() ;
          nllVals_scanDown[poivi] = plot_var->getVal() ;

          if ( nllVals_scanDown[poivi] < minNllVal ) { minNllVal = nllVals_scanDown[poivi] ; }

          delete rfr ;


       } // poivi


       printf("\n\n +++++ Resetting floats to best fit values.\n\n") ;

       for ( int pi=0; pi<nFloatParInitVal; pi++ ) {
          RooRealVar* par = ws->var( floatParName[pi] ) ;
          par->setVal( floatParInitVal[pi] ) ;
       } // pi.

       printf("\n\n +++++ Starting scan up from best value.\n\n") ;

      //-- Now do scan up.

       double poiVals_scanUp[1000] ;
       double nllVals_scanUp[1000] ;

       for ( int poivi=0; poivi < npoiPoints/2 ; poivi++ ) {

          double poiValue = best_poi_val + poivi*(poiMaxVal-best_poi_val)/(1.*(npoiPoints/2-1)) ;

          rrv_poiValue -> setVal( poiValue ) ;
          rrv_poiValue -> setConstant( kTRUE ) ;


       //+++++++++++++++++++++++++++++++++++

          rminuit->migrad() ;
          rminuit->hesse() ;
          RooFitResult* rfr = rminuit->save() ;

       //+++++++++++++++++++++++++++++++++++


          if ( verbLevel > 0 ) { rfr->Print("v") ; }


          float fit_minuit_var_val = rfr->minNll() ;

          printf(" %02d : poi constraint = %.2f : allvars : MinuitVar, createNLL, PV, POI :    %.5f   %.5f   %.5f   %.5f\n",
                poivi, rrv_poiValue->getVal(), fit_minuit_var_val, nll->getVal(), plot_var->getVal(), new_poi_rar->getVal() ) ;
          cout << flush ;

          poiVals_scanUp[poivi] = new_poi_rar->getVal() ;
          nllVals_scanUp[poivi] = plot_var->getVal() ;

          if ( nllVals_scanUp[poivi] < minNllVal ) { minNllVal = nllVals_scanUp[poivi] ; }

          delete rfr ;


       } // poivi





       double poiVals[1000] ;
       double nllVals[1000] ;

       int pointCount(0) ;
       for ( int pi=0; pi<npoiPoints/2; pi++ ) {
          poiVals[pi] = poiVals_scanDown[(npoiPoints/2-1)-pi] ;
          nllVals[pi] = nllVals_scanDown[(npoiPoints/2-1)-pi] ;
          pointCount++ ;
       }
       for ( int pi=1; pi<npoiPoints/2; pi++ ) {
          poiVals[pointCount] = poiVals_scanUp[pi] ;
          nllVals[pointCount] = nllVals_scanUp[pi] ;
          pointCount++ ;
       }
       npoiPoints = pointCount ;

       printf("\n\n --- TGraph arrays:\n") ;
       for ( int i=0; i<npoiPoints; i++ ) {
          printf("  %2d : poi = %6.1f, nll = %g\n", i, poiVals[i], nllVals[i] ) ;
       }
       printf("\n\n") ;

       double nllDiffVals[1000] ;

       double poiAtMinlnL(-1.) ;
       double poiAtMinusDelta2(-1.) ;
       double poiAtPlusDelta2(-1.) ;
       for ( int poivi=0; poivi < npoiPoints ; poivi++ ) {
          nllDiffVals[poivi] = 2.*(nllVals[poivi] - minNllVal) ;
          double poiValue = poiMinVal + poivi*(poiMaxVal-poiMinVal)/(1.*npoiPoints) ;
          if ( nllDiffVals[poivi] < 0.01 ) { poiAtMinlnL = poiValue ; }
          if ( poiAtMinusDelta2 < 0. && nllDiffVals[poivi] < 2.5 ) { poiAtMinusDelta2 = poiValue ; }
          if ( poiAtMinlnL > 0. && poiAtPlusDelta2 < 0. && nllDiffVals[poivi] > 2.0 ) { poiAtPlusDelta2 = poiValue ; }
       } // poivi

       printf("\n\n Estimates for poi at delta ln L = -2, 0, +2:  %g ,   %g ,   %g\n\n", poiAtMinusDelta2, poiAtMinlnL, poiAtPlusDelta2 ) ;




      //--- Main canvas

       TCanvas* cscan = (TCanvas*) gDirectory->FindObject("cscan") ;
       if ( cscan == 0x0 ) {
          printf("\n Creating canvas.\n\n") ;
          cscan = new TCanvas("cscan","Delta nll") ;
       }


       char gname[1000] ;

       TGraph* graph = new TGraph( npoiPoints, poiVals, nllDiffVals ) ;
       sprintf( gname, "scan_%s", new_poi_name ) ;
       graph->SetName( gname ) ;

       double poiBest(-1.) ;
       double poiMinus1stdv(-1.) ;
       double poiPlus1stdv(-1.) ;
       double poiMinus2stdv(-1.) ;
       double poiPlus2stdv(-1.) ;
       double twoDeltalnLMin(1e9) ;

       int nscan(1000) ;
       for ( int xi=0; xi<nscan; xi++ ) {

          double x = poiVals[0] + xi*(poiVals[npoiPoints-1]-poiVals[0])/(nscan-1) ;

          double twoDeltalnL = graph -> Eval( x, 0, "S" ) ;

          if ( poiMinus1stdv < 0. && twoDeltalnL < 1.0 ) { poiMinus1stdv = x ; printf(" set m1 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( poiMinus2stdv < 0. && twoDeltalnL < 4.0 ) { poiMinus2stdv = x ; printf(" set m2 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( twoDeltalnL < twoDeltalnLMin ) { poiBest = x ; twoDeltalnLMin = twoDeltalnL ; }
          if ( twoDeltalnLMin < 0.3 && poiPlus1stdv < 0. && twoDeltalnL > 1.0 ) { poiPlus1stdv = x ; printf(" set p1 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( twoDeltalnLMin < 0.3 && poiPlus2stdv < 0. && twoDeltalnL > 4.0 ) { poiPlus2stdv = x ; printf(" set p2 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}

          if ( xi%100 == 0 ) { printf( " %4d : poi=%6.2f,  2DeltalnL = %6.2f\n", xi, x, twoDeltalnL ) ; }

       }
       printf("\n\n POI estimate :  %g  +%g  -%g    [%g,%g],   two sigma errors: +%g  -%g   [%g,%g]\n\n",
               poiBest,
               (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv), poiMinus1stdv, poiPlus1stdv,
               (poiPlus2stdv-poiBest), (poiBest-poiMinus2stdv), poiMinus2stdv, poiPlus2stdv
               ) ;

       printf(" %s val,pm1sig,pm2sig: %7.2f  %7.2f  %7.2f  %7.2f  %7.2f\n",
          new_poi_name, poiBest, (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv), (poiPlus2stdv-poiBest), (poiBest-poiMinus2stdv) ) ;

       char htitle[1000] ;
       sprintf(htitle, "%s profile likelihood scan: -2ln(L/Lm)", new_poi_name ) ;
       TH1F* hscan = new TH1F("hscan", htitle, 10, poiMinVal, poiMaxVal ) ;
       hscan->SetMinimum(0.) ;
       hscan->SetMaximum(ymax) ;


       hscan->DrawCopy() ;
       graph->SetLineColor(4) ;
       graph->SetLineWidth(3) ;
       graph->Draw("CP") ;
       gPad->SetGridx(1) ;
       gPad->SetGridy(1) ;
       cscan->Update() ;

       TLine* line = new TLine() ;
       line->SetLineColor(2) ;
       line->DrawLine(poiMinVal, 1., poiPlus1stdv, 1.) ;
       line->DrawLine(poiMinus1stdv,0., poiMinus1stdv, 1.) ;
       line->DrawLine(poiPlus1stdv ,0., poiPlus1stdv , 1.) ;

       TText* text = new TText() ;
       text->SetTextSize(0.04) ;
       char tstring[1000] ;

       sprintf( tstring, "%s = %.1f +%.1f -%.1f", new_poi_name, poiBest, (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv) ) ;
       text -> DrawTextNDC( 0.15, 0.85, tstring ) ;

       sprintf( tstring, "68%% interval [%.1f,  %.1f]", poiMinus1stdv, poiPlus1stdv ) ;
       text -> DrawTextNDC( 0.15, 0.78, tstring ) ;


       char hname[1000] ;
       sprintf( hname, "hscanout_%s", new_poi_name ) ;
       TH1F* hsout = new TH1F( hname,"scan results",4,0.,4.) ;
       double obsVal(-1.) ;
       hsout->SetBinContent(1, obsVal ) ;
       hsout->SetBinContent(2, poiPlus1stdv ) ;
       hsout->SetBinContent(3, poiBest ) ;
       hsout->SetBinContent(4, poiMinus1stdv ) ;
       TAxis* xaxis = hsout->GetXaxis() ;
       xaxis->SetBinLabel(1,"Observed val.") ;
       xaxis->SetBinLabel(2,"Model+1sd") ;
       xaxis->SetBinLabel(3,"Model") ;
       xaxis->SetBinLabel(4,"Model-1sd") ;

       char outrootfile[10000] ;
       sprintf( outrootfile, "%s/scan-ff-%s.root", outputdir.Data(), new_poi_name ) ;

       char outpdffile[10000] ;
       sprintf( outpdffile, "%s/scan-ff-%s.pdf", outputdir.Data(), new_poi_name ) ;

       cscan->Update() ; cscan->Draw() ;

       printf("\n Saving %s\n", outpdffile ) ;
       cscan->SaveAs( outpdffile ) ;



     //--- save in root file

       printf("\n Saving %s\n", outrootfile ) ;
       TFile fout(outrootfile,"recreate") ;
       graph->Write() ;
       hsout->Write() ;
       fout.Close() ;

       delete ws ;
       wstf->Close() ;

   }
Beispiel #17
0
   void fitqual_plots( const char* wsfile = "outputfiles/ws.root", const char* plottitle="" ) {

      TText* tt_title = new TText() ;
      tt_title -> SetTextAlign(33) ;

      gStyle -> SetOptStat(0) ;
      gStyle -> SetLabelSize( 0.06, "y" ) ;
      gStyle -> SetLabelSize( 0.08, "x" ) ;
      gStyle -> SetLabelOffset( 0.010, "y" ) ;
      gStyle -> SetLabelOffset( 0.010, "x" ) ;
      gStyle -> SetTitleSize( 0.07, "y" ) ;
      gStyle -> SetTitleSize( 0.05, "x" ) ;
      gStyle -> SetTitleOffset( 1.50, "x" ) ;
      gStyle -> SetTitleH( 0.07 ) ;
      gStyle -> SetPadLeftMargin( 0.15 ) ;
      gStyle -> SetPadBottomMargin( 0.15 ) ;
      gStyle -> SetTitleX( 0.10 ) ;

      gDirectory->Delete("h*") ;

      TFile* wstf = new TFile( wsfile ) ;

      RooWorkspace* ws = dynamic_cast<RooWorkspace*>( wstf->Get("ws") );
      ws->Print() ;

      int bins_of_met = TMath::Nint( ws->var("bins_of_met")->getVal()  ) ;
      printf("\n\n Bins of MET : %d\n\n", bins_of_met ) ;

      int bins_of_nb = TMath::Nint( ws->var("bins_of_nb")->getVal()  ) ;
      printf("\n\n Bins of nb : %d\n\n", bins_of_nb ) ;

      int nb_lookup[10] ;
      if ( bins_of_nb == 2 ) {
         nb_lookup[0] = 2 ;
         nb_lookup[1] = 4 ;
      } else if ( bins_of_nb == 3 ) {
         nb_lookup[0] = 2 ;
         nb_lookup[1] = 3 ;
         nb_lookup[2] = 4 ;
      }

      TCanvas* cfq1 = (TCanvas*) gDirectory->FindObject("cfq1") ;
      if ( cfq1 == 0x0 ) {
         if ( bins_of_nb == 3 ) {
            cfq1 = new TCanvas("cfq1","hbb fit", 700, 1000 ) ;
         } else if ( bins_of_nb == 2 ) {
            cfq1 = new TCanvas("cfq1","hbb fit", 700, 750 ) ;
         } else {
            return ;
         }
      }

      RooRealVar* rv_sig_strength = ws->var("sig_strength") ;
      if ( rv_sig_strength == 0x0 ) { printf("\n\n *** can't find sig_strength in workspace.\n\n" ) ; return ; }

      ModelConfig* modelConfig = (ModelConfig*) ws->obj( "SbModel" ) ;

      RooDataSet* rds = (RooDataSet*) ws->obj( "hbb_observed_rds" ) ;

      rds->Print() ;
      rds->printMultiline(cout, 1, kTRUE, "") ;

      RooAbsPdf* likelihood = modelConfig->GetPdf() ;

      ///RooFitResult* fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(0) ) ;
      RooFitResult* fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(3) ) ;
      fitResult->Print() ;


      char hname[1000] ;
      char htitle[1000] ;
      char pname[1000] ;




     //-- unpack observables.

      int obs_N_msig[10][50] ; // first index is n btags, second is met bin.
      int obs_N_msb[10][50]  ; // first index is n btags, second is met bin.

      const RooArgSet* dsras = rds->get() ;
      TIterator* obsIter = dsras->createIterator() ;
      while ( RooRealVar* obs = (RooRealVar*) obsIter->Next() ) {
         for ( int nbi=0; nbi<bins_of_nb; nbi++ ) {
            for ( int mbi=0; mbi<bins_of_met; mbi++ ) {
               sprintf( pname, "N_%db_msig_met%d", nb_lookup[nbi], mbi+1 ) ;
               if ( strcmp( obs->GetName(), pname ) == 0 ) { obs_N_msig[nbi][mbi] = TMath::Nint( obs -> getVal() ) ; }
               sprintf( pname, "N_%db_msb_met%d", nb_lookup[nbi], mbi+1 ) ;
               if ( strcmp( obs->GetName(), pname ) == 0 ) { obs_N_msb[nbi][mbi] = TMath::Nint( obs -> getVal() ) ; }
            } // mbi.
         } // nbi.
      } // obs iterator.


      printf("\n\n") ;
      for ( int nbi=0; nbi<bins_of_nb; nbi++ ) {
         printf(" nb=%d :  ", nb_lookup[nbi] ) ;
         for ( int mbi=0; mbi<bins_of_met; mbi++ ) {
            printf("  sig=%3d, sb=%3d  |", obs_N_msig[nbi][mbi], obs_N_msb[nbi][mbi] ) ;
         } // mbi.
         printf("\n") ;
      } // nbi.
      printf("\n\n") ;




      int pad(1) ;

      cfq1->Clear() ;
      cfq1->Divide( 2, bins_of_nb+1 ) ;

      for ( int nbi=0; nbi<bins_of_nb; nbi++ ) {


         sprintf( hname, "h_bg_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_bg_msig = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_bg_msig -> SetFillColor( kBlue-9 ) ;
         labelBins( hist_bg_msig ) ;

         sprintf( hname, "h_bg_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sb, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_bg_msb = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_bg_msb -> SetFillColor( kBlue-9 ) ;
         labelBins( hist_bg_msb ) ;

         sprintf( hname, "h_sig_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_sig_msig = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_sig_msig -> SetFillColor( kMagenta+2 ) ;
         labelBins( hist_sig_msig ) ;

         sprintf( hname, "h_sig_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sb, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_sig_msb = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_sig_msb -> SetFillColor( kMagenta+2 ) ;
         labelBins( hist_sig_msb ) ;

         sprintf( hname, "h_all_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_all_msig = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;

         sprintf( hname, "h_all_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sb, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_all_msb = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;

         sprintf( hname, "h_data_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_data_msig = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_data_msig -> SetLineWidth(2) ;
         hist_data_msig -> SetMarkerStyle(20) ;
         labelBins( hist_data_msig ) ;

         sprintf( hname, "h_data_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sb, %db, MET", nb_lookup[nbi] ) ;
         TH1F* hist_data_msb = new TH1F( hname, htitle, bins_of_met, 0.5, bins_of_met+0.5 ) ;
         hist_data_msb -> SetLineWidth(2) ;
         hist_data_msb -> SetMarkerStyle(20) ;
         labelBins( hist_data_msb ) ;

         for ( int mbi=0; mbi<bins_of_met; mbi++ ) {



            sprintf( pname, "mu_bg_%db_msig_met%d", nb_lookup[nbi], mbi+1 ) ;
            RooAbsReal* mu_bg_msig = ws->function( pname ) ;
            if ( mu_bg_msig == 0x0 ) { printf("\n\n *** ws missing %s\n\n", pname ) ; return ; }
            hist_bg_msig -> SetBinContent( mbi+1, mu_bg_msig->getVal() ) ;

            sprintf( pname, "mu_sig_%db_msig_met%d", nb_lookup[nbi], mbi+1 ) ;
            RooAbsReal* mu_sig_msig = ws->function( pname ) ;
            if ( mu_sig_msig == 0x0 ) { printf("\n\n *** ws missing %s\n\n", pname ) ; return ; }
            hist_sig_msig -> SetBinContent( mbi+1, mu_sig_msig->getVal() ) ;

            hist_all_msig -> SetBinContent( mbi+1, mu_bg_msig->getVal() + mu_sig_msig->getVal() ) ;

            hist_data_msig -> SetBinContent( mbi+1, obs_N_msig[nbi][mbi] ) ;



            sprintf( pname, "mu_bg_%db_msb_met%d", nb_lookup[nbi], mbi+1 ) ;
            RooAbsReal* mu_bg_msb = ws->function( pname ) ;
            if ( mu_bg_msb == 0x0 ) { printf("\n\n *** ws missing %s\n\n", pname ) ; return ; }
            hist_bg_msb -> SetBinContent( mbi+1, mu_bg_msb->getVal() ) ;

            sprintf( pname, "mu_sig_%db_msb_met%d", nb_lookup[nbi], mbi+1 ) ;
            RooAbsReal* mu_sig_msb = ws->function( pname ) ;
            if ( mu_sig_msb == 0x0 ) { printf("\n\n *** ws missing %s\n\n", pname ) ; return ; }
            hist_sig_msb -> SetBinContent( mbi+1, mu_sig_msb->getVal() ) ;

            hist_all_msb -> SetBinContent( mbi+1, mu_bg_msb->getVal() + mu_sig_msb->getVal() ) ;

            hist_data_msb -> SetBinContent( mbi+1, obs_N_msb[nbi][mbi] ) ;



         } // mbi.

         cfq1->cd( pad ) ;

         sprintf( hname, "h_stack_%db_msig_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         THStack* hstack_msig = new THStack( hname, htitle ) ;
         hstack_msig -> Add( hist_bg_msig ) ;
         hstack_msig -> Add( hist_sig_msig ) ;

         hist_data_msig -> Draw("e") ;
         hstack_msig -> Draw("same") ;
         hist_data_msig -> Draw("same e") ;
         hist_data_msig -> Draw("same axis") ;

         tt_title -> DrawTextNDC( 0.85, 0.85, plottitle ) ;

         pad++ ;



         cfq1->cd( pad ) ;

         sprintf( hname, "h_stack_%db_msb_met", nb_lookup[nbi] ) ;
         sprintf( htitle, "mass sig, %db, MET", nb_lookup[nbi] ) ;
         THStack* hstack_msb = new THStack( hname, htitle ) ;
         hstack_msb -> Add( hist_bg_msb ) ;
         hstack_msb -> Add( hist_sig_msb ) ;

         hist_data_msb -> Draw("e") ;
         hstack_msb -> Draw("same") ;
         hist_data_msb -> Draw("same e") ;
         hist_data_msb -> Draw("same axis") ;

         tt_title -> DrawTextNDC( 0.85, 0.85, plottitle ) ;

         pad++ ;



      } // nbi.




      TH1F* hist_R_msigmsb = new TH1F( "h_R_msigmsb", "R msig/msb vs met bin", bins_of_met, 0.5, 0.5+bins_of_met ) ;
      hist_R_msigmsb -> SetLineWidth(2) ;
      hist_R_msigmsb -> SetMarkerStyle(20) ;
      hist_R_msigmsb -> SetYTitle("R msig/msb") ;
      labelBins( hist_R_msigmsb ) ;


      for ( int mbi=0; mbi<bins_of_met; mbi++ ) {
         sprintf( pname, "R_msigmsb_met%d", mbi+1 ) ;
         RooRealVar* rrv_R = ws->var( pname ) ;
         if ( rrv_R == 0x0 ) { printf("\n\n *** Can't find %s in ws.\n\n", pname ) ; return ; }
         hist_R_msigmsb -> SetBinContent( mbi+1, rrv_R -> getVal() ) ;
         hist_R_msigmsb -> SetBinError( mbi+1, rrv_R -> getError() ) ;
      } // mbi.

      cfq1->cd( pad ) ;

      gPad->SetGridy(1) ;

      hist_R_msigmsb -> SetMaximum(0.35) ;
      hist_R_msigmsb -> Draw("e") ;

      tt_title -> DrawTextNDC( 0.85, 0.85, plottitle ) ;

      pad++ ;



      cfq1->cd( pad ) ;

      scan_sigstrength( wsfile ) ;

      tt_title -> DrawTextNDC( 0.85, 0.25, plottitle ) ;



      TString pdffile( wsfile ) ;
      pdffile.ReplaceAll("ws-","fitqual-") ;
      pdffile.ReplaceAll("root","pdf") ;


      cfq1->SaveAs( pdffile ) ;



      TString histfile( wsfile ) ;
      histfile.ReplaceAll("ws-","fitqual-") ;

      saveHist( histfile, "h*" ) ;



   } // fitqual_plots
Beispiel #18
0
void paper_fit_plot()
{
  SetAtlasStyle();

  // get the stuff from the file
  char fname_postfit[200] = "monoh_withsm_SRCR_bg11.7_bgslop-0.0_nsig0.0.root";
  TFile *tf = new TFile(fname_postfit);
  RooWorkspace *ws_post = (RooWorkspace*)tf->Get("wspace");

  // data and pdf
  RooAbsData *data = ws_post->data("data");
  RooAbsPdf *pdfc = ws_post->pdf("jointModeld");
  
  // variables to be constrained
  RooRealVar *mh = ws_post->var("mh");
  RooRealVar *sigma_h = ws_post->var("sigma_h");
  RooRealVar *eff = ws_post->var("eff");
  RooRealVar *theory = ws_post->var("theory");
  RooRealVar *lumi = ws_post->var("lumi");
  RooRealVar *x_mgg = ws_post->var("mgg");
  RooArgSet cas(*mh,*sigma_h,*eff,*theory,*lumi);  

  // redo the fit
  RooFitResult *r = pdfc->fitTo(*data,RooFit::Constrain(cas),RooFit::Save(true));

  // make the frame
  RooPlot *frame = x_mgg->frame();
  TCanvas *tc = new TCanvas("tc","",700,500);
  frame->GetXaxis()->SetTitle("m_{#gamma#gamma} [GeV]");
  frame->GetYaxis()->SetTitle("Events / 1 GeV");

  // add the data
  data->plotOn(frame,RooFit::Binning(55),RooFit::Name("xdata"),RooFit::DataError(RooAbsData::Poisson));
  //data->plotOn(frame,RooFit::Binning(11),RooFit::Name("xdata"),RooFit::DataError(RooAbsData::Poisson));


  ///  PDFs
  pdfc->plotOn(frame, RooFit::Components("E"), RooFit::LineColor(kRed),   RooFit::Name("xbackground"));
  pdfc->plotOn(frame, RooFit::Components("S"), RooFit::LineColor(kBlue),RooFit::LineStyle(kDotted),   RooFit::Name("xsm"));
  pdfc->plotOn(frame, RooFit::Components("G"), RooFit::LineColor(kGreen),RooFit::LineStyle(kDotted),   RooFit::Name("xbsm"));
  pdfc->plotOn(frame, RooFit::LineColor(kRed), RooFit::LineStyle(kDashed),RooFit::Name("xtotal"));

  frame->SetMinimum(1e-7);
  frame->SetMaximum(9);

  // Legend
  double x1,y1,x2,y2;
  GetX1Y1X2Y2(tc,x1,y1,x2,y2);
  TLegend *legend_sr=FastLegend(x1+0.02,y2-0.3,x1+0.35,y2-0.02,0.045);
  legend_sr->AddEntry(frame->findObject("xdata"),"Data","LEP");
  legend_sr->AddEntry(frame->findObject("xbackground"),"Background fit","L");
  legend_sr->AddEntry(frame->findObject("xsm"),"SM H","L");
  legend_sr->AddEntry(frame->findObject("xbsm"),"Best-fit BSM H","L");
  legend_sr->AddEntry(frame->findObject("xtotal"),"Total","L");
  frame->Draw();
  legend_sr->Draw("SAME");

  // descriptive text
  vector<TString> pavetext11;
  pavetext11.push_back("#bf{#it{ATLAS Internal}}");
  pavetext11.push_back("#sqrt{#it{s}} = 8 TeV #scale[0.6]{#int}#it{L} dt = 20.3 fb^{-1}");
  pavetext11.push_back("#it{H + E}_{T}^{miss} , #it{H #rightarrow #gamma#gamma}, #it{m}_{#it{H}} = 125.4 GeV");

  TPaveText* text11=CreatePaveText(x2-0.47,y2-0.25,x2-0.05,y2-0.05,pavetext11,0.045);
  text11->Draw();
  tc->Print("paper_fit_plot.pdf");
 }
Beispiel #19
0
result fit_toy(RooWorkspace* wspace, int n, const RooArgSet* globals) {
    RooRandom::randomGenerator()->SetSeed(0);
    // TFile f(filename);
    // RooWorkspace *wspace = (RooWorkspace*)f.Get("combined");
    ModelConfig* model = (ModelConfig*)wspace->obj("ModelConfig");

    RooAbsPdf* pdf;
    pdf = model->GetPdf();

    RooAbsPdf* top_constraint = (RooAbsPdf*)wspace->obj("top_ratio_constraint");
    RooAbsPdf* vv_constraint = (RooAbsPdf*)wspace->obj("vv_ratio_constraint");
    RooAbsPdf* top_vv_constraint_sf = (RooAbsPdf*)wspace->obj("top_vv_ratio_sf_constraint");
    RooAbsPdf* top_vv_constraint_of = (RooAbsPdf*)wspace->obj("top_vv_ratio_of_constraint");


    // generate constraint global observables
    RooRealVar *nom_top_ratio = (RooRealVar*)wspace->obj("nom_top_ratio");
    nom_top_ratio->setRange(0, 100);
    RooRealVar *nom_vv_ratio = (RooRealVar*)wspace->obj("nom_vv_ratio");
    nom_vv_ratio->setRange(0,100);
    RooRealVar *nom_top_vv_ratio_sf = (RooRealVar*)wspace->obj("nom_top_vv_ratio_sf");
    nom_top_vv_ratio_sf->setRange(0,100);
    RooRealVar *nom_top_vv_ratio_of = (RooRealVar*)wspace->obj("nom_top_vv_ratio_of");
    nom_top_vv_ratio_of->setRange(0,100);

    RooDataSet *nom_top_generated = top_constraint->generateSimGlobal(RooArgSet(*nom_top_ratio), 1);
    nom_top_ratio->setVal(((RooRealVar*)nom_top_generated->get(0)->find("nom_top_ratio"))->getVal());

    RooDataSet *nom_vv_generated = vv_constraint->generateSimGlobal(RooArgSet(*nom_vv_ratio), 1);
    nom_vv_ratio->setVal(((RooRealVar*)nom_vv_generated->get(0)->find("nom_vv_ratio"))->getVal());

    RooDataSet *nom_top_vv_sf_generated = top_vv_constraint_sf->generateSimGlobal(RooArgSet(*nom_top_vv_ratio_sf), 1);
    nom_top_vv_ratio_sf->setVal(((RooRealVar*)nom_top_vv_sf_generated->get(0)->find("nom_top_vv_ratio_sf"))->getVal());

    RooDataSet *nom_top_vv_of_generated = top_vv_constraint_of->generateSimGlobal(RooArgSet(*nom_top_vv_ratio_of), 1);
    nom_top_vv_ratio_of->setVal(((RooRealVar*)nom_top_vv_of_generated->get(0)->find("nom_top_vv_ratio_of"))->getVal());

    NumEventsTestStat* dummy = new NumEventsTestStat(*pdf);

    ToyMCSampler* mc = new ToyMCSampler(*dummy, 1);
    mc->SetPdf(*pdf);
    mc->SetObservables(*model->GetObservables());
    mc->SetGlobalObservables(*globals);
    mc->SetNuisanceParameters(*model->GetNuisanceParameters());
    mc->SetParametersForTestStat(*model->GetParametersOfInterest());
    mc->SetNEventsPerToy(n);

    RooArgSet constr;
    constr.add(*(model->GetNuisanceParameters()));
    RemoveConstantParameters(&constr);

    RooDataSet* toy_data = (RooDataSet*)mc->GenerateToyData(*const_cast<RooArgSet*>(model->GetSnapshot()));

    RooFitResult *res = pdf->fitTo(*toy_data, Constrain(constr), PrintLevel(0), Save(),
                                               Range("fitRange"), InitialHesse(),
                                               ExternalConstraints(RooArgSet(*top_constraint, *vv_constraint, *top_vv_constraint_sf, *top_vv_constraint_of)));
    result yield = get_results(wspace, res);
    yield.of.generated_sum.val = toy_data->sumEntries("(channelCat==channelCat::of) & (obs_x_of>120)");
    yield.sf.generated_sum.val = toy_data->sumEntries("(channelCat==channelCat::sf) & (obs_x_sf>120)");

    delete mc;
    delete dummy;
    // f.Close();

    return yield;
}
Beispiel #20
0
   void constrained_scan( const char* wsfile = "outputfiles/ws.root",
                          const char* new_poi_name="mu_bg_4b_msig_met1",
                          double constraintWidth=1.5,
                          int npoiPoints = 20,
                          double poiMinVal = 0.,
                          double poiMaxVal = 10.0,
                          double ymax = 9.,
                          int verbLevel=1  ) {

      TString outputdir("outputfiles") ;

      gStyle->SetOptStat(0) ;

      TFile* wstf = new TFile( wsfile ) ;
      RooWorkspace* ws = dynamic_cast<RooWorkspace*>( wstf->Get("ws") );
      ws->Print() ;

      RooDataSet* rds = (RooDataSet*) ws->obj( "hbb_observed_rds" ) ;
      cout << "\n\n\n  ===== RooDataSet ====================\n\n" << endl ;
      rds->Print() ;
      rds->printMultiline(cout, 1, kTRUE, "") ;

      RooRealVar* rv_sig_strength = ws->var("sig_strength") ;
      if ( rv_sig_strength == 0x0 ) { printf("\n\n *** can't find sig_strength in workspace.\n\n" ) ; return ; }

      RooAbsPdf* likelihood = ws->pdf("likelihood") ;
      if ( likelihood == 0x0 ) { printf("\n\n *** can't find likelihood in workspace.\n\n" ) ; return ; }
      printf("\n\n Likelihood:\n") ;
      likelihood -> Print() ;



      /////rv_sig_strength -> setConstant( kFALSE ) ;
      rv_sig_strength -> setVal(0.) ;
      rv_sig_strength -> setConstant( kTRUE ) ;

      likelihood->fitTo( *rds, Save(false), PrintLevel(0), Hesse(true), Strategy(1) ) ;
      //RooFitResult* fitResult = likelihood->fitTo( *rds, Save(true), PrintLevel(0), Hesse(true), Strategy(1) ) ;
      //double minNllSusyFloat = fitResult->minNll() ;
      //double susy_ss_atMinNll = rv_sig_strength -> getVal() ;

      RooMsgService::instance().getStream(1).removeTopic(Minimization) ;
      RooMsgService::instance().getStream(1).removeTopic(Fitting) ;



     //-- Construct the new POI parameter.
      RooAbsReal* new_poi_rar(0x0) ;

      new_poi_rar = ws->var( new_poi_name ) ;
      if ( new_poi_rar == 0x0 ) {
         printf("\n\n New POI %s is not a variable.  Trying function.\n\n", new_poi_name ) ;
         new_poi_rar = ws->function( new_poi_name ) ;
         if ( new_poi_rar == 0x0 ) {
            printf("\n\n New POI %s is not a function.  I quit.\n\n", new_poi_name ) ;
            return ;
         } else {
            printf("\n Found it.\n\n") ;
         }
      } else {
         printf("\n\n     New POI %s is a variable with current value %.1f.\n\n", new_poi_name, new_poi_rar->getVal() ) ;
      }

       double startPoiVal = new_poi_rar->getVal() ;


       RooAbsReal* nll = likelihood -> createNLL( *rds, Verbose(true) ) ;

       RooRealVar* rrv_poiValue = new RooRealVar( "poiValue", "poiValue", 0., -10000., 10000. ) ;

       RooRealVar* rrv_constraintWidth = new RooRealVar("constraintWidth","constraintWidth", 0.1, 0.1, 1000. ) ;
       rrv_constraintWidth -> setVal( constraintWidth ) ;
       rrv_constraintWidth -> setConstant(kTRUE) ;


       RooMinuit* rminuit( 0x0 ) ;


       RooMinuit* rminuit_uc = new RooMinuit( *nll  ) ;

       rminuit_uc->setPrintLevel(verbLevel-1) ;
       rminuit_uc->setNoWarn() ;

       rminuit_uc->migrad() ;
       rminuit_uc->hesse() ;

       RooFitResult* rfr_uc = rminuit_uc->fit("mr") ;

       double floatParInitVal[10000] ;
       char   floatParName[10000][100] ;
       int nFloatParInitVal(0) ;
       RooArgList ral_floats = rfr_uc->floatParsFinal() ;
       TIterator* floatParIter = ral_floats.createIterator() ;
       {
          RooRealVar* par ;
          while ( (par = (RooRealVar*) floatParIter->Next()) ) {
             sprintf( floatParName[nFloatParInitVal], "%s", par->GetName() ) ;
             floatParInitVal[nFloatParInitVal] = par->getVal() ;
             nFloatParInitVal++ ;
          }
       }


       printf("\n\n Unbiased best value for new POI %s is : %7.1f\n\n", new_poi_rar->GetName(), new_poi_rar->getVal() ) ;
       double best_poi_val = new_poi_rar->getVal() ;

       char minuit_formula[10000] ;
       sprintf( minuit_formula, "%s+%s*(%s-%s)*(%s-%s)",
         nll->GetName(),
         rrv_constraintWidth->GetName(),
         new_poi_rar->GetName(), rrv_poiValue->GetName(),
         new_poi_rar->GetName(), rrv_poiValue->GetName()
          ) ;

       printf("\n\n Creating new minuit variable with formula: %s\n\n", minuit_formula ) ;
       RooFormulaVar* new_minuit_var = new RooFormulaVar("new_minuit_var", minuit_formula,
           RooArgList( *nll,
                       *rrv_constraintWidth,
                       *new_poi_rar, *rrv_poiValue,
                       *new_poi_rar, *rrv_poiValue
                       ) ) ;

       printf("\n\n Current value is %.2f\n\n",
            new_minuit_var->getVal() ) ;

       rminuit = new RooMinuit( *new_minuit_var ) ;


       RooAbsReal* plot_var = nll ;

       printf("\n\n Current value is %.2f\n\n",
            plot_var->getVal() ) ;


       rminuit->setPrintLevel(verbLevel-1) ;
       if ( verbLevel <=0 ) { rminuit->setNoWarn() ; }


       if ( poiMinVal < 0. && poiMaxVal < 0. ) {

          printf("\n\n Automatic determination of scan range.\n\n") ;

          if ( startPoiVal <= 0. ) {
             printf("\n\n *** POI starting value zero or negative %g.  Quit.\n\n\n", startPoiVal ) ;
             return ;
          }

          poiMinVal = startPoiVal - 3.5 * sqrt(startPoiVal) ;
          poiMaxVal = startPoiVal + 6.0 * sqrt(startPoiVal) ;

          if ( poiMinVal < 0. ) { poiMinVal = 0. ; }

          printf("    Start val = %g.   Scan range:   %g  to  %g\n\n", startPoiVal, poiMinVal, poiMaxVal ) ;


       }



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


       double poiVals_scanDown[1000] ;
       double nllVals_scanDown[1000] ;

       //-- Do scan down from best value.

       printf("\n\n +++++ Starting scan down from best value.\n\n") ;

       double minNllVal(1.e9) ;

       for ( int poivi=0; poivi < npoiPoints/2 ; poivi++ ) {

          ////double poiValue = poiMinVal + poivi*(poiMaxVal-poiMinVal)/(1.*(npoiPoints-1)) ;
          double poiValue = best_poi_val - poivi*(best_poi_val-poiMinVal)/(1.*(npoiPoints/2-1)) ;

          rrv_poiValue -> setVal( poiValue ) ;
          rrv_poiValue -> setConstant( kTRUE ) ;


       //+++++++++++++++++++++++++++++++++++

          rminuit->migrad() ;
          rminuit->hesse() ;
          RooFitResult* rfr = rminuit->save() ;

       //+++++++++++++++++++++++++++++++++++


          if ( verbLevel > 0 ) { rfr->Print("v") ; }


          float fit_minuit_var_val = rfr->minNll() ;

          printf(" %02d : poi constraint = %.2f : allvars : MinuitVar, createNLL, PV, POI :    %.5f   %.5f   %.5f   %.5f\n",
                poivi, rrv_poiValue->getVal(), fit_minuit_var_val, nll->getVal(), plot_var->getVal(), new_poi_rar->getVal() ) ;
          cout << flush ;



          poiVals_scanDown[poivi] = new_poi_rar->getVal() ;
          nllVals_scanDown[poivi] = plot_var->getVal() ;

          if ( nllVals_scanDown[poivi] < minNllVal ) { minNllVal = nllVals_scanDown[poivi] ; }

          delete rfr ;


       } // poivi


       printf("\n\n +++++ Resetting floats to best fit values.\n\n") ;

       for ( int pi=0; pi<nFloatParInitVal; pi++ ) {
          RooRealVar* par = ws->var( floatParName[pi] ) ;
          par->setVal( floatParInitVal[pi] ) ;
       } // pi.

       printf("\n\n +++++ Starting scan up from best value.\n\n") ;

      //-- Now do scan up.

       double poiVals_scanUp[1000] ;
       double nllVals_scanUp[1000] ;

       for ( int poivi=0; poivi < npoiPoints/2 ; poivi++ ) {

          double poiValue = best_poi_val + poivi*(poiMaxVal-best_poi_val)/(1.*(npoiPoints/2-1)) ;

          rrv_poiValue -> setVal( poiValue ) ;
          rrv_poiValue -> setConstant( kTRUE ) ;


       //+++++++++++++++++++++++++++++++++++

          rminuit->migrad() ;
          rminuit->hesse() ;
          RooFitResult* rfr = rminuit->save() ;

       //+++++++++++++++++++++++++++++++++++


          if ( verbLevel > 0 ) { rfr->Print("v") ; }


          float fit_minuit_var_val = rfr->minNll() ;

          printf(" %02d : poi constraint = %.2f : allvars : MinuitVar, createNLL, PV, POI :    %.5f   %.5f   %.5f   %.5f\n",
                poivi, rrv_poiValue->getVal(), fit_minuit_var_val, nll->getVal(), plot_var->getVal(), new_poi_rar->getVal() ) ;
          cout << flush ;

          poiVals_scanUp[poivi] = new_poi_rar->getVal() ;
          nllVals_scanUp[poivi] = plot_var->getVal() ;

          if ( nllVals_scanUp[poivi] < minNllVal ) { minNllVal = nllVals_scanUp[poivi] ; }

          delete rfr ;


       } // poivi





       double poiVals[1000] ;
       double nllVals[1000] ;

       int pointCount(0) ;
       for ( int pi=0; pi<npoiPoints/2; pi++ ) {
          poiVals[pi] = poiVals_scanDown[(npoiPoints/2-1)-pi] ;
          nllVals[pi] = nllVals_scanDown[(npoiPoints/2-1)-pi] ;
          pointCount++ ;
       }
       for ( int pi=1; pi<npoiPoints/2; pi++ ) {
          poiVals[pointCount] = poiVals_scanUp[pi] ;
          nllVals[pointCount] = nllVals_scanUp[pi] ;
          pointCount++ ;
       }
       npoiPoints = pointCount ;

       printf("\n\n --- TGraph arrays:\n") ;
       for ( int i=0; i<npoiPoints; i++ ) {
          printf("  %2d : poi = %6.1f, nll = %g\n", i, poiVals[i], nllVals[i] ) ;
       }
       printf("\n\n") ;

       double nllDiffVals[1000] ;

       double poiAtMinlnL(-1.) ;
       double poiAtMinusDelta2(-1.) ;
       double poiAtPlusDelta2(-1.) ;
       for ( int poivi=0; poivi < npoiPoints ; poivi++ ) {
          nllDiffVals[poivi] = 2.*(nllVals[poivi] - minNllVal) ;
          double poiValue = poiMinVal + poivi*(poiMaxVal-poiMinVal)/(1.*npoiPoints) ;
          if ( nllDiffVals[poivi] < 0.01 ) { poiAtMinlnL = poiValue ; }
          if ( poiAtMinusDelta2 < 0. && nllDiffVals[poivi] < 2.5 ) { poiAtMinusDelta2 = poiValue ; }
          if ( poiAtMinlnL > 0. && poiAtPlusDelta2 < 0. && nllDiffVals[poivi] > 2.0 ) { poiAtPlusDelta2 = poiValue ; }
       } // poivi

       printf("\n\n Estimates for poi at delta ln L = -2, 0, +2:  %g ,   %g ,   %g\n\n", poiAtMinusDelta2, poiAtMinlnL, poiAtPlusDelta2 ) ;




      //--- Main canvas

       TCanvas* cscan = (TCanvas*) gDirectory->FindObject("cscan") ;
       if ( cscan == 0x0 ) {
          printf("\n Creating canvas.\n\n") ;
          cscan = new TCanvas("cscan","Delta nll") ;
       }


       char gname[1000] ;

       TGraph* graph = new TGraph( npoiPoints, poiVals, nllDiffVals ) ;
       sprintf( gname, "scan_%s", new_poi_name ) ;
       graph->SetName( gname ) ;

       double poiBest(-1.) ;
       double poiMinus1stdv(-1.) ;
       double poiPlus1stdv(-1.) ;
       double poiMinus2stdv(-1.) ;
       double poiPlus2stdv(-1.) ;
       double twoDeltalnLMin(1e9) ;

       int nscan(1000) ;
       for ( int xi=0; xi<nscan; xi++ ) {

          double x = poiVals[0] + xi*(poiVals[npoiPoints-1]-poiVals[0])/(nscan-1) ;

          double twoDeltalnL = graph -> Eval( x, 0, "S" ) ;

          if ( poiMinus1stdv < 0. && twoDeltalnL < 1.0 ) { poiMinus1stdv = x ; printf(" set m1 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( poiMinus2stdv < 0. && twoDeltalnL < 4.0 ) { poiMinus2stdv = x ; printf(" set m2 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( twoDeltalnL < twoDeltalnLMin ) { poiBest = x ; twoDeltalnLMin = twoDeltalnL ; }
          if ( twoDeltalnLMin < 0.3 && poiPlus1stdv < 0. && twoDeltalnL > 1.0 ) { poiPlus1stdv = x ; printf(" set p1 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}
          if ( twoDeltalnLMin < 0.3 && poiPlus2stdv < 0. && twoDeltalnL > 4.0 ) { poiPlus2stdv = x ; printf(" set p2 : %d, x=%g, 2dnll=%g\n", xi, x, twoDeltalnL) ;}

          if ( xi%100 == 0 ) { printf( " %4d : poi=%6.2f,  2DeltalnL = %6.2f\n", xi, x, twoDeltalnL ) ; }

       }
       printf("\n\n POI estimate :  %g  +%g  -%g    [%g,%g],   two sigma errors: +%g  -%g   [%g,%g]\n\n",
               poiBest,
               (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv), poiMinus1stdv, poiPlus1stdv,
               (poiPlus2stdv-poiBest), (poiBest-poiMinus2stdv), poiMinus2stdv, poiPlus2stdv
               ) ;

       printf(" %s val,pm1sig,pm2sig: %7.2f  %7.2f  %7.2f  %7.2f  %7.2f\n",
          new_poi_name, poiBest, (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv), (poiPlus2stdv-poiBest), (poiBest-poiMinus2stdv) ) ;

       char htitle[1000] ;
       sprintf(htitle, "%s profile likelihood scan: -2ln(L/Lm)", new_poi_name ) ;
       TH1F* hscan = new TH1F("hscan", htitle, 10, poiMinVal, poiMaxVal ) ;
       hscan->SetMinimum(0.) ;
       hscan->SetMaximum(ymax) ;


       hscan->DrawCopy() ;
       graph->SetLineColor(4) ;
       graph->SetLineWidth(3) ;
       graph->Draw("CP") ;
       gPad->SetGridx(1) ;
       gPad->SetGridy(1) ;
       cscan->Update() ;

       TLine* line = new TLine() ;
       line->SetLineColor(2) ;
       line->DrawLine(poiMinVal, 1., poiPlus1stdv, 1.) ;
       line->DrawLine(poiMinus1stdv,0., poiMinus1stdv, 1.) ;
       line->DrawLine(poiPlus1stdv ,0., poiPlus1stdv , 1.) ;

       TText* text = new TText() ;
       text->SetTextSize(0.04) ;
       char tstring[1000] ;

       sprintf( tstring, "%s = %.1f +%.1f -%.1f", new_poi_name, poiBest, (poiPlus1stdv-poiBest), (poiBest-poiMinus1stdv) ) ;
       text -> DrawTextNDC( 0.15, 0.85, tstring ) ;

       sprintf( tstring, "68%% interval [%.1f,  %.1f]", poiMinus1stdv, poiPlus1stdv ) ;
       text -> DrawTextNDC( 0.15, 0.78, tstring ) ;


       char hname[1000] ;
       sprintf( hname, "hscanout_%s", new_poi_name ) ;
       TH1F* hsout = new TH1F( hname,"scan results",4,0.,4.) ;
       double obsVal(-1.) ;
       hsout->SetBinContent(1, obsVal ) ;
       hsout->SetBinContent(2, poiPlus1stdv ) ;
       hsout->SetBinContent(3, poiBest ) ;
       hsout->SetBinContent(4, poiMinus1stdv ) ;
       TAxis* xaxis = hsout->GetXaxis() ;
       xaxis->SetBinLabel(1,"Observed val.") ;
       xaxis->SetBinLabel(2,"Model+1sd") ;
       xaxis->SetBinLabel(3,"Model") ;
       xaxis->SetBinLabel(4,"Model-1sd") ;

       char outrootfile[10000] ;
       sprintf( outrootfile, "%s/scan-ff-%s.root", outputdir.Data(), new_poi_name ) ;

       char outpdffile[10000] ;
       sprintf( outpdffile, "%s/scan-ff-%s.pdf", outputdir.Data(), new_poi_name ) ;

       cscan->Update() ; cscan->Draw() ;

       printf("\n Saving %s\n", outpdffile ) ;
       cscan->SaveAs( outpdffile ) ;



     //--- save in root file

       printf("\n Saving %s\n", outrootfile ) ;
       TFile fout(outrootfile,"recreate") ;
       graph->Write() ;
       hsout->Write() ;
       fout.Close() ;

       delete ws ;
       wstf->Close() ;




   } // constrained_scan.
Beispiel #21
0
//____________________________________
void rs_bernsteinCorrection(){

  // set range of observable
  Double_t lowRange = -1, highRange =5;

  // make a RooRealVar for the observable
  RooRealVar x("x", "x", lowRange, highRange);

  // true model
  RooGaussian narrow("narrow","",x,RooConst(0.), RooConst(.8));
  RooGaussian wide("wide","",x,RooConst(0.), RooConst(2.));
  RooAddPdf reality("reality","",RooArgList(narrow, wide), RooConst(0.8));

  RooDataSet* data = reality.generate(x,1000);

  // nominal model
  RooRealVar sigma("sigma","",1.,0,10);
  RooGaussian nominal("nominal","",x,RooConst(0.), sigma);

  RooWorkspace* wks = new RooWorkspace("myWorksspace");

  wks->import(*data, Rename("data"));
  wks->import(nominal);

  // The tolerance sets the probability to add an unecessary term.
  // lower tolerance will add fewer terms, while higher tolerance
  // will add more terms and provide a more flexible function.
  Double_t tolerance = 0.05; 
  BernsteinCorrection bernsteinCorrection(tolerance);
  Int_t degree = bernsteinCorrection.ImportCorrectedPdf(wks,"nominal","x","data");

  cout << " Correction based on Bernstein Poly of degree " << degree << endl;

  RooPlot* frame = x.frame();
  data->plotOn(frame);
  // plot the best fit nominal model in blue
  nominal.fitTo(*data,PrintLevel(-1));
  nominal.plotOn(frame);

  // plot the best fit corrected model in red
  RooAbsPdf* corrected = wks->pdf("corrected");  
  corrected->fitTo(*data,PrintLevel(-1));
  corrected->plotOn(frame,LineColor(kRed));

  // plot the correction term (* norm constant) in dashed green
  // should make norm constant just be 1, not depend on binning of data
  RooAbsPdf* poly = wks->pdf("poly");  
  poly->plotOn(frame,LineColor(kGreen), LineStyle(kDashed));
  
  // this is a switch to check the sampling distribution
  // of -2 log LR for two comparisons:
  // the first is for n-1 vs. n degree polynomial corrections
  // the second is for n vs. n+1 degree polynomial corrections
  // Here we choose n to be the one chosen by the tolerance
  // critereon above, eg. n = "degree" in the code.
  // Setting this to true is takes about 10 min.
  bool checkSamplingDist = false;

  TCanvas* c1 = new TCanvas();
  if(checkSamplingDist) {
    c1->Divide(1,2);
    c1->cd(1);
  }
  frame->Draw();

  if(checkSamplingDist) {
    // check sampling dist
    TH1F* samplingDist = new TH1F("samplingDist","",20,0,10);
    TH1F* samplingDistExtra = new TH1F("samplingDistExtra","",20,0,10);
    int numToyMC = 1000;
    bernsteinCorrection.CreateQSamplingDist(wks,"nominal","x","data",samplingDist, samplingDistExtra, degree,numToyMC);
    
    c1->cd(2);
    samplingDistExtra->SetLineColor(kRed);
    samplingDistExtra->Draw();
    samplingDist->Draw("same");
  }
}
Beispiel #22
0
void MakePlots(RooWorkspace* ws){

  std::cout << "make plots" << std::endl;

  RooAbsPdf* model = ws->pdf("model");
  RooAbsPdf* model_dY = ws->pdf("model_dY");
  RooRealVar* nsig = ws->var("nsig");
  RooRealVar* nsigDPS = ws->var("nsigDPS");
  RooRealVar* nsigSPS = ws->var("nsigSPS");
  RooRealVar* nBbkg = ws->var("nBbkg");
  RooRealVar* nbkg = ws->var("nbkg");
  RooRealVar* nbkg2 = ws->var("nbkg2");
  RooRealVar* FourMu_Mass = ws->var("FourMu_Mass");
  RooRealVar* Psi1_Mass = ws->var("Psi1_Mass");
  RooRealVar* Psi2_Mass = ws->var("Psi2_Mass");
  RooRealVar* Psi1_CTxy = ws->var("Psi1_CTxy");
  RooRealVar* Psi2_CTxy = ws->var("Psi2_CTxy");
  RooRealVar* Psi1To2_dY = ws->var("Psi1To2_dY");
  RooRealVar* Psi1To2Significance = ws->var("Psi1To2Significance");

  // note, we get the dataset with sWeights
  RooDataSet* data = (RooDataSet*) ws->data("dataWithSWeights");
  model->fitTo(*data, Extended() );

  // make TTree with efficiency variation info
  //TFile *fFile = new TFile("Fit_Results_Eff_Cut.root","recreate");
  setTDRStyle();
  // make our canvas
  TCanvas* cmass1 = new TCanvas("sPlotMass1","sPlotMass1", 600, 600);
  cmass1->cd();
  cmass1->SetFillColor(kWhite);

  RooPlot* Mass1Plot = Psi1_Mass->frame(20);
  data->plotOn(Mass1Plot,Name("data"), DataError(RooAbsData::SumW2));
  model->plotOn(Mass1Plot,Name("all"));
  model->plotOn(Mass1Plot,Name("sig"),RooFit::Components("Sig,sig_*"),RooFit::LineColor(kRed), RooFit::LineStyle(2));
  model->plotOn(Mass1Plot,Name("bkg"),RooFit::Components("bkg_model"),RooFit::LineColor(kGreen), RooFit::LineStyle(3));
  model->plotOn(Mass1Plot,Name("bkg2"),RooFit::Components("bkg2_model"),RooFit::LineColor(kBlack), RooFit::LineStyle(4));
  model->plotOn(Mass1Plot,Name("Bbkg"),RooFit::Components("BBkg,Bbkg_*"),RooFit::LineColor(6), RooFit::LineStyle(7));
  Mass1Plot->SetTitle("");
  Mass1Plot->SetXTitle("#mu^{+}#mu^{-} 1 Invariant Mass (GeV/c^{2})");
  Mass1Plot->SetYTitle("Events / 0.025 GeV/c^{2}");
  Mass1Plot->SetLabelOffset(0.012);
  //Mass1Plot->SetTitleOffset(0.95);
  Mass1Plot->Draw();
  //cmass1->SaveAs("pic/Psi1_mass.pdf");
  //cmass1->Close();

  TCanvas* cmass2 = new TCanvas("sPlotMass2","sPlotMass2", 600, 600);
  cmass2->cd();
  cmass2->SetFillColor(kWhite);
  RooPlot* Mass2Plot = Psi2_Mass->frame(20); 
  data->plotOn(Mass2Plot,Name("data"), DataError(RooAbsData::SumW2)); 
  model->plotOn(Mass2Plot,Name("all"));   
  model->plotOn(Mass2Plot,Name("sig"),RooFit::Components("Sig,sig_*"),RooFit::LineColor(kRed), RooFit::LineStyle(2));
  model->plotOn(Mass2Plot,Name("bkg"),RooFit::Components("bkg_model"),RooFit::LineColor(kGreen), RooFit::LineStyle(3));
  model->plotOn(Mass2Plot,Name("bkg2"),RooFit::Components("bkg2_model"),RooFit::LineColor(kBlack), RooFit::LineStyle(4));
  model->plotOn(Mass2Plot,Name("Bbkg"),RooFit::Components("BBkg,Bbkg_*"),RooFit::LineColor(6), RooFit::LineStyle(7));
  Mass2Plot->SetTitle("");
  Mass2Plot->SetXTitle("#mu^{+}#mu^{-} 2 Invariant Mass (GeV/c^{2})");
  Mass2Plot->SetYTitle("Events / 0.025 GeV/c^{2}");
  Mass2Plot->SetLabelOffset(0.012);
  //Mass2Plot->SetTitleOffset(0.95);
  Mass2Plot->Draw();
  //cmass2->SaveAs("pic/Psi2_mass.pdf");
  //cmass2->Close();

  TCanvas* cctxy1 = new TCanvas("sPlotCTxy1","sPlotCTxy1", 600, 600);
  cctxy1->cd();
  cctxy1->SetFillColor(kWhite);
  RooPlot* CTxy1Plot = Psi1_CTxy->frame(30); 
  data->plotOn(CTxy1Plot,Name("data"), DataError(RooAbsData::SumW2)); 
  model->plotOn(CTxy1Plot,Name("all"));   
  model->plotOn(CTxy1Plot,Name("sig"),RooFit::Components("Sig,sig_*"),RooFit::LineColor(kRed), RooFit::LineStyle(2));
  model->plotOn(CTxy1Plot,Name("bkg"),RooFit::Components("bkg_model"),RooFit::LineColor(kGreen), RooFit::LineStyle(3));
  model->plotOn(CTxy1Plot,Name("bkg2"),RooFit::Components("bkg2_model"),RooFit::LineColor(kBlack), RooFit::LineStyle(4));
  model->plotOn(CTxy1Plot,Name("Bbkg"),RooFit::Components("BBkg,Bbkg_*"),RooFit::LineColor(6), RooFit::LineStyle(7));
  CTxy1Plot->SetTitle("");
  CTxy1Plot->SetXTitle("J/#psi^{1} ct_{xy} (cm)");
  CTxy1Plot->SetYTitle("Events / 0.005 cm");
  CTxy1Plot->SetMaximum(2000);
  CTxy1Plot->SetMinimum(0.1);
  CTxy1Plot->Draw();
  cctxy1->SetLogy();
  //cctxy1->SaveAs("pic/Psi1_CTxy.pdf");
  //cctxy1->Close();

  TCanvas* csig = new TCanvas("sPlotSig","sPlotSig", 600, 600);
  csig->cd();
  RooPlot* SigPlot = Psi1To2Significance->frame(20); 
  data->plotOn(SigPlot,Name("data"), DataError(RooAbsData::SumW2)); 
  model->plotOn(SigPlot,Name("all"));   
  model->plotOn(SigPlot,Name("sig"),RooFit::Components("Sig,sig_*"),RooFit::LineColor(kRed), RooFit::LineStyle(2));
  model->plotOn(SigPlot,Name("bkg"),RooFit::Components("bkg_model"),RooFit::LineColor(kGreen), RooFit::LineStyle(3));
  model->plotOn(SigPlot,Name("bkg2"),RooFit::Components("bkg2_model"),RooFit::LineColor(kBlack), RooFit::LineStyle(4));
  model->plotOn(SigPlot,Name("Bbkg"),RooFit::Components("BBkg,Bbkg_*"),RooFit::LineColor(6), RooFit::LineStyle(7));
  SigPlot->SetTitle("");
  SigPlot->SetYTitle("Events / 0.4");
  SigPlot->SetXTitle("J/#psi Distance Significance");
  SigPlot->Draw();
  //csig->SaveAs("pic/Psi1To2Significance.pdf");
  //csig->Close();

  // create weighted data set (signal-weighted)
  //RooDataSet * dataw_sig = new RooDataSet(data->GetName(),data->GetTitle(),data,*data->get(),0,"nsig_sw");
  //  model_dY->fitTo(*data);
  //TCanvas* cdata2 = new TCanvas("sPlot2","sPlots2", 700, 500);
  //cdata2->cd();
  //RooPlot* frame2 = Psi1To2_dY->frame(20); 
  //dataw_sig->plotOn(frame2, DataError(RooAbsData::SumW2) ); 
  /*
  model_dY->fitTo(*dataw_sig, SumW2Error(kTRUE), Extended());
  model_dY->plotOn(frame2);
  model_dY->plotOn(frame2,RooFit::Components("*DPS"),RooFit::LineColor(kRed), RooFit::LineStyle(kDashed));
  model_dY->plotOn(frame2,RooFit::Components("*SPS"),RooFit::LineColor(kGreen), RooFit::LineStyle(kDashed));
  */
  //frame2->SetTitle("DeltaY distribution for sig");
  //frame2->SetMinimum(1e-03);
  //frame2->Draw();

  //TCanvas* cdata3 = new TCanvas("sPlot3","sPlots3", 700, 500);
  //cdata3->cd();
  //RooPlot* frame3 = FourMu_Mass->frame(Bins(14),Range(6.,20.)); 
  //dataw_sig->plotOn(frame3, DataError(RooAbsData::SumW2));
  //frame3->SetTitle("FourMu_Mass distribution for sig");
  //frame3->SetMinimum(1e-03);
  //frame3->Draw();

  //fFile->Write();
  //fFile->Close();
  //delete fFile;

}
Beispiel #23
0
void plot_pll(TString fname="monoh_withsm_SRCR_bg11.7_bgslop-0.0_nsig0.0.root")
{
  SetAtlasStyle();



  TFile* file =  TFile::Open(fname);
  RooWorkspace* wspace = (RooWorkspace*) file->Get("wspace");

  cout << "\n\ncheck that eff and reco terms included in BSM component to make fiducial cross-section" <<endl;
  wspace->function("nsig")->Print();
  RooRealVar* reco = wspace->var("reco");
  if(  wspace->function("nsig")->dependsOn(*reco) ) {
    cout << "all good." <<endl;
  } else {
    cout << "need to rerun fit_withsm using DO_FIDUCIAL_LIMIT true" <<endl;
    return;
  }

  /*
  // DANGER
  // TEST WITH EXAGGERATED UNCERTAINTY
  wspace->var("unc_theory")->setMax(1);
  wspace->var("unc_theory")->setVal(1);
  wspace->var("unc_theory")->Print();
  */

  // this was for making plot about decoupling/recoupling approach
  TCanvas* tc = new TCanvas("tc","",400,400);
  RooPlot *frame = wspace->var("xsec_bsm")->frame();
  RooAbsPdf* pdfc = wspace->pdf("jointModeld");
  RooAbsData* data = wspace->data("data");
  RooAbsReal *nllJoint = pdfc->createNLL(*data, RooFit::Constrained()); // slice with fixed xsec_bsm
  RooAbsReal *profileJoint = nllJoint->createProfile(*wspace->var("xsec_bsm"));

  wspace->allVars().Print("v");
  pdfc->fitTo(*data);
  wspace->allVars().Print("v");
  wspace->var("xsec_bsm")->Print();
  double nllmin = 2*nllJoint->getVal();
  wspace->var("xsec_bsm")->setVal(0);
  double nll0 = 2*nllJoint->getVal();
  cout << Form("nllmin = %f, nll0 = %f, Z=%f", nllmin, nll0, sqrt(nll0-nllmin)) << endl;
  nllJoint->plotOn(frame, RooFit::LineColor(kGreen), RooFit::LineStyle(kDotted), RooFit::ShiftToZero(), RooFit::Name("nll_statonly")); // no error
  profileJoint->plotOn(frame,RooFit::Name("pll") );
  wspace->var("xsec_sm")->Print();
  wspace->var("theory")->Print();
  wspace->var("theory")->setConstant();
  profileJoint->plotOn(frame, RooFit::LineColor(kRed), RooFit::LineStyle(kDashed), RooFit::Name("pll_smfixed") );

  frame->GetXaxis()->SetTitle("#sigma_{BSM, fid} [fb]");
  frame->GetYaxis()->SetTitle("-log #lambda  ( #sigma_{BSM, fid} )");
  double temp = frame->GetYaxis()->GetTitleOffset();
  frame->GetYaxis()->SetTitleOffset( 1.1* temp );

  frame->SetMinimum(1e-7);
  frame->SetMaximum(4);


  // Legend
  double x1,y1,x2,y2;
  GetX1Y1X2Y2(tc,x1,y1,x2,y2);
  TLegend *legend_sr=FastLegend(x2-0.75,y2-0.3,x2-0.25,y2-0.5,0.045);
  legend_sr->AddEntry(frame->findObject("pll"),"with #sigma_{SM} uncertainty","L");
  legend_sr->AddEntry(frame->findObject("pll_smfixed"),"with #sigma_{SM} constant","L");
  legend_sr->AddEntry(frame->findObject("nll_statonly"),"no systematics","L");
  frame->Draw();
  legend_sr->Draw("SAME");



  // descriptive text
  vector<TString> pavetext11;
  pavetext11.push_back("#bf{#it{ATLAS Internal}}");
  pavetext11.push_back("#sqrt{#it{s}} = 8 TeV #scale[0.6]{#int}Ldt = 20.3 fb^{-1}");
  pavetext11.push_back("#it{H}+#it{E}_{T}^{miss} , #it{H #rightarrow #gamma#gamma}, #it{m}_{#it{H}} = 125.4 GeV");

  TPaveText* text11=CreatePaveText(x2-0.75,y2-0.25,x2-0.25,y2-0.05,pavetext11,0.045);
  text11->Draw();

  tc->SaveAs("pll.pdf");



  /*
  wspace->var("xsec_bsm")->setConstant(true);
  wspace->var("eff"     )->setConstant(true);
  wspace->var("mh"      )->setConstant(true);
  wspace->var("sigma_h" )->setConstant(true);
  wspace->var("lumi"    )->setConstant(true);
  wspace->var("xsec_sm" )->setVal(v_xsec_sm);
  wspace->var("eff"     )->setVal(1.0);
  wspace->var("lumi"    )->setVal(v_lumi);
  TH1* nllHist = profileJoint->createHistogram("xsec_bsm",100);
  TFile* out = new TFile("nllHist.root","REPLACE");
  nllHist->Write()
  out->Write();
  out->Close();
  */

}
Beispiel #24
0
  /***********************************************************************
   ***********************************************************************
   *   CONSTRUCTOR   MAKES ALLLLLLLL
   *******************************************************************
   *************************************************
   *****************************
   *****
   */
  Tbroomfit(double xlow, double xhi, TH1 *h2,  int npeak, double *peak, double *sigm, const char *chpol="p0"){
    int iq=0;
    printf("constructor - %d   %ld", iq++,  (int64_t)h2 );
    h2->Print();
    /*
     *   get global area, ranges for sigma, x
     */
    npeaks=npeak; // class defined int
    //    double areah2=h2->Integral( int(xlow), int(xhi) ); // WRONG - BINS
    min= h2->GetXaxis()->GetFirst();
    printf("constructor - %d   %f", iq++, min  );
    max= h2->GetXaxis()->GetLast();
    printf("constructor - %d   %f", iq++, max  );
    double areah2=h2->Integral( min, max );
    printf("constructor - %d   %f", iq++,  areah2 );
    min=xlow;
    max=xhi;


    double sigmamin=(max-min)/300;
    double sigmamax=(max-min)/4;
    double areamin=0;
    double areamax=2*areah2;
    printf("x:(%f,%f)  s:(%f,%f)  a:(%f,%f) \n", min,max,sigmamin, sigmamax,areamin, areamax );
  /*
   *   definition of  variables..............
   *
   */    
    RooRealVar       x("x",    "x",   min, max);

    int MAXPEAKS=6;  // later from 5 to 6 ???


    printf("RooFit: npeaks=%d\n",  npeaks );
    // ABOVE:  RooRealVar *msat[14][5]; //  POINTERS TO ALL variables
    // 0  m     Mean
    // 1  s     Sigma
    // 2  a     Area
    // 3  t     Tail
    // 4  [0] nalpha
    // 5  [0] n1

for (int ii=0;ii<14;ii++){
 for (int jj=0;jj<MAXPEAKS;jj++){
   msat[ii][jj]=NULL; 
   msat_values[ii][jj]=0.0;
 } //for for
 }// for for 

 printf("delete fitresult, why crash?\n%s","");
 fitresult=NULL;
 printf("delete fitresult, no crash?\n%s","");


    RooRealVar    mean1("mean1", "mean",  1*(max-min)/(npeaks+1)+min,    min,max);msat[0][0]=&mean1;
    RooRealVar    mean2("mean2", "mean",  2*(max-min)/(npeaks+1)+min,    min,max);msat[0][1]=&mean2;
    RooRealVar    mean3("mean3", "mean",  3*(max-min)/(npeaks+1)+min,    min,max);msat[0][2]=&mean3;
    RooRealVar    mean4("mean4", "mean",  4*(max-min)/(npeaks+1)+min,    min,max);msat[0][3]=&mean4;
    RooRealVar    mean5("mean5", "mean",  5*(max-min)/(npeaks+1)+min,    min,max);msat[0][4]=&mean5;
    RooRealVar    mean6("mean6", "mean",  6*(max-min)/(npeaks+1)+min,    min,max);msat[0][5]=&mean6;


    RooRealVar   sigma1("sigma1","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][0]=&sigma1;
    RooRealVar   sigma2("sigma2","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][1]=&sigma2;
    RooRealVar   sigma3("sigma3","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][2]=&sigma3;
    RooRealVar   sigma4("sigma4","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][3]=&sigma4;
    RooRealVar   sigma5("sigma5","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][4]=&sigma5;
    RooRealVar   sigma6("sigma6","sigma", (max-min)/10,       sigmamin,  sigmamax );msat[1][5]=&sigma6;


    RooRealVar    area1("area1", "area",      areah2/npeaks,       areamin, areamax  );msat[2][0]=&area1;
    RooRealVar    area2("area2", "area",      areah2/npeaks,       areamin, areamax  );msat[2][1]=&area2; 
    RooRealVar    area3("area3", "area",      areah2/npeaks,       areamin, areamax  );msat[2][2]=&area3; 
    RooRealVar    area4("area4", "area",      areah2/npeaks,       areamin, areamax  );msat[2][3]=&area4; 
    RooRealVar    area5("area5", "area",      areah2/npeaks,       areamin, areamax  );msat[2][4]=&area5; 
    RooRealVar    area6("area6", "area",      areah2/npeaks,       areamin, areamax  );msat[2][5]=&area6; 

    RooRealVar   bgarea("bgarea", "bgarea", areah2/5, 0, 2*areah2);  



    double  tailstart=-1.0;//  tune the tails....
    double  tailmin=-1e+4;
    double  tailmax=1e+4;

    RooRealVar    tail1("tail1", "tail",      tailstart,       tailmin, tailmax  );msat[3][0]=&tail1;
    RooRealVar    tail2("tail2", "tail",      tailstart,       tailmin, tailmax  );msat[3][1]=&tail2;
    RooRealVar    tail3("tail3", "tail",      tailstart,       tailmin, tailmax  );msat[3][2]=&tail3;
    RooRealVar    tail4("tail4", "tail",      tailstart,       tailmin, tailmax  );msat[3][3]=&tail4;
    RooRealVar    tail5("tail5", "tail",      tailstart,       tailmin, tailmax  );msat[3][4]=&tail5;
    RooRealVar    tail6("tail6", "tail",      tailstart,       tailmin, tailmax  );msat[3][5]=&tail6;

    // for CBShape
    RooRealVar    nalpha1("nalpha1", "nalpha",      1.3, 0, 100  );msat[4][0]=&nalpha1;

    RooRealVar    n1("n1",          "n",         5.1, 0, 100  );  msat[5][0]=&n1;






    /*
     *   initial values  for  peak positions................
     */
    if (npeaks>=1) {mean1=peak[0];sigma1=sigm[0];}
    if (npeaks>=2) {mean2=peak[1];sigma2=sigm[1];}
    if (npeaks>=3) {mean3=peak[2];sigma3=sigm[2];}
    if (npeaks>=4) {mean4=peak[3];sigma4=sigm[3];}
    if (npeaks>=5) {mean5=peak[4];sigma5=sigm[4];}
    if (npeaks>=6) {mean6=peak[5];sigma6=sigm[5];}


    /*
     *    RooAbsPdf -> RooGaussian
     *                 RooNovosibirsk
     *                 RooLandau
     */
     RooAbsPdf *pk[6];                 // MAXIMUM PEAKS ==5    6 NOW!!             
     RooAbsPdf *pk_dicto[14][6];        // ALL DICTIONARY OF PEAKS..........
     //  Abstract Class.... carrefuly

    RooGaussian gauss1("gauss1","gauss(x,mean,sigma)", x, mean1, sigma1);pk_dicto[0][0]=&gauss1;
    RooGaussian gauss2("gauss2","gauss(x,mean,sigma)", x, mean2, sigma2);pk_dicto[0][1]=&gauss2;
    RooGaussian gauss3("gauss3","gauss(x,mean,sigma)", x, mean3, sigma3);pk_dicto[0][2]=&gauss3;
    RooGaussian gauss4("gauss4","gauss(x,mean,sigma)", x, mean4, sigma4);pk_dicto[0][3]=&gauss4;
    RooGaussian gauss5("gauss5","gauss(x,mean,sigma)", x, mean5, sigma5);pk_dicto[0][4]=&gauss5;
    RooGaussian gauss6("gauss6","gauss(x,mean,sigma)", x, mean6, sigma6);pk_dicto[0][5]=&gauss6;

    RooNovosibirsk ns1("ns1","novosib(x,mean,sigma,tail)", x, mean1,sigma1, tail1 );pk_dicto[1][0]=&ns1;
    RooNovosibirsk ns2("ns2","novosib(x,mean,sigma,tail)", x, mean2,sigma2, tail2 );pk_dicto[1][1]=&ns2;
    RooNovosibirsk ns3("ns3","novosib(x,mean,sigma,tail)", x, mean3,sigma3, tail3 );pk_dicto[1][2]=&ns3;
    RooNovosibirsk ns4("ns4","novosib(x,mean,sigma,tail)", x, mean4,sigma4, tail4 );pk_dicto[1][3]=&ns4;
    RooNovosibirsk ns5("ns5","novosib(x,mean,sigma,tail)", x, mean5,sigma5, tail5 );pk_dicto[1][4]=&ns5;
 
    // BreitWiegner  is  Lorentzian...?
    RooBreitWigner bw1("bw1","BreitWigner(x,mean,sigma)", x, mean1, sigma1 );pk_dicto[2][0]=&bw1;
    RooBreitWigner bw2("bw2","BreitWigner(x,mean,sigma)", x, mean2, sigma2 );pk_dicto[2][1]=&bw2;
    RooBreitWigner bw3("bw3","BreitWigner(x,mean,sigma)", x, mean3, sigma3 );pk_dicto[2][2]=&bw3;
    RooBreitWigner bw4("bw4","BreitWigner(x,mean,sigma)", x, mean4, sigma4 );pk_dicto[2][3]=&bw4;
    RooBreitWigner bw5("bw5","BreitWigner(x,mean,sigma)", x, mean5, sigma5 );pk_dicto[2][4]=&bw5;

    RooCBShape cb1("cb1","CBShape(x,mean,sigma)", x, mean1, sigma1, nalpha1, n1 );pk_dicto[3][0]=&cb1;
    RooCBShape cb2("cb2","CBShape(x,mean,sigma)", x, mean2, sigma2, nalpha1, n1 );pk_dicto[3][1]=&cb2;
    RooCBShape cb3("cb3","CBShape(x,mean,sigma)", x, mean3, sigma3, nalpha1, n1 );pk_dicto[3][2]=&cb3;
    RooCBShape cb4("cb4","CBShape(x,mean,sigma)", x, mean4, sigma4, nalpha1, n1 );pk_dicto[3][3]=&cb4;
    RooCBShape cb5("cb5","CBShape(x,mean,sigma)", x, mean5, sigma5, nalpha1, n1 );pk_dicto[3][4]=&cb5;
    RooCBShape cb6("cb6","CBShape(x,mean,sigma)", x, mean6, sigma6, nalpha1, n1 );pk_dicto[3][5]=&cb6;



    /*
     *    PEAK TYPES   BACKGROUND TYPE .........   COMMAND BOX  OPTIONS ......
     */
    /****************************************************************************
     *  PLAY  WITH  THE DEFINITION  COMMANDLINE...................... POLYNOM + PEAKS
     */
    // CALSS DECLARED TString s;
  s=chpol;
  /*
   *   peaks+bg== ALL BEFORE  ; or :          (after ...  it is a conditions/options)
   */
  TString command;
  int comstart=s.Index(":");   if (comstart<0){ comstart=s.Index(";");}
  if  (comstart<0){ command="";}else{
    command=s(comstart+1, s.Length()-comstart -1 ); // without ;
    s=s(0,comstart); // without ;
    printf("COMMANDLINE : %s\n",  command.Data()  );
    if (TPRegexp("scom").Match(command)!=0){
      
    }// COMMANDS - 
  }// there is some command
  /*************************************************
   *  PLAY WITH peaks+bg..................    s
   */
  s.Append("+"); s.Prepend("+");  s.ReplaceAll(" ","+");
  s.ReplaceAll("++++","+"); s.ReplaceAll("+++","+"); s.ReplaceAll("++","+");s.ReplaceAll("++","+");
  printf ("   regextp =  %s\n",  s.Data()  );
  if (TPRegexp("\\+p[\\dn]\\+").Match(s)==0){ // no match
     printf("NO polynomial demanded =>: %s\n",  "appending  pn command"  ); s.Append("pn+");
  }
  TString spk=s;   TString sbg=s;
  TPRegexp("\\+p[\\dn]\\+").Substitute(spk,"+");  // remove   +p.+   
  TPRegexp(".+(p[\\dn]).+").Substitute(sbg,"$1"); // remove   all but +p+   

  printf ("PEAKS=%s      BG=%s\n",  spk.Data() ,  sbg.Data()  );
  spk.ReplaceAll("+","");   //  VARIANT 1 ------- EACH  LETTER MEANS ONE PEAK 






  /************************************************************************
   *          PREPARE PEAKS  FOLLOWING THE COMMAND BOX................
   */
    //default PEAK types
    pk[0]=&gauss1;
    pk[1]=&gauss2;
    pk[2]=&gauss3;
    pk[3]=&gauss4;
    pk[4]=&gauss5;
    pk[5]=&gauss6;


  int maxi=spk.Length();
  if (maxi>npeaks){maxi=npeaks;}
  for (int i=0;i<maxi;i++){
    if (spk[i]=='n'){
      pk[i]=pk_dicto[1][i];//novosibirsk
      printf("PEAK #%d ... Novosibirsk\n", i );
    }else if(spk[i]=='b'){
      pk[i]=pk_dicto[2][i];//BreitWiegner
      printf("PEAK #%d ... BreitWigner\n", i );
    }else if(spk[i]=='c'){
      pk[i]=pk_dicto[3][i];//CBShape
      printf("PEAK #%d ... CBShape\n", i );
    }else if(spk[i]=='y'){
    }else if(spk[i]=='z'){
    }else{
      pk[i]=pk_dicto[0][i]; //gauss
      printf("PEAK #%d ... Gaussian\n", i );
    }// ELSE CHAIN
  }//i to maxi


  for (int i=0;i<npeaks;i++){ printf("Peak %d   at  %f  s=%f:  PRINT:\n  " ,  i, peak[i], sigm[i]  );pk[i]->Print();}



 /******************************************************** BACKGROUND pn-p4
     *   a0 == level - also skew
     *   a1 == p2
     *   a2 == p3
     */
 // Build Chebychev polynomial p.d.f.  
 // RooRealVar a0("a0","a0", 0.) ;
  RooRealVar a0("a0","a0",    0., -10, 10) ;
  RooRealVar a1("a1","a1",    0., -10, 10) ;
  RooRealVar a2("a2","a2",    0., -10, 10) ;
  RooRealVar a3("a3","a3",    0., -10, 10) ;
  RooArgSet setcheb;
  if ( sbg=="pn" ){ setcheb.add(a0);  a0=0.; a0.setConstant(kTRUE);bgarea=0.; bgarea.setConstant(kTRUE);}
  if ( sbg=="p0" ){ setcheb.add(a0);  a0=0.; a0.setConstant(kTRUE); }
  if ( sbg=="p1" ){ setcheb.add(a0); }
  if ( sbg=="p2" ){ setcheb.add(a1); setcheb.add(a0); }
  if ( sbg=="p3" ){ setcheb.add(a2); setcheb.add(a1); setcheb.add(a0); }
  if ( sbg=="p4" ){ setcheb.add(a3);setcheb.add(a2); setcheb.add(a1); setcheb.add(a0); }
  //  RooChebychev bkg("bkg","Background",x,RooArgSet(a0,a1,a2,a3) ) ;
  RooChebychev bkg("bkg","Background",x, setcheb ) ;

 


  /**********************************************************************
   * MODEL
   */
 
 
 RooArgList rl;  
 if (npeaks>0)rl.add( *pk[0] );  
 if (npeaks>1)rl.add( *pk[1] );  
 if (npeaks>2)rl.add( *pk[2] );  
 if (npeaks>3)rl.add( *pk[3] );  
 if (npeaks>4)rl.add( *pk[4] );  
 if (npeaks>5)rl.add( *pk[5] );  
 rl.add( bkg ); 
 RooArgSet rs;
 if (npeaks>0)rs.add( area1 );  
 if (npeaks>1)rs.add( area2 );  
 if (npeaks>2)rs.add( area3 );  
 if (npeaks>3)rs.add( area4 );  
 if (npeaks>4)rs.add( area5 );  
 if (npeaks>5)rs.add( area6 );  
 rs.add( bgarea );
 RooAddPdf modelV("model","model", rl, rs );


 /*
  *  WITH CUSTOMIZER - I can change parameters inside. But
  *             - then all is a clone and I dont know how to reach it
  */
   RooCustomizer cust( modelV ,"cust"); 
   /*
    *  Possibility to fix all sigma  or tails....
    */ 
   if (TPRegexp("scom").Match(command)!=0){//----------------------SCOM
     printf("all sigma have common values.....\n%s", ""); 
     if (npeaks>1)cust.replaceArg(sigma2,sigma1) ;
     if (npeaks>2)cust.replaceArg(sigma3,sigma1) ;
     if (npeaks>3)cust.replaceArg(sigma4,sigma1) ;
     if (npeaks>4)cust.replaceArg(sigma5,sigma1) ;
     if (npeaks>5)cust.replaceArg(sigma6,sigma1) ;
    }
   if (TPRegexp("tcom").Match(command)!=0){//----------------------TCOM
     printf("all tails have common values.....\n%s", ""); 
     if (npeaks>1)cust.replaceArg(tail2,tail1) ;
     if (npeaks>2)cust.replaceArg(tail3,tail1) ;
     if (npeaks>3)cust.replaceArg(tail4,tail1) ;
     if (npeaks>4)cust.replaceArg(tail5,tail1) ;
     if (npeaks>5)cust.replaceArg(tail6,tail1) ;
    }
   /*   if (TPRegexp("tcom").Match(command)!=0){//----------------------TCOM Neni dalsi ACOM,NCOM pro CB...
     printf("all tails have common values.....\n%s", ""); 
     if (npeaks>1)cust.replaceArg(tail2,tail1) ;
     if (npeaks>2)cust.replaceArg(tail3,tail1) ;
     if (npeaks>3)cust.replaceArg(tail4,tail1) ;
     if (npeaks>4)cust.replaceArg(tail5,tail1) ;
    }
   */
   if  (TPRegexp("p1fix").Match(command)!=0){//----------------------
     mean1.setConstant();printf("position 1 set constant%s\n","");
   }
   if  (TPRegexp("p2fix").Match(command)!=0){//----------------------
     mean2.setConstant();printf("position 2 set constant%s\n","");
   }
   if  (TPRegexp("p3fix").Match(command)!=0){//----------------------
     mean3.setConstant();printf("position 3 set constant%s\n","");
   }
   if  (TPRegexp("p4fix").Match(command)!=0){//----------------------
     mean4.setConstant();printf("position 4 set constant%s\n","");
   }
   if  (TPRegexp("p5fix").Match(command)!=0){//----------------------
     mean5.setConstant();printf("position 5 set constant%s\n","");
   }
   if  (TPRegexp("p6fix").Match(command)!=0){//----------------------
     mean6.setConstant();printf("position 6 set constant%s\n","");
   }
   if  (TPRegexp("s1fix").Match(command)!=0){//----------------------
     sigma1.setConstant();printf("sigma 1 set constant%s\n","");
   }
   if  (TPRegexp("s2fix").Match(command)!=0){//----------------------
     sigma2.setConstant();printf("sigma 2 set constant%s\n","");
   }
   if  (TPRegexp("s3fix").Match(command)!=0){//----------------------
     sigma3.setConstant();printf("sigma 3 set constant%s\n","");
   }
   if  (TPRegexp("s4fix").Match(command)!=0){//----------------------
     sigma4.setConstant();printf("sigma 4 set constant%s\n","");
   }
   if  (TPRegexp("s5fix").Match(command)!=0){//----------------------
     sigma5.setConstant();printf("sigma 5 set constant%s\n","");
   }
   if  (TPRegexp("s6fix").Match(command)!=0){//----------------------
     sigma6.setConstant();printf("sigma 6 set constant%s\n","");
   }


   RooAbsPdf* model = (RooAbsPdf*) cust.build(kTRUE) ; //build a clone...comment on changes...
   //   model->Print("t") ;
   //delete model ; // eventualy delete the model...





 /*
  *  DISPLAY RESULTS            >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  */
   TPad *orig_gpad=(TPad*)gPad;


   TCanvas *c;
   c=(TCanvas*)gROOT->GetListOfCanvases()->FindObject("fitresult");
   if (c==NULL){
     printf("making new canvas\n%s","");
     c=new TCanvas("fitresult",h2->GetName(),1000,700);  
   }else{
     printf("using old canvas\n%s","");
     c->SetTitle( h2->GetName() );
   }
   c->Clear();
     printf(" canvas cleared\n%s","");
   c->Divide(1,2) ;
     printf(" canvas divided\n%s","");
  c->Modified();c->Update(); 

 RooDataHist datah("datah","datah with x",x,h2);
 RooPlot* xframe = x.frame();
 datah.plotOn(xframe,  DrawOption("logy") );

 // return;
   if (TPRegexp("chi2").Match(command)!=0){//----------------------CHI2
     //from lorenzo moneta
     //     TH1 * h1 = datah.createHistogram(x);
     //     TF1 * f = model->asTF(RooArgList(x) , parameters ); //??? 
     //     h2->Fit(f);
     //It will work but you need to create a THNSparse and fit it 
     //or use directly the ROOT::Fit::BinData class to create a ROOT::Fit::Chi2Function to minimize.
     // THIS CANNOT DO ZERO BINS
     fitresult = model->chi2FitTo( datah , Save()  );  
   }else{
     //   FIT    FIT    FIT    FIT    FIT    FIT    FIT     FIT    FIT   FIT   
      fitresult = model->fitTo( datah , Save()  );   
   }

   fitresult->SetTitle( h2->GetName() ); // I PUT histogram name to global fitresult
   
   // will be done by printResult ... fitresult->Print("v") ;
  //duplicite  fitresult->floatParsFinal().Print("s") ;
  // later - after  parsfinale .... : printResult();
    //    model->Print();  // not interesting........
    model->plotOn(xframe, LineColor(kRed),   DrawOption("l0z") );

  //,Minos(kFALSE)

 /*
  *  Posledni nakreslena vec je vychodiskem pro xframe->resid...?
  *   NA PORADI ZALEZI....
  */

    //unused RooHist* hresid = xframe->residHist() ;
 RooHist* hpull =  xframe->pullHist() ;

 // RooPlot* xframe2 = x.frame(Title("Residual Distribution")) ;
 // xframe2->addPlotable(hresid,"P") ;

  // Construct a histogram with the pulls of the data w.r.t the curve
 RooPlot* xframe3 = x.frame(Title("Pull Distribution")) ;
 xframe3->addPlotable(hpull,"P") ;

  /*
   *  plot components at the end....                     PLOT >>>>>>>>>>>>>>>>
   */

 int colorseq[10]={kRed,kGreen,kBlue,kYellow,kCyan,kMagenta,kViolet,kAzure,kGray,kOrange};

 // RooArgSet* model_params = model->getParameters(x); // this returns all parameters
 RooArgSet* model_params = model->getComponents();
 TIterator* iter = model_params->createIterator() ;
 RooAbsArg* arg ; int icomp=0, ipeak=0;
 //  printf("ENTERING COMPONENT ITERATOR x%dx.....................\n",  icomp );
  while((arg=(RooAbsArg*)iter->Next())) {
    //    printf("printing COMPONENT %d\n",  icomp );
    //    arg->Print();    
    //    printf("NAME==%s\n", arg->Class_Name()  ); //This returns only RooAbsArg
    //    printf("NAME==%s\n", arg->ClassName()  ); //This RooGaussian RooChebychev
    if ( IsPeak( arg->ClassName() )==1 ){
      pk[ipeak]=(RooAbsPdf*)arg; //?
      //      pk[ipeak]->Print();
      ipeak++;
      //      printf("adresses ... %d - %d - %d\n", pk[0], pk[1], pk[2]  );
    }// yes peak.
    icomp++; 
  }//iterations over all components


    model->plotOn(xframe, Components(bkg), LineColor(kRed), LineStyle(kDashed),  DrawOption("l0z") );
    for (int i=0;i<npeaks;i++){
      //      printf("plotting  %d. peak, color %d\n", i,  colorseq[i+1]  );
      //      printf("adresses ... %d - %d - %d\n", pk[0], pk[1], pk[2]  );
      //      pk[i]->Print();
      model->plotOn(xframe, Components( RooArgSet(*pk[i],bkg) ), LineColor(colorseq[i+1]), LineStyle(kDashed),
		    DrawOption("l0z") );
      //		    DrawOption("pz"),DataError(RooAbsData::SumW2) );???  pz removes complains...warnings
      //      model.plotOn(xframe, Components( RooArgSet(*pk[i],bkg) ), LineColor(colorseq[i+1]), LineStyle(kDashed));
    }
 

    // WE SET THE 1st PAD in "fitresult" to LOGY....  1
    //  .....  if the original window is LOGY.....   :)
    //
    //    printf("########### ORIGPAD LOGY==%d #########3\n",  orig_gpad->GetLogy()  );
    c->cd(1); xframe->Draw();  gPad->SetLogy(  orig_gpad->GetLogy()  );
 // c->cd(2); xframe2->Draw();  
 c->cd(2); xframe3->Draw();  
  c->Modified();c->Update(); 

 orig_gpad->cd();


 // printf("msat reference to peak 0 0 = %d,  (%f)\n",  msat[0][0] ,  msat[0][0]->getVal()  );
 for (int ii=0;ii<14;ii++){
 for (int jj=0;jj<MAXPEAKS;jj++){
   if ( msat[ii][jj]!=NULL){
     msat_values[ii][jj]=msat[ii][jj]->getVal();
   }//if
 } //for for
 }// for for   
 printf("at the total end of the constructor....%s\n","");
 // done in pirntResult .. fitresult->floatParsFinal().Print("s") ;
 printResult();
  }; // constructor
Beispiel #25
0
int main(int argc, char **argv)
{
	bool printSw = true;
	//TString massModel = "Gauss-m[5622]";
	string massModel = "DCB-m[5622]";
	TString effbase = "/afs/cern.ch/user/p/pluca/work/Lb/Lmumu/results/";
	bool printeff = false;
	TString dodata = "data";
	bool fitsingle = false;
	TString wstr = "physRate_polp006";
	TString decayToDo = "Lb2Lmumu";
	if(dodata=="genMC") wstr += "_noDecay";

	gROOT->ProcessLine(".x lhcbStyle.C");


	RooRealVar * cosThetaL = new RooRealVar("cosThetaL","cosThetaL",0.,-1.,1.);
	RooRealVar * cosThetaB = new RooRealVar("cosThetaB","cosThetaB",0.,-1.,1.);
	RooRealVar * nsig_sw = new RooRealVar("nsig_sw","nsig_sw",1,-1.e6,1.e6);
	RooRealVar * MCweight = new RooRealVar(wstr,wstr,1.,-1.e10,1.e10);
	RooRealVar * MM = new RooRealVar("Lb_MassConsLambda","Lb_MassConsLambda",5620.,5500.,5900.);
	TString datafilename = "/afs/cern.ch/user/p/pluca/work/Lb/Lmumu/candLb.root";
	if(dodata=="MC") datafilename = "/afs/cern.ch/user/p/pluca/work/Lb/Lmumu/candLb_MC.root";
	if(dodata=="genMC") datafilename = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/"+(string)decayToDo+"_geomMC_Pythia8_NBweighted.root";
	TreeReader * data;
	if(dodata!="genMC") data = new TreeReader("cand"+decayToDo);
	else data = new TreeReader("MCtree");
	data->AddFile(datafilename);

	TFile * histFile = new TFile("Afb_hist.root","recreate");

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

	int nbins = 1;//CutsDef::nq2bins;
	double q2min[] = {15.,11.0,15,16,18};//&CutsDef::q2min_highfirst[0];
	double q2max[] = {20.,12.5,16,18,20};//&CutsDef::q2max_highfirst[0];
	
	//int nbins = CutsDef::nq2bins
	//double *q2min = &CutsDef::q2min[0];
	//double *q2max = &CutsDef::q2max[0];


	TGraphErrors * Afb_vs_q2 = new TGraphErrors();
	TGraphErrors * AfbB_vs_q2 = new TGraphErrors();
	TGraphErrors * fL_vs_q2 = new TGraphErrors();
	TCanvas * ceff = new TCanvas();

	RooCategory * samples = new RooCategory("samples","samples");
	samples->defineType("DD");
	samples->defineType("LL");

	RooRealVar * afb = new RooRealVar("afb","afb",0.,-100,100);
	RooRealVar * fL = new RooRealVar("fL","fL",0.7,-1.,10.);
	//RooRealVar * afb = new RooRealVar("afb","afb",0.,-1.,1.);
	//RooRealVar * fL = new RooRealVar("fL","fL",0.7,0.,1.);
	RooRealVar * origafb = new RooRealVar("afb","afb",0.,-1.,1.);
	RooRealVar * origfL = new RooRealVar("fL","fL",0.7,-1.,10.);
	TString afbLpdf = "((3./8.)*(1.-fL)*(1 + TMath::Power(cosThetaL,2)) + afb*cosThetaL + (3./4.)*fL*(1 - TMath::Power(cosThetaL,2)))";
	RooRealVar * afbB = new RooRealVar("afbB","afbB",0.,-100,100);
	//RooRealVar * afbB = new RooRealVar("afbB","afbB",0.,-1.,1.);
	RooRealVar * origafbB = new RooRealVar("afbB","afbB",0.,-1.,1.);
	TString afbBpdf = "(1 + 2*afbB*cosThetaB)";

	vector< vector< double > > afb_errs, afbB_errs, fL_errs;
	TList * LLlist = new TList, * DDlist = new TList;

	TCanvas * cDD = new TCanvas();
	TCanvas * cLL = new TCanvas();
	TCanvas * cDDB = new TCanvas();
	TCanvas * cLLB = new TCanvas();

	for(int i = 0; i < nbins; i++)
	{
		//if(q2min[i] < 8) continue;
		TString q2name = ((TString)Form("q2_%4.2f_%4.2f",q2min[i],q2max[i])).ReplaceAll(".","");
		TString curq2cut = Form("TMath::Power(J_psi_1S_MM/1000,2) >= %e && TMath::Power(J_psi_1S_MM/1000,2) < %e",q2min[i],q2max[i]);	
		//TString curq2cut = Form("TMath::Power(J_psi_1S_MM/1000,2) >= %e && TMath::Power(J_psi_1S_MM/1000,2) < %e && (Lb_MassConsLambda > 5680 || Lb_MassConsLambda < 5590)",q2min[i],q2max[i]); 
		cout << "------------------- q2 bin: " << q2min[i] << " - " << q2max[i] << " -----------------------" << endl;

		TFile * effFile = NULL;
		TH1F * effDD = NULL, * effLL = NULL, * effLLB = NULL, * effDDB = NULL;
		if(q2min[i] == 15 && q2max[i] == 20)
		{
			effFile = TFile::Open(effbase+"LbeffvscosThetaL_DD.root");
			effDD  = (TH1F *)effFile->Get("htoteff");
			effFile = TFile::Open(effbase+"LbeffvscosThetaL_LL.root");
			effLL  = (TH1F *)effFile->Get("htoteff");
			effFile = TFile::Open(effbase+"LbeffvscosThetaB_DD.root");
			effDDB  = (TH1F *)effFile->Get("htot_nodet_eff");
			effFile = TFile::Open(effbase+"LbeffvscosThetaB_LL.root");
			effLLB  = (TH1F *)effFile->Get("htot_nodet_eff");
		}
		else
		{

			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaL_vs_q2_DD.root");
			TH2F * effDD2D  = (TH2F *)effFile->Get("htot_eff");
			effDD = (TH1F*)GetSliceX(effDD2D,(q2max[i]+q2min[i])/2.);
			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaL_vs_q2_LL.root");
			TH2F * effLL2D  = (TH2F *)effFile->Get("htot_eff");
			effLL = (TH1F*)GetSliceX(effLL2D,(q2max[i]+q2min[i])/2.);
			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaB_vs_q2_DD.root");
			TH2F * effDDB2D  = (TH2F *)effFile->Get("hupper_eff");
			effDDB = (TH1F*)GetSliceX(effDDB2D,(q2max[i]+q2min[i])/2.);
			effFile = TFile::Open(effbase+"Lbeff2D_cosThetaB_vs_q2_LL.root");
			TH2F * effLLB2D  = (TH2F *)effFile->Get("hupper_eff");
			effLLB = (TH1F*)GetSliceX(effLLB2D,(q2max[i]+q2min[i])/2.);
		}

		ceff->cd();

		/**                    FIT EFFICIENCY                  **/

		RooDataHist * hLL = new RooDataHist("hLL","hLL",*cosThetaL,effLL);
		RooDataHist * hDD = new RooDataHist("hDD","hDD",*cosThetaL,effDD);
		RooRealVar * c1LL = new RooRealVar("c1LL","",0.,-1.,1);
		RooRealVar * c1DD = new RooRealVar("c1DD","",0.,-1.,1);
		RooRealVar * c2LL = new RooRealVar("c2LL","",0.,-1.,1);
		RooRealVar * c2DD = new RooRealVar("c2DD","",0.,-1.,1);
		TString effLLstr = "(1 + c1LL*cosThetaL + c2LL*TMath::Power(cosThetaL,2))";
		TString effDDstr = "(1 + c1DD*cosThetaL + c2DD*TMath::Power(cosThetaL,2))";
		RooAbsPdf * effLLpdf = new RooGenericPdf("effLLpdf", "", effLLstr, RooArgSet(*cosThetaL, *c1LL, *c2LL));
		RooAbsPdf * effDDpdf = new RooGenericPdf("effDDpdf", "", effDDstr, RooArgSet(*cosThetaL, *c1DD, *c2DD));
		effLLpdf->fitTo(*hLL,PrintLevel(-1));
		effDDpdf->fitTo(*hDD,PrintLevel(-1));
		fixParams(effLLpdf,cosThetaL);
		fixParams(effDDpdf,cosThetaL);	

		RooDataHist * hLLB = new RooDataHist("hLLB","hLLB",*cosThetaB,effLLB);
		RooDataHist * hDDB = new RooDataHist("hDDB","hDDB",*cosThetaB,effDDB);
		RooRealVar * cB1LL = new RooRealVar("cB1LL","",0,-1.,1);
		RooRealVar * cB1DD = new RooRealVar("cB1DD","",0,-1.,1);
		RooRealVar * cB2LL = new RooRealVar("cB2LL","",0,-1.,1);
		RooRealVar * cB2DD = new RooRealVar("cB2DD","",0,-1.,1);
		TString effLLBstr = "(1 + cB1LL*cosThetaB + cB2LL*TMath::Power(cosThetaB,2))";
		TString effDDBstr = "(1 + cB1DD*cosThetaB + cB2DD*TMath::Power(cosThetaB,2))";
		RooAbsPdf * effLLpdfB = new RooGenericPdf("effLLpdfB", "", effLLBstr, RooArgSet(*cosThetaB, *cB1LL, *cB2LL));
		RooAbsPdf * effDDpdfB = new RooGenericPdf("effDDpdfB", "", effDDBstr, RooArgSet(*cosThetaB, *cB1DD, *cB2DD));
		effLLpdfB->fitTo(*hLLB,PrintLevel(-1));
		effDDpdfB->fitTo(*hDDB,PrintLevel(-1));
		fixParams(effLLpdfB,cosThetaB);
		fixParams(effDDpdfB,cosThetaB);

		//cout << q2min[i] << " - " << q2max[i] << " LL cosThetaL -> " << c1LL->getVal() << "  " << c2LL->getVal() << endl;
		//cout << q2min[i] << " - " << q2max[i] << " DD cosThetaL -> " << c1DD->getVal() << "  " << c2DD->getVal() << endl;
		//cout << q2min[i] << " - " << q2max[i] << " LL cosThetaB -> " << cB1LL->getVal() << "  " << cB2LL->getVal() << endl;
		//cout << q2min[i] << " - " << q2max[i] << " DD cosThetaB -> " << cB1DD->getVal() << "  " << cB2DD->getVal() << endl;


		if(printeff) {
			GetFrame(cosThetaL, hLL,effLLpdf,"-nochi2",0,NULL,0,"cos#theta_{l}","Tot. eff.")->Draw();
			ceff->Print("DDeffFit"+q2name+".pdf");
			GetFrame(cosThetaL, hDD,effDDpdf,"-nochi2",0,NULL,0,"cos#theta_{l}","Tot. eff.")->Draw();
			ceff->Print("LLeffFit"+q2name+".pdf");
			GetFrame(cosThetaB, hLLB,effLLpdfB,"-nochi2",0,NULL,0,"cos#theta_{#Lambda}","Tot. eff.")->Draw();
			ceff->Print("DDeffFitB"+q2name+".pdf");
			GetFrame(cosThetaB, hDDB,effDDpdfB,"-nochi2",0,NULL,0,"cos#theta_{#Lambda}","Tot. eff.")->Draw();
			ceff->Print("LLeffFitB"+q2name+".pdf"); }

			/**                    FIT AFB                  **/


			afb->setVal(0);
			afbB->setVal(0);
			fL->setVal(0.7);

			TString LLnorm = "1./( 1. + (2./3.)*afb*c1LL + (2./5.)*c2LL - (1./5.)*c2LL*fL )*"+effLLstr;
			TString DDnorm = "1./( 1. + (2./3.)*afb*c1DD + (2./5.)*c2DD - (1./5.)*c2DD*fL )*"+effDDstr;
			RooAbsPdf * corrPdfLL = new RooGenericPdf(Form("corrPdfLL_%i",i),LLnorm+"*"+afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1LL, *c2LL) );
			RooAbsPdf * corrPdfDD = new RooGenericPdf(Form("corrPdfDD_%i",i),DDnorm+"*"+afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1DD, *c2DD) );

			TString LLnormB = "1./( (2./3.)*( 2*afbB*cB1LL + cB2LL + 3.) )*"+effLLBstr;
			TString DDnormB = "1./( (2./3.)*( 2*afbB*cB1DD + cB2DD + 3.) )*"+effDDBstr;
			RooAbsPdf * corrPdfLLB = new RooGenericPdf(Form("corrPdfLLB_%i",i),LLnormB+"*"+afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1LL, *cB2LL) );
			RooAbsPdf * corrPdfDDB = new RooGenericPdf(Form("corrPdfDDB_%i",i),DDnormB+"*"+afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1DD, *cB2DD) );

			TCut cutLL = CutsDef::LLcut + (TCut)curq2cut;
			TCut cutDD = CutsDef::DDcut + (TCut)curq2cut;

			if(dodata=="genMC")
			{
				corrPdfLLB = new RooGenericPdf("corrPdfLL",afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1LL, *cB2LL) );
				corrPdfDDB = new RooGenericPdf("corrPdfDD",afbBpdf,RooArgSet(*cosThetaB, *afbB, *cB1DD, *cB2DD) );
				corrPdfLL = new RooGenericPdf("corrPdfLL",afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1LL, *c2LL) );
				corrPdfDD = new RooGenericPdf("corrPdfDD",afbLpdf,RooArgSet(*cosThetaL, *afb, *fL, *c1DD, *c2DD) );
				cutLL = (TCut)curq2cut;
				cutDD = (TCut)curq2cut;
			}

			Analysis * anaLL = new Analysis(Form("LL_mass_%i",i),"Lb",data,&cutLL,MM);
			anaLL->AddVariable(cosThetaL);
			anaLL->AddVariable(cosThetaB);
			anaLL->AddVariable("J_psi_1S_MM");
			if(dodata!="data") anaLL->SetWeight(wstr);
			RooDataSet * dataLL = anaLL->GetDataSet("-recalc-docuts");

			Analysis * anaDD = new Analysis(Form("DD_mass_%i",i),"Lb",data,&cutDD,MM);
			anaDD->AddVariable(cosThetaL);
			anaDD->AddVariable(cosThetaB);
			anaDD->AddVariable("J_psi_1S_MM");
			if(dodata!="data") anaDD->SetWeight(wstr);
			RooDataSet * dataDD = anaDD->GetDataSet("-recalc-docuts");

			RooDataSet * sdataDD, * sdataLL;

			if(dodata=="data")
			{
				sdataLL = anaLL->CalcSweight("",massModel.c_str(),"Exp");

				if(printSw) {
					GetFrame(MM,NULL,sdataLL,"-nochi2",30,NULL,0,"M(#Lambda#mu#mu) (MeV/c^{2})")->Draw();
					ceff->Print("Mass_LL_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,sdataLL,"-nochi2",6,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_LL_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,dataLL,"-nochi2",6,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_LL_"+q2name+".pdf");
				}

				sdataDD = anaDD->CalcSweight("",massModel.c_str(),"Exp");

				if(printSw) {
					GetFrame(MM,NULL,sdataDD,"-nochi2",30,NULL,0,"M(#Lambda#mu#mu) (MeV/c^{2})")->Draw();
					ceff->Print("Mass_DD_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,sdataDD,"-nochi2",10,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_DD_sWeighted"+q2name+".pdf");
					GetFrame(cosThetaL,NULL,dataDD,"-nochi2",10,NULL,0,"cos#theta_{l}")->Draw();
					ceff->Print("cosThetaL_DD_"+q2name+".pdf");
				}
			}		
			else { sdataLL = dataLL; sdataDD = dataDD; }

			histFile->cd();
			TTree * LLTree = (TTree*)sdataLL->tree();
			LLTree->SetName(Form("treeLL_%i",i));
			LLlist->Add(LLTree);
			TTree * DDTree = (TTree*)sdataDD->tree();
			DDTree->SetName(Form("treeDD_%i",i));
			DDlist->Add(DDTree);


			// CREATE COMBINED DATASET
			RooDataSet * combData;
			if(dodata=="data") combData = new RooDataSet(Form("combData_%i",i),"combined data",RooArgSet(*cosThetaL,*cosThetaB,*nsig_sw),Index(*samples),Import("DD",*sdataDD),Import("LL",*sdataLL),WeightVar("nsig_sw"));
			else combData = new RooDataSet(Form("combData_%i",i),"combined data",RooArgSet(*cosThetaL,*cosThetaB,*MCweight),Index(*samples),Import("DD",*sdataDD),Import("LL",*sdataLL),WeightVar(wstr));


			// FIT COS LEPTON
			RooSimultaneous * combModel = new RooSimultaneous(Form("combModel_%i",i),"",*samples);
			combModel->addPdf(*corrPdfLL,"LL");
			combModel->addPdf(*corrPdfDD,"DD");

			combModel->fitTo(*combData,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));

			if(fitsingle) corrPdfLL->fitTo(*sdataLL,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));
			GetFrame(cosThetaL,corrPdfLL,sdataLL,"-sumW2err-nochi2-noCost",6,NULL,0,"cos#theta_{l}")->Draw();
			ceff->Print("Afb_LL_"+q2name+".pdf");
			if(fitsingle) corrPdfDD->fitTo(*sdataDD,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));		
			GetFrame(cosThetaL,corrPdfDD,sdataDD,"-sumW2err-nochi2-noCost",10,NULL,0,"cos#theta_{l}")->Draw();
			ceff->Print("Afb_DD_"+q2name+".pdf");

			Afb_vs_q2->SetPoint(i,(q2max[i] + q2min[i])/2.,afb->getVal());
			Afb_vs_q2->SetPointError(i,(q2max[i] - q2min[i])/2.,afb->getError());
			fL_vs_q2->SetPoint(i,(q2max[i] + q2min[i])/2.,fL->getVal());
			fL_vs_q2->SetPointError(i,(q2max[i] - q2min[i])/2.,fL->getError());
				
			// FIT COS HADRON
			RooSimultaneous * combModelB = new RooSimultaneous(Form("combModelB_%i",i),"",*samples);
			combModelB->addPdf(*corrPdfLLB,"LL");
			combModelB->addPdf(*corrPdfDDB,"DD");

			combModelB->fitTo(*combData,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));

			if(fitsingle) corrPdfLLB->fitTo(*sdataLL,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));
			GetFrame(cosThetaB,corrPdfLLB,sdataLL,"-sumW2err-nochi2-noCost",6,NULL,0,"cos#theta_{#Lambda}")->Draw();
			ceff->Print("AfbB_LL_"+q2name+".pdf");
			if(fitsingle) corrPdfDDB->fitTo(*sdataDD,PrintLevel(-1),Verbose(kFALSE),SumW2Error(kTRUE));		
			GetFrame(cosThetaB,corrPdfDDB,sdataDD,"-sumW2err-nochi2-noCost",10,NULL,0,"cos#theta_{#Lambda}")->Draw();
			ceff->Print("AfbB_DD_"+q2name+".pdf");

			AfbB_vs_q2->SetPoint(i,(q2max[i] + q2min[i])/2.,afbB->getVal());
			AfbB_vs_q2->SetPointError(i,(q2max[i] - q2min[i])/2.,afbB->getError());
			
			cout << endl << fixed << setprecision(6) << "AfbB = " << afbB->getVal() << " +/- " << afbB->getError() << endl;
			cout << "Afb = " << afb->getVal() << " +/- " << afb->getError() << endl;
			cout << "fL = " << fL->getVal() << " +/- " << fL->getError() << endl;
			cout << endl;
			cout << "------------------------ FELDMAN AND COUSINS ------------------------" << endl;

			vector < RooDataSet * > datas;
			vector < RooAbsPdf * > pdfs, pdfsB;
			vector < TString > cat;
			cat.push_back("LL");
			cat.push_back("DD");
			datas.push_back(sdataLL);
			datas.push_back(sdataDD);

			RooArgSet * origPars = new RooArgSet();
			origPars->add(*origafb);
			origPars->add(*origfL);
			
			pdfs.push_back(corrPdfLL);
			pdfs.push_back(corrPdfDD);

			vector< double > afb_err, afbB_err, fL_err;
/*
			double fLval = fL->getVal(), fLerr = fL->getError();
			FeldmanCousins * FC = new FeldmanCousins(q2name,cat,datas,pdfs,cosThetaL,afb,"nsig_sw");
			//FC->SetNPointsToScan(20);
			//FC->SetNExp(1000);
			if(q2min[i]==18) afb_err = FC->ExtractLimits(origPars,-0.3,0.3);
			else if( (afb->getVal()-1.4*afb->getError()) > -1 && (afb->getVal()+1.4*afb->getError()) < 1 )
		       afb_err = FC->ExtractLimits(origPars,afb->getVal()-1.4*afb->getError(),afb->getVal()+1.4*afb->getError());
		    else afb_err = FC->ExtractLimits(origPars,-0.4,0.4);

			//FeldmanCousins * FCfL = new FeldmanCousins(q2name,cat,datas,pdfs,cosThetaL,fL,"nsig_sw");
			//if(q2min[i]==11) fL_err = FCfL->ExtractLimits(origPars,0.,0.6);
			//else if (q2min[i]==18) fL_err = FCfL->ExtractLimits(origPars,0.75,0.992);
			//( (fLval-1.3*fLerr) > 0 && (fLval+1.3*fLerr) <= 1 )
			//else fL_err = FCfL->ExtractLimits(origPars,fLval-1.3*fLerr,fLval+1.3*fLerr);

			afb_errs.push_back(afb_err);
			//fL_errs.push_back(fL_err);

 			RooArgSet * origParsB = new RooArgSet();
			origParsB->add(*origafbB);
			pdfsB.push_back(corrPdfLLB);
			pdfsB.push_back(corrPdfDDB);

			FeldmanCousins * FCB = new FeldmanCousins(q2name,cat,datas,pdfsB,cosThetaB,afbB,"nsig_sw");
			if( (afbB->getVal()-1.5*afbB->getError()) > -1 && (afbB->getVal()+1.5*afbB->getError()) < 1 )
			   afbB_err = FCB->ExtractLimits(origParsB,afbB->getVal()-1.5*afbB->getError(),afbB->getVal()+1.5*afbB->getError());
			else afbB_err = FCB->ExtractLimits(origParsB,-0.4,0.4);

			afbB_errs.push_back(afbB_err);
*/
			delete effDD;
			delete effLL;
			delete effLLB;
			delete effDDB;
	}

	cDD->Print("DDeff.pdf");
	cLL->Print("LLeff.pdf");
	cDDB->Print("DDBeff.pdf");
	cLLB->Print("LLBeff.pdf");


	Afb_vs_q2->GetXaxis()->SetTitle("q^{2}");
	Afb_vs_q2->GetYaxis()->SetTitle("Afb");
	Afb_vs_q2->SetMaximum(1);
	Afb_vs_q2->SetMinimum(-1);
	Afb_vs_q2->Draw("AP");
	ceff->Print("Afb_vs_q2.pdf");
	AfbB_vs_q2->GetXaxis()->SetTitle("q^{2}");
	AfbB_vs_q2->GetYaxis()->SetTitle("AfbB");
	AfbB_vs_q2->SetMaximum(1);
	AfbB_vs_q2->SetMinimum(-1);
	AfbB_vs_q2->Draw("AP");
	ceff->Print("AfbB_vs_q2.pdf");
	fL_vs_q2->GetXaxis()->SetTitle("q^{2}");
	fL_vs_q2->GetYaxis()->SetTitle("fL");
	fL_vs_q2->Draw("AP");
	ceff->Print("fL_vs_q2.pdf");

	for(int bb = 0; bb < Afb_vs_q2->GetN(); bb++)
	{
		double qq, qqerr, afbv, afbBv, fLv;
		Afb_vs_q2->GetPoint(bb,qq,afbv);
		qqerr = Afb_vs_q2->GetErrorX(bb);
		AfbB_vs_q2->GetPoint(bb,qq,afbBv);
		fL_vs_q2->GetPoint(bb,qq,fLv);
		cout << fixed << setprecision(1) << qq-qqerr << " - " << qq+qqerr;
		cout << fixed << setprecision(4); 
		//cout << " & $" << afbv << "_{-" << TMath::Abs(afb_errs[bb][0] - afbv) << "}^{+" << TMath::Abs(afb_errs[bb][1] - afbv)  << "} \\text{(stat)} \\pm \\text{(sys)}$ ";
		//cout << " & $" << afbBv << "_{-" << TMath::Abs(afbB_errs[bb][0] - afbBv) << "}^{+" << TMath::Abs(afbB_errs[bb][1]-afbBv) << "} \\text{(stat)} \\pm \\text{(sys)}$ " ;
		//cout << " & $" << fLv << "_{-" << TMath::Abs(fL_errs[bb][0] - fLv) << "}^{+" << TMath::Abs(fL_errs[bb][1] - fLv)  << "} \\text{(stat)} \\pm \\text{(sys)}$ ";
		cout << "  \\\\ " << endl;
	}

	histFile->cd();
	TTree * finalLLtree = (TTree*)TTree::MergeTrees(LLlist);
	TTree * finalDDtree = (TTree*)TTree::MergeTrees(DDlist);
	finalLLtree->SetName("LL_data");
	finalDDtree->SetName("DD_data");
	finalLLtree->Write();
	finalDDtree->Write();

	delete ceff;
	histFile->Write();
	delete histFile;

	}
Beispiel #26
0
void rf104_classfactory()
{
   // W r i t e   c l a s s   s k e l e t o n   c o d e
   // --------------------------------------------------

   // Write skeleton p.d.f class with variable x,a,b
   // To use this class,
   //    - Edit the file MyPdfV1.cxx and implement the evaluate() method in terms of x,a and b
   //    - Compile and link class with '.x MyPdfV1.cxx+'
   //
   RooClassFactory::makePdf("MyPdfV1","x,A,B") ;


   // W i t h   a d d e d   i n i t i a l   v a l u e   e x p r e s s i o n
   // ---------------------------------------------------------------------

   // Write skeleton p.d.f class with variable x,a,b and given formula expression
   // To use this class,
   //    - Compile and link class with '.x MyPdfV2.cxx+'
   //
   RooClassFactory::makePdf("MyPdfV2","x,A,B","","A*fabs(x)+pow(x-B,2)") ;


   // W i t h   a d d e d   a n a l y t i c a l   i n t e g r a l   e x p r e s s i o n
   // ---------------------------------------------------------------------------------

   // Write skeleton p.d.f class with variable x,a,b, given formula expression _and_
   // given expression for analytical integral over x
   // To use this class,
   //    - Compile and link class with '.x MyPdfV3.cxx+'
   //
   RooClassFactory::makePdf("MyPdfV3","x,A,B","","A*fabs(x)+pow(x-B,2)",kTRUE,kFALSE,
            "x:(A/2)*(pow(x.max(rangeName),2)+pow(x.min(rangeName),2))+(1./3)*(pow(x.max(rangeName)-B,3)-pow(x.min(rangeName)-B,3))") ;



   // U s e   i n s t a n c e   o f   c r e a t e d   c l a s s
   // ---------------------------------------------------------

   // Compile MyPdfV3 class (only when running in CINT)
   gROOT->ProcessLineSync(".x MyPdfV3.cxx+") ;

   // Create instance of MyPdfV3 class
   RooRealVar a("a","a",1) ;
   RooRealVar b("b","b",2,-10,10) ;
   RooRealVar y("y","y",-10,10);
   MyPdfV3 pdf("pdf","pdf",y,a,b) ;

   // Generate toy data from pdf and plot data and p.d.f on frame
   RooPlot* frame1 = y.frame(Title("Compiled class MyPdfV3")) ;
   RooDataSet* data = pdf.generate(y,1000) ;
   pdf.fitTo(*data) ;
   data->plotOn(frame1) ;
   pdf.plotOn(frame1) ;


   // -----------------------------------------------------------------
   // C o m p i l e d   v e r s i o n   o f   e x a m p l e   r f 1 0 3
   // =================================================================

   // Declare observable x
   RooRealVar x("x","x",-20,20) ;

   // The RooClassFactory::makePdfInstance() function performs code writing, compiling, linking
   // and object instantiation in one go and can serve as a straight replacement of RooGenericPdf

   RooRealVar alpha("alpha","alpha",5,0.1,10) ;
   RooAbsPdf* genpdf = RooClassFactory::makePdfInstance("GenPdf","(1+0.1*fabs(x)+sin(sqrt(fabs(x*alpha+0.1))))",RooArgSet(x,alpha)) ;

   // Generate a toy dataset from the interpreted p.d.f
   RooDataSet* data2 = genpdf->generate(x,50000) ;

   // Fit the interpreted p.d.f to the generated data
   genpdf->fitTo(*data2) ;

   // Make a plot of the data and the p.d.f overlaid
   RooPlot* frame2 = x.frame(Title("Compiled version of pdf of rf103")) ;
   data2->plotOn(frame2) ;
   genpdf->plotOn(frame2) ;

   // Draw all frames on a canvas
   TCanvas* c = new TCanvas("rf104_classfactory","rf104_classfactory",800,400) ;
   c->Divide(2) ;
   c->cd(1) ; gPad->SetLeftMargin(0.15) ; frame1->GetYaxis()->SetTitleOffset(1.4) ; frame1->Draw() ;
   c->cd(2) ; gPad->SetLeftMargin(0.15) ; frame2->GetYaxis()->SetTitleOffset(1.4) ; frame2->Draw() ;

}
Beispiel #27
0
void MakePlots(RooWorkspace* ws){

  // Here we make plots of the discriminating variable (invMass) after the fit
  // and of the control variable (isolation) after unfolding with sPlot.
  std::cout << "make plots" << std::endl;

  // make our canvas
  TCanvas* cdata = new TCanvas("sPlot","sPlot demo", 400, 600);
  cdata->Divide(1,3);

  // get what we need out of the workspace
  RooAbsPdf* model = ws->pdf("model");
  RooAbsPdf* zModel = ws->pdf("zModel");
  RooAbsPdf* qcdModel = ws->pdf("qcdModel");

  RooRealVar* isolation = ws->var("isolation");
  RooRealVar* invMass = ws->var("invMass");

  // note, we get the dataset with sWeights
  RooDataSet* data = (RooDataSet*) ws->data("dataWithSWeights");

  // this shouldn't be necessary, need to fix something with workspace
  // do this to set parameters back to their fitted values.
  model->fitTo(*data, Extended() );

  //plot invMass for data with full model and individual componenets overlayed
  //  TCanvas* cdata = new TCanvas();
  cdata->cd(1);
  RooPlot* frame = invMass->frame() ; 
  data->plotOn(frame ) ; 
  model->plotOn(frame) ;   
  model->plotOn(frame,Components(*zModel),LineStyle(kDashed), LineColor(kRed)) ;   
  model->plotOn(frame,Components(*qcdModel),LineStyle(kDashed),LineColor(kGreen)) ;   
    
  frame->SetTitle("Fit of model to discriminating variable");
  frame->Draw() ;
 

  // Now use the sWeights to show isolation distribution for Z and QCD.  
  // The SPlot class can make this easier, but here we demonstrait in more
  // detail how the sWeights are used.  The SPlot class should make this 
  // very easy and needs some more development.

  // Plot isolation for Z component.  
  // Do this by plotting all events weighted by the sWeight for the Z component.
  // The SPlot class adds a new variable that has the name of the corresponding
  // yield + "_sw".
  cdata->cd(2);

  // create weightfed data set 
  RooDataSet * dataw_z = new RooDataSet(data->GetName(),data->GetTitle(),data,*data->get(),0,"zYield_sw") ;

  RooPlot* frame2 = isolation->frame() ; 
  dataw_z->plotOn(frame2, DataError(RooAbsData::SumW2) ) ; 
    
  frame2->SetTitle("isolation distribution for Z");
  frame2->Draw() ;

  // Plot isolation for QCD component.  
  // Eg. plot all events weighted by the sWeight for the QCD component.
  // The SPlot class adds a new variable that has the name of the corresponding
  // yield + "_sw".
  cdata->cd(3);
  RooDataSet * dataw_qcd = new RooDataSet(data->GetName(),data->GetTitle(),data,*data->get(),0,"qcdYield_sw") ;
  RooPlot* frame3 = isolation->frame() ; 
  dataw_qcd->plotOn(frame3,DataError(RooAbsData::SumW2) ) ; 
    
  frame3->SetTitle("isolation distribution for QCD");
  frame3->Draw() ;

  //  cdata->SaveAs("SPlot.gif");

}
void statTest(double mu_pe, double mu_hyp, ModelConfig *mc , RooDataSet *data ){

    int nToyMC = 5;
    // set roofit seed
    RooRandom::randomGenerator()->SetSeed();

    cout << endl;
    cout << endl;
    cout << "Will generate " << nToyMC << " pseudo-experiments for : " << endl;
    cout << " - mu[pseudo-data] = " << mu_pe  << endl;
    cout << " - mu[stat-test]   = " << mu_hyp << endl;
    cout << endl;

    // Check number of POI (for Wald approx)
    RooArgSet *ParamOfInterest = (RooArgSet*) mc->GetParametersOfInterest();
    int nPOI = ParamOfInterest->getSize();
    if(nPOI>1){
      cout <<"not sure what to do with other parameters of interest, but here are their values"<<endl;
      mc->GetParametersOfInterest()->Print("v");
    }
    RooRealVar* firstPOI    = (RooRealVar*) ParamOfInterest->first(); 
    RooAbsPdf *simPdf = (mc->GetPdf());
    //PrintAllParametersAndValues( *mc->GetGlobalObservables() );
    //PrintAllParametersAndValues( *mc->GetObservables() );
    firstPOI->setVal(0.0); // FIXME

    //simPdf->fitTo( *data, Hesse(kTRUE), Minos(kTRUE), PrintLevel(1) );
    simPdf->fitTo( *data );

    // set up the sampler
    ToyMCSampler sampler;
    sampler.SetPdf(*mc->GetPdf());
    sampler.SetObservables(*mc->GetObservables());
    sampler.SetNToys(nToyMC);
    sampler.SetGlobalObservables(*mc->GetGlobalObservables());
    sampler.SetParametersForTestStat(*mc->GetParametersOfInterest());
    RooArgSet* poiset = dynamic_cast<RooArgSet*>(ParamOfInterest->Clone());


    // only unconditional fit
    MinNLLTestStat *minNll = new MinNLLTestStat(*mc->GetPdf());
    minNll->EnableDetailedOutput(true);
    sampler.AddTestStatistic(minNll);

    // enable PROOF if desired
    //ProofConfig pc(*w, 8, "workers=8", kFALSE);
    //sampler.SetProofConfig(&pc);

    // evaluate the test statistics - this is where most of our time will be spent
    cout << "Generating " << nToyMC << " toys...this will take a few minutes" << endl;
    TStopwatch *mn_t = new TStopwatch; 
    mn_t->Start();
    RooDataSet* sd = sampler.GetSamplingDistributions(*poiset);
    cout << "Toy generation complete :" << endl;
    // stop timing
    mn_t->Stop();
    cout << " total CPU time: " << mn_t->CpuTime() << endl;
    cout << " total real time: " << mn_t->RealTime() << endl; 

    // now sd contains all information about our test statistics, including detailed output
    // we might eg. want to explore the results either directly, or first converting to a TTree
    // do the conversion
    TFile f("mytoys.root", "RECREATE");
    TTree *toyTree = RooStats::GetAsTTree("toyTree", "TTree created from test statistics", *sd);
    // save result to file, but in general do whatever you like
    f.cd();
    toyTree->Write();
    f.Close();
/*
    TFile* tmpFile = new TFile("mytoys.root","READ");
    TTree* myTree = (TTree*)tmpFile->Get("toyTree");

    // get boundaries for histograms
    TIter nextLeaf( (myTree->GetListOfLeaves())->MakeIterator() );
    TObject* leafObj(0);
    map<TString, float> xMaxs;
    map<TString, float> xMins;
    for(int i(0); i<myTree->GetEntries(); i++) {
      myTree->GetEntry(i);
      nextLeaf = ( (myTree->GetListOfLeaves())->MakeIterator() );
      while( (leafObj = nextLeaf.Next()) ) {
        TString name(leafObj->GetName());
        float value(myTree->GetLeaf( leafObj->GetName() )->GetValue());
        if(value > xMaxs[name]) { xMaxs[name] = value; }
        if(value < xMins[name]) { xMins[name] = value; }
      } // loop over leaves
    } // loop over tree entries

    // plot everything in the tree
    myTree->GetEntry(0);
    nextLeaf = ( (myTree->GetListOfLeaves())->MakeIterator() );
    leafObj = 0;
    // make a histogram per leaf
    map<TString, TH1F*> hists;
    myTree->GetEntry(0);
    while( (leafObj = nextLeaf.Next()) ) {
      if(!leafObj) { continue; }
      //cout << leafObj->GetName() << endl;
      TString name(leafObj->GetName());
      // special ones : fit related things
      if(name.Contains("covQual"))   { hists[name] = new TH1F(name,name,5,0,5); continue; }
      if(name.Contains("fitStatus")) { hists[name] = new TH1F(name,name,5,0,5); continue; }
      int nbin(500); 
      float histMin( xMins[name] - 0.1*fabs(xMins[name]) ); 
      float histMax( xMaxs[name] + 0.1*fabs(xMaxs[name]) );
      if(name.Contains("ATLAS_norm")) { // floating normalization factors
        histMin = 0; histMax = 10;
      }
      else if(name.Contains("gamma_stat")) { // statistical nus param
        if(name.Contains("globObs")) {  // get custom range for sampling
          histMin = int( xMins[name] - 0.1*fabs(xMins[name]) );
          histMax = int( xMaxs[name] + 0.1*fabs(xMaxs[name]) );
        } // use small range for pull and error
        else { nbin = 100; histMin = 0.0; histMax = 2.0; }
      }
      else if(name.Contains("_err")) { // errors on nus param
        nbin = 100; histMin = 0.0; histMax = 2.0;
      }
      else if(name.Contains("fitCond") || name.Contains("fitUncond") || name.Contains("globObs")) { // fit pulls
        nbin = 500; histMin = -5; histMax = 5;
      }
      hists[name] = new TH1F(name,name,nbin,histMin,histMax);
    } // loop over leaves to declare histos

    // loop over entries and fill histograms
    for(int i(0); i<myTree->GetEntries(); i++) {
      myTree->GetEntry(i);
      nextLeaf = ( (myTree->GetListOfLeaves())->MakeIterator() );
      while( (leafObj = nextLeaf.Next()) ) {
        TString name(leafObj->GetName());
        if(hists.find(name) == hists.end()) { continue; }
        hists[name]->Fill( myTree->GetLeaf( leafObj->GetName() )->GetValue() );
      } // loop over leaves
    } // loop over tree entries

    // overflow and underflow
    for(map<TString,TH1F*>::iterator ihist(hists.begin()); ihist!=hists.end(); ihist++) {
      if(ihist->second->GetBinContent(0)>0) {
        ihist->second->SetBinContent(1, ihist->second->GetBinContent(0) + ihist->second->GetBinContent(1) );
        // fix err
      }
      int nBinx = ihist->second->GetNbinsX();
      if(ihist->second->GetBinContent(nBinx)>0) {
        ihist->second->SetBinContent(nBinx-1, ihist->second->GetBinContent(nBinx) + ihist->second->GetBinContent(nBinx-1) );
        // fix err
      }
    }

    // save the results
    TString dirName(OutputDir+"/PlotsStatisticalTest/GlobalFit");
    if(drawPlots) {
      system(TString("mkdir -vp "+dirName));
    }
    TCanvas* canvas = new TCanvas("pulls");
    TLegend *leg = new TLegend(0.67, 0.64, 0.87, 0.86);
    LegendStyle(leg);
    for(map<TString,TH1F*>::iterator ihist(hists.begin()); ihist!=hists.end(); ihist++) {
      if( (ihist->first).Contains("fitCond_") ) { continue; } // skip unconditional fit - get it explicitly
      canvas->Clear();
      leg->Clear();
      TString niceName(ihist->first);
      niceName.ReplaceAll("fitUncond_","");
      //niceName.ReplaceAll("SD_TS0_",""); // not good if have multiple test statistics
      // conditional fit information
      ihist->second->SetLineColor(kGray+2);
      ihist->second->SetTitle(niceName);
      ihist->second->SetLineStyle(kSolid);
      ihist->second->SetLineWidth(2);
      if((ihist->first).Contains("fit") && !(ihist->first).Contains("_err") 
          && !(ihist->first).Contains("Qual") && !(ihist->first).Contains("Status")) {
        ihist->second->Rebin(4);
      }

//      ihist->second->GetXaxis()->SetTitle("");
//      ihist->second->GetYaxis()->SetTitle("");

      if(niceName.Contains("globObs")) {
        leg->AddEntry( ihist->second, "Sampling", "l" ); // add value of mu
      } else {
        leg->AddEntry( ihist->second, "Unconditional Fit", "l" ); // add value of mu
      }
      TString condName(ihist->first);
      condName.ReplaceAll("fitUncond","fitCond");
      // uncomditional fit information
      if(hists.find(condName) != hists.end() && condName != ihist->first) {
        hists[condName]->SetLineColor(kGray+2);
        hists[condName]->SetLineStyle(kDashed);
        hists[condName]->SetLineWidth(2);
        if(!(ihist->first).Contains("_err")) { hists[condName]->Rebin(4); }
        leg->AddEntry( hists[condName], "Conditional Fit", "l" );
        if( hists[condName]->GetMaximum() > ihist->second->GetMaximum() ) {
          ihist->second->SetMaximum( hists[condName]->GetMaximum() );
        }
      }
      ihist->second->SetMaximum( 1.2 * ihist->second->GetMaximum() );
      canvas->cd();
      ihist->second->Draw();
      leg->Draw();
      if(hists[condName] && condName != ihist->first) { hists[condName]->Draw("same"); }
      if(drawPlots) { 
        canvas->Print(dirName+"/"+niceName+".eps");
        canvas->Print(dirName+"/"+niceName+".png");
      }

      MainDirStatTest->cd();
      canvas->Write();
      gROOT->cd();
    }

*/

return;
}
void StandardBayesianNumericalDemo(const char* infile = "",
                                   const char* workspaceName = "combined",
                                   const char* modelConfigName = "ModelConfig",
                                   const char* dataName = "obsData") {

   // option definitions 
   double confLevel = optBayes.confLevel; 
   TString integrationType = optBayes.integrationType;
   int nToys = optBayes.nToys; 
   bool scanPosterior = optBayes.scanPosterior; 
   int nScanPoints = optBayes.nScanPoints; 
   int intervalType = optBayes.intervalType;
   int  maxPOI =  optBayes.maxPOI;
   double  nSigmaNuisance = optBayes.nSigmaNuisance;
   


  /////////////////////////////////////////////////////////////
  // First part is just to access a user-defined file
  // or create the standard example file if it doesn't exist
  ////////////////////////////////////////////////////////////

   const char* filename = "";
   if (!strcmp(infile,"")) {
      filename = "results/example_combined_GaussExample_model.root";
      bool fileExist = !gSystem->AccessPathName(filename); // note opposite return code
      // if file does not exists generate with histfactory
      if (!fileExist) {
#ifdef _WIN32
         cout << "HistFactory file cannot be generated on Windows - exit" << endl;
         return;
#endif
         // Normally this would be run on the command line
         cout <<"will run standard hist2workspace example"<<endl;
         gROOT->ProcessLine(".! prepareHistFactory .");
         gROOT->ProcessLine(".! hist2workspace config/example.xml");
         cout <<"\n\n---------------------"<<endl;
         cout <<"Done creating example input"<<endl;
         cout <<"---------------------\n\n"<<endl;
      }

   }
   else
      filename = infile;

   // Try to open the file
   TFile *file = TFile::Open(filename);

   // if input file was specified byt not found, quit
   if(!file ){
      cout <<"StandardRooStatsDemoMacro: Input file " << filename << " is not found" << endl;
      return;
   }


  /////////////////////////////////////////////////////////////
  // Tutorial starts here
  ////////////////////////////////////////////////////////////

  // get the workspace out of the file
  RooWorkspace* w = (RooWorkspace*) file->Get(workspaceName);
  if(!w){
    cout <<"workspace not found" << endl;
    return;
  }

  // get the modelConfig out of the file
  ModelConfig* mc = (ModelConfig*) w->obj(modelConfigName);

  // get the modelConfig out of the file
  RooAbsData* data = w->data(dataName);

  // make sure ingredients are found
  if(!data || !mc){
    w->Print();
    cout << "data or ModelConfig was not found" <<endl;
    return;
  }

  /////////////////////////////////////////////
  // create and use the BayesianCalculator
  // to find and plot the 95% credible interval
  // on the parameter of interest as specified
  // in the model config

  // before we do that, we must specify our prior
  // it belongs in the model config, but it may not have
  // been specified
  RooUniform prior("prior","",*mc->GetParametersOfInterest());
  w->import(prior);
  mc->SetPriorPdf(*w->pdf("prior"));

  // do without systematics
  //mc->SetNuisanceParameters(RooArgSet() );
  if (nSigmaNuisance > 0) {
     RooAbsPdf * pdf = mc->GetPdf();
     assert(pdf);
     RooFitResult * res = pdf->fitTo(*data, Save(true), Minimizer(ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str()), Hesse(true),
                                     PrintLevel(ROOT::Math::MinimizerOptions::DefaultPrintLevel()-1) );

     res->Print();
     RooArgList nuisPar(*mc->GetNuisanceParameters());
     for (int i = 0; i < nuisPar.getSize(); ++i) {
        RooRealVar * v = dynamic_cast<RooRealVar*> (&nuisPar[i] );
        assert( v);
        v->setMin( TMath::Max( v->getMin(), v->getVal() - nSigmaNuisance * v->getError() ) );
        v->setMax( TMath::Min( v->getMax(), v->getVal() + nSigmaNuisance * v->getError() ) );
        std::cout << "setting interval for nuisance  " << v->GetName() << " : [ " << v->getMin() << " , " << v->getMax() << " ]" << std::endl;
     }
  }


  BayesianCalculator bayesianCalc(*data,*mc);
  bayesianCalc.SetConfidenceLevel(confLevel); // 95% interval

  // default of the calculator is central interval.  here use shortest , central or upper limit depending on input
  // doing a shortest interval might require a longer time since it requires a scan of the posterior function
  if (intervalType == 0)  bayesianCalc.SetShortestInterval(); // for shortest interval
  if (intervalType == 1)  bayesianCalc.SetLeftSideTailFraction(0.5); // for central interval
  if (intervalType == 2)  bayesianCalc.SetLeftSideTailFraction(0.); // for upper limit

  if (!integrationType.IsNull() ) {
     bayesianCalc.SetIntegrationType(integrationType); // set integrationType
     bayesianCalc.SetNumIters(nToys); // set number of ietrations (i.e. number of toys for MC integrations)
  }

  // in case of toyMC make a nnuisance pdf
  if (integrationType.Contains("TOYMC") ) {
    RooAbsPdf * nuisPdf = RooStats::MakeNuisancePdf(*mc, "nuisance_pdf");
    cout << "using TOYMC integration: make nuisance pdf from the model " << std::endl;
    nuisPdf->Print();
    bayesianCalc.ForceNuisancePdf(*nuisPdf);
    scanPosterior = true; // for ToyMC the posterior is scanned anyway so used given points
  }

  // compute interval by scanning the posterior function
  if (scanPosterior)
     bayesianCalc.SetScanOfPosterior(nScanPoints);

  RooRealVar* poi = (RooRealVar*) mc->GetParametersOfInterest()->first();
  if (maxPOI != -999 &&  maxPOI > poi->getMin())
    poi->setMax(maxPOI);


  SimpleInterval* interval = bayesianCalc.GetInterval();

  // print out the iterval on the first Parameter of Interest
  cout << "\n>>>> RESULT : " << confLevel*100 << "% interval on " << poi->GetName()<<" is : ["<<
    interval->LowerLimit() << ", "<<
    interval->UpperLimit() <<"] "<<endl;


  // make a plot
  // since plotting may take a long time (it requires evaluating
  // the posterior in many points) this command will speed up
  // by reducing the number of points to plot - do 50

  // ignore errors of PDF if is zero
  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::Ignore) ;

  
  cout << "\nDrawing plot of posterior function....." << endl;

  // always plot using numer of scan points
  bayesianCalc.SetScanOfPosterior(nScanPoints);

  RooPlot * plot = bayesianCalc.GetPosteriorPlot();
  plot->Draw();

}
Beispiel #30
0
//____________________________________
void DoSPlot(RooWorkspace* ws){
  std::cout << "Calculate sWeights" << std::endl;

  RooAbsPdf* model = ws->pdf("model");
  RooRealVar* nsig = ws->var("nsig");
  RooRealVar* nBbkg = ws->var("nBbkg");
  RooRealVar* nbkg = ws->var("nbkg");
  RooRealVar* nbkg2 = ws->var("nbkg2");
  RooDataSet* data = (RooDataSet*) ws->data("data");

  // fit the model to the data.
  model->fitTo(*data, Extended() );

  RooMsgService::instance().setSilentMode(true);

  // Now we use the SPlot class to add SWeights to our data set
  // based on our model and our yield variables
  RooStats::SPlot* sData = new RooStats::SPlot("sData","An SPlot",
					       *data, model, RooArgList(*nsig,*nBbkg,*nbkg,*nbkg2) );


  // Check that our weights have the desired properties

  std::cout << "Check SWeights:" << std::endl;

  std::cout << std::endl <<  "Yield of sig is " 
	    << nsig->getVal() << ".  From sWeights it is "
	    << sData->GetYieldFromSWeight("nsig") << std::endl;

  std::cout << std::endl <<  "Yield of Bbkg is " 
	    << nBbkg->getVal() << ".  From sWeights it is "
	    << sData->GetYieldFromSWeight("nBbkg") << std::endl;

  std::cout << std::endl <<  "Yield of bkg is " 
	    << nbkg->getVal() << ".  From sWeights it is "
	    << sData->GetYieldFromSWeight("nbkg") << std::endl;

  std::cout << std::endl <<  "Yield of bkg2 is " 
	    << nbkg2->getVal() << ".  From sWeights it is "
	    << sData->GetYieldFromSWeight("nbkg2") << std::endl;

  cout << endl;   cout << endl;   cout << endl;
  float sum20=0;
  float sum50=0;
  float sum100=0;
  float sum200=0;
  float sum300=0;
  float sum600=0;
  float sum900=0;
  float sum1200=0;
  float total=0;

  // saving weights into a file
  ofstream myfile;
  myfile.open ("weights.txt");
  // plot the weight event by event with the Sum of events values as cross-check
  for(Int_t i=0; i < data->numEntries(); i++) {
      //myfile << sData->GetSWeight(i,"nsig") << " " << sData->GetSWeight(i,"nBbkg") << " " << sData->GetSWeight(i,"nbkg") << " " << sData->GetSWeight(i,"nbkg2") << endl;  
      //myfile << sData->GetSWeight(i,"nsig") <<endl;
    myfile << (unsigned int) data->get(i)->getRealValue("run")
             << " " << (unsigned int) data->get(i)->getRealValue("event")
	   << " " << (float) data->get(i)->getRealValue("FourMu_Mass")
             << " " << sData->GetSWeight(i,"nsig")
             << endl;
     // std::cout << "nsig Weight   " << sData->GetSWeight(i,"nsig") 
     //		<< "   nBbkg Weight   " << sData->GetSWeight(i,"nBbkg")
     //		<< "   nbkg Weight   " << sData->GetSWeight(i,"nbkg")
     //		<< "   nbkg2 Weight  " << sData->GetSWeight(i,"nbkg2")
//		<< "   Total Weight   " << sData->GetSumOfEventSWeight(i) 
//		<< std::endl;
      total+=sData->GetSWeight(i,"nsig");         
      if(i<20) sum20+=sData->GetSWeight(i,"nsig");
      if(i<50) sum50+=sData->GetSWeight(i,"nsig");
      if(i<100) sum100+=sData->GetSWeight(i,"nsig");
      if(i<200) sum200+=sData->GetSWeight(i,"nsig");
      if(i<300) sum300+=sData->GetSWeight(i,"nsig");
      if(i<600) sum600+=sData->GetSWeight(i,"nsig");
      if(i<900) sum900+=sData->GetSWeight(i,"nsig");
      if(i<1200) sum1200+=sData->GetSWeight(i,"nsig");

    }
  myfile.close();

  std::cout << std::endl;

  std::cout<<"Sum of the sWeights is: "<<total<<std::endl;
  std::cout<<"Sum of the first 20 sWeights is: "<<sum20<<std::endl;
  std::cout<<"Sum of the first 50 sWeights is: "<<sum50<<std::endl;
  std::cout<<"Sum of the first 100 sWeights is: "<<sum100<<std::endl;
  std::cout<<"Sum of the first 200 sWeights is: "<<sum200<<std::endl;
  std::cout<<"Sum of the first 300 sWeights is: "<<sum300<<std::endl;
  std::cout<<"Sum of the first 600 sWeights is: "<<sum600<<std::endl;
  std::cout<<"Sum of the first 900 sWeights is: "<<sum900<<std::endl;
  std::cout<<"Sum of the first 1200 sWeights is: "<<sum1200<<std::endl;
  std::cout<<"Total # of events: "<<data->numEntries()<<std::endl;

  // import this new dataset with sWeights
  std::cout << "import new dataset with sWeights" << std::endl;
  ws->import(*data, Rename("dataWithSWeights"));

}