Exemplo n.º 1
0
void cmpLRD(TFile* f1, TFile* f2, const char* dName, const char* patt = 0, unsigned int logmod=0, unsigned int dOpt=1){
  //  std::cout<<"cmpLRD In "<< dName<<std::endl;
  TDirectory* td = gROOT->GetDirectory(dName);
  if (td){
    TList* tkl = td->GetListOfKeys();
    unsigned int tklSize = tkl->GetEntries();
    //    std::cout<<"\t size "<<tklSize<<std::endl;
    for (unsigned int iK=0; iK< tklSize; ++iK){
      //      std::cout<<"at "<<iK<<"\t " <<tkl->At(iK)->GetName()<<std::endl;
      if (TClass(((TKey*)tkl->At(iK))->GetClassName()).InheritsFrom("TDirectory")){
	TDirectory* tdc = (TDirectory*)((TKey*)tkl->At(iK))->ReadObj();
	if (tdc ==0) continue;
	TString tdcPFull(tdc->GetPath());
	TString pRel(tdcPFull.Tokenize(":")->At(1)->GetName());
	//	std::cout<<tdcPFull.Data()<<std::endl;
	
	//now execute compare 
	//	if(pRel.Index("/SiStrip/")>=0) continue; //this takes a huge time in alcareco and is irrelevant
	///DQMData/Run 1/Btag
	if (patt==0 || (patt!=0 && pRel.Index(patt)>=0)){
	  //	  std::cout<<"Comparing in " <<pRel.Data()<<std::endl;
	  compareInDir(f1, f2, pRel.Data(),logmod,dOpt);
	}
	cmpLRD(f1, f2, tdcPFull.Data(), patt,logmod,dOpt);
      }
    }
  }
}
/*************************************************************************************
 * getKS: Searches through the histograms in the plotter output, adds the MC together
 *        for each field, and compares the MC with the Data histogram using a KS test
 *  input:  the main() arguments array
 *  output: writes to stdout the (human-readable) KS statistics of pairs of histograms
 *
 *  Structure-wise: this is fine, can be implemented into class easily.
 ***********************************/
void getKS(const char* argv[]) {
  //open the input TFile
  TFile *f = new TFile(argv[2]);
  f->cd();

  //get the filesystem information from the file
  TList *alokDirs = (TList*) f->GetListOfKeys();

  //loop through the directories in the input file
  for(int idir=0; alokDirs->At(idir-1) != alokDirs->Last(); idir++) {
    TDirectory *cDir  = (TDirectory*) f->Get(alokDirs->At(idir)->GetName());
    TList *alokHistos = (TList*)      cDir->GetListOfKeys();

    // create the MC histogram and start collecting relevant MC histograms
    // from the current directory
    TList *aloh   = new TList;
    // loop through keys (histograms) in current directory
    for(int ihisto=0; alokHistos->At(ihisto) != alokHistos->Last(); ihisto++) {
      if(TString(alokHistos->At(ihisto)->GetName()).Contains("MC8TeV")) {
        TH1F *cHisto = (TH1F*) cDir->Get(alokHistos->At(ihisto)->GetName());
        aloh->Add(cHisto);
      }
    }
 
    //merge the data histograms into one histogram
    TH1F *MCHisto = (TH1F*) (aloh->Last())->Clone(TString(cDir->GetName()) + TString("MCHisto"));
    aloh->RemoveLast();
    MCHisto->Merge(aloh);

    cout<<"-------------------- "<<cDir->GetName()<<" -----------------------"<<endl;
    //now create the data histogram and run the KS test
    TH1F *DataHisto = (TH1F*) cDir->Get(alokHistos->Last()->GetName());
    cout<<"  ---> KS Test: "<<cDir->GetName()<<" has probability "<<MCHisto->KolmogorovTest(DataHisto, "D")<<"\n"<<endl;
  }
}
Exemplo n.º 3
0
   UInt_t GetListOfJobs( TFile* file, TList& jobdirs)
   {
      // get a list of all jobs in all method directories
      // based on ideas by Peter and Joerg found in macro deviations.C
      TIter next(file->GetListOfKeys());
      TKey *key(0);   
      while ((key = (TKey*)next())) {
         
         if (TString(key->GetName()).BeginsWith("Method_")) {
            if (gROOT->GetClass(key->GetClassName())->InheritsFrom("TDirectory")) {

               TDirectory* mDir = (TDirectory*)key->ReadObj();
               
               TIter keyIt(mDir->GetListOfKeys());
               TKey *jobkey;
               while ((jobkey = (TKey*)keyIt())) {
                  if (!gROOT->GetClass(jobkey->GetClassName())->InheritsFrom("TDirectory")) continue;
                  
                  TDirectory *jobDir = (TDirectory *)jobkey->ReadObj();
                  cout << "jobdir name  " << jobDir->GetName() << endl;
                  jobdirs.Add(jobDir);
               }
            }
         }
      }
      return jobdirs.GetSize();
   }
Exemplo n.º 4
0
std::vector<TString> histoList( TString currentfile, TString theDir )
{

 gROOT ->Reset();
 const char*  sfilename = currentfile.Data();

 delete gROOT->GetListOfFiles()->FindObject(sfilename);

 TFile * sfile = new TFile(sfilename);

 const char* baseDir=theDir.Data();

 sfile->cd(baseDir);

 TDirectory * d = gDirectory;

 std::vector<TString> theHistList;

 TIter i( d->GetListOfKeys() );
 TKey *k;
 while( (k = (TKey*)i())) {
   TClass * c1 = gROOT->GetClass(k->GetClassName());
   if ( !c1->InheritsFrom("TH1")) continue;
   theHistList.push_back(k->GetName());
 }
 
 std::cout << "Histograms considered: " << std::endl;
 for (unsigned int index = 0; index < theHistList.size() ; index++ ) {
   std::cout << index << " " << theHistList[index] << std::endl;
 }

 return theHistList;

}
Exemplo n.º 5
0
void create_module_info(TString dir = "/castor/cern.ch/user/r/rougny/vcalH2L_7/GainRun_173484"){
  ofstream t;
  t.open("module_info.txt");
  if(! t.is_open()){
    cout << "[create_module_info] Could not open output txt file. Exiting ..." << endl;
    exit(1);
  }

  for(int i=0 ; i<40 ; ++i){
    ostringstream f_str("");
    f_str << "rfio://" << dir << "/" << i << ".root";
    cout << "Opening file : " << f_str.str() << endl;
    TFile* f = TFile::Open(f_str.str().c_str() , "READ");
    vector<TString> dir_list = makedirlist(f , "Module");
    
    for(int m = 0 ; m < dir_list.size() ; ++m){
      
      TDirectory* dir = f->GetDirectory(dir_list[m]);
      int detid = getDetId(((TH1*) dir->Get(((TKey*) dir->GetListOfKeys()->At(0))->GetName()))->GetName());
    
      t << detid << "  " << i << "  " << dir_list[m].Remove(0,dir_list[m].First('y')+2) << endl;
    
    }


    f->Close();
  
  }

  t.close();

}
void fill(TDirectory & out, TObject * o, double w) {
  TDirectory * dir;
  TH1F * th1f;
  TH1D * th1d;
  TH2F * th2f;
  TH2D * th2d;
  if((dir  = dynamic_cast<TDirectory*>(o)) != 0) {
    const char * name = dir->GetName();
    TDirectory * outDir = dynamic_cast<TDirectory*>(out.Get(name));
    if(outDir == 0) {
      cerr << "can't find directory " << name << " in output file" << endl;
      exit(-1);
    }
    TIter next(dir->GetListOfKeys());
    TKey *key;
    while( (key = dynamic_cast<TKey*>(next())) ) {
      string className(key->GetClassName());
      string name(key->GetName());
      TObject * obj = dir->Get(name.c_str());
      if(obj == 0) {
	cerr <<"error: key " << name << " not found in directory " << dir->GetName() << endl;
	exit(-1);
      }
      fill(*outDir, obj, w);
    }
  } else if((th1f = dynamic_cast<TH1F*>(o)) != 0) {
    const char * name = th1f->GetName();
    TH1F * outTh1f = dynamic_cast<TH1F*>(out.Get(name));
    if(outTh1f == 0) {
      cerr <<"error: histogram TH1F" << name << " not found in directory " << out.GetName() << endl;
      exit(-1);	
    }
    outTh1f->Add(th1f, w);
  } else if((th1d = dynamic_cast<TH1D*>(o)) != 0) {
    const char * name = th1d->GetName();
    TH1D * outTh1d = dynamic_cast<TH1D*>(out.Get(name));
    if(outTh1d == 0) {
      cerr <<"error: histogram TH1D" << name << " not found in directory " << out.GetName() << endl;
      exit(-1);	
    } 
    outTh1d->Add(th1d, w);
  } else if((th2f = dynamic_cast<TH2F*>(o)) != 0) {
    const char * name = th2f->GetName();
    TH2F * outTh2f = dynamic_cast<TH2F*>(out.Get(name));
    if(outTh2f == 0) {
      cerr <<"error: histogram TH2F" << name << " not found in directory " << out.GetName() << endl;
      exit(-1);	
    }
    outTh2f->Add(th2f, w);
  } else if((th2d = dynamic_cast<TH2D*>(o)) != 0) {
    const char * name = th2d->GetName();
    TH2D * outTh2d = dynamic_cast<TH2D*>(out.Get(name));
    if(outTh2d == 0) {
      cerr <<"error: histogram TH2D" << name << " not found in directory " << out.GetName() << endl;
      exit(-1);	
    }
    outTh2d->Add(th2d, w);
  }
}
Exemplo n.º 7
0
int ReadFromDir(TFile *fout, const TString &dirName, std::vector<std::vector<TH1F*>*> &hVV, std::vector<TString> &names) {
  hVV.clear(); names.clear();

  fout->cd(dirName);
  TDirectory *sourceDir = gDirectory;
  TList *subDirList=sourceDir->GetListOfKeys();
  int count=subDirList->GetEntries();
  std::cout << "there are " << count << " keys\n";
  hVV.reserve(count);
  TIter subDirs(subDirList);
  TKey *key=NULL;
  while ( (key = (TKey*)subDirs()) ) {
    const TString sDirName=key->GetName();
    std::cout << "sDirName=" << sDirName << "\n";
    names.push_back( sDirName );
    sourceDir->cd( sDirName );
    TDirectory *currDir = gDirectory;
    TList *histosList=currDir->GetListOfKeys();
    TIter histos( histosList );
    std::vector<TH1F*> *hV = new std::vector<TH1F*>();
    hVV.push_back(hV);
    hV->reserve(histosList->GetEntries());
    while( (key = (TKey*)histos()) ) {
      std::cout << "key->GetName() = " << key->GetName() << "\n";
      TObject *obj= key->ReadObj();
      if ( obj->IsA()->InheritsFrom( TH1F::Class() ) ) {
	TH1F *h=(TH1F*)obj;
	h->SetDirectory(0);
	hV->push_back(h);
      }
      else {
	delete hV;
      }
    }
  }
  return 1;
}
Exemplo n.º 8
0
   UInt_t GetListOfTitles( TString & methodName, TList & titles, TDirectory *dir=0 )
   {
      // get the list of all titles for a given method
      // if the input dir is 0, gDirectory is used
      // returns a list of keys
      UInt_t ni=0;
      if (dir==0) dir = gDirectory;
      TDirectory* rfdir = (TDirectory*)dir->Get( methodName );
      if (rfdir==0) {
         cout << "+++ Could not locate directory '" << methodName << endl;
         return 0;
      }

      return GetListOfTitles( rfdir, titles );

      TList *keys = rfdir->GetListOfKeys();
      if (keys==0) {
         cout << "+++ Directory '" << methodName << "' contains no keys" << endl;
         return 0;
      }
      //
      TIter rfnext(rfdir->GetListOfKeys());
      TKey *rfkey;
      titles.Clear();
      titles.SetOwner(kFALSE);
      while ((rfkey = (TKey*)rfnext())) {
         // make sure, that we only look at histograms
         TClass *cl = gROOT->GetClass(rfkey->GetClassName());
         if (cl->InheritsFrom("TDirectory")) {
            titles.Add(rfkey);
            ni++;
         }
      }
      cout << "--- Found " << ni << " instance(s) of the method " << methodName << endl;
      return ni;
   }
Exemplo n.º 9
0
void CalibrationScanAnalysis::getSummaries(FileList::const_iterator file) {
  std::cout << "." << std::flush;
  std::vector<TH1*> result;  
  TFile* input = file->second;
  TDirectory* directory = input->GetDirectory(HISTOPATH);
  TList* histograms = directory->GetListOfKeys();
  TIter next(histograms);
  TKey* key = NULL;
  while ((key = (TKey*)next())) {
    if(TClass(key->GetClassName()).InheritsFrom("TH1")) {
      TH1* h = (TH1*)key->ReadObj();
      result.push_back(h);
    }
  }
  summaries_[file->first] = result;
}
void make(TDirectory & out, TObject * o) {
  TDirectory * dir;
  TH1F * th1f;
  TH1D * th1d;
  TH2F * th2f;
  TH2D * th2d;
  out.cd();
  if((dir = dynamic_cast<TDirectory*>(o)) != 0) {
    TDirectory * outDir = out.mkdir(dir->GetName(), dir->GetTitle());
    TIter next(dir->GetListOfKeys());
    TKey *key;
    while( (key = dynamic_cast<TKey*>(next())) ) {
      string className(key->GetClassName());
      string name(key->GetName());
      TObject * obj = dir->Get(name.c_str());
      if(obj == 0) {
	cerr <<"error: key " << name << " not found in directory " << dir->GetName() << endl;
	exit(-1);
      }
      make(*outDir, obj);
    }
  } else if((th1f = dynamic_cast<TH1F*>(o)) != 0) {
    TH1F *h = (TH1F*) th1f->Clone();
    h->Reset();
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th1d = dynamic_cast<TH1D*>(o)) != 0) {
    TH1D *h = (TH1D*) th1d->Clone();
    h->Reset();
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th2f = dynamic_cast<TH2F*>(o)) != 0) {
    TH2F *h = (TH2F*) th2f->Clone();
    h->Reset();   
    h->Sumw2();
    h->SetDirectory(&out);
  } else if((th2d = dynamic_cast<TH2D*>(o)) != 0) {
    TH2D *h = (TH2D*) th2d->Clone();
    h->Reset();   
    h->Sumw2();
    h->SetDirectory(&out);
  }
}
Exemplo n.º 11
0
void DrawNetworkMovie( TFile* file, const TString& methodType, const TString& methodTitle )
{

   TString     dirname  = methodType + "/" + methodTitle + "/" + "EpochMonitoring";
   TDirectory *epochDir = (TDirectory*)file->Get( dirname );
   if (!epochDir) {
      cout << "Big troubles: could not find directory \"" << dirname << "\"" << endl;
      exit(1);
   }
   epochDir->cd();

   // loop over all epoch-wise monitoring histograms
   TIter keyIt(epochDir->GetListOfKeys());
   TKey *key;
   vector<TString> epochList;
   Int_t ic = 0;
   while ((key = (TKey*)keyIt())) {
      
      if (!gROOT->GetClass(key->GetClassName())->InheritsFrom("TH2F")) continue;
      TString name = key->GetName();
      
      if (!name.BeginsWith("epochmonitoring___")) continue;
      
      // extract epoch
      TObjArray* tokens = name.Tokenize("_");
      TString es = ((TObjString*)tokens->At(2))->GetString();

      // check if done already      
      Bool_t isOld = kFALSE;
      for (vector<TString>::const_iterator it = epochList.begin(); it < epochList.end(); it++) {
         if (*it == es) isOld = kTRUE; 
      }
      if (isOld) continue;
      epochList.push_back( es );

      // create bulk file name
      TString bulkname  = Form( "epochmonitoring___epoch_%s_weights_hist", es.Data() );

      // draw the network
      if (ic <= 60) draw_network( file, epochDir, bulkname, kTRUE, es );
      ic++;
   }
}
Exemplo n.º 12
0
Arquivo: merge.C Projeto: XuQiao/HI
void merge(){
	if (!TClass::GetDict("NBD")) {
		gROOT->ProcessLine(".L /afs/cern.ch/user/q/qixu/CMSSW_6_2_5/src/Centrality/NBD_Glauber_fit/NBD/NBDclass.C++");
	}

	TFile *f;
	f=TFile::Open(Form("G.root"),"ReadOnly");
	TFile *fg = new TFile("graph.root","Update");
	TDirectory *dir;
	TList *def, *tl;
	TKey *key;
	TString dirname;
	for(int sth=0; sth<3; sth++){
	if(sth==0) dirname = "std";
        else if(sth==1) dirname ="Gri055";
        else  dirname ="Gri101";
	dir = f->GetDirectory(dirname);
	def = new TList();
	int iGlau=0;
	//int iGlau=atoi(getenv("GTH"));
	tl = dir->GetListOfKeys();
	for(iGlau=0; iGlau<nGlau; iGlau++){
		key = ((TKey*) tl->At(iGlau));
		NBD* temp = (NBD*)key->ReadObj();
		def->Add(temp);
	}
	
	NBD *n0 = (NBD*)def->At(0);
	n0->calcsys(def);
	TString op;
	for(int option=0;option<3;option++){
	if(option==0) op=Form("%s_Ncoll",dirname.Data());
	else if(option==1) op=Form("%s_Npart",dirname.Data());
	else op=Form("%s_B",dirname.Data());
	TGraphErrors* gr = n0->DrawGraph(option);
	gr->Write(op);
	}
	}
	fg->Close();
	f->Close();
}
Exemplo n.º 13
0
void rescaleBoundaryHists(std::string infile, int numSamples=-1){

  TFile* f = new TFile(infile.c_str(), "UPDATE");
  TDirectory* dir = 0;

  TIter dir_it(f->GetListOfKeys());
  TKey* dir_k;
  while ((dir_k = (TKey *)dir_it())) {
    if (TString(dir_k->GetClassName()) != "TDirectoryFile") continue;
    std::string dir_name = std::string(dir_k->GetTitle());
    if(dir_name == "") continue;
    dir = (TDirectory*)dir_k->ReadObj();
    if(dir == 0) continue;
    TIter hist_it(dir->GetListOfKeys(), kIterBackward);
    TKey* hist_k;
    while ((hist_k = (TKey *)hist_it())) {
      std::string hist_name = (hist_k->GetTitle());
      if (hist_name.find("_HI") != std::string::npos || hist_name.find("_LOW") != std::string::npos || hist_name.find("h_n_mt2bins") != std::string::npos) {
        TH1* h = (TH1*)hist_k->ReadObj();
        if(numSamples==-1)
            h->Scale(1.0/h->GetEntries());
        else
            h->Scale(1.0/numSamples);
        dir->cd();
        h->Write("",TObject::kOverwrite);
      }
    }
  }

  delete dir;

  gDirectory->GetList()->Delete();
  
  f->Write("",TObject::kOverwrite);
  f->Close();
  delete f;

}
Exemplo n.º 14
0
void printBadEvents(string filename){
  string run = filename.substr(filename.find("_R000")+10, 1);
  int nrun = atoi(run.c_str());
  string fname(filename.substr(filename.find_last_of("/")+1) );
  cout << "FileName is " << fname.c_str() << endl;

  ofstream outfile;
  stringstream namefile;
  namefile << "BadEvents_" << nrun << ".txt";
  outfile.open(namefile.str().c_str());
  outfile << "Bad events in file " << fname.c_str() << endl; 

  TDirectory* topDir; 
  TFile* file = TFile::Open(filename.c_str());
  if (!file->IsOpen()) {
    cerr << "Failed to open " << filename << endl; 
    return;
  }
  string dir = "DQMData/Run " + run + "/ParticleFlow/Run summary/ElectronValidation/JetPtRes/BadEvents";
  topDir = dynamic_cast<TDirectory*>( file->Get(dir.c_str()));
  topDir->cd();
  if (topDir){
    TIter next(topDir->GetListOfKeys());
    TKey *key;
    while  ( (key = dynamic_cast<TKey*>(next())) ) {
      string sflag = key->GetName();
      string info(sflag.substr(1, sflag.find_first_of(">")-1 ) );
      string run(info.substr(0, info.find_first_of("_")) );
      string evt = info.substr( info.find_first_of("_")+1, info.find_last_of("_")-2);
      string ls(info.substr(info.find_last_of("_")+1,info.find_first_of("_")+1));
      string ptres = ( sflag.substr( sflag.find( "f=" ) + 2, 6 ) ).c_str();
      cout << "Event info: Run " << run << " LS " << ls << " Evt " << evt << " Jet Pt Res = " << ptres << endl; 
      outfile << "Event info: Run " << run << " LS " << ls << " Evt " << evt << " Jet Pt Res = " << ptres << endl; 
    }
  }
}
Exemplo n.º 15
0
void drawBeamSpotGraphsAll (TFile* file, const char* fname=0)
{
  TDirectory* module = (TDirectory*)_file0->FindObjectAny("beamSpotFitPV");
  if ( module==0 )  return;

//   unsigned int nrun = module->GetListOfKeys()->GetSize();
//   TDirectory* currDir = gDirectory;
//   gROOT->cd();
//   TH1* hChi2 = new TH1F("runChi2","runChi2",nrun,0.5,nrun+0.5);
//   TH1* hConst = new TH1F("runConst","runConst",nrun,0.5,nrun+0.5);
//   TH1* hSlope = new TH1F("runSlope","runSlope",nrun,0.5,nrun+0.5);
//   currDir->cd();

  TIter iter(module->GetListOfKeys());
  TKey* key;
//   unsigned int irun(0);
//   float runSummary[6];
  while ( (key=(TKey*)iter()) ) {
    std::cout << key->GetName() << std::endl;
    drawBeamSpotGraphs(_file0,key->GetName(),fname);
    TIter ic(gROOT->GetListOfCanvases());
    TCanvas* c;
    while ( (c=(TCanvas*)ic()) )  delete c;
//     ++irun;
//     if ( runSummary[1]>0.1 )  hChi2->SetBinContent(irun,runSummary[0]/runSummary[1]);
//     hConst->SetBinContent(irun,runSummary[2]);
//     hConst->SetBinError(irun,runSummary[3]);
//     hSlope->SetBinContent(irun,runSummary[4]);
//     hSlope->SetBinError(irun,runSummary[5]);
//     hChi2->GetXaxis()->SetBinLabel(irun,key->GetName());
//     hConst->GetXaxis()->SetBinLabel(irun,key->GetName());
//     hSlope->GetXaxis()->SetBinLabel(irun,key->GetName());
//     if ( irun==3 )  return;
  }

}
Exemplo n.º 16
0
void TnPDrawMass_for_B() {
    gROOT->Macro("rootlogon.C");

    char *infile;
    char *files[maxfile_] = {
        "../../Ana/RD/MuTrk/tnp_pPb_Ana_MuTrk2_2GpP4_1st_Run_for_B_test.root",
    };

    TString outname_in, outname_mid, outname_out;
    TString middle_name, middle_name2;
    int Mode = 0;

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

    gStyle->SetPaperSize(20,26);
    TCanvas *c1 = new TCanvas();
    Int_t type = 112;
    TString out1 = outfile_ + "[";
    c1->Print(out1);

    for(int l = 0; l < maxfile_; l++) {

        infile = files[l];
        TFile *f = new TFile(infile);
        //TFile finput(infile);
        Mode = l;

        if(Mode == 0) {
            middle_name = "All";
            middle_name2 = "MinBias";
        } else if(Mode == 1) {
            middle_name = "0005";
            middle_name2 = "0 - 5 %";
        } else if(Mode == 2) {
            middle_name = "0510";
            middle_name2 = "5 - 10 %";
        } else if(Mode == 3) {
            middle_name = "1020";
            middle_name2 = "10 - 20 %";
        } else if(Mode == 4) {
            middle_name = "2030";
            middle_name2 = "20 - 30 %";
        } else if(Mode == 5) {
            middle_name = "3040";
            middle_name2 = "30 - 40 %";
        } else if(Mode == 6) {
            middle_name = "4050";
            middle_name2 = "40 - 50 %";
        } else if(Mode == 7) {
            middle_name = "5060";
            middle_name2 = "50 - 60 %";
        } else if(Mode == 8) {
            middle_name = "60100";
            middle_name2 = "60 - 100 %";
        }


        outname_in = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps[";
        outname_mid = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps";
        outname_out = "Jpsi_" + Cat1 + "_" + Cat2 + "_Mass_" + middle_name + ".ps]";


        cout<<" Out Name : "<<outname_in<<" "<<outname_mid<<" "<<outname_in<<endl;


        TString tot_dir, dir_pt, dir_eta, dir_suffix, intg;

        TString etabins[etaBins] = {"eta_bin0_", "eta_bin1_", "eta_bin2_", "eta_bin3_", "eta_bin4_"};
        TString ptbins[ptBins] = {"pt_bin0_", "pt_bin1_", "pt_bin2_", "pt_bin3_", "pt_bin4_",
                                  "pt_bin5_", "pt_bin6_"
                                 };
        if(Mode_ == 1) {
            if(TrgBit_ == 1) {
                dir_pt = "MuonTrgNew2CS/PAMu3_pt/";
                dir_eta = "MuonTrgNew2CS/PAMu3_eta/";
                dir_suffix = "_cbPlusExpo";
                intg = "MuonTrgNew2CS/PAMu3_1bin_pt_eta/eta_bin0__pt_bin0_";
            } else if(TrgBit_ == 2) {
                dir_pt = "MuonTrgNew/HLTL1HighQ_pt/";
                dir_eta = "MuonTrgNew/HLTL1HighQ_eta/";
                dir_suffix = "_cbPlusExpo";
                intg = "MuonTrgNew/HLTL1HighQ_1bin_pt_eta/pt_bin0__eta_bin0_";
            } else if(TrgBit_ == 3) {
                dir_pt = "MuonTrgNew/HLTL2_pt/";
                dir_eta = "MuonTrgNew/HLTL2_eta/";
                dir_suffix = "_cbPlusExpo";
                intg = "MuonTrgNew/HLTL2_1bin_pt_eta/pt_bin0__eta_bin0_";
            }
        } else if (Mode_ == 2) {
            dir_pt = "MuonTrk2/isTrk_pt/";
            dir_eta = "MuonTrk2/isTrk_eta/";
            dir_suffix = "_twoGaussPlusPoly4";
            intg = "MuonTrk2/isTrk_1bin_pt_eta/eta_bin0__pt_bin0_";
        } else if (Mode_ == 3) {
            dir_pt = "/MuonIDNew2CS/PassingTrk_pt/";
            dir_eta = "/MuonIDNew2CS/PassingTrk_eta/";
            dir_suffix = "_cbPlusPoly";
            intg = "/MuonIDNew2CS/PassingTrk_1bin_eta_pt/eta_bin0__pt_bin0_";
        }
        ///*

        cout<<" Total directory : "<<tot_dir<<endl;
        gStyle->SetPaperSize(20,26);

        Int_t type = 112;

        c1->Print(outname_in);
        int cnt = 0;

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

        TString title;
        title = "J/#psi " + Cat3 + " Efficiency Heavy Ion TnP Result (" + middle_name2 + ")";

        TLatex fitInfo;
        fitInfo.SetTextAlign(13);
        fitInfo.SetTextSize(0.05);
        fitInfo.DrawLatex(0.05,0.95, title);
        fitInfo.DrawLatex(0.05,0.90, data_set);
        fitInfo.SetTextSize(0.04);
        fitInfo.DrawLatex(0.05,0.80, "FitFunction Condition");
        fitInfo.SetTextSize(0.03);
        if(Mode_ == 1) {
            fitInfo.DrawLatex(0.1,0.60,"CBShape::signal(mass, mean[3.1,3.0,3.2], sigma[0.05,0.01,0.1], alpha[1.0, 0.2, 2.0], n[2, 0.5, 100.])");
            fitInfo.DrawLatex(0.1,0.55,"Exponential::backgroundPass(mass, lp[0,-5,5])");
            fitInfo.DrawLatex(0.1,0.50,"Exponential::backgroundFail(mass, lf[0,-5,5])");
        } else if(Mode_ == 2) {
            fitInfo.DrawLatex(0.1,0.70,"Gaussian::G1(mass, mean, sigma1[0.15,0.05,0.25])");
            fitInfo.DrawLatex(0.1,0.65,"Gaussian::G2(mass, mean, sigma2[0.02,0.01,0.1])");
            fitInfo.DrawLatex(0.1,0.60,"SUM::signal(coef[0.1,0,1]*G1,G2)");
            fitInfo.DrawLatex(0.1,0.55,"Chebychev::backgroundPass(mass, {cPass[0,-0.5,0.5], cPass2[0,-0.5,0.5]})");
            fitInfo.DrawLatex(0.1,0.50,"Chebychev::backgroundFail(mass, {cFail[0,-0.5,0.5], cFail2[0,-0.5,0.5]})");
        } else {
            fitInfo.DrawLatex(0.1,0.60,"CBShape::signal(mass, mean[3.1,3.0,3.2], sigma[0.05,0.01,0.1], alpha[1.0, 0.2, 3.0], n[1, 1.0, 100.])");
            fitInfo.DrawLatex(0.1,0.55,"Chebychev::backgroundPass(mass, {cPass[0,-0.5,0.5], cPass2[0,-0.5,0.5]})");
            fitInfo.DrawLatex(0.1,0.50,"Chebychev::backgroundFail(mass, {cFail[0,-0.5,0.5], cFail2[0,-0.5,0.5]})");
        }
        fitInfo.SetTextSize(0.04);
        fitInfo.DrawLatex(0.05,0.40,"Bin Information");
        fitInfo.SetTextSize(0.03);
        fitInfo.DrawLatex(0.1,0.30,"#eta : -2.4,-1.97,-1.72,-1.47,-1.22,-0.97,-0.72,0.47,0.22,0.03,0.28,0.53,0.78,1.03,1.46");
        fitInfo.DrawLatex(0.1,0.25,"p_{T} [GeV/c] : 6.5,7.5,8.5,9.5,11,14,30");
        c1 = (TCanvas *)tmp1->Clone();
        c1->Print(outname_mid);
        c1->Print(outfile_);

        TString mid_title = "Centrality : (" + middle_name2 + ")";
        TString leg_title = Cat2 + " " + Cat3 + " Efficiency (" + middle_name2 + ")";

        if(Mode < 1) {
            // pt
            for(int j = 0; j < ptBins; j++) {
                cout<<" dir_pt : "<<dir_pt<<", ptbins : "<<ptbins[j]<<", dir_suffix : "<<dir_suffix<<endl;
                TString tot_dir = dir_pt + ptbins[j] + dir_suffix;
                f->cd(tot_dir);
                cout<<" tot_dir : "<<tot_dir<<endl;
                TDirectory *root_dir = gDirectory;
                TIter rootnextkey( root_dir->GetListOfKeys() );
                root_dir->cd();
                TKey *rootkey;
                TCanvas *ctmp = new TCanvas();
                ctmp->cd();


                TLatex l;
                l.SetTextAlign(13);
                l.SetTextSize(0.06);
                l.DrawLatex(0.1,0.8,mid_title);
                l.DrawLatex(0.1,0.6,"Bin : ");
                l.SetTextSize(0.04);
                l.DrawLatex(0.1,0.5,tot_dir);
                ctmp->Update();
                c1 = (TCanvas *)ctmp->Clone();
                c1->Print(outname_mid);
                c1->Print(outfile_);

                while( rootkey = (TKey*)rootnextkey() )
                {
                    TObject *rootobj = rootkey->ReadObj();
                    TDirectory *rdir = gDirectory;
                    TIter rdirnextkey(rdir->GetListOfKeys());
                    rdir->cd();
                    TKey *dir_key;
                    while( dir_key = (TKey*)rdirnextkey())
                    {
                        if (rootobj->IsA()->InheritsFrom("TCanvas")) {
                            c1 = (TCanvas *)rootobj;
                            c1->Print(outname_mid);
                            c1->Print(outfile_);
                            cnt++;
                            cout<<"Count : "<<cnt<<endl;
                            if(cnt > 0) break;
                        }
                    }
                }
            }

            // eta
            for(int j = 0; j < etaBins; j++) {
                TString tot_dir = dir_eta + etabins[j] + dir_suffix;
                cout<<" tot_dir : "<<tot_dir<<endl;
                f->cd(tot_dir);
                TDirectory *root_dir = gDirectory;
                TIter rootnextkey( root_dir->GetListOfKeys() );
                root_dir->cd();
                TKey *rootkey;

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

                TLatex l;
                l.SetTextAlign(13);
                l.SetTextSize(0.06);
                l.DrawLatex(0.1,0.8,mid_title);
                l.DrawLatex(0.1,0.6,"Bin : ");
                l.SetTextSize(0.04);
                l.DrawLatex(0.1,0.5,tot_dir);
                ctmp->Update();
                c1 = (TCanvas *)ctmp->Clone();
                c1->Print(outname_mid);
                c1->Print(outfile_);

                while( rootkey = (TKey*)rootnextkey() )
                {
                    TObject *rootobj = rootkey->ReadObj();
                    TDirectory *rdir = gDirectory;
                    TIter rdirnextkey(rdir->GetListOfKeys());
                    rdir->cd();
                    TKey *dir_key;
                    while( dir_key = (TKey*)rdirnextkey())
                    {
                        if (rootobj->IsA()->InheritsFrom("TCanvas")) {
                            c1 = (TCanvas *)rootobj;
                            c1->Print(outname_mid);
                            c1->Print(outfile_);
                            cnt++;
                            cout<<"Count : "<<cnt<<endl;
                            if(cnt > 0) break;
                        }
                    }
                }
            }
        }

        tot_dir = intg + dir_suffix;
        f->cd(tot_dir);
        cout<<" tot_dir : "<<tot_dir<<endl;
        TDirectory *root_dir = gDirectory;
        TIter rootnextkey( root_dir->GetListOfKeys() );
        root_dir->cd();
        TKey *rootkey;
        TCanvas *ctmp = new TCanvas();
        ctmp->cd();


        TLatex l;
        l.SetTextAlign(13);
        l.SetTextSize(0.06);
        l.DrawLatex(0.1,0.8,mid_title);
        l.DrawLatex(0.1,0.6,"Bin : ");
        l.SetTextSize(0.04);
        l.DrawLatex(0.1,0.5,tot_dir);
        ctmp->Update();
        c1 = (TCanvas *)ctmp->Clone();
        c1->Print(outname_mid);
        c1->Print(outfile_);

        while( rootkey = (TKey*)rootnextkey() )
        {
            TObject *rootobj = rootkey->ReadObj();
            TDirectory *rdir = gDirectory;
            TIter rdirnextkey(rdir->GetListOfKeys());
            rdir->cd();
            TKey *dir_key;
            while( dir_key = (TKey*)rdirnextkey())
            {
                if (rootobj->IsA()->InheritsFrom("TCanvas")) {
                    c1 = (TCanvas *)rootobj;
                    c1->Print(outname_mid);
                    c1->Print(outfile_);
                    cnt++;
                    cout<<"Count : "<<cnt<<endl;
                    if(cnt > 0) break;
                }
            }
        }
    }
    c1->Print(outname_out);
    TString out2 = outfile_ + "]";
    c1->Print(out2);


}
/*************************************************************************************
 * getYields: Goes through each Counts histogram for every process and subprocess
 *            (i.e., EE & Drell-Yan, E & WJets, etc.) and properly adds the yields
 *            for data and MC. Reports ratios of Data:MC as well.
 *  input:  the main() arguments array
 *  output: writes to stdout the LaTeX-formatted table of yields (pipe the output to 
 *          save)
 ***********************************/
void getYields(const char* argv[]) { 
  //open mlbwidth output file
  TFile *f = new TFile(argv[2]);
  f->cd();

  //very inefficient, but for now it works
  //loop over all procs, leps and figure out the event counts
  for(int i=0; i<lepsSize; i++) {
    char a[128];
    sprintf(a, "mlbwa_%s_Count", leps[i]);
    TDirectory *tDir = (TDirectory*) f->Get(a);
    TList *alok = tDir->GetListOfKeys();

    for(int j=0; j<procsSize; j++) {
      for(int k=0; alok->At(k)->GetName() != alok->Last()->GetName(); k++) {
        if(TString(alok->At(k)->GetName()).Contains(TRegexp(procs[j]))) {
          char b[128];
          sprintf(b, "mlbwa_%s_Count/%s", leps[i], alok->At(k)->GetName());

          TH1F *h = (TH1F*) f->Get(b);
          eCounts[i][j] += h->GetSumOfWeights();
          eErrors[i][j] =  sqrt(pow(eErrors[i][j],2) + pow(h->GetBinError(2),2));

          delete h;
        }
      }
    }

    char d[128];
    sprintf(d, "mlbwa_%s_Count/%s", leps[i], alok->Last()->GetName());
    if(d == "") { exit(EXIT_FAILURE); }

    TH1F *tth = (TH1F*) f->Get(d);
    eCounts[i][procsSize] = tth->GetEntries();
    double integral = tth->GetSumOfWeights();
    eErrors[i][procsSize] = tth->GetBinError(2)*eCounts[i][procsSize]/integral;
    delete tth;
  }

  //Get a string to tell us how many columns we want (size leps + 1)
  char cols[] = "c";
  for(int i=0; i<lepsSize; i++) {
    strcat(cols, "c");
  }

  //print out LaTeX:
  //formatting
  cout<<"\\documentclass[12pt,a4paper,titlepage]{article}"<<endl;
  cout<<"\\usepackage[utf8]{inputenc}"<<endl;
  cout<<"\\usepackage{amsmath}"<<endl;
  cout<<"\\usepackage{amsfonts}"<<endl;
  cout<<"\\usepackage{amssymb}"<<endl;
  cout<<"\\usepackage{hyperref}\n\n"<<endl;
  cout<<"\\usepackage[margin=0.0025in]{geometry}"<<endl;
  cout<<"\\begin{document}"<<endl;
  cout<<"\\begin{tabular}{l|"<<cols<<"} \\\\"<<endl;

  //Print out the table header
  cout<<"Sample & ";
  for(int i=0; i<lepsLaTeXSize; i++) {
    cout<<lepsLaTeX[i]<<" & ";
  }
  cout<<"Sum \\\\ \\hline\\hline"<<endl;

  //Printing out the yields for each process
  for(int i=0; i<procsSize; i++) {
      cout<<yieldLaTeX[i]<<" & ";
    for(int j=0; j<lepsSize; j++) {
      cout<<GetLatex(j,i)<<" & ";
    }
    cout<<GetLatexSum(true,i)<<"\\\\"<<(i==procsSize-1 ? "\\hline" : "")<<endl;
  }
 
  //Print out the total MC yield
  cout<<"Total MC & ";
  for(int i=0; i<lepsSize; i++) {
    cout<<GetLatexSum(false,i)<<" & ";
  }
  cout<<GetLatexSum(false,-1)<<"\\\\"<<endl;

  //Print out the data yield
  cout<<"Data & ";
  for(int i=0; i<lepsSize; i++) {
    cout<<GetLatex(i,lepsSize+1)<<" & ";
  }
  cout<<GetLatexSum(true,lepsSize+1)<<"\\\\\\hline\\hline"<<endl;
  
  //Print out the data:MC ratio
  cout<<"Data/MC & ";
  for(int i=1; i<=procsSize;i++) {
    cout<<GetLatexRatio(i)<<(i==procsSize ? "" : " & ");
  }
  cout<<"\\\\"<<endl;

  //We did it! End the document
  cout<<"\\end{tabular}"<<endl;
  cout<<"\\end{document}"<<endl;
}
/*************************************************************************************
 * createMFOutfile: moves the MLB distributions into an output file for use in 
 *                  R. Nally's MassFit.C code.
 *  input:  the main() arguments array
 *  output: writes to an output file the histograms, in a MassFit.C-readable format 
 *
 *  Structure-wise: can be implemented into class easily.
 ***********************************/
void createMFOutfile(const char* argv[]) {
  TFile *f = new TFile(argv[2]);

  //create the output file we'd like to write histograms to
  TFile *output = new TFile(outfileName, "RECREATE");
  
  //get the filesystem information from the file
  f->cd();
  TList *alokDirs = (TList*) f->GetListOfKeys();

  //create a list of "All" histograms and initialize (TODO)
  TList *allHists = new TList;

  //loop through the directories in the input file
  for(int idir=0; alokDirs->At(idir-1) != alokDirs->Last(); idir++) {
    //if it's not mlb, we don't care
    if(!TString(alokDirs->At(idir)->GetName()).Contains("_Mlb")) continue;
    
    //get the file directory information, its histograms
    TDirectory *cDir  = (TDirectory*) f->Get(alokDirs->At(idir)->GetName());
    TList *alokHistos = (TList*)      cDir->GetListOfKeys();

    //loop through the histograms in the current directory 
    for(int ihisto=0; alokHistos->At(ihisto-1) != alokHistos->Last(); ihisto++) {
      // don't consider the graph objects
      if(TString(alokHistos->At(ihisto)->GetName()).Contains("Graph_")) continue; 

      // clone the histogram, give it a new name
      TString cloneName = formatName(alokHistos->At(ihisto)->GetName(),nominalWidth);
      TH1F *thisto = (TH1F*) cDir->Get(alokHistos->At(ihisto)->GetName());
      TH1F *tclone = (TH1F*) thisto->Clone(cloneName);

      // open the outfile and write the histo in
      output->cd();
      TList *outkeys = (TList*) output->GetListOfKeys();

      // if the histogram already exists, add thisto to the existing one
      // messy, but removes the need for magic
      for(int iout=0; outkeys->At(iout-1) != outkeys->Last(); iout++) {
        if(outkeys->At(iout)->GetName() == cloneName) {
          cout<<" - found another histogram in output with name "<<cloneName<<endl;
          TH1F *theHisto = (TH1F*) output->Get(cloneName);
          cout<<" - got the same histogram from the output file"<<endl;
          TH1F *tHclone  = (TH1F*) theHisto->Clone(cloneName);
          cout<<" - cloned the histogram"<<endl;

          cout<<" - adding in clone"<<endl;
          tclone->Add(tHclone);

          cout<<" - deleting the original histogram from the output file"<<endl;
          output->Delete(cloneName + TString(";1"));
          cout<<" - deleted thing from output file"<<endl;
          cout<<" - tclone looks like "<<tclone<<endl;
        }
      }
      cout<<" - writing the tclone to file"<<endl;
      tclone->Write();

      // reopen the input root file and clean up
      f->cd();
      delete thisto;
      delete tclone;
    }
  }

  f->Close();
  output->cd();
  output->Close();

  // if we want to interpolate, start making more histograms
  if(interpolate) {
    // Have to reopen the outfile because ROOT is odd
    TFile *output2 = new TFile(outfileName, "UPDATE");
    output2->cd();

    std::pair<double,TString> maxPair = *moreFiles.begin();
    double maxWidth = maxPair.first;

    // check that it makes sense to interpolate with our settings
    if(maxWidth <= nominalWidth) {
      cout<<"\n\nERROR: Max width is less than or equal to the nominal width! Exiting."<<endl;
      exit(EXIT_FAILURE);
    }

    // open the input file and loop through the relevant directories
    TFile *maxFile = new TFile(maxPair.second);
    for(int i=0; i<lepsSize; i++) {
      // change directory and get the name of the folder we want to access
      maxFile->cd();
      char a[128];
      sprintf(a, "mlbwa_%s_Mlb", leps[i]);
      TDirectory *tDir = (TDirectory*) maxFile->Get(a);
      TList *alok = tDir->GetListOfKeys();

      // get the maxWidth histogram in this folder, clone and rename it
      TString maxHName = alok->First()->GetName();
      TString maxCloneName = formatName(maxHName, maxWidth);
      TH1F *maxHisto = (TH1F*) tDir->Get(maxHName);
      TH1F *maxClone = (TH1F*) maxHisto->Clone(maxCloneName);

      // write this max histogram to the outfile
      output2->cd();
      maxClone->Write();

      // get the corresponding nominal histogram from the outfile
      TH1F *nomHisto = (TH1F*) output2->Get(formatName(maxHName,nominalWidth));

      TCanvas *c = new TCanvas("");
      nomHisto->Draw();
      c->SaveAs(formatName(maxHName,nominalWidth)+TString(".pdf"));


      // for each interpolation, create a morphed histogram and write to outfile
      for(int i=interpolations; i>0; i--) {
        double tWidth = nominalWidth + i*(maxWidth - nominalWidth)/(interpolations+1);
        TString interpName = formatName(maxHName, tWidth);
        TH1F *interpHisto = (TH1F*) th1fmorph(interpName, interpName,nomHisto,maxHisto,
                                               nominalWidth,maxWidth,tWidth,nomHisto->Integral(),1);
        interpHisto->Write();
      }
    }

    maxFile->cd();
    maxFile->Close();
    output2->cd();
    output2->Close();

    // Otherwise, we want to collect signal histograms of different weights
  } else {
    // Have to reopen the outfile because ROOT is odd
    TFile *output2 = new TFile(outfileName, "UPDATE");
    output2->cd();

    // Loop through the additional files
    for(std::vector<std::pair<double, TString> >::const_iterator pf=moreFiles.begin();
                                                                 pf!=moreFiles.end();
                                                                 pf++) {

        // This is the current file and width
        TFile *curFile = new TFile(pf->second, "READ");
        double curWid  = pf->first;

        // Loop through lepton final states
        for(int i=0; i<lepsSize; i++) {
            curFile->cd();

            // Get the desired directory
            char dirName[128];
            sprintf(dirName, "mlbwa_%s_Mlb", leps[i]);
            TDirectory *curDir = (TDirectory*) curFile->Get(dirName);

            // Get the names of the first histogram in the directory
            //     (we don't want more than one additional signal histo per extra file)
            // Format it with the usual method
            TString histName   = TString(curDir->GetListOfKeys()->First()->GetName());
            TString cloneName  = formatName(histName,curWid);
            
            // Get the mlb histo
            TH1D *curHisto = (TH1D*) curDir->Get(histName)->Clone(cloneName);

            // Write to the outfile
            output2->cd();
            curHisto->Write();
        }

        curFile->Close();
    }

    output2->cd();
    output2->Close();
  }

}
Exemplo n.º 19
0
// input: - Input file (result from TMVA)
//        - use of TMVA plotting TStyle
void deviations( TString fin = "TMVAReg.root", 
                 HistType htype = MVAType, Bool_t showTarget, Bool_t useTMVAStyle = kTRUE )
{
   // set style and remove existing canvas'
   TMVAGlob::Initialize( useTMVAStyle );
   gStyle->SetNumberContours(999);

   // switches
   const Bool_t Save_Images     = kTRUE;

   // checks if file with name "fin" is already open, and if not opens one
   TFile* file = TMVAGlob::OpenFile( fin );  

   // define Canvas layout here!
   Int_t xPad = 1; // no of plots in x
   Int_t yPad = 1; // no of plots in y
   Int_t noPad = xPad * yPad ; 
   const Int_t width = 650;   // size of canvas

   // this defines how many canvases we need
   TCanvas* c[100];

   // counter variables
   Int_t countCanvas = 0;

   // search for the right histograms in full list of keys
   //    TList* methods = new TMap();

   TIter next(file->GetListOfKeys());
   TKey *key(0);   
   while ((key = (TKey*)next())) {

      if (!TString(key->GetName()).BeginsWith("Method_")) continue;
      if (!gROOT->GetClass(key->GetClassName())->InheritsFrom("TDirectory")) continue;

      TString methodName;
      TMVAGlob::GetMethodName(methodName,key);
      cout << "--- Plotting deviation for method: " << methodName << endl;

      TObjString *mN  = new TObjString( methodName );
      TDirectory* mDir = (TDirectory*)key->ReadObj();

      TList* jobNames = new TList();

      TIter keyIt(mDir->GetListOfKeys());
      TKey *titkey;
      while ((titkey = (TKey*)keyIt())) {

         if (!gROOT->GetClass(titkey->GetClassName())->InheritsFrom("TDirectory")) continue;

         TDirectory *titDir = (TDirectory *)titkey->ReadObj();

         TObjString *jN = new TObjString( titDir->GetName() );
         if (!jobNames->Contains( jN )) jobNames->Add( jN );
         else delete jN;
	    
         TString methodTitle;
         TMVAGlob::GetMethodTitle(methodTitle,titDir);

         TString hname = "MVA_" + methodTitle;
         TIter   dirKeyIt( titDir->GetListOfKeys() );
         TKey*   dirKey;

         Int_t countPlots = 0;
         while ((dirKey = (TKey*)dirKeyIt())){
            if (dirKey->ReadObj()->InheritsFrom("TH2F")) {
               TString s(dirKey->ReadObj()->GetName());
               if (s.Contains("_reg_") && 
                   ( (showTarget && s.Contains("_tgt")) || (!showTarget && !s.Contains("_tgt")) ) && 
                   s.Contains( (htype == CompareType ? "train" : "test" ))) {
                  c[countCanvas] = new TCanvas( Form("canvas%d", countCanvas+1), 
                                                Form( "Regression output deviation versus %s for method: %s",
                                                      (showTarget ? "target" : "input variables"), methodName.Data() ),
                                                countCanvas*50+100, (countCanvas+1)*20, width, (Int_t)width*0.72 ); 
                  c[countCanvas]->SetRightMargin(0.10); // leave space for border
                  TH1* h = (TH1*)dirKey->ReadObj();
                  h->SetTitle( Form("Output deviation for method: %s (%s sample)", 
                                    hname.Data(), (htype == CompareType ? "training" : "test" )) );
                  //                                    methodName.Data(), (htype == CompareType ? "training" : "test" )) );
                  h->Draw("colz");
                  TLine* l = new TLine( h->GetXaxis()->GetXmin(), 0, h->GetXaxis()->GetXmax(), 0 );
                  l->SetLineStyle(2);
                  l->Draw();

                  // update and print
                  cout << "plotting logo" << endl;
                  TMVAGlob::plot_logo(1.058);
                  c[countCanvas]->Update();

                  TString fname = Form( "plots/deviation_%s_%s_%s_c%i", 
                                        methodName.Data(), 
                                        (showTarget ? "target" : "vars"),
                                        (htype == CompareType ? "training" : "test" ), countPlots );
                  TMVAGlob::imgconv( c[countCanvas], fname );

                  countPlots++;
                  countCanvas++;
               }
            }
         }         
      }
   }
}
Exemplo n.º 20
0
prepDataFiles(){
//	TDirectory *theDr = (TDirectory*) myFile->Get("eleIDdir");///denom_pt/fit_eff_plots");
	//theDr->ls();
	int myIndex;	
	
	TSystemDirectory dir(thePath, thePath);
	TSystemFile *file;
	TString fname;
	TIter next(dir.GetListOfFiles());
	while ((file=(TSystemFile*)next())) {
		fname = file->GetName();
		if (fname.BeginsWith("TnP")&& fname.Contains("mc")) {
	
			ofstream myfile;

			TFile *myFile = new TFile(fname);
			TIter nextkey(myFile->GetListOfKeys());
			TKey *key;
			while (key = (TKey*)nextkey()) {
				TString theTypeClasse = key->GetClassName();
				TString theNomClasse = key->GetTitle();
				if ( theTypeClasse == "TDirectoryFile"){
					TDirectory *theDr = (TDirectory*) myFile->Get(theNomClasse);
					TIter nextkey2(theDr->GetListOfKeys());
					TKey *key2;
					while (key2 = (TKey*)nextkey2()) {
						TString theTypeClasse2 = key2->GetClassName();
						TString theNomClasse2 = key2->GetTitle();	
						myfile.open (theNomClasse2+".info");
						if ( theTypeClasse == "TDirectoryFile"){
							cout << "avant " << endl;
							TDirectory *theDr2 = (TDirectory*) myFile->Get(theNomClasse+"/"+theNomClasse2);
							cout << "apres " << endl;
							TIter nextkey3(theDr2->GetListOfKeys());
							TKey *key3;
							while (key3 = (TKey*)nextkey3()) {
								TString theTypeClasse3 = key3->GetClassName();
								TString theNomClasse3 = key3->GetTitle();	
								if ((theNomClasse3.Contains("FromMC"))) {

									TString localClasse3 = theNomClasse3;
									localClasse3.ReplaceAll("__","%");
									cout << "apres " << localClasse3 << endl;
									TObjArray* listBin = localClasse3.Tokenize('%');
									TString first = ((TObjString*)listBin->At(0))->GetString();
									TString second = ((TObjString*)listBin->At(2))->GetString();
									myfile << first;
									myfile << " " << second << " ";
									cout << "coucou la on va récupérer le rooFitResult " << endl;

									RooFitResult *theResults = (RooFitResult*) myFile->Get(theNomClasse+"/"+theNomClasse2+"/"+theNomClasse3+"/fitresults");
									theResults->Print();
									RooArgList theParam = theResults->floatParsFinal();
									int taille = theParam.getSize();
									for (int m = 0 ; m < taille ; m++){
										cout << "m=" << m << endl;
									RooAbsArg *theArg = (RooAbsArg*) theParam.at(m);
									RooAbsReal *theReal = (RooAbsReal*) theArg;
										myfile << theReal->getVal() << " " ;
									}		
															
									myfile << "\n";

								}
							}
						}
						myfile.close();

					}
			
				}
			}
			delete myFile;
		}
	
	}

}
Exemplo n.º 21
0
void DrawAllHistos(TString filename,Bool_t isMC,TString format){
  
  //  setTDRStyle("logredblue");

  std::vector<TH1F*> h1vec;
  std::vector<TH2F*> h2vec;
  
  h1vec.clear();
  h2vec.clear();

  TFile *file = TFile::Open(filename);

  // to get the names of the conditions
  TObjArray *conditions_from_name = filename.Tokenize("_"); 
  TString sa = conditions_from_name->At(1)->GetName();
  TString sb = conditions_from_name->At(3)->GetName();
  sb.ReplaceAll(".root","");

  file->cd();
  
  TDirectory *stardir = gDirectory;
  TObject *thesourcedir;
  TIter nextdir(stardir->GetListOfKeys());

  while((thesourcedir=nextdir())){
    
    TString dirName = thesourcedir->GetName();
    
    stardir->cd(dirName);
    TDirectory *current_sourcedir = gDirectory;
    TH1::AddDirectory(kFALSE);

    std::cout << "*************************" <<std::endl;
    std::cout << "Reading Directory: " << dirName <<std::endl;
    
    TObject *obj;
    TIter next(current_sourcedir->GetListOfKeys());

    while ((obj=next())) {
      
      TString objName =obj->GetName();

      if(objName.Contains("pfx")) continue;

      if (objName.Contains("h2") && !objName.Contains("pfx")) {

	//std::cout << "Reading: " << obj->GetName() <<std::endl;

	TH2F* h2 = (TH2F*)file->Get(dirName+"/"+objName);
	h2->SetName(objName+dirName);
	h2vec.push_back(h2);

	TCanvas *c = new TCanvas(h2->GetName(),h2->GetName(),800,600);
	c->cd();
	gPad->SetTopMargin(0.08);
	gPad->SetRightMargin(0.15);
	h2->SetStats(kFALSE);
	h2->Draw("colz");
	c->Draw();
	
	c->cd();
	TProfile *hpfx_tmp = (TProfile*) h2->ProfileX("_pfx",1,-1,"o");
	hpfx_tmp->SetStats(kFALSE);
	//hpfx_tmp->SetMarkerColor(kBlack);
	hpfx_tmp->SetMarkerColor(kRed);
	hpfx_tmp->SetMarkerSize(1.2); 
	hpfx_tmp->SetMarkerStyle(20); 
	hpfx_tmp->Draw("psame");
	
	c->Draw();
	cmsPrel(60.,sa,sb, isMC);
	
	TString canvName = h2->GetName();
	c->cd()->SetLogz();
	c->SaveAs(canvName+"."+format);
	  
      } else { 
	
	TH1F* h1 = (TH1F*)file->Get(dirName+"/"+objName);
	h1->SetName(objName+dirName);
	h1vec.push_back(h1);
	
	TCanvas *c = new TCanvas(h1->GetName(),h1->GetName(),600,600);
	c->cd()->SetLogy();
	
	h1->SetMarkerColor(kBlack);
	h1->SetMarkerStyle(20);
	h1->SetLineWidth(1.5); 
	h1->SetFillColor(393);
	//h1->SetFillStyle(3005);
	h1->Draw("hist");
	h1->Draw("e1same");
	c->Draw();
	
	TObject    *statObj;
	TPaveStats *stats;
  
	statObj = h1->GetListOfFunctions()->FindObject("stats");
	stats= static_cast<TPaveStats*>(statObj);
	stats->SetFillColor(10);
	stats->SetLineWidth(1);
	stats->SetShadowColor(0);
	stats->SetTextFont(42);
	stats->SetTextSize(0.025);
	//stats->SetLineColor(LineColors);
	//stats->SetTextColor(LineColors);
	stats->SetX1NDC(0.75);
	stats->SetY1NDC(0.72);
	stats->SetX2NDC(0.97);
	stats->SetY2NDC(0.92);
	stats->Draw("same"); 
		
	cmsPrel(60.,sa,sb,isMC);
	TString canvName = h1->GetName();
	c->SaveAs(canvName+"."+format);
       	
      }
    }
  }
}
Exemplo n.º 22
0
void plotauto(TString infilename) {

  TString plname = infilename+".ps";
  TCanvas* cc = new TCanvas("validate","validate",500,370);
  cc->Print(plname+"[");

  TText tt;
  tt.SetTextColor(2);
  tt.SetTextSize(0.02);

  gStyle->SetMarkerSize(0.1);
  gStyle->SetTitleSize(0.15,"ff");
  gStyle->SetTitleTextColor(4);

  std::vector < TString > vnames;
  vnames.push_back("Sim_HitEn");
  vnames.push_back("Sim_HitTime");
  vnames.push_back("Sim_posXY");
  vnames.push_back("Sim_posXZ");
  vnames.push_back("Sim_posYZ");
  vnames.push_back("Sim_posRZ");

  std::vector <TString> exts;
  exts.push_back("");
  exts.push_back("_posZ");
  exts.push_back("_negZ");

  TH1F* h;
  TH2F* hh;
  TKey *key;
  TIter next;
  TKey *key2;
  TIter next2;

  TFile* infile = new TFile(infilename, "read");

  // overall geometry
  TDirectory* td = (TDirectory*) infile->Get("ALLCollections");
  cc->Clear();
  cc->Divide(3,3);
  cc->cd(1);
  hh = (TH2F*) td->Get("ALLCollections_overallhitZR");
  hh->Draw("box");
  cc->cd(2);
  int icol=1;
  bool first=true;
  TLegend* tl = new TLegend(0., 0., 1, 1);
  next = td->GetListOfKeys();
  while ((key = (TKey*)next())) {
    TClass *cll = gROOT->GetClass(key->GetClassName());
    if (cll->InheritsFrom("TH2F")) {
      hh = (TH2F*)key->ReadObj();
      TString hn = hh->GetName();
      if ( hn.Contains("ALL") ) continue;
      if ( hn.Contains("_Log") ) continue;
      hh->SetLineColor(icol);
      if ( first ) {hh->Draw("box"); first=false;}
      else hh->Draw("same;box");
      icol++;
      if (icol==10) icol=1;
      TString ss = hn.ReplaceAll( "_overallhitZR", "");
      tl->AddEntry(hh, ss , "l");
    }
  }
  // the legend
  cc->cd(3);
  tl->Draw();

  cc->cd(4);
  hh = (TH2F*) td->Get("ALLCollections_Log_overallhitZR");
  hh->Draw("box");
  cc->cd(5);
  icol=1;
  first=true;
  next = td->GetListOfKeys();
  while ((key = (TKey*)next())) {
    TClass *cll = gROOT->GetClass(key->GetClassName());
    if (cll->InheritsFrom("TH2F")) {
      hh = (TH2F*)key->ReadObj();
      TString hn = hh->GetName();
      if ( hn.Contains("ALL" ) ) continue;
      if ( ! hn.Contains("_Log_") ) continue;
      hh->SetLineColor(icol);
      if ( first ) {hh->Draw("box"); first=false;}
      else hh->Draw("same;box");
      icol++;
      if (icol==10) icol=1;
    }
  }

  cc->cd(7);
  hh = (TH2F*) td->Get("ALLCollections_LogLog_overallhitZR");
  hh->Draw("box");
  cc->cd(8);
  icol=1;
  first=true;
  next = td->GetListOfKeys();
  while ((key = (TKey*)next())) {
    TClass *cll = gROOT->GetClass(key->GetClassName());
    if (cll->InheritsFrom("TH2F")) {
      hh = (TH2F*)key->ReadObj();
      TString hn = hh->GetName();
      if ( hn.Contains("ALL" ) ) continue;
      if ( ! hn.Contains("_LogLog_") ) continue;
      hh->SetLineColor(icol);
      if ( first ) {hh->Draw("box"); first=false;}
      else hh->Draw("same;box");
      icol++;
      if (icol==10) icol=1;
    }
  }


  cc->Print(plname);

  // now collection-by-collection

  next = infile->GetListOfKeys();
  while ((key = (TKey*)next())) {
    TClass *cll = gROOT->GetClass(key->GetClassName());
    if (cll->InheritsFrom("TDirectory")) {
      td = (TDirectory*)key->ReadObj();
      TString dirname = td->GetName();
      if ( dirname=="ALLCollections" ) continue;

      // is it an endcap collection?
      bool isEndcap = td->Get(dirname+"_hitXY_posZ");

      // first overall geometry
      cc->Clear();
      cc->Divide(3,2);

	cc->cd(1);
	( (TH2F*) td->Get(dirname+"_hitEn"))->Draw("box");
	cc->cd(4)->SetLogy();
	( (TH2F*) td->Get(dirname+"_hitTime"))->Draw("box");

      if ( isEndcap ) {
	cc->cd(2);
	( (TH2F*) td->Get(dirname+"_hitXY_posZ"))->Draw("box");
	cc->cd(3);
	( (TH2F*) td->Get(dirname+"_hitXY_negZ"))->Draw("box");
	cc->cd(5);
	((TH2F*) td->Get(dirname+"_hitZR_posZ"))->Draw("box");
	cc->cd(6);
	((TH2F*) td->Get(dirname+"_hitZR_negZ"))->Draw("box");
      } else {
	cc->cd(2);
	( (TH2F*) td->Get(dirname+"_hitXY"))->Draw("box");
	cc->cd(3);
	( (TH2F*) td->Get(dirname+"_hitZR"))->Draw("box");
      }

      cc->Print(plname);


      // then the cell indices

      // work out how many indices/variables we're dealing with
      std::vector < TString > indices;
      std::vector < TString > variables;
      next2 = td->GetListOfKeys();
      while ((key2 = (TKey*)next2())) {
	cll = gROOT->GetClass(key2->GetClassName());
	if (cll->InheritsFrom("TH2F")) {
	  hh = (TH2F*) key2->ReadObj();
	  TString hn = hh->GetName();
	  if ( hn.Contains("Indx") ) {
	    TString ss = hn.ReplaceAll(dirname+"_", "");
	    TString asas = ((TObjString*) (ss.Tokenize("_") -> At(0)))->GetString();
	    if ( find( indices.begin(), indices.end(), asas )==indices.end() ) indices.push_back(asas);
	    asas = ((TObjString*) (ss.Tokenize("_") -> At(1)))->GetString();
	    if ( find( variables.begin(), variables.end(), asas )==variables.end() ) variables.push_back(asas);
	  }
	}
      }

      if ( indices.size()==0 || variables.size()==0 ) continue;


      for (int inp=0; inp<2; inp++) {
	if ( !isEndcap && inp==1 ) continue;
	cc->Clear();
	cc->Divide(indices.size(), variables.size());
	int ic=1;
	next2 = td->GetListOfKeys();
	while ((key2 = (TKey*)next2())) {
	  cll = gROOT->GetClass(key2->GetClassName());
	  if (cll->InheritsFrom("TH2F")) {
	    hh = (TH2F*) key2->ReadObj();
	    TString hn = hh->GetName();
	    if ( isEndcap ) {
	      if      ( inp==0 && ! hn.Contains("posZ") ) continue;
	      else if ( inp==1 && ! hn.Contains("negZ") ) continue;
	    }
	    if ( hn.Contains("Indx") ) {
	      TString asas = ((TObjString*) (hn.Tokenize("_") -> At(1)))->GetString();
	      asas = asas(4,asas.Length());
	      cc->cd(ic++);
	      hh->Draw("box");
	    }
	  }
	}

	cc->cd();
	for ( size_t k=0; k<variables.size(); k++) {
	  tt.DrawTextNDC( 0.0, 0.9 - (1.0*k)/(variables.size()), variables[k] );
	}

	for ( size_t k=0; k<indices.size(); k++) {
	  tt.DrawTextNDC( 0.05 + (1.0*k)/(indices.size()), 0.02, indices[k].ReplaceAll("Indx","Indx_") );
	}

	tt.DrawTextNDC( 0.1, 0.99, dirname);
	if ( isEndcap ) {
	  if (inp==0 ) tt.DrawTextNDC( 0.35, 0.99, "posZ");
	  else         tt.DrawTextNDC( 0.35, 0.99, "negZ");
	}

	cc->Print(plname);
      }
    }
  }

  infile->Close();

  cc->Print(plname+"]");
}
void recupThePlots(){
//	TDirectory *theDr = (TDirectory*) myFile->Get("eleIDdir");///denom_pt/fit_eff_plots");
	//theDr->ls();
	cout << "coucou" << theOutFileName << endl;
	
	TFile *myOutFile = new TFile(theOutFileName,"RECREATE");
	
	TSystemDirectory dir(thePath, thePath);
	TSystemFile *file;
	TString fname;
	TIter next(dir.GetListOfFiles());
	while (((file=(TSystemFile*)next()))) {
		fname = file->GetName();
		if ((fname.BeginsWith("TnP"))&&fname.Contains("data")) {
                        cout <<  "--------------------"<< "\n";
                        cout << fname << "\n";
			TFile *myFile = new TFile(fname);
			TIter nextkey(myFile->GetListOfKeys());                   
			TKey *key;
			while ((key = (TKey*)nextkey())) {
                                // cout << key << "\n";
				TString theTypeClasse = key->GetClassName();
				TString theNomClasse = key->GetTitle();
                                   cout << "theTypeClasse:  "<< theTypeClasse << " ,  " << theNomClasse << "\n";
				if ( theTypeClasse == "TDirectoryFile" ){
                                        //    cout << "we are here 1" << "\n";
					TDirectory *theDr = (TDirectory*) myFile->Get(theNomClasse);
					TIter nextkey2(theDr->GetListOfKeys());
					TKey *key2;
					while ((key2 = (TKey*)nextkey2())) {
						TString theTypeClasse2 = key2->GetClassName();
						TString theNomClasse2 = key2->GetTitle();	
						if ( theTypeClasse == "TDirectoryFile" || theTypeClasse == "TGraphAsymmErrors" ){
							TDirectory *theDr2 = (TDirectory*) myFile->Get(theNomClasse+"/"+theNomClasse2+"/fit_eff_plots");
							TIter nextkey3(theDr2->GetListOfKeys());
							TKey *key3;
							while ((key3 = (TKey*)nextkey3())) {
								TString theTypeClasse3 = key3->GetClassName();
								TString theNomClasse3 = key3->GetName();	
				 				cout << "type = " << theTypeClasse3 << " nom = " << theNomClasse3 << endl;
						
								TCanvas *theCanvas = (TCanvas*) myFile->Get(theNomClasse+"/"+theNomClasse2+"/fit_eff_plots/"+theNomClasse3);
								TIter nextObject(theCanvas->GetListOfPrimitives());
								TObject *obj;
								while ((obj = (TObject*)nextObject())) {
									if (obj->InheritsFrom("TGraphAsymmErrors")) {
					        				cout << "histo: " << obj->GetName() << endl;
										myOutFile->cd();
										obj->Write(theNomClasse2+"_"+theNomClasse3);
										myFile->cd();
									}
									if (obj->InheritsFrom("TH2F")) {
										cout << "the TH2F = " << obj->GetName() << endl;
										myOutFile->cd();
										obj->Write(theNomClasse2+"_"+theNomClasse3);
										myFile->cd();
									}
								}
							}
						}

					}
			
				}
			}
			delete myFile;
		}
	
	}
	myOutFile->Close();

}
Exemplo n.º 24
0
recupTheZpeak(){
//	TDirectory *theDr = (TDirectory*) myFile->Get("eleIDdir");///denom_pt/fit_eff_plots");
	//theDr->ls();
	int myIndex;	
	
	TSystemDirectory dir(thePath, thePath);
	TSystemFile *file;
	TString fname;
	TIter next(dir.GetListOfFiles());
	while ((file=(TSystemFile*)next())) {
		fname = file->GetName();
		if (fname.BeginsWith("TnP")) {
			if (fname.Contains("data")) kind = "data";
			else kind = "mc";
			bool pass = false;
			for (int p = 0 ; p< nbOfIds ; p++){
				if (fname.Contains(thePlotToDraw[p])) {
					pass = true;				 
					theIndex = p;
					break;
				}
			}
			if (!(pass)) continue;
			TFile *myFile = new TFile(fname);
			TIter nextkey(myFile->GetListOfKeys());
			TKey *key;
			while (key = (TKey*)nextkey()) {
				TString theTypeClasse = key->GetClassName();
				TString theNomClasse = key->GetTitle();
				if ( theTypeClasse == "TDirectoryFile"){
					TDirectory *theDr = (TDirectory*) myFile->Get(theNomClasse);
					TIter nextkey2(theDr->GetListOfKeys());
					TKey *key2;
					while (key2 = (TKey*)nextkey2()) {
						TString theTypeClasse2 = key2->GetClassName();
						TString theNomClasse2 = key2->GetTitle();	
						if ( theTypeClasse == "TDirectoryFile"){
							TDirectory *theDr2 = (TDirectory*) myFile->Get(theNomClasse+"/"+theNomClasse2);
							TIter nextkey3(theDr2->GetListOfKeys());
							TKey *key3;
							while (key3 = (TKey*)nextkey3()) {
								TString theTypeClasse3 = key3->GetClassName();
								TString theNomClasse3 = key3->GetTitle();	
								if (((theNomClasse3.Contains("vpvPlusExpo"))||(theNomClasse3.Contains("higgsSF")))&&(!(theNomClasse3.Contains("all")))) {
									TCanvas *theCanvas = (TCanvas*) myFile->Get(theNomClasse+"/"+theNomClasse2+"/"+theNomClasse3+"/fit_canvas");
									theCanvas->Print(outputDir+"/"+kind+"_"+theName[theIndex]+"__"+theNomClasse3+".png");
									
								}
							}
						}

					}
			
				}
			}
			delete myFile;
		}
	
	}

}
Exemplo n.º 25
0
void readAllToysFromFile(TGraphErrors*tge, TFile*f, double d_quantile) {
	tge->Set(0);	
	if (!f) throw std::logic_error("Cannot use readHypoTestResult: option toysFile not specified, or input file empty");
	TDirectory *toyDir = f->GetDirectory("");
	if (!toyDir) throw std::logic_error("Cannot use readHypoTestResult: empty toy dir in input file empty");
	TIter next(toyDir->GetListOfKeys()); TKey *k;
	std::map<double, TTree*> gridCLsb; //r, <clsb, clserr>
	std::map<double, TTree*> gridCLb; //r, <clsb, clserr>
	std::map<double, double> gridQdata; //r, q_data
	bool bdata = false;
	while ((k = (TKey *) next()) != 0) {
		double rVal;
		TString name(k->GetName());
		if(name.BeginsWith("SAMPLING_SB_TESTED_R")){
			rVal = name.ReplaceAll("SAMPLING_SB_TESTED_R","").Atof();
			TTree *t = dynamic_cast<TTree *>(toyDir->Get(k->GetName()));
			gridCLsb[rVal]=t;
			if (_debug > 2) std::cout << "  Do " << k->GetName() << " -> " << name << " --> " << rVal << " tsb->entries= "<<t->GetEntries()<< std::endl;
		}else if(name.BeginsWith("SAMPLING_B_TESTED_R")){
			rVal = name.ReplaceAll("SAMPLING_B_TESTED_R","").Atof();
			TTree *t = dynamic_cast<TTree *>(toyDir->Get(k->GetName()));
			gridCLb[rVal]=t;
			if (_debug > 2) std::cout << "  Do " << k->GetName() << " -> " << name << " --> " << rVal << " tb->entries= "<<t->GetEntries()<< std::endl;
		}else if(name.BeginsWith("DATA_R")){
			name.ReplaceAll("DATA_R","");
			TString tmp = name;
			rVal = tmp.Remove(tmp.Index("_"), tmp.Length()).Atof();
			name.Remove(0,name.Index("_Q")+2);
			gridQdata[rVal]=name.Atof();
			if (_debug > 2) std::cout << "  Do " << k->GetName() << " -> " << tmp << " --> " << rVal << " Q_data ="<<name<<" --> "<<name.Atof()<< std::endl;
			bdata = true;
		}else if(!bdata && name.BeginsWith("TESTED_R")){
			rVal = name.ReplaceAll("TESTED_R","").Atof();
			TTree *t = dynamic_cast<TTree *>(toyDir->Get(k->GetName()));
			if(t!=NULL) {
				TBranch *brQ;
				double q;
				t->SetBranchAddress("brT", &q, &brQ);
				t->GetEntry(0);
				gridQdata[rVal]=q;
				if (_debug > 2) std::cout << "  Do " << k->GetName() << " -> " << name << " --> " << rVal << " Q_data ="<<q<< std::endl;
			}
		}


	}

	int i = 0, n = gridCLsb.size();
	if(_debug)cout<<" grid size = "<<n<<endl;
	int n_valid = 0;
	for (std::map<double, TTree *>::iterator itg = gridCLsb.begin(), edg = gridCLsb.end(); itg != edg; ++itg) {
		double cls, clserr;
		GetCLs(gridQdata[itg->first], itg->second, gridCLb[itg->first], cls, clserr, d_quantile);
		//if(itg->first != 1.74 && itg->first != 1.95) continue;
		if(cls!=1 and clserr==0)continue;
		if(cls>0.9) continue;
		if(cls<0.0001) continue;
		if(clserr>=cls)continue;

		if( scanRmin >= 0 && itg->first < scanRmin ) continue; 
		if( scanRmax >= 0 && itg->first > scanRmax ) continue; 

		n_valid+=1;
		tge->Set(n_valid);
		tge->SetPoint(     n_valid-1, itg->first, cls   ); 
		tge->SetPointError(n_valid-1, 0,          clserr);
		if(_debug)cout<<" input grid:  r="<<itg->first<<" cls="<<cls<<"+/-"<<clserr<<endl;
		i++;
	}
	if(_debug)cout<<"tge->N = "<<tge->GetN()<<endl;
}
Exemplo n.º 26
0
TString* get_var_names( Int_t nVars )
{
   const TString directories[6] = { "InputVariables_NoTransform",
                                    "InputVariables_DecorrTransform",
                                    "InputVariables_PCATransform",
				    "InputVariables_Id",
				    "InputVariables_Norm",
				    "InputVariables_Deco"};

   TDirectory* dir = 0;
   for (Int_t i=0; i<6; i++) {
      dir = (TDirectory*)Network_GFile->Get( directories[i] );
      if (dir != 0) break;
   }
   if (dir==0) {
      cout << "*** Big troubles in macro \"network.C\": could not find directory for input variables, "
           << "and hence could not determine variable names --> abort" << endl;
      return 0;
   }
   cout << "--> go into directory: " << dir->GetName() << endl;
   dir->cd();

   TString* vars = new TString[nVars];
   Int_t ivar = 0;

   // loop over all objects in directory
   TIter next(dir->GetListOfKeys());
   TKey* key = 0;
   while ((key = (TKey*)next())) {
      if (key->GetCycle() != 1) continue;

      if(!TString(key->GetName()).Contains("__S") &&
	 !TString(key->GetName()).Contains("__r")) continue;

      // make sure, that we only look at histograms
      TClass *cl = gROOT->GetClass(key->GetClassName());
      if (!cl->InheritsFrom("TH1")) continue;
      TH1 *sig = (TH1*)key->ReadObj();
      TString hname = sig->GetTitle();
      
      vars[ivar] = hname; ivar++;

      if (ivar > nVars-1) break;
   }      
   
   if (ivar != nVars-1) { // bias layer is also in nVars counts
      cout << "*** Troubles in \"network.C\": did not reproduce correct number of "
           << "input variables: " << ivar << " != " << nVars << endl;
   }

   return vars;

   // ------------- old way (not good) -------------

   //    TString fname = "weights/TMVAnalysis_MLP.weights.txt";
   //    ifstream fin( fname );
   //    if (!fin.good( )) { // file not found --> Error
   //       cout << "Error opening " << fname << endl;
   //       exit(1);
   //    }
   
   //    Int_t   idummy;
   //    Float_t fdummy;
   //    TString dummy = "";
   
   //    // file header with name
   //    while (!dummy.Contains("#VAR")) fin >> dummy;
   //    fin >> dummy >> dummy >> dummy; // the rest of header line
   
   //    // number of variables
   //    fin >> dummy >> idummy;
   //    // at this point, we should have idummy == nVars
   
   //    // variable mins and maxes
   //    TString* vars = new TString[nVars];
   //    for (Int_t i = 0; i < idummy; i++) fin >> vars[i] >> dummy >> dummy >> dummy;
   
   //    fin.close();
   
   //    return vars;
}
Exemplo n.º 27
0
void plot_efficiencies( TFile* file, Int_t type = 2, TDirectory* BinDir)
{
   // input:   - Input file (result from TMVA),
   //          - type = 1 --> plot efficiency(B) versus eff(S)
   //                 = 2 --> plot rejection (B) versus efficiency (S)

   Bool_t __PLOT_LOGO__  = kTRUE;
   Bool_t __SAVE_IMAGE__ = kTRUE;

   // the coordinates
   Float_t x1 = 0;
   Float_t x2 = 1;
   Float_t y1 = 0;
   Float_t y2 = 0.8;

   // reverse order if "rejection"
   if (type == 2) {
      Float_t z = y1;
      y1 = 1 - y2;
      y2 = 1 - z;    
      //      cout << "--- type==2: plot background rejection versus signal efficiency" << endl;
   }
   else {
      //  cout << "--- type==1: plot background efficiency versus signal efficiency" << endl;
   }
   // create canvas
   TCanvas* c = new TCanvas( "c", "the canvas", 200, 0, 650, 500 );

   // global style settings
   c->SetGrid();
   c->SetTicks();

   // legend
   Float_t x0L = 0.107,     y0H = 0.899;
   Float_t dxL = 0.457-x0L, dyH = 0.22;
   if (type == 2) {
      x0L = 0.15;
      y0H = 1 - y0H + dyH + 0.07;
   }
   TLegend *legend = new TLegend( x0L, y0H-dyH, x0L+dxL, y0H );
   legend->SetTextSize( 0.05 );
   legend->SetHeader( "MVA Method:" );
   legend->SetMargin( 0.4 );

   TString xtit = "Signal efficiency";
   TString ytit = "Background efficiency";  
   if (type == 2) ytit = "Background rejection";
   TString ftit = ytit + " versus " + xtit;

   if (TString(BinDir->GetName()).Contains("multicut")){
      ftit += "  Bin: ";
      ftit += (BinDir->GetTitle());
   }

   // draw empty frame
   if(gROOT->FindObject("frame")!=0) gROOT->FindObject("frame")->Delete();
   TH2F* frame = new TH2F( "frame", ftit, 500, x1, x2, 500, y1, y2 );
   frame->GetXaxis()->SetTitle( xtit );
   frame->GetYaxis()->SetTitle( ytit );
   TMVAGlob::SetFrameStyle( frame, 1.0 );

   frame->Draw();  

   Int_t color = 1;
   Int_t nmva  = 0;
   TKey *key, *hkey;

   TString hNameRef = "effBvsS";
   if (type == 2) hNameRef = "rejBvsS";

   TList hists;
   TList methods;
   UInt_t nm = TMVAGlob::GetListOfMethods( methods );
   //   TIter next(file->GetListOfKeys());
   TIter next(&methods);

   // loop over all methods
   while (key = (TKey*)next()) {
      TDirectory * mDir = (TDirectory*)key->ReadObj();
      TList titles;
      UInt_t ninst = TMVAGlob::GetListOfTitles(mDir,titles);
      TIter nextTitle(&titles);
      TKey *titkey;
      TDirectory *titDir;
      while ((titkey = TMVAGlob::NextKey(nextTitle,"TDirectory"))) {
         titDir = (TDirectory *)titkey->ReadObj();
         TString methodTitle;
         TMVAGlob::GetMethodTitle(methodTitle,titDir);
         TIter nextKey( titDir->GetListOfKeys() );
         while ((hkey = TMVAGlob::NextKey(nextKey,"TH1"))) {
            TH1 *h = (TH1*)hkey->ReadObj();    
            TString hname = h->GetName();
            if (hname.Contains( hNameRef ) && hname.BeginsWith( "MVA_" )) {
               h->SetLineWidth(3);
               h->SetLineColor(color);
               color++; if (color == 5 || color == 10 || color == 11) color++; 
               h->Draw("csame");
               hists.Add(h);
               nmva++;
            }
         }
      }
   }

   while (hists.GetSize()) {
      TListIter hIt(&hists);
      TH1* hist(0);
      Double_t largestInt=-1;
      TH1* histWithLargestInt(0);
      while ((hist = (TH1*)hIt())!=0) {
         Double_t integral = hist->Integral(1,hist->FindBin(0.9999));
         if (integral>largestInt) {
            largestInt = integral;
            histWithLargestInt = hist;
         }
      }
      if (histWithLargestInt == 0) {
         cout << "ERROR - unknown hist \"histWithLargestInt\" --> serious problem in ROOT file" << endl;
         break;
      }
      legend->AddEntry(histWithLargestInt,TString(histWithLargestInt->GetTitle()).ReplaceAll("MVA_",""),"l");
      hists.Remove(histWithLargestInt);
   }   
   
   // rescale legend box size
   // current box size has been tuned for 3 MVAs + 1 title
   if (type == 1) {
      dyH *= (1.0 + Float_t(nmva - 3.0)/4.0);
      legend->SetY1( y0H - dyH );
   }
   else {
      dyH *= (Float_t(nmva - 3.0)/4.0);
      legend->SetY2( y0H + dyH);
   }

   // redraw axes
   frame->Draw("sameaxis");  
   legend->Draw("same");

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

   if (__PLOT_LOGO__) TMVAGlob::plot_logo();

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

   c->Update();

   TString fname = "plots/" + hNameRef;
   if (TString(BinDir->GetName()).Contains("multicut")){
      TString fprepend(BinDir->GetName());
      fprepend.ReplaceAll("multicutMVA_","");
      fname = "plots/" + fprepend + "_" + hNameRef;
   }
   if (__SAVE_IMAGE__) TMVAGlob::imgconv( c, fname );

   return;
}
Exemplo n.º 28
0
// input: - Input file (result from TMVA),
//        - normal/decorrelated/PCA
//        - use of TMVA plotting TStyle
void variables( TString fin = "TMVA.root", TString dirName = "InputVariables_Id", TString title = "TMVA Input Variables",
                Bool_t isRegression = kFALSE, Bool_t useTMVAStyle = kTRUE )
{
   TString outfname = dirName;
   outfname.ToLower(); outfname.ReplaceAll( "input", ""  );

   // set style and remove existing canvas'
   TMVAGlob::Initialize( useTMVAStyle );

   // obtain shorter histogram title 
   TString htitle = title; 
   htitle.ReplaceAll("variables ","variable");
   htitle.ReplaceAll("and target(s)","");
   htitle.ReplaceAll("(training sample)","");

   // checks if file with name "fin" is already open, and if not opens one
   TFile* file = TMVAGlob::OpenFile( fin );

   TDirectory* dir = (TDirectory*)file->Get( dirName );
   if (dir==0) {
      cout << "No information about " << title << " available in directory " << dirName << " of file " << fin << endl;
      return;
   }
   dir->cd();

   // how many plots are in the directory?
   Int_t noPlots = TMVAGlob::GetNumberOfInputVariables( dir ) +
      TMVAGlob::GetNumberOfTargets( dir );

   // define Canvas layout here!
   // default setting
   Int_t xPad;  // no of plots in x
   Int_t yPad;  // no of plots in y
   Int_t width; // size of canvas
   Int_t height;
   switch (noPlots) {
   case 1:
      xPad = 1; yPad = 1; width = 550; height = 0.90*width; break;
   case 2:
      xPad = 2; yPad = 1; width = 600; height = 0.50*width; break;
   case 3:
      xPad = 3; yPad = 1; width = 900; height = 0.4*width; break;
   case 4:
      xPad = 2; yPad = 2; width = 600; height = width; break;
   default:
//       xPad = 3; yPad = 2; width = 800; height = 0.55*width; break;
     xPad = 1; yPad = 1; width = 550; height = 0.90*width; break;
   }

   Int_t noPadPerCanv = xPad * yPad ;

   // counter variables
   Int_t countCanvas = 0;
   Int_t countPad    = 0;

   // loop over all objects in directory
   TCanvas* canv = 0;
   TKey*    key  = 0;
   Bool_t   createNewFig = kFALSE;
   TIter next(dir->GetListOfKeys());
   while ((key = (TKey*)next())) {
      if (key->GetCycle() != 1) continue;

      if (!TString(key->GetName()).Contains("__Signal") && 
          !(isRegression && TString(key->GetName()).Contains("__Regression"))) continue;

      // make sure, that we only look at histograms
      TClass *cl = gROOT->GetClass(key->GetClassName());
      if (!cl->InheritsFrom("TH1")) continue;
      TH1 *sig = (TH1*)key->ReadObj();
      TString hname(sig->GetName());

      //normalize to 1
      NormalizeHist(sig);      

      // create new canvas
      if (countPad%noPadPerCanv==0) {
         ++countCanvas;
         canv = new TCanvas( Form("canvas%d", countCanvas), title,
                             countCanvas*50+50, countCanvas*20, width, height );
         canv->Divide(xPad,yPad);
         canv->SetFillColor(kWhite);
         canv->Draw();
      }

      TPad* cPad = (TPad*)canv->cd(countPad++%noPadPerCanv+1);
      cPad->SetFillColor(kWhite);

      // find the corredponding backgrouns histo
      TString bgname = hname;
      bgname.ReplaceAll("__Signal","__Background");
      TH1 *bgd = (TH1*)dir->Get(bgname);
      if (bgd == NULL) {
         cout << "ERROR!!! couldn't find background histo for" << hname << endl;
         exit;
      }
      //normalize to 1
      NormalizeHist(bgd);


      // this is set but not stored during plot creation in MVA_Factory
      TMVAGlob::SetSignalAndBackgroundStyle( sig, (isRegression ? 0 : bgd) );            

      sig->SetTitle( TString( htitle ) + ": " + sig->GetTitle() );
      TMVAGlob::SetFrameStyle( sig, 1.2 );

      // normalise both signal and background
//       if (!isRegression) TMVAGlob::NormalizeHists( sig, bgd );
//       else {
//          // change histogram title for target
//          TString nme = sig->GetName();
//          if (nme.Contains( "_target" )) {
//             TString tit = sig->GetTitle();
//             sig->SetTitle( tit.ReplaceAll("Input variable", "Regression target" ) );
//          }
//       }
      sig->SetTitle( "" );            
      

      // finally plot and overlay
      Float_t sc = 1.1;
      if (countPad == 1) sc = 1.3;
      sig->SetMaximum( TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*sc );
      sig->Draw( "hist" );
      cPad->SetLeftMargin( 0.17 );

      sig->GetYaxis()->SetTitleOffset( 1.50 );
      if (!isRegression) {
         bgd->Draw("histsame");
         TString ytit = TString("(1/N) ") + sig->GetYaxis()->GetTitle();
         ytit = TString("Fraction of Events");
         sig->GetYaxis()->SetTitle( ytit ); // histograms are normalised
      }

      if (countPad == 1) sig->GetXaxis()->SetTitle("Leading Lepton p_{T} [GeV/c]");
      if (countPad == 2) sig->GetXaxis()->SetTitle("Trailing Lepton p_{T} [GeV/c]");
      if (countPad == 3) sig->GetXaxis()->SetTitle("#Delta#phi(l,l)");
      if (countPad == 4) sig->GetXaxis()->SetTitle("#Delta R(l,l)");
      if (countPad == 5) sig->GetXaxis()->SetTitle("Dilepton Mass [GeV/c^{2}]");
      if (countPad == 6) sig->GetXaxis()->SetTitle("Dilepton Flavor Final State");
      if (countPad == 7) sig->GetXaxis()->SetTitle("M_{T} (Higgs) [GeV/c^{2}]");
      if (countPad == 8) sig->GetXaxis()->SetTitle("#Delta#phi(Dilepton System, MET)");
      if (countPad == 9) sig->GetXaxis()->SetTitle("#Delta#phi(Dilepton System, Jet)");


      // Draw legend
//       if (countPad == 1 && !isRegression) {
         TLegend *legend= new TLegend( cPad->GetLeftMargin(), 
                                       1-cPad->GetTopMargin()-.15, 
                                       cPad->GetLeftMargin()+.4, 
                                       1-cPad->GetTopMargin() );

         if(countPad == 1 || countPad == 2 ||countPad == 3 ||countPad == 4 ||countPad == 5 ||countPad == 7  ) {
           legend= new TLegend( 0.50, 
                                1-cPad->GetTopMargin()-.15, 
                                0.90, 
                                1-cPad->GetTopMargin() );
         }

         legend->SetFillStyle(0);
         legend->AddEntry(sig,"Signal","F");
         legend->AddEntry(bgd,"Background","F");
         legend->SetBorderSize(0);
         legend->SetMargin( 0.3 );
         legend->SetTextSize( 0.03 );
         legend->Draw("same");
//       } 

      // redraw axes
      sig->Draw("sameaxis");

      // text for overflows
      Int_t    nbin = sig->GetNbinsX();
      Double_t dxu  = sig->GetBinWidth(0);
      Double_t dxo  = sig->GetBinWidth(nbin+1);
      TString uoflow = "";
      if (isRegression) {
         uoflow = Form( "U/O-flow: %.1f%% / %.1f%%", 
                        sig->GetBinContent(0)*dxu*100, sig->GetBinContent(nbin+1)*dxo*100 );
      }
      else {
         uoflow = Form( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", 
                        sig->GetBinContent(0)*dxu*100, bgd->GetBinContent(0)*dxu*100,
                        sig->GetBinContent(nbin+1)*dxo*100, bgd->GetBinContent(nbin+1)*dxo*100 );
      }
  
      TText* t = new TText( 0.98, 0.14, uoflow );
      t->SetNDC();
      t->SetTextSize( 0.040 );
      t->SetTextAngle( 90 );
//       t->AppendPad();    

      // save canvas to file
      if (countPad%noPadPerCanv==0) {
         TString fname = Form( "plots/%s_c%i", outfname.Data(), countCanvas );
         TMVAGlob::plot_logo();
         TMVAGlob::imgconv( canv, fname );
         createNewFig = kFALSE;
      }
      else {
         createNewFig = kTRUE;
      }
   }
   
   if (createNewFig) {
      TString fname = Form( "plots/%s_c%i", outfname.Data(), countCanvas );
      TMVAGlob::plot_logo();
      TMVAGlob::imgconv( canv, fname );
      createNewFig = kFALSE;
   }

   return;
}
Exemplo n.º 29
0
// input: - Input file (result from TMVA)
//        - use of TMVA plotting TStyle
void mvas( TString fin = "TMVA.root", HistType htype = MVAType, Bool_t useTMVAStyle = kTRUE )
{
   // set style and remove existing canvas'
   TMVAGlob::Initialize( useTMVAStyle );

   // switches
   const Bool_t Save_Images     = kTRUE;

   // checks if file with name "fin" is already open, and if not opens one
   TFile* file = TMVAGlob::OpenFile( fin );  

   // define Canvas layout here!
   Int_t xPad = 1; // no of plots in x
   Int_t yPad = 1; // no of plots in y
   Int_t noPad = xPad * yPad ; 
   const Int_t width = 600;   // size of canvas

   // this defines how many canvases we need
   TCanvas *c = 0;

   // counter variables
   Int_t countCanvas = 0;

   // search for the right histograms in full list of keys
   TIter next(file->GetListOfKeys());
   TKey *key(0);   
   while ((key = (TKey*)next())) {

      if (!TString(key->GetName()).BeginsWith("Method_")) continue;
      if( ! gROOT->GetClass(key->GetClassName())->InheritsFrom("TDirectory") ) continue;

      TString methodName;
      TMVAGlob::GetMethodName(methodName,key);

      TDirectory* mDir = (TDirectory*)key->ReadObj();

      TIter keyIt(mDir->GetListOfKeys());
      TKey *titkey;
      while ((titkey = (TKey*)keyIt())) {
         if (!gROOT->GetClass(titkey->GetClassName())->InheritsFrom("TDirectory")) continue;

         TDirectory *titDir = (TDirectory *)titkey->ReadObj();
         TString methodTitle;
         TMVAGlob::GetMethodTitle(methodTitle,titDir);

         cout << "--- Found directory for method: " << methodName << "::" << methodTitle << flush;
         TString hname = "MVA_" + methodTitle;
         if      (htype == ProbaType  ) hname += "_Proba";
         else if (htype == RarityType ) hname += "_Rarity";
         TH1* sig = dynamic_cast<TH1*>(titDir->Get( hname + "_S" ));
         TH1* bgd = dynamic_cast<TH1*>(titDir->Get( hname + "_B" ));

         if (sig==0 || bgd==0) {
            if     (htype == MVAType)     
               cout << "mva distribution not available (this is normal for Cut classifier)" << endl;
            else if(htype == ProbaType)   
               cout << "probability distribution not available (this is normal for Cut classifier)" << endl;
            else if(htype == RarityType)  
               cout << "rarity distribution not available (this is normal for Cut classifier)" << endl;
            else if(htype == CompareType) 
               cout << "overtraining check not available (this is normal for Cut classifier)" << endl;
            else cout << endl;
         } 
         else {
            cout << endl;
            // chop off useless stuff
            sig->SetTitle( Form("TMVA response for classifier: %s", methodTitle.Data()) );
            if      (htype == ProbaType) 
               sig->SetTitle( Form("TMVA probability for classifier: %s", methodTitle.Data()) );
            else if (htype == RarityType) 
               sig->SetTitle( Form("TMVA Rarity for classifier: %s", methodTitle.Data()) );
            else if (htype == CompareType) 
               sig->SetTitle( Form("TMVA overtraining check for classifier: %s", methodTitle.Data()) );
         
            // create new canvas
            TString ctitle = ((htype == MVAType) ? 
                              Form("TMVA response %s",methodTitle.Data()) : 
                              (htype == ProbaType) ? 
                              Form("TMVA probability %s",methodTitle.Data()) :
                              (htype == CompareType) ? 
                              Form("TMVA comparison %s",methodTitle.Data()) :
                              Form("TMVA Rarity %s",methodTitle.Data()));
         
            TString cname = ((htype == MVAType) ? 
                             Form("output_%s",methodTitle.Data()) : 
                             (htype == ProbaType) ? 
                             Form("probability_%s",methodTitle.Data()) :
                             (htype == CompareType) ? 
                             Form("comparison_%s",methodTitle.Data()) :
                             Form("rarity_%s",methodTitle.Data()));

            c = new TCanvas( Form("canvas%d", countCanvas+1), ctitle, 
                             countCanvas*50+200, countCanvas*20, width, (Int_t)width*0.78 ); 
    
            // set the histogram style
            TMVAGlob::SetSignalAndBackgroundStyle( sig, bgd );
   
            // normalise both signal and background
            TMVAGlob::NormalizeHists( sig, bgd );
   
            // frame limits (choose judicuous x range)
            Float_t nrms = 4;
            cout << "--- Mean and RMS (S): " << sig->GetMean() << ", " << sig->GetRMS() << endl;
            cout << "--- Mean and RMS (B): " << bgd->GetMean() << ", " << bgd->GetRMS() << endl;
            Float_t xmin = TMath::Max( TMath::Min(sig->GetMean() - nrms*sig->GetRMS(), 
                                                  bgd->GetMean() - nrms*bgd->GetRMS() ),
                                       sig->GetXaxis()->GetXmin() );
            Float_t xmax = TMath::Min( TMath::Max(sig->GetMean() + nrms*sig->GetRMS(), 
                                                  bgd->GetMean() + nrms*bgd->GetRMS() ),
                                       sig->GetXaxis()->GetXmax() );
            Float_t ymin = 0;
            Float_t maxMult = (htype == CompareType) ? 1.3 : 1.2;
            Float_t ymax = TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*maxMult;
   
            // build a frame
            Int_t nb = 500;
            TString hFrameName(TString("frame") + methodTitle);
            TObject *o = gROOT->FindObject(hFrameName);
            if(o) delete o;
            TH2F* frame = new TH2F( hFrameName, sig->GetTitle(), 
                                    nb, xmin, xmax, nb, ymin, ymax );
            frame->GetXaxis()->SetTitle( methodTitle + ((htype == MVAType || htype == CompareType) ? " response" : "") );
            if      (htype == ProbaType  ) frame->GetXaxis()->SetTitle( "Signal probability" );
            else if (htype == RarityType ) frame->GetXaxis()->SetTitle( "Signal rarity" );
            frame->GetYaxis()->SetTitle("Normalized");
            TMVAGlob::SetFrameStyle( frame );
   
            // eventually: draw the frame
            frame->Draw();  
    
            c->GetPad(0)->SetLeftMargin( 0.105 );
            frame->GetYaxis()->SetTitleOffset( 1.2 );

            // Draw legend               
            TLegend *legend= new TLegend( c->GetLeftMargin(), 1 - c->GetTopMargin() - 0.12, 
                                          c->GetLeftMargin() + (htype == CompareType ? 0.40 : 0.3), 1 - c->GetTopMargin() );
            legend->SetFillStyle( 1 );
            legend->AddEntry(sig,TString("Signal")     + ((htype == CompareType) ? " (test sample)" : ""), "F");
            legend->AddEntry(bgd,TString("Background") + ((htype == CompareType) ? " (test sample)" : ""), "F");
            legend->SetBorderSize(1);
            legend->SetMargin( (htype == CompareType ? 0.2 : 0.3) );
            legend->Draw("same");

            // overlay signal and background histograms
            sig->Draw("samehist");
            bgd->Draw("samehist");
   
            if (htype == CompareType) {
               // if overtraining check, load additional histograms
               TH1* sigOv = 0;
               TH1* bgdOv = 0;

               TString ovname = hname += "_Train";
               sigOv = dynamic_cast<TH1*>(titDir->Get( ovname + "_S" ));
               bgdOv = dynamic_cast<TH1*>(titDir->Get( ovname + "_B" ));
      
               if (sigOv == 0 || bgdOv == 0) {
                  cout << "+++ Problem in \"mvas.C\": overtraining check histograms do not exist" << endl;
               }
               else {
                  cout << "--- Found comparison histograms for overtraining check" << endl;

                  TLegend *legend2= new TLegend( 1 - c->GetRightMargin() - 0.42, 1 - c->GetTopMargin() - 0.12,
                                                 1 - c->GetRightMargin(), 1 - c->GetTopMargin() );
                  legend2->SetFillStyle( 1 );
                  legend2->SetBorderSize(1);
                  legend2->AddEntry(sigOv,"Signal (training sample)","P");
                  legend2->AddEntry(bgdOv,"Background (training sample)","P");
                  legend2->SetMargin( 0.1 );
                  legend2->Draw("same");
               }
               Int_t col = sig->GetLineColor();
               sigOv->SetMarkerColor( col );
               sigOv->SetMarkerSize( 0.7 );
               sigOv->SetMarkerStyle( 20 );
               sigOv->SetLineWidth( 1 );
               sigOv->SetLineColor( col );
               sigOv->Draw("e1same");
      
               col = bgd->GetLineColor();
               bgdOv->SetMarkerColor( col );
               bgdOv->SetMarkerSize( 0.7 );
               bgdOv->SetMarkerStyle( 20 );
               bgdOv->SetLineWidth( 1 );
               bgdOv->SetLineColor( col );
               bgdOv->Draw("e1same");

               ymax = TMath::Max( ymax, TMath::Max( sigOv->GetMaximum(), bgdOv->GetMaximum() )*maxMult );
               frame->GetYaxis()->SetLimits( 0, ymax );
      
               // for better visibility, plot thinner lines
               sig->SetLineWidth( 1 );
               bgd->SetLineWidth( 1 );

               // perform K-S test
               cout << "--- Perform Kolmogorov-Smirnov tests" << endl;
               Double_t kolS = sig->KolmogorovTest( sigOv );
               Double_t kolB = bgd->KolmogorovTest( bgdOv );
               cout << "--- Goodness of signal (background) consistency: " << kolS << " (" << kolB << ")" << endl;

               TString probatext = Form( "Kolmogorov-Smirnov test: signal (background) probability = %5.3g (%5.3g)", kolS, kolB );
               TText* tt = new TText( 0.12, 0.74, probatext );
               tt->SetNDC(); tt->SetTextSize( 0.032 ); tt->AppendPad(); 
            }

            // redraw axes
            frame->Draw("sameaxis");

            // text for overflows
            Int_t    nbin = sig->GetNbinsX();
            Double_t dxu  = sig->GetBinWidth(0);
            Double_t dxo  = sig->GetBinWidth(nbin+1);
            TString uoflow = Form( "U/O-flow (S,B): (%.1f, %.1f)%% / (%.1f, %.1f)%%", 
                                   sig->GetBinContent(0)*dxu*100, bgd->GetBinContent(0)*dxu*100,
                                   sig->GetBinContent(nbin+1)*dxo*100, bgd->GetBinContent(nbin+1)*dxo*100 );
            TText* t = new TText( 0.975, 0.115, uoflow );
            t->SetNDC();
            t->SetTextSize( 0.030 );
            t->SetTextAngle( 90 );
            t->AppendPad();    
   
            // update canvas
            c->Update();

            // save canvas to file

            TMVAGlob::plot_logo(1.058);
            if (Save_Images) {
               if      (htype == MVAType)     TMVAGlob::imgconv( c, Form("plots/mva_%s",     methodTitle.Data()) );
               else if (htype == ProbaType)   TMVAGlob::imgconv( c, Form("plots/proba_%s",   methodTitle.Data()) ); 
               else if (htype == CompareType) TMVAGlob::imgconv( c, Form("plots/overtrain_%s", methodTitle.Data()) ); 
               else                           TMVAGlob::imgconv( c, Form("plots/rarity_%s",  methodTitle.Data()) ); 
            }
            countCanvas++;
         }
      }
   }
}
Exemplo n.º 30
0
void visDQMVerifyStrict(void)
{
  for (int i = 0; i < 15; ++i)
    gSystem->ResetSignal(i, kTRUE);

  // NB: cannot use scalars like iRun, iEvent, iLumiSection.
  // We search for them manually out of an EventInfo.
  const char *required[] = { "Run summary",
			     "reportSummaryMap",
			     "reportSummaryContents",
			     "EventInfo" };

  if (! _file0)
  {
    std::cerr << "VERIFY: Invalid ROOT file\n";
    exit(1);
  }

  if (_file0->IsZombie())
  {
    std::cerr << "VERIFY: Zombie ROOT file\n";
    exit(1);
  }

  long long runnr = -1;
  long long eventnr = -1;
  long long luminr = -1;

  for (int i = 0, e = sizeof(required)/sizeof(required[0]); i != e; ++i)
  {
    TObject *obj = _file0->FindObjectAny(required[i]);
    if (! obj)
    {
      std::cerr << "VERIFY: Required object '" << required[i] << "' missing\n";
      exit(1);
    }

    if (! strcmp(required[i], "EventInfo"))
    {
      bool haverun = false;
      bool haveevent = false;
      bool havelumi = false;
      bool havesum = false;
      TDirectory *dir = (TDirectory *) obj;
      TIter next(dir->GetListOfKeys());
      TKey *key;

      while ((key = (TKey *) next()))
      {
	const char *name = key->ReadObj()->GetName();
	if (!strncmp(name, "<reportSummary>f=", 17))
	  havesum = true;
	if (!strncmp(name, "<iRun>i=", 8))
	  haverun = true, sscanf(name+8, "%jd", &runnr);
	if (!strncmp(name, "<iEvent>i=", 10))
	  haveevent = true, sscanf(name+10, "%jd", &eventnr);
	if (!strncmp(name, "<iLumiSection>i=", 16))
	  havelumi = true, sscanf(name+16, "%jd", &luminr);
      }

      if (! havesum)
      {
	std::cerr << "VERIFY: Required object 'reportSummary' missing\n";
	exit(1);
      }
      if (! haverun)
      {
	std::cerr << "VERIFY: Required object 'iRun' missing\n";
	exit(1);
      }
      if (! haveevent)
      {
	std::cerr << "VERIFY: Required object 'iEvent' missing\n";
	exit(1);
      }
      if (! havelumi)
      {
	std::cerr << "VERIFY: Required object 'iLumiSection' missing\n";
	exit(1);
      }
    }
  }

  std::cerr << "VERIFY: Good to go; R="
	    << runnr << ":L="
	    << luminr << ":E="
	    << eventnr << "\n";
  exit(0);
}