コード例 #1
0
//=============================================================================
// Standard constructor, initializes variables
//=============================================================================
void makeLongTracksonlyunnormalized(  ) {
  gROOT->SetBatch(kTRUE);
  TString tuplelocation = "/afs/cern.ch/work/m/mwilkins/b_b-bar_cross-section/";
  TString data2011tuple = tuplelocation+"Strp20r1_SL_D0andDp_MD.root";
  TString MC2011tuple = tuplelocation+"MC_2011_Bu_D0Xmunu_cocktail_12873441_MC2011_S20r1_noPID_Tuples.root";
  TString data2015tuple = tuplelocation+"B2DMuNuX_tuples_05082015.root";
  TString MC2015tuple = tuplelocation+"MC_2015_Bu_D0Xmunu_cocktail_12873441_MC2015_S22_noPID_Tuples.root";
  TFile *f[4];
  f[0] = TFile::Open(data2011tuple);
  f[1] = TFile::Open(MC2011tuple);
  f[2] = TFile::Open(data2015tuple);
  f[3] = TFile::Open(MC2015tuple);
  cout<<"files opened"<<endl;
  
  const int nhpc = 2; //number of histograms per canvas
  const int ncanvases = 4;
  const int nstacks = ncanvases;
  THStack *hs[nstacks];
  TCanvas *c[ncanvases];
  TH1F *h[ncanvases][nhpc];
  TLegend *leg[ncanvases];
  TString outputlocation = "output/longtracksplotsunnormalized/";//where the output will be saved
  TString plotfilename = "longtracksplotsunnormalized.pdf";//name of file that will hold drawn plots

  TCanvas *cf = new TCanvas("cf","combined");//canvas to hold everything
  float sqnc = sqrt(ncanvases), sqncu = ceil(sqnc), sqncd = floor(sqnc);
  while(sqncu*sqncd<ncanvases) sqncu++;
  cf->Divide(sqncu,sqncd);
  TLegend *legf = new TLegend(0.84, 0.84, .99, .95);

  TString placeholder; //to avoid adding strings within functions; assign immediately before use
  TString placeholder2;
  
  cout<<"starting canvas loop..."<<endl;
  for(int ci =0; ci<ncanvases; ci++){ //loop over canvases
    //create indicators and strings:
    int year;
    if(ci<(ncanvases/2)){//2011 for 1st half canvases, 2015 for 2nd half
      year = 2011;
    }else year = 2015;
    TString yearstring = Form("%d",year);
    TString filetype; //assigned in histogram loop
    TString tracktype = "nLongTracks";
    int B0;//assigned in histogram loop
    TString Bdecay;
    TString branch;

    TString cistring = Form("%d",ci);
    cout<<"loop "<<ci<<" indicators and strings created:"<<endl<<"year: "<<year<<endl;

    //create the plots
    placeholder = "c"+cistring;
    placeholder2=yearstring+filetype+tracktype;
    c[ci] = new TCanvas(placeholder,placeholder2,1200,800); //create the canvases
    c[ci]->cd();
    gStyle->SetOptStat("");
    leg[ci] = new TLegend(0.7, 0.7, .97, .93);//create legend
    placeholder = "hs"+cistring;
    hs[ci] = new THStack(placeholder,placeholder2); //create the stack to hold the histograms
    cout<<"starting histogram loop..."<<endl;
    for(int hi=0;hi<nhpc;hi++){ //loop over histograms in a canvas; B0=0 and B0=1
      if(hi%2==0){//true every other histogram
        filetype = "data";
      }else filetype = "MC";
      int file_num=-1000;//assign file_num based on combinations of data and MC
      if(year==2011){
        if(filetype=="data") file_num=0;
        if(filetype=="MC") file_num=1;
      }
      if(year==2015){
        if(filetype=="data") file_num=2;
        if(filetype=="MC") file_num=3;
      }
      cout<<"file_num: "<<file_num<<endl;
      if(ci%2 ==0){//every other canvas
        B0=0;
        Bdecay = "B^{-}->(D^{0}->K^{-} #pi^{+})#mu^{-}";
        if((filetype=="data")&&(year==2011)){
          branch="tupleb2D0Mu/tupleb2D0Mu"; 
        } else branch="Tuple_b2D0MuX/DecayTree"; 
      } else{
        B0=1;
        Bdecay = "B^{0}->(D^{-}->K^{+} #pi^{-} #pi^{-})#mu^{+}";
        if((filetype=="data")&&(year==2011)){
          branch="tupleb2DpMu/tupleb2DpMu"; 
        } else branch="Tuple_b2DpMuX/DecayTree"; 
      }
      //create convenient strings
      TString histring = Form("%d",hi);
      TString hname = "h"+cistring+histring;
      
      //create histograms
      if(tracktype=="nLongTracks") h[ci][hi] = new TH1F(hname,tracktype,131,0,262);
      cout<<"histogram loop "<<hi<<" strings and histograms created"<<endl;
      //navigate files
      cout<<"navigating file..."<<endl;
      TTree *MyTree;
      f[file_num]->GetObject(branch,MyTree);
      //draw histograms
      cout<<"drawing histogram "<<hi<<"..."<<endl;
      cout<<"branch: "<<branch<<endl;
      h[ci][hi]->SetLineColor(hi+1);
      placeholder = tracktype+">>"+hname;
      MyTree->Draw(placeholder);
      cout<<"stacking histogram "<<hi<<"..."<<endl;
      hs[ci]->Add(h[ci][hi]);//stack histograms
      leg[ci]->AddEntry(h[ci][hi],filetype,"l");//fill legend
      if(ci==0) legf->AddEntry(h[ci][hi],filetype,"l");//fill combined legend; all the same, so using the first one is fine
    }
    //draw stacked histograms
    cout<<"drawing stack "<<ci<<"..."<<endl;
    placeholder = yearstring+": "+Bdecay+": "+tracktype;
    hs[ci]->SetTitle(placeholder);
    hs[ci]->Draw("nostack");
    leg[ci]->Draw();
    cf->cd(ci+1);
    hs[ci]->Draw("nostack");//not using c[ci]->DrawClonePad(); because too many legends
    //save stuff:
    cout<<"saving files..."<<endl;
    placeholder = outputlocation+plotfilename+"(";//the closing page is added after the loop
    c[ci]->Print(placeholder);
    placeholder = outputlocation+"c"+cistring+".C";
    c[ci]->SaveAs(placeholder);
    cout<<endl;
  }
  cf->cd();
  legf->Draw();
  placeholder = outputlocation+plotfilename+")";
  cf->Print(placeholder);
  gROOT->SetBatch(kFALSE);
  cout<<"done"<<endl;
}
コード例 #2
0
int main (int argc, char **argv) {
    
    std::string type = argv[1];   // type "gg" or "qq"
    int bin = atoi(argv[2]);
    int binp1 = bin+100;          // pt bin
    int min = atoi(argv[3]);      // events to run over
    int max = atoi(argv[4]);      // events to run over
    std::string tag = argv[5];
    float rVal = atof(argv[6]);
    
    char inName[192];
    //sprintf( inName, "dataProcessedFinal/LHEFiles/%s-pt%04i-%04i-100k.lhe", type.c_str(), bin, bin+100 );
    // sprintf( inName, "dataProcessedFinal/LHEFiles/%s.lhe", type.c_str() );
    sprintf( inName, "dataLHE/%s-pt%04i-%04i-100k.lhe", type.c_str(), bin, bin+100 );
    std::cout << "fname = " << inName << std::endl;
    std::ifstream ifsbkg (inName) ;
    LHEF::Reader reader(ifsbkg) ;

    char outName[192];
    int rInt = (int) (rVal*10.);
    sprintf( outName, "dataProcessedFinalSCOT/boost2013-%s-pt%04i-%04i%s_ak%02i.root", type.c_str(), bin, bin+100, tag.c_str(), rInt );
    TFile *f = TFile::Open(outName,"RECREATE");
    TTree *t = new TTree("t","Tree with vectors");
    t->Branch("njets"      , &njets      );
    t->Branch("jpt"        , &jpt        );
    t->Branch("jeta"       , &jeta       );
    t->Branch("jmass"      , &jmass      );
    t->Branch("jtau1_b1"   , &jtau1_b1   );
    t->Branch("jtau2_b1"   , &jtau2_b1   );
    t->Branch("jtau1_b2"   , &jtau1_b2   );
    t->Branch("jtau2_b2"   , &jtau2_b2   );
    t->Branch("jtau21_b1"   , &jtau21_b1   );
    t->Branch("jtau21_b2"   , &jtau21_b2   );
    t->Branch("jc1_b0"      , &jc1_b0      );
    t->Branch("jc1_b1"      , &jc1_b1      );
    t->Branch("jc1_b2"      , &jc1_b2      );
    t->Branch("jc2_b1"      , &jc2_b1      );
    t->Branch("jc2_b2"      , &jc2_b2      );
    t->Branch("jd2_b1"      , &jd2_b1      );
    t->Branch("jd2_b2"      , &jd2_b2      );
    t->Branch("j_qjetVol"   , &j_qjetVol      );
    t->Branch("j_mass_trim"      , &j_mass_trim      );
    t->Branch("j_mass_mmdt"      , &j_mass_mmdt      );
    t->Branch("j_mass_prun"      , &j_mass_prun      );
    t->Branch("j_mass_sdb2"      , &j_mass_sdb2      );
    t->Branch("j_mass_sdm1"      , &j_mass_sdm1      );
    t->Branch("j_multiplicity"   , &j_multiplicity      );
            
    evtCtr = 0;
    std::vector < fastjet::PseudoJet > particles;

    // loop over events
    while ( reader.readEvent () ) {
        ++evtCtr;
        if (evtCtr % 1000 == 0) std::cout << "event " << evtCtr << "\n";
        if (evtCtr < min) continue;
        if (evtCtr > max) break;
        
        // per event
        particles.clear();
        jpt.clear();
        jeta.clear();
        jmass.clear();
        jtau1_b1.clear();
        jtau2_b1.clear();
        jtau1_b2.clear();
        jtau2_b2.clear();
        jtau21_b1.clear();
        jtau21_b2.clear();
        jc1_b0.clear();
        jc1_b1.clear();
        jc1_b2.clear();
        jc2_b1.clear();
        jc2_b2.clear();
        jd2_b1.clear();
        jd2_b2.clear();
        j_qjetVol.clear();
        j_mass_trim.clear();
        j_mass_mmdt.clear();
        j_mass_prun.clear();
        j_mass_sdb2.clear();
        j_mass_sdm1.clear();
        j_multiplicity.clear();
        
        for (unsigned int i = 0 ; i < reader.hepeup.IDUP.size(); ++i){

            if (reader.hepeup.ISTUP.at(i) == 1){
                float px = reader.hepeup.PUP.at(i).at(0);
                float py = reader.hepeup.PUP.at(i).at(1);
                float pz = reader.hepeup.PUP.at(i).at(2);
                float e  = reader.hepeup.PUP.at(i).at(3);                                    
                particles.push_back( fastjet::PseudoJet( px, py, pz, e ) );
            }   
        }
        analyzeEvent( particles, rVal );
        t->Fill();
        
    }
    
    std::cout << "finish loop" << std::endl;
    
    f->cd();
    t->Write();
    f->Close();
    
    delete f;
    return 0 ;
}
コード例 #3
0
ファイル: skimTree.C プロジェクト: ramankhurana/usercode
void skimTree(std::string inputFile_)
{

  
  TFile *f = (TFile*)gROOT->GetListOfFiles()->FindObject(inputFile_.data());
  if (!f) {
    f = new TFile(inputFile_.data());
    f->cd(Form("%s:/tree",inputFile_.data()));
  }
  TTree* fChain = (TTree*)gDirectory->Get("tree");
  cout << "Input file is " << inputFile_ << endl;

  // rename the output file
  std::string remword=".root";
  size_t pos = inputFile_.find(remword);
  std::string forOutput = inputFile_;  
  if(pos!= std::string::npos)
    forOutput.swap(forOutput.erase(pos,remword.length()));   
  std::string endfix = "_filteredtree.root";
  std::string outputFile = forOutput + endfix;
  // now open new root file
  TFile* newfile_data = new TFile(outputFile.data(),"recreate");
  cout << "Output file " << outputFile << endl;

  // clone tree
  TTree* newtree = fChain->CloneTree(0);
  newtree->SetMaxTreeSize(4000000000);
  cout << "Saving "  << endfix << " tree" << endl;

  Long64_t nentries = fChain->GetEntries();
  cout << "nentries = " << nentries << endl;

  Int_t           eventNo=-1;
  Int_t           runNo=-1;

  vector<int>*     trigResults;
  vector<string>*  trigName;


  bool isData=false;
  if(forOutput.find("DoubleElectron")!= std::string::npos || forOutput.find("DoubleMu")!= std::string::npos)
    isData=true;


  fChain->SetBranchAddress("EvtInfo_EventNum",&eventNo);
  fChain->SetBranchAddress("EvtInfo_RunNum",&runNo);
  if(isData){
    fChain->SetBranchAddress("trigResults", &trigResults);
    fChain->SetBranchAddress("trigName", &trigName);
  }

  Long64_t nlines=0;

  vector<runInfo> myList;

  ifstream fin;

  if(forOutput.find("DoubleElectron")!= std::string::npos)
    fin.open("/data4/syu/52X_533_validation/DoubleElectron_common.txt");
  else if(forOutput.find("DoubleMu")!= std::string::npos)
    fin.open("/data4/syu/52X_533_validation/DoubleMu_common.txt");
  else if(forOutput.find("GluGlu")!= std::string::npos)
    fin.open("/data4/syu/52X_533_validation/MC_common.txt");
  runInfo tempInfo;
  fin >> tempInfo.run >> tempInfo.evt;
  while(!fin.eof())
    {
      nlines++;
      myList.push_back(tempInfo);
      fin >> tempInfo.run >> tempInfo.evt;
    }
  fin.close();

  cout << "There are " << nlines << " lines" << endl;

  ofstream fout;
  fout.open(Form("%s_updated",forOutput.data()));

  Long64_t nPassEvt=0;

  for (Long64_t jentry=0; jentry<nentries;jentry++) {

    
    eventNo = -1;
    runNo = -1;
    trigName = 0;
    trigResults = 0;
    
    fChain->GetEntry(jentry);


    bool passTrigger=false;
    if(isData){

      for(int it=0; it< trigName->size(); it++)
	{
	  std::string thisTrig= trigName->at(it);
	  int results = trigResults->at(it);
//   	  cout << thisTrig << "\t" << results << endl;

	  if(forOutput.find("DoubleElectron")!= std::string::npos && 
	     thisTrig.find("HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL")
	     != std::string::npos && results==1)
	    {
	      passTrigger=true;
// 	      cout << "Find HLT_Ele17_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL_Ele8_CaloIdT_CaloIsoVL_TrkIdVL_TrkIsoVL" << endl;
	      break;
	    }	  

	  if(forOutput.find("DoubleMu")!= std::string::npos && thisTrig.find("HLT_Mu17_Mu8")!= std::string::npos && results==1)
	    {
	      passTrigger=true;
// 	      cout << "Find HLT_Mu17_Mu8" << endl;
	      break;
	    }

	  if(forOutput.find("DoubleMu")!= std::string::npos && thisTrig.find("HLT_Mu17_TkMu8")!= std::string::npos && results==1)
	    {
	      passTrigger=true;
// 	      cout << "Find HLT_Mu17_TkMu8" << endl;
	      break;
	    }

	}

    }
    if(!passTrigger && isData)continue;

    bool pass=false;

    runInfo thisInfo;
    thisInfo.run = runNo;
    thisInfo.evt = eventNo;

    vector<runInfo>::const_iterator location = std::find(myList.begin(), myList.end(), thisInfo);
    if(location != myList.end()) pass=true;

    if(!pass)continue;
    newtree->Fill();
    nPassEvt++;
    fout << runNo << "\t" << eventNo << endl;

    if (jentry%100==0)
      printf("%4.1f%% done.\r",(float)jentry/(float)nentries*100.);		

  }
 
  newtree->Print();
  newtree->AutoSave();
  delete newfile_data;

  fout.close();

  cout << "Number of passed events = " << nPassEvt << endl;
}
コード例 #4
0
ファイル: bit_combinations.C プロジェクト: c-dilks/scalers11t
void bit_combinations(const char * filename="counts.root")
{
  TFile * infile = new TFile(filename,"READ");
  TTree * acc = (TTree*) infile->Get("acc");

  // set branch addresses
  Int_t index,runnum,fill_index,fill;
  Double_t t;
  Double_t bbc[8];
  Double_t zdc[8];
  //Double_t vpd[4];
  Double_t vpd[8];
  Double_t tot_bx;
  Int_t blue,yell;
  acc->SetBranchAddress("i",&index);
  acc->SetBranchAddress("runnum",&runnum);
  acc->SetBranchAddress("fi",&fill_index);
  acc->SetBranchAddress("fill",&fill);
  acc->SetBranchAddress("t",&t);
  acc->SetBranchAddress("tot_bx",&tot_bx);
  acc->SetBranchAddress("blue",&blue);
  acc->SetBranchAddress("yell",&yell);
  char bbc_br[8][16];
  char zdc_br[8][16];
  //char vpd_br[4][16];
  char vpd_br[8][16];
  for(Int_t i=0; i<8; i++)
  {
    sprintf(bbc_br[i],"bbc_%d",i);
    sprintf(zdc_br[i],"zdc_%d",i);
    acc->SetBranchAddress(bbc_br[i],&(bbc[i]));
    acc->SetBranchAddress(zdc_br[i],&(zdc[i]));
    //if(i<4) 
    //{
      sprintf(vpd_br[i],"vpd_%d",i);
      acc->SetBranchAddress(vpd_br[i],&(vpd[i]));
    //};
  };

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

  // total counts vs. scaler bit bar charts
  TH1F * ntot_vs_bits_bbc = new TH1F();
  TH1F * ntot_vs_bits_zdc = new TH1F();
  TH1F * ntot_vs_bits_vpd = new TH1F();


  // scaler bit combination names
  char comb[8][16];
  strcpy(comb[0],"none");
  strcpy(comb[1],"e");
  strcpy(comb[2],"w");
  strcpy(comb[3],"w+e");
  strcpy(comb[4],"x");
  strcpy(comb[5],"x+e");
  strcpy(comb[6],"x+w");
  strcpy(comb[7],"x+w+e");

  // fill bar charts
  for(Int_t i=0; i<acc->GetEntries(); i++)
  {
    acc->GetEntry(i);
    for(Int_t j=0; j<8; j++)
    {
      ntot_vs_bits_bbc->Fill(comb[j],bbc[j]);
      ntot_vs_bits_zdc->Fill(comb[j],zdc[j]);
      //if(j<4) ntot_vs_bits_vpd->Fill(comb[j],vpd[j]);
      ntot_vs_bits_vpd->Fill(comb[j],vpd[j]);
    };
  };

  ntot_vs_bits_bbc->SetStats(0);
  ntot_vs_bits_bbc->SetTitle("total bbc counts vs. scaler bits");
  ntot_vs_bits_bbc->SetBarWidth(0.4);
  ntot_vs_bits_bbc->SetBarOffset(0.55);
  ntot_vs_bits_bbc->SetFillColor(50);
  TCanvas * c_bbc_bits = new TCanvas("c_bbc_bits","c_bbc_bits",700,500);
  c_bbc_bits->SetGrid(0,1);
  c_bbc_bits->SetLogy();
  ntot_vs_bits_bbc->Draw("bar2");

  ntot_vs_bits_zdc->SetStats(0);
  ntot_vs_bits_zdc->SetTitle("total zdc counts vs. scaler bits");
  ntot_vs_bits_zdc->SetBarWidth(0.4);
  ntot_vs_bits_zdc->SetBarOffset(0.55);
  ntot_vs_bits_zdc->SetFillColor(50);
  TCanvas * c_zdc_bits = new TCanvas("c_zdc_bits","c_zdc_bits",700,500);
  c_zdc_bits->SetGrid(0,1);
  c_zdc_bits->SetLogy();
  ntot_vs_bits_zdc->Draw("bar2");

  ntot_vs_bits_vpd->SetStats(0);
  ntot_vs_bits_vpd->SetTitle("total vpd counts vs. scaler bits");
  ntot_vs_bits_vpd->SetBarWidth(0.4);
  ntot_vs_bits_vpd->SetBarOffset(0.55);
  ntot_vs_bits_vpd->SetFillColor(50);
  TCanvas * c_vpd_bits = new TCanvas("c_vpd_bits","c_vpd_bits",700,500);
  c_vpd_bits->SetGrid(0,1);
  c_vpd_bits->SetLogy();
  ntot_vs_bits_vpd->Draw("bar2");

  char outdir[32];
  char bbc_outfile[64];
  char zdc_outfile[64];
  char vpd_outfile[64];
  strcpy(outdir,"bit_combos");
  sprintf(bbc_outfile,"%s/bbc_bit_combos.png",outdir);
  sprintf(zdc_outfile,"%s/zdc_bit_combos.png",outdir);
  sprintf(vpd_outfile,"%s/vpd_bit_combos.png",outdir);
  c_bbc_bits->Print(bbc_outfile,"png");
  c_zdc_bits->Print(zdc_outfile,"png");
  c_vpd_bits->Print(vpd_outfile,"png");
  printf("%s created\n",bbc_outfile);
  printf("%s created\n",zdc_outfile);
  printf("%s created\n",vpd_outfile);


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


  // get maximum number of runs  = IMAX
  Int_t IMAX_tmp = acc->GetMaximum("i");
  const Int_t IMAX = IMAX_tmp;


  // compute no. bXings with possible interaction in a given run
  Int_t nbx[IMAX]; 
  for(Int_t i=0; i<IMAX; i++) nbx[i]=0;
  for(Int_t i=0; i<acc->GetEntries(); i++)
  {
    acc->GetEntry(i);
    if(blue*yell != 0) nbx[index-1]++;
  };
};
コード例 #5
0
////////////////////////////////////
//     M      A     I     N      //
///////////////////////////////////
int main(int argc, char **argv)
{

  bool verbose = true;
  bool higgsDecay = true;

  // Define tree to fill
  TFile file(argv[2],"RECREATE");
  TTree* tree = new TTree("tree","tree");

  float mZ, mH, mVH, mT; //masses
  float costheta1, costheta2, costhetastar, phi, phi1; //angles
  float rapidityVH;
  int isLeptonic;
  int isUpTypeQuark;
  int passEta;
  int isWplus;  
  int decayMode;
  float b0_e, b0_eta, b0_phi, b0_pt;
  float b1_e, b1_eta, b1_phi, b1_pt;
  float f0_e, f0_eta, f0_phi, f0_pt;
  float f1_e, f1_eta, f1_phi, f1_pt;
  float V_e, V_eta, V_phi, V_pt;
  float H_e, H_eta, H_phi, H_pt;
  //float VH_e, VH_eta, VH_phi, VH_pt;


  tree->Branch("b0_e",   &b0_e,   "b0_e/F");
  tree->Branch("b0_eta", &b0_eta, "b0_eta/F");
  tree->Branch("b0_phi", &b0_phi, "b0_phi/F");
  tree->Branch("b0_pt",  &b0_pt,  "b0_pt/F");
  tree->Branch("b1_e",   &b1_e,   "b1_e/F");
  tree->Branch("b1_eta", &b1_eta, "b1_eta/F");
  tree->Branch("b1_phi", &b1_phi, "b1_phi/F");
  tree->Branch("b1_pt",  &b1_pt,  "b1_pt/F");
  tree->Branch("f0_e",   &f0_e,   "f0_e/F");
  tree->Branch("f0_eta", &f0_eta, "f0_eta/F");
  tree->Branch("f0_phi", &f0_phi, "f0_phi/F");
  tree->Branch("f0_pt",  &f0_pt,  "f0_pt/F");
  tree->Branch("f1_e",   &f1_e,   "f1_e/F");
  tree->Branch("f1_eta", &f1_eta, "f1_eta/F");
  tree->Branch("f1_phi", &f1_phi, "f1_phi/F");
  tree->Branch("f1_pt",  &f1_pt,  "f1_pt/F");
  tree->Branch("V_e",    &V_e,   "V_e/F");
  tree->Branch("V_eta",  &V_eta, "V_eta/F");
  tree->Branch("V_phi",  &V_phi, "V_phi/F");
  tree->Branch("V_pt",   &V_pt,  "V_pt/F");
  tree->Branch("H_e",    &H_e,   "H_e/F");
  tree->Branch("H_eta",  &H_eta, "H_eta/F");
  tree->Branch("H_phi",  &H_phi, "H_phi/F");
  tree->Branch("H_pt",   &H_pt,  "H_pt/F");
  //tree->Branch("VH_e",   &VH_e,   "VH_e/F");
  //tree->Branch("VH_eta", &VH_eta, "VH_eta/F");
  //tree->Branch("VH_phi", &VH_phi, "VH_phi/F");
  //tree->Branch("VH_pt",  &VH_pt,  "VH_pt/F");
  tree->Branch("mT",     &mT,     "mT/F");
  tree->Branch("mZ",     &mZ,     "mZ/F");
  tree->Branch("mH",     &mH,     "mH/F");
  tree->Branch("mVH",    &mVH,    "mVH/F");
  tree->Branch("costheta1",    &costheta1,    "costheta1/F");
  tree->Branch("costheta2",    &costheta2,    "costheta2/F");
  tree->Branch("costhetastar", &costhetastar, "costhetastar/F");
  tree->Branch("phi",          &phi,          "phi/F");
  tree->Branch("phi1",         &phi1,         "phi1/F");
  tree->Branch("rapidityVH",   &rapidityVH,   "rapidityVH/F");
  tree->Branch("isLeptonic",   &isLeptonic,   "isLeptonic/I");
  tree->Branch("isUpTypeQuark",&isUpTypeQuark,"isUpTypeQuark/I");
  tree->Branch("passEta",      &passEta,      "passEta/I");
  tree->Branch("isWplus",      &isWplus,      "isWplus/I");
  tree->Branch("decayMode",    &decayMode,    "decayMode/I");
  //Zee=0, Zmm=1, Ztt=2, Zuu=3, Zcc=4, Zdd=5, Zss=6, Zbb=7
  //Wen=8, Wmn=9, Wtn=10, Wud=11, Wcs=12
  //Znene=13, Znmnm=14, Zntnt=15

  // Reader object
  cout << "Creating reader object for input LHE file " << argv[1] << endl;
  std::ifstream ifsLHE (argv[1]) ;
  LHEF::Reader lheReader (ifsLHE) ;

  // Loop over events
  int eventCount = 0;
  int hadronicWCount = 0;
  int leptonicWCount = 0;
  int hadronicZCount = 0;
  int leptonicZCount = 0;
  int BR_Zee=0, BR_Zmm=0, BR_Ztt=0, BR_Znn=0, BR_Zuu=0, BR_Zcc=0, BR_Zdd=0, BR_Zss=0, BR_Zbb=0;
  int BR_Wen=0, BR_Wmn=0, BR_Wtn=0, BR_Wud=0, BR_Wcs=0;
  int BR_Znene=0, BR_Znmnm=0, BR_Zntnt=0;

  while ( lheReader.readEvent() ) 
    {
      eventCount++;
      if (eventCount % 100000 == 0 && verbose) std::cout << "Event " << eventCount << "\n" ;

      //Sanity check on number of particles
      if( higgsDecay==1 && lheReader.hepeup.IDUP.size() != 8 ) 
	{
	  cout << "Error! Expected 8 particles in the event but got " << lheReader.hepeup.IDUP.size() << endl;
	  return 0;
	}
      else if( higgsDecay==0 && lheReader.hepeup.IDUP.size() != 6 ) 
	{
	  cout << "Error! Expected 6 particles in the event but got " << lheReader.hepeup.IDUP.size() << endl;
	  return 0;
	}


      // Indices for particles of interest
      int i_f0 = -1; //final fermion particle
      int i_f1 = -1; //final fermion antiparticle 
      int i_b0 = -1; //final b particle
      int i_b1 = -1; //final b antiparticle 
      int i_H  = -1; //intermediate higgs 
      int i_V  = -1; //intermediate V  

      bool VisZ = false;
      bool VisW = false;
      decayMode = -1;
      
      std::vector<int> finalFermions ;

      // Loop over particles
      for (int iPart = 0 ; iPart < lheReader.hepeup.IDUP.size (); ++iPart){

	if( lheReader.hepeup.ISTUP.at (iPart) == -1  ) // incoming
	  {
	    //cout << "Event " << eventCount << ", incoming: " << lheReader.hepeup.IDUP.at (iPart) << endl;
	    //do nothing
	  }
	else if( lheReader.hepeup.ISTUP.at (iPart) == 2  ) // intermediate
	  {
	    
	    if( lheReader.hepeup.IDUP.at(iPart) == 25 ) //higgs
	      {
		i_H = iPart;
	      }
	    
	    if( lheReader.hepeup.IDUP.at(iPart) == 23) //Z
	      {
		i_V = iPart;
		VisZ = true;
	      }
	    
	    if( abs(lheReader.hepeup.IDUP.at(iPart)) == 24 ) //W+ or -
	      {
		i_V = iPart;
		VisW = true;
		isWplus=1;
		if(lheReader.hepeup.IDUP.at(iPart)==-24) isWplus=0;
	      }
	  }
	else if(  lheReader.hepeup.ISTUP.at (iPart) == 1 ) //outgoing 
	  {
	    //cout << "Event " << eventCount << ", outgoing: " << lheReader.hepeup.IDUP.at (iPart) << endl;
	    
	    if(higgsDecay==1) 
	      {
		if ( lheReader.hepeup.IDUP.at(iPart) == 5 ) i_b0 = iPart;
		if ( lheReader.hepeup.IDUP.at(iPart) == -5 ) i_b1 = iPart;
		if( abs(lheReader.hepeup.IDUP.at(iPart) ) == 5) continue;
	      }
	    
	    finalFermions.push_back (iPart) ;
	    if(     isFermion(lheReader.hepeup.IDUP.at(iPart)) ) i_f0 = iPart;
	    if( isAntiFermion(lheReader.hepeup.IDUP.at(iPart)) ) i_f1 = iPart;	 
	  }//end of outgoing if statement
	else { assert(0); } //sanity check that all particles are either incoming, intermediate, or outgoing.
	
      }// End loop over particles
      
      //some sanity checks
      assert( (VisZ && !VisW) || (VisW && !VisZ) );
      assert( finalFermions.size() == 2 ); //if not the case, have to be smarter with assigning i_f0 and i_f1
      assert( (i_f0 != -1) && (i_f1 != -1) && (i_H != -1) && (i_V != -1) );

      //Add to branching fraction counters and check if leptonic
      if( VisW && isQuark(lheReader.hepeup.IDUP.at(finalFermions.at(0))) && isQuark(lheReader.hepeup.IDUP.at(finalFermions.at(1))) ) //hadronic W
	{
	  hadronicWCount++;
	  isLeptonic=0;
	  isUpTypeQuark=0;
	}
      else if( VisW && isLepton(lheReader.hepeup.IDUP.at(finalFermions.at(0))) && isLepton(lheReader.hepeup.IDUP.at(finalFermions.at(1))) ) //leptonic W
	{
	  leptonicWCount++;
	  isLeptonic=1;
	  isUpTypeQuark=0;
	}
      else if( VisZ && isQuark(lheReader.hepeup.IDUP.at(finalFermions.at(0))) && isQuark(lheReader.hepeup.IDUP.at(finalFermions.at(1))) ) //hadronic Z
	{
	  hadronicZCount++;
	  isLeptonic=0;
	  isUpTypeQuark=0;
	  if( isUpType( lheReader.hepeup.IDUP.at(finalFermions.at(0)) ) ) isUpTypeQuark=1;
	}
      else if( VisZ && isLepton(lheReader.hepeup.IDUP.at(finalFermions.at(0))) && isLepton(lheReader.hepeup.IDUP.at(finalFermions.at(1))) ) //leptonic Z
	{
	  leptonicZCount++;
	  isLeptonic=1;
	  isUpTypeQuark=0;
	}
      else {assert(0);}
      
      //More detailed
      if(VisZ)
	{
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==11 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==11  ){
	    BR_Zee++;
	    decayMode=0;
	  }
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==13 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==13  ){
	    BR_Zmm++;
	    decayMode=1;
	  }
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==15 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==15  ){
	    BR_Ztt++;
	    decayMode=2;
	  }
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==12 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==12  ){
	    BR_Znene++;
	    decayMode=13;
	  }
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==14 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==14  ){
	    BR_Znmnm++;
	    decayMode=14;
	  }
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==16 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==16  ){
	    BR_Zntnt++;
	    decayMode=15;
	  }
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==2 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==2  ){
	    BR_Zuu++;
	    decayMode=3;
	  }
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==4 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==4  ){
	    BR_Zcc++;
	    decayMode=4;
	  }
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==1 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==1  ){
	    BR_Zdd++;
	    decayMode=5;
	  }
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==3 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==3  ){
	    BR_Zss++;
	    decayMode=6;
	  }
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==5 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==5  ){
	    BR_Zbb++;
	    decayMode=7;
	  }
	}
      else if(VisW)
	{
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==11 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==12
	      || abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==12 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==11){
	    BR_Wen++;
	    decayMode=8;
	  }
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==13 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==14
	      || abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==14 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==13){
	    BR_Wmn++;
	    decayMode=9;
	  }
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==15 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==16
	      || abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==16 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==15){
	    BR_Wtn++;
	    decayMode=10;
	  }
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==2 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==1
	      || abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==1 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==2){
	    BR_Wud++;
	    decayMode=11;
	  }
	  if( abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==4 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==3
	      || abs(lheReader.hepeup.IDUP.at(finalFermions.at(0)))==3 && abs(lheReader.hepeup.IDUP.at(finalFermions.at(1)))==4){
	    BR_Wcs++;
	    decayMode=12;
	  }
	}
      else {assert(0);}


      //Create the TLorentzVectors 
      TLorentzVector fs_f0
        (
         lheReader.hepeup.PUP.at(i_f0).at(0), //PG px
         lheReader.hepeup.PUP.at(i_f0).at(1), //PG py
         lheReader.hepeup.PUP.at(i_f0).at(2), //PG pz
         lheReader.hepeup.PUP.at(i_f0).at(3)  //PG E
         ) ;
      TLorentzVector fs_f1
        (
         lheReader.hepeup.PUP.at(i_f1).at(0), //PG px
         lheReader.hepeup.PUP.at(i_f1).at(1), //PG py
         lheReader.hepeup.PUP.at(i_f1).at(2), //PG pz
         lheReader.hepeup.PUP.at(i_f1).at(3)  //PG E
         ) ;
      TLorentzVector fs_H
        (
         lheReader.hepeup.PUP.at(i_H).at(0), //PG px
         lheReader.hepeup.PUP.at(i_H).at(1), //PG py
         lheReader.hepeup.PUP.at(i_H).at(2), //PG pz
         lheReader.hepeup.PUP.at(i_H).at(3)  //PG E
         ) ;
      
      TLorentzVector fs_b0, fs_b1;
      if(higgsDecay==1)
	{
	  fs_b0.SetPxPyPzE(
			   lheReader.hepeup.PUP.at(i_b0).at(0), //PG px
			   lheReader.hepeup.PUP.at(i_b0).at(1), //PG py
			   lheReader.hepeup.PUP.at(i_b0).at(2), //PG pz
			   lheReader.hepeup.PUP.at(i_b0).at(3)  //PG E
			   );
	  fs_b1.SetPxPyPzE(
			   lheReader.hepeup.PUP.at(i_b1).at(0), //PG px
			   lheReader.hepeup.PUP.at(i_b1).at(1), //PG py
			   lheReader.hepeup.PUP.at(i_b1).at(2), //PG pz
			   lheReader.hepeup.PUP.at(i_b1).at(3)  //PG E
			   );
	}
      else
	{
	  //fake the H decay -- this creates PROBLEMS for computeAngles.  Do i need to boost?
	  fs_b0 = (0.5)*fs_H; 
	  fs_b1 = (0.5)*fs_H;
	  //cout << "Total: " << fs_H.E() << " " << fs_H.Px() << " " << fs_H.Py() << " " << fs_H.Pz() << endl; //check that this works
	  //cout << "b0: " << fs_b0.E() << " " << fs_b0.Px() << " " << fs_b0.Py() << " " << fs_b0.Pz() << endl;
	  //cout << "b1: " << fs_b1.E() << " " << fs_b1.Px() << " " << fs_b1.Py() << " " << fs_b1.Pz() << endl;
	}
      
      //acceptance test
      passEta = 0;
      if(fabs(fs_f0.PseudoRapidity())<2.4 && fabs(fs_f1.PseudoRapidity())<2.4 && fabs(fs_b0.PseudoRapidity())<2.4 && fabs(fs_b1.PseudoRapidity())<2.4){
	passEta = 1;
      }

      TLorentzVector p4_Vff = fs_f0 + fs_f1;
      TLorentzVector p4_Hbb = fs_b0 + fs_b1;
      TLorentzVector p4_VH  = p4_Vff + p4_Hbb;
      
      //cuts
      //if(p4_Vff.Pt()<100 || p4_Hbb.Pt()<100) continue;

      double a_costheta1, a_costheta2, a_costhetastar, a_Phi, a_Phi1;
      computeAngles( p4_VH, p4_Vff, fs_f0, fs_f1, p4_Hbb, fs_b0, fs_b1, 
		     a_costheta1, a_costheta2, a_Phi, a_costhetastar, a_Phi1);
      
      mT = getMT(p4_Vff, p4_Hbb);

      //remap to convention of arXiv:1309.4819, including fix from Sinan&Alex
      costheta2     = (float) a_costheta1;
      costheta1     = (float) a_costhetastar;
      phi           = (float) a_Phi1;
      costhetastar  = (float) a_costheta2;
      phi1          = (float) a_Phi;
      mVH           = (float) p4_VH.M();
      rapidityVH    = (float) p4_VH.Rapidity();
      mZ            = (float) p4_Vff.M();
      mH            = (float) p4_Hbb.M();
      //isLeptonic, isUpTypeQuark, and decayMode already filled

      b0_e   = fs_b0.E();
      b0_phi = fs_b0.Phi();
      b0_eta = fs_b0.Eta();
      b0_pt  = fs_b0.Pt();
      b1_e   = fs_b1.E();
      b1_phi = fs_b1.Phi();
      b1_eta = fs_b1.Eta();
      b1_pt  = fs_b1.Pt();
      f0_e   = fs_f0.E();
      f0_phi = fs_f0.Phi();
      f0_eta = fs_f0.Eta();
      f0_pt  = fs_f0.Pt();
      f1_e   = fs_f1.E();
      f1_phi = fs_f1.Phi();
      f1_eta = fs_f1.Eta();
      f1_pt  = fs_f1.Pt();
      V_e    = p4_Vff.E();
      V_phi  = p4_Vff.Phi();
      V_eta  = p4_Vff.Eta();
      V_pt   = p4_Vff.Pt();
      H_e    = p4_Hbb.E();
      H_phi  = p4_Hbb.Phi();
      H_eta  = p4_Hbb.Eta();
      H_pt   = p4_Hbb.Pt();
      //VH_e   = p4_VH.E();
      //VH_phi = p4_VH.Phi();
      //VH_eta = p4_VH.Eta();
      //VH_pt  = p4_VH.Pt();


      tree->Fill();

    }// End loop over events

  BR_Znn = BR_Znene + BR_Znmnm + BR_Zntnt;
  
  if(verbose) {
    cout << "Total number of events processed: " << eventCount << endl;
    cout << leptonicWCount << " Leptonic W fraction: " << ((double)leptonicWCount)/((double)eventCount) << endl;
    cout << hadronicWCount << " Hadronic W fraction: " << ((double)hadronicWCount)/((double)eventCount) << endl;
    cout << leptonicZCount << " Leptonic Z fraction: " << ((double)leptonicZCount)/((double)eventCount) << endl;
    cout << hadronicZCount << " Hadronic Z fraction: " << ((double)hadronicZCount)/((double)eventCount) << endl;
    
    //detail
    cout << "BR_Zee " << ((double)BR_Zee)/((double)eventCount) << endl;
    cout << "BR_Zmm " << ((double)BR_Zmm)/((double)eventCount) << endl;
    cout << "BR_Ztt " << ((double)BR_Ztt)/((double)eventCount) << endl;
    cout << "BR_Znene " << ((double)BR_Znene)/((double)eventCount) << endl;
    cout << "BR_Znmnm " << ((double)BR_Znmnm)/((double)eventCount) << endl;
    cout << "BR_Zntnt " << ((double)BR_Zntnt)/((double)eventCount) << endl;
    cout << "BR_Zinv " << ((double)BR_Znn)/((double)eventCount) << endl;
    cout << "BR_Zuu " << ((double)BR_Zuu)/((double)eventCount) << endl;
    cout << "BR_Zcc " << ((double)BR_Zcc)/((double)eventCount) << endl;
    cout << "BR_Zdd " << ((double)BR_Zdd)/((double)eventCount) << endl;
    cout << "BR_Zss " << ((double)BR_Zss)/((double)eventCount) << endl;
    cout << "BR_Zbb " << ((double)BR_Zbb)/((double)eventCount) << endl;
    cout << "BR_Wen " << ((double)BR_Wen)/((double)eventCount) << endl;
    cout << "BR_Wmn " << ((double)BR_Wmn)/((double)eventCount) << endl;
    cout << "BR_Wtn " << ((double)BR_Wtn)/((double)eventCount) << endl;
    cout << "BR_Wud " << ((double)BR_Wud)/((double)eventCount) << endl;
    cout << "BR_Wcs " << ((double)BR_Wcs)/((double)eventCount) << endl;
  }

  // Write to file
  file.cd();
  tree->Write();
  file.Close();

  return 0;
}
コード例 #6
0
static void s_TEST_IdTree()
{
    typedef CTreePair<int, int>::TTreePair     TTreePair;
    typedef CTreePair<int, int>::TPairTreeNode TTree;

    TTree* tr = new TTree(TTreePair(0, 0));
    
    tr->AddNode(TTreePair(1, 10));
    tr->AddNode(TTreePair(100, 110));
    TTree* tr2 = tr->AddNode(TTreePair(2, 20));
    tr2->AddNode(TTreePair(20, 21));    
    TTree* tr3 =tr2->AddNode(TTreePair(22, 22));
    tr3->AddNode(TTreePair(222, 222));

    {{
    const TTree* tnd = tr->FindSubNode(100);
    assert(tnd);
    assert(tnd->GetValue().id == 100);
    assert(tnd->GetValue().value == 110);
    const TTree& tv = tnd->GetValue();
    assert(tv.GetValue().value == 110);

    }}

    {{
    list<int> npath;
    npath.push_back(2);
    npath.push_back(22);

    TTree::TConstNodeList res;
    tr->FindNodes(npath, &res);
    assert(!res.empty());
    TTree::TConstNodeList::const_iterator it = res.begin();
    const TTree* ftr = *it;

    assert(ftr->GetValue().value == 22);
    }}

    {{
    list<int> npath;
    npath.push_back(2);
    npath.push_back(32);

    TTree::TConstNodeList res;
    tr->FindNodes(npath, &res);
    assert(res.empty());
    }}

    {{
    list<int> npath;
    npath.push_back(2);
    npath.push_back(22);
    npath.push_back(222);
    npath.push_back(100);

    const TTree* node = PairTreeTraceNode(*tr, npath);
    assert(node);
    cout << node->GetValue().id << " " << node->GetValue().value << endl;
    assert(node->GetValue().value == 110);


    node = PairTreeBackTraceNode(*tr3, 1);
    assert(node);
    cout << node->GetValue().id << " " << node->GetValue().value << endl;
    assert(node->GetValue().value == 10);
    }}

    {{
    list<int> npath;
    npath.push_back(2);
    npath.push_back(22);
    npath.push_back(222);

    const TTree* node = PairTreeTraceNode(*tr, npath);
    assert(node);
    cout << node->GetValue().id << " " << node->GetValue().value << endl;
    assert(node->GetValue().value == 222);
    }}

    delete tr;
}
コード例 #7
0
void DCTPCTree::Loop()
{
  TStopwatch timer;
  gROOT->SetStyle("Plain");
  gStyle->SetEndErrorSize(3);
  gStyle->SetPalette(1,0);
  gStyle->SetLineWidth(2);
  gStyle->SetHistLineWidth(2);
  gStyle->SetOptStat(kTRUE);
  gStyle->SetOptFit(kTRUE);
  TH1::AddDirectory(false);
  
  TFile *outtree = new TFile("../input_files/hadd_01041_01158.root");//$LittleDCTPC_physics_input
  TTree *dctreepc = (TTree*)outtree->Get("dctpc_eventinfo");
  DCTPCTree aStep(dctreepc);

  Int_t Exposure_sec;
  TTree *dctreepc2 = (TTree*)outtree->Get("dctpc_runinfo");       
  dctreepc2->SetBranchAddress("Exposure_sec", &Exposure_sec);
  Int_t nentries2 = (Int_t)dctreepc2->GetEntries();  
  double totalexposure=0.;
  
  for (int runcounter = 0; runcounter<nentries2; runcounter++)
    {
      dctreepc2->GetEntry(runcounter);
      totalexposure+=Exposure_sec;
    }
  
  ofstream file_passccd;
  file_passccd.open("Pass_CCD.txt");
  ofstream file_passwfandccd;
  file_passwfandccd.open("Pass_WF_and_CCD.txt");
  
  
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  
  
  double seqcalib [19] = {0.955114 , 1.06241 , 1.07105 , 1.07669 , 1.02827 , 1.15574 , 1.18828 , 1.08779 , 0.998239 , 1.05118 , 1.03128 , 1.02639 , 0.992746 , 0.925486 , 1.1664 , 1.05791, 0.989169};
  
  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  
  //create event loop
  Long64_t nentries = dctreepc->GetEntries();
  cout << "Number of Entries: " << nentries << endl;
  
  /////////////////////////////////////////////////////////////////////////////////////////////////////////////
  
  int cutnum=-1;
  int neutronnumber=0;
  int passall=0;
  int passccd=0;
  int passwf=0;
  int passwfandccd=0;

  TH1D *hist_time_ccd=new TH1D("CCD Pass Rate", "CCD Pass Rate", 100, 1374000000, 1396000000);
  TH1D *hist_time_wf=new TH1D("WF Pass Rate", "WF Pass Rate", 100, 1374000000, 1396000000);
  TH1D *hist_time_wfandccd=new TH1D("CCD and WF Pass Rate", "CCD and WF Pass Rate", 100, 1374000000, 1396000000);

  TH1D *hist_time_ccd_percent = new TH1D("% Events Pass CCD", "% Events Pass CCD", 100, 1374000000, 1396000000);
  TH1D *hist_time_wfandccd_percent = new TH1D("% Events Pass WF and CCD", "% Events Pass WF and CCD", 100, 1374000000, 1396000000);

  TH2D *hist_ccdpass_rate=new TH2D("CCD Pass", "CCD Pass", 100, 1374000000, 1386000000, 2000, 0, 2000);
  TH2D *hist_wfpass_rate=new TH2D("WF Pass", "WF Pass", 100, 1374000000, 1386000000, 2000, 0, 2000);
  TH2D *hist_wfandccdpass_rate=new TH2D("CCD and WF Pass", "CCD and WF Pass", 100, 1374000000, 1386000000, 2000, 0, 2000);

  TH2D *hist_ccdpass_rate_percent=new TH2D("% CCD Pass", "% CCD Pass", 100, 1374000000, 1396000000, 100, 0, 100);
  TH2D *hist_wfandccdpass_rate_percent=new TH2D("% WF and CCD Pass", "% WF and CCD Pass", 100, 1374000000, 1396000000, 100, 0, 100);

  TH2D *hist_pass_rate=new TH2D("Pass", "Pass", 100, 1374000000, 1386000000, 100, 0, 1);

  TH1D *hist_eff_vs_eccd_ccd=new TH1D("Efficiency vs CCD Energy - CCD Only", "Efficiency vs CCD Energy - CCD Only", 60, 0, 6000);
  TH1D *hist_eff_vs_eccd_ccd2=new TH1D("Efficiency vs CCD Energy - CCD Only 2", "Efficiency vs CCD Energy - CCD Only 2", 25, 0, 1000);
  TH1D *hist_eff_vs_eccd_wfandccd=new TH1D("Efficiency vs CCD Energy - CCD and WF", "Efficiency vs CCD Energy - CCD and WF", 60, 0, 6000);
  TH1D *hist_eff_vs_eccd_wfandccd2=new TH1D("Efficiency vs CCD Energy - CCD and WF 2", "Efficiency vs CCD Energy - CCD and WF 2", 25, 0, 1000);

  TH1D *hist_eff_vs_elength=new TH1D("Efficiency vs Length Energy", "Efficiency vs Length Energy", 60, 0, 6000);
  TH1D *hist_eff_vs_elength2=new TH1D("Efficiency vs Length Energy 2", "Efficiency vs Length Energy 2", 25, 0, 1000);
  TH1D *hist_eff_vs_elength_ccd=new TH1D("Efficiency vs Length Energy - CCD Only", "Efficiency vs Length Energy - CCD Only", 60, 0, 6000);
  TH1D *hist_eff_vs_elength_ccd2=new TH1D("Efficiency vs Length Energy - CCD Only 2", "Efficiency vs Length Energy - CCD Only 2", 25, 0, 1000);
  TH1D *hist_eff_vs_elength_wf=new TH1D("Efficiency vs Length Energy - WF Only", "Efficiency vs Length Energy - WF Only", 60, 0, 6000);
  TH1D *hist_eff_vs_elength_wfandccd=new TH1D("Efficiency vs Length Energy - CCD and WF", "Efficiency vs Length Energy - CCD and WF", 60, 0, 6000);
  TH1D *hist_eff_vs_elength_wfandccd2=new TH1D("Efficiency vs Length Energy - CCD and WF 2", "Efficiency vs Length Energy - CCD and WF 2", 25, 0, 1000);

  /*TH1D *hist_eff_vs_eccd_ccd_percent=new TH1D("%CCD vs Energy", "%CCD vs Energy", 1000, 0, 10000);
  TH1D *hist_eff_vs_eccd_wfandccd_percent = new TH1D("%WF and CCD vs Energy", "%WF and CCD vs Energy", 1000, 0, 10000);
  TH1D *hist_eff_vs_eccd=new TH1D("Efficiency vs CCD Energy", "Efficiency vs CCD Energy", 1000, 0, 10000);*/
  
  /////////////////////////////////////////////////////////////////////////////////////////////////////////////

  for (int event = 0; event<nentries; event++)
    {
      
      aStep.GetEntry(event); 
      if(event%1000000==0)
	cout<<((double)event/(double)nentries)*100.<<"%"<<endl;
      
      r2 = (aStep.Track_x_pix*aStep.Track_x_pix+aStep.Track_y_pix*aStep.Track_y_pix)*pow(MMPERPIXEL/10.,2);
      weight=1./pow(RADIAL_PARAM0_CALIB/(RADIAL_PARAM1_CALIB+r2),RADIAL_PARAM2_CALIB);//radial calibration 
      rho_start=(sqrt(((aStep.Track_x_start_pix*MMPERPIXEL)*(aStep.Track_x_start_pix*MMPERPIXEL))+((aStep.Track_y_start_pix*MMPERPIXEL)*(aStep.Track_y_start_pix*MMPERPIXEL))));
      rho_end=(sqrt(((aStep.Track_x_end_pix*MMPERPIXEL)*(aStep.Track_x_end_pix*MMPERPIXEL))+((aStep.Track_y_end_pix*MMPERPIXEL)*(aStep.Track_y_end_pix*MMPERPIXEL))));
      
      meshcalib=MESH_CALIB;
      ccdcalib=CCD_CALIB;
      anodecalib=ANODE_CALIB;

      verticallength=((aStep.Mesh_R0time_samp+aStep.Mesh_F10time_samp)*driftspeed);
      horizontallength=aStep.Track_range_pix*MMPERPIXEL;
      tracklength=(sqrt((verticallength*verticallength)+(horizontallength*horizontallength)));
      lengthcalib=LENGTH_CALIB;
      lengthenergy=(El_0 + (El_1*tracklength) + (El_2*tracklength*tracklength))*lengthcalib;
      ccdenergy=((Eccd_0)+(Eccd_1*aStep.Etrack_kev*weight)+(Eccd_2*aStep.Etrack_kev*weight*aStep.Etrack_kev*weight))*ccdcalib;

      delta_anodeccd=((aStep.Etrig_kev*anodecalib)-(ccdenergy))/((aStep.Etrig_kev*anodecalib)+(ccdenergy));
      delta_meshccd=((aStep.Emesh_kev*meshcalib)-(ccdenergy))/((aStep.Emesh_kev*meshcalib)+(ccdenergy));
      delta_anodemesh=((aStep.Etrig_kev*anodecalib)-(aStep.Emesh_kev*meshcalib))/((aStep.Etrig_kev*anodecalib)+(aStep.Emesh_kev*meshcalib));
      delta_meshlength=((lengthenergy)-(aStep.Emesh_kev*meshcalib))/((lengthenergy)+(aStep.Emesh_kev*meshcalib));
      delta_anodelength=((aStep.Etrig_kev*anodecalib)-(lengthenergy))/((aStep.Etrig_kev*anodecalib)+(lengthenergy));
      delta_ccdlength=((ccdenergy)-(lengthenergy))/((ccdenergy)+(lengthenergy));
      mesh_over_ccd=((aStep.Emesh_kev*meshcalib)/(ccdenergy));
      
           //////////////////////////////////////////////////////////////////////////////////////////////////////////////
      
      if(aStep.Edge==1)
	{continue;}
      
      if(aStep.EventNum-aStep.LastSpark<7)
	{continue;}   
      
      if(aStep.Track_range_pix*MMPERPIXEL<=0.)
	{continue;}
      
      if(aStep.Etrack_kev*weight<300)
	{continue;}
      
      if(aStep.Track_maxpixel_ccdadu<72 ||
				     aStep.Track_maxpixel_ccdadu>200)
	{continue;}
      
      if(rho_start>100 ||
	 rho_end>100)
	{continue;}
      
      if(tracklength>72)
	{continue;}

      passccd++;
      file_passccd<<aStep.RunNum<<" "<<aStep.EventNum<<endl;
      hist_time_ccd->Fill(aStep.Timenow_sec);
      hist_time_ccd_percent->Fill(aStep.Timenow_sec);
      hist_ccdpass_rate->Fill(aStep.Timenow_sec, passccd);
      hist_ccdpass_rate_percent->Fill(aStep.Timenow_sec, (passccd/5577720.)*100.);
      if(ccdenergy>1000)
	hist_eff_vs_eccd_ccd->Fill(ccdenergy);
      if(ccdenergy<=1000)
	hist_eff_vs_eccd_ccd2->Fill(ccdenergy);
      if(lengthenergy>1000)
	hist_eff_vs_elength_ccd->Fill(lengthenergy);
      if(lengthenergy<=1000)
	hist_eff_vs_elength_ccd2->Fill(lengthenergy);
    
      /////////all events above have passed ccd cuts only
      
      //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////	 

      if(aStep.Etrig_kev<400)
	{continue;}
      
      if(aStep.Emesh_kev<500)
	{continue;}
          
      passwfandccd++;
      file_passwfandccd<<aStep.RunNum<<" "<<aStep.EventNum<<endl;
      hist_time_wfandccd->Fill(aStep.Timenow_sec);
      hist_time_wfandccd_percent->Fill(aStep.Timenow_sec);
      hist_wfandccdpass_rate->Fill(aStep.Timenow_sec, passwfandccd);
      hist_wfandccdpass_rate_percent->Fill(aStep.Timenow_sec, (passwfandccd/5577720.)*100.);
      if(ccdenergy>1000)
	hist_eff_vs_eccd_wfandccd->Fill(ccdenergy);
      if(ccdenergy<=1000)
	hist_eff_vs_eccd_wfandccd2->Fill(ccdenergy);
      if(lengthenergy>1000)
	hist_eff_vs_elength_wfandccd->Fill(lengthenergy);
      if(lengthenergy<=1000)
	hist_eff_vs_elength_wfandccd2->Fill(lengthenergy);

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

      double detectorefficiency=((passwfandccd*1.0)/(passccd*1.0));
      
      neutronnumber++;
     
     
    }

  hist_time=(TH1D*)hist_time_wfandccd_percent->Clone();
  hist_time->Divide(hist_time_ccd);
  hist_time_percent=(TH1D*)hist_time->Clone();
  hist_pass_rate->Fill(aStep.Timenow_sec, detectorefficiency);

  hist_eff_vs_eccd=(TH1D*)hist_eff_vs_eccd_wfandccd->Clone();
  hist_eff_vs_eccd->Divide(hist_eff_vs_eccd_ccd);
  hist_eff_vs_eccd2=(TH1D*)hist_eff_vs_eccd_wfandccd2->Clone();
  hist_eff_vs_eccd2->Divide(hist_eff_vs_eccd_ccd2);
  hist_eff_vs_eccd_percent=(TH1D*)hist_eff_vs_eccd->Clone();

  hist_eff_vs_elength=(TH1D*)hist_eff_vs_elength_wfandccd->Clone();
  hist_eff_vs_elength->Divide(hist_eff_vs_elength_ccd);
  hist_eff_vs_elength2=(TH1D*)hist_eff_vs_elength_wfandccd2->Clone();
  hist_eff_vs_elength2->Divide(hist_eff_vs_elength_ccd2);
  
  hist_time_percent->Scale(100);
  hist_eff_vs_eccd_percent->Scale(100);
  //hist_eff_vs_elength_ccd->SetMaximum(100);
  hist_eff_vs_eccd->SetMaximum(5);
  hist_eff_vs_eccd->SetMinimum(-5);
  hist_eff_vs_elength->SetMaximum(5);
  hist_eff_vs_elength->SetMinimum(-5);

   
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  
  Double_t fitf(Double_t *x, Double_t *par)
  {
    Double_t fitval = par[0]*x[0];
    return fitval;
  }   
コード例 #8
0
void  JetResponseMacro_TheDeadlyEagle_Eta(){

  gROOT->ProcessLine(".x rootlogon.C");
  gROOT->ProcessLine(".L format1Dhisto.C");
  gROOT->ProcessLine(".L formatTGraph.C");
  gROOT->ProcessLine(".x betterColors.C");

TFile *FileA = TFile::Open(Form("../JEC/Corrected_dijet_pp_mergedpthatbins_2013MCV2.root"));
  //TFile *FileA = TFile::Open(Form("~/rootFiles/JEC/Files/20120521/Correcteddijet_pp_mergedpthatbins_2012MC.root"));
  TString outname = "JetResponse_Plots.root"; 
  TFile* outf = new TFile(outname,"recreate");

  const char* AlgoNames[] = {"ak1PF","ak2PF","ak3PF","ak4PF","ak5PF","ak6PF","ak1Calo","ak2Calo","ak3Calo","ak4Calo","ak5Calo","ak6Calo","icPu5"};
  
  TCanvas *c1 = new TCanvas("c1","c1",1100,700);
  makeMultiPanelCanvas(c1,3,2,0.0,0.0,0.2,0.15,0.07);
  TCanvas *c1B = new TCanvas("c1B","c1B",1100,700);
  makeMultiPanelCanvas(c1B,3,2,0.0,0.0,0.2,0.15,0.07);
  TCanvas *c1C = new TCanvas("c1C","c1C",1100,700);
  makeMultiPanelCanvas(c1C,3,2,0.0,0.0,0.2,0.15,0.07);
  const int cCanDiv = 13;
  int nCanvDiv = cCanDiv;
  const int CnXbins = 30;
  int nXbins = CnXbins;

  TH2D* iHistoCorrEta[cCanDiv];
  TH2D* iHistoRefEta[cCanDiv];
  TH2D* iHistoJtEta[cCanDiv];
  TH2D* iHistoRawEta[cCanDiv];
  TH1D* h1[cCanDiv][CnXbins];
  TF1* Gauss6[cCanDiv][CnXbins];
  double mean[cCanDiv][CnXbins];
  double sigma[cCanDiv][CnXbins];
  double meanErr[cCanDiv][CnXbins];
  double sigmaErr[cCanDiv][CnXbins];
  double xPoint[cCanDiv][CnXbins];
  double xPointErr[cCanDiv][CnXbins];
  TLegend*  leg[cCanDiv];

  for(int i =0; i<nCanvDiv; i++)
    {
if(i==0 || i==6) continue;//skip the ak1 algos
if(i==12) continue;//skip the icpU5 algos
    if(i<=5)c1->cd(i+1);
    if(i>5 && i<12)c1B->cd(i-5);
    if(i>=12)c1C->cd(i-12);
    if(i==0)  TTree* t      = (TTree*)FileA->Get("ak1PFJetAnalyzer/t");
    if(i==1)  TTree* t      = (TTree*)FileA->Get("ak2PFJetAnalyzer/t");
    if(i==2)  TTree* t      = (TTree*)FileA->Get("ak3PFJetAnalyzer/t");
    if(i==3)  TTree* t      = (TTree*)FileA->Get("ak4PFJetAnalyzer/t");
    if(i==4)  TTree* t      = (TTree*)FileA->Get("ak5PFJetAnalyzer/t");
    if(i==5)  TTree* t      = (TTree*)FileA->Get("ak6PFJetAnalyzer/t");
    if(i==6)  TTree* t      = (TTree*)FileA->Get("ak1CaloJetAnalyzer/t");
    if(i==7)  TTree* t      = (TTree*)FileA->Get("ak2CaloJetAnalyzer/t");
    if(i==8)  TTree* t      = (TTree*)FileA->Get("ak3CaloJetAnalyzer/t");
    if(i==9)  TTree* t      = (TTree*)FileA->Get("ak4CaloJetAnalyzer/t");
    if(i==10) TTree* t      = (TTree*)FileA->Get("ak5CaloJetAnalyzer/t");
    if(i==11) TTree* t      = (TTree*)FileA->Get("ak6CaloJetAnalyzer/t");
    if(i==12) TTree* t      = (TTree*)FileA->Get("icPu5JetAnalyzer/t");
      
      leg[i]= new TLegend(0.22,0.63,0.45,0.90);//top right
      leg[i]->SetFillColor(0);
      leg[i]->SetTextSize(0.05);
      leg[i]->SetBorderSize(0);
      
      iHistoCorrEta[i] = new TH2D(Form("%s_CorrEta",AlgoNames[i]),Form("%s_CorrEta",AlgoNames[i]),nXbins,-2,2,500,0,5);
      //t->Draw(Form("corrpt/refpt:jteta>>%s_CorrEta",AlgoNames[i]),Form("corrpt>0 && fabs(jteta)<2.0"),"goff");
      t->Draw(Form("corrpt/refpt:jteta>>%s_CorrEta",AlgoNames[i]),Form("corrpt>5 && refpt>5 && fabs(jteta)<2.0"),"goff");
      iHistoCorrEta[i]->Draw("colz");
      leg[i]->AddEntry(iHistoCorrEta[i],Form("%s |#eta|<2.0",AlgoNames[i]),"");
      leg[i]->AddEntry(iHistoCorrEta[i],Form("Corrected / ref p_{T}"),"");
      format1Dhisto(*iHistoCorrEta[i],250,-1,2,20,2,1,"Jet #eta","Corrected p_{T}/ ref p_{T}");//Red      
      leg[i]->Draw();
      for(int iX=iHistoCorrEta[i]->GetXaxis()->GetFirst(); iX<iHistoCorrEta[i]->GetXaxis()->GetLast(); iX++ )
	{
	  //cout<<"bin ( "<<iX<<" ) --limits ["<<iHistoCorrEta[i]->GetXaxis()->GetBinLowEdge(iX)<<" , "<<iHistoCorrEta[i]->GetXaxis()->GetBinUpEdge(iX)<<" ] "<<endl;
	  h1[i][iX] = new TH1D(Form("h1_%d_%d_py",i,iX),Form("h1_%d_%d_py",i,iX),500,0,5);
	  h1[i][iX] =(TH1D*)iHistoCorrEta[i]->ProjectionY(Form("h1_%d_%d_py",i,iX),iX,iX,"e");
	  Gauss6[i][iX] = new TF1(Form("F6_c%d_d%d",i,iX),"gaus",0,5);
	  Gauss6[i][iX]->SetParLimits(1,0.7,1.5);
	  h1[i][iX]->Fit(Form("F6_c%d_d%d",i,iX),"0Q");
	  mean[i][iX] = Gauss6[i][iX]->GetParameter(1);
	  sigma[i][iX] = Gauss6[i][iX]->GetParameter(2);
	  meanErr[i][iX] = Gauss6[i][iX]->GetParError(1);
	  sigmaErr[i][iX] = Gauss6[i][iX]->GetParError(2);
	  xPoint[i][iX] =iHistoCorrEta[i]->GetXaxis()->GetBinCenter(iX);
	  xPointErr[i][iX] = 0;
	  
	  if(i==0 && iX==1)//Just to test 
	    {
	      TCanvas *c11 = new TCanvas("c11","c11",500,400);
	      c11->cd();	    
	      h1[i][iX]->Draw();
	      Gauss6[i][iX]->Draw("same");
	    }	  
	}

      
    }
  


  TLegend*  leg2B[cCanDiv];
  TLegend*  leg2A[cCanDiv];
  TGraphErrors *CorrEta_Mean[cCanDiv];
  TCanvas *c2 = new TCanvas("c2","c2",1100,700);
  makeMultiPanelCanvas(c2,3,2,0.0,0.0,0.2,0.15,0.07);
  TCanvas *c2B = new TCanvas("c2B","c2B",1100,700);
  makeMultiPanelCanvas(c2B,3,2,0.0,0.0,0.2,0.15,0.07);
  TCanvas *c2C = new TCanvas("c2C","c2C",1100,700);
  makeMultiPanelCanvas(c2C,3,2,0.0,0.0,0.2,0.15,0.07);

  TGraphErrors *CorrEta_Sigma[cCanDiv];
  TCanvas *c3 = new TCanvas("c3","c3",1100,700);
  makeMultiPanelCanvas(c3,3,2,0.0,0.0,0.2,0.15,0.07);
  TCanvas *c3B = new TCanvas("c3B","c3B",1100,700);
  makeMultiPanelCanvas(c3B,3,2,0.0,0.0,0.2,0.15,0.07);
  TCanvas *c3C = new TCanvas("c3C","c3C",1100,700);
  makeMultiPanelCanvas(c3C,3,2,0.0,0.0,0.2,0.15,0.07);

  for(int i2 =0; i2<nCanvDiv; i2++)
    {
      leg2A[i2]= new TLegend(0.22,0.18,0.45,0.35);//top right
      leg2A[i2]->SetFillColor(0);
      leg2A[i2]->SetTextSize(0.05);
      leg2A[i2]->SetBorderSize(0);
      
      leg2B[i2]= new TLegend(0.22,0.18,0.45,0.35);//top right
      leg2B[i2]->SetFillColor(0);
      leg2B[i2]->SetTextSize(0.05);
      leg2B[i2]->SetBorderSize(0);

      double xLoc[CnXbins];
      double y2Loc[CnXbins];
      double y3Loc[CnXbins];
      double xLocErr[CnXbins];
      double y2LocErr[CnXbins];
      double y3LocErr[CnXbins];
      for(int iBin=0; iBin<nXbins; iBin++)
	{	  
	  xLoc[iBin] = xPoint[i2][iBin];
	  xLocErr[iBin] = xPointErr[i2][iBin];
	  y2Loc[iBin] = mean[i2][iBin];
	  y2LocErr[iBin] = meanErr[i2][iBin];
	  y3Loc[iBin] = sigma[i2][iBin];
	  y3LocErr[iBin] = sigmaErr[i2][iBin];
	}


    
    if(i2<=5)c2->cd(i2+1);
    if(i2>5 && i2<12)c2B->cd(i2-5);
    if(i2>=12)c2C->cd(i2-12);
      CorrEta_Mean[i2] = new TGraphErrors(nXbins,xLoc,y2Loc,xLocErr,y2LocErr);
      formatTGraph(*CorrEta_Mean[i2],250,-1,1,20,1,1,"Jet #eta","#mu ");
      leg2A[i2]->AddEntry(CorrEta_Mean[i2],Form("%s |#eta|<2.0",AlgoNames[i2]),"");
      leg2A[i2]->AddEntry(CorrEta_Mean[i2],Form("Corrected p_{T}/ ref p_{T}"),"lp");
      CorrEta_Mean[i2]->SetMaximum(1.15);
      CorrEta_Mean[i2]->SetMinimum(0.90);
      CorrEta_Mean[i2]->Draw("AP");
      leg2A[i2]->Draw();

    if(i2<=5)c3->cd(i2+1);
    if(i2>5 && i2<12)c3B->cd(i2-5);
    if(i2>=12)c3C->cd(i2-12);
      CorrEta_Sigma[i2] = new TGraphErrors(nXbins,xLoc,y3Loc,xLocErr,y3LocErr);
      formatTGraph(*CorrEta_Sigma[i2],250,-1,1,20,1,1,"Jet #eta","#sigma ");
      leg2B[i2]->AddEntry(CorrEta_Sigma[i2],Form("%s |#eta|<2.0",AlgoNames[i2]),"");
      leg2B[i2]->AddEntry(CorrEta_Sigma[i2],Form("Corrected p_{T}/ ref p_{T}"),"lp");
      CorrEta_Sigma[i2]->SetMaximum(0.6);
      CorrEta_Sigma[i2]->SetMinimum(-0.2);
      CorrEta_Sigma[i2]->Draw("AP");
      leg2B[i2]->Draw();

    }
  
  c1->Print("plots/pPb2013_0126/EtaCorrection2D_AKPF.pdf");
  c1B->Print("plots/pPb2013_0126/EtaCorrection2D_AKCalo.pdf");
  c1C->Print("plots/pPb2013_0126/EtaCorrection2D_IC.pdf");
  c2->Print("plots/pPb2013_0126/EtaCorrection1DMean_AKPF.pdf");
  c2B->Print("plots/pPb2013_0126/EtaCorrection1DMean_AKCalo.pdf");
  c2C->Print("plots/pPb2013_0126/EtaCorrection1DMean_IC.pdf");
  c3->Print("plots/pPb2013_0126/EtaCorrection1DSigma_AKPF.pdf");
  c3B->Print("plots/pPb2013_0126/EtaCorrection1DSigma_AKCalo.pdf");
  c3C->Print("plots/pPb2013_0126/EtaCorrection1DSigma_IC.pdf");


}
コード例 #9
0
int main (int argc, char *argv[])
{

  printBoxedMessage("Starting plot generation");

  // ####################
  // ##   Init tools   ##
  // ####################

     // Create a sonic Screwdriver
      SonicScrewdriver s;

     // ##########################
     // ##   Create Variables   ##
     // ##########################

     s.AddVariable("MET",            "MET",                     "GeV",    16,50,530,      &(myEvent.MET),                  "logY");
     s.AddVariable("METPhi",         "METPhi",                  "GeV",    16,50,530,      &(myEvent.METPhi),               "");

     s.AddVariable("MT",             "M_{T}",                   "GeV",    40,0,400,       &(myEvent.MT),                   "");
    /*
     s.AddVariable("MTpeak",         "M_{T}",                   "GeV",    20,0,100,       &(myEvent.MT),                   "noOverflowInLastBin");
     s.AddVariable("MTtail",         "M_{T}",                   "GeV",    30,100,400,     &(myEvent.MT),                   "logY,noUnderflowInFirstBin");
     s.AddVariable("deltaPhiMETJets","#Delta#Phi(MET,j_{1,2})", "rad",    16,0,3.2,       &(myEvent.deltaPhiMETJets),      "");
     s.AddVariable("MT2W",           "M_{T2}^{W}",              "GeV",    20,0,500,       &(myEvent.MT2W),                 "");
     s.AddVariable("HTratio",        "H_{T}^{ratio}",           "",       20,0,1.2,       &(myEvent.HTRatio),              "");
     s.AddVariable("HadronicChi2",   "Hadronic #chi^{2}",       "",       20,0,20,        &(myEvent.hadronicChi2),         "logY");
     s.AddVariable("leadingBPt",     "p_{T}(leading b-jet)",    "GeV",    20,0,400,       &(myEvent.leadingBPt),           "");
     s.AddVariable("leadingJetPt",   "p_{T}(leading jet)",      "GeV",    20,0,600,       &(myEvent.leadingJetPt),         "");
     s.AddVariable("leptonPt",       "p_{T}(lepton)",           "GeV",    28,20,300,      &(myEvent.leadingLeptonPt),      "");
     s.AddVariable("Mlb",            "M'(lb)",                  "GeV",    20,0,500,       &(myEvent.Mlb),                  "");
     s.AddVariable("Mlb_hemi",       "M(lb)",             "GeV",          20,0,500,       &(myEvent.Mlb_hemi),             "");
     s.AddVariable("M3b",            "M3b",                     "GeV",    20,0,1000,      &(myEvent.M3b),                  "");
     s.AddVariable("deltaRLeptonB",  "#DeltaR(l,leading b)",    "",       20,0,5,         &(myEvent.deltaRLeptonLeadingB), "");
     s.AddVariable("HTLeptonPtMET",  "HT + MET + p_{T}(lepton)","GeV",    20,100,2100,    &(myEvent.HTPlusLeptonPtPlusMET),"");
     */
     s.AddVariable("HT",             "H_{T}",                   "",       46,120,1500,    &(myEvent.HT),                   "");
     s.AddVariable("METoverSqrtHT",  "MET / #sqrt{H_{T}}",      "",       32,0,32,        &(myEvent.METoverSqrtHT),        "");

     float leadingNonBPtN4;
     s.AddVariable("leadingNonBPt",     "p_{T}(leading nonb-jet)",    "GeV",    20,0,500,       &(leadingNonBPtN4),           "");
     float leadingNonBPtN5;
     s.AddVariable("leadingNonBPtN5",     "p_{T}(leading nonb-jet) (Njet>4)",    "GeV",    20,0,500,       &(leadingNonBPtN5),           "noUnderflowInFirstBin");

     int nJets, nBtag;

     s.AddVariable("nJets",          "Number of selected jets",               "",       11,0,10,        &(nJets),              "");
     s.AddVariable("nBtag",          "Number of selected b-tagged jets",      "",       5, 0,4,         &(nBtag),              "");
     s.AddVariable("numberOfPrimaryVertices",   "Number of primary vertices", "",       41, 0,40,       &(myEvent.numberOfPrimaryVertices),              "");

     float METPtReso;
     float METdPhiReso;
     s.AddVariable("METPtReso",      "MET p_{T} rel. resolution",         "GeV",    50, 0,5,      &(METPtReso),       "");
     s.AddVariable("METdPhiReso",     "MET #Delta #Phi rel. resolution",          "rad",    50, 0,2,      &(METdPhiReso),      "");

     // #########################################################
     // ##   Create ProcessClasses (and associated datasets)   ##
     // #########################################################

        s.AddProcessClass("1ltop", "1l top",                             "background",kRed-7);
            s.AddDataset("ttbar_powheg",                "1ltop",  0, 0);

            s.AddDataset("singleTop_st",                  "1ltop",  0, 0);

     s.AddProcessClass("ttbar_2l", "t#bar{t} #rightarrow l^{+}l^{-}", "background",kCyan-3);

     s.AddProcessClass("W+jets",   "W+jets",                          "background",kOrange-2);
             s.AddDataset("W+jets",    "W+jets", 0, 0);

     s.AddProcessClass("rare",   "rare",                              "background",kMagenta-5);
             s.AddDataset("rare",   "rare", 0, 0);
     /*
     s.AddProcessClass("T2tt", "T2tt (450, 50)",  "signal", COLORPLOT_GREEN );
            s.AddDataset("T2tt", "T2tt",   0, 0);

     s.AddProcessClass("T2bw", "T2bw, x = 0.50 (450, 50)",  "signal", COLORPLOT_MAGENTA );
            s.AddDataset("T2bw-050", "T2bw",   0, 0);
     */
     /*
     s.AddProcessClass("data",   "data",                              "data",COLORPLOT_BLACK);
            s.AddDataset("SingleElec",   "data", 0, 0);
            s.AddDataset("SingleMuon",   "data", 0, 0);
            s.AddDataset("DoubleElec",   "data", 0, 0);
            s.AddDataset("DoubleMuon",   "data", 0, 0);
            s.AddDataset("MuEl",         "data", 0, 0);
     */

     // ##########################
     // ##    Create Regions    ##
     // ##########################

     s.AddRegion("preselection",                  "Preselection",               &goesInPreselection          );
     s.AddRegion("preselection_MTtail",           "Preselection;M_{T} tail",    &goesInPreselectionMTtail    );

     // ##########################
     // ##   Create Channels    ##
     // ##########################

     s.AddChannel("singleLepton", "e/#mu-channels",            &goesInSingleLeptonChannel);

  // ########################################
  // ##       Create histograms and        ##
  // ##  schedule type of plots to produce ##
  // ########################################

     // Create histograms
     s.Create1DHistos();
     s.Add2DHisto("MET","HT");
     s.Add2DHisto("MT","METPtReso");
     s.Add2DHisto("MT","METdPhiReso");
     s.Add2DHisto("MT","numberOfPrimaryVertices");
     s.Add2DHisto("numberOfPrimaryVertices","METdPhiReso");
     s.Add2DHisto("numberOfPrimaryVertices","METPtReso");

     // Schedule plots
     //s.SchedulePlots("1DDataMCComparison");
     s.SchedulePlots("1DStack");
     s.SchedulePlots("1DSuperimposed");
     s.SchedulePlots("2D");
     s.SchedulePlots("1DFrom2DProjection","varX=MT,varY=METPtReso,projectionType=mean,labelY=MET Pt rel. resolution");
     s.SchedulePlots("1DFrom2DProjection","varX=MT,varY=METdPhiReso,projectionType=mean,labelY=MET #Delta #Phi rel. resolution");
     s.SchedulePlots("1DFrom2DProjection","varX=MT,varY=numberOfPrimaryVertices,projectionType=mean,labelY=Number of vertices");
     s.SchedulePlots("1DFrom2DProjection","varX=numberOfPrimaryVertices,varY=METdPhiReso,projectionType=mean,labelY=MET #Delta #Phi rel. resolution");
     s.SchedulePlots("1DFrom2DProjection","varX=numberOfPrimaryVertices,varY=METPtReso,projectionType=mean,labelY=MET Pt rel. resolution");

     // Config plots
     s.SetGlobalBoolOption  ("1DSuperimposed",    "includeSignal",    true   );

     s.SetGlobalStringOption("DataMCComparison",  "includeSignal",    "superimposed");
     s.SetGlobalFloatOption ("DataMCComparison",  "factorSignal",     100.0    );

     s.SetGlobalStringOption("1DStack",           "includeSignal",    "superimposed");
     s.SetGlobalFloatOption ("1DStack",           "factorSignal",     100.0    );

     s.SetGlobalFloatOption ("DataMCRatio",       "min",              0.0    );
     s.SetGlobalFloatOption ("DataMCRatio",       "max",              2.0    );

     s.SetGlobalStringOption("Plot",              "infoTopRight",     "CMS Preliminary");
     s.SetGlobalStringOption("Plot",              "infoTopLeft",      "#sqrt{s} = 8 TeV, L = 19.5 fb^{-1}");

     s.SetGlobalBoolOption  ("Plot",              "exportPdf",        true);
     s.SetGlobalBoolOption  ("Plot",              "exportEps",        false);
     s.SetGlobalBoolOption  ("Plot",              "exportPng",        false);

  // ########################################
  // ##       Run over the datasets        ##
  // ########################################

  vector<string> datasetsList;
  s.GetDatasetList(&datasetsList);

  cout << "   > Reading datasets... " << endl;
  cout << endl;

  for (unsigned int d = 0 ; d < datasetsList.size() ; d++)
  {
     string currentDataset = datasetsList[d];
     string currentProcessClass = s.GetProcessClass(currentDataset);

     sampleName = currentDataset;
     sampleType = s.GetProcessClassType(currentProcessClass);

     // Open the tree
     TFile f((string(FOLDER_BABYTUPLES)+currentDataset+".root").c_str());
     TTree* theTree = (TTree*) f.Get("babyTuple");

     intermediatePointers pointers;
     InitializeBranchesForReading(theTree,&myEvent,&pointers);

     if (sampleType == "signal")
     {
        theTree->SetBranchAddress("mStop",       &(myEvent.mStop));
        theTree->SetBranchAddress("mNeutralino", &(myEvent.mNeutralino));
     }
     else
     {
         myEvent.mStop       = -1;
         myEvent.mNeutralino = -1;
     }

  // ########################################
  // ##        Run over the events         ##
  // ########################################

     bool ttbarDatasetToBeSplitted = false;
      if (findSubstring(currentDataset,"ttbar"))
          ttbarDatasetToBeSplitted = true;

      int nEntries = theTree->GetEntries();
      for (int i = 0 ; i < nEntries ; i++)
      {
          //if (i > float(nEntries) * 0.1) break;

          if (i % (nEntries / 50) == 0) printProgressBar(i,nEntries,currentDataset);

          // Get the i-th entry
          ReadEvent(theTree,i,&pointers,&myEvent);

          nJets = myEvent.nJets;
          nBtag = myEvent.nBTag;

          float weight = getWeight();

          // Split 1-lepton ttbar and 2-lepton ttbar
          string currentProcessClass_ = currentProcessClass;
          if (ttbarDatasetToBeSplitted && (myEvent.numberOfGenLepton == 2))
              currentProcessClass_ = "ttbar_2l";

          #ifdef LEADING_NON_B_PT_ALREADY_COMPUTED
          leadingNonBPtN4= myEvent.leadingNonBPt;
          #else
          leadingNonBPtN4= leadingNonBPt();
          #endif
          leadingNonBPtN5=-1;
          if (nJets>4) leadingNonBPtN5= leadingNonBPtN4;

          if ((currentProcessClass_ == "T2tt") && ((myEvent.mStop != 450) || (myEvent.mNeutralino != 50))) continue;
          if ((currentProcessClass_ == "T2bw") && ((myEvent.mStop != 450) || (myEvent.mNeutralino != 50))) continue;

          computeGenInfo();
          METPtReso   = myEvent.MET    / myEvent.genMET;
          METdPhiReso = abs(Phi_mpi_pi(myEvent.METPhi - myEvent.leadingLepton.Phi())) / myEvent.genMETdPhi;

          s.AutoFillProcessClass(currentProcessClass_,weight);
      }

      printProgressBar(nEntries,nEntries,currentDataset);
      cout << endl;
      f.Close();

  }
/*
  // #############################
  // ##   Apply scale factors   ##
  // #############################

    Table scaleFactors = Table("../prediction/scaleFactors/preselection.tab");

    Figure SF_pre           = scaleFactors.Get("value","SF_pre");
    Figure SF_post          = scaleFactors.Get("value","SF_post");
    Figure SF_0btag         = scaleFactors.Get("value","SF_0btag");
    Figure SF_vetopeak      = scaleFactors.Get("value","SF_vetopeak");
    Figure SF_MTtail_1ltop  = scaleFactors.Get("value","SF_MTtail_1ltop");
    Figure SF_MTtail_Wjets  = scaleFactors.Get("value","SF_MTtail_Wjets");

    s.ApplyScaleFactor("ttbar_2l", "preselection_MTtail_withCorr",  "singleLepton", SF_pre);
    s.ApplyScaleFactor("1ltop",    "preselection_MTtail_withCorr",  "singleLepton", SF_post * SF_MTtail_1ltop);
    s.ApplyScaleFactor("W+jets",   "preselection_MTtail_withCorr",  "singleLepton", SF_post * SF_MTtail_Wjets);
*/
  // ###################################
  // ##   Make plots and write them   ##
  // ###################################

  cout << endl;
  cout << "   > Making plots..." << endl;
  s.MakePlots();
  cout << "   > Saving plots..." << endl;
  s.WritePlots("./plots/METresolution/");

  printBoxedMessage("Plot generation completed");

  // #############################
  // ##   Post-plotting tests   ##
  // #############################

  printBoxedMessage("Program done.");
  return (0);
}
コード例 #10
0
void ManagerNucleiCollisions::generateEvents( NucleiCollision *fPtrNuclStruct, int nEvents )
{
    cout << "generating events..." << endl;
    
    //reset all hists
//    fHistSources->Reset();

    TH2D *fHist2D_impParVSnStrings = new TH2D("fHist2D_impParVSnStrings", ";impact parameter, fm;n strings"
                                                , 400, 0, 20, 2001, -0.5 , 2000.5 );



    // ##### 10.07.2016 - save NucleiCollision info into the tree
    TTree *fNucleiCollisionsTree = new TTree("NucleiCollisionsTree","NucleiCollisionsTree");
    const int NMaxStrings = 35000;//8000;

    Float_t fImpactParameter = 0;
    Float_t fNuclTreeRandomEventPlanePhi = 0;
    Float_t fNuclTreeNu = 0;
    Int_t fNuclTreeNumberOfStrings = 0;
    Int_t fMultFromAllStringsFictiveV0 = 0;
    Int_t fMultFromAllStringsFictiveMidEta = 0;
//    Float_t fNuclTreeStringBoostAngle[NMaxStrings];
//    Float_t fNuclTreeStringBoostMagn[NMaxStrings];
    Float_t fDistanceBetweenPartonsForString[NMaxStrings];
    Float_t fNuclTreeStringRadiusVectorAngle[NMaxStrings];
    Float_t fNuclTreeStringX[NMaxStrings];
    Float_t fNuclTreeStringY[NMaxStrings];
    short fStringOrigin[NMaxStrings];
//    Bool_t fNuclTreeIsHardInteractionString[NMaxStrings];

    fNucleiCollisionsTree->Branch("impactParameter",&fImpactParameter,"fImpactParameter/F");
    fNucleiCollisionsTree->Branch("randomEventPlanePhi",&fNuclTreeRandomEventPlanePhi,"fNuclTreeRandomEventPlanePhi/F");
    fNucleiCollisionsTree->Branch("nu",&fNuclTreeNu,"fNuclTreeNu/F");
    fNucleiCollisionsTree->Branch("numberOfStrings",&fNuclTreeNumberOfStrings,"fNuclTreeNumberOfStrings/I");

//    fNucleiCollisionsTree->Branch("stringBoostAngle", fNuclTreeStringBoostAngle,"fNuclTreeStringBoostAngle[fNuclTreeNumberOfStrings]/F");
//    fNucleiCollisionsTree->Branch("stringBoostMagn", fNuclTreeStringBoostMagn,"fNuclTreeStringBoostMagn[fNuclTreeNumberOfStrings]/F");
    fNucleiCollisionsTree->Branch("stringX", fNuclTreeStringX,"fNuclTreeStringX[fNuclTreeNumberOfStrings]/F");
    fNucleiCollisionsTree->Branch("stringY", fNuclTreeStringY,"fNuclTreeStringY[fNuclTreeNumberOfStrings]/F");
    fNucleiCollisionsTree->Branch("distanceBetweenPartonsForString", fDistanceBetweenPartonsForString,"fDistanceBetweenPartonsForString[fNuclTreeNumberOfStrings]/F");
    fNucleiCollisionsTree->Branch("stringRadiusVectorAngle", fNuclTreeStringRadiusVectorAngle,"fNuclTreeStringRadiusVectorAngle[fNuclTreeNumberOfStrings]/F");
    fNucleiCollisionsTree->Branch("stringOrigin", fStringOrigin,"fStringOrigin[fNuclTreeNumberOfStrings]/S");
//    fNucleiCollisionsTree->Branch("isHardInteraction",fNuclTreeIsHardInteractionString,"fNuclTreeIsHardInteractionString[fNuclTreeNumberOfStrings]/O");

    fNucleiCollisionsTree->Branch( "multFromAllStringsFictiveV0", &fMultFromAllStringsFictiveV0,"fMultFromAllStringsFictiveV0/I");
    fNucleiCollisionsTree->Branch( "multFromAllStringsFictiveMidEta", &fMultFromAllStringsFictiveMidEta,"fMultFromAllStringsFictiveMidEta/I");


    // ##### event loop
    for ( int iEvent = 0; iEvent < nEvents; iEvent++)
    {
        if ( iEvent % 10 == 0 )
            cout <<"generating " << (int)iEvent << "\r"; cout.flush();

        //building event, spec impact parameter if requested:
        fPtrNuclStruct->setEventId( iEvent ); //to be used in fPtrNuclStruct for output files (tmp?)
        fPtrNuclStruct->buildEvent();
        //        fPtrNuclStruct->drawEventStructure();

        //need some event checks/triggers here?..
        if ( !fPtrNuclStruct->isMBcollision() )
        {
            iEvent--;
            continue;
        }

        fImpactParameter = fPtrNuclStruct->getImpactParameter();
        fNuclTreeNumberOfStrings = fPtrNuclStruct->getNstrings();
        fNuclTreeRandomEventPlanePhi = fPtrNuclStruct->getRandomEventPlanePhi();
        fNuclTreeNu = fPtrNuclStruct->getNu();
        fMultFromAllStringsFictiveV0 = fPtrNuclStruct->getMultFromAllStringsFictiveV0();
        fMultFromAllStringsFictiveMidEta = fPtrNuclStruct->getMultFromAllStringsFictiveMidEta();
        //cout << fMultFromAllStringsFictive << endl;

        if ( fNuclTreeNumberOfStrings >= NMaxStrings )
        {
            cout << "AHTUNG: fNuclTreeNumberOfStrings >= NMaxStrings!!!" << endl;
            return;
        }

        // ##### loop over strings
        for ( int iString = 0; iString < fNuclTreeNumberOfStrings; iString++)
        {
//            fNuclTreeStringBoostAngle[iString] = fPtrNuclStruct->getStringBoostAngle(iString);
//            fNuclTreeStringBoostMagn[iString] = fPtrNuclStruct->getStringBoostMagn(iString);
            fNuclTreeStringRadiusVectorAngle[iString] = fPtrNuclStruct->getStringRadiusVectorAngle(iString);
            fNuclTreeStringX[iString] = fPtrNuclStruct->getStringXminusBover2(iString);
            fNuclTreeStringY[iString] = fPtrNuclStruct->getStringY(iString);
            fStringOrigin[iString] = fPtrNuclStruct->getStringOrigin(iString);
            fDistanceBetweenPartonsForString[iString] = fPtrNuclStruct->getDistanceBetweenPartonsForString(iString);
//            fNuclTreeIsHardInteractionString[iString] = fPtrNuclStruct->isHardInteractionString(iString);
        }

        fHist2D_impParVSnStrings->Fill( fImpactParameter, fNuclTreeNumberOfStrings );

        fNucleiCollisionsTree->Fill();

    } // end of the event loop

    //draw the last generated event
    if (fDrawHistos)
    {
        fPtrNuclStruct->drawStatisticHists();
//        drawStatHists();
    }
    fPtrNuclStruct->finalActions();


    // ##### additional histogram with info (cross-section, etc) - March 2018
    const int nBinLabels = 3;
    TH1D *fAdditionalInfo = new TH1D( "fAdditionalInfo", "additional information from simulations;bin;value", nBinLabels,-0.5,nBinLabels-0.5);
    TString strBinLabels[nBinLabels] =
    {
//        "cross_seciton", // TUT OSHIBKA V NAPISANII!!!
        "cross_section",
        "mean_n_strings",
    };
    for( Int_t i = 1; i <= nBinLabels; i++ )
        fAdditionalInfo->GetXaxis()->SetBinLabel( i, strBinLabels[i-1].Data() );

    fAdditionalInfo->SetBinContent( 1, fPtrNuclStruct->getCrossSection() );
    fAdditionalInfo->SetBinContent( 2, fPtrNuclStruct->getMeanNstrings() );


    //
    TCanvas *canv_impParVSnStrings = new TCanvas("canv_impParVSnStrings","canvas impPar VS nStrings",380,280,800,600);
    fHist2D_impParVSnStrings->DrawCopy("colz");

    //write tree
    TFile* outFileNuclColTree = new TFile( Form( "%s/nuclCollisionsTree_nEv%d.root", fOutputDirName.Data(), nEvents ), "RECREATE" );
    outFileNuclColTree->cd();
    fNucleiCollisionsTree->Write();
    fHist2D_impParVSnStrings->Write();
    fAdditionalInfo->Write();
    outFileNuclColTree->Close();
}
コード例 #11
0
ファイル: rho_script.c プロジェクト: btcarlso/UserCode
void loop(){

	TFile *F=new TFile("TTree_SingleMu_Onia2MuMu_v20_PromptReco_AB.root","READ"); 
	TTree *tree = (TTree*)F->FindObjectAny("data"); 
	int entries = tree->GetEntries(); 
	set_branches(tree);
	
	double pt_bins[]={10,20,30,40,50,60,70,100};
	double dR_bins[]={0,0.25,0.3,0.35,0.4,0.8,1,1.5};
	int ndR=sizeof(dR_bins)/sizeof(double)-1; 
	int npT=sizeof(pt_bins)/sizeof(double)-1;
	//TEfficiency *rho = new TEfficiency("TEff_rho_pt","#rho p_{T}; p_{T}(#mu#mu) [GeV]; #rho",7,pt_bins); 
	
	CreateHistogram("hpt_lead","p_{T}(#mu) of higher p_{T} muon","p_{T}(#mu) [GeV]","#rho",100,0,100); 
	CreateHistogram("hpt_trail","p_{T}(#mu) of lower p_{T} muon","p_{T}(#mu) [GeV]","#rho",100,0,100); 

	CreateHistogram("h_mass_pt0","M_{#mu#mu}, p_{T}<35","M_{#mu#mu}","Events",100,8.5,11.5); 
	CreateHistogram("h_mass_pt1","M_{#mu#mu}, p_{T}>35","M_{#mu#mu}","Events",100,8.5,11.5); 

	CreateHistogram("h_massTrig_pt0","M_{#mu#mu}, p_{T}<35","M_{#mu#mu}","Events",100,8.5,11.5); 
	CreateHistogram("h_massTrig_pt1","M_{#mu#mu}, p_{T}>35","M_{#mu#mu}","Events",100,8.5,11.5); 
	
	CreateHistogram("DeltaRPtE_num","#DeltaR_p_{T}^{ellpictic}","#DeltaR_p_{T}^{ellpictic}","",100,0,3); 
	CreateHistogram("DeltaRPtE_num_uW","#DeltaR_p_{T}^{ellpictic}","#DeltaR_p_{T}^{ellpictic}","",100,0,3); 
	CreateHistogram("DeltaRPtE_den","#DeltaR_p_{T}^{ellpictic}","#DeltaR_p_{T}^{ellpictic}","",100,0,3); 

	
	CreateHistogram("hpt_den","#rho denominator","p_{T} [GeV]","",9,10,100); 
	CreateHistogram("hpt_num_uW","#rho numerator","p_{T} [GeV]","",9,10,100); 
	CreateHistogram("hpt_num","#rho numerator","p_{T} [GeV]","",9,10,100); 

	CreateHistogram("mass","mass","M_{#mu#mu}","",100,8.5,11.5); 
	
	CreateHistogram("mass_DeltaRPtE_num","M_{#mu#mu}","M_{#mu#mu}","#DeltaR_p_{T}^{ellpictic}",100,8.5,11.5,100,0,3);
	CreateHistogram("mass_DeltaRPtE_den","M_{#mu#mu}","M_{#mu#mu}","#DeltaR_p_{T}^{ellpictic}",100,8.5,11.5,100,0,3);

	
	CreateHistogram("mass_y0_DeltaRPtE_numBin","M_{#mu#mu}","M_{#mu#mu}","#DeltaR_p_{T}^{ellpictic}",100,8.5,11.5,ndR,dR_bins);
	CreateHistogram("mass_y0_DeltaRPtE_numBin_uW","M_{#mu#mu}","M_{#mu#mu}","#DeltaR_p_{T}^{ellpictic}",100,8.5,11.5,ndR,dR_bins);
	CreateHistogram("mass_y0_DeltaRPtE_denBin","M_{#mu#mu}","M_{#mu#mu}","#DeltaR_p_{T}^{ellpictic}",100,8.5,11.5,ndR,dR_bins);

	CreateHistogram("mass_y1_DeltaRPtE_numBin","M_{#mu#mu}","M_{#mu#mu}","#DeltaR_p_{T}^{ellpictic}",100,8.5,11.5,ndR,dR_bins);
	CreateHistogram("mass_y1_DeltaRPtE_numBin_uW","M_{#mu#mu}","M_{#mu#mu}","#DeltaR_p_{T}^{ellpictic}",100,8.5,11.5,ndR,dR_bins);
	CreateHistogram("mass_y1_DeltaRPtE_denBin","M_{#mu#mu}","M_{#mu#mu}","#DeltaR_p_{T}^{ellpictic}",100,8.5,11.5,ndR,dR_bins);


	CreateHistogram("mass_pt","M_{#mu#mu}","p_{T} [GeV]","",100,8.5,11.5,npT,pt_bins);
	CreateHistogram("mass_pt_num","M_{#mu#mu}","p_{T} [GeV]","",100,8.5,11.5,npT,pt_bins);
	CreateHistogram("mass_pt_num_uW","M_{#mu#mu}","p_{T} [GeV]","",100,8.5,11.5,npT,pt_bins);

	CreateHistogram("DeltaRPtE_pt","#DeltaR_p_{T}^{ellpictic} vs p_{T}","p_{T} [GeV]", "#DeltaR_p_{T}^{ellpictic}",9,10,100,20,0,3); 
	CreateHistogram("DeltaRPtE_pt_Trig","#DeltaR_p_{T}^{ellpictic} vs p_{T}","p_{T} [GeV]", "#DeltaR_p_{T}^{ellpictic}",9,10,100,20,0,3); 


	cout << "Entries: " << entries << endl;
	//entries=1000;
	for(int i=0; i<entries;i++){
		if(i%100000==0) {
			cout << "Event: " << i << endl;
			cout << "Run Nb: " << runNb << endl; 
		}
		tree->GetEntry(i); 

		if(D0_v1==1 || D0_v2==1 || D0_v3==1 || D0_v5==1 || D0_v6==1 || D0_v9==1 || DMu3_v1==1 || DUM0_v1==1 || DUM0_v2==1 || DUM0_v3==1 || DUM0_v4==1 || DUM0_v6==1) continue;
		if(runNb<165088 || runNb>179889) continue;
		if(Mu1_P->X()>900 || Mu2_P->X()>900) continue;
		fill_tree();
		if(!select_upsilons()) continue; 
//		if(!select_jpsi()) continue; 

		double DeltaPhi=TMath::Abs(Mu1_P->DeltaPhi(*Mu2_P)); 
		double DeltaEta=TMath::Abs(Mu1_P->Eta()-Mu2_P->Eta());
		double DeltaR=Mu1_P->DeltaR(*Mu2_P);
		double DeltaPt=TMath::Abs(Mu1_P->Perp()-Mu2_P->Perp());
		double DeltaRPtE=TMath::Sqrt(TMath::Power(0.00157*DeltaPt,2)+TMath::Power(1.2*DeltaPhi,2)+TMath::Power(DeltaEta,2));//deltaR elliptic_deltaPt

		if(Ups_P->Perp()<35)hName["h_mass_pt0"]->Fill(Ups_P->M()); 
		else hName["h_mass_pt1"]->Fill(Ups_P->M()); 
		
		hName["mass"]->Fill(Ups_P->M()); 
		hName2D["DeltaRPtE_pt"]->Fill(Ups_P->Perp(),DeltaRPtE); 
		
		hName2D["mass_pt"]->Fill(Ups_P->M(),Ups_P->Perp()); 
		int iy=-1;
		if(fabs(Ups_P->Rapidity()<0.6)) iy=0; 
		else iy=1; 
		hName2D["mass_DeltaRPtE_den"]->Fill(Ups_P->M(),DeltaRPtE); 
		hName2D[Form("mass_y%d_DeltaRPtE_denBin",iy)]->Fill(Ups_P->M(),DeltaRPtE); 
		if(Ups_P->M()>9.26 && Ups_P->M()<9.66){
			hName["hpt_den"]->Fill(Ups_P->Perp());
			hName["DeltaRPtE_den"]->Fill(DeltaRPtE);
		}


		double ptmin=TMath::Min(Mu1_P->Perp(),Mu2_P->Perp());
		double ptmax=TMath::Max(Mu1_P->Perp(),Mu2_P->Perp()); 
		
		hName["hpt_lead"]->Fill(ptmax);
		hName["hpt_trail"]->Fill(ptmin); 

		double etamin=0; 
		
		if(ptmin<Mu1_P->Perp()) etamin=Mu2_P->Eta();
		else etamin=Mu1_P->Eta();
		
		double dimuon_eff=muonEff(ptmin,etamin,"nom");
		bool Trig=false; 
		if(D5_v1==1 || D5_v2==1 || D5_v3==1 || D5_v5==1 || D7_v1==1 || D7_v4==1 || D9_v1==1 || D9_v4==1) Trig=true; 
		if(Trig && Ups_P->M()>9.26 && Ups_P->M()<9.66){
			hName["hpt_num_uW"]->Fill(Ups_P->Perp()); 
			hName["hpt_num"]->Fill(Ups_P->Perp(),1./dimuon_eff);
			hName["DeltaRPtE_num"]->Fill(DeltaRPtE,1./dimuon_eff);
			hName["DeltaRPtE_num_uW"]->Fill(DeltaRPtE); 
		}
		if(Trig){
			if(Ups_P->Perp()<35)hName["h_massTrig_pt0"]->Fill(Ups_P->M()); 
			else hName["h_massTrig_pt1"]->Fill(Ups_P->M()); 

			hName2D["mass_pt_num"]->Fill(Ups_P->M(),Ups_P->Perp(),1.0/dimuon_eff);
			hName2D["mass_pt_num_uW"]->Fill(Ups_P->M(),Ups_P->Perp());
			hName2D["mass_DeltaRPtE_num"]->Fill(Ups_P->M(),DeltaRPtE,1.0/dimuon_eff); 
			hName2D[Form("mass_y%d_DeltaRPtE_numBin",iy)]->Fill(Ups_P->M(), DeltaRPtE,1.0/dimuon_eff);
			hName2D[Form("mass_y%d_DeltaRPtE_numBin_uW",iy)]->Fill(Ups_P->M(), DeltaRPtE);
			hName2D["DeltaRPtE_pt_Trig"]->Fill(Ups_P->Perp(),DeltaRPtE);

		}

		//if(Ups_P->M()>9.26 && Ups_P->M()<9.66)rho->Fill(Trig,Ups_P->Perp());
	//	rho->SetWeight(0.97/dimuon_eff);
		
		//if(HLT_Dimuon7_Upsilon_Barrel_v1) hpt_num->Fill(Ups_P->Perp(),1./dimuon_eff); 
		
	}
		
}
コード例 #12
0
ファイル: GetEventWeightsv2.C プロジェクト: ktf/AliPhysics
void GetEventWeightsv2(Int_t incentmin=15, Int_t incentmax = 20, Int_t inRunMin=0, Int_t inRunMax=59){
  SetStyle();
  gStyle->SetOptTitle(1);
 
  centmin = incentmin;
  centmax = incentmax;
  runmin = inRunMin;
  runmax = inRunMax;
  
  for(Int_t ireg = 0;ireg<3;ireg++){
    Char_t hname[30];
    sprintf(hname,"hVz_Cent_Reg%i",ireg+1);
    hVz_Cent[ireg]=new TH2F(hname,hname,10,-5.0,5.0,centmax-centmin,centmin,centmax);
  }

  Int_t nevent1 = 0, nevent2 =0, nevent3=0;
  for(Int_t irun = runmin;irun<=runmax;irun++){
    nfile = 1;
    cout<<" Runnumber is "<<RunNumber[irun]<<endl;
    Char_t fname[120];
    sprintf(fname,"/Users/rashmiraniwala/ToALICE/ANALYSIS/V0MCentrality/Cent%3.3dto%3.3d/AsymRun%dCent%3.3dto%3.3d.root",centmin,centmax,RunNumber[irun],centmin,centmax);
    cout<<" Reading root file "<<fname<<" for asymTree "<<endl;
    
    TFile * f = new TFile(fname,"READ");
    TTree* asymTree = (TTree*)f->Get("asymTree");
    asymTree->SetBranchAddress("zdcasym",&zdcasym);
    asymTree->SetBranchAddress("fCentPercentile",fCentPercentile);
    asymTree->SetBranchAddress("fVertexZ",&fVertexZ);
    cout<<" Got asymTree with entries "<<asymTree->GetEntries()<<endl;
    for(Int_t iev = 0;iev<asymTree->GetEntries();iev++){
      asymTree->GetEntry(iev);
      //      cout<<" zdcasym, vertex, cent = "<<iev<<" "<<zdcasym<<" "<<fVertexZ<<" "<<fCentPercentile[0]<<endl;
      if(zdcasym>-1.0 && zdcasym<-0.1){
	nevent1++;
	hVz_Cent[0]->Fill(fVertexZ,fCentPercentile[0]);
      }
      if(zdcasym>0.1 && zdcasym<1.0){
	nevent2++;
	hVz_Cent[1]->Fill(fVertexZ,fCentPercentile[0]);
      }
      if(zdcasym>-0.1 && zdcasym<0.1){
	nevent3++;
	hVz_Cent[2]->Fill(fVertexZ,fCentPercentile[0]);
      }
    }
    f->Close();
    cout<<"nevent 1,2,3 = "<<nevent1<<" "<<nevent2<<" "<<nevent3<<endl;
  }
  for(Int_t ireg = 0;ireg<3;ireg++){
    cout<<" Number of events in region "<<ireg+1<<" = "<<hVz_Cent[ireg]->GetEntries()<<endl;
    hVz_Cent[ireg]->Scale(1.0/hVz_Cent[ireg]->GetEntries());
  }

  hRatio1=(TH2F*)hVz_Cent[0]->Clone("hRatio1");
  hRatio1->Divide(hVz_Cent[2]);

  hRatio2=(TH2F*)hVz_Cent[1]->Clone("hRatio2");
  hRatio2->Divide(hVz_Cent[2]);
  
  
  TCanvas * c = new TCanvas("c","c",1000,600);
  c->Divide(3,1);
  c->cd(1);
  hVz_Cent[0]->SetXTitle("Vz");
  hVz_Cent[0]->SetYTitle("Centrality %");
  hVz_Cent[0]->SetZTitle(" Number of Events");
  hVz_Cent[0]->Draw("lego");
  c->cd(2);
  hVz_Cent[1]->SetXTitle("Vz");
  hVz_Cent[1]->SetYTitle("Centrality %");
  hVz_Cent[1]->SetZTitle(" Number of Events");
  hVz_Cent[1]->Draw("lego");
  c->cd(3);
  hVz_Cent[2]->SetXTitle("Vz");
  hVz_Cent[2]->SetYTitle("Centrality %");
  hVz_Cent[2]->SetZTitle(" Number of Events");
  hVz_Cent[2]->Draw("lego");
  
  TCanvas * c1 = new TCanvas("c1","c1",900,500);
  c1->Divide(2,1);

  c1->cd(1);
  hRatio1->SetTitle("Event Weights for correction of Centrality and Vertex-Z distribution: Reg1");
  hRatio1->SetLineColor(4);
  hRatio1->SetXTitle("Vz");
  hRatio1->SetYTitle("Centrality %");
  hRatio1->SetZTitle("Ratio of Reg1/Reg3");
  hRatio1->Draw("lego");

  hRatio2->SetTitle("Event Weights for correction of Centrality and Vertex-Z distribution: Reg2");
  
  c1->cd(2);
  hRatio2->SetLineColor(2);
  hRatio2->SetXTitle("Vz");
  hRatio2->SetYTitle("Centrality %");
  hRatio2->SetZTitle("Ratio of Reg2/Reg3");
  hRatio2->Draw("lego");

  TLatex * l = new TLatex(-10,20,"Vertex-Z and Centrality Correction Weights: Region 2");
  l->SetTextSize(0.7);
  l->Draw();

  
  sprintf(fname,"/Users/rashmiraniwala/ToALICE/ANALYSIS/V0MCentrality/Cent%3.3dto%3.3d/EventWeightsCent%3.3dto%3.3d_Run%ito%i.root",centmin,centmax,centmin,centmax,runmin,runmax);
  TFile * fout = new TFile(fname,"RECREATE");
  fout->cd();
  for(Int_t ireg = 0;ireg<3;ireg++){
    hVz_Cent[ireg]->Write();
  }
  hRatio1->Write();
  hRatio2->Write();

}
コード例 #13
0
ファイル: TMVAtest1(asl).C プロジェクト: rgoldouz/tqA
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 );
}
コード例 #14
0
ファイル: plot_HE.C プロジェクト: Andrej-CMS/cmssw
// Commands executed in a GLOBAL scope, e.g. created hitograms aren't erased...
void plot_HE(TString  inputfile="simevent_HE.root",
	     TString outputfile="HE_histo.root",
	     Int_t drawmode = 2,
             TString    reffile="../data/HE_ref.root"){
 
  // Option to no-action(0)/draw(1)/save(2) (default = 0) histograms in gif.
  //int doDraw = 0; 
  int doDraw = drawmode;

  char * treename = "Events";        //The Title of Tree.
  
  delete gROOT->GetListOfFiles()->FindObject(inputfile);

  TFile * myf  = new TFile(inputfile);
  
  TTree * tree = dynamic_cast<TTree*>(myf->Get("Events"));
  assert(tree != 0);

  TBranch * branchLayer = tree->GetBranch("PHcalValidInfoLayer_g4SimHits_HcalInfoLayer_CaloTest.obj");
  assert(branchLayer != 0);

  TBranch * branchNxN = tree->GetBranch("PHcalValidInfoNxN_g4SimHits_HcalInfoNxN_CaloTest.obj");
  assert(branchNxN != 0);

  TBranch * branchJets = tree->GetBranch( "PHcalValidInfoJets_g4SimHits_HcalInfoJets_CaloTest.obj");  assert(branchJets != 0);

  // Just number of entries (same for all branches)
  int  nent = branchLayer->GetEntries();
  cout << "Entries branchLayer : " << nent << endl;
  nent = branchJets->GetEntries();
  cout << "Entries branchJets  : " << nent << endl;
  nent = branchNxN->GetEntries();
  cout << "Entries branchNxN   : " << nent << endl;

  // Variables from branches
  PHcalValidInfoJets infoJets;
  branchJets->SetAddress( &infoJets); 
  PHcalValidInfoLayer infoLayer;
  branchLayer->SetAddress( &infoLayer); 
  PHcalValidInfoNxN infoNxN;
  branchNxN->SetAddress( &infoNxN); 
  
  //***************************************************************************
  // Histo titles-labels

  const int Nhist1     = 47, Nhist2 = 1;  // N simple and N combined histos
  const int Nhist1spec =  7;              // N special out of Nsimple total 
  const int nLayersMAX = 20;
  const int nDepthsMAX =  5;

  TH1F *h;                              // just a pointer
  TH1F *h1[Nhist1];
  TH1F *h1l[nLayersMAX];                // + all scint. layers separately
  TH1F *h1d[nDepthsMAX];                // + all depths  

  TH2F *h2[Nhist2];
  TH2F *h2g[5];         // +  eta-phi grid -related for all depthes
  
  char *label1[Nhist1], *label2[Nhist2], *label1l[nLayersMAX ];
  char *label1d[nDepthsMAX], *label2g[5];
  

  // simple histos  
  label1[0]  = &"rJetHits.gif";
  label1[1]  = &"tJetHits.gif";
  label1[2]  = &"eJetHits.gif";
  label1[3]  = &"ecalJet.gif";
  label1[4]  = &"hcalJet.gif";
  label1[5]  = &"hoJet.gif";
  label1[6]  = &"etotJet.gif";
  label1[7]  = &"detaJet.gif";
  label1[8]  = &"dphiJet.gif";
  label1[9]  = &"drJet.gif";
  label1[10] = &"jetE.gif";
  label1[11] = &"jetEta.gif";
  label1[12] = &"jetPhi.gif";
  label1[13] = &"dijetM.gif";
  label1[14] = &"ecalNxNr.gif";
  label1[15] = &"hcalNxNr.gif";
  label1[16] = &"hoNxNr.gif";
  label1[17] = &"etotNxNr.gif";
  label1[18] = &"ecalNxN.gif";
  label1[19] = &"hcalNxN.gif";
  label1[20] = &"hoNxN.gif";
  label1[21] = &"etotNxN.gif";
  label1[22] = &"layerHits.gif";
  label1[23] = &"etaHits.gif";          
  label1[24] = &"phiHits.gif";
  label1[25] = &"eHits.gif";
  label1[26] = &"tHits.gif";
  label1[27] = &"idHits.gif";
  label1[28] = &"jitterHits.gif";
  label1[29] = &"eIxI.gif";
  label1[30] = &"tIxI.gif";
  label1[31] = &"eLayer.gif";
  label1[32] = &"eDepth.gif";
  label1[33] = &"eHO.gif";
  label1[34] = &"eHBHE.gif";
  label1[35] = &"elongHF.gif";
  label1[36] = &"eshortHF.gif";
  label1[37] = &"eEcalHF.gif";
  label1[38] = &"eHcalHF.gif";

  // special
  label1[39] = &"NxN_trans_fraction.gif"; 
  label1[40] = &"tHist_50ns.gif";   
  label1[41] = &"tHist_eweighted.gif"; 
  label1[42] = &"nHits_ECAL.gif";
  label1[43] = &"nHits_HCAL.gif";
  label1[44] = &"nHits.gif";
  label1[45] = &"longProf_eweighted.gif";
  label1[46] = &"E_hcal.gif";

  label1l[0] = &"layer_0.gif"; 
  label1l[1] = &"layer_1.gif"; 
  label1l[2] = &"layer_2.gif"; 
  label1l[3] = &"layer_3.gif"; 
  label1l[4] = &"layer_4.gif"; 
  label1l[5] = &"layer_5.gif"; 
  label1l[6] = &"layer_6.gif"; 
  label1l[7] = &"layer_7.gif"; 
  label1l[8] = &"layer_8.gif"; 
  label1l[9] = &"layer_9.gif"; 
  label1l[10] = &"layer_10.gif"; 
  label1l[11] = &"layer_11.gif"; 
  label1l[12] = &"layer_12.gif"; 
  label1l[13] = &"layer_13.gif"; 
  label1l[14] = &"layer_14.gif"; 
  label1l[15] = &"layer_15.gif"; 
  label1l[16] = &"layer_16.gif"; 
  label1l[17] = &"layer_17.gif"; 
  label1l[18] = &"layer_18.gif"; 
  label1l[19] = &"layer_19.gif"; 

  label1d[0] = &"depth_0.gif"; 
  label1d[1] = &"depth_1.gif"; 
  label1d[2] = &"depth_2.gif"; 
  label1d[3] = &"depth_3.gif"; 
  label1d[4] = &"depth_4.gif"; 
 
  // more complicated histos and profiles
 
  label2[0] = &"JetHCALvsECAL.gif";

  label2g[0] = &"Eta-phi_grid_depth_0.gif";
  label2g[1] = &"Eta-phi_grid_depth_1.gif";
  label2g[2] = &"Eta-phi_grid_depth_2.gif";
  label2g[3] = &"Eta-phi_grid_depth_3.gif";
  label2g[4] = &"Eta-phi_grid_all_depths.gif";

  // Some constants

  const float fact = 117.0; // sampling factor which corresponds to those 
                            // for layer = 0,1 in SimG4HcalValidation.cc

  //***************************************************************************
  //...Book histograms 

  for (Int_t i = 0; i < Nhist1-Nhist1spec; i++) {
    char hname[3]; 
    sprintf(hname,"h%d",i);

    if(i == 4 || i == 7 || i == 8 || i == 11 || i == 12 || i == 6) {
      if(i == 11) h1[i] = new TH1F(hname,label1[i],100,-5.,5.);   
      if(i == 12) h1[i] = new TH1F(hname,label1[i],72,-3.1415926,3.1415926);   
      if(i == 7 || i == 8) h1[i] = new TH1F(hname,label1[i],100,-0.1,0.1);  
      if( i == 4)          h1[i] = new TH1F(hname,label1[i],50,0.,100.);  
      if( i == 6)          h1[i] = new TH1F(hname,label1[i],50,0.,100.);
    }
    else { 
      h1[i] = new TH1F(hname,label1[i],100,1.,0.);  
    }

  }

  // Special : global timing < 50 ns 
  h1[40] = new TH1F("h40",label1[40],50,0.,50.);  
  // Special : timing in the cluster (7x7) enery-weighted
  h1[41] = new TH1F("h41",label1[41],30,0.,30.);  
  // Special : number of ECAL&HCAL hits
  h1[42] = new TH1F("h42",label1[42],300,0.,3000.);  
  h1[43] = new TH1F("h43",label1[43],300,0.,3000.);  
  h1[44] = new TH1F("h44",label1[44],300,0.,3000.);  

  // Special : Longitudinal profile
  h1[45] = new TH1F("h45",label1[45],20,0.,20.);
  // Etot HCAL
  TH1F *h1[46] = new TH1F("h46",label1[46],50,0.,1.0);
  
  for (int i = 0; i < Nhist1; i++) {
    if(i != 39)  h1[i]->Sumw2();
  }


  for (int i = 0; i < Nhist2; i++) {
    char hname[3]; 
    sprintf(hname,"D%d",i);
    h2[i] = new TH2F(hname,label2[i],100,0.,100.,100,0.,100.);
  }
  //  h[i]->Sumw2();         // to get errors properly calculated

  // scint. layers
  for (int i = 0; i < nLayersMAX; i++) {
    char hname[4]; 
    sprintf(hname,"hl%d",i);
    h1l[i] = new TH1F(hname,label1l[i],40,0.,0.4);  
  }
  // depths
  Float_t max[5] = {30000, 500, 500, 200, 200.};
  for (int i = 0; i < nDepthsMAX; i++) {
    char hname[3]; 
    sprintf(hname,"hd%d",i);
    h1d[i] = new TH1F(hname,label1d[i],100,0.,max[i]);  
  }

  // eta-phi grid (for muon samples)
  for (int i = 0; i < 5; i++) {
    char hname[3]; 
    sprintf(hname,"Dg%d",i);
    h2g[i] = new TH2F(hname,label2g[i],1000,-5.,5.,576,-3.1415927,3.1415927);
  }

  //***************************************************************************
  //***************************************************************************
  //...Fetch the data and fill the histogram 

  // branches separately - 

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

    // cout << "Ev. " << i << endl;

    // -- get entries
    branchLayer ->GetEntry(i);
    branchNxN   ->GetEntry(i);
    branchJets  ->GetEntry(i);

    // -- Leading Jet
    int nJetHits =  infoJets.njethit();
    //cout << "nJetHits = " << nJetHits << endl; 

    std::vector<float> rJetHits(nJetHits);
    rJetHits = infoJets.jethitr();
    std::vector<float> tJetHits(nJetHits);
    tJetHits = infoJets.jethitt();
    std::vector<float> eJetHits(nJetHits);
    eJetHits = infoJets.jethite();

    float ecalJet = infoJets.ecaljet();
    float hcalJet = infoJets.hcaljet();
    float   hoJet = infoJets.hojet();
    float etotJet = infoJets.etotjet();

    float detaJet = infoJets.detajet();
    float dphiJet = infoJets.dphijet();
    float   drJet = infoJets.drjet();
    float  dijetM = infoJets.dijetm();

    
    for (int j = 0; j < nJetHits; j++) {
      h1[0]->Fill(rJetHits[j]);
      h1[1]->Fill(tJetHits[j]); 
      h1[2]->Fill(eJetHits[j]);
    }
   
    h1[3]->Fill(ecalJet); //
    h1[4]->Fill(hcalJet); //

    h1[5]->Fill(hoJet);
    h1[6]->Fill(etotJet);

    h2[0]->Fill(ecalJet,hcalJet); //

    h1[7]->Fill(detaJet);
    h1[8]->Fill(dphiJet);
    h1[9]->Fill(drJet);

    h1[13]->Fill(dijetM);

    // All Jets 

    int                nJets  = infoJets.njet();
    std::vector<float> jetE  (nJets);
    jetE   = infoJets.jete();
    std::vector<float> jetEta(nJets);
    jetEta = infoJets.jeteta();
    std::vector<float> jetPhi(nJets);
    jetPhi = infoJets.jetphi();

  
    for (int j = 0; j < nJets; j++) {
      h1[10]->Fill(jetE[j]);
      h1[11]->Fill(jetEta[j]);
      h1[12]->Fill(jetPhi[j]);
    }

  
    // NxN quantities
    float ecalNxNr = infoNxN.ecalnxnr();
    float hcalNxNr = infoNxN.hcalnxnr();
    float   hoNxNr = infoNxN.honxnr();
    float etotNxNr = infoNxN.etotnxnr();

    float ecalNxN  = infoNxN.ecalnxn();
    float hcalNxN  = infoNxN.hcalnxn();
    float   hoNxN  = infoNxN.honxn();
    float etotNxN  = infoNxN.etotnxn();

    h1[14]->Fill(ecalNxNr);
    h1[15]->Fill(hcalNxNr);
    h1[16]->Fill(hoNxNr);
    h1[17]->Fill(etotNxNr);
   
    h1[18]->Fill(ecalNxN);
    h1[19]->Fill(hcalNxN);
    h1[20]->Fill(hoNxN);
    h1[21]->Fill(etotNxN);


    // CaloHits from PHcalValidInfoLayer  
    
    int                    nHits = infoLayer.nHit();
    std::vector<float>    idHits(nHits);
    idHits = infoLayer.idHit();
    std::vector<float>   phiHits(nHits);
    phiHits = infoLayer.phiHit();
    std::vector<float>   etaHits(nHits); 
    etaHits = infoLayer.etaHit();
    std::vector<float> layerHits(nHits); 
    layerHits = infoLayer.layerHit();
    std::vector<float>     eHits(nHits); 
    eHits = infoLayer.eHit();
    std::vector<float>     tHits(nHits); 
    tHits = infoLayer.tHit();

    int ne = 0, nh = 0; 
    for (int j = 0; j < nHits; j++) {
      int layer = layerHits[j]-1;
      int id    = (int)idHits[j];

      if(id >= 10) {ne++;}
      else {if (id < 5) nh++;}

      //      cout << "Hit subdet = " << id  << "  lay = " << layer << endl;

      h1[22]->Fill(Float_t(layer));
      h1[23]->Fill(etaHits[j]);
      h1[24]->Fill(phiHits[j]);
      h1[25]->Fill(eHits[j]);
      h1[26]->Fill(tHits[j]);
      h1[27]->Fill(idHits[j]);
      //      h1[28]->Fill(jitterHits[j]);   // no jitter anymore

      h1[40]->Fill(tHits[j]);
      h1[41]->Fill(tHits[j],eHits[j]);
      
      if(id < 6) { // HCAL only. Depth is needed, not layer !!!
	//if(layer == 0)               h2g[0]->Fill(etaHits[j],phiHits[j]);
	//if(layer == 1)               h2g[1]->Fill(etaHits[j],phiHits[j]);
	//if(layer == 2)               h2g[2]->Fill(etaHits[j],phiHits[j]);
	//if(layer == 3)               h2g[3]->Fill(etaHits[j],phiHits[j]);
	h2g[4]->Fill(etaHits[j],phiHits[j]);
      }
      

    }
      
    h1[42]->Fill(Float_t(ne));
    h1[43]->Fill(Float_t(nh));
    h1[44]->Fill(Float_t(nHits));

    // NxN  PHcalValidInfoNxN 
    //    cout << " nIxI = " << nIxI << endl;
    int                    nIxI = infoNxN.nnxn();
    std::vector<float>    idIxI(nIxI);  
    idIxI = infoNxN.idnxn();
    std::vector<float>     eIxI(nIxI); 
    eIxI  = infoNxN.enxn();
    std::vector<float>     tIxI(nIxI); 
    tIxI  = infoNxN.tnxn();
    
    for (int j = 0; j < nIxI ; j++) {   // NB !!! j < nIxI
      h1[29]->Fill(eIxI[j]);
      h1[30]->Fill(tIxI[j]);

      h1[39]->Fill(idIxI[j],eIxI[j]);  // transverse profile

    }

    // Layers and depths PHcalValidInfoLayer
    
    std::vector<float> eLayer(nLayersMAX);
    eLayer = infoLayer.elayer();
    std::vector<float> eDepth(nDepthsMAX);
    eDepth = infoLayer.edepth();
    
    float eTot = 0.;

    for (int j = 0; j < nLayersMAX ; j++) {
      h1[31]->Fill(eLayer[j]);
      h1l[j]->Fill(eLayer[j]);

	h1[45]->Fill((Float_t)(j),eLayer[j]);  // HCAL SimHits only 
        eTot += eLayer[j];
    }
    for (int j = 0; j < nDepthsMAX; j++) {
      h1[32]->Fill(eDepth[j]);
      h1d[j]->Fill(eDepth[j]);
    }

    h1[46]->Fill(eTot);               
       
    // The rest  PHcalValidInfoLayer
    float eHO      =  infoLayer.eho(); 
    float eHBHE    =  infoLayer.ehbhe(); 
    float elongHF  =  infoLayer.elonghf(); 
    float eshortHF =  infoLayer.eshorthf(); 
    float eEcalHF  =  infoLayer.eecalhf(); 
    float eHcalHF  =  infoLayer.ehcalhf(); 

    h1[33]->Fill(eHO);
    h1[34]->Fill(eHBHE);
 
    h1[35]->Fill(elongHF);
    h1[36]->Fill(eshortHF);
    h1[37]->Fill(eEcalHF);
    h1[38]->Fill(eHcalHF);

  }

  // cout << "After event cycle " << i << endl;


  //...Prepare the main canva 
  TCanvas *myc = new TCanvas("myc","",800,600);
  gStyle->SetOptStat(1111);   // set stat         :0 - nothing 
 
  // Cycle for 1D distributions
  for (int ihist = 0; ihist < Nhist1 ; ihist++) {
    if(h1[ihist]->Integral() > 1.e-30 && h1[ihist]->Integral() < 1.e30 ) { 
      
      h1[ihist]->SetLineColor(45);
      h1[ihist]->SetLineWidth(2); 
      
      if(doDraw == 1) {
	h1[ihist]->Draw("h");
	myc->SaveAs(label1[ihist]);
      }
    }
  }

  // Cycle for energy in all layers
  for (int ihist = 0; ihist < nLayersMAX; ihist++) {
    if(h1l[ihist]->Integral() > 1.e-30 && h1l[ihist]->Integral() < 1.e30 ) { 
      
      h1l[ihist]->SetLineColor(45);
      h1l[ihist]->SetLineWidth(2); 


      if(doDraw == 1) {
	h1l[ihist]->Draw("h");
	myc->SaveAs(label1l[ihist]);
      }
    }
  }


  // Cycle for 2D distributions 
  //  for (int ihist = 0; ihist < 1 ; ihist++) {
  for (int ihist = 0; ihist < Nhist2 ; ihist++) {
    if(h2[ihist]->Integral() > 1.e-30 && h2[ihist]->Integral() < 1.e30 ) { 

      h2[ihist]->SetMarkerColor(45);
      h2[ihist]->SetMarkerStyle(20);
      h2[ihist]->SetMarkerSize(0.7);  // marker size !
      
      h2[ihist]->SetLineColor(45);
      h2[ihist]->SetLineWidth(2); 
      
      if(doDraw == 1) {
	h2[ihist]->Draw();
	myc->SaveAs(label2[ihist]);
      }
    }
  }
  
 
  // Cycle for eta-phi grids 
  //  for (int ihist = 0; ihist < 5 ; ihist++) {
  for (int ihist = 4; ihist < 5 ; ihist++) {
    if(h2g[ihist]->Integral() > 1.e-30 && h2g[ihist]->Integral() < 1.e30 ) { 
      
      h2g[ihist]->SetMarkerColor(41);
      h2g[ihist]->SetMarkerStyle(20);
      h2g[ihist]->SetMarkerSize(0.2); 
      
      h2g[ihist]->SetLineColor(41);
      h2g[ihist]->SetLineWidth(2); 
      
      if(doDraw == 1) {
	h2g[ihist]->Draw();
	myc->SaveAs(label2g[ihist]);
      }
    }
  }
 

 

  // added by Julia Yarba
  //-----------------------   
  // this is a temporary stuff that I've made
  // to create a reference ROOT histogram file


  if (doDraw == 2) {
    TFile OutFile(outputfile,"RECREATE") ;
    int ih = 0 ;
    for ( ih=0; ih<nLayersMAX; ih++ )
      {
	h1l[ih]->Write() ;
      }
    for ( ih=0; ih<Nhist1; ih++ )
      { 
	h1[ih]->Write() ;
      }

    OutFile.Write() ;
    OutFile.Close() ;
    cout << outputfile << " histogram file created" << endl ;
    
    return ;
    
  }
  /*
  return;
  */
 

   // now perform Chi2 test for histograms that hold
   // energy deposition in the Hcal layers 1-10, using
   // "reference" and "current" histograms 
   
   
   // open up ref. ROOT file
   //
   TFile RefFile(reffile) ;
   
   // service variables
   //
   TH1F* ref_hist = 0 ;
   int ih = 0 ;
   
   // loop over layers 1-10 
   //
   for ( ih=1; ih<11; ih++ )
   {
      // service - name of the ref histo
      //
      char ref_hname[4] ;
      sprintf( ref_hname, "hl%d", ih ) ;
      
      // retrive ref.histos one by one
      //
      ref_hist = (TH1F*)RefFile.Get( ref_hname ) ;
      
      // check if valid (no-NULL)
      //
      if ( ref_hist == NULL )
      {
         // print warning in case of trouble
	 //
	 cout << "No such ref. histogram" << *ref_hname << endl ; 
      }
      else
      {
         // everything OK - perform Chi2 test
	 //
	Double_t *res;
	Double_t pval = h1l[ih]->Chi2Test( ref_hist, "UU", res ) ;
	 
	 // output Chi2 comparison results
	 //
	 cout << "[OVAL] : Edep in Layer " << ih << ", p-value= " << pval << endl ;
      }
   }


   // loop over specials : timing,  nhits(ECAL and HCAL) 
   //
   for ( ih=40; ih<47; ih++ )
   {
      // service - name of the ref histo
      //
      char ref_hname[4] ;
      sprintf( ref_hname, "h%d", ih ) ;
      
      // retrive ref.histos one by one
      //
      ref_hist = (TH1F*)RefFile.Get( ref_hname ) ;
      
      // check if valid (no-NULL)
      //
      if ( ref_hist == NULL )
      {
         // print warning in case of trouble
	 //
	 cout << "No such ref. histogram" << *ref_hname << endl ; 
      }
      else
      {
	// everything OK - perform Chi2 test
	//
	Double_t *res;
	Double_t pval = h1[ih]->Chi2Test( ref_hist, "UU", res) ;
	
	// output Chi2 comparison results
	//
	cout << "[OVAL] : histo " << ih << ", p-value= " << pval << endl ;
      }
   }

   
   // close ref. ROOT file
   //
   RefFile.Close() ;
   
  // at the end, close "current" ROOT tree file
  //
  myf->Close();


  return ;  
}
コード例 #15
0
static void s_TEST_Tree()
{
    typedef CTreeNode<int>  TTree;
    
    TTree* tr = new TTree(0);
    TTree* tr10 = tr->AddNode(10);
    tr->AddNode(11);
    tr10->AddNode(20);
    tr10->AddNode(21);
   
    TTree* sr = new TTree(0);
    sr->AddNode(10);
    sr->AddNode(11);

    TTree* ur = new TTree(0);
    ur->AddNode(10);
    ur->AddNode(11);
    ur->AddNode(20);
    ur->AddNode(21);
    

//    TreePrint(cout, *tr, (IntConvType) NStr::IntToString);
//    TreeReRoot(*tr10);
//    TreePrint(cout, *tr10, (IntConvType) NStr::IntToString);

    cout << "Testing Breadth First Traversal" << endl;
    TreeBreadthFirstTraverse(*tr, TestFunctor2);
    cout << endl;

    cout << "Testing Depth First Traversal" << endl;
    TreeDepthFirstTraverse(*tr, TestFunctor1);
    cout << endl;

    cout << "Testing Tree Comparison" << endl;
    cout << "tr and tr10 are ";
    if(!TreeCompare(*tr, *tr10, TestFunctor3)) cout << "not ";
    cout << "the same." << endl;
    cout << "tr and tr are ";
    if(!TreeCompare(*tr, *tr, TestFunctor3)) cout << "not ";
    cout << "the same." << endl;
    cout << "tr and sr are ";
    if(!TreeCompare(*tr, *sr, TestFunctor3)) cout << "not ";
    cout << "the same." << endl;
    cout << "tr and ur are ";
    if(!TreeCompare(*tr, *ur, TestFunctor3)) cout << "not ";
    cout << "the same." << endl;
    cout << "sr and ur are ";
    if(!TreeCompare(*sr, *ur, TestFunctor3)) cout << "not ";
    cout << "the same." << endl;
    cout << endl;

    {{
    unsigned int cnt;
    TTree::TNodeList_CI it = tr->SubNodeBegin();
    TTree::TNodeList_CI it_end = tr->SubNodeEnd();
    
    for (cnt = 0; it != it_end; ++it, ++cnt) {
        const TTree* t = *it;
        int v = t->GetValue();
        assert(v == 10 || v == 11);
    }
    assert(cnt == 2);
    }}
    
    {{
    TTree* tr2 = new TTree(*tr);
    unsigned int cnt;
    TTree::TNodeList_CI it = tr2->SubNodeBegin();
    TTree::TNodeList_CI it_end = tr2->SubNodeEnd();
    
    for (cnt = 0; it != it_end; ++it, ++cnt) {
        const TTree* t = *it;
        int v = t->GetValue();
        assert(v == 10 || v == 11);
    }
    assert(cnt == 2);
    delete tr2;
    }}
    
    
    {{
    TTree::TNodeList_I it = tr->SubNodeBegin();
    TTree::TNodeList_I it_end = tr->SubNodeEnd();
    
    for (; it != it_end; ++it) {
        TTree* t = *it;
        int v = t->GetValue();
        if (v == 10)
        {
            tr->RemoveNode(t);
            break;
        }
    }
    }}

    TreeDepthFirstTraverse(*tr, TestFunctor1);
    cout << endl;

    {{
    unsigned int cnt;
    TTree::TNodeList_CI it = tr->SubNodeBegin();
    TTree::TNodeList_CI it_end = tr->SubNodeEnd();
    
    for (cnt = 0; it != it_end; ++it, ++cnt) {
        const TTree* t = *it;
        int v = t->GetValue();
        assert(v == 11);
    }
    assert(cnt == 1);
    }}
    
    delete tr;

    TTree* str = tr = new TTree(0);
    
    //
    // 0 - 2 
    //       - 4
    //   - 3 
    //       - 5
    //       - 6
    //

    TTree* tr4 = tr->AddNode(2)->AddNode(4);
    tr = tr->AddNode(3);
    TTree* tr5 = tr->AddNode(5);
    TTree* tr6 = tr->AddNode(6);

    cout << "Test Tree: " << endl;

    TreeDepthFirstTraverse(*str, TestFunctor1);
    cout << endl;

    vector<const TTree*> trace_vec;
    TreeTraceToRoot(*tr6, trace_vec);

    assert(trace_vec.size() == 3);

    {{
    cout << "Trace to root: ";

    ITERATE(vector<const TTree*>, it, trace_vec) {
        cout << (*it)->GetValue() << "; ";
    }

    cout << endl;

    }}

    const TTree* parent_node = TreeFindCommonParent(*tr4, *tr6);

    assert(tr4->IsParent(*parent_node));
    assert(tr6->IsParent(*parent_node));
    assert(!tr4->IsParent(*tr6));


    assert(parent_node);

    cout << "parent: " << parent_node->GetValue() << endl;

    assert(parent_node->GetValue() == 0);

    parent_node = TreeFindCommonParent(*tr5, *tr6);
    assert(parent_node);
    assert(parent_node->GetValue() == 3);


    TreePrint(cout, *str, s_IntToStr);
    cout << endl;

    TreeReRoot(*tr5);
    TreePrint(cout, *tr5, s_IntToStr);

    tr5->MoveSubnodes(str);
    TreePrint(cout, *tr5, s_IntToStr);

    delete tr5;
    delete ur;
    delete sr;
}
コード例 #16
0
ファイル: plotHadTau.C プロジェクト: arapyan/MitHtt
void plotHadTau(std::string iVar="TMath::Min(abs(jphi_1-jphi_2),6.28-abs(jphi_1-jphi_2))",std::string iCut="vbf",std::string iName="can",std::string iDir="mtau/2012/mtau/",bool is2012=true,int iTauId = 2,bool iEmbed=true) { 
  //void plotHadTau(std::string iVar="pt_2*(1.015 + 0.001 * TMath::Min(TMath::Max(pt_2-45,0),10))",std::string iCut="(nprong_2 == 1 && ngamma_2 > 0  && pt_1 > 20 && iso_1 < 0.1 && iso_2 > 0.795  && pt_1 > 20   && nbtag == 0)",std::string iName="can",std::string iDir="mtau/2012/mtau/",bool is2012=true,int iTauId = 2,bool iEmbed=true) { 
//void plotHadTau(std::string iVar="mvamet*((acos(cos(mvametphi-phi_1)) > TMath::Pi()/2.)+(acos(cos(mvametphi-phi_1)) < TMath::Pi()/2.)*cos(mvametphi-phi_1))",std::string iCut="(pt_1 > 24 && pt_2 > 20 && iso_1 < 0.1 && iso_2 > 0.785 )",std::string iName="can",std::string iDir="2012/etau",int iTauId = 2,bool is2012=true,bool iEmbed=false) { 
  float iLumi = 4800.;
  if(is2012) iLumi = 19100.;
  //SetStyle();
  loadfMap();
  std::stringstream lNameId; //lNameId << "Flat_" << lTauId << "_";
  const int lN = 6;
  std::string lName = iDir+"ntuples/";
  //std::string lName1 = "2011/mutau/ntuples/";
  //std::string lName = "svfit/"+iDir;
  //std::string lName = iDir;

  fWId   = 2;
  fQCDId = 4;
  
  TTree **lTree = new TTree*[lN]; 
  TH1F**lH     = new TH1F*[lN]; 
  TH1F**lHSS   = new TH1F*[lN];
  TH1F**lHIso  = new TH1F*[lN];
  TH1F**lHMT   = new TH1F*[lN]; 
  TH1F**lHNMT  = new TH1F*[lN]; 
  TH1F**lHSSMT = new TH1F*[lN]; 
  TH1F**lHTIS  = new TH1F*[lN]; 
  TH1F**lHLIS  = new TH1F*[lN]; 
  TH1F**lHTemp = new TH1F*[lN]; 
  fString = new std::string[lN]; fWeights = new std::string[lN]; fColor = new int[lN]; fFreeWeights = new std::string[lN];
  lTree[0]     = load(lName+"ztt-mad_select.root");        fString[0] = "Z#rightarrow#tau#tau ";          fColor[0] = 796;//kOrange-3;
  lTree[1]     = load(lName+"ttbar-8TeV_select.root");     fString[1] = "t#bar{t}";                       fColor[1] = 592;//kRed+4;
  lTree[2]     = load(lName+"wjets_select.root");          fString[2] = "W+Jets";                         fColor[2] = 634;//kBlue-5;
  lTree[3]     = load(lName+"zmm_select.root");            fString[3] = "Z#rightarrow#tau#tau fakes";     fColor[3] = kBlue;
  lTree[4]     = load(lName+"data_select.root");           fString[4] = "QCD";                            fColor[4] = 606;//kBlue+3;
  //lTree[5]     = load(lName+"higgs_select.root");          fString[5] = "Higgs ";                         fColor[5] = kBlack;
  lTree[lN-1]  = load(lName+"data_select.root");        fString[lN-1] = "Data"; fColor[lN-1] = kBlack;
  TTree *lEmbTree  = load(lName+"ztt-emb_select.root"); 

  std::stringstream lLumi; lLumi << iLumi;
  if(iCut != "vbf") for(int i0 = 0; i0 < lN;   i0++) fWeights[i0]   = "(pt_1 > 20 && pt_2 > 20 && abs(eta_1) < 2.1 && abs(eta_2) < 2.3 )*"+iCut;
  if(iCut == "vbf") for(int i0 = 0; i0 < lN;   i0++) fWeights[i0]  += "(pt_1 > 20 && pt_2 > 20 && abs(eta_1) < 2.1 && abs(eta_2) < 2.3 )";

  for(int i0 = 0; i0 < lN-1; i0++) if(i0 != fQCDId ) fWeights[i0]  += "*weight*"+lLumi.str();//effweight*puOBweight*"+lLumi.str();
  //Z Scale Factors
  if(!is2012) { 
    fWeights[0]  += "*0.95";
    //fWeights[1]  += "*0.1";
    fWeights[3]  += "*0.95";
  }
  if(is2012) fWeights[1]  += "*1.01";//*0.1";//0.9*0.1";
  if(is2012) fWeights[0]  += "*1.01";
  if(is2012) fWeights[3]  += "*1.01";
  //if(iCut == "vbf") fWeights[2] += "*(weight < 0.1)";
  if(iCut == "vbf") for(int i0 = 0; i0 < lN;   i0++) fFreeWeights[i0]  += "(mjj > 300 && jdeta > 2.5 && iso_1 < 0.1 && iso_2 > 0.795 )";

  if(iEmbed) {
    TH1F *lMC = new TH1F("pXX","pXX",21,0,1000);
    TH1F *lDa = new TH1F("pAA","pAA",21,0,1000);
    std::string lCut = "weight*(pt_1 > 20 && pt_2 > 20 && abs(eta_1) < 2.1 && abs(eta_2) < 2.3 && iso_1 < 0.1 && iso_2 > 0.795 && genmass > 70)*"+lLumi.str();
    lTree[0]->Draw("pt_2>>pXX" ,lCut.c_str());
    lEmbTree->Draw("pt_2>>pAA" ,lCut.c_str());
    cout << "===> " << lMC->Integral() << " - " << lDa->Integral() << endl;
    double lIncWeight = lMC->Integral()/lDa->Integral();
    std::stringstream pSS; pSS << lIncWeight << "*";
    fWeights[0]   = pSS.str()+fWeights[0];
  delete lTree[0];
  lTree[0] = lEmbTree;
  }
  //bool applyVBFVeto

  std::string lVar = iVar;
  TCanvas *lC0 = new TCanvas("A","A",400,400);
  if(iCut != "vbf") drawSpec   (lTree,lH,lHSS,lHMT,lHNMT,lHSSMT,lHTIS              ,lN,lVar,"*( pt_2 > -10.105)",iName );    lC0->cd();
  if(iCut == "vbf") drawVBFSpec(lTree,lH,lHSS,lHMT,lHLIS,lHTIS ,lHNMT,lHSSMT,lHTemp,lN,lVar,"*( pt_2 > -10.105)",is2012);    lC0->cd();
}
コード例 #17
0
static void s_TEST_IdTreeOperations()
{
    cout << "--------------------- s_TEST_IdTreeOperations " << endl;

    typedef CTreeNode<IdValue> TTree;

    TTree* tr = new TTree(0);

    TTree* tr10 = tr->AddNode(10);
    TTree* tr11 = tr->AddNode(11);
    TTree* tr110 = tr10->AddNode(110);
    TTree* tr1100 = tr110->AddNode(1100);

    TreePrint(cout, *tr, s_IdValueToStr);

    bm::bvector<> bv;
    TreeMakeSubNodesSet(*tr, bv.inserter());
    assert(bv.count() == 2);
    assert(bv[10]);
    assert(bv[11]);

    typedef vector<TTree*> TNodeList;
    TNodeList node_list;
    node_list.push_back(tr10);
    node_list.push_back(tr11);
    node_list.push_back(tr110);
    node_list.push_back(tr1100);

    TNodeList res_node_list;

    CTreeNonRedundantSet<TTree, bm::bvector<>, TNodeList> nr_func;
    nr_func(node_list, res_node_list);

    cout << "Non-redundant set:" << endl;
    ITERATE(TNodeList, it, res_node_list) {
        cout << (*it)->GetValue().GetId() << "; ";
    }
    cout << endl;
    assert(res_node_list.size() == 2);


    res_node_list.clear();
    node_list.clear();

    node_list.push_back(tr110);
    node_list.push_back(tr1100);

    CTreeMinimalSet<TTree, bm::bvector<>, TNodeList> min_func;
    min_func(node_list, res_node_list);

    
    cout << "Minimal set:" << endl;
    ITERATE(TNodeList, it, res_node_list) {
        cout << (*it)->GetValue().GetId() << "; ";
    }
    cout << endl;
    cout << "-----" << endl;
    assert(res_node_list.size() == 1);


    res_node_list.clear();
    node_list.clear();


    node_list.push_back(tr110);
    node_list.push_back(tr1100);
    node_list.push_back(tr11);

    min_func(node_list, res_node_list);

    
    cout << "Minimal set:" << endl;
    ITERATE(TNodeList, it, res_node_list) {
        cout << (*it)->GetValue().GetId() << "; ";
    }
    cout << endl;
    cout << "-----" << endl;
    assert(res_node_list.size() == 1);


    res_node_list.clear();
    node_list.clear();


    
    TNodeList node_list_a;
    TNodeList node_list_b;
    TNodeList node_list_c;

    node_list_a.push_back(tr10);
    node_list_a.push_back(tr11);
    node_list_a.push_back(tr110);
    node_list_a.push_back(tr1100);
    
    node_list_b.push_back(tr10);
    node_list_b.push_back(tr11);
    node_list_b.push_back(tr110);

    CTreeNodesAnd<TTree, bm::bvector<>, TNodeList> and_func;
    and_func(node_list_a, node_list_b, node_list_c);

    ITERATE(TNodeList, it, node_list_c) {
        cout << (*it)->GetValue().GetId() << "; ";
    }
    cout << endl;
    assert(node_list_c.size() == 3);


    node_list_c.clear();

    CTreeNodesOr<TTree, bm::bvector<>, TNodeList> or_func;
    or_func(node_list_a, node_list_b, node_list_c);

    ITERATE(TNodeList, it, node_list_c) {
        cout << (*it)->GetValue().GetId() << "; ";
    }
    cout << endl;
    assert(node_list_c.size() == 4);


    delete tr;

    cout << "--------------------- s_TEST_IdTreeOperations ok" << endl;
}
コード例 #18
0
ファイル: p_ela.c プロジェクト: ekawa/test
int p_ela() {

  TRandom *r = new TRandom();

  //reaction
  TGenPhaseSpace event1;//p(gamma, omega)p
  TLorentzVector TotalLv1;

  //Initial state
  TLorentzVector * Beam_Lv = new TLorentzVector();
  TLorentzVector * Tgt_Lv = new TLorentzVector();



  //Final state
  TLorentzVector *Proton1_Lv = new TLorentzVector();
  TLorentzVector *Proton2_Lv = new TLorentzVector();

  //tree component
  double p1mom;
  double p1mom_x;
  double p1mom_y;
  double p1mom_z;
  double p2mom;
  double p2mom_x;
  double p2mom_y;
  double p2mom_z;
  double theta_p1;
  double theta_p2;
  double theta_12;



  //Set Initial Condition
  double beame=0.1;
  double beammom=sqrt( (0.1+M_PROTON)**2 - M_PROTON**2 );

  TVector3 mom_Beam(0.,0.,beammom);
  TVector3 mom_Tgt(0.,0.,0.);
  Beam_Lv->SetVectM(mom_Beam,M_PROTON);
  Tgt_Lv->SetVectM(mom_Tgt,M_PROTON);
  TotalLv1 = (*Beam_Lv) + (*Tgt_Lv);// Total Vector



  //Set Output file
  TFile *f = new TFile("p_ela.root","recreate");
  TTree *  tree = new TTree("tree","p_ela production");

  tree->Branch("beam"  ,  "TLorentzVector",      &Beam_Lv, 32000, 1);
  tree->Branch("tgt"   ,  "TLorentzVector",       &Tgt_Lv, 32000, 1);
  tree->Branch("proton1", "TLorentzVector",   &Proton1_Lv, 32000, 1);
  tree->Branch("proton2", "TLorentzVector",   &Proton2_Lv, 32000, 1);
  tree->Branch("p1mom"  ,     &p1mom,     "p1mom/D");
  tree->Branch("p1mom_x",   &p1mom_x,   "p1mom_x/D");
  tree->Branch("p1mom_y",   &p1mom_y,   "p1mom_y/D");
  tree->Branch("p1mom_z",   &p1mom_z,   "p1mom_z/D");
  tree->Branch("p2mom"  ,     &p2mom,     "p2mom/D");
  tree->Branch("p2mom_x",   &p2mom_x,   "p2mom_x/D");
  tree->Branch("p2mom_y",   &p2mom_y,   "p2mom_y/D");
  tree->Branch("p2mom_z",   &p2mom_z,   "p2mom_z/D");
  tree->Branch("theta_p1", &theta_p1,  "theta_p1/D");
  tree->Branch("theta_p2", &theta_p2,  "theta_p2/D");
  tree->Branch("theta_12", &theta_12,  "theta_12/D");

  //Event Generation start!
  int Max_No = 10000;  // repeat no
  int i=0;


  double masses[2];
  double weight=0;
  double comp=0;
  masses[0] = M_PROTON;
  masses[1] = M_PROTON;

  event1.SetDecay(TotalLv1, 2, masses, "Fermi");///Total E, particle No, particle mass

  do{
    if(i%1000 == 0){
      std::cout<<"ev_no=" << i <<std::endl;
    }
    int try_no=0;
    do{
      comp=r->Uniform(0.,0.5);
      weight =event1.Generate();
      try_no++;
    }while(comp > weight);




    std::cout << "weight = "<<weight << " comp = "<<comp <<" try_no ="<<try_no <<std::endl;

    if(TotalLv1.Mag() < masses[0] + masses[1]  ){
      std::cout<<"event1 not happen!" << TotalLv1.Mag() <<":"
        << masses[0] + masses[1]<<std::endl;
      continue;
    }

    Proton1_Lv = event1.GetDecay(0);
    Proton2_Lv = event1.GetDecay(1);


    p1mom   = Proton1_Lv->Vect().Mag();
    p1mom_x = Proton1_Lv->X();
    p1mom_y = Proton1_Lv->Y();
    p1mom_z = Proton1_Lv->Z();
    p2mom   = Proton2_Lv->Vect().Mag();
    p2mom_x = Proton2_Lv->X();
    p2mom_y = Proton2_Lv->Y();
    p2mom_z = Proton2_Lv->Z();
    theta_p1  = acos( p1mom_z/p1mom );
    theta_p2  = acos( p2mom_z/p2mom );
    theta_12  = acos( (p1mom_x*p2mom_x + p1mom_y*p2mom_y + p1mom_z*p2mom_z) / (p1mom*p2mom) );


    tree->Fill();

    i++;
  }while(i<Max_No);



  tree->Write();


  f->Close();

}
コード例 #19
0
static void s_TEST_TreeOperations()
{
  
  typedef CTreeNode<int> TTree;
  
  TTree* orig = new TTree(0);
  TTree* orig10 = orig->AddNode(10);
  TTree* orig11 = orig->AddNode(11);
  orig10->AddNode(20);
  orig10->AddNode(21);
  orig11->AddNode(22);
  orig11->AddNode(23);
  
  TTree* corr = new TTree(11);
  corr->AddNode(22);
  corr->AddNode(23);
  TTree* corr0 = corr->AddNode(0);
  TTree* corr10 = corr0->AddNode(10);
  corr10->AddNode(20);
  corr10->AddNode(21);

  TreeReRoot(*orig10);

  cout << "After rerooting original tree by node 10, " << endl;
  cout << "the original tree and correct tree are now ";
  if(TreeCompare(*orig10, *corr, TestFunctor3)) {
    cout << "the same." << endl;
  }
  else {
    cout << "different." << endl;
  }
  cout << endl;

  TreePrint(cout, *orig10, s_IntToStr, false);
  TreePrint(cout, *corr, s_IntToStr, false);
  cout << endl;
  /*
  TTree* corr2 = new TTree(11);
  corr2->AddNode(22);
  corr2->AddNode(23);
  corr2->AddNode(0);
 
  TTree* t = orig->DetachNode(orig10);

  cout << "After removing node 10 from this tree, " << endl;
  cout << "the original tree and correct tree are now ";
  if(TreeCompare(*orig11, *corr2, TestFunctor3)) {
    cout << "the same." << endl;
  }
  else {
    cout << "different." << endl;
  }
  cout << endl;
   
  TreePrint(cout, *orig11, s_IntToStr, false);
  TreePrint(cout, *t, s_IntToStr, false);
  TreePrint(cout, *corr2, s_IntToStr, false);
  cout << endl;
  */
    delete orig->GetRoot();
    delete corr->GetRoot();
}
コード例 #20
0
ファイル: makePUM0Table.C プロジェクト: richard-cms/L1macros
void makePUM0Table()
{
  const TString l1_input = "/mnt/hadoop/cms/store/user/luck/L1Emulator/minbiasHIanalyzer_withregions.root";
  TFile *lFile = TFile::Open(l1_input);
  TTree *l1Tree = (TTree*)lFile->Get("L1UpgradeAnalyzer/L1UpgradeTree");

  Int_t l1_event, l1_run;
  Int_t l1_num;
  Int_t region_hwPt[NREG], region_hwEta[NREG], region_hwPhi[NREG], region_tauVeto[NREG];

  l1Tree->SetBranchAddress("event",&l1_event);
  l1Tree->SetBranchAddress("run",&l1_run);
  l1Tree->SetBranchAddress("nRegions",&l1_num);
  l1Tree->SetBranchAddress("region_hwPt",region_hwPt);
  l1Tree->SetBranchAddress("region_hwEta",region_hwEta);
  l1Tree->SetBranchAddress("region_hwPhi",region_hwPhi);
  l1Tree->SetBranchAddress("region_tauVeto",region_tauVeto);

  const TString forest_input = "/mnt/hadoop/cms/store/user/luck/L1Emulator/minbiasForest_merged_v2/HiForest_PbPb_Data_minbias_fromSkim.root";
  TFile *fFile = TFile::Open(forest_input);
  TTree *fEvtTree = (TTree*)fFile->Get("hiEvtAnalyzer/HiTree");
  TTree *fSkimTree = (TTree*)fFile->Get("skimanalysis/HltTree");

  Int_t f_evt, f_run, f_lumi;
  Int_t hiBin;
  fEvtTree->SetBranchAddress("evt",&f_evt);
  fEvtTree->SetBranchAddress("run",&f_run);
  fEvtTree->SetBranchAddress("lumi",&f_lumi);
  fEvtTree->SetBranchAddress("hiBin",&hiBin);

  Int_t pcollisionEventSelection, pHBHENoiseFilter;
  fSkimTree->SetBranchAddress("pcollisionEventSelection",&pcollisionEventSelection);
  fSkimTree->SetBranchAddress("pHBHENoiseFilter",&pHBHENoiseFilter);

  TFile *outFile = new TFile("HI_PUM0_evtsel_out.root","RECREATE");

  std::map<Long64_t, Long64_t> kmap;

  // choose loop over l1 tree first (smaller)
  //std::cout << "Begin making map." << std::endl;
  Long64_t l_entries = l1Tree->GetEntries();
  for(Long64_t j = 0; j < l_entries; ++j)
  {
    l1Tree->GetEntry(j);
    Long64_t key = makeKey(l1_run, l1_event);

    std::pair<Long64_t,Long64_t> p(key,j);
    kmap.insert(p);
  }
  //std::cout << "Finished making map." << std::endl;

  outFile->cd();

  TH1I *hists[22][18]; // [eta][pu bin], arbitrary value of 18 for # bins in pu
  for(int i = 0; i < 22; ++i)
    for(int j = 0; j < 18; ++j)
    {
      hists[i][j] = new TH1I(Form("hist_%d_%d",i,j),"", 1024,0,1024);
    }

  TH2I *centPUM = new TH2I("cenPUM","",200,0,200,396,0,396);
  int count = 0;

  Long64_t entries = fEvtTree->GetEntries();
  for(Long64_t j = 0; j < entries; ++j)
  {
    //if(j % 10000 == 0)
    //  printf("%lld / %lld\n",j,entries);

    fEvtTree->GetEntry(j);
    Long64_t key = makeKey(f_run, f_evt);

    std::map<Long64_t,Long64_t>::const_iterator got = kmap.find(key);
    if(got == kmap.end() ) {
      continue;
    } else {
      l1Tree->GetEntry(got->second);
      kmap.erase(key);
      count++;

      fSkimTree->GetEntry(j);
      if((pcollisionEventSelection == 1) && (pHBHENoiseFilter == 1))
      {

	//int pubin = (int) ( (double)hiBin * (18.0/200.0));
	int PUM0 = 0;
	for(int i = 0; i < NREG; ++i)
	{
	  if(region_hwPt[i] > 0)
	    ++PUM0;
	}
	int pubin = PUM0/22;
	if(pubin == 18) pubin = 17; //special case for every region firing
	for(int i = 0; i < NREG; ++i)
	{
	  hists[region_hwEta[i]][pubin]->Fill(region_hwPt[i]);
	}
	centPUM->Fill(hiBin,PUM0);

      }
    }
  }

  std::cout << "cms.vdouble(";
  TH1D *hists_eta[22];
  for(int i = 0; i < 22; ++i)
  {
    hists_eta[i] = new TH1D(Form("hists_eta_%d",i),"",18,0,17);
    for(int j = 0; j < 18; ++j)
    {
      double Mean = hists[i][j]->GetMean();
      double MeanError = hists[i][j]->GetMeanError();
      hists_eta[i]->SetBinContent(j,Mean);
      hists_eta[i]->SetBinError(j,MeanError);
      std::cout << Mean*0.5;
      if(!((i == 21) && (j == 17))) std::cout << ", ";
    }
  }
  std::cout << ")" << std::endl;

  for(int i = 0; i < 22; ++i)
  {
    hists_eta[i]->Write();
    for(int j = 0; j < 18; ++j)
    {
      hists[i][j]->Write();
    }
  }
  centPUM->Write();


  //std::cout << "Matching entries: " << count << std::endl;

  lFile->Close();
  fFile->Close();
  outFile->Close();
}
コード例 #21
0
ファイル: TestSPlot.C プロジェクト: adevress/root-1
void TestSPlot()
{
//This tutorial illustrates the use of class TSPlot and of the sPlots method
//
//It is an example of analysis of charmless B decays, performed for BABAR.
//One is dealing with a data sample in which two species are present:
//the first is termed signal and the second background. 
//A maximum Likelihood fit is performed to obtain the two yields N1 and N2
//The fit relies on two discriminating variables collectively denoted y, 
//which are chosen within three possible variables denoted Mes, dE and F.
//The variable which is not incorporated in y, is used as the control variable x.
//The distributions of discriminating variables and more details about the method 
//can be found in the TSPlot class description
//
// NOTE: This script requires a data file "TestSPlot_toyMC.dat".
//       This data file is not distributed in the standard ROOT binary tar file.
//       You can download it from ftp://root.cern.ch/root/TestSPlot_toyMC.dat
//
//Authors: Anna Kreshuk, Muriel Pivc

   TString dir = gSystem->UnixPathName(gInterpreter->GetCurrentMacroName());
   dir.ReplaceAll("TestSPlot.C","");
   dir.ReplaceAll("/./","/");
   TString dataFile = Form("%sTestSPlot_toyMC.dat",dir.Data());
   
   //Read the data and initialize a TSPlot object
   TTree *datatree = new TTree("datatree", "datatree");
   datatree->ReadFile(dataFile, 
                      "Mes/D:dE/D:F/D:MesSignal/D:MesBackground/D:dESignal/D:dEBackground/D:FSignal/D:FBackground/D",' ');

   TSPlot *splot = new TSPlot(0, 3, 5420, 2, datatree);

   //Set the selection for data tree
   //Note the order of the variables: 
   //first the control variables (not presented in this example),
   //then the 3 discriminating variables, then their probability distribution 
   //functions for the first species(signal) and then their pdfs for the 
   //second species(background)
   splot->SetTreeSelection(
      "Mes:dE:F:MesSignal:dESignal:FSignal:MesBackground:"
      "dEBackground:FBackground");

   //Set the initial estimates of the number of events in each species 
   //- used as initial parameter values for the Minuit likelihood fit
   Int_t ne[2];
   ne[0]=500; ne[1]=5000;
   splot->SetInitialNumbersOfSpecies(ne);

   //Compute the weights
   splot->MakeSPlot();

   //Fill the sPlots
   splot->FillSWeightsHists(25);

   //Now let's look at the sPlots
   //The first two histograms are sPlots for the Mes variable signal and 
   //background. dE and F were chosen as discriminating variables to determine 
   //N1 and N2, through a maximum Likelihood fit, and thus the sPlots for the 
   //control variable Mes, unknown to the fit, was contructed.
   //One can see that the sPlot for signal reproduces the PDF correctly, 
   //even when the latter vanishes.
   //
   //The lower two histograms are sPlots for the F variables signal and 
   //background. dE and Mes were chosen as discriminating variables to 
   //determine N1 and N2, through a maximum Likelihood fit, and thus the 
   //sPlots for the control variable F, unknown to the fit, was contructed.

   TCanvas *myc = new TCanvas("myc", 
   "sPlots of Mes and F signal and background", 800, 600);
   myc->SetFillColor(40);

   TPaveText *pt = new TPaveText(0.02,0.85,0.98,0.98);
   pt->SetFillColor(18);
   pt->SetTextFont(20);
   pt->SetTextColor(4);
   pt->AddText("sPlots of Mes and F signal and background,");
   pt->AddText("obtained by the tutorial TestSPlot.C on BABAR MC "
               "data (sPlot_toyMC.fit)");
   TText *t3=pt->AddText(
      "M. Pivk and F. R. Le Diberder, Nucl.Inst.Meth.A, physics/0402083");
   t3->SetTextColor(1);
   t3->SetTextFont(30);
   pt->Draw();

   TPad* pad1 = new TPad("pad1","Mes signal",0.02,0.43,0.48,0.83,33);
   TPad* pad2 = new TPad("pad2","Mes background",0.5,0.43,0.98,0.83,33);
   TPad* pad3 = new TPad("pad3", "F signal", 0.02, 0.02, 0.48, 0.41,33);
   TPad* pad4 = new TPad("pad4", "F background", 0.5, 0.02, 0.98, 0.41,33);
   pad1->Draw();
   pad2->Draw();
   pad3->Draw();
   pad4->Draw();

   pad1->cd();
   pad1->SetGrid();
   TH1D *sweight00 = splot->GetSWeightsHist(-1, 0, 0);
   sweight00->SetTitle("Mes signal");
   sweight00->SetStats(kFALSE);
   sweight00->Draw("e");
   sweight00->SetMarkerStyle(21);
   sweight00->SetMarkerSize(0.7);
   sweight00->SetMarkerColor(2);
   sweight00->SetLineColor(2);
   sweight00->GetXaxis()->SetLabelSize(0.05);
   sweight00->GetYaxis()->SetLabelSize(0.06);
   sweight00->GetXaxis()->SetLabelOffset(0.02);

   pad2->cd();
   pad2->SetGrid();
   TH1D *sweight10 = splot->GetSWeightsHist(-1, 1, 0);
   sweight10->SetTitle("Mes background");
   sweight10->SetStats(kFALSE);
   sweight10->Draw("e");
   sweight10->SetMarkerStyle(21);
   sweight10->SetMarkerSize(0.7);
   sweight10->SetMarkerColor(2);
   sweight10->SetLineColor(2);
   sweight10->GetXaxis()->SetLabelSize(0.05);
   sweight10->GetYaxis()->SetLabelSize(0.06);
   sweight10->GetXaxis()->SetLabelOffset(0.02);
 
   pad3->cd();
   pad3->SetGrid();
   TH1D *sweight02 = splot->GetSWeightsHist(-1, 0, 2);
   sweight02->SetTitle("F signal");
   sweight02->SetStats(kFALSE);
   sweight02->Draw("e");
   sweight02->SetMarkerStyle(21);
   sweight02->SetMarkerSize(0.7);
   sweight02->SetMarkerColor(2);
   sweight02->SetLineColor(2);
   sweight02->GetXaxis()->SetLabelSize(0.06);
   sweight02->GetYaxis()->SetLabelSize(0.06);
   sweight02->GetXaxis()->SetLabelOffset(0.01);

   pad4->cd();
   pad4->SetGrid();
   TH1D *sweight12 = splot->GetSWeightsHist(-1, 1, 2);
   sweight12->SetTitle("F background");
   sweight12->SetStats(kFALSE);
   sweight12->Draw("e");
   sweight12->SetMarkerStyle(21);
   sweight12->SetMarkerSize(0.7);
   sweight12->SetMarkerColor(2);
   sweight12->SetLineColor(2);
   sweight12->GetXaxis()->SetLabelSize(0.06);
   sweight12->GetYaxis()->SetLabelSize(0.06);
   sweight02->GetXaxis()->SetLabelOffset(0.01);
   myc->cd();
}
コード例 #22
0
ファイル: PlotTool.c プロジェクト: ChiWang/DmpSW
void MapsPlot(TString filename){

  // Tool to make some maps plots
  cout << "Opening ROOT file: " << filename <<endl;

  gROOT->Reset();
  gStyle->SetOptStat(0);
  gStyle->SetPalette(1);
  //gStyle->SetCanvasColor(33);
  //gStyle->SetFrameFillColor(18);


  TFile *f = TFile::Open(filename);
  f->ls();



  TTree *MapTree = (TTree*)f->Get("MapTree");
  Int_t ev;
  Double_t lat_geo, lon_geo, rad_geo;
  Double_t dipoleMoment, L, B, bEast, bNorth, bDown, bAbs, bEquator, R, verticalRigidityCutoff, invariantLatitude; 
  Double_t BVect[3];
  Int_t LatSteps,LonSteps;


  
  MapTree->SetBranchAddress("lat_geo", &lat_geo);
  MapTree->SetBranchAddress("lon_geo", &lon_geo);
  MapTree->SetBranchAddress("rad_geo", &rad_geo);
  // Geomagnetic Section 
  MapTree->SetBranchAddress("dipoleMoment", &dipoleMoment);
  MapTree->SetBranchAddress("L", &L);

  MapTree->SetBranchAddress("bEast", &bEast);
  MapTree->SetBranchAddress("bNorth", &bNorth);
  MapTree->SetBranchAddress("bDown", &bDown);
  MapTree->SetBranchAddress("bAbs", &bAbs);
  OrbitTree->SetBranchAddress("BVect", &BVect);

  
  MapTree->SetBranchAddress("verticalRigidityCutoff", &verticalRigidityCutoff);
  MapTree->SetBranchAddress("invariantLatitude", &invariantLatitude);
  MapTree->SetBranchAddress("LatSteps", &LatSteps);
  MapTree->SetBranchAddress("LonSteps", &LonSteps);

  MapTree->GetEntry(1);
  Int_t iLatSteps = LatSteps;
  Int_t iLonSteps = LonSteps;
 

  TH2D *h_BAbs_Map = new TH2D("h_BAbs_Map", "Map of Magnetic field in Gauss", iLonSteps,0., +360.,iLatSteps, -90., 90. );
  TH2D *h_VRC_Map = new TH2D("h_VRC_Map", "Map of Vertical Rigidity Cutoff", iLonSteps,0., +360.,iLatSteps, -90., 90. );
 
  


  Int_t nentries = (Int_t)MapTree->GetEntries();
  for (Int_t i=0; i<nentries; i++) {
    MapTree->GetEntry(i);
    //cout << "lat_geo: " << lat_geo << " lon_geo "<<lon_geo << endl;
    h_BAbs_Map->Fill(lon_geo, lat_geo, bAbs);
    h_VRC_Map->Fill(lon_geo, lat_geo,verticalRigidityCutoff ); 
  }


  TCanvas *c1 = new TCanvas("c1", "c1", 600, 600);
  c1->Divide(1,2);
  c1->cd(1);
  h_BAbs_Map->DrawCopy("COLZ");
  c1->cd(2);
  h_VRC_Map->DrawCopy("COLZ");

  f->Close();

}
コード例 #23
0
ファイル: readOutAnglesWW.C プロジェクト: nhanvtran/usercode
void readOutAnglesWW(std::string filename, bool debug = false ) {
  
  ifstream fin;
  std::string filenameT = filename + ".txt";
  std::cout << "Processing " << filenameT << std::endl;
  fin.open(filenameT.c_str());
  int maxEvents = 1000000;
  
  char oname[192];
  sprintf(oname,"%s.root",filename.c_str());
  TFile fout(oname, "RECREATE");
  TTree* tree = new TTree("angles", "angles");
  
  Double_t m_costheta1, m_costheta2, m_phi, m_costhetastar, m_phistar1, m_phistar2, m_phistar12, m_phi1, m_phi2;
  Double_t m_wwmass, m_wplusmass, m_wminusmass;
  
  tree->Branch("wwmass", &m_wwmass, "wwmass/D");
  tree->Branch("wplusmass", &m_wplusmass, "wplusmass/D");
  tree->Branch("wminusmass", &m_wminusmass, "wminusmass/D");
  
  tree->Branch("costheta1", &m_costheta1, "costheta1/D");
  tree->Branch("costheta2", &m_costheta2, "costheta2/D");
  tree->Branch("phi", &m_phi, "phi/D");
  tree->Branch("costhetastar", &m_costhetastar, "costhetastar/D");
  tree->Branch("phi1", &m_phi1, "phi1/D");
  tree->Branch("phi2", &m_phi2, "phi2/D");
  tree->Branch("phistar1", &m_phistar1, "phistar1/D");
  tree->Branch("phistar2", &m_phistar2, "phistar2/D");
  tree->Branch("phistar12", &m_phistar12, "phistar12/D");
  
  Double_t m_lplus_pT, m_nu_pT, m_lminus_pT, m_nubar_pT;
  tree->Branch("lp_pT", &m_lplus_pT, "lp_pT/D");
  tree->Branch("nu_pT", &m_nu_pT, "nu_pT/D");
  tree->Branch("lm_pT", &m_lminus_pT, "lm_pT/D");
  tree->Branch("nubar_pT", &m_nubar_pT, "nubar_pT/D");
  
  //
  // WW analysis specific variables
  // 
  Double_t m_dphill, m_mll, m_leadleppt, m_trailleppt, m_met, m_dilpt, m_mt, m_leadlepeta, m_traillepeta;
  tree->Branch("dphill", &m_dphill, "dphill/D");
  tree->Branch("mll", &m_mll, "mll/D");
  tree->Branch("leadleppt", &m_leadleppt, "leadleppt/D");
  tree->Branch("trailleppt", &m_trailleppt, "trailleppt/D");
  tree->Branch("leadlepeta", &m_leadlepeta, "leadlepeta/D");
  tree->Branch("traillepeta", &m_traillepeta, "traillepeta/D");
  tree->Branch("met", &m_met, "met/D");	
  tree->Branch("mt", &m_mt, "mt/D");
  tree->Branch("dilpt", &m_dilpt, "dilpt/D");
  
  // 
  // resonance pT
  // 
  Double_t m_xpt, m_xmass;
  tree->Branch("xpt", &m_xpt, "xpt/D");
  tree->Branch("xmass", &m_xmass, "xmass/D");


  int ctr = 0;
  int iFile = 0;
  while (!fin.eof() && fin.good()) {
    
    std::vector <double> listOfMom;
    int idup[4], istup[4], mothup[4][2], icolup[4][2];
    double pup[4][5], vtimup[4], spinup[4];
    
    for (int a = 0; a < 4; a++){
      fin >> idup[a] >> istup[a] >> mothup[a][0] >> mothup[a][1] >> icolup[a][0] >> icolup[a][1];
      // std::cout <<  idup[a] << " " << istup[a] << " " <<  mothup[a][0]  << " " << mothup[a][1] << " " <<  icolup[a][0] << " " << icolup[a][1] << "\n";
      for (int i = 0; i < 5; i++)
	{
	  fin >> pup[a][i];
	}
      fin >> vtimup[a] >> spinup[a];
    }
    
    bool takeEvent = true;
    // check if one of the Id is tau or nu tau
    if ( TMath::Abs(idup[0]) == 15 || TMath::Abs(idup[1]) == 15 || TMath::Abs(idup[2]) == 15 || TMath::Abs(idup[2]) == 15 ) takeEvent = false;
    if ( TMath::Abs(idup[0]) == 16 || TMath::Abs(idup[1]) == 16 || TMath::Abs(idup[2]) == 16 || TMath::Abs(idup[2]) == 16 ) takeEvent = false;

    if ( !takeEvent && debug ) {
      std::cout << "--------------------------------\n";
      std::cout << "Event rejected \n";
      std::cout << idup[0] << ": " << pup[0][0] << "\t" << pup[0][1] << "\t" << pup[0][2] << "\t" << pup[0][3] << "\n";
      std::cout << idup[1] << ": " << pup[1][0] << "\t" << pup[1][1] << "\t" << pup[1][2] << "\t" << pup[1][3] << "\n";
      std::cout << idup[2] << ": " << pup[2][0] << "\t" << pup[2][1] << "\t" << pup[2][2] << "\t" << pup[2][3] << "\n";
      std::cout << idup[3] << ": " << pup[3][0] << "\t" << pup[3][1] << "\t" << pup[3][2] << "\t" << pup[3][3] << "\n";
    }


    TLorentzVector nu, lplus, nubar, lminus;    
    if (takeEvent) {
      
      if (mothup[0][0] == mothup[1][0]){
	lplus = new TLorentzVector(pup[0][0], pup[0][1], pup[0][2], pup[0][3]);
	nu = new TLorentzVector(pup[1][0], pup[1][1], pup[1][2], pup[1][3]);
	if (idup[2] < 0){
	  nubar = new TLorentzVector(pup[2][0], pup[2][1], pup[2][2], pup[2][3]);
	  lminus = new TLorentzVector(pup[3][0], pup[3][1], pup[3][2], pup[3][3]);		
	}
	else {
	  lminus = new TLorentzVector(pup[2][0], pup[2][1], pup[2][2], pup[2][3]);
	  nubar = new TLorentzVector(pup[3][0], pup[3][1], pup[3][2], pup[3][3]);						
	}
      }
      else if (mothup[0][0] == mothup[2][0]){
	lplus = new TLorentzVector(pup[0][0], pup[0][1], pup[0][2], pup[0][3]);
	nu = new TLorentzVector(pup[2][0], pup[2][1], pup[2][2], pup[2][3]);
	if (idup[1] < 0){
	  nubar = new TLorentzVector(pup[1][0], pup[1][1], pup[1][2], pup[1][3]);
	  lminus = new TLorentzVector(pup[3][0], pup[3][1], pup[3][2], pup[3][3]);		
	}
	else {
	  lminus = new TLorentzVector(pup[1][0], pup[1][1], pup[1][2], pup[1][3]);
	  nubar = new TLorentzVector(pup[3][0], pup[3][1], pup[3][2], pup[3][3]);			
	}
      }
      else if (mothup[0][0] == mothup[3][0]){
	lplus = new TLorentzVector(pup[0][0], pup[0][1], pup[0][2], pup[0][3]);
	nu = new TLorentzVector(pup[3][0], pup[3][1], pup[3][2], pup[3][3]);
	if (idup[1] < 0){
	  nubar = new TLorentzVector(pup[1][0], pup[1][1], pup[1][2], pup[1][3]);
	  lminus = new TLorentzVector(pup[2][0], pup[2][1], pup[2][2], pup[2][3]);		
	}
	else {
	  lminus = new TLorentzVector(pup[1][0], pup[1][1], pup[1][2], pup[1][3]);
	  nubar = new TLorentzVector(pup[2][0], pup[2][1], pup[2][2], pup[2][3]);		
	}				
      }
     
      TLorentzVector Wplus = nu+lplus;
      TLorentzVector Wminus = nubar+lminus;
      TLorentzVector X = Wplus + Wminus;

      if ( debug ) {
	std::cout << "--------------------------------\n";
	std::cout << "Event accepted \n";
	std::cout << Form("nu (px, py, pz, E): (%.3f, %.3f, %.3f, %.3f) \n", nu.Px(), nu.Py(), nu.Pz(), nu.E());
	std::cout << Form("lplus (px, py, pz, E): (%.3f, %.3f, %.3f, %.3f) \n", lplus.Px(), lplus.Py(), lplus.Pz(), lplus.E());
	std::cout << Form("lminus (px, py, pz, E): (%.3f, %.3f, %.3f, %.3f) \n", lminus.Px(), lminus.Py(), lminus.Pz(), lminus.E());
	std::cout << Form("nubar (px, py, pz, E): (%.3f, %.3f, %.3f, %.3f) \n", nubar.Px(), nubar.Py(), nubar.Pz(), nubar.E());
	std::cout << Form("WW pT: %.3f \n", X.Pt() );
      }
      
      double angle_costheta1, angle_costheta2, angle_phi, angle_costhetastar, angle_phistar1, angle_phistar2, angle_phistar12, angle_phi1, angle_phi2;
      calculateAngles( X, Wplus, nu, lplus,  Wminus, lminus, nubar, angle_costheta1, angle_costheta2, angle_phi, angle_costhetastar, angle_phistar1, angle_phistar2, angle_phistar12, angle_phi1, angle_phi2, false);
      
      m_costheta1 = angle_costheta1;
      m_costheta2 = angle_costheta2;
      m_phi = angle_phi;
      m_costhetastar = angle_costhetastar;
      m_phistar1 = angle_phistar1;
      m_phistar2 = angle_phistar2;
      m_phistar12 = angle_phistar12;
      m_phi1 = angle_phi1;
      m_phi2 = angle_phi2;
      
      m_wwmass = X.M();
      m_wplusmass = Wplus.M();
      m_wminusmass = Wminus.M();
      
      m_lplus_pT = lplus.Pt();
      m_nu_pT = nu.Pt();
      m_lminus_pT = lminus.Pt();
      m_nubar_pT = nubar.Pt();
      
      // 
      // get the WW analysis variables
      // 
      double dphillvalue = lplus.Phi() - lminus.Phi();
      while (dphillvalue > TMath::Pi()) dphillvalue -= 2*TMath::Pi();
      while (dphillvalue <= -TMath::Pi()) dphillvalue += 2*TMath::Pi();
      m_dphill  = TMath::Abs(dphillvalue);
      m_mll = (lplus + lminus).M();
      
      m_leadleppt = lplus.Pt() > lminus.Pt() ? lplus.Pt() : lminus.Pt();
      m_trailleppt = lplus.Pt() < lminus.Pt() ? lplus.Pt() : lminus.Pt();
      m_leadlepeta = lplus.Pt() > lminus.Pt() ? lplus.Eta() : lminus.Eta();
      m_traillepeta = lplus.Pt() < lminus.Pt() ? lplus.Eta() : lminus.Eta();
      m_met = sqrt(pow(nu.Px()+nubar.Px(), 2) + pow(nu.Py()+nubar.Py(), 2));
      m_dilpt = (lplus+lminus).Pt();
      double dphidilmet = (lplus+lminus).Phi() - (nu+nubar).Phi();
      while (dphidilmet > TMath::Pi()) dphidilmet -= 2*TMath::Pi();
      while (dphidilmet <= -TMath::Pi()) dphidilmet += 2*TMath::Pi();
      m_mt  = 2*sqrt(m_dilpt * m_met ) * fabs(sin(dphidilmet / 2.));
      m_xpt = X.Pt();
      m_xmass = X.M();
      // std::cout << __LINE__ << "\n";
      tree->Fill();
    }
    
    // counter
    ctr++;
    if (ctr%10000 == 0) std::cout << "event number: " << ctr << std::endl;
    if (ctr == maxEvents) break;
  }
  
  fout.cd();
  tree->Write();
  fout.Close();
  
}
コード例 #24
0
ファイル: validationPlots.C プロジェクト: abaty/Run2_trkVal
void validationPlots()
{
  bool isMB = 1;  

  int doCentCut = 0;
  int doEtaCut = 0; 
  int doPtCut = 0;
  const char * ptCut = "trkPt>30 && trkPt<300";
  int doFake = 0;
  int doVtx = 1;
  int nEvt = 2;

  bool doFineMVABins = 0;

  TH1::SetDefaultSumw2();
  TLatex * lat = new TLatex(0.5,0.5,"test");

  TFile * fMC;
  TFile * fDa;
  //if(isMB) fMC = TFile::Open("/mnt/hadoop/cms/store/user/dgulhan/hiForest_HydjetMB_2076GeV_FOREST_753p1_merged/HydjetMB_2076GeV_FOREST_753p1_v0_merged.root","read");
  if(isMB) fDa = TFile::Open("HiForest.root","read");
  if(!isMB) fMC = TFile::Open("/mnt/hadoop/cms/store/user/dgulhan/mergedForest/HiForest_HydjetMB_Pyquen_DiJet_pt80to9999_2670GeV_cfi_753_patch1/HiForest_HydjetMB_Pyquen_DiJet_pt80to9999_2670GeV_cfi_753_patch1_run1_mc_v2.root","read");
  if(!isMB) fDa = TFile::Open("/mnt/hadoop/cms/store/user/dgulhan/HiForest_HIHighPt_HIRun2011-v1_RECO_753_patch1_Jet80_merged/HiForest_HIHighPt_jet80_HIRun2011-v1_merged.root","read");

  TTree * tree[2];
  tree[0] = (TTree*)fDa->Get("hltAnaTrack/trackTree");
  tree[1] = (TTree*)fDa->Get("anaTrack/trackTree");
  TTree * hiBinTree[2];
  hiBinTree[0] = (TTree*)fDa->Get("hiEvtAnalyzer/HiTree");
  hiBinTree[1] = (TTree*)fDa->Get("hiEvtAnalyzer/HiTree");

  TH1D * daVtx = new TH1D("daVtx",";z",30,-15,15);
  TH1D * mcVtx = new TH1D("mcVtx",";z",30,-15,15);
  tree[1]->Draw("zVtx[0]>>daVtx","","",100000);
  tree[0]->Draw("zVtx[0]>>mcVtx","","",100000);
  daVtx->Scale(1.0/daVtx->Integral(1,30));
  mcVtx->Scale(1.0/mcVtx->Integral(1,30));
 // mcVtx->Divide(daVtx);

  TH1D * daHiBin = new TH1D("daHiBin",";hiBin",100,0,200);
  TH1D * mcHiBin = new TH1D("mcHiBin",";hiBin",100,0,200);
  hiBinTree[1]->Draw("hiBin>>daHiBin","");
  hiBinTree[0]->Draw("hiBin>>mcHiBin","");
  daHiBin->Scale(1.0/daHiBin->Integral(1,100));
  mcHiBin->Scale(1.0/mcHiBin->Integral(1,100));
//  mcHiBin->Divide(daHiBin);
  std::cout << "here" << std::endl;


  int hiBin = 0;
  float hiBinw = 0;
  float vz[200] = {0};
  float weight = 0;
  tree[1]->SetBranchAddress("zVtx",&vz);
  hiBinTree[1]->SetBranchAddress("hiBin",&hiBin);
  TFile * f = TFile::Open("vertexWeight.root","recreate");
  TTree * w = new TTree("w","w");
  w->Branch("vtxw",&weight);
  w->Branch("hiBinw",&hiBinw);
  for(int i=0; i<nEvt; i++)
  {
    if(i%1000==0) std::cout << i << std::endl;
    tree[1]->GetEntry(i);
    hiBinTree[1]->GetEntry(i);
    weight=mcVtx->GetBinContent(mcVtx->FindBin(vz[0]));
    hiBinw=mcHiBin->GetBinContent(mcHiBin->FindBin(hiBin));
    weight=1;
    hiBinw=1;
    w->Fill();
  }
  w->Write();
  tree[1]->AddFriend(w);
  tree[1]->AddFriend(hiBinTree[1]);
  tree[0]->AddFriend(w);
  tree[0]->AddFriend(hiBinTree[0]);
  std::cout << "done writing vtx tree" << std::endl;

  TH1D *chi2[6][2][2], *dxy[6][2][2], *dz[6][2][2], *nhit[6][2][2], *nlayer[6][2][2], *eta[6][2][2], *pterr[6][2][2], *mva[6][2][2], *mvaRat[6][2][1];

  int algos[5] = {4,5,6,7,11};
  const char *algName[5] = {" (Initial)"," (low pt triplet)"," (pixel pair)"," (detached)"," (jet-core)"};
  int nTracks[6][2][2];

  for(int algo = 0; algo<6; algo++)
  {
    for(int purity = 0; purity <2; purity++)
    {
      for(int sample = 0; sample<2; sample++)
      {
        chi2[algo][purity][sample] = new TH1D(Form("chi2%d%d%d",algo,purity,sample),";chi2/ndof/nlayer;dN/dchi2",100,0,1);
        chi2[algo][purity][sample]->SetMarkerSize(0.8); 
        tree[sample]->Draw(Form("trkChi2/(1.0*trkNlayer*trkNdof)>>chi2%d%d%d",algo,purity,sample),Form("(1+(vtxw-1)*(%d&&%d))*(1+(hiBinw-1)*(%d))*(((highPurity== 1)||(highPurity==%d)) && (trkEta>-2.4 && trkEta<2.4) && (%d==5 || %d==trkAlgo) && ((%s) || (!%d)) && ((trkEta>0.8 || trkEta<-0.8) || (!%d))&& ((hiBin>=100 && hiBin<200) || (!%d)))",sample,doVtx,sample,purity,algo,algos[algo],ptCut,doPtCut,doEtaCut,doCentCut),"",nEvt);
        chi2[algo][purity][sample]->Scale(1.0/chi2[algo][purity][sample]->Integral(1,100));
        chi2[algo][purity][sample]->GetYaxis()->SetRangeUser(0,0.2);
        std::cout << algo << std::endl;  
    
        dxy[algo][purity][sample] = new TH1D(Form("dxy%d%d%d",algo,purity,sample),";dxy/dxyerr;dN/(dxy/dxyerr)",100,-100,100);
        dxy[algo][purity][sample]->SetMarkerSize(0.8); 
        tree[sample]->Draw(Form("trkDxy1/(1.0*trkDxyError1)>>dxy%d%d%d",algo,purity,sample),Form("(1+(vtxw-1)*(%d&&%d))*(1+(hiBinw-1)*(%d))*(((highPurity== 1)||(highPurity==%d))  && (trkEta>-2.4 && trkEta<2.4) && (%d==5 || %d==trkAlgo) && ((%s) || (!%d))&& ((trkEta>0.8 || trkEta<-0.8) || (!%d))&& ((hiBin>=100 && hiBin<200) || (!%d)))",sample,doVtx,sample,purity,algo,algos[algo],ptCut,doPtCut,doEtaCut,doCentCut),"",nEvt);
        dxy[algo][purity][sample]->Scale(1.0/dxy[algo][purity][sample]->Integral(1,100));
        dxy[algo][purity][sample]->GetYaxis()->SetRangeUser(10e-7,1);
        
        dz[algo][purity][sample] = new TH1D(Form("dz%d%d%d",algo,purity,sample),";dz/dzerr;dN/(dz/dzerr)",100,-100,100);
        dz[algo][purity][sample]->SetMarkerSize(0.8);
        tree[sample]->Draw(Form("trkDz1/(1.0*trkDzError1)>>dz%d%d%d",algo,purity,sample),Form("(1+(vtxw-1)*(%d&&%d))*(1+(hiBinw-1)*(%d))*(((highPurity== 1)||(highPurity==%d))  && (trkEta>-2.4 && trkEta<2.4) && (%d==5 || %d==trkAlgo) && ((%s) || (!%d))&& ((trkEta>0.8 || trkEta<-0.8) || (!%d))&& ((hiBin>=100 && hiBin<200) || (!%d)))",sample,doVtx,sample,purity,algo,algos[algo],ptCut,doPtCut,doEtaCut,doCentCut),"",nEvt);
        dz[algo][purity][sample]->Scale(1.0/dz[algo][purity][sample]->Integral(1,100));
        dz[algo][purity][sample]->GetYaxis()->SetRangeUser(10e-7,1);

        nhit[algo][purity][sample] = new TH1D(Form("nhit%d%d%d",algo,purity,sample),";nhit;dN/nhit",28,3,30);
        nhit[algo][purity][sample]->SetMarkerSize(0.8); 
        tree[sample]->Draw(Form("trkNHit>>nhit%d%d%d",algo,purity,sample),Form("(1+(vtxw-1)*(%d&&%d))*(1+(hiBinw-1)*(%d))*(((highPurity== 1)||(highPurity==%d))  && (trkEta>-2.4 && trkEta<2.4) && (%d==5 || %d==trkAlgo) && ((%s) || (!%d))&& ((trkEta>0.8 || trkEta<-0.8) || (!%d))&& ((hiBin>=100 && hiBin<200) || (!%d)))",sample,doVtx,sample,purity,algo,algos[algo],ptCut,doPtCut,doEtaCut,doCentCut),"",nEvt);
        nhit[algo][purity][sample]->Scale(1.0/nhit[algo][purity][sample]->Integral(1,28));
        nhit[algo][purity][sample]->GetYaxis()->SetRangeUser(0,0.25);
        
        nlayer[algo][purity][sample] = new TH1D(Form("nlayer%d%d%d",algo,purity,sample),";nlayer;dN/nlayer",22,4,25);
        nlayer[algo][purity][sample]->SetMarkerSize(0.8); 
        tree[sample]->Draw(Form("trkNlayer>>nlayer%d%d%d",algo,purity,sample),Form("(1+(vtxw-1)*(%d&&%d))*(1+(hiBinw-1)*(%d))*(((highPurity== 1)||(highPurity==%d))  && (trkEta>-2.4 && trkEta<2.4) && (%d==5 || %d==trkAlgo) && ((%s) || (!%d))&& ((trkEta>0.8 || trkEta<-0.8) || (!%d))&& ((hiBin>=100 && hiBin<200) || (!%d)))",sample,doVtx,sample,purity,algo,algos[algo],ptCut,doPtCut,doEtaCut,doCentCut),"",nEvt);
        nlayer[algo][purity][sample]->Scale(1.0/nlayer[algo][purity][sample]->Integral(1,22));
        nlayer[algo][purity][sample]->GetYaxis()->SetRangeUser(0.0,0.3);
        
        eta[algo][purity][sample] = new TH1D(Form("eta%d%d%d",algo,purity,sample),";eta;dN/eta",50,-2.4,2.4);
        eta[algo][purity][sample]->SetMarkerSize(0.8); 
        tree[sample]->Draw(Form("trkEta>>eta%d%d%d",algo,purity,sample),Form("(1+(vtxw-1)*(%d&&%d))*(1+(hiBinw-1)*(%d))*(((highPurity== 1)||(highPurity==%d))  && (trkEta>-2.4 && trkEta<2.4) && (%d==5 || %d==trkAlgo) && ((%s) || (!%d))&& ((trkEta>0.8 || trkEta<-0.8) || (!%d))&& ((hiBin>=100 && hiBin<200) || (!%d)))",sample,doVtx,sample,purity,algo,algos[algo],ptCut,doPtCut,doEtaCut,doCentCut),"",nEvt);
        eta[algo][purity][sample]->Scale(1.0/eta[algo][purity][sample]->Integral(1,50));
        eta[algo][purity][sample]->GetYaxis()->SetRangeUser(0.0,0.03);
        
        pterr[algo][purity][sample] = new TH1D(Form("pterr%d%d%d",algo,purity,sample),";pterr;dN/(pt/pterr)",50,0,0.05);
        pterr[algo][purity][sample]->SetMarkerSize(0.8); 
        tree[sample]->Draw(Form("trkPtError/trkPt>>pterr%d%d%d",algo,purity,sample),Form("(1+(vtxw-1)*(%d&&%d))*(1+(hiBinw-1)*(%d))*(((highPurity== 1)||(highPurity==%d))  && (trkEta>-2.4 && trkEta<2.4) && (%d==5 || %d==trkAlgo) && ((%s) || (!%d))&& ((trkEta>0.8 || trkEta<-0.8) || (!%d))&& ((hiBin>=100 && hiBin<200) || (!%d)))",sample,doVtx,sample,purity,algo,algos[algo],ptCut,doPtCut,doEtaCut,doCentCut),"",nEvt);
        pterr[algo][purity][sample]->Scale(1.0/pterr[algo][purity][sample]->Integral(1,50));
        pterr[algo][purity][sample]->GetYaxis()->SetRangeUser(0.0,0.15);
        std::cout << algo << std::endl;  
        
        mva[algo][purity][sample] = new TH1D(Form("mva%d%d%d",algo,purity,sample),";mva;dN/d(mva)",doFineMVABins?100:30,-1,1);
        mva[algo][purity][sample]->SetMarkerSize(0.8); 
        tree[sample]->Draw(Form("trkMVA>>mva%d%d%d",algo,purity,sample),Form("(1+0.2*(!(%d) && %d && trkFake))*(1+(vtxw-1)*(%d&&%d))*(1+(hiBinw-1)*(%d))*(((highPurity== 1)||(highPurity==%d))  && (trkEta>-2.4 && trkEta<2.4) && (%d==5 || %d==trkAlgo) && ((%s) || (!%d))&& ((trkEta>0.8 || trkEta<-0.8) || (!%d))&& ((hiBin>=100 && hiBin<200) || (!%d)))",sample,doFake,sample,doVtx,sample,purity,algo,algos[algo],ptCut,doPtCut,doEtaCut,doCentCut),"",nEvt);
        nTracks[algo][purity][sample]=mva[algo][purity][sample]->Integral(1,doFineMVABins?100:30);
        mva[algo][purity][sample]->Scale(1.0/mva[algo][purity][sample]->Integral(1,doFineMVABins?100:30));
        mva[algo][purity][sample]->GetYaxis()->SetRangeUser(0.0,0.4);
        std::cout << algo << std::endl;  

        if(sample==1)
        {
          mvaRat[algo][purity][0] = (TH1D*)mva[algo][purity][1]->Clone(Form("mvaRat%d%d0",algo,purity));
          mvaRat[algo][purity][0]->GetYaxis()->SetTitle("offline/online");
          mvaRat[algo][purity][0]->Divide(mva[algo][purity][0]);
          mvaRat[algo][purity][0]->GetYaxis()->SetRangeUser(0,2);
          std::cout << algo << std::endl;  
        }
      }
    }
  }

  TCanvas * c1[2];
  TLegend * l1[2];
  for(int j = 0; j<2; j++)
  {
    c1[j] = new TCanvas(Form("c1_%d",j),Form("c1_%d",j),1800,1000);
    c1[j]->Divide(3,2);
    for(int i = 0; i<6; i++)
    {
      if(i==4 && isMB) continue;
      c1[j]->cd(i+1);
      chi2[i][j][0]->Draw("p");

      chi2[i][j][1]->SetMarkerColor(kRed+1);
      chi2[i][j][1]->SetLineColor(kRed+1);
      chi2[i][j][1]->Draw("p same");

      if(i==0)
      {
        l1[j] = new TLegend(0.6,0.5,0.9,0.9);
        l1[j]->AddEntry(chi2[0][j][0],"Online");
        l1[j]->AddEntry(chi2[0][j][1],"Offline");
        if(j==1) l1[j]->AddEntry((TObject*)0,"HighPurity","");
        l1[j]->Draw("same");
      }
      if(i<5) lat->DrawLatex(0.5,0.04,Form("Algo %d%s",algos[i],algName[i]));
      if(i==5) lat->DrawLatex(0.5,0.04,"All Algos");
    } 
    c1[j]->SaveAs(Form("validationPlots/chi2_%d.png",j));
  }
  
  TCanvas * c2[2];
  TLegend * l2[2];
  for(int j = 0; j<2; j++)
  {
    c2[j] = new TCanvas(Form("c2_%d",j),Form("c2_%d",j),1800,1000);
    c2[j]->Divide(3,2);
    for(int i = 0; i<6; i++)
    {
      if(i==4 && isMB) continue;
      c2[j]->cd(i+1);
      c2[j]->cd(i+1)->SetLogy();
      dxy[i][j][0]->Draw("p");

      dxy[i][j][1]->SetMarkerColor(kRed+1);
      dxy[i][j][1]->SetLineColor(kRed+1);
      dxy[i][j][1]->Draw("p same");

      if(i==0)
      {
        l2[j] = new TLegend(0.6,0.5,0.9,0.9);
        l2[j]->AddEntry(dxy[0][j][0],"Online");
        l2[j]->AddEntry(dxy[0][j][1],"Offline");
        if(j==1) l2[j]->AddEntry((TObject*)0,"HighPurity","");
        l2[j]->Draw("same");
      }
      if(i<5) lat->DrawLatex(-80,0.1,Form("Algo %d%s",algos[i],algName[i]));
      if(i==5) lat->DrawLatex(-80,0.1,"All Algos");
    }
    c2[j]->SaveAs(Form("validationPlots/dxy_%d.png",j));
  }
  
  TCanvas * c3[2];
  TLegend * l3[2];
  for(int j = 0; j<2; j++)
  {
    c3[j] = new TCanvas(Form("c3_%d",j),Form("c3_%d",j),1800,1000);
    c3[j]->Divide(3,2);
    for(int i = 0; i<6; i++)
    {
      if(i==4 && isMB) continue;
      c3[j]->cd(i+1);
      c3[j]->cd(i+1)->SetLogy();
      dz[i][j][0]->Draw("p");

      dz[i][j][1]->SetMarkerColor(kRed+1);
      dz[i][j][1]->SetLineColor(kRed+1);
      dz[i][j][1]->Draw("p same");

      if(i==0)
      {
        l3[j] = new TLegend(0.6,0.5,0.9,0.9);
        l3[j]->AddEntry(dz[0][j][0],"Online");
        l3[j]->AddEntry(dz[0][j][1],"Offline");
        if(j==1) l3[j]->AddEntry((TObject*)0,"HighPurity","");
        l3[j]->Draw("same");
      }
      if(i<5) lat->DrawLatex(-80,0.1,Form("Algo %d%s",algos[i],algName[i]));
      if(i==5) lat->DrawLatex(-80,0.1,"All Algos");
    }
    c3[j]->SaveAs(Form("validationPlots/dz_%d.png",j));
  }
  
  TCanvas * c4[2];
  TLegend * l4[2];
  for(int j = 0; j<2; j++)
  {
    c4[j] = new TCanvas(Form("c4_%d",j),Form("c4_%d",j),1800,1000);
    c4[j]->Divide(3,2);
    for(int i = 0; i<6; i++)
    {
      if(i==4 && isMB) continue;
      c4[j]->cd(i+1);
      nhit[i][j][0]->Draw("p");

      nhit[i][j][1]->SetMarkerColor(kRed+1);
      nhit[i][j][1]->SetLineColor(kRed+1);
      nhit[i][j][1]->Draw("p same");

      if(i==0)
      {
        l4[j] = new TLegend(0.6,0.5,0.9,0.9);
        l4[j]->AddEntry(nhit[0][j][0],"Online");
        l4[j]->AddEntry(nhit[0][j][1],"Offline");
        if(j==1) l4[j]->AddEntry((TObject*)0,"HighPurity","");
        l4[j]->Draw("same");
      }
      if(i<5) lat->DrawLatex(5,0.15,Form("Algo %d%s",algos[i],algName[i]));
      if(i==5) lat->DrawLatex(5,0.15,"All Algos");
    }
    c4[j]->SaveAs(Form("validationPlots/nhit_%d.png",j));
  }
  
  TCanvas * c5[2];
  TLegend * l5[2];
  for(int j = 0; j<2; j++)
  {
    c5[j] = new TCanvas(Form("c5_%d",j),Form("c5_%d",j),1800,1000);
    c5[j]->Divide(3,2);
    for(int i = 0; i<6; i++)
    {
      if(i==4 && isMB) continue; 
      c5[j]->cd(i+1);
      nlayer[i][j][0]->Draw("p");

      nlayer[i][j][1]->SetMarkerColor(kRed+1);
      nlayer[i][j][1]->SetLineColor(kRed+1);
      nlayer[i][j][1]->Draw("p same");

      if(i==0)
      {
        l5[j] = new TLegend(0.6,0.5,0.9,0.9);
        l5[j]->AddEntry(nlayer[0][j][0],"Online");
        l5[j]->AddEntry(nlayer[0][j][1],"Offline");
        if(j==1) l5[j]->AddEntry((TObject*)0,"HighPurity","");
        l5[j]->Draw("same");
      }
      if(i<5) lat->DrawLatex(5,0.2,Form("Algo %d%s",algos[i],algName[i]));
      if(i==5) lat->DrawLatex(5,0.2,"All Algos");
    }
    c5[j]->SaveAs(Form("validationPlots/nlayer_%d.png",j));
  }
  
  TCanvas * c6[2];
  TLegend * l6[2];
  for(int j = 0; j<2; j++)
  {
    c6[j] = new TCanvas(Form("c6_%d",j),Form("c6_%d",j),1800,1000);
    c6[j]->Divide(3,2);
    for(int i = 0; i<6; i++)
    {
      if(i==4 && isMB) continue; 
      c6[j]->cd(i+1);
      eta[i][j][0]->Draw("p");

      eta[i][j][1]->SetMarkerColor(kRed+1);
      eta[i][j][1]->SetLineColor(kRed+1);
      eta[i][j][1]->Draw("p same");

      if(i==0)
      {
        l6[j] = new TLegend(0.5,0.2,0.9,0.5);
        l6[j]->AddEntry(eta[0][j][0],"Online");
        l6[j]->AddEntry(eta[0][j][1],"Offline");
        if(j==1) l6[j]->AddEntry((TObject*)0,"HighPurity","");
        l6[j]->Draw("same");
      }
      if(i<5) lat->DrawLatex(-1.5,0.005,Form("Algo %d%s",algos[i],algName[i]));
      if(i==5) lat->DrawLatex(-1.5,0.005,"All Algos");
    }
    c6[j]->SaveAs(Form("validationPlots/eta_%d.png",j));
  }
  
  TCanvas * c7[2];
  TLegend * l7[2];
  for(int j = 0; j<2; j++)
  {
    c7[j] = new TCanvas(Form("c7_%d",j),Form("c7_%d",j),1800,1000);
    c7[j]->Divide(3,2);
    for(int i = 0; i<6; i++)
    {
      if(i==4 && isMB) continue;
      c7[j]->cd(i+1);
      pterr[i][j][0]->Draw("p");

      pterr[i][j][1]->SetMarkerColor(kRed+1);
      pterr[i][j][1]->SetLineColor(kRed+1);
      pterr[i][j][1]->Draw("p same");

      if(i==0)
      {
        l7[j] = new TLegend(0.6,0.5,0.9,0.9);
        l7[j]->AddEntry(pterr[0][j][0],"Online");
        l7[j]->AddEntry(pterr[0][j][1],"Offline");
        if(j==1) l7[j]->AddEntry((TObject*)0,"HighPurity","");
        l7[j]->Draw("same");
      }
      if(i<5) lat->DrawLatex(0.03,0.04,Form("Algo %d%s",algos[i],algName[i]));
      if(i==5) lat->DrawLatex(0.03,0.04,"All Algos");
    }
    c7[j]->SaveAs(Form("validationPlots/pterr_%d.png",j));
  }
 
  TCanvas * c8[2];
  TLegend * l8[2];
  for(int j = 0; j<2; j++)
  {
    c8[j] = new TCanvas(Form("c8_%d",j),Form("c8_%d",j),1800,1000);
    c8[j]->Divide(3,2);
    for(int i = 0; i<6; i++)
    {
      if(i==4 && isMB) continue;
      c8[j]->cd(i+1);
      mva[i][j][0]->Draw("p");

      mva[i][j][1]->SetMarkerColor(kRed+1);
      mva[i][j][1]->SetLineColor(kRed+1);
      mva[i][j][1]->Draw("p same");

      if(i==0)
      {
        l8[j] = new TLegend(0.6,0.5,0.9,0.9);
        l8[j]->AddEntry(mva[0][j][0],"Online");
        l8[j]->AddEntry(mva[0][j][1],"Offline");
        if(j==1) l8[j]->AddEntry((TObject*)0,"HighPurity","");
        l8[j]->Draw("same");
      }
      if(i<5) lat->DrawLatex(0.03,0.04,Form("Algo %d%s",algos[i],algName[i]));
      if(i==5) lat->DrawLatex(0.03,0.04,"All Algos");
    }
    c8[j]->SaveAs(Form("validationPlots/mva_%d.png",j));
  }
  
  TCanvas * c9[2];
  TLegend * l9[2];
  for(int j = 0; j<2; j++)
  {
    c9[j] = new TCanvas(Form("c9_%d",j),Form("c9_%d",j),1800,1000);
    c9[j]->Divide(3,2);
    for(int i = 0; i<6; i++)
    {
      if(i==4) continue;// && isMB) continue;
      c9[j]->cd(i+1);
      mvaRat[i][j][0]->Draw("p");

    //  mvaRat[i][j][1]->SetMarkerColor(kRed+1);
    //  mvaRat[i][j][1]->SetLineColor(kRed+1);
    //  mvaRat[i][j][1]->Draw("p same");

      if(i==0)
      {
        l9[j] = new TLegend(0.6,0.5,0.9,0.9);
      //  l9[j]->AddEntry(mvaRat[0][j][0],"Online");
      //  l9[j]->AddEntry(mvaRat[0][j][1],"Offline");
        if(j==1) l9[j]->AddEntry((TObject*)0,"HighPurity","");
        l9[j]->Draw("same");
      }
      if(i<5) lat->DrawLatex(0.03,0.4,Form("Algo %d%s",algos[i],algName[i]));
      if(i==5) lat->DrawLatex(0.03,0.4,"All Algos");
    }
    c9[j]->SaveAs(Form("validationPlots/mvaRat_%d.png",j));
  }

  //change in signal by reweighting MVAs
  for(int i = 0; i<6; i++)
  {
    if(i==4) continue;
    float cut[6] = {-0.77,0.35,0.77,-0.09,0,0};
    float dSig = mva[i][0][1]->Integral(mva[i][0][1]->FindBin(cut[i]),mva[i][0][1]->FindBin(1)); 
    mva[i][0][1]->Divide(mvaRat[i][0][0]);
    float dSig2 = (float)mva[i][0][1]->Integral(mva[i][0][1]->FindBin(cut[i]),mva[i][0][1]->FindBin(1))/mva[i][0][1]->Integral(mva[i][0][1]->FindBin(-1),mva[i][0][1]->FindBin(1)); 
    std::cout << "\n\nAlgo " << algos[i] << "\nSignal Purity before MVA weight: " << dSig << "  Signal Purity after MVA weight: " << dSig2 << "  Difference (as %): " << dSig-dSig2 << " (" << (dSig-dSig2)*100/dSig<<")" << std::endl;
    std::cout << "Fraction of tracks w/o highPurity (data): " << (float)nTracks[i][0][1]/nTracks[5][0][1] << std::endl;
    std::cout << "Fraction of tracks w/o highPurity (MC): " << (float)nTracks[i][0][0]/nTracks[5][0][0] << std::endl;
    std::cout << "\nFraction of tracks w/  highPurity  (data): " << (float)nTracks[i][1][1]/nTracks[5][1][1] << std::endl;
    std::cout << "Fraction of tracks w/  highPurity (MC): " << (float)nTracks[i][1][0]/nTracks[5][1][0] << std::endl;
  }
}
コード例 #25
0
std::string generateCodeFromStreamers(std::string url, std::string treeLocation, std::vector<std::string> &classNames, std::string &errorMessage) {
  TFile *tfile = TFile::Open(url.c_str());
  if (tfile == nullptr  ||  !tfile->IsOpen()) {
    errorMessage = std::string("File not found: ") + url;
    return std::string();
  }

  if (tfile->IsZombie()) {
    errorMessage = std::string("Not a ROOT file: ") + url;
    return std::string();
  }

  TTreeReader reader(treeLocation.c_str(), tfile);
  if (reader.IsZombie()) {
    errorMessage = std::string("Not a TTree: ") + treeLocation.c_str() + std::string(" in file: ") + url;
    return std::string();
  }

  TTree *ttree = reader.GetTree();

  std::set<std::string> includes;
  std::vector<ClassStructure> classes;

  TIter listOfBranches = ttree->GetListOfBranches();
  for (TBranch *tbranch = (TBranch*)listOfBranches.Next();  tbranch != nullptr;  tbranch = (TBranch*)listOfBranches.Next()) {
    TClass *tclass = TClass::GetClass(tbranch->GetClassName());
    if (tclass != nullptr  &&  tbranch->GetListOfBranches()->GetEntries() > 0)
      classesFromBranch(tbranch, tclass, classes, 0, includes);
  }

  for (int i = 0;  i < classes.size();  i++)
    classNames.push_back(classes[i].fullName);

  tfile->Close();

  std::string out;

  for (std::set<std::string>::iterator iter = includes.begin();  iter != includes.end();  ++iter)
    out += *iter + "\n";
  out += "\n";
  
  for (std::vector<ClassStructure>::iterator iter = classes.begin();  iter != classes.end();  ++iter) {
    int i = 0;
    for (;  i < iter->splitName.size() - 1;  i++)
      out += std::string(i * 2, ' ') + "namespace " + iter->splitName[i] + " {\n";

    out += std::string(i * 2, ' ') + "class " + iter->splitName.back() + ";\n";
    i--;
    for (;  i >= 0;  i--)
      out += std::string(i * 2, ' ') + "}\n";
  }
  out += "\n";

  for (std::vector<ClassStructure>::iterator iter = classes.begin();  iter != classes.end();  ++iter) {
    int i = 0;
    for (;  i < iter->splitName.size() - 1;  i++)
      out += std::string(i * 2, ' ') + "namespace " + iter->splitName[i] + " {\n";
    out += iter->cpp(i * 2) + "\n";
    i--;
    for (;  i >= 0;  i--)
      out += std::string(i * 2, ' ') + "}\n";
  }

  for (std::vector<ClassStructure>::iterator iter = classes.begin();  iter != classes.end();  ++iter) {
    int i = 0;
    for (;  i < iter->splitName.size() - 1;  i++)
      out += std::string(i * 2, ' ') + "namespace " + iter->splitName[i] + " {\n";
    out += std::string(i * 2, ' ') + "ClassImp(" + iter->splitName.back() + ")\n";
    i--;
    for (;  i >= 0;  i--)
      out += std::string(i * 2, ' ') + "}\n";
  }
  
  return out;
}
コード例 #26
0
void analyze_3inch_data(int nnnn){


  {


    TFile *f = new TFile("waveforms_r12199_1250V_dt720_shaper.root");

    TTree *waveforms = (TTree*)f->Get("waveformTree");

    if(waveforms)
      std::cout << "N entries: " << waveforms->GetEntries() << std::endl;
    TCanvas *c3 = new TCanvas("C3");
 
    TGraph *gr1 = new TGraph();
    waveforms->SetBranchAddress("g_ch1",&gr1);

    TGraph *gr2 = new TGraph();
    waveforms->SetBranchAddress("g_ch2",&gr2);


    TH1F *tdiff = new TH1F("diff","diff",200,0,100);

    if(nnnn == 0)
      nnnn = waveforms->GetEntries();
    
    for(int i = 1; i < nnnn; i++){

      waveforms->GetEntry(i);

      
      // Loop over channels
      double times[2] = {-9999,-9999};
      for(int ch = 0; ch < 2; ch++){

        TGraph *gr;
        if(ch == 0) gr = gr1;
        else gr = gr2;
        
        // Find the minimum bin
        double min = 999999, min_bin = -1;
        findMin(gr,min,min_bin);
      
        
      
        if(ch == 0){
          //gr->Draw("AP*");
          // Currently only has range set up for EMG, but EMG works well
          TF1 *fitted_ref = new TF1("EMG",funcEMG,min_bin-73,min_bin+121,5);
          fitted_ref->SetParameter(0,-0.5);
          fitted_ref->SetParameter(1,min_bin);
          fitted_ref->FixParameter(2,26);
          fitted_ref->FixParameter(3,33);
          fitted_ref->SetParameter(4,2112);
          //Exponential gaussian used for fitting
          // p[0]: amplitude
          // p[1]: gaussian mu
          // p[2]: gaussian sig
          // p[3]: exponential decay constant  -  ???
          // p[4]: baseline    
          gr->Fit("EMG","Q","",min_bin-73,min_bin+121);
          
          times[ch] =  fitted_ref->GetParameter(1);
          fitted_ref->Draw("SAME");
          //sleep(5);
          //char c;
          //cin << c;
          delete fitted_ref;
        }else{

          if(min <= 3918){ 
 
            gr->Draw("AP*");
            std::cout << "Fitting ch2" << std::endl;
            // Currently only has range set up for EMG, but EMG works well
            std::cout << "minbin " << min_bin << std::endl;
            TF1 *fitted_ref = new TF1("EMG",funcEMG,min_bin-26,min_bin+41,5);
            fitted_ref->SetParameter(0,-0.7);
            fitted_ref->SetParameter(1,min_bin);
            fitted_ref->SetParameter(2,8);
            fitted_ref->SetParameter(3,11);
            fitted_ref->SetParameter(4,3921.5);
            //Exponential gaussian used for fitting
            // p[0]: amplitude
            // p[1]: gaussian mu
            // p[2]: gaussian sig
            // p[3]: exponential decay constant  -  ???
            // p[4]: baseline    
            gr->Fit("EMG","","",min_bin-26,min_bin+41);
            
            //            std::cout << fitted_ref->GetParameter(1) << std::endl;
            fitted_ref->Draw("SAME");
            times[ch] =  fitted_ref->GetParameter(1);
            //sleep(5);
            //char c;
            //cin << c;
            delete fitted_ref;
          }
        }
      }

      double diff = times[1] - times[0];
      std::cout << "diff " << diff << std::endl;
      if(times[1] > 0)
        tdiff->Fill(diff);
      

    }


    TCanvas *c = new TCanvas("C2");
    tdiff->Draw();
  }


}
コード例 #27
0
ファイル: babylooper.C プロジェクト: hooberman/UserCode
void babylooper::ScanChain (TChain* chain, const char* version, const char* prefix, bool isData){

  char* outversion = (char*) "V00-00-09";
  bool doSigCont   = true;

  TObjArray *listOfFiles = chain->GetListOfFiles();
  unsigned int nEventsTotal = 0;

  //---------------------------------------
  // declare histograms
  //---------------------------------------

  const int   nm0points    = 100;
  const float m0min        = 20.;
  const float m0max        = 2020.;
  const int   nm12points   = 38;
  const float m12min       = 20.;
  const float m12max       = 780.;

  const unsigned int nbins = 6;

  float KKC[nbins] = { 2.74 , 2.74 , 2.59 , 2.59 , 1.81 , 1.81 };

  TH2F* h[nbins];
  TH2F* hptll[nbins];
  TH2F* hjup[nbins];
  TH2F* hjdn[nbins];
  //TH2F* hptlljup[nbins];
  //TH2F* hptlljdn[nbins];
  TH2F* hkup[nbins];
  TH2F* hkdn[nbins];

  for( unsigned int i = 0 ; i < nbins ; ++i ){
    h[i]        = new TH2F( Form("h_%i",i)        , Form("h_%i",i)           , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hjup[i]     = new TH2F( Form("hjup_%i",i)     , Form("hjup_%i",i)        , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hjdn[i]     = new TH2F( Form("hjdn_%i",i)     , Form("hjdn_%i",i)        , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hkup[i]     = new TH2F( Form("hkup_%i",i)     , Form("hkup_%i",i)        , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hkdn[i]     = new TH2F( Form("hkdn_%i",i)     , Form("hkdn_%i",i)        , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    hptll[i]    = new TH2F( Form("hptll_%i",i)    , Form("hptll_%i",i)       , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    //hptlljup[i] = new TH2F( Form("hptlljup_%i",i) , Form("hptlljup_%i",i)    , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
    //hptlljdn[i] = new TH2F( Form("hptlljdn_%i",i) , Form("hptlljdn_%i",i)    , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);

    h[i]    ->Sumw2();
    hjup[i] ->Sumw2();
    hjdn[i] ->Sumw2();
    hkup[i] ->Sumw2();
    hkdn[i] ->Sumw2();

    hptll[i]->Sumw2();
    //hptlljup[i]->Sumw2();
    //hptlljdn[i]->Sumw2();
  }

  TH2F* hall    = new TH2F( "hall"    , "hall"    , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
  TH2F* hkupall = new TH2F( "hkupall" , "hkupall" , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
  TH2F* hjdnall = new TH2F( "hjdnall" , "hjdnall" , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
  TH2F* hkdnall = new TH2F( "hkdnall" , "hkdnall" , nm0points,m0min-10,m0max-10,nm12points,m12min-10,m12max-10);
  
  hall->Sumw2();
  hkupall->Sumw2();
  hkdnall->Sumw2();


  // file loop
  TIter fileIter(listOfFiles);
  TFile* currentFile = 0;
  while ((currentFile = (TFile*)fileIter.Next())){
    
    TFile f(currentFile->GetTitle());
    TTree *tree = (TTree*)f.Get("t");

    setBranches(tree);

    // event loop
    unsigned int nEvents = tree->GetEntries();
 
    for (unsigned int event = 0 ; event < nEvents; ++event){
        
      tree->GetEntry(event);
      ++nEventsTotal;

      // progress feedback to user
      if (nEventsTotal % 1000 == 0){
            
        // xterm magic from L. Vacavant and A. Cerri
        if (isatty(1)){
                
          printf("\015\033[32m ---> \033[1m\033[31m%4.1f%%"
                 "\033[0m\033[32m <---\033[0m\015", (float)nEventsTotal/(nEvents*0.01));
          fflush(stdout);
        }
      }
      
      float weight      = weight_ * 4.7 * ndavtxweight_ * trgeff_ * lepscale_;

      bool presel	= pfmet_>50 && njets_>=2 && ht_>100 && passz_==0;
      bool preselptll	= pfmet_>50 && njets_>=2 && ht_>100 && passz_==0 && ( (leptype_==2) || (leptype_<2 && pfmet_>75) );
      bool preseljup	= pfmetUp_>50   && njetsUp_>=2   && htUp_>100   && passz_==0;
      bool preseljdn	= pfmetDown_>50 && njetsDown_>=2 && htDown_>100 && passz_==0;
      bool SF		= leptype_==0 || leptype_==1;
      bool OF		= leptype_==2;

      bool sig		= (ht_>300 && pfmet_>275) || (ht_>600 && pfmet_>200);  
      bool sigdn	= (htDown_>300 && pfmetDown_>275) || (htDown_>600 && pfmetDown_>200);

      bool SR1		= ht_>300 && ht_<600 && pfmet_>275;
      bool SR2		= ht_>600 && pfmet_>275;
      bool SR3		= ht_>600 && pfmet_>200 && pfmet_<275;

      bool SR1ptll	= ht_>300 && ht_<600 && dilpt_>275;
      bool SR2ptll	= ht_>600 && dilpt_>275;
      bool SR3ptll	= ht_>600 && dilpt_>200 && dilpt_<275;

      bool SR1jup	= htUp_>300 && htUp_<600 && pfmetUp_>275;
      bool SR2jup	= htUp_>600 && pfmetUp_>275;
      bool SR3jup	= htUp_>600 && pfmetUp_>200 && pfmetUp_<275;

      // bool SR1ptlljup	= htUp_>300 && htUp_<600 && dilpt_>275;
      // bool SR2ptlljup	= htUp_>600 && dilpt_>275;
      // bool SR3ptlljup	= htUp_>600 && dilpt_>200 && dilpt_<275;

      bool SR1jdn	= htDown_>300 && htDown_<600 && pfmetDown_>275;
      bool SR2jdn	= htDown_>600 && pfmetDown_>275;
      bool SR3jdn	= htDown_>600 && pfmetDown_>200 && pfmetDown_<275;

      // bool SR1ptlljdn	= htDown_>300 && htDown_<600 && dilpt_>275;
      // bool SR2ptlljdn	= htDown_>600 && dilpt_>275;
      // bool SR3ptlljdn	= htDown_>600 && dilpt_>200 && dilpt_<275;

      //----------------------------
      // nominal
      //----------------------------

      if( presel ){
	if( SR1 && SF ) h[0]->Fill( m0_ , m12_ , weight );
	if( SR1 && OF ) h[1]->Fill( m0_ , m12_ , weight );
	if( SR2 && SF ) h[2]->Fill( m0_ , m12_ , weight );
	if( SR2 && OF ) h[3]->Fill( m0_ , m12_ , weight );
	if( SR3 && SF ) h[4]->Fill( m0_ , m12_ , weight );
	if( SR3 && OF ) h[5]->Fill( m0_ , m12_ , weight );
	if( sig       ) hall->Fill( m0_ , m12_ , weight );
      }

      // ch->Draw("m12:m0>>h_0"        , (presel + SR1 + SF) * weight );
      // ch->Draw("m12:m0>>h_1"        , (presel + SR1 + OF) * weight );
      // ch->Draw("m12:m0>>h_2"        , (presel + SR2 + SF) * weight );
      // ch->Draw("m12:m0>>h_3"        , (presel + SR2 + OF) * weight );
      // ch->Draw("m12:m0>>h_4"        , (presel + SR3 + SF) * weight );
      // ch->Draw("m12:m0>>h_5"        , (presel + SR3 + OF) * weight );
      // ch->Draw("m12:m0>>hall"       , (presel + sig     ) * weight );

      //----------------------------
      // ptll control region
      //----------------------------

      if( preselptll ){
	if( SR1ptll && SF ) hptll[0]->Fill( m0_ , m12_ , weight );
	if( SR1ptll && OF ) hptll[1]->Fill( m0_ , m12_ , weight );
	if( SR2ptll && SF ) hptll[2]->Fill( m0_ , m12_ , weight );
	if( SR2ptll && OF ) hptll[3]->Fill( m0_ , m12_ , weight );
	if( SR3ptll && SF ) hptll[4]->Fill( m0_ , m12_ , weight );
	if( SR3ptll && OF ) hptll[5]->Fill( m0_ , m12_ , weight );
      }

      // ch->Draw("m12:m0>>hptll_0"    , (preselptll + SR1ptll) * weight );
      // ch->Draw("m12:m0>>hptll_1"    , (preselptll + SR1ptll) * weight );
      // ch->Draw("m12:m0>>hptll_2"    , (preselptll + SR2ptll) * weight );
      // ch->Draw("m12:m0>>hptll_3"    , (preselptll + SR2ptll) * weight );
      // ch->Draw("m12:m0>>hptll_4"    , (preselptll + SR3ptll) * weight );
      // ch->Draw("m12:m0>>hptll_5"    , (preselptll + SR3ptll) * weight );

      //----------------------------
      // JES up
      //----------------------------

      if( preseljup ){
	if( SR1jup && SF ) hjup[0]->Fill( m0_ , m12_ , weight );
	if( SR1jup && OF ) hjup[1]->Fill( m0_ , m12_ , weight );
	if( SR2jup && SF ) hjup[2]->Fill( m0_ , m12_ , weight );
	if( SR2jup && OF ) hjup[3]->Fill( m0_ , m12_ , weight );
	if( SR3jup && SF ) hjup[4]->Fill( m0_ , m12_ , weight );
	if( SR3jup && OF ) hjup[5]->Fill( m0_ , m12_ , weight );
      }

      //cout << "Filling JES up histos" << endl;
      // ch->Draw("m12:m0>>hjup_0"     , (preseljup + SR1jup + SF) * weight );
      // ch->Draw("m12:m0>>hjup_1"     , (preseljup + SR1jup + OF) * weight );
      // ch->Draw("m12:m0>>hjup_2"     , (preseljup + SR2jup + SF) * weight );
      // ch->Draw("m12:m0>>hjup_3"     , (preseljup + SR2jup + OF) * weight );
      // ch->Draw("m12:m0>>hjup_4"     , (preseljup + SR3jup + SF) * weight );
      // ch->Draw("m12:m0>>hjup_5"     , (preseljup + SR3jup + OF) * weight );

      //----------------------------
      // JES down
      //----------------------------

      if( preseljdn ){
	if( SR1jdn && SF ) hjdn[0]->Fill( m0_ , m12_ , weight );
	if( SR1jdn && OF ) hjdn[1]->Fill( m0_ , m12_ , weight );
	if( SR2jdn && SF ) hjdn[2]->Fill( m0_ , m12_ , weight );
	if( SR2jdn && OF ) hjdn[3]->Fill( m0_ , m12_ , weight );
	if( SR3jdn && SF ) hjdn[4]->Fill( m0_ , m12_ , weight );
	if( SR3jdn && OF ) hjdn[5]->Fill( m0_ , m12_ , weight );
	if( sigdn        ) hjdnall->Fill( m0_ , m12_ , weight );
      }
  
      //JES down
      // cout << "Filling JES dn histos" << endl;
      // ch->Draw("m12:m0>>hjdn_0"     , (preseljdn + SR1jdn + SF) * weight );
      // ch->Draw("m12:m0>>hjdn_1"     , (preseljdn + SR1jdn + OF) * weight );
      // ch->Draw("m12:m0>>hjdn_2"     , (preseljdn + SR2jdn + SF) * weight );
      // ch->Draw("m12:m0>>hjdn_3"     , (preseljdn + SR2jdn + OF) * weight );
      // ch->Draw("m12:m0>>hjdn_4"     , (preseljdn + SR3jdn + SF) * weight );
      // ch->Draw("m12:m0>>hjdn_5"     , (preseljdn + SR3jdn + OF) * weight );
      // ch->Draw("m12:m0>>hjdnall"    , (preseljdn + sigdn      ) * weight );

      
    }// end loop over events
  } // end loop over files
  

  ofstream* doScript = new ofstream();
  doScript->open(Form("cards/%s/doLimits.sh",outversion));

  ofstream* doScript_CLs = new ofstream();
  doScript_CLs->open(Form("cards/%s/doLimits_CLs.sh",outversion));

  ofstream* doScript_CLs1 = new ofstream();
  doScript_CLs1->open(Form("cards/%s/doLimits_CLs1.sh",outversion));

  ofstream* doScript_CLs2 = new ofstream();
  doScript_CLs2->open(Form("cards/%s/doLimits_CLs2.sh",outversion));

  ofstream* doScript_CLs3 = new ofstream();
  doScript_CLs3->open(Form("cards/%s/doLimits_CLs3.sh",outversion));

  ofstream* doScript_CLs4 = new ofstream();
  doScript_CLs4->open(Form("cards/%s/doLimits_CLs4.sh",outversion));

  ofstream* filelist = new ofstream();
  filelist->open(Form("cards/%s/file_list.txt",outversion));

  ofstream* filelist_CLs = new ofstream();
  filelist_CLs->open(Form("cards/%s/file_list_CLs.txt",outversion));


  //------------------------------------------
  // loop over CMSSM points
  //------------------------------------------

  int counter = 0;

  for( int m0bin = 1 ; m0bin <= hall->GetXaxis()->GetNbins() ; m0bin++ ){
    for( int m12bin = 1 ; m12bin <= hall->GetYaxis()->GetNbins() ; m12bin++ ){

      //------------------------------------------
      // require nentries = 10
      //------------------------------------------
      
      //int ngen = hscan->GetBinContent(m0bin,m12bin);
      //if( ngen != 10000 )  continue;
      
      //int m0  = hall->GetXaxis()->GetBinCenter(m0bin);
      //int m12 = hall->GetXaxis()->GetBinCenter(m12bin);

      //if( m0 > 1000 )                                  continue;
      if( hjdnall->GetBinContent(m0bin,m12bin) < 1e-10 ) continue;


      float nom = hall->GetBinContent(m0bin,m12bin);
      float kdn = hkupall->GetBinContent(m0bin,m12bin);
      float kup = hkdnall->GetBinContent(m0bin,m12bin);
	     
      float dup = kup / nom - 1;
      float ddn = 1 - kdn / nom;
      float kerr = 0.5 * ( dup + ddn );

      //---------------------------------------
      // make root file
      //---------------------------------------

      TH1F* histo_CMSSM               = new TH1F( Form("histo_CMSSM_%i_%i"              ,m0bin,m12bin) , Form("histo_CMSSM_%i_%i"              ,m0bin,m12bin) , nbins,0,nbins);
      TH1F* histo_CMSSM_JES_shapeUp   = new TH1F( Form("histo_CMSSM_%i_%i_JES_shapeUp"  ,m0bin,m12bin) , Form("histo_CMSSM_%i_%i_JES_shapeUp"  ,m0bin,m12bin) , nbins,0,nbins);
      TH1F* histo_CMSSM_JES_shapeDown = new TH1F( Form("histo_CMSSM_%i_%i_JES_shapeDown",m0bin,m12bin) , Form("histo_CMSSM_%i_%i_JES_shapeDown",m0bin,m12bin) , nbins,0,nbins);

      float sigtot    = 0;
      float sigtotjdn = 0;

      for( unsigned int ibin = 0 ; ibin < nbins ; ibin++ ){
	float yieldnom = h[ibin]->GetBinContent(m0bin,m12bin);
	float yieldjup = hjup[ibin]->GetBinContent(m0bin,m12bin);
	float yieldjdn = hjdn[ibin]->GetBinContent(m0bin,m12bin);

	if( doSigCont ){
	  float ptll = hptll[ibin]->GetBinContent(m0bin,m12bin) * 0.5 * KKC[ibin];

	  if( ptll < yieldnom ){
	    float scale = (yieldnom-ptll)/yieldnom;
	    yieldnom -= ptll;
	    yieldjup *= scale;
	    yieldjdn *= scale;
	  }
	  
	  else{
	    yieldnom = 0.0;
	    yieldjup = 0.0;
	    yieldjdn = 0.0;
	  }

	}

	sigtot    += yieldnom;
	sigtotjdn += yieldjdn;

	histo_CMSSM->SetBinContent              ( ibin + 1 , yieldnom );
	histo_CMSSM_JES_shapeUp->SetBinContent  ( ibin + 1 , yieldjup );
	histo_CMSSM_JES_shapeDown->SetBinContent( ibin + 1 , yieldjdn );
      }

      if( sigtotjdn < 1e-10 ) continue;
      if( sigtot    < 2     ) continue;
      if( sigtot    > 80    ) continue;

      //float sigtot = hall->GetBinContent(m0bin,m12bin);

      counter++;

      char* fitoptions = "-M Hybrid --freq  --nToysForCLsb 1500 --nToysForCLb 500  --scanRs 1 -vR [0.2,5,x1.1]";
      //char* fitoptions = "-M Hybrid --freq --ExpectationHints Asymptotic --scanRs 1 --freq --nToysForCLsb 3000 --nToysForCLb 1500 --seed 1234 -rMin 0 -rMax 5";

      *doScript << Form("../../../../test/lands.exe -M Bayesian -d CMSSM_%i_%i.txt",m0bin,m12bin)         << endl;

      *doScript_CLs << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

       if( counter%4 == 0 ) *doScript_CLs1 << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

       if( counter%4 == 1 ) *doScript_CLs2 << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

       if( counter%4 == 2 ) *doScript_CLs3 << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

       if( counter%4 == 3 ) *doScript_CLs4 << Form("../../../../test/lands.exe -d CMSSM_%i_%i.txt %s  -n CMSSM_%i_%i",m0bin,m12bin,fitoptions,m0bin,m12bin) << endl;

      *filelist << Form("cards/%s/CMSSM_%i_%i.txt_Bayesian_bysObsLimit.root",outversion,m0bin,m12bin)        << endl;

      *filelist_CLs << Form("cards/%s/CMSSM_%i_%i_m2lnQ2.root",outversion,m0bin,m12bin)        << endl;

      printCard( Form("CMSSM_%i_%i",m0bin,m12bin) , sigtot ,  outversion );
      
      //signal regions                         R1(SF)      R1(OF)    R2(SF)     R2(OF)      R3(SF)   R3(OF)
      int     data_yield[nbins]           = {    9     ,    10    ,    6     ,    5     ,     5    ,    13  };
      float   bkg_yield[nbins]            = {   5.7    ,    5.7   ,   5.2    ,   5.2    ,    5.6   ,   5.6  };
      float   bkg_syst[nbins]             = {   2.8    ,    2.8   ,   1.9    ,   1.9    ,    2.1   ,   2.1  };
      float   bkg_stat[nbins]             = {   5.1    ,    5.1   ,   4.1    ,   4.1    ,    3.4   ,   3.4  };

      TH1F* histo_Data = new TH1F("histo_Data","histo_Data",nbins,0,nbins);

      for( unsigned int ibin = 0 ; ibin < nbins ; ibin++){
	histo_Data->SetBinContent( ibin+1 , data_yield[ibin] );
      }

      TH1F* histo_bkg               = new TH1F("histo_bkg","histo_bkg",nbins,0,nbins);
      TH1F* histo_bkg_statUp        = new TH1F("histo_bkg_statUp"  ,"histo_bkg_statUp"  ,nbins,0,nbins);
      TH1F* histo_bkg_statDown      = new TH1F("histo_bkg_statDown","histo_bkg_statDown",nbins,0,nbins);
      TH1F* histo_bkg_systUp        = new TH1F("histo_bkg_systUp"  ,"histo_bkg_systUp"  ,nbins,0,nbins);
      TH1F* histo_bkg_systDown      = new TH1F("histo_bkg_systDown","histo_bkg_systDown",nbins,0,nbins);
      
      for( unsigned int ibin = 0 ; ibin < nbins ; ibin++){
	histo_bkg               -> SetBinContent(ibin+1,bkg_yield[ibin]);
	histo_bkg_statUp        -> SetBinContent(ibin+1, bkg_yield[ibin] + bkg_stat[ibin] );
	histo_bkg_statDown      -> SetBinContent(ibin+1, TMath::Max(bkg_yield[ibin] - bkg_stat[ibin],(float)0.0) );
	histo_bkg_systUp        -> SetBinContent(ibin+1, bkg_yield[ibin] + bkg_syst[ibin] );
	histo_bkg_systDown      -> SetBinContent(ibin+1, TMath::Max(bkg_yield[ibin] - bkg_syst[ibin],(float)0.0) );
      }


      TFile *f = TFile::Open( Form("rootfiles/%s/CMSSM_%i_%i.root",outversion,m0bin,m12bin) , "RECREATE");
      f->cd();
      histo_Data->Write();
      histo_bkg->Write();
      histo_bkg_statUp->Write();
      histo_bkg_statDown->Write();
      histo_bkg_systUp->Write();
      histo_bkg_systDown->Write();
      histo_CMSSM->Write();
      histo_CMSSM_JES_shapeUp->Write();
      histo_CMSSM_JES_shapeDown->Write();
      f->Close();

      delete histo_Data;
      delete histo_bkg;
      delete histo_bkg_statUp;
      delete histo_bkg_statDown;
      delete histo_bkg_systUp;
      delete histo_bkg_systDown;
      delete histo_CMSSM;
      delete histo_CMSSM_JES_shapeUp;
      delete histo_CMSSM_JES_shapeDown;
    }
  }

  cout << "Looped over " << nEventsTotal << " events" << endl;
  
  TFile* f = TFile::Open("histos.root","RECREATE");
  f->cd();
  for( unsigned int i = 0 ; i < nbins ; ++i ){
    h[i]        ->Write();
    hjup[i]     ->Write();
    hjdn[i]     ->Write();
    hkup[i]     ->Write();
    hkdn[i]     ->Write();
    hptll[i]    ->Write();
    //hptlljup[i] ->Write();
    //hptlljdn[i] ->Write();
  }
  f->Close();

} // end ScanChain
コード例 #28
0
ファイル: getXS.C プロジェクト: CmsHI/CVS_SavedFMa
void getXS(){

  bool inclusive = false;
  TFile* outf = new TFile("results.root","recreate");

  int j = 0;
    
    TH1::SetDefaultSumw2();
    TFile* inf = new TFile("dijets.root");

    outf->cd();    
    TH1D* h = new TH1D(Form("h%d",j),"",500,0,1000);
    TTree* t = (TTree*)inf->Get("jets/t");
    //    if(j< t->GetEntries()) t->SetEntries(j);
    
    if(inclusive) t->Draw(Form("jtpt>>h%d",j),"abs(jteta) < 5");
    else t->Draw(Form("jtpt[0]>>h%d",j),"abs(jteta[0]) < 5 && nref > 0");

    double Nev = t->GetEntries();
    double ncollProb = 1.;
    double A = 208;
    double AA = A*A*ncollProb;
    double bin = h->GetBinWidth(1); 
    
    double xs = 6.206E-02; // mb
    double intlum = 5000; // invmb
    double s = xs*intlum*AA/Nev/bin;

    double nChosen = 100;
    
    h->Scale(s);

    cout<<"h integral : "<<h->Integral("width")<<endl;

    float jtpt[1000],jteta[1000];
    int nref;
    t->SetBranchAddress("jtpt",jtpt);
    t->SetBranchAddress("jtpt",jteta);
    t->SetBranchAddress("nref",&nref);

    vector<float> vj;

    for(int i = 0; i < t->GetEntries(); ++i){
      t->GetEntry(i);
      if(inclusive){
	for(int it = 0; it < nref; ++it){
	  if(fabs(jteta[it]) < 5) vj.push_back(jtpt[it]);
	}
      }else{
	if(nref > 0 && fabs(jteta[0]) < 5) vj.push_back(jtpt[0]);
	else vj.push_back(0.);
      }
    }

    sort(vj.begin(),vj.end());

    int hund = vj.size() - xs*intlum*AA*nChosen*vj.size();
    if(hund > 0){
      cout<<"Entries = "<<j<<endl;
      cout<<"PT from vector : "<<vj[hund]<<endl;
    }

    double tot = 0;
    for(int i = h->GetNbinsX()+1; i >=0; --i){
      tot+= h->GetBinContent(i)*bin;
      if(tot > nChosen){
	cout<<"Entries = "<<j<<endl;   
	cout<<"PT : "<<h->GetBinLowEdge(i)<<endl;
	break;
      }
    }
    

  outf->Write();
  
}
コード例 #29
0
void TMVAClassificationApplication( TString myMethodList = "", TString filename="" ) 
{   
   //---------------------------------------------------------------
   // default MVA methods to be trained + tested

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

   std::map<std::string,int> Use;

   Use["CutsGA"]          = 1; // other "Cuts" methods work identically
   // ---
   Use["Likelihood"]      = 1;
   Use["LikelihoodD"]     = 1; // the "D" extension indicates decorrelated input variables (see option strings)
   Use["LikelihoodPCA"]   = 0; // the "PCA" extension indicates PCA-transformed input variables (see option strings)
   Use["LikelihoodKDE"]   = 0;
   Use["LikelihoodMIX"]   = 0;
   // ---
   Use["PDERS"]           = 1;
   Use["PDERSD"]          = 0;
   Use["PDERSPCA"]        = 0;
   Use["PDERSkNN"]        = 0; // depreciated until further notice
   Use["PDEFoam"]         = 1;
   // --
   Use["KNN"]             = 1;
   // ---
   Use["HMatrix"]         = 0;
   Use["Fisher"]          = 1;
   Use["FisherG"]         = 0;
   Use["BoostedFisher"]   = 0;
   Use["LD"]              = 1;
   // ---
   Use["FDA_GA"]          = 0;
   Use["FDA_SA"]          = 0;
   Use["FDA_MC"]          = 0;
   Use["FDA_MT"]          = 1;
   Use["FDA_GAMT"]        = 0;
   Use["FDA_MCMT"]        = 0;
   // ---
   Use["MLP"]             = 1; // this is the recommended ANN
   Use["MLPBFGS"]         = 0; // recommended ANN with optional training method
   Use["CFMlpANN"]        = 0; // *** missing
   Use["TMlpANN"]         = 0; 
   // ---
   Use["SVM"]             = 1;
   // ---
   Use["BDT"]             = 1;
   Use["BDTD"]            = 0;
   Use["BDTG"]            = 1;
   Use["BDTB"]            = 0;
   // ---
   Use["RuleFit"]         = 0;
   // ---
   Use["Plugin"]          = 0;
   // ---------------------------------------------------------------

   std::cout << std::endl;
   std::cout << "==> Start TMVAClassificationApplication" << 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 = gTools().SplitString( myMethodList, ',' );
      for (UInt_t i=0; i<mlist.size(); i++) {
         std::string regMethod(mlist[i]);

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

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

   // create a set of variables and declare them to the reader
   // - the variable names must corresponds in name and type to 
   // those given in the weight file(s) that you use

///Our variables here:
/************************************************************************************************************
*    Row   *      nEvt *     sumEt *       Et1 *    lepeta *       MET * dphiMETle * detajet2j * detajet3j *
************************************************************************************************************

mindijetmass
maxdijetmass

*/


   Float_t sumEt;
   Float_t Et1;
   Float_t lepeta;
   Float_t MET;
   Float_t dphiMETlepton;
    Float_t detajet2jet3;
    Float_t detajet3jet4;
    Float_t mindijetmass;
    Float_t maxdijetmass;
	


   reader->AddVariable( "sumEt", &sumEt );
   reader->AddVariable( "Et1", &Et1 );
   reader->AddVariable( "lepeta", &lepeta );
   reader->AddVariable( "MET", &MET );
   reader->AddVariable( "dphiMETlepton", &dphiMETlepton );
   reader->AddVariable( "detajet2jet3", &detajet2jet3 );
   reader->AddVariable( "detajet3jet4", &detajet3jet4 );
   reader->AddVariable( "mindijetmass", &mindijetmass );
   reader->AddVariable( "maxdijetmass", &maxdijetmass );


    TString TreeName = "KinVars";

    TFile * input = TFile::Open(filename+".root");

   TTree* theTree = (TTree*)input->Get(TreeName);
   
   Float_t userVar1, userVar2;
   theTree->SetBranchAddress( "MassOfJets", &MassOfJets );
   theTree->SetBranchAddress( "DeltaPhiOfJets", &DeltaPhiOfJets );
   theTree->SetBranchAddress( "DeltaPhiLeadingJet", &DeltaPhiLeadingJet );
   theTree->SetBranchAddress( "Pbalance", &Pbalance );
   theTree->SetBranchAddress( "Sphericity", &Sphericity );


      Double_t _Weight=1.0;
      
	if (filename.Contains("hbb_120GeV"))  _Weight = 5.09999999999999967e-02;
        if (filename.Contains("qcd_15to30Gev"))  _Weight = 3.54815799999999990e+03;
        if (filename.Contains("qcd_30to50Gev"))  _Weight = 3.36987000000000023e+02;
        if (filename.Contains("qcd_50to150Gev"))  _Weight = 1.08418000000000006e+02;
	if (filename.Contains("qcd_150toInfGev"))  _Weight = 4.70999999999999996e+00;
	if (filename.Contains("data"))  _Weight = -1e0;

   //
   // book the MVA methods
   //
   TString dir    = "weights/";
   TString prefix = "TMVAClassification";

   // book method(s)
   for (std::map<std::string,int>::iterator it = Use.begin(); it != Use.end(); it++) {
      if (it->second) {
         TString methodName = it->first + " method";
         TString weightfile = dir + prefix + "_" + TString(it->first) + ".weights.xml";
         reader->BookMVA( methodName, weightfile ); 
      }
   }
   
   // example how to use your own method as plugin
   if (Use["Plugin"]) {
      // the weight file contains a line 
      // Method         : MethodName::InstanceName

      // if MethodName is not a known TMVA method, it is assumed to be
      // a user implemented method which has to be loaded via the
      // plugin mechanism
      
      // for user implemented methods the line in the weight file can be
      // Method         : PluginName::InstanceName
      // where PluginName can be anything

      // before usage the plugin has to be defined, which can happen
      // either through the following line in .rootrc:
      // # plugin handler          plugin       class            library        constructor format
      // Plugin.TMVA@@MethodBase:  PluginName   MethodClassName  UserPackage    "MethodName(DataSet&,TString)"
      //  
      // or by telling the global plugin manager directly
      gPluginMgr->AddHandler("TMVA@@MethodBase", "PluginName", "MethodClassName", "UserPackage", "MethodName(DataSet&,TString)");
      // the class is then looked for in libUserPackage.so

      // now the method can be booked like any other
      reader->BookMVA( "User method", dir + prefix + "_User.weights.txt" );
   }

   // book output histograms
   UInt_t nbin = 100;
   TH1F *histLk(0), *histLkD(0), *histLkPCA(0), *histLkKDE(0), *histLkMIX(0), *histPD(0), *histPDD(0);
   TH1F *histPDPCA(0), *histPDEFoam(0), *histPDEFoamErr(0), *histPDEFoamSig(0), *histKNN(0), *histHm(0);
   TH1F *histFi(0), *histFiG(0), *histFiB(0), *histLD(0), *histNn(0), *histNnC(0), *histNnT(0), *histBdt(0), *histBdtG(0), *histBdtD(0);
   TH1F *histRf(0), *histSVMG(0), *histSVMP(0), *histSVML(0), *histFDAMT(0), *histFDAGA(0), *histPBdt(0);

   if (Use["Likelihood"])    histLk      = new TH1F( "MVA_Likelihood",    "MVA_Likelihood",    nbin, -1, 1 );
   if (Use["LikelihoodD"])   histLkD     = new TH1F( "MVA_LikelihoodD",   "MVA_LikelihoodD",   nbin, -1, 0.9999 );
   if (Use["LikelihoodPCA"]) histLkPCA   = new TH1F( "MVA_LikelihoodPCA", "MVA_LikelihoodPCA", nbin, -1, 1 );
   if (Use["LikelihoodKDE"]) histLkKDE   = new TH1F( "MVA_LikelihoodKDE", "MVA_LikelihoodKDE", nbin,  -0.00001, 0.99999 );
   if (Use["LikelihoodMIX"]) histLkMIX   = new TH1F( "MVA_LikelihoodMIX", "MVA_LikelihoodMIX", nbin,  0, 1 );
   if (Use["PDERS"])         histPD      = new TH1F( "MVA_PDERS",         "MVA_PDERS",         nbin,  0, 1 );
   if (Use["PDERSD"])        histPDD     = new TH1F( "MVA_PDERSD",        "MVA_PDERSD",        nbin,  0, 1 );
   if (Use["PDERSPCA"])      histPDPCA   = new TH1F( "MVA_PDERSPCA",      "MVA_PDERSPCA",      nbin,  0, 1 );
   if (Use["KNN"])           histKNN     = new TH1F( "MVA_KNN",           "MVA_KNN",           nbin,  0, 1 );
   if (Use["HMatrix"])       histHm      = new TH1F( "MVA_HMatrix",       "MVA_HMatrix",       nbin, -0.95, 1.55 );
   if (Use["Fisher"])        histFi      = new TH1F( "MVA_Fisher",        "MVA_Fisher",        nbin, -4, 4 );
   if (Use["FisherG"])        histFiG    = new TH1F( "MVA_FisherG",        "MVA_FisherG",        nbin, -1, 1 );
   if (Use["BoostedFisher"])  histFiB    = new TH1F( "MVA_BoostedFisher",        "MVA_BoostedFisher",        nbin, -2, 2 );
   if (Use["LD"])            histLD      = new TH1F( "MVA_LD",            "MVA_LD",            nbin, -2, 2 );
   if (Use["MLP"])           histNn      = new TH1F( "MVA_MLP",           "MVA_MLP",           nbin, -1.25, 1.5 );
   if (Use["CFMlpANN"])      histNnC     = new TH1F( "MVA_CFMlpANN",      "MVA_CFMlpANN",      nbin,  0, 1 );
   if (Use["TMlpANN"])       histNnT     = new TH1F( "MVA_TMlpANN",       "MVA_TMlpANN",       nbin, -1.3, 1.3 );
   if (Use["BDT"])           histBdt     = new TH1F( "MVA_BDT",           "MVA_BDT",           nbin, -0.8, 0.8 );
   if (Use["BDTD"])          histBdtD    = new TH1F( "MVA_BDTD",          "MVA_BDTD",          nbin, -0.8, 0.8 );
   if (Use["BDTG"])          histBdtG    = new TH1F( "MVA_BDTG",          "MVA_BDTG",          nbin, -1.0, 1.0 );
   if (Use["RuleFit"])       histRf      = new TH1F( "MVA_RuleFit",       "MVA_RuleFit",       nbin, -2.0, 2.0 );
   if (Use["SVM_Gauss"])     histSVMG    = new TH1F( "MVA_SVM_Gauss",     "MVA_SVM_Gauss",     nbin, 0.0, 1.0 );
   if (Use["SVM_Poly"])      histSVMP    = new TH1F( "MVA_SVM_Poly",      "MVA_SVM_Poly",      nbin, 0.0, 1.0 );
   if (Use["SVM_Lin"])       histSVML    = new TH1F( "MVA_SVM_Lin",       "MVA_SVM_Lin",       nbin, 0.0, 1.0 );
   if (Use["FDA_MT"])        histFDAMT   = new TH1F( "MVA_FDA_MT",        "MVA_FDA_MT",        nbin, -2.0, 3.0 );
   if (Use["FDA_GA"])        histFDAGA   = new TH1F( "MVA_FDA_GA",        "MVA_FDA_GA",        nbin, -2.0, 3.0 );
   if (Use["Plugin"])        histPBdt    = new TH1F( "MVA_PBDT",          "MVA_BDT",           nbin, -0.8, 0.8 );

   // PDEFoam also returns per-event error, fill in histogram, and also fill significance
   if (Use["PDEFoam"]) {
      histPDEFoam    = new TH1F( "MVA_PDEFoam",       "MVA_PDEFoam",              nbin,  0, 1 );
      histPDEFoamErr = new TH1F( "MVA_PDEFoamErr",    "MVA_PDEFoam error",        nbin,  0, 1 );
      histPDEFoamSig = new TH1F( "MVA_PDEFoamSig",    "MVA_PDEFoam significance", nbin,  0, 10 );
   }

   // book example histogram for probability (the other methods are done similarly)
   TH1F *probHistFi(0), *rarityHistFi(0);
   if (Use["Fisher"]) {
      probHistFi   = new TH1F( "MVA_Fisher_Proba",  "MVA_Fisher_Proba",  nbin, 0, 1 );
      rarityHistFi = new TH1F( "MVA_Fisher_Rarity", "MVA_Fisher_Rarity", nbin, 0, 1 );
   }

   // Prepare input tree (this must be replaced by your data source)
   // in this example, there is a toy tree with signal and one with background events
   // we'll later on use only the "signal" events for the test in this example.
   //   
   /*TFile *input(0);
   TString fname = "./tmva_example.root";   
   if (!gSystem->AccessPathName( fname )) {
      input = TFile::Open( fname ); // check if file in local directory exists
   } 
   else { 
      input = TFile::Open( "http://root.cern.ch/files/tmva_class_example.root" ); // if not: download from ROOT server
   }
   
   if (!input) {
      std::cout << "ERROR: could not open data file" << std::endl;
      exit(1);
   }
   std::cout << "--- TMVAClassificationApp    : Using input file: " << input->GetName() << std::endl;
   */
   //
   // prepare the tree
   // - here the variable names have to corresponds to your tree
   // - you can use the same variables as above which is slightly faster,
   //   but of course you can use different ones and copy the values inside the event loop
   //

   // efficiency calculator for cut method
   Int_t    nSelCutsGA = 0;
   Double_t effS       = 0.7;

   std::cout << "--- Processing: " << theTree->GetEntries() << " events" << std::endl;
   TStopwatch sw;
   sw.Start();
   for (Long64_t ievt=0; ievt<theTree->GetEntries();ievt++) {

cout<<"Entry # "<<ievt<<endl;

      if (ievt%1000 == 0){
         std::cout << "--- ... Processing event: " << ievt << std::endl;
      }

      theTree->GetEntry(ievt);


      // 
      // return the MVAs and fill to histograms
      // 
/*      if (Use["CutsGA"]) {
         // Cuts is a special case: give the desired signal efficienciy
         Bool_t passed = reader->EvaluateMVA( "CutsGA method", effS );
         if (passed) nSelCutsGA++;
      }
*/
      if (Use["Likelihood"   ])   histLk     ->Fill( reader->EvaluateMVA( "Likelihood method"    ) );

 if (Use["Likelihood"   ]) cout<<"MVA value: "<<reader->EvaluateMVA( "Likelihood method"   )<<endl;

continue;
/*
      if (Use["LikelihoodD"  ])   histLkD    ->Fill( reader->EvaluateMVA( "LikelihoodD method"   ) );
      if (Use["LikelihoodPCA"])   histLkPCA  ->Fill( reader->EvaluateMVA( "LikelihoodPCA method" ) );
      if (Use["LikelihoodKDE"])   histLkKDE  ->Fill( reader->EvaluateMVA( "LikelihoodKDE method" ) );
      if (Use["LikelihoodMIX"])   histLkMIX  ->Fill( reader->EvaluateMVA( "LikelihoodMIX method" ) );
      if (Use["PDERS"        ])   histPD     ->Fill( reader->EvaluateMVA( "PDERS method"         ) );
      if (Use["PDERSD"       ])   histPDD    ->Fill( reader->EvaluateMVA( "PDERSD method"        ) );
      if (Use["PDERSPCA"     ])   histPDPCA  ->Fill( reader->EvaluateMVA( "PDERSPCA method"      ) );
      if (Use["KNN"          ])   histKNN    ->Fill( reader->EvaluateMVA( "KNN method"           ) );
      if (Use["HMatrix"      ])   histHm     ->Fill( reader->EvaluateMVA( "HMatrix method"       ) );
      if (Use["Fisher"       ])   histFi     ->Fill( reader->EvaluateMVA( "Fisher method"        ) );
      if (Use["FisherG"      ])   histFiG    ->Fill( reader->EvaluateMVA( "FisherG method"        ) );
      if (Use["BoostedFisher"])   histFiB    ->Fill( reader->EvaluateMVA( "BoostedFisher method"        ) );
      if (Use["LD"           ])   histLD     ->Fill( reader->EvaluateMVA( "LD method"            ) );
      if (Use["MLP"          ])   histNn     ->Fill( reader->EvaluateMVA( "MLP method"           ) );
      if (Use["CFMlpANN"     ])   histNnC    ->Fill( reader->EvaluateMVA( "CFMlpANN method"      ) );
      if (Use["TMlpANN"      ])   histNnT    ->Fill( reader->EvaluateMVA( "TMlpANN method"       ) );
      if (Use["BDT"          ])   histBdt    ->Fill( reader->EvaluateMVA( "BDT method"           ) );
      if (Use["BDTD"         ])   histBdtD   ->Fill( reader->EvaluateMVA( "BDTD method"          ) );
      if (Use["BDTG"         ])   histBdtG   ->Fill( reader->EvaluateMVA( "BDTG method"          ) );
      if (Use["RuleFit"      ])   histRf     ->Fill( reader->EvaluateMVA( "RuleFit method"       ) );
      if (Use["SVM_Gauss"    ])   histSVMG   ->Fill( reader->EvaluateMVA( "SVM_Gauss method"     ) );
      if (Use["SVM_Poly"     ])   histSVMP   ->Fill( reader->EvaluateMVA( "SVM_Poly method"      ) );
      if (Use["SVM_Lin"      ])   histSVML   ->Fill( reader->EvaluateMVA( "SVM_Lin method"       ) );
      if (Use["FDA_MT"       ])   histFDAMT  ->Fill( reader->EvaluateMVA( "FDA_MT method"        ) );
      if (Use["FDA_GA"       ])   histFDAGA  ->Fill( reader->EvaluateMVA( "FDA_GA method"        ) );
      if (Use["Plugin"       ])   histPBdt   ->Fill( reader->EvaluateMVA( "P_BDT method"         ) );

      // retrieve also per-event error
      if (Use["PDEFoam"]) {
         Double_t val = reader->EvaluateMVA( "PDEFoam method" );
         Double_t err = reader->GetMVAError();
         histPDEFoam   ->Fill( val );
         histPDEFoamErr->Fill( err );         
         histPDEFoamSig->Fill( val/err );
      }         

      // retrieve probability instead of MVA output
      if (Use["Fisher"])   {
         probHistFi  ->Fill( reader->GetProba ( "Fisher method" ) );
         rarityHistFi->Fill( reader->GetRarity( "Fisher method" ) );
      }
*/
cout<<"End of processing"<<endl;

   }
   // get elapsed time
   sw.Stop();
   std::cout << "--- End of event loop: "; sw.Print();

   // get efficiency for cuts classifier
   if (Use["CutsGA"]) std::cout << "--- Efficiency for CutsGA method: " << double(nSelCutsGA)/theTree->GetEntries()
                                << " (for a required signal efficiency of " << effS << ")" << std::endl;

   if (Use["CutsGA"]) {

      // test: retrieve cuts for particular signal efficiency
      // CINT ignores dynamic_casts so we have to use a cuts-secific Reader function to acces the pointer  
      TMVA::MethodCuts* mcuts = reader->FindCutsMVA( "CutsGA method" ) ;

      if (mcuts) {      
         std::vector<Double_t> cutsMin;
         std::vector<Double_t> cutsMax;
         mcuts->GetCuts( 0.7, cutsMin, cutsMax );
         std::cout << "--- -------------------------------------------------------------" << std::endl;
         std::cout << "--- Retrieve cut values for signal efficiency of 0.7 from Reader" << std::endl;
         for (UInt_t ivar=0; ivar<cutsMin.size(); ivar++) {
            std::cout << "... Cut: " 
                      << cutsMin[ivar] 
                      << " < \"" 
                      << mcuts->GetInputVar(ivar)
                      << "\" <= " 
                      << cutsMax[ivar] << std::endl;
         }
         std::cout << "--- -------------------------------------------------------------" << std::endl;
      }
   }

   //
   // write histograms
   //
   TFile *target  = new TFile( filename+"_out"+".root","RECREATE" );
   if (Use["Likelihood"   ])   {if (_Weight>0)histLk->Scale(_Weight);histLk     ->Write();}
   if (Use["LikelihoodD"  ])   {if (_Weight>0)histLkD->Scale(_Weight);histLkD     ->Write();}
   if (Use["LikelihoodPCA"])   {if (_Weight>0)histLkPCA->Scale(_Weight);histLkPCA     ->Write();}
   if (Use["LikelihoodKDE"])   {if (_Weight>0)histLkKDE->Scale(_Weight);histLkKDE     ->Write();}  
   if (Use["LikelihoodMIX"])   {if (_Weight>0)histLkMIX->Scale(_Weight);histLkMIX     ->Write();}  
   if (Use["PDERS"        ])   histPD     ->Write();
   if (Use["PDERSD"       ])   histPDD    ->Write();
   if (Use["PDERSPCA"     ])   histPDPCA  ->Write();
   if (Use["KNN"          ])   histKNN    ->Write();
   if (Use["HMatrix"      ])   histHm     ->Write();
   if (Use["Fisher"       ])   histFi     ->Write();
   if (Use["FisherG"      ])   histFiG    ->Write();
   if (Use["BoostedFisher"])   histFiB    ->Write();
   if (Use["LD"           ])   histLD     ->Write();
   if (Use["MLP"          ])   histNn     ->Write();
   if (Use["CFMlpANN"     ])   histNnC    ->Write();
   if (Use["TMlpANN"      ])   histNnT    ->Write();
   if (Use["BDT"          ])   histBdt    ->Write();
   if (Use["BDTD"         ])   histBdtD   ->Write();
   if (Use["BDTG"         ])   histBdtG   ->Write(); 
   if (Use["RuleFit"      ])   histRf     ->Write();
   if (Use["SVM_Gauss"    ])   histSVMG   ->Write();
   if (Use["SVM_Poly"     ])   histSVMP   ->Write();
   if (Use["SVM_Lin"      ])   histSVML   ->Write();
   if (Use["FDA_MT"       ])   histFDAMT  ->Write();
   if (Use["FDA_GA"       ])   histFDAGA  ->Write();
   if (Use["Plugin"       ])   histPBdt   ->Write();

   // write also error and significance histos
   if (Use["PDEFoam"]) { histPDEFoam->Write(); histPDEFoamErr->Write(); histPDEFoamSig->Write(); }

   // write also probability hists
   if (Use["Fisher"]) { if (probHistFi != 0) probHistFi->Write(); if (rarityHistFi != 0) rarityHistFi->Write(); }
   target->Close();

   std::cout << "--- Created root file: \"TMVApp.root\" containing the MVA output histograms" << std::endl;
  
   delete reader;
    
   std::cout << "==> TMVAClassificationApplication is done!" << endl << std::endl;
} 
コード例 #30
0
ファイル: isoDist.C プロジェクト: YeonjuGo/PhotonAnalysis2014
void isoDist(int num=1){

   // TFile* f = new TFile("Pyquen_AllQCDPhotons_PtHat15_PhotonFilter_pt15GeV_eta3_TuneZ2_Unquenched_2760GeV.root");
   // TFile* f = new TFile("Pyquen_AllQCDPhotons_PtHat15_PhotonFilter_pt15GeV_eta3_TuneZ2_Unquenched_2760GeV.root");
   // TFile* f = new TFile("Pyquen_AllQCDPhotons_PtHat30_PhotonFilter_pt15GeV_eta3_TuneZ2_Unquenched_2760GeV_event1000.root");
   // TFile* f = new TFile("Pyquen_AllQCDPhotons_PtHat50_PhotonFilter_pt15GeV_eta3_TuneZ2_Unquenched_2760GeV_event1000.root");
   // TFile* f = new TFile("Pyquen_AllQCDPhotons_PtHat80_PhotonFilter_pt15GeV_eta3_TuneZ2_Unquenched_2760GeV_event1000.root");
   // TFile* f = new TFile("Pyquen_AllQCDPhotons_PtHat120_PhotonFilter_pt15GeV_eta3_TuneZ2_Unquenched_2760GeV_event1000.root");
  //  TFile* f = new TFile("Pyquen_AllQCDPhotons_PtHat170_PhotonFilter_pt15GeV_eta3_TuneZ2_Unquenched_2760GeV_event1000.root");
   // TFile* f = new TFile("Pyquen_AllQCDPhotons_PtHat5_PhotonFilter_pt15GeV_eta3_TuneZ2_Unquenched_2760GeV_numEvent780.root");
    TFile* f = new TFile("Pyquen_AllQCDPhotons_PtHat15_PhotonFilter_pt35GeV_eta3_TuneZ2_Unquenched_2760GeV_numEvent1000.root");

    TTree* t = (TTree*) f -> Get("genpana/photon");
 //  cout << "lsdjf" << endl; 
    Int_t cBin, nPar, id[3000], momId[3000], status[3000], collId[3000];
    Float_t hf, recoVtxZ, ptHat, pt[3000], et[3000], eta[3000], phi[3000], iso[3000], charge[3000]; 
    
    t -> SetBranchAddress("cBin", &cBin);
    t -> SetBranchAddress("hf", &hf);
    t -> SetBranchAddress("nPar", &nPar);
    t -> SetBranchAddress("recoVtxZ", &recoVtxZ);
    t -> SetBranchAddress("et", &et);
    t -> SetBranchAddress("pt", &pt);
   // t -> SetBranchAddress("ptHat", &ptHat);
    t -> SetBranchAddress("eta", &eta);
    t -> SetBranchAddress("phi", &phi);
    t -> SetBranchAddress("charge", &charge);
    t -> SetBranchAddress("id", &id);
    t -> SetBranchAddress("iso", &iso);
    t -> SetBranchAddress("momId", &momId);
    t -> SetBranchAddress("status", &status);
    t -> SetBranchAddress("collId", &collId);
    
//    cout << "sdgwggg" << endl;
    double tempPt = 0;
    double tempIso = 0;
    int tempIndex =0;
    TH1D* h = new TH1D("h", ";p_{T} (GeV); Entries", 80, 0, 80);
    TH1D* hbkg = (TH1D*)h->Clone("hbkg");
    TH1D* hdirect = (TH1D*)h->Clone("hdirect");
    TH1D* hfrag = (TH1D*)h->Clone("hfrag");
  //  TH1D* hbkg = new TH1D("hbkg", ";p_{T} (GeV); Entries", 50, 0, 300);
  //  TH1D* hdirect = new TH1D("hdirect", ";p_{T} (GeV); Entries", 50, 0, 300);
  //  TH1D* hfrag = new TH1D("hfrag", ";p_{T} (GeV); Entries", 50, 0, 300);
    
    hbkg -> SetLineColor(2); 
    hdirect -> SetLineColor(3); 
    hfrag -> SetLineColor(4); 
    
    for(int i=0; i<t->GetEntries(); i++){
        t -> GetEntry(i);
        cout << "event num = " << i <<  ", nPar : " << nPar << endl;
        for(int j=0; j<nPar; j++){
            if(id[j]!=22) continue;
            if(fabs(eta[j])>3) continue;
            if(status[j]!=1) continue;
          //  if(pt[j]<=35) continue;
          //  cout << "survive!! j = " << j << endl;
            if(pt[j]>=tempPt){
                tempPt = pt[j];
                tempIso = iso[j];
                tempIndex = j;
            }
            cout << "event : "<< i << ", particle number : " << j << ", pt : " << pt[j] << ", tempPt : " << tempPt << ", iso : " << iso[j]<< ", tempIso : " << tempIso << endl;
        }
      //  if(tempPt>=35){
        h -> Fill(tempIso);
        if(abs(momId[tempIndex])<22) hfrag -> Fill(tempIso);
        else if(abs(momId[tempIndex])==22) hdirect -> Fill(tempIso);
        else if(abs(momId[tempIndex])>22) hbkg -> Fill(tempIso);
       // }
        tempPt =0;
        tempIso = 0;
        tempIndex =0;
    }
    TCanvas* c1 = new TCanvas("c1", "c1", 400, 400);
    h -> Draw();
    hbkg -> Draw("same");
    hdirect -> Draw("same");
    hfrag -> Draw("same");
    gPad -> SetLogy();

    TLegend* l1 = new TLegend(0.4,0.6,0.87,0.80);
    l1 -> AddEntry("hbkg", "background");
    l1 -> AddEntry("hdirect", "direct photon");
    l1 -> AddEntry("hfrag", "fragmentation photon");
    l1 -> Draw();
    
    
    // directRatio = direct/(direct+frag), fragRatio = frag/(direct+frag)
    // for 15, 30, 
    double directRatio[3];
    double fragRatio[3];
    double direct[3];
    double frag[3];
    direct[0] = hdirect->Integral(hdirect->FindBin(15),hdirect->FindBin(300));
    direct[1] = hdirect->Integral(hdirect->FindBin(35),hdirect->FindBin(300));
    direct[2] = hdirect->Integral(hdirect->FindBin(60),hdirect->FindBin(300));
    frag[0] = hfrag->Integral(hfrag->FindBin(15),hfrag->FindBin(300));
    frag[1] = hfrag->Integral(hfrag->FindBin(35),hfrag->FindBin(300));
    frag[2] = hfrag->Integral(hfrag->FindBin(60),hfrag->FindBin(300));
    
    directRatio[0] = direct[0]/(direct[0]+frag[0]);
    directRatio[1] = direct[1]/(direct[1]+frag[1]);
    directRatio[2] = direct[2]/(direct[2]+frag[2]);
    
    fragRatio[0] = frag[0]/(direct[0]+frag[0]);
    fragRatio[1] = frag[1]/(direct[1]+frag[1]);
    fragRatio[2] = frag[2]/(direct[2]+frag[2]); 
    
    
    cout << directRatio[0]<< endl;
    cout << directRatio[1]<< endl;
    cout << directRatio[2]<< endl;
    cout << fragRatio[0]<< endl;
    cout << fragRatio[1]<< endl;
    cout << fragRatio[2]<< endl;
}