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

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

	return r;
}
void runFit(RooAbsPdf *pdf, RooDataSet *data, double *NLL, int *stat_t, int MaxTries, int mhLow, int mhHigh){

	int ntries=0;
	int stat=1;
	double minnll=10e8;
	while (stat!=0){
	  if (ntries>=MaxTries) break;
	  RooFitResult *fitTest = pdf->fitTo(*data,RooFit::Save(1),Range(mhLow,mhHigh));
	  //RooFitResult *fitTest = pdf->fitTo(*data,RooFit::Save(1),Range(85,110));
	  //RooFitResult *fitTest = pdf->fitTo(*data,RooFit::Save(1),SumW2Error(kTRUE)
          stat = fitTest->status();
	  minnll = fitTest->minNll();
	  ntries++; 
	}
	*stat_t = stat;
	*NLL = minnll;
}
Beispiel #3
0
///
/// Test PDF implementation.
/// Performs a fit to the minimum.
///
bool PDF_Abs::test()
{
	bool quiet = false;
	if(quiet) RooMsgService::instance().setGlobalKillBelow(ERROR);
	fixParameters(observables);
	floatParameters(parameters);
	setLimit(parameters, "free");
	RooFormulaVar ll("ll", "ll", "-2*log(@0)", RooArgSet(*pdf));
	RooMinuit m(ll);
	if(quiet) m.setPrintLevel(-2);
	m.setNoWarn();
	m.setLogFile("/dev/zero");
	m.setErrorLevel(1.0);
	m.setStrategy(2);
	// m.setProfile(1);
	m.migrad();
	RooFitResult *f = m.save();
	bool status = !(f->edm()<1 && f->status()==0);
	if(!quiet) f->Print("v");
	delete f;
	if(quiet) RooMsgService::instance().setGlobalKillBelow(INFO);
	if(!quiet) cout << "pdf->getVal() = " << pdf->getVal() << endl;
	return status;
}
// 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 ");
         }
      }
   }


  
   // 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) );
      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.....");
  
  
      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);
  
   // 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());
  
   ProfileLikelihoodTestStat profll(*sbModel->GetPdf());
   if (testStatType == 3) profll.SetOneSided(true);
   if (testStatType == 4) profll.SetSigned(true);
   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);
      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); 

  
   // 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 #5
0
void LL(){

  //y0 = 0.000135096401209 sigma_y0 = 0.000103896581837 x0 = 0.000446013873443 sigma_x0 =1.81384394011e-06
  //0.014108652249 0.0168368471049 0.0219755396247 0.000120423865262 1.5575931164 1.55759310722 3.41637854038
  //0.072569437325 0.084063541977 0.0376693978906 0.000284216132439 0.51908074913 0.519080758095 1.12037749267
 // double d = 0.014108652249;
 //  double sd = 0.0168368471049;
 //  double mc = 0.0219755396247;
 //  double smc = 0.000120423865262;
 //  double r0 = d/mc;

  double d = 0.072569437325;
  double sd =  0.084063541977;
  double mc =  0.0376693978906;
  double smc =  0.00028421613243;
  double r0 = d/mc;

  RooRealVar x("x","x",mc*0.9,mc*1.1);
  RooRealVar x0("x0","x0",mc);
  RooRealVar sx("sx","sx",smc);

  RooRealVar r("r","r",r0,0.,5.);
  RooRealVar y0("y0","y0",d); 
  RooRealVar sy("sy","sy",sd); 
  
  RooProduct rx("rx","rx",RooArgList(r,x));

  RooGaussian g1("g1","g1",x,x0,sx);
  RooGaussian g2("g2","g2",rx,y0,sy);

  RooProdPdf LL("LL","LL",g1,g2);

  RooArgSet obs(x0,y0); //observables
  RooArgSet poi(r); //parameters of interest
  RooDataSet data("data", "data", obs);
  data.add(obs); //actually add the data


  RooFitResult* res = LL.fitTo(data,RooFit::Minos(poi),RooFit::Save(),RooFit::Hesse(false));
  if(res->status()==0) {
    r.Print();
    x.Print();
    cout << r.getErrorLo() << " " << r.getErrorHi() << endl;
  } else {
    cout << "Likelihood maximization failed" << endl;
  }
  
  RooAbsReal* nll = LL.createNLL(data); 
  RooPlot* frame = r.frame();
  RooAbsReal* pll = nll->createProfile(poi);
  pll->plotOn(frame);//,RooFit::LineColor(ROOT::kRed));
  frame->Draw();

  r.setVal(0.);
  cout << pll->getVal() << endl; 

  return;
    
    


}
///
/// Perform the 1d Prob scan.
/// Saves chi2 values and the prob-Scan p-values in a root tree
/// For the datasets stuff, we do not yet have a MethodDatasetsProbScan class, so we do it all in
/// MethodDatasetsProbScan
/// \param nRun Part of the root tree file name to facilitate parallel production.
///
int MethodDatasetsProbScan::scan1d(bool fast, bool reverse)
{
	if (fast) return 0; // tmp

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

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


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

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

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

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

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

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

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

        this->probScanTree->scanpoint = scanpoint;

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

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

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

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

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

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

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

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

        this->pdf->deleteNLL();

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

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

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


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

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

    return 0;
}
void fit_fractions_hist_syst(const Int_t n_loop = 1, const Int_t flag=2, const TString channel="ee", 
			     const Bool_t debug=false, const int rebin=4)
{

  int generated_events = 23513 - 1266;
  if ( channel == "mm" ) 
    generated_events = 32719 - 1715;

  // ========================================================================================
  //  Define the fit observable
  // ========================================================================================
  
  RooRealVar x("x","SVX mass",0.,10.);



  // ========================================================================================
  //  Define the fit parameters
  // ========================================================================================

  double f_c_0 = 0.242451;
  double f_l_0 = 0.494342;
  if ( channel=="mm" ){
    f_c_0 = 0.272683;
    f_l_0 = 0.493308;
  }

  RooRealVar f_c("f_c","c-jet fraction",    f_c_0,0.,1.);
  RooRealVar f_l("f_l","dusg-jet fraction", f_l_0,0.,1.);
 


  // ========================================================================================
  //  Build the Likelihood
  // ========================================================================================

#if HISTPDF>0
  
  TString dir = ( channel=="ee" ? "anaEle/" : ("anaMuo/") );


  TFile * f_pdf = new TFile(path + "DYJetsToLL.root");
  TH1F * h_b = (TH1F*) f_pdf->Get(dir + hname + "_b")->Clone("h_b");
  TH1F * h_c = (TH1F*) f_pdf->Get(dir + hname + "_c")->Clone("h_c");
  TH1F * h_l = (TH1F*) f_pdf->Get(dir + hname + "_l")->Clone("h_l");

  if ( rebin>0 ) {
    h_b->Rebin(rebin);
    h_c->Rebin(rebin);
    h_l->Rebin(rebin);
  }

  const int nSmooth = 0;

  // --- b-jet pdf:
  RooHistPdf * Pdf_b = new RooHistPdf("Pdf_b","b pdf", x, 
				      RooDataHist("h_b","",RooArgSet(x),h_b),
				      nSmooth);

  // --- c-jet pdf:
  RooHistPdf * Pdf_c = new RooHistPdf("Pdf_c","c pdf",x,
				      RooDataHist("h_c","",RooArgSet(x),h_c),
				      nSmooth);
  // --- dusg-jet pdf:
  RooHistPdf * Pdf_l = new RooHistPdf("Pdf_l","l pdf",x,
				      RooDataHist("h_l","",RooArgSet(x),h_l),
				      nSmooth);

#else  

  // --- b-jet pdf:

  RooRealVar b0("b0","b0",  3.68511e+02);
  RooRealVar b1("b1","b1",  4.18671e+00);
  RooRealVar b2("b2","b2", -5.43157e+00);
  RooRealVar b3("b3","b3", -5.37153e+00);
  RooRealVar b4("b4","b4",  1.68118e+00);
  RooRealVar b5("b5","b5",  4.74296e-01);
  if (channel=="mm"){
    b0.setVal( 2.15313e+03);
    b1.setVal( 4.95404e+00);
    b2.setVal(-6.02701e+00);
    b3.setVal(-6.03382e+00);
    b4.setVal( 1.85650e+00);
    b5.setVal( 4.98217e-01);
  }

  RooArgList b_pdf_par(b0,b1,b2,b3,b4,b5,x);
  RooGenericPdf * Pdf_b = new RooGenericPdf("Pdf_b","b pdf",
					    "@0*(TMath::Power(@6+@1,@2)+TMath::Exp(@3*@6))*(1.+TMath::Erf((@6-@4)/@5))",
					    b_pdf_par);


  RooRealVar b0_0("b0_0","b0_0",  3.68511e+02);
  RooRealVar b1_0("b1_0","b1_0",  4.18671e+00);
  RooRealVar b2_0("b2_0","b2_0", -5.43157e+00);
  RooRealVar b3_0("b3_0","b3_0", -5.37153e+00);
  RooRealVar b4_0("b4_0","b4_0",  1.68118e+00);
  RooRealVar b5_0("b5_0","b5_0",  4.74296e-01);
  if (channel=="mm"){
    b0_0.setVal( 2.15313e+03);
    b1_0.setVal( 4.95404e+00);
    b2_0.setVal(-6.02701e+00);
    b3_0.setVal(-6.03382e+00);
    b4_0.setVal( 1.85650e+00);
    b5_0.setVal( 4.98217e-01);
  }

  RooArgList b_pdf_par_0(b0_0,b1_0,b2_0,b3_0,b4_0,b5_0,x);
  RooGenericPdf * Pdf_b_0 = new RooGenericPdf("Pdf_b","b pdf",
					      "@0*(TMath::Power(@6+@1,@2)+TMath::Exp(@3*@6))*(1.+TMath::Erf((@6-@4)/@5))",
					      b_pdf_par_0);

  // --- c-jet  pdf:


  RooRealVar c0("c0","c0",  2.82240e+00);
  RooRealVar c1("c1","c1",  2.55373e+00);
  RooRealVar c2("c2","c2", -4.04638e+00);
  RooRealVar c3("c3","c3", -2.60516e+00);
  RooRealVar c4("c4","c4",  1.23763e+00);
  RooRealVar c5("c5","c5",  4.27637e-01);
  if (channel=="mm"){
    c0.setVal( 2.40900e+01);
    c1.setVal( 3.45622e+00);
    c2.setVal(-4.75556e+00);
    c3.setVal(-3.84626e+00);
    c4.setVal( 1.40510e+00);
    c5.setVal( 4.41045e-01);
  }

  RooArgList c_pdf_par(c0,c1,c2,c3,c4,c5,x);
  RooGenericPdf * Pdf_c = new RooGenericPdf("Pdf_c","c pdf",
					    "@0*(TMath::Power(@6+@1,@2)+TMath::Exp(@3*@6))*(1.+TMath::Erf((@6-@4)/@5))",
					    c_pdf_par);

  RooRealVar c0_0("c0_0","c0_0",  2.82240e+00);
  RooRealVar c1_0("c1_0","c1_0",  2.55373e+00);
  RooRealVar c2_0("c2_0","c2_0", -4.04638e+00);
  RooRealVar c3_0("c3_0","c3_0", -2.60516e+00);
  RooRealVar c4_0("c4_0","c4_0",  1.23763e+00);
  RooRealVar c5_0("c5_0","c5_0",  4.27637e-01);
  if (channel=="mm"){
    c0_0.setVal( 2.40900e+01);
    c1_0.setVal( 3.45622e+00);
    c2_0.setVal(-4.75556e+00);
    c3_0.setVal(-3.84626e+00);
    c4_0.setVal( 1.40510e+00);
    c5_0.setVal( 4.41045e-01);
  }

  RooArgList c_pdf_par_0(c0_0,c1_0,c2_0,c3_0,c4_0,c5_0,x);
  RooGenericPdf * Pdf_c_0 = new RooGenericPdf("Pdf_c_0","c pdf",
					      "@0*(TMath::Power(@6+@1,@2)+TMath::Exp(@3*@6))*(1.+TMath::Erf((@6-@4)/@5))",
					      c_pdf_par_0);


  // --- dusg-jet pdf:

  RooRealVar l0("l0","l0",  6.31062e+00);
  RooRealVar l1("l1","l1",  6.12407e-01);
  RooRealVar l2("l2","l2",  2.67040e-01);
  RooRealVar l3("l3","l3",  1.13059e+00);
  RooRealVar l4("l4","l4",  1.80036e-01);
  RooRealVar l5("l5","l5",  2.22999e+00);
  RooRealVar l6("l6","l6", -4.48947e+00);
   if (channel=="mm"){
   l0.setVal( 3.65986e+01);
   l1.setVal( 5.83322e-01);
   l2.setVal( 2.51782e-01);
   l3.setVal( 1.10027e+00);
   l4.setVal( 2.16042e-01);
   l5.setVal( 3.00909e+00);
   l6.setVal(-5.10485e+00);
  }
  
  RooArgList l_pdf_par(l0,l1,l2,l3,l4,l5,l6,x);
  RooGenericPdf * Pdf_l = new RooGenericPdf("Pdf_l","l pdf",
  					    "@0*(2.+TMath::Erf((@7-@1)/@2)+TMath::Erf((@7-@3)/@4))*TMath::Power(@7+@5,@6)",
  					    l_pdf_par);

  RooRealVar l0_0("l0_0","l0_0",  6.31062e+00);
  RooRealVar l1_0("l1_0","l1_0",  6.12407e-01);
  RooRealVar l2_0("l2_0","l2_0",  2.67040e-01);
  RooRealVar l3_0("l3_0","l3_0",  1.13059e+00);
  RooRealVar l4_0("l4_0","l4_0",  1.80036e-01);
  RooRealVar l5_0("l5_0","l5_0",  2.22999e+00);
  RooRealVar l6_0("l6_0","l6_0", -4.48947e+00);
  if (channel=="mm"){
   l0_0.setVal( 3.65986e+01);
   l1_0.setVal( 5.83322e-01);
   l2_0.setVal( 2.51782e-01);
   l3_0.setVal( 1.10027e+00);
   l4_0.setVal( 2.16042e-01);
   l5_0.setVal( 3.00909e+00);
   l6_0.setVal(-5.10485e+00);
  }
   
  RooArgList l_pdf_par_0(l0_0,l1_0,l2_0,l3_0,l4_0,l5_0,l6_0,x);
  RooGenericPdf * Pdf_l_0 = new RooGenericPdf("Pdf_l_0","l pdf",
					      "@0*(2.+TMath::Erf((@7-@1)/@2)+TMath::Erf((@7-@3)/@4))*TMath::Power(@7+@5,@6)",
					      l_pdf_par_0);

  if ( debug ){
    frame = x.frame();
    Pdf_b->plotOn(frame); 
    frame->Draw();
    //return;
  } 


#endif


  // --- build the likelihood:
  
  RooAddPdf model("model","Likelihood",RooArgList(*Pdf_c,*Pdf_l,*Pdf_b),RooArgList(f_c,f_l));
  RooAddPdf model_0("model_0","Likelihood",RooArgList(*Pdf_c_0,*Pdf_l_0,*Pdf_b_0),RooArgList(f_c,f_l));


  // ========================================================================================
  //  Read the data
  // ========================================================================================


  RooDataHist *dataHist = NULL;

  if ( flag==0 || flag==1 || flag==2 ){
    
    // --- Fit the data
    if ( flag==0 ){

      if ( channel == "ee" ){
	//f = new TFile(path + "DoubleElectron_2012_merge.root");
	//h = (TH1F*) f->Get("anaEle/"+hname)->Clone("h");
	f = new TFile("data_noBkg.root");
	h = (TH1F*) f->Get("hc_ee")->Clone("h");
      }
      else if ( channel == "mm" ){
	//f = new TFile(path + "DoubleMu_2012_merge.root");
	//h = (TH1F*) f->Get("anaMuo/"+hname)->Clone("h");
	f = new TFile("data_noBkg.root");
	h = (TH1F*) f->Get("hc_mm")->Clone("h");
      }
      else {
	std::cout << "\n*** ERROR: wrong channel name\n" << std::endl;
	return;
      }

      if ( rebin>0 )
	h->Rebin(rebin);

      dataHist = new RooDataHist("dataHist","x",RooArgSet(x),h);
      
    }

    // --- Fit the DY sample
    else if ( flag==1 ){
      
      f = new TFile(path + "DYJetsToLL.root");
      
      if ( channel == "ee" ){
	h = (TH1F*) f->Get("anaEle/"+hname)->Clone("h");
      }
      else if ( channel == "mm" ){
	h = (TH1F*) f->Get("anaMuo/"+hname)->Clone("h");
      }
      else {
	std::cout << "\n*** ERROR: wrong channel name\n" << std::endl;
	return;
      }
      
      if ( rebin>0 )
	h->Rebin(rebin);

      dataHist = new RooDataHist("dataHist","x",RooArgSet(x),h);
      
    }
    
    // --- Generate a toy MC
    else if ( flag==2 ){
      
      x.setBins(50);
      dataHist = model_0.generateBinned(RooArgSet(x), generated_events);
   
    }

    if ( debug ){
      RooFitResult * fitRes = model_0.fitTo(*dataHist,Save(),SumW2Error(kFALSE),Minimizer("Minuit2")); 
      frame = x.frame();
      dataHist->plotOn(frame);
      model_0.plotOn(frame);
      model_0.plotOn(frame, Components(*Pdf_b_0),LineStyle(kDashed),LineColor(kRed)) ;
      model_0.plotOn(frame, Components(*Pdf_c_0),LineStyle(kDashed),LineColor(kBlue)) ;
      model_0.plotOn(frame, Components(*Pdf_l_0),LineStyle(kDashed),LineColor(kBlack)) ;
      canvas = new TCanvas("canvas","canvas");
      frame->Draw();
      //return;
    }

    // --- Set the parameters of MultiGaus

    // b flavour

    int nDim_h = 5;
    int nDim_l = 6;

    TVectorD parMeans_b(nDim_h);
    parMeans_b(0) = b1.getVal();
    parMeans_b(1) = b2.getVal();
    parMeans_b(2) = b3.getVal();
    parMeans_b(3) = b4.getVal();
    parMeans_b(4) = b5.getVal();
    TMatrixDSym covMatrix_b(nDim_h);
    covMatrix_b(0,0) = 1.671e+00;        covMatrix_b(0,1) = -1.254e+00;       covMatrix_b(0,2) = -1.296e+00;       covMatrix_b(0,3) =  4.291e-01;       covMatrix_b(0,4) =  6.217e-02;
    covMatrix_b(1,0) = covMatrix_b(0,1); covMatrix_b(1,1) =  1.011e+00;       covMatrix_b(1,2) =  1.045e+00;       covMatrix_b(1,3) = -3.317e-01;       covMatrix_b(1,4) = -4.667e-02;
    covMatrix_b(2,0) = covMatrix_b(0,2); covMatrix_b(2,1) = covMatrix_b(1,2); covMatrix_b(2,2) =  1.104e+00;       covMatrix_b(2,3) = -3.351e-01;       covMatrix_b(2,4) = -4.523e-02;
    covMatrix_b(3,0) = covMatrix_b(0,3); covMatrix_b(3,1) = covMatrix_b(1,3); covMatrix_b(3,2) = covMatrix_b(2,3); covMatrix_b(3,3) =  1.143e-01;       covMatrix_b(3,4) =  1.704e-02;
    covMatrix_b(4,0) = covMatrix_b(0,4); covMatrix_b(4,1) = covMatrix_b(1,4); covMatrix_b(4,2) = covMatrix_b(2,4); covMatrix_b(4,3) = covMatrix_b(3,4); covMatrix_b(4,4) =  2.746e-03;
    covMatrix_b.Print();
    TVectorD genPars_b(nDim_l);
    

    // c flavour

    TVectorD parMeans_c(nDim_h);
    parMeans_c(0) = c1.getVal();
    parMeans_c(1) = c2.getVal();
    parMeans_c(2) = c3.getVal();
    parMeans_c(3) = c4.getVal();
    parMeans_c(4) = c5.getVal();
    TMatrixDSym covMatrix_c(nDim_h);
    covMatrix_c(0,0) = 2.401e-01;        covMatrix_c(0,1) = 1.875e-01;        covMatrix_c(0,2) = 1.673e-01;        covMatrix_c(0,3) = -1.856e-02;       covMatrix_c(0,4) = -1.120e-03;
    covMatrix_c(1,0) = covMatrix_c(0,1); covMatrix_c(1,1) = 3.539e-01;        covMatrix_c(1,2) = 3.859e-01;        covMatrix_c(1,3) = -5.883e-02;       covMatrix_c(1,4) = -8.237e-03;
    covMatrix_c(2,0) = covMatrix_c(0,2); covMatrix_c(2,1) = covMatrix_c(1,2); covMatrix_c(2,2) = 4.353e-01;        covMatrix_c(2,3) = -6.739e-02;       covMatrix_c(2,4) = -9.588e-03;
    covMatrix_c(3,0) = covMatrix_c(0,3); covMatrix_c(3,1) = covMatrix_c(1,3); covMatrix_c(3,2) = covMatrix_c(2,3); covMatrix_c(3,3) =  1.112e-02;       covMatrix_c(3,4) =  1.785e-03;
    covMatrix_c(4,0) = covMatrix_c(0,4); covMatrix_c(4,1) = covMatrix_c(1,4); covMatrix_c(4,2) = covMatrix_c(2,4); covMatrix_c(4,3) = covMatrix_c(3,4); covMatrix_c(4,4) =  3.735e-04;
    covMatrix_c.Print();
    TVectorD genPars_c(nDim_l);


    // light flavour

    TVectorD parMeans_l(nDim_l);
    parMeans_l(0) = l1.getVal();
    parMeans_l(1) = l2.getVal();
    parMeans_l(2) = l3.getVal();
    parMeans_l(3) = l4.getVal();
    parMeans_l(4) = l5.getVal();
    parMeans_l(5) = l6.getVal();
    TMatrixDSym covMatrix_l(nDim_l);
    covMatrix_l(0,0) = 7.090e-04;        covMatrix_l(0,1) = 3.629e-04;        covMatrix_l(0,2) = 6.320e-04;        covMatrix_l(0,3) = -7.600e-05;       covMatrix_l(0,4) = -1.336e-02;       covMatrix_l(0,5) =  1.077e-02;
    covMatrix_l(1,0) = covMatrix_l(0,1); covMatrix_l(1,1) = 2.661e-04;        covMatrix_l(1,2) = 2.863e-04;        covMatrix_l(1,3) =  1.026e-05;       covMatrix_l(1,4) = -5.617e-03;       covMatrix_l(1,5) =  4.414e-03;
    covMatrix_l(2,0) = covMatrix_l(0,2); covMatrix_l(2,1) = covMatrix_l(1,2); covMatrix_l(2,2) = 1.198e-03;        covMatrix_l(2,3) = -2.218e-05;       covMatrix_l(2,4) = -1.200e-02;       covMatrix_l(2,5) =  9.095e-03;
    covMatrix_l(3,0) = covMatrix_l(0,3); covMatrix_l(3,1) = covMatrix_l(1,3); covMatrix_l(3,2) = covMatrix_l(2,3); covMatrix_l(3,3) =  1.214e-03;       covMatrix_l(3,4) =  3.792e-03;       covMatrix_l(3,5) = -3.238e-03;
    covMatrix_l(4,0) = covMatrix_l(0,4); covMatrix_l(4,1) = covMatrix_l(1,4); covMatrix_l(4,2) = covMatrix_l(2,4); covMatrix_l(4,3) = covMatrix_l(3,4); covMatrix_l(4,4) =  3.927e-01;       covMatrix_l(4,5) = -3.457e-01;
    covMatrix_l(5,0) = covMatrix_l(0,5); covMatrix_l(5,1) = covMatrix_l(1,5); covMatrix_l(5,2) = covMatrix_l(2,5); covMatrix_l(5,3) = covMatrix_l(3,5); covMatrix_l(5,4) = covMatrix_l(4,5); covMatrix_l(5,5) =  3.127e-01;
    covMatrix_l.Print();
    TVectorD genPars_l(nDim_l);
 
    b_frame = x.frame();
    c_frame = x.frame();
    l_frame = x.frame();

    TH1* h0_b = Pdf_b_0->createHistogram("h0_b",x); 
    h0_b->SetEntries((int) (1.-f_c_0-f_l_0)*generated_events);
    h0_b->Scale((1.-f_c_0-f_l_0)*generated_events/h0_b->Integral());
    TH1* h0_c = Pdf_c_0->createHistogram("h0_c",x); 
    h0_c->SetEntries((int) f_c_0*generated_events);
    h0_c->Scale(f_c_0*generated_events/h0_c->Integral());
    TH1* h0_l = Pdf_l_0->createHistogram("h0_l",x); 
    h0_l->SetEntries((int) f_l_0*generated_events);
    h0_l->Scale(f_l_0*generated_events/h0_l->Integral());

    for (int iloop=0; iloop<n_loop; ++iloop ){

      if ( iloop % 100 == 0 ) 
	cout << " >>>>>>>>>>>> Iteration # " << iloop << endl;


      f_l.setVal(f_l_0);
      f_c.setVal(f_c_0);

      double chi2 = 99999.;
      double prob = -999.;

      double chi2_b = 9999.;
      double chi2_c = 9999.;
      double chi2_l = 9999.;

      double ks_b = -999.;
      double ks_c = -999.;
      double ks_l = -999.;

      //while ( chi2_b>0.5 || std::isnan(chi2_b) ){
      while ( ks_b<0.1 ){

	MultiGaus(parMeans_b, covMatrix_b, genPars_b);
	//genPars_b.Print();

	b1.setVal(genPars_b[0]);
	b2.setVal(genPars_b[1]);
	b3.setVal(genPars_b[2]);
	b4.setVal(genPars_b[3]);
	b5.setVal(genPars_b[4]);
      

	TH1* h1_b = Pdf_b->createHistogram("h1_b",x); 
	h1_b->SetEntries((int) (1.-f_c_0-f_l_0)*generated_events);
	h1_b->Scale((1.-f_c_0-f_l_0)*generated_events/h1_b->Integral());
	//h1_b->Draw("SAME");
	chi2_b = h1_b->Chi2Test(h0_b,"WW CHI2/NDF");
	h_chi2_b.Fill(chi2_b);
	ks_b = h1_b->KolmogorovTest(h0_b);
	h_ks_b.Fill(ks_b);

	delete h1_b;
      }

      //while ( chi2_c>0.5 || std::isnan(chi2_c) ){
      while ( ks_c<0.1 ){

	MultiGaus(parMeans_c, covMatrix_c, genPars_c);
	//genPars_c.Print();

	c1.setVal(genPars_c[0]);
	c2.setVal(genPars_c[1]);
	c3.setVal(genPars_c[2]);
	c4.setVal(genPars_c[3]);
	c5.setVal(genPars_c[4]);

	TH1* h1_c = Pdf_c->createHistogram("h1_c",x); 
	h1_c->SetEntries((int) f_c_0*generated_events);
	h1_c->Scale(f_c_0*generated_events/h1_c->Integral());
	//h1_c->Draw("SAME");
	chi2_c = h1_c->Chi2Test(h0_c,"WW CHI2/NDF");
	h_chi2_c.Fill(chi2_c);
	ks_c = h1_c->KolmogorovTest(h0_c);
	h_ks_c.Fill(ks_c);

	delete h1_c;
      }


      //while ( chi2_l>0.5 || std::isnan(chi2_l) ){
      while ( ks_l<0.1 ){

	MultiGaus(parMeans_l, covMatrix_l, genPars_l);
	//genPars_l.Print();

	l1.setVal(genPars_l[0]);
	l2.setVal(genPars_l[1]);
	l3.setVal(genPars_l[2]);
	l4.setVal(genPars_l[3]);
	l5.setVal(genPars_l[4]);
	l6.setVal(genPars_l[5]);

	TH1* h1_l = Pdf_l->createHistogram("h1_l",x); 
	h1_l->SetEntries((int) f_l_0*generated_events);
	h1_l->Scale(f_l_0*generated_events/h1_l->Integral());
	//h1_l->Draw("SAME");
	chi2_l = h1_l->Chi2Test(h0_l,"WW CHI2/NDF");
	h_chi2_l.Fill(chi2_l);
	ks_l = h1_l->KolmogorovTest(h0_l);
	h_ks_l.Fill(ks_l);

	delete h1_l;
      }

      RooFitResult * fitRes = model.fitTo(*dataHist,Save(),SumW2Error(kFALSE),Minimizer("Minuit2"),PrintLevel(1),Verbose(0));

      if (fitRes->status() != 0 ) continue;
      
      frame = x.frame();
      dataHist->plotOn(frame);
      model.plotOn(frame);
       
      //chi2 = frame->chiSquare("model_Norm[x]","h_dataHist",2);
      chi2 = frame->chiSquare(2);
      prob = TMath::Prob(chi2,2);
      
      h_chi2.Fill(chi2);
      h_prob.Fill(prob);
      

      //if  ( prob < 0.6 ) continue;
      if ( chi2 > 5. ) continue;
      if ( f_c.getVal()<0.01 ||
      	   f_l.getVal()<0.01 ||
	   (1.-f_c.getVal()-f_l.getVal())<0.01 ) continue;
      
      if ( f_c.getVal()>0.99 ||
      	   f_l.getVal()>0.99 ||
      	   (1.-f_c.getVal()-f_l.getVal())>0.99 ) continue;

      
      Pdf_b->plotOn(b_frame);
      Pdf_c->plotOn(c_frame);
      Pdf_l->plotOn(l_frame);
      
      
      h_b1.Fill(genPars_b[0]);
      h_b2.Fill(genPars_b[1]);
      h_b3.Fill(genPars_b[2]);
      h_b4.Fill(genPars_b[3]);
      h_b5.Fill(genPars_b[4]);
      
      h_c1.Fill(genPars_c[0]);
      h_c2.Fill(genPars_c[1]);
      h_c3.Fill(genPars_c[2]);
      h_c4.Fill(genPars_c[3]);
      h_c5.Fill(genPars_c[4]);
      
      h_l1.Fill(genPars_l[0]);
      h_l2.Fill(genPars_l[1]);
      h_l3.Fill(genPars_l[2]);
      h_l4.Fill(genPars_l[3]);
      h_l5.Fill(genPars_l[4]);
      h_l6.Fill(genPars_l[5]);

      if ( debug ) {
	model.plotOn(frame, Components(*Pdf_b),LineStyle(kDashed),LineColor(kRed)) ;
	model.plotOn(frame, Components(*Pdf_c),LineStyle(kDashed),LineColor(kBlue)) ;
	model.plotOn(frame, Components(*Pdf_l),LineStyle(kDashed),LineColor(kBlack)) ;
	canvas = new TCanvas("canvas","canvas");
	frame->Draw();
      }

      h_fc.Fill(f_c.getVal());

    }

    Pdf_b_0->plotOn(b_frame,LineColor(kRed),LineWidth(1));
    Pdf_c_0->plotOn(c_frame,LineColor(kRed),LineWidth(1));
    Pdf_l_0->plotOn(l_frame,LineColor(kRed),LineWidth(1));

    c_chi2 = new TCanvas();
    h_chi2.Draw();
    c_prob = new TCanvas();
    h_prob.Draw();

    c_chi2_pdf = new TCanvas("c_chi2_pdf", "Pdf's chi2", 1024, 768);
    c_chi2_pdf->Divide(3,2);
    c_chi2_pdf->cd(1);
    h_chi2_b.Draw();
    c_chi2_pdf->cd(2);
    h_chi2_c.Draw();
    c_chi2_pdf->cd(3);
    h_chi2_l.Draw();
    c_chi2_pdf->cd(4);
    h_ks_b.Draw();
    c_chi2_pdf->cd(5);
    h_ks_c.Draw();
    c_chi2_pdf->cd(6);
    h_ks_l.Draw();

    c_bpars = new TCanvas("c_bpars", "generated b parameters: distributions", 1024, 768);
    c_bpars->Divide(3,2);
    c_bpars->cd(1);
    h_b1.Draw();
    c_bpars->cd(2);
    h_b2.Draw();
    c_bpars->cd(3);
    h_b3.Draw();
    c_bpars->cd(4);
    h_b4.Draw();
    c_bpars->cd(5);
    h_b5.Draw();

    c_cpars = new TCanvas("c_cpars", "generated c parameters: distributions", 1024, 768);
    c_cpars->Divide(3,2);
    c_cpars->cd(1);
    h_c1.Draw();
    c_cpars->cd(2);
    h_c2.Draw();
    c_cpars->cd(3);
    h_c3.Draw();
    c_cpars->cd(4);
    h_c4.Draw();
    c_cpars->cd(5);
    h_c5.Draw();

    c_lpars = new TCanvas("l_lpars", "generated dusg parameters: distributions", 1024, 768);
    c_lpars->Divide(3,2);
    c_lpars->cd(1);
    h_l1.Draw();
    c_lpars->cd(2);
    h_l2.Draw();
    c_lpars->cd(3);
    h_l3.Draw();
    c_lpars->cd(4);
    h_l4.Draw();
    c_lpars->cd(5);
    h_l5.Draw();
    c_lpars->cd(6);
    h_l6.Draw();

    c_bpdf = new TCanvas();
    b_frame->Draw();
    c_cpdf = new TCanvas();
    c_frame->Draw();
    c_lpdf = new TCanvas();
    l_frame->Draw();

    c_fc = new TCanvas();
    h_fc.Draw();
   
    c_bpdf ->SaveAs("figs/c_bpdf.png");
    c_cpdf ->SaveAs("figs/c_cpdf.png");
    c_lpdf ->SaveAs("figs/c_lpdf.png");
    c_fc   ->SaveAs("figs/c_fc.png");
    c_chi2 ->SaveAs("figs/c_chi2.png");
    c_prob ->SaveAs("figs/c_prob.png");
    c_bpars->SaveAs("figs/c_bpars.png");
    c_cpars->SaveAs("figs/c_cpars.png");
    c_lpars->SaveAs("figs/c_lpars.png");
    c_chi2_pdf->SaveAs("figs/c_chi2_pdf.png");
    
    c_bpdf ->SaveAs("figs/c_bpdf.root");
    c_cpdf ->SaveAs("figs/c_cpdf.root");
    c_lpdf ->SaveAs("figs/c_lpdf.root");
    c_fc   ->SaveAs("figs/c_fc.root");
    c_chi2 ->SaveAs("figs/c_chi2.root");
    c_prob ->SaveAs("figs/c_prob.root");
    c_bpars->SaveAs("figs/c_bpars.root");
    c_cpars->SaveAs("figs/c_cpars.root");
    c_lpars->SaveAs("figs/c_lpars.root");
    c_chi2_pdf->SaveAs("figs/c_chi2_pdf.root");

  }

}
Beispiel #8
0
Datei: fit.C Projekt: dcraik/lhcb
void fit(Int_t i, Double_t va=-0.43, Double_t vb=0.){
    sprintf(namestr,"%d_%.2f_%.2f",i,va,vb);

    Double_t g1, g2;
    g1 = 0.1*r.Rndm() - 0.05;
    g2 =     r.Rndm() - 0.5;

    //a->setVal(va);
    //b->setVal(vb);

    //G001->setVal(g1);
    //G002->setVal(g2);

    //RooRealVar * G000 = new RooRealVar("G000", "G000",  0.5);
    //RooRealVar * G001 = new RooRealVar("G001", "G001",  g1, -5., 5.);
    //RooRealVar * G002 = new RooRealVar("G002", "G002",  g2, -5., 5.);
    //RooRealVar * G003 = new RooRealVar("G003", "G003", 0.0);//, -1., 1.);
    //RooRealVar * G004 = new RooRealVar("G004", "G004", 0.0);//, -1., 1.);
    //RooRealVar * a    = new RooRealVar("a",    "a",    va);
    //RooRealVar * b    = new RooRealVar("b",    "b",    vb);
    //RooRealVar * n    = new RooRealVar("n",    "n",    1000., -100., 5000.);
    RooRealVar G000("G000", "G000",  0.5);
    RooRealVar G001("G001", "G001",  g1, -5., 5.);
    RooRealVar G002("G002", "G002",  g2, -5., 5.);
    RooRealVar G003("G003", "G003", 0.0);//, -1., 1.);
    RooRealVar G004("G004", "G004", 0.0);//, -1., 1.);
    RooRealVar    a("a",    "a",    va);
    RooRealVar    b("b",    "b",    vb);
    RooRealVar    n("n",    "n",    1000., -100., 5000.);

    RooB2Kll pdf("pdf", "pdf", *cosTheta, G000, G001, G002, G003, G004, a, b, n);

    RooFitResult * fitresult = pdf.fitTo(*data,Save(kTRUE), Minos(kFALSE), NumCPU(4), SumW2Error(kTRUE));
    
    RooPlot * frame = cosTheta->frame();
    data->plotOn(frame);
    pdf.plotOn(frame);

    if(fitresult->minNll() == fitresult->minNll() && fitresult->minNll()>0 ) {
    fout << i << "\t" << a.getVal() << "\t" << b.getVal() << "\t" << fitresult->minNll() << "\t" << fitresult->status() << "\t" 
         << G000.getVal() << "\t" << G001.getVal() << "\t" << G002.getVal() << "\t" << G003.getVal() << "\t" << G004.getVal() << endl;
    }

    gROOT->ProcessLine(".x ~/lhcb/lhcbStyle.C");
    TCanvas c("fit","fit", 800, 800);
    frame->Draw();
    c.SaveAs("fits/fit"+TString(namestr)+".png");
    c.SaveAs("fits/fit"+TString(namestr)+".pdf");
}
void performFit(string inputDir, string inputParameterFile, string label,
                string PassInputDataFilename, string FailInputDataFilename, 
                string PassSignalTemplateHistName, string FailSignalTemplateHistName)
{

  gBenchmark->Start("fitZCat");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================
  
  const Double_t mlow  = 60;
  const Double_t mhigh = 120;
  const Int_t    nbins = 24;

  TString effType = inputDir;

  // The fit variable - lepton invariant mass
  RooRealVar* rooMass_ = new RooRealVar("Mass","m_{ee}",mlow, mhigh, "GeV/c^{2}");
  RooRealVar Mass = *rooMass_;
  Mass.setBins(nbins);

  // Make the category variable that defines the two fits,
  // namely whether the probe passes or fails the eff criteria.
  RooCategory sample("sample","") ;
  sample.defineType("Pass", 1) ;
  sample.defineType("Fail", 2) ; 


  RooDataSet *dataPass  = RooDataSet::read((inputDir+PassInputDataFilename).c_str(),RooArgList(Mass));
  RooDataSet *dataFail  = RooDataSet::read((inputDir+FailInputDataFilename).c_str(),RooArgList(Mass));

  RooDataSet *dataCombined = new RooDataSet("dataCombined","dataCombined", RooArgList(Mass), RooFit::Index(sample), 
                                            RooFit::Import("Pass",*dataPass),
                                            RooFit::Import("Fail",*dataFail));



  //*********************************************************************************************
  //Define Free Parameters
  //*********************************************************************************************
  RooRealVar* ParNumSignal =  LoadParameters(inputParameterFile, label,"ParNumSignal");
  RooRealVar* ParNumBkgPass =  LoadParameters(inputParameterFile, label,"ParNumBkgPass");
  RooRealVar* ParNumBkgFail =  LoadParameters(inputParameterFile, label, "ParNumBkgFail");
  RooRealVar* ParEfficiency  = LoadParameters(inputParameterFile, label, "ParEfficiency");
  RooRealVar* ParPassBackgroundExpCoefficient = LoadParameters(inputParameterFile, label, "ParPassBackgroundExpCoefficient");
  RooRealVar* ParFailBackgroundExpCoefficient = LoadParameters(inputParameterFile, label, "ParFailBackgroundExpCoefficient");
  RooRealVar* ParPassSignalMassShift = LoadParameters(inputParameterFile, label, "ParPassSignalMassShift");
  RooRealVar* ParFailSignalMassShift = LoadParameters(inputParameterFile, label, "ParFailSignalMassShift");
  RooRealVar* ParPassSignalResolution = LoadParameters(inputParameterFile, label, "ParPassSignalResolution");
  RooRealVar* ParFailSignalResolution = LoadParameters(inputParameterFile, label, "ParFailSignalResolution");



// new RooRealVar  ("ParPassSignalMassShift","ParPassSignalMassShift",-2.6079e-02,-10.0, 10.0);   //ParPassSignalMassShift->setConstant(kTRUE);  
//   RooRealVar* ParFailSignalMassShift = new RooRealVar  ("ParFailSignalMassShift","ParFailSignalMassShift",7.2230e-01,-10.0, 10.0);   //ParFailSignalMassShift->setConstant(kTRUE);  
//   RooRealVar* ParPassSignalResolution = new RooRealVar ("ParPassSignalResolution","ParPassSignalResolution",6.9723e-01,0.0, 10.0);     ParPassSignalResolution->setConstant(kTRUE);  
//   RooRealVar* ParFailSignalResolution = new RooRealVar ("ParFailSignalResolution","ParFailSignalResolution",1.6412e+00,0.0, 10.0);     ParFailSignalResolution->setConstant(kTRUE);  

  //*********************************************************************************************
  //
  //Load Signal PDFs
  //
  //*********************************************************************************************

  TFile *Zeelineshape_file =  new TFile("res/photonEfffromZee.dflag1.eT1.2.gT40.mt15.root", "READ");
  TH1* histTemplatePass = (TH1D*) Zeelineshape_file->Get(PassSignalTemplateHistName.c_str());
  TH1* histTemplateFail = (TH1D*) Zeelineshape_file->Get(FailSignalTemplateHistName.c_str());

  //Introduce mass shift coordinate transformation 
//   RooFormulaVar PassShiftedMass("PassShiftedMass","@0-@1",RooArgList(Mass,*ParPassSignalMassShift));
//   RooFormulaVar FailShiftedMass("FailShiftedMass","@0-@1",RooArgList(Mass,*ParFailSignalMassShift));

  RooGaussian  *PassSignalResolutionFunction =  new RooGaussian("PassSignalResolutionFunction","PassSignalResolutionFunction",Mass,*ParPassSignalMassShift,*ParPassSignalResolution);
  RooGaussian  *FailSignalResolutionFunction =  new RooGaussian("FailSignalResolutionFunction","FailSignalResolutionFunction",Mass,*ParFailSignalMassShift,*ParFailSignalResolution);


  RooDataHist* dataHistPass = new RooDataHist("dataHistPass","dataHistPass", RooArgSet(Mass), histTemplatePass);
  RooDataHist* dataHistFail = new RooDataHist("dataHistFail","dataHistFail", RooArgSet(Mass), histTemplateFail);
  RooHistPdf* signalShapePassTemplatePdf = new RooHistPdf("signalShapePassTemplatePdf", "signalShapePassTemplatePdf", Mass, *dataHistPass, 1);
  RooHistPdf* signalShapeFailTemplatePdf = new RooHistPdf("signalShapeFailTemplatePdf", "signalShapeFailTemplatePdf", Mass, *dataHistFail, 1);

  RooFFTConvPdf* signalShapePassPdf = new RooFFTConvPdf("signalShapePassPdf","signalShapePassPdf"  , Mass, *signalShapePassTemplatePdf,*PassSignalResolutionFunction,2);
  RooFFTConvPdf* signalShapeFailPdf = new RooFFTConvPdf("signalShapeFailPdf","signalShapeFailPdf"  , Mass, *signalShapeFailTemplatePdf,*FailSignalResolutionFunction,2);


  // Now define some efficiency/yield variables  
  RooFormulaVar* NumSignalPass = new RooFormulaVar("NumSignalPass", "ParEfficiency*ParNumSignal", RooArgList(*ParEfficiency,*ParNumSignal));
  RooFormulaVar* NumSignalFail = new RooFormulaVar("NumSignalFail", "(1.0-ParEfficiency)*ParNumSignal", RooArgList(*ParEfficiency,*ParNumSignal));


  //*********************************************************************************************
  //
  // Create Background PDFs
  //
  //*********************************************************************************************
  RooExponential* bkgPassPdf = new RooExponential("bkgPassPdf","bkgPassPdf",Mass, *ParPassBackgroundExpCoefficient);
  RooExponential* bkgFailPdf = new RooExponential("bkgFailPdf","bkgFailPdf",Mass, *ParFailBackgroundExpCoefficient);


 //*********************************************************************************************
  //
  // Create Total PDFs
  //
  //*********************************************************************************************
  RooAddPdf pdfPass("pdfPass","pdfPass",RooArgList(*signalShapePassPdf,*bkgPassPdf), RooArgList(*NumSignalPass,*ParNumBkgPass));
  RooAddPdf pdfFail("pdfFail","pdfFail",RooArgList(*signalShapeFailPdf,*bkgFailPdf), RooArgList(*NumSignalFail,*ParNumBkgFail));

  // PDF for simultaneous fit
   RooSimultaneous totalPdf("totalPdf","totalPdf", sample);
   totalPdf.addPdf(pdfPass,"Pass");
//    totalPdf.Print();
   totalPdf.addPdf(pdfFail,"Fail");
   totalPdf.Print();


   //*********************************************************************************************
  //
  // Perform Fit
  //
  //*********************************************************************************************
   RooFitResult *fitResult = 0;

  // ********* Fix with Migrad first ********** //  
   fitResult = totalPdf.fitTo(*dataCombined, RooFit::Save(true), 
                              RooFit::Extended(true), RooFit::PrintLevel(-1));
   fitResult->Print("v");


//   // ********* Fit With Minos ********** //  
//    fitResult = totalPdf.fitTo(*dataCombined, RooFit::Save(true), 
//                               RooFit::Extended(true), RooFit::PrintLevel(-1), RooFit::Minos());
//    fitResult->Print("v");




//   // ********* Fix Mass Shift and Fit For Resolution ********** //  
//    ParPassSignalMassShift->setConstant(kTRUE); 
//    ParFailSignalMassShift->setConstant(kTRUE); 
//    ParPassSignalResolution->setConstant(kFALSE); 
//    ParFailSignalResolution->setConstant(kFALSE); 
//    fitResult = totalPdf.fitTo(*dataCombined, RooFit::Save(true), 
//    RooFit::Extended(true), RooFit::PrintLevel(-1));
//    fitResult->Print("v");


//   // ********* Do Final Fit ********** //  
//    ParPassSignalMassShift->setConstant(kFALSE); 
//    ParFailSignalMassShift->setConstant(kFALSE); 
//    ParPassSignalResolution->setConstant(kTRUE); 
//    ParFailSignalResolution->setConstant(kTRUE); 
//    fitResult = totalPdf.fitTo(*dataCombined, RooFit::Save(true), 
//                                             RooFit::Extended(true), RooFit::PrintLevel(-1));
//    fitResult->Print("v");





  double nSignalPass = NumSignalPass->getVal();
  double nSignalFail    = NumSignalFail->getVal();
  double denominator = nSignalPass + nSignalFail;

  printf("\nFit results:\n");
  if( fitResult->status() != 0 ){
    std::cout<<"ERROR: BAD FIT STATUS"<<std::endl;
  }

  printf("    Efficiency = %.4f +- %.4f\n", 
	 ParEfficiency->getVal(), ParEfficiency->getPropagatedError(*fitResult));  
  cout << "Signal Pass: "******"Signal Fail: " << nSignalFail << endl;

  cout << "*********************************************************************\n";
  cout << "Final Parameters\n";
  cout << "*********************************************************************\n";
  PrintParameter(ParNumSignal, label,"ParNumSignal");
  PrintParameter(ParNumBkgPass, label,"ParNumBkgPass");
  PrintParameter(ParNumBkgFail, label, "ParNumBkgFail");
  PrintParameter(ParEfficiency  , label, "ParEfficiency");
  PrintParameter(ParPassBackgroundExpCoefficient , label, "ParPassBackgroundExpCoefficient");
  PrintParameter(ParFailBackgroundExpCoefficient , label, "ParFailBackgroundExpCoefficient");
  PrintParameter(ParPassSignalMassShift , label, "ParPassSignalMassShift");
  PrintParameter(ParFailSignalMassShift , label, "ParFailSignalMassShift");
  PrintParameter(ParPassSignalResolution , label, "ParPassSignalResolution");
  PrintParameter(ParFailSignalResolution , label, "ParFailSignalResolution");
  cout << endl << endl;


  //--------------------------------------------------------------------------------------------------------------
  // Make plots 
  //==============================================================================================================  
  TFile *canvasFile = new TFile("Efficiency_FitResults.root", "UPDATE");


  RooAbsData::ErrorType errorType = RooAbsData::Poisson;

  Mass.setBins(NBINSPASS);
  TString cname = TString((label+"_Pass").c_str());
  TCanvas *c = new TCanvas(cname,cname,800,600);
  RooPlot* frame1 = Mass.frame();
  frame1->SetMinimum(0);
  dataPass->plotOn(frame1,RooFit::DataError(errorType));
  pdfPass.plotOn(frame1,RooFit::ProjWData(*dataPass), 
  RooFit::Components(*bkgPassPdf),RooFit::LineColor(kRed));
  pdfPass.plotOn(frame1,RooFit::ProjWData(*dataPass));
  frame1->Draw("e0");
  
  TPaveText *plotlabel = new TPaveText(0.23,0.87,0.43,0.92,"NDC");
   plotlabel->SetTextColor(kBlack);
   plotlabel->SetFillColor(kWhite);
   plotlabel->SetBorderSize(0);
   plotlabel->SetTextAlign(12);
   plotlabel->SetTextSize(0.03);
   plotlabel->AddText("CMS Preliminary 2010");
  TPaveText *plotlabel2 = new TPaveText(0.23,0.82,0.43,0.87,"NDC");
   plotlabel2->SetTextColor(kBlack);
   plotlabel2->SetFillColor(kWhite);
   plotlabel2->SetBorderSize(0);
   plotlabel2->SetTextAlign(12);
   plotlabel2->SetTextSize(0.03);
   plotlabel2->AddText("#sqrt{s} = 7 TeV");
  TPaveText *plotlabel3 = new TPaveText(0.23,0.75,0.43,0.80,"NDC");
   plotlabel3->SetTextColor(kBlack);
   plotlabel3->SetFillColor(kWhite);
   plotlabel3->SetBorderSize(0);
   plotlabel3->SetTextAlign(12);
   plotlabel3->SetTextSize(0.03);
  char temp[100];
  sprintf(temp, "%.4f", LUMINOSITY);
  plotlabel3->AddText((string("#int#font[12]{L}dt = ") + 
  temp + string(" pb^{ -1}")).c_str());
  TPaveText *plotlabel4 = new TPaveText(0.6,0.82,0.8,0.87,"NDC");
   plotlabel4->SetTextColor(kBlack);
   plotlabel4->SetFillColor(kWhite);
   plotlabel4->SetBorderSize(0);
   plotlabel4->SetTextAlign(12);
   plotlabel4->SetTextSize(0.03);
   double nsig = ParNumSignal->getVal();
   double nErr = ParNumSignal->getError();
   double e = ParEfficiency->getVal();
   double eErr = ParEfficiency->getError();
   double corr = fitResult->correlation(*ParEfficiency, *ParNumSignal);
   double err = ErrorInProduct(nsig, nErr, e, eErr, corr);
   sprintf(temp, "Signal = %.2f #pm %.2f", NumSignalPass->getVal(), err);
   plotlabel4->AddText(temp);
   TPaveText *plotlabel5 = new TPaveText(0.6,0.77,0.8,0.82,"NDC");
   plotlabel5->SetTextColor(kBlack);
   plotlabel5->SetFillColor(kWhite);
   plotlabel5->SetBorderSize(0);
   plotlabel5->SetTextAlign(12);
   plotlabel5->SetTextSize(0.03);
   sprintf(temp, "Bkg = %.2f #pm %.2f", ParNumBkgPass->getVal(), ParNumBkgPass->getError());
   plotlabel5->AddText(temp);
   TPaveText *plotlabel6 = new TPaveText(0.6,0.87,0.8,0.92,"NDC");
   plotlabel6->SetTextColor(kBlack);
   plotlabel6->SetFillColor(kWhite);
   plotlabel6->SetBorderSize(0);
   plotlabel6->SetTextAlign(12);
   plotlabel6->SetTextSize(0.03);
   plotlabel6->AddText("Passing probes");
   TPaveText *plotlabel7 = new TPaveText(0.6,0.72,0.8,0.77,"NDC");
   plotlabel7->SetTextColor(kBlack);
   plotlabel7->SetFillColor(kWhite);
   plotlabel7->SetBorderSize(0);
   plotlabel7->SetTextAlign(12);
   plotlabel7->SetTextSize(0.03); 
   sprintf(temp, "Eff = %.3f #pm %.3f", ParEfficiency->getVal(), ParEfficiency->getErrorHi());
   plotlabel7->AddText(temp);
   TPaveText *plotlabel8 = new TPaveText(0.6,0.72,0.8,0.66,"NDC");
   plotlabel8->SetTextColor(kBlack);
   plotlabel8->SetFillColor(kWhite);
   plotlabel8->SetBorderSize(0);
   plotlabel8->SetTextAlign(12);
   plotlabel8->SetTextSize(0.03);
   sprintf(temp, "#chi^{2}/DOF = %.3f", frame1->chiSquare());
   plotlabel8->AddText(temp);

  plotlabel4->Draw();
  plotlabel5->Draw();
  plotlabel6->Draw();
  plotlabel7->Draw();
  plotlabel8->Draw();

//   c->SaveAs( cname + TString(".eps"));
  c->SaveAs( cname + TString(".gif"));
  canvasFile->WriteTObject(c, c->GetName(), "WriteDelete");

 
  Mass.setBins(NBINSFAIL);
  cname = TString((label+"_Fail").c_str());
  TCanvas* c2 = new TCanvas(cname,cname,800,600);
  RooPlot* frame2 = Mass.frame();
  frame2->SetMinimum(0);
  dataFail->plotOn(frame2,RooFit::DataError(errorType));
  pdfFail.plotOn(frame2,RooFit::ProjWData(*dataFail), 
  RooFit::Components(*bkgFailPdf),RooFit::LineColor(kRed));
  pdfFail.plotOn(frame2,RooFit::ProjWData(*dataFail));
  frame2->Draw("e0");

  plotlabel = new TPaveText(0.23,0.87,0.43,0.92,"NDC");
   plotlabel->SetTextColor(kBlack);
   plotlabel->SetFillColor(kWhite);
   plotlabel->SetBorderSize(0);
   plotlabel->SetTextAlign(12);
   plotlabel->SetTextSize(0.03);
   plotlabel->AddText("CMS Preliminary 2010");
 plotlabel2 = new TPaveText(0.23,0.82,0.43,0.87,"NDC");
   plotlabel2->SetTextColor(kBlack);
   plotlabel2->SetFillColor(kWhite);
   plotlabel2->SetBorderSize(0);
   plotlabel2->SetTextAlign(12);
   plotlabel2->SetTextSize(0.03);
   plotlabel2->AddText("#sqrt{s} = 7 TeV");
  plotlabel3 = new TPaveText(0.23,0.75,0.43,0.80,"NDC");
   plotlabel3->SetTextColor(kBlack);
   plotlabel3->SetFillColor(kWhite);
   plotlabel3->SetBorderSize(0);
   plotlabel3->SetTextAlign(12);
   plotlabel3->SetTextSize(0.03);
   sprintf(temp, "%.4f", LUMINOSITY);
   plotlabel3->AddText((string("#int#font[12]{L}dt = ") + 
                        temp + string(" pb^{ -1}")).c_str());
   plotlabel4 = new TPaveText(0.6,0.82,0.8,0.87,"NDC");
   plotlabel4->SetTextColor(kBlack);
   plotlabel4->SetFillColor(kWhite);
   plotlabel4->SetBorderSize(0);
   plotlabel4->SetTextAlign(12);
   plotlabel4->SetTextSize(0.03);
   err = ErrorInProduct(nsig, nErr, 1.0-e, eErr, corr);
   sprintf(temp, "Signal = %.2f #pm %.2f", NumSignalFail->getVal(), err);
   plotlabel4->AddText(temp);
   plotlabel5 = new TPaveText(0.6,0.77,0.8,0.82,"NDC");
   plotlabel5->SetTextColor(kBlack);
   plotlabel5->SetFillColor(kWhite);
   plotlabel5->SetBorderSize(0);
   plotlabel5->SetTextAlign(12);
   plotlabel5->SetTextSize(0.03);
   sprintf(temp, "Bkg = %.2f #pm %.2f", ParNumBkgFail->getVal(), ParNumBkgFail->getError());
   plotlabel5->AddText(temp);
   plotlabel6 = new TPaveText(0.6,0.87,0.8,0.92,"NDC");
   plotlabel6->SetTextColor(kBlack);
   plotlabel6->SetFillColor(kWhite);
   plotlabel6->SetBorderSize(0);
   plotlabel6->SetTextAlign(12);
   plotlabel6->SetTextSize(0.03);
   plotlabel6->AddText("Failing probes");
   plotlabel7 = new TPaveText(0.6,0.72,0.8,0.77,"NDC");
   plotlabel7->SetTextColor(kBlack);
   plotlabel7->SetFillColor(kWhite);
   plotlabel7->SetBorderSize(0);
   plotlabel7->SetTextAlign(12);
   plotlabel7->SetTextSize(0.03);
   sprintf(temp, "Eff = %.3f #pm %.3f", ParEfficiency->getVal(), ParEfficiency->getErrorHi(), ParEfficiency->getErrorLo());
   plotlabel7->AddText(temp);
   plotlabel8 = new TPaveText(0.6,0.72,0.8,0.66,"NDC");
   plotlabel8->SetTextColor(kBlack);
   plotlabel8->SetFillColor(kWhite);
   plotlabel8->SetBorderSize(0);
   plotlabel8->SetTextAlign(12);
   plotlabel8->SetTextSize(0.03);
   sprintf(temp, "#chi^{2}/DOF = %.3f", frame2->chiSquare());
   plotlabel8->AddText(temp);

//   plotlabel->Draw();
//   plotlabel2->Draw();
//   plotlabel3->Draw();
  plotlabel4->Draw();
  plotlabel5->Draw();
  plotlabel6->Draw();
  plotlabel7->Draw();
  plotlabel8->Draw();

  c2->SaveAs( cname + TString(".gif"));
//   c2->SaveAs( cname + TString(".eps"));
//   c2->SaveAs( cname + TString(".root"));
  canvasFile->WriteTObject(c2, c2->GetName(), "WriteDelete");

  canvasFile->Close();

  
  effTextFile.width(40);
  effTextFile << label;
  effTextFile.width(20);
  effTextFile  << setiosflags(ios::fixed) << setprecision(4) << left << ParEfficiency->getVal() ;
  effTextFile.width(20);
  effTextFile  << left << ParEfficiency->getErrorHi();
  effTextFile.width(20);
  effTextFile  << left << ParEfficiency->getErrorLo();
  effTextFile.width(14);
  effTextFile  << setiosflags(ios::fixed) << setprecision(2) << left << nSignalPass ;
  effTextFile.width(14);
  effTextFile << left << nSignalFail << endl;

} 
Beispiel #10
0
double final4_D0::doFit(bool usePixel, bool isMC)
{
  gROOT->SetBatch(kTRUE);
  gROOT->SetStyle("Plain");

  //setTDRStyle();

  RooRealVar x("","",1.7,2.05);
  x.SetTitle("M(K#pi) [GeV/c^{ 2}]");

  RooRealVar mean("mean", "mean", 1.86484,1.5, 2.2);
  //RooRealVar mean("mean", "mean", 1.865116);
  RooRealVar sigma("sigma", "sigma", 0.017, 0.0002, 0.02);
  //RooRealVar sigma("sigma", "sigma", 0.015332);
  RooGaussian gauss("gauss","gaussian PDF", x, mean, sigma);

  RooRealVar alpha("alpha", "alpha", -1.0, -10.0, 10.0);
  RooRealVar power("power", "power", 3.0, 0.0, 50.0);
  RooCBShape cball("cball", "crystal ball PDF", x, mean, sigma, alpha, power);

  RooRealVar dm0("dm0", "dm0", 0.13957);
  dm0.setConstant(kTRUE);  
  RooRealVar shape("shape","shape",0.,-100.,100.);
  RooRealVar dstp1("p1","p1",0.,-500.,500.);
  RooRealVar dstp2("p2","p2",0.,-500.,500.);

  shape.setRange(0.000001,10.0);//was 0.02
  shape.setVal(0.0017);
  dstp1.setVal(0.45);
  dstp2.setVal(13.0);

  RooDstD0BG bkg("bkg","bkg",x,dm0,shape,dstp1,dstp2);

  RooRealVar c0("c0","c0",10.0,-10.0,11.0);
  RooRealVar c1("c1","c1",10.0,-10.0,11.0);
  RooRealVar c2("c2","c2",10.0,-10.0,11.0);
  RooRealVar c3("c3","c3",10.0,-10.0,11.0);
  RooRealVar c4("c4","c4",10.0,-10.0,11.0);
  RooRealVar c5("c5","c5",10.0,-10.0,11.0);
  RooRealVar c6("c6","c6",10.0,-10.0,11.0);
  RooRealVar c7("c7","c7",10.0,-10.0,11.0);
  RooRealVar c8("c8","c8",10.0,-10.0,11.0);
  RooGenericPdf cutoff("cutoff","cutoff","(@0 > @1)*(@2*abs(@0-@1) + @3*pow(abs(@0-@1),2) + @4*pow(abs(@0-@1),3) + @5*pow(abs(@0-@1),4) + @6*pow(abs(@0-@1),5) + @7*pow(abs(@0-@1),6) + @8*pow(abs(@0-@1),7))",RooArgSet(x,dm0,c0,c1,c2,c3,c4,c5,c6));

  RooRealVar poly1("poly1","poly1",0.,-5000.0,5000.0);
  RooRealVar poly2("poly2","poly2",1.0,-5000.0,5000.0);
  RooRealVar poly3("poly3","poly3",1.0,-5000.0,5000.0);
  RooRealVar poly4("poly4","poly4",1.0,-5000.0,5000.0);

  RooPolynomial polybkg("polybkg","polybkg",x,RooArgSet(poly1));


  RooRealVar cheby0("cheby0","cheby0",1.0,-500.0,500.0);
  RooRealVar cheby1("cheby1","cheby1",1.0,-500.0,500.0);
  RooRealVar cheby2("cheby2","cheby2",1.0,-500.0,500.0);
  RooRealVar cheby3("cheby3","cheby3",1.0,-500.0,500.0);

  RooChebychev chebybkg("chebybkg","chebybkg",x,RooArgSet(cheby0,cheby1,cheby2,cheby3));

  RooRealVar mean2("mean2", "mean2", 0.14548,0.144, 0.147);
  RooRealVar sigma2("sigma2", "sigma2", 0.00065, 0.0002, 0.005);
  RooGaussian gauss2("gauss2","gaussian PDF 2", x, mean2, sigma2);

  RooRealVar S("S", "Signal Yield", 1100, 0, 300000);
  //RooRealVar S("S", "Signal Yield", 0, 0, 300000);
  RooRealVar SS("SS", "Signal Yield #2", 100, 0, 100000);
  RooRealVar S2("S2", "Signal2 Yield (MC only)", 0, 0, 200);
  RooRealVar B("B", "Background Yield", 4000, 0, 30000000);
  //RooRealVar B("B", "Background Yield", 0, 0, 30000000);

  //RooAddPdf sum("sum", "gaussian plus threshold PDF",RooArgList(gauss, bkg), RooArgList(S, B));
  RooAddPdf sum("sum", "gaussian plus linear PDF", RooArgList(gauss, polybkg), RooArgList(S,B));
  //RooAddPdf sum("sum", "background PDF",RooArgList(polybkg), RooArgList(B));
  //RooAddPdf sum("sum", "background PDF",RooArgList(chebybkg), RooArgList(B));
  //RooAddPdf sum("sum", "background PDF",RooArgList(cutoff), RooArgList(B));
  // RooAddPdf sum("sum", "gaussians plus threshold PDF",RooArgList(gauss, gauss2, bkg), RooArgList(S, SS, B));
  //RooAddPdf sum("sum", "crystal ball plus threshold PDF",RooArgList(cball, bkg), RooArgList(S, B));
  RooAddPdf sumMC("sumMC","double gaussian",RooArgList(gauss, gauss2), RooArgList(S, S2));

  fstream file;

  char filename[50];
  double cut=5.5;
  sprintf(filename,"D0Mass.dat");
  
  RooDataSet* data = RooDataSet::read(filename,RooArgList(x));
  RooFitResult* fit = 0;
  if (isMC == 0)
  {
    fit = sum.fitTo(*data,RooFit::Extended(),PrintLevel(1),Save(true),RooFit::NumCPU(8),RooFit::Strategy(2));
    file << "cut: " << cut << "GeV" << endl;
    file << "status: " << fit->status() << endl;
    file << "covQual: " << fit->covQual() << endl;
    file << "edm: " << fit->edm() <<  endl;
    file << "Yield: " <<  S.getVal() << " " << S.getError() << endl;
    file << "Bkg: " << B.getVal() << " " << B.getError() << endl; 
    file << "sigma: " << sigma.getVal() <<  " " << sigma.getError() << endl;
    file << "mean: " << mean.getVal() << " " << mean.getError() << endl;
    file << "shape: " << shape.getVal() << " " << shape.getError() << endl;
    file << "dstp1: " << dstp1.getVal() << " " << dstp1.getError() << endl;
    file << "dstp2: " << dstp2.getVal() << " " << dstp2.getError() << endl;
    file << endl;
  }
  else
  {
    fit = sumMC.fitTo(*data,RooFit::Extended(),PrintLevel(1),Save(true),RooFit::NumCPU(8),RooFit::Strategy(2),Range(0.142,0.15));
    file << "cut: " << cut << "GeV" << endl;
    file << "status: " << fit->status() << endl;
    file << "covQual: " << fit->covQual() << endl;
    file << "edm: " << fit->edm() <<  endl;
    file << "Yield: " <<  S.getVal() << " " << S.getError() << endl;
    file << "Yield2: " << S2.getVal() << " " << S2.getError() << endl; 
    file << "sigma: " << sigma.getVal() <<  " " << sigma.getError() << endl;
    file << "mean: " << mean.getVal() << " " << mean.getError() << endl;
    file << "sigma2: " << sigma2.getVal() << " " << sigma2.getError() << endl;
    file << "mean2: " << mean2.getVal() << " " << mean2.getError() << endl;
    file << endl; 
  }
  
  RooPlot* xFrame = x.frame(Bins(35));
  xFrame->SetTitle("D* #rightarrow D^{0}(K#pi)#pi");
  data->plotOn(xFrame);
  if(isMC == 0)
  {
    sum.plotOn(xFrame);
    sum.plotOn(xFrame,RooFit::Components(bkg),RooFit::LineStyle(kDashed));
  }
  else
  {
    sumMC.plotOn(xFrame, Range(0.139,0.159));
    //      sumMC.plotOn(xFrame,RooFit::Components(gauss2),RooFit::LineStyle(kDashed),Range(0.139,0.159));
  }
  data->plotOn(xFrame);
  file << xFrame->chiSquare() << endl;
  TCanvas c;
  TPaveText* ptext = 0;
  TPaveText* ptex = 0;
  
  if(usePixel == 0)
  {
    ptext = new TPaveText(0.47,0.33,0.9,0.43,"TRNDC");
    ptex = new TPaveText(0.47,0.18,0.9,0.28,"NDC"); 
  }
  else
  {
    if(isMC == 0)
    {
      ptext = new TPaveText(0.47,0.8,0.9,0.9,"TRNDC");
      ptex = new TPaveText(0.47,0.8,0.9,0.9,"NDC"); 
    }
    else
    {
      ptext = new TPaveText(0.47,0.78,0.9,0.88,"TRNDC");
      ptex = new TPaveText(0.47,0.63,0.9,0.73,"NDC"); 
    }
  }
  
  ptext->SetFillColor(0);
  ptext->SetTextSize(0.04);
  ptext->SetTextAlign(13);
  ptext->AddText("CMS Preliminary");
  //ptext->AddText("#sqrt{s} = 13 TeV, 40.0 pb^{-1}");
  ptext->AddText("#sqrt{s} = 13 TeV, Spring15 MinBias MC");
  xFrame->SetYTitle("Events / 10 MeV/c^{ 2}");
  xFrame->GetYaxis()->SetTitleOffset(1.3);
  xFrame->GetYaxis()->SetLabelSize(0.03);
  xFrame->GetXaxis()->SetLabelSize(0.03);
  
  ptex->SetFillColor(0);
  ptex->SetTextSize(0.033);
  ptex->SetTextAlign(13);
  char theyield[50];
  char themean[50];
  char thesigma[50];
  if(isMC == 0)
  {
    sprintf(theyield,"Yield = %u #pm %u",(unsigned)S.getVal(),(unsigned)S.getError());
    sprintf(themean,"Mean = (%.3f #pm %.3f) MeV/c^{2}",mean.getVal()*1000.0,mean.getError()*1000.0);
    sprintf(thesigma,"Sigma = (%.3f #pm %.3f) MeV/c^{2}",sigma.getVal()*1000.0,sigma.getError()*1000.0);
  }
  else
  {
    sprintf(theyield,"Yield = %u #pm %u",(unsigned)(S.getVal()+S2.getVal()),(unsigned)(sqrt(pow(S.getError(),2)+pow(S2.getError(),2))));
    sprintf(themean,"Mean = (%.3f #pm %.3f) MeV/c^{2}",mean.getVal()*1000.0,mean.getError()*1000.0);
    sprintf(thesigma,"Sigma = (%.3f #pm %.3f) MeV/c^{2}",sigma.getVal()*1000.0,sigma.getError()*1000.0);
  } 
  ptex->AddText(theyield);
  ptex->AddText(themean);
  ptex->AddText(thesigma);
  
  xFrame->Draw();
  ptext->Draw("same");
  ptex->Draw("same");
  
  c.SaveAs("D0Mass.png");
  c.SaveAs("D0Mass.pdf");

  S.Print();

  // compute integrals
  double sfactor;
  if(isMC)
    sfactor = 0.0;
  else
  {
    double sigbkg, bkg1, bkg2;
    double base = 0.145421;
    
    x.setRange("signal",base-0.0013,base+0.0013);
    x.setRange("background1",base-0.0051,base-0.0025);
    x.setRange("background2",base+0.0025,base+0.0051);    

    RooAbsReal* iSB = B.createIntegral(x,Range("signal"));
    RooAbsReal* iB1 = B.createIntegral(x,Range("background1"));
    RooAbsReal* iB2 = B.createIntegral(x,Range("background2"));

    sigbkg = iSB->getVal();
    bkg1 = iB1->getVal();
    bkg2 = iB2->getVal();
 
    sfactor = -1.0 * (sigbkg / (bkg1 + bkg2));
  }

  return sfactor;
}