void plotVBFVHReweighted(){
  gROOT->ProcessLine(".x tdrstyle.cc");
  gStyle->SetOptStat(0);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  foutput->cd();

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

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

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

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

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

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

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

      foutput->WriteTObject(cc);

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

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

  for (int tr = 0; tr < kNumTemplates; tr++){
    delete hVBF_onshell_LC[tr];
    delete hVBF_offshell_LC[tr];
    delete hVBF_onshell_scaled[tr];
    delete hVBF_offshell_scaled[tr];
    delete hVBF_onshell_scaled_wVBF[tr];
    delete hVBF_offshell_scaled_wVBF[tr];
  }
  foutput->Close();
}
//this makes Z(nunu) prediction vs. MC truth plots for the AN.
//at the moment all numbers are hard-coded and this code needs major revision, the mc truth numbers are loaded from a root file created by ZnunuNumbers.C
//furthermore the stored root file is used for both producing the final result plots/tables and also interpretation
void ZinvVisualization(){

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}
int main() 
{
   // this loads the library
   TMVA::Tools::Instance();

   //---------------------------------------------------------------
   // default MVA methods to be trained + tested
   
   std::map<std::string,int> Use;
   Use["Cuts"]            =1;
   Use["BDT"]             =1;
   
   // ---------------------------------------------------------------

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

   // Create a new root output file.
   TString outfileName( "TMVA_output.root" );
   TFile* outputFile = TFile::Open( outfileName, "RECREATE" );

   TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile, 
                                               "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D" );

    // Add the variables you want to consider 
    
    //factory->AddVariable( "MT := MT",  'F' );
    //factory->AddVariable( "nJets := nJets",  'F' );
    factory->AddVariable( "MET := MET",                   'F' );
    factory->AddVariable( "MT2W := MT2W",                 'F' );
    factory->AddVariable( "dPhiMETjet := dPhiMETjet",     'F' );
    factory->AddVariable( "HTratio := HTratio",           'F' );
    factory->AddVariable( "HadronicChi2 := HadronicChi2", 'F' );
    factory->AddVariable( "nWTag := nWTag",               'I' );
    
    // Open samples
    
    TFile* f_signal = TFile::Open((string(MICROTUPLES_FOLDER)+"signal.root").c_str());
    TFile* f_ttbar  = TFile::Open((string(MICROTUPLES_FOLDER)+"ttbar.root" ).c_str());
    //TFile* f_W2Jets = TFile::Open((string(MICROTUPLES_FOLDER)+"W2Jets.root").c_str());
    //TFile* f_W3Jets = TFile::Open((string(MICROTUPLES_FOLDER)+"W3Jets.root").c_str());
    //TFile* f_W4Jets = TFile::Open((string(MICROTUPLES_FOLDER)+"W4Jets.root").c_str());
    
    TTree* signal = (TTree*) f_signal->Get("microTuple");
    TTree* ttbar  = (TTree*) f_ttbar ->Get("microTuple");
    //TTree* W2Jets = (TTree*) f_W2Jets->Get("microTuple");
    //TTree* W3Jets = (TTree*) f_W3Jets->Get("microTuple");
    //TTree* W4Jets = (TTree*) f_W4Jets->Get("microTuple");

    // Register the trees

//    float weightSignal     = 1.0   * 20000.0 / getNumberOfEvent(signal);
//    float weightBackground = 225.2 * 20000.0 / getNumberOfEvent(ttbar);
    float weightSignal     = 1.0;
    float weightBackground = 1.0;

    factory->AddSignalTree    ( signal, weightSignal    );
    factory->AddBackgroundTree( ttbar,  weightBackground);

    /*
    cout << " signal ; w = " << 1.0   * 20000.0 / getNumberOfEvent(signal) << endl;
    factory->AddSignalTree    ( signal, 1.0   * 20000.0 / getNumberOfEvent(signal));
    cout << " ttbar ; w = "  << 225.2 * 20000.0 / getNumberOfEvent(ttbar) << endl;
    factory->AddBackgroundTree( ttbar,  234.0 * 20000.0 / getNumberOfEvent(ttbar));
    cout << " W2Jets ; w = " << 2159  * 20000.0 / getNumberOfEvent(W2Jets) << endl;
    factory->AddBackgroundTree( W2Jets, 2159  * 20000.0 / getNumberOfEvent(W2Jets));
    cout << " W3Jets ; w = " << 640   * 20000.0 / getNumberOfEvent(W3Jets) << endl;
    factory->AddBackgroundTree( W3Jets, 640   * 20000.0 / getNumberOfEvent(W3Jets));
    cout << " W4Jets ; w = " << 264   * 20000.0 / getNumberOfEvent(W4Jets) << endl;
    factory->AddBackgroundTree( W4Jets, 264   * 20000.0 / getNumberOfEvent(W4Jets));
    */

    // Add preselection cuts
   
    std::string preselectionCutsSig("nJets > 4 && MET > 80 && MT > 100");
    std::string preselectionCutsBkg("nJets > 4 && MET > 80 && MT > 100");

    // Prepare the training

    factory->PrepareTrainingAndTestTree( preselectionCutsSig.c_str(), preselectionCutsBkg.c_str(),
                    "nTrain_Signal=40000:nTrain_Background=300000:nTest_Signal=40000:nTest_Background=300000:SplitMode=Random:NormMode=EqualNumEvents:!V" );

    // Cut optimisation
    //if (Use["Cuts"])     factory->BookMethod( TMVA::Types::kCuts, "Cuts",
    //                     "!H:!V:FitMethod=MC:EffSel:SampleSize=200000:VarProp=FSmart" );
    if (Use["BDT"])      factory->BookMethod( TMVA::Types::kBDT, "BDT", 
                         "!H:!V:NTrees=400:nEventsMin=400:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning");
   
   // --------------------------------------------------------------

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

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

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

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

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

   delete factory;

   // Launch the GUI for the root macros
   //if (!gROOT->IsBatch()) TMVAGui( outfileName );
}
void createCorrectedBackgroundModel(std::string fileName, int nsidebands=6, bool makePlots=false, std::string defaultPrepend="CMS-HGG" ){

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

     global_nMassBins=nsidebands;

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

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

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

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

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

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

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

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

    if (makePlots){
      TCanvas *canv = new TCanvas();
      uCorrErr->SetMarkerColor(kGray);
      gPad->SetRightMargin(2.);
      uCorrErr->Draw("colz text");
      canv->Print(Form("BMplots/%s/uncorrErr_m%3.1f.png",type.c_str(),mH));
      canv->Print(Form("BMplots/%s/uncorrErr_m%3.1f.pdf",type.c_str(),mH));
    }
	}
	std::cout << "Saving Fits to file -> " << out->GetName() << std::endl;
        out->Close();
     }
    
    std::cout << "Updated (with corrected background model) -> " << in->GetName() << std::endl;
    in->Close();
}
void combinePreFullTests( string rootFullName, string rootPreTest, string rootOutputName)
{

  // open output file 
  TFile *_fileSave = TFile::Open( rootOutputName.c_str(), "new" );
  // open existing files
  TFile * fileFullTest = TFile::Open( rootFullName.c_str(),"read" );  
  TFile * filePreTest = TFile::Open( rootPreTest.c_str(),"read" );

  fileFullTest->cd();
  if( ! fileFullTest ) continue;
  
  TIter nextkey( gDirectory->GetListOfKeys() );
  TKey * key;

  cout << "Copy Subdirectory/histograms from " << fileFullTest->GetName() << endl;
  cout << "into the file: " << _fileSave->GetName() << endl;

  while( ( key = (TKey*)nextkey() ) ) {
    
    TObject * obj = key->ReadObj();
    if (obj->IsA()->InheritsFrom( "TDirectory" )){
      cout << "----- Subdir " << obj->GetName() <<  "  " << obj->GetUniqueID() << endl;
      // create same structure
      _fileSave->mkdir(obj->GetName());
      
      // loop over all histograms in subdirectory
      fileFullTest->cd(obj->GetName());
      TIter nextkey2( gDirectory->GetListOfKeys() );
      TKey * key2;
       
      string objName = obj->GetName(); 
      if (objName.substr(0,3) == "BB2"){
	cout << "for Subdirectory BB2 in file " << fileFullTest->GetName() << " do nothing"  << endl;
      }
      else{
	while( ( key2 = (TKey*)nextkey2() ) ) {
	  _fileSave->cd();	
	  TObject * obj2 = key2->ReadObj();
	  
	  if( obj2->IsA()->InheritsFrom( "TH2D" )) {
	    //cout << "2d histograms " << obj2->GetName() << endl;
	    TH2D * h2 = (TH2D*)obj2;	  
	    _fileSave->cd(obj->GetName());
	    h2->Write();	  
	  }
	  else if ( obj2->IsA()->InheritsFrom( "TH1D" )) {	  
	    //cout << "1d histograms " << obj2->GetName() << endl;
	    TH1D * h1 = (TH1D*)obj2;
	    _fileSave->cd(obj->GetName());
	    h1->Write();	  
	  }	
	}
      } // do not save BB2 from Fulltest but from next file
      // here please save BB2 to final file

    }
    else{
      // store Histograms which are not in a subdirectory HA and HD
      _fileSave->cd();
      if ( obj->IsA()->InheritsFrom( "TH1D" )) {	  
	//cout << "1d histograms " << obj->GetName() << endl;
	TH1D * h1 = (TH1D*)obj;
	_fileSave->cd();
	h1->Write();	  
      }	
      //cout << obj->GetName() <<  " this is a histogram " << endl;
    }

  }

  // Now use BB2 from Pretest and store it in the outputfile _fileSave

  if( ! filePreTest ) continue;

  filePreTest->cd();
  filePreTest->cd("BB2");
  cout << "copy BB2 histograms from file " << filePreTest->GetName() << " into " << _fileSave->GetName() << endl;
 
  TIter nextkey3( gDirectory->GetListOfKeys() );
  TKey * key3;
  while( ( key3 = (TKey*)nextkey3() ) ) {    
    TObject * obj3 = key3->ReadObj();
    if( obj3->IsA()->InheritsFrom( "TH2D" )) {
      //cout << "2d histograms " << obj3->GetName() << endl;
      TH2D * h2 = (TH2D*)obj3;	  
      _fileSave->cd("BB2");
      h2->Write();	  
    }
    else if ( obj3->IsA()->InheritsFrom( "TH1D" )) {	  
      //cout << "1d histograms " << obj3->GetName() << endl;
      TH1D * h1 = (TH1D*)obj3;
      _fileSave->cd("BB2");
      h1->Write();	  
    }
    //cout << "----- " << obj3->GetName() << endl;
  }


  fileFullTest->Close();
  filePreTest->Close();
  _fileSave->Close();

}
Example #6
0
int Ana(const char *filename, const char* outdir, TFile *fileout)
{
  //TFile *file = new TFile("mc_KPI_22324.root");
  TFile *file;
  if (filename==0) file= new TFile("KK_22324.root");
  else file = new TFile(filename);
  std::cout<<"File name is "<<file->GetName()<<std::endl;
  if (file==0) return -1;
  TTree *tree = (TTree*)file->Get("TwoProng");
  if (tree==0) return -2;

  double ene[22];
  double pcut[22];
  double epcut[22];
  double thecut[22];
  double m_pcut;
  double m_epcut;
  double m_thecut;
  ifstream cutin("cutpar");
  char line[1000];
  if (cutin.is_open()) cutin.getline(line,1000);
  int iene=0;
  // set E/p and p cut, mark: set cut
  while (!cutin.eof()){
    cutin.getline(line,1000);
    istringstream iss;
    iss.str(line);
    iss>>ene[iene]>>pcut[iene]>>epcut[iene];
    iene++;
    if (iene==22) break;
  }
  for (int i=0;i<22;i++) epcut[i] = 1.64295 - 0.629622*ene[i] + 0.104755 *pow(ene[i],2);
  //for (int i=0;i<21;i++) thecut[i] = 173.946 + 1.74736*ene[i];
  for (int i=0;i<22;i++) thecut[i] = 179;

  double kappx,kappy,kappz,kampx,kampy,kampz;
  int nneu;
  int run;
  int idxmc;
  int pdgid[100];
  int motheridx[100];
  int emcstatusInt;
  short emcstatusShort;
  double emctrk1;
  double emctrk2;
  double epratio1;
  double epratio2;
  int ntof1;
  int ntof2;
  int tofl1[5];
  int tofl2[5];
  double tof1[5];
  double tof2[5];
  tree->SetBranchAddress("run",&run);
  tree->SetBranchAddress("indexmc",&idxmc);
  tree->SetBranchAddress("pdgid",pdgid);
  tree->SetBranchAddress("motheridx",motheridx);
  tree->SetBranchAddress("kappx",&kappx);
  tree->SetBranchAddress("kappy",&kappy);
  tree->SetBranchAddress("kappz",&kappz);
  tree->SetBranchAddress("kampx",&kampx);
  tree->SetBranchAddress("kampy",&kampy);
  tree->SetBranchAddress("kampz",&kampz);
  //tree->SetBranchAddress("costheta",&costheta);
  tree->SetBranchAddress("nneu",&nneu);
  if (strncmp(tree->GetBranch("emcstatus")->GetLeaf("emcstatus")->GetTypeName(),"Short_t",7)==0)
  	tree->SetBranchAddress("emcstatus",&emcstatusShort);
  else 
  	tree->SetBranchAddress("emcstatus",&emcstatusInt);
  tree->SetBranchAddress("epratio1",&epratio1);
  tree->SetBranchAddress("epratio2",&epratio2);
  tree->SetBranchAddress("emctrk1",&emctrk1);
  tree->SetBranchAddress("emctrk2",&emctrk2);
  tree->SetBranchAddress("ntof1",&ntof1);
  tree->SetBranchAddress("toflayer1",tofl1);
  tree->SetBranchAddress("tof1",tof1);
  tree->SetBranchAddress("ntof2",&ntof2);
  tree->SetBranchAddress("toflayer2",tofl2);
  tree->SetBranchAddress("tof2",tof2);
  double pi = TMath::Pi();
  double mka = 0.493677;
  //double mka = 0.13957;
  //double mka = 0.1057;
  

  tree->GetEntry(0);
  double Ebeam = GetEnergy(run);
  if (Ebeam<1.0) Ebeam = getEne(filename);
  //Ebeam = 3.08;

  for (int iene=0;iene<22;iene++){
    if (fabs(Ebeam-ene[iene])<1e-4) {
      m_pcut = pcut[iene];
      m_epcut = epcut[iene];
      m_thecut = thecut[iene];
      break;
    }
  }
  //m_epcut = m_epcut +0.05; // change E/p to determine uncertainty from this cut
  //m_thecut = 179+0.2; // uncertainty from theta cut
  //m_pcut = 0.956409;
  m_thecut = 179;
  m_epcut = 1.64295 - 0.629622*Ebeam + 0.104755 *pow(Ebeam,2);
  double m_tofcut = 3;
  //m_tofcut = 3-1;
  std::cout<<"pcut "<<m_pcut<<", E/p cut "<<m_epcut<<std::endl;

  //TFile *fileout = new TFile(name,"recreate");
  const char *pureName = getPureName2(filename);
  std::cout<<"Pure Name: "<< pureName <<std::endl;
  char name1[1000];
  //sprintf(name1,"output/%s.root",pureName);
  sprintf(name1,"output/%s.root",pureName);
  
  TLorentzVector kap,kam;
  double mass;

  double totp, costheta1, costheta2;
  double costheta;
  double p1,p2;
  double tof11=-1000,tof21=-1000;
  int tofid;
  int isrtag=0;
  int tof1tag=0;
  int tof2tag=0;
  int emctag=0;
  
  fileout->cd();

  int nentries = tree->GetEntries();
  double pexp = sqrt(pow(Ebeam/2,2)-pow(mka,2));
  std::cout<<"Total entries is " << nentries << std::endl;
  std::cout<<"Beam energy is " << Ebeam << std::endl;
  std::cout<<"Expected K momentum is " << pexp << std::endl;
  int count0=0,count1=0,count2=0,count3=0;
  int count[10]={0};
  int tagmc=0;

  double sumdeffp=0;
  double sumdeffm=0;
  double sumcntp=0;
  double sumcntm=0;

  for (int ien=0;ien<nentries;ien++){
    tree->GetEntry(ien);
    
     //if ( run == 39582||run == 39671||run == 39723||run == 39783||run == 40208||run == 40300||run == 40308||run == 40462||run == 40526||run == 40946||run == 41099||run == 41200||run == 41283||run == 41408||run == 41416||run == 41436||run == 41445||run == 41471||run == 41728||run == 41818||run == 41902) continue;
     
    isrtag = 0;
    for (int j=0;j<idxmc;j++){
      if (pdgid[j] == 22 && motheridx[j]==j) { tagmc++; isrtag=1;}
    }
    if (emcstatusShort!=0x3 && emcstatusInt!=0x3) continue;
    if (ntof1<1) continue;
    if (ntof2<1) continue;
    for (int i=0;i<ntof1;i++){
      if (tofl1[i]==1) tof11=tof1[i];
    }
    for (int i=0;i<ntof2;i++){
      if (tofl2[i]==1) tof21=tof2[i];
    }
    //if (tof11<-999 || tof21<-999) continue;
    count0++;

    kap.SetVectMag(TVector3(kappx,kappy,kappz),mka);
    kam.SetVectMag(TVector3(kampx,kampy,kampz),mka);
    
    // angular information in lab coordinate
    costheta1 = kap.CosTheta();
    costheta2 = kam.CosTheta();
    
    // momentum information in cms coordinalte
    kap.Boost(-0.011,0,0);
    kam.Boost(-0.011,0,0);
    costheta = kap.Vect().Dot(kam.Vect())/(kap.Vect().Mag()*kam.Vect().Mag());
    double theta = kap.Vect().Angle(kam.Vect())/TMath::Pi()*180.;
    mass = (kap+kam).M();
    totp = (kap+kam).Rho();
    p1 = kap.Rho();
    p2 = kam.Rho();
 
    // select candidate, p1 dis
    // if (count0%100000==0) std::cout<<"epratio1 is "<< epratio1<<std::endl;
    if (fabs(costheta1)<0.93 && costheta1 < 0.8) { count[4]++;
    if (fabs(costheta2)<0.93 && costheta2 > -0.8){ count[5]++;
    if (theta>m_thecut){ count[2]++;
    if (epratio1<m_epcut)
    { count[0]++;
      if (epratio2<m_epcut)
      { count[1]++;
        if (fabs(tof11-tof21)<m_tofcut){
          count3++;
          if (p2<m_pcut && p1<m_pcut) {/*datasel2->Fill();*/ count2++; // p2 dis
            //datasel1->Fill();
	sumdeffp += getDeffp(kap.Pt())/pow(getDeffpErr(kap.Pt()),2);
	sumdeffm += getDeffm(kam.Pt())/pow(getDeffmErr(kam.Pt()),2);
	sumcntp += 1.0/pow(getDeffpErr(kap.Pt()),2);
	sumcntm += 1.0/pow(getDeffmErr(kam.Pt()),2);
          }
        }
      }
    }
    }
    
    }
    }
  }
  double avedeffp = sumdeffp/sumcntp;
  double avedeffm = sumdeffm/sumcntm;
  double deff = sqrt(avedeffp*avedeffp+avedeffm*avedeffm);
  cout<< "for file: "<< filename<<endl;
  cout<<"+ tracking error: "<< avedeffp<<endl;
  cout<<"- tracking error: "<< avedeffm<<endl;
  cout<<"tracking error: sqrt    "<< deff<<endl;
  cout<<"tracking error: e+ + e- "<< avedeffp+avedeffm<<endl;
  cout<<"tracking error: abs+ + abs- "<<  fabs(avedeffp)+fabs(avedeffm)<<endl;
  

  ofstream cutflow("cutflow2",std::ios::app);
  cutflow<<filename<<std::endl;
  cutflow<<"Initial size      :"<<nentries<<std::endl;
  cutflow<<"Tagged ISR evt    :"<< tagmc  <<std::endl;
  cutflow<<"Tagged no ISR evt :"<< nentries - tagmc  <<std::endl;
  cutflow<<"Valid tof and emc :"<<count0<<std::endl;
  cutflow<<"After cos1<0.8    :"<<count[4]<<std::endl;
  cutflow<<"After cos2>-0.8   :"<<count[5]<<std::endl;
  cutflow<<"After theta cut   :"<<count[2]<<std::endl;
  cutflow<<"After ep1         :"<<count[0]<<std::endl;
  cutflow<<"After ep2         :"<<count[1]<<std::endl;
  //cutflow<<"After totp<0.05   :"<<count[3]<<std::endl;
  cutflow<<"After dtof<3      :"<<count3<<std::endl;
  //cutflow<<"p1-exp<0.08 for p1:"<<count1<<std::endl;
  cutflow<<"p2-exp<3 sigma    :"<<count2<<std::endl;

  // finish program here
  return 0;
 
}
void RunEbyEFlowAnalysisFWLite(
           int ffrom, int fto,
           double zvtxmin, double zvtxmax,
           int nmin, int nmax,
           int centmin, int centmax)
{
  setup(ffrom, fto, zvtxmin, zvtxmax, nmin, nmax, centmin, centmax);

  TStopwatch *watch = new TStopwatch();

  // Run the analysis 
  TList* files = GetFileList(gFilesetname.Data());
  if(!files) {
    cerr << "Could not retrieve fileset: " << gFilesetname << endl;
    return;
  }

  vector<string> fileNames = GetDataVector(files,gFfrom,gFto);
  fwlite::ChainEvent event(fileNames);  

  //Initialize the analyzer      
  EbyEFlowAnalyzerFWLite* corr = new EbyEFlowAnalyzerFWLite(event);
  corr->SetCutParameters(gCut);

  TString strtrgid = "Track";
  if(gSystem->Getenv("TRGID")) strtrgid = gSystem->Getenv("TRGID");
  DiHadronCorrelationMultiBaseFWLite::ParticleType gTrgID = corr->GetParticleID(strtrgid);
  TString strassid = "Track";
  if(gSystem->Getenv("ASSID")) strassid = gSystem->Getenv("ASSID");
  DiHadronCorrelationMultiBaseFWLite::ParticleType gAssID = corr->GetParticleID(strassid);
  corr->SetTrgID(gTrgID);
  corr->SetAssID(gAssID);

  if(gCentfilename.Contains("root"))
  {
    cout<<"Running correlation analysis in Heavy Ion!"<<endl;
    TFile* fcentfile = new TFile(gCentfilename.Data());
    if(fcentfile->IsOpen()) corr->SetCentrality(fcentfile,gCenttablename,gNCentBins,gCentRunnum);
    else cout<<"Centrality table cannot be opened!"<<endl;
  }
  else cout<<"Running correlation analysis in pp!"<<endl;

  if(gEffhistname.Contains("root"))
  {
    TFile* feffhist = new TFile(gEffhistname.Data());    
    if(feffhist->IsOpen())
    {
      TH3D* htotaleff = 0;
      if(!gCut.IsHI) htotaleff = (TH3D*)feffhist->Get("rTotalEff3D");
      else
      {
        int histcentbin = -1;
        if((gCut.centmin>=0 && gCut.centmax<=2) || gCut.centmin>=50) histcentbin = 0;
        if(gCut.centmin>=2 && gCut.centmax<=4) histcentbin = 1;
        if(gCut.centmin>=4 && gCut.centmax<=12) histcentbin = 2;
        if(gCut.centmin>=12 && gCut.centmax<=20) histcentbin = 3;
        if(gCut.centmin>=20 && gCut.centmax<=40) histcentbin = 4;
        if(gCut.centmin==-1 && gCut.centmax==-1) histcentbin = 4;

        htotaleff = (TH3D*)feffhist->Get(Form("Tot_%d",histcentbin));
      }
      corr->LoadEffWeight(htotaleff);
      cout<<"Tracking efficiency weighting histogram is loaded!"<<endl;
    }
    else cout<<"Tracking efficiency weighting file cannot be opened!"<<endl;
  }
  else cout<<"No Tracking efficiency weighting histogram is found, or it's running MC!"<<endl;

  if(gTrghistname.Contains("root"))
  {
    TFile* ftrghist = new TFile(gTrghistname.Data());
    if(ftrghist->IsOpen())
    {
      corr->LoadTrgWeight((TH1D*)ftrghist->Get("trgEff"));
      cout<<"Triggering efficiency weighting histogram is loaded!"<<endl;
    }
    else cout<<"Triggering efficiency weighting file cannot be opened!"<<endl;
  }
  else cout<<"No Triggering efficiency weighting histogram is found, or it's running MC!"<<endl;

  if(gPileupdistfunchistname.Contains("root"))
  {
    TFile* fpileupdistfunchist = new TFile(gPileupdistfunchistname.Data());
    if(fpileupdistfunchist->IsOpen())
    {
      corr->LoadPileUpDistFunc((TH1D*)fpileupdistfunchist->Get("distfunc"));
      cout<<"Pileup distfunc histogram is loaded!"<<endl;
    }
    else cout<<"Pileup distfunc file cannot be opened!"<<endl;
  }

  corr->Process();

  // open output file
  TString outputfilename = Form("%s/%s/unmerged/%s_%s_ffrom%d_fto%d_vtxmin%.1f_vtxmax%.1f_nmin%d_nmax%d_etatrg%.1f-%.1f_etaass%.1f-%.1f_centmin%d_centmax%d.root",gOutputDir.Data(),gEventtype.Data(),gEventtype.Data(),gTag.Data(),gFfrom,gFto,gCut.zvtxmin,gCut.zvtxmax,gCut.nmin,gCut.nmax,gCut.etatrgmin,gCut.etatrgmax,gCut.etaassmin,gCut.etaassmax,gCut.centmin,gCut.centmax);
  TFile* outf = new TFile(outputfilename.Data(),"recreate");

  // Save the outputs
  TList* output = corr->GetOutputs();
  if(outf && output) {
    outf->cd();
    output->Write();
    cout << "Output file " <<  outf->GetName()
    << " written: " << endl;
    outf->ls();
    outf->Close();
    if(outf) delete outf;
  }  
  delete output;

  watch->Stop();
  watch->Print();
}
void TMVAClassification( TString myMethodList = "" )
{
   // The explicit loading of the shared libTMVA is done in TMVAlogon.C, defined in .rootrc
   // if you use your private .rootrc, or run from a different directory, please copy the
   // corresponding lines from .rootrc

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

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

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

   Use["Cuts"]            = 0;
   Use["CutsD"]           = 0;
   Use["CutsPCA"]         = 0;
   Use["CutsGA"]          = 0;
   Use["CutsSA"]          = 0;
   // ---
   Use["Likelihood"]      = 1;
   Use["LikelihoodD"]     = 0; // 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;
   // ---
   Use["PDERS"]           = 0;
   Use["PDERSD"]          = 0;
   Use["PDERSPCA"]        = 0;
   Use["PDERSkNN"]        = 0; // depreciated until further notice
   Use["PDEFoam"]         = 0;
   // --
   Use["KNN"]             = 0;
   // ---
   Use["HMatrix"]         = 0;
   Use["Fisher"]          = 0;
   Use["FisherG"]         = 0;
   Use["BoostedFisher"]   = 0;
   Use["LD"]              = 0;
   // ---
   Use["FDA_GA"]          = 0;
   Use["FDA_SA"]          = 0;
   Use["FDA_MC"]          = 0;
   Use["FDA_MT"]          = 0;
   Use["FDA_GAMT"]        = 0;
   Use["FDA_MCMT"]        = 0;
   // ---
   Use["MLP"]             = 0; // this is the 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; // *** missing
   Use["TMlpANN"]         = 0;
   // ---
   Use["SVM"]             = 0;
   // ---
   Use["BDT"]             = 1;
   Use["BDTD"]            = 0;
   Use["BDTG"]            = 0;
   Use["BDTB"]            = 0;
   // ---
   Use["RuleFit"]         = 0;
   // ---
   Use["Plugin"]          = 0;
   // ---------------------------------------------------------------

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

   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] = 0;
      }
   }

   // Create a new root output file.
   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 will
   // then run the performance analysis for you.
   //
   // The first argument is the base of the name of all the
   // weightfiles in the directory weight/
   //
   // The second argument is the output file for the training results
   // All TMVA output can be suppressed by removing the "!" (not) in
   // front of the "Silent" argument in the option string
   TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
                                               "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );

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

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

   // 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

factory->AddVariable("BDTZH105",'F');

factory->AddVariable("LikelihoodZH105",'F');

factory->AddVariable("BDTZZ",'F');

factory->AddVariable("LikelihoodZZ",'F');
   if (ReadDataFromAsciiIFormat) {
      // load the signal and background event samples from ascii files
      // format in file must be:
      // var1/F:var2/F:var3/F:var4/F
      // 0.04551   0.59923   0.32400   -0.19170
      // ...

      TString datFileS = "tmva_example_sig.dat";
      TString datFileB = "tmva_example_bkg.dat";

      factory->SetInputTrees( datFileS, datFileB );
   }
   else {
      // load the signal and background event samples from ROOT trees
      TString fname = "./tmva_class_example.root";

      TString fname_Data7TeV_DoubleElectron2011B_0 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//Data7TeV_DoubleElectron2011B_0.root";

      TString fname_Data7TeV_MuEG2011B_0 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//Data7TeV_MuEG2011B_0.root";

      TString fname_SingleT_tW = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//SingleT_tW.root";

      TString fname_SingleT_s = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//SingleT_s.root";

      TString fname_Data7TeV_DoubleMu2011B_0 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//Data7TeV_DoubleMu2011B_0.root";

      TString fname_F_ZH150 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//F_ZH150.root";

      TString fname_F_ZH105 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//F_ZH105.root";

      TString fname_Data7TeV_DoubleElectron2011A_0 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//Data7TeV_DoubleElectron2011A_0.root";

      TString fname_DYJetsToLL = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//DYJetsToLL.root";

      TString fname_SingleTbar_t = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//SingleTbar_t.root";

      TString fname_Data7TeV_DoubleElectron2011B_1 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//Data7TeV_DoubleElectron2011B_1.root";

      TString fname_Data7TeV_DoubleMu2011A_1 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//Data7TeV_DoubleMu2011A_1.root";

      TString fname_Data7TeV_MuEG2011A_1 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//Data7TeV_MuEG2011A_1.root";

      TString fname_TTJets = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//TTJets.root";

      TString fname_F_ZH145 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//F_ZH145.root";

      TString fname_SingleTbar_s = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//SingleTbar_s.root";

      TString fname_WJetsToLNu = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//WJetsToLNu.root";

      TString fname_Data7TeV_DoubleElectron2011A_1 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//Data7TeV_DoubleElectron2011A_1.root";

      TString fname_F_ZH125 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//F_ZH125.root";

      TString fname_ZZ = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//ZZ.root";

      TString fname_Data7TeV_MuEG2011B_1 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//Data7TeV_MuEG2011B_1.root";

      TString fname_F_ZH135 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//F_ZH135.root";

      TString fname_WW = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//WW.root";

      TString fname_Data7TeV_DoubleMu2011A_0 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//Data7TeV_DoubleMu2011A_0.root";

      TString fname_SingleTbar_tW = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//SingleTbar_tW.root";

      TString fname_WZ = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//WZ.root";

      TString fname_Data7TeV_MuEG2011A_0 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//Data7TeV_MuEG2011A_0.root";

      TString fname_Data7TeV_DoubleMu2011B_1 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//Data7TeV_DoubleMu2011B_1.root";

      TString fname_F_ZH115 = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//F_ZH115.root";

      TString fname_SingleT_t = "/tmp/chasco/INIT/HADD/TMVA/Trees_FUSION2/ZZ_vs_nonZZ/ZH105_vs_ZZ/ZH115_vs_ZZ/ZH125_vs_ZZ/ZH150_vs_ZZ/ZH135_vs_ZZ/ZH145_vs_ZZ//SingleT_t.root";


      if (gSystem->AccessPathName( fname ))  // file does not exist in local directory
         gSystem->Exec("wget http://root.cern.ch/files/tmva_class_example.root");

      TFile *input_Data7TeV_DoubleElectron2011B_0 = TFile::Open( fname_Data7TeV_DoubleElectron2011B_0 );

      TFile *input_Data7TeV_MuEG2011B_0 = TFile::Open( fname_Data7TeV_MuEG2011B_0 );

      TFile *input_SingleT_tW = TFile::Open( fname_SingleT_tW );

      TFile *input_SingleT_s = TFile::Open( fname_SingleT_s );

      TFile *input_Data7TeV_DoubleMu2011B_0 = TFile::Open( fname_Data7TeV_DoubleMu2011B_0 );

      TFile *input_F_ZH150 = TFile::Open( fname_F_ZH150 );

      TFile *input_F_ZH105 = TFile::Open( fname_F_ZH105 );

      TFile *input_Data7TeV_DoubleElectron2011A_0 = TFile::Open( fname_Data7TeV_DoubleElectron2011A_0 );

      TFile *input_DYJetsToLL = TFile::Open( fname_DYJetsToLL );

      TFile *input_SingleTbar_t = TFile::Open( fname_SingleTbar_t );

      TFile *input_Data7TeV_DoubleElectron2011B_1 = TFile::Open( fname_Data7TeV_DoubleElectron2011B_1 );

      TFile *input_Data7TeV_DoubleMu2011A_1 = TFile::Open( fname_Data7TeV_DoubleMu2011A_1 );

      TFile *input_Data7TeV_MuEG2011A_1 = TFile::Open( fname_Data7TeV_MuEG2011A_1 );

      TFile *input_TTJets = TFile::Open( fname_TTJets );

      TFile *input_F_ZH145 = TFile::Open( fname_F_ZH145 );

      TFile *input_SingleTbar_s = TFile::Open( fname_SingleTbar_s );

      TFile *input_WJetsToLNu = TFile::Open( fname_WJetsToLNu );

      TFile *input_Data7TeV_DoubleElectron2011A_1 = TFile::Open( fname_Data7TeV_DoubleElectron2011A_1 );

      TFile *input_F_ZH125 = TFile::Open( fname_F_ZH125 );

      TFile *input_ZZ = TFile::Open( fname_ZZ );

      TFile *input_Data7TeV_MuEG2011B_1 = TFile::Open( fname_Data7TeV_MuEG2011B_1 );

      TFile *input_F_ZH135 = TFile::Open( fname_F_ZH135 );

      TFile *input_WW = TFile::Open( fname_WW );

      TFile *input_Data7TeV_DoubleMu2011A_0 = TFile::Open( fname_Data7TeV_DoubleMu2011A_0 );

      TFile *input_SingleTbar_tW = TFile::Open( fname_SingleTbar_tW );

      TFile *input_WZ = TFile::Open( fname_WZ );

      TFile *input_Data7TeV_MuEG2011A_0 = TFile::Open( fname_Data7TeV_MuEG2011A_0 );

      TFile *input_Data7TeV_DoubleMu2011B_1 = TFile::Open( fname_Data7TeV_DoubleMu2011B_1 );

      TFile *input_F_ZH115 = TFile::Open( fname_F_ZH115 );

      TFile *input_SingleT_t = TFile::Open( fname_SingleT_t );


      std::cout << "--- TMVAClassification       : Using input_Data7TeV_DoubleElectron2011B_0 file: " << input_Data7TeV_DoubleElectron2011B_0->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_Data7TeV_MuEG2011B_0 file: " << input_Data7TeV_MuEG2011B_0->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_SingleT_tW file: " << input_SingleT_tW->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_SingleT_s file: " << input_SingleT_s->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_Data7TeV_DoubleMu2011B_0 file: " << input_Data7TeV_DoubleMu2011B_0->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_F_ZH150 file: " << input_F_ZH150->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_F_ZH105 file: " << input_F_ZH105->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_Data7TeV_DoubleElectron2011A_0 file: " << input_Data7TeV_DoubleElectron2011A_0->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_DYJetsToLL file: " << input_DYJetsToLL->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_SingleTbar_t file: " << input_SingleTbar_t->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_Data7TeV_DoubleElectron2011B_1 file: " << input_Data7TeV_DoubleElectron2011B_1->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_Data7TeV_DoubleMu2011A_1 file: " << input_Data7TeV_DoubleMu2011A_1->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_Data7TeV_MuEG2011A_1 file: " << input_Data7TeV_MuEG2011A_1->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_TTJets file: " << input_TTJets->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_F_ZH145 file: " << input_F_ZH145->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_SingleTbar_s file: " << input_SingleTbar_s->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_WJetsToLNu file: " << input_WJetsToLNu->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_Data7TeV_DoubleElectron2011A_1 file: " << input_Data7TeV_DoubleElectron2011A_1->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_F_ZH125 file: " << input_F_ZH125->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_ZZ file: " << input_ZZ->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_Data7TeV_MuEG2011B_1 file: " << input_Data7TeV_MuEG2011B_1->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_F_ZH135 file: " << input_F_ZH135->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_WW file: " << input_WW->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_Data7TeV_DoubleMu2011A_0 file: " << input_Data7TeV_DoubleMu2011A_0->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_SingleTbar_tW file: " << input_SingleTbar_tW->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_WZ file: " << input_WZ->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_Data7TeV_MuEG2011A_0 file: " << input_Data7TeV_MuEG2011A_0->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_Data7TeV_DoubleMu2011B_1 file: " << input_Data7TeV_DoubleMu2011B_1->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_F_ZH115 file: " << input_F_ZH115->GetName() << std::endl;

      std::cout << "--- TMVAClassification       : Using input_SingleT_t file: " << input_SingleT_t->GetName() << std::endl;


      TTree *signal_F_ZH105     = (TTree*)input_F_ZH105->Get("tmvatree");

      TTree *background_SingleT_tW = (TTree*)input_SingleT_tW->Get("tmvatree");

      TTree *background_DYJetsToLL = (TTree*)input_DYJetsToLL->Get("tmvatree");

      TTree *background_SingleTbar_t = (TTree*)input_SingleTbar_t->Get("tmvatree");

      TTree *background_TTJets = (TTree*)input_TTJets->Get("tmvatree");

      TTree *background_ZZ = (TTree*)input_ZZ->Get("tmvatree");

      TTree *background_WW = (TTree*)input_WW->Get("tmvatree");

      TTree *background_SingleTbar_tW = (TTree*)input_SingleTbar_tW->Get("tmvatree");

      TTree *background_WZ = (TTree*)input_WZ->Get("tmvatree");

      TTree *background_SingleT_t = (TTree*)input_SingleT_t->Get("tmvatree");


      // global event weights per tree (see below for setting event-wise weights)
      Double_t signalWeight     = 1.0;
      Double_t backgroundWeight = 1.0;

      // ====== register trees ====================================================
      //
      // the following method is the prefered one:
      // you can add an arbitrary number of signal or background trees
      factory->AddSignalTree    ( signal_F_ZH105,     1.0     );

      factory->AddBackgroundTree( background_SingleT_tW, 1.0 );

      factory->AddBackgroundTree( background_DYJetsToLL, 1.0 );

      factory->AddBackgroundTree( background_SingleTbar_t, 1.0 );

      factory->AddBackgroundTree( background_TTJets, 1.0 );

      factory->AddBackgroundTree( background_ZZ, 1.0 );

      factory->AddBackgroundTree( background_WW, 1.0 );

      factory->AddBackgroundTree( background_SingleTbar_tW, 1.0 );

      factory->AddBackgroundTree( background_WZ, 1.0 );

      factory->AddBackgroundTree( background_SingleT_t, 1.0 );


      // To give different trees for training and testing, do as follows:
      //    factory->AddSignalTree( signal_F_ZH105TrainingTree, signal_F_ZH105TrainWeight, "Training" );

      //    factory->AddSignalTree( signal_F_ZH105TestTree,     signal_F_ZH105TestWeight,  "Test" );


      // Use the following code instead of the above two or four lines to add signal and background
      // training and test events "by hand"
      // NOTE that in this case one should not give expressions (such as "var1+var2") in the input
      //      variable definition, but simply compute the expression before adding the event
      //
      //    // --- begin ----------------------------------------------------------
      //    std::vector<Double_t> vars( 4 ); // vector has size of number of input variables
      //    Float_t  treevars[4];
      //    for (Int_t ivar=0; ivar<4; ivar++) signal->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
      //    for (Int_t i=0; i<signal->GetEntries(); i++) {
      //       signal->GetEntry(i);
      //       for (Int_t ivar=0; ivar<4; ivar++) vars[ivar] = treevars[ivar];
      //       // add training and test events; here: first half is training, second is testing
      //       // note that the weight can also be event-wise
      //       if (i < signal->GetEntries()/2) factory->AddSignalTrainingEvent( vars, signalWeight );
      //       else                            factory->AddSignalTestEvent    ( vars, signalWeight );
      //    }
      //
      //    for (Int_t ivar=0; ivar<4; ivar++) background->SetBranchAddress( Form( "var%i", ivar+1 ), &(treevars[ivar]) );
      //    for (Int_t i=0; i<background->GetEntries(); i++) {
      //       background->GetEntry(i);
      //       for (Int_t ivar=0; ivar<4; ivar++) vars[ivar] = treevars[ivar];
      //       // add training and test events; here: first half is training, second is testing
      //       // note that the weight can also be event-wise
      //       if (i < background->GetEntries()/2) factory->AddBackgroundTrainingEvent( vars, backgroundWeight );
      //       else                                factory->AddBackgroundTestEvent    ( vars, backgroundWeight );
      //    }
      //    // --- end ------------------------------------------------------------
      //
      // ====== end of register trees ==============================================
   }

   // This would set individual event weights (the variables defined in the
   // expression need to exist in the original TTree)
   //    for signal    : factory->SetSignalWeightExpression("weight1*weight2");
   //    for background: factory->SetBackgroundWeightExpression("weight1*weight2");
   factory->SetBackgroundWeightExpression("Eweight*XS*BR*LUM*(1/NGE)*(B2/B3)*CUT");
   factory->SetSignalWeightExpression("Eweight*XS*BR*LUM*(1/NGE)*(B2/B3)*CUT");

   // Apply additional cuts on the signal and background samples (can be different)
TCut mycuts = "(CUT>2)";
TCut mycutb = "(CUT>2)";

   // tell the factory to use all remaining events in the trees after training for testing:

 factory->PrepareTrainingAndTestTree( mycuts, "SplitMode=random:!V" );
//                                        "nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!V" );

   // If no numbers of events are given, half of the events in the tree are used for training, and
   // the other half for testing:
   //    factory->PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );
   // To also specify the number of testing events, use:
   //    factory->PrepareTrainingAndTestTree( mycut,
   //                                         "NSigTrain=3000:NBkgTrain=3000:NSigTest=3000:NBkgTest=3000:SplitMode=Random:!V" );

   // ---- 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:Seed=0:EffSel:Steps=50:Cycles=3:PopSize=1000: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
   if (Use["Likelihood"])
      factory->BookMethod( TMVA::Types::kLikelihood, "Likelihood",
                           "H:!V:!TransformOutput:PDFInterpol=Spline2:NSmoothBkg[1]=10:NSmooth=1:NAvEvtPerBin=50" );

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

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

   // test the new kernel density estimator
   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" ); 

   // test the mixed splines and kernel density estimator (depending on which variable)
   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["PDERSkNN"])
      factory->BookMethod( TMVA::Types::kPDERS, "PDERSkNN",
                           "!H:!V:VolumeRangeMode=kNN: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.0333:nActiveCells=500:nSampl=2000:nBin=5:CutNmin=T:Nmin=100: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" );

   // Fisher discriminant
   if (Use["Fisher"])
      factory->BookMethod( TMVA::Types::kFisher, "Fisher", "H:!V:Fisher:CreateMVAPdfs:PDFInterpolMVAPdf=Spline2:NbinsMVAPdf=60: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");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   // 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, see: TMVAClassificationCategory

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

   // As an example how to use the ROOT plugin mechanism, book BDT via
   // plugin mechanism
   if (Use["Plugin"]) {
         //
         // first the plugin has to be defined, which can happen either through the following line in the local or global .rootrc:
         //
         // # plugin handler          plugin name(regexp) class to be instanciated library        constructor format
         // Plugin.TMVA@@MethodBase:  ^BDT                TMVA::MethodBDT          TMVA.1         "MethodBDT(TString,TString,DataSet&,TString)"
         //
         // or by telling the global plugin manager directly
      gPluginMgr->AddHandler("TMVA@@MethodBase", "BDT", "TMVA::MethodBDT", "TMVA.1", "MethodBDT(TString,TString,DataSet&,TString)");
      factory->BookMethod( TMVA::Types::kPlugins, "BDT",
                           "!H:!V:NTrees=500:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=CostComplexity:PruneStrength=50" );
   }

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

   // ---- 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;

   delete factory;

   // Launch the GUI for the root macros

gROOT->ProcessLine(".q;");
}
void bfcread_tagsBranch( 
  const char *MainFile="/afs/rhic.bnl.gov/star/data/samples/gstar.tags.root",
  Int_t printEvent=1,
  const char *fname="qa_tags.out",
  Int_t fullPrint=0) 
{
  // start timer
  TStopwatch timer;
  timer.Start();

  cout << endl << endl;
  cout << " bfcread_tagsBranch.C: input file  = " << MainFile << endl;
  cout << " bfcread_tagsBranch.C: print event # " << printEvent << endl;
  cout << " bfcread_tagsBranch.C: output file = " << fname << endl;
  cout << " bfcread_tagsBranch.C: full printout = " << fullPrint << endl;
  cout << endl;

  ofstream fout(fname);

  fout << endl << endl;
  fout << " bfcread_tagsBranch.C: input file  = " << MainFile << endl;
  fout << " bfcread_tagsBranch.C: print evt#  = " << printEvent << endl;
  fout << " bfcread_tagsBranch.C: output file = " << fname << endl;
  fout << " bfcread_tagsBranch.C: full printout = " << fullPrint << endl;
  fout << endl;

  TFile *file = TFile::Open(MainFile);
  TTree *tree = (TTree*)file->Get("Tag");

  cout <<" read file: " << file->GetName() << endl << endl;

  Int_t nEntries = tree->GetEntries();
  cout << " Total # events  = " << nEntries << endl;

  TObjArray *leaves = tree->GetListOfLeaves();
  Int_t nLeaves = leaves->GetEntriesFast();

  cout << "  Total # leaves  = " << nLeaves << endl;

  TString *tName = new TString(" ");
  TNamed *tableName=0;
  TObjArray *tagTable = new TObjArray;
  Int_t tableCount = 0;
  Int_t *tableIndex = new Int_t[nLeaves];
  Int_t tagCount = 0;

  TBranch *branch=0;
  TLeaf *leaf=0;
  Int_t ndim =0;

//count number of tag tables encoded in the TTree branch names
  for (Int_t l=0;l<nLeaves;l++) {
    leaf = (TLeaf*)leaves->UncheckedAt(l);
    tagCount+=leaf->GetNdata();
    branch = leaf->GetBranch();
      cout << "leaf #  " << l << "  br name = " <<  
                                     branch->GetName() << endl;
    //new tag table name
    if ( strstr(branch->GetName(), tName->Data()) == 0 ) {
      tName = new TString(branch->GetName());
      tName->Resize(tName->Index("."));
      //the tableName is encoded in the branch Name before the "."
      tableName = new TNamed(tName->Data(),"Tag");
      tagTable->AddLast(tableName);
      tableCount++;
    }
    tableIndex[l]=tableCount-1;
  }

  cout << endl << "  Total num tables(branches),tags = " 
              << tableCount << "   " << tagCount << endl << endl;

  Int_t *countTagsTable = new Int_t[tableCount];
  Int_t *countLeavesTable = new Int_t[tableCount];
  Float_t *sumTagsLeaf = new Float_t[nLeaves];
  Int_t *countTagsLeaf = new Int_t[nLeaves];

// Now loop over leaves (to get values of tags)

   Int_t setBranch = -1;
   Int_t nowBranch = -1;

   for (Int_t l=0;l<nLeaves;l++) {

      leaf = (TLeaf*)leaves->UncheckedAt(l);
      branch = leaf->GetBranch();
      ndim = leaf->GetNdata();

      nowBranch = tableIndex[l];

      //cout << " nowbranch, setBranch = " << 
      //  nowBranch << ", "<< setBranch << endl;

      Float_t RtableIndex=tableIndex[l];

      if (nowBranch !=  setBranch){ 
          setBranch=nowBranch;
          cout << " QAInfo: branch ";
            cout.width(2);
            cout << tableIndex[l] << " = ";
            cout.width(10);
            cout << ((TNamed*)tagTable->UncheckedAt(tableIndex[l]))->GetName();
            cout << endl;
          fout << " QAInfo: branch ";
            fout.width(2);
            fout << RtableIndex << " = ";
            fout.width(10);
            fout << ((TNamed*)tagTable->UncheckedAt(tableIndex[l]))->GetName();
            fout << endl;
      }

      countTagsTable[tableIndex[l]]+=leaf->GetNdata();
      countLeavesTable[tableIndex[l]]++;
      countTagsLeaf[l]+=ndim;

      Float_t Rl=l;
      Float_t Rndim=ndim;
      cout << " QAInfo:     leaf ";
        cout.width(3);
        cout << l << " has ";
        cout.width(1);
        cout << ndim << " tags:";
        cout << endl;
      fout << " QAInfo:     leaf ";
        fout.width(3);
        fout << Rl << " has ";
        fout.width(1);
        fout << Rndim << " tags:";
        fout << endl;

//  loop over all events in each leaf

      for (Int_t nev=0; nev<nEntries; nev++) {
	branch->GetEntry(nev);

//  loop over all tags in each leaf for each event

	for (Int_t itag=0;itag<ndim;itag++) {

          Int_t ik = nev+1;
	  if (ik==printEvent) {

	     cout << " QAInfo:         " << leaf->GetName();
	     if (ndim>1) cout << '['<<itag<<']';
             cout << " = " << leaf->GetValue(itag) << endl; 	

	     fout << " QAInfo:         " << leaf->GetName();
	     if (ndim>1) fout << '['<<itag<<']';
             fout << " = " << leaf->GetValue(itag) << endl; 	  
	  }

          sumTagsLeaf[l]+=leaf->GetValue(itag);

	} 	
      }
    }
    cout << endl  << endl;
    fout << endl  << endl;


    if (fullPrint == 1){
// loop over leaves again for printout at end
     for (Int_t m=0; m<nLeaves; m++){

       leaf = (TLeaf*)leaves->UncheckedAt(m);
       branch = leaf->GetBranch();
       ndim = leaf->GetNdata();

      cout << " QAInfo: branch ";
        cout.width(2);
        cout << tableIndex[m] << " = ";
        cout.width(10);
        cout << ((TNamed*)tagTable->UncheckedAt(tableIndex[m]))->GetName();
        cout << ", leaf ";
        cout.width(3);
        cout << m << " = ";
        cout.width(24);
        cout << leaf->GetName();
        cout << ", #tags = ";     
        cout.width(1);
        cout << ndim;
        cout << endl;

	Float_t RtableIndex=tableIndex[m];
        Float_t Rm=m;
        Float_t Rndim=ndim;
      fout << " QAInfo: branch ";
        fout.width(2);
        fout << RtableIndex << " = ";
        fout.width(10);
        fout << ((TNamed*)tagTable->UncheckedAt(tableIndex[m]))->GetName();
        fout << ", leaf ";
        fout.width(3);
        fout << Rm << " = ";
        fout.width(24);
        fout << leaf->GetName();
        fout << ", #tags = ";     
        fout.width(1);
        fout << Rndim;
        fout << endl;

     }
    }
     cout << endl  << endl;
     fout << endl  << endl;



// loop over leaves again for printout at end of averages
     cout << " QAInfo: each leaf's avg over all tags,evts: " << endl;
     fout << " QAInfo: each leaf's avg over all tags,evts: " << endl;

     for (Int_t m=0; m<nLeaves; m++){

      leaf = (TLeaf*)leaves->UncheckedAt(m);

      sumTagsLeaf[m]/=countTagsLeaf[m]*nEntries;

      cout << " QAInfo: avg leaf #";
        cout.width(2);
        cout << m << ", ";
        cout.width(23);
        cout << leaf->GetName() << " = ";
        cout.width(12);
        cout << sumTagsLeaf[m];
        cout << endl;

	Float_t Rm=m;
      fout << " QAInfo: avg leaf #";
        fout.width(2);
        fout << Rm << ", ";
        fout.width(23);
        fout << leaf->GetName() << " = ";
        fout.width(12);
        fout << sumTagsLeaf[m];
        fout << endl;

     }
     cout << endl  << endl;
     fout << endl  << endl;



// loop over all tables
     for (Int_t m=0; m<tableCount; m++){

        cout << " QAInfo: branch(table) ";
	  cout.width(10);
	  cout << ((TNamed*)tagTable->UncheckedAt(m))->GetName() << " has ";
	  cout.width(4);
	  cout << countLeavesTable[m] << " leaves,";
	  cout.width(4);
	  cout << countTagsTable[m] << " tags" << endl;

	  Float_t RcountLeavesTable=countLeavesTable[m];
          Float_t RcountTagsTable=countTagsTable[m];
        fout << " QAInfo: branch(table) ";
	  fout.width(10);
	  fout << ((TNamed*)tagTable->UncheckedAt(m))->GetName() << " has ";
	  fout.width(4);
	  fout << RcountLeavesTable << " leaves,";
	  fout.width(4);
	  fout << RcountTagsTable << " tags" << endl;

     }
     cout << endl  << endl;
     fout << endl  << endl;


     Float_t RnEntries=nEntries;
     Float_t RtableCount=tableCount; 
     Float_t RnLeaves=nLeaves; 
     Float_t RtagCount=tagCount; 

     cout << " QAInfo:  tot num events = " << nEntries << endl;
     fout << " QAInfo:  tot num events = " << RnEntries << endl;

     cout << " QAInfo:   tot num branches = " << tableCount << endl;
     fout << " QAInfo:   tot num branches = " << RtableCount << endl;

     cout << " QAInfo:   tot num leaves = " << nLeaves << endl;
     fout << " QAInfo:   tot num leaves = " << RnLeaves << endl;

     cout << " QAInfo:   tot num tags = " << tagCount << endl;
     fout << " QAInfo:   tot num tags = " << RtagCount << endl;


  // stop timer and print results
  timer.Stop();
  cout<< endl << endl <<"RealTime="<<timer.RealTime()<<
       " seconds, CpuTime="<<timer.CpuTime()<<" seconds"<<endl;

  //cleanup
  file->Close();
  fout.close();
}
Example #10
0
int writentuple_pp(char *ksp="ppJet40")
{
    
    timer.Start();
    
    //LoadLib();
    
    TString inname="";
    if(strcmp(ksp,"ppJet40")==0)inname = "/hadoop/store/user/belt/hiForest2/PP2013_HiForest_PromptReco_JSon_Jet40Jet60_ppTrack_forestv84.root";
    else if(strcmp(ksp,"ppJet80")==0)inname = "/hadoop/store/user/belt/hiForest2/PP2013_HiForest_PromptReco_JsonPP_Jet80_PPReco_forestv82.root";
    
    //! Load Lib
    //gSystem->Load("/afs/cern.ch/user/p/pawan/scratch0/CMSSW_6_2_0/src/work/pPb/HiForest/V3/hiForest_h.so");
    
    //! Define the input file and HiForest
    //! CMSSW_5_3_3
    HiForest *c = new HiForest(inname,Form("Forest%s",ksp),cPP);
    cout<<"Loaded the hiforest tree : "<<c->GetName()<<endl;
    ShutoffBranches(c);
    
    
    DuplicateEvents dupEvt(inname);
    dupEvt.MakeList();

    //! Output file
    //! HIHighPt
    TFile *fout = new TFile(Form("ntuple_2013_%s.root",ksp),"RECREATE");
    
    std::cout<<"\t"<<std::endl;
    std::cout<<"\t"<<std::endl;
    std::cout<<"**************************************************** "<<std::endl;
    std::cout<<Form("Running for %s ",ksp)<<std::endl;
    std::cout<<Form("pT  cut for %0.3f ",kptrecocut)<<std::endl;
    std::cout<<Form("eta cut for %0.3f ",ketacut)<<std::endl;
    std::cout<<"My hiForest Tree : " <<c->GetName()<<"\t Entries "<<c->GetEntries()<<std::endl;
    std::cout<<"Output file  "<<fout->GetName()<<std::endl;
    std::cout<<"**************************************************** "<<std::endl;
    std::cout<<"\t"<<std::endl;
    std::cout<<"\t"<<std::endl;
    
    //! shut off jet trees
    //c->hasAk2CaloJetTree=0;
    //c->hasAk4CaloJetTree=0;
    //c->hasAk3CaloJetTree=0;
    //c->hasAk5CaloJetTree=0;
    
    c->hasAkPu2CaloJetTree=0;
    c->hasAkPu4CaloJetTree=0;
    c->hasAkPu3CaloJetTree=0;
    //c->hasAkPu5CaloJetTree=0;
    
    //c->hasAk2PFJetTree=0;
    //c->hasAk4PFJetTree=0;
    //c->hasAk5PFJetTree=0;
    
    //c->hasAkPu2PFJetTree=0;
    //c->hasAkPu4PFJetTree=0;
    //c->hasAkPu5PFJetTree=0;
    
    c->hasTrackTree=0;
    
    //! For jets
    Jets *mJets=0;
    Long64_t nentries = c->GetEntries();
    std::cout<<Form("# of entries in TTree for %s : ",ksp)<<nentries<<std::endl;
    
    string jetVars = "";
    jetVars += "evt:run:vz:trig:jet40:jet60:jet80:jet100:ntrk:nrefe:pt:raw:eta:phi:chMax:trkMax:chSum:phSum:neSum";
    TNtuple *ntjet=0;
    ntjet = new TNtuple("ntjet","",jetVars.data());
    
    for (Long64_t ievt=0; ievt<nentries;ievt++) {//! event loop
        //for (Long64_t ievt=0; ievt<100;ievt++) {//! event loop
        //! load the hiForest event
        c->GetEntry(ievt);
        
        if(dupEvt.occurence[ievt] == 2)continue;


        //! events with Single vertex
        bool evSel = false;
        float trig=-9;
        if(strcmp(ksp,"ppJet40")==0){
            evSel = fabs(c->evt.vz)<15. && c->skim.pHBHENoiseFilter  && c->skim.pPAcollisionEventSelectionPA && (c->hlt.HLT_PAJet40_NoJetID_v1 || c->hlt.HLT_PAJet60_NoJetID_v1);
            trig=1;
        }
        else if(strcmp(ksp,"ppJet80")==0){
            evSel = fabs(c->evt.vz)<15. && c->skim.pHBHENoiseFilter  && c->skim.pPAcollisionEventSelectionPA && (c->hlt.HLT_PAJet80_NoJetID_v1 || c->hlt.HLT_PAJet100_NoJetID_v1);
            trig=2;
        }
        if(!evSel)continue;
        
        float pt = -9,raw    = -9,eta    = -9,phi    = -9,chMax  = -9,trkMax=-9,chSum  = -9,phSum  = -9,neSum  = -9,nrefe = 0;

        
        
        float run   = c->evt.run;
        float evt   = c->evt.evt;
        float vz    = c->evt.vz;
        
        float jet40  = c->hlt.HLT_PAJet40_NoJetID_v1;
        float jet60  = c->hlt.HLT_PAJet60_NoJetID_v1;
        float jet80  = c->hlt.HLT_PAJet80_NoJetID_v1;
        float jet100 = c->hlt.HLT_PAJet100_NoJetID_v1;
        
        float ntrk    = c->evt.hiNtracks;
        
        if(ievt%10000==0)std::cout<<" ********** Event # " <<ievt<<"\t Run : "<<run<<std::endl;
        
        mJets = &(c->ak3PF);
	nrefe = mJets->nref;
        /*
        int *ljet = new int[3];
        FindLeadSubLeadJets(mJets,ljet);
        
        int jtLead = -1, jtSubLead = -1, jtThird = -1;
        
        if(ljet[0] >=0 ) jtLead    = ljet[0];
        if(ljet[1] >=0 ) jtSubLead = ljet[1];
        if(ljet[2] >=0 ) jtThird   = ljet[2];
        
        if(jtLead<0)continue;
        
        if(jtLead > -1){
            pt1     = mJets->jtpt[jtLead];
            eta1    = mJets->jteta[jtLead];
            phi1    = mJets->jtphi[jtLead];
            raw1    = mJets->rawpt[jtLead];
            chMax1  = mJets->chargedMax[jtLead];
            chSum1  = mJets->chargedSum[jtLead];
            phSum1  = mJets->photonSum[jtLead];
            neSum1  = mJets->neutralSum[jtLead];
        }
        
        if(jtSubLead > -1){
            pt2     = mJets->jtpt[jtSubLead];
            eta2    = mJets->jteta[jtSubLead];
            phi2    = mJets->jtphi[jtSubLead];
            raw2    = mJets->rawpt[jtSubLead];
            chMax2  = mJets->chargedMax[jtSubLead];
            chSum2  = mJets->chargedSum[jtSubLead];
            phSum2  = mJets->photonSum [jtSubLead];
            neSum2  = mJets->neutralSum[jtSubLead];
        }
        
        if(jtThird > -1){
            pt3     = mJets->jtpt[jtThird];
            eta3    = mJets->jteta[jtThird];
            phi3    = mJets->jtphi[jtThird];
            raw3    = mJets->rawpt[jtThird];
            chMax3  = mJets->chargedMax[jtThird];
            chSum3  = mJets->chargedSum[jtThird];
            phSum3  = mJets->photonSum [jtThird];
            neSum3  = mJets->neutralSum[jtThird];
        }
        */
        for (int i = 0; i<mJets->nref; i++) {
            pt     = mJets->jtpt[i];
            eta    = mJets->jteta[i];
            phi    = mJets->jtphi[i];
            raw    = mJets->rawpt[i];
            chMax  = mJets->chargedMax[i];
            trkMax = mJets->trackMax[i];
            chSum  = mJets->chargedSum[i];
            phSum  = mJets->photonSum[i];
            neSum  = mJets->neutralSum[i];
            
            float jentry[] = {evt,run,vz,trig,jet40,jet60,jet80,jet100,ntrk,nrefe,
			      pt,raw,eta,phi,chMax,trkMax,chSum,phSum,neSum
            };
            
            ntjet->Fill(jentry);
        }
        //delete [] ljet;
    }//! event loop ends
    
    
    //! Write to output file
    fout->cd();
    fout->Write();
    fout->Close();
    
    //! Check
    timer.Stop();
    float rtime  = timer.RealTime();
    float ctime  = timer.CpuTime();
    
    std::cout<<"\t"<<std::endl;
    std::cout<<Form("RealTime=%f seconds, CpuTime=%f seconds",rtime,ctime)<<std::endl;
    std::cout<<"\t"<<std::endl;
    std::cout<<"Good bye : " <<"\t"<<std::endl;
    
    return 0;
}
Example #11
0
//this makes shape plots of MT2 distributions for several VSPT bins for various SM types (W,Z,ttbar,susy,data)
void UTMplots(){

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

TChain *LM6 = new TChain("MassTree");
TChain *WJets = new TChain("MassTree");
TChain *ZJets = new TChain("MassTree");
TChain *TTbar = new TChain("MassTree");
TChain *Data = new TChain("MassTree");

//read in trees
LM6->Add("dcap://t3se01.psi.ch:22125/pnfs/psi.ch/cms/trivcat/store/user/mmasciov/SUSY/MassTrees/MT2_V02-03-02/20130430_8TeV/SUSY-LM6-sftsht-8TeV-pythia6-Summer12-DR53X-PU-S10-START53-V7A-v1/*.root");
WJets->Add("dcap://t3se01.psi.ch:22125/pnfs/psi.ch/cms/trivcat/store/user/mmasciov/SUSY/MassTrees/MT2_V02-03-02/20130318_8TeV/WJetsToLNu-HT-400ToInf-8TeV-madgraph-Summer12-DR53X-PU-S10-START53-V7A-v1/*.root");
WJets->Add("dcap://t3se01.psi.ch:22125/pnfs/psi.ch/cms/trivcat/store/user/mmasciov/SUSY/MassTrees/MT2_V02-03-02/20130318_8TeV/WJetsToLNu-HT-400ToInf-8TeV-madgraph-v2-Summer12-DR53X-PU-S10-START53-V7A-v1/*.root");
ZJets->Add("dcap://t3se01.psi.ch:22125/pnfs/psi.ch/cms/trivcat/store/user/haweber/SUSY/MassTrees/MT2_V02-03-02/20130318_8TeV/ZJetsToNuNu-400-HT-inf-TuneZ2Star-8TeV-madgraph-Summer12-DR53X-PU-S10-START53-V7A-v1/*.root");
ZJets->Add("dcap://t3se01.psi.ch:22125/pnfs/psi.ch/cms/trivcat/store/user/haweber/SUSY/MassTrees/MT2_V02-03-02/20130318_8TeV/ZJetsToNuNu-400-HT-inf-TuneZ2Star-8TeV-madgraph-ext-Summer12-DR53X-PU-S10-START53-V7A-v1/*.root");
TTbar->Add("dcap://t3se01.psi.ch:22125/pnfs/psi.ch/cms/trivcat/store/user/casal/SUSY/MassTrees/MT2_V02-03-02/20130503_8TeV/TTJets-SemiLeptMGDecays-8TeV-madgraph-tauola-Summer12-DR53X-PU-S10-START53-V7C-v1/*.root");
int nd = Data->Add("dcap://t3se01.psi.ch:22125/pnfs/psi.ch/cms/trivcat/store/user/casal/SUSY/MassTrees/MT2_V02-03-02/20130318_8TeV/HT-Run2012A-13Jul2012-v1-2/*.root");
nd += Data->Add("dcap://t3se01.psi.ch:22125/pnfs/psi.ch/cms/trivcat/store/user/casal/SUSY/MassTrees/MT2_V02-03-02/20130318_8TeV/HT-Run2012A-recover-06Aug2012-v1-2/*.root");
nd += Data->Add("dcap://t3se01.psi.ch:22125/pnfs/psi.ch/cms/trivcat/store/user/casal/SUSY/MassTrees/MT2_V02-03-02/20130318_8TeV/JetHT-Run2012B-13Jul2012-v1-2/*.root");
nd += Data->Add("dcap://t3se01.psi.ch:22125/pnfs/psi.ch/cms/trivcat/store/user/casal/SUSY/MassTrees/MT2_V02-03-02/20130318_8TeV/JetHT-Run2012C-24Aug2012-v2-2/*.root");
nd += Data->Add("dcap://t3se01.psi.ch:22125/pnfs/psi.ch/cms/trivcat/store/user/casal/SUSY/MassTrees/MT2_V02-03-02/20130318_8TeV/JetHT-Run2012C-EcalRecover-11Dec2012-v1-2/*.root");
nd += Data->Add("dcap://t3se01.psi.ch:22125/pnfs/psi.ch/cms/trivcat/store/user/casal/SUSY/MassTrees/MT2_V02-03-02/20130318_8TeV/JetHT-Run2012C-PromptReco-v2-3/*.root");
nd += Data->Add("dcap://t3se01.psi.ch:22125/pnfs/psi.ch/cms/trivcat/store/user/casal/SUSY/MassTrees/MT2_V02-03-02/20130318_8TeV/JetHT-Run2012D-PromptReco-v1-3/*.root");
cout << nd << endl;

//define histograms
TH1D *LM6VSPT0   = new TH1D("LM6VSPT0"  ,"", 75, 0, 750); LM6VSPT0  ->Sumw2(); LM6VSPT0  ->SetLineColor(kBlack);  LM6VSPT0  ->SetLineWidth(2);
TH1D *LM6VSPT20  = new TH1D("LM6VSPT20" ,"", 75, 0, 750); LM6VSPT20 ->Sumw2(); LM6VSPT20 ->SetLineColor(kRed);    LM6VSPT20 ->SetLineWidth(2);
TH1D *LM6VSPT30  = new TH1D("LM6VSPT30" ,"", 75, 0, 750); LM6VSPT30 ->Sumw2(); LM6VSPT30 ->SetLineColor(kGreen);  LM6VSPT30 ->SetLineWidth(2);
TH1D *LM6VSPT40  = new TH1D("LM6VSPT40" ,"", 75, 0, 750); LM6VSPT40 ->Sumw2(); LM6VSPT40 ->SetLineColor(kBlue);   LM6VSPT40 ->SetLineWidth(2);
TH1D *LM6VSPT50  = new TH1D("LM6VSPT50" ,"", 75, 0, 750); LM6VSPT50 ->Sumw2(); LM6VSPT50 ->SetLineColor(kYellow); LM6VSPT50 ->SetLineWidth(2);
TH1D *LM6VSPT70  = new TH1D("LM6VSPT70" ,"", 75, 0, 750); LM6VSPT70 ->Sumw2(); LM6VSPT70 ->SetLineColor(kMagenta);LM6VSPT70 ->SetLineWidth(2);
TH1D *LM6VSPT100 = new TH1D("LM6VSPT100","", 75, 0, 750); LM6VSPT100->Sumw2(); LM6VSPT100->SetLineColor(kCyan);   LM6VSPT100->SetLineWidth(2);
TH1D *WJetsVSPT0   = new TH1D("WJetsVSPT0"  ,"", 75, 0, 750); WJetsVSPT0  ->Sumw2(); WJetsVSPT0  ->SetLineColor(kBlack);   WJetsVSPT0  ->SetLineWidth(2);
TH1D *WJetsVSPT20  = new TH1D("WJetsVSPT20" ,"", 75, 0, 750); WJetsVSPT20 ->Sumw2(); WJetsVSPT20 ->SetLineColor(kRed);     WJetsVSPT20 ->SetLineWidth(2);
TH1D *WJetsVSPT30  = new TH1D("WJetsVSPT30" ,"", 75, 0, 750); WJetsVSPT30 ->Sumw2(); WJetsVSPT30 ->SetLineColor(kGreen);   WJetsVSPT30 ->SetLineWidth(2);
TH1D *WJetsVSPT40  = new TH1D("WJetsVSPT40" ,"", 75, 0, 750); WJetsVSPT40 ->Sumw2(); WJetsVSPT40 ->SetLineColor(kBlue);    WJetsVSPT40 ->SetLineWidth(2);
TH1D *WJetsVSPT50  = new TH1D("WJetsVSPT50" ,"", 75, 0, 750); WJetsVSPT50 ->Sumw2(); WJetsVSPT50 ->SetLineColor(kYellow);  WJetsVSPT50 ->SetLineWidth(2);
TH1D *WJetsVSPT70  = new TH1D("WJetsVSPT70" ,"", 75, 0, 750); WJetsVSPT70 ->Sumw2(); WJetsVSPT70 ->SetLineColor(kMagenta); WJetsVSPT70 ->SetLineWidth(2);
TH1D *WJetsVSPT100 = new TH1D("WJetsVSPT100","", 75, 0, 750); WJetsVSPT100->Sumw2(); WJetsVSPT100->SetLineColor(kCyan);    WJetsVSPT100->SetLineWidth(2);
TH1D *ZJetsVSPT0   = new TH1D("ZJetsVSPT0"  ,"", 75, 0, 750); ZJetsVSPT0  ->Sumw2(); ZJetsVSPT0  ->SetLineColor(kBlack);   ZJetsVSPT0  ->SetLineWidth(2);
TH1D *ZJetsVSPT20  = new TH1D("ZJetsVSPT20" ,"", 75, 0, 750); ZJetsVSPT20 ->Sumw2(); ZJetsVSPT20 ->SetLineColor(kRed);     ZJetsVSPT20 ->SetLineWidth(2);
TH1D *ZJetsVSPT30  = new TH1D("ZJetsVSPT30" ,"", 75, 0, 750); ZJetsVSPT30 ->Sumw2(); ZJetsVSPT30 ->SetLineColor(kGreen);   ZJetsVSPT30 ->SetLineWidth(2);
TH1D *ZJetsVSPT40  = new TH1D("ZJetsVSPT40" ,"", 75, 0, 750); ZJetsVSPT40 ->Sumw2(); ZJetsVSPT40 ->SetLineColor(kBlue);    ZJetsVSPT40 ->SetLineWidth(2);
TH1D *ZJetsVSPT50  = new TH1D("ZJetsVSPT50" ,"", 75, 0, 750); ZJetsVSPT50 ->Sumw2(); ZJetsVSPT50 ->SetLineColor(kYellow);  ZJetsVSPT50 ->SetLineWidth(2);
TH1D *ZJetsVSPT70  = new TH1D("ZJetsVSPT70" ,"", 75, 0, 750); ZJetsVSPT70 ->Sumw2(); ZJetsVSPT70 ->SetLineColor(kMagenta); ZJetsVSPT70 ->SetLineWidth(2);
TH1D *ZJetsVSPT100 = new TH1D("ZJetsVSPT100","", 75, 0, 750); ZJetsVSPT100->Sumw2(); ZJetsVSPT100->SetLineColor(kCyan);    ZJetsVSPT100->SetLineWidth(2);
TH1D *TTbarVSPT0   = new TH1D("TTbarVSPT0"  ,"", 75, 0, 750); TTbarVSPT0  ->Sumw2(); TTbarVSPT0  ->SetLineColor(kBlack);   TTbarVSPT0  ->SetLineWidth(2);
TH1D *TTbarVSPT20  = new TH1D("TTbarVSPT20" ,"", 75, 0, 750); TTbarVSPT20 ->Sumw2(); TTbarVSPT20 ->SetLineColor(kRed);     TTbarVSPT20 ->SetLineWidth(2);
TH1D *TTbarVSPT30  = new TH1D("TTbarVSPT30" ,"", 75, 0, 750); TTbarVSPT30 ->Sumw2(); TTbarVSPT30 ->SetLineColor(kGreen);   TTbarVSPT30 ->SetLineWidth(2);
TH1D *TTbarVSPT40  = new TH1D("TTbarVSPT40" ,"", 75, 0, 750); TTbarVSPT40 ->Sumw2(); TTbarVSPT40 ->SetLineColor(kBlue);    TTbarVSPT40 ->SetLineWidth(2);
TH1D *TTbarVSPT50  = new TH1D("TTbarVSPT50" ,"", 75, 0, 750); TTbarVSPT50 ->Sumw2(); TTbarVSPT50 ->SetLineColor(kYellow);  TTbarVSPT50 ->SetLineWidth(2);
TH1D *TTbarVSPT70  = new TH1D("TTbarVSPT70" ,"", 75, 0, 750); TTbarVSPT70 ->Sumw2(); TTbarVSPT70 ->SetLineColor(kMagenta); TTbarVSPT70 ->SetLineWidth(2);
TH1D *TTbarVSPT100 = new TH1D("TTbarVSPT100","", 75, 0, 750); TTbarVSPT100->Sumw2(); TTbarVSPT100->SetLineColor(kCyan);    TTbarVSPT100->SetLineWidth(2);
//small MinDPhi
TH1D *DataQCDVSPT0   = new TH1D("DataQCDVSPT0"  ,"", 75, 0, 750); DataQCDVSPT0  ->Sumw2(); DataQCDVSPT0  ->SetLineColor(kBlack);  DataQCDVSPT0  ->SetLineWidth(2);
TH1D *DataQCDVSPT20  = new TH1D("DataQCDVSPT20" ,"", 75, 0, 750); DataQCDVSPT20 ->Sumw2(); DataQCDVSPT20 ->SetLineColor(kRed);    DataQCDVSPT20 ->SetLineWidth(2);
TH1D *DataQCDVSPT30  = new TH1D("DataQCDVSPT30" ,"", 75, 0, 750); DataQCDVSPT30 ->Sumw2(); DataQCDVSPT30 ->SetLineColor(kGreen);  DataQCDVSPT30 ->SetLineWidth(2);
TH1D *DataQCDVSPT40  = new TH1D("DataQCDVSPT40" ,"", 75, 0, 750); DataQCDVSPT40 ->Sumw2(); DataQCDVSPT40 ->SetLineColor(kBlue);   DataQCDVSPT40 ->SetLineWidth(2);
TH1D *DataQCDVSPT50  = new TH1D("DataQCDVSPT50" ,"", 75, 0, 750); DataQCDVSPT50 ->Sumw2(); DataQCDVSPT50 ->SetLineColor(kYellow); DataQCDVSPT50 ->SetLineWidth(2);
TH1D *DataQCDVSPT70  = new TH1D("DataQCDVSPT70" ,"", 75, 0, 750); DataQCDVSPT70 ->Sumw2(); DataQCDVSPT70 ->SetLineColor(kMagenta);DataQCDVSPT70 ->SetLineWidth(2);
TH1D *DataQCDVSPT100 = new TH1D("DataQCDVSPT100","", 75, 0, 750); DataQCDVSPT100->Sumw2(); DataQCDVSPT100->SetLineColor(kCyan);   DataQCDVSPT100->SetLineWidth(2);
//1lep,0b
TH1D *DataWVSPT0   = new TH1D("DataWVSPT0"  ,"", 75, 0, 750); DataWVSPT0  ->Sumw2(); DataWVSPT0  ->SetLineColor(kBlack);  DataWVSPT0  ->SetLineWidth(2);
TH1D *DataWVSPT20  = new TH1D("DataWVSPT20" ,"", 75, 0, 750); DataWVSPT20 ->Sumw2(); DataWVSPT20 ->SetLineColor(kRed);    DataWVSPT20 ->SetLineWidth(2);
TH1D *DataWVSPT30  = new TH1D("DataWVSPT30" ,"", 75, 0, 750); DataWVSPT30 ->Sumw2(); DataWVSPT30 ->SetLineColor(kGreen);  DataWVSPT30 ->SetLineWidth(2);
TH1D *DataWVSPT40  = new TH1D("DataWVSPT40" ,"", 75, 0, 750); DataWVSPT40 ->Sumw2(); DataWVSPT40 ->SetLineColor(kBlue);   DataWVSPT40 ->SetLineWidth(2);
TH1D *DataWVSPT50  = new TH1D("DataWVSPT50" ,"", 75, 0, 750); DataWVSPT50 ->Sumw2(); DataWVSPT50 ->SetLineColor(kYellow); DataWVSPT50 ->SetLineWidth(2);
TH1D *DataWVSPT70  = new TH1D("DataWVSPT70" ,"", 75, 0, 750); DataWVSPT70 ->Sumw2(); DataWVSPT70 ->SetLineColor(kMagenta);DataWVSPT70 ->SetLineWidth(2);
TH1D *DataWVSPT100 = new TH1D("DataWVSPT100","", 75, 0, 750); DataWVSPT100->Sumw2(); DataWVSPT100->SetLineColor(kCyan);   DataWVSPT100->SetLineWidth(2);
//1lep,1b 
TH1D *DataTopVSPT0   = new TH1D("DataTopVSPT0"  ,"", 75, 0, 750); DataTopVSPT0  ->Sumw2(); DataTopVSPT0  ->SetLineColor(kBlack);  DataTopVSPT0  ->SetLineWidth(2);
TH1D *DataTopVSPT20  = new TH1D("DataTopVSPT20" ,"", 75, 0, 750); DataTopVSPT20 ->Sumw2(); DataTopVSPT20 ->SetLineColor(kRed);    DataTopVSPT20 ->SetLineWidth(2);
TH1D *DataTopVSPT30  = new TH1D("DataTopVSPT30" ,"", 75, 0, 750); DataTopVSPT30 ->Sumw2(); DataTopVSPT30 ->SetLineColor(kGreen);  DataTopVSPT30 ->SetLineWidth(2);
TH1D *DataTopVSPT40  = new TH1D("DataTopVSPT40" ,"", 75, 0, 750); DataTopVSPT40 ->Sumw2(); DataTopVSPT40 ->SetLineColor(kBlue);   DataTopVSPT40 ->SetLineWidth(2);
TH1D *DataTopVSPT50  = new TH1D("DataTopVSPT50" ,"", 75, 0, 750); DataTopVSPT50 ->Sumw2(); DataTopVSPT50 ->SetLineColor(kYellow); DataTopVSPT50 ->SetLineWidth(2);
TH1D *DataTopVSPT70  = new TH1D("DataTopVSPT70" ,"", 75, 0, 750); DataTopVSPT70 ->Sumw2(); DataTopVSPT70 ->SetLineColor(kMagenta);DataTopVSPT70 ->SetLineWidth(2);
TH1D *DataTopVSPT100 = new TH1D("DataTopVSPT100","", 75, 0, 750); DataTopVSPT100->Sumw2(); DataTopVSPT100->SetLineColor(kCyan);   DataTopVSPT100->SetLineWidth(2);
//highDeltaPhi,0b 
TH1D *DataZVSPT0   = new TH1D("DataZVSPT0"  ,"", 75, 0, 750); DataZVSPT0  ->Sumw2(); DataZVSPT0  ->SetLineColor(kBlack);  DataZVSPT0  ->SetLineWidth(2);
TH1D *DataZVSPT20  = new TH1D("DataZVSPT20" ,"", 75, 0, 750); DataZVSPT20 ->Sumw2(); DataZVSPT20 ->SetLineColor(kRed);    DataZVSPT20 ->SetLineWidth(2);
TH1D *DataZVSPT30  = new TH1D("DataZVSPT30" ,"", 75, 0, 750); DataZVSPT30 ->Sumw2(); DataZVSPT30 ->SetLineColor(kGreen);  DataZVSPT30 ->SetLineWidth(2);
TH1D *DataZVSPT40  = new TH1D("DataZVSPT40" ,"", 75, 0, 750); DataZVSPT40 ->Sumw2(); DataZVSPT40 ->SetLineColor(kBlue);   DataZVSPT40 ->SetLineWidth(2);
TH1D *DataZVSPT50  = new TH1D("DataZVSPT50" ,"", 75, 0, 750); DataZVSPT50 ->Sumw2(); DataZVSPT50 ->SetLineColor(kYellow); DataZVSPT50 ->SetLineWidth(2);
TH1D *DataZVSPT70  = new TH1D("DataZVSPT70" ,"", 75, 0, 750); DataZVSPT70 ->Sumw2(); DataZVSPT70 ->SetLineColor(kMagenta);DataZVSPT70 ->SetLineWidth(2);
TH1D *DataZVSPT100 = new TH1D("DataZVSPT100","", 75, 0, 750); DataZVSPT100->Sumw2(); DataZVSPT100->SetLineColor(kCyan);   DataZVSPT100->SetLineWidth(2);

//fill histograms
gROOT->cd();
cout << "LM6VSPT0" << endl;
LM6->Draw("misc.MT2>>LM6VSPT0",  "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=0&&misc.Vectorsumpt<20","goff");
cout << "LM6VSPT20" << endl;
LM6->Draw("misc.MT2>>LM6VSPT20", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=20&&misc.Vectorsumpt<30","goff");
cout << "LM6VSPT30" << endl;
LM6->Draw("misc.MT2>>LM6VSPT30", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=30&&misc.Vectorsumpt<40","goff");
cout << "LM6VSPT40" << endl;
LM6->Draw("misc.MT2>>LM6VSPT40", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=40&&misc.Vectorsumpt<50","goff");
cout << "LM6VSPT50" << endl;
LM6->Draw("misc.MT2>>LM6VSPT50", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=50&&misc.Vectorsumpt<70","goff");
cout << "LM6VSPT70" << endl;
LM6->Draw("misc.MT2>>LM6VSPT70", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=70&&misc.Vectorsumpt<100","goff");
cout << "LM6VSPT100" << endl;
LM6->Draw("misc.MT2>>LM6VSPT100","NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=100","goff");

cout << "WJetsVSPT0" << endl;
WJets->Draw("misc.MT2>>WJetsVSPT0",  "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=0&&misc.Vectorsumpt<20","goff");
cout << "WJetsVSPT20" << endl;
WJets->Draw("misc.MT2>>WJetsVSPT20", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=20&&misc.Vectorsumpt<30","goff");
cout << "WJetsVSPT30" << endl;
WJets->Draw("misc.MT2>>WJetsVSPT30", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=30&&misc.Vectorsumpt<40","goff");
cout << "WJetsVSPT40" << endl;
WJets->Draw("misc.MT2>>WJetsVSPT40", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=40&&misc.Vectorsumpt<50","goff");
cout << "WJetsVSPT50" << endl;
WJets->Draw("misc.MT2>>WJetsVSPT50", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=50&&misc.Vectorsumpt<70","goff");
cout << "WJetsVSPT70" << endl;
WJets->Draw("misc.MT2>>WJetsVSPT70", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=70&&misc.Vectorsumpt<100","goff");
cout << "WJetsVSPT100" << endl;
WJets->Draw("misc.MT2>>WJetsVSPT100","NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=100","goff");

cout << "ZJetsVSPT0" << endl;
ZJets->Draw("misc.MT2>>ZJetsVSPT0",  "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=0&&misc.Vectorsumpt<20","goff");
cout << "ZJetsVSPT20" << endl;
ZJets->Draw("misc.MT2>>ZJetsVSPT20", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=20&&misc.Vectorsumpt<30","goff");
cout << "ZJetsVSPT30" << endl;
ZJets->Draw("misc.MT2>>ZJetsVSPT30", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=30&&misc.Vectorsumpt<40","goff");
cout << "ZJetsVSPT40" << endl;
ZJets->Draw("misc.MT2>>ZJetsVSPT40", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=40&&misc.Vectorsumpt<50","goff");
cout << "ZJetsVSPT50" << endl;
ZJets->Draw("misc.MT2>>ZJetsVSPT50", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=50&&misc.Vectorsumpt<70","goff");
cout << "ZJetsVSPT70" << endl;
ZJets->Draw("misc.MT2>>ZJetsVSPT70", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=70&&misc.Vectorsumpt<100","goff");
cout << "ZJetsVSPT100" << endl;
ZJets->Draw("misc.MT2>>ZJetsVSPT100","NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=100","goff");

cout << "TTbarVSPT0" << endl;
TTbar->Draw("misc.MT2>>TTbarVSPT0",  "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=0&&misc.Vectorsumpt<20","goff");
cout << "TTbarVSPT20" << endl;
TTbar->Draw("misc.MT2>>TTbarVSPT20", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=20&&misc.Vectorsumpt<30","goff");
cout << "TTbarVSPT30" << endl;
TTbar->Draw("misc.MT2>>TTbarVSPT30", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=30&&misc.Vectorsumpt<40","goff");
cout << "TTbarVSPT40" << endl;
TTbar->Draw("misc.MT2>>TTbarVSPT40", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=40&&misc.Vectorsumpt<50","goff");
cout << "TTbarVSPT50" << endl;
TTbar->Draw("misc.MT2>>TTbarVSPT50", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=50&&misc.Vectorsumpt<70","goff");
cout << "TTbarVSPT70" << endl;
TTbar->Draw("misc.MT2>>TTbarVSPT70", "NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=70&&misc.Vectorsumpt<100","goff");
cout << "TTbarVSPT100" << endl;
TTbar->Draw("misc.MT2>>TTbarVSPT100","NJetsIDLoose40>=2&&misc.HT>450&&misc.MET>30&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.Vectorsumpt>=100","goff");

cout << "DataQCDVSPT0" << endl;
Data->Draw("misc.MT2>>DataQCDVSPT0",  "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40<0.2&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=0&&misc.Vectorsumpt<20","goff");
cout << "DataQCDVSPT20" << endl;
Data->Draw("misc.MT2>>DataQCDVSPT20", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40<0.2&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=20&&misc.Vectorsumpt<30","goff");
cout << "DataQCDVSPT30" << endl;
Data->Draw("misc.MT2>>DataQCDVSPT30", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40<0.2&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=30&&misc.Vectorsumpt<40","goff");
cout << "DataQCDVSPT40" << endl;
Data->Draw("misc.MT2>>DataQCDVSPT40", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40<0.2&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=40&&misc.Vectorsumpt<50","goff");
cout << "DataQCDVSPT50" << endl;
Data->Draw("misc.MT2>>DataQCDVSPT50", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40<0.2&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=50&&misc.Vectorsumpt<70","goff");
cout << "DataQCDVSPT70" << endl;
Data->Draw("misc.MT2>>DataQCDVSPT70", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40<0.2&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=70&&misc.Vectorsumpt<100","goff");
cout << "DataQCDVSPT100" << endl;
Data->Draw("misc.MT2>>DataQCDVSPT100","NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40<0.2&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=100","goff");

cout << "DataZVSPT0" << endl;
Data->Draw("misc.MT2>>DataZVSPT0",  "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM==0&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=0&&misc.Vectorsumpt<20","goff");
cout << "DataZVSPT20" << endl;
Data->Draw("misc.MT2>>DataZVSPT20", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM==0&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=20&&misc.Vectorsumpt<30","goff");
cout << "DataZVSPT30" << endl;
Data->Draw("misc.MT2>>DataZVSPT30", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM==0&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=30&&misc.Vectorsumpt<40","goff");
cout << "DataZVSPT40" << endl;
Data->Draw("misc.MT2>>DataZVSPT40", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM==0&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=40&&misc.Vectorsumpt<50","goff");
cout << "DataZVSPT50" << endl;
Data->Draw("misc.MT2>>DataZVSPT50", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM==0&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=50&&misc.Vectorsumpt<70","goff");
cout << "DataZVSPT70" << endl;
Data->Draw("misc.MT2>>DataZVSPT70", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM==0&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=70&&misc.Vectorsumpt<100","goff");
cout << "DataZVSPT100" << endl;
Data->Draw("misc.MT2>>DataZVSPT100","NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&NEles==0&&NMuons==0&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM==0&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=100","goff");

cout << "DataWVSPT0" << endl;
Data->Draw("misc.MT2>>DataWVSPT0",  "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&(NEles+NMuons)==1&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM==0&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=0&&misc.Vectorsumpt<20","goff");
cout << "DataWVSPT20" << endl;
Data->Draw("misc.MT2>>DataWVSPT20", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&(NEles+NMuons)==1&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM==0&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=20&&misc.Vectorsumpt<30","goff");
cout << "DataWVSPT30" << endl;
Data->Draw("misc.MT2>>DataWVSPT30", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&(NEles+NMuons)==1&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM==0&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=30&&misc.Vectorsumpt<40","goff");
cout << "DataWVSPT40" << endl;
Data->Draw("misc.MT2>>DataWVSPT40", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&(NEles+NMuons)==1&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM==0&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=40&&misc.Vectorsumpt<50","goff");
cout << "DataWVSPT50" << endl;
Data->Draw("misc.MT2>>DataWVSPT50", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&(NEles+NMuons)==1&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM==0&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=50&&misc.Vectorsumpt<70","goff");
cout << "DataWVSPT70" << endl;
Data->Draw("misc.MT2>>DataWVSPT70", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&(NEles+NMuons)==1&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM==0&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=70&&misc.Vectorsumpt<100","goff");
cout << "DataWVSPT100" << endl;
Data->Draw("misc.MT2>>DataWVSPT100","NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&(NEles+NMuons)==1&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM==0&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=100","goff");

cout << "DataWVSPT0" << endl;
Data->Draw("misc.MT2>>DataTopVSPT0",  "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&(NEles+NMuons)==1&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM>=1&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=0&&misc.Vectorsumpt<20","goff");
cout << "DataTopVSPT20" << endl;
Data->Draw("misc.MT2>>DataTopVSPT20", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&(NEles+NMuons)==1&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM>=1&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=20&&misc.Vectorsumpt<30","goff");
cout << "DataTopVSPT30" << endl;
Data->Draw("misc.MT2>>DataTopVSPT30", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&(NEles+NMuons)==1&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM>=1&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=30&&misc.Vectorsumpt<40","goff");
cout << "DataTopVSPT40" << endl;
Data->Draw("misc.MT2>>DataTopVSPT40", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&(NEles+NMuons)==1&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM>=1&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=40&&misc.Vectorsumpt<50","goff");
cout << "DataTopVSPT50" << endl;
Data->Draw("misc.MT2>>DataTopVSPT50", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&(NEles+NMuons)==1&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM>=1&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=50&&misc.Vectorsumpt<70","goff");
cout << "DataTopVSPT70" << endl;
Data->Draw("misc.MT2>>DataTopVSPT70", "NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&(NEles+NMuons)==1&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM>=1&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=70&&misc.Vectorsumpt<100","goff");
cout << "DataTopVSPT100" << endl;
Data->Draw("misc.MT2>>DataTopVSPT100","NJetsIDLoose40>=2&&misc.HT>750&&misc.MET>10&&(NEles+NMuons)==1&&NTausIDLoose3Hits==0&&misc.MinMetJetDPhi4Pt40>0.5&&NBJets40CSVM>=1&&misc.PassJet40ID ==1&&misc.HBHENoiseFlag == 0&&misc.CSCTightHaloIDFlag == 0&&misc.trackingFailureFlag==0&&misc.eeBadScFlag==0&&misc.EcalDeadCellTriggerPrimitiveFlag==0&&misc.TrackingManyStripClusFlag==0&&misc.TrackingTooManyStripClusFlag==0&&misc.TrackingLogErrorTooManyClustersFlag==0&&misc.CrazyHCAL==0&&(misc.MET>30||misc.MET/misc.CaloMETRaw<=2.)&&misc.Vectorsumpt>=100","goff");

TLegend *leg = new TLegend(.6,.6,.90,.90);
leg->SetName("leg");
leg -> SetFillColor(0);
leg -> SetBorderSize(0);
leg->AddEntry(LM6VSPT0,"0 #leq VSPT < 20 GeV", "l");
leg->AddEntry(LM6VSPT20,"20 #leq VSPT < 30 GeV", "l");
leg->AddEntry(LM6VSPT30,"30 #leq VSPT < 40 GeV", "l");
leg->AddEntry(LM6VSPT40,"40 #leq VSPT < 50 GeV", "l");
leg->AddEntry(LM6VSPT50,"50 #leq VSPT < 70 GeV", "l");
leg->AddEntry(LM6VSPT70,"70 #leq VSPT < 100 GeV", "l");
leg->AddEntry(LM6VSPT100,"100 GeV #leq VSPT", "l");

//store the file
TFile *file = new TFile("UTMfile.root","RECREATE");
file->cd();
LM6VSPT0  ->Write();
LM6VSPT20 ->Write();
LM6VSPT30 ->Write();
LM6VSPT40 ->Write();
LM6VSPT50 ->Write();
LM6VSPT70 ->Write();
LM6VSPT100->Write();
WJetsVSPT0  ->Write();
WJetsVSPT20 ->Write();
WJetsVSPT30 ->Write();
WJetsVSPT40 ->Write();
WJetsVSPT50 ->Write();
WJetsVSPT70 ->Write();
WJetsVSPT100->Write();
ZJetsVSPT0  ->Write();
ZJetsVSPT20 ->Write();
ZJetsVSPT30 ->Write();
ZJetsVSPT40 ->Write();
ZJetsVSPT50 ->Write();
ZJetsVSPT70 ->Write();
ZJetsVSPT100->Write();
TTbarVSPT0  ->Write();
TTbarVSPT20 ->Write();
TTbarVSPT30 ->Write();
TTbarVSPT40 ->Write();
TTbarVSPT50 ->Write();
TTbarVSPT70 ->Write();
TTbarVSPT100->Write();
DataQCDVSPT0  ->Write();
DataQCDVSPT20 ->Write();
DataQCDVSPT30 ->Write();
DataQCDVSPT40 ->Write();
DataQCDVSPT50 ->Write();
DataQCDVSPT70 ->Write();
DataQCDVSPT100->Write();
DataWVSPT0  ->Write();
DataWVSPT20 ->Write();
DataWVSPT30 ->Write();
DataWVSPT40 ->Write();
DataWVSPT50 ->Write();
DataWVSPT70 ->Write();
DataWVSPT100->Write();
DataZVSPT0  ->Write();
DataZVSPT20 ->Write();
DataZVSPT30 ->Write();
DataZVSPT40 ->Write();
DataZVSPT50 ->Write();
DataZVSPT70 ->Write();
DataZVSPT100->Write();
DataTopVSPT0  ->Write();
DataTopVSPT20 ->Write();
DataTopVSPT30 ->Write();
DataTopVSPT40 ->Write();
DataTopVSPT50 ->Write();
DataTopVSPT70 ->Write();
DataTopVSPT100->Write();
leg->Write();
file->Close();

cout << "File saved: " << file->GetName() << endl;

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

  std::string runName = "precalib_BGO_pedestal_noSource";
  std::string tag = "default";
  if( argc>2 ) {
    std::string runName_str(argv[1]);
    runName = runName_str;
    std::string tag_str(argv[2]);
    tag = tag_str;
  }else{
    std::cout<<"Usage:"<<std::endl;
    std::cout<<"./makeSimulationToAnalysisTree BeamEnergy(in MeV) tag"<<std::endl;
    exit(12345);
  }

  TString runName_tstr(runName);


  bool isIdeal = false;

  //run name = energy for now, might have to change this for different beams...
    std::string fileName = "OriginalSimulationData/EEShash" + runName + ".root";
    TFile* file = TFile::Open(fileName.c_str());
    if( file==0 ) {
    std::string fileName = "OriginalSimulationData/EEShashIdeal_" + runName + ".root";
    TFile* file = TFile::Open(fileName.c_str());
    isIdeal = true;
    }
    if( file==0 ) {
      std::cout << "ERROR! Din't find file " << fileName << std::endl;
      std::cout << "Exiting." << std::endl;
      exit(11);
    }

  TChain* tree = new TChain("EEShash");
  tree = (TChain*)file->Get("EEShash");





  //std::string outdir = "analysisTrees_" + tag;
  std::string outdir = "OriginalSimulationData";
  system( Form("mkdir -p %s", outdir.c_str()) );
  std::string outfileName;
  if(isIdeal==0){ outfileName = outdir + "/Reco_Simulation" + runName + ".root";}
  else { outfileName = outdir + "/Reco_Simulation_Ideal_" + runName + ".root";}
  TFile* outfile = TFile::Open( outfileName.c_str(), "RECREATE" );
  

  TTree* outTree = new TTree("recoTree","recoTree");

  double Eact_0;
  tree->SetBranchAddress("Eact_0", &Eact_0);
  double Eact_1;
  tree->SetBranchAddress("Eact_1", &Eact_1);
  double Eact_2;
  tree->SetBranchAddress("Eact_2", &Eact_2);
  double Eact_3;
  tree->SetBranchAddress("Eact_3", &Eact_3);
  double Eact_4;
  tree->SetBranchAddress("Eact_4", &Eact_4);
  double Eact_5;
  tree->SetBranchAddress("Eact_5", &Eact_5);
  double Eact_6;
  tree->SetBranchAddress("Eact_6", &Eact_6);
  double Eact_7;
  tree->SetBranchAddress("Eact_7", &Eact_7);
  double Eact_8;
  tree->SetBranchAddress("Eact_8", &Eact_8);
  double Eact_9;
  tree->SetBranchAddress("Eact_9", &Eact_9);
  double Eact_10;
  tree->SetBranchAddress("Eact_10", &Eact_10);

  double Eact_11;
  tree->SetBranchAddress("Eact_11", &Eact_11);
  double Eact_12;
  tree->SetBranchAddress("Eact_12", &Eact_12);
  double Eact_13;
  tree->SetBranchAddress("Eact_13", &Eact_13);
  double Eact_14;
  tree->SetBranchAddress("Eact_14", &Eact_14);


  double Ebgo_0;
  tree->SetBranchAddress( "Ebgo_0", &Ebgo_0);
  double Ebgo_1;
  tree->SetBranchAddress( "Ebgo_1", &Ebgo_1);
  double Ebgo_2;
  tree->SetBranchAddress( "Ebgo_2", &Ebgo_2);
  double Ebgo_3;
  tree->SetBranchAddress("Ebgo_3", &Ebgo_3);
  double Ebgo_4;
  tree->SetBranchAddress("Ebgo_4", &Ebgo_4);
  double Ebgo_5;
  tree->SetBranchAddress("Ebgo_5", &Ebgo_5);
  double Ebgo_6;
  tree->SetBranchAddress("Ebgo_6", &Ebgo_6);
  double Ebgo_7;
  tree->SetBranchAddress("Ebgo_7", &Ebgo_7);

  double Ebgo;
  tree->SetBranchAddress("Ebgo", &Ebgo);

  double Eabs;
  tree->SetBranchAddress("Eabs", &Eabs);
  double Eact;
  tree->SetBranchAddress("Eact", &Eact);

  double Escint1;
  tree->SetBranchAddress("Escint1", &Escint1);

  double Ehodo11;
  tree->SetBranchAddress("Ehodo11", &Ehodo11);

  double Ehodo12;
  tree->SetBranchAddress("Ehodo12", &Ehodo12);


  double Escint;
  tree->SetBranchAddress("Escint", &Escint);

  double Ehodo;
  tree->SetBranchAddress("Ehodo", &Ehodo);

  double xPosition;
  tree->SetBranchAddress("xPosition",&xPosition);
  double yPosition;
  tree->SetBranchAddress("yPosition",&yPosition);


  float cef3_corr_[CEF3_CHANNELS],bgo_corr_[BGO_CHANNELS];
  bool isSingleEle_scintFront_=1;
  int nHodoClustersY=1; int nHodoClustersX=1;
  int nHodoClusters1Y=1; int nHodoClusters1X=1;
  float E_abs;

  float xPos;
  float yPos;

  int bgo_chan=BGO_CHANNELS;
  int cef3_chan=CEF3_CHANNELS;

  outTree->Branch( "nHodoClustersX", &nHodoClustersX, "nHodoClustersX/I" );
  outTree->Branch( "nHodoClustersY", &nHodoClustersY, "nHodoClustersY/I" );
  outTree->Branch( "nHodoClusters1X", &nHodoClusters1X, "nHodoClusters1X/I" );
  outTree->Branch( "nHodoClusters1Y", &nHodoClusters1Y, "nHodoClusters1Y/I" );

  outTree->Branch( "cef3_chan", &cef3_chan, "cef3_chan/I" );
  outTree->Branch( "bgo_chan", &bgo_chan, "bgo_chan/I" );

  outTree->Branch( "bgo_corr", bgo_corr_, "bgo_corr_[bgo_chan]/F" );
  outTree->Branch( "cef3_corr", cef3_corr_, "cef3_corr_[cef3_chan]/F" );

  outTree->Branch( "isSingleEle_scintFront", &isSingleEle_scintFront_, "isSingleEle_scintFront_/O" );

  outTree->Branch( "E_abs", &E_abs, "E_abs/F");

  outTree->Branch( "xPos", &xPos, "xPos/F");
  outTree->Branch( "yPos", &yPos, "yPos/F");


  float LYSF[] = {0.85, 0.94, 0.95, 0.98, 1.00, 1.02, 1.05, 1.05, 1.05, 0.74};

  // float LYSF[] = {0.85, 0.94, 0.95, 0.98, 1.00, 0.7, 1.05, 1.05, 1.05, 0.74};

  // float LYSF[] =  {0.87, 0.96, 0.97, 1.00, 1.02, 1.04, 1.07, 1.07, 1.08, 0.75};
  //as a test with the best being the best one
  //  float LYSF[] =  {0.81, 0.89, 0.90, 0.93, 0.95, 0.97, 1.00, 1.00, 1.00, 0.70};


  //Test if 6.crystal fails
  //  float LYSFH[] = {0.87, 0.96, 0.97, 1.00, 1.02, 0.50, 1.07, 1.07, 1.08, 1.07, 1.08, 1.09, 1.09, 1.04, 0.75};
  ///



   float LYSFH[] = {0.87, 0.96, 0.97, 1.00, 1.02, 1.04, 1.07, 1.07, 1.08, 1.07, 1.08, 1.09, 1.09, 1.04, 0.75};

  /*
    std::string fullVarName = "";
    for( unsigned i=0; i<15; ++i ) {
    std::string plusSign = (i==0) ? "" : " + ";
    std::string thisPiece(Form("%s%f*Eact_%d", plusSign.c_str(), LYSFH[i], i));
    fullVarName += thisPiece;
    }
  
  */
  
  unsigned nentries = tree->GetEntries();
  
  double hodoEff;
  double scintEff;
  
  for( unsigned iEntry=0; iEntry<nentries; ++iEntry ) {
    
    tree->GetEntry(iEntry);
    
    if( iEntry % 5000 == 0 ) std::cout << "Entry: " << iEntry << " / " << nentries << std::endl;
 
 
        
    xPos = xPosition;
    yPos = yPosition;
    
    if(Ehodo11>0.1){
       nHodoClustersX=1;
      hodoEff++;
    } else{   nHodoClusters1X=0;}

    if(Ehodo12>0.1){
      nHodoClustersY=1; 
      hodoEff++;
    } else{   nHodoClusters1Y=0; }
   
    
    if(Escint1>0.25){
      isSingleEle_scintFront_=1;
      scintEff++;
    } else{       isSingleEle_scintFront_=0;}
    
   
 
   


    if(Ehodo>0.1){
       nHodoClustersX=1; nHodoClustersY=1;
      hodoEff++;
    } else{   nHodoClustersX=0;  nHodoClustersY=0;}
  
    /*
    if(Escint>0.25 && Escint< 1.5){
      isSingleEle_scintFront_=1;
      scintEff++;
    } else{       isSingleEle_scintFront_=0;}     
    */ 
    
    E_abs= Eabs;


    
    std::vector<float> cef3_corr;
    for( int i=0; i<CEF3_CHANNELS; ++i ) cef3_corr.push_back(-1.);
    
    std::vector<float> bgo_corr;
    for( int i=0; i<BGO_CHANNELS; ++i ) bgo_corr.push_back(-1.);
 
    /*
     
     for(int i=0; i<10; ++i){
     cef3_corr[0]= (LYSF[0]*Eact_0+LYSF[1]*Eact_1+LYSF[2]*Eact_2 +LYSF[3]*Eact_3 +LYSF[4]*Eact_4 +LYSF[5]*Eact_5 +LYSF[6]*Eact_6 +LYSF[7]*Eact_7 +LYSF[8]*Eact_8 +LYSF[9]*Eact_9)/4. ; //yes not very elegant, but it didn't want to work otherwise
     // cef3_corr[0] = Eact /4.;
     }
    */
      
  
    
    for(int i=0; i<15; ++i){
      cef3_corr[0]= (LYSFH[0]*Eact_0+LYSFH[1]*Eact_1+LYSFH[2]*Eact_2 +LYSFH[3]*Eact_3 +LYSFH[4]*Eact_4 +LYSFH[5]*Eact_5 +LYSFH[6]*Eact_6 +LYSFH[7]*Eact_7 +LYSFH[8]*Eact_8 +LYSFH[9]*Eact_9 +LYSFH[10]*Eact_10  +LYSFH[11]*Eact_11 +LYSFH[12]*Eact_12 +LYSFH[13]*Eact_13  +LYSFH[14]*Eact_14 )/4. ; //yes not very elegant, but it didn't want to work otherwise

      //  cef3_corr[0] = Eact /4.;
     }   
    

    
    bgo_corr[0] = Ebgo/8.;
    bgo_corr[1] = Ebgo/8.;
    bgo_corr[2] = Ebgo/8.;
    bgo_corr[3] = Ebgo/8.;
    bgo_corr[4] = Ebgo/8.;
    bgo_corr[5] = Ebgo/8.;
    bgo_corr[6] = Ebgo/8.;
    bgo_corr[7] = Ebgo/8.;
    
    
    for(int k=0; k<CEF3_CHANNELS; ++k){
      cef3_corr_[k] = cef3_corr[0];
    }
    
    for (int k=0; k<BGO_CHANNELS; ++k){ 
      bgo_corr_[k] = bgo_corr[k];
    }
    
    
    outTree->Fill();
  }
  
  
  outfile->cd();
  outTree->Write();
  outfile->Close();
  
  std::cout << "-> Simulated Analysis Tree saved in: " << outfile->GetName() << std::endl;

  std::cout << "Scintillator efficiency = " << scintEff/nentries << std::endl;
  std::cout << "Hodoscope efficiency = " << hodoEff/nentries << std::endl;
 

  return 0;

}
Example #13
0
void ZTMVAClassification( TString myMethodList = "" ) {
   

    //---------------------------------------------------------------
    // 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"]     = 0; // 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"]          = 0;
    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"]             = 1; // uses Adaptive Boost
    Use["BDTG"]            = 1; // uses Gradient Boost
    Use["BDTB"]            = 0; // uses Bagging
    Use["BDTD"]            = 0; // decorrelation + Adaptive Boost
    Use["BDTF"]            = 0; // allow usage of fisher discriminant for node splitting 
    // 
    // --- Friedman's RuleFit method, ie, an optimised series of cuts ("rules")
    Use["RuleFit"]         = 0;
    // ---------------------------------------------------------------

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



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

    // --- 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" );


    TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile,
                                               "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );


// ADD IN OUR VARIABLES HERE
    
    factory->AddVariable("log(kaon_IPCHI2_OWNPV)", "log(kaon_IPCHI2_OWNPV)", "", 'D');
    //factory->AddVariable("kaon_TRACK_GhostProb", "kaon_TRACK_GhostProb", "", 'D');
    factory->AddVariable("kaon_PT", "kaon_PT", "", 'D');
    
    factory->AddVariable("log(proton_IPCHI2_OWNPV)", "log(proton_IPCHI2_OWNPV)", "", 'D');
    //factory->AddVariable("proton_TRACK_GhostProb", "proton_TRACK_GhostProb", "", 'D');
    factory->AddVariable("proton_PT", "proton_PT", "", 'D');
    
    //factory->AddVariable("gamma_PT", "gamma_PT", "", 'D');
    //factory->AddVariable("gamma_CL", "gamma_CL", "", 'D');  
  
    factory->AddVariable("muminus_ProbNNmu", "muminus_ProbNNmu", "", 'D');  
    //factory->AddVariable("muminus_TRACK_GhostProb", "muminus_TRACK_GhostProb", "", 'D');  

    factory->AddVariable("muplus_ProbNNmu", "muplus_ProbNNmu", "", 'D');  
    //factory->AddVariable("muplus_TRACK_GhostProb", "muplus_TRACK_GhostProb", "", 'D');  

    factory->AddVariable("Lambda_b0_DTF_CHI2NDOF", "Lambda_b0_DTF_CHI2NDOF", "", 'D');
    //factory->AddVariable("log(Lambda_b0_IPCHI2_OWNPV)", "log(Lambda_b0_IPCHI2_OWNPV)", "", 'D');
    factory->AddVariable("Lambda_b0_FDS", "Lambda_b0_FDS", "", 'D');  
    factory->AddVariable("Lambda_b0_PT", "Lambda_b0_PT", "", 'D');
    


    //   TFile * input_Background = new TFile("../back.root");
    TFile * input_Signal = new TFile("/afs/cern.ch/work/a/apmorris/public/Lb2chicpK/signal_samples/reduced_Lb2chicpK_MC_2011_2012_signal.root");                                  //
    TFile * input_Background = new TFile("/afs/cern.ch/work/a/apmorris/public/Lb2chicpK/signal_samples/background.root");                                                  //
    std::cout << "--- TMVAClassification       : Using input file for signal    : " << input_Signal->GetName() << std::endl;
    std::cout << "--- TMVAClassification       : Using input file for background : " << input_Background->GetName() << std::endl;
   
    // --- Register the training and test trees

    TTree *signal     = (TTree*)input_Signal->Get("DecayTree");
    TTree *background = (TTree*)input_Background->Get("DecayTree");
   
    // global event weights per tree (see below for setting event-wise weights)
    Double_t signalWeight     = 1.0;
    Double_t backgroundWeight = 1.0;
   
    // You can add an arbitrary number of signal or background trees
    factory->AddSignalTree    ( signal,     signalWeight     );
    factory->AddBackgroundTree( background, backgroundWeight );
   

    // 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" );

    // 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" );

    // 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" );
      //factory->BookMethod( TMVA::Types::kMLP, "MLP", "H:!V:NeuronType=tanh:VarTransform=Norm:NCycles=600:HiddenLayers=N+5:TestRate=5" );
      // factory->BookMethod( TMVA::Types::kMLP, "MLPCE", "H:!V:NeuronType=sigmoid:VarTransform=Norm:NCycles=600:HiddenLayers=N+5:TestRate=5:EstimatorType=CE" );
      factory->BookMethod( TMVA::Types::kMLP, "MLP", "H:!V:NeuronType=sigmoid:VarTransform=Norm:NCycles=600:HiddenLayers=9:TestRate=5:EstimatorType=CE" );
      //   factory->BookMethod( TMVA::Types::kMLP, "MLPCE83", "H:!V:NeuronType=tanh:VarTransform=Norm:NCycles=600:HiddenLayers=8,3:TestRate=5:EstimatorType=CE" );
    }

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

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

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

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

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

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

       //     factory->BookMethod( TMVA::Types::kBDT, "BDTG6",
       //                      "!H:!V:NTrees=600:BoostType=Grad:Shrinkage=0.30:UseBaggedGrad:GradBaggingFraction=0.4:nCuts=20:NNodesMax=6" );
       //factory->BookMethod( TMVA::Types::kBDT, "BDTG2",
       //                    "!H:!V:NTrees=800:BoostType=Grad:Shrinkage=0.30:UseBaggedGrad:GradBaggingFraction=0.4:nCuts=20:NNodesMax=6" );
       factory->BookMethod( TMVA::Types::kBDT, "BDTG3",
                           "!H:!V:NTrees=1000:BoostType=Grad:Shrinkage=0.30:UseBaggedGrad:GradBaggingFraction=0.4:nCuts=20:NNodesMax=6" );
       // factory->BookMethod( TMVA::Types::kBDT, "BDTG4",
       //                     "!H:!V:NTrees=1200:BoostType=Grad:Shrinkage=0.30:UseBaggedGrad:GradBaggingFraction=0.4:nCuts=20:NNodesMax=6" );
       // factory->BookMethod( TMVA::Types::kBDT, "BDTG5",
       //                     "!H:!V:NTrees=1000:BoostType=Grad:Shrinkage=0.30:UseBaggedGrad:GradBaggingFraction=0.4:nCuts=20:NNodesMax=5" );

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

    delete factory;

    // Launch the GUI for the root macros
    //  if (!gROOT->IsBatch()) TMVAGui( outfileName );
}
void TMVAClassification_ttV( TString myMethodList = "" )
{
   // The explicit loading of the shared libTMVA is done in TMVAlogon.C, defined in .rootrc
   // if you use your private .rootrc, or run from a different directory, please copy the
   // corresponding lines from .rootrc

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

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

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

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

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

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

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

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

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

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

   // --- Here the preparation phase begins

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   delete factory;

   // Launch the GUI for the root macros
   if (!gROOT->IsBatch()) TMVAGui( outfileName );
}
Example #15
0
void MergeRootfile( TDirectory *target, TList *sourcelist, double crossArray[] ) {

  cout << "Target path: " << target->GetPath() << endl;
  TString path( (char*)strstr( target->GetPath(), ":" ) );
  path.Remove( 0, 2 );

  TFile *first_source = (TFile*)sourcelist->First();

  first_source->cd( path );
  TDirectory *current_sourcedir = gDirectory;
  //gain time, do not add the objects in the list in memory
  Bool_t status = TH1::AddDirectoryStatus();
  TH1::AddDirectory(kFALSE);

  // loop over all keys in this directory
  TChain *globChain = 0;
  TIter nextkey( current_sourcedir->GetListOfKeys() );
  TKey *key, *oldkey=0;
  while ( (key = (TKey*)nextkey())) {

    //keep only the highest cycle number for each key
    if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue;

    // read object from first source file
    first_source->cd( path );
    TObject *obj = key->ReadObj();

    if ( obj->IsA()->InheritsFrom( "TH1" ) ) {
      // descendant of TH1 -> merge it

      cout << "Merging histogram " << obj->GetName() << endl;
      TH1 *h1 = (TH1*)obj;

      // Scale by the cross-section factor
      h1->Scale(crossArray[0]);
      h1->Sumw2();

      // loop over all source files and add the content of the
      // correspondant histogram to the one pointed to by "h1"
      TFile *nextsource = (TFile*)sourcelist->After( first_source );

      int q = 1; // This keeps track of which
                 // cross section factor to use
      while ( nextsource ) {
        // make sure we are at the correct directory level by cd'ing to path
        nextsource->cd( path );
        TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(h1->GetName());
        if (key2) {
           TH1 *h2 = (TH1*)key2->ReadObj();

           // Scale by the cross section factor
           // before adding.
           h2->Scale(crossArray[q]);
           h1->Add( h2 );
           q++;
           delete h2;
        }

        nextsource = (TFile*)sourcelist->After( nextsource );
      }
    }
    else if ( obj->IsA()->InheritsFrom( "TTree" ) ) {

      // loop over all source files create a chain of Trees "globChain"
      const char* obj_name= obj->GetName();

      globChain = new TChain(obj_name);
      globChain->Add(first_source->GetName());
      TFile *nextsource = (TFile*)sourcelist->After( first_source );
      //      const char* file_name = nextsource->GetName();
      // cout << "file name  " << file_name << endl;
     while ( nextsource ) {

       globChain->Add(nextsource->GetName());
       nextsource = (TFile*)sourcelist->After( nextsource );
     }

    } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) {
      // it's a subdirectory

      cout << "Found subdirectory " << obj->GetName() << endl;

      // create a new subdir of same name and title in the target file
      target->cd();
      TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() );

      // newdir is now the starting point of another round of merging
      // newdir still knows its depth within the target file via
      // GetPath(), so we can still figure out where we are in the recursion
      MergeRootfile( newdir, sourcelist, crossArray );

    } else {

      // object is of no type that we know or can handle
      cout << "Unknown object type, name: "
           << obj->GetName() << " title: " << obj->GetTitle() << endl;
    }

    // now write the merged histogram (which is "in" obj) to the target file
    // note that this will just store obj in the current directory level,
    // which is not persistent until the complete directory itself is stored
    // by "target->Write()" below
    if ( obj ) {
      target->cd();

      //!!if the object is a tree, it is stored in globChain...
        if(obj->IsA()->InheritsFrom( "TTree" ))
          globChain->Merge(target->GetFile(),0,"keep");
        else
        obj->Write( key->GetName() );
    }

  } // while ( ( TKey *key = (TKey*)nextkey() ) )

  // save modifications to target file
  target->SaveSelf(kTRUE);
  TH1::AddDirectory(status);
}
Example #16
0
void TMVAtest1()
{

  // ---------------------------------------------------------------
  std::cout << std::endl;
  std::cout << "==> Start TMVAClassification" << std::endl;
  // --------------------------------------------------------------------------------------------------
  
  // --- Here the preparation phase begins
  
  // Create a ROOT output file where TMVA will store ntuples, histograms, etc.
  TString TrainName = "TMVA";
  
  TString outfileName( TrainName+".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( TrainName, outputFile,
					      "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D:AnalysisType=Classification" );
  
  // If you wish to modify default settings
  // (please check "src/Config.h" to see all available global options)
  //    (TMVA::gConfig().GetVariablePlotting()).fTimesRMS = 8.0;
  //    (TMVA::gConfig().GetIONames()).fWeightFileDir = "myWeightDirectory";
  
  // Define the input variables that shall be used for the MVA training
  // note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"
  // [all types of expressions that can also be parsed by TTree::Draw( "expression" )]
  
  factory->AddVariable ("ptphoton", 'F');
//  factory->AddVariable ("etaphoton", 'F');
  factory->AddVariable ("ptmuon", 'F');
// factory->AddVariable ("etamuon", 'F');
  factory->AddVariable ("ptjet", 'F');
//  factory->AddVariable ("etajet", 'F');
//  factory->AddVariable ("masstop", 'F');
//  factory->AddVariable ("mtw", 'F');
  factory->AddVariable ("deltaRphotonjet", 'F');
  factory->AddVariable ("deltaRphotonmuon", 'F');
//  factory->AddVariable ("ht", 'F');
//  factory->AddVariable ("photonmuonmass", 'F');
  factory->AddVariable ("costopphoton", 'F');
//  factory->AddVariable ("topphotonmass", 'F');
//factory->AddVariable ("pttop", 'F');
//factory->AddVariable ("etatop", 'F');
  factory->AddVariable ("jetmultiplicity", 'F');
//  factory->AddVariable ("bjetmultiplicity", 'F');
  factory->AddVariable ("deltaphiphotonmet", 'F');
  factory->AddVariable ("cvsdiscriminant", 'F');
//  factory->AddVariable ("leptoncharge", 'F');


  //Load the signal and background event samples from ROOT trees
  
//  TFile *inputSTrain(0);
//  TFile *inputBTrain(0);
  TString sigFileTrain  = "SIGNALtGu.root";
  TString bkgFileTrain = "WPHJET.root";
  TString ttbarFileTrain1 ="TTBAR1.root";
  TString ttbarFileTrain2 ="TTBAR2.root";
  TString ttbarFileTrain3 ="TTBAR3.root";
  TString TTGFileTrain ="TTG.root";
  TString WWFileTrain ="WW.root";
  TString WZFileTrain ="WZ.root";
  TString ZZFileTrain ="ZZ.root";
  TString ZGAMMAFileTrain ="ZGAMMA.root";


//  TString bkgFileTrain = "TTG.root";
  
  TFile *inputSTrain  = TFile::Open( sigFileTrain );
 if (!inputSTrain) {
      std::cout << "ERROR: could not open data file" << std::endl;
      exit(1);
   } 
  TFile *inputBTrain = TFile::Open( bkgFileTrain );
  TFile *inputBttbar1 = TFile::Open( ttbarFileTrain1);
  TFile *inputBttbar2 = TFile::Open( ttbarFileTrain2);
  TFile *inputBttbar3 = TFile::Open( ttbarFileTrain3);
  TFile *inputTTG= TFile::Open(TTGFileTrain );
  TFile *inputWW= TFile::Open(WWFileTrain );
  TFile *inputWZ= TFile::Open(WZFileTrain );
  TFile *inputZZ= TFile::Open(ZZFileTrain );
  TFile *inputZGAMMA= TFile::Open( ZGAMMAFileTrain);

if (!inputBTrain) {
      std::cout << "ERROR: could not open data file" << std::endl;
      exit(1);
   }

 
  std::cout << "--- TMVAnalysis    : Accessing Signal Train: " << sigFileTrain << std::endl;
  std::cout << "--- TMVAnalysis    : Accessing Background Train: " << bkgFileTrain << std::endl;
  
  TTree *signalTrain      = (TTree*)inputSTrain->FindObjectAny("atq");
  TTree *backgroundTrain = (TTree*)inputBTrain->FindObjectAny("atq");
  TTree *ttbarbackground1 = (TTree*)inputBttbar1->FindObjectAny("atq");
  TTree *ttbarbackground2 = (TTree*)inputBttbar2->FindObjectAny("atq");
  TTree *ttbarbackground3 = (TTree*)inputBttbar3->FindObjectAny("atq");
  TTree *TTGbackground = (TTree*)inputTTG->FindObjectAny("atq");
  TTree *WWbackground = (TTree*)inputWW->FindObjectAny("atq");
  TTree *WZbackground = (TTree*)inputWZ->FindObjectAny("atq");
  TTree *ZZbackground = (TTree*)inputZZ->FindObjectAny("atq");
  TTree *ZGAMMAbackground = (TTree*)inputZGAMMA->FindObjectAny("atq");

//  TTree *signalTrain      = (TTree*)inputSTrain->FindObjectAny("insidetopmass");
//  TTree *backgroundTrain = (TTree*)inputBTrain->FindObjectAny("insidetopmass");
  
 // factory->AddSignalTree( signalTrain, 1);
//cout<<"reza1";
  
 // factory->AddBackgroundTree( backgroundTrain, 1, );
//cout<<"reza2";

 factory->SetInputTrees(signalTrain,backgroundTrain,1,1);
 factory->AddBackgroundTree( ttbarbackground1, 1.1);
 factory->AddBackgroundTree( ttbarbackground2, 1.1);
// factory->AddBackgroundTree( ttbarbackground3, 0.3);
 factory->AddBackgroundTree( TTGbackground, 1);
 factory->AddBackgroundTree( WWbackground, 1);
 factory->AddBackgroundTree(WZbackground , 1);
 factory->AddBackgroundTree(ZZbackground , 1);
 factory->AddBackgroundTree(ZGAMMAbackground , 1);

  // Set xs-weight
//  factory->SetSignalWeightExpression    ("weight");
  //factory->SetBackgroundWeightExpression("weight");
  
  // Apply additional cuts on the signal and background samples (can be different)
  TCut mycut = "";
 // TCut mycutb = ""; 
  
  Int_t nSignalTrain = signalTrain->GetEntries();
  
  Int_t nBackTrain  = backgroundTrain->GetEntries();
  factory->PrepareTrainingAndTestTree( "","", "nTrain_Signal=0:nTrain_Background=0:nTest_Signal=0:nTest_Background=0:SplitMode=Random:SplitSeed=88!V" );

  
//factory->PrepareTrainingAndTestTree( "", "",
//				       "nTrain_Signal=100:nTrain_Background=100:nTest_Signal=100:nTest_Background=100:!V" );

//  factory->PrepareTrainingAndTestTree( mycuts, mycutb,
				       //":NSigTrain=:NBkgTrain=:NSigTest=:NBkgTest=:SplitMode=Alternate:!V" );  
				       //":nTrain_Signal=10000:nTest_Signal=2260:nTrain_Background=100000:nTest_Background=100000:SplitMode=Alternate:!V" );  
//				       ":nTrain_Signal=nSignalTrain:nTrain_Background=nBackTrain:!V");
  //":nTrain_Signal=nSignalTrain:nTest_Signal=nSignalTest:nTrain_Background=nBackTrain:nTest_Background=nBackTest:SplitMode=Block:!V");
  //":SplitMode=Alternate:!V");
  //":nTrain_Signal=:nTest_Signal=:nTrain_Background=:nTest_Background=:SplitMode=Block:!V");
  //":SplitMode=Alternate:!V" );  
  
  // ---- Book MVA methods
//  factory->BookMethod( TMVA::Types::kBDT, "BDT",
//		       "!H:!V:NTrees=300:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=-1:NNodesMax=5:UseNvars=4:PruneStrength=5:PruneMethod=CostComplexity:MaxDepth=4" );
//factory->BookMethod( TMVA::Types::kBDT, "BDT",
 //                      "!H:!V:NTrees=400:BoostType=AdaBoost:AdaBoostBeta=0.5:MaxDepth=3:SeparationType=GiniIndex:PruneMethod=NoPruning" );
factory->BookMethod( TMVA::Types::kBDT, "BDT",
                       "!H:!V:NTrees=400:BoostType=AdaBoost:AdaBoostBeta=0.8:MaxDepth=3:SeparationType=GiniIndex:PruneMethod=NoPruning" );


//  factory->BookMethod( TMVA::Types::kBDT, "BDT", "!H:!V:NTrees=1000:BoostType=Grad:Shrinkage=0.30:UseBaggedGrad:GradBaggingFraction=0.6:SeparationType=GiniIndex:nCuts=20:NNodesMax=5");
 // factory->BookMethod(TMVA::Types::kFisher, "Fisher", "H:!V:Fisher");   
  // ---- Now you can tell the factory to train, test, and evaluate the MVAs
// factory->BookMethod( TMVA::Types::kMLP, "MLP", "H:!V:NeuronType=tanh:VarTransform=N:NCycles=600:HiddenLayers=N+5:TestRate=5:!UseRegulator" ); 
// factory->BookMethod( TMVA::Types::kSVM, "SVM", "Gamma=0.25:Tol=0.001" );
// 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" ); 

  
// Train MVAs using the set of training events
  factory->TrainAllMethods();
  
   // ---- Evaluate all MVAs using the set of test events
  factory->TestAllMethods();
  
  // ----- Evaluate and compare performance of all configured MVAs
  factory->EvaluateAllMethods();
  
  // --------------------------------------------------------------
  
  // Save the output
  outputFile->Close();
  
  std::cout << "==> Wrote root file: " << outputFile->GetName() << std::endl;
  std::cout << "==> TMVAClassification is done!" << std::endl;
  
  delete factory;
  
  // Launch the GUI for the root macros
//  if (!gROOT->IsBatch()) TMVAGui( outfileName );
}
Example #17
0
void mytmvaClass( TString myMethodList = "" )
{
  // The explicit loading of the shared libTMVA is done in TMVAlogon.C, defined in .rootrc
  // if you use your private .rootrc, or run from a different directory, please copy the
  // corresponding lines from .rootrc

  // methods to be processed can be given as an argument; use format:
  //
  // mylinux~> root -l TMVAClassification.C\(\"myMethod1,myMethod2,myMethod3\"\)
  //
  // if you like to use a method via the plugin mechanism, we recommend using
  //
  // mylinux~> root -l TMVAClassification.C\(\"P_myMethod\"\)

  //--------------------------------
  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"]     = 0; // 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"]          = 0;
  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"]             = 1; // uses Adaptive Boost
  Use["BDTG"]            = 0; // uses Gradient Boost
  Use["BDTB"]            = 0; // uses Bagging
  Use["BDTD"]            = 0; // decorrelation + Adaptive Boost
  // 
  // --- 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 (Not of much interest)
  if (myMethodList != "") {
    for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) it->second = 0;

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

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

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

  // --- Here the preparation phase begins

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

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

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

  // Define the input variables that shall be used for the MVA training
  // note that you may also use variable expressions, such as: "3*var1/var2*abs(var3)"


  //Syntax --> "factory->AddVariable( "VarName", "UserDefinedLabel", "units", 'VarType' );" //Where VarType refers to float, int etc.

  Float_t nhiggsJetSubjets;
  Float_t njets;
  Float_t deltaPhiWH;
  Float_t jetPt[11];
  Float_t jetEta[11];
  Float_t jetPhi[11];
  Float_t jetE[11];
  Float_t higgsJetSubjetEta[3];
  Float_t higgsJetSubjetPhi[3];
  Float_t higgsJetSubjetPt[3];
  Float_t higgsJetSubjetE[3];
  Float_t Wphi;
  Float_t fatjetPt[15];
  Float_t fatjetEta[15];
  Float_t fatjetPhi[15];
  Float_t fatjetE[15];
  Float_t DeltaPhiWH;
  


  TLorentzVector fatjet(0,0,0,0);
  TLorentzVector subjet1(0,0,0,0);
  TLorentzVector subjet2(0,0,0,0);
  TLorentzVector subjet3(0,0,0,0);
  TLorentzVector akt[15];
  fatjet.SetPtEtaPhiE(fatjetPt[0],fatjetEta[0],fatjetPhi[0], fatjetE[0]);
  //   deltaPhiWH = std::fabs(Wphi-fatjetPhi[0]);
//   if(deltaPhiWH>TMath::Pi()){ std::fabs(deltaPhiWH = 2*TMath::Pi()-deltaPhiWH);} 

  
  
  factory->AddVariable( "deltaPhiWH", "deltaPhiWH", "", 'F' );
  factory->AddVariable( "jetPt.array[0]", "jetPt.array[0]", "", 'F' );
  factory->AddVariable( "fatjetPt[0].array[0]", "fatjetPt.array[0]", "", 'F' );
  //factory->AddVariable( "DeltaR[3][13]", "DeltaR[3][13]", "", 'F' );
  // factory->AddSpectator( "nhiggsJetSubjets", "nhiggsJetSubjets", "", 'F');
//   factory->AddSpectator( "njets", "", "njets", 'I');
//   factory->AddSpectator( "jetPt[0]", "jetPt[0]", "", 'F');
//   factory->AddSpectator( "jetPt[1]", "jetPt[1]", "", 'F');
//   factory->AddSpectator( "jetPt[2]", "jetPt[2]", "", 'F');
//   factory->AddSpectator( "jetPt[3]", "jetPt[3]", "", 'F');
//   factory->AddSpectator( "jetPt[4]", "jetPt[4]", "", 'F');
//   factory->AddSpectator( "jetPt[5]", "jetPt[5]", "", 'F');
//   factory->AddSpectator( "jetPt[6]", "jetPt[6]", "", 'F');
//   factory->AddSpectator( "jetPt[7]", "jetPt[7]", "", 'F');
//   factory->AddSpectator( "jetPt[8]", "jetPt[8]", "", 'F');
//   factory->AddSpectator( "jetPt[9]", "jetPt[9]", "", 'F');
//   factory->AddSpectator( "jetPt[10]", "jetPt[10]", "", 'F');
//   factory->AddSpectator( "jetEta[0]", "jetEta[0]", "", 'F');
//   factory->AddSpectator( "jetEta[1]", "jetEta[1]", "", 'F');
//   factory->AddSpectator( "jetEta[2]", "jetEta[2]", "", 'F');
//   factory->AddSpectator( "jetEta[3]", "jetEta[3]", "", 'F');
//   factory->AddSpectator( "jetEta[4]", "jetEta[4]", "", 'F');
//   factory->AddSpectator( "jetEta[5]", "jetEta[5]", "", 'F');
//   factory->AddSpectator( "jetEta[6]", "jetEta[6]", "", 'F');
//   factory->AddSpectator( "jetEta[7]", "jetEta[7]", "", 'F');
//   factory->AddSpectator( "jetEta[8]", "jetEta[8]", "", 'F');
//   factory->AddSpectator( "jetEta[9]", "jetEta[9]", "", 'F');
//   factory->AddSpectator( "jetEta[10]", "jetEta[10]", "", 'F');
//   factory->AddSpectator( "jetPhi[0]", "jetPhi[0]", "", 'F');
//   factory->AddSpectator( "jetPhi[1]", "jetPhi[1]", "", 'F');
//   factory->AddSpectator( "jetPhi[2]", "jetPhi[2]", "", 'F');
//   factory->AddSpectator( "jetPhi[3]", "jetPhi[3]", "", 'F');
//   factory->AddSpectator( "jetPhi[4]", "jetPhi[4]", "", 'F');
//   factory->AddSpectator( "jetPhi[5]", "jetPhi[5]", "", 'F');
//   factory->AddSpectator( "jetPhi[6]", "jetPhi[6]", "", 'F');
//   factory->AddSpectator( "jetPhi[7]", "jetPhi[7]", "", 'F');
//   factory->AddSpectator( "jetPhi[8]", "jetPhi[8]", "", 'F');
//   factory->AddSpectator( "jetPhi[9]", "jetPhi[9]", "", 'F');
//   factory->AddSpectator( "jetPhi[10]", "jetPhi[10]", "", 'F');
//   factory->AddSpectator("jetE[0]", "jetE[0]", "", 'F');
//   factory->AddSpectator("jetE[1]", "jetE[1]", "", 'F');
//   factory->AddSpectator("jetE[2]", "jetE[2]", "", 'F');
//   factory->AddSpectator("higgsJetSubjetEta[0]","higgsJetSubjetEta[0]", "", 'F');
//   factory->AddSpectator("higgsJetSubjetEta[1]","higgsJetSubjetEta[1]", "", 'F');
//   factory->AddSpectator("higgsJetSubjetEta[2]","higgsJetSubjetEta[2]", "", 'F');
//   factory->AddSpectator("higgsJetSubjetPhi[0]","higgsJetSubjetPhi[0]", "", 'F');
//   factory->AddSpectator("higgsJetSubjetPhi[1]","higgsJetSubjetPhi[1]", "", 'F');
//   factory->AddSpectator("higgsJetSubjetPhi[2]","higgsJetSubjetPhi[2]", "", 'F');
//   factory->AddSpectator("higgsJetSubjetPt[0]","higgsJetSubjetPt[0]", "", 'F');
//   factory->AddSpectator("higgsJetSubjetPt[1]","higgsJetSubjetPt[1]", "", 'F');
//   factory->AddSpectator("higgsJetSubjetPt[2]","higgsJetSubjetPt[2]", "", 'F');
//   factory->AddSpectator("higgsJetSubjetE[0]","higgsJetSubjetE[0]", "", 'F');
//   factory->AddSpectator("higgsJetSubjetE[1]","higgsJetSubjetE[1]", "", 'F');
//   factory->AddSpectator("higgsJetSubjetE[2]","higgsJetSubjetE[2]", "", 'F');
//   factory->AddSpectator("Wphi", "Wphi", "" , 'F');
//   factory->AddVariable("fatjetPt[0]", "fatjetPt[0]", "", 'F');
//   factory->AddSpectator("fatjetPhi[0]", "fatjetPhi[0]", "", 'F');
//   factory->AddSpectator("fatjetEta[0]", "fatjetEta[0]", "", 'F');
//   factory->AddSpectator("fatjetE[0]", "fatjetE[0]", "", 'F');
//   //if(std::fabs(Wphi-fatjetPhi[0])<TMath::Pi()){
//     factory->AddVariable("abs(Wphi-fatjetPhi[0])", "DeltaPhiWH", "", 'F'); 
//     //}
//   if ((abs(Wphi-fatjetPhi[0])>TMath::Pi())){
//     factory->AddVariable("(abs(DeltaPhiWH = 2*(TMath::Pi())-DeltaPhiWH))", "DeltaPhiWH", "", 'F');
//   }
  


  // Here, we add the lepton flag as a spectator so we can cut (further down) on lep == 0 for muons only or lep == 1 for electrons only.
  //factory->AddSpectator( "lepType[0]", "lepType[0]", "units", 'I');


 

  // 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 fsig_name_WH = "/Disk/speyside7/Grid/grid-files/rsmith/SummerProject/OverlapperInputFiles/PreCutsApplied/mc11_7TeV.128034.HerwigppPowHeg_Boosted_WH125lnubb.merge.NTUP_HSG5WH.Output_PreCuts-Original.root";
  TString fback_name_TT = "/Disk/speyside7/Grid/grid-files/rsmith/SummerProject/OverlapperInputFiles/PreCutsApplied/TT_NewBranch2.output_MERGE_PreCuts-Original.root";
  TString fback_name_Wbb = "/Disk/speyside7/Grid/grid-files/rsmith/SummerProject/OverlapperInputFiles/PreCutsApplied/mc11_7TeV.128861.SherpaWbb2J_lnu_Wpt100GeV_PreCuts-Original.root";


  TFile *sig_input_WH = TFile::Open( fsig_name_WH );
  TFile *back_input_TT = TFile::Open( fback_name_TT );
  TFile *back_input_Wbb = TFile::Open( fback_name_Wbb);
   
    
   // --- Register the training and test trees
  TTree *signal_WH     = (TTree*)sig_input_WH->Get("OutputTree");
  TTree *background_TT = (TTree*)back_input_TT->Get("OutputTree"); 
  TTree * background_Wbb = (TTree*)back_input_Wbb->Get("OutputTree");
  
  
 
  // --- global event weights per tree (see below for setting event-wise weights)
  Double_t signalWeight_WH     = 1;
  Double_t backgroundWeight_TT = 1;
  Double_t backgroundWeight_Wbb= 1;
  
  
  
  // --- Here can add an arbitrary number of signal or background trees
  factory->AddSignalTree    ( signal_WH,     signalWeight_WH     );
  factory->AddBackgroundTree( background_TT, backgroundWeight_TT );
  factory->AddBackgroundTree( background_Wbb, backgroundWeight_Wbb);


 Float_t nhiggsJetSubjets;
  Float_t njets;
  Float_t deltaPhiWH;
  Float_t jetPt[11];
  Float_t jetEta[11];
  Float_t jetPhi[11];
  Float_t jetE[11];
  Float_t higgsJetSubjetEta[3];
  Float_t higgsJetSubjetPhi[3];
  Float_t higgsJetSubjetPt[3];
  Float_t higgsJetSubjetE[3];
  Float_t Wphi;
  Float_t fatjetPt[15];
  Float_t fatjetEta[15];
  Float_t fatjetPhi[15];
  Float_t fatjetE[15];
  


  TLorentzVector fatjet(0,0,0,0);
  TLorentzVector subjet1(0,0,0,0);
  TLorentzVector subjet2(0,0,0,0);
  TLorentzVector subjet3(0,0,0,0);
  TLorentzVector akt[15];
  fatjet.SetPtEtaPhiE(fatjetPt[0],fatjetEta[0],fatjetPhi[0], fatjetE[0]);
  deltaPhiWH = std::fabs(Wphi-fatjetPhi[0]);
  if(deltaPhiWH>TMath::Pi()){ std::fabs(deltaPhiWH = 2*TMath::Pi()-deltaPhiWH);} 


  float deltaEta[3][11];
  float deltaPhi[3][11];
  float DeltaR[3][13];
  
  for(int j = 0; j<nhiggsJetSubjets; j++){
    for(int i = 0; i<njets; i++){
      deltaEta[j][i] = std::fabs(higgsJetSubjetEta[j]-jetEta[i]);
      deltaPhi[j][i] = std::fabs(higgsJetSubjetPhi[j]-jetPhi[i]);
      
      DeltaR[j][i] = std::sqrt(deltaEta[j][i]*deltaEta[j][i]+deltaPhi[j][i]*deltaPhi[j][i]);
    }
  }

   for (int i=0; i < njets; i++) {
	   akt[i].SetPtEtaPhiE(jetPt[i],jetEta[i],jetPhi[i], jetE[i]);
	 }

	 subjet1.SetPtEtaPhiE(higgsJetSubjetPt[0],higgsJetSubjetEta[0],higgsJetSubjetPhi[0], higgsJetSubjetE[0]);
	 subjet2.SetPtEtaPhiE(higgsJetSubjetPt[1],higgsJetSubjetEta[1],higgsJetSubjetPhi[1], higgsJetSubjetE[1]);
	 FatHiggs = subjet1 + subjet2;


	 if (nhiggsJetSubjets>2){
	   subjet3.SetPtEtaPhiE(higgsJetSubjetPt[2],higgsJetSubjetEta[2],higgsJetSubjetPhi[2], higgsJetSubjetE[2]);
	 }



  
   
  // To give different trees for training and testing, do:
  //    factory->AddSignalTree( signalTrainingTree, signalTrainWeight, "Training" );
  //    factory->AddSignalTree( signalTestTree,     signalTestWeight,  "Test" );
   

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


  // --- Apply additional cuts on the signal and background samples (can be different)
  // PLEASE NOTE: If no cuts are required, do NOT leave any spaces between quotation marks, otherwise an error will occur.
  TCut mycuts = "deltaPhiWH>-800"; //Signal Tree Cuts
  TCut mycutb = "deltaPhiWH>-800"; //Background Tree Cuts

  //cout << "DeltaPhiWH: " << deltaPhiWH << endl;
  

  // Tell the factory how to use the training and testing events
  //
  // If no numbers of events are given, half of the events in the tree are used 
  // for training, and the other half for testing:
  //    factory->PrepareTrainingAndTestTree( mycut, "SplitMode=random:!V" );
  // To also specify the number of testing events, use:
  //    factory->PrepareTrainingAndTestTree( mycut,
  //                                         "NSigTrain=3000:NBkgTrain=3000:NSigTest=3000:NBkgTest=3000:SplitMode=Random:!V" );
  factory->PrepareTrainingAndTestTree( mycuts, mycutb,
				       "nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:!V:NormMode=NumEvents");

  // ---- 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[1]=0:CutRangeMax[1]=450:VarProp[1]=FMax:EffSel:Steps=60:Cycles=3:PopSize=2000: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.0333: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" );

  // 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: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" );

  // 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=350:nEventsMin=100:MaxDepth=3:BoostType=Grad:Shrinkage=0.05:UseBaggedGrad:GradBaggingFraction=0.51:nCuts=65:PruneStrength=2:PruneMethod=ExpectedError:NNodesMax=7" ); 
  //"!H:!V:NTrees=350:nEventsMin=100:MaxDepth=3:BoostType=Grad:Shrinkage=0.05:UseBaggedGrad:GradBaggingFraction=0.55:nCuts=50:PruneStrength=2:PruneMethod=ExpectedError:NNodesMax=10" ); //nCuts=20 && no pruning originally

  if (Use["BDT"])  // Adaptive Boost
    factory->BookMethod( TMVA::Types::kBDT, "BDT",
			 "NTrees=550:nEventsMin=110:MaxDepth=5.5:BoostType=AdaBoost:AdaBoostBeta=0.5:SeparationType=GiniIndex:nCuts=10:PruneStrength=6:PruneMethod=ExpectedError");

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

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

  // 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" );


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

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

  // factory->OptimizeAllMethods("SigEffAt001","Scan");
  // factory->OptimizeAllMethods("SigEffAt001","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;

  delete factory;

  // Launch the GUI for the root macros
  if (!gROOT->IsBatch()) TMVAGui( outfileName );
}
void TMVAClassification( ) 
{
   // this loads the library
   TMVA::Tools::Instance();
   std::cout << std::endl;
   std::cout << "==> Start TMVAClassification" << std::endl;

   // Create a new root output file.
   TString outfileName( "TMVA.root" );
   TFile* outputFile = TFile::Open( outfileName, "RECREATE" );

   // Create the factory object.
   TMVA::Factory *factory = new TMVA::Factory( "TMVAClassification", outputFile, 
                                               "!V:!Silent:Color:DrawProgressBar:Transformations=I;D;P;G,D" );

   // ---------- input variables 
   factory->AddVariable("iso12x12", 'F');
   factory->AddVariable("iso4x4", 'F');
   factory->AddVariable("isoLshaped", 'F');
   factory->AddVariable("PUM0", 'F');

   // ---------- spectators ----------------
   factory->AddSpectator("pt", "F");
   factory->AddSpectator("eta", "F");
   factory->AddSpectator("phi", "F");
   factory->AddSpectator("e", "F");

   // read training and test data
   TString fSig = "DrellYan_Zee.root";
   TString fBkg = "MinBias.root";

   TFile *fileSig = TFile::Open( fSig );
   TFile *fileBkg = TFile::Open( fBkg );
   TTree *signal     = (TTree*)fileSig->Get("tree");
   TTree *background = (TTree*)fileBkg->Get("tree");
   

   // global event weights per tree (see below for setting event-wise weights)
   Double_t signalWeight     = 1.0;
   Double_t backgroundWeight = 1.0;

   // ====== register trees ====================================================
   // you can add an arbitrary number of signal or background trees
   factory->AddSignalTree    ( signal,     signalWeight     );
   factory->AddBackgroundTree( background, backgroundWeight );
   TCut mycuts = "pt > 10"; 
   TCut mycutb = "pt > 10"; 


   // tell the factory to use all remaining events in the trees after training for testing:
   factory->PrepareTrainingAndTestTree( mycuts, mycutb,
                                        "nTrain_Signal=0:nTrain_Background=0:SplitMode=Random:NormMode=NumEvents:!V" );

   // If no numbers of events are given, half of the events in the tree are used for training, and 
   // the other half for testing:

   // ---- Book MVA methods
   // Boosted Decision Trees
   factory->BookMethod( TMVA::Types::kBDT, "BDT", 
                        "!H:!V:NTrees=400:nEventsMin=400:MaxDepth=3:BoostType=AdaBoost:SeparationType=GiniIndex:nCuts=20:PruneMethod=NoPruning" );
   
   // ---- Train MVAs using the set of training events
   factory->TrainAllMethods();
   
   // ---- Evaluate all MVAs using the set of test events
   factory->TestAllMethods();

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

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

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

   delete factory;

   // Launch the GUI for the root macros
   if (!gROOT->IsBatch()) TMVAGui( outfileName );
}
void TAnalysisOfAlignment::DoEtaCorrection(UInt_t correctionStep){
	cout<<"****************************************"<<endl;
	cout<<"Do Eta correction for all silicon planes "<<correctionStep<< endl;
	cout<<"****************************************"<<endl;
	vector<TH1F*> histoStripDistribution,histoStripDistributionFlattned;
	vector<TH1F *>vecHEta;
	//	stringstream fileName;
	//	fileName<<	"etaIntegral_Step"<<correctionStep<<"."<<settings->getRunNumber()<<".root";
	TFile* correctedEtaFile = new TFile(settings->getEtaDistributionPath(correctionStep).c_str(),"RECREATE");
	cout<<"create Histos..."<<endl;
	for(UInt_t det=0; det<TPlaneProperties::getNSiliconDetectors();det++){
		stringstream histoTitle;
		histoTitle<<"hPredictedStripPosition"<<"_step"<<correctionStep<<"_"<<TPlaneProperties::getStringForDetector(det);
		histoStripDistribution.push_back(new TH1F(histoTitle.str().c_str(),histoTitle.str().c_str(),128,-0.501,0.501));
		histoTitle<<"_flattend";
		histoStripDistributionFlattned.push_back(new TH1F(histoTitle.str().c_str(),histoTitle.str().c_str(),128,-0.501,0.501));
		histoTitle.str("");
		histoTitle.clear();
		histoTitle<<"hCorrectedEtaDistribution"<<"_step"<<correctionStep<<"_"<<TPlaneProperties::getStringForDetector(det);
		vecHEta.push_back(new TH1F(histoTitle.str().c_str(),histoTitle.str().c_str(),128,0,1));
	}

	cout<<"fill first strip hit histo"<<eventReader->GetEntries()<<endl;

	for( nEvent=0;nEvent<eventReader->GetEntries();nEvent++){
		TRawEventSaver::showStatusBar(nEvent,eventReader->GetEntries());
		eventReader->LoadEvent(nEvent);
		if(!eventReader->useForAnalysis()&&!eventReader->useForAlignment())
			continue;
		for(UInt_t subjectPlane =0; subjectPlane<TPlaneProperties::getNSiliconPlanes();subjectPlane++){
			//			if(!eventReader->useForAlignment()&&!eventReader->useForAnalysis())
			//				continue;
			vector<UInt_t>vecRefPlanes;
			for(UInt_t refPlane=0;refPlane<TPlaneProperties::getNSiliconPlanes();refPlane++)
				if(subjectPlane!=refPlane)vecRefPlanes.push_back(refPlane);
			TPositionPrediction* pred = eventReader->predictPosition(subjectPlane,vecRefPlanes,false);
			Float_t predictedStripPositionX = eventReader->getPositionInDetSystem(subjectPlane*2,pred->getPositionX(),pred->getPositionY());
			Float_t predictedStripPositionY = eventReader->getPositionInDetSystem(subjectPlane*2+1,pred->getPositionX(),pred->getPositionY());
			UInt_t stripMiddleX=(UInt_t) (predictedStripPositionX+0.5);
			Float_t deltaX = predictedStripPositionX-stripMiddleX;
			UInt_t stripMiddleY=(UInt_t) (predictedStripPositionY+0.5);
			Float_t deltaY = predictedStripPositionY-stripMiddleY;
			//			cout<<nEvent<<": "<<subjectPlane<<"Fill "<<deltaX<<" "<<deltaY<<endl;
			histoStripDistribution.at(subjectPlane*2)->Fill(deltaX);
			histoStripDistribution.at(subjectPlane*2+1)->Fill(deltaY);
			chi2Distribution();
		}
	}
	saveHistos();
	vector<UInt_t> vecMinEntries;
	cout<<"Minimal Entries in a bin of historgram:"<<endl;
	for(UInt_t det=0;det<TPlaneProperties::getNSiliconDetectors();det++){
		TH1F* histo=histoStripDistribution.at(det);
		Int_t minBin =      histo->GetMinimumBin();
		Int_t nMinEntries = histo->GetBinContent(minBin);
		cout<<endl<< det<< ": "<<minBin<<" "<<nMinEntries<<"\t";
		vecMinEntries.push_back(nMinEntries);
	}
	cout<<"\n\n"<<endl;

	vector<UInt_t>vecEventNo[9];
	cout<<"create flattened strip hit histo "<<eventReader->GetEntries()<<endl;
	for( nEvent=0;nEvent<eventReader->GetEntries();nEvent++){
		TRawEventSaver::showStatusBar(nEvent,eventReader->GetEntries());
		eventReader->LoadEvent(nEvent);
		if(!eventReader->useForAnalysis()&&!eventReader->useForAlignment())
			continue;

		for(UInt_t subjectPlane=0; subjectPlane<TPlaneProperties::getNSiliconPlanes();subjectPlane++){
			//			if(!eventReader->useForAlignment()&&!eventReader->useForAnalysis())
			//				continue;
			vector<UInt_t>refPlanes;
			for(UInt_t refPlane=0;refPlane<TPlaneProperties::getNSiliconPlanes();refPlane++)
				if(subjectPlane!=refPlane)refPlanes.push_back(refPlane);
			TPositionPrediction* pred = eventReader->predictPosition(subjectPlane,refPlanes,false);

			Float_t predictedStripPositionX = eventReader->getPositionInDetSystem(subjectPlane*2,pred->getPositionX(),pred->getPositionY());
			Float_t predictedStripPositionY = eventReader->getPositionInDetSystem(subjectPlane*2+1,pred->getPositionX(),pred->getPositionY());
			UInt_t stripMiddleX=(UInt_t) (predictedStripPositionX+0.5);
			Float_t deltaX = predictedStripPositionX-stripMiddleX;
			//			histoStripDistribution.at(subjectPlane*2)->Fill(deltaX);
			UInt_t stripMiddleY=(UInt_t) (predictedStripPositionY+0.5);
			Float_t deltaY = predictedStripPositionY-stripMiddleY;
			//			histoStripDistribution.at(subjectPlane*2)->Fill(deltaY);

			Int_t binX=histoStripDistributionFlattned.at(subjectPlane)->FindBin(deltaX);
			Int_t binY=histoStripDistributionFlattned.at(subjectPlane)->FindBin(deltaY);
			if(histoStripDistributionFlattned.at(subjectPlane*2)->GetBinContent(binX)<vecMinEntries.at(subjectPlane*2)){
				vecEventNo[subjectPlane*2].push_back(nEvent);
				histoStripDistributionFlattned.at(subjectPlane*2)->Fill(deltaX);
			}
			if(histoStripDistributionFlattned.at(subjectPlane*2+1)->GetBinContent(binY)<vecMinEntries.at(subjectPlane*2+1)){
				vecEventNo[subjectPlane*2+1].push_back(nEvent);
				histoStripDistributionFlattned.at(subjectPlane*2+1)->Fill(deltaY);
			}
		}
	}
	for(UInt_t det =0; det<TPlaneProperties::getNSiliconDetectors();det++){
		cout<<"save histogram: "<<det<<"  "<<histoStripDistributionFlattned.at(det)->GetTitle()<<"  "<<histoStripDistribution.at(det)->GetTitle()<<endl;
		histSaver->SaveHistogram(histoStripDistributionFlattned.at(det));
		correctedEtaFile->Add(histoStripDistributionFlattned.at(det));
		histSaver->SaveHistogram(histoStripDistribution.at(det));
		correctedEtaFile->Add(histoStripDistribution.at(det));
	}

	cout<<"\n\ncreate eta correction histo"<<endl;
	for(UInt_t det =0; det<TPlaneProperties::getNSiliconDetectors();det++){
		for(UInt_t i=0;i<vecEventNo[det].size();i++){
			nEvent= vecEventNo[det].at(i);
			eventReader->LoadEvent(nEvent);

			if(!eventReader->useForAlignment()&&!eventReader->useForAnalysis())
				continue;
			Float_t eta = eventReader->getCluster(det,0).getEta();
			vecHEta.at(det)->Fill(eta);

		}

		stringstream histName;
		histName<<"hEtaIntegral"<<"_step"<<correctionStep<<"_"<<TPlaneProperties::getStringForDetector(det);;
		//			UInt_t nBins = vecHEta.at(det)->GetNbinsX();
		TH1F *histo= TClustering::createEtaIntegral(vecHEta.at(det),histName.str());
		cout<<"save "<<vecHEta.at(det)->GetTitle()<<" "<<vecHEta.at(det)->GetEntries()<<endl;
		histSaver->SaveHistogram(vecHEta.at(det));
		correctedEtaFile->Add(vecHEta.at(det));
		cout<<"save "<<histo->GetTitle()<<" "<<histo->GetEntries()<<endl;
		histSaver->SaveHistogram(histo);
		correctedEtaFile->Add((TH1F*)histo->Clone());
	}
	correctedEtaFile->Write();
	cout<<"Closing "<<correctedEtaFile->GetName()<<endl;
	for(UInt_t i=0;i<histoStripDistribution.size();i++)
		cout<<histoStripDistribution.at(i)<<" "<<flush;
	cout<<endl;
	for(UInt_t i =0;i<histoStripDistribution.size();i++)
		cout<<histoStripDistributionFlattned.at(i)<<" "<<flush;
	cout<<endl;
	for(UInt_t i =0;i<histoStripDistribution.size();i++)
		cout<<vecHEta.at(i)<<" "<<flush;

}