Example #1
0
int main(int argc, char* argv[]){

   // declarations
   Fitter fitter;
   map<string, Dataset> datasets;
   vector<Event> eventvec_datamc;
   vector<Event> eventvec_train;
   vector<Event> eventvec_test;
   map< string, map<string, TH1D*> > hists_all_;
   map< string, map<string, TH1D*> > hists_train_;
   map< string, map<string, TH1D*> > hists_test_;

   // output fit results
   int run_number=-1;
   int fitstatus=-1;
   double mt=0, mt_err=0;
   double kmbl=0, kmbl_err=0;
   double k220=0, k220_err=0;
   double mcmass=0;
   double fitchi2=0;
   double tsig_mbl_chi2 [8] = {0};
   double tbkg_mbl_chi2 [8] = {0};
   
   TTree *tree = new TTree("FitResults", "FitResults");
   tree->Branch("runNumber", &run_number);
   tree->Branch("fitStatus", &fitstatus);
   tree->Branch("mt", &mt);
   tree->Branch("mt_err", &mt_err);
   tree->Branch("kmbl", &kmbl);
   tree->Branch("kbml_err", &kmbl_err);
   tree->Branch("k220", &k220);
   tree->Branch("k220_err", &k220_err);
   tree->Branch("mcmass", &mcmass);
   tree->Branch("fitchi2", &fitchi2);
   tree->Branch("tsig_mbl_chi2", tsig_mbl_chi2, "tsig_mbl_chi2[8]/D");
   tree->Branch("tbkg_mbl_chi2", tbkg_mbl_chi2, "tbkg_mbl_chi2[8]/D");


   // option flags
   int c;
   int do_fit = 0;
   int do_diagnostics = 0;
   int use_data = 0;
   float masspnt = 0;
   int do_bootstrap = 0;
   int do_templates = 0;
   int do_learnparams = 0;
   int do_mbl = 0;
   int do_mt2 = 0;
   double fracevts = -1;

   struct option longopts[] = {
      { "run_number",   required_argument,   0,                'n' },
      { "fit",          no_argument,         &do_fit,          'f' },
      { "diagnostics",  no_argument,         &do_diagnostics,  'd' },
      { "templates",    no_argument,         &do_templates,    'e' },
      { "learnparams",  no_argument,         &do_learnparams,  'x' },
      { "data",         no_argument,         &use_data,        'a' },
      { "profile",      no_argument,         0,                'p' },
      { "masspnt",      required_argument,   0,                'm' },
      { "bootstrap",    no_argument,         &do_bootstrap,    'o' },
      { "fracevts",     required_argument,   0,                'c' },
      // If the lmbl flag is not entered, lengthscale_mbl has default value -1.
      // This instructs the code to not use mbl in the fit.
      // The same goes for each other kinematic variable.
      { "mbl",          no_argument,         &do_mbl,          'b' },
      { "mt2",          no_argument,         &do_mt2,          't' },
      { "help",         no_argument,         NULL,             'h' },
      { 0, 0, 0, 0 }
   };

   while( (c = getopt_long(argc, argv, "fdexahponbtm:c:", longopts, NULL)) != -1 ) {
      switch(c)
      {
         case 'n' :
            run_number = atoi(optarg);
            break;

         case 'f' :
            do_fit = 1;
            break;

         case 'd' :
            do_diagnostics = 1;
            break;

         case 'e' :
            do_templates = 1;
            break;

         case 'x' :
            do_learnparams = 1;
            break;

         case 'a' :
            use_data = 1;
            break;

         case 'm' :
            masspnt = atof(optarg);
            break;

         case 'p' :
            fitter.compute_profile = true;
            break;

         case 'o' :
            do_bootstrap = 1;
            break;

         case 'c' :
            fracevts = atof(optarg);
            break;

         case 'b' :
            do_mbl = true;
            break;

         case 't' :
            do_mt2 = true;
            break;

         case 'h' :
            print_usage();
            return -1;
            break;

         case 0:     /* getopt_long() set a variable, just keep going */
            break;

         case ':':   /* missing option argument */
            fprintf(stderr, "%s: option `-%c' requires an argument\n",
                  argv[0], optopt);
            return -1;

         case '?':
         default:    /* invalid option */
            fprintf(stderr, "%s: option `-%c' is invalid: ignored\n",
                  argv[0], optopt);
            print_usage();
            return -1;

      }
   }

   fitter.dists["mbl"].activate = do_mbl;
   fitter.dists["mt2_220_nomatchmbl"].activate = do_mt2;

   // Check that at least one kinematic variable's lengthscale has been entered.
   // Any additional distributions need to be added here
   if (!(fitter.dists["mbl"].activate) and !(fitter.dists["mt2_220_nomatchmbl"].activate) and do_fit == 1){
      std::cout << "At least one variable needed to do fit.  Input at least one lengthscale." << std::endl;
      print_usage();
      return -1;
   }

   fitter.LoadDatasets( datasets );

   // for event counting
   map<string, int> datacount;

   // random number seed for bootstrapping (turns on when nonzero)
   int randseed = 0;
   if( do_bootstrap ) randseed = run_number+1+10E6;

   cout << "\nLoading datasets" << endl;
   for(map<string, Dataset>::iterator it = datasets.begin(); it != datasets.end(); it++){

      string name = it->first;
      Dataset *dat = &(it->second);

      datacount[name] = 0;

      TFile file( (dat->path+dat->file).c_str() );
      TTree *trees = (TTree*)file.Get("RealData");

      cout << setiosflags(ios::left);
      cout << "... " << setw(25) << name
         << ": " << trees->GetEntries() << " events" << endl;

      if( do_diagnostics or use_data ){
         fitter.ReadNtuple( dat->path+dat->file, name, dat->mc_xsec/dat->mc_nevts,
               "RealData", eventvec_datamc, 0, 0, -1 );
      }

      // events for training and testing
      if( name.compare("data") != 0 ){

         if( use_data ){ // train on full mc set
            fitter.ReadNtuple( dat->path+dat->file, name, dat->mc_xsec/dat->mc_nevts,
                  "RealData", eventvec_train, 0, randseed, -1 );
         }else{
            fitter.ReadNtuple( dat->path+dat->file, name, dat->mc_xsec/dat->mc_nevts,
                  "RealData", eventvec_train, 1, randseed, -1 );
            fitter.ReadNtuple( dat->path+dat->file, name, dat->mc_xsec/dat->mc_nevts,
                  "RealData", eventvec_test, 2, randseed, fracevts );
         }

      }

   }

   // data/mc plots, kinematic distributions
   fitter.GetVariables( eventvec_datamc );
   fitter.GetVariables( eventvec_train );
   fitter.GetVariables( eventvec_test );

   fitter.DeclareHists( hists_train_, "train" );
   fitter.FillHists( hists_train_, eventvec_train );

   fitter.DeclareHists( hists_test_, "test" );
   fitter.FillHists( hists_test_, eventvec_test );

   if( do_diagnostics ){ 
      fitter.DeclareHists( hists_all_, "all" );
      fitter.FillHists( hists_all_, eventvec_datamc );
      fitter.PrintHists( hists_all_ );
   }

   if( do_fit ){

      vector<Event> eventvec_fit;
      vector<Event> eventvec_fit_bkgcontrol;
      map< string, map<string, TH1D*> > hists_fit_;
      map< string, map<string, TH1D*> > hists_fit_bkgcontrol_;

      if( use_data ){ // added 220 distribution to the data fit too, but haven't tested it

         //
         // turn this feature off for now -- will need to clean up later.
         //

         /*
         cout << "REMINDER: EVENT WEIGHTS IN MC" << endl;
         for(vector<Event>::iterator ev = eventvec_datamc.begin(); ev < eventvec_datamc.end();ev++){
            if( ev->type.find("data") != string::npos ){
               if( ev->type.find("bkgcontrol") == string::npos ){
                  eventvec_fit.push_back(*ev);
               }else{
                  eventvec_fit_bkgcontrol.push_back(*ev);
               }
            }
         }

         // flag events to be fitted
         for( vector<Event>::iterator ev = eventvec_fit.begin(); ev < eventvec_fit.end(); ev++){
            ev->fit_event = true;
            for(map<string, int>::iterator it = datacount.begin(); it != datacount.end(); it++){
               if( ev->process.compare(it->first) == 0 ) datacount[it->first]+=1;
            }
         }
         for( vector<Event>::iterator ev = eventvec_fit_bkgcontrol.begin();
               ev < eventvec_fit_bkgcontrol.end(); ev++){
            ev->fit_event = true;
            for(map<string, int>::iterator it = datacount.begin(); it != datacount.end(); it++){
               if( ev->process.compare(it->first) == 0 ) datacount[it->first]+=1;
            }
         }
         cout << "Fit event count: " << endl;
         cout << setiosflags(ios::left);
         for(map<string, int>::iterator it = datacount.begin(); it != datacount.end(); it++){
            cout << "... " << setw(25) << it->first << ": " << it->second << " events" << endl;
         }

         fitter.DeclareHists( hists_fit_, "fit" );
         fitter.FillHists( hists_fit_, eventvec_fit, true );
         fitter.DeclareHists( hists_fit_bkgcontrol_, "fit_bkgcontrol" );
         fitter.FillHists( hists_fit_bkgcontrol_, eventvec_fit_bkgcontrol, true );

         double wgt=0;
         for(vector<Event>::iterator ev = eventvec_fit.begin(); ev < eventvec_fit.end(); ev++){
            wgt += ev->weight;
         }
         cout << "wgt = " << wgt << endl;

         // do GP training
         cout << "Training GP." << endl;

         // GP training for mbl
         if ( lengthscale_mbl != -1){
            Shapes * fptr = new Shapes( "mbl", fitter.gplength_mbl, fitter.gplength_mt_mbl,
                  fitter.lbnd, fitter.rbnd );
            fptr->TrainGP( hists_train_ );
            fitter.aGPsig.ResizeTo( fptr->aGPsig.GetNoElements() );
            fitter.aGPsig = fptr->aGPsig;
            fitter.aGPbkg.ResizeTo( fptr->aGPbkg.GetNoElements() );
            fitter.aGPbkg = fptr->aGPbkg;
         }

         // GP training for 220
         if ( lengthscale_220 != -1){
            Shapes * fptr220 = new Shapes( "mt2_220_nomatchmbl", fitter.gplength_220, fitter.gplength_mt_220,
                  fitter.lbnd, fitter.rbnd );
            fptr220->TrainGP( hists_train_ );
            fitter.aGPsig220.ResizeTo( fptr220->aGPsig.GetNoElements() );
            fitter.aGPsig220 = fptr220->aGPsig;
            fitter.aGPbkg220.ResizeTo( fptr220->aGPbkg.GetNoElements() );
            fitter.aGPbkg220 = fptr220->aGPbkg;
         }

         // events for fitting, hists for training
         fitter.RunMinimizer( eventvec_fit );
         fitter.PlotResults( hists_fit_ ); // plot fitted events

         // fill results tree
         mcmass = 0;
         fitstatus = fitter.gMinuit->Status();
         const double *par = fitter.gMinuit->X();
         const double *par_err = fitter.gMinuit->Errors();
         mt = par[0];
         kmbl = par[1];
         k220 = par[2];
         mt_err = par_err[0];
         kmbl_err = par_err[1];
         k220_err = par_err[2];
         fitchi2 = fitter.fitchi2;
         gplength_mbl = lengthscale_mbl;
         gplength_220 = lengthscale_220;
         gplength_mt_mbl = lengthscale_mt_mbl;
         gplength_mt_220 = lengthscale_mt_220;

         // TODO
         //tree->Fill();

         eventvec_fit.clear();
         eventvec_fit_bkgcontrol.clear();
         fitter.DeleteHists( hists_fit_ );
         fitter.DeleteHists( hists_fit_bkgcontrol_ );
         */

      }else{ // loop over mc masses

         double masspnts [] = {161.5,163.5,166.5,169.5,172.5,175.5,178.5,181.5};
         for(int i=0; i < 8; i++){

            double mass = masspnts[i];
            // masspoint from command line
            if( masspnt != 0 ){
               bool check = false;
               for(int j=0; j < 8; j++){
                  if( masspnts[j] == masspnt ) check = true;
               }
               if(check){
                  mass = masspnt;
                  i = 7;
               }else{
                  cout << "masspoint " << masspnt << " not found!" << endl;
                  return -1;
               }
            }

            cout << "############# Fitting Masspoint " << mass << " ###############" << endl;

            stringstream dstr;
            dstr << floor(mass);
            string dname = "ttbar"+dstr.str();

            // load events to be fitted
            for(vector<Event>::iterator ev = eventvec_test.begin(); ev < eventvec_test.end(); ev++){
               if( ev->type.find(dname) != string::npos or ev->type.find("other") != string::npos ){
                  if( ev->type.find("bkgcontrol") == string::npos ){
                        eventvec_fit.push_back(*ev);
                  }else{
                     eventvec_fit_bkgcontrol.push_back(*ev);
                  }
               }
            }

            fitter.ReweightMC( eventvec_fit, dname );

            // flag events to be fitted
            for( vector<Event>::iterator ev = eventvec_fit.begin(); ev < eventvec_fit.end(); ev++){
               ev->fit_event = true;
               for(map<string, int>::iterator it = datacount.begin(); it != datacount.end(); it++){
                  if( ev->process.compare(it->first) == 0 ) datacount[it->first]+=1;
               }
            }
            for( vector<Event>::iterator ev = eventvec_fit_bkgcontrol.begin();
                  ev < eventvec_fit_bkgcontrol.end(); ev++){
               ev->fit_event = true;
               for(map<string, int>::iterator it = datacount.begin(); it != datacount.end(); it++){
                  if( ev->process.compare(it->first) == 0 ) datacount[it->first]+=1;
               }
            }

            cout << "Fit event count: " << endl;
            cout << setiosflags(ios::left);
            for(map<string, int>::iterator it = datacount.begin(); it != datacount.end(); it++){
               cout << "... " << setw(25) << it->first << ": " << it->second << " events" << endl;
            }

            fitter.DeclareHists( hists_fit_, "fit" );
            fitter.FillHists( hists_fit_, eventvec_fit, true );
            fitter.DeclareHists( hists_fit_bkgcontrol_, "fit_bkgcontrol" );
            fitter.FillHists( hists_fit_bkgcontrol_, eventvec_fit_bkgcontrol, true );

            // do GP training
            for( map<string, Distribution>::iterator it = fitter.dists.begin(); it != fitter.dists.end(); it++ ){

               string name = it->first;
               Distribution *dist = &(it->second);

               double m2llsig, m2llbkg;

               if( dist->activate ){
                  Shapes * fptr = new Shapes( name, dist->glx, dist->glmt, dist->gnorm1, dist->gnorm2 );
                  fptr->TrainGP( hists_train_, m2llsig, m2llbkg );

                  dist->aGPsig.ResizeTo( fptr->aGPsig.GetNoElements() );
                  dist->aGPsig = fptr->aGPsig;
                  dist->aGPbkg.ResizeTo( fptr->aGPbkg.GetNoElements() );
                  dist->aGPbkg = fptr->aGPbkg;

                  delete fptr;

               }

            }

            typedef map<string, TH1D*> tmap;
            typedef map<string, tmap> hmap;
            for( hmap::iterator h = hists_train_.begin(); h != hists_train_.end(); h++){
               for( tmap::iterator t = h->second.begin(); t != h->second.end(); t++){
                  for(int n=1; n < t->second->GetNbinsX(); n++){
                     if( t->second->GetBinContent(n) == 0 )
                        t->second->SetBinError(n, 1.0/35000);
                  }
               }
            }

            // events for fitting, hists for training
            fitter.RunMinimizer( eventvec_fit );
            fitter.PlotResults( hists_fit_ ); // plot fitted events

            cout << "Fit Chi2 = " << fitter.fitchi2 << endl;


            // fill results tree
            // any additional variables need to be added here
            mcmass = mass;
            fitstatus = fitter.gMinuit->Status();
            const double *par = fitter.gMinuit->X();
            const double *par_err = fitter.gMinuit->Errors();
            mt = par[0];
            kmbl = par[1];
            mt_err = par_err[0];
            kmbl_err = par_err[1];
            k220 = par[2];
            k220_err = par_err[2];
            fitchi2 = fitter.fitchi2;

            tree->Fill();

            eventvec_fit.clear();
            eventvec_fit_bkgcontrol.clear();
            fitter.DeleteHists( hists_fit_ );
            fitter.DeleteHists( hists_fit_bkgcontrol_ );

         }

      }

   }

   if( do_templates ){

            // do GP training
            for( map<string, Distribution>::iterator it = fitter.dists.begin(); it != fitter.dists.end(); it++ ){

               string name = it->first;
               Distribution *dist = &(it->second);

               double m2llsig, m2llbkg;

               if( dist->activate ){
                  Shapes * fptr = new Shapes( name, dist->glx, dist->glmt, dist->gnorm1, dist->gnorm2 );
                  fptr->TrainGP( hists_train_, m2llsig, m2llbkg );

                  dist->aGPsig.ResizeTo( fptr->aGPsig.GetNoElements() );
                  dist->aGPsig = fptr->aGPsig;
                  dist->aGPbkg.ResizeTo( fptr->aGPbkg.GetNoElements() );
                  dist->aGPbkg = fptr->aGPbkg;

                  dist->Ainv_sig.ResizeTo( fptr->aGPsig.GetNoElements(), fptr->aGPsig.GetNoElements() );
                  dist->Ainv_sig = fptr->Ainv_sig;
                  dist->Ainv_bkg.ResizeTo( fptr->aGPbkg.GetNoElements(), fptr->aGPbkg.GetNoElements() );
                  dist->Ainv_bkg = fptr->Ainv_bkg;

                  delete fptr;
               }

            }

            fitter.PlotTemplates( hists_train_ );

            for(int j=0; j < 8; j++){
               tsig_mbl_chi2[j] = fitter.tsig_mbl_chi2[j];
               tbkg_mbl_chi2[j] = fitter.tbkg_mbl_chi2[j];
            }

   }

   if( do_learnparams ){
      string name = "mbl";
      Distribution *dist = &(fitter.dists[name]);
      Shapes * fptr = new Shapes( name, dist->glx, dist->glmt, dist->gnorm1, dist->gnorm2 );
      fptr->LearnGPparams( hists_train_ );
      delete fptr;
   }

   if( do_fit or do_templates ){
      tree->Fill();
   }


   //
   // write fit results
   //
   if( do_fit or do_templates ){
      // set up output file path
      std::string pathstr;
      char* path = std::getenv("WORKING_DIR");
      if (path==NULL) {
         pathstr = "./results";
      }else {
         pathstr = path;
      }

      TFile *file = new TFile((pathstr+"/fitresults.root").c_str(), "RECREATE");
      file->cd();
      tree->Write();
      file->Write();
      file->Close();
   }

   return 0;
}
int main(int argc, char *argv[]) {

  
  if (argc!=2) {
    std::cout << "Usage: ./endpointGain.exe [octet]\n";
    //std::cout << "The code will produce comparisons for every octet in the range given,\non an octet-by-octet basis, and as a whole, using the Super-Sum\n";
    exit(0);
  }
  

  int octet = atoi(argv[1]);

  if ( std::find(badOct.begin(), badOct.end(),octet) != badOct.end() ) {

    std::cout << "Bad Octet... \n";

    std::ofstream gainFile(TString::Format("%s/EndpointGain/endpointGain_octet-%i.dat", getenv("ENDPOINT_ANALYSIS"),octet));

    for ( int i=0; i<8; ++i )  gainFile << 1. << std::endl;

    gainFile.close();

    return 0;
  }
  

  int nBins = 100;
  double minRange = 0.;
  double maxRange = 1000.;
  
  std::vector <int> runs = readOctetFile(octet);
  std::vector <int> bgruns = readOctetFileForBGruns(octet);

  std::vector < std::vector <Double_t> > pmtBackgroundRates = readPMTbackgroundRates(octet);

  

  ////////////////// Begin with data files /////////////////////

  // Vectors for creating the individual runs events and errors
  std::vector < std::vector < std::vector <Double_t> > > pmtSpec;
  std::vector < std::vector < std::vector <Double_t> > > pmtSpecErr;
    
  pmtSpec.resize(runs.size(),std::vector<std::vector<Double_t>>(8,std::vector<Double_t>(nBins,0.)));
  pmtSpecErr.resize(runs.size(),std::vector<std::vector<Double_t>>(8,std::vector<Double_t>(nBins,0.)));

  std::vector < std::vector < std::vector <Double_t> > > bgpmtSpec;
  std::vector < std::vector < std::vector <Double_t> > > bgpmtSpecErr;
    
  bgpmtSpec.resize(runs.size(),std::vector<std::vector<Double_t>>(8,std::vector<Double_t>(nBins,0.)));
  bgpmtSpecErr.resize(runs.size(),std::vector<std::vector<Double_t>>(8,std::vector<Double_t>(nBins,0.)));

  // Now loop over each run to determine the individual spectra, then fill their appropriate bins in the vector

  TH1D *spec[8]; // All 8 PMTs signals
  TH1D *bgspec[8]; // All 8 PMTs bg signals
  TH1D *simspec[8]; // All 8 PMTs signals

  int nRun = 0;
  
  std::vector <Double_t> totalTime(runs.size(),0.); // Holds the runLengths 
  std::vector <Double_t> bgtotalTime(runs.size(),0.); // Holds the runLengths 
  
  //runs.resize(0);
  for ( auto rn : runs ) {

    for ( int i=0; i<8; ++i ) {
      spec[i] = new TH1D(TString::Format("PMT%i",i),TString::Format("PMT %i",i),
		      nBins, minRange, maxRange);
    }
    
    // DataTree structure
    DataTree t;

    // Input ntuple
    char tempIn[500];
    sprintf(tempIn, "%s/replay_pass3_%i.root", getenv("REPLAY_PASS3"),rn);
    
    t.setupInputTree(std::string(tempIn),"pass3");

    unsigned int nevents = t.getEntries();

    t.getEvent(nevents-1);
    totalTime[nRun] = t.Time;

    double r2E = 0.; //position of event squared
    double r2W = 0.;
    
    for (unsigned int n=0 ; n<nevents ; n++ ) {

      t.getEvent(n);

      r2E = t.xE.center*t.xE.center + t.yE.center*t.yE.center;
      r2W = t.xW.center*t.xW.center + t.yW.center*t.yW.center;

      if ( t.PID==1 && t.Side<2 && t.Type==0 && t.Erecon>0. ) {

	if ( t.Side==0 ) {
	  if ( t.xeRC>6 || t.yeRC>6 ) continue; //only look at MWPC signal on East
	  else if ( t.xE.mult<1 || t.yE.mult<1 ) continue;
	}
	else if ( t.Side==1 ) {
	  if ( t.xwRC>6 || t.ywRC>6 ) continue; //only look at MWPC signal on West
	  else if ( t.xW.mult<1 || t.yW.mult<1 ) continue;      
	}

	if ( r2E > 30.*30. || r2W > 30.*30. ) continue;

	if ( t.Side==0 ) {
	  spec[0]->Fill(t.ScintE_bare.e1);
	  spec[1]->Fill(t.ScintE_bare.e2);
	  spec[2]->Fill(t.ScintE_bare.e3);
	  spec[3]->Fill(t.ScintE_bare.e4);
	}

	if ( t.Side==1 ) {
	  spec[4]->Fill(t.ScintW_bare.e1);
	  spec[5]->Fill(t.ScintW_bare.e2);
	  spec[6]->Fill(t.ScintW_bare.e3);
	  spec[7]->Fill(t.ScintW_bare.e4);
	}

      }
    }

    for ( int p=0; p<8; ++p ) {
      for ( int bin=1; bin<=nBins; ++bin ) {
	pmtSpec[nRun][p][bin-1] = (double)spec[p]->GetBinContent(bin)/totalTime[nRun];
	pmtSpecErr[nRun][p][bin-1] = spec[p]->GetBinError(bin)/totalTime[nRun];
      }
    }

    for ( int i=0; i<8; ++i ) { 
      // std::cout << "deleting spec[" << i << "]\n";
      delete spec[i];
    }
    nRun++;
    
  }

  nRun = 0;

  for ( auto rn : bgruns ) {

    for ( int i=0; i<8; ++i ) {
      bgspec[i] = new TH1D(TString::Format("bgPMT%i",i),TString::Format("bg PMT %i",i),
		      nBins, minRange, maxRange);
    }
    
    // DataTree structure
    DataTree t;

    // Input ntuple
    char tempIn[500];
    sprintf(tempIn, "%s/replay_pass3_%i.root", getenv("REPLAY_PASS3"),rn);
    
    t.setupInputTree(std::string(tempIn),"pass3");

    unsigned int nevents = t.getEntries();

    t.getEvent(nevents-1);
    bgtotalTime[nRun] = t.Time;

    double r2E = 0.; //position of event squared
    double r2W = 0.;
    
    for (unsigned int n=0 ; n<nevents ; n++ ) {

      t.getEvent(n);

      r2E = t.xE.center*t.xE.center + t.yE.center*t.yE.center;
      r2W = t.xW.center*t.xW.center + t.yW.center*t.yW.center;

      if ( t.PID==1 && t.Side<2 && t.Type==0 && t.Erecon>0. ) {

	if ( t.Side==0 ) {
	  if ( t.xeRC>6 || t.yeRC>6 ) continue; //only look at MWPC signal on East
	  else if ( t.xE.mult<1 || t.yE.mult<1 ) continue;
	}
	else if ( t.Side==1 ) {
	  if ( t.xwRC>6 || t.ywRC>6 ) continue; //only look at MWPC signal on West
	  else if ( t.xW.mult<1 || t.yW.mult<1 ) continue;      
	}

	if ( r2E > 30.*30. || r2W > 30.*30. ) continue;

	if ( t.Side==0 ) {
	  bgspec[0]->Fill(t.ScintE_bare.e1);
	  bgspec[1]->Fill(t.ScintE_bare.e2);
	  bgspec[2]->Fill(t.ScintE_bare.e3);
	  bgspec[3]->Fill(t.ScintE_bare.e4);
	}

	if ( t.Side==1 ) {
	  bgspec[4]->Fill(t.ScintW_bare.e1);
	  bgspec[5]->Fill(t.ScintW_bare.e2);
	  bgspec[6]->Fill(t.ScintW_bare.e3);
	  bgspec[7]->Fill(t.ScintW_bare.e4);
	}

      }
    }
    std::cout << "Made it through filling hists\n";
    for ( int p=0; p<8; ++p ) {
      for ( int bin=1; bin<=nBins; ++bin ) {
	bgpmtSpec[nRun][p][bin-1] = (double)bgspec[p]->GetBinContent(bin)/bgtotalTime[nRun];
	bgpmtSpecErr[nRun][p][bin-1] = ( bgspec[p]->GetBinContent(bin)>20 ?
					 bgspec[p]->GetBinError(bin)/bgtotalTime[nRun] :
					 TMath::Sqrt(pmtBackgroundRates[bin-1][p]/bgtotalTime[nRun]) );
      }
    }

    for ( int i=0; i<8; ++i ) { 
      // std::cout << "deleting spec[" << i << "]\n";
      delete bgspec[i];
    }
    nRun++;
    
  }

  

  ////////////// Now for simulation //////////////////
  // Vectors for creating the individual runs events and errors
  std::vector < std::vector < std::vector <Double_t> > > simSpec;
  std::vector < std::vector < std::vector <Double_t> > > simSpecErr;
    
  simSpec.resize(runs.size(),std::vector<std::vector<Double_t>>(8,std::vector<Double_t>(nBins,0.)));
  simSpecErr.resize(runs.size(),std::vector<std::vector<Double_t>>(8,std::vector<Double_t>(nBins,0.)));

  

  // Now loop over each run to determine the individual spectra, then fill their appropriate bins in the vector

  nRun = 0;
  
  for ( auto rn : runs ) {

    for ( int i=0; i<8; ++i ) {
      simspec[i] = new TH1D(TString::Format("SIM%i",i),TString::Format("SIM %i",i),
			 nBins, minRange, maxRange);
    }
    
    TFile *f = new TFile(TString::Format("%s/beta/revCalSim_%i_Beta.root",getenv("REVCALSIM"),rn), "READ");
    TTree *Tin = (TTree*)f->Get("revCalSim");

    std::cout << "Reading from " << TString::Format("%s/beta_highStatistics/revCalSim_%i_Beta.root",getenv("REVCALSIM"),rn).Data() << "\n";
    
    Double_t e0,e1,e2,e3,e4,e5,e6,e7;
    MWPC xE, yE, xW, yW;
    int PID, Side, Type;
    Double_t Erecon;
    
    
    Tin->SetBranchAddress("PID", &PID);
    Tin->SetBranchAddress("type", &Type);
    Tin->SetBranchAddress("side", &Side); 
    Tin->SetBranchAddress("Erecon",&Erecon);
    Tin->SetBranchAddress("xE",&xE);
    Tin->SetBranchAddress("yE",&yE);
    Tin->SetBranchAddress("xW",&xW);
    Tin->SetBranchAddress("yW",&yW);
    Tin->GetBranch("PMT")->GetLeaf("Evis0")->SetAddress(&e0);
    Tin->GetBranch("PMT")->GetLeaf("Evis1")->SetAddress(&e1);
    Tin->GetBranch("PMT")->GetLeaf("Evis2")->SetAddress(&e2);
    Tin->GetBranch("PMT")->GetLeaf("Evis3")->SetAddress(&e3);
    Tin->GetBranch("PMT")->GetLeaf("Evis4")->SetAddress(&e4);
    Tin->GetBranch("PMT")->GetLeaf("Evis5")->SetAddress(&e5);
    Tin->GetBranch("PMT")->GetLeaf("Evis6")->SetAddress(&e6);
    Tin->GetBranch("PMT")->GetLeaf("Evis7")->SetAddress(&e7);
    /*
      Tin->GetBranch("xE")->GetLeaf("center")->SetAddress(&EmwpcX);
      Tin->GetBranch("yE")->GetLeaf("center")->SetAddress(&EmwpcY);
      Tin->GetBranch("xW")->GetLeaf("center")->SetAddress(&WmwpcX);
      Tin->GetBranch("yW")->GetLeaf("center")->SetAddress(&WmwpcY);
      Tin->GetBranch("xE")->GetLeaf("nClipped")->SetAddress(&xE_nClipped);
      Tin->GetBranch("yE")->GetLeaf("nClipped")->SetAddress(&yE_nClipped);
      Tin->GetBranch("xW")->GetLeaf("nClipped")->SetAddress(&xW_nClipped);
      Tin->GetBranch("yW")->GetLeaf("nClipped")->SetAddress(&yW_nClipped);
      Tin->GetBranch("xE")->GetLeaf("mult")->SetAddress(&xE_mult);
      Tin->GetBranch("yE")->GetLeaf("mult")->SetAddress(&yE_mult);
      Tin->GetBranch("xW")->GetLeaf("mult")->SetAddress(&xW_mult);
      Tin->GetBranch("yW")->GetLeaf("mult")->SetAddress(&yW_mult);*/
    
    
    double r2E = 0.; //position of event squared
    double r2W = 0.;

    UInt_t nevents = Tin->GetEntriesFast();
    
    for (unsigned int n=0 ; n<nevents ; n++ ) {
      
      Tin->GetEvent(n);
      
      r2E = xE.center*xE.center + yE.center*yE.center;
      r2W = xW.center*xW.center + yW.center*yW.center;

      if ( PID==1 && Side<2 && Type==0 && Erecon>0. ) {

	if ( Side==0 && ( xE.mult<1 || yE.mult<1 ) ) continue;
	else if ( Side==1 && ( xW.mult<1 || yW.mult<1 ) ) continue;

	if ( r2E > 30.*30. || r2W > 30.*30. ) continue;

	
	if ( Side==0 ) {
	  simspec[0]->Fill(e0);
	  simspec[1]->Fill(e1);
	  simspec[2]->Fill(e2);
	  simspec[3]->Fill(e3);
	}

	if ( Side==1 ) {
	  simspec[4]->Fill(e4);
	  simspec[5]->Fill(e5);
	  simspec[6]->Fill(e6);
	  simspec[7]->Fill(e7);
	}

      }
    }

    for ( int p=0; p<8; ++p ) {
      for ( int bin=1; bin<=nBins; ++bin ) {
	simSpec[nRun][p][bin-1] = (double)simspec[p]->GetBinContent(bin)/totalTime[nRun];
	simSpecErr[nRun][p][bin-1] = simspec[p]->GetBinError(bin)/totalTime[nRun];
      }
    }

    for ( int i=0; i<8; ++i ) { 
      // std::cout << "deleting spec[" << i << "]\n";
      delete simspec[i];
    }
    nRun++;
    delete f;
    
  }

  //Now we take the weighted average over the runs in the octet
  
  TFile *fout = new TFile(TString::Format("%s/EndpointGain/endpointGain_octet-%i.root",
					  getenv("ENDPOINT_ANALYSIS"),octet),"RECREATE");
  //TFile *fout = new TFile(TString::Format("endpointGain_octet-%i.root",
  //					  octet),"RECREATE");
  
  std::cout << "Made output rootfile...\n\n";

  // Data //

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

    spec[i] = new TH1D(TString::Format("PMT%i",i),TString::Format("PMT %i",i),
		    nBins, minRange, maxRange);

  }
 
  for ( int p=0; p<8; ++p ) {
    for ( int bin=1; bin<=nBins; ++bin ) {
      
      double numer = 0.;
      double denom = 0.;
      
      for ( UInt_t i=0; i<runs.size(); ++i ) {
	
	//First background subtract each rate (keeping the error on the rate as just the counting
	// error
	if (i==0) std::cout << bin << ": " <<  pmtSpec[i][p][bin-1] << " - " << bgpmtSpec[i][p][bin-1] << " = ";
	pmtSpec[i][p][bin-1] -= bgpmtSpec[i][p][bin-1];//pmtBackgroundRates[bin-1][p];	
	pmtSpecErr[i][p][bin-1] = TMath::Sqrt( 
					      TMath::Power(bgpmtSpecErr[i][p][bin-1],2) + 
					      TMath::Power(pmtSpecErr[i][p][bin-1],2) );
	if (i==0) std::cout << pmtSpec[i][p][bin-1] << std::endl;

	double weight = pmtSpecErr[i][p][bin-1]>0. ? 1./(pmtSpecErr[i][p][bin-1]*pmtSpecErr[i][p][bin-1]) : 0.;
	numer += pmtSpec[i][p][bin-1]*weight;
	denom += weight;
      }

      spec[p]->SetBinContent(bin, denom>0. ? numer/denom : 0.);
      spec[p]->SetBinError(bin, denom>0. ? TMath::Sqrt(1./denom) : 0. );
    }
  }

  // Sim //
  for ( int i=0; i<8; ++i ) {

    simspec[i] = new TH1D(TString::Format("SIM%i",i),TString::Format("SIM %i",i),
		    nBins, minRange, maxRange);

  }
 
  for ( int p=0; p<8; ++p ) {
    for ( int bin=1; bin<=nBins; ++bin ) {

      double numer = 0.;
      double denom = 0.;
      
      for ( UInt_t i=0; i<runs.size(); ++i ) {
	double weight = simSpec[i][p][bin-1]>0. ? 1./(simSpecErr[i][p][bin-1]*simSpecErr[i][p][bin-1]) : 0.;
	numer += simSpec[i][p][bin-1]*weight;
	denom += weight;
      }

      simspec[p]->SetBinContent(bin, denom>0. ? numer/denom : 0.);
      simspec[p]->SetBinError(bin, denom>0. ? TMath::Sqrt(1./denom) : 0. );
    }
  }

  
  
  
  /////////////////////////// Kurie Fitting ////////////////////

  // First I'm going to Kurie fit the simulated endpoint, and then
  // I will iterate until the data until the endpoint matches this endpoint

  std::vector <Double_t> gain(8,0.);

  TGraphErrors kurie[8];
  TGraphErrors simkurie[8];

  KurieFitter kf, simkf;

  for ( int i=0; i<8; ++i ) {
    
    simkf.FitSpectrum(simspec[i],250.,500.,1.); //Fit the simulated spectrum to get relative endpoint

    kf.setActualW0( simkf.returnW0() ); // Setting the comparison endpoint to the extracted ep from sim
    kf.IterativeKurie(spec[i],250.,500.,1.,1.e-7);
   

    kurie[i] = kf.returnKuriePlot();
    kurie[i].SetName(TString::Format("data%i",i));
    kurie[i].Write();
    
    simkurie[i] = simkf.returnKuriePlot();
    simkurie[i].SetName(TString::Format("sim%i",i));
    simkurie[i].Write();

    gain[i] = kf.returnAlpha();

  }

  
  /*///// Getting the gains... 

  std::vector <Double_t> alpha_data(8,0.);
  std::vector <Double_t> alpha_sim(8,0.);
  std::vector <Double_t> gain(8,0.);

  TGraphErrors kurie[8];
  TGraphErrors simkurie[8];

  KurieFitter kf, simkf;

  for ( int i=0; i<8; ++i ) {
    
    kf.IterativeKurie(spec[i],300.,500.,1.1,1.e-6);
    simkf.IterativeKurie(simspec[i],300.,500.,1.1,1.e-6);

    kurie[i] = kf.returnKuriePlot();
    kurie[i].SetName(TString::Format("data%i",i));
    kurie[i].Write();
    
    simkurie[i] = simkf.returnKuriePlot();
    simkurie[i].SetName(TString::Format("sim%i",i));
    simkurie[i].Write();

    alpha_data[i] = kf.returnAlpha();
    alpha_sim[i] = simkf.returnAlpha();

    gain[i] = alpha_sim[i]>0. ? alpha_data[i]/alpha_sim[i] : 1.;

    }*/

  /// Write out pmt endpoint gain corrections
  std::ofstream gainFile(TString::Format("%s/EndpointGain/endpointGain_octet-%i.dat",
  					 getenv("ENDPOINT_ANALYSIS"),octet));
  // std::ofstream gainFile(TString::Format("endpointGain_octet-%i.dat",octet));

  for ( auto g : gain ) gainFile << g << std::endl;

  gainFile.close();
  

  fout->Write();
  delete fout;

  return 0;
  
}
void comparator_pu::Loop()
{
//   In a ROOT session, you can do:
//      Root > .L comparator_pu.C
//      Root > comparator_pu t
//      Root > t.GetEntry(12); // Fill t data members with entry number 12
//      Root > t.Show();       // Show values of entry 12
//      Root > t.Show(16);     // Read and show values of entry 16
//      Root > t.Loop();       // Loop on all entries
//

//     This is the loop skeleton where:
//    jentry is the global entry number in the chain
//    ientry is the entry number in the current Tree
//  Note that the argument to GetEntry must be:
//    jentry for TChain::GetEntry
//    ientry for TTree::GetEntry and TBranch::GetEntry
//
//       To read only selected branches, Insert statements like:
// METHOD1:
//    fChain->SetBranchStatus("*",0);  // disable all branches
//    fChain->SetBranchStatus("branchname",1);  // activate branchname
// METHOD2: replace line
//    fChain->GetEntry(jentry);       //read all branches
//by  b_branchname->GetEntry(ientry); //read only this branch
   if (fChain == 0) return;

   Long64_t nentries = fChain->GetEntriesFast();


   TFile *outfile = new TFile("joined.root","recreate");
   outfile->cd();
   TTree *outtree = new TTree("SCtree","SCtree");

   // Declaration of leaf types
   Int_t           event_nRecoVertex3;
   Float_t         event_rho3;
   Float_t         GenEnergy3;
   Float_t         GenEta3;
   Float_t         GenPhi3;
   Int_t           pho_isInPhiCrack3;
   Int_t           pho_isInEtaCrack3;
   Int_t           pho_isInEBEEGap3;
   Float_t         phoSC_RawEtCetaCorr3;
   Float_t         phoSC_RawEnergyCetaCorr3;
   Float_t         phoSC_GeomEta3;
   Float_t         phoSC_GeomPhi3;
   Float_t         pho_r93;
   Float_t         pho_Brem3;
   Float_t         pho_SCarea3;

   // Declaration of leaf types
   Int_t           event_nRecoVertex4;
   Float_t         event_rho4;
   Float_t         GenEnergy4;
   Float_t         GenEta4;
   Float_t         GenPhi4;
   Int_t           pho_isInPhiCrack4;
   Int_t           pho_isInEtaCrack4;
   Int_t           pho_isInEBEEGap4;
   Float_t         phoSC_RawEtCetaCorr4;
   Float_t         phoSC_RawEnergyCetaCorr4;
   Float_t         phoSC_GeomEta4;
   Float_t         phoSC_GeomPhi4;
   Float_t         pho_r94;
   Float_t         pho_Brem4;
   Float_t         pho_SCarea4;

   outtree->Branch("event_nRecoVertex_0",&event_nRecoVertex3,"event_nRecoVertex_0/I");
   outtree->Branch("event_rho_0",&event_rho3,"event_rho_0/F");
   outtree->Branch("GenEnergy_0",&GenEnergy3,"GenEnergy_0/F");
   outtree->Branch("GenEta_0",&GenEta3,"GenEta_0/F");
   outtree->Branch("GenPhi_0",&GenPhi3,"GenPhi_0/F");
   outtree->Branch("pho_isInPhiCrack_0",&pho_isInPhiCrack3,"pho_isInPhiCrack_0/I");
   outtree->Branch("pho_isInEtaCrack_0",&pho_isInEtaCrack3,"pho_isInEtaCrack_0/I");
   outtree->Branch("pho_isInEBEEGap_0",&pho_isInEBEEGap3,"pho_isInEBEEGap_0/I");
   outtree->Branch("phoSC_RawEtCetaCorr_0",&phoSC_RawEtCetaCorr3,"phoSC_RawEtCetaCorr_0/F");
   outtree->Branch("phoSC_RawEnergyCetaCorr_0",&phoSC_RawEnergyCetaCorr3,"phoSC_RawEnergyCetaCorr_0/F");
   outtree->Branch("phoSC_GeomEta_0",&phoSC_GeomEta3,"phoSC_GeomEta_0/F");
   outtree->Branch("phoSC_GeomPhi_0",&phoSC_GeomPhi3,"phoSC_GeomPhi_0/F");
   outtree->Branch("pho_r9_0",&pho_r93,"pho_r9_0/F");
   outtree->Branch("pho_Brem_0",&pho_Brem3,"pho_Brem_0/F");
   outtree->Branch("pho_SCarea_0",&pho_SCarea3,"pho_SCarea_0/F");

   outtree->Branch("event_nRecoVertex_40",&event_nRecoVertex4,"event_nRecoVertex_40/I");
   outtree->Branch("event_rho_40",&event_rho4,"event_rho_40/F");
   outtree->Branch("GenEnergy_40",&GenEnergy4,"GenEnergy_40/F");
   outtree->Branch("GenEta_40",&GenEta4,"GenEta_40/F");
   outtree->Branch("GenPhi_40",&GenPhi4,"GenPhi_40/F");
   outtree->Branch("pho_isInPhiCrack_40",&pho_isInPhiCrack4,"pho_isInPhiCrack_40/I");
   outtree->Branch("pho_isInEtaCrack_40",&pho_isInEtaCrack4,"pho_isInEtaCrack_40/I");
   outtree->Branch("pho_isInEBEEGap_40",&pho_isInEBEEGap4,"pho_isInEBEEGap_40/I");
   outtree->Branch("phoSC_RawEtCetaCorr_40",&phoSC_RawEtCetaCorr4,"phoSC_RawEtCetaCorr_40/F");
   outtree->Branch("phoSC_RawEnergyCetaCorr_40",&phoSC_RawEnergyCetaCorr4,"phoSC_RawEnergyCetaCorr_40/F");
   outtree->Branch("phoSC_GeomEta_40",&phoSC_GeomEta4,"phoSC_GeomEta_40/F");
   outtree->Branch("phoSC_GeomPhi_40",&phoSC_GeomPhi4,"phoSC_GeomPhi_40/F");
   outtree->Branch("pho_r9_40",&pho_r94,"pho_r9_40/F");
   outtree->Branch("pho_Brem_40",&pho_Brem4,"pho_Brem_40/F");
   outtree->Branch("pho_SCarea_40",&pho_SCarea4,"pho_SCarea_40/F");


   Long64_t nbytes = 0, nb = 0;
   for (Long64_t jentry=0; jentry<nentries;jentry++) {
      Long64_t ientry = LoadTree(jentry);
      if (ientry < 0) break;
      nb = fChain->GetEntry(jentry);   nbytes += nb;
      // if (Cut(ientry) < 0) continue;



      //      cout << "+++ev" << endl;

      bool retry=false;

      if (nb<0) retry=true;
      if (DeltaR(phoSC_GeomPhi,phoSC_GeomPhi2,phoSC_GeomEta,phoSC_GeomEta2)>0.2) retry=true;
      if (retry) nb = DoRetry();

      bool problem=false;
      if (nb<0) problem=true;
      if (DeltaR(phoSC_GeomPhi,phoSC_GeomPhi2,phoSC_GeomEta,phoSC_GeomEta2)>0.2) problem=true;


      if (problem) {
	//	cout << "---" << endl;
	//	cout << DoRetry(1) << endl;
	//	Printer();
	//	cout << DoRetry(1) << endl;
	//	Printer();
	//	cout << "---" << endl;
	continue;
      }

      if (pho_isInPhiCrack || pho_isInEtaCrack || pho_isInEBEEGap) continue;
      if (pho_isInPhiCrack2 || pho_isInEtaCrack2 || pho_isInEBEEGap2) continue;

      event_nRecoVertex3=event_nRecoVertex;
      event_rho3=event_rho;
      GenEnergy3=GenEnergy;
      GenEta3=GenEta;
      GenPhi3=GenPhi;
      pho_isInPhiCrack3=pho_isInPhiCrack;
      pho_isInEtaCrack3=pho_isInEtaCrack;
      pho_isInEBEEGap3=pho_isInEBEEGap;
      phoSC_RawEtCetaCorr3=phoSC_RawEtCetaCorr;
      phoSC_RawEnergyCetaCorr3=phoSC_RawEnergyCetaCorr;
      phoSC_GeomEta3=phoSC_GeomEta;
      phoSC_GeomPhi3=phoSC_GeomPhi;
      pho_r93=pho_r9;
      pho_Brem3=pho_Brem;
      pho_SCarea3=pho_SCarea;

      event_nRecoVertex4=event_nRecoVertex2;
      event_rho4=event_rho2;
      GenEnergy4=GenEnergy2;
      GenEta4=GenEta2;
      GenPhi4=GenPhi2;
      pho_isInPhiCrack4=pho_isInPhiCrack2;
      pho_isInEtaCrack4=pho_isInEtaCrack2;
      pho_isInEBEEGap4=pho_isInEBEEGap2;
      phoSC_RawEtCetaCorr4=phoSC_RawEtCetaCorr2;
      phoSC_RawEnergyCetaCorr4=phoSC_RawEnergyCetaCorr2;
      phoSC_GeomEta4=phoSC_GeomEta2;
      phoSC_GeomPhi4=phoSC_GeomPhi2;
      pho_r94=pho_r92;
      pho_Brem4=pho_Brem2;
      pho_SCarea4=pho_SCarea2;

      outtree->Fill();


   } // end event loop

   outfile->Write();
   outfile->Close();


};
Example #4
0
int main(int argc, char** argv) {

    PVHists atLeastOnGPV("DefW_PV", true);
    JetHists Jets("DefW_Jet", 2, true);
    JetHists BJets("DefW_BJet", 2, true);
    JetHists nonBJets("DefW_nonBJet", 2, true);
    JetHists FwDJet("DefW_FwD", 2, true);
    MuonHists GoldenFinalPUMuons("DefW_Muon", true);
    MetHists MetHist("DefW_Met", true);

    PVHists atLeastOnGPV_PuW("PuW_PV", true);
    JetHists Jets_PuW("PuW_Jet", 2, true);
    JetHists BJets_PuW("PuW_BJet", 2, true);
    JetHists nonBJets_PuW("PuW_nonBJet", 2, true);
    JetHists FwDJet_PuW("PuW_FwD", 2);
    MuonHists GoldenFinalPUMuons_PuW("PuW_Muon", true);
    MetHists MetHist_PuW("PuW_Met", true);

    PVHists atLeastOnGPV_BtagPuW("BtagPuW_PV", true);
    JetHists Jets_BtagPuW("BtagPuW_Jet", 2, true);
    JetHists BJets_BtagPuW("BtagPuW_BJet", 2, true);
    JetHists nonBJets_BtagPuW("BtagPuW_nonBJet", 2, true);
    JetHists FwDJet_BtagPuW("BtagPuW_FwD", 2, true);
    MuonHists GoldenFinalPUMuons_BtagPuW("BtagPuW_Muon", true);
    MetHists MetHist_BtagPuW("BtagPuW_Met", true);

    PVHists atLeastOnGPV_allW("allW_PV", true);
    JetHists Jets_allW("allW_Jet", 2);
    JetHists BJets_allW("allW_BJet", 2);
    JetHists nonBJets_allW("allW_nonBJet", 2, true);
    JetHists FwDJet_allW("allW_FwD", 2, true);
    MuonHists GoldenFinalPUMuons_allW("allW_Muon", true);
    MetHists MetHist_allW("allW_Met", true);

    SingleTopHistograms Default_Def("Default_Def", true);
    SingleTopHistograms EtaCut_Def("EtaFwD_Def", true);
    SingleTopHistograms HtCut_Def("HtCut_Def", true);
    SingleTopHistograms AntiEtaCut_allW("antiEtaFwD_allW", true);
    SingleTopHistograms AntiHtCut_Def("antiHtCut_Def", true);

    SingleTopHistograms DefaultTrue_Def("DefaultTrue_Def", true);
    SingleTopHistograms EtaCutTrue_Def("EtaFwDTrue_Def", true);
    SingleTopHistograms HtCutTrue_Def("HtCutTrue_Def", true);
    SingleTopHistograms AntiEtaCutTrue_Def("antiEtaFwDTrue_Def", true);
    SingleTopHistograms AntiHtCutTrue_Def("antiHtCutTrue_Def", true);

    SingleTopHistograms Default_PuW("Default_PuW", true);
    SingleTopHistograms Default_BtagPuW("Default_BtagPuW", true);
    SingleTopHistograms Default_allW("Default_allW", true);

    SingleTopHistograms EtaCut_PuW("EtaFwD_PuW", true);
    SingleTopHistograms EtaCut_BtagPuW("EtaFwD_BtagPuW", true);
    SingleTopHistograms EtaCut_allW("EtaFwD_allW", true);

    SingleTopHistograms DefaultTrue_PuW("DefaultTrue_PuW", true);
    SingleTopHistograms DefaultTrue_BtagPuW("DefaultTrue_BtagPuW", true);
    SingleTopHistograms DefaultTrue_allW("DefaultTrue_allW", true);

    SingleTopHistograms EtaCutTrue_PuW("EtaFwDTrue_PuW", true);
    SingleTopHistograms EtaCutTrue_BtagPuW("EtaFwDTrue_BtagPuW", true);
    SingleTopHistograms EtaCutTrue_allW("EtaFwDTrue_allW", true);

    DiLeptonHistograms DiLep_Default_Def("Default_Def", true);
    DiLeptonHistograms DiLep_EtaCut_Def("EtaFwD_Def", true);
    DiLeptonHistograms DiLep_HtCut_Def("HtCut_Def", true);
    DiLeptonHistograms DiLep_AntiEtaCut_allW("antiEtaFwD_allW", true);
    DiLeptonHistograms DiLep_AntiHtCut_Def("antiHtCut_Def", true);

    DiLeptonHistograms DiLep_DefaultTrue_Def("DefaultTrue_Def", true);
    DiLeptonHistograms DiLep_EtaCutTrue_Def("EtaFwDTrue_Def", true);
    DiLeptonHistograms DiLep_HtCutTrue_Def("HtCutTrue_Def", true);
    DiLeptonHistograms DiLep_AntiEtaCutTrue_Def("antiEtaFwDTrue_Def", true);
    DiLeptonHistograms DiLep_AntiHtCutTrue_Def("antiHtCutTrue_Def", true);

    DiLeptonHistograms DiLep_Default_PuW("Default_PuW", true);
    DiLeptonHistograms DiLep_Default_BtagPuW("Default_BtagPuW", true);
    DiLeptonHistograms DiLep_Default_allW("Default_allW", true);

    DiLeptonHistograms DiLep_EtaCut_PuW("EtaFwD_PuW", true);
    DiLeptonHistograms DiLep_EtaCut_BtagPuW("EtaFwD_BtagPuW", true);
    DiLeptonHistograms DiLep_EtaCut_allW("EtaFwD_allW", true);

    DiLeptonHistograms DiLep_DefaultTrue_PuW("DefaultTrue_PuW", true);
    DiLeptonHistograms DiLep_DefaultTrue_BtagPuW("DefaultTrue_BtagPuW", true);
    DiLeptonHistograms DiLep_DefaultTrue_allW("DefaultTrue_allW", true);

    DiLeptonHistograms DiLep_EtaCutTrue_PuW("EtaFwDTrue_PuW", true);
    DiLeptonHistograms DiLep_EtaCutTrue_BtagPuW("EtaFwDTrue_BtagPuW", true);
    DiLeptonHistograms DiLep_EtaCutTrue_allW("EtaFwDTrue_allW", true);


    TH1D * HT = new TH1D("HT", "H_{T};H_{T}(GeV)", 500, 0., 500.);
    TH1D * def_finalMT = new TH1D("def_finalMT", "final-W-neutrino transverse mass", 100, 0., 200.);
    def_finalMT->GetXaxis()->SetTitle("M_{T}(W,#nu)");
    TH1D * PuW_finalMT = new TH1D("PuW_finalMT", "final-W-neutrino transverse mass", 100, 0., 200.);
    PuW_finalMT->GetXaxis()->SetTitle("M_{T}(W,#nu)");
    TH1D * BtagPuW_finalMT = new TH1D("BtagPuW_finalMT", "final-W-neutrino transverse mass", 100, 0., 200.);
    BtagPuW_finalMT->GetXaxis()->SetTitle("M_{T}(W,#nu)");
    TH1D * allW_finalMT = new TH1D("allW_finalMT", "final-W-neutrino transverse mass", 100, 0., 200.);
    allW_finalMT->GetXaxis()->SetTitle("M_{T}(W,#nu)");
    TH1D * delNu = new TH1D("delNu", "delNu", 100, 0., 10.);
    delNu->GetXaxis()->SetTitle("#Delta#nu");
    TH1D * delNuII = new TH1D("delNuMET", "delNuMET", 100, 0., 100.);
    TH2D * MT_cosTheta = new TH2D("MTcosTheta", "MTcosTheta", 200, 0, 200, 100, -1., 1.);
    TH2D * MT_cosTheta_true = new TH2D("MTcosTheta_true", "MTcosTheta_true", 200, 0, 200, 100, -1., 1.);
    delNuII->GetXaxis()->SetTitle("#Delta#nu");
    std::vector<std::string> inputFileNames;
    std::string plotFileName;
    int verbosity = 0;
    TH1D * METResolutions = 0;
    std::string HLTname = "HLT_IsoMu17_v*";
    bool pu3D = true;
    string PUWeightFileName = "";
    double XSec = 1;
    double Luminosity = 1;
    double PreSelEff = 1;
    double doJES = 0;
    double doUnclMET = 0;
    string ttDecayMode = "";
    int btagSyst = 0;
    int ctagSyst = 0;
    int lighttagSyst = 0;
    bool isData = false;
    int smearingSkim = 1;
    string puAddress = "~/work/TopBrussels/TopTreeAnalysis/macros/PileUpReweighting/";
    string MCpuFile = "";
    string DataPuFile = "Central-unps_paper_finebin_Pileup.root";
    for (int f = 1; f < argc; f++) {
        std::string arg_fth(*(argv + f));

        if (arg_fth == "out") {
            f++;
            std::string out(*(argv + f));
            plotFileName = out;
        } else if (arg_fth == "input") {
            f++;
            std::string in(*(argv + f));
            inputFileNames.push_back(string("~/work/samples/" + in));
        } else if (arg_fth == "XSec") {
            f++;
            std::string Xsec(*(argv + f));
            XSec = atof(Xsec.c_str());
        } else if (arg_fth == "Lumi") {
            f++;
            std::string Lumi(*(argv + f));
            Luminosity = atof(Lumi.c_str());
        } else if (arg_fth == "preSelEff") {
            f++;
            std::string preSelEff(*(argv + f));
            PreSelEff = atof(preSelEff.c_str());
        } else if (arg_fth == "JES") {
            f++;
            std::string in(*(argv + f));
            doJES = atof(in.c_str());
        } else if (arg_fth == "isData") {
            f++;
            std::string in(*(argv + f));
            if (in == "yes" || in == "YES" || in == "Yes" || in == "y" || in == "Y")
                isData = true;
            else
                isData = false;
        } else if (arg_fth == "METResolFileName") {
            f++;
            std::string in(*(argv + f));
            TFile * METResolFileName = TFile::Open(in.c_str());
            METResolutions = (TH1D*) METResolFileName->Get("METresolutions");
        } else if (arg_fth == "HLTname") {
            f++;
            std::string in(*(argv + f));
            HLTname = in;
            std::cout << HLTname << endl;
        } else if (arg_fth == "PUWeightFileName") {
            f++;
            std::string in(*(argv + f));
            PUWeightFileName = in;
            std::cout << HLTname << endl;
        } else if (arg_fth == "dataPUoption") {
            f++;
            std::string in(*(argv + f));
            DataPuFile = in;
        } else if (arg_fth == "puOption") {
            f++;
            std::string in(*(argv + f));
            MCpuFile = in;
        } else if (arg_fth == "smearingSkim") {
            f++;
            std::string in(*(argv + f));
            smearingSkim = atof(in.c_str());
        } else if (arg_fth == "unclMET") {
            f++;
            std::string in(*(argv + f));
            doUnclMET = atof(in.c_str());
        } else if (arg_fth == "ttDecayMode") {
            f++;
            std::string in(*(argv + f));
            ttDecayMode = in;
        } else if (arg_fth == "bTag") {
            f++;
            std::string in(*(argv + f));
            btagSyst = atof(in.c_str());
        } else if (arg_fth == "cTag") {
            f++;
            std::string in(*(argv + f));
            ctagSyst = atof(in.c_str());
        } else if (arg_fth == "lTag") {
            f++;
            std::string in(*(argv + f));
            lighttagSyst = atof(in.c_str());
        }
    }
    MCpuFile = puAddress + MCpuFile;
    DataPuFile = puAddress + DataPuFile;
    TFile* f = 0;
    TApplication theApp("App", &argc, argv);
    double nInit = 0;
    double nFinalPU = 0;
    double nFinalHLT = 0;
    double nFinalbTag = 0;
    double nFinal = 0;
    double nHLTrunB = 0;
    double nMt = 0;
    double nGoodSolution = 0;
    Lumi3DReWeighting Lumi3DWeights;
    cout << "=====================================================================" << endl;
    cout << "Parameters:\n\tInput: " << inputFileNames.at(0);
    if (isData)
        cout << "\tis data" << endl;
    else
        cout << "\tis MC" << endl;
    cout << "\tOutput: " << plotFileName << endl;
    cout << "\tTop decay mode: " << ttDecayMode << endl;
    cout << "\tJES: " << doJES << "\t\t";
    if (doJES == 0)
        cout << "No JES systematics" << endl;
    else if (doJES > 0)
        cout << "UP JES systematics" << endl;
    else
        cout << "DOWN JES systematics" << endl;
    cout << "\tData pile-up: " << DataPuFile << "\n\t\t";
    if (DataPuFile.find("Low") > 0 && DataPuFile.find("Low") < DataPuFile.size())
        cout << "DOWN pile-up systematics" << endl;
    else if (DataPuFile.find("High") > 0 && DataPuFile.find("High") < DataPuFile.size())
        cout << "UP pile-up systematics" << endl;
    else
        cout << "No pile-up systematics" << endl;
    cout << "\tMC pile-up: " << MCpuFile;
    if (MCpuFile.find("Fall") > 0 && MCpuFile.find("Fall") < MCpuFile.size())
        cout << "\n\t\tFall11 pile-up" << endl;
    else
        cout << "\n\t\tSummer11 pile-up" << endl;
    cout << "\tunclMET: " << doUnclMET << "\n\t\t";
    if (doUnclMET == 0)
        cout << "No unclMET systematics" << endl;
    else if (doUnclMET > 0)
        cout << "UP unclMET systematics" << endl;
    else
        cout << "DOWN unclMET systematics" << endl;
    cout << "\tbTag: " << btagSyst << "\n\t\t";
    if (btagSyst == 0)
        cout << "No bTag systematics" << endl;
    else if (btagSyst > 0)
        cout << "UP bTag systematics" << endl;
    else
        cout << "DOWN bTag systematics" << endl;
    if (ctagSyst == 0)
        cout << "No cTag systematics" << endl;
    else if (ctagSyst > 0)
        cout << "UP cTag systematics" << endl;
    else
        cout << "DOWN cTag systematics" << endl;
    if (lighttagSyst == 0)
        cout << "No lightTag systematics" << endl;
    else if (lighttagSyst > 0)
        cout << "UP lightTag systematics" << endl;
    else
        cout << "DOWN lightTag systematics" << endl;
    cout << "=====================================================================" << endl;

    if (pu3D && !isData) {
        //        Lumi3DWeights.weight3D_set("../../../../TopBrussels/TopTreeAnalysis/macros/PileUpReweighting//MC_Fall11.root",
        //    "../../../../TopBrussels/TopTreeAnalysis/macros/PileUpReweighting/RunAB.root", "pileup", "pileup");
        Lumi3DWeights.weight3D_set(MCpuFile, DataPuFile, "pileup", "pileup");
        Lumi3DWeights.setWFileName(PUWeightFileName);
        Lumi3DWeights.weight3D_init(1.0);
        //    Lumi3DWeights.weight3D_init(PUWeightFileName);
    }
    TFile * HLTweights = TFile::Open("~/work/AnalysisClasses/EventSelection/macro/HLT_IsoMu17_W.root");
    TH1D * HLTWeights = (TH1D*) HLTweights->Get("weight");
    GenSingleTopMaker* genSingleTop = 0;
    UnclusteredEnergyUnc* myUnclMET = 0;
    for (unsigned int fNumber = 0; fNumber < inputFileNames.size(); fNumber++) {
        cout << "file number " << fNumber + 1 << ": " << inputFileNames.at(fNumber) << endl;
        f = TFile::Open(inputFileNames.at(fNumber).c_str());

        TTree* runTree = (TTree*) f->Get("runTree");
        TTree* eventTree = (TTree*) f->Get("eventTree");



        PracticalEvent * pracEvt = new PracticalEvent(eventTree, runTree);
        pracEvt->eventTree->SetBranchStatus("*", 1);

        std::cout << "beforeLoop" << std::endl;

        int ievt = 0;

        while (pracEvt->Next()) {

            ievt++;

            /* for single top genAnalysis
             * not to be used for real one
             */
            if (!isData && pracEvt->NPGenEvtCollection() != 0) {
                //                cout<<"I am here"<<endl;
                genSingleTop = new GenSingleTopMaker((TRootNPGenEvent*) pracEvt->NPGenEvtCollection()->At(0), verbosity);
            }
            double puOnlyW = 1;
            double btagpuW = 1;
            double lumiWeight3D = 1;
            if (pu3D) {
                if (!isData) {
                    //            cout<<"here I am ... "<<pracEvt->Event()<<endl;
                    lumiWeight3D = Lumi3DWeights.weight3D(pracEvt->Event());
                } else lumiWeight3D = 1;
            }
            puOnlyW = lumiWeight3D;
            //            cout<<lumiWeight3D<<endl;
            nInit += lumiWeight3D;
            //            nInit++;
            if (verbosity > 0)
                cout << ievt << "*******************************************************************" << endl;

            if (doUnclMET != 0) {
                myUnclMET = new UnclusteredEnergyUnc(pracEvt, 0.1);
                pracEvt->setDefaultMET(myUnclMET->getChangedUncEnergyMET(doUnclMET));
                delete myUnclMET;
            } else {
                pracEvt->setDefaultMET(*(TRootPFMET*) pracEvt->METCollection()->At(0));
            }
            std::vector<TRootPFJet> myJets_;
            myJets_.clear();
            //            cout<<"I am going to Jet Correction "<<isData<<endl;
            myJets_ = pracEvt->ScaledPFJetCollection(1, isData, doJES);

            Event myEvent_tmp(myJets_, *pracEvt->ElectronCollection()
                    , pracEvt->TypeICorrMET(), *pracEvt->MuonCollection(), *pracEvt->VertexCollection());
            //            Event myEvent_tmp(myJets_, *pracEvt->ElectronCollection()
            //                    , *pracEvt->METCollection(), *pracEvt->MuonCollection(), *pracEvt->VertexCollection());


            if (verbosity > 0)
                cout << "PV size: " << myEvent_tmp.pvs.size() << "\n"
                << "Muon size: " << myEvent_tmp.muons.size() << "\n"
                << "Electron size: " << myEvent_tmp.electrons.size() << "\n"
                << "Jet size: " << myEvent_tmp.PFJets.size() << "\n" << endl;
            myEvent_tmp.verbose(verbosity);
            if (verbosity > 0)
                cout << "ScrapFilterMaker-------------------------------------------------------------------" << endl;
            double scrapFilterer = (double) (pracEvt->Event()->nHighPurityTracks()) / (double) (pracEvt->Event()->nTracks());
            if (verbosity > 0)
                cout << "HBHEnoiseFilterMaker-------------------------------------------------------------------" << endl; //?????
            if (verbosity > 0)
                cout << "Vertex Makers ---------------------------------------------------------------------" << endl;
            myEvent_tmp.VertexMaker();
            if (verbosity > 0)
                cout << "Electron Maker ---------------------------------------------------------------------" << endl;
            myEvent_tmp.ElectronMaker();
            /*pt = 30., eta = 2.5,  Exc_Low = 1.4442 , Exc_High = 1.5660, Id = "VBTF70", IdSecond = "VBTF95" (not applied),
             * D0 = 0.02, IsoCut = 0.125, drToPV = 10000.,  secondEIso = 0.2, secPt=15 GeV 
             */


            if (verbosity > 0)
                cout << "Jet Makers ---------------------------------------------------------------------" << endl;
            myEvent_tmp.PFJetMaker(/*bTagAlgo*/"TCHP", /*pt*/30., /*eta*/4.5);
            if (verbosity > 0)
                cout << "Muon Maker ---------------------------------------------------------------------" << endl;
            //            myEvent_tmp.MuonMaker(20, 2.1, 10, 1000, 10, 0.5);
            myEvent_tmp.MuonMaker();
            /*
             * pt = 20.,  eta = 2.1, chi2 = 10,  D0 = 0.02,  nvh = 10, isoCut_ = 0.15,  doGL = false,  
             * nPixWithMeasuredHits = 1,  nSegM = 1
             */
            if (verbosity > 0)
                cout << "START TO SELECT : " << endl;
            if (scrapFilterer > 0.2) {
                if (verbosity > 0)
                    cout << "\tPassed!! scrapFilterer is " << scrapFilterer << endl;
            } else {
                cout << "Event number " << ievt << " has failed scrapping filter" << endl;
                continue;
            }

            if (myEvent_tmp.passPVsel) {
                if (verbosity > 0)
                    cout << "\tPVCut Passed" << endl;
            } else {
                if (verbosity > 0)
                    cout << "Event number " << ievt << " has failed primary vertex" << endl;
                continue;
            }

            if (myEvent_tmp.Dmuons.size() == 1) {
                if (verbosity > 0)
                    cout << "\tMu selection Passed" << endl;
            } else {
                if (verbosity > 0)
                    cout << "Event number " << ievt << " has failed muon" << endl;
                continue;
            }
//            if(!(myEvent_tmp.Dmuons[0].Pt() > 26))
//                continue;
            if (myEvent_tmp.looseMuons.size() == 0) {
                if (verbosity > 0)
                    cout << "\tlooseMuVeto is passed" << endl;
            } else {
                if (verbosity > 0)
                    cout << "Event number " << ievt << " has failed looseMuVeto" << endl;
                continue;
            }

            if (myEvent_tmp.Gelectrons.size() == 0 && myEvent_tmp.Secondelectrons.size() == 0) {
                if (verbosity > 0)
                    cout << "\tlooseEVeto is passed" << endl;
            } else {
                if (verbosity > 0)
                    cout << "Event number " << ievt << " has failed looseEVeto" << endl;
                continue;
            }

            if (myEvent_tmp.GPFJets.size() == 2) {
                if (verbosity > 0) {
                    cout << "\t==2 Jet Passed" << endl;
                }
            } else {
                if (verbosity > 0)
                    cout << "Event number " << ievt << " has failed jet" << endl;
                continue;
            }
//            if(!(myEvent_tmp.GPFJets[0].Pt() > 40 && myEvent_tmp.GPFJets[1].Pt() > 40))
//                continue;
            double mt = 0;
            double metT = sqrt((myEvent_tmp.mets.at(0).Px() * myEvent_tmp.mets.at(0).Px())+
                    (myEvent_tmp.mets.at(0).Py() * myEvent_tmp.mets.at(0).Py()));

            double muT = sqrt((myEvent_tmp.Dmuons.at(0).Px() * myEvent_tmp.Dmuons.at(0).Px())+
                    (myEvent_tmp.Dmuons.at(0).Py() * myEvent_tmp.Dmuons.at(0).Py()));
            mt = sqrt(pow(muT + metT, 2) - pow(myEvent_tmp.mets.at(0).Px() + myEvent_tmp.Dmuons.at(0).Px(), 2)
                    - pow(myEvent_tmp.mets.at(0).Py() + myEvent_tmp.Dmuons.at(0).Py(), 2));
            if (mt > 40) {
//            if (mt > 50) {
                //                nMt++;
                nMt += lumiWeight3D;
                if (verbosity > 0)
                    cout << "\tM_T cut is passed" << endl;
            } else {
                if (verbosity > 0)
                    cout << "Event number " << ievt << " has failed mt" << endl;
                continue;
            }

            if (myEvent_tmp.BPFJets.size() == 1) {
                if (verbosity > 0)
                    cout << "\t== 1bTag Passed" << endl;
            } else {
                if (verbosity > 0)
                    cout << "Event number " << ievt << " has failed btag" << endl;
                continue;
            }
            /*btag sf*/
            nFinalPU += lumiWeight3D;
            //            cout<<"pu: "<<lumiWeight3D<<"\t";
            double bw = 1;
            if (!isData) {
                double sf, eff;
                BTagWeight myBtagWeight;
                vector< vector<BTagWeight::JetInfo> > jInfosToReWeight(myEvent_tmp.GPFJets.size());
                for (int iJet = 0; iJet < myEvent_tmp.GPFJets.size(); iJet++) {
                    BTagWeight::GetEffSF_TCHPT(myEvent_tmp.GPFJets[iJet].Pt(),
                            myEvent_tmp.GPFJets[iJet].Eta(),
                            myEvent_tmp.GPFJets[iJet].btag_trackCountingHighPurBJetTags(),
                            myEvent_tmp.GPFJets[iJet].partonFlavour(),
                            //                            eff, sf, btagSyst, ctagSyst);
                            eff, sf, btagSyst);
                    BTagWeight::JetInfo jinfo(eff, sf);
                    jInfosToReWeight[iJet].push_back(jinfo);
                }
                bw *= myBtagWeight.weight(jInfosToReWeight);
            }
            //            cout<<"bw: "<<bw<<"\t";
            btagpuW = puOnlyW*bw;
            lumiWeight3D *= bw;

            nFinalbTag += bw;
            /*HLT sf*/
            double hltW = 1;
            if (!isData) {
                int bin = HLTWeights->GetXaxis()->FindBin(myEvent_tmp.Dmuons.at(0).Eta());
                if (bin > 0 && bin < 13)
                    hltW = HLTWeights->GetBinContent(bin);
                else
                    hltW = 1.;
            }
            lumiWeight3D *= hltW;
            //            cout<<"hlt: "<<hltW<<endl;
            nFinalHLT += hltW;

            nFinal += lumiWeight3D;

            int mySecondJetIndex = 0;
            if (mySecondJetIndex == myEvent_tmp.firstBtagIndex)
                mySecondJetIndex = 1;
            std::vector<TRootPFJet> nonBs;
            nonBs.push_back(myEvent_tmp.GPFJets.at(mySecondJetIndex));
            std::vector<TRootPFJet> sortedJetsbyEta;
            sortedJetsbyEta.push_back(myEvent_tmp.SortedJetsByEta().at(0));
            //Reweighting process
            if (myEvent_tmp.BPFJets.size() == 0) {
                myEvent_tmp.BPFJets.clear();
                if (myEvent_tmp.GPFJets.at(0).btag_trackCountingHighPurBJetTags() >
                        myEvent_tmp.GPFJets.at(1).btag_trackCountingHighPurBJetTags())
                    myEvent_tmp.BPFJets.push_back(myEvent_tmp.GPFJets.at(0));
                else
                    myEvent_tmp.BPFJets.push_back(myEvent_tmp.GPFJets.at(1));
                //                if ((ievt % 2) == 0)
                //                    myEvent_tmp.BPFJets.push_back(myEvent_tmp.GPFJets.at(0));
                //                else
                //                    myEvent_tmp.BPFJets.push_back(myEvent_tmp.GPFJets.at(1));
            }
            SemiLepTopQuark myLeptonicTop(myEvent_tmp.BPFJets.at(0), myEvent_tmp.mets.at(0), myEvent_tmp.Dmuons.at(0),
                    myEvent_tmp.GPFJets.at(mySecondJetIndex), sortedJetsbyEta.at(0), METResolutions);
            myLeptonicTop.setMuCharge((int) myEvent_tmp.Dmuons.at(0).charge());
            double eta = fabs(sortedJetsbyEta.at(0).Eta());
            double ht = myEvent_tmp.GPFJets.at(0).Pt() + myEvent_tmp.GPFJets.at(1).Pt();


            ht += myEvent_tmp.Dmuons.at(0).Pt();
            ht += myEvent_tmp.mets.at(0).Pt();
            HT->Fill(ht, lumiWeight3D);
            if (ttDecayMode == "") {
                if (myLeptonicTop.hasNeutrinoSolution()) {
                    MT_cosTheta_true->Fill(mt, myLeptonicTop.cosThetaStar(), 1);
                    nGoodSolution++;
                    DefaultTrue_Def.Fill(myLeptonicTop, 1, genSingleTop);

                    DefaultTrue_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop);
                    DefaultTrue_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop);
                    DefaultTrue_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop);

                    if (ht >= 180)
                        HtCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop);
                    else
                        AntiHtCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop);
                    if (eta > 1.5) {
                        EtaCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop);

                        EtaCutTrue_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop);
                        EtaCutTrue_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop);
                        EtaCutTrue_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop);
                    } else
                        AntiEtaCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop);
                }
                Default_Def.Fill(myLeptonicTop, 1, genSingleTop);
                MT_cosTheta->Fill(mt, myLeptonicTop.cosThetaStar(), 1);

                Default_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop);
                Default_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop);
                Default_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop);

                if (ht >= 180)
                    HtCut_Def.Fill(myLeptonicTop, 1, genSingleTop);
                else
                    AntiHtCut_Def.Fill(myLeptonicTop, 1, genSingleTop);
                if (eta > 1.5) {
                    EtaCut_Def.Fill(myLeptonicTop, 1, genSingleTop);

                    EtaCut_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop);
                    EtaCut_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop);
                    EtaCut_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop);
                } else
                    AntiEtaCut_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop);
            } else {//Dimuon, muTau, muE TtBar
                if (myLeptonicTop.hasNeutrinoSolution()) {
                    nGoodSolution++;
                    DiLep_DefaultTrue_Def.Fill(myLeptonicTop, 1, genSingleTop);

                    DiLep_DefaultTrue_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop);
                    DiLep_DefaultTrue_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop);
                    DiLep_DefaultTrue_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop);

                    if (ht >= 180)
                        DiLep_HtCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop);
                    else
                        DiLep_AntiHtCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop);
                    if (eta > 1.5) {
                        DiLep_EtaCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop);

                        DiLep_EtaCutTrue_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop);
                        DiLep_EtaCutTrue_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop);
                        DiLep_EtaCutTrue_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop);
                    } else
                        DiLep_AntiEtaCutTrue_Def.Fill(myLeptonicTop, 1, genSingleTop);
                }
                DiLep_Default_Def.Fill(myLeptonicTop, 1, genSingleTop);

                DiLep_Default_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop);
                DiLep_Default_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop);
                DiLep_Default_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop);

                if (ht >= 180)
                    DiLep_HtCut_Def.Fill(myLeptonicTop, 1, genSingleTop);
                else
                    DiLep_AntiHtCut_Def.Fill(myLeptonicTop, 1, genSingleTop);
                if (eta > 1.5) {
                    DiLep_EtaCut_Def.Fill(myLeptonicTop, 1, genSingleTop);

                    DiLep_EtaCut_PuW.Fill(myLeptonicTop, puOnlyW, genSingleTop);
                    DiLep_EtaCut_BtagPuW.Fill(myLeptonicTop, btagpuW, genSingleTop);
                    DiLep_EtaCut_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop);
                } else
                    DiLep_AntiEtaCut_allW.Fill(myLeptonicTop, lumiWeight3D, genSingleTop);
            }

            if (genSingleTop != NULL)
                delete genSingleTop;

            atLeastOnGPV.Fill(myEvent_tmp.Gpvs, myEvent_tmp.Gpvs.size(), 1);
            GoldenFinalPUMuons.Fill(myEvent_tmp.Dmuons, myEvent_tmp.Dmuons.size(), 1);
            Jets.FillPFJets(myEvent_tmp.GPFJets, myEvent_tmp.GPFJets.size(), myEvent_tmp.BPFJets.size(), false, 1);
            BJets.FillPFJets(myEvent_tmp.BPFJets, myEvent_tmp.BPFJets.size(), myEvent_tmp.BPFJets.size(), false, 1);
            nonBJets.FillPFJets(nonBs, nonBs.size(), myEvent_tmp.BPFJets.size(), false, 1);
            FwDJet.FillPFJets(sortedJetsbyEta, sortedJetsbyEta.size(), myEvent_tmp.BPFJets.size(), false, 1);
            MetHist.Fill(&myEvent_tmp.mets.at(0), 1);
            def_finalMT->Fill(mt, 1);

            atLeastOnGPV_PuW.Fill(myEvent_tmp.Gpvs, myEvent_tmp.Gpvs.size(), puOnlyW);
            GoldenFinalPUMuons_PuW.Fill(myEvent_tmp.Dmuons, myEvent_tmp.Dmuons.size(), puOnlyW);
            Jets_PuW.FillPFJets(myEvent_tmp.GPFJets, myEvent_tmp.GPFJets.size(), myEvent_tmp.BPFJets.size(), false, puOnlyW);
            BJets_PuW.FillPFJets(myEvent_tmp.BPFJets, myEvent_tmp.BPFJets.size(), myEvent_tmp.BPFJets.size(), false, puOnlyW);
            nonBJets_PuW.FillPFJets(nonBs, nonBs.size(), myEvent_tmp.BPFJets.size(), false, puOnlyW);
            FwDJet_PuW.FillPFJets(sortedJetsbyEta, sortedJetsbyEta.size(), myEvent_tmp.BPFJets.size(), false, puOnlyW);
            MetHist_PuW.Fill(&myEvent_tmp.mets.at(0), puOnlyW);
            PuW_finalMT->Fill(mt, puOnlyW);

            atLeastOnGPV_BtagPuW.Fill(myEvent_tmp.Gpvs, myEvent_tmp.Gpvs.size(), btagpuW);
            GoldenFinalPUMuons_BtagPuW.Fill(myEvent_tmp.Dmuons, myEvent_tmp.Dmuons.size(), btagpuW);
            Jets_BtagPuW.FillPFJets(myEvent_tmp.GPFJets, myEvent_tmp.GPFJets.size(), myEvent_tmp.BPFJets.size(), false, btagpuW);
            BJets_BtagPuW.FillPFJets(myEvent_tmp.BPFJets, myEvent_tmp.BPFJets.size(), myEvent_tmp.BPFJets.size(), false, btagpuW);
            nonBJets_BtagPuW.FillPFJets(nonBs, nonBs.size(), myEvent_tmp.BPFJets.size(), false, btagpuW);
            FwDJet_BtagPuW.FillPFJets(sortedJetsbyEta, sortedJetsbyEta.size(), myEvent_tmp.BPFJets.size(), false, btagpuW);
            MetHist_BtagPuW.Fill(&myEvent_tmp.mets.at(0), btagpuW);
            BtagPuW_finalMT->Fill(mt, btagpuW);

            atLeastOnGPV_allW.Fill(myEvent_tmp.Gpvs, myEvent_tmp.Gpvs.size(), lumiWeight3D);
            GoldenFinalPUMuons_allW.Fill(myEvent_tmp.Dmuons, myEvent_tmp.Dmuons.size(), lumiWeight3D);
            Jets_allW.FillPFJets(myEvent_tmp.GPFJets, myEvent_tmp.GPFJets.size(), myEvent_tmp.BPFJets.size(), false, lumiWeight3D);
            BJets_allW.FillPFJets(myEvent_tmp.BPFJets, myEvent_tmp.BPFJets.size(), myEvent_tmp.BPFJets.size(), false, lumiWeight3D);
            nonBJets_allW.FillPFJets(nonBs, nonBs.size(), myEvent_tmp.BPFJets.size(), false, lumiWeight3D);
            FwDJet_allW.FillPFJets(sortedJetsbyEta, sortedJetsbyEta.size(), myEvent_tmp.BPFJets.size(), false, lumiWeight3D);
            MetHist_allW.Fill(&myEvent_tmp.mets.at(0), lumiWeight3D);
            allW_finalMT->Fill(mt, lumiWeight3D);
            double genMet = genSingleTop->genSingleTop.getMET(0).Pt();
            delNu->Fill((fabs(genMet- myEvent_tmp.mets.at(0).Pt())/genMet));
        }

        cout << "before closing file input " << f->GetName() << endl;
        f->Close();
        delete f;

    }
    cout << "before endjob" << endl;
    TFile * fout = new TFile(plotFileName.c_str(), "recreate");
    fout->cd();

    atLeastOnGPV.WriteAll(fout);
    GoldenFinalPUMuons.WriteAll(fout);
    Jets.WriteAll(fout);
    BJets.WriteAll(fout);
    nonBJets.WriteAll(fout);
    FwDJet.WriteAll(fout);
    MetHist.WriteAll(fout);
    def_finalMT->Write();

    atLeastOnGPV_PuW.WriteAll(fout);
    GoldenFinalPUMuons_PuW.WriteAll(fout);
    Jets_PuW.WriteAll(fout);
    BJets_PuW.WriteAll(fout);
    nonBJets_PuW.WriteAll(fout);
    FwDJet_PuW.WriteAll(fout);
    MetHist_PuW.WriteAll(fout);
    PuW_finalMT->Write();

    atLeastOnGPV_BtagPuW.WriteAll(fout);
    GoldenFinalPUMuons_BtagPuW.WriteAll(fout);
    Jets_BtagPuW.WriteAll(fout);
    BJets_BtagPuW.WriteAll(fout);
    nonBJets_BtagPuW.WriteAll(fout);
    FwDJet_BtagPuW.WriteAll(fout);
    MetHist_BtagPuW.WriteAll(fout);
    BtagPuW_finalMT->Write();

    atLeastOnGPV_allW.WriteAll(fout);
    GoldenFinalPUMuons_allW.WriteAll(fout);
    Jets_allW.WriteAll(fout);
    BJets_allW.WriteAll(fout);
    nonBJets_allW.WriteAll(fout);
    FwDJet_allW.WriteAll(fout);
    MetHist_allW.WriteAll(fout);
    allW_finalMT->Write();
    if (ttDecayMode == "") {
        Default_Def.Write(fout);

        Default_PuW.Write(fout);
        Default_BtagPuW.Write(fout);
        Default_allW.Write(fout);

        EtaCut_Def.Write(fout);
        EtaCut_PuW.Write(fout);
        EtaCut_BtagPuW.Write(fout);
        EtaCut_allW.Write(fout);

        AntiEtaCut_allW.Write(fout);
        HtCut_Def.Write(fout);
        AntiHtCut_Def.Write(fout);
        DefaultTrue_Def.Write(fout);
        EtaCutTrue_Def.Write(fout);
        DefaultTrue_allW.Write(fout);
        EtaCutTrue_allW.Write(fout);
        AntiEtaCutTrue_Def.Write(fout);
        HtCutTrue_Def.Write(fout);
        AntiHtCutTrue_Def.Write(fout);
    } else {
        DiLep_Default_Def.Write(fout);

        DiLep_Default_PuW.Write(fout);
        DiLep_Default_BtagPuW.Write(fout);
        DiLep_Default_allW.Write(fout);

        DiLep_EtaCut_Def.Write(fout);
        DiLep_EtaCut_PuW.Write(fout);
        DiLep_EtaCut_BtagPuW.Write(fout);
        DiLep_EtaCut_allW.Write(fout);

        DiLep_AntiEtaCut_allW.Write(fout);
        DiLep_HtCut_Def.Write(fout);
        DiLep_AntiHtCut_Def.Write(fout);
        DiLep_DefaultTrue_Def.Write(fout);
        DiLep_EtaCutTrue_Def.Write(fout);
        DiLep_DefaultTrue_allW.Write(fout);
        DiLep_EtaCutTrue_allW.Write(fout);
        DiLep_AntiEtaCutTrue_Def.Write(fout);
        DiLep_HtCutTrue_Def.Write(fout);
        DiLep_AntiHtCutTrue_Def.Write(fout);
    }
    MT_cosTheta->Write();
    MT_cosTheta_true->Write();
    delNu->Write();
    HT->Write();
    fout->Write();
    fout->Close();

    cout << nInit << "\n" << nHLTrunB << "\n" << nMt << "\n" << nFinal << endl;
    cout << "only pu weight:\t" << nFinalPU << "\n" << "only btag sf:\t" << nFinalbTag << endl;
    cout << "only HLT weight:\t" << nFinalHLT << "\n" << "all sf's:\t" << nFinal << endl;
    return 0;
}
Example #5
0
void drawContour(TString bino="bino", TString jet="nojet", bool print=false) {

  bool useCustomGetContour = false;

  //  TString data_dir = "table_20120131/multiChannel"; // answering preapproval questions
  TString data_dir = "table_20120209/multiChannel"; // last success after answering preapproval questions
  //TString data_dir = ".";

  gStyle->SetOptStat(0);

  TString label = bino + "_mN375_met100_" + jet;
  if(bino.Contains("mNScan")) label = bino + "_met100_" + jet;

  gStyle->SetPalette(1);
  gStyle->SetPadLeftMargin(0.15);

  //  TString option2D = "CONT4 Z";
  TString option2D = "COL Z";

  // for bino & wino
  const int nG = 21;
  const int nS = 21;
  float mGVals[nG+1] = {400, 480, 560, 640, 720, 800, 880, 960, 1040, 1120, 1200, 1280, 1360, 1440, 1520, 1600, 1680, 1760, 1840, 1920, 2000, 2100};
  float mSVals[nS+1] = {400, 480, 560, 640, 720, 800, 880, 960, 1040, 1120, 1200, 1280, 1360, 1440, 1520, 1600, 1680, 1760, 1840, 1920, 2000, 2100};

  // to make valuse on the center of each bin
  float* mGBins = new float[nG+1];
  float* mSBins = new float[nS+1];
  for(int i=0; i<nG+1; i++) mGBins[i] = mGVals[i]-40;
  for(int i=0; i<nS+1; i++) mSBins[i] = mSVals[i]-40;


  // for mNScan
  const int nX = 10;
  const int nY = 23;
  float xVals[nX+1] = {150, 250, 350, 450, 550, 650, 750, 850, 950, 1050, 1150};
  float yVals[nY+1] = {240, 320, 400, 480, 560, 640, 720, 800, 880, 960, 1040, 1120, 1200, 1280, 1360, 1440, 1520, 1600, 1680, 1760, 1840, 1920, 2000, 2100};

  float* xBins = new float[nX+1];
  float* yBins = new float[nY+1];

  for(int i=0; i<nX+1; i++) xBins[i] = xVals[i]-50;
  for(int i=0; i<nY+1; i++) yBins[i] = yVals[i]-40;


  TFile* fout = new TFile("hist_exclusion_"+label+".root","RECREATE");

  const int nxs = 6;
  TString xsname[nxs] = {"xsec","xsec_1L","xsec_1H","xsec_2L","xsec_2H","acc"};
  TH2D* h_xs[nxs];
  for(int i=0; i<nxs; i++) {
    if(bino.Contains("mNScan")) h_xs[i] = new TH2D(xsname[i],xsname[i],nX,xBins,nY,yBins);
    else h_xs[i] = new TH2D(xsname[i],xsname[i],nS,mSBins,nG,mGBins);
  }

  const int nlimit = 6;
  TString limitname[nlimit] = {"limit", "exp", "exp_1L","exp_1H","exp_2L","exp_2H"};
  TH2D* h_limit[nlimit];
  for(int i=0; i<nlimit; i++) {
    if(bino.Contains("mNScan")) h_limit[i] = new TH2D(limitname[i],limitname[i],nX,xBins,nY,yBins);
    else h_limit[i] = new TH2D(limitname[i],limitname[i],nS,mSBins,nG,mGBins);
  }

  TString datafile = data_dir + "/" + bino + "_" + jet + ".table";

  std::ifstream fin;
  fin.open(datafile.Data());
  while(1){
    // #echo "mS mG mN acc xsec xsecPDFError xsecRSErrorNeg xsecRSErrorPos obsLimit expLimit exp_m1s exp_m2s exp_p1s exp_p2s"
    int mS, mG, mN;
    double acc, xsec, xsecPDFError, xsecRSErrorNeg, xsecRSErrorPos, obsLimit, expLimit, exp_m1s, exp_m2s, exp_p1s, exp_p2s;
    fin >> mS >> mG >> mN >> acc >> xsec >> xsecPDFError >> xsecRSErrorNeg >> xsecRSErrorPos >> obsLimit >> expLimit >> exp_m1s >> exp_m2s >> exp_p1s >> exp_p2s;
    if(!fin.good()) break;

//     std::cout << mS << ", " << mG << ", " << mN << ", " << acc << ", " << xsec << ", " << xsecPDFError << ", "
// 	      << xsecRSErrorNeg << ", " << xsecRSErrorPos << ", " << obsLimit << ", " << expLimit << ", "
// 	      << exp_m1s << ", " << exp_m2s << ", " << exp_p1s << ", " << exp_p2s << std::endl;

    double oneSigma_L = std::sqrt(xsecRSErrorNeg * xsecRSErrorNeg + xsecPDFError * xsecPDFError);
    double oneSigma_H = std::sqrt(xsecRSErrorPos * xsecRSErrorPos + xsecPDFError * xsecPDFError);

    if(bino.Contains("mNScan")) {
      if(mS != 2500) continue;
      h_xs[5]->Fill(mN,mG,acc);
      h_xs[0]->Fill(mN,mG,xsec);
      h_xs[1]->Fill(mN,mG,xsec - xsec*oneSigma_L);
      h_xs[2]->Fill(mN,mG,xsec + xsec*oneSigma_H);
      h_xs[3]->Fill(mN,mG,xsec - xsec*2*oneSigma_L);
      h_xs[4]->Fill(mN,mG,xsec + xsec*2*oneSigma_H);

      h_limit[0]->Fill(mN,mG,obsLimit*xsec);
      h_limit[1]->Fill(mN,mG,expLimit*xsec);
      h_limit[2]->Fill(mN,mG,exp_m1s*xsec);
      h_limit[3]->Fill(mN,mG,exp_p1s*xsec);
      h_limit[4]->Fill(mN,mG,exp_m2s*xsec);
      h_limit[5]->Fill(mN,mG,exp_p2s*xsec);
    }
    else {
      if(mN != 375) continue;
      h_xs[5]->Fill(mS,mG,acc);
      h_xs[0]->Fill(mS,mG,xsec);
      h_xs[1]->Fill(mS,mG,xsec - xsec*oneSigma_L);
      h_xs[2]->Fill(mS,mG,xsec + xsec*oneSigma_H);
      h_xs[3]->Fill(mS,mG,xsec - xsec*2*oneSigma_L);
      h_xs[4]->Fill(mS,mG,xsec + xsec*2*oneSigma_H);

      h_limit[0]->Fill(mS,mG,obsLimit*xsec);
      h_limit[1]->Fill(mS,mG,expLimit*xsec);
      h_limit[2]->Fill(mS,mG,exp_m1s*xsec);
      h_limit[3]->Fill(mS,mG,exp_p1s*xsec);
      h_limit[4]->Fill(mS,mG,exp_m2s*xsec);
      h_limit[5]->Fill(mS,mG,exp_p2s*xsec);
    }// if - else

  }// while
  fin.close();

  for(int i=0; i<nxs; i++) fillPotHoles(h_xs[i]);
  for(int i=0; i<nlimit; i++) fillPotHoles(h_limit[i]);


  TGraph* noRegion2 = new TGraph(3);
  noRegion2->SetPoint(0,200,200);
  noRegion2->SetPoint(1,1100,200);
  noRegion2->SetPoint(2,1100,1100);
  noRegion2->SetFillColor(16);

  TLatex* lat44 = new TLatex(0.7,0.25,"#tilde{g} NLSP");
  lat44->SetNDC(true);
  lat44->SetTextSize(0.04);


  TString title;

  TCanvas* can_acc = new TCanvas("can_acc_"+label,"can_acc_"+label,1000,800);
  can_acc->SetRightMargin(0.19);
  h_xs[5]->GetXaxis()->SetNdivisions(505);
  h_xs[5]->GetYaxis()->SetNdivisions(505);
  h_xs[5]->GetYaxis()->SetTitleOffset(1.2);
  h_xs[5]->GetZaxis()->SetTitleOffset(1.2);
  title = ";m_{#tilde{q}} (GeV/c^{2});m_{#tilde{g}} (GeV/c^{2});Acceptance";
  if(bino.Contains("mNScan")) title = ";m_{#chi^{0}} (GeV/c^{2});m_{#tilde{g}} (GeV/c^{2});Acceptance";
  h_xs[5]->SetTitle(title);
  h_xs[5]->Draw(option2D);
  if(bino.Contains("mNScan")){
    noRegion2->Draw("same f");
    lat44->Draw("same");
  }
  if(print) {
    can_acc->Print("",".gif");
    can_acc->Print("",".pdf");
  }



  TCanvas* can_xs = new TCanvas("can_xsec_"+label,"can_xsec_"+label,1000,800);
  can_xs->SetRightMargin(0.17);
  can_xs->SetLogz();
  h_xs[0]->GetXaxis()->SetNdivisions(505);
  h_xs[0]->GetYaxis()->SetNdivisions(505);
  h_xs[0]->GetYaxis()->SetTitleOffset(1.2);
  h_xs[0]->GetZaxis()->SetTitleOffset(1.0);
  title = ";m_{#tilde{q}} (GeV/c^{2});m_{#tilde{g}} (GeV/c^{2});Cross Section (pb)";
  if(bino.Contains("mNScan")) title = ";m_{#chi^{0}} (GeV/c^{2});m_{#tilde{g}} (GeV/c^{2});Cross Section (pb)";
  h_xs[0]->SetTitle(title);
  h_xs[0]->Draw(option2D);
  if(bino.Contains("mNScan")){
    noRegion2->Draw("same f");
    lat44->Draw("same");
  }
  if(print) {
    can_xs->Print("",".gif");
    can_xs->Print("",".pdf");
  }

  TCanvas* can_limit = new TCanvas("can_limit_"+label,"can_limit_"+label,1000,800);
  can_limit->SetRightMargin(0.2);
  h_limit[0]->GetXaxis()->SetNdivisions(505);
  h_limit[0]->GetYaxis()->SetNdivisions(505);
  h_limit[0]->GetYaxis()->SetTitleOffset(1.2);
  h_limit[0]->GetZaxis()->SetTitleOffset(1.3);
  if(bino.Contains("wino")){
    can_limit->SetRightMargin(0.17);
    h_limit[0]->GetZaxis()->SetTitleOffset(1.0);
  }

  title = ";m_{#tilde{q}} (GeV/c^{2});m_{#tilde{g}} (GeV/c^{2});95% CL Upper Limit (pb)";
  if(bino.Contains("mNScan")) title = ";m_{#chi^{0}} (GeV/c^{2});m_{#tilde{g}} (GeV/c^{2});95% CL Upper Limit (pb)";
  h_limit[0]->SetTitle(title);
  h_limit[0]->Draw(option2D);
  if(bino.Contains("mNScan")){
    noRegion2->Draw("same f");
    lat44->Draw("same");
  }
  if(print) {
    can_limit->Print("",".gif");
    can_limit->Print("",".pdf");
  }

  // now find exclusion curves
  TCanvas* can_diff = new TCanvas("can_diff_"+label,"can_diff_"+label,1200,800);
  //  can_diff->Divide(nlimit,nxs);
  TH2D* h_excl[nlimit][nxs-1];
  for(int i=0; i<nlimit; i++) {
    for(int j=0; j<nxs-1; j++) {

      h_excl[i][j] = (TH2D*) h_limit[i]->Clone("exclusion_"+limitname[i]+"_"+xsname[j]);
      int nbinsx = h_excl[i][j]->GetXaxis()->GetNbins();
      int nbinsy = h_excl[i][j]->GetYaxis()->GetNbins();

      for( int ibx=1; ibx<=nbinsx; ++ibx){
	for( int iby=1; iby<=nbinsy; ++iby){
	  double x1 = h_limit[i]->GetBinContent(ibx,iby);
	  double x2 = h_xs[j]->GetBinContent(ibx,iby);
	  h_excl[i][j]->SetBinContent(ibx,iby,x2-x1);
	  x1 = h_limit[i]->GetBinError(ibx,iby);
	  x2 = h_xs[j]->GetBinError(ibx,iby);
	  h_excl[i][j]->SetBinError(ibx,iby,std::sqrt(x1*x1+x2*x2));
	}// for iby
      }// for ibx
      fixBadCells(h_excl[i][j]);
      if(i==0 && j==0) h_excl[i][j]->Draw("TEXT");
    }// for j
  }// for i


  float xmin = 400;
  float ymin = 400;
  float xmax = 2000;
  float ymax = 2000;
  if(bino.Contains("mNScan")){
    xmin = 200;
    xmax = 1500;
    ymin = 300;
    ymax = 2000;
  }


  TGraph* curv[nlimit][nxs-1];
  TGraphSmooth* gsmooth = new TGraphSmooth("normal");

  TH2D* h_back;
  if(bino.Contains("mNScan")) h_back = new TH2D("h_back",";m_{#tilde{#chi^{0}}} (GeV/c^{2});m_{#tilde{g}} (GeV/c^{2})",100,xmin,xmax,100,ymin,ymax);
  else h_back = new TH2D("h_back",";m_{#tilde{q}} (GeV/c^{2});m_{#tilde{g}} (GeV/c^{2})",100,xmin,xmax,100,ymin,ymax);

  h_back->GetXaxis()->SetNdivisions(505);
  h_back->GetYaxis()->SetNdivisions(505);
  h_back->GetYaxis()->SetTitleOffset(1.2);


  double contours[2]={ 0.0, 1.0 };
  TCanvas *can_excl01 = new TCanvas("can_excl01_"+label, "can_excl01_"+label,1200,800);
  can_excl01->Divide(nlimit,nxs-1);
  for(int i=0; i<nlimit; i++) {
    for(int j=0; j<nxs-1; j++) {

      can_excl01->cd(j*nlimit + i + 1);
      h_back->Draw();

      if(useCustomGetContour) {
        curv[i][j] = getContour(h_excl[i][j],"excl_curv_"+limitname[i]+"_"+xsname[j]);
        curv[i][j]->Draw("SAME L");
      }
      else {
	h_excl[i][j]->SetContour(2,contours);
	h_excl[i][j]->Draw("SAME CONT LIST");
	gPad->Update();

	TObjArray *contsM = (TObjArray*) gROOT->GetListOfSpecials()->FindObject("contours");
	TList* contLevel = (TList*)contsM->At(0);
	curv[i][j] = (TGraph*)contLevel->First()->Clone("excl_curv_"+limitname[i]+"_"+xsname[j]);
      }
      //      PrintPoints(curv[i][j]);
      //      RemovePoints(curv[i][j]);

    }// for j
  }// for i

  if(bino.Contains("mNScan")) {
    for(int i=0; i<nlimit; i++) {
      for(int j=0; j<nxs-1; j++) {
	RemovePoints(curv[i][j]);
      }
    }

    for(int i=0; i<nlimit; i++) {
      for(int j=0; j<nxs-1; j++) {
	double x,y;
	int whichone = curv[i][j]->GetN()-1;
	curv[i][j]->GetPoint(whichone-1,x,y);
	curv[i][j]->SetPoint(whichone,y,y);
      }
    }
  }

  TGraphSmooth* gs[nlimit][nxs-1];
  TGraph* curvS[nlimit][nxs-1];
  for(int i=0; i<nlimit; i++) {
    for(int j=0; j<nxs-1; j++) {
      //      gs[i][j] = new TGraphSmooth("normal");
      //      curvS[i][j] = gs[i][j]->SmoothSuper(curv[i][j]);
      curvS[i][j] = (TGraph*) curv[i][j]->Clone();
      curvS[i][j]->SetName("excl_curvS_"+limitname[i]+"_"+xsname[j]);
    }
  }

  std::cout << "curv[3][0]----------------- N : " << curv[3][0]->GetN() << std::endl;
  PrintPoints(curv[3][0]);
  std::cout << "curvS[3][0]----------------- N : " << curvS[3][0]->GetN() << std::endl;
  PrintPoints(curvS[3][0]);
  std::cout << "---------------------------------" << std::endl;


  // make excluded region
  TGraph* excludedRegion = new TGraph(curvS[0][0]->GetN()+3);
  int nbins = curvS[0][0]->GetN();
  for(int i=0; i<nbins; i++){
    double x,y;
    curvS[0][0]->GetPoint(i,x,y);
    excludedRegion->SetPoint(i,x,y);
  }

  excludedRegion->SetPoint(nbins,xmax,ymin);
  excludedRegion->SetPoint(nbins+1,xmin,ymin);
  excludedRegion->SetPoint(nbins+2,xmin,ymax);

  // make band graph
  TGraph* exp1sigma_aroundExp = makeBandGraph(curvS[2][0],curvS[3][0]);


  TCanvas* can_excl02 = new TCanvas("can_excl02_"+label, "can_excl02_"+label,1000,800);
  h_back->Draw();
  //  can_excl02->SetGrid(1,1);

  // ecluded region
  excludedRegion->SetFillColor(kBlue-10);
  excludedRegion->SetFillStyle(1001);
  excludedRegion->Draw("SAME F");

  // experimental 1 sigma band around expected limit
  exp1sigma_aroundExp->SetFillColor(kOrange-3);
  exp1sigma_aroundExp->SetFillStyle(1001);
  exp1sigma_aroundExp->Draw("SAME F");

  // expected limit
  curvS[1][0]->SetLineStyle(9);
  curvS[1][0]->SetLineWidth(2);
  curvS[1][0]->SetLineColor(kOrange+9);
  curvS[1][0]->Draw("SAME L");

  // theory 1 sigma around expected limit
  curvS[1][1]->SetLineStyle(3);
  curvS[1][1]->SetLineWidth(1);
  curvS[1][1]->SetLineColor(kOrange+9);
  curvS[1][1]->Draw("SAME L");

  curvS[1][2]->SetLineStyle(3);
  curvS[1][2]->SetLineWidth(1);
  curvS[1][2]->SetLineColor(kOrange+9);
  curvS[1][2]->Draw("SAME L");

  // observed limit
  curvS[0][0]->SetLineWidth(3);
  curvS[0][0]->SetLineColor(4);
  curvS[0][0]->Draw("SAME L");

  // theory 1 sigma around observed limit
  curvS[0][1]->SetLineStyle(3);
  curvS[0][1]->SetLineWidth(2);
  curvS[0][1]->SetLineColor(kBlue);
  curvS[0][1]->Draw("SAME L");

  curvS[0][2]->SetLineStyle(3);
  curvS[0][2]->SetLineWidth(2);
  curvS[0][2]->SetLineColor(kBlue);
  curvS[0][2]->Draw("SAME L");


  PrintPoints(curvS[0][0]);


  float leg_xmin = 0.65;
  float leg_xmax = 0.9;
  float leg_ymin = 0.5;
  float leg_ymax = 0.8;
  if(bino.Contains("mNScan")){
    leg_xmin -= 0.45;
    leg_xmax -= 0.45;
  }


  TLegend* leg;
  if(bino.Contains("mNScan")) leg = new TLegend(leg_xmin,leg_ymin,leg_xmax,leg_ymax,"","brNDC");
  else leg = new TLegend(leg_xmin,leg_ymin,leg_xmax,leg_ymax,"GGM "+bino+"-like #tilde{#chi}^{0}","brNDC");
  leg->SetFillColor(0);
  leg->SetLineColor(0);
  leg->SetBorderSize(0);
  leg->SetTextFont(62);
  leg->SetTextSize(0.03);
  if(bino.Contains("mNScan")) leg->AddEntry("NULL","m_{#tilde{q}} = 2500 (GeV/c^{2})","h");
  else leg->AddEntry("NULL","m_{#tilde{#chi}^{0}} = 375 (GeV/c^{2})","h");
  TString jetRequirement = "Without jet requirement";
  if(jet.Contains("1jet")) jetRequirement = "At least 1 jet requirement";
  leg->AddEntry("NULL",jetRequirement,"h");
  leg->AddEntry("NULL","NLO Limits","h");
  leg->AddEntry(curvS[0][0],"Observed","L");
  leg->AddEntry(curvS[0][1],"#pm1#sigma (theory)","L");
  leg->AddEntry(curvS[1][0],"Expected","L");
  leg->AddEntry(curvS[1][1],"#pm1#sigma (theory)","L");
  leg->AddEntry(exp1sigma_aroundExp,"#pm1#sigma (experimental)","F");
  leg->Draw("same");

  TLatex* lat = new TLatex(leg_xmin+0.02,0.87,"CMS Preliminary");
  lat->SetNDC(true);
  lat->SetTextFont(43);
  lat->SetTextSize(30);
  lat->Draw("same");

  TLatex* lat2 = new TLatex(leg_xmin,0.83,"#int #font[12]{L}dt = 4.7fb^{-1}, #sqrt{s} = 7 TeV");
  lat2->SetNDC(true);
  lat2->SetTextFont(43);
  lat2->SetTextSize(24);
  lat2->Draw("same");

  float xv = 0.25;
  float yv = 0.25;
  if(bino.Contains("wino")){
    xv = 0.23;
    yv = 0.23;
  }
  if(bino.Contains("mNScan")){
    xv = 0.2;
    yv = 0.3;
  }
  TLatex* lat3 = new TLatex(xv,yv,"Excluded");
  lat3->SetNDC(true);
  lat3->SetTextFont(52);
  lat3->SetTextSize(0.06);
  lat3->Draw("same");

  TGraph* noRegion = new TGraph(3);
  noRegion->SetPoint(0,TMath::Min(xmin,ymin),TMath::Min(xmin,ymin));
  noRegion->SetPoint(1,xmax,ymin);
  noRegion->SetPoint(2,TMath::Min(xmax,ymax),TMath::Min(xmax,ymax));
  noRegion->SetFillColor(16);

  TLatex* lat4 = new TLatex(0.7,0.25,"#tilde{g} NLSP");
  lat4->SetNDC(true);
  lat4->SetTextSize(0.04);

  if(bino.Contains("mNScan")){
    noRegion->Draw("same f");
    lat4->Draw("same");
  }

  can_excl02->RedrawAxis();


  if(print) {
    can_excl02->Print("",".gif");
    can_excl02->Print("",".pdf");
  }

  fout->cd();
  fout->Write();

  can_acc->Write();
  can_xs->Write();
  can_limit->Write();
  can_excl01->Write();
  can_excl02->Write();

  for(int i=0; i<nlimit; i++){
    for(int j=0; j<nxs-1; j++){
      curv[i][j]->Write();
      curvS[i][j]->Write();
    }
  }


}
Example #6
0
void data_to_tree()
{
	Double_t pedtime;
	Double_t pedTr;
	Double_t pedTl;
	Double_t rped;
	Double_t lped;
	//ptfactor = point to time factor
	//const Double_t ptfactor = 0.050;
	const Double_t ptfactor = 0.0407;

	TFile* f = new TFile("data_to_tree.root", "RECREATE");

	ifstream in;
	ofstream out;

	//bring data files and give name to use in this code.
	//data file name is in order type_ch0highvoltage_ch2highvoltage_#ofevent_position_3.dat
	
	const Int_t nFile = 10; // including long file for TWC 
	const Char_t* file[nFile] = {"./Cobalt_data/Co_2090v_2160v_10k_10cm_3.dat",
									"./Cobalt_data/Co_2090v_2160v_10k_20cm_3.dat",
									"./Cobalt_data/Co_2090v_2160v_10k_30cm_3.dat",
									"./Cobalt_data/Co_2090v_2160v_10k_40cm_3.dat",
									"./Cobalt_data/Co_2090v_2160v_10k_50cm_3.dat",
									"./Cobalt_data/Co_2090v_2160v_10k_60cm_3.dat",
									"./Cobalt_data/Co_2090v_2160v_10k_70cm_3.dat",
									"./Cobalt_data/Co_2090v_2160v_10k_80cm_3.dat",
									"./Cobalt_data/Co_2090v_2160v_10k_90cm_3.dat",
									"./Cobalt_data/Co_2090v_2160v_100k_50cm_3.dat"};

	const Char_t* distance[nFile] = {"10cm", "20cm", "30cm", "40cm", "50cm", "60cm", "70cm", "80cm", "90cm", "50cm100k"};

	TCanvas* c1 = new TCanvas("c1", "pedl", 200, 0, 600, 600);
	TH1F* pedlhist = new TH1F("pedlhist", "left", 200, 0, 200);
	TCanvas* c2 = new TCanvas("c2", "pedr", 210, 10, 610, 610);
	TH1F* pedrhist = new TH1F("pedrhist", "right", 200, 0, 200);

	//bring the pedestal file
	in.open("./Cobalt_data/pedestal_2090v_2160v_10k_4.dat");

	if(in.is_open())
	{
		while(1)
		{
			in >> pedtime >> pedTl >> pedTr >> lped >> rped;
			if(!in.good()) break;
			pedlhist->Fill(lped);
			pedrhist->Fill(rped);
		}
	}
	in.close();

	c1->cd();
	pedlhist->Draw();
	pedlhist->Fit("gaus", "", "", 150, 160);
	Double_t pedlmean = pedlhist->GetFunction("gaus")->GetParameter(1);
	c1->SaveAs("CFDpedl.png");

	c2->cd();
	pedrhist->Draw();
	pedrhist->Fit("gaus", "", "", 105, 125);
	Double_t pedrmean = pedrhist->GetFunction("gaus")->GetParameter(1);
	c2->SaveAs("CFDpedr.png");

	//pr: position resolution
	TTree* pr[nFile];

	for(Int_t i = 0; i < nFile; i++)
	{
		in.open(file[i]);

		Double_t time = 0;
		Double_t Tl = 0;
		Double_t Tr = 0;
		Double_t Al = 0;
		Double_t Ar = 0;

		pr[i] = new TTree(distance[i], "position resolution data");
		pr[i]->Branch("Tl", &Tl, "Tl/D");
		pr[i]->Branch("Tr", &Tr, "Tr/D");
		pr[i]->Branch("Al", &Al, "Al/D");
		pr[i]->Branch("Ar", &Ar, "Ar/D");

		//correction 
		// 1. TDCchannel * ptfactor
		// 2. ADC - pedestal mean
		if(in.is_open())
		{
			while(1)
			{
				in >> time >> Tl >> Tr >> Al >> Ar;
				if(!in.good()) break;
				Tl = Tl*ptfactor;
				Tr = Tr*ptfactor;
				Al = Al-pedlmean;
				Ar = Ar-pedrmean;
				pr[i]->Fill();
			}
		}
		in.close();
	}
	f->Write();
}
//.x Skimming.C+("Input_2015D_v3_ONE.txt","BB_reduced.root")
void Skimming( TString fileList, TString outName ){

  //Doing the chain
  cout<<"Starting... "<<endl;
  TChain chain_data("cutFlowAnalyzer/Events");
  TChain chain_databb("cutFlowAnalyzer/Events_orphan");
  std::ifstream Myfile( fileList.Data() );
  std::string Line;
  if( !Myfile ) std::cout<<"ERROR opening "<<fileList<<std::endl;
  while (std::getline(Myfile, Line)){
    TString Line2(Line);
    if( Line2.Contains("root") ){
	chain_data.Add(Line2.Data());
	chain_databb.Add(Line2.Data());
    }
  }
  cout<<"Chain done!"<<endl;
  //Variables needed
  bool orph_passOffLineSel_bb, orph_passOffLineSelPt_bb, orph_passOffLineSelPt1788_bb, orph_FiredTrig_bb, orph_FiredTrig_pt_bb, orph_FiredTrig_ptColl_bb;
  int containstrig2_bb, containstrig_bb;
  float orph_dimu_mass_bb, orph_dimu_isoTk_bb;
  chain_databb.SetBranchAddress("orph_passOffLineSel",&orph_passOffLineSel_bb);
  chain_databb.SetBranchAddress("orph_passOffLineSelPt",&orph_passOffLineSelPt_bb);
  chain_databb.SetBranchAddress("orph_passOffLineSelPt1788",&orph_passOffLineSelPt1788_bb);
  chain_databb.SetBranchAddress("orph_FiredTrig",&orph_FiredTrig_bb);
  chain_databb.SetBranchAddress("orph_FiredTrig_pt",&orph_FiredTrig_pt_bb);
  chain_databb.SetBranchAddress("orph_FiredTrig_ptColl",&orph_FiredTrig_ptColl_bb);
  chain_databb.SetBranchAddress("orph_FiredTrig",&orph_FiredTrig_bb);
  chain_databb.SetBranchAddress("orph_dimu_isoTk",&orph_dimu_isoTk_bb);
  chain_databb.SetBranchAddress("containstrig2",&containstrig2_bb);
  chain_databb.SetBranchAddress("orph_dimu_mass",&orph_dimu_mass_bb);
  chain_databb.SetBranchAddress("containstrig",&containstrig_bb);
  float massC_mu, massF_mu, isoC_1mm_mu, isoF_1mm_mu;
  chain_data.SetBranchAddress("massC",&massC_mu);
  chain_data.SetBranchAddress("massF",&massF_mu);
  chain_data.SetBranchAddress("isoC_1mm",&isoC_1mm_mu);
  chain_data.SetBranchAddress("isoF_1mm",&isoF_1mm_mu);
  //My file
  TFile *f = new TFile(outName.Data(),"RECREATE");
  f->cd();
  TTree Events("Events","");
  float massC, massF, isoC_1mm, isoF_1mm;
  Events.Branch("massC",&massC,"massC/F");
  Events.Branch("massF",&massF,"massF/F");
  Events.Branch("isoC_1mm",&isoC_1mm,"isoC_1mm/F");
  Events.Branch("isoF_1mm",&isoF_1mm,"isoF_1mm/F");
  bool orph_passOffLineSel, orph_passOffLineSelPt, orph_passOffLineSelPt1788, orph_FiredTrig, orph_FiredTrig_pt, orph_FiredTrig_ptColl;
  int containstrig2, containstrig;
  float orph_dimu_mass, orph_dimu_isoTk;
  TTree Events_orphan("Events_orphan","");
  Events_orphan.Branch("orph_passOffLineSel",&orph_passOffLineSel,"orph_passOffLineSel/O");
  Events_orphan.Branch("orph_passOffLineSelPt",&orph_passOffLineSelPt,"orph_passOffLineSelPt/O");
  Events_orphan.Branch("orph_passOffLineSelPt1788",&orph_passOffLineSelPt1788,"orph_passOffLineSelPt1788/O");
  Events_orphan.Branch("orph_FiredTrig",&orph_FiredTrig,"orph_FiredTrig/O");
  Events_orphan.Branch("orph_FiredTrig_pt",&orph_FiredTrig_pt,"orph_FiredTrig_pt/O");
  Events_orphan.Branch("orph_FiredTrig_ptColl",&orph_FiredTrig_ptColl,"orph_FiredTrig_ptColl/O");
  Events_orphan.Branch("containstrig2",&containstrig2,"containstrig2/I");
  Events_orphan.Branch("containstrig",&containstrig,"containstrig/I");
  Events_orphan.Branch("orph_dimu_isoTk",&orph_dimu_isoTk,"orph_dimu_isoTk/F");
  Events_orphan.Branch("orph_dimu_mass",&orph_dimu_mass,"orph_dimu_mass/F");
  //Loops
  cout<<"Now starting loop on bb."<<endl;
  Long64_t entries = chain_databb.GetEntries(); 
  for(Long64_t i=0; i<entries; i++){ 
    if(i%10000==0) cout<<"i = "<<i<<" / "<<entries<<endl;
    chain_databb.GetEntry(i);
    if(orph_dimu_mass>-999.){
	orph_passOffLineSel = orph_passOffLineSel_bb;
	orph_passOffLineSelPt = orph_passOffLineSelPt_bb;
	orph_passOffLineSelPt1788 = orph_passOffLineSelPt1788_bb;
	orph_FiredTrig = orph_FiredTrig_bb;
	orph_FiredTrig_pt = orph_FiredTrig_pt_bb;
	orph_FiredTrig_ptColl = orph_FiredTrig_ptColl_bb;
	containstrig2 = containstrig2_bb;
	containstrig = containstrig_bb;
	orph_dimu_isoTk = orph_dimu_isoTk_bb;
	orph_dimu_mass = orph_dimu_mass_bb;
	Events_orphan.Fill();
    }
  }
  cout<<"Now starting loop on mu."<<endl;
  entries = chain_data.GetEntries(); 
  for(Long64_t i=0; i<entries; i++){ 
    if(i%10000==0) cout<<"i = "<<i<<" / "<<entries<<endl;
    chain_data.GetEntry(i);
    if(massC_mu>-999. || massF_mu>-999.){
	massC = massC_mu;
	massF = massF_mu;
	isoC_1mm = isoC_1mm_mu;
	isoF_1mm = isoF_1mm_mu;
	Events.Fill();
    }
  }
  cout<<"CLosing files"<<endl;
  f->Write();
  f->Close();
  cout<<"The end."<<endl;
}
Example #8
0
void projectPbPbMB()
{
  gStyle->SetTextSize(0.05);
  gStyle->SetTextFont(42);
  gStyle->SetPadRightMargin(0.043);
  gStyle->SetPadLeftMargin(0.18);
  gStyle->SetPadTopMargin(0.1);
  gStyle->SetPadBottomMargin(0.145);
  gStyle->SetTitleX(.0f);
  gStyle->SetOptFit(1111);
  gStyle->SetOptStat(0);
  gStyle->SetOptTitle(0);

  TFile* inf = new TFile("/data/jisun/PbPb2015/HF2and_ncand_skim_Dntuple_crab_PbPb_HIMinimumBias1to7_ForestAOD_D0y1p1_tkpt0p7eta1p5_goldenjson_EvtPlaneCali_03182015.root");
//	TFile* inf = new TFile("/afs/cern.ch/work/c/chengchi/work/Project/BtoD/MC_Dntuples/PbPb/Dntuple_PbPb_mergeall.root");
  TTree* tData = (TTree*)inf->Get("ntDkpi");
  TTree* tSkim = (TTree*)inf->Get("ntSkim");
  TTree* tHi = (TTree*)inf->Get("ntHi");
  TTree* tHlt = (TTree*)inf->Get("ntHlt");

  tData->AddFriend(tSkim);
  tData->AddFriend(tHi);
  tData->AddFriend(tHlt);

  TFile* outf = new TFile("bFeedDownPbPbMB.hist.root","recreate");
  
  TCut cutTriggerPbPbMB = "(HLT_HIL1MinimumBiasHF2AND_part1_v1||HLT_HIL1MinimumBiasHF2AND_part2_v1||HLT_HIL1MinimumBiasHF2AND_part3_v1)";
  TCut cutPbPbMB = "pclusterCompatibilityFilter&&pprimaryVertexFilter&&abs(PVz)<15&&phfCoincFilter3&&Dy>-1.&&Dy<1.&&Dtrk1highPurity&&Dtrk2highPurity&&Dtrk1Pt>1.0&&Dtrk2Pt>1.0&&Dtrk1PtErr/Dtrk1Pt<0.3&&Dtrk2PtErr/Dtrk2Pt<0.3&&abs(Dtrk1Eta)<1.5&&abs(Dtrk2Eta)<1.5&&((DlxyBS/DlxyBSErr)>1.5&&Dalpha<0.12&&((Dpt>1&&Dpt<2&&(DsvpvDistance/DsvpvDisErr)>6.0&&Dchi2cl>0.25)||(Dpt>2&&Dpt<4&&(DsvpvDistance/DsvpvDisErr)>5.86&&Dchi2cl>0.224)||(Dpt>4&&Dpt<5&&(DsvpvDistance/DsvpvDisErr)>5.46&&Dchi2cl>0.196)||(Dpt>5&&Dpt<6&&(DsvpvDistance/DsvpvDisErr)>4.86&&Dchi2cl>0.170)||(Dpt>6&&Dpt<8&&(DsvpvDistance/DsvpvDisErr)>4.54&&Dchi2cl>0.125)||(Dpt>8&&Dpt<10&&(DsvpvDistance/DsvpvDisErr)>4.42&&Dchi2cl>0.091)||(Dpt>10&&Dpt<15&&(DsvpvDistance/DsvpvDisErr)>4.06&&Dchi2cl>0.069)||(Dpt>15&&Dpt<20&&(DsvpvDistance/DsvpvDisErr)>3.71&&Dchi2cl>0.056)||(Dpt>20&&Dpt<25&&(DsvpvDistance/DsvpvDisErr)>3.25&&Dchi2cl>0.054)||(Dpt>25&&(DsvpvDistance/DsvpvDisErr)>2.97&&Dchi2cl>0.050)))";
  TCut cutCentralityBin = "hiBin>=0&&hiBin<200";
  TCut cutpt = "Dpt<20";
  TCut cutSignal = "abs(Dmass-1.8649)<0.025";
  TCut cutSideband = "abs(Dmass-1.8649)>0.075&&abs(Dmass-1.8649)<0.1";

  const int nBinX = 14;
  Float_t binsX[nBinX+1] = {2.,3.,4.,5.,6.,8.,10.,12,15.0,20.,25.,30.,40.,60.,100};

/*
  const int nBinY = 20;
  Float_t binsY[nBinY+1];
  float firstBinYWidth = 0.001;
  float binYWidthRatio = 1.27;
  binsY[0]=0;
  for(int i=1; i<=nBinY; i++)
    binsY[i] = binsY[i-1]+firstBinYWidth*pow(binYWidthRatio,i-1);
  cout<<"last y bin: "<<binsY[nBinY]<<endl;


	const int nBinY = 200;
	Float_t binsY[nBinY+1];
	float firstBinY = -0.1;
	float binWidthY = 0.001;
	for(int i = 0 ; i<=nBinY; i++)
		binsY[i] = firstBinY+binWidthY*i;
*/
  const int nBinY = 20;
  Float_t binsY[nBinY+1] = {-0.0734,-0.0562,-0.0428,-0.0320,-0.0236,-0.0170,-0.0118,-0.0078,-0.0046,-0.002,0.0,0.002,0.0046,0.0078,0.0118,0.0170,0.0236,0.0320,0.0428,0.0562,0.0734};


  const int nBinZ = 20;
  Float_t binsZ[nBinZ+1];
  float firstBinZ = 3.5;
  float binWidthZ = 5;
  for(int i=0; i<=nBinZ; i++)
    binsZ[i] = firstBinZ+binWidthZ*i;
  
  const int nBinM = 60;
  Float_t binsM[nBinM];
  float minMassBin = 1.7;
  float massBinWidth = 0.005;
  for(int i=0; i<=nBinM; i++)
    binsM[i] = minMassBin + massBinWidth*i;

  TH3D* hSideband = new TH3D("hSideband",";p_{T} (GeV/c};D^{0} DCA_xy(cm);flight distance significance",nBinX,binsX,nBinY,binsY,nBinZ,binsZ);
  TH3D* hData = new TH3D("hData",";p_{T} (GeV/c};D^{0} DCA_xy(cm);flight distance significance",nBinX,binsX,nBinY,binsY,nBinZ,binsZ);
  TH3D* hPtMD0Dca = new TH3D("hPtMD0Dca",";p_{T} (GeV/c);m (GeV/c^{2});D^{0} DCA_xy (cm)",nBinX,binsX,nBinM,binsM,nBinY,binsY);
  
  hSideband->Sumw2();
  hData->Sumw2();
  hPtMD0Dca->Sumw2();
  
  tData->Draw("DsvpvDistance/DsvpvDisErr:DvtxX*sin(Dphi)-DvtxY*cos(Dphi):Dpt>>hSideband",cutpt&&cutTriggerPbPbMB&&cutPbPbMB&&cutCentralityBin&&cutSideband);
  tData->Draw("DsvpvDistance/DsvpvDisErr:DvtxX*sin(Dphi)-DvtxY*cos(Dphi):Dpt>>hData",cutpt&&cutTriggerPbPbMB&&cutPbPbMB&&cutCentralityBin&&cutSignal);
  tData->Draw("DvtxX*sin(Dphi)-DvtxY*cos(Dphi):Dmass:Dpt>>hPtMD0Dca",cutpt&&cutTriggerPbPbMB&&cutPbPbMB&&cutCentralityBin);
  
  outf->Write();
}
void dimuonSkim(const TString configFile, const TString inputFile, const TString outputFile)
{
       std::cout<<"running dimuonSkim()"   <<std::endl;
       std::cout<<"configFile  = "<< configFile.Data() <<std::endl;
       std::cout<<"inputFile   = "<< inputFile.Data() <<std::endl;
       std::cout<<"outputFile  = "<< outputFile.Data() <<std::endl;

       InputConfiguration configInput = InputConfigurationParser::Parse(configFile.Data());
       CutConfiguration configCuts = CutConfigurationParser::Parse(configFile.Data());

       if (!configInput.isValid) {
           std::cout << "Input configuration is invalid." << std::endl;
           std::cout << "exiting" << std::endl;
           return;
       }
       if (!configCuts.isValid) {
           std::cout << "Cut configuration is invalid." << std::endl;
           std::cout << "exiting" << std::endl;
           return;
       }

       // input configuration
       int collisionType = configInput.proc[INPUT::kSKIM].i[INPUT::k_collisionType];
       std::string treePath = configInput.proc[INPUT::kSKIM].s[INPUT::k_treePath];

       // set default values
       if (treePath.size() == 0)  treePath = "ggHiNtuplizer/EventTree";

       // verbose about input configuration
       std::cout<<"Input Configuration :"<<std::endl;
       std::cout << "collisionType = " << collisionType << std::endl;
       const char* collisionName =  getCollisionTypeName((COLL::TYPE)collisionType).c_str();
       std::cout << "collision = " << collisionName << std::endl;
       std::cout << "treePath = " << treePath.c_str() << std::endl;

       // cut configuration
       float cut_vz = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].f[CUTS::EVT::k_vz];
       int cut_pcollisionEventSelection = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].i[CUTS::EVT::k_pcollisionEventSelection];
       int cut_pPAprimaryVertexFilter = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].i[CUTS::EVT::k_pPAprimaryVertexFilter];
       int cut_pBeamScrapingFilter = configCuts.proc[CUTS::kSKIM].obj[CUTS::kEVENT].i[CUTS::EVT::k_pBeamScrapingFilter];

       int cut_nMu = configCuts.proc[CUTS::kSKIM].obj[CUTS::kMUON].i[CUTS::MUO::k_nMu];

       // bool isMC = collisionIsMC((COLL::TYPE)collisionType);
       bool isHI = collisionIsHI((COLL::TYPE)collisionType);
       bool isPP = collisionIsPP((COLL::TYPE)collisionType);

       // verbose about cut configuration
       std::cout<<"Cut Configuration :"<<std::endl;
       std::cout<<"cut_vz = "<< cut_vz <<std::endl;
       if (isHI) {
           std::cout<<"cut_pcollisionEventSelection = "<< cut_pcollisionEventSelection <<std::endl;
       }
       else {   // PP
           std::cout<<"cut_pPAprimaryVertexFilter = "<< cut_pPAprimaryVertexFilter <<std::endl;
           std::cout<<"cut_pBeamScrapingFilter = "<< cut_pBeamScrapingFilter <<std::endl;
       }

       std::cout<<"cut_nMu = "<<cut_nMu<<std::endl;

       std::vector<std::string> inputFiles = InputConfigurationParser::ParseFiles(inputFile.Data());

       std::cout<<"input ROOT files : num = "<<inputFiles.size()<< std::endl;
       std::cout<<"#####"<< std::endl;
       for (std::vector<std::string>::iterator it = inputFiles.begin() ; it != inputFiles.end(); ++it) {
           std::cout<<(*it).c_str()<< std::endl;
       }
       std::cout<<"##### END #####"<< std::endl;

       TChain* treeHLT   = new TChain("hltanalysis/HltTree");
       TChain* treeggHiNtuplizer  = new TChain("ggHiNtuplizer/EventTree");
       TChain* treeHiEvt = new TChain("hiEvtAnalyzer/HiTree");
       TChain* treeSkim  = new TChain("skimanalysis/HltTree");
       TChain* treeHiForestInfo = new TChain("HiForest/HiForestInfo");

       for (std::vector<std::string>::iterator it = inputFiles.begin() ; it != inputFiles.end(); ++it) {
          treeHLT->Add((*it).c_str());
          treeggHiNtuplizer->Add((*it).c_str());
          treeHiEvt->Add((*it).c_str());
          treeSkim->Add((*it).c_str());
          treeHiForestInfo->Add((*it).c_str());
       }

       HiForestInfoController hfic(treeHiForestInfo);
       std::cout<<"### HiForestInfo Tree ###"<< std::endl;
       hfic.printHiForestInfo();
       std::cout<<"###"<< std::endl;

       treeHLT->SetBranchStatus("*",0);     // disable all branches
       treeHLT->SetBranchStatus("HLT_HI*SinglePhoton*Eta*",1);     // enable photon branches
       treeHLT->SetBranchStatus("HLT_HI*DoublePhoton*Eta*",1);     // enable photon branches
       treeHLT->SetBranchStatus("*DoubleMu*",1);                      // enable muon branches
       treeHLT->SetBranchStatus("HLT_HIL1Mu*",1);                     // enable muon branches
       treeHLT->SetBranchStatus("HLT_HIL2Mu*",1);                     // enable muon branches
       treeHLT->SetBranchStatus("HLT_HIL3Mu*",1);                     // enable muon branches
       
       // specify explicitly which branches to store, do not use wildcard
       treeHiEvt->SetBranchStatus("*",1);

       // specify explicitly which branches to store, do not use wildcard
       treeSkim->SetBranchStatus("*",0);

       Int_t pcollisionEventSelection;  // this filter is used for HI.
       if (isHI) {
           treeSkim->SetBranchStatus("pcollisionEventSelection",1);
           if (treeSkim->GetBranch("pcollisionEventSelection")) {
               treeSkim->SetBranchAddress("pcollisionEventSelection",&pcollisionEventSelection);
           }
           else {   // overwrite to default
               pcollisionEventSelection = 1;
               std::cout<<"could not get branch : pcollisionEventSelection"<<std::endl;
               std::cout<<"set to default value : pcollisionEventSelection = "<<pcollisionEventSelection<<std::endl;
           }
       }
       else {
           pcollisionEventSelection = 0;    // default value if the collision is not HI, will not be used anyway.
       }
       Int_t pPAprimaryVertexFilter;    // this filter is used for PP.
       if (isPP) {
           treeSkim->SetBranchStatus("pPAprimaryVertexFilter",1);
           if (treeSkim->GetBranch("pPAprimaryVertexFilter")) {
               treeSkim->SetBranchAddress("pPAprimaryVertexFilter",&pPAprimaryVertexFilter);
           }
           else {   // overwrite to default
               pPAprimaryVertexFilter = 1;
               std::cout<<"could not get branch : pPAprimaryVertexFilter"<<std::endl;
               std::cout<<"set to default value : pPAprimaryVertexFilter = "<<pPAprimaryVertexFilter<<std::endl;
           }
       }
       else {
           pPAprimaryVertexFilter = 0;      // default value if the collision is not PP, will not be used anyway.
       }
       Int_t pBeamScrapingFilter;   // this filter is used for PP.
       if (isPP) {
           treeSkim->SetBranchStatus("pBeamScrapingFilter",1);
           if (treeSkim->GetBranch("pBeamScrapingFilter")) {
               treeSkim->SetBranchAddress("pBeamScrapingFilter",&pBeamScrapingFilter);
           }
           else {   // overwrite to default
               pBeamScrapingFilter = 1;
               std::cout<<"could not get branch : pBeamScrapingFilter"<<std::endl;
               std::cout<<"set to default value : pBeamScrapingFilter = "<<pBeamScrapingFilter<<std::endl;
           }
       }
       else {
           pBeamScrapingFilter = 0;     // default value if the collision is not PP, will not be used anyway.
       }

       ggHiNtuplizer ggHi;
       ggHi.setupTreeForReading(treeggHiNtuplizer);
       
       hiEvt hiEvt;
       hiEvt.setupTreeForReading(treeHiEvt);

       TFile* output = new TFile(outputFile,"RECREATE");
       TTree *configTree = setupConfigurationTreeForWriting(configCuts);

       // output tree variables
       TTree *outputTreeHLT           = treeHLT->CloneTree(0);
       outputTreeHLT->SetName("hltTree");
       outputTreeHLT->SetTitle("subbranches of hltanalysis/HltTree");
       TTree *outputTreeggHiNtuplizer = treeggHiNtuplizer->CloneTree(0);
       TTree *outputTreeHiEvt = treeHiEvt->CloneTree(0);
       outputTreeHiEvt->SetName("HiEvt");
       outputTreeHiEvt->SetTitle("subbranches of hiEvtAnalyzer/HiTree");
       TTree* outputTreeSkim  = treeSkim->CloneTree(0);
       outputTreeSkim->SetName("skim");
       outputTreeSkim->SetTitle("subbranches of skimanalysis/HltTree");
       TTree* outputTreeHiForestInfo = treeHiForestInfo->CloneTree(0);
       outputTreeHiForestInfo->SetName("HiForestInfo");
       outputTreeHiForestInfo->SetTitle("first entry of HiForest/HiForestInfo");
       
       outputTreeHLT->SetMaxTreeSize(MAXTREESIZE);
       outputTreeggHiNtuplizer->SetMaxTreeSize(MAXTREESIZE);
       outputTreeHiEvt->SetMaxTreeSize(MAXTREESIZE);
       outputTreeHiForestInfo->SetMaxTreeSize(MAXTREESIZE);

       // write HiForestInfo
       treeHiForestInfo->GetEntry(0);
       outputTreeHiForestInfo->Fill();

       TTree *diMuonTree = new TTree("dimuon","muon pairs");
       diMuonTree->SetMaxTreeSize(MAXTREESIZE);

       dimuon diMu;
       diMu.branchDiMuonTree(diMuonTree);

       EventMatcher* em = new EventMatcher();
       Long64_t duplicateEntries = 0;

       Long64_t entries = treeggHiNtuplizer->GetEntries();
       Long64_t entriesPassedEventSelection = 0;
       Long64_t entriesAnalyzed = 0;
       std::cout << "entries = " << entries << std::endl;
       std::cout<< "Loop : " << treePath.c_str() <<std::endl;
       for (Long64_t j_entry=0; j_entry<entries; ++j_entry)
       {
           if (j_entry % 20000 == 0)  {
             std::cout << "current entry = " <<j_entry<<" out of "<<entries<<" : "<<std::setprecision(2)<<(double)j_entry/entries*100<<" %"<<std::endl;
           }

           treeHLT->GetEntry(j_entry);
           treeggHiNtuplizer->GetEntry(j_entry);
           treeHiEvt->GetEntry(j_entry);
           treeSkim->GetEntry(j_entry);

           bool eventAdded = em->addEvent(ggHi.run,ggHi.lumis,ggHi.event,j_entry);
           if(!eventAdded) // this event is duplicate, skip this one.
           {
               duplicateEntries++;
               continue;
           }

           // event selection
           if (!(TMath::Abs(hiEvt.vz) < cut_vz))  continue;
           if (isHI) {
               if ((pcollisionEventSelection < cut_pcollisionEventSelection))  continue;
           }
           else {
               if (pPAprimaryVertexFilter < cut_pPAprimaryVertexFilter || pBeamScrapingFilter < cut_pBeamScrapingFilter)  continue;
           }
           entriesPassedEventSelection++;

           // skip if there are no muon pairs to study
           if(ggHi.nMu < cut_nMu)  continue;
           entriesAnalyzed++;

           diMu.makeDiMuonPairs(ggHi);

           outputTreeHLT->Fill();
           outputTreeggHiNtuplizer->Fill();
           outputTreeHiEvt->Fill();
           outputTreeSkim->Fill();
           diMuonTree->Fill();
       }
       std::cout<< "Loop ENDED : " << treePath.c_str() <<std::endl;
       std::cout << "entries            = " << entries << std::endl;
       std::cout << "duplicateEntries   = " << duplicateEntries << std::endl;
       std::cout << "entriesPassedEventSelection   = " << entriesPassedEventSelection << std::endl;
       std::cout << "entriesAnalyzed    = " << entriesAnalyzed << std::endl;
       std::cout << "outputTreeHLT->GetEntries()           = " << outputTreeHLT->GetEntries() << std::endl;
       std::cout << "outputTreeggHiNtuplizer->GetEntries() = " << outputTreeggHiNtuplizer->GetEntries() << std::endl;
       std::cout << "outputTreeHiEvt->GetEntries() = " << outputTreeHiEvt->GetEntries() << std::endl;
       std::cout << "outputTreeSkim->GetEntries()  = " << outputTreeSkim->GetEntries() << std::endl;
       std::cout << "diMuonTree->GetEntries()          = " << diMuonTree->GetEntries() << std::endl;

       // overwrite existing trees
       outputTreeHLT->Write("", TObject::kOverwrite);
       outputTreeggHiNtuplizer->Write("", TObject::kOverwrite);
       outputTreeHiEvt->Write("", TObject::kOverwrite);
       diMuonTree->Write("", TObject::kOverwrite);

       configTree->Write("", TObject::kOverwrite);

       output->Write("", TObject::kOverwrite);
       output->Close();

       std::cout<<"dimuonSkim() - END"   <<std::endl;
}
Example #10
0
void selectAntiWe(const TString conf,        // input file
                  const TString outputDir,   // output directory
	          const Bool_t  doScaleCorr  // apply energy scale corrections?
) {
  gBenchmark->Start("selectAntiWe");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 

  const Double_t PT_CUT   = 20;
  const Double_t ETA_CUT  = 2.5;
  const Double_t ELE_MASS = 0.000511;
  
  const Double_t ECAL_GAP_LOW  = 1.4442;
  const Double_t ECAL_GAP_HIGH = 1.566;
  
  const Double_t escaleNbins  = 6;
  const Double_t escaleEta[]  = { 0.4,     0.8,     1.2,     1.4442,  2,        2.5 };
  const Double_t escaleCorr[] = { 1.00284, 1.00479, 1.00734, 1.00851, 1.00001,  0.982898 };
  
  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  vector<TString>  snamev;      // sample name (for output files)  
  vector<CSample*> samplev;     // data/MC samples

  //
  // parse .conf file
  //
  confParse(conf, snamev, samplev);
  const Bool_t hasData = (samplev[0]->fnamev.size()>0);

  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  const TString ntupDir = outputDir + TString("/ntuples");
  gSystem->mkdir(ntupDir,kTRUE);
  
  //
  // Declare output ntuple variables
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  Float_t genVPt, genVPhi, genVy, genVMass;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Int_t   q;
  LorentzVector *lep=0;
  ///// electron specific /////
  Float_t trkIso, emIso, hadIso;
  Float_t pfChIso, pfGamIso, pfNeuIso, pfCombIso;
  Float_t sigieie, hovere, eoverp, fbrem, ecalE;
  Float_t dphi, deta;
  Float_t d0, dz;
  UInt_t  isConv, nexphits, typeBits;
  LorentzVector *sc=0;
  
  // Data structures to store info from TTrees
  mithep::TEventInfo *info  = new mithep::TEventInfo();
  mithep::TGenInfo   *gen   = new mithep::TGenInfo();
  TClonesArray *electronArr = new TClonesArray("mithep::TElectron");
  TClonesArray *pvArr       = new TClonesArray("mithep::TVertex");
  
  TFile *infile=0;
  TTree *eventTree=0;
  
  //
  // loop over samples
  //  
  for(UInt_t isam=0; isam<samplev.size(); isam++) {
    
    // Assume data sample is first sample in .conf file
    // If sample is empty (i.e. contains no ntuple files), skip to next sample
    if(isam==0 && !hasData) continue;
  
    CSample* samp = samplev[isam];
  
    //
    // Set up output ntuple
    //
    TString outfilename = ntupDir + TString("/") + snamev[isam] + TString("_select.root");
    if(isam==0 && !doScaleCorr) outfilename = ntupDir + TString("/") + snamev[isam] + TString("_select.raw.root");
    TFile *outFile = new TFile(outfilename,"RECREATE"); 
    TTree *outTree = new TTree("Events","Events");

    outTree->Branch("runNum",   &runNum,   "runNum/i");     // event run number
    outTree->Branch("lumiSec",  &lumiSec,  "lumiSec/i");    // event lumi section
    outTree->Branch("evtNum",   &evtNum,   "evtNum/i");     // event number
    outTree->Branch("npv",      &npv,      "npv/i");        // number of primary vertices
    outTree->Branch("npu",      &npu,      "npu/i");        // number of in-time PU events (MC)
    outTree->Branch("genVPt",   &genVPt,   "genVPt/F");     // GEN boson pT (signal MC)
    outTree->Branch("genVPhi",  &genVPhi,  "genVPhi/F");    // GEN boson phi (signal MC)
    outTree->Branch("genVy",    &genVy,    "genVy/F");      // GEN boson rapidity (signal MC)
    outTree->Branch("genVMass", &genVMass, "genVMass/F");   // GEN boson mass (signal MC)
    outTree->Branch("scale1fb", &scale1fb, "scale1fb/F");   // event weight per 1/fb (MC)
    outTree->Branch("met",      &met,      "met/F");        // MET
    outTree->Branch("metPhi",   &metPhi,   "metPhi/F");     // phi(MET)
    outTree->Branch("sumEt",    &sumEt,    "sumEt/F");      // Sum ET
    outTree->Branch("mt",       &mt,       "mt/F");         // transverse mass
    outTree->Branch("u1",       &u1,       "u1/F");         // parallel component of recoil
    outTree->Branch("u2",       &u2,       "u2/F");         // perpendicular component of recoil
    outTree->Branch("q",        &q,        "q/I");          // lepton charge
    outTree->Branch("lep", "ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double> >", &lep);  // lepton 4-vector
    ///// electron specific /////
    outTree->Branch("trkIso",    &trkIso,    "trkIso/F");     // track isolation of tag lepton
    outTree->Branch("emIso",     &emIso,     "emIso/F");      // ECAL isolation of tag lepton
    outTree->Branch("hadIso",    &hadIso,    "hadIso/F");     // HCAL isolation of tag lepton
    outTree->Branch("pfChIso",   &pfChIso,   "pfChIso/F");    // PF charged hadron isolation of lepton
    outTree->Branch("pfGamIso",  &pfGamIso,  "pfGamIso/F");   // PF photon isolation of lepton
    outTree->Branch("pfNeuIso",  &pfNeuIso,  "pfNeuIso/F");   // PF neutral hadron isolation of lepton
    outTree->Branch("pfCombIso", &pfCombIso, "pfCombIso/F");  // PF combined isolation of electron
    outTree->Branch("sigieie",   &sigieie,   "sigieie/F");    // sigma-ieta-ieta of electron
    outTree->Branch("hovere",    &hovere,    "hovere/F");     // H/E of electron
    outTree->Branch("eoverp",    &eoverp,    "eoverp/F");     // E/p of electron
    outTree->Branch("fbrem",     &fbrem,     "fbrem/F");      // brem fraction of electron
    outTree->Branch("dphi",      &dphi,	     "dphi/F");       // GSF track - ECAL dphi of electron
    outTree->Branch("deta",      &deta,      "deta/F");       // GSF track - ECAL deta of electron
    outTree->Branch("ecalE",     &ecalE,     "ecalE/F");      // ECAL energy of electron
    outTree->Branch("d0",        &d0,        "d0/F");         // transverse impact parameter of electron
    outTree->Branch("dz",        &dz,        "dz/F");         // longitudinal impact parameter of electron
    outTree->Branch("isConv",    &isConv,    "isConv/i");     // conversion filter flag of electron
    outTree->Branch("nexphits",  &nexphits,  "nexphits/i");   // number of missing expected inner hits of electron
    outTree->Branch("typeBits",  &typeBits,  "typeBits/i");   // electron type of electron
    outTree->Branch("sc",  "ROOT::Math::LorentzVector<ROOT::Math::PtEtaPhiM4D<double> >", &sc);   // electron Supercluster 4-vector
    
    //
    // loop through files
    //
    const UInt_t nfiles = samp->fnamev.size();
    for(UInt_t ifile=0; ifile<nfiles; ifile++) {  

      // Read input file and get the TTrees
      cout << "Processing " << samp->fnamev[ifile] << " [xsec = " << samp->xsecv[ifile] << " pb] ... "; cout.flush();      
      infile = new TFile(samp->fnamev[ifile]); 
      assert(infile);

      Bool_t hasJSON = kFALSE;
      mithep::RunLumiRangeMap rlrm;
      if(samp->jsonv[ifile].CompareTo("NONE")!=0) { 
        hasJSON = kTRUE;
        rlrm.AddJSONFile(samp->jsonv[ifile].Data()); 
      }
  
      eventTree = (TTree*)infile->Get("Events");
      assert(eventTree);  
      eventTree->SetBranchAddress("Info",     &info);        TBranch *infoBr     = eventTree->GetBranch("Info");
      eventTree->SetBranchAddress("Electron", &electronArr); TBranch *electronBr = eventTree->GetBranch("Electron");
      eventTree->SetBranchAddress("PV",       &pvArr);       TBranch *pvBr       = eventTree->GetBranch("PV");
      Bool_t hasGen = eventTree->GetBranchStatus("Gen");
      TBranch *genBr=0;
      if(hasGen) {
        eventTree->SetBranchAddress("Gen", &gen);
	genBr = eventTree->GetBranch("Gen");
      }
    
      // Compute MC event weight per 1/fb
      Double_t weight = 1;
      const Double_t xsec = samp->xsecv[ifile];
      if(xsec>0) weight = 1000.*xsec/(Double_t)eventTree->GetEntries();     

      //
      // loop over events
      //
      Double_t nsel=0, nselvar=0;
      for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
        infoBr->GetEntry(ientry);
	
	if(genBr) genBr->GetEntry(ientry);
     
        // check for certified lumi (if applicable)
        mithep::RunLumiRangeMap::RunLumiPairType rl(info->runNum, info->lumiSec);      
        if(hasJSON && !rlrm.HasRunLumi(rl)) continue;  

        // trigger requirement               
        ULong64_t trigger = kHLT_Ele22_CaloIdL_CaloIsoVL;
	ULong64_t trigObj = kHLT_Ele22_CaloIdL_CaloIsoVL_EleObj;   
        if(!(info->triggerBits & trigger)) continue;      
      
        // good vertex requirement
        if(!(info->hasGoodPV)) continue;
        pvArr->Clear();
        pvBr->GetEntry(ientry);
      
        //
	// SELECTION PROCEDURE:
	//  (1) Look for 1 good electron matched to trigger
	//  (2) Reject event if another electron is present passing looser cuts
	//
	electronArr->Clear();
        electronBr->GetEntry(ientry);
	Int_t nLooseLep=0;
	const mithep::TElectron *goodEle=0;
	Bool_t passSel=kFALSE;
        for(Int_t i=0; i<electronArr->GetEntriesFast(); i++) {
          const mithep::TElectron *ele = (mithep::TElectron*)((*electronArr)[i]);
	  
	  // check ECAL gap
	  if(fabs(ele->scEta)>=ECAL_GAP_LOW && fabs(ele->scEta)<=ECAL_GAP_HIGH) continue;

	  Double_t escale=1;
	  if(doScaleCorr && isam==0) {
	    for(UInt_t ieta=0; ieta<escaleNbins; ieta++) {
	      if(fabs(ele->scEta)<escaleEta[ieta]) {
	        escale = escaleCorr[ieta];
		break;
	      }
	    }
	  }
	  
          if(fabs(ele->scEta)   > 2.5) continue;                // loose lepton |eta| cut
          if(escale*(ele->scEt) < 20)  continue;                // loose lepton pT cut
//          if(passEleLooseID(ele,info->rhoLowEta)) nLooseLep++;  // loose lepton selection
          if(nLooseLep>1) {  // extra lepton veto
            passSel=kFALSE;
            break;
          }
          
          if(fabs(ele->scEta)   > ETA_CUT)        continue;  // lepton |eta| cut
          if(escale*(ele->scEt) < PT_CUT)         continue;  // lepton pT cut
          if(!passAntiEleID(ele,info->rhoLowEta)) continue;  // lepton anti-selection
          if(!(ele->hltMatchBits & trigObj))      continue;  // check trigger matching
	  
	  passSel=kTRUE;
	  goodEle = ele;  
	}
	
	if(passSel) {
	  
	  /******** We have a W candidate! HURRAY! ********/
	    
	  nsel+=weight;
          nselvar+=weight*weight;

	  Double_t escale=1;
	  if(doScaleCorr && isam==0) {
	    for(UInt_t ieta=0; ieta<escaleNbins; ieta++) {
	      if(fabs(goodEle->scEta)<escaleEta[ieta]) {
	        escale = escaleCorr[ieta];
		break;
	      }
	    }
	  }
	  	  
	  LorentzVector vLep(escale*(goodEle->pt), goodEle->eta, goodEle->phi, ELE_MASS);  
	  LorentzVector vSC(escale*(goodEle->scEt), goodEle->scEta, goodEle->scPhi, ELE_MASS); 	  
	  
	  //
	  // Fill tree
	  //
	  runNum   = info->runNum;
	  lumiSec  = info->lumiSec;
	  evtNum   = info->evtNum;
	  npv	   = pvArr->GetEntriesFast();
	  npu	   = info->nPU;
          genVPt   = 0;
	  genVPhi  = 0;
	  genVy    = 0;
	  genVMass = 0;
	  u1       = 0;
	  u2       = 0;
	  if(hasGen) {
	    genVPt   = gen->vpt;
            genVPhi  = gen->vphi;
	    genVy    = gen->vy;
	    genVMass = gen->vmass;
	    TVector2 vWPt((gen->vpt)*cos(gen->vphi),(gen->vpt)*sin(gen->vphi));
	    TVector2 vLepPt(vLep.Px(),vLep.Py());      
            TVector2 vMet((info->pfMET)*cos(info->pfMETphi), (info->pfMET)*sin(info->pfMETphi));        
            TVector2 vU = -1.0*(vMet+vLepPt);
            u1 = ((vWPt.Px())*(vU.Px()) + (vWPt.Py())*(vU.Py()))/(gen->vpt);  // u1 = (pT . u)/|pT|
            u2 = ((vWPt.Px())*(vU.Py()) - (vWPt.Py())*(vU.Px()))/(gen->vpt);  // u2 = (pT x u)/|pT|
	  }
	  scale1fb = weight;
	  met	   = info->pfMET;
	  metPhi   = info->pfMETphi;
	  sumEt    = info->pfSumET;
	  mt       = sqrt( 2.0 * (vLep.Pt()) * (info->pfMET) * (1.0-cos(toolbox::deltaPhi(vLep.Phi(),info->pfMETphi))) );
	  q        = goodEle->q;	  
	  lep      = &vLep;	  
	  
	  ///// electron specific /////
	  sc	    = &vSC;
	  trkIso    = goodEle->trkIso03;
	  emIso     = goodEle->emIso03;
	  hadIso    = goodEle->hadIso03;
	  pfChIso   = goodEle->pfChIso03;
	  pfGamIso  = goodEle->pfGamIso03;
	  pfNeuIso  = goodEle->pfNeuIso03;	
	  pfCombIso = goodEle->pfChIso03 + TMath::Max(goodEle->pfNeuIso03 + goodEle->pfGamIso03 - (info->rhoLowEta)*getEffArea(goodEle->scEta), 0.);
	  sigieie   = goodEle->sigiEtaiEta;
	  hovere    = goodEle->HoverE;
	  eoverp    = goodEle->EoverP;
	  fbrem     = goodEle->fBrem;
	  dphi      = goodEle->deltaPhiIn;
	  deta      = goodEle->deltaEtaIn;
	  d0        = goodEle->d0;
	  dz        = goodEle->dz;
	  isConv    = goodEle->isConv;
	  nexphits  = goodEle->nExpHitsInner;
	  typeBits  = goodEle->typeBits;
	   
	  outTree->Fill();
        }
      }
      delete infile;
      infile=0, eventTree=0;    

      cout << nsel  << " +/- " << sqrt(nselvar);
      if(isam!=0) cout << " per 1/fb";
      cout << endl;
    }
    outFile->Write();
    outFile->Close();
  }
  delete info;
  delete gen;
  delete electronArr;
  delete pvArr;
  
    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  cout << " W -> e nu" << endl;
  cout << "  pT > " << PT_CUT << endl;
  cout << "  |eta| < " << ETA_CUT << endl;
  if(doScaleCorr)
    cout << "  *** Scale corrections applied ***" << endl;
  cout << endl;

  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;  
      
  gBenchmark->Show("selectAntiWe"); 
}
Example #11
0
void makeVNDet(){

  bool testrun          = 0;
  const int norder_     = 2;
  const double vtxCut   = 15.;

  static const int ptBinMin  = 0;
  static const int ptBinMax  = nptbinsDefault-1;
  static const int etaBinMin = 0;  //0;
  static const int etaBinMax = netabinsDefault-1;

  TFile * fAna;
  TTree * tree;
  double centval;
  double vtx;
  TH2D * sumw;
  TH2D * sumwqx;
  TH2D * sumwqy;
  TH2I * hMult;

  TFile * fSplit;
  TTree * treeSplit;
  int iSplit;

  TFile * fOut;

  TH1D * hVNDetX_0[NSPLIT];
  TH1D * hVNDetY_0[NSPLIT];
  TH1D * hVNDetX_1[NSPLIT];
  TH1D * hVNDetY_1[NSPLIT];
  TH1D * hVNDetX_full[NSPLIT];
  TH1D * hVNDetY_full[NSPLIT];

  double VNDetX_0[NCENT][NSPLIT];
  double VNDetY_0[NCENT][NSPLIT];
  double VNDetX_1[NCENT][NSPLIT];
  double VNDetY_1[NCENT][NSPLIT];
  double VNDetX_full[NCENT][NSPLIT];
  double VNDetY_full[NCENT][NSPLIT];

  int Nevents[NCENT][NSPLIT];
  int NFails[NCENT][NSPLIT];

  //
  // MAIN
  //


  //-- Set up the analyzer objects
  fAna = new TFile("/rfs/jcastle/PbPb2015/PixelTracking_MB2/EbyETree_pixel_noTeff.root");

  tree = (TTree*) fAna->Get("ebyeana/tree");
  sumwqx = new TH2D(Form("sumwqx%i", norder_), Form("sumwqx%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumwqy = new TH2D(Form("sumwqy%i", norder_), Form("sumwqy%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumw   = new TH2D("sumw",                    "sumw",                    nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  hMult  = new TH2I("hMult",                   "hMult",                   nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
    
  tree->SetBranchAddress("Cent",                    &centval);
  tree->SetBranchAddress("Vtx",                     &vtx);
  tree->SetBranchAddress("mult",                    &hMult);
  tree->SetBranchAddress(Form("sumwqx%i", norder_), &sumwqx);
  tree->SetBranchAddress(Form("sumwqy%i", norder_), &sumwqy);
  tree->SetBranchAddress("sumw",                    &sumw);

  //-- Set up the file splitter
  fSplit = new TFile(fileSplit);
  treeSplit = (TTree*) fSplit->Get("SplitTree");
  treeSplit->SetBranchAddress("iSplit", &iSplit);

  //-- Setup the output objects
  fOut     = new TFile( Form("V%iDet.root", norder_), "recreate" );
  for(int iS = 0; iS < NSPLIT; iS++){
    fOut->cd();
    hVNDetX_0[iS]    = new TH1D( Form("hVNDetX_0_Split%i", iS),    Form("hVNDetX_0_Split%i", iS),    NCENT, centbinsDefault);
    hVNDetX_0[iS]->GetXaxis()->SetTitle("Centrality %");
    
    hVNDetY_0[iS]    = new TH1D( Form("hVNDetY_0_Split%i", iS),    Form("hVNDetY_0_Split%i", iS),    NCENT, centbinsDefault);
    hVNDetY_0[iS]->GetXaxis()->SetTitle("Centrality %");
    
    hVNDetX_1[iS]    = new TH1D( Form("hVNDetX_1_Split%i", iS),    Form("hVNDetX_1_Split%i", iS),    NCENT, centbinsDefault);
    hVNDetX_1[iS]->GetXaxis()->SetTitle("Centrality %");
    
    hVNDetY_1[iS]    = new TH1D( Form("hVNDetY_1_Split%i", iS),    Form("hVNDetY_1_Split%i", iS),    NCENT, centbinsDefault);
    hVNDetY_1[iS]->GetXaxis()->SetTitle("Centrality %");
    
    hVNDetX_full[iS] = new TH1D( Form("hVNDetX_full_Split%i", iS), Form("hVNDetX_full_Split%i", iS), NCENT, centbinsDefault);
    hVNDetX_full[iS]->GetXaxis()->SetTitle("Centrality %");
    
    hVNDetY_full[iS] = new TH1D( Form("hVNDetY_full_Split%i", iS), Form("hVNDetY_full_Split%i", iS), NCENT, centbinsDefault);
    hVNDetY_full[iS]->GetXaxis()->SetTitle("Centrality %");
  }    

  //-- initialize all variables
  for(int icent = 0; icent<NCENT; icent++){
    for(int iS = 0; iS < NSPLIT; iS++){

      VNDetX_0[icent][iS]     = 0.;
      VNDetY_0[icent][iS]     = 0.;
      VNDetX_1[icent][iS]     = 0.;
      VNDetY_1[icent][iS]     = 0.;
      VNDetX_full[icent][iS]  = 0.;
      VNDetY_full[icent][iS]  = 0.;

      Nevents[icent][iS]      = 0;
      NFails[icent][iS]       = 0;

    }
  }
    
  //
  // Calculate Vn_det
  //
    
  cout<<"Begin DETECTOR loop, contains "<<tree->GetEntries()<<" Events"<<endl;
    
  int N;
  if(testrun) N = 10000; 
  else        N = tree->GetEntries();

  //-- Begin event loop
  for(int ievent = 0; ievent < N; ievent++) {
        
    if((ievent+1)% 500000 == 0) cout << "Processing Event " << ievent+1 << "\t" << (100.*(ievent+1)/N) << "% Completed" << endl;
        
    int itree = tree->GetEntry(ievent);
    if(itree < 0){
      std::cout<<"!!! BAD EVENT !!!"<<std::endl;
      continue;
    }

    treeSplit->GetEntry(ievent);

    //-- Vertex Cut
    if(TMath::Abs(vtx) > vtxCut) continue;
      
    //-- Calculate centbin
    if( centval > cent_max[NCENT-1]) continue;
    int icent = (centval - cent_min[0]) / centBinWidth;

    //-- Reset Raw and sumw values
    double VNRawX_0     = 0.;
    double VNRawY_0     = 0.;
    double VNRawX_1     = 0.;
    double VNRawY_1     = 0.;
    double VNRawX_full  = 0.;
    double VNRawY_full  = 0.;            
	
    double sumw_0       = 0.;
    double sumw_1       = 0.;
    double sumw_full    = 0.;
      
    double evtMult_0    = 0;
    double evtMult_1    = 0;
    double evtMult_full = 0;
      
    Nevents[icent][iSplit]++;

    //-- Begin analyzer histogram loops
    for(int ipt = ptBinMin; ipt <= ptBinMax; ipt++){
      for(int ieta = etaBinMin; ieta <= etaBinMax; ieta++){
	  
	if(sumw->GetBinContent(ipt+1,ieta+1) !=0){
	    
	  //-- Subevent 0 (eta >= 0)
	  if(etabinsDefault[ieta] >= 0){
	    VNRawX_0   += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VNRawY_0   += sumwqy->GetBinContent(ipt+1,ieta+1);
	      
	    sumw_0     += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_0  += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  //-- Subevent 1 (eta < 0)
	  else{
	    VNRawX_1   += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VNRawY_1   += sumwqy->GetBinContent(ipt+1,ieta+1);
	      
	    sumw_1     += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_1  += hMult->GetBinContent(ipt+1,ieta+1);
	  }
	  //-- Full Event
	  VNRawX_full  += sumwqx->GetBinContent(ipt+1,ieta+1);
	  VNRawY_full  += sumwqy->GetBinContent(ipt+1,ieta+1);
	    
	  sumw_full    += sumw->GetBinContent(ipt+1,ieta+1);
	  evtMult_full += hMult->GetBinContent(ipt+1,ieta+1);
	}
	  
      } //-- End eta loop
      
    } //-- End pt loop
    
    //-- Only use events that have tracks in all subevents AND subevents that have at least two tracks to determine VN
    if( sumw_0 == 0 || sumw_1 == 0 || evtMult_0 < 2 || evtMult_1 < 2 ){
	NFails[icent][iSplit]++;
    }
    else{      
      VNDetX_0[icent][iSplit]    += VNRawX_0    / sumw_0;
      VNDetY_0[icent][iSplit]    += VNRawY_0    / sumw_0;
      VNDetX_1[icent][iSplit]    += VNRawX_1    / sumw_1;
      VNDetY_1[icent][iSplit]    += VNRawY_1    / sumw_1;
      VNDetX_full[icent][iSplit] += VNRawX_full / sumw_full;
      VNDetY_full[icent][iSplit] += VNRawY_full / sumw_full;
    }

  } //-- End event loop
    
  std::cout<<"End DETECTOR loop"<<std::endl;

  //-- Average VNDet over all events for each centrality, EP and, qn bin
  for(int icent = 0; icent < NCENT; icent++){
    for(int iS = 0; iS < NSPLIT; iS++){
   
      double  Neffective = (double) Nevents[icent][iS] - (double) NFails[icent][iS];
      if( Neffective == 0 ) continue;
    
      VNDetX_0[icent][iS]    /= Neffective;
      VNDetY_0[icent][iS]    /= Neffective;
      VNDetX_1[icent][iS]    /= Neffective;
      VNDetY_1[icent][iS]    /= Neffective;
      VNDetX_full[icent][iS] /= Neffective;
      VNDetY_full[icent][iS] /= Neffective;

      //-- Populate histograms that will be used by ReadTree_normDet.C
      hVNDetX_0[iS]    -> SetBinContent(icent+1, VNDetX_0[icent][iS]);
      hVNDetX_1[iS]    -> SetBinContent(icent+1, VNDetX_1[icent][iS]);
      hVNDetX_full[iS] -> SetBinContent(icent+1, VNDetX_full[icent][iS]);
      
      hVNDetY_0[iS]    -> SetBinContent(icent+1, VNDetY_0[icent][iS]);
      hVNDetY_1[iS]    -> SetBinContent(icent+1, VNDetY_1[icent][iS]);
      hVNDetY_full[iS] -> SetBinContent(icent+1, VNDetY_full[icent][iS]);

    }
  }
  fOut->Write();
  cout<<"File written, process completed"<<endl;

}
void ztree::ffgammajet(std::string outfname, int centmin, int centmax, float phoetmin, float phoetmax, std::string gen)
{
  string tag = outfname;
  string s_alpha = gen;
  if (fChain == 0) return;
  Long64_t nentries = fChain->GetEntriesFast();
  TFile * fout = new TFile(Form("%s_%s_%s_%d_%d.root",outfname.data(),tag.data(),s_alpha.data(),abs(centmin),abs(centmax)),"recreate");

  TH2D * hsubept = new TH2D(Form("hsubept_%s_%s_%d_%d",tag.data(),s_alpha.data(),abs(centmin),abs(centmax)),Form(";#xi=ln(1/z);"),100,-0.5,99.5,100,0,100);
  TH2D * hsubept_refcone = new TH2D(Form("hsubept_refcone_%s_%s_%d_%d",tag.data(),s_alpha.data(),abs(centmin),abs(centmax)),Form(";#xi=ln(1/z);"),100,-0.5,99.5,100,0,100);

  TH1D * hjetpt = new TH1D(Form("hjetpt_%s_%s_%d_%d",tag.data(),s_alpha.data(),abs(centmin),abs(centmax)),Form(";jet p_{T};"),20,0,500);
  TH1D * hjetgendphi = new TH1D(Form("hjetgendphi_%s_%s_%d_%d",tag.data(),s_alpha.data(),abs(centmin),abs(centmax)),Form(";#DeltaR_{gen,reco};"),20,0,0.1);
  TH1D * hgammaff = new TH1D(Form("hgammaff_%s_%s_%d_%d",tag.data(),s_alpha.data(),abs(centmin),abs(centmax)),Form(";z;"),20,0,1);
  TH1D * hgammaffxi = new TH1D(Form("hgammaffxi_%s_%s_%d_%d",tag.data(),s_alpha.data(),abs(centmin),abs(centmax)),Form(";#xi=ln(1/z);"),10,0,5);
  TH1D * hgammaffxi_refcone = new TH1D(Form("hgammaffxi_refcone_%s_%s_%d_%d",tag.data(),s_alpha.data(),abs(centmin),abs(centmax)),Form(";#xi=ln(1/z);"),10,0,5);
  TH1D * hgammaphoffxi = new TH1D(Form("hgammaphoffxi_%s_%s_%d_%d",tag.data(),s_alpha.data(),abs(centmin),abs(centmax)),Form(";#xi=ln(1/z);"),10,0,5);
  TH1D * hgammaphoffxi_refcone = new TH1D(Form("hgammaphoffxi_refcone_%s_%s_%d_%d",tag.data(),s_alpha.data(),abs(centmin),abs(centmax)),Form(";#xi=ln(1/z);"),10,0,5);
  Long64_t nbytes = 0, nb = 0;
  cout<<phoetmin<<" "<<phoetmax<<endl;
  for (Long64_t jentry=0; jentry<nentries;jentry++) {
    if(jentry%10000==0) { cout<<jentry<<"/"<<nentries<<endl; }
    Long64_t ientry = LoadTree(jentry);
    if (ientry < 0) break;
    // cout<<njet<<endl;
    // if(jentry > 10000) break;
    nb = fChain->GetEntry(jentry);   nbytes += nb;
    if(hiBin < centmin || hiBin >= centmax) continue; //centrality cut
    if(nPho!=1) continue;
    if(gen.compare("gen")==0)
    {
      if(mcEt[pho_genMatchedIndex[0]]<phoetmin || mcEt[pho_genMatchedIndex[0]]>phoetmax) continue;
    }
    else
    {
      if(phoEt[0]*phoCorr[0]<phoetmin || phoEt[0]*phoCorr[0]>phoetmax) continue;
    }
    if(weight==0)                   weight=1;
    // cout<<njet<<endl;

    if(gen.compare("gen")==0)
    {
      for (int ijet = 0; ijet < njet; ijet++) {
        if( nPho==2 ) continue;
        if( jetpt[ijet]<40 ) continue; //jet pt Cut
        if( fabs(jeteta[ijet]) > 1.6) continue; //jeteta Cut
        if( fabs(jeteta[ijet]) < 0.3) continue; //jeteta Cut for reflected cone
        if( jetID[ijet]==0 ) continue; //redundant in this skim (all true)
        if( acos(cos(jetphi[ijet] - phoPhi[0])) < 7 * pi / 8 ) continue;
        hjetpt->Fill(jetpt[ijet]);
        float denrecodphi = acos(cos(jetphi[ijet] - gjetphi[ijet]));
        hjetgendphi->Fill(denrecodphi);
        for(int igen = 0 ; igen < mult ; ++igen)
        {
          if(!(abs(pdg[igen])==11 || abs(pdg[igen])==13 || abs(pdg[igen])==211 || abs(pdg[igen])==2212 || abs(pdg[igen])==321)) continue;
          if(sube[igen] != 0) continue;
          float dr = genjettrk_dr(igen,ijet);
          float dr_refcone = genrefconetrk_dr(igen,ijet);
          if(dr<0.3)
          {
            float z = pt[igen]/gjetpt[ijet];
            float zpho = pt[igen]/phoEt[0];
            float xi = log(1.0/z);
            float xipho = log(1.0/zpho);

            hgammaff->Fill(z);
            hgammaffxi->Fill(xi);
            hgammaphoffxi->Fill(xipho);
            hsubept->Fill(sube[igen],pt[igen]);
            // cout<<jetpt[ijet]<<endl;
          }
          if(dr_refcone<0.3)
          {
            float z = pt[igen]/gjetpt[ijet];
            float zpho = pt[igen]/phoEt[0];
            float xi = log(1.0/z);
            float xipho = log(1.0/zpho);

            hgammaffxi_refcone->Fill(xi);
            hgammaphoffxi_refcone->Fill(xipho);
            hsubept_refcone->Fill(sube[igen],pt[igen]);
          }
        }
      }
    }
    else
    {
      for (int ijet = 0; ijet < njet; ijet++) {
        if( nPho==2 ) continue;
        if( jetpt[ijet]<40 ) continue; //jet pt Cut
        if( fabs(jeteta[ijet]) > 1.6) continue; //jeteta Cut
        if( fabs(jeteta[ijet]) < 0.3) continue; //jeteta Cut for reflected cone
        if( jetID[ijet]==0 ) continue; //redundant in this skim (all true)
        if( acos(cos(jetphi[ijet] - phoPhi[0])) < 7 * pi / 8 ) continue;
        hjetpt->Fill(jetpt[ijet]);

        for (int itrk = 0; itrk < nTrk; itrk++) {
          float dr = jettrk_dr(itrk,ijet);
          // float dr = genjetrecotrk_dr(itrk,ijet);
          float dr_refcone = refconetrk_dr(itrk,ijet);
          // float dr_refcone = genrefconerecotrk_dr(itrk,ijet);
          if(dr<0.3)
          {
            float z = trkPt[itrk]/jetpt[ijet];
            float zpho = trkPt[itrk]/phoEt[0];
            float xi = log(1.0/z);
            float xipho = log(1.0/zpho);

            hgammaff->Fill(z,trkWeight[itrk]);
            hgammaffxi->Fill(xi,trkWeight[itrk]);
            hgammaphoffxi->Fill(xipho,trkWeight[itrk]);
            // hgammaff->Fill(z);
            // hgammaffxi->Fill(xi);
            // hgammaphoffxi->Fill(xipho);
            // cout<<jetpt[ijet]<<endl;
          }
          if(dr_refcone<0.3)
          {
            float z = trkPt[itrk]/jetpt[ijet];
            float zpho = trkPt[itrk]/phoEt[0];
            float xi = log(1.0/z);
            float xipho = log(1.0/zpho);

            hgammaffxi_refcone->Fill(xi,trkWeight[itrk]);
            hgammaphoffxi_refcone->Fill(xipho,trkWeight[itrk]);
            // hgammaffxi_refcone->Fill(xi);
            // hgammaphoffxi_refcone->Fill(xipho);
          }
        }
        // photons: normal mode power mode
        // pho 40 trigger
        // photon spike cuts etc
        // phoet > 35
        // phoet > 40 after correction // haven't made it yet
        // phoeta < 1.44
        // sumiso < 1 GeV
        // h/em < 0.1
        // sigmaetaeta < 0.01

        // jets:
        // some pt
        // jeteta < 1.6
        // some id cuts // none yet but we'll add some
        // ak3pupf jets

        // delphi > 7 pi / 8


      }
    }


  }

  fout->Write();
  fout->Close();
}
Example #13
0
int main(int argc, char*argv[])
{
 gSystem->Load("libDelphes");
 gSystem->Load("libExRootAnalysis");
 //arg
 string inputFile=argv[1];
 string outputFile=argv[2];
 TFile *out = TFile::Open(outputFile.c_str(),"RECREATE");
 // Create chain of root trees
 TChain chain("Delphes");
 chain.Add(inputFile.c_str());

 // Create object of class ExRootTreeReader
 ExRootTreeReader *treeReader = new ExRootTreeReader(&chain);
 Long64_t numberOfEntries = treeReader->GetEntries();

 // Get pointers to branches used in this analysis
 TClonesArray *branchJet  = treeReader->UseBranch("Jet");
 TClonesArray *branchGenJet = treeReader->UseBranch("GenJet");
 TClonesArray *scalarht = treeReader->UseBranch("ScalarHT");

 /////////////////////////////
 //Histograms/////////////////
 /////////////////////////////

 TH2 *hist_deltaY_60_100 = new TH2F("hist_deltaY_60_100","hist_deltaY_60_100",500,-5.0,5.0,500,-0.2,0.2);
 TH2 *hist_deltaY_100_150 = new TH2F("hist_deltaY_100_150","hist_deltaY_100_150",500,-5.0,5.0,500,-0.2,0.2);
 TH2 *hist_deltaY_150_200 = new TH2F("hist_deltaY_150_200","hist_deltaY_150_200",500,-5.0,5.0,500,-0.2,0.2);

 TH1 *histevent60100 = new TH1F("histevent60100","histevent60100",500,-0.5,0.5);
 TH1 *histevent100150 = new TH1F("histevent100150","histevent60100",500,-0.5,0.5);
 TH1 *histevent150200 = new TH1F("histevent150200","histevent60100",500,-0.5,0.5);

 TH1 *hist_PT_resolution = new TH1F("hist_PT_resolution","hist_PT_resolution",500,-1.0,1);

 TH2 *hist_PT_resolution_for_each[3];
 hist_PT_resolution_for_each[0] = new TH2F("hist_leading_pt_res","hist_PT_resolution_for_each",500,0.0,4000,500,-1.0,1.0);
 hist_PT_resolution_for_each[1] = new TH2F("hist_nleading_pt_res","hist_PT_resolution_for_each",500,0.0,4000,500,-1.0,1.0);
 hist_PT_resolution_for_each[2] = new TH2F("hist_nnleading_pt_res","hist_PT_resolution_for_each",500,0.0,4000,500,-1.0,1.0);

 TH1 *histleadingcolojetpt = new TH1F("leadingcolojetpt", "leadingcolojetpt", 50, 0.0, 400.0);
 TH1 *histnleadingcolojetpt = new TH1F("nleadingcolojetpt", "nleadingcolojetpt", 50, 0.0, 400.0);
 TH1 *histnnleadingcolojetpt = new TH1F("nnleadingcolojetpt", "nnleadingcolojetpt", 50, 0.0, 400.0);

 TH1 *histcolojetht = new TH1F("histcolojetht","histcolojetht",1000, 0.0, 10000.0);




 TH2 *histresleadingjet = new TH2F("histresleadingjet","histresleadingjet",500,0.0,4000,500,-1.0,1.0);
 TH2 *histres2leadingjet = new TH2F("histres2leadingjet","histresleadingjet",500,0.0,4000,500,-1.0,1.0);
 TH2 *histres3leadingjet = new TH2F("histres3leadingjet","histresleadingjet",500,0.0,2500,500,-1.0,1.0);

 TH1 *histcolo2jetht = new TH1F("histcolo2jetht",">2jet ht",500,0.0,10000.0);
 TH1 *histcolo3jetht = new TH1F("histcolo3jetht",">3jet ht",500,0.0,10000.0);

 TH1 *histgen2jetht = new TH1F("histgen2jetht",">2jet ht",500,0.0,10000.0);
 TH1 *histgen3jetht = new TH1F("histgen3jetht",">3jet ht",500,0.0,10000.0);

  //Definition
 vector<Jet *> colojet;
 vector<Jet *> genjet;

 ScalarHT* scht=0;
 Jet *cjet;
 Jet *gjet;

 int nocolojet = 0;
 //double ptrescut = 0;


  for(int entry = 0; entry < numberOfEntries; ++entry)
  {
     //her 10000 olayda bıze bılgı verıyor
     if(entry%10000 == 0) cout << "event number: " << entry << endl;
     // Load selected branches with data from specified event
     treeReader->ReadEntry(entry);

     //////////////////////////////////////
     ///Scalerht yı scht ye dolduruyor.////
     //////////////////////////////////////

     for(int i =0 ;i<scalarht->GetEntriesFast();++i )
     {
       scht =(ScalarHT*) scalarht->At(i);
     }

     ///////////////////////////////////////////////
     ////genjet bilgilerini alıyor//////////////////
     ///////////////////////////////////////////////

     genjet.clear();
     for(int i=0;i < branchGenJet->GetEntriesFast();++i)
     {
       gjet = (Jet*) branchGenJet->At(i);
       genjet.push_back(gjet);
     }

     //////////////////////////////////////////////
     ///colojet bilgilerini alıyor ////////////////
     //////////////////////////////////////////////

     colojet.clear();
     for(int i=0;i < branchJet->GetEntriesFast(); ++i)
     {
      cjet = (Jet*) branchJet->At(i);
      colojet.push_back(cjet);
     }

     /////////////////////////////////////////////
     /////// delta(y) for (60 - (100) - (150) - 250)///////////
     /////////////////////////////////////////////

     double ptbins=0;
     if(genjet.size()==colojet.size())
     {

       for(unsigned i = 0; i< genjet.size();++i)
       {
         ptbins=genjet[i]->PT;
         if( ptbins > 60 && ptbins < 100)
         {
           hist_deltaY_60_100->Fill(genjet[i]->Eta,genjet[i]->Eta - colojet[i]->Eta);
           histevent60100->Fill(genjet[i]->Eta - colojet[i]->Eta);
         }
         if(ptbins > 100 && ptbins < 150)
         {
           hist_deltaY_100_150->Fill(genjet[i]->Eta,genjet[i]->Eta - colojet[i]->Eta);
           histevent100150->Fill(genjet[i]->Eta - colojet[i]->Eta);
         }
         if(ptbins > 150 && ptbins < 200)
         {
           hist_deltaY_150_200->Fill(genjet[i]->Eta,genjet[i]->Eta - colojet[i]->Eta);
           histevent150200->Fill(genjet[i]->Eta - colojet[i]->Eta);
         }
       }
     }



     //////////////////////////////////////////////////////////////////////
     //R parametresi buluyor ve pt resolution yapıyor//////////////////////
     //////////////////////////////////////////////////////////////////////

     double r =0;
     double pt_res_cut=0;
     if(genjet.size()> 1 && colojet.size()>1)
     {
       for(unsigned i = 0; i<3;i++)
       {
         if(abs(genjet[i]->Eta) <= 2.5 && abs(colojet[i]->Eta) <= 2.5)
         {
           double deltaPhi = abs(genjet[i]->Phi - colojet[i]->Phi);
           double deltaEta = abs(genjet[i]->Eta - colojet[i]->Eta);
           r = sqrt( pow(deltaPhi,2) + pow(deltaEta,2));
            if(r<0.25)
            {
             pt_res_cut = ((genjet[i]->PT - colojet[i]->PT) / (genjet[i]->PT));
            }
           hist_PT_resolution->Fill(pt_res_cut);
           hist_PT_resolution_for_each[i]->Fill(genjet[i]->PT,pt_res_cut);
          }
        }
      }

     ///////////////////////////////////
     ////jet > 2  ve jet > 3 için HT////
     ///////////////////////////////////

     int genjetsay=0;
     double genjetht2=0;
     double genjetht3=0;
     if(genjet.size() >= 2)
     {
       if(r<2.5)
       {
       for(unsigned i = 0; i<genjet.size();++i)
       {
         if(genjet[i]->PT > 50 && abs( genjet[i]->Eta ) <= 2.5)
         {
           genjetsay++;
         }
       }
      }
     }

     if(genjetsay>=2)
     {
       for(unsigned i =0;i<genjet.size();++i)
       {
         genjetht2=genjetht2+genjet[i]->PT;
       }
     }
     if(genjetsay>=3)
     {
       for(unsigned i = 0;i<genjet.size();++i)
       {
         genjetht3=genjetht3+genjet[i]->PT;
       }
     }
     histgen2jetht->Fill(genjetht2);
     histgen3jetht->Fill(genjetht3);

     ///////////////////////////////////
     ///R32 Colo ///////////////////////
     ///////////////////////////////////
     int say=0;
     for(unsigned i=0; i < colojet.size() ; i++)
     {
       if(colojet[i]->PT >= 50.0 && abs( colojet[i]->Eta ) <= 2.5)
       {
         say++;
       }
     }

     if( say >= 2 )
     {
       histcolo2jetht->Fill(scht->HT);
     }
     if( say >= 3 )
     {
       histcolo3jetht->Fill(scht->HT);
     }



     if(colojet.size()<1)
     {
       nocolojet=nocolojet+1;
     }
     else
     {
       double colojetht=0;
       for(unsigned i = 0 ; i < colojet.size();++i)
       {
         colojetht=colojetht+colojet[i]->PT;
       }
       histcolojetht->Fill(colojetht);
     }
     if(colojet.size()==1)
     {
       histleadingcolojetpt->Fill(colojet[0]->PT);
     }
     if(colojet.size()==2)
     {
       histnleadingcolojetpt->Fill(colojet[1]->PT);
     }
     if(colojet.size()==3)
     {
       histnnleadingcolojetpt->Fill(colojet[2]->PT);
     }
     //////////////

     if(genjet.size()>0 && colojet.size()>0)
     {
       if(abs(genjet[0]->Eta)<=2.5 ){
       histresleadingjet->Fill(genjet[0]->PT,((genjet[0]->PT - colojet[0]->PT)/genjet[0]->PT));
       }

     }
     if(genjet.size()>1 && colojet.size()>1)
     {
       if(abs(genjet[1]->Eta)<=2.5 ){
       histres2leadingjet->Fill(genjet[1]->PT,((genjet[1]->PT - colojet[1]->PT)/genjet[1]->PT));
       }
     }
     if(genjet.size()>2 && colojet.size()>2)
     {
       if(abs(genjet[2]->Eta)<=2.5 ){
       histres3leadingjet->Fill(genjet[2]->PT,((genjet[2]->PT - colojet[2]->PT)/genjet[2]->PT));
     }
     }

  }
  out->Write();
  out->Close();

 }
int main(int argc, char* argv[]) {
    
  if (argc != 3) {
    cout << "Usage: " << argv[0] << " runcard  rootfile" << endl;
    return 2;
  }
  char* runcard  = argv[1];
  char* rootfile = argv[2];
  const char* xmlDB    = "/global/u1/l/liwei/minepythia/PYTHIA/pythia8135/xmldoc";
    
  //--------------------------------------------------------------
  //  Initialization
  //--------------------------------------------------------------
    
  //
  //  ROOT
  //
  TFile *hfile  = new TFile(rootfile,"RECREATE");
  TTree tree("tree","b->e c->e and b->c->e decays pp at 500 GeV");
  tree.Branch("hf2eDecay",&hf2eDecay.Event_id,
	      "Event_id/I:refMult/I:numberofcElectrons/I:numberofbElectrons/I:numberofbcElectrons/I:numberofHadrons/I:noTracks/I:"
	      "ce_id[3]/I:ce_status[3]/I:ce_pt[3]/F:ce_pz[3]/F:ce_phi[3]/F:ce_eta[3]/F:ce_y[3]/F:"
	      "be_id[3]/I:be_status[3]/I:be_pt[3]/F:be_pz[3]/F:be_phi[3]/F:be_eta[3]/F:be_y[3]/F:"
	      "bce_id[3]/I:bce_status[3]/I:bce_pt[3]/F:bce_pz[3]/F:bce_phi[3]/F:bce_eta[3]/F:bce_y[3]/F:"
	      "hadron_id[800]/I:hadron_status[800]/I:hadron_pt[800]/F:hadron_pz[800]/F:hadron_phi[800]/F:hadron_eta[800]/F:hadron_y[800]/F");
  //  Create instance of Pythia 
  //
  Pythia pythia(xmlDB); // the init parameters are read from xml files
  // stored in the xmldoc directory. This includes
  // particle data and decay definitions.
    
  //
  // Shorthand for (static) settings
  //
  Settings& settings = pythia.settings;
    
  //
  //  Read in runcard
  //
  pythia.readFile(runcard);  
  cout << "Runcard '" << runcard << "' loaded." << endl;
    
  //
  //  Retrieve number of events and other parameters from the runcard.
  //  We need to deal with those settings ourself. Getting
  //  them through the runcard just avoids recompiling.
  //
  int  maxNumberOfEvents = settings.mode("Main:numberOfEvents");
  int  nList     = settings.mode("Main:numberToList");
  int  nShow     = settings.mode("Main:timesToShow");
  int  maxErrors = settings.mode("Main:timesAllowErrors");
  bool showCS    = settings.flag("Main:showChangedSettings");
  bool showAS    = settings.flag("Main:showAllSettings");
  int  pace = maxNumberOfEvents/nShow;
	
  //
  //  Remark: in this example we do NOT alter the
  //  BRs since they are different for the various charm
  //  hadrons making the normalization at the end rather
  //  cumbersome. In a production version this is what
  //  one probably would implement to save processing time.
  //
    
  //
  //  Initialize Pythia, ready to go
  //
  pythia.init();
    
  //
  // List changed or all data
  //
  if (showCS) settings.listChanged();
  if (showAS) settings.listAll();
    
  //--------------------------------------------------------------
  //  Event loop
  //--------------------------------------------------------------
  int ievent = 0;
  int numberOfElectrons = 0;
  int iErrors = 0;
  while (ievent < maxNumberOfEvents) {
        
    if (!pythia.next()) {
      if (++iErrors < maxErrors) continue;
      cout << "Error: too many errors in event generation - check your settings & code" << endl;
      break;
    }

    Event &event = pythia.event;
    int eventId=ievent+maxNumberOfEvents;
    hf2eDecay.Event_id   = eventId;
    //    if(!event){ cout << " Error : No Event" << endl;return 0; }           //how to ignore wrong event------------------
    //    int nelectrons = 0;
    int total_tracks = 0;
    int ic =0;
    int e_number=0;
    int nce=0,nbe=0,nbce=0;
    int hadron_number=0;
    int nh=0;
    //----------------------------------------------------------------------------------------------------------------------------------------------------------------
    for (int i = 0; i < event.size(); i++) {                                      //event.size means total track number
      //       if(abs(event[i].id())>100)
      if(event[i].isHadron()&&event[i].isFinal())                     //select hadron
	{
	  hf2eDecay.hadron_id[nh] = event[i].id();
	  hf2eDecay.hadron_status[nh] = event[i].status();
	  hf2eDecay.hadron_pt[nh] = event[i].pT();
	  hf2eDecay.hadron_pz[nh] = event[i].pz();
	  hf2eDecay.hadron_phi[nh] = event[i].phi();
	  hf2eDecay.hadron_eta[nh] = event[i].eta();
	  hf2eDecay.hadron_y[nh] = event[i].y();

	  nh++;
	}
      if (abs(event[i].id()) == 11) {

	//
	//  Check if mother is a c/b hadron
	//
	vector<int> mothers = event.motherList(i);
	if (mothers.size() != 1) {
	  cout << "Error: electron has more than one mother. Stop." << endl;
	  //abort();
	  //  return 0;
	  continue;
	}
	ic = mothers[0];
	int ic_id = abs(event[ic].id());
	int flavor = static_cast<int>(ic_id/pow(10.,static_cast<int>(log10(ic_id)))); //this will miss excited states like D0*
	//          if (flavor != 4 && flavor != 5) continue; // c (b) hadrons start with 4(5)  
	if (flavor != 4 && flavor != 5) continue;
	//  Acceptance filter
	//            if (!(isInAcceptance(i, event))) continue;                    //--------------------------------------------------------------
	if(flavor == 4)
	  {
            vector<int> grandmothers = event.motherList(ic);
	    /*            if(grandmothers.size()==0)
			  {   hf2eDecay.ce_id[nce] = event[i].id();
			  hf2eDecay.ce_status[nce] = event[i].status();
			  hf2eDecay.ce_pt[nce] = event[i].pT();
			  hf2eDecay.ce_pz[nce] = event[i].pz();
			  hf2eDecay.ce_phi[nce] = event[i].phi();
			  hf2eDecay.ce_eta[nce] = event[i].eta();
			  hf2eDecay.ce_y[nce] = event[i].y();
			  nce++;
			  }
	    */
	    if(grandmothers.size()==1)
	      {
                int orig = grandmothers[0];
                int orig_id = abs(event[orig].id());     //need absolute value here? -----------------------------------------
                int flavor_grandmon = static_cast<int>(orig_id/pow(10.,static_cast<int>(log10(orig_id)))); //this will miss excited states like D0*
                if(flavor_grandmon == 5)
		  {
		    hf2eDecay.bce_id[nbce] = event[i].id();
		    hf2eDecay.bce_status[nbce] = event[i].status();
		    hf2eDecay.bce_pt[nbce] = event[i].pT();
		    hf2eDecay.bce_pz[nbce] = event[i].pz();
		    hf2eDecay.bce_phi[nbce] = event[i].phi();
		    hf2eDecay.bce_eta[nbce] = event[i].eta();
		    hf2eDecay.bce_y[nbce] = event[i].y();
		    nbce++;
		  }
		else
		  {
		    hf2eDecay.ce_id[nce] = event[i].id();
		    hf2eDecay.ce_status[nce] = event[i].status();
		    hf2eDecay.ce_pt[nce] = event[i].pT();
		    hf2eDecay.ce_pz[nce] = event[i].pz();
		    hf2eDecay.ce_phi[nce] = event[i].phi();
		    hf2eDecay.ce_eta[nce] = event[i].eta();
		    hf2eDecay.ce_y[nce] = event[i].y();
		    nce++;
		  }


	      }

	  }
	if(flavor == 5)
	  {
	    hf2eDecay.be_id[nbe] = event[i].id();
	    hf2eDecay.be_status[nbe] = event[i].status();
	    hf2eDecay.be_pt[nbe] = event[i].pT();
	    hf2eDecay.be_pz[nbe] = event[i].pz();
	    hf2eDecay.be_phi[nbe] = event[i].phi();
	    hf2eDecay.be_eta[nbe] = event[i].eta();
	    hf2eDecay.be_y[nbe] = event[i].y();
	    nbe++;
	  }

	//            ne++;                     //counts have some problems
	//            nelectrons++;

	//
	// Get grandmother (origin of c/b hadron)
	//
	//  Store in tuple
	//

	// If no origin or more than 1 than id == 0
	// and the status identifies what happens: -1 no mother, 
	// -2 more than 1. This should not happen at all, but ...
      }

    }              //end of this track loop                            
   
    e_number=nbe+nce+nbce;
    hadron_number=nh;
    total_tracks = event.size();
    hf2eDecay.numberofcElectrons =nce;
    hf2eDecay.numberofbElectrons =nbe;
    hf2eDecay.numberofbcElectrons =nbce;
    hf2eDecay.numberofHadrons = hadron_number;
    hf2eDecay.noTracks = e_number+hadron_number;    //event.size();
    if(e_number > 0) tree.Fill();
    for(int i=0;i<nh;i++)
      {
	hf2eDecay.hadron_id[i] = 0;
	hf2eDecay.hadron_status[i] = 0;
	hf2eDecay.hadron_pt[i] = 0.;
	hf2eDecay.hadron_pz[i] = 0.;
	hf2eDecay.hadron_phi[i] = 0.;
	hf2eDecay.hadron_eta[i] = 0.;
	hf2eDecay.hadron_y[i] = 0.;
      }
    for(int i=0;i<nce;i++)
      {
	hf2eDecay.ce_id[i] = 0;
	hf2eDecay.ce_status[i] = 0;
	hf2eDecay.ce_pt[i] = 0.;
	hf2eDecay.ce_pz[i] = 0.;
	hf2eDecay.ce_phi[i] = 0.;
	hf2eDecay.ce_eta[i] = 0.;
	hf2eDecay.ce_y[i] = 0.;

      }
    for(int i=0;i<nbe;i++)
      {
	hf2eDecay.be_id[i] = 0;
	hf2eDecay.be_status[i] = 0;
	hf2eDecay.be_pt[i] = 0.;
	hf2eDecay.be_pz[i] = 0.;
	hf2eDecay.be_phi[i] = 0.;
	hf2eDecay.be_eta[i] = 0.;
	hf2eDecay.be_y[i] = 0.;

      }
    for(int i=0;i<nbce;i++)
      {
	hf2eDecay.bce_id[i] = 0;
	hf2eDecay.bce_status[i] = 0;
	hf2eDecay.bce_pt[i] = 0.;
	hf2eDecay.bce_pz[i] = 0.;
	hf2eDecay.bce_phi[i] = 0.;
	hf2eDecay.bce_eta[i] = 0.;
	hf2eDecay.bce_y[i] = 0.;

      }

    //        n= myEvent(pythia, maxNumberOfEvents,ievent);  // in myEvent we deal with the whole event and return
    //        numberOfElectrons += n; 
    //        if (n) tree.Fill();                 //here only fill once no matter how many electrons have been found?     
    ievent++;
    numberOfElectrons = numberOfElectrons+e_number;
    if (ievent%1000 == 0) {
      cout << "# of events generated = " << ievent 
	   << ", # of electrons from c or b hadron decays generated so far = " <<  numberOfElectrons << endl;
    }
        
    // List first few events.
    if (ievent < nList) {
      pythia.info.list(); 
      pythia.process.list();
      pythia.event.list();
    }
  }
    
  //--------------------------------------------------------------
  //  Finish up
  //--------------------------------------------------------------
  pythia.statistics();
  cout << "Writing File" << endl;
  hfile->Write();
  return 0;
}                                 //end of main function-------------------------------------------------------------------
Example #15
0
void polRec(double rapdilepton_min = 1,
		double rapdilepton_max = 1,
		double pTdilepton_min = 1,
		double pTdilepton_max = 1,
		double mass_signal_peak  =  1,
		double mass_signal_sigma =  1,
		double n_sigmas_signal = 1,
		int nEff=1,
		int nDileptonEff=1,
		int nRhoFactor=1,
		int FidCuts=0,
		Char_t *dirstruct = "ToyDirectory_Default",
		bool applyFidCuts=false,
		Char_t *effDir = "effDir_Default",
		bool MCeff=false,
		bool MCDileptoneff=false,
		int rapBin=999,
		int pTbin=999,
		bool useAmapApproach=false,
		int nAmap=999,
		int nDenominatorAmap=999){

  gROOT->Reset();

  bool ForceEpsSmallerOne=false;

//Get single Lepton Efficiency File name
  char EffFile[200];
  char EffFileName[200];
  EvaluateEffFileName(nEff,EffFileName,true);
  sprintf(EffFile,"%s/%s",effDir,EffFileName);

	char EffType[200];
	if(MCeff) sprintf(EffType,"hEff_MC_central");
	else sprintf(EffType,"hEff_DATA_central");

  TFile *fInEff = new TFile(EffFile);
  TH1* hEff=(TH1*) fInEff->Get(EffType);

//Get DiLepton Efficiency File name

  EvaluateEffFileName(nDileptonEff,EffFileName,false);
  sprintf(EffFile,"%s/%s",effDir,EffFileName);

  TFile *fInDileptonEff = new TFile(EffFile);
  TH1* hDileptonEff=(TH1*) fInDileptonEff->Get(EffType);

  EvaluateEffFileName(nRhoFactor,EffFileName,false);
  sprintf(EffFile,"%s/%s",effDir,EffFileName);
  TFile *fInRhoFactor = new TFile(EffFile);


  cout<<"Filling Efficiency Evaluation Histogram"<<endl;
  TH2D*  hEvalEff1D;
  TH2D*  hEvalEff2D;
  char hEvalEffName[200];

  double AlmostZero=1e-8;

  if(fInEff->Get(EffType) != NULL){
 int pTBinsTotal = hEff -> GetNbinsX();
  int etaBinsTotal = hEff -> GetNbinsY();
  int pTBinsNew = 2000;
  int etaBinsNew = 200;
  hEvalEff1D   = new TH2D( "hEvalEff1D", "hEvalEff1D", etaBinsNew, hEff->GetXaxis()->GetXmin(),1.6, pTBinsNew,  hEff->GetYaxis()->GetXmin(), 100);
  hEvalEff2D   = new TH2D( "hEvalEff2D", "hEvalEff2D", etaBinsNew, hEff->GetXaxis()->GetXmin(),1.6, pTBinsNew,  hEff->GetYaxis()->GetXmin(), 100);
  double eff;
  double effBuffer;
  char graphName[200], graphName2D[200];

//  if(fInEff->Get("gEff2D_MC") != NULL){

  if(MCeff) sprintf(graphName2D,"gEff2D_MC");
  else sprintf(graphName2D,"gEff2D_DATA");
//  TGraph2D *graph2D = new TGraph2D(*((TGraph2D *) fInEff->Get(graphName2D)));

  for(int etaBin=0;etaBin<etaBinsNew;etaBin++){
	  int currentEtaBin = hEff->GetXaxis()->FindBin(hEvalEff1D->GetXaxis()->GetBinCenter(etaBin+1));
	  if(MCeff) sprintf(graphName,"gEff_MC_PT_AETA%d",currentEtaBin-1);
	  else sprintf(graphName,"gEff_DATA_PT_AETA%d",currentEtaBin-1);
	  TGraphAsymmErrors *graph = new TGraphAsymmErrors(*((TGraphAsymmErrors *) fInEff->Get(graphName)));
	  double pTMaxCenter=-999;
	  double EtaConst=-999;
	  double pTcenterGraphM1=-999;
	  for(int pTBinGraph=0;pTBinGraph<100;pTBinGraph++){
		double pTcenterGraph;
		double effGraph;
		graph->GetPoint(pTBinGraph,pTcenterGraph,effGraph);
		if(TMath::Abs(pTcenterGraph-pTcenterGraphM1)<AlmostZero) {pTMaxCenter=pTcenterGraph; EtaConst=effGraph; break;}
		pTcenterGraphM1=pTcenterGraph;
	  }

		  for(int pTBin=0;pTBin<pTBinsNew;pTBin++){
			  eff = graph->Eval(hEvalEff1D->GetYaxis()->GetBinCenter(pTBin+1));
		  	  if(eff<0) eff=0;
		  	  if(hEvalEff1D->GetYaxis()->GetBinCenter(pTBin+1)>pTMaxCenter) eff=EtaConst;
		  	  hEvalEff1D->SetBinContent(etaBin+1,pTBin+1,eff); effBuffer=eff;
//			  eff = graph2D->Interpolate(hEvalEff1D->GetYaxis()->GetBinCenter(pTBin+1),hEvalEff1D->GetXaxis()->GetBinCenter(etaBin+1));
		  	  if(eff<AlmostZero && currentEtaBin==1) eff=effBuffer;
		  	  if(eff<AlmostZero && hEvalEff1D->GetYaxis()->GetBinCenter(pTBin+1)>pTMaxCenter*0.5) eff=effBuffer;
			  if(eff<0) eff=0;
		  	  hEvalEff2D->SetBinContent(etaBin+1,pTBin+1,eff);
  }
  }
  sprintf(hEvalEffName,"%s/EvalHisto1D.root",dirstruct);
//  hEvalEff1D->SaveAs(hEvalEffName);
  sprintf(hEvalEffName,"%s/EvalHisto2D.root",dirstruct);
//  hEvalEff2D->SaveAs(hEvalEffName);
}




  if( nEff>1019 && nEff<1099 ){
  const int etaBinsTotal = 8;
  double etaBinningParametrized[etaBinsTotal+1]={0.,0.2,0.3,0.6,0.8,1.0,1.2,1.4,1.6};
  int pTBinsNew = 2000;
  int etaBinsNew = 200;
  hEvalEff1D   = new TH2D( "hEvalEff1D", "hEvalEff1D", etaBinsNew, 0,1.6, pTBinsNew,  0, 100);
  double eff;
  double effBuffer;
  char graphName[200];


  int currentEtaBin;
  for(int etaBin=0;etaBin<etaBinsNew;etaBin++){
	  for(int etaSearch=0;etaSearch<etaBinsTotal;etaSearch++){
	  if(hEvalEff1D->GetXaxis()->GetBinCenter(etaBin+1)>etaBinningParametrized[etaSearch] && hEvalEff1D->GetXaxis()->GetBinCenter(etaBin+1)<etaBinningParametrized[etaSearch+1])
		  currentEtaBin=etaSearch+1;
	  }
	  sprintf(graphName,"gEff_DATA_PT_AETA%d",currentEtaBin-1);
	  TGraphAsymmErrors *graph = new TGraphAsymmErrors(*((TGraphAsymmErrors *) fInEff->Get(graphName)));

		  for(int pTBin=0;pTBin<pTBinsNew;pTBin++){
			  eff = graph->Eval(hEvalEff1D->GetYaxis()->GetBinCenter(pTBin+1));
		  	  if(eff<0) eff=0;
		  	  hEvalEff1D->SetBinContent(etaBin+1,pTBin+1,eff); effBuffer=eff;
  }

  }
  sprintf(hEvalEffName,"%s/EvalHisto1D.root",dirstruct);
//  hEvalEff1D->SaveAs(hEvalEffName);
}


  if( nEff==1101||nEff==1102 ){
  const int etaBinsTotal = 16;
  double etaBinningParametrized[etaBinsTotal+1]={0.,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6};
  int pTBinsNew = 2000;
  int etaBinsNew = 200;
  hEvalEff1D   = new TH2D( "hEvalEff1D", "hEvalEff1D", etaBinsNew, 0,1.6, pTBinsNew,  0, 100);
  double eff;
  double effBuffer;
  char graphName[200];


  int currentEtaBin;
  for(int etaBin=0;etaBin<etaBinsNew;etaBin++){
	  for(int etaSearch=0;etaSearch<etaBinsTotal;etaSearch++){
	  if(hEvalEff1D->GetXaxis()->GetBinCenter(etaBin+1)>etaBinningParametrized[etaSearch] && hEvalEff1D->GetXaxis()->GetBinCenter(etaBin+1)<etaBinningParametrized[etaSearch+1])
		  currentEtaBin=etaSearch+1;
	  }
	  sprintf(graphName,"gEff_DATA_PT_AETA%d",currentEtaBin-1);
	  TGraphAsymmErrors *graph = new TGraphAsymmErrors(*((TGraphAsymmErrors *) fInEff->Get(graphName)));

		  for(int pTBin=0;pTBin<pTBinsNew;pTBin++){
			  eff = graph->Eval(hEvalEff1D->GetYaxis()->GetBinCenter(pTBin+1));
		  	  if(eff<0) eff=0;
		  	  hEvalEff1D->SetBinContent(etaBin+1,pTBin+1,eff); effBuffer=eff;
  }

  }
  sprintf(hEvalEffName,"%s/EvalHisto1D.root",dirstruct);
//  hEvalEff1D->SaveAs(hEvalEffName);
}





TEfficiency* TEff;
TH2D* hEvalEff;
if(nEff==105 || nEff==106){
	sprintf(EffType,"totEff_MCTRUTH_pT_eta");
	TEff=(TEfficiency*) fInEff->Get(EffType);
	TH1* hEffTOT=(TH1*)TEff->GetTotalHistogram();
	TH1* hEffPASS=(TH1*)TEff->GetPassedHistogram();
	hEffPASS->Divide(hEffTOT);
	hEvalEff=(TH2D*)hEffPASS->Clone("hEffPASS");
}

if(nEff!=105 && nEff!=106 && nEff!=1 && nEff!=1)
	hEvalEff = (TH2D*)hEvalEff1D->Clone("hEvalEff");
if(nEff > 10000) hEvalEff = (TH2D*)hEvalEff2D->Clone("hEvalEff");

  //sprintf(hEvalEffName,"%s/EvalHisto.root",dirstruct);
  //hEvalEff->SaveAs(hEvalEffName);





////// Get Amap

EvaluateEffFileName(nAmap,EffFileName,false);
sprintf(EffFile,"%s/%s",effDir,EffFileName);

TFile *fInAmap = new TFile(EffFile);







////// Get Amap Denominator

TEfficiency* TEff_nDenominatorAmap;
TH2D* hEvalEff_nDenominatorAmap;

TH2D*  hEvalEff1D_nDenominatorAmap;

EvaluateEffFileName(nDenominatorAmap,EffFileName,true);
sprintf(EffFile,"%s/%s",effDir,EffFileName);

TFile *fInEff_nDenominatorAmap = new TFile(EffFile);

if( nDenominatorAmap==1101 ){
const int etaBinsTotal = 16;
double etaBinningParametrized[etaBinsTotal+1]={0.,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1.0,1.1,1.2,1.3,1.4,1.5,1.6};
int pTBinsNew = 2000;
int etaBinsNew = 200;
hEvalEff1D_nDenominatorAmap   = new TH2D( "hEvalEff1D_nDenominatorAmap", "hEvalEff1D_nDenominatorAmap", etaBinsNew, 0,1.6, pTBinsNew,  0, 100);
double eff;
double effBuffer;
char graphName[200];


int currentEtaBin;
for(int etaBin=0;etaBin<etaBinsNew;etaBin++){
	  for(int etaSearch=0;etaSearch<etaBinsTotal;etaSearch++){
	  if(hEvalEff1D_nDenominatorAmap->GetXaxis()->GetBinCenter(etaBin+1)>etaBinningParametrized[etaSearch] && hEvalEff1D_nDenominatorAmap->GetXaxis()->GetBinCenter(etaBin+1)<etaBinningParametrized[etaSearch+1])
		  currentEtaBin=etaSearch+1;
	  }
	  sprintf(graphName,"gEff_DATA_PT_AETA%d",currentEtaBin-1);
	  TGraphAsymmErrors *graph = new TGraphAsymmErrors(*((TGraphAsymmErrors *) fInEff_nDenominatorAmap->Get(graphName)));

		  for(int pTBin=0;pTBin<pTBinsNew;pTBin++){
			  eff = graph->Eval(hEvalEff1D_nDenominatorAmap->GetYaxis()->GetBinCenter(pTBin+1));
		  	  if(eff<0) eff=0;
		  	  hEvalEff1D_nDenominatorAmap->SetBinContent(etaBin+1,pTBin+1,eff); effBuffer=eff;
}

}
}

if(nDenominatorAmap!=105 && nDenominatorAmap!=106 && nDenominatorAmap!=1)
	hEvalEff_nDenominatorAmap = (TH2D*)hEvalEff1D_nDenominatorAmap->Clone("hEvalEff_nDenominatorAmap");


if(nDenominatorAmap==105 || nDenominatorAmap==106){
	sprintf(EffType,"totEff_MCTRUTH_pT_eta");
	TEfficiency* TEff2=(TEfficiency*) fInEff_nDenominatorAmap->Get(EffType);
	TH1* hEffTOT=(TH1*)TEff2->GetTotalHistogram();
	TH1* hEffPASS=(TH1*)TEff2->GetPassedHistogram();
	hEffPASS->Divide(hEffTOT);
	hEvalEff_nDenominatorAmap=(TH2D*)hEffPASS->Clone("hEffPASS");
	TEff_nDenominatorAmap=(TEfficiency*) fInEff_nDenominatorAmap->Get(EffType);
}




















	double mass_min = mass_signal_peak - n_sigmas_signal*mass_signal_sigma;
	double mass_max = mass_signal_peak + n_sigmas_signal*mass_signal_sigma;

  char filename [500];

  // get ntuple of generated data from file

  sprintf(filename,"%s/genData.root",dirstruct);
  TFile* genFile = new TFile(filename,"READ");
  TTree* genData = (TTree*)genFile->Get("genData");


  // create output data file

  sprintf(filename,"%s/data.root",dirstruct);
  TFile* dataFile = new TFile(filename, "RECREATE", "dataFile");


  // output ntuple

  TTree* data = new TTree("selectedData","selectedData");


  // histograms to be output to the opened file

  // background distributions

  const int nbinth   = 15;
  const int nbinph   = 15;
  const int nbinpT   =  7;
  const int nbinrap  =  2;
  const int nbinmass =  7;

  TH2D* background_costhphiPX = new TH2D( "background_costhphiPHX", "", nbinth,    -1.,    1.,
                                                                        nbinph,   180.,  180.  );
  TH3D* background_pTrapMass  = new TH3D( "background_pTrapMass",   "", nbinpT,   pTdilepton_min,  pTdilepton_max,
                                                                        nbinrap,  rapdilepton_min, rapdilepton_max,
                                                                        nbinmass, mass_min,        mass_max         );
  TH1D* background_fraction = new TH1D( "background_fraction", "", 1, 0., 1. );

  // this is a temporary histogram to calculate BG fraction after acceptence and efficiency cuts
  TH1D* isBGdistribution    = new TH1D( "isBGdistribution", "", 2, 0., 2. );


  // structure of input ntuple

  TLorentzVector* lepP_gen = 0;    genData->SetBranchAddress( "lepP",    &lepP_gen );
  TLorentzVector* lepN_gen = 0;    genData->SetBranchAddress( "lepN",    &lepN_gen );

  double costh_CS;  genData->SetBranchAddress( "costh_CS",     &costh_CS );
  double phi_CS;    genData->SetBranchAddress( "phi_CS",       &phi_CS   );
  double phith_CS;  genData->SetBranchAddress( "phith_CS",     &phith_CS );

  double costh_HX;  genData->SetBranchAddress( "costh_HX",     &costh_HX );
  double phi_HX;    genData->SetBranchAddress( "phi_HX",       &phi_HX   );
  double phith_HX;  genData->SetBranchAddress( "phith_HX",     &phith_HX );

  double costh_PX;  genData->SetBranchAddress( "costh_PX",     &costh_PX );
  double phi_PX;    genData->SetBranchAddress( "phi_PX",       &phi_PX   );
  double phith_PX;  genData->SetBranchAddress( "phith_PX",     &phith_PX );

  double mass;      genData->SetBranchAddress( "mass",         &mass     );
  double pT;        genData->SetBranchAddress( "pT",           &pT       );
  double rap;       genData->SetBranchAddress( "rap",          &rap      );

  int isBG;         genData->SetBranchAddress( "isBG",         &isBG     );


  // structure of output ntuple

  TLorentzVector* lepP = new TLorentzVector(0.,0.,0.,0.);  data->Branch( "lepP", "TLorentzVector", &lepP );
  TLorentzVector* lepN = new TLorentzVector(0.,0.,0.,0.);  data->Branch( "lepN", "TLorentzVector", &lepN );


  // loop over events in the input ntuple

  int numEvts = int( genData->GetEntries() );


  cout << endl;
  cout << "Reading " << numEvts << " dilepton events"<< endl;
  cout << "------------------------------------------------------------" << endl;
  cout << "Progress: "<<endl;

  int n_step = numEvts/5;
  int n_step_=1;
  int rejected=0;

  for ( int evtNumber = 0; evtNumber < numEvts; evtNumber++ ) {

	    if ((evtNumber+1)%n_step == 0) {cout << n_step_*20 <<" % "<<endl; n_step_++;}

    genData->GetEvent( evtNumber );




    // select data in acceptance and apply efficiency

    double lepP_pT  = lepP_gen->Pt();
    double lepN_pT  = lepN_gen->Pt();
    double lepP_eta  = lepP_gen->PseudoRapidity();
    double lepN_eta  = lepN_gen->PseudoRapidity();

    bool isEventAccepted = isMuonInAcceptance( FidCuts-1, lepP_pT, lepP_eta )
                         * isMuonInAcceptance( FidCuts-1, lepN_pT, lepN_eta );

//    if (lepP_gen->Phi()>0 && lepP_gen->Phi()<TMath::Pi()/8.) isEventAccepted=false;
//    if (lepN_gen->Phi()>0 && lepN_gen->Phi()<TMath::Pi()/8.) isEventAccepted=false;

    if ( !isEventAccepted ) {rejected++; continue;}

    double effP = singleLeptonEfficiency( lepP_pT, lepP_eta, nEff, fInEff , hEvalEff , MCeff , TEff);
    double effN = singleLeptonEfficiency( lepN_pT, lepN_eta, nEff, fInEff , hEvalEff , MCeff , TEff);

    double costh_DILEff;
    double phi_DILEff;
    if(nDileptonEff>200 && nDileptonEff<211) {costh_DILEff=costh_CS; phi_DILEff=phi_CS;}
    if(nDileptonEff>210 && nDileptonEff<221) {costh_DILEff=costh_HX; phi_DILEff=phi_HX;}
    if(nDileptonEff>220 && nDileptonEff<231) {costh_DILEff=costh_PX; phi_DILEff=phi_PX;}
    double DileptonEff = DiLeptonEfficiency( costh_DILEff, phi_DILEff, nDileptonEff, fInDileptonEff, MCDileptoneff);

    double costh_RhoFactor;
    double phi_RhoFactor;
    if(nRhoFactor>300 && nRhoFactor<311) {costh_RhoFactor=costh_CS; phi_RhoFactor=phi_CS;}
    if(nRhoFactor>310 && nRhoFactor<321) {costh_RhoFactor=costh_HX; phi_RhoFactor=phi_HX;}
    if(nRhoFactor>320 && nRhoFactor<331) {costh_RhoFactor=costh_PX; phi_RhoFactor=phi_PX;}
	double RhoFactor = EvaluateRhoFactor( costh_RhoFactor, phi_RhoFactor, nRhoFactor, fInRhoFactor, rap, pT);

	double epsilon = effP*effN;

	if(!useAmapApproach) epsilon = epsilon*DileptonEff*RhoFactor;

	if(useAmapApproach){
	    double costh_Amap=0;
	    double phi_Amap=0;
	    if(nAmap>10000 && nAmap<20000) {costh_Amap=costh_CS; phi_Amap=phi_CS;}
	    if(nAmap>20000 && nAmap<30000) {costh_Amap=costh_HX; phi_Amap=phi_HX;}
	    if(nAmap>30000 && nAmap<40000) {costh_Amap=costh_PX; phi_Amap=phi_PX;}
		double AmapValue=EvaluateAmap( costh_Amap, phi_Amap, nAmap, fInAmap, rap, pT);
		double AmapDenominator= DenominatorAmapEfficiency( lepP_pT, lepP_eta, nDenominatorAmap, fInEff_nDenominatorAmap, hEvalEff_nDenominatorAmap, true, TEff_nDenominatorAmap) * DenominatorAmapEfficiency( lepN_pT, lepN_eta, nDenominatorAmap, fInEff_nDenominatorAmap, hEvalEff_nDenominatorAmap, true, TEff_nDenominatorAmap);
		epsilon = epsilon*AmapValue/AmapDenominator;
	}


	if(epsilon>1&&ForceEpsSmallerOne) {epsilon=1;}

/*    double rndmeffP = gRandom->Uniform(1.);
    double rndmeffN = gRandom->Uniform(1.);
    double rndmDileptoneff = gRandom->Uniform(1.);
    double rndmRhoFactor = gRandom->Uniform(1.);
*/
    double rndmepsilon = gRandom->Uniform(1.);

    if ( rndmepsilon > epsilon ) {rejected++; continue;}

    // fill background histograms and output ntuple

    isBGdistribution->Fill( isBG );
    if ( isBG ) {
       background_costhphiPX->Fill( costh_PX, phi_PX );
       background_pTrapMass->Fill( pT, TMath::Abs(rap), mass );
    }

    *lepP = *lepP_gen;
    *lepN = *lepN_gen;

    data->Fill();

  } // end of RD ntuple loop

  cout << endl << endl;



  // background fraction

  double f_BG = isBGdistribution->GetMean();


  background_fraction->SetBinContent( 1, f_BG );

  double effFrac=(double(numEvts-rejected))/double(numEvts);


  cout<<"Effective Background Fraction:           "<<f_BG<<endl;
  cout<<"Fraction of Events Surviving Efficiency: "<<effFrac<<endl;
  cout<<"Surviving Signal Events:                 "<<isBGdistribution->GetEntries()*(1-f_BG)<<endl;

  // end

  genFile->Close();
  dataFile->Write();
 dataFile->Close();

}
Example #16
0
void selectZeeSC(const TString conf="zee_sc.conf", // input file
		 const TString outputDir=".",   // output directory
		 const Bool_t  doScaleCorr=0    // apply energy scale corrections?
) {
  gBenchmark->Start("selectZee");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 

  const Double_t MASS_LOW  = 40;
  const Double_t MASS_HIGH = 200;
  const Double_t PT_CUT    = 25;
  const Double_t ETA_CUT   = 2.5;
  const Double_t ELE_MASS  = 0.000511;
  
  const Double_t ECAL_GAP_LOW  = 1.4442;
  const Double_t ECAL_GAP_HIGH = 1.566;
  
  const Double_t escaleNbins  = 6;
  const Double_t escaleEta[]  = { 0.4,     0.8,     1.2,     1.4442,  2,        2.5 };
  const Double_t escaleCorr[] = { 1.00284, 1.00479, 1.00734, 1.00851, 1.00001,  0.982898 };

  const Int_t BOSON_ID  = 23;
  const Int_t LEPTON_ID = 11;

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  enum { ePass=0, eFail };  // event category enum
  
  vector<TString>  snamev;      // sample name (for output files)  
  vector<CSample*> samplev;     // data/MC samples

  //
  // parse .conf file
  //
  confParse(conf, snamev, samplev);
  const Bool_t hasData = (samplev[0]->fnamev.size()>0);

  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  const TString ntupDir = outputDir + TString("/ntuples");
  gSystem->mkdir(ntupDir,kTRUE);
  
  //
  // Declare output ntuple variables
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  matchGen;
  UInt_t  category;
  UInt_t  npv, npu;
  UInt_t  id_1, id_2;
  Double_t x_1, x_2, xPDF_1, xPDF_2;
  Double_t scalePDF, weightPDF;
  TLorentzVector *genV=0;
  Float_t genVPt, genVPhi, genVy, genVMass;
  Float_t scale1fb;
  Float_t met, metPhi, sumEt, u1, u2;
  Float_t tkMet, tkMetPhi, tkSumEt, tkU1, tkU2;
  Float_t mvaMet, mvaMetPhi, mvaSumEt, mvaU1, mvaU2;
  Float_t ppMet, ppMetPhi, ppSumEt, ppU1, ppU2;
  Int_t   q1, q2;
  TLorentzVector *dilep=0, *lep1=0, *lep2=0;
  ///// electron specific /////
  Float_t trkIso1, emIso1, hadIso1, trkIso2, emIso2, hadIso2;
  Float_t pfChIso1, pfGamIso1, pfNeuIso1, pfCombIso1, pfChIso2, pfGamIso2, pfNeuIso2, pfCombIso2;
  Float_t sigieie1, hovere1, eoverp1, fbrem1, ecalE1, sigieie2, hovere2, eoverp2, fbrem2, ecalE2;
  Float_t dphi1, deta1, dphi2, deta2;
  Float_t d01, dz1, d02, dz2;
  UInt_t  isConv1, nexphits1, typeBits1, isConv2, nexphits2, typeBits2; 
  TLorentzVector *sc1=0, *sc2=0;
  
  // Data structures to store info from TTrees
  baconhep::TEventInfo *info   = new baconhep::TEventInfo();
  baconhep::TGenEventInfo *gen = new baconhep::TGenEventInfo();
  TClonesArray *genPartArr     = new TClonesArray("baconhep::TGenParticle");
  TClonesArray *electronArr    = new TClonesArray("baconhep::TElectron");
  TClonesArray *muonArr        = new TClonesArray("baconhep::TMuon");
  TClonesArray *scArr          = new TClonesArray("baconhep::TPhoton");
  
  TFile *infile=0;
  TTree *eventTree=0;
  
  //
  // loop over samples
  //  
  for(UInt_t isam=0; isam<samplev.size(); isam++) {
    
    // Assume data sample is first sample in .conf file
    // If sample is empty (i.e. contains no ntuple files), skip to next sample
    if(isam==0 && !hasData) continue;
    
    // Assume signal sample is given name "zee" - flag to store GEN Z kinematics
    Bool_t isSignal = (snamev[isam].CompareTo("zee",TString::kIgnoreCase)==0);  

    // flag to reject Z->ee events when selecting at wrong-flavor background events
    Bool_t isWrongFlavor = (snamev[isam].CompareTo("zxx",TString::kIgnoreCase)==0);  

    CSample* samp = samplev[isam];
  
    //
    // Set up output ntuple
    //
    TString outfilename = ntupDir + TString("/") + snamev[isam] + TString("_select.root");
    if(isam==0 && !doScaleCorr) outfilename = ntupDir + TString("/") + snamev[isam] + TString("_select.raw.root");
    TFile *outFile = new TFile(outfilename,"RECREATE"); 
    TTree *outTree = new TTree("Events","Events");
    outTree->Branch("runNum",     &runNum,     "runNum/i");      // event run number
    outTree->Branch("lumiSec",    &lumiSec,    "lumiSec/i");     // event lumi section
    outTree->Branch("evtNum",     &evtNum,     "evtNum/i");      // event number
    outTree->Branch("matchGen",   &matchGen,   "matchGen/i");    // event has both leptons matched to MC Z->ll
    outTree->Branch("category",   &category,   "category/i");    // dilepton category
    outTree->Branch("id_1",       &id_1,       "id_1/i");        // PDF info -- parton ID for parton 1
    outTree->Branch("id_2",       &id_2,       "id_2/i");        // PDF info -- parton ID for parton 2
    outTree->Branch("x_1",        &x_1,        "x_1/d");         // PDF info -- x for parton 1
    outTree->Branch("x_2",        &x_2,        "x_2/d");         // PDF info -- x for parton 2
    outTree->Branch("xPDF_1",     &xPDF_1,     "xPDF_1/d");      // PDF info -- x*F for parton 1
    outTree->Branch("xPDF_2",     &xPDF_2,     "xPDF_2/d");      // PDF info -- x*F for parton 2
    outTree->Branch("scalePDF",   &scalePDF,   "scalePDF/d");    // PDF info -- energy scale of parton interaction
    outTree->Branch("weightPDF",  &weightPDF,  "weightPDF/d");   // PDF info -- PDF weight
    outTree->Branch("npv",        &npv,        "npv/i");         // number of primary vertices
    outTree->Branch("npu",        &npu,        "npu/i");         // number of in-time PU events (MC)
    outTree->Branch("genV",      "TLorentzVector",  &genV);      // GEN boson 4-vector
    outTree->Branch("genVPt",     &genVPt,     "genVPt/F");      // GEN boson pT (signal MC)
    outTree->Branch("genVPhi",    &genVPhi,    "genVPhi/F");     // GEN boson phi (signal MC)
    outTree->Branch("genVy",      &genVy,      "genVy/F");       // GEN boson rapidity (signal MC)
    outTree->Branch("genVMass",   &genVMass,   "genVMass/F");    // GEN boson mass (signal MC)
    outTree->Branch("scale1fb",   &scale1fb,   "scale1fb/F");    // event weight per 1/fb (MC)
    outTree->Branch("met",        &met,        "met/F");         // MET
    outTree->Branch("metPhi",     &metPhi,     "metPhi/F");      // phi(MET)
    outTree->Branch("sumEt",      &sumEt,      "sumEt/F");       // Sum ET
    outTree->Branch("u1",         &u1,         "u1/F");          // parallel component of recoil
    outTree->Branch("u2",         &u2,         "u2/F");          // perpendicular component of recoil
    outTree->Branch("tkMet",      &tkMet,      "tkMet/F");       // MET (track MET)
    outTree->Branch("tkMetPhi",   &tkMetPhi,   "tkMetPhi/F");    // phi(MET) (track MET)
    outTree->Branch("tkSumEt",    &tkSumEt,    "tkSumEt/F");     // Sum ET (track MET)
    outTree->Branch("tkU1",       &tkU1,       "tkU1/F");        // parallel component of recoil (track MET)
    outTree->Branch("tkU2",       &tkU2,       "tkU2/F");        // perpendicular component of recoil (track MET)
    outTree->Branch("mvaMet",     &mvaMet,     "mvaMet/F");      // MVA MET
    outTree->Branch("mvaMetPhi",  &mvaMetPhi,  "mvaMetPhi/F");   // phi(MVA MET)
    outTree->Branch("mvaSumEt",   &mvaSumEt,   "mvaSumEt/F");    // Sum ET (mva MET)
    outTree->Branch("mvaU1",      &mvaU1,      "mvaU1/F");       // parallel component of recoil (mva MET)
    outTree->Branch("mvaU2",      &mvaU2,      "mvaU2/F");       // perpendicular component of recoil (mva MET)
    outTree->Branch("ppMet",      &ppMet,      "ppMet/F");       // PUPPI MET
    outTree->Branch("ppMetPhi",   &ppMetPhi,   "ppMetPhi/F");    // phi(PUPPI MET)
    outTree->Branch("ppSumEt",    &ppSumEt,    "ppSumEt/F");     // Sum ET (PUPPI MET)
    outTree->Branch("ppU1",       &ppU1,       "ppU1/F");        // parallel component of recoil (PUPPI MET)
    outTree->Branch("ppU2",       &ppU2,       "ppU2/F");        // perpendicular component of recoil (PUPPI MET)
    outTree->Branch("q1",         &q1,         "q1/I");          // charge of tag lepton
    outTree->Branch("q2",         &q2,         "q2/I");          // charge of probe lepton
    outTree->Branch("dilep",      "TLorentzVector",  &dilep);    // di-lepton 4-vector
    outTree->Branch("lep1",       "TLorentzVector",  &lep1);     // tag lepton 4-vector
    outTree->Branch("lep2",       "TLorentzVector",  &lep2);     // probe lepton 4-vector
    ///// electron specific /////
    outTree->Branch("trkIso1",    &trkIso1,    "trkIso1/F");     // track isolation of tag lepton
    outTree->Branch("trkIso2",    &trkIso2,    "trkIso2/F");     // track isolation of probe lepton
    outTree->Branch("emIso1",     &emIso1,     "emIso1/F");      // ECAL isolation of tag lepton
    outTree->Branch("emIso2",     &emIso2,     "emIso2/F");      // ECAL isolation of probe lepton
    outTree->Branch("hadIso1",    &hadIso1,    "hadIso1/F");     // HCAL isolation of tag lepton
    outTree->Branch("hadIso2",    &hadIso2,    "hadIso2/F");     // HCAL isolation of probe lepton
    outTree->Branch("pfChIso1",   &pfChIso1,   "pfChIso1/F");    // PF charged hadron isolation of tag lepton
    outTree->Branch("pfChIso2",   &pfChIso2,   "pfChIso2/F");    // PF charged hadron isolation of probe lepton
    outTree->Branch("pfGamIso1",  &pfGamIso1,  "pfGamIso1/F");   // PF photon isolation of tag lepton
    outTree->Branch("pfGamIso2",  &pfGamIso2,  "pfGamIso2/F");   // PF photon isolation of probe lepton
    outTree->Branch("pfNeuIso1",  &pfNeuIso1,  "pfNeuIso1/F");   // PF neutral hadron isolation of tag lepton
    outTree->Branch("pfNeuIso2",  &pfNeuIso2,  "pfNeuIso2/F");   // PF neutral hadron isolation of probe lepton
    outTree->Branch("pfCombIso1", &pfCombIso1, "pfCombIso1/F");  // PF combine isolation of tag lepton
    outTree->Branch("pfCombIso2", &pfCombIso2, "pfCombIso2/F");  // PF combined isolation of probe lepton    
    outTree->Branch("sigieie1",   &sigieie1,   "sigieie1/F");    // sigma-ieta-ieta of tag
    outTree->Branch("sigieie2",   &sigieie2,   "sigieie2/F");    // sigma-ieta-ieta of probe
    outTree->Branch("hovere1",    &hovere1,    "hovere1/F");     // H/E of tag
    outTree->Branch("hovere2",    &hovere2,    "hovere2/F");     // H/E of probe
    outTree->Branch("eoverp1",    &eoverp1,    "eoverp1/F");     // E/p of tag
    outTree->Branch("eoverp2",    &eoverp2,    "eoverp2/F");     // E/p of probe	 
    outTree->Branch("fbrem1",     &fbrem1,     "fbrem1/F");      // brem fraction of tag
    outTree->Branch("fbrem2",     &fbrem2,     "fbrem2/F");      // brem fraction of probe
    outTree->Branch("dphi1",      &dphi1,      "dphi1/F");       // GSF track - ECAL dphi of tag
    outTree->Branch("dphi2",      &dphi2,      "dphi2/F");       // GSF track - ECAL dphi of probe 	
    outTree->Branch("deta1",      &deta1,      "deta1/F");       // GSF track - ECAL deta of tag
    outTree->Branch("deta2",      &deta2,      "deta2/F");       // GSF track - ECAL deta of probe
    outTree->Branch("ecalE1",     &ecalE1,     "ecalE1/F");      // ECAL energy of tag
    outTree->Branch("ecalE2",     &ecalE2,     "ecalE2/F");      // ECAL energy of probe
    outTree->Branch("d01",        &d01,        "d01/F");	 // transverse impact parameter of tag
    outTree->Branch("d02",        &d02,        "d02/F");	 // transverse impact parameter of probe	  
    outTree->Branch("dz1",        &dz1,        "dz1/F");	 // longitudinal impact parameter of tag
    outTree->Branch("dz2",        &dz2,        "dz2/F");	 // longitudinal impact parameter of probe
    outTree->Branch("isConv1",    &isConv1,    "isConv1/i");     // conversion filter flag of tag lepton
    outTree->Branch("isConv2",    &isConv2,    "isConv2/i");     // conversion filter flag of probe lepton
    outTree->Branch("nexphits1",  &nexphits1,  "nexphits1/i");   // number of missing expected inner hits of tag lepton
    outTree->Branch("nexphits2",  &nexphits2,  "nexphits2/i");   // number of missing expected inner hits of probe lepton
    outTree->Branch("typeBits1",  &typeBits1,  "typeBits1/i");   // electron type of tag lepton
    outTree->Branch("typeBits2",  &typeBits2,  "typeBits2/i");   // electron type of probe lepton
    outTree->Branch("sc1",       "TLorentzVector",  &sc1);       // tag supercluster 4-vector
    outTree->Branch("sc2",       "TLorentzVector",  &sc2);       // probe supercluster 4-vector

    //
    // loop through files
    //
    const UInt_t nfiles = samp->fnamev.size();
    for(UInt_t ifile=0; ifile<nfiles; ifile++) {  

      // Read input file and get the TTrees
      cout << "Processing " << samp->fnamev[ifile] << " [xsec = " << samp->xsecv[ifile] << " pb] ... " << endl; cout.flush();
      infile = TFile::Open(samp->fnamev[ifile]); 
      assert(infile);

      const baconhep::TTrigger triggerMenu("../../BaconAna/DataFormats/data/HLT_50nsGRun");
      UInt_t trigger, trigObjL1, trigObjHLT;
      if (isam==0) {
        trigger = triggerMenu.getTriggerBit("HLT_Ele23_WPLoose_Gsf_v*"); //data trigger
        trigObjL1  = 1; //data
        trigObjHLT = 2; //data
      }
      else {
        trigger = triggerMenu.getTriggerBit("HLT_Ele23_WP75_Gsf_v*");
        trigObjL1  = 4; //triggerMenu.getTriggerObjectBit("HLT_Ele22_WP75_Gsf_v*", "hltL1sL1SingleEG20");
        trigObjHLT = 5; //triggerMenu.getTriggerObjectBit("HLT_Ele23_WP75_Gsf_v*", "hltEle23WP75GsfTrackIsoFilter");
      }

      //Bool_t hasJSON = kFALSE;
      //baconhep::RunLumiRangeMap rlrm;
      //if(samp->jsonv[ifile].CompareTo("NONE")!=0) { 
      //hasJSON = kTRUE;
      //rlrm.AddJSONFile(samp->jsonv[ifile].Data()); 
      //}
  
      eventTree = (TTree*)infile->Get("Events");
      assert(eventTree);  
      eventTree->SetBranchAddress("Info",     &info);        TBranch *infoBr     = eventTree->GetBranch("Info");
      eventTree->SetBranchAddress("Electron", &electronArr); TBranch *electronBr = eventTree->GetBranch("Electron");
      eventTree->SetBranchAddress("Muon",     &muonArr);     TBranch *muonBr     = eventTree->GetBranch("Muon");
      eventTree->SetBranchAddress("Photon",   &scArr);       TBranch *scBr       = eventTree->GetBranch("Photon");
      Bool_t hasGen = eventTree->GetBranchStatus("GenEvtInfo");
      TBranch *genBr=0, *genPartBr=0;
      if(hasGen) {
        eventTree->SetBranchAddress("GenEvtInfo", &gen); genBr = eventTree->GetBranch("GenEvtInfo");
	eventTree->SetBranchAddress("GenParticle",&genPartArr); genPartBr = eventTree->GetBranch("GenParticle");
      }

      // Compute MC event weight per 1/fb
      const Double_t xsec = samp->xsecv[ifile];
      Double_t totalWeight=1;
      if (hasGen) {
	TH1D *hall = new TH1D("hall", "", 1,0,1);
	eventTree->Draw("0.5>>hall", "GenEvtInfo->weight");
	totalWeight=hall->Integral();
	delete hall;
	hall=0;
      }

      //
      // loop over events
      //
      Double_t nsel=0, nselvar=0;
      for(UInt_t ientry=0; ientry<eventTree->GetEntries()/10; ientry++) {
        infoBr->GetEntry(ientry);

        if(ientry%1000000==0) cout << "Processing event " << ientry << ". " << (double)ientry/(double)eventTree->GetEntries()*100 << " percent done with this file." << endl;

        Double_t weight=1;
        if(xsec>0 && totalWeight>0) weight = xsec/totalWeight;
	if(hasGen) {
	  genPartArr->Clear();
	  genBr->GetEntry(ientry);
	  genPartBr->GetEntry(ientry);
	  weight*=gen->weight;
	}

	// veto z -> xx decays for signal and z -> ee for bacground samples (needed for inclusive DYToLL sample)
	if (isWrongFlavor && hasGen && toolbox::flavor(genPartArr, BOSON_ID)==LEPTON_ID) continue;
	else if (isSignal && hasGen && toolbox::flavor(genPartArr, BOSON_ID)!=LEPTON_ID) continue;

        // check for certified lumi (if applicable)
        //baconhep::RunLumiRangeMap::RunLumiPairType rl(info->runNum, info->lumiSec);      
        //if(hasJSON && !rlrm.HasRunLumi(rl)) continue;  

        // trigger requirement               
        if(!(info->triggerBits[trigger])) continue;

        // good vertex requirement
        if(!(info->hasGoodPV)) continue;
	
        //
	// SELECTION PROCEDURE:
	//  (1) Find a good electron matched to trigger -> this will be the "tag"
	//  (2) Pair the tag with Supercluster probes which form a tag+probe mass inside 
	//      the Z window and divide candidates into exclusive categories as follows:
	//      (a) if probe SC is part of a good electron matched to trigger     -> EleEle2HLT category
	//      (b) if probe SC is part of a good electron not matched to trigger -> EleEle1HLT category
	//      (c) if probe SC is part of an electron failing selection cuts     -> EleEleNoSel category
	//      (d) if probe SC is not part of an ECAL driven electron            -> EleSC category
	//	

	TLorentzVector *gvec=new TLorentzVector(0,0,0,0);
	TLorentzVector *glep1=new TLorentzVector(0,0,0,0);
	TLorentzVector *glep2=new TLorentzVector(0,0,0,0);
	toolbox::fillGen(genPartArr, BOSON_ID, gvec, glep1, glep2,1);

	electronArr->Clear();
        electronBr->GetEntry(ientry);
	scArr->Clear();
	scBr->GetEntry(ientry);

	for(Int_t i1=0; i1<electronArr->GetEntriesFast(); i1++) {
          const baconhep::TElectron *tag = (baconhep::TElectron*)((*electronArr)[i1]);

	  // check ECAL gap
	  if(fabs(tag->scEta)>=ECAL_GAP_LOW && fabs(tag->scEta)<=ECAL_GAP_HIGH) continue;
	  
	  if (!(((glep1) && toolbox::deltaR(tag->eta, tag->phi, glep1->Eta(), glep1->Phi())<0.1) || 
		 ((glep2) && toolbox::deltaR(tag->eta, tag->phi, glep2->Eta(), glep2->Phi())<0.1))) continue;
	  
	  Double_t escale1=1;
	  if(doScaleCorr && isam==0) {
	    for(UInt_t ieta=0; ieta<escaleNbins; ieta++) {
	      if(fabs(tag->scEta)<escaleEta[ieta]) {
	        escale1 = escaleCorr[ieta];
		break;
	      }
	    }
	  }
	  if(escale1*(tag->scEt) < PT_CUT)     continue;  // lepton pT cut
	  if(fabs(tag->scEta)    > ETA_CUT)    continue;  // lepton |eta| cut
	  if(!passEleID(tag,info->rhoIso))     continue;  // lepton selection
	  if(!(tag->hltMatchBits[trigObjHLT])) continue;  // check trigger matching

	  TLorentzVector vTag;     vTag.SetPtEtaPhiM(tag->pt,   tag->eta,   tag->phi,   ELE_MASS);
	  TLorentzVector vTagSC; vTagSC.SetPtEtaPhiM(tag->scEt, tag->scEta, tag->scPhi, ELE_MASS);

	  muonArr->Clear();
	  muonBr->GetEntry(ientry); 
	  for(Int_t j=0; j<muonArr->GetEntriesFast(); j++) {
	    const baconhep::TMuon *tkProbe = (baconhep::TMuon*)((*muonArr)[j]);
	    if (tkProbe->typeBits & baconhep::EMuType::kGlobal) continue;
	    if (toolbox::deltaR(tkProbe->eta, tkProbe->phi, tag->eta, tag->phi)<0.1) continue;

	    if (!( ((glep1) && toolbox::deltaR(tkProbe->eta, tkProbe->phi, glep1->Eta(), glep1->Phi())<0.1) || 
		   ((glep2) && toolbox::deltaR(tkProbe->eta, tkProbe->phi, glep2->Eta(), glep2->Phi())<0.1) ) ) continue;

	    // check ECAL gap
	    if(fabs(tkProbe->eta)>=ECAL_GAP_LOW && fabs(tkProbe->eta)<=ECAL_GAP_HIGH) continue;
	    
	    if(tkProbe->pt < PT_CUT)  continue;  // Track pT cut 
	    if(fabs(tkProbe->eta)  > ETA_CUT) continue;  // track |eta| cuts
	  
	    const baconhep::TPhoton *scProbe=0;
	    Int_t iprobe=-1;
	    for(Int_t i2=0; i2<scArr->GetEntriesFast(); i2++) {
	      const baconhep::TPhoton *sc = (baconhep::TPhoton*)((*scArr)[i2]);
	      if (toolbox::deltaR(tkProbe->eta, tkProbe->phi, sc->eta, sc->phi)<0.1) {
		scProbe=sc;
		iprobe=i2;
		break;
	      }
	    }
	    
	    TLorentzVector vProbe(0,0,0,0);
	    vProbe.SetPtEtaPhiM(tkProbe->pt, tkProbe->eta, tkProbe->phi, ELE_MASS);
	    TLorentzVector vProbeSC(0,0,0,0);
	    vProbeSC.SetPtEtaPhiM((scProbe) ? scProbe->scEt  : tkProbe->pt,
				  tkProbe->eta, tkProbe->phi, ELE_MASS);
	    
	    // mass window
	    TLorentzVector vDilep = vTag + vProbe;
	    if((vDilep.M()<MASS_LOW) || (vDilep.M()>MASS_HIGH)) continue;
	    
	    // determine event category
	    UInt_t icat=0;
	    if(scProbe) icat=ePass;
	    else icat=eFail;

	    //******** We have a Z candidate! HURRAY! ********
	    nsel+=weight;
            nselvar+=weight*weight;

	    // Perform matching of dileptons to GEN leptons from Z decay
	    Bool_t hasGenMatch = kFALSE;
	    if(isSignal && hasGen) {

	      Bool_t match1 = ( ((glep1) && toolbox::deltaR(tag->eta, tag->phi, glep1->Eta(), glep1->Phi())<0.1) || 
				((glep2) && toolbox::deltaR(tag->eta, tag->phi, glep2->Eta(), glep2->Phi())<0.1) );

	      Bool_t match2 = ( ((glep1) && toolbox::deltaR(vProbe.Eta(), vProbe.Phi(), glep1->Eta(), glep1->Phi())<0.1) || 
				((glep2) && toolbox::deltaR(vProbe.Eta(), vProbe.Phi(), glep2->Eta(), glep2->Phi())<0.1) );
	      if(match1 && match2) {
		hasGenMatch = kTRUE;
		if (gvec!=0) {
		  genV=new TLorentzVector(0,0,0,0);
		  genV->SetPtEtaPhiM(gvec->Pt(), gvec->Eta(), gvec->Phi(), gvec->M());
		  genVPt   = gvec->Pt();
		  genVPhi  = gvec->Phi();
		  genVy    = gvec->Rapidity();
		  genVMass = gvec->M();
		}
		else {
		  TLorentzVector tvec=*lep1+*lep2;
		  genV=new TLorentzVector(0,0,0,0);
		  genV->SetPtEtaPhiM(tvec.Pt(), tvec.Eta(), tvec.Phi(), tvec.M());
		  genVPt   = tvec.Pt();
		  genVPhi  = tvec.Phi();
		  genVy    = tvec.Rapidity();
		  genVMass = tvec.M();
		}
		delete gvec;
		delete glep1;
		delete glep2;
		glep1=0; glep2=0; gvec=0;
	      }
	      else {
		genV     = new TLorentzVector(0,0,0,0);
		genVPt   = -999;
		genVPhi  = -999;
		genVy    = -999;
		genVMass = -999;
	      }
	    }

	    if (hasGen) {
	      id_1      = gen->id_1;
	      id_2      = gen->id_2;
	      x_1       = gen->x_1;
	      x_2       = gen->x_2;
	      xPDF_1    = gen->xPDF_1;
	      xPDF_2    = gen->xPDF_2;
	      scalePDF  = gen->scalePDF;
	      weightPDF = gen->weight;
	    }
	    else {
	      id_1      = -999;
	      id_2      = -999;
	      x_1       = -999;
	      x_2       = -999;
	      xPDF_1    = -999;
	      xPDF_2    = -999;
	      scalePDF  = -999;
	      weightPDF = -999;
	    }

	    //
	    // Fill tree
	    //
	    runNum   = info->runNum;
	    lumiSec  = info->lumiSec;
	    evtNum   = info->evtNum;

	    if (hasGenMatch) matchGen=1;
            else matchGen=0;

	    category = icat;
	    npv      = 0; 
	    npu      = info->nPU;
	    scale1fb = weight;
	    met      = info->pfMET;
	    metPhi   = info->pfMETphi;
	    sumEt    = 0;
	    tkMet    = info->trkMET;
	    tkMetPhi = info->trkMETphi;
	    tkSumEt  = 0;
	    mvaMet   = info->mvaMET;
            mvaMetPhi = info->mvaMETphi;
	    mvaSumEt = 0;
            ppMet    = 0;
            ppMetPhi = 0;
	    ppSumEt  = 0;
	    lep1     = &vTag;
	    lep2     = &vProbe;
	    dilep    = &vDilep;
	    q1       = tag->q;
	    q2       = (tkProbe) ? tkProbe->q : -(tag->q);

	    TVector2 vZPt((vDilep.Pt())*cos(vDilep.Phi()),(vDilep.Pt())*sin(vDilep.Phi()));        
            TVector2 vMet((info->pfMET)*cos(info->pfMETphi), (info->pfMET)*sin(info->pfMETphi));        
            TVector2 vU = -1.0*(vMet+vZPt);
            u1 = ((vDilep.Px())*(vU.Px()) + (vDilep.Py())*(vU.Py()))/(vDilep.Pt());  // u1 = (pT . u)/|pT|
            u2 = ((vDilep.Px())*(vU.Py()) - (vDilep.Py())*(vU.Px()))/(vDilep.Pt());  // u2 = (pT x u)/|pT|

            TVector2 vTkMet((info->trkMET)*cos(info->trkMETphi), (info->trkMET)*sin(info->trkMETphi));        
            TVector2 vTkU = -1.0*(vTkMet+vZPt);
            tkU1 = ((vDilep.Px())*(vTkU.Px()) + (vDilep.Py())*(vTkU.Py()))/(vDilep.Pt());  // u1 = (pT . u)/|pT|
            tkU2 = ((vDilep.Px())*(vTkU.Py()) - (vDilep.Py())*(vTkU.Px()))/(vDilep.Pt());  // u2 = (pT x u)/|pT|

	    TVector2 vMvaMet((info->mvaMET)*cos(info->mvaMETphi), (info->mvaMET)*sin(info->mvaMETphi));
            TVector2 vMvaU = -1.0*(vMvaMet+vZPt);
            mvaU1 = ((vDilep.Px())*(vMvaU.Px()) + (vDilep.Py())*(vMvaU.Py()))/(vDilep.Pt());  // u1 = (pT . u)/|pT|
            mvaU2 = ((vDilep.Px())*(vMvaU.Py()) - (vDilep.Py())*(vMvaU.Px()))/(vDilep.Pt());  // u2 = (pT x u)/|pT|

	    //TVector2 vPpMet((info->ppMET)*cos(info->ppMETphi), (info->ppMET)*sin(info->ppMETphi));
            //TVector2 vPpU = -1.0*(vPpMet+vZPt);
            //ppU1 = ((vDilep.Px())*(vPpU.Px()) + (vDilep.Py())*(vPpU.Py()))/(vDilep.Pt());  // u1 = (pT . u)/|pT|
            //ppU2 = ((vDilep.Px())*(vPpU.Py()) - (vDilep.Py())*(vPpU.Px()))/(vDilep.Pt());  // u2 = (pT x u)/|pT|
	  
	    ///// electron specific ///// 
	    sc1        = &vTagSC;
	    trkIso1    = tag->trkIso;
	    emIso1     = tag->ecalIso;
	    hadIso1    = tag->hcalIso;
	    pfChIso1   = tag->chHadIso;
	    pfGamIso1  = tag->gammaIso;	    
	    pfNeuIso1  = tag->neuHadIso;
	    pfCombIso1 = tag->chHadIso + TMath::Max(tag->neuHadIso + tag->gammaIso - 
						    (info->rhoIso)*getEffAreaEl(tag->eta), 0.);
	    /*	    sigieie1   = tag->sieie;
	    hovere1    = tag->hovere;
	    eoverp1    = tag->eoverp;
	    fbrem1     = tag->fbrem;
	    dphi1      = tag->dPhiIn;
	    deta1      = tag->dEtaIn;
	    ecalE1     = 0;
	    d01        = tag->d0;
	    dz1        = tag->dz;
	    isConv1    = tag->isConv;
	    nexphits1  = tag->nMissingHits;
	    typeBits1  = tag->typeBits;*/

	    sc2        = &vProbeSC;
	    trkIso2    = (tkProbe) ? tkProbe->trkIso        : -1;
	    emIso2     = (tkProbe) ? tkProbe->ecalIso       : -1;
	    hadIso2    = (tkProbe) ? tkProbe->hcalIso       : -1;
	    pfChIso2   = (tkProbe) ? tkProbe->chHadIso      : -1;
	    pfGamIso2  = (tkProbe) ? tkProbe->gammaIso      : -1;
	    pfNeuIso2  = (tkProbe) ? tkProbe->neuHadIso     : -1;	    
	    pfCombIso2 = (tkProbe) ? 
	      tkProbe->chHadIso + TMath::Max(tkProbe->neuHadIso + tkProbe->gammaIso - 
					      (info->rhoIso)*getEffAreaEl(tkProbe->eta), 0.) :  -1;
	    /*	    sigieie2   = (tkProbe) ? tkProbe->sieie         : scProbe->sieie;
	    hovere2    = (tkProbe) ? tkProbe->hovere        : scProbe->hovere;
	    eoverp2    = (tkProbe) ? tkProbe->eoverp        : -1;
	    fbrem2     = (tkProbe) ? tkProbe->fbrem         : -1;
	    dphi2      = (tkProbe) ? tkProbe->dPhiIn        : -999;
	    deta2      = (tkProbe) ? tkProbe->dEtaIn        : -999;
	    ecalE2     = (tkProbe) ? 0    : -999;
	    d02        = (tkProbe) ? tkProbe->d0            : -999;
	    dz2        = (tkProbe) ? tkProbe->dz            : -999;
	    isConv2    = (tkProbe) ? tkProbe->isConv        : 0;
	    nexphits2  = (tkProbe) ? tkProbe->nMissingHits  : 0;
	    typeBits2  = (tkProbe) ? tkProbe->typeBits      : 0; */

	    outTree->Fill();
	    delete genV;
	    genV=0, dilep=0, lep1=0, lep2=0, sc1=0, sc2=0;
	  }
	}
      }
      delete infile;
      infile=0, eventTree=0;    

      cout << nsel  << " +/- " << sqrt(nselvar);
      if(isam!=0) cout << " per 1/fb";
      cout << endl;
    }
    outFile->Write();
    outFile->Close(); 
  }
  delete info;
  delete gen;
  delete genPartArr;
  delete electronArr;
  delete scArr;
    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  cout << " Z -> e e" << endl;
  cout << "  Mass window: [" << MASS_LOW << ", " << MASS_HIGH << "]" << endl;
  cout << "  pT > " << PT_CUT << endl;
  cout << "  |eta| < " << ETA_CUT << endl;
  if(doScaleCorr)
    cout << "  *** Scale corrections applied ***" << endl;
  cout << endl;
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;  
      
  gBenchmark->Show("selectZee"); 
}
Example #17
0
void ReadTree_normDet(){

  bool testrun          = 0;
  const int norder_     = 2;
  const int QnBinOrder_ = 2;
  const double vtxCut   = 15.;

  static const int ptBinMin  = 0;
  static const int ptBinMax  = nptbinsDefault-1;
  static const int etaBinMin = 0; //0;
  static const int etaBinMax = netabinsDefault-1;

  TFile * fAna;
  TTree * tree;
  double centval;
  double vtx;
  TH2D * sumw;
  TH2D * sumwqx;
  TH2D * sumwqy;
  TH2I * hMult;
  double qnHFx_EP[NumEPNames];
  double qnHFy_EP[NumEPNames];
  double sumET_EP[NumEPNames];

  TFile * fQNDet;
  TH1D * hqnHFDet_x[NumEPNames];
  TH1D * hqnHFDet_y[NumEPNames];

  TFile * fQN;
  TH1D * hqbins[NCENT][NEPSymm];

  TFile * fVNDet;
  TH2D * hVNDetX_0[NQN];
  TH2D * hVNDetY_0[NQN];
  TH2D * hVNDetX_1[NQN];
  TH2D * hVNDetY_1[NQN];
  TH2D * hVNDetX_full[NQN];
  TH2D * hVNDetY_full[NQN];

  TFile * fHists;
  TDirectory * qwebye;
  TH2D * hVn2Dfull[NCENT][NEPSymm][NQN];
  TH2D * hVn2Dsub0[NCENT][NEPSymm][NQN];
  TH2D * hVn2Dsub1[NCENT][NEPSymm][NQN];
  TH2D * hVn2D0v1[NCENT][NEPSymm][NQN];
  TH1D * hVnFull[NCENT][NEPSymm][NQN];
  TH1D * hVnSub0[NCENT][NEPSymm][NQN];
  TH1D * hVnSub1[NCENT][NEPSymm][NQN];
  TH1I * Mult[NCENT][NEPSymm][NQN];
  TH2D * h2Vn2D0v1[NCENT][NEPSymm][NQN];
  TH1D * h2Vn2D0v1Magnitude[NCENT][NEPSymm][NQN];

  double VnRaw_x_0;
  double VnRaw_y_0;
  double VnRaw_x_1;
  double VnRaw_y_1;
  double VnRaw_x_full;
  double VnRaw_y_full;

  double sumw_0;
  double sumw_1;
  double sumw_full;

  double VnCorrected_x_0;
  double VnCorrected_y_0;
  double VnCorrected_x_1;
  double VnCorrected_y_1;
  double VnCorrected_x_full;
  double VnCorrected_y_full;

  int evtMult_0;
  int evtMult_1;
  int evtMult_full;

  //
  // MAIN
  //
  setTDRStyle();
  TH1D::SetDefaultSumw2();
  TH2D::SetDefaultSumw2();
  TH1I::SetDefaultSumw2();

  //-- Set up analyzer objects
  fAna = new TFile(fAnaTreeName);

  tree   = (TTree *) fAna->Get("ebyeana/tree");
  sumwqx = new TH2D(Form("sumwqx%i", norder_), Form("sumwqx%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumwqy = new TH2D(Form("sumwqy%i", norder_), Form("sumwqy%i", norder_), nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  sumw   = new TH2D("sumw",                    "sumw",                    nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);
  hMult  = new TH2I("hMult",                   "hMult",                   nptbinsDefault, ptbinsDefault, netabinsDefault, etabinsDefault);

  tree->SetBranchAddress("Cent",                    &centval);
  tree->SetBranchAddress("Vtx",                     &vtx);
  tree->SetBranchAddress("mult",                    &hMult);
  tree->SetBranchAddress(Form("sumwqx%i", norder_), &sumwqx);
  tree->SetBranchAddress(Form("sumwqy%i", norder_), &sumwqy);
  tree->SetBranchAddress("sumw",                    &sumw);
  tree->SetBranchAddress("qnHFx_EP",                &qnHFx_EP);
  tree->SetBranchAddress("qnHFy_EP",                &qnHFy_EP);
  tree->SetBranchAddress("sumET_EP",                &sumET_EP);

  //-- Get the QN Detector histograms
  fQNDet = new TFile( Form("../../../../../../v%i/eta2.4/systematicStudies/vtxCut/vtx3_15/AnalyzerResults/Q%iDet.root", QnBinOrder_, QnBinOrder_) );
  for(int iEP = 0; iEP < NumEPNames; iEP++){
    int EPbin  = EPSymmPartnerBin[iEP];
    if( EPbin != EPSymmBin ) continue;
    hqnHFDet_x[iEP] = (TH1D*) fQNDet->Get( Form("hqnHFDet_x_%s", EPNames[iEP].data()) );
    hqnHFDet_y[iEP] = (TH1D*) fQNDet->Get( Form("hqnHFDet_y_%s", EPNames[iEP].data()) );
  }

  //-- Setup the QN binning objects
  fQN = new TFile( Form( "../../../../../../v%i/eta2.4/systematicStudies/vtxCut/vtx3_15/AnalyzerResults/q%iCuts.root", QnBinOrder_, QnBinOrder_) );
  for(int icent = 0; icent < NCENT; icent++){
    for(int iEP = 0; iEP < NEPSymm; iEP++){
      if( iEP != EPSymmBin ) continue;
      hqbins[icent][iEP] = (TH1D*) fQN->Get( Form("hqbins_%s_c%i", EPSymmNames[iEP].data(), icent) );
    }
  }

  //-- Set up VN detector objects 
  fVNDet = new TFile( Form("V%iDet.root", norder_ ) );
  for(int iqn = 0; iqn < NQN; iqn++){
    hVNDetX_0[iqn]    = (TH2D*) fVNDet->Get( Form("SubEvt_0/hVNDetX_0_qbin%i",   iqn) );
    hVNDetY_0[iqn]    = (TH2D*) fVNDet->Get( Form("SubEvt_0/hVNDetY_0_qbin%i",   iqn) );
    hVNDetX_1[iqn]    = (TH2D*) fVNDet->Get( Form("SubEvt_1/hVNDetX_1_qbin%i",   iqn) );
    hVNDetY_1[iqn]    = (TH2D*) fVNDet->Get( Form("SubEvt_1/hVNDetY_1_qbin%i",   iqn) );
    hVNDetX_full[iqn] = (TH2D*) fVNDet->Get( Form("FullEvt/hVNDetX_full_qbin%i", iqn) );
    hVNDetY_full[iqn] = (TH2D*) fVNDet->Get( Form("FullEvt/hVNDetY_full_qbin%i", iqn) );
  }

  //-- Setup the output objects
  fHists = new TFile("CastleEbyE.root","recreate");
  qwebye = (TDirectory*) fHists->mkdir("qwebye");

  for(int iqn = 0; iqn < NQN; iqn++){
    for(int icent = 0; icent < NCENT; icent++){
      for(int iEP = 0; iEP < NEPSymm; iEP++){    
	if( iEP != EPSymmBin ) continue;

	qwebye->cd();
	hVn2Dfull[icent][iEP][iqn]          = new TH2D(Form("hVn2Dfull_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVn2Dfull_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	hVn2Dfull[icent][iEP][iqn]->SetOption("colz");
	hVn2Dfull[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs}", norder_) );
	hVn2Dfull[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs}", norder_) );

	hVn2Dsub0[icent][iEP][iqn]          = new TH2D( Form("hVn2Dsub0_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVn2Dsub0_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	hVn2Dsub0[icent][iEP][iqn]->SetOption("colz");
	hVn2Dsub0[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,a}", norder_) );
	hVn2Dsub0[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,a}", norder_) );

	hVn2Dsub1[icent][iEP][iqn]          = new TH2D( Form("hVn2Dsub1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVn2Dsub1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	hVn2Dsub1[icent][iEP][iqn]->SetOption("colz");
	hVn2Dsub1[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,b}", norder_) );
	hVn2Dsub1[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,b}", norder_) );

	hVn2D0v1[icent][iEP][iqn]           = new TH2D( Form("hVn2D0v1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVn2D0v1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	hVn2D0v1[icent][iEP][iqn]->SetOption("colz");
	hVn2D0v1[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b}", norder_, norder_) );
	hVn2D0v1[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("v_{%i,y}^{obs,a} - v_{%i,y}^{obs,b}", norder_, norder_) );

	hVnFull[icent][iEP][iqn]            = new TH1D( Form("hVnFull_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVnFull_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), NBins, 0., vnMax[norder_] );
	hVnFull[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i}", norder_) );
	hVnFull[icent][iEP][iqn]->GetYaxis()->SetTitle( "Events" );

	hVnSub0[icent][iEP][iqn]            = new TH1D( Form("hVnSub0_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVnSub0_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), NBins, 0., vnMax[norder_] );
	hVnSub0[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i}^{obs,a}", norder_) );

	hVnSub1[icent][iEP][iqn]            = new TH1D( Form("hVnSub1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("hVnSub1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), NBins, 0., vnMax[norder_] );
	hVnSub1[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("v_{%i}^{obs,b}", norder_) );

	Mult[icent][iEP][iqn]               = new TH1I( Form("Mult_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("Mult_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 300, 1, 1500 );
	Mult[icent][iEP][iqn]->GetXaxis()->SetTitle("Multiplicity");

	h2Vn2D0v1[icent][iEP][iqn]          = new TH2D( Form("h2Vn2D0v1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("h2Vn2D0v1_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), 2*NBins, -vnMax[norder_], vnMax[norder_], 2*NBins, -vnMax[norder_], vnMax[norder_] );
	h2Vn2D0v1[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("(v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b})/2", norder_, norder_) );
	h2Vn2D0v1[icent][iEP][iqn]->GetYaxis()->SetTitle( Form("(v_{%i,y}^{obs,a} - v_{%i,y}^{obs,b})/2", norder_, norder_) );
	h2Vn2D0v1[icent][iEP][iqn]->SetOption("colz");

	h2Vn2D0v1Magnitude[icent][iEP][iqn] = new TH1D( Form("h2Vn2D0v1Magnitude_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), Form("h2Vn2D0v1Magnitude_%s_c%i_qbin%i", EPSymmNames[iEP].data(), icent, iqn), NBins, 0., vnMax[norder_] );
	h2Vn2D0v1Magnitude[icent][iEP][iqn]->GetXaxis()->SetTitle( Form("|(v_{%i,x}^{obs,a} - v_{%i,x}^{obs,b})/2|", norder_, norder_) );

      }
    } 
  }
    
  //
  // Tree Loop
  //
    
  cout<<"Begin FINAL loop, contains "<<tree->GetEntries()<<" Events"<<endl;
    
  int N;
  if( testrun ) N = 10000;
  else          N = tree->GetEntries();

  for(int ievent = 0; ievent < N; ievent++) {
        
    if((ievent+1)% 500000 == 0) cout<<"Processing Event "<<ievent+1<<"\t"<<100.*(ievent+1)/(double)N<<"% Completed"<<endl;
      
    tree->GetEntry(ievent);

    //-- Vertex Cut
    if(TMath::Abs(vtx) < 3. || TMath::Abs(vtx) > 15.) continue;

    //-- Calculate centbin
    if( centval > cent_max[NCENT-1]) continue;
    int icent = hCentBins.FindBin(centval)-1;

    //-- begin EP loop
    for(int iEP = 0; iEP < NEP; iEP++){

      int EPbin  = EPSymmPartnerBin[iEP];
      if( EPbin != EPSymmBin ) continue;

      //-- Calculate qbin
      double qx    = qnHFx_EP[iEP];
      double qy    = qnHFy_EP[iEP];
      double qxDet = hqnHFDet_x[iEP]->GetBinContent(icent+1);
      double qyDet = hqnHFDet_y[iEP]->GetBinContent(icent+1);
      double sumET = sumET_EP[iEP];
      if(sumET == 0) continue;
      qx -= qxDet;
      qy -= qyDet;
      qx /= sumET;
      qy /= sumET;
      double qn = TMath::Sqrt( qx*qx + qy*qy );
      int   iqn = hqbins[icent][EPbin]->FindBin( qn ) - 1;
      if(iqn >= NQN) continue;

      //-- Reset raw and sumw values
      VnRaw_x_0    = 0;
      VnRaw_y_0    = 0;
      VnRaw_x_1    = 0;
      VnRaw_y_1    = 0;
      VnRaw_x_full = 0;
      VnRaw_y_full = 0;                

      sumw_0       = 0;
      sumw_1       = 0;
      sumw_full    = 0;

      evtMult_0    = 0;
      evtMult_1    = 0;
      evtMult_full = 0;

      //-- Begin analyzer histogram loops
      for(int ipt = ptBinMin; ipt <= ptBinMax; ipt++){
	for(int ieta = etaBinMin; ieta <= etaBinMax; ieta++){

	  if(sumw->GetBinContent(ipt+1,ieta+1) !=0){

	    //-- Subevent 0 (eta >= 0)
	    if(etabinsDefault[ieta] >= 0){
	      VnRaw_x_0     += sumwqx->GetBinContent(ipt+1,ieta+1);
	      VnRaw_y_0     += sumwqy->GetBinContent(ipt+1,ieta+1);
	      sumw_0        += sumw->GetBinContent(ipt+1,ieta+1);
	      evtMult_0     += hMult->GetBinContent(ipt+1,ieta+1);
	    }
	    //-- Subevent 1 (eta < 0)
	    else{
	      VnRaw_x_1     += sumwqx->GetBinContent(ipt+1,ieta+1);
	      VnRaw_y_1     += sumwqy->GetBinContent(ipt+1,ieta+1);
	      sumw_1        += sumw->GetBinContent(ipt+1,ieta+1);
	      evtMult_1     += hMult->GetBinContent(ipt+1,ieta+1);
	    }
	    //-- Full Event
	    VnRaw_x_full    += sumwqx->GetBinContent(ipt+1,ieta+1);
	    VnRaw_y_full    += sumwqy->GetBinContent(ipt+1,ieta+1);
	    sumw_full       += sumw->GetBinContent(ipt+1,ieta+1);
	    evtMult_full    += hMult->GetBinContent(ipt+1,ieta+1);

	  }

	} //-- End eta loop
      } //-- End pt loop

      //-- Fill Histograms, only use events that have at least two tracks in each SE
      if(sumw_0 == 0 || sumw_1 == 0 || evtMult_1 < 2 || evtMult_full < 2) continue;

      VnRaw_x_full /= sumw_full;
      VnRaw_y_full /= sumw_full;
	
      VnRaw_x_0 /= sumw_0;
      VnRaw_y_0 /= sumw_0;
	
      VnRaw_x_1 /= sumw_1;
      VnRaw_y_1 /= sumw_1;
                
      //-- Full Tracker
      VnCorrected_x_full = VnRaw_x_full - hVNDetX_full[iqn]->GetBinContent(icent+1, EPbin+1);
      VnCorrected_y_full = VnRaw_y_full - hVNDetY_full[iqn]->GetBinContent(icent+1, EPbin+1);
      double vn_full     = TMath::Sqrt( VnCorrected_x_full * VnCorrected_x_full +  VnCorrected_y_full * VnCorrected_y_full);

      hVnFull[icent][EPbin][iqn]   -> Fill( vn_full );
      hVn2Dfull[icent][EPbin][iqn] -> Fill(VnCorrected_x_full, VnCorrected_y_full);

      Mult[icent][EPbin][iqn]->Fill(evtMult_full);

      //-- SubEvt 0 (Eta > 0)
      VnCorrected_x_0 = VnRaw_x_0 - hVNDetX_0[iqn]->GetBinContent(icent+1, EPbin+1);
      VnCorrected_y_0 = VnRaw_y_0 - hVNDetY_0[iqn]->GetBinContent(icent+1, EPbin+1);
      double vn_0     = TMath::Sqrt( VnCorrected_x_0 * VnCorrected_x_0 + VnCorrected_y_0 * VnCorrected_y_0 );

      hVnSub0[icent][EPbin][iqn]   -> Fill( vn_0 );
      hVn2Dsub0[icent][EPbin][iqn] -> Fill(VnCorrected_x_0, VnCorrected_y_0);
                
      //-- SubEvt 1 (Eta < 0)
      VnCorrected_x_1 = VnRaw_x_1 - hVNDetX_1[iqn]->GetBinContent(icent+1, EPbin+1);
      VnCorrected_y_1 = VnRaw_y_1 - hVNDetY_1[iqn]->GetBinContent(icent+1, EPbin+1);
      double vn_1     = TMath::Sqrt( VnCorrected_x_1 * VnCorrected_x_1 + VnCorrected_y_1 *VnCorrected_y_1 );

      hVnSub1[icent][EPbin][iqn]   -> Fill( vn_1 );
      hVn2Dsub1[icent][EPbin][iqn] -> Fill(VnCorrected_x_1, VnCorrected_y_1);

      //-- SubEvt Difference
      double vn0m1_x = VnCorrected_x_0 - VnCorrected_x_1;
      double vn0m1_y = VnCorrected_y_0 - VnCorrected_y_1;
      hVn2D0v1[icent][EPbin][iqn]->Fill(vn0m1_x, vn0m1_y);	

      //-- SubEvt Difference for DD response
      double vn0m1_x2 = (VnCorrected_x_0 - VnCorrected_x_1) / 2.;
      double vn0m1_y2 = (VnCorrected_y_0 - VnCorrected_y_1) / 2.;
      h2Vn2D0v1[icent][EPbin][iqn]->Fill(vn0m1_x2, vn0m1_y2);

      double vn0m12 = TMath::Sqrt( pow(vn0m1_x2, 2) + pow(vn0m1_y2, 2) );
      h2Vn2D0v1Magnitude[icent][EPbin][iqn]->Fill(vn0m12);

    } //-- End EP loop        

  } //-- End Event loop

  cout<<"End FINAL loop!"<<endl;
        
  fHists->Write();
  cout<<"File written, process completed"<<endl;
    
}
int main(int argc, char *argv[])
{    
    /////////********* Beam Variables
    double vBeamMomentum = 400. * GeV;
    double vParticleMass = cProtonMass;
    double vParticleCharge = +1.;
    
    double vMeanIncomingAngleX = 3. * microrad;
    double vVarianceIncomingAngleX = 0. * microrad;
    unsigned int vBeamAngleDistributionType = 1;
    
    unsigned int vMultipleScatteringModel = 0;
    unsigned int vFormFactorType = 2;

    /////////********* Crystal Variables
    unsigned int vIntegrationStepNumber = 512;
    float vCrystalLenght = 1.96 * millimeter;
    std::vector<double> vSecondaryCurvature;

//        vSecondaryCurvature.push_back(28.41);
//        vSecondaryCurvature.push_back(18.40);
//        vSecondaryCurvature.push_back(6.76);
//        vSecondaryCurvature.push_back(3.54);
//        vSecondaryCurvature.push_back(2.31);
    vSecondaryCurvature.push_back(0.);
    
    //for(unsigned int i=0;i<3;i++) vSecondaryCurvature.push_back(i * meter * 0.1 + 0.7);
    //for(unsigned int i=0;i<9;i++) vSecondaryCurvature.push_back(i * meter * 1.0 + 1.0);
    //for(unsigned int i=0;i<5;i++) vSecondaryCurvature.push_back(i * meter * 5.0 + 10.0);

    int vMillerPl[3] = {2,2,0};
    int vMillerAx[3] = {1,1,1};
    
    /////////********* Temporary Variables
    time_t vInitialTime = time (NULL);
    
    
    /////////********* TFile & TTree Inizialization
    
    std::string vRootFileName = "analytical_complete.root";
    TFile *vRootFile = new TFile(vRootFileName.c_str(),"RECREATE");

    /////////********* 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
    
    ECHARM_crystal_reciprocal *crystal_reciprocal = new ECHARM_crystal_reciprocal(crystal_base);
    crystal_reciprocal->FindPlanarFourierCoefficient();
         
    /////////********* Beam Inizialization
    ECHARM_distribution *vDistributionParticlePositionX = new ECHARM_distribution();
    vDistributionParticlePositionX->SetDistributionType(0);
    vDistributionParticlePositionX->SetDistributionParameter(0,crystal_reciprocal->GetDirectPeriodPlanar() * 1.0 / 2.0);
    vDistributionParticlePositionX->SetDistributionParameter(1,crystal_reciprocal->GetDirectPeriodPlanar() * 1.0 / 2.0);
    
    ECHARM_distribution *vDistributionParticleMomentumX = new ECHARM_distribution();
    vDistributionParticleMomentumX->SetDistributionType(vBeamAngleDistributionType);
    vDistributionParticleMomentumX->SetDistributionParameter(0,vMeanIncomingAngleX*vBeamMomentum);
    vDistributionParticleMomentumX->SetDistributionParameter(1,vVarianceIncomingAngleX*vBeamMomentum);
        
    ECHARM_crystal_interpolation *vCrystal = new ECHARM_crystal_interpolation(crystal_reciprocal);
    
    ECHARM_threevector *vStripCurvatureRadius = new ECHARM_threevector(vSecondaryCurvature[0],0.,0.);
    ECHARM_threevector *vStripDimension = new ECHARM_threevector(1.*millimeter,1.*millimeter,vCrystalLenght);
    ECHARM_strip *vStrip = new ECHARM_strip(vCrystal,vStripDimension,vStripCurvatureRadius);
    
    ECHARM_threevector *vParticlePositionVector = new ECHARM_threevector(0.0*AA,0.0*AA,0.);;
    ECHARM_threevector *vParticleMomentumVector = new ECHARM_threevector(0.,0.,vBeamMomentum);
    ECHARM_particle* vParticle = new ECHARM_particle(vParticleCharge,vParticleMass,vParticleMomentumVector,vParticlePositionVector);
        
    ECHARM_simulation_integration_averaged* vSimulationAveraged = new ECHARM_simulation_integration_averaged(vStrip,vParticle);
    vSimulationAveraged->SetStepLengthMin(2.E-8 / vBeamMomentum * (400. * GeV));
    vSimulationAveraged->SetTransverseVariationMax(2.E-10 / vBeamMomentum * (400. * GeV));
    vSimulationAveraged->GetMultipleScattering()->SetNuclearScatteringModel(vMultipleScatteringModel);
    vSimulationAveraged->SetIntegrationStepNumberPlanar(vIntegrationStepNumber);

    TH1D *total = new TH1D("total","total;Curvature Radius [R/R_{c}];Efficiency [%]",int(vSecondaryCurvature.size() * 10)+1,-0.5,vSecondaryCurvature.size()+0.5);
    TGraph *gTot = new TGraph( vSecondaryCurvature.size() );
    gTot->SetTitle("Graph");
    gTot->SetName("gTot");
    
    double vResult = 0.0;
    for(unsigned int k=0;k<vSecondaryCurvature.size();k++)
    {
        std::cout << "Radius [ " << k << " of " << vSecondaryCurvature.size() << " ]" << " = " << vSecondaryCurvature.at(k) << std::endl;
        vStrip->GetCurvatureRadius()->Set(vSecondaryCurvature.at(k),0.,0.);
        vParticle->GetPositionVector()->Set(0.0,0.0,0.0);
        vParticle->GetMomentumVector()->Set(vBeamMomentum*vMeanIncomingAngleX,0.0,vBeamMomentum);
 
        vParticle->PrintParticleProperties();
        vSimulationAveraged->PrintChannelingProperties();
                
        vSimulationAveraged->PreInitializeEnergyToDechannel();
        vSimulationAveraged->PreInitializePlanarDensityOverOnePeriod();
        
        vResult = vSimulationAveraged->GetAveragedDechannelingProbability();
        total->SetBinContent( total->GetXaxis()->FindBin(k), vResult);
        gTot->SetPoint(k,vSecondaryCurvature.at(k),vResult);
        
        std::cout << " --- Time Elapsed (m): " << std::setw(10) << float(time(NULL) - vInitialTime)/60. << std::endl;
    }
    gDirectory->Append(gTot);
    vRootFile->Write(); // write ROOT file
    vRootFile->Close(); // close ROOT file
    return 0;
}
Example #19
0
int main(int argc, char** argv){//main  

  if (argc < 7) {
    std::cout << " Usage: " 
	      << argv[0] << " <nEvts to process (0=all)>"
	      << " <path to input files>"
	      << " <name of input sim file>"
	      << " <name of input reco file>"
	      << " <full path to output file>"
	      << " <number of si layers to consider: 1,2 or 3>" 
      //<< " <generated E>"
	      << " <optional: debug (default=0)>"
	      << std::endl;
    return 1;
  }

  //////////////////////////////////////////////////////////
  //// Hardcoded config ////////////////////////////////////
  //////////////////////////////////////////////////////////
  bool concept = true;

  //for xvsy plots
  double minX=-1700,maxX=1700;
  double minY=-1700,maxY=1700;
  double minZ=3170,maxZ=3370;
  //double minX=-510,maxX=510;
  //double minY=-510,maxY=510;
  //double minZ=-1000,maxZ=1000;

  unsigned nX=(maxX-minX)/10,nY=(maxY-minY)/10;
  unsigned nZ=maxZ-minZ;

  //size of signal region to perform Chi2 position fit.
  //in units of 2.5mm cells to accomodate different granularities
  unsigned nSR = 12;

  //maximum value of residuals to use in error matrix: discard positions that are too far away 
  double residualMax = 25;//mm

  //////////////////////////////////////////////////////////
  //// End Hardcoded config ////////////////////////////////////
  //////////////////////////////////////////////////////////

  const unsigned pNevts = atoi(argv[1]);
  std::string filePath = argv[2];
  std::string simFileName = argv[3];
  std::string recoFileName = argv[4];

  std::string inFilePath = filePath+simFileName;

  std::string outPath = argv[5];
  unsigned nSiLayers = 2;
  nSiLayers = atoi(argv[6]);

  //unsigned genEn;
  //genEn = atoi(argv[7]);

  unsigned debug = 0;
  if (argc >7) debug = atoi(argv[7]);

  size_t end=outPath.find_last_of(".");
  std::string outFolder = outPath.substr(0,end);

  std::cout << " -- Input parameters: " << std::endl
	    << " -- Input file path: " << filePath << std::endl
	    << " -- Output file path: " << outPath << std::endl
	    << " -- Output folder: " << outFolder << std::endl
    //<< " -- Generated energy: " << genEn << std::endl
	    << " -- Requiring " << nSiLayers << " si layers." << std::endl
	    << " -- Number cells in signal region for fit: " << nSR << " *2.5*2.5 mm^2 cells" << std::endl
	    << " -- Processing ";
  if (pNevts == 0) std::cout << "all events." << std::endl;
  else std::cout << pNevts << " events." << std::endl;

  TRandom3 lRndm(1);
  std::cout << " -- Random number seed: " << lRndm.GetSeed() << std::endl;

  /////////////////////////////////////////////////////////////
  //input
  /////////////////////////////////////////////////////////////

  std::ostringstream input;
  input << filePath << "/" << simFileName;

  TFile *simFile = TFile::Open(input.str().c_str());

  if (!simFile) {
    std::cout << " -- Error, input file " << input.str() << " cannot be opened. Exiting..." << std::endl;
    return 1;
  }
  else std::cout << " -- input file " << simFile->GetName() << " successfully opened." << std::endl;
  
  TTree *lSimTree = (TTree*)simFile->Get("HGCSSTree");
  if (!lSimTree){
    std::cout << " -- Error, tree HGCSSTree cannot be opened. Exiting..." << std::endl;
    return 1;
  }

  input.str("");
  input << filePath << "/" << recoFileName;
  
  TFile *recFile = TFile::Open(input.str().c_str());

  if (!recFile) {
    std::cout << " -- Error, input file " << input.str() << " cannot be opened. Exiting..." << std::endl;
    return 1;
  }
  else std::cout << " -- input file " << recFile->GetName() << " successfully opened." << std::endl;

  TTree *lRecTree = (TTree*)recFile->Get("RecoTree");
  if (!lRecTree){
    std::cout << " -- Error, tree RecoTree cannot be opened. Exiting..." << std::endl;
    return 1;
  }


  /////////////////////////////////////////////////////////////
  //Info
  /////////////////////////////////////////////////////////////

  HGCSSInfo * info=(HGCSSInfo*)simFile->Get("Info");
  const double cellSize = info->cellSize();
  const unsigned versionNumber = info->version();
  const unsigned model = info->model();
  
  //models 0,1 or 3.
  bool isTBsetup = (model != 2);
  bool isCaliceHcal = versionNumber==23;//inFilePath.find("version23")!=inFilePath.npos || inFilePath.find("version_23")!=inFilePath.npos;

  //extract input energy

  std::cout << " -- Version number is : " << versionNumber 
	    << ", model = " << model
	    << ", cellSize = " << cellSize
	    << std::endl;


  //initialise detector
  HGCSSDetector & myDetector = theDetector();

  myDetector.buildDetector(versionNumber,concept,isCaliceHcal);

  //initialise calibration class
  HGCSSCalibration mycalib(inFilePath);
  HGCSSDigitisation myDigitiser;
  myDigitiser.setRandomSeed(lRndm.GetSeed());

  const unsigned nLayers = myDetector.nLayers();
  const unsigned nSections = myDetector.nSections();

  std::cout << " -- N layers = " << nLayers << std::endl
	    << " -- N sections = " << nSections << std::endl;

  HGCSSGeometryConversion geomConv(inFilePath,model,cellSize);
  //assemble in 7.5*7.5 to fill maxE
  std::vector<unsigned> granularity;
  granularity.resize(nLayers,4);
  geomConv.setGranularity(granularity);
  geomConv.initialiseHistos(false,"_10");

  //////////////////////////////////////////////////
  //////////////////////////////////////////////////
  ///////// Output histos  /////////////////////////
  //////////////////////////////////////////////////
  //////////////////////////////////////////////////

  TFile *outputFile = TFile::Open(outPath.c_str(),"RECREATE");
  
  if (!outputFile) {
    std::cout << " -- Error, output file " << outPath << " cannot be opened. Please create output directory. Exiting..." << std::endl;
    return 1;
  }
  else {
    std::cout << " -- output file " << outputFile->GetName() << " successfully opened." << std::endl;
  }
    outputFile->cd();
  TH1F *p_nSimHits = new TH1F("p_nSimHits","n(SimHits)",
			      1000,0,500000);
  p_nSimHits->StatOverflows();
  
  TH1F *p_nRecHits = new TH1F("p_nRecHits","n(RecHits)",
			      1000,0,5000);
  p_nRecHits->StatOverflows();

  TH1F *p_EsimTotal = new TH1F("p_EsimTotal",";Esim (MIPs)",5000,0,50000);
  TH1F *p_ErecoTotal = new TH1F("p_ErecoTotal",";Ereco (MIPs)",5000,0,50000);
  p_EsimTotal->StatOverflows();
  p_ErecoTotal->StatOverflows();

  TH2F *p_genxy[nLayers];
  TH2F *p_xy[nLayers];
  TH2F *p_recoxy[nLayers];

  TH1F *p_residuals_x = new TH1F("p_residuals_x",";xreco-xtruth (mm)",1000,-50,50);
  TH1F *p_residuals_y = new TH1F("p_residuals_y",";yreco-ytruth (mm)",1000,-50,50);
  p_residuals_x->StatOverflows();
  p_residuals_y->StatOverflows();

  std::ostringstream lName;
  for (unsigned iL(0); iL<nLayers; ++iL){
    lName.str("");
    lName << "p_genxy_" << iL;
    p_genxy[iL] = new TH2F(lName.str().c_str(),";x(mm);y(mm)",
			   nX*10,minX,maxX,
			   nY*10,minY,maxY);
    lName.str("");
    lName << "p_xy_" << iL;
    p_xy[iL] = new TH2F(lName.str().c_str(),";x(mm);y(mm)",
   			nX,minX,maxX,
   			nY,minY,maxY);
    lName.str("");
    lName << "p_recoxy_" << iL;
    p_recoxy[iL] = new TH2F(lName.str().c_str(),";x(mm);y(mm)",
   			    nX,minX,maxX,
   			    nY,minY,maxY);
  }

    //////////////////////////////////////////////////
    //////////////////////////////////////////////////
    ///////// Event loop /////////////////////////////
    //////////////////////////////////////////////////
    //////////////////////////////////////////////////

  HGCSSEvent * event = 0;
  std::vector<HGCSSSamplingSection> * ssvec = 0;
  std::vector<HGCSSSimHit> * simhitvec = 0;
  std::vector<HGCSSRecoHit> * rechitvec = 0;
  std::vector<HGCSSGenParticle> * genvec = 0;
  
  lSimTree->SetBranchAddress("HGCSSEvent",&event);
  lSimTree->SetBranchAddress("HGCSSSamplingSectionVec",&ssvec);
  lSimTree->SetBranchAddress("HGCSSSimHitVec",&simhitvec);
  lSimTree->SetBranchAddress("HGCSSGenParticleVec",&genvec);
  
  lRecTree->SetBranchAddress("HGCSSRecoHitVec",&rechitvec);

  const unsigned nEvts = ((pNevts > lSimTree->GetEntries() || pNevts==0) ? static_cast<unsigned>(lSimTree->GetEntries()) : pNevts) ;
  
  std::cout << "- Processing = " << nEvts  << " events out of " << lSimTree->GetEntries() << std::endl;
  
  //Initialise histos
  //necessary to have overflows ?
  gStyle->SetOptStat(1111111);
  double EtotSim[nLayers];
  double EtotRec[nLayers];
  //initialisation for error matrix
  double mean[2][nLayers];//sum residuals for x and y
  double sigma[2][nLayers][nLayers];//sum square
  unsigned nL_mean[nLayers];//number of valid layers
  unsigned nL_sigma[nLayers][nLayers];

  std::vector<double> avgZ;
  avgZ.resize(nLayers,0);


  for (unsigned iL(0);iL<nLayers;++iL){
    EtotSim[iL] = 0;
    EtotRec[iL] = 0;
    nL_mean[iL] = 0;
    mean[0][iL] = 0;
    mean[1][iL] = 0;
    for (unsigned jL(0);jL<nLayers;++jL){
      nL_sigma[iL][jL] = 0;
      sigma[0][iL][jL] = 0;
      sigma[1][iL][jL] = 0;
    }
  }



  bool firstEvent = true;

  for (unsigned ievt(0); ievt<nEvts; ++ievt){//loop on entries
    if (debug) std::cout << "... Processing entry: " << ievt << std::endl;
    else if (ievt%50 == 0) std::cout << "... Processing entry: " << ievt << std::endl;
    
    lSimTree->GetEntry(ievt);
    lRecTree->GetEntry(ievt);

    if (debug){
      std::cout << "... Size of hit vectors: sim = " <<  (*simhitvec).size() << ", reco = " << (*rechitvec).size()<< std::endl;
    }

    //////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////
    //////// output files to save position for chi2 fit //////////
    //////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////

    std::ofstream fout;
    std::ostringstream foutname;
    foutname << outFolder << "_initialPos_evt" << ievt << ".dat";
    fout.open(foutname.str());
    if (!fout.is_open()){
      std::cout << " Cannot open outfile " << foutname.str() << " for writing ! Exiting..." << std::endl;
      return 1;
    }


    //////////////////////////////////////////////////
    //////////////////////////////////////////////////
    ///////// SimHits ////////////////////////////////
    //////////////////////////////////////////////////
    //////////////////////////////////////////////////

    //loop on simhits
    double etotmips = 0;
    unsigned prevLayer = 10000;
    DetectorEnum type = DetectorEnum::FECAL;
    unsigned subdetLayer=0;

    TH2F *etavsphi = new TH2F("etavsphi",";#phi;#eta;hits",150,-3.1416,3.1416,160,1.4,3.0);

    for (unsigned iH(0); iH<(*simhitvec).size(); ++iH){//loop on hits
      HGCSSSimHit lHit = (*simhitvec)[iH];

      //discard some si layers...
      if (lHit.silayer() >= nSiLayers) continue; 

      unsigned layer = lHit.layer();

      if (layer >= nLayers) {
	//std::cout << " WARNING! SimHits with layer " << layer << " outside of detector's definition range ! Please fix the digitiser or the detector definition used here. Ignoring..." << std::endl;
	continue;
      }
      if (layer != prevLayer){
	const HGCSSSubDetector & subdet = myDetector.subDetectorByLayer(layer);
	type = subdet.type;
	subdetLayer = layer-subdet.layerIdMin;
	prevLayer = layer;
	if (debug > 1) std::cout << " - layer " << layer << " " << subdet.name << " " << subdetLayer << std::endl;
      }     

      //unsigned sec =  myDetector.getSection(layer);

      double posx = lHit.get_x(cellSize);
      double posy = lHit.get_y(cellSize);
      double posz = lHit.get_z();
      //double radius = sqrt(posx*posx+posy*posy);
      double lRealTime = mycalib.correctTime(lHit.time(),posx,posy,posz);
      double energy = lHit.energy()*mycalib.MeVToMip(layer);

      //if (energy>1) std::cout << "Hit " << layer << " " << posx << " " << posy << " " << posz << " " << energy << std::endl;

      if (type == DetectorEnum::FECAL ||
	  type == DetectorEnum::MECAL ||
	  type == DetectorEnum::BECAL){
	//correct for si thickness
	//default for 200um
	energy *= 2./nSiLayers;
      }
      
      geomConv.fill(type,subdetLayer,energy,lRealTime,posx,posy,posz);

      bool passTime = myDigitiser.passTimeCut(type,lRealTime);
      if (!passTime) continue;

      if (debug>1) {
	std::cout << " --  SimHit " << iH << "/" << (*simhitvec).size() << " --" << std::endl
		  << " --  position x,y " << posx << "," << posy << std::endl;
	lHit.Print(std::cout);
      }

      EtotSim[layer] += energy;
      p_xy[layer]->Fill(posx,posy,energy);

      ROOT::Math::XYZVector pos(posx,posy,posz);
      etavsphi->Fill(pos.phi(),pos.eta(),energy);

      //double absweight = myDetector.subDetectorByLayer(layer).absWeight;
      double absweight = (*ssvec)[layer].volX0trans()/(*ssvec)[1].volX0trans();

      //if (versionNumber==12){
	//absweight = layer%2==0 ?
	//(*ssvec)[layer].volX0trans()/refThicknessEven : 
	//(*ssvec)[layer].volX0trans()/refThicknessOdd;
	//}
      etotmips += energy*absweight;
      
    }//loop on hits

    p_nSimHits->Fill((*simhitvec).size());
 
    if (debug)  std::cout << std::endl;


    //get position of maximum E tower
    int maxbin = etavsphi->GetMaximumBin();
    int binx,biny,binz;
    etavsphi->GetBinXYZ(maxbin,binx,biny,binz);
    double phimax =etavsphi->GetXaxis()->GetBinCenter(binx); 
    double etamax =etavsphi->GetYaxis()->GetBinCenter(biny); 

    //std::cout << " MaxE cell eta,phi = " << etamax << " " << phimax << std::endl;
    //////////////////////////////////////////////////
    //////////////////////////////////////////////////
    ///////// GenParticles////////////////////////////
    //////////////////////////////////////////////////
    //////////////////////////////////////////////////

    //get truth position

    std::vector<ROOT::Math::XYPoint> truthPos;
    truthPos.resize(nLayers,ROOT::Math::XYPoint());

    for (unsigned iP(0); iP<(*genvec).size(); ++iP){//loop on gen particles    
      //if ((*genvec).size()!= 1) (*genvec)[iP].Print(std::cout);
      if ((*genvec)[iP].trackID()==1){
	double x0 = (*genvec)[iP].x();
	double y0 = (*genvec)[iP].y();
	double z0 = (*genvec)[iP].z();
	double p = sqrt(pow((*genvec)[iP].px(),2)+pow((*genvec)[iP].py(),2)+pow((*genvec)[iP].pz(),2));
	//double energy = sqrt(pow((*genvec)[iP].mass(),2)+pow(p,2));
	//p_genxy[0]->Fill(x0,y0,energy);
	//std::cout << "init : " << x0 << " " << y0 << " " << z0 << std::endl;
	//fill layers by propagating with momentum
	ROOT::Math::XYZVector unit((*genvec)[iP].px()/p,(*genvec)[iP].py()/p,(*genvec)[iP].pz()/p);

	//std::cout << " Gen particle eta,phi = " << unit.eta() << " " << unit.phi() << std::endl;

	for (unsigned iL(0); iL<nLayers; ++iL){
	  if (avgZ[iL]<z0) avgZ[iL] = geomConv.getAverageZ(iL);
	  if (avgZ[iL]>z0) {
	    double xy = (avgZ[iL]-z0)/sinh(unit.eta());
	    double x = xy*cos(unit.phi())+x0;
	    double y = xy*sin(unit.phi())+y0;
	    
	    //std::cout << "Lay " << iL << ": " << x << " " << y << " " << avgZ[iL] << std::endl;
	    p_genxy[iL]->Fill(x,y,1);
	    truthPos[iL] = ROOT::Math::XYPoint(x,y);
	  }
	}

      }

      //p_genPartId->Fill((*genvec)[iP].pdgid());
    }//loop on gen particles

    //////////////////////////////////////////////////
    //////////////////////////////////////////////////
    ///////// RecHits ////////////////////////////////
    //////////////////////////////////////////////////
    //////////////////////////////////////////////////

    double Etotcal = 0;
    std::vector<double> xmax;
    xmax.resize(nLayers,0);
    std::vector<double> ymax;
    ymax.resize(nLayers,0);
    std::vector<double> dRmin;
    dRmin.resize(nLayers,10);

    for (unsigned iH(0); iH<(*rechitvec).size(); ++iH){//loop on rechits
      HGCSSRecoHit lHit = (*rechitvec)[iH];
      if (debug>1) {
	std::cout << " --  RecoHit " << iH << "/" << (*rechitvec).size() << " --" << std::endl
		  << " --  position x,y " << lHit.get_x() << "," << lHit.get_y() << std::endl;
	lHit.Print(std::cout);
      }
      
      double energy = lHit.energy();//in MIP already...
      unsigned layer = lHit.layer();

      if (layer >= nLayers) {
	std::cout << " WARNING! RecoHits with layer " << layer << " outside of detector's definition range ! Please fix the digitiser or the detector definition used here. Ignoring..." << std::endl;
	continue;
      }

      double posx = lHit.get_x();
      double posy = lHit.get_y();
      double posz = lHit.get_z();
      ROOT::Math::XYZVector pos(posx,posy,posz);
      double deta = fabs(pos.eta()-etamax);
      double dphi = fabs(pos.phi()-phimax);
      double dR = sqrt(pow(deta,2)+pow(dphi,2));
      if (dR<dRmin[layer]) {
	dRmin[layer] = dR;
	xmax[layer] = posx;
	ymax[layer] = posy;
      }


      //unsigned sec =  myDetector.getSection(layer);
      
      p_recoxy[layer]->Fill(posx,posy,energy);
      EtotRec[layer] += energy;

      if (debug>1) std::cout << "-hit" << iH << "-" << layer << " " << energy << " " << EtotRec[layer];

      double absweight = (*ssvec)[layer].volX0trans()/(*ssvec)[1].volX0trans();

      Etotcal += energy*absweight;
    }//loop on rechits
    
    p_nRecHits->Fill((*rechitvec).size());

    p_EsimTotal->Fill(etotmips);
    p_ErecoTotal->Fill(Etotcal);
    
    //for (unsigned iL(0);iL<nLayers;++iL){//loop on layers
      //p_EsimvsLayer->Fill(iL,EtotSim[iL]);
      // p_ErecovsLayer->Fill(iL,EtotRec[iL]);
      //}

    //get energy-weighted position around maximum
    std::vector<ROOT::Math::XYPoint> recoPos;
    recoPos.resize(nLayers,ROOT::Math::XYPoint(0,0));
    std::vector<double> eSum;
    eSum.resize(nLayers,0);
    std::vector<unsigned> nHits;
    nHits.resize(nLayers,0);
    for (unsigned iH(0); iH<(*rechitvec).size(); ++iH){//loop on rechits
      HGCSSRecoHit lHit = (*rechitvec)[iH];
      double energy = lHit.energy();//in MIP already...
      unsigned layer = lHit.layer();
      double posx = lHit.get_x();
      double posy = lHit.get_y();
      double posz = lHit.get_z();
      double step = cellSize*nSR/2.+0.1;//+0.1 to accomodate double precision
      if (fabs(posx-xmax[layer]) < step && 
	  fabs(posy-ymax[layer]) < step){
	recoPos[layer].SetX(recoPos[layer].X() + posx*energy);
	recoPos[layer].SetY(recoPos[layer].Y() + posy*energy);
	eSum[layer] += energy;
	if (energy>0) nHits[layer]++;
      }

    }//loop on rechits


    //fill error matrix
    if (debug) std::cout << " Summary of reco and truth positions:" << std::endl;
    for (unsigned iL(0);iL<nLayers;++iL){//loop on layers
      if (nHits[iL]==0) continue;
      recoPos[iL].SetX(recoPos[iL].X()/eSum[iL]);
      recoPos[iL].SetY(recoPos[iL].Y()/eSum[iL]);
      if (debug) std::cout << iL << " nHits=" << nHits[iL] << " Max=(" << xmax[iL] << "," << ymax[iL] << ")\t Reco=(" << recoPos[iL].X() << "," << recoPos[iL].Y() << ")\t Truth=(" << truthPos[iL].X() << "," << truthPos[iL].Y() << ")" << std::endl;
      fout << iL << " " << recoPos[iL].X() << " " << recoPos[iL].Y() << " " << avgZ[iL] << " " << truthPos[iL].X() << " " << truthPos[iL].Y() << std::endl;
    }
    for (unsigned iL(0);iL<nLayers;++iL){//loop on layers
      if (nHits[iL]==0) continue;
      double residual_xi = recoPos[iL].X()-truthPos[iL].X();
      double residual_yi = recoPos[iL].Y()-truthPos[iL].Y();
      p_residuals_x->Fill(residual_xi);
      p_residuals_y->Fill(residual_yi);
      if (fabs(residual_xi)>residualMax || fabs(residual_yi)>residualMax) continue;
      mean[0][iL] += residual_xi;
      mean[1][iL] += residual_yi;
      ++nL_mean[iL];
      for (unsigned jL(0);jL<nLayers;++jL){//loop on layers
	if (nHits[jL]==0) continue;
	double residual_xj = recoPos[jL].X()-truthPos[jL].X();
	double residual_yj = recoPos[jL].Y()-truthPos[jL].Y();
	if (fabs(residual_xj)>residualMax || fabs(residual_yj)>residualMax) continue;
	double sigma_x = residual_xi*residual_xj;
	double sigma_y = residual_yi*residual_yj;
	sigma[0][iL][jL] += sigma_x;
	sigma[1][iL][jL] += sigma_y;
	++nL_sigma[iL][jL];
      }//loop on layers
    }//loop on layers

    geomConv.initialiseHistos();
    etavsphi->Delete();

    fout.close();

    firstEvent = false;
  }//loop on entries
  std::cout << " -- Total Esim in MIPS: "
	    <<  p_EsimTotal->GetEntries() 
	    << " mean " << p_EsimTotal->GetMean() 
	    << " rms " << p_EsimTotal->GetRMS() 
	    << " rms/mean " << p_EsimTotal->GetRMS()/p_EsimTotal->GetMean()
	    << " underflows " << p_EsimTotal->GetBinContent(0)
	    << " overflows " << p_EsimTotal->GetBinContent(p_EsimTotal->GetNbinsX()+1)
	    << std::endl;
  
  std::cout << " -- Total Ereco in MIPS: "
	    <<  p_ErecoTotal->GetEntries() 
	    << " mean " << p_ErecoTotal->GetMean() 
	    << " rms " << p_ErecoTotal->GetRMS() 
	    << " rms/mean " << p_ErecoTotal->GetRMS()/p_ErecoTotal->GetMean()
	    << " underflows " << p_ErecoTotal->GetBinContent(0)
	    << " overflows " << p_ErecoTotal->GetBinContent(p_ErecoTotal->GetNbinsX()+1)
	    << std::endl;
  

  //finalise error matrix
  std::ofstream fmatrix;
  std::ostringstream fmatrixname;
  fmatrixname << outFolder << "_errorMatrix_ref.dat";
  fmatrix.open(fmatrixname.str());
  if (!fmatrix.is_open()){
    std::cout << " Cannot open outfile " << fmatrixname.str() << " for writing ! Exiting..." << std::endl;
    exit(1);
  }



  TMatrixD matrix(nLayers,nLayers);
  outputFile->cd();
  TH2F *p_errorMatrix = new TH2F("p_errorMatrix",";i;j;M_{ij}",
			    nLayers,0,nLayers,
			    nLayers,0,nLayers);
  TH2F *p_corrMatrix = new TH2F("p_corrMatrix",";i;j;M_{ij}",
				nLayers,0,nLayers,
				nLayers,0,nLayers);

  for (unsigned iL(0);iL<nLayers;++iL){//loop on layers
    mean[0][iL] = mean[0][iL]/nL_mean[iL];
    mean[1][iL] = mean[1][iL]/nL_mean[iL];
  }
  for (unsigned iL(0);iL<nLayers;++iL){//loop on layers
    for (unsigned jL(0);jL<nLayers;++jL){//loop on layers
      sigma[0][iL][jL] = sigma[0][iL][jL]/nL_sigma[iL][jL];
      sigma[1][iL][jL] = sigma[1][iL][jL]/nL_sigma[iL][jL];
      //consider average of both x and y in one matrix
      matrix[iL][jL] = 0.5*(sigma[0][iL][jL]-mean[0][iL]*mean[0][jL]+
			    sigma[1][iL][jL]-mean[1][iL]*mean[1][jL]);
      //matrix[jL][iL] = matrix[iL][jL];
      p_errorMatrix->Fill(iL,jL,matrix[iL][jL]);
 
      fmatrix << iL << " " << jL << " " << std::setprecision(17) << matrix[iL][jL] << std::endl;

      //if (iL!=jL){
      //p_matrix->Fill(jL,iL,matrix[iL][jL]);
      //}
    }
  }
  fmatrix.close();

  //fill correlation matrix
  for (unsigned iL(0);iL<nLayers;++iL){//loop on layers
    for (unsigned jL(0);jL<nLayers;++jL){//loop on layers
      if (matrix[iL][iL]!=0 && matrix[jL][jL]!= 0) 
	p_corrMatrix->Fill(iL,jL,matrix[iL][jL]/sqrt(matrix[iL][iL]*matrix[jL][jL]));
    }
  }

  //get back data for each event and perform chi2 fit:
  std::cout << " -- Performing chi2 fit for each event" << std::endl;

  unsigned nInvalidFits=0;
  TH1F *p_chi2[2];
  TH1F *p_chi2overNDF[2];

  p_chi2[0] = new TH1F("p_chi2",";#chi^{2};n_{events}",100,0,500);
  p_chi2overNDF[0] = new TH1F("p_chi2overNDF",";#chi^{2}/NDF;n_{events}",100,0,10);
  p_chi2[1] = new TH1F("p_chi2_truth",";#chi^{2};n_{events}",100,0,500);
  p_chi2overNDF[1] = new TH1F("p_chi2overNDF_truth",";#chi^{2}/NDF;n_{events}",100,0,10);
  for (unsigned rt(0); rt<2;++rt){
  p_chi2[rt]->StatOverflows();
  p_chi2overNDF[rt]->StatOverflows();
  }

  TH1F *p_impactX[2];
  p_impactX[0] = new TH1F("p_impactX",";x front face impact (mm);n_{events}",200,-500,500);
  p_impactX[1] = new TH1F("p_impactX_truth",";x front face impact (mm);n_{events}",200,-500,500);
  TH1F *p_impactY[2];
  p_impactY[0] = new TH1F("p_impactY",";y front face impact (mm);n_{events}",240,300,1500);
  p_impactY[1] = new TH1F("p_impactY_truth",";y front face impact (mm);n_{events}",240,300,1500);
  TH1F *p_angleX[2];
  p_angleX[0] = new TH1F("p_angleX",";x direction angle (rad);n_{events}",150,-3.1416,3.1416);
  p_angleX[1] = new TH1F("p_angleX_truth",";x direction angle (rad);n_{events}",150,-3.1416,3.1416);
  TH1F *p_angleY[2];
  p_angleY[0] = new TH1F("p_angleY",";y direction angle (rad);n_{events}",150,-3.1416,3.1416);
  p_angleY[1] = new TH1F("p_angleY_truth",";y direction angle (rad);n_{events}",150,-3.1416,3.1416);

  TH1F *p_positionReso[2];
  TH1F *p_angularReso[2];
  p_positionReso[0] = new TH1F("p_positionResoX",";#sigma_{x,y} (mm);n_{events}",100,0,20);
  p_positionReso[1] = new TH1F("p_positionResoY",";#sigma_{x,y} (mm);n_{events}",100,0,20);
  p_angularReso[0] = new TH1F("p_angularResoX",";#sigma_{#theta} (rad);n_{events}",100,0,1);
  p_angularReso[1] = new TH1F("p_angularResoY",";#sigma_{#theta} (rad);n_{events}",100,0,1);

  //open new file to save accurate positions
  std::ofstream fout;
  std::ostringstream foutname;
  foutname << outFolder << "_accuratePos.dat";
  fout.open(foutname.str());
  if (!fout.is_open()){
    std::cout << " Cannot open outfile " << foutname.str() << " for writing ! Exiting..." << std::endl;
    return 1;
  }

  for (unsigned ievt(0); ievt<nEvts; ++ievt){//loop on entries
    if (debug) std::cout << "... Processing entry: " << ievt << std::endl;
    else if (ievt%50 == 0) std::cout << "... Processing entry: " << ievt << std::endl;

    std::ifstream fin;
    std::ostringstream finname;
    finname << outFolder << "_initialPos_evt" << ievt << ".dat";
    fin.open(finname.str());
    if (!fin.is_open()){
      std::cout << " Cannot open input file " << finname.str() << "! Exiting..." << std::endl;
      return 1;
    }

    std::vector<unsigned> layerId;
    std::vector<double> posx;
    std::vector<double> posy;
    std::vector<double> posz;
    std::vector<double> posxtruth;
    std::vector<double> posytruth;
    layerId.reserve(nLayers);
    posx.reserve(nLayers);
    posy.reserve(nLayers);
    posz.reserve(nLayers);
    posxtruth.reserve(nLayers);
    posytruth.reserve(nLayers);

    while (!fin.eof()){
      unsigned l=nLayers;
      double xr=0,yr=0,z=0,xt=0,yt=0;
      fin>>l>>xr>>yr>>z>>xt>>yt;
      if (l<nLayers){
	layerId.push_back(l);
	posx.push_back(xr);
	posy.push_back(yr);
	posz.push_back(z);
	posxtruth.push_back(xt);
	posytruth.push_back(yt);	
      }
    }

    fin.close();

    const unsigned nL = layerId.size();

    //for (unsigned iL(0); iL<nL;++iL){
      //std::cout << layerId[iL] << " " << posx[iL] << " " << posy[iL] << " " << posz[iL] << std::endl;
    //}

    //if less than 3 valid layers: no point doing a fit !!
    if (nL<3){
      nInvalidFits++;
      continue;
    }

    //number of points: x and y per layer minus number of parameters: 2 for x + 2 for y.
    double ndf = 2*nL-4;

    //Get error matrix removing lines with zero hits
    TMatrixDSym e(nL);
    TVectorD u(nL),z(nL),x(nL),y(nL);
    
    for(unsigned i(0);i<nL;++i) {
      u(i)=1.0;
      z(i)=posz[i];
      //std::cout << "fit() z(" << i << ") = " << z(i) << std::endl;
      
      for(unsigned j(i);j<nL;++j) {
	e(i,j)=matrix(layerId[i],layerId[j]);
	e(j,i)=matrix(layerId[j],layerId[i]);
      }
    }

    e.Invert();

    
    //do fit for reco and truth

    for (unsigned rt(0); rt<2;++rt){
      if (debug) {
	std::cout << "... Processing ";
	if (rt==0) std::cout << " fit to reco position.";
	else std::cout << " fit to truth position.";
	std::cout << std::endl;
      }
      double chiSq(0.0);
      double position[2];
      double positionFF[2];
      double TanAngle[2];
      
      TMatrixD fitMatrix(4,4);
      
      //resolve equation for x and y separately
      for(unsigned xy(0);xy<2;xy++) {//loop on x or y
	if (debug) {
	  std::cout << "... Processing ";
	  if (xy==0) std::cout << " fit to x position.";
	  else std::cout << " fit to y position.";
	  std::cout << std::endl;
	}
	for(unsigned i(0);i<nL;i++) {
	  x(i)= rt==0 ? ((xy==0) ? posx[i] : posy[i]) : ((xy==0) ? posxtruth[i] : posytruth[i]);
	  //std::cout << "fit() x(" << i << ") = " << x(i) << std::endl;
	}
	
	TMatrixD w(2,2);
	TVectorD v(2),p(2);
	
	w(0,0)=u*(e*u);
	w(0,1)=u*(e*z);
	w(1,0)=z*(e*u);
	w(1,1)=z*(e*z);

	v(0)=u*(e*x);
	v(1)=z*(e*x);
	
	w.Invert();
	
	p=w*v;
	if (debug) {
	  std::cout << "fit() w(0,0) = " << w(0,0) << std::endl;
	  std::cout << "fit() w(0,1) = " << w(0,1) << std::endl;
	  std::cout << "fit() w(1,0) = " << w(1,0) << std::endl;
	  std::cout << "fit() w(1,1) = " << w(1,1) << std::endl;	
	  std::cout << "fit() p(0) = " << p(0) << std::endl;
	  std::cout << "fit() p(1) = " << p(1) << std::endl;
	}

	position[xy] = p(0);
	positionFF[xy] = p(0)+p(1)*posz[0];
	TanAngle[xy] = p(1);
	
	fitMatrix[2*xy][2*xy]=w(0,0);
	fitMatrix[2*xy][2*xy+1]=w(0,1);
	fitMatrix[2*xy+1][2*xy]=w(1,0);
	fitMatrix[2*xy+1][2*xy+1]=w(1,1);
	
	
	TVectorD dp(nL);
	for(unsigned i(0);i<nL;i++) {
	  dp(i)=x(i)-p(0)-p(1)*z(i);
	}
	
	chiSq+=dp*(e*dp);
      }//loop on x or y
      
      p_chi2[rt]->Fill(chiSq);
      p_chi2overNDF[rt]->Fill(chiSq/ndf);
      p_impactX[rt]->Fill(positionFF[0]);
      p_angleX[rt]->Fill(atan(TanAngle[0]));
      p_impactY[rt]->Fill(positionFF[1]);
      p_angleY[rt]->Fill(atan(TanAngle[1]));

      if (rt==0) {
	p_positionReso[0]->Fill(sqrt(fabs(fitMatrix[0][0])));
	p_positionReso[1]->Fill(sqrt(fabs(fitMatrix[2][2])));
	p_angularReso[0]->Fill(sqrt(fabs(fitMatrix[1][1])));
	p_angularReso[1]->Fill(sqrt(fabs(fitMatrix[3][3])));

	fout << ievt << " " 
	     << position[0] << " " 
	     << sqrt(fabs(fitMatrix[0][0])) << " " 
	     << TanAngle[0] << " " 
	     << sqrt(fabs(fitMatrix[1][1])) << " "
	     << position[1] << " " 
	     << sqrt(fabs(fitMatrix[2][2])) << " "
	     << TanAngle[1] << " "
	     << sqrt(fabs(fitMatrix[3][3]))
	     << std::endl;
      }

    }//reco or truth

  }//loop on entries
  
  fout.close();    


  std::cout << " -- Number of invalid fits: " << nInvalidFits << std::endl;


  outputFile->Write();
  //outputFile->Close();
  
  return 0;


}//main
void produce_elefakepho(){//main  

//  TFile *efile = TFile::Open("plot_elefakepho_test.root","read");
//  TTree* etree = (TTree*)efile->Get("FakeRateTree");

 TChain *etree = new TChain("FakeRateTree");
 etree->Add("../data/plot_elefakepho_Calib.root"); 


  int tracks=0; 
  int nVertex=0;
  float mass_denmg=0,mass_nummg=0,et_denmg=0,et_nummg=0, rap_denmg=0, rap_nummg=0;
  float mass_denrandom=0,mass_numrandom=0,et_denrandom=0,et_numrandom=0,rap_denrandom=0,rap_numrandom=0;
  std::vector<float> *mass_denbothcount=0;
  std::vector<float> *mass_numbothcount=0;
  std::vector<float> *et_denbothcount=0;
  std::vector<float> *et_numbothcount=0;
  std::vector<float> *rap_denbothcount=0;
  std::vector<float> *rap_numbothcount=0;
  std::vector<float> *track_denbothcount=0;
  std::vector<float> *track_numbothcount=0;
  std::vector<float> *tagEta=0;
  std::vector<float> *tagPhi=0;
  std::vector<float> *tagPt=0;
  std::vector<float> *probeEta=0;
  std::vector<float> *probePhi=0;
  std::vector<float> *probePt=0;
  std::vector<float> *invmass=0;
  std::vector<bool>  *vetovalue=0;
  
  etree->SetBranchAddress("tracks",&tracks);
  etree->SetBranchAddress("nVertex",&nVertex);
  etree->SetBranchAddress("mass_denrandom",      &mass_denrandom);    
  etree->SetBranchAddress("mass_numrandom",      &mass_numrandom);
  etree->SetBranchAddress("et_denrandom",        &et_denrandom);   
  etree->SetBranchAddress("et_numrandom",        &et_numrandom);  
  etree->SetBranchAddress("rap_denrandom",       &rap_denrandom);   
  etree->SetBranchAddress("rap_numrandom",       &rap_numrandom);  
  etree->SetBranchAddress("mass_denbothcount",   &mass_denbothcount); 
  etree->SetBranchAddress("mass_numbothcount",   &mass_numbothcount); 
  etree->SetBranchAddress("et_denbothcount",     &et_denbothcount);   
  etree->SetBranchAddress("et_numbothcount",     &et_numbothcount);   
  etree->SetBranchAddress("rap_denbothcount",    &rap_denbothcount);  
  etree->SetBranchAddress("rap_numbothcount",    &rap_numbothcount);  
  etree->SetBranchAddress("track_denbothcount",  &track_denbothcount);
  etree->SetBranchAddress("track_numbothcount",  &track_numbothcount);
  etree->SetBranchAddress("tagEta",              &tagEta);
  etree->SetBranchAddress("tagPhi",              &tagPhi);
  etree->SetBranchAddress("tagPt",               &tagPt);
  etree->SetBranchAddress("probeEta",            &probeEta);
  etree->SetBranchAddress("probePhi",            &probePhi);
  etree->SetBranchAddress("probePt",             &probePt);
  etree->SetBranchAddress("invmass",             &invmass);
  etree->SetBranchAddress("vetovalue",           &vetovalue);

  //float PtBins[]={25,30,35,40,45,50,60,70,90,110};
  float PtBins[]={25,30,35,40,50,60,70};
  float NtrkBins[] = {10,20,30,40,50,60,70,90,120};
  float EtaBins[] = {0.0,0.1,0.2,0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3};
  float VertexBins[]={0,4,8,10,11,12,13,14,15,16,17,18,20};
  unsigned nPtBins = sizeof(PtBins)/sizeof(float);
  unsigned nNtrkBins = sizeof(NtrkBins)/sizeof(float);
  unsigned nEtaBins = sizeof(EtaBins)/sizeof(float);
  unsigned nVertexBins = sizeof(VertexBins)/sizeof(float);

  TFile *outputfile = TFile::Open("histo_elefakepho_Calib.root","RECREATE");
  outputfile->cd();

  TH1F* den_random_pt[nPtBins]; 
  TH1F* den_random_trk[nNtrkBins];
  TH1F* den_random_eta[nEtaBins];
  TH1F* den_random_vtx[nVertexBins];
  TH1F* num_random_pt[nPtBins]; 
  TH1F* num_random_trk[nNtrkBins];
  TH1F* num_random_eta[nEtaBins];
  TH1F* num_random_vtx[nVertexBins];

  TH1F* den_both_pt[nPtBins]; 
  TH1F* den_both_trk[nNtrkBins];
  TH1F* den_both_eta[nEtaBins];
  TH1F* den_both_vtx[nVertexBins];
  TH1F* num_both_pt[nPtBins]; 
  TH1F* num_both_trk[nNtrkBins];
  TH1F* num_both_eta[nEtaBins];
  TH1F* num_both_vtx[nVertexBins];

  TH1F *event_type=new TH1F("event_type","",10,0,10);
 
  std::ostringstream binname; 
  for(unsigned iPt(0); iPt < nPtBins; iPt++){
    binname.str("");
    if(iPt != nPtBins-1)binname << "den_random_pt-" << PtBins[iPt] << "-" << PtBins[iPt+1];
    else binname << "den_random_pt-" << PtBins[iPt] << "-inf";
    den_random_pt[iPt] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iPt != nPtBins-1)binname << "num_random_pt-" << PtBins[iPt] << "-" << PtBins[iPt+1];
    else binname << "num_random_pt-" << PtBins[iPt] << "-inf";
    num_random_pt[iPt] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iPt != nPtBins-1)binname << "den_both_pt-" << PtBins[iPt] << "-" << PtBins[iPt+1];
    else binname << "den_both_pt-" << PtBins[iPt] << "-inf";
    den_both_pt[iPt] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iPt != nPtBins-1)binname << "num_both_pt-" << PtBins[iPt] << "-" << PtBins[iPt+1];
    else binname << "num_both_pt-" << PtBins[iPt] << "-inf";
    num_both_pt[iPt] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
  }
    

  for(unsigned iNtrk(0); iNtrk < nNtrkBins; iNtrk++){
    binname.str("");
    if(iNtrk != nNtrkBins-1)binname << "den_random_trk-" << NtrkBins[iNtrk] << "-" << NtrkBins[iNtrk+1];
    else binname << "den_random_trk-" << NtrkBins[iNtrk] << "-inf";
    den_random_trk[iNtrk] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iNtrk != nNtrkBins-1)binname << "num_random_trk-" << NtrkBins[iNtrk] << "-" << NtrkBins[iNtrk+1];
    else binname << "num_random_trk-" << NtrkBins[iNtrk] << "-inf";
    num_random_trk[iNtrk] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iNtrk != nNtrkBins-1)binname << "den_both_trk-" << NtrkBins[iNtrk] << "-" << NtrkBins[iNtrk+1];
    else binname << "den_both_trk-" << NtrkBins[iNtrk] << "-inf";
    den_both_trk[iNtrk] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iNtrk != nNtrkBins-1)binname << "num_both_trk-" << NtrkBins[iNtrk] << "-" << NtrkBins[iNtrk+1];
    else binname << "num_both_trk-" << NtrkBins[iNtrk] << "-inf";
    num_both_trk[iNtrk] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
  }


  for(unsigned iEta(0); iEta < nEtaBins; iEta++){
    binname.str("");
    if(iEta != nEtaBins-1)binname << "den_random_eta-" << EtaBins[iEta] << "-" << EtaBins[iEta+1];
    else binname << "den_random_eta-" << EtaBins[iEta] << "-inf";
    den_random_eta[iEta] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iEta != nEtaBins-1)binname << "num_random_eta-" << EtaBins[iEta] << "-" << EtaBins[iEta+1];
    else binname << "num_random_eta-" << EtaBins[iEta] << "-inf";
    num_random_eta[iEta] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iEta != nEtaBins-1)binname << "den_both_eta-" << EtaBins[iEta] << "-" << EtaBins[iEta+1];
    else binname << "den_both_eta-" << EtaBins[iEta] << "-inf";
    den_both_eta[iEta] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iEta != nEtaBins-1)binname << "num_both_eta-" << EtaBins[iEta] << "-" << EtaBins[iEta+1];
    else binname << "num_both_eta-" << EtaBins[iEta] << "-inf";
    num_both_eta[iEta] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
  }

  for(unsigned iVertexBins(0); iVertexBins < nVertexBins; iVertexBins++){
    binname.str("");
    if(iVertexBins != nVertexBins-1)binname << "den_random_vtx-" << VertexBins[iVertexBins] << "-" << VertexBins[iVertexBins+1];
    else binname << "den_random_vtx-" << VertexBins[iVertexBins] << "-inf";
    den_random_vtx[iVertexBins] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iVertexBins != nVertexBins-1)binname << "num_random_vtx-" << VertexBins[iVertexBins] << "-" << VertexBins[iVertexBins+1];
    else binname << "num_random_vtx-" << VertexBins[iVertexBins] << "-inf";
    num_random_vtx[iVertexBins] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iVertexBins != nVertexBins-1)binname << "den_both_vtx-" << VertexBins[iVertexBins] << "-" << VertexBins[iVertexBins+1];
    else binname << "den_both_vtx-" << VertexBins[iVertexBins] << "-inf";
    den_both_vtx[iVertexBins] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
    binname.str("");
    if(iVertexBins != nVertexBins-1)binname << "num_both_vtx-" << VertexBins[iVertexBins] << "-" << VertexBins[iVertexBins+1];
    else binname << "num_both_vtx-" << VertexBins[iVertexBins] << "-inf";
    num_both_vtx[iVertexBins] = new TH1F(binname.str().c_str(), binname.str().c_str(), 60, 60,120);
  }

  const unsigned nEvts = etree->GetEntries(); 
  for(unsigned iEvt(0); iEvt < nEvts; iEvt++){
    etree->GetEntry(iEvt);
    nVertex = nVertex+0.1;

    if(mass_denrandom > 40.0){
      den_random_pt[findIndex(PtBins,et_denrandom,nPtBins)]->Fill(mass_denrandom);
      den_random_trk[findIndex(NtrkBins,tracks,nNtrkBins)]->Fill(mass_denrandom);
      den_random_eta[findIndex(EtaBins,fabs(rap_denrandom),nEtaBins)]->Fill(mass_denrandom); 
      den_random_vtx[findIndex(VertexBins,nVertex, nVertexBins)]->Fill(mass_denrandom);
    }

    if(mass_numrandom > 40.0){
      num_random_pt[findIndex(PtBins,et_numrandom,nPtBins)]->Fill(mass_numrandom);
      num_random_trk[findIndex(NtrkBins,tracks,nNtrkBins)]->Fill(mass_numrandom);
      num_random_eta[findIndex(EtaBins,fabs(rap_numrandom),nEtaBins)]->Fill(mass_numrandom); 
      num_random_vtx[findIndex(VertexBins,nVertex, nVertexBins)]->Fill(mass_numrandom);
    }

    if(mass_denbothcount->size()>0){
      for(unsigned ii(0); ii<mass_denbothcount->size(); ii++){
        den_both_pt[findIndex(PtBins, (*et_denbothcount)[ii], nPtBins)]->Fill( (*mass_denbothcount)[ii]);
        den_both_trk[findIndex(NtrkBins, (*track_denbothcount)[ii], nNtrkBins)]->Fill((*mass_denbothcount)[ii]);
        den_both_eta[findIndex(EtaBins, fabs((*rap_denbothcount)[ii]), nEtaBins)]->Fill((*mass_denbothcount)[ii]);
        den_both_vtx[findIndex(VertexBins,nVertex, nVertexBins)]->Fill((*mass_denbothcount)[ii]);
      }
    }

    if(mass_numbothcount->size()>0){
      for(unsigned ii(0); ii<mass_numbothcount->size(); ii++){
        num_both_pt[findIndex(PtBins, (*et_numbothcount)[ii], nPtBins)]->Fill( (*mass_numbothcount)[ii]);
        num_both_trk[findIndex(NtrkBins, (*track_numbothcount)[ii], nNtrkBins)]->Fill((*mass_numbothcount)[ii]);
        num_both_eta[findIndex(EtaBins, fabs((*rap_numbothcount)[ii]), nEtaBins)]->Fill((*mass_numbothcount)[ii]);
        num_both_vtx[findIndex(VertexBins,nVertex, nVertexBins)]->Fill((*mass_numbothcount)[ii]);
      }
    }

  }

outputfile->Write();
outputfile->Close();
}
void TakeDataAnalyzer(Int_t RunN){
 
  //Int_t RunN = 4591;   
  //string FileRoot = "/d00/icali/PixelHwStudies/PSIStuff/log/bt05r";
 string FileRoot = "/home/l_tester/log/bt05r";
 string FileInName = "thistos.root";
 string FileOutName = "ProcessedData.root";
 char RunNumber[6];
 sprintf(RunNumber, "%.6d", RunN);
 FileRoot = FileRoot + RunNumber + "/";
 FileInName = FileRoot + FileInName;
 FileOutName = FileRoot + FileOutName;
 
 TFile *iFile = new TFile((const char*)FileInName.c_str());
 TNtuple *Digis = (TNtuple*)iFile->FindObjectAny("events");
 Int_t EvN, row, col, roc, ph;
 Float_t vcal;
 Digis->SetBranchAddress("row", &row);
 Digis->SetBranchAddress("col", &col);
 Digis->SetBranchAddress("roc", &roc);
 Digis->SetBranchAddress("ph", &ph);
 Digis->SetBranchAddress("vcal", &vcal);
 Digis->SetBranchAddress("eventNr", &EvN);
 Int_t iNTlenght = Digis->GetEntries();
 
 TFile *oFile = new TFile((const char*)FileOutName.c_str(), "RECREATE");
 TNtuple *Multiplicity = new TNtuple("ModMult", "ModMult", "EvN:roc:NModHits:NROCHits:NRows:NCols:MeanPh:MeanPhPuls",10000000);
 
 //******************Calculating Number of Events**************
 Digis->GetEntry(iNTlenght -1);
 std::cout << " MaxEvent " << EvN << std::endl;
  
 //*****************Creating Multiplicity NTuple***************
 
 ModuleMultiplicity  ModMult;
 Int_t OldEvN = 1;
 for(Int_t i =0; i< iNTlenght; ++i){
    Digis->GetEntry(i);
    if(OldEvN != EvN ||( i == iNTlenght -1) ){
      for(Int_t j=0; j < 16; ++j){ 
        Float_t NModHits = ModMult.ModMultiplicity();
        Float_t NROCHits = ModMult.ROCMultiplicity(j);
        Float_t NRows = ModMult.NumberOfRows(j);
        Float_t NCols = ModMult.NumberOfColumns(j);
        Float_t MeanPh = ModMult.MeanPh(j);  
        Float_t MeanPhPuls = ModMult.MeanPhPuls(j); 
        if(NROCHits >0) Multiplicity->Fill(EvN-1, j,NModHits ,NROCHits ,NRows ,NCols ,MeanPh, MeanPhPuls); 
      }
      ModMult.Clean();
      OldEvN = EvN;
    }
    
    bool SelPixel = 0;
    if(row ==5 && col ==5)SelPixel = 1;
    if(roc>-1&&col>-1)ModMult.Add(roc, row, col, ph, SelPixel);
 }
 
 oFile->Write();
 oFile->Close();          
 
}
void merge_results(int generated_PDF_set=1, int generated_PDF_member=0){

  TString     WCharge_str[]={"Pos","Neg"};
  TRandom3 *initmass = new TRandom3(0); 

  gStyle->SetOptStat(0);
  
  TFile *fout = new TFile(Form("likelihood_results.root"),"RECREATE");
  
    TGraph *result;
    TCanvas*c_chi2;
    TF1*ffit[3][2];
    // TGraph *result_NonScaled[WMass::PDF_members][3];
    TGraph *result_NonScaled[WMass::NtoysMomCorr][WMass::PDF_members][3][2];
    double deltaM[WMass::NtoysMomCorr][WMass::PDF_members][3][2];
    double deltaMmin[3][2]={{0}},deltaMmax[3][2]={{0}};
    double deltaMnegSummed[3][2]={{0}},deltaMposSummed[3][2]={{0}},deltaMSummed[3][2]={{0}},deltaMJuan[3][2]={{0}};
    TH1D*h_deltaM_PDF[3][2];
    TGraphErrors*g_deltaM_PDF[3][2];

  for(int c=0; c<2; c++){
    cout <<"merging W " << WCharge_str[c].Data() << endl;
    
    if(WMass::PDF_members>1 || WMass::NtoysMomCorr>1){
      for(int k=0;k<3;k++){
        TString eta_str = Form("%.1f",WMass::etaMaxMuons[0]); eta_str.ReplaceAll(".","p");

        g_deltaM_PDF[k][c] = new TGraphErrors();
        g_deltaM_PDF[k][c]->SetName(Form("g_deltaM_PDF_W%s_%sNonScaled_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),eta_str.Data()));
        g_deltaM_PDF[k][c]->SetTitle(Form("g_deltaM_PDF_W%s_%sNonScaled_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),eta_str.Data()));
        g_deltaM_PDF[k][c]->SetMarkerStyle(20);
        h_deltaM_PDF[k][c] = new TH1D(Form("h_deltaM_PDF_W%s_%sNonScaled_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),eta_str.Data()),Form("h_deltaM_PDF_%sNonScaled_eta%s",WMass::FitVar_str[k].Data(),eta_str.Data()),200,-50,50);

      }
    }
    
    for(int h=0; h<WMass::PDF_members; h++){
      for(int m=0; m<WMass::NtoysMomCorr; m++){
        TString toys_str = "";
        if(WMass::NtoysMomCorr>1) toys_str = Form("_MomCorrToy%d",m);
        // for(int i=0; i<WMass::etaMuonNSteps; i++){
        cout << "using pdf " << (WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets) << "-"<<h<< endl;
        
        for(int i=0; i<1; i++){
          TString eta_str = Form("%.1f",WMass::etaMaxMuons[i]); eta_str.ReplaceAll(".","p");
          cout << "merging pdf eta bin= " << i << endl;
          
          for(int k=0;k<3;k++){

            cout << "variable= " << k << endl;
          
            int npoint=0;

            // result = new TGraph();
            // result->SetName(Form("likelihood_results_%s_eta%s",WMass::FitVar_str[k].Data(),eta_str.Data()));
            // result->SetTitle(Form("likelihood_results_%s_eta%s",WMass::FitVar_str[k].Data(),eta_str.Data()));

            result_NonScaled[m][h][k][c] = new TGraph();
            result_NonScaled[m][h][k][c]->SetName(Form("likelihood_result_W%s_%sNonScaled_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,toys_str.Data(),eta_str.Data()));
            result_NonScaled[m][h][k][c]->SetTitle(Form("likelihood_result_W%s_%sNonScaled_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,toys_str.Data(),eta_str.Data()));

            std::vector<double> l_res;
            double lmin=0, lmax=0, deriv1=0, deriv2=0, deriv3=0;

            for(int j=0; j<2*WMass::WMassNSteps+1; j++){
              int jWmass = WMass::WMassCentral_MeV-(WMass::WMassNSteps-j)*WMass::WMassStep_MeV;
          
              // std::ifstream fileNames(Form("dummy_datacard_Wmass_MuPos_eta%s_%d.log",eta_str.Data(),jWmass));
              string StringFromFile;
              TString TStringFromFile;
              double likelihood_val;
              int ncol;
              // while (!fileNames.eof()){
                // getline (fileNames,StringFromFile);
                // TStringFromFile = StringFromFile.c_str();
                // if(TStringFromFile.Contains("nll S+B ->")){
                  // break;
                // }
              // }
              // TObjArray* LineColumns = TStringFromFile.Tokenize(" ");
              // ncol = LineColumns->GetEntries();
              // if(ncol<3){
                // cout << Form("problem while analyzing fit result in dummy_datacard_Wmass_MuPos_eta%s_%d.log",eta_str.Data(),jWmass) << endl;
                // return;
              // }
              // TString str_icol = ((TObjString *)LineColumns->At(3))->GetString();
              // likelihood_val = (double) (str_icol.Atof());
              // if(likelihood_val<0) result->SetPoint(npoint,jWmass,likelihood_val);
              
              // cout << Form("dummy_datacard_Wmass_MuPos_pdf%d-%d%s_eta%s_%d_%sNonScaled.log",WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,(WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):""),eta_str.Data(),jWmass,WMass::FitVar_str[k].Data()) << endl;
              TString test1 = Form("dummy_datacard_Wmass_Mu%s_pdf%d-%d%s_eta%s_%d_%sNonScaled.log",WCharge_str[c].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,(WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):""),eta_str.Data(),jWmass,WMass::FitVar_str[k].Data());
              // cout << test1 << endl;
              std::ifstream fileNames_NonScaled(test1.Data());
              // string StringFromFile;
              // TString TStringFromFile;
              while (!fileNames_NonScaled.eof()){
                getline (fileNames_NonScaled,StringFromFile);
                TStringFromFile = StringFromFile.c_str();
                // if(TStringFromFile.Contains("nll S+B ->")){
                if(TStringFromFile.Contains("-2 ln Q_{TEV}")){
                  break;
                }
              }
              TObjArray* LineColumns = TStringFromFile.Tokenize(" ");
              ncol = LineColumns->GetEntries();
              // str_icol = ((TObjString *)LineColumns->At(3))->GetString();
              TString str_icol = ((TObjString *)LineColumns->At(4))->GetString();
              likelihood_val = (double) (str_icol.Atof());
              // cout << jWmass << " LIKELIHOOD VALUE= "<<likelihood_val << " lmin= " << lmin << " lmax=" << lmax << endl;
              cout << " " << jWmass << " LIKELIHOOD VALUE= "<<likelihood_val; fflush(stdout);
              l_res.push_back(likelihood_val);
              if(likelihood_val<lmin) lmin=likelihood_val;
              if(likelihood_val>lmax) lmax=likelihood_val;
              
              if(npoint==0) deriv1=likelihood_val;
              else if(npoint==WMass::WMassNSteps) deriv2=likelihood_val;
              else if(npoint==2*WMass::WMassNSteps) deriv3=likelihood_val;

              npoint++;
          
            }
            cout << endl;

            double l_offset;
            if(lmax>0)
              l_offset=-lmax;
            else
              l_offset=-lmin;
            // cout << "lmin= " << lmin << " lmax= " << lmax << endl;  
            for(int j=0; j<2*WMass::WMassNSteps+1; j++){
              int jWmass = WMass::WMassCentral_MeV-(WMass::WMassNSteps-j)*WMass::WMassStep_MeV;
              // cout << "result_NonScaled[h][k]->SetPoint("<<j<<","<<jWmass<<","<<(lmax>0 ? -l_res.at(j) -l_offset : l_res.at(j) -l_offset) <<");"<<endl;
              result_NonScaled[m][h][k][c]->SetPoint(j,jWmass,deriv3-2*deriv2+deriv1<0 ? -l_res.at(j) -l_offset : l_res.at(j) -l_offset );
            }
            // cout << "second derivative= " << (deriv3-2*deriv2+deriv1) << endl;
            
            
            // result->SetMarkerStyle(20);
            // result->SetMarkerSize(1);
            // result->Write();
            result_NonScaled[m][h][k][c]->SetMarkerStyle(20);
            result_NonScaled[m][h][k][c]->SetMarkerSize(1);
            result_NonScaled[m][h][k][c]->Write();
            
            c_chi2=new TCanvas(Form("c_chi2_W%s_%s_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()),Form("c_chi2_W%s_%s_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()));
            ffit[k][c]=new TF1(Form("ffit_W%s_%s_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()),Form("[0]+TMath::Power((x-[1])/[2],2)"),70,100);
            ffit[k][c]->SetParameter(0,result_NonScaled[m][h][k][c]->GetMinimum());
            ffit[k][c]->SetParameter(1,80410);
            ffit[k][c]->SetParameter(2,10); // IF FIT DOES NOT CONVERGE, CHANGE THIS PARAMETER BY LOOKING AT THE CHI2 VS MASS DISTRIBUTION (~value for which Delta_chi2 = 1)
            // ffit[k]->SetParameter(2,1e4); // IF FIT DOES NOT CONVERGE, CHANGE THIS PARAMETER BY LOOKING AT THE CHI2 VS MASS DISTRIBUTION (~value for which Delta_chi2 = 1)
            ffit[k][c]->SetLineColor(2);
            ffit[k][c]->SetLineWidth(1);
            int fires = result_NonScaled[m][h][k][c]->Fit(Form("ffit_W%s_%s_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()),"WEM");
            cout << "fitres= " << fires << " chi2= " << ffit[k][c]->GetChisquare() << " ndof= " << ffit[k][c]->GetNDF() << " chi2/ndof= " << (ffit[k][c]->GetChisquare()/ffit[k][c]->GetNDF()) << endl;
            int attempts=0;
            while((ffit[k][c]->GetChisquare()/ ffit[k][c]->GetNDF())>1 && attempts<10){
              double rmass = initmass->Gaus(80410, 200);
              ffit[k][c]->SetParameter(1, rmass );
              ffit[k][c]->SetParameter(2,10); // IF FIT DOES NOT CONVERGE, CHANGE THIS PARAMETER BY LOOKING AT THE CHI2 VS MASS DISTRIBUTION (~value for which Delta_chi2 = 1)
              ffit[k][c]->SetLineColor(2);
              ffit[k][c]->SetLineWidth(1);
              result_NonScaled[m][h][k][c]->Fit(Form("ffit_W%s_%s_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()),"WEM");
              cout << "refitted with init mass: " << rmass << " chi2 norm: " << (ffit[k][c]->GetChisquare()/ ffit[k][c]->GetNDF()) << endl;
              attempts++;
            }
            
            result_NonScaled[m][h][k][c]->Draw("ap");
            TLatex *text,*text2;
            text = new TLatex(0.25,0.7,Form("Best M_{W} with %s= %.0f #pm %.0f MeV", WMass::FitVar_str[k].Data(),ffit[k][c]->GetParameter(1),ffit[k][c]->GetParameter(2)));
            text->SetNDC();
            text->Draw();
            text = new TLatex(0.25,0.6,Form("#DeltaM_{W} = %.0f MeV", (ffit[k][c]->GetParameter(1) - WMass::WMassCentral_MeV )));
            text->SetNDC();
            text->Draw();
            // text2 = new TLatex(0.25,0.6,Form("Best #chi^{2} ratio = %.1f", ffit[k]->GetParameter(0) ));
            // text2->SetNDC();
            // text2->Draw();
            cout << Form("Best M_W value with %s = %.0f +/- %.0f MeV, DeltaM_W = %.0f",WMass::FitVar_str[k].Data(), ffit[k][c]->GetParameter(1), ffit[k][c]->GetParameter(2), (ffit[k][c]->GetParameter(1) - WMass::WMassCentral_MeV)) << endl;
            // cout << "Best chi2 ratio value = " << ffit[k]->GetParameter(0) << endl;
            // cout << "Measured mass points chi2 min = " << chi2min << " max = " << chi2max << endl;
            
            c_chi2->Write();
            
            // result_NonScaled[h][k]->Delete();
            // result->Delete();
            
          }
       
          TCanvas *c_summary=new TCanvas(Form("c_summary_W%s_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()),Form("c_summary_pdf%d-%d%s_eta%s",WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data())); 
          c_summary->SetGridy();
          c_summary->SetGridx();
          TH2D*frame=new TH2D("frame",Form("pdf %d-%d %s eta %s;M_{W} (MeV); -2ln(L/L_{ref})",WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()),2*WMass::WMassStep_MeV+1,WMass::WMassCentral_MeV-(WMass::WMassNSteps)*WMass::WMassStep_MeV,WMass::WMassCentral_MeV+(WMass::WMassNSteps)*WMass::WMassStep_MeV,10,0,5);
          frame->Draw();
          TLine *l=new TLine(WMass::WMassCentral_MeV,0,WMass::WMassCentral_MeV,5);
          l->SetLineStyle(6);
          l->SetLineColor(4);
          l->SetLineWidth(2);
          l->Draw();

          TLegend *leg1 = new TLegend(0.51,0.7,0.89,0.89);
          leg1->SetFillColor(10);  leg1->SetBorderSize(1);
          leg1->SetTextSize(0.035);
          leg1->AddEntry(l, Form("gen M_{W} (%d MeV)",WMass::WMassCentral_MeV), "l");

          TF1*f[3];
          for(int k=0;k<3;k++){
            // cout << result_NonScaled[h][k]->GetParameter(1) << " " << ffit[k]->GetParameter(2) << endl;
            // ffit[k]->Draw("");
            f[k] = (TF1*) result_NonScaled[m][h][k][c]->GetFunction(Form("ffit_W%s_%s_pdf%d-%d%s_eta%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data(),WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets,h,WMass::NtoysMomCorr>1?Form("_MomCorrToy%d",m):"",eta_str.Data()));
            f[k]->SetLineColor(k+1);
            f[k]->SetLineWidth(2);
            f[k]->Draw("same");
            leg1->AddEntry(f[k], Form("%s Fit (#DeltaM_{W} = %.0f #pm %0.f MeV)",WMass::FitVar_str[k].Data(), (f[k]->GetParameter(1) - WMass::WMassCentral_MeV),f[k]->GetParameter(2)), "l");
            // result_NonScaled[h][k]->Draw("l same");
            // ffit[k]->SetLineColor(4);
            // ffit[k]->SetLineWidth(4);
            // ffit[k]->Draw(k>0?"same":"");
            // result_NonScaled[h][k]->SaveAs("test_func");
            deltaM[m][h][k][c]=f[k]->GetParameter(1) - WMass::WMassCentral_MeV;
            if(deltaM[m][h][k][c]<deltaMmin[k][c]) deltaMmin[k][c]=deltaM[m][h][k][c];
            if(deltaM[m][h][k][c]>deltaMmax[k][c]) deltaMmax[k][c]=deltaM[m][h][k][c];

            if(h>0){
              if(deltaM[m][h][k][c]<0) deltaMnegSummed[k][c] = TMath::Sqrt(deltaMnegSummed[k][c]*deltaMnegSummed[k][c] + deltaM[m][h][k][c]*deltaM[m][h][k][c]);
              if(deltaM[m][h][k][c]>0) deltaMposSummed[k][c] = TMath::Sqrt(deltaMposSummed[k][c]*deltaMposSummed[k][c] + deltaM[m][h][k][c]*deltaM[m][h][k][c]);
              deltaMSummed[k][c] = TMath::Sqrt(deltaMSummed[k][c]*deltaMSummed[k][c] + deltaM[m][h][k][c]*deltaM[m][h][k][c]);
              if(h%2==0)
                deltaMJuan[k][c] = TMath::Sqrt( deltaMJuan[k][c]*deltaMJuan[k][c] + (deltaM[m][h][k][c]-deltaM[m][h-1][k][c])*(deltaM[m][h][k][c]-deltaM[m][h-1][k][c]));
            }
            
            if(WMass::PDF_members>1){
              g_deltaM_PDF[k][c]->SetPoint(h,h,deltaM[m][h][k][c]);
              g_deltaM_PDF[k][c]->SetPointError(h,0,f[k]->GetParameter(2));
              h_deltaM_PDF[k][c]->Fill(deltaM[m][h][k][c]);
            }else if(WMass::NtoysMomCorr>1){
              g_deltaM_PDF[k][c]->SetPoint(m,m,deltaM[m][h][k][c]);
              g_deltaM_PDF[k][c]->SetPointError(m,0,f[k]->GetParameter(2));
              h_deltaM_PDF[k][c]->Fill(deltaM[m][h][k][c]);
            }
          }
          leg1->Draw("same");
          c_summary->Write();

        }
      }
    }
    
    for(int k=0;k<3;k++){
      if(WMass::PDF_members>1){

        cout << endl;
        int usedpdf = WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets;
        cout << Form("PDF %d with %s: #DeltaM_{W, min}= %.0f MeV, #DeltaM_{W,max}= %.0f MeV", WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), deltaMmin[k][c], deltaMmax[k][c]) << endl;
        double denominator = 1;

        TCanvas*c1= new TCanvas(Form("c_deltaM_PDF_W%s_%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data()),Form("c_deltaM_PDF_W%s_%s",WCharge_str[c].Data(),WMass::FitVar_str[k].Data()));
        
        g_deltaM_PDF[k][c]->Draw("ape");
        TLatex *text;
        text = new TLatex(0.2,0.85,Form("W%s, PDF %d with %s: #DeltaM_{W, min}= %.0f MeV, #DeltaM_{W,max}= %.0f MeV", WCharge_str[c].Data(), WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), deltaMmin[k][c], deltaMmax[k][c]));
        text->SetTextSize(0.035);
        text->SetNDC();
        text->Draw();
        
        if(usedpdf==232000){ // NNPDF, see ref. http://arxiv.org/pdf/1301.6754v1.pdf formulae 2.23 and 2.25
          // cout << Form("PDF %d with %s: #DeltaM_{W} square summed = -%.0f MeV, #DeltaM_{W} square summed = %.0f MeV", WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), deltaMnegSummed[k]/denominator, deltaMposSummed[k]/denominator) << endl;
          denominator = TMath::Sqrt(WMass::PDF_members/2-1);
          cout << Form("PDF %d with %s: #DeltaM_{W} square summed = %.0f MeV", WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), deltaMSummed[k][c]/denominator) << endl;
          text = new TLatex(0.2,0.8,Form("PDF %d with %s: #DeltaM_{W} square summed = %.0f MeV", WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), deltaMSummed[k][c]/denominator));
          text->SetTextSize(0.035);
          text->SetNDC();
          text->Draw();
        }else{
          cout << Form("PDF %d with %s: #DeltaM_{W} as of J. Rojo = %.0f MeV", WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), (deltaMJuan[k][c]/2/denominator)) << endl;
          text = new TLatex(0.2,0.8,Form("PDF %d with %s: #DeltaM_{W} as of J. Rojo = %.0f MeV", WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), (deltaMJuan[k][c]/2/denominator)));
          text->SetTextSize(0.035);
          text->SetNDC();
          text->Draw();
        }

        g_deltaM_PDF[k][c]->Write();
        h_deltaM_PDF[k][c]->Write();
        c1->Write();
        
        // mean = TMath::Mean(n, &v[0]);
        // vector<double> v;
        // // std::generate(v.begin(), v.end(), 1);
        // if(k==1)
          // for(int h=0; h<WMass::PDF_members; h++){
            // // v.push_back(deltaM[h][k]);
            // cout << deltaM[h][k] << endl;
          // }
        // double meanWmass= TMath::Mean(v.begin(), v.end());
        // cout << "meanWmass= " << meanWmass << endl;
      }
      if(WMass::NtoysMomCorr>1){
        cout << endl;
        // int usedpdf = WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets;
        cout << Form("MomCorr toys with %s: #DeltaM_{W, min}= %.0f MeV, #DeltaM_{W,max}= %.0f MeV", WMass::FitVar_str[k].Data(), deltaMmin[k][c], deltaMmax[k][c]) << endl;
        double denominator = 1;

        TCanvas*c1= new TCanvas(Form("c_deltaM_PDF_%s",WMass::FitVar_str[k].Data()),Form("c_deltaM_PDF_%s",WMass::FitVar_str[k].Data()));
        g_deltaM_PDF[k][c]->Draw("ape");
        TLatex *text;
        text = new TLatex(0.2,0.85,Form("MomCorr toys with %s: #DeltaM_{W, min}= %.0f MeV, #DeltaM_{W,max}= %.0f MeV", WMass::FitVar_str[k].Data(), deltaMmin[k][c], deltaMmax[k][c]));
        text->SetTextSize(0.035);
        text->SetNDC();
        text->Draw();
        
        // if(usedpdf==232000){ // NNPDF, see ref. http://arxiv.org/pdf/1301.6754v1.pdf formulae 2.23 and 2.25
          // cout << Form("PDF %d with %s: #DeltaM_{W} square summed = -%.0f MeV, #DeltaM_{W} square summed = %.0f MeV", WMass::PDF_sets<0?generated_PDF_set:WMass::PDF_sets, WMass::FitVar_str[k].Data(), deltaMnegSummed[k]/denominator, deltaMposSummed[k]/denominator) << endl;
          denominator = TMath::Sqrt(WMass::NtoysMomCorr/2-1);
          cout << Form("MomCorr toys with %s: #DeltaM_{W} square summed = %.0f MeV", WMass::FitVar_str[k].Data(), deltaMSummed[k][c]/denominator) << endl;
          text = new TLatex(0.2,0.8,Form("MomCorr toys with %s: #DeltaM_{W} square summed = %.0f MeV", WMass::FitVar_str[k].Data(), deltaMSummed[k][c]/denominator));
          text->SetTextSize(0.035);
          text->SetNDC();
          text->Draw();
        // }else{
          // cout << Form("MomCorr toys with %s: #DeltaM_{W} as of J. Rojo = %.0f MeV", WMass::FitVar_str[k].Data(), (deltaMJuan[k]/2/denominator)) << endl;
          // text = new TLatex(0.2,0.8,Form("MomCorr toys with %s: #DeltaM_{W} as of J. Rojo = %.0f MeV", WMass::FitVar_str[k].Data(), (deltaMJuan[k]/2/denominator)));
          // text->SetTextSize(0.035);
          // text->SetNDC();
          // text->Draw();
        // }

        g_deltaM_PDF[k][c]->Write();
        h_deltaM_PDF[k][c]->Write();
        c1->Write();

      }
    }
  }
    
    fout->Write();
    
    fout->Delete();
}
int main( int argc, const char* argv[] ){

  // List of arguments:
  // 0: The executable itself
  // 1: The number of times JetMET is smeared (not smeared if equal to 1)
  // 2: The scale and type of JES shift (if fabs(x) < 0.5, shift by eta, else absolute

// fixme: Depracated
   float JES_JetMET = 1.0;

  string xmlFileName = string ("./MyMassAnalysis.xml");

  for (int i=1;i<argc;++i) {
    if (strncmp(argv[i],"-c",2)==0) xmlFileName = string(argv[i+1]);
    if (strncmp(argv[i],"-h",2)==0) {
      cout << " -c xm_config_file\n";
      exit(1);
    }
  }

  cout<<"#########################"<<endl;
  cout<<"Beginning of the program"<<endl;
  cout<<"#########################"<<endl;

  //////////////////////
  //Global variables
  //////////////////////

  // GEN
  TH1F * histoGenTopRapidity1 = new TH1F("GenTopRapidity1", "GenTopRapidity1", 100, -5, 5);
  TH1F * histoGenTopRapidity2 = new TH1F("GenTopRapidity2", "GenTopRapidity2", 100, -5, 5);
  TH1F * histoGenTopMass1 = new TH1F("GenTopMass1", "GenTopMass1", 200, 0, 200);
  TH1F * histoGenTopMass2 = new TH1F("GenTopMass2", "GenTopMass2", 200, 0, 200);
  TH2F * histoGenTopMass1VsTopMass2 = new TH2F("GenTopMass1VsTopMass2", "GenTopMass1VsTopMass2", 200, 0, 200, 200, 0, 200);
  TH1F * histoGenDelta_y = new TH1F("GenDelta_y", "GenDelta_y", 400, -2, 2);
  TH1F * histoGenTTRapidity = new TH1F("GenTTRapidity", "GenTTRapidity", 500, -2.5, 2.5);
  TH1F * histoGenTTPt = new TH1F("GenTTPt", "GenTTPt", 250, 0, 250);
  TH1F * histoGenTTMass = new TH1F("GenTTMass", "GenTTMass", 100, 0, 1000);

  TH2F * histoGenDelta_yVsTTRapidity = new TH2F("GenDelta_yVsTTRapidity", "GenDelta_yVsTTRapidity", 10, -2, 2, 5, -2.5, 2.5);
  TH2F * histoGenDelta_yVsTTPt = new TH2F("GenDelta_yVsTTPt", "GenDelta_yVsTTPt", 10, -2, 2, 5, 0, 250);
  TH2F * histoGenDelta_yVsTTMass = new TH2F("GenDelta_yVsTTMass", "GenDelta_yVsTTMass", 10, -2, 2, 5, 0, 1000);
  TH1F * histoGenN_plusTTRapidity = new TH1F("GenN_plusTTRapidity", "GenN_plusTTRapidity", 20, -2.5, 2.5);
  histoGenN_plusTTRapidity->Sumw2();
  TH1F * histoGenN_plusTTPt = new TH1F("GenN_plusTTPt", "GenN_plusTTPt", 20, 0, 250);
  histoGenN_plusTTPt->Sumw2();
  TH1F * histoGenN_plusTTMass = new TH1F("GenN_plusTTMass", "GenN_plusTTMass", 20, 0, 1000);
  histoGenN_plusTTMass->Sumw2();
  TH1F * histoGenN_minusTTRapidity = new TH1F("GenN_minusTTRapidity", "GenN_minusTTRapidity", 20, -2.5, 2.5);
  histoGenN_minusTTRapidity->Sumw2();
  TH1F * histoGenN_minusTTPt = new TH1F("GenN_minusTTPt", "GenN_minusTTPt", 20, 0, 250);
  histoGenN_minusTTPt->Sumw2();
  TH1F * histoGenN_minusTTMass = new TH1F("GenN_minusTTMass", "GenN_minusTTMass", 20, 0, 1000);
  histoGenN_minusTTMass->Sumw2();
  TH1F * histoGenN_plusMinusN_minusTTRapidity = new TH1F("GenN_plusMinusN_minusTTRapidity", "GenN_plusMinusN_minusTTRapidity", 20, -2.5, 2.5);
  histoGenN_plusMinusN_minusTTRapidity->Sumw2();
  TH1F * histoGenN_plusPlusN_minusTTRapidity = new TH1F("GenN_plusPlusN_minusTTRapidity", "GenN_plusPlusN_minusTTRapidity", 20, -2.5, 2.5);
  histoGenN_plusPlusN_minusTTRapidity->Sumw2();
  TH1F * histoGenN_plusMinusN_minusTTPt = new TH1F("GenN_plusMinusN_minusTTPt", "GenN_plusMinusN_minusTTPt", 20, 0, 250);
  histoGenN_plusMinusN_minusTTPt->Sumw2();
  TH1F * histoGenN_plusPlusN_minusTTPt = new TH1F("GenN_plusPlusN_minusTTPt", "GenN_plusPlusN_minusTTPt", 20, 0, 250);
  histoGenN_plusPlusN_minusTTPt->Sumw2();
  TH1F * histoGenN_plusMinusN_minusTTMass = new TH1F("GenN_plusMinusN_minusTTMass", "GenN_plusMinusN_minusTTMass", 20, 0, 1000);
  histoGenN_plusMinusN_minusTTMass->Sumw2();
  TH1F * histoGenN_plusPlusN_minusTTMass = new TH1F("GenN_plusPlusN_minusTTMass", "GenN_plusPlusN_minusTTMass", 20, 0, 1000);
  histoGenN_plusPlusN_minusTTMass->Sumw2();
  TH1F * histoGenA_cTTRapidity = new TH1F("GenA_cTTRapidity", "GenA_cTTRapidity", 20, -2.5, 2.5);
  histoGenA_cTTRapidity->Sumw2();
  TH1F * histoGenA_cTTPt = new TH1F("GenA_cTTPt", "GenA_cTTPt", 20, 0, 250);
  histoGenA_cTTPt->Sumw2();
  TH1F * histoGenA_cTTMass = new TH1F("GenA_cTTMass", "GenA_cTTMass", 20, 0, 1000);
  histoGenA_cTTMass->Sumw2();
  // Fine binning
  TH2F * histoFineBinning_GenDelta_yVsTTRapidity = new TH2F("FineBinning_GenDelta_yVsTTRapidity", "FineBinning_GenDelta_yVsTTRapidity", 200, -2, 2, 500, -2.5, 2.5);
  TH2F * histoFineBinning_GenDelta_yVsTTPt = new TH2F("FineBinning_GenDelta_yVsTTPt", "FineBinning_GenDelta_yVsTTPt", 200, -2, 2, 250, 0, 250);
  TH2F * histoFineBinning_GenDelta_yVsTTMass = new TH2F("FineBinning_GenDelta_yVsTTMass", "FineBinning_GenDelta_yVsTTMass", 200, -2, 2, 100, 0, 1000);
  TH1F * histoFineBinning_GenN_plusTTRapidity = new TH1F("FineBinning_GenN_plusTTRapidity", "FineBinning_GenN_plusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_GenN_plusTTRapidity->Sumw2();
  TH1F * histoFineBinning_GenN_plusTTPt = new TH1F("FineBinning_GenN_plusTTPt", "FineBinning_GenN_plusTTPt", 250, 0, 250);
  histoFineBinning_GenN_plusTTPt->Sumw2();
  TH1F * histoFineBinning_GenN_plusTTMass = new TH1F("FineBinning_GenN_plusTTMass", "FineBinning_GenN_plusTTMass", 100, 0, 1000);
  histoFineBinning_GenN_plusTTMass->Sumw2();
  TH1F * histoFineBinning_GenN_minusTTRapidity = new TH1F("FineBinning_GenN_minusTTRapidity", "FineBinning_GenN_minusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_GenN_minusTTRapidity->Sumw2();
  TH1F * histoFineBinning_GenN_minusTTPt = new TH1F("FineBinning_GenN_minusTTPt", "FineBinning_GenN_minusTTPt", 250, 0, 250);
  histoFineBinning_GenN_minusTTPt->Sumw2();
  TH1F * histoFineBinning_GenN_minusTTMass = new TH1F("FineBinning_GenN_minusTTMass", "FineBinning_GenN_minusTTMass", 100, 0, 1000);
  histoFineBinning_GenN_minusTTMass->Sumw2();
  TH1F * histoFineBinning_GenN_plusMinusN_minusTTRapidity = new TH1F("FineBinning_GenN_plusMinusN_minusTTRapidity", "FineBinning_GenN_plusMinusN_minusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_GenN_plusMinusN_minusTTRapidity->Sumw2();
  TH1F * histoFineBinning_GenN_plusPlusN_minusTTRapidity = new TH1F("FineBinning_GenN_plusPlusN_minusTTRapidity", "FineBinning_GenN_plusPlusN_minusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_GenN_plusPlusN_minusTTRapidity->Sumw2();
  TH1F * histoFineBinning_GenN_plusMinusN_minusTTPt = new TH1F("FineBinning_GenN_plusMinusN_minusTTPt", "FineBinning_GenN_plusMinusN_minusTTPt", 250, 0, 250);
  histoFineBinning_GenN_plusMinusN_minusTTPt->Sumw2();
  TH1F * histoFineBinning_GenN_plusPlusN_minusTTPt = new TH1F("FineBinning_GenN_plusPlusN_minusTTPt", "FineBinning_GenN_plusPlusN_minusTTPt", 250, 0, 250);
  histoFineBinning_GenN_plusPlusN_minusTTPt->Sumw2();
  TH1F * histoFineBinning_GenN_plusMinusN_minusTTMass = new TH1F("FineBinning_GenN_plusMinusN_minusTTMass", "FineBinning_GenN_plusMinusN_minusTTMass", 100, 0, 1000);
  histoFineBinning_GenN_plusMinusN_minusTTMass->Sumw2();
  TH1F * histoFineBinning_GenN_plusPlusN_minusTTMass = new TH1F("FineBinning_GenN_plusPlusN_minusTTMass", "FineBinning_GenN_plusPlusN_minusTTMass", 100, 0, 1000);
  histoFineBinning_GenN_plusPlusN_minusTTMass->Sumw2();
  TH1F * histoFineBinning_GenA_cTTRapidity = new TH1F("FineBinning_GenA_cTTRapidity", "FineBinning_GenA_cTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_GenA_cTTRapidity->Sumw2();
  TH1F * histoFineBinning_GenA_cTTPt = new TH1F("FineBinning_GenA_cTTPt", "FineBinning_GenA_cTTPt", 250, 0, 250);
  histoFineBinning_GenA_cTTPt->Sumw2();
  TH1F * histoFineBinning_GenA_cTTMass = new TH1F("FineBinning_GenA_cTTMass", "FineBinning_GenA_cTTMass", 100, 0, 1000);
  histoFineBinning_GenA_cTTMass->Sumw2();


  // RECO
  TH1F * histoRecoTopRapidity1 = new TH1F("RecoTopRapidity1", "RecoTopRapidity1", 100, -5, 5);
  TH1F * histoRecoTopRapidity2 = new TH1F("RecoTopRapidity2", "RecoTopRapidity2", 100, -5, 5);
  TH1F * histoRecoLeptonRapidity1 = new TH1F("RecoLeptonRapidity1", "RecoLeptonRapidity1", 100, -5, 5);
  TH1F * histoRecoLeptonRapidity2 = new TH1F("RecoLeptonRapidity2", "RecoLeptonRapidity2", 100, -5, 5);
  TH1F * histoRecoTopMass1 = new TH1F("RecoTopMass1", "RecoTopMass1", 300, 0, 300);
  TH1F * histoRecoTopMass2 = new TH1F("RecoTopMass2", "RecoTopMass2", 300, 0, 300);
  TH2F * histoRecoTopMass1VsTopMass2 = new TH2F("RecoTopMass1VsTopMass2", "RecoTopMass1VsTopMass2", 300, 0, 300, 300, 0, 300);
  TH1F * histoRecoDelta_y = new TH1F("RecoDelta_y", "RecoDelta_y", 400, -2, 2);
  TH1F * histoRecoTTRapidity = new TH1F("RecoTTRapidity", "RecoTTRapidity", 500, -2.5, 2.5);
  TH1F * histoRecoTTPt = new TH1F("RecoTTPt", "RecoTTPt", 250, 0, 250);
  TH1F * histoRecoTTMass = new TH1F("RecoTTMass", "RecoTTMass", 100, 0, 1000);

  TH2F * histoRecoDelta_yVsTTRapidity = new TH2F("RecoDelta_yVsTTRapidity", "RecoDelta_yVsTTRapidity", 10, -2, 2, 5, -2.5, 2.5);
  TH2F * histoRecoDelta_yVsTTPt = new TH2F("RecoDelta_yVsTTPt", "RecoDelta_yVsTTPt", 10, -2, 2, 5, 0, 250);
  TH2F * histoRecoDelta_yVsTTMass = new TH2F("RecoDelta_yVsTTMass", "RecoDelta_yVsTTMass", 10, -2, 2, 5, 0, 1000);
  TH1F * histoRecoN_plusTTRapidity = new TH1F("RecoN_plusTTRapidity", "RecoN_plusTTRapidity", 20, -2.5, 2.5);
  histoRecoN_plusTTRapidity->Sumw2();
  TH1F * histoRecoN_plusTTPt = new TH1F("RecoN_plusTTPt", "RecoN_plusTTPt", 20, 0, 250);
  histoRecoN_plusTTPt->Sumw2();
  TH1F * histoRecoN_plusTTMass = new TH1F("RecoN_plusTTMass", "RecoN_plusTTMass", 20, 0, 1000);
  histoRecoN_plusTTMass->Sumw2();
  TH1F * histoRecoN_minusTTRapidity = new TH1F("RecoN_minusTTRapidity", "RecoN_minusTTRapidity", 20, -2.5, 2.5);
  histoRecoN_minusTTRapidity->Sumw2();
  TH1F * histoRecoN_minusTTPt = new TH1F("RecoN_minusTTPt", "RecoN_minusTTPt", 20, 0, 250);
  histoRecoN_minusTTPt->Sumw2();
  TH1F * histoRecoN_minusTTMass = new TH1F("RecoN_minusTTMass", "RecoN_minusTTMass", 20, 0, 1000);
  histoRecoN_minusTTMass->Sumw2();
  TH1F * histoRecoN_plusMinusN_minusTTRapidity = new TH1F("RecoN_plusMinusN_minusTTRapidity", "RecoN_plusMinusN_minusTTRapidity", 20, -2.5, 2.5);
  histoRecoN_plusMinusN_minusTTRapidity->Sumw2();
  TH1F * histoRecoN_plusPlusN_minusTTRapidity = new TH1F("RecoN_plusPlusN_minusTTRapidity", "RecoN_plusPlusN_minusTTRapidity", 20, -2.5, 2.5);
  histoRecoN_plusPlusN_minusTTRapidity->Sumw2();
  TH1F * histoRecoN_plusMinusN_minusTTPt = new TH1F("RecoN_plusMinusN_minusTTPt", "RecoN_plusMinusN_minusTTPt", 20, 0, 250);
  histoRecoN_plusMinusN_minusTTPt->Sumw2();
  TH1F * histoRecoN_plusPlusN_minusTTPt = new TH1F("RecoN_plusPlusN_minusTTPt", "RecoN_plusPlusN_minusTTPt", 20, 0, 250);
  histoRecoN_plusPlusN_minusTTPt->Sumw2();
  TH1F * histoRecoN_plusMinusN_minusTTMass = new TH1F("RecoN_plusMinusN_minusTTMass", "RecoN_plusMinusN_minusTTMass", 20, 0, 1000);
  histoRecoN_plusMinusN_minusTTMass->Sumw2();
  TH1F * histoRecoN_plusPlusN_minusTTMass = new TH1F("RecoN_plusPlusN_minusTTMass", "RecoN_plusPlusN_minusTTMass", 20, 0, 1000);
  histoRecoN_plusPlusN_minusTTMass->Sumw2();
  TH1F * histoRecoA_cTTRapidity = new TH1F("RecoA_cTTRapidity", "RecoA_cTTRapidity", 20, -2.5, 2.5);
  histoRecoA_cTTRapidity->Sumw2();
  TH1F * histoRecoA_cTTPt = new TH1F("RecoA_cTTPt", "RecoA_cTTPt", 20, 0, 250);
  histoRecoA_cTTPt->Sumw2();
  TH1F * histoRecoA_cTTMass = new TH1F("RecoA_cTTMass", "RecoA_cTTMass", 20, 0, 1000);
  histoRecoA_cTTMass->Sumw2();
  // Fine binning
  TH2F * histoFineBinning_RecoDelta_yVsTTRapidity = new TH2F("FineBinning_RecoDelta_yVsTTRapidity", "FineBinning_RecoDelta_yVsTTRapidity", 200, -2, 2, 500, -2.5, 2.5);
  TH2F * histoFineBinning_RecoDelta_yVsTTPt = new TH2F("FineBinning_RecoDelta_yVsTTPt", "FineBinning_RecoDelta_yVsTTPt", 200, -2, 2, 250, 0, 250);
  TH2F * histoFineBinning_RecoDelta_yVsTTMass = new TH2F("FineBinning_RecoDelta_yVsTTMass", "FineBinning_RecoDelta_yVsTTMass", 200, -2, 2, 100, 0, 1000);
  TH1F * histoFineBinning_RecoN_plusTTRapidity = new TH1F("FineBinning_RecoN_plusTTRapidity", "FineBinning_RecoN_plusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_RecoN_plusTTRapidity->Sumw2();
  TH1F * histoFineBinning_RecoN_plusTTPt = new TH1F("FineBinning_RecoN_plusTTPt", "FineBinning_RecoN_plusTTPt", 250, 0, 250);
  histoFineBinning_RecoN_plusTTPt->Sumw2();
  TH1F * histoFineBinning_RecoN_plusTTMass = new TH1F("FineBinning_RecoN_plusTTMass", "FineBinning_RecoN_plusTTMass", 100, 0, 1000);
  histoFineBinning_RecoN_plusTTMass->Sumw2();
  TH1F * histoFineBinning_RecoN_minusTTRapidity = new TH1F("FineBinning_RecoN_minusTTRapidity", "FineBinning_RecoN_minusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_RecoN_minusTTRapidity->Sumw2();
  TH1F * histoFineBinning_RecoN_minusTTPt = new TH1F("FineBinning_RecoN_minusTTPt", "FineBinning_RecoN_minusTTPt", 250, 0, 250);
  histoFineBinning_RecoN_minusTTPt->Sumw2();
  TH1F * histoFineBinning_RecoN_minusTTMass = new TH1F("FineBinning_RecoN_minusTTMass", "FineBinning_RecoN_minusTTMass", 100, 0, 1000);
  histoFineBinning_RecoN_minusTTMass->Sumw2();
  TH1F * histoFineBinning_RecoN_plusMinusN_minusTTRapidity = new TH1F("FineBinning_RecoN_plusMinusN_minusTTRapidity", "FineBinning_RecoN_plusMinusN_minusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_RecoN_plusMinusN_minusTTRapidity->Sumw2();  
  TH1F * histoFineBinning_RecoN_plusPlusN_minusTTRapidity = new TH1F("FineBinning_RecoN_plusPlusN_minusTTRapidity", "FineBinning_RecoN_plusPlusN_minusTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_RecoN_plusPlusN_minusTTRapidity->Sumw2();
  TH1F * histoFineBinning_RecoN_plusMinusN_minusTTPt = new TH1F("FineBinning_RecoN_plusMinusN_minusTTPt", "FineBinning_RecoN_plusMinusN_minusTTPt", 250, 0, 250);
  histoFineBinning_RecoN_plusMinusN_minusTTPt->Sumw2();
  TH1F * histoFineBinning_RecoN_plusPlusN_minusTTPt = new TH1F("FineBinning_RecoN_plusPlusN_minusTTPt", "FineBinning_RecoN_plusPlusN_minusTTPt", 250, 0, 250);
  histoFineBinning_RecoN_plusPlusN_minusTTPt->Sumw2();
  TH1F * histoFineBinning_RecoN_plusMinusN_minusTTMass = new TH1F("FineBinning_RecoN_plusMinusN_minusTTMass", "FineBinning_RecoN_plusMinusN_minusTTMass", 100, 0, 1000);
  histoFineBinning_RecoN_plusMinusN_minusTTMass->Sumw2();
  TH1F * histoFineBinning_RecoN_plusPlusN_minusTTMass = new TH1F("FineBinning_RecoN_plusPlusN_minusTTMass", "FineBinning_RecoN_plusPlusN_minusTTMass", 100, 0, 1000);
  histoFineBinning_RecoN_plusPlusN_minusTTMass->Sumw2();
  TH1F * histoFineBinning_RecoA_cTTRapidity = new TH1F("FineBinning_RecoA_cTTRapidity", "FineBinning_RecoA_cTTRapidity", 500, -2.5, 2.5);
  histoFineBinning_RecoA_cTTRapidity->Sumw2();
  TH1F * histoFineBinning_RecoA_cTTPt = new TH1F("FineBinning_RecoA_cTTPt", "FineBinning_RecoA_cTTPt", 250, 0, 250);
  histoFineBinning_RecoA_cTTPt->Sumw2();
  TH1F * histoFineBinning_RecoA_cTTMass = new TH1F("FineBinning_RecoA_cTTMass", "FineBinning_RecoA_cTTMass", 100, 0, 1000);
  histoFineBinning_RecoA_cTTMass->Sumw2();




  // RECO vs GEN
  TH2F * histoRecoVsGenTopRapidity1 = new TH2F("RecoVsGenTopRapidity1", "RecoVsGenTopRapidity1", 100, -5, 5, 100, -5, 5);
  TH2F * histoRecoVsGenTopRapidity2 = new TH2F("RecoVsGenTopRapidity2", "RecoVsGenTopRapidity2", 100, -5, 5, 100, -5, 5);
  TH2F * histoRecoVsGenTopMass1 = new TH2F("RecoVsGenTopMass1", "RecoVsGenTopMass1", 300, 0, 300, 200, 0, 200);
  TH2F * histoRecoVsGenTopMass2 = new TH2F("RecoVsGenTopMass2", "RecoVsGenTopMass2", 300, 0, 300, 200, 0, 200);
  TH1F * histoRecoMinusGenDivGenTopRapidity1 = new TH1F("RecoMinusGenDivGenTopRapidity1", "RecoMinusGenDivGenTopRapidity1", 100, -3, 3);
  TH1F * histoRecoMinusGenDivGenTopRapidity2 = new TH1F("RecoMinusGenDivGenTopRapidity2", "RecoMinusGenDivGenTopRapidity2", 100, -3, 3);
  TH1F * histoRecoMinusGenDivGenLeptonRapidity1 = new TH1F("RecoMinusGenDivGenLeptonRapidity1", "RecoMinusGenDivGenLeptonRapidity1", 100, -3, 3);
  TH1F * histoRecoMinusGenDivGenLeptonRapidity2 = new TH1F("RecoMinusGenDivGenLeptonRapidity2", "RecoMinusGenDivGenLeptonRapidity2", 100, -3, 3);
  TH1F * histoRecoMinusGenDivGenTopMass1 = new TH1F("RecoMinusGenDivGenTopMass1", "RecoMinusGenDivGenTopMass1", 100, -3, 3);
  TH1F * histoRecoMinusGenDivGenTopMass2 = new TH1F("RecoMinusGenDivGenTopMass2", "RecoMinusGenDivGenTopMass2", 100, -3, 3);

  TH2F * histoFineBinning_RecoVsGenDelta_y = new TH2F("FineBinning_RecoVsGenDelta_y", "FineBinning_RecoVsGenDelta_y", 400, -2, 2, 400, -2, 2); // Migration Matrix
  TH2F * histoRecoVsGenDelta_y = new TH2F("RecoVsGenDelta_y", "RecoVsGenDelta_y", 8, -2, 2, 16, -2, 2); // Migration Matrix
  TH1F * histoRecoMinusGenDivGenDelta_y = new TH1F("RecoMinusGenDivGenDelta_y", "RecoMinusGenDivGenDelta_y", 100, -3, 3);

  TH2F * histoRecoVsGenTTRapidity = new TH2F("RecoVsGenTTRapidity", "RecoVsGenTTRapidity", 500, -2.5, 2.5, 500, -2.5, 2.5);
  TH1F * histoRecoMinusGenDivGenTTRapidity = new TH1F("RecoMinusGenDivGenTTRapidity", "RecoMinusGenDivGenTTRapidity", 100, -3, 3);
  TH2F * histoRecoVsGenTTPt = new TH2F("RecoVsGenTTPt", "RecoVsGenTTPt", 250, 0, 250, 250, 0, 250);
  TH1F * histoRecoMinusGenDivGenTTPt = new TH1F("RecoMinusGenDivGenTTPt", "RecoMinusGenDivGenTTPt", 100, -3, 3);
  TH2F * histoRecoVsGenTTMass = new TH2F("RecoVsGenTTMass", "RecoVsGenTTMass", 100, 0, 1000, 100, 0, 1000);
  TH1F * histoRecoMinusGenDivGenTTMass = new TH1F("RecoMinusGenDivGenTTMass", "RecoMinusGenDivGenTTMass", 100, -3, 3);

  TH1F * histoDelta_yEfficiencyN = new TH1F("Delta_yEfficiencyN", "Delta_yEfficiencyN", 10, -2, 2);
  TH1F * histoDelta_yEfficiencyD = new TH1F("Delta_yEfficiencyD", "Delta_yEfficiencyD", 10, -2, 2);
  TH1F * histoDelta_yEfficiency = new TH1F("Delta_yEfficiency", "Delta_yEfficiency", 10, -2, 2);

  TH2F * histoDelta_yVsTTRapidityEfficiency = new TH2F("Delta_yVsTTRapidityEfficiency", "Delta_yVsTTRapidityEfficiency", 10, -2, 2, 5, -2.5, 2.5);
  TH2F * histoDelta_yVsTTPtEfficiency = new TH2F("Delta_yVsTTPtEfficiency", "Delta_yVsTTPtEfficiency", 10, -2, 2, 5, 0, 250);
  TH2F * histoDelta_yVsTTMassEfficiency = new TH2F("Delta_yVsTTMassEfficiency", "Delta_yVsTTMassEfficiency", 10, -2, 2, 5, 0, 1000);
  // Fine binning
  TH1F * histoFineBinning_Delta_yEfficiencyN = new TH1F("FineBinning_Delta_yEfficiencyN", "FineBinning_Delta_yEfficiencyN", 200, -2, 2);
  TH1F * histoFineBinning_Delta_yEfficiencyD = new TH1F("FineBinning_Delta_yEfficiencyD", "FineBinning_Delta_yEfficiencyD", 200, -2, 2);
  TH1F * histoFineBinning_Delta_yEfficiency = new TH1F("FineBinning_Delta_yEfficiency", "FineBinning_Delta_yEfficiency", 200, -2, 2);

  TH2F * histoFineBinning_Delta_yVsTTRapidityEfficiency = new TH2F("FineBinning_Delta_yVsTTRapidityEfficiency", "FineBinning_Delta_yVsTTRapidityEfficiency", 200, -2, 2, 500, -2.5, 2.5);
  TH2F * histoFineBinning_Delta_yVsTTPtEfficiency = new TH2F("FineBinning_Delta_yVsTTPtEfficiency", "FineBinning_Delta_yVsTTPtEfficiency", 200, -2, 2, 250, 0, 250);
  TH2F * histoFineBinning_Delta_yVsTTMassEfficiency = new TH2F("FineBinning_Delta_yVsTTMassEfficiency", "FineBinning_Delta_yVsTTMassEfficiency", 200, -2, 2, 100, 0, 1000);




  vector < Dataset > datasets;
  DiLeptonSelection sel;
  float Luminosity = 0;
  // 0: MC - 1: Data - 2 Data & MC
  int DataType = 0;
  int verbosity = -1;
  
  // Analysis variables
  int step;
  //4-vectors
  vector < TLorentzVector > nu1;
  vector < TLorentzVector > nu2;
  //  TLorentzVector lvTop1_aux;
  //TLorentzVector lvTop2_aux;

  //////////////////////

  //////////////////////
  // Initialisation
  //////////////////////
  AnalysisEnvironmentLoader anaEL (xmlFileName);
  anaEL.LoadSamples (datasets); // now the list of datasets written in the xml file is known
  anaEL.LoadDiLeptonSelection (sel); // now the parameters for the selection are given to the selection
  anaEL.LoadGeneralInfo(DataType, Luminosity, verbosity );

  float weight_MC; 
  int nEvents;
  int firstEvent;
  int initialEvents;
  anaEL.LoadAnalysisInfo("Run", "firstEvent", firstEvent);
  anaEL.LoadAnalysisInfo("Run", "nEvents", nEvents);
  anaEL.LoadAnalysisInfo("Run", "initialEvents", initialEvents);
  string channelName;
  anaEL.LoadAnalysisInfo("MassAnalysis", "ChannelName", channelName);

  anaEL.LoadWeight (sel); // now the parameters for SFBweight are initialized (for b-tag!)

  //******************************************
  //Load Scale Factors for lepton efficiencies
  //******************************************
  sel.LoadElScaleFactors();
  sel.LoadMuScaleFactors();
  sel.InitJESUnc();

  bool nonskimmed = false;

  TopTree::NTEvent * event = 0;

  TFile * TupleFile = new TFile("TupleFileSkimmed_ZJets.root","RECREATE");
  float mttbar_rec, mttbar_gen;
  float diffysquare_rec, diffysquare_gen;
  float diffabseta_rec, diffabseta_gen;
  float weight;
  float pt_ttbar, pt_ttbar_gen;
  float pz_ttbar, pz_ttbar_gen;
  float eta_ttbar_rec, eta_ttbar_gen;
  float y_ttbar_rec, y_ttbar_gen;
  float diffabsy_rec, diffabsy_gen;

  TTree *tree = new TTree("Tuple","Tuple");
  tree->Branch("mttbar_rec",&mttbar_rec,"mttbar_rec/F");
  tree->Branch("mttbar_gen",&mttbar_gen,"mttbar_gen/F");
  tree->Branch("diffysquare_rec",&diffysquare_rec,"diffysquare_rec/F");
  tree->Branch("diffysquare_gen",&diffysquare_gen,"diffysquare_gen/F");
  tree->Branch("diffabseta_rec",&diffabseta_rec,"diffabseta_rec/F");
  tree->Branch("diffabseta_gen",&diffabseta_gen,"diffabseta_gen/F");
  tree->Branch("weight",&weight,"weight/F");
  tree->Branch("pt_ttbar",&pt_ttbar,"pt_ttbar/F");
  tree->Branch("pt_ttbar_gen",&pt_ttbar_gen,"pt_ttbar_gen/F");
  tree->Branch("pz_ttbar",&pz_ttbar,"pz_ttbar/F");
  tree->Branch("pz_ttbar_gen",&pz_ttbar_gen,"pz_ttbar_gen/F");
  tree->Branch("eta_ttbar_rec",&eta_ttbar_rec,"eta_ttbar_rec/F");
  tree->Branch("eta_ttbar_gen",&eta_ttbar_gen,"eta_ttbar_gen/F");
  tree->Branch("y_ttbar_rec",&y_ttbar_rec,"y_ttbar_rec/F");
  tree->Branch("y_ttbar_gen",&y_ttbar_gen,"y_ttbar_gen/F");
  tree->Branch("diffabsy_rec",&diffabsy_rec,"diffabsy_rec/F");
  tree->Branch("diffabsy_gen",&diffabsy_gen,"diffabsy_gen/F");

  //////////////////////
  //LOOP OVER THE DATASETS
  //////////////////////
  if(verbosity>0) {
    cout<<"#########################"<<endl;
    cout<<" Loop over the datasets  "<<endl;
    cout<<"#########################"<<endl;
  }

  float num_mttbar_eff = 0.;
  float den_mttbar_eff = 0.;

  for (unsigned int d = 0; d < datasets.size (); d++) {

    weight_MC = datasets[d].NormFactor()*Luminosity;

    if(datasets[d].isData() == true) weight_MC = 1.; cout << "isDATA" << endl;

    AMWT amwt(anaEL, datasets[d].isData());

    TString sample_name(datasets[d].Name());


    bool isData = datasets[d].isData ();
    datasets[d].eventTree ()->SetBranchAddress ("NTEvent",&event);

    cout << "Sample : " << sample_name<< endl;
    cout << "Data   : " << isData<< endl;

    unsigned int nEventsSample = (int) (datasets[d].eventTree ()->GetEntries ());
    unsigned int endEventToRun;

    if (firstEvent>nEventsSample) firstEvent = nEventsSample;
    if ((nEvents==-1)||((nEvents+firstEvent)>nEventsSample)) endEventToRun = nEventsSample;
    else endEventToRun = nEvents+firstEvent;
    cout << "Events to run: number / first / last / all: " << endEventToRun-firstEvent 
         << " / " << firstEvent << " / " << endEventToRun
         << " / " << nEventsSample << endl;

// Standard parameters for doFullSelection:

    bool applyEEScale = false; float EEScaleParam = 1.; bool applyEEResol = false; float EEResolParam = 1.;
    bool applyMEScale = false; float MEScaleParam = 1.; bool applyMEResol = false; float MEResolParam = 1.;
    bool applyMETS = false; float METScale = 1.;
    bool applyJES = false; float JESParam = 1.;
    bool applyJER = false; float JERFactor = 0.; 

    //////////////////////
    //LOOP OVER THE EVENTS
    //////////////////////

    float N_plus_reco = 0;
    float N_minus_reco = 0;

    float N_plus_gen = 0;
    float N_minus_gen = 0;

    mttbar_rec = 0;
    mttbar_gen = 0;
    diffysquare_rec = 0;
    diffysquare_gen = 0;
    diffabseta_rec = 0;
    diffabseta_gen = 0;
    weight = weight_MC;
    pt_ttbar = 0;
    pt_ttbar_gen = 0;
    pz_ttbar = 0;
    pz_ttbar_gen = 0;
    eta_ttbar_rec = 0;
    eta_ttbar_gen = 0;
    y_ttbar_rec = 0;
    y_ttbar_gen = 0;
    diffabsy_rec = 0;
    diffabsy_gen = 0;

    for (unsigned int ievt = firstEvent; ievt < endEventToRun; ievt++) {
//           for (unsigned int ievt = 0; ievt < 10; ievt++) {

      datasets[d].eventTree ()->GetEntry (ievt);

      if(ievt%1000 == 0) cout << "number of processed events " << ievt << endl;
      if (verbosity >= 1) cout << "Event : "<< event->runNb<<" , " << event->lumiblock <<" , " << event->eventNb<<endl;

      string candType;
      vector<NTElectron> candElec;
      vector<NTMuon> candMuon;

      //Load event for the selection
      sel.LoadEvent(event);

      //Manage DY samples to avoid overlaps
      double dileptInvMass = 0;
      if( (event->zAndDecays).size() > 0){
        TLorentzVector dilept = (event->zAndDecays)[0].p4_Lep1_gen + (event->zAndDecays)[0].p4_Lep2_gen;
        dileptInvMass = dilept.M();
      }
      if(datasets[d].Name()=="Zjets" && dileptInvMass < 50) continue;
      if(datasets[d].Name()=="DYToMuMu_M-20"	   && (dileptInvMass > 50 || dileptInvMass < 20) ) continue;
      if(datasets[d].Name()=="DYToEE_M-20"        && (dileptInvMass > 50 || dileptInvMass < 20) ) continue;
      if(datasets[d].Name()=="DYToTauTau_M-20"    && (dileptInvMass > 50 || dileptInvMass < 20) ) continue;
      if(datasets[d].Name()=="DYToMuMu_M-10To20"   &&  dileptInvMass > 20) continue;
      if(datasets[d].Name()=="DYToEE_M-10To20"    &&  dileptInvMass > 20) continue;
      if(datasets[d].Name()=="DYToTauTau_M-10To20" &&  dileptInvMass > 20) continue;

      int finalCut = sel.doFullSelection(&(datasets[d]), channelName, false, /*print*/ verbosity,
	false, false, -1., -1., applyJES,  JESParam,
	 applyEEScale,  EEScaleParam,  applyEEResol,  EEResolParam,
	 applyMEScale,  MEScaleParam,  
	 applyJER,  JERFactor,  applyMETS,  METScale);




        TLorentzVector lvTop1_gen;
        TLorentzVector lvTop2_gen;
        TLorentzVector lvTop1plusTop2_gen;
        float yt_gen = 0.;
        float ytbar_gen = 0.;
        float Delta_y_gen = 0.;

        if(datasets[d].Name() == "TTJets_Sig"){


        lvTop1_gen = (event->topAndDecays)[0].p4_t_gen;
        lvTop2_gen = (event->topAndDecays)[1].p4_t_gen;
        lvTop1plusTop2_gen = lvTop1_gen + lvTop2_gen;

        /////////////////////////
        //// GENERATOR LEVEL ////
        /////////////////////////

        histoGenTopRapidity1->Fill(lvTop1_gen.Rapidity());
        histoGenTopRapidity2->Fill(lvTop2_gen.Rapidity());
        histoGenTopMass1->Fill(lvTop1_gen.M());
        histoGenTopMass2->Fill(lvTop2_gen.M());
        histoGenTopMass1VsTopMass2->Fill(lvTop1_gen.M(),lvTop2_gen.M());

        yt_gen = lvTop1_gen.Rapidity();
        if(yt_gen<0.) yt_gen = (-1)*yt_gen;
        ytbar_gen = lvTop2_gen.Rapidity();
        if(ytbar_gen<0.) ytbar_gen = (-1)*ytbar_gen;
        Delta_y_gen = yt_gen - ytbar_gen;
	//        cout << "Delta_y_gen:" << Delta_y_gen << endl;
        histoGenDelta_y->Fill(Delta_y_gen);
        histoDelta_yEfficiencyD->Fill(Delta_y_gen);
        histoFineBinning_Delta_yEfficiencyD->Fill(Delta_y_gen);

        if(Delta_y_gen>0.){
          N_plus_gen++;
          histoGenN_plusTTRapidity->Fill(lvTop1plusTop2_gen.Rapidity());
          histoGenN_plusTTPt->Fill(lvTop1plusTop2_gen.Perp());
          histoGenN_plusTTMass->Fill(lvTop1plusTop2_gen.M());
          histoFineBinning_GenN_plusTTRapidity->Fill(lvTop1plusTop2_gen.Rapidity());
          histoFineBinning_GenN_plusTTPt->Fill(lvTop1plusTop2_gen.Perp());
          histoFineBinning_GenN_plusTTMass->Fill(lvTop1plusTop2_gen.M());
	}

        if(Delta_y_gen<0.){
          N_minus_gen++;
          histoGenN_minusTTRapidity->Fill(lvTop1plusTop2_gen.Rapidity());
          histoGenN_minusTTPt->Fill(lvTop1plusTop2_gen.Perp());
          histoGenN_minusTTMass->Fill(lvTop1plusTop2_gen.M());
          histoFineBinning_GenN_minusTTRapidity->Fill(lvTop1plusTop2_gen.Rapidity());
          histoFineBinning_GenN_minusTTPt->Fill(lvTop1plusTop2_gen.Perp());
          histoFineBinning_GenN_minusTTMass->Fill(lvTop1plusTop2_gen.M());

	}

        histoGenTTRapidity->Fill(lvTop1plusTop2_gen.Rapidity());
        histoGenTTPt->Fill(lvTop1plusTop2_gen.Perp());
        histoGenTTMass->Fill(lvTop1plusTop2_gen.M());
        histoGenDelta_yVsTTRapidity->Fill(Delta_y_gen, lvTop1plusTop2_gen.Rapidity());
        histoGenDelta_yVsTTPt->Fill(Delta_y_gen, lvTop1plusTop2_gen.Perp());
        histoGenDelta_yVsTTMass->Fill(Delta_y_gen, lvTop1plusTop2_gen.M());

        histoFineBinning_GenDelta_yVsTTRapidity->Fill(Delta_y_gen, lvTop1plusTop2_gen.Rapidity());
        histoFineBinning_GenDelta_yVsTTPt->Fill(Delta_y_gen, lvTop1plusTop2_gen.Perp());
        histoFineBinning_GenDelta_yVsTTMass->Fill(Delta_y_gen, lvTop1plusTop2_gen.M());


        if(nonskimmed == true){
         mttbar_gen = lvTop1plusTop2_gen.M();
         diffysquare_gen = yt_gen*yt_gen - ytbar_gen*ytbar_gen;
         diffabseta_gen = fabs(lvTop1_gen.Eta()) - fabs(lvTop2_gen.Eta());
         pt_ttbar_gen = lvTop1plusTop2_gen.Perp();
         pz_ttbar_gen = lvTop1plusTop2_gen.Pz();
         eta_ttbar_gen = lvTop1plusTop2_gen.Eta();
         y_ttbar_gen = lvTop1plusTop2_gen.Rapidity();
         diffabsy_gen = fabs(lvTop1_gen.Rapidity()) - fabs(lvTop2_gen.Rapidity());
	}

	}

      if (finalCut >6) {

        if(nonskimmed == false){
         if(datasets[d].Name() == "TTJets_Sig"){
         mttbar_gen = lvTop1plusTop2_gen.M();
         diffysquare_gen = yt_gen*yt_gen - ytbar_gen*ytbar_gen;
         diffabseta_gen = fabs(lvTop1_gen.Eta()) - fabs(lvTop2_gen.Eta());
         pt_ttbar_gen = lvTop1plusTop2_gen.Perp();
         pz_ttbar_gen = lvTop1plusTop2_gen.Pz();
         eta_ttbar_gen = lvTop1plusTop2_gen.Eta();
         y_ttbar_gen = lvTop1plusTop2_gen.Rapidity();
         diffabsy_gen = fabs(lvTop1_gen.Rapidity()) - fabs(lvTop2_gen.Rapidity());
	 }
	}

        sel.GetLeptonPair(candMuon, candElec, candType);

        for(unsigned int i=0; i<candMuon.size(); i++){
          if(candMuon[i].Charge == +1) histoRecoLeptonRapidity1->Fill(candMuon[i].p4.Rapidity());
          if(candMuon[i].Charge == -1) histoRecoLeptonRapidity2->Fill(candMuon[i].p4.Rapidity());
	}

        for(unsigned int j=0; j<candElec.size(); j++){
          if(candElec[j].Charge == +1) histoRecoLeptonRapidity1->Fill(candElec[j].p4.Rapidity());
          if(candElec[j].Charge == -1) histoRecoLeptonRapidity2->Fill(candElec[j].p4.Rapidity());
	}



        TLorentzVector lvTop1_reco;
        TLorentzVector lvTop2_reco;
        TLorentzVector lvTop1plusTop2_reco;


        TopMassVariables * tmv = amwt.findMass(sel, lvTop1_reco, lvTop2_reco);
        lvTop1plusTop2_reco = lvTop1_reco + lvTop2_reco;



        ////////////////////
        /// RECO LEVEL /////
        ////////////////////

        histoRecoTopRapidity1->Fill(lvTop1_reco.Rapidity());
        histoRecoTopRapidity2->Fill(lvTop2_reco.Rapidity());
        histoRecoTopMass1->Fill(lvTop1_reco.M());
        histoRecoTopMass2->Fill(lvTop2_reco.M());
        histoRecoTopMass1VsTopMass2->Fill(lvTop1_reco.M(),lvTop2_reco.M());

        float yt_reco = lvTop1_reco.Rapidity();
        if(yt_reco<0.) yt_reco = (-1)*yt_reco;
        float ytbar_reco = lvTop2_reco.Rapidity();
        if(ytbar_reco<0.) ytbar_reco = (-1)*ytbar_reco;
        float Delta_y_reco = yt_reco - ytbar_reco;
	//        cout << "Delta_y_reco:" << Delta_y_reco << endl;
        histoRecoDelta_y->Fill(Delta_y_reco);
        histoDelta_yEfficiencyN->Fill(Delta_y_reco);
        histoFineBinning_Delta_yEfficiencyN->Fill(Delta_y_reco);

        if(Delta_y_reco>0.){
          N_plus_reco++;
          histoRecoN_plusTTRapidity->Fill(lvTop1plusTop2_reco.Rapidity());
          histoRecoN_plusTTPt->Fill(lvTop1plusTop2_reco.Perp());
          histoRecoN_plusTTMass->Fill(lvTop1plusTop2_reco.M());
          histoFineBinning_RecoN_plusTTRapidity->Fill(lvTop1plusTop2_reco.Rapidity());
          histoFineBinning_RecoN_plusTTPt->Fill(lvTop1plusTop2_reco.Perp());
          histoFineBinning_RecoN_plusTTMass->Fill(lvTop1plusTop2_reco.M());
	}

        if(Delta_y_reco<0.){
          N_minus_reco++;
          histoRecoN_minusTTRapidity->Fill(lvTop1plusTop2_reco.Rapidity());
          histoRecoN_minusTTPt->Fill(lvTop1plusTop2_reco.Perp());
          histoRecoN_minusTTMass->Fill(lvTop1plusTop2_reco.M());
          histoFineBinning_RecoN_minusTTRapidity->Fill(lvTop1plusTop2_reco.Rapidity());
          histoFineBinning_RecoN_minusTTPt->Fill(lvTop1plusTop2_reco.Perp());
          histoFineBinning_RecoN_minusTTMass->Fill(lvTop1plusTop2_reco.M());
	}

        histoRecoTTRapidity->Fill(lvTop1plusTop2_reco.Rapidity());
        histoRecoTTPt->Fill(lvTop1plusTop2_reco.Perp());
        histoRecoTTMass->Fill(lvTop1plusTop2_reco.M());
        histoRecoDelta_yVsTTRapidity->Fill(Delta_y_reco, lvTop1plusTop2_reco.Rapidity());
        histoRecoDelta_yVsTTPt->Fill(Delta_y_reco, lvTop1plusTop2_reco.Perp());
        histoRecoDelta_yVsTTMass->Fill(Delta_y_reco, lvTop1plusTop2_reco.M());

        histoFineBinning_RecoDelta_yVsTTRapidity->Fill(Delta_y_reco, lvTop1plusTop2_reco.Rapidity());
        histoFineBinning_RecoDelta_yVsTTPt->Fill(Delta_y_reco, lvTop1plusTop2_reco.Perp());
        histoFineBinning_RecoDelta_yVsTTMass->Fill(Delta_y_reco, lvTop1plusTop2_reco.M());

        if(nonskimmed == false){

         mttbar_rec = lvTop1plusTop2_reco.M();
         diffysquare_rec = yt_reco*yt_reco - ytbar_reco*ytbar_reco;
         diffabseta_rec = fabs(lvTop1_reco.Eta()) - fabs(lvTop2_reco.Eta());
         pt_ttbar = lvTop1plusTop2_reco.Perp();
         pz_ttbar = lvTop1plusTop2_reco.Pz();
         eta_ttbar_rec = lvTop1plusTop2_reco.Eta();
         y_ttbar_rec = lvTop1plusTop2_reco.Rapidity();
         diffabsy_rec = fabs(lvTop1_reco.Rapidity()) - fabs(lvTop2_reco.Rapidity());

	}

        ////////////////////////
        // RECO VS GEN LEVEL ///
        ////////////////////////
        if(datasets[d].Name() == "TTJets_Sig"){
 
        histoRecoVsGenTopRapidity1->Fill(lvTop1_reco.Rapidity(), lvTop1_gen.Rapidity());
        histoRecoVsGenTopRapidity2->Fill(lvTop2_reco.Rapidity(), lvTop2_gen.Rapidity());
        histoRecoVsGenTopMass1->Fill(lvTop1_reco.M(), lvTop1_gen.M());
        histoRecoVsGenTopMass2->Fill(lvTop2_reco.M(), lvTop2_gen.M());
	histoRecoMinusGenDivGenTopRapidity1->Fill((lvTop1_reco.Rapidity() - lvTop1_gen.Rapidity())/lvTop1_gen.Rapidity());
        histoRecoMinusGenDivGenTopRapidity2->Fill((lvTop2_reco.Rapidity() - lvTop2_gen.Rapidity())/lvTop2_gen.Rapidity());

        for(unsigned int i=0; i<candMuon.size(); i++){
          if(candMuon[i].Charge == +1) histoRecoMinusGenDivGenLeptonRapidity1->Fill((candMuon[i].p4.Rapidity() - lvTop1_gen.Rapidity())/lvTop1_gen.Rapidity());
          if(candMuon[i].Charge == -1) histoRecoMinusGenDivGenLeptonRapidity2->Fill((candMuon[i].p4.Rapidity() - lvTop2_gen.Rapidity())/lvTop2_gen.Rapidity());
	}

        for(unsigned int j=0; j<candElec.size(); j++){
          if(candElec[j].Charge == +1) histoRecoMinusGenDivGenLeptonRapidity1->Fill((candElec[j].p4.Rapidity() - lvTop1_gen.Rapidity())/lvTop1_gen.Rapidity());
          if(candElec[j].Charge == -1) histoRecoMinusGenDivGenLeptonRapidity2->Fill((candElec[j].p4.Rapidity() - lvTop2_gen.Rapidity())/lvTop2_gen.Rapidity());
	}

	histoRecoMinusGenDivGenTopMass1->Fill((lvTop1_reco.M() - lvTop1_gen.M())/lvTop1_gen.M());
        histoRecoMinusGenDivGenTopMass2->Fill((lvTop2_reco.M() - lvTop2_gen.M())/lvTop2_gen.M());

        histoRecoVsGenDelta_y->Fill(Delta_y_reco, Delta_y_gen);
        histoFineBinning_RecoVsGenDelta_y->Fill(Delta_y_reco, Delta_y_gen);
        histoRecoMinusGenDivGenDelta_y->Fill((Delta_y_reco - Delta_y_gen)/Delta_y_gen);

        histoRecoVsGenTTRapidity->Fill(lvTop1plusTop2_reco.Rapidity(),lvTop1plusTop2_gen.Rapidity());
        histoRecoMinusGenDivGenTTRapidity->Fill((lvTop1plusTop2_reco.Rapidity() - lvTop1plusTop2_gen.Rapidity())/lvTop1plusTop2_gen.Rapidity());
        histoRecoVsGenTTPt->Fill(lvTop1plusTop2_reco.Perp(),lvTop1plusTop2_gen.Perp());
        histoRecoMinusGenDivGenTTPt->Fill((lvTop1plusTop2_reco.Perp() - lvTop1plusTop2_gen.Perp())/lvTop1plusTop2_gen.Perp());
        histoRecoVsGenTTMass->Fill(lvTop1plusTop2_reco.M(),lvTop1plusTop2_gen.M());
        histoRecoMinusGenDivGenTTMass->Fill((lvTop1plusTop2_reco.M() - lvTop1plusTop2_gen.M())/lvTop1plusTop2_gen.M());

	}

	//	tmv->printAll();
	delete tmv;
       if(nonskimmed == false && mttbar_rec > 60.){ tree->Fill(); num_mttbar_eff += weight_MC;}
       if(nonskimmed == false) den_mttbar_eff += weight_MC;
      }

      if(nonskimmed == true) tree->Fill();

    }  // end of loop over evts

    float A_C_reco = (N_plus_reco - N_minus_reco)/(N_plus_reco + N_minus_reco);
    float A_C_gen = (N_plus_gen - N_minus_gen)/(N_plus_gen + N_minus_gen);

    cout << "A_C_gen:" << A_C_gen << endl;
    cout << "A_C_reco:" << A_C_reco << endl;

    histoGenN_plusMinusN_minusTTRapidity->Add(histoGenN_plusTTRapidity);
    histoGenN_plusMinusN_minusTTRapidity->Add(histoGenN_minusTTRapidity,-1);
    histoGenN_plusPlusN_minusTTRapidity->Add(histoGenN_plusTTRapidity);
    histoGenN_plusPlusN_minusTTRapidity->Add(histoGenN_minusTTRapidity);

    histoGenA_cTTRapidity->Divide(histoGenN_plusMinusN_minusTTRapidity, histoGenN_plusPlusN_minusTTRapidity);

    histoGenN_plusMinusN_minusTTPt->Add(histoGenN_plusTTPt);
    histoGenN_plusMinusN_minusTTPt->Add(histoGenN_minusTTPt,-1);
    histoGenN_plusPlusN_minusTTPt->Add(histoGenN_plusTTPt);
    histoGenN_plusPlusN_minusTTPt->Add(histoGenN_minusTTPt);

    histoGenA_cTTPt->Divide(histoGenN_plusMinusN_minusTTPt, histoGenN_plusPlusN_minusTTPt);

    histoGenN_plusMinusN_minusTTMass->Add(histoGenN_plusTTMass);
    histoGenN_plusMinusN_minusTTMass->Add(histoGenN_minusTTMass,-1);
    histoGenN_plusPlusN_minusTTMass->Add(histoGenN_plusTTMass);
    histoGenN_plusPlusN_minusTTMass->Add(histoGenN_minusTTMass);

    histoGenA_cTTMass->Divide(histoGenN_plusMinusN_minusTTMass, histoGenN_plusPlusN_minusTTMass);

    histoRecoN_plusMinusN_minusTTRapidity->Add(histoRecoN_plusTTRapidity);
    histoRecoN_plusMinusN_minusTTRapidity->Add(histoRecoN_minusTTRapidity,-1);
    histoRecoN_plusPlusN_minusTTRapidity->Add(histoRecoN_plusTTRapidity);
    histoRecoN_plusPlusN_minusTTRapidity->Add(histoRecoN_minusTTRapidity);

    histoRecoA_cTTRapidity->Divide(histoRecoN_plusMinusN_minusTTRapidity, histoRecoN_plusPlusN_minusTTRapidity);

    histoRecoN_plusMinusN_minusTTPt->Add(histoRecoN_plusTTPt);
    histoRecoN_plusMinusN_minusTTPt->Add(histoRecoN_minusTTPt,-1);
    histoRecoN_plusPlusN_minusTTPt->Add(histoRecoN_plusTTPt);
    histoRecoN_plusPlusN_minusTTPt->Add(histoRecoN_minusTTPt);

    histoRecoA_cTTPt->Divide(histoRecoN_plusMinusN_minusTTPt, histoRecoN_plusPlusN_minusTTPt);

    histoRecoN_plusMinusN_minusTTMass->Add(histoRecoN_plusTTMass);
    histoRecoN_plusMinusN_minusTTMass->Add(histoRecoN_minusTTMass,-1);
    histoRecoN_plusPlusN_minusTTMass->Add(histoRecoN_plusTTMass);
    histoRecoN_plusPlusN_minusTTMass->Add(histoRecoN_minusTTMass);

    histoRecoA_cTTMass->Divide(histoRecoN_plusMinusN_minusTTMass, histoRecoN_plusPlusN_minusTTMass);





    histoFineBinning_GenN_plusMinusN_minusTTRapidity->Add(histoFineBinning_GenN_plusTTRapidity);
    histoFineBinning_GenN_plusMinusN_minusTTRapidity->Add(histoFineBinning_GenN_minusTTRapidity,-1);
    histoFineBinning_GenN_plusPlusN_minusTTRapidity->Add(histoFineBinning_GenN_plusTTRapidity);
    histoFineBinning_GenN_plusPlusN_minusTTRapidity->Add(histoFineBinning_GenN_minusTTRapidity);

    histoFineBinning_GenA_cTTRapidity->Divide(histoFineBinning_GenN_plusMinusN_minusTTRapidity, histoFineBinning_GenN_plusPlusN_minusTTRapidity);

    histoFineBinning_GenN_plusMinusN_minusTTPt->Add(histoFineBinning_GenN_plusTTPt);
    histoFineBinning_GenN_plusMinusN_minusTTPt->Add(histoFineBinning_GenN_minusTTPt,-1);
    histoFineBinning_GenN_plusPlusN_minusTTPt->Add(histoFineBinning_GenN_plusTTPt);
    histoFineBinning_GenN_plusPlusN_minusTTPt->Add(histoFineBinning_GenN_minusTTPt);

    histoFineBinning_GenA_cTTPt->Divide(histoFineBinning_GenN_plusMinusN_minusTTPt, histoFineBinning_GenN_plusPlusN_minusTTPt);

    histoFineBinning_GenN_plusMinusN_minusTTMass->Add(histoFineBinning_GenN_plusTTMass);
    histoFineBinning_GenN_plusMinusN_minusTTMass->Add(histoFineBinning_GenN_minusTTMass,-1);
    histoFineBinning_GenN_plusPlusN_minusTTMass->Add(histoFineBinning_GenN_plusTTMass);
    histoFineBinning_GenN_plusPlusN_minusTTMass->Add(histoFineBinning_GenN_minusTTMass);

    histoFineBinning_GenA_cTTMass->Divide(histoFineBinning_GenN_plusMinusN_minusTTMass, histoFineBinning_GenN_plusPlusN_minusTTMass);

    histoFineBinning_RecoN_plusMinusN_minusTTRapidity->Add(histoFineBinning_RecoN_plusTTRapidity);
    histoFineBinning_RecoN_plusMinusN_minusTTRapidity->Add(histoFineBinning_RecoN_minusTTRapidity,-1);
    histoFineBinning_RecoN_plusPlusN_minusTTRapidity->Add(histoFineBinning_RecoN_plusTTRapidity);
    histoFineBinning_RecoN_plusPlusN_minusTTRapidity->Add(histoFineBinning_RecoN_minusTTRapidity);

    histoFineBinning_RecoA_cTTRapidity->Divide(histoFineBinning_RecoN_plusMinusN_minusTTRapidity, histoFineBinning_RecoN_plusPlusN_minusTTRapidity);

    histoFineBinning_RecoN_plusMinusN_minusTTPt->Add(histoFineBinning_RecoN_plusTTPt);
    histoFineBinning_RecoN_plusMinusN_minusTTPt->Add(histoFineBinning_RecoN_minusTTPt,-1);
    histoFineBinning_RecoN_plusPlusN_minusTTPt->Add(histoFineBinning_RecoN_plusTTPt);
    histoFineBinning_RecoN_plusPlusN_minusTTPt->Add(histoFineBinning_RecoN_minusTTPt);

    histoFineBinning_RecoA_cTTPt->Divide(histoFineBinning_RecoN_plusMinusN_minusTTPt, histoFineBinning_RecoN_plusPlusN_minusTTPt);

    histoFineBinning_RecoN_plusMinusN_minusTTMass->Add(histoFineBinning_RecoN_plusTTMass);
    histoFineBinning_RecoN_plusMinusN_minusTTMass->Add(histoFineBinning_RecoN_minusTTMass,-1);
    histoFineBinning_RecoN_plusPlusN_minusTTMass->Add(histoFineBinning_RecoN_plusTTMass);
    histoFineBinning_RecoN_plusPlusN_minusTTMass->Add(histoFineBinning_RecoN_minusTTMass);

    histoFineBinning_RecoA_cTTMass->Divide(histoFineBinning_RecoN_plusMinusN_minusTTMass, histoFineBinning_RecoN_plusPlusN_minusTTMass);



    histoDelta_yEfficiency->Divide(histoDelta_yEfficiencyN, histoDelta_yEfficiencyD);
    histoFineBinning_Delta_yEfficiency->Divide(histoFineBinning_Delta_yEfficiencyN, histoFineBinning_Delta_yEfficiencyD);


    for (unsigned int bin_index1 = 1; bin_index1 < 11; bin_index1++) {
     for (unsigned int bin_index2 = 1; bin_index2 < 6; bin_index2++) {
       float value = histoRecoDelta_yVsTTRapidity->GetBinContent(bin_index1,bin_index2)/histoGenDelta_yVsTTRapidity->GetBinContent(bin_index1,bin_index2);
       histoDelta_yVsTTRapidityEfficiency->SetBinContent(bin_index1, bin_index2, value);
       float value_fb = histoFineBinning_RecoDelta_yVsTTRapidity->GetBinContent(bin_index1,bin_index2)/histoFineBinning_GenDelta_yVsTTRapidity->GetBinContent(bin_index1,bin_index2);
       histoFineBinning_Delta_yVsTTRapidityEfficiency->SetBinContent(bin_index1, bin_index2, value_fb);

     }
    }

    for (unsigned int bin_index1 = 1; bin_index1 < 11; bin_index1++) {
     for (unsigned int bin_index2 = 1; bin_index2 < 6; bin_index2++) {
       float value = histoRecoDelta_yVsTTPt->GetBinContent(bin_index1,bin_index2)/histoGenDelta_yVsTTPt->GetBinContent(bin_index1,bin_index2);
       histoDelta_yVsTTPtEfficiency->SetBinContent(bin_index1, bin_index2, value);
       float value_fb = histoFineBinning_RecoDelta_yVsTTPt->GetBinContent(bin_index1,bin_index2)/histoFineBinning_GenDelta_yVsTTPt->GetBinContent(bin_index1,bin_index2);
       histoFineBinning_Delta_yVsTTPtEfficiency->SetBinContent(bin_index1, bin_index2, value_fb);

     }
    }


    for (unsigned int bin_index1 = 1; bin_index1 < 11; bin_index1++) {
     for (unsigned int bin_index2 = 1; bin_index2 < 6; bin_index2++) {
       float value = histoRecoDelta_yVsTTMass->GetBinContent(bin_index1,bin_index2)/histoGenDelta_yVsTTMass->GetBinContent(bin_index1,bin_index2);
       histoDelta_yVsTTMassEfficiency->SetBinContent(bin_index1, bin_index2, value);
       float value_fb = histoFineBinning_RecoDelta_yVsTTPt->GetBinContent(bin_index1,bin_index2)/histoFineBinning_GenDelta_yVsTTPt->GetBinContent(bin_index1,bin_index2);
       histoFineBinning_Delta_yVsTTPtEfficiency->SetBinContent(bin_index1, bin_index2, value_fb);

     }
    }






  }				// end of loop over the datasets


//  if(verbosity>0) {
    cout<<"#########################"<<endl;
    cout<<"    End of the program   "<<endl;
    cout<<"#########################"<<endl;
//  }

    tree->Print();

    TupleFile->Write();
    TupleFile->Close();


    TFile * fileCA = new TFile("ChargeAsymmetryResults_ZJets.root","RECREATE");
    //  fileCA->cd();

    // GEN
    histoGenTopRapidity1->Write();
    histoGenTopRapidity2->Write();
    histoGenTopMass1->Write();
    histoGenTopMass2->Write();
    histoGenTopMass1VsTopMass2->Write();
    histoGenDelta_y->Write();
    histoGenTTRapidity->Write();
    histoGenTTPt->Write();
    histoGenTTMass->Write();
    histoGenDelta_yVsTTRapidity->Write();
    histoGenDelta_yVsTTPt->Write();
    histoGenDelta_yVsTTMass->Write();
    histoGenN_plusTTRapidity->Write();
    histoGenN_plusTTPt->Write();
    histoGenN_plusTTMass->Write();
    histoGenN_minusTTRapidity->Write();
    histoGenN_minusTTPt->Write();
    histoGenN_minusTTMass->Write();
    histoGenN_plusMinusN_minusTTRapidity->Write();
    histoGenN_plusPlusN_minusTTRapidity->Write();
    histoGenN_plusMinusN_minusTTPt->Write();
    histoGenN_plusPlusN_minusTTPt->Write();
    histoGenN_plusMinusN_minusTTMass->Write();
    histoGenN_plusPlusN_minusTTMass->Write();
    histoGenA_cTTRapidity->Write();
    histoGenA_cTTPt->Write();
    histoGenA_cTTMass->Write();
    histoFineBinning_GenDelta_yVsTTRapidity->Write();
    histoFineBinning_GenDelta_yVsTTPt->Write();
    histoFineBinning_GenDelta_yVsTTMass->Write();
    histoFineBinning_GenN_plusTTRapidity->Write();
    histoFineBinning_GenN_plusTTPt->Write();
    histoFineBinning_GenN_plusTTMass->Write();
    histoFineBinning_GenN_minusTTRapidity->Write();
    histoFineBinning_GenN_minusTTPt->Write();
    histoFineBinning_GenN_minusTTMass->Write();
    histoFineBinning_GenN_plusMinusN_minusTTRapidity->Write();
    histoFineBinning_GenN_plusPlusN_minusTTRapidity->Write();
    histoFineBinning_GenN_plusMinusN_minusTTPt->Write();
    histoFineBinning_GenN_plusPlusN_minusTTPt->Write();
    histoFineBinning_GenN_plusMinusN_minusTTMass->Write();
    histoFineBinning_GenN_plusPlusN_minusTTMass->Write();
    histoFineBinning_GenA_cTTRapidity->Write();
    histoFineBinning_GenA_cTTPt->Write();
    histoFineBinning_GenA_cTTMass->Write(); 



    // RECO
    histoRecoTopRapidity1->Write();
    histoRecoTopRapidity2->Write();
    histoRecoLeptonRapidity1->Write();
    histoRecoLeptonRapidity2->Write();
    histoRecoTopMass1->Write();
    histoRecoTopMass2->Write();
    histoRecoTopMass1VsTopMass2->Write();
    histoRecoDelta_y->Write();
    histoRecoTTRapidity->Write();
    histoRecoTTPt->Write();
    histoRecoTTMass->Write();
    histoRecoDelta_yVsTTRapidity->Write();
    histoRecoDelta_yVsTTPt->Write();
    histoRecoDelta_yVsTTMass->Write();
    histoRecoN_plusTTRapidity->Write();
    histoRecoN_plusTTPt->Write();
    histoRecoN_plusTTMass->Write();
    histoRecoN_minusTTRapidity->Write();
    histoRecoN_minusTTPt->Write();
    histoRecoN_minusTTMass->Write();
    histoRecoN_plusMinusN_minusTTRapidity->Write();
    histoRecoN_plusPlusN_minusTTRapidity->Write();
    histoRecoN_plusMinusN_minusTTPt->Write();
    histoRecoN_plusPlusN_minusTTPt->Write();
    histoRecoN_plusMinusN_minusTTMass->Write();
    histoRecoN_plusPlusN_minusTTMass->Write();
    histoRecoA_cTTRapidity->Write();
    histoRecoA_cTTPt->Write();
    histoRecoA_cTTMass->Write();
    histoFineBinning_RecoDelta_yVsTTRapidity->Write();
    histoFineBinning_RecoDelta_yVsTTPt->Write();
    histoFineBinning_RecoDelta_yVsTTMass->Write();
    histoFineBinning_RecoN_plusTTRapidity->Write();
    histoFineBinning_RecoN_plusTTPt->Write();
    histoFineBinning_RecoN_plusTTMass->Write();
    histoFineBinning_RecoN_minusTTRapidity->Write();
    histoFineBinning_RecoN_minusTTPt->Write();
    histoFineBinning_RecoN_minusTTMass->Write();
    histoFineBinning_RecoN_plusMinusN_minusTTRapidity->Write();
    histoFineBinning_RecoN_plusPlusN_minusTTRapidity->Write();
    histoFineBinning_RecoN_plusMinusN_minusTTPt->Write();
    histoFineBinning_RecoN_plusPlusN_minusTTPt->Write();
    histoFineBinning_RecoN_plusMinusN_minusTTMass->Write();
    histoFineBinning_RecoN_plusPlusN_minusTTMass->Write();
    histoFineBinning_RecoA_cTTRapidity->Write();
    histoFineBinning_RecoA_cTTPt->Write();
    histoFineBinning_RecoA_cTTMass->Write(); 

    // RECO vs GEN
    histoRecoVsGenTopRapidity1->Write();
    histoRecoVsGenTopRapidity2->Write();
    histoRecoMinusGenDivGenLeptonRapidity1->Write();
    histoRecoMinusGenDivGenLeptonRapidity2->Write();
    histoRecoMinusGenDivGenTopRapidity1->Write();
    histoRecoMinusGenDivGenTopRapidity2->Write();
    histoRecoVsGenTopMass1->Write();
    histoRecoVsGenTopMass2->Write();
    histoRecoMinusGenDivGenTopMass1->Write();
    histoRecoMinusGenDivGenTopMass2->Write();
    histoRecoVsGenDelta_y->Write();
    histoFineBinning_RecoVsGenDelta_y->Write();
    histoRecoMinusGenDivGenDelta_y->Write();
    histoRecoVsGenTTRapidity->Write();
    histoRecoMinusGenDivGenTTRapidity->Write();
    histoRecoVsGenTTPt->Write();
    histoRecoMinusGenDivGenTTPt->Write();
    histoRecoVsGenTTMass->Write();
    histoRecoMinusGenDivGenTTMass->Write();
    histoDelta_yEfficiencyN->Write();
    histoDelta_yEfficiencyD->Write();
    histoDelta_yEfficiency->Write();
    histoDelta_yVsTTRapidityEfficiency->Write();
    histoDelta_yVsTTPtEfficiency->Write();
    histoDelta_yVsTTMassEfficiency->Write();
    histoFineBinning_Delta_yEfficiencyN->Write();
    histoFineBinning_Delta_yEfficiencyD->Write();
    histoFineBinning_Delta_yEfficiency->Write();
    histoFineBinning_Delta_yVsTTRapidityEfficiency->Write();
    histoFineBinning_Delta_yVsTTPtEfficiency->Write();
    histoFineBinning_Delta_yVsTTMassEfficiency->Write();


    //    fileCA->Write();
    fileCA->Close();
    delete fileCA;

    cout << "num_mttbar_eff = " <<  num_mttbar_eff << endl;
    cout << "den_mttbar_eff = " <<  den_mttbar_eff << endl;
    cout << "mttbar_eff = " <<  num_mttbar_eff / den_mttbar_eff << endl;

  return (0);
}
Example #24
0
void analyzeDijetAj(std::vector<std::string> urls, const char *outname = "eventObjects.root", Long64_t nentries = 20, Int_t firstF = -1, Int_t lastF = -1, Int_t firstEvent = 0) {

  /*
    ptminType: minimum raw pt for particles used by puppi
    0 : 0 GeV
    1 : 1 GeV
    2 : 2 GeV

    jetSignalType: jets used to select jetty region in events
    0 : detector-level jets (akPu4PF)
    1 : particle-level jets (gen jets)
   */

  double ptminjet = 30.;
  TString jetName = "aktCs4PF";
  TString jetTreeName = "akCs4PFJetAnalyzer";
  //jetName = "akCs4PFFilter";
  //jetTreeName = "akCs4PFFilterJetAnalyzer";

  std::cout << "analyzing subjets for: " << jetName << " tree: " << jetTreeName << std::endl;
   
  std::cout << "nfiles: " << urls.size() << std::endl;
  for (auto i = urls.begin(); i != urls.end(); ++i)
    std::cout << *i << std::endl;

  size_t firstFile = 0;
  size_t lastFile = urls.size();

  if(firstF>-1) {
    firstFile = (size_t)firstF;
    lastFile = std::min((size_t)lastF,lastFile);
  }
  std::cout << "firstFile: " << firstFile << "  lastFile: " << lastFile << std::endl;

  Int_t lastEvent = nentries;
  if(firstEvent>0) {
    lastEvent = firstEvent + nentries;
  }
  std::cout << "firstEvent: " << firstEvent << std::endl;
  
  //add files to chain
  TChain *chain = NULL;
  chain = new TChain("hiEvtAnalyzer/HiTree");
  for(size_t i=firstFile; i<lastFile; i++) chain->Add(urls[i].c_str());
  Printf("hiTree done");

  TChain *skimTree = new TChain("skimanalysis/HltTree");
  for(size_t i=firstFile; i<lastFile; i++) skimTree->Add(urls[i].c_str());
  chain->AddFriend(skimTree);
  Printf("skimTree done");

  TChain *hltTree = new TChain("hltanalysis/HltTree");
  for(size_t i=firstFile; i<lastFile; i++) hltTree->Add(urls[i].c_str());
  chain->AddFriend(hltTree);
  Printf("hltTree done");
  
  TChain *jetTree = new TChain(Form("%s/t",jetTreeName.Data()));
  for(size_t i=firstFile; i<lastFile; i++) jetTree->Add(urls[i].c_str());
  chain->AddFriend(jetTree);
  Printf("jetTree done");

  // TChain *csJetTree = new TChain(Form("%s/t","akCs4PFJetAnalyzer"));
  // for(size_t i=firstFile; i<lastFile; i++) csJetTree->Add(urls[i].c_str());
  // chain->AddFriend(csJetTree);
  // Printf("csJetTree done");

  TList *fEventObjects = new TList();

  //---------------------------------------------------------------
  // producers
  //
  hiEventProducer *p_evt = new hiEventProducer("hiEvtProd");
  p_evt->SetInput(chain);
  p_evt->SetHIEventContName("hiEventContainer");
  p_evt->SetEventObjects(fEventObjects);

  triggerProducer *p_trg = new triggerProducer("trigProd");
  p_trg->SetInput(chain);//hltTree);
  p_trg->SetTriggerMapName("triggerMap");
  p_trg->AddTrigger("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  p_trg->SetEventObjects(fEventObjects);

  lwJetFromForestProducer *p_PUJet = new lwJetFromForestProducer("lwJetForestProd");
  p_PUJet->SetInput(chain);
  p_PUJet->SetJetContName(jetName);
  p_PUJet->SetGenJetContName("");
  p_PUJet->SetEventObjects(fEventObjects);
  p_PUJet->SetRadius(0.4);
  p_PUJet->SetMinJetPt(ptminjet);
  // lwJetFromForestProducer *p_CSJet = new lwJetFromForestProducer("lwJetForestProd");
  // p_CSJet->SetInput(csJetTree);
  // p_CSJet->SetJetContName("aktCs4PF");
  // p_CSJet->SetGenJetContName("");
  // p_CSJet->SetEventObjects(fEventObjects);
  // p_CSJet->SetRadius(0.4);
  
  //---------------------------------------------------------------
  //analysis modules
  //

  //handler to which all modules will be added
  anaBaseTask *handler = new anaBaseTask("handler","handler");

  anaDijetAj *anadijetAj = new anaDijetAj("anaDijetAj","anaDijetAj");
  anadijetAj->ConnectEventObject(fEventObjects);
  anadijetAj->SetHiEvtName("hiEventContainer");
  anadijetAj->DoCollisionEventSel(true);
  anadijetAj->DoHBHENoiseFilter(true);
  anadijetAj->DoHBHENoiseFilterLoose(true);
  anadijetAj->DoPrimaryVertexFilter(true);
  anadijetAj->DoClusterCompatibilityFilter(true);
  anadijetAj->DoHFCoincFilter(true);
  anadijetAj->SetTriggerMapName("triggerMap");
  anadijetAj->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  anadijetAj->SetJetsName(jetName);
  anadijetAj->SetNCentBins(5);
  anadijetAj->SetJetEtaRange(-1.3,1.3);
  anadijetAj->SetDoDijets(true);
  anadijetAj->AddLeadingJetPtBin(120.,150.);
  anadijetAj->AddLeadingJetPtBin(150.,180.);
  anadijetAj->AddLeadingJetPtBin(180.,220.);
  anadijetAj->AddLeadingJetPtBin(220.,260.);
  anadijetAj->AddLeadingJetPtBin(260.,300.);
  anadijetAj->AddLeadingJetPtBin(300.,500.);
  anadijetAj->SetPtMinSubleading(40.);
  handler->Add(anadijetAj);

  anaDijetAj *anadijetAjMassCut = new anaDijetAj("anaDijetAjMassCut","anaDijetAjMassCut");
  anadijetAjMassCut->ConnectEventObject(fEventObjects);
  anadijetAjMassCut->SetHiEvtName("hiEventContainer");
  anadijetAjMassCut->DoCollisionEventSel(true);
  anadijetAjMassCut->DoHBHENoiseFilter(true);
  anadijetAjMassCut->DoHBHENoiseFilterLoose(true);
  anadijetAjMassCut->DoPrimaryVertexFilter(true);
  anadijetAjMassCut->DoClusterCompatibilityFilter(true);
  anadijetAjMassCut->DoHFCoincFilter(true);
  anadijetAjMassCut->SetTriggerMapName("triggerMap");
  anadijetAjMassCut->AddTriggerSel("HLT_HIPuAK4CaloJet100_Eta5p1_v1");
  anadijetAjMassCut->SetJetsName(jetName);
  anadijetAjMassCut->SetNCentBins(5);
  anadijetAjMassCut->SetJetEtaRange(-1.,3.);
  anadijetAjMassCut->SetDoDijets(true);
  anadijetAjMassCut->AddLeadingJetPtBin(120.,150.);
  anadijetAjMassCut->AddLeadingJetPtBin(150.,180.);
  anadijetAjMassCut->AddLeadingJetPtBin(180.,220.);
  anadijetAjMassCut->AddLeadingJetPtBin(220.,260.);
  anadijetAjMassCut->AddLeadingJetPtBin(260.,300.);
  anadijetAjMassCut->AddLeadingJetPtBin(300.,500.);
  anadijetAjMassCut->SetPtMinSubleading(40.);
  anadijetAjMassCut->SetMinMassLeading(10.);
  handler->Add(anadijetAjMassCut);
  
  //---------------------------------------------------------------
  //Event loop
  //---------------------------------------------------------------
  Long64_t entries_tot =  chain->GetEntries(); //93064
  if(nentries<0) lastEvent = chain->GetEntries();
  Printf("nentries: %lld  tot: %lld",nentries,entries_tot);
  for (Long64_t jentry=firstEvent; jentry<lastEvent; ++jentry) {
    if(jentry%10000==0) cout << "entry: "<< jentry << endl;
    //Run producers
    //Printf("produce hiEvent");
    p_evt->Run(jentry);   //hi event properties
    //Printf("produce PU jets");
    p_PUJet->Run(jentry); //forest jets
    p_trg->Run(jentry);	    

    //Execute all analysis tasks
    handler->ExecuteTask();
  }
    
  fEventObjects->Print();

  TFile *out = new TFile(outname,"RECREATE");
  TList *tasks = handler->GetListOfTasks();
  TIter next(tasks);
  anaBaseTask *obj;
  while ((obj = dynamic_cast<anaBaseTask*>(next()) ))
    if(obj->GetOutput()) obj->GetOutput()->Write(obj->GetName(),TObject::kSingleKey);
  
  out->Write();
  out->Close();
  
}
Example #25
0
void select(const TString sample="", const TString tempinput="bacon_sample.root", const Double_t xsec = 1,
    const Int_t eosflag = 2)
{
    TString input;
    if(eosflag==2) input = "/afs/cern.ch/work/a/ariostas/public/CP-Higgs/" + tempinput;
    else if(eosflag==1) input = "root://eoscms.cern.ch//store/user/arapyan/higgs_cp_samples/" + sample + "/Bacon/" + tempinput;
    else input = "/afs/cern.ch/work/a/arapyan/public/forMarkus/higgs_cp_samples/" + sample + "/" + tempinput;

    TString output = "/afs/cern.ch/work/a/ariostas/private/CP-Higgs_temp/" + sample + "/" + tempinput;

    TChain chain("Events");
    chain.Add(input);

    const Double_t DR=0.4;

    // Data structures to store info from TTrees
    TGenEventInfo *info = new TGenEventInfo();
    TClonesArray *jet = new TClonesArray("baconhep::TGenJet");
    TClonesArray *part = new TClonesArray("baconhep::TGenParticle");

    chain.SetBranchAddress("GenEvtInfo",  &info);
    TBranch *infoBr = chain.GetBranch("GenEvtInfo");
    chain.SetBranchAddress("GenJet" ,     &jet );
    TBranch *jetBr = chain.GetBranch("GenJet");
    chain.SetBranchAddress("GenParticle", &part);
    TBranch *partBr = chain.GetBranch("GenParticle");

    // Output file and trees
    TFile *outfile = new TFile(output, "RECREATE");

    TTree *infoTree = new TTree("Count", "Count");
    Long64_t n = chain.GetEntries();
    infoTree->Branch("n", &n, "n/i");
    infoTree->Fill();

    TTree *outtree = new TTree("Events", "Events");

    Double_t eventWeight;

    UInt_t ncpions1=0, ncpions2=0, nnpions1=0, nnpions2=0, nLeptons=0;
    Int_t zToLep=0;

    // Jets matched to gen taus
    Double_t jetTau1_pt, jetTau2_pt;
    Double_t jetTau1_eta, jetTau2_eta;
    Double_t jetTau1_phi, jetTau2_phi;
    Double_t jetTau1_mass, jetTau2_mass;

    // Gen taus
    Double_t genTau1_pt, genTau2_pt;
    Double_t genTau1_eta, genTau2_eta;
    Double_t genTau1_phi, genTau2_phi;
    Double_t genTau1_mass, genTau2_mass;

    // Visible taus (taus minus neutrino)
    Double_t visTau1_pt, visTau2_pt;
    Double_t visTau1_eta, visTau2_eta;
    Double_t visTau1_phi, visTau2_phi;
    Double_t visTau1_mass, visTau2_mass;

    // Charged pions coming from taus
    Double_t cpions1_pt, cpions2_pt;
    Double_t cpions1_eta, cpions2_eta;
    Double_t cpions1_phi, cpions2_phi;
    Double_t cpions1_mass, cpions2_mass;

    // Neutral pions coming from taus
    Double_t npions1_pt, npions2_pt;
    Double_t npions1_eta, npions2_eta;
    Double_t npions1_phi, npions2_phi;
    Double_t npions1_mass, npions2_mass;

    // Particles/jets from Z
    Double_t z1_pt, z2_pt;
    Double_t z1_eta, z2_eta;
    Double_t z1_phi, z2_phi;
    Double_t z1_mass, z2_mass;

    // Z
    Double_t z_pt, z_eta, z_phi, z_mass;

    // Reco Z
    Double_t recoz_pt, recoz_eta, recoz_phi, recoz_mass;

    outtree->Branch("eventWeight",      &eventWeight,       "eventWeight/D");   // event weight from cross-section and Event->Weight

    outtree->Branch("nLeptons",         &nLeptons,          "nLeptons/i");      // number of leptons
    outtree->Branch("ncpions1",         &ncpions1,          "ncpions1/i");
    outtree->Branch("ncpions2",         &ncpions2,          "ncpions2/i");
    outtree->Branch("nnpions1",         &nnpions1,          "nnpions1/i");
    outtree->Branch("nnpions2",         &nnpions2,          "nnpions2/i");

    outtree->Branch("zToLep",           &zToLep,            "zToLep/I");

    outtree->Branch("jetTau1_pt",       &jetTau1_pt,        "jetTau1_pt/D");    // pt(Tau1)
    outtree->Branch("jetTau1_eta",      &jetTau1_eta,       "jetTau1_eta/D");   // eta(Tau1)
    outtree->Branch("jetTau1_phi",      &jetTau1_phi,       "jetTau1_phi/D");   // phi(Tau1)
    outtree->Branch("jetTau1_mass",     &jetTau1_mass,      "jetTau1_mass/D");  // m(Tau1)

    outtree->Branch("jetTau2_pt",       &jetTau2_pt,        "jetTau2_pt/D");    // pt(Tau2)
    outtree->Branch("jetTau2_eta",      &jetTau2_eta,       "jetTau2_eta/D");   // eta(Tau2)
    outtree->Branch("jetTau2_phi",      &jetTau2_phi,       "jetTau2_phi/D");   // phi(Tau2)
    outtree->Branch("jetTau2_mass",     &jetTau2_mass,      "jetTau2_mass/D");  // m(Tau2)

    outtree->Branch("genTau1_pt",       &genTau1_pt,        "genTau1_pt/D");    // pt(Tau1)
    outtree->Branch("genTau1_eta",      &genTau1_eta,       "genTau1_eta/D");   // eta(Tau1)
    outtree->Branch("genTau1_phi",      &genTau1_phi,       "genTau1_phi/D");   // phi(Tau1)
    outtree->Branch("genTau1_mass",     &genTau1_mass,      "genTau1_mass/D");  // m(Tau1)

    outtree->Branch("genTau2_pt",       &genTau2_pt,        "genTau2_pt/D");    // pt(Tau2)
    outtree->Branch("genTau2_eta",      &genTau2_eta,       "genTau2_eta/D");   // eta(Tau2)
    outtree->Branch("genTau2_phi",      &genTau2_phi,       "genTau2_phi/D");   // phi(Tau2)
    outtree->Branch("genTau2_mass",     &genTau2_mass,      "genTau2_mass/D");  // m(Tau2)

    outtree->Branch("visTau1_pt",       &visTau1_pt,        "visTau1_pt/D");    // pt(Tau1)
    outtree->Branch("visTau1_eta",      &visTau1_eta,       "visTau1_eta/D");   // eta(Tau1)
    outtree->Branch("visTau1_phi",      &visTau1_phi,       "visTau1_phi/D");   // phi(Tau1)
    outtree->Branch("visTau1_mass",     &visTau1_mass,      "visTau1_mass/D");  // m(Tau1)

    outtree->Branch("visTau2_pt",       &visTau2_pt,        "visTau2_pt/D");    // pt(Tau2)
    outtree->Branch("visTau2_eta",      &visTau2_eta,       "visTau2_eta/D");   // eta(Tau2)
    outtree->Branch("visTau2_phi",      &visTau2_phi,       "visTau2_phi/D");   // phi(Tau2)
    outtree->Branch("visTau2_mass",     &visTau2_mass,      "visTau2_mass/D");  // m(Tau2)

    outtree->Branch("cpions1_pt",       &cpions1_pt,        "cpions1_pt/D");
    outtree->Branch("cpions1_eta",      &cpions1_eta,       "cpions1_eta/D");
    outtree->Branch("cpions1_phi",      &cpions1_phi,       "cpions1_phi/D");
    outtree->Branch("cpions1_mass",     &cpions1_mass,      "cpions1_mass/D");

    outtree->Branch("cpions2_pt",       &cpions2_pt,        "pions2_pt/D");
    outtree->Branch("cpions2_eta",      &cpions2_eta,       "pions2_eta/D");
    outtree->Branch("cpions2_phi",      &cpions2_phi,       "pions2_phi/D");
    outtree->Branch("cpions2_mass",     &cpions2_mass,      "pions2_mass/D");

    outtree->Branch("npions1_pt",       &npions1_pt,        "npions1_pt/D");
    outtree->Branch("npions1_eta",      &npions1_eta,       "npions1_eta/D");
    outtree->Branch("npions1_phi",      &npions1_phi,       "npions1_phi/D");
    outtree->Branch("npions1_mass",     &npions1_mass,      "npions1_mass/D");

    outtree->Branch("npions2_pt",       &npions2_pt,        "npions2_pt/D");
    outtree->Branch("npions2_eta",      &npions2_eta,       "npions2_eta/D");
    outtree->Branch("npions2_phi",      &npions2_phi,       "npions2_phi/D");
    outtree->Branch("npions2_mass",     &npions2_mass,      "npions2_mass/D");

    outtree->Branch("z1_pt",            &z1_pt,             "z1_pt/D");
    outtree->Branch("z1_eta",           &z1_eta,            "z1_eta/D");
    outtree->Branch("z1_phi",           &z1_phi,            "z1_phi/D");
    outtree->Branch("z1_mass",          &z1_mass,           "z1_mass/D");

    outtree->Branch("z2_pt",            &z2_pt,             "z2_pt/D");
    outtree->Branch("z2_eta",           &z2_eta,            "z2_eta/D");
    outtree->Branch("z2_phi",           &z2_phi,            "z2_phi/D");
    outtree->Branch("z2_mass",          &z2_mass,           "z2_mass/D");

    outtree->Branch("z_pt",             &z_pt,              "z_pt/D");
    outtree->Branch("z_eta",            &z_eta,             "z_eta/D");
    outtree->Branch("z_phi",            &z_phi,             "z_phi/D");
    outtree->Branch("z_mass",           &z_mass,            "z_mass/D");

    outtree->Branch("recoz_pt",         &recoz_pt,          "recoz_pt/D");
    outtree->Branch("recoz_eta",        &recoz_eta,         "recoz_eta/D");
    outtree->Branch("recoz_phi",        &recoz_phi,         "recoz_phi/D");
    outtree->Branch("recoz_mass",       &recoz_mass,        "recoz_mass/D");

    for (Int_t i=0; i<chain.GetEntries(); i++)
    {
        if(i==0 || (i+1)%1000==0) cout << "Processing event " << i+1 << endl;

        infoBr->GetEntry(i);

        part->Clear();
        partBr->GetEntry(i);
        jet->Clear();
        //jetBr->GetEntry(i);

        if (part->GetEntries()==0) continue;

        Int_t iTau1=-1, iTau2=-1;
        Int_t iT1=-1, iT2=-1;

        Int_t iZ1=-1, iZ2=-1;
        Int_t ijetZ1=-1, ijetZ2=-1;

        Int_t iZ=-1;

        // Reset variables
        nLeptons=ncpions1=ncpions2=nnpions1=nnpions2=zToLep=0;

        jetTau1_pt=jetTau1_eta=jetTau1_phi=jetTau1_mass=0;
        jetTau2_pt=jetTau2_eta=jetTau2_phi=jetTau2_mass=0;

        genTau1_pt=genTau1_eta=genTau1_phi=genTau1_mass=0;
        genTau2_pt=genTau2_eta=genTau2_phi=genTau2_mass=0;

        visTau1_pt=visTau1_eta=visTau1_phi=visTau1_mass=0;
        visTau2_pt=visTau2_eta=visTau2_phi=visTau2_mass=0;

        cpions1_pt=cpions1_eta=cpions1_phi=cpions1_mass=0;
        cpions2_pt=cpions2_eta=cpions2_phi=cpions2_mass=0;

        npions1_pt=npions1_eta=npions1_phi=npions1_mass=0;
        npions2_pt=npions2_eta=npions2_phi=npions2_mass=0;

        z1_pt=z1_eta=z1_phi=z1_mass=0;
        z2_pt=z2_eta=z2_phi=z2_mass=0;

        z_pt=z_eta=z_phi=z_mass=0;
        recoz_pt=recoz_eta=recoz_phi=recoz_mass=0;

        eventWeight=xsec*1000.0;

        bool hasH=false, hasZ=false;

        for (Int_t j=0; j<part->GetEntries(); j++)
        {
            const TGenParticle* genloop = (TGenParticle*) ((*part)[j]);
            if(abs(genloop->pdgId)==25) hasH = true;
            if(abs(genloop->pdgId)==23) hasZ = true;
        }

        Int_t tausParent=-1;
        for (Int_t j=0; j<part->GetEntries(); j++)
        {
            const TGenParticle* genloop = (TGenParticle*) ((*part)[j]);
            Int_t parentPdg=abs(dynamic_cast<TGenParticle *>(part->At(genloop->parent>-1 ? genloop->parent : 0))->pdgId);

            if(hasH){
                if (abs(genloop->pdgId)==15)
                {
                    if (iTau1==-1 && parentPdg==25)
                    {
                        iTau1=j;
                        tausParent=genloop->parent;
                    }
                    else if (genloop->parent==iTau1)
                    {
                        iTau1=j;
                    }
                    else if (iTau2==-1 && parentPdg==25 && tausParent==genloop->parent)
                    {
                        iTau2=j;
                    }
                    else if (genloop->parent==iTau2)
                    {
                        iTau2=j;
                    }
                }
            }

            else if(hasZ){
                if (abs(genloop->pdgId)==15)
                {
                    if (iTau1==-1 && parentPdg==23)
                    {
                        iTau1=j;
                        tausParent=genloop->parent;
                    }
                    else if (genloop->parent==iTau1)
                    {
                        iTau1=j;
                    }
                    else if (iTau2==-1 && parentPdg==23 && tausParent==genloop->parent)
                    {
                        iTau2=j;
                    }
                    else if (genloop->parent==iTau2)
                    {
                        iTau2=j;
                    }
                }
            }

            else{
                if (abs(genloop->pdgId)==15)
                {
                    if (iTau1==-1)
                    {
                        iTau1=j;
                        tausParent=genloop->parent;
                    }
                    else if (genloop->parent==iTau1)
                    {
                        iTau1=j;
                    }
                    else if (iTau2==-1 && tausParent==genloop->parent)
                    {
                        iTau2=j;
                    }
                    else if (genloop->parent==iTau2)
                    {
                        iTau2=j;
                    }
                }
            }
        }

        if (iTau1==-1 || iTau2==-1) continue;

        Int_t isLep=0;
        for (Int_t j=0; j<part->GetEntries(); j++)
        {
            const TGenParticle* genloop = (TGenParticle*) ((*part)[j]);
            Int_t parentPdg=abs(dynamic_cast<TGenParticle *>(part->At(genloop->parent>-1 ? genloop->parent : 0))->pdgId);

            if (genloop->parent != iTau1 && genloop->parent != iTau2) continue;
            if ((abs(genloop->pdgId)==13||abs(genloop->pdgId)==11)){
                isLep=1;
            }
        }

        if (isLep!=0) continue;

        if(dynamic_cast<TGenParticle *>(part->At(iTau1))->pdgId==15 &&  dynamic_cast<TGenParticle *>(part->At(iTau2))->pdgId==-15)
        {
            Int_t temp=iTau1;
            iTau1=iTau2;
            iTau2=temp;
        }
        else if(dynamic_cast<TGenParticle *>(part->At(iTau1))->pdgId==-15 &&  dynamic_cast<TGenParticle *>(part->At(iTau2))->pdgId==15)
        {

        }
        else
        {
            cout << "Ignoring event." << endl;
            continue;
        }

        for (Int_t j=0; j<part->GetEntries(); j++)
        {
            TGenParticle* genloop = (TGenParticle*) ((*part)[j]);

            Int_t pdg=abs(genloop->pdgId);
            Int_t parent=genloop->parent;

            if(pdg==23){
                if(iZ==-1){
                    iZ=j;
                }
                else if(parent==iZ){
                    iZ=j;
                }
            }
        }

        TLorentzVector cpions1, cpions2, npions1, npions2;
        cpions1.SetPxPyPzE(0,0,0,0); cpions2.SetPxPyPzE(0,0,0,0);
        npions1.SetPxPyPzE(0,0,0,0); npions2.SetPxPyPzE(0,0,0,0);

        for (Int_t j=0; j<part->GetEntries(); j++)
        {
            TGenParticle* genloop = (TGenParticle*) ((*part)[j]);

            Int_t pdg=abs(genloop->pdgId);
            Int_t parent=genloop->parent;

            if(pdg!=211 && pdg!=111) continue;

            Int_t parentTau=0;

            if(parent==iTau1) parentTau=1;
            else if(parent==iTau2) parentTau=2;

            if(parentTau==0) continue;

            TLorentzVector vTemp;
            vTemp.SetPtEtaPhiM(genloop->pt, genloop->eta, genloop->phi, genloop->mass);

            if(parentTau==1)
            {
                if(pdg==211){
                    cpions1+=vTemp;
                    ncpions1++;
                }
                else{
                    npions1+=vTemp;
                    nnpions1++;
                }
            }
            else
            {
                if(pdg==211){
                    cpions2+=vTemp;
                    ncpions2++;
                }
                else{
                    npions2+=vTemp;
                    nnpions2++;
                }
            }

        }


        TLorentzVector vRecoZ;
        vRecoZ.SetPxPyPzE(0,0,0,0);
        for (Int_t j=0; j<part->GetEntries(); j++)
        {
            const TGenParticle* genloop = (TGenParticle*) ((*part)[j]);
            if (fabs(genloop->pdgId)==12 || fabs(genloop->pdgId)==14 || fabs(genloop->pdgId)==14) continue;
            if(fabs(genloop->eta) > 5. || genloop->status!=1) continue;
            if(deltaR(genloop->eta, cpions1.Eta(), genloop->phi, cpions1.Phi()) < DR) continue;
            if(deltaR(genloop->eta, cpions2.Eta(), genloop->phi, cpions2.Phi()) < DR) continue;
            if(deltaR(genloop->eta, npions1.Eta(), genloop->phi, npions1.Phi()) < DR) continue;
            if(deltaR(genloop->eta, npions2.Eta(), genloop->phi, npions2.Phi()) < DR) continue;
            TLorentzVector vTemp;
            vTemp.SetPtEtaPhiM(genloop->pt, genloop->eta, genloop->phi, genloop->mass);
            vRecoZ+=vTemp;
        }

        const TGenParticle* genTau1 = (TGenParticle*) ((*part)[iTau1]);
        TLorentzVector vGenTau1;
        vGenTau1.SetPtEtaPhiM(genTau1->pt, genTau1->eta, genTau1->phi, genTau1->mass);

        const TGenParticle* genTau2 = (TGenParticle*) ((*part)[iTau2]);
        TLorentzVector vGenTau2;
        vGenTau2.SetPtEtaPhiM(genTau2->pt, genTau2->eta, genTau2->phi, genTau2->mass);

        TLorentzVector vVisTau1, vVisTau2;

        if (deltaR(genTau1->eta, genTau2->eta, genTau1->phi, genTau2->phi)<DR) continue;

        for (Int_t j=0; j<part->GetEntries(); j++)
        {
            const TGenParticle* genloop = (TGenParticle*) ((*part)[j]);
            if (fabs(genloop->pdgId)!=16) continue;
            TLorentzVector vTemp;
            vTemp.SetPtEtaPhiM(genloop->pt, genloop->eta, genloop->phi, 0);
            if (genloop->parent==iTau1)
            {
                vVisTau1=vGenTau1-vTemp;
            }
            if (genloop->parent==iTau2)
            {
                vVisTau2=vGenTau2-vTemp;
            }
        }


        for (Int_t j=0; j<jet->GetEntries(); j++)
        {
            const TGenJet* loop = (TGenJet*) ((*jet)[j]);

            if(loop->pt < 10) continue;

            if (iT1==-1)
            {
                if(deltaR(loop->eta,vVisTau1.Eta(),loop->phi,vVisTau1.Phi())<DR){
                    iT1=j;
                    continue;
                }
            }
            if(iT1!=-1 && ((TGenJet*) ((*jet)[iT1]))->pt < loop->pt){
                if(deltaR(loop->eta,vVisTau1.Eta(),loop->phi,vVisTau1.Phi())<DR){
                    iT1=j;
                    continue;
                }
            }
            if (iT2==-1)
            {
                if(deltaR(loop->eta,vVisTau2.Eta(),loop->phi,vVisTau2.Phi())<DR){
                    iT2=j;
                    continue;
                }
            }
            if(iT2!=-1 && ((TGenJet*) ((*jet)[iT2]))->pt < loop->pt){
                if(deltaR(loop->eta,vVisTau2.Eta(),loop->phi,vVisTau2.Phi())<DR){
                  iT2=j;
                  continue;
                }
            }

        }

        for (Int_t j=0; j<jet->GetEntries(); j++)
        {
            const TGenJet* loop = (TGenJet*) ((*jet)[j]);

            if(loop->pt < 20) continue;

            if(deltaR(vVisTau1.Eta(), loop->eta, vVisTau1.Phi(), loop->phi)<DR+0.5) continue;
            if(deltaR(vVisTau2.Eta(), loop->eta, vVisTau2.Phi(), loop->phi)<DR+0.5) continue;
            
            if (ijetZ1==-1)
            {
                ijetZ1=j;
            }
            else if(((TGenJet*) ((*jet)[ijetZ1]))->pt < loop->pt){
                ijetZ2=ijetZ1;
                ijetZ1=j;
            }
            else if (ijetZ2==-1)
            {
                ijetZ2=j;
            }
            else if(((TGenJet*) ((*jet)[ijetZ2]))->pt < loop->pt){
                ijetZ2=j;
            }
        }

        if(ijetZ1==-1 || ijetZ2==-1) zToLep=1;

        if(zToLep==1){
            for (Int_t j=0; j<part->GetEntries(); j++)
            {
                TGenParticle *genloop = (TGenParticle*) ((*part)[j]);

                Int_t pdg=abs(genloop->pdgId);
                Int_t parent=genloop->parent;

                if(pdg!=11 && pdg!= 13) continue;
                if(genloop->pt < 20) continue;

                if(deltaR(vVisTau1.Eta(), genloop->eta, vVisTau1.Phi(), genloop->phi)<DR+0.5) continue;
                if(deltaR(vVisTau2.Eta(), genloop->eta, vVisTau2.Phi(), genloop->phi)<DR+0.5) continue;

                if (iZ1==-1)
                {
                    iZ1=j;
                }
                else if(((TGenParticle*) ((*part)[iZ1]))->pt < genloop->pt){
                    iZ1=j;
                }
            }

            if(iZ1!=-1){
                for (Int_t j=0; j<part->GetEntries(); j++)
                {
                    TGenParticle* genloop = (TGenParticle*) ((*part)[j]);

                    Int_t pdg=abs(genloop->pdgId);
                    Int_t parent=genloop->parent;

                    if(pdg!=11 && pdg!= 13) continue;
                    if(genloop->pt < 30) continue;
                    if(iZ1==j) continue;
                    if(pdg!=abs(((TGenParticle*) ((*part)[iZ1]))->pdgId)) continue;
                    if(deltaR(vVisTau1.Eta(), genloop->eta, vVisTau1.Phi(), genloop->phi)<DR+0.5) continue;
                    if(deltaR(vVisTau2.Eta(), genloop->eta, vVisTau2.Phi(), genloop->phi)<DR+0.5) continue;

                    if (iZ2==-1)
                    {
                        iZ2=j;
                    }
                    else if(((TGenParticle*) ((*part)[iZ2]))->pt < genloop->pt){
                        iZ2=j;
                    }
                }
            }
        }
        
        if(zToLep==1 && (iZ1==-1 || iZ2==-1)) zToLep=-1;

        if(iZ==-1 && (iZ1==-1 || iZ2==-1) && (ijetZ1==-1 || ijetZ2==-1)) continue;

        if(zToLep==0){
            const TGenJet *jetZ1, *jetZ2;

            jetZ1 = (TGenJet*) ((*jet)[ijetZ1]);
            jetZ2 = (TGenJet*) ((*jet)[ijetZ2]);

            z1_pt=jetZ1->pt;
            z1_eta=jetZ1->eta;
            z1_phi=jetZ1->phi;
            z1_mass=jetZ1->mass;

            z2_pt=jetZ2->pt;
            z2_eta=jetZ2->eta;
            z2_phi=jetZ2->phi;
            z2_mass=jetZ2->mass;
        }

        if(zToLep==1){
            const TGenParticle *z1, *z2;

            z1 = (TGenParticle*) ((*part)[iZ1]);
            z2 = (TGenParticle*) ((*part)[iZ2]);

            z1_pt=z1->pt;
            z1_eta=z1->eta;
            z1_phi=z1->phi;
            z1_mass=z1->mass;

            z2_pt=z2->pt;
            z2_eta=z2->eta;
            z2_phi=z2->phi;
            z2_mass=z2->mass;
        }

        if(iZ!=-1){
            const TGenParticle *parZ = (TGenParticle*) ((*part)[iZ]);

            z_pt = parZ->pt;
            z_eta = parZ->eta;
            z_phi = parZ->phi;
            z_mass = parZ->mass;
        }

        recoz_pt = vRecoZ.Pt();
        recoz_eta = vRecoZ.Eta();
        recoz_phi = vRecoZ.Phi();
        recoz_mass = vRecoZ.M();

        if(iT1!=-1 && iT2!=-1){
            const TGenJet *taujet1, *taujet2;

            taujet1 = (TGenJet*) ((*jet)[iT1]);
            taujet2 = (TGenJet*) ((*jet)[iT2]);

            jetTau1_pt=taujet1->pt;
            jetTau1_eta=taujet1->eta;
            jetTau1_phi=taujet1->phi;
            jetTau1_mass=taujet1->mass;

            jetTau2_pt=taujet2->pt;
            jetTau2_eta=taujet2->eta;
            jetTau2_phi=taujet2->phi;
            jetTau2_mass=taujet2->mass;
        } 

        genTau1_pt=genTau1->pt;
        genTau1_eta=genTau1->eta;
        genTau1_phi=genTau1->phi;
        genTau1_mass=genTau1->mass;

        genTau2_pt=genTau2->pt;
        genTau2_eta=genTau2->eta;
        genTau2_phi=genTau2->phi;
        genTau2_mass=genTau2->mass;

        visTau1_pt=vVisTau1.Pt();
        visTau1_eta=vVisTau1.Eta();
        visTau1_phi=vVisTau1.Phi();
        visTau1_mass=vVisTau1.M();

        visTau2_pt=vVisTau2.Pt();
        visTau2_eta=vVisTau2.Eta();
        visTau2_phi=vVisTau2.Phi();
        visTau2_mass=vVisTau2.M();

        cpions1_pt=cpions1.Pt();
        cpions1_eta=cpions1.Eta();
        cpions1_phi=cpions1.Phi();
        cpions1_mass=cpions1.M();

        cpions2_pt=cpions2.Pt();
        cpions2_eta=cpions2.Eta();
        cpions2_phi=cpions2.Phi();
        cpions2_mass=cpions2.M();

        npions1_pt=npions1.Pt();
        npions1_eta=npions1.Eta();
        npions1_phi=npions1.Phi();
        npions1_mass=npions1.M();

        npions2_pt=npions2.Pt();
        npions2_eta=npions2.Eta();
        npions2_phi=npions2.Phi();
        npions2_mass=npions2.M();

        for (Int_t j=0; j<part->GetEntries(); j++)
        {
            const TGenParticle* genloop = (TGenParticle*) ((*part)[j]);
            if ( genloop->pt<20) continue;
            if ( abs(genloop->pdgId)!=13 && abs(genloop->pdgId)!=11 ) continue;
            nLeptons++;
        }

        outtree->Fill();

    }

    outfile->Write();
    outfile->Save();

}
int main(int argc, char* argv[]){

   if(argc<2){
      cout<<"USAGE: MakeGGMatrixDecay #DECAYRUN"<<endl;
      return 0;
   }

   int runD = atoi(argv[1]);
   char decayfile[128];
   char outfile[128];


   Int_t index;
   Int_t run;

   Int_t ion_z;
   Int_t ion_x;
   Int_t ion_y;

   Double_t beta35;
   Double_t beta57;
   Double_t beta711;
   Double_t aoq37;
   Double_t zed;

   Int_t Zed;
   Int_t Mass;
   Int_t flagall;

   Long64_t t;
   Int_t z;
   Float_t x;
   Float_t y;
   Int_t ex;
   Int_t ey;
   Int_t mulx;
   Int_t muly;
   Int_t flag_side;
   Int_t deltaz;
   Double_t deltaxy;

   Int_t gc_matrix;
   Double_t gc1_E[7056];//(beta_index_max(10) X gc_hit_max(20))^2
   Double_t gc2_E[7056];
   Double_t gc1_T[7056];
   Double_t gc2_T[7056];
   Int_t gc_hit;
   Int_t gc_ch[84];   //[gc_hit]
   Double_t gc_E[84];   //[gc_hit]
   Double_t gc_T[84];   //[gc_hit]

   Int_t ab_matrix;
   Double_t ab1_E[7056];
   Double_t ab2_E[7056];
   Double_t ab1_T[7056];
   Double_t ab2_T[7056];
   Int_t ab_hit;
   Int_t ab_ch[84];   //[ab_hit]
   Double_t ab_E[84];   //[ab_hit]
   Double_t ab_T[84];   //[ab_hit]

   sprintf(decayfile,"../root/decay/cu81/decay_new%04d.root",runD);
   //sprintf(decayfile,"go4.root");
   sprintf(outfile,"../gamma_db/ni75_%04d.root",runD);

   decay_ggmatrix ggdecay(decayfile);

   Long64_t dEntry, dEntryMAX;  //entry for decay
   TFile *rootfile = new TFile(outfile,"RECREATE");

   TTree *decay = new TTree("decay","decay");

   decay->Branch("run",&run,"run/I");
   decay->Branch("ion_z",&ion_z,"ion_z/I");
   decay->Branch("ion_x",&ion_x,"ion_x/I");
   decay->Branch("ion_y",&ion_y,"ion_y/I");

   decay->Branch("beta35", &beta35,"beta35/D");
   decay->Branch("beta57", &beta57,"beta57/D");
   decay->Branch("beta711", &beta711,"beta711/D");
   decay->Branch("aoq37", &aoq37,"aoq37/D");
   decay->Branch("zed", &zed,"zed/D");

   decay->Branch("Zed", &Zed,"Zed/I");
   decay->Branch("Mass", &Mass,"Mass/I");
   decay->Branch("flagall", &flagall,"flagall/I");

   decay->Branch("index",&index,"index/I");
   decay->Branch("t",&t,"t/L");
   decay->Branch("z",&z,"z/I");
   decay->Branch("x",&x,"x/F");
   decay->Branch("y",&y,"y/F");
   decay->Branch("ex",&ex,"ex/I");
   decay->Branch("ey",&ey,"ey/I");
   decay->Branch("mulx",&mulx,"mulx/I");
   decay->Branch("muly",&muly,"muly/I");
   decay->Branch("flag_side",&flag_side,"flag_side/I");
   decay->Branch("deltaz",&deltaz,"deltaz/I");
   decay->Branch("deltaxy",&deltaxy,"deltaxy/D");

   decay->Branch("ab_hit",&ab_hit,"ab_hit/I");
   decay->Branch("ab_ch",ab_ch,"ab_ch[ab_hit]/I");
   decay->Branch("ab_E",ab_E,"ab_E[ab_hit]/D");
   decay->Branch("ab_T",ab_T,"ab_T[ab_hit]/D");

   decay->Branch("gc_hit",&gc_hit,"gc_hit/I");
   decay->Branch("gc_ch",gc_ch,"gc_ch[gc_hit]/I");
   decay->Branch("gc_E",gc_E,"gc_E[gc_hit]/D");
   decay->Branch("gc_T",gc_T,"gc_T[gc_hit]/D");

   decay->Branch("ab_matrix",&ab_matrix,"ab_matrix/I");
   decay->Branch("ab1_E",ab1_E,"ab1_E[ab_matrix]/D");
   decay->Branch("ab2_E",ab2_E,"ab2_E[ab_matrix]/D");
   decay->Branch("ab1_T",ab1_T,"ab1_T[ab_matrix]/D");
   decay->Branch("ab2_T",ab2_T,"ab2_T[ab_matrix]/D");

   decay->Branch("gc_matrix",&gc_matrix,"gc_matrix/I");
   decay->Branch("gc1_E",gc1_E,"gc1_E[gc_matrix]/D");
   decay->Branch("gc2_E",gc2_E,"gc2_E[gc_matrix]/D");
   decay->Branch("gc1_T",gc1_T,"gc1_T[gc_matrix]/D");
   decay->Branch("gc2_T",gc2_T,"gc2_T[gc_matrix]/D");

   dEntryMAX = ggdecay.fChain->GetEntriesFast();

   for(dEntry = 0; dEntry < dEntryMAX; dEntry++){
      if(dEntry%1000 == 0){
         cout<<"RUN#"<<runD<<", "<<dEntry<<" lines finished."<<endl;
      }

      ab_matrix=0;
      gc_matrix=0;

      ggdecay.GetEntry(dEntry);
      ion_z = ggdecay.z;
      ion_x = ggdecay.x;
      ion_y = ggdecay.y;

      beta35 = ggdecay.beta35;
      beta57 = ggdecay.beta57;
      beta711 = ggdecay.beta711;
      aoq37 = ggdecay.aoq37;
      zed = ggdecay.zed;
      Zed = ggdecay.Zed;
      Mass = ggdecay.Mass;

      flagall = ggdecay.flagall;

      if(Zed != 28 || Mass != 75){
         continue;
      }

      run = ggdecay.run;
      int index_all = ggdecay.beta_;
      for(int i=0; i<index_all; i++){
         index = i;
         t = ggdecay.beta_t[i];
         z = ggdecay.beta_z[i];
         x = ggdecay.beta_x[i];
         y = ggdecay.beta_y[i];
         ex = ggdecay.beta_ex[i];
         ey = ggdecay.beta_ey[i];
         if(z>=4){
            mulx = ggdecay.beta_mulx[i]/2;
         }else{
            mulx = ggdecay.beta_mulx[i];
         }
         muly = ggdecay.beta_muly[i];
         flag_side = ggdecay.beta_flag_side[i];
         deltaz = ggdecay.beta_deltaz[i];
         deltaxy = ggdecay.beta_deltaxy[i];

         gc_hit=ggdecay.beta_gc_hit[i];
         memcpy(gc_ch, ggdecay.beta_gc_ch[i], sizeof(ggdecay.beta_gc_ch[i]));
         memcpy(gc_E, ggdecay.beta_gc_E[i], sizeof(ggdecay.beta_gc_E[i]));
         memcpy(gc_T, ggdecay.beta_gc_T[i], sizeof(ggdecay.beta_gc_T[i]));

         ggdecay.GammaAddback(i);
         ab_hit=ggdecay.beta_ab_hit[i];
         memcpy(ab_ch, ggdecay.beta_ab_ch[i], sizeof(ggdecay.beta_ab_ch[i]));
         memcpy(ab_E, ggdecay.beta_ab_E[i], sizeof(ggdecay.beta_ab_E[i]));
         memcpy(ab_T, ggdecay.beta_ab_T[i], sizeof(ggdecay.beta_ab_T[i]));

         gc_matrix = gc_hit*gc_hit;
         for(int a=0; a<gc_hit; a++){
            for(int b=0; b<gc_hit; b++){
               gc1_E[a*gc_hit+b]=gc_E[a];
               gc2_E[a*gc_hit+b]=gc_E[b];
               gc1_T[a*gc_hit+b]=gc_T[a];
               gc2_T[a*gc_hit+b]=gc_T[b];
            }
         }
         ab_matrix = ab_hit*ab_hit;
         for(int a=0; a<ab_hit; a++){
            for(int b=0; b<ab_hit; b++){
               ab1_E[a*ab_hit+b]=ab_E[a];
               ab2_E[a*ab_hit+b]=ab_E[b];
               ab1_T[a*ab_hit+b]=ab_T[a];
               ab2_T[a*ab_hit+b]=ab_T[b];
            }
         }
         decay->Fill();
      }
   }
   rootfile->Write();
   rootfile->Close();
   cout<<"finished"<<endl;
}
Example #27
0
int
Fitfraction(){
   ofstream myfile;
   myfile.open("JetFakeRate-mg-2016.txt");
   std::ostringstream hadfrac;
   hadfrac.str("");

  double IsoCutLower[]={3.32,3.42,3.52,3.62,3.72,3.82,3.92,4.02,4.12,4.22,4.32,4.42,4.52,4.62,4.72,4.82,4.92};
  double IsoCutUpper[]={12,12.5,13,13.5,14,14.5,15,15.5,16,16.5,17,17.5,18};
  unsigned nUpper = sizeof(IsoCutUpper)/sizeof(double);
  unsigned nLower = sizeof(IsoCutLower)/sizeof(double);
  //int PtBins[]=  {25,30,35,45,55,70,90};
  int PtBins[]=  {25,28,30,34,38,42,46,50,54,58,62,66,70,75,80,90,100,120,140};
  unsigned nSet = sizeof(PtBins)/sizeof(int);
  TH1F* h_data[nSet][nLower][nUpper]; 
  TH1F* h_bg[nSet][nLower][nUpper];
  TH1F* h_target[nSet][nLower][nUpper];
  TObjArray *templatelist[nSet][nLower][nUpper];
  TFractionFitter* fitter[nSet][nLower][nUpper];
  TH1F* result[nSet][nLower][nUpper];
  TCanvas *can[nSet][nLower][nUpper];
  std::ostringstream hname;

  TFile *outputfile = TFile::Open("hadfraction.root","NEW");
  outputfile->cd();
  TH2F* fracHad2D[nSet];
  TH1F* fracHad1D[nSet];
  for(unsigned iF(0); iF<nSet; iF++){
	hname.str("");
	hname << "fracHad2D_" << iF;
	fracHad2D[iF]=new TH2F(hname.str().c_str(),hname.str().c_str(),17,3.3,5,13,12,18);
	hname.str("");
    hname << "fracHad1D_" << iF;
    fracHad1D[iF]=new TH1F(hname.str().c_str(),hname.str().c_str(),100,0,0.4);
  } 
//************ Signal Tree **********************//
  TChain *egtree = new TChain("egTree");
  egtree->Add("../data/plot_hadron_2016.root");
  float eg_phoEt(0);
  float eg_phoSigma(0);
  float eg_phoChIso(0);
  
  egtree->SetBranchAddress("phoEt",     &eg_phoEt);
  egtree->SetBranchAddress("phoSigma",  &eg_phoSigma);
  egtree->SetBranchAddress("phoChIso",  &eg_phoChIso);

  TChain *mgtree = new TChain("mgTree","mgTree");
  mgtree->Add("../data/plot_hadron_2016.root");
  float mg_phoEt(0);
  float mg_phoSigma(0);
  float mg_phoChIso(0);
  
  mgtree->SetBranchAddress("phoEt",     &mg_phoEt);
  mgtree->SetBranchAddress("phoSigma",  &mg_phoSigma);
  mgtree->SetBranchAddress("phoChIso",  &mg_phoChIso);

  TChain *hadtree = new TChain("hadTree","hadTree");
  hadtree->Add("../data/plot_hadron_2016.root");
  float had_phoEt(0);
  float had_phoSigma(0);
  float had_phoChIso(0);
  
  hadtree->SetBranchAddress("phoEt",     &had_phoEt);
  hadtree->SetBranchAddress("phoSigma",  &had_phoSigma);
  hadtree->SetBranchAddress("phoChIso",  &had_phoChIso);

  TChain *Zeetree = new TChain("ZeeTree");
  Zeetree->Add("../data/plotZ_DoubleMu2016.root");
  float phoEt(0);
  float phoSigma(0);
  float invmass(0);
  bool  ismg(0); 
 
  Zeetree->SetBranchAddress("phoEt",     &phoEt);
  Zeetree->SetBranchAddress("phoSigma",  &phoSigma);
  Zeetree->SetBranchAddress("invmass",   &invmass);
  Zeetree->SetBranchAddress("ismg",      &ismg);

  double fittingError[nSet];
  double systematicError[nSet];
  for(unsigned iF(0); iF<nSet; iF++){ fittingError[iF] = 0; systematicError[iF] = 0;}

  for(unsigned iUpper(0); iUpper<nUpper; iUpper++){
    for(unsigned iLower(0); iLower<nLower; iLower++){
	  for(unsigned iF(0); iF<nSet; iF++){
		templatelist[iF][iLower][iUpper] = new TObjArray(2);
		hname.str("");
		hname << "can" << iF << "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper] ;
		can[iF][iLower][iUpper]=new TCanvas(hname.str().c_str(),hname.str().c_str(),600,600);
		hname.str("");
        if(iF==nSet-1)hname << "p_SigmaZ-pt-140-inf" << "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper];
        else hname <<"p_SigmaZ-pt-" << PtBins[iF] << "-" << PtBins[iF+1] << "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper];
		h_data[iF][iLower][iUpper] = new TH1F(hname.str().c_str(), hname.str().c_str(), 40, 0.0, 0.02); 
		hname.str("");
		if(iF==nSet-1)hname<< "SigmaHadEB-pt-140-inf" << "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper];
		else hname <<"SigmaHadEB-pt-" <<  PtBins[iF] << "-" << PtBins[iF+1] << "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper];
		h_bg[iF][iLower][iUpper] = new TH1F(hname.str().c_str(), hname.str().c_str(), 40, 0.0, 0.02);
		hname.str("");
		if(iF==nSet-1)hname<< "p_SigmaTarEB-pt-140-inf" << "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper];
		else hname <<"p_SigmaTarEB-pt-" <<  PtBins[iF] << "-" << PtBins[iF+1]<< "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper];
		h_target[iF][iLower][iUpper] = new TH1F(hname.str().c_str(), hname.str().c_str(),40, 0.0, 0.02);    

        for(unsigned ievt(0); ievt < Zeetree->GetEntries(); ievt++){
          Zeetree->GetEntry(ievt);
          if(invmass > 70 && invmass < 110 && ismg){
			if(PtBins[iF] < 50){
			  if(phoEt >= PtBins[iF] && phoEt < PtBins[iF+1])h_data[iF][iLower][iUpper]->Fill(phoSigma);
			}else{
              if(phoEt >= 50)h_data[iF][iLower][iUpper]->Fill(phoSigma);
			}
          }
        }
 
		double nden(0), totalden(0);
		double nnum(0), totalnum(0);
		for(unsigned ievt(0); ievt < mgtree->GetEntries(); ievt++){
		  mgtree->GetEntry(ievt);
		  if(iF!= nSet-1){
			if(mg_phoEt >= PtBins[iF] && mg_phoEt < PtBins[iF+1]){
			  if(mg_phoChIso <= 3.32){
                h_target[iF][iLower][iUpper]->Fill(mg_phoSigma);
                totalden+=1;
                if(mg_phoSigma < 0.0103)nden+=1;
              }
			}
		  }else{
			if(mg_phoEt >= PtBins[iF]){
			  if(mg_phoChIso <= 3.32){
                h_target[iF][iLower][iUpper]->Fill(mg_phoSigma);
                totalden+=1;
                if(mg_phoSigma < 0.0103)nden+=1;
              }
			}
		  }
		}

		for(unsigned ievt(0); ievt < mgtree->GetEntries(); ievt++){
		  mgtree->GetEntry(ievt);
		  if(iF!= nSet-1){
			if(mg_phoEt >= PtBins[iF] && mg_phoEt < PtBins[iF+1]){
			  if(mg_phoChIso > IsoCutLower[iLower] && mg_phoChIso < IsoCutUpper[iUpper]){
                h_bg[iF][iLower][iUpper]->Fill(mg_phoSigma);
                totalnum+=1;
                if(mg_phoSigma < 0.0103)nnum+=1;
              }
			}
		  }else{
			if(mg_phoEt >= PtBins[iF]){
			  if(mg_phoChIso > IsoCutLower[iLower] && mg_phoChIso < IsoCutUpper[iUpper]){
                h_bg[iF][iLower][iUpper]->Fill(mg_phoSigma);
                totalnum+=1;
                if(mg_phoSigma < 0.0103)nnum+=1;
              }
			}
		  }
		}
		double den = nden/totalden; 
		double denerror = (1.0/sqrt(nden)+ 1.0/sqrt(totalden))*den;
		double num = nnum/totalnum; 
		double numerror = (1.0/sqrt(nnum) + 1.0/sqrt(totalnum))*num;
		myfile << "pt=" << PtBins[iF] << " " <<  IsoCutLower[iLower] << " < Iso < " << IsoCutUpper[iUpper] <<  " numIntegral/entries = " << num << std::endl; 

		templatelist[iF][iLower][iUpper]->Add(h_data[iF][iLower][iUpper]);
		templatelist[iF][iLower][iUpper]->Add(h_bg[iF][iLower][iUpper]);
		fitter[iF][iLower][iUpper]= new TFractionFitter(h_target[iF][iLower][iUpper], templatelist[iF][iLower][iUpper], "V");
		fitter[iF][iLower][iUpper]->SetRangeX(3,32);
		fitter[iF][iLower][iUpper]->Constrain(1,0.0,1.0);
		Int_t status = fitter[iF][iLower][iUpper]->Fit();
		if(status == 0){
		  result[iF][iLower][iUpper] = (TH1F*)fitter[iF][iLower][iUpper]->GetPlot();
          result[iF][iLower][iUpper]->SetMinimum(0);
		  double fracBkg, errorBkg;
		  double fracSig, errorSig;
		  fitter[iF][iLower][iUpper]->GetResult(0, fracSig, errorSig);
		  fitter[iF][iLower][iUpper]->GetResult(1, fracBkg, errorBkg);
		  can[iF][iLower][iUpper]->cd();
		  h_target[iF][iLower][iUpper]->GetXaxis()->SetRangeUser(0.006,0.02);
		  h_target[iF][iLower][iUpper]->SetMarkerStyle(20);
		  h_target[iF][iLower][iUpper]->Draw("Ep");
		  result[iF][iLower][iUpper]->SetLineColor(kBlue);
		  result[iF][iLower][iUpper]->SetFillStyle(1001);
		  result[iF][iLower][iUpper]->SetFillColor(kBlue);
		  result[iF][iLower][iUpper]->Draw("same");
		  h_bg[iF][iLower][iUpper]->Scale(1.0/h_bg[iF][iLower][iUpper]->GetEntries()*h_target[iF][iLower][iUpper]->GetEntries()*fracBkg);
		  h_bg[iF][iLower][iUpper]->SetLineColor(kGreen);
		  h_bg[iF][iLower][iUpper]->SetFillStyle(1001);
		  h_bg[iF][iLower][iUpper]->SetFillColor(kGreen);
		  h_bg[iF][iLower][iUpper]->Draw("same");
		  h_target[iF][iLower][iUpper]->Draw("Ep same");
		  TLatex* latex = new TLatex();
		  hname.str("");
		  hname << "Bkg% = " << fracBkg << " #pm " << errorBkg << std::endl;
		  latex->DrawLatex(0.01,0.9*h_target[iF][iLower][iUpper]->GetMaximum(),hname.str().c_str()); 
		  hname.str("");
		  hname << "#chi^{2}/ndof = " << fitter[iF][iLower][iUpper]->GetChisquare() << "/" << fitter[iF][iLower][iUpper]->GetNDF(); 
		  latex->DrawLatex(0.01,0.8*h_target[iF][iLower][iUpper]->GetMaximum(),hname.str().c_str());
		  hname.str("");
		  hname << "frac=" << num << "*" << fracBkg << "/" << den << std::endl;
		  latex->DrawLatex(0.01,0.7*h_target[iF][iLower][iUpper]->GetMaximum(),hname.str().c_str());
		  hname.str("");
		  hname << " =" << num*fracBkg/den << " #pm " << (numerror/num + denerror/den + errorBkg/fracBkg)*num*fracBkg/den;
		  latex->DrawLatex(0.01,0.6*h_target[iF][iLower][iUpper]->GetMaximum(),hname.str().c_str());
		 
		  if(IsoCutLower[iLower] == 3.32 && IsoCutUpper[iUpper]==15.0){
            hadfrac << num*fracBkg/den << ",";
		    fittingError[iF] = (numerror/num + denerror/den + errorBkg/fracBkg)*num*fracBkg/den ;
          }
		  myfile << "frac = " << fracBkg << std::endl;
          fracHad2D[iF]->Fill(IsoCutLower[iLower], IsoCutUpper[iUpper], num*fracBkg/den);
          fracHad1D[iF]->Fill(num*fracBkg/den); 
		} 
		 
		hname.str("");
		hname << "frac" << iF << "_" << IsoCutLower[iLower] << "_" << IsoCutUpper[iUpper] << ".pdf";
		if(IsoCutLower[iLower] == 3.32 && IsoCutUpper[iUpper]==15.0)can[iF][iLower][iUpper]->SaveAs(hname.str().c_str());

	  }
    }
  }
  myfile << hadfrac.str().c_str() << std::endl;
  for(unsigned iF(0); iF < nSet; iF++)systematicError[iF] =  fracHad1D[iF]->GetMeanError();
  for(unsigned iF(0); iF < nSet; iF++)myfile << sqrt(fittingError[iF]*fittingError[iF] + systematicError[iF]*systematicError[iF]) << ",";
  myfile.close();
  outputfile->Write();
  return 1;
}
Example #28
0
int main( int argc, char* argv[] ) {

  setStyle();
  
  std::string runName = "test_10";
  if( argc>1 ) {
    std::string runName_str(argv[1]);
    runName = runName_str;
  }
  
  
  std::string fileName = "../PositionAnalysis/PosAn_" + runName + ".root";
  TFile* file = TFile::Open( fileName.c_str() );
  std::cout << "-> Opened file: " << fileName << std::endl;

  TTree* tree = (TTree*)file->Get("tree_passedEvents");

  float hodox_corr[HODOX_CHANNELS], hodoy_corr[HODOY_CHANNELS],cef3[CEF3_CHANNELS],cef3_corr[CEF3_CHANNELS],cef3_pedSubtracted[CEF3_CHANNELS],scintFront;
  int nHodoClustersX,nHodoClustersY;

  tree->SetBranchAddress( "nHodoClustersX", &nHodoClustersX );
  tree->SetBranchAddress( "nHodoClustersY", &nHodoClustersY );
  tree->SetBranchAddress( "hodox_corr", hodox_corr );
  tree->SetBranchAddress( "hodoy_corr", hodoy_corr );
  tree->SetBranchAddress( "cef3", cef3 );
  tree->SetBranchAddress( "cef3_corr", cef3_corr );
  tree->SetBranchAddress( "cef3_pedSubtracted", cef3_pedSubtracted );
  tree->SetBranchAddress( "scintFront", &scintFront );

  int nentries = tree->GetEntries();

  std::string outfileName = "PhotoElectronAn_" + runName + ".root";
  TFile* outfile = TFile::Open( outfileName.c_str(), "RECREATE" );

  TH1D* h1_singleEleEnergyDistribution = new TH1D("singleEleEnergyDistribution", "",1000 , 0 , 10000);
  TH1D* h1_singleEleEnergyDistributionCalib = new TH1D("singleEleEnergyDistribution", "",1000 , 0 , 10000);
  TH1D* h1_singleEleEnergyDistribution_ch[4];
  TH1D* h1_singleEleEnergyDistributionCalib_ch[4];

//  Q1 calibration
//  std::vector<float> correctionFactors;
//  correctionFactors.push_back(1.11228);
//  correctionFactors.push_back(0.855333);
//  correctionFactors.push_back(0.9802);
//  correctionFactors.push_back(1.08781);

//  mu*Q1 calibration
//  std::vector<float> correctionFactors;
//  correctionFactors.push_back(1.19514);
//  correctionFactors.push_back(0.860177);
//  correctionFactors.push_back(0.952363);
//  correctionFactors.push_back(0.977169);

  //mumean*Q1 calibration
  std::vector<float> correctionFactors;
  correctionFactors.push_back(1.09716);
  correctionFactors.push_back(0.843707);
  correctionFactors.push_back(0.966413);
  correctionFactors.push_back(1.07241);



  for (int i=0;i<4;++i){
    TString nameHisto="singleEnergyDistribution";
    TString nameHistoCalib="singleEnergyDistributionCalib";
    nameHisto+=i;
    nameHistoCalib+=i;
    h1_singleEleEnergyDistribution_ch[i] = new TH1D(nameHisto, "",100 , 0 , 4000.);
    h1_singleEleEnergyDistributionCalib_ch[i] = new TH1D(nameHistoCalib, "",100 , 0 , 4000);
  }



  for( unsigned iEntry=0; iEntry<nentries; ++iEntry ) {
    
    tree->GetEntry(iEntry);

    if( iEntry % 1000 == 0 ) std::cout << "Entry: " << iEntry << " / " << nentries << std::endl;

    bool isSingleEle=scintFront>500. && scintFront<2000. && nHodoClustersX==1 && nHodoClustersY==1;
    float cef3Total=0.;    
    float cef3TotalCalib=0.;   
 
    for (int i=0;i<CEF3_CHANNELS;i++){

      float energy=cef3_pedSubtracted[i];

      cef3Total+=energy;
      cef3TotalCalib+=energy*correctionFactors[i];

      if(isSingleEle){
	h1_singleEleEnergyDistribution_ch[i]->Fill(energy);
	h1_singleEleEnergyDistributionCalib_ch[i]->Fill(energy*correctionFactors[i]);
      }
    }

    if(isSingleEle) {
      h1_singleEleEnergyDistribution->Fill(cef3Total);
      h1_singleEleEnergyDistributionCalib->Fill(cef3TotalCalib);
    }
  }

  TCanvas * c1 = new TCanvas("c1", "c1", 600, 600);
  c1->cd();



  TH2D* h2_axes = new TH2D("axes", "", 10, 100., 2000., 10, 0., 1.15*h1_singleEleEnergyDistributionCalib_ch[2]->GetMaximum() );
  h2_axes->SetXTitle( "ADC Counts" );
  h2_axes->Draw();

  h1_singleEleEnergyDistributionCalib_ch[0]->SetLineColor(kBlack);
  h1_singleEleEnergyDistributionCalib_ch[1]->SetLineColor(kRed);
  h1_singleEleEnergyDistributionCalib_ch[2]->SetLineColor(kBlue);
  h1_singleEleEnergyDistributionCalib_ch[3]->SetLineColor(kMagenta);
     					  
  h1_singleEleEnergyDistributionCalib_ch[0]->SetLineWidth(2);
  h1_singleEleEnergyDistributionCalib_ch[1]->SetLineWidth(2);
  h1_singleEleEnergyDistributionCalib_ch[2]->SetLineWidth(2);
  h1_singleEleEnergyDistributionCalib_ch[3]->SetLineWidth(2);

  TLegend* legend = new TLegend( 0.7, 0.7, 0.90, 0.9 );
  legend->SetLineColor(0);
  legend->SetFillColor(0);
  legend->SetFillStyle(0);
  legend->SetTextSize(0.038);
  legend->AddEntry( h1_singleEleEnergyDistributionCalib_ch[0], "channel 0", "L" );
  legend->AddEntry( h1_singleEleEnergyDistributionCalib_ch[1], "channel 1", "L" );
  legend->AddEntry( h1_singleEleEnergyDistributionCalib_ch[2], "channel 2", "L" );
  legend->AddEntry( h1_singleEleEnergyDistributionCalib_ch[3], "channel 3", "L" );
  legend->Draw("same");

  h1_singleEleEnergyDistributionCalib_ch[2]->Draw("same");
  h1_singleEleEnergyDistributionCalib_ch[0]->Draw("same");
  h1_singleEleEnergyDistributionCalib_ch[1]->Draw("same");
  h1_singleEleEnergyDistributionCalib_ch[3]->Draw("same");

  c1->SaveAs("calibratedChannels.png");
  c1->SaveAs("calibratedChannels.eps");

  c1->Clear();

  h2_axes->Draw();

  h1_singleEleEnergyDistribution_ch[0]->SetLineColor(kBlack);
  h1_singleEleEnergyDistribution_ch[1]->SetLineColor(kRed);
  h1_singleEleEnergyDistribution_ch[2]->SetLineColor(kBlue);
  h1_singleEleEnergyDistribution_ch[3]->SetLineColor(kMagenta);
     					  
  h1_singleEleEnergyDistribution_ch[0]->SetLineWidth(2);
  h1_singleEleEnergyDistribution_ch[1]->SetLineWidth(2);
  h1_singleEleEnergyDistribution_ch[2]->SetLineWidth(2);
  h1_singleEleEnergyDistribution_ch[3]->SetLineWidth(2);

  h1_singleEleEnergyDistribution_ch[0]->Draw("same");
  h1_singleEleEnergyDistribution_ch[1]->Draw("same");
  h1_singleEleEnergyDistribution_ch[2]->Draw("same");
  h1_singleEleEnergyDistribution_ch[3]->Draw("same");

  legend->Draw("same");

  c1->SaveAs("uncalibratedChannels.png");
  c1->SaveAs("uncalibratedChannels.eps");


  //plot mu,rms of uncalib distribution
  TH1D* h1_mean = new TH1D("mean", "", 4, -0.5, 3.5);
  TH1D* h1_rms = new TH1D("rms", "", 4, -0.5, 3.5);

  TF1* f1_gaus = new TF1( "f1_gaus", "gaus",0,2000 );

  f1_gaus->SetRange(h1_singleEleEnergyDistribution_ch[0]->GetMean()-3*h1_singleEleEnergyDistribution_ch[0]->GetRMS(),h1_singleEleEnergyDistribution_ch[0]->GetMean()+3*h1_singleEleEnergyDistribution_ch[0]->GetRMS() );
  h1_singleEleEnergyDistribution_ch[0]->Fit(f1_gaus,"R");
  h1_mean->SetBinContent( 1, f1_gaus->GetParameter(1) );
  h1_mean->SetBinError( 1, f1_gaus->GetParError(1) );
  h1_rms->SetBinContent( 1, f1_gaus->GetParameter(2) );
  h1_rms->SetBinError( 1, f1_gaus->GetParError(2) );


  f1_gaus->SetRange(h1_singleEleEnergyDistribution_ch[1]->GetMean()-3*h1_singleEleEnergyDistribution_ch[1]->GetRMS(),h1_singleEleEnergyDistribution_ch[1]->GetMean()+3*h1_singleEleEnergyDistribution_ch[1]->GetRMS() );
  h1_singleEleEnergyDistribution_ch[1]->Fit(f1_gaus,"R");
  h1_mean->SetBinContent( 2, f1_gaus->GetParameter(1) );
  h1_mean->SetBinError( 2, f1_gaus->GetParError(1) );
  h1_rms->SetBinContent( 2, f1_gaus->GetParameter(2) );
  h1_rms->SetBinError( 2, f1_gaus->GetParError(2) );


  f1_gaus->SetRange(h1_singleEleEnergyDistribution_ch[2]->GetMean()-3*h1_singleEleEnergyDistribution_ch[2]->GetRMS(),h1_singleEleEnergyDistribution_ch[2]->GetMean()+3*h1_singleEleEnergyDistribution_ch[2]->GetRMS() );
  h1_singleEleEnergyDistribution_ch[2]->Fit(f1_gaus,"R");
  h1_mean->SetBinContent( 3, f1_gaus->GetParameter(1) );
  h1_mean->SetBinError( 3, f1_gaus->GetParError(2) );
  h1_rms->SetBinContent( 3, f1_gaus->GetParameter(2) );
  h1_rms->SetBinError( 3, f1_gaus->GetParError(2) );

  f1_gaus->SetRange(h1_singleEleEnergyDistribution_ch[3]->GetMean()-3*h1_singleEleEnergyDistribution_ch[3]->GetRMS(),h1_singleEleEnergyDistribution_ch[3]->GetMean()+3*h1_singleEleEnergyDistribution_ch[3]->GetRMS() );
  h1_singleEleEnergyDistribution_ch[3]->Fit(f1_gaus,"R");
  h1_mean->SetBinContent( 4, f1_gaus->GetParameter(1) );
  h1_mean->SetBinError( 4, f1_gaus->GetParError(1) );
  h1_rms->SetBinContent( 4, f1_gaus->GetParameter(2) );
  h1_rms->SetBinError( 4, f1_gaus->GetParError(2) );


  c1->Clear();
  h1_mean->SetXTitle( "Channel Number");
  h1_mean->SetMarkerStyle(20);
  h1_mean->SetMarkerSize(1.6);

  h1_mean->GetYaxis()->SetRangeUser(720.,890.);
  h1_mean->Draw();

  c1->SaveAs("muUncalibratedChannels.png");
  c1->SaveAs("muUncalibratedChannels.eps");

  c1->Clear();
  h1_rms->SetXTitle( "Channel Number");
  h1_rms->SetMarkerStyle(20);
  h1_rms->SetMarkerSize(1.6);


  h1_rms->Draw();

  c1->SaveAs("rmsUncalibratedChannels.png");
  c1->SaveAs("rmsUncalibratedChannels.eps");


  //plot mu,rms of uncalib distribution
  TH1D* h1_meanCalib = new TH1D("meanCalib", "", 4, -0.5, 3.5);
  TH1D* h1_rmsCalib = new TH1D("rmsCalib", "", 4, -0.5, 3.5);


  f1_gaus->SetRange(h1_singleEleEnergyDistributionCalib_ch[0]->GetMean()-3*h1_singleEleEnergyDistributionCalib_ch[0]->GetRMS(),h1_singleEleEnergyDistributionCalib_ch[0]->GetMean()+3*h1_singleEleEnergyDistributionCalib_ch[0]->GetRMS() );
  h1_singleEleEnergyDistributionCalib_ch[0]->Fit(f1_gaus,"R");
  h1_meanCalib->SetBinContent( 1, f1_gaus->GetParameter(1) );
  h1_meanCalib->SetBinError( 1, f1_gaus->GetParError(1) );
  h1_rmsCalib->SetBinContent( 1, f1_gaus->GetParameter(2) );
  h1_rmsCalib->SetBinError( 1, f1_gaus->GetParError(2) );


  f1_gaus->SetRange(h1_singleEleEnergyDistributionCalib_ch[1]->GetMean()-3*h1_singleEleEnergyDistributionCalib_ch[1]->GetRMS(),h1_singleEleEnergyDistributionCalib_ch[1]->GetMean()+3*h1_singleEleEnergyDistributionCalib_ch[1]->GetRMS() );
  h1_singleEleEnergyDistributionCalib_ch[1]->Fit(f1_gaus,"R");
  h1_meanCalib->SetBinContent( 2, f1_gaus->GetParameter(1) );
  h1_meanCalib->SetBinError( 2, f1_gaus->GetParError(1) );
  h1_rmsCalib->SetBinContent( 2, f1_gaus->GetParameter(2) );
  h1_rmsCalib->SetBinError( 2, f1_gaus->GetParError(2) );


  f1_gaus->SetRange(h1_singleEleEnergyDistributionCalib_ch[2]->GetMean()-3*h1_singleEleEnergyDistributionCalib_ch[2]->GetRMS(),h1_singleEleEnergyDistributionCalib_ch[2]->GetMean()+3*h1_singleEleEnergyDistributionCalib_ch[2]->GetRMS() );
  h1_singleEleEnergyDistributionCalib_ch[2]->Fit(f1_gaus,"R");
  h1_meanCalib->SetBinContent( 3, f1_gaus->GetParameter(1) );
  h1_meanCalib->SetBinError( 3, f1_gaus->GetParError(2) );
  h1_rmsCalib->SetBinContent( 3, f1_gaus->GetParameter(2) );
  h1_rmsCalib->SetBinError( 3, f1_gaus->GetParError(2) );

  f1_gaus->SetRange(h1_singleEleEnergyDistributionCalib_ch[3]->GetMean()-3*h1_singleEleEnergyDistributionCalib_ch[3]->GetRMS(),h1_singleEleEnergyDistributionCalib_ch[3]->GetMean()+3*h1_singleEleEnergyDistributionCalib_ch[3]->GetRMS() );
  h1_singleEleEnergyDistributionCalib_ch[3]->Fit(f1_gaus,"R");
  h1_meanCalib->SetBinContent( 4, f1_gaus->GetParameter(1) );
  h1_meanCalib->SetBinError( 4, f1_gaus->GetParError(1) );
  h1_rmsCalib->SetBinContent( 4, f1_gaus->GetParameter(2) );
  h1_rmsCalib->SetBinError( 4, f1_gaus->GetParError(2) );


  c1->Clear();
  h1_meanCalib->GetYaxis()->SetRangeUser(720.,890.);
  h1_meanCalib->SetXTitle( "Channel Number");
  h1_meanCalib->SetMarkerStyle(20);
  h1_meanCalib->SetMarkerSize(1.6);


  h1_meanCalib->Draw();

  c1->SaveAs("muCalibratedChannels.png");
  c1->SaveAs("muCalibratedChannels.eps");

  c1->Clear();
  h1_rmsCalib->SetXTitle( "Channel Number");
  h1_rmsCalib->SetMarkerStyle(20);
  h1_rmsCalib->SetMarkerSize(1.6);


  h1_rmsCalib->Draw();

  c1->SaveAs("rmsCalibratedChannels.png");
  c1->SaveAs("rmsCalibratedChannels.eps");

  float mean=0.,rms=0.;
  float meanCalib=0.,rmscalib=0.;
  for (int i=1;i<=4;i++){
    mean+=h1_mean->GetBinContent(i);
    meanCalib+=h1_meanCalib->GetBinContent(i);
  }
  mean=mean/4.;
  meanCalib=meanCalib/4.;

  for (int i=1;i<=4;i++){
    rms+= (h1_mean->GetBinContent(i)-mean)*(h1_mean->GetBinContent(i)-mean);
    rmscalib+= (h1_meanCalib->GetBinContent(i)-meanCalib)*(h1_meanCalib->GetBinContent(i)-meanCalib);
  }
  rms=sqrt(rms/4);
  rmscalib=sqrt(rmscalib/4);
  std::cout<<"rms: "<<rms<<" rms_calib: "<<rmscalib<<std::endl;

  outfile->Write();
  outfile->Close();

  return 0;

    
}
Example #29
0
void ttbarEventLooper(const std::string& inputFileList, const std::string& sampleName)
{
  using namespace ttbar;

  TrackTagrate_1_2 tagRatePredictor("UserCode/TagratePredictions_mgregoire/Ptagged_track_photon_66bin_1_30GeV.txt");

  TChain* chain = new TChain("tree");

  ifstream in(inputFileList.c_str());
  while(!in.eof())
  {
    std::string fileName;
    getline(in, fileName);
    if(fileName == "")
      continue;
    std::cout << "Adding " << fileName << " to TChain." << std::endl;
    chain->AddFile(fileName.c_str());
  }

  std::cout << "Getting Event Info" << std::endl;
  chain->SetBranchAddress("eventInfo", &eventInfo_.runNumber_);

  std::cout << "Getting Trigger Info" << std::endl;
  chain->SetBranchStatus("tTResult", 0);
  chain->SetBranchStatus("tTPreScale", 0);
  chain->SetBranchStatus("tTName", 0);

  chain->SetBranchAddress("hltResult", hltResult_);
  chain->SetBranchStatus("hltPreScale", 0);
  chain->SetBranchAddress("hltName", &hltName_);

  std::cout << "Getting Primary Vertex Info" << std::endl;
  chain->SetBranchAddress("pvInfo", &pvInfo_.pvIsFake_);

  std::cout << "Getting Muon Info" << std::endl;
  chain->SetBranchAddress("nMuons", &nMuons_);
  chain->SetBranchAddress("isGlobalMuon", isGlobalMuon_);
  chain->SetBranchAddress("isTrackerMuon", isTrackerMuon_);
  chain->SetBranchAddress("ptMu", ptMu_);
  chain->SetBranchAddress("etaMu", etaMu_);
  chain->SetBranchAddress("phiMu", phiMu_);
  chain->SetBranchAddress("nHitsMu", nHitsMu_);
  chain->SetBranchAddress("d0Mu", d0Mu_);
  chain->SetBranchAddress("d0ErrMu", d0ErrMu_);
  chain->SetBranchAddress("nChi2Mu", nChi2Mu_);
  chain->SetBranchAddress("nMuonHitsMu", nMuonHitsMu_);
  chain->SetBranchAddress("relIso", relIso_);
  chain->SetBranchAddress("deltaPVMu", deltaPVMu_);
  chain->SetBranchAddress("nPixelHitsMu", nPixelHitsMu_);
  chain->SetBranchAddress("nMatchesMu", nMatchesMu_);

  std::cout << "Getting Jet info" << std::endl;
  chain->SetBranchAddress("nJets", &nJets_);
  chain->SetBranchAddress("isCaloJet", isCaloJet_);
  chain->SetBranchAddress("isJPT", isJPT_);
  chain->SetBranchAddress("isPFJet", isPFJet_);
  chain->SetBranchAddress("ptJet", ptJet_);
  chain->SetBranchAddress("etaJet", etaJet_);
  chain->SetBranchAddress("phiJet", phiJet_);
  chain->SetBranchAddress("emFracJet", emFracJet_);
  chain->SetBranchAddress("n90HitsJet", n90HitsJet_);
  chain->SetBranchAddress("fHPDJet", fHPDJet_);
  chain->SetBranchAddress("nConstituentsJet", nConstituentsJet_);
  chain->SetBranchAddress("chargedEMFracJet", chargedEMFracJet_);
  chain->SetBranchAddress("chargedHadFracJet", chargedHadFracJet_);
  chain->SetBranchAddress("neutralEMFracJet", neutralEMFracJet_);
  chain->SetBranchAddress("neutralHadFracJet", neutralHadFracJet_);
  chain->SetBranchAddress("chargedMultiplicityJet", chargedMultiplicityJet_);
  chain->SetBranchAddress("rrMomentJet", rrMomentJet_);

  chain->SetBranchStatus("*BJetTags*", 0);
  
  chain->SetBranchAddress("nTracks", nTracks_);
  chain->SetBranchAddress("trackPt", trackPt_);
  chain->SetBranchAddress("trackEta", trackEta_);
  chain->SetBranchAddress("trackPhi", trackPhi_);
  chain->SetBranchAddress("trackNChi2", trackNChi2_);
  chain->SetBranchAddress("trackNHits", trackNHits_);
  chain->SetBranchAddress("trackNPixelHits", trackNPixelHits_);
  chain->SetBranchAddress("trackD0", trackD0_);
  chain->SetBranchAddress("deltaPVTrack", deltaPVTrack_);

  chain->SetBranchStatus("n90Jet", 0);
  chain->SetBranchStatus("flavorJet", 0);

  chain->SetBranchAddress("nMusInJet", nMusInJet_);
  chain->SetBranchAddress("ptMuJet", ptMuJet_);
  chain->SetBranchAddress("etaMuJet", etaMuJet_);
  chain->SetBranchAddress("phiMuJet", phiMuJet_);
  chain->SetBranchAddress("nChi2MuJet", nChi2MuJet_);
  chain->SetBranchAddress("nHitsMuJet", nHitsMuJet_);
  chain->SetBranchAddress("nPixelHitsMuJet", nPixelHitsMuJet_);
  chain->SetBranchAddress("d0MuJet", d0MuJet_);
  chain->SetBranchAddress("deltaPVMuJet", deltaPVMuJet_);

  chain->SetBranchStatus("*Elec*", 0);
  chain->SetBranchStatus("*Conv*", 0);

  std::cout << "Getting Electron Info" << std::endl;
  chain->SetBranchStatus("nElectrons", 1);
  chain->SetBranchAddress("nElectrons", &nElectrons_);
  chain->SetBranchStatus("eTElectron", 1);
  chain->SetBranchAddress("eTElectron", eTElectron_);
  chain->SetBranchStatus("etaElectron", 1);
  chain->SetBranchAddress("etaElectron", etaElectron_);
  chain->SetBranchStatus("phiElectron", 1);
  chain->SetBranchAddress("phiElectron", phiElectron_);
  chain->SetBranchStatus("relIsoElectron",1);
  chain->SetBranchAddress("relIsoElectron", relIsoElectron_);

  std::cout << "Getting MET info" << std::endl;
  chain->SetBranchAddress("metInfo", &metInfo_.met_);

  std::cout << "Opening output file" << std::endl;
  std::string fileName = "outputFile_" + sampleName + ".root";
  TFile* file = new TFile(fileName.c_str(), "RECREATE");
  TH2F* relIso_Vs_d0 = new TH2F("relIso_Vs_d0", "Primary Muon relIso vs. d_{0}", 100, 0.0, 0.25, 100, 0.0, 5.0);
  TH2F* relIso_Vs_d0_noDeltaR = new TH2F("relIso_Vs_d0_noDeltaR", "Primary Muon relIso vs. d_{0} w/o Jet #Delta R Cut", 100, 0.0, 0.25, 100, 0.0, 5.0);
  TH2F* relIso_Vs_d0_tagRatePred = new TH2F("relIso_Vs_d0_tagRatePred", "Primary Muon relIso vs. d_{0}", 100, 0.0, 0.25, 100, 0.0, 5.0);
  TH2F* relIso_Vs_d0_noDeltaR_tagRatePred = new TH2F("relIso_Vs_d0_noDeltaR_tagRatePred", "Primary Muon relIso vs. d_{0} w/o Jet #Delta R Cut", 100, 0.0, 0.25, 100, 0.0, 5.0);
  TH2F* relIso_Vs_d0_tagRatePredLowError = new TH2F("relIso_Vs_d0_tagRatePredLowError", "Primary Muon relIso vs. d_{0}", 100, 0.0, 0.25, 100, 0.0, 5.0);
  TH2F* relIso_Vs_d0_noDeltaR_tagRatePredLowError = new TH2F("relIso_Vs_d0_noDeltaR_tagRatePredLowError", "Primary Muon relIso vs. d_{0} w/o Jet #Delta R Cut", 100, 0.0, 0.25, 100, 0.0, 5.0);
  TH2F* relIso_Vs_d0_tagRatePredHighError = new TH2F("relIso_Vs_d0_tagRatePredHighError", "Primary Muon relIso vs. d_{0}", 100, 0.0, 0.25, 100, 0.0, 5.0);
  TH2F* relIso_Vs_d0_noDeltaR_tagRatePredHighError = new TH2F("relIso_Vs_d0_noDeltaR_tagRatePredHighError", "Primary Muon relIso vs. d_{0} w/o Jet #Delta R Cut", 100, 0.0, 0.25, 100, 0.0, 5.0);
  TH2F* relIso_Vs_d0_tagRateObs = new TH2F("relIso_Vs_d0_tagRateObs", "Primary Muon relIso vs. d_{0}", 100, 0.0, 0.25, 100, 0.0, 5.0);
  TH2F* relIso_Vs_d0_noDeltaR_tagRateObs = new TH2F("relIso_Vs_d0_noDeltaR_tagRateObs", "Primary Muon relIso vs. d_{0} w/o Jet #Delta R Cut", 100, 0.0, 0.25, 100, 0.0, 5.0);

  unsigned int passedStep1  = 0;
  unsigned int passedStep2  = 0;
  unsigned int passedStep3  = 0;
  unsigned int passedStep4  = 0;
  unsigned int passedStep5  = 0;
  unsigned int passedStep6c = 0;

  const unsigned int nEntries = chain->GetEntries();
  std::cout << "Processing " << nEntries << " Events." << std::endl;
  for(unsigned int i = 0; i != nEntries; ++i)
  {
    chain->GetEntry(i);

    const std::string muTrigger = eventInfo_.runNumber_ < 147196 ? "HLT_Mu9" : "HLT_Mu15_v1";
    const std::vector<std::string>::const_iterator iter = std::find(hltName_->begin(), hltName_->end(), muTrigger);
    bool goodTrigger = iter != hltName_->end() && hltResult_[iter - hltName_->begin()];
 
    bool goodPV = pvInfo_.pvIsFake_ == 0 && pvInfo_.pvNDOF_ > 4 && fabs(pvInfo_.pvZ_) < 24 && pvInfo_.pvRho_ < 2.0;

    std::vector<std::pair<double, double> > jetInfos;
    std::vector<std::pair<double, std::pair<double, double> > > tagRateInfos;
    for(unsigned int j = 0; j != nJets_; ++j)
    {
      if(ptJet_[j] > 30.0 && fabs(etaJet_[j]) < 2.4 && emFracJet_[j] > 0.01 && n90HitsJet_[j] > 1 && fHPDJet_[j] < 0.98)
      {
        jetInfos.push_back(std::make_pair(etaJet_[j], phiJet_[j]));
        for(unsigned int k = 0; k != nTracks_[j]; ++k)
        {
          double dRTrack = deltaR(trackEta_[j][k], etaJet_[j], trackPhi_[j][k], phiJet_[j]);
          if(trackPt_[j][k] > 4.0 && fabs(trackEta_[j][k]) < 2.4 && dRTrack < 0.4 && trackNHits_[j][k] > 10 && fabs(trackD0_[j][k]) < 0.2 && fabs(deltaPVTrack_[j][k]) < 1.0 )
          {
            double trackProb = trackPt_[j][k] > 20.0 ? 0.007 : tagRatePredictor.tagrate(trackPt_[j][k], trackEta_[j][k]);
            double trackProbLowError = trackPt_[j][k] > 20.0 ? 0.0007 : tagRatePredictor.tagrateErrorLow(trackPt_[j][k], trackEta_[j][k]);
            double trackProbHighError = trackPt_[j][k] > 20.0 ? 0.0007 : tagRatePredictor.tagrateErrorHigh(trackPt_[j][k], trackEta_[j][k]);
            tagRateInfos.push_back(std::make_pair(trackProb, std::make_pair(trackProbLowError, trackProbHighError)));
          }
        }
      }
    }
    double eventProb = 1.0 - calcTotalTrackProb(tagRateInfos);
    std::pair<double, double> eventErrors = calcTotalErrors(tagRateInfos);

    unsigned int nTightMuons = 0;
    unsigned int nLooseMuons = 0;
    std::vector<std::pair<double, double> > muInfos;
    std::vector<std::pair<double, double> > muInfosEtaPhi;
    std::vector<std::pair<double, double> > muInfosNoDeltaR;
    std::vector<std::pair<double, double> > tightMuInfos;
    for(unsigned int j = 0; j != nMuons_; ++j)
    {
      bool isTightABCD_NoDeltaR = isGlobalMuon_[j]          &&
                                  isTrackerMuon_[j]         &&
                                  ptMu_[j] > 20.0           &&
                                  fabs(etaMu_[j]) < 2.1     &&
                                  nChi2Mu_[j] < 10.0        &&
                                  nMuonHitsMu_[j] > 0       &&
                                  nHitsMu_[j] > 10          &&
                                  fabs(deltaPVMu_[j]) < 1.0 &&
                                  nPixelHitsMu_[j] > 0      &&
                                  nMatchesMu_[j] > 1;
      if(isTightABCD_NoDeltaR)
        muInfosNoDeltaR.push_back(std::make_pair(fabs(d0Mu_[j]), relIso_[j]));

      bool isTightABCD = isTightABCD_NoDeltaR && minDeltaR(etaMu_[j], phiMu_[j], jetInfos) > 0.3;
      if(isTightABCD)
      {
        muInfos.push_back(std::make_pair(fabs(d0Mu_[j]), relIso_[j]));
        muInfosEtaPhi.push_back(std::make_pair(etaMu_[j], phiMu_[j]));
      }

      bool isTight = isTightABCD && relIso_[j] < 0.05 && fabs(d0Mu_[j]) < 0.02;
      if(isTight)
        tightMuInfos.push_back(std::make_pair(etaMu_[j], phiMu_[j]));

      bool isLoose = isGlobalMuon_[j]      &&
                     ptMu_[j] > 10.0       &&
                     fabs(etaMu_[j]) < 2.5 &&
                     relIso_[j] < 0.2;
      if(isTight)
        ++nTightMuons;
      else if(isLoose)
        ++nLooseMuons;
    }

    unsigned int nTags = 0;
    for(unsigned int j = 0; j != nJets_; ++j)
    {
      if(ptJet_[j] > 30.0 && fabs(etaJet_[j]) < 2.4 && emFracJet_[j] > 0.01 && n90HitsJet_[j] > 1 && fHPDJet_[j] < 0.98)
      {
        for(unsigned int l = 0; muInfosEtaPhi.size() == 1 && l != nMusInJet_[j]; ++l)
        {
          double dRMu = deltaR(etaMuJet_[j][l], muInfosEtaPhi.front().first, phiMuJet_[j][l], muInfosEtaPhi.front().second);
          if(ptMuJet_[j][l] > 4.0 && fabs(d0MuJet_[j][l]) < 0.2 && nHitsMuJet_[j][l] > 10 && fabs(deltaPVMuJet_[j][l]) < 1.0 && dRMu > 1e-3)
          {
            ++nTags;
          }
        }
      }
    }

    unsigned int nLooseElectrons = 0;
    for(unsigned int j = 0; j != nElectrons_; ++j)
    {
      if(eTElectron_[j] > 15.0 && fabs(etaElectron_[j]) < 2.5 && relIsoElectron_[j] < 0.2)
        ++nLooseElectrons;
    }

    if(goodTrigger)
    {
      ++passedStep1;
      if(goodPV)
      {
        ++passedStep2;
        if(nTightMuons == 1)
        {
          ++passedStep3;
          if(nLooseMuons == 0)
          {
            ++passedStep4;
            if(nLooseElectrons == 0)
            {
              ++passedStep5;
              if(jetInfos.size() >2)
              {
                ++passedStep6c;
              }
            }
          }
        }
      }
    }

    if(goodTrigger && goodPV && muInfosNoDeltaR.size() == 1 && ((nTightMuons == 1 && nLooseMuons == 0) || (nTightMuons == 0 && nLooseMuons == 1) || (nTightMuons == 0 && nLooseMuons == 0)) && nLooseElectrons == 0 && jetInfos.size() > 2)
    {
      relIso_Vs_d0_noDeltaR->Fill(muInfosNoDeltaR.front().first, muInfosNoDeltaR.front().second);
      relIso_Vs_d0_noDeltaR_tagRatePred->Fill(muInfosNoDeltaR.front().first, muInfosNoDeltaR.front().second, eventProb);
      relIso_Vs_d0_noDeltaR_tagRatePredLowError->Fill(muInfosNoDeltaR.front().first, muInfosNoDeltaR.front().second, eventErrors.first);
      relIso_Vs_d0_noDeltaR_tagRatePredHighError->Fill(muInfosNoDeltaR.front().first, muInfosNoDeltaR.front().second, eventErrors.second);
      if(nTags > 0) relIso_Vs_d0_noDeltaR_tagRateObs->Fill(muInfosNoDeltaR.front().first, muInfosNoDeltaR.front().second);
    }

    if(goodTrigger && goodPV && muInfos.size() == 1 && ((nTightMuons == 1 && nLooseMuons == 0) || (nTightMuons == 0 && nLooseMuons == 1) || (nTightMuons == 0 && nLooseMuons == 0)) && nLooseElectrons == 0 && jetInfos.size() > 2)
    {
      relIso_Vs_d0->Fill(muInfos.front().first, muInfos.front().second);
      relIso_Vs_d0_tagRatePred->Fill(muInfos.front().first, muInfos.front().second, eventProb);
      relIso_Vs_d0_tagRatePredLowError->Fill(muInfos.front().first, muInfos.front().second, eventErrors.first);
      relIso_Vs_d0_tagRatePredHighError->Fill(muInfos.front().first, muInfos.front().second, eventErrors.second);
      if(nTags > 0) relIso_Vs_d0_tagRateObs->Fill(muInfos.front().first, muInfos.front().second);    
    }
  }

  std::cout << passedStep1 << " events passed Cut 1." << std::endl;
  std::cout << passedStep2 << " events passed Cut 2." << std::endl;
  std::cout << passedStep3 << " events passed Cut 3." << std::endl;
  std::cout << passedStep4 << " events passed Cut 4." << std::endl;
  std::cout << passedStep5 << " events passed Cut 5." << std::endl;
  std::cout << passedStep6c << " events passed Cut 6." << std::endl;

  file->Write();
  file->Close();
  delete file;
}
Example #30
0
int writentuple_pbpb(char *ksp="pbpbJet80")
{

  timer.Start();

  LoadLib();

  TString inname="root://eoscms//eos/cms/store/group/phys_heavyions/yjlee/PbPb2011/HITracking2011/HiForest-promptskim-hiForest2_v21_HLTFix.root";

  //! Load Lib
  //gSystem->Load("/afs/cern.ch/user/p/pawan/scratch0/CMSSW_6_2_0/src/work/pPb/HiForest/V3/hiForest_h.so");

  //! Define the input file and HiForest
  //! CMSSW_5_3_3
  HiForest *c = new HiForest(inname,Form("Forest%s",ksp),cPP);
  cout<<"Loaded the hiforest tree : "<<c->GetName()<<endl;
  ShutoffBranches(c);

  DuplicateEvents dupEvt(inname);
  dupEvt.MakeList();



  //! Output file
  //! HIHighPt
  TFile *fout = new TFile(Form("ntuple_2011_%s.root",ksp),"RECREATE");  

  std::cout<<"\t"<<std::endl;
  std::cout<<"\t"<<std::endl;
  std::cout<<"**************************************************** "<<std::endl;
  std::cout<<Form("Running for %s ",ksp)<<std::endl;
  std::cout<<Form("pT  cut for %0.3f ",kptrecocut)<<std::endl;
  std::cout<<Form("eta cut for %0.3f ",ketacut)<<std::endl;
  std::cout<<"My hiForest Tree : " <<c->GetName()<<"\t Entries "<<c->GetEntries()<<std::endl;
  std::cout<<"Output file  "<<fout->GetName()<<std::endl;
  std::cout<<"**************************************************** "<<std::endl;
  std::cout<<"\t"<<std::endl;
  std::cout<<"\t"<<std::endl;

  //! shut off jet trees
  c->hasAk2CaloJetTree=0;
  c->hasAk4CaloJetTree=0;
  c->hasAk3CaloJetTree=0;
  c->hasAk5CaloJetTree=0;

  c->hasAkPu2CaloJetTree=0;
  c->hasAkPu4CaloJetTree=0;
  c->hasAkPu3CaloJetTree=0;
  c->hasAkPu5CaloJetTree=0;

  c->hasAk2PFJetTree=0;
  c->hasAk4PFJetTree=0;
  c->hasAk5PFJetTree=0;

  c->hasAkPu2PFJetTree=0;
  c->hasAkPu4PFJetTree=0;
  c->hasAkPu5PFJetTree=0;

  c->hasTrackTree=0;

  //! For jets
  Jets *mJets=0;
  Long64_t nentries = c->GetEntries();
  std::cout<<Form("# of entries in TTree for %s : ",ksp)<<nentries<<std::endl;

  string jetVars = "";
  jetVars += "evt:run:bin:vz:trig:jet55:jet65:jet80:ntrk:pt1:raw1:eta1:phi1:chMax1:chSum1:phSum1:neSum1:pt2:raw2:eta2:phi2:chMax2:chSum2:phSum2:neSum2:pt3:raw3:eta3:phi3:chMax3:chSum3:phSum3:neSum3";
  TNtuple *ntjet=0;
  ntjet = new TNtuple("ntjet","",jetVars.data());

  for (Long64_t ievt=0; ievt<nentries;ievt++) {//! event loop
    //for (Long64_t ievt=0; ievt<100;ievt++) {//! event loop
    //! load the hiForest event
    c->GetEntry(ievt);

    if(dupEvt.occurence[ievt] == 2)continue;
    
    //! events with Single vertex
    bool evSel = false;
    float trig=-9;
    // if(strcmp(ksp,"pbpbJet55")==0){
    //   evSel = fabs(c->evt.vz)<15. && c->skim.pHBHENoiseFilter  && c->skim.pcollisionEventSelection && c->hlt.HLT_HIJet55_v1; 
    //   trig=1;
    // }
    // else if(strcmp(ksp,"pbpbJet65")==0){
    //   evSel = fabs(c->evt.vz)<15. && c->skim.pHBHENoiseFilter && c->skim.pcollisionEventSelection && c->hlt.HLT_HIJet65_v1; 
    //   trig=2;
    // }
    // else if(strcmp(ksp,"pbpbJet80")==0){
    //   evSel = fabs(c->evt.vz)<15. && c->skim.pHBHENoiseFilter && c->skim.pcollisionEventSelection && c->hlt.HLT_HIJet80_v1; 
    //   trig=3;
    // }


    evSel = fabs(c->evt.vz)<15. && c->skim.pHBHENoiseFilter  && c->skim.pcollisionEventSelection && (c->hlt.HLT_HIJet55_v1 || c->hlt.HLT_HIJet65_v1 || c->hlt.HLT_HIJet80_v1); 
    if(!evSel)continue;

    float pt1 = -9, pt2    = -9, pt3    = -9,
      raw1    = -9, raw2   = -9, raw3   = -9,
      eta1    = -9, eta2   = -9, eta3   = -9,
      phi1    = -9, phi2   = -9, phi3   = -9,
      chMax1  = -9, chMax2 = -9, chMax3 = -9,
      chSum1  = -9, chSum2 = -9, chSum3 = -9,
      phSum1  = -9, phSum2 = -9, phSum3 = -9,
      neSum1  = -9, neSum2 = -9, neSum3 = -9;

    
    float run   = c->evt.run;
    float evt   = c->evt.evt;
    float vz    = c->evt.vz;
    
    float jet55  = c->hlt.HLT_HIJet55_v1;
    float jet65  = c->hlt.HLT_HIJet65_v1;
    float jet80  = c->hlt.HLT_HIJet80_v1;
    
    float ntrk    = c->evt.hiNtracks;

    float bin = c->evt.hiBin;

    if(ievt%10000==0)std::cout<<" ********** Event # " <<ievt<<"\t Run : "<<run<<std::endl;
    //std::cout<<" ********** Event # " <<ievt<<"\t Run : "<<run<<std::endl;    
    mJets = &(c->akPu3PF);
    
    int *ljet = new int[3];
    FindLeadSubLeadJets(mJets,ljet);
    
    int jtLead = -1, jtSubLead = -1, jtThird = -1;
    
    if(ljet[0] >=0 ) jtLead    = ljet[0];
    if(ljet[1] >=0 ) jtSubLead = ljet[1];    
    if(ljet[2] >=0 ) jtThird   = ljet[2];    
    
    if(jtLead<0)continue;
    
    if(jtLead > -1){
      pt1     = mJets->jtpt[jtLead];
      eta1    = mJets->jteta[jtLead];
      phi1    = mJets->jtphi[jtLead];
      raw1    = mJets->rawpt[jtLead];
      //chMax1  = mJets->chargedMax[jtLead];
      chMax1  = mJets->trackMax[jtLead];
      chSum1  = mJets->chargedSum[jtLead];
      phSum1  = mJets->photonSum[jtLead];
      neSum1  = mJets->neutralSum[jtLead];
    }
    
    if(jtSubLead > -1){
      pt2     = mJets->jtpt[jtSubLead];
      eta2    = mJets->jteta[jtSubLead];
      phi2    = mJets->jtphi[jtSubLead];
      raw2    = mJets->rawpt[jtSubLead];
      //chMax2  = mJets->chargedMax[jtSubLead];
      chMax2  = mJets->trackMax[jtSubLead];
      chSum2  = mJets->chargedSum[jtSubLead];
      phSum2  = mJets->photonSum [jtSubLead];
      neSum2  = mJets->neutralSum[jtSubLead];
    }
    
    if(jtThird > -1){
      pt3     = mJets->jtpt[jtThird];
      eta3    = mJets->jteta[jtThird];
      phi3    = mJets->jtphi[jtThird];
      raw3    = mJets->rawpt[jtThird];
      //chMax3  = mJets->chargedMax[jtThird];
      chMax3  = mJets->trackMax[jtThird];
      chSum3  = mJets->chargedSum[jtThird];
      phSum3  = mJets->photonSum [jtThird];
      neSum3  = mJets->neutralSum[jtThird];
    }
    
    float jentry[] = {evt,run,vz,bin,trig,jet55,jet65,jet80,ntrk,
		       pt1,raw1,eta1,phi1,chMax1,chSum1,phSum1,neSum1,
		       pt2,raw2,eta2,phi2,chMax2,chSum2,phSum2,neSum2,
		       pt3,raw3,eta3,phi3,chMax3,chSum3,phSum3,neSum3
    };
    
    ntjet->Fill(jentry);
    delete [] ljet;
  }//! event loop ends


  //! Write to output file
  fout->cd();
  fout->Write();
  fout->Close();

  //! Check
  timer.Stop();
  float rtime  = timer.RealTime();
  float ctime  = timer.CpuTime();

  std::cout<<"\t"<<std::endl;
  std::cout<<Form("RealTime=%f seconds, CpuTime=%f seconds",rtime,ctime)<<std::endl;
  std::cout<<"\t"<<std::endl;
  std::cout<<"Good bye : " <<"\t"<<std::endl;

  return 0;
}