Exemplo n.º 1
0
void trim(const char* treepath = "/media/Disk1/avartak/CMS/Data/Dileptons/DoubleMuon/tree*.root", const char* outfilename = "/media/Disk1/avartak/CMS/Data/Dileptons/DoubleMuon/trim.root", bool isMC = false) {

    TFile purwtfile("../data/purwt.root");
    TFile muoidfile("../data/muonIDIsoSF.root");

    TH1F* purwthist = (TH1F*)purwtfile.Get("puhist");

    TH2F* muidlhist = (TH2F*)muoidfile.Get("scalefactors_MuonMediumId_Muon");
    TH2F* muidmhist = (TH2F*)muoidfile.Get("scalefactors_MuonMediumId_Muon");
    TH2F* muidthist = (TH2F*)muoidfile.Get("scalefactors_TightId_Muon"     );

    TH2F* muislhist = (TH2F*)muoidfile.Get("scalefactors_Iso_MuonMediumId" );
    TH2F* muismhist = (TH2F*)muoidfile.Get("scalefactors_Iso_MuonMediumId" );
    TH2F* muisthist = (TH2F*)muoidfile.Get("scalefactors_Iso_MuonTightId"  );

    TFileCollection fc("fc");
    fc.Add(treepath);

    TChain* chain = new TChain("mmtree/tree");
    chain->AddFileInfoList(fc.GetList());

    TTreeReader reader(chain);

    TTreeReaderValue<double>                       xsec     (reader, "xsec"       );
    TTreeReaderValue<double>                       wgt      (reader, "wgt"        );
    TTreeReaderValue<unsigned>                     nvtx     (reader, "nvtx"       );
    TTreeReaderValue<std::vector<TLorentzVector> > dimuons  (reader, "dimuons"    );
    TTreeReaderValue<std::vector<unsigned> >       m1idx    (reader, "m1idx"      );
    TTreeReaderValue<std::vector<unsigned> >       m2idx    (reader, "m2idx"      );
    TTreeReaderValue<std::vector<double> >         masserr  (reader, "masserr"    );
    TTreeReaderValue<std::vector<TLorentzVector> > muons    (reader, "muons"      );
    TTreeReaderValue<std::vector<double> >         miso     (reader, "miso"       );
    TTreeReaderValue<std::vector<char> >           mid      (reader, "mid"        );
    TTreeReaderValue<unsigned char>                hlt2m    (reader, "hltdoublemu");
    TTreeReaderValue<unsigned char>                hlt1m    (reader, "hltsinglemu");

    TFile* outfile = new TFile(outfilename, "RECREATE");
    TTree* outtree = new TTree("tree", "tree");

    double wgtsum  = isMC ? sumwgt(treepath) : 1.0;
    double mcwgt   = 1.0;
    double puwgt   = 1.0;
    double lidw1   = 1.0;
    double lidw2   = 1.0;
    double midw1   = 1.0;
    double midw2   = 1.0;
    double tidw1   = 1.0;
    double tidw2   = 1.0;
    double m1pt    = 0.0;        
    double m1eta   = 0.0;        
    double m1phi   = 0.0;        
    double m1iso   = 0.0;        
    double m2pt    = 0.0;        
    double m2eta   = 0.0;        
    double m2phi   = 0.0;        
    double m2iso   = 0.0;        
    double mmpt    = 0.0;        
    double mmeta   = 0.0;        
    double mmphi   = 0.0;        
    double mass    = 0.0;        
    double merr    = 0.0;        

    char   m1id    = 0;
    char   m2id    = 0;
    char   trig1m  = 0;
    char   trig2m  = 0;

    outtree->Branch("mcwgt" , &mcwgt , "mcwgt/D" );
    outtree->Branch("puwgt" , &puwgt , "puwgt/D" );
    outtree->Branch("lidw1" , &lidw1 , "lidw1/D" );
    outtree->Branch("lidw2" , &lidw2 , "lidw2/D" );
    outtree->Branch("midw1" , &midw1 , "midw1/D" );
    outtree->Branch("midw2" , &midw2 , "midw2/D" );
    outtree->Branch("tidw1" , &tidw1 , "tidw1/D" );
    outtree->Branch("tidw2" , &tidw2 , "tidw2/D" );
    outtree->Branch("m1pt"  , &m1pt  , "m1pt/D"  );
    outtree->Branch("m1eta" , &m1eta , "m1eta/D" );
    outtree->Branch("m1eta" , &m1phi , "m1phi/D" );
    outtree->Branch("m1id"  , &m1id  , "m1id/B"  );
    outtree->Branch("m1iso" , &m1iso , "m1iso/D" );
    outtree->Branch("m2pt"  , &m2pt  , "m2pt/D"  );
    outtree->Branch("m2eta" , &m2eta , "m2eta/D" );
    outtree->Branch("m2eta" , &m2phi , "m2phi/D" );
    outtree->Branch("m2id"  , &m2id  , "m2id/B"  );
    outtree->Branch("m2iso" , &m2iso , "m2iso/D" );
    outtree->Branch("mmpt"  , &mmpt  , "mmpt/D"  );
    outtree->Branch("mmeta" , &mmeta , "mmeta/D" );
    outtree->Branch("mmeta" , &mmphi , "mmphi/D" );
    outtree->Branch("mass"  , &mass  , "mass/D"  );
    outtree->Branch("merr"  , &merr  , "merr/D"  );
    outtree->Branch("trig1m", &trig1m, "trig1m/b");
    outtree->Branch("trig2m", &trig2m, "trig2m/b");

    while(reader.Next()) {

        if (muons->size() != 2) continue;
        if (dimuons->size() != 1) continue;

        unsigned numvtx = *nvtx;
        if (numvtx > 40) numvtx = 40;

        double pt1  = muons->at((*m1idx)[0]).Pt();
        double pt2  = muons->at((*m2idx)[0]).Pt();

        double eta1 = fabs(muons->at((*m1idx)[0]).Eta());
        double eta2 = fabs(muons->at((*m2idx)[0]).Eta());

        if (pt1 >= 120.0) pt1 = 119.9;
        if (pt2 >= 120.0) pt2 = 119.9;

        if (pt1 <=  20.0) pt1 =  20.1;
        if (pt2 <=  20.0) pt2 =  20.1;

        if (isMC) {
            mcwgt = 35.9 * (*wgt) * (*xsec) / wgtsum;
            puwgt = purwthist->GetBinContent(purwthist->FindBin(numvtx));
            
            lidw1 = muidlhist->GetBinContent(muidlhist->FindBin(eta1, pt1));
            lidw1*= muislhist->GetBinContent(muislhist->FindBin(eta1, pt1));
            lidw2 = muidlhist->GetBinContent(muidlhist->FindBin(eta2, pt2));
            lidw2*= muislhist->GetBinContent(muislhist->FindBin(eta2, pt2));
            
            midw1 = muidmhist->GetBinContent(muidmhist->FindBin(eta1, pt1));
            midw1*= muismhist->GetBinContent(muismhist->FindBin(eta1, pt1));
            midw2 = muidmhist->GetBinContent(muidmhist->FindBin(eta2, pt2));
            midw2*= muismhist->GetBinContent(muismhist->FindBin(eta2, pt2));
            
            tidw1 = muidthist->GetBinContent(muidthist->FindBin(eta1, pt1));
            tidw1*= muisthist->GetBinContent(muisthist->FindBin(eta1, pt1));
            tidw2 = muidthist->GetBinContent(muidthist->FindBin(eta2, pt2));
            tidw2*= muisthist->GetBinContent(muisthist->FindBin(eta2, pt2));
        }

        m1pt   = muons->at((*m1idx)[0]).Pt();
        m1eta  = muons->at((*m1idx)[0]).Eta();
        m1phi  = muons->at((*m1idx)[0]).Phi();

        m2pt   = muons->at((*m2idx)[0]).Pt();
        m2eta  = muons->at((*m2idx)[0]).Eta();
        m2phi  = muons->at((*m2idx)[0]).Phi();

        mmpt   = (*dimuons)[0].Pt();
        mmeta  = (*dimuons)[0].Eta();
        mmphi  = (*dimuons)[0].Phi();
        mass   = (*dimuons)[0].M();

        merr   = (*masserr)[0];

        m1id   = mid->at((*m1idx)[0]);
        m2id   = mid->at((*m2idx)[0]);

        m1iso  = miso->at((*m1idx)[0]);
        m2iso  = miso->at((*m2idx)[0]);

        trig1m = (*hlt1m);
        trig2m = (*hlt2m);

        outtree->Fill();

    }

    outtree->Write();

    outfile->Close();
}
Exemplo n.º 2
0
//recompile:
//root -b -l -q MakeAllDCsyst.C++
void MakeAllDCsyst(int mode=-1, string setname="", string indir="root://cmseos.fnal.gov//store/user/lpcsusyhad/SusyRA2Analysis2015/Skims/Run2ProductionV11", string systTypes="nominal,scaleuncUp,scaleuncDown,isruncUp,isruncDown,triguncUp,triguncDown,btagSFuncUp,btagSFuncDown,mistagSFuncUp,mistagSFuncDown,isotrackuncUp,isotrackuncDown,lumiuncUp,lumiuncDown", string varTypes="JECup,JECdown,JERup,JERdown"){
	gErrorIgnoreLevel = kBreak;
	
	if(mode==-1){
		cout << "Recompiled MakeAllDCsyst, exiting." << endl;
		return;
	}
	
	if(indir[indir.size()-1] != '/') indir = indir + "/";
	string inpre = "tree_";
	string region = "signal";
	string outpre = "RA2bin_";
	string outdir = "";
	string input = "input/input_RA2bin_DC_syst.txt";
	//string inputQCD = "input/input_RA2bin_DC_QCD.txt";
	string setlist = "";
	string osuff = "";
	
	//process variaton types - comma-separated input, need to be run separately
	vector<string> vars;
	KParser::process(varTypes,',',vars);
	
	if(mode==1){
		outdir = "datacards_fast/";
		setlist = "input/fast/input_set_DC_"+setname+".txt";
		osuff = "_"+setname;
	}
	else {
		outdir = "datacards_syst/";
		setlist = "input/input_set_DC_"+setname+".txt";
		osuff = "_"+setname;
	}
	
	//check for directory
	if(outdir.size()>0) system(("mkdir -p "+outdir).c_str());
	
	//keep a list of root files
	vector<string> rootfiles;
	
	//do the simple systematics all at once
	rootfiles.push_back(outdir+outpre+region+osuff);
	KPlotDriver(indir+inpre+region,{input,setlist},{"OPTION","string:rootfile["+rootfiles.back()+"]","vstring:selections["+systTypes+"]"});
	
	//do the full variations separately
	//produce a selection for each variation on the fly, cloned from nominal
	for(auto& ivar : vars){
		//change region
		string region_ = region + "_"+ivar;
		rootfiles.push_back(outdir+outpre+region_+osuff);
		KPlotDriver(indir+inpre+region_,{input,setlist},{"OPTION","string:rootfile["+rootfiles.back()+"]","vstring:selections["+ivar+"]","SELECTION",ivar,"\tnominal"});
	}
	
	//hadd
	stringstream slist;
	copy(rootfiles.begin(),rootfiles.end(),ostream_iterator<string>(slist,".root "));
	string therootfile = outpre+region+osuff+".root";
	string cmd = "hadd -f "+therootfile+" "+slist.str();
	system(cmd.c_str());
	
	//further processing
	TFile* infile = TFile::Open(therootfile.c_str());
	TH1F* nominal = NULL;
	TH1F* genMHT = NULL;
	vector<TH1F*> hsyst;
	TKey *key;
	TIter next(infile->GetListOfKeys());
	while ((key = (TKey*)next())) {
		string ntmp = key->GetName();
		TH1F* htmp = (TH1F*)infile->Get(ntmp.c_str());
		if(ntmp.find("nominal")!=string::npos) nominal = htmp;
		else if(ntmp.find("genMHT")!=string::npos) genMHT = htmp;
		else hsyst.push_back(htmp);
	}
	
	if(!nominal){
		cout << "Nominal histogram not found, will not make relative systematics." << endl;
		return;
	}
	
	//todo: factorize the operations below
	
	//setup systematics analysis tree (to study changes in yield)
	vector<string> setnames;
	KParser::process(setname,'_',setnames);
	TTree* tree = new TTree("tree","systematics");
	int mMother = KParser::getOptionValue<int>(setnames[1]);
	int mLSP = KParser::getOptionValue<int>(setnames[2]);
	tree->Branch("mMother",&mMother,"mMother/I");
	tree->Branch("mLSP",&mLSP,"mLSP/I");
	//map to keep track of maximum pct diffs
	KMap<double> pctDiffMap;
	double nominal_yield = nominal->Integral(0,nominal->GetNbinsX()+1);
	
	//divide, bound, set labels (prepended w/ "signal_")
	for(auto isyst : hsyst){
		vector<string> inames;
		KParser::process(isyst->GetName(),'_',inames);
		string binname;
		bool up = (inames.back().find("up")!=string::npos or inames.back().find("Up")!=string::npos);
		if(up) binname = inames.back().substr(0,inames.back().size()-2);
		else binname = inames.back().substr(0,inames.back().size()-4); //down
		string treename = binname;
		binname = "signal_"+binname;
		//check yield (keep max diff in case of up and down)
		double iyield = isyst->Integral(0,isyst->GetNbinsX()+1);
		double pctdiff = fabs(1.-iyield/nominal_yield)*100;
		if(!pctDiffMap.Has(treename) or pctDiffMap.Get(treename) < pctdiff){
			pctDiffMap.Add(treename,pctdiff);
		}
		for(unsigned b = 1; b <= isyst->GetNbinsX(); ++b){
			//divide
			double unc = 1.0;
			double denom = nominal->GetBinContent(b);
			//if central value is zero, treat syst as a shift
			if(denom==0.) denom = 1.0;
			unc = isyst->GetBinContent(b)/denom;
			//bound
			unc = min(max(unc,0.01),3.0);
			//set
			isyst->SetBinContent(b,unc);
			isyst->GetXaxis()->SetBinLabel(b,binname.c_str());
		}
	}
	
	//make stat error
	string sname = changeHistoName(nominal->GetName(),"MCStatErr");
	TH1F* ssyst = (TH1F*)nominal->Clone(sname.c_str());
	double stat_yield = 0;
	for(unsigned b = 1; b <= ssyst->GetNbinsX(); ++b){
		//label
		string slabel = "signal_MCStatErr_";
		slabel += ssyst->GetXaxis()->GetBinLabel(b);
		ssyst->GetXaxis()->SetBinLabel(b,slabel.c_str());
		stat_yield += ssyst->GetBinError(b)+ssyst->GetBinContent(b);
		//divide
		if(ssyst->GetBinContent(b)>0.) ssyst->SetBinContent(b, 1.0+ssyst->GetBinError(b)/ssyst->GetBinContent(b));
		else ssyst->SetBinContent(b, 1.0+ssyst->GetBinError(b));
	}
	hsyst.push_back(ssyst);
	pctDiffMap.Add("MCStatErr",fabs(1-stat_yield/nominal_yield)*100);
	
	//genMHT correction and unc for fastsim
	if(genMHT){
		//keep original nominal histogram
		string nname = changeHistoName(nominal->GetName(),"nominalOrig");
		TH1F* nominalOrig = (TH1F*)nominal->Clone(nname.c_str());
		string gname = changeHistoName(nominal->GetName(),"MHTSyst");
		TH1F* gsyst = (TH1F*)nominal->Clone(gname.c_str());
		double g_yield = 0;
		
		//modify nominal as average of nominal and genMHT & compute syst as difference
		for(unsigned b = 1; b <= nominal->GetNbinsX(); ++b){
			gsyst->SetBinContent(b, 1.0+abs(nominal->GetBinContent(b) - genMHT->GetBinContent(b))/2.0);
			gsyst->GetXaxis()->SetBinLabel(b,"signal_MHTSyst");
			nominal->SetBinContent(b, (nominal->GetBinContent(b) + genMHT->GetBinContent(b))/2.0);
			g_yield += (gsyst->GetBinContent(b)-1.0)+nominal->GetBinContent(b);
		}
		
		hsyst.push_back(gsyst);
		hsyst.push_back(nominalOrig);
		hsyst.push_back(genMHT);
		pctDiffMap.Add("MHTSyst",fabs(1-g_yield/nominal_yield)*100);
	}
	
	//add branches to syst tree
	for(auto& systpair : pctDiffMap.GetTable()){
		tree->Branch(systpair.first.c_str(),&systpair.second,(systpair.first+"/D").c_str());
	}
	
	//fill and write tree w/ hadd-able filename
	tree->Fill();
	string thetrfile = "tree_syst_"+setnames[0]+"_block"+setnames[1]+"-"+setnames[2]+"_fast.root";
	TFile* trfile = TFile::Open(thetrfile.c_str(),"RECREATE");
	trfile->cd();
	tree->Write();
	trfile->Close();

	//write processed syst histos
	string thenewfile = outpre+"proc"+osuff+".root";
	TFile* outfile = TFile::Open(thenewfile.c_str(),"RECREATE");
	outfile->cd();
	nominal->Write();
	for(auto isyst : hsyst) isyst->Write();
	outfile->Close();
}
void TMVAClassification_ttV( TString myMethodList = "" )
{
   // The explicit loading of the shared libTMVA is done in TMVAlogon.C, defined in .rootrc
   // if you use your private .rootrc, or run from a different directory, please copy the
   // corresponding lines from .rootrc

   // methods to be processed can be given as an argument; use format:
   //
   // mylinux~> root -l TMVAClassification.C\(\"myMethod1,myMethod2,myMethod3\"\)
   //
   // if you like to use a method via the plugin mechanism, we recommend using
   //
   // mylinux~> root -l TMVAClassification.C\(\"P_myMethod\"\)
   // (an example is given for using the BDT as plugin (see below),
   // but of course the real application is when you write your own
   // method based)

   //---------------------------------------------------------------
   // This loads the library
   TMVA::Tools::Instance();

   // to get access to the GUI and all tmva macros
   TString tmva_dir(TString(gRootDir) + "/tmva");
   if(gSystem->Getenv("TMVASYS"))
      tmva_dir = TString(gSystem->Getenv("TMVASYS"));
   gROOT->SetMacroPath(tmva_dir + "/test/:" + gROOT->GetMacroPath() );
   gROOT->ProcessLine(".L TMVAGui.C");

   // Default MVA methods to be trained + tested
   std::map<std::string,int> Use;

   // --- Cut optimisation
   Use["Cuts"]            = 0;//1
   Use["CutsD"]           = 0;//1
   Use["CutsPCA"]         = 0;
   Use["CutsGA"]          = 0;
   Use["CutsSA"]          = 0;
   // 
   // --- 1-dimensional likelihood ("naive Bayes estimator")
   Use["Likelihood"]      = 0;//1
   Use["LikelihoodD"]     = 0; // the "D" extension indicates decorrelated input variables (see option strings)
   Use["LikelihoodPCA"]   = 0;//1 // the "PCA" extension indicates PCA-transformed input variables (see option strings)
   Use["LikelihoodKDE"]   = 0;
   Use["LikelihoodMIX"]   = 0;
   //
   // --- Mutidimensional likelihood and Nearest-Neighbour methods
   Use["PDERS"]           = 0;//1
   Use["PDERSD"]          = 0;
   Use["PDERSPCA"]        = 0;
   Use["PDEFoam"]         = 0;//1
   Use["PDEFoamBoost"]    = 0; // uses generalised MVA method boosting
   Use["KNN"]             = 0;//1 // k-nearest neighbour method
   //
   // --- Linear Discriminant Analysis
   Use["LD"]              = 0; //1// Linear Discriminant identical to Fisher
   Use["Fisher"]          = 0;
   Use["FisherG"]         = 0;
   Use["BoostedFisher"]   = 0; // uses generalised MVA method boosting
   Use["HMatrix"]         = 0;
   //
   // --- Function Discriminant analysis
   Use["FDA_GA"]          = 0; //1// minimisation of user-defined function using Genetics Algorithm
   Use["FDA_SA"]          = 0;
   Use["FDA_MC"]          = 0;
   Use["FDA_MT"]          = 0;
   Use["FDA_GAMT"]        = 0;
   Use["FDA_MCMT"]        = 0;
   //
   // --- Neural Networks (all are feed-forward Multilayer Perceptrons)
   Use["MLP"]             = 0; // Recommended ANN
   Use["MLPBFGS"]         = 0; // Recommended ANN with optional training method
   Use["MLPBNN"]          = 0;//1; // Recommended ANN with BFGS training method and bayesian regulator
   Use["CFMlpANN"]        = 0; // Depreciated ANN from ALEPH
   Use["TMlpANN"]         = 0; // ROOT's own ANN
   //
   // --- Support Vector Machine 
   Use["SVM"]             = 0;//1;
   // 
   // --- Boosted Decision Trees
   Use["BDT"]             = 0;//1; // uses Adaptive Boost
   Use["BDTG"]            = 0; // uses Gradient Boost
   Use["BDTB"]            = 0; // uses Bagging
   Use["BDTD"]            = 0; // decorrelation + Adaptive Boost
   Use["BDTF"]            = 0; // allow usage of fisher discriminant for node splitting 
   // 
   // --- Friedman's RuleFit method, ie, an optimised series of cuts ("rules")
   Use["RuleFit"]         = 1;//1;
   // ---------------------------------------------------------------

   std::cout << std::endl;
   std::cout << "==> Start TMVAClassification" << std::endl;

   // Select methods (don't look at this code - not of interest)
   if (myMethodList != "") {
      for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;

      std::vector<TString> mlist = TMVA::gTools().SplitString( myMethodList, ',' );
      for (UInt_t i=0; i<mlist.size(); i++) {
         std::string regMethod(mlist[i]);

         if (Use.find(regMethod) == Use.end()) {
            std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
            for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
            std::cout << std::endl;
            return;
         }
         Use[regMethod] = 1;
      }
   }

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

   // --- Here the preparation phase begins

   // Create a ROOT output file where TMVA will store ntuples, histograms, etc.
   TString outfileName( "TMVA.root" );
   TFile* outputFile = TFile::Open( outfileName, "RECREATE" );

   // Create the factory object. Later you can choose the methods
   // whose performance you'd like to investigate. The factory is 
   // the only TMVA object you have to interact with
   //
   // The first argument is the base of the name of all the
   // weightfiles in the directory weight/
   //
   // The second argument is the output file for the training results
   // All TMVA output can be suppressed by removing the "!" (not) in
   // front of the "Silent" argument in the option string
   TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
                                               "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );

   // If you wish to modify default settings
   // (please check "src/Config.h" to see all available global options)
   //    (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0;
   //    (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory";

   // Define the input variables that shall be used for the MVA training
   // note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
   // [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
   factory->AddVariable(" Mqq := Mqq", 'F');
   factory->AddVariable(" Pt_qq := Pt_qq", 'F');
   //factory->AddVariable( "myvar1 := var1+var2", 'F' );
   //factory->AddVariable( "myvar2 := var1-var2", "Expression 2", "", 'F' );
   //factory->AddVariable( "var3",                "Variable 3", "units", 'F' );
   //factory->AddVariable( "var4",                "Variable 4", "units", 'F' );
   //factory->AddVariable( "Mqq", 'F' );
   //factory->AddVariable( "Pt_qq", 'F' );

   // You can add so-called "Spectator variables", which are not used in the MVA training,
   // but will appear in the final "TestTree" produced by TMVA. This TestTree will contain the
   // input variables, the response values of all trained MVAs, and the spectator variables
   //factory->AddSpectator( "spec1 := var1*2",  "Spectator 1", "units", 'F' );
   //factory->AddSpectator( "spec2 := var1*3",  "Spectator 2", "units", 'F' );

   // Read training and test data
   // (it is also possible to use ASCII format as input -> see TMVA Users Guide)
   
   //Change the input files
   /*
   TString fname = "./tmva_class_example.root";
   
   if (gSystem->AccessPathName( fname ))  // file does not exist in local directory
      gSystem->Exec("wget http://root.cern.ch/files/tmva_class_example.root");
   
   TFile *input = TFile::Open( fname );
   
   std::cout << "--- TMVAClassification       : Using input file: " << input->GetName() << std::endl;
   
   // --- Register the training and test trees

   TTree *signal     = (TTree*)input->Get("TreeS");
   TTree *background = (TTree*)input->Get("TreeB");
   */
   VCandStruct vcand;
   AsymetryStruct asym;
   
   //TFile* fsignal = TFile::Open("/opt/sbg/data/data1/cms/echabert/ttbarMET/ProdAlexMars13/CMSSW_5_3_2_patch4/src/NTuple/NTupleAnalysis/macros/TTbarMET/backup_outputProof08-04-13_18-01-24/proof_ttW.root");
   TFile* fsignal = TFile::Open("/opt/sbg/data/data1/cms/echabert/ttbarMET/ProdAlexMars13/CMSSW_5_3_2_patch4/src/NTuple/NTupleAnalysis/macros/TTbarMET/backup_outputProof10-04-13_16-00-57/proof_ttW.root");
   TTree *signal     = (TTree*)fsignal->Get("theTree2");
   //TTree *signal_orig     = (TTree*)fsignal->Get("theTree2");
   //TTree *signal = signal_orig->CloneTree(0);
   //signal->SetDirectory(0);
   TFile* fbackground = TFile::Open("/opt/sbg/data/data1/cms/echabert/ttbarMET/ProdAlexMars13/CMSSW_5_3_2_patch4/src/NTuple/NTupleAnalysis/macros/TTbarMET/backup_outputProof10-04-13_16-00-57/proof_tt-dilepton.root");
   TTree *background = (TTree*)fbackground->Get("theTree2");
   //TTree *background_orig = (TTree*)fbackground->Get("theTree");
   //TTree *background = background_orig->CloneTree(0);
   //background->SetDirectory(0);

   // global event weights per tree (see below for setting event-wise weights)
   Double_t signalWeight     = 0.30*20/185338;
   Double_t backgroundWeight = 222.*0.1*20/9982625;
   
   // You can add an arbitrary number of signal or background trees
   //Commented by Eric
   factory->AddSignalTree    ( signal,     signalWeight     );
   factory->AddBackgroundTree( background, backgroundWeight );
   
   // To give different trees for training and testing, do as follows:
       //factory->AddSignalTree( signalTrainingTree, signalTrainWeight, "Training" );
       //factory->AddSignalTree( signalTestTree,     signalTestWeight,  "Test" );
   
   // Use the following code instead of the above two or four lines to add signal and background
   // training and test events "by hand"
   // NOTE that in this case one should not give expressions (such as "var1+var2") in the input
   //      variable definition, but simply compute the expression before adding the event
   //
   //     // --- begin ----------------------------------------------------------
   /*
        cout<<"begin"<<endl;
	std::vector<Double_t> vars( 2 ); // vector has size of number of input variables
        //Float_t  treevars[4], weight;
   //     
   //     // Signal
        //for (UInt_t ivar=0; ivar<4; ivar++) signal->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
   	signal->SetBranchAddress("Vcand",&vcand);
        //signal->SetBranchAddress("VCand/Mqq",&vcand.Mqq);
        //signal->SetBranchAddress("VCand/Pt_qq",&vcand.Pt_qq);
	for (UInt_t i=0; i<signal->GetEntries(); i++) {
           //cout<<"GetEntry "<<i<<endl;
           signal->GetEntry(i);
	   //cout<<"done"<<endl;
           //for (UInt_t ivar=0; ivar<2; ivar++) vars[ivar] = treevars[ivar];
           vars[0] = vcand.Mqq;
	   vars[1] = vcand.Pt_qq;
	   //cout<<vars[0]<<" "<<vars[1]<<endl;
	   // add training and test events; here: first half is training, second is testing
           // note that the weight can also be event-wise
           //cout<<"there"<<endl;
	   if (i < signal->GetEntries()/2.0) factory->AddSignalTrainingEvent( vars, signalWeight );
           else                              factory->AddSignalTestEvent    ( vars, signalWeight );
           //return ;
	}
	//delete signal;
        //fsignal->Close();
	cout<<"begin"<<endl;
        //TFile* fbackground = TFile::Open("/opt/sbg/data/data1/cms/echabert/ttbarMET/ProdAlexMars13/CMSSW_5_3_2_patch4/src/NTuple/NTupleAnalysis/macros/TTbarMET/backup_outputProof08-04-13_18-01-24/proof_tt-dilepton.root");
	cout<<fsignal<<" "<<signal<<endl;
      
        // Background (has event weights)
        //background->SetBranchAddress( "weight", &weight );
        //for (UInt_t ivar=0; ivar<4; ivar++) background->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
   	background->SetBranchAddress("Vcand",&vcand);
        //background->SetBranchAddress("VCand/Mqq",&vcand.Mqq);
        //background->SetBranchAddress("VCand/Pt_qq",&vcand.Pt_qq);
        cout<<"here"<<endl;
	for (UInt_t i=0; i<background->GetEntries(); i++) {
           //cout<<"GetEntry "<<i<<endl;
           background->GetEntry(i);
           //cout<<"done"<<endl;
	   //for (UInt_t ivar=0; ivar<4; ivar++) vars[ivar] = treevars[ivar];
           vars[0] = vcand.Mqq;
	   vars[1] = vcand.Pt_qq;
	   //cout<<vars[0]<<" "<<vars[1]<<endl;
           // add training and test events; here: first half is training, second is testing
           // note that the weight can also be event-wise
           //if (i < background->GetEntries()/2) factory->AddBackgroundTrainingEvent( vars, backgroundWeight*weight );
           //else                                factory->AddBackgroundTestEvent    ( vars, backgroundWeight*weight );
           //cout<<"toto"<<endl;
	   if (i < background->GetEntries()/2) factory->AddBackgroundTrainingEvent( vars, backgroundWeight);
           else                                factory->AddBackgroundTestEvent    ( vars, backgroundWeight);
           //cout<<"toto"<<endl;
           //return ;
	}
	*/
	cout<<"eND"<<endl;
	factory->EvaluateAllVariables();
	factory->Print();
         //return;
	 // --- end ------------------------------------------------------------
   //
   // --- end of tree registration 

   // Set individual event weights (the variables must exist in the original TTree)
   //    for signal    : factory->SetSignalWeightExpression    ("weight1*weight2");
   //    for background: factory->SetBackgroundWeightExpression("weight1*weight2");
   //Commented by Eric: factory->SetBackgroundWeightExpression( "weight" );

   // Apply additional cuts on the signal and background samples (can be different)
   TCut mycuts = ""; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
   TCut mycutb = ""; // for example: TCut mycutb = "abs(var1)<0.5";

   // Tell the factory how to use the training and testing events
   //
   // If no numbers of events are given, half of the events in the tree are used 
   // for training, and the other half for testing:
   //    factory->PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );
   // To also specify the number of testing events, use:
   //    factory->PrepareTrainingAndTestTree( mycut,
   //                                         "NSigTrain=3000:NBkgTrain=3000:NSigTest=3000:NBkgTest=3000:SplitMode=Random:!V" );
   cout<<"Prepare it"<<endl;
   factory->PrepareTrainingAndTestTree( mycuts, mycutb,
                                        "nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!V" );
   cout<<"Prepare it : DONE"<<endl;
   
   // ---- Book MVA methods
   //
   // Please lookup the various method configuration options in the corresponding cxx files, eg:
   // src/MethoCuts.cxx, etc, or here: http://tmva.sourceforge.net/optionRef.html
   // it is possible to preset ranges in the option string in which the cut optimisation should be done:
   // "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable

   // Cut optimisation
    cout<<"Use cuts"<<endl;
   if (Use["Cuts"])
      factory->BookMethod( TMVA::Types::kCuts, "Cuts",
                           "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart" );
   cout<<"done"<<endl;

   if (Use["CutsD"])
      factory->BookMethod( TMVA::Types::kCuts, "CutsD",
                           "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=Decorrelate" );

   if (Use["CutsPCA"])
      factory->BookMethod( TMVA::Types::kCuts, "CutsPCA",
                           "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart:VarTransform=PCA" );

   if (Use["CutsGA"])
      factory->BookMethod( TMVA::Types::kCuts, "CutsGA",
                           "H:!V:FitMethod=GA:CutRangeMin[0]=-10:CutRangeMax[0]=10:VarProp[1]=FMax:EffSel:Steps=30:Cycles=3:PopSize=400:SC_steps=10:SC_rate=5:SC_factor=0.95" );

   if (Use["CutsSA"])
      factory->BookMethod( TMVA::Types::kCuts, "CutsSA",
                           "!H:!V:FitMethod=SA:EffSel:MaxCalls=150000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" );

   // Likelihood ("naive Bayes estimator")
   if (Use["Likelihood"])
      factory->BookMethod( TMVA::Types::kLikelihood, "Likelihood",
                           "H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" );

   // Decorrelated likelihood
   if (Use["LikelihoodD"])
      factory->BookMethod( TMVA::Types::kLikelihood, "LikelihoodD",
                           "!H:!V:TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmooth=5:NAvEvtPerBin=50:VarTransform=Decorrelate" );

   // PCA-transformed likelihood
   if (Use["LikelihoodPCA"])
      factory->BookMethod( TMVA::Types::kLikelihood, "LikelihoodPCA",
                           "!H:!V:!TransformOutput:PDFInterpol=Spline2:NSmoothSig[0]=20:NSmoothBkg[0]=20:NSmooth=5:NAvEvtPerBin=50:VarTransform=PCA" ); 

   // Use a kernel density estimator to approximate the PDFs
   if (Use["LikelihoodKDE"])
      factory->BookMethod( TMVA::Types::kLikelihood, "LikelihoodKDE",
                           "!H:!V:!TransformOutput:PDFInterpol=KDE:KDEtype=Gauss:KDEiter=Adaptive:KDEFineFactor=0.3:KDEborder=None:NAvEvtPerBin=50" ); 

   // Use a variable-dependent mix of splines and kernel density estimator
   if (Use["LikelihoodMIX"])
      factory->BookMethod( TMVA::Types::kLikelihood, "LikelihoodMIX",
                           "!H:!V:!TransformOutput:PDFInterpolSig[0]=KDE:PDFInterpolBkg[0]=KDE:PDFInterpolSig[1]=KDE:PDFInterpolBkg[1]=KDE:PDFInterpolSig[2]=Spline2:PDFInterpolBkg[2]=Spline2:PDFInterpolSig[3]=Spline2:PDFInterpolBkg[3]=Spline2:KDEtype=Gauss:KDEiter=Nonadaptive:KDEborder=None:NAvEvtPerBin=50" ); 

   // Test the multi-dimensional probability density estimator
   // here are the options strings for the MinMax and RMS methods, respectively:
   //      "!H:!V:VolumeRangeMode=MinMax:DeltaFrac=0.2:KernelEstimator=Gauss:GaussSigma=0.3" );
   //      "!H:!V:VolumeRangeMode=RMS:DeltaFrac=3:KernelEstimator=Gauss:GaussSigma=0.3" );
   if (Use["PDERS"])
      factory->BookMethod( TMVA::Types::kPDERS, "PDERS",
                           "!H:!V:NormTree=T:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600" );

   if (Use["PDERSD"])
      factory->BookMethod( TMVA::Types::kPDERS, "PDERSD",
                           "!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=Decorrelate" );

   if (Use["PDERSPCA"])
      factory->BookMethod( TMVA::Types::kPDERS, "PDERSPCA",
                           "!H:!V:VolumeRangeMode=Adaptive:KernelEstimator=Gauss:GaussSigma=0.3:NEventsMin=400:NEventsMax=600:VarTransform=PCA" );

   // Multi-dimensional likelihood estimator using self-adapting phase-space binning
   if (Use["PDEFoam"])
      factory->BookMethod( TMVA::Types::kPDEFoam, "PDEFoam",
                           "!H:!V:SigBgSeparate=F:TailCut=0.001:VolFrac=0.0666:nActiveCells=500:nSampl=2000:nBin=5:Nmin=100:Kernel=None:Compress=T" );

   if (Use["PDEFoamBoost"])
      factory->BookMethod( TMVA::Types::kPDEFoam, "PDEFoamBoost",
                           "!H:!V:Boost_Num=30:Boost_Transform=linear:SigBgSeparate=F:MaxDepth=4:UseYesNoCell=T:DTLogic=MisClassificationError:FillFoamWithOrigWeights=F:TailCut=0:nActiveCells=500:nBin=20:Nmin=400:Kernel=None:Compress=T" );

   // K-Nearest Neighbour classifier (KNN)
   if (Use["KNN"])
      factory->BookMethod( TMVA::Types::kKNN, "KNN",
                           "H:nkNN=20:ScaleFrac=0.8:SigmaFact=1.0:Kernel=Gaus:UseKernel=F:UseWeight=T:!Trim" );

   // H-Matrix (chi2-squared) method
   if (Use["HMatrix"])
      factory->BookMethod( TMVA::Types::kHMatrix, "HMatrix", "!H:!V:VarTransform=None" );

   // Linear discriminant (same as Fisher discriminant)
   if (Use["LD"])
      factory->BookMethod( TMVA::Types::kLD, "LD", "H:!V:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );

   // Fisher discriminant (same as LD)
   if (Use["Fisher"])
      factory->BookMethod( TMVA::Types::kFisher, "Fisher", "H:!V:Fisher:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );

   // Fisher with Gauss-transformed input variables
   if (Use["FisherG"])
      factory->BookMethod( TMVA::Types::kFisher, "FisherG", "H:!V:VarTransform=Gauss" );

   // Composite classifier: ensemble (tree) of boosted Fisher classifiers
   if (Use["BoostedFisher"])
      factory->BookMethod( TMVA::Types::kFisher, "BoostedFisher", 
                           "H:!V:Boost_Num=20:Boost_Transform=log:Boost_Type=AdaBoost:Boost_AdaBoostBeta=0.2:!Boost_DetailedMonitoring" );

   // Function discrimination analysis (FDA) -- test of various fitters - the recommended one is Minuit (or GA or SA)
   if (Use["FDA_MC"])
      factory->BookMethod( TMVA::Types::kFDA, "FDA_MC",
                           "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MC:SampleSize=100000:Sigma=0.1" );

   if (Use["FDA_GA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options])
      factory->BookMethod( TMVA::Types::kFDA, "FDA_GA",
                           "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:PopSize=300:Cycles=3:Steps=20:Trim=True:SaveBestGen=1" );

   if (Use["FDA_SA"]) // can also use Simulated Annealing (SA) algorithm (see Cuts_SA options])
      factory->BookMethod( TMVA::Types::kFDA, "FDA_SA",
                           "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=SA:MaxCalls=15000:KernelTemp=IncAdaptive:InitialTemp=1e+6:MinTemp=1e-6:Eps=1e-10:UseDefaultScale" );

   if (Use["FDA_MT"])
      factory->BookMethod( TMVA::Types::kFDA, "FDA_MT",
                           "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=2:UseImprove:UseMinos:SetBatch" );

   if (Use["FDA_GAMT"])
      factory->BookMethod( TMVA::Types::kFDA, "FDA_GAMT",
                           "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=GA:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:Cycles=1:PopSize=5:Steps=5:Trim" );

   if (Use["FDA_MCMT"])
      factory->BookMethod( TMVA::Types::kFDA, "FDA_MCMT",
                           "H:!V:Formula=(0)+(1)*x0+(2)*x1+(3)*x2+(4)*x3:ParRanges=(-1,1);(-10,10);(-10,10);(-10,10);(-10,10):FitMethod=MC:Converger=MINUIT:ErrorLevel=1:PrintLevel=-1:FitStrategy=0:!UseImprove:!UseMinos:SetBatch:SampleSize=20" );

   // TMVA ANN: MLP (recommended ANN) -- all ANNs in TMVA are Multilayer Perceptrons
   if (Use["MLP"])
      factory->BookMethod( TMVA::Types::kMLP, "MLP", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:!UseRegulator" );

   if (Use["MLPBFGS"])
      factory->BookMethod( TMVA::Types::kMLP, "MLPBFGS", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:TrainingMethod=BFGS:!UseRegulator" );

   if (Use["MLPBNN"])
      factory->BookMethod( TMVA::Types::kMLP, "MLPBNN", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:TrainingMethod=BFGS:UseRegulator" ); // BFGS training with bayesian regulators

   // CF(Clermont-Ferrand)ANN
   if (Use["CFMlpANN"])
      factory->BookMethod( TMVA::Types::kCFMlpANN, "CFMlpANN", "!H:!V:NCycles=2000:HiddenLayers=N+1,N"  ); // n_cycles:#nodes:#nodes:...  

   // Tmlp(Root)ANN
   if (Use["TMlpANN"])
      factory->BookMethod( TMVA::Types::kTMlpANN, "TMlpANN", "!H:!V:NCycles=200:HiddenLayers=N+1,N:LearningMethod=BFGS:ValidationFraction=0.3"  ); // n_cycles:#nodes:#nodes:...

   // Support Vector Machine
   if (Use["SVM"])
      factory->BookMethod( TMVA::Types::kSVM, "SVM", "Gamma=0.25:Tol=0.001:VarTransform=Norm" );

   // Boosted Decision Trees
   if (Use["BDTG"]) // Gradient Boost
      factory->BookMethod( TMVA::Types::kBDT, "BDTG",
                           "!H:!V:NTrees=1000:BoostType=Grad:Shrinkage=0.10:UseBaggedGrad:GradBaggingFraction=0.5:nCuts=20:NNodesMax=5" );

   if (Use["BDT"])  // Adaptive Boost
      factory->BookMethod( TMVA::Types::kBDT, "BDT",
                           "!H:!V:NTrees=850:nEventsMin=150:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=0.5:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning" );


   if (Use["BDTB"]) // Bagging
      factory->BookMethod( TMVA::Types::kBDT, "BDTB",
                           "!H:!V:NTrees=400:BoostType=Bagging:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning" );

   if (Use["BDTD"]) // Decorrelation + Adaptive Boost
      factory->BookMethod( TMVA::Types::kBDT, "BDTD",
                           "!H:!V:NTrees=400:nEventsMin=400:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning:VarTransform=Decorrelate" );

   if (Use["BDTF"])  // Allow Using Fisher discriminant in node splitting for (strong) linearly correlated variables
      factory->BookMethod( TMVA::Types::kBDT, "BDTMitFisher",
                           "!H:!V:NTrees=50:nEventsMin=150:UseFisherCuts:MaxDepth=3:BoostType=AdaBoost:AdaBoostBeta=0.5:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning" );

   // RuleFit -- TMVA implementation of Friedman's method
   if (Use["RuleFit"])
      factory->BookMethod( TMVA::Types::kRuleFit, "RuleFit",
                           "H:!V:RuleFitModule=RFTMVA:Model=ModRuleLinear:MinImp=0.001:RuleMinDist=0.001:NTrees=20:fEventsMin=0.01:fEventsMax=0.5:GDTau=-1.0:GDTauPrec=0.01:GDStep=0.01:GDNSteps=10000:GDErrScale=1.02" );

   // For an example of the category classifier usage, see: TMVAClassificationCategory

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

   // ---- Now you can optimize the setting (configuration) of the MVAs using the set of training events

   // factory->OptimizeAllMethods("SigEffAt001","Scan");
   // factory->OptimizeAllMethods("ROCIntegral","GA");

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

   // ---- Now you can tell the factory to train, test, and evaluate the MVAs

   cout<<"TrainAllMethods"<<endl;
   // Train MVAs using the set of training events
   factory->TrainAllMethods();

   // ---- Evaluate all MVAs using the set of test events
   factory->TestAllMethods();

   // ----- Evaluate and compare performance of all configured MVAs
   factory->EvaluateAllMethods();

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

   // Save the output
   outputFile->Close();

   std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
   std::cout << "==> TMVAClassification is done!" << std::endl;

   delete factory;

   // Launch the GUI for the root macros
   if (!gROOT->IsBatch()) TMVAGui( outfileName );
}
Exemplo n.º 4
0
//this makes Z(nunu) prediction vs. MC truth plots for the AN.
//at the moment all numbers are hard-coded and this code needs major revision, the mc truth numbers are loaded from a root file created by ZnunuNumbers.C
//furthermore the stored root file is used for both producing the final result plots/tables and also interpretation
void ZinvVisualization(){

    const int gNMT2bins_2j0b_hHT                      = 6;
    double  gMT2bins_2j0b_hHT[gNMT2bins_2j0b_hHT+1]   = {120, 150, 200, 260, 350, 550, 900};
    const int gNMT2bins_2j1b_hHT                      = 2;
    double  gMT2bins_2j1b_hHT[gNMT2bins_2j1b_hHT+1]   = {100, 180, 350};
    const int gNMT2bins_3j0b_hHT                      = 7;
    double  gMT2bins_3j0b_hHT[gNMT2bins_3j0b_hHT+1]   = {160, 185, 220, 270, 350, 450, 650, 1000};
    const int gNMT2bins_3j1b_hHT                      = 4;
    double  gMT2bins_3j1b_hHT[gNMT2bins_3j1b_hHT+1]   = {150, 180, 230, 350, 550};
    const int gNMT2bins_3j2b_hHT                      = 2;
    double  gMT2bins_3j2b_hHT[gNMT2bins_3j2b_hHT+1]   = {130, 200, 350};
    const int gNMT2bins_6j0b_hHT                      = 3;
    double  gMT2bins_6j0b_hHT[gNMT2bins_6j0b_hHT+1]   = {160, 200, 300, 500};
    const int gNMT2bins_6j1b_hHT                      = 3;
    double  gMT2bins_6j1b_hHT[gNMT2bins_6j1b_hHT+1]   = {150, 200, 300, 500};
    const int gNMT2bins_6j2b_hHT                      = 2;
    double  gMT2bins_6j2b_hHT[gNMT2bins_6j2b_hHT+1]   = {130, 200, 350};
    const int gNMT2bins_3b_hHT                        = 1;
    double  gMT2bins_3b_hHT[gNMT2bins_3b_hHT+1]       = {125, 300};

    // HT > 750 && HT < 1200
    const int gNMT2bins_2j0b_mHT                      = 9;
    double  gMT2bins_2j0b_mHT[gNMT2bins_2j0b_mHT+1]   = {125, 150, 180, 220, 270, 325, 425, 580, 780, 1000};
    const int gNMT2bins_2j1b_mHT                      = 5;
    double  gMT2bins_2j1b_mHT[gNMT2bins_2j1b_mHT+1]   = {100, 135, 170, 260, 450, 700};
    const int gNMT2bins_3j0b_mHT                      = 9;
    double  gMT2bins_3j0b_mHT[gNMT2bins_3j0b_mHT+1]   = {160, 185, 215, 250, 300, 370, 480, 640, 800, 1000};
    const int gNMT2bins_3j1b_mHT                      = 6;
    double  gMT2bins_3j1b_mHT[gNMT2bins_3j1b_mHT+1]   = {150, 175, 210, 270, 380, 600, 900};
    const int gNMT2bins_3j2b_mHT                      = 5;
    double  gMT2bins_3j2b_mHT[gNMT2bins_3j2b_mHT+1]   = {130, 160, 200, 270, 370, 500};
    const int gNMT2bins_6j0b_mHT                      = 5;
    double  gMT2bins_6j0b_mHT[gNMT2bins_6j0b_mHT+1]   = {160, 200, 250, 325, 425, 600};
    const int gNMT2bins_6j1b_mHT                      = 4;
    double  gMT2bins_6j1b_mHT[gNMT2bins_6j1b_mHT+1]   = {150, 190, 250, 350, 500};
    const int gNMT2bins_6j2b_mHT                      = 4;
    double  gMT2bins_6j2b_mHT[gNMT2bins_6j2b_mHT+1]   = {130, 170, 220, 300, 450};
    const int gNMT2bins_3b_mHT                        = 3;
    double  gMT2bins_3b_mHT[gNMT2bins_3b_mHT+1]       = {125, 175, 275, 450};

    // HT > 450 && HT < 750
    const int gNMT2bins_2j0b_lHT                      = 8;
    double  gMT2bins_2j0b_lHT[gNMT2bins_2j0b_lHT+1]   = {200, 240, 290, 350, 420, 490, 570, 650, 750};
    const int gNMT2bins_2j1b_lHT                      = 6;
    double  gMT2bins_2j1b_lHT[gNMT2bins_2j1b_lHT+1]   = {200, 250, 310, 380, 450, 550, 700};
    const int gNMT2bins_3j0b_lHT                      = 8;
    double  gMT2bins_3j0b_lHT[gNMT2bins_3j0b_lHT+1]   = {200, 240, 290, 350, 420, 490, 570, 650, 750};
    const int gNMT2bins_3j1b_lHT                      = 6;
    double  gMT2bins_3j1b_lHT[gNMT2bins_3j1b_lHT+1]   = {200, 250, 310, 380, 460, 550, 700};
    const int gNMT2bins_3j2b_lHT                      = 4;
    double  gMT2bins_3j2b_lHT[gNMT2bins_3j2b_lHT+1]   = {200, 250, 325, 425, 550};
    const int gNMT2bins_6j0b_lHT                      = 3;
    double  gMT2bins_6j0b_lHT[gNMT2bins_6j0b_lHT+1]   = {200, 280, 380, 520};
    const int gNMT2bins_6j1b_lHT                      = 3;
    double  gMT2bins_6j1b_lHT[gNMT2bins_6j1b_lHT+1]   = {200, 250, 325, 450};
    const int gNMT2bins_6j2b_lHT                      = 3;
    double  gMT2bins_6j2b_lHT[gNMT2bins_6j2b_lHT+1]   = {200, 250, 300, 400};
    const int gNMT2bins_3b_lHT                        = 2;
    double  gMT2bins_3b_lHT  [gNMT2bins_3b_lHT+1]     = {200, 280, 400};

const int signalregionsize = 9;
string signal_region[signalregionsize] = {"2j0b", "2j1to2b", "3to5j0b", "3to5j1b", "3to5j2b", "6j0b", "6j1b", "6j2b", "3b"};
const int HTbinsize = 3;
string HT_bin[HTbinsize] = {"lowHT", "mediumHT", "highHT"};

    	gROOT->SetStyle("Plain");
	gStyle->SetPalette(1);
	gStyle->SetOptStat(0);

    TLegend *leg = new TLegend(0.6551724,0.7299578,0.8706897,0.8987342,NULL,"brNDC");
    leg->SetBorderSize(0);
    leg->SetTextFont(62);
    leg->SetTextSize(0.04575163);
    leg->SetLineColor(1);
    leg->SetLineStyle(1);
    leg->SetLineWidth(1);
    leg->SetFillColor(0);
    leg->SetFillStyle(1001);

//load MC truth numbers
TFile *fmctruth = TFile::Open("../Results/Filtered/GammaJetsPrediction/20130617_test/ZnunuNumbers.root");

	//define all histograms
	map<string, TH1D*>    histos;
	for(int i3 = 0; i3<HTbinsize;        ++i3){
	for(int i2 = 0; i2<signalregionsize; ++i2){
		int NMT2bins;
		if(i3==0){
			if(signal_region[i2]=="2j0b")    NMT2bins = gNMT2bins_2j0b_lHT;
			if(signal_region[i2]=="2j1to2b") NMT2bins = gNMT2bins_2j1b_lHT;
			if(signal_region[i2]=="3to5j0b") NMT2bins = gNMT2bins_3j0b_lHT;
			if(signal_region[i2]=="3to5j1b") NMT2bins = gNMT2bins_3j1b_lHT;
			if(signal_region[i2]=="3to5j2b") NMT2bins = gNMT2bins_3j2b_lHT;
			if(signal_region[i2]=="6j0b")    NMT2bins = gNMT2bins_6j0b_lHT;
			if(signal_region[i2]=="6j1b")    NMT2bins = gNMT2bins_6j1b_lHT;
			if(signal_region[i2]=="6j2b")    NMT2bins = gNMT2bins_6j2b_lHT;
			if(signal_region[i2]=="3b")      NMT2bins = gNMT2bins_3b_lHT;
		} if(i3==1){
			if(signal_region[i2]=="2j0b")    NMT2bins = gNMT2bins_2j0b_mHT;
			if(signal_region[i2]=="2j1to2b") NMT2bins = gNMT2bins_2j1b_mHT;
			if(signal_region[i2]=="3to5j0b") NMT2bins = gNMT2bins_3j0b_mHT;
			if(signal_region[i2]=="3to5j1b") NMT2bins = gNMT2bins_3j1b_mHT;
			if(signal_region[i2]=="3to5j2b") NMT2bins = gNMT2bins_3j2b_mHT;
			if(signal_region[i2]=="6j0b")    NMT2bins = gNMT2bins_6j0b_mHT;
			if(signal_region[i2]=="6j1b")    NMT2bins = gNMT2bins_6j1b_mHT;
			if(signal_region[i2]=="6j2b")    NMT2bins = gNMT2bins_6j2b_mHT;
			if(signal_region[i2]=="3b")      NMT2bins = gNMT2bins_3b_mHT;
		} if(i3==2){
			if(signal_region[i2]=="2j0b")    NMT2bins = gNMT2bins_2j0b_hHT;
			if(signal_region[i2]=="2j1to2b") NMT2bins = gNMT2bins_2j1b_hHT;
			if(signal_region[i2]=="3to5j0b") NMT2bins = gNMT2bins_3j0b_hHT;
			if(signal_region[i2]=="3to5j1b") NMT2bins = gNMT2bins_3j1b_hHT;
			if(signal_region[i2]=="3to5j2b") NMT2bins = gNMT2bins_3j2b_hHT;
			if(signal_region[i2]=="6j0b")    NMT2bins = gNMT2bins_6j0b_hHT;
			if(signal_region[i2]=="6j1b")    NMT2bins = gNMT2bins_6j1b_hHT;
			if(signal_region[i2]=="6j2b")    NMT2bins = gNMT2bins_6j2b_hHT;
			if(signal_region[i2]=="3b")      NMT2bins = gNMT2bins_3b_hHT;
		}
  		double MT2bins[NMT2bins+1];
		if(i3==0){
			if(signal_region[i2]=="2j0b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_2j0b_lHT[i0]; }
			if(signal_region[i2]=="2j1to2b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_2j1b_lHT[i0]; }
			if(signal_region[i2]=="3to5j0b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j0b_lHT[i0]; }
			if(signal_region[i2]=="3to5j1b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j1b_lHT[i0]; }
			if(signal_region[i2]=="3to5j2b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j2b_lHT[i0]; }
			if(signal_region[i2]=="6j0b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j0b_lHT[i0]; }
			if(signal_region[i2]=="6j1b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j1b_lHT[i0]; }
			if(signal_region[i2]=="6j2b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j2b_lHT[i0]; }
			if(signal_region[i2]=="3b")      { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3b_lHT[i0];   }
		} if(i3==1){
			if(signal_region[i2]=="2j0b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_2j0b_mHT[i0];  }
			if(signal_region[i2]=="2j1to2b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_2j1b_mHT[i0];  }
			if(signal_region[i2]=="3to5j0b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j0b_mHT[i0];  }
			if(signal_region[i2]=="3to5j1b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j1b_mHT[i0];  }
			if(signal_region[i2]=="3to5j2b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j2b_mHT[i0];  }
			if(signal_region[i2]=="6j0b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j0b_mHT[i0];  }
			if(signal_region[i2]=="6j1b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j1b_mHT[i0];  }
			if(signal_region[i2]=="6j2b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j2b_mHT[i0];  }
			if(signal_region[i2]=="3b")      { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3b_mHT[i0];    }
		} if(i3==2){
			if(signal_region[i2]=="2j0b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_2j0b_hHT[i0];  }
			if(signal_region[i2]=="2j1to2b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_2j1b_hHT[i0];  }
			if(signal_region[i2]=="3to5j0b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j0b_hHT[i0];  }
			if(signal_region[i2]=="3to5j1b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j1b_hHT[i0];  }
			if(signal_region[i2]=="3to5j2b") { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3j2b_hHT[i0];  }
			if(signal_region[i2]=="6j0b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j0b_hHT[i0];  }
			if(signal_region[i2]=="6j1b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j1b_hHT[i0];  }
			if(signal_region[i2]=="6j2b")    { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_6j2b_hHT[i0];  }
			if(signal_region[i2]=="3b")      { for(int i0 = 0; i0<=NMT2bins; ++i0) MT2bins[i0] = gMT2bins_3b_hHT[i0];    }
		}

		string hs = string("_") + HT_bin[i3] + string("_") + signal_region[i2];// + string("_") + sample_type[i1];
		string mapname = "MT2" + hs;
		TH1D *h = (TH1D*)fmctruth->Get(mapname.c_str());
		mapname = "MT2truth" + hs;
		if(histos.count(mapname) == 0 ) histos[mapname] = (TH1D*)h->Clone(mapname.c_str());
		histos[mapname]->SetFillColor(kViolet-3); histos[mapname]->SetFillStyle(3001);
		//get MC truth histo style
		if(i3==0&&i2==0) leg->AddEntry(histos[mapname], "MC truth", "f");
			histos[mapname]->GetXaxis()->SetTitle("M_{T2} [GeV]");
			histos[mapname]->GetXaxis()->SetLabelFont(42);
			histos[mapname]->GetXaxis()->SetLabelSize(0.06);
			histos[mapname]->GetXaxis()->SetTitleSize(0.06);
			histos[mapname]->GetXaxis()->SetLabelOffset(0.01);
			histos[mapname]->GetXaxis()->SetTitleOffset(1.2);
			histos[mapname]->GetXaxis()->SetTitleFont(42);
			histos[mapname]->GetYaxis()->SetTitle("Z(#nu#nu) yield");
			histos[mapname]->GetYaxis()->SetLabelFont(42);
			histos[mapname]->GetYaxis()->SetLabelSize(0.06);
			histos[mapname]->GetYaxis()->SetTitleSize(0.06);
			histos[mapname]->GetYaxis()->SetLabelOffset(0.01);
			histos[mapname]->GetYaxis()->SetTitleOffset(1.2);
			histos[mapname]->GetYaxis()->SetTitleFont(42);
			histos[mapname]->GetZaxis()->SetLabelFont(42);
			histos[mapname]->GetZaxis()->SetLabelSize(0.035);
			histos[mapname]->GetZaxis()->SetTitleSize(0.035);
			histos[mapname]->GetZaxis()->SetTitleFont(42);
		mapname = "MT2pred" + hs;
		if(histos.count(mapname) == 0 ) histos[mapname] = new TH1D(mapname.c_str(), "", NMT2bins, MT2bins);
		histos[mapname]->SetMarkerStyle(20), histos[mapname]->SetMarkerColor(kBlack); histos[mapname]->SetLineWidth(3); histos[mapname]->SetLineColor(kBlack);
		//get prediction histo style
		if(i3==0&&i2==0) leg->AddEntry(histos[mapname], "data prediction", "lp");
			histos[mapname]->GetXaxis()->SetTitle("M_{T2} [GeV]");
			histos[mapname]->GetXaxis()->SetLabelFont(42);
			histos[mapname]->GetXaxis()->SetLabelSize(0.06);
			histos[mapname]->GetXaxis()->SetTitleSize(0.06);
			histos[mapname]->GetXaxis()->SetLabelOffset(0.01);
			histos[mapname]->GetXaxis()->SetTitleOffset(1.2);
			histos[mapname]->GetXaxis()->SetTitleFont(42);
			histos[mapname]->GetYaxis()->SetTitle("Z(#nu#nu) yield");
			histos[mapname]->GetYaxis()->SetLabelFont(42);
			histos[mapname]->GetYaxis()->SetLabelSize(0.06);
			histos[mapname]->GetYaxis()->SetTitleSize(0.06);
			histos[mapname]->GetYaxis()->SetLabelOffset(0.01);
			histos[mapname]->GetYaxis()->SetTitleOffset(1.2);
			histos[mapname]->GetYaxis()->SetTitleFont(42);
			histos[mapname]->GetZaxis()->SetLabelFont(42);
			histos[mapname]->GetZaxis()->SetLabelSize(0.035);
			histos[mapname]->GetZaxis()->SetTitleSize(0.035);
			histos[mapname]->GetZaxis()->SetTitleFont(42);
	}}

	//hard-coded numbers
	for(int i3 = 0; i3<HTbinsize;        ++i3){
	for(int i2 = 0; i2<signalregionsize; ++i2){
	   string hs = string("_") + HT_bin[i3] + string("_") + signal_region[i2];
	   string mapname = "MT2pred" + hs;
	   if(i3==0&&i2==0){//lHT,2j,0b
		histos[mapname]->SetBinContent(1,304.27); histos[mapname]->SetBinError(1,sqrt(pow(11.84,2)+pow(62.55,2)));
		histos[mapname]->SetBinContent(2,236.52); histos[mapname]->SetBinError(2,sqrt(pow(10.55,2)+pow(48.41,2)));
		histos[mapname]->SetBinContent(3,182.98); histos[mapname]->SetBinError(3,sqrt(pow( 9.30,2)+pow(37.50,2)));
		histos[mapname]->SetBinContent(4,160.92); histos[mapname]->SetBinError(4,sqrt(pow( 9.09,2)+pow(50.38,2)));
		histos[mapname]->SetBinContent(5,116.69); histos[mapname]->SetBinError(5,sqrt(pow( 7.46,2)+pow(35.07,2)));
		histos[mapname]->SetBinContent(6, 47.95); histos[mapname]->SetBinError(6,sqrt(pow( 4.86,2)+pow(14.57,2)));
		histos[mapname]->SetBinContent(7, 11.74); histos[mapname]->SetBinError(7,sqrt(pow( 2.39,2)+pow( 3.56,2)));
		histos[mapname]->SetBinContent(8,  3.28); histos[mapname]->SetBinError(8,sqrt(pow( 1.24,2)+pow( 0.98,2)));
	   } if(i3==0&&i2==2){//lHT,35j,0b
		histos[mapname]->SetBinContent(1,458.79); histos[mapname]->SetBinError(1,sqrt(pow(16.03,2)+pow(97.64,2)));
		histos[mapname]->SetBinContent(2,366.96); histos[mapname]->SetBinError(2,sqrt(pow(14.70,2)+pow(80.26,2)));
		histos[mapname]->SetBinContent(3,301.04); histos[mapname]->SetBinError(3,sqrt(pow(12.94,2)+pow(62.16,2)));
		histos[mapname]->SetBinContent(4,173.25); histos[mapname]->SetBinError(4,sqrt(pow(10.18,2)+pow(54.86,2)));
		histos[mapname]->SetBinContent(5, 93.60); histos[mapname]->SetBinError(5,sqrt(pow( 7.29,2)+pow(28.28,2)));
		histos[mapname]->SetBinContent(6, 41.36); histos[mapname]->SetBinError(6,sqrt(pow( 4.88,2)+pow(12.64,2)));
		histos[mapname]->SetBinContent(7,  9.80); histos[mapname]->SetBinError(7,sqrt(pow( 2.38,2)+pow( 3.01,2)));
		histos[mapname]->SetBinContent(8,  2.73); histos[mapname]->SetBinError(8,sqrt(pow( 1.22,2)+pow( 0.82,2)));
	   } if(i3==0&&i2==5){//lHT,6j,0b
		histos[mapname]->SetBinContent(1, 12.02); histos[mapname]->SetBinError(1,sqrt(pow( 2.76,2)+pow( 2.58,2)));
		histos[mapname]->SetBinContent(2,  5.13); histos[mapname]->SetBinError(2,sqrt(pow( 1.95,2)+pow( 1.29,2)));
		histos[mapname]->SetBinContent(3,  3.53); histos[mapname]->SetBinError(3,sqrt(pow( 1.77,2)+pow( 1.24,2)));
	   } if(i3==1&&i2==0){//mHT,2j,0b
		histos[mapname]->SetBinContent(1, 76.13); histos[mapname]->SetBinError(1,sqrt(pow( 5.38,2)+pow(15.32,2)));
		histos[mapname]->SetBinContent(2, 62.24); histos[mapname]->SetBinError(2,sqrt(pow( 4.92,2)+pow(12.55,2)));
		histos[mapname]->SetBinContent(3, 38.49); histos[mapname]->SetBinError(3,sqrt(pow( 3.95,2)+pow( 7.78,2)));
		histos[mapname]->SetBinContent(4, 40.84); histos[mapname]->SetBinError(4,sqrt(pow( 4.19,2)+pow( 8.26,2)));
		histos[mapname]->SetBinContent(5, 20.11); histos[mapname]->SetBinError(5,sqrt(pow( 3.00,2)+pow( 4.08,2)));
		histos[mapname]->SetBinContent(6, 30.21); histos[mapname]->SetBinError(6,sqrt(pow( 3.82,2)+pow( 9.14,2)));
		histos[mapname]->SetBinContent(7, 12.73); histos[mapname]->SetBinError(7,sqrt(pow( 2.44,2)+pow( 3.84,2)));
		histos[mapname]->SetBinContent(8, 15.96); histos[mapname]->SetBinError(8,sqrt(pow( 2.79,2)+pow( 4.83,2)));
		histos[mapname]->SetBinContent(9,  2.83); histos[mapname]->SetBinError(9,sqrt(pow( 1.15,2)+pow( 0.85,2)));
	   } if(i3==1&&i2==2){//mHT,35j,0b
		histos[mapname]->SetBinContent(1, 88.17); histos[mapname]->SetBinError(1,sqrt(pow( 6.50,2)+pow(17.75,2)));
		histos[mapname]->SetBinContent(2, 73.11); histos[mapname]->SetBinError(2,sqrt(pow( 6.38,2)+pow(14.78,2)));
		histos[mapname]->SetBinContent(3, 63.34); histos[mapname]->SetBinError(3,sqrt(pow( 5.72,2)+pow(12.78,2)));
		histos[mapname]->SetBinContent(4, 59.03); histos[mapname]->SetBinError(4,sqrt(pow( 5.71,2)+pow(11.95,2)));
		histos[mapname]->SetBinContent(5, 50.85); histos[mapname]->SetBinError(5,sqrt(pow( 5.36,2)+pow(10.32,2)));
		histos[mapname]->SetBinContent(6, 43.54); histos[mapname]->SetBinError(6,sqrt(pow( 4.88,2)+pow(13.11,2)));
		histos[mapname]->SetBinContent(7, 23.40); histos[mapname]->SetBinError(7,sqrt(pow( 3.63,2)+pow( 7.07,2)));
		histos[mapname]->SetBinContent(8,  6.43); histos[mapname]->SetBinError(8,sqrt(pow( 1.85,2)+pow( 1.93,2)));
		histos[mapname]->SetBinContent(9,  2.68); histos[mapname]->SetBinError(9,sqrt(pow( 1.20,2)+pow( 0.81,2)));
	  } if(i3==1&&i2==5){//mHT,6j,0b
		histos[mapname]->SetBinContent(1, 10.51); histos[mapname]->SetBinError(1,sqrt(pow( 2.84,2)+pow( 2.43,2)));
		histos[mapname]->SetBinContent(2,  3.03); histos[mapname]->SetBinError(2,sqrt(pow( 1.35,2)+pow( 0.68,2)));
		histos[mapname]->SetBinContent(3,  4.05); histos[mapname]->SetBinError(3,sqrt(pow( 1.65,2)+pow( 0.94,2)));
		histos[mapname]->SetBinContent(4,  2.61); histos[mapname]->SetBinError(4,sqrt(pow( 1.51,2)+pow( 0.88,2)));
		histos[mapname]->SetBinContent(5,  0.66); histos[mapname]->SetBinError(5,sqrt(pow( 0.66,2)+pow( 0.23,2)));
	   } if(i3==2&&i2==0){//hHT,2j,0b
		histos[mapname]->SetBinContent(1, 10.05); histos[mapname]->SetBinError(1,sqrt(pow( 1.99,2)+pow( 2.09,2)));
		histos[mapname]->SetBinContent(2, 10.34); histos[mapname]->SetBinError(2,sqrt(pow( 2.07,2)+pow( 2.14,2)));
		histos[mapname]->SetBinContent(3,  9.22); histos[mapname]->SetBinError(3,sqrt(pow( 2.06,2)+pow( 1.97,2)));
		histos[mapname]->SetBinContent(4,  3.52); histos[mapname]->SetBinError(4,sqrt(pow( 1.25,2)+pow( 0.76,2)));
		histos[mapname]->SetBinContent(5,  2.94); histos[mapname]->SetBinError(5,sqrt(pow( 1.20,2)+pow( 0.91,2)));
		histos[mapname]->SetBinContent(6,  2.45); histos[mapname]->SetBinError(6,sqrt(pow( 1.10,2)+pow( 0.76,2)));
	   } if(i3==2&&i2==2){//hHT,35j,0b
		histos[mapname]->SetBinContent(1,  8.73); histos[mapname]->SetBinError(1,sqrt(pow( 2.13,2)+pow( 1.86,2)));
		histos[mapname]->SetBinContent(2, 11.85); histos[mapname]->SetBinError(2,sqrt(pow( 2.42,2)+pow( 2.48,2)));
		histos[mapname]->SetBinContent(3, 10.16); histos[mapname]->SetBinError(3,sqrt(pow( 2.33,2)+pow( 2.13,2)));
		histos[mapname]->SetBinContent(4,  8.54); histos[mapname]->SetBinError(4,sqrt(pow( 2.20,2)+pow( 1.82,2)));
		histos[mapname]->SetBinContent(5,  4.85); histos[mapname]->SetBinError(5,sqrt(pow( 1.73,2)+pow( 1.52,2)));
		histos[mapname]->SetBinContent(6,  2.88); histos[mapname]->SetBinError(6,sqrt(pow( 1.29,2)+pow( 0.88,2)));
		histos[mapname]->SetBinContent(7,  2.88); histos[mapname]->SetBinError(7,sqrt(pow( 1.29,2)+pow( 0.88,2)));
	   } if(i3==2&&i2==5){//hHT,6j,0b
		histos[mapname]->SetBinContent(1,  2.80); histos[mapname]->SetBinError(1,sqrt(pow( 1.40,2)+pow( 0.80,2)));
		histos[mapname]->SetBinContent(2,  3.43); histos[mapname]->SetBinError(2,sqrt(pow( 1.98,2)+pow( 0.93,2)));
	//	histos[mapname]->SetBinContent(3,); histos[mapname]->SetBinError(3,sqrt(pow(,2)+pow(,2)));
	  } if(i3==0&&i2==1){//lHT,2j,1b
		histos[mapname]->SetBinContent(1, 33.99); histos[mapname]->SetBinError(1,sqrt(pow( 1.21,2)+pow(10.70,2)));
		histos[mapname]->SetBinContent(2, 22.83); histos[mapname]->SetBinError(2,sqrt(pow( 1.00,2)+pow( 7.19,2)));
		histos[mapname]->SetBinContent(3, 17.90); histos[mapname]->SetBinError(3,sqrt(pow( 0.91,2)+pow( 6.97,2)));
		histos[mapname]->SetBinContent(4, 13.92); histos[mapname]->SetBinError(4,sqrt(pow( 0.82,2)+pow( 5.44,2)));
		histos[mapname]->SetBinContent(5,  9.25); histos[mapname]->SetBinError(5,sqrt(pow( 0.65,2)+pow( 3.56,2)));
		histos[mapname]->SetBinContent(6,  1.91); histos[mapname]->SetBinError(6,sqrt(pow( 0.30,2)+pow( 0.74,2)));
	   } if(i3==0&&i2==3){//lHT,35j,1b
		histos[mapname]->SetBinContent(1, 87.24); histos[mapname]->SetBinError(1,sqrt(pow( 2.82,2)+pow(22.79,2)));
		histos[mapname]->SetBinContent(2, 64.63); histos[mapname]->SetBinError(2,sqrt(pow( 2.45,2)+pow(16.77,2)));
		histos[mapname]->SetBinContent(3, 42.61); histos[mapname]->SetBinError(3,sqrt(pow( 1.94,2)+pow(14.56,2)));
		histos[mapname]->SetBinContent(4, 23.77); histos[mapname]->SetBinError(4,sqrt(pow( 1.52,2)+pow( 8.25,2)));
		histos[mapname]->SetBinContent(5, 11.56); histos[mapname]->SetBinError(5,sqrt(pow( 1.04,2)+pow( 3.90,2)));
		histos[mapname]->SetBinContent(6,  2.66); histos[mapname]->SetBinError(6,sqrt(pow( 0.50,2)+pow( 0.91,2)));
	   } if(i3==0&&i2==6){//lHT,6j,1b
		histos[mapname]->SetBinContent(1,  2.12); histos[mapname]->SetBinError(1,sqrt(pow( 0.61,2)+pow( 1.40,2)));
		histos[mapname]->SetBinContent(2,  1.84); histos[mapname]->SetBinError(2,sqrt(pow( 0.53,2)+pow( 1.22,2)));
		histos[mapname]->SetBinContent(3,  1.55); histos[mapname]->SetBinError(3,sqrt(pow( 0.64,2)+pow( 1.11,2)));
	   } if(i3==1&&i2==1){//mHT,2j,1b
		histos[mapname]->SetBinContent(1, 12.04); histos[mapname]->SetBinError(1,sqrt(pow( 0.61,2)+pow( 6.91,2)));
		histos[mapname]->SetBinContent(2,  8.03); histos[mapname]->SetBinError(2,sqrt(pow( 0.54,2)+pow( 4.61,2)));
		histos[mapname]->SetBinContent(3,  8.67); histos[mapname]->SetBinError(3,sqrt(pow( 0.58,2)+pow( 4.97,2)));
		histos[mapname]->SetBinContent(4,  5.38); histos[mapname]->SetBinError(4,sqrt(pow( 0.49,2)+pow( 3.31,2)));
		histos[mapname]->SetBinContent(5,  2.65); histos[mapname]->SetBinError(5,sqrt(pow( 0.34,2)+pow( 1.63,2)));
	   } if(i3==1&&i2==3){//mHT,35j,1b
		histos[mapname]->SetBinContent(1, 16.86); histos[mapname]->SetBinError(1,sqrt(pow( 1.14,2)+pow( 3.89,2)));
		histos[mapname]->SetBinContent(2, 15.66); histos[mapname]->SetBinError(2,sqrt(pow( 1.16,2)+pow( 3.62,2)));
		histos[mapname]->SetBinContent(3, 16.99); histos[mapname]->SetBinError(3,sqrt(pow( 1.18,2)+pow( 3.92,2)));
		histos[mapname]->SetBinContent(4, 13.70); histos[mapname]->SetBinError(4,sqrt(pow( 1.13,2)+pow( 3.17,2)));
		histos[mapname]->SetBinContent(5,  8.91); histos[mapname]->SetBinError(5,sqrt(pow( 0.89,2)+pow( 2.87,2)));
		histos[mapname]->SetBinContent(6,  2.27); histos[mapname]->SetBinError(6,sqrt(pow( 0.45,2)+pow( 0.73,2)));
	   } if(i3==1&&i2==6){//mHT,6j,1b
		histos[mapname]->SetBinContent(1,  2.41); histos[mapname]->SetBinError(1,sqrt(pow( 0.70,2)+pow( 1.39,2)));
		histos[mapname]->SetBinContent(2,  1.55); histos[mapname]->SetBinError(2,sqrt(pow( 0.52,2)+pow( 0.89,2)));
		histos[mapname]->SetBinContent(3,  1.11); histos[mapname]->SetBinError(3,sqrt(pow( 0.45,2)+pow( 0.64,2)));
		histos[mapname]->SetBinContent(4,  0.85); histos[mapname]->SetBinError(4,sqrt(pow( 0.42,2)+pow( 0.53,2)));
	   } if(i3==2&&i2==1){//hHT,2j,1b
		histos[mapname]->SetBinContent(1,  2.69); histos[mapname]->SetBinError(1,sqrt(pow( 0.31,2)+pow( 1.80,2)));
		histos[mapname]->SetBinContent(2,  2.25); histos[mapname]->SetBinError(2,sqrt(pow( 0.31,2)+pow( 1.51,2)));
	   } if(i3==2&&i2==3){//hHT,35j,1b
		histos[mapname]->SetBinContent(1,  2.16); histos[mapname]->SetBinError(1,sqrt(pow( 0.41,2)+pow( 0.61,2)));
		histos[mapname]->SetBinContent(2,  2.40); histos[mapname]->SetBinError(2,sqrt(pow( 0.43,2)+pow( 0.67,2)));
		histos[mapname]->SetBinContent(3,  2.57); histos[mapname]->SetBinError(3,sqrt(pow( 0.49,2)+pow( 0.72,2)));
		histos[mapname]->SetBinContent(4,  1.70); histos[mapname]->SetBinError(4,sqrt(pow( 0.40,2)+pow( 0.61,2)));
	   } if(i3==2&&i2==6){//hHT,6j,1b
		histos[mapname]->SetBinContent(1,  1.06); histos[mapname]->SetBinError(1,sqrt(pow( 0.44,2)+pow( 0.84,2)));
		histos[mapname]->SetBinContent(2,  0.92); histos[mapname]->SetBinError(2,sqrt(pow( 0.53,2)+pow( 0.73,2)));
	//	histos[mapname]->SetBinContent(3,); histos[mapname]->SetBinError(3,sqrt(pow(,2)+pow(,2)));
	   }
	}}

	cout << "Saving." << endl;
    	TFile *fsavefile = new TFile("../Results/Filtered/GammaJetsPrediction/20130617_test/ZinvPredictionNumbers.root","RECREATE");
	fsavefile->cd();
	for(map<string,TH1D*>::iterator h=histos.begin(); h!=histos.end();++h){
		h->second->Write();
	}
	fsavefile->Close();
	cout << "Saved histograms in " << fsavefile->GetName() << endl;

	//make the plots - not TDR style
    TLatex TitleBox;
	TitleBox.SetNDC();
    TitleBox.SetNDC();
    TitleBox.SetTextAlign(12);
    TitleBox.SetTextFont(42);
    TitleBox.SetTextSize(0.04219409);
    TitleBox.SetLineWidth(2);
	TString text;
    string outname;
    double max = 0.;
    double max1,max2;
    string outputdir = "../Results/Filtered/GammaJetsPrediction/20130617_test/ZinvPredictionPlots/";
    	Util::MakeOutputDir(outputdir);

   TCanvas *c1 = new TCanvas("c1", "c1",485,220,700,504);
   c1->Range(82.71719,-0.4425771,532.9945,2.212885);
    c1->SetFillColor(0);
    c1->SetBorderMode(0);
    c1->SetBorderSize(2);
   c1->SetLeftMargin(0.1494253);
   c1->SetRightMargin(0.07327586);
   c1->SetTopMargin(0.08016878);
   c1->SetBottomMargin(0.1666667);
    c1->SetFrameBorderMode(0);
    c1->SetFrameBorderMode(0);
	for(int i3 = 0; i3<HTbinsize;        ++i3){
	for(int i2 = 0; i2<signalregionsize; ++i2){
	   string hs = string("_") + HT_bin[i3] + string("_") + signal_region[i2];// + string("_") + sample_type[i1];
	   string mapname   = "MT2pred"  + hs;
	   string mapnameMC = "MT2truth" + hs;
	   if(i3==0&&i2==0){//lHT,2j,0b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 1.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "2 jets, 0 b-jets, low H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(1.);
		histos[mapnameMC]->SetMinimum(1.);
		text = "2 jets, 0 b-jets, low H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==0&&i2==2){//lHT,35j,0b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 1.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "3-5 jets, 0 b-jets, low H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(1.);
		histos[mapnameMC]->SetMinimum(1.);
		text = "3-5 jets, 0 b-jets, low H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==0&&i2==5){//lHT,6j,0b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 1.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "#geq6 jets, 0 b-jets, low H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(1.);
		histos[mapnameMC]->SetMinimum(1.);
		text = "#geq6 jets, 0 b-jets, low H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==1&&i2==0){//mHT,2j,0b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 1.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "2 jets, 0 b-jets, medium H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(1.);
		histos[mapnameMC]->SetMinimum(1.);
		text = "2 jets, 0 b-jets, medium H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==1&&i2==2){//mHT,35j,0b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 1.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "3-5 jets, 0 b-jets, medium H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(1.);
		histos[mapnameMC]->SetMinimum(1.);
		text = "3-5 jets, 0 b-jets, medium H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==1&&i2==5){//mHT,6j,0b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 1.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "#geq6 jets, 0 b-jets, medium H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.2);
		histos[mapnameMC]->SetMinimum(0.2);
		text = "#geq6 jets, 0 b-jets, medium H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==2&&i2==0){//hHT,2j,0b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 1.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "2 jets, 0 b-jets, high H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(1.);
		histos[mapnameMC]->SetMinimum(1.);
		text = "2 jets, 0 b-jets, high H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==2&&i2==2){//hHT,35j,0b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 1.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "3-5 jets, 0 b-jets, high H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(1.);
		histos[mapnameMC]->SetMinimum(1.);
		text = "3-5 jets, 0 b-jets, high H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==2&&i2==5){//hHT,6j,0b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
	//	max = 1.5*max;
		max = 5.5;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "#geq6 jets, 0 b-jets, high H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(1.);
		histos[mapnameMC]->SetMinimum(1.);
		text = "#geq6 jets, 0 b-jets, high H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==0&&i2==1){//lHT,2j,1b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 1.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "2 jets, #geq1 b-jets, low H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(1.);
		histos[mapnameMC]->SetMinimum(1.);
		text = "2 jets, #geq1 b-jets, low H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==0&&i2==3){//lHT,35j,1b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 1.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "3-5 jets, 1 b-jet, low H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(1.);
		histos[mapnameMC]->SetMinimum(1.);
		text = "3-5 jets, 1 b-jet, low H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==0&&i2==6){//lHT,6j,1b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
	//	max = 1.5*max;
		max = 3.5;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "#geq6 jets, 1 b-jet, low H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.3);
		histos[mapnameMC]->SetMinimum(0.3);
		text = "#geq6 jets, 1 b-jet, low H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==1&&i2==1){//mHT,2j,1b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 1.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "2 jets, #geq1 b-jets, medium H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(1.);
		histos[mapnameMC]->SetMinimum(1.);
		text = "2 jets, #geq1 b-jets, medium H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==1&&i2==3){//mHT,35j,1b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 1.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "3-5 jets, 1 b-jet, medium H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(1.);
		histos[mapnameMC]->SetMinimum(1.);
		text = "3-5 jets, 1 b-jet, medium H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==1&&i2==6){//mHT,6j,1b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 1.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "#geq6 jets, 1 b-jet, medium H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.3);
		histos[mapnameMC]->SetMinimum(0.3);
		text = "#geq6 jets, 1 b-jet, medium H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==2&&i2==1){//hHT,2j,1b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
	//	max = 1.5*max;
		max = 6.5;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "2 jets, #geq1 b-jets, high H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(1.);
		histos[mapnameMC]->SetMinimum(1.);
		text = "2 jets, #geq1 b-jets, high H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==2&&i2==3){//hHT,35j,1b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 1.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "3-5 jets, 1 b-jet, high H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(1.);
		histos[mapnameMC]->SetMinimum(1.);
		text = "3-5 jets, 1 b-jet, high H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
		c1->Clear();
	   } if(i3==2&&i2==6){//hHT,6j,1b
		c1->Clear();
		c1->cd();
    		gPad->SetLogy(0);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
	//	max = 1.5*max;
		max = 2.;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.);
		histos[mapnameMC]->SetMinimum(0.);
		text = "#geq6 jets, 1 b-jet, high H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + ".eps";
		c1->SaveAs(outname.c_str());

		c1->Clear();
		c1->cd();
    		gPad->SetLogy(1);
		max1=histos[mapname]  ->GetMaximum();
		max2=histos[mapnameMC]->GetMaximum();
		max  = (max1>max2)?max1:max2;
		max = 2.5*max;
		histos[mapname  ]->SetMaximum(max);
		histos[mapnameMC]->SetMaximum(max);
		histos[mapname  ]->SetMinimum(0.2);
		histos[mapnameMC]->SetMinimum(0.2);
		text = "#geq6 jets, 1 b-jet, high H_{T}";
		histos[mapnameMC]->Draw("E2");
		histos[mapname  ]->Draw("sameE1");
		leg->Draw();
		TitleBox.DrawLatex(0.1494253,0.9493671,text.Data());
		outname = histos[mapname  ]->GetName();outname = outputdir + outname + "_log.eps";
		c1->SaveAs(outname.c_str());
	//	c1->Clear();
	   }
	}}

}
void 
HTT_EM_X(bool scaled=true, bool log=true, float min=0.1, float max=-1., TString datacard="htt_em_0_7TeV", string inputfile="root/$HISTFILE", const char* directory="emu_$CATEGORY")
{
  // define common canvas, axes pad styles
  SetStyle(); gStyle->SetLineStyleString(11,"20 10");

  // determine category tag
  const char* category = ""; const char* category_extra = ""; const char* category_extra2 = "";
  if(std::string(directory) == std::string("emu_0jet_low"             )){ category = "e#mu, 0 jet";          }    
  if(std::string(directory) == std::string("emu_0jet_low"             )){ category_extra = "p_{T}(lep1) low";          }    
  if(std::string(directory) == std::string("emu_0jet_high"            )){ category = "e#mu, 0 jet";          }    
  if(std::string(directory) == std::string("emu_0jet_high"            )){ category_extra = "p_{T}(lep1) high";         }    
  if(std::string(directory) == std::string("emu_1jet_low"          )){ category = "e#mu, 1 jet";          }    
  if(std::string(directory) == std::string("emu_1jet_low"          )){ category_extra = "p_{T}(lep1) low";       }    
  if(std::string(directory) == std::string("emu_1jet_high"          )){ category = "e#mu, 1 jet";          }    
  if(std::string(directory) == std::string("emu_1jet_high"          )){ category_extra = "p_{T}(lep1) high";       }    
  if(std::string(directory) == std::string("emu_vbf_loose"            )){ category = "e#mu, 2 jet";          }    
  if(std::string(directory) == std::string("emu_vbf_loose"            )){ category_extra = "VBF, loose";              }    
  if(std::string(directory) == std::string("emu_vbf_tight"            )){ category = "e#mu, 2 jet";          }    
  if(std::string(directory) == std::string("emu_vbf_tight"            )){ category_extra = "VBF, tight";              }    
  if(std::string(directory) == std::string("emu_nobtag"               )){ category = "e#mu";          }    
  if(std::string(directory) == std::string("emu_nobtag"               )){ category_extra = "No B-Tag";                        }    
  if(std::string(directory) == std::string("emu_btag"                 )){ category = "e#mu";          }    
  if(std::string(directory) == std::string("emu_btag"                 )){ category_extra = "B-Tag";                           }

  const char* dataset;
  if(std::string(inputfile).find("7TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 4.9 fb^{-1} at 7 TeV";}
  if(std::string(inputfile).find("8TeV")!=std::string::npos){dataset = "CMS Preliminary,  H#rightarrow#tau#tau, 19.7 fb^{-1} at 8 TeV";}
  
  TFile* input = new TFile(inputfile.c_str());
#ifdef MSSM
  TFile* input2 = new TFile((inputfile+"_$MA_$TANB").c_str());
#endif
  TH1F* Fakes  = refill((TH1F*)input->Get(TString::Format("%s/Fakes"     , directory)), "Fakes"  ); InitHist(Fakes, "", "", kMagenta-10, 1001);
  TH1F* EWK    = refill((TH1F*)input->Get(TString::Format("%s/EWK"       , directory)), "EWK"    ); InitHist(EWK  , "", "", kRed    + 2, 1001);
  TH1F* ttbar  = refill((TH1F*)input->Get(TString::Format("%s/ttbar"     , directory)), "ttbar"  ); InitHist(ttbar, "", "", kBlue   - 8, 1001);
  TH1F* Ztt    = refill((TH1F*)input->Get(TString::Format("%s/Ztt"       , directory)), "Ztt"    ); InitHist(Ztt  , "", "", kOrange - 4, 1001);
#ifdef MSSM
  TH1F* ggH  = refill((TH1F*)input2->Get(TString::Format("%s/ggH$MA"     , directory)), "ggH"    ); InitSignal(ggH    ); ggH    ->Scale($TANB);
  TH1F* bbH  = refill((TH1F*)input2->Get(TString::Format("%s/bbH$MA"     , directory)), "bbH"    ); InitSignal(bbH    ); bbH    ->Scale($TANB);
#else
#ifdef HWW_BG
  TH1F* ggH_hww= refill((TH1F*)input->Get(TString::Format("%s/ggH_hww125", directory)), "ggH_hww"); InitHist(ggH_hww  , "", "", kGreen + 2, 1001); ggH_hww->Scale(SIGNAL_SCALE);
  TH1F* qqH_hww= refill((TH1F*)input->Get(TString::Format("%s/qqH_hww125", directory)), "qqH_hww"); InitHist(qqH_hww  , "", "", kGreen + 2, 1001); qqH_hww->Scale(SIGNAL_SCALE);
#else
 TH1F* ggH_hww= refill((TH1F*)input->Get(TString::Format("%s/ggH_hww125", directory)), "ggH_hww"); InitSignal(ggH_hww); ggH_hww->Scale(SIGNAL_SCALE);
  TH1F* qqH_hww= refill((TH1F*)input->Get(TString::Format("%s/qqH_hww125", directory)), "qqH_hww"); InitSignal(qqH_hww); qqH_hww->Scale(SIGNAL_SCALE);
#endif
#ifndef DROP_SIGNAL
  TH1F* ggH    = refill((TH1F*)input->Get(TString::Format("%s/ggH125"    , directory)), "ggH"    ); InitSignal(ggH    ); ggH    ->Scale(SIGNAL_SCALE);
  TH1F* qqH    = refill((TH1F*)input->Get(TString::Format("%s/qqH125"    , directory)), "qqH"    ); InitSignal(qqH    ); qqH    ->Scale(SIGNAL_SCALE);
  TH1F* VH     = refill((TH1F*)input->Get(TString::Format("%s/VH125"     , directory)), "VH"     ); InitSignal(VH     ); VH     ->Scale(SIGNAL_SCALE);
#ifndef HWW_BG
  ggH->Add(ggH_hww);
  qqH->Add(qqH_hww);
#endif
#endif
#endif
#ifdef ASIMOV
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs_asimov", directory)), "data", true);
#else
  TH1F* data   = refill((TH1F*)input->Get(TString::Format("%s/data_obs", directory)), "data", true);
#endif
  InitHist(data, "#bf{m_{#tau#tau} [GeV]}", "#bf{dN/dm_{#tau#tau} [1/GeV]}"); InitData(data);

  TH1F* ref=(TH1F*)Fakes->Clone("ref");
  ref->Add(EWK  );
  ref->Add(ttbar);
  ref->Add(Ztt  );
#ifdef HWW_BG
  ref->Add(qqH_hww);
  ref->Add(ggH_hww);
#endif

#ifdef HWW_BG
  const int numhistos = 9;
  const int offset = 2;
#else
  const int numhistos = 7;
  const int offset = 0;
#endif
  double unscaled[numhistos];
  unscaled[0] = Fakes->Integral();
  unscaled[1] = EWK  ->Integral();
  unscaled[2] = ttbar->Integral();
  unscaled[3] = Ztt  ->Integral();
#ifdef MSSM
  unscaled[4] = ggH  ->Integral();
  unscaled[5] = bbH  ->Integral();
  unscaled[6] = 0;
#else
#ifdef HWW_BG
  unscaled[4] = ggH_hww  ->Integral();
  unscaled[5] = qqH_hww  ->Integral();
#endif
#ifndef DROP_SIGNAL
  unscaled[4+offset] = ggH  ->Integral();
  unscaled[5+offset] = qqH  ->Integral();
  unscaled[6+offset] = VH   ->Integral();
#endif
#endif

  if(scaled){
    Fakes = refill(shape_histos(Fakes, datacard, "Fakes"), "Fakes"); 
    EWK = refill(shape_histos(EWK, datacard, "EWK"), "EWK"); 
    ttbar = refill(shape_histos(ttbar, datacard, "ttbar"), "ttbar"); 
    Ztt = refill(shape_histos(Ztt, datacard, "Ztt"), "Ztt"); 
#ifdef MSSM
    ggH = refill(shape_histos(ggH, datacard, "ggH$MA"), "ggH$MA"); 
    bbH = refill(shape_histos(bbH, datacard, "bbH$MA"), "bbH$MA"); 
#else
#ifndef DROP_SIGNAL
    ggH = refill(shape_histos(ggH, datacard, "ggH"), "ggH"); 
    qqH = refill(shape_histos(qqH, datacard, "qqH"), "qqH"); 
    VH = refill(shape_histos(VH, datacard, "VH"), "VH"); 
#endif  
#endif
#ifdef HWW_BG
    ggH_hww = refill(shape_histos(ggH_hww, datacard, "ggH_hww125"), "ggH_hww125");
    qqH_hww = refill(shape_histos(qqH_hww, datacard, "qqH_hww125"), "qqH_hww125");
#endif
    
    rescale(Fakes, 4); 
    rescale(EWK,   3); 
    rescale(ttbar, 2); 
    rescale(Ztt,   1);
#ifdef MSSM 
    rescale(ggH,   5);
    rescale(bbH,   6);
#else
#ifdef HWW_BG
    rescale(qqH_hww, 8);
    rescale(qqH_hww, 9);
#endif
#ifndef DROP_SIGNAL
    rescale(ggH,   5);
    rescale(qqH,   6);
    rescale(VH,    7);
#endif
#endif
  }

  TH1F* scales[numhistos];
  scales[0] = new TH1F("scales-Fakes", "", numhistos, 0, numhistos);
  scales[0]->SetBinContent(1, unscaled[0]>0 ? (Fakes->Integral()/unscaled[0]-1.) : 0.);
  scales[1] = new TH1F("scales-EWK"  , "", numhistos, 0, numhistos);
  scales[1]->SetBinContent(2, unscaled[1]>0 ? (EWK  ->Integral()/unscaled[1]-1.) : 0.);
  scales[2] = new TH1F("scales-ttbar", "", numhistos, 0, numhistos);
  scales[2]->SetBinContent(3, unscaled[2]>0 ? (ttbar->Integral()/unscaled[2]-1.) : 0.);
  scales[3] = new TH1F("scales-Ztt"  , "", numhistos, 0, numhistos);
  scales[3]->SetBinContent(4, unscaled[3]>0 ? (Ztt  ->Integral()/unscaled[3]-1.) : 0.);
#ifdef MSSM
  scales[4] = new TH1F("scales-ggH"  , "", numhistos, 0, numhistos);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH"  , "", numhistos, 0, numhistos);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (bbH  ->Integral()/unscaled[5]-1.) : 0.);
  scales[6] = new TH1F("scales-NONE" , "", numhistos, 0, numhistos);
  scales[6]->SetBinContent(numhistos, 0.);
#else
#ifdef HWW_BG
  scales[4] = new TH1F("scales-ggH_hww"  , "", numhistos, 0, numhistos);
  scales[4]->SetBinContent(5, unscaled[4]>0 ? (ggH_hww  ->Integral()/unscaled[4]-1.) : 0.);
  scales[5] = new TH1F("scales-qqH_hww"  , "", numhistos, 0, numhistos);
  scales[5]->SetBinContent(6, unscaled[5]>0 ? (qqH_hww  ->Integral()/unscaled[5]-1.) : 0.);
#endif  
#ifndef DROP_SIGNAL
  scales[4+offset] = new TH1F("scales-ggH"  , "", numhistos, 0, numhistos);
  scales[4+offset]->SetBinContent(5+offset, unscaled[4+offset]>0 ? (ggH  ->Integral()/unscaled[4+offset]-1.) : 0.);
  scales[5+offset] = new TH1F("scales-qqH"  , "", numhistos, 0, numhistos);
  scales[5+offset]->SetBinContent(6+offset, unscaled[5+offset]>0 ? (qqH  ->Integral()/unscaled[5+offset]-1.) : 0.);
  scales[6+offset] = new TH1F("scales-VH"   , "", numhistos, 0, numhistos);
  scales[6+offset]->SetBinContent(7+offset, unscaled[6+offset]>0 ? (VH   ->Integral()/unscaled[6+offset]-1.) : 0.);
#endif
#endif

  EWK  ->Add(Fakes);
  ttbar->Add(EWK  );
  Ztt  ->Add(ttbar);
#ifdef HWW_BG
  qqH_hww->Add(Ztt);
  ggH_hww->Add(qqH_hww);
#endif
  if(log){
#ifdef MSSM
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }
  else{
#ifdef MSSM
    bbH  ->Add(Ztt);
    ggH  ->Add(bbH);
#else
#ifndef DROP_SIGNAL
#ifdef HWW_BG
    VH   ->Add(qqH_hww);
#else
    VH   ->Add(Ztt);
#endif
    qqH  ->Add(VH );
    ggH  ->Add(qqH);
#endif
#endif
  }

  /*
    mass plot before and after fit
  */
  TCanvas* canv = MakeCanvas("canv", "histograms", 600, 600);
  canv->cd();
  if(log){ canv->SetLogy(1); }
#if defined MSSM
  if(!log){ data->GetXaxis()->SetRange(0, data->FindBin(345)); } else{ data->GetXaxis()->SetRange(0, data->FindBin(UPPER_EDGE)); };
#else
  data->GetXaxis()->SetRange(0, data->FindBin(345));
#endif
  data->SetNdivisions(505);
  data->SetMinimum(min);
#ifndef DROP_SIGNAL
  data->SetMaximum(max>0 ? max : std::max(std::max(maximum(data, log), maximum(Ztt, log)), maximum(ggH, log)));
#else
  data->SetMaximum(max>0 ? max : std::max(maximum(data, log), maximum(Ztt, log)));
#endif
  data->Draw("e");

#ifdef HWW_BG
  TH1F* errorBand = (TH1F*)ggH_hww ->Clone("errorBand");
#else
  TH1F* errorBand = (TH1F*)Ztt ->Clone("errorBand");
#endif
  errorBand  ->SetMarkerSize(0);
  errorBand  ->SetFillColor(1);
  errorBand  ->SetFillStyle(3013);
  errorBand  ->SetLineWidth(1);
  for(int idx=0; idx<errorBand->GetNbinsX(); ++idx){
    if(errorBand->GetBinContent(idx)>0){
      std::cout << "Uncertainties on summed background samples: " << errorBand->GetBinError(idx)/errorBand->GetBinContent(idx) << std::endl;
      break;
    }
  }
  if(log){
#ifdef HWW_BG
    ggH_hww->Draw("histsame");
#endif
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
  }
  else{
#ifndef DROP_SIGNAL
    ggH  ->Draw("histsame");
#endif
#ifdef HWW_BG
    ggH_hww->Draw("histsame");
#endif
    Ztt  ->Draw("histsame");
    ttbar->Draw("histsame");
    EWK  ->Draw("histsame");
    Fakes->Draw("histsame");
    $DRAW_ERROR
  }
  data->Draw("esame");
  canv->RedrawAxis();

  //CMSPrelim(dataset, "#tau_{e}#tau_{#mu}", 0.17, 0.835);
  CMSPrelim(dataset, "", 0.16, 0.835);
  TPaveText* chan     = new TPaveText(0.20, (category_extra2 && category_extra2[0]=='\0') ? 0.65+0.061 : 0.65+0.061, 0.32, 0.75+0.161, "tlbrNDC");
  chan->SetBorderSize(   0 );
  chan->SetFillStyle(    0 );
  chan->SetTextAlign(   12 );
  chan->SetTextSize ( 0.05 );
  chan->SetTextColor(    1 );
  chan->SetTextFont (   62 );
  chan->AddText(category);
  chan->AddText(category_extra);
  chan->AddText(category_extra2);
  chan->Draw();

/*  TPaveText* cat      = new TPaveText(0.20, 0.71+0.061, 0.32, 0.71+0.161, "NDC");
  cat->SetBorderSize(   0 );
  cat->SetFillStyle(    0 );
  cat->SetTextAlign(   12 );
  cat->SetTextSize ( 0.05 );
  cat->SetTextColor(    1 );
  cat->SetTextFont (   62 );
  cat->AddText(category_extra);
  cat->Draw();

#ifdef MSSM
  TPaveText* massA      = new TPaveText(0.53, 0.50+0.061, 0.95, 0.50+0.161, "NDC");
  massA->SetBorderSize(   0 );
  massA->SetFillStyle(    0 );
  massA->SetTextAlign(   12 );
  massA->SetTextSize ( 0.03 );
  massA->SetTextColor(    1 );
  massA->SetTextFont (   62 );
  massA->AddText("m^{h}_{max} (m_{A}=$MA GeV, tan#beta=$TANB)");
  massA->Draw();
#endif
*/
#ifdef MSSM  
  TLegend* leg = new TLegend(0.53, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
  leg->AddEntry(ggH  , "#phi#rightarrow#tau#tau" , "L" );
#else
  TLegend* leg = new TLegend(0.50, 0.65, 0.95, 0.90);
  SetLegendStyle(leg);
#ifndef DROP_SIGNAL
  if(SIGNAL_SCALE!=1){
    leg->AddEntry(ggH  , TString::Format("%.0f#timesH(125 GeV)#rightarrow#tau#tau", SIGNAL_SCALE) , "L" );
  }
  else{
#ifdef HWW_BG
    leg->AddEntry(ggH  , "H(125 GeV)#rightarrow#tau#tau" , "L" );
#else
    leg->AddEntry(ggH  , "#splitline{H(125 GeV)#rightarrow#tau#tau}{H(125 GeV)#rightarrowWW}" , "L" );
    leg->AddEntry((TObject*)0, "", "");
#endif
  }
#endif
#endif
#ifdef ASIMOV
  leg->AddEntry(data , "sum(bkg) + H(125)"              , "LP");
#else
  leg->AddEntry(data , "observed"                       , "LP");
#endif
#ifdef HWW_BG
  leg->AddEntry(ggH_hww  , "H(125 GeV)#rightarrowWW" , "F" );
#endif
  leg->AddEntry(Ztt  , "Z#rightarrow#tau#tau"           , "F" );
  leg->AddEntry(ttbar, "t#bar{t}"                       , "F" );
  leg->AddEntry(EWK  , "electroweak"                    , "F" );
  leg->AddEntry(Fakes, "Fakes"                          , "F" );
  $ERROR_LEGEND
  leg->Draw();

  /*
    Ratio Data over MC
  */
  TCanvas *canv0 = MakeCanvas("canv0", "histograms", 600, 400);
  canv0->SetGridx();
  canv0->SetGridy();
  canv0->cd();
#ifdef HWW_BG
  TH1F* model = (TH1F*)ggH_hww ->Clone("model");
#else
  TH1F* model = (TH1F*)Ztt ->Clone("model");
#endif
  TH1F* test1 = (TH1F*)data->Clone("test1"); 
  for(int ibin=0; ibin<test1->GetNbinsX(); ++ibin){
    //the small value in case of 0 entries in the model is added to prevent the chis2 test from failing
    model->SetBinContent(ibin+1, model->GetBinContent(ibin+1)>0 ? model->GetBinContent(ibin+1)*model->GetBinWidth(ibin+1) : 0.01);
    model->SetBinError  (ibin+1, CONVERVATIVE_CHI2 ? 0. : model->GetBinError  (ibin+1)*model->GetBinWidth(ibin+1));
    test1->SetBinContent(ibin+1, test1->GetBinContent(ibin+1)*test1->GetBinWidth(ibin+1));
    test1->SetBinError  (ibin+1, test1->GetBinError  (ibin+1)*test1->GetBinWidth(ibin+1));
  }
  double chi2prob = test1->Chi2Test      (model,"PUW");        std::cout << "chi2prob:" << chi2prob << std::endl;
  double chi2ndof = test1->Chi2Test      (model,"CHI2/NDFUW"); std::cout << "chi2ndf :" << chi2ndof << std::endl;
  double ksprob   = test1->KolmogorovTest(model);              std::cout << "ksprob  :" << ksprob   << std::endl;
  double ksprobpe = test1->KolmogorovTest(model,"DX");         std::cout << "ksprobpe:" << ksprobpe << std::endl;  

  std::vector<double> edges;
  TH1F* zero = (TH1F*)ref ->Clone("zero"); zero->Clear();
  TH1F* rat1 = (TH1F*)data->Clone("rat1"); 
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    rat1->SetBinContent(ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinContent(ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    rat1->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? data->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
    zero->SetBinContent(ibin+1, 0.);
    zero->SetBinError  (ibin+1, Ztt->GetBinContent(ibin+1)>0 ? Ztt ->GetBinError  (ibin+1)/Ztt->GetBinContent(ibin+1) : 0);
  }
  for(int ibin=0; ibin<rat1->GetNbinsX(); ++ibin){
    if(rat1->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat1->GetBinContent(ibin+1)-1.)+TMath::Abs(rat1->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat1->SetBinContent(ibin+1, rat1->GetBinContent(ibin+1)-1.);
    }
  }
  float range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
  rat1->SetLineColor(kBlack);
  rat1->SetFillColor(kGray );
  rat1->SetMaximum(+range);
  rat1->SetMinimum(-range);
  rat1->GetYaxis()->CenterTitle();
  rat1->GetYaxis()->SetTitle("#bf{Data/MC-1}");
  rat1->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat1->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->SetMarkerSize(0.1);
  zero->Draw("e2histsame");
  canv0->RedrawAxis();

  TPaveText* stat1 = new TPaveText(0.20, 0.76+0.061, 0.32, 0.76+0.161, "NDC");
  stat1->SetBorderSize(   0 );
  stat1->SetFillStyle(    0 );
  stat1->SetTextAlign(   12 );
  stat1->SetTextSize ( 0.05 );
  stat1->SetTextColor(    1 );
  stat1->SetTextFont (   62 );
  stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f", chi2ndof, chi2prob));
  //stat1->AddText(TString::Format("#chi^{2}/ndf=%.3f,  P(#chi^{2})=%.3f, P(KS)=%.3f", chi2ndof, chi2prob, ksprob));
  stat1->Draw();

  /*
    Ratio After fit over Prefit
  */
  TCanvas *canv1 = MakeCanvas("canv1", "histograms", 600, 400);
  canv1->SetGridx();
  canv1->SetGridy();
  canv1->cd();

  edges.clear();
#ifdef HWW_BG
  TH1F* rat2 = (TH1F*) ggH_hww->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? ggH_hww->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? ggH_hww->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
#else
  TH1F* rat2 = (TH1F*) Ztt->Clone("rat2");
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    rat2->SetBinContent(ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinContent(ibin+1)/ref->GetBinContent(ibin+1) : 0);
    rat2->SetBinError  (ibin+1, ref->GetBinContent(ibin+1)>0 ? Ztt->GetBinError  (ibin+1)/ref->GetBinContent(ibin+1) : 0);
  }
#endif
  for(int ibin=0; ibin<rat2->GetNbinsX(); ++ibin){
    if(rat2->GetBinContent(ibin+1)>0){
      edges.push_back(TMath::Abs(rat2->GetBinContent(ibin+1)-1.)+TMath::Abs(rat2->GetBinError(ibin+1)));
      // catch cases of 0 bins, which would lead to 0-alpha*0-1
      rat2 ->SetBinContent(ibin+1, rat2->GetBinContent(ibin+1)-1.);
    }
  }
  range = 0.1;
  std::sort(edges.begin(), edges.end());
  if (edges[edges.size()-2]>0.1) { range = 0.2; }
  if (edges[edges.size()-2]>0.2) { range = 0.5; }
  if (edges[edges.size()-2]>0.5) { range = 1.0; }
  if (edges[edges.size()-2]>1.0) { range = 1.5; }
  if (edges[edges.size()-2]>1.5) { range = 2.0; }
#if defined MSSM
  if(!log){ rat2->GetXaxis()->SetRange(0, rat2->FindBin(345)); } else{ rat2->GetXaxis()->SetRange(0, rat2->FindBin(UPPER_EDGE)); };
#else
  rat2->GetXaxis()->SetRange(0, rat2->FindBin(345));
#endif
  rat2->SetNdivisions(505);
  rat2->SetLineColor(kRed+ 3);
  rat2->SetMarkerColor(kRed+3);
  rat2->SetMarkerSize(1.1);
  rat2->SetMaximum(+range);
  rat2->SetMinimum(-range);
  rat2->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  rat2->GetYaxis()->CenterTitle();
  rat2->GetXaxis()->SetTitle("#bf{m_{#tau#tau} [GeV]}");
  rat2->Draw();
  zero->SetFillStyle(  3013);
  zero->SetFillColor(kBlack);
  zero->SetLineColor(kBlack);
  zero->Draw("e2histsame");
  canv1->RedrawAxis();

  /*
    Relative shift per sample
  */
  TCanvas *canv2 = MakeCanvas("canv2", "histograms", 600, 400);
  canv2->SetGridx();
  canv2->SetGridy();
  canv2->cd();

  InitHist  (scales[0], "", "", kMagenta-10, 1001);
  InitHist  (scales[1], "", "", kRed    + 2, 1001);
  InitHist  (scales[2], "", "", kBlue   - 8, 1001);
  InitHist  (scales[3], "", "", kOrange - 4, 1001);
#ifdef HWW_BG
  InitHist(scales[4], "", "", kGreen + 2, 1001);
  InitHist(scales[5], "", "", kGreen + 2, 1001);
#endif
#ifndef DROP_SIGNAL
  InitSignal(scales[4+offset]);
  InitSignal(scales[5+offset]);
  InitSignal(scales[6+offset]);
#endif
  scales[0]->Draw();
  scales[0]->GetXaxis()->SetBinLabel(1, "#bf{Fakes}");
  scales[0]->GetXaxis()->SetBinLabel(2, "#bf{EWK}"  );
  scales[0]->GetXaxis()->SetBinLabel(3, "#bf{ttbar}");
  scales[0]->GetXaxis()->SetBinLabel(4, "#bf{Ztt}"  );
#ifdef MSSM
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{bbH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7, "#bf{NONE}" );
#else
#ifdef HWW_BG
  scales[0]->GetXaxis()->SetBinLabel(5, "#bf{ggH_hww}");
  scales[0]->GetXaxis()->SetBinLabel(6, "#bf{qqH_hww}");
#endif
  scales[0]->GetXaxis()->SetBinLabel(5+offset, "#bf{ggH}"  );
  scales[0]->GetXaxis()->SetBinLabel(6+offset, "#bf{qqH}"  );
  scales[0]->GetXaxis()->SetBinLabel(7+offset, "#bf{VH}"   );
#endif
  scales[0]->SetMaximum(+0.5);
  scales[0]->SetMinimum(-0.5);
  scales[0]->GetYaxis()->CenterTitle();
  scales[0]->GetYaxis()->SetTitle("#bf{Postfit/Prefit-1}");
  scales[1]->Draw("same");
  scales[2]->Draw("same");
  scales[3]->Draw("same");
#ifdef HWW_BG
  scales[4]->Draw("same");
  scales[5]->Draw("same");
#endif
#ifndef DROP_SIGNAL
  scales[4+offset]->Draw("same");
  scales[5+offset]->Draw("same");
  scales[6+offset]->Draw("same");
#endif
  TH1F* zero_samples = (TH1F*)scales[0]->Clone("zero_samples"); zero_samples->Clear();
  zero_samples->SetBinContent(1,0.);
  zero_samples->Draw("same");
  canv2->RedrawAxis();

  /*
    prepare output
  */
  bool isSevenTeV = std::string(inputfile).find("7TeV")!=std::string::npos;
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.png"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.pdf"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  canv   ->Print(TString::Format("%s_%sfit_%s_%s.eps"       , directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
  if(!log || FULLPLOTS)
  {
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv0->Print(TString::Format("%s_datamc_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }
  if((!log && scaled) || FULLPLOTS)
  {
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv1->Print(TString::Format("%s_prefit_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.png", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN")); 
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.pdf", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
    canv2->Print(TString::Format("%s_sample_%sfit_%s_%s.eps", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"));
  }

  TFile* output = new TFile(TString::Format("%s_%sfit_%s_%s.root", directory, scaled ? "post" : "pre", isSevenTeV ? "7TeV" : "8TeV", log ? "LOG" : "LIN"), "update");
  output->cd(); 
  data ->Write("data_obs");
  Fakes->Write("Fakes"   );
  EWK  ->Write("EWK"     );
  ttbar->Write("ttbar"   );
  Ztt  ->Write("Ztt"     );
#ifdef MSSM
  ggH  ->Write("ggH"     );
  bbH  ->Write("bbH"     );
#else
#ifdef HWW_BG
  ggH_hww  ->Write("ggH_hww"     );
#endif
#ifndef DROP_SIGNAL
  ggH  ->Write("ggH"     );
  qqH  ->Write("qqH"     );
  VH   ->Write("VH"      );
#endif
#endif
  if(errorBand){
    errorBand->Write("errorBand");
  }
  output->Close();
 
  delete errorBand;
  delete model;
  delete test1;
  delete zero;
  delete rat1;
  delete rat2;
  delete zero_samples;
  delete ref;
}
Exemplo n.º 6
0
void diffXsecZbb( TString inputFile1Name,
		  TString inputFile2Name,
		  TString inputFile3Name,
		  TString eventsNumberHistoName,
		  TString HistoName) {
  // general root setting
  gROOT->Reset(); 
  //  gROOT->SetBatch(kTRUE);
  gStyle->SetOptStat(0);
  gStyle->SetTitleSize(0.1);
  gStyle->SetLabelSize(0.04,"X");
  gStyle->SetLabelSize(0.04,"Y");
  gStyle->SetPadBorderMode(0);
  gStyle->SetPadColor(0);
  gStyle->SetCanvasBorderMode(0);
  gStyle->SetCanvasColor(0);

  const double xSec_Zbb0jets_  = 1.66; // in pb	  
  const double xSec_Zbb1jets_  = 0.29; // in pb	  
  const double xSec_Zbb2jets_  = 0.05; // in pb	  
  const double xSec_Zbb3jets_  = 0.01; // in pb	  

  const double leptonFactor = 2.0;

  const double luminosityFactor = 100000.; // 100fb^-1 of luminosity assumed in histograms

  TFile * inputFile1 = new TFile(inputFile1Name);
  TFile * inputFile2 = new TFile(inputFile2Name);
  TFile * inputFile3 = new TFile(inputFile3Name);
 
  TH1D * eventsNumberHisto1 = dynamic_cast<TH1D*>(inputFile1->Get(eventsNumberHistoName));
  TH1D * histo1 = dynamic_cast<TH1D*>(inputFile1->Get(HistoName));
  TH1D * histoirrBkg1 = dynamic_cast<TH1D*>(inputFile1->Get(HistoName+"irrBkg"));
  TH1D * eventsNumberHisto2 = dynamic_cast<TH1D*>(inputFile2->Get(eventsNumberHistoName));
  TH1D * histo2 = dynamic_cast<TH1D*>(inputFile2->Get(HistoName));
  TH1D * histoirrBkg2 = dynamic_cast<TH1D*>(inputFile2->Get(HistoName+"irrBkg"));
  TH1D * eventsNumberHisto3 = dynamic_cast<TH1D*>(inputFile3->Get(eventsNumberHistoName));
  TH1D * histo3 = dynamic_cast<TH1D*>(inputFile3->Get(HistoName));
  TH1D * histoirrBkg3 = dynamic_cast<TH1D*>(inputFile3->Get(HistoName+"irrBkg"));

  TString HistoTitle = histo1->GetTitle();
  int nbin = histo1->GetNbinsX();
  double xmin = histo1->GetXaxis()->GetXmin();
  double xmax = histo1->GetXaxis()->GetXmax();
  TH1D * histoTot       = new TH1D(HistoName+"TOT",      "inclusive "+HistoTitle,nbin,xmin,xmax);
  TH1D * histoirrBkgTot = new TH1D(HistoName+"irrBkgTOT","inclusive irrudicible background "+HistoTitle,nbin,xmin,xmax);

  histo1->SetTitle(HistoTitle+ " for Zbb 0 jets");
  histo2->SetTitle(HistoTitle+ " for Zbb 1 jets");
  histo3->SetTitle(HistoTitle+ " for Zbb 2 jets");
  histoirrBkg1->SetTitle("irriducible background "+HistoTitle+ " for Zbb 0 jets");
  histoirrBkg2->SetTitle("irriducible background "+HistoTitle+ " for Zbb 1 jets");
  histoirrBkg3->SetTitle("irriducible background "+HistoTitle+ " for Zbb 2 jets");

  double histo1Entries = histo1->GetEntries();
  double histo2Entries = histo2->GetEntries();
  double histo3Entries = histo3->GetEntries();
  double histoirrBkg1Entries = histoirrBkg1->GetEntries();
  double histoirrBkg2Entries = histoirrBkg2->GetEntries();
  double histoirrBkg3Entries = histoirrBkg3->GetEntries();
  double events1 = (double)eventsNumberHisto1->GetMaximum(); 
  double events2 = (double)eventsNumberHisto2->GetMaximum();
  double events3 = (double)eventsNumberHisto3->GetMaximum();
  double xSecEff1  = leptonFactor*xSec_Zbb0jets_;
  double xSecEff2  = leptonFactor*xSec_Zbb1jets_;
  double xSecEff3  = leptonFactor*xSec_Zbb2jets_;
  double invLuminosityEff1 = xSecEff1/events1;
  double invLuminosityEff2 = xSecEff2/events2;
  double invLuminosityEff3 = xSecEff3/events3;


  TLegend * legend1 = new TLegend(0.5,0.6,0.89,0.8);
  legend1->SetFillColor(0);
  legend1->SetBorderSize(0);  
  legend1->SetTextFont(72);
  legend1->SetTextSize(0.035);
  legend1->SetFillColor(0);
  TLegend * legend2 = new TLegend(0.5,0.6,0.89,0.8);
  legend2->SetFillColor(0);
  legend2->SetBorderSize(0);  
  legend2->SetTextFont(72);
  legend2->SetTextSize(0.035);
  legend2->SetFillColor(0);
  TLegend * legend3 = new TLegend(0.5,0.6,0.89,0.8);
  legend3->SetFillColor(0);
  legend3->SetBorderSize(0);  
  legend3->SetTextFont(72);
  legend3->SetTextSize(0.035);
  legend3->SetFillColor(0);
  TLegend * legendTot = new TLegend(0.7,0.65,0.89,0.85);
  legendTot->SetFillColor(0);
  legendTot->SetBorderSize(0);  
  legendTot->SetTextFont(72);
  legendTot->SetTextSize(0.035);
  legendTot->SetFillColor(0);
  char nev[50];

  TCanvas * canvas = new TCanvas ( "diffxSec", "differential xSec", 1200, 400 );
  gStyle->SetOptStat(0);
  //  canvas->UseCurrentStyle();
  canvas->Divide(3,1);
  canvas->cd(1);
  histo1->SetNormFactor(histo1Entries*invLuminosityEff1*luminosityFactor);
  histo1->Draw();
  sprintf(nev,"number of events in 100 fb^{-1}:");
  sprintf(nev,"%.2f",histo1Entries*invLuminosityEff1*luminosityFactor);
  legend1->AddEntry(histo1,nev,"");
  legend1->Draw();
  canvas->cd(2);
  histo2->SetNormFactor(histo2Entries*invLuminosityEff2*luminosityFactor);
  histo2->Draw();
  legend2->Clear();
  sprintf(nev,"number of events in 100 fb^{-1}:");
  sprintf(nev,"%.2f",histo2Entries*invLuminosityEff2*luminosityFactor);
  legend2->AddEntry(histo2,nev,"");
  legend2->Draw();
  canvas->cd(3);
  histo3->SetNormFactor(histo3Entries*invLuminosityEff3*luminosityFactor);
  histo3->Draw();
  legend3->Clear();
  sprintf(nev,"number of events in 100 fb^{-1}:");
  sprintf(nev,"%.2f",histo3Entries*invLuminosityEff3*luminosityFactor);
  legend3->AddEntry(histo3,nev,"");
  legend3->Draw();

  histoTot->Sumw2();
  histoTot->Add(histo1);
  histoTot->Add(histo2);
  histoTot->Add(histo3);

  TCanvas * canvasTot = new TCanvas ( "inclusivediffxSec", "differential xSec", 1200, 400 );
  gStyle->SetOptStat(0);
  canvasTot->UseCurrentStyle();
  canvasTot->cd();
  histo1->SetTitle("4-body mass (100 fb^{-1})");
  histo1->GetXaxis()->SetTitle("m_{llbb} (GeV)");
  histo1->GetYaxis()->SetTitle("d#sigma/dm_{llbb} events/10GeV");
  histo1->SetMinimum(0.001);
  histo1->SetLineColor(51);
  histo1->Draw();
  histo2->SetLineColor(56);
  histo2->Draw("same");
  histo3->SetLineColor(60);
  histo3->Draw("same");
  histoTot->Draw("same");

  legendTot->Clear();
  sprintf(nev,"Zb\\bar{b}+0jets");
  legendTot->AddEntry(histo1,nev,"l");
  sprintf(nev,"Zb\\bar{b}+1jets");
  legendTot->AddEntry(histo2,nev,"l");
  sprintf(nev,"Zb\\bar{b}+2jets");
  legendTot->AddEntry(histo3,nev,"l");
  sprintf(nev,"inclusive");
  legendTot->AddEntry(histoTot,nev,"l");
  legendTot->Draw();



  TCanvas * canvasirrBkg = new TCanvas ( "diffxSecirrbkg", "differential xSec for irriducible background", 1200, 400 );
  gStyle->SetOptStat(0);
  canvasirrBkg->UseCurrentStyle();
  canvasirrBkg->Divide(3,1);
  canvasirrBkg->cd(1);
  histoirrBkg1->SetNormFactor(histoirrBkg1Entries*invLuminosityEff1*luminosityFactor);
  histoirrBkg1->Draw();
  sprintf(nev,"number of events in 100 fb^{-1}:");
  sprintf(nev,"%.2f",histoirrBkg1Entries*invLuminosityEff1*luminosityFactor);
  legend1->AddEntry(histoirrBkg1,nev,"");
  legend1->Draw();
  canvasirrBkg->cd(2);
  histoirrBkg2->SetNormFactor(histoirrBkg2Entries*invLuminosityEff2*luminosityFactor);
  histoirrBkg2->Draw();
  legend2->Clear();
  sprintf(nev,"number of events in 100 fb^{-1}:");
  sprintf(nev,"%.2f",histoirrBkg2Entries*invLuminosityEff2*luminosityFactor);
  legend2->AddEntry(histoirrBkg2,nev,"");
  legend2->Draw();
  canvasirrBkg->cd(3);
  histoirrBkg3->SetNormFactor(histoirrBkg3Entries*invLuminosityEff3*luminosityFactor);
  histoirrBkg3->Draw();
  legend3->Clear();
  sprintf(nev,"number of events in 100 fb^{-1}:");
  sprintf(nev,"%.2f",histoirrBkg3Entries*invLuminosityEff3*luminosityFactor);
  legend3->AddEntry(histoirrBkg3,nev,"");
  legend3->Draw();

  histoirrBkgTot->Sumw2();
  histoirrBkgTot->Add(histoirrBkg1);
  histoirrBkgTot->Add(histoirrBkg2);
  histoirrBkgTot->Add(histoirrBkg3);

  TCanvas * canvasirrBkgTot = new TCanvas ( "inclusivediffxSecirrBkg", "differential xSec", 1200, 400 );
  gStyle->SetOptStat(0);
  canvasirrBkgTot->UseCurrentStyle();
  canvasirrBkgTot->cd();
  gPad->SetLogy();
  histoirrBkg1->SetTitle("4-body mass (100 fb^{-1})");
  histoirrBkg1->GetXaxis()->SetTitle("m_{llbb} (GeV)");
  histoirrBkg1->GetYaxis()->SetTitle("d#sigma/dm_{llbb} events/10GeV");
  histoirrBkg1->SetMinimum(0.001);
  histoirrBkg1->SetLineColor(51);
  histoirrBkg1->Draw();
  histoirrBkg2->SetLineColor(56);
  histoirrBkg2->Draw("same");
  histoirrBkg3->SetLineColor(60);
  histoirrBkg3->Draw("same");
  histoirrBkgTot->Draw("same");

  legendTot->Clear();
  sprintf(nev,"Zb\\bar{b}+0jets");
  legendTot->AddEntry(histoirrBkg1,nev,"l");
  sprintf(nev,"Zb\\bar{b}+1jets");
  legendTot->AddEntry(histoirrBkg2,nev,"l");
  sprintf(nev,"Zb\\bar{b}+2jets");
  legendTot->AddEntry(histoirrBkg3,nev,"l");
  sprintf(nev,"inclusive");
  legendTot->AddEntry(histoirrBkgTot,nev,"l");
  legendTot->Draw();

  canvas->Print("Zbb.jpg");
  canvasTot->Print("Zbbtot.jpg");
  canvasirrBkg->Print("ZbbIrr.jpg");
  canvasirrBkgTot->Print("ZbbIrrtot.jpg");

  TFile * outputFile = new TFile("diffXsecZbb.root","RECREATE");

  histo1->Write();
  histo2->Write();
  histo3->Write();
  histoTot->Write();
  histoirrBkg1->Write();
  histoirrBkg2->Write();
  histoirrBkg3->Write();
  histoirrBkgTot->Write();

  outputFile->Close();

}
//Function to build one template
// folder = 0,1,2 (final state corresponds to 4mu,4e,2mu2e respectively)
// erg_tev = 7,8 (CoM energy)
void produce_MJJdistributions_one(int folder, int erg_tev){
  gStyle->SetOptStat(0);

  char TREE_NAME[] = "SelectedTree";
	TString OUTPUT_NAME = "HtoZZ4l_Phantom_125p6_VHDistributions_GenLevel";
  TString comstring;
  comstring.Form("%iTeV", erg_tev);
  TString gencomstring;
  gencomstring.Form("%iT/", erg_tev);
  TString erg_dir;
	erg_dir.Form("LHC_%iTeV/", erg_tev);
  OUTPUT_NAME += ".root";

  TString sample_VBF_suffix[4] ={
    "BSI_VBF_Phantom",
    "Bkg_VBF_Phantom",
    "BSI10_VBF_Phantom",
    "BSI25_VBF_Phantom"
  };
  TString sample_VBF_gensuffix[4] ={
    "BSI",
    "Bkg",
    "BSI10",
    "BSI25"
  };

  double xsec_VBF_Phantom[2][3][4]={
    {
      { 2.053859553143833e-1, 1.611617374456183e-1, 2.187258636589030e-1, 2.505576749660674e-1 },
      { 2.050597663931831e-1, 1.610671663387286e-1, 2.178041943144518e-1, 2.502592444436491e-1 },
      { 4.512172284721055e-1, 3.718595894117134e-1, 4.512172284721055e-1, 5.417040330546889e-1 }
    },
    {
      { 2.487975936891337e-1, 1.951954743601816e-1, 2.678337815958082e-1, 3.117289755556746e-1 },
      { 2.484688144236787e-1, 1.952187837277965e-1, 2.680082365969152e-1, 3.117402751925978e-1 },
      { 5.434945696873235e-1, 4.447269876857436e-1, 5.814292186114383e-1, 6.707175001136875e-1 }
    }
  };

  TString cinput_common = "/scratch0/hep/ianderso/LHEFiles/VBF/Phantom/" + gencomstring;

	int EnergyIndex = 1;
	if (erg_tev == 7) EnergyIndex = 0;
	float lowside[3] = { 220, 230, 240 };
	double mPOLE = 125.6;
	float ZZMass_PeakCut[2] = { 125.1, 126.1 }; // Spin 0 analysis

	float templateWeight = 1;
  float GenDiJetMass;
  float MC_weight;
	float ZZMass = 0;

	double nVBFPeak[4] = { 0 };

	for (int lo = 0; lo < 1; lo++){
    TString coutput_common = user_TemplateswithTrees_dir + "../VHContributions/" + erg_dir;
		coutput_common += user_folder[folder] + "/";
		gSystem->Exec("mkdir -p " + coutput_common);

		cout << "===============================" << endl;
		cout << "CoM Energy: " << erg_tev << " TeV" << endl;
		cout << "Decay Channel: " << user_folder[folder] << endl;
		cout << endl;

		TString coutput = coutput_common + OUTPUT_NAME;
		TFile* foutput = new TFile(coutput, "recreate");

    foutput->cd();

		float ZZMass_cut[2] = { lowside[lo], 1600 };
		float ZZwidth = 20.0;
		const int nbinsx = (ZZMass_cut[1] - ZZMass_cut[0]) / ZZwidth;
		float kDXarray[nbinsx + 3];
    kDXarray[0] = ZZMass_PeakCut[0];
    kDXarray[1] = ZZMass_PeakCut[1];
		for (int bin = 2; bin < nbinsx + 3; bin++){
			kDXarray[bin] = ZZMass_cut[0] + ZZwidth*(bin-2);
		}
    float beginWMass = floor(MG_W_Phantom[0]-5.*MG_W_Phantom[1]); // = 70 GeV
    float endZMass = ceil(MG_Z_Phantom[0]+5.*MG_Z_Phantom[1]); // = 104 GeV
//    float WZthreshold = 0.5*(floor(MG_W_Phantom[0]+(MG_Z_Phantom[0]-MG_W_Phantom[0])*MG_W_Phantom[1]/(MG_W_Phantom[1]+MG_Z_Phantom[1]))+ceil(MG_W_Phantom[0]+(MG_Z_Phantom[0]-MG_W_Phantom[0])*MG_W_Phantom[1]/(MG_W_Phantom[1]+MG_Z_Phantom[1]))); // = 85.5 GeV
    float WZthreshold = ceil(MG_W_Phantom[0]+(MG_Z_Phantom[0]-MG_W_Phantom[0])*MG_W_Phantom[1]/(MG_W_Phantom[1]+MG_Z_Phantom[1])); // = 86 GeV
    float sidebandBeginMass = beginWMass-(endZMass-beginWMass)*0.5; // = 53 GeV
    float sidebandEndMass = endZMass+(endZMass-beginWMass)*0.5; // = 121 GeV
    float beginLowHHMass = min((float) 50., sidebandBeginMass);
    float beginHHMass = floor(mPOLE-0.5);
    float endHHMass = floor(mPOLE+0.5);
    float sidebandBeginHHMass = floor(beginHHMass - (endHHMass-beginHHMass)*0.5);
    float sidebandEndHHMass = ceil(endHHMass + (endHHMass-beginHHMass)*0.5);
    cout << "Mass thresholds: "
      << beginLowHHMass << '\t'
      << sidebandBeginMass << '\t'
      << beginWMass << '\t'
      << WZthreshold << '\t'
      << endZMass << '\t'
      << sidebandEndMass << '\t'
      << sidebandBeginHHMass << '\t'
      << beginHHMass << '\t'
      << endHHMass << '\t'
      << sidebandEndHHMass << '\t'
      << endl;

//    const int nbinsy = 260;
    const int nbinsy = 130;
    //    const int nbinsy = 261;
    float kDYarray[nbinsy + 2];
    float kDY_bounds[2] ={ 0, 130 };
 //   float kDY_bounds[2] ={ 0, 130.5 };
    for (int bin = 0; bin < nbinsy + 2; bin++){
			double binwidth = (kDY_bounds[1] - kDY_bounds[0]) / nbinsy;
			kDYarray[bin] = kDY_bounds[0] + binwidth*bin;
		}

		const int kNumTemplates = 3;
		double overall_scale[kNumTemplates] = { 1 };
    TString templatetitles[kNumTemplates+1] ={ "VBF Sig", "VBF Bkg", "VBF Int", "VBF extra" };
    TString templatenames[kNumTemplates+1] ={ "VBF_Sig", "VBF_Bkg", "VBF_Int", "VBF_extra" };
    // Build template structure, including anomalous couplings

		int nEntries;
		MC_weight = 1;
		ZZMass = 0;

		//Initialize and grab each of the four Phantom trees
    TChain* tree_VBF[4];
    TH2F* h2DVBF[4];
    TH1F* hVBF_onshell[4];
    TH1F* hVBF_offshell[4];
    TH1F* hVBF_onshell_LC[4];
    TH1F* hVBF_offshell_LC[4];
    TH1F* hVBF_onshell_scaled[4];
    TH1F* hVBF_offshell_scaled[4];
    TH1F* hVBF_onshell_scaled_wVBF[4];
    TH1F* hVBF_offshell_scaled_wVBF[4];

    for (int tr = 0; tr < 4; tr++){
      /*
      0: BSI
      1: BKG
      2: BSI10
      3: BSI25
      */
      tree_VBF[tr] = new TChain(TREE_NAME);
      for (int decay = 0; decay < 3; decay++){
        if (decay!=folder) continue;
        TString channelname = user_folder[decay];
        if (decay == 2) channelname = "2e2mu";

        TString cinput_VBF = cinput_common + sample_VBF_gensuffix[tr] + "/" + channelname + "/phantom_" + comstring + "_" + channelname + "_" + sample_VBF_gensuffix[tr] + "_false.root";
				tree_VBF[tr]->Add(cinput_VBF);
			}

      tree_VBF[tr]->SetBranchAddress("DiJetMass", &GenDiJetMass);
      tree_VBF[tr]->SetBranchAddress("ZZMass", &ZZMass);


      foutput->cd();
      TString templatename_2D_core;
      TString templatename_2D;

      templatename_2D_core = "VBF_";
      templatename_2D_core += templatenames[tr];

      templatename_2D = templatename_2D_core;
      h2DVBF[tr] = new TH2F(templatename_2D, templatetitles[tr], nbinsx+2, kDXarray, nbinsy+1, kDYarray);
      hVBF_onshell[tr] = new TH1F(Form("%s_onshell_raw", h2DVBF[tr]->GetName()), templatetitles[tr], nbinsy+1, kDYarray);
      hVBF_offshell[tr] = new TH1F(Form("%s_offshell_raw", h2DVBF[tr]->GetName()), templatetitles[tr], nbinsy+1, kDYarray);
      hVBF_onshell_LC[tr] = new TH1F(Form("%s_onshell_LC", h2DVBF[tr]->GetName()), templatetitles[tr], nbinsy+1, kDYarray);
      hVBF_offshell_LC[tr] = new TH1F(Form("%s_offshell_LC", h2DVBF[tr]->GetName()), templatetitles[tr], nbinsy+1, kDYarray);
      hVBF_onshell_scaled[tr] = new TH1F(Form("%s_onshell_scaled", h2DVBF[tr]->GetName()), templatetitles[tr], nbinsy+1, kDYarray);
      hVBF_offshell_scaled[tr] = new TH1F(Form("%s_offshell_scaled", h2DVBF[tr]->GetName()), templatetitles[tr], nbinsy+1, kDYarray);
      hVBF_onshell_scaled_wVBF[tr] = new TH1F(Form("%s_onshell_scaled_wVBF", h2DVBF[tr]->GetName()), templatetitles[tr], nbinsy+1, kDYarray);
      hVBF_offshell_scaled_wVBF[tr] = new TH1F(Form("%s_offshell_scaled_wVBF", h2DVBF[tr]->GetName()), templatetitles[tr], nbinsy+1, kDYarray);

      int nVBFEntries = tree_VBF[tr]->GetEntries();
      double sumFilled=0;
      MC_weight = xsec_VBF_Phantom[EnergyIndex][folder][tr];
      for (int ev = 0; ev < nVBFEntries; ev++){
        progressbar(ev, tree_VBF[tr]->GetEntries());
        tree_VBF[tr]->GetEntry(ev);

        if (ZZMass>=kDXarray[nbinsx + 2] || ZZMass<kDXarray[0]) continue;
        if (GenDiJetMass>=kDYarray[nbinsy]) GenDiJetMass = (kDYarray[nbinsy]+kDYarray[nbinsy+1])/2.;

        double weight = MC_weight / nVBFEntries;

        // Anomalous couplings loop
        double fillWeight = weight;
        h2DVBF[tr]->Fill(ZZMass, GenDiJetMass, fillWeight);
        sumFilled += fillWeight;
      }
      cout << endl;
      cout << "Filled " << sumFilled*luminosity[EnergyIndex] << endl;

      h2DVBF[tr]->Scale(luminosity[EnergyIndex]);

      foutput->cd();
      for (int biny=1; biny<=h2DVBF[tr]->GetNbinsY(); biny++){
        double sumOffshell=h2DVBF[tr]->Integral(3, nbinsx + 2, biny, biny);
        double sumOnshell=h2DVBF[tr]->Integral(1, 1, biny, biny);
        hVBF_onshell[tr]->SetBinContent(biny, sumOnshell);
        hVBF_offshell[tr]->SetBinContent(biny, sumOffshell);
        hVBF_onshell_LC[tr]->SetBinContent(biny, sumOnshell);
        hVBF_offshell_LC[tr]->SetBinContent(biny, sumOffshell);
        hVBF_onshell_scaled[tr]->SetBinContent(biny, sumOnshell);
        hVBF_offshell_scaled[tr]->SetBinContent(biny, sumOffshell);
        hVBF_onshell_scaled_wVBF[tr]->SetBinContent(biny, sumOnshell);
        hVBF_offshell_scaled_wVBF[tr]->SetBinContent(biny, sumOffshell);
      }
      cout << "On-shell integral: " << hVBF_onshell[tr]->Integral() << endl;
      cout << "Off-shell integral: " << hVBF_offshell[tr]->Integral() << endl;

      delete tree_VBF[tr];
    }

		//Make VBF Sig/Int from linear combinations of above templates
		//0: VBF Sig
		//2: VBF Int
		//	 For 7 TeV samples, BSI25, Bkg, and BSI10 are used
		//	 For 8 TeV samples, BSI, Bkg, and BSI10 are used
		if (EnergyIndex == 0){
      oneDlinearcombination(hVBF_offshell_LC[2], kBSI10Hist, hVBF_offshell_LC[1], kBkgHist, hVBF_offshell_LC[3], kBSI25Hist, hVBF_offshell_LC[0], kSigHist, hVBF_offshell_LC[2], kIntHist);

      for (int binx=1; binx<=hVBF_onshell_LC[0]->GetNbinsX(); binx++){
        for (int tr = 0; tr < 4; tr++) nVBFPeak[tr] = hVBF_onshell_LC[tr]->GetBinContent(binx);
        double nVBFsigtemp = doPeakCombination(nVBFPeak[2], 10, nVBFPeak[3], 25, nVBFPeak[1], kSigHist);
        double nVBFinterftemp = doPeakCombination(nVBFPeak[2], 10, nVBFPeak[3], 25, nVBFPeak[1], kIntHist);
        nVBFPeak[0] = nVBFsigtemp;
        nVBFPeak[2] = nVBFinterftemp;
        for (int tr = 0; tr < 4; tr++) hVBF_onshell_LC[tr]->SetBinContent(binx, nVBFPeak[tr]);
      }
    }
		else if (EnergyIndex == 1){
      oneDlinearcombination(hVBF_offshell_LC[0], kBSIHist, hVBF_offshell_LC[1], kBkgHist, hVBF_offshell_LC[2], kBSI10Hist, hVBF_offshell_LC[0], kSigHist, hVBF_offshell_LC[2], kIntHist);

      for (int binx=1; binx<=hVBF_onshell_LC[0]->GetNbinsX(); binx++){
        for (int tr = 0; tr < 4; tr++) nVBFPeak[tr] = hVBF_onshell_LC[tr]->GetBinContent(binx);
        double nVBFsigtemp = doPeakCombination(nVBFPeak[2], 10, nVBFPeak[0], 1, nVBFPeak[1], kSigHist);
        double nVBFinterftemp = doPeakCombination(nVBFPeak[2], 10, nVBFPeak[0], 1, nVBFPeak[1], kIntHist);
        nVBFPeak[0] = nVBFsigtemp;
        nVBFPeak[2] = nVBFinterftemp;
        for (int tr = 0; tr < 4; tr++) hVBF_onshell_LC[tr]->SetBinContent(binx, nVBFPeak[tr]);
      }
    }
    cout << "Finished peak combination" << endl;
    int beginSB = hVBF_onshell_LC[0]->GetXaxis()->FindBin(sidebandBeginMass);
    int beginW = hVBF_onshell_LC[0]->GetXaxis()->FindBin(beginWMass);
    int binWZthreshold = hVBF_onshell_LC[0]->GetXaxis()->FindBin(WZthreshold);
    int endZ = hVBF_onshell_LC[0]->GetXaxis()->FindBin(endZMass);
    int endSB = hVBF_onshell_LC[0]->GetXaxis()->FindBin(sidebandEndMass);
    int beginLowHH = hVBF_onshell_LC[0]->GetXaxis()->FindBin(beginLowHHMass);
    int beginHH = hVBF_onshell_LC[0]->GetXaxis()->FindBin(beginHHMass);
    int endHH = hVBF_onshell_LC[0]->GetXaxis()->FindBin(endHHMass);
    int sidebandBeginHH = hVBF_onshell_LC[0]->GetXaxis()->FindBin(sidebandBeginHHMass);
    int sidebandEndHH = hVBF_onshell_LC[0]->GetXaxis()->FindBin(sidebandEndHHMass);

    double simulatedSB = hVBF_onshell_LC[0]->Integral(beginSB, beginW-1) + hVBF_onshell_LC[0]->Integral(endZ, endSB-1);
    cout << "Total signal SB before scaling: " << simulatedSB << endl;
    double simulatedW = hVBF_onshell_LC[0]->Integral(beginW, binWZthreshold-1);
    double simulatedZ = hVBF_onshell_LC[0]->Integral(binWZthreshold,endZ-1);
    double simulatedWbkg = simulatedSB*(WZthreshold-beginWMass)/(endZMass-beginWMass);
    double simulatedZbkg = simulatedSB*(endZMass-WZthreshold)/(endZMass-beginWMass);
    cout << "W Total / Bkg: " << simulatedW << " / " << simulatedWbkg << endl;
    cout << "Z Total / Bkg: " << simulatedZ << " / " << simulatedZbkg << endl;

    double brval = BR_Table[1][2];
    if (folder==2) brval = BR_Table[1][3];
    brval *= 1000.;
    double ratioW = (XSEC_Table_WH[EnergyIndex][1]*brval*luminosity[EnergyIndex]) / (simulatedW-simulatedWbkg);
    double ratioZ = (XSEC_Table_ZH[EnergyIndex][1]*brval*luminosity[EnergyIndex]) / (simulatedZ-simulatedZbkg);
    double scale_SB_VBF = (simulatedW + simulatedZ)/(ratioW*simulatedW + ratioZ*simulatedZ);
    double scale_SB_HH = 1.5;
    double nVBF_Sig_Simulated = 0;
    cout << "VBF SB scale: " << scale_SB_VBF << endl;
    cout << "WH scale: " << ratioW << endl;
    cout << "ZH scale: " << ratioZ << endl;

    for (int tr = 0; tr < 4; tr++){
      for (int binx=1; binx<=hVBF_onshell_LC[tr]->GetNbinsX(); binx++){
        double bincontent = hVBF_onshell_LC[tr]->GetBinContent(binx);
        if (binx < endZ && binx >= binWZthreshold) bincontent *= ratioZ;
        else if (binx < binWZthreshold && binx >= beginW) bincontent *= ratioW;
        else{
          if ((binx < endSB && binx >= endZ) || (binx < beginW && binx >= beginSB)) bincontent *= scale_SB_VBF;
          if (tr==0){
            double bincount = bincontent;
            if (binx<beginLowHH || (binx>=beginHH && binx<endHH)) bincount=0;
            if ((binx<beginHH && binx>=sidebandBeginHH) || (binx<sidebandEndHH && binx>=endHH)) bincount*=scale_SB_HH;
            nVBF_Sig_Simulated += bincount;
          }
        }
        hVBF_onshell_scaled[tr]->SetBinContent(binx, bincontent);
      }
      for (int binx=1; binx<=hVBF_offshell_LC[tr]->GetNbinsX(); binx++){
        double bincontent = hVBF_offshell_LC[tr]->GetBinContent(binx);
        if ((binx < endSB && binx >= endZ) || (binx < beginW && binx >= beginSB)) bincontent *= scale_SB_VBF;
        if (binx < endZ && binx >= binWZthreshold) bincontent *= ratioZ;
        if (binx < binWZthreshold && binx >= beginW) bincontent *= ratioW;
        hVBF_offshell_scaled[tr]->SetBinContent(binx, bincontent);
      }
    }
    double vbfscale = (XSEC_Table_VBF[EnergyIndex][1]*brval*luminosity[EnergyIndex]) / nVBF_Sig_Simulated;
    cout << "VBF scale: " << vbfscale << endl;

    for (int tr = 0; tr < 4; tr++){
      for (int binx=1; binx<=hVBF_onshell_scaled[tr]->GetNbinsX(); binx++){
        double bincontent = hVBF_onshell_scaled[tr]->GetBinContent(binx);
        if (!(binx < endZ && binx >= binWZthreshold) && !(binx < binWZthreshold && binx >= beginW)) bincontent *= vbfscale;
        if (binx<beginLowHH || (binx>=beginHH && binx<endHH)) bincontent=0;
        if ((binx<beginHH && binx>=sidebandBeginHH) || (binx<sidebandEndHH && binx>=endHH)) bincontent*=scale_SB_HH;
        hVBF_onshell_scaled_wVBF[tr]->SetBinContent(binx, bincontent);
      }
      for (int binx=1; binx<=hVBF_offshell_scaled[tr]->GetNbinsX(); binx++){
        double bincontent = hVBF_offshell_scaled[tr]->GetBinContent(binx);
        if (!(binx < endZ && binx >= binWZthreshold) && !(binx < binWZthreshold && binx >= beginW)) bincontent *= vbfscale;
        if (binx<beginLowHH || (binx>=beginHH && binx<endHH)) bincontent=0;
        if ((binx<beginHH && binx>=sidebandBeginHH) || (binx<sidebandEndHH && binx>=endHH)) bincontent*=scale_SB_HH;
        hVBF_offshell_scaled_wVBF[tr]->SetBinContent(binx, bincontent);
      }
      cout << "Initial yield for " << templatetitles[tr] << ": " << hVBF_offshell_LC[tr]->Integral() << endl;
      cout << "Intermediate yield for " << templatetitles[tr] << " without VBF re-scaling: " << hVBF_offshell_scaled[tr]->Integral() << endl;
      cout << "Final yield for " << templatetitles[tr] << ": " << hVBF_offshell_scaled_wVBF[tr]->Integral() << endl;
      cout << endl;
    }

    TH1F* hRatio = (TH1F*)hVBF_offshell_scaled_wVBF[0]->Clone("Phantom_VBFVH_ScalingRatio");
    hRatio->Divide(hVBF_offshell_LC[0]);
    for (int binx=1; binx<=hRatio->GetNbinsX(); binx++){
      double bincontent = hRatio->GetBinContent(binx);
      if (bincontent<=0 && !(binx<beginLowHH || (binx>=beginHH && binx<endHH))) cout << "Bin " << binx << " is unexpectedly non-positive!" << endl;
    }
    foutput->WriteTObject(hRatio);
    delete hRatio;

    for (int tr = 0; tr < 4; tr++){
      foutput->WriteTObject(h2DVBF[tr]);
      foutput->WriteTObject(hVBF_onshell[tr]);
      foutput->WriteTObject(hVBF_offshell[tr]);
      foutput->WriteTObject(hVBF_onshell_LC[tr]);
      foutput->WriteTObject(hVBF_offshell_LC[tr]);
      foutput->WriteTObject(hVBF_onshell_scaled[tr]);
      foutput->WriteTObject(hVBF_offshell_scaled[tr]);
      foutput->WriteTObject(hVBF_onshell_scaled_wVBF[tr]);
      foutput->WriteTObject(hVBF_offshell_scaled_wVBF[tr]);

      delete h2DVBF[tr];
      delete hVBF_onshell[tr];
      delete hVBF_offshell[tr];
      delete hVBF_onshell_LC[tr];
      delete hVBF_offshell_LC[tr];
      delete hVBF_onshell_scaled[tr];
      delete hVBF_offshell_scaled[tr];
      delete hVBF_onshell_scaled_wVBF[tr];
      delete hVBF_offshell_scaled_wVBF[tr];
    }
    
    foutput->Close();
	}
}
Exemplo n.º 8
0
//---------------------------------------------------------------
double *unbinnedFit(TString fiName, vector<double> xlim, double mtop, TLatex *channel_tex, TString outdir, double lumi)
//---------------------------------------------------------------
{
  using namespace RooFit;
  // reduce RooFit's verbosity on the INFO level
  RooMsgService::instance().getStream(1).removeTopic(Minimization);
  RooMsgService::instance().getStream(1).removeTopic(Plotting);
  RooMsgService::instance().getStream(1).removeTopic(ObjectHandling);
  RooMsgService::instance().getStream(1).removeTopic(Eval);
  RooMsgService::instance().getStream(1).removeTopic(Fitting);
  RooMsgService::instance().setSilentMode(true);
  RooMsgService::instance().setGlobalKillBelow(RooFit::FATAL);

  TFile *res = TFile::Open(fiName);

  RooRealVar mtl("mass", "M_{J/#psi+l}", 0., 250., "GeV");
  RooRealVar weight("weight", "weight", 0., 2.);
  //RooRealVar mean("mean", "mass", (xlim[1]+xlim[0])/2., (xlim[1]+3.*xlim[0])/4., (3.*xlim[1]+xlim[0])/4.);
  RooRealVar mean("mean", "mass", 70., 60., 80.);
  RooRealVar width("width", "width", 25., 15., 40.);

  TTree *tree = (TTree*)res->Get("MTriLept");
  RooDataSet *dataset = new RooDataSet("dataset", "dataset", RooArgSet(mtl, weight), Import(*tree), WeightVar(weight));
  RooGaussian pdf("gaus", "gaus", mtl, mean, width);
  pdf.fitTo(*dataset, Range(xlim[0], xlim[1]), SumW2Error(kTRUE), PrintLevel(-1), PrintEvalErrors(-1));

  TCanvas *cn = new TCanvas("cn", "cn", 800, 800);
  cn->cd();
  RooPlot *massframe = mtl.frame();
  if (mtop < 1e-6)
    dataset->plotOn(massframe, Binning(25), DataError(RooAbsData::SumW2));
  else
    dataset->plotOn(massframe, Binning(50), DataError(RooAbsData::SumW2));
  pdf.plotOn(massframe, Range(xlim[0], xlim[1]));
  massframe->Draw();
  TLegend *leg = new TLegend(0.58,0.82,0.93,0.92,NULL,"brNDC");
  if (mtop < 1e-6)
    leg->SetHeader(TString::Format("#tilde{M}_{J/#psi+l} = (%3.1f #pm %3.1f) GeV", mean.getVal(), mean.getError()));
  else
    leg->SetHeader(TString::Format("#splitline{M_{t}^{gen} = %3.1f GeV}{#tilde{M}_{J/#psi+l} = (%3.1f #pm %3.1f) GeV}", mtop+0.5, mean.getVal(), mean.getError()));
  leg_myStyle(leg);
  leg->Draw("same");
  channel_tex->Draw("same");
  if (mtop < 1e-6)
    cms_myStyle(lumi, true);
  else
    cms_myStyle(lumi, false);
  TString outFile = outdir;
  if (mtop < 1e-6)
    outFile += "GausianUnbinnedFit_Data";
  else
    outFile += TString::Format("GaussianUnbinnedFit_%d_5", (int)mtop);
  cn->SaveAs(outFile+".pdf");
  cn->SaveAs(outFile+".C");
  cn->SaveAs(outFile+".jpg");
  cn->SaveAs(outFile+".eps");

  res->Close();

  double *mean_err = new double[2];
  mean_err[0] = mean.getVal();
  mean_err[1] = mean.getError();

  return mean_err;
}
Exemplo n.º 9
0
int main(int argc, char** argv)
{
  gStyle->SetOptStat(0);
  TString filename = argv[1];
  TFile * file = new TFile(filename, "READ");
  TTree *tree = (TTree *)file->Get("adc");
  
  Float_t floodx[2],floody[2],ratio[2];
  int trigger[2];
  bool bad;
  Short_t charge[32];
  
  tree->SetBranchAddress("TriggerChannel_0",&trigger[0]);
  tree->SetBranchAddress("FloodX_0",&floodx[0]);
  tree->SetBranchAddress("FloodY_0",&floody[0]);
  tree->SetBranchAddress("RatioTriggerOnAll_0",&ratio[0]);
  tree->SetBranchAddress("TriggerChannel_1",&trigger[1]);
  tree->SetBranchAddress("FloodX_1",&floodx[1]);
  tree->SetBranchAddress("FloodY_1",&floody[1]);
  tree->SetBranchAddress("RatioTriggerOnAll_1",&ratio[1]);
  tree->SetBranchAddress("BadEvent",&bad);
  
  std::stringstream sname,stype;
  std::string name,type;
   
  for(int i=0; i<32; i++)
  {
    sname.str(std::string());
    stype.str(std::string());
    sname << "ch" << i;
    name = sname.str();
    tree->SetBranchAddress(name.c_str(), &charge[i]);
  }
  
  //TCuts
  TCut Crystals[32]=
  {
    "TriggerChannel_0 == 0"                                                                                                                                                                                                                                                                                                                                                                ,
    "TriggerChannel_0 == 1 && (( TMath::Power(FloodX_0 - -3.668,2) / TMath::Power(0.412041,2))  + ( TMath::Power(FloodY_0 - 1.036,2) / TMath::Power(0.412041,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 3786.52 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 4915.66"                       ,
    "TriggerChannel_0 == 2 && (( TMath::Power(FloodX_0 - -3.724,2) / TMath::Power(0.385788,2))  + ( TMath::Power(FloodY_0 - -1.708,2) / TMath::Power(0.385788,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 3867.03 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 4956.38"                      ,
    "TriggerChannel_0 == 3 && (( TMath::Power(FloodX_0 - -3.612,2) / TMath::Power(0.438224,2))  + ( TMath::Power(FloodY_0 - -3.892,2) / TMath::Power(0.438224,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 3086.97 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 4119.18"                      ,
    "TriggerChannel_0 == 4 && (( TMath::Power(FloodX_0 - -0.98,2) / TMath::Power(0.395637,2))  + ( TMath::Power(FloodY_0 - 3.892,2) / TMath::Power(0.395637,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 3629.98 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 4637.16"                        ,
    "TriggerChannel_0 == 5 && (( TMath::Power(FloodX_0 - -1.148,2) / TMath::Power(0.326781,2))  + ( TMath::Power(FloodY_0 - 1.092,2) / TMath::Power(0.326781,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 4321.57 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 5574.69"                       ,
    "TriggerChannel_0 == 6 && (( TMath::Power(FloodX_0 - -1.204,2) / TMath::Power(0.318083,2))  + ( TMath::Power(FloodY_0 - -1.54,2) / TMath::Power(0.318083,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 4228.77 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 5387.56"                       ,
    "TriggerChannel_0 == 7 && (( TMath::Power(FloodX_0 - -1.316,2) / TMath::Power(0.38977,2))  + ( TMath::Power(FloodY_0 - -4.228,2) / TMath::Power(0.38977,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 3736.52 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 4746.55"                        ,
    "TriggerChannel_0 == 8 && (( TMath::Power(FloodX_0 - 1.596,2) / TMath::Power(0.379766,2))  + ( TMath::Power(FloodY_0 - 3.948,2) / TMath::Power(0.379766,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 3797.15 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 4955.01"                        ,
    "TriggerChannel_0 == 9 && (( TMath::Power(FloodX_0 - 1.428,2) / TMath::Power(0.339249,2))  + ( TMath::Power(FloodY_0 - 1.148,2) / TMath::Power(0.339249,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 3851.75 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 4933.12"                        ,
    "TriggerChannel_0 == 10 && (( TMath::Power(FloodX_0 - 1.26,2) / TMath::Power(0.31409,2))  + ( TMath::Power(FloodY_0 - -1.54,2) / TMath::Power(0.31409,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 4343.24 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 5622.86"                          ,
    "TriggerChannel_0 == 11 && (( TMath::Power(FloodX_0 - 1.54,2) / TMath::Power(0.439377,2))  + ( TMath::Power(FloodY_0 - -4.172,2) / TMath::Power(0.439377,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 3041.24 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 3901.02"                       ,
    "TriggerChannel_0 == 12 && (( TMath::Power(FloodX_0 - 4.004,2) / TMath::Power(0.327012,2))  + ( TMath::Power(FloodY_0 - 4.172,2) / TMath::Power(0.327012,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 3441.52 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 4418.59"                       ,
    "TriggerChannel_0 == 13 && (( TMath::Power(FloodX_0 - 3.724,2) / TMath::Power(0.389074,2))  + ( TMath::Power(FloodY_0 - 1.036,2) / TMath::Power(0.389074,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 3629.07 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 4667.87"                       ,
    "TriggerChannel_0 == 14 && (( TMath::Power(FloodX_0 - 3.78,2) / TMath::Power(0.368637,2))  + ( TMath::Power(FloodY_0 - -1.484,2) / TMath::Power(0.368637,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 4076.73 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 5264.54"                       ,
    "TriggerChannel_0 == 15 && (( TMath::Power(FloodX_0 - 3.556,2) / TMath::Power(0.468446,2))  + ( TMath::Power(FloodY_0 - -3.948,2) / TMath::Power(0.468446,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 2822.28 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 3681.71"                      ,
    "TriggerChannel_1 == 16 && (( TMath::Power(FloodX_1 - -3.724,2) / TMath::Power(0.443754,2))  + ( TMath::Power(FloodY_1 - 3.892,2) / TMath::Power(0.443754,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > 3132.72 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 4266.53"  ,
    "TriggerChannel_1 == 17 && (( TMath::Power(FloodX_1 - -3.724,2) / TMath::Power(0.439618,2))  + ( TMath::Power(FloodY_1 - 1.316,2) / TMath::Power(0.439618,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > 3002.34 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 4135.14"  ,
    "TriggerChannel_1 == 18 && (( TMath::Power(FloodX_1 - -3.668,2) / TMath::Power(0.406535,2))  + ( TMath::Power(FloodY_1 - -1.26,2) / TMath::Power(0.406535,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > 3366.09 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 4747.98"  ,
    "TriggerChannel_1 == 19 && (( TMath::Power(FloodX_1 - -3.836,2) / TMath::Power(0.454168,2))  + ( TMath::Power(FloodY_1 - -3.948,2) / TMath::Power(0.454168,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > 3169.97 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 4260.33" ,
    "TriggerChannel_1 == 20 && (( TMath::Power(FloodX_1 - -1.26,2) / TMath::Power(0.435707,2))  + ( TMath::Power(FloodY_1 - 4.06,2) / TMath::Power(0.435707,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > 3115.91 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 4299.74"    ,
    "TriggerChannel_1 == 21 && (( TMath::Power(FloodX_1 - -1.54,2) / TMath::Power(0.375443,2))  + ( TMath::Power(FloodY_1 - 1.428,2) / TMath::Power(0.375443,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > 3354 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 4641.48"      ,
    "TriggerChannel_1 == 22 && (( TMath::Power(FloodX_1 - -1.372,2) / TMath::Power(0.368213,2))  + ( TMath::Power(FloodY_1 - -1.26,2) / TMath::Power(0.368213,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > 3160.73 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 4253.92"  ,
    "TriggerChannel_1 == 23 && (( TMath::Power(FloodX_1 - -1.428,2) / TMath::Power(0.457071,2))  + ( TMath::Power(FloodY_1 - -4.284,2) / TMath::Power(0.457071,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > 3125.02 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 4301.74" ,
    "TriggerChannel_1 == 24 && (( TMath::Power(FloodX_1 - 1.316,2) / TMath::Power(0.437403,2))  + ( TMath::Power(FloodY_1 - 4.172,2) / TMath::Power(0.437403,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > 2662.73 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 3593.6"    ,
    "TriggerChannel_1 == 25"                                                                                                                                                                                                                                                                                                                                                                ,
    "TriggerChannel_1 == 26 && (( TMath::Power(FloodX_1 - 1.204,2) / TMath::Power(0.379761,2))  + ( TMath::Power(FloodY_1 - -1.428,2) / TMath::Power(0.379761,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > -510629 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 48433.2"  ,
    "TriggerChannel_1 == 27 && (( TMath::Power(FloodX_1 - 1.372,2) / TMath::Power(0.447345,2))  + ( TMath::Power(FloodY_1 - -4.284,2) / TMath::Power(0.447345,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > 3241.13 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 4519.65"  ,
    "TriggerChannel_1 == 28 && (( TMath::Power(FloodX_1 - 4.228,2) / TMath::Power(0.197975,2))  + ( TMath::Power(FloodY_1 - 4.172,2) / TMath::Power(0.197975,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > 2950.12 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 3987.89"   ,
    "TriggerChannel_1 == 29 && (( TMath::Power(FloodX_1 - 3.836,2) / TMath::Power(0.444737,2))  + ( TMath::Power(FloodY_1 - 1.316,2) / TMath::Power(0.444737,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > 3334.08 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 4473.93"   ,
    "TriggerChannel_1 == 30 && (( TMath::Power(FloodX_1 - 3.668,2) / TMath::Power(0.435218,2))  + ( TMath::Power(FloodY_1 - -1.316,2) / TMath::Power(0.435218,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > 3244.59 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 4411.88"  ,
    "TriggerChannel_1 == 31 && (( TMath::Power(FloodX_1 - 3.668,2) / TMath::Power(0.478436,2))  + ( TMath::Power(FloodY_1 - -4.172,2) / TMath::Power(0.478436,2))) < 1 && (ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) > 2831.63 &&(ch16+ch17+ch18+ch19+ch20+ch21+ch22+ch23+ch24+ch25+ch26+ch27+ch28+ch29+ch30+ch31) < 3839.56"
  };
  
  
  
  double xPos[32] = 
  {
    0,
    -3.668,
-3.724,
-3.612,
-0.98 ,
-1.148,
-1.204,
-1.316,
1.596 ,
1.428 ,
1.26  ,
3.836, 
4.004, 
3.724, 
3.78, 
3.556 ,
     -3.724,
 -3.724,
 -3.668,
 -3.836,
 -1.26, 
 -1.54, 
 -1.372,
 -1.428,
 1.316,
 0,
 1.204, 
 1.372, 
 3.892, 
 3.836, 
 3.668, 
 3.668
  };
  double yPos[32] =
  {
    0,
    1.036, 
-1.708,
-3.892,
3.892, 
1.092, 
-1.54, 
-4.228,
3.948, 
1.148, 
-1.54, 
3.724, 
4.172, 
1.036, 
-1.484,
-3.948,
 3.892 ,
 1.316 ,
 -1.26 ,
 -3.948,
 4.06  ,
 1.428 ,
 -1.26 ,
 -4.284,
 4.172 ,
 0,
 -1.428,
 -4.284,
 4.06  ,
 1.316 ,
 -1.316,
 -4.172
  };
  
  double xSigma[32]
  {
    0,
    0.412041,
0.385788,
0.438224,
0.395637,
0.326781,
0.318083,
0.38977 ,
0.379766,
0.339249,
0.31409 ,
0.151452,
0.327012,
0.389074,
0.368637,
0.468446,
0.443754,
0.439618,
0.406535,
0.454168,
0.435707,
0.375443,
0.368213,
0.457071,
0.437403,
0,
0.379761,
0.447345,
0.1562,  
0.444737,
0.435218,
0.478436
  };
  
  double ySigma[32]
  {
   0,
    0.412041,
0.385788,
0.438224,
0.395637,
0.326781,
0.318083,
0.38977 ,
0.379766,
0.339249,
0.31409 ,
0.151452,
0.327012,
0.389074,
0.368637,
0.468446,
 0.443754,
0.439618,
0.406535,
0.454168,
0.435707,
0.375443,
0.368213,
0.457071,
0.437403,
0.379761,
0.447345,
0,
0.1562,  
0.444737,
0.435218,
0.478436
  };
  
  
  double eMin[32] =
  {
    0         ,
    3786.52   ,
3867.03       ,
3086.97       ,
3629.98       ,
4321.57       ,
4228.77       ,
3736.52       ,
3797.15       ,
3851.75       ,
4343.24       ,
3663.34       ,
3441.52       ,
3629.07       ,
4076.73       ,
2822.28       ,
3132.72       ,
3002.34       ,
3366.09       ,
3169.97       ,
3115.91       ,
3354          ,
3160.73       ,
3125.02       ,
2662.73       ,
-510629       ,
3241.13       ,
3128.64       ,
3334.08       ,
3244.59       ,
2831.63
    
  };
  
  double eMax[32] =
  {
    0        ,
    4915.66  ,
4956.38      ,
4119.18      ,
4637.16      ,
5574.69      ,
5387.56      ,
4746.55      ,
4955.01      ,
4933.12      ,
5622.86      ,
4609.81      ,
4418.59      ,
4667.87      ,
5264.54      ,
3681.71      ,
4266.53      ,
4135.14      ,
4747.98      ,
4260.33      ,
4299.74      ,
4641.48      ,
4253.92      ,
4301.74      ,
3593.6       ,
48433.2      ,
4519.65      ,
4021.49      ,
4473.93      ,
4411.88      ,
3839.56
  };
  
  
  //increase the limits in TFormula, because the cut string is way too long for the defaults 
  //TFormula::SetMaxima(100000,1000,1000000);
  //create the formula from the cuts
//   TTreeFormula* Formula = new TTreeFormula("Formula",MegaString.c_str(),t1);
  
  //mapping for the new boards
  Double_t xmppc[32]={-4.8,-4.8,-4.8,-4.8,-1.6,-1.6,-1.6,-1.6,1.6,1.6,1.6,1.6,4.8,4.8,4.8,4.8,-4.8,-4.8,-4.8,-4.8,-1.6,-1.6,-1.6,-1.6,1.6,1.6,1.6,1.6,4.8,4.8,4.8,4.8};
  Double_t ymppc[32]={4.8,1.6,-1.6,-4.8,4.8,1.6,-1.6,-4.8,4.8,1.6,-1.6,-4.8,4.8,1.6,-1.6,-4.8,4.8,1.6,-1.6,-4.8,4.8,1.6,-1.6,-4.8,4.8,1.6,-1.6,-4.8,4.8,1.6,-1.6,-4.8};
  
  
  TH2F *histo2= new TH2F("ciao2","",4,-6.2,6.2,4,-6.2,6.2);
  Long64_t counter = 0;
  //loop on entries
  Long64_t nentries = tree->GetEntriesFast();   //nentries num eventi
  for (Long64_t jentry=0; jentry<nentries;jentry++)
  {
    tree->GetEntry(jentry);
    
    bool chBoard0 = false;
    bool chBoard1 = false;
    float z0= -3.9;    
    float z1= 3.9;
    float w = z0 - z1;
    float s = (0 - z0)/w;
    float x0,x1,y0,y1;
    
    //calculate sum charge
    
    float sumCharge0 = 0;
    float sumCharge1 = 0;
    
    for(int i = 0 ; i < 16 ; i++)
    {
      sumCharge0 += charge[i];
    }
    for(int i = 16 ; i < 32 ; i++)
    {
      sumCharge1 += charge[i];
    }
    
    
    for(int i = 0 ; i < 32 ; i++)
    {
      //TriggerChannel_0 == 1 &&  (( TMath::Power(FloodX_0 - -3.668,2) / TMath::Power(0.412041,2))  + ( TMath::Power(FloodY_0 - 1.036 ,2 ) / TMath::Power(0.412041,2))) < 1 && (ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) > 3786.52 &&(ch0+ch1+ch2+ch3+ch4+ch5+ch6+ch7+ch8+ch9+ch10+ch11+ch12+ch13+ch14+ch15) < 4915.66
      if(i < 16) //on board0
      {
	if( (((TMath::Power(floodx[0] - xPos[i],2)/ TMath::Power(xSigma[i],2))  + ( TMath::Power(floody[0] - yPos[i] ,2 ) / TMath::Power(ySigma[i],2))) < 1 )    &&    sumCharge0 > eMin[i] && sumCharge0 < eMax[i]              )
	{
	  if(chBoard0 == true) // 2 511 in the same matrix, get rid of the event
	  {
	    continue;
	  }
	  else
	  {
	    chBoard0 = true;
	    x0 = xmppc[i];
	    y0 = ymppc[i];
	  }
	}
      }
      else //it was on board1
      {
	if( (((TMath::Power(floodx[1] - xPos[i],2)/ TMath::Power(xSigma[i],2))  + ( TMath::Power(floody[1] - yPos[i] ,2 ) / TMath::Power(ySigma[i],2))) < 1 )    &&    sumCharge1 > eMin[i] && sumCharge1 < eMax[i]              )
	{
	  if(chBoard1 == true) // 2 511 in the same matrix, get rid of the event
	  {    
	    continue; 
	  }
	  else    
	  {
	    chBoard1 = true;
	    x1 = xmppc[i];
	    y1 = ymppc[i];
	  }
	}
      }
    }
    
//     for(int i = 0 ; i < 32 ; i++)
//     {
//       TTreeFormula* Formula = new TTreeFormula("Formula",Crystals[i],tree);
//       if( Formula->EvalInstance() )
//       {
// 	if(i < 16) //it was on board0
// 	{
// 	  if(chBoard0 == true) // 2 511 in the same matrix, get rid of the event
// 	  {
// 	    continue;
// 	  }
// 	  else
// 	  {
// 	    chBoard0 = true;
// 	    x0 = xmppc[i];
// 	    y0 = ymppc[i];
// 	  }
// 	}
// 	else //it was on board1
// 	{
// 	  if(chBoard1 == true) // 2 511 in the same matrix, get rid of the event
// 	  {
// 	    continue;
// 	  }
// 	  else
// 	  {
// 	    chBoard1 = true;
// 	    x1 = xmppc[i];
// 	    y1 = ymppc[i];
// 	  }
// 	}
//       }
//     }
    
    if(chBoard0&&chBoard1)
    {
      //std::cout << " coincidence " <<  x0 << " " << y0 << " " << z0 << " " << x1 << " " << y1 << " " << z1 << std::endl; 
      float u = x0-x1;
      float v = y0-y1;
      float mx = x0 + s*u;
      float my = y0 + s*v;
      histo2->Fill(mx,my);
    }
    //std::cout << std::endl;
    /*
    if( Formula->EvalInstance() )
    {
      TimeTag = ExtendedTimeTag;
      CrystalID = 0; //TODO
      t2->Fill();
    }*/
    
    counter++;
    
    int perc = ((100*counter)/nentries); //should strictly have not decimal part, written like this...
    if( (perc % 10) == 0 )
    {
      std::cout << "\r";
      std::cout << perc << "% done... ";
      //std::cout << counter << std::endl;
    }
    
  }
  
  TCanvas *canvas= new TCanvas("ciao1", "Distribuzione di Poisson");
  histo2->Draw("COLZ");
  TFile *outFile = new TFile ("histo2d.root","recreate");
  //histo->Write();
  histo2->Write();
  canvas->Write();
  outFile->Close();
  
  
  
  return 0;
}
Exemplo n.º 10
0
void MultiHistoOverlap(TString namesandlabels, Int_t nOfFiles, const TString& outDir="./") {

    gROOT->Reset();
    gROOT->ProcessLine(".L tdrstyle.C");
    gROOT->ProcessLine("setTDRStyle()");

//  gSystem->Load("libRooFit");
//  using namespace RooFit;
// preamble
    TPaveText *cmsprel = new TPaveText(0.19, 0.95, 0.95, 0.99, "NDC");
    cmsprel->SetTextSize(0.03);
    cmsprel->SetTextFont(42);
    cmsprel->SetFillColor(0);
    cmsprel->SetBorderSize(0);
    cmsprel->SetMargin(0.01);
    cmsprel->SetTextAlign(12); // align left
    TString text = "CMS Preliminary 2011";
    cmsprel->AddText(0.0, 0.5,text);
    TString text2 = "#sqrt{s} = 7 TeV  |#eta_{#mu}|<2.4";
    cmsprel->AddText(0.8, 0.5, text2);


    TList* FileList  = new TList();
    TList* LabelList = new TList();
    TObjArray *nameandlabelpairs = namesandlabels.Tokenize(",");
    for (Int_t i = 0; i < nameandlabelpairs->GetEntries(); ++i) {
        TObjArray *aFileLegPair = TString(nameandlabelpairs->At(i)->GetName()).Tokenize("=");
        if(aFileLegPair->GetEntries() == 2) {
            FileList->Add( TFile::Open(aFileLegPair->At(0)->GetName())  );
            LabelList->Add( aFileLegPair->At(1) );
        } else {
            std::cout << "Please give file name and legend entry in the following form:\n" 		<< " filename1=legendentry1,filename2=legendentry2\n";
        }
    }


    Int_t NOfFiles =  FileList->GetSize();
    if ( NOfFiles!=nOfFiles ) {
        std::cout<<"&MSG-e: NOfFiles = "<<nOfFiles<<std::endl;
        return;
    }


    TString LegLabels[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {
        TObjString* legend = (TObjString*)LabelList->At(j);
        LegLabels[j] = legend->String();
        std::cout<<"LegLabels["<<j<<"]"<<LegLabels[j]<<std::endl;
    }

    TLegend *leg=0;

    TCanvas* c0 = new TCanvas("c0", "c0",50, 20, 800,600);
    TCanvas* c1 = new TCanvas("c1", "c1",50, 20, 800,600);
    TCanvas* c2 = new TCanvas("c2", "c2",50, 20, 800,600);
    TCanvas* c3 = new TCanvas("c3", "c3",50, 20, 800,600);
    TCanvas* c4 = new TCanvas("c4", "c4",50, 20, 800,600);
    TCanvas* c5 = new TCanvas("c5", "c5",50, 20, 1200,800);
    TCanvas* c6 = new TCanvas("c6", "c6",50, 20, 1200,800);

    TCanvas* c0s = new TCanvas("c0s", "c0s",50, 20, 800,600);
    TCanvas* c1s = new TCanvas("c1s", "c1s",50, 20, 800,600);
    TCanvas* c2s = new TCanvas("c2s", "c2s",50, 20, 800,600);
    TCanvas* c3s = new TCanvas("c3s", "c3s",50, 20, 800,600);

    TCanvas* cFit = new TCanvas("cFit", "cFit",50, 20, 1600, 800);


//----------------- CANVAS C0 --------------//
    c0->SetFillColor(0);
    c0->cd();

    leg = new TLegend(0.50,0.25,0.90,0.40);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);
    leg->SetTextFont(42);

// Mass VS muon phi plus -------------------------------
    TH1D *histoMassVsPhiPlus[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoMassVsPhiPlus[j] = (TH1D*)fin->Get("MassVsPhiPlus/allHistos/meanHisto")) {
            histoMassVsPhiPlus[j]->SetLineStyle(linestylelist[j]);
            histoMassVsPhiPlus[j]->SetMarkerColor(colorlist[j]);
            histoMassVsPhiPlus[j]->SetLineColor(colorlist[j]);
            histoMassVsPhiPlus[j]->SetMarkerStyle(markerstylelist[j]);
            //     histoMassVsPhiPlus[j]->SetMarkerSize(0.75);
            if ( j == 0 ) {
                histoMassVsPhiPlus[j]->GetXaxis()->SetTitle("positive muon #phi (rad)");
                histoMassVsPhiPlus[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
                //       histoMassVsPhiPlus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
                histoMassVsPhiPlus[j]->GetYaxis()->SetRangeUser(90.0,91.5);
                histoMassVsPhiPlus[j]->GetXaxis()->SetRangeUser(-3.14,3.14);
                histoMassVsPhiPlus[j]->Draw();
            } else {
                histoMassVsPhiPlus[j]->Draw("SAME");
            }
            leg->AddEntry(histoMassVsPhiPlus[j],LegLabels[j],"PL");
        }
    }
//cmsprel->Draw("same");
    leg->Draw("same");
    c0->SaveAs(outDir+"MassVsPhiPlus.png");


//----------------- CANVAS C1 --------------//
    c1->SetFillColor(0);
    c1->cd();

    leg = new TLegend(0.50,0.25,0.90,0.40);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);
    leg->SetTextFont(42);

// Mass VS muon eta plus -------------------------------
    TH1D *histoMassVsEtaPlus[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoMassVsEtaPlus[j] = (TH1D*)fin->Get("MassVsEtaPlus/allHistos/meanHisto")) {
            histoMassVsEtaPlus[j]->SetLineStyle(linestylelist[j]);
            histoMassVsEtaPlus[j]->SetMarkerColor(colorlist[j]);
            histoMassVsEtaPlus[j]->SetLineColor(colorlist[j]);
            histoMassVsEtaPlus[j]->SetMarkerStyle(markerstylelist[j]);
            //     histoMassVsEtaPlus[j]->SetMarkerSize(0.75);
            if ( j == 0 ) {
                histoMassVsEtaPlus[j]->GetXaxis()->SetTitle("positive muon #eta");
                histoMassVsEtaPlus[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
                //       histoMassVsEtaPlus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
                histoMassVsEtaPlus[j]->GetYaxis()->SetRangeUser(90.0,91.5);
                histoMassVsEtaPlus[j]->GetXaxis()->SetRangeUser(-2.41,2.41);
                histoMassVsEtaPlus[j]->Draw();
            } else {
                histoMassVsEtaPlus[j]->Draw("SAME");
            }
            leg->AddEntry(histoMassVsEtaPlus[j],LegLabels[j],"PL");
        }
    }
//cmsprel->Draw("same");
    leg->Draw("same");
    c1->SaveAs(outDir+"MassVsEtaPlus.png");


//----------------- CANVAS C2 --------------//
    c2->SetFillColor(0);
    c2->cd();

    leg = new TLegend(0.50,0.25,0.90,0.40);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);
    leg->SetTextFont(42);

// Mass VS muon eta plus - eta minus  -------------------------------
    TH1D *histoMassVsEtaPlusMinusDiff[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoMassVsEtaPlusMinusDiff[j] = (TH1D*)fin->Get("MassVsEtaPlusMinusDiff/allHistos/meanHisto")) {
            histoMassVsEtaPlusMinusDiff[j]->SetLineStyle(linestylelist[j]);
            histoMassVsEtaPlusMinusDiff[j]->SetMarkerColor(colorlist[j]);
            histoMassVsEtaPlusMinusDiff[j]->SetLineColor(colorlist[j]);
            histoMassVsEtaPlusMinusDiff[j]->SetMarkerStyle(markerstylelist[j]);
            //     histoMassVsEtaPlusMinusDiff[j]->SetMarkerSize(0.75);
            if ( j == 0 ) {
                histoMassVsEtaPlusMinusDiff[j]->GetXaxis()->SetTitle("#eta pos. muon  #eta neg. muon");
                histoMassVsEtaPlusMinusDiff[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
                //       histoMassVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(88.0,96.0);
                histoMassVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(90.0,91.5);
                histoMassVsEtaPlusMinusDiff[j]->GetXaxis()->SetRangeUser(-3,3);
                histoMassVsEtaPlusMinusDiff[j]->Draw();
            } else {
                histoMassVsEtaPlusMinusDiff[j]->Draw("SAME");
            }
            leg->AddEntry(histoMassVsEtaPlusMinusDiff[j],LegLabels[j],"PL");
        }
    }
//cmsprel->Draw("same");
    leg->Draw("same");
    c2->SaveAs(outDir+"MassVsEtaPlusMinusDiff.png");

//----------------- CANVAS C3 --------------//
    c3->SetFillColor(0);
    c3->cd();

    leg = new TLegend(0.50,0.25,0.90,0.40);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);
    leg->SetTextFont(42);

// Mass VS muon phi minus -------------------------------
    TH1D *histoMassVsPhiMinus[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoMassVsPhiMinus[j] = (TH1D*)fin->Get("MassVsPhiMinus/allHistos/meanHisto")) {
            histoMassVsPhiMinus[j]->SetLineStyle(linestylelist[j]);
            histoMassVsPhiMinus[j]->SetMarkerColor(colorlist[j]);
            histoMassVsPhiMinus[j]->SetLineColor(colorlist[j]);
            histoMassVsPhiMinus[j]->SetMarkerStyle(markerstylelist[j]);
            //     histoMassVsPhiMinus[j]->SetMarkerSize(0.75);
            if ( j == 0 ) {
                histoMassVsPhiMinus[j]->GetXaxis()->SetTitle("negative muon #phi (rad)");
                histoMassVsPhiMinus[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
                //       histoMassVsPhiMinus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
                histoMassVsPhiMinus[j]->GetYaxis()->SetRangeUser(90.0,91.5);
                histoMassVsPhiMinus[j]->GetXaxis()->SetRangeUser(-3.14,3.14);
                histoMassVsPhiMinus[j]->Draw();
            } else {
                histoMassVsPhiMinus[j]->Draw("SAME");
            }
            leg->AddEntry(histoMassVsPhiMinus[j],LegLabels[j],"PL");
        }
    }
//cmsprel->Draw("same");
    leg->Draw("same");
    c3->SaveAs(outDir+"MassVsPhiMinus.png");


//----------------- CANVAS C4 --------------//
    c4->SetFillColor(0);
    c4->cd();

    leg = new TLegend(0.50,0.25,0.90,0.40);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);
    leg->SetTextFont(42);

// Mass VS muon eta minus -------------------------------
    TH1D *histoMassVsEtaMinus[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoMassVsEtaMinus[j] = (TH1D*)fin->Get("MassVsEtaMinus/allHistos/meanHisto")) {
            histoMassVsEtaMinus[j]->SetLineStyle(linestylelist[j]);
            histoMassVsEtaMinus[j]->SetMarkerColor(colorlist[j]);
            histoMassVsEtaMinus[j]->SetLineColor(colorlist[j]);
            histoMassVsEtaMinus[j]->SetMarkerStyle(markerstylelist[j]);
            //     histoMassVsEtaMinus[j]->SetMarkerSize(0.75);
            if ( j == 0 ) {
                histoMassVsEtaMinus[j]->GetXaxis()->SetTitle("negative muon #eta");
                histoMassVsEtaMinus[j]->GetYaxis()->SetTitle("M_{#mu#mu} (GeV)");
                //       histoMassVsEtaMinus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
                histoMassVsEtaMinus[j]->GetYaxis()->SetRangeUser(90.0,91.5);
                histoMassVsEtaMinus[j]->GetXaxis()->SetRangeUser(-2.41,2.41);
                histoMassVsEtaMinus[j]->Draw();
            } else {
                histoMassVsEtaMinus[j]->Draw("SAME");
            }
            leg->AddEntry(histoMassVsEtaMinus[j],LegLabels[j],"PL");
        }
    }
//cmsprel->Draw("same");
    leg->Draw("same");
    c4->SaveAs(outDir+"MassVsEtaMinus.png");

//----------------- CANVAS C5 --------------//
    c5->SetFillColor(0);
    c5->cd();

    leg = new TLegend(0.50,0.25,0.90,0.40);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);
    leg->SetTextFont(42);

// Mass VS muon phi plus -------------------------------
    TH2D *histoMassVsEtaPhiPlus[nOfFiles];

    TStyle *newStyle;
    newStyle->SetPalette(1);
// newStyle->SetOptTitle(1);

    Double_t zMin(82.);
    Double_t zMax(96.);
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoMassVsEtaPhiPlus[j] = (TH2D*)fin->Get("MassVsEtaPhiPlus/allHistos/meanHisto")) {
            if ( j == 0 ) {
                histoMassVsEtaPhiPlus[j]->SetTitle(LegLabels[j]);
                histoMassVsEtaPhiPlus[j]->GetXaxis()->SetTitle("positive muon #phi (rad)");
                histoMassVsEtaPhiPlus[j]->GetYaxis()->SetTitle("positive muon #eta");
                zMin = histoMassVsEtaPhiPlus[j]->GetMinimum();
                zMax = histoMassVsEtaPhiPlus[j]->GetMaximum();
                histoMassVsEtaPhiPlus[j]->Draw("COLZ");
                c5->SaveAs(outDir+"MassVsEtaPhiPlus_file0.png");
            } else {
                histoMassVsEtaPhiPlus[j]->SetTitle(LegLabels[j]);
                histoMassVsEtaPhiPlus[j]->SetMinimum(zMin);
                histoMassVsEtaPhiPlus[j]->SetMaximum(zMax);
                histoMassVsEtaPhiPlus[j]->Draw("COLZ");
                c5->SaveAs(outDir+"MassVsEtaPhiPlus_file"+(TString)Form("%d",(Int_t)j)+".png");
            }

        }
    }
//cmsprel->Draw("same");

//  //----------------- CANVAS C6 --------------//
//  c6->SetFillColor(0);
//  c6->cd();

//  leg = new TLegend(0.50,0.25,0.90,0.40);
//  leg->SetBorderSize(1);
//  leg->SetFillColor(0);
//  leg->SetTextFont(42);

//  // Mass VS muon phi minus -------------------------------
//  TH2D *histoMassVsEtaPhiMinus[nOfFiles];

//  for(Int_t j=0; j < nOfFiles; j++) {

//    TFile *fin = (TFile*)FileList->At(j);
//    if ( histoMassVsEtaPhiMinus[j] = (TH2D*)fin->Get("MassVsEtaPhiMinus/allHistos/meanHisto")){
//      if ( j == 0 ) {
//        histoMassVsEtaPhiMinus[j]->GetXaxis()->SetTitle("negative muon #phi (rad)");
//        histoMassVsEtaPhiMinus[j]->GetYaxis()->SetTitle("negative muon #eta");
//        zMin = histoMassVsEtaPhiMinus[j]->GetMinimum();
//        zMax = histoMassVsEtaPhiMinus[j]->GetMaximum();
//        histoMassVsEtaPhiMinus[j]->Draw();
//      } else {
//        histoMassVsEtaPhiMinus[j]->SetMinimum(zMin);
//        histoMassVsEtaPhiMinus[j]->SetMaximum(zMax);
//        histoMassVsEtaPhiMinus[j]->Draw("SAME");
//      }
//      leg->AddEntry(histoMassVsEtaPhiMinus[j],LegLabels[j],"PL");
//    }
//  }
//  //cmsprel->Draw("same");
//  leg->Draw("same");
//  c6->SaveAs(outDir+"MassVsEtaPhiMinus.png");

// newStyle->SetOptTitle(0);

    const Color_t colorlist_resol[7]= {kBlack,kGreen,kBlue,kMagenta,kCyan,kTeal,kRed};
    const Int_t linestylelist_resol[7]= {1,1,1,1,1,1,1};
    const Int_t stylelist_resol[7]= {1,1,1,1,1,1,1};
    const Style_t markerstylelist_resol[7]= {kOpenCircle,kOpenTriangleUp,kOpenTriangleUp,kOpenCircle,kOpenTriangleUp,kOpenCircle,kOpenTriangleUp};


//  //----------------- CANVAS C0S --------------//
//  c0s->SetFillColor(0);
//  c0s->cd();

//  leg = new TLegend(0.50,0.25,0.90,0.40);
//  leg->SetBorderSize(1);
//  leg->SetFillColor(0);
//  leg->SetTextFont(42);

// // Sigma VS muon phi plus -------------------------------
//  TH1D *histoSigmaVsPhiPlus[nOfFiles];
//  for(Int_t j=0; j < nOfFiles; j++) {

//    TFile *fin = (TFile*)FileList->At(j);
//    if ( histoSigmaVsPhiPlus[j] = (TH1D*)fin->Get("MassVsPhiPlus/allHistos/sigmaHisto")){
//      histoSigmaVsPhiPlus[j]->SetLineStyle(linestylelist_resol[j]);
//      histoSigmaVsPhiPlus[j]->SetMarkerColor(colorlist_resol[j]);
//      histoSigmaVsPhiPlus[j]->SetLineColor(colorlist_resol[j]);
//      histoSigmaVsPhiPlus[j]->SetMarkerStyle(markerstylelist_resol[j]);
//      //     histoSigmaVsPhiPlus[j]->SetMarkerSize(0.75);
//      if ( j == 0 ) {
//        histoSigmaVsPhiPlus[j]->GetXaxis()->SetTitle("positive muon #phi (rad)");
//        histoSigmaVsPhiPlus[j]->GetYaxis()->SetTitle("#sigma(M_{#mu#mu}) (GeV)");
//        //       histoSigmaVsPhiPlus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
//        histoSigmaVsPhiPlus[j]->GetYaxis()->SetRangeUser(0.,3.);
//        histoSigmaVsPhiPlus[j]->GetXaxis()->SetRangeUser(-3.14,3.14);
//        histoSigmaVsPhiPlus[j]->Draw();
//      } else {
//        histoSigmaVsPhiPlus[j]->Draw("SAME");
//      }
//      leg->AddEntry(histoSigmaVsPhiPlus[j],LegLabels[j],"PL");
//    }
//  }
//  //cmsprel->Draw("same");
//  leg->Draw("same");
//  c0s->SaveAs(outDir+"SigmaVsPhiPlus.png");


//----------------- CANVAS C1S --------------//
    c1s->SetFillColor(0);
    c1s->cd();

    leg = new TLegend(0.50,0.25,0.90,0.40);
    leg->SetBorderSize(1);
    leg->SetFillColor(0);
    leg->SetTextFont(42);


// Sigma VS muon eta plus -------------------------------
    TH1D *histoSigmaVsEtaPlus[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoSigmaVsEtaPlus[j] = (TH1D*)fin->Get("MassVsEtaPlus/allHistos/sigmaHisto")) {
            histoSigmaVsEtaPlus[j]->SetLineStyle(linestylelist_resol[j]);
            histoSigmaVsEtaPlus[j]->SetMarkerColor(colorlist_resol[j]);
            histoSigmaVsEtaPlus[j]->SetLineColor(colorlist_resol[j]);
            histoSigmaVsEtaPlus[j]->SetMarkerStyle(markerstylelist_resol[j]);
            //     histoSigmaVsEtaPlus[j]->SetMarkerSize(0.75);
            if ( j == 0 ) {
                histoSigmaVsEtaPlus[j]->GetXaxis()->SetTitle("positive muon #eta");
                histoSigmaVsEtaPlus[j]->GetYaxis()->SetTitle("#sigma(M_{#mu#mu}) (GeV)");
                //       histoSigmaVsEtaPlus[j]->GetYaxis()->SetRangeUser(88.5,93.5);
                histoSigmaVsEtaPlus[j]->GetYaxis()->SetRangeUser(0.,3.);
                histoSigmaVsEtaPlus[j]->GetXaxis()->SetRangeUser(-2.41,2.41);
                histoSigmaVsEtaPlus[j]->Draw();
            } else {
                histoSigmaVsEtaPlus[j]->Draw("SAME");
            }
            leg->AddEntry(histoSigmaVsEtaPlus[j],LegLabels[j],"PL");
        }
    }
//cmsprel->Draw("same");
    leg->Draw("same");
    c1s->SaveAs(outDir+"SigmaVsEtaPlus.png");


//  //----------------- CANVAS C2S --------------//
//  c2s->SetFillColor(0);
//  c2s->cd();

//  leg = new TLegend(0.50,0.25,0.90,0.40);
//  leg->SetBorderSize(1);
//  leg->SetFillColor(0);
//  leg->SetTextFont(42);

// // Sigma VS muon eta plus - eta minus  -------------------------------
//  TH1D *histoSigmaVsEtaPlusMinusDiff[nOfFiles];
//  for(Int_t j=0; j < nOfFiles; j++) {

//    TFile *fin = (TFile*)FileList->At(j);
//    if ( histoSigmaVsEtaPlusMinusDiff[j] = (TH1D*)fin->Get("MassVsEtaPlusMinusDiff/allHistos/sigmaHisto")){
//      histoSigmaVsEtaPlusMinusDiff[j]->SetLineStyle(linestylelist_resol[j]);
//      histoSigmaVsEtaPlusMinusDiff[j]->SetMarkerColor(colorlist_resol[j]);
//      histoSigmaVsEtaPlusMinusDiff[j]->SetLineColor(colorlist_resol[j]);
//      histoSigmaVsEtaPlusMinusDiff[j]->SetMarkerStyle(markerstylelist_resol[j]);
//      //     histoSigmaVsEtaPlusMinusDiff[j]->SetMarkerSize(0.75);
//      if ( j == 0 ) {
//        histoSigmaVsEtaPlusMinusDiff[j]->GetXaxis()->SetTitle("#eta pos. muon - #eta neg. muon");
//        histoSigmaVsEtaPlusMinusDiff[j]->GetYaxis()->SetTitle("#sigma(M_{#mu#mu}) (GeV)");
//        //       histoSigmaVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(88.0,96.0);
//        histoSigmaVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(0.,3.);
//        //histoSigmaVsEtaPlusMinusDiff[j]->GetYaxis()->SetRangeUser(90.60,90.75);
//        histoSigmaVsEtaPlusMinusDiff[j]->GetXaxis()->SetRangeUser(-3.2,3.2);
//        histoSigmaVsEtaPlusMinusDiff[j]->Draw();
//      } else {
//        histoSigmaVsEtaPlusMinusDiff[j]->Draw("SAME");
//      }
//      leg->AddEntry(histoSigmaVsEtaPlusMinusDiff[j],LegLabels[j],"PL");
//    }
//  }
//  //cmsprel->Draw("same");
//  leg->Draw("same");
//  c2s->SaveAs(outDir+"SigmaVsEtaPlusMinusDiff.png");


//  //----------------- CANVAS C3S --------------//
//  c3s->SetFillColor(0);
//  c3s->cd();

//  leg = new TLegend(0.35,0.15,0.55,0.35);
//  leg->SetBorderSize(1);
//  leg->SetFillColor(0);
//  leg->SetTextFont(42);

// // Sigma VS muon pT  -------------------------------
//  TH1D *histoSigmaVsPt[nOfFiles];
//  for(Int_t j=0; j < nOfFiles; j++) {

//    TFile *fin = (TFile*)FileList->At(j);
//    if ( histoSigmaVsPt[j] = (TH1D*)fin->Get("MassVsPt/allHistos/sigmaHisto")){
//      histoSigmaVsPt[j]->SetLineStyle(linestylelist_resol[j]);
//      histoSigmaVsPt[j]->SetMarkerColor(colorlist_resol[j]);
//      histoSigmaVsPt[j]->SetLineColor(colorlist_resol[j]);
//      histoSigmaVsPt[j]->SetMarkerStyle(markerstylelist_resol[j]);
//      //     histoSigmaVsPt[j]->SetMarkerSize(0.75);
//      if ( j == 0 ) {
//        histoSigmaVsPt[j]->GetXaxis()->SetTitle("muon p_T (GeV)");
//        histoSigmaVsPt[j]->GetYaxis()->SetTitle("#sigma(M_{#mu#mu}) (GeV)");
//        //       histoSigmaVsPt[j]->GetYaxis()->SetRangeUser(88.0,96.0);
//        histoSigmaVsPt[j]->GetYaxis()->SetRangeUser(0.,3.);
//        //histoSigmaVsPt[j]->GetYaxis()->SetRangeUser(90.60,90.75);
//        histoSigmaVsPt[j]->GetXaxis()->SetRangeUser(15.,105.);
//        histoSigmaVsPt[j]->Draw();
//      } else {
//        histoSigmaVsPt[j]->Draw("SAME");
//      }
//      leg->AddEntry(histoSigmaVsPt[j],LegLabels[j],"PL");
//    }
//  }
//  //cmsprel->Draw("same");
//  leg->Draw("same");
//  c3s->SaveAs(outDir+"SigmaVsPt.png");

//----------------- CANVAS CFIT --------------//
    cFit->SetFillColor(0);
    cFit->cd();
    Float_t nN = TMath::Sqrt(nOfFiles);
    Int_t nX = (Int_t)nN;
    if ( nN-nX > 0.5 ) nX++;
    Int_t nY = (Int_t)(nOfFiles/nX);
    std::cout << nX << " ," << nY << std::endl;
    cFit->Divide(nOfFiles,1);

// Mass VS muon phi plus -------------------------------
    TFile *ZFitFile = new TFile("ZFitFile.root","RECREATE");
    RooPlot *histoLineShape[nOfFiles];
    for(Int_t j=0; j < nOfFiles; j++) {

        TFile *fin = (TFile*)FileList->At(j);
        if ( histoLineShape[j] = (RooPlot*)fin->Get("hRecBestResAllEvents_Mass_frame")) {
            std::cout<<"Writing fit histogrem file n. "<<j<<std::endl;
            histoLineShape[j]->Write();
            cFit->cd(j+1);
            histoLineShape[j]->SetTitle(LegLabels[j]);
            histoLineShape[j]->Draw();
            histoLineShape[j]->GetXaxis()->SetTitle("M_{#mu#mu} (GeV)");
//      TPaveText *cmsprel2 = new TPaveText(0.19, 0.95, 0.95, 0.99, "NDC");
//      cmsprel2->SetTextSize(0.03);
//      cmsprel2->SetTextFont(42);
//      cmsprel2->SetFillColor(0);
//      cmsprel2->SetBorderSize(0);
//      cmsprel2->SetMargin(0.01);
//      cmsprel2->SetTextAlign(12); // align left
//      cmsprel2->AddText(0.666666, 0.5, LegLabels[j]);

        }
    }
    ZFitFile->Close();
// cmsprel2->Draw("same");
    cFit->SaveAs("ZFitFile.root");



    return;
};
Exemplo n.º 11
0
int main(int argc, char *argv[])
{
    /////////********* Calculation Variables
    unsigned int vNumberOfParticles = 1000;
    double vStepLengthMin = 2.E-11;
    double vTransverseVariationMax = 2.E-13;
    //std::string vName = "/home/ebagli/DATA/ESTB_Crystal";
    
    /////////********* Beam Variables
    double vBeamMomentum = 150. * GeV;
    double vParticleMass = cElectronMass;
    double vParticleCharge = -1.;
    
    double vMeanIncomingAngleX = 0. * microrad;
    double vVarianceIncomingAngleX = 5. * microrad;
    
    double vMeanIncomingAngleY = 0. * microrad;
    double vVarianceIncomingAngleY = 5. * microrad;
    
    unsigned int vBeamAngleDistributionType = 0;
    
    unsigned int vMultipleScatteringModel = 3;
    if(vParticleCharge == cElectronMass) vMultipleScatteringModel = 3;
    
    /////////********* Crystal Variables
#ifdef Cut_
    double vCutStart = 4. * micrometer;
    double vCutEnd = 18. * micrometer;
#endif
#ifdef SiGe_
    double vGeConcentration = 0.04;
#endif
    
    double vCrystalLenght = 0.185 * millimeter;
    double vSecondaryCurvature = 0. * meter;
    
#ifdef bUndulator
    double vUndulatorAmplitude = 0.6 * AA;
    double vUndulatorPeriod = 600. * nanometer;
#endif
    
    int vMillerPl[3] = {2,2,0};
    int vMillerAx[3] = {1,1,0};
    
    /////////********* Defect Variables
#ifdef bDefect
    unsigned int vNumberOfStackingFaults = 0;
    unsigned int vNumberOfEdges = 1;
    
    float vDefectMeanX = 0.0 * AA;
    float vDefectVarianceX = 0.5 * millimeter;
    
    float vDefectMeanZ = vCrystalLenght / 2.;
    float vDefectVarianceZ = vCrystalLenght / 2.;
#endif
    
    
#ifdef bNumberOfThreads
    vNumberOfParticles = int(bNumberOfThreads);
#endif
    
    
    if(argv[1]){
        if(atoi(argv[1]) != 0){
            vNumberOfParticles = atoi(argv[1]);
        }
    }
    
    std::string vName = "noname";
    if(argv[2]){
        vName = argv[2];
    }
    
    
    
    /////////********* Save Structures Inizialization
    static ECHARM_Particle_Save vPartIn;
    static ECHARM_Particle_Save vPartOut;
    static double vRadius;
    static double vLength;
    static double vOutAng;
    static double vOutPos;
#ifdef bSaveTrajectory
    static ECHARM_Particle_Save vPart;
    static ECHARM_Strip_Save vStrip;
#endif
    /////////********* TFile & TTree Inizialization
    
    std::string vRootFileName = vName + ".root";
    TFile *vRootFile = new TFile(vRootFileName.c_str(),"RECREATE");
    TTree *vTree = new TTree("SiSim","Monte Carlo Simulation with OpenMP enabled");
    vTree->Branch("vPartIn",&vPartIn,"x_in/D:y_in/D:z_in/D:px_in/D:py_in/D:pz_in/D");
    vTree->Branch("vPartout",&vPartOut,"x_out/D:y_out/D:z_out/D:px_out/D:py_out/D:pz_out/D");
    vTree->Branch("vRadius",&vRadius,"R/D");
    vTree->Branch("vLength",&vLength,"L/D");
    vTree->Branch("vOutPos",&vOutPos,"dx/D");
    vTree->Branch("vOutAng",&vOutAng,"dthx/D");
    
#ifdef bSaveTrajectory
    TTree *vTreeTraj = new TTree("SiSimTraj","Monte Carlo simulation of trajectories");
    vTreeTraj->Branch("vPart",&vPart,"x/D:y/D:z/D:px/D:py/D:pz/D");
    vTreeTraj->Branch("vStrip",&vStrip,"Rx/D:Ry/D:Rz/D:Lx/D:Ly/D:Lz/D");
    vTreeTraj->Branch("vOutPos",&vOutPos,"dx/D");
    vTreeTraj->Branch("vOutAng",&vOutAng,"dthx/D");
#endif
    
#ifdef bSaveTrajectory
    std::string vFileNameTrajectory = vName + "_traj.txt";  //
    std::ofstream fOutputTrajectory;
    fOutputTrajectory.open(vFileNameTrajectory.c_str());
#endif
    
    
    
    
    
    
    
    
    
    /////////********* Crystal Inizialization
#ifdef Si_
    ECHARM_crystal_Si *crystal_base = new ECHARM_crystal_Si(vMillerPl,vMillerAx);
#endif
    
#ifdef Ge_
    ECHARM_crystal_Ge *crystal_base = new ECHARM_crystal_Ge(vMillerPl,vMillerAx);
#endif
    
#ifdef SiGe_
    ECHARM_crystal_SiGe *crystal_base = new ECHARM_crystal_SiGe(vMillerPl,vMillerAx,vGeConcentration);
#endif
    
    ECHARM_crystal_reciprocal *crystal_reciprocal = new ECHARM_crystal_reciprocal(crystal_base);
#ifdef Axial_
    ECHARM_crystal_interpolation *crystal_interpolation;
    std::string vFileName = crystal_base->PrintNameOnString(0,1) + ".txt";
    
    std::ifstream fInput;
    fInput.open(vFileName.c_str());
    if(!(fInput.good())){
        fInput.close();
        crystal_reciprocal->SetIntegrationStepNumberAxialX(bIntegrationNumberAxialX);
        crystal_reciprocal->SetIntegrationStepNumberAxialY(bIntegrationNumberAxialY);
        
        crystal_reciprocal->FindAxialFourierCoefficient();
        crystal_reciprocal->FindPlanarFourierCoefficient();
        
        crystal_interpolation = new ECHARM_crystal_interpolation(crystal_reciprocal,1);
        for(unsigned int i=0;i<5;i++){
            vFileName = crystal_base->PrintNameOnString(i,1) + ".txt";
            std::cout << vFileName << std::endl;
            crystal_interpolation->PrintAxialElectricCharacteristicToFile(vFileName,crystal_interpolation->GetAxialElectricCharacteristicVector(i));
        }
        for(unsigned int i=0;i<4;i++){
            vFileName = crystal_base->PrintNameOnString(i,0) + ".txt";
            std::cout << vFileName << std::endl;
            crystal_interpolation->PrintPlanarElectricCharacteristicToFile(vFileName,crystal_interpolation->GetPlanarElectricCharacteristicVector(i));
        }
    }
    else{
        fInput.close();
        
        
        crystal_interpolation = new ECHARM_crystal_interpolation(crystal_base);
        
        for(unsigned int i=0;i<5;i++){
            vFileName = crystal_base->PrintNameOnString(i,1) + ".txt";
            crystal_interpolation->ReadAxialElectricCharacteristicFromFileInterpolation(vFileName,i);
        }
        for(unsigned int i=0;i<4;i++){
            vFileName = crystal_base->PrintNameOnString(i,0) + ".txt";
            crystal_interpolation->ReadPlanarElectricCharacteristicFromFileInterpolation(vFileName,i);
        }
    }
#else
    crystal_reciprocal->FindPlanarFourierCoefficient();
    ECHARM_crystal_interpolation *crystal_interpolation = new ECHARM_crystal_interpolation(crystal_reciprocal);
#endif
    
    crystal_interpolation->SetIntegrationStepNumberAxialX(bIntegrationNumberAxialX);
    crystal_interpolation->SetIntegrationStepNumberAxialY(bIntegrationNumberAxialY);
    
    /////////********* Beam Inizialization
#ifdef Axial_
    ECHARM_distribution *vDistributionParticlePositionX = new ECHARM_distribution();
    vDistributionParticlePositionX->SetDistributionType(0);
    vDistributionParticlePositionX->SetDistributionParameter(0,0.*crystal_reciprocal->GetDirectPeriodAxialX() * 1.0 / 2.0);
    vDistributionParticlePositionX->SetDistributionParameter(1,crystal_reciprocal->GetDirectPeriodAxialX() * 1.0 / 2.0);
    
    ECHARM_distribution *vDistributionParticlePositionY = new ECHARM_distribution();
    vDistributionParticlePositionY->SetDistributionType(0);
    vDistributionParticlePositionY->SetDistributionParameter(0,0.*crystal_reciprocal->GetDirectPeriodAxialY() * 1.0 / 2.0);
    vDistributionParticlePositionY->SetDistributionParameter(1,crystal_reciprocal->GetDirectPeriodAxialY() * 1.0 / 2.0);
    
#else
    ECHARM_distribution *vDistributionParticlePositionX = new ECHARM_distribution();
    vDistributionParticlePositionX->SetDistributionType(0);
    vDistributionParticlePositionX->SetDistributionParameter(0,0.*crystal_reciprocal->GetDirectPeriodPlanar() * 1.0 / 2.0);
    if(vParticleCharge < 0.) {
        vDistributionParticlePositionX->SetDistributionParameter(0,0.0);
    }
    vDistributionParticlePositionX->SetDistributionParameter(1,crystal_reciprocal->GetDirectPeriodPlanar() * 1.0 / 2.0);
#endif
    
    ECHARM_distribution *vDistributionParticleMomentumX = new ECHARM_distribution();
    vDistributionParticleMomentumX->SetDistributionType(vBeamAngleDistributionType);
    vDistributionParticleMomentumX->SetDistributionParameter(0,vMeanIncomingAngleX*vBeamMomentum);
    vDistributionParticleMomentumX->SetDistributionParameter(1,vVarianceIncomingAngleX*vBeamMomentum);
    
    ECHARM_distribution *vDistributionParticleMomentumY = new ECHARM_distribution();
    vDistributionParticleMomentumY->SetDistributionType(vBeamAngleDistributionType);
    vDistributionParticleMomentumY->SetDistributionParameter(0,vMeanIncomingAngleY*vBeamMomentum);
    vDistributionParticleMomentumY->SetDistributionParameter(1,vVarianceIncomingAngleY*vBeamMomentum);
    
#ifdef bDefect
    /////////********* Dislocation Inizialization
    ECHARM_distribution *vDistributionDislocationPositionX = new ECHARM_distribution();
    vDistributionDislocationPositionX->SetDistributionType(0);
    vDistributionDislocationPositionX->SetDistributionParameter(0,vDefectMeanX);
    vDistributionDislocationPositionX->SetDistributionParameter(1,vDefectVarianceX);
    
    ECHARM_distribution *vDistributionDislocationPositionZ = new ECHARM_distribution();
    vDistributionDislocationPositionZ->SetDistributionType(0);
    vDistributionDislocationPositionZ->SetDistributionParameter(0,vDefectMeanZ);
    vDistributionDislocationPositionZ->SetDistributionParameter(1,vDefectVarianceZ);
#endif
    
    
    
    
    
    
    
    
    
    
    
    /////////********* Write simulation variables on a file
    std::string vParameterFileName = vName + ".txt";
    std::ofstream vParameterFile;
    vParameterFile.open(vParameterFileName.c_str());
    vParameterFile << "******************************" << std::endl;
    vParameterFile << "********* General ************" << std::endl;
    vParameterFile << "******************************" << std::endl;
    vParameterFile << "Number of particles = " << vNumberOfParticles << std::endl;
    vParameterFile << "Z Variation Min [AA] = " << vStepLengthMin/AA << std::endl;
    vParameterFile << "X Variation Max [AA] = " << vTransverseVariationMax/AA << std::endl;
    vParameterFile << "******************************" << std::endl;
    vParameterFile << "********* Beam ***************" << std::endl;
    vParameterFile << "******************************" << std::endl;
    vParameterFile << "Momentum [GeV] = " << vBeamMomentum/GeV << std::endl;
    vParameterFile << "Mass [MeV] = " << vParticleMass/MeV << std::endl;
    vParameterFile << "Charge = " << vParticleCharge << std::endl;
    vParameterFile << "Mean Incoming Angle [µrad] = " << vMeanIncomingAngleX/microrad << std::endl;
    vParameterFile << "Variance Incoming Angle [GeV] = " << vVarianceIncomingAngleX/microrad << std::endl;
    vParameterFile << "Distribution Type [0=box;1=gauss] = " << vBeamAngleDistributionType << std::endl;
    vParameterFile << std::endl;
    vParameterFile << "******************************" << std::endl;
    vParameterFile << "********* Crystal ************" << std::endl;
    vParameterFile << "******************************" << std::endl;
    vParameterFile << "Material = " << crystal_base->GetAtomName() << std::endl;
    vParameterFile << "Length [mm] = " << vCrystalLenght/millimeter << std::endl;
    vParameterFile << "Bending Radius [m;0=infty] = " << vSecondaryCurvature/meter << std::endl;
    vParameterFile << "Channeling plane = [ " << vMillerPl[0] << " " << vMillerPl[1] << " " << vMillerPl[2] << " ]" << std::endl;
    vParameterFile << "Channeling axis = < " << vMillerAx[0] << " " << vMillerAx[1] << " " << vMillerAx[2] << " >" << std::endl;
#ifdef Cut_
    vParameterFile << "********* Cut" << std::endl;
    vParameterFile << "Begin [mm] = " << vCutStart/millimeter << std::endl;
    vParameterFile << "End [mm] = " << vCutEnd/millimeter << std::endl;
#endif
#ifdef SiGe_
    vParameterFile << "********* SiGe" << std::endl;
    vParameterFile << "Ge Concentration [%] = " << vGeConcentration * 100. << std::endl;
#endif
#ifdef bUndulator
    vParameterFile << "********* Undulator" << std::endl;
    vParameterFile << "Amplitude [A] = " << vUndulatorAmplitude/AA << std::endl;
    vParameterFile << "Period [µm] = " << vUndulatorPeriod/micrometer << std::endl;
#endif
#ifdef bDefect
    vParameterFile << "********* Defects" << std::endl;
    vParameterFile << "Number of stacking faults = " << vNumberOfStackingFaults << std::endl;
    vParameterFile << "Number of edges = " << vNumberOfEdges << std::endl;
    vParameterFile << "X Position Mean [AA] = " << vDefectMeanX/AA << std::endl;
    vParameterFile << "X Position Variance [mm] = " << vDefectVarianceX/millimeter << std::endl;
    vParameterFile << "Z Position Mean [mm] = " << vDefectMeanZ/millimeter << std::endl;
    vParameterFile << "Z Position Variance [mm] = " << vDefectVarianceZ/millimeter << std::endl;
#endif
    vParameterFile.close();
    
    
    
    
    
    
    
    
    
    
    /////////********* Loop on particles
    int j,vNumberOfThreads,vNumberOfParticlesOMP;
    time_t vInitialTime = time (NULL);
    
#pragma omp parallel shared(vNumberOfThreads,vNumberOfParticlesOMP) private(j)
    
    vNumberOfThreads = omp_get_num_threads();
    
#ifdef bNumberOfThreads
    vNumberOfThreads = bNumberOfThreads;
#endif
    
    vNumberOfParticlesOMP = int(vNumberOfParticles/vNumberOfThreads);
    
#ifdef bSaveTrajectory
    int saveTrajPoint[vNumberOfParticles];
#endif
    
    bool bIntegrationEnd[vNumberOfThreads];
    
    double saveOutgoingAngle[vNumberOfThreads];
    double saveOutgoingPosition[vNumberOfThreads];
    
#ifdef bUndulator
    ECHARM_threevector* saveUndulatorAmplitude[vNumberOfThreads];
    ECHARM_threevector* saveUndulatorPeriod[vNumberOfThreads];
    ECHARM_undulator *saveUndulator[vNumberOfThreads];
#endif
    
    ECHARM_threevector* saveParticlePositionVector[vNumberOfThreads];
    ECHARM_threevector* saveParticleMomentumVector[vNumberOfThreads];
    ECHARM_particle* saveParticle[vNumberOfThreads];
    
    ECHARM_threevector *saveStripCurvatureRadius[vNumberOfThreads];
    ECHARM_threevector *saveStripDimension[vNumberOfThreads];
    ECHARM_crystal_interpolation *saveCrystal[vNumberOfThreads];
    ECHARM_strip *saveStrip[vNumberOfThreads];
    
    ECHARM_simulation_integration* saveSimulationIntegration[vNumberOfThreads];
    
    ECHARM_Particle_Save saveParticleIncoming[vNumberOfThreads];
    ECHARM_Particle_Save saveParticleOutgoing[vNumberOfThreads];
    
#ifdef bMultipleScattering
    ECHARM_multiple_scattering* saveMultipleScattering[vNumberOfThreads];
#endif
    
    
#ifdef bDefect
    ECHARM_defect_edge *saveEdge[vNumberOfThreads*vNumberOfEdges];
    bool bDefectEdgeON[vNumberOfThreads*vNumberOfEdges];
    
    ECHARM_threevector *saveStackingFaults[vNumberOfThreads*vNumberOfStackingFaults];
    bool bDefectStackingFaultsON[vNumberOfThreads*vNumberOfStackingFaults];
#endif
    
    for(j=0; j<vNumberOfThreads;j++)
    {
        saveCrystal[j] = new ECHARM_crystal_interpolation(crystal_interpolation);
        saveCrystal[j]->SetIntegrationStepNumberAxialX(bIntegrationNumberAxialX);
        saveCrystal[j]->SetIntegrationStepNumberAxialY(bIntegrationNumberAxialY);
        
        saveStripCurvatureRadius[j] = new ECHARM_threevector(vSecondaryCurvature,0.,0.);
        saveStripDimension[j] = new ECHARM_threevector(1.*millimeter,1.*millimeter,vCrystalLenght);
        saveStrip[j] = new ECHARM_strip(saveCrystal[j],saveStripDimension[j],saveStripCurvatureRadius[j]);
        
        
        saveParticlePositionVector[j] = new ECHARM_threevector(0.0*AA,0.0*AA,0.);;
        saveParticleMomentumVector[j] = new ECHARM_threevector(0.,0.,vBeamMomentum);
        saveParticle[j] = new ECHARM_particle(vParticleCharge,vParticleMass,saveParticleMomentumVector[j],saveParticlePositionVector[j]);
        
#ifdef bUndulator
        saveUndulatorAmplitude[j] = new ECHARM_threevector(vUndulatorAmplitude,0.,0.);
        saveUndulatorPeriod[j] = new ECHARM_threevector(vUndulatorPeriod,0.,0.);
        saveUndulator[j] = new ECHARM_undulator(saveUndulatorAmplitude[j],saveUndulatorPeriod[j],saveParticlePositionVector[j]);
#endif
        
        saveSimulationIntegration[j] = new ECHARM_simulation_integration(saveStrip[j],saveParticle[j]);
        saveSimulationIntegration[j]->SetStepLengthMin(vStepLengthMin);
        saveSimulationIntegration[j]->SetTransverseVariationMax(vTransverseVariationMax);
        saveSimulationIntegration[j]->UpdateStepLengthPlanarMin();
        
        
#ifdef bMultipleScattering
        saveMultipleScattering[j] = new ECHARM_multiple_scattering(saveCrystal[j],saveParticle[j]);
        saveMultipleScattering[j]->SetNuclearScatteringModel(vMultipleScatteringModel);
        saveMultipleScattering[j]->SetElectronScatteringModel(4);
        saveMultipleScattering[j]->SetCrossedMaterialLength(1.*millimeter);
#endif
        
#ifdef bDefect
        for(unsigned int k=0;k<vNumberOfEdges;k++)
        {
            saveEdge[j+k] = new ECHARM_defect_edge();
            saveEdge[k]->SetPoissonRatio(0.42);
            
        }
        for(unsigned int l=0;l<vNumberOfStackingFaults;l++) saveStackingFaults[j+l] = new ECHARM_threevector();
#endif
    }
    
    saveParticle[0]->PrintParticleProperties();
    saveSimulationIntegration[0]->PrintChannelingProperties();
#ifdef bMultipleScattering
    saveMultipleScattering[0]->PrintMultipleScatteringFunctionTH1(vMultipleScatteringModel);
#endif
    for(int i=0;i<vNumberOfParticlesOMP;i++)
    {
        for(j=0; j<vNumberOfThreads;j++)
        {
            bIntegrationEnd[j] = false;
#ifdef Axial_
            saveParticle[j]->GetPositionVector()->Set(vDistributionParticlePositionX->GenerateNumber(),0.0,0.0);
            saveParticle[j]->GetMomentumVector()->Set(vDistributionParticleMomentumX->GenerateNumber(),0.0,vBeamMomentum);
            
            saveParticle[j]->GetPositionVector()->Set(vDistributionParticlePositionY->GenerateNumber(),0.0,0.0);
            saveParticle[j]->GetMomentumVector()->Set(vDistributionParticleMomentumY->GenerateNumber(),0.0,vBeamMomentum);
            
#else
            saveParticle[j]->GetPositionVector()->Set(vDistributionParticlePositionX->GenerateNumber(),0.0,0.0);
            saveParticle[j]->GetMomentumVector()->Set(vDistributionParticleMomentumX->GenerateNumber(),0.0,vBeamMomentum);
#endif
            
            saveOutgoingPosition[j] = 0.0;
            saveOutgoingAngle[j] = 0.0;
            
#ifdef bSaveTrajectory
            saveTrajPoint[j] = 0.0;
#endif
            
#ifdef bDefect
            for(unsigned int k=0;k<vNumberOfEdges;k++)
            {
                bDefectEdgeON[j+k] = true;
                saveEdge[j+k]->GetBurger()->Set(saveCrystal[0]->GetDirectPeriodPlanar(),0.,0.);
                saveEdge[j+k]->GetDefectCenter()->Set(vDistributionDislocationPositionX->GenerateNumber(),0.,vDistributionDislocationPositionZ->GenerateNumber());
            }
            
            for(unsigned int k=0;k<vNumberOfStackingFaults;k++)
            {
                bDefectStackingFaultsON[j+k] = true;
                saveStackingFaults[j+k]->Set(vDistributionDislocationPositionX->GenerateNumber(),0.,vDistributionDislocationPositionZ->GenerateNumber());
            }
#endif
        }
        
#ifdef bPrintScreenNumberOfParticles
        if(fmod(i+1,bPrintScreenNumberOfParticles)==0){
            std::cout << "Particle OMP " << std::setw(5) << i + 1 << " of " << vNumberOfParticlesOMP << " with " << vNumberOfThreads << " threads" << std::endl;
        }
#endif
        
        for(j=0;j<vNumberOfThreads;j++) saveParticle[j]->PrintParticleOn(saveParticleIncoming[j]);
        
#pragma omp parallel for
        for(j=0;j<vNumberOfThreads;j++)
        {
            do
            {
                
#ifdef bDefect
                for(unsigned int k=0;k<vNumberOfEdges;k++)
                {
                    if(saveParticle[j]->GetPositionVector()->GetZ() < saveEdge[j*vNumberOfEdges+k]->GetDefectCenter()->GetZ()) bDefectEdgeON[j*vNumberOfEdges+k] = false;
                    else bDefectEdgeON[j*vNumberOfEdges+k] = true;
                    
                    if(bDefectEdgeON[j*vNumberOfEdges+k])
                    {
                        saveEdge[j*vNumberOfEdges+k]->FindDisplacement(saveParticle[j]->GetPositionVector(),saveEdge[j*vNumberOfEdges+k]->GetDisplacement());
                        saveParticle[j]->GetPositionVector()->AddX(saveEdge[j*vNumberOfEdges+k]->GetDisplacement()->GetX() - saveEdge[j*vNumberOfEdges+k]->GetDisplacementOld()->GetX());
                        saveOutgoingPosition[j] += ( saveEdge[j*vNumberOfEdges+k]->GetDisplacement()->GetX() - saveEdge[j*vNumberOfEdges+k]->GetDisplacementOld()->GetX() );
                        saveEdge[j*vNumberOfEdges+k]->FindDisplacement(saveParticle[j]->GetPositionVector(),saveEdge[j*vNumberOfEdges+k]->GetDisplacementOld());
                    }
                }
                
                for(unsigned int l=0;l<vNumberOfStackingFaults;l++)
                {
                    if(bDefectStackingFaultsON[j*vNumberOfStackingFaults+l])
                        if(saveParticle[j]->GetPositionVector()->GetZ() > saveStackingFaults[j*vNumberOfStackingFaults+l]->GetZ())
                        {
                            saveParticle[j]->GetPositionVector()->AddX(saveCrystal[j]->GetDirectPeriodPlanar() / 2.);
                            bDefectStackingFaultsON[j*vNumberOfStackingFaults+l] = false;
                            saveOutgoingPosition[j] += (saveCrystal[j]->GetDirectPeriodPlanar() / 2.);
                        }
                }
#endif
                
#ifdef bUndulator
                saveStripCurvatureRadius[j]->SetX(vSecondaryCurvature + saveUndulator[j]->GetOsculatorRadius()->GetX());
#endif
                
#ifdef Axial_
                saveSimulationIntegration[j]->UpdateStepLengthAxial();
#else
                saveSimulationIntegration[j]->UpdateStepLengthPlanar();
#endif
                
#ifdef Cut_
                if(saveParticle[j]->GetPositionVector()->GetZ() > vCutStart &&
                   saveParticle[j]->GetPositionVector()->GetZ() < vCutEnd)
                {
                    saveSimulationIntegration[j]->DoStraightStep();
                }
                else{
#ifdef Axial_
                    saveSimulationIntegration[j]->DoIntegrationStepAxialVelocityVerlet();
#else
                    saveSimulationIntegration[j]->DoIntegrationStepPlanarVelocityVerlet();
#endif
                    
                }
#else
#ifdef Axial_
                saveSimulationIntegration[j]->DoIntegrationStepAxialVelocityVerlet();
#else
                saveSimulationIntegration[j]->DoIntegrationStepPlanarVelocityVerlet();
#endif
#endif
                
                
#ifdef bMultipleScattering
                saveMultipleScattering[j]->SetCrossedMaterialLength(saveSimulationIntegration[j]->GetStepLength());
                saveMultipleScattering[j]->UpdateElectronScatteringOutgoingDistribution();
                saveMultipleScattering[j]->DoElectronScatteringPlanar();
                saveMultipleScattering[j]->UpdateNuclearScatteringOutgoingDistribution();
                saveMultipleScattering[j]->DoNuclearScatteringPlanar();
#endif
                
                saveOutgoingAngle[j] = saveParticle[j]->GetPositionVector()->GetZ()/saveStrip[j]->GetCurvatureRadius()->GetX();
                
#ifdef bSaveTrajectory
                if(saveParticle[j]->GetPositionVector()->GetZ() > saveTrajPoint[j]*bSaveTrajectoryMinDistance){
#pragma omp critical
                    {
                        vOutAng = saveOutgoingAngle[j];
                        vOutPos = saveOutgoingPosition[j];
#ifdef bUndulator
                        vOutPos += saveUndulator[j]->GetOsculatorRadius()->GetX();
#endif
                        saveParticle[j]->PrintParticleOn(vPart);
                        saveStrip[j]->PrintStripOn(vStrip);
                        vTreeTraj->Fill();
                        saveTrajPoint[j]++;
                        
                        fOutputTrajectory << i+j;
                        fOutputTrajectory << " " << - cos(vPart.z/vStrip.Rx) * (vStrip.Rx - (vPart.x + vOutPos)) + vStrip.Rx;
                        fOutputTrajectory << " " << vPart.y;
                        fOutputTrajectory << " " << sin(vPart.z/vStrip.Rx) * (vStrip.Rx - (vPart.x + vOutPos));
                        fOutputTrajectory << " " << vPart.px/vPart.pz + vOutAng;
                        fOutputTrajectory << " " << vPart.py/vPart.pz;
                        fOutputTrajectory << std::endl;
                    }
                }
#endif
                
                if(saveParticle[j]->GetPositionVector()->GetZ() > saveStrip[j]->GetDimension()->GetZ()) bIntegrationEnd[j] = true;
            } while (bIntegrationEnd[j] != true);
            saveParticle[j]->PrintParticleOn(saveParticleOutgoing[j]);
            
#pragma omp critical
            {
                vRadius = saveStripCurvatureRadius[j]->GetX();
                vLength = saveStripDimension[j]->GetZ();
                vOutAng = saveOutgoingAngle[j]/vLength;
                vOutPos = saveOutgoingPosition[j];
                
                ECHARM_Particle_Save_Copy(saveParticleIncoming[j],vPartIn);
                ECHARM_Particle_Save_Copy(saveParticleOutgoing[j],vPartOut);
                vTree->Fill();
#ifdef bSaveTrajectory
                fOutputTrajectory << "***next_particle***" << std::endl;
#endif
            }
        }
        
#ifdef bPrintScreenNumberOfParticles
        if(fmod(i+1,bPrintScreenNumberOfParticles)==0){
            std::cout << " --- Time Elapsed (m): " << std::setw(10) << float(time(NULL) - vInitialTime)/60. << std::endl;
            std::cout << " --- Time Left    (m): " << std::setw(10) << (float(time(NULL) - vInitialTime)/(i)*(vNumberOfParticlesOMP) )/60. << std::endl;
        }
#endif
    }
    
    vRootFile->Write(); // write ROOT file
    vRootFile->Close(); // close ROOT file
    
    vParameterFile.open(vParameterFileName.c_str(),std::fstream::app);
    vParameterFile << "******************************" << std::endl;
    vParameterFile << "******** Job Finished ********" << std::endl;
    vParameterFile << "***** Total Elapsed Time *****" << std::endl;
    vParameterFile << "******************************" << std::endl;
    vParameterFile << "Time [m] = " <<  float(time(NULL) - vInitialTime)/60. << std::endl;
    vParameterFile.close();
    
#ifdef bSaveTrajectory
    fOutputTrajectory.close();
#endif
    
    return 0;
}
Exemplo n.º 12
0
void drawQGFraction(){

	const double PI = 3.14159;

	TChain *mix = new TChain("mixing_tree");
	mix->Add("/data/kurtjung/JetTrackCorr_skims/2p76TeV_MC_Pythia6/MergedPythia_withPartonFlavor.root");
	//mix->Add("/data/kurtjung/JetTrackCorr_skims/5TeV_MC_Pythia6/*");

	//double xsecs[11] = {5.335E-01, 3.378E-02, 3.778E-03, 4.412E-04, 6.147E-05, 1.018E-05, 2.477E-06, 6.160E-07, 1.088E-07, 3.216E-08, 0}; //pythia6 5.02 tev weights
    double xsecs[11] = {2.043e-01, 1.075E-02, 1.025E-03, 9.865E-05, 1.129E-05, 1.465E-06, 2.837E-07, 5.323E-08, 5.934e-09, 8.125e-10, 0}; //2.76 tev weights
	int recalculatedEntries[10] = {0,0,0,0,0,0,0,0,0,0};
	double pthatbins[11] = {15,30,50,80,120,170,220,280,370,460,9999};

	TFile *fout = new TFile("QGFrac_pythia6_2p76TeV.root","recreate");

	TH1D *quarkFracIncl = new TH1D("quarkFracIncl","",20,120,500); quarkFracIncl->Sumw2();
	TH1D *glueFracIncl = new TH1D("glueFracIncl","",20,120,500); glueFracIncl->Sumw2();
	TH1D *inclJets = new TH1D("inclJets","",20,120,500); inclJets->Sumw2();

	TH1D *quarkFracLead = new TH1D("quarkFracLead","",20,120,500); quarkFracLead->Sumw2();
	TH1D *glueFracLead = new TH1D("glueFracLead","",20,120,500); glueFracLead->Sumw2();
	TH1D *leadJets = new TH1D("leadJets","",20,120,500); leadJets->Sumw2();


	Int_t HBHENoiseFilterResultRun2Loose, pPAprimaryVertexFilter;
	vector<float> *calo_corrpt=0, *calo_jtphi=0;
	vector<int> *calo_refparton_flavor=0;
	float pthat;

	mix->SetBranchAddress("calo_corrpt",&calo_corrpt);
	mix->SetBranchAddress("calo_jtphi",&calo_jtphi);
	mix->SetBranchAddress("calo_refparton_flavor",&calo_refparton_flavor);
	mix->SetBranchAddress("pthat",&pthat);

	mix->SetBranchAddress("HBHENoiseFilterResultRun2Loose",&HBHENoiseFilterResultRun2Loose);
	mix->SetBranchAddress("pPAprimaryVertexFilter",&pPAprimaryVertexFilter);


	TH1D *pthatHisto = new TH1D("pthatHisto","",10,pthatbins);
	mix->Project("pthatHisto","pthat");
	for(int i=0; i<10; i++){
		recalculatedEntries[i] = pthatHisto->GetBinContent(i+1);
		cout << "entries between pthat " << pthatbins[i] << " and " << pthatbins[i+1] << ": " << recalculatedEntries[i] << endl;
		cout << "weight: " << (xsecs[i]-xsecs[i+1])/recalculatedEntries[i] <<endl;
	}

	int totEntries = mix->GetEntries();
	cout << "entries: "<< totEntries << endl;
	totEntries=100000;
	for(int ievt=0; ievt<totEntries; ievt++){
		mix->GetEntry(ievt);
		if(ievt && ievt%10000==0) cout << "entry: " << ievt << endl;

		//if(!HBHENoiseFilterResultRun2Loose || !pPAprimaryVertexFilter) continue;

		int ibin=0;
		double weight=0.;
		while(pthat>pthatbins[ibin]) ibin++;
		ibin--;
		weight = (xsecs[ibin]-xsecs[ibin+1])/recalculatedEntries[ibin];
		if(weight>1){ 
			cout << "xsec: "<< xsecs[ibin]-xsecs[ibin+1] << " entries: " << recalculatedEntries[ibin] << endl;
			cout << "pthat: "<< pthat << " bin " << ibin << endl;
		}
		
		for(unsigned int ijet=0; ijet<calo_corrpt->size(); ijet++){
			
			if(abs(calo_refparton_flavor->at(ijet))>0 && abs(calo_refparton_flavor->at(ijet))<6) quarkFracIncl->Fill(calo_corrpt->at(ijet), weight);
			if(abs(calo_refparton_flavor->at(ijet))==21){ glueFracIncl->Fill(calo_corrpt->at(ijet), weight); }
			inclJets->Fill(calo_corrpt->at(ijet), weight);

			if(ijet==0 && calo_corrpt->size()>1){
				double dphi = abs(calo_jtphi->at(0) - calo_jtphi->at(1));
				if(dphi>(7*PI/8.) && dphi<(9*PI/8.) && calo_corrpt->at(1)>50) {

					if(abs(calo_refparton_flavor->at(ijet))>0 && abs(calo_refparton_flavor->at(ijet))<6) quarkFracLead->Fill(calo_corrpt->at(ijet), weight);
					if(abs(calo_refparton_flavor->at(ijet))==21) glueFracLead->Fill(calo_corrpt->at(ijet), weight);
					leadJets->Fill(calo_corrpt->at(ijet), weight);

				}
			}
		}
	}

	//quarkFracLead->Divide(leadJets);
	//glueFracLead->Divide(leadJets);

	//quarkFracIncl->Divide(inclJets);
	//glueFracIncl->Divide(inclJets);

	fout->cd();

	formatHisto(quarkFracLead,1);
	formatHisto(glueFracLead,2);
	formatHisto(quarkFracIncl,4);
	formatHisto(glueFracIncl,8);

	quarkFracLead->Write();
	glueFracLead->Write();
	quarkFracIncl->Write();
	glueFracIncl->Write();
	leadJets->Write();
	inclJets->Write();

	fout->Close();

}
void createCorrectedBackgroundModel(std::string fileName, int nsidebands=6, bool makePlots=false, std::string defaultPrepend="CMS-HGG" ){

     if (makePlots){
       system("mkdir -p BMplots/ada");
       system("mkdir -p BMplots/grad");
       gStyle->SetPalette(1);
       gStyle->SetOptStat(0);
     }

     global_nMassBins=nsidebands;

     double massMin = 120;
     double massMax = 130;
     double dM  = 0.1;
	
     // Open the original Workspace
     TFile *in = TFile::Open(fileName.c_str(),"UPDATE");
     RooWorkspace *work = (RooWorkspace*)in->Get("cms_hgg_workspace");
 
     std::string types[2]={"grad","ada"};

     for (int ty=0;ty<2;ty++){

	std::string type = types[ty];
	// Create An output file for the TF1 Sideband Fits
  	std::string pathToFile=fileName.substr(0,fileName.find(defaultPrepend.c_str()));
 	std::string fName=fileName.substr(fileName.find(defaultPrepend.c_str()),fileName.size());
	TFile *out = new TFile(Form("%sbdtSidebandFits_%s_%s",pathToFile.c_str(),type.c_str(),fName.c_str()),"RECREATE");
	for (double mH=massMin;mH<=massMax;mH+=dM){

		//TH1F *originalHist      = (TH1F*) in->Get(Form("th1f_bkg_%s_%3.1f_cat0",type.c_str(),mH)); // This histogram is normalized to the inclusive fit (will not include VBF cat)
		RooRealVar *nSignalVar = (RooRealVar*)work->var(Form("NBkgInSignal_mH%3.1f",mH));
		TH1F *dataHist  = (TH1F*) in->Get(Form("th1f_data_%s_%3.1f_cat0",type.c_str(),mH)); // Data Histogram, includes VBF category
		int nBins = dataHist->GetNbinsX();

		// Want to make a "corrected" histogram 
		TH1F *correctedHist = new TH1F(Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr",type.c_str(),mH),Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr",type.c_str(),mH),nBins,0,nBins);		     
		TH1F *correctedHistFR = new TH1F(Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr_frac",type.c_str(),mH),Form("th1f_bkg_%s_%3.1f_cat0_fitsb_biascorr_frac",type.c_str(),mH),nBins,0,nBins);		     
      	        TH2F *hFCovar=new TH2F(Form("fCovar_%3.1f",mH),
			 Form("Fraction covariance matrix m %3.1f",mH),
			 nBins,0.0,nBins,nBins,0.0,nBins);
		TH2F *uCorrErr = new TH2F(Form("fUncorrErr_%s_%3.1f",type.c_str(),mH),
			 Form("Uncorrelated Errors m %3.1f",mH),
			 nBins,0.0,nBins,nBins,0.0,nBins);
	
		TDirectory *mass_dir = out->mkdir(Form("mH_%3.1f",mH));

		// For a given mass point, need to set up globals
		global_nBdtBins=nBins;		
		global_mH=mH;
		global_nSignalRegion=nSignalVar->getVal();

		fillData(mH,in,type);
		paulFit(mass_dir,correctedHistFR,correctedHist,hFCovar,makePlots,type);
		
		// Finally Get the uncorrleated errors from the covariance matrix
		diagonalizeMatrix(hFCovar,uCorrErr);

		std::cout << "Final Check of Normalizations at mH="<<mH <<std::endl;
		std::cout << "Original - "<< global_nSignalRegion <<  ", After - " <<correctedHist->Integral() <<std::endl;
		
		// Write out the Hists into the original File
		in->cd();
		correctedHist->Write(correctedHist->GetName(),TObject::kOverwrite);
		correctedHistFR->Write(correctedHistFR->GetName(),TObject::kOverwrite);
		//hFCovar->Write();
		uCorrErr->Write(uCorrErr->GetName(),TObject::kOverwrite);
    out->cd();
    mass_dir->cd();
    uCorrErr->Write(uCorrErr->GetName(),TObject::kOverwrite);

    if (makePlots){
      TCanvas *canv = new TCanvas();
      uCorrErr->SetMarkerColor(kGray);
      gPad->SetRightMargin(2.);
      uCorrErr->Draw("colz text");
      canv->Print(Form("BMplots/%s/uncorrErr_m%3.1f.png",type.c_str(),mH));
      canv->Print(Form("BMplots/%s/uncorrErr_m%3.1f.pdf",type.c_str(),mH));
    }
	}
	std::cout << "Saving Fits to file -> " << out->GetName() << std::endl;
        out->Close();
     }
    
    std::cout << "Updated (with corrected background model) -> " << in->GetName() << std::endl;
    in->Close();
}
void PlotDecisionBoundary( TString weightFile = "weights/TMVAClassification_BDT.weights.xml",TString v0="var0", TString v1="var1", TString dataFileName = "/home/hvoss/TMVA/TMVA_data/data/data_circ.root") 
{   
   //---------------------------------------------------------------
   // default MVA methods to be trained + tested

   // this loads the library
   TMVA::Tools::Instance();

   std::cout << std::endl;
   std::cout << "==> Start TMVAClassificationApplication" << std::endl;


   //
   // create the Reader object
   //
   TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );    

   // create a set of variables and declare them to the reader
   // - the variable names must corresponds in name and type to 
   // those given in the weight file(s) that you use
   Double_t var0, var1;
   reader->AddVariable( v0,                &var0 );
   reader->AddVariable( v1,                &var1 );

   //
   // book the MVA method
   //
   reader->BookMVA( "MyMVAMethod", weightFile ); 
   
   TFile *f = new TFile(dataFileName);
   TTree *signal     = (TTree*)f->Get("TreeS");
   TTree *background = (TTree*)f->Get("TreeB");


//Declaration of leaves types
   Float_t         svar0;
   Float_t         svar1;
   Float_t         bvar0;
   Float_t         bvar1;
   Float_t         sWeight=1.0; // just in case you have weight defined, also set these branchaddresses
   Float_t         bWeight=1.0*signal->GetEntries()/background->GetEntries(); // just in case you have weight defined, also set these branchaddresses

   // Set branch addresses.
   signal->SetBranchAddress(v0,&svar0);
   signal->SetBranchAddress(v1,&svar1);
   background->SetBranchAddress(v0,&bvar0);
   background->SetBranchAddress(v1,&bvar1);


   UInt_t nbin = 50;
   Float_t xmax = signal->GetMaximum(v0.Data());
   Float_t xmin = signal->GetMinimum(v0.Data());
   Float_t ymax = signal->GetMaximum(v1.Data());
   Float_t ymin = signal->GetMinimum(v1.Data());
 
   xmax = TMath::Max(xmax,(Float_t)background->GetMaximum(v0.Data()));  
   xmin = TMath::Min(xmin,(Float_t)background->GetMinimum(v0.Data()));
   ymax = TMath::Max(ymax,(Float_t)background->GetMaximum(v1.Data()));
   ymin = TMath::Min(ymin,(Float_t)background->GetMinimum(v1.Data()));


   TH2D *hs=new TH2D("hs","",nbin,xmin,xmax,nbin,ymin,ymax);   
   TH2D *hb=new TH2D("hb","",nbin,xmin,xmax,nbin,ymin,ymax);   
   hs->SetXTitle(v0);
   hs->SetYTitle(v1);
   hb->SetXTitle(v0);
   hb->SetYTitle(v1);
   hs->SetMarkerColor(4);
   hb->SetMarkerColor(2);


   TH2F * hist = new TH2F( "MVA",    "MVA",    nbin,xmin,xmax,nbin,ymin,ymax);

   // Prepare input tree (this must be replaced by your data source)
   // in this example, there is a toy tree with signal and one with background events
   // we'll later on use only the "signal" events for the test in this example.

   Float_t MinMVA=10000, MaxMVA=-100000;
   for (UInt_t ibin=1; ibin<nbin+1; ibin++){
      for (UInt_t jbin=1; jbin<nbin+1; jbin++){
         var0 = hs->GetXaxis()->GetBinCenter(ibin);
         var1 = hs->GetYaxis()->GetBinCenter(jbin);
         Float_t mvaVal=reader->EvaluateMVA( "MyMVAMethod" ) ;
         if (MinMVA>mvaVal) MinMVA=mvaVal;
         if (MaxMVA<mvaVal) MaxMVA=mvaVal;
         hist->SetBinContent(ibin,jbin, mvaVal);
      }
   }


   // now you need to try to find the MVA-value at which you cut for the plotting of the decision boundary
   // (Use the smallest number of misclassifications as criterion)
   const Int_t nValBins=100;
   Double_t    sum = 0.;
   TH1F *mvaS= new TH1F("mvaS","",nValBins,MinMVA,MaxMVA); mvaS->SetXTitle("MVA-ouput"); mvaS->SetYTitle("#entries");
   TH1F *mvaB= new TH1F("mvaB","",nValBins,MinMVA,MaxMVA); mvaB->SetXTitle("MVA-ouput"); mvaB->SetYTitle("#entries");
   TH1F *mvaSC= new TH1F("mvaSC","",nValBins,MinMVA,MaxMVA); mvaSC->SetXTitle("MVA-ouput"); mvaSC->SetYTitle("cummulation");
   TH1F *mvaBC= new TH1F("mvaBC","",nValBins,MinMVA,MaxMVA); mvaBC->SetXTitle("MVA-ouput"); mvaBC->SetYTitle("cummulation");

   Long64_t nentries;
   nentries = signal->GetEntries();
   for (Long64_t is=0; is<nentries;is++) {
      signal->GetEntry(is);
      sum +=sWeight;
      var0 = svar0;
      var1 = svar1;
      Float_t mvaVal=reader->EvaluateMVA( "MyMVAMethod" ) ;
      hs->Fill(svar0,svar1);
      mvaS->Fill(mvaVal,sWeight);
   }
   nentries = background->GetEntries();
   for (Long64_t ib=0; ib<nentries;ib++) {
      background->GetEntry(ib);
      sum +=bWeight;
      var0 = bvar0;
      var1 = bvar1;
      Float_t mvaVal=reader->EvaluateMVA( "MyMVAMethod" ) ;
      hb->Fill(bvar0,bvar1);
      mvaB->Fill(mvaVal,bWeight);
   }

   SeparationBase *sepGain = new MisClassificationError();
   //SeparationBase *sepGain = new GiniIndex();
   //SeparationBase *sepGain = new CrossEntropy();

   Double_t sTot = mvaS->GetSum();
   Double_t bTot = mvaB->GetSum();

   mvaSC->SetBinContent(1,mvaS->GetBinContent(1));
   mvaBC->SetBinContent(1,mvaB->GetBinContent(1));
   Double_t sSel=mvaSC->GetBinContent(1);
   Double_t bSel=mvaBC->GetBinContent(1);
   Double_t sSelBest=0;
   Double_t bSelBest=0;
   Double_t separationGain=sepGain->GetSeparationGain(sSel,bSel,sTot,bTot);
   Double_t mvaCut=mvaSC->GetBinCenter(1);
   Double_t mvaCutOrientation=1; // 1 if mva > mvaCut --> Signal and -1 if mva < mvaCut (i.e. mva*-1 > mvaCut*-1) --> Signal
   for (UInt_t ibin=2;ibin<nValBins;ibin++){ 
      mvaSC->SetBinContent(ibin,mvaS->GetBinContent(ibin)+mvaSC->GetBinContent(ibin-1));
      mvaBC->SetBinContent(ibin,mvaB->GetBinContent(ibin)+mvaBC->GetBinContent(ibin-1));
    
      sSel=mvaSC->GetBinContent(ibin);
      bSel=mvaBC->GetBinContent(ibin);

      if (separationGain < sepGain->GetSeparationGain(sSel,bSel,sTot,bTot)){
         separationGain = sepGain->GetSeparationGain(sSel,bSel,sTot,bTot);
         mvaCut=mvaSC->GetBinCenter(ibin);
         if (sSel/bSel > (sTot-sSel)/(bTot-bSel)) mvaCutOrientation=-1;
         else                                     mvaCutOrientation=1;
         sSelBest=sSel;
         bSelBest=bSel;
     }
   }
   

   cout << "Min="<<MinMVA << " Max=" << MaxMVA 
        << " sTot=" << sTot
        << " bTot=" << bTot
        << " sSel=" << sSelBest
        << " bSel=" << bSelBest
        << " sepGain="<<separationGain
        << " cut=" << mvaCut
        << " cutOrientation="<<mvaCutOrientation
        << endl;


   delete reader;

   gStyle->SetPalette(1);

  
   plot(hs,hb,hist     ,v0,v1,mvaCut);


   TCanvas *cm=new TCanvas ("cm","",900,1200);
   cm->cd();
   cm->Divide(1,2);
   cm->cd(1);
   mvaS->SetLineColor(4);
   mvaB->SetLineColor(2);
   mvaS->Draw();
   mvaB->Draw("same");

   cm->cd(2);
   mvaSC->SetLineColor(4);
   mvaBC->SetLineColor(2);
   mvaBC->Draw();
   mvaSC->Draw("same");

   // TH1F *add=(TH1F*)mvaBC->Clone("add");
   // add->Add(mvaSC);

   // add->Draw();

   // errh->Draw("same");

   //
   // write histograms
   //
   TFile *target  = new TFile( "TMVAPlotDecisionBoundary.root","RECREATE" );

   hs->Write();
   hb->Write();

   hist->Write();

   target->Close();

} 
Exemplo n.º 15
0
int BfinderAna(TString infile="/data/twang/BfinderRun2/DoubleMu/BfinderData_pp_20151130/finder_pp_merged.root", 
		TString outfile="test.root", 
		Bool_t REAL=false, 
		Bool_t isPbPb=false, 
		Int_t startEntries=0, 
		Int_t endEntries=-1,  
//		Int_t endEntries=100000,  
		Bool_t skim=true, 
		Bool_t gskim=true, 
		Bool_t checkMatching=true, 
		Bool_t iseos=false, 
		Bool_t SkimHLTtree=true)
{
	if(istest)
	{
//		infile="/store/group/phys_heavyions/HeavyFlavourRun2/BfinderRun2/MC/BJpsiMM_5p02TeV_TuneCUETP8M1/crab_BfinderMC_pp_BJpsiMM_5p02TeV_TuneCUETP8M1_20160613_bPt0jpsiPt0tkPt0p5_Bp/160612_195743/0000/finder_pp_62.root";
//		infile="/data/HeavyFlavourRun2/BfinderRun2/MC/crab_BfinderMC_pp_BJpsiMM_5p02TeV_TuneCUETP8M1_20160613_bPt0jpsiPt0tkPt0p5_Bp.root";
		infile="/data/HeavyFlavourRun2/BfinderRun2/MC/crab_BfinderMC_PbPb_Pythia8_BJpsiMM_ptJpsi_0_inf_Hydjet_MB_20160613_bPt5jpsiPt0tkPt0p8_Bp.root";
		outfile="test.root";
		REAL=false;
		isPbPb=false;
		skim=false;
		checkMatching=true;
//		iseos=true;
		iseos=false;
	}

	cout<<endl;
	if(REAL) cout<<"--- Processing - REAL DATA";
	else cout<<"--- Processing - MC";
	if(isPbPb) cout<<" - PbPb";
	else cout<<" - pp";
	cout<<endl;

	TString ifname;
	if(iseos) ifname = Form("root://eoscms.cern.ch//eos/cms%s",infile.Data());
	else ifname = infile;
	TFile* f = TFile::Open(ifname);
	TTree* root = (TTree*)f->Get("Bfinder/root");
	TTree* hltroot = (TTree*)f->Get("hltanalysis/HltTree");
	TTree* skimroot = (TTree*)f->Get("skimanalysis/HltTree");
	TTree* hiroot = (TTree*)f->Get("hiEvtAnalyzer/HiTree");

	EvtInfoBranches     *EvtInfo = new EvtInfoBranches;
	VtxInfoBranches     *VtxInfo = new VtxInfoBranches;
	MuonInfoBranches    *MuonInfo = new MuonInfoBranches;
	TrackInfoBranches   *TrackInfo = new TrackInfoBranches;
	BInfoBranches       *BInfo = new BInfoBranches;
	GenInfoBranches     *GenInfo = new GenInfoBranches;

	setHltBranch(hltroot);
	setHiTreeBranch(hiroot);

	EvtInfo->setbranchadd(root);
	VtxInfo->setbranchadd(root);
	MuonInfo->setbranchadd(root);
	TrackInfo->setbranchadd(root);
	BInfo->setbranchadd(root);
	GenInfo->setbranchadd(root);

	Long64_t nentries = root->GetEntries();
	if(endEntries>nentries || endEntries == -1) endEntries = nentries;
	TFile *outf = TFile::Open(Form("%s", outfile.Data()),"recreate");

	cout<<"--- Check the number of events for four trees"<<endl;
	cout<<root->GetEntries()<<" "<<hltroot->GetEntries()<<" "<<hiroot->GetEntries();
	cout<<" "<<skimroot->GetEntries()<<endl;
	cout<<endl;

	//
	double min = 4.6;
	double max = 6.0;
	TH1D* Bmass = new TH1D("Bmass","Bmass", 50, min, max);
	TH1D* Bmass_nosig = new TH1D("Bmass_nosig","Bmass_nosig", 50, min, max);
	TH1D* BmassBpPi = new TH1D("BmassBpPi","BmassBpPi", 50, min, max);
	TH1D* BmassBpXPi = new TH1D("BmassBpXPi","BmassBpXPi", 50, min, max);
	TH1D* BmassBpK = new TH1D("BmassBpK","BmassBpK", 50, min, max);
	TH1D* BmassB0K = new TH1D("BmassB0K","BmassB0K", 50, min, max);
	TH1D* BmassBpK_tkmatch = new TH1D("BmassBpK_tkmatch","BmassBpK_tkmatch", 50, min, max);
	TH1D* BmassB0K_tkmatch = new TH1D("BmassB0K_tkmatch","BmassB0K_tkmatch", 50, min, max);
	TH1D* BmassBpK_tknotmatch = new TH1D("BmassBpK_tknotmatch","BmassBpK_tknotmatch", 50, min, max);
	TH1D* BmassB0K_tknotmatch = new TH1D("BmassB0K_tknotmatch","BmassB0K_tknotmatch", 50, min, max);
	Bmass->SetMinimum(0);
	Bmass_nosig->SetMinimum(0); 
	BmassBpPi->SetMinimum(0); 
	BmassBpXPi->SetMinimum(0);
	BmassBpK->SetMinimum(0);
	BmassB0K->SetMinimum(0);
	BmassBpK_tkmatch->SetMinimum(0);
	BmassB0K_tkmatch->SetMinimum(0);
	BmassBpK_tknotmatch->SetMinimum(0);
	BmassB0K_tknotmatch->SetMinimum(0);

	std::map<int,int> BtypeCountBpK;
	std::map<int,int> BtypeCountB0K;
	cout<<"--- Processing events"<<endl;
	for(Int_t i=startEntries;i<endEntries;i++)
	{
		root->GetEntry(i);
		hltroot->GetEntry(i);
		skimroot->GetEntry(i);
		hiroot->GetEntry(i);

		if(i%100000==0) cout<<setw(7)<<i<<" / "<<endEntries<<endl;
		if(checkMatching)
		{
			if(((int)Bf_HLT_Event!=EvtInfo->EvtNo||(int)Bf_HLT_Run!=EvtInfo->RunNo||(int)Bf_HLT_LumiBlock!=EvtInfo->LumiNo) || 
					((int)Bf_HiTree_Evt!=EvtInfo->EvtNo||(int)Bf_HiTree_Run!=EvtInfo->RunNo||(int)Bf_HiTree_Lumi!=EvtInfo->LumiNo))
			{
				cout<<"Error: not matched "<<i<<" | (Hlt,Bfr,Hi) | ";
				cout<<"EvtNo("<<Bf_HLT_Event<<","<<EvtInfo->EvtNo<<","<<Bf_HiTree_Evt<<") ";
				cout<<"RunNo("<<Bf_HLT_Run<<","<<EvtInfo->RunNo<<","<<Bf_HiTree_Run<<") ";
				cout<<"LumiNo("<<Bf_HLT_LumiBlock<<","<<EvtInfo->LumiNo<<","<<Bf_HiTree_Lumi<<")"<<endl;
				continue;
			}
		}
		//Do oyur analysis here
		//example: checking GenInfo
	    for(int j=0;j<GenInfo->size;j++){
			if( int(GenInfo->pdgId[j]/100)%100 == 5){
//				cout<<GenInfo->pdgId[j]<<endl;
//				if(abs(GenInfo->pdgId[GenInfo->da1[j]]) == 443 || abs(GenInfo->pdgId[GenInfo->da2[j]]) == 443){
//					printDa(GenInfo, j, 1);
//				}
				if(abs(GenInfo->pdgId[j])==521)
				if(GenInfo->da1[j] != -1)
				if(abs(GenInfo->pdgId[GenInfo->da1[j]]) == 443)
				if(abs(GenInfo->pdgId[GenInfo->da2[j]]) == 211)
				{
					//printDa(GenInfo, j, 1);
				}

				if(abs(GenInfo->pdgId[j])==521)
				if(GenInfo->da1[j] != -1)
				if(abs(GenInfo->pdgId[GenInfo->da1[j]]) == 443)
				if((abs(GenInfo->pdgId[GenInfo->da2[j]])/100)%100 == 3)
				{
					//printDa(GenInfo, j, 1);
				}

				if(abs(GenInfo->pdgId[j])==511)
				if(GenInfo->da1[j] != -1)
				if(abs(GenInfo->pdgId[GenInfo->da1[j]]) == 443)
				if((abs(GenInfo->pdgId[GenInfo->da2[j]])/100)%100 == 3)
				{
					//printDa(GenInfo, j, 1);
				}
				
			}
		}

		bool isBsig = false;
		for(int j=0;j<BInfo->size;j++){
			int rtk1idx = BInfo->rftk1_index[j];
			int rtk2idx = BInfo->rftk2_index[j];
			int rmu1idx = BInfo->uj_rfmu1_index[BInfo->rfuj_index[j]];
			int rmu2idx = BInfo->uj_rfmu2_index[BInfo->rfuj_index[j]];
			int gtk1idx =  TrackInfo->geninfo_index[BInfo->rftk1_index[j]];
			int gtk2idx =  TrackInfo->geninfo_index[BInfo->rftk2_index[j]];
			int gmu1idx =  MuonInfo->geninfo_index[BInfo->uj_rfmu1_index[BInfo->rfuj_index[j]]];
			int gmu2idx =  MuonInfo->geninfo_index[BInfo->uj_rfmu2_index[BInfo->rfuj_index[j]]];

			//some recon cut
			bool cut = false;

			if(
			BInfo->mass[j] > min && BInfo->mass[j] < max && BInfo->pt[j] > 10 && BInfo->pt[j] < 1000
			&& fabs(BInfo->eta[j]) < 2.4
			){
				cut = true;
			}

//			if(
//			BInfo->mass[j] > min && BInfo->mass[j] < max && BInfo->pt[j] > 10 && BInfo->pt[j] < 1000
//			&&	((fabs(MuonInfo->eta[rmu1idx]) < 1.2 && MuonInfo->pt[rmu1idx] > 3.5) || (fabs(MuonInfo->eta[rmu1idx]) > 1.2 && fabs(MuonInfo->eta[rmu1idx]) < 2.1 && MuonInfo->pt[rmu1idx] > (5.77-1.8*fabs(MuonInfo->eta[rmu1idx]))) || (fabs(MuonInfo->eta[rmu1idx]) > 2.1 && fabs(MuonInfo->eta[rmu1idx]) < 2.4 && MuonInfo->pt[rmu1idx] > 1.8))
//			&&  MuonInfo->TMOneStationTight[rmu1idx] &&  MuonInfo->i_nPixelLayer[rmu1idx] > 0 && (MuonInfo->i_nPixelLayer[rmu1idx] + MuonInfo->i_nStripLayer[rmu1idx]) > 5 && MuonInfo->dxyPV[rmu1idx] < 0.3 && MuonInfo->dzPV[rmu1idx] < 20 && MuonInfo->isGlobalMuon[rmu1idx]
//			&&	((fabs(MuonInfo->eta[rmu2idx]) < 1.2 && MuonInfo->pt[rmu2idx] > 3.5) || (fabs(MuonInfo->eta[rmu2idx]) > 1.2 && fabs(MuonInfo->eta[rmu2idx]) < 2.1 && MuonInfo->pt[rmu2idx] > (5.77-1.8*fabs(MuonInfo->eta[rmu2idx]))) || (fabs(MuonInfo->eta[rmu2idx]) > 2.1 && fabs(MuonInfo->eta[rmu2idx]) < 2.4 && MuonInfo->pt[rmu2idx] > 1.8))
//			&&  MuonInfo->TMOneStationTight[rmu2idx] &&  MuonInfo->i_nPixelLayer[rmu2idx] > 0 && (MuonInfo->i_nPixelLayer[rmu2idx] + MuonInfo->i_nStripLayer[rmu2idx]) > 5 && MuonInfo->dxyPV[rmu2idx] < 0.3 && MuonInfo->dzPV[rmu2idx] < 20 && MuonInfo->isGlobalMuon[rmu2idx]
//			&& TrackInfo->highPurity[rtk1idx]
//			&& TrackInfo->pt[rtk1idx] > 1.0
//			&& fabs(TrackInfo->eta[rtk1idx]) < 2.4
//			&& fabs(BInfo->eta[j]) < 2.4
//			&& TMath::Prob(BInfo->vtxchi2[j],BInfo->vtxdof[j]) > 0.005
//			){
//				cut = true;
//			}

			if(!cut) continue;
		
		
			//identify B sig
			Bmass->Fill(BInfo->mass[j]);
			bool isBsig = false;
			if(gmu1idx != -1 && gmu2idx != -1)
			if(abs(GenInfo->pdgId[gmu1idx]) == 13 && abs(GenInfo->pdgId[gmu2idx]) == 13)
			if((GenInfo->mo1[gmu1idx]) != -1 && (GenInfo->mo1[gmu2idx]) != -1 && GenInfo->mo1[gmu1idx] == GenInfo->mo1[gmu2idx])
			if(abs(GenInfo->pdgId[GenInfo->mo1[gmu1idx]]) == 443 && abs(GenInfo->pdgId[GenInfo->mo1[gmu2idx]]) == 443)
			if(GenInfo->mo1[GenInfo->mo1[gmu1idx]] != -1)
			if(gtk1idx != -1)
			if(GenInfo->mo1[gtk1idx] != -1)
			if(GenInfo->mo1[gtk1idx] == GenInfo->mo1[GenInfo->mo1[gmu1idx]] && abs(GenInfo->pdgId[GenInfo->mo1[gtk1idx]]) == 521 && abs(GenInfo->pdgId[gtk1idx]) == 321)
				isBsig = true;
			if(!isBsig) Bmass_nosig->Fill(BInfo->mass[j]);

			//identify jpsi + ?
			if(gmu1idx != -1 && gmu2idx != -1)
				if(abs(GenInfo->pdgId[gmu1idx]) == 13 && abs(GenInfo->pdgId[gmu2idx]) == 13)
					if((GenInfo->mo1[gmu1idx]) != -1 && (GenInfo->mo1[gmu2idx]) != -1 && GenInfo->mo1[gmu1idx] == GenInfo->mo1[gmu2idx])
						if(abs(GenInfo->pdgId[GenInfo->mo1[gmu1idx]]) == 443 && abs(GenInfo->pdgId[GenInfo->mo1[gmu2idx]]) == 443)
						{
							int mmu1idx = GenInfo->mo1[gmu1idx];
							int mmu2idx = GenInfo->mo1[gmu2idx];
							int mjpsiidx = GenInfo->mo1[mmu1idx];
							//B+ to jpsi pi+
							if(gtk1idx != -1){
								int mtk1idx = GenInfo->mo1[gtk1idx];
								if(mtk1idx != 1){
									int mtk1pdg = GenInfo->pdgId[mtk1idx];
									int tk1pdg = GenInfo->pdgId[gtk1idx];
									if(mtk1idx == mjpsiidx && abs(mtk1pdg) == 521 && abs(tk1pdg) == 211){
										if(gtk1idx == GenInfo->da2[mtk1idx]){
											//cout<<"-----"<<endl;
											//printDa(GenInfo, mtk1idx, 1);
											//cout<<"-----"<<endl;
											//printDa(GenInfo, mtk1idx, 1);
											//cout<<"Bmass: "<<BInfo->mass[j]<<endl;
											BmassBpPi->Fill(BInfo->mass[j]);
										}
										else{
											//printDa(GenInfo, mtk1idx, 1);
											//cout<<"Bmass: "<<BInfo->mass[j]<<endl;
											BmassBpXPi->Fill(BInfo->mass[j]);
										}
									}
								}
								//B+ to jpsi K 
								if(abs(GenInfo->pdgId[GenInfo->mo1[mmu1idx]]) == 521){
									int bidx = GenInfo->mo1[mmu1idx];
									int bda2idx = GenInfo->da2[bidx]; 
									int bda2pdg = GenInfo->pdgId[bda2idx];
									int tkancestor = getBAncestor(GenInfo, gtk1idx, 521);
									/*
									if(tkancestor != -1){
									cout<<"tk1 pt: "<<GenInfo->pt[gtk1idx]<<endl;
									cout<<"tk1anc: "<<tkancestor<<endl;
									cout<<"tk1anc pdg: "<<GenInfo->pdgId[tkancestor]<<endl;
									cout<<"bidx: "<<bidx<<endl;
                                    printDa(GenInfo, tkancestor, 1);
									}*/
									if((abs(bda2pdg)/100)%100==3
									&& abs(bda2pdg) != 321 
									){
										//printDa(GenInfo, bidx, 1);
										//cout<<"Bmass: "<<BInfo->mass[j]<<endl;
										BmassBpK->Fill(BInfo->mass[j]);
										if(tkancestor == bidx){
											BmassBpK_tkmatch->Fill(BInfo->mass[j]);
										}
										else{BmassBpK_tknotmatch->Fill(BInfo->mass[j]);}

										if(BtypeCountBpK.find(abs(bda2pdg)) == BtypeCountBpK.end()){
											BtypeCountBpK[abs(bda2pdg)] = 1;
										}
										else{
											BtypeCountBpK[abs(bda2pdg)] += 1;
										}
									}
								}

								//B0 to jpsi K 
								if(abs(GenInfo->pdgId[GenInfo->mo1[mmu1idx]]) == 511){
									int bidx = GenInfo->mo1[mmu1idx];
									int bda2idx = GenInfo->da2[bidx]; 
									int bda2pdg = GenInfo->pdgId[bda2idx];
									int tkancestor = getBAncestor(GenInfo, gtk1idx, 511);
									if((abs(bda2pdg)/100)%100==3){
										//printDa(GenInfo, bidx, 1);
										//cout<<"Bmass: "<<BInfo->mass[j]<<endl;
										BmassB0K->Fill(BInfo->mass[j]);
										if(tkancestor == bidx){
											BmassB0K_tkmatch->Fill(BInfo->mass[j]);
										}
										else{BmassB0K_tknotmatch->Fill(BInfo->mass[j]);}

										if(BtypeCountB0K.find(abs(bda2pdg)) == BtypeCountB0K.end()){
											BtypeCountB0K[abs(bda2pdg)] = 1;
										}
										else{
											BtypeCountB0K[abs(bda2pdg)] += 1;
										}
									}
								}
							}

						}
		}
		//

	}
	cout<<"Bp + K type count========="<<endl;
	std::map<int,int>::iterator BtypeCountBpKIt;
	for(BtypeCountBpKIt = BtypeCountBpK.begin(); BtypeCountBpKIt != BtypeCountBpK.end(); BtypeCountBpKIt++){
		cout<<"Ktype: "<<BtypeCountBpKIt->first<<" Count: "<<BtypeCountBpKIt->second<<endl;
	}

	cout<<"B0 + K type count========="<<endl;
	std::map<int,int>::iterator BtypeCountB0KIt;
	for(BtypeCountB0KIt = BtypeCountB0K.begin(); BtypeCountB0KIt != BtypeCountB0K.end(); BtypeCountB0KIt++){
		cout<<"Ktype: "<<BtypeCountB0KIt->first<<" Count: "<<BtypeCountB0KIt->second<<endl;
	}
	outf->Write();
	cout<<"--- Writing finished"<<endl;
	outf->Close();

	cout<<"--- In/Output files"<<endl;
	cout<<ifname<<endl;
	cout<<outfile<<endl;
	cout<<endl;

	return 1;
}
Exemplo n.º 16
0
void addBranches(string filename = "Bsphiphi")
{
  double m_K = 0.493677;
  int nphi = count(filename, "phi");
  int nBs = count(filename, "Bs");
  cout << "Adding branches to " << filename << endl;
/*Input************************************************************************/
  // Open the input file and create the output file
  TFile* infile  = TFile::Open((filename+".root"   ).c_str()),
       * outfile = TFile::Open((filename+"_branches.root").c_str(),"RECREATE");
  // Get the input tree and create an empty output tree
  TTree* intree  = GetTree(infile),
       * outtree = intree->CloneTree(0);
  // Read the number of events in the input file
  Int_t n = intree->GetEntries();
  TLorentzVector Kp_0_P, Km_0_P, Kp_1_P, Km_1_P, phi_P, KK_P;
  double m_b, m_phi, m_kk;
  double M_B, M_PHI, M_KK, M_phiKp, M_phiKm;
  double Kp_0_PX, Km_0_PX, Kp_1_PX, Km_1_PX;
  double Kp_0_PY, Km_0_PY, Kp_1_PY, Km_1_PY;
  double Kp_0_PZ, Km_0_PZ, Kp_1_PZ, Km_1_PZ;
  intree->SetBranchAddress("Kp_0_PX_TRUE",&Kp_0_PX);
  intree->SetBranchAddress("Kp_0_PY_TRUE",&Kp_0_PY);
  intree->SetBranchAddress("Kp_0_PZ_TRUE",&Kp_0_PZ);
  intree->SetBranchAddress("Km_0_PX_TRUE",&Km_0_PX);
  intree->SetBranchAddress("Km_0_PY_TRUE",&Km_0_PY);
  intree->SetBranchAddress("Km_0_PZ_TRUE",&Km_0_PZ);
  if(nBs == 1)
  {
    intree->SetBranchAddress("Bs0_0_M_TRUE",&m_b);
    intree->SetBranchAddress("Kp_1_PX_TRUE",&Kp_1_PX);
    intree->SetBranchAddress("Kp_1_PY_TRUE",&Kp_1_PY);
    intree->SetBranchAddress("Kp_1_PZ_TRUE",&Kp_1_PZ);
    intree->SetBranchAddress("Km_1_PX_TRUE",&Km_1_PX);
    intree->SetBranchAddress("Km_1_PY_TRUE",&Km_1_PY);
    intree->SetBranchAddress("Km_1_PZ_TRUE",&Km_1_PZ);
    outtree->Branch("B_s0_M",&M_B);
    outtree->Branch("KK_M",&M_KK);
    outtree->Branch("phiKplusM",&M_phiKm);
    outtree->Branch("phiKminusM",&M_phiKp);
    cout << "Creating branch B_s0_M" << endl;
    cout << "Creating branch KK_M" << endl;
    cout << "Creating branch phiKplusM" << endl;
    cout << "Creating branch phiKminusM" << endl;
  }
  outtree->Branch("phi_1020_M",&M_PHI);
  cout << "Creating branch phi_1020_M" << endl;
  if(nphi>0)
  {
    intree->SetBranchAddress("phi_0_M_TRUE",&m_phi);
    cout << "Can just read the branch phi_0_M" << endl;
  }
  if(nphi==2)
  {
    intree->SetBranchAddress("phi_1_M_TRUE",&m_kk);
    cout << "Can just read the branch phi_1_M" << endl;
  }
/*Event loop*******************************************************************/
  for(Int_t i = 0; i < n; i++)
  {
    intree->GetEntry(i);
    if(nBs == 1)
    {
//      M_B = m_b*1e3;
      Kp_0_P.SetXYZM(Kp_0_PX,Kp_0_PY,Kp_0_PZ,m_K);
      Km_0_P.SetXYZM(Km_0_PX,Km_0_PY,Km_0_PZ,m_K);
      Kp_1_P.SetXYZM(Kp_1_PX,Kp_1_PY,Kp_1_PZ,m_K);
      Km_1_P.SetXYZM(Km_1_PX,Km_1_PY,Km_1_PZ,m_K);
      M_B = (Kp_0_P+Km_0_P+Kp_1_P+Km_1_P).M()*1e3;
      M_phiKp = (Kp_0_P+Km_0_P+Kp_1_P).M()*1e3;
      M_phiKm = (Kp_0_P+Km_0_P+Km_1_P).M()*1e3;
      switch(nphi)
      {
        case 0:
          M_PHI = (Kp_0_P+Km_0_P).M()*1e3;
          M_KK = (Kp_1_P+Km_1_P).M()*1e3;
          break;
        case 1:
          M_PHI = m_phi*1e3;
          M_KK = (Kp_1_P+Km_1_P).M()*1e3;
          break;
        case 2:
          M_PHI = m_phi*1e3;
          M_KK = m_kk*1e3;
      }
    }
    else
    {
      M_PHI = m_phi*1e3;
    }
/*Fill tree********************************************************************/
    outtree->Fill();
    if(i%100000 == 0)
      cout << "Event " << i << "/" << n << endl;
  }
/*Write the output*************************************************************/
  outtree->Write();
  infile->Close();
  outfile->Close();
  return;
}
Exemplo n.º 17
0
void ensembleTest()
{
    // open log file
    BCLog::OpenLog("log.txt", BCLog::detail, BCLog::detail);

    // ---- read histograms from a file ---- //

    // open file
    std::string fname = "templates.root";
    TFile* file = TFile::Open(fname.data(), "READ");

    // check if file is open
    if (!file || !file->IsOpen()) {
        BCLog::OutError(Form("Could not open file %s.", fname.c_str()));
        BCLog::OutError("Run macro CreateHistograms.C in Root to create the file.");
        return;
    }

    // read histograms
    TH1D* hist_bkg1  = (TH1D*)file->Get("hist_bkg1");    // background template for channel 1
    TH1D* hist_bkg2  = (TH1D*)file->Get("hist_bkg2");    // background template for channel 2
    TH1D* hist_sgn1  = (TH1D*)file->Get("hist_sgn1");    // signal template for channel 1
    TH1D* hist_sgn2  = (TH1D*)file->Get("hist_sgn2");    // signal template for channel 2
    TH1D* hist_data1 = (TH1D*)file->Get("hist_data1");  // data for channel 1
    TH1D* hist_data2 = (TH1D*)file->Get("hist_data2");  // data for channel 2

    if (!hist_bkg1 || !hist_bkg2 || !hist_sgn1 || !hist_sgn2 || !hist_data1 || !hist_data2) {
        BCLog::OutError("Could not find data histograms");
        return;
    }

    // ---- perform fitting ---- //

    // create new fitter object
    BCMTF* m = new BCMTF("MyModel");

    // set Metropolis as marginalization method
    m->SetMarginalizationMethod(BCIntegrate::kMargMetropolis);

    // set the required precision of the MCMC (kLow, kQuick, kMedium, kHigh)
    // the higher the precision the longer the MCMC run
    m->SetPrecision(BCEngineMCMC::kQuick);

    // add channels
    m->AddChannel("channel1");
    m->AddChannel("channel2");

    // add processes
    m->AddProcess("background_channel1", 700., 900.);
    m->AddProcess("background_channel2", 300., 700.);
    m->AddProcess("signal",                0., 400.);

    // set data
    m->SetData("channel1", *hist_data1);
    m->SetData("channel2", *hist_data2);

    // set template and histograms
    // note: the process "background_channel2" is ignored in channel 1
    m->SetTemplate("channel1", "signal", *hist_sgn1, 0.5);
    m->SetTemplate("channel1", "background_channel1", *hist_bkg1, 1.0);
    // m->SetTemplate("channel1", "background_channel2", *hist_bkg1, 0.0);

    // note: the process "background_channel1" is ignored in channel 2
    m->SetTemplate("channel2", "signal", *hist_sgn2, 1.0);
    m->SetTemplate("channel2", "background_channel2", *hist_bkg2, 1.0);
    // m->SetTemplate("channel2", "background_channel1", *hist_bkg2, 0.0);

    // set priors
    m->GetParameter("background_channel1").SetPrior(new BCGaussianPrior(800, 10));
    m->GetParameter("background_channel2").SetPrior(new BCGaussianPrior(500, 50));
    m->GetParameter("signal").SetPriorConstant();

    // run MCMC
    m->MarginalizeAll();

    // find global mode
    m->FindMode( m->GetBestFitParameters() );

    // print all marginalized distributions
    m->PrintAllMarginalized("marginalized.pdf");

    // print results of the analysis into a text file
    m->PrintSummary();

    // print templates and stacks
    for (int i = 0; i < m->GetNChannels(); ++i) {
        BCMTFChannel* channel = m->GetChannel(i);
        channel->PrintTemplates(channel->GetName() + "_templates.pdf");
        m->PrintStack(i, m->GetBestFitParameters(), channel->GetName() + "_stack.pdf");
    }

    // ---- perform ensemble tests ---- //

    // create new analysis facility
    BCMTFAnalysisFacility* facility = new BCMTFAnalysisFacility(m);

    // settings
    facility->SetFlagMarginalize(false);

    // open new file
    file = TFile::Open("ensembles.root", "RECREATE");
    file->cd();

    // create ensembles
    TTree* tree = facility->BuildEnsembles( m->GetBestFitParameters(), 2000 );

    // run ensemble test
    TTree* tree_out = facility->PerformEnsembleTest(tree, 2000);

    // write trees into file
    tree->Write();
    tree_out->Write();

    // close file
    file->Close();

    // free memory
    delete file;

    // ---- clean up ---- //

    // free memory
    delete m;
}
Exemplo n.º 18
0
int main(int argc, char* argv[]){
  setstyle();

  char inputFileName[400];
  char outputFileName[400];
  
  if ( argc < 2 ){
    cout << "Error at Input: please specify an input .root file";
    cout << " and an (optional) output filename" << endl;
    cout << "Example:   ./Calibrate_xADC input_file.root" << endl;
    cout << "Example:   ./Calibrate_xADC input_file.root -o output_file.root" << endl;
    return 1;
  }

  sscanf(argv[1],"%s", inputFileName);
  bool user_output = false;
  for (int i=0;i<argc;i++){
    if (strncmp(argv[i],"-o",2)==0){
      sscanf(argv[i+1],"%s", outputFileName);
      user_output = true;
    }
  }

  string output_name;
  if(!user_output){
    string input_name = string(inputFileName);
    // strip path from input name
    while(input_name.find("/") != string::npos)
      input_name.erase(input_name.begin(),
		       input_name.begin()+
		       input_name.find("/")+1);
    if(input_name.find(".root") != string::npos)
      input_name.erase(input_name.find(".root"),5);
    output_name = input_name+"_xADCcalib.root";
    sprintf(outputFileName,"%s.root",inputFileName);
  } else {
    output_name = string(outputFileName);
  }

  TChain* tree = new TChain("xADC_fit");
  tree->AddFile(inputFileName);

  xADCfitBase* base = new xADCfitBase(tree);

  int N = tree->GetEntries();
  if(N == 0) return 0;

  map<pair<int,int>, int> MMFE8VMM_to_index;
  
  vector<int>             vMMFE8;  // board ID
  vector<int>             vVMM;    // VMM number
  vector<vector<double> > vmeanQ;
  vector<vector<double> > vmeanQerr;
  vector<vector<double> > vDAC;

  int MMFE8;
  int VMM;

  for(int i = 0; i < N; i++){
    base->GetEntry(i);

    MMFE8 = base->MMFE8;
    VMM   = base->VMM;

    // add a new MMFE8+VMM combination 
    if(MMFE8VMM_to_index.count(pair<int,int>(MMFE8,VMM)) == 0){
      int ind = int(vMMFE8.size());
      MMFE8VMM_to_index[pair<int,int>(MMFE8,VMM)] = ind;
      vMMFE8.push_back(MMFE8);
      vVMM.push_back(VMM);
      vmeanQ.push_back(vector<double>());
      vmeanQerr.push_back(vector<double>());
      vDAC.push_back(vector<double>());
    }

    // MMFE8+VMM index
    int index = MMFE8VMM_to_index[pair<int,int>(MMFE8,VMM)];

    vDAC[index].push_back(base->DAC);
    vmeanQ[index].push_back(base->meanQ);
    vmeanQerr[index].push_back(base->meanQerr);
  }

  int Nindex = vMMFE8.size();

  vector<TGraphErrors*> vgraph;
  vector<double> vsigma;
  vector<double> vQmin;
  for(int index = 0; index < Nindex; index++){
    int Npoint = vDAC[index].size();
    double DAC[Npoint];
    double meanQ[Npoint];
    double meanQerr[Npoint];
    double sigma = 0.;

    double Qmin = -1.;
    for(int p = 0; p < Npoint; p++){
      DAC[p] = vDAC[index][p];
      meanQ[p] = vmeanQ[index][p];
      meanQerr[p] = vmeanQerr[index][p];
      // if(meanQerr[p] > sigma)
      // 	sigma = meanQerr[p];
      sigma += meanQerr[p]/double(Npoint);

      if(meanQ[p] < Qmin || Qmin < 0.)
	Qmin = meanQ[p];
    }

    vgraph.push_back(new TGraphErrors(Npoint, DAC, meanQ, 0, meanQerr));
    vsigma.push_back(sigma);
    vQmin.push_back(Qmin);
  }

  TFile* fout = new TFile(output_name.c_str(), "RECREATE");

  // write xADCBase tree to outputfile
  //TChain* base_tree = new TChain("xADC_data");
  //base_tree->AddFile(inputFileName);
  //TTree* new_base_tree = base_tree->CloneTree();
  //fout->cd();
  //new_base_tree->Write();

  // add plots of charge v DAC for each
  // MMFE8+VMM combo to output file
  fout->mkdir("xADCfit_plots");
  fout->cd("xADCfit_plots");
  for(int i = 0; i < Nindex; i++){
    char stitle[50];
    sprintf(stitle, "Board #%d, VMM #%d", vMMFE8[i], vVMM[i]);
    char scan[50];
    sprintf(scan, "c_xADXfit_Board%d_VMM%d", vMMFE8[i], vVMM[i]);
    TCanvas* can = Plot_Graph(scan, vgraph[i], "Test Pulse DAC", "Input Charge (fC)", stitle);
    can->Write();
    delete can;
  }
  fout->cd("");

  // write xADCfitBase tree to outputfile
  TTree* newtree = tree->CloneTree();
  fout->cd();
  newtree->Write();
  delete newtree;
  delete base;
  delete tree;

  // Output xADC calib tree
  double calib_MMFE8;
  double calib_VMM;
  double calib_sigma;
  double calib_c0;
  double calib_A2;
  double calib_t02;
  double calib_d21;
  double calib_chi2;
  double calib_prob;
  
  TTree* calib_tree = new TTree("xADC_calib", "xADC_calib");
  calib_tree->Branch("MMFE8", &calib_MMFE8);
  calib_tree->Branch("VMM", &calib_VMM);
  calib_tree->Branch("sigma", &calib_sigma);
  calib_tree->Branch("c0", &calib_c0);
  calib_tree->Branch("A2", &calib_A2);
  calib_tree->Branch("t02", &calib_t02);
  calib_tree->Branch("d21", &calib_d21);
  calib_tree->Branch("chi2", &calib_chi2);
  calib_tree->Branch("prob", &calib_prob);

  // Perform fits on each vector of 
  // charge v DACMMFE8+VMM graphs
  fout->mkdir("xADCcalib_plots");
  fout->cd("xADCcalib_plots");

  vector<TF1*> vfunc;

  for(int index = 0; index < Nindex; index++){
    char fname[50];
    sprintf(fname, "funcP0P2P1_MMFE8-%d_VMM-%d", 
	    vMMFE8[index], vVMM[index]);
    int ifunc = vfunc.size();
    vfunc.push_back(new TF1(fname, P0_P2_P1, 0., 400., 4));

    vfunc[ifunc]->SetParName(0, "c_{0}");
    //vfunc[ifunc]->SetParameter(0, 20.);
    vfunc[ifunc]->SetParameter(0, vQmin[index]);
    vfunc[ifunc]->SetParName(1, "A_{2}");
    vfunc[ifunc]->SetParameter(1, 0.003);
    vfunc[ifunc]->SetParName(2, "t_{0 , 2}");
    vfunc[ifunc]->SetParameter(2, 50.);
    vfunc[ifunc]->SetParName(3, "d_{2 , 1}");
    vfunc[ifunc]->SetParameter(3, 50.);
    
    vfunc[ifunc]->SetParLimits(3, 0., 10000.);
    
    vgraph[index]->Fit(fname, "EQ");

    char stitle[50];
    sprintf(stitle, "Board #%d, VMM #%d", vMMFE8[index], vVMM[index]);
    char scan[50];
    sprintf(scan, "c_xADXcalib_Board%d_VMM%d", vMMFE8[index], vVMM[index]);
    TCanvas* can = Plot_Graph(scan, vgraph[index], "Test Pulse DAC", "Input Charge (fC)", stitle);
    can->Write();
    delete can;

   calib_MMFE8 = vMMFE8[index];
   calib_VMM = vVMM[index];
   calib_sigma = vsigma[index];
   calib_c0 = vfunc[ifunc]->GetParameter(0);
   calib_A2 = vfunc[ifunc]->GetParameter(1);
   calib_t02 = vfunc[ifunc]->GetParameter(2);
   calib_d21 = vfunc[ifunc]->GetParameter(3);
   calib_chi2 = vfunc[ifunc]->GetChisquare();
   calib_prob = vfunc[ifunc]->GetProb();

   calib_tree->Fill();
  }
  fout->cd("");

  // Write calib_tree to output file
  fout->cd("");
  calib_tree->Write();
  fout->Close();
}
void plotVBFVHReweighted(){
  gROOT->ProcessLine(".x tdrstyle.cc");
  gStyle->SetOptStat(0);

  TString INPUT_NAME = "HtoZZ4l_Phantom_125p6_VHDistributions_GenLevel.root";
  TString OUTPUT_NAME = "HtoZZ4l_Phantom_125p6_VHReweightingPlots_GenLevel.root";

  double mPOLE = 125.6;
  float ZZMass_PeakCut[2] ={ 125.1, 126.1 }; // Spin 0 analysis

  float templateWeight = 1;
  float GenDiJetMass;
  float MC_weight;
  float ZZMass = 0;

  TString coutput_common = user_TemplateswithTrees_dir + "../VHContributions/Plots/GenLevel/";
  gSystem->Exec("mkdir -p " + coutput_common);
  TString coutput = coutput_common + OUTPUT_NAME;
  TFile* foutput = new TFile(coutput, "recreate");

  const int kNumTemplates = 3;
  TString templatetitles[kNumTemplates] ={ "VBF Sig", "VBF Bkg", "VBF Int" };
  TString templatenames[kNumTemplates] ={ "VBF_Sig", "VBF_Bkg", "VBF_Int" };
  TH1F* hVBF_onshell_LC[kNumTemplates] ={ 0 };
  TH1F* hVBF_offshell_LC[kNumTemplates] ={ 0 };
  TH1F* hVBF_onshell_scaled[kNumTemplates] ={ 0 };
  TH1F* hVBF_offshell_scaled[kNumTemplates] ={ 0 };
  TH1F* hVBF_onshell_scaled_wVBF[kNumTemplates] ={ 0 };
  TH1F* hVBF_offshell_scaled_wVBF[kNumTemplates] ={ 0 };

  for (int erg_tev=7; erg_tev<=8; erg_tev++){
    for (int folder=0; folder<3; folder++){
      TString comstring;
      comstring.Form("%i", erg_tev);
      TString erg_dir;
      erg_dir.Form("LHC_%iTeV/", erg_tev);
      int EnergyIndex = 1;
      if (erg_tev == 7) EnergyIndex = 0;
      TString cinput_common = user_TemplateswithTrees_dir + "../VHContributions/" + erg_dir;
      cinput_common += user_folder[folder] + "/";
      TString cinput = cinput_common + INPUT_NAME;
      TFile* finput = new TFile(cinput, "read");
      if (finput->IsZombie()){
        delete finput;
        continue;
      }
      else if (finput==0) continue;

      cout << "Opened file " << finput->GetName() << endl;
      for (int tr=0; tr<kNumTemplates; tr++){
        TString templatename = "VBF_";
        templatename += templatenames[tr];

        TH1F* hVBF_onshell_LC_temp = (TH1F*)finput->Get(Form("%s_onshell_LC", templatename.Data()));
        TH1F* hVBF_offshell_LC_temp = (TH1F*)finput->Get(Form("%s_offshell_LC", templatename.Data()));
        TH1F* hVBF_onshell_scaled_temp = (TH1F*)finput->Get(Form("%s_onshell_scaled", templatename.Data()));
        TH1F* hVBF_offshell_scaled_temp = (TH1F*)finput->Get(Form("%s_offshell_scaled", templatename.Data()));
        TH1F* hVBF_onshell_scaled_wVBF_temp = (TH1F*)finput->Get(Form("%s_onshell_scaled_wVBF", templatename.Data()));
        TH1F* hVBF_offshell_scaled_wVBF_temp = (TH1F*)finput->Get(Form("%s_offshell_scaled_wVBF", templatename.Data()));

        foutput->cd();
        gStyle->SetOptStat(0);
        if (hVBF_onshell_LC[tr]==0) hVBF_onshell_LC[tr] = (TH1F*)hVBF_onshell_LC_temp->Clone(Form("%s_clone", hVBF_onshell_LC_temp->GetName()));
        else hVBF_onshell_LC[tr]->Add(hVBF_onshell_LC_temp);
        delete hVBF_onshell_LC_temp;

        if (hVBF_onshell_scaled[tr]==0) hVBF_onshell_scaled[tr] = (TH1F*)hVBF_onshell_scaled_temp->Clone(Form("%s_clone", hVBF_onshell_scaled_temp->GetName()));
        else hVBF_onshell_scaled[tr]->Add(hVBF_onshell_scaled_temp);
        delete hVBF_onshell_scaled_temp;

        if (hVBF_onshell_scaled_wVBF[tr]==0) hVBF_onshell_scaled_wVBF[tr] = (TH1F*)hVBF_onshell_scaled_wVBF_temp->Clone(Form("%s_clone", hVBF_onshell_scaled_wVBF_temp->GetName()));
        else hVBF_onshell_scaled_wVBF[tr]->Add(hVBF_onshell_scaled_wVBF_temp);
        delete hVBF_onshell_scaled_wVBF_temp;

        if (hVBF_offshell_LC[tr]==0) hVBF_offshell_LC[tr] = (TH1F*)hVBF_offshell_LC_temp->Clone(Form("%s_clone", hVBF_offshell_LC_temp->GetName()));
        else hVBF_offshell_LC[tr]->Add(hVBF_offshell_LC_temp);
        delete hVBF_offshell_LC_temp;

        if (hVBF_offshell_scaled[tr]==0) hVBF_offshell_scaled[tr] = (TH1F*)hVBF_offshell_scaled_temp->Clone(Form("%s_clone", hVBF_offshell_scaled_temp->GetName()));
        else hVBF_offshell_scaled[tr]->Add(hVBF_offshell_scaled_temp);
        delete hVBF_offshell_scaled_temp;

        if (hVBF_offshell_scaled_wVBF[tr]==0) hVBF_offshell_scaled_wVBF[tr] = (TH1F*)hVBF_offshell_scaled_wVBF_temp->Clone(Form("%s_clone", hVBF_offshell_scaled_wVBF_temp->GetName()));
        else hVBF_offshell_scaled_wVBF[tr]->Add(hVBF_offshell_scaled_wVBF_temp);
        delete hVBF_offshell_scaled_wVBF_temp;
      }
      finput->Close();
    }
  }

  TH1F* hVBF_sig[2][3]={
    { hVBF_onshell_LC[0], hVBF_onshell_scaled[0], hVBF_onshell_scaled_wVBF[0] },
    { hVBF_offshell_LC[0], hVBF_offshell_scaled[0], hVBF_offshell_scaled_wVBF[0] }
  };
  TH1F* hVBF_bkg[2][3]={
    { hVBF_onshell_LC[1], hVBF_onshell_scaled[1], hVBF_onshell_scaled_wVBF[1] },
    { hVBF_offshell_LC[1], hVBF_offshell_scaled[1], hVBF_offshell_scaled_wVBF[1] }
  };
  TH1F* hVBF_int[2][3]={
    { hVBF_onshell_LC[2], hVBF_onshell_scaled[2], hVBF_onshell_scaled_wVBF[2] },
    { hVBF_offshell_LC[2], hVBF_offshell_scaled[2], hVBF_offshell_scaled_wVBF[2] }
  };
  double max_plot[2][3] ={ { 0 } };
  double min_plot[2][3] ={ { 0 } };
//  TString strmzztitle[2]={ "105.6<m_{4l}<140.6 GeV", "220<m_{4l}<1600 GeV" };
  TString strmzztitle[2]={ "On-shell", "Off-shell" };
  TString strmzzname[2]={ "Onshell", "Offshell" };
  TString strBSItitle[3]={ "Signal", "Background", "Interference" };
  TString strBSIname[3]={ "Signal", "Background", "Interference" };
  TString strScaleSchemeTitle[3]={ " (Default Phantom)", " (VH Rescaling)", " (+VBF Rescaling)" };
  cout << "Set up canvas gadgets" << endl;
  for (int os=0; os<2; os++){
    cout << strmzzname[os] << endl;
    for (int sc=0; sc<3; sc++){
      cout << strBSItitle[0] << strScaleSchemeTitle[sc] << " mJJ>=130 GeV / mJJ<130 GeV: " << hVBF_sig[os][sc]->GetBinContent(hVBF_sig[os][sc]->GetNbinsX()) << " / " << (hVBF_sig[os][sc]->Integral() - hVBF_sig[os][sc]->GetBinContent(hVBF_sig[os][sc]->GetNbinsX())) << " = " << hVBF_sig[os][sc]->GetBinContent(hVBF_sig[os][sc]->GetNbinsX())/(hVBF_sig[os][sc]->Integral() - hVBF_sig[os][sc]->GetBinContent(hVBF_sig[os][sc]->GetNbinsX())) << endl;
      cout << strBSItitle[1] << strScaleSchemeTitle[sc] << " mJJ>=130 GeV / mJJ<130 GeV: " << hVBF_bkg[os][sc]->GetBinContent(hVBF_bkg[os][sc]->GetNbinsX()) << " / " << (hVBF_bkg[os][sc]->Integral() - hVBF_bkg[os][sc]->GetBinContent(hVBF_bkg[os][sc]->GetNbinsX())) << " = " << hVBF_bkg[os][sc]->GetBinContent(hVBF_bkg[os][sc]->GetNbinsX())/(hVBF_bkg[os][sc]->Integral() - hVBF_bkg[os][sc]->GetBinContent(hVBF_bkg[os][sc]->GetNbinsX())) << endl;
      cout << strBSItitle[2] << strScaleSchemeTitle[sc] << " mJJ>=130 GeV / mJJ<130 GeV: " << hVBF_int[os][sc]->GetBinContent(hVBF_int[os][sc]->GetNbinsX()) << " / " << (hVBF_int[os][sc]->Integral() - hVBF_int[os][sc]->GetBinContent(hVBF_int[os][sc]->GetNbinsX())) << " = " << hVBF_int[os][sc]->GetBinContent(hVBF_int[os][sc]->GetNbinsX())/(hVBF_int[os][sc]->Integral() - hVBF_int[os][sc]->GetBinContent(hVBF_int[os][sc]->GetNbinsX())) << endl;

      hVBF_sig[os][sc]->SetTitle("");
      hVBF_bkg[os][sc]->SetTitle("");
      hVBF_int[os][sc]->SetTitle("");
      hVBF_sig[os][sc]->GetXaxis()->SetRangeUser(22, 129.9);
      hVBF_bkg[os][sc]->GetXaxis()->SetRangeUser(22, 129.9);
      hVBF_int[os][sc]->GetXaxis()->SetRangeUser(22, 129.9);
      hVBF_sig[os][sc]->GetXaxis()->SetTitle("m^{true}_{jj} (GeV)");
      hVBF_bkg[os][sc]->GetXaxis()->SetTitle("m^{true}_{jj} (GeV)");
      hVBF_int[os][sc]->GetXaxis()->SetTitle("m^{true}_{jj} (GeV)");
      double binwidth = hVBF_sig[os][sc]->GetBinWidth(1);
      hVBF_sig[os][sc]->GetYaxis()->SetTitleOffset(1.5);
      hVBF_bkg[os][sc]->GetYaxis()->SetTitleOffset(1.5);
      hVBF_int[os][sc]->GetYaxis()->SetTitleOffset(1.5);
      hVBF_sig[os][sc]->GetYaxis()->SetTitle(Form("Events / %.0f GeV", binwidth));
      hVBF_bkg[os][sc]->GetYaxis()->SetTitle(Form("Events / %.0f GeV", binwidth));
      hVBF_int[os][sc]->GetYaxis()->SetTitle(Form("Events / %.0f GeV", binwidth));
      hVBF_sig[os][sc]->SetLineWidth(2);
      hVBF_bkg[os][sc]->SetLineWidth(2);
      hVBF_int[os][sc]->SetLineWidth(2);
      hVBF_sig[os][sc]->SetLineStyle(1);
      hVBF_bkg[os][sc]->SetLineStyle(1);
      hVBF_int[os][sc]->SetLineStyle(1);
      if (sc==0){
        hVBF_sig[os][sc]->SetLineColor(kRed);
        hVBF_bkg[os][sc]->SetLineColor(kRed);
        hVBF_int[os][sc]->SetLineColor(kRed);
      }
      if (sc==1){
        hVBF_sig[os][sc]->SetLineColor(kViolet);
        hVBF_bkg[os][sc]->SetLineColor(kViolet);
        hVBF_int[os][sc]->SetLineColor(kViolet);
      }
      else if (sc==2){
        hVBF_sig[os][sc]->SetLineColor(kBlue);
        hVBF_bkg[os][sc]->SetLineColor(kBlue);
        hVBF_int[os][sc]->SetLineColor(kBlue);
      }
      for (int bin=1; bin<hVBF_sig[os][sc]->GetNbinsX(); bin++){
        double bcsig = hVBF_sig[os][sc]->GetBinContent(bin);
        double bcbkg = hVBF_bkg[os][sc]->GetBinContent(bin);
        double bcint = hVBF_int[os][sc]->GetBinContent(bin);

        max_plot[os][0] = max(max_plot[os][0], bcsig);
        min_plot[os][0] = min(min_plot[os][0], bcsig);
        max_plot[os][1] = max(max_plot[os][1], bcbkg);
        min_plot[os][1] = min(min_plot[os][1], bcbkg);
        max_plot[os][2] = max(max_plot[os][2], bcint);
        min_plot[os][2] = min(min_plot[os][2], bcint);
      }
      cout << "Set up region " << os << " scheme " << sc << " complete." << endl;
    }
    for (int sc=0; sc<3; sc++){
      hVBF_sig[os][sc]->GetYaxis()->SetRangeUser(min_plot[os][0]*1.5, max_plot[os][0]*1.5);
      hVBF_bkg[os][sc]->GetYaxis()->SetRangeUser(min_plot[os][1]*1.5, max_plot[os][1]*1.5);
      hVBF_int[os][sc]->GetYaxis()->SetRangeUser(min_plot[os][2]*1.5, max_plot[os][2]*1.5);
    }
  }

  foutput->cd();

  for (int os=0; os<2; os++){
    for (int bsi=0; bsi<3; bsi++){
      cout << "Begin plot of region " << os << endl;

      TPaveText* pt = new TPaveText(0.15, 0.93, 0.85, 1, "brNDC");
      pt->SetBorderSize(0);
      pt->SetFillStyle(0);
      pt->SetTextAlign(12);
      pt->SetTextFont(42);
      pt->SetTextSize(0.045);
      TText* text = pt->AddText(0.025, 0.45, "#font[61]{CMS}");
      text->SetTextSize(0.044);
      text = pt->AddText(0.165, 0.42, "#font[52]{Simulation}");
      text->SetTextSize(0.0315);
//      TString cErgTev = "#font[42]{19.7 fb^{-1} (8 TeV) + 5.1 fb^{-1} (7 TeV)}";
      TString cErgTev = "#font[42]{              2e+2#mu 19.7 fb^{-1} (8 TeV)}";
      text = pt->AddText(0.537, 0.45, cErgTev);
      text->SetTextSize(0.0315);

      TString appendName;
      appendName = "_";
      appendName += strmzzname[os];
      appendName += strBSIname[bsi];
      TString canvasname = "cCompareMJJ_GenLevel";
      canvasname.Append(appendName);
      TCanvas* cc = new TCanvas(canvasname, "", 8, 30, 800, 800);
      gStyle->SetOptStat(0);
      cc->cd();
      gStyle->SetOptStat(0);
      cc->SetFillColor(0);
      cc->SetBorderMode(0);
      cc->SetBorderSize(2);
      cc->SetTickx(1);
      cc->SetTicky(1);
      cc->SetLeftMargin(0.17);
      cc->SetRightMargin(0.05);
      cc->SetTopMargin(0.07);
      cc->SetBottomMargin(0.13);
      cc->SetFrameFillStyle(0);
      cc->SetFrameBorderMode(0);
      cc->SetFrameFillStyle(0);
      cc->SetFrameBorderMode(0);

      TLegend *ll;
      ll = new TLegend(0.22, 0.70, 0.60, 0.90);
      ll->SetBorderSize(0);
      ll->SetTextFont(42);
      ll->SetTextSize(0.03);
      ll->SetLineColor(1);
      ll->SetLineStyle(1);
      ll->SetLineWidth(1);
      ll->SetFillColor(0);
      ll->SetFillStyle(0);

      for (int sc=0; sc<3; sc++){
        if (bsi==0){
          TString legendLabel = strBSItitle[bsi] + strScaleSchemeTitle[sc];
          ll->AddEntry(hVBF_sig[os][sc], legendLabel, "l");
          if (sc==0) hVBF_sig[os][sc]->Draw("hist");
          else hVBF_sig[os][sc]->Draw("histsame");
        }
        else if (bsi==1){
          TString legendLabel = strBSItitle[bsi] + strScaleSchemeTitle[sc];
          ll->AddEntry(hVBF_bkg[os][sc], legendLabel, "l");
          if (sc==0) hVBF_bkg[os][sc]->Draw("hist");
          else hVBF_bkg[os][sc]->Draw("histsame");
        }
        else if (bsi==2){
          TString legendLabel = strBSItitle[bsi] + strScaleSchemeTitle[sc];
          ll->AddEntry(hVBF_int[os][sc], legendLabel, "l");
          if (sc==0) hVBF_int[os][sc]->Draw("hist");
          else hVBF_int[os][sc]->Draw("histsame");
        }
      }

      ll->Draw("same");
      pt->Draw();

      TPaveText *pt10 = new TPaveText(0.80, 0.86, 0.90, 0.90, "brNDC");
      pt10->SetBorderSize(0);
      pt10->SetTextAlign(12);
      pt10->SetTextSize(0.03);
      pt10->SetFillStyle(0);
      pt10->SetTextFont(42);
      TText* text10;
      text10 = pt10->AddText(0.01, 0.01, strmzztitle[os]);
      pt10->Draw();

      foutput->WriteTObject(cc);

      delete pt10;
      delete ll;
      cc->Close();
      delete pt;

      cout << "End plot of region " << os << endl;
    }
  }

  for (int tr = 0; tr < kNumTemplates; tr++){
    delete hVBF_onshell_LC[tr];
    delete hVBF_offshell_LC[tr];
    delete hVBF_onshell_scaled[tr];
    delete hVBF_offshell_scaled[tr];
    delete hVBF_onshell_scaled_wVBF[tr];
    delete hVBF_offshell_scaled_wVBF[tr];
  }
  foutput->Close();
}
Exemplo n.º 20
0
void plotZmmResScaleUncert(const TString  inputDir,    // input directory
			   const TString  outputDir,   // output directory
			   const Double_t lumi         // integrated luminosity (/fb)
) {
  gBenchmark->Start("plotZmmResScaleUncert");
  gStyle->SetTitleOffset(1.100,"Y");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //==============================================================================================================   
  const Double_t mu_MASS  = 0.1057;
  //
  // input ntuple file names
  //
  enum { eData, eZmm, eEWK, eTop };  // data type enum
  vector<TString> fnamev;
  vector<Int_t>   typev;

  fnamev.push_back(inputDir + TString("/") + TString("data_select.root")); typev.push_back(eData);
  fnamev.push_back(inputDir + TString("/") + TString("zmm_select.raw.root"));   typev.push_back(eZmm);
  fnamev.push_back(inputDir + TString("/") + TString("ewk_select.raw.root"));  typev.push_back(eEWK);
  fnamev.push_back(inputDir + TString("/") + TString("top_select.raw.root"));  typev.push_back(eTop);

  //
  // Fit options
  //
  const Int_t    NBINS     = 60;
  const Double_t MASS_LOW  = 60;
  const Double_t MASS_HIGH = 120;  
  const Double_t PT_CUT    = 25;
  const Double_t ETA_CUT   = 2.4;

  //----- 
  const int NTOYS = 100;

  // efficiency files
  const TString dataHLTEffName_pos = "/data/blue/xniu/WZXSection/NewMu/MuHLTEff/NewBin/MG/eff.root";
  const TString dataHLTEffName_neg = "/data/blue/xniu/WZXSection/NewMu/MuHLTEff/NewBin/MG/eff.root";
  const TString zmmHLTEffName_pos  = "/data/blue/xniu/WZXSection/NewMu/MuHLTEff/NewBin/CT/eff.root";
  const TString zmmHLTEffName_neg  = "/data/blue/xniu/WZXSection/NewMu/MuHLTEff/NewBin/CT/eff.root";

  const TString dataSelEffName_pos = "/data/blue/xniu/WZXSection/NewMu/MuSITEff/NewBin/MG/eff.root";
  const TString dataSelEffName_neg = "/data/blue/xniu/WZXSection/NewMu/MuSITEff/NewBin/MG/eff.root";
  const TString zmmSelEffName_pos  = "/data/blue/xniu/WZXSection/NewMu/MuSITEff/NewBin/CT/eff.root";
  const TString zmmSelEffName_neg  = "/data/blue/xniu/WZXSection/NewMu/MuSITEff/NewBin/CT/eff.root";

  const TString dataTrkEffName_pos = "/data/blue/xniu/WZXSection/NewMu/MuSITEff/NewBin/MG/eff.root";
  const TString dataTrkEffName_neg = "/data/blue/xniu/WZXSection/NewMu/MuSITEff/NewBin/MG/eff.root";
  const TString zmmTrkEffName_pos  = "/data/blue/xniu/WZXSection/NewMu/MuSITEff/NewBin/CT/eff.root";
  const TString zmmTrkEffName_neg  = "/data/blue/xniu/WZXSection/NewMu/MuSITEff/NewBin/CT/eff.root";

  const TString dataStaEffName_pos = "/data/blue/xniu/WZXSection/NewMu/MuStaEff/NewBin/MG/eff.root";
  const TString dataStaEffName_neg = "/data/blue/xniu/WZXSection/NewMu/MuStaEff/NewBin/MG/eff.root";
  const TString zmmStaEffName_pos  = "/data/blue/xniu/WZXSection/NewMu/MuStaEff/NewBin/CT/eff.root";
  const TString zmmStaEffName_neg  = "/data/blue/xniu/WZXSection/NewMu/MuStaEff/NewBin/CT/eff.root";

   
  //
  // Set up output file
  //
  TString outfilename = outputDir + TString("/") + TString("Zmm_DataBkg_ResScale.root");
  TFile *outFile = new TFile(outfilename,"RECREATE");


  // plot output file format
  const TString format("png");
   
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  // event category enumeration
  enum { eMuMu2HLT=1, eMuMu1HLT1L1, eMuMu1HLT, eMuMuNoSel, eMuSta, eMuTrk }; // event category enum
    
  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  CPlot::sOutDir = outputDir;  
  
  // histograms for full selection
  double ZPtBins[]={0,1.25,2.5,3.75,5,6.25,7.5,8.75,10,11.25,12.5,15,17.5,20,25,30,35,40,45,50,60,70,80,90,100,110,130,150,170,190,220,250,400,1000};
  double PhiStarBins[]={0,0.001,0.002,0.003,0.004,0.005,0.006,0.007,0.008,0.01,0.012,0.014,0.016,0.018,0.021,0.024,0.027,0.030,0.034,0.038,0.044,0.050,0.058,0.066,0.076,0.088,0.10,0.12,0.14,0.16,0.18,0.20,0.24,0.28,0.34,0.42,0.52,0.64,0.8,1.0,1.5,2,3};
  double Lep1PtBins[]={25,26.3,27.6,28.9,30.4,31.9,33.5,35.2,36.9,38.8,40.7,42.8,44.9,47.1,49.5,52.0,54.6,57.3,60.7,65.6,72.2,80.8,92.1,107,126,150,200,300};
  double Lep2PtBins[]={25,26.3,27.6,28.9,30.4,31.9,33.5,35.2,36.9,38.8,40.7,42.8,44.9,47.1,49.5,52.0,54.6,57.3,60.7,65.6,72.2,80.8,92.1,107,126,150};
  double LepNegPtBins[]={25,26.3,27.6,28.9,30.4,31.9,33.5,35.2,36.9,38.8,40.7,42.8,44.9,47.1,49.5,52.0,54.6,57.3,60.7,65.6,72.2,80.8,92.1,107,126,150,200,300};
  double LepPosPtBins[]={25,26.3,27.6,28.9,30.4,31.9,33.5,35.2,36.9,38.8,40.7,42.8,44.9,47.1,49.5,52.0,54.6,57.3,60.7,65.6,72.2,80.8,92.1,107,126,150,200,300};
  
  vector<TH1D> hData; create(hData,"hData",NBINS,MASS_LOW,MASS_HIGH,NTOYS);
  vector<TH1D> hZmm; create(hZmm,"hZmm",NBINS,MASS_LOW,MASS_HIGH,NTOYS);
  vector<TH1D> hEWK; create(hEWK,"hEWK",NBINS,MASS_LOW,MASS_HIGH,NTOYS);
  vector<TH1D> hTop; create(hTop,"hTop",NBINS,MASS_LOW,MASS_HIGH,NTOYS);
  vector<TH1D> hMC; create(hMC,"hMC",NBINS,MASS_LOW,MASS_HIGH,NTOYS);

  const int nBinsZPt= sizeof(ZPtBins)/sizeof(double)-1;
  vector<TH1D> hDataZPt ; create(hDataZPt,"hDataZPt",nBinsZPt,ZPtBins,NTOYS);
  vector<TH1D> hZmmZPt ; create(hZmmZPt,"hZmmZPt",nBinsZPt,ZPtBins,NTOYS);
  vector<TH1D> hEWKZPt ; create(hEWKZPt,"hEWKZPt",nBinsZPt,ZPtBins,NTOYS);
  vector<TH1D> hTopZPt ; create(hTopZPt,"hTopZPt",nBinsZPt,ZPtBins,NTOYS);
  vector<TH1D> hMCZPt ; create(hMCZPt,"hMCZPt",nBinsZPt,ZPtBins,NTOYS);

  const int nBinsPhiStar= sizeof(PhiStarBins)/sizeof(double)-1;
  vector<TH1D> hDataPhiStar ; create(hDataPhiStar,"hDataPhiStar",nBinsPhiStar,PhiStarBins,NTOYS);
  vector<TH1D> hZmmPhiStar ; create(hZmmPhiStar,"hZmmPhiStar",nBinsPhiStar,PhiStarBins,NTOYS);
  vector<TH1D> hEWKPhiStar ; create(hEWKPhiStar,"hEWKPhiStar",nBinsPhiStar,PhiStarBins,NTOYS);
  vector<TH1D> hTopPhiStar ; create(hTopPhiStar,"hTopPhiStar",nBinsPhiStar,PhiStarBins,NTOYS);
  vector<TH1D> hMCPhiStar ; create(hMCPhiStar,"hMCPhiStar",nBinsPhiStar,PhiStarBins,NTOYS);

  vector<TH1D> hDataZRap ; create(hDataZRap,"hDataZRap",24,0,2.4,NTOYS);
  vector<TH1D> hZmmZRap ; create(hZmmZRap,"hZmmZRap",24,0,2.4,NTOYS);
  vector<TH1D> hEWKZRap ; create(hEWKZRap,"hEWKZRap",24,0,2.4,NTOYS);
  vector<TH1D> hTopZRap ; create(hTopZRap,"hTopZRap",24,0,2.4,NTOYS);
  vector<TH1D> hMCZRap ; create(hMCZRap,"hMCZRap",24,0,2.4,NTOYS);

  const int nBinsLep1Pt= sizeof(Lep1PtBins)/sizeof(double)-1;
  vector<TH1D> hDataLep1Pt ; create(hDataLep1Pt,"hDataLep1Pt",nBinsLep1Pt,Lep1PtBins,NTOYS);
  vector<TH1D> hZmmLep1Pt ; create(hZmmLep1Pt,"hZmmLep1Pt",nBinsLep1Pt,Lep1PtBins,NTOYS);
  vector<TH1D> hEWKLep1Pt ; create(hEWKLep1Pt,"hEWKLep1Pt",nBinsLep1Pt,Lep1PtBins,NTOYS);
  vector<TH1D> hTopLep1Pt ; create(hTopLep1Pt,"hTopLep1Pt",nBinsLep1Pt,Lep1PtBins,NTOYS);
  vector<TH1D> hMCLep1Pt ; create(hMCLep1Pt,"hMCLep1Pt",nBinsLep1Pt,Lep1PtBins,NTOYS);

  const int nBinsLep2Pt= sizeof(Lep2PtBins)/sizeof(double)-1;
  vector<TH1D> hDataLep2Pt ; create(hDataLep2Pt,"hDataLep2Pt",nBinsLep2Pt,Lep2PtBins,NTOYS);
  vector<TH1D> hZmmLep2Pt ; create(hZmmLep2Pt,"hZmmLep2Pt",nBinsLep2Pt,Lep2PtBins,NTOYS);
  vector<TH1D> hEWKLep2Pt ; create(hEWKLep2Pt,"hEWKLep2Pt",nBinsLep2Pt,Lep2PtBins,NTOYS);
  vector<TH1D> hTopLep2Pt ; create(hTopLep2Pt,"hTopLep2Pt",nBinsLep2Pt,Lep2PtBins,NTOYS);
  vector<TH1D> hMCLep2Pt ; create(hMCLep2Pt,"hMCLep2Pt",nBinsLep2Pt,Lep2PtBins,NTOYS);

  const int nBinsLepNegPt= sizeof(LepNegPtBins)/sizeof(double)-1;
  vector<TH1D> hDataLepNegPt ; create(hDataLepNegPt,"hDataLepNegPt",nBinsLepNegPt,LepNegPtBins,NTOYS);
  vector<TH1D> hZmmLepNegPt ; create(hZmmLepNegPt,"hZmmLepNegPt",nBinsLepNegPt,LepNegPtBins,NTOYS);
  vector<TH1D> hEWKLepNegPt ; create(hEWKLepNegPt,"hEWKLepNegPt",nBinsLepNegPt,LepNegPtBins,NTOYS);
  vector<TH1D> hTopLepNegPt ; create(hTopLepNegPt,"hTopLepNegPt",nBinsLepNegPt,LepNegPtBins,NTOYS);
  vector<TH1D> hMCLepNegPt ; create(hMCLepNegPt,"hMCLepNegPt",nBinsLepNegPt,LepNegPtBins,NTOYS);

  const int nBinsLepPosPt= sizeof(LepPosPtBins)/sizeof(double)-1;
  vector<TH1D> hDataLepPosPt ; create(hDataLepPosPt,"hDataLepPosPt",nBinsLepPosPt,LepPosPtBins,NTOYS);
  vector<TH1D> hZmmLepPosPt ; create(hZmmLepPosPt,"hZmmLepPosPt",nBinsLepPosPt,LepPosPtBins,NTOYS);
  vector<TH1D> hEWKLepPosPt ; create(hEWKLepPosPt,"hEWKLepPosPt",nBinsLepPosPt,LepPosPtBins,NTOYS);
  vector<TH1D> hTopLepPosPt ; create(hTopLepPosPt,"hTopLepPosPt",nBinsLepPosPt,LepPosPtBins,NTOYS);
  vector<TH1D> hMCLepPosPt ; create(hMCLepPosPt,"hMCLepPosPt",nBinsLepPosPt,LepPosPtBins,NTOYS);

  vector<TH1D> hDataLep1Eta ; create(hDataLep1Eta,"hDataLep1Eta",24,0,2.4,NTOYS);
  vector<TH1D> hZmmLep1Eta ; create(hZmmLep1Eta,"hZmmLep1Eta",24,0,2.4,NTOYS);
  vector<TH1D> hEWKLep1Eta ; create(hEWKLep1Eta,"hEWKLep1Eta",24,0,2.4,NTOYS);
  vector<TH1D> hTopLep1Eta ; create(hTopLep1Eta,"hTopLep1Eta",24,0,2.4,NTOYS);
  vector<TH1D> hMCLep1Eta ; create(hMCLep1Eta,"hMCLep1Eta",24,0,2.4,NTOYS);

  
  vector<TH1D> hDataLep2Eta ; create(hDataLep2Eta,"hDataLep2Eta",24,0,2.4,NTOYS);
  vector<TH1D> hZmmLep2Eta ; create(hZmmLep2Eta,"hZmmLep2Eta",24,0,2.4,NTOYS);
  vector<TH1D> hEWKLep2Eta ; create(hEWKLep2Eta,"hEWKLep2Eta",24,0,2.4,NTOYS);
  vector<TH1D> hTopLep2Eta ; create(hTopLep2Eta,"hTopLep2Eta",24,0,2.4,NTOYS);
  vector<TH1D> hMCLep2Eta ; create(hMCLep2Eta,"hMCLep2Eta",24,0,2.4,NTOYS);

  
  //
  // Declare variables to read in ntuple
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  category;
  UInt_t  npv, npu;
  Float_t scale1fb, scale1fbUp, scale1fbDown;
  Int_t   q1, q2;
  TLorentzVector *lep1=0, *lep2=0;
  
  TH2D *h=0;

  //
  // HLT efficiency
  //
  cout << "Loading trigger efficiencies..." << endl;
  
  TFile *dataHLTEffFile_pos = new TFile(dataHLTEffName_pos);
  CEffUser2D dataHLTEff_pos;
  dataHLTEff_pos.loadEff((TH2D*)dataHLTEffFile_pos->Get("hEffEtaPt"), (TH2D*)dataHLTEffFile_pos->Get("hErrlEtaPt"), (TH2D*)dataHLTEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *dataHLTEffFile_neg = new TFile(dataHLTEffName_neg);
  CEffUser2D dataHLTEff_neg;
  dataHLTEff_neg.loadEff((TH2D*)dataHLTEffFile_neg->Get("hEffEtaPt"), (TH2D*)dataHLTEffFile_neg->Get("hErrlEtaPt"), (TH2D*)dataHLTEffFile_neg->Get("hErrhEtaPt"));
    
  TFile *zmmHLTEffFile_pos = new TFile(zmmHLTEffName_pos);
  CEffUser2D zmmHLTEff_pos;
  zmmHLTEff_pos.loadEff((TH2D*)zmmHLTEffFile_pos->Get("hEffEtaPt"), (TH2D*)zmmHLTEffFile_pos->Get("hErrlEtaPt"), (TH2D*)zmmHLTEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *zmmHLTEffFile_neg = new TFile(zmmHLTEffName_neg);
  CEffUser2D zmmHLTEff_neg;
  zmmHLTEff_neg.loadEff((TH2D*)zmmHLTEffFile_neg->Get("hEffEtaPt"), (TH2D*)zmmHLTEffFile_neg->Get("hErrlEtaPt"), (TH2D*)zmmHLTEffFile_neg->Get("hErrhEtaPt"));

    
  //
  // Selection efficiency
  //
  cout << "Loading selection efficiencies..." << endl;
  
  TFile *dataSelEffFile_pos = new TFile(dataSelEffName_pos);
  CEffUser2D dataSelEff_pos;
  dataSelEff_pos.loadEff((TH2D*)dataSelEffFile_pos->Get("hEffEtaPt"), (TH2D*)dataSelEffFile_pos->Get("hErrlEtaPt"), (TH2D*)dataSelEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *dataSelEffFile_neg = new TFile(dataSelEffName_neg);
  CEffUser2D dataSelEff_neg;
  dataSelEff_neg.loadEff((TH2D*)dataSelEffFile_neg->Get("hEffEtaPt"), (TH2D*)dataSelEffFile_neg->Get("hErrlEtaPt"), (TH2D*)dataSelEffFile_neg->Get("hErrhEtaPt"));
  
  TFile *zmmSelEffFile_pos = new TFile(zmmSelEffName_pos);
  CEffUser2D zmmSelEff_pos;
  zmmSelEff_pos.loadEff((TH2D*)zmmSelEffFile_pos->Get("hEffEtaPt"), (TH2D*)zmmSelEffFile_pos->Get("hErrlEtaPt"), (TH2D*)zmmSelEffFile_pos->Get("hErrhEtaPt"));

  TFile *zmmSelEffFile_neg = new TFile(zmmSelEffName_neg);
  CEffUser2D zmmSelEff_neg;
  zmmSelEff_neg.loadEff((TH2D*)zmmSelEffFile_neg->Get("hEffEtaPt"), (TH2D*)zmmSelEffFile_neg->Get("hErrlEtaPt"), (TH2D*)zmmSelEffFile_neg->Get("hErrhEtaPt"));

  //
  // Standalone efficiency
  //
  cout << "Loading standalone efficiencies..." << endl;
  
  TFile *dataStaEffFile_pos = new TFile(dataStaEffName_pos);
  CEffUser2D dataStaEff_pos;
  dataStaEff_pos.loadEff((TH2D*)dataStaEffFile_pos->Get("hEffEtaPt"), (TH2D*)dataStaEffFile_pos->Get("hErrlEtaPt"), (TH2D*)dataStaEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *dataStaEffFile_neg = new TFile(dataStaEffName_neg);
  CEffUser2D dataStaEff_neg;
  dataStaEff_neg.loadEff((TH2D*)dataStaEffFile_neg->Get("hEffEtaPt"), (TH2D*)dataStaEffFile_neg->Get("hErrlEtaPt"), (TH2D*)dataStaEffFile_neg->Get("hErrhEtaPt"));
  
  TFile *zmmStaEffFile_pos = new TFile(zmmStaEffName_pos);
  CEffUser2D zmmStaEff_pos;
  zmmStaEff_pos.loadEff((TH2D*)zmmStaEffFile_pos->Get("hEffEtaPt"), (TH2D*)zmmStaEffFile_pos->Get("hErrlEtaPt"), (TH2D*)zmmStaEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *zmmStaEffFile_neg = new TFile(zmmStaEffName_neg);
  CEffUser2D zmmStaEff_neg;
  zmmStaEff_neg.loadEff((TH2D*)zmmStaEffFile_neg->Get("hEffEtaPt"), (TH2D*)zmmStaEffFile_neg->Get("hErrlEtaPt"), (TH2D*)zmmStaEffFile_neg->Get("hErrhEtaPt"));

  
  //
  // Tracker efficiency
  //
  cout << "Loading track efficiencies..." << endl;
  
  TFile *dataTrkEffFile_pos = new TFile(dataTrkEffName_pos);
  CEffUser2D dataTrkEff_pos;
  dataTrkEff_pos.loadEff((TH2D*)dataTrkEffFile_pos->Get("hEffEtaPt"), (TH2D*)dataTrkEffFile_pos->Get("hErrlEtaPt"), (TH2D*)dataTrkEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *dataTrkEffFile_neg = new TFile(dataTrkEffName_neg);
  CEffUser2D dataTrkEff_neg;
  dataTrkEff_neg.loadEff((TH2D*)dataTrkEffFile_neg->Get("hEffEtaPt"), (TH2D*)dataTrkEffFile_neg->Get("hErrlEtaPt"), (TH2D*)dataTrkEffFile_neg->Get("hErrhEtaPt"));
  
  TFile *zmmTrkEffFile_pos = new TFile(zmmTrkEffName_pos);
  CEffUser2D zmmTrkEff_pos;
  zmmTrkEff_pos.loadEff((TH2D*)zmmTrkEffFile_pos->Get("hEffEtaPt"), (TH2D*)zmmTrkEffFile_pos->Get("hErrlEtaPt"), (TH2D*)zmmTrkEffFile_pos->Get("hErrhEtaPt"));
  
  TFile *zmmTrkEffFile_neg = new TFile(zmmTrkEffName_neg);
  CEffUser2D zmmTrkEff_neg;
  zmmTrkEff_neg.loadEff((TH2D*)zmmTrkEffFile_neg->Get("hEffEtaPt"), (TH2D*)zmmTrkEffFile_neg->Get("hErrlEtaPt"), (TH2D*)zmmTrkEffFile_neg->Get("hErrhEtaPt"));
  

  //Setting up rochester corrections
  vector<rochcor2015> vRocToys;
  for (int i=0 ; i<NTOYS; ++i) vRocToys.push_back(rochcor2015(1234+i*1000));
   

  TFile *infile=0;
  TTree *intree=0;

  for(UInt_t ifile=0; ifile<fnamev.size(); ifile++) {
  
    // Read input file and get the TTrees
    cout << "Processing " << fnamev[ifile] << "..." << endl;
    infile = new TFile(fnamev[ifile]);	    assert(infile);
    intree = (TTree*)infile->Get("Events"); assert(intree);

    intree -> SetBranchStatus("*",0);
    intree -> SetBranchStatus("runNum",1);
    intree -> SetBranchStatus("lumiSec",1);
    intree -> SetBranchStatus("evtNum",1);
    intree -> SetBranchStatus("category",1);
    intree -> SetBranchStatus("scale1fb",1);
    intree -> SetBranchStatus("q1",1);
    intree -> SetBranchStatus("q2",1);
    intree -> SetBranchStatus("lep1",1);
    intree -> SetBranchStatus("lep2",1);

    intree->SetBranchAddress("runNum",     &runNum);      // event run number
    intree->SetBranchAddress("lumiSec",    &lumiSec);     // event lumi section
    intree->SetBranchAddress("evtNum",     &evtNum);      // event number
    intree->SetBranchAddress("category",   &category);    // dilepton category
    intree->SetBranchAddress("scale1fb",   &scale1fb);    // event weight per 1/fb (MC)
    intree->SetBranchAddress("q1",         &q1);	  // charge of tag lepton
    intree->SetBranchAddress("q2",         &q2);	  // charge of probe lepton
    intree->SetBranchAddress("lep1",       &lep1);        // tag lepton 4-vector
    intree->SetBranchAddress("lep2",       &lep2);        // probe lepton 4-vector

    //
    // loop over events
    //
    for(UInt_t ientry=0; ientry<intree->GetEntries(); ientry++) {
      intree->GetEntry(ientry);
      
      if(fabs(lep1->Eta()) > ETA_CUT)   continue;      
      if(fabs(lep2->Eta()) > ETA_CUT)   continue;
      if(q1*q2>0) continue;
      
      float mass = 0;
      float pt = 0;
      float rapidity = 0;
      float phiacop=0;
      float costhetastar=0;
      float phistar=0;

      Double_t weight=1;
      if(typev[ifile]!=eData) {
	weight *= scale1fb*lumi;
      }
 	     
      for(int itoys=0;itoys!=NTOYS;++itoys)
	{
      // fill Z events passing selection (MuMu2HLT + MuMu1HLT)
      if((category==eMuMu2HLT) || (category==eMuMu1HLT) || (category==eMuMu1HLT1L1)) {
        if(typev[ifile]==eData) { 
	  TLorentzVector mu1;
	  TLorentzVector mu2;
	  mu1.SetPtEtaPhiM(lep1->Pt(),lep1->Eta(),lep1->Phi(),mu_MASS);
	  mu2.SetPtEtaPhiM(lep2->Pt(),lep2->Eta(),lep2->Phi(),mu_MASS);
	  float qter1=1.0;
	  float qter2=1.0;
          
	  vRocToys[itoys].momcor_data(mu1,q1,0,qter1);
	  vRocToys[itoys].momcor_data(mu2,q2,0,qter2);
	  
	  Double_t lp1 = mu1.Pt();
	  Double_t lp2 = mu2.Pt();
	  Double_t lq1 = q1;
	  Double_t lq2 = q2;

	  TLorentzVector l1, l2;
	  if(lp1>lp2)
	    {
	      l1.SetPtEtaPhiM(lp1,lep1->Eta(),lep1->Phi(),mu_MASS);
	      l2.SetPtEtaPhiM(lp2,lep2->Eta(),lep2->Phi(),mu_MASS);
	    }
	  else
	    {
	      l1.SetPtEtaPhiM(lp2,lep2->Eta(),lep2->Phi(),mu_MASS);
	      l2.SetPtEtaPhiM(lp1,lep1->Eta(),lep1->Phi(),mu_MASS);
	      lq1=q2;
	      lq2=q1;
	    }

	  mass=(l1+l2).M();
	  pt =(l1+l2).Pt();
	  rapidity = (l1+l2).Rapidity();

	  phiacop=TMath::Pi()-fabs(l1.DeltaPhi(l2));
	  if(lq1<0) costhetastar=tanh(float((l1.Rapidity()-l2.Rapidity())/2));
	  else costhetastar=tanh(float((l2.Rapidity()-l1.Rapidity())/2));
	  phistar=tan(phiacop/2)*sqrt(1-pow(costhetastar,2));
	  
	  if(mass        < MASS_LOW)  continue;
	  if(mass        > MASS_HIGH) continue;
	  if(l1.Pt()        < PT_CUT)    continue;
	  if(l2.Pt()        < PT_CUT)    continue;

	  hData[itoys].Fill(mass); 
	  hDataZPt[itoys].Fill(pt); 
	  hDataPhiStar[itoys].Fill(phistar); 
	  hDataLep1Pt[itoys].Fill(l1.Pt()); 
	  hDataLep2Pt[itoys].Fill(l2.Pt()); 
	  if(lq1<0)
	    {
	      hDataLepNegPt[itoys].Fill(l1.Pt()); 
	      hDataLepPosPt[itoys].Fill(l2.Pt());
	    }
	  else 
	    {
	      hDataLepNegPt[itoys].Fill(l2.Pt()); 
	      hDataLepPosPt[itoys].Fill(l1.Pt());
	    }
	  hDataLep1Eta[itoys].Fill(fabs(l1.Eta())); 
	  hDataLep2Eta[itoys].Fill(fabs(l2.Eta())); 
	  hDataZRap[itoys].Fill(fabs(rapidity));
	} else {
	  TLorentzVector mu1;
	  TLorentzVector mu2;
	  mu1.SetPtEtaPhiM(lep1->Pt(),lep1->Eta(),lep1->Phi(),mu_MASS);
	  mu2.SetPtEtaPhiM(lep2->Pt(),lep2->Eta(),lep2->Phi(),mu_MASS);
	  float qter1=1.0;
	  float qter2=1.0;

	  vRocToys[itoys].momcor_mc(mu1,q1,0,qter1);
	  vRocToys[itoys].momcor_mc(mu2,q2,0,qter2);

	  Double_t lp1 = mu1.Pt();
	  Double_t lp2 = mu2.Pt();
	  Double_t lq1 = q1;
	  Double_t lq2 = q2;

	  TLorentzVector l1, l2;
	  if(lp1>lp2)
	    {
	      l1.SetPtEtaPhiM(lp1,lep1->Eta(),lep1->Phi(),mu_MASS);
	      l2.SetPtEtaPhiM(lp2,lep2->Eta(),lep2->Phi(),mu_MASS);
	    }
	  else
	    {
	      l1.SetPtEtaPhiM(lp2,lep2->Eta(),lep2->Phi(),mu_MASS);
	      l2.SetPtEtaPhiM(lp1,lep1->Eta(),lep1->Phi(),mu_MASS);
	      lq1=q2;
	      lq2=q1;
	    }

	  double mll=(l1+l2).M();
	  Double_t effdata, effmc;
	  Double_t corr=1;
	 
	  if(mll       < MASS_LOW)  continue;
	  if(mll       > MASS_HIGH) continue;
	  if(lp1        < PT_CUT)    continue;
	  if(lp2        < PT_CUT)    continue;
	  effdata=1; effmc=1;    
          if(lq1>0) { 
            effdata *= (1.-dataHLTEff_pos.getEff((l1.Eta()), l1.Pt())); 
            effmc   *= (1.-zmmHLTEff_pos.getEff((l1.Eta()), l1.Pt())); 
          } else {
            effdata *= (1.-dataHLTEff_neg.getEff((l1.Eta()), l1.Pt())); 
            effmc   *= (1.-zmmHLTEff_neg.getEff((l1.Eta()), l1.Pt())); 
          }
          if(lq2>0) {
            effdata *= (1.-dataHLTEff_pos.getEff((l2.Eta()), l2.Pt())); 
            effmc   *= (1.-zmmHLTEff_pos.getEff((l2.Eta()), l2.Pt()));
          } else {
            effdata *= (1.-dataHLTEff_neg.getEff((l2.Eta()), l2.Pt())); 
            effmc   *= (1.-zmmHLTEff_neg.getEff((l2.Eta()), l2.Pt()));
          }
          effdata = 1.-effdata;
          effmc   = 1.-effmc;
          corr *= effdata/effmc;
	     
          effdata=1; effmc=1;
	  if(lq1>0) { 
	    effdata *= dataSelEff_pos.getEff((l1.Eta()), l1.Pt()); 
	    effmc   *= zmmSelEff_pos.getEff((l1.Eta()), l1.Pt()); 
	  } else {
	    effdata *= dataSelEff_neg.getEff((l1.Eta()), l1.Pt()); 
	    effmc   *= zmmSelEff_neg.getEff((l1.Eta()), l1.Pt()); 
	  }
	  if(lq2>0) {
	    effdata *= dataSelEff_pos.getEff((l2.Eta()), l2.Pt()); 
	    effmc   *= zmmSelEff_pos.getEff((l2.Eta()), l2.Pt());
	  } else {
	    effdata *= dataSelEff_neg.getEff((l2.Eta()), l2.Pt()); 
	    effmc   *= zmmSelEff_neg.getEff((l2.Eta()), l2.Pt());
	  }
	  corr *= effdata/effmc;

	  effdata=1; effmc=1;
	  if(lq1>0) { 
	    effdata *= dataStaEff_pos.getEff((l1.Eta()), l1.Pt()); 
	    effmc   *= zmmStaEff_pos.getEff((l1.Eta()), l1.Pt()); 
	  } else {
	    effdata *= dataStaEff_neg.getEff((l1.Eta()), l1.Pt()); 
	    effmc   *= zmmStaEff_neg.getEff((l1.Eta()), l1.Pt()); 
	  }
	  if(lq2>0) {
	    effdata *= dataStaEff_pos.getEff((l2.Eta()), l2.Pt()); 
	    effmc   *= zmmStaEff_pos.getEff((l2.Eta()), l2.Pt());
	  } else {
	    effdata *= dataStaEff_neg.getEff((l2.Eta()), l2.Pt()); 
	    effmc   *= zmmStaEff_neg.getEff((l2.Eta()), l2.Pt());
	  }
	  corr *= effdata/effmc; 
	  
          effdata=1; effmc=1;
          if(lq1>0) { 
            effdata *= dataTrkEff_pos.getEff((l1.Eta()), l1.Pt()); 
            effmc   *= zmmTrkEff_pos.getEff((l1.Eta()), l1.Pt()); 
          } else {
            effdata *= dataTrkEff_neg.getEff((l1.Eta()), l1.Pt()); 
            effmc   *= zmmTrkEff_neg.getEff((l1.Eta()), l1.Pt()); 
          }
          if(lq2>0) {
            effdata *= dataTrkEff_pos.getEff((l2.Eta()), l2.Pt()); 
            effmc   *= zmmTrkEff_pos.getEff((l2.Eta()), l2.Pt());
          } else {
            effdata *= dataTrkEff_neg.getEff((l2.Eta()), l2.Pt()); 
            effmc   *= zmmTrkEff_neg.getEff((l2.Eta()), l2.Pt());
          }
          //corr *= effdata/effmc;
	  //corr=1;	  
	
	  mass = (l1+l2).M();
	  pt = (l1+l2).Pt();
	  rapidity = (l1+l2).Rapidity();

	  phiacop=TMath::Pi()-fabs(l1.DeltaPhi(l2));
	  if(lq1<0) costhetastar=tanh(float((l1.Rapidity()-l2.Rapidity())/2));
	  else costhetastar=tanh(float((l2.Rapidity()-l1.Rapidity())/2));
	  phistar=tan(phiacop/2)*sqrt(1-pow(costhetastar,2));

	  if(typev[ifile]==eZmm) 
	    {
	      hZmm[itoys].Fill(mass,weight*corr); 
	      hMC[itoys].Fill(mass,weight*corr);
	      hZmmZPt[itoys].Fill(pt,weight*corr); 
	      hMCZPt[itoys].Fill(pt,weight*corr);
	      hZmmPhiStar[itoys].Fill(phistar,weight*corr); 
	      hMCPhiStar[itoys].Fill(phistar,weight*corr);
	      hZmmZRap[itoys].Fill(fabs(rapidity),weight*corr); 
	      hMCZRap[itoys].Fill(fabs(rapidity),weight*corr);
	      hZmmLep1Pt[itoys].Fill(l1.Pt(),weight*corr); 
	      hMCLep1Pt[itoys].Fill(l1.Pt(),weight*corr);
	      if(lq1<0)
		{
		  hZmmLepNegPt[itoys].Fill(l1.Pt(),weight*corr); 
		  hMCLepNegPt[itoys].Fill(l1.Pt(),weight*corr);
		  hZmmLepPosPt[itoys].Fill(l2.Pt(),weight*corr); 
		  hMCLepPosPt[itoys].Fill(l2.Pt(),weight*corr);
		}
	      else 
		{
		  hZmmLepNegPt[itoys].Fill(l2.Pt(),weight*corr); 
		  hMCLepNegPt[itoys].Fill(l2.Pt(),weight*corr);
		  hZmmLepPosPt[itoys].Fill(l1.Pt(),weight*corr); 
		  hMCLepPosPt[itoys].Fill(l1.Pt(),weight*corr);
		}
	      hZmmLep2Pt[itoys].Fill(l2.Pt(),weight*corr); 
	      hMCLep2Pt[itoys].Fill(l2.Pt(),weight*corr);
	      hZmmLep1Eta[itoys].Fill(fabs(l1.Eta()),weight*corr); 
	      hMCLep1Eta[itoys].Fill(fabs(l1.Eta()),weight*corr);
	      hZmmLep2Eta[itoys].Fill(fabs(l2.Eta()),weight*corr); 
	      hMCLep2Eta[itoys].Fill(fabs(l2.Eta()),weight*corr);
	    }
	  if(typev[ifile]==eEWK) 
	    {
	      hEWK[itoys].Fill(mass,weight*corr); 
	      hMC[itoys].Fill(mass,weight*corr);

	      hEWKZPt[itoys].Fill(pt,weight*corr); 
	      hMCZPt[itoys].Fill(pt,weight*corr);

	      hEWKPhiStar[itoys].Fill(phistar,weight*corr);
	      hMCPhiStar[itoys].Fill(phistar,weight*corr);

	      hEWKZRap[itoys].Fill(fabs(rapidity),weight*corr); 
	      hMCZRap[itoys].Fill(fabs(rapidity),weight*corr);

	      hEWKLep1Pt[itoys].Fill(l1.Pt(),weight*corr);
	      hMCLep1Pt[itoys].Fill(l1.Pt(),weight*corr);

	      hEWKLep2Pt[itoys].Fill(l2.Pt(),weight*corr);
	      hMCLep2Pt[itoys].Fill(l2.Pt(),weight*corr);

	      if(lq1<0)
		{
		  hEWKLepNegPt[itoys].Fill(l1.Pt(),weight*corr);
		  hMCLepNegPt[itoys].Fill(l1.Pt(),weight*corr);
		  
		  hEWKLepPosPt[itoys].Fill(l2.Pt(),weight*corr);
		  hMCLepPosPt[itoys].Fill(l2.Pt(),weight*corr);
		}
	      else
		{
		  hEWKLepNegPt[itoys].Fill(l2.Pt(),weight*corr);
		  hMCLepNegPt[itoys].Fill(l2.Pt(),weight*corr);
		  
		  hEWKLepPosPt[itoys].Fill(l1.Pt(),weight*corr);
		  hMCLepPosPt[itoys].Fill(l1.Pt(),weight*corr);
		}

	      hEWKLep1Eta[itoys].Fill(fabs(l1.Eta()),weight*corr); 
	      hMCLep1Eta[itoys].Fill(fabs(l1.Eta()),weight*corr);

	      hEWKLep2Eta[itoys].Fill(fabs(l2.Eta()),weight*corr);
	      hMCLep2Eta[itoys].Fill(fabs(l2.Eta()),weight*corr);
	    }
	  if(typev[ifile]==eTop) 
	    {
	      hTop[itoys].Fill(mass,weight*corr); 
	      hMC[itoys].Fill(mass,weight*corr);

	      hTopZPt[itoys].Fill(pt,weight*corr); 
	      hMCZPt[itoys].Fill(pt,weight*corr);

	      hTopPhiStar[itoys].Fill(phistar,weight*corr);
	      hMCPhiStar[itoys].Fill(phistar,weight*corr);

	      hTopZRap[itoys].Fill(fabs(rapidity),weight*corr); 
	      hMCZRap[itoys].Fill(fabs(rapidity),weight*corr);

	      hTopLep1Pt[itoys].Fill(l1.Pt(),weight*corr);
	      hMCLep1Pt[itoys].Fill(l1.Pt(),weight*corr);

	      hTopLep2Pt[itoys].Fill(l2.Pt(),weight*corr);
	      hMCLep2Pt[itoys].Fill(l2.Pt(),weight*corr);

	      if(lq1<0)
		{
		  hTopLepNegPt[itoys].Fill(l1.Pt(),weight*corr);
		  hMCLepNegPt[itoys].Fill(l1.Pt(),weight*corr);
		  
		  hTopLepPosPt[itoys].Fill(l2.Pt(),weight*corr);
		  hMCLepPosPt[itoys].Fill(l2.Pt(),weight*corr);
		}
	      else
		{
		  hTopLepNegPt[itoys].Fill(l2.Pt(),weight*corr);
		  hMCLepNegPt[itoys].Fill(l2.Pt(),weight*corr);
		  
		  hTopLepPosPt[itoys].Fill(l1.Pt(),weight*corr);
		  hMCLepPosPt[itoys].Fill(l1.Pt(),weight*corr);
		}

	      hTopLep1Eta[itoys].Fill(fabs(l1.Eta()),weight*corr);
	      hMCLep1Eta[itoys].Fill(fabs(l1.Eta()),weight*corr);

	      hTopLep2Eta[itoys].Fill(fabs(l2.Eta()),weight*corr);
	      hMCLep2Eta[itoys].Fill(fabs(l2.Eta()),weight*corr);
	    }
	}//end MC
      } //end category
	}//end toys
    }//end loop ientry
    
    delete infile;
    infile=0, intree=0;
  } // end loop ifile

  

  outFile->cd();

  for(int itoys=0;itoys!=NTOYS;++itoys)
    {
  hDataZPt[itoys].Write();
  hEWKZPt[itoys].Write();
  hTopZPt[itoys].Write();

  hDataPhiStar[itoys].Write();
  hEWKPhiStar[itoys].Write();
  hTopPhiStar[itoys].Write();
 
  hDataZRap[itoys].Write();
  hEWKZRap[itoys].Write();
  hTopZRap[itoys].Write();
 
  hDataLep1Pt[itoys].Write();
  hEWKLep1Pt[itoys].Write();
  hTopLep1Pt[itoys].Write();
  
  hDataLep2Pt[itoys].Write();
  hEWKLep2Pt[itoys].Write();
  hTopLep2Pt[itoys].Write();

  hDataLepNegPt[itoys].Write();
  hEWKLepNegPt[itoys].Write();
  hTopLepNegPt[itoys].Write();

  hDataLepPosPt[itoys].Write();
  hEWKLepPosPt[itoys].Write();
  hTopLepPosPt[itoys].Write();
 
  hDataLep1Eta[itoys].Write();
  hEWKLep1Eta[itoys].Write();
  hTopLep1Eta[itoys].Write();
  
  hDataLep2Eta[itoys].Write();
  hEWKLep2Eta[itoys].Write();
  hTopLep2Eta[itoys].Write();
    }
  
  outFile->Write();
  outFile->Close(); 

  
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
  


  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;  
  cout << endl;

  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;     

  gBenchmark->Show("plotZmmResScaleUncert");
}
Exemplo n.º 21
0
int main(int argc, char *argv[])
{
    TRandom rng;
    rng.SetSeed(2014);
    hxx_tree data;

    std::string opt, infile, outroot, outdir;
    koptions options(argc, argv);

    //check for the --help option:
    if ( options.find("--help") ) {
        usage();
    }
    //options.set("--seed=", seed);
    //if (seed > 0) rng.SetSeed(seed);
    double met_smear = 30.0;
    options.set("--met_smear=", met_smear);
    int    num_smear = 1;
    options.set("--num_smear=", num_smear);
    double fake_rate = 0.0;
    options.set("--fake_rate=", fake_rate);
    int mode_8tev = options.find("--8tev");
    int pub_plots = options.find("--pub_plots");



    double lumi = 300;
    double met_cut = 250.0;

    if (mode_8tev) {
        lumi = 20.0;
        met_cut = 250;
        cout << "INFO:  settings for sqrt(s) = 8 TeV\n";
    } else {
        cout << "INFO:  settings for sqrt(s) = 14 TeV\n";
    }
    cout << "INFO:  lumi:     " << lumi << "\n";
    cout << "INFO:  MET cut:  " << met_cut << "\n";

    //check for unrecognized options (beginning with -- or -)
    while(options.unrecognized_option(opt)) {
        cout << "WARNING: unrecognized option:" << opt << "\n";
        usage();
    }

    if (options.size() != 3) {
        usage();
    }

    options.shift_argument(infile);
    options.shift_argument(outroot);
    options.shift_argument(outdir);

    cout << "INFO: reading analysis tree file:    " << infile  << "\n";
    cout << "INFO: writing histogram root file:   " << outroot << "\n";
    cout << "INFO: writing results to directory:  " << outdir  << "\n";
    cout << "INFO: MET smearing amount is " << met_smear << "\n";
    cout << "INFO: MET smearing number is " << num_smear << "\n";
    cout << "INFO: W+jets fake rate is " << fake_rate << "\n";

    auto_write aw;

    cutflow_tool cutflow;
    histogram_manager h0mll(new TH1F("h0mll","",60,60.0,120.0));

    if (pub_plots) {
        h0mll.add_sample(1,  "_z");
        h0mll.add_sample(2,  "_h");
        h0mll.add_sample(3,  "_w");
        h0mll.add_sample(4,  "_top");

        cutflow.add_sample_name(1, "Z,ZZ,ZW");
        cutflow.add_sample_name(2, "Higgs");
        cutflow.add_sample_name(3, "W,WW");
        cutflow.add_sample_name(4, "tt");
    } else {
        h0mll.add_sample(1,  "_zjj");
        h0mll.add_sample(2,  "_zz_zw");
        h0mll.add_sample(3,  "_ww");
        h0mll.add_sample(4,  "_tt");
        h0mll.add_sample(5,  "_hzz");
        h0mll.add_sample(6,  "_zh");
        h0mll.add_sample(7,  "_wh");
        h0mll.add_sample(8,  "_wjjj");

        cutflow.add_sample_name(1, "Zjj");
        cutflow.add_sample_name(2, "ZZ,ZW");
        cutflow.add_sample_name(3, "WW");
        cutflow.add_sample_name(4, "tt");
        cutflow.add_sample_name(5, "HZZ");
        cutflow.add_sample_name(6, "ZH");
        cutflow.add_sample_name(7, "WH");
        cutflow.add_sample_name(8, "W+jets");
    }




    h0mll.add_sample(20,  "_hxx1");
    h0mll.add_sample(21,  "_hxx10");
    h0mll.add_sample(22,  "_hxx100");
    h0mll.add_sample(23,  "_hxx500");
    h0mll.add_sample(24,  "_hxx1000");

    cutflow.add_sample_name(20, "HXX1");
    cutflow.add_sample_name(21, "HXX10");
    cutflow.add_sample_name(22, "HXX100");
    cutflow.add_sample_name(23, "HXX500");
    cutflow.add_sample_name(24, "HXX1000");


    h0mll.add_sample(30,  "_hzp_100_1");
    h0mll.add_sample(31,  "_hzp_100_10");
    h0mll.add_sample(32,  "_hzp_100_100");
    h0mll.add_sample(33,  "_hzp_100_500");
    h0mll.add_sample(34,  "_hzp_100_1000");
    h0mll.add_sample(35,  "_hzp_1000_1");
    h0mll.add_sample(36,  "_hzp_1000_10");
    h0mll.add_sample(37,  "_hzp_1000_100");
    h0mll.add_sample(38,  "_hzp_1000_500");
    h0mll.add_sample(39,  "_hzp_1000_1000");

    cutflow.add_sample_name(30, "HZP_100_1");
    cutflow.add_sample_name(31, "HZP_100_10");
    cutflow.add_sample_name(32, "HZP_100_100");
    cutflow.add_sample_name(33, "HZP_100_500");
    cutflow.add_sample_name(34, "HZP_100_1000");
    cutflow.add_sample_name(35, "HZP_1000_1");
    cutflow.add_sample_name(36, "HZP_1000_10");
    cutflow.add_sample_name(37, "HZP_1000_100");
    cutflow.add_sample_name(38, "HZP_1000_500");
    cutflow.add_sample_name(39, "HZP_1000_1000");


    h0mll.add_sample(40,  "_hzpzp_100_1");
    h0mll.add_sample(41,  "_hzpzp_100_10");
    h0mll.add_sample(42,  "_hzpzp_100_100");
    h0mll.add_sample(43,  "_hzpzp_100_500");
    h0mll.add_sample(44,  "_hzpzp_100_1000");
    h0mll.add_sample(45,  "_hzpzp_1000_1");
    h0mll.add_sample(46,  "_hzpzp_1000_10");
    h0mll.add_sample(47,  "_hzpzp_1000_100");
    h0mll.add_sample(48,  "_hzpzp_1000_500");
    h0mll.add_sample(49,  "_hzpzp_1000_1000");

    cutflow.add_sample_name(40, "HZPZP_100_1");
    cutflow.add_sample_name(41, "HZPZP_100_10");
    cutflow.add_sample_name(42, "HZPZP_100_100");
    cutflow.add_sample_name(43, "HZPZP_100_500");
    cutflow.add_sample_name(44, "HZPZP_100_1000");
    cutflow.add_sample_name(45, "HZPZP_1000_1");
    cutflow.add_sample_name(46, "HZPZP_1000_10");
    cutflow.add_sample_name(47, "HZPZP_1000_100");
    cutflow.add_sample_name(48, "HZPZP_1000_500");
    cutflow.add_sample_name(49, "HZPZP_1000_1000");


    h0mll.add_auto_write(aw);


    TH1F hfit_bkg("sample_1","",  100,0.0,300.0);
    TH1F hfit_sig20("signal20","",  100,0.0,300.0);
    TH1F hfit_sig21("signal21","",  100,0.0,300.0);
    TH1F hfit_sig22("signal22","",  100,0.0,300.0);
    TH1F hfit_sig23("signal23","",  100,0.0,300.0);
    TH1F hfit_sig24("signal24","",  100,0.0,300.0);

    int    nsig = 0;
    double wsig = 0.0;
    hfit_bkg.Sumw2();
    hfit_sig20.Sumw2();
    hfit_sig21.Sumw2();
    hfit_sig22.Sumw2();
    hfit_sig23.Sumw2();
    hfit_sig24.Sumw2();

    //control plots (no pre-selection)
    histogram_manager hcnjet  (new TH1F("hcnjet",  "", 10,  0.0, 10.0),     h0mll, aw);
    histogram_manager hcmjjon (new TH1F("hcmjjon", "", 75,  0.0, 150.0),    h0mll, aw);
    histogram_manager hcmjjoff(new TH1F("hcmjjoff","", 100, 0.0, 500.0),    h0mll, aw);

    //test new variables
    histogram_manager htestx  (new TH1F("htestx",  "", 25,  0.0, 3.2),      h0mll, aw);
    histogram_manager htesty  (new TH1F("htesty",  "", 25,  0.0, 200.0),    h0mll, aw);

    //histograms at stage 0
    histogram_manager h0mjj   (new TH1F("h0mjj",   "", 100, 0.0,  500.0),   h0mll, aw);
    histogram_manager h0mlj   (new TH1F("h0mlj",   "", 100, 0.0,  500.0),   h0mll, aw);
    histogram_manager h0mlljj (new TH1F("h0mlljj", "", 100, 0.0,  500.0),  h0mll, aw);
    histogram_manager h0mllj  (new TH1F("h0mllj",  "", 100, 0.0,  500.0),   h0mll, aw);
    histogram_manager h0met   (new TH1F("h0met",   "", 100, 0.0,  300.0),   h0mll, aw);
    histogram_manager h0njet  (new TH1F("h0njet",  "", 10,  0.0,  10.0),    h0mll, aw);
    histogram_manager h0nbjet (new TH1F("h0nbjet", "", 8,   0.0,  8.0),     h0mll, aw);
    histogram_manager h0jdphi (new TH1F("h0jdphi", "", 100, 0.0,  3.2),     h0mll, aw);
    histogram_manager h0ptja  (new TH1F("h0ptja","", 32, 0.0,  300.0),   h0mll, aw);
    histogram_manager h0drlla (new TH1F("h0drlla","", 81,  0.0,  8.1),     h0mll, aw);
    histogram_manager h0drllb (new TH1F("h0drllb","", 81,  0.0,  8.1),     h0mll, aw);
    histogram_manager h0dphizz     (new TH1F("h0dphizz",     "", 32, 0.0, 3.2), h0mll, aw);
    histogram_manager h0dphizllmet (new TH1F("h0dphizllmet", "", 32, 0.0, 3.2), h0mll, aw);


    histogram_manager h0ht   (new TH1F("h0ht",    "", 100, 0.0, 500.0), h0mll, aw);
    histogram_manager h0l1pt (new TH1F("h0l1pt",  "", 100, 0.0, 300.0), h0mll, aw);
    histogram_manager h0l2pt (new TH1F("h0l2pt",  "", 100, 0.0, 300.0), h0mll, aw);
    histogram_manager h0j1pt (new TH1F("h0j1pt",  "", 100, 0.0, 300.0), h0mll, aw);
    histogram_manager h0j2pt (new TH1F("h0j2pt",  "", 100, 0.0, 300.0), h0mll, aw);

    histogram_manager h0l1eta(new TH1F("h0l1eta","", 60, -3.0, 3.0), h0mll, aw);
    histogram_manager h0l2eta(new TH1F("h0l2eta","", 60, -3.0, 3.0), h0mll, aw);
    histogram_manager h0j1eta(new TH1F("h0j1eta","", 60, -3.0, 3.0), h0mll, aw);
    histogram_manager h0j2eta(new TH1F("h0j2eta","", 60, -3.0, 3.0), h0mll, aw);

    //histograms at stage 1
    histogram_manager h1mll   (new TH1F("h1mll",   "", 60, 60.0,  120.0),   h0mll, aw);
    histogram_manager h1mjj   (new TH1F("h1mjj",   "", 100, 0.0,  500.0),   h0mll, aw);
    histogram_manager h1mlj   (new TH1F("h1mlj",   "", 100, 0.0,  500.0),   h0mll, aw);
    histogram_manager h1mlljj (new TH1F("h1mlljj", "", 100, 0.0,  500.0),  h0mll, aw);
    histogram_manager h1mllj  (new TH1F("h1mllj",  "", 100, 0.0,  500.0),   h0mll, aw);
    histogram_manager h1met   (new TH1F("h1met",   "", 100, 0.0,  300.0),   h0mll, aw);
    histogram_manager h1njet  (new TH1F("h1njet",  "", 10,  0.0,  10.0),    h0mll, aw);
    histogram_manager h1nbjet (new TH1F("h1nbjet", "", 8,   0.0,  8.0),     h0mll, aw);
    histogram_manager h1jdphi (new TH1F("h1jdphi", "", 100, 0.0,  3.2),     h0mll, aw);
    histogram_manager h1ptja  (new TH1F("h1ptja","", 100, 0.0,  300.0),   h0mll, aw);
    histogram_manager h1drlla (new TH1F("h1drlla","", 81,  0.0,  8.1),     h0mll, aw);
    histogram_manager h1drllb (new TH1F("h1drllb","", 81,  0.0,  8.1),     h0mll, aw);
    histogram_manager h1dphizz     (new TH1F("h1dphizz",     "", 100, 0.0, 3.2), h0mll, aw);
    histogram_manager h1dphizllmet (new TH1F("h1dphizllmet", "", 100, 0.0, 3.2), h0mll, aw);

    cout << "INFO: opening file: " << infile << "\n";

    TFile * file = new TFile(infile.c_str());
    TTree * tree = (TTree*) file->Get("hxxtree");

    if (! tree) {
        cout << "ERROR:  could not open tree.\n";
        exit(0);
    }

    data.ReadTree(tree);
    long int numberOfEntries = tree->GetEntries();

    //tree->Print();

    int count = 0;
    int nupdate = numberOfEntries / 20;
    if (nupdate < 1) nupdate=1;
    cout << "PROGRESS:  ";

    int prescale  = 0;
    int iprescale = 0;
    // Loop over all events
    for(Int_t entry = 0; entry < numberOfEntries; ++entry)
    {
        count++;
        if (count % nupdate == 0) {
            cout << ".";
            cout.flush();
        }

        if (iprescale < prescale) {
            iprescale++;
            continue;
        } else {
            iprescale = 0;
        }

        tree->GetEntry(entry);


        int num_smear_event = num_smear;
        if (data.sample == 1) {
            num_smear_event = num_smear * 10;
        }
        //if (data.sample == 4) {
        //num_smear_event = num_smear * 10;
        //}
        //if (data.sample == 3) {
        //num_smear_event = num_smear * 10;
        //}


        // First, apply W+jets fake rate if applicable:
        if (fake_rate > 0.0 && data.sample == 8) {
            apply_fake_rate(rng, data, fake_rate);
        }

        // remap sample id for publication plots:
        if (pub_plots) {
            switch (data.sample) {
            case 1:
                data.sample = 1;
                break;
            case 2:
                data.sample = 1;
                break;
            case 3:
                data.sample = 3;
                break;
            case 4:
                data.sample = 4;
                break;
            case 5:
                data.sample = 2;
                break;
            case 6:
                data.sample = 2;
                break;
            case 7:
                data.sample = 2;
                break;
            case 8:
                data.sample = 3;
                break;
            }
        }


        double mjjon;
        control_vars(data, mjjon);
        if (mjjon > 0.0) hcmjjon.Fill(data.sample, mjjon, data.weight);
        hcnjet.Fill(data.sample, data.jet_pt->size(), data.weight);


        //if (data.l1_pt < 12.0) continue;
        //if (data.l2_pt < 12.0) continue;

        if (data.l1_pt < 20.0) continue;
        if (data.l2_pt < 15.0) continue;

        // prune jet list according to analysis selection:
        for (int i=0; i<data.jet_pt->size(); i++) {
            int veto = 0;
            if (data.jet_pt->at(i) < 15.0) veto = 1;
            if (fabs(data.jet_eta->at(i)) > 2.5) veto = 1;
            if (veto) {
                data.erase_jet(i);
                i--;
            }
        }
        if (data.jet_pt->size() != data.jet_btag->size()) {
            cout << "ERROR:  Jet vectors out of sync.  Something is wrong.\n";
            exit(0);
        }

        int nbtag = 0;
        for (int i=0; i<data.jet_btag->size(); i++) {
            if (data.jet_btag->at(i)) nbtag++;
        }

        //preselection cuts:
        if (data.jet_pt->size() < 2) continue;
        if (data.nmuon + data.nelec > 2) continue;


        // checking 2-jet bin:
        //if (data.jet_pt->size() > 2) continue;

        cutflow.increment(0, data.sample, data.weight);


        double mlj, pt_ja, dr_lla, dr_llb, mjj, mjj_off, mllj, mlljj, dphi_zz, zll_phi, x, y;
        best_mlj(data, mlj);
        kinematic_vars(data, pt_ja, dr_lla, dr_llb, mjj, mjj_off, mllj, mlljj, dphi_zz, zll_phi, x, y);

        if (mjj_off > 0.0) {
            hcmjjoff.Fill(data.sample, mjj_off, data.weight);
        }

        // Here we smear the MET to account for pile-up effects:
        vector<double> met;
        vector<double> met_phi;
        vector<double> jet_dphi;
        vector<double> zllmet_dphi;

        // use reduced weight when looping over entire MET vector:
        double met_weight = (data.weight / (double) num_smear_event);
        double nopu_metx = data.nopu_met * cos(data.nopu_met_phi);
        double nopu_mety = data.nopu_met * sin(data.nopu_met_phi);

        for (int i=0; i<num_smear_event; i++) {
            double metx            = nopu_metx + rng.Gaus() * met_smear;
            double mety            = nopu_mety + rng.Gaus() * met_smear;
            double new_met         = sqrt(metx*metx + mety*mety);
            double new_met_phi     = atan2(mety, metx);
            int min_i;
            double new_jet_dphi    = min_delta_phi(new_met_phi, *data.jet_phi, min_i,-1,1);
            double new_zllmet_dphi = delta_phi(new_met_phi, zll_phi);
            met.push_back(new_met);
            met_phi.push_back(new_met_phi);
            jet_dphi.push_back(new_jet_dphi);
            zllmet_dphi.push_back(new_zllmet_dphi);
        }

        // high MET test:
        //if (data.nopu_met < 100.0) continue;

        h0mll.Fill(data.sample, data.mll, data.weight);




        if (data.jet_pt->size() > 0) {
            h0j1pt  .Fill(data.sample, data.jet_pt ->at(0), data.weight);
            h0j1eta .Fill(data.sample, data.jet_eta->at(0), data.weight);
        }
        if (data.jet_pt->size() > 1) {
            h0j2pt  .Fill(data.sample, data.jet_pt ->at(1), data.weight);
            h0j2eta .Fill(data.sample, data.jet_eta->at(1), data.weight);
        }
        h0l1pt  .Fill(data.sample, data.l1_pt,  data.weight);
        h0l1eta .Fill(data.sample, data.l1_eta, data.weight);
        h0l2pt  .Fill(data.sample, data.l2_pt,  data.weight);
        h0l2eta .Fill(data.sample, data.l2_eta, data.weight);

        h0njet.Fill(data.sample, data.jet_pt->size(), data.weight);
        h0nbjet.Fill(data.sample, nbtag, data.weight);

        h0mjj.Fill(data.sample, mjj, data.weight);
        h0mlj.Fill(data.sample, mlj, data.weight);
        h0mlljj.Fill(data.sample, mlljj, data.weight);
        h0mllj.Fill(data.sample, mllj, data.weight);
        h0ht.Fill(data.sample, data.ht, data.weight);
        h0dphizz .Fill(data.sample, dphi_zz, data.weight);

        h0ptja   .Fill(data.sample, pt_ja,  data.weight);
        h0drlla  .Fill(data.sample, dr_lla, data.weight);
        h0drllb  .Fill(data.sample, dr_llb, data.weight);




        htestx .Fill(data.sample, x);
        htesty .Fill(data.sample, y);

        for (int i=0; i<met.size(); i++) {
            h0met        .Fill(data.sample, met[i],          met_weight);
            h0jdphi      .Fill(data.sample, jet_dphi[i],     met_weight);
            h0dphizllmet .Fill(data.sample, zllmet_dphi[i] , met_weight);
        }



        // Z-peak:
        if (data.mll < 82)  continue;
        if (data.mll > 98) continue;
        cutflow.increment(1, data.sample, data.weight);
        if (mllj > 124.0)  continue;
        cutflow.increment(2, data.sample, data.weight);
        if (dphi_zz > 2.25)  continue;
        cutflow.increment(3, data.sample, data.weight);
        //if (mlj > 60.0)  continue;
        // These two cuts are applied in MET loop... 0 = no cut
        double jet_dphi_cut = 0.0;
        double zllmet_dphi_cut = 0.0;
        //if (mlj > 120.0)  continue;
        //






        h1njet.  Fill(data.sample, data.jet_pt->size(), data.weight);
        h1mll.   Fill(data.sample, data.mll,            data.weight);
        h1mjj.   Fill(data.sample, mjj,                 data.weight);
        h1mlj.   Fill(data.sample, mlj,                 data.weight);
        h1mlljj. Fill(data.sample, mlljj,               data.weight);
        h1mllj.  Fill(data.sample, mllj,                data.weight);
        h1ptja.  Fill(data.sample, pt_ja,  data.weight);
        h1drlla. Fill(data.sample, dr_lla, data.weight);
        h1drllb. Fill(data.sample, dr_llb, data.weight);


        for (int i=0; i<met.size(); i++) {
            double tmet =met[i];
            if (tmet > 299.0) tmet = 299.;

            h1jdphi .Fill(data.sample, jet_dphi[i], met_weight);
            h1dphizllmet .Fill(data.sample, zllmet_dphi[i] , met_weight);
            if (jet_dphi[i]   < jet_dphi_cut) continue; // APPEARS IN TWO PLACES
            if (zllmet_dphi[i] < zllmet_dphi_cut) continue; // APPEARS IN TWO PLACES
            h1met.Fill(data.sample, tmet, met_weight);
        }

        // fill limit setting histograms:
        for (int i=0; i<met.size(); i++) {
            if (met_weight > 100) {
                cout << "WARNING:  large weight at MET stage:  " << met_weight << "\n";
            }
            double tmet =met[i];
            if (tmet > 299.0) tmet = 299.;

            if (jet_dphi[i]   < jet_dphi_cut) continue; // APPEARS IN TWO PLACES
            if (zllmet_dphi[i] < zllmet_dphi_cut) continue; // APPEARS IN TWO PLACES
            if (data.sample < 20)  hfit_bkg.Fill(tmet, met_weight);
            if (data.sample == 20) hfit_sig20.Fill(tmet, met_weight);
            if (data.sample == 21) hfit_sig21.Fill(tmet, met_weight);
            if (data.sample == 22) hfit_sig22.Fill(tmet, met_weight);
            if (data.sample == 23) hfit_sig23.Fill(tmet, met_weight);
            if (data.sample == 24) hfit_sig24.Fill(tmet, met_weight);

            if (met[i] > met_cut)
                cutflow.increment(4, data.sample, met_weight);
        }
    }
    cout << "\n";

    cout << "SUMMARY:  read " << count << " of " << tree->GetEntries() << " events from analysis tree.\n";

    TFile * foutroot = new TFile(outroot.c_str(), "RECREATE");
    foutroot->cd();
    aw.WriteAll();
    foutroot->Close();

    //cout << "SUMMARY:  done writing files.\n";

    cout << "Cutflow:  Stage 0 (lljj preselection)\n";
    cutflow.print(0);

    cout << "Cutflow:  Stage 1 (mll cut)\n";
    cutflow.print(1);

    cout << "Cutflow:  Stage 2 (after mjj cut) \n";
    cutflow.print(2);

    cout << "Cutflow:  Stage 3 (after mjjll cut) \n";
    cutflow.print(3);

    cout << "Cutflow:  Stage 4 (after MET cut) \n";
    cutflow.print(4);

    cout << "Fit Histogram Summary:  \n";
    double SIGTOT = lumi * 149.8;
    hfit_sig20.Scale(1.0/SIGTOT);
    hfit_sig21.Scale(1.0/SIGTOT);
    hfit_sig22.Scale(1.0/SIGTOT);
    hfit_sig23.Scale(1.0/SIGTOT);
    hfit_sig24.Scale(1.0/SIGTOT);
    cout << " -> using total signal events of :    " << SIGTOT << "\n";
    cout << " -> background integral (evts):       " << hfit_bkg.GetSumOfWeights() << "\n";
    cout << " -> signal 1    integral (eff):       " << hfit_sig20.GetSumOfWeights() << "\n";
    cout << " -> signal 10   integral (eff):       " << hfit_sig21.GetSumOfWeights() << "\n";
    cout << " -> signal 100  integral (eff):       " << hfit_sig22.GetSumOfWeights() << "\n";
    cout << " -> signal 500  integral (eff):       " << hfit_sig23.GetSumOfWeights() << "\n";
    cout << " -> signal 1000 integral (eff):       " << hfit_sig24.GetSumOfWeights() << "\n";
    cout << " -> local count of signal events:     " << nsig << "\n";
    cout << " -> local integral of signal weight:  " << wsig << "\n";

    cout << " --> signal 1    sensitivity:  " << sensitivity(&hfit_sig20, &hfit_bkg, SIGTOT) << "\n";
    cout << " --> signal 10   sensitivity:  " << sensitivity(&hfit_sig21, &hfit_bkg, SIGTOT) << "\n";
    cout << " --> signal 100  sensitivity:  " << sensitivity(&hfit_sig22, &hfit_bkg, SIGTOT) << "\n";
    cout << " --> signal 500  sensitivity:  " << sensitivity(&hfit_sig23, &hfit_bkg, SIGTOT) << "\n";
    cout << " --> signal 1000 sensitivity:  " << sensitivity(&hfit_sig24, &hfit_bkg, SIGTOT) << "\n";

    char name[100];
    TFile * f = NULL;
    TH1F * h = NULL;

    sprintf(name, "%s/mchi1.root", outdir.c_str());
    f = new TFile(name, "RECREATE");
    f->cd();
    h = (TH1F *) hfit_sig20.Clone("signal");
    h->Write();
    hfit_bkg.Write();
    f->Close();

    sprintf(name, "%s/mchi10.root", outdir.c_str());
    f = new TFile(name, "RECREATE");
    f->cd();
    h = (TH1F *) hfit_sig21.Clone("signal");
    h->Write();
    hfit_bkg.Write();
    f->Close();

    sprintf(name, "%s/mchi100.root", outdir.c_str());
    f = new TFile(name, "RECREATE");
    f->cd();
    h = (TH1F *) hfit_sig22.Clone("signal");
    h->Write();
    hfit_bkg.Write();
    f->Close();

    sprintf(name, "%s/mchi500.root", outdir.c_str());
    f = new TFile(name, "RECREATE");
    f->cd();
    h = (TH1F *) hfit_sig23.Clone("signal");
    h->Write();
    hfit_bkg.Write();
    f->Close();

    sprintf(name, "%s/mchi1000.root", outdir.c_str());
    f = new TFile(name, "RECREATE");
    f->cd();
    h = (TH1F *) hfit_sig24.Clone("signal");
    h->Write();
    hfit_bkg.Write();
    f->Close();



}
Exemplo n.º 22
0
void filter(const int type){
  int M_MODE = 0;
  TChain* tree = new TChain("TEvent");
  string fname;
  switch(type){
  case 0://Data
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_data.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_data.root");
    break;
  case 11://Signal MC pi0
    M_MODE = 1;
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_sigmcPI0_s7.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_sigmcPi0_s7.root");
    break;
  case 12://Signal MC eta
    M_MODE = 2;
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_sigmcETA_s2.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_sigmcEta_s2.root");
    break;
  case 13://Signal MC omega
    M_MODE = 3;
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_sigmcOMEGA_s5.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_sigmcOmega_s5.root");
    break;
  case 14://Signal MC rho
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_sigmcRHO_s1.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_sigmcRho_s1.root");
    break;
  case 15://Signal MC eta'
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_sigmcETAP_s1.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_sigmcETAP_s1.root");
    break;
  case 21://charged
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charged_2.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charged_12.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_charged_2_12.root");
    break;
  case 22://mixed
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_mixed_2.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_mixed_12.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_mixed_2_12.root");
    break;
  case 23://charm
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charm_12.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charm_2.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_charm_2_12.root");
    break;
  case 24://uds
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_uds_12.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_uds_2.root");
    fname = string("/home/vitaly/B0toDh0/Tuples/fil_b2dh_uds_2_12.root");
    break;
  case 2://Generic MC
//    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_gen.root");
//    stringstream out;
//    string path("/home/vitaly/B0toDh0/Tuples/");
    vector<string> types;
    types.push_back(string("charged"));
    types.push_back(string("mixed"));
    types.push_back(string("uds"));
    types.push_back(string("charm"));
    for(int i=0; i<types.size(); i++){
      for(int j=0; j<1; j++){
        out.str("");
        out << path << "b2dh_" << types[i] << "_" << j << ".root";
        tree->Add(out.str().c_str());
      }
    }
    fname = string("fil_b2dh_gen_0_2.root");
    break;
  case 3://Continuum
//    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_cont.root");
    stringstream out;
    string path("/home/vitaly/B0toDh0/Tuples/");
    vector<string> types;
    types.push_back(string("uds"));
    types.push_back(string("charm"));
    for(int i=0; i<types.size(); i++){
      for(int j=0; j<6; j++){
        out.str("");
	    out << path << "b2dh_" << types[i] << "_" << j << ".root";
	    tree->Add(out.str().c_str());
	  }
    }
    fname = string("fil_b2dh_cont.root");
    break;
  case 4://Custom
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charged_10.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charged_0.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_mixed_10.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_mixed_0.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charged_11.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_charged_1.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_mixed_11.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/b2dh_mixed_1.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/fil_b2dh_charm_0_10.root");
    tree->Add("/home/vitaly/B0toDh0/Tuples/fil_b2dh_uds_0_10.root");
    fname = string("fil_b2dh_gen.root");
    break;
  default:
    return;
  }
  Double_t p_d0,p_h0,p_ks,p_pi0_h0,p_pip_h0,p_pim_h0,pi0_chi2,egamma,cos_thr,cos_hel,thr_sig,thr_oth;
  Int_t ndf_tag_vtx,phsp,bin,exp,run,evtn;
  Int_t b0f,d0f;
  Double_t k0mm2,k0et,k0hso00,k0hso02,k0hso04,k0hso10,k0hso12,k0hso14,k0hso20,k0hso22,k0hso24,k0hoo0,k0hoo1,k0hoo2,k0hoo3,k0hoo4;
  Double_t k1mm2,k1et,k1hso00,k1hso01,k1hso02,k1hso03,k1hso04,k1hso10,k1hso12,k1hso14,k1hso20,k1hso22,k1hso24,k1hoo0,k1hoo1,k1hoo2,k1hoo3,k1hoo4;

  Double_t mbc,de,mp,mm,dz,atckpi_max,mpi0,mh0,mk;
  Double_t ks_dr,ks_dz,ks_dphi,ks_fl,tag_LH,tag_LH_err;
  Double_t mp_mc,mm_mc,d0_t_mc,dt_mc,dz_mc,bin_mc,flv_mc,d0_flv_mc;
//  Double_t z_sig_d0;
//  Double_t sz_sig_d0;
//  Double_t dz_mc_sig_d0;
  Double_t chi2_vtx_d0, chi2_mass_d0;
  Int_t good_icpv;//,good_icpv_d0;

  Int_t mode,h0mode,h0f,pi0f;
  Double_t z_sig,z_asc;
  Double_t sz_sig,sz_asc;
  Int_t ntrk_sig,ntrk_asc,ndf_z_sig,ndf_z_asc;
  Double_t chisq_z_sig,chisq_z_asc,h0_chi2;
  Double_t cl_z_sig,cl_z_asc;
  Double_t costhB,costhBcms,Ecms;
  Double_t t_sig_mc,z_sig_mc,t_asc_mc,z_asc_mc;
  Double_t dz_mc_sig, dz_mc_asc;
  Double_t z_upsilon;
//  Double_t dz_pull_sig,dz_pull_sig_d0,dz_pull_asc;
  Int_t nptag;

  tree->Print();

  TFile *ofile = new TFile(fname.c_str(),"RECREATE");
  TTree* TEvent = new TTree("TEvent","TEvent");

  tree->SetBranchAddress("exp",&exp);
  tree->SetBranchAddress("run",&run);
  tree->SetBranchAddress("evtn",&evtn);

  tree->SetBranchAddress("p_d0",&p_d0);
  tree->SetBranchAddress("p_h0",&p_h0);
  tree->SetBranchAddress("p_ks",&p_ks);
  tree->SetBranchAddress("p_pi0_h0",&p_pi0_h0);
  tree->SetBranchAddress("p_pip_h0",&p_pip_h0);
  tree->SetBranchAddress("p_pim_h0",&p_pim_h0);
  tree->SetBranchAddress("egamma",&egamma);
  tree->SetBranchAddress("cos_thr",&cos_thr);
  tree->SetBranchAddress("cos_hel",&cos_hel);
  tree->SetBranchAddress("thr_sig",&thr_sig);
  tree->SetBranchAddress("thr_oth",&thr_oth);
  tree->SetBranchAddress("ndf_tag_vtx",&ndf_tag_vtx);
  tree->SetBranchAddress("thr_oth",&thr_oth);
  tree->SetBranchAddress("phsp",&phsp);
  tree->SetBranchAddress("bin",&bin);

  Double_t px_pim,py_pim,pz_pim;
  Double_t px_pip,py_pip,pz_pip;
  Double_t px_ks,py_ks,pz_ks;

  tree->SetBranchAddress("px_pim",&px_pim);
  tree->SetBranchAddress("py_pim",&py_pim);
  tree->SetBranchAddress("pz_pim",&pz_pim);
  tree->SetBranchAddress("px_pip",&px_pip);
  tree->SetBranchAddress("py_pip",&py_pip);
  tree->SetBranchAddress("pz_pip",&pz_pip);
  tree->SetBranchAddress("px_ks",&px_ks);
  tree->SetBranchAddress("py_ks",&py_ks);
  tree->SetBranchAddress("pz_ks",&pz_ks);

  TEvent->Branch("px_pim",&px_pim,"px_pim/D");
  TEvent->Branch("py_pim",&py_pim,"py_pim/D");
  TEvent->Branch("pz_pim",&pz_pim,"pz_pim/D");
  TEvent->Branch("px_pip",&px_pip,"px_pip/D");
  TEvent->Branch("py_pip",&py_pip,"py_pip/D");
  TEvent->Branch("pz_pip",&pz_pip,"pz_pip/D");
  TEvent->Branch("px_ks",&px_ks,"px_ks/D");
  TEvent->Branch("py_ks",&py_ks,"py_ks/D");
  TEvent->Branch("pz_ks",&pz_ks,"pz_ks/D");

  Int_t b0id,d0id,h0id,dst0id,dst0f,etapid,etapf;

  tree->SetBranchAddress("chi2_vtx_d0",&chi2_vtx_d0);
  tree->SetBranchAddress("chi2_mass_d0",&chi2_mass_d0);

  TEvent->Branch("chi2_vtx_d0",&chi2_vtx_d0,"chi2_vtx_d0/D");
  TEvent->Branch("chi2_mass_d0",&chi2_mass_d0,"chi2_mass_d0/D");
  TEvent->Branch("good_icpv",&good_icpv,"good_icpv/I");

  if(type){
    tree->SetBranchAddress("b0id",&b0id);
    tree->SetBranchAddress("b0f",&b0f);
    tree->SetBranchAddress("d0id",&d0id);
    tree->SetBranchAddress("d0f",&d0f);
    tree->SetBranchAddress("h0id",&h0id);
    tree->SetBranchAddress("h0f",&h0f);
    tree->SetBranchAddress("pi0f",&pi0f);
    tree->SetBranchAddress("dst0id",&dst0id);
    tree->SetBranchAddress("dst0f",&dst0f);
    tree->SetBranchAddress("etapid",&etapid);
    tree->SetBranchAddress("etapf",&etapf);

    TEvent->Branch("b0id",&b0id,"b0id/I");
    TEvent->Branch("b0f",&b0f,"b0f/I");
    TEvent->Branch("d0id",&d0id,"d0id/I");
    TEvent->Branch("d0f",&d0f,"d0f/I");
    TEvent->Branch("h0id",&h0id,"h0id/I");
    TEvent->Branch("h0f",&h0f,"h0f/I");
    TEvent->Branch("pi0f",&pi0f,"pi0f/I");
    TEvent->Branch("dst0id",&dst0id,"dst0id/I");
    TEvent->Branch("dst0f",&dst0f,"dst0f/I");
    TEvent->Branch("etapid",&etapid,"etapid/I");
    TEvent->Branch("etapf",&etapf,"etapf/I");

    Double_t mp_raw, mm_raw;
    if(type>10 && type<20 || type == 111){
      tree->SetBranchAddress("mp_mc",&mp_mc);
      tree->SetBranchAddress("mm_mc",&mm_mc);
      tree->SetBranchAddress("mp_raw",&mp_raw);
      tree->SetBranchAddress("mm_raw",&mm_raw);
      tree->SetBranchAddress("d0_t_mc",&d0_t_mc);
      tree->SetBranchAddress("z_upsilon",&z_upsilon);
      tree->SetBranchAddress("bin_mc",&bin_mc);
      tree->SetBranchAddress("flv_mc",&flv_mc);
      tree->SetBranchAddress("d0_flv_mc",&d0_flv_mc);

      tree->SetBranchAddress("t_sig_mc",&t_sig_mc);
      tree->SetBranchAddress("z_sig_mc",&z_sig_mc);
      tree->SetBranchAddress("t_asc_mc",&t_asc_mc);
      tree->SetBranchAddress("z_asc_mc",&z_asc_mc);

      TEvent->Branch("mp_mc",&mp_mc,"mp_mc/D");
      TEvent->Branch("mm_mc",&mm_mc,"mm_mc/D");
      TEvent->Branch("mp_raw",&mp_raw,"mp_raw/D");
      TEvent->Branch("mm_raw",&mm_raw,"mm_raw/D");
      TEvent->Branch("d0_t_mc",&d0_t_mc,"d0_t_mc/D");
      TEvent->Branch("dt_mc",&dt_mc,"dt_mc/D");
      TEvent->Branch("dz_mc",&dz_mc,"dz_mc/D");
      TEvent->Branch("dz_mc_sig",&dz_mc_sig,"dz_mc_sig/D");
      TEvent->Branch("dz_mc_asc",&dz_mc_asc,"dz_mc_asc/D");
//      TEvent->Branch("dz_pull_sig",&dz_pull_sig,"dz_pull_sig/D");
//      if(type == 12 || type == 13 || type == 14){
//        tree->SetBranchAddress("z_sig_d0",&z_sig_d0);
//        tree->SetBranchAddress("sz_sig_d0",&sz_sig_d0);

//        TEvent->Branch("good_icpv_d0",&good_icpv_d0,"good_icpv_d0/I");
//        TEvent->Branch("dz_mc_sig_d0",&dz_mc_sig_d0,"dz_mc_sig_d0/D");
//        TEvent->Branch("dz_pull_sig_d0",&dz_pull_sig_d0,"dz_pull_sig_d0/D");
//        TEvent->Branch("z_sig_d0",&z_sig_d0,"z_sig_d0/D");
//        TEvent->Branch("sz_sig_d0",&sz_sig_d0,"sz_sig_d0/D");
//      }
//      TEvent->Branch("dz_pull_asc",&dz_pull_asc,"dz_pull_asc/D");
      TEvent->Branch("bin_mc",&bin_mc,"bin_mc/I");
      TEvent->Branch("flv_mc",&flv_mc,"flv_mc/I");
      TEvent->Branch("d0_flv_mc",&d0_flv_mc,"d0_flv_mc/I");

      TEvent->Branch("t_sig_mc",&t_sig_mc,"t_sig_mc/D");
      TEvent->Branch("z_sig_mc",&z_sig_mc,"z_sig_mc/D");
      TEvent->Branch("t_asc_mc",&t_asc_mc,"t_asc_mc/D");
      TEvent->Branch("z_asc_mc",&z_asc_mc,"z_asc_mc/D");

    }
  }

  tree->SetBranchAddress("nptag",&nptag);
  tree->SetBranchAddress("mbc",&mbc);
  tree->SetBranchAddress("de",&de);
  tree->SetBranchAddress("mp",&mp);
  tree->SetBranchAddress("mm",&mm);
  tree->SetBranchAddress("atckpi_max",&atckpi_max);
  tree->SetBranchAddress("mh0_raw",&mh0);
  tree->SetBranchAddress("mpi0_raw",&mpi0);
  tree->SetBranchAddress("mks_raw",&mk);

  Double_t md, md_raw, md_fit, mdpip, mdpim;
  tree->SetBranchAddress("md0_raw",&md_raw);
  tree->SetBranchAddress("md0_fit",&md_fit);
  tree->SetBranchAddress("md0",&md);
  tree->SetBranchAddress("md0pip",&mdpip);
  tree->SetBranchAddress("md0pim",&mdpim);

  TEvent->Branch("md",&md,"md/D");
  TEvent->Branch("md_raw",&md_raw,"md_raw/D");
  TEvent->Branch("md_fit",&md_fit,"md_fit/D");
  TEvent->Branch("mdpip",&mdpip,"mdpip/D");
  TEvent->Branch("mdpim",&mdpim,"mdpim/D");

  Double_t mdst0, metap, dmdst0, dmetap;
  tree->SetBranchAddress("mdst0",&mdst0);
  tree->SetBranchAddress("dmdst0",&dmdst0);
  tree->SetBranchAddress("metap",&metap);
  tree->SetBranchAddress("dmetap",&dmetap);

  TEvent->Branch("mdst0",&mdst0,"mdst0/D");
  TEvent->Branch("dmdst0",&dmdst0,"dmdst0/D");
  TEvent->Branch("metap",&metap,"metap/D");
  TEvent->Branch("dmetap",&dmetap,"dmetap/D");

  tree->SetBranchAddress("mode",&mode);
  tree->SetBranchAddress("h0mode",&h0mode);

  tree->SetBranchAddress("z_sig",&z_sig);
  tree->SetBranchAddress("z_asc",&z_asc);

  tree->SetBranchAddress("sz_sig",&sz_sig);
  tree->SetBranchAddress("sz_asc",&sz_asc);

  tree->SetBranchAddress("ntrk_sig",&ntrk_sig);
  tree->SetBranchAddress("ntrk_asc",&ntrk_asc);
  tree->SetBranchAddress("ndf_z_sig",&ndf_z_sig);
  tree->SetBranchAddress("ndf_z_asc",&ndf_z_asc);

  tree->SetBranchAddress("chisq_z_sig",&chisq_z_sig);
  tree->SetBranchAddress("chisq_z_asc",&chisq_z_asc);
  tree->SetBranchAddress("cl_z_sig",&cl_z_sig);
  tree->SetBranchAddress("cl_z_asc",&cl_z_asc);

  tree->SetBranchAddress("pi0_chi2",&pi0_chi2);
  tree->SetBranchAddress("h0_chi2",&h0_chi2);

  TEvent->Branch("h0_chi2",&h0_chi2,"h0_chi2/D");
  TEvent->Branch("pi0_chi2",&pi0_chi2,"pi0_chi2/D");

  tree->SetBranchAddress("costhB",&costhB);
  tree->SetBranchAddress("costhBcms",&costhBcms);
  tree->SetBranchAddress("Ecms",&Ecms);

  tree->SetBranchAddress("tag_LH",&tag_LH);
  tree->SetBranchAddress("tag_LH_err",&tag_LH_err);

  tree->SetBranchAddress("k0mm2",&k0mm2);
  tree->SetBranchAddress("k0et",&k0et);
  tree->SetBranchAddress("k0hso00",&k0hso00);
  tree->SetBranchAddress("k0hso02",&k0hso02);
  tree->SetBranchAddress("k0hso04",&k0hso04);
  tree->SetBranchAddress("k0hso10",&k0hso10);
  tree->SetBranchAddress("k0hso12",&k0hso12);
  tree->SetBranchAddress("k0hso14",&k0hso14);
  tree->SetBranchAddress("k0hso20",&k0hso20);
  tree->SetBranchAddress("k0hso22",&k0hso22);
  tree->SetBranchAddress("k0hso24",&k0hso24);
  tree->SetBranchAddress("k0hoo0",&k0hoo0);
  tree->SetBranchAddress("k0hoo1",&k0hoo1);
  tree->SetBranchAddress("k0hoo2",&k0hoo2);
  tree->SetBranchAddress("k0hoo3",&k0hoo3);
  tree->SetBranchAddress("k0hoo4",&k0hoo4);

  tree->SetBranchAddress("k1mm2",&k1mm2);
  tree->SetBranchAddress("k1et",&k1et);
  tree->SetBranchAddress("k1hso00",&k1hso00);
  tree->SetBranchAddress("k1hso01",&k1hso01);
  tree->SetBranchAddress("k1hso02",&k1hso02);
  tree->SetBranchAddress("k1hso03",&k1hso03);
  tree->SetBranchAddress("k1hso04",&k1hso04);
  tree->SetBranchAddress("k1hso10",&k1hso10);
  tree->SetBranchAddress("k1hso12",&k1hso12);
  tree->SetBranchAddress("k1hso14",&k1hso14);
  tree->SetBranchAddress("k1hso20",&k1hso20);
  tree->SetBranchAddress("k1hso22",&k1hso22);
  tree->SetBranchAddress("k1hso24",&k1hso24);
  tree->SetBranchAddress("k1hoo0",&k1hoo0);
  tree->SetBranchAddress("k1hoo1",&k1hoo1);
  tree->SetBranchAddress("k1hoo2",&k1hoo2);
  tree->SetBranchAddress("k1hoo3",&k1hoo3);
  tree->SetBranchAddress("k1hoo4",&k1hoo4);

  TEvent->Branch("exp",&exp,"exp/I");
  TEvent->Branch("run",&run,"run/I");
  TEvent->Branch("evtn",&evtn,"evtn/I");

  TEvent->Branch("p_d0",&p_d0,"p_d0/D");
  TEvent->Branch("p_h0",&p_h0,"p_h0/D");
  TEvent->Branch("p_ks",&p_ks,"p_ks/D");
  TEvent->Branch("p_pi0_h0",&p_pi0_h0,"p_pi0_h0/D");
  TEvent->Branch("p_pip_h0",&p_pip_h0,"p_pip_h0/D");
  TEvent->Branch("p_pim_h0",&p_pim_h0,"p_pim_h0/D");
  TEvent->Branch("egamma",&egamma,"egamma/D");
  TEvent->Branch("cos_thr",&cos_thr,"cos_thr/D");
  TEvent->Branch("cos_hel",&cos_hel,"cos_hel/D");
  TEvent->Branch("thr_sig",&thr_sig,"thr_sig/D");
  TEvent->Branch("thr_oth",&thr_oth,"thr_oth/D");
  TEvent->Branch("ndf_tag_vtx",&ndf_tag_vtx,"ndf_tag_vtx/I");
  TEvent->Branch("thr_oth",&thr_oth,"thr_oth/D");
  TEvent->Branch("phsp",&phsp,"phsp/I");
  TEvent->Branch("bin",&bin,"bin/I");

  TEvent->Branch("nptag",&nptag,"nptag/I");
  TEvent->Branch("mbc",&mbc,"mbc/D");
  TEvent->Branch("de",&de,"de/D");
  TEvent->Branch("mp",&mp,"mp/D");
  TEvent->Branch("mm",&mm,"mm/D");
  TEvent->Branch("dz",&dz,"dz/D");

  TEvent->Branch("atckpi_max",&atckpi_max,"atckpi_max/D");
  TEvent->Branch("mh0",&mh0);
  TEvent->Branch("mpi0",&mpi0,"mpi0/D");
  TEvent->Branch("mk",&mk,"mk/D");

  TEvent->Branch("mode",&mode,"mode/I");
  TEvent->Branch("h0mode",&h0mode,"h0mode/I");

  TEvent->Branch("z_sig",&z_sig,"z_sig/D");
  TEvent->Branch("z_asc",&z_asc,"z_asc/D");
  TEvent->Branch("sz_sig",&sz_sig,"sz_sig/D");
  TEvent->Branch("sz_asc",&sz_asc,"sz_asc/D");

  TEvent->Branch("ntrk_sig",&ntrk_sig,"ntrk_sig/I");
  TEvent->Branch("ntrk_asc",&ntrk_asc,"ntrk_asc/I");
  TEvent->Branch("ndf_z_sig",&ndf_z_sig,"ndf_z_sig/I");
  TEvent->Branch("ndf_z_asc",&ndf_z_asc,"ndf_z_asc/I");

  TEvent->Branch("chisq_z_sig",&chisq_z_sig,"chisq_z_sig/D");
  TEvent->Branch("chisq_z_asc",&chisq_z_asc,"chisq_z_asc/D");
  TEvent->Branch("cl_z_sig",&cl_z_sig,"cl_z_sig/D");
  TEvent->Branch("cl_z_asc",&cl_z_asc,"cl_z_asc/D");

  TEvent->Branch("costhB",&costhB,"costhB/D");
  TEvent->Branch("costhBcms",&costhBcms,"costhBcms/D");
  TEvent->Branch("Ecms",&Ecms,"Ecm/D");

  TEvent->Branch("ks_dr",&ks_dr,"ks_dr/D");
  TEvent->Branch("ks_dz",&ks_dz,"ks_dz/D");
  TEvent->Branch("ks_dphi",&ks_dphi,"ks_dphi/D");
  TEvent->Branch("ks_fl",&ks_fl,"ks_fl/D");
  TEvent->Branch("tag_LH",&tag_LH,"tag_LH/D");
  TEvent->Branch("tag_LH_err",&tag_LH_err,"tag_LH_err/D");

  TEvent->Branch("k0mm2",&k0mm2,"k0mm2/D");
  TEvent->Branch("k0et",&k0et,"k0et/D");
  TEvent->Branch("k0hso00",&k0hso00,"k0hso00/D");
  TEvent->Branch("k0hso02",&k0hso02,"k0hso02/D");
  TEvent->Branch("k0hso04",&k0hso04,"k0hso04/D");
  TEvent->Branch("k0hso10",&k0hso10,"k0hso10/D");
  TEvent->Branch("k0hso12",&k0hso12,"k0hso12/D");
  TEvent->Branch("k0hso14",&k0hso14,"k0hso14/D");
  TEvent->Branch("k0hso20",&k0hso20,"k0hso20/D");
  TEvent->Branch("k0hso22",&k0hso22,"k0hso22/D");
  TEvent->Branch("k0hso24",&k0hso24,"k0hso24/D");
  TEvent->Branch("k0hoo0",&k0hoo0,"k0hoo0/D");
  TEvent->Branch("k0hoo1",&k0hoo1,"k0hoo1/D");
  TEvent->Branch("k0hoo2",&k0hoo2,"k0hoo2/D");
  TEvent->Branch("k0hoo3",&k0hoo3,"k0hoo3/D");
  TEvent->Branch("k0hoo4",&k0hoo4,"k0hoo4/D");

  TEvent->Branch("k1mm2",&k1mm2,"k1mm2/D");
  TEvent->Branch("k1et",&k1et,"k1et/D");
  TEvent->Branch("k1hso00",&k1hso00,"k1hso00/D");
  TEvent->Branch("k1hso01",&k1hso01,"k1hso01/D");
  TEvent->Branch("k1hso02",&k1hso02,"k1hso02/D");
  TEvent->Branch("k1hso03",&k1hso03,"k1hso03/D");
  TEvent->Branch("k1hso04",&k1hso04,"k1hso04/D");
  TEvent->Branch("k1hso10",&k1hso10,"k1hso10/D");
  TEvent->Branch("k1hso12",&k1hso12,"k1hso12/D");
  TEvent->Branch("k1hso14",&k1hso14,"k1hso14/D");
  TEvent->Branch("k1hso20",&k1hso20,"k1hso20/D");
  TEvent->Branch("k1hso22",&k1hso22,"k1hso22/D");
  TEvent->Branch("k1hso24",&k1hso24,"k1hso24/D");
  TEvent->Branch("k1hoo0",&k1hoo0,"k1hoo0/D");
  TEvent->Branch("k1hoo1",&k1hoo1,"k1hoo1/D");
  TEvent->Branch("k1hoo2",&k1hoo2,"k1hoo2/D");
  TEvent->Branch("k1hoo3",&k1hoo3,"k1hoo3/D");
  TEvent->Branch("k1hoo4",&k1hoo4,"k1hoo4/D");

  const int NTot = tree->GetEntries();
  for(int i=1; i<NTot; i++){
    if(!(i%10000)){ cout << i << " events" << endl;}
    tree->GetEvent(i);
    if((b0f == 0 || b0f<-1) && type) continue;
    if(M_MODE){
      if(M_MODE != mode) continue;
    }
//    if(type == 11){
//      if((b0f != 1) && (b0f != 5) && (b0f != 10)) continue;
//    }
//    if(type == 11 || type == 12 || type == 13 || type == 14){
//      if(b0f < 1) continue;
//    }
//    if(type == 3){
//      if(!(b0f != 1 && b0f != 10 && !(d0f == 1 && (b0f == 5 || b0f == 4)))) continue;
//    }
//    if(type == 2){

//    }
//    if(md_raw<(DMass-md_cut) || md_raw>(DMass+md_cut)) continue;
//    if(!(mode == 2 && h0mode == 10) && mode != 14){
//      if(mpi0<(Pi0Mass-mpi0_cut) || mpi0>(Pi0Mass+mpi0_cut)) continue;
//    }
    if(mk<(KMass-mk_cut) || mk>(KMass+mk_cut)) continue;
//    if(chi2_vtx_d0>1000) continue;

    z_sig *= 10; z_asc *=10;// z_sig_d0 *= 10;
//    dz_mc_sig_d0   = z_sig_d0-z_sig_mc;
    dz_mc_sig      = z_sig-z_sig_mc;
    dz_mc_asc      = z_asc-z_asc_mc;
    dz = z_sig - z_asc;
    dt_mc = t_sig_mc - t_asc_mc;
    dz_mc = z_sig_mc - z_asc_mc;
    sz_sig      = 10.*TMath::Sqrt(sz_sig);
//    sz_sig_d0   = 10.*TMath::Sqrt(sz_sig_d0);
    sz_asc      = 10.*TMath::Sqrt(sz_asc);
//    dz_pull_sig      = dz_mc_sig/sz_sig;
//    dz_pull_sig_d0   = dz_mc_sig_d0/sz_sig_d0;
//    dz_pull_asc      = dz_mc_asc/sz_asc;

    // * Standatd ICPV cuts * //
    good_icpv    = IsGoodICPV(ndf_z_sig,sz_sig,chisq_z_sig,ndf_z_asc,sz_asc,chisq_z_asc);
//    good_icpv_d0 = IsGoodICPV(0,sz_sig_d0,1,ndf_z_asc,sz_asc,chisq_z_asc);
    // * ////////////////// * //

    TEvent->Fill();
  }
  TEvent->Print();
  TEvent->Write();
  ofile->Close();
  return;
}
Exemplo n.º 23
0
int fitfunc(int *energy, int *gopt, int append, char* addname){
  if(setlogy==0){
    //double labelx[6]={380,800,1200,1700,2400,5000}, labely[6]={80,45,25,21,25,15}; //Position
  }else{
    //double labelx[6]={300,750,1400,1800,2700,5000}, labely[6]={130,75,50,30,25,5}; //Position
  }

  //void fitfunc(int energy[5], int gopt[5]){
  for(int i=0; i<6; i++){
    cout<<energy[i]<<" "<<gopt[i]<<endl;
  }
  
  if(histname=="p2p"){
    char* dirsim = "../output/rec";
  }else if(histname=="p3p"){
    //char* dirsim = "../output/rec_p3p";
    char* dirsim = "../output/rec";
    //char* direxp = "../expout/Feb12/h_SpectrumMINOS_wAdBk.root";
    //char* outname = Form("../output/fit/%i%i%i%i%i_%s%i",gopt[0],gopt[1],gopt[2],gopt[3],gopt[4],histname,energy[4]); // .pdf .png .C .root will be created
  }else{// if(histname=="h23"){
    char* dirsim = "../output/rec";
    //char* direxp = "../expout/Feb12/h_SpectrumMINOS_wAdBk.root";
    //char* outname = Form("../output/fit/%i%i%i%i%i_%s%i",gopt[0],gopt[1],gopt[2],gopt[3],gopt[4],histname,energy[4]); // .pdf .png .C .root will be created
  }

  char* outname = Form("../output/fit/%s_%i_%i_%i_%i_%i_%i%s",histname, energy[0],energy[1],energy[2],energy[3],energy[4],energy[5],addname); // .pdf .png .C .root will be created


  ofstream fpara(Form("%s_fitresult.txt",outname));
  if(append == 1){
    ofstream fitlist(Form("../output/fit/fitlist_%s%s.csv",histname,addname),ios_base::app);
  }else{
    ofstream fitlist(Form("../output/fit/fitlist_%s%s.csv",histname,addname));    
  fitlist<<"E0, E1, E2, E3, E4, E5, CS0, CS1, CS2, CS3, CS4, CS5, ER0, ER1, ER2, ER3, ER4, ER5, Chi-sq"<<endl;
  }
  
  gStyle->SetOptStat(kFALSE);
  
  gROOT->ProcessLine( ".L fit78Ni.h" );
  gStyle->SetOptStat(kFALSE);
  gStyle->SetPadGridX(false);
  gStyle->SetPadGridY(false);
  //gStyle->SetOptLogy(1);

  char temp[300];
  int minBin = 0;
  //int maxBin = 5500;
  int maxBin = 6000;
  int binning = 100;
  int numBin = (maxBin-minBin)/binning;
  
  //Id starts with one!!!
  int daliIDMin = 1;
  int daliIDMax = 186;

  //****************************************************************************
  // The simulated peaks
  TFile *sim[6];
  for(int i=0; i<6; i++){
    if(energy[i]>0){
      sim[i] = new TFile(Form("%s/%ikeV.root",dirsim,energy[i]));
    }else{
      sim[i] = new TFile(Form("%s/%ikeV.root",dirsim,2620));//dummy
      gopt[i] = 0;
    }
  }

  //The experimental data:
  TFile *exp[1];
  //exp[0] = new TFile(Form("%s/MINOStest.root",direxp));
  exp[0] = new TFile(direxp);

  TCanvas *fCanvas=new TCanvas("Canvas","Response function",700,700);
  fCanvas->SetBorderSize(0);
  fCanvas->SetBorderMode(0);
  fCanvas->SetFrameBorderMode(0);
  fCanvas->SetFrameFillColor(0);
  fCanvas->SetBottomMargin(0.15);
  fCanvas->SetLeftMargin(0.15);
  fCanvas->cd();

  TFile *fout = new TFile(Form("%s.root",outname),"RECREATE");
  fout->cd();

  // Main
  TPad *c_m = new TPad("c_m", "c_m",0.0,0.0,1.0,1.0);
  c_m->Draw();
  c_m->cd();
  c_m->SetFillColor(0);
  //c_m->SetFillStyle(0);
  c_m->SetBorderSize(0);
  c_m->SetRightMargin(0.05);
  c_m->SetTopMargin(0.03);
  c_m->SetBottomMargin(0.15);
  c_m->SetLeftMargin(0.15);
  if(setlogy>0) c_m->SetLogy();
  fCanvas->cd();

  //****************************************************************************
  //The simulated spectra:
  TH1F *hsim[6];
  for(int i=0;i<6;i++) {
    sprintf(temp,"hsim[%i]",i);  
    hsim[i] = new TH1F(temp,temp,numBin,minBin,maxBin);
    hsim[i] = (TH1F*)sim[i]->Get("h_doppler_addback[0]");
  }
  /*
  hsim[0] = (TH1F*)sim[0]->Get("h_doppler_addback[0]");
  hsim[1] = (TH1F*)sim[1]->Get("h_doppler_addback[0]");
  hsim[2] = (TH1F*)sim[2]->Get("h_doppler_addback[0]");
  hsim[3] = (TH1F*)sim[3]->Get("h_doppler_addback[0]");
  hsim[4] = (TH1F*)sim[4]->Get("h_doppler_addback[0]");
  */

  //The experimental spectra:
  TH1F *hexp[1];
  for(int i=0;i<1;i++) {
    sprintf(temp,"hexp[%i]",i);  
    hexp[i] = new TH1F(temp,temp,numBin,minBin,maxBin);
  }

  //Getting the experimental spectrum
  //78Ni
  hexp[0] = (TH1F*)exp[0]->Get(histname);
  //hexp[0] = (TH1F*)exp[0]->Get("h23;1");
  //hexp[0]->Rebin(2);

  
  for(int i=0;i<1;i++) {
    hexp[i]->SetStats(0);
    hexp[i]->SetFillColor(0);
    hexp[i]->SetLineColor(kBlue);
    hexp[i]->SetLineStyle(0);
    
    //hexp[i]->GetXaxis()->SetRangeUser(0,maxBin);
    hexp[i]->GetXaxis()->SetRangeUser(minBin,maxBin);
    //hexp[i]->GetXaxis()->SetRangeUser(0,6000);
    if(setlogy==0){
      hexp[i]->GetYaxis()->SetRangeUser(0,yrangemax);
    }else {
      hexp[i]->GetYaxis()->SetRangeUser(0.5,yrangemax);
    }

    hexp[i]->GetXaxis()->SetNdivisions(305);
    hexp[i]->GetYaxis()->SetNdivisions(305);
  
    hexp[i]->GetYaxis()->SetTitle(Form("Counts / %i keV",binning));
     hexp[i]->GetXaxis()->SetTitle("Energy (keV)");
    
    hexp[i]->GetXaxis()->SetTitleOffset(0.9);  
    hexp[i]->GetYaxis()->SetTitleOffset(0.9);
    
    hexp[i]->GetXaxis()->SetTitleFont(132);
    hexp[i]->GetYaxis()->SetTitleFont(132);
    
    /*
    hexp[i]->GetXaxis()->SetTitleSize(0.08);
    hexp[i]->GetYaxis()->SetTitleSize(0.08);
    
    hexp[i]->GetXaxis()->SetLabelSize(0.08);
    hexp[i]->GetYaxis()->SetLabelSize(0.08);
    */
    hexp[i]->GetXaxis()->SetTitleSize(0.05);
    hexp[i]->GetYaxis()->SetTitleSize(0.05);
    
    hexp[i]->GetXaxis()->SetLabelSize(0.05);
    hexp[i]->GetYaxis()->SetLabelSize(0.05);

    //How to get error bar for each bin
    hexp[i]->SetDefaultSumw2(kTRUE);
    

    hexp[i]->SetTitle("");
  }   
   
  //*****************************************************************************
  peak1g = new TGraph(hsim[0]);
  peak2g = new TGraph(hsim[1]);
  peak3g = new TGraph(hsim[2]);
  peak4g = new TGraph(hsim[3]);
  peak5g = new TGraph(hsim[4]);
  peak6g = new TGraph(hsim[5]);
  /*TGraph *peak1g = new TGraph(hsim[0]);
  TGraph *peak2g = new TGraph(hsim[1]);
  TGraph *peak3g = new TGraph(hsim[2]);
  TGraph *peak4g = new TGraph(hsim[3]);
  TGraph *peak5g = new TGraph(hsim[4]);
  */
  //******************Function Definition****************************************
  //*****************************************************************************
  const Double_t fitmin=300.;
  const Double_t fitmax=(Double_t)maxBin;//4000.;
   
  c_m->cd();
  TF1 *whole = new TF1( "whole", ex_respf,fitmin,fitmax,10);
  whole->SetParameters(0.0001,0.01,0.00,0.0001,0.001,0.001,3.,-1e-03,3,-1.e-3);
  //whole->SetParameters(0.0001,0.0001,0.0001, 5.9,-0.00080 );

  for(int i=0; i<6; i++){
    if(gopt[i]==1){
      whole->SetParLimits(i,0.0,parlimit[i]);
    }else{
      whole->FixParameter(i,0.0);
    }
  }
  whole->SetParLimits(6,0,10);
  whole->SetParLimits(7,-1e-02,0.);
  whole->SetParLimits(8,0,5);
  whole->SetParLimits(9,-1e-02,-1e-5);
  //whole->FixParameter(8,1.426);
  //whole->FixParameter(9,-8.1e-5);
  whole->SetLineColor(1);
  whole->SetLineWidth(2);
  whole->SetNpx(200); 
  hexp[0]->Fit(whole,"R LL");
  //hexp[0]->Fit(whole,"");
  //cout<<"test"<<endl;
  //hexp[0]->Draw("");

  //hexp[0]->GetXaxis()->SetRangeUser(0,5000);


  //fCanvas->Print(Form("%s.png",outname));

  fpara<<"Chisquare\t"<< whole->GetChisquare()<<endl;
  fpara<<"para\tvalue\terror\tfilename"<<endl;
  for(int para=0;para<10;para++){
    fpara<<para<<"\t"<<whole->GetParameter(para)<<"\t"<<whole->GetParError(para);
    if(para<6) {
      string strenergy =sim[para]->GetName();
      int itr = strenergy.find_last_of("/");
      strenergy.erase(0,itr+1);
      fpara<<"\t"<<strenergy;
    }
    fpara<<endl;
  }
  
  // fitlist<<"E0, E1, E2, E3, E4, CS0, CS1, CS2, CS3, CS4, ER0, ER1, ER2, ER3, ER4, Chi-sq"<<endl;
  for(int i=0; i<6; i++) gopt[i]==1? fitlist<<energy[i]<<", ": fitlist<<"0, ";
  for(int i=0; i<6; i++) gopt[i]==1? fitlist<<genevts*whole->GetParameter(i)*CSincl/tot78Ni<<", ": fitlist<<"0, ";
  for(int i=0; i<6; i++){gopt[i]==1?
      fitlist<<sqrt(pow(whole->GetParError(i)*CSincl,2.) //Error from fitting
		    //+whole->GetParameter(i)*pow(CSincl,2) //Statistical error for the events (included?
		    //+pow(whole->GetParameter(i)*CSinclerr,2) // Inclusive cross section error
		    )*genevts/tot78Ni<<", " 
      :fitlist<<"0, ";
      }
  fitlist<<whole->GetChisquare()<<endl;

  //RT end


  TF1 *peak1f= new TF1( "peak1f", resp1,fitmin,fitmax,1);
  peak1f->SetParameter(0,whole->GetParameter(0) );
  peak1f->SetLineColor(2);
  peak1f->SetLineWidth(2);
  peak1f->SetLineStyle(9);
  peak1f->Draw("same");

  TF1 *peak2f= new TF1( "peak2f", resp2,fitmin,fitmax,1);
  peak2f->SetParameter(0,whole->GetParameter(1) );
  peak2f->SetLineColor(2);
  peak2f->SetLineWidth(2);
  peak2f->SetLineStyle(9);
  peak2f->Draw("same");

  //
  TF1 *peak3f= new TF1( "peak3f", resp3,fitmin,fitmax,1);
  peak3f->SetParameter(0,whole->GetParameter(2) );
  peak3f->SetLineColor(2);
  peak3f->SetLineWidth(2);
  peak3f->SetLineStyle(9);
  peak3f->Draw("same");
  
  TF1 *peak4f= new TF1( "peak4f", resp4,fitmin,fitmax,1);
  peak4f->SetParameter(0,whole->GetParameter(3) );
  peak4f->SetLineColor(2);
  peak4f->SetLineWidth(2);
  peak4f->SetLineStyle(9);
  peak4f->Draw("same");
  
  TF1 *peak5f= new TF1( "peak5f", resp5,fitmin,fitmax,1);
  peak5f->SetParameter(0,whole->GetParameter(4) );
  peak5f->SetLineColor(2);
  peak5f->SetLineWidth(2);
  peak5f->SetLineStyle(9);
  peak5f->Draw("same");

  TF1 *peak6f= new TF1( "peak6f", resp6,fitmin,fitmax,1);
  peak6f->SetParameter(0,whole->GetParameter(5) );
  peak6f->SetLineColor(2);
  peak6f->SetLineWidth(2);
  peak6f->SetLineStyle(9);
  peak6f->Draw("same");


  TF1 *expon= new TF1( "expon",expf ,fitmin,fitmax,4);
  //expon->SetParameters(whole->GetParameter(5),whole->GetParameter(6),whole->GetParameter(7),whole->GetParameter(8));
  expon->SetParameters(whole->GetParameter(6),whole->GetParameter(7),whole->GetParameter(8),whole->GetParameter(9));
  expon->SetLineColor(4);
  expon->SetLineWidth(2);
  expon->SetLineStyle(7);
  expon->Draw("same");

  //hexp[0]->Draw("same");
  hexp[0]->Draw("EL same");
  
  /*TLatex *tex = new TLatex(2000,setlogy?130:60,Form("^{78}Ni (%s)",histname));
  tex->SetTextFont(132);
  tex->SetTextSize(0.07);
  tex->SetLineWidth(2);
  tex->Draw();
  */
  /*TLatex *tex = new TLatex(2700,setlogy?80:55,Form("Incl: %2.1f mbarn for %d cnts", CSincl, (int)tot78Ni));
  tex->SetTextFont(132);
  tex->SetTextSize(0.04);
  tex->SetLineWidth(2);
  tex->Draw();
  */
  for(int i =0; i<6; i++){
  if(gopt[i]==1){
    TLatex *tex = new TLatex(labelx[i],labely[i],
			     //Form("#splitline{%d keV }{%2.2f mbarn (%3.1f cnts)}",energy[i], genevts*whole->GetParameter(i)*CSincl/tot78Ni, genevts*whole->GetParameter(i)));
			     Form("%d keV",energy[i]));
    tex->SetTextFont(132);
    tex->SetTextSize(0.05);
    tex->SetLineWidth(2);
    tex->Draw();
    }
  }
    
  fCanvas->Print(Form("%s.C",outname));
  fCanvas->Print(Form("%s.png",outname));
  fCanvas->Print(Form("%s.pdf",outname));
  
  fCanvas->Write();
  hexp[0]->Write();
  fout->Write();
  fout->Close();

}
Exemplo n.º 24
0
//**********MAIN**************************************************************************
int main(int argc, char* argv[])
{
    if(argc < 2)
    {
        cout << argv[0] << " cfg file " << "[run]" << endl; 
        return -1;
    }

    gROOT->SetBatch(kTRUE);
    //---load options---
    CfgManager opts;
    opts.ParseConfigFile(argv[1]);

    //---data opts
    string path=opts.GetOpt<string>("global.path2data");
    string run=opts.GetOpt<string>("global.run");
    string outSuffix=opts.GetOpt<string>("global.outFileSuffix");
    if(argc > 2)
        run = argv[2];
    int maxEvents = opts.GetOpt<int>("global.maxEvents");
    //---channels opts
    int nCh = opts.GetOpt<int>("global.nCh");
    int nSamples = opts.GetOpt<int>("global.nSamples");
    float tUnit = opts.GetOpt<float>("global.tUnit");
    string refChannel = opts.GetOpt<string>("global.refChannel");
    vector<string> channelsNames = opts.GetOpt<vector<string> >("global.channelsNames");
    map<string, vector<float> > timeOpts;
    timeOpts[refChannel] = opts.GetOpt<vector<float> >(refChannel+".timeOpts");
    for(auto& channel : channelsNames)
         timeOpts[channel] = opts.GetOpt<vector<float> >(channel+".timeOpts");

    //---definitions---
    int iEvent=0;
  
    //-----output setup-----
    TString outF="ntuples/Templates_"+TString(outSuffix)+"_"+TString(run)+".root";
    TFile* outROOT = TFile::Open(outF, "RECREATE");
    outROOT->cd();
    map<string, TH2F*> templates;
    for(auto channel : channelsNames)
        templates[channel] = new TH2F(channel.c_str(), channel.c_str(),
				      16000, -40, 160, 1200, -0.1, 1.1);
  
    //-----input setup-----
    TChain* inTree = new TChain("H4tree");
    string ls_command;
    if(path.find("/eos/cms") != string::npos)
        ls_command = string("gfal-ls root://eoscms/"+path+run+" | grep 'root' > tmp/"+run+".list");
    else
        ls_command = string("ls "+path+run+" | grep 'root' > tmp/"+run+".list");
    system(ls_command.c_str());
    ifstream waveList(string("tmp/"+run+".list").c_str(), ios::in);
    string file;
    
    int nFiles=0;
    while(waveList >> file && (opts.GetOpt<int>("global.maxFiles")<0 || nFiles<opts.GetOpt<int>("global.maxFiles")) )
    {
      
        if(path.find("/eos/cms") != string::npos)
	  {
	    std::cout << "+++ Adding file " << ("root://eoscms/"+path+run+"/"+file).c_str() << std::endl;
            inTree->AddFile(("root://eoscms/"+path+run+"/"+file).c_str());
	  }
        else
	  {
	    std::cout << "+++ Adding file " << (path+run+"/"+file).c_str() << std::endl;
            inTree->AddFile((path+run+"/"+file).c_str());
	  }
	++nFiles;

    }
    H4Tree h4Tree(inTree);

    //---process WFs---
    long nentries=h4Tree.GetEntries();
    cout << ">>> Processing H4DAQ run #" << run << " events #" << nentries << " <<<" << endl;
    while(h4Tree.NextEntry() && (iEvent<maxEvents || maxEvents==-1))
    {        
        ++iEvent;
	if (iEvent%1000==0) std::cout << "Processing event " << iEvent << "/" << nentries << std::endl;
        //---setup output event 
        int outCh=0;
        bool badEvent=false;
        
        //---read the digitizer
        //---read time raference channel
        float refTime=0, refAmpl=0;
        WFClass WF(opts.GetOpt<int>(refChannel+".polarity"), tUnit);
        int digiGr = opts.GetOpt<int>(refChannel+".digiGroup");
        int digiCh = opts.GetOpt<int>(refChannel+".digiChannel");
        int offset = digiGr*9*nSamples + digiCh*nSamples;
        for(int iSample=offset; iSample<offset+nSamples; ++iSample)
        {
            //---H4DAQ bug: sometimes ADC value is out of bound.
            if(h4Tree.digiSampleValue[iSample] > 4096)
            {
                badEvent = true;
                break;
            }
            WF.AddSample(h4Tree.digiSampleValue[iSample]);
        }
        //---skip bad events
        if(badEvent)
            continue;
        WF.SetBaselineWindow(opts.GetOpt<int>(refChannel+".baselineWin", 0), 
                             opts.GetOpt<int>(refChannel+".baselineWin", 1));
        WF.SetSignalWindow(opts.GetOpt<int>(refChannel+".signalWin", 0), 
                           opts.GetOpt<int>(refChannel+".signalWin", 1));
        WFBaseline refBaseline=WF.SubtractBaseline();
        refAmpl = WF.GetInterpolatedAmpMax();            
        refTime = WF.GetTime(opts.GetOpt<string>(refChannel+".timeType"), timeOpts[refChannel]).first;
	//---you may want to use an offset, for example if you use the trigger time
	if(opts.OptExist(refChannel+".timeOffset"))refTime -= opts.GetOpt<float>(refChannel+".timeOffset");
        //---require reference channel to be good
        if(refTime/tUnit < opts.GetOpt<int>(refChannel+".signalWin", 0) ||
           refTime/tUnit > opts.GetOpt<int>(refChannel+".signalWin", 1) ||
	   refBaseline.rms > opts.GetOpt<float>(refChannel+".noiseThreshold") ||  refAmpl < opts.GetOpt<int>(refChannel+".amplitudeThreshold"))
	  continue;

        //---template channels
        for(auto& channel : channelsNames)
        {
            //---read WFs
            WFClass WF(opts.GetOpt<int>(channel+".polarity"), tUnit);
            int digiGr = opts.GetOpt<int>(channel+".digiGroup");
            int digiCh = opts.GetOpt<int>(channel+".digiChannel");
            int offset = digiGr*9*nSamples + digiCh*nSamples;
            for(int iSample=offset; iSample<offset+nSamples; ++iSample)
            {
                //---H4DAQ bug: sometimes ADC value is out of bound.
                if(h4Tree.digiSampleValue[iSample] > 4096)
                {
                    badEvent = true;
                    break;
                }
                WF.AddSample(h4Tree.digiSampleValue[iSample]);
            }
            //---skip bad events
            if(badEvent)
                continue;
            //---compute reco variables
            float channelTime=0, channelAmpl=0;            
            WF.SetBaselineWindow(opts.GetOpt<int>(channel+".baselineWin", 0), 
                                 opts.GetOpt<int>(channel+".baselineWin", 1));
            WF.SetSignalWindow(opts.GetOpt<int>(channel+".signalWin", 0), 
                               opts.GetOpt<int>(channel+".signalWin", 1));
            WFBaseline channelBaseline=WF.SubtractBaseline();
	    channelAmpl = WF.GetInterpolatedAmpMax(-1,-1,opts.GetOpt<int>(channel+".signalWin", 2));
            channelTime = WF.GetTime(opts.GetOpt<string>(channel+".timeType"), timeOpts[channel]).first;
            //---skip bad events or events with no signal
            if(channelTime/tUnit > opts.GetOpt<int>(channel+".signalWin", 0) &&
               channelTime/tUnit < opts.GetOpt<int>(channel+".signalWin", 1) &&
	       channelBaseline.rms < opts.GetOpt<float>(channel+".noiseThreshold") &&
               channelAmpl > opts.GetOpt<int>(channel+".amplitudeThreshold") &&
               channelAmpl < 4000)
            {                
                vector<float>* analizedWF = WF.GetSamples();
                for(int iSample=0; iSample<analizedWF->size(); ++iSample)
		  templates[channel]->Fill(iSample*tUnit-refTime, analizedWF->at(iSample)/channelAmpl);
	    }
        }
    }   


    cout << ">>> Writing output " << outF << " <<<" << endl;    

    outROOT->cd();

    for(auto& channel : channelsNames)
    {
      //      pair<TH1F, TH1F> dft = DFT_cut(getMeanProfile(templates[channel]), channel, 4);
      //      dft.first.Write();
      //      dft.second.Write();
      if (templates[channel]->GetEntries()>1024*10)
	{
	  TH1F* prof=getMeanProfile(templates[channel]);
	  templates[channel]->Write();
	  prof->Write();
	}
    }
    opts.Write("cfg");
    outROOT->Close();
}
Exemplo n.º 25
0
int main (int argc, char** argv)
{
  std::string fileName (argv[1]) ;
  boost::shared_ptr<edm::ProcessDesc> processDesc = edm::readConfigFile (fileName) ;
  boost::shared_ptr<edm::ParameterSet> parameterSet = processDesc->getProcessPSet () ;
  std::cout << parameterSet->dump () << std::endl ; //PG for testing
  
  // edm::ParameterSet subPSetSelections =  parameterSet->getParameter<edm::ParameterSet> ("Selections") ;
  edm::ParameterSet subPSetInput = parameterSet->getParameter<edm::ParameterSet> ("inputNtuples") ;
  std::vector<std::string> inputFiles = subPSetInput.getParameter<std::vector<std::string> > ("inputFiles") ;

  TChain *chain = new TChain ("EcalCosmicsAnalysis") ;
  EcalCosmicsTreeContent treeVars ; 
  setBranchAddresses (chain, treeVars) ;


  // input files
  for (std::vector<std::string>::const_iterator listIt = inputFiles.begin () ;
       listIt != inputFiles.end () ; ++listIt)
  {
    std::cout << *listIt << " " << std::endl ;
    chain->Add (listIt->c_str ()) ;
  }

  int nEntries = chain->GetEntries () ;
  std::cout << "FOUND " << nEntries << " ENTRIES\n" ;    
  // input files


  // output file
  std::string outputRootName = "CRAFT_SCdistr.root" ;
  // output file  



  // output distributions
  TH2F SCoccupancy ("SCoccupancy", "SCoccupancy", PHI_BIN, PHI_MIN, PHI_MAX, ETA_BIN, ETA_MIN, ETA_MAX) ;
  
  TH1F SCenergy ("SCenergy", "SCenergy", E_BIN, E_MIN, E_MAX) ;
  TProfile2D SCenergy_ETAvsPHI ("SCenergy_ETAvsPHI", "SCenergy_ETAvsPHI", PHI_BIN, PHI_MIN, PHI_MAX, ETA_BIN, ETA_MIN, ETA_MAX) ;
  // output distributions



  // loop over entries
  for (int entry = 0; entry < nEntries; ++entry)
  {
    chain->GetEntry (entry) ;

    for (int SCindex = 0; SCindex < treeVars.nSuperClusters; ++SCindex)
    {
      SCoccupancy.Fill (treeVars.superClusterPhi[SCindex], treeVars.superClusterEta[SCindex]) ;
      
      SCenergy.Fill (treeVars.superClusterRawEnergy[SCindex]) ;
      SCenergy_ETAvsPHI.Fill (treeVars.superClusterPhi[SCindex], treeVars.superClusterEta[SCindex], treeVars.superClusterRawEnergy[SCindex]) ;
    }
  
  
  } //PG loop over entries

  TFile saving (outputRootName.c_str (),"recreate") ;
  saving.cd () ;  
  
  SCoccupancy.Write () ;
  SCenergy.Write () ;
  SCenergy_ETAvsPHI.Write () ;
  
  saving.Close () ;
  
  return 0 ;
}
Exemplo n.º 26
0
void TMVARegressionApplication( int wMs,int wM, string st,string st2,string option="",TString myMethodList = "" )
{
    //---------------------------------------------------------------
    // This loads the library
    TMVA::Tools::Instance();

    // Default MVA methods to be trained + tested
    std::map<std::string,int> Use;

    // --- Mutidimensional likelihood and Nearest-Neighbour methods
    Use["PDERS"]           = 0;
    Use["PDEFoam"]         = 0;
    Use["KNN"]             = 0;
    //
    // --- Linear Discriminant Analysis
    Use["LD"]		        = 0;
    //
    // --- Function Discriminant analysis
    Use["FDA_GA"]          = 0;
    Use["FDA_MC"]          = 0;
    Use["FDA_MT"]          = 0;
    Use["FDA_GAMT"]        = 0;
    //
    // --- Neural Network
    Use["MLP"]             = 0;
    //
    // --- Support Vector Machine
    Use["SVM"]             = 0;
    //
    // --- Boosted Decision Trees
    Use["BDT"]             = 0;
    Use["BDTG"]            = 1;
    // ---------------------------------------------------------------

    std::cout << std::endl;
    std::cout << "==> Start TMVARegressionApplication" << std::endl;

    // Select methods (don't look at this code - not of interest)
    if (myMethodList != "") {
        for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;

        std::vector<TString> mlist = gTools().SplitString( myMethodList, ',' );
        for (UInt_t i=0; i<mlist.size(); i++) {
            std::string regMethod(mlist[i]);

            if (Use.find(regMethod) == Use.end()) {
                std::cout << "Method \"" << regMethod << "\" not known in TMVA under this name. Choose among the following:" << std::endl;
                for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) std::cout << it->first << " ";
                std::cout << std::endl;
                return;
            }
            Use[regMethod] = 1;
        }
    }

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

    // --- Create the Reader object

    TMVA::Reader *reader = new TMVA::Reader( "!Color:!Silent" );

    // Create a set of variables and declare them to the reader
    // - the variable names MUST corresponds in name and type to those given in the weight file(s) used
    //Float_t var1, var2;
    //reader->AddVariable( "var1", &var1 );
    //reader->AddVariable( "var2", &var2 );
    Float_t pt_AK8MatchedToHbb,eta_AK8MatchedToHbb,nsv_AK8MatchedToHbb,sv0mass_AK8MatchedToHbb,sv1mass_AK8MatchedToHbb,
            nch_AK8MatchedToHbb,nmu_AK8MatchedToHbb,nel_AK8MatchedToHbb,muenfr_AK8MatchedToHbb,emenfr_AK8MatchedToHbb;
    reader->AddVariable( "pt_AK8MatchedToHbb", &pt_AK8MatchedToHbb );
    reader->AddVariable( "eta_AK8MatchedToHbb", &eta_AK8MatchedToHbb );
    reader->AddVariable( "nsv_AK8MatchedToHbb", &nsv_AK8MatchedToHbb );
    reader->AddVariable( "sv0mass_AK8MatchedToHbb", &sv0mass_AK8MatchedToHbb );
    reader->AddVariable( "sv1mass_AK8MatchedToHbb", &sv1mass_AK8MatchedToHbb );
    reader->AddVariable( "nch_AK8MatchedToHbb", &nch_AK8MatchedToHbb );
    reader->AddVariable( "nmu_AK8MatchedToHbb", &nmu_AK8MatchedToHbb );
    reader->AddVariable( "nel_AK8MatchedToHbb", &nel_AK8MatchedToHbb );
    reader->AddVariable( "muenfr_AK8MatchedToHbb", &muenfr_AK8MatchedToHbb );
    reader->AddVariable( "emenfr_AK8MatchedToHbb", &emenfr_AK8MatchedToHbb );


    // Spectator variables declared in the training have to be added to the reader, too
    Float_t spec1,spec2;
    reader->AddSpectator( "spec1:=n_pv",  &spec1 );
    reader->AddSpectator( "spec2:=msoftdrop_AK8MatchedToHbb",  &spec2 );

    // --- Book the MVA methods

    TString dir    = "weights/";
    TString prefix = "TMVARegression";

    // Book method(s)
    for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
        if (it->second) {
            TString methodName = it->first + " method";
            TString weightfile = dir + prefix + "_" + TString(it->first) + ".weights.xml";
            reader->BookMVA( methodName, weightfile );
        }
    }

    TH1* hists[100];
    Int_t nhists = -1;
    for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
        TH1* h = new TH1F( it->first.c_str(), TString(it->first) + " method", 100, -100, 600 );
        if (it->second) hists[++nhists] = h;
    }
    nhists++;

    //1=signal ,0=QCD ,2=data
    int nameRoot=1;
    if((st2.find("QCD")!= std::string::npos)||
            (st2.find("bGen")!= std::string::npos)||
            (st2.find("bEnriched")!= std::string::npos))nameRoot=0;
    if(st2.find("data")!= std::string::npos)nameRoot=2;
    cout<<"nameRoot = "<<nameRoot<<endl;

    //option-----------------------------------------------------------

    int JESOption=0;


    // Prepare input tree (this must be replaced by your data source)
    // in this example, there is a toy tree with signal and one with background events
    // we'll later on use only the "signal" events for the test in this example.
    //
    TFile *f;
    TTree *tree;
    int nPass[20]= {0};
    int total=0;
    double fixScaleNum[2]= {0};

    TH1D* th1=new TH1D("a","a",150,50,200);

    string massName[nMass]= {"Thea","HCorr","Reg"};
    string catName[nCat]= {"PP","PF","FP","FF"};
    string tau21Name[3]= {"withTau21","woTau21","antiTau21"};

    TH1D* th2[nMass][nCat][3];
    TH1D* th3[nMass][nCat][3];
    TH1D* th4[nMass][nCat][3];
    for(int i=0; i<nMass; i++) {
        for(int j=0; j<nCat; j++) {
            for(int k=0; k<3; k++) {
                th2[i][j][k]=(TH1D*)th1->Clone(Form("loose_%s_%s_%s",massName[i].data(),catName[j].data(),tau21Name[k].data()));
                th3[i][j][k]=(TH1D*)th1->Clone(Form("tight_%s_%s_%s",massName[i].data(),catName[j].data(),tau21Name[k].data()));
                th4[i][j][k]=(TH1D*)th1->Clone(Form("tl_%s_%s_%s",massName[i].data(),catName[j].data(),tau21Name[k].data()));

                th2[i][j][k]->Sumw2();
                th3[i][j][k]->Sumw2();
                th4[i][j][k]->Sumw2();
            }
        }
    }


    for (int w=wMs; w<wM; w++) {
        if(w%20==0)cout<<w<<endl;

        if (nameRoot!=1)f = TFile::Open(Form("%s%d.root",st.data(),w));
        else f = TFile::Open(st.data());
        if (!f || !f->IsOpen())continue;

        /*TDirectory * dir;
        		if (nameRoot!=1)dir = (TDirectory*)f->Get(Form("%s%d.root:/tree",st.data(),w));
        		else dir = (TDirectory*)f->Get(Form("%s:/tree",st.data()));

        		dir->GetObject("treeMaker",tree);
        		*/
        tree=(TTree*)f->Get("treeMaker");
        TreeReader data(tree);
        total+=data.GetEntriesFast();
        for(Long64_t jEntry=0; jEntry<data.GetEntriesFast() ; jEntry++) {
            data.GetEntry(jEntry);



            Int_t nVtx        = data.GetInt("nVtx");
            //0. has a good vertex
            if(nVtx<1)continue;
            nPass[0]++;

            //1.trigger
            std::string* trigName = data.GetPtrString("hlt_trigName");
            vector<bool> &trigResult = *((vector<bool>*) data.GetPtr("hlt_trigResult"));
            bool passTrigger=false;
            for(int it=0; it< data.GetPtrStringSize(); it++) {
                std::string thisTrig= trigName[it];
                bool results = trigResult[it];
                if( ((thisTrig.find("HLT_PFHT800")!= std::string::npos||
                        thisTrig.find("HLT_AK8DiPFJet300_200_TrimMass30_BTagCSV_p20")!= std::string::npos
                     ) && results==1)) {
                    passTrigger=true;
                    break;
                }
            }
            if(!passTrigger && nameRoot==2)continue;
            nPass[1]++;

            const int nAK8Jet=data.GetInt("AK8PuppinJet");
            //2.nJets
            if(nAK8Jet<2)continue;
            nPass[2]++;
            int* AK8PuppinSubSDJet=data.GetPtrInt("AK8PuppinSubSDJet");
            if(AK8PuppinSubSDJet[0]!=2||AK8PuppinSubSDJet[1]!=2)continue;
            TClonesArray* AK8PuppijetP4 = (TClonesArray*) data.GetPtrTObject("AK8PuppijetP4");
            float*  AK8PuppijetCorrUncUp = data.GetPtrFloat("AK8PuppijetCorrUncUp");
            float*  AK8PuppijetCorrUncDown = data.GetPtrFloat("AK8PuppijetCorrUncDown");
            TLorentzVector* thisJet ,* thatJet;


            thisJet=(TLorentzVector*)AK8PuppijetP4->At(0);
            thatJet=(TLorentzVector*)AK8PuppijetP4->At(1);

            //3. Pt
            if(thisJet->Pt()>99998 ||thatJet->Pt()>99998 )continue;
            if(thisJet->Pt()<300)continue;
            if(thatJet->Pt()<300)continue;
            nPass[3]++;
            //4tightId-----------------------------------------
            vector<bool>    &AK8PuppijetPassIDTight = *((vector<bool>*) data.GetPtr("AK8PuppijetPassIDTight"));
            if(AK8PuppijetPassIDTight[0]==0)continue;
            if(AK8PuppijetPassIDTight[1]==0)continue;
            Float_t*  AK8PuppijetCEmEF = data.GetPtrFloat("AK8PuppijetCEmEF");
            Float_t*  AK8PuppijetMuoEF = data.GetPtrFloat("AK8PuppijetMuoEF");
            if(AK8PuppijetMuoEF[0]>0.8)continue;
            if(AK8PuppijetCEmEF[0]>0.9)continue;
            if(AK8PuppijetMuoEF[1]>0.8)continue;
            if(AK8PuppijetCEmEF[1]>0.9)continue;
            nPass[4]++;
            //5. Eta-----------------------------------------
            if(fabs(thisJet->Eta())>2.4)continue;
            if(fabs(thatJet->Eta())>2.4)continue;
            nPass[5]++;
            //6. DEta-----------------------------------------
            float dEta = fabs(thisJet->Eta()-thatJet->Eta());
            if(dEta>1.3)continue;
            nPass[6]++;
            //7. Mjj-----------------------------------------
            //float mjjRed = (*thisJet+*thatJet).M()+250-thisJet->M()-thatJet->M();
            //if(mjjRed<1000)continue;
            nPass[7]++;
            //8. fatjetPRmassL2L3Corr-----------------------------------------
            nPass[8]++;
            //9.-----------------------------------------



            Float_t*  AK8Puppijet_DoubleSV = data.GetPtrFloat("AK8Puppijet_DoubleSV");


            int looseStat=-1;
            int tightStat=-1;
            int tlStat=-1;

            if(AK8Puppijet_DoubleSV[0]>0.3 && AK8Puppijet_DoubleSV[1]>0.3)looseStat=0;
            else if(AK8Puppijet_DoubleSV[0]>0.3 && AK8Puppijet_DoubleSV[1]<0.3)looseStat=1;
            else if(AK8Puppijet_DoubleSV[0]<0.3 && AK8Puppijet_DoubleSV[1]>0.3)looseStat=2;
            else looseStat=3;

            if(AK8Puppijet_DoubleSV[0]>0.8 && AK8Puppijet_DoubleSV[1]>0.8)tightStat=0;
            else if(AK8Puppijet_DoubleSV[0]>0.8 && AK8Puppijet_DoubleSV[1]<0.8)tightStat=1;
            else if(AK8Puppijet_DoubleSV[0]<0.3 && AK8Puppijet_DoubleSV[1]>0.8)tightStat=2;
            else if(AK8Puppijet_DoubleSV[0]<0.3 && AK8Puppijet_DoubleSV[1]<0.8)tightStat=3;
            else tightStat=-1;

            if(AK8Puppijet_DoubleSV[0]>0.8 && AK8Puppijet_DoubleSV[1]>0.3)tlStat=0;
            else if(AK8Puppijet_DoubleSV[0]>0.8 && AK8Puppijet_DoubleSV[1]<0.3)tlStat=1;
            else if(AK8Puppijet_DoubleSV[0]<0.3 && AK8Puppijet_DoubleSV[1]>0.3)tlStat=2;
            else if(AK8Puppijet_DoubleSV[0]<0.3 && AK8Puppijet_DoubleSV[1]<0.3)tlStat=3;
            else tlStat=-1;

            double varTemp[2];

            Float_t*  AK8PuppijetSDmass = data.GetPtrFloat("AK8PuppijetSDmass");

            Int_t* AK8Puppijet_nSV=data.GetPtrInt("AK8Puppijet_nSV");
            vector<float>   *AK8Puppijet_SVMass  =  data.GetPtrVectorFloat("AK8Puppijet_SVMass");
            int nEle= data.GetInt("nEle");
            int nMu=data.GetInt("nMu");
            Float_t*  AK8PuppijetEleEF = data.GetPtrFloat("AK8PuppijetEleEF");
            //Float_t*  AK8PuppijetMuoEF = data.GetPtrFloat("AK8PuppijetMuoEF");
            Int_t* AK8PuppijetCMulti=data.GetPtrInt("AK8PuppijetCMulti");
            Int_t* AK8PuppijetEleMulti=data.GetPtrInt("AK8PuppijetEleMulti");
            Int_t* AK8PuppijetMuoMulti=data.GetPtrInt("AK8PuppijetMuoMulti");

            for(int i=0; i<2; i++) {

                TLorentzVector* thisAK8Jet ;

                if(i==1)thisAK8Jet=thatJet;
                else thisAK8Jet=thisJet;


                pt_AK8MatchedToHbb=thisAK8Jet->Pt();
                eta_AK8MatchedToHbb=thisAK8Jet->Eta();
                nsv_AK8MatchedToHbb=AK8Puppijet_nSV[i];
                sv0mass_AK8MatchedToHbb=AK8Puppijet_SVMass[i][0];
                sv1mass_AK8MatchedToHbb=AK8Puppijet_SVMass[i][1];
                nmu_AK8MatchedToHbb=AK8PuppijetMuoMulti[i];
                nel_AK8MatchedToHbb=AK8PuppijetEleMulti[i];
                muenfr_AK8MatchedToHbb=AK8PuppijetMuoEF[i];
                nch_AK8MatchedToHbb=AK8PuppijetCMulti[i];
                emenfr_AK8MatchedToHbb=AK8PuppijetEleEF[i];
                spec1=nVtx;
                spec2=AK8PuppijetSDmass[i];
                Float_t val ;
                for (Int_t ih=0; ih<nhists; ih++) {
                    TString title = hists[ih]->GetTitle();
                    val= (reader->EvaluateRegression( title ))[0];
                }
                varTemp[i]=val;
            }

            double PUPPIweight[2]= {0};
            PUPPIweight[0]=getPUPPIweight(thisJet->Pt(),thisJet->Eta());
            PUPPIweight[1]=getPUPPIweight(thatJet->Pt(),thatJet->Eta());

            double PUPPIweightThea[2]= {0};
            PUPPIweightThea[0]=getPUPPIweight_o(thisJet->Pt(),thisJet->Eta());
            PUPPIweightThea[1]=getPUPPIweight_o(thatJet->Pt(),thatJet->Eta());


            TLorentzVector  thisJetReg, thatJetReg;
            thisJetReg=(*thisJet)*varTemp[0];
            thatJetReg=(*thatJet)*varTemp[1];
            double PUPPIweightOnRegressed[2]= {0};
            PUPPIweightOnRegressed[0]=getPUPPIweightOnRegressed(thisJetReg.Pt(),thisJetReg.Eta());
            PUPPIweightOnRegressed[1]=getPUPPIweightOnRegressed(thatJetReg.Pt(),thatJetReg.Eta());

            double mass_j0=0,mass_j1=0;

            for(int i=0; i<nMass; i++) {
                if(i==0) {
                    mass_j0=AK8PuppijetSDmass[0]*PUPPIweightThea[0];
                    mass_j1=AK8PuppijetSDmass[1]*PUPPIweightThea[1];
                }
                else if (i==1) {
                    mass_j0=AK8PuppijetSDmass[0]*PUPPIweight[0];
                    mass_j1=AK8PuppijetSDmass[1]*PUPPIweight[1];
                }
                else {
                    mass_j0=AK8PuppijetSDmass[0]*varTemp[0]*PUPPIweightOnRegressed[0];
                    mass_j1=AK8PuppijetSDmass[1]*varTemp[1]*PUPPIweightOnRegressed[1];
                }

                if(mass_j1<50)continue;
                if(mass_j0>100 && mass_j0<145)continue;

                //cout<<mass_j0<<","<<mass_j1<<",stat="<<looseStat<<","<<tightStat<<endl;

                th2[i][looseStat][1]->Fill(mass_j0);
                if(tightStat>=0)th3[i][tightStat][1]->Fill(mass_j0);
                if(tlStat>=0)th4[i][tlStat][1]->Fill(mass_j0);
            }


            Float_t*  AK8PuppijetTau1 = data.GetPtrFloat("AK8PuppijetTau1");
            Float_t*  AK8PuppijetTau2 = data.GetPtrFloat("AK8PuppijetTau2");
            double puppiTau21[2];
            puppiTau21[0]=(AK8PuppijetTau2[0]/AK8PuppijetTau1[0]),puppiTau21[1]=(AK8PuppijetTau2[1]/AK8PuppijetTau1[1]);

            if(puppiTau21[0]>0.6 && puppiTau21[1]<0.6) {
                for(int i=0; i<nMass; i++) {
                    if(i==0) {
                        mass_j0=AK8PuppijetSDmass[0]*PUPPIweightThea[0];
                        mass_j1=AK8PuppijetSDmass[1]*PUPPIweightThea[1];
                    }
                    else if (i==1) {
                        mass_j0=AK8PuppijetSDmass[0]*PUPPIweight[0];
                        mass_j1=AK8PuppijetSDmass[1]*PUPPIweight[1];
                    }
                    else {
                        mass_j0=AK8PuppijetSDmass[0]*varTemp[0]*PUPPIweightOnRegressed[0];
                        mass_j1=AK8PuppijetSDmass[1]*varTemp[1]*PUPPIweightOnRegressed[1];
                    }

                    if(mass_j1<50)continue;
                    if(mass_j0>100 && mass_j0<145)continue;


                    th2[i][looseStat][2]->Fill(mass_j0);
                    if(tightStat>=0)th3[i][tightStat][2]->Fill(mass_j0);
                    if(tlStat>=0)th4[i][tlStat][2]->Fill(mass_j0);
                }
            }

            if(puppiTau21[0]>0.6 || puppiTau21[1]>0.6) continue;


            for(int i=0; i<nMass; i++) {
                if(i==0) {
                    mass_j0=AK8PuppijetSDmass[0]*PUPPIweightThea[0];
                    mass_j1=AK8PuppijetSDmass[1]*PUPPIweightThea[1];
                }
                else if (i==1) {
                    mass_j0=AK8PuppijetSDmass[0]*PUPPIweight[0];
                    mass_j1=AK8PuppijetSDmass[1]*PUPPIweight[1];
                }
                else {
                    mass_j0=AK8PuppijetSDmass[0]*varTemp[0]*PUPPIweightOnRegressed[0];
                    mass_j1=AK8PuppijetSDmass[1]*varTemp[1]*PUPPIweightOnRegressed[1];
                }

                if(mass_j1<50)continue;
                if(mass_j0>100 && mass_j0<145)continue;


                th2[i][looseStat][0]->Fill(mass_j0);
                if(tightStat>=0)th3[i][tightStat][0]->Fill(mass_j0);
                if(tlStat>=0)th4[i][tlStat][0]->Fill(mass_j0);
            }


        }
    }

    for(int i=0; i<10; i++)cout<<"npass["<<i<<"]="<<nPass[i]<<endl;


    TFile* outFile;//= new TFile(Form("PFRatio/%s.root",st2.data()),"recreate");
    outFile= new TFile(Form("PFRatio/%s/%d.root",st2.data(),wMs),"recreate");
    for(int i=0; i<nMass; i++) {
        for(int j=0; j<nCat; j++) {
            for(int k=0; k<3; k++) {
                th2[i][j][k]->Write();
                th3[i][j][k]->Write();
                th4[i][j][k]->Write();
            }
        }
    }
    outFile->Close();

    for(int i=0; i<nMass; i++) {
        for(int j=0; j<nCat; j++) {
            for(int k=0; k<2; k++) {
                delete th2[i][j][k];
                delete th3[i][j][k];
                delete th4[i][j][k];
            }
        }
    }

    delete reader;


}
Exemplo n.º 27
0
void CalibrateData(Int_t nevt,Int_t startEv = 1, char *PedFile = "drs4_20100311_t_ped.root") {

	// create progress bar
	TGHProgressBar *gProgress = ProgressBar("Calibrazione dati");

	// Redefine DOMINO Depth in ADC counts
	const Float_t DominoDepthADC = pow(2, DOMINO_DEPTH);

	// create list of histograms for pedestals
	TList *grPedList = new TList();
	TGraphErrors *grPed;

	// create list of histograms for channels
	TList *hCellCalibList = new TList();
	TH1F *hCellCalib;

	TList *grCellCalibList = new TList();
	TGraphErrors *grCellCalib;

	int mV[NCALIBFILES] = {-500,-400,-300,-200,-100,0,100,200,300,400,500};

	/*for (int iFile = 0; iFile < NCALIBFILES; iFile++) {
		mV[iFile] = mVStart;
		mVStart += mVStep;
	}*/

	char *calibrationFile;
	char *calibrationFileArray[NCALIBFILES];
	calibrationFileArray[0] = "drs4_1000ev_dcm500mv.dat";
	calibrationFileArray[1] = "drs4_1000ev_dcm400mv.dat";
	calibrationFileArray[2] = "drs4_1000ev_dcm300mv.dat";
	calibrationFileArray[3] = "drs4_1000ev_dcm200mv.dat";
	calibrationFileArray[4] = "drs4_1000ev_dcm100mv.dat";
	calibrationFileArray[5] = "drs4_1000ev_dc1mv.dat";
	calibrationFileArray[6] = "drs4_1000ev_dc100mv.dat";
	calibrationFileArray[7] = "drs4_1000ev_dc200mv.dat";
	calibrationFileArray[8] = "drs4_1000ev_dc300mv.dat";
	calibrationFileArray[9] = "drs4_1000ev_dc400mv.dat";
	calibrationFileArray[10] = "drs4_1000ev_dc500mv.dat";

	for (int iFile = 0; iFile < NCALIBFILES; iFile++) {
		for (int ch = 0; ch < DOMINO_NCELL; ch++) {
			//
			TString title = "Calibration signal file:";
			title += iFile;
			title += " ch:";
			title += ch;
			hCellCalib = new TH1F(title,title, DominoDepthADC, -DominoDepthADC, DominoDepthADC);
			hCellCalibList->Add(hCellCalib);
		}
	}


	for (int ch = 0; ch < DOMINO_NCELL; ch++) {
		grCellCalib = new TGraphErrors(NCALIBFILES);
		grCellCalibList->Add(grCellCalib);
	}


	// calculate or read pedestals from file
	grPedList = OpenPedestals(PedFile);
	grPedData = (TGraphErrors *) grPedList->At(anaChannel);
	grPedTrig = (TGraphErrors *) grPedList->At(trigChannel);

	// create gauss function
	TF1 *fgauss = new TF1("fgauss", "TMath::Gaus(x,[0],[1],0)", -DOMINO_NCELL, DOMINO_NCELL);
	fgauss->SetParameter(0,0.);
	fgauss->SetParameter(1,1.);
	fgauss->SetParLimits(0, 0., DominoDepthADC);
	fgauss->SetParLimits(1, 0.1, 20.);

	TCanvas *ctest = new TCanvas("ChannelTest", "ChannelTest", 800, 600);
	ctest->Divide(3, 4);

	gProgress->Reset();
	gProgress->SetMax(nevt*NCALIBFILES);

	gSystem->ProcessEvents();


	for (int iFile = 0; iFile < NCALIBFILES; iFile++) {

		// open file

		calibrationFile = calibrationFileArray[iFile];
		FILE *fdata = OpenDataFile(calibrationFile);
		struct channel_struct *p;
		struct channel_struct *dep;

		Double_t refval=0, reftmp = 0;
		Double_t PedVal, itmp;

		// Count number of events in data file
		int nevtDataMax = 0;
		while (!feof(fdata)) {
			fread((void *) &event_data, 1, sizeof(event_data), fdata);
			nevtDataMax++;
		}
		printf("nevtDataMax: %d\n", nevtDataMax);

		if (nevt > (nevtDataMax - startEv) || nevt == 0)
			nevt = nevtDataMax - startEv;
		cout << endl << "==>> Processing " << nevt << " events from file "
				<< calibrationFile << endl;

		rewind(fdata);

		for (int j = 0; j < 1; j++) {
			fread((void *) &event_data, 1, sizeof(event_data), fdata);
			p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data
			p += anaChannel;
			for (ch = 0; ch < DOMINO_NCELL; ch++) {
				grPedData->GetPoint(ch, itmp, PedVal);
				reftmp = TMath::Abs((Double_t)(p->data[ch])-PedVal);
				if (reftmp > 0.8* refval)
					refval = 0.2*reftmp+0.8*refval;
				//					cout << ch << " " <<p->data[ch] << " " <<reftmp << " " << refval <<endl ;
			}
		}
		cout << "refval="<< refval<<endl;
		rewind(fdata);

		Int_t ievt = 1;
		// go to first event (startEv)
		while (ievt < startEv) {
			fread((void *) &event_data, 1, sizeof(event_data), fdata);
			if (feof(fdata))
				break;
			ievt++;
		}

		ievt = 1;
		Int_t iTrig = 0;
		Int_t flagEnd = 0;
		Double_t chtmp, chtrig;
		Double_t ratio;
		Double_t mean, rms;

		// loop on events

		while (ievt <= nevt && !flagEnd) {

			fread((void *) &event_data, 1, sizeof(event_data), fdata);
			if (feof(fdata))
				flagEnd = 1;

			p = (struct channel_struct *) &event_data.ch[0]; // read bunch of data
			dep = (struct channel_struct *) &event_data.ch[1]; // read bunch of data

			//now anaChannel analysis

			p += anaChannel;

			// read data, subtract pedestals values and fill hCellCalibList.

			for (int ch = 0; ch < DOMINO_NCELL; ch++) {
				// Read pedestal value for this cell
				grPedData->GetPoint(ch, itmp, PedVal);
				chtmp = (Double_t)(p->data[ch]); // data value
				chtmp = chtmp - PedVal;
				//if (TMath::Abs(chtmp) > 0.9 * refval)
				((TH1 *) hCellCalibList->At(iFile*DOMINO_NCELL+ch))->Fill(chtmp);
				//cout << ch << " " << iFile << " " << chtmp << endl;
			}

			gProgress->Increment(1);
			gSystem->DispatchOneEvent(kTRUE);
			ievt++; // next event
		}


		TH1 *hCellTmp;
		for(ch = 0; ch < DOMINO_NCELL;ch++) {
			hCellTmp = ((TH1 *) hCellCalibList->At(iFile*DOMINO_NCELL+ch));
			//hCellTmp->Fit("gaus", "Q");
			//mean = (hCellTmp->GetFunction("gaus"))->GetParameter(1);
			//rms = (hCellTmp->GetFunction("gaus"))->GetParameter(2);
			mean = hCellTmp->GetMean();
			rms = hCellTmp->GetRMS();
			((TGraphErrors *) (grCellCalibList->At(ch)))->SetPoint(iFile, (Double_t) mV[iFile], mean);
			((TGraphErrors *) (grCellCalibList->At(ch)))->SetPointError(iFile, 0., rms);
		}


		ctest->cd(iFile + 1);
		hCellTmp = ((TH1 *) hCellCalibList->At(567 + iFile*DOMINO_NCELL));
		hCellTmp->Fit("gaus","Q");
		hCellTmp->DrawCopy();
	}

	TString OutFile = "CalibrationDataNew";
	OutFile += nevt;
	OutFile += "events.root";
	TFile *f = new TFile(OutFile, "RECREATE");
	for (int ch = 0; ch < DOMINO_NCELL; ch++) {
		TString key = "CalibDataCell";
		key += ch;
		((TGraphErrors*) grCellCalibList->At(ch))->Write(key);
	}
	f->Close();

	hCellCalibList->Delete();

	((TGMainFrame *) gProgress->GetParent())->CloseWindow();
	fclose(fdata);
}
Exemplo n.º 28
0
int main(int argc,char *argv[]) {
    int c;
    bool writeOutput = false;
    std::vector<std::string> years;
    std::string inYears = "";
    bool useHistogramsFile = false;
    std::string srsValue = "free";
    std::string outFileName = "";
    double sigmas = 3;
    int nbins = 33;
    std::string predictionDay = "";
    std::string endRangeDay = "";
    /*____________________________Parse Command Line___________________________*/
    while ((c = getopt(argc, argv, "y:HS:o:s:n:d:D:h")) != -1) {
        switch (c) {
            case 'y':
                inYears.assign(optarg);
                boost::split(years, inYears, boost::is_any_of(","));
                break;
            case 's':
                srsValue.assign(optarg);
                break;
            case 'H':
                useHistogramsFile = true;
                break;
            case 'o':
                outFileName = optarg;
                break;
            case 'S':
                sigmas = atof(optarg);
                break;
            case 'n':
                nbins = atoi(optarg);
                break;
            case 'd':
                predictionDay.assign(optarg);
                break;
            case 'D':
                endRangeDay.assign(optarg);
                break;
            case 'h':
                printOptions();
                return 0;
            default:
                // not an option
                break;
        }
    }

    //ensure years and outYear are set
    if (years.empty()) {
        std::cout << "You must set the input years using the -y switch and a comma-separated list of years" <<
        std::endl;
        printOptions();
        return 0;
    }

    boost::gregorian::date predictionDate;
    if (predictionDay != "")
        predictionDate = boost::gregorian::date(boost::gregorian::from_string(predictionDay));

    boost::gregorian::date endRangeDate;
    if (endRangeDay != ""){
        endRangeDate = boost::gregorian::date(boost::gregorian::from_string(endRangeDay));
        if (predictionDay == ""){
            std::cout << "If you enter an end date, you must also specify a start date" << std::endl;
            return 0;
        }
    }

    char *homePath, path[256];
    homePath = getenv("HOME");

    //read in the necessary constants
    sprintf(path, "%s/cpp/NCAA_C/constants/waverage_standard_deviations.d", homePath);
    ConstantStandardDeviations *stdDevs = ConstantStandardDeviations::Instance();
    stdDevs->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/season_info.d", homePath);
    ConstantSeasonInfo *seasonInfo = ConstantSeasonInfo::Instance();
    seasonInfo->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/waverage_functions.d", homePath);
    ConstantWAverageFunctions *functions = ConstantWAverageFunctions::Instance();
    functions->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/team_neutral_ratios.d", homePath);
    ConstantTeamNeutralRatios *ratios = ConstantTeamNeutralRatios::Instance();
    ratios->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/srs_additions.d", homePath);
    ConstantSRSadditions *additions = ConstantSRSadditions::Instance();
    additions->initialize(path);

    sprintf(path, "%s/cpp/NCAA_C/constants/game_function_weights.%s.d", homePath,srsValue.c_str());
    ConstantGameFunction *gameFunction = ConstantGameFunction::Instance();
    gameFunction->initialize(path);

    //read in the game and waverage info
    for (std::string &year : years) {
        sprintf(path, "%s/cpp/NCAA_C/teams/%s/", homePath, year.c_str());
        std::cout << "Reading in games and waverages for " << year << std::endl;
        readTeamsFromDir(path);
        readTeamsFromDir(path, "waverages");
    }

    TFile *histsFile;
    std::unordered_map<int, TH1F*> probs_by_year, probs_err_by_year;
    if (useHistogramsFile){
        sprintf(path, "%s/cpp/NCAA_C/rootFiles/gameFunctionHistograms.%s.root", homePath, srsValue.c_str());
        histsFile = new TFile(path);

        for (int y = 2007; y <= 2016; y++){
            sprintf(path, "probs_by_year_%d", y);
            probs_by_year.emplace(y, (TH1F*)gROOT->FindObject(path));
            sprintf(path, "probs_err_by_year_%d", y);
            probs_err_by_year.emplace(y, (TH1F*)gROOT->FindObject(path));
        }
    }

    std::unordered_map<std::string, Team *> teams = Team::getTeams();
    std::unordered_map<std::string, TeamGame *> games;
    Team *opp;
    TeamWAverage *wa1, *wa2;

    int gameScoreWins = 0, gameScoreTotal = 0;
    int gameScoreWinsSpread = 0, gameScoreTotalSpread = 0;
    int vegasWinsSpread = 0, vegasTotalSpread = 0;
    int adjGameScoreWins = 0, adjGameScoreTotal = 0;
    int unadjustedSrsWins = 0, unadjustedSrsTotal = 0;
    int srsWins = 0, srsTotal = 0;
    int srsWinsSpread = 0, srsTotalSpread = 0;

    int srsGameScoreWins = 0, srsGameScoreTotal = 0;
    int srsGameScoreWinsSpread = 0, srsGameScoreTotalSpread = 0;

    TFile *outFile;
    if (outFileName != "") {
        sprintf(path, "%s/cpp/NCAA_C/rootFiles/%s",homePath,outFileName.c_str());
        outFile = new TFile(path, "RECREATE");
    }

    TH1F *h_wins = new TH1F("h_wins","",nbins,0,1);
    TH1F *h_total = new TH1F("h_total","",nbins,0,1);
    TH2F *spread_vs_spread = new TH2F("spread_vs_spread","",80,-20,20,80,-20,20);
    TH2F *myspread_vs_pct = new TH2F("myspread_vs_pct","",100,0,1,80,-20,20);
    TH2F *myPct_vs_VegasPct = new TH2F("myPct_vs_VegasPct","",nbins,0,1,nbins,0,1);

    for (auto &team : teams) {
        games = team.second->getGamesByDate();
        for (auto &game : games) {
            //look only at games within a certain range
            if (predictionDay != ""){
                if (endRangeDay == ""){
                    if (predictionDate != game.second->getDate()) continue;
                }
                else{
                    if (game.second->getDate() < predictionDate || game.second->getDate() > endRangeDate) continue;
                }
            }
            else{
                if (game.second->getDate() >= seasonInfo->get(team.second->getYear(), "tournament start")) continue;
                if (game.second->getDate().month().as_number() == 11) continue;
            }
            if (team.first < game.second->getOpp()) continue; //look at each game only once
            opp = Team::findTeam(game.second->getOpp());
            if (!opp) continue;

            TeamGame *oppgame = opp->GameOnDate(game.second->getDate(),team.second->getName());

            bool win = game.second->getWin() == 1;
            double spread = game.second->getSpread();
            double mySpread;

            wa1 = team.second->WAverageOnDate(game.second->getDate());
            wa2 = opp->WAverageOnDate(game.second->getDate());

            std::string loc = game.second->getLoc();
            std::string oppLoc = game.second->getOppLoc();

            double gameScore = gameFunction->predictGame(wa1,wa2,team.second->getYear(),loc,oppLoc);
            if (gameScore >= 0 && win) gameScoreWins++;
            if (gameScore < 0 && !win) gameScoreWins++;
            gameScoreTotal++;

            double gameScorePct = -1;
            double gameScorePct_err = -1;

            double unadjustedSrsVal = wa1->getSrs() - wa2->getSrs();
            if (win && unadjustedSrsVal >= 0) unadjustedSrsWins++;
            if (!win && unadjustedSrsVal < 0) unadjustedSrsWins++;
            unadjustedSrsTotal++;

            double srsVal = wa1->getSrs() - wa2->getSrs() + additions->get(team.second->getYear(),loc);
            if (win && srsVal >= 0) srsWins++;
            if (!win && srsVal < 0) srsWins++;
            srsTotal++;

            if (gameScore >= 0 && srsVal >= 0){
                if (win) srsGameScoreWins++;
                srsGameScoreTotal++;
            }
            if (gameScore < 0 && srsVal < 0){
                if (!win) srsGameScoreWins++;
                srsGameScoreTotal++;
            }

            if (useHistogramsFile){
                if (gameScore >= 3){
                    gameScorePct = 1;
                    gameScorePct_err = 1;
                }
                else if (gameScore <= -3){
                    gameScorePct = 0;
                    gameScorePct_err = 1;
                }
                else{
                    gameScorePct = probs_by_year[team.second->getYear()]->GetBinContent((gameScore+3)*1600/6.0);
                    gameScorePct_err = probs_err_by_year[team.second->getYear()]->GetBinContent((gameScore+3)*1600/6.0);
                }

                if (gameScorePct >= 0.5 && gameScorePct - sigmas*gameScorePct_err >= 0.5 && win) adjGameScoreWins++;
                if (gameScorePct < 0.5 && gameScorePct + sigmas*gameScorePct_err < 0.5 && !win) adjGameScoreWins++;
                if ((gameScorePct >= 0.5 && gameScorePct - sigmas*gameScorePct_err >= 0.5) ||
                    (gameScorePct < 0.5 && gameScorePct + sigmas*gameScorePct_err < 0.5)) adjGameScoreTotal++;

                if (win) h_wins->Fill(gameScorePct);
                h_total->Fill(gameScorePct);

                if (spread != 0 && spread == -1*oppgame->getSpread()){
                    mySpread = pctToSpread(gameScorePct);
                    myspread_vs_pct->Fill(gameScorePct,mySpread);
                    spread_vs_spread->Fill(spread, mySpread);
                    myPct_vs_VegasPct->Fill(spreadToPct(spread),gameScorePct);
                }
            }

            if (spread != -1*oppgame->getSpread()) continue; //if the spreads are somehow messed up

            if (spread != 0){
                gameScoreTotalSpread++;
                if (gameScore > 0 && win) gameScoreWinsSpread++;
                if (gameScore < 0 && !win) gameScoreWinsSpread++;

                srsTotalSpread++;
                if (win && srsVal >= 0) srsWinsSpread++;
                if (!win && srsVal < 0) srsWinsSpread++;

                if (gameScore >= 0 && srsVal >= 0){
                    if (win) srsGameScoreWinsSpread++;
                    srsGameScoreTotalSpread++;
                }
                if (gameScore < 0 && srsVal < 0){
                    if (!win) srsGameScoreWinsSpread++;
                    srsGameScoreTotalSpread++;
                }

                vegasTotalSpread++;
                if (spread < 0 && win) vegasWinsSpread++;
                if (spread > 0 && !win) vegasWinsSpread++;
            }
        }
    }

    std::cout << "All Games" << std::endl;
    std::cout << "gameScore:\t\t" << gameScoreWins << " / " << gameScoreTotal << " = " <<
    doubleFormatter(gameScoreWins / (double) gameScoreTotal, 3) << std::endl;

    if (useHistogramsFile) {
        std::cout << "Games above sigma:\t" << adjGameScoreWins << " / " << adjGameScoreTotal << " = " <<
        doubleFormatter(adjGameScoreWins / (double) adjGameScoreTotal, 3) << std::endl;
    }

    std::cout << "Unadjusted SRS:\t\t" << unadjustedSrsWins << " / " << unadjustedSrsTotal << " = " <<
    doubleFormatter(unadjustedSrsWins / (double) unadjustedSrsTotal, 3) << std::endl;

    std::cout << "Adjusted SRS:\t\t" << srsWins << " / " << srsTotal << " = " <<
    doubleFormatter(srsWins / (double) srsTotal, 3) << std::endl;

    std::cout << "SRS, GameScore agree :\t" << srsGameScoreWins << " / " << srsGameScoreTotal << " = " <<
    doubleFormatter(srsGameScoreWins / (double) srsGameScoreTotal, 3) << std::endl;

    std::cout << std::endl;

    std::cout << "Games with a spread" << std::endl;
    std::cout << "Vegas:\t\t\t" << vegasWinsSpread << " / " << vegasTotalSpread << " = " <<
    doubleFormatter(vegasWinsSpread / (double) vegasTotalSpread,3) << std::endl;

    std::cout << "gameScore:\t\t" << gameScoreWinsSpread << " / " << gameScoreTotalSpread << " = " <<
    doubleFormatter(gameScoreWinsSpread / (double) gameScoreTotalSpread, 3) << std::endl;

    std::cout << "SRS:\t\t\t" << srsWinsSpread << " / " << srsTotalSpread << " = " <<
    doubleFormatter(srsWinsSpread / (double) srsTotalSpread, 3) << std::endl;

    std::cout << "SRS, GameScore agree :\t" << srsGameScoreWinsSpread << " / " << srsGameScoreTotalSpread << " = " <<
    doubleFormatter(srsGameScoreWinsSpread / (double) srsGameScoreTotalSpread, 3) << std::endl;

    if (outFileName != "") {
        outFile->Write();
        outFile->Close();
    }

    return 0;
}
Exemplo n.º 29
0
void CompareCent(){
gStyle->SetOptStat(kFALSE);
gStyle->SetErrorX(0);
TString coll="PbP";
bool Save=kTRUE;
TF1 * fCen = new TF1("fCen","[0]*exp([1]+[2]*x+[3]*x*x+[4]*x*x*x+[5]*x*x*x*x+[6]*x*x*x*x*x)", 0., 100.);
if(coll=="PPb"){
//fCen->SetParameters(1.20916e-02, 5.02157e+00, -3.38300e-02, 1.87647e-03, -6.76442e-05, 9.08602e-07, -4.01536e-09);//parameterize on 05.03 after approval
//fCen->SetParameters(7.92204e-03, 4.52005e+00, 9.77340e-02, -5.00362e-03, 9.74735e-05, -8.93897e-07, 3.39375e-09);//parameterize on new official MC after QM on 12/03/14
fCen->SetParameters(6.06918e-03, 4.84487e+00, 4.26255e-02, -1.30682e-03, 1.94753e-05, -2.53606e-07, 1.61323e-09); //! parameterize on new official MC using double side HF on 02/02/15
TH1F* histodata=(TH1F*)fDataPPb->Get("Cent");
TH1F* histo1=(TH1F*)fMCPPb->Get("Cent");
//TH1F* histo2=(TH1F*)fNMCPPb->Get("Cent");
TH1F* histo2=(TH1F*)fMCPPb->Get("CentW");
TString data="Pb going positive side";
}
//fCen->SetParameters(8.68073e-03, 5.09356e+00, -1.33053e-02, 1.46904e-03, -6.99681e-05, 1.06721e-06, -5.21398e-09); //original
else if(coll=="PbP"){
//fCen->SetParameters(1.05408e-02, 5.27477e+00, -8.03382e-02, 3.51669e-03, -8.85332e-05, 1.08917e-06, -4.90091e-09);
//fCen->SetParameters(1.14851e-02, 5.31172e+00, -8.52366e-02, 3.00268e-03, -6.04667e-05, 6.24105e-07, -2.43580e-09);
//fCen->SetParameters(2.89263e-02, 3.43643e+00, 5.62562e-02, -1.86555e-03, 1.97924e-06, 3.15416e-07, -1.97946e-09);//parameterize on new official MC after QM on 12/03/14
fCen->SetParameters(5.10893e-03,4.88698e+00,8.37930e-02,-3.77127e-03, 7.90191e-05,-9.04877e-07, 4.26221e-09); //! parameterize on new official MC using double side HF on 02/02/15
TH1F* histodata=(TH1F*)fDataPbP->Get("Cent");
TH1F* histo1=(TH1F*)fMCPbP->Get("Cent");
//TH1F* histo2=(TH1F*)fNMCPbP->Get("Cent");
TH1F* histo2=(TH1F*)fMCPbP->Get("CentW");
TString data="Proton going positive side";
}
histo1->SetName(Form("%sNewMC_unweighted",coll.Data()));
histo2->SetName(Form("%sNewMC_weighted",coll.Data()));
histodata->SetName(Form("%sData",coll.Data()));
//histo1=(TH1F*)histo1->Rebin(Nbin_vz,"histo1",binbound_vz);
//histo2=(TH1F*)histo2->Rebin(Nbin_vz,"histo2",binbound_vz);
histo1->Scale(1/histo1->Integral());
histo2->Scale(1/histo2->Integral());
histodata->Scale(1/histodata->Integral());
histo1->SetMarkerStyle(24);
histo1->SetMarkerSize(1.2);
histo1->SetMarkerColor(4);
histo1->SetLineColor(4);
histo2->SetMarkerStyle(0);
histo2->SetMarkerSize(0);
histo2->SetFillStyle(3004);
histo2->SetFillColor(2);
histo2->SetLineColor(2);
//histo2->SetMarkerColor(4);
//histo2->SetMarkerColor(2);
histodata->SetMarkerStyle(20);
histodata->SetMarkerSize(1.2);
histodata->SetMarkerColor(1);
histodata->SetLineColor(1);

TCanvas* c1 = new TCanvas("c1"," ",500,500);
TCanvas* c2 = new TCanvas("c2"," ",500,500);
makeMultiPanelCanvas(c1,1,1,-0.16,0,0.16,0.14,0.03);
makeMultiPanelCanvas(c2,1,1,-0.16,0,0.16,0.14,0.03);

TH1F* hFrame=new TH1F("","",100,0,100);
fixedFontHist(hFrame,1.2,1.7);
hFrame->SetTitle("");
hFrame->GetXaxis()->SetTitleSize(0.05);
hFrame->GetYaxis()->SetTitleSize(0.05);
hFrame->GetXaxis()->SetTitle("Centrality");
hFrame->GetYaxis()->SetTitle("Event Fraction");
hFrame->GetXaxis()->SetLimits(0,100);
//hFrame->GetXaxis()->SetLimits(-3,3);
hFrame->GetYaxis()->SetRangeUser(0,9.2e-2);
c1->cd(1);
hFrame->DrawCopy();
histodata->Draw("same");
histo1->Draw("same");
histo2->Draw("HIST same");
TLegend *leg1=new TLegend(0.20,0.80,0.85,0.92);
TLegend *leg2=new TLegend(0.20,0.80,0.85,0.92);
leg1->SetBorderSize(0);
leg2->SetBorderSize(0);
leg1->SetFillColor(0);
leg2->SetFillColor(0);
leg1->SetTextSize(0.04);
leg2->SetTextSize(0.04);
leg1->AddEntry(histo1,"Before Centrality weighting","lp");
leg1->AddEntry(histo2,"After Centrality weighting","lfp");
//leg1->AddEntry(histo2,"Before Centrality weighting Last 2 pthat","lfp");
leg1->AddEntry(histodata,data,"lp");
leg1->Draw("same");
TLatex *T1=new TLatex(0.25,0.92,"");
T1->SetNDC();
T1->SetTextAlign(12);
T1->SetTextSize(0.05);
T1->SetTextColor(1);
T1->SetTextFont(42);
T1->Draw("same");
c2->cd(1);
hFrame->GetYaxis()->SetTitle("Data/MC");
hFrame->GetXaxis()->SetLimits(0,100);
hFrame->GetYaxis()->SetRangeUser(0,2);
hFrame->DrawCopy();
TH1F* ratio = (TH1F*)histodata->Clone(Form("%sratio",coll.Data()));
//ratio->SetName("ratio");
ratio->Divide(histo1);
/*ratio->Fit(fCen);
cout<<fCen->GetNDF()<<endl;
cout<<fCen->GetChisquare()<<endl;
for(int icent=0;icent<=6;icent++)
cout<<fCen->GetParameter(icent)<<",";
cout<<endl;*/
ratio->DrawCopy("same");
fCen->SetLineColor(2);
fCen->Draw("same");
leg2->AddEntry(ratio,data,"lp");
leg2->AddEntry(fCen,"reweighting function","lp");
leg2->Draw("same");
if(Save){
TFile *fout = new TFile("CentCompare.root","Update");
fout->cd();
ratio->Write("",TObject::kOverwrite);
histo1->Write("",TObject::kOverwrite);
histo2->Write("",TObject::kOverwrite);
histodata->Write("",TObject::kOverwrite);
fout->Close();
c2->Print(Form("ratio_Cent_%s.png",coll.Data()));
c1->Print(Form("CentCompare_Data%s.png",coll.Data()));
c1->Print(Form("CentCompare_Data%s.pdf",coll.Data()));
}

}
Exemplo n.º 30
0
void TreeFiller(string inFiles, string outFile, string histName) {

	
	TChain *origFiles = new TChain("treeVars", "treeVars");
	origFiles->Add(inFiles.c_str());
	
	int nEntries = origFiles->GetEntries();
	cout << "The old chain contains " << nEntries << " entries." << endl;
	
	
	float puWeight, jet1Eta, jet2Eta, deltaY, genTopPt1, genTopPt2, jet1Mass, jet2Mass, jet1MinMass, jet2MinMass, jet1BDisc, jet2BDisc, jet1SubjetMaxBDisc, jet2SubjetMaxBDisc,
			jet1tau32, jet2tau32, jet1Pt, jet2Pt, jet1bSF, jet2bSF, jet1bSFErrUp, jet2bSFErrUp, jet1bSFErrDn, jet2bSFErrDn, jetPtForMistag, mttMass, mttMassPred, mistagWt, mistagWtErr, mistagWtAll, mistagWtNsubAll, mistagWtNsub, NNoutput, ptReweight, cutflow, index, trigWt;
	int jet1NSubjets, jet2NSubjets, jet1Parton, jet2Parton, npv;
		
	origFiles->SetBranchAddress("npv", &npv);
	origFiles->SetBranchAddress("jet1Eta", &jet1Eta);
	origFiles->SetBranchAddress("jet2Eta", &jet2Eta);
	origFiles->SetBranchAddress("deltaY", &deltaY);
	origFiles->SetBranchAddress("jet1Mass", &jet1Mass);
	origFiles->SetBranchAddress("jet2Mass", &jet2Mass);
	origFiles->SetBranchAddress("jet1minMass", &jet1MinMass);
	origFiles->SetBranchAddress("jet2minMass", &jet2MinMass);
	origFiles->SetBranchAddress("jet1Nsubj", &jet1NSubjets);
	origFiles->SetBranchAddress("jet2Nsubj", &jet2NSubjets);
	origFiles->SetBranchAddress("jet1BDisc", &jet1BDisc);
	origFiles->SetBranchAddress("jet2BDisc", &jet2BDisc);
	origFiles->SetBranchAddress("jet1SubjetMaxBDisc", &jet1SubjetMaxBDisc);
	origFiles->SetBranchAddress("jet2SubjetMaxBDisc", &jet2SubjetMaxBDisc);
	origFiles->SetBranchAddress("jet1tau32", &jet1tau32);
	origFiles->SetBranchAddress("jet2tau32", &jet2tau32);
	origFiles->SetBranchAddress("jet1Pt", &jet1Pt);
	origFiles->SetBranchAddress("jet2Pt", &jet2Pt);
	origFiles->SetBranchAddress("jetPtForMistag", &jetPtForMistag);
	origFiles->SetBranchAddress("mttMass", &mttMass);
	origFiles->SetBranchAddress("mttMassPred", &mttMassPred);
	origFiles->SetBranchAddress("index", &index);
	origFiles->SetBranchAddress("cutflow", &cutflow);
	origFiles->SetBranchAddress("NNoutput", &NNoutput);
	origFiles->SetBranchAddress("mistagWt", &mistagWt);
	origFiles->SetBranchAddress("genTopPt1", &genTopPt1);	
	origFiles->SetBranchAddress("genTopPt2", &genTopPt2);
	origFiles->SetBranchAddress("jet1Parton", &jet1Parton);
	origFiles->SetBranchAddress("jet2Parton", &jet2Parton);	
	origFiles->SetBranchAddress("trigWt", &trigWt);
	
	TFile *newFile = new TFile(outFile.c_str(), "RECREATE");
	TTree *newTree = origFiles->CloneTree(0);
	newTree->Branch("mistagWtNsub", &mistagWtNsub, "mistagWtNsub/F");
	newTree->Branch("mistagWtNsubAll", &mistagWtNsubAll, "mistagWtNsubAll/F");
	newTree->Branch("mistagWtAll", &mistagWtAll, "mistagWtAll/F");
	newTree->Branch("ptReweight", &ptReweight, "ptReweight/F");
	newTree->Branch("puWeight", &puWeight, "puWeight/F");
	newTree->Branch("jet1bSF", &jet1bSF, "jet1bSF/F");
	newTree->Branch("jet2bSF", &jet2bSF, "jet2bSF/F");
	newTree->Branch("jet1bSFErrUp", &jet1bSFErrUp, "jet1bSFErrUp/F");
	newTree->Branch("jet2bSFErrUp", &jet2bSFErrUp, "jet2bSFErrUp/F");
	newTree->Branch("jet1bSFErrDn", &jet1bSFErrDn, "jet1bSFErrDn/F");
	newTree->Branch("jet2bSFErrDn", &jet2bSFErrDn, "jet2bSFErrDn/F");
	newTree->Branch("mistagWtErr", &mistagWtErr, "mistagWtErr/F");

	newTree->SetBranchAddress("mistagWtNsub", &mistagWtNsub);
	newTree->SetBranchAddress("misagWtNsubAll", &mistagWtNsubAll);
	newTree->SetBranchAddress("mistagWtAll", &mistagWtAll);
	newTree->SetBranchAddress("ptReweight", &ptReweight);
	newTree->SetBranchAddress("puWeight", &puWeight);
	newTree->SetBranchAddress("mistagWtErr", &mistagWtErr);

/*	
	TMVA::Reader* reader = new TMVA::Reader();
	reader->AddVariable("jet1Eta", &jet1Eta);
	reader->AddVariable("jet2Eta", &jet2Eta);
	reader->AddVariable("deltaY", &deltaY);
	reader->AddVariable("jet1Mass", &jet1Mass);
	reader->AddVariable("jet2Mass", &jet2Mass);
	reader->AddVariable("jet1BDisc", &jet1BDisc);
	reader->AddVariable("jet2BDisc", &jet2BDisc);
	reader->AddVariable("jet1SubjetMaxBDisc", &jet1SubjetMaxBDisc);
	reader->AddVariable("jet2SubjetMaxBDisc", &jet2SubjetMaxBDisc);
	reader->AddVariable("jet1tau32", &jet1tau32);
	reader->AddVariable("jet2tau32", &jet2tau32);
	reader->AddVariable("jet1Pt", &jet1Pt);
	reader->AddVariable("jet2Pt", &jet2Pt);
	reader->AddVariable("mttMass", &mttMass);

	reader->BookMVA("MLP", "weights/TMVA_tt_Zp_MLP.weightsZp10_cut4.xml");
*/	
	//TFile *mistagFileLow = new TFile("notCSVL_notCSVM_mistag.root");
	//TFile *mistagFileMed = new TFile("CSVL_notCSVM_mistag.root");
	//TFile *mistagFileHi = new TFile("CSVM_mistag.root");
	TFile *mistagFile = new TFile("Jul3_mistag.root");//data_AllBscore_mistag_Dec16.root");
	histName = "MISTAG_RATE_SUB_TTBAR_Inclusive";
	TFile *triggerFile = new TFile("trigger_weights.root");
	TH1F *triggerHist = (TH1F *) triggerFile->Get("triggerHist");
	TH3F *mistagRateHistAll = (TH3F *) mistagFile->Get( histName.c_str() )->Clone();	
	cout << histName << endl;
	cout << "Entries " << mistagRateHistAll->Integral() << endl;	
	TFile *puFile = new TFile("puHists.root");
	TH1F *puWeightsHist = (TH1F *) puFile->Get("weightsH");
	
	for (int i = 0; i < origFiles->GetEntries(); i++){
	
		origFiles->GetEntry(i);
		if  (i % 1000000 == 0) cout << 100*(float(i) / float(nEntries)) << " Percent Complete." << endl;
		mistagWt = 0.000;
		mistagWtNsub = 30.0000;
		puWeight = puWeightsHist->GetBinContent(npv); 	
		triggerWt = triggerHist->GetBinContent( triggerHist->FindBin( jet1Pt + jet2Pt ) );

		if (cutflow == 4 || index == 1){
		
			if (genTopPt1 > 400) genTopPt1 = 400;
			if (genTopPt2 > 400) genTopPt2 = 400;
			//NNoutput =  reader->EvaluateMVA("MLP");
			ptReweight = sqrt( exp(0.156 - 0.00137*genTopPt1)*exp(0.156 - 0.00137*genTopPt2) );			
		
			
			jet1bSF = 1.0;
			jet1bSFErrUp = 1.0;
			jet1bSFErrDn = 1.0;
			jet2bSF = 1.0;
			jet2bSFErrUp = 1.0;
			jet2bSFErrDn = 1.0;

			if (jet1BDisc > 0.679){
				jet1bSF = findBSF(jet1Pt, jet1Eta, jet1Parton, 0);
				jet1bSFErrUp = findBSF(jet1Pt, jet1Eta, jet1Parton, 1);
				jet1bSFErrDn = findBSF(jet1Pt, jet1Eta, jet1Parton, -1);
			}
			if (jet2BDisc > 0.679){
				jet2bSF = findBSF(jet2Pt, jet2Eta, jet2Parton, 0);
				jet2bSFErrUp = findBSF(jet2Pt, jet2Eta, jet2Parton, 1);
				jet2bSFErrDn = findBSF(jet2Pt, jet2Eta, jet2Parton, -1);
			}

	
			if (index == 1) {
				
				float bScore = -9.99;
				float tauScore = 9.99;
				int probeJet = 0;
				if (jet1Pt == jetPtForMistag) {
					probeJet = 1;
					bScore = jet1SubjetMaxBDisc;
					tauScore = jet1tau32;
				}
				if (jet2Pt == jetPtForMistag) {
					bScore = jet2SubjetMaxBDisc;
					tauScore = jet2tau32;
					probeJet = 2;
				}

				int bin = mistagRateHistAll->FindBin( ptMap(jetPtForMistag),bMap(bScore),tauMap(tauScore) );
				mistagWt = mistagRateHistAll->GetBinContent( bin );
				mistagWtErr = mistagRateHistAll->GetBinError( bin );
			}
		
			newTree->Fill();
		
		}
		

	}


	
	
	


	newFile->cd();
	newTree->Write();
	newFile->Write();
	newFile->Close();
	
}