Beispiel #1
0
void exportHistograms(){
	TreeReader reader;
	reader.openSeries(257,"D");
	reader.openSeries(258,"D");
	reader.openSeries(260,"D");
	reader.openSeries(261,"D");
	reader.openSeries(262,"D");
	TH1F hist1("hist1","hist1",100,0,30000);
	TH1F hist2("hist2","hist2",100,0,30000);
	TH1F hist3("hist3","hist3",100,0,30000);
	for(Long64_t i=0;i<reader.tree->GetEntries();i++){
		reader.tree->GetEntry(i);
		if(fabs(reader.recon.t_gamma[2]-600)<10){
			hist1.Fill(reader.recon.E_gamma[2]);
		}
		if(fabs(reader.recon.t_gamma[6]-600)<10){
			hist2.Fill(reader.recon.E_gamma[6]);
		}
		if(fabs(reader.recon.t_gamma[13]-600)<10){
			hist3.Fill(reader.recon.E_gamma[13]);
		}
	}
	ofstream output(Form("%s/output.csv",RDKANAL));
	output<<"bin center,det02,det06,det16"<<endl;
	for(Long64_t i=1;i<=100;i++){
		output<<hist1.GetBinCenter(i)<<","<<hist1.GetBinContent(i)<<",";
		output<<hist2.GetBinContent(i)<<","<<hist3.GetBinContent(i)<<endl;
	}
	output.close();
}
int main3(int argc, const char *argv[])
{
	TreeReader tr;
	//tr.ParseTree("simple_out.txt", "tes.txt");
	
	tr.ParseTree(argv[1], argv[2]);
	//int x;
	//std::cin >> x;
    return 0;
}
Beispiel #3
0
int main(void) {
	TreeReader tr;
	string test;
	test = "((a:2,b:2):3,(c:4,d:4):1):1;";

/*
	ifstream infile("../../big_geo/final_ml.tre.cn.rr.pr.nw.pathd8.bgstates.tre");
	if (!infile){
		cerr << "Could not open file." << endl;
		return 1;
	}
	vector<string> lines;
	string line;
	while (getline(infile, line)){
		lines.push_back(line);
	}
	infile.close();

	test = lines[0];
*/

	Tree tree = *tr.readTree(test);
	cout << tree.getNodeCount() << endl;
	cout << tree.getRoot()->getNewick(true) << ";" << endl;
	cout << tree.getRoot()->getNewick(true,"number") << ";" << endl;
	string a = "c";
	tree.pruneExternalNode(tree.getExternalNode(a));
	cout << tree.getRoot()->getNewick(true) << ";" << endl;

	StringNodeObject sno("...a node object");
	tree.getRoot()->assocObject("test",sno);
	cout << tree.getRoot()->getNewick(true,"test") << ";" << endl;

	cout << *((StringNodeObject*) (tree.getRoot()->getObject("test"))) << endl;

	VectorNodeObject<int> vno;
	vno.push_back(1);vno.push_back(2);
	tree.getRoot()->assocObject("testvno",vno);

	cout << ((VectorNodeObject<int> *) (tree.getRoot()->getObject("testvno")))->at(0) << endl;

	a = "b";
	tree.setHeightFromRootToNodes();
	cout << tree.getExternalNode(a)->getHeight() << endl;
	cout << tree.getRoot()->getHeight() << endl;
	cout << tree.getInternalNode(0)->getHeight() << endl;
	cout << tree.getInternalNode(1)->getHeight() << endl;
	//for(int i=0;i<tree.getInternalNodeCount();i++){
		//cout << tree.getInternalNode(i).getBL() << endl;
	//}
	return EXIT_SUCCESS;
}
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();
  }
    
    

}
Beispiel #5
0
void InputReader::readMultipleTreeFile(string filename, vector<Tree *> & ret){
	TreeReader tr;
	ifstream ifs( filename.c_str() );
	string temp;
	int count = 1;
	while( getline( ifs, temp ) ){
		if(temp.size() > 1){
			Tree * intree = tr.readTree(temp);
			intree->setNewickStr(temp);
			cout << "Tree "<< count <<" has " << intree->getExternalNodeCount() << " leaves." << endl;
			ret.push_back(intree);
			count++;
		}
	}
}
Beispiel #6
0
void listEvents(){
	Recon recon;
	//TFile f(Form("%s/cal.root",RDKANAL));
	//CalibrationList *list=(CalibrationList*)f.Get("CalibrationList");
	TString path=Form("%s/calibration/TCfit_511keV_calibration_21Feb11.dat",RDKANAL);
	CalibrationList *list=new CalibrationList(path);
	TreeReader reader;
	reader.reset(kTRUE);
	//NData ndata=reader.openList(Form("%s/runlist.csv",RDKANAL));
	NData ndata=reader.openSeries(256,"S");
	//NData ndata=reader.openSeries(TreeReader::n1400,TreeReader::all1400,"S");
	logNdat(ndata);
	ofstream log(Form("%s/eventLists/list.csv",RDKANAL));
	log<<"Series,Run,EventNum,PeakHeight,Energy,DeltaTime"<<endl;
	Int_t series=0,run=0,evnt=0;
	for(Long64_t i=0;i<reader.tree->GetEntries();i++){
		if(i%10000==0){
			cout<<i<<endl;
		}
		reader.tree->GetEntry(i);
		//if(series==reader.entry.nseries && run==reader.entry.nrun){
		//	reader.entry.nevent=++evnt;
		//}else{
		//	series=reader.entry.nseries;
		//	run=reader.entry.nrun;
		//	evnt=0;
		//}
		recon=list->calibrate(reader.entry,reader.recon);
		Int_t delta_t=recon.t_gamma[CH]-recon.t_e-PEAK;
		if(recon.E_gamma[CH]>=MIN && recon.E_gamma[CH]<=MAX && recon.t_p-recon.t_e<650
			&& delta_t>-ONPEAK && delta_t<=ONPEAK && recon.E_e<30000 && recon.E_p>300 && recon.E_p<1000){
			log<<reader.entry.nseries<<","<<reader.entry.nrun<<","<<reader.entry.nevent<<",";
			log<<reader.recon.E_gamma[CH]<<","<<recon.E_gamma[CH]<<",";
			log<<(recon.t_gamma[CH]-recon.t_e)<<endl;
		}
	}
	log.close();
	delete list;
	//f.close();
	gSystem->ChangeDirectory(WORKDIR);
}
Beispiel #7
0
void secondPass(){
	TreeReader reader;
	reader.openSeries(256,"S");
	Int_t i=1,r0,r1;
	Long64_t t0,t1;
	reader.tree->GetEntry(0);
	r0=reader.entry.nrun;
	t0=150*reader.entry.timestamp[0];
	reader.tree->GetEntry(i);
	r1=reader.entry.nrun;
	t1=150*reader.entry.timestamp[1];
	while(r0==r1){
		if(t1-t0<bitError && t0-t1<bitError){
			g.SetPoint(i-1,i-1,t1-t0);
		}else{
			g.SetPoint(i-1,i-1,0);
		}
		reader.tree->GetEntry(++i);
		r0=r1;
		t0=t1;
		r1=reader.entry.nrun;
		t1=150*reader.entry.timestamp[0];
	}
}
Beispiel #8
0
int main(int argc, char **argv)
{
	bool printSw = true;
	//TString massModel = "Gauss-m[5622]";
	string massModel = "DCB-m[5622]";
	TString effbase = "/afs/cern.ch/user/p/pluca/work/Lb/Lmumu/results/";
	bool printeff = false;
	TString dodata = "data";
	bool fitsingle = false;
	TString wstr = "physRate_polp006";
	TString decayToDo = "Lb2Lmumu";
	if(dodata=="genMC") wstr += "_noDecay";

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


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

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

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

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


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

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

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

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

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

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

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

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

		ceff->cd();

		/**                    FIT EFFICIENCY                  **/

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

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

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


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

			/**                    FIT AFB                  **/


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

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

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

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

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

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

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

			RooDataSet * sdataDD, * sdataLL;

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

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

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

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

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


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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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


}
Beispiel #11
0
int main(int argc, char * argv[]) {
    
    log_call(argc, argv);
    
    bool datafileset = false; // not used
    bool treefileset = false; // not used
    bool conffileset = false;
    bool logfileset = false;
    bool outancfileset = false;
    bool outstochtimefileset = false;
    bool outstochnumfileset = false;
    bool outstochnumanyfileset = false;
    bool datawide = false;
    bool periodsset = false;
    bool dataz = false; //the datafile will have probabilities
    char * conff = NULL;
    char * treef = NULL;
    char * dataf = NULL;
    char * logf = NULL;
    char * outanc = NULL;
    char * outnum = NULL;
    char * outnumany = NULL;
    char * outtime = NULL;
    string periodstring;
    vector<string> ptokens;
    vector<double> period_times;
    
    while (1) {
        int oi = -1;
        int c = getopt_long(argc, argv, "d:t:c:o:n:m:a:l:p:hVwz", long_options, &oi);
        if (c == -1) {
            break;
        }
        switch(c) {
            case 'd':
                datafileset = true;
                dataf = strdup(optarg);
                check_file_exists(dataf);
                break;
            case 'z':
                dataz = true;
                datawide = true;
                break;
            case 'w':
                datawide = true;
                break;
            case 't':
                treefileset = true;
                treef = strdup(optarg);
                check_file_exists(treef);
                break;
            case 'c':
                conffileset = true;
                conff = strdup(optarg);
                check_file_exists(conff);
                break;
            case 'o':
                outancfileset = true;
                outanc = strdup(optarg);
                break;
            case 'n':
                outstochnumfileset = true;
                outnum = strdup(optarg);
                break;
            case 'm':
                outstochtimefileset = true;
                outtime = strdup(optarg);
                break;
            case 'a':
                outstochnumanyfileset = true;
                outnumany = strdup(optarg);
                break;
            case 'p':
                periodsset = true;
                periodstring = (strdup(optarg));
                parse_comma_list(periodstring, period_times);
                break;
            case 'l':
                logfileset = true;
                logf = strdup(optarg);
                break;
            case 'h':
                print_help();
                exit(0);
            case 'V':
                cout << versionline << endl;
                exit(0);
            default:
                print_error(argv[0], (char)c);
                exit(0);
        }
    }
    
    ofstream * logout = NULL;
    ostream * loos = NULL;
    
    if (logfileset == true) {
        logout = new ofstream(logf);
        loos = logout;
    } else {
        loos = &cout;
    }

    if (conffileset == false) {
        cerr << "right now, you need to have a conf file. to change soon." << endl;
        print_help();
        exit(0);
    }

    bool verbose = true;
    string outfile_stochnum_any ="";
    string ratematrixfile = "";
    vector<vector<double> > ratematrix;
    bool estimate = true;
    map<string,vector<string> > mrcas;
    vector<string> stochtime;
    vector<string> stochnumber;
    vector<string> stochnumber_any;
    vector<string> ancstates;
    string freeparams = "_one_"; //right now, just _all_ or _one_

    /*************
     * read the configuration file
     **************/
    ifstream ifs(conff);
    string line;
    while (getline(ifs, line)) {
        if (line.size() > 1) {
            if (strcmp( (&line[0]), "#") != 0) {
            //if ((&line[0]) != "#") {
                vector<string> tokens;
                string del("=");
                tokens.clear();
                tokenize(line, tokens, del);
                for (unsigned int j=0; j < tokens.size(); j++) {
                    trim_spaces(tokens[j]);
                }
                if (!strcmp(tokens[0].c_str(), "freeparams")) {
                    freeparams = tokens[1];
                } else if (!strcmp(tokens[0].c_str(),  "outstnum_any")) {
                    outfile_stochnum_any = tokens[1];
                } else if (!strcmp(tokens[0].c_str(),  "ratematrix")) {
                    ratematrixfile = tokens[1];
                    if (ratematrixfile == "d" || ratematrixfile == "D") {
                        ratematrixfile = "";
                    }
                    estimate =false;
                } else if (!strcmp(tokens[0].c_str(), "mrca")) {
                    /*
                     * need to make sure that the mrca exist in the tree, 
                     * that the names are correct
                     */
                    vector<string> searchtokens;
                    tokenize(tokens[1], searchtokens, ",     ");
                    for (unsigned int j=0; j < searchtokens.size(); j++) {
                        trim_spaces(searchtokens[j]);
                    }
                    vector<string> mrc;
                    for (unsigned int j=1; j < searchtokens.size(); j++) {
                        mrc.push_back(searchtokens[j]);
                    }
                    mrcas[searchtokens[0]] = mrc;
                } else if (!strcmp(tokens[0].c_str(), "stochtime")) {
                    vector<string> searchtokens;
                    tokenize(tokens[1], searchtokens, ",     ");
                    for (unsigned int j=0; j < searchtokens.size(); j++) {
                        trim_spaces(searchtokens[j]);
                        stochtime.push_back(searchtokens[j]);
                    }
                } else if (!strcmp(tokens[0].c_str(), "stochnumber")) {
                    vector<string> searchtokens;
                    tokenize(tokens[1], searchtokens, ",     ");
                    for (unsigned int j=0; j < searchtokens.size(); j++) {
                        trim_spaces(searchtokens[j]);
                        stochnumber.push_back(searchtokens[j]);
                    }
                } else if (!strcmp(tokens[0].c_str(), "stochnumber_any")) {
                    vector<string> searchtokens;
                    tokenize(tokens[1], searchtokens, ",     ");
                    for (unsigned int j=0; j < searchtokens.size(); j++) {
                        trim_spaces(searchtokens[j]);
                        stochnumber_any.push_back(searchtokens[j]);
                    }
                } else if (!strcmp(tokens[0].c_str(), "ancstates")) {
                    vector<string> searchtokens;
                    tokenize(tokens[1], searchtokens, ",     ");
                    for (unsigned int j=0; j < searchtokens.size(); j++) {
                        trim_spaces(searchtokens[j]);
                        ancstates.push_back(searchtokens[j]);
                    }
                }
            }
        }
    }
    if (verbose) {
        (*loos) << "finished reading config file" << endl;
    }
    /**
     * read the data file
     */

    vector<Sequence> seqs;
    Sequence seq;
    ifstream * fstr = new ifstream(dataf);
    istream * pios = fstr;
    line = "";
    int ft = test_seq_filetype_stream(*pios,line);
    while (read_next_seq_from_stream(*pios,ft,line,seq)) {
    //(*loos) << seq.get_sequence() << endl;
        seqs.push_back(seq);
    }
    //fasta has a trailing one
    if (ft == 2) {
        seqs.push_back(seq);
    }
    if (verbose) {
        (*loos) << "taxa: " << seqs.size() << endl;
    }

    /**
     * read the tree file
     */
    TreeReader tr;
    vector<Tree *> trees;
    ifstream infile2(treef);
    if (!infile2) {
        cerr << "Could not open treefile." << endl;
        return 1;
    }
    line = "";
    while (getline(infile2, line)) {
        if (line.length() > 5) {
            trees.push_back(tr.readTree(line));
        }
    }
    infile2.close();
    if (verbose) {
        (*loos) << "trees: "<< trees.size() << endl;
    }
    
    /**
     * process the data
     * datawide means 
     * 
     * NOT datawide means
     */
    int nstates;
    int nsites;
    if (datawide) {
        if (dataz == false) {
            nstates = seqs[0].get_sequence().length();
        } else {
            vector<string> searchtokens;
            tokenize(seqs[0].get_sequence(), searchtokens, ",");
            nstates = searchtokens.size();
        }
        nsites = 1;
    } else {
        int maxstate=1;
        vector<string> searchtokens;
        tokenize(seqs[0].get_sequence(), searchtokens, " ");
        for (unsigned int j=0; j < searchtokens.size(); j++) {
            trim_spaces(searchtokens[j]);
        }
        nsites = searchtokens.size();
        if (verbose) {
            (*loos) << "nsites: " << nsites << endl;
        }
        for (unsigned int se = 0;se<seqs.size();se++) {
            searchtokens = vector<string> ();
            tokenize(seqs[se].get_sequence(), searchtokens, "     ");
            for (unsigned int j=0; j < searchtokens.size(); j++) {
                trim_spaces(searchtokens[j]);
                int pos = atoi(searchtokens[j].c_str());
                if (pos > maxstate) {
                    maxstate = pos;
                }
            }
        }
        nstates = maxstate+1;//TODO this can be determined by largest number +1
    }
    if (verbose) {
        (*loos) << "total number of states in dataset: " << nstates << endl;
    }
    //reading ratematrixfile
    if (ratematrixfile.size() > 1) {
        ratematrix = processRateMatrixConfigFile(ratematrixfile,nstates);
    }
    //end ratematrixfile

    ofstream ancout;
    ofstream stnumout;
    ofstream sttimeout;
    ofstream sttnumout_any;
    
    if (ancstates.size() > 0 && outancfileset == true) {
        ancout.open(outanc,ios::out);
        ancout << "site\ttree\tMRCA\tlnL";
        for (int i=0; i < nstates; i++) {
            ancout << "\tstate_" << i+1;
        }
        ancout << endl;
    }
    if (stochnumber.size() > 0 && outstochnumfileset == true) {
        stnumout.open(outnum,ios::out);
        stnumout << "site\ttree\tMRCA\tlnL";
        for (int i=0; i < nstates; i++) {
            for (int j=0; j < nstates; j++) {
                if (i != j) {
                    stnumout << "\tstate_" << i+1 << "->state_" << j+1;
                }
            }
        }
        stnumout << endl;
    }
    if (stochtime.size() > 0 && outstochtimefileset == true ) {
        sttimeout.open(outtime,ios::out);
        sttimeout << "site\ttree\tMRCA\tlnL";
        for (int i=0; i < nstates; i++) {
            sttimeout << "\tstate_" << i+1;
        }
        sttimeout << endl;
    }
    if (stochnumber_any.size() > 0 && outstochnumanyfileset == true) {
        sttnumout_any.open(outnumany,ios::out);
        sttnumout_any << "site\ttree\tMRCA\tlnL";
        sttnumout_any << "\tanystate";
        sttnumout_any << endl;
    }
    
    for (int n = 0; n < nsites; n++) {
        (*loos) << "site: " << n+1 << endl;
        /*
         * this converts the data and is a little long to accomodate datasets
         * with sites that don't have all the states but the results can still
         * be printed to the same outfile for analysis after
         */
        //need to put the data into a wide view
        vector<Sequence> runseqs;
        int nstates_site_n;
        vector<int> existing_states(nstates,0);
        if (datawide == false) {
            for (unsigned int se = 0;se<seqs.size();se++) {
                vector<string> searchtokens;
                tokenize(seqs[se].get_sequence(), searchtokens, "     ");
                for (unsigned int j=0; j < searchtokens.size(); j++) {
                    trim_spaces(searchtokens[j]);
                }
                string tseqs(nstates,'0');
                if (searchtokens[n]=="?") {
                    for (int mse = 0; mse < nstates; mse++) {
                    tseqs.replace(mse,1,"1");
                    }
                } else {
                    int pos = atoi(searchtokens[n].c_str());
                    tseqs.replace(pos,1,"1");
                }
                for (int i=0; i < nstates; i++) {
                    if (tseqs.at(i) =='1') {
                        existing_states[i] = 1;
                    }
                }
                Sequence tse =Sequence(seqs[se].get_id(),tseqs,true);
                runseqs.push_back(tse);
            }
            nstates_site_n = sum(existing_states);
        } else {
            runseqs = seqs;
            if (dataz == false) {
                for (unsigned int se=0; se < seqs.size(); se++) {
                    for (int i=0; i < nstates; i++) {
                        if (seqs[se].get_sequence().at(i) =='1') {
                            existing_states[i] = 1;
                        }
                    }
                }
                nstates_site_n = sum(existing_states);
            } else {
                for (int i=0; i < nstates; i++) {
                    existing_states[i] = 1;
                }
                nstates_site_n = nstates;
            }
        }
        //mapping the existing states to the full states
        //int statecnt = 0; // not used
        for (int i=nstates-1; i >= 0; i--) {
            if (existing_states[i] == 1) {
                continue;
            } else {
                for (unsigned int se=0; se < runseqs.size(); se++) {
                    runseqs[se].set_sequence(runseqs[se].get_sequence().erase(i,1));
                }
            }
        }

        if (verbose) {
            (*loos) <<"states: " << nstates_site_n << endl;
            (*loos) << "trees: ";
        }
        for (unsigned int i=0; i < trees.size(); i++) {
            if (verbose) {
                (*loos) << i << endl;
            }
            vector<RateModel> rms;
            RateModel rm(nstates_site_n);
            StateReconstructor sr(rm,rms);
            rm.setup_P(0.1,false);
            if (periodsset == true) {
                rms.push_back(rm);
                for (unsigned int p=1; p < period_times.size(); p++) {
                    RateModel rm2(nstates_site_n);
                    rm2.setup_P(0.1,false);
                    rms.push_back(rm2);
                }
                sr.set_periods(period_times,rms);
            }
            sr.set_store_p_matrices(false);
            Tree * tree = trees[i];
            if (verbose) {
                (*loos) << "tips: "<< tree->getExternalNodeCount() << endl;
            }
            sr.set_tree(tree);
            if (periodsset == true) {
                sr.set_periods_model();
            }
            //checking that the data and the tree have the same names
            if (checkdata(tree,runseqs) == 0) {
                exit(0);
            }
            bool same;
            if (dataz == false) {
                same = sr.set_tip_conditionals(runseqs);
            } else {
                same = sr.set_tip_conditionals_already_given(runseqs);
            }
            if (same == true) {
                (*loos) << "skipping calculation" <<endl;
                continue;
            }
            double finallike; Superdouble totlike_sd;
            if (periodsset == false) {
                mat free_var(nstates_site_n,nstates_site_n);
                free_var.fill(0);
                int ct = 0;
                if (freeparams == "_one_") {
                    ct = 1;
                } else if (freeparams == "_all_") {
                    ct = 0;
                    for (int k=0; k < nstates_site_n; k++) {
                        for (int j=0; j < nstates_site_n; j++) {
                            if (k != j) {
                                free_var(k,j) = ct;
                                ct += 1;
                            }
                        }
                    }
                }
                if (verbose) {
                    (*loos) << free_var << endl;
                    (*loos) << ct << endl;
                }
                rm.neg_p = false;
                cout << "likelihood: " << sr.eval_likelihood() << endl;
                //estimating the optimal rates
                if (estimate) {//optimize
                    optimize_sr_nlopt(&rm,&sr,&free_var,ct);
                } else { // requires that the ratematrix is available
                    for (int i=0; i < nstates_site_n; i++) {
                        for (int j=0; j < nstates_site_n; j++) {
                            free_var(i,j) = ratematrix[i][j];
                        }
                    }
                }
                //end estimating
                if (verbose) {
                    (*loos) << free_var << endl;
                }
                rm.setup_Q(free_var);
                sr.set_store_p_matrices(true);
                finallike = sr.eval_likelihood();
                if (verbose) {
                    (*loos) << "final_likelihood: " << finallike << endl;
                }
            } else { //optimize with periods
                vector<mat> periods_free_var(period_times.size());
                int ct = 0;
                if (freeparams == "_one_") {
                    ct = 1;
                    for (unsigned int s=0; s < period_times.size(); s++) {
                        mat free_var(nstates_site_n,nstates_site_n);free_var.fill(0);
                        periods_free_var[s] = free_var;
                    }
                } else if (freeparams == "_all_") {
                    ct = 0;
                    for (unsigned int s=0; s < period_times.size(); s++) {
                        mat free_var(nstates_site_n,nstates_site_n);free_var.fill(0);
                        for (int k=0; k < nstates_site_n; k++) {
                            for (int j=0; j < nstates_site_n; j++) {
                            if (k != j) {
                                free_var(k, j) = ct;
                                ct += 1;
                            }
                            }
                        }
                        periods_free_var[s] = free_var;
                    }
                }
                if (verbose) {
                    for (unsigned int s=0; s < period_times.size(); s++) {
                        (*loos) << periods_free_var[s] << endl;
                    }
                    (*loos) << ct << endl;
                }
                rm.neg_p = false;
                cout << "likelihood: " << sr.eval_likelihood() << endl;
                optimize_sr_periods_nlopt(&rms,&sr,&periods_free_var,ct);
                if (verbose) {
                    for (unsigned int s=0; s < period_times.size(); s++) {
                        (*loos) << periods_free_var[s] << endl;
                    }
                    (*loos) << ct << endl;
                    cout << "////////////////////////" << endl;
                }
                for (unsigned int s=0; s < period_times.size(); s++) {
                    rms[s].setup_Q(periods_free_var[s]);
                }
                sr.set_store_p_matrices(true);
                finallike = sr.eval_likelihood();
                if (verbose) {
                    (*loos) << "final_likelihood: " << finallike << endl;
                }
                cout << "period set and so no ancestral states just yet" << endl;
                continue;
            }
            if (verbose) {
                (*loos) << "ancestral states" <<endl;
            }
            sr.prepare_ancstate_reverse();
            for (unsigned int j=0; j < ancstates.size(); j++) {
            if (ancstates[j] == "_all_") {
                vector<Superdouble> lhoods;
                for (int l=0; l < tree->getInternalNodeCount(); l++) {
                    lhoods = sr.calculate_ancstate_reverse_sd(*tree->getInternalNode(l));
                    totlike_sd = calculate_vector_Superdouble_sum(lhoods);

                    //bool neg = false; // not used
                    int excount = 0;
                    double highest = 0;
                    int high = 0;
                    for (int k=0; k < nstates; k++) {
                        if (existing_states[k] == 1) {
                            if (double(lhoods[excount]/totlike_sd) > highest) {
                                highest= double(lhoods[excount]/totlike_sd);
                                high = k;
                            }
                            excount += 1;
                        }
                    }
                    std::string s;
                    std::stringstream out;
                    out << high;
                    tree->getInternalNode(l)->setName(out.str());
                }
                ancout << getNewickString(tree) << endl;
            } else {
                vector<Superdouble> lhoods;
                if (verbose) {
                    (*loos) <<"node: " << tree->getMRCA(mrcas[ancstates[j]])->getName() << "\tmrca: " << ancstates[j] <<  endl;
                }
                ancout << n+1 << "\t" << i+1 << "\t" << ancstates[j] << "\t" << finallike;
                lhoods = sr.calculate_ancstate_reverse_sd(*tree->getMRCA(mrcas[ancstates[j]]));
                totlike_sd = calculate_vector_Superdouble_sum(lhoods);
                bool neg = false;
                int excount = 0;
                for (int k=0; k < nstates; k++) {
                    if (existing_states[k] == 1) {
                        if (verbose) {
                            (*loos) << double(lhoods[excount]/totlike_sd) << " ";//"(" << lhoods[excount] << ") ";
                        }
                        ancout << "\t" << double(lhoods[excount]/totlike_sd);
                        if (double(lhoods[excount]/totlike_sd) < 0)
                        neg = true;
                        excount += 1;
                    } else {
                        if (verbose) {
                            (*loos) << "NA" << " ";
                            ancout << "\t" << "NA";
                        }
                    }
                }
                if (neg == true) {
                    exit(0);
                }
                ancout <<endl;
                if (verbose) {
                    (*loos) << endl;
                }
            }
            }
            if (verbose) {
                (*loos) << endl;
                (*loos) << "stochastic time" << endl;
            }

            for (unsigned int j=0; j < stochtime.size(); j++) {
            if (tree->getMRCA(mrcas[stochtime[j]])->isRoot() == false) {
                vector<double> lhoods;
                if (verbose) {
                    (*loos)  << "mrca: " << stochtime[j] <<  endl;
                }
                sttimeout << n+1 << "\t" << i+1 << "\t" << stochtime[j]<< "\t" << finallike;
                bool neg = false;
                int excount = 0;
                for (int k=0; k < nstates; k++) {
                    if (existing_states[k]==1) {
                        sr.prepare_stochmap_reverse_all_nodes(excount,excount);
                        sr.prepare_ancstate_reverse();
                        vector<double> stoch = sr.calculate_reverse_stochmap(*tree->getMRCA(mrcas[stochtime[j]]),true);
                        double tnum = sum(stoch)/double(totlike_sd);
                        double bl = tree->getMRCA(mrcas[stochtime[j]])->getBL();
                        if (verbose) {
                            (*loos) << tnum << " ";
                        }
                        sttimeout << "\t" << tnum/bl;
                        if (tnum < 0) {
                            neg = true;
                        }
                        excount += 1;
                    } else {
                        if (verbose) {
                            (*loos) << "NA" << " ";
                        }
                        sttimeout << "\t" << "NA";
                    }

                }
                sttimeout << endl;
                if (verbose) {
                    (*loos) << endl;
                }
                if (neg == true) {
                    exit(0);
                }
            }
            }
            if (verbose) {
                (*loos) << endl;
                (*loos) << "stochastic number" << endl;
            }
            for (unsigned int j=0; j < stochnumber.size(); j++) {
                if (tree->getMRCA(mrcas[stochnumber[j]])->isRoot() == false) {
                    vector<double> lhoods;
                    if (verbose) {
                        (*loos) << "mrca: " << stochnumber[j] <<  endl;
                    }
                    stnumout << n+1 << "\t" << i+1 << "\t" << stochnumber[j]<< "\t" << finallike;
                    bool neg = false;
                    int excount = 0;
                    for (int k=0; k < nstates; k++) {
                        if (existing_states[k]==1) {
                            int excount2 = 0;
                            for (int l=0; l < nstates; l++) {
                                if (existing_states[l] == 1) {
                                    if (k == l) {
                                        if (verbose) {
                                            (*loos) << " - ";
                                        }
                                    } else {
                                        sr.prepare_stochmap_reverse_all_nodes(excount,excount2);
                                        sr.prepare_ancstate_reverse();
                                        vector<double> stoch = sr.calculate_reverse_stochmap(*tree->getMRCA(mrcas[stochnumber[j]]),false);
                                        double tnum = sum(stoch)/totlike_sd;
                                        if (verbose) {
                                            (*loos) << tnum << " ";
                                        }
                                        stnumout << "\t" << tnum;
                                        if (tnum < 0) {
                                            neg = true;
                                        }
                                    }
                                    excount2 += 1;
                                } else {
                                    if (verbose) {
                                        (*loos) << "NA" << " ";
                                    }
                                    stnumout << "\t" << "NA";
                                }
                            }
                            if (verbose) {
                                (*loos) << endl;
                            }
                            excount += 1;
                        } else {
                            for (int l=0; l < nstates; l++) {
                                if (k == l) {
                                    if (verbose) {
                                        (*loos) << " - ";
                                    }
                                } else {
                                    if (verbose) {
                                        (*loos) << "NA" << " ";
                                    }
                                    stnumout << "\t" << "NA";
                                }
                            }
                            if (verbose) {
                                (*loos) << endl;
                            }
                        }
                    }
                    stnumout << endl;
                    if (verbose) {
                        (*loos) << endl;
                    }
                    if (neg == true) {
                        exit(0);
                    }
                }
            }
            if (verbose) {
                (*loos) << endl;
            }
            if (verbose) {
                (*loos) << "stochastic number (any)" << endl;
            }
            if (stochnumber_any.size() > 0) {
                sr.prepare_stochmap_reverse_all_nodes_all_matrices();
                sr.prepare_ancstate_reverse();
            }
            for (unsigned int j=0; j < stochnumber_any.size(); j++) {
                if (tree->getMRCA(mrcas[stochnumber_any[j]])->isRoot() == false) {
                    vector<double> lhoods;
                    if (verbose) {
                        (*loos) <<"node: " << tree->getMRCA(mrcas[stochnumber_any[j]])->getName() << " mrca: " << stochnumber_any[j] <<  endl;
                    }
                    sttnumout_any << n+1 << "\t" << i+1 << "\t" << stochnumber_any[j]<< "\t" << finallike;
                    vector<double> stoch = sr.calculate_reverse_stochmap(*tree->getMRCA(mrcas[stochnumber_any[j]]),false);
                    double tnum = sum(stoch)/totlike_sd;
                    //(*loos) << sum(stoch)<< " "<<totlike << endl;
                    if (verbose) {
                        (*loos) << tnum << " " ;
                    }
                    sttnumout_any << "\t" << tnum;
                    sttnumout_any << endl;
                    if (verbose) {
                        (*loos) << endl;
                    }
                }
            }

            //delete tree;
        }
    }
    if (ancstates.size() > 0  && outancfileset == true) {
        ancout.close();
    }
    if (stochnumber.size() > 0) {
        stnumout.close();
    }
    if (stochtime.size() > 0) {
        sttimeout.close();
    }
    
    if (logfileset) {
        logout->close();
        delete loos;
    }
    return EXIT_SUCCESS;
}
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;
}
int ParsimonyCommand::execute() {
	try {
	
		if (abort == true) { if (calledHelp) { return 0; }  return 2;	}
		
		
		//randomtree will tell us if user had their own treefile or if they just want the random distribution
		//user has entered their own tree
		if (randomtree == "") { 
			
			m->setTreeFile(treefile);
			
            TreeReader* reader;
            if (countfile == "") { reader = new TreeReader(treefile, groupfile, namefile); }
            else { reader = new TreeReader(treefile, countfile); }
            T = reader->getTrees();
            ct = T[0]->getCountTable();
            delete reader;
	
			if(outputDir == "") { outputDir += m->hasPath(treefile); }
            map<string, string> variables; 
            variables["[filename]"] = outputDir + m->getSimpleName(treefile) +  ".";
            
			output = new ColumnFile(getOutputFileName("parsimony",variables), itersString);
			outputNames.push_back(getOutputFileName("parsimony",variables));
			outputTypes["parsimony"].push_back(getOutputFileName("parsimony",variables));
				
			sumFile = getOutputFileName("psummary",variables);
			m->openOutputFile(sumFile, outSum);
			outputNames.push_back(sumFile);
			outputTypes["psummary"].push_back(sumFile);
		}else { //user wants random distribution
			getUserInput();
				
			if(outputDir == "") { outputDir += m->hasPath(randomtree); }
			output = new ColumnFile(outputDir+ m->getSimpleName(randomtree), itersString);
			outputNames.push_back(outputDir+ m->getSimpleName(randomtree));
			outputTypes["parsimony"].push_back(outputDir+ m->getSimpleName(randomtree));
		}
			
		//set users groups to analyze
		SharedUtil util;
		vector<string> mGroups = m->getGroups();
		vector<string> tGroups = ct->getNamesOfGroups();
		util.setGroups(mGroups, tGroups, allGroups, numGroups, "parsimony");	//sets the groups the user wants to analyze
		util.getCombos(groupComb, mGroups, numComp);
		m->setGroups(mGroups);
			
		if (numGroups == 1) { numComp++; groupComb.push_back(allGroups); }
			
		Parsimony pars;
		counter = 0;
	
		Progress* reading;
		reading = new Progress("Comparing to random:", iters);
		
		if (m->control_pressed) { 
			delete reading; delete output;
			delete ct; for (int i = 0; i < T.size(); i++) { delete T[i]; }
			if (randomtree == "") {  outSum.close();  }
			for (int i = 0; i < outputNames.size(); i++) {	m->mothurRemove(outputNames[i]); } outputTypes.clear();
			m->clearGroups();
			return 0;
		}
			
		
		//get pscore for users tree
		userData.resize(numComp,0);  //data = AB, AC, BC, ABC.
		randomData.resize(numComp,0);  //data = AB, AC, BC, ABC.
		rscoreFreq.resize(numComp);  
		uscoreFreq.resize(numComp);  
		rCumul.resize(numComp);  
		uCumul.resize(numComp);  
		userTreeScores.resize(numComp);  
		UScoreSig.resize(numComp); 
				
		if (randomtree == "") {
			//get pscores for users trees
			for (int i = 0; i < T.size(); i++) {
				userData = pars.getValues(T[i], processors, outputDir);  //data = AB, AC, BC, ABC.
				
				if (m->control_pressed) { 
					delete reading; delete output;
					delete ct; for (int i = 0; i < T.size(); i++) { delete T[i]; }
					if (randomtree == "") {  outSum.close();  }
					for (int i = 0; i < outputNames.size(); i++) {	m->mothurRemove(outputNames[i]); } outputTypes.clear();
					m->clearGroups();
					return 0;
				}


				//output scores for each combination
				for(int k = 0; k < numComp; k++) {

					//update uscoreFreq
					map<int,double>::iterator it = uscoreFreq[k].find(userData[k]);
					if (it == uscoreFreq[k].end()) {//new score
						uscoreFreq[k][userData[k]] = 1;
					}else{ uscoreFreq[k][userData[k]]++; }
					
					//add users score to valid scores
					validScores[userData[k]] = userData[k];
					
					//save score for summary file
					userTreeScores[k].push_back(userData[k]);
				}
			}
			
			//get pscores for random trees
			for (int j = 0; j < iters; j++) {
								
				//create new tree with same num nodes and leaves as users
				randT = new Tree(ct);

				//create random relationships between nodes
				randT->assembleRandomTree();

				//get pscore of random tree
				randomData = pars.getValues(randT, processors, outputDir);
				
				if (m->control_pressed) { 
					delete reading;  delete output; delete randT;
					if (randomtree == "") {  outSum.close();  }
					for (int i = 0; i < outputNames.size(); i++) {	m->mothurRemove(outputNames[i]); } outputTypes.clear();
					delete ct; for (int i = 0; i < T.size(); i++) { delete T[i]; }
					m->clearGroups();
					return 0;
				}
					
				for(int r = 0; r < numComp; r++) {
					//add trees pscore to map of scores
					map<int,double>::iterator it = rscoreFreq[r].find(randomData[r]);
					if (it != rscoreFreq[r].end()) {//already have that score
						rscoreFreq[r][randomData[r]]++;
					}else{//first time we have seen this score
						rscoreFreq[r][randomData[r]] = 1;
					}
			
					//add randoms score to validscores
					validScores[randomData[r]] = randomData[r];
				}
				
				//update progress bar
				reading->update(j);
				
				delete randT;
			}

		}else {
			//get pscores for random trees
			for (int j = 0; j < iters; j++) {
								
				//create new tree with same num nodes and leaves as users
				randT = new Tree(ct);
				//create random relationships between nodes

				randT->assembleRandomTree();
				
				if (m->control_pressed) { 
					delete reading; delete output; delete randT; delete ct; 
					for (int i = 0; i < outputNames.size(); i++) {	m->mothurRemove(outputNames[i]); } outputTypes.clear(); return 0;
				}


				//get pscore of random tree
				randomData = pars.getValues(randT, processors, outputDir);
				
				if (m->control_pressed) { 
					delete reading; delete output; delete randT; delete ct; 
					for (int i = 0; i < outputNames.size(); i++) {	m->mothurRemove(outputNames[i]); } outputTypes.clear(); return 0;
				}
			
				for(int r = 0; r < numComp; r++) {
					//add trees pscore to map of scores
					map<int,double>::iterator it = rscoreFreq[r].find(randomData[r]);
					if (it != rscoreFreq[r].end()) {//already have that score
						rscoreFreq[r][randomData[r]]++;
					}else{//first time we have seen this score
						rscoreFreq[r][randomData[r]] = 1;
					}
			
					//add randoms score to validscores
					validScores[randomData[r]] = randomData[r];
				}
				
				//update progress bar
				reading->update(j);
				
				delete randT;
			}
		}

		for(int a = 0; a < numComp; a++) {
			float rcumul = 0.0000;
			float ucumul = 0.0000;
			//this loop fills the cumulative maps and put 0.0000 in the score freq map to make it easier to print.
			for (map<int,double>::iterator it = validScores.begin(); it != validScores.end(); it++) { 
				if (randomtree == "") {
					map<int,double>::iterator it2 = uscoreFreq[a].find(it->first);
					//user data has that score 
					if (it2 != uscoreFreq[a].end()) { uscoreFreq[a][it->first] /= T.size(); ucumul+= it2->second;  }
					else { uscoreFreq[a][it->first] = 0.0000; } //no user trees with that score
					//make uCumul map
					uCumul[a][it->first] = ucumul;
				}
			
				//make rscoreFreq map and rCumul
				map<int,double>::iterator it2 = rscoreFreq[a].find(it->first);
				//get percentage of random trees with that info
				if (it2 != rscoreFreq[a].end()) {  rscoreFreq[a][it->first] /= iters; rcumul+= it2->second;  }
				else { rscoreFreq[a][it->first] = 0.0000; } //no random trees with that score
				rCumul[a][it->first] = rcumul;
			}
			
			//find the signifigance of each user trees score when compared to the random trees and save for printing the summary file
			for (int h = 0; h < userTreeScores[a].size(); h++) {
				UScoreSig[a].push_back(rCumul[a][userTreeScores[a][h]]);
			}
		}
		
		if (m->control_pressed) { 
				delete reading; delete output;
				delete ct; for (int i = 0; i < T.size(); i++) { delete T[i]; }
				if (randomtree == "") {  outSum.close();  }
				for (int i = 0; i < outputNames.size(); i++) {	m->mothurRemove(outputNames[i]); } outputTypes.clear();
				return 0;
		}
		
		//finish progress bar
		reading->finish();
		delete reading;
		
		printParsimonyFile();
		if (randomtree == "") { printUSummaryFile(); }
				
        delete output; delete ct; for (int i = 0; i < T.size(); i++) { delete T[i]; }
		
		if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {	m->mothurRemove(outputNames[i]); } outputTypes.clear(); return 0;}
		
		m->mothurOutEndLine();
		m->mothurOut("Output File Names: "); m->mothurOutEndLine();
		for (int i = 0; i < outputNames.size(); i++) {	m->mothurOut(outputNames[i]); m->mothurOutEndLine();	}
		m->mothurOutEndLine();

		
		return 0;
		
	}
	catch(exception& e) {
		m->errorOut(e, "ParsimonyCommand", "execute");
		exit(1);
	}
}
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;
}
void ROC_Occupancy() {
  gStyle->SetPalette(1);

  TH2D* l1 = new TH2D("l1","Layer 1;Modules along Z;Ladders",72, -4.5, 4.5,  42, -10.5,  10.5);
  TH2D* l2 = new TH2D("l2","Layer 2;Modules along Z;Ladders",72, -4.5, 4.5,  66, -16.5,  16.5);
  TH2D* l3 = new TH2D("l3","Layer 3;Modules along Z;Ladders",72, -4.5, 4.5,  90, -22.5,  22.5);
  TH2D* fpixI = new TH2D("fpixI","FPix Inner Shells (+x);;Blades", 72, -4.5, 4.5, 144,   0.5,  12.5);
  TH2D* fpixO = new TH2D("fpixO","FPix Outer Shells (-X);;Blades", 72, -4.5, 4.5, 144, -12.5,  -0.5);
  fpixI->GetXaxis()->SetBinLabel(1, "Disk-2 Pnl2");
  fpixI->GetXaxis()->SetBinLabel(9, "Disk-2 Pnl1");
  fpixI->GetXaxis()->SetBinLabel(19, "Disk-1 Pnl2");
  fpixI->GetXaxis()->SetBinLabel(27, "Disk-1 Pnl1");
  fpixI->GetXaxis()->SetBinLabel(41, "Disk+1 Pnl1");
  fpixI->GetXaxis()->SetBinLabel(49, "Disk+1 Pnl2");
  fpixI->GetXaxis()->SetBinLabel(59, "Disk+2 Pnl1");
  fpixI->GetXaxis()->SetBinLabel(67, "Disk+2 Pnl2");
  fpixI->GetXaxis()->LabelsOption("d");
  fpixO->GetXaxis()->SetBinLabel(1, "Disk-2 Pnl2");
  fpixO->GetXaxis()->SetBinLabel(9, "Disk-2 Pnl1");
  fpixO->GetXaxis()->SetBinLabel(19, "Disk-1 Pnl2");
  fpixO->GetXaxis()->SetBinLabel(27, "Disk-1 Pnl1");
  fpixO->GetXaxis()->SetBinLabel(41, "Disk+1 Pnl1");
  fpixO->GetXaxis()->SetBinLabel(49, "Disk+1 Pnl2");
  fpixO->GetXaxis()->SetBinLabel(59, "Disk+2 Pnl1");
  fpixO->GetXaxis()->SetBinLabel(67, "Disk+2 Pnl2");
  fpixO->GetXaxis()->LabelsOption("d");

  TreeReader tr;
  TChain *filechain = new TChain("filechain");
  filechain->Add("Ntuple.root");

  
  gROOT->SetStyle("Plain");
  gStyle->SetOptStat(0);
  TCanvas c("c","c",1200,800);
  c.Divide(3,2);

  TObjArray* files=filechain->GetListOfFiles();
  for (int nf=0; nf<files->GetEntries(); ++nf) {
    TFile* file = TFile::Open(files->At(nf)->GetTitle());
    tr.readtrees(*file);
    
    for (Long64_t i=0; i<tr.nclu(); i++) {
      tr.clu_read(i);
      Cluster clu = tr.clu();
      EventData e = tr.clu_evt();
      
      int clu_sdpx = ((clu.mod_on.disk>0) ? 1 : -1) * (2 * (abs(clu.mod_on.disk) - 1) + clu.mod_on.panel);
      // Roc BinX number for ROC map plots (clust branch)
      int clu_roc_binx = NOVAL_I;
      if (clu.mod_on.det==0) {
	for (int j=1;j<=8;j++) if (clu.y>=((8-j)*52.0)&&clu.y<((9-j)*52.0))
          clu_roc_binx = (clu.mod_on.module+4)*8 + j;
      } else if (clu.mod_on.det==1) {
        // Roc is left (0) or right (1) on the ROC map plot (+Z side)
        int binselx = (clu.mod_on.panel==1&&(clu.mod_on.module==1||clu.mod_on.module==4)) ? (clu.mod_on.module==1)
          : ((clu.mod_on.panel==1&&clu.x<80.0)||(clu.mod_on.panel==2&&clu.x>=80.0));
        // Gives the Roc location inside a panel (0 to 5 on +Z side)
        int nperpan = 2 * clu.mod_on.module + clu.mod_on.panel - 1 + binselx;
        clu_roc_binx = ((clu.mod_on.disk>0) ? nperpan : 9 - nperpan) + (clu_sdpx + 4) * 8 
          - 2 * ((abs(clu.mod_on.disk)==1) ? clu.mod_on.disk : 0);
      }
      // Roc BinY number for ROC map plots (c branch)
      int clu_roc_biny = NOVAL_I; 
      if (clu.mod_on.det==0) {
        // Roc is in bottom (0) or top bin (1) inside a ladder on th ROC map plot
        int binsely = ((clu.mod_on.half==1&&((clu.mod_on.ladder<0&&clu.mod_on.ladder%2==0)||clu.mod_on.ladder%2==1))
        	       ||(clu.mod_on.half==0&&((clu.mod_on.ladder<0 &&((clu.mod_on.ladder%2==-1&&clu.x<80.0)
        								   ||(clu.mod_on.ladder%2==0&&clu.x>=80.0)))
        					 ||(clu.mod_on.ladder>0 &&((clu.mod_on.ladder%2==0&&clu.x<80.0)
        								     ||(clu.mod_on.ladder%2==1&&clu.x>=80.0))))));
        clu_roc_biny = (clu.mod_on.layer * 6 + clu.mod_on.ladder + 4) * 2 + 1 + binsely;
      } else if (clu.mod_on.det==1) {
        // Gives the number of ROCs along ly
        int nrocly = clu.mod_on.module + clu.mod_on.panel;
        for (int j=0; j<nrocly; j++) {
          // ROC number = nrocly - 1 - j for + LX and nrocly + j for -LX.
          int k = (clu.mod_on.disk<0) ? j : nrocly - 1 - j;
          if (clu.y>=(k*52.0)&&clu.y<((k+1)*52.0))
            clu_roc_biny = 6 - nrocly + 2 * j + ((clu.mod_on.blade>0) ? clu.mod_on.blade-1 : clu.mod_on.blade + 12)*12 + 1;
        }
      }
      
      if (clu.mod_on.layer==1) l1->SetBinContent(clu_roc_binx,clu_roc_biny, l1->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
      else if (clu.mod_on.layer==2) l2->SetBinContent(clu_roc_binx,clu_roc_biny, l2->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
      else if (clu.mod_on.layer==3) l3->SetBinContent(clu_roc_binx,clu_roc_biny, l3->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
      else if (clu.mod_on.blade>0) {
	fpixI->SetBinContent(clu_roc_binx,clu_roc_biny, fpixI->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
	fpixI->SetBinContent(clu_roc_binx,clu_roc_biny+1, fpixI->GetBinContent(clu_roc_binx,clu_roc_biny+1)+1);
      } else if (clu.mod_on.blade<0) {
	fpixO->SetBinContent(clu_roc_binx,clu_roc_biny, fpixO->GetBinContent(clu_roc_binx,clu_roc_biny)+1);
	fpixO->SetBinContent(clu_roc_binx,clu_roc_biny+1, fpixO->GetBinContent(clu_roc_binx,clu_roc_biny+1)+1);
      }
	
      if (i%500000==0) {
	c.cd(1);
	l1->Draw("COLZ");
	c.cd(2);
	l2->Draw("COLZ");
	c.cd(3);
	l3->Draw("COLZ");
	c.cd(4);
	fpixI->Draw("COLZ");
	c.cd(5);
	fpixO->Draw("COLZ");
	gPad->Update();
      }
    }
	c.SaveAs("output.root");
  } std::cout<<"Done."<<std::endl;
}
Beispiel #16
0
int main(int argc, char * argv[]) {
    
    log_call(argc, argv);
    
    bool cfileset = false;
    bool tfileset = false;
    bool outfileset = false;
    
    char * treef = NULL;
    char * charf = NULL;
    char * outf = NULL;
    int analysis = 0;
    while (1) {
        int oi = -1;
        int c = getopt_long(argc, argv, "c:t:o:hV", long_options, &oi);
        if (c == -1) {
            break;
        }
        switch(c) {
            case 'c':
                cfileset = true;
                charf = strdup(optarg);
                check_file_exists(charf);
                break;
            case 't':
                tfileset = true;
                treef = strdup(optarg);
                check_file_exists(treef);
                break;
            case 'o':
                outfileset = true;
                outf = strdup(optarg);
                break;
            case 'h':
                print_help();
                exit(0);
            case 'V':
                cout << versionline << endl;
                exit(0);
            default:
                print_error(argv[0], (char)c);
                exit(0);
        }
    }

    istream * pios = NULL;
    istream * poos = NULL;
    ifstream * cfstr = NULL;
    ifstream * tfstr = NULL;

    ostream * poouts = NULL;
    ofstream * ofstr = NULL;
    

    if (tfileset == true) {
        tfstr = new ifstream(treef);
        poos = tfstr;
    } else {
        poos = &cin;
    }

    if (cfileset == true) {
        cfstr = new ifstream(charf);
        pios = cfstr;
    } else {
        cout << "you have to set a character file. Only a tree file can be read in through the stream;" << endl;
    }

    //out file
    //
    if (outfileset == true){
        ofstr = new ofstream(outf);
        poouts = ofstr;
    } else{
        poouts = &cout;
    }
    //

    string retstring;
    int ft = test_char_filetype_stream(*pios, retstring);
    if (ft != 1 && ft != 2) {
        cout << "only fasta and phylip (with spaces) supported so far" << endl;
        exit(0);
    }
    Sequence seq;
    vector <Sequence> seqs;
    map <string, int> seq_map;
    int y = 0;
    int nchars = 0 ;
    while (read_next_seq_char_from_stream(*pios, ft, retstring, seq)) {
        seqs.push_back(seq);
        nchars = seq.get_num_cont_char();
        seq_map[seq.get_id()] = y;
        seq.clear_cont_char();
        y++;
    }
    cout << "nchars: " <<  nchars << endl;
    
    if (ft == 2) {
        seqs.push_back(seq);
        seq_map[seq.get_id()] = y;
        seq.clear_cont_char();
    }
    //read trees
    TreeReader tr;
    vector<Tree *> trees;
    while (getline(*poos,retstring)) {
        if (retstring.size()<4){
            continue;
        }
        trees.push_back(tr.readTree(retstring));
    }
    int x = 0;
    //conduct analyses for each character
    for (int i=0; i < trees[x]->getExternalNodeCount(); i++) {
        vector<Superdouble> tv (nchars);
        for (int c=0; c < nchars; c++) {
            tv[c] = seqs[seq_map[trees[x]->getExternalNode(i)->getName()]].get_cont_char(c);
        }
        trees[x]->getExternalNode(i)->assocDoubleVector("val",tv);
    }
    for (int i=0; i < trees[x]->getInternalNodeCount(); i++) {
        vector<Superdouble> tv (nchars);
        for (int c=0; c < nchars; c++) {
            tv[c] = 0;
        }
        trees[x]->getInternalNode(i)->assocDoubleVector("val",tv);
    }
    float sigma = 1;
    cout << calc_bm_prune(trees[x], sigma) << endl;
    optimize_single_rate_bm_bl(trees[x]);
    (*poouts) << trees[x]->getRoot()->getNewick(true) << ";" << endl;
    cout << calc_bm_prune(trees[x], sigma) << endl;

    if (cfileset) {
        cfstr->close();
        delete pios;
    }
    if (tfileset) {
        tfstr->close();
        delete poos;
    }
    if (outfileset) {
        ofstr->close();
        delete poouts;
    }
    return EXIT_SUCCESS;
}
Beispiel #17
0
TTree* cudaFitTest(){
	//find/record test signals
	TreeReader reader;
	reader.openFile(258,0);
	int index[512],channel[512];
	float energy[512],time[512];
	int i=0,j=0;
	while(i<512 && j<reader.tree->GetEntries()){
		reader.tree->GetEntry(j);
		for(int k=0;k<11;k++){
			int t=reader.recon.t_gamma[CH[k]];
			float E=reader.recon.E_gamma[CH[k]];
			if(t>0 && t<NPOINTS && E>3000 && E<6000 && i<512){
				index[i]=j;
				channel[i]=CH[k];
				time[i]=t;
				energy[i]=E;
				i++;
			}
		}
		j++;
	}
	reader.reset();
	//copy signals to data;
	RawFileReader rawReader(258,0);
	Entry entry;
	RawData rdata;
	data=new float[512];
	i=0;
	rawReader.initialize();
	for(i=0;i<512;i++){
		data[i]=new float[2048];
		j=index[i];
		int k=channel[i];
		rawReader.seek(j);
		rawReader.readNext(entry,rdata);
		for(int x=0;x<2048;x++){
			data[i][x]=rdata.ch[k][x];
		}
	}
	rawReader.close();
	//fit
	fitter=new cudaFit(512);
	fitter->setData(data);
	float *initParam=new float[8];
	initParam[0]=100;
	initParam[1]=0;
	initParam[2]=15000;
	initParam[3]=1.1e-3;
	initParam[4]=1.3e-3;
	initParam[5]=625;
	initParam[6]=0;
	initParam[7]=0;
	fitter->fit(initParam,0);
	float **param=new float[512];
	for(i=0;i<512;i++){
		param[i]=new float[8];
	}
	float fitE[512],fitT[512];
	fitter->getParameters(param);
	for(int evnt=0;evnt<512;evnt++){
		fitE[evnt]=peakHeight(param[evnt]);
		fitT[evnt]=param[evnt][5];
	}
	//compare
	deltaT=new TH1F("deltaT","deltaT",250,-250,0);
	deltaE=new TH1F("deltaE","deltaE",200,0,2);
	paramB=new TH1F("paramB","paramB",500,10000,30000);
	for(int evnt=0;evnt<512;evnt++){
		deltaT->Fill(time[evnt]-fitT[evnt]);
		deltaE->Fill(fitE[evnt]/energy[evnt]);
		paramB->Fill(param[evnt][2]);
	}
	delete[] param;
	delete[] initParam;
}