Beispiel #1
0
   Bool_t ExistMethodName( TString name, TDirectory *dir=0 )
   {
      // find the key for a method
      if (dir==0) dir = gDirectory;
      TIter mnext(dir->GetListOfKeys());
      TKey *mkey;
      Bool_t loop=kTRUE;
      while (loop) {
         mkey = (TKey*)mnext();
         if (mkey==0) {
            loop = kFALSE;
         } 
         else {
            TString clname  = mkey->GetClassName();
            TString keyname = mkey->GetName();
            TClass *cl = gROOT->GetClass(clname);
            if (keyname.Contains("Method") && cl->InheritsFrom("TDirectory")) {

               TDirectory* d_ = (TDirectory*)dir->Get( keyname );
               if (!d_) {
                  cout << "HUUUGE TROUBLES IN TMVAGlob::ExistMethodName() --> contact authors" << endl;
                  return kFALSE;
               }

               TIter mnext_(d_->GetListOfKeys());
               TKey *mkey_;
               while ((mkey_ = (TKey*)mnext_())) {
                  TString clname_ = mkey_->GetClassName();
                  TClass *cl_ = gROOT->GetClass(clname_);
                  if (cl_->InheritsFrom("TDirectory")) {
                     TString mname = mkey_->GetName(); // method name
                     if (mname==name) { // target found!                  
                        return kTRUE;
                     }
                  }
               }
            }
         }
      }
      return kFALSE;
   }
//Clone the file excluding the histogram (code stolen from Rene Brun)
void copyDir(TDirectory *source,std::string iSkipHist,bool iFirst=true) { 
  //copy all objects and subdirs of directory source as a subdir of the current directory   
  TDirectory *savdir = gDirectory;
  TDirectory *adir   = savdir;
  if(!iFirst) adir   = savdir->mkdir(source->GetName());
  if(!iFirst) adir->cd();
  //loop on all entries of this directory
  TKey *key;
  TIter nextkey(source->GetListOfKeys());
  while ((key = (TKey*)nextkey())) {
    const char *classname = key->GetClassName();
    TClass *cl = gROOT->GetClass(classname);
    if (!cl) continue;
    if (cl->InheritsFrom(TDirectory::Class())) {
      source->cd(key->GetName());
      TDirectory *subdir = gDirectory;
      adir->cd();
      copyDir(subdir,iSkipHist,false);
      adir->cd();
    } else {
      source->cd();
      TObject *obj = key->ReadObj();
      std::string pFullName = std::string(adir->GetName())+"/"+std::string(obj->GetName());
      std::string iSkipHist2 = iSkipHist;
      std::string fine_binning = "_fine_binning";
      iSkipHist2.replace(iSkipHist2.find(fine_binning), fine_binning.length(),"");
      if(pFullName.find(iSkipHist) != std::string::npos || pFullName.find(iSkipHist2) != std::string::npos) {
	continue;
      }
      adir->cd();
      obj->Write();
      delete obj;
    }
  }
  adir->SaveSelf(kTRUE);
  savdir->cd();
}
Beispiel #3
0
int compareHistograms(TString mode) {
	int status(0);

	TFile *f1 = TFile::Open("../validation/rootfiles/"+mode+"_hists.root");
	TFile *f2 = TFile::Open("../validation/"+mode+"_hists.root");

	if(!f1 || !f2) {
		std::cout << "ERROR in compareHistograms : Files do not exist for mode " << mode << std::endl;
		return 1;
	}

	TIter next(f1->GetListOfKeys());
	TKey *key;
	
	while ((key = (TKey*)next())) {
		TClass *cl = gROOT->GetClass(key->GetClassName());
		if (!cl->InheritsFrom("TH1")) continue;
		TH1 *h1 = (TH1*)key->ReadObj();
		TH1* h2 = (TH1*)f2->Get(h1->GetName());

		if(!h2) {
			std::cout << "WARNING in compareHistograms : Histogram " << h1->GetName() << " not found." << std::endl;
			status=1;
			continue;
		}

		double chi2 = h1->Chi2Test(h2,"UU");
		std::cout << "INFO in compareHstograms : " << h1->GetName() << " :\tchi2 = " << chi2 << std::endl;
		if(chi2<1.0) {
			std::cout << "WARNING in compareHistograms : Histograms do not match for " << h1->GetName() << std::endl;
			status=1;
		}
	}

	return status;
}
Beispiel #4
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;
   }
Beispiel #5
0
 UInt_t GetListOfMethods( TList & methods, TDirectory *dir=0 )
 {
    // get a list of methods
    // the list contains TKey objects
    if (dir==0) dir = gDirectory;
    TIter mnext(dir->GetListOfKeys());
    TKey *mkey;
    methods.Clear();
    methods.SetOwner(kFALSE);
    UInt_t ni=0;
    while ((mkey = (TKey*)mnext())) {
       // make sure, that we only look at TDirectory with name Method_<xxx>
       TString name = mkey->GetClassName();
       TClass *cl = gROOT->GetClass(name);
       if (cl->InheritsFrom("TDirectory")) {
          if (TString(mkey->GetName()).BeginsWith("Method_")) {
             methods.Add(mkey);
             ni++;
          }
       }
    }
    cout << "--- Found " << ni << " classifier types" << endl;
    return ni;
 }
Beispiel #6
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 draw_network(TDirectory* d)
{
   Bool_t __PRINT_LOGO__ = kTRUE;

   // create canvas
   TStyle* TMVAStyle = gROOT->GetStyle("TMVA"); // the TMVA style
   Int_t canvasColor = TMVAStyle->GetCanvasColor(); // backup
   TMVAStyle->SetCanvasColor( c_DarkBackground );

   static icanvas = -1;
   icanvas++;
   TCanvas* c = new TCanvas( Form( "c%i", icanvas ), Form("Neural Network Layout for: %s", d->GetName()), 
                             100 + (icanvas)*40, 0 + (icanvas+1)*20, 1000, 650  );

   TIter next = d->GetListOfKeys();
   TKey *key;
   TString hName = "weights_hist";
   Int_t numHists = 0;

   // loop over all histograms with hName in name
   while (key = (TKey*)next()) {
      TClass *cl = gROOT->GetClass(key->GetClassName());
      if (!cl->InheritsFrom("TH2F")) continue;    
      TH2F *h = (TH2F*)key->ReadObj();    
      if (TString(h->GetName()).Contains( hName )) {
         numHists++;
      }
   }

   // loop over all histograms with hName in name again
   next.Reset();
   Double_t maxWeight = 0;

   // find max weight
   while (key = (TKey*)next()) {

      //cout << "Title: " << key->GetTitle() << endl;
      TClass *cl = gROOT->GetClass(key->GetClassName());
      if (!cl->InheritsFrom("TH2F")) continue;    

      TH2F* h = (TH2F*)key->ReadObj();    
      if (TString(h->GetName()).Contains( hName )){
 
         Int_t n1 = h->GetNbinsX();
         Int_t n2 = h->GetNbinsY();
         for (Int_t i = 0; i < n1; i++) {
            for (Int_t j = 0; j < n2; j++) {
               Double_t weight = TMath::Abs(h->GetBinContent(i+1, j+1));
               if (maxWeight < weight) maxWeight = weight;
            }
         }
      }
   }

   // draw network
   next.Reset();
   Int_t count = 0;
   while (key = (TKey*)next()) {

      TClass *cl = gROOT->GetClass(key->GetClassName());
      if (!cl->InheritsFrom("TH2F")) continue;    

      TH2F* h = (TH2F*)key->ReadObj();    
      if (TString(h->GetName()).Contains( hName )){
         draw_layer(c, h, count++, numHists+1, maxWeight);
      }
   }

   draw_layer_labels(numHists+1);

   // ============================================================
   if (__PRINT_LOGO__) TMVAGlob::plot_logo();
   // ============================================================  

   c->Update();

   TString fname = "plots/network";
   TMVAGlob::imgconv( c, fname );

   TMVAStyle->SetCanvasColor( canvasColor );
}
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;
}
Beispiel #9
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;
}
Beispiel #10
0
void loopdir( TFile *f1 )
{

    TIter next( f1->GetListOfKeys() );
    TKey *k; //histos inside the file.
    TCanvas *c = new TCanvas( "c", "canvas", 800, 800 );
    while( ( k = ( TKey * )next() ) ) { //loop over histos
        TClass *cl = gROOT->GetClass( k->GetClassName() );
        std::cout << k->GetName() << std::endl;
        if( !cl->InheritsFrom( "TH1" ) ) { continue; } //make sure it is a histogram!

        TH1 *h1 = ( TH1 * )k->ReadObj(); //get handle on histo, cast as TH1
        h1->SetBit( TH1::kNoTitle ); //don't print title

        std::ostringstream title;
        title << h1->GetName();

        //	std::cout << h1->GetName() << std::endl;
        //	std::cout << (title.str().find("un")) << std::endl;
        //	std::cout << (title.str().size()) << std::endl;
        //	std::cout << ((title.str().find("un"))>title.str().size()) << std::endl;

        if( ( title.str().find( "hOverE" ) ) < title.str().size() ) {
            c->SetLogx();
            std::cout << "[SETTING LOG X|" << std::endl;
        } else {
            c->SetLogx( 0 );
        }

        if( ( title.str().find( "un" ) ) < title.str().size() ) {continue;} //if it contains "un", it is the 53x unmatched electrons. We use this later, when plotting vs the regular 53x electrons. so skip them now and access later.

        //std::cout << (title.str().find("5")) << std::endl;

        // PLOTS 53X vs 70X
        if( ( title.str().find( "5" ) ) < title.str().size() ) { // make sure the histo title contains 5. These are the regular 53x histos.

            c->cd();
            TPad *pad1 = new TPad( "pad1", "pad1", 0, 0.3, 1, 1.0 ); //create pad for distributions
            pad1->SetBottomMargin( 0.05 );
            pad1->SetGridx();         // Vertical grid
            pad1->Draw();             // Draw the upper pad: pad1
            pad1->cd();               // pad1 becomes the current pad
            h1->SetStats( 0 );        // No statistics on upper plot

            //	used to zoom to a more sensible range
            float xlo = 0;
            float xhi = 0;

            //find sensble lower axis range
            for( int n = 0 ; n < h1->GetNbinsX(); n++ ) {
                //std::cout << h1->GetBinContent(n) << std::endl;
                //if(n %1 ==0) std::cout << "test " << n << "	" << h1->GetBinCenter(n) << " " <<  h1->GetBinContent(n) << std::endl;
                if( h1->GetBinContent( n ) < h1->GetEntries() / 10000 ) {continue ;} //basically picks out first bin with more than 100 events.
                xlo = h1->GetBinCenter( n - 1 );
                break;
            }

            // find sensible upper axis range
            for( int n = h1->GetNbinsX();  n > -1 * h1->GetNbinsX()  ;  n-- ) {
                //std::cout << h1->GetBinContent(n) << std::endl;
                if( h1->GetBinContent( n ) < h1->GetEntries() / 10000 ) { continue; } //basically picks out first bin with more than 100 events.
                xhi = h1->GetBinCenter( n + 1 );
                break;
            }

            //	std::cout << xlo << "	" << xhi << std::endl;;
            //	if ((title.str().find("FBrem"))< title.str().size()){
            //	h1->GetXaxis()->SetRangeUser(0.01,xhi);
            //	}
            //	if ((title.str().find("hOverE"))< title.str().size()){
            //	h1->GetXaxis()->SetRangeUser(0.01,xhi);
            //	std::cout << "hOverE" << std::endl;
            //	}else{
            h1->GetXaxis()->SetRangeUser( xlo, xhi );
            //	}

            if( ( title.str().find( "graph" ) ) < title.str().size() ) {
                h1->Draw( "h" );
            } else {
                h1->DrawNormalized( "h" );
            }

            std::string title2 = title.str().replace( title.str().find( "5" ), 1, "7" );
            std::cout << title2 << std::endl;
            TKey *k2 = ( f1->GetKey( title2.c_str() ) ); //grab equivalent 70x histo
            TH1 *h2 = ( TH1 * )k2->ReadObj(); //cast as Th1
            if( ( title.str().find( "graph" ) ) < title.str().size() ) {
                h2->Draw( "h same" ); // plot on same graph
            } else {
                h2->DrawNormalized( "h same" ); // plot on same graph
            }

            // Plot the ratio plot below
            c->cd();          // Go back to the main canvas before defining pad2
            TPad *pad2 = new TPad( "pad2", "pad2", 0, 0.05, 1, 0.3 );
            pad2->SetTopMargin( 0 );
            pad2->SetBottomMargin( 0.2 );
            pad2->SetGridx(); // vertical grid
            pad2->Draw();
            pad2->cd();       // pad2 becomes the current pad

            TH1F *h3 = ( TH1F * )h1->Clone( "h3" ); //make raio plot
            h3->SetLineColor( kBlack );
            h3->SetMarkerSize( 0.1 );
            h3->Sumw2();
            h3->SetStats( 0 );    // No statistics on lower plot
            Double_t factor = ( h2->GetEntries() ) / ( h1->GetEntries() );
            h3->Divide( h1, h2, factor, 1. );
            //h3->Divide(h2);
            double max = h3->GetMaximum();
            double min = h3->GetMinimum();
            h3->SetMarkerStyle( 21 );
            h3->SetMinimum( min ); // Define Y ..
            h3->SetMaximum( max ); // .. range
            h3->Draw( "ep" );     // Draw the ratio plot


            h1->GetYaxis()->SetTitleSize( 20 );
            h1->GetYaxis()->SetTitleFont( 43 );
            h1->GetYaxis()->SetTitleOffset( 1.55 );


            h3->GetYaxis()->SetTitle( "ratio 53x/70x " );
            h3->GetYaxis()->SetNdivisions( 505 );
            h3->GetYaxis()->SetTitleSize( 20 );
            h3->GetYaxis()->SetTitleFont( 43 );
            h3->GetYaxis()->SetTitleOffset( 1.55 );
            h3->GetYaxis()->SetLabelFont( 43 ); // Absolute font size in pixel (precision 3)
            h3->GetYaxis()->SetLabelSize( 15 );

            // X axis ratio plot settings
            h3->GetXaxis()->SetTitle( title.str().replace( title.str().find( "5" ), 1, "" ).c_str() );
            h3->GetXaxis()->SetTitleSize( 20 );
            h3->GetXaxis()->SetTitleFont( 43 );
            h3->GetXaxis()->SetTitleOffset( 4. );
            h3->GetXaxis()->SetLabelFont( 43 ); // Absolute font size in pixel (precision 3)
            h3->GetXaxis()->SetLabelSize( 15 );

            double w = h3->GetBinWidth( 0 );
            int N = h3->GetNbinsX();
            TLine *l = new TLine( 0, 0, 0, 0 );
            l->SetLineColor( kRed );
            //l->DrawLine(h3->GetBinCenter(0)-0.49*w,1,h3->GetBinCenter(N)+0.5*w,1);
            l->DrawLine( xlo, 1, xhi, 1 );


            c->cd();
            pad1->cd();

            if( ( title.str().find( "Pt" ) ) < title.str().size() ) {
                TLegend *leg = new TLegend( 0.7, 0.7, 0.9, 0.9 );
                leg->AddEntry( h1, "PFCHS (legacy vtx)", "l" );
                leg->AddEntry( h2, "PUPPI (legacy vtx)", "l" );
                leg->AddEntry( h3, "ratio", "lep" );
                leg->Draw();
            } else {
                TLegend *leg = new TLegend( 0.1, 0.7, 0.3, 0.9 );
                leg->AddEntry( h1, "PFCHS (legacy vtx)", "l" );
                leg->AddEntry( h2, "PUPPI (legacy vtx)", "l" );
                leg->AddEntry( h3, "ratio", "lep" );
                leg->Draw();
            }

            //	std::cout <<  << "	" <<  << std:: endl;
            // save pdf
            std::ostringstream saveas;
            saveas << "Plots/" << h1->GetName() << ".pdf" ;
            c->Print( saveas.str().c_str() );
            std::cout << "print" << std::endl;
        }

        /*	// 53X matched vs 53X unmatched //basically same as above
        	if ((title.str().find("5"))< title.str().size()){
        		c->cd();
        		TPad *pad1 = new TPad("pad1", "pad1", 0, 0.3, 1, 1.0);
        		pad1->SetBottomMargin(0.05);
        		pad1->SetGridx();         // Vertical grid
        		pad1->Draw();             // Draw the upper pad: pad1
        		pad1->cd();               // pad1 becomes the current pad
        		h1->SetStats(0);          // No statistics on upper plot

        	//	float w1 = h1->GetBinWidth(0);
        		float xlo =0;
        		float xhi =0;
        		for (int n = 0 ; n < h1->GetNbinsX(); n++)
        		{
        			//std::cout << h1->GetBinContent(n) << std::endl;
        			//if(n %1 ==0) std::cout << "test " << n << "	" << h1->GetBinCenter(n) << " " <<  h1->GetBinContent(n) << std::endl;
        			if (h1->GetBinContent(n) < h1->GetEntries()/10000 ) {continue ;}
        			xlo = h1->GetBinCenter(n-1);
        			break;
        		}

        		for (int n = h1->GetNbinsX();  n> -1*h1->GetNbinsX()  ;  n--)
        		{
        			//std::cout << h1->GetBinContent(n) << std::endl;
        			if (h1->GetBinContent(n) < h1->GetEntries()/10000 ) continue;
        			xhi = h1->GetBinCenter(n+1);
        			break;
        		}

        //	std::cout << xlo << "	" << xhi << std::endl;;
        		if ((title.str().find("FBrem"))< title.str().size()){
        		h1->GetXaxis()->SetRangeUser(0.001,xhi);
        		}
        		if ((title.str().find("hOverE"))< title.str().size()){
        		h1->GetXaxis()->SetRangeUser(0.001,xhi);
        		}

        		h1->GetXaxis()->SetRangeUser(xlo,xhi);
        		h1->DrawNormalized("h");

        		std::string title2 = title.str().replace(title.str().find("5"), 1, "5_un");
        		TKey *k2 =(f1->GetKey(title2.c_str()));
        		TH1 *h2 =(TH1*)k2->ReadObj();
        		h2->DrawNormalized("h same");

        	//	h1->GetYaxis()->SetLabelSize(0.);
        		//		TGaxis *axis = new TGaxis( -5, 20, -5, 220, 20,220,510,"");
        		//		axis->SetLabelFont(43); // Absolute font size in pixel (precision 3)
        		//		axis->SetLabelSize(15);
        		//		axis->Draw();


        		c->cd();          // Go back to the main canvas before defining pad2
        		TPad *pad2 = new TPad("pad2", "pad2", 0, 0.05, 1, 0.3);
        		pad2->SetTopMargin(0);
        		pad2->SetBottomMargin(0.2);
        		pad2->SetGridx(); // vertical grid
        		pad2->Draw();
        		pad2->cd();       // pad2 becomes the current pad

        		TH1F *h3 = (TH1F*)h1->Clone("h3");
        		h3->SetLineColor(kBlack);
        		h3->SetMarkerSize(0.1);
        		h3->Sumw2();
        		h3->SetStats(0);      // No statistics on lower plot
        		Double_t factor = (h2->GetEntries())/(h1->GetEntries());
        		h3->Divide(h1,h2, factor, 1.);

        		h3->SetMarkerStyle(21);
        		double max = h3->GetMaximum();
        		double min = h3->GetMinimum();
        		h3->GetYaxis()->SetRangeUser(min,max);  // Define Y ..
        		h3->Draw("ep");       // Draw the ratio plot

        		h1->GetYaxis()->SetTitleSize(20);
        		h1->GetYaxis()->SetTitleFont(43);
        		h1->GetYaxis()->SetTitleOffset(1.55);


        		h3->GetYaxis()->SetTitle("ratio h1/h2 ");
        		h3->GetYaxis()->SetNdivisions(505);
        		h3->GetYaxis()->SetTitleSize(20);
        		h3->GetYaxis()->SetTitleFont(43);
        		h3->GetYaxis()->SetTitleOffset(1.55);
        		h3->GetYaxis()->SetLabelFont(43); // Absolute font size in pixel (precision 3)
        		h3->GetYaxis()->SetLabelSize(15);

        		// X axis ratio plot settings
        		h3->GetXaxis()->SetTitle(title.str().replace(title.str().find("5"), 1, "").c_str());
        		h3->GetXaxis()->SetTitleSize(20);
        		h3->GetXaxis()->SetTitleFont(43);
        		h3->GetXaxis()->SetTitleOffset(4.);
        		h3->GetXaxis()->SetLabelFont(43); // Absolute font size in pixel (precision 3)
        		h3->GetXaxis()->SetLabelSize(15);

        		double w = h3->GetBinWidth(0);
        		int N = h3->GetNbinsX();
        		TLine *l = new TLine(0,0,0,0);
        		l->SetLineColor(kRed);
        		//l->DrawLine(h3->GetBinCenter(0)-0.49*w,1,h3->GetBinCenter(N)+0.5*w,1);
        		l->DrawLine(xlo,1,xhi,1);

        		c->cd();
        		pad1->cd();

        		if ((title.str().find("Pt"))< title.str().size()){
        		TLegend *leg = new TLegend(0.7,0.7,0.9,0.9);
        		leg->AddEntry(h1,"53X","l");
        		leg->AddEntry(h2,"53X unmatched","l");
        		leg->AddEntry(h3,"ratio","lep");
        		leg->Draw();
        		}else {
        		TLegend *leg = new TLegend(0.1,0.7,0.3,0.9);
        		leg->AddEntry(h1,"53X","l");
        		leg->AddEntry(h2,"53X unmatched","l");
        		leg->AddEntry(h3,"ratio","lep");
        		leg->Draw();
        		}

        		//	std::cout <<  << "	" <<  << std:: endl;

        		std::ostringstream saveas;
        		saveas << "Plots/" << h1->GetName()<<"_un.pdf" ;
        		c->Print(saveas.str().c_str());
        		std::cout <<"print" << std::endl;
        	}*/
        //PLOT DELTA of 53X and 70X
        if( ( title.str().find( "diff" ) ) < title.str().size() ) {
            c->cd();
            h1->SetStats( 1 );        // No statistics on upper plot

            //std::string title2 = title.str().replace(title.str().find("5"), 1, "_diff");
            //TKey *k2 =(f1->GetKey(title2.c_str()));
            //	TH1 *h2 =(TH1*)k2->ReadObj();
            //	float w1 = h1->GetBinWidth(0);
            float xlo = 0;
            float xhi = 0;
            for( int n = 0 ; n < h1->GetNbinsX(); n++ ) {
                //std::cout << h1->GetBinContent(n) << std::endl;
                //if(n %1 ==0) std::cout << "test " << n << "	" << h1->GetBinCenter(n) << " " <<  h1->GetBinContent(n) << std::endl;
                if( h1->GetBinContent( n ) < h1->GetEntries() / 100 ) {continue ;}
                xlo = h1->GetBinCenter( n - 1 );
                break;
            }

            for( int n = h1->GetNbinsX();  n > -1 * h1->GetNbinsX()  ;  n-- ) {
                //std::cout << h1->GetBinContent(n) << std::endl;
                if( h1->GetBinContent( n ) < h1->GetEntries() / 100 ) { continue; }
                xhi = h1->GetBinCenter( n + 1 );
                break;
            }

            xlo = std::max( std::fabs( xlo ), std::fabs( xhi ) );
            xhi = xlo;
            xlo = -xlo;
            //std::cout << xlo << "	" << xhi << std::endl;;
            h1->GetXaxis()->SetRangeUser( xlo, xhi );
            //	h1->DrawNormalized("h");

            h1->GetXaxis()->SetTitle( title.str().replace( title.str().find( "_diff" ), 5, "" ).insert( 0, "#Delta" ).c_str() );

            h1->GetYaxis()->SetTitleSize( 20 );
            h1->GetYaxis()->SetTitleFont( 43 );
            h1->GetYaxis()->SetTitleOffset( 1.55 );
            h1->Draw( "h" );
            gPad->Update();
            TPaveStats *st = ( TPaveStats * )h1->FindObject( "stats" );
            st->SetX1NDC( 0.1 );
            st->SetX2NDC( 0.3 );
            st->SetY1NDC( 0.7 );
            st->SetY2NDC( 0.9 );

            //	std::cout <<  << "	" <<  << std:: endl;

            std::ostringstream saveas;
            saveas << "Plots/" << h1->GetName() << ".pdf" ;
            c->Print( saveas.str().c_str() );
            std::cout << "print" << std::endl;
            c->Clear();
        }
    }
    //  c.Print("hsimple.ps]");
}
Beispiel #11
0
void rulevisHists( TDirectory *rfdir, TDirectory *vardir, TDirectory *corrdir, TMVAGlob::TypeOfPlot type) {
   //
   if (rfdir==0)   return;
   if (vardir==0)  return;
   if (corrdir==0) return;
   //
   const TString rfName    = rfdir->GetName();
   const TString maintitle = rfName + " : Rule Importance";
   const TString rfNameOpt = "_RF2D_";
   const TString outfname[TMVAGlob::kNumOfMethods] = { "rulevisHists",
                                                       "rulevisHists_decorr",
                                                       "rulevisCorr_pca",
                                                       "rulevisCorr_gaussdecorr" };

   const TString outputName = outfname[type]+"_"+rfdir->GetName();
   //
   TIter rfnext(rfdir->GetListOfKeys());
   TKey *rfkey;
   Double_t rfmax;
   Double_t rfmin;
   Bool_t allEmpty=kTRUE;
   Bool_t first=kTRUE;
   while ((rfkey = (TKey*)rfnext())) {
      // make sure, that we only look at histograms
      TClass *cl = gROOT->GetClass(rfkey->GetClassName());
      if (!cl->InheritsFrom("TH2F")) continue;
      TH2F *hrf = (TH2F*)rfkey->ReadObj();
      TString hname= hrf->GetName();
      if (hname.Contains("__RF_")){ // found a new RF plot
         Double_t valmin = hrf->GetMinimum();
         Double_t valmax = hrf->GetMaximum();
         if (first) {
            rfmin=valmin;
            rfmax=valmax;
            first = kFALSE;
         } else {
            if (valmax>rfmax) rfmax=valmax;
            if (valmin<rfmin) rfmin=valmin;
         }
         if (hrf->GetEntries()>0) allEmpty=kFALSE;
      }
   }
   if (first) {
      cout << "ERROR: no RF plots found..." << endl;
      return;
   }

   const Int_t nContours = 100;
   Double_t contourLevels[nContours];
   Double_t dcl = (rfmax-rfmin)/Double_t(nContours-1);
   //
   for (Int_t i=0; i<nContours; i++) {
      contourLevels[i] = rfmin+dcl*Double_t(i);
   }

   ///////////////////////////
   vardir->cd();
 
   // how many plots are in the directory?
   Int_t noPlots = ((vardir->GetListOfKeys())->GetEntries()) / 2;
 
   // 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 = 500; height = 0.7*width; break;
   case 2:
      xPad = 2; yPad = 1; width = 600; height = 0.7*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.7*width; break;
   }
   Int_t noPad = xPad * yPad ;   

   // this defines how many canvases we need
   const Int_t noCanvas = 1 + (Int_t)((noPlots - 0.001)/noPad);
   TCanvas **c = new TCanvas*[noCanvas];
   for (Int_t ic=0; ic<noCanvas; ic++) c[ic] = 0;

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

   // loop over all objects in directory
   TIter next(vardir->GetListOfKeys());
   TKey *key;
   TH1F *sigCpy=0;
   TH1F *bgdCpy=0;
   //
   Bool_t first = kTRUE;

   while ((key = (TKey*)next())) {

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

      // check for all signal histograms
      if (hname.Contains("__S")){ // found a new signal plot
         //         sigCpy = new TH1F(*sig);
         // create new canvas
         if ((c[countCanvas]==NULL) || (countPad>noPad)) {
            char cn[20];
            sprintf( cn, "rulehist%d_", countCanvas+1 );
            TString cname(cn);
            cname += rfdir->GetName();
            c[countCanvas] = new TCanvas( cname, maintitle,
                                          countCanvas*50+200, countCanvas*20, width, height ); 
            // style
            c[countCanvas]->Divide(xPad,yPad);
            countPad = 1;
         }       

         // save canvas to file
         TPad *cPad = (TPad *)(c[countCanvas]->GetPad(countPad));
         c[countCanvas]->cd(countPad);
         countPad++;

         // find the corredponding background histo
         TString bgname = hname;
         bgname.ReplaceAll("__S","__B");
         hkey = vardir->GetKey(bgname);
         bgd = (TH1F*)hkey->ReadObj();
         if (bgd == NULL) {
            cout << "ERROR!!! couldn't find backgroung histo for" << hname << endl;
            exit;
         }

         TString rfname = hname;
         rfname.ReplaceAll("__S","__RF");
         TKey *hrfkey = rfdir->GetKey(rfname);
         TH2F *hrf = (TH2F*)hrfkey->ReadObj();
         Double_t wv = hrf->GetMaximum();
         //         if (rfmax>0.0)
         //            hrf->Scale(1.0/rfmax);
         hrf->SetMinimum(rfmin); // make sure it's zero  -> for palette axis
         hrf->SetMaximum(rfmax); // make sure max is 1.0 -> idem
         hrf->SetContour(nContours,&contourLevels[0]);

         // this is set but not stored during plot creation in MVA_Factory
         //         TMVAGlob::SetSignalAndBackgroundStyle( sigK, bgd );
         sig->SetFillStyle(3002);
         sig->SetFillColor(1);
         sig->SetLineColor(1);
         sig->SetLineWidth(2);

         bgd->SetFillStyle(3554);
         bgd->SetFillColor(1);
         bgd->SetLineColor(1);
         bgd->SetLineWidth(2);

         // chop off "signal" 
         TString title(hrf->GetTitle());
         title.ReplaceAll("signal","");

         // finally plot and overlay       
         Float_t sc = 1.1;
         if (countPad==2) sc = 1.3;
         sig->SetMaximum( TMath::Max( sig->GetMaximum(), bgd->GetMaximum() )*sc );
         Double_t smax = sig->GetMaximum();

         if (first) {
            hrf->SetTitle( maintitle );
            first = kFALSE;
         } else {
            hrf->SetTitle( "" );
         }
         hrf->Draw("colz ah");
         TMVAGlob::SetFrameStyle( hrf, 1.2 );

         sig->Draw("same ah");
         bgd->Draw("same ah");
         // draw axis using range [0,smax]
         hrf->GetXaxis()->SetTitle( title );
         hrf->GetYaxis()->SetTitleOffset( 1.30 );
         hrf->GetYaxis()->SetTitle("Events");
         hrf->GetYaxis()->SetLimits(0,smax);
         hrf->Draw("same axis");

         cPad->SetRightMargin(0.13);
         cPad->Update();

         // Draw legend
         if (countPad==2){
            TLegend *legend= new TLegend( cPad->GetLeftMargin(), 
                                          1-cPad->GetTopMargin()-.18, 
                                          cPad->GetLeftMargin()+.4, 
                                          1-cPad->GetTopMargin() );
            legend->AddEntry(sig,"Signal","F");
            legend->AddEntry(bgd,"Background","F");
            legend->Draw("same");
            legend->SetBorderSize(1);
            legend->SetMargin( 0.3 );
            legend->SetFillColor(19);
            legend->SetFillStyle(1);
         } 

         // save canvas to file
         if (countPad > noPad) {
            c[countCanvas]->Update();
            TString fname = Form( "plots/%s_c%i", outputName.Data(), countCanvas+1 );
            TMVAGlob::imgconv( c[countCanvas], fname );
            //        TMVAGlob::plot_logo(); // don't understand why this doesn't work ... :-(
            countCanvas++;
         }
      }
   }

   if (countPad <= noPad) {
      c[countCanvas]->Update();
      TString fname = Form( "plots/%s_c%i", outputName.Data(), countCanvas+1 );
      TMVAGlob::imgconv( c[countCanvas], fname );
   }
}
Beispiel #12
0
void addcanvases(){
  fSavePath = "data/perfLL";
  const Int_t narr = 20;
  gStyle->SetOptStat(0); 
  gStyle->SetOptTitle(0); 

  TFile *f1 = TFile::Open("c_l3.root");
  TIter next1(f1->GetListOfKeys());
  TKey *key1;
  Int_t it1 = 0;
  TCanvas *carr1[narr];

  while((key1 = (TKey*)next1())) {
    TClass *cl = gROOT->GetClass(key1->GetClassName());
    if (!cl->InheritsFrom("TCanvas")) continue;
    carr1[it1] = (TCanvas*)key1->ReadObj();
    it1++;
  }

  TFile *f2 = TFile::Open("c_l0.root");
  TIter next2(f2->GetListOfKeys());
  TKey *key2;
  Int_t it2 = 0;
  TCanvas *carr2[narr];

  while ((key2 = (TKey*)next2())) {
    TClass *cl = gROOT->GetClass(key2->GetClassName());
    if (!cl->InheritsFrom("TCanvas")) continue;
    carr2[it2] = (TCanvas*)key2->ReadObj();
    it2++;
  }

  TLegend *leg = new TLegend(0.2,0.7,0.5,0.9);
  leg->SetFillColor(0);
  leg->SetFillStyle(0);
  leg->SetBorderSize(0);


  for(Int_t i=0; i<it2; i++){
    carr1[i]->Draw();
    //leg->AddEntry( carr1[i],"3x3 full coverage","l");
    //leg->Draw();
    canvasAdd(carr1[i]);
    TIter next(carr2[i]->GetListOfPrimitives());
    TObject *obj;

    while((obj = next())){
      // if(obj->InheritsFrom("TH1F")){
      // 	TH1F *h = (TH1F*)obj;
      // 	std::cout<<"name "<< h->GetName() <<std::endl;      
      // 	h->SetLineStyle(7);
      // 	h->SetLineWidth(2);
      //   h->Draw("same");
      // }
      if(obj->InheritsFrom("TGraph")){
	TGraph *h = (TGraph*)obj;
	std::cout<<"name "<< h->GetName() <<std::endl;      
	h->SetLineColor(32);
	h->SetMarkerColor(2);
	//	h->SetLineWidth(2);
        h->Draw("same PL");
	// leg->AddEntry(h,"6.5x6.5 MCP PMTs coverage","lp");
	// leg->Draw();
      }

    }
  }
  std::cout<<"save all  " <<std::endl;
  
  canvasSave(0,1);
}
Beispiel #13
0
void presyst(TString s) {
    TFile * fin = TFile::Open("graphs_"+ s +".root");
    TList * l = fin->GetListOfKeys();
    TCanvas C("C", "C", 3, 58, 1185, 658);
    C.Divide(3,1);
    TGraphAsymmErrors * gra = 0;
    TGraphErrors * gr = 0;
    //Loop for line
    Int_t I = 0;
    TKey *key3;
    TIter nextkey3(fin->GetListOfKeys());
    while ((key3 = (TKey*) nextkey3())) {
        const char *classname = key3->GetClassName();
        TClass *cl = gROOT->GetClass(classname);
        if (!cl) continue;
        if (!cl->InheritsFrom(TGraphAsymmErrors::Class()))
            continue;
        gra = (TGraphAsymmErrors*) fin->Get(key3->GetName());
        C.cd(I + 1);
        gra->Draw("alp");
        I++;
    }
    
    TKey *key;
    TIter nextkey(fin->GetListOfKeys());
    //Loop for stat uncertainty
    Int_t nStat = 0;
    I = 0;
    while ((key = (TKey*) nextkey())) {
        const char *classname = key->GetClassName();
        TClass *cl = gROOT->GetClass(classname);
        if (!cl) continue;
        if (cl->InheritsFrom(TGraphAsymmErrors::Class()))
            continue;
        nStat++;
        gr = (TGraphErrors*) fin->Get(key->GetName());
        gr->SetMarkerColor(kRed);
        gr->SetLineWidth(2);
        gr->SetLineColor(kBlue);
        C.cd(I + 1);
        gr->Draw("p");
        I++;
    }

    //Loop for syst uncertainty
    I = 0;
    TKey *key2;
    TIter nextkey2(fin->GetListOfKeys());

    while ((key2 = (TKey*) nextkey2())) {
        const char *classname = key2->GetClassName();
        TClass *cl = gROOT->GetClass(classname);
        if (!cl) continue;
        if (!cl->InheritsFrom(TGraphAsymmErrors::Class()))
            continue;
        gra = (TGraphAsymmErrors*) fin->Get(key2->GetName());
        gra->SetMarkerColor(kRed);
        gra->SetLineWidth(2);
        gra->SetLineColor(kGreen);
        //        gra->SetLineStyle(kDashed);
        gra->SetMarkerStyle(4);
        C.cd(I + 1);
        gra->Draw("p|>");
        I++;
    }

    C.SaveAs(s + "_figs.gif");
}
Beispiel #14
0
//-----------------------------------------------------------------------------
StatusCode
RootHistCnv::RDirectoryCnv::fillObjRefs(IOpaqueAddress* pAddr,DataObject* pObj)  {
  MsgStream log(msgSvc(), "RDirectoryCnv");
  IRegistry* pReg = pObj->registry();
  std::string full  = pReg->identifier();
  const std::string& fname = pAddr->par()[0];

  TFile *tf;
  findTFile(full,tf).ignore();

  // cd to TFile:
  setDirectory(full);
  TIter nextkey(gDirectory->GetListOfKeys());
  while (TKey *key = (TKey*)nextkey()) {
    IOpaqueAddress* pA = 0;
    TObject *obj = key->ReadObj();
    std::string title = obj->GetTitle();
    std::string sid = obj->GetName();
    std::string f2 = full + "/" + sid;
    int idh = ::strtol(sid.c_str(),NULL,10);
    // introduced by Grigori Rybkine
    std::string clname = key->GetClassName();
    std::string clnm = clname.substr(0,3);
    TClass* isa = obj->IsA();
    if (isa->InheritsFrom("TTree")) {
      createAddress(full, CLID_ColumnWiseTuple, idh, obj, pA).ignore();
      TTree* tree = (TTree*) obj;
      tree->Print();
      log << MSG::DEBUG << "Reg CWNT \"" << obj->GetTitle()
       	  << "\" as " << f2 << endmsg;
      title = "/" + sid;
    } else if (isa->InheritsFrom("TDirectory")) {
      createAddress(full,CLID_NTupleDirectory, title, obj, pA).ignore();
    } else if ( isa == TProfile::Class() ) {
      createAddress(full,CLID_ProfileH,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TProfile2D::Class() ) {
      createAddress(full,CLID_ProfileH2,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH1C::Class() ) {
      createAddress(full,CLID_H1D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH1S::Class() ) {
      createAddress(full,CLID_H1D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH1I::Class() ) {
      createAddress(full,CLID_H1D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH1F::Class() ) {
      createAddress(full,CLID_H1D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH1D::Class() ) {
      createAddress(full,CLID_H1D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH2C::Class() ) {
      createAddress(full,CLID_H2D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH2S::Class() ) {
      createAddress(full,CLID_H2D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH2I::Class() ) {
      createAddress(full,CLID_H2D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH2F::Class() ) {
      createAddress(full,CLID_H2D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH2D::Class() ) {
      createAddress(full,CLID_H2D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH3C::Class() ) {
      createAddress(full,CLID_H3D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH3S::Class() ) {
      createAddress(full,CLID_H3D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH3I::Class() ) {
      createAddress(full,CLID_H3D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH3F::Class() ) {
      createAddress(full,CLID_H3D,idh,obj,pA).ignore();
      title = sid;
    } else if ( isa == TH3D::Class() ) {
      createAddress(full,CLID_H3D,idh,obj,pA).ignore();
      title = sid;
    } else {
      log << MSG::ERROR << "Encountered an unknown object with key: "
      	  << obj->GetName() << " in ROOT file " << fname << endmsg;
      return StatusCode::FAILURE;
    }
    if ( 0 != pA )    {
      StatusCode sc = dataManager()->registerAddress(pReg, title, pA);
      if ( !sc.isSuccess() )  {
        log << MSG::ERROR << "Failed to register address for " << full  << endmsg;
        return sc;
      }
      log << MSG::VERBOSE << "Created address for " << clnm
          << "'" << title << "' in " << full << endmsg;
    }
  }
  return StatusCode::SUCCESS;
}
Beispiel #15
0
//_____________________________________________________________________________________________________//
KVIDGrid* KVIDTelescope::CalculateDeltaE_EGrid(const Char_t* Zrange, Int_t deltaA, Int_t npoints, Double_t lifetime, UChar_t massformula, Double_t xfactor)
{
   //Genere une grille dE-E (perte d'energie - energie residuelle) pour une gamme en Z donnee
   // - Zrange definit l'ensemble des charges pour lequel les lignes vont etre calculees
   // - deltaA permet de definir si a chaque Z n'est associee qu'un seul A (deltaA=0) ou plusieurs
   //Exemple :
   //      deltaA=1 -> Aref-1, Aref et Aref+1 seront les masses associees a chaque Z et
   //      donc trois lignes de A par Z. le Aref pour chaque Z est determine par
   //      la formule de masse par defaut (Aref = KVNucleus::GetA() voir le .kvrootrc)
   //      deltaA=0 -> pour chaque ligne de Z le A associe sera celui de KVNucleus::GetA()
   // - est le nombre de points par ligne
   //
   //un noyau de A et Z donne n'est considere que s'il retourne KVNucleus::IsKnown() = kTRUE
   //
   if (GetSize() <= 1) return 0;

   KVNumberList nlz(Zrange);

   TClass* cl = TClass::GetClass(GetDefaultIDGridClass());
   if (!cl || !cl->InheritsFrom("KVIDZAGrid")) cl = TClass::GetClass("KVIDZAGrid");
   KVIDGrid* idgrid = (KVIDGrid*)cl->New();

   idgrid->AddIDTelescope(this);
   idgrid->SetOnlyZId((deltaA == 0));

   KVDetector* det_de = GetDetector(1);
   if (!det_de)      return 0;
   KVDetector* det_eres = GetDetector(2);
   if (!det_eres)    return 0;

   KVNucleus part;
   Info("CalculateDeltaE_EGrid",
        "Calculating dE-E grid: dE detector = %s, E detector = %s",
        det_de->GetName(), det_eres->GetName());

   KVIDCutLine* B_line = (KVIDCutLine*)idgrid->Add("OK", "KVIDCutLine");
   Int_t npoi_bragg = 0;
   B_line->SetName("Bragg_line");
   B_line->SetAcceptedDirection("right");

   Double_t SeuilE = 0.1;

   nlz.Begin();
   while (!nlz.End()) {
      Int_t zz = nlz.Next();
      part.SetZ(zz, massformula);
      Int_t aref = part.GetA();
//        printf("%d\n",zz);
      for (Int_t aa = aref - deltaA; aa <= aref + deltaA; aa += 1) {
         part.SetA(aa);
//            printf("+ %d %d %d\n",aa,aref,part.IsKnown());
         if (part.IsKnown() && (part.GetLifeTime() > lifetime)) {

            //loop over energy
            //first find :
            //  ****E1 = energy at which particle passes 1st detector and starts to enter in the 2nd one****
            //      E2 = energy at which particle passes the 2nd detector
            //then perform npoints calculations between these two energies and use these
            //to construct a KVIDZALine

            Double_t E1, E2;
            //find E1
            //go from SeuilE MeV to det_de->GetEIncOfMaxDeltaE(part.GetZ(),part.GetA()))
            Double_t E1min = SeuilE, E1max = det_de->GetEIncOfMaxDeltaE(zz, aa);
            E1 = (E1min + E1max) / 2.;

            while ((E1max - E1min) > SeuilE) {

               part.SetEnergy(E1);
               det_de->Clear();
               det_eres->Clear();

               det_de->DetectParticle(&part);
               det_eres->DetectParticle(&part);
               if (det_eres->GetEnergy() > SeuilE) {
                  //particle got through - decrease energy
                  E1max = E1;
                  E1 = (E1max + E1min) / 2.;
               } else {
                  //particle stopped - increase energy
                  E1min = E1;
                  E1 = (E1max + E1min) / 2.;
               }
            }

            //add point to Bragg line
            Double_t dE_B = det_de->GetMaxDeltaE(zz, aa);
            Double_t E_B = det_de->GetEIncOfMaxDeltaE(zz, aa);
            Double_t Eres_B = det_de->GetERes(zz, aa, E_B);
            B_line->SetPoint(npoi_bragg++, Eres_B, dE_B);

            //find E2
            //go from E1 MeV to maximum value where the energy loss formula is valid
            Double_t E2min = E1, E2max = det_eres->GetEmaxValid(part.GetZ(), part.GetA());
            E2 = (E2min + E2max) / 2.;

            while ((E2max - E2min > SeuilE)) {

               part.SetEnergy(E2);
               det_de->Clear();
               det_eres->Clear();

               det_de->DetectParticle(&part);
               det_eres->DetectParticle(&part);
               if (part.GetEnergy() > SeuilE) {
                  //particle got through - decrease energy
                  E2max = E2;
                  E2 = (E2max + E2min) / 2.;
               } else {
                  //particle stopped - increase energy
                  E2min = E2;
                  E2 = (E2max + E2min) / 2.;
               }
            }
            E2 *= xfactor;
            if ((!strcmp(det_eres->GetType(), "CSI")) && (E2 > 5000)) E2 = 5000;
//                printf("z=%d a=%d E1=%lf E2=%lf\n",zz,aa,E1,E2);
            KVIDZALine* line = (KVIDZALine*)idgrid->Add("ID", "KVIDZALine");
            if (TMath::Even(zz)) line->SetLineColor(4);
            line->SetZ(zz);
            line->SetA(aa);

            Double_t logE1 = TMath::Log(E1);
            Double_t logE2 = TMath::Log(E2);
            Double_t dLog = (logE2 - logE1) / (npoints - 1.);

            for (Int_t i = 0; i < npoints; i++) {
               //              Double_t E = E1 + i*(E2-E1)/(npoints-1.);
               Double_t E = TMath::Exp(logE1 + i * dLog);

               Double_t Eres = 0.;
               Int_t niter = 0;
               while (Eres < SeuilE && niter <= 20) {
                  det_de->Clear();
                  det_eres->Clear();

                  part.SetEnergy(E);

                  det_de->DetectParticle(&part);
                  det_eres->DetectParticle(&part);

                  Eres = det_eres->GetEnergy();
                  E += SeuilE;
                  niter += 1;
               }
               if (!(niter > 20)) {
                  Double_t dE = det_de->GetEnergy();
                  Double_t gEres, gdE;
                  line->GetPoint(i - 1, gEres, gdE);
                  line->SetPoint(i, Eres, dE);

               }
            }
            //printf("sort de boucle points");
         }
      }
   }

   return idgrid;

}
Beispiel #16
0
 bool recognize(const std::string& typeName)
 {
     TClass* klass = TClass::GetClass(typeName.c_str());
     return klass && klass->InheritsFrom("TCollection");
 }
void loopPlot(){

  gErrorIgnoreLevel=kFatal;//suppresses all info messages
  setTDRStyle();//TDR style
  
  
  //#####################EDIT THE OPTIONS##############################
  /// Boolean flags to steer the histogram making
  bool wantElectrons = false; // Will make histograms for electrons
  bool wantMuons     = true; // Will make histograms for muons
  bool wantSideband  = false; // Will make histograms for sideband region
  bool wantSignal    = true; // Will make histograms for signal region
  bool wantFullRange = false; // Will not check signal or sideband, ie, pick all jet mass range
  int  wantNXJets    = 1; // Will make histograms for 1 or 2 jet topology
  int  isZZchannel   = 1; //plot label for zz (1) or ww (0)
  int  flavour = 0; 
  if(wantElectrons) flavour=11; if(wantMuons) flavour=13;
  
  /// Luminosity value in pb^-1
  //double lumiValue = 19531.85;// for singleEle2012
  //  double lumiValue = 19747; // for doubleMu2012
  //double lumiValue = 19788; // for doubleEle2012
  double lumiValue = 19768.0; 
  /// Should we scale the histograms to data?
  bool scaleToData = false;
  // Should we scale only wjets to make total MC = DATA?
  bool scaleOnlyWJets = false;
  /// Should we plot the Data/Bkg and Data-Bkg/Error ratios?
  bool makeRatio = false;
  /// Should we REDO histograms?
  bool redoHistograms = true;
  /// Should we put the signal MC stacked on top of the background (or just plot the signal alone)?
  bool isSignalStackOnBkg = false;

  /// Path to wherever the files with the trees are. 
  //CA8 (cmgTuple_08032013_CA8)

  std::string pathToTrees="/afs/cern.ch/user/b/bonato/scratch0/PhysAnalysis/EXOVV_2012/analyzer_trees/productionv2i/fullsig/";

  /// Path to wherever you want to put the histograms (figures) in.
  std::string outputDir = "./plots_productionv2i_fullsig_1JLP_MU";
 

  /// Setup names of data files for trees.
 
  
 const int nDATA=4;
 std::string dataLabels[nDATA]={"DoubleMu_Run2012A_22Jan2013",
				"DoubleMuParked_Run2012B_22Jan2013",
				"DoubleMuParked_Run2012C_22Jan2013",
				"DoubleMuParked_Run2012D_22Jan2013"};
  /*
  
  const int nDATA=4;//set to zero if you don't want to plot
  std::string dataLabels[nDATA]={"Photon_Run2012A_22Jan2013",
                                "DoublePhotonHighPt_Run2012B_22Jan2013",
                                "DoublePhotonHighPt_Run2012C_22Jan2013",
                                "DoublePhotonHighPt_Run2012D_22Jan2013"
				};
  */

  /*
  const int nDATA=8;//set to zero if you don't want to plot
  std::string dataLabels[nDATA]={"DoubleMu_Run2012A_22Jan2013",
				"DoubleMuParked_Run2012B_22Jan2013",
				"DoubleMuParked_Run2012C_22Jan2013",
				 "DoubleMuParked_Run2012D_22Jan2013",
				 "Photon_Run2012A_22Jan2013",
                                "DoublePhotonHighPt_Run2012B_22Jan2013",
                                "DoublePhotonHighPt_Run2012C_22Jan2013",
                                "DoublePhotonHighPt_Run2012D_22Jan2013"
				};
  */
  
/* 
  const int nDATA=7;//set to zero if you don't want to plot
  std::string dataLabels[nDATA]={"SingleElectron_Run2012A_13Jul2012_xww",
				 "SingleElectron_Run2012A_recover_xww",
				 "SingleElectron_Run2012B_13Jul2012_xww",
				 "SingleElectron_Run2012C_24Aug2012_xww",
				 "SingleElectron_Run2012C_PromptReco_xww",
				 "SingleElectron_Run2012C_EcalRecove_xww",
				 "SingleElectron_Run2012D_PromptReco_xww"};  


   const int nDATA=7;//set to zero if you don't want to plot
  std::string dataLabels[nDATA]={"SingleMu_Run2012A_13Jul2012_xww",
                 "SingleMu_Run2012A_recover_xww",
                 "SingleMu_Run2012B_13Jul2012_xww",
                 "SingleMu_Run2012C_24Aug2012_xww",
                 "SingleMu_Run2012C_PromptReco_xww",
                 "SingleMu_Run2012C_EcalRecove_xww",
                 "SingleMu_Run2012D_PromptReco_xww"};
*/

/*
  const int nDATA=1;//set to zero if you don't want to plot
  std::string dataLabels[nDATA]={"data_xww"};
*/

/*   
  const int nDATA=0;//set to zero if you don't want to plot
  std::string dataLabels[nDATA]={};
 */

  std::vector<std::string> fData;
  for(int ii=0;ii<nDATA;ii++){
    fData.push_back(pathToTrees+"treeEDBR_"+dataLabels[ii]+".root");
  }

  /// Setup names of MC files for trees.

  const int nMC=6;//set to zero if you don't want to plot
  std::string mcLabels[nMC]={"TTBARpowheg",
			     "WW",
			     "WZ",
			     "ZZ",
			     "DYJetsPt70To100",
			     "DYJetsPt100",
  };
  double kFactorsMC_array[nMC] = {1, 1, 1, 1, 1, 1};
  
  /*
  const int nMC=7;//set to zero if you don't want to plot
  std::string mcLabels[nMC]={"TTBARpowheg",
			     "WW",
			     "WZ",
			     "ZZ",
			     "DYJetsPt50To70",
			     "DYJetsPt70To100",
			     "DYJetsPt100"};
  double kFactorsMC_array[nMC] = {1., 1., 1., 1., 1., 1., 1.};
  */  

  
  /*
  const int nMC=5;//set to zero if you don't want to plot
  std::string mcLabels[nMC]={//"TTBAR_xww",
                               "TTBARpowheg_xww",
			     //"SingleTopBarTWchannel_xww",
			     //"SingleTopTWchannel_xww",
			     //"SingleTopBarSchannel_xww", 
			     //"SingleTopSchannel_xww",
			     //"SingleTopBarTchannel_xww",
			     //"SingleTopTchannel_xww",
				"SingleTop_xww",
			     //"WW_xww",
			     //"WZ_xww",
			     //"ZZ_xww",
				"VV_xww",
			     //"DYJetsPt50To70_xww",
			     //"DYJetsPt70To100_xww",
			     //"DYJetsPt100_xww",
				"DYJets_xww",
			     //"WJetsPt50To70_xww",
			     //"WJetsPt70To100_xww",
			     // "WJetsPt180_xww",
			        "WJetsPt100_xww",
			     };
  */
  //WW, muon channel
  //double kFactorsMC_array[nMC] = {1, 1., 1., 1., 1.3};
  //WW, electron channel

  std::vector<std::string> fMC;
  for(int ii=0;ii<nMC;ii++){
    fMC.push_back(pathToTrees+"treeEDBR_"+mcLabels[ii]+".root");
  }

  std::vector<double> kFactorsMC;
  //std::cout << "The contents of kFactorsMC are:" << std::endl;
  for (int index=0; index<nMC; index++)
    {
      //std::cout << kFactorsMC_array[index] << std::endl;
      kFactorsMC.push_back( kFactorsMC_array[index] );	
    }

  /// Setup names of MC signal files for trees.
  const int nMCSig=1;//set to zero if you don't want to plot
  std::string mcLabelsSig[nMCSig]={"BulkG_ZZ_lljj_c0p2_M1000"
				   //"BulkG_WW_lvjj_c0p2_M1000_xww",				   
                                   //"BulkG_WW_lvjj_c0p2_M2000_xww"				   
                                  };
  double kFactorsSig_array[nMCSig] = {1000.0};


  std::vector<double> kFactorsMCSig;
  for (int index=0; index<nMCSig; index++)
    {
      kFactorsMCSig.push_back( kFactorsSig_array[index] );	
    }
  
  /*
  const int nMCSig=1;//set to zero if you don't want to plot
  std::string mcLabelsSig[nMCSig]={"BulkG_ZZ_lljj_c1p0_M1500"};
  */
  
  std::vector<std::string> fMCSig;
  for(int ii=0;ii<nMCSig;ii++){
    fMCSig.push_back(pathToTrees+"treeEDBR_"+mcLabelsSig[ii]+".root");
  }

  /// Setup names of files for histograms (data and MC)
  std::vector<std::string> fHistosData;
  std::vector<std::string> fHistosMC;
  std::vector<std::string> fHistosMCSig;
 
  char buffer[256];
  printf("All strings set\n");


  /// ----------------------------------------------------------------
  /// This first part is the loop over trees to create histogram files 
  /// ----------------------------------------------------------------

  /// The EDBRHistoMaker, for reference
  ///
  ///EDBRHistoMaker::EDBRHistoMaker(TTree* tree, 
  ///		       bool wantElectrons,
  ///		       bool wantMuons,
  ///		       bool wantSideband,
  ///		       bool wantSignal,
  ///		       int  wantNXJets,
  ///              bool isZZchannel)

  printf("\nStart making histograms\n\n");

  //loop over data files and make histograms individually for each of them
  for(int i=0;i<nDATA;i++){

    std::cout<<"\n-------\nRunning over "<<dataLabels[i].c_str()<<std::endl;
    std::cout<<"The file is " <<fData.at(i)<<std::endl;
    sprintf(buffer,"histos_%s.root",dataLabels[i].c_str());
    fHistosData.push_back(buffer);
    
    if(redoHistograms) {
      TFile *fileData = TFile::Open(fData.at(i).c_str());
      TTree *treeData = (TTree*)fileData->Get("SelectedCandidates");
      EDBRHistoMaker* maker = new EDBRHistoMaker(treeData, 
						 wantElectrons,
						 wantMuons,
						 wantSideband,
						 wantSignal,
						 wantFullRange,
						 wantNXJets,
						 isZZchannel);
      maker->setUnitaryWeights(true);
      maker->Loop(buffer);
      //delete maker; // This class is badly written and deleting it isn't safe!
      fileData->Close();
    }
    
  }//end loop on data files

  printf("Loop over data done\n");
 
  //loop over MC files and make histograms individually for each of them
  for(int i=0;i<nMC;i++){
    std::cout<<"\n-------\nRunning over "<<mcLabels[i].c_str()<<std::endl;
    std::cout<<"The file is " <<fMC.at(i)<<std::endl;    
    sprintf(buffer,"histos_%s.root",mcLabels[i].c_str());
    fHistosMC.push_back(buffer);
    
    if(redoHistograms){
      TFile *fileMC = TFile::Open(fMC.at(i).c_str());
      TTree *treeMC = (TTree*)fileMC->Get("SelectedCandidates");
      EDBRHistoMaker* maker = new EDBRHistoMaker(treeMC, 
						 wantElectrons, 
						 wantMuons, 
						 wantSideband, 
						 wantSignal, 
						 wantFullRange,
						 wantNXJets,
						 isZZchannel);
      maker->setUnitaryWeights(false);
      maker->Loop(buffer);
      //delete maker; // This class is badly written and deleting it isn't safe!
      fileMC->Close();
    }
    
  }//end loop on MC files

  printf("Loop over MC done\n");

  //loop over MC signal files and make histograms individually for each of them
  for(int i=0;i<nMCSig;i++){
    std::cout<<"\n-------\nRunning over "<<mcLabelsSig[i].c_str()<<std::endl;
    std::cout<<"The file is " <<fMCSig.at(i)<<std::endl;    
    sprintf(buffer,"histos_%s.root",mcLabelsSig[i].c_str());
    fHistosMCSig.push_back(buffer);
    
    if(redoHistograms){
      TFile *fileMCSig = TFile::Open(fMCSig.at(i).c_str());
      TTree *treeMCSig = (TTree*)fileMCSig->Get("SelectedCandidates");
      EDBRHistoMaker* maker = new EDBRHistoMaker(treeMCSig, 
						 wantElectrons, 
						 wantMuons, 
						 wantSideband, 
						 wantSignal, 
						 wantFullRange,
						 wantNXJets,
						 isZZchannel);
      maker->setUnitaryWeights(false);
      maker->Loop(buffer);
      //delete maker; // This class is badly written and deleting it isn't safe!
      fileMCSig->Close();
    }
    
  }//end loop on MC files

  printf("Loop over MC signal done\n");
  
  /// ------------------------------------------------------------------
  /// This second part is the loop over histograms to create stack plots
  /// ------------------------------------------------------------------  

  //  EDBRHistoMaker::EDBRHistoMaker(TTree* tree,
  //			 bool wantElectrons,
  //			 bool wantMuons,
  //			 bool wantSideband,
  //			 bool wantSignal,
  //			 int  wantNXJets,
  //			 bool isZZchannel){
    
  printf("\nStart looping over histograms\n\n");
  //make nice plots
  std::vector<std::string> listOfHistos;
  if(nMC>0){
    // Open one of the histogram files just to get the list of histograms
    // produced, then loop over all the histograms inheriting 
    // from TH1 contained in the file.
    sprintf(buffer,"histos_%s.root",mcLabels[0].c_str());
    std::cout<<"Opening "<<buffer<<std::endl;
    TFile* oneFile = TFile::Open(buffer);
    TIter next(oneFile->GetListOfKeys());
    TKey *key;
    
    while ((key = (TKey*)next())) {
      TClass *cl = gROOT->GetClass(key->GetClassName());
      if (!cl->InheritsFrom("TH1")) continue;
      TH1 *hTMP = (TH1*)key->ReadObj();
      std::string hName=hTMP->GetName();
      //  printf("Histogram found: %s\n",hName.c_str());
      if(hName=="h_mj_vs_mzz")continue;//skip 2D histos
      bool isMJJhisto=(hName.find("mJJ")!=std::string::npos);
      bool isMZZhisto=(hName.find("mZZ")!=std::string::npos);
      if( !isMJJhisto && !isMZZhisto)continue;//skip all histos except MJJ and MZZ
      listOfHistos.push_back(hName);
    }//end while loop
    oneFile->Close();
  }//end if fmc size >0

  EDBRHistoPlotter *plotter=new EDBRHistoPlotter("./",
						 fHistosData,
						 fHistosMC,
						 fHistosMCSig,
						 lumiValue,
						 wantNXJets,
						 flavour,
						 isZZchannel,
						 scaleToData,
						 scaleOnlyWJets,
						 makeRatio,
						 isSignalStackOnBkg,
						 kFactorsMC,kFactorsMCSig);
  std::cout<<"Set output dir"<<std::endl;
  plotter->setOutDir(outputDir);
  plotter->setDebug(false);

  //colors are assigned in the same order of mcLabels

  
  //For ZZ
  ////// {"TTBAR","WW","WZ","ZZ","DYJetsPt50To70","DYJetsPt70To100","DYJetsPt100","WJetsPt50To70","WJetsPt70To100","WJetsPt100"};
  std::vector<int> fColorsMC;
  fColorsMC.push_back(kGreen-3);
  //fColorsMC.push_back(kYellow-9);
  //fColorsMC.push_back(kYellow-6);
  //fColorsMC.push_back(kYellow-3);
  //fColorsMC.push_back(kYellow+3);
  //fColorsMC.push_back(kYellow+6);
  //fColorsMC.push_back(kYellow+9);
  fColorsMC.push_back(kMagenta-9);
  fColorsMC.push_back(kMagenta-6);
  fColorsMC.push_back(kMagenta-3);
  //fColorsMC.push_back(kBlue-3);
  fColorsMC.push_back(kBlue-6);
  fColorsMC.push_back(kBlue-9);
  //fColorsMC.push_back(kRed+3);
  //fColorsMC.push_back(kRed);
  //fColorsMC.push_back(kRed-4);
  
  //For WW
  //{ "TTBARpowheg_xww", "SingleTop_xww", "VV_xww", "DYJets_xww", "WJetsPt100_xww"}
  //std::vector<int> fColorsMC;
  //fColorsMC.push_back(kGreen-3);
  //fColorsMC.push_back(kYellow-9);
  //fColorsMC.push_back(kMagenta-9);
  //fColorsMC.push_back(kBlue-3);
  //fColorsMC.push_back(kRed-4);

  ////// {"BulkG_WW_lvjj_c1p0_M600_xww","BulkG_WW_lvjj_c1p0_M1000_xww","BulkG_WW_lvjj_c1p0_M1500_xww"};
  std::vector<int> fColorsMCSig;
  //  fColorsMCSig.push_back(kPink);
  fColorsMCSig.push_back(kOrange+7);
  fColorsMCSig.push_back(kMagenta);
  fColorsMCSig.push_back(kBlue+3);
  
  plotter->setFillColor(fColorsMC);
  plotter->setLineColor(fColorsMCSig);

  int numOfHistos = listOfHistos.size();
  for(int i = 0; i != numOfHistos; ++i) 
    plotter->makeStackPlots(listOfHistos.at(i));      

  printf("Plotting done\n");
    
  delete plotter;

}//end main
Beispiel #18
0
Bool_t fitsHere(TLegend *l,Double_t x1, Double_t y1, Double_t x2, Double_t y2)
{
    Bool_t fits = true;
    TList *list = l->GetListOfPrimitives();
    for (Int_t k = 0; list->At(k) != 0 && fits; k++)
    {
        TObject *obj = ((TLegendEntry*)(list->At(k)))->GetObject();
        if (obj == 0) continue;
        TClass *cl = obj->IsA();

        //Histogram, drawn as a histogram
        if (cl->InheritsFrom("TH1") && !cl->InheritsFrom("TH2") && !cl->InheritsFrom("TH3")
         && cl != TProfile::Class() && ((TH1*)obj)->GetMarkerColor() == kWhite)
        {
            Int_t where = 0;
            TH1 *h = (TH1*)obj;
            for (Int_t i = 1; i <= h->GetNbinsX() && fits; i++)
            {
                if (h->GetBinLowEdge(i) + h->GetBinWidth(i) < x1) continue;   //to the left of the legend
                if (h->GetBinLowEdge(i)                     > x2) continue;   //to the right of the legend
                if (h->GetBinContent(i) > y1 && h->GetBinContent(i) < y2) fits = false;   //inside the legend
                if (h->GetBinContent(i) < y1)
                {
                    if (where == 0) where = -1;             //below the legend
                    if (where == 1) fits = false;           //a previous bin was above it so there's a vertical line through it
                }
                if (h->GetBinContent(i) > y2)
                {
                    if (where == 0) where = 1;              //above the legend
                    if (where == -1) fits = false;          //a previous bin was below it so there's a vertical line through it
                }
            }
            continue;
        }
        //Histogram, drawn with Draw("P")
        else if (cl->InheritsFrom("TH1") && !cl->InheritsFrom("TH2") && !cl->InheritsFrom("TH3")
              && cl != TProfile::Class())
        //Probably TProfile would be the same but I haven't tested it
        {
            TH1 *h = (TH1*)obj;
            for (Int_t i = 1; i <= h->GetNbinsX() && fits; i++)
            {
                if (h->GetBinLowEdge(i) + h->GetBinWidth(i)/2 < x1) continue;
                if (h->GetBinLowEdge(i)                       > x2) continue;
                if (h->GetBinContent(i) > y1 && h->GetBinContent(i) < y2) fits = false;
                if (h->GetBinContent(i) + h->GetBinError(i) > y2 && h->GetBinContent(i) - h->GetBinError(i) < y2) fits = false;
                if (h->GetBinContent(i) + h->GetBinError(i) > y1 && h->GetBinContent(i) - h->GetBinError(i) < y1) fits = false;
            }
        }
        else if (cl->InheritsFrom("TF1") && !cl->InheritsFrom("TF2"))
        {
            //TF1 *f = (TF1*)obj;
            //Double_t max = f->GetMaximum(x1,x2);
            //Double_t min = f->GetMinimum(x1,x2);
            //if (min < y2 && max > y1) fits = false;
        }
        // else if (cl->InheritsFrom(...... add more objects here
        else
        {
            cout << "Don't know how to place the legend around objects of type " << obj->ClassName() << "." << endl
                 << "Add this class into placeLegend.C if you want it to work properly." << endl
                 << "The legend will still be placed around any other objects." << endl;
        }
    }
    return fits;
}