double* IfitBin(TH1D* dataInput, TH1D* sigTemplate, TH1D* bkgTemplate)
{
   // Start TFractionFitter
   double Spara(0), eSpara(0);
   double Bpara(0), eBpara(0);
   TObjArray *mc = new TObjArray(2);
   mc->Add(sigTemplate);
   mc->Add(bkgTemplate);

   TFractionFitter *fitTemplate = new TFractionFitter(dataInput, mc);
   fitTemplate->Constrain(0, 0.0, 1.0);
   fitTemplate->Constrain(1, 0.0, 1.0);
   int status = fitTemplate->Fit();
   cout<<" Fitting status = "<<status<<endl;
   if (status == 0) {
      fitTemplate->GetResult(0, Spara, eSpara);
      fitTemplate->GetResult(1, Bpara, eBpara);

      cout<<" Fitting result = "<<endl;
      cout<<"               Chi2 = "<<fitTemplate->GetChisquare()<<endl;
      cout<<"                NDF = "<<fitTemplate->GetNDF()<<endl;
      cout<<"               Prob = "<<fitTemplate->GetProb()<<endl;
      cout<<"      Signal fraction     = "<<Spara<<"; Error = "<<eSpara<<endl;
      cout<<"      Background fraction = "<<Bpara<<"; Error = "<<eBpara<<endl;
   }

   TH1D *FitResultReal = (TH1D*)sigTemplate->Clone();
   TH1D *FitResultFake = (TH1D*)bkgTemplate->Clone();
   TH1D *FitResultAll  = (TH1D*)dataInput->Clone();
   FitResultReal->SetName("ResultReal");
   FitResultFake->SetName("ResultFake");
   FitResultAll->SetName("ResultAll");
   FitResultReal->Scale(1./FitResultReal->Integral()*Spara*dataInput->Integral());
   FitResultFake->Scale(1./FitResultFake->Integral()*Bpara*dataInput->Integral());
   FitResultAll->Reset();
   FitResultAll->Add(FitResultReal);
   FitResultAll->Add(FitResultFake);
   
   TCanvas *c1 = new TCanvas("c1", "", 600, 400);
   c1->cd();
   FitResultAll->SetXTitle("#sigma_{i#etai#eta}");
   FitResultAll->SetYTitle("Number of photons");
   FitResultAll->SetMinimum(0);
   FitResultAll->SetMaximum(FitResultAll->GetMaximum()*1.4);
   FitResultAll->SetLineColor(1);
   FitResultAll->SetLineWidth(2);
   FitResultAll->Draw();
   dataInput->SetMarkerStyle(21);
   dataInput->SetMarkerSize(0.7);
   dataInput->SetLineColor(1);
   dataInput->SetLineWidth(2);
   dataInput->Draw("PE1same");
   FitResultReal->SetLineColor(2);
   FitResultReal->SetFillColor(2);
   FitResultReal->SetFillStyle(3002);
   FitResultReal->Draw("same");
   FitResultFake->SetLineColor(4);
   FitResultFake->SetFillColor(4);
   FitResultFake->SetFillStyle(3004);
   FitResultFake->Draw("same");
   TLegend *leg1 = new TLegend(0.5,0.5,0.9,0.85);
   char text[200];
   leg1->SetFillColor(0);
   leg1->SetShadowColor(0);
   leg1->SetFillStyle(0);
   leg1->SetBorderSize(0);
   leg1->SetLineColor(0);
   sprintf(text,"Data: %5.1f events", dataInput->Integral());
   leg1->AddEntry(dataInput, text, "pl");
   sprintf(text,"Fitted: %5.1f events", FitResultAll->Integral());
   leg1->AddEntry(FitResultAll, text, "l");
   sprintf(text,"Signal %5.1f #pm %5.1f events", FitResultReal->Integral(), eSpara/Spara*FitResultReal->Integral());
   leg1->AddEntry(FitResultReal, text, "f");
   sprintf(text,"Background %5.1f #pm %5.1f events", FitResultFake->Integral(), eBpara/Bpara*FitResultFake->Integral());
   leg1->AddEntry(FitResultFake, text, "f");
   leg1->Draw();

   return;
}
void makeCaloMEtTriggerEffPlots_Ztautau()
{
//--- stop ROOT from keeping references to all histograms
  TH1::AddDirectory(false);

//--- suppress the output canvas 
  gROOT->SetBatch(true);

  TString inputFilePath = "/data1/veelken/tmp/muonPtGt17/V10_5tauEnRecovery_L1ETM20Eff_v3/2011RunB/tauIdEfficiency/";
  
  TString inputFileName = "analyzeTauIdEffHistograms_all_2011Oct30V10_5tauEnRecovery.root";

  TString dqmDirectory = "";

  TString meName_numerator_data = "%s_%s_numCaloMEt_HLT_IsoMu15_L1ETM20_tauDiscrHPScombLooseDBcorr_%s";
  TString meName_numerator_mc   = "%s_%s_numCaloMEt_L1_ETM20_tauDiscrHPScombLooseDBcorr_%s"; 
  TString meName_denominator    = "%s_%s_denomCaloMEt_tauDiscrHPScombLooseDBcorr_%s"; 

  TObjArray processes;
  processes.Add(new TObjString("Ztautau"));
  processes.Add(new TObjString("Zmumu"));
  processes.Add(new TObjString("WplusJets"));
  processes.Add(new TObjString("QCD"));
  processes.Add(new TObjString("TTplusJets"));

  TString region_passed = "C1p";
  TString region_failed = "C1f";

  TString inputFileName_full = inputFilePath;
  if ( !inputFileName_full.EndsWith("/") ) inputFileName_full.Append("/");
  inputFileName_full.Append(inputFileName);
  std::cout << "opening inputFile = " << inputFileName_full.Data() << std::endl;
  TFile* inputFile = new TFile(inputFileName_full.Data());

  TH1* histogram_numerator_Data_passed    = getHistogram(inputFile, meName_numerator_data, "Data",    region_passed);
  TH1* histogram_denominator_Data_passed  = getHistogram(inputFile, meName_denominator,    "Data",    region_passed);
  TH1* histogram_numerator_mcSum_passed   = getHistogram(inputFile, meName_numerator_mc,   processes, region_passed);
  TH1* histogram_denominator_mcSum_passed = getHistogram(inputFile, meName_denominator,    processes, region_passed);

  TH1* histogram_numerator_Data_failed    = getHistogram(inputFile, meName_numerator_data, "Data",    region_failed);
  TH1* histogram_denominator_Data_failed  = getHistogram(inputFile, meName_denominator,    "Data",    region_failed);
  TH1* histogram_numerator_mcSum_failed   = getHistogram(inputFile, meName_numerator_mc,   processes, region_failed);
  TH1* histogram_denominator_mcSum_failed = getHistogram(inputFile, meName_denominator,    processes, region_failed);

  TString outputFileName = Form("makeCaloMEtTriggerEffPlots_Ztautau.png");
  makePlot_wrapper("",
		   histogram_numerator_Data_passed, histogram_denominator_Data_passed, 
		   histogram_numerator_mcSum_passed, histogram_denominator_mcSum_passed,
		   histogram_numerator_Data_failed, histogram_denominator_Data_failed,  
		   histogram_numerator_mcSum_failed, histogram_denominator_mcSum_failed,
		   "Data", "Simulation", region_passed, region_failed,
		   outputFileName);

  delete inputFile;
}
void SecondaryElectronsNeutrons(const char* fileName,int numEvents){

    double XMAX = 2.75;
    char histKey_1[128] ="secElectronKinE_00_01PID";
    char histKey_2[128] ="secElectronKinE_00_02PID";
    char histKey_3[128] ="secElectronKinE_00_03PID";
    char histKey_4[128] ="secElectronKinE_00_04PID";
    // Getting the files and thickness
    FILE* in = fopen(fileName,"r");
    TObjArray *files = new TObjArray();
    TObjArray *histPID1 = new TObjArray();
    TObjArray *histPID2 = new TObjArray();
    TObjArray *histPID3 = new TObjArray();
    TObjArray *histPID4 = new TObjArray();
    TObjArray *thickness = new TObjArray();
    char* token;
    TFile* f = NULL;
    TH1F* h = NULL;
    TH1F* hRef = NULL;
    TObjString *s = NULL;
    if (in != NULL){
        char line[128];
        while ( fscanf(in,"%s\n",line) == 1 ){
            f = new TFile(line,"READ");
            files->Add(f);
            // Getting the histograms
            h = (TH1F*) f->Get(histKey_1);
            histPID1->Add(h);
            h = (TH1F*) f->Get(histKey_2);
            histPID2->Add(h);
            h = (TH1F*) f->Get(histKey_3);
            histPID3->Add(h);
            h = (TH1F*) f->Get(histKey_4);
            histPID4->Add(h);
            token = strtok(line,"_");
            s = new TObjString(token);
            thickness->Add(s);
        }
        fclose(in);
    }
    else{
        perror(fileName);
    }
    fprintf(stdout,"Files:\n");
    files->Print();
    fprintf(stdout,"\nThickness:\n");
    thickness->Print();

    plotHistograms("SecElec_Neutrons_PID3.eps",histPID3,thickness,XMAX,"PID = 3","Electron Kinetic Energy (MeV)");
    plotHistograms("SecElec_Neutrons_PID4.eps",histPID4,thickness,XMAX,"PID = 4","Electron Kinetic Energy (MeV)");

    // Saving the histograms
    saveHistograms("Neutron_PID3_HistData.txt", histPID3, thickness);
    saveHistograms("Neutron_PID4_HistData.txt", histPID4, thickness);
}
Example #4
0
void PublishCanvas(TList *qaList, const char* det, const char* name, TString nadd)
{
  //
  // draw all nSigma + signal histo
  //


  TObjArray arrHistos;

  TPaveText pt(.1,.1,.9,.9,"NDC");
  pt.SetBorderSize(1);
  pt.SetFillColor(0);
  pt.SetTextSizePixels(16);
  pt.AddText(Form("%s PID QA",det));
  if (!nadd.IsNull()){
    pt.AddText(nadd.Data());
    nadd.Prepend("_");
  }
  arrHistos.Add(&pt);

  TH2 *hSig=Get2DHistogramfromList(qaList,det,Form("hSigP_%s",det));
  if (hSig){
    hSig->SetOption("colz");
    arrHistos.Add(hSig);
  }

  for (Int_t i=0;i<AliPID::kSPECIESC;++i){
    //     for (Int_t i=0;i<AliPID::kSPECIES;++i){
    if (i==(Int_t)AliPID::kMuon) continue;
    TH2 *h=Get2DHistogramfromList(qaList,det,Form(name,AliPID::ParticleName(i)));
    if (!h) continue;
    h->SetOption("colz");
    AddFit(h);
    arrHistos.Add(h);
  }

  Int_t nPads=arrHistos.GetEntriesFast();
  Int_t nCols = (Int_t)TMath::Ceil( TMath::Sqrt(nPads) );
  Int_t nRows = (Int_t)TMath::Ceil( (Double_t)nPads/(Double_t)nCols );

  
  fCanvas->Divide(nCols,nRows);


  for (Int_t i=0; i<nPads;++i) {
    fCanvas->cd(i+1);
    SetupPadStyle();
    arrHistos.At(i)->Draw();
  }

  fCanvas->Update();
  fCanvas->Clear();

}
Example #5
0
TMap* CreateDCSAliasMap()
{
  // Creates a DCS structure
  // The structure is the following:
  //   TMap (key --> value)
  //     <DCSAlias> --> <valueList>
  //     <DCSAlias> is a string
  //     <valueList> is a TObjArray of AliDCSValue
  //     An AliDCSValue consists of timestamp and a value in form of a AliSimpleValue

  // In this example 6 aliases exists: DCSAlias1 ... DCSAlias6
  // Each contains 1000 values randomly generated by TRandom::Gaus + 5*nAlias

  TMap* aliasMap = new TMap;
  aliasMap->SetOwner(1);
  TRandom random;

	FILE *fp = fopen("./DCSValues.txt","r");

	char name[50];
	Float_t val;
	while(!(EOF == fscanf(fp,"%s %f",name,&val))){
		TObjArray* valueSet = new TObjArray;
		valueSet->SetOwner(1);

		TString aliasName=name;
		
		//printf("alias: %s\t\t",aliasName.Data());

		int timeStamp=10;
		
		
		if(aliasName.Contains("HV")) {
			for(int i=0;i<200;i++){
				dcsVal = new AliDCSValue((Float_t) (val+random.Gaus(0,val*0.1)), timeStamp+10*i);
				valueSet->Add(dcsVal);
			}
		} else {
			for(int i=0;i<2;i++){
				AliDCSValue* dcsVal = new AliDCSValue((UInt_t) (val), timeStamp+10*i);
				valueSet->Add(dcsVal);
			}
		}
		
		aliasMap->Add(new TObjString(aliasName), valueSet);

	}
	fclose(fp);
  return aliasMap;
}
Example #6
0
//_____________________________________________________
TLegendEntry* GFHistManager::AddHist(TH1* hist, Int_t layer, const char* legendTitle,
				     const char* legOpt)
{
  // add hist to 'layer'th list  of histos (expands, if layer does not already exist!)
  if(!hist){
    this->Warning("AddHist", "adding NULL pointer will be ignored!");
    return NULL;
  }

  if(!this->CheckDepth("AddHist", layer)) return NULL;
  GFHistArray* newHist = new GFHistArray;
  newHist->Add(hist);
  TObjArray* layerHistArrays = static_cast<TObjArray*>(fHistArrays->At(layer));
  layerHistArrays->Add(newHist);
  if(legendTitle){
    TObjArray* legends = this->MakeLegends(layer);
    TLegend* legend = new TLegend(fLegendX1, fLegendY1, fLegendX2, fLegendY2);
#if ROOT_VERSION_CODE < ROOT_VERSION(5,6,0)
    if (TString(gStyle->GetName()) == "Plain") legend->SetBorderSize(1);
#endif
    legends->AddAtAndExpand(legend, layerHistArrays->IndexOf(newHist));
    return legend->AddEntry(hist, legendTitle, legOpt ? legOpt : fgLegendEntryOption.Data());
  }
  return NULL;
}
Example #7
0
TObjArray* findClassesForAlias(THashList &list, const char* aliasName)
{

    TObjArray* matchingTrClasses = new TObjArray(2);
    TIter iter(&list);
    TNamed *n = 0;
    iter.Reset();
    while((n = dynamic_cast<TNamed*>(iter.Next()))){
	TString aliasList(n->GetTitle());
	if(aliasList.Contains(aliasName)){
	    TObjArray* arrAliases = aliasList.Tokenize(',');
	    Int_t nAliases = arrAliases->GetEntries();
	    for(Int_t i=0; i<nAliases; i++){
		TObjString *alias = (TObjString*) arrAliases->At(i);
		alias->Print(0);
		if(alias->String()==TString(aliasName)){
		    TObjString *trClass = new TObjString(n->GetName());
		    matchingTrClasses->Add(trClass);
		}
	    }
	}
    }

    return matchingTrClasses;
}
Example #8
0
/* *************************************************************************** *
 *                                                                             *
 * Format:                                                                     *
 *                                                                             *
 * Save into a format to be used in main code                                  *
 *                                                                             *
 * *************************************************************************** */
void GeomAcc::Format(TString saveName, TString pol){

  TString plotName;
  if(pol == "NoPol/") plotName = "GeoEff";
  else if (pol == "Long/") plotName = "GeoLongEff";
  else if (pol == "Trans/") plotName = "GeoTransEff"; 

  TFile *f1 = TFile::Open("Output/" + saveName);
  TH2D *GeoEff2 = (TH2D*) f1->Get(plotName);
  GeoEff2->SetName("Geometric Acceptance");

  //
  //hack to use existing description plot
  //

  TFile *f2 = TFile::Open("Description/" + saveName);
  TH1 * Descrip = (TH1*) f2->Get("Description");

  TObjArray * histList = new TObjArray(0);
  histList->Add(GeoEff2);
  histList->Add(Descrip);

  TFile* saveFile = new TFile("Efficiency/"+ pol+ saveName, "recreate");
  histList->Write();
  saveFile->Close();
 

  return;
}
Example #9
0
//
// Sometimes we have h_jet_pt1_os, h_jet_pt2_os, h_jet_pt3_os but no h_jet_pt
// This function allows to add all three histos in one file, for all files
// 
TObjArray GetThreeSameHistos(TString h1name, TString h2name, TString h3name, TEnv *params){
    TObjArray histos; histos.Clear();
    int num_files = params->GetValue ("Files.Number", 0);    
    for (int i = 1; i <= num_files; i++) {
	ostringstream baseName;
	baseName << "Files." << i << ".";
	TString bName (baseName.str().c_str());	
	TString fname (params->GetValue(bName+"Name", "bogus_file"));
	Double_t factor = params->GetValue(bName+"Factor", 1.0);
	TFile *f = new TFile (fname, "READ");
	TH1F * h1 = (TH1*) f->Get(h1name);
	TH1F * h2 = (TH1*) f->Get(h2name);
	TH1F * h3 = (TH1*) f->Get(h3name);
	if (h1 && h2 && h3){
	    h1->Sumw2(); h2->Sumw2(); h3->Sumw2(); // you need this for the KS test	    
	    h1->Add (h1, factor-1.000);// Apply scaling factor (default=1.0)
	    h2->Add (h2, factor-1.000);
	    h3->Add (h3, factor-1.000);
	    h1->Add (h2);
	    h1->Add (h3);
	    histos.Add(h1);
	    //cout << "reading histo " << i << " factor=" << factor << " integral " << h->Integral() << endl;
	} else {
	    printf(" Could not find histogram %s in file %s \n",h1name.Data(),fname.Data());
	    exit;
	}
    }
    return histos;

}
Example #10
0
CombinedSpectra(const Char_t *fileoutname, Int_t what = -1)
{

  TFile *itssafile = TFile::Open(itssafilename);
  //  TFile *itstpcfile = TFile::Open(itstpcfilename);
  TFile *tpctoffile = TFile::Open(tpctoffilename);
  TFile *toffile = TFile::Open(toffilename);

  TFile *fileout = TFile::Open(fileoutname, "RECREATE");

  TH1D *hITSsa, *hITSTPC, *hTPCTOF, *hTOF;
  TH1D *hCombined[10];
  for (Int_t part = 2; part < AliPID::kSPECIES; part++) {
    for (Int_t charge = 0; charge < 2; charge++) {
      for (Int_t icent = 0; icent < 10; icent++) {
	hCombined[icent] = new TH1D(Form("cent%d_%s_%s", icent, AliPID::ParticleName(part), chargeName[charge]), "", NptBins, ptBin);
	TObjArray spectraArray;
	hITSsa = GetITSsaSpectrum(itssafile, part, charge, icent);
	//hITSTPC = GetITSTPCSpectrum(itstpcfile, part, charge, icent);
	hTPCTOF = GetTPCTOFSpectrum(tpctoffile, part, charge, icent);
	hTOF = GetTOFSpectrum(toffile, part, charge, icent);
	if (hITSsa && (what == -1 || what == 0)) {
	  spectraArray.Add(hITSsa);
	}
	if (hITSTPC && (what == -1 || what == 1)) {
	  spectraArray.Add(hITSTPC);
	}
	if (hTPCTOF && (what == -1 || what == 2)) {
	  spectraArray.Add(hTPCTOF);
	}
	if (hTOF && (what == -1 || what == 3)) {
	  spectraArray.Add(hTOF);
	}
	
	CombineSpectra(hCombined[icent], &spectraArray);
	fileout->cd();
	hCombined[icent]->Write();
      }
    }
  }	  
  
  fileout->Close();

}
Example #11
0
void OccupancyAscii2OCDB(Int_t runNumber,
                         const char* filename,
                         const char* ocdbpath,
                         const char* comment)
{
    TObjArray a;
    a.SetOwner(kTRUE);
    a.Add(new TObjString(filename));
    OccupancyAscii2OCDB(runNumber,a,ocdbpath,comment);
}
Example #12
0
TObjArray* Chain2List(TChain* chain)
{
  // returns a TObjArray of TObjStrings of the file names in the chain

  TObjArray* result = new TObjArray;

  for (Int_t i=0; i<chain->GetListOfFiles()->GetEntries(); i++)
    result->Add(new TObjString(chain->GetListOfFiles()->At(i)->GetTitle()));

  return result;
}
Example #13
0
	float PhiLab( const PseudoJet& jet, Double_t PzInLepton, Double_t PzInHadron, TLorentzVector electron )
	{
		TLorentzVector p;
		p . SetPxPyPzE( jet.px(), jet.py(), jet.pz(), jet.e() );
		TObjArray InputCand;
		InputCand.Add( &p );
		
		TObjArray OutputCand;
		Dijets::BreitBoost( InputCand,  OutputCand, PzInLepton, PzInHadron, electron, 2 );
		OutputCand.SetOwner();
		float phi = (static_cast<TLorentzVector*>(OutputCand.At(0))) -> Phi();
		OutputCand.Clear();
		return phi;
	}
Example #14
0
void OccupancyHLTtest()
{
//  tail -c +205 EOR_mch-occupancy_0x02_HLT\:FXS_CAL  | more > toto
// mv toto EOR_mch-occupancy_0x02_HLT\:FXS_CAL

    TObjArray hlt;
    hlt.SetOwner(kTRUE);

    hlt.Add(new TObjString("EOR_mch-occupancy_0x02_HLT:FXS_CAL"));
    hlt.Add(new TObjString("EOR_mch-occupancy_0x03_HLT:FXS_CAL"));

    OccupancyAscii2OCDB(196474,hlt,"alien://folder=/alice/cern.ch/user/l/laphecet/HCDB","HLT");
    OccupancyAscii2OCDB(196474,"occupancy.000196474082.15","alien://folder=/alice/cern.ch/user/l/laphecet/OCDB",
                        "occupancy.000196474082.15");
}
Example #15
0
TObjArray* KVRangeYanez::GetListOfMaterials()
{
   // Create and fill a list of all materials for which range tables exist.
   // Each entry is a TNamed with the name and type (title) of the material.
   // User's responsibility to delete list after use (it owns its objects).

   TObjArray* list = new TObjArray(fMaterials->GetEntries());
   list->SetOwner(kTRUE);
   TIter next(fMaterials);
   KVIonRangeTableMaterial* mat;
   while ((mat = (KVIonRangeTableMaterial*)next())) {
      list->Add(new TNamed(mat->GetName(), mat->GetType()));
   }
   return list;
}
Example #16
0
TObjArray readOnline(int runNumber)
{
  // Open connection to online database
  const char* database = "mysql://db04.star.bnl.gov:3411/Conditions_rts?timeout=60";
  const char* user = "******";
  const char* pass = "";
  TMySQLServer* mysql = TMySQLServer::Connect(database,user,pass);

  if (!mysql) {
    cerr << "Connection to " << database << " failed" << endl;
    return;
  }

  TObjArray arr;
  TString query;
  TMySQLResult* result;
  //  TDatime beginTime;


  query = Form("select object,idx,reg,label,value,defaultvalue from `Conditions_rts`.`dict` where hash=(select dicthash from run where idx_rn = %d)",runNumber);

  result = (TMySQLResult*)mysql->Query(query);
  if (result) {
    TMySQLRow* row;
    while (row = (TMySQLRow*)result->Next()) {
      StTriggerThreshold* th = new StTriggerThreshold;
      th->object = atoi(row->GetField(0));
      th->index = atoi(row->GetField(1));
      th->reg = atoi(row->GetField(2));
      th->label = row->GetField(3);
      th->value = atoi(row->GetField(4));
      th->defaultvalue = atoi(row->GetField(5));
      delete row;
      arr.Add(th);
    }
    result->Close();
  }

  mysql->Close();

  for (int i = 0; i < arr.GetEntriesFast(); ++i) {
    StTriggerThreshold* th = (StTriggerThreshold*)arr.At(i);
    th->print();
  }
  return arr;
}
Example #17
0
void tauIdEffValidation()
{
  //TFile* inputFile = TFile::Open("rfio:/castor/cern.ch/user/v/veelken/CMSSW_3_3_x/bgEstPlots/ZtoMuTau_frSimple/10TeVii/plotsZtoMuTau_bgEstFakeRate.root");
  TFile* inputFile = TFile::Open("file:/afs/cern.ch/user/v/veelken/scratch0/CMSSW_3_3_6_patch5/src/TauAnalysis/BgEstimationTools/test/plotsZtoMuTau_bgEstFakeRate.root");

  // define colors used to plot efficiencies/fake-rates of different tau id. criteria
  // (definition of "rainbow" colors taken from TauAnalysis/DQMTools/python/plotterStyleDefinitions_cfi.py)
  TArrayI colors(7);
  colors[0] = 877; // violett
  colors[1] = 596; // dark blue
  //colors[2] = 856; // light blue
  colors[2] = 817; // green
  //colors[4] = 396; // yellow
  //colors[3] = 797; // orange
  colors[3] = 628; // red

  TObjArray cutEffNames;
  cutEffNames.Add(new TObjString("ByTrackIsolationSeq"));
  cutEffNames.Add(new TObjString("ByEcalIsolationSeq"));  
  cutEffNames.Add(new TObjString("ByNTracksSeq"));
  cutEffNames.Add(new TObjString("ByChargeSeq"));
  //cutEffNames.Add(new TObjString("ByStandardChain"));

  TObjArray meNames;
  meNames.Add(new TObjString("TauPt"));
  meNames.Add(new TObjString("TauEta"));
  meNames.Add(new TObjString("TauPhi"));
  meNames.Add(new TObjString("TauAssocJetPt"));
  meNames.Add(new TObjString("TauLeadTrkPt"));
  meNames.Add(new TObjString("TauJetRadius"));

  //TString dqmDirectory = "zMuTauAnalyzer_frUnweighted/afterEvtSelTauLeadTrkPt_beforeEvtSelTauTrkIso/TauIdEffValidation";
  TString dqmDirectory = "zMuTauAnalyzer_frUnweighted/afterEvtSelDiMuPairZmumuHypothesisVeto/TauIdEffValidation";

  showTauIdEfficiency(inputFile, "Ztautau", dqmDirectory, meNames, cutEffNames, "effZTTsim", colors, false);
  showTauIdEfficiency(inputFile, "qcdSum", dqmDirectory, meNames, cutEffNames, "frMuEnrichedQCDsim", colors, true);
  //showTauIdEfficiency(inputFile, "PPmuXptGt20_factorized", dqmDirectory, meNames, cutEffNames, "frMuEnrichedQCDsim", colors, true);

  delete inputFile;
}
// ______________________________________________________________________________________
TPad* SetupCanvas(const Char_t* canName, const Char_t *canTitle) {
  // -- setup canvas and pad
  
  canA.Add(new TCanvas(Form("can%s", canName), canTitle, 0, 0 , 420, 700));
  can = static_cast<TCanvas*>(canA.Last());
  can->SetFillColor(0);
  can->SetBorderMode(0);
  can->SetBorderSize(0.0);
  can->SetFrameFillColor(0);
  can->SetFrameBorderMode(0);
  can->cd();
  
  pad = new TPad("pad", "pad",0.05, 0.06, 0.99, 0.98);
  pad->SetBorderMode(0);
  pad->SetFillColor(0);
  pad->Draw();
  pad->cd();
  pad->Divide(1, 3, 0., 0., 0);

  can->cd();

  TLatex *texb_5 = new TLatex(0.45, 0.03, "#sqrt{#it{s}_{NN}} (GeV)");
  texb_5->SetTextSize(0.04);
  texb_5->Draw("same");
  
  TLatex *texb_6a = new TLatex(0.05,0.8, aMomentsTitle[4]);
  texb_6a->SetTextSize(0.04);
  texb_6a->SetTextAngle(90);
  texb_6a->Draw("same");
  
  TLatex *texb_6b = new TLatex(0.05,0.45, aMomentsTitle2[5]);
  texb_6b->SetTextSize(0.04);
  texb_6b->SetTextAngle(90);
  texb_6b->Draw("same");
  
  TLatex *texb_6c = new TLatex(0.05,0.2, aMomentsTitle[6]);
  texb_6c->SetTextSize(0.04);
  texb_6c->SetTextAngle(90);
  texb_6c->Draw("same");
  
  return pad;
}
Example #19
0
//________________________________________________________
TObjArray GFOverlay::FindAllBetween(const TString &text,
				    const char *startStr, const char *endStr) const
{
  TObjArray result; // TObjStrings...

  if (text.Contains(startStr, TString::kIgnoreCase)) {
    Ssiz_t start = text.Index(startStr);
    while (start != kNPOS && start < text.Length()) {
      TString name = this->FindNextBetween(text, start, startStr, endStr);
      if (!name.IsNull()) {
	result.Add(new TObjString(name));
	start = text.Index(startStr, start + name.Length() + TString(endStr).Length());
      } else {
	break;
      }
    }
  }

  return result;
}
void read_plot_PMTposition()
{
	histlist.Add(sct1);
	histlist.Add(sct2);
	
	sprintf(buf,"%s\\%s.root",directory,fileName);	//root文件的路径
	TFile *file1 = new TFile(buf);
	
	if(file1->IsZombie()) {
    cout<<endl<<buf<<" doesn't exist!!"<<endl<<endl;
    exit(-1);
  }
  else {
  	cout<<"Root File:"<<endl<<"########  "<<buf<<"  ########"<<endl<<endl;
  	
  	sprintf(buf,"h1");  //tree的名称
		Read(file1,buf);		
		Int_t nEvents= (Int_t)h1->GetEntries();
		
		plotHis();
  }
}
Example #21
0
void book(){
  cout << "\n[book]\n" << endl;

  char filename[128];
  sprintf(filename,"%s.root",outFile);
  outFile_ = new TFile(filename,"RECREATE");
  
  for (int i=1;i<iovDim;i++){
    char dirName[128];
    sprintf(dirName,"IOV_%d",iov[i]);
    cout << dirName << endl;
    outFile_->mkdir(dirName);
    outFile_->cd(dirName);
    
    gDirectory->mkdir("DetId");
    gDirectory->mkdir("Layer");
    gDirectory->mkdir("SubDet");

    gDirectory->cd("DetId");
    //Make Histos for each detector
    for (int j=0;j<vHistoNames.size();j++){
      //cout << "vHistoName " << vHistoNames[j] << endl;
      char newName[128];
      SubNamePtr=((strstr(vHistoNames[j].c_str(),":"))+1);
      sprintf(newName,"NoiseVariationProfile_%s_%s",SubNamePtr,dirName);
      //cout << "newName " << newName << endl;
      Hlist.Add(new TH1F(newName,newName,vHistoNBinsX[j],-0.5,vHistoNBinsX[j]-0.5));
      sprintf(newName,"NoiseVariation_%s_%s",SubNamePtr,dirName);
      Hlist.Add(new TH1F(newName,newName,histoBins,histoMin,histoMax));      
    }

    gDirectory->cd("../Layer");
    //Make Histos for each layer
    for (int j=0;j<vLayerName.size();j++){
      char newName[128];
      sprintf(newName,"NoiseVariation_%s_%s",vLayerName[j].c_str(),dirName);
      Hlist.Add(new TH1F(newName,newName,histoBins,histoMin,histoMax));      
      sprintf(newName,"NoiseComparison_%s_%s",vLayerName[j].c_str(),dirName);
      Hlist.Add(new TH2F(newName,newName,histoBins,0,10,histoBins,0,10));      
    }

    gDirectory->cd("../SubDet");
    //Make Histos hor each SubDet
    Hlist.Add(new TH1F("NoiseVariation_TIB_"+TString(dirName),"NoiseVariation_TIB_"+TString(dirName),histoBins,histoMin,histoMax));      
    Hlist.Add(new TH1F("NoiseVariation_TOB_"+TString(dirName),"NoiseVariation_TOB_"+TString(dirName),histoBins,histoMin,histoMax));      
    Hlist.Add(new TH1F("NoiseVariation_TEC_"+TString(dirName),"NoiseVariation_TEC_"+TString(dirName),histoBins,histoMin,histoMax));      
    Hlist.Add(new TH1F("NoiseVariation_TID_"+TString(dirName),"NoiseVariation_TID_"+TString(dirName),histoBins,histoMin,histoMax));      
  }
  
  gDirectory->cd("../..");
  
  for (int j=0;j<vLayerName.size();j++){
    char newName[128];
    sprintf(newName,"pNoiseVariation_%s",vLayerName[j].c_str());
    Hlist.Add(new TProfile(newName,newName,iovDim,minIov,maxIov,histoMin,histoMax));
  }
  
  Hlist.Add(new TProfile("pNoiseVariation_TIB","pNoiseVariation_TIB",iovDim,minIov,maxIov,histoMin,histoMax));
  Hlist.Add(new TProfile("pNoiseVariation_TID","pNoiseVariation_TID",iovDim,minIov,maxIov,histoMin,histoMax));
  Hlist.Add(new TProfile("pNoiseVariation_TOB","pNoiseVariation_TOB",iovDim,minIov,maxIov,histoMin,histoMax));
  Hlist.Add(new TProfile("pNoiseVariation_TEC","pNoiseVariation_TEC",iovDim,minIov,maxIov,histoMin,histoMax));
  
  outFile_->cd();
}     
void makeTauIsolationPlots()
{
  TFile* inputFile = TFile::Open("../test/patTauIsolationAnalyzer.root");

  TObjArray ptThresholds;
  ptThresholds.Add(new TObjString("0_50GeV"));
  ptThresholds.Add(new TObjString("1_00GeV"));
  ptThresholds.Add(new TObjString("1_50GeV"));
  ptThresholds.Add(new TObjString("2_00GeV"));
  ptThresholds.Add(new TObjString("2_50GeV"));
  ptThresholds.Add(new TObjString("3_00GeV"));
  unsigned numPtThresholds = ptThresholds.GetEntries();

  TObjArray sigConeSizes;
  sigConeSizes.Add(new TObjString("0_05dRsig"));
  sigConeSizes.Add(new TObjString("0_10dRsig"));
  sigConeSizes.Add(new TObjString("0_15dRsig"));
  sigConeSizes.Add(new TObjString("0_20dRsig"));
  sigConeSizes.Add(new TObjString("0_25dRsig"));
  sigConeSizes.Add(new TObjString("0_30dRsig"));
  unsigned numSigConeSizes = sigConeSizes.GetEntries();

  TString dqmDirectory = "";

  TCanvas* canvas = new TCanvas("canvas", "canvas", 800, 600);
  canvas->SetFillColor(10);
  canvas->SetBorderSize(2);

//-------------------------------------------------------------------------------
// show distributions of isolation Pt sums **before** tight tau id. is applied
//-------------------------------------------------------------------------------
  TPostScript* psBeforeTauId = new TPostScript("patTauIsolationPlots_beforeTauId.ps", 112);
  for ( unsigned iSigConeSize = 0; iSigConeSize < numSigConeSizes; ++iSigConeSize ) {
    TObjString* sigConeSize = (TObjString*)sigConeSizes.At(iSigConeSize);
//--- show plots for PFCandidate Pt > XX GeV
//   (same threshold for all types of PFCandidates)
    for ( unsigned iPtThreshold = 0; iPtThreshold < numPtThresholds; ++iPtThreshold ) {
      TObjString* ptThreshold = (TObjString*)ptThresholds.At(iPtThreshold);

      TString meName = TString("PFCandIso").Append(sigConeSize->GetString()).Append(ptThreshold->GetString()).Append("_matched");

      showTauIsolation(inputFile, dqmDirectory, meName, 
		       "TauPFIsolationQuantities/beforeTauId", "MuonPFIsolationQuantities", "ElectronPFIsolationQuantities",
		       canvas, psBeforeTauId, "beforeTauId", true);
    }
//--- show plots for PFChargedHadron Pt > 1.0 GeV, PFGamma Pt > 1.5 GeV
    TString meName = TString("PFCandIso").Append(sigConeSize->GetString()).Append("1_00_1_50GeV").Append("_matched");
    showTauIsolation(inputFile, dqmDirectory, meName, 
		     "TauPFIsolationQuantities/beforeTauId", "MuonPFIsolationQuantities", "ElectronPFIsolationQuantities",
		     canvas, psBeforeTauId, "beforeTauId", true);
  }
  delete psBeforeTauId;

//-------------------------------------------------------------------------------
// show distributions of isolation Pt sums **after** tight tau id. is applied
//-------------------------------------------------------------------------------
  TPostScript* psAfterTauId = new TPostScript("patTauIsolationPlots_afterTauId.ps", 112);
  for ( unsigned iSigConeSize = 0; iSigConeSize < numSigConeSizes; ++iSigConeSize ) {
    TObjString* sigConeSize = (TObjString*)sigConeSizes.At(iSigConeSize);
//--- show plots for PFCandidate Pt > XX GeV
//   (same threshold for all types of PFCandidates)
    for ( unsigned iPtThreshold = 0; iPtThreshold < numPtThresholds; ++iPtThreshold ) {
      TObjString* ptThreshold = (TObjString*)ptThresholds.At(iPtThreshold);

      TString meName = TString("PFCandIso").Append(sigConeSize->GetString()).Append(ptThreshold->GetString()).Append("_matched");

      showTauIsolation(inputFile, dqmDirectory, meName, 
		       "TauPFIsolationQuantities/afterTauId", "", "",
		       canvas, psAfterTauId, "afterTauId", true);
    }
//--- show plots for PFChargedHadron Pt > 1.0 GeV, PFGamma Pt > 1.5 GeV
    TString meName = TString("PFCandIso").Append(sigConeSize->GetString()).Append("1_00_1_50GeV").Append("_matched");
    showTauIsolation(inputFile, dqmDirectory, meName, 
		     "TauPFIsolationQuantities/afterTauId", "", "",
		     canvas, psAfterTauId, "afterTauId", true);
  }
  delete psAfterTauId;

  delete canvas;

  delete inputFile;
}
Example #23
0
void buildFakeAngTree(const Char_t* outtag,
                      const Float_t timereso,     // ns
                      const UInt_t  simevts=1,
                      const Float_t thetaOpt=400, // deg
                      const Float_t phiOpt=400,   // deg
                      const Float_t coneOpt=400,  // deg
                      const UInt_t  rseed=23192,
                      const Float_t norm=100.0,   // mV
                      const Float_t noise=20.0,   // mV
                      const Char_t* outdir="/data/users/cjreed/work/simEvts",
                      const Char_t* infn="/w2/arianna/jtatar/nt.sigtemps.root",
                      const Char_t* geofn="/data/users/cjreed/work/"
                                          "BounceStudy/Stn10/"
                                          "CampSiteGeometry.root") {
   // if any of the angles (thetaOpt, phiOpt, coneOpt) > 360, a random
   // value will be used instead
   //
   // expect angles in the Templates tree to be in degrees
   //
   // expect the waveforms in the Templates tree to have amplitude 1
   
   TRandom3 rnd(rseed);
   
   
   geof = TFile::Open(geofn);
   gg = dynamic_cast<TGeoManager*>(geof->Get("CampSite2013"));
   site = dynamic_cast<const TSnGeoStnSite*>(gg->GetTopVolume());
   
   
   TVector3 pos[NSnConstants::kNchans], nvec[NSnConstants::kNchans];
   for (UChar_t ch=0; ch<NSnConstants::kNchans; ++ch) {
      site->SetLPDAPosition(ch, pos[ch]);
      site->SetLPDANormalVec(ch, nvec[ch]);
      Printf("pos ch%d:",ch);
      pos[ch].Print();
      Printf("normal ch%d:",ch);
      nvec[ch].Print();
   }
   
   TArrayD zeros(6);
   
   
   inf = TFile::Open(infn);
   nnt = dynamic_cast<TTree*>(inf->Get("Templates"));
   
   TString infns(infn);
   TString indir;
   Int_t fl(0);
   if (infns.Contains('/')) {
      fl = infns.Last('/') + 1;
      indir = infns(0, fl-1);
   }
   TString plaininfn = infns(fl, infns.Length()-fl);
   TString outfn = Form("%s/FakeEvts.%s.%s", outdir, outtag,
                        plaininfn.Data());
   outf = TFile::Open(outfn.Data(),"recreate");
   outf->cd();
   TParameter<Float_t> trp("TimeResolution", timereso);
   trp.Write();
   TParameter<Float_t> nmp("Normalization", norm);
   nmp.Write();
   TParameter<Float_t> nop("NoiseRMS", noise);
   nop.Write();
   TParameter<UInt_t> rsp("RandomSeed", rseed);
   rsp.Write();
   
   
   TSnCalWvData* wave = new TSnCalWvData;
   Float_t eang(0), hang(0), hpf(0), limiter(0), coneang(0);
   Bool_t bice(kFALSE);
   nnt->SetBranchAddress("wave.",&wave);
   nnt->SetBranchAddress("EAng",&eang);
   nnt->SetBranchAddress("HAng",&hang);
   nnt->SetBranchAddress("hpf",&hpf);
   nnt->SetBranchAddress("limiter",&limiter);
   nnt->SetBranchAddress("coneAng",&coneang);
   nnt->SetBranchAddress("bIce",&bice);
   // to look up waveform for EAng, HAng
   nnt->BuildIndex("EAng + (1000*HAng)","coneAng");
   // find the max angles
   Printf("finding allowed angles...");
   std::set<Float_t> Eangs, Hangs, Cangs;
   const Long64_t nnents = nnt->GetEntries();
   for (Long64_t i=0; i<nnents; ++i) {
      nnt->GetEntry(i);
      Eangs.insert(eang);
      Hangs.insert(hang);
      Cangs.insert(coneang);
   }
#ifdef DEBUG
   std::set<Float_t>::const_iterator ang, end = Eangs.end();
   Printf("EAngs:");
   for (ang=Eangs.begin(); ang!=end; ++ang) {
      Printf("%g",*ang);
   }
   Printf("HAngs:");
   for (ang=Hangs.begin(), end=Hangs.end(); ang!=end; ++ang) {
      Printf("%g",*ang);
   }
   Printf("ConeAngs:");
   for (ang=Cangs.begin(), end=Cangs.end(); ang!=end; ++ang) {
      Printf("%g",*ang);
   }
#endif
   
   Float_t theta(0), phi(0), cone(0);
   Float_t EAng[NSnConstants::kNchans], 
           HAng[NSnConstants::kNchans];
   Float_t CAng(0);
   TSnCalWvData* evdat = new TSnCalWvData;
   TSnEventMetadata* meta = new TSnEventMetadata;
   TSnEventHeader* hdr = new TSnEventHeader;
   //ot = nnt->CloneTree(0);
   //ot->SetName("SimTemplEvts");
   ot = new TTree("SimTemplEvts","simulated events from templates",1);
   ot->SetDirectory(outf);
   ot->Branch("EventMetadata.",&meta);
   ot->Branch("EventHeader.",&hdr);
   ot->Branch("EAng",&(EAng[0]),Form("EAng[%hhu]/F",NSnConstants::kNchans));
   ot->Branch("HAng",&(HAng[0]),Form("HAng[%hhu]/F",NSnConstants::kNchans));
   ot->Branch("CAng",&CAng,"CAng/F");
   ot->Branch("theta",&theta,"theta/F");
   ot->Branch("phi",&phi,"phi/F");
   ot->Branch("NuData.",&evdat);
   // some useful aliases
   TString an;
   for (UChar_t ch=0; ch<NSnConstants::kNchans; ++ch) {
      // to use as a cut for a particular channel:
      an = Form("Ch%d",ch);
      ot->SetAlias(an.Data(),
                   Form("(Iteration$>=(%hhu*%hhu)) && (Iteration$<(%hhu*%hhu))",
                        NSnConstants::kNsamps, ch,
                        NSnConstants::kNsamps,
                        static_cast<UChar_t>(ch+1)));
      // to use as a variable showing the sample number [0,127] for any chan
      an = Form("SmpCh%d",ch);
      ot->SetAlias(an.Data(),
                   Form("Iteration$-%u", static_cast<UInt_t>(ch)
                        *static_cast<UInt_t>(NSnConstants::kNsamps)));
      // e.g. Draw("RawData.fData:SmpCh2","EventHeader.fNum==21 && Ch2","l")
   }

   Printf("generating events...");
   TStopwatch timer;
   timer.Start();
   
   for (UInt_t i=0; i<simevts; ++i) {
      
      if ( (i%1000)==0 ) {
         fprintf(stderr,"Processing %u/%u ...            \r",i,simevts);
      }
      
      // choose angles
      theta = (thetaOpt>360.) ? TMath::ACos( rnd.Uniform(-1.0, 0.0) ) 
                              : thetaOpt * TMath::DegToRad();
      phi   = (phiOpt>360.) ? rnd.Uniform(0.0, TMath::TwoPi())
                            : phiOpt * TMath::DegToRad();
      cone  = (coneOpt>360.) 
         ? rnd.Uniform(*(Cangs.begin()), *(Cangs.rbegin()))
         : coneOpt; // leave this one in degrees (as in the tree)
      CAng = findNearestAllowedAngle(Cangs, cone);
      
#ifdef DEBUG
      Printf("--- theta=%g, phi=%g, cone=%g",
             theta*TMath::RadToDeg(), phi*TMath::RadToDeg(), cone);
#endif
      
      // calculate channel shifts
      TArrayD pwdt = NSnChanCorl::GetPlaneWaveOffsets(theta,
                                                      phi,
                                                      zeros,
                                                      pos,
                                                      kNgTopFirn);
      TVector3 dir;
      dir.SetMagThetaPhi(1.0, theta, phi);
      
#ifdef DEBUG
      TObjArray graphs;
      graphs.SetOwner(kTRUE);
      TCanvas* c1 = new TCanvas("c1","c1",800,700);
      c1->Divide(2,2);
#endif
      
      for (UChar_t ch=0; ch<NSnConstants::kNchans; ++ch) {
         
         // look up the EAng, fhang for this antenna
         Float_t feang(0), fhang(0);
         findEangHang(nvec[ch], dir, feang, fhang);
         feang  = TMath::Abs(TVector2::Phi_mpi_pi(feang));
         fhang  = TMath::Abs(TVector2::Phi_mpi_pi(fhang));
         feang *= TMath::RadToDeg();
         fhang *= TMath::RadToDeg();
         // find closest allowed angle
         EAng[ch] = findNearestAllowedAngle(Eangs, feang);
         HAng[ch] = findNearestAllowedAngle(Hangs, fhang);
         const Long64_t ni = 
            nnt->GetEntryNumberWithIndex(EAng[ch] + (1000*HAng[ch]), CAng);
#ifdef DEBUG
         Printf("EAng=%g (%g), HAng=%g (%g), CAng=%g, ni=%lld",
                EAng[ch],feang,HAng[ch],fhang,CAng,ni);
#endif
         if (ni>-1) {
            nnt->GetEntry(ni);
#ifdef DEBUG
            c1->cd(ch+1);
            TGraph* och = wave->NewGraphForChan(0, kTRUE);
            const Int_t ochnp = och->GetN();
            Double_t* ochy = och->GetY();
            for (Int_t k=0; k<ochnp; ++k, ++ochy) {
               *ochy *= norm;
            }
            graphs.Add(och);
            och->SetLineColor(kBlack);
            och->SetMarkerColor(kBlack);
            och->SetMarkerStyle(7);
            och->Draw("apl");
#endif
            
            // first calculate the shift between chans due to the angle
            // ch0 is always unshifted; other chans shifted w.r.t. ch0
            // jitter the shift by the specified timing resolution
            const Double_t shift = 
               rnd.Gaus( (ch==0) ? 0.0
                            : -pwdt.At( TSnRecoChanOffsets::IndexFor(ch, 0) ),
                         timereso);
            // get a graph of the waveform
            // data only in channel 0 of the template
            TGraph* gch = wave->NewGraphForChan(0, kTRUE);
            // "fit" the graph with an spline interpolation
            TSpline3* gsp = new TSpline3("stmp", gch);
            // evaluate the spline at the new sample positions
            // (shifted, but NOT wrapped)
            // and save that into the event data waveform
            Float_t* d = evdat->GetData(ch);
            const Float_t tstep = 1.0 / NSnConstants::kSampRate;
            const Float_t tlast = static_cast<Float_t>(NSnConstants::kNsamps-1)
               / NSnConstants::kSampRate;
            Float_t xloc = shift;
            for (UChar_t s=0; s<NSnConstants::kNsamps; ++s, ++d, xloc+=tstep) {
               if ( (xloc<0.0) || (xloc>=tlast) ) {
                  *d = 0.0;
               } else {
                  *d = gsp->Eval( xloc );
               }
            }
#ifdef DEBUG
            Printf("ch%hhu: shift=%g, dt=%g", ch, shift,
                   (ch==0) ? 0.0
                   : pwdt.At( TSnRecoChanOffsets::IndexFor(ch, 0) ));
            
            TGraph* fch = evdat->NewGraphForChan(ch, kTRUE);
            Double_t* y = gch->GetY();
            Double_t* fy = fch->GetY();
            for (UChar_t s=0; s<NSnConstants::kNsamps; ++s, ++y, ++fy) {
               *y *= norm;
               *fy *= norm;
            }
            
            gch->SetLineColor(kRed+1);
            gch->SetMarkerColor(kRed+1);
            gch->SetMarkerStyle(7);
            gch->Draw("pl");
            
            delete gsp;
            gsp = new TSpline3("stmp",gch);
            gsp->SetLineColor(kAzure-6);
            gsp->SetMarkerColor(kAzure-6);
            gsp->SetMarkerStyle(7);
            gsp->Draw("pl same");
            
            graphs.Add(fch);
            fch->SetLineColor(kOrange+7);
            fch->SetMarkerColor(kOrange+7);
            fch->SetMarkerStyle(7);
            fch->Draw("pl");
#endif


            d = evdat->GetData(ch);
            // finally add noise to the waveform
            for (UChar_t s=0; s<NSnConstants::kNsamps; ++s, ++d) {
               *d = rnd.Gaus( (*d) * norm, noise );
            }
            
#ifdef DEBUG
            TGraph* nch = evdat->NewGraphForChan(ch, kTRUE);
            graphs.Add(nch);
            nch->SetLineColor(kGreen+2);
            nch->SetMarkerColor(kGreen+2);
            nch->SetMarkerStyle(7);
            nch->Draw("pl");
#endif
            
            // cleanup
#ifdef DEBUG
            graphs.Add(gch);
            graphs.Add(gsp);
#else
            delete gch;
            delete gsp;
#endif
         }

      } // end channel loop

#ifdef DEBUG
      TObject* o(0);
      while ( (o=c1->WaitPrimitive())!=0 ) {
         gSystem->ProcessEvents();
      }
      delete c1;
#endif
         
         // save this event
         ot->Fill();
         
   } // end event loop

   fprintf(stderr,"\n");

   timer.Stop();
   Printf("Finished generating events in:");
   timer.Print();
   
   outf->Write();
   
   Printf("Wrote [%s]",outf->GetName());
   
   delete outf; outf=0; // close file
}
Example #24
0
void getCalibrationResults(TString url="TopMassCalibration.root",int nCategs=4)
{
  TString mpts[]={"161.5","163.5","166.5","169.5","172.5","175.5","178.5","181.5","184.5"};
  const size_t nmpts=sizeof(mpts)/sizeof(TString);

  std::vector<TString> labels;
  if(nCategs==2)
    {
      labels.push_back("1 b-tags");
      labels.push_back("#geq 2 b-tags");
    }
  else if(nCategs==4)
    {
      labels.push_back("1 b-tags (ee+#mu#mu)");
      labels.push_back("#geq 2 b-tags (ee+#mu#mu)");
      labels.push_back("1 b-tags (e#mu)");
      labels.push_back("#geq 2 b-tags (e#mu)");
    }
  else 
    {
      labels.push_back("1 b-tags (ee)");
      labels.push_back("#geq 2 b-tags (ee)");
      labels.push_back("1 b-tags (#mu#mu)");
      labels.push_back("#geq 2 b-tags (#mu#mu)");
      labels.push_back("1 b-tags (e#mu)");
      labels.push_back("#geq 2 b-tags (e#mu)");
    }
  
  TString outDir=gSystem->DirName(url);
  report << "Plots will be stored at @ " << outDir << endl;

  TGraphErrors *lingr = new TGraphErrors;  
  lingr->SetMarkerStyle(20);
  TGraphErrors *biasgr = new TGraphErrors; 
  biasgr->SetMarkerStyle(20);
  std::vector<TGraphErrors *> categbiasgr;
  for(int icat=0; icat<nCategs; icat++) categbiasgr.push_back( new TGraphErrors );
  TObjArray statUncResults;
  TObjArray pullResults;

  //get results from file
  TFile *fin=TFile::Open(url);
  for(size_t i=0; i<nmpts; i++)
    {
      Float_t trueMass=mpts[i].Atof();
      
      TH1D *massFitH=(TH1D *)fin->Get(mpts[i]+"/massfit");
      if(massFitH==0) continue;

      TF1 *ffunc=massFitH->GetFunction("gaus");
      float avgMass=ffunc->GetParameter(1);
      float avgMassErr=ffunc->GetParError(1);
      int ipt=lingr->GetN();
      lingr->SetPoint(ipt,trueMass,avgMass);
      lingr->SetPointError(ipt,0,avgMassErr);

      for(int icat=0; icat<=nCategs;icat++)
	{
	  TString postfix("");
	  TGraphErrors *gr=biasgr;
	  if(icat<nCategs){ postfix ="_"; postfix +=( icat+1); gr=categbiasgr[icat]; }
	  TH1D *biasH=(TH1D *)fin->Get(mpts[i]+"/bias"+postfix);
	  ffunc=biasH->GetFunction("gaus");
	  float avgBias=ffunc->GetParameter(1);
	  float avgBiasErr=ffunc->GetParError(1);   
	  ipt=gr->GetN();
	  gr->SetPoint(ipt,trueMass,avgBias);
	  gr->SetPointError(ipt,0,avgBiasErr);
	
	  if(trueMass==172.5) 
	    { 
	      TH1D *h=(TH1D *)fin->Get(mpts[i]+"/statunc"+postfix); 
	      h->SetDirectory(0);
	      h->SetLineColor(icat==nCategs? 1 : icat+2); 
	      h->SetMarkerColor(icat==nCategs? 1 : icat+2); 
	      h->SetMarkerStyle(1);
	      h->SetLineWidth(2);
	      statUncResults.Add(h);
	    }  
	}



      TH1D *pullH=(TH1D *)fin->Get(mpts[i]+"/pull");
      pullH->SetDirectory(0);
      pullResults.Add(pullH);
    }
  fin->Close();


  //plot results
  setStyle();
  gStyle->SetOptFit(0);

  TCanvas *c=new TCanvas("linc","linc",600,600);
  c->SetWindowSize(600,600);
  c->Divide(1,2);
  TPad *p=(TPad *)c->cd(1);
  p->SetPad(0,0.3,1.0,1.0);
  lingr->Draw("ap");
  lingr->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]");
  lingr->GetXaxis()->SetTitle("Fitted m_{top} [GeV/c^{2}]");

  TLine *l=new TLine(lingr->GetXaxis()->GetXmin(),lingr->GetYaxis()->GetXmin(),
		     lingr->GetXaxis()->GetXmax(),lingr->GetYaxis()->GetXmax());
  l->SetLineColor(kGray);
  l->SetLineStyle(6);
  l->Draw("same");
  TLegend *leg = p->BuildLegend();
  formatForCmsPublic(p,leg,"CMS simulation",3);
  leg->Delete();


  p=(TPad *)c->cd(2);
  p->SetPad(0,0.0,1.0,0.28);
  p->SetTopMargin(0);
  p->SetBottomMargin(0.5);
  float yscale = (1.0-0.3)/(0.28-0);
  biasgr->Draw("ap");
  biasgr->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]");
  biasgr->GetYaxis()->SetTitle("Bias");
  biasgr->GetYaxis()->SetRangeUser(-5.2,5.2);
  biasgr->GetXaxis()->SetTitleOffset(0.85);
  biasgr->GetXaxis()->SetLabelSize(0.04 * yscale);
  biasgr->GetXaxis()->SetTitleSize(0.05 * yscale);
  biasgr->GetXaxis()->SetTickLength( 0.03 * yscale );
  biasgr->GetYaxis()->SetTitleOffset(0.5);
  biasgr->GetYaxis()->SetLabelSize(0.04 * yscale);
  biasgr->GetYaxis()->SetTitleSize(0.04 * yscale);
  biasgr->Fit("pol1");
  float a=biasgr->GetFunction("pol1")->GetParameter(1);
  float b=biasgr->GetFunction("pol1")->GetParameter(0);
  report << "[Inclusive bias correction] resslope:" << (a+1.) << " resbias:" << b << endl;
  c->Modified();
  c->Update();
  c->SaveAs(outDir+"/TopMassCalibrationResults.C");
  c->SaveAs(outDir+"/TopMassCalibrationResults.png");
  c->SaveAs(outDir+"/TopMassCalibrationResults.pdf");
  //  delete c;
  
  //biases per category
  c=new TCanvas("biasc","biasc",600,600);
  c->SetWindowSize(600,600);
  c->Divide(1,nCategs+1);
  c->cd(nCategs+1)->Delete();
  float ystep=(1.0)/(nCategs+1);
  for(int icat=nCategs-1; icat>=0; --icat)
    {
      TGraphErrors *gr=categbiasgr[icat];
      gr->SetMarkerStyle(20);
      TPad *p=(TPad *)c->cd(icat+1);
      p->SetFillStyle(1001);
      p->SetFillColor(0);
      float ymin=(icat+1)*ystep-0.05;
      float ymax=(icat+2)*ystep-0.05;
      if(icat==0)
	{
	  ymin=icat*ystep;
	}
      p->SetPad(0,ymin,1.0,ymax);
      p->SetTopMargin(0.0);
      p->SetBottomMargin(icat==0?0.4:0.0);
      gr->Draw("ap");
      float yscale = (0.95-ystep)/(ystep-0.0);
      if(icat==0) yscale=(0.95-2*ystep)/(1.2*ystep-0);
      if(icat==0) gr->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]");
      else gr->GetXaxis()->SetNdivisions(0);
      gr->GetYaxis()->SetTitle("Bias");
      gr->GetYaxis()->SetRangeUser(-5.2,5.2);
      gr->GetXaxis()->SetTitleOffset(0.85);
      gr->GetXaxis()->SetLabelSize(0.04 * yscale);
      gr->GetXaxis()->SetTitleSize(0.05 * yscale);
      gr->GetXaxis()->SetTickLength( 0.03 * yscale );
      gr->GetYaxis()->SetTitleOffset(icat==0?0.5:0.3);
      gr->GetYaxis()->SetLabelSize(0.04 * yscale);
      gr->GetYaxis()->SetTitleSize(0.04 * yscale);
      gr->Fit("pol1");
      float a=gr->GetFunction("pol1")->GetParameter(1);
      float b=gr->GetFunction("pol1")->GetParameter(0);
      report << "[Bias correction #" << icat+1 << "] resslope:" << (a+1.) << " resbias:" << b << endl;
      
      //prepare label
      TPaveText *pave = new TPaveText(0.70,0.65,0.8,0.92,"NDC");
      pave->SetTextFont(42);
      pave->SetFillStyle(0);
      pave->SetBorderSize(0);
      pave->AddText( labels[icat] )->SetTextAlign(11);
      pave->Draw();

      if(icat==nCategs-1)
	{
	  pave = new TPaveText(0.2,0.75,0.45,0.92,"NDC");
	  pave->SetTextFont(42);
	  pave->SetFillStyle(0);
	  pave->SetBorderSize(0);
	  pave->AddText( "CMS simulation" )->SetTextAlign(11);
	  pave->Draw();
	}
    }
  c->Modified();
  c->Update();
  c->SaveAs(outDir+"/TopMassCalibrationBiases.C");
  c->SaveAs(outDir+"/TopMassCalibrationBiases.png");
  c->SaveAs(outDir+"/TopMassCalibrationBiases.pdf");
  //delete c;

  //stat uncertainty
  c=new TCanvas("statc","statc",600,600);
  c->SetWindowSize(600,600);
  for(int i=0; i<statUncResults.GetEntriesFast(); i++)
    {
      int idx=statUncResults.GetEntriesFast()-1-i;
      statUncResults.At(idx)->Draw(i==0?"hist":"histsame");
      ((TH1*)statUncResults.At(idx))->SetTitle( i==0 ? "combined" :labels[idx] );
    }
  leg = c->BuildLegend();
  formatForCmsPublic(c,leg,"CMS simulation",3);  c->Modified();
  c->Update();
  c->SaveAs(outDir+"/TopMassCalibrationStat.C");
  c->SaveAs(outDir+"/TopMassCalibrationStat.png");
  c->SaveAs(outDir+"/TopMassCalibrationStat.pdf");
  //delete c;
  
  //pulls
  TGraphErrors *avgPull = new TGraphErrors;   avgPull->SetMarkerStyle(20);
  TGraphErrors *sigmaPull = new TGraphErrors; sigmaPull->SetMarkerStyle(20);
  c=new TCanvas("pullsc","pullsc",1600,(pullResults.GetEntriesFast()/4+1)*400);
  c->SetWindowSize(1600,(pullResults.GetEntriesFast()/4+1)*400);
  c->Divide(4,pullResults.GetEntriesFast()/4+1);
  for(int i=0; i<pullResults.GetEntriesFast(); i++)
    {
      TPad *p=(TPad *)c->cd(i+1);
      TH1 *pullH=(TH1 *)pullResults.At(i);
      pullH->Draw("e1");

      Float_t trueMass=mpts[i].Atof();
      TF1 *gaus=pullH->GetFunction("gaus");
      avgPull->SetPoint(i,trueMass,gaus->GetParameter(1));
      avgPull->SetPointError(i,0,gaus->GetParError(1));
      sigmaPull->SetPoint(i,trueMass,gaus->GetParameter(2));
      sigmaPull->SetPointError(i,0,gaus->GetParError(2));

      if(i==0)
	{
	  leg = p->BuildLegend();
	  formatForCmsPublic(p,leg,"CMS simulation",3);
	  leg->Delete();
	}
      
      TPaveText *pave = new TPaveText(0.2,0.8,0.35,0.88,"NDC");
      pave->SetTextFont(42);
      pave->SetFillStyle(0);
      pave->SetBorderSize(0);
      pave->AddText( mpts[i] )->SetTextAlign(11);
      pave->Draw();

    }
  c->Modified();
  c->Update();
  c->SaveAs(outDir+"/TopMassCalibrationPulls.C");
  c->SaveAs(outDir+"/TopMassCalibrationPulls.png");
  c->SaveAs(outDir+"/TopMassCalibrationPulls.pdf");
  //delete c;

  //pull momenta
  c=new TCanvas("pullsmomc","pullsmomc",600,600);
  c->SetWindowSize(600,600);
  c->Divide(1,2);
  p=(TPad *)c->cd(1);
  avgPull->Draw("ap");
  avgPull->GetYaxis()->SetRangeUser(-3,3);
  avgPull->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]");
  avgPull->GetYaxis()->SetTitle("Average pull");
  leg = p->BuildLegend();
  formatForCmsPublic(p,leg,"CMS simulation",3);
  leg->Delete();
  c->cd(2);
  sigmaPull->GetYaxis()->SetRangeUser(0.9,1.2);
  sigmaPull->Draw("ap");
  sigmaPull->GetXaxis()->SetTitle("Generated m_{top} [GeV/c^{2}]");
  sigmaPull->GetYaxis()->SetTitle("Pull width");
  c->Modified();
  c->Update();
  c->SaveAs(outDir+"/TopMassCalibrationPullsMomenta.C");
  c->SaveAs(outDir+"/TopMassCalibrationPullsMomenta.png");
  c->SaveAs(outDir+"/TopMassCalibrationPullsMomenta.pdf");
  //delete c;

  cout << report.str() << endl;


}
Example #25
0
//-------------------------------------------------------------------------------------------------------------------------------------------
void ComparisonDataMC(TString fileNameData = "Data/efficiency_new.root", TString fileNameSim ="MonteCarlo/efficiency_new.root", Bool_t integrated = kFALSE)
{
  // Open input Data files
  TFile *fileData = new TFile(fileNameData.Data(), "read");
  if (!fileData || !fileData->IsOpen()) {
    printf("cannot open file %s \n",fileNameData.Data());
    return;
  }
  // Open input Sim files
  TFile *fileSim = new TFile(fileNameSim.Data(), "read");
  if (!fileSim || !fileSim->IsOpen()) {
    printf("cannot open file %s \n",fileNameSim.Data());
    return;
  }
  
  TString hname = integrated ? "integratedTracking" : "tracking";
  
  // Get Global Data and Sim graphs
  
//  TGraphAsymmErrors *effVScentData = static_cast<TGraphAsymmErrors*>(fileData->FindObjectAny("trackingEffVscentrality"));
//  if (!effVScentData) {
//    printf("Efficiency vs centrality from data not found\n");
//    return;
//  }
//  TGraphAsymmErrors *effVScentSim = static_cast<TGraphAsymmErrors*>(fileSim->FindObjectAny("trackingEffVscentrality"));
//  if (!effVScentSim) {
//    printf("Efficiency vs centrality from sim not found\n");
//    return;
//  }
  
  TGraphAsymmErrors *effVSrunData = static_cast<TGraphAsymmErrors*>(fileData->FindObjectAny("trackingEffVsRun"));
  if (!effVSrunData) {
    printf("Efficiency vs run from data not found\n");
    return;
  }
  TGraphAsymmErrors *effVSrunSim = static_cast<TGraphAsymmErrors*>(fileSim->FindObjectAny("trackingEffVsRun"));
  if (!effVSrunSim) {
    printf("Efficiency vs run from sim not found\n");
    return;
  }
  
  
  TGraphAsymmErrors *effVSyData = static_cast<TGraphAsymmErrors*>(fileData->FindObjectAny(Form("%sEffVsy",hname.Data())));
  if (!effVSyData) {
    printf("Efficiency vs rapidity from data not found\n");
    return;
  }
  TGraphAsymmErrors *effVSySim = static_cast<TGraphAsymmErrors*>(fileSim->FindObjectAny(Form("%sEffVsy",hname.Data())));
  if (!effVSySim) {
    printf("Efficiency vs rapidity from sim not found\n");
    return;
  }

  
  TGraphAsymmErrors *effVSptData = static_cast<TGraphAsymmErrors*>(fileData->FindObjectAny(Form("%sEffVspt",hname.Data())));
  if (!effVSptData) {
    printf("Efficiency vs pt from data not found\n");
    return;
  }
  TGraphAsymmErrors *effVSptSim = static_cast<TGraphAsymmErrors*>(fileSim->FindObjectAny(Form("%sEffVspt",hname.Data())));
  if (!effVSptSim) {
    printf("Efficiency vs pt from sim not found\n");
    return;
  }
  
  TGraphAsymmErrors *effVSphiData = static_cast<TGraphAsymmErrors*>(fileData->FindObjectAny(Form("%sEffVsphi",hname.Data())));
  if (!effVSphiData) {
    printf("Efficiency vs phi from data not found\n");
    return;
  }
  TGraphAsymmErrors *effVSphiSim = static_cast<TGraphAsymmErrors*>(fileSim->FindObjectAny(Form("%sEffVsphi",hname.Data())));
  if (!effVSphiSim) {
    printf("Efficiency vs phi from sim not found\n");
    return;
  }
  
  // Create an array list with the global ratios
  TObjArray globalRatios;
  
  // Create an array with the global plots of the individual efficencies and the ratios
  TObjArray globalRatiosAndEff;
  
//  globalRatios.Add(CreateRatioGraph("RatioEffVsCent","data/sim tracking efficiency versus centrality",effVScentData,effVScentSim));
  
  //---- Eff vs run
  TGraphAsymmErrors* effVSrunDataCopy = static_cast<TGraphAsymmErrors*>(effVSrunData->Clone()); // We make clones to do not modify them
  TGraphAsymmErrors* effVSrunSimCopy = static_cast<TGraphAsymmErrors*>(effVSrunSim->Clone());
  
  TGraphAsymmErrors *ratioRun = CreateRatioGraph("RatioEffVsRun","data/sim tracking efficiency versus run",*effVSrunData,*effVSrunSim);
  globalRatios.Add(ratioRun);
  
  TGraphAsymmErrors* ratioRunCopy = static_cast<TGraphAsymmErrors*>(ratioRun->Clone());
  
  globalRatiosAndEff.Add(DrawRatio("RatioEffVSRunAndEff","Comparison Data&MC tracking efficiency versus run", effVSrunDataCopy,effVSrunSimCopy,ratioRunCopy));
  //-----
  
  //---- Eff vs y
  TGraphAsymmErrors* effVSyDataCopy = static_cast<TGraphAsymmErrors*>(effVSyData->Clone()); // We make clones to do not modify them
  TGraphAsymmErrors* effVSySimCopy = static_cast<TGraphAsymmErrors*>(effVSySim->Clone());
  
  TGraphAsymmErrors *ratioY = CreateRatioGraph("RatioEffVsY","data/sim tracking efficiency versus rapidity",*effVSyData,*effVSySim);
  globalRatios.Add(ratioY);
  
  TGraphAsymmErrors* ratioYCopy = static_cast<TGraphAsymmErrors*>(ratioY->Clone());
 
  globalRatiosAndEff.Add(DrawRatio("RatioEffVSyAndEff","Comparison Data&MC tracking efficiency versus rapidity", effVSyDataCopy,effVSySimCopy,ratioYCopy));
  //-----

  //-----Eff vs Pt
  TGraphAsymmErrors* effVSptDataCopy = static_cast<TGraphAsymmErrors*>(effVSptData->Clone()); // We make clones to do not modify them
  TGraphAsymmErrors* effVSptSimCopy = static_cast<TGraphAsymmErrors*>(effVSptSim->Clone());

  TGraphAsymmErrors *ratioPt = CreateRatioGraph("RatioEffVsPt","data/sim tracking efficiency versus Pt",*effVSptData,*effVSptSim);
  globalRatios.Add(ratioPt);
  
  TGraphAsymmErrors* ratioPtCopy = static_cast<TGraphAsymmErrors*>(ratioPt->Clone());
  
   globalRatiosAndEff.Add(DrawRatio("RatioEffVSptAndEff","Comparison Data&MC tracking efficiency versus Pt",effVSptDataCopy,effVSptSimCopy,ratioPtCopy));
  //-----
  
  //----Eff vs phi
  TGraphAsymmErrors* effVSphiDataCopy = static_cast<TGraphAsymmErrors*>(effVSphiData->Clone()); // We make clones to do not modify them
  TGraphAsymmErrors* effVSphiSimCopy = static_cast<TGraphAsymmErrors*>(effVSphiSim->Clone());
  
  TGraphAsymmErrors *ratioPhi = CreateRatioGraph("RatioEffVsPhi","data/sim tracking efficiency versus phi",*effVSphiData,*effVSphiSim);
  globalRatios.Add(ratioPhi);
  
  TGraphAsymmErrors* ratioPhiCopy = static_cast<TGraphAsymmErrors*>(ratioPhi->Clone());
  
  globalRatiosAndEff.Add(DrawRatio("RatioEffVSphiAndEff","Comparison Data&MC tracking efficiency versus phi",effVSphiDataCopy,effVSphiSimCopy,ratioPhiCopy));
  //-------
  
  //----Eff vs y vs phi

  TH2F *effVSyVSphiData = static_cast<TH2F*>(fileData->FindObjectAny("trackingEffVsphi-y"));
  if (!effVSyVSphiData) {
    printf("Efficiency vs rapidity vs phi from data not found\n");
    return;
  }
  TH2F *effVSyVSphiSim = static_cast<TH2F*>(fileSim->FindObjectAny("trackingEffVsphi-y"));
  if (!effVSyVSphiSim) {
    printf("Efficiency vs rapidity vs phi from sim not found\n");
    return;
  }
  Int_t nBins2dX = effVSyVSphiData->GetXaxis()->GetNbins();
  Int_t nBins2dY = effVSyVSphiData->GetYaxis()->GetNbins();
  Double_t effData2D,effSim2D,ratio2D;
  
  TH2F *effVSphiVSyRatio = new TH2F("RatioEffVSphiVSy","EffData/EffSim vs phi vs y",nBins2dX, effVSyVSphiData->GetXaxis()->GetBinLowEdge(1), effVSyVSphiData->GetXaxis()->GetBinUpEdge(nBins2dX),nBins2dY, effVSyVSphiData->GetYaxis()->GetBinLowEdge(1), effVSyVSphiData->GetYaxis()->GetBinUpEdge(nBins2dY));
  effVSphiVSyRatio->GetXaxis()->SetTitle("phi");
  effVSphiVSyRatio->GetYaxis()->SetTitle("y");
    
  for (Int_t i = 1 ; i <= nBins2dX ; i++ )
  {
    for (Int_t j = 1 ; j <= nBins2dY ; j++ )
    {
      effData2D = effVSyVSphiData->GetBinContent(i,j);
      effSim2D = effVSyVSphiSim->GetBinContent(i,j);

      if (effData2D > 0. && effSim2D > 0.)
      {
        ratio2D = effData2D/effSim2D;
//        ratio2DErrh = rat*TMath::Sqrt(effDErrh*effDErrh/effD*effD + effSErrl*effSErrl/effS*effS);
//        ratio2DErrl = rat*TMath::Sqrt(effDErrl*effDErrl/effD*effD + effSErrh*effSErrh/effS*effS);
      }
      if (effData2D == 0 && effSim2D == 0)
      {
        ratio2D = 1.;
//        ratio2DErrh = 0.;
//        ratio2DErrl = 0.;
      }
      if (effData2D == 0 && effSim2D > 0.)
      {
        ratio2D = 0.;
//        ratio2DErrh = 0.;
//        ratio2DErrl = 0.;
      }
      if (effData2D > 0. && effSim2D == 0)
      {
        ratio2D = 2.;
//        ratio2DErrh = 0.;
//        ratio2DErrl = 0.;
      }
      effVSphiVSyRatio->SetBinContent(i,j,ratio2D);
    }
  }
  
  
  TH2F *effVSphiVSyRatioRapBins = new TH2F();
  effVSphiVSyRatioRapBins->GetXaxis()->SetTitle("phi");
  effVSphiVSyRatioRapBins->GetYaxis()->SetTitle("y");
  effVSphiVSyRatioRapBins->SetName("RatioEffVSphiVSyRapBins");
  effVSphiVSyRatioRapBins->SetTitle("EffData/EffSim vs phi vs y");

  
  Int_t nxBins = effVSphiVSyRatio->GetXaxis()->GetNbins();
  Int_t nyBins = effVSphiVSyRatio->GetYaxis()->GetNbins();
  
  Double_t xBinEdge[nxBins+1];
  Double_t yBinEdge[nyBins+1];
  
  for (Int_t ybin = 0 ; ybin <= nyBins ; ybin++)
  {
    yBinEdge[ybin] = 2*TMath::ATan(TMath::Exp((effVSphiVSyRatio->GetYaxis()->GetBinLowEdge(ybin+1))));
  }
  for (Int_t xbin = 0 ; xbin <= nxBins ; xbin++)
  {
    xBinEdge[xbin] = effVSphiVSyRatio->GetXaxis()->GetBinLowEdge(xbin+1);
  }
  
  effVSphiVSyRatioRapBins->SetBins(nxBins,xBinEdge,nyBins,yBinEdge);
  
  for (Int_t xbin = 1 ; xbin <= nxBins ; xbin++)
  {
    for (Int_t ybin = 1 ; ybin <= nyBins ; ybin++)
    {
      effVSphiVSyRatioRapBins->SetBinContent(xbin,ybin,effVSphiVSyRatio->GetBinContent(xbin,ybin));
    }
  }
  globalRatiosAndEff.Add(effVSphiVSyRatio);
  globalRatiosAndEff.Add(effVSphiVSyRatioRapBins);

 
  //--------
  
  TString hname2 = integrated ? "IntegratedChamber" : "Chamber";
  
  // Get Chamber and DE Data and Sim graphs
//  TObjArray *listChEffVSrunData = static_cast<TObjArray*>(fileData->FindObjectAny("ChambersEffVSrun"));
//  if (!listChEffVSrunData) {
//    printf("list of Chamber efficiencies vs run from data not found\n");
//    return;
//  }
//  TObjArray *listChEffVSrunSim = static_cast<TObjArray*>(fileSim->FindObjectAny("ChambersEffVSrun"));
//  if (!listChEffVSrunSim) {
//    printf("list of Chamber efficiencies vs run from sim not found\n");
//    return;
//  }

  TObjArray *listChEffVSDEData = static_cast<TObjArray*>(fileData->FindObjectAny(Form("%sEffVsDE",hname2.Data())));
  if (!listChEffVSDEData) {
    printf("list of Chamber efficiencies per DE from data not found\n");
    return;
  }
  TObjArray *listChEffVSDESim = static_cast<TObjArray*>(fileSim->FindObjectAny(Form("%sEffVsDE",hname2.Data())));
  if (!listChEffVSDESim) {
    printf("list of Chamber efficiencies per DE from sim not found\n");
    return;
  }
  
//  TObjArray *listDEEffVSrunData = static_cast<TObjArray*>(fileData->FindObjectAny("DEEffVSrun"));
//  if (!listDEEffVSrunData) {
//    printf("list of DE efficiencies vs run from data not found\n");
//    return;
//  }
//  TObjArray *listDEEffVSrunSim = static_cast<TObjArray*>(fileSim->FindObjectAny("DEEffVSrun"));
//  if (!listDEEffVSrunSim) {
//    printf("list of DE efficiencies vs run from sim not found\n");
//    return;
//  }
  
  // Graph for global efficiency vs run
  TGraphAsymmErrors* gData ;//= static_cast<TGraphAsymmErrors*>(listChEffVSrunData->At(0));
  TGraphAsymmErrors* gSim ;//= static_cast<TGraphAsymmErrors*>(listChEffVSrunSim->At(0));
  
  
  //----Eff vs run  
//  TGraphAsymmErrors *ratioEffvsrRun = CreateRatioGraph("RatioEffVsRun","data/sim tracking efficiency versus run",*gData,*gSim);
//  globalRatios.Add(ratioEffvsrRun);
//  
//  TGraphAsymmErrors* ratioEffvsrRunCopy = static_cast<TGraphAsymmErrors*>(ratioEffvsrRun->Clone());
//  
//  globalRatiosAndEff.Add(DrawRatio("RatioEffVsRunAndEff","Comparison Data&MC tracking efficiency versus run",gData,gSim,ratioEffvsrRunCopy));
  //-------

  //globalRatios.Add(CreateRatioGraph("RatioEffVsRun","data/sim tracking efficiency versus run",*gData,*gSim));
  
  // Create a list with the Chamber and DE ratios
//  TObjArray chamberVSrunRatios;
//  TObjArray deVSrunRatios;
  TObjArray chamberVSdeRatios;
  
//  TObjArray chamberVSrunRatiosAndEff;
//  TObjArray deVSrunRatiosAndEff;
  TObjArray chamberVSdeRatiosAndEff;
  
  // Compute the ratios for Chamber vs run
//  for (Int_t nList = 1 ; nList < listChEffVSrunData->GetEntries() ; nList++)
//  {
//    gData = static_cast<TGraphAsymmErrors*>(listChEffVSrunData->At(nList));
//    gSim = static_cast<TGraphAsymmErrors*>(listChEffVSrunSim->At(nList));
//    if (!gData || !gSim )
//    {
//      printf("Error readig from Chamber efficiency vs run list \n");
//      return;
//    }
//    //----Eff of Chs vs run
//    TString name =  Form("RatioEffCh%dVsRun",nList); TString title = Form("Chamber %d data/sim tracking efficiency versus run",nList);
//    
//    TGraphAsymmErrors *ratioEffChVsrRun = CreateRatioGraph(name.Data(),title.Data(),*gData,*gSim);
//    chamberVSrunRatios.Add(ratioEffChVsrRun);
//    
//    TGraphAsymmErrors* ratioEffChVsrRunCopy = static_cast<TGraphAsymmErrors*>(ratioEffChVsrRun->Clone());
//    
//    TString nameRatio =  Form("RatioEffCh%dVsRunAndEff",nList); TString titleRatio = Form("Comparison Data&MC Ch%d tracking efficiency versus run",nList);
//    chamberVSrunRatiosAndEff.Add(DrawRatio(nameRatio.Data(),titleRatio.Data(),gData,gSim,ratioEffChVsrRunCopy));
//    //-------
//
//    
////    chamberVSrunRatios.Add(CreateRatioGraph(,,*gData,*gSim));
//    
//  }
  
  //Load the mapping for the DE histos
  AliCDBManager::Instance()->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  AliCDBManager::Instance()->SetRun(0);
  AliMUONCDB::LoadMapping();
  AliMpDEIterator deit;

  // Loop over Chambers
  for (Int_t ich = 0 ; ich < 10 ; ich++)
  {
    // Compute the ratios for DE vs run
    deit.First(ich);
  
//    while ( !deit.IsDone() )
//    {
//      TString currentDEName = Form("EffDE%dVSrun",deit.CurrentDEId());
//      gData = static_cast<TGraphAsymmErrors*>(listDEEffVSrunData->FindObject(currentDEName.Data()));
//      gSim = static_cast<TGraphAsymmErrors*>(listDEEffVSrunSim->FindObject(currentDEName.Data()));
//      
//      TString name =  Form("RatioEffDE%dVsRun",deit.CurrentDEId()); TString title = Form("DE %d data/sim tracking efficiency versus run",deit.CurrentDEId());
//      if (!gData || !gSim )
//      {
//        printf("Error readig from DE efficiency vs run list \n");
//        return;
//      }
//      //----Eff of DEs vs run
//      TGraphAsymmErrors *ratioEffDEvsRun = CreateRatioGraph(name.Data(),title.Data(),*gData,*gSim);
//      deVSrunRatios.Add(ratioEffDEvsRun);
//      
//      TGraphAsymmErrors* ratioEffDEvsRunCopy = static_cast<TGraphAsymmErrors*>(ratioEffDEvsRun->Clone());
//      
//      TString nameRatio =  Form("RatioEffDE%dVsRunAndEff",deit.CurrentDEId()); TString titleRatio = Form("Comparison Data&MC DE%d tracking efficiency versus run",deit.CurrentDEId());
//      deVSrunRatiosAndEff.Add(DrawRatio(nameRatio.Data(),titleRatio.Data(),gData,gSim,ratioEffDEvsRunCopy));
//      //-------
//
////      deVSrunRatios.Add(CreateRatioGraph(name.Data(),title.Data(),*gData,*gSim));
//      
//      deit.Next();
//    }
  
    // Compute the ratios for Ch vs DE
    TString hname3 = integrated ? "integratedEff" : "eff";
    gData = static_cast<TGraphAsymmErrors*>(listChEffVSDEData->FindObject(Form("%sCh%dVsDE",hname3.Data(),ich+1)));
    gSim = static_cast<TGraphAsymmErrors*>(listChEffVSDESim->FindObject(Form("%sCh%dVsDE",hname3.Data(),ich+1)));
    
    if (!gData || !gSim )
    {
      printf("Error reading from Chamber efficiency per DE list \n");
      return;
    }
    TString name =  Form("RatioEffCh%dVsDE",ich+1); TString title = Form("Chamber %d data/sim tracking efficiency versus DE",ich+1);
    //----Eff of CHs vs DE
    TGraphAsymmErrors *ratioEffChvsDE = CreateRatioGraph(name.Data(),title.Data(),*gData,*gSim);
    chamberVSdeRatios.Add(ratioEffChvsDE);
    
    TGraphAsymmErrors* ratioEffChvsDECopy = static_cast<TGraphAsymmErrors*>(ratioEffChvsDE->Clone());
    
    TString nameRatio =  Form("RatioEffCh%dVsDEAndEff",ich+1); TString titleRatio = Form("Comparison Data&MC Ch%d tracking efficiency versus DE",ich+1);
    chamberVSdeRatiosAndEff.Add(DrawRatio(nameRatio.Data(),titleRatio.Data(),gData,gSim,ratioEffChvsDECopy));
    //-------

    
//    chamberVSdeRatios.Add(CreateRatioGraph(name.Data(),title.Data(),*gData,*gSim));
    
  }

  //Beautify graphs
  BeautifyGraphs(globalRatios,"EffData/EffSim");
//  BeautifyGraphs(deVSrunRatios,"EffData/EffSim");
//  BeautifyGraphs(chamberVSrunRatios,"EffData/EffSim");
  BeautifyGraphs(chamberVSdeRatios,"EffData/EffSim");

//  BeautifyGraphs(globalRatiosAndEff,"EffData/EffSim");
//  BeautifyGraphs(deVSrunRatiosAndEff,"EffData/EffSim");
//  BeautifyGraphs(chamberVSrunRatiosAndEff,"EffData/EffSim");
//  BeautifyGraphs(chamberVSdeRatiosAndEff,"EffData/EffSim");

  // set bin labels
//  SetRunLabel(deVSrunRatios,irun,runs);
//  SetRunLabel(chamberVSrunRatios,irun,runs);
//  SetRunLabel(globalRatios,irun,runs,1); //Write it in such a way the number is the position on the list of the graph you want to label
//  
  // save output
  TFile* file = new TFile("EffComparison.root","update");
  
  globalRatios.Write("GlobalEffRatios", TObject::kOverwrite | TObject::kSingleKey);
//  chamberVSrunRatios.Write("ChambersEffVSrunRatios", TObject::kOverwrite | TObject::kSingleKey);
//  deVSrunRatios.Write("DEEffVSrunRatios", TObject::kOverwrite | TObject::kSingleKey);
  chamberVSdeRatios.Write("ChamberEffperDERatios", TObject::kOverwrite | TObject::kSingleKey);
  
  globalRatiosAndEff.Write("GlobalEffRatiosAndEffs", TObject::kOverwrite | TObject::kSingleKey);
//  chamberVSrunRatiosAndEff.Write("ChambersEffVSrunRatiosAndEff", TObject::kOverwrite | TObject::kSingleKey);
//  deVSrunRatiosAndEff.Write("DEEffVSrunRatiosAndEff", TObject::kOverwrite | TObject::kSingleKey);
  chamberVSdeRatiosAndEff.Write("ChamberEffperDERatiosAndEff", TObject::kOverwrite | TObject::kSingleKey);

  
   
  file->Close();
 
  fileData->Close();
  fileSim->Close();
   


}
void TBDataParser::OnStartElement(const char *element, const TList *attributes)
{
	TXMLAttr *attr;
	TIter next(attributes);

	char *name = element;
	_currentElement = new TString(element);
	
	char *method = NULL;

	while ((attr = (TXMLAttr*) next())) {
		char *attrName = attr->GetName();
		char *attrValue = attr->GetValue();

		if(!strcmp(attrName, "name")) {
			name = attrValue; 
		}
		
		if(!strcmp(attrName, "method")) {
			method = attrValue;	
			_currentMethod = new TString(method);
		}
		
	}

	TFolder *currentFolder = _foldersStack->Last();

	if(!strcmp(element, "vector")) {
		TString *nameString = new TString(name);
		vector<float> *values = new vector<float>;
		_values = values;

		nameString->ReplaceAll(" ","_");

		TObjString *currentVector = new TObjString(nameString->Data());

		TObjArray *vectorsStack = _vectorsStack;
		vectorsStack->AddLast(currentVector);

		TString *joinedName = new TString(((TObjString *) vectorsStack->First())->GetString().Data());

		for(Int_t i = 1; i < vectorsStack->GetEntries(); i++) {
			joinedName->Append("_");
			joinedName->Append(((TObjString *) vectorsStack->At(i))->GetString().Data());
		}
		
		TObjString *joinedNameObj = new TObjString(joinedName->Data());
		TObjArray *joinedNameStack = _joinedNameStack;
		
		TNtuple *vector = new TNtuple(joinedName->Data(),joinedName->Data(),"values");
		_vector = vector;
		currentFolder->Add(vector);

		if(joinedNameStack->Contains(joinedName->Data()))
			cout << joinedName->Data() << "Error: " << "vector already exists. Be sure that in your XML file every vector has a unique path + name combination" << endl;
			
		joinedNameStack->Add(joinedNameObj);
			
			
		return;
	}

	_foldersStack->AddLast(currentFolder->AddFolder(name, name));
}
TObjArray getDistributionFromPlotter(TString plot,TString baseURL="~/scratch0/top-nosyst/plotter.root")
{
  using namespace std;

  setStyle();
  
  //the relevant processes
  TString procs[]={"Di-bosons","Single top", "W+jets", "Z-#gamma^{*}+jets#rightarrow ll", "other t#bar{t}", "t#bar{t} dileptons", "data"};
  const size_t nprocs=sizeof(procs)/sizeof(TString);

  //containers for the histos
  TList *data     = new TList;
  TH1F *totalData=0;
  TList *mc       = new TList;
  TH1F *totalMC=0;
  TH1F *ttbarMC=0;
  TList *spimpose = new TList;
  
  //open file with histograms
  TFile *f=TFile::Open(baseURL);
  for(size_t iproc=0; iproc<nprocs; iproc++)
    {
      TH1F *histo = (TH1F *) f->Get(procs[iproc]+"/"+plot);
      if(histo==0) { cout << "[Warning] " << plot << " not found for " << procs[iproc] << " ...skipping" << endl; continue; }
      histo->SetDirectory(0);
      if(procs[iproc].Contains("data")) 
	{
	  data->Add(histo);
	  if(totalData==0) { totalData = (TH1F *) histo->Clone(plot+"totaldata"); totalData->SetDirectory(0); }
	  else             { totalData->Add(histo); }
	}
      else
	{
	  mc->Add(histo);
	  if(totalMC==0) { totalMC = (TH1F *) histo->Clone(plot+"totalmc"); totalMC->SetDirectory(0); }
	  else           { totalMC->Add(histo); }
	  if(procs[iproc]=="t#bar{t} dileptons") { ttbarMC = (TH1F *)histo->Clone(plot+"ttbar"); ttbarMC->SetDirectory(0); }
	}
    }
  f->Close();

  cout << "Drawing now" << endl;
  
  //draw
  TCanvas *cnv = getNewCanvas(plot+"c",plot+"c",false);
  cnv->Clear();
  cnv->SetWindowSize(600,600);
  cnv->cd(); 
  TLegend *leg=showPlotsAndMCtoDataComparison(cnv,*mc,*spimpose,*data,false);
  formatForCmsPublic(cnv,leg,"CMS preliminary", 4);
  cnv->SaveAs(plot+".C");

  cout << "Stat comparison for " << plot << endl
       << "Sample \t Average \t\t RMS " << endl
       << "----------------------------------------" << endl;
  if(totalData) cout << "Data \t " << totalData->GetMean() << " +/- " << totalData->GetMeanError() << " \t " << totalData->GetRMS() << " +/- " << totalData->GetRMSError() << endl;
  if(totalMC)   cout << "MC \t "   << totalMC->GetMean() << " +/- " << totalMC->GetMeanError() << " \t " << totalMC->GetRMS() << " +/- " << totalMC->GetRMSError() << endl;
  if(ttbarMC)   cout << "Signal \t "   << ttbarMC->GetMean() << " +/- " << ttbarMC->GetMeanError() << " \t " << ttbarMC->GetRMS() << " +/- " << ttbarMC->GetRMSError() << endl;

  TObjArray res;
  res.Add(totalData);
  res.Add(totalMC);
  res.Add(ttbarMC);
  res.Add(mc);
  return res;
}
Int_t r3b_sim_and_rclass(){

   // Load the Main Simulation macro
   gROOT->LoadMacro("r3ball.C");

   //-------------------------------------------------
   // Monte Carlo type     |    fMC        (TString)
   //-------------------------------------------------
   //   Geant3:                 "TGeant3"
   //   Geant4:                 "TGeant4"
   //   Fluka :                 "TFluka"

   TString fMC ="TGeant3";

   //-------------------------------------------------
   // Primaries generation
   // Event Generator Type |   fGene       (TString)
   //-------------------------------------------------
   // Box generator:             "box"
   // Ascii generator:           "ascii"
   // R3B spec. generator:       "r3b"

   TString fGene="box";

   //-------------------------------------------------
   // Secondaries  generation (G4 only)
   // R3B Spec. PhysicList |     fUserPList (Bool_t)
   // ----------------------------------------------
   //     VMC Standard           kFALSE
   //     R3B Special            kTRUE;

   Bool_t fUserPList= kTRUE;

   // Target type
   TString target1="LeadTarget";
   TString target2="Para";
   TString target3="Para45";
   TString target4="LiH";

   //-------------------------------------------------
   //- Geometrical Setup Definition
   //-  Non Sensitiv        |    fDetName (String)
   //-------------------------------------------------
   //   Target:                  TARGET
   //   Magnet:                  ALADIN
   //
   //-------------------------------------------------
   //-  Sensitiv            |    fDetName
   //-------------------------------------------------
   //   Calorimeter:             CALIFA
   //                            CRYSTALBALL
   //
   //   Tof:                     TOF
   //                            MTOF
   //
   //   Tracker:                 DCH
   //                            TRACKER
   //                            GFI
   //
   //   Neutron Detector
   //   Plastic                  LAND
   //   RPC                      
   //                            RPCFLAND
   //                            RPCMLAND

    TObjString det1("TARGET");
    TObjString det2("ALADIN");
    TObjString det3("CALIFA");
    TObjString det4("CRYSTALBALL");
    TObjString det5("TOF");
    TObjString det6("MTOF");
    TObjString det7("DCH");
    TObjString det8("TRACKER");
    TObjString det9("GFI");
    TObjString det10("LAND");
    TObjString det11("RPCMLAND");
    TObjString det12("RPCFLAND");
    TObjString det13("SCINTNEULAND");

    TObjArray fDetList;
//    fDetList.Add(&det1);
    fDetList.Add(&det2);
//    fDetList.Add(&det4);
//    fDetList.Add(&det5);
//    fDetList.Add(&det6);
//    fDetList.Add(&det7);
//    fDetList.Add(&det8);
//    fDetList.Add(&det9);
    fDetList.Add(&det10);
//    fDetList.Add(&det11);


   //-------------------------------------------------
   //- N# of Sim. Events   |    nEvents     (Int_t)
   //-------------------------------------------------

   Int_t nEvents = 1;

   //-------------------------------------------------
   //- EventDisplay        |    fEventDisplay (Bool_t)
   //-------------------------------------------------
   //   connected:              kTRUE
   //   not connected:          kFALSE

   Bool_t fEventDisplay=kTRUE;

    // Magnet Field definition
   Bool_t fR3BMagnet = kTRUE;

   // Main Sim function call
   r3ball(  nEvents,
            fDetList,
            target1,
	    fEventDisplay,
	    fMC,
	    fGene,
	    fUserPList,
            fR3BMagnet
          );

//------------------- Read Data from LMD-ROOT file -------------------------------------
// the ROOT files (simulated and experimental) are the same but, for testing purpose, show how to use two quantities for comparison
   R3BLandData* LandData1 = new R3BLandData("s318_172.root", "h309"); // file input and tree name
   R3BLandData* LandData2 = new R3BLandData("s318_172.root", "h309"); // file input and tree name
// Define diferent options for TCanvas
   TCanvas* c = new TCanvas("Compare quantities from ROOT files","ROOT Canvas");
   c->Divide(2,1);                                                                 // Divide a canvas in two ...or more
   int entries1 = LandData1->GetEntries();                                         // entries number of first TTree
   int entries2 = LandData2->GetEntries();                                         // entries number of first TTree
   TLeaf* leaf1;
//   TLeaf* leaf11;                                                                  // define one leaf...
   TLeaf* leaf2;
//   TLeaf* leaf22;                                                                  // define another leaf
   cout<<"Entries number in  first TTree = "<<entries1<<endl;
   cout<<"Entries number in second TTree = "<<entries2<<endl;
//  Reprezentation of 1D histogram from ROOT files
   for (int i=0; i < entries1; i++)
      {
         leaf1 = LandData1->GetLeaf("Nte",i);                                      // Accessing TLeaf informations
//         leaf11 = LandData1->GetLeaf("Nhe",i);                                   // Accessing TLeaf informations
       LandData1->FillHisto1D(leaf1);                                              // Fill 1D histogram ... automatical bin width
//         LandData1->FillHisto2D(leaf1,leaf11);                                   // Fill 2D histogram ... automatical bin width
      }
      c->cd(1);
      LandData1->Draw1D();                                                         // Plotting 1D histogram ... automatical bin width
//      LandData1->Draw2D();                                                         // Plotting 2D histogram ... automatical bin width

   for (int i=0; i < entries2; i++)
      {
         leaf2 = LandData2->GetLeaf("Nhe",i);                                      // Accessing TLeaf informations
//         leaf22 = LandData2->GetLeaf("Nte",i);                                     // Accessing TLeaf informations
         LandData2->FillHisto1D(leaf2);                                            // Fill 1D histogram ... automatical bin width
//         LandData2->FillHisto2D(leaf2,leaf22);                                     // Fill 2D histogram ... automatical bin width
      }
      c->cd(2);
      LandData2->Draw1D();                                                         // Plotting 1D histogram ... automatical bin width
//      LandData2->Draw2D();                                                        // Plotting 2D histogram ... automatical bin width
      // ... or you can plot on the same histogram by comment the precedent two line and comment out the next line
//      LandData2->Draw1Dsame();                                                        // Plotting 1D histogram ... automatical bin width
// ... The same things for 2D histograming

   //####### for diferent TLeaf analysis ###############
/*
   Int_t len = leaf1->GetLen();
   for(Int_t j=0; j<len ; j++)
      {
       leaf1->GetValue(j);                                              // TLeaf Value for different analysis
      }
*/
    
}
Example #29
0
void DrawGlobal(TObjArray List,TFile *in, TFile *out){
  TObjArray List;

  TCanvas *MeanTk = new TCanvas("MeanTk","MeanTk",10,10,900,500);

  TIFTree->Project("h0","Tracks.MeanTrack:number","Clusters.entries_all>2000");
  
  h0->SetTitle("Number of Events with at least on Track/Total number of Events");
  h0->GetXaxis()->SetTitle("Run Number");
  h0->GetXaxis()->CenterTitle(1);
  h0->GetYaxis()->SetTitle("Fraction of Events with nTracks non zero");
  h0->GetYaxis()->CenterTitle(1); 
  h0->SetMarkerStyle(20);
  h0->SetStats(0);
  h0->Draw();
  List.Add(MeanTk);

  TCanvas *Events = new TCanvas("Events","Events",10,10,900,500);

  TIFTree->Project("h3","Clusters.entries_all:number","Clusters.entries_all>2000");
  
  h3->SetTitle("Total Number of Events");
  h3->GetXaxis()->SetTitle("Run Number");
  h3->GetXaxis()->CenterTitle(1);
  h3->GetYaxis()->SetTitle("Events");
  h3->GetYaxis()->CenterTitle(1); 
  h3->SetMarkerStyle(20);
  h3->SetStats(0);
  h3->Draw();
  List.Add(Events);

  TCanvas *nTracks = new TCanvas("nTracks","nTracks",10,10,900,500);

  TIFTree->Project("h","Tracks.mean:number","Clusters.entries_all>2000");
  
  h->SetTitle("Mean Track number per Event");
  h->GetXaxis()->SetTitle("Run Number");
  h->GetXaxis()->CenterTitle(1);
  h->GetYaxis()->SetTitle("Mean Track number per Event");
  h->GetYaxis()->CenterTitle(1); 
  h->SetMarkerStyle(20);
  h->SetStats(0);
  h->Draw();
  List.Add(nTracks);
  
  TCanvas *nRecHits= new TCanvas("nRecHits","nRecHits",10,10,900,500);  
  TIFTree->Project("h1","RecHits.mean:number","Clusters.entries_all>2000");
  
  h1->SetTitle("Mean RecHits Number per Event");
  h1->GetXaxis()->SetTitle("Run Number");
  h1->GetXaxis()->CenterTitle(1);
  h1->GetYaxis()->SetTitle("Mean RecHits Number per Event");
  h1->GetYaxis()->CenterTitle(1); 
  h1->SetMarkerStyle(20);
  h1->SetStats(0);
  h1->Draw();
  List.Add(nRecHits);

  TCanvas *nCluster= new TCanvas("nClusters","nClusters",10,10,900,500);
  TIFTree->Project("h2","Clusters.mean_corr:number","Clusters.entries_all>2000");
  
  h2->SetTitle("Mean Number of Cluster per Event");
  h2->GetXaxis()->SetTitle("Run Number");
  h2->GetXaxis()->CenterTitle(1);
  h2->GetYaxis()->SetTitle("Mean Number of Cluster per Event");
  h2->GetYaxis()->CenterTitle(1); 
  h2->SetMarkerStyle(20);
  h2->SetStats(0);
  h2->Draw();
  List.Add(nClusters);

 out->cd();
 List.Write();
 // out->Close();

 in->cd();
}
Example #30
0
Bool_t CheckESD(const char* gAliceFileName = "galice.root", 
		const char* esdFileName = "AliESDs.root")
{
// check the content of the ESD
 
  // check values
  Int_t    checkNGenLow = 1;

  Double_t checkEffLow = 0.5;
  Double_t checkEffSigma = 3;
  Double_t checkFakeHigh = 0.5;
  Double_t checkFakeSigma = 3;

  Double_t checkResPtInvHigh = 5;
  Double_t checkResPtInvSigma = 3;
  Double_t checkResPhiHigh = 10;
  Double_t checkResPhiSigma = 3;
  Double_t checkResThetaHigh = 10;
  Double_t checkResThetaSigma = 3;

  Double_t checkPIDEffLow = 0.5;
  Double_t checkPIDEffSigma = 3;
  Double_t checkResTOFHigh = 500;
  Double_t checkResTOFSigma = 3;

  Double_t checkPHOSNLow = 5;
  Double_t checkPHOSEnergyLow = 0.3;
  Double_t checkPHOSEnergyHigh = 1.0;
  Double_t checkEMCALNLow = 50;
  Double_t checkEMCALEnergyLow = 0.05;
  Double_t checkEMCALEnergyHigh = 1.0;

  Double_t checkMUONNLow = 1;
  Double_t checkMUONPtLow = 0.5;
  Double_t checkMUONPtHigh = 10.;

  Double_t cutPtV0 = 0.3;
  Double_t checkV0EffLow = 0.02;
  Double_t checkV0EffSigma = 3;
  Double_t cutPtCascade = 0.5;
  Double_t checkCascadeEffLow = 0.01;
  Double_t checkCascadeEffSigma = 3;

  // open run loader and load gAlice, kinematics and header
  AliRunLoader* runLoader = AliRunLoader::Open(gAliceFileName);
  if (!runLoader) {
    Error("CheckESD", "getting run loader from file %s failed", 
	    gAliceFileName);
    return kFALSE;
  }
  runLoader->LoadgAlice();
  gAlice = runLoader->GetAliRun();
  if (!gAlice) {
    Error("CheckESD", "no galice object found");
    return kFALSE;
  }
  runLoader->LoadKinematics();
  runLoader->LoadHeader();

  // open the ESD file
  TFile* esdFile = TFile::Open(esdFileName);
  if (!esdFile || !esdFile->IsOpen()) {
    Error("CheckESD", "opening ESD file %s failed", esdFileName);
    return kFALSE;
  }
  AliESDEvent * esd = new AliESDEvent;
  TTree* tree = (TTree*) esdFile->Get("esdTree");
  if (!tree) {
    Error("CheckESD", "no ESD tree found");
    return kFALSE;
  }
  esd->ReadFromTree(tree);

  // efficiency and resolution histograms
  Int_t nBinsPt = 15;
  Float_t minPt = 0.1;
  Float_t maxPt = 3.1;
  TH1F* hGen = CreateHisto("hGen", "generated tracks", 
			   nBinsPt, minPt, maxPt, "p_{t} [GeV/c]", "N");
  TH1F* hRec = CreateHisto("hRec", "reconstructed tracks", 
			   nBinsPt, minPt, maxPt, "p_{t} [GeV/c]", "N");
  Int_t nGen = 0;
  Int_t nRec = 0;
  Int_t nFake = 0;

  TH1F* hResPtInv = CreateHisto("hResPtInv", "", 100, -10, 10, 
           "(p_{t,rec}^{-1}-p_{t,sim}^{-1}) / p_{t,sim}^{-1} [%]", "N");
  TH1F* hResPhi = CreateHisto("hResPhi", "", 100, -20, 20, 
			      "#phi_{rec}-#phi_{sim} [mrad]", "N");
  TH1F* hResTheta = CreateHisto("hResTheta", "", 100, -20, 20, 
				"#theta_{rec}-#theta_{sim} [mrad]", "N");

  // PID
  Int_t partCode[AliPID::kSPECIES] = 
    {kElectron, kMuonMinus, kPiPlus, kKPlus, kProton};
  const char* partName[AliPID::kSPECIES+1] = 
    {"electron", "muon", "pion", "kaon", "proton", "other"};
  Double_t partFrac[AliPID::kSPECIES] = 
    {0.01, 0.01, 0.85, 0.10, 0.05};
  Int_t identified[AliPID::kSPECIES+1][AliPID::kSPECIES];
  for (Int_t iGen = 0; iGen < AliPID::kSPECIES+1; iGen++) {
    for (Int_t iRec = 0; iRec < AliPID::kSPECIES; iRec++) {
      identified[iGen][iRec] = 0;
    }
  }
  Int_t nIdentified = 0;

  // dE/dx and TOF
  TH2F* hDEdxRight = new TH2F("hDEdxRight", "", 300, 0, 3, 100, 0, 400);
  hDEdxRight->SetStats(kFALSE);
  hDEdxRight->GetXaxis()->SetTitle("p [GeV/c]");
  hDEdxRight->GetYaxis()->SetTitle("dE/dx_{TPC}");
  hDEdxRight->SetMarkerStyle(kFullCircle);
  hDEdxRight->SetMarkerSize(0.4);
  TH2F* hDEdxWrong = new TH2F("hDEdxWrong", "", 300, 0, 3, 100, 0, 400);
  hDEdxWrong->SetStats(kFALSE);
  hDEdxWrong->GetXaxis()->SetTitle("p [GeV/c]");
  hDEdxWrong->GetYaxis()->SetTitle("dE/dx_{TPC}");
  hDEdxWrong->SetMarkerStyle(kFullCircle);
  hDEdxWrong->SetMarkerSize(0.4);
  hDEdxWrong->SetMarkerColor(kRed);
  TH1F* hResTOFRight = CreateHisto("hResTOFRight", "", 100, -1000, 1000, 
				   "t_{TOF}-t_{track} [ps]", "N");
  TH1F* hResTOFWrong = CreateHisto("hResTOFWrong", "", 100, -1000, 1000, 
				   "t_{TOF}-t_{track} [ps]", "N");
  hResTOFWrong->SetLineColor(kRed);

  // calorimeters
  TH1F* hEPHOS = CreateHisto("hEPHOS", "PHOS", 100, 0, 50, "E [GeV]", "N");
  TH1F* hEEMCAL = CreateHisto("hEEMCAL", "EMCAL", 100, 0, 50, "E [GeV]", "N");

  // muons
  TH1F* hPtMUON = CreateHisto("hPtMUON", "MUON", 100, 0, 20, 
			      "p_{t} [GeV/c]", "N");

  // V0s and cascades
  TH1F* hMassK0 = CreateHisto("hMassK0", "K^{0}", 100, 0.4, 0.6, 
			      "M(#pi^{+}#pi^{-}) [GeV/c^{2}]", "N");
  TH1F* hMassLambda = CreateHisto("hMassLambda", "#Lambda", 100, 1.0, 1.2, 
				  "M(p#pi^{-}) [GeV/c^{2}]", "N");
  TH1F* hMassLambdaBar = CreateHisto("hMassLambdaBar", "#bar{#Lambda}", 
				     100, 1.0, 1.2, 
				     "M(#bar{p}#pi^{+}) [GeV/c^{2}]", "N");
  Int_t nGenV0s = 0;
  Int_t nRecV0s = 0;
  TH1F* hMassXi = CreateHisto("hMassXi", "#Xi", 100, 1.2, 1.5, 
			      "M(#Lambda#pi) [GeV/c^{2}]", "N");
  TH1F* hMassOmega = CreateHisto("hMassOmega", "#Omega", 100, 1.5, 1.8, 
				 "M(#LambdaK) [GeV/c^{2}]", "N");
  Int_t nGenCascades = 0;
  Int_t nRecCascades = 0;

  // loop over events
  for (Int_t iEvent = 0; iEvent < runLoader->GetNumberOfEvents(); iEvent++) {
    runLoader->GetEvent(iEvent);

    // select simulated primary particles, V0s and cascades
    AliStack* stack = runLoader->Stack();
    Int_t nParticles = stack->GetNtrack();
    TArrayF vertex(3);
    runLoader->GetHeader()->GenEventHeader()->PrimaryVertex(vertex);
    TObjArray selParticles;
    TObjArray selV0s;
    TObjArray selCascades;
    for (Int_t iParticle = 0; iParticle < nParticles; iParticle++) {
      TParticle* particle = stack->Particle(iParticle);
      if (!particle) continue;
      if (particle->Pt() < 0.001) continue;
      if (TMath::Abs(particle->Eta()) > 0.9) continue;
      TVector3 dVertex(particle->Vx() - vertex[0], 
		       particle->Vy() - vertex[1],
		       particle->Vz() - vertex[2]);
      if (dVertex.Mag() > 0.0001) continue;

      switch (TMath::Abs(particle->GetPdgCode())) {
      case kElectron:
      case kMuonMinus:
      case kPiPlus:
      case kKPlus:
      case kProton: {
	if (particle->Pt() > minPt) {
	  selParticles.Add(particle);
	  nGen++;
	  hGen->Fill(particle->Pt());
	}
	break;
      }
      case kK0Short:
      case kLambda0: {
	if (particle->Pt() > cutPtV0) {
	  nGenV0s++;
	  selV0s.Add(particle);
	}
	break;
      }
      case kXiMinus:
      case kOmegaMinus: {
	if (particle->Pt() > cutPtCascade) {
	  nGenCascades++;
	  selCascades.Add(particle);
	}
	break;
      }
      default: break;
      }
    }

    // get the event summary data
    tree->GetEvent(iEvent);
    if (!esd) {
      Error("CheckESD", "no ESD object found for event %d", iEvent);
      return kFALSE;
    }

    // loop over tracks
    for (Int_t iTrack = 0; iTrack < esd->GetNumberOfTracks(); iTrack++) {
      AliESDtrack* track = esd->GetTrack(iTrack);

      // select tracks of selected particles
      Int_t label = TMath::Abs(track->GetLabel());
      if (label > stack->GetNtrack()) continue;     // background
      TParticle* particle = stack->Particle(label);
      if (!selParticles.Contains(particle)) continue;
      if ((track->GetStatus() & AliESDtrack::kITSrefit) == 0) continue;
      if (track->GetConstrainedChi2() > 1e9) continue;
      selParticles.Remove(particle);   // don't count multiple tracks

      nRec++;
      hRec->Fill(particle->Pt());
      if (track->GetLabel() < 0) nFake++;

      // resolutions
      hResPtInv->Fill(100. * (TMath::Abs(track->GetSigned1Pt()) - 1./particle->Pt()) * 
		      particle->Pt());
      hResPhi->Fill(1000. * (track->Phi() - particle->Phi()));
      hResTheta->Fill(1000. * (track->Theta() - particle->Theta()));

      // PID
      if ((track->GetStatus() & AliESDtrack::kESDpid) == 0) continue;
      Int_t iGen = 5;
      for (Int_t i = 0; i < AliPID::kSPECIES; i++) {
	if (TMath::Abs(particle->GetPdgCode()) == partCode[i]) iGen = i;
      }
      Double_t probability[AliPID::kSPECIES];
      track->GetESDpid(probability);
      Double_t pMax = 0;
      Int_t iRec = 0;
      for (Int_t i = 0; i < AliPID::kSPECIES; i++) {
	probability[i] *= partFrac[i];
	if (probability[i] > pMax) {
	  pMax = probability[i];
	  iRec = i;
	}
      }
      identified[iGen][iRec]++;
      if (iGen == iRec) nIdentified++;

      // dE/dx and TOF
      Double_t time[AliPID::kSPECIES];
      track->GetIntegratedTimes(time);
      if (iGen == iRec) {
	hDEdxRight->Fill(particle->P(), track->GetTPCsignal());
        if ((track->GetStatus() & AliESDtrack::kTOFpid) != 0) {
	  hResTOFRight->Fill(track->GetTOFsignal() - time[iRec]);
	}
      } else {
	hDEdxWrong->Fill(particle->P(), track->GetTPCsignal());
        if ((track->GetStatus() & AliESDtrack::kTOFpid) != 0) {
	  hResTOFWrong->Fill(track->GetTOFsignal() - time[iRec]);
	}
      }
    }

    // loop over muon tracks
    {
    for (Int_t iTrack = 0; iTrack < esd->GetNumberOfMuonTracks(); iTrack++) {
      AliESDMuonTrack* muonTrack = esd->GetMuonTrack(iTrack);
      Double_t ptInv = TMath::Abs(muonTrack->GetInverseBendingMomentum());
      if (ptInv > 0.001) {
	hPtMUON->Fill(1./ptInv);
      }
    }
    }

    // loop over V0s
    for (Int_t iV0 = 0; iV0 < esd->GetNumberOfV0s(); iV0++) {
      AliESDv0* v0 = esd->GetV0(iV0);
      if (v0->GetOnFlyStatus()) continue;
      v0->ChangeMassHypothesis(kK0Short);
      hMassK0->Fill(v0->GetEffMass());
      v0->ChangeMassHypothesis(kLambda0);
      hMassLambda->Fill(v0->GetEffMass());
      v0->ChangeMassHypothesis(kLambda0Bar);
      hMassLambdaBar->Fill(v0->GetEffMass());

      Int_t negLabel = TMath::Abs(esd->GetTrack(v0->GetNindex())->GetLabel());
      if (negLabel > stack->GetNtrack()) continue;     // background
      Int_t negMother = stack->Particle(negLabel)->GetMother(0);
      if (negMother < 0) continue;
      Int_t posLabel = TMath::Abs(esd->GetTrack(v0->GetPindex())->GetLabel());
      if (posLabel > stack->GetNtrack()) continue;     // background
      Int_t posMother = stack->Particle(posLabel)->GetMother(0);
      if (negMother != posMother) continue;
      TParticle* particle = stack->Particle(negMother);
      if (!selV0s.Contains(particle)) continue;
      selV0s.Remove(particle);
      nRecV0s++;
    }

    // loop over Cascades
    for (Int_t iCascade = 0; iCascade < esd->GetNumberOfCascades(); 
	 iCascade++) {
      AliESDcascade* cascade = esd->GetCascade(iCascade);
      Double_t v0q;
      cascade->ChangeMassHypothesis(v0q,kXiMinus);
      hMassXi->Fill(cascade->GetEffMassXi());
      cascade->ChangeMassHypothesis(v0q,kOmegaMinus);
      hMassOmega->Fill(cascade->GetEffMassXi());

      Int_t negLabel = TMath::Abs(esd->GetTrack(cascade->GetNindex())
				  ->GetLabel());
      if (negLabel > stack->GetNtrack()) continue;     // background
      Int_t negMother = stack->Particle(negLabel)->GetMother(0);
      if (negMother < 0) continue;
      Int_t posLabel = TMath::Abs(esd->GetTrack(cascade->GetPindex())
				  ->GetLabel());
      if (posLabel > stack->GetNtrack()) continue;     // background
      Int_t posMother = stack->Particle(posLabel)->GetMother(0);
      if (negMother != posMother) continue;
      Int_t v0Mother = stack->Particle(negMother)->GetMother(0);
      if (v0Mother < 0) continue;
      Int_t bacLabel = TMath::Abs(esd->GetTrack(cascade->GetBindex())
				  ->GetLabel());
      if (bacLabel > stack->GetNtrack()) continue;     // background
      Int_t bacMother = stack->Particle(bacLabel)->GetMother(0);
      if (v0Mother != bacMother) continue;
      TParticle* particle = stack->Particle(v0Mother);
      if (!selCascades.Contains(particle)) continue;
      selCascades.Remove(particle);
      nRecCascades++;
    }

    // loop over the clusters
    {
      for (Int_t iCluster=0; iCluster<esd->GetNumberOfCaloClusters(); iCluster++) {
	AliESDCaloCluster * clust = esd->GetCaloCluster(iCluster);
	if (clust->IsPHOS()) hEPHOS->Fill(clust->E());
	if (clust->IsEMCAL()) hEEMCAL->Fill(clust->E());
      }
    }

  }

  // perform checks
  if (nGen < checkNGenLow) {
    Warning("CheckESD", "low number of generated particles: %d", Int_t(nGen));
  }

  TH1F* hEff = CreateEffHisto(hGen, hRec);

  Info("CheckESD", "%d out of %d tracks reconstructed including %d "
	 "fake tracks", nRec, nGen, nFake);
  if (nGen > 0) {
    // efficiency
    Double_t eff = nRec*1./nGen;
    Double_t effError = TMath::Sqrt(eff*(1.-eff) / nGen);
    Double_t fake = nFake*1./nGen;
    Double_t fakeError = TMath::Sqrt(fake*(1.-fake) / nGen);
    Info("CheckESD", "eff = (%.1f +- %.1f) %%  fake = (%.1f +- %.1f) %%",
	 100.*eff, 100.*effError, 100.*fake, 100.*fakeError);

    if (eff < checkEffLow - checkEffSigma*effError) {
      Warning("CheckESD", "low efficiency: (%.1f +- %.1f) %%", 
	      100.*eff, 100.*effError);
    }
    if (fake > checkFakeHigh + checkFakeSigma*fakeError) {
      Warning("CheckESD", "high fake: (%.1f +- %.1f) %%", 
	      100.*fake, 100.*fakeError);
    }

    // resolutions
    Double_t res, resError;
    if (FitHisto(hResPtInv, res, resError)) {
      Info("CheckESD", "relative inverse pt resolution = (%.1f +- %.1f) %%",
	   res, resError);
      if (res > checkResPtInvHigh + checkResPtInvSigma*resError) {
	Warning("CheckESD", "bad pt resolution: (%.1f +- %.1f) %%", 
		res, resError);
      }
    }

    if (FitHisto(hResPhi, res, resError)) {
      Info("CheckESD", "phi resolution = (%.1f +- %.1f) mrad", res, resError);
      if (res > checkResPhiHigh + checkResPhiSigma*resError) {
	Warning("CheckESD", "bad phi resolution: (%.1f +- %.1f) mrad", 
		res, resError);
      }
    }

    if (FitHisto(hResTheta, res, resError)) {
      Info("CheckESD", "theta resolution = (%.1f +- %.1f) mrad", 
	   res, resError);
      if (res > checkResThetaHigh + checkResThetaSigma*resError) {
	Warning("CheckESD", "bad theta resolution: (%.1f +- %.1f) mrad", 
		res, resError);
      }
    }

    // PID
    if (nRec > 0) {
      Double_t eff = nIdentified*1./nRec;
      Double_t effError = TMath::Sqrt(eff*(1.-eff) / nRec);
      Info("CheckESD", "PID eff = (%.1f +- %.1f) %%", 
	   100.*eff, 100.*effError);
      if (eff < checkPIDEffLow - checkPIDEffSigma*effError) {
	Warning("CheckESD", "low PID efficiency: (%.1f +- %.1f) %%", 
		100.*eff, 100.*effError);
      }
    }

    printf("%9s:", "gen\\rec");
    for (Int_t iRec = 0; iRec < AliPID::kSPECIES; iRec++) {
      printf("%9s", partName[iRec]);
    }
    printf("\n");
    for (Int_t iGen = 0; iGen < AliPID::kSPECIES+1; iGen++) {
      printf("%9s:", partName[iGen]);
      for (Int_t iRec = 0; iRec < AliPID::kSPECIES; iRec++) {
	printf("%9d", identified[iGen][iRec]);
      }
      printf("\n");
    }

    if (FitHisto(hResTOFRight, res, resError)) {
      Info("CheckESD", "TOF resolution = (%.1f +- %.1f) ps", res, resError);
      if (res > checkResTOFHigh + checkResTOFSigma*resError) {
	Warning("CheckESD", "bad TOF resolution: (%.1f +- %.1f) ps", 
		res, resError);
      }
    }

    // calorimeters
    if (hEPHOS->Integral() < checkPHOSNLow) {
      Warning("CheckESD", "low number of PHOS particles: %d", 
	      Int_t(hEPHOS->Integral()));
    } else {
      Double_t mean = hEPHOS->GetMean();
      if (mean < checkPHOSEnergyLow) {
	Warning("CheckESD", "low mean PHOS energy: %.1f GeV", mean);
      } else if (mean > checkPHOSEnergyHigh) {
	Warning("CheckESD", "high mean PHOS energy: %.1f GeV", mean);
      }
    }

    if (hEEMCAL->Integral() < checkEMCALNLow) {
      Warning("CheckESD", "low number of EMCAL particles: %d", 
	      Int_t(hEEMCAL->Integral()));
    } else {
      Double_t mean = hEEMCAL->GetMean();
      if (mean < checkEMCALEnergyLow) {
	Warning("CheckESD", "low mean EMCAL energy: %.1f GeV", mean);
      } else if (mean > checkEMCALEnergyHigh) {
	Warning("CheckESD", "high mean EMCAL energy: %.1f GeV", mean);
      }
    }

    // muons
    if (hPtMUON->Integral() < checkMUONNLow) {
      Warning("CheckESD", "low number of MUON particles: %d", 
	      Int_t(hPtMUON->Integral()));
    } else {
      Double_t mean = hPtMUON->GetMean();
      if (mean < checkMUONPtLow) {
	Warning("CheckESD", "low mean MUON pt: %.1f GeV/c", mean);
      } else if (mean > checkMUONPtHigh) {
	Warning("CheckESD", "high mean MUON pt: %.1f GeV/c", mean);
      }
    }

    // V0s
    if (nGenV0s > 0) {
      Double_t eff = nRecV0s*1./nGenV0s;
      Double_t effError = TMath::Sqrt(eff*(1.-eff) / nGenV0s);
      if (effError == 0) effError = checkV0EffLow / TMath::Sqrt(1.*nGenV0s);
      Info("CheckESD", "V0 eff = (%.1f +- %.1f) %%", 
	   100.*eff, 100.*effError);
      if (eff < checkV0EffLow - checkV0EffSigma*effError) {
	Warning("CheckESD", "low V0 efficiency: (%.1f +- %.1f) %%", 
		100.*eff, 100.*effError);
      }
    }

    // Cascades
    if (nGenCascades > 0) {
      Double_t eff = nRecCascades*1./nGenCascades;
      Double_t effError = TMath::Sqrt(eff*(1.-eff) / nGenCascades);
      if (effError == 0) effError = checkV0EffLow / 
			   TMath::Sqrt(1.*nGenCascades);
      Info("CheckESD", "Cascade eff = (%.1f +- %.1f) %%", 
	   100.*eff, 100.*effError);
      if (eff < checkCascadeEffLow - checkCascadeEffSigma*effError) {
	Warning("CheckESD", "low Cascade efficiency: (%.1f +- %.1f) %%", 
		100.*eff, 100.*effError);
      }
    }
  }

  // draw the histograms if not in batch mode
  if (!gROOT->IsBatch()) {
    new TCanvas;
    hEff->DrawCopy();
    new TCanvas;
    hResPtInv->DrawCopy("E");
    new TCanvas;
    hResPhi->DrawCopy("E");
    new TCanvas;
    hResTheta->DrawCopy("E");
    new TCanvas;
    hDEdxRight->DrawCopy();
    hDEdxWrong->DrawCopy("SAME");
    new TCanvas;
    hResTOFRight->DrawCopy("E");
    hResTOFWrong->DrawCopy("SAME");
    new TCanvas;
    hEPHOS->DrawCopy("E");
    new TCanvas;
    hEEMCAL->DrawCopy("E");
    new TCanvas;
    hPtMUON->DrawCopy("E");
    new TCanvas;
    hMassK0->DrawCopy("E");
    new TCanvas;
    hMassLambda->DrawCopy("E");
    new TCanvas;
    hMassLambdaBar->DrawCopy("E");
    new TCanvas;
    hMassXi->DrawCopy("E");
    new TCanvas;
    hMassOmega->DrawCopy("E");
  }

  // write the output histograms to a file
  TFile* outputFile = TFile::Open("check.root", "recreate");
  if (!outputFile || !outputFile->IsOpen()) {
    Error("CheckESD", "opening output file check.root failed");
    return kFALSE;
  }
  hEff->Write();
  hResPtInv->Write();
  hResPhi->Write();
  hResTheta->Write();
  hDEdxRight->Write();
  hDEdxWrong->Write();
  hResTOFRight->Write();
  hResTOFWrong->Write();
  hEPHOS->Write();
  hEEMCAL->Write();
  hPtMUON->Write();
  hMassK0->Write();
  hMassLambda->Write();
  hMassLambdaBar->Write();
  hMassXi->Write();
  hMassOmega->Write();
  outputFile->Close();
  delete outputFile;

  // clean up
  delete hGen;
  delete hRec;
  delete hEff;
  delete hResPtInv;
  delete hResPhi;
  delete hResTheta;
  delete hDEdxRight;
  delete hDEdxWrong;
  delete hResTOFRight;
  delete hResTOFWrong;
  delete hEPHOS;
  delete hEEMCAL;
  delete hPtMUON;
  delete hMassK0;
  delete hMassLambda;
  delete hMassLambdaBar;
  delete hMassXi;
  delete hMassOmega;

  delete esd;
  esdFile->Close();
  delete esdFile;

  runLoader->UnloadHeader();
  runLoader->UnloadKinematics();
  delete runLoader;

  // result of check
  Info("CheckESD", "check of ESD was successfull");
  return kTRUE;
}