Пример #1
0
testWrapper(){
	gSystem->Load("libTMVAWrapper.so");
	RooWorkspace w("w");
	w.factory("x[-5,5]");
	w.factory("alpha[-5,5]");
	x = w.var("x");
	alpha = w.var("alpha");
	//	vars = w.allVars();
	RooArgList vars;
	vars.add(*x);
	vars.add(*alpha);
	vars.Print();

	TMVAWrapper wrap("wrap","wrap", vars, "TMVARegression_alphavary.root_MLP.weights.xml");
	wrap.Print("v");
	cout << "wrap = " << wrap.getVal() <<endl;
	x->setVal(1);
	alpha->setVal(2.);
	cout << "wrap = " << wrap.getVal() <<endl;

//	w.import(wrap);
//	w.Print();
//	return;
	//	cout << "\n\nvars are: " << wrap.getListOfVars() << endl;
	frame = x->frame();
	wrap.plotOn(frame);
	frame->Draw();
}
Пример #2
0
void THSRooFit::SetDataWeight(){
  if(!fInWeights) return;
  if(fInWeights->GetSpeciesID(fWeightName)<0) return;
  RooArgList setWeights;
  RooRealVar wvar(fWeightName,fWeightName,0);
  setWeights.add(wvar);
  setWeights.Print();
  RooDataSet wData("weights","weights",setWeights) ;

  //Loop over the weights find the entry for the event ID
  for(Int_t ev=0;ev<fData->numEntries();ev++){
    const RooArgSet* vars=fData->get(ev);
    fInWeights->GetEntryBinarySearch((Long64_t)vars->getRealValue(fIDBranchName));
    // wvar.setVal(fInWeights->GetWeight(fWeightName));
    wvar.setVal(fInWeights->GetWeight(fWeightName));
    wData.add(setWeights);
  }
  wData.Print();
  ((RooDataSet*)fData)->merge(&wData);
  fData->Print();
  RooDataSet* tmpData=0;
  tmpData=new RooDataSet(TString("Weight_")+fWeightName+fData->GetName(),fData->GetTitle(),(RooDataSet*)fData,*fData->get(),0,fWeightName);
  fData->SetName("Empty");fData->reset();fData=0;
  fData=tmpData;
  fData->Print();
  if(ftoWS) fWS->import(*fData); //import if told to
  else if(!(fDataBins))fWS->import(*fData); //or no databins to confuse it 
}
int main(int argc, char* argv[]) {

     doofit::builder::EasyPdf *epdf = new doofit::builder::EasyPdf();

     

    epdf->Var("sig_yield");
    epdf->Var("sig_yield").setVal(153000);
    epdf->Var("sig_yield").setConstant(false);
    //decay time
    epdf->Var("obsTime");
    epdf->Var("obsTime").SetTitle("t_{#kern[-0.2]{B}_{#kern[-0.1]{ d}}^{#kern[-0.1]{ 0}}}");
    epdf->Var("obsTime").setUnit("ps");
    epdf->Var("obsTime").setRange(0.,16.);

    // tag, respectively the initial state of the produced B meson
    epdf->Cat("obsTag");
    epdf->Cat("obsTag").defineType("B_S",1);
    epdf->Cat("obsTag").defineType("Bbar_S",-1);

    //finalstate
    epdf->Cat("catFinalState");
    epdf->Cat("catFinalState").defineType("f",1);
    epdf->Cat("catFinalState").defineType("fbar",-1);

    epdf->Var("obsEtaOS");
    epdf->Var("obsEtaOS").setRange(0.0,0.5);


     std::vector<double> knots;
            knots.push_back(0.07);
            knots.push_back(0.10);
            knots.push_back(0.138);
            knots.push_back(0.16);
            knots.push_back(0.23);
            knots.push_back(0.28);
            knots.push_back(0.35);
            knots.push_back(0.42);
            knots.push_back(0.44);
            knots.push_back(0.48);
            knots.push_back(0.5);

            // empty arg list for coefficients
            RooArgList* list = new RooArgList();

            // create first coefficient
            RooRealVar* coeff_first = &(epdf->Var("parCSpline1"));
            coeff_first->setRange(0,10000);
            coeff_first->setVal(1);
            coeff_first->setConstant(false);
            list->add( *coeff_first );

            for (unsigned int i=1; i <= knots.size(); ++i){
               std::string number = boost::lexical_cast<std::string>(i);
               RooRealVar* coeff = &(epdf->Var("parCSpline"+number));
               coeff->setRange(0,10000);
               coeff->setVal(1);
               coeff->setConstant(false);
               list->add( *coeff );
            }

            // create last coefficient
            RooRealVar* coeff_last = &(epdf->Var("parCSpline"+boost::lexical_cast<std::string>(knots.size())));
            coeff_last->setRange(0,10000);
            coeff_last->setVal(1);
            coeff_last->setConstant(false);
            list->add( *coeff_last );



            list->Print();

            doofit::roofit::pdfs::DooCubicSplinePdf splinePdf("splinePdf",epdf->Var("obsEtaOS"),knots,*list,0,0.5);
            //doofit::roofit::pdfs::DooCubicSplinePdf* splinePdf = new doofit::roofit::pdfs::DooCubicSplinePdf("splinePdf", epdf->Var("obsEtaOS"), knots, *list,0,0.5);



     //Koeffizienten
            DecRateCoeff *coeff_c = new DecRateCoeff("coef_cos","coef_cos",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("C_f"),epdf->Var("C_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Var("obsEtaOS"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
            DecRateCoeff *coeff_s = new DecRateCoeff("coef_sin","coef_sin",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("S_f"),epdf->Var("S_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Var("obsEtaOS"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
            DecRateCoeff *coeff_sh = new DecRateCoeff("coef_sinh","coef_sinh",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f1_f"),epdf->Var("f1_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Var("obsEtaOS"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
            DecRateCoeff *coeff_ch = new DecRateCoeff("coef_cosh","coef_cosh",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f0_f"),epdf->Var("f0_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Var("obsEtaOS"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));

            epdf->AddRealToStore(coeff_ch);
            epdf->AddRealToStore(coeff_sh);
            epdf->AddRealToStore(coeff_c);
            epdf->AddRealToStore(coeff_s);


    ///////////////////Generiere PDF's/////////////////////
    //Zeit
    epdf->GaussModel("resTimeGauss",epdf->Var("obsTime"),epdf->Var("allTimeResMean"),epdf->Var("allTimeReso"));
    epdf->BDecay("pdfSigTime",epdf->Var("obsTime"),epdf->Var("tau"),epdf->Var("dgamma"),epdf->Real("coef_cosh"),epdf->Real("coef_sinh"),epdf->Real("coef_cos"),epdf->Real("coef_sin"),epdf->Var("deltaM"),epdf->Model("resTimeGauss"));


     //Zusammenfassen der Parameter in einem RooArgSet
     RooArgSet Observables;
     Observables.add(RooArgSet( epdf->Var("obsTime"),epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("obsEtaOS")));


     epdf->Extend("pdfExtend", epdf->Pdf("pdfSigTime"),epdf->Real("sig_yield"));



     //Multipliziere Signal und Untergrund PDF mit ihrer jeweiligen Zerfalls PDF//
     //Untergrund * Zerfall
     /*epdf->Product("pdf_bkg", RooArgSet(epdf->Pdf("pdf_bkg_mass_expo"), epdf->Pdf("pdf_bkg_mass_time")));
     //Signal * Zerfall
     epdf->Product("pdf_sig", RooArgSet(epdf->Pdf("pdf_sig_mass_gauss"),epdf->Pdf("pdfSigTime")));
    //Addiere PDF's
     epdf->Add("pdf_total", RooArgSet(epdf->Pdf("pdf_sig_mass_gauss*pdf_sig_time_decay"), epdf->Pdf("pdf_bkg_mass*pdf_bkg_time_decay")), RooArgSet(epdf->Var("bkg_Yield"),epdf->Var("sig_Yield")));*/





     RooWorkspace ws;
                 ws.import(epdf->Pdf("pdfExtend"));
                 ws.defineSet("Observables",Observables, true);

                 ws.Print();

                 doofit::config::CommonConfig cfg_com("common");
                 cfg_com.InitializeOptions(argc, argv);
                 doofit::toy::ToyFactoryStdConfig cfg_tfac("toyfac");
                 cfg_tfac.InitializeOptions(cfg_com);
                 doofit::toy::ToyStudyStdConfig cfg_tstudy("toystudy");
                 cfg_tstudy.InitializeOptions(cfg_tfac);

                 // set a previously defined workspace to get PDF from (not mandatory, but convenient)
                 cfg_tfac.set_workspace(&ws);

                 // Check for a set --help flag and if so, print help and exit gracefully
                 // (recommended).
                 cfg_com.CheckHelpFlagAndPrintHelp();

                 // More custom code, e.g. to set options internally.
                 // Not required as configuration via command line/config file is enough.
                 cfg_com.PrintAll();

                 // Print overview of all options (optional)
                 // cfg_com.PrintAll();

                 // Initialize the toy factory module with the config objects and start
                 // generating toy samples.
                 doofit::toy::ToyFactoryStd tfac(cfg_com, cfg_tfac);
                 doofit::toy::ToyStudyStd tstudy(cfg_com, cfg_tstudy);




          RooDataSet* data = tfac.Generate();
          data->Print();
          epdf->Pdf("pdfExtend").getParameters(data)->readFromFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter_spline.txt");
          epdf->Pdf("pdfExtend").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter_spline.txt.new");

          //epdf->Pdf("pdfExtend").fitTo(*data);
          //epdf->Pdf("pdfExtend").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-fit-result.txt");
		      RooFitResult* fit_result = epdf->Pdf("pdfExtend").fitTo(*data, RooFit::Save(true));
       	  tstudy.StoreFitResult(fit_result);

          /*using namespace doofit::plotting;

          PlotConfig cfg_plot("cfg_plot");
          cfg_plot.InitializeOptions();
          cfg_plot.set_plot_directory("/net/lhcb-tank/home/chasenberg/Ergebnis/dootoycp_spline-lhcb/time/");
          // plot PDF and directly specify components
          Plot myplot(cfg_plot, epdf->Var("obsTime"), *data, RooArgList(epdf->Pdf("pdfExtend")));
          myplot.PlotItLogNoLogY();

          PlotConfig cfg_plotEta("cfg_plotEta");
          cfg_plotEta.InitializeOptions();
          cfg_plotEta.set_plot_directory("/net/lhcb-tank/home/chasenberg/Ergebnis/dootoycp_spline-lhcb/eta/");
          // plot PDF and directly specify components
          Plot myplotEta(cfg_plotEta, epdf->Var("obsEtaOS"), *data, RooArgList(splinePdf));
          myplotEta.PlotIt();*/

 }
Пример #4
0
///
/// Find the global minimum in a more thorough way.
/// First fit with external start parameters, then
/// for each parameter that starts with "d" or "r" (typically angles and ratios):
///   - at upper scan range, rest at start parameters
///   - at lower scan range, rest at start parameters
/// This amounts to a maximum of 1+2^n fits, where n is the number
/// of parameters to be varied.
///
/// \param w Workspace holding the pdf.
/// \param name Name of the pdf without leading "pdf_".
/// \param forceVariables Apply the force method for these variables only. Format
/// "var1,var2,var3," (list must end with comma). Default is to apply for all angles,
/// all ratios except rD_k3pi and rD_kpi, and the k3pi coherence factor.
///
RooFitResult* Utils::fitToMinForce(RooWorkspace *w, TString name, TString forceVariables)
{
	bool debug = true;

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

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

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

	//////////

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

	//////////

	int nErrors = 0;

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

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

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

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

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

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

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

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

	delete startPars;
	return r;
}
int main(int argc, char* argv[]) {

 doofit::builder::EasyPdf *epdf = new doofit::builder::EasyPdf();

    

 epdf->Var("sig_yield");
 epdf->Var("sig_yield").setVal(153000);
 epdf->Var("sig_yield").setConstant(false);
 //decay time
 epdf->Var("obsTime");
 epdf->Var("obsTime").SetTitle("t_{#kern[-0.2]{B}_{#kern[-0.1]{ d}}^{#kern[-0.1]{ 0}}}");
 epdf->Var("obsTime").setUnit("ps");
 epdf->Var("obsTime").setRange(0.,16.);

 // tag, respectively the initial state of the produced B meson
 epdf->Cat("obsTag");
 epdf->Cat("obsTag").defineType("B_S",1);
 epdf->Cat("obsTag").defineType("Bbar_S",-1);

  //finalstate
  epdf->Cat("catFinalState");
  epdf->Cat("catFinalState").defineType("f",1);
  epdf->Cat("catFinalState").defineType("fbar",-1);

  epdf->Var("obsEtaOS");
  epdf->Var("obsEtaOS").setRange(0.0,0.5);


  std::vector<double> knots;
    knots.push_back(0.07);
    knots.push_back(0.10);
    knots.push_back(0.138);
    knots.push_back(0.16);
    knots.push_back(0.23);
    knots.push_back(0.28);
    knots.push_back(0.35);
    knots.push_back(0.42);
    knots.push_back(0.44);
    knots.push_back(0.48);
    knots.push_back(0.5);

  // empty arg list for coefficients
  RooArgList* list = new RooArgList();

  // create first coefficient
  RooRealVar* coeff_first = &(epdf->Var("parCSpline1"));
  coeff_first->setRange(0,10000);
  coeff_first->setVal(1);
  coeff_first->setConstant(false);
  list->add( *coeff_first );

  for (unsigned int i=1; i <= knots.size(); ++i){
    std::string number = boost::lexical_cast<std::string>(i);
    RooRealVar* coeff = &(epdf->Var("parCSpline"+number));
    coeff->setRange(0,10000);
    coeff->setVal(1);
    coeff->setConstant(false);
    list->add( *coeff );
    }
  
  // create last coefficient
  RooRealVar* coeff_last = &(epdf->Var("parCSpline"+boost::lexical_cast<std::string>(knots.size())));
  coeff_last->setRange(0,10000);
  coeff_last->setVal(1);
  coeff_last->setConstant(false);
  list->add( *coeff_last );
  list->Print();
  // define Eta PDF
  doofit::roofit::pdfs::DooCubicSplinePdf splinePdf("splinePdf",epdf->Var("obsEtaOS"),knots,*list,0,0.5);
  
  //Berechne die Tagging Assymetrie
  epdf->Var("p0");
  epdf->Var("p0").setVal(0.369);
  epdf->Var("p0").setConstant(true);

  epdf->Var("p1");
  epdf->Var("p1").setVal(0.952);
  epdf->Var("p1").setConstant(true);

  epdf->Var("delta_p0");
  epdf->Var("delta_p0").setVal(0.019);
  epdf->Var("delta_p0").setConstant(true);

  epdf->Var("delta_p1");
  epdf->Var("delta_p1").setVal(-0.012);
  epdf->Var("delta_p1").setConstant(true);

  epdf->Var("etamean");
  epdf->Var("etamean").setVal(0.365);
  epdf->Var("etamean").setConstant(true);

  epdf->Formula("omega","@0 +@1/2 +(@2+@3/2)*(@4-@5)", RooArgList(epdf->Var("p0"),epdf->Var("delta_p0"),epdf->Var("p1"),epdf->Var("delta_p1"),epdf->Var("obsEtaOS"),epdf->Var("etamean")));
  epdf->Formula("omegabar","@0 -@1/2 +(@2-@3/2)*(@4-@5)", RooArgList(epdf->Var("p0"),epdf->Var("delta_p0"),epdf->Var("p1"),epdf->Var("delta_p1"),epdf->Var("obsEtaOS"),epdf->Var("etamean")));
      


  //Koeffizienten
  DecRateCoeff *coeff_c = new DecRateCoeff("coef_cos","coef_cos",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("C_f"),epdf->Var("C_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_s = new DecRateCoeff("coef_sin","coef_sin",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("S_f"),epdf->Var("S_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_sh = new DecRateCoeff("coef_sinh","coef_sinh",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f1_f"),epdf->Var("f1_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_ch = new DecRateCoeff("coef_cosh","coef_cosh",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f0_f"),epdf->Var("f0_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prod"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));

  epdf->AddRealToStore(coeff_ch);
  epdf->AddRealToStore(coeff_sh);
  epdf->AddRealToStore(coeff_c);
  epdf->AddRealToStore(coeff_s);

  ///////////////////Generiere PDF's/////////////////////
  //Zeit
  epdf->GaussModel("resTimeGauss",epdf->Var("obsTime"),epdf->Var("allTimeResMean"),epdf->Var("allTimeReso"));
  epdf->BDecay("pdfSigTime",epdf->Var("obsTime"),epdf->Var("tau"),epdf->Var("dgamma"),epdf->Real("coef_cosh"),epdf->Real("coef_sinh"),epdf->Real("coef_cos"),epdf->Real("coef_sin"),epdf->Var("deltaM"),epdf->Model("resTimeGauss"));

  //Zusammenfassen der Parameter in einem RooArgSet
  RooArgSet Observables;
  Observables.add(RooArgSet( epdf->Var("obsTime"),epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("obsEtaOS")));

  epdf->Extend("pdfExtend", epdf->Pdf("pdfSigTime"),epdf->Real("sig_yield"));

  RooWorkspace ws;
    ws.import(epdf->Pdf("pdfExtend"));
    ws.defineSet("Observables",Observables, true);
    ws.Print();

    doofit::config::CommonConfig cfg_com("common");
    cfg_com.InitializeOptions(argc, argv);
    doofit::toy::ToyFactoryStdConfig cfg_tfac("toyfac");
    cfg_tfac.InitializeOptions(cfg_com);
    doofit::toy::ToyStudyStdConfig cfg_tstudy("toystudy");
    cfg_tstudy.InitializeOptions(cfg_tfac);

    // set a previously defined workspace to get PDF from (not mandatory, but convenient)
    cfg_tfac.set_workspace(&ws);
    cfg_com.CheckHelpFlagAndPrintHelp();

    // Initialize the toy factory module with the config objects and start
    // generating toy samples.
    doofit::toy::ToyFactoryStd tfac(cfg_com, cfg_tfac);
    doofit::toy::ToyStudyStd tstudy(cfg_com, cfg_tstudy);

  //Generate data
  RooDataSet* data = tfac.Generate();
  data->Print();
  epdf->Pdf("pdfExtend").getParameters(data)->readFromFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter.txt");
  epdf->Pdf("pdfExtend").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter.txt.new");


  //FIT-PDF-Koeffizienten
  epdf->Var("asym_prodFit");
  epdf->Var("asym_prodFit").setVal(-0.0108);
  epdf->Var("asym_prodFit").setConstant(false);

  DecRateCoeff *coeff_cFit = new DecRateCoeff("coef_cosFit","coef_cosFit",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("C_f"),epdf->Var("C_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prodFit"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_sFit = new DecRateCoeff("coef_sinFit","coef_sinFit",DecRateCoeff::CPOdd,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("S_f"),epdf->Var("S_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prodFit"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_shFit = new DecRateCoeff("coef_sinhFit","coef_sinhFit",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f1_f"),epdf->Var("f1_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prodFit"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));
  DecRateCoeff *coeff_chFit = new DecRateCoeff("coef_coshFit","coef_coshFit",DecRateCoeff::CPEven,epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("f0_f"),epdf->Var("f0_fbar"),epdf->Var("obsEtaOS"),splinePdf,epdf->Var("tageff"),epdf->Real("omega"),epdf->Real("omegabar"),epdf->Var("asym_prodFit"),epdf->Var("asym_det"),epdf->Var("asym_tageff"));

  epdf->AddRealToStore(coeff_chFit);
  epdf->AddRealToStore(coeff_shFit);
  epdf->AddRealToStore(coeff_cFit);
  epdf->AddRealToStore(coeff_sFit);

  ///////////////////Generiere PDF's/////////////////////
  //Zeit
  
  epdf->BDecay("pdfSigTimeFit",epdf->Var("obsTime"),epdf->Var("tau"),epdf->Var("dgamma"),epdf->Real("coef_coshFit"),epdf->Real("coef_sinhFit"),epdf->Real("coef_cosFit"),epdf->Real("coef_sinFit"),epdf->Var("deltaM"),epdf->Model("resTimeGauss"));

  //Zusammenfassen der Parameter in einem RooArgSet
  RooArgSet ObservablesFit;
  ObservablesFit.add(RooArgSet( epdf->Var("obsTime"),epdf->Cat("catFinalState"),epdf->Cat("obsTag"),epdf->Var("obsEtaOS")));

  epdf->Extend("pdfExtendFit", epdf->Pdf("pdfSigTimeFit"),epdf->Real("sig_yield"));
  
  
  RooFitResult* fit_result = epdf->Pdf("pdfExtendFit").fitTo(*data, RooFit::Save(true));
  tstudy.StoreFitResult(fit_result);
  //epdf->Pdf("pdfExtendFit").getParameters(data)->readFromFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter.txt");
  //epdf->Pdf("pdfExtendFit").getParameters(data)->writeToFile("/home/chasenberg/Repository/bachelor-template/ToyStudy/dootoycp-parameter.txt.new");

  //Plotten auf lhcb
  /*using namespace doofit::plotting;

  PlotConfig cfg_plot("cfg_plot");
  cfg_plot.InitializeOptions();
  cfg_plot.set_plot_directory("/net/storage03/data/users/chasenberg/ergebnis/dootoycp_float-lhcb/dgamma/time/");
  // plot PDF and directly specify components
  Plot myplot(cfg_plot, epdf->Var("obsTime"), *data, RooArgList(epdf->Pdf("pdfExtend")));
  myplot.PlotItLogNoLogY();

  PlotConfig cfg_plotEta("cfg_plotEta");
  cfg_plotEta.InitializeOptions();
  cfg_plotEta.set_plot_directory("/net/storage03/data/users/chasenberg/ergebnis/dootoycp_float-lhcb/dgamma/eta/");
  // plot PDF and directly specify components
  Plot myplotEta(cfg_plotEta, epdf->Var("obsEtaOS"), *data, RooArgList(splinePdf));
  myplotEta.PlotIt();*/

 }
Пример #6
0
void toyMC(
	   int collId = kAADATA,
	   float ptLow=0, float ptHigh=5,
	   float yLow=0, float yHigh=2.4,
	   int cLow=0, int cHigh=200,
	   float muPtCut=4.0,
	   int inputOption=kChPol4, //kChPol3,
	   int nGen = 10000,
	   int useCentIntBkgShape = 1,
     int nToys = 1000
	    ) 
{
  using namespace RooFit;
  RooRandom::randomGenerator()->SetSeed(111);
  gStyle->SetEndErrorSize(0);
  float Val_2S_1S_nom = 0;
  float Val_2S_1S_alt = 0;
  float Dev_2S_1S = 0;
  

  TString fcoll;
  TString finput;
  if(collId == kAADATA) fcoll = "AA";
  else if(collId == kPPDATA) fcoll = "PP";
  if(inputOption == 3) finput = "4th poly";
  else if(inputOption == 4) finput = "Nominal+Exp";
  
  TFile *wf = new TFile(Form("%s_fit_pt%.1f-%.1f_rap%.1f-%.1f_cent%d-%d_Gen%d_input%d_useCentBkg%d_nToys%d.root",fcoll.Data(),ptLow,ptHigh,yLow,yHigh,cLow,cHigh,nGen,inputOption,useCentIntBkgShape,nToys),"recreate");
  
  TH1D *h1 = new TH1D("h1",Form("SR Nominal, %d toys, %d events, cent %d-%d;2S/1S nom;Counts",nToys,nGen,cLow,cHigh),100,0,1);
  TH1D *h2 = new TH1D("h2",Form("SR %s, %d toys, %d events, cent %d-%d;2S/1S nom;Counts",finput.Data(),nToys,nGen,cLow,cHigh),100,0,1);
  TH1D *h3 = new TH1D("h3","Deviation;2S/1S dev;Counts",1000,0,100);

  //----****************--------for loop -----*******************-----------------
  //----****************--------for loop -----*******************-----------------
  //----****************--------for loop -----*******************-----------------
  //----****************--------for loop -----*******************-----------------
  //----****************--------for loop -----*******************-----------------
  
  for(int i=0;i<nToys;i++){
  
  float massLow = 8. ;
  float massHigh = 14.;
  int   nMassBin  = (massHigh-massLow)*10;
  
  RooWorkspace *ws = new RooWorkspace("ws");
  RooWorkspace *wsinp = new RooWorkspace("wsinp");

  RooRealVar mass("mass","mass", massLow, massHigh);
  ws->import(mass);
  wsinp->import(mass);
  mass.Print();
  

  RooRealVar mRatio21("mRatio21","mRatio21",pdgMass.Y2S / pdgMass.Y1S );
  RooRealVar mRatio31("mRatio31","mRatio31",pdgMass.Y3S / pdgMass.Y1S );
  RooRealVar mean1s("m_{#Upsilon(1S)}","mean of the signal gaussian mass PDF",pdgMass.Y1S, pdgMass.Y1S -0.1, pdgMass.Y1S + 0.1 ) ;
  
  PSet3SingleCB InitialSetUpsilons = getUpsilonPsets( collId, ptLow, ptHigh, yLow, yHigh, cLow, cHigh, muPtCut) ; 
  RooRealVar sigma1s_1("sigma1s_1","width/sigma of the signal gaussian mass PDF",0.05, 0.05, 0.14);
  RooRealVar sigma2s_1("sigma2s_1","width/sigma of the signal gaussian mass PDF",0.05, 0.05, 0.14);
  RooRealVar sigma1s_2("sigma1s_2","width/sigma of the signal gaussian mass PDF",0.05, 0.05, 0.14);
  RooRealVar sigma2s_2("sigma2s_2","width/sigma of the signal gaussian mass PDF",0.05, 0.05, 0.14);

  RooRealVar alpha1s_1("alpha1s_1","tail shift", 5. , 1.0, 9.8);
  RooRealVar alpha2s_1("alpha2s_1","tail shift", 5. , 1.15, 9.2);
  RooRealVar alpha1s_2("alpha1s_2","tail shift", 5. , 1.0, 9.2);
  RooRealVar alpha2s_2("alpha2s_2","tail shift", 2.5, 1.10, 10.);

  RooRealVar n1s_1("n1s_1","power order", 5. , 1.4, 10.);
  RooRealVar n2s_1("n2s_1","power order", 6. , 1.1, 9.5);
  RooRealVar n1s_2("n1s_2","power order", 5. , 1.4, 10.);
  RooRealVar n2s_2("n2s_2","power order", 6. , 1.1, 9.5);
    
  RooRealVar *f1S = new RooRealVar("f1S","1S CB fraction", InitialSetUpsilons.MCf, InitialSetUpsilons.MCf*0.9, InitialSetUpsilons.MCf*1.1);
  f1S->setVal(InitialSetUpsilons.MCf);  f1S->setConstant();
  RooRealVar X1S("X1S","sigma fraction 1S 2nd CB", InitialSetUpsilons.MCX, InitialSetUpsilons.MCX*0.9, InitialSetUpsilons.MCX*1.1);
  
  // Fix the parameters 
  n1s_1.setVal(InitialSetUpsilons.MCN);  n1s_1.setConstant();  
  n1s_2.setVal(InitialSetUpsilons.MCN);  n1s_2.setConstant();  
  n2s_1.setVal(InitialSetUpsilons.MCN);  n2s_1.setConstant();  
  n2s_2.setVal(InitialSetUpsilons.MCN);  n2s_2.setConstant(); 
  alpha1s_1.setVal(InitialSetUpsilons.MCAlpha);  alpha1s_1.setConstant(); 
  alpha1s_2.setVal(InitialSetUpsilons.MCAlpha);  alpha1s_2.setConstant();
  alpha2s_1.setVal(InitialSetUpsilons.MCAlpha);  alpha2s_1.setConstant();
  alpha2s_2.setVal(InitialSetUpsilons.MCAlpha);  alpha2s_2.setConstant();  
  sigma1s_1.setVal(InitialSetUpsilons.MCSigma1S);  sigma1s_1.setConstant();  
  sigma1s_2.setVal(InitialSetUpsilons.MCSigma1S);  sigma1s_2.setConstant();  
  sigma2s_1.setVal(InitialSetUpsilons.MCSigma1S * InitialSetUpsilons.MCX );  sigma2s_1.setConstant();  
  sigma2s_2.setVal(InitialSetUpsilons.MCSigma1S * InitialSetUpsilons.MCX );  sigma2s_2.setConstant();  
  mean1s.setVal(InitialSetUpsilons.bkg_mass_res); mean1s.setConstant();
  
  RooFormulaVar mean2s("mean2s","m_{#Upsilon(1S)}*mRatio21", RooArgSet(mean1s,mRatio21) );
  RooFormulaVar mean3s("mean3s","m_{#Upsilon(1S)}*mRatio31", RooArgSet(mean1s,mRatio31) );
  
  RooCBShape* cb1s_1 = new RooCBShape("cball1s_1", "cystal Ball", mass, mean1s, sigma1s_1, alpha1s_1, n1s_1);
  RooCBShape* cb2s_1 = new RooCBShape("cball2s_1", "cystal Ball", mass, mean2s, sigma2s_1, alpha2s_1, n2s_1);
  
  RooCBShape* cb1s_2 = new RooCBShape("cball1s_2", "cystal Ball", mass, mean1s, sigma1s_2, alpha1s_2, n1s_2);
  RooCBShape* cb2s_2 = new RooCBShape("cball2s_2", "cystal Ball", mass, mean2s, sigma2s_2, alpha2s_2, n2s_2);
 
  RooAddPdf*  cb1s = new RooAddPdf();
  RooAddPdf*  cb2s = new RooAddPdf();
  cb1s = new RooAddPdf("cb1s","Signal 1S",RooArgList(*cb1s_1,*cb1s_2), RooArgList(*f1S) );
  cb2s = new RooAddPdf("cb2s","Signal 2S",RooArgList(*cb2s_1,*cb2s_2), RooArgList(*f1S) );


  // Input model 
  PSet3SingleCB bkgParm = getUpsilonPsets( collId, ptLow, ptHigh, yLow, yHigh, cLow, cHigh, muPtCut) ; 
  PSet3SingleCB bkgParmCentInt;
  if ( !( (cLow==0) && (cHigh==200) ) && (collId==kAADATA)   ) {
    bkgParmCentInt      = getUpsilonPsets( collId, ptLow, ptHigh, yLow, yHigh,    0,   200, muPtCut) ; 
    cout << " ok done " << endl;
  }

  // if ( inputOption == kErrExp ) 
  RooRealVar err_mu1("#mu1","err_mu1",  bkgParm.bkg_mu1 ) ;
  RooRealVar err_sigma1("#sigma1","err_sigma1", bkgParm.bkg_sigma1);
  RooRealVar m_decay1("#lambda1","m_decay1", bkgParm.bkg_lambda1);
  RooRealVar err_mu2("#mu2","err_mu2",  bkgParm.bkg_mu2 ) ;
  RooRealVar err_sigma2("#sigma2","err_sigma2", bkgParm.bkg_sigma2);
  RooRealVar m_decay2("#lambda2","m_decay2", bkgParm.bkg_lambda2);
  
  
  float the_ch3_k1 = bkgParm.ch3_k1 ;   float the_ch3_k2 = bkgParm.ch3_k2 ;  float the_ch3_k3 = bkgParm.ch3_k3 ;
  float the_ch4_k1 = bkgParm.ch4_k1 ;   float the_ch4_k2 = bkgParm.ch4_k2 ;  float the_ch4_k3 = bkgParm.ch4_k3 ; float the_ch4_k4 = bkgParm.ch4_k4 ;
  float the_bkg4_mu = bkgParm.bkg4_mu ;           float the_bkg4_sigma = bkgParm.bkg4_sigma; 
  float the_bkg4_lambda = bkgParm.bkg4_lambda ;   float the_bkg4_lambda2 = bkgParm.bkg4_lambda2 ;
  if ( !( (cLow==0) && (cHigh==200) ) && (collId==kAADATA) && useCentIntBkgShape  ) {
    the_ch3_k1 = bkgParmCentInt.ch3_k1 ;    the_ch3_k2 = bkgParmCentInt.ch3_k2 ;   the_ch3_k3 = bkgParmCentInt.ch3_k3 ;
    the_ch4_k1 = bkgParmCentInt.ch4_k1 ;    the_ch4_k2 = bkgParmCentInt.ch4_k2 ;   the_ch4_k3 = bkgParmCentInt.ch4_k3 ; the_ch4_k4 = bkgParmCentInt.ch4_k4 ;
    the_bkg4_mu = bkgParmCentInt.bkg4_mu ;            bkgParmCentInt.bkg4_sigma =bkgParmCentInt.bkg4_sigma;
    the_bkg4_lambda = bkgParmCentInt.bkg4_lambda ;    the_bkg4_lambda2 = bkgParmCentInt.bkg4_lambda2 ;
  }
  // if ( inputOption == kChPol3 ) 
  RooRealVar ch3_k1("pol3_k1","pol3_k1", the_ch3_k1 ) ;
  RooRealVar ch3_k2("pol3_k2","pol3_k2", the_ch3_k2 ) ;
  RooRealVar ch3_k3("pol3_k3","pol3_k3", the_ch3_k3 ) ;
  // if ( inputOption == kChPol4 ) 
  RooRealVar ch4_k1("pol4_k1","pol4_k1", the_ch4_k1 , the_ch4_k1*0.3, the_ch4_k1*1.6) ;
  RooRealVar ch4_k2("pol4_k2","pol4_k2", the_ch4_k2 , the_ch4_k2*0.3, the_ch4_k2*1.6) ;
  RooRealVar ch4_k3("pol4_k3","pol4_k3", the_ch4_k3 , the_ch4_k3*0.3, the_ch4_k3*1.6) ;
  RooRealVar ch4_k4("pol4_k4","pol4_k4", the_ch4_k4 , the_ch4_k4*0.3, the_ch4_k4*1.6) ;


  // if (inputOption == kErrExpExp ) 
  RooRealVar err4_mu("err4_mu","err4_mu",  the_bkg4_mu , the_bkg4_mu*0.4,the_bkg4_mu*1.4) ;
  RooRealVar err4_sigma("err4_sigma","err4_sigma", the_bkg4_sigma, the_bkg4_sigma*0.4, the_bkg4_sigma*1.4);
  RooRealVar m4_decay("err4_lambda","m4_decay", the_bkg4_lambda, the_bkg4_lambda*0.4, the_bkg4_lambda*1.4);
  RooRealVar m4_decay2("err4_lambda2","m4_decay2", the_bkg4_lambda2, the_bkg4_lambda2*0.4, the_bkg4_lambda2*1.4);

  RooGenericPdf *bkgErrExp1;
  RooGenericPdf *bkgErrExp2;

  RooGenericPdf *bkg4ErrExp ; // kErrExpExp
  RooGenericPdf *bkg4Exp = new RooGenericPdf("bkg4Exp","bkg4Exp","TMath::Exp(-@0/@1)",RooArgList(mass,m4_decay2));


 
 if ( ptLow == 0)  { 
   bkg4ErrExp = new RooGenericPdf("bkg4ErrExp","bkg4ErrExp","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err4_mu,err4_sigma,m4_decay));
   bkgErrExp1 = new RooGenericPdf("bkgErrExp1","Background1","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err_mu1,err_sigma1,m_decay1));
   bkgErrExp2 = new RooGenericPdf("bkgErrExp2","Background2","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err_mu2,err_sigma2,m_decay2));
 }
  else  { // if ptLow >= 5 
    bkg4ErrExp = new RooGenericPdf("bkg4ErrExp","bkg4ErrExp", "TMath::Exp(-@0/@1)",RooArgList(mass,m4_decay));
    bkgErrExp1 = new RooGenericPdf("bkgErrExp1","Background1","TMath::Exp(-@0/@1)",RooArgList(mass,m_decay1));
    bkgErrExp2 = new RooGenericPdf("bkgErrExp2","Background2","TMath::Exp(-@0/@1)",RooArgList(mass,m_decay2));
  }




  RooRealVar* rBkg2nd = new RooRealVar("rBkg2over1","rBkg2over1", bkgParm.rBkg42over1); // bkgParm.rBkgErr2over1
  RooAddPdf* bkgDblErr = new RooAddPdf("bkgDblErrExp","Bkg Only",RooArgList(*bkgErrExp2, *bkgErrExp1),RooArgList(*rBkg2nd));   // if ( inputOption == kErrExp )
  RooAddPdf* bkgComp4 = new RooAddPdf("bkgComp4","bkgComp4",RooArgList(*bkg4Exp, *bkg4ErrExp),RooArgList(*rBkg2nd));   // if ( inputOption == kErrExp )

  RooChebychev * bkgChPol3 = new RooChebychev("cPolBkg","Background1",mass,RooArgSet(ch3_k1,ch3_k2,ch3_k3));  // if ( inputOption == kChPol3 )
  RooChebychev * bkgChPol4 = new RooChebychev("cPol4Bkg","Background4",mass,RooArgSet(ch4_k1,ch4_k2,ch4_k3,ch4_k4));  // if ( inputOption == kChPol3 )

  float r1S_overTot = bkgParm.nSignal1s / ( bkgParm.nSignal1s + bkgParm.nSignal2s + bkgParm.nBkg ) ; // Numbers obtained from the real data
  float r2S_overTot = bkgParm.nSignal2s / ( bkgParm.nSignal1s + bkgParm.nSignal2s + bkgParm.nBkg ) ; 
  float rBkg_overTot = bkgParm.nBkg / ( bkgParm.nSignal1s + bkgParm.nSignal2s + bkgParm.nBkg ) ; 
  
  RooRealVar *nSig1sInp  = new RooRealVar("nSig1sInp","nSig1sInp", nGen * r1S_overTot,  0,   nGen);
  RooRealVar *nSig2sInp  = new RooRealVar("nSig2sInp","nSig2sInp", nGen * r2S_overTot, 0,   nGen);
  RooRealVar *nBkgInp  = new RooRealVar("nBkgInp","n_bkgInp",      nGen * rBkg_overTot,  0,   nGen);
  

  //----------------------------------------------------------------------------------------
  //Generating function from nominal fit
  
  RooRealVar err_mu_gen("err_mu_gen","err_mu_gen",  bkgParm.bkg_mu_res) ;
  RooRealVar err_sigma_gen("err_sigma_gen","err_sigma_gen", bkgParm.bkg_sigma_res);
  RooRealVar m_decay_gen("err_lambda_gen","m_decay_gen", bkgParm.bkg_lambda_res);

  err_mu_gen.setVal(bkgParm.bkg_mu_res); err_mu_gen.setConstant();
  err_sigma_gen.setVal(bkgParm.bkg_sigma_res); err_sigma_gen.setConstant();
  m_decay_gen.setVal(bkgParm.bkg_lambda_res); m_decay_gen.setConstant();
  
  RooGenericPdf* bkgInp_gen;
  RooGenericPdf *bkgInp_in;
  if ( ptLow == 0)  { 
    bkgInp_in = new RooGenericPdf("bkgInp_gen","Background Gen","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err_mu_gen,err_sigma_gen,m_decay_gen));
  }
  else {
    bkgInp_in = new RooGenericPdf("bkgInp_gen","Background Gen","TMath::Exp(-@0/@1)",RooArgList(mass,m_decay_gen));
  }
  
  bkgInp_gen = bkgInp_in;
  
  
  RooAddPdf* modelInput_gen; 
  modelInput_gen = new RooAddPdf("modelInput_gen","1S+2S + Bkg",RooArgList(*cb1s, *cb2s, *bkgInp_gen),RooArgList(*nSig1sInp,*nSig2sInp,*nBkgInp));
  
  //----------------------------------------------------------------------------------------
  //----------------------------------------------------------------------------------------
  
  RooAddPdf* modelInput; 
  RooGenericPdf* bkgInp;
  if ( inputOption == kErrExp ) { 
    bkgInp = (RooGenericPdf*) bkgDblErr;
  }
  else if ( inputOption == kChPol3 ) { 
    bkgInp = (RooGenericPdf*) bkgChPol3;
  }
  else if ( inputOption == kChPol4 ) { 
    bkgInp = (RooGenericPdf*) bkgChPol4;
  }
  else if ( inputOption == kErrExpExp ) { 
    bkgInp = (RooGenericPdf*) bkgComp4;
  }

  modelInput = new RooAddPdf("modelInput","1S+2S + Bkg",RooArgList(*cb1s, *cb2s, *bkgInp),RooArgList(*nSig1sInp,*nSig2sInp,*nBkgInp));
  wsinp->import(*modelInput);

  Val_2S_1S_nom=0;
  Val_2S_1S_alt=0;
  Dev_2S_1S=0;


  RooDataSet *data = modelInput_gen->generate(mass,nGen) ;

  RooPlot* xframe  = ws->var("mass")->frame(nMassBin); // bins
  xframe->SetXTitle("mass (Gev/c^{2})");
  xframe->GetXaxis()->CenterTitle();
  xframe->GetYaxis()->CenterTitle();
  RooPlot* xframe2 = (RooPlot*)xframe->Clone("xframe2");
  
  RooFitResult* fitResInput = wsinp->pdf("modelInput")->fitTo(*data,Save(), Hesse(kTRUE),Range(massLow, massHigh),Minos(0), SumW2Error(kTRUE));
  data->plotOn(xframe,Name("dataHist"),MarkerSize(0.7)) ;
  wsinp->pdf("modelInput")->plotOn(xframe, Name("inputModelHist"));
  wsinp->pdf("modelInput")->plotOn(xframe, Components(RooArgSet(*bkgInp)),LineColor(kBlack),LineStyle(kDashed));
  if ( inputOption == kErrExp ) 
    {  
      modelInput->plotOn(xframe,Components(RooArgSet(*bkgDblErr)),LineColor(kRed),LineStyle(kDashed));
      modelInput->plotOn(xframe,Components(RooArgSet(*bkgErrExp1)),LineColor(kBlack),LineStyle(kDashed));
      modelInput->plotOn(xframe,Components(RooArgSet(*bkgErrExp2)),LineColor(kBlack),LineStyle(kDashed));
    }
  else if  ( inputOption == kChPol3 )
    modelInput->plotOn(xframe,Components(RooArgSet(*bkgChPol3)),LineColor(kBlack),LineStyle(kDashed));
  else if  ( inputOption == kChPol4 )
    modelInput->plotOn(xframe,Components(RooArgSet(*bkgChPol4)),LineColor(kBlack),LineStyle(kDashed));
  else if (inputOption == kErrExpExp ) {
    modelInput->plotOn(xframe,Components(RooArgSet(*bkgComp4)),LineColor(kBlack),LineStyle(kDashed));
    modelInput->plotOn(xframe,Components(RooArgSet(*bkg4ErrExp)),LineColor(kBlack),LineStyle(kDashed));
    modelInput->plotOn(xframe,Components(RooArgSet(*bkg4Exp)),LineColor(kBlack),LineStyle(kDashed));
  }


  // New fit 
  
  float the_bkg_mu = bkgParm.bkg_mu ;
  float the_bkg_sigma = bkgParm.bkg_sigma ;
  float the_bkg_lambda = bkgParm.bkg_lambda ;
  if ( !( (cLow==0) && (cHigh==200) ) && (collId==kAADATA) && useCentIntBkgShape  ) {
    the_bkg_mu = bkgParmCentInt.bkg_mu ;
    the_bkg_sigma = bkgParmCentInt.bkg_sigma ;
    the_bkg_lambda = bkgParmCentInt.bkg_lambda ;
  }

  //RooRealVar err_mu("err_mu","err_mu", the_bkg_mu, 0.0, 40);
  RooRealVar err_mu("err_mu","err_mu", the_bkg_mu, the_bkg_mu*0.4, the_bkg_mu*1.4);
  //RooRealVar err_mu("err_mu","err_mu", 1., 0.0, 30);
  //RooRealVar err_sigma("err_sigma","err_sigma", 1.2, 1.1,55);
  //RooRealVar err_sigma("err_sigma","err_sigma", 10.,0,20);
  RooRealVar err_sigma("err_sigma","err_sigma", the_bkg_sigma, the_bkg_sigma*0.4, the_bkg_sigma*1.4);
  //RooRealVar m_decay("m_decay","m_decay", 10., 6.5, 30);
  RooRealVar m_decay("m_decay","m_decay",the_bkg_lambda, the_bkg_lambda*0.4, the_bkg_lambda*1.4);
  
  if( ( ptLow == (float)0 ) && (ptHigh == (float)30 ) && (yLow == (float)0 ) && (yHigh == (float)2.4) && collId==kPPDATA) 
  {
    err_sigma.setVal(1.055); 
    err_sigma.setConstant();
  }
  if( ( ptLow == (float)0 ) && (ptHigh == (float)30 ) && (yLow == (float)0 ) && (yHigh == (float)2.4) && collId==kAADATA) 
  {
    err_sigma.setVal(1.103); 
    err_sigma.setConstant();
  }

  RooGenericPdf *bkgFitOut;
  if ( ptLow == 0)  { 
    bkgFitOut = new RooGenericPdf("bkgFitOut","BackgroundOut","(TMath::Erf((@0-@1)/(TMath::Sqrt(2)*@2))+1)*0.5*TMath::Exp(-@0/@3)",RooArgList(mass,err_mu,err_sigma,m_decay));
  }
  else {
    bkgFitOut = new RooGenericPdf("bkgFitOut","BackgroundOut","TMath::Exp(-@0/@1)",RooArgList(mass,m_decay));
  }

  

  RooRealVar *nSig1sOut  = new RooRealVar("nSig1sOut","nSig1sOut", r1S_overTot*nGen, 0,  r1S_overTot*2.*nGen);
  RooRealVar *nSig2sOut  = new RooRealVar("nSig2sOut","nSig2sOut", r2S_overTot*nGen, 0, r2S_overTot*2.*nGen);
  RooRealVar *nBkgOut  = new RooRealVar("nBkgOut","n_bkgOut",nGen * rBkg_overTot, 0, nGen);

  RooAddPdf*  cb1sOut = (RooAddPdf*)cb1s->Clone("cb1sOutput");
  RooAddPdf*  cb2sOut = (RooAddPdf*)cb2s->Clone("cb2sOutput");
  RooAddPdf* modelOutput = new RooAddPdf("modelOutput","1S+2S + Bkg",RooArgList(*cb1sOut, *cb2sOut, *bkgFitOut),RooArgList(*nSig1sOut,*nSig2sOut,*nBkgOut));
  ws->import(*modelOutput);
  
  RooFitResult* fitRes = ws->pdf("modelOutput")->fitTo(*data,Save(), Hesse(kTRUE),Range(massLow, massHigh),Minos(0), SumW2Error(kTRUE));
  data->plotOn(xframe2,Name("dataHist2"),MarkerSize(0.7)) ;
  ws->pdf("modelOutput")->plotOn(xframe2, Name("outputModelHist"));
  ws->pdf("modelOutput")->plotOn(xframe2, Components(RooArgSet(*bkgFitOut)),LineColor(kBlack),LineStyle(kDashed));
  
  Val_2S_1S_nom = (float)(ws->var("nSig2sOut")->getVal() / ws->var("nSig1sOut")->getVal());
  Val_2S_1S_alt = (float)(wsinp->var("nSig2sInp")->getVal() / wsinp->var("nSig1sInp")->getVal());
  Dev_2S_1S = (Val_2S_1S_alt/Val_2S_1S_nom - 1) * 100;
  h1->Fill(Val_2S_1S_nom);
  h2->Fill(Val_2S_1S_alt);
  h3->Fill(Dev_2S_1S);

  // DRAW! 
  if(i == 0){
  TCanvas* c1 =  new TCanvas("canvas2","My plots",4,45,800,400);
  c1->cd();
  TPad *pad1 = new TPad("pad1", "pad1", 0, 0.25, 0.49, 1.0);
  pad1->SetTicks(1,1);
  pad1->Draw(); pad1->cd();
  pad1->SetBottomMargin(0); // Upper and lower plot are joined

  xframe->GetYaxis()->SetTitleOffset(1.4) ; xframe->Draw() ;
  drawText(Form("#Upsilon(2S)/#Upsilon(1S) = %.5f",(float)(wsinp->var("nSig2sInp")->getVal() / wsinp->var("nSig1sInp")->getVal())),0.2,0.54,1,16) ;
  
  if (inputOption==kChPol4 ) 
    drawText("4th order poly. Bkg.",0.2,0.62,2,15) ;
  if (inputOption==kErrExpExp ) 
    drawText("Erf*exp + exp Bkg.",0.2,0.62,2,15) ;
  
  if(collId == kAADATA)
    drawText("PbPb",0.4,0.45,1,15);
  if(collId == kPPDATA)
    drawText("pp", 0.4,0.45,1,15);

  drawText(Form("%.1f < p_{T}^{#mu#mu} < %.1f GeV",ptLow,ptHigh ),0.5,0.60,1,12);
  drawText(Form("%.1f < y^{#mu#mu} < %.1f",yLow,yHigh ), 0.5,0.55,1,12);
  TString perc = "%";
  if(collId == kAADATA)
    drawText(Form("Cent %d-%d%s",cLow/2,cHigh/2,perc.Data()),0.5,0.5,4,12);
  
  TLatex *tex = new TLatex(0.4,0.88,"Toy MC generated");
  tex->SetTextFont(43);
  tex->SetTextSize(15);
  tex->SetNDC();
  //  tex->SetTextAngle(180);
  tex->Draw();

  RooArgList paramListinp = fitResInput->floatParsFinal();
  paramListinp.Print("v");
  RooPlot* legFrameinp = wsinp->var("mass")->frame(Name("Fit Results"), Title("Fit Results"));
  wsinp->pdf("modelInput")->paramOn(legFrameinp,Layout(.6,.9, .5),Parameters(paramListinp));
  legFrameinp->getAttText()->SetTextAlign(11);
  legFrameinp->getAttText()->SetTextSize(0.028);
  TPaveText* hhinp = (TPaveText*)legFrameinp->findObject(Form("%s_paramBox",wsinp->pdf("modelInput")->GetName()));
  hhinp->SetY1(0.35); hhinp->SetY2(0.83);
  hhinp->Draw();
  // PULL

  TPad *pad2 = new TPad("pad2", "pad2", 0, 0.05, 0.49, 0.25);
  c1->cd();
  pad2->Draw();
  pad2->cd();
  RooHist* hpull = xframe->pullHist("dataHist","inputModelHist");
  RooPlot* pullFrame = wsinp->var("mass")->frame(Title("Pull Distribution")) ;
  pullFrame->addPlotable(hpull,"P") ;
  pullFrame->SetTitleSize(2.57);
  pullFrame->GetYaxis()->SetTitleOffset(1.8) ;
  pullFrame->GetYaxis()->SetLabelSize(0.16) ;
  pullFrame->GetYaxis()->SetRange(-10,10) ;
  pullFrame->GetXaxis()->SetTitleOffset(0.7) ;
  pullFrame->GetXaxis()->SetLabelSize(0.1) ;
  pullFrame->GetXaxis()->SetTitleSize(0.13) ;
  pullFrame->Draw() ;


  TPad *pad3 = new TPad("pad3", "pad3", 0.51, 0.25, 0.99, 1);
  pad3->SetTicks(1,1);
  pad3->SetBottomMargin(0); // Upper and lower plot are joined
  c1->cd();
  pad3->Draw(); pad3->cd();

  xframe2->GetYaxis()->SetTitleOffset(1.4) ; xframe2->Draw() ;
  TLatex *tex2 = new TLatex(0.4,0.9,"Fitted by Nominal function");
  tex2->SetTextFont(43);
  tex2->SetTextSize(15);
  tex2->SetTextColor(2);
  tex2->SetNDC();
  tex2->Draw();
  drawText(Form("#Upsilon(2S)/#Upsilon(1S) = %.5f",(float)(ws->var("nSig2sOut")->getVal() / ws->var("nSig1sOut")->getVal())), 0.4,0.85,1,16 );

  // *~*~*~*~*~*~*~* Draw the parameters in the plot  *~*~*~*~*~*~*~* //
  RooArgList paramList = fitRes->floatParsFinal();
  paramList.Print("v");
  RooPlot* legFrame = ws->var("mass")->frame(Name("Fit Results"), Title("Fit Results"));
  ws->pdf("modelOutput")->paramOn(legFrame,Layout(.6,.9, .5),Parameters(paramList));
  legFrame->getAttText()->SetTextAlign(11);
  legFrame->getAttText()->SetTextSize(0.028);
  TPaveText* hh = (TPaveText*)legFrame->findObject(Form("%s_paramBox",ws->pdf("modelOutput")->GetName()));
  hh->SetY1(0.35); hh->SetY2(0.83);
  hh->Draw();

  TPad *pad4 = new TPad("pad4", "pad4", 0.51, 0.05, 0.99, 0.25);
  // pad4->SetBottomMargin(0); // Upper and lower plot are joined
  c1->cd();
  pad4->Draw();
  pad4->cd();
  RooHist* hpullOut = xframe2->pullHist("dataHist2","outputModelHist");
  RooPlot* pullOutFrm = ws->var("mass")->frame(Title("Pull Distribution")) ;
  pullOutFrm->addPlotable(hpullOut,"P") ;
  pullOutFrm->SetTitleSize(2.57);
  pullOutFrm->GetYaxis()->SetTitleOffset(1.8) ;
  pullOutFrm->GetYaxis()->SetLabelSize(0.16) ;
  pullOutFrm->GetYaxis()->SetRange(-10,10) ;
  pullOutFrm->GetXaxis()->SetTitleOffset(0.7) ;
  pullOutFrm->GetXaxis()->SetLabelSize(0.1) ;
  pullOutFrm->GetXaxis()->SetTitleSize(0.13) ;
  pullOutFrm->Draw() ;



  // *~*~*~*~*~*~*~* Print the results *~*~*~*~*~*~*~* //

  //cout << "nSig2sInp/nSig1sInp = " << nSig2sInp->getVal() / nSig1sInp->getVal() << endl;
  cout << "input fit ratio = " << wsinp->var("nSig2sInp")->getVal() / wsinp->var("nSig1sInp")->getVal() << endl;
  cout << "output fit ratio = " << ws->var("nSig2sOut")->getVal() / ws->var("nSig1sOut")->getVal() << endl;
  c1->SaveAs(Form( "toyMCFit_collId%d_pt%.0f-%.0fGeV_y%.0f-%.0f_cBin%d-%d_muPtCut%.0fGeV_BkgPDFOpt%d_nGen%d_useCentIntBkgShape%d.png",
		   collId, ptLow, ptHigh, yLow*10, yHigh*10, cLow, cHigh, muPtCut, inputOption, nGen,useCentIntBkgShape) );
  
  float r1 =  wsinp->var("nSig2sInp")->getVal() / wsinp->var("nSig1sInp")->getVal() ; 
  float r2 =  ws->var("nSig2sOut")->getVal() / ws->var("nSig1sOut")->getVal() ; 
  cout << Form( "collId: %d,    pt: %.0f - %.0fGeV,   y: %.1f - %.1f,  cBin: %d - %d", collId, ptLow, ptHigh, yLow, yHigh, cLow, cHigh ) << endl;
  cout << "Uncertainty = "  << (r2 - r1 ) / r1 << endl;
  }  
  
  }

  wf->cd();
  h1->Write();
  h2->Write();
  h3->Write();

   
} 
Пример #7
0
int main(){

  BaBarStyle p;
  p.SetBaBarStyle();
  //gROOT->SetStyle("Plain");

  Bool_t doNorm = kTRUE;
  Bool_t doComparison = kFALSE;
  Bool_t doFract = kFALSE;
  Bool_t doFit = kFALSE;
  Bool_t doPlots = kFALSE;

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

  RooRealVar m2Kpi_d0mass("m2Kpi_d0mass","m2Kpi_d0mass",1.,dalitzSpace.qAbsMin(EvtCyclic3::AB),dalitzSpace.qAbsMax(EvtCyclic3::AB));
  RooRealVar m2Kpi0_d0mass("m2Kpi0_d0mass","m2Kpi0_d0mass",1.,dalitzSpace.qAbsMin(EvtCyclic3::AC),dalitzSpace.qAbsMax(EvtCyclic3::AC));
  RooRealVar m2pipi0_d0mass("m2pipi0_d0mass","m2pipi0_d0mass",1.,dalitzSpace.qAbsMin(EvtCyclic3::BC),dalitzSpace.qAbsMax(EvtCyclic3::BC));
  RooCategory D0flav("D0flav","D0flav");
  D0flav.defineType("D0",-1);
  D0flav.defineType("antiD0",1);

  //this is just to plot the m23 pdf
  Float_t total = pow(dalitzSpace.bigM(),2) + pow(dalitzSpace.mA(),2) + pow(dalitzSpace.mB(),2) + pow(dalitzSpace.mC(),2);
  RooRealVar totalm("totalm","totalm",total);
  RooFormulaVar mass13a("mass13a","@0-@1-@2",RooArgSet(totalm,m2Kpi_d0mass,m2pipi0_d0mass));

  cout << "read the dataset" << endl;

  TFile hello("DataSet_out_tmp.root");
  gROOT->cd();
  RooDataSet *data = (RooDataSet*)hello.Get("fulldata");
  RooDataSet *data_1 = (RooDataSet*)data->reduce("D0flav ==  1 && isWS == 0 && d0LifetimeErr < 0.5 && d0Lifetime > -2. && d0Lifetime < 4.");
  RooDataSet *finaldata = (RooDataSet*)data_1->reduce("deltaMass > 0.1449 && deltaMass < 0.1459 && d0Mass > 1.8495 && d0Mass < 1.8795");
  RooDataSet *leftdata = (RooDataSet*)(RooDataSet*)data_1->reduce("d0Mass > 1.74 && d0Mass < 1.79");
  RooDataSet *rightdata = (RooDataSet*)data_1->reduce("d0Mass > 1.94 && d0Mass < 1.99");

  //here we set the weights for the dataset
  finaldata->setWeightVar(0);
  leftdata->setWeightVar(0);
  rightdata->setWeightVar(0);

  //if you want to have a little dataset to test, uncomment next line and rename finaldata above
  //RooDataSet *finaldata = finaldata_1->reduce(EventRange(1,1000));
  cout << "*************************************************************" << endl;
  cout << "The final data entry    " << finaldata->numEntries() << endl;
  cout << "*************************************************************" << endl;

  //Construct signal pdf
  string dirname = "configmaps/effmapping_RS_CP/";

  RooKpipi0pdf *D0pdf = new RooKpipi0pdf("D0pdf","D0pdf",m2Kpi_d0mass,m2Kpi0_d0mass,&dalitzSpace,dirname,1);
  RooKpipi0pdf *D0pdf23 = new RooKpipi0pdf("D0pdf23","D0pdf23",m2Kpi_d0mass,mass13a,&dalitzSpace,dirname,1);

  if(doNorm) D0pdf->getManager()->calNorm();

  //When we plot the 1D projection, need to calculate the 1D integral
  //set the precision here
  //cout << "config integrator " << endl;
  RooNumIntConfig *cfg = RooAbsReal::defaultIntegratorConfig();
  cfg->setEpsAbs(1E-3);
  cfg->setEpsRel(1E-3);
  cfg->method1D().setLabel("RooSegmentedIntegrator1D");
  //cfg.getConfigSection("RooSegmentedIntegrator1D").setRealValue("numSeg",3);
  //cfg->method1D()->Print("v");
  D0pdf->setIntegratorConfig(*cfg);
  D0pdf23->setIntegratorConfig(*cfg);

  cout << "about to init" << endl;

  m2Kpi_d0mass.setBins(150);
  m2Kpi0_d0mass.setBins(150);
  m2pipi0_d0mass.setBins(150);

  //background description
  //RooBkg combdalitz("combdalitz","combdalitz",m2Kpi_d0mass,m2Kpi0_d0mass,&dalitzSpace);
  //RooBkg combdalitz23("combdalitz23","combdalitz23",m2Kpi_d0mass,mass13a,&dalitzSpace);

  RooRealVar Nsig("Nsig","Nsig", 653962. + 2218.);
  RooRealVar Nbkg("Nbkg","Nbkg", 2255. + 551.);

  RooDataHist* dbdalitz = new RooDataHist("dbdalitz","dbdalitz",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),*finaldata);
  RooDataHist* dbdalitz23 = new RooDataHist("dbdalitz23","dbdalitz23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),*finaldata);

  ////////////////////////////////////////
  //background parametrization using sidebands histograms
  ////////////////////////////////////////
  TH2F *lefth = m2Kpi_d0mass.createHistogram("lefth",m2Kpi0_d0mass);
  leftdata->fillHistogram(lefth,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass));
  TH2F *righth = m2Kpi_d0mass.createHistogram("righth",m2Kpi0_d0mass);
  rightdata->fillHistogram(righth,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass));

  TH2F *lefth23 = m2Kpi_d0mass.createHistogram("lefth23",m2pipi0_d0mass);
  leftdata->fillHistogram(lefth23,RooArgList(m2Kpi_d0mass,m2pipi0_d0mass));
  TH2F *righth23 = m2Kpi_d0mass.createHistogram("righth23",m2pipi0_d0mass);
  rightdata->fillHistogram(righth23,RooArgList(m2Kpi_d0mass,m2pipi0_d0mass));

  righth->Scale(lefth->Integral()/righth->Integral());
  lefth->Sumw2();
  righth->Sumw2();
  righth23->Scale(lefth23->Integral()/righth23->Integral());
  lefth23->Sumw2();
  righth23->Sumw2();

  RooDataHist *lefthist = new RooDataHist("lefthist","lefthist",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),lefth);
  RooDataHist *righthist = new RooDataHist("righthist","righthist",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),righth);
  RooDataHist *lefthist23 = new RooDataHist("lefthist23","lefthist23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),lefth23);
  RooDataHist *righthist23 = new RooDataHist("righthist23","righthist23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),righth23);

  RooHistPdf leftpdf("leftpdf","leftpdf",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),*lefthist,4);
  RooHistPdf rightpdf("rightpdf","rightpdf",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),*righthist,4);
  RooHistPdf leftpdf23("leftpdf23","leftpdf23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),*lefthist23,4);
  RooHistPdf rightpdf23("rightpdf23","rightpdf23",RooArgSet(m2Kpi_d0mass,m2pipi0_d0mass),*righthist23,4);

  RooRealVar fcomb("fcomb","fcomb",0.738);
  RooAddPdf combdalitz("combdalitz","combdalitz",RooArgList(leftpdf,rightpdf),RooArgList(fcomb));
  RooAddPdf combdalitz23("combdalitz23","combdalitz23",RooArgList(leftpdf23,rightpdf23),RooArgList(fcomb));
  ///////////////////////////////////////

  RooAddPdf totpdf("totpdf","totpdf",RooArgList(*D0pdf,combdalitz),RooArgList(Nsig,Nbkg));
  RooAddPdf totpdf23("totpdf23","totpdf23",RooArgList(*D0pdf23,combdalitz23),RooArgList(Nsig,Nbkg));

  if(doFit){
    // Start Minuit session on Chi2
    RooChi2Var chi2("chi2","chi2",totpdf,*dbdalitz);
    RooMinuit m2(chi2);
    m2.migrad();
    m2.hesse();
    RooFitResult* fitRes = m2.save();
    fitRes->Print("v");
    RooArgSet results(fitRes->floatParsFinal());
    RooArgSet conresults(fitRes->constPars());
    results.add(conresults);
    results.writeToFile("fit_isobar_RS.txt");

    //save the stupid result
    TFile f("fit_RSDalitz_result.root","RECREATE");
    fitRes->Write();
    f.Close();
  }

  if(doFract) {

    cout << "Calculating fit fractions" << endl;
    TFile f("fit_RSDalitz_result.root");
    RooFitResult* fitRes = (RooFitResult*)f.Get("chi2");

    //now calculate the fit fractions
    const Int_t nRes = D0pdf->getManager()->getnRes();

    //recalculate the normalization if necessary
    D0pdf->getManager()->calNorm();

    EvtComplex normarray[nRes][nRes];

    const Int_t myRes = 12;
    TH1F fitty[myRes];

    //read the integral value from the cache file.
    //In this way we don't need to compute the normalization everytime during MIGRAD
    char int_name[50];
    D0pdf->getManager()->getFileName(int_name);

    ifstream f1;
    f1.open(int_name);
    if (!f1){
      cout << "Error opening file " << endl;
      assert(0);
    }
  
    Double_t re=0.,im=0.;
    //Read in the cache file and store back to array
    for(Int_t j=0;j<nRes;j++) {
      char thname[100];
      sprintf(thname,"thname_%d",j);
      if(j < myRes) fitty[j] = TH1F(thname,thname,30,0.,1.);
      for(Int_t k=0;k<nRes;k++){
	f1 >> re >> im;       
	normarray[j][k] = EvtComplex(re,im);
      }
    }   

    EvtComplex mynorm[myRes][myRes];
    Int_t m = 0, l = 0;
    for(Int_t i=0;i<myRes;i++){
      for(Int_t j=0;j<myRes;j++){
	if(i==0) l = 7;
	else if(i==1) l = 6;
	else if(i==2) l = 11;
	else if(i==3) l = 4;
	else if(i==4) l = 5;
	else if(i==5) l = 3;
	else if(i==6) l = 9;
	else if(i==7) l = 10;
	else if(i==8) l = 12;
	else if(i==9) l = 8;
	else if(i==10) l = 2;
	else if(i==11) l = 0;

	if(j==0) m = 7;
	else if(j==1) m = 6;
	else if(j==2) m = 11;
	else if(j==3) m = 4;
	else if(j==4) m = 5;
	else if(j==5) m = 3;
	else if(j==6) m = 9;
	else if(j==7) m = 10;
	else if(j==8) m = 12;
	else if(j==9) m = 8;
	else if(j==10) m = 2;
	else if(j==11) m = 0;

	mynorm[i][j] = normarray[l][m];
      }
    }

    //do 100 experiments and extract parameters using covariance matrix
    for(Int_t l=0;l<300;l++){
      RooArgList listpar = fitRes->randomizePars();
      if(l==0) listpar.Print();

      Double_t mynormD0 = 0.;
      EvtComplex coeff_i(0.,0.), coeff_j(0.,0.);
      for(Int_t i=0;i<2*myRes;i++){
	for(Int_t j=0;j<2*myRes;j++){
	  if(i==(2*myRes - 2)) coeff_i = EvtComplex(1.,0.);
	  else coeff_i = EvtComplex(((RooAbsReal*)listpar.at(i))->getVal()*cos(((RooAbsReal*)listpar.at(i+1))->getVal()),
				    ((RooAbsReal*)listpar.at(i))->getVal()*sin(((RooAbsReal*)listpar.at(i+1))->getVal()));

	  if(j==(2*myRes - 2)) coeff_j = EvtComplex(1.,0.);
	  else coeff_j = EvtComplex(((RooAbsReal*)listpar.at(j))->getVal()*cos(((RooAbsReal*)listpar.at(j+1))->getVal()),
				    ((RooAbsReal*)listpar.at(j))->getVal()*sin(((RooAbsReal*)listpar.at(j+1))->getVal()));

	  mynormD0 += real(coeff_i*conj(coeff_j)*(mynorm[i/2][j/2]));
	  j++;
	}
	i++;
      }

      //now calculate the fit fractions
      for(Int_t i=0;i<2*myRes;i++){
	Double_t fitfrac = 0.;
	if(i==(2*myRes - 2)) fitfrac = abs(mynorm[i/2][i/2])/mynormD0;
	else fitfrac = abs2( ((RooAbsReal*)listpar.at(i))->getVal())*abs(mynorm[i/2][i/2])/mynormD0;
	fitty[i/2].Fill(fitfrac);
	i++;
      }
    }// nexperiments

    Double_t tot_frac = 0.;
    for(Int_t i=0;i<myRes;i++){
      tot_frac += fitty[i].GetMean();
      cout << "Resonance " << i << ": fit fraction = " << fitty[i].GetMean() << " +/- " << fitty[i].GetRMS() << endl;
    }

    cout << "Total fit fraction = " << tot_frac << endl;
    cout << "///////////////////////////" << endl;
  }

  if(doPlots){
    //Make the plots
    // REMEBER: if you want roofit to consider the reweighted errors, you must put DataError(RooAbsData::SumW2))
    //******************************************************
    RooPlot* xframe = m2Kpi_d0mass.frame();
    dbdalitz->plotOn(xframe,MarkerSize(0.1),DrawOption("z"));
    totpdf.plotOn(xframe);
    xframe->getAttLine()->SetLineWidth(1);
    xframe->getAttLine()->SetLineStyle(1);
    xframe->SetTitle("");
    xframe->GetXaxis()->SetTitle("s_{12} [GeV^{2}/c^{4}]");
    xframe->GetYaxis()->SetTitle("Events/4 MeV^{2}/c^{4}");
    Double_t chi2Kpi = xframe->chiSquare();

    RooPlot* yframe = m2Kpi0_d0mass.frame();
    dbdalitz->plotOn(yframe,MarkerSize(0.1),DrawOption("z"));
    totpdf.plotOn(yframe);
    yframe->getAttLine()->SetLineWidth(1);
    yframe->getAttLine()->SetLineStyle(1);
    yframe->SetTitle("");
    yframe->GetXaxis()->SetTitle("s_{13} [GeV^{2}/c^{4}]");
    yframe->GetYaxis()->SetTitle("Events/5 MeV^{2}/c^{4}");
    Double_t chi2Kpi0 = yframe->chiSquare();
    /*
    RooPlot* zframe = m2pipi0_d0mass.frame(0.,2.3);
    dbdalitz23->plotOn(zframe,MarkerSize(0.1),DrawOption("z"));
    totpdf23.plotOn(zframe);
    zframe->getAttLine()->SetLineWidth(1);
    zframe->getAttLine()->SetLineStyle(1);
    zframe->SetTitle("");
    zframe->GetXaxis()->SetTitle("m^{2}_{#pi^{+}#pi^{0}}");
    Double_t chi2pipi0 = zframe->chiSquare();

    cout << "Chi2 for Kpi = " << chi2Kpi << endl;
    cout << "Chi2 for Kpi0 = " << chi2Kpi0 << endl;
    cout << "Chi2 for pipi0 = " << chi2pipi0 << endl;

    RooPlot* pullFramem12 = m2Kpi_d0mass.frame() ;
    pullFramem12->SetTitle("");
    pullFramem12->GetXaxis()->SetTitle("");
    pullFramem12->addPlotable(xframe->pullHist()) ;
    pullFramem12->SetMaximum(5.);
    pullFramem12->SetMinimum(-5.);

    RooPlot* pullFramem13 = m2Kpi0_d0mass.frame() ;
    pullFramem13->SetTitle("");
    pullFramem13->GetXaxis()->SetTitle("");
    pullFramem13->addPlotable(yframe->pullHist()) ;
    pullFramem13->SetMaximum(5.);
    pullFramem13->SetMinimum(-5.);

    RooPlot* pullFramem23 = m2pipi0_d0mass.frame() ;
    pullFramem23->SetTitle("");        
    pullFramem23->GetXaxis()->SetTitle("");
    pullFramem23->addPlotable(zframe->pullHist()) ;
    pullFramem23->SetMaximum(5.);
    pullFramem23->SetMinimum(-5.);

    TCanvas *c2 = new TCanvas("c2","residuals",1200,200);
    c2->Divide(3,1);
    c2->cd(1);pullFramem12->Draw();
    c2->cd(2);pullFramem13->Draw();
    c2->cd(3);pullFramem23->Draw();
    c2->SaveAs("RSresiduals.eps");
    */
    totpdf.plotOn(xframe,Project(m2Kpi0_d0mass),Components(RooArgSet(combdalitz)),DrawOption("F"),FillColor(kRed));
    totpdf.plotOn(yframe,Project(m2Kpi_d0mass),Components(RooArgSet(combdalitz)),DrawOption("F"),FillColor(kRed));
    //totpdf23.plotOn(zframe,Project(m2Kpi_d0mass),Components(RooArgSet(combdalitz23)),DrawOption("F"),FillColor(kRed));

    TPaveText *box_m12 = new TPaveText(2.5,2.5,2.7,2.7,"");
    box_m12->AddText("(b)");
    box_m12->SetFillColor(10);

    TPaveText *box_m13 = new TPaveText(2.5,2.5,2.7,2.7,"");
    box_m13->AddText("(c)");
    box_m13->SetFillColor(10);

    TCanvas c1("c1","c1",600,600);
    c1.cd();
    xframe->Draw();box_m12->Draw("SAME");
    c1.SaveAs("RSfit_m2Kpi.eps");

    TCanvas c2("c2","c2",600,600);
    c2.cd();
    yframe->Draw();box_m13->Draw("SAME");
    c2.SaveAs("RSfit_m2Kpi0.eps");
    /*
    TCanvas *c1 = new TCanvas("c1","allevents",1200,400);
    c1->Divide(3,1);
    c1->cd(1);xframe->Draw();
    //p.SetBaBarLabel(-1,-1,-1,"preliminary");
    c1->cd(2);yframe->Draw();
    //p.SetBaBarLabel(-1,-1,-1,"preliminary");
    c1->cd(3);zframe->Draw();
    //p.SetBaBarLabel(-1,-1,-1,"preliminary");
    c1->SaveAs("RSsigfit.eps");
    */
  }

  if(doComparison){
    RooDataSet *littledata = (RooDataSet*)finaldata->reduce(EventRange(1,70000));
    RooArgSet VarList1(m2Kpi_d0mass,m2Kpi0_d0mass);
    Int_t num_entries = littledata->numEntries();
    RooDataSet* genpdf = D0pdf->generate(VarList1,num_entries);

    Int_t nbinx = 20;
    Int_t nbiny = 20;
    m2Kpi_d0mass.setBins(nbinx);
    m2Kpi0_d0mass.setBins(nbiny);

    TH2F* pdfhist = new TH2F("pdfhist","pdfhist",nbinx,0.39,3.,nbiny,0.39,3.);
    TH2F* datahist = new TH2F("datahist","datahist",nbinx,0.39,3.,nbiny,0.39,3.);
    pdfhist = genpdf->createHistogram(m2Kpi_d0mass,m2Kpi0_d0mass);
    datahist = finaldata->createHistogram(m2Kpi_d0mass,m2Kpi0_d0mass);
    pdfhist->GetXaxis()->SetTitle("m_{K#pi}^{2}");
    pdfhist->GetYaxis()->SetTitle("m_{K#pi^{0}}^{2}");

    pdfhist->Scale(datahist->Integral()/pdfhist->Integral());

    pdfhist->Add(datahist,-1.);

    TCanvas c2;
    c2.cd();pdfhist->Draw("LEGO2Z");
    c2.SaveAs("RSsigdiff.eps");

    TFile ftmp("prova.root","RECREATE");
    ftmp.cd();pdfhist->Write();
    ftmp.Close();

  }

  return 0;
}//end of the macro
Пример #8
0
int main(int argc, char* argv[])
{
  string name;

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

    switch(pchar[0]){

    case '-':{

      switch(pchar[1]){
      case 'n':
        name = argv[i+1];
        cout << "Name of the configuration key " << name << endl;
        break;
      }
    }
    }
  }

  Bool_t doFit = kFALSE;
  Bool_t extract = kFALSE;
  Bool_t doFrac = kFALSE;
  Bool_t doPlots = kTRUE;
  Bool_t doChi2 = kFALSE;

  BaBarStyle p;
  p.SetBaBarStyle();
  gROOT->GetStyle("BABAR")->SetPalette(1);
  gROOT->GetStyle("BABAR")->SetPadTopMargin(0.04);
  gROOT->GetStyle("BABAR")->SetPadLeftMargin(0.17);
  gROOT->GetStyle("BABAR")->SetPadBottomMargin(0.19);
  gROOT->GetStyle("BABAR")->SetTitleSize(0.08,"xyz"); // set the 3 axes title size 

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

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

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

  RooRealVar c1("c1","c1",-2.,2.);
  RooRealVar c2("c2","c2",-2.,2.);
  RooUnblindOffset c1_unblind("c1_unblind","c1 (unblind)","VaffanculoS",1.,c1) ;
  RooUnblindOffset c2_unblind("c2_unblind","c2 (unblind)","VaffanculoS",1.,c2) ;

  TFile fWS("DataSet_out_tmp.root");
  gROOT->cd();
  RooDataSet *data = (RooDataSet*)fWS.Get("fulldata");
  RooDataSet *data_clean = (RooDataSet*)data->reduce("d0LifetimeErr < 0.5 && d0Lifetime > -2. && d0Lifetime < 4. && deltaMass > 0.1449 && deltaMass < 0.1459");
  RooDataSet *dataWS_2 = (RooDataSet*)data_clean->reduce("isWS == 1");
  RooDataSet *dataWS = (RooDataSet*)dataWS_2->reduce("d0Mass > 1.8495 && d0Mass < 1.8795");
  RooDataSet *RSdata = (RooDataSet*)data_clean->reduce("isWS == 0 && d0Mass > 1.8495 && d0Mass < 1.8795");

  Double_t low12,hig12,low13,hig13,low23,hig23;
  Bool_t m12bool = dataWS->getRange(m2Kpi_d0mass,low12,hig12);
  Bool_t m13bool = dataWS->getRange(m2Kpi0_d0mass,low13,hig13);
  Bool_t m23bool = dataWS->getRange(m2pipi0_d0mass,low23,hig23);
  m2Kpi_d0mass.setRange(low12,hig12);
  m2Kpi0_d0mass.setRange(low13,hig13);
  m2pipi0_d0mass.setRange(low23,hig23);

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

  Float_t total = pow(dalitzSpace.bigM(),2) + pow(dalitzSpace.mA(),2) + pow(dalitzSpace.mB(),2) + pow(dalitzSpace.mC(),2);
  RooRealVar totalm("totalm","totalm",total);
  RooFormulaVar mass13a("mass13a","@0-@1-@2",RooArgSet(totalm,m2Kpi_d0mass,m2pipi0_d0mass));

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

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

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

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

  string dirname = "configmaps/effmapping_" + name + "/";

  RooTimepdf TOTsigD0("TOTsigD0","TOTsigD0",d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass,gm,&dalitzSpace,tau,c1,c2,-1,dirname);
  //RooTimepdf TOTsigantiD0("TOTsigantiD0","TOTsigantiD0",d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass,gm,&dalitzSpace,tau,c1_unblind,c2_unblind,1);
 
  //RooSimultaneous TOTTime("TOTTime","TOTTime",D0flav);
  //TOTTime.addPdf(TOTsigD0,"D0");
  //TOTTime.addPdf(TOTsigantiD0,"antiD0");

  RooTimepdf TOTsigD023("TOTsigD023","TOTsigD023",d0Lifetime,m2Kpi_d0mass,mass13a,gm,&dalitzSpace,tau,c1,c2,-1,dirname);

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

  //Mistag parametrization
  m2Kpi_d0mass.setBins(150);
  m2Kpi0_d0mass.setBins(150);
  m2pipi0_d0mass.setBins(150);
  d0Lifetime.setBins(70);

  TH3F *mis_h = m2Kpi_d0mass.createHistogram("mis_h",m2Kpi0_d0mass,d0Lifetime,"");
  RSdata->fillHistogram(mis_h,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime));
  mis_h->Sumw2();
  RooDataHist *mis_hist = new RooDataHist("mis_hist","mis_hist",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),mis_h);
  RooHistPdf Tot_mis("Tot_mis","Tot_mis",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),*mis_hist);

  TH3F *mis_h23 = m2Kpi_d0mass.createHistogram("mis_h",m2pipi0_d0mass,d0Lifetime,"");
  RSdata->fillHistogram(mis_h23,RooArgList(m2Kpi_d0mass,m2pipi0_d0mass,d0Lifetime));
  mis_h23->Sumw2();
  RooDataHist *mis_hist23 = new RooDataHist("mis_hist23","mis_hist23",RooArgList(m2Kpi_d0mass,m2pipi0_d0mass,d0Lifetime),mis_h23);
  RooHistPdf Tot_mis23("Tot_mis23","Tot_mis23",RooArgList(m2Kpi_d0mass,m2pipi0_d0mass,d0Lifetime),*mis_hist23);

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

  RooArgSet observ(d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass);
  RooArgSet observ23(d0Lifetime,m2Kpi_d0mass,m2pipi0_d0mass);
  RooArgSet tot_var(d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass,d0LifetimeErr);

  //combinatoric
  RooDataSet *leftdata = (RooDataSet*)dataWS_2->reduce("d0Mass > 1.75 && d0Mass < 1.77");
  RooDataSet *rightdata = (RooDataSet*)dataWS_2->reduce("d0Mass > 1.95 && d0Mass < 1.97");
  RooDataSet *bkgdata = (RooDataSet*)dataWS_2->reduce("d0Mass > 1.95 || d0Mass < 1.77");
  rightdata->setWeightVar(0);
  leftdata->setWeightVar(0);

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

  TH3F *lefth23 = m2Kpi_d0mass.createHistogram("lefth23",m2pipi0_d0mass,d0Lifetime,"");
  leftdata->fillHistogram(lefth23,RooArgList(m2Kpi_d0mass,m2pipi0_d0mass,d0Lifetime));
  TH3F *righth23 = m2Kpi_d0mass.createHistogram("righth23",m2pipi0_d0mass,d0Lifetime,"");
  rightdata->fillHistogram(righth23,RooArgList(m2Kpi_d0mass,m2pipi0_d0mass,d0Lifetime));
  righth23->Scale(lefth23->Integral()/righth23->Integral());
  lefth23->Sumw2();
  righth23->Sumw2();
  lefth23->Add(righth23);
  lefth23->Sumw2();
  RooDataHist *lefthist23 = new RooDataHist("lefthist23","lefthist23",RooArgList(m2Kpi_d0mass,m2pipi0_d0mass,d0Lifetime),lefth23);
  RooHistPdf Tot_comb23("Tot_comb23","Tot_comb23",RooArgList(m2Kpi_d0mass,m2pipi0_d0mass,d0Lifetime),*lefthist23);

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

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

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

  RooProdPdf totsig_norm("totsig_norm","totsig_norm",RooArgSet(terr_sig_pdf),Conditional(TOTsigD0,observ));
  RooProdPdf totmis_norm("totmis_norm","totmis_norm",RooArgSet(terr_sig_pdf),Conditional(Tot_mis,observ));
  RooProdPdf totbkg_norm("totbkg_norm","totbkg_norm",RooArgSet(terr_bkg_pdf),Conditional(Tot_comb,observ));

  RooProdPdf totsig_norm23("totsig_norm23","totsig_norm23",RooArgSet(terr_sig_pdf),Conditional(TOTsigD023,observ23));
  RooProdPdf totmis_norm23("totmis_norm23","totmis_norm23",RooArgSet(terr_sig_pdf),Conditional(Tot_mis23,observ23));
  RooProdPdf totbkg_norm23("totbkg_norm23","totbkg_norm23",RooArgSet(terr_bkg_pdf),Conditional(Tot_comb23,observ23));

  //Signal + background
  RooAddPdf TOTpdf("TOTpdf","TOTpdf",RooArgList(totsig_norm,totmis_norm,totbkg_norm),RooArgList(Nsig,Nmis,Ncomb));
  RooAddPdf TOTpdf23("TOTpdf23","TOTpdf23",RooArgList(totsig_norm23,totmis_norm23,totbkg_norm23),RooArgList(Nsig,Nmis,Ncomb));

  if(doFit){

    RooFitResult *theRes = TOTpdf.fitTo(*dataWS,Save(1),Minos(0),Extended(0));

    string filename = "syst_root/fit_WS_" + name + ".root";
    TFile fout(filename.c_str(),"RECREATE");
    fout.cd();
    theRes->Write();
    fout.Close();
  }

  if(extract){
    TFile f("fitWS.root");
    RooFitResult* theRes = (RooFitResult*)f.Get("nll");
 
    RooRealVar myc1("myc1","myc1",-10.,10.);
    RooRealVar myc2("myc2","myc2",-10.,10.);
    RooRealVar myratio("myratio","myratio",0.,0.,1.);
    RooRealVar myx("myx","myx",0.,-1.,1.);
    RooRealVar myy("myy","myy",0.,-1.,1.);
 
    Double_t NrsNws = 2562./1132332.;
    Double_t ratioerr = sqrt(pow(89.,2.) + pow(NrsNws,2.)*pow(2862.,2.))/1132332.;
    RooDataSet *parFloat = new RooDataSet("parFloat","parFloat",RooArgList(myratio,myx,myy));
 
    for(Int_t j=0;j<400;j++){
      cout << "Performing step number " << j << endl;
      RooArgList floated = theRes->randomizePars();
      myc1.setVal(((RooAbsReal*)floated.find("c1"))->getVal());
      myc2.setVal(((RooAbsReal*)floated.find("c2"))->getVal());
 
      RooTimepdf mysigD0("mysigD0","mysigD0",d0Lifetime,m2Kpi_d0mass,m2Kpi0_d0mass,gm,&dalitzSpace,tau,myc1,myc2,-1,dirname);
      Double_t myDenom = mysigD0.createIntegral(RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime))->getVal();
      Double_t myNum = RooRandom::randomGenerator()->Gaus(NrsNws,ratioerr);
 
      myratio.setVal(myNum/myDenom);
      myx.setVal(myc2.getVal()*sqrt((myNum/myDenom)));
      myy.setVal(myc1.getVal()*sqrt((myNum/myDenom)));
 
      parFloat->add(RooArgSet(myratio,myx,myy));
    }
 
    TFile *f1 = new TFile("fitWS_float.root","RECREATE");
    f1->cd();
    parFloat->Write();
    f1->Close();
  }

  if(doChi2){
 
    m2Kpi_d0mass.setBins(40);
    m2Kpi0_d0mass.setBins(40);
 
    RooDataSet *dterr_ds = (RooDataSet*)dataWS->reduce(RooArgSet(d0LifetimeErr));
 
    TH2F *dphist_data = (TH2F*)m2Kpi_d0mass.createHistogram("dphist_data",m2Kpi0_d0mass);
    dataWS->fillHistogram(dphist_data,RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass));
 
    RooDataSet *pdf_ds = (RooDataSet*)TOTpdf.generate(RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass,d0Lifetime),dataWS->numEntries(),RooFit::ProtoData(*dterr_ds,1));
    TH2F *dphist = (TH2F*)m2Kpi_d0mass.createHistogram("dphist",m2Kpi0_d0mass);
    pdf_ds->fillHistogram(dphist,RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass));
 
    Int_t binx = m2Kpi_d0mass.getBinning().numBins();
    Int_t biny = m2Kpi0_d0mass.getBinning().numBins();
    Double_t chi2 = 0.;
    Int_t myBins = 0;
    Int_t nBin = 1;
 
    TH2F *pull_dal = (TH2F*)m2Kpi_d0mass.createHistogram("pull_dal",m2Kpi0_d0mass);
 
    dphist->Sumw2();
    dphist->Scale(dphist_data->Integral()/dphist->Integral());
    dphist->Sumw2();
 
    for(Int_t i=0;i<binx*biny;i++){
 
      Double_t chi_tmp = (dphist->GetBinContent(i)-dphist_data->GetBinContent(i))/dphist->GetBinError(i);
      Double_t nEv = dphist_data->GetBinContent(i);
      if(nEv == 0.) chi_tmp = 0.;
      pull_dal->SetBinContent(i,chi_tmp);
 
      if(nBin > 1){
	nBin--;
	//Double_t chi_tmp = (dphist->GetBinContent(i)-dphist_data->GetBinContent(i))/dphist->GetBinError(i);
	//pull_dal->SetBinContent(i,chi_tmp);
	continue;
      }
 
      if(nEv == 0.) continue;
      Double_t ndata = dphist_data->GetBinContent(i);
      Double_t npdf = dphist->GetBinContent(i);
      Double_t err = dphist->GetBinError(i);
      myBins++;
 
      while(nEv < 9.){
	if(dphist_data->GetBinContent(i+nBin) == 0. || dphist->GetBinError(i+nBin) == 0.){
	  nBin++;
	  continue;
	}
	ndata += dphist_data->GetBinContent(i+nBin);
	npdf += dphist->GetBinContent(i+nBin);
	err += sqrt(pow(err,2.) + pow(dphist->GetBinError(i+nBin),2.));
	nEv += dphist_data->GetBinContent(i+nBin);
	nBin++;
      }
 
      chi2 += pow((ndata-npdf)/err,2.);
    }
 
    Double_t chi2_root = dphist_data->Chi2Test(dphist,"UW");
 
    cout << "chi2 = " << chi2 << endl;
    cout << "chi2/ndof = " << chi2/(myBins -1.) << endl;
    cout << "mybins = " << myBins << endl;
    cout << "chi2 for root = " << chi2_root << endl;
 
    dphist_data->Sumw2();
    dphist->Sumw2();
    dphist_data->Add(dphist,-1.);
    dphist_data->SetMaximum(15.);

    dphist_data->SetMinimum(-15.);

    TCanvas c;
    c.Divide(1,2);
    c.cd(1);dphist_data->Draw("COLZ");
    c.cd(2);pull_dal->Draw("COLZ");
    c.SaveAs("WScomparison.eps");
    TFile fp("prova.root","RECREATE");
    dphist_data->Write();
    pull_dal->Write();
    fp.Close();
  }

  if(doPlots){
 
    m2Kpi_d0mass.setBins(20);
    m2Kpi0_d0mass.setBins(20);
    m2pipi0_d0mass.setBins(20);
    d0Lifetime.setBins(70);
 
    RooDataHist *dshist = new RooDataHist("dshist","dshist",RooArgSet(d0LifetimeErr),*dataWS);

    TH2F *lefth_t = m2Kpi_d0mass.createHistogram("lefth_t",m2Kpi0_d0mass);
    leftdata->fillHistogram(lefth_t,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass));
    TH2F *righth_t = m2Kpi_d0mass.createHistogram("righth_t",m2Kpi0_d0mass);
    rightdata->fillHistogram(righth_t,RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass));
    righth_t->Scale(lefth_t->Integral()/righth_t->Integral());
    lefth_t->Sumw2();
    righth_t->Sumw2();
    lefth_t->Add(righth);
    lefth_t->Sumw2();
    TH1F *left_t = (TH1F*)d0Lifetime.createHistogram("left_t");
    leftdata->fillHistogram(left_t,RooArgList(d0Lifetime));
    TH1F *right_t = (TH1F*)d0Lifetime.createHistogram("right_t");
    rightdata->fillHistogram(right_t,RooArgList(d0Lifetime));
    right_t->Scale(left_t->Integral()/right_t->Integral());
    left_t->Sumw2();
    right_t->Sumw2();
    left_t->Add(right_t);
    left_t->Sumw2();
 
    RooDataHist *lefthist_d = new RooDataHist("lefthist_d","lefthist_d",RooArgList(m2Kpi_d0mass,m2Kpi0_d0mass),lefth_t);
    RooDataHist *lefthist_t = new RooDataHist("lefthist_t","lefthist_t",RooArgList(d0Lifetime),left_t);
    RooHistPdf left_plot("left_plot","left_plot",RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass),*lefthist_d,6);
    RooHistPdf left_t_plot("left_t_plot","left_t_plot",RooArgSet(d0Lifetime),*lefthist_t,6);
 
    RooProdPdf tot_plot("tot_plot","tot_plot",left_plot,left_t_plot);
 
    RooProdPdf totbkg_norm_plot("totbkg_norm_plot","totbkg_norm_plot",RooArgSet(terr_bkg_pdf),Conditional(tot_plot,observ));
    RooAddPdf TOTpdf_plot("TOTpdf_plot","TOTpdf_plot",RooArgList(totsig_norm,totmis_norm,totbkg_norm_plot),RooArgList(Nsig,Nmis,Ncomb));

    RooPlot* tframe = d0Lifetime.frame();
    dataWS->plotOn(tframe,MarkerSize(0.1),DrawOption("z"));
    //TOTpdf.plotOn(tframe,Project(RooArgSet(m2Kpi_d0mass,m2Kpi0_d0mass,d0LifetimeErr)),ProjWData(*dshist));
    TOTpdf_plot.plotOn(tframe);
    Double_t chi2t = tframe->chiSquare();
    TOTpdf_plot.plotOn(tframe,Components(RooArgSet(totmis_norm,totbkg_norm_plot)),DrawOption("F"),FillColor(kBlue));       //FillColor(17));
    TOTpdf_plot.plotOn(tframe,Components(RooArgSet(totbkg_norm_plot)),DrawOption("F"),FillColor(kRed));                       //FillColor(14));
    tframe->getAttLine()->SetLineWidth(1);
    tframe->getAttLine()->SetLineStyle(1);
    tframe->SetTitle("");
    tframe->GetXaxis()->SetTitle("t_{K^{+}#pi^{-}#pi^{0}} [ps]");
    tframe->GetYaxis()->SetTitle("Events/0.08 ps");

    TPaveText *boxt = new TPaveText(2.5,2.5,2.7,2.7,"");
    boxt->AddText("(d)");
    boxt->SetFillColor(10);

    cout << "Chi2 for t = " << chi2t << endl;
    TCanvas ct("t","t",300,300);
    ct.cd();tframe->Draw();boxt->Draw("SAME");
    ct.SaveAs("WSfit_t.eps");

    //When we plot the 1D projection, need to calculate the 1D integral
    //set the precision here
    //cout << "config integrator " << endl;
    RooNumIntConfig *cfg = RooAbsReal::defaultIntegratorConfig();
    cfg->setEpsAbs(1E-5);
    cfg->setEpsRel(1E-5);
    cfg->method1D().setLabel("RooSegmentedIntegrator1D");
    //cfg.getConfigSection("RooSegmentedIntegrator1D").setRealValue("numSeg",3);
    //cfg->method1D()->Print("v");
    TOTsigD0.setIntegratorConfig(*cfg);
    //TOTsigantiD0.setIntegratorConfig(*cfg);
    TOTsigD023.setIntegratorConfig(*cfg);
    //TOTsigantiD023.setIntegratorConfig(*cfg);

    RooPlot* xframe = m2Kpi_d0mass.frame(53);  //was 19
    dataWS->plotOn(xframe,MarkerSize(0.1),DrawOption("z"));
    TOTpdf.plotOn(xframe,Project(RooArgSet(m2Kpi0_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist));
    xframe->getAttLine()->SetLineWidth(1);
    xframe->getAttLine()->SetLineStyle(1);
    xframe->SetTitle("");
    xframe->GetXaxis()->SetTitle("m^{2}_{K^{+}#pi^{-}}  [GeV^{2}/c^{4}]");
    xframe->GetYaxis()->SetTitle("Events/0.05 GeV^{2}/c^{4}");
    Double_t chi2Kpi = xframe->chiSquare();
    TOTpdf.plotOn(xframe,Project(RooArgSet(m2Kpi0_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist),Components(RooArgSet(totmis_norm,totbkg_norm)),DrawOption("F"),FillColor(kBlue)); //FillColor(17));
    TOTpdf.plotOn(xframe,Project(RooArgSet(m2Kpi0_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist),Components(RooArgSet(totbkg_norm)),DrawOption("F"),FillColor(kRed)); //FillColor(14));
    dataWS->plotOn(xframe,MarkerSize(0.1),DrawOption("z"));

    xframe->GetYaxis()->SetTitleOffset(1.3);

    TPaveText *box_m12 = new TPaveText(2.5,2.5,2.7,2.7,"");
    box_m12->AddText("(b)");
    box_m12->SetFillColor(10);

    TCanvas c1("c1","c1",300,300);
    c1.cd();xframe->Draw();box_m12->Draw("SAME");
    c1.SaveAs("WSfit_m2Kpi.eps");

    m2Kpi0_d0mass.setBins(50);

    RooPlot* yframe = m2Kpi0_d0mass.frame(49);
    dataWS->plotOn(yframe,MarkerSize(0.1),DrawOption("z"));
    TOTpdf.plotOn(yframe,Project(RooArgSet(m2Kpi_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist));
    yframe->getAttLine()->SetLineWidth(1);
    yframe->getAttLine()->SetLineStyle(1);
    yframe->SetTitle("");
    yframe->GetYaxis()->SetTitle("Events/0.05 GeV^{2}/c^{4}");
    yframe->GetXaxis()->SetTitle("m^{2}_{K^{+}#pi^{0}}  [GeV^{2}/c^{4}]");
    Double_t chi2Kpi0 = yframe->chiSquare();
    TOTpdf.plotOn(yframe,Project(RooArgSet(m2Kpi_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist),Components(RooArgSet(totmis_norm,totbkg_norm)),DrawOption("F"),FillColor(kBlue)); //FillColor(17));
    TOTpdf.plotOn(yframe,Project(RooArgSet(m2Kpi_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist),Components(RooArgSet(totbkg_norm)),DrawOption("F"),FillColor(kRed));  //FillColor(14));

    yframe->GetYaxis()->SetTitleOffset(1.3);

    TPaveText *box_m13 = new TPaveText(2.5,2.5,2.7,2.7,"");
    box_m13->AddText("(c)");
    box_m13->SetFillColor(10);

    TCanvas c2("c2","c2",300,300);
    c2.cd();yframe->Draw();box_m13->Draw("SAME");
    c2.SaveAs("WSfit_m2Kpi0.eps");

    m2Kpi0_d0mass.setBins(20);

    RooPlot* zframe = m2pipi0_d0mass.frame(50);
    dataWS->plotOn(zframe,MarkerSize(0.1),DrawOption("z"));
    TOTpdf23.plotOn(zframe,Project(RooArgSet(m2Kpi_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist));
    zframe->getAttLine()->SetLineWidth(1);
    zframe->getAttLine()->SetLineStyle(1);
    zframe->SetTitle("");
    zframe->GetYaxis()->SetTitle("Events/0.08 GeV^{2}/c^{4}");
    zframe->GetXaxis()->SetTitle("m^{2}_{#pi^{-}#pi^{0}} [GeV/c^{2}]");
    Double_t chi2pipi0 = zframe->chiSquare();
    TOTpdf23.plotOn(zframe,Project(RooArgSet(m2Kpi_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist),Components(RooArgSet(totmis_norm23,totbkg_norm23)),DrawOption("F"),FillColor(kBlue));
    TOTpdf23.plotOn(zframe,Project(RooArgSet(m2Kpi_d0mass,d0Lifetime,d0LifetimeErr)),ProjWData(*dshist),Components(RooArgSet(totbkg_norm23)),DrawOption("F"),FillColor(kRed));

    cout << "Chi2 for Kpi = " << chi2Kpi << endl;
    cout << "Chi2 for Kpi0 = " << chi2Kpi0 << endl;
    cout << "Chi2 for pipi0 = " << chi2pipi0 << endl;

    TCanvas *c = new TCanvas("c","allevents",1200,400);
    c->Divide(3,1);
    c->cd(1);xframe->Draw();
    c->cd(2);yframe->Draw();
    c->cd(3);zframe->Draw();
    c->SaveAs("WSfit.eps");

  }

  if(doFrac){
    cout << "Calculating fit fractions" << endl;
    TFile f("fitWS.root");
    RooFitResult* fitRes = (RooFitResult*)f.Get("nll");
 
    //now calculate the fit fractions
    const Int_t nRes = TOTsigD0.getManager()->getnRes();
 
    //recalculate the normalization if necessary
    //TOTsigD0.getManager()->calNorm();
 
    EvtComplex normarray[nRes][nRes];
 
    const Int_t myRes = 7;
    TH1F fitty[myRes];
 
    //read the integral value from the cache file.
    //In this way we don't need to compute the normalization everytime during MIGRAD
    char int_name[50];
    TOTsigD0.getManager()->getFileName(int_name);
 
    ifstream f1;
    f1.open(int_name);
    if (!f1){
      cout << "Error opening file " << endl;
      assert(0);
    }
   
    Double_t re=0.,im=0.;
    //Read in the cache file and store back to array
    for(Int_t j=0;j<nRes;j++) {
      char thname[100];
      sprintf(thname,"thname_%d",j);
      if(j < myRes) fitty[j] = TH1F(thname,thname,30,0.,1.);
      for(Int_t k=0;k<nRes;k++){
	f1 >> re >> im;       
	normarray[j][k] = EvtComplex(re,im);
      }
    }   
    EvtComplex mynorm[myRes][myRes];
    Int_t m = 0, l = 0;
    for(Int_t i=0;i<myRes;i++){
      for(Int_t j=0;j<myRes;j++){
	if(i==0) l = 11;
	else if(i==1) l = 5;
	else if(i==2) l = 3;
	else if(i==3) l = 10;
	else if(i==4) l = 8;
	else if(i==5) l = 2;
	else if(i==6) l = 0;
 
	if(j==0) m = 11;
	else if(j==1) m = 5;
	else if(j==2) m = 3;
	else if(j==3) m = 10;
	else if(j==4) m = 8;
	else if(j==5) m = 2;
	else if(j==6) m = 0;
 
	mynorm[i][j] = normarray[l][m];
      }
    }
 
    //do 100 experiments and extract parameters using covariance matrix
    for(Int_t l=0;l<200;l++){
      RooArgList listpar = fitRes->randomizePars();
      if(l==0) listpar.Print();

      Double_t mynormD0 = 0.;
      EvtComplex coeff_i(0.,0.), coeff_j(0.,0.);
      for(Int_t i=0;i<2*myRes;i++){
        for(Int_t j=0;j<2*myRes;j++){
          if(i==(2*myRes - 2)) coeff_i = EvtComplex(1.,0.);
          else coeff_i = EvtComplex(((RooAbsReal*)listpar.at(i))->getVal()*cos(((RooAbsReal*)listpar.at(i+1))->getVal()),
                                    ((RooAbsReal*)listpar.at(i))->getVal()*sin(((RooAbsReal*)listpar.at(i+1))->getVal()));

          if(j==(2*myRes - 2)) coeff_j = EvtComplex(1.,0.);
          else coeff_j = EvtComplex(((RooAbsReal*)listpar.at(j))->getVal()*cos(((RooAbsReal*)listpar.at(j+1))->getVal()),
                                    ((RooAbsReal*)listpar.at(j))->getVal()*sin(((RooAbsReal*)listpar.at(j+1))->getVal()));
          mynormD0 += real(coeff_i*conj(coeff_j)*(mynorm[i/2][j/2]));
          j++;
        }
        i++;
      }

      //now calculate the fit fractions
      for(Int_t i=0;i<2*myRes;i++){
        Double_t fitfrac = 0.;
        if(i==(2*myRes - 2)) fitfrac = abs(mynorm[i/2][i/2])/mynormD0;
        else fitfrac = abs2( ((RooAbsReal*)listpar.at(i))->getVal())*abs(mynorm[i/2][i/2])/mynormD0;
        fitty[i/2].Fill(fitfrac);
        i++;
      }
    }// nexperiments

    Double_t tot_frac = 0.;
    for(Int_t i=0;i<myRes;i++){
      tot_frac += fitty[i].GetMean();
      cout << "Resonance " << i << ": fit fraction = " << fitty[i].GetMean() << " +/- " << fitty[i].GetRMS() << endl;
    }
    cout << "Total fit fraction = " << tot_frac << endl;
    cout << "///////////////////////////" << endl;
  }

  return 0;
}