예제 #1
0
//_________________________________________________________________________________________________
void GroupByStation(AliMergeableCollection& hc, int timeResolution)
{
  int station(1);
  
  for ( Int_t ich = 1; ich < 10; ich += 2 )
  {
    TH1* h = hc.Histo(Form("/CHAMBER/HITS/%ds/CHAMBER%d",timeResolution,ich));
    TH1* h1 = hc.Histo(Form("/CHAMBER/HITS/%ds/CHAMBER%d",timeResolution,ich+1));
    
    TH1* hstation = static_cast<TH1*>(h->Clone(Form("STATION%d",station)));
    
    hstation->Add(h1);
    hc.Adopt(Form("/STATION/HITS/%ds",timeResolution),hstation);

    h = hc.Histo(Form("/CHAMBER/HITS/%ds/CHAMBER%dLEFT",timeResolution,ich));
    h1 = hc.Histo(Form("/CHAMBER/HITS/%ds/CHAMBER%dLEFT",timeResolution,ich+1));
    
    hstation = static_cast<TH1*>(h->Clone(Form("STATION%dLEFT",station)));
    
    hstation->Add(h1);
    hc.Adopt(Form("/STATION/HITS/%ds",timeResolution),hstation);

    h = hc.Histo(Form("/CHAMBER/HITS/%ds/CHAMBER%dRIGHT",timeResolution,ich));
    h1 = hc.Histo(Form("/CHAMBER/HITS/%ds/CHAMBER%dRIGHT",timeResolution,ich+1));
    
    hstation = static_cast<TH1*>(h->Clone(Form("STATION%dRIGHT",station)));
    
    hstation->Add(h1);
    hc.Adopt(Form("/STATION/HITS/%ds",timeResolution),hstation);
    
    ++station;
  }
}
예제 #2
0
void dominik()
{
  TH1* matHistogramRoman = static_cast<TH1*>(extractObjectFromFile("lyRoman.root", "lightYieldProjectionY")->At(0));
  TList* objects = extractObjectFromFile("c.root", "chargeBins");
  TH1* matHistogramDominik = new TH1D("matHistogramDominik", ";channel;light yield / pixels", 512, -0.5, 512-0.5);
  int sipmIt = 0;
  for (int i = 0; i < objects->GetSize(); ++i) {
    TH1* h = static_cast<TH1*>(objects->At(i));
    if (h->GetLineColor() == 8) {
      for (int bin = 1; bin <= 128; ++bin) {
        matHistogramDominik->SetBinContent(512 - (sipmIt * 128 + bin - 1), h->GetBinContent(bin));
        if (h->GetBinError(bin) > 0)
          matHistogramDominik->SetBinError(512 - (sipmIt * 128 + bin - 1), h->GetBinError(bin));
      }
      ++sipmIt;
    }
  }
  TCanvas* c = new TCanvas;
  c->Divide(1, 2);
  c->cd(1);
  matHistogramDominik->Draw();
  matHistogramRoman->Draw("SAME");
  c->cd(2);
  TH1* h = static_cast<TH1*>(matHistogramDominik->Clone());
  h->Add(matHistogramRoman, -1);
  h->Draw();
}
예제 #3
0
//_________________________________________________________________________________________________
void GroupByChamber(AliMergeableCollection& hc, int timeResolution)
{
  for ( Int_t ich = 1; ich <= 10; ++ich )
  {
    AliMpDEIterator it;
  
    it.First(ich-1);
  
    TH1* hchamberLeft(0x0);
    TH1* hchamberRight(0x0);
    TList listLeft;
    TList listRight;
    listLeft.SetOwner(kFALSE);
    listRight.SetOwner(kFALSE);
    
    AliMpDCSNamer dcs("TRACKER");

    while (!it.IsDone())
    {
      Int_t detElemId = it.CurrentDEId();

       AliMpDetElement* de = AliMpDDLStore::Instance()->GetDetElement(detElemId);
    
      TH1* h = hc.Histo(Form("/DE/HITS/%ds/DE%04d",timeResolution,detElemId));
      
      if (dcs.DCSAliasName(detElemId).Contains("Left"))
      {
        if (!hchamberLeft)
        {
          hchamberLeft = static_cast<TH1*>(h->Clone(Form("CHAMBER%dLEFT",ich)));
        }
        else
        {
          listLeft.Add(h);
        }
      }
      else
      {
        if (!hchamberRight)
        {
          hchamberRight = static_cast<TH1*>(h->Clone(Form("CHAMBER%dRIGHT",ich)));
        }
        else
        {
          listRight.Add(h);
        }
      }
      
      it.Next();
    }
    
    hchamberLeft->Merge(&listLeft);
    hchamberRight->Merge(&listRight);
    hc.Adopt(Form("/CHAMBER/HITS/%ds",timeResolution),hchamberLeft);
    hc.Adopt(Form("/CHAMBER/HITS/%ds",timeResolution),hchamberRight);
    TH1* hchamber = static_cast<TH1*>(hchamberLeft->Clone(Form("CHAMBER%d",ich)));
    hchamber->Add(hchamberRight);
    hc.Adopt(Form("/CHAMBER/HITS/%ds",timeResolution),hchamber);
  }
}
TH1* GetHist(const string histname)
{
	const float scaleTo = fDATA_LUMI; // pb

	TH1 *hists[nBins] = {0,0,0,0,0,0,0};
	TH1 *Hist = 0;

	for (int i=0; i<nBins; ++i)
	{
		hists[i] = dynamic_cast<TH1*> (files[i]->Get(histname.c_str()));
		if (hists[i] != 0)
		{
			hists[i]->Sumw2();
			const float scale = scaleTo/ ( nEvents[i] / xSec[i] );
			hists[i]->Scale(scale);
			hists[i]->SetLineWidth(2);
			hists[i]->SetLineColor(i);

			if (i == 0) 
			{
				Hist = dynamic_cast<TH1*> (hists[i]->Clone("hist0_copy"));
				Hist->SetDirectory(0);
			} else
			{
				Hist->Add(hists[i]);
			}

		} else {
			cout << "hist " << histname << " not found in " << files[i]->GetName() << "!" << endl;
			assert (false);
		}
	}

	return Hist;
}
예제 #5
0
// Extract and merge histograms in range [from, to) (to is not included)
//
TH1 *merge(const string &path, TFile **input, const int &from, const int &to,
        const bool &do_normalize = false)
{
    TH1 *result = 0;
    for(int i = from; to > i; ++i)
    {
        TH1 *hist = get(path, input[i], i);
        if (!hist)
        {
            cerr << "failed to extract: " << path << endl;

            continue;
        }

        if (!result)
            result = dynamic_cast<TH1 *>(hist->Clone());
        else
            result->Add(hist);
    }

    if (do_normalize
            && result
            && result->GetEntries())
    {
        result->Scale(1. / result->Integral());
    }

    return result;
}
TH1* getHistogram(TFile* inputFile, const std::string& channel, double massPoint, 
		  const std::string& directory, const std::string& histogramName, double metResolution)
{
  std::string process = "";
  if   ( massPoint <  95. ) process = "ZToTauTau";
  else                      process = Form("HToTauTau_M-%1.0f", massPoint);
  
  std::string metResolution_label = "";
  if ( metResolution > 0. ) metResolution_label = Form("pfMEtRes%1.0f", metResolution);
  else metResolution_label = "pfMEtResMC";

  std::vector<TH1*> histograms;
  std::string directory_process = 
    //Form("DQMData/%s/%s/%s/%s/plotEntryType1", process.data(), channel.data(), metResolution_label.data(), directory.data());
    Form("DQMData/%s/%s/%s/plotEntryType1", process.data(), channel.data(), directory.data());
  histograms.push_back(getHistogram(inputFile, directory_process, histogramName));
  TH1* histogramSum = NULL;
  for ( std::vector<TH1*>::const_iterator histogram = histograms.begin();
	histogram != histograms.end(); ++histogram ) {
    if ( !histogramSum ) {
      std::string histogramSumName = std::string((*histogram)->GetName()).append("_summed");
      histogramSum = (TH1*)(*histogram)->Clone(histogramSumName.data());
    } else {
      histogramSum->Add(*histogram);
    }
  }

  assert(histogramSum);

  if ( !histogramSum->GetSumw2N() ) histogramSum->Sumw2();
  if ( histogramSum->Integral() > 0. ) histogramSum->Scale(1./histogramSum->Integral());
  
  return histogramSum;
}
예제 #7
0
void Test(TH1* h, TH1* s, const char* test)
{
   // Check that hist and sparse are equal, print the test result
   cout << test << ": ";
   
   // What exactly is "equal"?
   // Define it as  the max of 1/1000 of the "amplitude" of the 
   // original hist, or 1E-4, whatever is larger.
   Double_t epsilon = 1E-4;
   Double_t diffH = h->GetMaximum() - h->GetMinimum();
   if (diffH < 0.) diffH = -diffH;
   if (diffH / 1000. > epsilon)
      epsilon = diffH / 1000.;

   TH1* diff = (TH1*)s->Clone("diff");
   diff->Add(h, -1);
   Double_t max = diff->GetMaximum();
   Double_t min = diff->GetMinimum();
   if (max < -min) max = -min;
   if (max < epsilon) cout << "SUCCESS";
   else {
      cout << "FAIL: delta=" << max;
      TCanvas* c = new TCanvas(test, test);
      c->Divide(1,3);
      c->cd(1); h->Draw();
      c->cd(2); s->Draw();
      c->cd(3); diff->Draw();
      TFile f("runsparse.root", "UPDATE");
      c->Write();
      delete c;
   }
   cout <<endl;
   delete diff;
}
예제 #8
0
//________________________________________________________________________________
void MergeSimpleHistogramFile( const Char_t *TargetName=0, const Char_t *inputFilesPattern=0) 
{
   // This is the deprecated version. To be dleted after debugging
  if (TargetName && TargetName[0] && inputFilesPattern && inputFilesPattern[0] ) {
    TStopwatch time;
    Int_t fileCounter = 0;
    Int_t histogramCounter = 0;
     // Create the output file
     TFile *outFile = TFile::Open(TargetName,"RECREATE");     
     TDirIter listOfFiles(inputFilesPattern);
     const char *fileName = 0;
     while ( (fileName =  listOfFiles.NextFile() ) ) {
        printf(".");
        fileCounter++;
        TFileIter file(fileName);
        TObject *obj = 0;
        while ( (obj = *file) ) {
           if ( obj->IsA()->InheritsFrom( "TH1" ) ) {
              // descendant of TH1 -> merge it
              // printf("Merging histogram: %s\n",obj->GetName() ); 
//              std::cout << "Merging histogram " << obj->GetName() << std::endl;
              TH1 *h1 = (TH1*)obj;
              TH1 *dstHistogram = 0;
              // Check whether we found the new histogram
              if ( (dstHistogram = (TH1 *)outFile->FindObject(h1->GetName()))) {
                 // Accumulate  the  histogram
                  dstHistogram->Add(h1);
                  delete h1;  // Optional, to reduce the memory consumption
                  printf("+");
              } else {
                // First time - move the histogram
                h1->SetDirectory(outFile);
                printf(" The new Histogram found: %s \n", h1->GetName() );
                histogramCounter++;
              }
           } else {
              // printf("Skipping object: %s\n",obj->GetName() ); 
           }
           ++file;
        }
              
     }
     printf("\n Finishing  . . . \n");
     outFile->ls();
     outFile->Write();
     outFile->Close();     
     delete outFile;
     printf(" Total files merged: %d \n", fileCounter);
     printf(" Total histograms merged: %d \n", histogramCounter);
     time.Print("Merge");
  } else {
     printf("\nUsage: root MergeHistogramFile.C(\"DestinationFileName\",\"InputFilesPattern\",kTRUE)\n");     
     printf("------        where InputFilesPattern  ::= <regexp_pattern_for_the_input_files>|@indirect_file_list\n");
     printf("                    indirect_file_list ::= a text file with the list of the files\n");
     printf("                    indirect_file_list can be create by the shell command:\n");
     printf("                         ls -1 --color=never *.root>indirect_file_list \n\n");
  }
}
예제 #9
0
// -----------------------------------------------------------------------------
//
TH1* getHisto( std::string nameFile,
	       std::string nameHist,
	       std::string Dirname, 
	       int rebin ) {
  std::string name = nameFile;
  TFile* file =  new TFile(name.c_str());
  if (file) { std::cout << "Opened file: " << file->GetName() << std::endl; }
  else { 
    std::cout << "Could not find file: " << name << std::endl; 
    return 0; 
  }
  
  TDirectory* dir = (TDirectory*)file->Get(Dirname.c_str());
  if (dir) { std::cout << "Opened dir: " << dir->GetName() << std::endl; }
  else { 
    std::cout << "Could not find dir: " << Dirname << std::endl; 
    return 0; 
  }
  
  int low = 375;
  TH1* hist = 0;
  if ( false || nameHist.find("HtMultiplicity_HT375") == std::string::npos ) { 
    hist = (TH1*)dir->Get(nameHist.c_str());
  } else {
    
    for ( uint ii = low; ii <= 975; ii+=100 ) {
      std::stringstream tmp; tmp << "HtMultiplicity_HT" << ii << nameHist.substr(20);
      if ( !hist ) { 
	dir->cd();
	TH1D* temp = (TH1D*)dir->Get( "HtMultiplicity_HT375_aT0" );
	//TH1D* temp = (TH1D*)file->Get( tmp.str().c_str() );
	if (temp) { hist = (TH1D*)temp->Clone(); } 
	else { std::cout << "1 Unable to retrieve histo with name " << tmp.str() << std::endl; }
      } else { 
	dir->cd();
	TH1D* temp = (TH1D*)dir->Get( tmp.str().c_str() );
	if (temp) { hist->Add( (TH1D*)temp ); } 
	else { std::cout << "2 Unable to retrieve histo with name " << tmp.str() << std::endl; }
      }
    }

  }
  if (hist) { std::cout << "Opened histo: " << hist->GetName() << std::endl; }
  else { 
    std::cout << "Could not find histo: " << nameHist << std::endl; 
    return 0; 
  }

  hist->SetLineWidth(3);
  if ( rebin > 0 ) { hist->Rebin(rebin); }
  hist->GetXaxis()->SetTitleSize(0.055);
  hist->GetYaxis()->SetTitleSize(0.055);
  hist->GetXaxis()->SetLabelSize(0.05);
  hist->GetYaxis()->SetLabelSize(0.05);
  hist->SetStats(kFALSE);
  return hist;
}
예제 #10
0
void findHisto(int ppac) {


  sprintf(canvasname,"ppac%02i",ppac);
  myCanvas[ppac-1] = new TCanvas(canvasname,canvasname,1000,700);


  for (int j=1;j<23;j++)
    {
      f->cd("histos/DoubleCoinc");
      sprintf(histoname,"dc1_5_diff_time_t00_ppac%02i_ligl%02i",ppac,j);
      if (j==3 || j==5 || j==16) continue;
      if (j==1) TH1 *hf = (TH1*)gDirectory->FindObjectAny(histoname);
      else      TH1*  h = (TH1*)gDirectory->FindObjectAny(histoname);
      hf->Add(h);
      //std::cout<<"Adding "<<histoname<<std::endl;                                                                          \
                                                                                                                              
      f->cd("histos/DoubleCoinc/background");
      sprintf(histname,"dc1_5_back_diff_time_t00_ppac%02i_ligl%02i",ppac,j);
      if (j==3 || j==5 || j==16) continue;
      if (j==1) TH1 *hb = (TH1*)gDirectory->FindObjectAny(histoname);
      else      TH1* h1 = (TH1*)gDirectory->FindObjectAny(histoname);
      hb->Add(h1);
    }//end of loop over ligls                                                                                                \
                                                                                                                              

  myCanvas[ppac-1]->cd(1);
  //gPad->SetLogy();                                                                                                         \
                                                                                                                              
  gPad->SetLogy();
  sprintf(histotitle,"ToF PPAC %02i All Ligls Except 3,5,16",ppac);
  hf->SetTitle(histotitle);
  gStyle->SetOptStat(0);
  hf->Draw();
  hb->Draw("same");

  tex1=new TLatex(0.65,0.75,"E_{n}^{in} = 0.7-6 MeV");
  tex1->SetNDC();
  tex1->SetTextFont(43);
  tex1->SetTextSize(22);
  tex1->SetTextColor(kRed);
  tex1->Draw();

}//end of findHisto      
예제 #11
0
double Fit511Photopeak(TH1* h, double* error=0)
{
  TSpectrum spec(1);
  spec.Search(h);
  h->GetXaxis()->SetTitle("Energy [photoelectrons]");
  h->Draw("e");
  TH1* bg = spec.Background(h);
  TH1* sig = (TH1*)(h->Clone());
  sig->SetLineColor(kGreen);
  
  sig->Add(bg,-1);
  sig->Draw("same e");
  sig->Fit("gaus","m","same e");
  TF1* gaus = sig->GetFunction("gaus");
  if(gaus)
    gaus->SetLineColor(kGreen);
  
  bg->SetLineColor(kRed);
  bg->Draw("same e");
  
  TLine* line = new TLine(gaus->GetParameter(1),0,
			  gaus->GetParameter(1),h->GetMaximum());
  line->SetLineColor(kBlue);
  line->SetLineWidth(2);
  line->Draw();
  

  double yield = spec.GetPositionX()[0]/epeak;
  double err = 0;
  
  cout<<"Results from TSpectrum: \n\t"
      <<"Peak = "<<spec.GetPositionX()[0]<<" p.e.; Light Yield = "
      <<yield<<" p.e./keV"<<endl;
  if(gaus){
    yield = gaus->GetParameter(1)/epeak;
    err = gaus->GetParError(1)/epeak;
    cout<<"Results from BG Subtracted Gaus Fit: \n\t"
	<<"Peak = "<<gaus->GetParameter(1)<<" p.e.; Light Yield = "
	<<yield<<" +/- "<<err<<" p.e./keV"<<endl;
    err = max(err, TMath::Abs(yield-spec.GetPositionX()[0]/epeak));
    
  }
  TLegend* leg = new TLegend(.6,.6,.9,.9);
  leg->AddEntry(h,"Raw Spectrum","lpe");
  leg->AddEntry(bg,"Background","lpe");
  leg->AddEntry(sig,"Signal","lpe");
  char title[20];
  sprintf(title,"Yield = %.2f pe/keV",yield);
  leg->AddEntry(line, title ,"l");
  leg->Draw();

  if(error) *error = err;
  return yield;
}
예제 #12
0
void fit() {
  FILE *ofile;
  ofile = fopen("xsect-integrated-me.txt","w");
  TFile *_file0 = TFile::Open("h3maker-hn.root","update");
  _file0->Delete("*_f;*");
  TH2 *h2xsect = new TH2("hq2wXsect","Q^2:W",32,1.6,3.2,7,1.5,5.1);
  Double_t qbinedges[] = { 1.5, 1.6, 1.8, 2.1, 2.4, 2.76, 3.3, 5.1 };
  h2xsect->GetYaxis()->Set(7,qbinedges);
  TH3 *h3 = (TH3*)_file0->Get("hq2wmmp");
  int qbins = h3->GetZaxis()->GetNbins();
  int wbins = h3->GetYaxis()->GetNbins();
  fprintf(ofile, "W\tQ2\txsect\terror\tpol4p0\tpol4p1\tpol4p2\tpol4p3\tpol4p4\tgN\tgM\tgS\n");
  for (int iq = 0; iq < qbins; iq++) {
    TString hsn = TString::Format("hs%d",iq);
    THStack *hs = (THStack*)_file0->Get(hsn.Data());
    TIter next(hs->GetHists());
    //while (TObject *obj = next()) {
    //TH1 *h = (TH1*)obj;
    while (TH1 *h = (TH1*)next()) {
      float *wq = getwq(h);
      float wval = wq[0];
      float qval = wq[1];
      fitmmp(h);
      TH1 *htmp = (TH1*)h->Clone("hbgsubtracted");
      TF1 *fbg = (TF1*)h->GetListOfFunctions()->FindObject("fbg");
      htmp->Add(fbg,-1);
      double N = htmp->Integral(34,43);
      double qwidth = h3->GetZaxis()->GetBinWidth(iq+1);
      int wbin = h3->GetYaxis()->FindBin(wval);
      double wwidth = h3->GetYaxis()->GetBinWidth(wbin);
      double xsect = N/(0.891*wwidth*qwidth*19.844);
      double err2 = 0;
      for (int immp = 34; immp < 44; immp++) err2 += htmp->GetBinError(immp)*htmp->GetBinError(immp);
      //fprintf(ofile, "%.3f\t%.3f\t%.0f\t%.0f",wval,qval,xsect/(1e6), sqrt(err2)/(1e6));
      fprintf(ofile, "%.3f\t%.3f\t%.3e\t%.3e",wval,qval,xsect/(1e6), sqrt(err2)/(1e6));
      TF1 *ftmp = (TF1*)h->GetListOfFunctions()->At(0);
      int npar = ftmp->GetNpar();
      for (int ipar = 0; ipar < npar; ipar++) fprintf(ofile, "\t%.3e", ftmp->GetParameter(ipar));
      fprintf(ofile, "\n");
    }
    hsn.Append("_f");
    _file0->WriteObject(hs,hsn.Data());
    delete hs;
  }
  fclose(ofile);
  delete _file0;
}
예제 #13
0
TH1* merge_histos(TList *sourcelist){
  TH1 *htot;

  TFile *first_source = (TFile*)sourcelist->First();
  TDirectory *current_sourcedir = gDirectory;
  //gain time, do not add the objects in the list in memory
  Bool_t status = TH1::AddDirectoryStatus();
  TH1::AddDirectory(kFALSE);
  
  
  // loop over all keys in this directory
  TChain *globChain = 0;
  TIter nextkey( current_sourcedir->GetListOfKeys() );
  TKey *key, *oldkey=0;
  while ( (key = (TKey*)nextkey())) {

    //keep only the highest cycle number for each key
    if (oldkey && !strcmp(oldkey->GetName(),key->GetName())) continue;
    
    // read object from first source file
    TObject *obj = key->ReadObj();
    
    // if the object is named "tot_edp_hbcoil" merge it
    if ( obj->FindObject("Tot_Edep_HBCoil")) {

      //      cout << "Merging histogram " << obj->GetName() << endl;
      htot = (TH1*)obj;
      
      // loop over all source files and add the content of the
      // correspondant histogram to the one pointed to by "h1"
      TFile *nextsource = (TFile*)sourcelist->After( first_source );
      while ( nextsource ) {
	// make sure we are at the correct directory level by cd'ing to path
	TKey *key2 = (TKey*)gDirectory->GetListOfKeys()->FindObject(htot->GetName());
	if (key2) {
	  TH1 *htemp = (TH1*)key2->ReadObj();
	  htot->Add(htemp);
	  delete htemp;
	}
	
	nextsource = (TFile*)sourcelist->After( nextsource );
      }
    }   
  }

  return htot;
}
예제 #14
0
std::shared_ptr<TH1> getHistogram(const std::string& name, const std::vector<Input>& inputs, int type) {

  TH1* h = nullptr;

  for (const auto& input: inputs) {
    if (input.type != type)
      continue;

    TH1* f = static_cast<TH1*>(input.file->Get(name.c_str()));
    f->Scale(input.cross_section / (input.generated_events * input.top_pt_weight));

    if (! h) {
      h = static_cast<TH1*>(f->Clone());
      h->SetDirectory(NULL);
    } else
      h->Add(f);
  }

  return std::shared_ptr<TH1>(h);
}
예제 #15
0
void fitmmp(TH1 *hmmp, bool verbose = false) {
  TString options;
  if (verbose) options = "";
  else options = "Q";
  TF1 *fbg = f_pol4("fbg",0.4,2,true);
  hmmp->Fit(fbg,options.Data(),"",0.42,2);
  //printf("%s\n",gMinuit->fCstatu.Data());
  if (true) { //gMinuit->fCstatu.Contains("CONVER")) {
    TF1 *fbg2 = f_pol4("fbg",0.4,2,false);
    fbg2->SetParameters(fbg->GetParameters());
    //fbg2->Draw("same");
    fbg2->SetParameter(5,0);
    fbg2->SetParameter(6,0);
    TH1 *htmp = (TH1*)hmmp->Clone("hmmp_bgsub");
    htmp->Add(fbg2,-1);
    //htmp->Draw();
    TF1 *fgaus = new TF1("fgaus","gaus",0.4,2);
    htmp->Fit(fgaus,options.Data(),"",0.74,0.85);
    TF1 *f = f_pol4gaus("f",0.4,2,fbg2,fgaus);
    f->SetNpx(500);
    hmmp->Fit(f,options.Data(),"",0.42,2);
    fgaus->SetRange(0.4,2);
    for (int i = 0; i < 3; i++) fgaus->SetParameter(i,f->GetParameter(i+5));
    for (int i = 0; i < 5; i++) fbg2->SetParameter(i,f->GetParameter(i));
    fbg2->SetLineStyle(2);
    fbg2->SetLineColor(kRed+1);
    fgaus->SetLineStyle(2);
    fgaus->SetLineColor(kGreen+1);
    hmmp->GetListOfFunctions()->Add(fbg2->Clone());
    hmmp->GetListOfFunctions()->Add(fgaus->Clone());
    delete fbg2;
    delete htmp;
    delete fgaus;
    delete f;
  } else hmmp->GetListOfFunctions()->Delete();
  delete fbg;
}
예제 #16
0
파일: CBEnergy.C 프로젝트: Physott/acqu
//______________________________________________________________________________
void CBEnergy()
{
    // Main method.
    
    Char_t tmp[256];
    
    // load CaLib
    gSystem->Load("libCaLib.so");
    
    // general configuration
    const Char_t* data = "Data.CB.E1";
    const Char_t* hName = "CaLib_CB_IM_Neut";

    // configuration (December 2007)
    //const Char_t calibration[] = "LD2_Dec_07";
    //const Char_t filePat[] = "/usr/puma_scratch0/werthm/A2/Dec_07/AR/out/ARHistograms_CB_RUN.root";

    // configuration (February 2009)
    const Char_t calibration[] = "LD2_Feb_09";
    //const Char_t filePat[] = "/usr/puma_scratch0/werthm/A2/Feb_09/AR/out/ARHistograms_CB_RUN.root";
    const Char_t filePat[] = "/usr/cheetah_scratch0/kaeser/CaLib/Feb_09/ARHistograms_CB_RUN.root";

    // configuration (May 2009)
    //const Char_t calibration[] = "LD2_May_09";
    //const Char_t filePat[] = "/usr/puma_scratch0/werthm/A2/May_09/AR/out/ARHistograms_CB_RUN.root";
    
    // get number of sets
    Int_t nSets = TCMySQLManager::GetManager()->GetNsets(data, calibration);

    // create canvas
    Int_t n = TMath::Sqrt(nSets);
    TCanvas* cOverview = new TCanvas();
    cOverview->Divide(n, nSets / n + 1);
    
    // create arrays
    Double_t* pos = new Double_t[nSets+1];
    Double_t* fwhm = new Double_t[nSets+1];
    
    // total sum histogram
    TH1* hTot = 0;

    // loop over sets
    for (Int_t i = 0; i < nSets; i++)
    { 
        // create file manager
        TCFileManager m(data, calibration, 1, &i, filePat);
        
        // get histo
        TH2* h2 = (TH2*) m.GetHistogram(hName);
        
        // skip empty histo
        if (!h2) continue;
        
        // project histo
        sprintf(tmp, "Proj_%d", i);
        TH1* h = (TH1*) h2->ProjectionX(tmp);
        
        // add to total histogram
        if (!hTot) hTot = (TH1*) h->Clone();
        else hTot->Add(h);

        // fit histo
        cOverview->cd(i+1);
        Fit(h, &pos[i], &fwhm[i]);
    }

    // show total histogram
    TCanvas* cTot = new TCanvas();
    Fit(hTot, &pos[nSets], &fwhm[nSets]);

    // show results
    for (Int_t i = 0; i < nSets; i++)
        printf("Set %02d:   Pos: %.2f MeV   FWHM: %.2f MeV\n", i, pos[i], fwhm[i]);
    printf("Total :   Pos: %.2f MeV   FWHM: %.2f MeV\n", pos[nSets], fwhm[nSets]);
}
예제 #17
0
void reingold_ROOThomework(){

// Initalizing the Canvas

	TCanvas *c1 = new TCanvas("c1" , "Homework Plots" , 800 , 600 );
	c1 -> Divide(3,3);

// Defining the function with three Gaussians on a quadratic background.

	TF1 *func = new TF1("func", "pol2(0) + gaus(3) + gaus(6) + gaus(9)" , 0 , 100 );
	Double_t param[12] = {9 , 1 , -0.01 , 100 , 20 , 1 , 100 , 50 , 1 , 100 , 80 , 1};
	func->SetParameters(param);
			//  quad, lin, const, A, mu, std , ... 
// Generting and filling the histograms

	TH1F *h0 = new TH1F("h0" , "Original Spectrum" , 100 , 0 , 100 );
	for ( Int_t i = 0 ; i < 2000 ; i++ ){
		Float_t rand = func->GetRandom();
		h0->Fill(rand);
	}
	
	for ( Int_t j = 1 ; j < 4 ; j++ ){
		c1->cd(j);
		h0->Draw();
	}
// Fitting the background using ShowBackground()
	c1->cd(4);
	TH1 *hPeaks = (TH1*) h0->Clone();
	TH1 *hBkgrd = (TH1*) h0->Clone();

	hPeaks->SetName("hPeaks");
	hBkgrd->SetName("hBkgrd");

	hBkgrd = h0->ShowBackground(15);

	h0->Draw();
	hBkgrd->Draw("same");
	
	hPeaks->Add(hBkgrd,-1);
	c1->cd(7);
	hPeaks->Draw();

// Fitting the background without excluding the peaks

	c1->cd(5);
	TH1F *hPeaks2 = (TH1F*) h0->Clone();
	TH1F *hBkg2 = (TH1F*) h0->Clone();

	hPeaks2->SetName("hPeaks2");
	hBkg2->SetName("hBkg2");

	TF1 *quadBack = new TF1("quadBack" , "pol2(0)" , 0 , 100 );
	hBkg2->Fit(quadBack,"R+");
	
	hBkg2->Draw();

	c1->cd(8);

	hPeaks2->Add(quadBack , -1 );
	hPeaks2->Draw();

// Fitting the background excluding the peaks

	c1->cd(6);
	TH1F *hPeaks3 = (TH1F*) h0->Clone();
	TH1F *hBkg3 = (TH1F*) h0->Clone();

	hPeaks3->SetName("hPeaks3");
	hBkg3->SetName("hBkg3");

	TF1 *quadBack2 = new TF1("quadBack2" , fQuad , 0 , 100 ,3);
	hBkg3->Fit(quadBack2,"R+");
	
	hBkg3->Draw();

	c1->cd(9);

	hPeaks3->Add(quadBack2 , -1 );
	hPeaks3->Draw();

}
예제 #18
0
void ttreesToHistograms() {
//********************************************************************
//****                      Variables                           ****//
cout << "Loading variables into vectors..." << endl;

vector<TString> fileName;
fileName.push_back( "rootfiles0/PhotonJetPt15_Summer09.root"  );//file0
fileName.push_back( "rootfiles0/PhotonJetPt30_Summer09.root"  );//file1
fileName.push_back( "rootfiles0/PhotonJetPt80_Summer09.root"  );//file2
fileName.push_back( "rootfiles0/PhotonJetPt170_Summer09.root" );//file3
fileName.push_back( "rootfiles0/PhotonJetPt300_Summer09.root" );//file4
fileName.push_back( "rootfiles0/PhotonJetPt470_Summer09.root" );//file5
fileName.push_back( "rootfiles0/PhotonJetPt800_Summer09.root" );//file6

TString treeName = "TreePhotonJet";

TString outputFileName = "PhotonJetHists-2009-09-02-matchesReco.root";


//*********************************
//**** Set Scale
// The following 4 number set the scale
// example:
//   scale = (integrated luminosity (1/pb))*(cross section (pb))*(filter eff)/(events analyzed)
float invLuminosityToScaleTo = 200; // in pb-1

vector<float> crossSection;
crossSection.push_back( 2.887E5 -3.222E4 );  // in pb
crossSection.push_back( 3.222E4 -1.010E3 );
crossSection.push_back( 1.010E3 -5.143E1 );
crossSection.push_back( 5.143E1 -4.193E0 );
crossSection.push_back( 4.193E0 -4.515E-1 );
crossSection.push_back( 4.515E-1 -2.003E-2 );
crossSection.push_back( 2.003E-2 );

vector<float> filterEffeciency;
filterEffeciency.push_back( 1.0 );
filterEffeciency.push_back( 1.0 );
filterEffeciency.push_back( 1.0 );
filterEffeciency.push_back( 1.0 );
filterEffeciency.push_back( 1.0 );
filterEffeciency.push_back( 1.0 );
filterEffeciency.push_back( 1.0 );

vector<float> eventsAnalyzied;
eventsAnalyzied.push_back( 1073270 );
eventsAnalyzied.push_back( 1088546 );
eventsAnalyzied.push_back(  993509 );
eventsAnalyzied.push_back( 1483940 );
eventsAnalyzied.push_back( 1024589 );
eventsAnalyzied.push_back( 1014413 );
eventsAnalyzied.push_back( 1216320 );
// END of setting scale
//*********************************


//*********************************
//****         Set Cuts      ****//
// Variables will be plotted for each "location"
vector<TString> locationCut;
locationCut.push_back( "abs(hardGenPhoton_eta)>1.55&&abs(hardGenPhoton_eta)<2.5" );
locationCut.push_back( "abs(hardGenPhoton_eta)<1.45" );

vector<TString> locationName;
locationName.push_back( "Endcap" );
locationName.push_back( "Barrel" );

// These cuts will be merged into one giant cut, applied to all plots for all files
vector<TString> cuts;
cuts.push_back( "hardGenPhoton_et>15.0&&photon_et>15.0&&photon_matches_hardGen>0.5" );

// These cuts will be applied only to corresponding file
vector<TString> fileCuts;
fileCuts.push_back( "event_genEventScale>15&&event_genEventScale<30"    ); //file0
fileCuts.push_back( "event_genEventScale>30&&event_genEventScale<80"    ); //file1
fileCuts.push_back( "event_genEventScale>80&&event_genEventScale<170"   ); //file2
fileCuts.push_back( "event_genEventScale>170&&event_genEventScale<300"  ); //file3
fileCuts.push_back( "event_genEventScale>300&&event_genEventScale<470"  ); //file4
fileCuts.push_back( "event_genEventScale>470&&event_genEventScale<800"  ); //file5
fileCuts.push_back( "event_genEventScale>800&&event_genEventScale<1400" ); //file6
//**** END of setting cuts
//*********************************


//*********************************
int locationVariablesToPlot[2][2]; // [a][b], a=number of locations, b=2 (for min,max range of variables to plot)
locationVariablesToPlot[0][0] = 16; // Endcap
locationVariablesToPlot[0][1] = 35;
locationVariablesToPlot[1][0] = 16; // Barrel
locationVariablesToPlot[1][1] = 35;
/*locationVariablesToPlot[2][0] = 0;
locationVariablesToPlot[2][1] = 4;
locationVariablesToPlot[3][0] = 0;
locationVariablesToPlot[3][1] = 4;
locationVariablesToPlot[4][0] = 0;
locationVariablesToPlot[4][1] = 4;
locationVariablesToPlot[5][0] = 0;
locationVariablesToPlot[5][1] = 4;
locationVariablesToPlot[6][0] = 0;
locationVariablesToPlot[6][1] = 4;
locationVariablesToPlot[7][0] = 0;
locationVariablesToPlot[7][1] = 4;*/

// Variables you want plotted
vector<TString> variableToPlot;
// --- the following require gen level info
variableToPlot.push_back( "hardGenPhoton_et"  );  // 0
variableToPlot.push_back( "hardGenPhoton_eta" );
variableToPlot.push_back( "hardGenPhoton_phi" );
variableToPlot.push_back( "fmod(hardGenPhoton_phi+3.141592,20.0*3.141592/180.0)-10.0*3.141592/180.0" );
variableToPlot.push_back( "abs(hardGenPhoton_eta)" ); // 4
variableToPlot.push_back( "(recPhoton.energy-hardGenPhoton_energy)/hardGenPhoton_energy" );
variableToPlot.push_back( "(recPhoton.energy-hardGenPhoton_energy)/hardGenPhoton_energy:hardGenPhoton_energy"   );
variableToPlot.push_back( "(recPhoton.energy-hardGenPhoton_energy)/hardGenPhoton_energy:abs(hardGenPhoton_eta)" );
variableToPlot.push_back( "(recPhoton.energy-hardGenPhoton_energy)/hardGenPhoton_energy:hardGenPhoton_phiMod"   );
variableToPlot.push_back( "photon_hadronicOverEm:hardGenPhoton_et"       );
variableToPlot.push_back( "photon_hadronicOverEm:abs(hardGenPhoton_eta)" ); // 10
variableToPlot.push_back( "photon_hadronicOverEm:hardGenPhoton_phiMod"   );
variableToPlot.push_back( "photon_eta-hardGenPhoton_eta" );
variableToPlot.push_back( "photon_eta-hardGenPhoton_eta:hardGenPhoton_et" );
variableToPlot.push_back( "photon_eta-hardGenPhoton_eta:abs(hardGenPhoton_eta)" );
variableToPlot.push_back( "deltaPhiGenRecPhoton" );  // 15
// --- the following require only rec photons
variableToPlot.push_back( "photon_et"  );         // 16
variableToPlot.push_back( "photon_eta" );
variableToPlot.push_back( "photon_phi" );
variableToPlot.push_back( "fmod(photon_phi+3.141592,20.0*3.141592/180.0)-10.0*3.141592/180.0" );
variableToPlot.push_back( "abs(photon_eta)" );    // 20
variableToPlot.push_back( "photon_r9" );
variableToPlot.push_back( "photon_ecalRecHitSumEtConeDR03" );
variableToPlot.push_back( "photon_hcalTowerSumEtConeDR03"  );
variableToPlot.push_back( "photon_trkSumPtSolidConeDR03"   );
variableToPlot.push_back( "photon_trkSumPtHollowConeDR03"  ); //25
variableToPlot.push_back( "photon_nTrkSolidConeDR03"  );
variableToPlot.push_back( "photon_nTrkHollowConeDR03" );
variableToPlot.push_back( "photon_hadronicOverEm"     );
variableToPlot.push_back( "photon_r2x5" );
variableToPlot.push_back( "photon_ecalRecHitSumEtConeDR03/photon_et" ); // 30
variableToPlot.push_back( "photon_hcalTowerSumEtConeDR03/photon_et"  );
variableToPlot.push_back( "photon_trkSumPtSolidConeDR03/photon_et"   );
variableToPlot.push_back( "photon_trkSumPtHollowConeDR03/photon_et"  );
// --- the following require jets
/*variableToPlot.push_back( "calcDeltaPhi(photon_phi,jet_phi)"  );
variableToPlot.push_back( "calcDeltaPhi(photon_phi,jet2_phi)" ); // 35
variableToPlot.push_back( "calcDeltaPhi(jet_phi,jet2_phi)"    );*/
variableToPlot.push_back( "(photon_et-jet_et)/photon_et"      );
variableToPlot.push_back( "jet2_et/photon_et"                 );

// Histograms for the above variables
vector<TH1*> histogram;
// --- the following require gen level info
histogram.push_back( new TH1F("photonGenEt",     "Photon E_{T} ;E_{T} (GeV);entries per 15 GeV",  50,  0, 750)  );  // 0
histogram.push_back( new TH1F("photonGenEta",    "Photon #eta ;#eta;entries per 0.1 bin",   61, -3.05,   3.05) );
histogram.push_back( new TH1F("photonGenPhi",    "Photon #phi ;#phi;entries per bin",   62, (-1.-1./30.)*TMath::Pi(), (1.+1./30.)*TMath::Pi()) );
histogram.push_back( new TH1F("photonGenPhiMod", "Photon #phi_{mod} ", 42, (-1.-1./20)*0.1745329, (1.+1./20.)*0.1745329) );
histogram.push_back( new TH1F("photonGenAbsEta", "Photon |#eta| ", 51, 0.00,   2.55) );
histogram.push_back( new TH1F("photonDeltaE",    "(E(#gamma_{rec})-E(#gamma_{gen}))/E(#gamma_{gen}) ", 50, -0.8, 0.3) );
histogram.push_back( new TH2F("photonDeltaE_vs_E","(E(#gamma_{rec})-E(#gamma_{gen}))/E(#gamma_{gen}) vs E(#gamma_{gen}) ", 50, 0, 3000, 50, -0.8, 0.3) );
histogram.push_back( new TH2F("photonDeltaE_vs_AbsEta","(E(#gamma_{rec})-E(#gamma_{gen}))/E(#gamma_{gen}) vs |#eta(#gamma_{gen}|) ", 51, 0.0, 2.5, 50, -0.8, 0.3) );
histogram.push_back( new TH2F("photonDeltaE_vs_PhiMod","(E(#gamma_{rec})-E(#gamma_{gen}))/E(#gamma_{gen}) vs #phi_{mod}(#gamma_{gen}) ", 42, (-1.-1./20)*0.1745329, (1.+1./20.)*0.1745329, 50, -0.9, 0.2) );
histogram.push_back( new TH2F("photonHoverE_vs_Et",     "H/E vs E_{T}(#gamma_{gen}) ", 50, 0, 1000, 50, 0.0, 0.2) );
histogram.push_back( new TH2F("photonHoverE_vs_AbsEta", "H/E vs |#eta(#gamma_{gen})| ", 51, 0.0, 2.5, 50, 0.0, 0.2) );
histogram.push_back( new TH2F("photonHoverE_vs_PhiMod", "H/E vs #phi_{mod}(#gamma_{gen}) ", 42, (-1.-1./20)*0.1745329, (1.+1./20.)*0.1745329, 50, 0.0, 0.2) );
histogram.push_back( new TH1F("photonDeltaEta", "#Delta#eta(#gamma_{rec},#gamma_{gen}) ;#Delta#eta(#gamma_{rec},#gamma_{gen});entries/bin", 41, -0.01, 0.01) );
histogram.push_back( new TH2F("photonDeltaEta_vs_Et",    "#Delta#eta(#gamma_{rec},#gamma_{gen}) vs E_{T}(#gamma_{gen}) ", 50, 0, 1000, 41, -0.1, 0.1) );
histogram.push_back( new TH2F("photonDeltaEta_vs_AbsEta","#Delta#eta(#gamma_{rec},#gamma_{gen}) vs #eta(#gamma_{gen})", 51, 0.0, 2.55, 41, -0.1, 0.1) );
histogram.push_back( new TH1F("photonDeltaPhi",          "#Delta#phi(#gamma_{rec},#gamma_{gen}) ;#Delta#phi(#gamma_{rec},#gamma_{gen});entries/bin", 41, 0.0, 0.01) ); // 15
// --- the following require only rec photons
histogram.push_back( new TH1F("photonEt",        "Photon E_{T} ;E_{T} (GeV);entries per 15 GeV", 50,  0,    750   ) ); // 16
histogram.push_back( new TH1F("photonEta",       "Photon #eta ;#eta;entries per 0.1"           , 61, -3.05,   3.05) );
histogram.push_back( new TH1F("photonPhi",       "Photon #phi ;#phi;entries per bin"           , 62, (-1.-1./30.)*TMath::Pi(), (1.+1./30.)*TMath::Pi()) );
histogram.push_back( new TH1F("photonPhiMod",    "Photon #phi_{mod} "                          , 42, (-1.-1./20)*0.1745329, (1.+1./20.)*0.1745329) );
histogram.push_back( new TH1F("photonAbsEta",    "Photon |#eta| "                              , 51, 0.00,  2.55) );  // 20
histogram.push_back( new TH1F("photonR9",        "R9 = E(3x3) / E(SuperCluster)  ;R9;entries/bin"   , 50, 0.6, 1.0) );
histogram.push_back( new TH1F("photonEcalIso",   "#SigmaEcal Rec Hit E_{T} in Hollow #DeltaR cone " , 50, 0  , 15) );
histogram.push_back( new TH1F("photonHcalIso",   "#SigmaHcal Rec Hit E_{T} in Hollow #DeltaR cone " , 50, 0  , 15) );
histogram.push_back( new TH1F("photonTrackSolidIso",     "#Sigmatrack p_{T} in Solid #DeltaR cone " , 50, 0  , 15) );
histogram.push_back( new TH1F("photonTrackHollowIso",    "#Sigmatrack p{T} in Hollow #DeltaR cone " , 50, 0  , 15) );  // 25
histogram.push_back( new TH1F("photonTrackCountSolid",   "Number of tracks in Solid #DeltaR cone ;Number of Tracks;entries/bin" , 25, -0.5, 24.5) );
histogram.push_back( new TH1F("photonTrackCountHollow",  "Number of tracks in Hollow #DeltaR cone ;Number of Tracks;entries/bin", 25, -0.5, 24.5) );
histogram.push_back( new TH1F("photonHoverE",            "Hadronic / EM ", 50, 0.0, 0.2) );
histogram.push_back( new TH1F("photonScSeedE2x5over5x5", "E2x5/E5x5  "   , 50, 0.6, 1.0) );
histogram.push_back( new TH1F("photonEcalIsoOverE",        "#SigmaEcal Rec Hit E_{T} in #DeltaR cone / Photon E_{T} " , 50, -0.1, 1.0) ); // 30
histogram.push_back( new TH1F("photonHcalIsoOverE",        "#SigmaHcal Rec Hit E_{T} in #DeltaR cone / Photon E_{T} " , 50, -0.1, 1.0) );
histogram.push_back( new TH1F("photonTrackSolidIsoOverE" , "#SigmaTrack p_{T} in #DeltaR cone / Photon E_{T} "        , 50, -0.1, 1.0) );
histogram.push_back( new TH1F("photonTrackHollowIsoOverE", "#SigmaTrack p_{T} in Hollow #DeltaR cone / Photon E_{T} " , 50, -0.1, 1.0) );
// --- the following require jets
/*histogram.push_back( new TH1F("h_deltaPhi_photon_jet", "#Delta#phi between Highest E_{T} #gamma and jet;#Delta#phi(#gamma,1^{st} jet)"               , 50, 0, 3.1415926) );
histogram.push_back( new TH1F("h_deltaPhi_photon_jet2","#Delta#phi between Highest E_{T} #gamma and 2^{nd} highest jet;#Delta#phi(#gamma,2^{nd} jet)", 50, 0, 3.1415926) );
histogram.push_back( new TH1F("h_deltaPhi_jet_jet2"  , "#Delta#phi between Highest E_{T} jet and 2^{nd} jet;#Delta#phi(1^{st} jet,2^{nd} jet)"       , 50, 0, 3.1415926) );*/
histogram.push_back( new TH1F("h_deltaEt_photon_jet" , "(E_{T}(#gamma)-E_{T}(jet))/E_{T}(#gamma) when #Delta#phi(#gamma,1^{st} jet) > 2.8;#DeltaE_{T}(#gamma,1^{st} jet)/E_{T}(#gamma)", 20, -1.0, 1.0) );
histogram.push_back( new TH1F("h_jet2_etOverPhotonEt", "E_{T}(2^{nd} highest jet) / E_{T}(#gamma);E_{T}(2^{nd} Jet)/E_{T}(#gamma)", 20, 0.0, 4.0) );
//****                  END of Variables                        ****//
//********************************************************************




//********************************************************************
//****                Main part of Program                      ****//

 // Human error checking
 if (variableToPlot.size() != histogram.size() ) {
   cout << "Should have equal entries in histogram and variableToPlot vector." << endl;
   return;
 }
 if (fileName.size() > crossSection.size() ) {
   cout << "Should have equal entries in fileName and crossSection vetor." << endl;
   return;
 }
 if (fileName.size() > fileCuts.size() ) {
   cout << "Should have equal entries in fileName and fileCuts vector." << endl;
   return;
 }

 // Combine all the cuts into one
 cout << endl << "Cuts that will be applied to everything: " << endl << "  ";
 TCut allCuts = "";
 for (int i =0; i<cuts.size(); i++) {
   allCuts += cuts[i];
   if (i>0) cout << "&&";
   cout << "(" << cuts[i] << ")";
 }
 cout << endl << endl;


 // Open the files & set their scales
 cout << endl << "Histograms will be scaled to " << invLuminosityToScaleTo << "pb-1 " << endl;
 cout << "Looking for TTree named \"" << treeName << "\" in files..." << endl;
 vector<float> fileScale;
 TList *fileList = new TList();
 for (int i=0; i < fileName.size(); i++) {

   TFile* currentFile = TFile::Open(fileName[i]);
   fileList->Add(currentFile);
   float currentScale = crossSection[i]*invLuminosityToScaleTo*filterEffeciency[i]/eventsAnalyzied[i];
   fileScale.push_back( currentScale );

   // Display entries in that file's TTree
   TTree* tree;
   currentFile->GetObject(treeName, tree);
   cout << "file" << i <<": " << fileName[i] << " contains " << tree->GetEntries(allCuts) << " entries, and will be scaled by " << 
currentScale << endl;
 }
 cout << endl << endl;


 //Create output file
 TFile *outputFile = TFile::Open( outputFileName, "RECREATE" );


 //************************************************************
 //                 Core of the Script                       //
 // Loop over locations
 for (int l=0; l<locationName.size(); l++) {
   TString currentLocation = locationName[l];
   TCut currentCuts = allCuts;
   currentCuts += locationCut[l];
   cout << "Creating plots for " << currentLocation << ", " << locationCut[l] << endl;
  
   // Loop over variables to plot
   for (int i=0; i<variableToPlot.size(); i++) {
     // should we plot this variable for this location?
     if (i<locationVariablesToPlot[l][0] || i>locationVariablesToPlot[l][1]) continue;

     TString currentHistType  = histogram[i]->IsA()->GetName();
     TString currentHistName  = TString(histogram[i]->GetName())  + "_" + currentLocation;
     TString currentHistTitle = TString(histogram[i]->GetTitle()) + "(" + currentLocation + ")";
     cout << "  " << variableToPlot[i] << " >> " << currentHistName;
     TString currentHistDrawOpt;
     if (currentHistType=="TH2F") {
       currentHistDrawOpt="goffbox";
     } else {
       currentHistDrawOpt="egoff";
     }
     TH1* currentHist = (TH1*)histogram[i]->Clone(currentHistName);  // Creates clone with name currentHistName
     currentHist->Sumw2(); // store errors
     currentHist->SetTitle(currentHistTitle);
     //cout << " from file";

     // Plot from the first file
     int f = 0;
     //cout << f;
     TTree *tree;
     TFile *current_file = (TFile*)fileList->First();
     current_file->cd();
     current_file->GetObject(treeName, tree);
     tree->Draw(variableToPlot[i]+">>"+currentHistName,currentCuts+TCut(fileCuts[f]),currentHistDrawOpt);
     currentHist->Scale(fileScale[f]);
     f++;

     // Loop over files
     current_file = (TFile*)fileList->After( current_file );
     while ( current_file ) {
       current_file->cd();
       //cout << ", file" << f;
       current_file->GetObject(treeName, tree);

       TString tempHistName = currentHistName+"Temp";
       TH1* tempHist = (TH1*)currentHist->Clone(tempHistName);
       tree->Draw(variableToPlot[i]+">>"+tempHistName,currentCuts+TCut(fileCuts[f]),currentHistDrawOpt);
       tempHist->Scale(fileScale[f]);
       currentHist->Add(tempHist);
       tempHist->Delete();

       current_file = (TFile*)fileList->After( current_file );
       f++;
     } // End of loop over files

     outputFile->cd();
     currentHist->Write();
     cout << endl;
   } // End of loop over variabls to plot
 } // End of loop over locations
 //                  END of Core of Script                   //
 //************************************************************

 cout << endl;
 cout << "Wrote file " << outputFileName << endl;
 cout << endl;
 outputFile->Close();
}
예제 #19
0
void EMuSigEff() {

    vector <int> masses;
    masses.push_back(40);
    masses.push_back(50);
    masses.push_back(60);
    masses.push_back(70);
    masses.push_back(80);
    masses.push_back(90);
    masses.push_back(100);
    masses.push_back(125);
    masses.push_back(150);
    masses.push_back(175);
    masses.push_back(200);
    masses.push_back(250);
    masses.push_back(300);
    masses.push_back(350);
    masses.push_back(400);
    masses.push_back(500);

    vector <TString> smasses;
    smasses.push_back("40");
    smasses.push_back("50");
    smasses.push_back("60");
    smasses.push_back("70");
    smasses.push_back("80");
    smasses.push_back("90");
    smasses.push_back("100");
    smasses.push_back("125");
    smasses.push_back("150");
    smasses.push_back("175");
    smasses.push_back("200");
    smasses.push_back("250");
    smasses.push_back("300");
    smasses.push_back("350");
    smasses.push_back("400");
    smasses.push_back("500");


    for(unsigned int i = 0 ; i < masses.size(); ++i) {

        TString im = smasses.at(i);

        TFile * file1 = new TFile(("/home/jalmond/HeavyNeutrino/Analysis/LQanalyzer/data/output/SSElectronMuon/HNEMu_SKHNmue" + im + "_nocut_5_3_14.root").Data());
        TFile * file2 = new TFile(("/home/jalmond/HeavyNeutrino/Analysis/LQanalyzer/data/output/SSElectronMuon/HNEMu_SKHNemu" + im + "_nocut_5_3_14.root").Data());

        TString cut = "SS_highmass_exc";// + im;
        //cut = "SS_highmass";
        //    if(i < 5) cut = "SS_lowmass_" + im;
        //if(i < 5) cut = "SS_lowmass_80_2";
        TString hist = (cut + "/h_Nelectrons_"+cut);

        TH1* hnsig =   (TH1F*)file1->Get(("CutFlow/_eventcutflow"));

        TH1* hnsig2 =   (TH1F*)file2->Get(("CutFlow/_eventcutflow"));

        float nsig = float(hnsig->GetBinContent(2));
        float nsig2= float(hnsig2->GetBinContent(2));

        TH1*  hpass = (TH1F*)file1->Get(hist);
        TH1*  hpass2 = (TH1F*)file2->Get(hist);

        cout  << " \n ------- " << endl;
        cout  << " Mass = " << masses.at(i) << endl;
        cout << "mu eacceptance = " << hpass->Integral()/nsig << endl;
        cout << "emu acceptance = " << hpass2->Integral()/nsig2 << endl;

        hpass->Add(hpass2,1.);
        double err ;
        hpass->IntegralAndError(1, hpass->GetNbinsX()+1, err    , "");
        cout << "Average = " << hpass->Integral()/(nsig + nsig2) << endl;
        cout << "%err = " << 100*err/(hpass->Integral())<< endl;;

    }
}
예제 #20
0
//------------------------------------------------------------------------------
THStack* PlotAlignmentValidation::addHists(const char *selection, const TString &residType,
					   bool printModuleIds)
{
  enum ResidType {
    xPrimeRes, yPrimeRes, xPrimeNormRes, yPrimeNormRes, xRes, yRes, xNormRes, /*yResNorm*/
    ResXvsXProfile,  ResXvsYProfile, ResYvsXProfile, ResYvsYProfile
  };
  ResidType rType = xPrimeRes;
  if (residType == "xPrime") rType = xPrimeRes;
  else if (residType == "yPrime") rType = yPrimeRes;
  else if (residType == "xPrimeNorm") rType = xPrimeNormRes;
  else if (residType == "yPrimeNorm") rType = yPrimeNormRes;
  else if (residType == "x") rType = xRes;
  else if (residType == "y") rType = yRes;
  else if (residType == "xNorm") rType = xNormRes;
  // else if (residType == "yNorm") rType = yResNorm;
  else if (residType == "ResXvsXProfile") rType = ResXvsXProfile;
  else if (residType == "ResYvsXProfile") rType = ResYvsXProfile;
  else if (residType == "ResXvsYProfile") rType = ResXvsYProfile;
  else if (residType == "ResYvsYProfile") rType = ResYvsYProfile;
  else {
    std::cout << "PlotAlignmentValidation::addHists: Unknown residual type "
	      << residType << std::endl; 
    return 0;
  }

  cout << "PlotAlignmentValidation::addHists: using selection " << selection << endl;
  THStack * retHistoStack = new THStack();
  double legendY = 0.80;
  TLegend * myLegend = new TLegend(0.17, legendY, 0.85, 0.88);
  setLegendStyle( *myLegend );

  for(std::vector<TkOfflineVariables*>::iterator itSourceFile = sourceList.begin();
      itSourceFile != sourceList.end(); ++itSourceFile) {

    //  TFile *f = (*sourceList.begin())->getFile();
    TFile *f = (*itSourceFile)->getFile();
    //  TTree *tree= (*sourceList.begin())->getTree();
    TTree *tree= (*itSourceFile)->getTree();
    int myLineColor = (*itSourceFile)->getLineColor();
    int myLineStyle = (*itSourceFile)->getLineStyle();
    TString myLegendName = (*itSourceFile)->getName();
    if (!f || !tree) {
      std::cout << "PlotAlignmentValidation::addHists: no tree or no file" << std::endl;
      return 0;
    }

    // Todo: TLegend?
  
    // first loop on tree to find out which entries (i.e. modules) fulfill the selection
    // 'Entry$' gives the entry number in the tree
    Long64_t nSel = tree->Draw("Entry$", selection, "goff");
    if (nSel == -1) return 0; // error in selection
    if (nSel == 0) {
      std::cout << "PlotAlignmentValidation::addHists: no selected module." << std::endl;
      return 0;
    }
    // copy entry numbers that fulfil the selection
    const std::vector<double> selected(tree->GetV1(), tree->GetV1() + nSel);

    TH1 *h = 0;       // becomes result
    UInt_t nEmpty = 0;// selected, but empty hists
    Long64_t nentries =  tree->GetEntriesFast();
    std::vector<double>::const_iterator iterEnt = selected.begin();

    // second loop on tree:
    // for each selected entry get the hist from the file and merge
    TkOffTreeVariables *treeMem = 0; // ROOT will initialise
    tree->SetBranchAddress("TkOffTreeVariables", &treeMem);
    for (Long64_t i = 0; i < nentries; i++){
      if (i < *iterEnt - 0.1             // smaller index (with tolerance): skip
	  || iterEnt == selected.end()) { // at the end: skip 
	continue;
      } else if (TMath::Abs(i - *iterEnt) < 0.11) {
	++iterEnt; // take this entry!
      } else std::cout << "Must not happen: " << i << " " << *iterEnt << std::endl;

      tree->GetEntry(i);
      if (printModuleIds) {
	std::cout << treeMem->moduleId << ": " << treeMem->entries << " entries" << std::endl;
      }
      if (treeMem->entries <= 0) {  // little speed up: skip empty hists
	++nEmpty;
	continue;
      }
      TString hName;
      switch(rType) {
      case xPrimeRes:     hName = treeMem->histNameX.c_str();          break;
      case yPrimeRes:     hName = treeMem->histNameY.c_str();          break;
      case xPrimeNormRes: hName = treeMem->histNameNormX.c_str();      break;
      case yPrimeNormRes: hName = treeMem->histNameNormY.c_str();      break;
      case xRes:          hName = treeMem->histNameLocalX.c_str();     break;
      case yRes:          hName = treeMem->histNameLocalY.c_str();     break;
      case xNormRes:      hName = treeMem->histNameNormLocalX.c_str(); break;
	/*case yResNorm:      hName = treeMem->histNameNormLocalY.c_str(); break;*/
      case ResXvsXProfile: hName = treeMem->profileNameResXvsX.c_str();    break;
      case ResXvsYProfile: hName = treeMem->profileNameResXvsY.c_str();    break;
      case ResYvsXProfile: hName = treeMem->profileNameResYvsX.c_str();    break;
      case ResYvsYProfile: hName = treeMem->profileNameResYvsY.c_str();    break;
      }
      TKey *histKey = f->FindKeyAny(hName);
      TH1 *newHist = (histKey ? static_cast<TH1*>(histKey->ReadObj()) : 0);
      if (!newHist) {
	std::cout << "Hist " << hName << " not found in file, break loop." << std::endl;
	break;
      }
      newHist->SetLineColor(myLineColor);
      newHist->SetLineStyle(myLineStyle);
      if (!h) { // first hist: clone, but rename keeping only first part of name
	TString name(newHist->GetName());
	Ssiz_t pos_ = 0;
	for (UInt_t i2 = 0; i2 < 3; ++i2) pos_ = name.Index("_", pos_+1);
	name = name(0, pos_); // only up to three '_'
	h = static_cast<TH1*>(newHist->Clone("summed_"+name));
	//      TString myTitle = Form("%s: %lld modules", selection, nSel);
	//	h->SetTitle( myTitle );
      } else { // otherwise just add
	h->Add(newHist);
      }
      delete newHist;
    }

    std::cout << "PlotAlignmentValidation::addHists" << "Result is merged from " << nSel-nEmpty
	      << " modules, " << nEmpty << " hists were empty." << std::endl;

    if (nSel-nEmpty == 0) continue;

    myLegend->AddEntry(myLegendName, myLegendName, "L");
    
    retHistoStack->Add(h);
  }
  myLegend->Draw();
  return retHistoStack;
}
예제 #21
0
파일: SingleChi28.C 프로젝트: nadjieh/work
int main(int argc, char** argv) {
    TH1* data;
    std::vector<TH2*> signalIID; // for munub t-processes
    std::vector<TH3*> signalIIID; // for munub t-processes
    TH1* bkginsignal = 0; //for t-processes other than munub
    TH1* bkg = 0; // for non-t processes
    TH1* wtemplate = 0;
    bool do3D = true;
    int nReBin = 10;
    TFile * file = 0;
    std::vector<double> pars;
    double nTop7 = 1.;
    double nW8 = 0;
    double nW7 = 0;
    //    cout << pars[0] << "\t" << pars[1] << "\t" << pars[2] << "\t" << pars[3] << "\t" << endl;
    double delStatF0 = 0;
    double delStatFL = 0;

    double delSystF0 = 0;
    double delSystFL = 0;
    double F0_ = 0;
    double FL_ = 0;
    double delTotF0 = 0;
    double delTotFL = 0;
    string channel = "";
    std::vector<string> namings;
    std::map<string, double> sampleinfo;
    double iRandom = 0;
    string addname = "";
    for (int f = 1; f < argc; f++) {
        std::string arg_fth(*(argv + f));
        cout << f << " ---- " << arg_fth << endl;
        if (arg_fth == "channel") {
            f++;
            std::string out(*(argv + f));
            channel = out; //e-mu
            namings.push_back(string("di") + channel);
            namings.push_back(channel + string("had"));
            namings.push_back(channel + string("tau"));
            namings.push_back("mue");
        } else if (arg_fth == "FL") {
            f++;
            std::string out(*(argv + f));
            FL_ = atof(out.c_str());
        } else if (arg_fth == "F0") {
            f++;
            std::string out(*(argv + f));
            F0_ = atof(out.c_str());
        } else if (arg_fth == "F0Stat") {
            f++;
            std::string out(*(argv + f));
            delStatF0 = atof(out.c_str());
        } else if (arg_fth == "FLStat") {
            f++;
            std::string out(*(argv + f));
            delStatFL = atof(out.c_str());
        } else if (arg_fth == "F0Syst") {
            f++;
            std::string out(*(argv + f));
            delSystF0 = atof(out.c_str());
        } else if (arg_fth == "FLSyst") {
            f++;
            std::string out(*(argv + f));
            delSystFL = atof(out.c_str());
        } else if (arg_fth == "F0Tot") {
            f++;
            std::string out(*(argv + f));
            delTotF0 = atof(out.c_str());
        } else if (arg_fth == "FLTot") {
            f++;
            std::string out(*(argv + f));
            delTotFL = atof(out.c_str());
        } else if (arg_fth == "nW7") {
            f++;
            std::string out(*(argv + f));
            nW7 = atof(out.c_str());
        } else if (arg_fth == "ntop7") {
            f++;
            std::string out(*(argv + f));
            nTop7 = atof(out.c_str());
        } else if (arg_fth == "signal") {
            f++;
            std::string out(*(argv + f));
            file = new TFile(out.c_str(), "read");
            bool muonfile = false;
            for (unsigned int i = 0; i < namings.size(); i++) {
                int pos = string(file->GetName()).find(namings[i].c_str());
                muonfile = (pos >= 0 && pos < string(file->GetName()).size());
                if (muonfile) {
                    if (iRandom == 0) {
                        cout << "I am in " << channel << " channel and I accept ";
                        cout << file->GetName() << " as signal" << endl;
                    }
                    break;
                }
            }

            if (!do3D || (do3D && !muonfile)) {
                signalIID.push_back(((TH2*) file->Get("Default_allW/Default_allWcosTheta2D"))->RebinY(nReBin));
                //                signalIID.at(signalIID.size() - 1)->Scale(ratio);
                //                cout << signalIID.at(signalIID.size() - 1)->GetName() << endl;
            }//                else
            //                signalIID.push_back(((TH2*) ((TH3D*) file->Get("Default_allW/Default_allWcosTheta3D"))->Project3D("yx"))->Rebin2D(1,1));
            if (do3D && muonfile) {
                //                cout << " in 3D :-)" << endl;
                signalIIID.push_back(((TH3D*) file->Get("Default_allW/Default_allWcosTheta3D"))->Rebin3D(1, nReBin, 1, "newname"));
                //                cout << signalIIID.at(signalIIID.size() - 1) << endl;
                //                signalIIID.at(signalIIID.size() - 1)->Scale(ratio);
            }
            if (bkginsignal == 0)
                bkginsignal = (((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin));
            else
                bkginsignal->Add(((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin));

            TH1 * myTemp = (TH1*) (((TH1*) file->Get("Default_allW/Default_allWcosTheta")))->Clone("myTemp");
            if (iRandom == 0) {
                if (!muonfile) {
                    cout << " : " << signalIID.at(signalIID.size() - 1)->Integral() << " + " << myTemp->Integral()
                            << " = " << signalIID.at(signalIID.size() - 1)->Integral() + myTemp->Integral() << endl;
                    sampleinfo[out] = signalIID.at(signalIID.size() - 1)->Integral() + myTemp->Integral();
                } else if (do3D) {
                    cout << " : " << signalIIID.at(signalIIID.size() - 1)->Integral() << " + " << myTemp->Integral()
                            << " = " << signalIIID.at(signalIIID.size() - 1)->Integral() + myTemp->Integral() << endl;
                    sampleinfo[out] = signalIIID.at(signalIIID.size() - 1)->Integral() + myTemp->Integral();
                }
            }
            delete myTemp;

        } else if (arg_fth == "data") {
            f++;
            std::string out(*(argv + f));
            cout << "data" << endl;
            file = new TFile(out.c_str(), "read");
            data = ((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin);
            cout << data << endl;
        } else if (arg_fth == "bkg") {
            f++;
            std::string out(*(argv + f));
            cout << "bkg" << endl;
            file = new TFile(out.c_str(), "read");
            if (bkg == NULL) {
                cout << "here .." << endl;
                bkg = ((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin);
            } else {
                bkg->Add(((TH1*) file->Get("Default_allW/Default_allWcosTheta"))->Rebin(nReBin));
            }
        } else if (arg_fth == "wtemplate") {
            f++;
            std::string out(*(argv + f));
            cout << "w template" << endl;
            file = new TFile(out.c_str(), "read");
            cout << out << "\t";
            wtemplate = ((TH1*) file->Get("Default_allW/Default_allWcosTheta"));
            cout << wtemplate << endl;
            wtemplate->Rebin(nReBin);
        } else if (arg_fth == "name") {
            f++;
            std::string out(*(argv + f));
            addname = out;
        }
    }
    cout << bkg << "\t" << data << "\t" << wtemplate << endl;
    wtemplate->Sumw2();
    wtemplate->Scale((double) 1. / (double) wtemplate->Integral());
    data->Print();

    cout << "In Bias fit: \n\tsize of 2D signal is " << signalIID.size() <<
            "\n\tsize of 3D signal is " << signalIIID.size() << endl;
    cout << "bkginsignal: " << bkginsignal->Integral() << " bkg: " << bkg->Integral() << endl;
    if (bkg != NULL && bkginsignal != NULL) {
        bkg->Add(bkginsignal);
    } else if (bkg == NULL && bkginsignal != NULL) {
        bkg = (TH1*) bkginsignal->Clone("myBkg");
    }
    //        bkg->Scale(ratio);
    cout << "bkg: " << bkg->Integral() << " data: " << data->Integral() << " signal: ";
    double nSignal = 0;
    for (unsigned int p = 0; p < signalIID.size(); p++) {
        nSignal += signalIID[p]->Integral();
        //            cout << signalIID[p]->Integral() << endl;
    }
    for (unsigned int p = 0; p < signalIIID.size(); p++) {
        nSignal += signalIIID[p]->Integral();
        //            cout << signalIIID[p]->Integral() << endl;
    }
    cout << nSignal << endl;
    WTempForCombination3D my3DInput;
    my3DInput.Wtemplate = (TH1*) wtemplate->Clone("Wtemp_Syst"); //normal
    my3DInput.rest.data = data;
    my3DInput.rest.nonRWs = bkg;
    my3DInput.rest.signalIID = signalIID;
    my3DInput.rest.signalIIID = signalIIID;


    pars.push_back(F0_);
    pars.push_back(FL_);
    pars.push_back(nTop7);
    pars.push_back(nW7);

    ChiSquaredCaculatorAndPlotter myChi2Syst(channel + string("_Chi2Syst_") + addname, pars, my3DInput, delSystF0, delSystFL);
    myChi2Syst.PrintOut();
    cout << "ChiSquared: " << myChi2Syst.GetChiSquared() << endl;
    cout << "NormalChiSquared: " << myChi2Syst.GetNormalizedChiSquared() << endl;
    myChi2Syst.WriteInfo();

    my3DInput.Wtemplate = (TH1*) wtemplate->Clone("Wtemp_Stat"); //normal
    ChiSquaredCaculatorAndPlotter myChi2Stat(channel + string("_Chi2Stat_") + addname, pars, my3DInput, delStatF0, delStatFL);
    myChi2Stat.PrintOut();
    cout << "ChiSquared: " << myChi2Stat.GetChiSquared() << endl;
    cout << "NormalChiSquared: " << myChi2Stat.GetNormalizedChiSquared() << endl;
    myChi2Stat.WriteInfo();

    my3DInput.Wtemplate = (TH1*) wtemplate->Clone("Wtemp_total"); //normal
    ChiSquaredCaculatorAndPlotter myChi2total(channel + string("_Chi2total_") + addname, pars, my3DInput, delTotF0, delTotFL);
    myChi2total.PrintOut();
    cout << "ChiSquared: " << myChi2total.GetChiSquared() << endl;
    cout << "NormalChiSquared: " << myChi2total.GetNormalizedChiSquared() << endl;
    myChi2total.WriteInfo();



    return 0;
}
void fit(float bgpar2smudge=1.0) {
  TF1 *fsig = new TF1("fsig",&d_sig,0.4,2,5);
  FILE *ofile;
  ofile = fopen("xsect-integrated-me.txt","w");
  TFile *_file0 = TFile::Open("h3maker-hn.root","update");
  _file0->Delete("*_f;*");
  TH2 *h2xsect = new TH2("hq2wXsect","Q^2:W",32,1.6,3.2,7,1.5,5.1);
  Double_t qbinedges[] = { 1.5, 1.6, 1.8, 2.1, 2.4, 2.76, 3.3, 5.1 };
  h2xsect->GetYaxis()->Set(7,qbinedges);
  TH3 *h3 = (TH3*)_file0->Get("hq2wmmp");
  int qbins = h3->GetZaxis()->GetNbins();
  //int wbins = h3->GetYaxis()->GetNbins();
  fprintf(ofile, "W\tQ2\txsect\terror\tpol4p0\tpol4p1\tpol4p2\tpol4p3\tpol4p4\tgN\tgM\tgS\tstepx0\tstepx1\txsectFn\n");
  for (int iq = 0; iq < qbins; iq++) {
    TString hsn = TString::Format("hs%d",iq);
    THStack *hs = (THStack*)_file0->Get(hsn.Data());
    TIter next(hs->GetHists());
    //while (TObject *obj = next()) {
    //TH1 *h = (TH1*)obj;
    while (TH1 *h = (TH1*)next()) {
      float *wq = getwq(h);
      float wval = wq[0];
      float qval = wq[1];
      delete [] wq;
      int wbin = h3->GetYaxis()->FindBin(wval);
      float wlow = h3->GetYaxis()->GetBinLowEdge(wbin);
      float step_x0 = sqrt(wlow*wlow+MASS_P*MASS_P-2*wlow*MASS_P);
      float whigh = h3->GetYaxis()->GetBinLowEdge(wbin+1);
      float step_x1 = sqrt(whigh*whigh+MASS_P*MASS_P-2*whigh*MASS_P);
      fitmmp(h,step_x0,step_x1,wval);
      TH1 *htmp = (TH1*)h->Clone("hbgsubtracted");
      TF1 *fbg = (TF1*)h->GetListOfFunctions()->FindObject("fbg");
      htmp->Add(fbg,-1);
      double N = htmp->Integral(34,43);
      double qwidth = h3->GetZaxis()->GetBinWidth(iq+1);
      //int wbin = h3->GetYaxis()->FindBin(wval);
      double wwidth = h3->GetYaxis()->GetBinWidth(wbin);

      TF1 *ftmp = (TF1*)h->GetListOfFunctions()->At(0);
      fsig->SetParameter(0,ftmp->GetParameter(5));
      fsig->SetParameter(1,ftmp->GetParameter(6));
      fsig->SetParameter(2,ftmp->GetParameter(7));
      fsig->SetParameter(3,step_x0);
      fsig->SetParameter(4,step_x1);
      fsig->SetLineWidth(2);
      fsig->SetLineColor(kBlue+1);
      h->GetListOfFunctions()->Add((TF1*)fsig->Clone("fsig"));
      //fsig->Print();
      double Nfn = 0;
      for (int b = 1; b < h->GetNbinsX(); b++) {
        double x = h->GetXaxis()->GetBinCenter(b);
        Nfn += fsig->Eval(x);
      }
      //printf("**** %.3e\t\%.3e\n",Nfn,N);
      double xsect = N/(0.891*wwidth*qwidth*19.844);
      double xsectFn = Nfn/(0.891*wwidth*qwidth*19.844);
      double err2 = 0;
      for (int immp = 34; immp < 44; immp++) err2 += htmp->GetBinError(immp)*htmp->GetBinError(immp);
      //fprintf(ofile, "%.3f\t%.3f\t%.0f\t%.0f",wval,qval,xsect/(1e6), sqrt(err2)/(1e6));
      fprintf(ofile, "%.3f\t%.3f\t%.3e\t%.3e",wval,qval,xsect/(1e6), sqrt(err2)/(1e6));
      int npar = ftmp->GetNpar();
      for (int ipar = 0; ipar < npar; ipar++) fprintf(ofile, "\t%.3e", ftmp->GetParameter(ipar));
      fprintf(ofile,"\t%.3e",xsectFn/(1e6));
      fprintf(ofile, "\n");
    }
    hsn.Append("_f");
    _file0->WriteObject(hs,hsn.Data());
    delete hs;
  }
  fclose(ofile);
  delete _file0;
}
void plot_MistagRate_allSamples(string sample="TTbar_", int wjets_hadtau_only=0){

  //
  // icomp=0: only show own results
  //       1: show also Koushik's results
  //
  
  //
  ///////////////////////////////////////////////////////////////////////////////////////////
  ////Some cosmetic work for official documents. 
  gStyle->SetOptStat(0);  ///to avoid the stat. on the plots 
  gROOT->LoadMacro("tdrstyle.C");
  //  setTDRStyle();
  gROOT->LoadMacro("CMS_lumi_v2.C");

  char tempname[200];
  char tempname2[200];
  int W = 800;
  int H = 600;
  int H_ref = 600;
  int W_ref = 800;
  float T = 0.08*H_ref;
  float B = 0.12*H_ref;
  float L = 0.12*W_ref;
  float R = 0.04*W_ref;

  TCanvas* c1 = new TCanvas("name","name",10,10,W,H);
  c1->SetFillColor(0);
  c1->SetBorderMode(0);
  c1->SetFrameFillStyle(0);
  c1->SetFrameBorderMode(0);
  c1->SetLeftMargin( L/W );
  c1->SetRightMargin( R/W );
  c1->SetTopMargin( T/H );
  c1->SetBottomMargin( B/H );
  c1->SetTickx(0);
  c1->SetTicky(0);
  
  Float_t legendX1 = .15; //.50;
  Float_t legendX2 = .50; //.70;
  Float_t legendY1 = .55; //.65;
  Float_t legendY2 = .88;
  TLegend* catLeg1 = new TLegend(legendX1,legendY1,legendX2,legendY2);
  catLeg1->SetTextSize(0.042);
  catLeg1->SetTextFont(42);
  catLeg1->SetFillColor(0);
  catLeg1->SetLineColor(0);
  catLeg1->SetBorderSize(0);

  TH1D * temp_tt_tauH, * temp_wj_tauH, *temp_tt_muH, * temp_wj_muH;
  
  //
  // From W+jets
  TFile file_WJet("Stack/TauBtaggedRate_WJet_stacked.root","R");
  temp_wj_tauH = (TH1D*)file_WJet.Get("TauBtaggedRate")->Clone();
  TH1D * wj_tauH = new TH1D("wj_tauH","WJet -- Tau mistag",temp_wj_tauH->GetNbinsX(),temp_wj_tauH->GetXaxis()->GetXmin(),temp_wj_tauH->GetXaxis()->GetXmax());
  for(int ibin=0;ibin<wj_tauH->GetNbinsX()+2;ibin++){
    double con = (double)temp_wj_tauH->GetBinContent(ibin);
    double err = (double)temp_wj_tauH->GetBinError(ibin);
    cout << "con: " << con << " err: " << err << endl;
    wj_tauH->SetBinContent(ibin,con);
    wj_tauH->SetBinError(ibin,err);
  }

  //
  // From ttbar
  TFile file_TTbar("Stack/TauBtaggedRate_TTbar_stacked.root","R");  
  temp_tt_tauH = (TH1D*)file_TTbar.Get("TauBtaggedRate")->Clone();
  TH1D * tt_tauH = new TH1D("tt_tauH","WJet -- Tau mistag",temp_tt_tauH->GetNbinsX(),temp_tt_tauH->GetXaxis()->GetXmin(),temp_tt_tauH->GetXaxis()->GetXmax());
  for(int ibin=0;ibin<tt_tauH->GetNbinsX()+2;ibin++){
    double con = (double)temp_tt_tauH->GetBinContent(ibin);
    double err = (double)temp_tt_tauH->GetBinError(ibin);
    cout << "con: " << con << " err: " << err << endl;
    tt_tauH->SetBinContent(ibin,con);
    tt_tauH->SetBinError(ibin,err);
  }

  //
  // From W+jets - predictions
  TFile file_WJet_mu("../TauHad2/Stack/TauBtaggedRate_WJet_stacked.root","R");  
  temp_wj_muH = (TH1D*)file_WJet_mu.Get("TauBtaggedRate")->Clone();
  TH1D * wj_muH = new TH1D("wj_muH","WJet -- Tau mistag",temp_wj_muH->GetNbinsX(),temp_wj_muH->GetXaxis()->GetXmin(),temp_wj_muH->GetXaxis()->GetXmax());
  for(int ibin=0;ibin<wj_muH->GetNbinsX()+2;ibin++){
    double con = (double)temp_wj_muH->GetBinContent(ibin);
    double err = (double)temp_wj_muH->GetBinError(ibin);
    cout << "con: " << con << " err: " << err << endl;
    wj_muH->SetBinContent(ibin,con);
    wj_muH->SetBinError(ibin,err);
  }

  //
  // From ttbar - predictions
  TFile file_TTbar_mu("../TauHad2/Stack/TauBtaggedRate_TTbar_stacked.root","R");
  temp_tt_muH = (TH1D*)file_TTbar_mu.Get("TauBtaggedRate")->Clone();
  TH1D * tt_muH = new TH1D("tt_muH","WJet -- Tau mistag",temp_tt_muH->GetNbinsX(),temp_tt_muH->GetXaxis()->GetXmin(),temp_tt_muH->GetXaxis()->GetXmax());
  for(int ibin=0;ibin<tt_muH->GetNbinsX()+2;ibin++){
    double con = (double)temp_tt_muH->GetBinContent(ibin);
    double err = (double)temp_tt_muH->GetBinError(ibin);
    cout << "con: " << con << " err: " << err << endl;
    tt_muH->SetBinContent(ibin,con);
    tt_muH->SetBinError(ibin,err);
  }

  //  catLeg1->SetHeader("Prob. of #mu from #tau ");

  //...........................................................................//
  // TTbar ....................................................................//
  //...........................................................................//
  double XUp = 350. , maxVal=1.;

    wj_tauH->GetXaxis()->SetRangeUser(30.,XUp);
    wj_tauH->SetMaximum(maxVal);
    wj_tauH->SetTitle("");
    
    wj_tauH->GetXaxis()->SetLabelFont(42);
    wj_tauH->GetXaxis()->SetLabelOffset(0.007);
    wj_tauH->GetXaxis()->SetLabelSize(0.04);
    wj_tauH->GetXaxis()->SetTitleSize(0.05);
    wj_tauH->GetXaxis()->SetTitleOffset(1.0);
    wj_tauH->GetXaxis()->SetTitleFont(42);
    wj_tauH->GetYaxis()->SetLabelFont(42);
    wj_tauH->GetYaxis()->SetLabelOffset(0.007);
    wj_tauH->GetYaxis()->SetLabelSize(0.04);
    wj_tauH->GetYaxis()->SetTitleSize(0.05);
    wj_tauH->GetYaxis()->SetTitleOffset(1.0);
    wj_tauH->GetYaxis()->SetTitleFont(42);
    wj_tauH->GetXaxis()->SetTitle("p_{T}(#tau jet)");
    wj_tauH->GetYaxis()->SetTitle("b-tagging mistag rate");
    wj_tauH->GetXaxis()->SetRangeUser(30.,XUp);
    wj_tauH->SetMaximum(maxVal);
    wj_tauH->SetLineColor(1);
    wj_tauH->Draw();

    tt_tauH->SetLineColor(2);
    //    thist.SetFillColor(0);
    //    thist.SetLineWidth(3);
    if (!wjets_hadtau_only) tt_tauH->Draw("same");

    wj_muH->SetLineColor(8); 
    //    wj_muH->SetMarkerStyle(20);
    if (!wjets_hadtau_only) {
      wj_muH->GetXaxis()->SetRangeUser(30.,500.);
      wj_muH->Draw("same");
    }
      
    tt_muH->SetLineColor(4);   
    if (!wjets_hadtau_only){
      tt_muH->GetXaxis()->SetRangeUser(30.,500.);
      tt_muH->Draw("same");
    }
    
    // sanity plot
    TH1 * sanityH = static_cast<TH1D*>(wj_tauH->Clone("sanity"));
    sanityH->Add(tt_muH);
    TH1 * tempH = static_cast<TH1D*>(wj_tauH->Clone("sanity"));
    tempH->Multiply(tt_muH);
    sanityH->Add(tempH,-1);
    sanityH->SetLineColor(34); 
    if (!wjets_hadtau_only){
      sanityH->GetXaxis()->SetRangeUser(30.,500.);
      sanityH->Draw("same");
    }
    
    //
    // TLegend
    sprintf(tempname,"(a) #tau_{h}-jets in t#bar{t}");
    if (!wjets_hadtau_only) catLeg1->AddEntry(tt_tauH,tempname,"l");

    if (wjets_hadtau_only)
      sprintf(tempname,"#tau_{h}-jets in W+jets");
    else 
      sprintf(tempname,"(b) #tau_{h}-jets in W+jets");
    catLeg1->AddEntry(wj_tauH,tempname,"l");    

    sprintf(tempname,"(c) #mu-jets in t#bar{t}");
    if (!wjets_hadtau_only) catLeg1->AddEntry(tt_muH,tempname,"l");

    sprintf(tempname,"(d) #mu-jets in W+jets");
    if (!wjets_hadtau_only) catLeg1->AddEntry(wj_muH,tempname,"l");

    //sprintf(tempname,"blue+(1 - blue)*red ");
    if (!wjets_hadtau_only){
      sprintf(tempname,"(e) #mu-jets (t#bar{t}) + #tau_{h}-jets (W+jets)");
      catLeg1->AddEntry(sanityH,tempname,"l");      
      TH1F *sanityHdummy = (TH1F*) sanityH->Clone();
      sanityHdummy->SetLineColor(0);
      sprintf(tempname,"= (c) + [1-(c)]#times(b)");
      catLeg1->AddEntry(sanityHdummy,tempname,"l");      
    }
    catLeg1->Draw();
    
    if (wjets_hadtau_only) {
      sprintf(tempname,"TauBtaggedRate_allSamples_hadtau_Wjets.png");
      c1->Print(tempname);
      sprintf(tempname,"TauBtaggedRate_allSamples_hadtau_Wjets.pdf");
      c1->Print(tempname);
    } else {
      sprintf(tempname,"TauBtaggedRate_allSamples.png");
      c1->Print(tempname);
      sprintf(tempname,"TauBtaggedRate_allSamples.pdf");
      c1->Print(tempname);
    }
    
}
예제 #24
0
파일: DrawKs.C 프로젝트: ktf/AliPhysics
TH1* GetCentK(TDirectory* top, Double_t c1, Double_t c2, Int_t s,
	      TLegend* l)
{
  TString dname; dname.Form("cent%06.2f_%06.2f", c1, c2);
  dname.ReplaceAll(".", "d");
  TDirectory* d = top->GetDirectory(dname);
  if (!d) {
    Warning("GetCetnK", "Directory %s not found in %s",
	    dname.Data(), top->GetName());
    return;
  }

  TDirectory* det = d->GetDirectory("details");
  if (!det) {
    Warning("GetCetnK", "Directory details not found in %s",
	    d->GetName());
    d->ls();
    return;
  }

  TObject* o = det->Get("scalar");
  if (!o) {
    Warning("GetCetnK", "Object scalar not found in %s",
	    det->GetName());
    return;
  }

  if (!o->IsA()->InheritsFrom(TH1::Class())) {
    Warning("GetCetnK", "Object %s is not a TH1, but a %s",
	    o->GetName(), o->ClassName());
    return;
  }
  TH1* h = static_cast<TH1*>(o->Clone());
  Color_t col = cc[(s-1)%10];
  h->SetLineColor(col);
  h->SetMarkerColor(col);
  h->SetFillColor(col);
  h->SetFillStyle(1001);
  // h->SetTitle(Form("%5.2f-%5.2f%% #times %d", c1, c2, s));
  h->SetTitle(Form("%2.0f-%2.0f%% + %d", c1, c2, s-1));
  TF1* f = new TF1("", "[0]",-2.2,2.2);
  f->SetParameter(0,s-1);
  f->SetLineColor(col);
  f->SetLineStyle(7);
  f->SetLineWidth(1);
  // h->Scale(s);
  h->Add(f);
  h->GetListOfFunctions()->Add(f);
  f->SetParameter(0,s);
  for (Int_t i = 1; i <= h->GetNbinsX(); i++) {
    if (TMath::Abs(h->GetBinCenter(i)) > 2) {
      h->SetBinContent(i,0);
      h->SetBinError(i,0);
    }
  }
  
  TLegendEntry* e = l->AddEntry(h, h->GetTitle(), "f");
  e->SetFillColor(col);
  e->SetFillStyle(1001);
  e->SetLineColor(col);

  return h;
}
void makePlot(TCanvas* canvas, const std::string& outputFileName, TTree* testTree, const std::string& varName, 
	      unsigned numBinsX, double xMin, double xMax)
{
  std::cout << "creating histogramTauIdPassed..." << std::endl;
  TString histogramTauIdPassedName = TString("histogramTauIdPassed").Append("_").Append(varName.data());
  TH1* histogramTauIdPassed = fillHistogram(testTree, varName, "type==1", "",
					    histogramTauIdPassedName.Data(), numBinsX, xMin, xMax);
  std::cout << "--> histogramTauIdPassed = " << histogramTauIdPassed << ":" 
	    << " integral = " << histogramTauIdPassed->Integral() << std::endl;

  std::cout << "creating histogramTauIdFailed..." << std::endl;
  TString histogramTauIdFailedName = TString("histogramTauIdFailed").Append("_").Append(varName.data());
  TH1* histogramTauIdFailed = fillHistogram(testTree, varName, "type==0", "",
					    histogramTauIdFailedName.Data(), numBinsX, xMin, xMax);
  std::cout << "--> histogramTauIdFailed = " << histogramTauIdFailed 
	    << " integral = " << histogramTauIdFailed->Integral() << std::endl;

  std::cout << "creating histogramTauIdDenominator..." << std::endl;
  TString histogramTauIdDenominatorName = TString("histogramTauIdDenominator").Append("_").Append(varName.data());
  TH1* histogramTauIdDenominator = new TH1F(histogramTauIdDenominatorName.Data(), 
					    histogramTauIdDenominatorName.Data(), numBinsX, xMin, xMax);
  histogramTauIdDenominator->Add(histogramTauIdPassed);
  histogramTauIdDenominator->Add(histogramTauIdFailed);
  std::cout << "--> histogramTauIdDenominator = " << histogramTauIdDenominator 
	    << " integral = " << histogramTauIdDenominator->Integral() << std::endl;

  std::cout << "creating histogramFakeRate..." << std::endl;
  TString histogramFakeRateName = TString("histogramFakeRate").Append("_").Append(varName.data());
  TH1* histogramFakeRate = new TH1F(histogramFakeRateName.Data(), 
				    histogramFakeRateName.Data(), numBinsX, xMin, xMax);
  histogramFakeRate->Add(histogramTauIdPassed);
  histogramFakeRate->Divide(histogramTauIdDenominator);
  std::cout << "--> histogramFakeRate = " << histogramFakeRate 
	    << " integral = " << histogramFakeRate->Integral() << std::endl;

  std::cout << "creating histogramFakeRateWeighted..." << std::endl;
  TString histogramFakeRateWeightedName = TString("histogramFakeRateWeighted").Append("_").Append(varName.data());
  TH1* histogramFakeRateWeighted = fillHistogram(testTree, varName, "", "MVA_KNN", 
						 histogramFakeRateWeightedName.Data(), numBinsX, xMin, xMax);
  histogramFakeRateWeighted->Divide(histogramTauIdDenominator);
  std::cout << "--> histogramFakeRateWeighted = " << histogramFakeRateWeighted 
	    << " entries = " << histogramFakeRateWeighted->GetEntries() << ","
	    << " integral = " << histogramFakeRateWeighted->Integral() << std::endl;
  // Scale the weighted fake rate histogram

  histogramFakeRate->SetTitle(varName.data());
  histogramFakeRate->SetStats(false);
  histogramFakeRate->SetMinimum(1.e-4);
  histogramFakeRate->SetMaximum(1.e+1);
  histogramFakeRate->SetLineColor(2);
  histogramFakeRate->SetLineWidth(2);
  histogramFakeRate->SetMarkerStyle(20);
  histogramFakeRate->SetMarkerColor(2);
  histogramFakeRate->SetMarkerSize(1);
  histogramFakeRate->Draw("e1p");

  histogramFakeRateWeighted->SetLineColor(4);
  histogramFakeRateWeighted->SetLineWidth(2);
  histogramFakeRateWeighted->SetMarkerStyle(24);
  histogramFakeRateWeighted->SetMarkerColor(4);
  histogramFakeRateWeighted->SetMarkerSize(1);
  histogramFakeRateWeighted->Draw("e1psame");

  TLegend legend(0.11, 0.73, 0.31, 0.89);
  legend.SetBorderSize(0);
  legend.SetFillColor(0);
  legend.AddEntry(histogramFakeRate, "Tau id. discr.", "p");
  legend.AddEntry(histogramFakeRateWeighted, "Fake-Rate weight", "p");
  legend.Draw();

  canvas->Update();
  canvas->Print(outputFileName.data());
}
예제 #26
0
//______________________________________________________________________________
void PIDEnergy()
{
    // Main method.

    Char_t tmp[256];

    // load CaLib
    gSystem->Load("libCaLib.so");

    // general configuration
    const Char_t* data = "Data.PID.E0";
    const Char_t* hName = "CaLib_PID_Energy_Proton_PID_Energy";

    // configuration (December 2007)
    //const Char_t calibration[] = "LD2_Dec_07";
    //const Char_t filePat[] = "/usr/puma_scratch0/werthm/A2/Dec_07/AR/out/ARHistograms_CB_RUN.root";
    //const Char_t mcFile[] = "/usr/panther_scratch0/werthm/A2/Dec_07/MC/calibration/all.root";

    // configuration (February 2009)
    //const Char_t calibration[] = "LD2_Feb_09";
    //const Char_t filePat[] = "/usr/puma_scratch0/werthm/A2/Feb_09/AR/out/ARHistograms_CB_RUN.root";
    //const Char_t mcFile[] = "/usr/panther_scratch0/werthm/A2/Feb_09/MC/calibration/all.root";

    // configuration (May 2009)
    const Char_t calibration[] = "LD2_May_09";
    const Char_t filePat[] = "/usr/puma_scratch0/werthm/A2/May_09/AR/out/ARHistograms_CB_RUN.root";
    const Char_t mcFile[] = "/usr/panther_scratch0/werthm/A2/May_09/MC/calibration/all.root";

    // get number of sets
    Int_t nSets = TCMySQLManager::GetManager()->GetNsets(data, calibration);

    // create canvas
    Int_t n = TMath::Sqrt(nSets);
    TCanvas* cOverview = new TCanvas("c", "c", 1200, 900);
    cOverview->Divide(n, nSets / n + 1);

    // create arrays
    Double_t* pos = new Double_t[nSets+1];
    Double_t* fwhm = new Double_t[nSets+1];

    // total sum histogram
    TH1* hTot = 0;

    // load MC histo
    TFile* fMC = new TFile(mcFile);
    TH2* hMC2 = (TH2*) fMC->Get(hName);
    TH1* hMC = hMC2->ProjectionX("mc");
    hMC->SetLineColor(kBlue);

    // loop over sets
    for (Int_t i = 0; i < nSets; i++)
    {
        // create file manager
        TCFileManager m(data, calibration, 1, &i, filePat);

        // get histo
        TH2* h2 = (TH2*) m.GetHistogram(hName);

        // skip empty histo
        if (!h2) continue;

        // project histo
        sprintf(tmp, "Proj_%d", i);
        TH1* h = (TH1*) h2->ProjectionX(tmp);
        //TH1* h = (TH1*) h2->ProjectionX(tmp, 9, 9);
        //h->Rebin(4);

        // add to total histogram
        if (!hTot) hTot = (TH1*) h->Clone();
        else hTot->Add(h);

        // fit histo
        cOverview->cd(i+1);
        h->SetLineColor(kBlack);
        h->Draw();
        hMC->Scale(h->GetMaximum()/hMC->GetMaximum());
        hMC->DrawCopy("same");
    }
}
예제 #27
0
void MakeIndividualPDFhists(const std::string name)
{
	const int nfiles = 6;
	
	TFile* f[nfiles];
	f[0] = new TFile("~/RESULTS/10222009_PDFsystFullMCDataset/10272009_Result3/PDFsyst1.root");
	f[1] = new TFile("~/RESULTS/10222009_PDFsystFullMCDataset/10272009_Result3/PDFsyst2.root");
	f[2] = new TFile("~/RESULTS/10222009_PDFsystFullMCDataset/10272009_Result3/PDFsyst3.root");
	f[3] = new TFile("~/RESULTS/10222009_PDFsystFullMCDataset/10272009_Result3/PDFsyst4.root");
	f[4] = new TFile("~/RESULTS/10222009_PDFsystFullMCDataset/10272009_Result3/PDFsyst5.root");
	f[5] = new TFile("~/RESULTS/10222009_PDFsystFullMCDataset/10272009_Result3/PDFsyst6.root");


	assert (f[0] !=NULL && "FILE 1 NOT FOUND!");
	assert (f[1] !=NULL && "FILE 2 NOT FOUND!");
	assert (f[2] !=NULL && "FILE 3 NOT FOUND!");
	assert (f[3] !=NULL && "FILE 4 NOT FOUND!");
	assert (f[4] !=NULL && "FILE 5 NOT FOUND!");
	assert (f[5] !=NULL && "FILE 6 NOT FOUND!");

	TH1* h[41];
	
	float xmin = 0;
	float xpoint1 = 200;
	float xpoint2 = 250;
	float xpoint3 = 300;
	float xpoint4 = 650;
	float width1 = 10;
	float width2 = 10;
	float width3 = 50;
	float width4 = 250;
	
	//0th hist is the reference. other 40 are the variants.
	for (int i=0; i < 41; ++i)
	{
		std::stringstream hist;
		hist << "Ana/PhoJetsTemp/Hist/1Jet/PDFSyst/PDFSystPara"<< i << "_" << name;
		std::cout << "looking for hist " << hist.str() << std::endl;
		h[i] = dynamic_cast<TH1*> (f[0]->Get(hist.str().c_str()));
		assert (h[i] != NULL && "hist is null");
		//Sumw2() for these hists are called at creation
		
		//add the other 2 jobs resutls
		for (int nf=1;nf< nfiles;++nf)
		{
			TH1* temp = dynamic_cast<TH1*> (f[nf]->Get(hist.str().c_str()));
			assert (temp != NULL && "hist is null");
			h[i]->Add(temp);
		}
		

		h[i] = (TH1F*) MakeVariableBins (h[i], xmin, xpoint1, xpoint2, xpoint3, xpoint4, width1, width2, width3, width4, false);
		if (i>0)
		{
			h[i]->Scale(h[0]->Integral()/(1. * h[i]->Integral()));
			h[i]->Divide(h[0]);
			int marker = 22, color=2;
			if (i%2)
			{
				marker = 23;
				color = 4;
			}
				
			h[i]->SetMarkerColor(color);
			h[i]->SetLineColor(color);
			h[i]->SetMarkerStyle(marker);
			h[i]->SetMarkerSize(1);
		}
	}


			gStyle->SetOptStat(0);
		new TCanvas();
		gPad->SetGridx();
		gPad->SetGridy();
		gPad->SetTickx();
		gPad->SetTicky();



	//make a plot for each PDF parameter wrt to reference
	for (int ipdf = 1; ipdf <41; ipdf=ipdf+2)
	{
		//h[ipdf]->Scale(h[0]->Integral()/(1. * h[ipdf]->Integral()));
		//h[ipdf+1]->Scale(h[0]->Integral()/(1. * h[ipdf+1]->Integral()));
		std::string xtitle, ytitle;
		if (name == "PhoEt") xtitle = "E_{T}^{#gamma}";
		ytitle = "Ratio wrt base (Parameter 0)";
		
		std::stringstream title, le1,le2, file;
		int jpdf = ipdf+1;
		title << "PDF parameter " << ipdf << " & "<< jpdf << "(normalized to base and ratio wrt to base)"
				<< ";" << xtitle << ";" << ytitle;
		le1 << "Parameter " << ipdf;
		le2 << "Parameter " << jpdf;
		file << "PDFpara_"<< ipdf << "_" << jpdf << ".eps";

		
		//h[ipdf]->SetMinimum(0.9);
		//h[ipdf]->SetMaximum(1.1);
		//h[ipdf]->SetTitle(title.str().c_str());
		h[ipdf]->GetXaxis()->CenterTitle(1);
		h[ipdf]->GetYaxis()->CenterTitle(1);

		if (ipdf==1) 
		{
			h[ipdf]->Draw();
			h[ipdf+1]->Draw("SAME");
		} else 
		{
			h[ipdf]->Draw("SAME");
			h[ipdf+1]->Draw("SAME");
		}

		TLegend *leg = new TLegend (0.7,0.8,0.9,0.9);
		leg->SetTextFont(42);
		leg->SetTextSize(0.03);


		leg->AddEntry(h[ipdf],le1.str().c_str());
		leg->AddEntry(h[ipdf+1],le2.str().c_str());
		//leg->Draw();
		//gPad->Print(file.str().c_str());
		
	}



	return;

	
	for (int i=1; i < 40; ++i)
	{
		if (i==1)
		{
			h[i]->Draw("P");
			h[i]->SetTitle("PDF: 40 variants wrt to CTEQ6;E_{T}^{#gamma};Ratio");
			//h[i]->SetTitle("PDF: 40 variants wrt to CTEQ6;E_{T}^{jet};Ratio");
		}
		else h[i]->Draw("P same");
	}

	//no make a plot with max/min values
	//exclude the 0th hist which is the reference
	
	for (int bin=0; bin<= h[1]->GetNbinsX(); ++bin)
	{
		if (h[1]->GetBinContent(bin))
		{
			float max=1,min=1;
			float maxer=0,miner=0;
			for (int nh=2; nh<41; ++nh)
			{
				if (h[nh]->GetBinContent(bin) > max )
				{
					max = h[nh]->GetBinContent(bin);
					maxer = h[nh]->GetBinError(bin);
				}
				if (h[nh]->GetBinContent(bin) < min )
				{
					min = h[nh]->GetBinContent(bin);
					miner = h[nh]->GetBinError(bin);
				}
			}
			
			h[1]->SetBinContent(bin,max);
			h[1]->SetBinError(bin,maxer);
			h[2]->SetBinContent(bin,min);
			h[2]->SetBinError(bin,miner);
		}

	}

	new TCanvas();
	gPad->SetGridx();
	gPad->SetGridy();
	gPad->SetTickx(2);
	gPad->SetTicky(2);
	h[1]->SetTitle("Max/Min of 40 PDF variants");
	h[1]->Draw("PE1");
	h[2]->Draw("SAME PE1");
	
	

return;

	TH1* ph = dynamic_cast<TH1*> (f[0]->Get("Ana/PhoJetsTemp/Hist/1Jet/Photon/EtCorr"));
	assert (ph != NULL && " photon hist is null");
	for (int nf=1;nf< nfiles;++nf)
	{
		TH1* temp = dynamic_cast<TH1*> (f[nf]->Get("Ana/PhoJetsTemp/Hist/1Jet/Photon/EtCorr"));
		assert (temp != NULL && "photon jobs hist is null");
		temp->Sumw2();
		ph->Add(temp);
	}

	ph = (TH1F*) MakeVariableBins (ph, xmin, xpoint1, xpoint2, xpoint3, xpoint4, width1, width2, width3, width4, false);

	new TCanvas();
	ph->Draw();
	return;
	
	TH1* final = dynamic_cast<TH1*> (ph->Clone("copy"));
	assert (final != NULL && " photon hist is null");
	for (int bin =0; bin <= ph->GetNbinsX()+1; ++bin)
	{
		final->SetBinError(bin,0);
		final->SetBinContent(bin,0);
void drawData( RooWorkspace *w ) {

  w->var("B_s0_DTF_B_s0_M")->setBins(100);

  TH1 *Data              = w->data("Data")->createHistogram( "Data", *w->var("B_s0_DTF_B_s0_M") );
  Data->SetLineWidth(2);
  Data->SetLineColor(kBlack);

  TH1 *Data2011          = w->data("Data2011")->createHistogram( "Data2011", *w->var("B_s0_DTF_B_s0_M") );
  Data2011->SetLineWidth(4);
  Data2011->SetLineColor(kBlue);
  Data2011->SetFillColor(0);
  Data2011->SetFillStyle(0);

  TH1 *Data2012          = w->data("Data2012")->createHistogram( "Data2012", *w->var("B_s0_DTF_B_s0_M") );
  Data2012->SetLineWidth(4);
  Data2012->SetLineColor(kRed);
  Data2012->SetFillColor(0);
  Data2012->SetFillStyle(0);

  int col1 = TColor::GetColor( "#b2e2e2" );
  int col2 = TColor::GetColor( "#66c2a4" );
  int col3 = TColor::GetColor( "#2ca25f" );
  int col4 = TColor::GetColor( "#006d2c" );

  TH1 *Data2011HadronTOS = w->data("Data2011HadronTOS")->createHistogram( "Data2011HadronTOS", *w->var("B_s0_DTF_B_s0_M") );
  Data2011HadronTOS->SetLineColor(col1);
  Data2011HadronTOS->SetFillColor(col1);

  TH1 *Data2011GlobalTIS = w->data("Data2011GlobalTIS")->createHistogram( "Data2011GlobalTIS", *w->var("B_s0_DTF_B_s0_M") );
  Data2011GlobalTIS->SetLineColor(col2);
  Data2011GlobalTIS->SetFillColor(col2);

  TH1 *Data2012HadronTOS = w->data("Data2012HadronTOS")->createHistogram( "Data2012HadronTOS", *w->var("B_s0_DTF_B_s0_M") );
  Data2012HadronTOS->SetLineColor(col3);
  Data2012HadronTOS->SetFillColor(col3);

  TH1 *Data2012GlobalTIS = w->data("Data2012GlobalTIS")->createHistogram( "Data2012GlobalTIS", *w->var("B_s0_DTF_B_s0_M") );
  Data2012GlobalTIS->SetLineColor(col4);
  Data2012GlobalTIS->SetFillColor(col4);


  THStack *hsData = new THStack("DataHs","");
  hsData->Add( Data2011HadronTOS );
  hsData->Add( Data2011GlobalTIS );
  hsData->Add( Data2012HadronTOS );
  hsData->Add( Data2012GlobalTIS );

  TH1 *DataYears = (TH1*)Data2011->Clone("DataYears");
  DataYears->Add( Data2012 );
  DataYears->SetLineColor(kRed);
  DataYears->SetLineWidth(4);

  TLegend *leg = new TLegend(0.6,0.4,0.89,0.89);
  leg->SetFillColor(0);
  leg->AddEntry( Data2011HadronTOS, "2011 Hadron TOS", "F" );
  leg->AddEntry( Data2011GlobalTIS, "2011 Global TIS", "F" );
  leg->AddEntry( Data2012HadronTOS, "2012 Hadron TOS", "F" );
  leg->AddEntry( Data2012GlobalTIS, "2012 Global TIS", "F" );
  leg->AddEntry( Data2011, "2011" , "L" );
  leg->AddEntry( DataYears, "2012" , "L" );
  leg->AddEntry( Data, "All", "L" );

  TCanvas *c = new TCanvas();
  hsData->Draw("HISTF");
  DataYears->Draw("HISTsame");
  Data2011->Draw("HISTsame");
  Data->Draw("HISTsame");
  leg->Draw("same");

  hsData->GetHistogram()->GetXaxis()->SetTitle("m(K^{+}#pi^{-}K^{-}#pi^{+}) [MeV]");
  hsData->GetHistogram()->GetYaxis()->SetTitle("Events / ( 8 MeV )");
  hsData->GetHistogram()->GetXaxis()->SetTitleOffset(0.8);
  hsData->GetHistogram()->GetYaxis()->SetTitleOffset(0.9);
  hsData->GetHistogram()->GetXaxis()->SetTitleSize(0.08);
  hsData->GetHistogram()->GetYaxis()->SetTitleSize(0.08);

  c->Update();
  c->Modified();
  c->Print("plots/DataSets.pdf");
}
예제 #29
0
파일: addhistos.C 프로젝트: svn2github/Go4
///////////////////////////////////////////////////////////////////
//////// Go4 GUI example script addhistos.C
//          J.Adamczewski, gsi, May 2006
//          JAM May 2015: added support for 2d histograms
// NOTE: to be run in Go4 GUI local command line only!
//       NEVER call this script in remote analysis process!!!
/////// Functionality:
// adds histogram of name2 to histogram of name1
/////// Usage:
// histogram name2 will be scaled by factor.
// (e.g. if factor==-1, his2 is substracted from his1)
// The draw flag switches if the results are displayed each time this makro is called
// if display is switched off, the result histogram is just updated in browser and existing displays
///////
Bool_t addhistos(const char* name1, const char* name2, Double_t factor, Bool_t draw)
{
   if(TGo4AbstractInterface::Instance()==0 || go4!=TGo4AbstractInterface::Instance()) {
      std::cout <<"FATAL: Go4 gui macro executed outside Go4 GUI!! returning." << std::endl;
      return kFALSE;
   }
   TString fullname1 = go4->FindItem(name1);
   TObject* ob1=go4->GetObject(fullname1,1000); // 1000=timeout to get object from analysis in ms
   TH1 *his1(0), *his2(0);
   if(ob1 && ob1->InheritsFrom("TH1"))
      his1 = (TH1*) ob1;
   if(his1==0) {
      std::cout <<"addhistos could not get histogram "<<fullname1 << std::endl;
      return kFALSE;
   }

   TString fullname2 = go4->FindItem(name2);
   TObject* ob2=go4->GetObject(fullname2,1000); // 1000=timeout to get object from analysis in ms
   if(ob2 && ob2->InheritsFrom("TH1"))
      his2 = (TH1*)ob2;
   if(his2==0) {
      std::cout <<"addhistos could not get histogram "<<fullname2 << std::endl;
      return kFALSE;
   }
   if((his1->GetDimension()) != (his2->GetDimension()))
   {
       std::cout <<"addhistos could not add histograms of different dimensions "<< std::endl;
       return kFALSE;
   }
   TH1* result = (TH1*) his1->Clone();
   TString n1 = his1->GetName();
   TString n2 = his2->GetName();
   TString t1 = his1->GetTitle();
   TString t2 = his2->GetTitle();
   TString soper;
   if(factor>0)
      soper.Form(") + %4.1E * (",factor);
   else
      soper.Form(") - %4.1E * (",-1*factor);
   TString finalname = TString("(")+n1+soper+n2+")";
   TString finaltitle = TString("(")+t1+soper+t2+")";
   result->SetName(finalname);
   result->SetTitle(finaltitle);
   result->Sumw2();
   result->Add(his2,factor);
   result->SetDirectory(0);
   TString rname = go4->SaveToMemory("Sums", result, kTRUE);
   std::cout<< "Saved result histogram to " << rname.Data() <<std::endl;
   if(draw) {
      ViewPanelHandle vpanel = go4->StartViewPanel();
      if(result->GetDimension()>1)
      {
          // superimpose mode is not supported for 2d histograms
          go4->DrawItem(rname, vpanel);
      }
      else
      {
        go4->SetSuperimpose(vpanel,kTRUE);
        go4->DrawItem(fullname1, vpanel);
        go4->DrawItem(fullname2, vpanel);
        go4->DrawItem(rname, vpanel);
      }
   }
   return kTRUE;
}
void fitmmp(TH1 *hmmp, float step_x0 = 2, float step_x1 = 2.1, float wval = 0, bool verbose = false) {
  float fnrangemax = 1.1;
  float mmplow = 0.4;
  //float bgp2 = 2.1e8;
  float gsig = -0.0065+0.013*wval;
  float pol2cutoff = 4; //wval under which to use pol2
  float fitcutoff = 1.1;
  TString options;
  if (verbose) options = "";
  else options = "Q";
  TF1 *fbg = f_pol4("fbg",0.4,fnrangemax,true);
  fbg->FixParameter(7,step_x0);
  fbg->FixParameter(8,step_x1);
  if (wval<pol2cutoff) {
    fitcutoff = 1.1;
    fbg->FixParameter(3,0);
    fbg->FixParameter(4,0);
  } else fitcutoff = 2;
  hmmp->Fit(fbg,options.Data(),"",mmplow,fitcutoff);
  if (true) { //gMinuit->fCstatu.Contains("CONVER")) {
    TF1 *fbg2 = f_pol4("fbg",0.4,fnrangemax,false);
    fbg2->SetParameters(fbg->GetParameters());
    fbg2->FixParameter(7,step_x0);
    fbg2->FixParameter(8,step_x1);
    if (wval<pol2cutoff) {
      fbg2->FixParameter(3,0);
      fbg2->FixParameter(4,0);
    }
    fbg2->SetParameter(5,0);
    fbg2->SetParameter(6,0);
    TH1 *htmp = (TH1*)hmmp->Clone("hmmp_bgsub");
    htmp->Add(fbg2,-1);
    TF1 *fgaus = new TF1("fgaus","gaus",0.4,fnrangemax);
    fgaus->FixParameter(2,gsig);
    fgaus->FixParameter(1,0.783);
    float gmax = 0.85;
    if (gmax > step_x0) gmax = step_x0;
    htmp->Fit(fgaus,options.Data(),"",0.74,gmax);
    TF1 *f = f_pol4gaus("f",0.4,fnrangemax,fbg2,fgaus);
    f->FixParameter(8,step_x0);
    f->FixParameter(9,step_x1);
    if (wval<pol2cutoff) {
      f->FixParameter(3,0);
      f->FixParameter(4,0);
    }
    f->SetNpx(500);
    f->FixParameter(6,0.783);
    f->FixParameter(7,gsig);
    hmmp->Fit(f,options.Data(),"",mmplow,fitcutoff);

    //f->FixParameter(2,0.9*f->GetParameter(2));
    //hmmp->Fit(f,options.Data(),"",mmplow,fitcutoff);

    fgaus->SetRange(0.4,fnrangemax);
    for (int i = 0; i < 3; i++) fgaus->SetParameter(i,f->GetParameter(i+5));
    for (int i = 0; i < 5; i++) fbg2->SetParameter(i,f->GetParameter(i));
    fbg2->SetLineStyle(2);
    fbg2->SetLineColor(kRed+1);
    fgaus->SetLineStyle(2);
    fgaus->SetLineColor(kGreen+1);
    hmmp->GetListOfFunctions()->Add(fbg2->Clone());
    hmmp->GetListOfFunctions()->Add(fgaus->Clone());
    float ymax = 1.1*hmmp->GetMaximum();
    hmmp->GetYaxis()->SetRangeUser(0,ymax);
    TLine *l1 = new TLine(step_x0,0,step_x0,ymax);
    TLine *l2 = new TLine(step_x1,0,step_x1,ymax);
    l1->SetLineColor(kBlue+1);
    l2->SetLineColor(kBlue+1);
    hmmp->GetListOfFunctions()->Add(l1);
    hmmp->GetListOfFunctions()->Add(l2);
    delete fbg2;
    delete htmp;
    delete fgaus;
    delete f;
  } else hmmp->GetListOfFunctions()->Delete();
  delete fbg;
}