int main(){
  std::vector<MCSample> Samples;
  PkPhi.FileName="../PkphiSingle.root";
  PkPhi.Description="#Lambda_b -> p K #phi background";
  Samples.push_back(PkPhi);
  Rare.FileName="../RareMCSingle.root";
  Rare.Description="#eta' -> #pi #pi #gamma";
  Samples.push_back(Rare);
  Rare2.FileName="../Rare2MCSingle.root";
  Rare2.Description="#eta' -> #pi #pi #eta";
  Samples.push_back(Rare2);
  Control.FileName="../CCMCSingle.root";
  Control.Description="Control Channel";
  Samples.push_back(Control);
  
  for(auto &Sample : Samples){
    TreeReader * Reader = new TreeReader("DecayTree");
    Reader->AddFile(Sample.FileName.data());
    Reader->Initialize();
    Long64_t N=Reader->GetEntries();
    Sample.CC=new CorrelationCoeff(Sample.Description);
    std::string HeadMassName="Lambda_b0_DTF_MF";
    Reader->GetEntry(0);
    try{
      Reader->GetValue("Lambda_b0_DTF_MF");
    }catch(...){
      HeadMassName="Bu_DTF_MF";
    }
    for(int i=0;i<N;++i){
      Reader->GetEntry(i);
      double HeadMass=Reader->GetValue(HeadMassName.data());
      double EtaMass=Reader->GetValue("eta_prime_MM");
      if(HeadMassName.compare("Lambda_b0_DTF_MF")==0){
	if(HeadMass>5200.0&&HeadMass<6000.0&&EtaMass>880.0&&EtaMass<1040.0){
	  Sample.CC->Fill(HeadMass,EtaMass);
	}
      }else{
	if(HeadMass>5000.0&&HeadMass<5500.0&&EtaMass>880.0&&EtaMass<1040.0){
	  Sample.CC->Fill(HeadMass,EtaMass);
	}
      }
    }
    double NBootStraps=N*10;
    std::cout<<"After "<<NBootStraps<<" Boostraps"<<std::endl;
    std::cout<<Sample.Description<<" Coefficient = "<<Sample.CC->GetCC()<<" +/- "<<Sample.CC->GetBootstrapError(NBootStraps)<<std::endl;
  }
  TFile * Output = new TFile("Output.root","RECREATE");
  for(auto &Sample : Samples){
    Sample.CC->GetBootStrapHist(0)->Write();
    Sample.CC->GetCorrelationPlot()->Write();
  }
    
    

}
int main(int argc, char **argv)
{
	TString analysis = "Lb2Lmumu";
	bool MC = false;
	TString base = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/";

	if(argc > 1)
	{
		string arg = argv[1];
		if(arg == "MC") MC = true;
	}

	vector< string > novar;
	novar.push_back("Lb_MassCons");
	novar.push_back("Lb_MassConsLambda");
	novar.push_back("Lb_MassConsJpsiLambda");
	novar.push_back("cosTheta");
	novar.push_back("cosThetaL");
	novar.push_back("cosThetaB");
	novar.push_back("phiL");
	novar.push_back("phiB");
	novar.push_back("dphi");
	novar.push_back("cosTheta_TRUE");
	novar.push_back("cosThetaL_TRUE");
	novar.push_back("cosThetaB_TRUE");
	novar.push_back("phiL_TRUE");
	novar.push_back("phiB_TRUE");
	novar.push_back("dphi_TRUE");

	TCut cutJpsi = CutsDef::cutJpsi;
	TCut cutMuMu = CutsDef::cutMuMu_veto;

	TreeReader* treeReader = new TreeReader("tree");

	TString namefile = base + "candLb";
	if(MC) namefile += "_MC";
	namefile += ".root";

	TFile * candFile = new TFile(namefile,"recreate");

	if(!MC) treeReader->AddFile(base+analysis+"_CL_NBweighted.root");
	else treeReader->AddFile(base+analysis+"_MC_Pythia8_NBweighted.root");
	treeReader->Initialize(novar,"except");

	Analysis * anaLbMuMu = new Analysis("Lb2Lmumu","Lb",treeReader,&cutMuMu);

	candFile->cd();
	TTree * candLbMuMu = anaLbMuMu->applyCuts(&addVariables);
	candLbMuMu->Write();
	string tnameMuMu = candLbMuMu->GetName();

	candFile->Close();
	candFile = TFile::Open(namefile,"update");
	TTree * singleCand_LbMuMu = anaLbMuMu->checkMultiple("weight",namefile,tnameMuMu,&randomKill);
	singleCand_LbMuMu->Write();



	if(MC)
	{
		treeReader = new TreeReader("tree");
		treeReader->AddFile(base+"Lb2JpsiL_MC_Pythia8_NBweighted.root");
		treeReader->Initialize(novar,"except");
	}
	Analysis * anaLbJpsi = new Analysis("Lb2JpsiL","Lb",treeReader,&cutJpsi);

	candFile->cd();
	TTree * candLbJpsi = anaLbJpsi->applyCuts(&addVariables);
	candLbJpsi->Write();
	string tnameJpsi = candLbJpsi->GetName();

	candFile->Close();
	candFile = TFile::Open(namefile,"update");	
	TTree * singleCand_LbJpsi = anaLbJpsi->checkMultiple("weight",namefile,tnameJpsi,&randomKill);
	singleCand_LbJpsi->Write();

	candFile->cd();
	TTree * candLbJpsi_reduced = anaLbJpsi->applyCuts(&addVariables,300);
	candLbJpsi_reduced->SetName("candLb2JpsiL_reduced");
	candLbJpsi_reduced->Write();



	if(MC)
	{
		candFile->cd();
		TCut jpsiSwap = cutJpsi + CutsDef::jpsiSwapID;
		TCut mumuSwap = cutMuMu + CutsDef::mumuSwapID;
		TTree * mumuSwapTree = anaLbMuMu->applyCuts(&mumuSwap, false,&addVariables);
		mumuSwapTree->SetName("candLmumuSwap");
		mumuSwapTree->Write();
		TTree * jpsiSwapTree = anaLbJpsi->applyCuts(&jpsiSwap, false, &addVariables);
		jpsiSwapTree->SetName("candJpsiLSwap");
		jpsiSwapTree->Write();

		TreeReader * KSReader = new TreeReader("tree");
		KSReader->AddFile(base+"Bd2JpsiKS_MC12_NBweighted.root");
		KSReader->Initialize(novar,"except");
		TCut cutBdLL = cutJpsi + CutsDef::LLcut;
		TCut cutBdDD = cutJpsi + CutsDef::DDcut;
		Analysis * KSAnalysis_LL = new Analysis("BdJpsiKS_LL","B0",KSReader,&cutBdLL);
		TTree *KSTree_LL = KSAnalysis_LL->applyCuts(&addVariables);		
		KSTree_LL->Write();
		Analysis * KSAnalysis_DD = new Analysis("BdJpsiKS_DD","B0",KSReader,&cutBdDD);
		TTree *KSTree_DD = KSAnalysis_DD->applyCuts(&addVariables);		
		KSTree_DD->Write();
		Analysis * KSAnalysis_all = new Analysis("BdJpsiKS","B0",KSReader,&cutJpsi);
		TTree *KSTree = KSAnalysis_all->applyCuts(&addVariables);		
		KSTree->Write();

		candFile->cd();
		TreeReader * KstmumuReader = new TreeReader("tree");
		KstmumuReader->AddFile(base+"Bu2Kstmumu_MC12_NBweighted.root");
		KstmumuReader->Initialize(novar,"except");
		Analysis * KstmumuAnalysis = new Analysis("BuKstmumu","B0",KstmumuReader,&cutMuMu);
		TTree *KstmumuTree = KstmumuAnalysis->applyCuts(&addVariables);
		KstmumuTree->Write();

		candFile->cd();
		TreeReader * KSmumuReader = new TreeReader("tree");
		KSmumuReader->AddFile(base+"Bd2KSmumu_MC12_NBweighted.root");
		KSmumuReader->Initialize(novar,"except");
		Analysis * KSmumuAnalysis = new Analysis("BdKSmumu","B0",KSmumuReader,&cutMuMu);
		TTree *KSmumuTree = KSmumuAnalysis->applyCuts(&addVariables);
		KSmumuTree->Write();

		candFile->cd();
		TreeReader * JpsiGenReader = new TreeReader("tree");
		JpsiGenReader->AddFile("/afs/cern.ch/work/k/kreps/public/LbLMuMuAna/generatorLevel/LbJpsiLGenOnlyDaughInAccForRadiativeTail.root");
		JpsiGenReader->Initialize();
		TCut JpsiTailCut = "TMath::Power(J_psi_1S_MASS/1000,2) < 8 && Lb_MASS > 5300 && Lambda0_MASS > 1105 && Lambda0_MASS < 1125";
		Analysis * JpsiTailAnalysis = new Analysis("JpsiTail","Lb",JpsiGenReader,&JpsiTailCut);
		TTree *JpsiTailTree = JpsiTailAnalysis->applyCuts(&RenameMass, 0.1);
		JpsiTailTree->Write();
	}

	candFile->Close();
	delete candFile;

	return 0;
}
示例#3
0
int main(int argc, char **argv)
{
	bool printSw = true;
	//TString massModel = "Gauss-m[5622]";
	string massModel = "DCB-m[5622]";
	TString effbase = "/afs/cern.ch/user/p/pluca/work/Lb/Lmumu/results/";
	bool printeff = false;
	TString dodata = "data";
	bool fitsingle = false;
	TString wstr = "physRate_polp006";
	TString decayToDo = "Lb2Lmumu";
	if(dodata=="genMC") wstr += "_noDecay";

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


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

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

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

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


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

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

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

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

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

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

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

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

		ceff->cd();

		/**                    FIT EFFICIENCY                  **/

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

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

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


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

			/**                    FIT AFB                  **/


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

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

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

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

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

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

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

			RooDataSet * sdataDD, * sdataLL;

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

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

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

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

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


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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

	}
示例#4
0
int main(int argc, char **argv)
{
	bool printeff = true;
	string fc = "none";
	
	gROOT->ProcessLine(".x lhcbStyle.C");

	if(argc > 1)
	{
		for(int a = 1; a < argc; a++)
		{
			string arg = argv[a];
			string str = arg.substr(2,arg.length()-2);

			if(arg.find("-E")!=string::npos) fc = str;
			if(arg=="-peff") printeff = true;
		}
	}
	
	int nexp = 100;
	int nbins = 6;
	double q2min[] = {8.,15.,11.0,15,16,18};
	double q2max[] = {11.,20.,12.5,16,18,20};

	TString datafilename = "/afs/cern.ch/work/p/pluca/weighted/Lmumu/candLb.root";
	TreeReader * data = new TreeReader("candLb2Lmumu");
	data->AddFile(datafilename);
	TreeReader * datajpsi = new TreeReader("candLb2JpsiL");
	datajpsi->AddFile(datafilename);

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

	string options = "-quiet-noPlot-lin-stdAxis-XM(#Lambda#mu#mu) (MeV/c^{2})-noCost-noParams";
	Analysis::SetPrintLevel("s");

	RooRealVar * cosThetaL = new RooRealVar("cosThetaL","cosThetaL",0.,-1.,1.);
	RooRealVar * cosThetaB = new RooRealVar("cosThetaB","cosThetaB",0.,-1.,1.);
	RooRealVar * MM = new RooRealVar("Lb_MassConsLambda","Lb_MassConsLambda",5621.,5400.,6000.);
	MM->setRange("Signal",5600,5640);
	RooMsgService::instance().setGlobalKillBelow(RooFit::ERROR);

	//TGraphAsymmErrors * fL_vs_q2 = new TGraphAsymmErrors();
	//TCanvas * ceff = new TCanvas();

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

	RooRealVar * afb = new RooRealVar("afb","afb",0.,-0.75,0.75);
	RooRealVar * fL = new RooRealVar("fL","fL",0.6,0.,1.);
	TString afbLpdf = "((3./8.)*(1.-fL)*(1 + TMath::Power(cosThetaL,2)) + afb*cosThetaL + (3./4.)*fL*(1 - TMath::Power(cosThetaL,2)))";
	RooRealVar * afbB = new RooRealVar("afbB","afbB",0.,-0.5,0.5);
	TString afbBpdf = "(1 + 2*afbB*cosThetaB)";
	RooAbsPdf * teoPdf = new RooGenericPdf("teoPdf",afbLpdf,RooArgSet(*cosThetaL,*afb,*fL));
	RooAbsPdf * teoPdfB = new RooGenericPdf("teoPdfB",afbBpdf,RooArgSet(*cosThetaB,*afbB));

	TreeReader * mydata = datajpsi;
	Str2VarMap jpsiParsLL = getJpsiPars("LL", CutsDef::LLcut, histFile);
	Str2VarMap jpsiParsDD = getJpsiPars("DD", CutsDef::DDcut, histFile);

	vector<TH1 *> fLsysh, afbsysh, afbBsysh, fLsysh_frac, afbsysh_frac, afbBsysh_frac;

	for(int i = 0; i < nbins; i++)
	{
		TString q2name = ((TString)Form("q2_%4.2f_%4.2f",q2min[i],q2max[i])).ReplaceAll(".","");
		if(i>0) { mydata = data; MM->setRange(5400,6000); }
		else { q2name = "jpsi"; MM->setRange(5500,5850); }
		TString curq2cut = Form("TMath::Power(J_psi_1S_MM/1000,2) >= %e && TMath::Power(J_psi_1S_MM/1000,2) < %e",q2min[i],q2max[i]);	
		
		cout << "------------------- q2 bin: " << q2min[i] << " - " << q2max[i] << " -----------------------" << endl;

		/**               GET AND FIT EFFICIENCIES                  **/

		RooAbsPdf * effDDpdf = NULL, * effLLpdf = NULL, * effLLBpdf = NULL, * effDDBpdf = NULL;	
		getEfficiencies(q2min[i],q2max[i],&effLLpdf,&effDDpdf,&effLLBpdf,&effDDBpdf,printeff);
		cout << "Efficiencies extracted" << endl;
		histFile->cd();


		/**                    FIT AFB                  **/


		afb->setVal(0);
		afbB->setVal(-0.37);
		fL->setVal(0.6);

		RooAbsPdf * corrPdfLL = new RooProdPdf("sigPdfLL"+q2name,"corrPdfLL",*teoPdf,*effLLpdf);
		RooAbsPdf * corrPdfDD = new RooProdPdf("sigPdfDD"+q2name,"corrPdfDD",*teoPdf,*effDDpdf);
		RooAbsPdf * corrPdfLLB = new RooProdPdf("sigPdfLLB"+q2name,"corrPdfLLB",*teoPdfB,*effLLBpdf);
		RooAbsPdf * corrPdfDDB = new RooProdPdf("sigPdfDDB"+q2name,"corrPdfDDB",*teoPdfB,*effDDBpdf);

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

		histFile->cd();
		double fracDDv[2], fracLLv[2];
		double nsigDD, nsigLL;
		RooDataSet * dataLL = getDataAndFrac("LL",q2name,mydata,cutLL,MM,&fracLLv[0],jpsiParsLL,&nsigLL);
		RooDataSet * dataDD = getDataAndFrac("DD",q2name,mydata,cutDD,MM,&fracDDv[0],jpsiParsDD,&nsigDD);
		double nevts = nsigDD+nsigLL;

		cout << fixed << setprecision(3) << fracDDv[0] << "   " << fracDDv[1] << endl;
		RooRealVar * fracLL = new RooRealVar("fracLL","fracLL",fracLLv[0]);
		RooRealVar * fracDD = new RooRealVar("fracDD","fracDD",fracDDv[0]);

		RooAbsPdf * bkgLL = NULL, * bkgLLB = NULL, * bkgDD = NULL, * bkgDDB = NULL;
		buildBkgPdfs(q2min[i],q2max[i],"LL",CutsDef::LLcut,&bkgLL,&bkgLLB);
		buildBkgPdfs(q2min[i],q2max[i],"DD",CutsDef::DDcut,&bkgDD,&bkgDDB);
	
		cout << "Backgrounds extracted" << endl;

		RooAbsPdf * modelLL = new RooAddPdf("modelLL","modelLL",RooArgSet(*corrPdfLL,*bkgLL),*fracLL);
		RooAbsPdf * modelDD = new RooAddPdf("modelDD","modelDD",RooArgSet(*corrPdfDD,*bkgDD),*fracDD);
		RooAbsPdf * modelLLB = new RooAddPdf("modelLLB","modelLLB",RooArgSet(*corrPdfLLB,*bkgLLB),*fracLL);
		RooAbsPdf * modelDDB = new RooAddPdf("modelDDB","modelDDB",RooArgSet(*corrPdfDDB,*bkgDDB),*fracDD);

		// CREATE COMBINED DATASET
		RooDataSet * combData = new RooDataSet(Form("combData_%i",i),"combined data",RooArgSet(*MM,*cosThetaL,*cosThetaB),Index(*samples),Import("DD",*dataDD),Import("LL",*dataLL));

		Str2VarMap params;
		params["fL"] = fL;
		params["afb"] = afb;	
		Str2VarMap paramsB;
		paramsB["afbB"] = afbB;

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

		RooFitResult * res = safeFit(combModel,combData,params,&isInAllowedArea);	
	
		// FIT COS HADRON
		RooSimultaneous * combModelB = new RooSimultaneous(Form("combModelB_%i",i),"",*samples);
		combModelB->addPdf(*modelLLB,"LL");
		combModelB->addPdf(*modelDDB,"DD");

		RooFitResult * resB = safeFit(combModelB,combData,paramsB,&isInAllowedAreaB);

		cout << endl << fixed << setprecision(6) << "AfbB = " << afbB->getVal() << " +/- " << afbB->getError() << endl;
		cout << "Afb = " << afb->getVal() << " +/- " << afb->getError() << endl;
		cout << "fL = " << fL->getVal() << " +/- " << fL->getError() << endl;
		cout << endl;
		cout << "lepton:  " << res->edm() << "   "  << res->covQual() << endl;
		cout << "baryon:  " << resB->edm() << "   "  << resB->covQual() << endl;
		cout << endl;

		TH1F * fLsys = new TH1F(Form("fLsys_%i",i),"fLsys",40,-1,1);
		TH1F * afbsys = new TH1F(Form("afbsys_%i",i),"afbsys",40,-1,1);
		TH1F * afbBsys = new TH1F(Form("afbBsys_%i",i),"afbBsys",40,-1,1);
		TH1F * fLsys_frac = new TH1F(Form("fLsys_frac%i",i),"fLsys",40,-1,1);
		TH1F * afbsys_frac = new TH1F(Form("afbsys_frac%i",i),"afbsys",40,-1,1);
		TH1F * afbBsys_frac = new TH1F(Form("afbBsys_frac%i",i),"afbBsys",40,-1,1);


		RooAbsPdf * mybkgDD_2 = NULL, * mybkgDDB_2 = NULL;
		buildBkgPdfs(q2min[i],q2max[i],"DD",CutsDef::DDcut,&mybkgDD_2,&mybkgDDB_2,"RooKeyPdf");

		//cout << nevts << endl;
		//TRandom3 r(0);

		for(int e = 0; e < nexp; e++)
		{
			histFile->cd();
			RooAbsPdf * toypdf = (RooAbsPdf *)modelDD->Clone();
			Analysis * toy = new Analysis("toy",cosThetaL,modelDD,nevts);
			RooAbsPdf * toypdfB = (RooAbsPdf *)modelDDB->Clone();
			Analysis * toyB = new Analysis("toyB",cosThetaB,modelDDB,nevts);
			
			afb->setVal(0);
			afbB->setVal(-0.37);
			fL->setVal(0.6);

			safeFit(toypdf,toy->GetDataSet("-recalc"),params,&isInAllowedArea);
			safeFit(toypdfB,toyB->GetDataSet("-recalc"),paramsB,&isInAllowedAreaB);
			double def_afb = afb->getVal();
			double def_fL = fL->getVal();
			double def_afbB = afbB->getVal();

			afb->setVal(0);
			afbB->setVal(-0.37);
			fL->setVal(0.6);

			RooAbsPdf * modelDD_2 = new RooAddPdf("modelDD_2","modelDD",RooArgSet(*corrPdfDD,*mybkgDD_2),*fracDD);
			RooAbsPdf * modelDDB_2 = new RooAddPdf("modelDDB_2","modelDDB",RooArgSet(*corrPdfDDB,*mybkgDDB_2),*fracDD);
			safeFit(modelDD_2,toy->GetDataSet("-recalc"),params,&isInAllowedArea);
			safeFit(modelDDB_2,toyB->GetDataSet("-recalc"),paramsB,&isInAllowedAreaB);
			double oth_afb = afb->getVal();
			double oth_fL = fL->getVal();
			double oth_afbB = afbB->getVal();

			fLsys->Fill(oth_fL-def_fL);
			afbsys->Fill(oth_afb-def_afb);
			afbBsys->Fill(oth_afbB-def_afbB);
			

			afb->setVal(0.);
			afbB->setVal(-0.37);
			fL->setVal(0.6);

			//double rdm_frac = r.Gaus(fracDDv[0],fracDDv[1]);
			double rdm_frac = fracDDv[0] + fracDDv[1];
			RooRealVar * fracDD_2 = new RooRealVar("fracDD_2","fracDD_2",rdm_frac);	
			RooAbsPdf * modelDD_3 = new RooAddPdf("modelDD_3","modelDD",RooArgSet(*corrPdfDD,*bkgDD),*fracDD_2);
			RooAbsPdf * modelDDB_3 = new RooAddPdf("modelDDB_3","modelDDB",RooArgSet(*corrPdfDDB,*bkgDDB),*fracDD_2);
			safeFit(modelDD_3,toy->GetDataSet("-recalc"),params,&isInAllowedArea);
			safeFit(modelDDB_3,toyB->GetDataSet("-recalc"),paramsB,&isInAllowedAreaB);

			double frc_afb = afb->getVal();
			double frc_fL = fL->getVal();
			double frc_afbB = afbB->getVal();

			fLsys_frac->Fill(frc_fL-def_fL);
			afbsys_frac->Fill(frc_afb-def_afb);
			afbBsys_frac->Fill(frc_afbB-def_afbB);
			
		}

		afbsysh.push_back(afbsys);
		afbBsysh.push_back(afbBsys);
		fLsysh.push_back(fLsys);
		afbsysh_frac.push_back(afbsys_frac);
		afbBsysh_frac.push_back(afbBsys_frac);
		fLsysh_frac.push_back(fLsys_frac);

	}

	
	for(int q = 0; q < nbins; q++)
	{
		cout << fixed << setprecision(2) << "-------- Bin " << q2min[q] << "-" << q2max[q] << endl;
		cout << fixed << setprecision(5) << "fL sys = " << fLsysh[q]->GetMean() << " +/- " << fLsysh[q]->GetMeanError() << endl;
		cout << "Afb sys = " << afbsysh[q]->GetMean() << " +/- " << afbsysh[q]->GetMeanError() << endl;
		cout << "AfbB sys = " << afbBsysh[q]->GetMean() << " +/- " << afbBsysh[q]->GetMeanError() << endl;
	}

	cout << "#################################################################" << endl;
	for(int q = 0; q < nbins; q++)
	{
		cout << fixed << setprecision(2) << "-------- Bin " << q2min[q] << "-" << q2max[q] << endl;
		cout << fixed << setprecision(5) << "fL sys = " << fLsysh_frac[q]->GetMean() << " +/- " << fLsysh_frac[q]->GetMeanError() << endl;
		cout << "Afb sys = " << afbsysh_frac[q]->GetMean() << " +/- " << afbsysh_frac[q]->GetMeanError() << endl;
		cout << "AfbB sys = " << afbBsysh_frac[q]->GetMean() << " +/- " << afbBsysh_frac[q]->GetMeanError() << endl;
	}

	cout << "#################################################################" << endl;
	for(int q = 0; q < nbins; q++)
	{
		cout << fixed << setprecision(2) << "-------- Bin " << q2min[q] << "-" << q2max[q] << endl;
		cout << fixed << setprecision(5) << "fL sys = " << TMath::Sqrt(TMath::Power(fLsysh_frac[q]->GetMean(),2) + TMath::Power(fLsysh[q]->GetMean(),2) )  << endl;
		cout << "Afb sys = " << TMath::Sqrt(TMath::Power(afbsysh_frac[q]->GetMean(),2) + TMath::Power(afbsysh[q]->GetMean(),2) ) << endl;
		cout << "AfbB sys = " << TMath::Sqrt(TMath::Power(afbBsysh_frac[q]->GetMean(),2) + TMath::Power(afbBsysh[q]->GetMean(),2) ) << endl;
	}

}
int main() {
    bool recutdata=false;
    bool recutmc=false;
    bool remakedatasets=false;
    std::vector<std::string> VariablesToCompare= {"gamma_CL","nSPDHits","Bu_DIRA_OWNPV","Bu_M01"};
    auto BranchesToKeepMC = ControlCuts::BranchesToKeep;
    for(auto branch : VariablesToCompare) {
        if (std::find(BranchesToKeepMC.begin(),BranchesToKeepMC.end(),branch)==std::end(BranchesToKeepMC)) {
            BranchesToKeepMC.push_back(std::move(branch));
        }
    }

    auto BranchesToKeep = ControlCuts::BranchesToKeep;
    for(auto branch : VariablesToCompare) {
        if (std::find(BranchesToKeep.begin(),BranchesToKeep.end(),branch)==std::end(BranchesToKeep)) {
            BranchesToKeep.push_back(std::move(branch));
        }
    }

    if(recutdata) {
        DataFile TwelA(std::getenv("BUKETAPDATAROOT"),Data,Twel,MagAll,buketap,"TriggerCut_SampleA");
        DataFile TwelB(std::getenv("BUKETAPDATAROOT"),Data,Twel,MagAll,buketap,"TriggerCut_SampleB");
        DataFile ElevA(std::getenv("BUKETAPDATAROOT"),Data,Elev,MagAll,buketap,"TriggerCut_SampleA");
        DataFile ElevB(std::getenv("BUKETAPDATAROOT"),Data,Elev,MagAll,buketap,"TriggerCut_SampleB");

        TreeReader* TwelReader = new TreeReader("DecayTree");
        TwelReader->AddFile(TwelA);
        TwelReader->AddFile(TwelB);

        TreeReader* ElevReader = new TreeReader("DecayTree");
        ElevReader->AddFile(ElevA);
        ElevReader->AddFile(ElevB);


        TwelReader->Initialize(BranchesToKeep,"names");
        ElevReader->Initialize(BranchesToKeep,"names");

        auto TwelMinimalFile=std::make_unique<TFile>("TwelMinimalFile.root","RECREATE");
        TTree* TwelMinimalTree=TwelReader->CopyTree("gamma_CL>0.1",-1,"DecayTree");
        TwelMinimalTree->Write();

        auto ElevMinimalFile=std::make_unique<TFile>("ElevMinimalFile.root","RECREATE");
        TTree* ElevMinimalTree=ElevReader->CopyTree("gamma_CL>0.1",-1,"DecayTree");
        ElevMinimalTree->Write();
    }
    if(recutmc) {
        DataFile MCTwel(std::getenv("BUKETAPMCROOT"),MC,Twel,MagAll,buketap,"TriggerCut");
        DataFile MCElev(std::getenv("BUKETAPMCROOT"),MC,Elev,MagAll,buketap,"TriggerCut");

        TreeReader* TwelReaderMC = new TreeReader("DecayTree");
        TwelReaderMC->AddFile(MCTwel);

        TreeReader* ElevReaderMC = new TreeReader("DecayTree");
        ElevReaderMC->AddFile(MCElev);


        TwelReaderMC->Initialize(BranchesToKeepMC,"names");
        ElevReaderMC->Initialize(BranchesToKeepMC,"names");

        auto TwelMinimalFileMC=std::make_unique<TFile>("TwelMinimalFileMC.root","RECREATE");
        TTree* TwelMinimalTreeMC=TwelReaderMC->CopyTree("gamma_CL>0.1",-1,"DecayTree");
        TwelMinimalTreeMC->Write();

        auto ElevMinimalFileMC=std::make_unique<TFile>("ElevMinimalFileMC.root","RECREATE");
        TTree* ElevMinimalTreeMC=ElevReaderMC->CopyTree("gamma_CL>0.1",-1,"DecayTree");
        ElevMinimalTreeMC->Write();
    }
    if(remakedatasets||recutmc||recutdata) {
        RooArgSet* MCVars= new RooArgSet("MCVars");
        RooArgSet* Vars= new RooArgSet("Vars");

        for(auto & Branch : BranchesToKeep) {
            Vars->add(*(HandyFunctions::CreateRealVar(Branch)));
        }

        for(auto & MCBranch:  BranchesToKeepMC) {
            MCVars->add(*(HandyFunctions::CreateRealVar(MCBranch)));
            std::cout<<MCBranch<<std::endl;
        }

        auto TwelMinimalFile = std::make_unique<TFile>("TwelMinimalFile.root");
        TTree* TwelMinimalTree=(TTree*)TwelMinimalFile->Get("DecayTree");
        std::cout<<"Tree Entreies = "<<TwelMinimalTree->GetEntries()<<std::endl;
        RooDataSet* TwelData= new RooDataSet("TwelData","TwelData",*Vars,Import(*TwelMinimalTree));
        std::cout<<"Events in Dataset= "<<TwelData->sumEntries()<<std::endl;

        auto ElevMinimalFile = std::make_unique<TFile>("ElevMinimalFile.root");
        TTree* ElevMinimalTree=(TTree*)ElevMinimalFile->Get("DecayTree");
        std::cout<<"Tree Entreies = "<<ElevMinimalTree->GetEntries()<<std::endl;
        RooDataSet* ElevData= new RooDataSet("ElevData","ElevData",*Vars,Import(*ElevMinimalTree));
        std::cout<<"Events in Dataset= "<<ElevData->sumEntries()<<std::endl;

        auto TwelMinimalFileMC = std::make_unique<TFile>("TwelMinimalFileMC.root");
        TTree* TwelMinimalTreeMC=(TTree*)TwelMinimalFileMC->Get("DecayTree");
        std::cout<<"Tree Entreies = "<<TwelMinimalTreeMC->GetEntries()<<std::endl;
        RooDataSet* TwelDataMC= new RooDataSet("TwelDataMC","TwelDataMC",*Vars,Import(*TwelMinimalTreeMC));
        std::cout<<"Events in Dataset= "<<TwelDataMC->sumEntries()<<std::endl;
        auto ElevMinimalFileMC = std::make_unique<TFile>("ElevMinimalFileMC.root");
        TTree* ElevMinimalTreeMC=(TTree*)ElevMinimalFileMC->Get("DecayTree");
        std::cout<<"Tree Entreies = "<<ElevMinimalTreeMC->GetEntries()<<std::endl;
        RooDataSet* ElevDataMC= new RooDataSet("ElevDataMC","ElevDataMC",*Vars,Import(*ElevMinimalTreeMC));
        std::cout<<"Events in Dataset= "<<ElevDataMC->sumEntries()<<std::endl;

        TwelMinimalFile->Close();
        ElevMinimalFile->Close();
        TwelMinimalFileMC->Close();
        ElevMinimalFileMC->Close();
        auto DataSetCache=std::make_unique<TFile>("DataSetCache.root","RECREATE");
        gDirectory->pwd();
        TwelData->Write();
        ElevData->Write();
        TwelDataMC->Write();
        ElevDataMC->Write();
    }

    TFile* DataSetCache= new TFile("DataSetCache.root");
    RooDataSet* Data12=SafeGetDataSet(DataSetCache,"TwelData");
    RooDataSet* Data11=SafeGetDataSet(DataSetCache,"ElevData");
    RooDataSet* MC12=SafeGetDataSet(DataSetCache,"TwelDataMC");
    RooDataSet* MC11=SafeGetDataSet(DataSetCache,"ElevDataMC");

    RooRealVar * BuMass= new RooRealVar("Bu_DTF_MF","Bu_DTF_MF",5000.0,5500.0);
    RooRealVar* BkgP1= new RooRealVar("BkgP1","BkgP1",-1.0,-10.0,10.0);
    RooRealVar* BkgP2= new RooRealVar("BkgP2","BkgP2",1.0,-10.0,10.0);
    RooChebychev* BkgPdf= new RooChebychev("BkgPdf","BkgPdf",*BuMass,RooArgList(*BkgP1,*BkgP2));

    BkgPdf->fitTo(*Data12,Range(5000.0,5200.));

    RooPlot* BFrame = BuMass->frame(Bins(50));
    Data12->plotOn(BFrame);
    BkgPdf->plotOn(BFrame);
    BkgPdf->paramOn(BFrame);
    TCanvas C;
    BFrame->Draw();

    C.SaveAs("BFrame.pdf");


}
int main(int argc, char** argv)
{
	string dataType = "12";
	//if(argc > 1) if((string)argv[1] == "11") dataType = "11";
	
	NeuroBayesTeacher* nb = NeuroBayesTeacher::Instance();
	
	nb->NB_DEF_TASK("CLASSIFICATION");
	
	//setup network topology
	int nvar = 20;  // Set this to number of inputs to your NN
	

	char ** varnames = new char*[nvar];
	varnames[0]  = "chi2_DTF";
	varnames[1]  = "Lb_TAU";
	varnames[2]  = "Lb_DIRA_OWNPV";
	varnames[3]  = "Lb_IPCHI2_OWNPV";
	varnames[4]  = "max_mu_IPCHI2_OWNPV";
	varnames[5]  = "min_mu_TRACKCHI2";
	varnames[6]  = "min_mu_PID";
	varnames[7]  = "min_mu_PID";
	varnames[8]  = "LL_Lambda0_IPCHI2_OWNPV";
	varnames[9] = "LL_Lambda0_FDCHI2_OWNPV";
	varnames[10] = "LL_Lambda0_PT";
	varnames[11] = "DD_Lambda0_IPCHI2_OWNPV";
	varnames[12] = "DD_Lambda0_FDCHI2_OWNPV";
	varnames[13] = "DD_Lambda0_PT";
	varnames[14]  = "DD_pplus_IPCHI2_OWNPV";
	varnames[15]  = "DD_piminus_IPCHI2_OWNPV";
	varnames[16]  = "DD_piminus_PT";
	varnames[17]  = "LL_pplus_IPCHI2_OWNPV";
	varnames[18]  = "LL_piminus_IPCHI2_OWNPV";
	varnames[19]  = "LL_piminus_PT";

	nb->NB_DEF_NODE1(nvar+1);
	nb->NB_DEF_NODE2(nvar);      // nodes in hidden layer 
	nb->NB_DEF_NODE3(1);       // nodes in output layer

	nb->NB_DEF_TASK("CLA");    // binominal classification

	nb->NB_DEF_PRE(822);
	//  nb->NB_DEF_PRE(812);
	nb->NB_DEF_REG("REG");           // 'OFF','REG' (def) ,'ARD','ASR','ALL'
	nb->NB_DEF_LOSS("ENTROPY");      // 'ENTROPY'(def),'QUADRATIC'
	nb->NB_DEF_METHOD("BFGS");
	nb->NB_DEF_SHAPE("DIAG");
	nb->NB_DEF_LEARNDIAG(1);

	nb->NB_DEF_RTRAIN(1.0);          // use 70% of events for training
	//  nb->NB_DEF_EPOCH(200);           // weight update after n events

	nb->NB_DEF_SPEED(2.0);           // multiplicative factor to enhance global learning speed
	nb->NB_DEF_MAXLEARN(1.0);        // multiplicative factor to limit the global learning speed in any direction, this number should be smaller than NB_DEF_SPEED

	nb->NB_DEF_ITER(100);             // number of training iteration
	//nb->NB_DEF_ITER(0);             // number of training iteration

    //int i = 4701;
	//int j = 29; 
	//nb->NB_RANVIN(i,j,2);            // random number seed initialisation, i has to be an odd number, the third argument is a debugging flag

	nb->SetOutputFile(("expert_"+dataType+".nb").c_str());  // expert file
	SetupNNPrepro(nb);
	
	// MC
	TreeReader* reader = new TreeReader("tree");
	reader->AddFile("/afs/cern.ch/work/p/pluca/Lmumu/weighted/Lb2Lmumu_MC_Pythia8_NBweighted_new.root");
	reader->Initialize();

	
	// We take all signal and 20% of background
	
	nb->SetTarget(1);
	int ntot = reader->GetEntries();
	int npassedMC = 0;
	
	cout << "Read in " << ntot << " events" << endl;
	
	int nstepMC = 5;
	//if(dataType=="11") nstepMC = 5;

	TFile ofile("/afs/cern.ch/work/p/pluca/Lmumu/weighted/samplesMVA_"+(TString)dataType+".root","recreate");
	TTree * sigTrainSample = new TTree("sigTrainSample","");
	reader->BranchNewTree(sigTrainSample);
	TTree * sigTestSample = new TTree("sigTestSample","");
	reader->BranchNewTree(sigTestSample);

	for(int event = 0; event < ntot; event++)
	{
		reader->GetEntry(event);
		
		if( TrueID(reader) && TriggerPassed(reader))
		{
			if( event%nstepMC==0 && npassedMC <= 4e4 )
			{
				npassedMC++;
				float InputArray[nvar+1];
				fillInputArray(reader,InputArray);
				if(isnan(InputArray[0])) continue;
				nb->SetWeight(reader->GetValue("Lb_weight"));
				nb->SetNextInput(nvar,InputArray);
				sigTrainSample->Fill();
			}
			else sigTestSample->Fill();
		}
	}


	// Data
	TreeReader* reader2 = new TreeReader("tree");
	reader2->AddFile("/afs/cern.ch/work/p/pluca/Lmumu/weighted/Lb2Lmumu_CL_NBweighted.root");
	reader2->Initialize();

	TTree * bkgTrainSample = new TTree("bkgTrainSample","");
	reader2->BranchNewTree(bkgTrainSample);
	TTree * bkgTestSample = new TTree("bkgTestSample","");
	reader2->BranchNewTree(bkgTestSample);

	nb->SetTarget(0);
	int ntot2 = reader2->GetEntries();
	int npassed = 0;
	
	cout << "Read in " << ntot2 << " events" << endl;
	int nstep = 2;
	//if(dataType=="11") nstep = 2;
	
	for(int event = 0; event < ntot2; event++)
	{
		reader2->GetEntry(event);
		
		double massLb = reader2->GetValue("Lb_MassConsLambda_M",0);
		double massJpsi = reader2->GetValue("J_psi_1S_MM");
		if(massLb > 6000 && TMath::Abs(massJpsi - 3096) > 100 && TMath::Abs(massJpsi - 3686) > 90 && TriggerPassed(reader2))
		{
			if(event%nstep==0 && npassed <=4e4)
			{
				float InputArray[100];
				npassed++;
				fillInputArray(reader2,InputArray);
				if(isnan(InputArray[0])) continue;
				nb->SetWeight(1.);
				nb->SetNextInput(nvar,InputArray);
				bkgTrainSample->Fill();
			}
			else bkgTestSample->Fill();
		}
	}
	
	bkgTrainSample->Write();
	bkgTestSample->Write();
	sigTestSample->Write();
	sigTrainSample->Write();
	ofile.Close();

	cout << "\nData used = " << npassed << ", MC used = " << npassedMC << endl;
	
	cout << "Train the Network\n" << endl;
	nb->TrainNet();
	nb->nb_correl_signi(varnames,"correl_signi.txt","correl_signi.html");

	cout << "\nData used = " << npassed << ", MC used = " << npassedMC << endl;
	
	return 0;
}