void splitStopSamples(){

  char* path = "/tas/cms2/stop/MiniBabies/V00-02-s18b20__V00-03-01__BDT007__4jetsMET100MT150_all";

  //-------------------------------------
  // declare input file, tree, etc.
  //-------------------------------------

  //char* infilename = Form("%s/T2tt_*.root" , path);
  //char* infilename = Form("%s/T2bw_*75.root" , path);
  //char* infilename = Form("%s/T2bw_*50.root" , path);
  char* infilename = Form("%s/T2bw_*25.root" , path);
  long long max_tree_size = 20000000000000000LL;
  TTree::SetMaxTreeSize(max_tree_size);

  TChain *chain = new TChain("t");
  chain->Add(infilename);

  //-------------------------------------
  // which grid points to skim?
  //-------------------------------------
  
  vector<string> filenames;
  vector<int> mg;
  vector<int> ml;

  // mg.push_back(350);   ml.push_back(100);
  // mg.push_back(450);   ml.push_back(100);
  // mg.push_back(250);   ml.push_back(75);
  // mg.push_back(250);   ml.push_back(100);
  // mg.push_back(400);   ml.push_back(150);
  // mg.push_back(500);   ml.push_back(100);
  // mg.push_back(600);   ml.push_back(0);
  // mg.push_back(550);   ml.push_back(0);
  // mg.push_back(650);   ml.push_back(50);
  // mg.push_back(750);   ml.push_back(100);
  // mg.push_back(500);   ml.push_back(100);
  // mg.push_back(600);   ml.push_back(200);
  // mg.push_back(650);   ml.push_back(250);
  // mg.push_back(75000);   ml.push_back(100);
  // mg.push_back(350);   ml.push_back(50);
  // mg.push_back(450);   ml.push_back(50);
  // mg.push_back(500);   ml.push_back(50);
  // mg.push_back(400);   ml.push_back(50);

  // T2bw 75 R1
  // mg.push_back(350);   ml.push_back(125);
  // mg.push_back(350);   ml.push_back(175);
  // mg.push_back(400);   ml.push_back(175);

  // T2bw 75 R2
  // mg.push_back(425);   ml.push_back(75);
  // mg.push_back(450);   ml.push_back(100);
  // mg.push_back(500);   ml.push_back(125);

  // T2bw 75 R3
  // mg.push_back(500);   ml.push_back(0);
  // mg.push_back(550);   ml.push_back(0);
  // mg.push_back(525);   ml.push_back(75);

  // T2bw 75 R4
  // mg.push_back(150);      ml.push_back(0);
  // mg.push_back(200);      ml.push_back(0);
  // mg.push_back(200);      ml.push_back(50);

  // T2bw 50 R1
  // mg.push_back(225);      ml.push_back(0);
  // mg.push_back(275);      ml.push_back(50);
  // mg.push_back(325);      ml.push_back(100);

  // T2bw 50 R2
  // mg.push_back(350);      ml.push_back(0);
  // mg.push_back(375);      ml.push_back(50);
  // mg.push_back(400);      ml.push_back(100);

  // T2bw 50 R3
  // mg.push_back(450);      ml.push_back(0);
  // mg.push_back(500);      ml.push_back(50);
  // mg.push_back(550);      ml.push_back(100);

  // T2bw 25 R2
  // mg.push_back(400);      ml.push_back(0);
  // mg.push_back(500);      ml.push_back(100);
  // mg.push_back(600);      ml.push_back(200);

  // T2bw 25 R3
  mg.push_back(500);      ml.push_back(0);
  mg.push_back(550);      ml.push_back(50);
  mg.push_back(600);      ml.push_back(100);

  // cut-and-count T2tt
  // mg.push_back(600);   ml.push_back(25);
  // mg.push_back(500);   ml.push_back(200);
  // mg.push_back(300);   ml.push_back(100);

  // R4
  // mg.push_back(200);   ml.push_back(100);
  // mg.push_back(300);   ml.push_back(200);
  // mg.push_back(400);   ml.push_back(300);

  // R4
  // mg.push_back(550);   ml.push_back(25);
  // mg.push_back(650);   ml.push_back(50);
  // mg.push_back(750);   ml.push_back(100);

  // R3
  // mg.push_back(500);   ml.push_back(100);
  // mg.push_back(600);   ml.push_back(200);
  // mg.push_back(650);   ml.push_back(250);

  // R2
  // mg.push_back(350);   ml.push_back(75);
  // mg.push_back(400);   ml.push_back(125);
  // mg.push_back(450);   ml.push_back(175);

  // R1
  //mg.push_back(250);   ml.push_back(25);
  //mg.push_back(300);   ml.push_back(25);
  //mg.push_back(300);   ml.push_back(75);

  const unsigned int npoints = mg.size();

  //-------------------------------------
  // skim grid points
  //-------------------------------------

  TFile *file[npoints];
  TTree *tree[npoints];

  TChain* pretest = new TChain("t");
  TChain* posttest = new TChain("t");

  for( unsigned int i = 0 ; i < npoints ; ++i ){

    //char* filename = Form("%s/T2ttPoint_%i_%i.root",path,mg.at(i),ml.at(i));
    //char* filename = Form("%s/T2bw75Point_%i_%i.root",path,mg.at(i),ml.at(i));
    //char* filename = Form("%s/T2bw50Point_%i_%i.root",path,mg.at(i),ml.at(i));
    char* filename = Form("%s/T2bw25Point_%i_%i.root",path,mg.at(i),ml.at(i));

    TCut cut(Form("mg==%i && ml==%i",mg.at(i),ml.at(i)));

    cout << endl;
    cout << "Skimming input file  : " << infilename << endl;
    cout << "Using selection      : " << cut.GetTitle() << endl;
    cout << "Skim filename        : " << filename << endl;


    file[i] = TFile::Open(filename, "RECREATE");
    assert( file[i] != 0 );
    tree[i] = chain->CopyTree( cut );

    tree[i]->Write();
    file[i]->Close();

    pretest->Add(infilename);
    posttest->Add(filename);
    
    cout << "Pre  total           : " << pretest->GetEntries() << endl;
    cout << "Pre  skim            : " << pretest->GetEntries(cut) << endl;
    cout << "Post total           : " << posttest->GetEntries() << endl;
    cout << "Post skim            : " << posttest->GetEntries(cut) << endl;

    pretest->Reset();
    posttest->Reset();


  }

}
void makeBSM_MCFM_single(int folder, int erg_tev){
  //  if (erg_tev==7) return;
  //  char TREE_NAME[] = "SelectedTree";
  char TREE_NAME[] = "GenTree";
  TString INPUT_NAME = "HZZ4l-125_6-";
  int tFitD = 0;
  TString comstring;
  comstring.Form("%iTeV", erg_tev);
  TString erg_dir;
  erg_dir.Form("LHC_%iTeV/", erg_tev);
  INPUT_NAME.Append(comstring);
  INPUT_NAME.Append("-");

  double mPOLE = 125.6;
  Mela mela(erg_tev, mPOLE);

  TString cinput_common = "/scratch0/hep/usarical/WidthSamples/" + erg_dir + "/";
  if (erg_tev!=7) cinput_common = cinput_common + user_folder[folder] + "/";

  int EnergyIndex = 1;
  if (erg_tev == 7) EnergyIndex = 0;

  float templateWeight = 1;
  float MC_weight;
  float ZZMass = 0;
  float Z1Mass = 0;
  float Z2Mass = 0;

  float GenHMass = 0;
  float GenZ1Mass = 0;
  float GenZ2Mass = 0;
  float GenLep1Id, GenLep2Id, GenLep3Id, GenLep4Id;
  float GenLep1Mass, GenLep2Mass, GenLep3Mass, GenLep4Mass;
  float GenLep1Pt, GenLep2Pt, GenLep3Pt, GenLep4Pt;
  float GenLep1Phi, GenLep2Phi, GenLep3Phi, GenLep4Phi;
  float GenLep1Eta, GenLep2Eta, GenLep3Eta, GenLep4Eta;
  float GenLep1E, GenLep2E, GenLep3E, GenLep4E;

  float p0plus_VAJHU;
  float p0hplus_VAJHU;
  float p0minus_VAJHU;
  float p0_g1prime2_VAJHU;
  float p0_g1prime4_VAJHU;

  float pg1g2_VAJHU;
  float pg1g4_VAJHU;
  float pg1g1prime2_VAJHU;
  float pg1g1prime4_VAJHU;

  TString coutput_common = user_TemplateswithTrees_dir + "../BSMReweight_GenLevel/" + erg_dir;
  coutput_common += user_folder[folder] + "/";
  gSystem->Exec("mkdir -p " + coutput_common);

  TString cinput_KDFactor = "./data/HZZ4l-KDFactorGraph";
  if (EnergyIndex == 0) cinput_KDFactor = cinput_KDFactor + "_7TeV";
  cinput_KDFactor = cinput_KDFactor + ".root";
  TFile* finput_KDFactor = new TFile(cinput_KDFactor, "read");
  TString tgkfname = "KDScale_";
  tgkfname = tgkfname + "AllFlavors_UnNormalized";
  TGraphAsymmErrors* tgkf = (TGraphAsymmErrors*)finput_KDFactor->Get(tgkfname);
  TGraph* tg_interf = make_HZZ_LeptonInterferenceGraph();

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


  const int kNumTemplates = 4;
  TString templatenames[kNumTemplates] ={ "ggF Sig", "gg Bkg", "ggF BSI", "ggF BSI25" };

  int nEntries;
  float fitYval = 0;
  MC_weight = 1;
  ZZMass = 0;

  double selfDHvvcoupl[SIZE_HVV][2] ={ { 0 } };
  double ggvvcoupl[2]={ 0, 0 };

  //Template and tree filler
  for (int t = 0; t < kNumTemplates; t++){
    TString OUTPUT_NAME;
    OUTPUT_NAME = "HtoZZ4l_MCFM_125p6_BSMTrees_";
    OUTPUT_NAME += sample_suffix[t] + ".root";
    TString coutput = coutput_common + OUTPUT_NAME;
    TFile* foutput = new TFile(coutput, "recreate");

    foutput->cd();

    TChain* tree = new TChain(TREE_NAME);
    TTree* templateTree = new TTree(TREE_NAME, TREE_NAME);

    float wPOLE=4.15e-3;
    if (t==3) wPOLE*=25;

    TString cinput = cinput_common + sample_suffix[t] + "/" + INPUT_NAME + sample_suffix[t] + ".root";
    tree->Add(cinput);

    templateTree->Branch("MC_weight", &templateWeight);
    templateTree->Branch("ZZMass", &ZZMass);
    templateTree->Branch("Z1Mass", &Z1Mass);
    templateTree->Branch("Z2Mass", &Z2Mass);
    //    templateTree->Branch("GenHMass", &GenHMass);
    templateTree->Branch("p0plus_VAJHU", &p0plus_VAJHU);
    templateTree->Branch("p0hplus_VAJHU", &p0hplus_VAJHU);
    templateTree->Branch("p0minus_VAJHU", &p0minus_VAJHU);
    templateTree->Branch("p0_g1prime2_VAJHU", &p0_g1prime2_VAJHU);
    templateTree->Branch("p0_g1prime4_VAJHU", &p0_g1prime4_VAJHU);
    templateTree->Branch("pg1g2_VAJHU", &pg1g2_VAJHU);
    templateTree->Branch("pg1g4_VAJHU", &pg1g4_VAJHU);
    templateTree->Branch("pg1g1prime2_VAJHU", &pg1g1prime2_VAJHU);
    templateTree->Branch("pg1g1prime4_VAJHU", &pg1g1prime4_VAJHU);

    //Making templates using appropriate weights
    //    tree->SetBranchAddress("ZZMass", &ZZMass);
    //    tree->SetBranchAddress("MC_weight", &MC_weight);
    tree->SetBranchAddress("GenZZMass", &GenHMass);
    tree->SetBranchAddress("GenLep1Id", &GenLep1Id);
    tree->SetBranchAddress("GenLep2Id", &GenLep2Id);
    tree->SetBranchAddress("GenLep3Id", &GenLep3Id);
    tree->SetBranchAddress("GenLep4Id", &GenLep4Id);
    tree->SetBranchAddress("GenLep1Pt", &GenLep1Pt);
    tree->SetBranchAddress("GenLep2Pt", &GenLep2Pt);
    tree->SetBranchAddress("GenLep3Pt", &GenLep3Pt);
    tree->SetBranchAddress("GenLep4Pt", &GenLep4Pt);
    tree->SetBranchAddress("GenLep1Phi", &GenLep1Phi);
    tree->SetBranchAddress("GenLep2Phi", &GenLep2Phi);
    tree->SetBranchAddress("GenLep3Phi", &GenLep3Phi);
    tree->SetBranchAddress("GenLep4Phi", &GenLep4Phi);
    tree->SetBranchAddress("GenLep1Eta", &GenLep1Eta);
    tree->SetBranchAddress("GenLep2Eta", &GenLep2Eta);
    tree->SetBranchAddress("GenLep3Eta", &GenLep3Eta);
    tree->SetBranchAddress("GenLep4Eta", &GenLep4Eta);
    tree->SetBranchAddress("GenLep1E", &GenLep1E);
    tree->SetBranchAddress("GenLep2E", &GenLep2E);
    tree->SetBranchAddress("GenLep3E", &GenLep3E);
    tree->SetBranchAddress("GenLep4E", &GenLep4E);

    if (tFitD != 0){
      if (tree->GetBranchStatus(strFitDim[tFitD])){
        tree->SetBranchAddress("Dgg10_VAMCFM", &fitYval);
        templateTree->Branch(strFitDim[tFitD], &fitYval);
      }
      else{
        cerr << "Could NOT find branch named " << strFitDim[tFitD] << "!!! Setting strFitDim[" << tFitD << "] = 0." << endl;
        fitYval = 0;
      }
    }

    nEntries = tree->GetEntries();
    double xsec = 1./nEntries;
    if (t==0) xsec *= xsec_ggHZZ_MCFM[EnergyIndex];
    else if (t==1) xsec *= xsec_ggZZ_MCFM[EnergyIndex];
    else if (t==2) xsec *= xsec_ggHZZ_BSI_MCFM[EnergyIndex];
    else if (t==3) xsec *= xsec_ggHZZ_BSI25_MCFM[EnergyIndex];
    else xsec = 1;
    if (folder<2) xsec *= 0.25;
    else xsec *= 0.5;

    //    for (int ev = 0; ev < 100; ev++){

    for (int ev = 0; ev < nEntries; ev++){
      tree->GetEntry(ev);
      ZZMass = GenHMass;
      MC_weight = xsec;

      if (fitYval != fitYval) continue;
      // Protect against any KD exceeding boundaries
      if (tFitD!=0 && fitYval>=1){
        cout << "Found fitYval == " << fitYval;
        fitYval = 0.999;
        cout << ". Fixed to " << fitYval << endl;
      }
      if (tFitD!=0 && fitYval<0) fitYval = 0;

      if (t < 4 && erg_tev==7){
        if (folder==1){
          GenLep1Id=11;
          GenLep2Id=-11;
          GenLep3Id=11;
          GenLep4Id=-11;
        }
        else if (folder==0){
          GenLep1Id=13;
          GenLep2Id=-13;
          GenLep3Id=13;
          GenLep4Id=-13;
        }
      }

      double weight = MC_weight;
      if (t < 4) weight *= tgkf->Eval(GenHMass);
      if (t < 4
        && abs(GenLep1Id)==abs(GenLep2Id)
        && abs(GenLep1Id)==abs(GenLep3Id)
        && abs(GenLep1Id)==abs(GenLep4Id)
        ) weight *= tg_interf->Eval(GenHMass);
      templateWeight = weight;

      float mzz = mPOLE;
      float m1 = 0;
      float m2 = 0;
      float h1 = 0;
      float h2 = 0;
      float phi = 0;
      float hs = 0;
      float phi1 = 0;

      GenLep1Mass = findLeptonMass(GenLep1Id);
      GenLep2Mass = findLeptonMass(GenLep2Id);
      GenLep3Mass = findLeptonMass(GenLep3Id);
      GenLep4Mass = findLeptonMass(GenLep4Id);

      TLorentzVector p1, p2, p3, p4;
      p1.SetPtEtaPhiE(GenLep1Pt, GenLep1Eta, GenLep1Phi, GenLep1E);
      p2.SetPtEtaPhiE(GenLep2Pt, GenLep2Eta, GenLep2Phi, GenLep2E);
      p3.SetPtEtaPhiE(GenLep3Pt, GenLep3Eta, GenLep3Phi, GenLep3E);
      p4.SetPtEtaPhiE(GenLep4Pt, GenLep4Eta, GenLep4Phi, GenLep4E);
      TLorentzVector pZ1 = p1+p2;
      TLorentzVector pZ2 = p3+p4;
      TLorentzVector pZ1p = p1+p4;
      TLorentzVector pZ2p = p3+p2;
      TLorentzVector pZZ = pZ1+pZ2;
      mzz=pZZ.M();
      m1=pZ1.M();
      m2=pZ2.M();
      Z1Mass = m1;
      Z2Mass=m2;
      if (Z1Mass>=120 || Z1Mass<=40) continue;
      if (Z2Mass>=120 || Z2Mass<=12) continue;
      if (!passAcceptance(GenLep1Pt, GenLep1Eta, (int)GenLep1Id)) continue;
      if (!passAcceptance(GenLep2Pt, GenLep2Eta, (int)GenLep2Id)) continue;
      if (!passAcceptance(GenLep3Pt, GenLep3Eta, (int)GenLep3Id)) continue;
      if (!passAcceptance(GenLep4Pt, GenLep4Eta, (int)GenLep4Id)) continue;
      if (pZ1.M()<=4 ||pZ2.M()<=4 ||pZ1p.M()<=4 ||pZ2p.M()<=4) continue;
      TLorentzVector pp[4] ={ p1, p2, p3, p4 };
      int pass20=-1;
      int pass10=-1;
      for (int vv=0; vv<4; vv++){
        if (pp[vv].Pt()>20){
          pass20=vv; break;
        }
      }
      for (int vv=0; vv<4; vv++){
        if (vv==pass20) continue;
        if (pp[vv].Pt()>10){
          pass10=vv; break;
        }
      }
      if (pass20<0 || pass10<0) continue;

      mela::computeAngles(p1, GenLep1Id,
        p2, GenLep2Id,
        p3, GenLep3Id,
        p4, GenLep4Id,
        hs,
        h1,
        h2,
        phi,
        phi1);
      int lepIdOrdered[4] ={ (int)GenLep1Id, (int)GenLep2Id, (int)GenLep3Id, (int)GenLep4Id };
      float angularOrdered[8] ={ mzz, m1, m2, hs, h1, h2, phi, phi1 };

      if (t==0) mela.setProcess(TVar::HSMHiggs, TVar::MCFM, TVar::ZZGG);
      if (t==2 || t==3) mela.setProcess(TVar::bkgZZ_SMHiggs, TVar::MCFM, TVar::ZZGG);
      if (t!=1){
        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[0][0]=1;
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        p0plus_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[1][0]=1.638;
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        p0hplus_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[3][0]=2.521;
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        p0minus_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[11][0]=-12046.01;
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        p0_g1prime2_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[13][0]=-pow(10000.0/mPOLE, 2);
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        p0_g1prime4_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);


        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[0][0]=1;
        selfDHvvcoupl[1][0]=1.638;
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        pg1g2_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[0][0]=1;
        selfDHvvcoupl[3][0]=2.521;
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        pg1g4_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[0][0]=1;
        selfDHvvcoupl[11][0]=-12046.01;
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        pg1g1prime2_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        for (int ii = 0; ii < SIZE_HVV; ii++){ for (int jj = 0; jj < 2; jj++) selfDHvvcoupl[ii][jj] = 0; }
        selfDHvvcoupl[0][0]=1;
        selfDHvvcoupl[13][0]=-pow(10000.0/mPOLE, 2);
        mela.setMelaLeptonInterference(TVar::InterfOn);
        mela.setMelaHiggsWidth(wPOLE);
        pg1g1prime4_VAJHU = getJHUGenMELAWeight(mela, lepIdOrdered, angularOrdered, selfDHvvcoupl);

        if (p0plus_VAJHU!=0){
          p0hplus_VAJHU/=p0plus_VAJHU;
          p0minus_VAJHU/=p0plus_VAJHU;
          p0_g1prime2_VAJHU/=p0plus_VAJHU;
          p0_g1prime4_VAJHU/=p0plus_VAJHU;

          pg1g2_VAJHU/=p0plus_VAJHU;
          pg1g4_VAJHU/=p0plus_VAJHU;
          pg1g1prime2_VAJHU/=p0plus_VAJHU;
          pg1g1prime4_VAJHU/=p0plus_VAJHU;
          p0plus_VAJHU=1;
        }
        else{
          p0plus_VAJHU=0;
          p0hplus_VAJHU=0;
          p0minus_VAJHU=0;
          p0_g1prime2_VAJHU=0;
          p0_g1prime4_VAJHU=0;

          pg1g2_VAJHU=0;
          pg1g4_VAJHU=0;
          pg1g1prime2_VAJHU=0;
          pg1g1prime4_VAJHU=0;
        }
      }
      else{
        p0plus_VAJHU=1;
        p0hplus_VAJHU=1;
        p0minus_VAJHU=1;
        p0_g1prime2_VAJHU=1;
        p0_g1prime4_VAJHU=1;

        pg1g2_VAJHU=1;
        pg1g4_VAJHU=1;
        pg1g1prime2_VAJHU=1;
        pg1g1prime4_VAJHU=1;
      }

      p0plus_VAJHU*=templateWeight;
      p0hplus_VAJHU*=templateWeight;
      p0minus_VAJHU*=templateWeight;
      p0_g1prime2_VAJHU*=templateWeight;
      p0_g1prime4_VAJHU*=templateWeight;

      pg1g2_VAJHU*=templateWeight;
      pg1g4_VAJHU*=templateWeight;
      pg1g1prime2_VAJHU*=templateWeight;
      pg1g1prime4_VAJHU*=templateWeight;

      templateTree->Fill();
    }

    foutput->WriteTObject(templateTree);
    delete tree;
    delete templateTree;
    foutput->Close();
  }

  delete tg_interf;
  delete tgkf;
  finput_KDFactor->Close();
}
Beispiel #3
0
void makeTable(int nbins = 40, const string label = "HFhits", const char * tag = "Preliminary_NoEffCor_AMPT_d1107", const char* dataset = "DATA"){

  bool DATA = false;
  bool SIM = true;
  bool MC = false;
  double EFF = 1;
  double MXS = 1. - EFF;

   // Retrieving data
  int maxEvents = -200;
  vector<int> runnums;
  
  //  const char* infileName = Form("/net/hisrv0001/home/yetkin/hidsk0001/analysis/prod/%s_RECO_391/test.root",dataset);
  const char* infileName = Form("/net/hisrv0001/home/yetkin/hidsk0001/centrality/prod/%s/test.root",dataset);

  //  TFile* infile = new TFile(infileName,"read");
  TChain* t = new TChain("HltTree");
  //  TChain* t = new TChain("hltanalysis/HltTree");

  t->Add(infileName);

  // Creating output table
  TFile* outFile = new TFile("tables_d1108.root","update");
   TDirectory* dir = outFile->mkdir(tag);
   dir->cd();
   TNtuple* nt = new TNtuple("nt","","hf:bin:b:npart:ncoll:nhard");
   CentralityBins* bins = new CentralityBins("noname","Test tag", nbins);
   bins->table_.reserve(nbins);

  TH1D::SetDefaultSumw2();

  int runMC = 1;
  TFile * inputMCfile;
  CentralityBins* inputMCtable;
  
  if(DATA){
    inputMCfile = new TFile("tables_d1103.root","read");
    inputMCtable = (CentralityBins*)inputMCfile->Get("CentralityTable_HFhits40_AMPT2760GeV_v1_mc_MC_38Y_V12/run1");
  }

  // Setting up variables & branches
  double binboundaries[nbinsMax+1];
  vector<float> values;

  float b,npart,ncoll,nhard,hf,hfhit,eb,ee,etmr,parameter;
  int npix,ntrks;
  //  TTree* t = (TTree*)infile->Get("HltTree");
  int run;

  if(SIM){
    t->SetBranchAddress("b",&b);
    t->SetBranchAddress("Npart",&npart);
    t->SetBranchAddress("Ncoll",&ncoll);
    t->SetBranchAddress("Nhard",&nhard);
  }

  t->SetBranchAddress("hiHFhit",&hfhit);
  t->SetBranchAddress("hiHF",&hf);
  t->SetBranchAddress("hiEB",&eb);
  t->SetBranchAddress("hiEE",&ee);
  t->SetBranchAddress("hiET",&etmr);
  t->SetBranchAddress("hiNpix",&npix);
  t->SetBranchAddress("hiNtracks",&ntrks);
  t->SetBranchAddress("Run",&run);

  bool binNpart = label.compare("Npart") == 0;
  bool binNcoll = label.compare("Ncoll") == 0;
  bool binNhard = label.compare("Nhard") == 0;
  bool binB = label.compare("b") == 0;
  bool binHF = label.compare("HFtowers") == 0;
  bool binHFhit = label.compare("HFhits") == 0;
  bool binEB = label.compare("EB") == 0;
  bool binEE = label.compare("EE") == 0;
  bool binETMR = label.compare("ETMR") == 0;
  bool binNpix = label.compare("PixelHits") == 0;
  bool binNtrks = label.compare("Ntracks") == 0;

  // Determining bins of cross section
  // loop over events
  unsigned int events=t->GetEntries();
  for(unsigned int iev = 0; iev < events && (maxEvents < 0 || iev< maxEvents); ++iev){
    if( iev % 100 == 0 ) cout<<"Processing event : "<<iev<<endl;
    t->GetEntry(iev);

    if(binNpart) parameter = npart;
    if(binNcoll) parameter = ncoll;
    if(binNhard) parameter = nhard;
    if(binB) parameter = b;
    if(binHF) parameter = hf;
    if(binHFhit) parameter = hfhit;
    if(binEB) parameter = eb;
    if(binEE) parameter = ee;
    if(binETMR) parameter = etmr;
    if(binNpix) parameter = npix;
    if(binNtrks) parameter = ntrks;
 
    values.push_back(parameter);
    if(runnums.size() == 0 || runnums[runnums.size()-1] != run) runnums.push_back(run);
  }
  
  if(label.compare("b") == 0) sort(values.begin(),values.end(),descend);
  else sort(values.begin(),values.end());

  double max = values[events-1];
  binboundaries[nbins] = max;

  cout<<"-------------------------------------"<<endl;
  cout<<label.data()<<" based cuts are : "<<endl;
  cout<<"(";

  int bin = 0;
  double dev = events;
  for(int i = 0; i< nbins; ++i){
     // Find the boundary 
    int entry = (int)(i*(dev/nbins));
    binboundaries[i] = values[entry];

     cout<<" "<<binboundaries[i];
     if(i < nbins - 1) cout<<",";
     else cout<<")"<<endl;
  }

  cout<<"-------------------------------------"<<endl;

  if(!DATA){

  // Determining Glauber results in various bins
  dir->cd();
  TH2D* hNpart = new TH2D("hNpart","",nbins,binboundaries,500,0,500);
  TH2D* hNcoll = new TH2D("hNcoll","",nbins,binboundaries,2000,0,2000);
  TH2D* hNhard = new TH2D("hNhard","",nbins,binboundaries,250,0,250);
  TH2D* hb = new TH2D("hb","",nbins,binboundaries,300,0,30);

  for(unsigned int iev = 0; iev < events && (maxEvents < 0 || iev< maxEvents); ++iev){
     if( iev % 100 == 0 ) cout<<"Processing event : "<<iev<<endl;
     t->GetEntry(iev);
     if(binNpart) parameter = npart;
     if(binNcoll) parameter = ncoll;
     if(binNhard) parameter = nhard;
     if(binB) parameter = b;
     if(binHF) parameter = hf;
     if(binHFhit) parameter = hfhit;
     if(binEB) parameter = eb;
     if(binEE) parameter = ee;
     if(binETMR) parameter = etmr;
     if(binNpix) parameter = npix;
     if(binNtrks) parameter = ntrks;
    
     hNpart->Fill(parameter,npart);
     hNcoll->Fill(parameter,ncoll);
     hNhard->Fill(parameter,nhard);
     hb->Fill(parameter,b);
     int bin = hNpart->GetXaxis()->FindBin(parameter) - 1;
     if(bin < 0) bin = 0;
     if(bin >= nbins) bin = nbins - 1;
     nt->Fill(hf,bin,b,npart,ncoll,nhard);
  }

  // Fitting Glauber distributions in bins to get mean and sigma values

  dir->cd();
  TF1* fGaus = new TF1("fb","gaus(0)",0,2); 
  fGaus->SetParameter(0,1);
  fGaus->SetParameter(1,0.04);
  fGaus->SetParameter(2,0.02); 
  
  fitSlices(hNpart,fGaus);
  fitSlices(hNcoll,fGaus);
  fitSlices(hNhard,fGaus);
  fitSlices(hb,fGaus);

  TH1D* hNpartMean = (TH1D*)gDirectory->Get("hNpart_1");
  TH1D* hNpartSigma = (TH1D*)gDirectory->Get("hNpart_2");
  TH1D* hNcollMean = (TH1D*)gDirectory->Get("hNcoll_1");
  TH1D* hNcollSigma = (TH1D*)gDirectory->Get("hNcoll_2");
  TH1D* hNhardMean = (TH1D*)gDirectory->Get("hNhard_1");
  TH1D* hNhardSigma = (TH1D*)gDirectory->Get("hNhard_2");
  TH1D* hbMean = (TH1D*)gDirectory->Get("hb_1");
  TH1D* hbSigma = (TH1D*)gDirectory->Get("hb_2");

  cout<<"-------------------------------------"<<endl;
  cout<<"# Bin NpartMean NpartSigma NcollMean NcollSigma bMean bSigma BinEdge"<<endl;

  // Enter values in table
  for(int i = 0; i < nbins; ++i){
     int ii = nbins-i;
     bins->table_[i].n_part_mean = hNpartMean->GetBinContent(ii);
     bins->table_[i].n_part_var = hNpartSigma->GetBinContent(ii);
     bins->table_[i].n_coll_mean = hNcollMean->GetBinContent(ii);
     bins->table_[i].n_coll_var = hNcollSigma->GetBinContent(ii);
     bins->table_[i].b_mean = hbMean->GetBinContent(ii);
     bins->table_[i].b_var = hbSigma->GetBinContent(ii);
     bins->table_[i].n_hard_mean = hNhardMean->GetBinContent(ii);
     bins->table_[i].n_hard_var = hNhardSigma->GetBinContent(ii);
     bins->table_[i].bin_edge = binboundaries[ii-1];

     cout<<i<<" "
	 <<hNpartMean->GetBinContent(ii)<<" "
	 <<hNpartSigma->GetBinContent(ii)<<" "
	 <<hNcollMean->GetBinContent(ii)<<" "
	 <<hNcollSigma->GetBinContent(ii)<<" "
	 <<hbMean->GetBinContent(ii)<<" "
	 <<hbSigma->GetBinContent(ii)<<" "
	 <<binboundaries[ii]<<" "
	 <<endl;
  }
  cout<<"-------------------------------------"<<endl;

  // Save the table in output file
  if(onlySaveTable){

     hNpart->Delete();
     hNpartMean->Delete();
     hNpartSigma->Delete();
     hNcoll->Delete();
     hNcollMean->Delete();
     hNcollSigma->Delete();
     hNhard->Delete();
     hNhardMean->Delete();
     hNhardSigma->Delete();
     hb->Delete();
     hbMean->Delete();
     hbSigma->Delete();
  }
 
  }else{
    cout<<"-------------------------------------"<<endl;
    cout<<"# Bin NpartMean NpartSigma NcollMean NcollSigma bMean bSigma BinEdge"<<endl;

    // Enter values in table
    for(int i = 0; i < nbins; ++i){
      int ii = nbins-i;
      bins->table_[i].n_part_mean = inputMCtable->NpartMeanOfBin(i);
      bins->table_[i].n_part_var = inputMCtable->NpartSigmaOfBin(i);
      bins->table_[i].n_coll_mean = inputMCtable->NcollMeanOfBin(i);
      bins->table_[i].n_coll_var = inputMCtable->NcollSigmaOfBin(i);
      bins->table_[i].b_mean = inputMCtable->bMeanOfBin(i);
      bins->table_[i].b_var = inputMCtable->bSigmaOfBin(i);
      bins->table_[i].n_hard_mean = inputMCtable->NhardMeanOfBin(i);
      bins->table_[i].n_hard_var = inputMCtable->NhardSigmaOfBin(i);
      bins->table_[i].bin_edge = binboundaries[ii-1];

      cout<<i<<" "
	  <<bins->table_[i].n_part_mean<<" "
          <<bins->table_[i].n_part_var<<" "
          <<bins->table_[i].n_coll_mean<<" "
          <<bins->table_[i].n_coll_var<<" "
          <<bins->table_[i].b_mean<<" "
          <<bins->table_[i].b_var<<" "
          <<bins->table_[i].n_hard_mean<<" "
          <<bins->table_[i].n_hard_var<<" "
          <<bins->table_[i].bin_edge<<" "<<endl;

    }
    cout<<"-------------------------------------"<<endl;

  }


  outFile->cd(); 
  dir->cd();

  bins->SetName(Form("run%d",1));
  bins->Write();
  nt->Write();  
  bins->Delete();
  outFile->Write();
  
}
void mergeDATA(TString Tree="/afs/cern.ch/work/s/shuai/public/diboson/trees/productionv7_newMJ/fullallrange")
{

	TFile * outputfile = new TFile(Tree+"/treeEDBR_data_xww.root","RECREATE");

	TString treename;
	treename = "SelectedCandidates";

	TChain * chain_SingleEle = new TChain(treename);
	TChain * chain_SingleMu = new TChain(treename);
/*
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012A_13Jul2012_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012A_recover_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012B_13Jul2012_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012C_24Aug2012_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012C_EcalRecove_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012C_PromptReco_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012D_PromptReco_xww.root");

	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012A_13Jul2012_xww.root");
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012A_recover_xww.root");
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012B_13Jul2012_xww.root");
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012C_24Aug2012_xww.root");
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012C_EcalRecove_xww.root");	
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012C_PromptReco_xww.root");	
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012D_PromptReco_xww.root");
*/

	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012A-22Jan2013_xww.root");
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012B-22Jan2013_xww.root");
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012C-22Jan2013_xww.root");
	chain_SingleMu->Add(Tree+"/"+"treeEDBR_SingleMu_Run2012D-22Jan2013_xww.root");	

	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012A-22Jan2013_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012B-22Jan2013_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012C-22Jan2013_xww.root");
	chain_SingleEle->Add(Tree+"/"+"treeEDBR_SingleElectron_Run2012D-22Jan2013_xww.root");



	TChain * chain = new TChain(treename);
	chain->Add(chain_SingleEle);
	int nele = chain->GetEntries();
	chain->Add(chain_SingleMu);
	int ntotal = chain->GetEntries();
	int nmu  = ntotal - nele;
	cout<<"ele entries: "<<nele<<endl;
	cout<<"mu entries: "<<nmu<<endl;
	cout<<"ele+mu entries: "<<ntotal<<endl;

	TTree * outTree = chain->CloneTree(0);

	double lep[99];
	int nLooseEle;
	int nLooseMu;
	chain->SetBranchAddress("lep", lep);
	chain->SetBranchAddress("nLooseMu", &nLooseMu);
	chain->SetBranchAddress("nLooseEle",&nLooseEle);

	//fill only lep==0 for SingEle
	for(int i=0; i<nele; i++)
	{
		chain->GetEntry(i);
		if(nLooseEle+nLooseMu!=1)continue;
		if(lep[0]==0)outTree->Fill();
	}
	//fill only lep==1 for SingMu
	
	for(int i=nele; i<ntotal; i++)
	{
		chain->GetEntry(i);
		if(nLooseEle+nLooseMu!=1)continue;
		if(lep[0]==1)outTree->Fill();
	}
	

	cout<<"output entries:  "<<outTree->GetEntries()<<endl;

	outputfile->cd();
	outTree->Write();
	outputfile->Close();

}
Beispiel #5
0
void InConeLeadFrag_AJ(
    //TString algo="akpu3pf"
    TString algo="icpu5"
    )
{
  TH1::SetDefaultSumw2();
  TString infnamedata = Form("histntff_tv1data_%s_cv3.root",algo.Data());
  TString infnamemc = Form("histntff_tv1mc80_%s_cv3.root",algo.Data());
  TCut evtSel;
  if (algo=="akpu3pf")
    evtSel = "cent<20&&jtpt[0]>90&&jtpt[1]>40&&abs(jteta[0])<1.6&&abs(jteta[1])<1.6&&abs(jdphi)>2.09";
  if (algo=="icpu5")
    evtSel = "cent<20&&jtpt[0]>120&&jtpt[1]>50&&abs(jteta[0])<1.6&&abs(jteta[1])<1.6&&abs(jdphi)>2.09";

  TChain * tdata = new TChain("tjfrRec");
  tdata->Add(infnamedata);
  TChain * tmc = new TChain("tjfrRec");
  tmc->Add(infnamemc);

  cout << "Cut: " << TString(evtSel) << endl;
  cout << infnamedata << " " << tdata->GetEntries(evtSel) << endl;
  cout << infnamemc << " " << tmc->GetEntries(evtSel) << endl;

  TProfile * hLFJ1Data = new TProfile("hLFJ1Data","",5,0,0.5);
  TProfile * hLFJ1Mc = new TProfile("hLFJ1Mc","",5,0,0.5);
  TProfile * hLFJ2Data = new TProfile("hLFJ2Data","",5,0,0.5);
  TProfile * hLFJ2Mc = new TProfile("hLFJ2Mc","",5,0,0.5);

  cout << "========== LF ana ==========" << endl;
  TCut jet1Sel = evtSel&&"clppt[0]>0";
  TCut jet2Sel = evtSel&&"clppt[1]>0";
  cout << "Cut: " << TString(jet1Sel) << endl;
  cout << infnamedata << " " << tdata->GetEntries(jet1Sel) << endl;
  cout << infnamemc << " " << tmc->GetEntries(jet1Sel) << endl;
  cout << "Cut: " << TString(jet2Sel) << endl;
  cout << infnamedata << " " << tdata->GetEntries(jet2Sel) << endl;
  cout << infnamemc << " " << tmc->GetEntries(jet2Sel) << endl;

  tdata->Project("hLFJ1Data","clppt[0]/jtpt[0]:Aj",jet1Sel*"cltrkwt","prof");
  tmc->Project("hLFJ1Mc","clppt[0]/jtpt[0]:Aj",jet1Sel*"cltrkwt","prof");
  tdata->Project("hLFJ2Data","clppt[1]/jtpt[1]:Aj",jet2Sel*"cltrkwt","prof");
  tmc->Project("hLFJ2Mc","clppt[1]/jtpt[1]:Aj",jet2Sel*"cltrkwt","prof");

  TCanvas * c2 = new TCanvas("c2","c2",500,500);
  hLFJ1Mc->SetAxisRange(0,0.3,"Y");
  hLFJ1Mc->SetTitle(";A_{J};<z^{lead}>=<p_{T}^{Leading Trk}/p_{T}^{Jet}>;");
  hLFJ1Mc->GetXaxis()->CenterTitle();
  hLFJ1Mc->GetYaxis()->CenterTitle();
  hLFJ1Mc->SetLineColor(kRed);
  hLFJ1Mc->SetLineStyle(2);

  hLFJ2Mc->SetLineColor(kRed);

  hLFJ1Data->SetMarkerStyle(kOpenCircle);

  hLFJ1Mc->Draw("hist");
  hLFJ2Mc->Draw("samehist");
  hLFJ1Data->Draw("sameE");
  hLFJ2Data->Draw("sameE");

  TLegend *leg = new TLegend(0.18,0.18,0.68,0.38);
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);
  leg->SetTextSize(0.035);
  leg->AddEntry(hLFJ1Data,"0-20%, "+algo,"");
  leg->AddEntry(hLFJ1Data,"Data J1","p");
  leg->AddEntry(hLFJ2Data,"Data J2","p");
  leg->AddEntry(hLFJ1Mc,"PYTHIA+HYDJET J1","l");
  leg->AddEntry(hLFJ2Mc,"PYTHIA+HYDJET J2","l");
  leg->Draw();

  c2->Print(Form("InConeLeadingFragment_vs_AJ_%s.gif",algo.Data()));
}
void run_TSelector_SusyNtuple_excess_n0150_Egamma_L() {

//  TString options = TString(""); //TString(tag.c_str()) ;
// //     TString outputfile = "test.root";
//     string richtigerString = InputPath;
// //     int Position = richtigerString.find("mc12_8TeV.");
// //     outputfile = "histos_ZTauTau_" +  richtigerString.substr(Position+10,6)  + "_proof.root";
//     
//     int Position = -1;
//     Position = richtigerString.find("45_bg");
//     if (Position>0){
//       outputfile = "histos_test_" +  richtigerString.substr(Position+6,2)  + ".root";
//     }
//     else{
//       Position = richtigerString.find("45_signal");
//       if (Position>0){
//       outputfile = "histos_test_" +  richtigerString.substr(Position+3,2)  + ".root";
//       }
//     }
//     if(outputfile == ""){
//       cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
//       cout << "EMPTY OUPTPUTFILE STRING" << endl;
//       cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
//       abort();
//     }
//     cout << "outputfile= " << outputfile << endl;
    
      cout<<"Have you set up RootCore via  \"source RootCore/scripts/setup.sh\" ?"<<endl;  

      gSystem->Setenv("ROOTCOREDIR", "/data/etp3/jwittkow/analysis_SUSYTools_03_04_SusyNt_01_16/RootCore");
      gSystem->SetIncludePath("-I$ROOTCOREDIR/include/");

      gROOT->ProcessLine(".x $ROOTCOREDIR/scripts/load_packages.C+"); 

      TString selectorName = "TSelector_SusyNtuple_excess"; // !!! enter the name of your Selector (without _C.so)

      TChain *ch;
      
      ch = new TChain("susyNt");

      TString processLine = ".L " + selectorName + ".cpp++g";
      TString execLine;

      gROOT->ProcessLine(processLine); // need to add this, or PoD at LRZ will not be able to load the .so
      gROOT->ProcessLine(".x $ROOTCOREDIR/scripts/load_packages.C+");
//       ch->Add(InputPath);
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0150/WH/user.gerbaudo.mc12_8TeV.177501.Herwigpp_sM_wA_noslep_notauhad_WH_2Lep_1.SusyNt.e2149_s1581_s1586_r3658_r3549_p1512_n0150.140109072637/*");
  ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0150/Egamma/user.gerbaudo.group.phys-susy.data12_8TeV.periodL.physics_Egamma.PhysCont.SusyNt.t0pro14_v01_p1542_n0150.131226172851/*");
  ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0150/Egamma/user.gerbaudo.group.phys-susy.data12_8TeV.periodL.physics_Egamma.PhysCont.SusyNt.t0pro14_v01_p1542_n0150.131226172939/*");
  ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0150/Egamma/user.gerbaudo.group.phys-susy.data12_8TeV.periodL.physics_Egamma.PhysCont.SusyNt.t0pro14_v01_p1542_n0150.131226173027/*");
  ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0150/Egamma/user.gerbaudo.group.phys-susy.data12_8TeV.periodL.physics_Egamma.PhysCont.SusyNt.t0pro14_v01_p1542_n0150.131226173125/*");
  ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0150/Egamma/user.gerbaudo.group.phys-susy.data12_8TeV.periodL.physics_Egamma.PhysCont.SusyNt.t0pro14_v01_p1542_n0150.131226212707/*");

  
  

  
     

	    


      Long64_t nEntries = ch->GetEntries();
      ch->ls();

      cout << "all entries: " << nEntries << endl;


      TSelector_SusyNtuple_excess* SusyNtupleObject = new TSelector_SusyNtuple_excess();
      SusyNtupleObject->buildSumwMap(ch);
//       TString options="NtSys_NOM";
      ch->Process(SusyNtupleObject);
      delete SusyNtupleObject;
      
      if (ch) {delete ch; ch=0;}

  abort();
  }
void builtVetoCal(string Input = ""){

	int mode = 1;		// switch: 0 for local files, 1 for pdsf files
	UInt_t card1 = 13;	// 11: prototype, 13: module 1
	UInt_t card2 = 18;
	Bool_t useThresh = true; // if true, also enables fitting LED peaks

	// "low" qdc threshold values
	//Int_t thresh[numPanels] = {123,115,95,93,152,115,105,103,119,91,108,103,94,107,95,167,
	//	53,150,89,120,65,85,132,62,130,101,80,108,145,164,119,82};

	// "high" qdc threshold values
	Int_t thresh[numPanels] = {124,117,96,93,155,115,112,105,120,91,109,108,95,112,96,168,
		63,157,100,127,72,100,140,65,145,125,82,112,151,168,122,94};

	// Input a list of run numbers
	Char_t InputName[200];
	string def = "builtVeto_DebugList"; // default
	if (Input == "") strcpy(InputName,def.c_str());
	else strcpy(InputName,Input.c_str());
	Char_t InputFile[200];
	sprintf(InputFile,"%s.txt",InputName);
	ifstream InputList;
	InputList.open(InputFile);
	Char_t TheFile[200];

	// Set up output file(s)
	Char_t OutputFile[200];
	sprintf(OutputFile,"./output/%s.root",InputName);
	TFile *RootFile = new TFile(OutputFile, "RECREATE");	
  	TH1::AddDirectory(kFALSE); // Global flag: "When a (root) file is closed, all histograms in memory associated with this file are automatically deleted."

	ofstream calib;
	Char_t CalibFile[200];
	sprintf(CalibFile,"./output/%s_CalibrationTable.txt",InputName);
	calib.open(CalibFile);


	//=== Global counters / variables / plots ===

		Int_t run = 0;
		Float_t duration = 0;
		Float_t durationTotal = 0;
		
		// get number of files in dataset for the TGraph
		Int_t filesToScan = 0;
		Int_t filesScanned = 0;
	  	while(!InputList.eof()) { InputList >> run; filesToScan++; }
	  	cout << "Scanning " << filesToScan << " files." << endl;	  	
	  	InputList.close();
	  	InputList.open(InputFile);
	  	run=0;
	 	TGraph *SCorruption = new TGraph(filesToScan);
	 	Int_t BadTSTotal = 0;

	 	TH1D *TotalCorruptionInTime = new TH1D("TotalCorruptionInTime","corrupted entries during run (entry method)",(Int_t)3600/5,0,3600);
	 	TotalCorruptionInTime->GetXaxis()->SetTitle("time (5 sec / bin)");
	 	Bool_t PlotCorruptedEntries = false; // flag for plotting corrupted entries in time for EACH RUN

	 	TH1D *TotalMultiplicity = new TH1D("TotalMultiplicity","Events over threshold",32,0,32);
	 	TotalMultiplicity->GetXaxis()->SetTitle("number of panels hit");
	 	Bool_t PlotMultiplicity = false;	// flag to plot multiplicity for EACH RUN

	 	const Int_t nqdc_bins=1400;  // this gives 3 qdc / bin
		const Float_t ll_qdc=0.;
		const Float_t ul_qdc=4200.;
		Char_t hname[50];
		for (Int_t i=0; i<numPanels; i++){
			sprintf(hname,"hRawQDC%d",i);
			hRawQDC[i] = new TH1F(hname,hname,nqdc_bins,ll_qdc,ul_qdc);
			sprintf(hname,"hCutQDC%d",i);
			hCutQDC[i] = new TH1F(hname,hname,nqdc_bins,ll_qdc,ul_qdc);
			sprintf(hname,"hThreshQDC%d",i);
			hThreshQDC[i] = new TH1F(hname,hname,500,ll_qdc,500);
			sprintf(hname,"hLEDCutQDC%d",i);
			hLEDCutQDC[i] = new TH1F(hname,hname,500,ll_qdc,500);
		}

		Long64_t CountsBelowThresh[numPanels] = {0};
		Long64_t TotalCounts[numPanels] = {0};		

		
	//=== End ===



	// Loop over files
	while(!InputList.eof()){

		// initialize 
		InputList >> run;
		if (mode==0) sprintf(TheFile,"~/dev/datasets/muFinder/OR_run%i.root",run);
		else if (mode==1) sprintf(TheFile,"/global/project/projectdirs/majorana/data/mjd/surfmjd/data/built/P3JDY/OR_run%u.root",run); 
		TChain *VetoTree = new TChain("VetoTree");
		VetoTree->AddFile(TheFile);
		TChain *MGTree = new TChain("MGTree");
		MGTree->AddFile(TheFile);
		MJTRun *MyRun = new MJTRun();
		MGTree->SetBranchAddress("run",&MyRun);
		Long64_t nentries = VetoTree->GetEntries();
		MGTBasicEvent *b = new MGTBasicEvent; 
		//MGTBasicEvent b;
		VetoTree->SetBranchAddress("vetoEvent",&b);
		const int vd_size = 16;	
		MJTVetoData *vd[vd_size];
		VetoTree->GetEntry(0);
		for (int i=0; i<vd_size; i++) { vd[i] = dynamic_cast<MJTVetoData*>(b->GetDetectorData()->At(i)); }
        MGTree->GetEntry(0);
        duration = MyRun->GetStopTime() - MyRun->GetStartTime();
        if (duration < 0) {
        	printf("\nRun %i has duration %.0f, skipping file!\n\n",run,duration);
        	continue;
        }
        durationTotal += duration;

    	//=== Single-file counters / variables / plots

			QEvent qdc;
			QEvent prevqdc;
				prevqdc.EventCount=-1;
			VEvent veto;
			Bool_t EventMatch = false;

			Int_t BadTSInFile = 0;
			Float_t corruption = 0;
			Int_t numPanelsHit = 0;

			// only write these if their bools are set = true
			TH1D *CorruptionInTime = new TH1D("CorruptionInTime","corrupted entries during run (entry method)",(Int_t)duration/5,0,(Int_t)duration);
			CorruptionInTime->GetXaxis()->SetTitle("time (5 sec / bin)");
			TH1D *OneRunMultiplicity = new TH1D("multiplicity","multiplicity of veto entries",32,0,32);
			OneRunMultiplicity->GetXaxis()->SetTitle("number of panels hit");
		
		//=== End ===

		// Loop over VetoTree entries
		printf("Now scanning run %i: %lli entries, %.2f sec.  \n",run,nentries,duration);
		for (int i = 0; i < nentries; i++) {
			VetoTree->GetEntry(i);

			// move data into QEvent structure
			qdc.runNumber=run;
			qdc.crate=vd[0]->GetCrate();
			qdc.card=vd[0]->GetCard();
			qdc.EventCount=vd[0]->GetEventCount();
			int k = 0;
			for (int j = 0; j<16; j++)	{
				k = vd[j]->GetChannel();
				qdc.QDC[k]=vd[j]->GetAmplitude();
				qdc.IsUnderThreshold[k]=vd[j]->IsUnderThreshold();
				qdc.IsOverflow[k]=vd[j]->IsOverflow();
			}
			
			// check qdc data after moving into QEvent structure
			//printf("QDC -- run: %i  Entry: %i  crate: %i  card: %i  EventCount: %i \n",qdc.runNumber,i,qdc.crate,qdc.card,qdc.EventCount);
			//cout << "QDC: "; for (int k = 0; k<16; ++k) { cout << qdc.QDC[k] << "  "; } cout << endl;
			//cout << "UTh: "; for (int k = 0; k<16; ++k) { cout << qdc.IsUnderThreshold[k] << "  "; } cout << endl;
			//cout << "Ovr: "; for (int k = 0; k<16; ++k) { cout << qdc.IsOverflow[k] << "  "; } cout << endl;	
			
			// check entry numbers
			//printf("Entry: %i  card: %i  EventCount: %i",i,qdc.card,qdc.EventCount);
			//printf("  ||  ScalerCount: %i  TimeStamp: %.5f  IsBadTs: %i \n",
			//	vd[0]->GetScalerCount(),vd[0]->GetTimeStamp()/1E8,vd[0]->IsBadTS());
			
			// set flag if current qdc entry has same EventCount as previous one.
			EventMatch = false;
			if (qdc.EventCount == prevqdc.EventCount) { 
				EventMatch = true; 
				//printf("EventMatch true.  qdc.EventCount:%i  prevqdc.EventCount:%i \n",qdc.EventCount,prevqdc.EventCount);
			}
			else if (abs(qdc.EventCount - prevqdc.EventCount) > 1 && i > 2) {
				printf(" EventCount mismatch! Run:%i current:%i previous:%i card:%i prev.card:%i  Breaking at %.0f%% through file.\n",run,i,qdc.card,prevqdc.card,((Float_t)i/nentries)*100);
				break;
			}

			
			
			if (EventMatch) {
				
				// move matching events into VEvent structure and incorporate scaler info.
				veto.run = qdc.runNumber;
				veto.vEnt = qdc.EventCount;
				veto.sEnt = vd[0]->GetScalerCount();
				veto.sTime = vd[0]->GetTimeStamp()/1E8;
				veto.sTimeBad = vd[0]->IsBadTS();
				veto.eTime = ((Float_t)i/nentries)*duration;	
				// case 1
				if (prevqdc.card==card1 && qdc.card==card2) {
					veto.card[0]=vd[0]->GetScalerID();
					veto.card[1]=prevqdc.card;
					veto.card[2]=qdc.card;
					for (int k = 0; k<16; k++) {
						veto.QDC[k]=prevqdc.QDC[k];
						veto.QDC[16+k]=qdc.QDC[k];
						veto.IsUnderThreshold[k]=prevqdc.IsUnderThreshold[k];
						veto.IsUnderThreshold[16+k]=qdc.IsUnderThreshold[k];
						veto.IsOverflow[k]=prevqdc.IsOverflow[k];
						veto.IsOverflow[16+k]=qdc.IsOverflow[k];
					}
				}
				// case 2
				else if (prevqdc.card==card2 && qdc.card==card1) {
					veto.card[0]=vd[0]->GetScalerID();
					veto.card[1]=qdc.card;
					veto.card[2]=prevqdc.card;
					for (int k = 0; k<16; k++) {
						veto.QDC[k]=qdc.QDC[k];
						veto.QDC[16+k]=prevqdc.QDC[k];
						veto.IsUnderThreshold[k]=qdc.IsUnderThreshold[k];
						veto.IsUnderThreshold[16+k]=prevqdc.IsUnderThreshold[k];
						veto.IsOverflow[k]=qdc.IsOverflow[k];
						veto.IsOverflow[16+k]=prevqdc.IsOverflow[k];
					}
				}
				else if ((int)prevqdc.card==-1) { cout << "Previous Card was 0, EventMatch: " << EventMatch << endl;  continue; }
				else { printf("Failed to match!  Run: %i  VetoTree entry: %i  Card:%i  Prev.Card:%i  Breaking at %.0f%% through file.\n",run,i,qdc.card,prevqdc.card,((Float_t)i/nentries)*100); break; }

				// check VEvent data
				//printf("run:%i  vEnt:%i  sEnt:%i  card0:%i  card1:%i  card2:%i  sTime:%.5f  sTimeBad:%i\n",
				//	veto.run,veto.vEnt,veto.sEnt,veto.card[0],veto.card[1],veto.card[2],veto.sTime,veto.sTimeBad);
				//cout << "QDC: "; for (int k = 0; k<numPanels; ++k) { cout << veto.QDC[k] << "  "; } cout << endl;
				//cout << "UTh: "; for (int k = 0; k<numPanels; ++k) { cout << veto.IsUnderThreshold[k] << "  "; } cout << endl;
				//cout << "Ovr: "; for (int k = 0; k<numPanels; ++k) { cout << veto.IsOverflow[k] << "  "; } cout << endl;

				//=====================BEGIN ACTUAL GODDAMMED ANALYSIS=================

				// scaler corruption
				if (veto.sTimeBad) { 
					BadTSInFile++;
					TotalCorruptionInTime->Fill(veto.eTime);
					if (PlotCorruptedEntries) CorruptionInTime->Fill(veto.eTime);
				}

				// loop over panels
				for (int k=0; k<numPanels; k++) {
					
					// test lowered panel-by-panel thresholds
					if (veto.QDC[k]<thresh[k]) CountsBelowThresh[k]++;
					TotalCounts[k]++;

					// plot qdc entries above threshold
					hRawQDC[k]->Fill(veto.QDC[k]);
					if (veto.QDC[k]<500) hThreshQDC[k]->Fill(veto.QDC[k]);
					if (useThresh && veto.QDC[k]>thresh[k]) hCutQDC[k]->Fill(veto.QDC[k]);

					// count multiplicity
					if (useThresh) { if (veto.QDC[k]>thresh[k]) numPanelsHit++; }
					else { if (!veto.IsUnderThreshold[k]) numPanelsHit++; }
				}
		        TotalMultiplicity->Fill(numPanelsHit);			
		        if (PlotMultiplicity) OneRunMultiplicity->Fill(numPanelsHit);


				//=====================END ACTUAL GODDAMMED ANALYSIS===================

			} // end EventMatch condition

			// Save qdc into prevqdc before getting next VetoTree entry.
			prevqdc = qdc;
			EventMatch = false;
			numPanelsHit=0;

		}	// End loop over VetoTree entries.

		// === END OF FILE Output & Plotting ===
		
		corruption = ((Float_t)BadTSInFile/nentries)*100;
		printf(" Corrupted scaler entries: %i of %lli, %.3f %%.\n",BadTSInFile,nentries,corruption);
		if(run>45000000) SCorruption->SetPoint(filesScanned,run-45000000,corruption);
		else SCorruption->SetPoint(filesScanned,run,corruption);

		if (PlotCorruptedEntries) {
			char outfile1[200];	
			sprintf(outfile1,"CorruptionInTime_Run%i",run);
			CorruptionInTime->Write(outfile1,TObject::kOverwrite);
		}
		if (PlotMultiplicity) {
			char outfile2[200];
			sprintf(outfile2,"Multiplicity_Run%i",run);
			OneRunMultiplicity->Write(outfile2,TObject::kOverwrite);
		}

		// ==========================

		delete VetoTree;
		delete MGTree;
		filesScanned++;
	} // End loop over files.

	

	// === END OF SCAN Output & Plotting ===
	printf("Finished loop over files.\n");

	// estimate reduction in data
	if (useThresh) {
		Long64_t total=0, below=0;
		double reduction;
		for (int i=0; i<numPanels; i++) {
			below += CountsBelowThresh[i];
			total += TotalCounts[i];
		}
		reduction = ((double)below/total)*100;
		double rateBefore = (double)total/durationTotal; 
		double rateAfter = (double)(total-below)/durationTotal;
		printf("Counts below thresh make up %.2f%% of total entries scanned, over %.2f seconds.\n",reduction,durationTotal);
		printf("This is %lli of %lli events.  Rate reduction would be from %.2f Hz to %.2f Hz.\n",below,total,rateBefore,rateAfter);
	}

	TCanvas *c1 = new TCanvas("c1", "Bob Ross's Canvas",600,600);
	c1->SetGrid();
	SCorruption->SetMarkerColor(4);
	SCorruption->SetMarkerStyle(21);
	SCorruption->SetMarkerSize(0.5);
	SCorruption->SetTitle("Corruption in scaler card");
	SCorruption->GetXaxis()->SetTitle("Run");
	SCorruption->GetYaxis()->SetTitle("% corrupted events");
	SCorruption->Draw("ALP");	
	SCorruption->Write("ScalerCorruption",TObject::kOverwrite);

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

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

	// QDC Plots & Calibration Table:
	// gaus: A gaussian with 3 parameters: f(x) = p0*exp(-0.5*((x-p1)/p2)^2)).
	TF1 *fits[numPanels];
	TCanvas *vcan0 = new TCanvas("vcan0","cut & fitted veto QDC, panels 1-32",0,0,800,600);
	vcan0->Divide(8,4,0,0);
	TCanvas *vcan1 = new TCanvas("vcan1","veto QDC thresholds, panels 1-32",0,0,800,600);
	vcan1->Divide(8,4,0,0);	
	Char_t buffer[2000];
	printf("\n Calibration Table:\n  Panel / Mean,error / Sigma,error / Chi-square/NDF (~1?) / LED Peak Pos.\n");
	for (Int_t i=0; i<numPanels; i++){
		
		vcan0->cd(i+1);
		TVirtualPad *vpad0 = vcan0->cd(i+1); vpad0->SetLogy();
		hThreshQDC[i]->Write(); // write the low-QDC part of the spectrum separately
		if (useThresh) {
			hCutQDC[i]->Write();    // write the cut QDC
			hCutQDC[i]->Fit("gaus","q");
			hCutQDC[i]->Draw();
			fits[i] = hCutQDC[i]->GetFunction("gaus");
			if (hCutQDC[i]->GetEntries() > 0) {
				Float_t NDF = (Float_t)fits[i]->GetNDF();
				if (fits[i]->GetNDF() == 0) NDF = 0.0000001;
				sprintf(buffer,"%i  %.1f  %.1f  %.1f  %.1f  %.1f",i,
					fits[i]->GetParameter(1),fits[i]->GetParError(1),		// mean (LED center)
					fits[i]->GetParameter(2),fits[i]->GetParError(2),		// sigma
					fits[i]->GetChisquare()/NDF); // X^2/NDF (closer to 1, better fit.)
				cout << "  " << buffer << endl;
				calib << buffer << endl;
			}
		}
		else {
			hRawQDC[i]->Write();		// write the raw QDC without fitting
		}	
    	
   	// plot low-QDC range separately
  		vcan1->cd(i+1);
  		TVirtualPad *vpad1 = vcan1->cd(i+1); vpad1->SetLogy();
  		hThreshQDC[i]->Draw();
	}

	// Output canvasses of interest.
	Char_t OutputName[200];
	
	sprintf(OutputName,"./output/%s_VetoQDC.C",InputName);
	vcan0->Print(OutputName);

	sprintf(OutputName,"./output/%s_ThreshVetoQDC.C",InputName);
	vcan1->Print(OutputName);
	
	// ==========================

	calib.close();
	RootFile->Close();
	cout << "Wrote ROOT file." << endl;
}
Beispiel #8
0
void Calc_Eff_200(int cen) {
const float PI = TMath::Pi();
const float mean = 0.01166;
const float rms = 0.05312;
TFile *f1 = new TFile("cen6.ntuple_result_v2_11_subEP_dca1_pt015_eta1_noP_pionDca1_higherEP.root");
TH1* h_pt = (TH1*)f1->Get("Hist_Pt");

float real[9][7] = {{1.68441e+07,1.94857e+07,1.91433e+07,1.76339e+07,1.57031e+07,1.3709e+07,1.18246e+07},
			{3.87595e+07,4.43888e+07,4.34577e+07,4.00144e+07,3.57267e+07,3.13252e+07,2.71556e+07},
			{8.04378e+07,9.2009e+07,9.01896e+07,8.33911e+07,7.47927e+07,6.59201e+07,5.74707e+07},
			{1.28651e+08,1.47865e+08,1.45606e+08,1.3528e+08,1.2199e+08,1.08084e+08,9.47436e+07},
			{1.9998e+08,2.31542e+08,2.29316e+08,2.14124e+08,1.94076e+08,1.72786e+08,1.52079e+08},
			{2.91541e+08,3.40818e+08,3.39637e+08,3.1877e+08,2.90097e+08,2.59203e+08,2.29072e+08},
			{3.94517e+08,4.66796e+08,4.68155e+08,4.41467e+08,4.03254e+08,3.61425e+08,3.20203e+08},
			{2.3895e+08,2.85928e+08,2.88314e+08,2.72767e+08,2.49768e+08,2.24261e+08,1.98897e+08},
			{2.70925e+08,3.27361e+08,3.31383e+08,3.14285e+08,2.88208e+08,2.5899e+08,2.29898e+08}};
float emrc[9][7] = {{127.287,180.108,180.46,203.105,201.325,185.72,183.217},
			{111.057,137.61,163.772,151.6,161.841,157.728,178.696},
			{157.959,196.018,206.222,184.609,183.632,238.975,225.804},
			{294.14,355.613,355.514,396.844,397.958,385.601,425},
			{499,551,666,616,706,750,677},
			{715,916,988,992,1031,1047,1070},
			{1045,1247,1393,1414,1523,1589,1527},
			{653,853,898,928,1016,1073,996},
			{863,975,1199,1263,1262,1258,1314}};
const int cenDef[9] = {10, 22, 43, 76, 125, 193, 281, 396, 466};

float Eweight = 1;

        TChain* chain = new TChain("McV0PicoDst");
        int nfile = 0;
        nfile += chain->Add("output_p/*.root");
	nfile += chain->Add("output_pbar/*.root");
//	nfile += chain->Add("output_test/*.root");
//	nfile += chain->Add("output_km/*.root");
//        nfile += chain->Add("output_kp/*.root");
                cout <<"Added "<<nfile<<" files"<<endl;
                cout<<"# entries in chain: "<<chain->GetEntries()<<endl;

	char fname_out[200];
	sprintf(fname_out,"cen%d.eff_200_p.root",cen);
        TFile fout(fname_out,"RECREATE");

	TH1D* Hist_RefMult = new TH1D("Hist_RefMult","Hist_RefMult",500,-0.5,499.5);
	TH2D* Hist_mc_pt = new TH2D("Hist_mc_pt","Hist_mc_pt",28,0,560,200,0,10);
	TH1D* Hist_mc_pt_cen = new TH1D("Hist_mc_pt_cen","Hist_mc_pt_cen",200,0,10);
        TH1D* Hist_mc_pt_L = new TH1D("Hist_mc_pt_L","Hist_mc_pt_Lokesh",200,0,10);
	TH1D* Hist_mc_eta = new TH1D("Hist_mc_eta","Hist_mc_eta",200,-1,1);
	TH1D* Hist_rc_flag = new TH1D("Hist_rc_flag","Hist_rc_flag",3000,-1000+0.5,2000.5);
	TH2D* Hist_rc_pt = new TH2D("Hist_rc_pt","Hist_rc_pt",28,0,560,200,0,10);
	TH1D* Hist_rc_pt_cen = new TH1D("Hist_rc_pt_cen","Hist_rc_pt_cen",200,0,10);
	TH1D* Hist_rc_pt_scale = new TH1D("Hist_rc_pt_scale","Hist_rc_pt_scale",200,0,10);
	TH1D* Hist_rc_pt_L = new TH1D("Hist_rc_pt_L","Hist_rc_pt_Lokesh",200,0,10);
	TH1D* Hist_rc_eta = new TH1D("Hist_rc_eta","Hist_rc_eta",200,-1,1);
	TH1D* Hist_rc_dca = new TH1D("Hist_rc_dca","Hist_rc_dca",200,0,20);
	TH1D* Hist_rc_dca_scale = new TH1D("Hist_rc_dca_scale","Hist_rc_dca_scale",200,0,20);
	TH1D* Hist_rc_nfit = new TH1D("Hist_rc_nfit","Hist_rc_nfit",100,0,100);
	TH1D* Hist_rc_rat = new TH1D("Hist_rc_rat","Hist_rc_rat",100,0,2);
	TH1D* Hist_dphi = new TH1D("Hist_dphi","Hist_dphi",128,-3.2,3.2);
        TH1D* Hist_dphi1 = new TH1D("Hist_dphi1","Hist_dphi1",128,-3.2,3.2);
        TH1D* Hist_dphi2 = new TH1D("Hist_dphi2","Hist_dphi2",128,-3.2,3.2);
        TH1D* Hist_dphi3 = new TH1D("Hist_dphi3","Hist_dphi3",128,-3.2,3.2);
        TH1D* Hist_dphi4 = new TH1D("Hist_dphi4","Hist_dphi4",128,-3.2,3.2);
        TH1D* Hist_dphi_pion = new TH1D("Hist_dphi_pion","Hist_dphi_pion",128,-3.2,3.2);
        TH1D* Hist_ddphi = new TH1D("Hist_ddphi","Hist_ddphi",128,-3.2,3.2);
        TProfile* p_dphi = new TProfile("p_dphi","p_dphi",4,0.5,4.5,-100,100);
        TProfile* p_dphi_pt = new TProfile("p_dphi_pt","p_dphi_pt",200,0,10,-100,100);
        TProfile* p_dphi_L = new TProfile("p_dphi_L","p_dphi_L",4,0.5,4.5,-100,100);
        TProfile* p_dphi_LM= new TProfile("p_dphi_LM","p_dphi_LM",4,0.5,4.5,-100,100);
        TProfile* p_dphi_M = new TProfile("p_dphi_M","p_dphi_M",4,0.5,4.5,-100,100);
        TProfile* p_dphi_RM= new TProfile("p_dphi_RM","p_dphi_RM",4,0.5,4.5,-100,100);
        TProfile* p_dphi_R = new TProfile("p_dphi_R","p_dphi_R",4,0.5,4.5,-100,100);
	TProfile* p_ddphi = new TProfile("p_ddphi","p_ddphi",4,0.5,4.5,-100,100);
        TProfile* p_ddphi_L = new TProfile("p_ddphi_L","p_ddphi_L",4,0.5,4.5,-100,100);
        TProfile* p_ddphi_LM= new TProfile("p_ddphi_LM","p_ddphi_LM",4,0.5,4.5,-100,100);
        TProfile* p_ddphi_M = new TProfile("p_ddphi_M","p_ddphi_M",4,0.5,4.5,-100,100);
        TProfile* p_ddphi_RM= new TProfile("p_ddphi_RM","p_ddphi_RM",4,0.5,4.5,-100,100);
        TProfile* p_ddphi_R = new TProfile("p_ddphi_R","p_ddphi_R",4,0.5,4.5,-100,100);
        TH1D* Hist_asym = new TH1D("Hist_asym","Hist_asym",600,-1.5+0.0025,1.5+0.0025);
        TH1D* Hist_asym_L = new TH1D("Hist_asym_L","Hist_asym_L",600,-1.5+0.0025,1.5+0.0025);
        TH1D* Hist_asym_LM= new TH1D("Hist_asym_LM","Hist_asym_LM",600,-1.5+0.0025,1.5+0.0025);
        TH1D* Hist_asym_M = new TH1D("Hist_asym_M","Hist_asym_M",600,-1.5+0.0025,1.5+0.0025);
        TH1D* Hist_asym_RM= new TH1D("Hist_asym_RM","Hist_asym_RM",600,-1.5+0.0025,1.5+0.0025);
        TH1D* Hist_asym_R = new TH1D("Hist_asym_R","Hist_asym_R",600,-1.5+0.0025,1.5+0.0025);

	Int_t nentries = chain->GetEntries();
	for(int i = 0; i < nentries; i++){

                if((i+1)%1000==0) cout<<"Processing entry == "<< i+1 <<" == out of "<<nentries<<".\n";
                chain->GetEntry(i);

                TLeaf* leaf_RunId   = chain->GetLeaf("runnumber");
		TLeaf* leaf_RefMult = chain->GetLeaf("nrefmult");
		TLeaf* leaf_Px	    = chain->GetLeaf("primvertexX");
		TLeaf* leaf_Py      = chain->GetLeaf("primvertexY");
		TLeaf* leaf_Pz      = chain->GetLeaf("primvertexZ");
		TLeaf* leaf_ZDCrate = chain->GetLeaf("zdcrate");
		TLeaf* leaf_nmcv0   = chain->GetLeaf("nmcv0");
		TLeaf* leaf_nv0	    = chain->GetLeaf("nv0");
                TLeaf* leaf_Np      = chain->GetLeaf("numberP");
                TLeaf* leaf_Nn      = chain->GetLeaf("numberN");

		int Run 	    = leaf_RunId->GetValue(0);
		int RefMult	    = leaf_RefMult->GetValue(0);
		float PVtxz	    = leaf_Pz->GetValue(0);
		int NmcTracks	    = leaf_nmcv0->GetValue(0);
		int NrcTracks	    = leaf_nv0->GetValue(0);
                int Np              = leaf_Np->GetValue(0);
                int Nn              = leaf_Nn->GetValue(0);

		Hist_RefMult->Fill(RefMult);
                int Centrality  = 0;
                for(int j=0;j<9;j++) if(RefMult>cenDef[j]) Centrality = j+1;
                if(RefMult) {
                        float gM = 0.9995 + 21.89/(4.191*RefMult-18.17) - 2.723e-5*(4.191*RefMult-18.17);
                        Eweight = gM + 0.0009326*(gM-1)*PVtxz;
                }
                if(cen && Centrality != cen) continue;

                TLeaf* leaf_mc_Pt        = chain->GetLeaf("mcv0pt");
		TLeaf* leaf_mc_Pz        = chain->GetLeaf("mcv0pz");
		TLeaf* leaf_mc_Px        = chain->GetLeaf("mcv0px");
		TLeaf* leaf_mc_Py        = chain->GetLeaf("mcv0py");
		TLeaf* leaf_mc_id        = chain->GetLeaf("mcv0id");

		for(int trk = 0; trk < NmcTracks; trk++) {
			float mc_pt = leaf_mc_Pt->GetValue(trk);
			float mc_pz = leaf_mc_Pz->GetValue(trk);
			float mc_theta = atan2(mc_pt,mc_pz);
			float mc_eta = -log(tan(mc_theta/2));
			Hist_mc_eta->Fill(mc_eta, Eweight);
			if(mc_eta>-0.5 && mc_eta<0.5) {Hist_mc_pt->Fill(RefMult,mc_pt);}
			if(mc_eta>-1 && mc_eta<1) {Hist_mc_pt_cen->Fill(mc_pt);}
			if(mc_eta>-0.1 && mc_eta<0.1) Hist_mc_pt_L->Fill(mc_pt, Eweight);
		}

                TLeaf* leaf_rc_Pt        = chain->GetLeaf("v0pt");
		TLeaf* leaf_rc_Phi	 = chain->GetLeaf("v0phi");
		TLeaf* leaf_rc_Eta	 = chain->GetLeaf("v0eta");
                TLeaf* leaf_rc_Charge    = chain->GetLeaf("v0charge");
		TLeaf* leaf_rc_flag	 = chain->GetLeaf("v0flag");
		TLeaf* leaf_rc_dca	 = chain->GetLeaf("v0dca");
		TLeaf* leaf_rc_Nfithits  = chain->GetLeaf("v0nfithits");
		TLeaf* leaf_rc_Nmaxhits  = chain->GetLeaf("v0nmaxhits"); 
		TLeaf* leaf_rc_Ndedxhits = chain->GetLeaf("v0ndedxhits");
                TLeaf* leaf_rc_id        = chain->GetLeaf("v0mcid");

               for(int trk = 0; trk < NrcTracks; trk++) {
			int flag = leaf_rc_flag->GetValue(trk);
			Hist_rc_flag->Fill(flag,Eweight);
			if(flag<0 || flag>1000) continue;
			float dca = leaf_rc_dca->GetValue(trk);
			float rc_pt = leaf_rc_Pt->GetValue(trk);
			float eta = leaf_rc_Eta->GetValue(trk);
			int nFitHits = leaf_rc_Nfithits->GetValue(trk);
			int nMaxHits = leaf_rc_Nmaxhits->GetValue(trk);
			float ratio = float(nFitHits)/nMaxHits;
			int ndEdxHits = leaf_rc_Ndedxhits->GetValue(trk);
			Hist_rc_nfit->Fill(nFitHits, Eweight);
			Hist_rc_rat->Fill(ratio, Eweight);
			if(nFitHits<20 || nFitHits>50) continue;
			if(ratio<0.52 || ratio>1.05) continue;
				if(dca>2) continue;

				int ptbin = 0;
				if(rc_pt>0.2) ptbin = 1;
				if(rc_pt>0.25) ptbin = 2;
				if(rc_pt>0.3) ptbin = 3;
				if(rc_pt>0.35) ptbin = 4;
				if(rc_pt>0.4) ptbin = 5;
				if(rc_pt>0.45) ptbin = 6;
				float ptW = 0.001*real[cen-1][ptbin]/emrc[cen-1][ptbin];
//			if((i+1)%1000==0 && rc_pt<0.3 && rc_pt>0.25)  cout<<ptW<<endl;
			Hist_rc_eta->Fill(eta, Eweight);
			
			if(rc_pt>0.15 && rc_pt<0.5) {Hist_rc_dca->Fill(dca, Eweight);Hist_rc_dca_scale->Fill(dca, Eweight*ptW);}
                        if(eta>-0.5 && eta<0.5) {Hist_rc_pt->Fill(RefMult,rc_pt);}

                        if(dca<2 && ndEdxHits>14) {
                        if(eta>-1 && eta<1) Hist_rc_pt_cen->Fill(rc_pt);
			Hist_rc_pt_scale->Fill(rc_pt, Eweight*ptW);
}
			if(dca<3 && nFitHits>=25 &&ndEdxHits>15 && eta>-0.1 && eta<0.1) Hist_rc_pt_L->Fill(rc_pt, Eweight);
                }
///////ONLY ABOVE THIS LINE IS NEEDED FOR EFFICIENCY/////////////////////////////////////////////////// 	
		float Mpt[30], Mdca[30], MndEdxHits[30], Mdphi[30], Mweight[30];
		float integral = (float)h_pt->Integral(1,40);
                float bin_mean = integral/40.;
		int Mnmatch = 0;
		for(int trk = 0; trk < NrcTracks; trk++) {
                        int flag = leaf_rc_flag->GetValue(trk);
			if(flag<0 || flag>1000) continue;
                        float dca = leaf_rc_dca->GetValue(trk);
                        float rc_pt = leaf_rc_Pt->GetValue(trk);
			float rc_phi = leaf_rc_Phi->GetValue(trk);
			float rc_charge = leaf_rc_Charge->GetValue(trk);
                        float eta = leaf_rc_Eta->GetValue(trk);
			if(eta>1 || eta<-1) continue; 
                        int nFitHits = leaf_rc_Nfithits->GetValue(trk);
                        int nMaxHits = leaf_rc_Nmaxhits->GetValue(trk);
                        float ratio = float(nFitHits)/nMaxHits;
                        int ndEdxHits = leaf_rc_Ndedxhits->GetValue(trk);
                        if(nFitHits<20 || nFitHits>50) continue;
                        if(ratio<0.52 || ratio>1.05) continue;
			int rc_id = leaf_rc_id->GetValue(trk);
			int bin = h_pt->FindBin(rc_pt);
			float weight = h_pt->GetBinContent(bin)/bin_mean;

			for(int tr = 0; tr < NmcTracks; tr++) {
                        	float mc_px = leaf_mc_Px->GetValue(tr);
                        	float mc_py = leaf_mc_Py->GetValue(tr);
				float mc_phi = atan2(mc_py,mc_px);
				int mc_id = leaf_mc_id->GetValue(tr);
				if(mc_id==rc_id) {
					Mpt[Mnmatch] = rc_pt;
					Mdca[Mnmatch] = dca;
					MndEdxHits[Mnmatch] = ndEdxHits;
					float dphi = rc_phi - mc_phi;
					if(dphi > PI) dphi -= 2*PI;
					if(dphi <-PI) dphi += 2*PI;
					if(rc_pt>0.15 && rc_pt<2) Hist_dphi->Fill(dphi,weight);
					if(rc_pt>0.15 && rc_pt<0.5) Hist_dphi1->Fill(dphi,weight);
					else if(rc_pt<1) Hist_dphi2->Fill(dphi,weight);
                                        else if(rc_pt<1.5) Hist_dphi3->Fill(dphi,weight);
                                        else if(rc_pt<2) Hist_dphi4->Fill(dphi,weight);
					Mdphi[Mnmatch] = dphi;
					Mweight[Mnmatch] = weight;
					Mnmatch++;
                                        if(rc_charge>0) Np--;
                                        else Nn--;
				}
			}
		}
              float asym = (float(Np)-float(Nn))/(Np+Nn);
              Hist_asym->Fill(asym);
                if(asym<mean-rms) Hist_asym_L->Fill(asym);
                else if(asym<mean-0.3*rms) Hist_asym_LM->Fill(asym);
                else if(asym<mean+0.3*rms) Hist_asym_M->Fill(asym);
                else if(asym<mean+rms) Hist_asym_RM->Fill(asym);
                else Hist_asym_R->Fill(asym);
//cout<<"Nmatch = "<<Mnmatch<<endl;
		for(int ii=0;ii<Mnmatch;ii++) {
                                float dphi = Mdphi[ii];
                        if(Mdca[ii]>1) continue;
                        if(MndEdxHits[ii]<=10) continue;
                        p_dphi_pt->Fill(Mpt[ii],100*cos(2*dphi));
                        if(Mpt[ii]<0.15 || Mpt[ii]>0.5) continue;
                        Hist_dphi_pion->Fill(Mdphi[ii]);
                                p_dphi->Fill(1,100*cos(2*dphi));
                                p_dphi->Fill(2,100*sin(2*dphi));
                                if(asym<mean-rms) {p_dphi_L->Fill(3,100*cos(2*dphi));
                                                        p_dphi_L->Fill(1,100*cos(2*dphi), Mweight[ii]);
                                                        p_dphi_L->Fill(4,100*sin(2*dphi));
                                                        p_dphi_L->Fill(2,100*sin(2*dphi), Mweight[ii]);}
                                else if(asym<mean-0.3*rms) {p_dphi_LM->Fill(3,100*cos(2*dphi));
                                                        p_dphi_LM->Fill(1,100*cos(2*dphi), Mweight[ii]);
                                                        p_dphi_LM->Fill(4,100*sin(2*dphi));
                                                        p_dphi_LM->Fill(2,100*sin(2*dphi), Mweight[ii]);}
                                else if(asym<mean+0.3*rms) {p_dphi_M->Fill(3,100*cos(2*dphi));
                                                        p_dphi_M->Fill(1,100*cos(2*dphi), Mweight[ii]);
                                                        p_dphi_M->Fill(4,100*sin(2*dphi));
                                                        p_dphi_M->Fill(2,100*sin(2*dphi), Mweight[ii]);}
                                else if(asym<mean+rms) {p_dphi_RM->Fill(3,100*cos(2*dphi));
                                                        p_dphi_RM->Fill(1,100*cos(2*dphi), Mweight[ii]);
                                                        p_dphi_RM->Fill(4,100*sin(2*dphi));
                                                        p_dphi_RM->Fill(2,100*sin(2*dphi), Mweight[ii]);}
                                else {p_dphi_R->Fill(3,100*cos(2*dphi));
                                                        p_dphi_R->Fill(1,100*cos(2*dphi), Mweight[ii]);
                                                        p_dphi_R->Fill(4,100*sin(2*dphi));
                                                        p_dphi_R->Fill(2,100*sin(2*dphi), Mweight[ii]);}

			for(int jj=0;jj<Mnmatch;jj++) {
				if(ii==jj) continue;
				if(Mpt[jj]<0.15 || Mpt[jj]>2.0) continue;
				float ddphi = Mdphi[ii] - Mdphi[jj];
				Hist_ddphi->Fill(ddphi);
				p_ddphi->Fill(1,100*cos(2*ddphi));
				p_ddphi->Fill(2,100*sin(2*ddphi));
                                if(asym<mean-rms) {p_ddphi_L->Fill(3,100*cos(2*ddphi));
							p_ddphi_L->Fill(1,100*cos(2*ddphi), Mweight[ii]*Mweight[jj]);
							p_ddphi_L->Fill(4,100*sin(2*ddphi));
							p_ddphi_L->Fill(2,100*sin(2*ddphi), Mweight[ii]*Mweight[jj]);}
                                else if(asym<mean-0.3*rms) {p_ddphi_LM->Fill(3,100*cos(2*ddphi));
							p_ddphi_LM->Fill(1,100*cos(2*ddphi), Mweight[ii]*Mweight[jj]);
                                                        p_ddphi_LM->Fill(4,100*sin(2*ddphi));			
							p_ddphi_LM->Fill(2,100*sin(2*ddphi), Mweight[ii]*Mweight[jj]);}
                                else if(asym<mean+0.3*rms) {p_ddphi_M->Fill(3,100*cos(2*ddphi));
							p_ddphi_M->Fill(1,100*cos(2*ddphi), Mweight[ii]*Mweight[jj]);
                                                        p_ddphi_M->Fill(4,100*sin(2*ddphi));
							p_ddphi_M->Fill(2,100*sin(2*ddphi), Mweight[ii]*Mweight[jj]);}
                                else if(asym<mean+rms) {p_ddphi_RM->Fill(3,100*cos(2*ddphi));
							p_ddphi_RM->Fill(1,100*cos(2*ddphi), Mweight[ii]*Mweight[jj]);
                                                        p_ddphi_RM->Fill(4,100*sin(2*ddphi));
							p_ddphi_RM->Fill(2,100*sin(2*ddphi), Mweight[ii]*Mweight[jj]);}
                                else {p_ddphi_R->Fill(3,100*cos(2*ddphi));
							p_ddphi_R->Fill(1,100*cos(2*ddphi), Mweight[ii]*Mweight[jj]);
                                                        p_ddphi_R->Fill(4,100*sin(2*ddphi));
							p_ddphi_R->Fill(2,100*sin(2*ddphi), Mweight[ii]*Mweight[jj]);}
			}
		}
	}

        fout.Write();
	return;

}
void conv2CaloGeoView(const Char_t *input, const Char_t *output)
{
  TChain *rootChain = new TChain("CollectionTree");
  rootChain->Add(input);
  
  const Int_t nevent = rootChain->GetEntries(); 
  cout << "Formating " << nevent << " events..." << endl;

  //Input vectors.
  UInt_t nClusters;
  vector<UInt_t> *rootNCells = new vector<UInt_t>;
  vector<UChar_t> *rootLayers = new vector<UChar_t>;
  vector<Float_t> *rootEnergy = new vector<Float_t>;
  vector<Float_t> *rootEta = new vector<Float_t>;
  vector<Float_t> *rootPhi = new vector<Float_t>;
  vector<UInt_t> *rootLVL1Id = new vector<UInt_t>;
  vector<UInt_t> *rootRoIId = new vector<UInt_t>;
  vector<Float_t> *rootLVL1Eta = new vector<Float_t>;
  vector<Float_t> *rootLVL1Phi = new vector<Float_t>;
  vector<Float_t> *rootLVL2Eta = new vector<Float_t>;
  vector<Float_t> *rootLVL2Phi = new vector<Float_t>;
  vector<Float_t> *rootLVL2Et = new vector<Float_t>;

  // Output vectors.
  UInt_t nCellsEM;
  vector<UChar_t> *layersEM = new vector<UChar_t>;
  vector<Float_t> *energyEM = new vector<Float_t>;
  vector<Float_t> *etaEM = new vector<Float_t>;
  vector<Float_t> *phiEM = new vector<Float_t>;
  UInt_t nCellsHAD;
  vector<UChar_t> *layersHAD = new vector<UChar_t>;
  vector<Float_t> *energyHAD = new vector<Float_t>;
  vector<Float_t> *etaHAD = new vector<Float_t>;
  vector<Float_t> *phiHAD = new vector<Float_t>;
  UInt_t lvl1Id;
  UInt_t roiId;
  Float_t lvl1Eta;
  Float_t lvl1Phi;
  Float_t lvl2Eta;
  Float_t lvl2Phi;
  Float_t lvl2Et;

  //Creating the output tree.
  TTree *outTree = new TTree("CollectionTree", "RoI for CaloGeoView.");
  outTree->Branch("NCellsLRoI", &nCellsEM, "NCellsLRoI/i");
  outTree->Branch("DetCellsLRoI", &layersEM);
  outTree->Branch("ECellsLRoI", &energyEM);
  outTree->Branch("EtaCellsLRoI", &etaEM);
  outTree->Branch("PhiCellsLRoI", &phiEM);
  outTree->Branch("NCellsTRoI", &nCellsHAD, "NCellsTRoI/i");
  outTree->Branch("DetCellsTRoI", &layersHAD);
  outTree->Branch("ECellsTRoI", &energyHAD);
  outTree->Branch("EtaCellsTRoI", &etaHAD);
  outTree->Branch("PhiCellsTRoI", &phiHAD);
  outTree->Branch("LVL1_Id", &lvl1Id, "LVL1_Id/i");
  outTree->Branch("RoI_Id", &roiId, "RoI_Id/i");
  outTree->Branch("LVL1_Eta", &lvl1Eta, "LVL1_Eta/f");
  outTree->Branch("LVL1_Phi", &lvl1Phi, "LVL1_Phi/f");
  outTree->Branch("LVL2_Eta", &lvl2Eta, "LVL2_Eta/f");
  outTree->Branch("LVL2_Phi", &lvl2Phi, "LVL2_Phi/f");
  outTree->Branch("LVL2_Et", &lvl2Et, "LVL2_Et/f");

  //Selecting the branches we want to read.
  rootChain->SetBranchStatus("*",0);  // disable all branches
  rootChain->SetBranchStatus("Ringer_NClusters",1);
  rootChain->SetBranchStatus("Ringer_NCells",1);
  rootChain->SetBranchStatus("Ringer_DetCells",1);
  rootChain->SetBranchStatus("Ringer_ECells",1);
  rootChain->SetBranchStatus("Ringer_EtaCells",1);
  rootChain->SetBranchStatus("Ringer_PhiCells",1);
  rootChain->SetBranchStatus("Ringer_LVL1_Id",1);
  rootChain->SetBranchStatus("Ringer_Roi_Id",1);
  rootChain->SetBranchStatus("Ringer_LVL1_Eta",1);
  rootChain->SetBranchStatus("Ringer_LVL1_Phi",1);
  rootChain->SetBranchStatus("Ringer_LVL2_Eta",1);
  rootChain->SetBranchStatus("Ringer_LVL2_Phi",1);
  rootChain->SetBranchStatus("Ringer_LVL2_Et",1);
  
  // Associating branches with the input vectors.
  rootChain->SetBranchAddress("Ringer_NClusters", &nClusters);
  rootChain->SetBranchAddress("Ringer_NCells", &rootNCells);
  rootChain->SetBranchAddress("Ringer_DetCells", &rootLayers);
  rootChain->SetBranchAddress("Ringer_ECells", &rootEnergy);
  rootChain->SetBranchAddress("Ringer_EtaCells", &rootEta);
  rootChain->SetBranchAddress("Ringer_PhiCells", &rootPhi);
  rootChain->SetBranchAddress("Ringer_LVL1_Id", &rootLVL1Id);
  rootChain->SetBranchAddress("Ringer_Roi_Id", &rootRoIId);
  rootChain->SetBranchAddress("Ringer_LVL1_Eta", &rootLVL1Eta);
  rootChain->SetBranchAddress("Ringer_LVL1_Phi", &rootLVL1Phi);
  rootChain->SetBranchAddress("Ringer_LVL2_Eta", &rootLVL2Eta);
  rootChain->SetBranchAddress("Ringer_LVL2_Phi", &rootLVL2Phi);
  rootChain->SetBranchAddress("Ringer_LVL2_Et", &rootLVL2Et);

  for (Int_t ev=0; ev<nevent; ev++)
  {
    rootChain->GetEntry(ev);
    if (!nClusters) continue;
    
    UInt_t roiCellBegin = 0;
    nCellsEM = nCellsHAD = 0;
    for (UInt_t roi=0; roi<nClusters; roi++)
    {
      //Copying RoI header values.
      lvl1Id = rootLVL1Id->at(roi);
      roiId = rootRoIId->at(roi);
      lvl1Eta = rootLVL1Eta->at(roi);
      lvl1Phi = rootLVL1Phi->at(roi);
      lvl2Eta = rootLVL2Eta->at(roi);
      lvl2Phi = rootLVL2Phi->at(roi);
      lvl2Et = rootLVL2Et->at(roi);

      //Copying the RoI elements.
      for (UInt_t c = roiCellBegin; c < (roiCellBegin+rootNCells->at(roi)); c++)
      {
        if (rootLayers->at(c) < 8) // If it is EM...
        {
          layersEM->push_back(rootLayers->at(c));
          energyEM->push_back(rootEnergy->at(c));
          etaEM->push_back(rootEta->at(c));
          phiEM->push_back(rootPhi->at(c));
          nCellsEM++;
        }
        else // If it is Hadronic...
        {
          layersHAD->push_back(rootLayers->at(c));
          energyHAD->push_back(rootEnergy->at(c));
          etaHAD->push_back(rootEta->at(c));
          phiHAD->push_back(rootPhi->at(c));
          nCellsHAD++;
        }
      }
        
      //Pointing to the next RoI.
      roiCellBegin += rootNCells->at(roi);
     
      //Saving to the output ntuple.
      outTree->Fill();
      
      //Clearing the vectors for the next cycle.
      layersEM->clear();
      energyEM->clear();
      etaEM->clear();
      phiEM->clear();
      layersHAD->clear();
      energyHAD->clear();
      etaHAD->clear();
      phiHAD->clear();
    }
  }
  
  //Saving the NTuple file.
  TFile outFile(output, "RECREATE");
  outTree->Write();
  outFile.Close();

  delete rootChain;
  delete outTree;
  delete rootNCells;
  delete rootLayers;
  delete rootEnergy;
  delete rootEta;
  delete rootPhi;
  delete layersEM;
  delete energyEM;
  delete etaEM;
  delete phiEM;
  delete layersHAD;
  delete energyHAD;
  delete etaHAD;
  delete phiHAD;
}
Beispiel #10
0
int MC_Ratio(TString _filetag,int leptonId, double* par1, int npar1bins, double* par2, int npar2bins, TString sel_den , TString sel_num, double cut_num , TString par_x , TString par_y , TString option ){

  setTDRStyle();

  option.Append(" ");
  option.Prepend(" ");

  ///////////////
  //Get the TTree
  ///////////////

  //Location of the .root file
  TString location = "/Users/GLP/Desktop/CERN_data/2014-11-13_skim2ll-mva-softbtag/postprocessed/matched2/";
  TString location2 = "/Users/GLP/Desktop/CERN_data/dyjetsnew/postprocessed/matched/";

  //Reading the tree 
  //
  TChain* tree = new TChain("treeProducerSusyMultilepton");

  //DY events
  if(option.Contains("oldtree")){tree->Add(location+"DYJetsToLLM50_PU_S14_POSTLS170.root");}
      else{tree->Add(location2+"dyjetsnew.root");}

  //Plot the result

  Long64_t n = tree->GetEntries();

  //Path for input and output file. Written in FitDataPath.txt
  TString _path = "/Users/GLP/Dropbox/Physique/Master_Thesis/plots_root/MC_ratio/";

  //////////////////////
  //Name for the plots//
  //////////////////////

  TString pname;
  TString _pname;
  TString _par;
  TString _sel_num;
  TString _sel_den;
  TString _option;

  ////Writing string
  //particle string
  if(abs(leptonId) == 11){pname = "e"; _pname = "e";}
  if(abs(leptonId) == 13){pname = " #mu"; _pname = "mu";}
  //Parameter string
  if(par_x == "Pt"){_par = "P_{t}";}
  else if(par_x == "eta"){_par = "#eta";}
  else if(par_x == "phi"){_par = "#phi";}
  //sel_den string
  if((sel_den == "tightmva")&&(leptonId == 13)){cout<<"ERROR: no tightId MVA defined for the muon !"<<endl;return 1;}
  if(sel_den == "tightcut"){_sel_den = "tightcut";}
  else if(sel_den == "tightmva"){_sel_den = "tightmva";}
  else if(sel_den == "loose"){_sel_den = "loose";}
  else if(sel_den == ""){_sel_den = "";}
  else{cout<<"ERROR: wrong sel_denion !";return 1;}
  //sel_num string
  if((sel_num == "tightmva")&&(leptonId == 13)){cout<<"ERROR: no tightId MVA defined for the muon !"<<endl;return 1;}
  if(sel_num == "tightcut"){_sel_num = "tightcut";}
  else if(sel_num == "tightmva"){_sel_num = "tightmva";}
  else if(sel_num == ""){_sel_num = "";}
  else if(sel_num == "loose"){_sel_num = "loose";}
  else if(sel_num == "reliso3"){_sel_num = Form("reliso3_%0.3lf",cut_num);}
  else if(sel_num == "reliso4"){_sel_num = Form("reliso4_%0.3lf",cut_num);}
  else if(sel_num == "chiso3"){_sel_num = Form("chiso3_%0.3lf",cut_num);}
  else if(sel_num == "chiso4"){_sel_num = Form("chiso4_%0.3lf",cut_num);}
  else if(sel_num == "dxy"){_sel_num = Form("dxy_%0.3lf",cut_num);}
  else if(sel_num == "dz"){_sel_num = Form("dz_%0.3lf",cut_num);}
  else{cout<<"ERROR: wrong numerator name !";return 1;}
  //option string
  if(option.Contains(" ll ")){_option += "_ll";}
  if(option.Contains(" unmatched ")){_option += "_unmatched";}
  if(option.Contains(" alleta ")){_option += "_alleta";}
  if(option.Contains(" short ")){_option += "_short";}
  if(option.Contains(" loose ")){_option += "_loose";}
  if(option.Contains(" oldtree ")){_option += "_oldtree";}
  _option += "_";
  //parameter range string
  TString _par1range;
  _par1range = Form("%0.3f_"+par_x+"%0.3f",par1[0],par1[npar1bins]);
  TString _par2range;
  _par2range = Form("%0.3f_"+par_y+"%0.3f",par2[0],par2[npar2bins]);

  /////////////////////////////////////
  //Write the name of the output file//
  /////////////////////////////////////

  TString _fname = "eff"+_filetag+_option+_pname+_par1range+"_"+_par2range+"_den_"+_sel_den+"_num_"+_sel_num;

  //Output file
  TFile* file_out = new TFile(_path+_fname+".root","recreate");

  //Declaration of histogram
  TH1D **histo_num = new TH1D*[npar2bins];
  TH1D **histo_den = new TH1D*[npar2bins];
  TH1D **eff = new TH1D*[npar2bins];


  //Par1 distribution histogram
  TH1D** histo_par1 = new TH1D*[npar2bins];
  TH1D*** h_par1 = new TH1D**[npar2bins];

  //Distribution of the cut parameter whose efficiency is studied
  TH1D *histo_other_sel = new TH1D("histo_other_sel","h",5,0,5);
  TH1D *histo_good_sel = new TH1D("histo_good_sel","h",5,0,5);

  //Histo separate in Lep_good Lep_other
  //
  TH1D **histo_num_O = new TH1D*[npar2bins];
  TH1D **histo_den_O = new TH1D*[npar2bins];
  TH1D **eff_O = new TH1D*[npar2bins];
  TH1D **histo_num_G = new TH1D*[npar2bins];
  TH1D **histo_den_G = new TH1D*[npar2bins];
  TH1D **eff_G = new TH1D*[npar2bins];

  //Counter LepGood vs LepOther

  TH1D **histo_counter = new TH1D*[npar2bins];
  TH1D **histo_counter_G_par1 = new TH1D*[npar2bins];
  TH1D **histo_counter_O_par1 = new TH1D*[npar2bins];
  TH1D **histo_counter_par1 = new TH1D*[npar2bins];


  for(int _i = 0; _i < npar2bins; ++_i){ 

    histo_num[_i] = new TH1D("histo_num","Pt",npar1bins,par1[0],par1[npar1bins]);
    histo_den[_i] = new TH1D("histo_den","Pt",npar1bins,par1[0],par1[npar1bins]);
    eff[_i] = new TH1D("eff","Pt",npar1bins,par1[0],par1[npar1bins]);

    //
    histo_par1[_i] = new TH1D("histo_par1","par1",npar1bins*25,par1[0],par1[npar1bins]);
    h_par1[_i] = new TH1D*[npar1bins];

    for(int _j = 0; _j < npar1bins; ++_j){

      h_par1[_i][_j] = new TH1D("h_par1","par1",25,par1[_j],par1[_j+1]);

    }

    //
    histo_num_O[_i] = new TH1D("histo_num_O","Pt",npar1bins,par1[0],par1[npar1bins]);
    histo_den_O[_i] = new TH1D("histo_den_O","Pt",npar1bins,par1[0],par1[npar1bins]);
    eff_O[_i] = new TH1D("eff_O","Pt",npar1bins,par1[0],par1[npar1bins]);

    histo_num_G[_i] = new TH1D("histo_num_G","Pt",npar1bins,par1[0],par1[npar1bins]);
    histo_den_G[_i] = new TH1D("histo_den_G","Pt",npar1bins,par1[0],par1[npar1bins]);
    eff_G[_i] = new TH1D("eff_G","Pt",npar1bins,par1[0],par1[npar1bins]);

    histo_counter_G_par1[_i] = new TH1D("histo_counter_G_par1","count",npar1bins,par1[0],par1[npar1bins]);
    histo_counter_O_par1[_i] = new TH1D("histo_counter_O_par1","count",npar1bins,par1[0],par1[npar1bins]);
    histo_counter_par1[_i] = new TH1D("histo_counter_par1","count",npar1bins,par1[0],par1[npar1bins]);

    histo_counter[_i] = new TH1D("histo_counter","count",2,0,2); 

  }

  //Event variables
  Int_t evt_id;
  Float_t scale;
  //Generated
  Float_t gen_phi[200];
  Float_t gen_eta[200];
  Float_t Pt[200];
  Float_t m[200];
  Int_t Id[200];
  Int_t Mo[200];
  Float_t charge[200];
  Int_t status[200];
  Int_t GrMa[200];
  Int_t ngenPart;
  Int_t source[200];
  //not loose
  Int_t On;
  Int_t Oid[200];
  Float_t Opt[200];
  Float_t Om[200];
  Float_t Oeta[200];
  Float_t Ophi[200];
  Int_t   Oq[200];
  Int_t Otight[200];
  Int_t Otighte[200];
  //Float_t Omvaid[200];
  Int_t Oloose[200];
  Float_t Oiso3[200];
  Float_t Oiso4[200];
  Float_t Ochiso3[200];
  Float_t Ochiso4[200];
  Float_t Odxy[200];
  Float_t Odz[200];
  Int_t Ofromtau[200];
  //loose
  Int_t 	Gn;
  Int_t 	Gid[200];
  Float_t 	Gpt[200];
  Float_t 	Gm[200];
  Float_t 	Geta[200];
  Float_t 	Gphi[200];
  Int_t   	Gq[200];
  Int_t 	Gtight[200];
  Int_t 	Gtighte[200];
  Int_t 	Gloose[200];
  Float_t 	Giso3[200];
  Float_t 	Giso4[200];
  Float_t 	Gchiso3[200];
  Float_t 	Gchiso4[200];
  Float_t 	Gdxy[200];
  Float_t 	Gdz[200];
  Int_t         Gfromtau[200];

  //Assigne branches tree->SetBranchAddress("evt_scale1fb", &scale);
  tree->SetBranchAddress("evt_id", &evt_id);
  //generated
  tree->SetBranchAddress("ngenLep", &ngenPart);
  tree->SetBranchAddress("genLep_pdgId", &Id);
  tree->SetBranchAddress("genLep_sourceId", &source);
  tree->SetBranchAddress("genLep_eta", &gen_eta);
  tree->SetBranchAddress("genLep_phi", &gen_phi);
  tree->SetBranchAddress("genLep_pt", &Pt);
  tree->SetBranchAddress("genLep_mass", &m);
  tree->SetBranchAddress("genLep_charge", &charge);
  tree->SetBranchAddress("genLep_status", &status);
  //not loose
  tree->SetBranchAddress("nLepOther",&On);
  tree->SetBranchAddress("LepOther_pdgId",&Oid);
  tree->SetBranchAddress("LepOther_pt",&Opt);
  tree->SetBranchAddress("LepOther_mass",&Om);
  tree->SetBranchAddress("LepOther_eta",&Oeta);
  tree->SetBranchAddress("LepOther_phi",&Ophi);
  tree->SetBranchAddress("LepOther_charge",&Oq);
  tree->SetBranchAddress("LepOther_tightId",&Otight);
  tree->SetBranchAddress("LepOther_eleCutIdCSA14_50ns_v1",&Otighte);
  tree->SetBranchAddress("LepOther_relIso03",&Oiso3);
  tree->SetBranchAddress("LepOther_relIso04",&Oiso4);
  tree->SetBranchAddress("LepOther_chargedHadRelIso03",&Ochiso3);
  tree->SetBranchAddress("LepOther_chargedHadRelIso04",&Ochiso4);
  tree->SetBranchAddress("LepOther_dxy",&Odxy);
  tree->SetBranchAddress("LepOther_dz",&Odz);
  tree->SetBranchAddress("LepOther_mcMatchTau",&Ofromtau);
  //Loose
  tree->SetBranchAddress("nLepGood",&Gn);
  tree->SetBranchAddress("LepGood_pdgId",&Gid);
  tree->SetBranchAddress("LepGood_pt",&Gpt);
  tree->SetBranchAddress("LepGood_mass",&Gm);
  tree->SetBranchAddress("LepGood_eta",&Geta);
  tree->SetBranchAddress("LepGood_phi",&Gphi);
  tree->SetBranchAddress("LepGood_charge",&Gq);
  tree->SetBranchAddress("LepGood_tightId",&Gtight);
  tree->SetBranchAddress("LepGood_eleCutIdCSA14_50ns_v1",&Gtighte);
  tree->SetBranchAddress("LepGood_relIso03",&Giso3);
  tree->SetBranchAddress("LepGood_relIso04",&Giso4);
  tree->SetBranchAddress("LepGood_chargedHadRelIso03",&Gchiso3);
  tree->SetBranchAddress("LepGood_chargedHadRelIso04",&Gchiso4);
  tree->SetBranchAddress("LepGood_dxy",&Gdxy);
  tree->SetBranchAddress("LepGood_dz",&Gdz);
  tree->SetBranchAddress("LepGood_mcMatchTau",&Gfromtau);

  int count = 0;

  //Count lepgood/other
  int goodcount = 0;
  int othercount = 0;

  //count number of leptons


  if(option.Contains("short")){n = 100000;}

  //Start loop over all events
  for (int k = 0; k < n; ++k) {

    //Declaration of event parameters
    Int_t 	evtn;
    Int_t 	evtloose[200];
    Int_t 	evtid[200];
    Float_t 	evtpt[200];
    Float_t 	evtm[200];
    Float_t 	evteta[200];
    Float_t 	evtphi[200];
    Int_t   	evtq[200];
    Int_t 	evttight[200];
    Int_t 	evttighte[200];
    Float_t 	evtiso3[200];
    Float_t 	evtiso4[200];
    Float_t 	evtchiso3[200];
    Float_t 	evtchiso4[200];
    Float_t 	evtdxy[200];
    Float_t 	evtdz[200];
    Float_t 	evtfromtau[200];

    if( 100*(double)k/n> count){cout<<count<<endl;++count;}

    tree->GetEntry(k);

    int nlep  = 0;//count the number of leptons

    //Selection on denominator
    for(int j = 0; j < Gn+On; ++j){

      //Separate here other from loose
      if(j < On){

	evtloose[j]			  = 0;
	evtid[j]                      = Oid[j];
	evtpt[j]                      = Opt[j];
	evtm[j]                       = Om[j];
	evteta[j]                     = Oeta[j];
	evtphi[j]                     = Ophi[j];
	evtq[j]                       = Oq[j];
	evttight[j]                   = Otight[j];
	evttighte[j]                  = Otighte[j];
	evtiso3[j]                    = Oiso3[j];
	evtiso4[j]                    = Oiso4[j];
	evtchiso3[j]                  = Ochiso3[j];
	evtchiso4[j]                  = Ochiso4[j];
	evtdxy[j]                     = Odxy[j];
	evtdz[j]                      = Odz[j];
	evtfromtau[j]                 = Ofromtau[j];


      }else if((j >=  On)&&(j < Gn+On)){

	evtloose[j]		       = 1;
	evtid[j]                   = Gid[j-On];
	evtpt[j]                   = Gpt[j-On];
	evtm[j]                    = Gm[j-On];
	evteta[j]                  = Geta[j-On];
	evtphi[j]                  = Gphi[j-On];
	evtq[j]                    = Gq[j-On];
	evttight[j]                = Gtight[j-On];
	evttighte[j]               = Gtighte[j-On];
	evtiso3[j]                 = Giso3[j-On];
	evtiso4[j]                 = Giso4[j-On];
	evtchiso3[j]               = Gchiso3[j-On];
	evtchiso4[j]               = Gchiso4[j-On];
	evtdxy[j]                  = Gdxy[j-On];
	evtdz[j]                   = Gdz[j-On];
	evtfromtau[j]              = Gfromtau[j-On];

      }

      if((!option.Contains(" ll "))||((option.Contains(" ll "))&&(Gn+On == 2)&&(evtq[0] == -evtq[1]))){
	if(abs(evtid[j]) == leptonId){
	  if((!option.Contains("loose"))||((option.Contains("loose"))&&(evtloose[j] == 1))){
	    if((sel_den != "tightcut")||(((abs(evtid[j]) == 13)&&(sel_den == "tightcut")&&(evttight[j] == 1 ))||((abs(evtid[j]) == 11)&&(sel_den == "tightcut")&&(evttighte[j] >= 3)))){
	      if((sel_den != "tightmva")||((abs(evtid[j]) == 11)&&(sel_den == "tightmva")&&(evttight[j] == 1))){

		//Variable for matching
		double R = 999;
		double delta_P = 999;
		double delta_charge = 999;

		//Parameter on the xaxis

		double par;
		double par_2;

		//loop over all generated particles to do the matching
		for (int i = 0; i < ngenPart; ++i) {
		  if(Id[i] == evtid[j]){ 

		    //Electrons selection
		    double R2 = DeltaR(gen_eta[i],evteta[j],gen_phi[i],evtphi[j] );

		    //Minimise DeltaR and Fill the other variables
		    if (R > R2) {
		      R = R2;
		      delta_P = abs(evtpt[j]-Pt[i])/Pt[i];
		      delta_charge = abs(evtq[j] - charge[i]);
		    }
		  }
		}

		//Choose the parameter to be filled for the eff.
		if(par_x == "Pt"){par = evtpt[j];}
		else if(par_x == "eta"){par = evteta[j];}
		else if(par_x == "phi"){par = evtphi[j];}
		if(par_y == "Pt"){par_2 = evtpt[j];}
		else if(par_y == "eta"){par_2 = abs(evteta[j]);}
		else if(par_y == "phi"){par_2 = abs(evtphi[j]);}

		//Fill Pt only for matched events
		if(((R<0.1)&&(delta_P < 0.2)&&(delta_charge < 0.5))||option.Contains(" unmatched ")){

		  for(int ii = 0; ii < npar2bins; ++ii){
		    if((par_2 > par2[ii])&&(par_2 <= par2[ii+1])){histo_den[ii]->Fill(par);histo_par1[ii]->Fill(par);

		      if(evtloose[j] == 1){histo_good_sel->Fill(evttighte[j]);}
		      else if(evtloose[j] == 0){histo_other_sel->Fill(evttighte[j]);}
		      else{cout<<"Error !"<<endl; return 1;}

		      //Fill par1 distribution
		      for(int pp = 0; pp <npar1bins; ++pp){
			if((par > par1[pp])&&(par <= par1[pp+1])){h_par1[ii][pp]->Fill(par);}
		      }
		    }
		  }

		  //Additional cut on the numerator
		  int a = 0;

		  if((sel_num == "tightcut")&&(abs(evtid[j]) == 13)&&(evttight[j] == 1)){a = 1;}
		  if((sel_num == "tightcut")&&(abs(evtid[j]) == 11)&&(evttighte[j] >= 3)){a = 1;}
		  if((sel_num == "reliso3")&&(evtiso3[j] <= cut_num)){a = 2;}
		  if((sel_num == "reliso4")&&(evtiso4[j] <= cut_num)){a = 3;}
		  if((sel_num == "chiso3")&&(evtchiso3[j] <= cut_num)){a = 4;}
		  if((sel_num == "chiso4")&&(evtchiso4[j] <= cut_num)){a = 5;}
		  if((sel_num == "dxy")&&(abs(evtdxy[j]) <= cut_num)){a = 6;}
		  if((sel_num == "dz")&&(abs(evtdz[j]) <= cut_num)){a = 7;}
		  if((sel_num == "tightmva")&&(abs(evtid[j]) == 11)&&(evttight[j] == 1)){a = 9;}
		  if((sel_num == "loose")&&(evtloose[j]) == 1){a = 8;}

		  //Find the corresponding histogram for par2
		  TH1D* hist;
		  TH1D* hist_evt;

		  bool found = false;
		  for(int _i = 0; _i < npar2bins; ++_i){
		    if((par_2 > par2[_i])&&(par_2 <= par2[_i+1])){hist = histo_num[_i];found = true;}
		  }

		  if(!found){a = 0;}

		  switch(a){

		    case 0:

		      break;

		    case 1:
		      hist->Fill(par);
		      break;

		    case 2:
		      hist->Fill(par);
		      break;
		    case 3:
		      hist->Fill(par);
		      break;
		    case 4:
		      hist->Fill(par);
		      break;
		    case 5:
		      hist->Fill(par);
		      break;
		    case 6:
		      hist->Fill(par);
		      break;

		    case 7:
		      hist->Fill(par);
		      break;

		    case 8:
		      hist->Fill(par);
		      break;

		    case 9:
		      hist->Fill(par);
		      break;
		  }
		}
	      }
	    }
	  }
	}
	}
	//}
    }
  }

  mkdir(_path+_fname+"_PDF/", S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);

  ///////////////////
  //Draw histograms//
  ///////////////////

  //Canvas declaration
  for(int i = 0; i < npar2bins; ++i){

    ////////////////////
    //Build histograms//
    ////////////////////

    histo_num[i]->Sumw2();
    histo_den[i]->Sumw2();
    eff[i]->Divide(histo_num[i],histo_den[i],1,1,"B");

    //histo_num_O[i]->Sumw2();
    //histo_den_O[i]->Sumw2();
    //eff_O[i]->Divide(histo_num_O[i],histo_den_O[i],1,1,"B");

    //histo_num_G[i]->Sumw2();
    //histo_den_G[i]->Sumw2();
    //eff_G[i]->Divide(histo_num_G[i],histo_den_G[i],1,1,"B");

    //histo_counter_G_par1[i]->Sumw2();
    //histo_counter_O_par1[i]->Sumw2();
    //histo_counter_par1[i]->Divide(histo_counter_O_par1[i],histo_counter_G_par1[i],1,1,"B");

    //histo_counter[i]->Fill(0.5,goodcount);
    //histo_counter[i]->Fill(1.5,othercount);

    //String for name of the ouput files and histograms titles
    //

    TString _parybin;

    //Parameter string
    if(par_y == "Pt"){_parybin = Form("%0.f_Pt%0.f",par2[i],par2[i+1]);}
    else if(par_y == "eta"){_parybin = Form("%0.3f_eta%0.3f",par2[i],par2[i+1]);cout<<"it works !"<<endl;}
    else if(par_y == "phi"){_parybin = Form("%0.3f_phi%0.3f",par2[i],par2[i+1]);}

    TString _parytitle;

    //Title string
    if(par_y == "Pt"){_parytitle = Form("%0.f #leq P_{t} #leq %0.f",par2[i],par2[i+1]);}
    else if(par_y == "eta"){_parytitle = Form("%0.3f #leq #||{#eta}  #leq %0.3f",par2[i],par2[i+1]);cout<<"it works !"<<endl;}
    else if(par_y == "phi"){_parytitle = Form("%0.3f #leq #||{#phi}  #leq %0.3f",par2[i],par2[i+1]);}

    //Draw histograms
    TCanvas* c1 = new TCanvas("c1","c1");
    c1->cd();
    eff[i]->Draw();
    eff[i]->GetYaxis()->SetTitle("#epsilon");
    eff[i]->GetYaxis()->SetRangeUser(0,1.1);
    eff[i]->GetXaxis()->SetTitle(_par);
    eff[i]->SetMarkerStyle(20);
    eff[i]->SetMarkerSize(1);
    eff[i]->SetMarkerColor(4);
    eff[i]->SetLineColor(4);
    eff[i]->SetTitle(_sel_num+" for "+_sel_den+" "+pname+" "+_parytitle);

    TCanvas* c_par1 = new TCanvas("cpar1","cpar1");
    TString _partitle = _par + (TString)" distribution for "+pname+", "+_parytitle+", "+sel_num;
    c_par1->cd();
    histo_par1[i]->Draw();
    histo_par1[i]->SetTitle(_partitle);
    histo_par1[i]->GetXaxis()->SetTitle(_par);
    histo_par1[i]->SetLineWidth(2);
    histo_par1[i]->SetLineColor(4);
    histo_par1[i]->SetMarkerColor(4);


    //TCanvas* cO = new TCanvas("cO","cO");
    //cO->cd();
    //eff_O[i]->Draw();
    //eff_O[i]->GetYaxis()->SetTitle("#epsilon");
    //eff_O[i]->GetXaxis()->SetTitle(_par);
    //eff_O[i]->SetMarkerStyle(20);
    //eff_O[i]->SetMarkerSize(1);
    //eff_O[i]->SetMarkerColor(4);
    //eff_O[i]->SetLineColor(4);
    //eff_O[i]->SetTitle(_sel_num+" for "+_sel_den+" "+pname+" "+_parytitle+" , LepOther");

    //TCanvas* cG = new TCanvas("cG","cG");
    //cG->cd();
    //eff_G[i]->Draw();
    //eff_G[i]->GetYaxis()->SetTitle("#epsilon");
    //eff_G[i]->GetXaxis()->SetTitle(_par);
    //eff_G[i]->SetMarkerStyle(20);
    //eff_G[i]->SetMarkerSize(1);
    //eff_G[i]->SetMarkerColor(4);
    //eff_G[i]->SetLineColor(4);
    //eff_G[i]->SetTitle(_sel_num+" for "+_sel_den+" "+pname+" "+_parytitle+" , LepGood");

    //TCanvas* ccpar = new TCanvas("ccpar","ccpar");
    //ccpar->cd();
    //histo_counter_par1[i]->Draw();

    //TCanvas* cc = new TCanvas("cc","cc");
    //cc->cd();
    //histo_counter[i]->Draw();
    //
    histo_good_sel->Add(histo_other_sel);
    TCanvas* csel = new TCanvas("csel","csel");
    csel->cd();
    histo_good_sel->Draw();

    /////////////////////
    //Saving the output//
    /////////////////////

    //Write pdf
    TString cname = "eff"+_filetag+_option+_pname+_par1range+"_"+_parybin+"_den_"+_sel_den+"_num_"+_sel_num;
    c1->SaveAs(_path+_fname+"_PDF/"+cname+".pdf");
    //c_par1->SaveAs(_path+_fname+"_PDF/"+cname+"par_distr.pdf");
    csel->SaveAs(_path+_fname+"_PDF/"+cname+"sel.pdf");
    //cO->SaveAs(_path+_fname+"_PDF/"+cname+"_LepOther.pdf");
    //cG->SaveAs(_path+_fname+"_PDF/"+cname+"_LepGood.pdf");
    //ccpar->SaveAs(_path+_fname+"_PDF/"+cname+"_counter_par.pdf");
    //cc->SaveAs(_path+_fname+"_PDF/"+cname+"_counter.pdf");

    //Write in output file
    file_out->cd();
    eff[i]->Write("eff"+_parybin);
    histo_par1[i]->Write("histo_par1_"+_parybin);
    histo_good_sel->Write("sel"+_parybin);
    //eff_O[i]->Write("eff_LepOther"+_parybin);
    //eff_G[i]->Write("eff_LepGood"+_parybin);
    //histo_counter_par1[i]->Write("counter_par"+_parybin);
    //histo_counter[i]->Write("counter"+_parybin);
    //
    //
    for( int _i = 0; _i < npar1bins; ++_i){

      TString _parxbin;

      if(par_x == "Pt"){_parxbin = Form("%0.f_Pt%0.f",par1[_i],par1[_i+1]);}
      else if(par_x == "eta"){_parxbin = Form("%0.3f_eta%0.3f",par1[_i],par1[_i+1]);}
      else if(par_x == "phi"){_parxbin = Form("%0.3f_phi%0.3f",par1[_i],par1[_i+1]);}

      h_par1[i][_i]->Write("histo_par1_"+_parxbin+"_"+_parybin);

    }

  }

  file_out->Close();


  return 0;

}
void builtVetoMult2reader(string Input = ""){

	int card1 = 13;
	int card2 = 18;
	Bool_t useThresh = true; // if true, also enables fitting LED peaks
	
	
	//led (low) qdc threshold values from findThresh.C
		Int_t ledthresh[numPanels] = {136, 129, 115, 108, 172, 129, 129, 122, 129, 108, 122, 115, 108, 115, 108, 186, 65, 165, 100, 136, 93, 100, 143, 79, 136, 115, 93, 122, 158, 172, 129, 93};
	
		//muon (high) qdc threshold values
		Int_t muonthresh[numPanels] = {0};

		for (Int_t k=0; k<numPanels; k++){
			muonthresh[k] = 500;
		}

	
	// Input a list of run numbers
	if (Input == "") Char_t InputName[200] = "builtVeto_DebugList";
	else Char_t InputName[200] = Input.c_str();
	Char_t InputFile[200];
	sprintf(InputFile,"%s.txt",InputName);
	ifstream InputList;
	InputList.open(InputFile);
	Char_t TheFile[200];
	
	// Set up output file(s)
	Char_t OutputFile[200];
	sprintf(OutputFile,"%s.root",InputName);
	TFile *RootFile = new TFile(OutputFile, "RECREATE");	
  	TH1::AddDirectory(kFALSE); // Global flag: "When a (root) file is closed, all histograms in memory associated with this file are automatically deleted."
	
	ofstream lowdt;
	lowdt.open ("zerodeltat.txt");

	//=== Global counters / variables / plots ===

		Int_t run = 0;
		Float_t duration = 0;

		const Int_t nqdc_bins=1400;  // this gives 3 qdc / bin
		const Float_t ll_qdc=0.;
		const Float_t ul_qdc=4300.;

		Float_t Tnew = 0;
		Float_t Told = 0;
		Float_t deltaT = 0;

		Float_t totdur = 0;
		Int_t badtimecount = 0;
		Int_t baddurcount = 0;

		Float_t ledcount[numFiles] = {0};
		Float_t ledcountmax[numFiles] = {0};
		Float_t ledtimemax[numFiles] = {0}; 
		Float_t totledcount = 0;

		Float_t muoncount[numFiles] = {0};
		Float_t totmuoncount = 0;
		Int_t omitteddur[numFiles] = {0};


		Float_t ledQDCcount[numFiles][numPanels] = {0};
		Float_t totledQDC[numFiles][numPanels] = {0};
		Float_t quadtotledQDC[numFiles][numPanels] = {0};
		Float_t AvgledQDC[numFiles][numPanels] = {0};
		Float_t rmsledQDC[numFiles][numPanels] = {0};
		Float_t AvgFileLEDQDC[numFiles] = {0};
		Float_t totFileLEDQDC[numFiles] = {0};
		Float_t totFileledQDCcount[numFiles] = {0};
		Float_t slope[numFiles] = {0}; //slope of # leds vs duration
		Int_t runnum[numFiles] = {0}; //array of run numbers
		
		// get number of files in dataset for the TGraph
		Int_t filesToScan = 0;
		Int_t filesScanned = 0;
	  	while(true) { 
			InputList >> run; 
			if (InputList.eof()) 		break;
			filesToScan++; 
		}
	  	cout << "Scanning " << numFiles << " files." << endl;	  	
	  	InputList.close();
	  	InputList.open(InputFile);
	  	run=0;
	 	TGraph *SCorruption = new TGraph(filesToScan);
	 	Int_t BadTSTotal = 0;
		if (filesToScan != numFiles){
			cout << " Error: number of files in builtVetoMult.C does not equal number of files in builtVeto_DebugList.txt" << endl;
			break;
		}

	 	TH1D *TotalCorruptionInTime = new TH1D("TotalCorruptionInTime","corrupted entries during run (entry method)",(Int_t)3600/5,0,3600);
	 	TotalCorruptionInTime->GetXaxis()->SetTitle("time (5 sec / bin)");
	 	Bool_t PlotCorruptedEntries = true; // flag for plotting corrupted entries in time for EACH RUN

	 	TH1D *TotalMultiplicity = new TH1D("TotalMultiplicity","Events over threshold",32,0,32);
	 	TotalMultiplicity->GetXaxis()->SetTitle("number of panels hit");
	 	Bool_t PlotMultiplicity = true;	// flag to plot multiplicity for EACH RUN

		Int_t ledcut = 20;
		TH1D *hLEDCutMult = new TH1D("hLEDCutMult","LED Events over threshold (ledcut = 20) ",32,0,32);
	 	hLEDCutMult->GetXaxis()->SetTitle("number of panels hit");

		TH1D *hLEDCutMulttest = new TH1D("hLEDCutMult","LED Events over threshold (ledcut = 2) ",32,0,32);
	 	hLEDCutMulttest->GetXaxis()->SetTitle("number of panels hit");		

		TH1D *hLEDCutDT = new TH1D("hLEDCutDT","Delta T between LED Events over threshold (ledcut = 20) ",20000,0,20);
	 	hLEDCutDT->GetXaxis()->SetTitle("time (seconds)");
		
		TH1D *hLEDCutDTFocus = new TH1D("hLEDCutDTFocus","Delta T between LED Events over threshold (ledcut = 20)",100000,7,8); //graph DT peak with high resolution
		hLEDCutDTFocus->GetXaxis()->SetTitle("time (seconds)");

		TH1D *hLEDpertime = new TH1D("hLEDpertime","LED events vs run duration (ledcut = 10) ",3600,0,3600);
	 	hLEDpertime->GetXaxis()->SetTitle("run duration");
		hLEDpertime->GetYaxis()->SetTitle("# of LED events");

		TH1D *hAvgMuonQDC = new TH1D("hAvgMuonQDC","Muon Multiplicity vs Muon Avg QDC value",1000,0,5000);
	 	hAvgMuonQDC->GetXaxis()->SetTitle("Muon Avg QDC value");
		hAvgMuonQDC->GetYaxis()->SetTitle("Multiplicity");

	
		Char_t hname[50];
/*		
		for (Int_t j=0; j<numFiles; j++){
			
			for (Int_t i=0; i<numPanels; i++){
				sprintf(hname,"File%dhRawQDC%d",j,i);
				hRawQDC[j][i] = new TH1F(hname,hname,nqdc_bins,ll_qdc,ul_qdc);
				sprintf(hname,"File%dhLEDCutQDC%d",j,i);
				hLEDCutQDC[j][i] = new TH1F(hname,hname,nqdc_bins,ll_qdc,ul_qdc);
				sprintf(hname,"File%dhMuonCutQDC%d",j,i);
				hMuonCutQDC[j][i] = new TH1F(hname,hname,nqdc_bins,ll_qdc,ul_qdc);
			}
		}
*/
		for (Int_t i=0; i<numFiles; i++){
			sprintf(hname,"ledTime_run%d",i);
			ledTime[i] = new TH1F(hname,hname,nqdc_bins,ll_qdc,ul_qdc);

		}

		for (Int_t i=0; i<numPanels; i++){
			sprintf(hname,"MuonMultiplicityGT%d",i);
			hMuonMult[i] = new TH1F(hname,hname,32,0,32);
			sprintf(hname,"MuonManyTrigQDCPanel%d",i);
			hMuonManyQDC[i] = new TH1F(hname,hname,3600,0,3600);
			sprintf(hname,"hLEDAvgQDCPanel%d",i);
			hLEDAvgQDCPanel[i] = new TH1F(hname,hname,runspace,runmin,runmax);
			sprintf(hname,"hLEDrmsQDCPanel%d",i);
			hLEDrmsQDCPanel[i] = new TH1F(hname,hname,runspace,runmin,runmax);
		}

	//=== End ===


	// Loop over files
	while(true){

		// initialize 
		InputList >> run;
		if (InputList.eof()) 		break;
		sprintf(TheFile,"/global/project/projectdirs/majorana/data/mjd/surfmjd/data/built/P3JDY/OR_run%u.root",run); 	
		TChain *VetoTree = new TChain("VetoTree");
		VetoTree->AddFile(TheFile);
		Long64_t nentries = VetoTree->GetEntries();
		
		MJTRun *VetoRun = new MJTRun();
		MGTBasicEvent *vetoEvent = new MGTBasicEvent();
		UInt_t mVeto = 0;
		
		//set branch addresses
		VetoTree->SetBranchAddress("run",&VetoRun);
		VetoTree->SetBranchAddress("mVeto",&mVeto);
		VetoTree->SetBranchAddress("vetoEvent",&vetoEvent);
	
	

		// Unsigned int from MGTypes.hh -- kData=0, kTest=1, kCalibration=2, kMC=3, kUndefined=4																	  
		printf("Run Type: %u\n",VetoRun->GetRunType());  
		
//-------------

    	//=== Single-file counters / variables / plots

			Bool_t IsEmpty = false;

			Int_t BadTSInFile = 0;
			Float_t corruption = 0;
			if (PlotCorruptedEntries) {
				TH1D *CorruptionInTime = new TH1D("CorruptionInTime","corrupted entries during run (entry method)",(Int_t)duration/5,0,(Int_t)duration);
				CorruptionInTime->GetXaxis()->SetTitle("time (5 sec / bin)");
			}
			
			Int_t lednumPanelsHit = 0;
			Int_t muonnumPanelsHit = 0;
			runnum[filesScanned] = run;
			
			Float_t MuonQDCtot = 0;
			Float_t AvgMuonQDCvalue = 0;
			
			sprintf(hname,"ledtimestamp_run%d",run);
			ledtimestamp[filesScanned] = new TGraph(nentries);
			ledtimestamp[filesScanned]->SetName(hname);
			
			//check if runmin and runmax are correct
			if (filesScanned == 0 && runmin != run){
				cout << "Runmin is not set correctly (should be first run number in debug list" << endl;
				break;
			}	
			
			if (filesScanned == numFiles -1 && runmax != run){
				cout << "Runmax is not set correctly (should be last run number in debug list" << endl;
				break;
			}
			
			if (PlotMultiplicity) {
				TH1D *OneRunMultiplicity = new TH1D("multiplicity","multiplicity of veto entries",32,0,32);
  				OneRunMultiplicity->GetXaxis()->SetTitle("number of panels hit");
  			}
			
			TGraph *AvgFileLEDQDCgraph = new TGraph(numFiles);
			AvgFileLEDQDCgraph->SetTitle("Average LED QDC value per file");
			AvgFileLEDQDCgraph->GetXaxis()->SetTitle("File Number");
			AvgFileLEDQDCgraph->GetYaxis()->SetTitle("Avg QDC value");

			TGraph *ledFiletime = new TGraph(numFiles);
			ledFiletime->SetTitle("# of LEDs vs run number");
			ledFiletime->GetXaxis()->SetTitle("Run number");
			ledFiletime->GetYaxis()->SetTitle("Total # of LEDs");
			
			TGraph *ledfitslope = new TGraph(numFiles);
			ledfitslope->SetTitle("(# of led vs run duration) linear fit slope vs run number");
			ledfitslope->GetXaxis()->SetTitle("Run number");
			ledfitslope->GetYaxis()->SetTitle("slope (corresponds to frequency)");

		//=== End ===

		// Loop over VetoTree entries
		printf("Now scanning run %i: %lli entries, %.2f sec.  \n",run,nentries,duration);
		if (nentries == 0) IsEmpty = true;
		for (int z = 0; z < nentries; z++) {
				VetoTree->GetEntry(z);
				
				//Access run duration
				duration = VetoRun->GetStopTime() - VetoRun->GetStartTime();
				
				// Access the MJTVetoData objects "vd"
				MJTVetoData *vd[numPanels];
				for (int i=0; i<numPanels; i++) { vd[i] = dynamic_cast<MJTVetoData*>(vetoEvent->GetDetectorData()->At(i)); }
				
				if (vd[0]->GetEventCount() != vd[0]->GetScalerCount()) 
				printf("Warning!  EventCount and ScalerCount don't match!\n");
		
				Bool_t isBadTS = vd[0]->IsBadTS();
				double TimeStamp = vd[0]->GetTimeStamp()/1E8; //scaler timestamp in seconds
					
				//sort data into arrays
				// Sort raw data into arrays and then display.
				// This may not be totally necessary, but makes hit pattern analysis easier
				//   to match to the physical veto panel locations, and Yuri's wiring diagrams.
				// Most things are cast to int's.  
				// Original types can be found in MJTVetoData.hh and MGDetectorData.hh if necessary.
				const int card1 = 13;
				const int card2 = 18;
				int Card[numPanels] = {0};
				int QDC[numPanels] = {0};
				int IsUnderThreshold[numPanels] = {0};
				int IsOverflow[numPanels] = {0};
				int ID[numPanels] = {0};
				long Index[numPanels] = {0};
				int k = 0;
				for (int j = 0; j<numPanels; j++)	{
					if (vd[j]){
						k = vd[j]->GetChannel();	// goes from 0 to 15
						if (vd[j]->GetCard() == card1) {
							Card[k] = vd[j]->GetCard();
							QDC[k] = (int)vd[j]->GetAmplitude();
							IsUnderThreshold[k] = (int)vd[j]->IsUnderThreshold();
							IsOverflow[k] = (int)vd[j]->IsOverflow();
							ID[k] = vd[j]->GetID();
							Index[k] = (Long_t)vd[j]->GetIndex();
						}
						else if (vd[j]->GetCard() == card2) {
							Card[16+k] = vd[j]->GetCard();
							QDC[16+k] = (int)vd[j]->GetAmplitude();
							IsUnderThreshold[16+k] = (int)vd[j]->IsUnderThreshold();
							IsOverflow[16+k] = (int)vd[j]->IsOverflow();	
							ID[16+k] = vd[j]->GetID();
							Index[16+k] = (Long_t)vd[j]->GetIndex();
						}
					}
				}
				
		

				//=====================BEGIN ACTUAL GODDAMMED ANALYSIS=================
				//change Bool_t isLED to isIdentified? (0=unidentified, 1 = LED, 2 = muon)?


				Bool_t isLED = false; 		//if true, event is LED (first assume event is not an LED)
		
				if (isBadTS) { 
					BadTSInFile++;
					TotalCorruptionInTime->Fill(TimeStamp);
					if (PlotCorruptedEntries) CorruptionInTime->Fill(TimeStamp);
				}

				// multiplicity of panels above threshold
		       		for (int k=0; k<numPanels; k++) { 
				//	hRawQDC[filesScanned][k]->Fill(QDC[k]);
				
				

				// count lednumPanelsHit and muonnumPanelsHit
				if (useThresh) { 
					if (QDC[k]>ledthresh[k]) lednumPanelsHit++; 
					if (QDC[k]>muonthresh[k]) muonnumPanelsHit++;
				}
				else { if (!IsUnderThreshold[k]) lednumPanelsHit++; }
				
				}
		      		TotalMultiplicity->Fill(lednumPanelsHit);			
		       		if (PlotMultiplicity) OneRunMultiplicity->Fill(lednumPanelsHit);

				if (lednumPanelsHit >= 2){
					hLEDCutMulttest->Fill(lednumPanelsHit);
				}

				//include LED cut
				if (lednumPanelsHit >= ledcut){
					isLED = true; // if true, marks the signal as an LED
					hLEDCutMult->Fill(lednumPanelsHit);
					ledcount[filesScanned] +=1;
/*					if(filesScanned == 0) {
						cout << "led count for file 0 is: " << ledcount[filesScanned] << endl;
					}
*/
					//fill ledtimestamp
					ledtimestamp[filesScanned]->SetPoint(ledcount[filesScanned], TimeStamp, ledcount[filesScanned]);
	
					hLEDpertime->Fill(TimeStamp,ledcount[filesScanned]);
					ledTime[filesScanned]->Fill(TimeStamp,ledcount[filesScanned]);
					
					if (ledcountmax[filesScanned] < ledcount[filesScanned]) ledcountmax[filesScanned] = ledcount[filesScanned];

					if (ledtimemax[filesScanned] < TimeStamp) ledtimemax[filesScanned] = TimeStamp;
					
					for (int k=0; k<numPanels; ++k) {
						if (useThresh) { 
							if (QDC[k]>ledthresh[k]){
							//	hLEDCutQDC[filesScanned][k]->Fill(QDC[k]);
								ledQDCcount[filesScanned][k] += 1;
								totledQDC[filesScanned][k] += QDC[k];
								quadtotledQDC[filesScanned][k] += QDC[k]*QDC[k];
								
							}
						}
						else {
						//	if (!IsUnderThreshold[k]) hLEDCutQDC[filesScanned][k]->Fill(QDC[k]); 
						}	
						
					}
					//find deltat
					Tnew = TimeStamp;
					//see if 0 in deltat is from the first event
					if (ledcount[filesScanned] == 1 | ledcount[filesScanned] == 2){
//						cout << "led count = " << ledcount[filesScanned] << " | Timestamp = " << Tnew << endl;
					}					
					deltaT = Tnew - Told;
					if (deltaT < 0.01 || deltaT > 10000){
					lowdt << "delta T = " << deltaT << " | led #'s = " << ledcount[filesScanned]-1 << " and " << ledcount[filesScanned] << "run # = " << run << endl;

					}
					Told = Tnew;
					hLEDCutDT->Fill(deltaT);
					hLEDCutDTFocus->Fill(deltaT);
					if (TimeStamp > 10000){
						badtimecount++;
					}
	
				}
			
				//count multiplicity for muon cut
				if (!isLED && muonnumPanelsHit > 2 && muonnumPanelsHit < ledcut){
					muoncount[filesScanned] += 1;
										
					for (Int_t k=0; k<numPanels; k++){
						if (muonnumPanelsHit > k) hMuonMult[k]->Fill(muonnumPanelsHit);
						if(QDC[k]>muonthresh[k]){
							//hMuonCutQDC[filesScanned][k]->Fill(QDC[k]);
							hMuonManyQDC[k]->Fill(QDC[k]);
							MuonQDCtot += QDC[k];
						}
					}			
					AvgMuonQDCvalue = MuonQDCtot/((double) muonnumPanelsHit);
					hAvgMuonQDC->Fill(AvgMuonQDCvalue);
					MuonQDCtot = 0;
					
				}
				
				//=====================END ACTUAL GODDAMMED ANALYSIS===================
			
			lednumPanelsHit=0;
			muonnumPanelsHit=0;

		}	// End loop over VetoTree entries.

		// === END OF FILE Output & Plotting ===
		if (filesScanned == 0){
			TDirectory *runmultiplicity = RootFile->mkdir("RunMultiplicity");	
			TDirectory *corruptionintime = RootFile->mkdir("CorruptionInTime");
		}
		
		corruption = ((Float_t)BadTSInFile/nentries)*100;
		printf(" Corrupted scaler entries: %i of %lli, %.3f %%.\n",BadTSInFile,nentries,corruption);
		if(run>45000000) SCorruption->SetPoint(filesScanned,run-45000000,corruption);
		else SCorruption->SetPoint(filesScanned,run,corruption);

		if (PlotCorruptedEntries) {
			RootFile->cd("CorruptionInTime");
			char outfile1[200];	
			sprintf(outfile1,"CorruptionInTime_Run%i",run);
			CorruptionInTime->Write(outfile1,TObject::kOverwrite);
			RootFile->cd();
		}
		if (PlotMultiplicity) {
			RootFile->cd("RunMultiplicity");
			char outfile2[200];
			sprintf(outfile2,"Multiplicity_Run%i",run);
			OneRunMultiplicity->Write(outfile2,TObject::kOverwrite);
			RootFile->cd();
		}

		if (!IsEmpty && ledcount[filesScanned] > 2){
			ledTime[filesScanned]->Fit("pol1");
			slope[filesScanned] = ledTime[filesScanned]->GetFunction("pol1")->GetParameter(1);
		}
		
		for (int j=0; j<numFiles; ++j){
			ledFiletime->SetPoint(j, runnum[j], ledcount[j]);
		}

		// ==========================

		delete VetoTree;
		cout << "files Scanned: " << filesScanned << endl;
		if (duration >= 0){
			totdur += duration;
		}
		if (duration < 0){
			omitteddur[baddurcount]=run;
			baddurcount +=1;
		}
		cout << "totdur = " << totdur << " | duration = " << duration << endl;
		filesScanned++;
	} // End loop over files.

	//calculate/fill qdc mean and rms
	for (int k=0; k<numPanels; ++k){
		for (int j=0; j<numFiles; ++j){
			if(k == 15){
				AvgledQDC[j][k] = 0;
				rmsledQDC[j][k] = 0;
			}
			else{
				AvgledQDC[j][k] = totledQDC[j][k]/ledQDCcount[j][k];
				rmsledQDC[j][k] = sqrt(quadtotledQDC[j][k]/ledQDCcount[j][k]);
			}
			hLEDAvgQDCPanel[k]->Fill(runnum[j],AvgledQDC[j][k]);
			hLEDrmsQDCPanel[k]->Fill(runnum[j],rmsledQDC[j][k]);
//		cout << "panel number: " << k << " | mean value " << AvgQDC[k] << " | rms value " << rmsQDC[k] << endl;
		}
	} 

	//calculate qdc mean for each file
	for (int j=0; j<numFiles; ++j){		
		for (int k=0; k<numPanels; ++k){
			totFileLEDQDC[j] += totledQDC[j][k];
			totFileledQDCcount[j] += ledQDCcount[j][k];
		}
		AvgFileLEDQDC[j] = totFileLEDQDC[j]/totFileledQDCcount[j];
		AvgFileLEDQDCgraph->SetPoint(j, runnum[j], AvgFileLEDQDC[j]);
		if (!IsEmpty){
			ledfitslope->SetPoint(j,runnum[j],slope[j]);
		}
	}
	
	for (int i=0; i<numFiles; ++i){
		printf("led count for file %i: %i. \n", i,ledcount[i]);	
		totledcount += ledcount[i];

		printf("muon count for file %i: %i. \n", i,muoncount[i]);	
		totmuoncount += muoncount[i];
	}

	// === END OF SCAN Output & Plotting ===
	printf("Finished loop over files.\n");
	printf("Total # of Files: %i. \n",numFiles);
	printf("Total Duration: %f seconds. \n",totdur);
	printf("Total LED Count: %f. \n", totledcount);
	printf("Total Muon Count: %f. \n", totmuoncount);	
	printf("Number of Bad Durations: %f. \n", baddurcount);
	

//	TCanvas *c1 = new TCanvas("c1", "Bob Ross's Canvas",600,600);
//	c1->SetGrid();
	SCorruption->SetMarkerColor(4);
	SCorruption->SetMarkerStyle(21);
	SCorruption->SetMarkerSize(0.5);
	SCorruption->SetTitle("Corruption in scaler card");
	SCorruption->GetXaxis()->SetTitle("Run");
	SCorruption->GetYaxis()->SetTitle("% corrupted events");
//	SCorruption->Draw("ALP");	
	
	SCorruption->Write("ScalerCorruption",TObject::kOverwrite);

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

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


//	TCanvas *c2 = new TCanvas("c2", "LEDCutMult",600,600);
//	c2->SetGrid();
//	c2->SetLogy();
//	hLEDCutMult->Draw();
	hLEDCutMult->Write();

//	TCanvas *c3 = new TCanvas("c3", "LEDCutMulttest",600,600);
//	c3->SetGrid();
//	c3->SetLogy();
//	hLEDCutMulttest->Draw();
	hLEDCutMulttest->Write();

//	TCanvas *c4 = new TCanvas("c4", "LEDCutDT",600,600);
//	c4->SetGrid();
//	hLEDCutDT->Draw();
	hLEDCutDT->Write();

//	TCanvas *c5 = new TCanvas("c5", "AvgFileLEDQDCgraph",600,600);
//	c5->SetGrid();
	AvgFileLEDQDCgraph->SetMarkerColor(4);
	AvgFileLEDQDCgraph->SetMarkerStyle(21);
	AvgFileLEDQDCgraph->SetMarkerSize(0.5);
//	AvgFileLEDQDCgraph->Draw("AP");	
	AvgFileLEDQDCgraph->Write("AvgFileLEDQDCgraph",TObject::kOverwrite);


//	TCanvas *c6 = new TCanvas("c6", "ledFiletime",600,600);
//	c6->SetGrid();
	ledFiletime->SetMarkerColor(4);
	ledFiletime->SetMarkerStyle(21);
	ledFiletime->SetMarkerSize(0.5);
//	ledFiletime->Draw("ALP");	
	ledFiletime->Write("LEDFileTime",TObject::kOverwrite);


//	TCanvas *c7 = new TCanvas("c7", "LEDpertime",600,600);
//	c7->SetGrid();
//	hLEDpertime->Draw();
//	hLEDpertime->Write();

//	TCanvas *c9 = new TCanvas("c9", "slope vs file number", 600,600);
//	c9->SetGrid();
	ledfitslope->SetMarkerColor(4);
	ledfitslope->SetMarkerStyle(21);
	ledfitslope->SetMarkerSize(0.5);
//	ledfitslope->Draw("ALP");	
	ledfitslope->Write("LEDFitSlope",TObject::kOverwrite);
	
//	TCanvas *c10 = new TCanvas("c10", "avg muon qdc value", 600,600);
//	c10->SetGrid();
//	hAvgMuonQDC->Draw();
	hAvgMuonQDC->Write();
	
//	TCanvas *c11 = new TCanvas("c11", "LEDCutDTFocus",600,600);
//	c11->SetGrid();
//	hLEDCutDTFocus->Draw();
	hLEDCutDTFocus->Write();
	
//	TCanvas *vcan0 = new TCanvas("vcan0","raw veto QDC, panels 1-32",0,0,1600,900);
//	vcan0->Divide(8,4,0,0);
	
//	TCanvas *vcan1 = new TCanvas("vcan1","LED Cut veto QDC (ledcut = 20), panels 1-32",0,0,1600,900);
//	vcan1->Divide(8,4,0,0);

//	TCanvas *vcan2 = new TCanvas("vcan2","Muon Cut veto QDC (all qdc over muon thresh), panels 1-32",0,0,1600,900);
//	vcan2->Divide(8,4,0,0);

//	TCanvas *vcan9 = new TCanvas("vcan9","Muon Cut Multiplicity (muon cut = 0-31)", 0,0,1600,900);
//	vcan9->Divide(8,4,0,0);	
//	TCanvas *vcan10 = new TCanvas("vcan10","LED event vs time (ledcut = 20), files 1-2",0,0,800,600);
//	vcan10->Divide(2);
	
//	TCanvas *vcan11 = new TCanvas("vcan11","Muon QDC numPanelsHit > 2 && < 20", 0,0,1600,900);
//	vcan11->Divide(8,4,0,0);

//	TCanvas *vcan12 = new TCanvas("vcan12","Avg LED QDC", 0,0, 1600,900);
//	vcan12->Divide(8,4,0,0);

//	TCanvas *vcan13 = new TCanvas("vcan13","rms LED QDC", 0,0,1600,900);
//	vcan13->Divide(8,4,0,0);

//	TCanvas *vcan14 = new TCanvas("vcan14","ledtimestamps",0,0,1600,900);
	
	
	Char_t buffer[2000];
	printf("\n Calibration Table:\n  Panel / Mean,error / Sigma,error / Chi-square/NDF (~1?) / LED Peak Pos.\n");

	
	RootFile->Write();

	TDirectory *ledtime = RootFile->mkdir("LEDTime");
	for (Int_t i=0; i<filesToScan; i++){

		RootFile->cd("LEDTime");
//		vcan10->cd(i+1);
//		TVirtualPad *vpad10 = vcan10->cd(i+1);
//		ledTime[i]->Draw();
		ledTime[i]->Write();

	}
	
	TDirectory *rawqdc = RootFile->mkdir("RawQDC");
	TDirectory *ledcutqdc = RootFile->mkdir("LEDCutQDC");
	TDirectory *muoncutqdc = RootFile->mkdir("MuonCutQDC");
	TDirectory *muonmult = RootFile->mkdir("MuonMult");
	TDirectory *muonmanyqdc = RootFile->mkdir("MuonManyQDC");
	TDirectory *avgledqdc = RootFile->mkdir("AvgLEDQDC");
	TDirectory *rmsledqdc = RootFile->mkdir("rmsLEDQDC");
	TDirectory *ledtimestamps = RootFile->mkdir("LEDTimestamps");

	
	for (Int_t j=0; j<numFiles; j++){


		for (Int_t i=0; i<numPanels; i++){
		
			RootFile->cd("RawQDC");
//			vcan0->cd(i+1);
//			TVirtualPad *vpad0 = vcan0->cd(i+1); vpad0->SetLogy();
//			hRawQDC[j][i]->Draw();
//			hRawQDC[j][i]->Write();		// write the raw QDC without fitting

			
			RootFile->cd("LEDCutQDC");
//			vcan1->cd(i+1);
//			TVirtualPad *vpad1 = vcan1->cd(i+1); vpad1->SetLogy();
//			hLEDCutQDC[j][i]->Draw();
//			hLEDCutQDC[j][i]->Write();		
		
			RootFile->cd("MuonCutQDC");
//			vcan2->cd(i+1);
//			TVirtualPad *vpad2 = vcan2->cd(i+1); vpad2->SetLogy();
//			hMuonCutQDC[j][i]->Draw();
//			hMuonCutQDC[j][i]->Write();	

		}
		RootFile->cd("LEDTimestamps");
//		vcan14->cd(1);
//		vcan14->SetLogy();
		ledtimestamp[j]->SetMarkerColor(4);
		ledtimestamp[j]->SetMarkerStyle(21);
		ledtimestamp[j]->SetMarkerSize(0.5);
		ledtimestamp[j]->SetTitle("ledcount vs timestamp");
		ledtimestamp[j]->GetXaxis()->SetTitle("timestamp");
		ledtimestamp[j]->GetYaxis()->SetTitle("ledcount");
//		ledtimestamp[j]->Draw("ALP");	
		ledtimestamp[j]->Write();
		
	}
	
	RootFile->cd("MuonManyQDC");
	for (Int_t i=0; i<numPanels; i++){
//		vcan11->cd(i+1);
//		TVirtualPad *vpad11 = vcan11->cd(i+1); vpad11->SetLogy();
		hMuonManyQDC[i]->GetYaxis()->SetTitle("Multiplicity");
		hMuonManyQDC[i]->GetXaxis()->SetTitle("QDC Values");
//		hMuonManyQDC[i]->Draw();
		hMuonManyQDC[i]->Write();
	
	}
	RootFile->cd("MuonMult");
	for (Int_t i=0; i<numPanels; i++){
//		vcan9->cd(i+1);
//		TVirtualPad *vpad9 = vcan9->cd(i+1); vpad9->SetLogy();
		hMuonMult[i]->GetYaxis()->SetTitle("Multiplicity");
		hMuonMult[i]->GetXaxis()->SetTitle("# of panels hit");
//		hMuonMult[i]->Draw();
		hMuonMult[i]->Write();
	}

	RootFile->cd("AvgLEDQDC");
	for (Int_t i=0; i<numPanels; i++){
//		vcan12->cd(i+1);
//		TVirtualPad *vpad12 = vcan12->cd(i+1); vpad12->SetLogy();
		hLEDAvgQDCPanel[i]->GetYaxis()->SetTitle("Avg QDC value");
		hLEDAvgQDCPanel[i]->GetXaxis()->SetTitle("Run Number");
//		hLEDAvgQDCPanel[i]->Draw();
		hLEDAvgQDCPanel[i]->Write();
	}

	RootFile->cd("rmsLEDQDC");
	for (Int_t i=0; i<numPanels; i++){
//		vcan13->cd(i+1);
//		TVirtualPad *vpad13 = vcan13->cd(i+1); vpad13->SetLogy();
		hLEDAvgQDCPanel[i]->GetYaxis()->SetTitle("rms QDC value");
		hLEDAvgQDCPanel[i]->GetXaxis()->SetTitle("Run Number");
//		hLEDrmsQDCPanel[i]->Draw();
		hLEDrmsQDCPanel[i]->Write();
	}

	RootFile->cd();

	// ==========================

	RootFile->Close();

	cout << "badtimecount = " << badtimecount << endl;
	cout << "Wrote ROOT file." << endl;
	
	lowdt.close();

}
void run_root_TSelector_SusyNtuple_Muons_1() {

//  TString options = TString(""); //TString(tag.c_str()) ;
// //     TString outputfile = "test.root";
//     string richtigerString = InputPath;
// //     int Position = richtigerString.find("mc12_8TeV.");
// //     outputfile = "histos_ZTauTau_" +  richtigerString.substr(Position+10,6)  + "_proof.root";
//     
//     int Position = -1;
//     Position = richtigerString.find("45_bg");
//     if (Position>0){
//       outputfile = "histos_test_" +  richtigerString.substr(Position+6,2)  + ".root";
//     }
//     else{
//       Position = richtigerString.find("45_signal");
//       if (Position>0){
//       outputfile = "histos_test_" +  richtigerString.substr(Position+3,2)  + ".root";
//       }
//     }
//     if(outputfile == ""){
//       cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
//       cout << "EMPTY OUPTPUTFILE STRING" << endl;
//       cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
//       abort();
//     }
//     cout << "outputfile= " << outputfile << endl;
    
      cout<<"Have you set up RootCore via  \"source RootCore/scripts/setup.sh\" ?"<<endl;  

      gSystem->Setenv("ROOTCOREDIR", "/data/etp3/jwittkow/analysis_SUSYTools_03_04_SusyNt_01_16/RootCore");
      gSystem->SetIncludePath("-I$ROOTCOREDIR/include/");

      gROOT->ProcessLine(".x $ROOTCOREDIR/scripts/load_packages.C+"); 

      TString selectorName = "TSelector_SusyNtuple"; // !!! enter the name of your Selector (without _C.so)

      TChain *ch;

      ch = new TChain("susyNt");


      TString processLine = ".L " + selectorName + ".cpp++g";
      TString execLine;

      gROOT->ProcessLine(processLine); // need to add this, or PoD at LRZ will not be able to load the .so
      gROOT->ProcessLine(".x $ROOTCOREDIR/scripts/load_packages.C+");
//======================================             1                                  ============================================================================================
      ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodA.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708165423/*");
      ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodA.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708165447/*");
      ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodA.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708165507/*");
      ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodA.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708165547/*");
      ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodA.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708165619/*");
      ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodA.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708165710/*");
      ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodB.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708165732/*");
      ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodB.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708165801/*");
      ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodB.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708165829/*");
      ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodB.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708165907/*");
      ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodB.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708165935/*");
      //-------------------------------
      //======================================             2                                  ============================================================================================
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodB.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170005/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodB.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130709051736/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodB.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130709212230/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodB.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130709212332/*");   
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodB.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130709212411/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodC.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170128/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodC.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170157/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodC.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170223/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodC.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170245/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodC.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170315/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodC.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130709051801/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodD.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170353/*");
      //-------------------------------
//======================================             3                                 ============================================================================================
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodD.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170420/*");      
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodD.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170458/*");  
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodD.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170524/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodD.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170550/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodD.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170614/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodD.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170645/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodD.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130709051836/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodD.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130709212549/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodE.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170738/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodE.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170757/*");
      //-------------------------------
      //======================================             4                                 ============================================================================================
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodE.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170819/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodE.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170844/*");    
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodE.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170905/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodE.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708170956/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodG.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708171047/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodG.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708171104/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodG.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708171121/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodG.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708171154/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodG.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708171226/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodG.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708171251/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodH.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708171315/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodH.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708171342/*");
      //-------------------------------
     //======================================             5                                  ============================================================================================
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodH.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708171402/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodH.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708171419/*");  
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodH.physics_Muons.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708171442/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodI.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708171503_rev117460/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodI.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708171521/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodI.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708171541/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodI.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708171559/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodI.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708171646/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodI.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130710002540/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodJ.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708171724/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodJ.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708171804/*");
      //-------------------------------
      //======================================             6                                  ============================================================================================
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodJ.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708171839/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodJ.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708171907/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodJ.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708171941/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodJ.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708172025/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodJ.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708172123/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodJ.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130709052308/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodJ.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130709213130/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodL.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708172211/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodL.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708172233/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodL.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708172252/*");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Muons/user.sfarrell.group.phys-susy.data12_8TeV.periodL.physics_Muons.PhysCont.SusyNt.t0pro14_v01_p1542_n0145.130708172319/*");


      Long64_t nEntries = ch->GetEntries();
      ch->ls();

      cout << "all entries: " << nEntries << endl;


      TSelector_SusyNtuple* susyAna = new TSelector_SusyNtuple();
      susyAna->buildSumwMap(ch);
      ch->Process(susyAna);
      delete susyAna;
      cout << "run_root_TSelector_SusyNtuple_Muons_1 processed" << endl;
      if (ch) {delete ch; ch=0;}

  abort();
  }
void revCalSimulation (Int_t runNumber, string b, string A) 
{

  int numFiles = 180;//(b==std::string("inf")?200:(A==std::string("-1")?200:20));

  bool allEvtsTrigg = false; //This just removes the use of the trigger function for an initial calibration. 
                            // Once a calibration is established (or if running on Betas), you can keep this false

  bool simProperStatistics = false; // If True, this uses the actual data run to determine the number of Type 0s to simulate

  
  cout << "Running reverse calibration for run " << runNumber << endl;  

  UInt_t BetaEvents = 0; //Holds the number of electron like Type 0 events to process

  Char_t temp[500],tempE[500],tempW[500];
  
  //First get the number of total electron events around the source position from the data file and also the length of the run
  
  //sprintf(temp,"%s/replay_pass4_%i.root",getenv("REPLAY_PASS4"),runNumber);
  sprintf(temp,"%s/replay_pass3_%i.root",getenv("REPLAY_PASS3"),runNumber);
  TFile *dataFile = new TFile(temp,"READ");
  TTree *data = (TTree*)(dataFile->Get("pass3"));
  
  sprintf(tempE,"Type<4 && Type>=0 && PID==1 && Side==0 && (xE.center*xE.center+yE.center*yE.center)<2500. && (xW.center*xW.center+yW.center*yW.center)<2500.");
  sprintf(tempW,"Type<4 && Type>=0 && PID==1 && Side==1 && (xW.center*xW.center+yW.center*yW.center)<2500. && (xE.center*xE.center+yE.center*yE.center)<2500.");
 
  BetaEvents = data->GetEntries(tempE) + data->GetEntries(tempW);
  cout << "Electron Events in Data file: " << BetaEvents << endl;
  cout << "East: " << data->GetEntries(tempE) << "\tWest: " << data->GetEntries(tempW) << endl;
  delete data;
  dataFile->Close(); 
  
  
  //If we have a Beta run and we don't want exact statistics, simulate 16 times the number of events
  if ( !simProperStatistics  ) {
    BetaEvents = 100*BetaEvents;
  } 

  std::cout << "Processing " << BetaEvents << " events...\n";



  ///////////////////////// SETTING GAIN OF FIRST and second DYNYODE
  Double_t g_d = 16.;
  Double_t g_rest = 12500.;

  /////// Loading other run dependent quantities
  vector <Int_t> pmtQuality = getEreconPMTQuality(runNumber); // Get the quality of the PMTs for that run
  UInt_t calibrationPeriod = getSrcRunPeriod(runNumber); // retrieve the calibration period for this run
  UInt_t XePeriod = getXeRunPeriod(runNumber); // Get the proper Xe run period for the Trigger functions
  //GetPositionMap(XePeriod);
  PositionMap posmap(5.0,50.); //Load position map with 5 mm bins
  posmap.readPositionMap(XePeriod,"endpoint");
  vector <Double_t> alpha = GetAlphaValues(calibrationPeriod); // fill vector with the alpha (nPE/keV) values for this run period


  /////////////// Load trigger functions //////////////////
  TriggerFunctions trigger(runNumber);

  std::vector < std::vector <Double_t> > pedestals = loadPMTpedestals(runNumber);
  std::vector < Double_t > PMTgain = loadGainFactors(runNumber);

  //Load the simulated relationship between EQ and Etrue
  EreconParameterization eRecon(runNumber);
  // Int_t pol = source=="Beta" ? getPolarization(runNumber) : 1;

  LinearityCurve linCurve(calibrationPeriod,false);
  std::cout << "Loaded Linearity Curves\n";

  //Decide which simulation to use...
  TChain *chain = new TChain("anaTree"); 

  std::string geom;
  if (runNumber<20000) geom = "2011-2012_geom";
  else if (runNumber>=21087 && runNumber<21679) geom = "2012-2013_isobutane_geom";
  else geom = "2012-2013_geom";
  
  TString fileLocation = TString::Format("/extern/mabrow05/ucna/xuan_stuff/AbFit_Fierz_2011-2013/%s/A_%s_b_%s/",
					 geom.c_str(),A.c_str(),b.c_str());
 
  std::cout << "Using simulation from " << fileLocation << "...\n";

  //Read in simulated data and put in a TChain
  TRandom3 *randFile = new TRandom3(runNumber*2);
  
  int fileNum = (int)(randFile->Rndm()*numFiles);
  delete randFile;
  for (int i=0; i<numFiles; i++) {
    if (fileNum==numFiles) fileNum=0;
    chain->AddFile(TString::Format("%s/xuan_analyzed_%i.root",fileLocation.Data(),fileNum));
    fileNum++;
  }

  // Set the addresses of the information read in from the simulation file
  /*chain->SetBranchAddress("MWPCEnergy",&mwpcE);       x
  chain->SetBranchAddress("time",&Time);                x
  chain->SetBranchAddress("Edep",&edep);                x
  chain->SetBranchAddress("EdepQ",&edepQ);              x
  chain->SetBranchAddress("MWPCPos",&mwpc_pos);         x 
  chain->SetBranchAddress("ScintPos",&scint_pos);       x
  chain->SetBranchAddress("primKE",&primKE);            x
  chain->SetBranchAddress("primTheta",&primTheta);
  chain->SetBranchAddress("Cath_EX",Cath_EX);
  chain->SetBranchAddress("Cath_EY",Cath_EY);
  chain->SetBranchAddress("Cath_WX",Cath_WX);
  chain->SetBranchAddress("Cath_WY",Cath_WY);
  chain->SetBranchAddress("hitCountSD",hitCountSD);*/
  
  //These are for feeding in Xuan's simulations... this needs to be updated so that I can pass a flag and change these on the fly
  chain->SetBranchAddress("primaryParticleSpecies",&primaryID);
  chain->SetBranchAddress("mwpcEnergy",&mwpcE);
  chain->SetBranchAddress("scintTimeToHit",&Time);
  chain->SetBranchAddress("scintillatorEdep",&edep);
  chain->SetBranchAddress("scintillatorEdepQuenched",&edepQ);
  chain->SetBranchAddress("MWPCPos",&mwpc_pos);
  chain->SetBranchAddress("ScintPos",&scint_pos);
  chain->SetBranchAddress("primaryKE",&primKE);
  chain->SetBranchAddress("primaryMomentum",primMom);


  //Set random number generator

  TRandom3 *seed = new TRandom3( 3*runNumber ); // seed generator
  TRandom3 *rand0 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *rand1 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *rand2 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *rand3 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );

  //Initialize random numbers for 8 pmt trigger probabilities
  TRandom3 *randPMTE1 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *randPMTE2 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *randPMTE3 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *randPMTE4 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *randPMTW1 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *randPMTW2 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *randPMTW3 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );
  TRandom3 *randPMTW4 = new TRandom3( (unsigned int) (seed->Rndm()*10000.) );

  std::vector <Double_t> triggRandVec(4,0.);

  // Wirechamber information
  bool EastScintTrigger, WestScintTrigger, EMWPCTrigger, WMWPCTrigger; //Trigger booleans
  Double_t MWPCAnodeThreshold=0.; // keV dep in the wirechamber.. 


  //Get total number of events in TChain
  UInt_t nevents = chain->GetEntries();
  cout << "events = " << nevents << endl;
 
  //Start from random position in evt sequence if we aren't simulating veryHighStatistics
  UInt_t evtStart = seed->Rndm()*nevents;
    
  
  UInt_t evtTally = 0; //To keep track of the number of events 
  UInt_t evt = evtStart; //current event number


  vector < vector <Int_t> > gridPoint;

  
  //Create simulation output file
  
  TFile *outfile = new TFile(TString::Format("%s/revCalSim_%i.root",fileLocation.Data(),runNumber), "RECREATE");

  //Setup the output tree
  TTree *tree = new TTree("revCalSim", "revCalSim");
  SetUpTree(tree); //Setup the output tree and branches

  //Histograms of event types for quick checks
  vector <TH1D*> finalEn (6,NULL);
  finalEn[0] = new TH1D("finalE0", "Simulated Weighted Sum East Type 0", 400, 0., 1200.);
  finalEn[1] = new TH1D("finalW0", "Simulated Weighted Sum West Type 0", 400, 0., 1200.);
  finalEn[2] = new TH1D("finalE1", "Simulated Weighted Sum East Type 1", 400, 0., 1200.);
  finalEn[3] = new TH1D("finalW1", "Simulated Weighted Sum West Type 1", 400, 0., 1200.);
  finalEn[4] = new TH1D("finalE23", "Simulated Weighted Sum East Type 2/3", 400, 0., 1200.);
  finalEn[5] = new TH1D("finalW23", "Simulated Weighted Sum West Type 2/3", 400, 0., 1200.);


  //Read in events and determine evt type based on triggers
  while (evtTally<=BetaEvents) {
    if (evt>=nevents) evt=0; //Wrapping the events back to the beginning
    EastScintTrigger = WestScintTrigger = EMWPCTrigger = WMWPCTrigger = false; //Resetting triggers each event

    chain->GetEvent(evt);

    //Checking that the event occurs within the fiducial volume in the simulation to minimize
    // contamination from edge effects and interactions with detector walls
    // This is also the fiducial cut used in extracting asymmetries and doing calibrations
    Double_t fidCut = 50.;


    /////////////// Do position and Wirechamber stuff ///////////////////
    
    // Following negative sign is to turn x-coordinate into global coordinate on East
    scint_pos_adj.ScintPosAdjE[0] = scint_pos.ScintPosE[0]*sqrt(0.6)*1000.;
    scint_pos_adj.ScintPosAdjE[1] = scint_pos.ScintPosE[1]*sqrt(0.6)*1000.;
    scint_pos_adj.ScintPosAdjW[0] = scint_pos.ScintPosW[0]*sqrt(0.6)*1000.;//sqrt(0.6)*10.*scint_pos.ScintPosW[0]+displacementX;
    scint_pos_adj.ScintPosAdjW[1] = scint_pos.ScintPosW[1]*sqrt(0.6)*1000.;//sqrt(0.6)*10.*scint_pos.ScintPosW[1]+displacementY;
    scint_pos_adj.ScintPosAdjE[2] = scint_pos.ScintPosE[2]*1000.;
    scint_pos_adj.ScintPosAdjW[2] = scint_pos.ScintPosW[2]*1000.;

    
    Double_t mwpcAdjE[3] = {0.,0.,0.};
    Double_t mwpcAdjW[3] = {0.,0.,0.};
   
    mwpcAdjE[0] = mwpc_pos.MWPCPosE[0] * sqrt(0.6) * 1000.; 
    mwpcAdjE[1] = mwpc_pos.MWPCPosE[1] * sqrt(0.6) * 1000.; 
    mwpcAdjW[0] = mwpc_pos.MWPCPosW[0] * sqrt(0.6) * 1000. ;
    mwpcAdjW[1] = mwpc_pos.MWPCPosW[1] * sqrt(0.6) * 1000. ;
    mwpcAdjE[2] = mwpc_pos.MWPCPosE[2] * 1000. ;
    mwpcAdjW[2] = mwpc_pos.MWPCPosW[2] * 1000. ;
    

    
    //std::cout << mwpcAdjE[0] << "\t" << mwpcAdjW[0] << std::endl;
    //if (evtTally==5) exit(0);


    /////////////////////////////////////////////////////////////////////
    // Creating all extra structs to hold the alternate position reconstruction
    // crap before writing it all out
    /////////////////////////////////////////////////////////////////////
    

    std::vector <Double_t> eta; 
    std::vector <Double_t> trueEta; // This is the position map value of the actual event position, not the position as determined
                                    // by cathode reconstruction
    

    trueEta = posmap.getInterpolatedEta(scint_pos_adj.ScintPosAdjE[0],
					scint_pos_adj.ScintPosAdjE[1],
					scint_pos_adj.ScintPosAdjW[0],
					scint_pos_adj.ScintPosAdjW[1]);
   
    eta = posmap.getInterpolatedEta(scint_pos_adj.ScintPosAdjE[0],
				    scint_pos_adj.ScintPosAdjE[1],
				    scint_pos_adj.ScintPosAdjW[0],
				    scint_pos_adj.ScintPosAdjW[1]);

      
      
    //MWPC triggers
    if (mwpcE.MWPCEnergyE>MWPCAnodeThreshold) EMWPCTrigger=true;
    if (mwpcE.MWPCEnergyW>MWPCAnodeThreshold) WMWPCTrigger=true;
    
    std::vector<Double_t> ADCvecE(4,0.);
    std::vector<Double_t> ADCvecW(4,0.);

    //East Side smeared PMT energies
    
    
    for (UInt_t p=0; p<4; p++) {
      if ( edep.EdepE>0. ) { //Check to make sure that there is light to see in the scintillator
	
	if (eta[p]>0.) {

	  pmt.etaEvis[p] = (1./(alpha[p]*g_d*g_rest)) * (rand3->Poisson(g_rest*rand2->Poisson(g_d*rand1->Poisson(alpha[p]*trueEta[p]*edepQ.EdepQE))));
	  Double_t ADC = linCurve.applyInverseLinCurve(p, pmt.etaEvis[p]) + rand0->Gaus(0.,pedestals[p][1]); //Take into account non-zero width of the pedestal
	  ADCvecE[p] = ADC;
	  pmt.etaEvis[p] = linCurve.applyLinCurve(p, ADC);
	  pmt.Evis[p] = pmt.etaEvis[p]/eta[p];

	}

	else { //To avoid dividing by zero.. these events won't be used in analysis since they are outside the fiducial cut
	  
	  pmt.etaEvis[p] = (1./(alpha[p]*g_d*g_rest)) * (rand3->Poisson(g_rest*rand2->Poisson(g_d*rand1->Poisson(alpha[p]*edepQ.EdepQE))));
	  Double_t ADC = linCurve.applyInverseLinCurve(p, pmt.etaEvis[p]);// + rand0->Gaus(0.,pedestals[p][1]); //Take into account non-zero width of the pedestal
	  ADCvecE[p] = ADC;
	  pmt.etaEvis[p] = linCurve.applyLinCurve(p, ADC);
	  pmt.Evis[p] = pmt.etaEvis[p];

	}


	
	pmt.nPE[p] = alpha[p]*pmt.etaEvis[p] ;

      }

    // If eQ is 0...
      else {
	pmt.etaEvis[p] = 0.;
	pmt.Evis[p] = 0.;
	pmt.nPE[p] = 0.;
	
      }
    }
  
    Double_t numer=0., denom=0.;
    
    for (UInt_t p=0;p<4;p++) {
      numer += ( pmtQuality[p] ) ? pmt.nPE[p] : 0.;
      denom += ( pmtQuality[p] ) ? eta[p]*alpha[p] : 0.;
      //numer += ( pmtQuality[p] && pmt.etaEvis[p]>0. ) ? pmt.nPE[p] : 0.;
      //denom += ( pmtQuality[p] && pmt.etaEvis[p]>0. ) ? eta[p]*alpha[p] : 0.;
    }

    
    Double_t totalEnE = denom>0. ? numer/denom : 0.;
    evis.EvisE = totalEnE;

    //Now we apply the trigger probability
    triggRandVec[0] = randPMTE1->Rndm();
    triggRandVec[1] = randPMTE2->Rndm();
    triggRandVec[2] = randPMTE3->Rndm();
    triggRandVec[3] = randPMTE4->Rndm();
    
    if ( (allEvtsTrigg && totalEnE>0.) || ( trigger.decideEastTrigger(ADCvecE,triggRandVec) ) ) EastScintTrigger = true; 
      
    //West Side
    for (UInt_t p=4; p<8; p++) {
      if ( !(p==5 && runNumber>16983 && runNumber<17249) &&  edep.EdepW>0. ) { //Check to make sure that there is light to see in the scintillator and that run isn't one where PMTW2 was dead
	
	if (eta[p]>0.) {

	  pmt.etaEvis[p] = (1./(alpha[p]*g_d*g_rest)) * (rand3->Poisson(g_rest*rand2->Poisson(g_d*rand1->Poisson(alpha[p]*trueEta[p]*edepQ.EdepQW))));
	  Double_t ADC = linCurve.applyInverseLinCurve(p, pmt.etaEvis[p]) + rand0->Gaus(0.,pedestals[p][1]); //Take into account non-zero width of the pedestal
	  ADCvecW[p-4] = ADC;
	  //cout << ADCvecW[p-4] << endl;
	  pmt.etaEvis[p] = linCurve.applyLinCurve(p, ADC);	  
	  pmt.Evis[p] = pmt.etaEvis[p]/eta[p];

	}

	else { //To avoid dividing by zero.. these events won't be used in analysis since they are outside the fiducial cut

	  pmt.etaEvis[p] = (1./(alpha[p]*g_d*g_rest)) * (rand3->Poisson(g_rest*rand2->Poisson(g_d*rand1->Poisson(alpha[p]*edepQ.EdepQW))));
	  Double_t ADC = linCurve.applyInverseLinCurve(p, pmt.etaEvis[p]);// + rand0->Gaus(0.,pedestals[p][1]); //Take into account non-zero width of the pedestal
	  ADCvecW[p-4] = ADC;
	  pmt.etaEvis[p] = linCurve.applyLinCurve(p, ADC);
	  pmt.Evis[p] = pmt.etaEvis[p];
	  
	}

	pmt.nPE[p] = alpha[p]*pmt.etaEvis[p];
	
      }
      // If PMT is dead and EQ=0...
      else {
	pmt.etaEvis[p] = 0.;
	pmt.Evis[p] = 0.;
	pmt.nPE[p] = 0.;
      }
    }

     //Calculate the total weighted energy
    numer=denom=0.;
    for (UInt_t p=4;p<8;p++) {
      numer += ( pmtQuality[p] ) ? pmt.nPE[p] : 0.;
      denom += ( pmtQuality[p] ) ? eta[p]*alpha[p] : 0.;
      //numer += ( pmtQuality[p] && pmt.etaEvis[p]>0. ) ? pmt.nPE[p] : 0.;
      //denom += ( pmtQuality[p] && pmt.etaEvis[p]>0. ) ? eta[p]*alpha[p] : 0.;
    }
    //Now we apply the trigger probability
    Double_t totalEnW = denom>0. ? numer/denom : 0.;
    evis.EvisW = totalEnW;

    triggRandVec[0] = randPMTW1->Rndm();
    triggRandVec[1] = randPMTW2->Rndm();
    triggRandVec[2] = randPMTW3->Rndm();
    triggRandVec[3] = randPMTW4->Rndm();
    
    if ( (allEvtsTrigg && totalEnW>0.) || ( trigger.decideWestTrigger(ADCvecW,triggRandVec) ) ) WestScintTrigger = true;

    //if (totalEnW<25.) std::cout << totalEnW << " " << WestScintTrigger << "\n";

            
    //Fill proper total event histogram based on event type
    PID=6; //This is an unidentified particle
    type=4; //this is a lost event
    side=2; //This means there are no scintillator triggers

    //Type 0 East
    if (EastScintTrigger && EMWPCTrigger && !WestScintTrigger && !WMWPCTrigger) {
      PID=1;
      type=0;
      side=0;
      //finalEn[0]->Fill(evis.EvisE);
      //cout << "Type 0 East E = " << totalEnE << endl;
    }
    //Type 0 West
    else if (WestScintTrigger && WMWPCTrigger && !EastScintTrigger && !EMWPCTrigger) {
      PID=1;
      type=0;
      side=1;
      //finalEn[1]->Fill(totalEnW);
    }
    //Type 1 
    else if (EastScintTrigger && EMWPCTrigger && WestScintTrigger && WMWPCTrigger) {
      PID=1;
      type=1;
      //East
      if (Time.timeE<Time.timeW) {
	//finalEn[2]->Fill(totalEnE);
	side=0;
      }
      //West
      else if (Time.timeE>Time.timeW) {
	//finalEn[3]->Fill(totalEnW);
	side=1;
      }
    }
    //Type 2/3 East
    else if (EastScintTrigger && EMWPCTrigger && !WestScintTrigger && WMWPCTrigger) {
      PID=1;
      type=2;
      side=0;
      //finalEn[4]->Fill(totalEnE);
      //cout << "Type 2/3 East E = " << totalEnE << endl;
    }
    //Type 2/3 West
    else if (!EastScintTrigger && EMWPCTrigger && WestScintTrigger && WMWPCTrigger) {
      PID=1;
      type=2;
      side=1;
      //finalEn[5]->Fill(totalEnW);
      //cout << "Type 2/3 East W = " << totalEnW << endl;
    }   
    //Gamma events and missed events (Type 4)
    else {
      if (!WMWPCTrigger && !EMWPCTrigger) {
	if (EastScintTrigger && !WestScintTrigger) {
	  PID=0;
	  type=0;
	  side=0;
	}
	else if (!EastScintTrigger && WestScintTrigger) {
	  PID=0;
	  type=0;
	  side=1;
	}
	else if (EastScintTrigger && WestScintTrigger) {
	  PID=0;
	  type=1;
	  if (Time.timeE<Time.timeW) {
	    side=0;
	  }
	  else {
	    side=1;
	  }
	}
	else {
	  PID=6;
	  type=4;
	  side=2;
	}
      }
      else {
	PID=1;
	type=4;
	side = (WMWPCTrigger && EMWPCTrigger) ? 2 : (WMWPCTrigger ? 1 : 0); //Side==2 means the event triggered both wirechambers, but neither scint
      }
    }
    
    //Calculate Erecon
    Erecon = -1.;
    Int_t typeIndex = (type==0 || type==4) ? 0:(type==1 ? 1:2); //for retrieving the parameters from EQ2Etrue
    if (side==0) {
      Double_t totalEvis = type==1 ? (evis.EvisE+evis.EvisW):evis.EvisE;
      if (evis.EvisE>0. && totalEvis>0.) {
	Erecon = eRecon.getErecon(0,typeIndex,totalEvis);
	if (type==0) finalEn[0]->Fill(Erecon); 
	else if (type==1) finalEn[2]->Fill(Erecon); 
	else if(type==2 ||type==3) finalEn[4]->Fill(Erecon);
      }
      else Erecon=-1.;
      
    }
    if (side==1) {
      Double_t totalEvis = type==1 ? (evis.EvisE+evis.EvisW):evis.EvisW;
      if (evis.EvisW>0. && totalEvis>0.) {
	Erecon = eRecon.getErecon(1,typeIndex,totalEvis);	
	if (type==0) finalEn[1]->Fill(Erecon); 
	else if (type==1) finalEn[3]->Fill(Erecon); 
	else if(type==2 ||type==3) finalEn[5]->Fill(Erecon);
      }
      else Erecon=-1.;
    }    
  
    if ( PID==1 && Erecon>0. &&  sqrt( scint_pos_adj.ScintPosAdjE[0]*scint_pos_adj.ScintPosAdjE[0]
				       + scint_pos_adj.ScintPosAdjE[1]*scint_pos_adj.ScintPosAdjE[1] )<fidCut &&
	 sqrt( scint_pos_adj.ScintPosAdjW[0]*scint_pos_adj.ScintPosAdjW[0]
				       + scint_pos_adj.ScintPosAdjW[1]*scint_pos_adj.ScintPosAdjW[1] )<fidCut ) evtTally++;
    
    evt++;
    
    tree->Fill();
    if (evtTally%10000==0) {std::cout << evtTally  << "    PID=" << PID << "    Erecon=" << Erecon << std::endl;}//cout << "filled event " << evt << endl;
  }
  cout << endl;

  delete chain; delete seed; delete rand0; delete rand1; delete rand2; delete rand3;
  delete randPMTE1; delete randPMTE2; delete randPMTE3; delete randPMTE4; delete randPMTW1; delete randPMTW2; delete randPMTW3; delete randPMTW4;

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

}
Beispiel #14
0
void compareMET( bool printgif = false ){

  printgif_ = printgif;

  gStyle->SetOptStat(0);

  char* path = "output/PVT/promptreco/dcsonly";

  TChain *dymm = new TChain("Events");
  dymm->Add(Form("%s/dymm_default_baby.root",path));
  
  TChain *dyee = new TChain("Events");
  dyee->Add(Form("%s/dyee_default_baby.root",path));
  
  TChain *zjets = new TChain("Events");
  zjets->Add(Form("%s/zjets_default_baby.root",path));

  TChain *tt = new TChain("Events");
  tt->Add(Form("%s/tt_default_baby.root",path));
  
  TChain *h130 = new TChain("Events");
  h130->Add(Form("%s/h130_default_baby.root",path));

  TChain *chdata = new TChain("Events");
  chdata->Add(Form("%s/data_default_baby.root",path));

  cout << "DATA " << chdata->GetEntries() << endl;

  TChain *chmc = new TChain("Events");
  chmc->Add(Form("%s/dymm_default_baby.root",path));
  chmc->Add(Form("%s/dyee_default_baby.root",path));
  //chmc->Add(Form("%s/zjets_spring11_default_baby.root",path));
  //chmc->Add(Form("%s/tt_spring11_default_baby.root",path));
  
  cout << "MC " << chmc->GetEntries() << endl;

  TCut sel("njets30==1&&dilep.mass()>76&&dilep.mass()<106");
  //TCut sel("njets30==1&&dilep.mass()>76&&dilep.mass()<106");
  //TCut sel("njets30==0&&dilep.mass()>81&&dilep.mass()<101");
  
  TCut type("leptype==0||(leptype==3&&lep1.pt()>27)");
  //TCut type("leptype==3&&lep1.pt()>27");
  //TCut type("leptype==0");
  //TCut weight("weight*vtxweight");
  //TCut weight("weight");
  TCut weight("(7429./6555.1)*weight*davtxweight"); //powheg
  //TCut weight("(7429./6352)*10*weight*vtxweight");   //MG
  TCut seltype = sel+type;
  /*
  TCanvas *ctemp = new TCanvas();
  ctemp->cd();
  
  int nbins  = 100;
  float xmin = 0.;
  float xmax = 100.;
  
  TH1F* hmc_tcmet     = new TH1F("hmc_tcmet",  "", nbins,xmin,xmax);
  TH1F* hdata_tcmet   = new TH1F("hdata_tcmet","", nbins,xmin,xmax);

  hmc_tcmet->Sumw2();
  hdata_tcmet->Sumw2();

  TH1F* hmc_pfmet     = new TH1F("hmc_pfmet",  "", nbins,xmin,xmax);
  TH1F* hdata_pfmet   = new TH1F("hdata_pfmet","", nbins,xmin,xmax);

  hmc_pfmet->Sumw2();
  hdata_pfmet->Sumw2();

  TH1F* hmc_hmetpf     = new TH1F("hmc_hmetpf",  "", nbins,xmin,xmax);
  TH1F* hdata_hmetpf   = new TH1F("hdata_hmetpf","", nbins,xmin,xmax);

  hmc_hmetpf->Sumw2();
  hdata_hmetpf->Sumw2();
 
  TH1F* hmc_hmetpf4     = new TH1F("hmc_hmetpf4",  "", nbins,xmin,xmax);
  TH1F* hdata_hmetpf4   = new TH1F("hdata_hmetpf4","", nbins,xmin,xmax);

  hmc_hmetpf4->Sumw2();
  hdata_hmetpf4->Sumw2();

  TH1F* hmc_jetzmet     = new TH1F("hmc_jetzmet",  "", nbins,xmin,xmax);
  TH1F* hdata_jetzmet   = new TH1F("hdata_jetzmet","", nbins,xmin,xmax);

  hmc_jetzmet->Sumw2();
  hdata_jetzmet->Sumw2();
 
  //char* met1 = "tcmet";
  //char* met1 = "hmetpf";
  //char* met1 = "TMath::Min(pfmet,hmetpf)";
  
  chmc->Draw  ("TMath::Min(tcmet,99.9) >> hmc_tcmet"  ,(sel+type)*weight);
  chdata->Draw("TMath::Min(tcmet,99.9) >> hdata_tcmet",(sel+type)       );

  chmc->Draw  ("TMath::Min(pfmet,99.9) >> hmc_pfmet"  ,(sel+type)*weight);
  chdata->Draw("TMath::Min(pfmet,99.9) >> hdata_pfmet",(sel+type)       );
  
  chmc->Draw  ("TMath::Min(hmetpf,99.9) >> hmc_hmetpf"  ,(sel+type)*weight);
  chdata->Draw("TMath::Min(hmetpf,99.9) >> hdata_hmetpf",(sel+type)       );
  
  chmc->Draw  ("TMath::Min(hmetpf4,99.9) >> hmc_hmetpf4"  ,(sel+type)*weight);
  chdata->Draw("TMath::Min(hmetpf4,99.9) >> hdata_hmetpf4",(sel+type)       );

  chmc->Draw  ("TMath::Min(jetzmet,99.9) >> hmc_jetzmet"  ,(sel+type)*weight);
  chdata->Draw("TMath::Min(jetzmet,99.9) >> hdata_jetzmet",(sel+type)       );
  
  cout << "Tot MC   " << hmc_tcmet->Integral() << endl;
  cout << "Tot data " << hdata_tcmet->Integral() << endl;

  TH1F* hmc_zpt     = new TH1F("hmc_zpt",  "", nbins,xmin,xmax);
  TH1F* hdata_zpt   = new TH1F("hdata_zpt","", nbins,xmin,xmax);

  hmc_zpt->Sumw2();
  hdata_zpt->Sumw2();

  chmc->Draw  ("TMath::Min(dilep.pt(),99.9) >> hmc_zpt"  ,(sel+type)*weight);
  chdata->Draw("TMath::Min(dilep.pt(),99.9) >> hdata_zpt",(sel+type)       );

  delete ctemp;
  */
  //----------------------------------
  // tcmet, pfmet plots
  //----------------------------------

  /*

  TCanvas *c1 = new TCanvas();  
  c1->cd();
  plotHist( c1 , hmc_tcmet , hdata_tcmet , "" , "tcmet (GeV)" , "MC" , "data" , 30 , false , true);
  
  if( printgif ) c1->Print("plots/tcmet_datamc_mm.gif");

  
  TCanvas *c2 = new TCanvas();
  c2->cd();
  plotHist( c2 , hmc_pfmet , hdata_pfmet , "" , "pfmet (GeV)" , "MC" , "data" , 30 , false , true );
  
  if( printgif ) c2->Print("plots/pfmet_datamce_mm.gif");
  
  
  TCanvas *c3 = new TCanvas();
  c3->cd();
  plotHist( c3 , hmc_hmetpf , hdata_hmetpf , "" , "track-MET (GeV)" , "MC" , "data" , 30 , false , true );
  
  if( printgif ) c3->Print("plots/trkmet_datamc.gif");
  
  TCanvas *c4 = new TCanvas();
  c4->cd();
  plotHist( c4 , hmc_hmetpf4 , hdata_hmetpf4 , "" , "track/neu-MET (GeV)" , "MC" , "data" , 30 , false , true );
  
  if( printgif ) c4->Print("plots/trkneumet_datamc.gif");

  
  TCanvas *c5 = new TCanvas();
  c5->cd();
  plotHist( c5 , hmc_jetzmet , hdata_jetzmet , "" , "jet/Z MET (GeV)" , "MC" , "data" , 30 , false , true );
  
  if( printgif ) c5->Print("plots/jetzmet_datamc.gif");
  */  


  /*
  //----------------------------------
  // Z pt
  //----------------------------------
  
  // TCanvas *c2 = new TCanvas("c1","",600,600);
 
  // c2->cd();
  // plotHist( c2 , hmc_zpt , hdata_zpt , "" , "Z p_{T} (GeV)" , "MC" , "data" , false , false );



  vector<TChain*> ch;
  ch.push_back(chmc);
  ch.push_back(chdata);

  vector<TChain*> ch2;
  ch2.push_back(chmc);
  ch2.push_back(chdata);
  ch2.push_back(chmc);
  ch2.push_back(chdata);

  
  //------------------------------
  // pfmet
  //------------------------------
 
  vector<char*> pfmetTypes;
  pfmetTypes.push_back("pfmet");
  pfmetTypes.push_back("pfmet");
  
  vector<char*> pflabels;
  pflabels.push_back("MC (pfmet)");
  pflabels.push_back("data (pfmet)");

  //TCanvas *c2 = new TCanvas();
  //c2->cd();
  //effVsPU( "Spring11 MC vs. data", ch , pfmetTypes , pflabels , seltype , 30. , 1 );
  //if( printgif ) c2->Print("plots/DA_pfmet30.gif");

  TCanvas *c3 = new TCanvas();
  c3->cd();
  effVsPU( "Spring11 MC vs. data", ch , pfmetTypes , pflabels , seltype , 45. , 1 );
  if( printgif ) c3->Print("plots/DA_pfmet45.gif");


  //------------------------------
  // tcmet
  //------------------------------
  
  vector<char*> tcmetTypes;
  tcmetTypes.push_back("tcmet");
  tcmetTypes.push_back("tcmet");
  
  vector<char*> tclabels;
  tclabels.push_back("MC (tcmet)");
  tclabels.push_back("data (tcmet)");

  TCanvas *c4 = new TCanvas();
  c4->cd();
  effVsPU( "Spring11 MC vs. data", ch , tcmetTypes , tclabels , seltype , 30. , 1 );
  if( printgif ) c4->Print("plots/DA_tcmet30.gif");

  TCanvas *c5 = new TCanvas();
  c5->cd();
  effVsPU( "Spring11 MC vs. data", ch , tcmetTypes , tclabels , seltype , 45. , 1 );
  if( printgif ) c5->Print("plots/DA_tcmet45.gif");
  */

  //------------------------------
  // pfmet+trk-MET
  //------------------------------
  /*
  vector<char*> pftrkmetTypes;
  pftrkmetTypes.push_back("pfmet");
  pftrkmetTypes.push_back("pfmet");
  //pftrkmetTypes.push_back("hmetpf");
  //pftrkmetTypes.push_back("hmetpf");
  //pftrkmetTypes.push_back("hmetpf4");
  //pftrkmetTypes.push_back("hmetpf4");
  pftrkmetTypes.push_back("TMath::Min(pfmet,hmetpf)");
  pftrkmetTypes.push_back("TMath::Min(pfmet,hmetpf)");
  
  vector<char*> pftrklabels;
  pftrklabels.push_back("MC (pfmet)");
  pftrklabels.push_back("data (pfmet)");
  //pftrklabels.push_back("MC (trk-MET)");
  //pftrklabels.push_back("data (trk-MET)");
  //pftrklabels.push_back("MC (trk/neu-MET)");
  //pftrklabels.push_back("data (trk/neu-MET)");
  pftrklabels.push_back("MC (min-MET)");
  pftrklabels.push_back("data (min-MET)");

  TCanvas *c6 = new TCanvas();
  c6->cd();
  effVsPU( "Spring11 MC vs. data", ch2 , pftrkmetTypes , pftrklabels , seltype , 30. , 1 );
  if( printgif ) c6->Print("plots/DA_pftrkmet30.gif");

  TCanvas *c7 = new TCanvas();
  c7->cd();
  effVsPU( "Spring11 MC vs. data", ch2 , pftrkmetTypes , pftrklabels , seltype , 45. , 1 );
  if( printgif ) c7->Print("plots/DA_pftrkmet45.gif");
  */

 
  /*

  vector<char*> metTypes;
  //metTypes.push_back("pfmet");
  //metTypes.push_back("pfmet");
  metTypes.push_back("tcmet");
  metTypes.push_back("tcmet");
  //metTypes.push_back("hmetpf");
  //metTypes.push_back("hmetpf");
  //metTypes.push_back("hmetpf4");
  //metTypes.push_back("hmetpf4");
  //metTypes.push_back("TMath::Min(pfmet,hmetpf)");
  //metTypes.push_back("TMath::Min(pfmet,hmetpf)");
  //metTypes.push_back("jetzmet");
  //metTypes.push_back("jetzmet");

  vector<char*> labels;
  //labels.push_back("MC (pfmet)");
  //labels.push_back("data (pfmet)");
  labels.push_back("MC (tcmet)");
  labels.push_back("data (tcmet)");
  //labels.push_back("MC (trk-MET)");
  //labels.push_back("data (trk-MET)");
  //labels.push_back("MC (trk/neu-MET)");
  //labels.push_back("data (trk/neu-MET)");
  //labels.push_back("MC (min-MET)");
  //labels.push_back("data (min-MET)");
  //labels.push_back("MC (jet/Z-MET)");
  //labels.push_back("data (jet/Z-MET)");

  */


  //---------------------------------------
  // ROC curves pfmet, track-met, min-MET
  //---------------------------------------
  /*
  vector<char*> rocMetTypes;
  rocMetTypes.push_back("pfmet");
  rocMetTypes.push_back("hmetpf");
  rocMetTypes.push_back("hmetpf4");
  rocMetTypes.push_back("TMath::Min(pfmet,hmetpf)");

  vector<char*> rocMetLabels;
  rocMetLabels.push_back("pfmet");
  rocMetLabels.push_back("trk-met");
  rocMetLabels.push_back("trk/neu-met");
  rocMetLabels.push_back("min-met");

  TCanvas *c4 = new TCanvas();
  c4->cd();

  //TCut jetveto1("njets30==0&&nvtx<8&&dilep.mass()>12&&dilep.mass()<76");
  TCut jetveto1("njets30==0&&nvtx<8");

  ROC(h130,dymm,rocMetTypes,jetveto1,rocMetLabels);

  c4->Print("plots/ROC1_m76.gif");
  //c4->Print("plots/ROC1.gif");

  TCanvas *c5 = new TCanvas();
  c5->cd();
  
  //TCut jetveto2("njets30==0&&nvtx>7&&dilep.mass()>12&&dilep.mass()<76");
  TCut jetveto2("njets30==0&&nvtx>7");
  
  ROC(h130,dymm,rocMetTypes,jetveto2,rocMetLabels);
  
  c5->Print("plots/ROC2_m76.gif");
  //c5->Print("plots/ROC2.gif");
  */



  /*
  vector<char*> rocMetTypes;
  rocMetTypes.push_back("pfmet");
  rocMetTypes.push_back("jetzmet");
  rocMetTypes.push_back("TMath::Min(pfmet,jetzmet)");

  vector<char*> rocMetLabels;
  rocMetLabels.push_back("pfmet");
  rocMetLabels.push_back("jet-Z MET");
  rocMetLabels.push_back("min-MET");

  TCanvas *c6 = new TCanvas();
  c6->cd();

  TCut jet1_loPU("njets30==1&&jetpv==1&&nvtx<8&&dilep.mass()>76&&dilep.mass()<106");

  ROC(h130,dymm,rocMetTypes,jet1_loPU,rocMetLabels);

  c6->Print("plots/jetzmet_loPU.gif");
  
  TCanvas *c7 = new TCanvas();
  c7->cd();
  
  TCut jet1_hiPU("njets30==1&&jetpv==1&&nvtx>7&&dilep.mass()>76&&dilep.mass()<106");
  
  ROC(h130,dymm,rocMetTypes,jet1_hiPU,rocMetLabels);
  
  c7->Print("plots/jetzmet_hiPU.gif");
  */


  /*
  
//   TCut sel("njets30==0");

//   TCanvas *ctemp = new TCanvas();
//   ctemp->cd();
  
//   int nbins  = 100;
//   float xmin = 0.;
//   float xmax = 100.;

//   TH1F* dymm_met1   = new TH1F("dymm_met1",  "",nbins,xmin,xmax);
//   TH1F* dyee_met1   = new TH1F("dyee_met1",  "",nbins,xmin,xmax);
//   TH1F* h130_met1   = new TH1F("h130_met1",  "",nbins,xmin,xmax);
  
//   TH1F* dymm_met2   = new TH1F("dymm_met2",  "",nbins,xmin,xmax);
//   TH1F* dyee_met2   = new TH1F("dyee_met2",  "",nbins,xmin,xmax);
//   TH1F* h130_met2   = new TH1F("h130_met2",  "",nbins,xmin,xmax);

//   dymm_met1->Sumw2();
//   dyee_met1->Sumw2();
//   h130_met1->Sumw2();
  
//   dymm_met2->Sumw2();
//   dyee_met2->Sumw2();
//   h130_met2->Sumw2();
  
//   char* met1 = "pfmet";
//   char* met2 = "pfmet";

//   TCut sel1("njets30==0 && nvtx<5");
//   TCut sel2("njets30==0 && nvtx>=5");

//   dymm->Draw(Form("TMath::Min(%s,199.9) >> dymm_met1",met1),sel1);
//   dyee->Draw(Form("TMath::Min(%s,199.9) >> dyee_met1",met1),sel1);
//   h130->Draw(Form("TMath::Min(%s,199.9) >> h130_met1",met1),sel1);
  
//   dymm->Draw(Form("TMath::Min(%s,199.9) >> dymm_met2",met2),sel2);
//   dyee->Draw(Form("TMath::Min(%s,199.9) >> dyee_met2",met2),sel2);
//   h130->Draw(Form("TMath::Min(%s,199.9) >> h130_met2",met2),sel2);
  
//   delete ctemp;
  
//   TCanvas *c1 = new TCanvas();
//   c1->cd();
//   //plotHist( c1 , dymm_met1 , dymm_met2 , "DYmm" , "MET" , "trk-MET" , "+ neutrals" );
//   plotHist( c1 , dymm_met1 , dymm_met2 , "DYmm" , "pfmet (GeV)" , "N_{PV} < 5" , "N_{PV} #geq 5" , true );
  
//   TCanvas *c2 = new TCanvas();
//   c2->cd();
//   plotHist( c2 , dyee_met1 , dyee_met2 , "DYee" , "MET" , "trk-MET" , "+ neutrals" , true );
  
//   TCanvas *c3 = new TCanvas();
//   c3->cd();
//   plotHist( c3 , h130_met1 , h130_met2 , "Higgs130" , "MET" , "trk-MET" , "+ neutrals" );

  //------------------------------------------
  // met flavors in 0-jet bin
  //------------------------------------------

//   TCanvas *effcan = new TCanvas();
//   effcan->cd();

//   vector<char*> metTypes1;
//   metTypes1.push_back("pfmet");
//   metTypes1.push_back("hmetpf");
//   metTypes1.push_back("hmetpf8");

//   TCut mysel1("njets30==0 && dilmass>76 && dilmass<106");

//   effVsPU( "DY#rightarrow#mu#mu" , dymm , metTypes1 , mysel1 , 45. );
//   effcan->Print("plots/dymm_met_vtx.gif");
//   effcan->Clear();

//   effVsPU( "DY#rightarrowee" , dyee , metTypes1 , mysel1 , 45. );
//   effcan->Print("plots/dyee_met_vtx.gif");
//   effcan->Clear();
  
//   effVsPU( "Higgs 130 GeV" , h130 , metTypes1 , mysel1 , 45. );
//   effcan->Print("plots/h130_met_vtx.gif");
//   effcan->Clear();

//  effVsPU( "Data" , data , metTypes1 , mysel1 , 45. );


//   TCanvas *effcan_mll = new TCanvas();
//   effcan_mll->cd();

//   TCut jetveto_dilmass("njets30==0&&dilmass<76&&dilmass>12");

//   effVsPU( "DY#rightarrow#mu#mu (12 < M_{ll} < 76 GeV)" , dymm , metTypes1 , jetveto_dilmass , 45. );
//   effcan_mll->Print("plots/dymm_met_vtx_m76.gif");
//   effcan_mll->Clear();

//   effVsPU( "DY#rightarrowee (12 < M_{ll} < 76 GeV)"     , dyee , metTypes1 , jetveto_dilmass , 45. );  
//   effcan_mll->Print("plots/dyee_met_vtx_m76.gif");
//   effcan_mll->Clear();

//   effVsPU( "Higgs 130 GeV (12 < M_{ll} < 76 GeV)"       , h130 , metTypes1 , jetveto_dilmass , 45. );
//   effcan_mll->Print("plots/h130_met_vtx_m76.gif");
//   effcan_mll->Clear();
  

*/
  //------------------------------------------
  // met flavors in 1-jet bin
  //------------------------------------------

  TCanvas *effcan2 = new TCanvas("effcan2","",1200,600);
  effcan2->Divide(2,1);

  vector<char*> metTypes2;
  metTypes2.push_back("pfmet");
  //metTypes2.push_back("hmetpf4");
  //metTypes2.push_back("jetzmet");
  //metTypes2.push_back("jetzmet4");
  //metTypes2.push_back("jetzmet8");
  metTypes2.push_back("TMath::Min(pfmet,jetzmet)");

  TCut dphizjet("acos(cos(dilep.phi()-jet.phi()))>2");
  TCut lepveto("nlep==0");
  TCut zmass("dilep.mass()>76&&dilep.mass()<106");
  TCut ee("leptype==0");
  TCut mm("leptype==3");

  TCut sel1          = zmass+(mm||ee)+lepveto+dphizjet+"njets30==1 && jetpv==1";

  //TCut mysel2("njets30==1 && (leptype==0||leptype==3) && jetpv==1 && dilep.mass()>76 && dilep.mass()<106");

  effcan2->cd(1);
  effVsPU( "DY" , chmc , metTypes2 , sel1 , 30. );

  effcan2->cd(2);
  effVsPU( "data" , chdata , metTypes2 , sel1 , 30. );




  //effVsPU( "DY#rightarrowee"     , dyee , metTypes2 , mysel2 , 45. , 5 );

  
}
Beispiel #15
0
void analyzeJES(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)
   */


  TString jetName = "aktPuppiR040";
  TString jetTreeName = "akPuppi4PFJetAnalyzer";
  jetName = "aktCsR040";
  jetTreeName = "akCs4PFJetAnalyzer";
  //jetName = "aktVsR040";
  //jetTreeName = "akVs4PFJetAnalyzer";

  std::cout << "analyzing JES 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 *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");

  TList *fEventObjects = new TList();

  //---------------------------------------------------------------
  // producers
  //
  hiEventProducer *p_evt = new hiEventProducer("hiEvtProd");
  p_evt->SetInput(chain);
  p_evt->SetHIEventContName("hiEventContainer");
  p_evt->SetEventObjects(fEventObjects);

  lwJetFromForestProducer *p_PUJet = new lwJetFromForestProducer("lwJetForestProd");
  p_PUJet->SetInput(chain);
  p_PUJet->SetJetContName(jetName);
  p_PUJet->SetGenJetContName("akt4Gen");
  p_PUJet->SetEventObjects(fEventObjects);
  p_PUJet->SetRadius(0.4);
  
  //---------------------------------------------------------------
  //analysis modules
  //

  //handler to which all modules will be added
  anaBaseTask *handler = new anaBaseTask("handler","handler");

  anaJetEnergyScale *anajesForest = new anaJetEnergyScale("anaJESForest","anaJESForest");
  anajesForest->ConnectEventObject(fEventObjects);
  anajesForest->SetHiEvtName("hiEventContainer");
  anajesForest->SetGenJetsName("akt4Gen");
  anajesForest->SetRecJetsName(jetName);
  anajesForest->SetNCentBins(4);
  anajesForest->SetUseForestMatching(true);
  //anajesForest->SetMaxDistance(0.2);
  handler->Add(anajesForest);

  anaJetEnergyScale *anajesForestQuarks = new anaJetEnergyScale("anaJESForestQuarks","anaJESForestQuarks");
  anajesForestQuarks->ConnectEventObject(fEventObjects);
  anajesForestQuarks->SetHiEvtName("hiEventContainer");
  anajesForestQuarks->SetGenJetsName("akt4Gen");
  anajesForestQuarks->SetRecJetsName(jetName);
  anajesForestQuarks->SetNCentBins(4);
  anajesForestQuarks->SetUseForestMatching(true);
  //anajesForestQuarks->SetMaxDistance(0.2);
  anajesForestQuarks->SetRefPartonFlavor(0,2);
  handler->Add(anajesForestQuarks);

  anaJetEnergyScale *anajesForestGluons = new anaJetEnergyScale("anaJESForestGluons","anaJESForestGluons");
  anajesForestGluons->ConnectEventObject(fEventObjects);
  anajesForestGluons->SetHiEvtName("hiEventContainer");
  anajesForestGluons->SetGenJetsName("akt4Gen");
  anajesForestGluons->SetRecJetsName(jetName);
  anajesForestGluons->SetNCentBins(4);
  anajesForestGluons->SetUseForestMatching(true);
  //anajesForestGluons->SetMaxDistance(0.2);
  anajesForestGluons->SetRefPartonFlavor(21,21);
  handler->Add(anajesForestGluons);
  
  anaJetEnergyScale *anajesForestRaw = new anaJetEnergyScale("anaJESForestRaw","anaJESForestRaw");
  anajesForestRaw->ConnectEventObject(fEventObjects);
  anajesForestRaw->SetHiEvtName("hiEventContainer");
  anajesForestRaw->SetGenJetsName("");
  anajesForestRaw->SetRecJetsName(jetName);
  anajesForestRaw->SetNCentBins(4);
  anajesForestRaw->SetUseForestMatching(true);
  anajesForestRaw->SetUseRawPt(true);
  //handler->Add(anajesForestRaw);

  //particle-detector-level jet matching
  anaJetMatching *match = new anaJetMatching("jetMatching","jetMatching");
  match->ConnectEventObject(fEventObjects);
  match->SetHiEvtName("hiEventContainer");
  //match->SetJetsNameBase(jetName);
  //match->SetJetsNameTag("akt4Gen");
  match->SetJetsNameTag(jetName);
  match->SetJetsNameBase("akt4Gen");
  match->SetMatchingType(0);
  //handler->Add(match);
  
  anaJetEnergyScale *anajes = new anaJetEnergyScale("anaJES","anaJES");
  anajes->ConnectEventObject(fEventObjects);
  anajes->SetHiEvtName("hiEventContainer");
  anajes->SetGenJetsName("akt4Gen");
  anajes->SetRecJetsName(jetName);
  anajes->SetNCentBins(4);
  //handler->Add(anajes);

  anaJetEnergyScale *anajesRaw = new anaJetEnergyScale("anaJESRaw","anaJESRaw");
  anajesRaw->ConnectEventObject(fEventObjects);
  anajesRaw->SetHiEvtName("hiEventContainer");
  anajesRaw->SetGenJetsName("akt4Gen");
  anajesRaw->SetRecJetsName(jetName);
  anajesRaw->SetNCentBins(4);
  anajesRaw->SetUseForestMatching(false);
  anajesRaw->SetUseRawPt(true);
  //handler->Add(anajesRaw);

 
  //---------------------------------------------------------------
  //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
	    
    //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();
  
}
int main(int argc,char **argv){
	if (argc==1){
		PrintHelp();
		exit(1);
	}
	ParseCommandLine(argc,argv);
	//Load Cintex and the shared library
	LOADLIBS

	if (fDoBatch)  gROOT->SetBatch();



	if (fSigName.length()==0){
		cerr<<"Missing SIGNAL file name!"<<endl;
		return -1;
	}
	if (fBckName.length()==0){
		cerr<<"Missing BCK file name!"<<endl;
		return -1;
	}
	if (fDetName.length()==0){
		cerr<<"Missing DET file name"<<endl;
		return -1;
	}
	if (fSetupName.length()==0){
		cerr<<"Missing Setup file name"<<endl;
		return -1;
	}
	if (fReconName.length()==0){
		cerr<<"Missing Recon file name"<<endl;
		return -1;
	}
	else if (fReconName.find(".root")!=std::string::npos){
		cout<<"ROOT mode"<<endl;
		fDoRoot=1;
	}
	else{
		cout<<"Model mode";
		fDoRoot=0;
	}
	if (fOutName.length()==0){
		cout<<"Missing OUT file name, auto-selecting"<<endl;
		fOutName=fSigName+".out";
	}
	fOutNameRoot=fOutName+".root";
	fOutNamePS=fOutName+".ps";
	TFile *f1=new TFile(fSigName.c_str());
	TFile *f2=new TFile(fBckName.c_str());

	TFile *fOut=new TFile(fOutNameRoot.c_str(),"recreate");


	TTree *tSig=(TTree*)f1->Get("fTdata");
	TTree *tBck=(TTree*)f2->Get("fTdata");

	Float_t ADC[TMarocSetupHandler::nMarocChannels];
	Bool_t hit[TMarocSetupHandler::nMarocChannels];
	double PedSig[TMarocSetupHandler::nMarocChannels],PedBck[TMarocSetupHandler::nMarocChannels],MeanDiff[TMarocSetupHandler::nMarocChannels];

	double fExp[6][MAX_DETECTORS][TMarocSetupHandler::nH8500Pixels];double fNormExp;
	double fTeo[6][MAX_DETECTORS][TMarocSetupHandler::nH8500Pixels];double fNormTeo;
	double fMC[6][MAX_DETECTORS][TMarocSetupHandler::nH8500Pixels];double fNormMC;

	Int_t EvtMultiplicity;
	int Nb,Ns,Nped;
	int id;
	int ix,iy,iH8500,iMarocChannel,iMarocCard,iRealDet,iReconDet,iReconFace,iReconPixel;
	int iPad;

	int flagQcut;
	double Q,QSigTot,QBckTot;
	double QSigTotL,QBckTotL;
	double QSigTotR,QBckTotR;

	const double QTotThr=-20E3;
	const double QTotLThr=0;
	const double QTotRThr=0;

	double Scale;
	double oldMeanSig,oldMeanBck,oldMeanDiff;
	double MeanDiffCorrected;
	double Gain,F,Corr;
	double min,max;
	TVector3 vin;


	int Nx,Ny;
	TDetector *m_detector=new TDetector(fDetName);
	TMarocSetupHandler *m_setup=new TMarocSetupHandler(fSetupName);
	TDetectorUtils *m_utils=0;

	/*MC DATA INPUT CASE*/
	TChain *cMC;

	vector < TH1D* > hSimChargeMC[6][MAX_DETECTORS];
	vector < double > chargeMC[6][MAX_DETECTORS];


	TEvent *event = 0;
	TClonesArray *digi;
	int NeventsMC;
	int Nhits,faceNumber,detNumber,pixelNumber;
	int nBckCut,nSigCut;
	double qMeanMC;


	m_setup->Print(1);

	m_detector->PrintPixels();
	m_detector->Print();

	if (fDoRoot){
		cMC=new TChain("Event"); //must have the TTree name I am going to read
		cMC->Add(fReconName.c_str());
		NeventsMC=cMC->GetEntries(); //1 entry=1 event
		cMC->SetBranchAddress("Event", &event);
	}

	m_utils=new TDetectorUtils(m_detector);




	/*Set the first gain, i.e. the Hamamatsu one. The index is the H8500ID!!!*/
	double PmtDA0359[TMarocSetupHandler::nH8500Pixels]={76,79,86,96,100,95,88,83,76,71,80,89,95,89,87,82,75,68,82,87,92,91,81,77,71,64,79,83,88,88,75,74,69,63,74,79,78,83,73,70,68,61,71,75,76,73,68,65,63,60,65,69,66,62,59,60,61,64,66,70,65,60,56,52};
	double PmtDA0361[TMarocSetupHandler::nH8500Pixels]={56,71,76,81,89,87,78,82,61,66,72,77,82,78,76,85,60,64,72,74,75,81,80,88,61,65,70,72,73,82,82,93,63,66,71,72,73,85,86,99,68,68,77,75,82,91,89,100,73,75,83,88,95,97,92,99,60,73,80,85,92,99,90,71};

	for (int ii=0;ii<TMarocSetupHandler::nH8500Pixels;ii++){
		iReconPixel=m_setup->getPixelReconId(32,ii);
		iMarocChannel=m_setup->getMarocChannelFromH8500(ii);
		iReconFace=m_setup->getReconstructionDetectorFace(32);
		iReconDet=m_setup->getReconstructionDetectorID(32);
		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,1,PmtDA0359[ii]/100.);
		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,3,0.718); /*This is the gain configuration PMT359 vs PMT361*/
		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.5);

		//	if (iMarocChannel<=31)			m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.5);
		//	else if (iMarocChannel<=47)		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.375);
		//	else if (iMarocChannel<=63)		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.25);



		iReconPixel=m_setup->getPixelReconId(33,ii);
		iMarocChannel=m_setup->getMarocChannelFromH8500(ii);
		iReconFace=m_setup->getReconstructionDetectorFace(33);
		iReconDet=m_setup->getReconstructionDetectorID(33);
		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,1,PmtDA0361[ii]/100.);
		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,3,1.); /*This is the gain configuration PMT359 vs PMT361*/
		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.5);
		//	if (iMarocChannel<=31)			m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.5);
		//	else if (iMarocChannel<=47)		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.375);
		//	else if (iMarocChannel<=63)		m_setup->setPixelGain(iReconFace,iReconDet,iReconPixel,2,.25);

	}


	m_setup->Print(1);




	/*Define here the histograms*/
	/*These are indexed by the real pixel id*/
	TH1D **hChargeSig=new TH1D*[Ntot];  TH1D **hChargeSigCorr=new TH1D*[Ntot];  TH1D **hChargeHitSig=new TH1D*[Ntot];
	TH1D **hChargeBck=new TH1D*[Ntot];  TH1D **hChargeBckCorr=new TH1D*[Ntot];  TH1D **hChargeHitBck=new TH1D*[Ntot];
	TH1D **hChargeDiff=new TH1D*[Ntot];

	TH2D **hChargeSigVsTot=new TH2D*[Ntot];
	TH2D **hChargeBckVsTot=new TH2D*[Ntot];




	TH2D *hGrid=new TH2D("hGrid","hGrid",16,-8.5,7.5,8,-0.5,7.5);
	TH2D *hGainMap=new TH2D("hGainMap","hGainMap",16,-8.5,7.5,8,-0.5,7.5);
	TH2D *hMeanSig=new TH2D("hMeanSig","hMeanSig",16,-8.5,7.5,8,-0.5,7.5);
	TH2D *hMeanBck=new TH2D("hMeanBck","hMeanBck",16,-8.5,7.5,8,-0.5,7.5);
	TH2D *hMeanDiff=new TH2D("hMeanDiff","hMeanDiff",16,-8.5,7.5,8,-0.5,7.5);

	TH2D *hHitSig=new TH2D("hHitSig","hHitSig",16,-8.5,7.5,8,-0.5,7.5);
	TH2D *hHitBck=new TH2D("hHitBck","hHitBck",16,-8.5,7.5,8,-0.5,7.5);
	TH2D *hHitDiff=new TH2D("hHitDiff","hHitDiff",16,-8.5,7.5,8,-0.5,7.5);


	TH1D* hChargeExp[6][MAX_DETECTORS];
	TH1D* hChargeTeo[6][MAX_DETECTORS];
	TH1D* hChargeMC[6][MAX_DETECTORS];
	TH2D* hChargeComparison[6][MAX_DETECTORS];

	TH1D* hChargeSigTot=new TH1D("hChargeSigTot","hChargeSigTot",5000,-10E3,200E3);
	TH1D* hChargeBckTot=new TH1D("hChargeBckTot","hChargeBckTot",5000,-10E3,200E3);
	TH1D* hChargeDiffTot=new TH1D("hChargeDiffTot","hChargeDiffTot",5000,-10E3,200E3);

	TH1D* hChargeSigTotR=new TH1D("hChargeSigTotR","hChargeSigTotR",5000,-10E3,200E3);
	TH1D* hChargeBckTotR=new TH1D("hChargeBckTotR","hChargeBckTotR",5000,-10E3,200E3);
	TH1D* hChargeDiffTotR=new TH1D("hChargeDiffTotR","hChargeDiffTotR",5000,-10E3,200E3);

	TH1D* hChargeSigTotL=new TH1D("hChargeSigTotL","hChargeSigTotL",5000,-10E3,200E3);
	TH1D* hChargeBckTotL=new TH1D("hChargeBckTotL","hChargeBckTotL",5000,-10E3,200E3);
	TH1D* hChargeDiffTotL=new TH1D("hChargeDiffTotL","hChargeDiffTotL",5000,-10E3,200E3);

	TH2D* hChargeSigTotLR=new TH2D("hChargeSigTotLR","hChargeSigTotLR",2000,-10E3,200E3,2000,-10E3,200E3);
	TH2D* hChargeBckTotLR=new TH2D("hChargeBckTotLR","hChargeBckTotLR",2000,-10E3,200E3,2000,-10E3,200E3);


	cout<<"Creating channel histograms"<<endl;
	for (int ii=0;ii<Ntot;ii++){
		iH8500=m_setup->getH8500IdFromGlobal(ii+N0);

		hChargeSig[ii]=new TH1D(Form("hChargeSig%i",ii),Form("hChargeSig%i:H8500_%i",ii,iH8500),4096,-0.5,4095.5);
		hChargeBck[ii]=new TH1D(Form("hChargeBck%i",ii),Form("hChargeBck%i:H8500_%i",ii,iH8500),4096,-0.5,4095.5);
		hChargeHitSig[ii]=new TH1D(Form("hChargeHitSig%i",ii),Form("hChargeHitSig%i:H8500_%i",ii,iH8500),4096,-0.5,4095.5);
		hChargeHitBck[ii]=new TH1D(Form("hChargeHitBck%i",ii),Form("hChargeHitBck%i:H8500_%i",ii,iH8500),4096,-0.5,4095.5);

		hChargeDiff[ii]=new TH1D(Form("hChargeDiff%i",ii),Form("hChargeDiff%i:H8500_%i",ii,iH8500),6000,-2000.5,3999.5);

		hChargeSigCorr[ii]=new TH1D(Form("hChargeSigCorr%i",ii),Form("hChargeSigCorr%i:H8500_%i",ii,iH8500),6096,-2000.5,4095.5);
		hChargeBckCorr[ii]=new TH1D(Form("hChargeBckCorr%i",ii),Form("hChargeBckCorr%i:H8500_%i",ii,iH8500),6096,-2000.5,4095.5);


		hChargeSigVsTot[ii]=new TH2D(Form("hChargeSigVsTot%i",ii),Form("hChargeSigVsTot%i",ii),500,-1000.5,5095.5,500,-10E3,200E3);
		hChargeBckVsTot[ii]=new TH2D(Form("hChargeBckVsTot%i",ii),Form("hChargeBckVsTot%i",ii),500,-1000.5,4095.5,500,-10E3,200E3);
	}
	cout<<"Done"<<endl;
	cout<<"Creating comparison histograms"<<endl;
	for (int ii=0;ii<6;ii++){
		for (int jj=0;jj<m_detector->getNdet(ii);jj++){
			if (m_detector->isDetPresent(ii,jj)){
				Nx=m_detector->getNPixelsX(ii,jj);
				Ny=m_detector->getNPixelsY(ii,jj);
				hChargeExp[ii][jj]=new TH1D(Form("hChargeExp%i_%i",ii,jj),Form("hChargeExp%i_%i; Pixel ID",ii,jj),Nx*Ny,-0.5,Nx*Ny-0.5);
				hChargeTeo[ii][jj]=new TH1D(Form("hChargeTeo%i_%i",ii,jj),Form("hChargeTeo%i_%i; Pixel ID",ii,jj),Nx*Ny,-0.5,Nx*Ny-0.5);
				hChargeMC[ii][jj]=new TH1D(Form("hChargeMC%i_%i",ii,jj),Form("hChargeMC%i_%i; Pixel ID",ii,jj),Nx*Ny,-0.5,Nx*Ny-0.5);
				hChargeComparison[ii][jj]=new TH2D(Form("hChargeComparison%i_%i",ii,jj),Form("hChargeComparison%i_%i",ii,jj),Nx,-0.5,Nx-0.5,Ny,-0.5,Ny-0.5);
				for (int kk=0;kk<Nx*Ny;kk++){
					hSimChargeMC[ii][jj].push_back(new TH1D(Form("hChargeMC_%i_%i_%i",ii,jj,kk),Form("hCharge_%i_%i_%i",ii,jj,kk),1000,-0.5,999.5));
					chargeMC[ii][jj].push_back(0.);
				}
			}
		}
	}
	cout<<"Done creating histograms"<<endl;

	/*Process the signal*/
	tSig->SetBranchAddress("ADC",ADC);
	tSig->SetBranchAddress("EvtMultiplicity",&EvtMultiplicity);
	tSig->SetBranchAddress("hit",hit);

	nSigCut=nBckCut=0;
	Ns=tSig->GetEntries();
	cout<<"There are "<<Ns<<" signals "<<endl;
	for (int ii=0;ii<Ns;ii++){
		tSig->GetEntry(ii);
		for (int jj=0;jj<Ntot;jj++){
			id=jj+N0;


			iRealDet=m_setup->getMarocCard(id);
			iH8500=m_setup->getH8500IdFromGlobal(id);
			iMarocChannel=m_setup->getMarocChannelFromGlobal(id);
			iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
			iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
			iReconPixel=m_setup->getPixelReconId(id);
			if (iRealDet==32){
				ix=iH8500%8;
			}
			else {
				ix=-iH8500%8-1;
			}
			iy=7-iH8500/8;
			Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);
			Q=ADC[id];
			hChargeSig[jj]->Fill(Q);
			if (hit[id]){
				hHitSig->Fill(ix,iy,+1);
				hHitDiff->Fill(ix,iy,+1);
				hChargeHitSig[jj]->Fill(Q);
			}


			if (ii==0){
				MeanDiff[jj]=0;
			}
			//  hChargeDiff[jj]->Fill(Q,+1);
		}
	}

	/*Process the background*/
	tBck->SetBranchAddress("ADC",ADC);
	tBck->SetBranchAddress("EvtMultiplicity",&EvtMultiplicity);
	tBck->SetBranchAddress("hit",hit);

	Nb=tBck->GetEntries();
	cout<<"There are "<<Nb<<" backgrounds"<<endl;
	for (int ii=0;ii<Nb;ii++){
		tBck->GetEntry(ii);
		for (int jj=0;jj<Ntot;jj++){
			id=jj+N0;

			iRealDet=m_setup->getMarocCard(id);
			iH8500=m_setup->getH8500IdFromGlobal(id);
			iMarocChannel=m_setup->getMarocChannelFromGlobal(id);
			iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
			iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
			iReconPixel=m_setup->getPixelReconId(id);
			Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);

			if (iRealDet==32){
				ix=iH8500%8;
			}
			else {
				ix=-iH8500%8-1;
			}
			iy=7-iH8500/8;
			Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);
			Q=ADC[id];
			hChargeBck[jj]->Fill(Q);

			if (hit[id]){
				hHitBck->Fill(ix,iy,+1);
				hHitDiff->Fill(ix,iy,-1);
				hChargeHitBck[jj]->Fill(Q);
			}

		}
	}
	/*Compute the pedestals*/
	for (int jj=0;jj<Ntot;jj++){
		min=hChargeSig[jj]->GetBinCenter(hChargeSig[jj]->GetMaximumBin());
		max=min;
		min-=15;
		max+=15;
		hChargeSig[jj]->Fit("gaus","RL","",min,max);

		min=hChargeBck[jj]->GetBinCenter(hChargeBck[jj]->GetMaximumBin());
		max=min;
		min-=15;
		max+=15;
		hChargeBck[jj]->Fit("gaus","RL","",min,max);
		PedSig[jj]=hChargeSig[jj]->GetFunction("gaus")->GetParameter(1);
		PedBck[jj]=hChargeBck[jj]->GetFunction("gaus")->GetParameter(1);
	}




	/*Process the signal, again*/
	tSig->SetBranchAddress("ADC",ADC);
	tSig->SetBranchAddress("EvtMultiplicity",&EvtMultiplicity);
	tSig->SetBranchAddress("hit",hit);
	Ns=tSig->GetEntries();

	for (int ii=0;ii<Ns;ii++){
		QSigTot=0;
		QSigTotL=0;
		QSigTotR=0;
		tSig->GetEntry(ii);
		for (int jj=0;jj<Ntot;jj++){
			id=jj+N0;

			iRealDet=m_setup->getMarocCard(id);
			iH8500=m_setup->getH8500IdFromGlobal(id);
			iMarocChannel=m_setup->getMarocChannelFromGlobal(id);
			iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
			iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
			iReconPixel=m_setup->getPixelReconId(id);
			Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);
			Q=ADC[id]-PedSig[jj];
			QSigTot+=Q/Gain;
			if (jj<Ntot/2) QSigTotL+=Q/Gain;
			else QSigTotR+=Q/Gain;
		}
		hChargeSigTot->Fill(QSigTot);
		hChargeSigTotL->Fill(QSigTotL);
		hChargeSigTotR->Fill(QSigTotR);
		hChargeSigTotLR->Fill(QSigTotR,QSigTotL);

		hChargeDiffTot->Fill(QSigTot,+1);
		hChargeDiffTotR->Fill(QSigTotR,+1);
		hChargeDiffTotL->Fill(QSigTotL,+1);


		flagQcut=1;
		if (QSigTot<QTotThr) flagQcut=0;
		for (int jj=0;jj<Ntot;jj++){
			id=jj+N0;

			iRealDet=m_setup->getMarocCard(id);
			iH8500=m_setup->getH8500IdFromGlobal(id);
			iMarocChannel=m_setup->getMarocChannelFromGlobal(id);
			iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
			iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
			iReconPixel=m_setup->getPixelReconId(id);
			Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);

			Q=ADC[id]-PedSig[jj];

			//hChargeSigVsTot[jj]->Fill(Q,QSigTot);


			if (flagQcut){
				hChargeDiff[jj]->Fill(Q,+1);
				hChargeSigCorr[jj]->Fill(Q);
				MeanDiff[jj]+=Q;
				if (jj==0) nSigCut++;
			}
		}
	}


	/*Process the bck, again*/
	tBck->SetBranchAddress("ADC",ADC);
	tBck->SetBranchAddress("EvtMultiplicity",&EvtMultiplicity);
	tBck->SetBranchAddress("hit",hit);

	for (int ii=0;ii<Nb;ii++){
		QBckTot=0;
		QBckTotR=0;
		QBckTotL=0;
		tBck->GetEntry(ii);
		for (int jj=0;jj<Ntot;jj++){
			id=jj+N0;

			iRealDet=m_setup->getMarocCard(id);
			iH8500=m_setup->getH8500IdFromGlobal(id);
			iMarocChannel=m_setup->getMarocChannelFromGlobal(id);
			iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
			iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
			iReconPixel=m_setup->getPixelReconId(id);
			Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);
			Q=ADC[id]-PedBck[jj];
			QBckTot+=Q/Gain;


			if (jj<Ntot/2) QBckTotL+=Q/Gain;
			else QBckTotR+=Q/Gain;
		}
		hChargeBckTot->Fill(QBckTot);
		hChargeDiffTot->Fill(QBckTot,-1);

		hChargeBckTotL->Fill(QBckTotL);
		hChargeBckTotR->Fill(QBckTotR);
		hChargeBckTotLR->Fill(QBckTotR,QBckTotL);

		hChargeDiffTotR->Fill(QBckTotR,-1);
		hChargeDiffTotL->Fill(QBckTotL,-1);


		flagQcut=1;
		if (QBckTot<QTotThr) flagQcut=0;

		for (int jj=0;jj<Ntot;jj++){
			id=jj+N0;

			iRealDet=m_setup->getMarocCard(id);
			iH8500=m_setup->getH8500IdFromGlobal(id);
			iMarocChannel=m_setup->getMarocChannelFromGlobal(id);
			iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
			iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
			iReconPixel=m_setup->getPixelReconId(id);
			Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);

			Q=ADC[id]-PedBck[jj];
			//hChargeBckVsTot[jj]->Fill(Q,QBckTot);

			if (flagQcut){
				hChargeBckCorr[jj]->Fill(Q);
				hChargeDiff[jj]->Fill(Q,-1);
				MeanDiff[jj]-=Q;
				if (jj==0) nBckCut++;
			}
		}
	}

	for (int jj=0;jj<Ntot;jj++){
		MeanDiff[jj]/=(nSigCut-nBckCut);
	}

	for (int iGlobal=N0;iGlobal<(Ntot+N0);iGlobal++){
		iRealDet=m_setup->getMarocCard(iGlobal);
		iH8500=m_setup->getH8500IdFromGlobal(iGlobal);
		iMarocChannel=m_setup->getMarocChannelFromGlobal(iGlobal);

		iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
		iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
		iReconPixel=m_setup->getPixelReconId(iGlobal);

		if (iRealDet==32){
			ix=iH8500%8;
		}
		else {
			ix=-iH8500%8-1;
		}
		iy=7-iH8500/8;

		oldMeanSig=hChargeSig[iGlobal-N0]->GetMean();
		oldMeanBck=hChargeBck[iGlobal-N0]->GetMean();
		oldMeanDiff=hChargeDiff[iGlobal-N0]->GetMean();


		Gain=m_setup->getPixelGain(iReconFace,iReconDet,iReconPixel);

		MeanDiffCorrected=MeanDiff[iGlobal-N0]/Gain;


		hGrid->Fill(ix,iy,iGlobal-N0);
		hGainMap->Fill(ix,iy,Gain);
		hMeanSig->Fill(ix,iy,oldMeanSig);
		hMeanBck->Fill(ix,iy,oldMeanBck);
		hMeanDiff->Fill(ix,iy,MeanDiffCorrected);



		hChargeDiff[iGlobal-N0]->Fit("pol1","LQ","R",0.5E3,.9E3);
		hChargeDiff[iGlobal-N0]->GetFunction("pol1")->SetLineColor(2);

		fExp[iReconFace][iReconDet][iReconPixel]=MeanDiffCorrected;

	}



	if (fDoRoot){
		cout<<"Geant4 recon: start filling histograms"<<endl;
		cout<<"There are: "<<NeventsMC<<" MonteCarlo events"<<endl;
		for (int ii=0;ii<NeventsMC;ii++){
			cMC->GetEntry(ii);

			digi=event->getCollection(OpNoviceDigi::Class(),"DetDigiMC");

			Nhits=digi->GetEntries();
			for (int jj=0;jj<Nhits;jj++){
				faceNumber=((OpNoviceDigi*)digi->At(jj))->GetFaceNumber();
				detNumber=((OpNoviceDigi*)digi->At(jj))->GetDetectorNumber();
				pixelNumber=((OpNoviceDigi*)digi->At(jj))->GetPixelNumber();
				hSimChargeMC[faceNumber][detNumber].at(pixelNumber)->Fill(((OpNoviceDigi*)digi->At(jj))->GetPheCount());
				chargeMC[faceNumber][detNumber].at(pixelNumber)+=((OpNoviceDigi*)digi->At(jj))->GetPheCount();
			}
		}
		cout<<"Geant4 recon: mean"<<endl;
		for (int ii=0;ii<6;ii++){
			for (int jj=0;jj<m_detector->getNdet(ii);jj++){
				if (m_detector->isDetPresent(ii,jj)){
					for (int kk=0;kk<m_detector->getNPixels(ii,jj);kk++){
						qMeanMC=chargeMC[ii][jj].at(kk)/NeventsMC;
						fMC[ii][jj][kk]=qMeanMC;
					}
				}
			}
		}
	}


	vin.SetXYZ(xSource,3.,ySource);
	for (int ii=0;ii<6;ii++){
		for (int jj=0;jj<m_detector->getNdet(ii);jj++){
			if (m_detector->isDetPresent(ii,jj)){
				for (int kk=0;kk<m_detector->getNPixels(ii,jj);kk++){
					F=m_utils->SinglePixelAverageCharge(vin,ii,jj,kk);
					//Corr=CorrectionPixel(vin,ii,jj,kk,m_detector);
				//	cout<<"Setting: "<<F<<" "<<ii<<" "<<jj<<" "<<kk<<endl;
				//	cin.get();
					fTeo[ii][jj][kk]=F;
					if (!fDoRoot) {
						fMC[ii][jj][kk]=0;
						for (int qq=0;qq<1000;qq++){
							hSimChargeMC[ii][jj].at(kk)->Fill(gRandom->Poisson(F));
						}
					}
				}
			}
		}
	}



	cout<<"Comparison, fixing normalization"<<endl;
	/*Now compute normalization and fill histograms*/
	fNormTeo=fNormExp=fNormMC=0;
	for (int iface=0;iface<6;iface++){
		for (int idetector=0;idetector<m_detector->getNdet(iface);idetector++){
			if (m_detector->isDetPresent(iface,idetector)){
				for (int ipixel=0;ipixel<m_detector->getNPixels(iface,idetector);ipixel++){
					fNormTeo+=fTeo[iface][idetector][ipixel];
					fNormMC+=fMC[iface][idetector][ipixel];
					fNormExp+=fExp[iface][idetector][ipixel];
					hChargeTeo[iface][idetector]->Fill(ipixel,fTeo[iface][idetector][ipixel]);
					hChargeExp[iface][idetector]->Fill(ipixel,fExp[iface][idetector][ipixel]);
					if (fDoRoot) hChargeMC[iface][idetector]->Fill(ipixel,fMC[iface][idetector][ipixel]);
				}
			}
		}
	}


	/*Histograms have been filled. Scale them to compare*/
	for (int ii=0;ii<6;ii++){
		for (int jj=0;jj<m_detector->getNdet(ii);jj++){
			if (m_detector->isDetPresent(ii,jj)){
				hChargeExp[ii][jj]->Scale(1./fNormExp);
				hChargeTeo[ii][jj]->Scale(1./fNormTeo);
				if (fDoRoot) hChargeMC[ii][jj]->Scale(1./fNormMC);
				/*Set the error*/
				for (int ipixel=0;ipixel<m_detector->getNPixels(ii,jj);ipixel++){
					hChargeExp[ii][jj]->SetBinError(ipixel+1,3E-3); //the error is ~ 3E-3
				}

				for (int ipixel=0;ipixel<m_detector->getNPixels(ii,jj);ipixel++){
					ix=7-ipixel%8;
					iy=ipixel/8;
					hChargeComparison[ii][jj]->Fill(ix,iy,hChargeExp[ii][jj]->GetBinContent(ipixel+1)-hChargeTeo[ii][jj]->GetBinContent(ipixel+1));

				}

			}
		}
	}

	/*Plots*/
	TCanvas **c=new TCanvas*[Ntot];
	TLatex latex;

	for (int iGlobal=N0;iGlobal<(Ntot+N0);iGlobal++){
		iRealDet=m_setup->getMarocCard(iGlobal);
		iH8500=m_setup->getH8500IdFromGlobal(iGlobal);
		iMarocChannel=m_setup->getMarocChannelFromGlobal(iGlobal);

		iReconDet=m_setup->getReconstructionDetectorID(iRealDet);
		iReconFace=m_setup->getReconstructionDetectorFace(iRealDet);
		iReconPixel=m_setup->getPixelReconId(iGlobal);



		c[iGlobal-N0]=new TCanvas(Form("c%i",(iGlobal-N0)),Form("c%i:H8500_%i",(iGlobal-N0),iH8500));
		c[iGlobal-N0]->Divide(3,3);
		c[iGlobal-N0]->cd(1)->SetLogy();


		c[iGlobal-N0]->cd(1)->SetLogy();
		hChargeSig[iGlobal-N0]->GetXaxis()->SetRangeUser(1250,3000);

		hChargeSig[iGlobal-N0]->SetLineColor(1);
		hChargeSig[iGlobal-N0]->Draw();
		hChargeHitSig[iGlobal-N0]->SetLineColor(4);
		hChargeHitSig[iGlobal-N0]->Draw("SAMES");

		c[iGlobal-N0]->cd(2)->SetLogy();
		hChargeBck[iGlobal-N0]->GetXaxis()->SetRangeUser(1250,3000);
		hChargeBck[iGlobal-N0]->SetLineColor(2);
		hChargeBck[iGlobal-N0]->Draw();
		hChargeHitBck[iGlobal-N0]->SetLineColor(6);
		hChargeHitBck[iGlobal-N0]->Draw("SAMES");

		c[iGlobal-N0]->cd(3)->SetLogy();
		hChargeSig[iGlobal-N0]->GetXaxis()->SetRangeUser(1250,3000);
		hChargeSig[iGlobal-N0]->Draw();
		hChargeBck[iGlobal-N0]->Draw("SAMES");

		c[iGlobal-N0]->cd(4)->SetLogy();
		//	hChargeSigCorr[iGlobal-N0]->GetXaxis()->SetRangeUser(1250,3000);
		hChargeSigCorr[iGlobal-N0]->SetFillColor(kYellow-9);
		hChargeSigCorr[iGlobal-N0]->Draw();
		hChargeBckCorr[iGlobal-N0]->SetLineColor(2);
		hChargeBckCorr[iGlobal-N0]->SetFillColor(kRed-9);
		hChargeBckCorr[iGlobal-N0]->Draw("SAMES");

		c[iGlobal-N0]->cd(5)->SetLogy();
		hChargeDiff[iGlobal-N0]->GetXaxis()->SetRangeUser(-500,1600);
		hChargeDiff[iGlobal-N0]->Draw();
		latex.DrawLatex(1000,100,Form("m: %f",MeanDiff[iGlobal-N0]));
		c[iGlobal-N0]->cd(6);
		hSimChargeMC[iReconFace][iReconDet].at(iReconPixel)->Draw();


		//hChargeDiffCorr[iGlobal-N0]->GetXaxis()->SetRangeUser(-500,1600);
		//	hChargeDiffCorr[iGlobal-N0]->Draw();

		c[iGlobal-N0]->cd(7);
		//hChargeSigVsTot[iGlobal-N0]->Draw("colz");

		c[iGlobal-N0]->cd(8);
		//hChargeBckVsTot[iGlobal-N0]->Draw("colz");

		c[iGlobal-N0]->cd(9);





		if ((iGlobal-N0)==0) c[iGlobal-N0]->Print((fOutNamePS+"(").c_str());
		else  c[iGlobal-N0]->Print(fOutNamePS.c_str());
		fOut->cd();
		c[iGlobal-N0]->Write();
	}

	TLine *l=new TLine(-0.5,-0.5,-0.5,7.5);l->SetLineWidth(2);l->SetLineColor(2);



	TCanvas *ca=new TCanvas("ca","ca");
	ca->Divide(3,3);
	ca->cd(1);
	hGainMap->GetXaxis()->SetRangeUser(1000,2000);
	hGainMap->Draw("colz");
	hGrid->SetMarkerSize(1.8);hGrid->SetMarkerColor(0);
	hGrid->Draw("TEXTSAME");
	l->Draw("SAME");


	ca->cd(2);
	hMeanSig->SetStats(0);
	hMeanSig->Draw("colz");
	hGrid->Draw("TEXTSAME");
	l->Draw("SAME");

	ca->cd(3);
	hMeanBck->SetStats(0);
	hMeanBck->Draw("colz");
	hGrid->Draw("TEXTSAME");

	ca->cd(4);
	hMeanDiff->SetStats(0);
	hMeanDiff->Draw("colz");
	hGrid->Draw("TEXTSAME");
	l->Draw("SAME");

	ca->cd(7);
	hHitSig->SetStats(0);
	hHitSig->Draw("colz");
	hGrid->Draw("TEXTSAME");

	ca->cd(8);
	hHitBck->SetStats(0);
	hHitBck->Draw("colz");
	hGrid->Draw("TEXTSAME");


	ca->cd(9);
	hHitDiff->SetStats(0);
	hHitDiff->Draw("colz");
	hGrid->Draw("TEXTSAME");

	ca->Print(fOutNamePS.c_str());
	fOut->cd();
	ca->Write();

	TCanvas *ctot=new TCanvas("ctot","ctot");
	ctot->Divide(3,3);
	ctot->cd(1);
	hChargeSigTot->Draw();
	hChargeBckTot->SetLineColor(2);
	hChargeBckTot->Draw("SAMES");
	ctot->cd(2);
	hChargeSigTotL->Draw();
	hChargeBckTotL->SetLineColor(2);
	hChargeBckTotL->Draw("SAMES");
	ctot->cd(3);
	hChargeSigTotR->Draw();
	hChargeBckTotR->SetLineColor(2);
	hChargeBckTotR->Draw("SAMES");



	ctot->cd(4);
	hChargeDiffTot->Draw();
	ctot->cd(5);
	hChargeDiffTotL->Draw();
	ctot->cd(6);
	hChargeDiffTotR->Draw();

	ctot->cd(7);
	hChargeSigTotLR->Draw("colz");

	ctot->cd(8);
	hChargeBckTotLR->Draw("colz");



	ctot->Print(fOutNamePS.c_str());
	fOut->cd();
	ctot->Write();



	TCanvas *cRecon01=new TCanvas("cRecon01","cRecon01");
	cRecon01->Divide(2,2);
	iPad=0;
	for (int ii=0;ii<6;ii++){
		for (int jj=0;jj<m_detector->getNdet(ii);jj++){
			if (m_detector->isDetPresent(ii,jj)){
				cRecon01->cd(1+iPad)->SetGridx();
				cRecon01->cd(1+iPad)->SetGridy();

				hChargeExp[ii][jj]->SetStats(0);
				hChargeExp[ii][jj]->SetLineWidth(2);
				//hChargeExp[ii][jj]->GetYaxis()->SetRangeUser(0.,2);
				hChargeExp[ii][jj]->Draw();
				//hChargeExp[ii][jj]->GetYaxis()->SetRangeUser(0.,2);


				hChargeTeo[ii][jj]->SetStats(0);
				hChargeTeo[ii][jj]->SetLineWidth(2);
				hChargeTeo[ii][jj]->SetLineColor(2);
				hChargeTeo[ii][jj]->Draw("SAME");
				if (fDoRoot){
					hChargeMC[ii][jj]->SetStats(0);
					hChargeMC[ii][jj]->SetLineWidth(2);
					hChargeMC[ii][jj]->SetLineColor(3);
					hChargeMC[ii][jj]->Draw("SAME");
				}
				/*Also write histograms to file*/
				fOut->cd();
				hChargeExp[ii][jj]->Write();
				hChargeTeo[ii][jj]->Write();
				hChargeMC[ii][jj]->Write();
				iPad++;
			}
		}
	}

	for (int ii=0;ii<6;ii++){
		for (int jj=0;jj<m_detector->getNdet(ii);jj++){
			if (m_detector->isDetPresent(ii,jj)){
				cRecon01->cd(1+iPad)->SetGridx();
				cRecon01->cd(1+iPad)->SetGridy();

				hChargeComparison[ii][jj]->SetStats(0);
				hChargeComparison[ii][jj]->Draw("colz");

				iPad++;
			}
		}
	}

	cRecon01->Print((fOutNamePS+")").c_str());
	fOut->cd();
	cRecon01->Write();




	if (fDoBatch==0){
		gui.Run(1);
	}




	cout<<"Done"<<endl;
}
Beispiel #17
0
//void TMVAClassification( TString myMethodList = "" )
void tmvaClassifier( TString myMethodList = "", TString inputDir="~/work/ewkzp2j_5311/ll/", bool minimalTrain=false, bool useQG=false)
{   
  gSystem->ExpandPathName(inputDir);
  TString pf("base_weights");
  if(!minimalTrain){
    if(useQG) pf="full_weights";
    else      pf="weights";
  }
  TMVA::gConfig().GetIONames().fWeightFileDir = inputDir + pf;
  
  // The explicit loading of the shared libTMVA is done in TMVAlogon.C, defined in .rootrc
  // if you use your private .rootrc, or run from a different directory, please copy the
  // corresponding lines from .rootrc
  
  // methods to be processed can be given as an argument; use format:
  //
  // mylinux~> root -l TMVAClassification.C\(\"myMethod1,myMethod2,myMethod3\"\)
  //
  // if you like to use a method via the plugin mechanism, we recommend using
  //
  // mylinux~> root -l TMVAClassification.C\(\"P_myMethod\"\)
  // (an example is given for using the BDT as plugin (see below),
  // but of course the real application is when you write your own
  // method based)
  
  //---------------------------------------------------------------
  // This loads the library
  TMVA::Tools::Instance();
  
  // Default MVA methods to be trained + tested
  std::map<std::string,int> Use;
  
  // --- Cut optimisation
  Use["Cuts"]            = 0;
  Use["CutsD"]           = 0;
  Use["CutsPCA"]         = 0;
  Use["CutsGA"]          = 0;
  Use["CutsSA"]          = 0;
  // 
  // --- 1-dimensional likelihood ("naive Bayes estimator")
  Use["Likelihood"]      = 0;
  Use["LikelihoodD"]     = 1; // the "D" extension indicates decorrelated input variables (see option strings)
  Use["LikelihoodPCA"]   = 0; // the "PCA" extension indicates PCA-transformed input variables (see option strings)
  Use["LikelihoodKDE"]   = 0;
  Use["LikelihoodMIX"]   = 0;
  //
  // --- Mutidimensional likelihood and Nearest-Neighbour methods
  Use["PDERS"]           = 0;
  Use["PDERSD"]          = 0;
  Use["PDERSPCA"]        = 0;
  Use["PDEFoam"]         = 0;
  Use["PDEFoamBoost"]    = 0; // uses generalised MVA method boosting
  Use["KNN"]             = 0; // k-nearest neighbour method
  //
  // --- Linear Discriminant Analysis
  Use["LD"]              = 0; // Linear Discriminant identical to Fisher
  Use["Fisher"]          = 1;
  Use["FisherCat"]       = 0;//added by loic
  Use["FisherG"]         = 0;
  Use["BoostedFisher"]   = 0; // uses generalised MVA method boosting
  Use["HMatrix"]         = 0;
  //
  // --- Function Discriminant analysis
  Use["FDA_GA"]          = 0; // minimisation of user-defined function using Genetics Algorithm
  Use["FDA_SA"]          = 0;
  Use["FDA_MC"]          = 0;
  Use["FDA_MT"]          = 0;
  Use["FDA_GAMT"]        = 0;
  Use["FDA_MCMT"]        = 0;
  //
  // --- Neural Networks (all are feed-forward Multilayer Perceptrons)
  Use["MLP"]             = 0; // Recommended ANN
  Use["MLPBFGS"]         = 0; // Recommended ANN with optional training method
  Use["MLPBNN"]          = 0; // Recommended ANN with BFGS training method and bayesian regulator
  Use["CFMlpANN"]        = 0; // Depreciated ANN from ALEPH
  Use["TMlpANN"]         = 0; // ROOT's own ANN
  //
  // --- Support Vector Machine 
  Use["SVM"]             = 0;
  // 
  // --- Boosted Decision Trees
  Use["BDT"]             = 0; // uses Adaptive Boost
  Use["BDTG"]            = 0; // uses Gradient Boost
  Use["BDTB"]            = 0; // uses Bagging
  Use["BDTD"]            = 1; // decorrelation + Adaptive Boost
  Use["BDTF"]            = 0; // allow usage of fisher discriminant for node splitting 
  // 
  // --- Friedman's RuleFit method, ie, an optimised series of cuts ("rules")
  Use["RuleFit"]         = 0;
  // ---------------------------------------------------------------

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

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

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

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

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

  // --- Here the preparation phase begins

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

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

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

  // Read training and test data
  // (it is also possible to use ASCII format as input -> see TMVA Users Guide)
  //   TString fname = "./tmva_class_example.root";
   
  //if (gSystem->AccessPathName( fname ))  // file does not exist in local directory
  //   gSystem->Exec("wget http://root.cern.ch/files/tmva_class_example.root");
   
  
  //   std::cout << "--- TMVAClassification       : Using input file: " << input->GetName() << std::endl;
   
  // --- Register the training and test trees
  TChain *signal     = new TChain("ewkzp2j");
  TChain *background = new TChain("ewkzp2j");
  TSystemDirectory dir(inputDir,inputDir);
  TList *files = dir.GetListOfFiles();
  if (files) {
    TSystemFile *file;
    TString fname;
    TIter next(files);
    while ((file=(TSystemFile*)next())) {
      fname = file->GetName();
      if(!fname.EndsWith("_summary.root")) continue;
      if(fname.Contains("Data")) continue;
      if(!fname.Contains("DY")) continue;
      bool isSignal(false);
      if(fname.Contains("JJ")) { signal->Add(fname); isSignal=true; }
      else if(fname.Contains("50toInf") && fname.Contains("DY")) background->Add(fname);
      cout << fname << " added as " << (isSignal ? "signal" : "background") << endl;
    }
  }else{
    cout << "[Error] no files found in " << inputDir << endl;
  }
  cout << "Signal has " << signal->GetEntries() << " raw events" << endl
       << "Background has " << background->GetEntries() << " raw events"<< endl;

  // global event weights per tree
  Double_t signalWeight     = 1.0;
  Double_t backgroundWeight = 1.0;
  factory->AddSignalTree    ( signal,     signalWeight     );
  factory->AddBackgroundTree( background, backgroundWeight );
  // event-per-event weights per tree
  factory->SetBackgroundWeightExpression( "weight/cnorm" );
  factory->SetSignalWeightExpression( "weight/cnorm" );

  //define variables for the training
  if(minimalTrain)
    {
      factory->AddVariable( "mjj",     "M_{jj}"              "GeV", 'F' );
      factory->AddVariable( "detajj",  "#Delta#eta_{jj}",     "",    'F' );
      factory->AddVariable( "spt",     "#Delta_{rel}",        "GeV", 'F' );
    }
  else
    {
      factory->AddVariable( "mjj",     "M_{jj}"              "GeV",  'F' );
      factory->AddVariable( "detajj",  "#Delta#eta_{jj}",     "",    'F' );
      factory->AddVariable( "setajj",  "#Sigma#eta_{j}",      "",    'F' );
      factory->AddVariable( "eta1",    "#eta(1)",             "",    'F' );
      factory->AddVariable( "eta2",    "#eta(2)",             "",    'F' );
      factory->AddVariable( "pt1",     "p_{T}(1)",            "GeV", 'F' );
      factory->AddVariable( "pt2",     "p_{T}(2)",            "GeV", 'F' );
      factory->AddVariable( "spt",     "#Delta_{rel}",        "GeV", 'F' );
      if(useQG) factory->AddVariable( "qg1",   "q/g(1)",      "",    'F' );
      if(useQG) factory->AddVariable( "qg2",   "q/g(2)",      "",    'F' );
    }
  

  // Apply additional cuts on the signal and background samples (can be different)
  TCut mycuts = ""; // for example: TCut mycuts = "abs(var1)<0.5 && abs(var2-0.5)<1";
  TCut mycutb = ""; // for example: TCut mycutb = "abs(var1)<0.5";
  factory->PrepareTrainingAndTestTree( mycuts, mycutb,
				       "nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!V" );

  // ---- Book MVA methods
  //
  // Please lookup the various method configuration options in the corresponding cxx files, eg:
  // src/MethoCuts.cxx, etc, or here: http://tmva.sourceforge.net/optionRef.html
  // it is possible to preset ranges in the option string in which the cut optimisation should be done:
  // "...:CutRangeMin[2]=-1:CutRangeMax[2]=1"...", where [2] is the third input variable

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  // Fisher discriminant (same as LD)
  if (Use["Fisher"])
    factory->BookMethod( TMVA::Types::kFisher, "Fisher", "H:!V:Fisher:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
   
  if (Use["FisherCat"]){
    TMVA::MethodBase* fiCat = factory->BookMethod( TMVA::Types::kCategory, "FisherCat","" );
    TMVA::MethodCategory* mcategory = dynamic_cast<TMVA::MethodCategory*>(fiCat);
    mcategory->AddMethod( "mjj<250", "mjj:detajj:spt:", TMVA::Types::kFisher, "Fisher_Cat1", "H:!V:Fisher:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
    mcategory->AddMethod( "mjj>=250&&mjj<350" , "mjj:detajj:spt:", TMVA::Types::kFisher, "Fisher_Cat0000", "H:!V:Fisher:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
    mcategory->AddMethod( "mjj>=350&&mjj<450" , "mjj:detajj:spt:", TMVA::Types::kFisher, "Fisher_Cat0350", "H:!V:Fisher:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
    mcategory->AddMethod( "mjj>=450&&mjj<550" , "mjj:detajj:spt:", TMVA::Types::kFisher, "Fisher_Cat0450", "H:!V:Fisher:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
    mcategory->AddMethod( "mjj>=550&&mjj<750" , "mjj:detajj:spt:", TMVA::Types::kFisher, "Fisher_Cat0550", "H:!V:Fisher:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
    mcategory->AddMethod( "mjj>=750&&mjj<1000", "mjj:detajj:spt:", TMVA::Types::kFisher, "Fisher_Cat0750", "H:!V:Fisher:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
    mcategory->AddMethod( "mjj>=1000"         , "mjj:detajj:spt:", TMVA::Types::kFisher, "Fisher_Cat1000", "H:!V:Fisher:VarTransform=None:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=50:NsmoothMVAPdf=10" );
  }


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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




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

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

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

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

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

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

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

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

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

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

  std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
  std::cout << "==> TMVAClassification is done!" << std::endl;
  std::cout << " ==> Weights are stored in " << TMVA::gConfig().GetIONames().fWeightFileDir << std::endl;
  delete factory;



  // Launch the GUI for the root macros
  //   if (!gROOT->IsBatch()) TMVAGui( outfileName );
}
Beispiel #18
0
//! main program
int main (int argc, char** argv)
{

  std::string outputRootName = "matchDistance.root" ;
  std::string fileName (argv[1]) ;
  boost::shared_ptr<edm::ProcessDesc> processDesc = edm::readConfigFile (fileName) ;
  boost::shared_ptr<edm::ParameterSet> parameterSet = processDesc->getProcessPSet () ;
  std::cout << parameterSet->dump () << std::endl ; //PG for testing
  
  edm::ParameterSet subPSetSelections =  parameterSet->getParameter<edm::ParameterSet> ("selections") ;
  //cuts on SC Energy
  double EnergyMaxSC = subPSetSelections.getParameter<double> ("EnergyMaxSC") ;
  double EnergyMinSC = subPSetSelections.getParameter<double> ("EnergyMinSC") ;
  
  //cuts on Angle Muon / SCdirection
  double angleMAX = subPSetSelections.getParameter<double> ("angleMAX") ;
  double angleMIN = subPSetSelections.getParameter<double> ("angleMIN") ;
 
  //cuts on Xtal Energy
  double XtalMaxEnergyMin = subPSetSelections.getParameter<double> ("XtalMaxEnergyMin") ;
  double XtalMaxEnergyMax = subPSetSelections.getParameter<double> ("XtalMaxEnergyMax") ;
  double XtalMinEnergy = subPSetSelections.getParameter<double> ("XtalMinEnergy") ;
  
  //cuts on Windows
  double phiWINDOW    = subPSetSelections.getParameter<double> ("phiWINDOW") ;
  double ietaMAX    = subPSetSelections.getUntrackedParameter<int> ("ietaMAX",85) ;

  edm::ParameterSet subPSetInput =  
    parameterSet->getParameter<edm::ParameterSet> ("inputNtuples") ;
  std::vector<std::string> inputFiles = 
   subPSetInput.getParameter<std::vector<std::string> > ("inputFiles") ;
  std::cout << "reading : " ;

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

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

  TProfile2D aveEoxMap ("aveEoxMap","aveEoxMap",360,1.,361.,172,-86.,86.); 

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

  //PG loop over entries
  for (int entry = 0 ; entry < nEntries ; ++entry)
    {
      chain->GetEntry (entry) ;
      if (entry % 100000 == 0) std::cout << "reading entry " << entry << std::endl ;


      std::vector<ect::association> associations ;
      ect::fillAssocVector (associations, treeVars) ;
      ect::selectOnDR (associations, treeVars, 0.3) ;

      //PG loop on associations vector
      for (unsigned int i = 0 ; 
           i < associations.size () ; 
           ++i)
        {
          int MUindex = associations.at (i).first  ;
          int SCindex = associations.at (i).second ;

          TVector3 SC0_pos (treeVars.superClusterX[SCindex], 
                            treeVars.superClusterY[SCindex], 
                            treeVars.superClusterZ[SCindex]) ; 
	       
          TVector3 MuonDir (treeVars.muonPx[MUindex], 
                            treeVars.muonPy[MUindex], 
                            treeVars.muonPz[MUindex]) ;

          float dummyEmax = 0.;
          float dummyLmax = 0.;
          int numCrystalEMax = -1;
          int numCrystalLMax = -1;
          bool SclOk = false;
          double dummyLength = 0;
       
          for (int XTLindex = treeVars.xtalIndexInSuperCluster[SCindex] ;
               XTLindex < treeVars.xtalIndexInSuperCluster[SCindex] +
                          treeVars.nXtalsInSuperCluster[SCindex] ; 
               ++XTLindex)
            {
              if(treeVars.xtalTkLength[XTLindex] == -1) continue;
          
              dummyLength+= treeVars.xtalTkLength[XTLindex];
          
              //---- check the link Xtal with max energy  == Xtal with max length ----
              if (treeVars.xtalEnergy[XTLindex] > dummyEmax) numCrystalEMax = XTLindex;
              if(treeVars.xtalTkLength[XTLindex] > dummyLmax) numCrystalLMax = XTLindex;
            }
       
          //   if( abs(treeVars.muonTkLengthInEcalDetail[associations.at(i).first] - dummyLength) > 0.5) continue;
       
          if ( (numCrystalEMax != numCrystalLMax) && 
               (numCrystalEMax != -1) && 
               (numCrystalLMax != -1)) 
          {
            if ( 3.*treeVars.xtalEnergy[numCrystalLMax] < 
                 treeVars.xtalTkLength[numCrystalLMax] * 0.0125) SclOk = false;
          }
          else SclOk = true;
          if ((numCrystalEMax == -1) || (numCrystalLMax == -1)) SclOk = false;
          if(SclOk == false) continue;

          double SCphi = fabs(SC0_pos.Phi()) / 3.1415 * 180. ;
          if ( (SCphi < 90. - phiWINDOW/2) || (SCphi > 90. + phiWINDOW/2) ) continue;

          double SCieta = SC0_pos.Eta () / 0.0175 ;
          if (fabs (SCieta) > ietaMAX) continue ;
        
          double angle = MuonDir.Angle ( SC0_pos ) ;
          if( angle > 3.1415/2. ) angle = 3.1415 - angle; // angle belongs to [0:90]

          if ((angle < angleMIN) || (angle >= angleMAX)) continue ;

          if ((treeVars.superClusterRawEnergy[SCindex] >= EnergyMaxSC) || 
              (treeVars.superClusterRawEnergy[SCindex] < EnergyMinSC)) continue ; 

          std::pair <int,int> maxima = findMaxXtalsInSC (treeVars, SCindex) ;
          double XtalEnergyMax = treeVars.xtalEnergy[maxima.first] ;

          if ((XtalEnergyMax < XtalMaxEnergyMin) || 
              (XtalEnergyMax >= XtalMaxEnergyMax)) continue ;
          
          //loop su cristalli di Supercluster Associato
          for (int XTLindex = treeVars.xtalIndexInSuperCluster[SCindex] ;
                   XTLindex < treeVars.xtalIndexInSuperCluster[SCindex] +
                              treeVars.nXtalsInSuperCluster[SCindex] ;
                   ++XTLindex)
            {
              if (treeVars.xtalEnergy[XTLindex] < XtalMinEnergy) continue ;               
              if (treeVars.xtalTkLength[XTLindex] <= 0.) continue ;
              double eox = treeVars.xtalEnergy[XTLindex] / 
                           treeVars.xtalTkLength[XTLindex] ;
              EBDetId dummy = EBDetId::unhashIndex (treeVars.xtalHashedIndex[XTLindex]) ;
              aveEoxMap.Fill (dummy.iphi (), dummy.ieta (), eox) ;
            }
        }
    } //PG loop over entries

  TH1F aveEoxDistr ("aveEoxDistr","aveEoxDistr",500,0,0.5) ;
  for (int phiIndex = 1 ; phiIndex < 361 ; ++phiIndex)
    for (int etaIndex = 1 ; etaIndex < 173 ; ++etaIndex)
      aveEoxDistr.Fill (aveEoxMap.GetBinContent (phiIndex,etaIndex)) ;

  TFile saving ("singleXtalEox.root","recreate") ;
  saving.cd () ;  
  aveEoxMap.Write () ;
  aveEoxDistr.Write () ;
  saving.Close () ;

  return 0 ;
}
void GetBinM(vector<RooUnfoldResponse*> &BinM, vector<TH1D*> &h_gen, vector<TH1D*> &h_reco, bool madgraph=1, int elec=0){

  TH2D* BinMigration=new TH2D("BinMigration","BinMigration",nphistar,phistarBins,nphistar,phistarBins);
  BinMigration->Sumw2();
  TH1D* Gen=new TH1D("Gen","gen",nphistar,phistarBins);
  Gen->Sumw2();
  TH1D* Reco=new TH1D("Reco","Reco",nphistar,phistarBins);
  Reco->Sumw2();

  TChain* t = new TChain(reco_name.c_str(),reco_name.c_str());
  int nfiles;
  if (madgraph)  nfiles=t->Add(File_Signal_reco.c_str());
  else nfiles=t->Add(File_Powheg_reco.c_str());

  TBranch *b_reco=t->GetBranch("reco");
  TBranch *b_truth=t->GetBranch("truth");
  TBranch *b_event=t->GetBranch("event_info");
  TLeaf *l_phistar=b_reco->GetLeaf("z_phistar_dressed");
  TLeaf *l_phistar_true=b_truth->GetLeaf("z_phistar_dressed");
  TLeaf *l_en=b_event->GetLeaf("event_number");
  if (elec==1) l_phistar_true=b_truth->GetLeaf("z_phistar_born");
  if (elec==2) l_phistar_true=b_truth->GetLeaf("z_phistar_naked");
  int nweights;
  t->SetBranchAddress("weight_size",&nweights);
  t->GetEntry(0);
  cout<<"The sample has nweights: "<<nweights<<endl;
  double weights[nweights];
  int weightid[nweights];
  t->SetBranchAddress("weights",&weights);
  t->SetBranchAddress("weight_ids",&weightid);

  cout<<"Entries: "<<t->GetEntries()<<endl;
  cout<<"reading signal reco "<<endl;
  for (int i=0; i<t->GetEntries();i++){
    // if (!madgraph && (i>N_MC+50000 || i<50000) &&N_MC!=-1) continue;
    if (!madgraph && i>N_MC &&N_MC!=-1) continue;
    //for (int i=0; i<50000;i++){
    t->GetEntry(i);
    double phistar=l_phistar->GetValue();
    double phistar_true=l_phistar_true->GetValue();
    double weight =1;
    double eventn=l_en->GetValue();
    // else en=eventn;
    for (int w=0; w<nweights;w++){
      if (weightid[w]==1 || weightid[w]==2 || weightid[w]==12 || weightid[w]==13 || weightid[w]==20 || weightid[w]==30) {weight=weight*weights[w];}
    }
    Gen ->Fill(phistar_true,weight);
    Reco->Fill(phistar,weight);
    BinMigration->Fill(phistar,phistar_true,weight); 
  }
  if (!madgraph){
    TCanvas* BM = new TCanvas("BM","BM",800,900);
    BinMigration->GetXaxis()->SetRangeUser(0.001,3.2);
    BinMigration->GetXaxis()->SetTitle("#phi^{*}(reconstructed)");
    BinMigration->GetXaxis()->SetTitleOffset(0.8);
    BinMigration->GetXaxis()->SetTitleSize(0.04);
    BinMigration->GetXaxis()->SetLabelOffset(-0.01);
    BinMigration->GetXaxis()->SetLabelSize(0.04);
    BinMigration->GetYaxis()->SetTitleOffset(1.05);
    BinMigration->GetYaxis()->SetTitleSize(0.04);
    BinMigration->GetYaxis()->SetLabelSize(0.04);
    BinMigration->GetYaxis()->SetRangeUser(0.001,3.2);
    BinMigration->GetYaxis()->SetTitle("#phi^{*}(generated)");
    BinMigration->GetZaxis()->SetTitleOffset(-0.004);
    BinMigration->SetStats(0);
    BinMigration->SetBit( TH2::kNoTitle, true );
    BM->SetLogx();
    BM->SetLogy();
    BM->SetLogz();
    BinMigration->Draw("COLZ");
    TLatex mark;
    mark.SetTextSize(0.04);
    mark.SetTextFont(42);
    mark.SetNDC(true);
    mark.DrawLatex(0.19,0.80,"Powheg");
  }
  RooUnfoldResponse* BinM1  =new RooUnfoldResponse (Reco,Gen,BinMigration);
  BinM.push_back(BinM1);
  h_gen.push_back(Gen);
  h_reco.push_back(Reco);
  for (int i=0; i<N_TOY; i++){
    TH1D* Recotemp=new TH1D("Reco","Reco",nphistar,phistarBins);
    Recotemp->Sumw2();
    TH2D* BinMigrationtemp=new TH2D("BinMigration","BinMigration",nphistar,phistarBins,nphistar,phistarBins);
    BinMigrationtemp->Sumw2();
    for (int j=0; j<nphistar; j++){
      double x=gRandom->Gaus(Reco->GetBinContent(j+1),Reco->GetBinError(j+1));
      Recotemp->SetBinContent(j+1,x);
      Recotemp->SetBinError(j+1,Reco->GetBinError(j+1));
      for (int k=0; k<nphistar; k++){
	double mean=BinMigration->GetBinContent(j+1,k+1);
	if (mean==0) continue;
	double error=BinMigration->GetBinError(j+1,k+1);
	if (mean/error<5){
	  x=gRandom->Poisson(mean);
	}
	else{
	  x=gRandom->Gaus(mean,error);
	}
	BinMigrationtemp->SetBinContent(j+1,k+1,x);
	BinMigrationtemp->SetBinError(j+1,k+1,error);
      }
    }
    TH1D* recotemp=BinMigrationtemp->ProjectionX();
    TH1D* gentemp=BinMigrationtemp->ProjectionY();
    RooUnfoldResponse* BinM1temp  =new RooUnfoldResponse (recotemp,gentemp,BinMigrationtemp);
    BinM.push_back(BinM1temp);
    h_reco.push_back(Recotemp);
  }

  cout<<"done reading data for "<<File_Signal_reco<<"  "<<reco_name<<endl;
  return;
}
void run_root_TSelector_SusyNtuple_ZPlusJetsNEW_1() {

//  TString options = TString(""); //TString(tag.c_str()) ;
// //     TString outputfile = "test.root";
//     string richtigerString = InputPath;
// //     int Position = richtigerString.find("mc12_8TeV.");
// //     outputfile = "histos_ZTauTau_" +  richtigerString.substr(Position+10,6)  + "_proof.root";
//     
//     int Position = -1;
//     Position = richtigerString.find("45_bg");
//     if (Position>0){
//       outputfile = "histos_test_" +  richtigerString.substr(Position+6,2)  + ".root";
//     }
//     else{
//       Position = richtigerString.find("45_signal");
//       if (Position>0){
//       outputfile = "histos_test_" +  richtigerString.substr(Position+3,2)  + ".root";
//       }
//     }
//     if(outputfile == ""){
//       cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
//       cout << "EMPTY OUPTPUTFILE STRING" << endl;
//       cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
//       abort();
//     }
//     cout << "outputfile= " << outputfile << endl;
    
      cout<<"Have you set up RootCore via  \"source RootCore/scripts/setup.sh\" ?"<<endl;  

      gSystem->Setenv("ROOTCOREDIR", "/data/etp3/jwittkow/analysis_SUSYTools_03_04_SusyNt_01_16/RootCore");
      gSystem->SetIncludePath("-I$ROOTCOREDIR/include/");

      gROOT->ProcessLine(".x $ROOTCOREDIR/scripts/load_packages.C+"); 

      TString selectorName = "TSelector_SusyNtuple"; // !!! enter the name of your Selector (without _C.so)

      TChain *ch;
      
      ch = new TChain("susyNt");

      TString processLine = ".L " + selectorName + ".cpp++g";
      TString execLine;

      gROOT->ProcessLine(processLine); // need to add this, or PoD at LRZ will not be able to load the .so
      gROOT->ProcessLine(".x $ROOTCOREDIR/scripts/load_packages.C+");
      
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147105.AlpgenPythia_Auto_P2011C_ZeeNp0.SusyNt.e1879_s1581_s1586_r3658_r3549_p1512_n0145.130711110642/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147105.AlpgenPythia_Auto_P2011C_ZeeNp0.SusyNt.e1879_s1581_s1586_r3658_r3549_p1512_n0145.130712075048/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147105.AlpgenPythia_Auto_P2011C_ZeeNp0.SusyNt.e1879_s1581_s1586_r3658_r3549_p1512_n0145.130713000355/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147106.AlpgenPythia_Auto_P2011C_ZeeNp1.SusyNt.e1879_s1581_s1586_r3658_r3549_p1512_n0145.130708185230/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147107.AlpgenPythia_Auto_P2011C_ZeeNp2.SusyNt.e1879_s1581_s1586_r3658_r3549_p1512_n0145.130711110708/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147108.AlpgenPythia_Auto_P2011C_ZeeNp3.SusyNt.e1879_s1581_s1586_r3658_r3549_p1512_n0145.130708185306/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147109.AlpgenPythia_Auto_P2011C_ZeeNp4.SusyNt.e1879_s1581_s1586_r3658_r3549_p1512_n0145.130708185318/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147110.AlpgenPythia_Auto_P2011C_ZeeNp5incl.SusyNt.e1879_s1581_s1586_r3658_r3549_p1512_n0145.130708185332/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147113.AlpgenPythia_Auto_P2011C_ZmumuNp0.SusyNt.e1880_s1581_s1586_r3658_r3549_p1512_n0145.130711110756/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147114.AlpgenPythia_Auto_P2011C_ZmumuNp1.SusyNt.e1880_s1581_s1586_r3658_r3549_p1512_n0145.130711110816/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147115.AlpgenPythia_Auto_P2011C_ZmumuNp2.SusyNt.e1880_s1581_s1586_r3658_r3549_p1512_n0145.130711110839/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147116.AlpgenPythia_Auto_P2011C_ZmumuNp3.SusyNt.e1880_s1581_s1586_r3658_r3549_p1512_n0145.130708185453/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147117.AlpgenPythia_Auto_P2011C_ZmumuNp4.SusyNt.e1880_s1581_s1586_r3658_r3549_p1512_n0145.130708185508/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147118.AlpgenPythia_Auto_P2011C_ZmumuNp5incl.SusyNt.e1880_s1581_s1586_r3658_r3549_p1512_n0145.130708185521/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147121.AlpgenPythia_Auto_P2011C_ZtautauNp0.SusyNt.e1881_s1581_s1586_r3658_r3549_p1512_n0145.130710211438/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147121.AlpgenPythia_Auto_P2011C_ZtautauNp0.SusyNt.e1881_s1581_s1586_r3658_r3549_p1512_n0145.130710211503/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147121.AlpgenPythia_Auto_P2011C_ZtautauNp0.SusyNt.e1881_s1581_s1586_r3658_r3549_p1512_n0145.130711110938/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147122.AlpgenPythia_Auto_P2011C_ZtautauNp1.SusyNt.e1881_s1581_s1586_r3658_r3549_p1512_n0145.130711085119/*");
ch->Add("/data/etp5/jwittkow/SusyNtuples_n0145_bg_new2/user.sfarrell.mc12_8TeV.147122.AlpgenPythia_Auto_P2011C_ZtautauNp1.SusyNt.e1881_s1581_s1586_r3658_r3549_p1512_n0145.130711111032/*");



//       ch->Add(InputPath);
//       ch->Add("/data/etp6/jwittkow/SusyNtuples_n0145_bg_new/WZ_SherpaVVtotautauqq/user.sfarrell.mc12_8TeV.157816.Sherpa_CT10_VVtotautauqq.SusyNt.e1515_s1499_s1504_r3658_r3549_p1512_n0145.130708082025/*");



//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Egamma/user.sfarrell.group.phys-susy.data12_8TeV.periodA.physics_Egamma.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708161315/user.sfarrell.116519._00003.susyNt.root");
      
//       ch->Add("/data/etp6/jwittkow/SusyNtuple_testdir/126893_n0145/*");
//       ch->Add("/data/etp6/jwittkow/user.gerbaudo.mc12_8TeV.126893.Sherpa_CT10_lllnu_WZ.SusyNt.e1434_s1499_s1504_r3658_r3549_p1512_n0145dev4.131220015824/*");
      
//       ch->Add("/data/etp6/jwittkow/SusyNtuples_n0145_bg_new/ttbar105200/*");

//             ch->Add("/data/etp6/jwittkow/SusyNtuples_n0145_signal_samples/user.gerbaudo.mc12_8TeV.177503.Herwigpp_sM_wA_noslep_notauhad_WH_2Lep_3.SusyNt.e2149_s1581_s1586_r3658_r3549_p1512_n0145.130806161345/user.gerbaudo.023459._00001.susyNt.root");
      
      

	    


      Long64_t nEntries = ch->GetEntries();
      ch->ls();

      cout << "all entries: " << nEntries << endl;


      TSelector_SusyNtuple* susyAna = new TSelector_SusyNtuple();
      susyAna->buildSumwMap(ch);
      ch->Process(susyAna);
      delete susyAna;
      
      if (ch) {delete ch; ch=0;}

  abort();
  }
Beispiel #21
0
void Plot_PDO_v_CH(const string& filename, int MMFE8 = -1){
  setstyle();
  
  TChain* tree = new TChain("VMM_data","VMM_data");

  tree->AddFile(filename.c_str());

  VMM_data* base = new VMM_data(tree);

  int N = tree->GetEntries();
  
  TH2D* hist = new TH2D("hist","hist",
			64*8, 0.5, 64*8+0.5,
			1100, -0.5, 1099.5);

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

    if(base->MMFE8 != MMFE8 && MMFE8 >= 0)
      continue;

    hist->Fill(base->CHword+64*base->VMM,base->PDO);
  }

  TH1D* histX = hist->ProjectionX("1DX",200,1100);

  TCanvas* c1 = Plot_2D("c1", hist, X_label, Y_label, Z_label, "Harvard chamber Run #");
  TCanvas* c2 = Plot_1D("c2", histX, X_label, Z_label, "Harvard chamber Run #");

  // TCanvas* can = new TCanvas("can","can",600,500);
  // can->SetLeftMargin(0.15);
  // can->SetRightMargin(0.22);
  // can->SetBottomMargin(0.15);
  // can->SetTopMargin(0.08);

  // can->Draw();
  // can->SetGridx();
  // can->SetGridy();
  // can->SetLogz();
  
  // can->cd();

  // hist->Draw("COLZ");

  // hist->GetXaxis()->CenterTitle();
  // hist->GetXaxis()->SetTitleFont(132);
  // hist->GetXaxis()->SetTitleSize(0.06);
  // hist->GetXaxis()->SetTitleOffset(1.06);
  // hist->GetXaxis()->SetLabelFont(132);
  // hist->GetXaxis()->SetLabelSize(0.05);
  // hist->GetXaxis()->SetTitle(varXname.c_str());
  // hist->GetYaxis()->CenterTitle();
  // hist->GetYaxis()->SetTitleFont(132);
  // hist->GetYaxis()->SetTitleSize(0.06);
  // hist->GetYaxis()->SetTitleOffset(1.12);
  // hist->GetYaxis()->SetLabelFont(132);
  // hist->GetYaxis()->SetLabelSize(0.05);
  // hist->GetYaxis()->SetTitle(varYname.c_str());
  // hist->GetZaxis()->CenterTitle();
  // hist->GetZaxis()->SetTitleFont(132);
  // hist->GetZaxis()->SetTitleSize(0.06);
  // hist->GetZaxis()->SetTitleOffset(1.3);
  // hist->GetZaxis()->SetLabelFont(132);
  // hist->GetZaxis()->SetLabelSize(0.05);
  // hist->GetZaxis()->SetTitle(varZname.c_str());
  // hist->GetZaxis()->SetRangeUser(0.9*hist->GetMinimum(),1.1*hist->GetMaximum());

  // TLatex l;
  // l.SetTextFont(132);
  // l.SetNDC();
  // l.SetTextSize(0.05);
  // l.SetTextFont(132);
  // l.DrawLatex(0.5,0.943,"MMFE8 Analysis");
  // l.SetTextSize(0.04);
  // l.SetTextFont(42);
  // l.DrawLatex(0.15,0.943,"#bf{#it{ATLAS}} Internal");

  // l.SetTextSize(0.06);
  // l.SetTextFont(132);
  // l.DrawLatex(0.80,0.04, "Run 5");

  // TCanvas* canP = new TCanvas("canP","canP",600,500);
  // canP->SetLeftMargin(0.15);
  // canP->SetRightMargin(0.05);
  // canP->SetBottomMargin(0.15);
  // canP->SetTopMargin(0.08);
  // canP->Draw();

  // TH1D* histX = hist->ProjectionX("1DX",200,1100);
  // histX->Draw();
  // histX->GetXaxis()->CenterTitle();
  // histX->GetXaxis()->SetTitleFont(132);
  // histX->GetXaxis()->SetTitleSize(0.06);
  // histX->GetXaxis()->SetTitleOffset(1.06);
  // histX->GetXaxis()->SetLabelFont(132);
  // histX->GetXaxis()->SetLabelSize(0.05);
  // histX->GetXaxis()->SetTitle(varXname.c_str());
  // histX->GetYaxis()->CenterTitle();
  // histX->GetYaxis()->SetTitleFont(132);
  // histX->GetYaxis()->SetTitleSize(0.06);
  // histX->GetYaxis()->SetTitleOffset(1.12);
  // histX->GetYaxis()->SetLabelFont(132);
  // histX->GetYaxis()->SetLabelSize(0.05);
  // histX->GetYaxis()->SetTitle(varZname.c_str());
  
}
Beispiel #22
0
void plot_ZJetBalance( int index, int bin, TH1& responseHistGen, 
		       TH1& responseHistReco, TH1& genJetpt, 
		       TH1& caloJetpt, TH1& recoZpt ) {

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

  TChain* t = new TChain("ZJet");
  if( useLocalFile == true ) t->Add("analysis_zjet.root");
  else t->Add(basename + TString("*.root"));

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

  Float_t JetRecoPt[20][4];
  Float_t JetCorPt[20][4];
  Float_t JetGenPt[20][4];
  Float_t JetRecoEta[20][4];
  Float_t JetGenEta[20][4];
  Float_t JetRecoPhi[20][4];
  Float_t JetGenPhi[20][4];
  Float_t JetRecoType[20][4];
  Float_t Z_Pt;
  Float_t Z_Phi;
  Float_t Z_Eta;
  Float_t Z_PtGen;
  Float_t Z_PhiGen;
  Float_t ePlusPt;
  Float_t eMinusPt;
  Float_t ePlusPtGen;
  Float_t eMinusPtGen;
  Float_t ePlusEta;
  Float_t eMinusEta;
  Float_t ePlusPhi;
  Float_t eMinusPhi;
  Float_t mZeeGen;
  Float_t mZee;

  Float_t ePlus_ecaliso_20;
  Float_t ePlus_sc_e;
  Float_t eMinus_ecaliso_20;
  Float_t eMinus_sc_e;
  Float_t ePlus_ptisoatecal_15;	   
  Float_t eMinus_ptisoatecal_15;
  

  t->SetBranchAddress("JetGenPt",   JetGenPt);
  t->SetBranchAddress("JetGenEta",  JetGenEta);
  t->SetBranchAddress("JetGenPhi",  JetGenPhi);
  t->SetBranchAddress("JetCorPt",   JetCorPt);
  t->SetBranchAddress("JetRecoPt",  JetRecoPt);
  t->SetBranchAddress("JetRecoEta", JetRecoEta);
  t->SetBranchAddress("JetRecoPhi", JetRecoPhi);

  t->SetBranchAddress("Z_Pt",       &Z_Pt);
  t->SetBranchAddress("Z_Phi",      &Z_Phi);
  t->SetBranchAddress("Z_Eta",      &Z_Eta);
  t->SetBranchAddress("Z_PtGen",    &Z_PtGen);
  t->SetBranchAddress("Z_PhiGen",   &Z_PhiGen);
  t->SetBranchAddress("ePlusPt",    &ePlusPt);
  t->SetBranchAddress("eMinusPt",   &eMinusPt);
  t->SetBranchAddress("ePlusPtGen", &ePlusPtGen);
  t->SetBranchAddress("eMinusPtGen",&eMinusPtGen);
  t->SetBranchAddress("ePlusEta",   &ePlusEta);
  t->SetBranchAddress("eMinusEta",  &eMinusEta);
  t->SetBranchAddress("ePlusPhi",   &ePlusPhi);
  t->SetBranchAddress("eMinusPhi",  &eMinusPhi);
  t->SetBranchAddress("mZeeGen",     &mZeeGen);
  t->SetBranchAddress("mZee",        &mZee);
  t->SetBranchAddress("ePlus_ecaliso_20",      &ePlus_ecaliso_20);
  t->SetBranchAddress("ePlus_sc_e",            &ePlus_sc_e);
  t->SetBranchAddress("eMinus_ecaliso_20",     &eMinus_ecaliso_20);
  t->SetBranchAddress("eMinus_sc_e",           &eMinus_sc_e);
  t->SetBranchAddress("ePlus_ptisoatecal_15",  &ePlus_ptisoatecal_15);	   
  t->SetBranchAddress("eMinus_ptisoatecal_15", &eMinus_ptisoatecal_15);

  t->SetBranchStatus("*",    0);
  t->SetBranchStatus("JetGenPt",    1);
  t->SetBranchStatus("JetGenEta",   1);
  t->SetBranchStatus("JetGenPhi",   1);
  t->SetBranchStatus("JetRecoPt",   1);
  t->SetBranchStatus("JetRecoEta",  1);
  t->SetBranchStatus("JetRecoPhi",  1);
  t->SetBranchStatus("JetCorPt",    1);
  t->SetBranchStatus("JetCorEta",   1);
  t->SetBranchStatus("JetCorPhi",   1);
  t->SetBranchStatus("Z_Pt",        1);
  t->SetBranchStatus("Z_Phi",       1);
  t->SetBranchStatus("Z_Eta",       1);
  t->SetBranchStatus("Z_PtGen",     1);
  t->SetBranchStatus("Z_PhiGen",    1);
  t->SetBranchStatus("ePlusPt",     1);
  t->SetBranchStatus("eMinusPt",    1);
  t->SetBranchStatus("ePlusPtGen",  1);
  t->SetBranchStatus("eMinusPtGen", 1);
  t->SetBranchStatus("ePlusEta",    1);
  t->SetBranchStatus("eMinusEta",   1);
  t->SetBranchStatus("ePlusPhi",    1);
  t->SetBranchStatus("eMinusPhi",   1);
  t->SetBranchStatus("mZeeGen",     1);
  t->SetBranchStatus("mZee",        1);
  t->SetBranchStatus("ePlus_ecaliso_20",      1);
  t->SetBranchStatus("ePlus_sc_e",            1);
  t->SetBranchStatus("eMinus_ecaliso_20",     1);
  t->SetBranchStatus("eMinus_sc_e",           1);
  t->SetBranchStatus("ePlus_ptisoatecal_15",  1);	   
  t->SetBranchStatus("eMinus_ptisoatecal_15", 1);





  for (Long64_t entry =0; entry < t->GetEntries(); entry++) {
    t->GetEntry(entry);
    if(entry%20000==0) std::cout<<"************ Event # "<< entry <<std::endl;


    bool isPtCut  = (ePlusPt>20.0) && (eMinusPt>20.0) && 
      (Z_Pt > GenPt[bin]) && (Z_Pt < GenPt[bin+1]);


    bool isEtaCutP = (fabs(ePlusEta)<1.4442) || 
      (fabs(ePlusEta)>1.560 && fabs(ePlusEta)<2.5);
    bool isEtaCutM = (fabs(eMinusEta)<1.4442) || 
      (fabs(eMinusEta)>1.560 && fabs(eMinusEta)<2.5);
    bool isECALiso = (ePlus_ecaliso_20 > 0.0) && 
      (ePlus_ecaliso_20 < 0.2) && (eMinus_ecaliso_20 > 0.0) && 
      (eMinus_ecaliso_20 < 0.2);    
    bool isTrackiso = (ePlus_ptisoatecal_15 < 0.2) && 
      (eMinus_ptisoatecal_15 < 0.2);


    if( !(isPtCut && isEtaCutP && isEtaCutM && isECALiso && 
	  isTrackiso && fabs(mZee-91.2)<2.5) )  continue;

    float leadGenJetPt=JetGenPt[index][0]; 
    float secondGenJetPt=JetGenPt[index][0]; 


    int leadRecoIndex=-1, secondRecoIndex=-1;
    float leadRecoJetPt   = 0.0;
    float secondRecoJetPt = 0.0;

    leadRecoIndex = 0; 
    secondRecoIndex = 1;
    leadRecoJetPt   =  JetRecoPt[index][0];
    secondRecoJetPt =  JetRecoPt[index][1];


//   FindLeadIndex(JetRecoCorrectedPt[index], leadRecoIndex[index], secondRecoIndex[index]);
//   leadRecoJetPt   = JetRecoCorrectedPt[index][leadRecoIndex];
//   secondRecoJetPt = JetRecoCorrectedPt[index][secondRecoIndex];

//   if(leadRecoIndex==-1) continue;


    // ************ test: apply jet pT cut *****************
    if( JetRecoPt[index][0] < MINPTCUT || 
	JetRecoPt[index][1] < MINPTCUT ) continue;


    float leadRecoJetEta = JetRecoEta[index][leadRecoIndex];
    double dPhiReco = dPhi(JetRecoPhi[index][leadRecoIndex], Z_Phi);


    if( fabs(dPhiReco)<2.94 || fabs(leadRecoJetEta)>1.3 || 
	secondRecoJetPt/leadRecoJetPt>0.2 ) continue;


    double ptRatioGen  = leadGenJetPt/Z_PtGen;
    double ptRatioReco = 0.0;

    if(usingCorrectedCaloJetPt) ptRatioReco = JetCorPt[index][0]/Z_Pt;
    else ptRatioReco = JetRecoPt[index][0]/Z_Pt;


    responseHistGen.Fill( ptRatioGen );
    responseHistReco.Fill( ptRatioReco );

    genJetpt.Fill(leadGenJetPt); 
    caloJetpt.Fill(leadRecoJetPt);
    recoZpt.Fill( Z_Pt );

    
  } // end TTree loop


  if(makeplot_ZptBalance==true) {

    TString plotname = 
      Form("ptBalance-allCuts_%d_%d", (int) GenPt[bin], 
	   (int) GenPt[bin+1] );
    
    PlotOnCanvas( responseHistGen, responseHistReco, 
		  plotname);
  }

}
Beispiel #23
0
void Embedding(const char* dataset="collection.xml")
{
    
  gSystem->Load("libTree");
  gSystem->Load("libGeom");
  gSystem->Load("libVMC");
  gSystem->Load("libPhysics");
  
  //load analysis framework
  gSystem->Load("libSTEERBase");
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice"); //AliAnalysisTaskSE
  
  gSystem->AddIncludePath("-I$ALICE_ROOT/include -I$ALICE_ROOT/PHOS");

  // A task can be compiled dynamically with AClic
  gROOT->LoadMacro("AliPHOSEmbedding.cxx+g");
  
  // Connect to alien
  TString token = gSystem->Getenv("GRID_TOKEN") ;
  if (1) // token == "OK" ) 
    TGrid::Connect("alien://");
  else 
    AliInfo("You are not connected to the GRID") ; 
  cout << "Pi0Analysis: processing collection " << dataset << endl;
  
  // Create the chain
  TChain* chain = new TChain("esdTree");

  TGridCollection * collection = dynamic_cast<TGridCollection*>(TAlienCollection::Open(dataset));
  
  TAlienResult* result = collection->GetGridResult("",0 ,0);
  TList* rawFileList = result->GetFileInfoList();
  for (Int_t counter=0 ; counter < rawFileList->GetEntries() ; counter++) {
    TFileInfo * fi =  static_cast<TFileInfo*>(rawFileList->At(counter)) ; 
    const char * rawFile = fi->GetCurrentUrl()->GetUrl() ;  
    printf("Processing %s\n", rawFile) ;
    chain->Add(rawFile);
    printf("Chain: %d entries.\n",chain->GetEntries()); 
  }
  TFileInfo * fi =  static_cast<TFileInfo*>(rawFileList->At(0));
  const char * fn = fi->GetCurrentUrl()->GetUrl() ;

  char runNum[7]; 
  for(Int_t i=0;i<6;i++)runNum[i]=fn[35+i] ;

  runNum[6]=0 ;
  Int_t iRunNum=atoi(runNum) ;
  printf("Run number=%d \n",iRunNum) ;

  //Run AOD simulation
  int nrun = atoi(runNum);
  int nevent = 0;
  int seed = 0;

  char sseed[1024];
  char sevent[1024];
  char sprocess[1024];
  char sfield[1024];
  char senergy[1024];

  sprintf(sevent,"");
  sprintf(sprocess,"");
  sprintf(sfield,"");
  sprintf(senergy,"");

  seed = 0;
  sprintf(sseed,"%d",seed);

  if (seed==0) {
    fprintf(stderr,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
    fprintf(stderr,"!!!!  WARNING! Seeding variable for MC is 0          !!!!\n");
    fprintf(stderr,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
  } else {
    fprintf(stdout,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
    fprintf(stdout,"!!!  MC Seed is %d \n",seed);
    fprintf(stdout,"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
  }
  
// set the seed environment variable
  gSystem->Setenv("CONFIG_SEED",sseed);
  gSystem->Setenv("CONFIG_RUN_TYPE","kPythia6"); // kPythia6 or kPhojet^M
  gSystem->Setenv("CONFIG_FIELD","k5kG");      // kNoField or k5kG^M
  gSystem->Setenv("CONFIG_ENERGY","2760");    // 900 or 10000 (GeV)
  gSystem->Setenv("DC_RUN",runNum);    //run number 
  

  char nSimEvents[55] ;
  sprintf(nSimEvents,"%d",chain->GetEntries());
  gSystem->Setenv("SIM_EVENTS",nSimEvents); 
  gSystem->Exec("mv geometry.root geometry_PHOS.root") ;
  gSystem->Exec("aliroot -b -q simrun.C > simrun.log 2>&1");
  gSystem->Exec("mv geometry_PHOS.root geometry.root") ;

  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("Pi0EmbeddingManager");
  
  // ESD input handler
  AliESDInputHandler* esdH = new AliESDInputHandler();
  esdH->SetReadFriends(kFALSE);
  mgr->SetInputEventHandler(esdH);

  // Output
  AliAODHandler* aodHandler   = new AliAODHandler();
  aodHandler->SetOutputFileName("AliAODout.root");
  mgr->SetOutputEventHandler(aodHandler);

  
  // Debug level
  mgr->SetDebugLevel(0);


  // Add physics selection
  gROOT->LoadMacro("$ALICE_ROOT/OADB/macros/AddTaskPhysicsSelection.C");
  AliPhysicsSelectionTask* physSelTask = AddTaskPhysicsSelection(kFALSE);

  gROOT->LoadMacro("$ALICE_ROOT/OADB/macros/AddTaskCentrality.C");
  AliCentralitySelectionTask *taskCentrality = AddTaskCentrality() ;

  gROOT->LoadMacro("$ALICE_ROOT/ANALYSIS/macros/AddTaskEventplane.C");
  AliEPSelectionTask *taskEP = AddTaskEventplane() ;

  // Add my task
  AliPHOSEmbedding *task1 = new AliPHOSEmbedding("Embedding");

  TChain* chainAOD = new TChain("aodTree");
  chainAOD->AddFile("AliAOD.root") ;
  task1->SetSignalChain(chainAOD) ;
  task1->SelectCollisionCandidates();


  TFile *fOldCalib = TFile::Open("OldCalibration.root");
  if(fOldCalib->IsOpen()){
    printf("\n\n...Adding PHOS calibration used in ESD production \n") ;
    char key[55] ;
    TH2F * hCalib[5] ;
    for(Int_t mod=0;mod<5; mod++){
      sprintf(key,"calibrationMod%d",mod) ;
      hCalib[mod] = (TH2F*)fOldCalib->Get(key) ;
    }
    task1->SetOldCalibration(hCalib) ;
    fOldCalib->Close() ;
  }

  mgr->AddTask(task1);
  
  // Create containers for input/output
  AliAnalysisDataContainer *cinput   = mgr->GetCommonInputContainer(); 
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("output0",
                      TTree::Class(), AliAnalysisManager::kOutputContainer);


  // Connect input/output
  mgr->ConnectInput(task1 , 0, cinput);
  mgr->ConnectOutput(task1, 0,coutput1);

  AliLog::SetClassDebugLevel("AliGeomManager", 10) ;

  AliCDBManager::Instance()->SetRun(iRunNum) ;
//  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/OCDB") ;
//  AliCDBManager::Instance()->SetDefaultStorage("raw://") ;
  AliCDBManager::Instance()->SetDefaultStorage("alien://folder=/alice/data/2010/OCDB") ;
  AliCDBManager::Instance()->SetSpecificStorage("PHOS/*/*",
                                                "local://OCDB");
printf("RunNunm===%d \n",iRunNum) ;
  

  if (mgr->InitAnalysis()) {
    mgr->PrintStatus();
    mgr->StartAnalysis("local", chain);
  }
  
  if(iRunNum<=137848){ //period 1
    gSystem->Exec("mv BadMap_LHC10h_period1.root BadMap_LHC10h.root") ;
  }
  else{
    gSystem->Exec("mv BadMap_LHC10h_period234.root BadMap_LHC10h.root") ;
  }
  gSystem->Exec("aliroot -b -q AnalyzeDiff.C> analyze3.log 2>&1");

}
Beispiel #24
0
int main(int argc, char* argv[])
{
  if( argc<2 ) 
  {
    std::cout << argv[0] << " config_file " << std::endl;
    return 0;
  }

  // open steering file names
  config  steer(argv[1]);
 

  mode = steer.getInt("mode");

  rootfile_in = steer.getString("rootfile_in"); 
  rootfile_out = steer.getString("rootfile_out"); 

  signalFraction = steer.getDouble("signalFraction"); 
  
  method = steer.getInt("method");
  
  gaus_reso = steer.getDouble("gaus_reso");

  RegVersion = steer.getString("RegVersion");

  debug = steer.getInt("debug");

  doEvenOdd = steer.getInt("doEvenOdd");

 
  // check 
  if (mode==73||mode==75||mode==77)
  {
    parfile_ref = steer.getString("parfile_ref");
    if (parfile_ref=="") 
    {
      std::cout << "Missing parameters reference file. Please run " << argv[0] << " to print usage information. " << std::endl;  
      return 1;
    } 
  }
  
  if (mode==782) 
  { 
    calibtable_filename = steer.getString("calibtable_filename");
    // fitscale is a stupid control to tell FillAllEvent 
    // if you want it to store all hits information, false is to store.
    fitscale = false; 
  }
 
  std::cout << argv[0] << std::endl;
  std::cout << "  mode = " << mode << std::endl;
  std::cout << "  method = " << method << std::endl;
  std::cout << "  rootfile_in = " << rootfile_in << std::endl;
  std::cout << "  rootfile_out = " << rootfile_out << std::endl;
  std::cout << "  signalFraction = " << signalFraction << std::endl;
  std::cout << "  GaussianResolution = " << gaus_reso << std::endl;
  std::cout << "  RegVersion = " << RegVersion << std::endl;
  std::cout << "  doEvenOdd = " << doEvenOdd << std::endl;
  if (mode==73||mode==75||mode==77) std::cout << "  Parameter Reference File = " << parfile_ref << std::endl;
  if (mode==782) std::cout << "  calibtable_filename = " << calibtable_filename << std::endl;
  
  std::cout << " Start program. " << std::endl;
  
  // reading data
  TChain* tree = new TChain("selected", "selected");
  tree->Add(rootfile_in.c_str());
  // Set the branches for the TChain/TTree
  SetTreeBranch(tree);

  // reading extra tree
  TChain* extree = new TChain("extraCalibTree", "extraCalibTree");
  extree->Add(rootfile_in.c_str());
  // Set the branches for the extra TTree
  SetExtraTreeBranch(extree);
  
  // output root file
  TFile* fout = TFile::Open(rootfile_out.c_str(), "recreate");
  


  // all events
  nEvents = tree->GetEntries();
  nSignals = nEvents;

  // Fill all events into vectors
  FillAllEvents(tree, extree, 2, RegVersion, fitscale, doEvenOdd);
  if (debug>0) std::cout << " Step 1: fill all events: " << nEvents << std::endl;
  
  // delete the chain no more need it
  tree->Delete();
  extree->Delete();
  
  // define the fitting function
  BWGSLikelihoodFCN fcn;

  fcn.setdebug(debug);

  if (debug>0) std::cout << " Step 1: Initialize PDF overall " << std::endl;
  // initialize PDF
  fcn.initBWGSParameters(_FitWindowHigh, // windowHigh
                         _FitWindowLow, // windowLow
                         _Zmass, //voigtMass
                         gaus_reso, //voightResolution
                         2.4952, //voigtWidth
                         nSignals,
                         nEvents);
  
  // define the energy scales as parameters
  MnUserParameters scales;
  
  // reference scales 
  std::vector<double> scalesref;

  if (mode==73) 
  {
    // read reference scales
    std::ifstream reffile(parfile_ref.c_str());
    if (reffile.is_open())
    {
      std::string line;
      double s, e;
      while (getline(reffile,line))
      {
        std::stringstream sline(line);
        sline >> s >> e;
        scalesref.push_back(s);
      }
      reffile.close();
    } 
Beispiel #25
0
void MuonPlots(TString HLTname = "IsoMu20")
{
	TTimeStamp ts_start;
	cout << "[Start Time(local time): " << ts_start.AsString("l") << "]" << endl;

	TStopwatch totaltime;
	totaltime.Start();

	TString HLT;
	Double_t LeadPtCut = 9999;
	Double_t SubPtCut = 9999;
	Double_t LeadEtaCut = 9999;
	Double_t SubEtaCut = 9999;
	AssignAccThreshold(HLTname, &HLT, &LeadPtCut, &SubPtCut, &LeadEtaCut, &SubEtaCut);
	cout << "===========================================================" << endl;
	cout << "Trigger: " << HLT << endl;
	cout << "leading lepton pT Cut: " << LeadPtCut << endl;
	cout << "Sub-leading lepton pT Cut: " << SubPtCut << endl;
	cout << "leading lepton Eta Cut: " << LeadEtaCut << endl;
	cout << "sub-leading lepton Eta Cut: " << SubEtaCut << endl;
	cout << "===========================================================" << endl;

	Double_t Factor = 569.0171*2008.4*3/4.5275/10;

	//TFile *f = new TFile("ROOTFile_Histogram_InvMass_"+HLTname+"_Data.root", "RECREATE");
	//TFile *f = new TFile("ROOTFile_Histogram_InvMass_60to120_Data.root", "RECREATE");
	TFile *fcut = new TFile("MuonCut.root", "RECREATE");
	//TFile *fisPF = new TFile("MuonCutIsPF.root", "RECREATE");
	//TFile *fisChi2dof = new TFile("MuonCutChi2dof.root", "RECREATE");
	//TFile *f = new TFile("MuonCutMuonHits.root", "RECREATE");
	//TFile *f = new TFile("MuonCutNMatches.root", "RECREATE");
	//TFile *f = new TFile("MuonCutDxyVTX.root", "RECREATE");
	//TFile *f = new TFile("MuonCutDzVTX.root", "RECREATE");
	//TFile *f = new TFile("MuonCutPixelHits.root", "RECREATE");
	//TFile *f = new TFile("MuonCutTrackerLayers.root", "RECREATE");

	TString BaseLocation = "/data4/Users/kplee/DYntuple";
	//Each ntuple directory & corresponding Tags
	vector< TString > ntupleDirectory; vector< TString > Tag;
	//MC
	// ntupleDirectory.push_back( "Spring15DR/25ns/DYLL_M10to50_v2_AddTauInfo" ); Tag.push_back( "DYMuMu_M20to50" );
	ntupleDirectory.push_back( "Spring15DR/25ns/DYLL_M50_v1" ); Tag.push_back( "DYMuMu" );
	// ntupleDirectory.push_back( "Spring15DR/25ns/DYLL_M10to50_v2_AddTauInfo" ); Tag.push_back( "DYTauTau_M20to50" );
	// ntupleDirectory.push_back( "Spring15DR/25ns/DYLL_M50_v1" ); Tag.push_back( "DYTauTau" );
	// ntupleDirectory.push_back( "Spring15DR/25ns/ttbar_v1" );  Tag.push_back( "ttbar" );
	// ntupleDirectory.push_back( "Spring15DR/25ns/WJets_v1" );  Tag.push_back( "WJets" );
	// ntupleDirectory.push_back( "Spring15DR/25ns/WW_v1" );  Tag.push_back( "WW" );
	// ntupleDirectory.push_back( "Spring15DR/25ns/WZ_v1" );  Tag.push_back( "WZ" );
	// ntupleDirectory.push_back( "Spring15DR/25ns/ZZ_v1" );  Tag.push_back( "ZZ" );

	//Data
	ntupleDirectory.push_back( "Run2015C/GoldenJSON/SingleMuon_v3_Run246908to256869" ); Tag.push_back( "Data" ); // -- Run2015C -- //


	//Loop for all samples
	const Int_t Ntup = ntupleDirectory.size();
	for(Int_t i_tup = 0; i_tup<Ntup; i_tup++)
	{
		TStopwatch looptime;
		looptime.Start();

		cout << "\t<" << Tag[i_tup] << ">" << endl;

		ControlPlots *Plots = new ControlPlots( Tag[i_tup] );
		//Histograms for cuts
		TH1D *h_isGLB_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_isGLB_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_isGLB_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_isPF_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_isPF_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_isPF_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_chi2dof_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_chi2dof_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_chi2dof_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_muonHits_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_muonHits_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_muonHits_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_nMatches_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_nMatches_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_nMatches_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_dxyVTX_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_dxyVTX_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_dxyVTX_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_dzVTX_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_dzVTX_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_dzVTX_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_pixelHits_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_pixelHits_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_pixelHits_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);
		TH1D *h_trackerLayers_Pt = new TH1D("h_isGLB_Pt"+Tag[i_tup], "", 250, 0, 500);
		TH1D *h_trackerLayers_eta = new TH1D("h_isGLB_eta"+Tag[i_tup], "", 60, -3, 3);
		TH1D *h_trackerLayers_phi = new TH1D("h_isGLB_phi"+Tag[i_tup], "", 80, -4, 4);

		TChain *chain = new TChain("recoTree/DYTree");
		chain->Add(BaseLocation+"/"+ntupleDirectory[i_tup]+"/ntuple_*.root");
		if( Tag[i_tup] == "Data" )
		{
			// -- Run2015D -- // 
			chain->Add("/data4/Users/kplee/DYntuple/Run2015D/GoldenJSON/v20151016_v3JSON_Run2015D_SingleMuon_Run246908to256869/*.root");
			chain->Add("/data4/Users/kplee/DYntuple/Run2015D/GoldenJSON/v20151010_v2JSON_SingleMuon_Run256870to257599/*.root");
			chain->Add("/data4/Users/kplee/DYntuple/Run2015D/GoldenJSON/v20151009_SingleMuon_Run257600toRun258159/*.root");
		}
		
		NtupleHandle *ntuple = new NtupleHandle( chain );

		Bool_t isNLO = 0;
		if( Tag[i_tup] == "DYMuMu" || Tag[i_tup] == "DYTauTau" || Tag[i_tup] == "WJets" || Tag[i_tup] == "DYMuMu_M20to50" || Tag[i_tup] == "DYTauTau_M20to50" )
		{
			isNLO = 1;
			cout << "\t" << Tag[i_tup] << ": generated with NLO mode - Weights are applied" << endl;
		}

		Int_t count_Zpeak = 0;
		Double_t SumWeight = 0;
		Double_t SumWeight_DYMuMu_M20to50 = 0;
		Double_t SumWeight_DYTauTau_M20to50 = 0;

		Int_t NEvents = chain->GetEntries();
		cout << "\t[Total Events: " << NEvents << "]" << endl;
		for(Int_t i=0; i<NEvents; i++)
		{
			loadBar(i+1, NEvents, 100, 100);
			
			ntuple->GetEvent(i);

			//Bring weights for NLO MC events
			Double_t GenWeight;
			if( isNLO == 1 )
				GenWeight = ntuple->GENEvt_weight;
			else
				GenWeight = 1;
			// cout << "Weight of " << i << "th Event: " << GenWeight << endl;
			SumWeight += GenWeight;

			Int_t GenMassFlag = -1;
			//Take the events within 20<M<50 in gen-level
/*
 *            if( Tag[i_tup] == "DYMuMu_M20to50" )
 *            {
 *                GenMassFlag = 0;
 *                vector<GenLepton> GenLeptonCollection;
 *                Int_t NGenLeptons = ntuple->gnpair;
 *                for(Int_t i_gen=0; i_gen<NGenLeptons; i_gen++)
 *                {
 *                    GenLepton genlep;
 *                    genlep.FillFromNtuple(ntuple, i_gen);
 *                    if( genlep.isMuon() && genlep.fromHardProcessFinalState )
 *                        GenLeptonCollection.push_back( genlep );
 *                }
 *
 *                if( GenLeptonCollection.size() == 2 )
 *                {
 *                    GenLepton genlep1 = GenLeptonCollection[0];
 *                    GenLepton genlep2 = GenLeptonCollection[1];
 *
 *                    TLorentzVector gen_v1 = genlep1.Momentum;
 *                    TLorentzVector gen_v2 = genlep2.Momentum;
 *                    TLorentzVector gen_vtot = gen_v1 + gen_v2;
 *                    Double_t gen_M = gen_vtot.M();
 *
 *                    if( gen_M > 20 && gen_M < 50 ) //Take the events within 20<M<50 in gen-level
 *                    {
 *                        GenMassFlag = 1;
 *                        SumWeight_DYMuMu_M20to50 += GenWeight;
 *                    }		
 *                }
 *            }
 *            else if( Tag[i_tup] == "DYTauTau_M20to50" )
 *            {
 *                GenMassFlag = 0;
 *                vector<GenLepton> GenLeptonCollection;
 *                Int_t NGenLeptons = ntuple->gnpair;
 *                for(Int_t i_gen=0; i_gen<NGenLeptons; i_gen++)
 *                {
 *                    GenLepton genlep;
 *                    genlep.FillFromNtuple(ntuple, i_gen);
 *                    if( abs(genlep.ID) == 15 && genlep.fromHardProcessDecayed )
 *                        GenLeptonCollection.push_back( genlep );
 *                }
 *
 *                if( GenLeptonCollection.size() == 2 )
 *                {
 *                    GenLepton genlep1 = GenLeptonCollection[0];
 *                    GenLepton genlep2 = GenLeptonCollection[1];
 *
 *                    TLorentzVector gen_v1 = genlep1.Momentum;
 *                    TLorentzVector gen_v2 = genlep2.Momentum;
 *                    TLorentzVector gen_vtot = gen_v1 + gen_v2;
 *                    Double_t gen_M = gen_vtot.M();
 *
 *                    if( gen_M > 20 && gen_M < 50 ) //Take the events within 20<M<50 in gen-level
 *                    {
 *                        GenMassFlag = 1;
 *                        SumWeight_DYTauTau_M20to50 += GenWeight;
 *                    }	
 *                }
 *            }
 *            else
 */
				GenMassFlag = 1; // -- other cases: pass


			
			if( ntuple->isTriggered( HLT ) && GenMassFlag)
			{
				//Collect Reconstruction level information
				vector< Muon > MuonCollection;
				Int_t NLeptons = ntuple->nMuon;
				for(Int_t i_reco=0; i_reco<NLeptons; i_reco++)
				{
					Muon mu;
					mu.FillFromNtuple(ntuple, i_reco);
						MuonCollection.push_back( mu );
				}

				//Select muons directly from Z/gamma by matching with gen-level final state muons from hard process
				if( Tag[i_tup] == "DYMuMu" )
					GenMatching(HLTname, "fromHardProcess", ntuple, &MuonCollection);
/*
 *                //Select muons directly from tau by matching with gen-level final state muons from prompt tau
 *                else if( Tag[i_tup] == "DYTauTau" )
 *                    GenMatching(HLTname, "fromTau", ntuple, &MuonCollection);
 *
 */

				//Collect qualified muons among muons
				vector< Muon > QMuonCollection;
				for(Int_t j=0; j<(int)MuonCollection.size(); j++)
				{
					if( MuonCollection[j]->isGLB == 1)
					{
						h_isGLB_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_isGLB_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_isGLB_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( MuonCollection[j]->isPF == 1)
					{
						h_isPF_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_isPF_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_isPF_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( MuonCollection[j]->chi2dof < 10)
					{
						h_ischi2dof_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_ischi2dof_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_ischi2dof_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( MuonCollection[j]->muonHits > 0)
					{
						h_is_muonHits_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_is_muonHits_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_is_muonHits_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( MuonCollection[j]->nMatches > 1)
					{
						h_nMatches_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_nMatches_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_nMatches_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( fabs(MuonCollection[j]->dxyVTX) < 0.2)
					{
						h_dxyVTX_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_dxyVTX_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_dxyVTX_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( fabs(MuonCollection[j]->dzVTX) < 0.5 )
					{
						h_dzVTX_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_dzVTX_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_dzVTX_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( MuonCollection[j]->pixelHits > 0 )
					{
						h_pixelHits_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_pixelHits_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_pixelHits_phi->Fill( MuonCollection[j].phi, GenWeight);
					}
					if( MuonCollection[j]->trackerLayers > 5)
					{
						h_trackerLayers_Pt->Fill( MuonCollection[j].Pt, GenWeight );
						h_trackerLayers_eta->Fill( MuonCollection[j].eta, GenWeight);
						h_trackerLayers_phi->Fill( MuonCollection[j].phi, GenWeight);
					}

					//if( MuonCollection[j].isTightMuon() && MuonCollection[j].trkiso < 0.10)
						//QMuonCollection.push_back( MuonCollection[j] );
				}

/*
 *                //Give Acceptance cuts
 *                if( QMuonCollection.size() >= 2)
 *                {
 *                    Muon leadMu, subMu;
 *                    CompareMuon(&QMuonCollection[0], &QMuonCollection[1], &leadMu, &subMu);
 *                    if( !(leadMu.Pt > LeadPtCut && subMu.Pt > SubPtCut && abs(leadMu.eta) < LeadEtaCut && abs(subMu.eta) < SubEtaCut) )
 *                        QMuonCollection.clear();
 *                }
 *
 *                if( QMuonCollection.size() == 2)
 *                {
 *                    Muon recolep1 = QMuonCollection[0];
 *                    Muon recolep2 = QMuonCollection[1];
 *                    TLorentzVector reco_v1 = recolep1.Momentum;
 *                    TLorentzVector reco_v2 = recolep2.Momentum;
 *                    Double_t reco_M = (reco_v1 + reco_v2).M();
 *
 *                    if( reco_M > 60 && reco_M < 120 && isPassDimuonVertexCut(ntuple, recolep1.cktpT, recolep2.cktpT) )
 *                    {
 *                        Plots->FillHistograms(ntuple, HLT, recolep1, recolep2, GenWeight);
 *
 *                        //Count # events in the Z-peak region for each sample
 *                        //if( reco_M > 60 && reco_M < 120 )
 *                            count_Zpeak++;
 *                    }
 *                }
 *
 */
			} //End of if( isTriggered )

		} //End of event iteration

		/*
		 *cout << "\tcount_Zpeak(" << Tag[i_tup] << "): " << count_Zpeak << endl;
		 */

		// if( Tag[i_tup] == "DYTauTau_M20to50" )
		// {
		// 	for(Int_t i_hist=0; i_hist < (Int_t)Plots->Histo.size(); i_hist++)
		// 		Plots->Histo[i_hist]->Scale( 2.49997e+10 / 4.48119e+11 );
		// }




		//Plots->WriteHistograms( fisGLB );
		fisGLB->cd();
		h_isGLB_Pt->Write();
		h_isGLB_eta->Write();
		h_isGLB_phi->Write();
		h_isPF_Pt->Write();
		h_isPF_eta->Write();
		h_isPF_phi->Write();
		h_chi2dof_Pt->Write();
		h_chi2dof_eta->Write();
		h_chi2dof_phi->Write();
		h_muonHits_Pt->Write();
		h_muonHits_eta->Write();
		h_muonHits_phi->Write();
		h_nMatches_Pt->Write();
		h_nMatches_eta->Write();
		h_nMatches_phi->Write();
		h_dxyVTX_Pt->Write();
		h_dxyVTX_eta->Write();
		h_dxyVTX_phi->Write();
		h_dzVTX_Pt->Write();
		h_dzVTX_eta->Write();
		h_dzVTX_phi->Write();
		h_pixelHits_Pt->Write();
		h_pixelHits_eta->Write();
		h_pixelHits_phi->Write();
		h_trackerLayers_Pt->Write();
		h_trackerLayers_eta->Write();
		h_trackerLayers_phi->Write();
		



		if(isNLO == 1)
			cout << "\tTotal sum of weights: " << SumWeight << endl;

		if( Tag[i_tup] == "DYMuMu_M20to50" )
			cout << "\tSum of weights in 20<M<50 for DYMuMu events: " << SumWeight_DYMuMu_M20to50 << endl;

		if( Tag[i_tup] == "DYTauTau_M20to50" )
			cout << "\tSum of weights in 20<M<50 for DYTauTau events: " << SumWeight_DYTauTau_M20to50 << endl;

		Double_t LoopRunTime = looptime.CpuTime();
		cout << "\tLoop RunTime(" << Tag[i_tup] << "): " << LoopRunTime << " seconds\n" << endl;
	} //end of i_tup iteration

	Double_t TotalRunTime = totaltime.CpuTime();
	cout << "Total RunTime: " << TotalRunTime << " seconds" << endl;

	TTimeStamp ts_end;
	cout << "[End Time(local time): " << ts_end.AsString("l") << "]" << endl;
}
void run_TSelector_SusyNtuple_Truth_n0150_WH(TString SysUncertType, TString InputPath) {

//  TString options = TString(""); //TString(tag.c_str()) ;
// //     TString outputfile = "test.root";
//     string richtigerString = InputPath;
// //     int Position = richtigerString.find("mc12_8TeV.");
// //     outputfile = "histos_ZTauTau_" +  richtigerString.substr(Position+10,6)  + "_proof.root";
//     
//     int Position = -1;
//     Position = richtigerString.find("45_bg");
//     if (Position>0){
//       outputfile = "histos_test_" +  richtigerString.substr(Position+6,2)  + ".root";
//     }
//     else{
//       Position = richtigerString.find("45_signal");
//       if (Position>0){
//       outputfile = "histos_test_" +  richtigerString.substr(Position+3,2)  + ".root";
//       }
//     }
//     if(outputfile == ""){
//       cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
//       cout << "EMPTY OUPTPUTFILE STRING" << endl;
//       cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
//       abort();
//     }
//     cout << "outputfile= " << outputfile << endl;
    
      cout<<"Have you set up RootCore via  \"source RootCore/scripts/setup.sh\" ?"<<endl;  

      gSystem->Setenv("ROOTCOREDIR", "/data/etp3/jwittkow/analysis_SUSYTools_03_04/RootCore");
      gSystem->SetIncludePath("-I$ROOTCOREDIR/include/");

      gROOT->ProcessLine(".x $ROOTCOREDIR/scripts/load_packages.C+"); 

      TString selectorName = "TSelector_SusyNtuple_Truth"; // !!! enter the name of your Selector (without _C.so)

      TChain *ch;
      
      ch = new TChain("susyNt");

      TString processLine = ".L " + selectorName + ".cpp++g";
      TString execLine;

      gROOT->ProcessLine(processLine); // need to add this, or PoD at LRZ will not be able to load the .so
      gROOT->ProcessLine(".x $ROOTCOREDIR/scripts/load_packages.C+");
      ch->Add(InputPath);
//       ch->Add("/data/etp6/jwittkow/SusyNtuples_n0145_bg_new/WZ_SherpaVVtotautauqq/user.sfarrell.mc12_8TeV.157816.Sherpa_CT10_VVtotautauqq.SusyNt.e1515_s1499_s1504_r3658_r3549_p1512_n0145.130708082025/*");



//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Egamma/user.sfarrell.group.phys-susy.data12_8TeV.periodA.physics_Egamma.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708161315/user.sfarrell.116519._00003.susyNt.root");
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Egamma/user.sfarrell.group.phys-susy.data12_8TeV.periodA.physics_Egamma.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708161315/*");
// ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Egamma/user.sfarrell.group.phys-susy.data12_8TeV.periodA.physics_Egamma.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708161341/*");  
// ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Egamma/user.sfarrell.group.phys-susy.data12_8TeV.periodA.physics_Egamma.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708161402/*");
// ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0145_data/Egamma/user.sfarrell.group.phys-susy.data12_8TeV.periodA.physics_Egamma.PhysCont.SusyNt.repro14_v01_p1542_n0145.130708161438/*");
      
//       ch->Add("/nobackup/etp2/Josephine.Wittkowski/SusyNtuples_n0150/WH/user.gerbaudo.mc12_8TeV.177501.Herwigpp_sM_wA_noslep_notauhad_WH_2Lep_1.SusyNt.e2149_s1581_s1586_r3658_r3549_p1512_n0150.140109072637/*");
//       ch->Add("/data/etp6/jwittkow/user.gerbaudo.mc12_8TeV.126893.Sherpa_CT10_lllnu_WZ.SusyNt.e1434_s1499_s1504_r3658_r3549_p1512_n0145dev4.131220015824/*");
      
//       ch->Add("/data/etp6/jwittkow/SusyNtuples_n0145_bg_new/ttbar105200/*");

//             ch->Add("/data/etp6/jwittkow/SusyNtuples_n0145_signal_samples/user.gerbaudo.mc12_8TeV.177503.Herwigpp_sM_wA_noslep_notauhad_WH_2Lep_3.SusyNt.e2149_s1581_s1586_r3658_r3549_p1512_n0145.130806161345/user.gerbaudo.023459._00001.susyNt.root");
      
      

	    


      Long64_t nEntries = ch->GetEntries();
      ch->ls();

      cout << "all entries: " << nEntries << endl;


      TSelector_SusyNtuple_Truth* SusyNtupleObject = new TSelector_SusyNtuple_Truth();
//       SusyNtupleObject->buildSumwMap(ch);
//       TString options="NtSys_NOM";
      ch->Process(SusyNtupleObject,SysUncertType);
      delete SusyNtupleObject;
      
      if (ch) {delete ch; ch=0;}

  abort();
  }
Beispiel #27
0
#define MMUON 0.10566

// -- Open file 
TChain chain("T1");
chain.Add("msel5.root");

Int_t nentries(0), nb(0);
Int_t iEvent(0), it(0);

// -- Set up for reading
TAna01Event *pEvent = new TAna01Event(0);
TAnaTrack *m1Track, *m2Track;
TAnaCand  *pCand;
TAnaVertex *pVtx;

chain.SetBranchAddress("TAna01Event", &pEvent);
nentries = chain.GetEntries();

cout << "Found " << nentries << " entries in the chain" << endl;

for (iEvent = 0; iEvent < nentries; iEvent++) {
  cout << "event " << iEvent << endl;
  pEvent->Clear();
  nb += chain.GetEvent(iEvent); 
  
  pEvent->dumpGenBlock(); 

}

}
Beispiel #28
0
void distEfficiency()
{
	//gStyle->SetCanvasPreferGL(kTRUE);
	int bin_e = 20;
	int max_e = 30;
	TCanvas * c1 = new TCanvas("c1", "Data-MC",0,0,500,500);
	TH1F * distmc = new TH1F("distmc", "E(Ntracks)", bin_e,0,max_e);
	TH1F * distreco = new TH1F("distreco", "tracks", bin_e,0,max_e);
	TH1F * kaons = new TH1F("kaons","N",5,0,5);
	distreco->Sumw2();
	distmc->Sumw2();
	TChain* MC = new TChain("Stats");
	MC->Add("MCTest.root");
	TChain* RECO = new TChain("TaggedVertices");
	RECO->Add("RecoTest.root");
	//T1->Add("~/Processors/Analysis/TestProcessor/build/test/Data_10_GeV/Test.root");
	/*int _numberOfVertexes = 0;
	int _tag = 0;
	const int MAXV = 8;
	float _coordinates[MAXV][3];
	int _PDG[MAXV];
	int _generation[MAXV];
	int _distance[MAXV];
	
	MC->SetBranchAddress("numberOfVertexes", &_numberOfVertexes);
	MC->SetBranchAddress("tag", &_tag);
	MC->SetBranchAddress("coordinates", _coordinates);
	MC->SetBranchAddress("distance", _distance);
	MC->SetBranchAddress("PDG", _PDG);
	MC->SetBranchAddress("generation", _generation);*/
	//MC->SetBranchAddress("coordinates", _coordinates);
	float _bdistance = 0.0;
	float _bbardistance = 0.0;

	MC->SetBranchAddress("bdistance", &_bdistance);
	MC->SetBranchAddress("bbardistance", &_bbardistance);

	int _numberOfTagged = 0;
	int _PDGreco[MAXV];
	int _nparticles[MAXV];
	int _type[MAXV][MAXV];
	int _charge[MAXV][MAXV];

	RECO->SetBranchAddress("numberOfTagged", &_numberOfTagged);
	RECO->SetBranchAddress("numberOfParticles", &_nparticles);
	RECO->SetBranchAddress("chargeOfParticles", &_nparticles);
	RECO->SetBranchAddress("pidTypeOfParticles", &_type);
	RECO->SetBranchAddress("chargeOfParticles", &_charge);
	RECO->SetBranchAddress("PDG", _PDGreco);
	int mTotalNumberOfEvents1 = MC->GetEntries();
	int totalnumber = 0;
	int totalb = 0;
	int kaonnumber = 0;
	int kaonnumbertotal = 0;
	int pionnumber = 0;
	for (int k = 0; k < mTotalNumberOfEvents1; k++)
	{
	        RECO->GetEntry(k);
	        MC->GetEntry(k);
		int bvtxnumber = 0;
		int bbarvtxnumber = 0;
		for (int i = 0; i < _numberOfTagged; i++) 
		{
			int knumber = 0;
			int kcharge = 0;
			int kbarnumber = 0;
			int kbarcharge = 0;
			if (_PDGreco[i] > 0) 
			{
				bvtxnumber++;
			}
			if (_PDGreco[i] > 0) 
			{
				bbarvtxnumber++;
			}
			for (int j = 0; j < _nparticles[i]; j++) 
			{
				//if (abs(_type[i][j]) == 321) 
				if (_PDGreco[i] < 0) 
				{
					if (abs(_type[i][j]) == 321)
					{
						kbarnumber++;
						kbarcharge += _charge[i][j];
					}
				}
				if (_PDGreco[i] > 0) 
				{
					if (abs(_type[i][j]) == 321)
					{
						knumber++;
						kcharge += _charge[i][j];
					}
				}
			}
			if (knumber > 0 && kcharge < 0) 
			{
				kaonnumber++;
			}
			if (kbarnumber > 0 && kbarcharge > 0) 
			{
				kaonnumber++;
			}
			if (knumber > 0 && kcharge != 0) 
			{
				cout << "K: " << knumber << " q: " << kcharge << endl; 
				kaonnumbertotal++;
			}
			if (kbarnumber > 0 && kbarcharge != 0) 
			{
				cout << "Kbar: " << kbarnumber << " q: " << kbarcharge << endl; 
				kaonnumbertotal++;
			}
			//kaonnumber += knumber;
			kaons->Fill(knumber);
		}
	}
	cout << "Total: " << kaonnumbertotal <<  " purity: " << (float)kaonnumber/kaonnumbertotal << endl;
	//cout << "Nparticles: " << totalb << " Nkaons: " << kaonnumber << " (" << (float)kaonnumber/totalb*100 << "%)\n" ;
	//cout << "\tNpions: " << pionnumber << " (" << (float)pionnumber/totalb*100 << "%)\n" ;
	//cout << "\tNpions: " << totalnumber << " (" << (float)totalnumber/totalb*100 << "%)\n" ;
	//kaons->Scale(1./totalb);
	//kaons->Draw("htext");
}
Beispiel #29
0
//------------------------------------------------------------------------
void makeSmearedTable(const int nbins = 100, const string label = "HFtowersPlusTrunc", const char * tag = "CentralityTable_HFtowersPlusTrunc_SmearedGlauber_sigma74_eff0_v5", int eff = 0) {

 TH1::SetDefaultSumw2();
 const char * inputMCforest = Form("/tmp/azsigmon/HiForest_pPb_Hijing_NEWFIX_v2.root");

 ProduceResponsePlots2(inputMCforest);

 bool plot = false;
 if(plot) {
   TCanvas *c1 = new TCanvas();
   Npart_vs_PtGenPlusEta4[0]->Draw("colz");
   TCanvas *c2 = new TCanvas();
   PtGenPlusEta4_vs_HFplusEta4[0]->Draw("colz");
   TCanvas *c3 = new TCanvas();
   Npart_vs_PtGenMinusEta4[0]->Draw("colz");
   TCanvas *c4 = new TCanvas();
   PtGenMinusEta4_vs_HFminusEta4[0]->Draw("colz");
   TCanvas *c5 = new TCanvas();
   Npart_vs_Ngentrk[0]->Draw("colz");
   TCanvas *c6 = new TCanvas();
   Ngentrk_vs_Ntracks[0]->Draw("colz");
 }

 bool binHFplusTrunc = label.compare("HFtowersPlusTrunc") == 0;
 bool binHFminusTrunc = label.compare("HFtowersMinusTrunc") == 0;
 bool binTracks = label.compare("Tracks") == 0;

 if (binHFplusTrunc) {
   getProjections(Npart_vs_PtGenPlusEta4[eff],Proj1,"Proj1",1,30);
   getProjections(PtGenPlusEta4_vs_HFplusEta4[eff],Proj2,"Proj2",1,140);
 }
 else if (binHFminusTrunc) {
   getProjections(Npart_vs_PtGenMinusEta4[0],Proj1,"Proj1",1,30);
   getProjections(PtGenMinusEta4_vs_HFminusEta4[0],Proj2,"Proj2",1,140);
 }
 else if (binTracks) {
   getProjections(Npart_vs_Ngentrk[0],Proj1,"Proj1",1,30);
   getProjections(Ngentrk_vs_Ntracks[0],Proj2,"Proj2",1,200);
 }

 //input Glauber ntuple
 const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/Standard/Phob_Glau_pPb_sNN70mb_v15_1M_dmin04.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/D/D04914/Phob_Glau_pPb_sNN70mb_v15_1M_D04914.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/D/D06006/Phob_Glau_pPb_sNN70mb_v15_1M_D06006.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/R/R649/Phob_Glau_pPb_sNN70mb_v15_1M_R649.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/R/R675/Phob_Glau_pPb_sNN70mb_v15_1M_R675.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/dmin/dmin00/Phob_Glau_pPb_sNN70mb_v15_1M_dmin00.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/dmin/dmin08/Phob_Glau_pPb_sNN70mb_v15_1M_dmin08.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/sigma/sigma66/Phob_Glau_pPb_sNN66mb_v15_1M_dmin04.root");
 //const char * infilename = Form("/afs/cern.ch/work/t/tuos/public/pPb/Glauber/1M/sigma/sigma74/Phob_Glau_pPb_sNN74mb_v15_1M_dmin04.root");
 TChain * t = new TChain("nt_p_Pb");
 t->Add(infilename);

 //output
 //const char* outfilename = "out/tables_Glauber2012B_AmptResponse_d20130116_v4.root";
 //const char* outfilename = "out/tables_Glauber2012B_EposLHCResponse_d20130118_v4.root";
 const char* outfilename = "out/tables_Glauber2012B_HijingResponse_d20130130_v5.root";
 TFile * outf = new TFile(outfilename,"update");
 outf->cd();
 TDirectory* dir = outf->mkdir(tag);
 dir->cd();
 TNtuple* nt = new TNtuple("nt","","HFbyPt:genPt:Bin:b:Npart:Ncoll:Nhard");
 CentralityBins * outputTable = new CentralityBins(Form("run%d",1), tag, nbins);
 outputTable->table_.reserve(nbins);

 ofstream txtfile("out/output.txt");
 txtfile << "Input Glauber tree: " << infilename << endl << "Input MC HiForest HIJING" << endl;

 //Setting up variables and branches
 double binboundaries[nbins+1];
 vector<float> values;

 float b, npart, ncoll, nhard, parameter;

 t->SetBranchAddress("B",&b);
 t->SetBranchAddress("Npart",&npart);
 t->SetBranchAddress("Ncoll",&ncoll);
 nhard = 0;

 //Event loop 1
 unsigned int Nevents = t->GetEntries();
 txtfile << "Number of events = " << Nevents << endl << endl;
 for(unsigned int iev = 0; iev < Nevents; iev++) {
   if(iev%20000 == 0) cout<<"Processing event: " << iev << endl;
   t->GetEntry(iev);

   if (binHFplusTrunc) parameter = getHFplusByPt(npart);
   if (binHFminusTrunc) parameter = getHFminusByPt(npart);
   if (binTracks) parameter = getTracksByGen(npart);

   values.push_back(parameter);
 }

 if(label.compare("b") == 0) sort(values.begin(),values.end(),descend);
 else sort(values.begin(),values.end());

 //Finding the bin boundaries
 txtfile << "-------------------------------------" << endl;
 txtfile << label.data() << " based cuts are: " << endl;
 txtfile << "(";

 int size = values.size();
 binboundaries[nbins] = values[size-1];

 for(int i = 0; i < nbins; i++) {
   int entry = (int)(i*(size/nbins));
   if(entry < 0 || i == 0) binboundaries[i] = 0;
   else binboundaries[i] = values[entry];
   txtfile << binboundaries[i] << ", ";
 }
 txtfile << binboundaries[nbins] << ")" << endl << "-------------------------------------" << endl;

 // Determining Glauber results in various bins
 TH2D* hNpart = new TH2D("hNpart","",nbins,binboundaries,40,0,40);
 TH2D* hNcoll = new TH2D("hNcoll","",nbins,binboundaries,40,0,40);
 TH2D* hNhard = new TH2D("hNhard","",nbins,binboundaries,50,0,50);
 TH2D* hb = new TH2D("hb","",nbins,binboundaries,600,0,30);

 for(unsigned int iev = 0; iev < Nevents; iev++) {
   if( iev % 20000 == 0 ) cout<<"Processing event : " << iev << endl;
   t->GetEntry(iev);

   if (binHFplusTrunc) parameter = getHFplusByPt(npart);
   if (binHFminusTrunc) parameter = getHFminusByPt(npart);
   if (binTracks) parameter = getTracksByGen(npart);

   hNpart->Fill(parameter,npart);
   hNcoll->Fill(parameter,ncoll);
   hNhard->Fill(parameter,nhard);
   hb->Fill(parameter,b);

   int bin = hNpart->GetXaxis()->FindBin(parameter) - 1;
   if(bin < 0) bin = 0;
   if(bin >= nbins) bin = nbins - 1;
   nt->Fill(parameter, et, bin, b, npart, ncoll, nhard);
 }

 TCanvas *cf = new TCanvas();
 TF1* fGaus = new TF1("fb","gaus(0)",0,2);
 fitSlices(hNpart,fGaus);
 fitSlices(hNcoll,fGaus);
 fitSlices(hNhard,fGaus);
 fitSlices(hb,fGaus);

 TH1D* hNpartMean = (TH1D*)gDirectory->Get("hNpart_1");
 TH1D* hNpartSigma = (TH1D*)gDirectory->Get("hNpart_2");
 TH1D* hNcollMean = (TH1D*)gDirectory->Get("hNcoll_1");
 TH1D* hNcollSigma = (TH1D*)gDirectory->Get("hNcoll_2");
 TH1D* hNhardMean = (TH1D*)gDirectory->Get("hNhard_1");
 TH1D* hNhardSigma = (TH1D*)gDirectory->Get("hNhard_2");
 TH1D* hbMean = (TH1D*)gDirectory->Get("hb_1");
 TH1D* hbSigma = (TH1D*)gDirectory->Get("hb_2");

 txtfile<<"-------------------------------------"<<endl;
 txtfile<<"# Bin NpartMean NpartSigma NcollMean NcollSigma bMean bSigma BinEdge"<<endl;
 for(int i = 0; i < nbins; i++){
   int ii = nbins-i;
   outputTable->table_[i].n_part_mean = hNpartMean->GetBinContent(ii);
   outputTable->table_[i].n_part_var = hNpartSigma->GetBinContent(ii);
   outputTable->table_[i].n_coll_mean = hNcollMean->GetBinContent(ii);
   outputTable->table_[i].n_coll_var = hNcollSigma->GetBinContent(ii);
   outputTable->table_[i].b_mean = hbMean->GetBinContent(ii);
   outputTable->table_[i].b_var = hbSigma->GetBinContent(ii);
   outputTable->table_[i].n_hard_mean = hNhardMean->GetBinContent(ii);
   outputTable->table_[i].n_hard_var = hNhardSigma->GetBinContent(ii);
   outputTable->table_[i].bin_edge = binboundaries[ii-1];

   txtfile << i << " " << hNpartMean->GetBinContent(ii) << " " << hNpartSigma->GetBinContent(ii) << " " << hNcollMean->GetBinContent(ii) << " " << hNcollSigma->GetBinContent(ii) << " " << hbMean->GetBinContent(ii) << " " <<hbSigma->GetBinContent(ii) << " " << binboundaries[ii-1] << " " <<endl;
 }
 txtfile<<"-------------------------------------"<<endl;

 outf->cd();
 dir->cd();
 outputTable->Write();
 nt->Write();
 for(int ih = 0; ih < nhist; ih++) {
   Npart_vs_PtGenPlusEta4[ih]->Write();
   PtGenPlusEta4_vs_HFplusEta4[ih]->Write();
   Npart_vs_PtGenMinusEta4[ih]->Write();
   PtGenMinusEta4_vs_HFminusEta4[ih]->Write();
   Npart_vs_Ngentrk[ih]->Write();
   Ngentrk_vs_Ntracks[ih]->Write();
 }
 outf->Write();
 txtfile.close();

}
Beispiel #30
0
void Run(const char *inFileName, const char *dirName, const char *treeName, 
	 const char *outFileName, const char *corrFileName,
	 const char *dupFileName, const char* rcorFileName, 
	 bool useweight, bool useMean, int nMin, bool inverse, double ratMin, 
	 double ratMax, int ietaMax, int sysmode, int puCorr, int applyL1Cut,
	 double l1Cut, int truncateFlag, int maxIter, bool useDepth, 
	 bool useGen, int runlo, int runhi, int phimin, int phimax, int zside,
	 int nvxlo, int nvxhi, int rbx, bool exclude, int higheta, 
	 double fraction, bool writeHisto, bool debug) {
 
  char    name[500];
  sprintf (name, "%s/%s", dirName, treeName);
  TChain *chain = new TChain(name);
  std::cout << "Create a chain for " << name << " from " << inFileName
	    << std::endl;
  if (!fillChain(chain,inFileName)) {
    std::cout << "*****No valid tree chain can be obtained*****" << std::endl;
  } else {
    std::cout << "Proceed with a tree chain with " << chain->GetEntries()
	      << " entries" << std::endl;
    Long64_t nentryTot = chain->GetEntries();
    Long64_t nentries = (fraction > 0.01 && fraction < 0.99) ? 
      (Long64_t)(fraction*nentryTot) : nentryTot;
    std::cout << "Tree " << name << " " << chain << " in directory " 
	      << dirName << " from file " << inFileName 
	      << " with nentries (tracks): " << nentries << std::endl;
    unsigned int k(0), kmax(maxIter);
    CalibTree t(dupFileName, rcorFileName, truncateFlag, useMean, runlo, runhi, 
		phimin, phimax, zside, nvxlo, nvxhi, sysmode, rbx, puCorr, 
		useDepth, useGen, exclude, higheta, chain); 
    t.h_pbyE      = new TH1D("pbyE", "pbyE", 100, -1.0, 9.0);
    t.h_Ebyp_bfr  = new TProfile("Ebyp_bfr","Ebyp_bfr",60,-30,30,0,10);
    t.h_Ebyp_aftr = new TProfile("Ebyp_aftr","Ebyp_aftr",60,-30,30,0,10);
    t.h_cvg       = new TH1D("Cvg0", "Convergence", kmax, 0, kmax);
    t.h_cvg->SetMarkerStyle(7);
    t.h_cvg->SetMarkerSize(5.0);
  
    TFile *fout = new TFile(outFileName, "RECREATE");
    std::cout << "Output file: " << outFileName << " opened in recreate mode" 
	      << std::endl;
    fout->cd();

    double cvgs[100], itrs[100]; 
    for (; k<=kmax; ++k) {
      std::cout << "Calling Loop() "  << k << "th time" << std::endl; 
      double cvg = t.Loop(k, fout, useweight, nMin, inverse, ratMin, ratMax, 
			  ietaMax, applyL1Cut, l1Cut, k==kmax, fraction, 
			  writeHisto, debug);
      itrs[k] = k;
      cvgs[k] = cvg;
      if (cvg < 0.00001) break;
    }

    t.writeCorrFactor(corrFileName, ietaMax);

    fout->cd();
    TGraph *g_cvg;
    g_cvg = new TGraph(k, itrs, cvgs);
    g_cvg->SetMarkerStyle(7);
    g_cvg->SetMarkerSize(5.0);
    g_cvg->Draw("AP");
    g_cvg->Write("Cvg");
    std::cout << "Finish looping after " << k << " iterations" << std::endl;
    t.makeplots(ratMin, ratMax, ietaMax, useweight, fraction, debug);
    fout->Close();
  }
}