void mvaPUPPETEvaluation() {
  
  //output dir
  TString dirname = "."; 
  gSystem->mkdir(dirname,true);
  gSystem->cd(dirname);    
  
  //read workspace from training
  TString fname;
  fname = "mvaPUPPET.root";
  
  TString infile = fname.Data();
  
  TFile *fws = TFile::Open(infile); 
  RooWorkspace *ws = (RooWorkspace*)fws->Get("wereg");
  
  //read variables from workspace
  RooGBRTargetFlex *perpwidth = static_cast<RooGBRTargetFlex*>(ws->arg("perpwidth"));  
  RooGBRTargetFlex *perpmean  = static_cast<RooGBRTargetFlex*>(ws->arg("perpmean"));  
  RooGBRTargetFlex *parpwidth = static_cast<RooGBRTargetFlex*>(ws->arg("parwidth"));  
  RooGBRTargetFlex *parmean   = static_cast<RooGBRTargetFlex*>(ws->arg("parmean"));  
  RooRealVar *tgtvarX = ws->var("tgtX");
  RooRealVar *tgtvarY = ws->var("tgtY");
  
  
  RooArgList vars;
  vars.add(perpwidth->FuncVars());
  vars.add(perpmean->FuncVars());
  vars.add(perpwidth->FuncVars());
  vars.add(parmean->FuncVars());
  vars.add(*tgtvarX);
  vars.add(*tgtvarY);
   
  //read testing dataset from TTree
  RooRealVar weightvar("weightvar","",1.);

  TChain *dtree = new TChain("tree");
  
  dtree->Add("root://eoscms.cern.ch//store//group/dpg_ecal/alca_ecalcalib/ecalMIBI/rgerosa/PUPPETAnalysis/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8_Asympt50ns_MCRUN2_74_V9A_forMVATraining/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/crab_20150724_111858/150724_091912/0000/output_mc_1.root/PUPPET/t");
  //TFile *fdin = TFile::Open("/data/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-zllm50-v7n_noskim.root");

//  TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("");
//  dtree = (TTree*)ddir->Get("t");       
  
  //selection cuts for testing
  TCut selcut;
  selcut = "Boson_daughter==13"; 
  
  TCut selweight = "1";
  TCut prescale100alt = "(evt%100==1)";
  
  weightvar.SetTitle(selcut);
  
  //make testing dataset
  RooDataSet *hdata = RooTreeConvert::CreateDataSet("hdata",dtree,vars,weightvar);   

  weightvar.SetTitle(selcut);
  //make reduced testing dataset for integration over conditional variables
  RooDataSet *hdatasmall = RooTreeConvert::CreateDataSet("hdatasmall",dtree,vars,weightvar);     
    
  //retrieve full pdf from workspace
  RooAbsPdf *sigpdfX = ws->pdf("sigpdfX");
  RooAbsPdf *sigpdfY = ws->pdf("sigpdfY");
  
  //input variable corresponding to sceta
  RooRealVar *scetavar = ws->var("var_1");
  
  //regressed output functions
  RooAbsReal *perpwidthlim = ws->function("perpwidthlim");
  RooAbsReal *perpmeanlim  = ws->function("perpmeanlim");
  RooAbsReal *parwidthlim  = ws->function("parwidthlim");
  RooAbsReal *parmeanlim   = ws->function("parmeanlim");

//////////////////////////////////////////////////////////////////////////////////////
//
// formula for corrected recoil?
//
/*
  //formula for corrected energy/true energy ( 1.0/(etrue/eraw) * regression mean)
  RooFormulaVar ecor("ecor","","1./(@0)*@1",RooArgList(*tgtvar,*sigmeanlim));
  RooRealVar *ecorvar = (RooRealVar*)hdata->addColumn(ecor);
  ecorvar->setRange(0.,2.);
  ecorvar->setBins(800);
  
  //formula for raw energy/true energy (1.0/(etrue/eraw))
  RooFormulaVar raw("raw","","1./@0",RooArgList(*tgtvar));
  RooRealVar *rawvar = (RooRealVar*)hdata->addColumn(raw);
  rawvar->setRange(0.,2.);
  rawvar->setBins(800);
*/
//////////////////////////////////////////////////////////////////////////////////////
  //clone data and add regression outputs for plotting
  RooDataSet *hdataclone = new RooDataSet(*hdata,"hdataclone");

  RooRealVar *perpwidthvar = (RooRealVar*)hdataclone->addColumn(*perpwidthlim);
  RooRealVar *perpmeanvar  = (RooRealVar*)hdataclone->addColumn(*perpmeanlim);
  RooRealVar *parwidthvar  = (RooRealVar*)hdataclone->addColumn(*parwidthlim);
  RooRealVar *parmeanvar   = (RooRealVar*)hdataclone->addColumn(*parmeanlim);
  
  
  //plot target variable and weighted regression prediction (using numerical integration over reduced testing dataset)
  TCanvas *crawX = new TCanvas;
  //RooPlot *plot = tgtvar->frame(0.6,1.2,100);
  RooPlot *plot = tgtvarX->frame(-2.0,2.0,100);
  hdata->plotOn(plot);
  sigpdfX->plotOn(plot,ProjWData(*hdatasmall));
  plot->Draw();
  crawX->SaveAs("RawX.png");
  
  //plot target variable and weighted regression prediction (using numerical integration over reduced testing dataset)
  TCanvas *crawY = new TCanvas;
  //RooPlot *plot = tgtvar->frame(0.6,1.2,100);
  RooPlot *plot2 = tgtvarY->frame(-2.0,2.0,100);
  hdata->plotOn(plot2);
  sigpdfY->plotOn(plot2,ProjWData(*hdatasmall));
  plot2->Draw();
  crawY->SaveAs("RawY.png");
//////////////////////////////////////////////////////////////////////////////////////
/*
  //plot distribution of regressed functions over testing dataset
  TCanvas *cmean = new TCanvas;
  RooPlot *plotmean = meanvar->frame(0.8,2.0,100);
  hdataclone->plotOn(plotmean);
  plotmean->Draw();
  cmean->SaveAs("mean.eps");
  
  
  TCanvas *cwidth = new TCanvas;
  RooPlot *plotwidth = widthvar->frame(0.,0.05,100);
  hdataclone->plotOn(plotwidth);
  plotwidth->Draw();
  cwidth->SaveAs("width.eps");
  
  TCanvas *cn = new TCanvas;
  RooPlot *plotn = nvar->frame(0.,111.,200);
  hdataclone->plotOn(plotn);
  plotn->Draw();
  cn->SaveAs("n.eps");

  TCanvas *cn2 = new TCanvas;
  RooPlot *plotn2 = n2var->frame(0.,111.,100);
  hdataclone->plotOn(plotn2);
  plotn2->Draw();
  cn2->SaveAs("n2.eps");
  
  TCanvas *ceta = new TCanvas;
  RooPlot *ploteta = scetavar->frame(-2.6,2.6,200);
  hdataclone->plotOn(ploteta);
  ploteta->Draw();      
  ceta->SaveAs("eta.eps");  
  

  //create histograms for eraw/etrue and ecor/etrue to quantify regression performance
  TH1 *heraw = hdata->createHistogram("hraw",*rawvar,Binning(800,0.,2.));
  TH1 *hecor = hdata->createHistogram("hecor",*ecorvar);
  
  
  //heold->SetLineColor(kRed);
  hecor->SetLineColor(kBlue);
  heraw->SetLineColor(kMagenta);
  
  hecor->GetXaxis()->SetRangeUser(0.6,1.2);
  //heold->GetXaxis()->SetRangeUser(0.6,1.2);
  
  TCanvas *cresponse = new TCanvas;
  
  hecor->Draw("HIST");
  //heold->Draw("HISTSAME");
  heraw->Draw("HISTSAME");
  cresponse->SaveAs("response.eps");
  cresponse->SetLogy();
  cresponse->SaveAs("responselog.eps");
  
  
  printf("make fine histogram\n");
  TH1 *hecorfine = hdata->createHistogram("hecorfine",*ecorvar,Binning(20e3,0.,2.));

  printf("calc effsigma\n");
  
  double effsigma = effSigma(hecorfine);
  
  printf("effsigma = %5f\n",effsigma);
  */
}
Beispiel #2
0
void fitbkgdataCard(TString configCard="template.config", 
		    bool dobands  = true,  // create baerror bands for BG models
		    bool dosignal = false, // plot the signal model (needs to be present)
		    bool blinded  = true,  // blind the data in the plots?
		    bool verbose  = true  ) {
  
  gROOT->Macro("MitStyle.C");
  gStyle->SetErrorX(0); 
  gStyle->SetOptStat(0);
  gROOT->ForceStyle();  
  
  TString projectDir;

  std::vector<TString> catdesc;
  std::vector<TString> catnames;  
  std::vector<int>     polorder;

  double massmin = -1.;
  double massmax = -1.;

  double theCMenergy = -1.;

  bool readStatus = readFromConfigCard( configCard,
					projectDir,
					catnames,
					catdesc,
					polorder,
					massmin,
					massmax,
					theCMenergy
					);
  
  if( !readStatus ) {
    std::cerr<<" ERROR: Could not read from card > "<<configCard.Data()<<" <."<<std::endl;
    return;
  }
  
  TFile *fdata = new TFile(TString::Format("%s/CMS-HGG-data.root",projectDir.Data()),"READ");
  if( !fdata ) {
    std::cerr<<" ERROR: Could not open file "<<projectDir.Data()<<"/CMS-HGG-data.root."<<std::endl;
    return;
  }
  
  if( !gSystem->cd(TString::Format("%s/databkg/",projectDir.Data())) ) {
    std::cerr<<" ERROR: Could not change directory to "<<TString::Format("%s/databkg/",projectDir.Data()).Data()<<"."<<std::endl;
    return;
  }
  
  // ----------------------------------------------------------------------
  // load the input workspace....
  RooWorkspace* win = (RooWorkspace*)fdata->Get("cms_hgg_workspace_data");
  if( !win ) {
    std::cerr<<" ERROR: Could not load workspace > cms_hgg_workspace_data < from file > "<<TString::Format("%s/CMS-HGG-data.root",projectDir.Data()).Data()<<" <."<<std::endl;
    return;
  }

  RooRealVar *intLumi = win->var("IntLumi");
  RooRealVar *hmass   = win->var("CMS_hgg_mass");
  if( !intLumi || !hmass ) {
    std::cerr<<" ERROR: Could not load needed variables > IntLumi < or > CMS_hgg_mass < forom input workspace."<<std::endl;
    return;
  }

  //win->Print();

  hmass->setRange(massmin,massmax);
  hmass->setBins(4*(int)(massmax-massmin));
  hmass->SetTitle("m_{#gamma#gamma}");
  hmass->setUnit("GeV");
  hmass->setRange("fitrange",massmin,massmax);

  hmass->setRange("blind1",100.,110.);
  hmass->setRange("blind2",150.,180.);
  
  // ----------------------------------------------------------------------
  // some auxiliray vectro (don't know the meaning of all of them ... yet...
  std::vector<RooAbsData*> data_vec;
  std::vector<RooAbsPdf*>  pdfShape_vec;   // vector to store the NOT-EXTENDED PDFs (aka pdfshape)
  std::vector<RooAbsPdf*>  pdf_vec;        // vector to store the EXTENDED PDFs
  
  std::vector<RooAbsReal*> normu_vec;      // this holds the normalization vars for each Cat (needed in bands for combined cat)

  RooArgList               normList;       // list of range-limityed normalizations (needed for error bands on combined category)

  //std::vector<RooRealVar*> coeffv;
  //std::vector<RooAbsReal*> normu_vecv; // ???

  // ----------------------------------------------------------------------
  // define output works
  RooWorkspace *wOut = new RooWorkspace("wbkg","wbkg") ;
  
  // util;ities for the combined fit
  RooCategory     finalcat  ("finalcat",  "finalcat") ;  
  RooSimultaneous fullbkgpdf("fullbkgpdf","fullbkgpdf",finalcat);
  RooDataSet      datacomb  ("datacomb",  "datacomb",  RooArgList(*hmass,finalcat)) ;

  RooDataSet *datacombcat = new RooDataSet("data_combcat","",RooArgList(*hmass)) ;
  
  // add the 'combcat' to the list...if more than one cat
  if( catnames.size() > 1 ) {
    catnames.push_back("combcat");    
    catdesc.push_back("Combined");
  }
  
  for (UInt_t icat=0; icat<catnames.size(); ++icat) {
    TString catname = catnames.at(icat);
    finalcat.defineType(catname);
    
    // check if we're in a sub-cat or the comb-cat
    RooDataSet *data   = NULL;
    RooDataSet *inData = NULL;
    if( icat < (catnames.size() - 1) || catnames.size() == 1) { // this is NOT the last cat (which is by construction the combination)
      inData = (RooDataSet*)win->data(TString("data_mass_")+catname);
      if( !inData ) {
	std::cerr<<" ERROR: Could not find dataset > data_mass_"<<catname.Data()<<" < in input workspace."<<std::endl;
	return;
      }
      data = new RooDataSet(TString("data_")+catname,"",*hmass,Import(*inData));  // copy the dataset (why?)
      
      // append the data to the combined data...
      RooDataSet *datacat = new RooDataSet(TString("datacat")+catname,"",*hmass,Index(finalcat),Import(catname,*data)) ;
      datacomb.append(*datacat);
      datacombcat->append(*data);
      
      // normalization for this category
      RooRealVar *nbkg = new RooRealVar(TString::Format("CMS_hgg_%s_bkgshape_norm",catname.Data()),"",800.0,0.0,25e3);
      
      // we keep track of the normalizario vars only for N-1 cats, naming convetnions hystoric...
      if( catnames.size() > 2 && icat < (catnames.size() - 2) ) {
	RooRealVar* cbkg = new RooRealVar(TString::Format("cbkg%s",catname.Data()),"",0.0,0.0,1e3);
	cbkg->removeRange();
	normu_vec.push_back(cbkg);
	normList.add(*cbkg);
      }
      
      /// generate the Bernstrin polynomial (FIX-ME: add possibility ro create other models...)
      fstBernModel* theBGmodel = new fstBernModel(hmass, polorder[icat], icat, catname);            // using my dedicated class...
      
      std::cout<<" model name is "<<theBGmodel->getPdf()->GetName()<<std::endl;

      RooAbsPdf*    bkgshape   = theBGmodel->getPdf();                                              // the BG shape
      RooAbsPdf*    bkgpdf     = new RooExtendPdf(TString("bkgpdf")+catname,"",*bkgshape,*nbkg);    // the extended PDF
      
      // add the extedned PDF to the RooSimultaneous holding all models...
      fullbkgpdf.addPdf(*bkgpdf,catname);
      // store the NON-EXTENDED PDF for usgae to compute the error bands later..
      pdfShape_vec.push_back(bkgshape);
      pdf_vec     .push_back(bkgpdf);
      data_vec    .push_back(data);
      
    } else {
      data = datacombcat;   // we're looking at the last cat (by construction the combination)
      data_vec.push_back(data);
      
      // sum up all the cts PDFs for combined PDF
      RooArgList subpdfs;
      for (int ipdf=0; ipdf<pdf_vec.size(); ++ipdf) {
	subpdfs.add(*pdf_vec.at(ipdf));
      }
      RooAddPdf* bkgpdf = new RooAddPdf(TString("bkgpdf")+catname,"",subpdfs);
      pdfShape_vec.push_back(bkgpdf);      
      pdf_vec     .push_back(bkgpdf);  // I don't think this is really needed though....
    }
    
    // generate the binned dataset (to be put into the workspace... just in case...)
    RooDataHist *databinned = new RooDataHist(TString("databinned_")+catname,"",*hmass,*data);
    
    wOut->import(*data);
    wOut->import(*databinned);

  }
  
  std::cout<<" ***************** "<<std::endl;

  // fit the RooSimultaneous to the combined dataset -> (we could also fit each cat separately)
  fullbkgpdf.fitTo(datacomb,Strategy(1),Minos(kFALSE),Save(kTRUE));
  RooFitResult *fullbkgfitres = fullbkgpdf.fitTo(datacomb,Strategy(2),Minos(kFALSE),Save(kTRUE));
  
  // in principle we're done now, so store the results in the output workspace
  wOut->import(datacomb);  
  wOut->import(fullbkgpdf);
  wOut->import(*fullbkgfitres);

  std::cout<<" ***************** "<<std::endl;
  

  if( verbose ) wOut->Print();

  
  std::cout<<" ***************** "<<std::endl;

  wOut->writeToFile("bkgdatawithfit.root") ;  
  
  if( verbose ) {
    printf("IntLumi = %5f\n",intLumi->getVal());
    printf("ndata:\n");
    for (UInt_t icat=0; icat<catnames.size(); ++icat) {    
      printf("%i ",data_vec.at(icat)->numEntries());      
    }   
    printf("\n");
  } 
  
  // --------------------------------------------------------------------------------------------
  // Now comesd the plotting
  // chage the Statistics style...
  gStyle->SetOptStat(1110);
  
  // we want to plot in 1GeV bins (apparently...)
  UInt_t nbins = (UInt_t) (massmax-massmin);
  
  // here we'll store the curves for the bands...
  std::vector<RooCurve*> fitcurves;
  
  // loop again over the cats
  TCanvas **canbkg = new TCanvas*[catnames.size()];
  RooPlot** plot   = new RooPlot*[catnames.size()];

  TLatex** lat  = new TLatex*[catnames.size()];
  TLatex** lat2 = new TLatex*[catnames.size()];

  std::cout<<"  beofre plotting..."<<std::endl;
  

  for (UInt_t icat=0; icat<catnames.size(); ++icat) {
    TString catname = catnames.at(icat);
    

    std::cout<<" trying to plot #"<<icat<<std::endl;

    // plot the data and the fit 
    canbkg[icat] = new TCanvas;
    plot  [icat] = hmass->frame(Bins(nbins),Range("fitrange"));
    
    std::cout<<" trying to plot #"<<icat<<std::endl;

    // first plot the data invisibly... and put the fitted BG model on top...
    data_vec    .at(icat)->plotOn(plot[icat],RooFit::LineColor(kWhite),MarkerColor(kWhite),Invisible());
    pdfShape_vec.at(icat)->plotOn(plot[icat],RooFit::LineColor(kRed),Range("fitrange"),NormRange("fitrange"));
    
    std::cout<<" trying to plot #"<<icat<<std::endl;


    // if toggled on, plot also the Data visibly
    if( !blinded ) {
      data_vec.at(icat)->plotOn(plot[icat]);
    }
   
    std::cout<<" trying to plot #"<<icat<<std::endl;

    // some cosmetics...
    plot[icat]->SetTitle("");      
    plot[icat]->SetMinimum(0.0);
    plot[icat]->SetMaximum(1.40*plot[icat]->GetMaximum());
    plot[icat]->GetXaxis()->SetTitle("m_{#gamma#gamma} (GeV/c^{2})");
    plot[icat]->Draw();       
            

    std::cout<<" trying to plot #"<<icat<<std::endl;

    // legend....
    TLegend *legmc = new TLegend(0.68,0.70,0.97,0.90);
    legmc->AddEntry(plot[icat]->getObject(2),"Data","LPE");
    legmc->AddEntry(plot[icat]->getObject(1),"Bkg Model","L");
    
    // this part computes the 1/2-sigma bands.    
    TGraphAsymmErrors *onesigma = NULL;
    TGraphAsymmErrors *twosigma = NULL;
    
    std::cout<<" trying ***  to plot #"<<icat<<std::endl;

    RooAddition* sumcatsnm1 = NULL;

    if ( dobands ) { //&& icat == (catnames.size() - 1) ) {

      onesigma = new TGraphAsymmErrors();
      twosigma = new TGraphAsymmErrors();

      // get the PDF for this cat from the vector
      RooAbsPdf *thisPdf = pdfShape_vec.at(icat); 

      // get the nominal fir curve
      RooCurve *nomcurve = dynamic_cast<RooCurve*>(plot[icat]->getObject(1));
      fitcurves.push_back(nomcurve);

      bool iscombcat       = ( icat == (catnames.size() - 1) && catnames.size() > 1);
      RooAbsData *datanorm = ( iscombcat ? &datacomb : data_vec.at(icat) );

      // this si the nornmalization in the 'sliding-window' (i.e. per 'test-bin')
      RooRealVar *nlim = new RooRealVar(TString::Format("nlim%s",catnames.at(icat).Data()),"",0.0,0.0,10.0);
      nlim->removeRange();

      if( iscombcat ) {
	// ----------- HISTORIC NAMING  ----------------------------------------
	sumcatsnm1 = new RooAddition("sumcatsnm1","",normList);   // summing all normalizations epect the last Cat
	// this is the normlization of the last Cat
	RooFormulaVar *nlast = new RooFormulaVar("nlast","","TMath::Max(0.1,@0-@1)",RooArgList(*nlim,*sumcatsnm1));
	// ... and adding it ot the list of norms
	normu_vec.push_back(nlast);
      }

      //if (icat == 1 && catnames.size() == 2) continue; // only 1 cat, so don't need combination

      for (int i=1; i<(plot[icat]->GetXaxis()->GetNbins()+1); ++i) {
	
	// this defines the 'binning' we use for the error bands
        double lowedge = plot[icat]->GetXaxis()->GetBinLowEdge(i);
        double upedge = plot[icat]->GetXaxis()->GetBinUpEdge(i);
        double center = plot[icat]->GetXaxis()->GetBinCenter(i);
        
	// get the nominal value at the center of the bin
        double nombkg = nomcurve->interpolate(center);
        nlim->setVal(nombkg);
        hmass->setRange("errRange",lowedge,upedge);

	// this is the new extended PDF whith the normalization restricted to the bin-area
        RooAbsPdf *extLimPdf = NULL;
	if( iscombcat ) {
	  extLimPdf = new RooSimultaneous("epdf","",finalcat);
	  // loop over the cats and generate temporary extended PDFs
	  for (int jcat=0; jcat<(catnames.size()-1); ++jcat) {
            RooRealVar *rvar = dynamic_cast<RooRealVar*>(normu_vec.at(jcat));
            if (rvar) rvar->setVal(fitcurves.at(jcat)->interpolate(center));
            RooExtendPdf *ecpdf = new RooExtendPdf(TString::Format("ecpdf%s",catnames.at(jcat).Data()),"",*pdfShape_vec.at(jcat),*normu_vec.at(jcat),"errRange");
            static_cast<RooSimultaneous*>(extLimPdf)->addPdf(*ecpdf,catnames.at(jcat));
          }
	} else
	  extLimPdf = new RooExtendPdf("extLimPdf","",*thisPdf,*nlim,"errRange");

        RooAbsReal *nll = extLimPdf->createNLL(*datanorm,Extended(),NumCPU(1));
        RooMinimizer minim(*nll);
        minim.setStrategy(0);
        double clone = 1.0 - 2.0*RooStats::SignificanceToPValue(1.0);
        double cltwo = 1.0 - 2.0*RooStats::SignificanceToPValue(2.0);
	
        if (iscombcat) minim.setStrategy(2);
        
        minim.migrad();
	
        if (!iscombcat) { 
          minim.minos(*nlim);
        }
        else {
          minim.hesse();
          nlim->removeAsymError();
        }

	if( verbose ) 
	  printf("errlo = %5f, errhi = %5f\n",nlim->getErrorLo(),nlim->getErrorHi());
        
        onesigma->SetPoint(i-1,center,nombkg);
        onesigma->SetPointError(i-1,0.,0.,-nlim->getErrorLo(),nlim->getErrorHi());
        
	// to get the 2-sigma bands...
        minim.setErrorLevel(0.5*pow(ROOT::Math::normal_quantile(1-0.5*(1-cltwo),1.0), 2)); // the 0.5 is because qmu is -2*NLL
                          // eventually if cl = 0.95 this is the usual 1.92!      
        
        if (!iscombcat) { 
          minim.migrad();
          minim.minos(*nlim);
        }
        else {
          nlim->setError(2.0*nlim->getError());
          nlim->removeAsymError();          
        }
	
        twosigma->SetPoint(i-1,center,nombkg);
        twosigma->SetPointError(i-1,0.,0.,-nlim->getErrorLo(),nlim->getErrorHi());      
        
        // for memory clean-up
        delete nll;
        delete extLimPdf;
      }
      
      hmass->setRange("errRange",massmin,massmax);

      if( verbose )
	onesigma->Print("V");
      
      // plot[icat] the error bands
      twosigma->SetLineColor(kGreen);
      twosigma->SetFillColor(kGreen);
      twosigma->SetMarkerColor(kGreen);
      twosigma->Draw("L3 SAME");     
      
      onesigma->SetLineColor(kYellow);
      onesigma->SetFillColor(kYellow);
      onesigma->SetMarkerColor(kYellow);
      onesigma->Draw("L3 SAME");
      
      plot[icat]->Draw("SAME");
    
      // and add the error bands to the legend
      legmc->AddEntry(onesigma,"#pm1 #sigma","F");  
      legmc->AddEntry(twosigma,"#pm2 #sigma","F");  
    }
    
    std::cout<<" trying ***2  to plot #"<<icat<<std::endl;

    // rest of the legend ....
    legmc->SetBorderSize(0);
    legmc->SetFillStyle(0);
    legmc->Draw();   

    lat[icat]  = new TLatex(103.0,0.9*plot[icat]->GetMaximum(),TString::Format("#scale[0.7]{#splitline{CMS preliminary}{#sqrt{s} = %.1f TeV L = %.2f fb^{-1}}}",theCMenergy,intLumi->getVal()));
    lat2[icat] = new TLatex(103.0,0.75*plot[icat]->GetMaximum(),catdesc.at(icat));

    lat[icat] ->Draw();
    lat2[icat]->Draw();
    
    // -------------------------------------------------------    
    // save canvas in different formats
    canbkg[icat]->SaveAs(TString("databkg") + catname + TString(".pdf"));
    canbkg[icat]->SaveAs(TString("databkg") + catname + TString(".eps"));
    canbkg[icat]->SaveAs(TString("databkg") + catname + TString(".root"));              
  }
  
  return;
  
}
void eregtesting_13TeV_Pi0_lessP2(bool dobarrel=true, bool doele=false,int gammaID=0) {
  
  //output dir
  TString EEorEB = "EE";
  if(dobarrel)
	{
	EEorEB = "EB";
	}
  TString gammaDir = "bothGammas";
  if(gammaID==1)
  {
   gammaDir = "gamma1";
  }
  else if(gammaID==2)
  {
   gammaDir = "gamma2";
  }
  TString dirname = TString::Format("ereg_test_plots_PU_lessP_2/%s_%s",gammaDir.Data(),EEorEB.Data());
  
  gSystem->mkdir(dirname,true);
  gSystem->cd(dirname);    
  
  //read workspace from training
  TString fname;
  if (doele && dobarrel) 
    fname = "wereg_ele_eb.root";
  else if (doele && !dobarrel) 
    fname = "wereg_ele_ee.root";
  else if (!doele && dobarrel) 
    fname = "wereg_ph_eb.root";
  else if (!doele && !dobarrel) 
    fname = "wereg_ph_ee.root";
  
  TString infile = TString::Format("../../ereg_ws_PU_lessP_2/%s/%s",gammaDir.Data(),fname.Data());
  
  TFile *fws = TFile::Open(infile); 
  RooWorkspace *ws = (RooWorkspace*)fws->Get("wereg");
  
  //read variables from workspace
  RooGBRTargetFlex *meantgt = static_cast<RooGBRTargetFlex*>(ws->arg("sigmeant"));  
  RooRealVar *tgtvar = ws->var("tgtvar");
  
  
  RooArgList vars;
  vars.add(meantgt->FuncVars());
  vars.add(*tgtvar);
   
  //read testing dataset from TTree
  RooRealVar weightvar("weightvar","",1.);

  TTree *dtree;
  
  if (doele) {
    //TFile *fdin = TFile::Open("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-zllm50-v7n_noskim.root");
    TFile *fdin = TFile::Open("/data/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-zllm50-v7n_noskim.root");

    TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterSingleInvert");
    dtree = (TTree*)ddir->Get("hPhotonTreeSingle");       
  }
  else {
    if(dobarrel)
    {
    TFile *fdin = TFile::Open("/afs/cern.ch/work/z/zhicaiz/public/ECALpro_MC_TreeForRegression/sum_Pi0Gun_Flat0to50bx25_EB_combine.root");//("root://eoscms.cern.ch///eos/cms/store/cmst3/user/bendavid/idTreesAug1/hgg-2013Final8TeV_ID_s12-h124gg-gf-v7n_noskim.root");
   // TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterPreselNoSmear");
	if(gammaID==0)
	{
	dtree = (TTree*)fdin->Get("Tree_Optim_gamma");
	}
	else if(gammaID==1)
	{
	dtree = (TTree*)fdin->Get("Tree_Optim_gamma1");
	}
	else if(gammaID==2)
	{
	dtree = (TTree*)fdin->Get("Tree_Optim_gamma2");
	}
    }      
   else
    {
  TFile *fdin = TFile::Open("/afs/cern.ch/work/z/zhicaiz/public/ECALpro_MC_TreeForRegression/sum_Pi0Gun_Flat0to50bx25_EE_combine.root");//("root://eoscms.cern.ch///eos/cms/store/cmst3/user/bendavid/idTreesAug1/hgg-2013Final8TeV_ID_s12-h124gg-gf-v7n_noskim.root");
   // TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterPreselNoSmear");
   	if(gammaID==0)
	{
	dtree = (TTree*)fdin->Get("Tree_Optim_gamma");
	}
	else if(gammaID==1)
	{
	dtree = (TTree*)fdin->Get("Tree_Optim_gamma1");
	}
	else if(gammaID==2)
	{
	dtree = (TTree*)fdin->Get("Tree_Optim_gamma2");
	}
    } 
  }
  
  //selection cuts for testing
  //TCut selcut = "(STr2_enG1_true/cosh(STr2_Eta_1)>1.0) && (STr2_S4S9_1>0.75)";
  TCut selcut = "(STr2_enG_nocor/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_isMerging < 2) && (STr2_DeltaR < 0.05)";
//  TCut selcut = "(STr2_enG_nocor/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_S4S9 < 0.999) && (STr2_S2S9 < 0.999)";
/*  
TCut selcut;
  if (dobarrel) 
    selcut = "ph.genpt>25. && ph.isbarrel && ph.ispromptgen"; 
  else
    selcut = "ph.genpt>25. && !ph.isbarrel && ph.ispromptgen"; 
 */ 
  TCut selweight = "xsecweight(procidx)*puweight(numPU,procidx)";
  TCut prescale10 = "(Entry$%10==0)";
  TCut prescale10alt = "(Entry$%10==1)";
  TCut prescale25 = "(Entry$%25==0)";
  TCut prescale100 = "(Entry$%100==0)";  
  TCut prescale1000 = "(Entry$%1000==0)";  
  TCut evenevents = "(Entry$%2==0)";
  TCut oddevents = "(Entry$%2==1)";
  TCut prescale100alt = "(Entry$%100==1)";
  TCut prescale1000alt = "(Entry$%1000==1)";
  TCut prescale50alt = "(Entry$%50==1)";
  TCut Events3_4 = "(Entry$%4==3)";
  TCut Events1_4 = "(Entry$%4==1)";
  TCut Events2_4 = "(Entry$%4==2)";
  TCut Events0_4 = "(Entry$%4==0)";

  TCut Events01_4 = "(Entry$%4<2)";
  TCut Events23_4 = "(Entry$%4>1)";
 
  if (doele) 
    weightvar.SetTitle(prescale100alt*selcut);
  else
    weightvar.SetTitle(Events01_4*selcut);
  
  //make testing dataset
  RooDataSet *hdata = RooTreeConvert::CreateDataSet("hdata",dtree,vars,weightvar);   

  if (doele) 
    weightvar.SetTitle(prescale1000alt*selcut);
  else
    weightvar.SetTitle(prescale10alt*selcut);
  //make reduced testing dataset for integration over conditional variables
  RooDataSet *hdatasmall = RooTreeConvert::CreateDataSet("hdatasmall",dtree,vars,weightvar);     
    
  //retrieve full pdf from workspace
  RooAbsPdf *sigpdf = ws->pdf("sigpdf");
  
  //input variable corresponding to sceta
////  RooRealVar *scetavar = ws->var("var_1");
////  RooRealVar *scphivar = ws->var("var_2");
  
 
  //regressed output functions
  RooAbsReal *sigmeanlim = ws->function("sigmeanlim");
  RooAbsReal *sigwidthlim = ws->function("sigwidthlim");
  RooAbsReal *signlim = ws->function("signlim");
  RooAbsReal *sign2lim = ws->function("sign2lim");

  //formula for corrected energy/true energy ( 1.0/(etrue/eraw) * regression mean)
  RooFormulaVar ecor("ecor","","1./(@0)*@1",RooArgList(*tgtvar,*sigmeanlim));
  RooRealVar *ecorvar = (RooRealVar*)hdata->addColumn(ecor);
  ecorvar->setRange(0.,2.);
  ecorvar->setBins(800);
  
  //formula for raw energy/true energy (1.0/(etrue/eraw))
  RooFormulaVar raw("raw","","1./@0",RooArgList(*tgtvar));
  RooRealVar *rawvar = (RooRealVar*)hdata->addColumn(raw);
  rawvar->setRange(0.,2.);
  rawvar->setBins(800);

  //clone data and add regression outputs for plotting
  RooDataSet *hdataclone = new RooDataSet(*hdata,"hdataclone");
  RooRealVar *meanvar = (RooRealVar*)hdataclone->addColumn(*sigmeanlim);
  RooRealVar *widthvar = (RooRealVar*)hdataclone->addColumn(*sigwidthlim);
  RooRealVar *nvar = (RooRealVar*)hdataclone->addColumn(*signlim);
  RooRealVar *n2var = (RooRealVar*)hdataclone->addColumn(*sign2lim);
  
  
  //plot target variable and weighted regression prediction (using numerical integration over reduced testing dataset)
  TCanvas *craw = new TCanvas;
  //RooPlot *plot = tgtvar->frame(0.6,1.2,100);
  RooPlot *plot = tgtvar->frame(0.6,2.0,100);
  hdata->plotOn(plot);
  sigpdf->plotOn(plot,ProjWData(*hdatasmall));
  plot->Draw();
  craw->SaveAs("RawE.eps");
  craw->SetLogy();
  plot->SetMinimum(0.1);
  craw->SaveAs("RawElog.eps");
  
  //plot distribution of regressed functions over testing dataset
  TCanvas *cmean = new TCanvas;
  RooPlot *plotmean = meanvar->frame(0.8,2.0,100);
  hdataclone->plotOn(plotmean);
  plotmean->Draw();
  cmean->SaveAs("mean.eps");
  
  
  TCanvas *cwidth = new TCanvas;
  RooPlot *plotwidth = widthvar->frame(0.,0.05,100);
  hdataclone->plotOn(plotwidth);
  plotwidth->Draw();
  cwidth->SaveAs("width.eps");
  
  TCanvas *cn = new TCanvas;
  RooPlot *plotn = nvar->frame(0.,111.,200);
  hdataclone->plotOn(plotn);
  plotn->Draw();
  cn->SaveAs("n.eps");

  TCanvas *cn2 = new TCanvas;
  RooPlot *plotn2 = n2var->frame(0.,111.,100);
  hdataclone->plotOn(plotn2);
  plotn2->Draw();
  cn2->SaveAs("n2.eps");
 
////
/* 
  TCanvas *ceta = new TCanvas;
  RooPlot *ploteta = scetavar->frame(-2.6,2.6,200);
  hdataclone->plotOn(ploteta);
  ploteta->Draw();      
  ceta->SaveAs("eta.eps");  
  
*/

  //create histograms for eraw/etrue and ecor/etrue to quantify regression performance
  TH1 *heraw;// = hdata->createHistogram("hraw",*rawvar,Binning(800,0.,2.));
  TH1 *hecor;// = hdata->createHistogram("hecor",*ecorvar);
  if (EEorEB == "EB")
  {
         heraw = hdata->createHistogram("hraw",*rawvar,Binning(800,0.,2.));
         hecor = hdata->createHistogram("hecor",*ecorvar, Binning(800,0.,2.));
  }
  else
  {
         heraw = hdata->createHistogram("hraw",*rawvar,Binning(200,0.,2.));
         hecor = hdata->createHistogram("hecor",*ecorvar, Binning(200,0.,2.));
  }

  
  
  //heold->SetLineColor(kRed);
  hecor->SetLineColor(kBlue);
  heraw->SetLineColor(kMagenta);
  
  hecor->GetYaxis()->SetRangeUser(1.0,1.3*hecor->GetMaximum());
  heraw->GetYaxis()->SetRangeUser(1.0,1.3*hecor->GetMaximum());

  hecor->GetXaxis()->SetRangeUser(0.0,1.5);
  heraw->GetXaxis()->SetRangeUser(0.0,1.5);
  
/*if(EEorEB == "EE")
{
  heraw->GetYaxis()->SetRangeUser(10.0,200.0);
  hecor->GetYaxis()->SetRangeUser(10.0,200.0);
}
*/ 
 
//heold->GetXaxis()->SetRangeUser(0.6,1.2);
  double effsigma_cor, effsigma_raw, fwhm_cor, fwhm_raw;

  if(EEorEB == "EB")
  {
  TH1 *hecorfine = hdata->createHistogram("hecorfine",*ecorvar,Binning(800,0.,2.));
  effsigma_cor = effSigma(hecorfine);
  fwhm_cor = FWHM(hecorfine);
  TH1 *herawfine = hdata->createHistogram("herawfine",*rawvar,Binning(800,0.,2.));
  effsigma_raw = effSigma(herawfine);
  fwhm_raw = FWHM(herawfine);
  }
  else
  {
  TH1 *hecorfine = hdata->createHistogram("hecorfine",*ecorvar,Binning(200,0.,2.));
  effsigma_cor = effSigma(hecorfine);
  fwhm_cor = FWHM(hecorfine);
  TH1 *herawfine = hdata->createHistogram("herawfine",*rawvar,Binning(200,0.,2.));
  effsigma_raw = effSigma(herawfine);
  fwhm_raw = FWHM(herawfine);
  }


  TCanvas *cresponse = new TCanvas;
  gStyle->SetOptStat(0); 
  hecor->SetTitle("");
  heraw->SetTitle("");
  hecor->Draw("HIST");
  //heold->Draw("HISTSAME");
  heraw->Draw("HISTSAME");

  //show errSigma in the plot
  TLegend *leg = new TLegend(0.1, 0.75, 0.7, 0.9);
  leg->AddEntry(hecor,Form("E_{cor}/E_{true}, #sigma_{eff}=%4.3f, FWHM=%4.3f", effsigma_cor, fwhm_cor),"l");
  leg->AddEntry(heraw,Form("E_{raw}/E_{true}, #sigma_{eff}=%4.3f, FWHM=%4.3f", effsigma_raw, fwhm_raw),"l");
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
 // leg->SetTextColor(kRed);
  leg->Draw();

  cresponse->SaveAs("response.eps");
  cresponse->SetLogy();
  cresponse->SaveAs("responselog.eps");
 

  // draw CCs vs eta and phi

//////
/*
  TCanvas *c_eta = new TCanvas;
  TH1 *h_eta = hdata->createHistogram("h_eta",*scetavar,Binning(100,-3.2,3.2));
  h_eta->Draw("HIST");
  c_eta->SaveAs("heta.eps");

  TCanvas *c_phi = new TCanvas;
  TH1 *h_phi = hdata->createHistogram("h_phi",*scphivar,Binning(100,-3.2,3.2));
  h_phi->Draw("HIST");
  c_phi->SaveAs("hphi.eps");
*/
/*
  RooRealVar *scetaiXvar = ws->var("var_1");
  RooRealVar *scphiiYvar = ws->var("var_2");
 
   if(EEorEB=="EB")
   {
   scetaiXvar->setRange(-90,90);
   scetaiXvar->setBins(1800);
   scphiiYvar->setRange(0,360);
   scphiiYvar->setBins(3600);
   }
   else
   {
   scetaiXvar->setRange(0,50);
   scetaiXvar->setBins(500);
   scphiiYvar->setRange(0,50);
   scphiiYvar->setBins(500);
 
   }
   ecorvar->setRange(0.5,1.5);
   ecorvar->setBins(100);
   rawvar->setRange(0.5,1.5);
   rawvar->setBins(100);
  

  TCanvas *c_cor_eta = new TCanvas;
  TH2F *h_CC_eta = hdata->createHistogram(*scetaiXvar, *ecorvar, "","cor_vs_eta");
  if(EEorEB=="EB")
  {
  h_CC_eta->GetXaxis()->SetTitle("i#eta"); 
  }
  else
  {
  h_CC_eta->GetXaxis()->SetTitle("iX");
  }
  h_CC_eta->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_eta->Draw("COLZ");
  c_cor_eta->SaveAs("cor_vs_eta.eps");

  	
  TCanvas *c_cor_phi = new TCanvas;
  TH2F *h_CC_phi = hdata->createHistogram(*scphiiYvar, *ecorvar, "","cor_vs_phi"); 
  if(EEorEB=="EB")
  {
  h_CC_phi->GetXaxis()->SetTitle("i#phi"); 
  }
  else
  {
  h_CC_phi->GetXaxis()->SetTitle("iY");
  }

  h_CC_phi->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_phi->Draw("COLZ");
  c_cor_phi->SaveAs("cor_vs_phi.eps");
 
  TCanvas *c_raw_eta = new TCanvas;
  TH2F *h_RC_eta = hdata->createHistogram(*scetaiXvar, *rawvar, "","raw_vs_eta");
  if(EEorEB=="EB")
  {
  h_RC_eta->GetXaxis()->SetTitle("i#eta"); 
  }
  else
  {
  h_RC_eta->GetXaxis()->SetTitle("iX");
  }

  h_RC_eta->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_eta->Draw("COLZ");
  c_raw_eta->SaveAs("raw_vs_eta.eps");
	
  TCanvas *c_raw_phi = new TCanvas;
  TH2F *h_RC_phi = hdata->createHistogram(*scphiiYvar, *rawvar, "","raw_vs_phi"); 
  if(EEorEB=="EB")
  {
  h_RC_phi->GetXaxis()->SetTitle("i#phi"); 
  }
  else
  {
  h_RC_phi->GetXaxis()->SetTitle("iY");
  }

  h_RC_phi->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_phi->Draw("COLZ");
  c_raw_phi->SaveAs("raw_vs_phi.eps");

// other variables

  TCanvas *myC_variables = new TCanvas;
*/

/////
/*  RooRealVar *Nxtalvar = ws->var("var_3");
  Nxtalvar->setRange(0,10);
  Nxtalvar->setBins(10);
  TH2F *h_CC_Nxtal = hdata->createHistogram(*Nxtalvar, *ecorvar, "","cor_vs_Nxtal");
  h_CC_Nxtal->GetXaxis()->SetTitle("Nxtal"); 
  h_CC_Nxtal->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_Nxtal->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_Nxtal.eps");
  TH2F *h_RC_Nxtal = hdata->createHistogram(*Nxtalvar, *rawvar, "","raw_vs_Nxtal");
  h_RC_Nxtal->GetXaxis()->SetTitle("Nxtal"); 
  h_RC_Nxtal->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_Nxtal->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_Nxtal.eps");
	
  RooRealVar *S4S9var = ws->var("var_4");
  S4S9var->setRange(0.6,1.0);
  S4S9var->setBins(100);
  TH2F *h_CC_S4S9 = hdata->createHistogram(*S4S9var, *ecorvar, "","cor_vs_S4S9");
  h_CC_S4S9->GetXaxis()->SetTitle("S4S9"); 
  h_CC_S4S9->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_S4S9->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_S4S9.eps");
  TH2F *h_RC_S4S9 = hdata->createHistogram(*S4S9var, *rawvar, "","raw_vs_S4S9");
  h_RC_S4S9->GetXaxis()->SetTitle("S4S9"); 
  h_RC_S4S9->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_S4S9->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_S4S9.eps");
*/	
//////
/* 
  RooRealVar *S1S9var = ws->var("var_5");
  S1S9var->setRange(0.3,1.0);
  S1S9var->setBins(100);
  TH2F *h_CC_S1S9 = hdata->createHistogram(*S1S9var, *ecorvar, "","cor_vs_S1S9");
  h_CC_S1S9->GetXaxis()->SetTitle("S1S9"); 
  h_CC_S1S9->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_S1S9->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_S1S9.eps");
  TH2F *h_RC_S1S9 = hdata->createHistogram(*S1S9var, *rawvar, "","raw_vs_S1S9");
  h_RC_S1S9->GetXaxis()->SetTitle("S1S9"); 
  h_RC_S1S9->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_S1S9->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_S1S9.eps");
 */
//////
/*
  RooRealVar *S2S9var = ws->var("var_5");
  S2S9var->setRange(0.5,1.0);
  S2S9var->setBins(100);
  TH2F *h_CC_S2S9 = hdata->createHistogram(*S2S9var, *ecorvar, "","cor_vs_S2S9");
  h_CC_S2S9->GetXaxis()->SetTitle("S2S9"); 
  h_CC_S2S9->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_S2S9->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_S2S9.eps");
  TH2F *h_RC_S2S9 = hdata->createHistogram(*S2S9var, *rawvar, "","raw_vs_S2S9");
  h_RC_S2S9->GetXaxis()->SetTitle("S2S9"); 
  h_RC_S2S9->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_S2S9->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_S2S9.eps");
  
  RooRealVar *DeltaRvar = ws->var("var_6");
  DeltaRvar->setRange(0.0,0.1);
  DeltaRvar->setBins(100);
  TH2F *h_CC_DeltaR = hdata->createHistogram(*DeltaRvar, *ecorvar, "","cor_vs_DeltaR");
  h_CC_DeltaR->GetXaxis()->SetTitle("#Delta R"); 
  h_CC_DeltaR->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_DeltaR->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_DeltaR.eps");
  TH2F *h_RC_DeltaR = hdata->createHistogram(*DeltaRvar, *rawvar, "","raw_vs_DeltaR");
  h_RC_DeltaR->GetXaxis()->SetTitle("#Delta R"); 
  h_RC_DeltaR->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_DeltaR->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_DeltaR.eps");

  if(EEorEB=="EE")
{
  RooRealVar *Es_e1var = ws->var("var_9");
  Es_e1var->setRange(0.0,200.0);
  Es_e1var->setBins(1000);
  TH2F *h_CC_Es_e1 = hdata->createHistogram(*Es_e1var, *ecorvar, "","cor_vs_Es_e1");
  h_CC_Es_e1->GetXaxis()->SetTitle("Es_e1"); 
  h_CC_Es_e1->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_Es_e1->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_Es_e1.eps");
  TH2F *h_RC_Es_e1 = hdata->createHistogram(*Es_e1var, *rawvar, "","raw_vs_Es_e1");
  h_RC_Es_e1->GetXaxis()->SetTitle("Es_e1"); 
  h_RC_Es_e1->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_Es_e1->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_Es_e1.eps");

  RooRealVar *Es_e2var = ws->var("var_10");
  Es_e2var->setRange(0.0,200.0);
  Es_e2var->setBins(1000);
  TH2F *h_CC_Es_e2 = hdata->createHistogram(*Es_e2var, *ecorvar, "","cor_vs_Es_e2");
  h_CC_Es_e2->GetXaxis()->SetTitle("Es_e2"); 
  h_CC_Es_e2->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_Es_e2->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_Es_e2.eps");
  TH2F *h_RC_Es_e2 = hdata->createHistogram(*Es_e2var, *rawvar, "","raw_vs_Es_e2");
  h_RC_Es_e2->GetXaxis()->SetTitle("Es_e2"); 
  h_RC_Es_e2->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_Es_e2->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_Es_e2.eps");

}

*/

/*	
  TProfile *p_CC_eta = h_CC_eta->ProfileX();
  p_CC_eta->GetYaxis()->SetRangeUser(0.5,1.5);
  if(EEorEB == "EB")
  {
   p_CC_eta->GetYaxis()->SetRangeUser(0.85,1.0);
//   p_CC_eta->GetXaxis()->SetRangeUser(-1.5,1.5);
  }
  p_CC_eta->GetYaxis()->SetTitle("E_{cor}/E_{true}");
  p_CC_eta->SetTitle("");
  p_CC_eta->Draw();
  myC_variables->SaveAs("profile_cor_vs_eta.eps"); 
  
  TProfile *p_RC_eta = h_RC_eta->ProfileX();
  p_RC_eta->GetYaxis()->SetRangeUser(0.5,1.5);
  if(EEorEB=="EB")
  {
   p_RC_eta->GetYaxis()->SetRangeUser(0.80,0.95);
  // p_RC_eta->GetXaxis()->SetRangeUser(-1.5,1.5);
  }
  p_RC_eta->GetYaxis()->SetTitle("E_{raw}/E_{true}");
  p_RC_eta->SetTitle("");
  p_RC_eta->Draw();
  myC_variables->SaveAs("profile_raw_vs_eta.eps"); 

  TProfile *p_CC_phi = h_CC_phi->ProfileX();
  p_CC_phi->GetYaxis()->SetRangeUser(0.84,1.06);
  if(EEorEB == "EB")
  {
   p_CC_phi->GetYaxis()->SetRangeUser(0.91,1.00);
  }
  p_CC_phi->GetYaxis()->SetTitle("E_{cor}/E_{true}");
  p_CC_phi->SetTitle("");
  p_CC_phi->Draw();
  myC_variables->SaveAs("profile_cor_vs_phi.eps"); 
  
  TProfile *p_RC_phi = h_RC_phi->ProfileX();
  p_RC_phi->GetYaxis()->SetRangeUser(0.82,1.04);
  if(EEorEB=="EB")
  {
   p_RC_phi->GetYaxis()->SetRangeUser(0.86,0.95);
  }
  p_RC_phi->GetYaxis()->SetTitle("E_{raw}/E_{true}");
  p_RC_phi->SetTitle("");
  p_RC_phi->Draw();
  myC_variables->SaveAs("profile_raw_vs_phi.eps"); 



  printf("calc effsigma\n");
  std::cout<<"_"<<EEorEB<<std::endl;
  printf("corrected curve effSigma= %5f, FWHM=%5f \n",effsigma_cor, fwhm_cor);
  printf("raw curve effSigma= %5f FWHM=%5f \n",effsigma_raw, fwhm_raw);
*/
  
/*  new TCanvas;
  RooPlot *ploteold = testvar.frame(0.6,1.2,100);
  hdatasigtest->plotOn(ploteold);
  ploteold->Draw();    
  
  new TCanvas;
  RooPlot *plotecor = ecorvar->frame(0.6,1.2,100);
  hdatasig->plotOn(plotecor);
  plotecor->Draw(); */   
  
  
}
Beispiel #4
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 #5
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 LeptonPreselectionCMG( PreselType type, RooWorkspace * w ) {
	const Options & opt = Options::getInstance(); 
	if (type == ELE)
		cout << "Running Electron Preselection :" << endl;
	else if (type == MU)
		cout << "Running Muon Preselection :" << endl;
	else if (type == EMU)
		cout << "Running Electron-Muon Preselection() ..." << endl;
	else if (type == PHOT)
		cout << "Running Photon Preselection :" << endl;

	string systVar;
	try {
		systVar = opt.checkStringOption("SYSTEMATIC_VAR");
	} catch (const std::string & exc) {
		cout << exc << endl;
	}
	if (systVar == "NONE")
		systVar.clear();

#ifdef CMSSWENV
	JetCorrectionUncertainty jecUnc("Summer13_V4_MC_Uncertainty_AK5PFchs.txt");
#endif

	string inputDir = opt.checkStringOption("INPUT_DIR");
	string outputDir = opt.checkStringOption("OUTPUT_DIR");
	string sampleName = opt.checkStringOption("SAMPLE_NAME");
	string inputFile = inputDir + '/' + sampleName + ".root";
	cout << "\tInput file: " << inputFile << endl;

	bool isSignal = opt.checkBoolOption("SIGNAL");
	TGraph * higgsW = 0;
	TGraph * higgsI = 0;
	if (isSignal) {
		double higgsM = opt.checkDoubleOption("HIGGS_MASS");
		if (higgsM >= 400) {
			string dirName = "H" + double2string(higgsM);
			bool isVBF = opt.checkBoolOption("VBF");
			string lshapeHistName = "cps";
			string intHistName = "nominal";
			
			if (systVar == "LSHAPE_UP") {
				intHistName = "up";
			} else if (systVar == "LSHAPE_DOWN") {
				intHistName = "down";
			}

			if (isVBF) {
				TFile weightFile("VBF_LineShapes.root");
				higgsW = (TGraph *) ( (TDirectory *) weightFile.Get(dirName.c_str()))->Get( lshapeHistName.c_str() )->Clone();

			} else {
				TFile weightFile("GG_LineShapes.root");
				higgsW = (TGraph *) ( (TDirectory *) weightFile.Get(dirName.c_str()))->Get( lshapeHistName.c_str() )->Clone();
				TFile interfFile("newwgts_interf.root");
				higgsI = (TGraph *) ( (TDirectory *) interfFile.Get(dirName.c_str()))->Get( intHistName.c_str() )->Clone();
			}
		}
	}

	TFile * file = new TFile( inputFile.c_str() );
	if (!file->IsOpen())
		throw string("ERROR: Can't open the file: " + inputFile + "!");
	TDirectory * dir = (TDirectory *) file->Get("dataAnalyzer");
	TH1D * nEvHisto = (TH1D *) dir->Get("cutflow");
	TH1D * puHisto = (TH1D *) dir->Get("pileup");
	TTree * tree = ( TTree * ) dir->Get( "data" );
	Event ev( tree );
	const int * runP = ev.getSVA<int>("run"); 
	const int * lumiP = ev.getSVA<int>("lumi"); 
	const int * eventP = ev.getSVA<int>("event"); 
	const bool * trigBits = ev.getAVA<bool>("t_bits");
	const int * trigPres = ev.getAVA<int>("t_prescale");
	const float * metPtA = ev.getAVA<float>("met_pt");
	const float * metPhiA = ev.getAVA<float>("met_phi");
	const float * rhoP = ev.getSVA<float>("rho");
	const float * rho25P = ev.getSVA<float>("rho25");
	const int * nvtxP = ev.getSVA<int>("nvtx"); 
	const int * niP = ev.getSVA<int>("ngenITpu"); 
	
#ifdef PRINTEVENTS
	string eventFileName;
	if (type == ELE)
		eventFileName = "events_ele.txt";
	else if (type == MU)
		eventFileName = "events_mu.txt";
	else if (type == EMU)
		eventFileName = "events_emu.txt";

	EventPrinter evPrint(ev, type, eventFileName);
	evPrint.readInEvents("diff.txt");
	evPrint.printElectrons();
	evPrint.printMuons();
	evPrint.printZboson();
	evPrint.printJets();
	evPrint.printHeader();
#endif

	string outputFile = outputDir + '/' + sampleName;

	if (systVar.size())
		outputFile += ('_' + systVar);

	if (type == ELE)
		outputFile += "_elePresel.root";
	else if (type == MU)
		outputFile += "_muPresel.root";
	else if (type == EMU)
		outputFile += "_emuPresel.root";
	else if (type == PHOT)
		outputFile += "_phPresel.root";
	cout << "\tOutput file: " << outputFile << endl;

	TFile * out = new TFile( outputFile.c_str(), "recreate" );
	TH1D * outNEvHisto = new TH1D("nevt", "nevt", 1, 0, 1);
	outNEvHisto->SetBinContent(1, nEvHisto->GetBinContent(1));
	outNEvHisto->Write("nevt");

	TH1D * outPuHisto = new TH1D( *puHisto );
	outPuHisto->Write("pileup");

	std::vector< std::tuple<std::string, std::string> > eleVars;
	eleVars.push_back( std::make_tuple("ln_px", "F") );
	eleVars.push_back( std::make_tuple("ln_py", "F") );
	eleVars.push_back( std::make_tuple("ln_pz", "F") );
	eleVars.push_back( std::make_tuple("ln_en", "F") );
	eleVars.push_back( std::make_tuple("ln_idbits", "I") );
	eleVars.push_back( std::make_tuple("ln_d0", "F") );
	eleVars.push_back( std::make_tuple("ln_dZ", "F") );
	eleVars.push_back( std::make_tuple("ln_nhIso03", "F") );
	eleVars.push_back( std::make_tuple("ln_gIso03", "F") );
	eleVars.push_back( std::make_tuple("ln_chIso03", "F") );
	eleVars.push_back( std::make_tuple("ln_trkLostInnerHits", "F") );

	std::vector< std::tuple<std::string, std::string> > addEleVars;
	addEleVars.push_back( std::make_tuple("egn_sceta", "F") );
	addEleVars.push_back( std::make_tuple("egn_detain", "F") );
	addEleVars.push_back( std::make_tuple("egn_dphiin", "F") );
	addEleVars.push_back( std::make_tuple("egn_sihih", "F") );
	addEleVars.push_back( std::make_tuple("egn_hoe", "F") );
	addEleVars.push_back( std::make_tuple("egn_ooemoop", "F") );
	addEleVars.push_back( std::make_tuple("egn_isConv", "B") );

	std::vector< std::tuple<std::string, std::string> > muVars;
	muVars.push_back( std::make_tuple("ln_px", "F") );
	muVars.push_back( std::make_tuple("ln_py", "F") );
	muVars.push_back( std::make_tuple("ln_pz", "F") );
	muVars.push_back( std::make_tuple("ln_en", "F") );
	muVars.push_back( std::make_tuple("ln_idbits", "I") );
	muVars.push_back( std::make_tuple("ln_d0", "F") );
	muVars.push_back( std::make_tuple("ln_dZ", "F") );
	muVars.push_back( std::make_tuple("ln_nhIso04", "F") );
	muVars.push_back( std::make_tuple("ln_gIso04", "F") );
	muVars.push_back( std::make_tuple("ln_chIso04", "F") );
	muVars.push_back( std::make_tuple("ln_puchIso04", "F") );
	muVars.push_back( std::make_tuple("ln_trkchi2", "F") );
	muVars.push_back( std::make_tuple("ln_trkValidPixelHits", "F") );

	std::vector< std::tuple<std::string, std::string> > addMuVars;
	addMuVars.push_back( std::make_tuple("mn_trkLayersWithMeasurement", "F") );
	addMuVars.push_back( std::make_tuple("mn_pixelLayersWithMeasurement", "F") );
	addMuVars.push_back( std::make_tuple("mn_innerTrackChi2", "F") );
	addMuVars.push_back( std::make_tuple("mn_validMuonHits", "F") );
	addMuVars.push_back( std::make_tuple("mn_nMatchedStations", "F") );

	unsigned run;
	unsigned lumi;
	unsigned event;
	double pfmet;
	int nele;
	int nmu;
	int nsoftmu;
	double l1pt;
	double l1eta;
	double l1phi;
	double l2pt;
	double l2eta;
	double l2phi;
	double zmass;
	double zpt;
	double zeta;
	double mt;
	int nsoftjet;
	int nhardjet;
	double maxJetBTag;
	double minDeltaPhiJetMet;
	double detajj;
	double mjj;
	int nvtx;
	int ni;
	int category;
	double weight;
	double hmass;
	double hweight;

	TTree * smallTree = new TTree("HZZ2l2nuAnalysis", "HZZ2l2nu Analysis Tree");
	smallTree->Branch( "Run", &run, "Run/i" );
	smallTree->Branch( "Lumi", &lumi, "Lumi/i" );
	smallTree->Branch( "Event", &event, "Event/i" );
	smallTree->Branch( "PFMET", &pfmet, "PFMET/D" );
	smallTree->Branch( "NELE", &nele, "NELE/I" );
	smallTree->Branch( "NMU", &nmu, "NMU/I" );
	smallTree->Branch( "NSOFTMU", &nsoftmu, "NSOFTMU/I" );
	smallTree->Branch( "L1PT", &l1pt, "L1PT/D" );
	smallTree->Branch( "L1ETA", &l1eta, "L1ETA/D" );
	smallTree->Branch( "L1PHI", &l1phi, "L1PHI/D" );
	smallTree->Branch( "L2PT", &l2pt, "L2PT/D" );
	smallTree->Branch( "L2ETA", &l2eta, "L2ETA/D" );
	smallTree->Branch( "L2PHI", &l2phi, "L2PHI/D" );
	smallTree->Branch( "ZMASS", &zmass, "ZMASS/D" );
	smallTree->Branch( "ZPT", &zpt, "ZPT/D" );
	smallTree->Branch( "ZETA", &zeta, "ZETA/D" );
	smallTree->Branch( "MT", &mt, "MT/D" );
	smallTree->Branch( "NSOFTJET", &nsoftjet, "NSOFTJET/I" );
	smallTree->Branch( "NHARDJET", &nhardjet, "NHARDJET/I" );
	smallTree->Branch( "MAXJETBTAG", &maxJetBTag, "MAXJETBTAG/D" );
	smallTree->Branch( "MINDPJETMET", &minDeltaPhiJetMet, "MINDPJETMET/D" );
	smallTree->Branch( "DETAJJ", &detajj, "DETAJJ/D" );
	smallTree->Branch( "MJJ", &mjj, "MJJ/D" );
	smallTree->Branch( "NVTX", &nvtx, "NVTX/I" );
	smallTree->Branch( "nInter" , &ni, "nInter/I" );
	smallTree->Branch( "CATEGORY", &category, "CATEGORY/I" );
	smallTree->Branch( "Weight" , &weight, "Weight/D" );
	smallTree->Branch( "HMASS", &hmass, "HMASS/D" );
	smallTree->Branch( "HWEIGHT", &hweight, "HWEIGHT/D" );

	bool isData = opt.checkBoolOption("DATA");

	unsigned long nentries = tree->GetEntries();

	RooDataSet * events = nullptr;

	PhotonPrescale photonPrescales;

	vector<int> thresholds;
	if (type == PHOT) {
		if (w == nullptr)
			throw string("ERROR: No mass peak pdf!");
		RooRealVar * zmass = w->var("mass");
		zmass->setRange(76.0, 106.0);
		RooAbsPdf * pdf = w->pdf("massPDF");
		events = pdf->generate(*zmass, nentries);

		photonPrescales.addTrigger("HLT_Photon36_R9Id90_HE10_Iso40_EBOnly", 36, 3, 7);
		photonPrescales.addTrigger("HLT_Photon50_R9Id90_HE10_Iso40_EBOnly", 50, 5, 8);
		photonPrescales.addTrigger("HLT_Photon75_R9Id90_HE10_Iso40_EBOnly", 75, 7, 9);
		photonPrescales.addTrigger("HLT_Photon90_R9Id90_HE10_Iso40_EBOnly", 90, 10, 10);
	}

	TH1D ptSpectrum("ptSpectrum", "ptSpectrum", 200, 55, 755);
	ptSpectrum.Sumw2();

	unordered_set<EventAdr> eventsSet;
	for ( unsigned long iEvent = 0; iEvent < nentries; iEvent++ ) {
//		if (iEvent < 6060000)
//			continue;

		if ( iEvent % 10000 == 0) {
			cout << string(40, '\b');
			cout << setw(10) << iEvent << " / " << setw(10) << nentries << " done ..." << std::flush;
		}

		tree->GetEntry( iEvent );

		run = -999;
		lumi = -999;
		event = -999;
		pfmet = -999;
		nele = -999;
		nmu = -999;
		nsoftmu = -999;
		l1pt = -999;
		l1eta = -999;
		l1phi = -999;
		l2pt = -999;
		l2eta = -999;
		l2phi = -999;
		zmass = -999;
		zpt = -999;
		zeta = -999;
		mt = -999;
		nsoftjet = -999;
		nhardjet = -999;
		maxJetBTag = -999;
		minDeltaPhiJetMet = -999;
		detajj = -999;
		mjj = -999;
		nvtx = -999;
		ni = -999;
		weight = -999;
		category = -1;
		hmass = -999;
		hweight = -999;

		run = *runP;
		lumi = *lumiP;
		event = *eventP;

		EventAdr tmp(run, lumi, event);
		if (eventsSet.find( tmp ) != eventsSet.end()) {
			continue;
		}
		eventsSet.insert( tmp );

		if (type == ELE && isData) {
			if (trigBits[0] != 1 || trigPres[0] != 1)
				continue;
		}

		if (type == MU && isData) {
			if ( (trigBits[2] != 1 || trigPres[2] != 1)
				&& (trigBits[3] != 1 || trigPres[3] != 1)
				&& (trigBits[6] != 1 || trigPres[6] != 1)
			   )
				continue;
		}

		if (type == EMU && isData) {
			if ( (trigBits[4] != 1 || trigPres[4] != 1)
				&& (trigBits[5] != 1 || trigPres[5] != 1)
			   )
				continue;
		}

		vector<Electron> electrons = buildLeptonCollection<Electron, 11>(ev, eleVars, addEleVars);
		vector<Muon> muons = buildLeptonCollection<Muon, 13>(ev, muVars, addMuVars);

		float rho = *rhoP;
		float rho25 = *rho25P;

		vector<Electron> looseElectrons;
		vector<Electron> selectedElectrons;
		for (unsigned j = 0; j < electrons.size(); ++j) {
			try {
			TLorentzVector lv = electrons[j].lorentzVector();
			if (
					lv.Pt() > 10 &&
					fabs(lv.Eta()) < 2.5 &&
					!electrons[j].isInCrack() &&
					electrons[j].passesVetoID() &&
					electrons[j].isPFIsolatedLoose(rho25)
				) {
				looseElectrons.push_back(electrons[j]);
			}

			if (
					lv.Pt() > 20 &&
					fabs(lv.Eta()) < 2.5 &&
					!electrons[j].isInCrack() &&
					electrons[j].passesMediumID() &&
					electrons[j].isPFIsolatedMedium(rho25)
				) {
				selectedElectrons.push_back(electrons[j]);
			}
			} catch (const string & exc) {
				cout << exc << endl;
				cout << "run = " << run << endl;
				cout << "lumi = " << lumi << endl;
				cout << "event = " << event << endl;
			}
		}

		vector<Muon> looseMuons;
		vector<Muon> softMuons;
		vector<Muon> selectedMuons;
		for (unsigned j = 0; j < muons.size(); ++j) {
			TLorentzVector lv = muons[j].lorentzVector();
			if (
					lv.Pt() > 10 &&
					fabs(lv.Eta()) < 2.4 &&
					muons[j].isLooseMuon() &&
					muons[j].isPFIsolatedLoose()
				) {
				looseMuons.push_back(muons[j]);
			} else if (
					lv.Pt() > 3 &&
					fabs(lv.Eta()) < 2.4 &&
					muons[j].isSoftMuon()
				) {
				softMuons.push_back(muons[j]);
			}
			if (
					lv.Pt() > 20 &&
					fabs(lv.Eta()) < 2.4 &&
					muons[j].isTightMuon() &&
					muons[j].isPFIsolatedTight()
				) {
				selectedMuons.push_back(muons[j]);
			}
		}

		vector<Lepton> looseLeptons;
		for (unsigned i = 0; i < looseElectrons.size(); ++i)
			looseLeptons.push_back(looseElectrons[i]);
		for (unsigned i = 0; i < looseMuons.size(); ++i)
			looseLeptons.push_back(looseMuons[i]);
		for (unsigned i = 0; i < softMuons.size(); ++i)
			looseLeptons.push_back(softMuons[i]);

#ifdef PRINTEVENTS
		evPrint.setElectronCollection(selectedElectrons);
		evPrint.setMuonCollection(selectedMuons);
#endif

		vector<Photon> photons = selectPhotonsCMG( ev );
		vector<Photon> selectedPhotons;
		for (unsigned i = 0; i < photons.size(); ++i) {
			if (photons[i].isSelected(rho) && photons[i].lorentzVector().Pt() > 55)
				selectedPhotons.push_back( photons[i] );
		}

		if (type == PHOT) {
			vector<Electron> tmpElectrons;
			for (unsigned i = 0; i < selectedPhotons.size(); ++i) {
				TLorentzVector phVec = selectedPhotons[i].lorentzVector();
				for (unsigned j = 0; j < looseElectrons.size(); ++j) {
					TLorentzVector elVec = looseElectrons[j].lorentzVector();
					double dR = deltaR(phVec.Eta(), phVec.Phi(), elVec.Eta(), elVec.Phi());
					if ( dR > 0.05 )
						tmpElectrons.push_back( looseElectrons[j] );
				}
			}
			looseElectrons = tmpElectrons;
		}

		string leptonsType;
		Lepton * selectedLeptons[2] = {0};
		if (type == ELE) {
			if (selectedElectrons.size() < 2) {
				continue;
			} else {
				selectedLeptons[0] = &selectedElectrons[0];
				selectedLeptons[1] = &selectedElectrons[1];
			}
		} else if (type == MU) {
			if (selectedMuons.size() < 2) {
				continue;
			} else {
				selectedLeptons[0] = &selectedMuons[0];
				selectedLeptons[1] = &selectedMuons[1];
			}
		} else if (type == EMU) {
			if (selectedElectrons.size() < 1 || selectedMuons.size() < 1) {
				continue;
			} else {
				selectedLeptons[0] = &selectedElectrons[0];
				selectedLeptons[1] = &selectedMuons[0];
			}
		} else if (type == PHOT) {
			if (selectedPhotons.size() != 1) {
				continue;
			}
		}

		nele = looseElectrons.size();
		nmu = looseMuons.size();
		nsoftmu = softMuons.size();

		TLorentzVector Zcand;

		if (type == ELE || type == MU || type == EMU) {
			TLorentzVector lep1 = selectedLeptons[0]->lorentzVector();
			TLorentzVector lep2 = selectedLeptons[1]->lorentzVector();

			if (lep2.Pt() > lep1.Pt() && type != EMU) {
				TLorentzVector temp = lep1;
				lep1 = lep2;
				lep2 = temp;
			}

			l1pt = lep1.Pt();
			l1eta = lep1.Eta();
			l1phi = lep1.Phi();

			l2pt = lep2.Pt();
			l2eta = lep2.Eta();
			l2phi = lep2.Phi();

			Zcand = lep1 + lep2;
			zmass = Zcand.M();
		} else if (type == PHOT) {
			Zcand = selectedPhotons[0].lorentzVector();
			zmass = events->get(iEvent)->getRealValue("mass");
		}

		zpt = Zcand.Pt();
		zeta = Zcand.Eta();

		if (type == PHOT) {
			unsigned idx = photonPrescales.getIndex(zpt);
			if (trigBits[idx])
				weight = trigPres[idx];
			else
				continue;
			ptSpectrum.Fill(zpt, weight);
		}

		TLorentzVector met;
		met.SetPtEtaPhiM(metPtA[0], 0.0, metPhiA[0], 0.0);
		TLorentzVector clusteredFlux;

		unsigned mode = 0;
		if (systVar == "JES_UP")
			mode = 1;
		else if (systVar == "JES_DOWN")
			mode = 2;
		TLorentzVector jecCorr;

#ifdef CMSSWENV
		vector<Jet> jetsAll = selectJetsCMG( ev, looseLeptons, jecUnc, &jecCorr, mode );
#else
		vector<Jet> jetsAll = selectJetsCMG( ev, looseLeptons, &jecCorr, mode );
#endif

		met -= jecCorr;

		mode = 0;
		if (systVar == "JER_UP")
			mode = 1;
		else if (systVar == "JER_DOWN")
			mode = 2;
		TLorentzVector smearCorr = smearJets( jetsAll, mode );
		if (isData && smearCorr != TLorentzVector())
			throw std::string("Jet smearing corrections different from zero in DATA!");
		met -= smearCorr;

		vector<Jet> selectedJets;
		for (unsigned i = 0; i < jetsAll.size(); ++i) {
			if (
					jetsAll[i].lorentzVector().Pt() > 10
					&& fabs(jetsAll[i].lorentzVector().Eta()) < 4.7
					&& jetsAll[i].passesPUID() &&
					jetsAll[i].passesPFLooseID()
				)
				selectedJets.push_back( jetsAll[i] );
		}
		if (type == PHOT) {
			vector<Jet> tmpJets;
			for (unsigned i = 0; i < selectedPhotons.size(); ++i) {
				TLorentzVector phVec = selectedPhotons[i].lorentzVector();
				for (unsigned j = 0; j < selectedJets.size(); ++j) {
					TLorentzVector jVec = selectedJets[j].lorentzVector();
					double dR = deltaR(phVec.Eta(), phVec.Phi(), jVec.Eta(), jVec.Phi());
					if ( dR > 0.4 )
						tmpJets.push_back( selectedJets[j] );
				}
			}
			selectedJets = tmpJets;
		}

		if (systVar == "UMET_UP" || systVar == "UMET_DOWN") {
			for (unsigned i = 0; i < jetsAll.size(); ++i)
				clusteredFlux += jetsAll[i].lorentzVector();
			for (unsigned i = 0; i < looseElectrons.size(); ++i)
				clusteredFlux += looseElectrons[i].lorentzVector();
			for (unsigned i = 0; i < looseMuons.size(); ++i)
				clusteredFlux += looseMuons[i].lorentzVector();

			TLorentzVector unclusteredFlux = -(met + clusteredFlux);
			if (systVar == "UMET_UP")
				unclusteredFlux *= 1.1;
			else
				unclusteredFlux *= 0.9;
			met = -(clusteredFlux + unclusteredFlux);
		}

		if (systVar == "LES_UP" || systVar == "LES_DOWN") {
			TLorentzVector diff;
			double sign = 1.0;
			if (systVar == "LES_DOWN")
				sign = -1.0;
			for (unsigned i = 0; i < looseElectrons.size(); ++i) {
				TLorentzVector tempEle = looseElectrons[i].lorentzVector();
				if (looseElectrons[i].isEB())
					diff += sign * 0.02 * tempEle;
				else
					diff += sign * 0.05 * tempEle;
			}
			for (unsigned i = 0; i < looseMuons.size(); ++i)
				diff += sign * 0.01 * looseMuons[i].lorentzVector();

			met -= diff;
		}

		pfmet = met.Pt();

		double px = met.Px() + Zcand.Px();
		double py = met.Py() + Zcand.Py();
		double pt2 = px * px + py * py;
		double e = sqrt(zpt * zpt + zmass * zmass) + sqrt(pfmet * pfmet + zmass * zmass);
		double mt2 = e * e - pt2;
		mt = (mt2 > 0) ? sqrt(mt2) : 0;

		vector<Jet> hardjets;
		vector<Jet> softjets;
		maxJetBTag = -999;
		minDeltaPhiJetMet = 999;
		for ( unsigned j = 0; j < selectedJets.size(); ++j ) {
			TLorentzVector jet = selectedJets[j].lorentzVector();

			if ( jet.Pt() > 30 ) {
				hardjets.push_back( selectedJets[j] );
			}
			if ( jet.Pt() > 15 )
				softjets.push_back( selectedJets[j] );
		}
		nhardjet = hardjets.size();
		nsoftjet = softjets.size();
//		if ( type == PHOT && nsoftjet == 0 )
//			continue;

		if (nhardjet > 1) {
			sort(hardjets.begin(), hardjets.end(), [](const Jet & a, const Jet & b) {
					return a.lorentzVector().Pt() > b.lorentzVector().Pt();
				});
			TLorentzVector jet1 = hardjets[0].lorentzVector();
			TLorentzVector jet2 = hardjets[1].lorentzVector();
			const double maxEta = max( jet1.Eta(), jet2.Eta() );
			const double minEta = min( jet1.Eta(), jet2.Eta() );
			bool passCJV = true;
			for (unsigned j = 2; j < hardjets.size(); ++j) {
				double tmpEta = hardjets[j].lorentzVector().Eta();
				if ( tmpEta > minEta && tmpEta < maxEta )
					passCJV = false;
			}
			const double tmpDelEta = std::fabs(jet2.Eta() - jet1.Eta());
			TLorentzVector diJetSystem = jet1 + jet2;
			const double tmpMass = diJetSystem.M();
			if ( type == PHOT) {
				if (passCJV && tmpDelEta > 4.0 && tmpMass > 500 && zeta > minEta && maxEta > zeta) {
					detajj = tmpDelEta;
					mjj = tmpMass;
				}
			} else {
				if (passCJV && tmpDelEta > 4.0 && tmpMass > 500 && l1eta > minEta && l2eta > minEta && maxEta > l1eta && maxEta > l2eta) {
					detajj = tmpDelEta;
					mjj = tmpMass;
				}
			}
		}

		category = evCategory(nhardjet, nsoftjet, detajj, mjj, type == PHOT);

		minDeltaPhiJetMet = 10;
		for ( unsigned j = 0; j < hardjets.size(); ++j ) {
			TLorentzVector jet = hardjets[j].lorentzVector();
			if ( hardjets[j].getVarF("jn_jp") > maxJetBTag && fabs(jet.Eta()) < 2.5 )
				maxJetBTag = hardjets[j].getVarF("jn_jp");
			double tempDelPhiJetMet = deltaPhi(met.Phi(), jet.Phi());
			if ( tempDelPhiJetMet < minDeltaPhiJetMet )
				minDeltaPhiJetMet = tempDelPhiJetMet;
		}

		nvtx = *nvtxP;

		if (isData)
			ni = -1;
		else
			ni = *niP;

		if (isSignal) {
			const int nMC = ev.getSVV<int>("mcn");
			const int * mcID = ev.getAVA<int>("mc_id");
			int hIdx = 0;
			for (; hIdx < nMC; ++hIdx)
				if (fabs(mcID[hIdx]) == 25)
					break;
			if (hIdx == nMC)
				throw string("ERROR: Higgs not found in signal sample!");

			float Hpx = ev.getAVV<float>("mc_px", hIdx);
			float Hpy = ev.getAVV<float>("mc_py", hIdx);
			float Hpz = ev.getAVV<float>("mc_pz", hIdx);
			float Hen = ev.getAVV<float>("mc_en", hIdx);
			TLorentzVector higgs;
			higgs.SetPxPyPzE( Hpx, Hpy, Hpz, Hen );
			hmass = higgs.M();

			if (higgsW) {
				hweight = higgsW->Eval(hmass);
				if (higgsI)
					hweight *= higgsI->Eval(hmass);
			} else
				hweight = 1;
		}

		if ( opt.checkBoolOption("ADDITIONAL_LEPTON_VETO") && (type == ELE || type == MU || type == EMU) && ((nele + nmu + nsoftmu) > 2) )
			continue;
		if ( opt.checkBoolOption("ADDITIONAL_LEPTON_VETO") && (type == PHOT) && ((nele + nmu + nsoftmu) > 0) )
			continue;
		if ( opt.checkBoolOption("ZPT_CUT") && zpt < 55 )
			continue;
		// for different background estimation methods different window should be applied:
		// * sample for photons should have 76.0 < zmass < 106.0
		// * sample for non-resonant background should not have this cut applied
		if ( opt.checkBoolOption("TIGHT_ZMASS_CUT") && (type == ELE || type == MU) && (zmass < 76.0 || zmass > 106.0))
			continue;
		if ( opt.checkBoolOption("WIDE_ZMASS_CUT") && (type == ELE || type == MU) && (zmass < 76.0 || zmass > 106.0))
			continue;
		if ( opt.checkBoolOption("BTAG_CUT") && ( maxJetBTag > 0.264) )
			continue;
		if ( opt.checkBoolOption("DPHI_CUT") && ( minDeltaPhiJetMet < 0.5) )
			continue;


#ifdef PRINTEVENTS
		evPrint.setJetCollection(hardjets);
		evPrint.setMET(met);
		evPrint.setMT(mt);
		string channelType;
		if (type == ELE)
			channelType = "ee";
		else if (type == MU)
			channelType = "mumu";
		else if (type == EMU)
			channelType = "emu";
		if (category == 1)
			channelType += "eq0jets";
		else if (category == 2)
			channelType += "geq1jets";
		else
			channelType += "vbf";
		evPrint.setChannel(channelType);
		unsigned bits = 0;
		bits |= (0x7);
		bits |= ((zmass > 76.0 && zmass < 106.0) << 3);
		bits |= ((zpt > 55) << 4);
		bits |= (((nele + nmu + nsoftmu) == 2) << 5);
		bits |= ((maxJetBTag < 0.275) << 6);
		bits |= ((minDeltaPhiJetMet > 0.5) << 7);
		evPrint.setBits(bits);
		evPrint.print();
#endif
		
		smallTree->Fill();
	}
	cout << endl;
	
	TCanvas canv("canv", "canv", 800, 600);
	//effNum.Sumw2();
	//effDen.Sumw2();
	//effNum.Divide(&effDen);
	//effNum.Draw();
	canv.SetGridy();
	canv.SetGridx();
	//canv.SaveAs("triggEff.ps");
	//canv.Clear();
	ptSpectrum.SetMarkerStyle(20);
	ptSpectrum.SetMarkerSize(0.5);
	ptSpectrum.Draw("P0E");
	//ptSpectrum.Draw("COLZ");
	canv.SetLogy();
	canv.SaveAs("ptSpectrum.ps");

	delete file;
	smallTree->Write("", TObject::kOverwrite);
	delete smallTree;
	delete out;
}
// internal routine to run the inverter
HypoTestInverterResult *
RooStats::HypoTestInvTool::RunInverter(RooWorkspace * w,
                                       const char * modelSBName, const char * modelBName, 
                                       const char * dataName, int type,  int testStatType, 
                                       bool useCLs, int npoints, double poimin, double poimax, 
                                       int ntoys,
                                       bool useNumberCounting,
                                       const char * nuisPriorName ){

   std::cout << "Running HypoTestInverter on the workspace " << w->GetName() << std::endl;
  
   w->Print();
  
  
   RooAbsData * data = w->data(dataName); 
   if (!data) { 
      Error("StandardHypoTestDemo","Not existing data %s",dataName);
      return 0;
   }
   else 
      std::cout << "Using data set " << dataName << std::endl;
  
   if (mUseVectorStore) { 
      RooAbsData::setDefaultStorageType(RooAbsData::Vector);
      data->convertToVectorStore() ;
   }
  
  
   // get models from WS
   // get the modelConfig out of the file
   ModelConfig* bModel = (ModelConfig*) w->obj(modelBName);
   ModelConfig* sbModel = (ModelConfig*) w->obj(modelSBName);
  
   if (!sbModel) {
      Error("StandardHypoTestDemo","Not existing ModelConfig %s",modelSBName);
      return 0;
   }
   // check the model 
   if (!sbModel->GetPdf()) { 
      Error("StandardHypoTestDemo","Model %s has no pdf ",modelSBName);
      return 0;
   }
   if (!sbModel->GetParametersOfInterest()) {
      Error("StandardHypoTestDemo","Model %s has no poi ",modelSBName);
      return 0;
   }
   if (!sbModel->GetObservables()) {
      Error("StandardHypoTestInvDemo","Model %s has no observables ",modelSBName);
      return 0;
   }
   if (!sbModel->GetSnapshot() ) { 
      Info("StandardHypoTestInvDemo","Model %s has no snapshot  - make one using model poi",modelSBName);
      sbModel->SetSnapshot( *sbModel->GetParametersOfInterest() );
   }
  
   // case of no systematics
   // remove nuisance parameters from model
   if (noSystematics) { 
      const RooArgSet * nuisPar = sbModel->GetNuisanceParameters();
      if (nuisPar && nuisPar->getSize() > 0) { 
         std::cout << "StandardHypoTestInvDemo" << "  -  Switch off all systematics by setting them constant to their initial values" << std::endl;
         RooStats::SetAllConstant(*nuisPar);
      }
      if (bModel) { 
         const RooArgSet * bnuisPar = bModel->GetNuisanceParameters();
         if (bnuisPar) 
            RooStats::SetAllConstant(*bnuisPar);
      }
   }
  
   if (!bModel || bModel == sbModel) {
      Info("StandardHypoTestInvDemo","The background model %s does not exist",modelBName);
      Info("StandardHypoTestInvDemo","Copy it from ModelConfig %s and set POI to zero",modelSBName);
      bModel = (ModelConfig*) sbModel->Clone();
      bModel->SetName(TString(modelSBName)+TString("_with_poi_0"));      
      RooRealVar * var = dynamic_cast<RooRealVar*>(bModel->GetParametersOfInterest()->first());
      if (!var) return 0;
      double oldval = var->getVal();
      var->setVal(0);
      bModel->SetSnapshot( RooArgSet(*var)  );
      var->setVal(oldval);
   }
   else { 
      if (!bModel->GetSnapshot() ) { 
         Info("StandardHypoTestInvDemo","Model %s has no snapshot  - make one using model poi and 0 values ",modelBName);
         RooRealVar * var = dynamic_cast<RooRealVar*>(bModel->GetParametersOfInterest()->first());
         if (var) { 
            double oldval = var->getVal();
            var->setVal(0);
            bModel->SetSnapshot( RooArgSet(*var)  );
            var->setVal(oldval);
         }
         else { 
            Error("StandardHypoTestInvDemo","Model %s has no valid poi",modelBName);
            return 0;
         }         
      }
   }

   // check model  has global observables when there are nuisance pdf
   // for the hybrid case the globobs are not needed
   if (type != 1 ) { 
      bool hasNuisParam = (sbModel->GetNuisanceParameters() && sbModel->GetNuisanceParameters()->getSize() > 0);
      bool hasGlobalObs = (sbModel->GetGlobalObservables() && sbModel->GetGlobalObservables()->getSize() > 0);
      if (hasNuisParam && !hasGlobalObs ) {  
         // try to see if model has nuisance parameters first 
         RooAbsPdf * constrPdf = RooStats::MakeNuisancePdf(*sbModel,"nuisanceConstraintPdf_sbmodel");
         if (constrPdf) { 
            Warning("StandardHypoTestInvDemo","Model %s has nuisance parameters but no global observables associated",sbModel->GetName());
            Warning("StandardHypoTestInvDemo","\tThe effect of the nuisance parameters will not be treated correctly ");
         }
      }
   }

   // save all initial parameters of the model including the global observables 
   RooArgSet initialParameters; 
   RooArgSet * allParams = sbModel->GetPdf()->getParameters(*data); 
   allParams->snapshot(initialParameters);
   delete allParams; 
  
   // run first a data fit 
  
   const RooArgSet * poiSet = sbModel->GetParametersOfInterest();
   RooRealVar *poi = (RooRealVar*)poiSet->first();
  
   std::cout << "StandardHypoTestInvDemo : POI initial value:   " << poi->GetName() << " = " << poi->getVal()   << std::endl;  
  
   // fit the data first (need to use constraint )
   TStopwatch tw; 

   bool doFit = initialFit;
   if (testStatType == 0 && initialFit == -1) doFit = false;  // case of LEP test statistic
   if (type == 3  && initialFit == -1) doFit = false;         // case of Asymptoticcalculator with nominal Asimov
   double poihat = 0;

   if (minimizerType.size()==0) minimizerType = ROOT::Math::MinimizerOptions::DefaultMinimizerType();
   else 
      ROOT::Math::MinimizerOptions::SetDefaultMinimizer(minimizerType.c_str());
    
   Info("StandardHypoTestInvDemo","Using %s as minimizer for computing the test statistic",
        ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str() );
   
   if (doFit)  { 

      // do the fit : By doing a fit the POI snapshot (for S+B)  is set to the fit value
      // and the nuisance parameters nominal values will be set to the fit value. 
      // This is relevant when using LEP test statistics

      Info( "StandardHypoTestInvDemo"," Doing a first fit to the observed data ");
      RooArgSet constrainParams;
      if (sbModel->GetNuisanceParameters() ) constrainParams.add(*sbModel->GetNuisanceParameters());
      RooStats::RemoveConstantParameters(&constrainParams);
      tw.Start(); 
      RooFitResult * fitres = sbModel->GetPdf()->fitTo(*data,InitialHesse(false), Hesse(false),
                                                       Minimizer(minimizerType.c_str(),"Migrad"), Strategy(0), PrintLevel(mPrintLevel), Constrain(constrainParams), Save(true), Offset(RooStats::IsNLLOffset()) );
      if (fitres->status() != 0) {
         Warning("StandardHypoTestInvDemo","Fit to the model failed - try with strategy 1 and perform first an Hesse computation");
         fitres = sbModel->GetPdf()->fitTo(*data,InitialHesse(true), Hesse(false),Minimizer(minimizerType.c_str(),"Migrad"), Strategy(1), PrintLevel(mPrintLevel+1), Constrain(constrainParams),
                                           Save(true), Offset(RooStats::IsNLLOffset()) );
      }
      if (fitres->status() != 0) 
         Warning("StandardHypoTestInvDemo"," Fit still failed - continue anyway.....");
  
  
      poihat  = poi->getVal();
      std::cout << "StandardHypoTestInvDemo - Best Fit value : " << poi->GetName() << " = "  
                << poihat << " +/- " << poi->getError() << std::endl;
      std::cout << "Time for fitting : "; tw.Print(); 
  
      //save best fit value in the poi snapshot 
      sbModel->SetSnapshot(*sbModel->GetParametersOfInterest());
      std::cout << "StandardHypoTestInvo: snapshot of S+B Model " << sbModel->GetName() 
                << " is set to the best fit value" << std::endl;
  
   }

   // print a message in case of LEP test statistics because it affects result by doing or not doing a fit 
   if (testStatType == 0) {
      if (!doFit) 
         Info("StandardHypoTestInvDemo","Using LEP test statistic - an initial fit is not done and the TS will use the nuisances at the model value");
      else 
         Info("StandardHypoTestInvDemo","Using LEP test statistic - an initial fit has been done and the TS will use the nuisances at the best fit value");
   }


   // build test statistics and hypotest calculators for running the inverter 
  
   SimpleLikelihoodRatioTestStat slrts(*sbModel->GetPdf(),*bModel->GetPdf());

   // null parameters must includes snapshot of poi plus the nuisance values 
   RooArgSet nullParams(*sbModel->GetSnapshot());
   if (sbModel->GetNuisanceParameters()) nullParams.add(*sbModel->GetNuisanceParameters());
   if (sbModel->GetSnapshot()) slrts.SetNullParameters(nullParams);
   RooArgSet altParams(*bModel->GetSnapshot());
   if (bModel->GetNuisanceParameters()) altParams.add(*bModel->GetNuisanceParameters());
   if (bModel->GetSnapshot()) slrts.SetAltParameters(altParams);
   if (mEnableDetOutput) slrts.EnableDetailedOutput();
  
   // ratio of profile likelihood - need to pass snapshot for the alt
   RatioOfProfiledLikelihoodsTestStat 
      ropl(*sbModel->GetPdf(), *bModel->GetPdf(), bModel->GetSnapshot());
   ropl.SetSubtractMLE(false);
   if (testStatType == 11) ropl.SetSubtractMLE(true);
   ropl.SetPrintLevel(mPrintLevel);
   ropl.SetMinimizer(minimizerType.c_str());
   if (mEnableDetOutput) ropl.EnableDetailedOutput();
  
   ProfileLikelihoodTestStat profll(*sbModel->GetPdf());
   if (testStatType == 3) profll.SetOneSided(true);
   if (testStatType == 4) profll.SetSigned(true);
   profll.SetMinimizer(minimizerType.c_str());
   profll.SetPrintLevel(mPrintLevel);
   if (mEnableDetOutput) profll.EnableDetailedOutput();

   profll.SetReuseNLL(mOptimize);
   slrts.SetReuseNLL(mOptimize);
   ropl.SetReuseNLL(mOptimize);

   if (mOptimize) { 
      profll.SetStrategy(0);
      ropl.SetStrategy(0);
      ROOT::Math::MinimizerOptions::SetDefaultStrategy(0);
   }
  
   if (mMaxPoi > 0) poi->setMax(mMaxPoi);  // increase limit
  
   MaxLikelihoodEstimateTestStat maxll(*sbModel->GetPdf(),*poi); 
   NumEventsTestStat nevtts;

   AsymptoticCalculator::SetPrintLevel(mPrintLevel);
  
   // create the HypoTest calculator class 
   HypoTestCalculatorGeneric *  hc = 0;
   if (type == 0) hc = new FrequentistCalculator(*data, *bModel, *sbModel);
   else if (type == 1) hc = new HybridCalculator(*data, *bModel, *sbModel);
   // else if (type == 2 ) hc = new AsymptoticCalculator(*data, *bModel, *sbModel, false, mAsimovBins);
   // else if (type == 3 ) hc = new AsymptoticCalculator(*data, *bModel, *sbModel, true, mAsimovBins);  // for using Asimov data generated with nominal values 
   else if (type == 2 ) hc = new AsymptoticCalculator(*data, *bModel, *sbModel, false );
   else if (type == 3 ) hc = new AsymptoticCalculator(*data, *bModel, *sbModel, true );  // for using Asimov data generated with nominal values 
   else {
      Error("StandardHypoTestInvDemo","Invalid - calculator type = %d supported values are only :\n\t\t\t 0 (Frequentist) , 1 (Hybrid) , 2 (Asymptotic) ",type);
      return 0;
   }

  
   // set the test statistic 
   TestStatistic * testStat = 0;
   if (testStatType == 0) testStat = &slrts;
   if (testStatType == 1 || testStatType == 11) testStat = &ropl;
   if (testStatType == 2 || testStatType == 3 || testStatType == 4) testStat = &profll;
   if (testStatType == 5) testStat = &maxll;
   if (testStatType == 6) testStat = &nevtts;

   if (testStat == 0) { 
      Error("StandardHypoTestInvDemo","Invalid - test statistic type = %d supported values are only :\n\t\t\t 0 (SLR) , 1 (Tevatron) , 2 (PLR), 3 (PLR1), 4(MLE)",testStatType);
      return 0;
   }
  
  
   ToyMCSampler *toymcs = (ToyMCSampler*)hc->GetTestStatSampler();
   if (toymcs && (type == 0 || type == 1) ) { 
      // look if pdf is number counting or extended
      if (sbModel->GetPdf()->canBeExtended() ) { 
         if (useNumberCounting)   Warning("StandardHypoTestInvDemo","Pdf is extended: but number counting flag is set: ignore it ");
      }
      else { 
         // for not extended pdf
         if (!useNumberCounting  )  { 
            int nEvents = data->numEntries();
            Info("StandardHypoTestInvDemo","Pdf is not extended: number of events to generate taken  from observed data set is %d",nEvents);
            toymcs->SetNEventsPerToy(nEvents);
         }
         else {
            Info("StandardHypoTestInvDemo","using a number counting pdf");
            toymcs->SetNEventsPerToy(1);
         }
      }

      toymcs->SetTestStatistic(testStat);
    
      if (data->isWeighted() && !mGenerateBinned) { 
         Info("StandardHypoTestInvDemo","Data set is weighted, nentries = %d and sum of weights = %8.1f but toy generation is unbinned - it would be faster to set mGenerateBinned to true\n",data->numEntries(), data->sumEntries());
      }
      toymcs->SetGenerateBinned(mGenerateBinned);
  
      toymcs->SetUseMultiGen(mOptimize);
    
      if (mGenerateBinned &&  sbModel->GetObservables()->getSize() > 2) { 
         Warning("StandardHypoTestInvDemo","generate binned is activated but the number of ovservable is %d. Too much memory could be needed for allocating all the bins",sbModel->GetObservables()->getSize() );
      }

      // set the random seed if needed
      if (mRandomSeed >= 0) RooRandom::randomGenerator()->SetSeed(mRandomSeed); 
    
   }
  
   // specify if need to re-use same toys
   if (reuseAltToys) {
      hc->UseSameAltToys();
   }
  
   if (type == 1) { 
      HybridCalculator *hhc = dynamic_cast<HybridCalculator*> (hc);
      assert(hhc);
    
      hhc->SetToys(ntoys,ntoys/mNToysRatio); // can use less ntoys for b hypothesis 
    
      // remove global observables from ModelConfig (this is probably not needed anymore in 5.32)
      bModel->SetGlobalObservables(RooArgSet() );
      sbModel->SetGlobalObservables(RooArgSet() );
    
    
      // check for nuisance prior pdf in case of nuisance parameters 
      if (bModel->GetNuisanceParameters() || sbModel->GetNuisanceParameters() ) {

         // fix for using multigen (does not work in this case)
         toymcs->SetUseMultiGen(false);
         ToyMCSampler::SetAlwaysUseMultiGen(false);

         RooAbsPdf * nuisPdf = 0; 
         if (nuisPriorName) nuisPdf = w->pdf(nuisPriorName);
         // use prior defined first in bModel (then in SbModel)
         if (!nuisPdf)  { 
            Info("StandardHypoTestInvDemo","No nuisance pdf given for the HybridCalculator - try to deduce  pdf from the model");
            if (bModel->GetPdf() && bModel->GetObservables() ) 
               nuisPdf = RooStats::MakeNuisancePdf(*bModel,"nuisancePdf_bmodel");
            else 
               nuisPdf = RooStats::MakeNuisancePdf(*sbModel,"nuisancePdf_sbmodel");
         }   
         if (!nuisPdf ) {
            if (bModel->GetPriorPdf())  { 
               nuisPdf = bModel->GetPriorPdf();
               Info("StandardHypoTestInvDemo","No nuisance pdf given - try to use %s that is defined as a prior pdf in the B model",nuisPdf->GetName());            
            }
            else { 
               Error("StandardHypoTestInvDemo","Cannnot run Hybrid calculator because no prior on the nuisance parameter is specified or can be derived");
               return 0;
            }
         }
         assert(nuisPdf);
         Info("StandardHypoTestInvDemo","Using as nuisance Pdf ... " );
         nuisPdf->Print();
      
         const RooArgSet * nuisParams = (bModel->GetNuisanceParameters() ) ? bModel->GetNuisanceParameters() : sbModel->GetNuisanceParameters();
         RooArgSet * np = nuisPdf->getObservables(*nuisParams);
         if (np->getSize() == 0) { 
            Warning("StandardHypoTestInvDemo","Prior nuisance does not depend on nuisance parameters. They will be smeared in their full range");
         }
         delete np;
      
         hhc->ForcePriorNuisanceAlt(*nuisPdf);
         hhc->ForcePriorNuisanceNull(*nuisPdf);
      
      
      }
   } 
   else if (type == 2 || type == 3) { 
      if (testStatType == 3) ((AsymptoticCalculator*) hc)->SetOneSided(true);  
      if (testStatType != 2 && testStatType != 3)  
         Warning("StandardHypoTestInvDemo","Only the PL test statistic can be used with AsymptoticCalculator - use by default a two-sided PL");
   }
   else if (type == 0 || type == 1) { 
      ((FrequentistCalculator*) hc)->SetToys(ntoys,ntoys/mNToysRatio); 
      // store also the fit information for each poi point used by calculator based on toys
      if (mEnableDetOutput) ((FrequentistCalculator*) hc)->StoreFitInfo(true);
   }

  
   // Get the result
   RooMsgService::instance().getStream(1).removeTopic(RooFit::NumIntegration);
  
  
  
   HypoTestInverter calc(*hc);
   calc.SetConfidenceLevel(confidenceLevel);
  
  
   calc.UseCLs(useCLs);
   calc.SetVerbose(true);
  
   // can speed up using proof-lite
   if (mUseProof) { 
      ProofConfig pc(*w, mNWorkers, "", kFALSE);
      toymcs->SetProofConfig(&pc);    // enable proof
   }
  
  
   if (npoints > 0) {
      if (poimin > poimax) { 
         // if no min/max given scan between MLE and +4 sigma 
         poimin = int(poihat);
         poimax = int(poihat +  4 * poi->getError());
      }
      std::cout << "Doing a fixed scan  in interval : " << poimin << " , " << poimax << std::endl;
      calc.SetFixedScan(npoints,poimin,poimax);
   }
   else { 
      //poi->setMax(10*int( (poihat+ 10 *poi->getError() )/10 ) );
      std::cout << "Doing an  automatic scan  in interval : " << poi->getMin() << " , " << poi->getMax() << std::endl;
   }
  
   tw.Start();
   HypoTestInverterResult * r = calc.GetInterval();
   std::cout << "Time to perform limit scan \n";
   tw.Print();

   if (mRebuild) {

      std::cout << "\n***************************************************************\n";
      std::cout << "Rebuild the upper limit distribution by re-generating new set of pseudo-experiment and re-compute for each of them a new upper limit\n\n";

         
      allParams = sbModel->GetPdf()->getParameters(*data); 

      // define on which value of nuisance parameters to do the rebuild
      // default is best fit value for bmodel snapshot 



      if (mRebuildParamValues != 0) { 
         // set all parameters to their initial workspace values 
         *allParams = initialParameters; 
      }
      if (mRebuildParamValues == 0 || mRebuildParamValues == 1 ) { 
          RooArgSet constrainParams;
          if (sbModel->GetNuisanceParameters() ) constrainParams.add(*sbModel->GetNuisanceParameters());
          RooStats::RemoveConstantParameters(&constrainParams);
          
          const RooArgSet * poiModel = sbModel->GetParametersOfInterest(); 
          bModel->LoadSnapshot(); 

          // do a profile using the B model snapshot
          if (mRebuildParamValues == 0 ) { 

             RooStats::SetAllConstant(*poiModel,true);

             sbModel->GetPdf()->fitTo(*data,InitialHesse(false), Hesse(false),
                                      Minimizer(minimizerType.c_str(),"Migrad"), Strategy(0), PrintLevel(mPrintLevel), Constrain(constrainParams), Offset(RooStats::IsNLLOffset()) );


             std::cout << "rebuild using fitted parameter value for B-model snapshot" << std::endl;
             constrainParams.Print("v");
          
             RooStats::SetAllConstant(*poiModel,false);
          }
      }
      std::cout << "StandardHypoTestInvDemo: Initial parameters used for rebuilding: ";
      RooStats::PrintListContent(*allParams, std::cout); 
      delete allParams; 

      calc.SetCloseProof(1);
      tw.Start();
      SamplingDistribution * limDist = calc.GetUpperLimitDistribution(true,mNToyToRebuild);
      std::cout << "Time to rebuild distributions " << std::endl;
      tw.Print();
    
      if (limDist) { 
         std::cout << "Expected limits after rebuild distribution " << std::endl;
         std::cout << "expected upper limit  (median of limit distribution) " << limDist->InverseCDF(0.5) << std::endl; 
         std::cout << "expected -1 sig limit (0.16% quantile of limit dist) " << limDist->InverseCDF(ROOT::Math::normal_cdf(-1)) << std::endl; 
         std::cout << "expected +1 sig limit (0.84% quantile of limit dist) " << limDist->InverseCDF(ROOT::Math::normal_cdf(1)) << std::endl; 
         std::cout << "expected -2 sig limit (.025% quantile of limit dist) " << limDist->InverseCDF(ROOT::Math::normal_cdf(-2)) << std::endl; 
         std::cout << "expected +2 sig limit (.975% quantile of limit dist) " << limDist->InverseCDF(ROOT::Math::normal_cdf(2)) << std::endl; 

         // Plot the upper limit distribution
         SamplingDistPlot limPlot( (mNToyToRebuild < 200) ? 50 : 100); 
         limPlot.AddSamplingDistribution(limDist); 
         limPlot.GetTH1F()->SetStats(true); // display statistics
         limPlot.SetLineColor(kBlue); 
         new TCanvas("limPlot","Upper Limit Distribution");
         limPlot.Draw(); 
                  
         /// save result in a file 
         limDist->SetName("RULDist"); 
         TFile * fileOut = new TFile("RULDist.root","RECREATE");
         limDist->Write();
         fileOut->Close();                                                                     

      
         //update r to a new updated result object containing the rebuilt expected p-values distributions
         // (it will not recompute the expected limit)
         if (r) delete r;  // need to delete previous object since GetInterval will return a cloned copy
         r = calc.GetInterval();
      
      }
      else 
         std::cout << "ERROR : failed to re-build distributions " << std::endl; 
   }
  
   return r;
}
Beispiel #8
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 #9
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 ;

}
Beispiel #10
0
void drawSidebandsWithCurve( DrawBase* db, const std::string& data_dataset, const std::string& PUType, const std::string& data_mc, const std::string& flags, int nbtags, const std::string& leptType, std::string suffix ) {

  if( suffix!="" ) suffix = "_" + suffix;

  TH1F::AddDirectory(kTRUE);

  // get histograms:

  std::vector< TH1D* > lastHistos_data = db->get_lastHistos_data();


  TH1D* h1_data = new TH1D(*(lastHistos_data[0]));
  float xMin = (db->get_xAxisMin()!=9999.) ? db->get_xAxisMin() : h1_data->GetXaxis()->GetXmin();
  float xMax = (db->get_xAxisMax()!=9999.) ? db->get_xAxisMax() : h1_data->GetXaxis()->GetXmax();
  int nBins = (int)(xMax-xMin)/h1_data->GetXaxis()->GetBinWidth(1);




  std::string sherpa_suffix = (use_sherpa) ? "_sherpa" : "";


  // open fit results file:
  char fitResultsFileName[200];
  sprintf( fitResultsFileName, "fitResultsFile_%s_%dbtag_ALL_PU%s_fit%s%s%s.root", data_dataset.c_str(), nbtags, PUType.c_str(), data_mc.c_str(), sherpa_suffix.c_str(), flags.c_str() );
  TFile* fitResultsFile = TFile::Open(fitResultsFileName);

  // get bg workspace:
  char workspaceName[200];
  sprintf( workspaceName, "fitWorkspace_%dbtag", nbtags );
  RooWorkspace* bgws = (RooWorkspace*)fitResultsFile->Get(workspaceName);
  char fitResultsName[200];
  sprintf( fitResultsName, "fitResults_%dbtag_decorr", nbtags );
  RooFitResult* bgfr = (RooFitResult*)fitResultsFile->Get(fitResultsName);

  // get mZZ variable:
  RooRealVar* CMS_hzz2l2q_mZZ = (RooRealVar*)bgws->var("CMS_hzz2l2q_mZZ");

  // get bg shape:
  RooAbsPdf* background = (RooAbsPdf*)bgws->pdf("background_decorr");


  // get data sidebands:
  TTree* tree_sidebands = (TTree*)fitResultsFile->Get("sidebandsDATA_alpha");
  TH1D* h1_dataSidebands = new TH1D("dataSidebands", "", nBins, xMin, xMax);
  h1_dataSidebands->Sumw2();

  char selection[900];
  if( leptType=="ALL" )
    sprintf( selection, "eventWeight_alpha*(((mZjj>60.&&mZjj<75.)||(mZjj>105.&&mZjj<130.)) && nBTags==%d && CMS_hzz2l2q_mZZ>183. && CMS_hzz2l2q_mZZ<800.)", nbtags);
  else {
    int leptType_int = SidebandFitter::convert_leptType(leptType);
    sprintf( selection, "eventWeight_alpha*(((mZjj>60.&&mZjj<75.)||(mZjj>105.&&mZjj<130.)) && nBTags==%d && leptType==%d && CMS_hzz2l2q_mZZ>183. && CMS_hzz2l2q_mZZ<800.)", nbtags, leptType_int);
  }
  tree_sidebands->Project("dataSidebands", "CMS_hzz2l2q_mZZ", selection);



  // create data graph (poisson asymm errors):
  TGraphAsymmErrors* graph_data_poisson = new TGraphAsymmErrors(0);
  graph_data_poisson = fitTools::getGraphPoissonErrors(h1_dataSidebands);
  graph_data_poisson->SetMarkerStyle(20);


  std::string leptType_cut;
  if( leptType=="MU" ) leptType_cut = "&& leptType==0";
  if( leptType=="ELE" ) leptType_cut = "&& leptType==1";


  SidebandFitter* sf = new SidebandFitter( data_dataset, PUType, data_mc, flags );

  // get bg normalization:
  //float expBkg = sf->get_backgroundNormalization( nbtags, leptType, "DATA" );
  std::pair<Double_t, Double_t> bgNormAndError = sf->get_backgroundNormalizationAndError( nbtags, leptType, "DATA" );
  float expBkg = bgNormAndError.first;
  float expBkg_err = bgNormAndError.second;


  //TTree* treeSidebandsDATA_alphaCorr = (TTree*)fitResultsFile->Get("sidebandsDATA_alpha");
  //TH1D* h1_mZZ_sidebands_alpha = new TH1D("mZZ_sidebands_alpha", "", 65, xMin, xMax);
  //char sidebandsCut_alpha[500];
  //sprintf(sidebandsCut_alpha, "eventWeight_alpha*(isSidebands && nBTags==%d %s)", nbtags, leptType_cut.c_str());
  //treeSidebandsDATA_alphaCorr->Project("mZZ_sidebands_alpha", "CMS_hzz2l2q_mZZ", sidebandsCut_alpha);
  //float expBkg = h1_mZZ_sidebands_alpha->Integral();


  RooPlot *plot_MCbkg = CMS_hzz2l2q_mZZ->frame(xMin,xMax,nBins);
  background->plotOn(plot_MCbkg,RooFit::Normalization(expBkg));
  if( !QUICK_ ) {
    background->plotOn(plot_MCbkg,RooFit::VisualizeError(*bgfr,2.0,kFALSE),RooFit::FillColor(kYellow), RooFit::Normalization(expBkg));
    background->plotOn(plot_MCbkg,RooFit::VisualizeError(*bgfr,1.0,kFALSE),RooFit::FillColor(kGreen), RooFit::Normalization(expBkg));
    background->plotOn(plot_MCbkg,RooFit::Normalization(expBkg));
  }

  TF1* f1_bgForLegend = new TF1("bgForLegend", "[0]");
  f1_bgForLegend->SetLineColor(kBlue);
  f1_bgForLegend->SetLineWidth(3);
  

  TH2D* h2_axes = new TH2D("axes", "", 10, xMin, xMax, 10, 0., 1.3*h1_data->GetMaximum());
  char yTitle[200];
  sprintf( yTitle, "Events / (%.0f GeV)", h1_data->GetXaxis()->GetBinWidth(1) );
  h2_axes->SetYTitle(yTitle);
  if( leptType=="MU" )
    h2_axes->SetXTitle("m_{#mu#mujj} [GeV]");
  else if( leptType=="ELE" )
    h2_axes->SetXTitle("m_{eejj} [GeV]");
  else
    h2_axes->SetXTitle("m_{ZZ} [GeV]");

  float legend_xMin = 0.5;
  float legend_yMax = 0.85;
  float legend_yMin = legend_yMax - 0.12*2.;
  float legend_xMax = 0.92;

  char legendTitle[300];
  sprintf( legendTitle, "%d b-tag sidebands", nbtags );

  TLegend* legend = new TLegend(legend_xMin, legend_yMin, legend_xMax, legend_yMax, legendTitle);
  legend->SetTextSize(0.04);
  legend->SetFillColor(0);
  legend->AddEntry( graph_data_poisson, "Data", "P");
  legend->AddEntry( f1_bgForLegend, "Fit", "L");

  TPaveText* cmsLabel = db->get_labelCMS();
  TPaveText* sqrtLabel = db->get_labelSqrt();


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

  h2_axes->Draw();
  cmsLabel->Draw("same");
  sqrtLabel->Draw("same");
  if( suffix != "_turnOnZOOM" )
    legend->Draw("same");
  plot_MCbkg->Draw("same");
  graph_data_poisson->Draw("P same");

  gPad->RedrawAxis();


  
  char canvasName[1000];
  if( leptType=="ALL" )
    sprintf( canvasName, "%s/mZZsidebands_%dbtag_withCurve%s", (db->get_outputdir()).c_str(), nbtags, suffix.c_str() );
  else 
    sprintf( canvasName, "%s/mZZsidebands_%dbtag_withCurve%s_%s", (db->get_outputdir()).c_str(), nbtags, suffix.c_str(), leptType.c_str() );
  std::string canvasName_str(canvasName);
  std::string canvasName_eps = canvasName_str+".eps";
  c1->SaveAs(canvasName_eps.c_str());

  c1->Clear();

  c1->SetLogy();


  TLegend* legend_log = new TLegend(0.6, legend_yMin, legend_xMax, legend_yMax, (db->get_legendTitle()).c_str());
  legend_log->SetTextSize(0.04);
  legend_log->SetFillColor(0);
  legend_log->AddEntry( graph_data_poisson, "Data", "P");
  legend_log->AddEntry( f1_bgForLegend, "Exp. BG", "L");



  TH2D* h2_axes_log = new TH2D("axes_log", "", 10, xMin, xMax, 10, 0.05, 200.*h1_data->GetMaximum());
  h2_axes_log->SetYTitle(yTitle);
  h2_axes_log->SetXTitle("m_{ZZ} [GeV]");

  h2_axes_log->Draw();
  cmsLabel->Draw("same");
  sqrtLabel->Draw("same");
  //legend_log->Draw("same");
  legend->Draw("same");
  plot_MCbkg->Draw("same");
  graph_data_poisson->Draw("P same");

  gPad->RedrawAxis();

  std::string canvasName_log_eps = canvasName_str+"_log.eps";
  c1->SaveAs(canvasName_log_eps.c_str());


  delete sf;
  delete h2_axes;
  delete h2_axes_log;
  delete c1;

}
Beispiel #11
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"));

}
Beispiel #12
0
void drawHistoWithCurve( DrawBase* db, const std::string& data_dataset, const std::string& PUType, const std::string& data_mc, const std::string& flags, int nbtags, const std::string& leptType, std::string suffix ) {

  if( suffix!="" ) suffix = "_" + suffix;

  TH1F::AddDirectory(kTRUE);

  // get histograms:

  std::vector< TH1D* > lastHistos_data = db->get_lastHistos_data();
  std::vector< TH1D* > lastHistos_mc   = db->get_lastHistos_mc();
  std::vector< TH1D* > lastHistos_mc_superimp   = db->get_lastHistos_mc_superimp();


  TH1D* h1_data = new TH1D(*(lastHistos_data[0]));
  float xMin = (db->get_xAxisMin()!=9999.) ? db->get_xAxisMin() : h1_data->GetXaxis()->GetXmin();
  float xMax = (db->get_xAxisMax()!=9999.) ? db->get_xAxisMax() : h1_data->GetXaxis()->GetXmax();

  // create data graph (poisson asymm errors):
  TGraphAsymmErrors* graph_data_poisson = new TGraphAsymmErrors(0);
  graph_data_poisson = fitTools::getGraphPoissonErrors(h1_data);
  graph_data_poisson->SetMarkerStyle(20);

  THStack* mc_stack = new THStack();
  for( unsigned ihisto=0; ihisto<lastHistos_mc.size(); ++ihisto ) 
    mc_stack->Add(lastHistos_mc[lastHistos_mc.size()-ihisto-1]);



  std::string sherpa_suffix = (use_sherpa) ? "_sherpa" : "";


  // open fit results file:
  char fitResultsFileName[200];
  sprintf( fitResultsFileName, "fitResultsFile_%s_%dbtag_ALL_PU%s_fit%s%s%s.root", data_dataset.c_str(), nbtags, PUType.c_str(), data_mc.c_str(), sherpa_suffix.c_str(), flags.c_str() );
  TFile* fitResultsFile = TFile::Open(fitResultsFileName);

  // get bg workspace:
  char workspaceName[200];
  sprintf( workspaceName, "fitWorkspace_%dbtag", nbtags );
  RooWorkspace* bgws = (RooWorkspace*)fitResultsFile->Get(workspaceName);
  char fitResultsName[200];
  sprintf( fitResultsName, "fitResults_%dbtag_decorr", nbtags );
  RooFitResult* bgfr = (RooFitResult*)fitResultsFile->Get(fitResultsName);

  // get mZZ variable:
  RooRealVar* CMS_hzz2l2q_mZZ = (RooRealVar*)bgws->var("CMS_hzz2l2q_mZZ");

  // get bg shape:
  RooAbsPdf* background = (RooAbsPdf*)bgws->pdf("background_decorr");


  std::string leptType_cut;
  if( leptType=="MU" ) leptType_cut = "&& leptType==0";
  if( leptType=="ELE" ) leptType_cut = "&& leptType==1";


  SidebandFitter* sf = new SidebandFitter( data_dataset, PUType, data_mc, flags );

  // get bg normalization:
  //float expBkg = sf->get_backgroundNormalization( nbtags, leptType, "DATA" );
  std::pair<Double_t, Double_t> bgNormAndError = sf->get_backgroundNormalizationAndError( nbtags, leptType, "DATA" );
  float expBkg = bgNormAndError.first;
  float expBkg_err = bgNormAndError.second;


  //TTree* treeSidebandsDATA_alphaCorr = (TTree*)fitResultsFile->Get("sidebandsDATA_alpha");
  //TH1D* h1_mZZ_sidebands_alpha = new TH1D("mZZ_sidebands_alpha", "", 65, xMin, xMax);
  //char sidebandsCut_alpha[500];
  //sprintf(sidebandsCut_alpha, "eventWeight_alpha*(isSidebands && nBTags==%d %s)", nbtags, leptType_cut.c_str());
  //treeSidebandsDATA_alphaCorr->Project("mZZ_sidebands_alpha", "CMS_hzz2l2q_mZZ", sidebandsCut_alpha);
  //float expBkg = h1_mZZ_sidebands_alpha->Integral();


  RooPlot *plot_MCbkg = CMS_hzz2l2q_mZZ->frame(xMin,xMax,(int)(xMax-xMin)/h1_data->GetXaxis()->GetBinWidth(1));
  background->plotOn(plot_MCbkg,RooFit::Normalization(expBkg));
  if( suffix == "_turnOnZOOM" && !QUICK_ ) {
    background->plotOn(plot_MCbkg,RooFit::VisualizeError(*bgfr,2.0,kFALSE),RooFit::FillColor(kYellow), RooFit::Normalization(expBkg));
    background->plotOn(plot_MCbkg,RooFit::VisualizeError(*bgfr,1.0,kFALSE),RooFit::FillColor(kGreen), RooFit::Normalization(expBkg));
    background->plotOn(plot_MCbkg,RooFit::Normalization(expBkg));
    background->plotOn(plot_MCbkg,RooFit::LineStyle(2),RooFit::Normalization(expBkg+expBkg_err));
    background->plotOn(plot_MCbkg,RooFit::LineStyle(2),RooFit::Normalization(expBkg-expBkg_err));
  }

  TF1* f1_bgForLegend = new TF1("bgForLegend", "[0]");
  f1_bgForLegend->SetLineColor(kBlue);
  f1_bgForLegend->SetLineWidth(3);
  

  TH2D* h2_axes = new TH2D("axes", "", 10, xMin, xMax, 10, 0., 1.3*h1_data->GetMaximum());
  char yTitle[200];
  sprintf( yTitle, "Events / (%.0f GeV)", h1_data->GetXaxis()->GetBinWidth(1) );
  h2_axes->SetYTitle(yTitle);
  if( leptType=="MU" )
    h2_axes->SetXTitle("m_{#mu#mujj} [GeV]");
  else if( leptType=="ELE" )
    h2_axes->SetXTitle("m_{eejj} [GeV]");
  else
    h2_axes->SetXTitle("m_{ZZ} [GeV]");

  float legend_xMin = 0.38;
  float legend_yMax = 0.91;
  float legend_yMin = legend_yMax - 0.07*6.;
  float legend_xMax = 0.92;

  TLegend* legend = new TLegend(legend_xMin, legend_yMin, legend_xMax, legend_yMax, (db->get_legendTitle()).c_str());
  legend->SetTextSize(0.04);
  legend->SetFillColor(0);
  legend->AddEntry( graph_data_poisson, "Data", "P");
  legend->AddEntry( f1_bgForLegend, "Expected background", "L");
  for( unsigned imc=0; imc<lastHistos_mc.size(); ++imc ) 
    legend->AddEntry( lastHistos_mc[imc], (db->get_mcFile(imc).legendName).c_str(), "F");

  TPaveText* cmsLabel = db->get_labelCMS();
  TPaveText* sqrtLabel = db->get_labelSqrt();


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

  h2_axes->Draw();
  cmsLabel->Draw("same");
  sqrtLabel->Draw("same");
  if( suffix != "_turnOnZOOM" )
    legend->Draw("same");
  mc_stack->Draw("histo same");
  for( unsigned imc=0; imc<lastHistos_mc_superimp.size(); ++imc ) 
    lastHistos_mc_superimp[imc]->Draw("same");
  plot_MCbkg->Draw("same");
  graph_data_poisson->Draw("P same");

  gPad->RedrawAxis();


  
  char canvasName[1000];
  if( leptType=="ALL" )
    sprintf( canvasName, "%s/mZZ_%dbtag_withCurve%s", (db->get_outputdir()).c_str(), nbtags, suffix.c_str() );
  else 
    sprintf( canvasName, "%s/mZZ_%dbtag_withCurve%s_%s", (db->get_outputdir()).c_str(), nbtags, suffix.c_str(), leptType.c_str() );
  std::string canvasName_str(canvasName);
  std::string canvasName_eps = canvasName_str+".eps";
  c1->SaveAs(canvasName_eps.c_str());
  std::string canvasName_root = canvasName_str+".root";
  if( root_aussi_ ) {
    c1->SetFixedAspectRatio(true);
    c1->SaveAs(canvasName_root.c_str());
  }

  c1->Clear();


  legend_yMin = legend_yMax - 0.07*4.;

  TLegend* legend2 = new TLegend(legend_xMin, legend_yMin, legend_xMax, legend_yMax, (db->get_legendTitle()).c_str());
  legend2->SetTextSize(0.04);
  legend2->SetFillColor(0);
  legend2->AddEntry( graph_data_poisson, "Data", "P");
  legend2->AddEntry( f1_bgForLegend, "Expected background", "L");
  for( unsigned imc=0; imc<lastHistos_mc.size(); ++imc ) {
    if( db->get_mcFile(imc).fillColor==kYellow ) //signal only
      legend2->AddEntry( lastHistos_mc[imc], (db->get_mcFile(imc).legendName).c_str(), "F");
  }

  h2_axes->Draw();
  cmsLabel->Draw("same");
  sqrtLabel->Draw("same");
  legend2->Draw("same");
  for( unsigned imc=0; imc<lastHistos_mc.size(); ++imc ) {
    if( db->get_mcFile(imc).fillColor==kYellow ) //signal only
      lastHistos_mc[imc]->Draw("same");
  }
  plot_MCbkg->Draw("same");
  graph_data_poisson->Draw("P same");

  gPad->RedrawAxis();


  
  if( leptType=="ALL" )
    sprintf( canvasName, "%s/mZZ_%dbtag_withCurve_noMC%s", (db->get_outputdir()).c_str(), nbtags, suffix.c_str() );
  else 
    sprintf( canvasName, "%s/mZZ_%dbtag_withCurve_noMC%s_%s", (db->get_outputdir()).c_str(), nbtags, suffix.c_str(), leptType.c_str() );
  std::string canvasName2_str(canvasName);
  std::string canvasName2_eps = canvasName2_str+".eps";
  c1->SaveAs(canvasName2_eps.c_str());

  c1->Clear();






  c1->SetLogy();

  TLegend* legend_log = new TLegend(0.6, legend_yMin, legend_xMax, legend_yMax, (db->get_legendTitle()).c_str());
  legend_log->SetTextSize(0.04);
  legend_log->SetFillColor(0);
  legend_log->AddEntry( graph_data_poisson, "Data", "P");
  legend_log->AddEntry( f1_bgForLegend, "Exp. BG", "L");
  for( unsigned imc=0; imc<lastHistos_mc.size(); ++imc ) 
    legend_log->AddEntry( lastHistos_mc[imc], (db->get_mcFile(imc).legendName).c_str(), "F");



  TH2D* h2_axes_log = new TH2D("axes_log", "", 10, xMin, xMax, 10, 0.05, 200.*h1_data->GetMaximum());
  h2_axes_log->SetYTitle(yTitle);
  h2_axes_log->SetXTitle("m_{ZZ} [GeV]");
  h2_axes_log->GetYaxis()->SetNoExponent();

  h2_axes_log->Draw();
  cmsLabel->Draw("same");
  sqrtLabel->Draw("same");
  legend_log->Draw("same");
  mc_stack->Draw("histo same");
  plot_MCbkg->Draw("same");
  graph_data_poisson->Draw("P same");

  gPad->RedrawAxis();

  std::string canvasName_log_eps = canvasName_str+"_log.eps";
  c1->SaveAs(canvasName_log_eps.c_str());

  delete sf;
  delete h2_axes;
  delete h2_axes_log;
  delete c1;

}
Beispiel #13
0
void StandardHypoTestDemo(const char* infile = "",
                          const char* workspaceName = "combined",
                          const char* modelSBName = "ModelConfig",
                          const char* modelBName = "",
                          const char* dataName = "obsData",
                          int calcType = 0, // 0 freq 1 hybrid, 2 asymptotic
                          int testStatType = 3,   // 0 LEP, 1 TeV, 2 LHC, 3 LHC - one sided
                          bool newHypoTest = true,
                          int ntoys = 5000,
                          const char* hypoTestGraphFile = "hypoTestGraph.root",
                          bool useNC = false,
                          const char * nuisPriorName = 0)
{

/*

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

  type = 0 Freq calculator
  type = 1 Hybrid calculator
  type = 2 Asymptotic calculator

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

  ntoys:         number of toys to use

  useNumberCounting:  set to true when using number counting events

  nuisPriorName:   name of prior for the nnuisance. This is often expressed as constraint term in the global model
  It is needed only when using the HybridCalculator (type=1)
  If not given by default the prior pdf from ModelConfig is used.

  extra options are available as global paramwters of the macro. They major ones are:

  generateBinned       generate binned data sets for toys (default is false) - be careful not to activate with
  a too large (>=3) number of observables
  nToyRatio            ratio of S+B/B toys (default is 2)
  printLevel

*/

   // disable - can cause some problems
   //ToyMCSampler::SetAlwaysUseMultiGen(true);

   SimpleLikelihoodRatioTestStat::SetAlwaysReuseNLL(true);
   ProfileLikelihoodTestStat::SetAlwaysReuseNLL(true);
   RatioOfProfiledLikelihoodsTestStat::SetAlwaysReuseNLL(true);

   //RooRandom::randomGenerator()->SetSeed(0);

   // to change minimizers
   // ROOT::Math::MinimizerOptions::SetDefaultStrategy(0);
   // ROOT::Math::MinimizerOptions::SetDefaultMinimizer("Minuit2");
   // ROOT::Math::MinimizerOptions::SetDefaultTolerance(1);

  /////////////////////////////////////////////////////////////
  // 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;
  }
  w->Print();

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


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

  // make sure ingredients are found
  if(!data || !sbModel){
    w->Print();
    cout << "data or ModelConfig was not found" <<endl;
    return;
  }
  // make b model
  ModelConfig* bModel = (ModelConfig*) w->obj(modelBName);


   // case of no systematics
   // remove nuisance parameters from model
   if (noSystematics) {
      const RooArgSet * nuisPar = sbModel->GetNuisanceParameters();
      if (nuisPar && nuisPar->getSize() > 0) {
         std::cout << "StandardHypoTestInvDemo" << "  -  Switch off all systematics by setting them constant to their initial values" << std::endl;
         RooStats::SetAllConstant(*nuisPar);
      }
      if (bModel) {
         const RooArgSet * bnuisPar = bModel->GetNuisanceParameters();
         if (bnuisPar)
            RooStats::SetAllConstant(*bnuisPar);
      }
   }


  if (!bModel ) {
      Info("StandardHypoTestInvDemo","The background model %s does not exist",modelBName);
      Info("StandardHypoTestInvDemo","Copy it from ModelConfig %s and set POI to zero",modelSBName);
      bModel = (ModelConfig*) sbModel->Clone();
      bModel->SetName(TString(modelSBName)+TString("B_only"));
      RooRealVar * var = dynamic_cast<RooRealVar*>(bModel->GetParametersOfInterest()->first());
      if (!var) return;
      double oldval = var->getVal();
      var->setVal(0);
      //bModel->SetSnapshot( RooArgSet(*var, *w->var("lumi"))  );
      bModel->SetSnapshot( RooArgSet(*var)  );
      var->setVal(oldval);
  }

   if (!sbModel->GetSnapshot() || poiValue > 0) {
      Info("StandardHypoTestDemo","Model %s has no snapshot  - make one using model poi",modelSBName);
      RooRealVar * var = dynamic_cast<RooRealVar*>(sbModel->GetParametersOfInterest()->first());
      if (!var) return;
      double oldval = var->getVal();
      if (poiValue > 0)  var->setVal(poiValue);
      //sbModel->SetSnapshot( RooArgSet(*var, *w->var("lumi") ) );
      sbModel->SetSnapshot( RooArgSet(*var) );
      if (poiValue > 0) var->setVal(oldval);
      //sbModel->SetSnapshot( *sbModel->GetParametersOfInterest() );
   }





   // part 1, hypothesis testing
   SimpleLikelihoodRatioTestStat * slrts = new SimpleLikelihoodRatioTestStat(*bModel->GetPdf(), *sbModel->GetPdf());
   // null parameters must includes snapshot of poi plus the nuisance values
   RooArgSet nullParams(*bModel->GetSnapshot()); //Obtains parameters of the null Hypothesis
   if (bModel->GetNuisanceParameters()) nullParams.add(*bModel->GetNuisanceParameters()); //Add nuisance parameters to the null hypothesis

   slrts->SetNullParameters(nullParams);
   RooArgSet altParams(*sbModel->GetSnapshot()); //Obtains parameters of the alternate Hypothesis
   if (sbModel->GetNuisanceParameters()) altParams.add(*sbModel->GetNuisanceParameters());//Add nuisance parameters to the alternate    hypothesis
   slrts->SetAltParameters(altParams);


   ProfileLikelihoodTestStat * profll = new ProfileLikelihoodTestStat(*bModel->GetPdf());


   RatioOfProfiledLikelihoodsTestStat *
      ropl = new RatioOfProfiledLikelihoodsTestStat(*bModel->GetPdf(), *sbModel->GetPdf(), sbModel->GetSnapshot());
   ropl->SetSubtractMLE(false);

   if (testStatType == 3) profll->SetOneSidedDiscovery(1);
   profll->SetPrintLevel(printLevel);

   // profll.SetReuseNLL(mOptimize);
   // slrts.SetReuseNLL(mOptimize);
   // ropl.SetReuseNLL(mOptimize);

   AsymptoticCalculator::SetPrintLevel(printLevel);

   HypoTestCalculatorGeneric *  hypoCalc = 0;
   // note here Null is B and Alt is S+B
   if (calcType == 0) hypoCalc = new  FrequentistCalculator(*data, *sbModel, *bModel);
   else if (calcType == 1) hypoCalc= new  HybridCalculator(*data, *sbModel, *bModel);
   else if (calcType == 2) hypoCalc= new  AsymptoticCalculator(*data, *sbModel, *bModel);

   if (calcType == 0)
       ((FrequentistCalculator*)hypoCalc)->SetToys(ntoys, ntoys/nToysRatio);
   if (calcType == 1)
       ((HybridCalculator*)hypoCalc)->SetToys(ntoys, ntoys/nToysRatio);
   if (calcType == 2 ) {
      if (testStatType == 3) ((AsymptoticCalculator*) hypoCalc)->SetOneSidedDiscovery(true);
      if (testStatType != 2 && testStatType != 3)
         Warning("StandardHypoTestDemo","Only the PL test statistic can be used with AsymptoticCalculator - use by default a two-sided PL");


   }


   // check for nuisance prior pdf in case of nuisance parameters
   if (calcType == 1 && (bModel->GetNuisanceParameters() || sbModel->GetNuisanceParameters() )) {
         RooAbsPdf * nuisPdf = 0;
         if (nuisPriorName) nuisPdf = w->pdf(nuisPriorName);
         // use prior defined first in bModel (then in SbModel)
         if (!nuisPdf)  {
            Info("StandardHypoTestDemo","No nuisance pdf given for the HybridCalculator - try to deduce  pdf from the   model");
            if (bModel->GetPdf() && bModel->GetObservables() )
               nuisPdf = RooStats::MakeNuisancePdf(*bModel,"nuisancePdf_bmodel");
            else
               nuisPdf = RooStats::MakeNuisancePdf(*sbModel,"nuisancePdf_sbmodel");
         }
         if (!nuisPdf ) {
            if (bModel->GetPriorPdf())  {
               nuisPdf = bModel->GetPriorPdf();
               Info("StandardHypoTestDemo","No nuisance pdf given - try to use %s that is defined as a prior pdf in the B model",nuisPdf->GetName());
            }
            else {
               Error("StandardHypoTestDemo","Cannnot run Hybrid calculator because no prior on the nuisance parameter is specified or can be derived");
               return;
            }
         }
         assert(nuisPdf);
         Info("StandardHypoTestDemo","Using as nuisance Pdf ... " );
         nuisPdf->Print();

         const RooArgSet * nuisParams = (bModel->GetNuisanceParameters() ) ? bModel->GetNuisanceParameters() : sbModel->GetNuisanceParameters();
         RooArgSet * np = nuisPdf->getObservables(*nuisParams);
         if (np->getSize() == 0) {
            Warning("StandardHypoTestDemo","Prior nuisance does not depend on nuisance parameters. They will be smeared in their full range");
         }
         delete np;

         ((HybridCalculator*)hypoCalc)->ForcePriorNuisanceAlt(*nuisPdf);
         ((HybridCalculator*)hypoCalc)->ForcePriorNuisanceNull(*nuisPdf);
   }

   // hypoCalc->ForcePriorNuisanceAlt(*sbModel->GetPriorPdf());
   // hypoCalc->ForcePriorNuisanceNull(*bModel->GetPriorPdf());

   ToyMCSampler * sampler = (ToyMCSampler *)hypoCalc->GetTestStatSampler();

   if (sampler && (calcType == 0 || calcType == 1) ) {

      // look if pdf is number counting or extended
      if (sbModel->GetPdf()->canBeExtended() ) {
         if (useNC)   Warning("StandardHypoTestDemo","Pdf is extended: but number counting flag is set: ignore it ");
      }
      else {
         // for not extended pdf
         if (!useNC)  {
            int nEvents = data->numEntries();
            Info("StandardHypoTestDemo","Pdf is not extended: number of events to generate taken  from observed data set is %d",nEvents);
            sampler->SetNEventsPerToy(nEvents);
         }
         else {
            Info("StandardHypoTestDemo","using a number counting pdf");
            sampler->SetNEventsPerToy(1);
         }
      }

      if (data->isWeighted() && !generateBinned) {
         Info("StandardHypoTestDemo","Data set is weighted, nentries = %d and sum of weights = %8.1f but toy generation is unbinned - it would be faster to set generateBinned to true\n",data->numEntries(), data->sumEntries());
      }
      if (generateBinned)  sampler->SetGenerateBinned(generateBinned);


      // set the test statistic
      if (testStatType == 0) sampler->SetTestStatistic(slrts);
      if (testStatType == 1) sampler->SetTestStatistic(ropl);
      if (testStatType == 2 || testStatType == 3) sampler->SetTestStatistic(profll);

   }

   HypoTestResult *  htr = hypoCalc->GetHypoTest();
   htr->SetPValueIsRightTail(true);
   htr->SetBackgroundAsAlt(false);
   htr->Print(); // how to get meaningfull CLs at this point?

   delete sampler;
   delete slrts;
   delete ropl;
   delete profll;

   if (calcType != 2) {
      HypoTestPlot * plot = new HypoTestPlot(*htr,100);
      plot->SetLogYaxis(true);
      plot->Draw();
      plot->SamplingDistPlot::DumpToFile(hypoTestGraphFile,"RECREATE");
   }
   else {
      std::cout << "Asymptotic results " << std::endl;

   }

   // look at expected significances
   // found median of S+B distribution
   if (calcType != 2) {

      SamplingDistribution * altDist = htr->GetAltDistribution();
      HypoTestResult htExp("Expected Result");
      htExp.Append(htr);
      // find quantiles in alt (S+B) distribution
      double p[5];
      double q[5];
      for (int i = 0; i < 5; ++i) {
         double sig = -2  + i;
         p[i] = ROOT::Math::normal_cdf(sig,1);
      }
      std::vector<double> values = altDist->GetSamplingDistribution();
      TMath::Quantiles( values.size(), 5, &values[0], q, p, false);

      for (int i = 0; i < 5; ++i) {
         htExp.SetTestStatisticData( q[i] );
         double sig = -2  + i;
         std::cout << " Expected p -value and significance at " << sig << " sigma = "
                   << htExp.NullPValue() << " significance " << htExp.Significance() << " sigma " << std::endl;

      }
   }
   else {
      // case of asymptotic calculator
      for (int i = 0; i < 5; ++i) {
         double sig = -2  + i;
         // sigma is inverted here
         double pval = AsymptoticCalculator::GetExpectedPValues( htr->NullPValue(), htr->AlternatePValue(), -sig, false);
         std::cout << " Expected p -value and significance at " << sig << " sigma = "
                   << pval << " significance " << ROOT::Math::normal_quantile_c(pval,1) << " sigma " << std::endl;

      }
   }
    
    ////////////////////////////////////////////////////////////////////////////////////////////////
    //      FROM HERE ON IT HAS BEEN MODIFIED TO SAVE THE RESULTS IN TREES IN A .ROOT FILE
    
    
    //Declare the variable in which the hypothesis test results will be stored
    Double_t p_value, significance_t, cl_b, cl_sb, cl_s ;

    
    if(newHypoTest){
        
        TNtuple *resultsHypoTest = new TNtuple("resultsHypoTest", "resultsHypoTest", "p_value:significance_t:cl_b:cl_sb:cl_s");
        
        //Store the current results
        resultsHypoTest->Fill(htr->NullPValue(),htr->Significance(),htr->CLb(),htr->CLsplusb(),htr->CLs()) ;
        
        // Save the NTuple  to a .root file
        TFile* f_hypoTestResults = new TFile("resultsHypoTestDisc.root","RECREATE") ;
        resultsHypoTest->Write() ;
        f_hypoTestResults->Close() ;
    }
    else{
        // Open the .root that contains the NTuple and add the newly calculated results
        TFile* f_hypoTestResults = new TFile("resultsHypoTestDisc.root","UPDATE") ;

        //Get the NTuple from the file
        TNtuple *resultsHypoTest = (TNtuple*)f_hypoTestResults->Get("resultsHypoTest");
        
        resultsHypoTest->Fill(htr->NullPValue(),htr->Significance(),htr->CLb(),htr->CLsplusb(),htr->CLs()) ;
        
        //IF YOU WANT A DIFFERENT BRANCH FOR EACH TEST
        resultsHypoTest->Write();
        f_hypoTestResults->Close();
        //*/
        
        /*// IF YOU ONLY WNAT ONE BRANCH WITH ALL VALUES INSIDE IT. keep the latest ntuple header only
        resultsHypoTest->Write("",TObject::kOverwrite);
        f_hypoTestResults->Close();
        //*/
    }
    
}
Beispiel #14
0
	void fitpeaks(int bin){
		switch (bin)
		{
			case 0:
				cut_="abs(upsRapidity)<2.4";
				//cut_="( (muPlusPt>3.5 && abs(muPlusEta)<1.6) || (muPlusPt>2.5 && abs(muPlusEta)>=1.6 && abs(muPlusEta)<2.4) ) && ( (muMinusPt>3.5 && abs(muMinusEta)<1.6) || (muMinusPt>2.5 && abs(muMinusEta)>=1.6 && abs(muMinusEta)<2.4) ) && abs(upsRapidity)<2.0";   //pp acceptance for Upsilon 
				suffix_="";
				f2Svs1S_pp->setVal(0.5569);
				//f2Svs1S_pp->setVal(0);
				f3Svs1S_pp->setVal(0.4140);
				//f3Svs1S_pp->setVal(0);
				break;
			case 1:
				cut_="abs(upsRapidity)>=0.0 && abs(upsRapidity)<1.2";
				suffix_="_eta0-12"; binw_=0.14;
				break;
			case 2:
				cut_="abs(upsRapidity)>=1.2 && abs(upsRapidity)<2.4";
				suffix_="_eta12-24"; binw_=0.14;
				break;
			case 3:
				cut_="Centrality>=0 && Centrality<2";
				suffix_="_cntr0-5"; binw_=0.14;
				break;
			case 4:
				cut_="Centrality>=2 && Centrality<4";
				suffix_="_cntr5-10"; binw_=0.14;
				break;
			case 5:
				cut_="Centrality>=4 && Centrality<8";
				suffix_="_cntr10-20"; binw_=0.14;
				break;
			case 6:
				cut_="Centrality>=8 && Centrality<12";
				suffix_="_cntr20-30"; binw_=0.14;
				break;
			case 7:
				cut_="Centrality>=12 && Centrality<16";
				suffix_="_cntr30-40"; binw_=0.14;
				break;
			case 8:
				cut_="Centrality>=16 && Centrality<20";
				suffix_="_cntr40-50"; binw_=0.14;
				break;
			case 9:
				cut_="Centrality>=20 && Centrality<50";
				suffix_="_cntr50-100"; binw_=0.14;
				break;
			case 10:
				cut_="Centrality>=20 && Centrality<24";
				suffix_="_cntr50-60"; binw_=0.14;
				break;
			case 11:
				cut_="Centrality>=0 && Centrality<8";
				suffix_="_cntr0-20"; binw_=0.1;
				break;
			case 12:
				cut_="Centrality>=16 && Centrality<50";
				suffix_="_cntr40-100"; binw_=0.14;
				break;
			case 13:
				cut_="Centrality>=8 && Centrality<50";
				suffix_="_cntr20-100"; binw_=0.1;
				break;
			default:
				cout<<"error in binning"<<endl;
				break;
		}

		cout << "oniafitter processing"
			<< "\n\tInput:  \t" << finput
			<< "\n\tresults:\t" << figs_
			<< endl;
		ofstream outfile("fitresults.out", ios_base::app);
		outfile<<endl<<"**********"<<suffix_<<"**********"<<endl<<endl;

		//read the data
		TFile f(finput,"read");
		gDirectory->Cd(finput+":/"+dirname_);
		TTree* theTree     = (TTree*)gROOT->FindObject("UpsilonTree");
		TTree* allsignTree     = (TTree*)gROOT->FindObject("UpsilonTree_allsign");
		if (PR_plot) {TRKROT = 1; PbPb=1;}
		if (TRKROT) TTree* trkRotTree = (TTree*)gROOT->FindObject("UpsilonTree_trkRot");

		RooRealVar* mass  = new RooRealVar("invariantMass","#mu#mu mass",mmin_,mmax_,"GeV/c^{2}");
		RooRealVar* upsPt  = new RooRealVar("upsPt","p_{T}(#Upsilon)",0,60,"GeV");
		RooRealVar* upsEta = new RooRealVar("upsEta",  "upsEta"  ,-7,7);
		RooRealVar* upsRapidity = new RooRealVar("upsRapidity",  "upsRapidity"  ,-2.4,2.4);
		RooRealVar* vProb = new RooRealVar("vProb",  "vProb"  ,0.05,1.00);
		RooRealVar* QQsign = new RooRealVar("QQsign",  "QQsign"  ,-1,5);
		RooRealVar* weight = new RooRealVar("weight",  "weight"  ,-2,2);
		if (PbPb) RooRealVar* Centrality = new RooRealVar("Centrality",  "Centrality"  ,0,40);
		RooRealVar* muPlusPt = new RooRealVar("muPlusPt","muPlusPt",muonpTcut,50);
		RooRealVar* muPlusEta = new RooRealVar("muPlusEta","muPlusEta",-2.5,2.5);
		RooRealVar* muMinusPt = new RooRealVar("muMinusPt","muMinusPt",muonpTcut,50);
		RooRealVar* muMinusEta = new RooRealVar("muMinusEta","muMinusEta",-2.5,2.5);


		//import unlike-sign data set
		RooDataSet* data0, *data, *likesignData0, *likesignData, *TrkRotData0, *TrkRotData;
		if (PbPb) data0 = new RooDataSet("data","data",theTree,RooArgSet(*mass,*upsRapidity,*vProb,*upsPt,*Centrality,*muPlusPt,*muMinusPt));
		//data0 = new RooDataSet("data","data",theTree,RooArgSet(*mass,*upsRapidity,*upsPt,*muPlusPt,*muMinusPt,*QQsign,*weight));
		else data0 = new RooDataSet("data","data",theTree,RooArgSet(*mass,*upsRapidity,*vProb,*upsPt,*muPlusPt,*muMinusPt,*muPlusEta,*muMinusEta));
		data0->Print();
		data = ( RooDataSet*) data0->reduce(Cut(cut_));
		data->Print();

		//import like-sign data set
		if (PbPb) likesignData0 = new RooDataSet("likesignData","likesignData",allsignTree,RooArgSet(*mass,*upsRapidity,*vProb,*upsPt,*Centrality,*muPlusPt,*muMinusPt,*QQsign));
		else likesignData0 = new RooDataSet("likesignData","likesignData",allsignTree,RooArgSet(*mass,*upsRapidity,*vProb,*upsPt,*muPlusPt,*muMinusPt,*QQsign));
		likesignData0->Print();
		likesignData = ( RooDataSet*) likesignData0->reduce(Cut(cut_+" && QQsign != 0"));
		likesignData->Print();


		//import track-rotation data set
		if (TRKROT) {
			if (PbPb) TrkRotData0 = new RooDataSet("TrkRotData","TrkRotData",trkRotTree,RooArgSet(*mass,*upsRapidity,*vProb,*upsPt,*Centrality,*muPlusPt,*muMinusPt,*QQsign));
			else TrkRotData0 = new RooDataSet("TrkRotData","TrkRotData",trkRotTree,RooArgSet(*mass,*upsRapidity,*upsPt,*vProb,*muPlusPt,*muMinusPt,*QQsign));
			TrkRotData0->Print();
			if (PR_plot && RAA) TrkRotData = ( RooDataSet*) TrkRotData0->reduce(Cut(cut_+" && upsPt < 8.1"));
			else if (PR_plot && !RAA) TrkRotData = ( RooDataSet*) TrkRotData0->reduce(Cut(cut_+" && upsPt < 7.07"));
			else TrkRotData = ( RooDataSet*) TrkRotData0->reduce(Cut(cut_+" && QQsign != 0"));
			TrkRotData->Print();
		}

		mass->setRange("R1",7.0,10.2);
		mass->setRange("R2",7,14);
		mass->setRange("R3",10.8,14);
		const double M1S = 9.46;   //upsilon 1S pgd mass value
		const double M2S = 10.02;  //upsilon 2S pgd mass value
		const double M3S = 10.35;  //upsilon 3S pgd mass value

		RooRealVar *mean    = new RooRealVar("#mu_{#Upsilon(1S)}","#Upsilon mean",M1S,M1S-0.1,M1S+0.1);
		RooRealVar *shift21 = new RooRealVar("shift2","mass diff #Upsilon(1,2S)",M2S-M1S);
		RooRealVar *shift31 = new RooRealVar("shift3","mass diff #Upsilon(1,3S)",M3S-M1S);
		RooRealVar *mscale  = new RooRealVar("mscale","mass scale factor",1.,0.7,1.3);
		mscale->setConstant(kTRUE); /* the def. parameter value is fixed in the fit */
		RooFormulaVar *mean1S = new RooFormulaVar("mean1S","@0",
				RooArgList(*mean));
		RooFormulaVar *mean2S = new RooFormulaVar("mean2S","@0+@1*@2",
				RooArgList(*mean,*mscale,*shift21));
		RooFormulaVar *mean3S = new RooFormulaVar("mean3S","@0+@1*@2",
				RooArgList(*mean,*mscale,*shift31));

		RooRealVar *sigma1 = new RooRealVar("sigma","Sigma_1",0.10,0.01,0.30);    //detector resolution
		RooRealVar *sigma2 = new RooRealVar("#sigma_{#Upsilon(1S)}","Sigma_1S",0.08,0.01,0.30); //Y(1S) resolution
		RooFormulaVar *reso1S = new RooFormulaVar("reso1S","@0"             ,RooArgList(*sigma2));
		RooFormulaVar *reso2S = new RooFormulaVar("reso2S","@0*10.023/9.460",RooArgList(*sigma2));
		RooFormulaVar *reso3S = new RooFormulaVar("reso3S","@0*10.355/9.460",RooArgList(*sigma2));

		/// to describe final state radiation tail on the left of the peaks
		RooRealVar *alpha  = new RooRealVar("alpha","tail shift",0.982,0,2.4);   // minbias fit value
		//RooRealVar *alpha  = new RooRealVar("alpha","tail shift",1.6,0.2,4);   // MC value
		RooRealVar *npow   = new RooRealVar("npow","power order",2.3,1,3);       // MC value
		npow ->setConstant(kTRUE);
		if (!fitMB) alpha->setConstant(kTRUE);
		// relative fraction of the two peak components 
		RooRealVar *sigmaFraction = new RooRealVar("sigmaFraction","Sigma Fraction",0.3,0.,1.);
		sigmaFraction->setVal(0);
		sigmaFraction->setConstant(kTRUE);

		/// Upsilon 1S
		//RooCBShape  *gauss1S1 = new RooCBShape ("gauss1S1", "FSR cb 1s",
		//                  *mass,*mean1S,*sigma1,*alpha,*npow);
		RooCBShape  *gauss1S2 = new RooCBShape ("gauss1S2", "FSR cb 1s",
				*mass,*mean1S,*reso1S,*alpha,*npow);
		//RooAddPdf *sig1S      = new RooAddPdf  ("sig1S","1S mass pdf",
		//                  RooArgList(*gauss1S1,*gauss1S2),*sigmaFraction);

		//mean->setVal(9.46);
		//mean->setConstant(kTRUE);
		sigma1->setVal(0);
		sigma1->setConstant(kTRUE);
		if (!fitMB) {
			sigma2->setVal(width_);        //fix the resolution
			sigma2->setConstant(kTRUE);
		}
		/// Upsilon 2S
		RooCBShape  *gauss2S1 = new RooCBShape ("gauss2S1", "FSR cb 2s", 
				*mass,*mean2S,*sigma1,*alpha,*npow); 
		RooCBShape  *gauss2S2 = new RooCBShape ("gauss2S2", "FSR cb 2s", 
				*mass,*mean2S,*reso2S,*alpha,*npow); 
		RooAddPdf *sig2S      = new RooAddPdf  ("sig2S","2S mass pdf",
				RooArgList(*gauss2S1,*gauss2S2),*sigmaFraction);

		/// Upsilon 3S
		RooCBShape  *gauss3S1 = new RooCBShape ("gauss3S1", "FSR cb 3s", 
				*mass,*mean3S,*sigma1,*alpha,*npow); 
		RooCBShape  *gauss3S2 = new RooCBShape ("gauss3S2", "FSR cb 3s", 
				*mass,*mean3S,*reso3S,*alpha,*npow); 
		RooAddPdf *sig3S      = new RooAddPdf  ("sig3S","3S mass pdf",
				RooArgList(*gauss3S1,*gauss3S2),*sigmaFraction);

		/// Background
		RooRealVar *bkg_a1  = new RooRealVar("bkg_{a1}", "background a1", 0, -2, 2);
		RooRealVar *bkg_a2  = new RooRealVar("bkg_{a2}", "background a2", 0, -1, 1);
		//RooRealVar *bkg_a3  = new RooRealVar("bkg_{a3}", "background a3", 0, -1, 1);
		RooAbsPdf  *bkgPdf  = new RooChebychev("bkg","background",
				*mass, RooArgList(*bkg_a1,*bkg_a2));
		//bkg_a1->setVal(0);
		//bkg_a1->setConstant(kTRUE);
		//bkg_a2->setVal(0);
		//bkg_a2->setConstant(kTRUE); //set constant for liner background

		// only sideband region pdf, using RooPolynomial instead of RooChebychev for multiple ranges fit
		RooRealVar *SB_bkg_a1  = new RooRealVar("SB bkg_{a1}", "background a1", 0, -1, 1);
		RooRealVar *SB_bkg_a2  = new RooRealVar("SB bkg_{a2}", "background a2", 0, -1, 1);
		RooAbsPdf  *SB_bkgPdf  = new RooPolynomial("SB_bkg","side-band background",
				*mass, RooArgList(*SB_bkg_a1,*SB_bkg_a2));
		//SB_bkg_a1->setVal(0);
		//SB_bkg_a1->setConstant(kTRUE);
		//SB_bkg_a2->setVal(0);
		//SB_bkg_a2->setConstant(kTRUE);

		/// Combined pdf
		int nt = 100000;
		//bool fitfraction = true;
		RooRealVar *nbkgd = new RooRealVar("N_{bkg}","nbkgd",nt*0.75,0,10*nt);
		RooRealVar *SB_nbkgd = new RooRealVar("SB N_{bkg}","SB_nbkgd",nt*0.75,0,10*nt);
		RooRealVar *nsig1f  = new RooRealVar("N_{#Upsilon(1S)}","nsig1S",nt*0.25,0,10*nt);
		/*
		//use the YIELDs of 2S and 3S as free parameters
		RooRealVar *nsig2f  = new RooRealVar("N_{#Upsilon(2S)}","nsig2S",   nt*0.25,-1*nt,10*nt);
		RooRealVar *nsig3f  = new RooRealVar("N_{#Upsilon(3S)}","nsig3S",   nt*0.25,-1*nt,10*nt);
		 */
		//use the RATIOs of 2S and 3S as free parameters
		RooRealVar *f2Svs1S = new RooRealVar("N_{2S}/N_{1S}","f2Svs1S",0.21,-0.1,1);
		//RooRealVar *f3Svs1S = new RooRealVar("N_{3S}/N_{1S}","f3Svs1S",0.0,-0.1,0.5);
		RooRealVar *f23vs1S = new RooRealVar("N_{2S+3S}/N_{1S}","f23vs1S",0.45,-0.1,1);
		RooFormulaVar *nsig2f = new RooFormulaVar("nsig2S","@0*@1", RooArgList(*nsig1f,*f2Svs1S));
		//RooFormulaVar *nsig3f = new RooFormulaVar("nsig3S","@0*@1", RooArgList(*nsig1f,*f3Svs1S));
		RooFormulaVar *nsig3f = new RooFormulaVar("nsig3S","@0*@2-@0*@1", RooArgList(*nsig1f,*f2Svs1S,*f23vs1S));

		//f3Svs1S->setConstant(kTRUE);

		//force the ratio to the pp value
		f2Svs1S_pp->setConstant(kTRUE);
		f3Svs1S_pp->setConstant(kTRUE);
		RooFormulaVar *nsig2f_ = new RooFormulaVar("nsig2S_pp","@0*@1", RooArgList(*nsig1f,*f2Svs1S_pp)); 
		RooFormulaVar *nsig3f_ = new RooFormulaVar("nsig3S_pp","@0*@1", RooArgList(*nsig1f,*f3Svs1S_pp)); 

		//only sideband region pdf, using RooPolynomial instead of RooChebychev for multiple ranges fit
		RooAbsPdf  *SB_pdf = new RooAddPdf ("SB_pdf","sideband background pdf",
				RooArgList(*SB_bkgPdf),
				RooArgList(*SB_nbkgd));
		//only signal region pdf, using RooPolynomial instead of RooChebychev for multiple ranges fit
		RooAbsPdf  *S_pdf   = new RooAddPdf ("S_pdf","total signal+background pdf",
				RooArgList(*gauss1S2,*sig2S,*sig3S,*SB_bkgPdf),
				RooArgList(*nsig1f,*nsig2f,*nsig3f,*SB_nbkgd));

		//parameters for likesign
		RooRealVar m0shift("turnOn","turnOn",8.6,0,20.) ;
		RooRealVar width("width","width",2.36,0,20.) ;
		RooRealVar par3("decay","decay",6.8, 0, 20.) ;
		RooGaussian* m0shift_constr;
		RooGaussian* width_constr;
		RooGaussian* par3_constr;

		RooRealVar *nLikesignbkgd = new RooRealVar("NLikesign_{bkg}","nlikesignbkgd",nt*0.75,0,10*nt);
		if (TRKROT) {
			nLikesignbkgd->setVal(TrkRotData->sumEntries());
			nLikesignbkgd->setError(sqrt(TrkRotData->sumEntries()));
		}
		else {
			nLikesignbkgd->setVal(likesignData->sumEntries());
			nLikesignbkgd->setError(sqrt(likesignData->sumEntries()));
		}

		if (LS_constrain) {
			RooGaussian* nLikesignbkgd_constr = new RooGaussian("nLikesignbkgd_constr","nLikesignbkgd_constr",*nLikesignbkgd,RooConst(nLikesignbkgd->getVal()),RooConst(nLikesignbkgd->getError()));
		}
		else nLikesignbkgd->setConstant(kTRUE);

		RooFormulaVar *nResidualbkgd = new RooFormulaVar("NResidual_{bkg}","@0-@1",RooArgList(*nbkgd,*nLikesignbkgd));

		switch (bkgdModel) {
			case 1 :  //use error function to fit the like-sign, then fix the shape and normailization, 
				RooGenericPdf *LikeSignPdf = new  RooGenericPdf("Like-sign","likesign","exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",RooArgList(*mass,m0shift,width,par3));
				if (TRKROT) RooFitResult* fit_1st = LikeSignPdf->fitTo(*TrkRotData,Save()) ;
				else RooFitResult* fit_1st = LikeSignPdf->fitTo(*likesignData,Save()) ; // likesign data
				//LikeSignPdf.fitTo(*data) ;       // unlikesign data    
				//fit_1st->Print();
				if (LS_constrain) {
					m0shift_constr = new RooGaussian("m0shift_constr","m0shift_constr",m0shift,RooConst(m0shift.getVal()),RooConst(m0shift.getError()));
					width_constr = new RooGaussian("width_constr","width_constr",width,RooConst(width.getVal()),RooConst(width.getError()));
					par3_constr = new RooGaussian("par3_constr","par3_constr",par3,RooConst(par3.getVal()),RooConst(par3.getError()));
					//m0shift_constr = new RooGaussian("m0shift_constr","m0shift_constr",m0shift,RooConst(7.9),RooConst(0.34*2));
					//width_constr = new RooGaussian("width_constr","width_constr",width,RooConst(2.77),RooConst(0.38*2));
					//par3_constr = new RooGaussian("par3_constr","par3_constr",par3,RooConst(6.3),RooConst(1.0*2));
				}
				else {
					m0shift.setConstant(kTRUE);
					width.setConstant(kTRUE);
					par3.setConstant(kTRUE);
				}
				RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("pdf_combinedbkgd","total combined background pdf",
						RooArgList(*bkgPdf,*LikeSignPdf),
						RooArgList(*nResidualbkgd,*nLikesignbkgd));
				//RooArgList(*LikeSignPdf),
				//RooArgList(*nbkgd));
				break;

			case 2 : //use RooKeysPdf to smooth the like-sign, then fix the shape and normailization
				if (TRKROT) RooKeysPdf *LikeSignPdf = new RooKeysPdf("Like-sign","likesign",*mass,*TrkRotData,3,1.5);
				else RooKeysPdf *LikeSignPdf = new RooKeysPdf("Like-sign","likesign",*mass,*likesignData,3,1.7);
				RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("pdf_combinedbkgd","total combined background pdf",
						RooArgList(*bkgPdf,*LikeSignPdf),
						RooArgList(*nResidualbkgd,*nLikesignbkgd));
				break;

			case 3 : //use error function to fit the unlike-sign directly
				RooGenericPdf *LikeSignPdf = new  RooGenericPdf("Like-sign","likesign","exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",RooArgList(*mass,m0shift,width,par3));
				RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("pdf_combinedbkgd","total combined background pdf",
						RooArgList(*LikeSignPdf),
						RooArgList(*nbkgd));
				break;

			case 4 : //use polynomial to fit the unlike-sign directly
				RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("pdf_combinedbkgd","total combined background pdf",
						RooArgList(*bkgPdf),
						RooArgList(*nbkgd));
				break;


			case 5 : //use ( error function + polynomial ) to fit the unlike-sign directly
				RooGenericPdf *LikeSignPdf = new  RooGenericPdf("Like-sign","likesign","exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",RooArgList(*mass,m0shift,width,par3));
				RooAbsPdf  *pdf_combinedbkgd   = new RooAddPdf ("pdf_combinedbkgd","total combined background pdf",
						RooArgList(*bkgPdf,*LikeSignPdf),
						RooArgList(*nResidualbkgd,*nLikesignbkgd));
				break;

			default :
				break;
		}

		//pdf with fixed ratio of the pp ratio
		RooAbsPdf  *pdf_pp   = new RooAddPdf ("pdf_pp","total signal+background pdf",
				RooArgList(*gauss1S2,*sig2S,*sig3S,*pdf_combinedbkgd),
				RooArgList(*nsig1f,*nsig2f_,*nsig3f_,*nbkgd));

		//the nominal fit with default pdf 
		if (LS_constrain) {
			RooAbsPdf  *pdf_unconstr   = new RooAddPdf ("pdf_unconstr","total signal+background pdf",
					RooArgList(*gauss1S2,*sig2S,*sig3S,*pdf_combinedbkgd),
					RooArgList(*nsig1f,*nsig2f,*nsig3f,*nbkgd));
			RooProdPdf *pdf  = new RooProdPdf ("pdf","total constr pdf",
					RooArgSet(*pdf_unconstr,*m0shift_constr,*width_constr,*par3_constr,*nLikesignbkgd_constr));
			RooFitResult* fit_2nd = pdf->fitTo(*data,Constrained(),Save(kTRUE),Extended(kTRUE),Minos(doMinos));
		}
		else {
			RooAbsPdf  *pdf   = new RooAddPdf ("pdf","total signal+background pdf",
					RooArgList(*gauss1S2,*sig2S,*sig3S,*pdf_combinedbkgd),
					RooArgList(*nsig1f,*nsig2f,*nsig3f,*nbkgd));
			RooFitResult* fit_2nd = pdf->fitTo(*data,Save(kTRUE),Extended(kTRUE),Minos(doMinos));
		}


		//plot
		TCanvas c; c.cd();
		int nbins = ceil((mmax_-mmin_)/binw_); 
		RooPlot* frame = mass->frame(Bins(nbins),Range(mmin_,mmax_));
		data->plotOn(frame,Name("theData"),MarkerSize(0.8));
		pdf->plotOn(frame,Name("thePdf"));
		if (plotLikeSign) {
			if (TRKROT) TrkRotData->plotOn(frame,Name("theLikeSignData"),MarkerSize(0.8),MarkerColor(kMagenta),MarkerStyle(22));
			else likesignData->plotOn(frame,Name("theLikeSignData"),MarkerSize(0.8),MarkerColor(kRed),MarkerStyle(24));
			//LikeSignPdf->plotOn(frame,Name("theLikeSign"),VisualizeError(*fit_1st,1),FillColor(kOrange));
			//LikeSignPdf->plotOn(frame,Name("theLikeSign"),LineColor(kRed));
		}
		RooArgSet * pars = pdf->getParameters(data);
		//RooArgSet * pars = LikeSignPdf->getParameters(likesignData);

		//calculate chi2 in a mass range
		float bin_Min = (8.2-mmin_)/binw_;
		float bin_Max = (10.8-mmin_)/binw_;
		int binMin = ceil(bin_Min);
		int binMax = ceil(bin_Max);
		int nfloatpars = pars->selectByAttrib("Constant",kFALSE)->getSize();
		float myndof = ceil((10.8-8.2)/binw_) - nfloatpars;
		cout<<binMin<<" "<<binMax<<" "<<nfloatpars<<" "<<myndof<<endl;
		double mychsq = frame->mychiSquare("thePdf","theData",nfloatpars,true,binMin,binMax)*myndof;
		//double mychsq = frame->mychiSquare("theLikeSign","theLikeSignData",nfloatpars,true,binMin,binMax)*myndof;

		/*
		   int nfloatpars = pars->selectByAttrib("Constant",kFALSE)->getSize();
		   float myndof = frame->GetNbinsX() - nfloatpars;
		   double mychsq = frame->chiSquare("theLikeSign","theLikeSignData",nfloatpars)*myndof;
		 */
		//plot parameters
		if(plotpars) {
			paramOn_ = "_paramOn";
			pdf->paramOn(frame,Layout(0.15,0.6,0.4),Layout(0.5,0.935,0.97),Label(Form("#chi^{2}/ndf = %2.1f/%2.0f", mychsq,myndof)));
		}

		/*
		   mass->setRange("R1S",8.8,9.7);
		   mass->setRange("R2S",9.8,10.2);
		//pdf_combinedbkgd->fitTo(*data,Range("R1,R3"),Constrained(),Save(kTRUE),Extended(kTRUE),Minos(doMinos));
		RooAbsReal* integral_1S = pdf_combinedbkgd->createIntegral(*mass,NormSet(*mass),Range("R1S")) ;
		cout << "1S bkgd integral = " << integral_1S->getVal() * (nbkgd->getVal()) << endl ;
		RooAbsReal* integral_2S = pdf_combinedbkgd->createIntegral(*mass,NormSet(*mass),Range("R2S")) ;
		cout << "2S bkgd integral = " << integral_2S->getVal() * (nbkgd->getVal()) << endl ;
		cout << "1S range count: " << data->sumEntries("invariantMass","R1S") <<endl;
		cout << "2S range count: " << data->sumEntries("invariantMass","R2S") <<endl;
		cout << "1S signal yield: " << data->sumEntries("invariantMass","R1S") - integral_1S->getVal() * (nbkgd->getVal()) << endl;
		cout << "2S signal yield: " << data->sumEntries("invariantMass","R2S") - integral_2S->getVal() * (nbkgd->getVal()) << endl;
		 */
		outfile<<"Y(1S) yield  : = "<<nsig1f->getVal()<<" +/- "<<nsig1f->getError()<<endl<<endl;
		outfile<<"free parameter = "<< nfloatpars << ", mychi2 = " << mychsq << ", ndof = " << myndof  << endl << endl;

		//draw the fit lines and save plots
		data->plotOn(frame,Name("theData"),MarkerSize(0.8));
		pdf->plotOn(frame,Components("bkg"),Name("theBkg"),LineStyle(5),LineColor(kGreen));
		pdf->plotOn(frame,Components("pdf_combinedbkgd"),LineStyle(kDashed));
		if (plotLikeSign) {
			if (TRKROT) pdf->plotOn(frame,Components("Like-sign"),Name("theLikeSign"),LineStyle(9),LineColor(kMagenta));
			else  pdf->plotOn(frame,Components("Like-sign"),Name("theLikeSign"),LineStyle(9),LineColor(kRed));
		}
		pdf->plotOn(frame,Name("thePdf"));
		data->plotOn(frame,MarkerSize(0.8));
		if (plotLikeSign) {
			if (TRKROT) TrkRotData->plotOn(frame,Name("theTrkRotData"),MarkerSize(0.8),MarkerColor(kMagenta),MarkerStyle(22));
			else likesignData->plotOn(frame,Name("theLikeSignData"),MarkerSize(0.8),MarkerColor(kRed),MarkerStyle(24));
		}   


		frame->SetTitle( "" );
		frame->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})");
		frame->GetXaxis()->CenterTitle(kTRUE);
		frame->GetYaxis()->SetTitleOffset(1.3);
		if (PR_plot && RAA) frame->GetYaxis()->SetRangeUser(0,1200);
		//frame->GetYaxis()->SetLabelSize(0.05);
		frame->Draw();


		//plot parameters
		if(!plotpars) {
			paramOn_ = ""; 
			TLatex latex1;
			latex1.SetNDC();
			if (PbPb) {
				latex1.DrawLatex(0.46,1.-0.05*3,"CMS PbPb  #sqrt{s_{NN}} = 2.76 TeV");
				latex1.DrawLatex(0.5,1.-0.05*4.9,"L_{int} = 150 #mub^{-1}"); 
				switch (bin) {  
					case 0: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 0-100%, |y| < 2.4"); break;
					case 3: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 0-5%, |y| < 2.4"); break;
					case 4: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 5-10%, |y| < 2.4"); break;
					case 5: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 10-20%, |y| < 2.4"); break;
					case 6: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 20-30%, |y| < 2.4"); break;
					case 7: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 30-40%, |y| < 2.4"); break;
					case 8: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 40-50%, |y| < 2.4"); break;
					case 9: latex1.DrawLatex(0.5,1.-0.05*6.2,"Cent. 50-100%, |y| < 2.4"); break;
							default; break;
				}   
			}
			else {
void buildAndFitModels(TDirectory *fout, RooWorkspace *wspace, RooRealVar &x, std::string proc="Zvv"){

   // Build and fit the model for the Zvv/Wlv background
   RooAbsPdf *pdfZvv 		   = wspace->pdf(doubleexp(wspace,x,Form("%s_control",proc.c_str())));
   RooAbsPdf *pdfZvv_mc 	   = wspace->pdf(doubleexp(wspace,x,Form("%s_control_mc",proc.c_str())));
   RooAbsPdf *pdfZvv_background_mc = wspace->pdf(doubleexp(wspace,x,Form("%s_control_bkg_mc",proc.c_str())));

   pdfZvv_mc->Print("v");
   // Fit control region MC
   std::cout << " Fit for control MC " << Form("%s_control_mc",proc.c_str())<< std::endl;
   RooFitResult *fit_res_control_mc  = pdfZvv_mc->fitTo(*(wspace->data(Form("%s_control_mc",proc.c_str()))),RooFit::Save(1),RooFit::SumW2Error(false));
   fout->cd(); fit_res_control_mc->SetName(Form("fitResult_%s_control_mc",proc.c_str())); fit_res_control_mc->Write();

   std::cout << " Fit for background MC " << Form("%s_control_bkg_mc",proc.c_str()) << std::endl;
   // Fit background MC and then fix it
   pdfZvv_background_mc->fitTo(*(wspace->data(Form("%s_control_bkg_mc",proc.c_str()))),RooFit::SumW2Error(true));
   freezeParameters(pdfZvv_background_mc->getParameters(RooArgSet(x)));
   
   // Now fit the Zvv Data 
   //RooRealVar frac_contamination_Zvv(Form("frac_contamination_%s",proc.c_str()),Form("frac_contamination_%s",proc.c_str()),0,1);
   double nbkgcont = wspace->data(Form("%s_control_bkg_mc",proc.c_str()))->sumEntries();
   double ncont    = wspace->data(Form("%s_control",proc.c_str()))->sumEntries()-nbkgcont;

   RooRealVar num_contamination_Zvv(Form("num_contamination_%s",proc.c_str()),Form("num_contamination_%s",proc.c_str()),nbkgcont,0,10E10);
   num_contamination_Zvv.setConstant();
   RooRealVar num_Zvv(Form("num_%s",proc.c_str()),Form("num_%s",proc.c_str()),ncont,0,10E10);
   num_Zvv.setConstant(true);// freeze the n_data now

   RooAddPdf modelZvv(Form("model_%s_control",proc.c_str()),Form("model_%s_control",proc.c_str()),RooArgList(*pdfZvv_background_mc,*pdfZvv),RooArgList(num_contamination_Zvv,num_Zvv));
   std::cout << " Fit for control Data " << Form("%s_control",proc.c_str()) << std::endl;
   RooFitResult *fit_res_control = modelZvv.fitTo(*(wspace->data(Form("%s_control",proc.c_str()))),RooFit::Save(1));
   fout->cd(); fit_res_control->SetName(Form("fitResult_%s_control",proc.c_str())); fit_res_control->Write();


   // Find the scale of ndata/nmc to normalize the yields
   double nmontecarlo = wspace->data(Form("%s_control_mc",proc.c_str()))->sumEntries();
   double ndata = num_Zvv.getVal();
   RooRealVar scalef(Form("scalef_%s",proc.c_str()),"scalef",ndata/nmontecarlo);
   // uncomment make this ONLY a shape correction!
   // scalef.setVal(1);
   scalef.setConstant(true);

   std::cout << proc.c_str() << " N Control Data == " << ndata       << std::endl;
   std::cout << proc.c_str() << " N Control MC   == " << nmontecarlo << std::endl;

   // Plot the fits
   TCanvas can_datafit(Form("%s_datafit",proc.c_str()),"Data Fit",800,600); 
   RooPlot *pl = x.frame();
   (wspace->data(Form("%s_control_bkg_mc",proc.c_str())))->plotOn(pl,RooFit::MarkerStyle(kOpenCircle));
   (wspace->data(Form("%s_control",proc.c_str())))->plotOn(pl);
   modelZvv.plotOn(pl);
   modelZvv.paramOn(pl);
   //pdfZvv_background_mc->plotOn(pl,RooFit::LineStyle(2));
   pl->Draw();
   fout->cd();can_datafit.Write();

   TCanvas can_mcfit(Form("%s_mcfit",proc.c_str()),"MC Fit",800,600); 
   RooPlot *plmc = x.frame();
   (wspace->data(Form("%s_control_mc",proc.c_str())))->plotOn(plmc,RooFit::MarkerColor(kBlack));
   pdfZvv_mc->plotOn(plmc,RooFit::LineStyle(1),RooFit::LineColor(2));
   pdfZvv_mc->paramOn(plmc);
   plmc->Draw();
   fout->cd();can_mcfit.Write();

   TCanvas can_mcdatafit(Form("%s_mcdatafit",proc.c_str()),"MC and Data Fits",800,600); 
   RooPlot *plmcdata = x.frame();
   pdfZvv_mc->plotOn(plmcdata,RooFit::LineColor(2),RooFit::Normalization(nmontecarlo));
   pdfZvv->plotOn(plmcdata,RooFit::Normalization(ndata));
   plmcdata->Draw();
   fout->cd();can_mcdatafit.Write();

   // Import the correction and the models 
   RooFormulaVar ratio(Form("ratio_%s",proc.c_str()),"@0*@1/@2",RooArgList(scalef,*pdfZvv,*pdfZvv_mc));
   wspace->import(ratio);
   wspace->import(num_Zvv);

   TCanvas can_ra(Form("%s_ratio",proc.c_str()),"MC Fit",800,600); 
   RooPlot *plra = x.frame();
   ratio.plotOn(plra,RooFit::LineStyle(1));
   plra->Draw();
   fout->cd();can_ra.Write();
}
Beispiel #16
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)
#ifdef __CINT__
  gROOT->ProcessLineSync(".x MyPdfV3.cxx+") ;
#endif

  // Creat 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 #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 Raa3S_Workspace(const char* filename="fitresult_combo_nofixed.root"){

   TFile File(filename);

   RooWorkspace * ws;
   File.GetObject("wcombo", ws);
   // ws->Print();
   RooAbsData * data = ws->data("data");

   // RooDataSet * US_data = (RooDataSet*) data->reduce( "QQsign == QQsign::PlusMinus");
   // US_data->SetName("US_data");
   // ws->import(* US_data);
   // RooDataSet * hi_data = (RooDataSet*) US_data->reduce("dataCat == dataCat::hi");
   // hi_data->SetName("hi_data");
   // ws->import(* hi_data);
   // hi_data->Print();

   RooRealVar* raa3 = new RooRealVar("raa3","R_{AA}(#Upsilon (3S))",0.5,0,1);
   RooRealVar* leftEdge = new RooRealVar("leftEdge","leftEdge",0);
   RooRealVar* rightEdge = new RooRealVar("rightEdge","rightEdge",1);
   RooGenericPdf step("step", "step", "(@0 >= @1) && (@0 < @2)", RooArgList(*raa3, *leftEdge, *rightEdge));
   ws->import(step);
   ws->factory( "Uniform::flat(raa3)" );

   //pp Luminosities, Taa and efficiency ratios Systematics

   ws->factory( "Taa_hi[5.662e-9]" );
   ws->factory( "Taa_kappa[1.057]" );
   ws->factory( "expr::alpha_Taa('pow(Taa_kappa,beta_Taa)',Taa_kappa,beta_Taa[0,-5,5])" );
   ws->factory( "prod::Taa_nom(Taa_hi,alpha_Taa)" );
   ws->factory( "Gaussian::constr_Taa(beta_Taa,glob_Taa[0,-5,5],1)" );

   ws->factory( "lumipp_hi[5.4]" );
   ws->factory( "lumipp_kappa[1.06]" );
   ws->factory( "expr::alpha_lumipp('pow(lumipp_kappa,beta_lumipp)',lumipp_kappa,beta_lumipp[0,-5,5])" );
   ws->factory( "prod::lumipp_nom(lumipp_hi,alpha_lumipp)" );
   ws->factory( "Gaussian::constr_lumipp(beta_lumipp,glob_lumipp[0,-5,5],1)" );

   // ws->factory( "effRat1[1]" );
   // ws->factory( "effRat2[1]" );
   ws->factory( "effRat3_hi[0.95]" );
   ws->factory( "effRat_kappa[1.054]" );
   ws->factory( "expr::alpha_effRat('pow(effRat_kappa,beta_effRat)',effRat_kappa,beta_effRat[0,-5,5])" );
   // ws->factory( "prod::effRat1_nom(effRat1_hi,alpha_effRat)" );
   ws->factory( "Gaussian::constr_effRat(beta_effRat,glob_effRat[0,-5,5],1)" );
   // ws->factory( "prod::effRat2_nom(effRat2_hi,alpha_effRat)" );
   ws->factory( "prod::effRat3_nom(effRat3_hi,alpha_effRat)" );
   //  
   ws->factory("Nmb_hi[1.161e9]");
   ws->factory("prod::denominator(Taa_nom,Nmb_hi)");
   ws->factory( "expr::lumiOverTaaNmbmodified('lumipp_nom/denominator',lumipp_nom,denominator)");
   RooFormulaVar *lumiOverTaaNmbmodified = ws->function("lumiOverTaaNmbmodified");
   //  
   //  RooRealVar *raa1 = ws->var("raa1");
   //  RooRealVar* nsig1_pp = ws->var("nsig1_pp");
   //  RooRealVar* effRat1 = ws->function("effRat1_nom");
   //  RooRealVar *raa2 = ws->var("raa2");
   //  RooRealVar* nsig2_pp = ws->var("nsig2_pp");
   //  RooRealVar* effRat2 = ws->function("effRat2_nom");
   RooRealVar* nsig3_pp = ws->var("N_{#Upsilon(3S)}_pp");
   cout << nsig3_pp << endl;
   RooRealVar* effRat3 = ws->function("effRat3_nom");
   //  
   //  RooFormulaVar nsig1_hi_modified("nsig1_hi_modified", "@0*@1*@3/@2", RooArgList(*raa1, *nsig1_pp, *lumiOverTaaNmbmodified, *effRat1));
   //  ws->import(nsig1_hi_modified);
   //  RooFormulaVar nsig2_hi_modified("nsig2_hi_modified", "@0*@1*@3/@2", RooArgList(*raa2, *nsig2_pp, *lumiOverTaaNmbmodified, *effRat2));
   //  ws->import(nsig2_hi_modified);
   RooFormulaVar nsig3_hi_modified("nsig3_hi_modified", "@0*@1*@3/@2", RooArgList(*raa3, *nsig3_pp, *lumiOverTaaNmbmodified, *effRat3));
   ws->import(nsig3_hi_modified);

   //  // background yield with systematics
   ws->factory( "nbkg_hi_kappa[1.10]" );
   ws->factory( "expr::alpha_nbkg_hi('pow(nbkg_hi_kappa,beta_nbkg_hi)',nbkg_hi_kappa,beta_nbkg_hi[0,-5,5])" );
   ws->factory( "SUM::nbkg_hi_nom(alpha_nbkg_hi*bkgPdf_hi)" );
   ws->factory( "Gaussian::constr_nbkg_hi(beta_nbkg_hi,glob_nbkg_hi[0,-5,5],1)" );
   RooAbsPdf* sig1S_hi = ws->pdf("cbcb_hi");
   RooAbsPdf* sig2S_hi = ws->pdf("sig2S_hi");
   RooAbsPdf* sig3S_hi = ws->pdf("sig3S_hi");
   RooAbsPdf* LSBackground_hi = ws->pdf("nbkg_hi_nom");
   RooRealVar* nsig1_hi = ws->var("N_{#Upsilon(1S)}_hi");
   RooRealVar* nsig2_hi = ws->var("N_{#Upsilon(2S)}_hi");
   cout << nsig1_hi << " " << nsig2_hi << " " << nsig3_pp << endl;
   RooFormulaVar* nsig3_hi = ws->function("nsig3_hi_modified");
   RooRealVar* norm_nbkg_hi = ws->var("n_{Bkgd}_hi");

   RooArgList pdfs_hi( *sig1S_hi,*sig2S_hi,*sig3S_hi, *LSBackground_hi);
   RooArgList norms_hi(*nsig1_hi,*nsig2_hi,*nsig3_hi, *norm_nbkg_hi);

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

   ws->factory( "nbkg_pp_kappa[1.03]" );
   ws->factory( "expr::alpha_nbkg_pp('pow(nbkg_pp_kappa,beta_nbkg_pp)',nbkg_pp_kappa,beta_nbkg_pp[0,-5,5])" );
   ws->factory( "SUM::nbkg_pp_nom(alpha_nbkg_pp*bkgPdf_pp)" );
   ws->factory( "Gaussian::constr_nbkg_pp(beta_nbkg_pp,glob_nbkg_pp[0,-5,5],1)" );
   RooAbsPdf* sig1S_pp = ws->pdf("cbcb_pp");
   RooAbsPdf* sig2S_pp = ws->pdf("sig2S_pp");
   RooAbsPdf* sig3S_pp = ws->pdf("sig3S_pp");
   RooAbsPdf* LSBackground_pp = ws->pdf("nbkg_pp_nom");
   RooRealVar* nsig1_pp = ws->var("N_{#Upsilon(1S)}_pp");
   RooRealVar* nsig2_pp = ws->var("N_{#Upsilon(2S)}_pp");
   RooRealVar* nsig3_pp = ws->var("N_{#Upsilon(3S)}_pp");
   RooRealVar* norm_nbkg_pp = ws->var("n_{Bkgd}_pp");

   RooArgList pdfs_pp( *sig1S_pp,*sig2S_pp,*sig3S_pp, *LSBackground_pp);
   RooArgList norms_pp( *nsig1_pp,*nsig2_pp,*nsig3_pp,*norm_nbkg_pp);

   RooAddPdf model_num("model_num", "model_num", pdfs_hi,norms_hi); 
   ws->import(model_num);
   ws->factory("PROD::model_hi(model_num, constr_nbkg_hi,constr_lumipp,constr_Taa,constr_effRat)");

   RooAddPdf model_den("model_den", "model_den", pdfs_pp,norms_pp); 
   ws->import(model_den);
   ws->factory("PROD::model_pp(model_den, constr_nbkg_pp)");

   ws->factory("SIMUL::joint(dataCat,hi=model_hi,pp=model_pp)");



   /////////////////////////////////////////////////////////////////////
   RooRealVar * pObs = ws->var("invariantMass"); // get the pointer to the observable
   RooArgSet obs("observables");
   obs.add(*pObs);
   obs.add( *ws->cat("dataCat"));    
   //  /////////////////////////////////////////////////////////////////////
   ws->var("glob_lumipp")->setConstant(true);
   ws->var("glob_Taa")->setConstant(true);
   ws->var("glob_effRat")->setConstant(true);
   ws->var("glob_nbkg_pp")->setConstant(true);
   ws->var("glob_nbkg_hi")->setConstant(true);
   RooArgSet globalObs("global_obs");
   globalObs.add( *ws->var("glob_lumipp") );
   globalObs.add( *ws->var("glob_Taa") );
   globalObs.add( *ws->var("glob_effRat") );
   globalObs.add( *ws->var("glob_nbkg_hi") );
   globalObs.add( *ws->var("glob_nbkg_pp") );

   // ws->Print();

   RooArgSet poi("poi");
   poi.add( *ws->var("raa3") );



   // create set of nuisance parameters
   RooArgSet nuis("nuis");
   nuis.add( *ws->var("beta_lumipp") );
   nuis.add( *ws->var("beta_nbkg_hi") );
   nuis.add( *ws->var("beta_nbkg_pp") );
   nuis.add( *ws->var("beta_Taa") );
   nuis.add( *ws->var("beta_effRat") );

   ws->var("#alpha_{CB}_hi")->setConstant(true);
   ws->var("#alpha_{CB}_pp")->setConstant(true);
   ws->var("#sigma_{CB1}_hi")->setConstant(true);
   ws->var("#sigma_{CB1}_pp")->setConstant(true);
   ws->var("#sigma_{CB2}/#sigma_{CB1}_hi")->setConstant(true);
   ws->var("#sigma_{CB2}/#sigma_{CB1}_pp")->setConstant(true);
   ws->var("Centrality")->setConstant(true);
   ws->var("N_{#Upsilon(1S)}_hi")->setConstant(true);
   ws->var("N_{#Upsilon(1S)}_pp")->setConstant(true);
   ws->var("N_{#Upsilon(2S)}_hi")->setConstant(true);
   ws->var("N_{#Upsilon(2S)}_pp")->setConstant(true);
   ws->var("N_{#Upsilon(3S)}_pp")->setConstant(true);
   ws->var("Nmb_hi")->setConstant(true);
   // ws->var("QQsign")->setConstant(true);
   ws->var("Taa_hi")->setConstant(true);
   ws->var("Taa_kappa")->setConstant(true);
   // ws->var("beta_Taa")->setConstant(true);
   // ws->var("beta_effRat")->setConstant(true);
   // ws->var("beta_lumipp")->setConstant(true);
   // ws->var("beta_nbkg_hi")->setConstant(true);
   // ws->var("beta_nbkg_pp")->setConstant(true);
   // ws->var("dataCat")->setConstant(true);
   ws->var("decay_hi")->setConstant(true);
   ws->var("decay_pp")->setConstant(true);
   ws->var("effRat3_hi")->setConstant(true);
   ws->var("effRat_kappa")->setConstant(true);
   // ws->var("glob_Taa")->setConstant(true);
   // ws->var("glob_effRat")->setConstant(true);
   // ws->var("glob_lumipp")->setConstant(true);
   // ws->var("glob_nbkg_hi")->setConstant(true);
   // ws->var("glob_nbkg_pp")->setConstant(true);
   // ws->var("invariantMass")->setConstant(true);
   ws->var("leftEdge")->setConstant(true);
   ws->var("lumipp_hi")->setConstant(true);
   ws->var("lumipp_kappa")->setConstant(true);
   ws->var("mass1S_hi")->setConstant(true);
   ws->var("mass1S_pp")->setConstant(true);
   ws->var("muMinusPt")->setConstant(true);
   ws->var("muPlusPt")->setConstant(true);
   ws->var("n_{Bkgd}_hi")->setConstant(true);
   ws->var("n_{Bkgd}_pp")->setConstant(true);
   ws->var("nbkg_hi_kappa")->setConstant(true);
   ws->var("nbkg_pp_kappa")->setConstant(true);
   ws->var("npow")->setConstant(true);
   ws->var("N_{#Upsilon(3S)}_pp")->setConstant(true);
   // ws->var("raa3")->setConstant(true);
   ws->var("rightEdge")->setConstant(true);
   ws->var("sigmaFraction_hi")->setConstant(true);
   ws->var("sigmaFraction_pp")->setConstant(true);
   ws->var("turnOn_hi")->setConstant(true);
   ws->var("turnOn_pp")->setConstant(true);
   ws->var("upsPt")->setConstant(true);
   ws->var("upsRapidity")->setConstant(true);
   ws->var("vProb")->setConstant(true);
   ws->var("width_hi")->setConstant(true);
   ws->var("width_pp")->setConstant(true);
   ws->var("x3raw")->setConstant(true);
   //  RooArgSet fixed_again("fixed_again");
   //  fixed_again.add( *ws->var("leftEdge") );
   //  fixed_again.add( *ws->var("rightEdge") );
   //  fixed_again.add( *ws->var("Taa_hi") );
   //  fixed_again.add( *ws->var("Nmb_hi") );
   //  fixed_again.add( *ws->var("lumipp_hi") );
   //  fixed_again.add( *ws->var("effRat1_hi") );
   //  fixed_again.add( *ws->var("effRat2_hi") );
   //  fixed_again.add( *ws->var("effRat3_hi") );
   //  fixed_again.add( *ws->var("nsig3_pp") );
   //  fixed_again.add( *ws->var("nsig1_pp") );
   //  fixed_again.add( *ws->var("nbkg_hi") );
   //  fixed_again.add( *ws->var("alpha") );
   //  fixed_again.add( *ws->var("nbkg_kappa") );
   //  fixed_again.add( *ws->var("Taa_kappa") );
   //  fixed_again.add( *ws->var("lumipp_kappa") );
   // fixed_again.add( *ws->var("mean_hi") );
   // fixed_again.add( *ws->var("mean_pp") );
   // fixed_again.add( *ws->var("width_hi") );
   // fixed_again.add( *ws->var("turnOn_hi") );
   // fixed_again.add( *ws->var("bkg_a1_pp") );
   // fixed_again.add( *ws->var("bkg_a2_pp") );
   // fixed_again.add( *ws->var("decay_hi") );
   // fixed_again.add( *ws->var("raa1") );
   // fixed_again.add( *ws->var("raa2") );
   //  fixed_again.add( *ws->var("nsig2_pp") );
   // fixed_again.add( *ws->var("sigma1") );
   //  fixed_again.add( *ws->var("nbkg_pp") );
   // fixed_again.add( *ws->var("npow") );
   // fixed_again.add( *ws->var("muPlusPt") );
   // fixed_again.add( *ws->var("muMinusPt") );
   // fixed_again.add( *ws->var("mscale_hi") );
   // fixed_again.add( *ws->var("mscale_pp") );
   //  
   // ws->Print();

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

   // ws->Print();
   /////////////////////////////////////////////////////////////////////
   RooAbsReal * pNll = sbHypo.GetPdf()->createNLL( *data,NumCPU(2) );
   RooMinuit(*pNll).migrad(); // minimize likelihood wrt all parameters before making plots
   RooPlot *framepoi = ((RooRealVar *)poi.first())->frame(Bins(10),Range(0.,0.2),Title("LL and profileLL in raa3"));
   pNll->plotOn(framepoi,ShiftToZero());
   
   RooAbsReal * pProfile = pNll->createProfile( globalObs ); // do not profile global observables
   pProfile->getVal(); // this will do fit and set POI and nuisance parameters to fitted values
   pProfile->plotOn(framepoi,LineColor(kRed));
   framepoi->SetMinimum(0);
   framepoi->SetMaximum(3);
   TCanvas *cpoi = new TCanvas();
   cpoi->cd(); framepoi->Draw();
   cpoi->SaveAs("cpoi.pdf");

   RooArgSet * pPoiAndNuisance = new RooArgSet("poiAndNuisance");
   // pPoiAndNuisance->add(*sbHypo.GetNuisanceParameters());
   // pPoiAndNuisance->add(*sbHypo.GetParametersOfInterest());
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   sbHypo.SetSnapshot(*pPoiAndNuisance);

   RooPlot* xframeSB = pObs->frame(Title("SBhypo"));
   data->plotOn(xframeSB,Cut("dataCat==dataCat::hi"));
   RooAbsPdf *pdfSB = sbHypo.GetPdf();
   RooCategory *dataCat = ws->cat("dataCat");
   pdfSB->plotOn(xframeSB,Slice(*dataCat,"hi"),ProjWData(*dataCat,*data));
   TCanvas *c1 = new TCanvas();
   c1->cd(); xframeSB->Draw();
   c1->SaveAs("c1.pdf");

   delete pProfile;
   delete pNll;
   delete pPoiAndNuisance;
   ws->import( sbHypo );
   /////////////////////////////////////////////////////////////////////
   RooStats::ModelConfig bHypo = sbHypo;
   bHypo.SetName("BHypo");
   bHypo.SetWorkspace(*ws);
   pNll = bHypo.GetPdf()->createNLL( *data,NumCPU(2) );
   RooArgSet poiAndGlobalObs("poiAndGlobalObs");
   poiAndGlobalObs.add( poi );
   poiAndGlobalObs.add( globalObs );
   pProfile = pNll->createProfile( poiAndGlobalObs ); // do not profile POI and global observables
   double oldval = ((RooRealVar *)poi.first())->getVal( ); 
   ((RooRealVar *)poi.first())->setVal( 0 );  // set raa3=0 here
   pProfile->getVal(); // this will do fit and set nuisance parameters to profiled values
   pPoiAndNuisance = new RooArgSet( "poiAndNuisance" );
   pPoiAndNuisance->add( nuis );
   pPoiAndNuisance->add( poi );
   bHypo.SetSnapshot(*pPoiAndNuisance);

   RooPlot* xframeB = pObs->frame(Title("Bhypo"));
   data->plotOn(xframeB,Cut("dataCat==dataCat::hi"));
   RooAbsPdf *pdfB = bHypo.GetPdf();
   pdfB->plotOn(xframeB,Slice(*dataCat,"hi"),ProjWData(*dataCat,*data));
   TCanvas *c2 = new TCanvas();
   c2->cd(); xframeB->Draw();
   c2->SaveAs("c2.pdf");

   delete pProfile;
   delete pNll;
   delete pPoiAndNuisance;

   // import model config into workspace
   bHypo.SetWorkspace(*ws);
   ws->import( bHypo );
   /////////////////////////////////////////////////////////////////////
   ws->Print();
   bHypo.Print();
   sbHypo.Print();

   ((RooRealVar *)poi.first())->setVal( oldval );  // set raa3=oldval here
   // save workspace to file
   ws -> SaveAs("TRIAL.root");

   return;
}
// internal routine to run the inverter
HypoTestInverterResult *
RooStats::HypoTestInvTool::RunInverter(RooWorkspace * w,
                                       const char * modelSBName, const char * modelBName, 
                                       const char * dataName, int type,  int testStatType, 
                                       bool useCLs, int npoints, double poimin, double poimax, 
                                       int ntoys,
                                       bool useNumberCounting,
                                       const char * nuisPriorName ){

   std::cout << "Running HypoTestInverter on the workspace " << w->GetName() << std::endl;
  
   w->Print();
  
  
   RooAbsData * data = w->data(dataName); 
   if (!data) { 
      Error("StandardHypoTestDemo","Not existing data %s",dataName);
      return 0;
   }
   else 
      std::cout << "Using data set " << dataName << std::endl;
  
   if (mUseVectorStore) { 
      RooAbsData::defaultStorageType = RooAbsData::Vector;
      data->convertToVectorStore() ;
   }
  
  
   // get models from WS
   // get the modelConfig out of the file
   ModelConfig* bModel = (ModelConfig*) w->obj(modelBName);
   ModelConfig* sbModel = (ModelConfig*) w->obj(modelSBName);
  
   if (!sbModel) {
      Error("StandardHypoTestDemo","Not existing ModelConfig %s",modelSBName);
      return 0;
   }
   // check the model 
   if (!sbModel->GetPdf()) { 
      Error("StandardHypoTestDemo","Model %s has no pdf ",modelSBName);
      return 0;
   }
   if (!sbModel->GetParametersOfInterest()) {
      Error("StandardHypoTestDemo","Model %s has no poi ",modelSBName);
      return 0;
   }
   if (!sbModel->GetObservables()) {
      Error("StandardHypoTestInvDemo","Model %s has no observables ",modelSBName);
      return 0;
   }
   if (!sbModel->GetSnapshot() ) { 
      Info("StandardHypoTestInvDemo","Model %s has no snapshot  - make one using model poi",modelSBName);
      sbModel->SetSnapshot( *sbModel->GetParametersOfInterest() );
   }
  
   // case of no systematics
   // remove nuisance parameters from model
   if (noSystematics) { 
      const RooArgSet * nuisPar = sbModel->GetNuisanceParameters();
      if (nuisPar && nuisPar->getSize() > 0) { 
         std::cout << "StandardHypoTestInvDemo" << "  -  Switch off all systematics by setting them constant to their initial values" << std::endl;
         RooStats::SetAllConstant(*nuisPar);
      }
      if (bModel) { 
         const RooArgSet * bnuisPar = bModel->GetNuisanceParameters();
         if (bnuisPar) 
            RooStats::SetAllConstant(*bnuisPar);
      }
   }
  
   if (!bModel || bModel == sbModel) {
      Info("StandardHypoTestInvDemo","The background model %s does not exist",modelBName);
      Info("StandardHypoTestInvDemo","Copy it from ModelConfig %s and set POI to zero",modelSBName);
      bModel = (ModelConfig*) sbModel->Clone();
      bModel->SetName(TString(modelSBName)+TString("_with_poi_0"));      
      RooRealVar * var = dynamic_cast<RooRealVar*>(bModel->GetParametersOfInterest()->first());
      if (!var) return 0;
      double oldval = var->getVal();
      var->setVal(0);
      bModel->SetSnapshot( RooArgSet(*var)  );
      var->setVal(oldval);
   }
   else { 
      if (!bModel->GetSnapshot() ) { 
         Info("StandardHypoTestInvDemo","Model %s has no snapshot  - make one using model poi and 0 values ",modelBName);
         RooRealVar * var = dynamic_cast<RooRealVar*>(bModel->GetParametersOfInterest()->first());
         if (var) { 
            double oldval = var->getVal();
            var->setVal(0);
            bModel->SetSnapshot( RooArgSet(*var)  );
            var->setVal(oldval);
         }
         else { 
            Error("StandardHypoTestInvDemo","Model %s has no valid poi",modelBName);
            return 0;
         }         
      }
   }
  
   // run first a data fit 
  
   const RooArgSet * poiSet = sbModel->GetParametersOfInterest();
   RooRealVar *poi = (RooRealVar*)poiSet->first();
  
   std::cout << "StandardHypoTestInvDemo : POI initial value:   " << poi->GetName() << " = " << poi->getVal()   << std::endl;  
  
   // fit the data first (need to use constraint )
   Info( "StandardHypoTestInvDemo"," Doing a first fit to the observed data ");
   if (minimizerType.size()==0) minimizerType = ROOT::Math::MinimizerOptions::DefaultMinimizerType();
   else 
      ROOT::Math::MinimizerOptions::SetDefaultMinimizer(minimizerType.c_str());
   Info("StandardHypoTestInvDemo","Using %s as minimizer for computing the test statistic",
        ROOT::Math::MinimizerOptions::DefaultMinimizerType().c_str() );
   RooArgSet constrainParams;
   if (sbModel->GetNuisanceParameters() ) constrainParams.add(*sbModel->GetNuisanceParameters());
   RooStats::RemoveConstantParameters(&constrainParams);
   TStopwatch tw; 
   tw.Start(); 
   RooFitResult * fitres = sbModel->GetPdf()->fitTo(*data,InitialHesse(false), Hesse(false),
                                                    Minimizer(minimizerType.c_str(),"Migrad"), Strategy(0), PrintLevel(mPrintLevel+1), Constrain(constrainParams), Save(true) );
   if (fitres->status() != 0) { 
      Warning("StandardHypoTestInvDemo","Fit to the model failed - try with strategy 1 and perform first an Hesse computation");
      fitres = sbModel->GetPdf()->fitTo(*data,InitialHesse(true), Hesse(false),Minimizer(minimizerType.c_str(),"Migrad"), Strategy(1), PrintLevel(mPrintLevel+1), Constrain(constrainParams), Save(true) );
   }
   if (fitres->status() != 0) 
      Warning("StandardHypoTestInvDemo"," Fit still failed - continue anyway.....");
  
  
   double poihat  = poi->getVal();
   std::cout << "StandardHypoTestInvDemo - Best Fit value : " << poi->GetName() << " = "  
             << poihat << " +/- " << poi->getError() << std::endl;
   std::cout << "Time for fitting : "; tw.Print(); 
  
   //save best fit value in the poi snapshot 
   sbModel->SetSnapshot(*sbModel->GetParametersOfInterest());
   std::cout << "StandardHypoTestInvo: snapshot of S+B Model " << sbModel->GetName() 
             << " is set to the best fit value" << std::endl;
  
   // build test statistics and hypotest calculators for running the inverter 
  
   SimpleLikelihoodRatioTestStat slrts(*sbModel->GetPdf(),*bModel->GetPdf());
  
   if (sbModel->GetSnapshot()) slrts.SetNullParameters(*sbModel->GetSnapshot());
   if (bModel->GetSnapshot()) slrts.SetAltParameters(*bModel->GetSnapshot());
  
   // ratio of profile likelihood - need to pass snapshot for the alt
   RatioOfProfiledLikelihoodsTestStat 
      ropl(*sbModel->GetPdf(), *bModel->GetPdf(), bModel->GetSnapshot());
   ropl.SetSubtractMLE(false);
   ropl.SetPrintLevel(mPrintLevel);
   ropl.SetMinimizer(minimizerType.c_str());
  
   ProfileLikelihoodTestStat profll(*sbModel->GetPdf());
   if (testStatType == 3) profll.SetOneSided(1);
   profll.SetMinimizer(minimizerType.c_str());
   profll.SetPrintLevel(mPrintLevel);

   profll.SetReuseNLL(mOptimize);
   slrts.SetReuseNLL(mOptimize);
   ropl.SetReuseNLL(mOptimize);

   if (mOptimize) { 
      profll.SetStrategy(0);
      ropl.SetStrategy(0);
   }
  
   if (mMaxPoi > 0) poi->setMax(mMaxPoi);  // increase limit
  
   MaxLikelihoodEstimateTestStat maxll(*sbModel->GetPdf(),*poi); 
  
   // create the HypoTest calculator class 
   HypoTestCalculatorGeneric *  hc = 0;
   if (type == 0) hc = new FrequentistCalculator(*data, *bModel, *sbModel);
   else if (type == 1) hc = new HybridCalculator(*data, *bModel, *sbModel);
   else if (type == 2) hc = new AsymptoticCalculator(*data, *bModel, *sbModel);
   else {
      Error("StandardHypoTestInvDemo","Invalid - calculator type = %d supported values are only :\n\t\t\t 0 (Frequentist) , 1 (Hybrid) , 2 (Asymptotic) ",type);
      return 0;
   }
  
   // set the test statistic 
   TestStatistic * testStat = 0;
   if (testStatType == 0) testStat = &slrts;
   if (testStatType == 1) testStat = &ropl;
   if (testStatType == 2 || testStatType == 3) testStat = &profll;
   if (testStatType == 4) testStat = &maxll;
   if (testStat == 0) { 
      Error("StandardHypoTestInvDemo","Invalid - test statistic type = %d supported values are only :\n\t\t\t 0 (SLR) , 1 (Tevatron) , 2 (PLR), 3 (PLR1), 4(MLE)",testStatType);
      return 0;
   }
  
  
   ToyMCSampler *toymcs = (ToyMCSampler*)hc->GetTestStatSampler();
   if (toymcs) { 
      if (useNumberCounting) toymcs->SetNEventsPerToy(1);
      toymcs->SetTestStatistic(testStat);
    
      if (data->isWeighted() && !mGenerateBinned) { 
         Info("StandardHypoTestInvDemo","Data set is weighted, nentries = %d and sum of weights = %8.1f but toy generation is unbinned - it would be faster to set mGenerateBinned to true\n",data->numEntries(), data->sumEntries());
      }
      toymcs->SetGenerateBinned(mGenerateBinned);
    
      toymcs->SetUseMultiGen(mOptimize);
    
      if (mGenerateBinned &&  sbModel->GetObservables()->getSize() > 2) { 
         Warning("StandardHypoTestInvDemo","generate binned is activated but the number of ovservable is %d. Too much memory could be needed for allocating all the bins",sbModel->GetObservables()->getSize() );
      }
    
   }
  
  
   if (type == 1) { 
      HybridCalculator *hhc = dynamic_cast<HybridCalculator*> (hc);
      assert(hhc);
    
      hhc->SetToys(ntoys,ntoys/mNToysRatio); // can use less ntoys for b hypothesis 
    
      // remove global observables from ModelConfig (this is probably not needed anymore in 5.32)
      bModel->SetGlobalObservables(RooArgSet() );
      sbModel->SetGlobalObservables(RooArgSet() );
    
    
      // check for nuisance prior pdf in case of nuisance parameters 
      if (bModel->GetNuisanceParameters() || sbModel->GetNuisanceParameters() ) {
         RooAbsPdf * nuisPdf = 0; 
         if (nuisPriorName) nuisPdf = w->pdf(nuisPriorName);
         // use prior defined first in bModel (then in SbModel)
         if (!nuisPdf)  { 
            Info("StandardHypoTestInvDemo","No nuisance pdf given for the HybridCalculator - try to deduce  pdf from the model");
            if (bModel->GetPdf() && bModel->GetObservables() ) 
               nuisPdf = RooStats::MakeNuisancePdf(*bModel,"nuisancePdf_bmodel");
            else 
               nuisPdf = RooStats::MakeNuisancePdf(*sbModel,"nuisancePdf_sbmodel");
         }   
         if (!nuisPdf ) {
            if (bModel->GetPriorPdf())  { 
               nuisPdf = bModel->GetPriorPdf();
               Info("StandardHypoTestInvDemo","No nuisance pdf given - try to use %s that is defined as a prior pdf in the B model",nuisPdf->GetName());            
            }
            else { 
               Error("StandardHypoTestInvDemo","Cannnot run Hybrid calculator because no prior on the nuisance parameter is specified or can be derived");
               return 0;
            }
         }
         assert(nuisPdf);
         Info("StandardHypoTestInvDemo","Using as nuisance Pdf ... " );
         nuisPdf->Print();
      
         const RooArgSet * nuisParams = (bModel->GetNuisanceParameters() ) ? bModel->GetNuisanceParameters() : sbModel->GetNuisanceParameters();
         RooArgSet * np = nuisPdf->getObservables(*nuisParams);
         if (np->getSize() == 0) { 
            Warning("StandardHypoTestInvDemo","Prior nuisance does not depend on nuisance parameters. They will be smeared in their full range");
         }
         delete np;
      
         hhc->ForcePriorNuisanceAlt(*nuisPdf);
         hhc->ForcePriorNuisanceNull(*nuisPdf);
      
      
      }
   } 
   else if (type == 2) { 
      ((AsymptoticCalculator*) hc)->SetOneSided(true); 
      // ((AsymptoticCalculator*) hc)->SetQTilde(true); // not needed should be done automatically now
      ((AsymptoticCalculator*) hc)->SetPrintLevel(mPrintLevel+1); 
   }
   else if (type != 2) 
      ((FrequentistCalculator*) hc)->SetToys(ntoys,ntoys/mNToysRatio); 
  
   // Get the result
   RooMsgService::instance().getStream(1).removeTopic(RooFit::NumIntegration);
  
  
  
   HypoTestInverter calc(*hc);
   calc.SetConfidenceLevel(0.95);
  
  
   calc.UseCLs(useCLs);
   calc.SetVerbose(true);
  
   // can speed up using proof-lite
   if (mUseProof && mNWorkers > 1) { 
      ProofConfig pc(*w, mNWorkers, "", kFALSE);
      toymcs->SetProofConfig(&pc);    // enable proof
   }
  
  
   if (npoints > 0) {
      if (poimin > poimax) { 
         // if no min/max given scan between MLE and +4 sigma 
         poimin = int(poihat);
         poimax = int(poihat +  4 * poi->getError());
      }
      std::cout << "Doing a fixed scan  in interval : " << poimin << " , " << poimax << std::endl;
      calc.SetFixedScan(npoints,poimin,poimax);
   }
   else { 
      //poi->setMax(10*int( (poihat+ 10 *poi->getError() )/10 ) );
      std::cout << "Doing an  automatic scan  in interval : " << poi->getMin() << " , " << poi->getMax() << std::endl;
   }
  
   tw.Start();
   HypoTestInverterResult * r = calc.GetInterval();
   std::cout << "Time to perform limit scan \n";
   tw.Print();
  
   if (mRebuild) {
      calc.SetCloseProof(1);
      tw.Start();
      SamplingDistribution * limDist = calc.GetUpperLimitDistribution(true,mNToyToRebuild);
      std::cout << "Time to rebuild distributions " << std::endl;
      tw.Print();
    
      if (limDist) { 
         std::cout << "expected up limit " << limDist->InverseCDF(0.5) << " +/- " 
                   << limDist->InverseCDF(0.16) << "  " 
                   << limDist->InverseCDF(0.84) << "\n"; 
      
         //update r to a new updated result object containing the rebuilt expected p-values distributions
         // (it will not recompute the expected limit)
         if (r) delete r;  // need to delete previous object since GetInterval will return a cloned copy
         r = calc.GetInterval();
      
      }
      else 
         std::cout << "ERROR : failed to re-build distributions " << std::endl; 
   }
  
   return r;
}
Beispiel #20
0
void cutChecker()
{
  int kCut =2 ;//1:vProb, 2:dca, 3:MatchedStations, 4:ctau/ctauErr
  int pbpb=false;
  gROOT->Macro("./cm/logon.C+");//it all looks much nicer with this.  
  // TString fname2011="../dimuonTree_HI2011_fulldataset_trkRot.root";
  // TFile *_file0 = TFile::Open(fname2011);
  // TTree *upsi2011    = (TTree*)_file0->Get("UpsilonTree");
 
  
  if(pbpb) { TString fname2013=" ../dimuonTree_upsiMiniTree_AA2p76tev_WithIDCuts_RunHIN-15-001_trigBit1_allTriggers0.root";//../dimuonTree_upsiMiniTree_aa276tev_regitreco_glbglb_Runa_trigBit1_allTriggers0_pt4.root";
  }else if(!pbpb){
  TString fname2013=" ../dimuonTree_upsiMiniTree_pp2p76tev_noIDVars_GlbGlb_RunHIN-15-001_trigBit2_allTriggers0.root";
  }
  //TString fname2013="../upsiMiniTree_pyquen1S_noMuonPtCuts_QQtrigbit1_Trig_analysisOK_20140729_cuts10-006.root";
  TFile *_file1 = TFile::Open(fname2013);
  TTree *upsi2013 = (TTree*)_file1->Get("UpsilonTree");
  RooRealVar* upsPt      = new RooRealVar("upsPt","p_{T}(#Upsilon)",0,60,"GeV");
  //  RooRealVar* upsEta     = new RooRealVar("upsEta",  "upsEta"  ,-10,10);
  RooRealVar* upsRapidity= new RooRealVar("upsRapidity",  "upsRapidity",-1000, 1000);
  RooRealVar* vProb      = new RooRealVar("vProb",  "vProb"  ,0.01,1.00);
  RooRealVar* _dca      = new RooRealVar("_dca",  "_dca"  ,0.0,5.00);
  RooRealVar* _ctau     = new RooRealVar("_ctau",  "_ctau"  ,-100,100,"cm");
  RooRealVar* _ctauErr     = new RooRealVar("_ctauErr",  "_ctauErr"  ,-100,100,"cm");
  RooRealVar* muPlusPt   = new RooRealVar("muPlusPt","muPlusPt",3.5,100);
  RooRealVar* muMinusPt  = new RooRealVar("muMinusPt","muMinusPt",3.5,100);
  RooRealVar* muPlusEta  = new RooRealVar("muPlusEta","muPlusEta",  -2.4,2.4);
  RooRealVar* muMinusEta = new RooRealVar("muMinusEta","muMinusEta",-2.4,2.4);
  RooRealVar* _mupl_StationsMatched  = new RooRealVar("_mupl_StationsMatched","_mupl_StationsMatched",0,5);
  RooRealVar* _mumi_StationsMatched  = new RooRealVar("_mumi_StationsMatched","_mumi_StationsMatched",0,5);
  RooRealVar* muMinusEta = new RooRealVar("muMinusEta","muMinusEta",-2.4,2.4);
  RooRealVar* mass = new RooRealVar("invariantMass","#mu#mu mass",7,14,"GeV/c^{2}"); 
  TCut cut_acc = " ((muPlusPt >3.5 && muMinusPt>4)||(muPlusPt>4 &&muMinusPt>3.5))  && abs(upsRapidity)<2.4 && (invariantMass<14 && invariantMass>7)"; //  
  cout << "cut: "<< cut_acc.Print() << endl;
  //  TCut cut_add(cutList(1,1));
  //cout << "cut: "<< cut_add.Print() << endl;
 
  switch (kCut){
  case 1: //vProb]   
    RooDataSet *data0 = new RooDataSet("data0","data0",upsi2013,
				       RooArgSet(*mass,*muPlusPt,*muMinusPt,*upsRapidity,*vProb));
    string cut[4]={"vProb>0.01",// very loose
		   "vProb>0.05",
		   "vProb>0.1",
		   "vProb>0.2"};//very tight
    // for plotting purposes...
    break;
  case 2: //dca
    RooDataSet *data0 = new RooDataSet("data0","data0",upsi2013,
				       RooArgSet(*mass,*muPlusPt,*muMinusPt,*upsRapidity,*_dca));
    string cut[4]={"_dca<0.004", //very tight
		   "_dca<0.006",
		   "_dca<0.008",
		   "_dca<0.01"}; // very loose
    break;
  case 3: // number of matched Stations
    RooDataSet *data0 = new RooDataSet("data0","data0",upsi2013,
				       RooArgSet(*mass,*muPlusPt,*muMinusPt,*upsRapidity,*_mupl_StationsMatched,*_mumi_StationsMatched));
    string cut[4]={  "_mumi_StationsMatched>0&&_mupl_StationsMatched>0",  
		     "_mumi_StationsMatched>1&&_mupl_StationsMatched>1",
		     "_mumi_StationsMatched>2&&_mupl_StationsMatched>2",
		     "_mumi_StationsMatched>3&&_mupl_StationsMatched>3"};
    string cutname[4]={  "at least one",  
			 "more than 1",
			 "more than 2",
			 "more than 3"};
    break;
  case 4: ///fabs(ctau/ctau_err)
    RooDataSet *data0 = new RooDataSet("data0","data0",upsi2013,
				       RooArgSet(*mass,*muPlusPt,*muMinusPt,*upsRapidity,*_ctau,*_ctauErr));
    
    string cut[4]={"abs(_ctau/_ctauErr)<5",//very loose
		   "abs(_ctau/_ctauErr)<4" ,
		   "abs(_ctau/_ctauErr)<3" ,
		   "abs(_ctau/_ctauErr)<2" }; //tighter
    string cutname[4]={"|c#tau/#sigma(c#tau)| < 5",  
		       "|c#tau/#sigma(c#tau)| < 4",
		       "|c#tau/#sigma(c#tau)| < 3",
		       "|c#tau/#sigma(c#tau)| < 2"};
    break;
  default:
    cout<< "no Cut Variable specified!"<<endl; break;
  }
  TCut cut_add1((cut[0]).c_str());
  TCut cut_add2((cut[1]).c_str());  
  TCut cut_add3((cut[2]).c_str());
  TCut cut_add4((cut[3]).c_str());
  TString figName_(Form("%s",(cut[0]).c_str()));
    figName_.ReplaceAll(">","_gt");
    figName_.ReplaceAll("<","_lt");
    figName_.ReplaceAll(".","p");
    figName_.ReplaceAll("&&","_AND_");
    figName_.ReplaceAll("||","_OR_");
    figName_.ReplaceAll("(","");
    figName_.ReplaceAll("/","-");
    figName_.ReplaceAll(")","");
    
    cout << "hello"<< endl;
  // cut_add.Print();

  int nt = data0->sumEntries();
  redData1 =  ( RooDataSet*) data0->reduce(Cut(cut_acc+cut_add1));
  redData1->Print();
  TH1D *MReco1;
  MReco1 = new TH1D("MReco1","Reco di-muon mass",70,7,14);
  MReco1 = (TH1D*) redData1->createHistogram("invariantMass",*mass);
  redData2 =  ( RooDataSet*) data0->reduce(Cut(cut_acc+cut_add2));
  redData2->Print();
  TH1D *MReco2;
  MReco2 = new TH1D("MReco2","Reco di-muon mass",70,7,14);
  MReco2 = (TH1D*) redData2->createHistogram("invariantMass",*mass);
  redData3 =  ( RooDataSet*) data0->reduce(Cut(cut_acc+cut_add3));
  redData3->Print();
  TH1D *MReco3;
  MReco3 = new TH1D("MReco3","Reco di-muon mass",70,7,14);
  MReco3 = (TH1D*) redData3->createHistogram("invariantMass",*mass);
  redData4 =  ( RooDataSet*) data0->reduce(Cut(cut_acc+cut_add4));
  redData4->Print();
  TH1D *MReco4;
  MReco4 = new TH1D("MReco4","Reco di-muon mass",70,7,14);
  MReco4 = (TH1D*) redData4->createHistogram("invariantMass",*mass);
  const double M1S = 9.46;   //upsilon 1S pgd mass value
  const double M2S = 10.023;  //upsilon 2S pgd mass value
  const double M3S = 10.355;  //upsilon 3S pgd mass value
  RooRealVar *nsig1f   = new RooRealVar("N_{#Upsilon(1S)}","nsig1S",0,nt*10);
  RooRealVar *nsig2f  = new RooRealVar("N_{#Upsilon(2S)}","nsig2S",   nt*0.25,-1*nt,10*nt);
  RooRealVar *nsig3f  = new RooRealVar("N_{#Upsilon(3S)}","nsig3S",   nt*0.25,-1*nt,10*nt);
  RooRealVar  *mean = new RooRealVar("mass1S","#Upsilon mean",M1S,M1S-0.1,M1S+0.1);
  RooConstVar *rat2 = new RooConstVar("rat2", "rat2", M2S/M1S);
  RooConstVar *rat3 = new RooConstVar("rat3", "rat3", M3S/M1S);
  // scale mean and resolution by mass ratio
  RooFormulaVar *mean1S = new RooFormulaVar("mean1S","@0",RooArgList(*mean));
  RooFormulaVar *mean2S = new RooFormulaVar("mean2S","@0*@1", RooArgList(*mean,*rat2));
  RooFormulaVar *mean3S = new RooFormulaVar("mean3S","@0*@1", RooArgList(*mean,*rat3));
  
  //detector resolution ?? where is this coming from?
  RooRealVar    *sigma1  = new RooRealVar("#sigma_{CB1}","#sigma_{CB1}",0,0.5); // 
  RooFormulaVar *sigma1S = new RooFormulaVar("sigma1S","@0"   ,RooArgList(*sigma1));
  RooFormulaVar *sigma2S = new RooFormulaVar("sigma2S","@0*@1",RooArgList(*sigma1,*rat2));
  RooFormulaVar *sigma3S = new RooFormulaVar("sigma3S","@0*@1",RooArgList(*sigma1,*rat3));
  RooRealVar *alpha  = new RooRealVar("#alpha_{CB}","tail shift",0.01,8);    // MC 5tev 1S pol2 
  RooRealVar *npow   = new RooRealVar("npow","power order",1,60);    // MC 5tev 1S pol2 
  RooRealVar *sigmaFraction = new RooRealVar("sigmaFraction","Sigma Fraction",0.,1.);
  // scale the sigmaGaus with sigma1S*scale=sigmaGaus now.
  RooRealVar    *scaleWidth = new RooRealVar("#sigma_{CB2}/#sigma_{CB1}","scaleWidth",1.,2.7);
  RooFormulaVar *sigmaGaus = new RooFormulaVar("sigmaGaus","@0*@1", RooArgList(*sigma1,*scaleWidth));
  RooFormulaVar *sigmaGaus2 = new RooFormulaVar("sigmaGaus","@0*@1*@2", RooArgList(*sigma1,*scaleWidth,*rat2));
  RooFormulaVar *sigmaGaus3 = new RooFormulaVar("sigmaGaus","@0*@1*@2", RooArgList(*sigma1,*scaleWidth,*rat3));
  RooCBShape  *cb1S_1    = new RooCBShape ("cb1S_1", "FSR cb 1s",
					   *mass,*mean1S,*sigma1,*alpha,*npow);
  
  RooCBShape  *cb1S_2    = new RooCBShape ("cb1S_2", "FSR cb 1s",
					   *mass,*mean1S,*sigmaGaus,*alpha,*npow);
  RooAddPdf      *sig1S  = new RooAddPdf  ("cbcb","1S mass pdf",
					   RooArgList(*cb1S_1,*cb1S_2),*sigmaFraction);
  // /// Upsilon 2S
  RooCBShape  *cb2S_1    = new RooCBShape ("cb2S_1", "FSR cb 2s", 
					   *mass,*mean2S,*sigma2S,*alpha,*npow); 
  RooCBShape  *cb2S_2    = new RooCBShape ("cb2S_2", "FSR cb 2s", 
					   *mass,*mean2S,*sigmaGaus2,*alpha,*npow); 
  RooAddPdf      *sig2S  = new RooAddPdf  ("sig2S","2S mass pdf",
					   RooArgList(*cb2S_1,*cb2S_2),*sigmaFraction);
    
  // /// Upsilon 3S
  RooCBShape  *cb3S_1    = new RooCBShape ("cb3S_1", "FSR cb 3s", 
					   *mass,*mean3S,*sigma3S,*alpha,*npow); 
  RooCBShape  *cb3S_2    = new RooCBShape ("cb3S_2", "FSR cb 3s", 
					   *mass,*mean3S,*sigmaGaus3,*alpha,*npow); 
  RooAddPdf      *sig3S  = new RooAddPdf  ("sig3S","3S mass pdf",
					   RooArgList(*cb3S_1,*cb3S_2),*sigmaFraction);
  // bkg Chebychev
  RooRealVar *nbkgd   = new RooRealVar("n_{Bkgd}","nbkgd",0,nt);
  RooRealVar *bkg_a1  = new RooRealVar("a1_bkg", "bkg_{a1}", 0, -5, 5);
  RooRealVar *bkg_a2  = new RooRealVar("a2_Bkg", "bkg_{a2}", 0, -5, 5);
  RooRealVar *bkg_a3  = new RooRealVar("a3_Bkg", "bkg_{a3}", 0, -2, 2);
  RooAbsPdf  *pdf_combinedbkgd  = new RooChebychev("bkgPdf","bkgPdf",
						   *mass, RooArgList(*bkg_a1,*bkg_a2));
  RooRealVar turnOn("turnOn","turnOn",2.,8.6);
  RooRealVar width("width","width",0.3,8.5);// MB 2.63
  RooRealVar decay("decay","decay",1,18);// MB: 3.39
  RooGenericPdf *ErrPdf     = new  RooGenericPdf("ErrPdf","ErrPdf",
						 "exp(-@0/decay)*(TMath::Erf((@0-turnOn)/width)+1)",
						 RooArgList(*mass,turnOn,width,decay));
  

  // bkg_a2->setVal(0);
  // bkg_a2->setConstant();
  RooDataHist binnedData1 ("binnedData1","binnedData1",*mass,Import(*MReco1));  
  RooDataHist binnedData2 ("binnedData2","binnedData2",*mass,Import(*MReco2));
  RooDataHist binnedData3 ("binnedData3","binnedData3",*mass,Import(*MReco3));
  RooDataHist binnedData4 ("binnedData4","binnedData4",*mass,Import(*MReco4));
  RooAbsPdf  *pdf             = new RooAddPdf ("pdf","total p.d.f.",
					       RooArgList(*sig1S,*sig2S,*sig3S,*ErrPdf),
					       RooArgList(*nsig1f,*nsig2f,*nsig3f,*nbkgd));
  npow->setVal(2);
  npow->setConstant();
  //for the plots!
  TCanvas c; c.cd();  
  TPad phead("phead","phead",0.05,0.9,1.,1.,0,0,0); 
  phead.Draw(); phead.cd();
  TLatex *cms = new TLatex (0.1,0.1,"CMS Internal");
  cms->SetTextFont(40);
  cms->SetTextSize(0.4);
  cms->SetTextColor(kBlack);
  cms->Draw();  
  if(pbpb){  TLatex *pbpb = new TLatex (0.6,0.1,"PbPb #sqrt{s_{NN}} = 2.76 TeV");
  pbpb->SetTextFont(42);
  pbpb->SetTextSize(0.35);
  pbpb->SetTextColor(kBlack);
  pbpb->Draw(); 
  }else if(!pbpb){
  TLatex *pp = new TLatex (0.6,0.1,"pp #sqrt{s} = 2.76 TeV");
  pp->SetTextFont(42);
  pp->SetTextSize(0.35);
  pp->SetTextColor(kBlack);
  pp->Draw();    
  }
  TPad pbody("pbody","pbody",0.0,0.0,1.,0.9,0,0,0);
  c.cd();
  pbody.SetLeftMargin(0.15);
  pbody.Draw(); pbody.cd();
  RooPlot* frame = mass->frame(Bins(70),Range(7,14));
  // 1st round
    RooAbsReal* nll1 = pdf->createNLL(binnedData1,NumCPU(4)) ;
    RooMinuit(*nll1).migrad();
    RooMinuit(*nll1).hesse();
    binnedData1.plotOn(frame,Name("theData"),MarkerSize(0.6),MarkerStyle(20),MarkerColor(kBlue));   
    pdf->plotOn(frame,Name("thePdf"),LineColor(kBlue)); 
    double signif1 = nsig1f->getVal()/nsig1f->getError();
    double signif1_2s = nsig2f->getVal()/nsig2f->getError();
    double signif1_3s = nsig3f->getVal()/nsig3f->getError();
    MReco1->SetMarkerSize(1.0);
    MReco1->SetMarkerStyle(20);
    MReco1->SetMarkerColor(kBlue);
    MReco1->Draw("esame");  
    // 2nd round
    RooAbsReal* nll2 = pdf->createNLL(binnedData2,NumCPU(4)) ;
    RooMinuit(*nll2).migrad();
    RooMinuit(*nll2).hesse();
    binnedData2.plotOn(frame,Name("theData"),MarkerSize(0.6),MarkerStyle(20),MarkerColor(kRed));   
    pdf->plotOn(frame,Name("thePdf"),LineColor(kRed)); 
    double signif2 = nsig1f->getVal()/nsig1f->getError();
    double signif2_2s = nsig2f->getVal()/nsig2f->getError();
    double signif2_3s = nsig3f->getVal()/nsig3f->getError();
    MReco2->SetMarkerSize(1.0);
    MReco2->SetMarkerStyle(20);
    MReco2->SetMarkerColor(kRed);
    MReco2->Draw("esame");  
    // 3rd round
    RooAbsReal* nll3 = pdf->createNLL(binnedData3,NumCPU(4)) ;
    RooMinuit(*nll3).migrad();
    RooMinuit(*nll3).hesse();
    binnedData3.plotOn(frame,Name("theData"),MarkerSize(0.6),MarkerStyle(20),MarkerColor(8));   
    pdf->plotOn(frame,Name("thePdf"),LineColor(8)); 
    double signif3 = nsig1f->getVal()/nsig1f->getError();
    double signif3_2s = nsig2f->getVal()/nsig2f->getError();
    double signif3_3s = nsig3f->getVal()/nsig3f->getError();
    MReco3->SetMarkerSize(1.0);
    MReco3->SetMarkerStyle(20);
    MReco3->SetMarkerColor(8);
    MReco3->Draw("esame");  
    // 4th round
    RooAbsReal* nll4 = pdf->createNLL(binnedData4,NumCPU(4)) ;
    RooMinuit(*nll4).migrad();
    RooMinuit(*nll4).hesse();
    binnedData4.plotOn(frame,Name("theData"),MarkerSize(0.6),MarkerStyle(20),MarkerColor(28));   
    pdf->plotOn(frame,Name("thePdf"),LineColor(28)); 
    double signif4 = nsig1f->getVal()/nsig1f->getError();
    double signif4_2s = nsig2f->getVal()/nsig2f->getError();
    double signif4_3s = nsig3f->getVal()/nsig3f->getError();
    // pdf->paramOn(frame,Layout(0.5,0.95,0.9),Parameters(RooArgSet(signif)),Format("N",AutoPrecision(1)));
    MReco4->SetMarkerSize(1.0);
    MReco4->SetMarkerStyle(20);
    MReco4->SetMarkerColor(28);
    MReco4->Draw("esame");  
    // and all that.
    frame->SetTitle("");
    frame->GetXaxis()->SetTitle("m_{#mu^{+}#mu^{-}} (GeV/c^{2})");
    frame->GetXaxis()->CenterTitle(kTRUE);
    frame->GetYaxis()->SetTitleOffset(2);
    frame->GetXaxis()->SetTitleOffset(1.5);
    frame->Draw();
    TLegend *legend = new TLegend(0.5,0.6,0.95,0.9);
    legend->SetTextSize(0.034);
    legend->SetFillStyle(0);
    legend->SetFillColor(0);
    legend->SetBorderSize(0);
    legend->SetTextFont(42);
    legend->AddEntry(MReco1,"1S significance, #Sigma","");
    switch (kCut){
    case 1: //vProb]   
      legend->AddEntry(MReco1,"Vertex Probability","");
      legend->AddEntry(MReco1,Form("%s, #Sigma = %0.2f",cut[0].c_str(),signif1),"p");
      legend->AddEntry(MReco2,Form("%s, #Sigma = %0.2f",cut[1].c_str(),signif2),"p");
      legend->AddEntry(MReco3,Form("%s, #Sigma = %0.2f",cut[2].c_str(),signif3),"p");
      legend->AddEntry(MReco4,Form("%s, #Sigma = %0.2f",cut[3].c_str(),signif4),"p");
      break;
    case 2:   
      legend->AddEntry(MReco1,"Dist. of closest approach","");
      legend->AddEntry(MReco1,Form("%s, #Sigma = %0.2f",cut[0].c_str(),signif1),"p");
      legend->AddEntry(MReco2,Form("%s, #Sigma = %0.2f",cut[1].c_str(),signif2),"p");
      legend->AddEntry(MReco3,Form("%s, #Sigma = %0.2f",cut[2].c_str(),signif3),"p");
      legend->AddEntry(MReco4,Form("%s, #Sigma = %0.2f",cut[3].c_str(),signif4),"p");
      break;
    case 3:
      legend->AddEntry(MReco1,"Stations matched to each track","");
      legend->AddEntry(MReco1,Form("%s, #Sigma = %0.2f",cutname[0].c_str(),signif1),"p");
      legend->AddEntry(MReco2,Form("%s, #Sigma = %0.2f",cutname[1].c_str(),signif2),"p");
      legend->AddEntry(MReco3,Form("%s, #Sigma = %0.2f",cutname[2].c_str(),signif3),"p");
      legend->AddEntry(MReco4,Form("%s, #Sigma = %0.2f",cutname[3].c_str(),signif4),"p");
      break;
    case 4:
      legend->AddEntry(MReco1,"Pseudo-proper decay length","");
      legend->AddEntry(MReco1,Form("%s, #Sigma = %0.2f",cutname[0].c_str(),signif1),"p");
      legend->AddEntry(MReco2,Form("%s, #Sigma = %0.2f",cutname[1].c_str(),signif2),"p");
      legend->AddEntry(MReco3,Form("%s, #Sigma = %0.2f",cutname[2].c_str(),signif3),"p");
      legend->AddEntry(MReco4,Form("%s, #Sigma = %0.2f",cutname[3].c_str(),signif4),"p");
      break;
    default: break;
    }
    legend->Draw();
    //    legend->AddEntry(MReco1,Form(",),"f");
    // TLatex latex1;
    // latex1.SetNDC();
    // latex1.SetTextSize(0.032);
    // latex1.DrawLatex(0.35,1.-0.05*2.,Form("significance: #Sigma vs %s",cut[0].c_str()));
    // latex1.DrawLatex(0.55,1.-0.05*3.,Form(" #Sigma = %f",signif1));
    // latex1.DrawLatex(0.55,1.-0.05*4.,Form(" #Sigma = %f",signif2));
    // latex1.DrawLatex(0.55,1.-0.05*5.,Form(" #Sigma = %f",signif3));
    // latex1.DrawLatex(0.55,1.-0.05*6.,Form(" #Sigma = %f",signif4));
    c.Draw();
    if(pbpb){
      c.SaveAs("~/Desktop/Grenelle/"+figName_+".pdf");
    }
    else if(!pbpb){
      c.SaveAs("~/Desktop/Grenelle/"+figName_+"_pp.pdf");
    }
   
    cout <<" SIGNIFICANCES \\Sigma OF ALL STATES:" << endl;
    cout << "xxxx - \\Sigma(1S) \&  \\Sigma(2S) \& \\Sigma(3S) " <<endl;
    cout << cut[0].c_str() <<" & "<< signif1 << " &"<< signif1_2s << " & "<< signif1_3s << endl;
    cout << cut[1].c_str() <<" & "<< signif2 << " &"<< signif2_2s << " & "<< signif2_3s << endl;
    cout << cut[2].c_str() <<" & "<< signif3 << " &"<< signif3_2s << " & "<< signif3_3s << endl;
    cout << cut[3].c_str() <<" & "<< signif4 << " &"<< signif4_2s << " & "<< signif4_3s << endl;
}
   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() ;

   }
void eregtestingExample(bool dobarrel=true, bool doele=true) {
  
  //output dir
  TString dirname = "/data/bendavid/eregexampletest/eregexampletest_test/"; 
  gSystem->mkdir(dirname,true);
  gSystem->cd(dirname);    
  
  //read workspace from training
  TString fname;
  if (doele && dobarrel) 
    fname = "wereg_ele_eb.root";
  else if (doele && !dobarrel) 
    fname = "wereg_ele_ee.root";
  else if (!doele && dobarrel) 
    fname = "wereg_ph_eb.root";
  else if (!doele && !dobarrel) 
    fname = "wereg_ph_ee.root";
  
  TString infile = TString::Format("/data/bendavid/eregexampletest/%s",fname.Data());
  
  TFile *fws = TFile::Open(infile); 
  RooWorkspace *ws = (RooWorkspace*)fws->Get("wereg");
  
  //read variables from workspace
  RooGBRTargetFlex *meantgt = static_cast<RooGBRTargetFlex*>(ws->arg("sigmeant"));  
  RooRealVar *tgtvar = ws->var("tgtvar");
  
  
  RooArgList vars;
  vars.add(meantgt->FuncVars());
  vars.add(*tgtvar);
   
  //read testing dataset from TTree
  RooRealVar weightvar("weightvar","",1.);

  TTree *dtree;
  
  if (doele) {
    //TFile *fdin = TFile::Open("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-zllm50-v7n_noskim.root");
    TFile *fdin = TFile::Open("/data/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-zllm50-v7n_noskim.root");

    TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterSingleInvert");
    dtree = (TTree*)ddir->Get("hPhotonTreeSingle");       
  }
  else {
    TFile *fdin = TFile::Open("root://eoscms.cern.ch///eos/cms/store/cmst3/user/bendavid/idTreesAug1/hgg-2013Final8TeV_ID_s12-h124gg-gf-v7n_noskim.root");
    TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterPreselNoSmear");
    dtree = (TTree*)ddir->Get("hPhotonTreeSingle");       
  }
  
  //selection cuts for testing
  TCut selcut;
  if (dobarrel) 
    selcut = "ph.genpt>25. && ph.isbarrel && ph.ispromptgen"; 
  else
    selcut = "ph.genpt>25. && !ph.isbarrel && ph.ispromptgen"; 
  
  TCut selweight = "xsecweight(procidx)*puweight(numPU,procidx)";
  TCut prescale10 = "(evt%10==0)";
  TCut prescale10alt = "(evt%10==1)";
  TCut prescale25 = "(evt%25==0)";
  TCut prescale100 = "(evt%100==0)";  
  TCut prescale1000 = "(evt%1000==0)";  
  TCut evenevents = "(evt%2==0)";
  TCut oddevents = "(evt%2==1)";
  TCut prescale100alt = "(evt%100==1)";
  TCut prescale1000alt = "(evt%1000==1)";
  TCut prescale50alt = "(evt%50==1)";
  
  if (doele) 
    weightvar.SetTitle(prescale100alt*selcut);
  else
    weightvar.SetTitle(selcut);
  
  //make testing dataset
  RooDataSet *hdata = RooTreeConvert::CreateDataSet("hdata",dtree,vars,weightvar);   

  if (doele) 
    weightvar.SetTitle(prescale1000alt*selcut);
  else
    weightvar.SetTitle(prescale10alt*selcut);
  //make reduced testing dataset for integration over conditional variables
  RooDataSet *hdatasmall = RooTreeConvert::CreateDataSet("hdatasmall",dtree,vars,weightvar);     
    
  //retrieve full pdf from workspace
  RooAbsPdf *sigpdf = ws->pdf("sigpdf");
  
  //input variable corresponding to sceta
  RooRealVar *scetavar = ws->var("var_1");
  
  //regressed output functions
  RooAbsReal *sigmeanlim = ws->function("sigmeanlim");
  RooAbsReal *sigwidthlim = ws->function("sigwidthlim");
  RooAbsReal *signlim = ws->function("signlim");
  RooAbsReal *sign2lim = ws->function("sign2lim");

  //formula for corrected energy/true energy ( 1.0/(etrue/eraw) * regression mean)
  RooFormulaVar ecor("ecor","","1./(@0)*@1",RooArgList(*tgtvar,*sigmeanlim));
  RooRealVar *ecorvar = (RooRealVar*)hdata->addColumn(ecor);
  ecorvar->setRange(0.,2.);
  ecorvar->setBins(800);
  
  //formula for raw energy/true energy (1.0/(etrue/eraw))
  RooFormulaVar raw("raw","","1./@0",RooArgList(*tgtvar));
  RooRealVar *rawvar = (RooRealVar*)hdata->addColumn(raw);
  rawvar->setRange(0.,2.);
  rawvar->setBins(800);

  //clone data and add regression outputs for plotting
  RooDataSet *hdataclone = new RooDataSet(*hdata,"hdataclone");
  RooRealVar *meanvar = (RooRealVar*)hdataclone->addColumn(*sigmeanlim);
  RooRealVar *widthvar = (RooRealVar*)hdataclone->addColumn(*sigwidthlim);
  RooRealVar *nvar = (RooRealVar*)hdataclone->addColumn(*signlim);
  RooRealVar *n2var = (RooRealVar*)hdataclone->addColumn(*sign2lim);
  
  
  //plot target variable and weighted regression prediction (using numerical integration over reduced testing dataset)
  TCanvas *craw = new TCanvas;
  //RooPlot *plot = tgtvar->frame(0.6,1.2,100);
  RooPlot *plot = tgtvar->frame(0.6,2.0,100);
  hdata->plotOn(plot);
  sigpdf->plotOn(plot,ProjWData(*hdatasmall));
  plot->Draw();
  craw->SaveAs("RawE.eps");
  craw->SetLogy();
  plot->SetMinimum(0.1);
  craw->SaveAs("RawElog.eps");
  
  //plot distribution of regressed functions over testing dataset
  TCanvas *cmean = new TCanvas;
  RooPlot *plotmean = meanvar->frame(0.8,2.0,100);
  hdataclone->plotOn(plotmean);
  plotmean->Draw();
  cmean->SaveAs("mean.eps");
  
  
  TCanvas *cwidth = new TCanvas;
  RooPlot *plotwidth = widthvar->frame(0.,0.05,100);
  hdataclone->plotOn(plotwidth);
  plotwidth->Draw();
  cwidth->SaveAs("width.eps");
  
  TCanvas *cn = new TCanvas;
  RooPlot *plotn = nvar->frame(0.,111.,200);
  hdataclone->plotOn(plotn);
  plotn->Draw();
  cn->SaveAs("n.eps");

  TCanvas *cn2 = new TCanvas;
  RooPlot *plotn2 = n2var->frame(0.,111.,100);
  hdataclone->plotOn(plotn2);
  plotn2->Draw();
  cn2->SaveAs("n2.eps");
  
  TCanvas *ceta = new TCanvas;
  RooPlot *ploteta = scetavar->frame(-2.6,2.6,200);
  hdataclone->plotOn(ploteta);
  ploteta->Draw();      
  ceta->SaveAs("eta.eps");  
  

  //create histograms for eraw/etrue and ecor/etrue to quantify regression performance
  TH1 *heraw = hdata->createHistogram("hraw",*rawvar,Binning(800,0.,2.));
  TH1 *hecor = hdata->createHistogram("hecor",*ecorvar);
  
  
  //heold->SetLineColor(kRed);
  hecor->SetLineColor(kBlue);
  heraw->SetLineColor(kMagenta);
  
  hecor->GetXaxis()->SetRangeUser(0.6,1.2);
  //heold->GetXaxis()->SetRangeUser(0.6,1.2);
  
  TCanvas *cresponse = new TCanvas;
  
  hecor->Draw("HIST");
  //heold->Draw("HISTSAME");
  heraw->Draw("HISTSAME");
  cresponse->SaveAs("response.eps");
  cresponse->SetLogy();
  cresponse->SaveAs("responselog.eps");
  
  
  printf("make fine histogram\n");
  TH1 *hecorfine = hdata->createHistogram("hecorfine",*ecorvar,Binning(20e3,0.,2.));

  printf("calc effsigma\n");
  
  double effsigma = effSigma(hecorfine);
  
  printf("effsigma = %5f\n",effsigma);
  
/*  new TCanvas;
  RooPlot *ploteold = testvar.frame(0.6,1.2,100);
  hdatasigtest->plotOn(ploteold);
  ploteold->Draw();    
  
  new TCanvas;
  RooPlot *plotecor = ecorvar->frame(0.6,1.2,100);
  hdatasig->plotOn(plotecor);
  plotecor->Draw(); */   
  
  
}
Beispiel #23
0
int main(int argc, char** argv)
{
  RooMsgService::instance().deleteStream(0);
  RooMsgService::instance().deleteStream(1);
  
  
  //Check if all nedeed arguments to parse are there
  if(argc != 2)
  {
    std::cerr << ">>>>> drawWorkspace::usage: " << argv[0] << " configFileName" << std::endl ;
    return 1;
  }
  
  
  // Parse the config file
  parseConfigFile (argv[1]);
  
  
  //[Input]
  std::string inputDir       = gConfigParser -> readStringOption("Input::inputDir");
  std::string analysisMethod = gConfigParser -> readStringOption("Input::analysisMethod");
  std::string fitMethod      = gConfigParser -> readStringOption("Input::fitMethod");
  
  //[Output]
  std::string outputDir = gConfigParser -> readStringOption("Output::outputDir");
  
  //[Options]
  float mass = gConfigParser -> readIntOption("Options::mH");
    
  float xWidth = gConfigParser -> readFloatOption("Options::xWidth");
  char xWidthChar[50];
  sprintf(xWidthChar,"%d",int(xWidth));
  
  int step = gConfigParser -> readIntOption("Options::step");
  char stepChar[50];
  sprintf(stepChar,"%d",step);
  
  std::string additionalCuts = gConfigParser -> readStringOption("Options::additionalCuts");
  
  std::string flavour = gConfigParser -> readStringOption("Options::flavour");
  
  float sigStrength = gConfigParser -> readFloatOption("Options::sigStrength");
  
  int nToys = gConfigParser -> readIntOption("Options::nToys");
  
  
  if( additionalCuts == "none" )
  {
    inputDir += "/combine_signal/binWidth" + std::string(xWidthChar) + "/step" + std::string(stepChar) + "/";
  }
  else
  {
    inputDir += "/coumbine_signal/binWidth" + std::string(xWidthChar) + "/step" + std::string(stepChar) + "_" + additionalCuts + "/";
  }
  
  // define infile
  std::stringstream inFileName;
  if( analysisMethod != "sidebands" )
    inFileName << inputDir << "/shapes_" << analysisMethod << "_" << fitMethod << "_" << mass << "_" << flavour << ".root";
  else
    inFileName << inputDir << "/shapes_" << analysisMethod << "_" << mass << "_" << flavour << ".root";
  
  std::stringstream outFileName;
  if( analysisMethod != "sidebands" )
    outFileName << outputDir << "/drawWorkspace_" << analysisMethod << "_" << fitMethod << "_" << mass << "_" << flavour << ".root";
  else
    outFileName << outputDir << "/drawWorkspace_" << analysisMethod << "_" << mass << "_" << flavour << ".root";
  
  
  
  
  
  
  //------------------------------------
  // open the file and get the workspace
  
  std::cout << ">>> drawWorkspace::open file " << inFileName.str() << std::endl;
  TFile* inFile  = new TFile((inFileName.str()).c_str(), "READ");
  TFile* outFile = new TFile((outFileName.str()).c_str(),"RECREATE");
  
  inFile -> cd();
  RooWorkspace* workspace = (RooWorkspace*)( inFile->Get("workspace") );
  workspace -> Print();
  
  
  
  //-------------------
  // get the x variable
  
  RooRealVar* x         = (RooRealVar*)( workspace->var("x"));
  RooRealVar* rooXMin   = (RooRealVar*)( workspace->var("rooXMin"));
  RooRealVar* rooXMax   = (RooRealVar*)( workspace->var("rooXMax"));
  RooRealVar* rooXWidth = (RooRealVar*)( workspace->var("rooXWidth"));
 
  x -> setMin(rooXMin->getVal());
  x -> setMax(rooXMax->getVal());
  x -> setBins(int((rooXMax->getVal()-rooXMin->getVal())/rooXWidth->getVal()));
  x -> setRange("signal",GetLepNuWMMIN(mass),GetLepNuWMMAX(mass));
  
  
  
  //-------------------------
  // get the number of events
  
  RooRealVar* rooN_data_obs = (RooRealVar*)( workspace->var("rooN_data_obs") );
  RooRealVar* rooN_ggH      = (RooRealVar*)( workspace->var("rooN_ggH") );
  RooRealVar* rooN_qqH      = (RooRealVar*)( workspace->var("rooN_qqH") );
  
  double n_data_obs = rooN_data_obs -> getVal();
  double n_ggH = sigStrength * (rooN_ggH -> getVal());
  double n_qqH = sigStrength * (rooN_qqH -> getVal());
  double n_H = n_ggH + n_qqH;
  
  
  
  //------------
  // get the pdf
  RooDataHist* data_obs = (RooDataHist*)( workspace->data("data_obs") );
  RooAbsPdf* ggH = (RooAbsPdf*)( workspace->pdf("ggH") );
  RooAbsPdf* qqH = (RooAbsPdf*)( workspace->pdf("qqH") );
  RooGenericPdf* bkg = (RooGenericPdf*)( workspace->pdf("bkg") );
  
  
  
  //-------------------
  // get the parameters  
  
  int nPars = 0;
  if( fitMethod == "exponential" )                 nPars = 1;
  if( fitMethod == "attenuatedExponential" )       nPars = 3;
  if( fitMethod == "doubleExponential" )           nPars = 3;
  if( fitMethod == "attenuatedDoubleExponential" ) nPars = 5;
  
  float* initPars = new float[nPars];
  std::string* initParNames = new std::string[nPars];
  
  if( fitMethod == "exponential")
  {
    RooRealVar* roo_L1 = (RooRealVar*)( workspace->var(("CMS_HWWlvjj_"+flavour+"_L1").c_str()) );
    initPars[0] = roo_L1 -> getVal();
    initParNames[0] == "L1";
  }
  
  if( fitMethod == "attenuatedExponential")
  {
    RooRealVar* roo_mu = (RooRealVar*)( workspace->var(("CMS_HWWlvjj_"+flavour+"_mu").c_str()) );
    initPars[0] = roo_mu -> getVal();
    initParNames[0] = "mu";
    
    RooRealVar* roo_kT = (RooRealVar*)( workspace->var(("CMS_HWWlvjj_"+flavour+"_kT").c_str()) );
    initPars[1] = roo_kT -> getVal();
    initParNames[1] = "kT";
    
    RooRealVar* roo_L1 = (RooRealVar*)( workspace->var(("CMS_HWWlvjj_"+flavour+"_L1").c_str()) );
    initPars[2] = roo_L1 -> getVal();
    initParNames[2] = "L1";
  }
  
  if( fitMethod == "doubleExponential")
  {
    RooRealVar* roo_N = (RooRealVar*)( workspace->var(("CMS_HWWlvjj_"+flavour+"_N").c_str()) );
    initPars[0] = roo_N -> getVal();
    initParNames[0] = "N";
    
    RooRealVar* roo_L1 = (RooRealVar*)( workspace->var(("CMS_HWWlvjj_"+flavour+"_L1").c_str()) );
    initPars[1] = roo_L1 -> getVal();
    initParNames[1] = "L1";
    
    RooRealVar* roo_L2 = (RooRealVar*)( workspace->var(("CMS_HWWlvjj_"+flavour+"_L2").c_str()) );
    initPars[2] = roo_L2 -> getVal();
    initParNames[2] = "L2";
  }
  
  if( fitMethod == "attenuatedDoubleExponential")
  {
    RooRealVar* roo_mu = (RooRealVar*)( workspace->var(("CMS_HWWlvjj_"+flavour+"_mu").c_str()) );
    initPars[0] = roo_mu -> getVal();
    initParNames[0] = "mu";
    
    RooRealVar* roo_kT = (RooRealVar*)( workspace->var(("CMS_HWWlvjj_"+flavour+"_kT").c_str()) );
    initPars[1] = roo_kT -> getVal();
    initParNames[1] = "kT";
    
    RooRealVar* roo_N = (RooRealVar*)( workspace->var(("CMS_HWWlvjj_"+flavour+"_N").c_str()) );
    initPars[2] = roo_N -> getVal();
    initParNames[2] = "N";
    
    RooRealVar* roo_L1 = (RooRealVar*)( workspace->var(("CMS_HWWlvjj_"+flavour+"_L1").c_str()) );
    initPars[3] = roo_L1 -> getVal();
    initParNames[3] = "L1";
    
    RooRealVar* roo_L2 = (RooRealVar*)( workspace->var(("CMS_HWWlvjj_"+flavour+"_L2").c_str()) );
    initPars[4] = roo_L2 -> getVal();
    initParNames[4] = "L2";
  }
  
  
  
  
  
  
  std::cout << "\n\n\n***********************************************************" << std::endl;
  std::cout << "*** VARIABLES ***" << std::endl;
  std::cout << "***********************************************************" << std::endl;
  
  std::cout << "x: "      << x->getVal() << std::endl;
  std::cout << "xMin: "   << rooXMin->getVal() << std::endl;
  std::cout << "xMax: "   << rooXMax->getVal() << std::endl;
  std::cout << "xWidth: " << rooXWidth->getVal() << std::endl;
  
  std::cout << "n_data_obs: " << n_data_obs << std::endl;
  std::cout << "n_ggH: "      << n_ggH      << std::endl;
  std::cout << "n_qqH: "      << n_qqH      << std::endl;
  
  
  
  std::cout << "\n\n\n***********************************************************" << std::endl;
  std::cout << "*** PARAMETERS ***" << std::endl;
  std::cout << "***********************************************************" << std::endl;
  
  for(int parIt = 0; parIt < nPars; ++parIt)
  {
    std::cout << initParNames[parIt] << ": " << initPars[parIt] << std::endl;
  }
  
  
  
  
  
  
  std::cout << "\n\n\n***********************************************************" << std::endl;
  std::cout << "*** PRINT HISTOGRAMS ***" << std::endl;
  std::cout << "***********************************************************" << std::endl;
  
  outFile -> cd();
  
  TCanvas* c_data_obs = new TCanvas("c_data_obs","c_data_obs");  
  RooPlot* plot_data_obs = x->frame();
  data_obs -> plotOn(plot_data_obs);
  plot_data_obs -> Draw();
  c_data_obs -> Write();
  delete plot_data_obs;
  delete c_data_obs;
  
  
  TCanvas* c_H = new TCanvas("c_H","c_H");
  RooPlot* plot_H = x->frame();
  ggH -> plotOn(plot_H,LineColor(kRed));
  qqH -> plotOn(plot_H,LineColor(kBlue));
  plot_H -> Draw();
  c_H -> Write();
  delete plot_H;
  delete c_H;
  

  TCanvas* c_bkg = new TCanvas("c_bkg","c_bkg");
  RooPlot* plot_bkg = x->frame();
  bkg -> plotOn(plot_bkg,LineColor(kRed));
  plot_bkg -> Draw();
  c_bkg -> Write();
  delete plot_bkg;
  delete c_bkg;
  
  
  
  
  
  
  std::cout << "\n\n\n***********************************************************" << std::endl;
  std::cout << "*** FIT B ***" << std::endl;
  std::cout << "***********************************************************" << std::endl;
  
  inFile -> cd();
  
  RooRealVar* B = new RooRealVar("B","",n_data_obs,0.,2.*n_data_obs);
  RooAddPdf* rooTotPdf_B = new RooAddPdf("rooTotPdf_B","",RooArgList(*bkg),RooArgList(*B));
  rooTotPdf_B -> fitTo(*data_obs,Extended(kTRUE),Save(),PrintLevel(-1));
  
  std::cout  << ">>> B: " << B -> getVal() << std::endl;
  
  
  outFile -> cd();
  
  TCanvas* c_fit_B = new TCanvas("c_fit_B","c_fit_B");
  RooPlot* plot_fit_B = x->frame();
  data_obs -> plotOn(plot_fit_B);
  rooTotPdf_B -> plotOn(plot_fit_B);
  plot_fit_B -> Draw();
  c_fit_B -> Write();
  delete plot_fit_B;
  delete c_fit_B;
  
  
  
  
  
  
  std::cout << "\n\n\n***********************************************************" << std::endl;
  std::cout << "*** TOY EXPERIMENTS ***" << std::endl;
  std::cout << "***********************************************************" << std::endl;
  
  inFile -> cd();
  
  TH1F* h_diffB_parentB_fitB   = new TH1F("h_diffB_parentB_fitB",  "",400,-1.,1.);
  TH1F* h_diffB_parentBS_fitB  = new TH1F("h_diffB_parentBS_fitB", "",400,-1.,1.);
  TH1F* h_diffB_parentBS_fitBS = new TH1F("h_diffB_parentBS_fitBS","",400,-1.,1.);
  TH1F* h_diffS_parentBS_fitBS = new TH1F("h_diffS_parentBS_fitBS","",400,-1.,1.);
  
  
  
  //--------------------------------------1.
  // define background parent distribution
  
  RooRealVar** pars = new RooRealVar*[nPars];
  RooGenericPdf* rooParentPdf_B;
  
  if( fitMethod == "exponential" )
  {
    pars[0] = new RooRealVar("parent_L1","",initPars[0],initPars[0],initPars[0]);
    rooParentPdf_B = new RooGenericPdf("rooParentPdf_B","","exp(-1*@1*@0)",RooArgSet(*x,*pars[0]));
  }
  
  if( fitMethod == "attenuatedExponential" )
  {
    pars[0] = new RooRealVar("parent_mu","",initPars[0],initPars[0],initPars[0]);
    pars[1] = new RooRealVar("parent_kT","",initPars[1],initPars[1],initPars[1]);
    pars[2] = new RooRealVar("parent_L1","",initPars[2],initPars[2],initPars[2]);
    rooParentPdf_B = new RooGenericPdf("rooParentPdf_B","","1./(exp(-1.*(@0-@1)/@2)+1.) * exp(-1*@3*@0)",RooArgSet(*x,*pars[0],*pars[1],*pars[2]));
  }
  
  if( fitMethod == "doubleExponential" )
  {
    pars[0] = new RooRealVar("parent_N","", initPars[0],initPars[0],initPars[0]);
    pars[1] = new RooRealVar("parent_L1","",initPars[1],initPars[1],initPars[1]);
    pars[2] = new RooRealVar("parent_L2","",initPars[2],initPars[2],initPars[2]);
    rooParentPdf_B = new RooGenericPdf("rooParentPdf_B","","(exp(-1*@2*@0) + @1*exp(-1*@3*@0))",RooArgSet(*x,*pars[0],*pars[1],*pars[2]));
  }
  
  if( fitMethod == "attenuatedDoubleExponential" )
  {
    pars[0] = new RooRealVar("parent_mu","",initPars[0],initPars[0],initPars[0]);
    pars[1] = new RooRealVar("parent_kT","",initPars[1],initPars[1],initPars[1]);
    pars[2] = new RooRealVar("parent_N","", initPars[2],initPars[2],initPars[2]);
    pars[3] = new RooRealVar("parent_L1","",initPars[3],initPars[3],initPars[3]);
    pars[4] = new RooRealVar("parent_L2","",initPars[4],initPars[4],initPars[4]);
    rooParentPdf_B = new RooGenericPdf("bkg","","1./(exp(-1.*(@0-@1)/@2)+1.) * (exp(-1*@4*@0) + @3*exp(-1*@5*@0))",RooArgSet(*x,*pars[0],*pars[1],*pars[2],*pars[3],*pars[4]));
  }
  
  RooAbsReal* integral_parent_B = rooParentPdf_B -> createIntegral(*x,NormSet(*x),Range("signal"));
  double n_parent_B = integral_parent_B->getVal() * int(n_data_obs);
  std::cout << ">>> n_parent_B: " << n_parent_B << std::endl; 
  
  
  
  //----------------------------------
  // define signal parent distribution
  
  RooGenericPdf* rooParentPdf_ggS = (RooGenericPdf*)( ggH->Clone("rooParentPdf_ggS") );
  RooGenericPdf* rooParentPdf_qqS = (RooGenericPdf*)( qqH->Clone("rooParentPdf_qqS") );
  
  RooAddPdf* rooParentPdf_S = new RooAddPdf("rooParentPdf_S","",RooArgList(*rooParentPdf_ggS,*rooParentPdf_qqS),RooArgList(*rooN_ggH,*rooN_qqH));
  
  RooAbsReal* integral_parent_S = rooParentPdf_S -> createIntegral(*x,NormSet(*x),Range("signal"));
  double n_parent_S = integral_parent_S->getVal() * (n_H);
  std::cout << ">>> n_parent_S: " << n_parent_S << std::endl; 
  
  
  
  //------------
  // create toys
  
  for(int toyIt = 0; toyIt < nToys; ++toyIt)
  {
    if(toyIt%100 == 0) std::cout << ">>> generating toy " << toyIt << " / " << nToys << "\r" << std::flush;
    
    RooDataSet* ds_B_toy = rooParentPdf_B -> generate(*x,int(n_data_obs));
    RooDataHist* dh_B_toy = ds_B_toy -> binnedClone();
    
    RooDataSet* ds_BS_toy = rooParentPdf_S -> generate(*x,int(n_H));
    ds_BS_toy -> append(*ds_B_toy);
    RooDataHist* dh_BS_toy = ds_BS_toy -> binnedClone();
    
    
    
    // generate B - fit B
    RooRealVar* B_toy = new RooRealVar("B_toy","",n_data_obs,0.,2.*n_data_obs);
    
    RooRealVar** pars_toy = new RooRealVar*[nPars];
    RooGenericPdf* bkg_toy;
    InitializeBkgPdf(x,&bkg_toy,pars_toy,initPars,fitMethod,nPars);
    
    RooAddPdf* rooTotPdf_B_toy = new RooAddPdf("rooTotPdf_B_toy","",RooArgList(*bkg_toy),RooArgList(*B_toy));
    rooTotPdf_B_toy -> fitTo(*dh_B_toy,Extended(kTRUE),Save(),PrintLevel(-10));
    
    RooAbsReal* integral_B_toy = rooTotPdf_B_toy -> createIntegral(*x,NormSet(*x),Range("signal"));
    double n_B_toy = integral_B_toy->getVal() * B_toy->getVal();
    
    h_diffB_parentB_fitB -> Fill(n_B_toy/n_parent_B - 1.);
    
    
    
    // generate BS - fit B
    RooRealVar* B2_toy = new RooRealVar("B2_toy","",n_data_obs,0.,2.*n_data_obs);
    
    RooRealVar** pars2_toy = new RooRealVar*[nPars];
    RooGenericPdf* bkg2_toy;
    InitializeBkgPdf(x,&bkg2_toy,pars2_toy,initPars,fitMethod,nPars);
    
    RooAddPdf* rooTotPdf_B2_toy = new RooAddPdf("rooTotPdf_B2_toy","",RooArgList(*bkg2_toy),RooArgList(*B2_toy));
    rooTotPdf_B2_toy -> fitTo(*dh_BS_toy,Extended(kTRUE),Save(),PrintLevel(-10));
    
    RooAbsReal* integral_B2_toy = rooTotPdf_B2_toy -> createIntegral(*x,NormSet(*x),Range("signal"));
    double n_B2_toy = integral_B2_toy->getVal() * B2_toy->getVal();
    
    h_diffB_parentBS_fitB -> Fill(n_B2_toy/n_parent_B - 1.);
    
    
    
    // generate BS - fit BS
    RooRealVar* B3_toy = new RooRealVar("B3_toy","",n_data_obs,0.,2.*n_data_obs);
    RooRealVar* S3_toy = new RooRealVar("S3_toy","",n_H,0.,2.*n_H);
    
    RooRealVar** pars3_toy = new RooRealVar*[nPars];
    RooGenericPdf* bkg3_toy;
    InitializeBkgPdf(x,&bkg3_toy,pars3_toy,initPars,fitMethod,nPars);
    
    RooGenericPdf* sig3_toy = (RooGenericPdf*)( rooParentPdf_S -> Clone("sig3_toy") );
    
    RooAddPdf* rooTotPdf_BS3_toy = new RooAddPdf("rooTotPdf_BS3_toy","",RooArgList(*bkg3_toy,*sig3_toy),RooArgList(*B3_toy,*S3_toy));
    rooTotPdf_BS3_toy -> fitTo(*dh_BS_toy,Extended(kTRUE),Save(),PrintLevel(-10));
    
    RooAbsReal* integral_B3_toy = bkg3_toy -> createIntegral(*x,NormSet(*x),Range("signal"));
    RooAbsReal* integral_S3_toy = sig3_toy -> createIntegral(*x,NormSet(*x),Range("signal"));
    double n_B3_toy = integral_B3_toy->getVal() * B3_toy->getVal();
    double n_S3_toy = integral_S3_toy->getVal() * S3_toy->getVal();
    
    h_diffB_parentBS_fitBS -> Fill(n_B3_toy/n_parent_B - 1.);
    h_diffS_parentBS_fitBS -> Fill(n_S3_toy/n_parent_S - 1.);
    
    
    
    if(toyIt < 10)
    {
      outFile -> cd();
      
      char dirName[50];
      sprintf(dirName,"toy%d",toyIt);
      
      outFile -> mkdir(dirName);
      outFile -> cd(dirName);
      
      char canvasName[50];
      
      sprintf(canvasName,"parentB_fitB_%d",toyIt);
      TCanvas* c_parentB_fitB_toy = new TCanvas(canvasName);
      RooPlot* plot_parentB_fitB_toy = x->frame();
      dh_B_toy -> plotOn(plot_parentB_fitB_toy);
      rooTotPdf_B_toy -> plotOn(plot_parentB_fitB_toy);
      plot_parentB_fitB_toy -> Draw();
      c_parentB_fitB_toy -> Write();
      delete plot_parentB_fitB_toy;
      delete c_parentB_fitB_toy;
      
      sprintf(canvasName,"parentBS_fitB_%d",toyIt);
      TCanvas* c_parentBS_fitB_toy = new TCanvas(canvasName);
      RooPlot* plot_parentBS_fitB_toy = x->frame();
      dh_BS_toy -> plotOn(plot_parentBS_fitB_toy);
      rooTotPdf_B2_toy -> plotOn(plot_parentBS_fitB_toy);
      plot_parentBS_fitB_toy -> Draw();
      c_parentBS_fitB_toy -> Write();
      delete plot_parentBS_fitB_toy;
      delete c_parentBS_fitB_toy;
      
      sprintf(canvasName,"parentBS_fitBS_%d",toyIt);
      TCanvas* c_parentBS_fitBS_toy = new TCanvas(canvasName);
      RooPlot* plot_parentBS_fitBS_toy = x->frame();
      dh_BS_toy -> plotOn(plot_parentBS_fitBS_toy);
      rooTotPdf_BS3_toy -> plotOn(plot_parentBS_fitBS_toy);
      plot_parentBS_fitBS_toy -> Draw();
      c_parentBS_fitBS_toy -> Write();
      delete plot_parentBS_fitBS_toy;
      delete c_parentBS_fitBS_toy;
    }
    
    
    
    delete integral_B_toy;
    delete rooTotPdf_B_toy;
    delete bkg_toy;
    for(int parIt = 0; parIt < nPars; ++parIt)
      delete pars_toy[parIt];
    delete B_toy;
    
    delete integral_B2_toy;
    delete rooTotPdf_B2_toy;
    delete bkg2_toy;
    for(int parIt = 0; parIt < nPars; ++parIt)
      delete pars2_toy[parIt];
    delete B2_toy;
    
    delete integral_B3_toy;
    delete rooTotPdf_BS3_toy;
    delete bkg3_toy;
    for(int parIt = 0; parIt < nPars; ++parIt)
      delete pars3_toy[parIt];
    delete B3_toy;
    
    delete integral_S3_toy;
    delete sig3_toy;
    delete S3_toy;
    
    delete dh_B_toy;
    delete ds_B_toy;
    delete dh_BS_toy;
    delete ds_BS_toy;
  }
  
  
  
  
  outFile -> cd();
  
  h_diffB_parentB_fitB -> Write();
  h_diffB_parentBS_fitB -> Write();
  h_diffB_parentBS_fitBS -> Write();
  h_diffS_parentBS_fitBS -> Write();
  
  outFile -> Close();
  
  
    
  return 0;
}
Beispiel #24
0
   void constrained_scan( const char* wsfile = "outputfiles/ws-lhfit3.root",
                          ///////const char* new_poi_name="mu_qcd_hdp_Nj1_HT1",
                          //////const char* new_poi_name="mu_allnonqcd_ldp_Nj5_HT3",
                          const char* new_poi_name="mu_allnonqcd_ldp_Nj1_HT1",
                          double constraintWidth=1.5,
                          int npoiPoints = 10,
                          double poiMinVal = 5000.,
                          double poiMaxVal = 7000.,
                          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( "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.
void StandardHistFactoryPlotsWithCategories(const char* infile = "",
                                            const char* workspaceName = "combined",
                                            const char* modelConfigName = "ModelConfig",
                                            const char* dataName = "obsData"){


   double nSigmaToVary=5.;
   double muVal=0;
   bool doFit=false;

   // -------------------------------------------------------
   // 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;
   }

   // -------------------------------------------------------
   // now use the profile inspector

   RooRealVar* obs = (RooRealVar*)mc->GetObservables()->first();
   TList* list = new TList();


   RooRealVar * firstPOI = dynamic_cast<RooRealVar*>(mc->GetParametersOfInterest()->first());

   firstPOI->setVal(muVal);
   //  firstPOI->setConstant();
   if(doFit){
      mc->GetPdf()->fitTo(*data);
   }

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


   mc->GetNuisanceParameters()->Print("v");
   int  nPlotsMax = 1000;
   cout <<" check expectedData by category"<<endl;
   RooDataSet* simData=NULL;
   RooSimultaneous* simPdf = NULL;
   if(strcmp(mc->GetPdf()->ClassName(),"RooSimultaneous")==0){
      cout <<"Is a simultaneous PDF"<<endl;
      simPdf = (RooSimultaneous *)(mc->GetPdf());
   } else {
      cout <<"Is not a simultaneous PDF"<<endl;
   }



   if(doFit) {
      RooCategory* channelCat = (RooCategory*) (&simPdf->indexCat());
      TIterator* iter = channelCat->typeIterator() ;
      RooCatType* tt = NULL;
      tt=(RooCatType*) iter->Next();
      RooAbsPdf* pdftmp = ((RooSimultaneous*)mc->GetPdf())->getPdf(tt->GetName()) ;
      RooArgSet* obstmp = pdftmp->getObservables(*mc->GetObservables()) ;
      obs = ((RooRealVar*)obstmp->first());
      RooPlot* frame = obs->frame();
      cout <<Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())<<endl;
      cout << tt->GetName() << " " << channelCat->getLabel() <<endl;
      data->plotOn(frame,MarkerSize(1),Cut(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())),DataError(RooAbsData::None));

      Double_t normCount = data->sumEntries(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())) ;

      pdftmp->plotOn(frame,LineWidth(2.),Normalization(normCount,RooAbsReal::NumEvent)) ;
      frame->Draw();
      cout <<"expected events = " << mc->GetPdf()->expectedEvents(*data->get()) <<endl;
      return;
   }



   int nPlots=0;
   if(!simPdf){

      TIterator* it = mc->GetNuisanceParameters()->createIterator();
      RooRealVar* var = NULL;
      while( (var = (RooRealVar*) it->Next()) != NULL){
         RooPlot* frame = obs->frame();
         frame->SetYTitle(var->GetName());
         data->plotOn(frame,MarkerSize(1));
         var->setVal(0);
         mc->GetPdf()->plotOn(frame,LineWidth(1.));
         var->setVal(1);
         mc->GetPdf()->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(1));
         var->setVal(-1);
         mc->GetPdf()->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(1));
         list->Add(frame);
         var->setVal(0);
      }


   } else {
      RooCategory* channelCat = (RooCategory*) (&simPdf->indexCat());
      //    TIterator* iter = simPdf->indexCat().typeIterator() ;
      TIterator* iter = channelCat->typeIterator() ;
      RooCatType* tt = NULL;
      while(nPlots<nPlotsMax && (tt=(RooCatType*) iter->Next())) {

         cout << "on type " << tt->GetName() << " " << endl;
         // Get pdf associated with state from simpdf
         RooAbsPdf* pdftmp = simPdf->getPdf(tt->GetName()) ;

         // Generate observables defined by the pdf associated with this state
         RooArgSet* obstmp = pdftmp->getObservables(*mc->GetObservables()) ;
         //      obstmp->Print();


         obs = ((RooRealVar*)obstmp->first());

         TIterator* it = mc->GetNuisanceParameters()->createIterator();
         RooRealVar* var = NULL;
         while(nPlots<nPlotsMax && (var = (RooRealVar*) it->Next())){
            TCanvas* c2 = new TCanvas("c2");
            RooPlot* frame = obs->frame();
            frame->SetName(Form("frame%d",nPlots));
            frame->SetYTitle(var->GetName());

            cout <<Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())<<endl;
            cout << tt->GetName() << " " << channelCat->getLabel() <<endl;
            data->plotOn(frame,MarkerSize(1),Cut(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())),DataError(RooAbsData::None));

            Double_t normCount = data->sumEntries(Form("%s==%s::%s",channelCat->GetName(),channelCat->GetName(),tt->GetName())) ;

            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal());
               var->Print();
            } else{
               var->setVal(0);
            }
            // w->allVars().Print("v");
            // mc->GetNuisanceParameters()->Print("v");
            // pdftmp->plotOn(frame,LineWidth(2.));
            // mc->GetPdf()->plotOn(frame,LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            //pdftmp->plotOn(frame,LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            normCount = pdftmp->expectedEvents(*obs);
            pdftmp->plotOn(frame,LineWidth(2.),Normalization(normCount,RooAbsReal::NumEvent)) ;

            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal()+0.05);
               var->Print();
            } else{
               var->setVal(nSigmaToVary);
            }
            // pdftmp->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(2));
            // mc->GetPdf()->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            //pdftmp->plotOn(frame,LineColor(kRed),LineStyle(kDashed),LineWidth(2.),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            normCount = pdftmp->expectedEvents(*obs);
            pdftmp->plotOn(frame,LineWidth(2.),LineColor(kRed),LineStyle(kDashed),Normalization(normCount,RooAbsReal::NumEvent)) ;

            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal()-0.05);
               var->Print();
            } else{
               var->setVal(-nSigmaToVary);
            }
            // pdftmp->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(2));
            // mc->GetPdf()->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(2),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            //pdftmp->plotOn(frame,LineColor(kGreen),LineStyle(kDashed),LineWidth(2),Slice(*channelCat,tt->GetName()),ProjWData(*data));
            normCount = pdftmp->expectedEvents(*obs);
            pdftmp->plotOn(frame,LineWidth(2.),LineColor(kGreen),LineStyle(kDashed),Normalization(normCount,RooAbsReal::NumEvent)) ;



            // set them back to normal
            if(strcmp(var->GetName(),"Lumi")==0){
               cout <<"working on lumi"<<endl;
               var->setVal(w->var("nominalLumi")->getVal());
               var->Print();
            } else{
               var->setVal(0);
            }

            list->Add(frame);

            // quit making plots
            ++nPlots;

            frame->Draw();
            c2->SaveAs(Form("%s_%s_%s.pdf",tt->GetName(),obs->GetName(),var->GetName()));
            delete c2;
         }
      }
   }



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


   // now make plots
   TCanvas* c1 = new TCanvas("c1","ProfileInspectorDemo",800,200);
   if(list->GetSize()>4){
      double n = list->GetSize();
      int nx = (int)sqrt(n) ;
      int ny = TMath::CeilNint(n/nx);
      nx = TMath::CeilNint( sqrt(n) );
      c1->Divide(ny,nx);
   } else
      c1->Divide(list->GetSize());
   for(int i=0; i<list->GetSize(); ++i){
      c1->cd(i+1);
      list->At(i)->Draw();
   }





}
double RunHypoTest(char *smwwFileName, char *ttbarFileName, char *wp3jetsFileName, char *wp4jetsFileName, char *opsFileName, char *outputFileName, double lambda) {
    TFile *smwwFile = new TFile(smwwFileName);
    TFile *ttbarFile = new TFile(ttbarFileName);
    TFile *wp3jetsFile = new TFile(wp3jetsFileName);
    TFile *wp4jetsFile = new TFile(wp4jetsFileName);
    TFile *opsFile = new TFile(opsFileName);

    TFile *outputFile = new TFile(outputFileName, "UPDATE");

    TH1F *smww = (TH1F*)smwwFile->Get(WW_MASS_HISTOGRAM_NAME);
    TH1F *ttbar = (TH1F*)ttbarFile->Get(WW_MASS_HISTOGRAM_NAME);
    TH1F *wp3jets = (TH1F*)wp3jetsFile->Get(WW_MASS_HISTOGRAM_NAME);
    TH1F *wp4jets = (TH1F*)wp4jetsFile->Get(WW_MASS_HISTOGRAM_NAME);

    //Histogram of ww-scattering with effective operator contributions
    TH1F *ops = (TH1F*)opsFile->Get(WW_MASS_HISTOGRAM_NAME);

    RooRealVar *mww = new RooRealVar("mww", "M_{WW}", 600, 2500, "GeV");

    RooDataHist smData("smData", "smData", RooArgList(*mww), smww);
    RooDataHist opsData("opsData", "opsData", RooArgList(*mww), ops);
    RooDataHist ttbarData("ttbarData", "ttbarData", RooArgList(*mww), ttbar);
    RooDataHist wp3jetsData("wp3jetsData", "wp3jetsData", RooArgList(*mww), wp3jets);
    RooDataHist wp4jetsData("wp4jetsData", "wp4jetsData", RooArgList(*mww), wp4jets);


    /*
    RooAbsPdf *opsModel;
    if (lambda == 400) {

        opsModel = SpecialCaseModel(&opsData, mww, (char*)"ops");
    }
    else {
        opsModel = MakeModel(&opsData, mww, (char*)"ops");
    }*/
    RooAbsPdf *opsModel = MakeModel(&opsData, mww, (char*)"ops");
    //RooPlot *xframe = mww->frame();
    //opsData.plotOn(xframe);
    //opsModel->plotOn(xframe);
    //printf("Chi-squared for lambda = %f: = %f\n", lambda, xframe->chiSquare("opsModel", "opsData", 3));


    RooAbsPdf *smModel = MakeModelNoSignal(&smData, mww, (char*)"sm");

    RooAbsPdf *ttbarModel = MakeModelNoSignal(&ttbarData, mww, (char*)"ttbar");
    RooAbsPdf *wp3jetsModel = MakeModelNoSignal(&wp3jetsData, mww, (char*)"wp3jets");
    RooAbsPdf *wp4jetsModel = MakeModelNoSignal(&wp4jetsData, mww, (char*)"wp4jets");

    TCanvas *canvas = new TCanvas(opsFileName);
    RooPlot *frame = mww->frame();
    frame->SetTitle("");
    //smData.plotOn(frame, RooFit::LineColor(kBlack), RooFit::Name("smData"));

    //smModel->plotOn(frame, RooFit::LineColor(kBlue), RooFit::Name("smModel"));
    //ttbarModel->plotOn(frame, RooFit::LineColor(kRed), RooFit::Name("ttbarModel"));
    //wp3jetsModel->plotOn(frame, RooFit::LineColor(kYellow), RooFit::Name("wpjetsModel"));
    opsData.plotOn(frame);
    opsModel->plotOn(frame, RooFit::LineColor(kBlue), RooFit::Name("opsModel"));
    //leg->AddEntry(frame->findObject("smModel"), "SM Model", "lep");
    //leg->AddEntry(frame->findObject("ttbarModel"), "TTBar Model", "lep");
    //leg->AddEntry(frame->findObject("wp3jetsModel"), "WP3Jets Model", "lep");
    //leg->AddEntry(frame->findObject("opsModel"), "Effective Operator Model", "lep");

    frame->Draw();
    canvas->Write();

    Double_t ww_x = WW_CROSS_SECTION * smww->GetEntries();
    Double_t ttbar_x = TTBAR_CROSS_SECTION * ttbar->GetEntries();
    Double_t wp3jets_x = WP3JETS_CROSS_SECTION * wp3jets->GetEntries();
    Double_t wp4jets_x = WP4JETS_CROSS_SECTION * wp4jets->GetEntries();


    Double_t ttbar_weight = ttbar_x/(ttbar_x + wp3jets_x + wp4jets_x + ww_x);
    Double_t wp3jets_weight = wp3jets_x/(wp3jets_x + ttbar_x + ww_x);
    Double_t wp4jets_weight = wp4jets_x/(wp4jets_x + ttbar_x + ww_x);

    RooRealVar *ttbarWeight = new RooRealVar("ttbarWeight", "ttbarWeight", 0.0, 1.0, ttbar_weight);
    RooRealVar *wp3jetsWeight = new RooRealVar("wp3jetsWeight", "wp3jetsWeight", 0.0, 1.0, wp3jets_weight);
    RooRealVar *wp4jetsWeight = new RooRealVar("wp4jetsWeight", "wp4jetsWeight", 0.0, 1.0, wp4jets_weight);

    ttbarWeight->setConstant();
    wp3jetsWeight->setConstant();
    wp4jetsWeight->setConstant();

    RooRealVar *mu = new RooRealVar("mu", "mu", 0.0, 1.0, "");
    RooAddPdf *wwModel = new RooAddPdf("wwModel", "u*effective_ww + (1-u)*SM_WW", 
            RooArgList(*opsModel, *smModel), RooArgList(*mu), kTRUE);

    RooAddPdf *model = new RooAddPdf("model", "Full model", 
            RooArgList(*ttbarModel, *wp3jetsModel, *wp4jetsModel, *wwModel), 
            RooArgList(*ttbarWeight, *wp3jetsWeight, *wp4jetsWeight), kTRUE);

    //Generate data under the alternate hypothesis
    mu->setVal(1.0);
    int nTestSetEvents = WW_CROSS_SECTION * TOTAL_INTEGRATED_LUMINOSITY;
    RooAbsData *generatedData = model->generate(*mww, nTestSetEvents);

    TCanvas *canvas2 = new TCanvas("CombinedModels");
    RooPlot *frame2 = mww->frame();
    //wwModel->plotOn(frame2, RooFit::LineColor(kRed), RooFit::Name("wwModel"));
    //generatedData->plotOn(frame2);
    mu->setVal(0.0);
    model->plotOn(frame2, RooFit::LineColor(kBlue), RooFit::Name("nullModel"));
    mu->setVal(1.0);
    model->plotOn(frame2, RooFit::LineColor(kRed), RooFit::Name("altModel"));
    TLegend *leg2 = new TLegend(0.65,0.73,0.86,0.87);
    //leg->AddEntry(frame2->findObject("wwModel"), "SM WW Scattering model with background",
    //        "lep");
    leg2->AddEntry(frame2->findObject("nullModel"), 
            "SM + Background", "lep");
    leg2->AddEntry(frame2->findObject("altModel"), 
            "Effective Operator + Background", "lep");
    frame2->SetTitle("");
    frame2->GetXaxis()->SetTitle("M_{WW} (GeV)");
    frame2->GetYaxis()->SetTitle("");
    frame2->Draw();
    leg2->Draw();
    canvas2->Write();
    outputFile->Close();

    
    RooArgSet poi(*mu);
    RooArgSet *nullParams = (RooArgSet*) poi.snapshot(); 

    nullParams->setRealValue("mu", 0.0); 

    RooStats::ProfileLikelihoodCalculator plc(*generatedData, *model, poi, 0.05, nullParams);


    RooStats::HypoTestResult* htr = plc.GetHypoTest();
    std::cerr << "P Value = " << htr->NullPValue() << "\n";
    return htr->Significance();
}
void eregtesting_13TeV_Pi0(bool dobarrel=true, bool doele=false,int gammaID=0) {
  
  //output dir
  TString EEorEB = "EE";
  if(dobarrel)
	{
	EEorEB = "EB";
	}
  TString gammaDir = "bothGammas";
  if(gammaID==1)
  {
   gammaDir = "gamma1";
  }
  else if(gammaID==2)
  {
   gammaDir = "gamma2";
  }
  TString dirname = TString::Format("ereg_test_plots_Pi0/%s_%s",gammaDir.Data(),EEorEB.Data());
  TString dirname_fits = TString::Format("ereg_test_plots_Pi0/%s_%s/fits",gammaDir.Data(),EEorEB.Data());
  
  gSystem->mkdir(dirname,true);
  gSystem->mkdir(dirname_fits,true);
  gSystem->cd(dirname);    
  
  //read workspace from training
  TString fname;
  if (doele && dobarrel) 
    fname = "wereg_ele_eb.root";
  else if (doele && !dobarrel) 
    fname = "wereg_ele_ee.root";
  else if (!doele && dobarrel) 
    fname = "wereg_ph_eb.root";
  else if (!doele && !dobarrel) 
    fname = "wereg_ph_ee.root";
  
  TString infile = TString::Format("../../ereg_ws_Pi0/%s/%s",gammaDir.Data(),fname.Data());
  
  TFile *fws = TFile::Open(infile); 
  RooWorkspace *ws = (RooWorkspace*)fws->Get("wereg");
  
  //read variables from workspace
  RooGBRTargetFlex *meantgt = static_cast<RooGBRTargetFlex*>(ws->arg("sigmeant"));  
  RooRealVar *tgtvar = ws->var("tgtvar");
  
  
  RooArgList vars;
  vars.add(meantgt->FuncVars());
  vars.add(*tgtvar);
   
  //read testing dataset from TTree
  RooRealVar weightvar("weightvar","",1.);

  TTree *dtree;
  
  if (doele) {
    //TFile *fdin = TFile::Open("root://eoscms.cern.ch//eos/cms/store/cmst3/user/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-zllm50-v7n_noskim.root");
    TFile *fdin = TFile::Open("/data/bendavid/regTreesAug1/hgg-2013Final8TeV_reg_s12-zllm50-v7n_noskim.root");

    TDirectory *ddir = (TDirectory*)fdin->FindObjectAny("PhotonTreeWriterSingleInvert");
    dtree = (TTree*)ddir->Get("hPhotonTreeSingle");       
  }
  else {
    //TFile *fdin = TFile::Open("/eos/cms/store/group/dpg_ecal/alca_ecalcalib/piZero2017/zhicaiz/Gun_MultiPion_FlatPt-1To15/Gun_FlatPt1to15_MultiPion_withPhotonPtFilter_pythia8/photons_0_half2.root");
    TFile *fdin = TFile::Open("/eos/cms/store/group/dpg_ecal/alca_ecalcalib/piZero2017/zhicaiz/Gun_MultiPion_FlatPt-1To15/Gun_FlatPt1to15_MultiPion_withPhotonPtFilter_pythia8/photons_20171008_half2.root");
    //TFile *fdin = TFile::Open("/eos/cms/store/group/dpg_ecal/alca_ecalcalib/piZero2017/zhicaiz/Gun_MultiEta_FlatPt-1To15/Gun_FlatPt1to15_MultiEta_withPhotonPtFilter_pythia8/photons_22Aug2017_V3_half2.root");
   	if(gammaID==0)
	{
	dtree = (TTree*)fdin->Get("Tree_Optim_gamma");
	}
	else if(gammaID==1)
	{
	dtree = (TTree*)fdin->Get("Tree_Optim_gamma1");
	}
	else if(gammaID==2)
	{
	dtree = (TTree*)fdin->Get("Tree_Optim_gamma2");
	}
  }
  
  //selection cuts for testing
  //TCut selcut = "(STr2_enG1_true/cosh(STr2_Eta_1)>1.0) && (STr2_S4S9_1>0.75)";
  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_isMerging < 2) && (STr2_DeltaR < 0.03)  && (STr2_enG_true/STr2_enG_rec)<3.0 && STr2_EOverEOther < 10.0 && STr2_EOverEOther > 0.1";
  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>0) && (STr2_S4S9 > 0.75) && (STr2_isMerging < 2) && (STr2_DeltaR < 0.03)  && (STr2_mPi0_nocor>0.1)";
  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_Nxtal > 6) && (STr2_mPi0_nocor>0.1) && (STr2_mPi0_nocor < 0.2)";
  TCut selcut = "";
  //if(dobarrel) selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_Nxtal > 6) && (STr2_mPi0_nocor>0.2) && (STr2_mPi0_nocor < 1.0) && (STr2_ptPi0_nocor > 2.0) && abs(STr2_Eta)<1.479 && (!STr2_fromPi0)";
  if(dobarrel) selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_Nxtal > 6) && (STr2_mPi0_nocor>0.1) && (STr2_mPi0_nocor < 0.2) && (STr2_ptPi0_nocor > 2.0) && abs(STr2_Eta)<1.479";
  //else selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_Nxtal > 6) && (STr2_mPi0_nocor>0.2) && (STr2_mPi0_nocor < 1.0) && (STr2_ptPi0_nocor > 2.0) && abs(STr2_Eta)>1.479 && (!STr2_fromPi0)";
  else selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_Nxtal > 6) && (STr2_mPi0_nocor>0.1) && (STr2_mPi0_nocor < 0.2) && (STr2_ptPi0_nocor > 2.0) && abs(STr2_Eta)>1.479";

  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_isMerging < 2) && (STr2_DeltaR < 0.03) && (STr2_iEta_on2520==0 || STr2_iPhi_on20==0) ";
  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_isMerging < 2) && (STr2_DeltaR < 0.03) && (abs(STr2_iEtaiX)<60)";
  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.75) && (STr2_isMerging < 2) && (STr2_DeltaR < 0.03) && (abs(STr2_iEtaiX)>60)";
  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.9) && (STr2_S2S9>0.85)&& (STr2_isMerging < 2) && (STr2_DeltaR < 0.03) && (abs(STr2_iEtaiX)<60)";
  //TCut selcut = "(STr2_enG_rec/cosh(STr2_Eta)>1.0) && (STr2_S4S9 > 0.9) && (STr2_S2S9>0.85)&& (STr2_isMerging < 2) && (STr2_DeltaR < 0.03)";
/*  
TCut selcut;
  if (dobarrel) 
    selcut = "ph.genpt>25. && ph.isbarrel && ph.ispromptgen"; 
  else
    selcut = "ph.genpt>25. && !ph.isbarrel && ph.ispromptgen"; 
 */ 
  TCut selweight = "xsecweight(procidx)*puweight(numPU,procidx)";
  TCut prescale10 = "(Entry$%10==0)";
  TCut prescale10alt = "(Entry$%10==1)";
  TCut prescale25 = "(Entry$%25==0)";
  TCut prescale100 = "(Entry$%100==0)";  
  TCut prescale1000 = "(Entry$%1000==0)";  
  TCut evenevents = "(Entry$%2==0)";
  TCut oddevents = "(Entry$%2==1)";
  TCut prescale100alt = "(Entry$%100==1)";
  TCut prescale1000alt = "(Entry$%1000==1)";
  TCut prescale50alt = "(Entry$%50==1)";
  TCut Events3_4 = "(Entry$%4==3)";
  TCut Events1_4 = "(Entry$%4==1)";
  TCut Events2_4 = "(Entry$%4==2)";
  TCut Events0_4 = "(Entry$%4==0)";

  TCut Events01_4 = "(Entry$%4<2)";
  TCut Events23_4 = "(Entry$%4>1)";

  TCut EventsTest = "(Entry$%2==1)";

  //weightvar.SetTitle(EventsTest*selcut);
  weightvar.SetTitle(selcut);
/*
  if (doele) 
    weightvar.SetTitle(prescale100alt*selcut);
  else
    weightvar.SetTitle(selcut);
  */
  //make testing dataset
  RooDataSet *hdata = RooTreeConvert::CreateDataSet("hdata",dtree,vars,weightvar);   

  if (doele) 
    weightvar.SetTitle(prescale1000alt*selcut);
  else
    weightvar.SetTitle(prescale10alt*selcut);
  //make reduced testing dataset for integration over conditional variables
  RooDataSet *hdatasmall = RooTreeConvert::CreateDataSet("hdatasmall",dtree,vars,weightvar);     
    
  //retrieve full pdf from workspace
  RooAbsPdf *sigpdf = ws->pdf("sigpdf");
  
  //input variable corresponding to sceta
  RooRealVar *scEraw = ws->var("var_0");
  scEraw->setRange(1.,2.);
  scEraw->setBins(100);
//  RooRealVar *scetavar = ws->var("var_1");
//  RooRealVar *scphivar = ws->var("var_2");
  
 
  //regressed output functions
  RooAbsReal *sigmeanlim = ws->function("sigmeanlim");
  RooAbsReal *sigwidthlim = ws->function("sigwidthlim");
  RooAbsReal *signlim = ws->function("signlim");
  RooAbsReal *sign2lim = ws->function("sign2lim");

//  RooAbsReal *sigalphalim = ws->function("sigalphalim");
  //RooAbsReal *sigalpha2lim = ws->function("sigalpha2lim");


  //formula for corrected energy/true energy ( 1.0/(etrue/eraw) * regression mean)
  RooFormulaVar ecor("ecor","","1./(@0)*@1",RooArgList(*tgtvar,*sigmeanlim));
  RooRealVar *ecorvar = (RooRealVar*)hdata->addColumn(ecor);
  ecorvar->setRange(0.,2.);
  ecorvar->setBins(800);
  
  //formula for raw energy/true energy (1.0/(etrue/eraw))
  RooFormulaVar raw("raw","","1./@0",RooArgList(*tgtvar));
  RooRealVar *rawvar = (RooRealVar*)hdata->addColumn(raw);
  rawvar->setRange(0.,2.);
  rawvar->setBins(800);

  //clone data and add regression outputs for plotting
  RooDataSet *hdataclone = new RooDataSet(*hdata,"hdataclone");
  RooRealVar *meanvar = (RooRealVar*)hdataclone->addColumn(*sigmeanlim);
  RooRealVar *widthvar = (RooRealVar*)hdataclone->addColumn(*sigwidthlim);
  RooRealVar *nvar = (RooRealVar*)hdataclone->addColumn(*signlim);
  RooRealVar *n2var = (RooRealVar*)hdataclone->addColumn(*sign2lim);
 
//  RooRealVar *alphavar = (RooRealVar*)hdataclone->addColumn(*sigalphalim);
//  RooRealVar *alpha2var = (RooRealVar*)hdataclone->addColumn(*sigalpha2lim);
  
  
  //plot target variable and weighted regression prediction (using numerical integration over reduced testing dataset)
  TCanvas *craw = new TCanvas;
  //RooPlot *plot = tgtvar->frame(0.6,1.2,100);
  RooPlot *plot = tgtvar->frame(0.6,2.0,100);
  hdata->plotOn(plot);
  sigpdf->plotOn(plot,ProjWData(*hdatasmall));
  plot->Draw();
  craw->SaveAs("RawE.pdf");
  craw->SaveAs("RawE.png");
  craw->SetLogy();
  plot->SetMinimum(0.1);
  craw->SaveAs("RawElog.pdf");
  craw->SaveAs("RawElog.png");
  
  //plot distribution of regressed functions over testing dataset
  TCanvas *cmean = new TCanvas;
  RooPlot *plotmean = meanvar->frame(0.8,2.0,100);
  hdataclone->plotOn(plotmean);
  plotmean->Draw();
  cmean->SaveAs("mean.pdf");
  cmean->SaveAs("mean.png");
  
  
  TCanvas *cwidth = new TCanvas;
  RooPlot *plotwidth = widthvar->frame(0.,0.05,100);
  hdataclone->plotOn(plotwidth);
  plotwidth->Draw();
  cwidth->SaveAs("width.pdf");
  cwidth->SaveAs("width.png");
  
  TCanvas *cn = new TCanvas;
  RooPlot *plotn = nvar->frame(0.,111.,200);
  hdataclone->plotOn(plotn);
  plotn->Draw();
  cn->SaveAs("n.pdf");
  cn->SaveAs("n.png");

  TCanvas *cn2 = new TCanvas;
  RooPlot *plotn2 = n2var->frame(0.,111.,100);
  hdataclone->plotOn(plotn2);
  plotn2->Draw();
  cn2->SaveAs("n2.pdf");
  cn2->SaveAs("n2.png");

/*
  TCanvas *calpha = new TCanvas;
  RooPlot *plotalpha = alphavar->frame(0.,5.,200);
  hdataclone->plotOn(plotalpha);
  plotalpha->Draw();
  calpha->SaveAs("alpha.pdf");
  calpha->SaveAs("alpha.png");

  TCanvas *calpha2 = new TCanvas;
  RooPlot *plotalpha2 = alpha2var->frame(0.,5.,200);
  hdataclone->plotOn(plotalpha2);
  plotalpha2->Draw();
  calpha2->SaveAs("alpha2.pdf");
  calpha2->SaveAs("alpha2.png");
*/

/* 
  TCanvas *ceta = new TCanvas;
  RooPlot *ploteta = scetavar->frame(-2.6,2.6,200);
  hdataclone->plotOn(ploteta);
  ploteta->Draw();      
  ceta->SaveAs("eta.pdf");  
  ceta->SaveAs("eta.png");  
  */

  //create histograms for eraw/etrue and ecor/etrue to quantify regression performance
  TH1 *heraw;// = hdata->createHistogram("hraw",*rawvar,Binning(800,0.,2.));
  TH1 *hecor;// = hdata->createHistogram("hecor",*ecorvar);
  if (EEorEB == "EB")
  {
         heraw = hdata->createHistogram("hraw",*rawvar,Binning(800,0.,2.0));
         hecor = hdata->createHistogram("hecor",*ecorvar, Binning(800,0.,2.0));
  }
  else
  {
         heraw = hdata->createHistogram("hraw",*rawvar,Binning(200,0.,2.));
         hecor = hdata->createHistogram("hecor",*ecorvar, Binning(200,0.,2.));
  }

  
  
  //heold->SetLineColor(kRed);
  hecor->SetLineColor(kBlue);
  heraw->SetLineColor(kMagenta);
  
  hecor->GetYaxis()->SetRangeUser(1.0,1.3*hecor->GetMaximum());
  heraw->GetYaxis()->SetRangeUser(1.0,1.3*hecor->GetMaximum());

  hecor->GetXaxis()->SetRangeUser(0.0,1.5);
  heraw->GetXaxis()->SetRangeUser(0.0,1.5);
  
/*if(EEorEB == "EE")
{
  heraw->GetYaxis()->SetRangeUser(10.0,200.0);
  hecor->GetYaxis()->SetRangeUser(10.0,200.0);
}
*/ 
 
//heold->GetXaxis()->SetRangeUser(0.6,1.2);
  double effsigma_cor, effsigma_raw, fwhm_cor, fwhm_raw;

  if(EEorEB == "EB")
  {
  TH1 *hecorfine = hdata->createHistogram("hecorfine",*ecorvar,Binning(800,0.,2.));
  effsigma_cor = effSigma(hecorfine);
  fwhm_cor = FWHM(hecorfine);
  TH1 *herawfine = hdata->createHistogram("herawfine",*rawvar,Binning(800,0.,2.));
  effsigma_raw = effSigma(herawfine);
  fwhm_raw = FWHM(herawfine);
  }
  else
  {
  TH1 *hecorfine = hdata->createHistogram("hecorfine",*ecorvar,Binning(200,0.,2.));
  effsigma_cor = effSigma(hecorfine);
  fwhm_cor = FWHM(hecorfine);
  TH1 *herawfine = hdata->createHistogram("herawfine",*rawvar,Binning(200,0.,2.));
  effsigma_raw = effSigma(herawfine);
  fwhm_raw = FWHM(herawfine);
  }


  TCanvas *cresponse = new TCanvas;
  gStyle->SetOptStat(0); 
  gStyle->SetPalette(107);
  hecor->SetTitle("");
  heraw->SetTitle("");
  hecor->Draw("HIST");
  //heold->Draw("HISTSAME");
  heraw->Draw("HISTSAME");

  //show errSigma in the plot
  TLegend *leg = new TLegend(0.1, 0.75, 0.7, 0.9);
  leg->AddEntry(hecor,Form("E_{cor}/E_{true}, #sigma_{eff}=%4.3f, FWHM=%4.3f", effsigma_cor, fwhm_cor),"l");
  leg->AddEntry(heraw,Form("E_{raw}/E_{true}, #sigma_{eff}=%4.3f, FWHM=%4.3f", effsigma_raw, fwhm_raw),"l");
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
 // leg->SetTextColor(kRed);
  leg->Draw();

  cresponse->SaveAs("response.pdf");
  cresponse->SaveAs("response.png");
  cresponse->SetLogy();
  cresponse->SaveAs("responselog.pdf");
  cresponse->SaveAs("responselog.png");
 

  // draw CCs vs eta and phi
/*
  TCanvas *c_eta = new TCanvas;
  TH1 *h_eta = hdata->createHistogram("h_eta",*scetavar,Binning(100,-3.2,3.2));
  h_eta->Draw("HIST");
  c_eta->SaveAs("heta.pdf");
  c_eta->SaveAs("heta.png");

  TCanvas *c_phi = new TCanvas;
  TH1 *h_phi = hdata->createHistogram("h_phi",*scphivar,Binning(100,-3.2,3.2));
  h_phi->Draw("HIST");
  c_phi->SaveAs("hphi.pdf");
  c_phi->SaveAs("hphi.png");
*/

  RooRealVar *scetaiXvar = ws->var("var_4");
  RooRealVar *scphiiYvar = ws->var("var_5");
 
   if(EEorEB=="EB")
   {
   scetaiXvar->setRange(-90,90);
   scetaiXvar->setBins(180);
   scphiiYvar->setRange(0,360);
   scphiiYvar->setBins(360);
   }
   else
   {
   scetaiXvar->setRange(0,50);
   scetaiXvar->setBins(50);
   scphiiYvar->setRange(0,50);
   scphiiYvar->setBins(50);
 
   }
   ecorvar->setRange(0.5,1.5);
   ecorvar->setBins(800);
   rawvar->setRange(0.5,1.5);
   rawvar->setBins(800);
  

  TCanvas *c_cor_eta = new TCanvas;
  TH3F *h3_CC_eta_phi = (TH3F*) hdata->createHistogram("var_5,var_4,ecor",(EEorEB=="EB") ? 170 : 100, (EEorEB=="EB") ? 360 : 100,25);
  TProfile2D *h_CC_eta_phi = h3_CC_eta_phi->Project3DProfile();

  h_CC_eta_phi->SetTitle("E_{cor}/E_{true}");
  if(EEorEB=="EB")
  {
  h_CC_eta_phi->GetXaxis()->SetTitle("i#eta");
  h_CC_eta_phi->GetYaxis()->SetTitle("i#phi");
  h_CC_eta_phi->GetXaxis()->SetRangeUser(-85,85);
  h_CC_eta_phi->GetYaxis()->SetRangeUser(0,360);
  }
  else
  {
  h_CC_eta_phi->GetXaxis()->SetTitle("iX");
  h_CC_eta_phi->GetYaxis()->SetTitle("iY");
  }

  h_CC_eta_phi->SetMinimum(0.5);
  h_CC_eta_phi->SetMaximum(1.5);

  h_CC_eta_phi->Draw("COLZ");
  c_cor_eta->SaveAs("cor_vs_eta_phi.pdf");
  c_cor_eta->SaveAs("cor_vs_eta_phi.png"); 



  TH2F *h_CC_eta = hdata->createHistogram(*scetaiXvar, *ecorvar, "","cor_vs_eta");
  if(EEorEB=="EB")
  {
  h_CC_eta->GetXaxis()->SetTitle("i#eta"); 
  }
  else
  {
  h_CC_eta->GetXaxis()->SetTitle("iX");
  }
  h_CC_eta->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_eta->Draw("COLZ");
  c_cor_eta->SaveAs("cor_vs_eta.pdf");
  c_cor_eta->SaveAs("cor_vs_eta.png");

 
  TCanvas *c_cor_scEraw = new TCanvas;
  TH2F *h_CC_scEraw = hdata->createHistogram(*scEraw, *ecorvar, "","cor_vs_scEraw");
  h_CC_scEraw->GetXaxis()->SetTitle("E_{raw}"); 
  h_CC_scEraw->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_scEraw->Draw("COLZ");
  c_cor_scEraw->SaveAs("cor_vs_scEraw.pdf");
  c_cor_scEraw->SaveAs("cor_vs_scEraw.png");

  TCanvas *c_raw_scEraw = new TCanvas;
  TH2F *h_RC_scEraw = hdata->createHistogram(*scEraw, *rawvar, "","raw_vs_scEraw");
  h_RC_scEraw->GetXaxis()->SetTitle("E_{raw}"); 
  h_RC_scEraw->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_scEraw->Draw("COLZ");
  c_raw_scEraw->SaveAs("raw_vs_scEraw.pdf");
  c_raw_scEraw->SaveAs("raw_vs_scEraw.png");

 
 	
  TCanvas *c_cor_phi = new TCanvas;
  TH2F *h_CC_phi = hdata->createHistogram(*scphiiYvar, *ecorvar, "","cor_vs_phi"); 
  if(EEorEB=="EB")
  {
  h_CC_phi->GetXaxis()->SetTitle("i#phi"); 
  }
  else
  {
  h_CC_phi->GetXaxis()->SetTitle("iY");
  }

  h_CC_phi->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_phi->Draw("COLZ");
  c_cor_phi->SaveAs("cor_vs_phi.pdf");
  c_cor_phi->SaveAs("cor_vs_phi.png");
 
//2D map of Eraw/Etrue and Ecor/Etrue of ieta and iphi
  
  TCanvas *c_raw_eta = new TCanvas;
  TH3F *h3_RC_eta_phi = (TH3F*) hdata->createHistogram("var_5,var_4,raw",(EEorEB=="EB") ? 170 : 100, (EEorEB=="EB") ? 360 : 100,25);
  TProfile2D *h_RC_eta_phi = h3_RC_eta_phi->Project3DProfile();

  h_RC_eta_phi->SetTitle("E_{raw}/E_{true}");
  if(EEorEB=="EB")
  {
  h_RC_eta_phi->GetXaxis()->SetTitle("i#eta");
  h_RC_eta_phi->GetYaxis()->SetTitle("i#phi");
  h_RC_eta_phi->GetXaxis()->SetRangeUser(-85,85);
  h_RC_eta_phi->GetYaxis()->SetRangeUser(0,360);
  }
  else
  {
  h_RC_eta_phi->GetXaxis()->SetTitle("iX");
  h_RC_eta_phi->GetYaxis()->SetTitle("iY");
  }

  h_RC_eta_phi->SetMinimum(0.5);
  h_RC_eta_phi->SetMaximum(1.5);

  h_RC_eta_phi->Draw("COLZ");
  c_raw_eta->SaveAs("raw_vs_eta_phi.pdf");
  c_raw_eta->SaveAs("raw_vs_eta_phi.png"); 

  TH2F *h_RC_eta = hdata->createHistogram(*scetaiXvar, *rawvar, "","raw_vs_eta");
  if(EEorEB=="EB")
  {
  h_RC_eta->GetXaxis()->SetTitle("i#eta"); 
  }
  else
  {
  h_RC_eta->GetXaxis()->SetTitle("iX");
  }

  h_RC_eta->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_eta->Draw("COLZ");
  c_raw_eta->SaveAs("raw_vs_eta.pdf");
  c_raw_eta->SaveAs("raw_vs_eta.png");
	
  TCanvas *c_raw_phi = new TCanvas;




  TH2F *h_RC_phi = hdata->createHistogram(*scphiiYvar, *rawvar, "","raw_vs_phi"); 
  if(EEorEB=="EB")
  {
  h_RC_phi->GetXaxis()->SetTitle("i#phi"); 
  }
  else
  {
  h_RC_phi->GetXaxis()->SetTitle("iY");
  }

  h_RC_phi->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_phi->Draw("COLZ");
  c_raw_phi->SaveAs("raw_vs_phi.pdf");
  c_raw_phi->SaveAs("raw_vs_phi.png");


//on2,5,20, etc
if(EEorEB == "EB")
{

  TCanvas *myC_iCrystal_mod = new TCanvas;

  RooRealVar *SM_distvar = ws->var("var_6");
  SM_distvar->setRange(0,10);
  SM_distvar->setBins(10);
  TH2F *h_CC_SM_dist = hdata->createHistogram(*SM_distvar, *ecorvar, "","cor_vs_SM_dist");
  h_CC_SM_dist->GetXaxis()->SetTitle("SM_dist"); 
  h_CC_SM_dist->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_SM_dist->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("cor_vs_SM_dist.pdf");
  myC_iCrystal_mod->SaveAs("cor_vs_SM_dist.png");
  TH2F *h_RC_SM_dist = hdata->createHistogram(*SM_distvar, *rawvar, "","raw_vs_SM_dist");
  h_RC_SM_dist->GetXaxis()->SetTitle("distance to SM gap"); 
  h_RC_SM_dist->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_SM_dist->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("raw_vs_SM_dist.pdf");
  myC_iCrystal_mod->SaveAs("raw_vs_SM_dist.png");

  RooRealVar *M_distvar = ws->var("var_7");
  M_distvar->setRange(0,13);
  M_distvar->setBins(10);
  TH2F *h_CC_M_dist = hdata->createHistogram(*M_distvar, *ecorvar, "","cor_vs_M_dist");
  h_CC_M_dist->GetXaxis()->SetTitle("M_dist"); 
  h_CC_M_dist->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_M_dist->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("cor_vs_M_dist.pdf");
  myC_iCrystal_mod->SaveAs("cor_vs_M_dist.png");
  TH2F *h_RC_M_dist = hdata->createHistogram(*M_distvar, *rawvar, "","raw_vs_M_dist");
  h_RC_M_dist->GetXaxis()->SetTitle("distance to module gap"); 
  h_RC_M_dist->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_M_dist->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("raw_vs_M_dist.pdf");
  myC_iCrystal_mod->SaveAs("raw_vs_M_dist.png");

/*
  RooRealVar *DeltaRG1G2var = ws->var("var_8");
  DeltaRG1G2var->setRange(0,0.2);
  DeltaRG1G2var->setBins(100);
  TH2F *h_CC_DeltaRG1G2 = hdata->createHistogram(*DeltaRG1G2var, *ecorvar, "","cor_vs_DeltaRG1G2");
  h_CC_DeltaRG1G2->GetXaxis()->SetTitle("DeltaRG1G2"); 
  h_CC_DeltaRG1G2->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_DeltaRG1G2->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("cor_vs_DeltaRG1G2.pdf");
  myC_iCrystal_mod->SaveAs("cor_vs_DeltaRG1G2.png");
  TH2F *h_RC_DeltaRG1G2 = hdata->createHistogram(*DeltaRG1G2var, *rawvar, "","raw_vs_DeltaRG1G2");
  h_RC_DeltaRG1G2->GetXaxis()->SetTitle("distance to module gap"); 
  h_RC_DeltaRG1G2->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_DeltaRG1G2->Draw("COLZ");
  myC_iCrystal_mod->SaveAs("raw_vs_DeltaRG1G2.pdf");
  myC_iCrystal_mod->SaveAs("raw_vs_DeltaRG1G2.png");

*/
}
	 

// other variables

  TCanvas *myC_variables = new TCanvas;

  RooRealVar *Nxtalvar = ws->var("var_1");
  Nxtalvar->setRange(0,10);
  Nxtalvar->setBins(10);
  TH2F *h_CC_Nxtal = hdata->createHistogram(*Nxtalvar, *ecorvar, "","cor_vs_Nxtal");
  h_CC_Nxtal->GetXaxis()->SetTitle("Nxtal"); 
  h_CC_Nxtal->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_Nxtal->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_Nxtal.pdf");
  myC_variables->SaveAs("cor_vs_Nxtal.png");
  TH2F *h_RC_Nxtal = hdata->createHistogram(*Nxtalvar, *rawvar, "","raw_vs_Nxtal");
  h_RC_Nxtal->GetXaxis()->SetTitle("Nxtal"); 
  h_RC_Nxtal->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_Nxtal->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_Nxtal.pdf");
  myC_variables->SaveAs("raw_vs_Nxtal.png");
	
  RooRealVar *S4S9var = ws->var("var_2");

  int Nbins_S4S9 = 100;
  double Low_S4S9 = 0.6;
  double High_S4S9 = 1.0; 
  S4S9var->setRange(Low_S4S9,High_S4S9);
  S4S9var->setBins(Nbins_S4S9);
 
  TH2F *h_CC_S4S9 = hdata->createHistogram(*S4S9var, *ecorvar, "","cor_vs_S4S9");
  h_CC_S4S9->GetXaxis()->SetTitle("S4S9"); 
  h_CC_S4S9->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_S4S9->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_S4S9.pdf");
  myC_variables->SaveAs("cor_vs_S4S9.png");
  TH2F *h_RC_S4S9 = hdata->createHistogram(*S4S9var, *rawvar, "","raw_vs_S4S9");
  h_RC_S4S9->GetXaxis()->SetTitle("S4S9"); 
  h_RC_S4S9->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_S4S9->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_S4S9.pdf");
  myC_variables->SaveAs("raw_vs_S4S9.png");
	
  RooRealVar *S2S9var = ws->var("var_3");
  int Nbins_S2S9 = 100;
  double Low_S2S9 = 0.5;
  double High_S2S9 = 1.0; 
  S2S9var->setRange(Low_S2S9,High_S2S9);
  S2S9var->setBins(Nbins_S2S9);


  TH2F *h_CC_S2S9 = hdata->createHistogram(*S2S9var, *ecorvar, "","cor_vs_S2S9");
  h_CC_S2S9->GetXaxis()->SetTitle("S2S9"); 
  h_CC_S2S9->GetYaxis()->SetTitle("E_{cor}/E_{true}"); 
  h_CC_S2S9->Draw("COLZ");
  myC_variables->SaveAs("cor_vs_S2S9.pdf");
  myC_variables->SaveAs("cor_vs_S2S9.png");
  TH2F *h_RC_S2S9 = hdata->createHistogram(*S2S9var, *rawvar, "","raw_vs_S2S9");
  h_RC_S2S9->GetXaxis()->SetTitle("S2S9"); 
  h_RC_S2S9->GetYaxis()->SetTitle("E_{raw}/E_{true}"); 
  h_RC_S2S9->Draw("COLZ");
  myC_variables->SaveAs("raw_vs_S2S9.pdf");
  myC_variables->SaveAs("raw_vs_S2S9.png");



  TH2F *h_S2S9_eta = hdata->createHistogram(*scetaiXvar, *S2S9var, "","S2S9_vs_eta");
  h_S2S9_eta->GetYaxis()->SetTitle("S2S9"); 
  if(EEorEB=="EB")
  {
  h_CC_eta->GetYaxis()->SetTitle("i#eta"); 
  }
  else
  {
  h_CC_eta->GetYaxis()->SetTitle("iX");
  }
  h_S2S9_eta->Draw("COLZ");
  myC_variables->SaveAs("S2S9_vs_eta.pdf");
  myC_variables->SaveAs("S2S9_vs_eta.png");
  
  TH2F *h_S4S9_eta = hdata->createHistogram(*scetaiXvar, *S4S9var, "","S4S9_vs_eta");
  h_S4S9_eta->GetYaxis()->SetTitle("S4S9"); 
  if(EEorEB=="EB")
  {
  h_CC_eta->GetYaxis()->SetTitle("i#eta"); 
  }
  else
  {
  h_CC_eta->GetYaxis()->SetTitle("iX");
  }
  h_S4S9_eta->Draw("COLZ");
  myC_variables->SaveAs("S4S9_vs_eta.pdf");
  myC_variables->SaveAs("S4S9_vs_eta.png");
  
  TH2F *h_S2S9_phi = hdata->createHistogram(*scphiiYvar, *S2S9var, "","S2S9_vs_phi");
  h_S2S9_phi->GetYaxis()->SetTitle("S2S9"); 
  if(EEorEB=="EB")
  {
  h_CC_phi->GetYaxis()->SetTitle("i#phi"); 
  }
  else
  {
  h_CC_phi->GetYaxis()->SetTitle("iY");
  }
  h_S2S9_phi->Draw("COLZ");
  myC_variables->SaveAs("S2S9_vs_phi.pdf");
  myC_variables->SaveAs("S2S9_vs_phi.png");
  
  TH2F *h_S4S9_phi = hdata->createHistogram(*scphiiYvar, *S4S9var, "","S4S9_vs_phi");
  h_S4S9_phi->GetYaxis()->SetTitle("S4S9"); 
  if(EEorEB=="EB")
  {
  h_CC_phi->GetYaxis()->SetTitle("i#phi"); 
  }
  else
  {
  h_CC_phi->GetYaxis()->SetTitle("iY");
  }
  h_S4S9_phi->Draw("COLZ");
  myC_variables->SaveAs("S4S9_vs_phi.pdf");
  myC_variables->SaveAs("S4S9_vs_phi.png");
  
 
  if(EEorEB=="EE")
{

}
	
  TProfile *p_CC_eta = h_CC_eta->ProfileX("p_CC_eta");//,1,-1,"s");
  p_CC_eta->GetYaxis()->SetRangeUser(0.8,1.05);
  if(EEorEB == "EB")
  {
//   p_CC_eta->GetYaxis()->SetRangeUser(0.85,1.0);
//   p_CC_eta->GetXaxis()->SetRangeUser(-1.5,1.5);
  }
  p_CC_eta->GetYaxis()->SetTitle("E_{cor}/E_{true}");
  p_CC_eta->SetTitle("");
  p_CC_eta->Draw();
  myC_variables->SaveAs("profile_cor_vs_eta.pdf"); 
  myC_variables->SaveAs("profile_cor_vs_eta.png"); 
 
// fill the E/Etrue vs. eta with each point taken from fits
  gStyle->SetOptStat(111); 
  gStyle->SetOptFit(1); 
  TH1F *h1_fit_CC_eta = new TH1F("h1_fit_CC_eta","h1_fit_CC_eta",(EEorEB=="EB") ? 180 : 50,(EEorEB=="EB") ? -90 : 0, (EEorEB=="EB") ? 90 : 50);

  for(int ix = 1;ix <= h_CC_eta->GetNbinsX(); ix++)
  {
	stringstream os_iEta;
	os_iEta << ((EEorEB=="EB") ? (-90 + ix -1) : (0 + ix -1));
	string ss_iEta = os_iEta.str();
	TH1D * h_temp = h_CC_eta->ProjectionY("h_temp",ix,ix);	
	h_temp->Rebin(4);
	TF1 *f_temp = new TF1("f_temp","gaus(0)",0.95,1.07);
	h_temp->Fit("f_temp","R");
	h1_fit_CC_eta->SetBinContent(ix, f_temp->GetParameter(1));
	h1_fit_CC_eta->SetBinError(ix, f_temp->GetParError(1));
	h_temp->GetXaxis()->SetTitle("E_{cor}/E_{true}");
	h_temp->SetTitle("");
	h_temp->Draw();
	myC_variables->SaveAs(("fits/CC_iEta_"+ss_iEta+".pdf").c_str());
	myC_variables->SaveAs(("fits/CC_iEta_"+ss_iEta+".png").c_str());
	myC_variables->SaveAs(("fits/CC_iEta_"+ss_iEta+".C").c_str());
  }
  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  h1_fit_CC_eta->GetYaxis()->SetRangeUser((gammaID==1) ? 0.95 : 0.9 , (gammaID==1) ? 1.05 : 1.1);
  h1_fit_CC_eta->GetYaxis()->SetTitle("E_{cor}/E_{true}");
  h1_fit_CC_eta->GetXaxis()->SetTitle((EEorEB=="EB") ? "i#eta" : "iX");
  h1_fit_CC_eta->SetTitle("");
  h1_fit_CC_eta->Draw();
  myC_variables->SaveAs("profile_fit_cor_vs_eta.pdf");	
  myC_variables->SaveAs("profile_fit_cor_vs_eta.png");	
  myC_variables->SaveAs("profile_fit_cor_vs_eta.C");	

 
  TProfile *p_RC_eta = h_RC_eta->ProfileX("p_RC_eta");//,1,-1,"s");
  p_RC_eta->GetYaxis()->SetRangeUser(0.8,1.05);
  if(EEorEB=="EB")
  {
//   p_RC_eta->GetYaxis()->SetRangeUser(0.80,0.95);
  // p_RC_eta->GetXaxis()->SetRangeUser(-1.5,1.5);
  }
  p_RC_eta->GetYaxis()->SetTitle("E_{raw}/E_{true}");
  p_RC_eta->SetTitle("");
  p_RC_eta->Draw();
  myC_variables->SaveAs("profile_raw_vs_eta.pdf"); 
  myC_variables->SaveAs("profile_raw_vs_eta.png"); 

// fill the E/Etrue vs. eta with each point taken from fits
  gStyle->SetOptStat(111);
  gStyle->SetOptFit(1);
  TH1F *h1_fit_RC_eta = new TH1F("h1_fit_RC_eta","h1_fit_RC_eta",(EEorEB=="EB") ? 180 : 50,(EEorEB=="EB") ? -90 : 0, (EEorEB=="EB") ? 90 : 50);
  for(int ix = 1;ix <= h_RC_eta->GetNbinsX(); ix++)
  {
	stringstream os_iEta;
	os_iEta << ((EEorEB=="EB") ? (-90 + ix -1) : (0 + ix -1));
	string ss_iEta = os_iEta.str();
	TH1D * h_temp = h_RC_eta->ProjectionY("h_temp",ix,ix);	
	h_temp->Rebin(4);
	TF1 *f_temp = new TF1("f_temp","gaus(0)",0.87,1.05);
	h_temp->Fit("f_temp","R");
	
	h1_fit_RC_eta->SetBinContent(ix, f_temp->GetParameter(1));
	h1_fit_RC_eta->SetBinError(ix, f_temp->GetParError(1));
	
	h_temp->GetXaxis()->SetTitle("E_{raw}/E_{true}");
	h_temp->SetTitle("");

	h_temp->Draw();
	
	myC_variables->SaveAs(("fits/RC_iEta_"+ss_iEta+".pdf").c_str());
	myC_variables->SaveAs(("fits/RC_iEta_"+ss_iEta+".png").c_str());
	myC_variables->SaveAs(("fits/RC_iEta_"+ss_iEta+".C").c_str());
  }

  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  h1_fit_RC_eta->GetYaxis()->SetRangeUser((gammaID==1) ? 0.9 : 0.8,1.0);
  h1_fit_RC_eta->GetYaxis()->SetTitle("E_{raw}/E_{true}");
  h1_fit_RC_eta->GetXaxis()->SetTitle((EEorEB=="EB") ? "i#eta" : "iX");
  h1_fit_RC_eta->SetTitle("");
  h1_fit_RC_eta->Draw();
  myC_variables->SaveAs("profile_fit_raw_vs_eta.pdf");	
  myC_variables->SaveAs("profile_fit_raw_vs_eta.png");	
  myC_variables->SaveAs("profile_fit_raw_vs_eta.C");	


  int Nbins_iEta = EEorEB=="EB" ? 180 : 50;
  int nLow_iEta  = EEorEB=="EB" ? -90 : 0;
  int nHigh_iEta = EEorEB=="EB" ? 90 : 50;
  
  TH1F *h1_RC_eta = new TH1F("h1_RC_eta","h1_RC_eta",Nbins_iEta,nLow_iEta,nHigh_iEta);
  for(int i=1;i<=Nbins_iEta;i++)
  {
    h1_RC_eta->SetBinContent(i,p_RC_eta->GetBinError(i)); 
  } 
  h1_RC_eta->GetXaxis()->SetTitle("i#eta");
  h1_RC_eta->GetYaxis()->SetTitle("#sigma_{E_{raw}/E_{true}}");
  h1_RC_eta->SetTitle("");
  h1_RC_eta->Draw();
  myC_variables->SaveAs("sigma_Eraw_Etrue_vs_eta.pdf");
  myC_variables->SaveAs("sigma_Eraw_Etrue_vs_eta.png");
 
  TH1F *h1_CC_eta = new TH1F("h1_CC_eta","h1_CC_eta",Nbins_iEta,nLow_iEta,nHigh_iEta);
  for(int i=1;i<=Nbins_iEta;i++)
  {
    h1_CC_eta->SetBinContent(i,p_CC_eta->GetBinError(i)); 
  } 
  h1_CC_eta->GetXaxis()->SetTitle("i#eta");
  h1_CC_eta->GetYaxis()->SetTitle("#sigma_{E_{cor}/E_{true}}");
  h1_CC_eta->SetTitle("");
  h1_CC_eta->Draw();
  myC_variables->SaveAs("sigma_Ecor_Etrue_vs_eta.pdf");
  myC_variables->SaveAs("sigma_Ecor_Etrue_vs_eta.png");
 
  TProfile *p_CC_phi = h_CC_phi->ProfileX("p_CC_phi");//,1,-1,"s");
  p_CC_phi->GetYaxis()->SetRangeUser( (gammaID==1) ? 0.9 :  0.8,1.0);
  if(EEorEB == "EB")
  {
//   p_CC_phi->GetYaxis()->SetRangeUser(0.94,1.00);
  }
  p_CC_phi->GetYaxis()->SetTitle("E_{cor}/E_{true}");
  p_CC_phi->SetTitle("");
  p_CC_phi->Draw();
  myC_variables->SaveAs("profile_cor_vs_phi.pdf"); 
  myC_variables->SaveAs("profile_cor_vs_phi.png"); 
 
  gStyle->SetOptStat(111);
  gStyle->SetOptFit(1);
  TH1F *h1_fit_CC_phi = new TH1F("h1_fit_CC_phi","h1_fit_CC_phi",(EEorEB=="EB") ? 360 : 50,(EEorEB=="EB") ? 0 : 0, (EEorEB=="EB") ? 360 : 50);
  for(int ix = 1;ix <= h_CC_phi->GetNbinsX(); ix++)
  {
        stringstream os_iPhi;
        os_iPhi << ((EEorEB=="EB") ? (0 + ix -1) : (0 + ix -1));
        string ss_iPhi = os_iPhi.str();
        TH1D * h_temp = h_CC_phi->ProjectionY("h_temp",ix,ix);
        h_temp->Rebin(4);
        TF1 *f_temp = new TF1("f_temp","gaus(0)",0.95,1.07);
        h_temp->Fit("f_temp","R");

        h1_fit_CC_phi->SetBinContent(ix, f_temp->GetParameter(1));
        h1_fit_CC_phi->SetBinError(ix, f_temp->GetParError(1));
	h_temp->GetXaxis()->SetTitle("E_{cor}/E_{true}");
	h_temp->SetTitle("");
        h_temp->Draw();

        myC_variables->SaveAs(("fits/CC_iPhi_"+ss_iPhi+".pdf").c_str());
        myC_variables->SaveAs(("fits/CC_iPhi_"+ss_iPhi+".png").c_str());
        myC_variables->SaveAs(("fits/CC_iPhi_"+ss_iPhi+".C").c_str());
  }

  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  h1_fit_CC_phi->GetYaxis()->SetRangeUser((gammaID==1) ? 0.95 : 0.9,(gammaID==1) ? 1.05 : 1.1);
  h1_fit_CC_phi->GetYaxis()->SetTitle("E_{cor}/E_{true}");
  h1_fit_CC_phi->GetXaxis()->SetTitle((EEorEB=="EB") ? "i#phi" : "iX");
  h1_fit_CC_phi->SetTitle("");
  h1_fit_CC_phi->Draw();
  myC_variables->SaveAs("profile_fit_cor_vs_phi.pdf");
  myC_variables->SaveAs("profile_fit_cor_vs_phi.png");
  myC_variables->SaveAs("profile_fit_cor_vs_phi.C");

 
  TProfile *p_RC_phi = h_RC_phi->ProfileX("p_RC_phi");//,1,-1,"s");
  p_RC_phi->GetYaxis()->SetRangeUser((gammaID==1) ? 0.9 : 0.8,1.0);
  if(EEorEB=="EB")
  {
 //  p_RC_phi->GetYaxis()->SetRangeUser(0.89,0.95);
  }
  p_RC_phi->GetYaxis()->SetTitle("E_{raw}/E_{true}");
  p_RC_phi->SetTitle("");
  p_RC_phi->Draw();
  myC_variables->SaveAs("profile_raw_vs_phi.pdf"); 
  myC_variables->SaveAs("profile_raw_vs_phi.png"); 

  gStyle->SetOptStat(111);
  gStyle->SetOptFit(1);
  TH1F *h1_fit_RC_phi = new TH1F("h1_fit_RC_phi","h1_fit_RC_phi",(EEorEB=="EB") ? 360 : 50,(EEorEB=="EB") ? 0 : 0, (EEorEB=="EB") ? 360 : 50);
  for(int ix = 1;ix <= h_RC_phi->GetNbinsX(); ix++)
  {
        stringstream os_iPhi;
        os_iPhi << ((EEorEB=="EB") ? (0 + ix -1) : (0 + ix -1));
        string ss_iPhi = os_iPhi.str();
        TH1D * h_temp = h_RC_phi->ProjectionY("h_temp",ix,ix);
        h_temp->Rebin(4);
        TF1 *f_temp = new TF1("f_temp","gaus(0)",0.87,1.05);
        h_temp->Fit("f_temp","R");

        h1_fit_RC_phi->SetBinContent(ix, f_temp->GetParameter(1));
        h1_fit_RC_phi->SetBinError(ix, f_temp->GetParError(1));
	h_temp->GetXaxis()->SetTitle("E_{raw}/E_{true}");
	h_temp->SetTitle("");

        h_temp->Draw();

        myC_variables->SaveAs(("fits/RC_iPhi_"+ss_iPhi+".pdf").c_str());
        myC_variables->SaveAs(("fits/RC_iPhi_"+ss_iPhi+".png").c_str());
        myC_variables->SaveAs(("fits/RC_iPhi_"+ss_iPhi+".C").c_str());
  }

  gStyle->SetOptStat(0);
  gStyle->SetOptFit(0);
  h1_fit_RC_phi->GetYaxis()->SetRangeUser((gammaID==1) ? 0.9 : 0.8,1.0);
  h1_fit_RC_phi->GetYaxis()->SetTitle("E_{raw}/E_{true}");
  h1_fit_RC_phi->GetXaxis()->SetTitle((EEorEB=="EB") ? "i#phi" : "iX");
  h1_fit_RC_phi->SetTitle("");
  h1_fit_RC_phi->Draw();
  myC_variables->SaveAs("profile_fit_raw_vs_phi.pdf");
  myC_variables->SaveAs("profile_fit_raw_vs_phi.png");
  myC_variables->SaveAs("profile_fit_raw_vs_phi.C");



  int Nbins_iPhi = EEorEB=="EB" ? 360 : 50;
  int nLow_iPhi  = EEorEB=="EB" ? 0 : 0;
  int nHigh_iPhi = EEorEB=="EB" ? 360 : 50;
  
  TH1F *h1_RC_phi = new TH1F("h1_RC_phi","h1_RC_phi",Nbins_iPhi,nLow_iPhi,nHigh_iPhi);
  for(int i=1;i<=Nbins_iPhi;i++)
  {
    h1_RC_phi->SetBinContent(i,p_RC_phi->GetBinError(i)); 
  } 
  h1_RC_phi->GetXaxis()->SetTitle("i#phi");
  h1_RC_phi->GetYaxis()->SetTitle("#sigma_{E_{raw}/E_{true}}");
  h1_RC_phi->SetTitle("");
  h1_RC_phi->Draw();
  myC_variables->SaveAs("sigma_Eraw_Etrue_vs_phi.pdf");
  myC_variables->SaveAs("sigma_Eraw_Etrue_vs_phi.png");
 
  TH1F *h1_CC_phi = new TH1F("h1_CC_phi","h1_CC_phi",Nbins_iPhi,nLow_iPhi,nHigh_iPhi);
  for(int i=1;i<=Nbins_iPhi;i++)
  {
    h1_CC_phi->SetBinContent(i,p_CC_phi->GetBinError(i)); 
  } 
  h1_CC_phi->GetXaxis()->SetTitle("i#phi");
  h1_CC_phi->GetYaxis()->SetTitle("#sigma_{E_{cor}/E_{true}}");
  h1_CC_phi->SetTitle("");
  h1_CC_phi->Draw();
  myC_variables->SaveAs("sigma_Ecor_Etrue_vs_phi.pdf");
  myC_variables->SaveAs("sigma_Ecor_Etrue_vs_phi.png");


// FWHM over sigma_eff vs. eta/phi
   
  TH1F *h1_FoverS_RC_phi = new TH1F("h1_FoverS_RC_phi","h1_FoverS_RC_phi",Nbins_iPhi,nLow_iPhi,nHigh_iPhi);
  TH1F *h1_FoverS_CC_phi = new TH1F("h1_FoverS_CC_phi","h1_FoverS_CC_phi",Nbins_iPhi,nLow_iPhi,nHigh_iPhi);
  TH1F *h1_FoverS_RC_eta = new TH1F("h1_FoverS_RC_eta","h1_FoverS_RC_eta",Nbins_iEta,nLow_iEta,nHigh_iEta);
  TH1F *h1_FoverS_CC_eta = new TH1F("h1_FoverS_CC_eta","h1_FoverS_CC_eta",Nbins_iEta,nLow_iEta,nHigh_iEta);
  TH1F *h1_FoverS_CC_S2S9 = new TH1F("h1_FoverS_CC_S2S9","h1_FoverS_CC_S2S9",Nbins_S2S9,Low_S2S9,High_S2S9);
  TH1F *h1_FoverS_RC_S2S9 = new TH1F("h1_FoverS_RC_S2S9","h1_FoverS_RC_S2S9",Nbins_S2S9,Low_S2S9,High_S2S9);
  TH1F *h1_FoverS_CC_S4S9 = new TH1F("h1_FoverS_CC_S4S9","h1_FoverS_CC_S4S9",Nbins_S4S9,Low_S4S9,High_S4S9);
  TH1F *h1_FoverS_RC_S4S9 = new TH1F("h1_FoverS_RC_S4S9","h1_FoverS_RC_S4S9",Nbins_S4S9,Low_S4S9,High_S4S9);

  float FWHMoverSigmaEff = 0.0;  
  TH1F *h_tmp_rawvar = new TH1F("tmp_rawvar","tmp_rawvar",800,0.5,1.5);
  TH1F *h_tmp_corvar = new TH1F("tmp_corvar","tmp_corvar",800,0.5,1.5);

  for(int i=1;i<=Nbins_iPhi;i++)
  {
    float FWHM_tmp = 0.0;
    float effSigma_tmp = 0.0;
    for(int j=1;j<=800;j++) 
    {
	h_tmp_rawvar->SetBinContent(j,h_RC_phi->GetBinContent(i,j));
	h_tmp_corvar->SetBinContent(j,h_CC_phi->GetBinContent(i,j));
    }

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_rawvar);
    effSigma_tmp = effSigma(h_tmp_rawvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_RC_phi->SetBinContent(i, FWHMoverSigmaEff); 

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_corvar);
    effSigma_tmp = effSigma(h_tmp_corvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_CC_phi->SetBinContent(i, FWHMoverSigmaEff); 
  }
  
  h1_FoverS_CC_phi->GetXaxis()->SetRangeUser(0,2.0);
  h1_FoverS_CC_phi->GetXaxis()->SetTitle("i#phi");
  h1_FoverS_CC_phi->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{cor}/E_{true}");
  h1_FoverS_CC_phi->SetTitle("");
  h1_FoverS_CC_phi->Draw();
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_phi.pdf");
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_phi.png");

  h1_FoverS_RC_phi->GetXaxis()->SetRangeUser(0,2.0);
  h1_FoverS_RC_phi->GetXaxis()->SetTitle("i#phi");
  h1_FoverS_RC_phi->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{raw}/E_{true}");
  h1_FoverS_RC_phi->SetTitle("");
  h1_FoverS_RC_phi->Draw();
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_phi.pdf");
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_phi.png");


  for(int i=1;i<=Nbins_iEta;i++)
  {
    float FWHM_tmp = 0.0;
    float effSigma_tmp = 0.0;
    for(int j=1;j<=800;j++) 
    {
	h_tmp_rawvar->SetBinContent(j,h_RC_eta->GetBinContent(i,j));
	h_tmp_corvar->SetBinContent(j,h_CC_eta->GetBinContent(i,j));
    }

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_rawvar);
    effSigma_tmp = effSigma(h_tmp_rawvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_RC_eta->SetBinContent(i, FWHMoverSigmaEff); 

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_corvar);
    effSigma_tmp = effSigma(h_tmp_corvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_CC_eta->SetBinContent(i, FWHMoverSigmaEff); 
  }
  
  h1_FoverS_CC_eta->GetXaxis()->SetRangeUser(0,2.0);
  h1_FoverS_CC_eta->GetXaxis()->SetTitle("i#eta");
  h1_FoverS_CC_eta->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{cor}/E_{true}");
  h1_FoverS_CC_eta->SetTitle("");
  h1_FoverS_CC_eta->Draw();
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_eta.pdf");
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_eta.png");

  h1_FoverS_RC_eta->GetXaxis()->SetRangeUser(0,2.0);
  h1_FoverS_RC_eta->GetXaxis()->SetTitle("i#eta");
  h1_FoverS_RC_eta->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{raw}/E_{true}");
  h1_FoverS_RC_eta->SetTitle("");
  h1_FoverS_RC_eta->Draw();
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_eta.pdf");
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_eta.png");


  for(int i=1;i<=Nbins_S2S9;i++)
  {
    float FWHM_tmp = 0.0;
    float effSigma_tmp = 0.0;
    for(int j=1;j<=800;j++) 
    {
	h_tmp_rawvar->SetBinContent(j,h_RC_S2S9->GetBinContent(i,j));
	h_tmp_corvar->SetBinContent(j,h_CC_S2S9->GetBinContent(i,j));
    }

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_rawvar);
    effSigma_tmp = effSigma(h_tmp_rawvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_RC_S2S9->SetBinContent(i, FWHMoverSigmaEff); 

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_corvar);
    effSigma_tmp = effSigma(h_tmp_corvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_CC_S2S9->SetBinContent(i, FWHMoverSigmaEff); 
  }
  
  h1_FoverS_CC_S2S9->GetXaxis()->SetTitle("S2S9");
  h1_FoverS_CC_S2S9->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{cor}/E_{true}");
  h1_FoverS_CC_S2S9->GetYaxis()->SetRangeUser(0.0,2.0);
  h1_FoverS_CC_S2S9->SetTitle("");
  h1_FoverS_CC_S2S9->Draw();
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_S2S9.pdf");
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_S2S9.png");

  h1_FoverS_RC_S2S9->GetXaxis()->SetTitle("S2S9");
  h1_FoverS_RC_S2S9->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{raw}/E_{true}");
  h1_FoverS_RC_S2S9->GetYaxis()->SetRangeUser(0.0,2.0);
  h1_FoverS_RC_S2S9->SetTitle("");
  h1_FoverS_RC_S2S9->Draw();
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_S2S9.pdf");
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_S2S9.png");


  for(int i=1;i<=Nbins_S4S9;i++)
  {
    float FWHM_tmp = 0.0;
    float effSigma_tmp = 0.0;
    for(int j=1;j<=800;j++) 
    {
	h_tmp_rawvar->SetBinContent(j,h_RC_S4S9->GetBinContent(i,j));
	h_tmp_corvar->SetBinContent(j,h_CC_S4S9->GetBinContent(i,j));
    }

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_rawvar);
    effSigma_tmp = effSigma(h_tmp_rawvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_RC_S4S9->SetBinContent(i, FWHMoverSigmaEff); 

    FWHMoverSigmaEff = 0.0;
    FWHM_tmp= FWHM(h_tmp_corvar);
    effSigma_tmp = effSigma(h_tmp_corvar);
    if(effSigma_tmp>0.000001)  FWHMoverSigmaEff = FWHM_tmp/effSigma_tmp;
    h1_FoverS_CC_S4S9->SetBinContent(i, FWHMoverSigmaEff); 
  }
  
  h1_FoverS_CC_S4S9->GetXaxis()->SetTitle("S4S9");
  h1_FoverS_CC_S4S9->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{cor}/E_{true}");
  h1_FoverS_CC_S4S9->GetYaxis()->SetRangeUser(0.0,2.0);
  h1_FoverS_CC_S4S9->SetTitle("");
  h1_FoverS_CC_S4S9->Draw();
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_S4S9.pdf");
  myC_variables->SaveAs("FoverS_Ecor_Etrue_vs_S4S9.png");

  h1_FoverS_RC_S4S9->GetXaxis()->SetTitle("S4S9");
  h1_FoverS_RC_S4S9->GetYaxis()->SetTitle("FWHM/#sigma_{eff} of E_{raw}/E_{true}");
  h1_FoverS_RC_S4S9->GetYaxis()->SetRangeUser(0.0,2.0);
  h1_FoverS_RC_S4S9->SetTitle("");
  h1_FoverS_RC_S4S9->Draw();
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_S4S9.pdf");
  myC_variables->SaveAs("FoverS_Eraw_Etrue_vs_S4S9.png");




  printf("calc effsigma\n");
  std::cout<<"_"<<EEorEB<<std::endl;
  printf("corrected curve effSigma= %5f, FWHM=%5f \n",effsigma_cor, fwhm_cor);
  printf("raw curve effSigma= %5f FWHM=%5f \n",effsigma_raw, fwhm_raw);

  
/*  new TCanvas;
  RooPlot *ploteold = testvar.frame(0.6,1.2,100);
  hdatasigtest->plotOn(ploteold);
  ploteold->Draw();    
  
  new TCanvas;
  RooPlot *plotecor = ecorvar->frame(0.6,1.2,100);
  hdatasig->plotOn(plotecor);
  plotecor->Draw(); */   
  
  
}
Beispiel #28
0
TH1D* runSig(RooWorkspace* ws,
             const char* modelConfigName = "ModelConfig",
             const char* dataName = "obsData",
             const char* asimov1DataName = "asimovData_1",
             const char* conditional1Snapshot = "conditionalGlobs_1",
             const char* nominalSnapshot = "nominalGlobs")
{
    string defaultMinimizer    = "Minuit";     // or "Minuit"
    int defaultStrategy        = 2;             // Minimization strategy. 0-2. 0 = fastest, least robust. 2 = slowest, most robust

    double mu_profile_value = 1; // mu value to profile the obs data at wbefore generating the expected
    bool doUncap            = 1; // uncap p0
    bool doInj              = 0; // setup the poi for injection study (zero is faster if you're not)
    bool doMedian           = 1; // compute median significance
    bool isBlind            = 0; // Dont look at observed data
    bool doConditional      = !isBlind; // do conditional expected data
    bool doObs              = !isBlind; // compute observed significance

    TStopwatch timer;
    timer.Start();

    if (!ws)
    {
        cout << "ERROR::Workspace is NULL!" << endl;
        return NULL;
    }
    ModelConfig* mc = (ModelConfig*)ws->obj(modelConfigName);
    if (!mc)
    {
        cout << "ERROR::ModelConfig: " << modelConfigName << " doesn't exist!" << endl;
        return NULL;
    }
    RooDataSet* data = (RooDataSet*)ws->data(dataName);
    if (!data)
    {
        cout << "ERROR::Dataset: " << dataName << " doesn't exist!" << endl;
        return NULL;
    }

    mc->GetNuisanceParameters()->Print("v");

    //RooNLLVar::SetIgnoreZeroEntries(1);
    ROOT::Math::MinimizerOptions::SetDefaultMinimizer(defaultMinimizer.c_str());
    ROOT::Math::MinimizerOptions::SetDefaultStrategy(defaultStrategy);
    ROOT::Math::MinimizerOptions::SetDefaultPrintLevel(-1);
    //  cout << "Setting max function calls" << endl;
    //ROOT::Math::MinimizerOptions::SetDefaultMaxFunctionCalls(20000);
    //RooMinimizer::SetMaxFunctionCalls(10000);

    ws->loadSnapshot("conditionalNuis_0");
    RooArgSet nuis(*mc->GetNuisanceParameters());

    RooRealVar* mu = (RooRealVar*)mc->GetParametersOfInterest()->first();

    RooAbsPdf* pdf_temp = mc->GetPdf();

    string condSnapshot(conditional1Snapshot);
    RooArgSet nuis_tmp2 = *mc->GetNuisanceParameters();
    RooNLLVar* obs_nll = doObs ? (RooNLLVar*)pdf_temp->createNLL(*data, Constrain(nuis_tmp2)) : NULL;

    RooDataSet* asimovData1 = (RooDataSet*)ws->data(asimov1DataName);
    if (!asimovData1)
    {
        cout << "Asimov data doesn't exist! Please, allow me to build one for you..." << endl;
        string mu_str, mu_prof_str;

        asimovData1 = makeAsimovData(mc, doConditional, ws, obs_nll, 1, &mu_str, &mu_prof_str, mu_profile_value, true);
        condSnapshot="conditionalGlobs"+mu_prof_str;

        //makeAsimovData(mc, true, ws, mc->GetPdf(), data, 0);
        //ws->Print();
        //asimovData1 = (RooDataSet*)ws->data("asimovData_1");
    }

    if (!doUncap) mu->setRange(0, 40);
    else mu->setRange(-40, 40);

    RooAbsPdf* pdf = mc->GetPdf();
    RooArgSet nuis_tmp1 = *mc->GetNuisanceParameters();
    RooNLLVar* asimov_nll = (RooNLLVar*)pdf->createNLL(*asimovData1, Constrain(nuis_tmp1));

    //do asimov
    mu->setVal(1);
    mu->setConstant(0);
    if (!doInj) mu->setConstant(1);

    int status,sign;
    double med_sig=0,obs_sig=0,asimov_q0=0,obs_q0=0;

    if (doMedian)
    {
        ws->loadSnapshot(condSnapshot.c_str());
        if (doInj) ws->loadSnapshot("conditionalNuis_inj");
        else ws->loadSnapshot("conditionalNuis_1");
        mc->GetGlobalObservables()->Print("v");
        mu->setVal(0);
        mu->setConstant(1);
        status = minimize(asimov_nll, ws);
        if (status >= 0) cout << "Success!" << endl;

        if (status < 0) 
        {
            cout << "Retrying with conditional snapshot at mu=1" << endl;
            ws->loadSnapshot("conditionalNuis_0");
            status = minimize(asimov_nll, ws);
            if (status >= 0) cout << "Success!" << endl;
        }
        double asimov_nll_cond = asimov_nll->getVal();

        mu->setVal(1);
        if (doInj) ws->loadSnapshot("conditionalNuis_inj");
        else ws->loadSnapshot("conditionalNuis_1");
        if (doInj) mu->setConstant(0);
        status = minimize(asimov_nll, ws);
        if (status >= 0) cout << "Success!" << endl;

        if (status < 0) 
        {
            cout << "Retrying with conditional snapshot at mu=1" << endl;
            ws->loadSnapshot("conditionalNuis_0");
            status = minimize(asimov_nll, ws);
            if (status >= 0) cout << "Success!" << endl;
        }

        double asimov_nll_min = asimov_nll->getVal();
        asimov_q0 = 2*(asimov_nll_cond - asimov_nll_min);
        if (doUncap && mu->getVal() < 0) asimov_q0 = -asimov_q0;

        sign = int(asimov_q0 != 0 ? asimov_q0/fabs(asimov_q0) : 0);
        med_sig = sign*sqrt(fabs(asimov_q0));

        ws->loadSnapshot(nominalSnapshot);
    }

    if (doObs)
    {
        ws->loadSnapshot("conditionalNuis_0");
        mu->setVal(0);
        mu->setConstant(1);
        status = minimize(obs_nll, ws);
        if (status < 0) 
        {
            cout << "Retrying with conditional snapshot at mu=1" << endl;
            ws->loadSnapshot("conditionalNuis_0");
            status = minimize(obs_nll, ws);
            if (status >= 0) cout << "Success!" << endl;
        }
        double obs_nll_cond = obs_nll->getVal();

        //ws->loadSnapshot("ucmles");
        mu->setConstant(0);
        status = minimize(obs_nll, ws);
        if (status < 0) 
        {
            cout << "Retrying with conditional snapshot at mu=1" << endl;
            ws->loadSnapshot("conditionalNuis_0");
            status = minimize(obs_nll, ws);
            if (status >= 0) cout << "Success!" << endl;
        }

        double obs_nll_min = obs_nll->getVal();

        obs_q0 = 2*(obs_nll_cond - obs_nll_min);
        if (doUncap && mu->getVal() < 0) obs_q0 = -obs_q0;

        sign = int(obs_q0 == 0 ? 0 : obs_q0 / fabs(obs_q0));
        if (!doUncap && ((obs_q0 < 0 && obs_q0 > -0.1) || mu->getVal() < 0.001)) obs_sig = 0; 
        else obs_sig = sign*sqrt(fabs(obs_q0));
    }

    cout << "obs: " << obs_sig << endl;
    cout << "Observed significance: " << obs_sig << endl;

    if (med_sig)
    {
        cout << "Median test stat val: " << asimov_q0 << endl;
        cout << "Median significance:   " << med_sig << endl;
    }

    TH1D* h_hypo = new TH1D("hypo","hypo",2,0,2);
    h_hypo->SetBinContent(1, obs_sig);
    h_hypo->SetBinContent(2, med_sig);

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

  /////////////////////////////////////////////////////////////
  // 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() );


  BayesianCalculator bayesianCalc(*data,*mc);
  bayesianCalc.SetConfidenceLevel(0.95); // 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 << "\n95% 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

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

  bayesianCalc.SetScanOfPosterior(nScanPoints);

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

}
Beispiel #30
0
   void ws_cls_hybrid1_ag( const char* wsfile = "output-files/expected-ws-lm9-2BL.root", bool isBgonlyStudy=false, double poiVal = 150.0, int nToys=100, bool makeTtree=true, int verbLevel=0 ) {



       TTree* toytt(0x0) ;
       TFile* ttfile(0x0) ;

       int    tt_gen_Nsig ;
       int    tt_gen_Nsb ;
       int    tt_gen_Nsig_sl ;
       int    tt_gen_Nsb_sl ;
       int    tt_gen_Nsig_ldp ;
       int    tt_gen_Nsb_ldp ;
       int    tt_gen_Nsig_ee ;
       int    tt_gen_Nsb_ee ;
       int    tt_gen_Nsig_mm ;
       int    tt_gen_Nsb_mm ;

       double tt_testStat ;
       double tt_dataTestStat ;
       double tt_hypo_mu_susy_sig ;
       char ttname[1000] ;
       char tttitle[1000] ;

       if ( makeTtree ) {

          ttfile = gDirectory->GetFile() ;
          if ( ttfile == 0x0 ) { printf("\n\n\n *** asked for a ttree but no open file???\n\n") ; return ; }


          if ( isBgonlyStudy ) {
             sprintf( ttname, "toytt_%.0f_bgo", poiVal ) ;
             sprintf( tttitle, "Toy study for background only, mu_susy_sig = %.0f", poiVal ) ;
          } else {
             sprintf( ttname, "toytt_%.0f_spb", poiVal ) ;
             sprintf( tttitle, "Toy study for signal+background, mu_susy_sig = %.0f", poiVal ) ;
          }

          printf("\n\n Creating TTree : %s : %s\n\n", ttname, tttitle ) ;

          gDirectory->pwd() ;
          gDirectory->ls() ;

          toytt = new TTree( ttname, tttitle ) ;

          gDirectory->ls() ;

          toytt -> Branch(  "gen_Nsig"         ,       &tt_gen_Nsig         ,      "gen_Nsig/I"         ) ;
          toytt -> Branch(  "gen_Nsb"          ,       &tt_gen_Nsb          ,      "gen_Nsb/I"          ) ;
          toytt -> Branch(  "gen_Nsig_sl"      ,       &tt_gen_Nsig_sl      ,      "gen_Nsig_sl/I"      ) ;
          toytt -> Branch(  "gen_Nsb_sl"       ,       &tt_gen_Nsb_sl       ,      "gen_Nsb_sl/I"       ) ;
          toytt -> Branch(  "gen_Nsig_ldp"     ,       &tt_gen_Nsig_ldp     ,      "gen_Nsig_ldp/I"     ) ;
          toytt -> Branch(  "gen_Nsb_ldp"      ,       &tt_gen_Nsb_ldp      ,      "gen_Nsb_ldp/I"      ) ;
          toytt -> Branch(  "gen_Nsig_ee"      ,       &tt_gen_Nsig_ee      ,      "gen_Nsig_ee/I"      ) ;
          toytt -> Branch(  "gen_Nsb_ee"       ,       &tt_gen_Nsb_ee       ,      "gen_Nsb_ee/I"       ) ;
          toytt -> Branch(  "gen_Nsig_mm"      ,       &tt_gen_Nsig_mm      ,      "gen_Nsig_mm/I"      ) ;
          toytt -> Branch(  "gen_Nsb_mm"       ,       &tt_gen_Nsb_mm       ,      "gen_Nsb_mm/I"       ) ;

          toytt -> Branch(  "testStat"         ,       &tt_testStat         ,      "testStat/D"         ) ;
          toytt -> Branch(  "dataTestStat"     ,       &tt_dataTestStat     ,      "dataTestStat/D"     ) ;
          toytt -> Branch(  "hypo_mu_susy_sig" ,       &tt_hypo_mu_susy_sig ,      "hypo_mu_susy_sig/D" ) ;

       }


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


       random_ng = new TRandom2(12345) ;

   /// char sel[100] ;
   /// if ( strstr( wsfile, "1BL" ) != 0 ) {
   ///    sprintf( sel, "1BL" ) ;
   /// } else if ( strstr( wsfile, "2BL" ) != 0 ) {
   ///    sprintf( sel, "2BL" ) ;
   /// } else if ( strstr( wsfile, "3B" ) != 0 ) {
   ///    sprintf( sel, "3B" ) ;
   /// } else if ( strstr( wsfile, "1BT" ) != 0 ) {
   ///    sprintf( sel, "1BT" ) ;
   /// } else if ( strstr( wsfile, "2BT" ) != 0 ) {
   ///    sprintf( sel, "2BT" ) ;
   /// } else {
   ///    printf("\n\n\n *** can't figure out which selection this is.  I quit.\n\n" ) ;
   ///    return ;
   /// }
   /// printf("\n\n selection is %s\n\n", sel ) ;




       TFile* wstf = new TFile( wsfile ) ;

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

       ws->Print() ;






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

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





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

       const RooArgSet* nuisanceParameters = modelConfig->GetNuisanceParameters() ;

       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 ;
       }






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

 ////  RooFitResult* preFitResult = likelihood->fitTo( *rds, Save(true) ) ;
 ////  const RooArgList preFitFloatVals = preFitResult->floatParsFinal() ;
 ////  {
 ////    TIterator* parIter = preFitFloatVals.createIterator() ;
 ////    while ( RooRealVar* par = (RooRealVar*) parIter->Next() ) {
 ////       printf(" %20s : %8.2f\n", par->GetName(), par->getVal() ) ;
 ////    }
 ////  }







       //--- Get pointers to the model predictions of the observables.

       rfv_n_sig       = ws->function("n_sig") ;
       rfv_n_sb        = ws->function("n_sb") ;
       rfv_n_sig_sl    = ws->function("n_sig_sl") ;
       rfv_n_sb_sl     = ws->function("n_sb_sl") ;
       rfv_n_sig_ldp   = ws->function("n_sig_ldp") ;
       rfv_n_sb_ldp    = ws->function("n_sb_ldp") ;
       rfv_n_sig_ee    = ws->function("n_sig_ee") ;
       rfv_n_sb_ee     = ws->function("n_sb_ee") ;
       rfv_n_sig_mm    = ws->function("n_sig_mm") ;
       rfv_n_sb_mm     = ws->function("n_sb_mm") ;

       if ( rfv_n_sig         == 0x0 ) { printf("\n\n\n *** can't find n_sig       in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sb          == 0x0 ) { printf("\n\n\n *** can't find n_sb        in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sig_sl      == 0x0 ) { printf("\n\n\n *** can't find n_sig_sl    in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sb_sl       == 0x0 ) { printf("\n\n\n *** can't find n_sb_sl     in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sig_ldp     == 0x0 ) { printf("\n\n\n *** can't find n_sig_ldp   in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sb_ldp      == 0x0 ) { printf("\n\n\n *** can't find n_sb_ldp    in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sig_ee      == 0x0 ) { printf("\n\n\n *** can't find n_sig_ee    in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sb_ee       == 0x0 ) { printf("\n\n\n *** can't find n_sb_ee     in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sig_mm      == 0x0 ) { printf("\n\n\n *** can't find n_sig_mm    in workspace.  Quitting.\n\n\n") ; return ; }
       if ( rfv_n_sb_mm       == 0x0 ) { printf("\n\n\n *** can't find n_sb_mm     in workspace.  Quitting.\n\n\n") ; return ; }







       //--- Get pointers to the observables.

       const RooArgSet* dsras = rds->get() ;
       TIterator* obsIter = dsras->createIterator() ;
       while ( RooRealVar* obs = (RooRealVar*) obsIter->Next() ) {
          if ( strcmp( obs->GetName(), "Nsig"     ) == 0 ) { rrv_Nsig      = obs ; }
          if ( strcmp( obs->GetName(), "Nsb"      ) == 0 ) { rrv_Nsb       = obs ; }
          if ( strcmp( obs->GetName(), "Nsig_sl"  ) == 0 ) { rrv_Nsig_sl   = obs ; }
          if ( strcmp( obs->GetName(), "Nsb_sl"   ) == 0 ) { rrv_Nsb_sl    = obs ; }
          if ( strcmp( obs->GetName(), "Nsig_ldp" ) == 0 ) { rrv_Nsig_ldp  = obs ; }
          if ( strcmp( obs->GetName(), "Nsb_ldp"  ) == 0 ) { rrv_Nsb_ldp   = obs ; }
          if ( strcmp( obs->GetName(), "Nsig_ee"  ) == 0 ) { rrv_Nsig_ee   = obs ; }
          if ( strcmp( obs->GetName(), "Nsb_ee"   ) == 0 ) { rrv_Nsb_ee    = obs ; }
          if ( strcmp( obs->GetName(), "Nsig_mm"  ) == 0 ) { rrv_Nsig_mm   = obs ; }
          if ( strcmp( obs->GetName(), "Nsb_mm"   ) == 0 ) { rrv_Nsb_mm    = obs ; }
       }

       if ( rrv_Nsig       == 0x0 ) { printf("\n\n\n *** can't find Nsig       in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsb        == 0x0 ) { printf("\n\n\n *** can't find Nsb        in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsig_sl    == 0x0 ) { printf("\n\n\n *** can't find Nsig_sl    in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsb_sl     == 0x0 ) { printf("\n\n\n *** can't find Nsb_sl     in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsig_ldp   == 0x0 ) { printf("\n\n\n *** can't find Nsig_ldp   in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsb_ldp    == 0x0 ) { printf("\n\n\n *** can't find Nsb_ldp    in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsig_ee    == 0x0 ) { printf("\n\n\n *** can't find Nsig_ee    in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsb_ee     == 0x0 ) { printf("\n\n\n *** can't find Nsb_ee     in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsig_mm    == 0x0 ) { printf("\n\n\n *** can't find Nsig_mm    in dataset.  Quitting.\n\n\n") ; return ; }
       if ( rrv_Nsb_mm     == 0x0 ) { printf("\n\n\n *** can't find Nsb_mm     in dataset.  Quitting.\n\n\n") ; return ; }






       printf("\n\n\n === Model values for observables\n\n") ;

       printObservables() ;



      //--- save the actual values of the observables.

       saveObservables() ;











       //--- evaluate the test stat on the data: fit with susy floating.

       rrv_mu_susy_sig->setVal( poiVal ) ;
       rrv_mu_susy_sig->setConstant( kTRUE ) ;

       printf("\n\n\n ====== Fitting the data with susy fixed.\n\n") ;

       RooFitResult* dataFitResultSusyFixed = likelihood->fitTo(*rds, Save(true));
       int dataSusyFixedFitCovQual = dataFitResultSusyFixed->covQual() ;
       if ( dataSusyFixedFitCovQual != 3 ) { printf("\n\n\n *** Failed fit!  Cov qual %d.  Quitting.\n\n", dataSusyFixedFitCovQual ) ; return ; }
       double dataFitSusyFixedNll = dataFitResultSusyFixed->minNll() ;


       rrv_mu_susy_sig->setVal( 0.0 ) ;
       rrv_mu_susy_sig->setConstant( kFALSE ) ;

       printf("\n\n\n ====== Fitting the data with susy floating.\n\n") ;

       RooFitResult* dataFitResultSusyFloat = likelihood->fitTo(*rds, Save(true));
       int dataSusyFloatFitCovQual = dataFitResultSusyFloat->covQual() ;
       if ( dataSusyFloatFitCovQual != 3 ) { printf("\n\n\n *** Failed fit!  Cov qual %d.  Quitting.\n\n", dataSusyFloatFitCovQual ) ; return ; }
       double dataFitSusyFloatNll = dataFitResultSusyFloat->minNll() ;

       double dataTestStat = 2.*( dataFitSusyFixedNll - dataFitSusyFloatNll) ;

       printf("\n\n\n Data value of test stat : %8.2f\n", dataTestStat ) ;












       printf("\n\n\n === Nuisance parameters\n\n") ;

       {
          int npi(0) ;
          TIterator* npIter = nuisanceParameters->createIterator() ;
          while ( RooRealVar* np_rrv = (RooRealVar*) npIter->Next() ) {

             np_initial_val[npi] = np_rrv->getVal() ; //--- I am assuming that the order of the NPs in the iterator does not change.

             TString npname( np_rrv->GetName() ) ;
             npname.ReplaceAll("_prim","") ;
             RooAbsReal* np_rfv = ws->function( npname ) ;

             TString pdfname( np_rrv->GetName() ) ;
             pdfname.ReplaceAll("_prim","") ;
             pdfname.Prepend("pdf_") ;
             RooAbsPdf* np_pdf = ws->pdf( pdfname ) ;
             if ( np_pdf == 0x0 ) { printf("\n\n *** Can't find nuisance parameter pdf with name %s.\n\n", pdfname.Data() ) ; }

             if ( np_rfv != 0x0 ) {
                printf(" %20s : %8.2f , %20s, %8.2f\n", np_rrv->GetName(), np_rrv->getVal(), np_rfv->GetName(), np_rfv->getVal() ) ;
             } else {
                printf(" %20s : %8.2f\n", np_rrv->GetName(), np_rrv->getVal() ) ;
             }

             npi++ ;
          } // np_rrv iterator.

          np_count = npi ;

       }







       tt_dataTestStat = dataTestStat ;
       tt_hypo_mu_susy_sig = poiVal ;














       printf("\n\n\n === Doing the toys\n\n") ;

       int nToyOK(0) ;
       int nToyWorseThanData(0) ;

       for ( int ti=0; ti<nToys; ti++ ) {

          printf("\n\n\n ======= Toy %4d\n\n\n", ti ) ;





          //--- 1) pick values for the nuisance parameters from the PDFs and fix them.

          {
             TIterator* npIter = nuisanceParameters->createIterator() ;
             while ( RooRealVar* np_rrv = (RooRealVar*) npIter->Next() ) {

                TString pdfname( np_rrv->GetName() ) ;
                pdfname.ReplaceAll("_prim","") ;
                pdfname.Prepend("pdf_") ;
                RooAbsPdf* np_pdf = ws->pdf( pdfname ) ;
                if ( np_pdf == 0x0 ) { printf("\n\n *** Can't find nuisance parameter pdf with name %s.\n\n", pdfname.Data() ) ; return ; }

                RooDataSet* nprds = np_pdf->generate( RooArgSet(*np_rrv) ,1) ;
                const RooArgSet* npdsras = nprds->get() ;
                TIterator* valIter = npdsras->createIterator() ;
                RooRealVar* val = (RooRealVar*) valIter->Next() ;

                //--- reset the value of the nuisance parameter and fix it for the toy model definition fit.
                np_rrv->setVal( val->getVal() ) ;
                np_rrv->setConstant( kTRUE ) ;


                TString npname( np_rrv->GetName() ) ;
                npname.ReplaceAll("_prim","") ;
                RooAbsReal* np_rfv = ws->function( npname ) ;

                if ( verbLevel > 0 ) {
                   if ( np_rfv != 0x0 ) {
                      printf(" %20s : %8.2f , %15s, %8.3f\n", val->GetName(), val->getVal(), np_rfv->GetName(), np_rfv->getVal() ) ;
                   } else if ( strstr( npname.Data(), "eff_sf" ) != 0 ) {
                      np_rfv = ws->function( "eff_sf_sig" ) ;
                      RooAbsReal* np_rfv2 = ws->function( "eff_sf_sb" ) ;
                      printf(" %20s : %8.2f , %15s, %8.3f , %15s, %8.3f\n", val->GetName(), val->getVal(), np_rfv->GetName(), np_rfv->getVal(), np_rfv2->GetName(), np_rfv2->getVal() ) ;
                   } else if ( strstr( npname.Data(), "sf_ll" ) != 0 ) {
                      np_rfv = ws->function( "sf_ee" ) ;
                      RooAbsReal* np_rfv2 = ws->function( "sf_mm" ) ;
                      printf(" %20s : %8.2f , %15s, %8.3f , %15s, %8.3f\n", val->GetName(), val->getVal(), np_rfv->GetName(), np_rfv->getVal(), np_rfv2->GetName(), np_rfv2->getVal() ) ;
                   } else {
                      printf(" %20s : %8.2f\n", val->GetName(), val->getVal() ) ;
                   }
                }

                delete nprds ;

             } // np_rrv iterator
          }






          //--- 2) Fit the dataset with these values for the nuisance parameters.

          if ( isBgonlyStudy ) {
            //-- fit with susy yield fixed to zero.
             rrv_mu_susy_sig -> setVal( 0. ) ;
             if ( verbLevel > 0 ) { printf("\n Setting mu_susy_sig to zero.\n\n") ; }
          } else {
            //-- fit with susy yield fixed to predicted value.
             rrv_mu_susy_sig -> setVal( poiVal ) ;
             if ( verbLevel > 0 ) { printf("\n Setting mu_susy_sig to %8.1f.\n\n", poiVal) ; }
          }
          rrv_mu_susy_sig->setConstant( kTRUE ) ;

          if ( verbLevel > 0 ) {
             printf("\n\n") ;
             printf("  Fitting with these values for the observables to define the model for toy generation.\n") ;
             rds->printMultiline(cout, 1, kTRUE, "") ;
             printf("\n\n") ;
          }

          RooFitResult* toyModelDefinitionFitResult(0x0) ;
          if ( verbLevel < 2 ) {
             toyModelDefinitionFitResult = likelihood->fitTo(*rds, Save(true), PrintLevel(-1));
          } else {
             toyModelDefinitionFitResult = likelihood->fitTo(*rds, Save(true));
          }

          int toyModelDefFitCovQual = toyModelDefinitionFitResult->covQual() ;
          if ( verbLevel > 0 ) { printf("\n fit covariance matrix quality: %d\n\n", toyModelDefFitCovQual ) ; }
          if ( toyModelDefFitCovQual != 3 ) {
             printf("\n\n\n *** Bad toy model definition fit.  Cov qual %d.  Aborting this toy.\n\n\n", toyModelDefFitCovQual ) ;
             continue ;
          }

          delete toyModelDefinitionFitResult ;

          if ( verbLevel > 0 ) {
             printf("\n\n\n === Model values for observables.  These will be used to generate the toy dataset.\n\n") ;
             printObservables() ;
          }









          //--- 3) Generate a new set of observables based on this model.

          generateObservables() ;

          printf("\n\n\n   Generated dataset\n") ;
          rds->Print() ;
          rds->printMultiline(cout, 1, kTRUE, "") ;

          //--- Apparently, I need to make a new RooDataSet...  Resetting the
          //    values in the old one doesn't stick.  If you do likelihood->fitTo(*rds), it
          //    uses the original values, not the reset ones, in the fit.

          RooArgSet toyFitobservedParametersList ;
          toyFitobservedParametersList.add( *rrv_Nsig        ) ;
          toyFitobservedParametersList.add( *rrv_Nsb         ) ;
          toyFitobservedParametersList.add( *rrv_Nsig_sl     ) ;
          toyFitobservedParametersList.add( *rrv_Nsb_sl      ) ;
          toyFitobservedParametersList.add( *rrv_Nsig_ldp    ) ;
          toyFitobservedParametersList.add( *rrv_Nsb_ldp     ) ;
          toyFitobservedParametersList.add( *rrv_Nsig_ee     ) ;
          toyFitobservedParametersList.add( *rrv_Nsb_ee      ) ;
          toyFitobservedParametersList.add( *rrv_Nsig_mm     ) ;
          toyFitobservedParametersList.add( *rrv_Nsb_mm      ) ;


          RooDataSet* toyFitdsObserved = new RooDataSet("toyfit_ra2b_observed_rds", "RA2b toy observed data values",
                                         toyFitobservedParametersList ) ;
          toyFitdsObserved->add( toyFitobservedParametersList ) ;





          //--- 4) Reset and free the nuisance parameters.

          {
             if ( verbLevel > 0 ) { printf("\n\n") ; }
             int npi(0) ;
             TIterator* npIter = nuisanceParameters->createIterator() ;
             while ( RooRealVar* np_rrv = (RooRealVar*) npIter->Next() ) {
                np_rrv -> setVal( np_initial_val[npi] ) ; // assuming that the order in the iterator does not change.
                np_rrv -> setConstant( kFALSE ) ;
                npi++ ;
                if ( verbLevel > 0 ) { printf("    reset %20s to %8.2f and freed it.\n", np_rrv->GetName() , np_rrv->getVal() ) ; }
             } // np_rrv iterator.
             if ( verbLevel > 0 ) { printf("\n\n") ; }
          }





          //--- 5a) Evaluate the test statistic: Fit with susy yield floating to get the absolute maximum log likelihood.

          if ( verbLevel > 0 ) { printf("\n\n  Evaluating the test statistic for this toy.  Fitting with susy floating.\n\n") ; }

          rrv_mu_susy_sig->setVal( 0.0 ) ;
          rrv_mu_susy_sig->setConstant( kFALSE ) ;

          if ( verbLevel > 0 ) {
             printf("\n toy dataset\n\n") ;
             toyFitdsObserved->printMultiline(cout, 1, kTRUE, "") ;
          }

     /////---- nfg.  Need to create a new dataset  ----------
     /////RooFitResult* maxLikelihoodFitResult = likelihood->fitTo(*rds, Save(true), PrintLevel(-1));
     /////RooFitResult* maxLikelihoodFitResult = likelihood->fitTo(*rds, Save(true));
     /////--------------

          RooFitResult* maxLikelihoodFitResult(0x0) ;
          if ( verbLevel < 2 ) {
             maxLikelihoodFitResult = likelihood->fitTo(*toyFitdsObserved, Save(true), PrintLevel(-1));
          } else {
             maxLikelihoodFitResult = likelihood->fitTo(*toyFitdsObserved, Save(true));
          }

          if ( verbLevel > 0 ) { printObservables() ; }

          int mlFitCovQual = maxLikelihoodFitResult->covQual() ;
          if ( verbLevel > 0 ) { printf("\n fit covariance matrix quality: %d , -log likelihood %f\n\n", mlFitCovQual, maxLikelihoodFitResult->minNll() ) ; }
          if ( mlFitCovQual != 3 ) {
             printf("\n\n\n *** Bad maximum likelihood fit (susy floating).  Cov qual %d.  Aborting this toy.\n\n\n", mlFitCovQual ) ;
             continue ;
          }
          double maxL_susyFloat = maxLikelihoodFitResult->minNll() ;
          double maxL_mu_susy_sig = rrv_mu_susy_sig->getVal() ;

          delete maxLikelihoodFitResult ;






          //--- 5b) Evaluate the test statistic: Fit with susy yield fixed to hypothesis value.
          //        This is only necessary if the maximum likelihood fit value of the susy yield
          //        is less than the hypothesis value (to get a one-sided limit).


          double testStat(0.0) ;
          double maxL_susyFixed(0.0) ;

          if ( maxL_mu_susy_sig < poiVal ) {

             if ( verbLevel > 0 ) { printf("\n\n  Evaluating the test statistic for this toy.  Fitting with susy fixed to %8.2f.\n\n", poiVal ) ; }

             rrv_mu_susy_sig->setVal( poiVal ) ;
             rrv_mu_susy_sig->setConstant( kTRUE ) ;

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

         ////--------- nfg.  need to make a new dataset  ---------------
         ////RooFitResult* susyFixedFitResult = likelihood->fitTo(*rds, Save(true), PrintLevel(-1));
         ////RooFitResult* susyFixedFitResult = likelihood->fitTo(*rds, Save(true));
         ////-----------------------------

             RooFitResult* susyFixedFitResult(0x0) ;
             if ( verbLevel < 2 ) {
                susyFixedFitResult = likelihood->fitTo(*toyFitdsObserved, Save(true), PrintLevel(-1));
             } else {
                susyFixedFitResult = likelihood->fitTo(*toyFitdsObserved, Save(true));
             }

             if ( verbLevel > 0 ) { printObservables() ; }

             int susyFixedFitCovQual = susyFixedFitResult->covQual() ;
             if ( verbLevel > 0 ) { printf("\n fit covariance matrix quality: %d , -log likelihood %f\n\n", susyFixedFitCovQual, susyFixedFitResult->minNll()  ) ; }
             if ( susyFixedFitCovQual != 3 ) {
                printf("\n\n\n *** Bad maximum likelihood fit (susy fixed).  Cov qual %d.  Aborting this toy.\n\n\n", susyFixedFitCovQual ) ;
                continue ;
             }
             maxL_susyFixed = susyFixedFitResult->minNll() ;
             testStat = 2. * (maxL_susyFixed - maxL_susyFloat) ;


             delete susyFixedFitResult ;


          } else {

             if ( verbLevel > 0 ) { printf("\n\n  Floating value of susy yield greater than hypo value (%8.2f > %8.2f).  Setting test stat to zero.\n\n", maxL_mu_susy_sig, poiVal ) ; }

             testStat = 0.0 ;

          }

          printf("   --- test stat for toy %4d : %8.2f\n", ti, testStat ) ;





          nToyOK++ ;

          if ( testStat > dataTestStat ) { nToyWorseThanData++ ; }


          if ( makeTtree ) {

             tt_testStat = testStat ;

             tt_gen_Nsig     = rrv_Nsig->getVal() ;
             tt_gen_Nsb      = rrv_Nsb->getVal() ;
             tt_gen_Nsig_sl  = rrv_Nsig_sl->getVal() ;
             tt_gen_Nsb_sl   = rrv_Nsb_sl->getVal() ;
             tt_gen_Nsig_ldp = rrv_Nsig_ldp->getVal() ;
             tt_gen_Nsb_ldp  = rrv_Nsb_ldp->getVal() ;
             tt_gen_Nsig_ee  = rrv_Nsig_ee->getVal() ;
             tt_gen_Nsb_ee   = rrv_Nsb_ee->getVal() ;
             tt_gen_Nsig_mm  = rrv_Nsig_mm->getVal() ;
             tt_gen_Nsb_mm   = rrv_Nsb_mm->getVal() ;

             toytt->Fill() ;

          }





          //--- *) reset things for the next toy.

          resetObservables() ;

          delete toyFitdsObserved ;




       } // ti.

       wstf->Close() ;

       printf("\n\n\n") ;

       if ( nToyOK == 0 ) { printf("\n\n\n *** All toys bad !?!?!\n\n\n") ; return ; }

       double pValue = (1.0*nToyWorseThanData) / (1.0*nToyOK) ;

       if ( isBgonlyStudy ) {
          printf("\n\n\n p-value result, BG-only , poi=%3.0f : %4d / %4d = %6.3f\n\n\n\n", poiVal, nToyWorseThanData, nToyOK, pValue ) ;
       } else {
          printf("\n\n\n p-value result, S-plus-B, poi=%3.0f : %4d / %4d = %6.3f\n\n\n\n", poiVal, nToyWorseThanData, nToyOK, pValue ) ;
       }


       if ( makeTtree ) {
          printf("\n\n Writing TTree : %s : %s\n\n", ttname, tttitle ) ;
          ttfile->cd() ;
          toytt->Write() ;
       }


   } // ws_cls_hybrid1