void CalculateDeff(Int_t MM_low, Int_t MM_high, Char_t* filename, Double_t Ratio) {

	CalculateYield(MM_low, MM_high, filename, Ratio);
	Deff = Double_t(yield)/Double_t(nentries);
	printf("Detection Efficiency: %f \n", Deff);

}
void CheckOutput(){
  //
  //
  //
  TFile * f  = TFile::Open("Filtered.root");
  TTree * highPt = (TTree*)f->Get("highPt");
  TTree * treeV0s = (TTree*)f->Get("V0s");
  //
  // Export variable:
  //
  Double_t ratioHighPtV0Entries=treeV0s->GetEntries()/Double_t(treeV0s->GetEntries()+highPt->GetEntries()+0.000001);
  Double_t ratioHighPtV0Size=treeV0s->GetZipBytes()/Double_t(treeV0s->GetZipBytes()+highPt->GetZipBytes()+0.000001);
  printf("#UnitTest:\tAliAnalysisTaskFiltered\tRatioPtToV0Entries\t%f\n",ratioHighPtV0Entries);
  printf("#UnitTest:\tAliAnalysisTaskFiltered\tRatioPtToV0Size\t%f\n",ratioHighPtV0Size);
  //
  //
  Double_t ratioPointsV0 = 2*treeV0s->GetBranch("friendTrack0.fCalibContainer")->GetZipBytes()/Double_t(0.00001+treeV0s->GetZipBytes());
  Double_t ratioPointsHighPt = highPt->GetBranch("friendTrack.fCalibContainer")->GetZipBytes()/Double_t(0.00001+highPt->GetZipBytes());
  printf("#UnitTest:\tAliAnalysisTaskFiltered\tRatioPointsV0\t%f\n",ratioPointsV0);
  printf("#UnitTest:\tAliAnalysisTaskFiltered\tRatioPointsHighPt\t%f\n",ratioPointsHighPt);
  //
  // a.) Check track correspondence
  //
  Int_t entries= highPt->Draw("(friendTrack.fTPCOut.fP[3]-esdTrack.fIp.fP[3])/sqrt(friendTrack.fTPCOut.fC[9]+esdTrack.fIp.fC[9])","friendTrack.fTPCOut.fP[3]!=0","");
  // here we should check if the tracks
  Double_t pulls=TMath::RMS(entries, highPt->GetV1());
  printf("#UnitTest:\tAliAnalysisTaskFiltered\tFriendPull\t%2.4f\n",pulls);
  printf("#UnitTest:\tAliAnalysisTaskFiltered\tFriendOK\t%d\n",pulls<10);

}
//   Definition der Fit-Funktion
    Double_t HistoSum(Double_t *x, Double_t *par)
{
  Double_t eins = Double_t(histo1->GetBinContent(histo1->GetXaxis()->FindFixBin(x[0]),histo1->GetYaxis()->FindFixBin(x[1])));
  Double_t zwei = Double_t(histo2->GetBinContent(histo2->GetXaxis()->FindFixBin(x[0]),histo2->GetYaxis()->FindFixBin(x[1])));
  //Double_t drei = Double_t(histo3->GetBinContent(histo3->GetXaxis()->FindFixBin(x[0]),histo3->GetYaxis()->FindFixBin(x[1])));
  //Double_t vier = Double_t(histo4->GetBinContent(histo4->GetXaxis()->FindFixBin(x[0]),histo4->GetYaxis()->FindFixBin(x[1])));
 //Allgemeine "return"-Varianten:
  //return faktor*( par[0]*eins + par[1]*zwei + par[2]*drei + par[3]*vier );
  return faktor*( par[0]*eins + par[1]*zwei );

}
Beispiel #4
0
void gtime2(Int_t nsteps = 200, Int_t np=5000) {
   if (np > 5000) np = 5000;
   Int_t color[5000];
   Double_t cosphi[5000], sinphi[5000], speed[5000];
   TRandom3 r;
   Double_t xmin = 0, xmax = 10, ymin = -10, ymax = 10;
   TGraphTime *g = new TGraphTime(nsteps,xmin,ymin,xmax,ymax);
   g->SetTitle("TGraphTime demo 2;X;Y");
   Int_t i,s;
   Double_t phi,fact = xmax/Double_t(nsteps);
   for (i=0;i<np;i++) { //calculate some object parameters
      speed[i]  = r.Uniform(0.5,1);
      phi       = r.Gaus(0,TMath::Pi()/6.);
      cosphi[i] = fact*speed[i]*TMath::Cos(phi);
      sinphi[i] = fact*speed[i]*TMath::Sin(phi);
      Double_t rc = r.Rndm();
      color[i] = kRed;
      if (rc > 0.3) color[i] = kBlue;
      if (rc > 0.7) color[i] = kYellow;
   }
   for (s=0;s<nsteps;s++) { //fill the TGraphTime step by step
      for (i=0;i<np;i++) {
         Double_t xx = s*cosphi[i];
         if (xx < xmin) continue;
         Double_t yy = s*sinphi[i];
         TMarker *m = new TMarker(xx,yy,25);
         m->SetMarkerColor(color[i]);
         m->SetMarkerSize(1.5 -s/(speed[i]*nsteps));
         g->Add(m,s);
      }
      g->Add(new TPaveLabel(.70,.92,.98,.99,Form("shower at %5.3f nsec",3.*s/nsteps),"brNDC"),s);
   }
   g->Draw();
}
Beispiel #5
0
//----------------------------------------------
KVCouple::KVCouple(Int_t zf,Int_t zsup,Int_t div){

	zfra = zf;
	zmax = zsup;
		
	zlim = zfra/div;
	Double_t zmoy = zfra/Double_t(div);
	Double_t diff = zmoy-zlim;
	Int_t sup = TMath::Nint(diff*div);
	if (sup>=1){
		zlim+=1;
	}

	if (zfra>=zmax) {	
		//cas 1
		nbre = zmax-zlim+1;
		if (nbre>0){

			tz1 = new Int_t[nbre];
			tz2 = new Int_t[nbre];
			Int_t z1=0;
			for (Int_t ii=0;ii<nbre;ii+=1){
				z1 = zmax-ii;
				tz1[ii]	=	z1;
				tz2[ii]	=	zfra-z1;
			}
			init=kTRUE;		
		}
		else {
			//return;
			ResetVars();
		}
	}
	else {
		nbre = zfra-zlim+1;
		if (nbre>0){

			tz1 = new Int_t[nbre];
			tz2 = new Int_t[nbre];
			Int_t z1=0;
			for (Int_t ii=0;ii<nbre;ii+=1){
				z1 = zfra-ii;
				tz1[ii]	=	z1;
				tz2[ii]	=	zfra-z1;
			}
			init=kTRUE;		
		}
		else {
			//return;
			ResetVars();
		}
	}
}
Beispiel #6
0
Double_t THSEventsPDF::evaluate() const 
{ 
  if(!fHist) return 1;//needed in case pdf evalualed before model loaded
  //   Double_t arg=x-offset;
  Double_t arg=(x-fMean)*scale+fMean;
  
  // Double_t arg=(x)*scale;
  arg=arg-offset;
  fx_off->setVal(arg);
  falpha->setVal(Double_t(alpha));
  // return  fHist->weight(RooArgSet(*fx_off,*falpha),1,kTRUE)*TMath::Gaus(offset,0,(offset.max()-offset.min())*0.2); //Guassian prior with width  1/5*range 
  return  fHist->weight(RooArgSet(*fx_off,*falpha),1,kTRUE);//*TMath::Gaus(scale,1.,1);
} 
Beispiel #7
0
   void plot_logo( Float_t v_scale = 1.0, Float_t skew = 1.0 )
   {

      TImage *img = findImage("tmva_logo.gif");
      if (!img) {
         cout << "+++ Could not open image tmva_logo.gif" << endl;
         return;
      }
      
      img->SetConstRatio(kFALSE);
      UInt_t h_ = img->GetHeight();
      UInt_t w_ = img->GetWidth();

      Float_t r = w_/h_;
      gPad->Update();
      Float_t rpad = Double_t(gPad->VtoAbsPixel(0) - gPad->VtoAbsPixel(1))/(gPad->UtoAbsPixel(1) - gPad->UtoAbsPixel(0));
      r *= rpad;

      Float_t d = 0.055;
      // absolute coordinates
      Float_t x1R = 1 - gStyle->GetPadRightMargin(); 
      Float_t y1B = 1 - gStyle->GetPadTopMargin()+.01; // we like the logo to sit a bit above the histo 

      Float_t x1L = x1R - d*r/skew;
      Float_t y1T = y1B + d*v_scale*skew;
      if (y1T>0.99) y1T = 0.99;

      TPad *p1 = new TPad("imgpad", "imgpad", x1L, y1B, x1R, y1T );
      p1->SetRightMargin(0);
      p1->SetBottomMargin(0);
      p1->SetLeftMargin(0);
      p1->SetTopMargin(0);
      p1->Draw();

      Int_t xSizeInPixel = p1->UtoAbsPixel(1) - p1->UtoAbsPixel(0);
      Int_t ySizeInPixel = p1->VtoAbsPixel(0) - p1->VtoAbsPixel(1);
      if (xSizeInPixel<=25 || ySizeInPixel<=25) {
         delete p1;
         return; // ROOT doesn't draw smaller than this
      }

      p1->cd();
      img->Draw();
   } 
Beispiel #8
0
//-------------------------
TH1* KVRandomizor::FillHisto(Int_t ntimes)
//-------------------------
{
   fNtest = 0;
   TH1* h1 = 0;
   if (fNd == 1) {
      h1 = FillHisto1D(ntimes);
   }
   else if (fNd == 2) {
      h1 = FillHisto2D(ntimes);
   }
   else if (fNd == 3) {
      h1 = FillHisto3D(ntimes);
   }
   else {
      Info("FillHisto", "method implemented for dimansion <= 3\nDo nothing ...");
      return h1;
   }
   Info("FillHisto", "stat=%d in %d tentatives => %lf", ntimes, fNtest, Double_t(ntimes) / fNtest);

   return h1;
}
Beispiel #9
0
//----------------------------------------------
KVCouple::KVCouple(Int_t zf,Int_t zsup){

	//printf("zf=%d zmax=%d\n",zf,zsup);
	zfra = zf;
	zmax = zsup;

	Int_t div=2;

	zlim = zfra/div;
	Double_t zmoy = zfra/Double_t(div);
	Double_t diff = zmoy-zlim;
	Int_t sup = TMath::Nint(diff*div);
	if (sup>=1){
		zlim+=1;
	}
	Int_t zref = 0;
	( (zfra>=zmax) ? zref=zmax : zref=zfra );

	nbre = zref-zlim+1;
	if (nbre>0){
		tz1 = new Int_t[nbre];
		tz2 = new Int_t[nbre];
		Int_t z1=0;
		for (Int_t ii=0;ii<nbre;ii+=1){
			z1 = zref-ii;
			tz1[ii]	=	z1;
			tz2[ii]	=	zfra-z1;
			//printf("      %d    %d %d\n",ii,z1,zfra-z1);
		}
		init=kTRUE;		
	}
	else {
		//return;
		ResetVars();
	}
		
}
Beispiel #10
0
//_________________________________________________________________________________
void ProcessTRDRunQA(TString qaFile, Int_t runNumber, TString dataType, 
		     Int_t year, TString period, TString pass, 
		     TString ocdbStorage) {
  //
  // Process run level QA
  // Create standard QA plots and trending tree in the current directory
  const Char_t *friendsOpt="PID DET RES";
  
  //gStyle->SetTitleX(gStyle->GetPadLeftMargin());
	gStyle->SetGridColor(kBlack);
	gStyle->SetGridStyle(3);
	gStyle->SetGridWidth(1);

  // Load needed libraries
  gSystem->SetIncludePath("-I$ROOTSYS/include -I$ALICE_ROOT/include -I$ALICE_PHYSICS/include -I$ALICE_ROOT/ITS -I$ALICE_ROOT -I$ALICE_PHYSICS -I$ALICE_ROOT/TRD");
  gSystem->Load("libSTEERBase");
  gSystem->Load("libSTAT");
  gSystem->Load("libANALYSIS");
  gSystem->Load("libANALYSISalice");
  gSystem->Load("libTender");
  gSystem->Load("libTenderSupplies");
  gSystem->Load("libCORRFW");
  gSystem->Load("libPWGPP");
  
  // Initialize a tree streamer
  TTreeSRedirector *treeStreamer = new TTreeSRedirector("trending.root","RECREATE");
  (*treeStreamer)<< "trending"
          << "run=" << runNumber;
  
  // connect to grid if its the case
  if(qaFile.Contains("alien://") || ocdbStorage.Contains("alien://") || ocdbStorage[0]=='\0')
    TGrid::Connect("alien://");
  
  // trending values from the ESD task ------------------------------------------------
  gROOT->LoadMacro("$ALICE_PHYSICS/PWGPP/TRD/macros/makeResults.C");
  Double_t esdTrendValues[100]; 
  for(Int_t i=0;i<100;i++) esdTrendValues[i]=0.0;
  makeSummaryESD(qaFile.Data(), esdTrendValues, 1);
  const Int_t kNESDtrends = 24;
  const TString kESDTrendNames[kNESDtrends] = {
    "TPCTRDmatchEffPosAll","TPCTRDmatchEffPosAllErr",
    "TPCTRDmatchEffNegAll","TPCTRDmatchEffNegAllErr",					      
    "TRDTOFmatchEffPosAll","TRDTOFmatchEffPosAllErr",					      
    "TRDTOFmatchEffNegAll","TRDTOFmatchEffNegAllErr",						     
    "AvTRDtrkltsPerTrackAll", "AvTRDtrkltsPerTrackAllErr",						      
    "AvNclsPerTrackAll", "AvNclsPerTrackAllErr",						      
    "PHplateauHeight", "PHplateauHeightErr",						
    "PHplateauSlope", "PHplateauSlopeErr",						
    "QtotLandauMPV1GeVAll", "QtotLandauWidth1GeVAll",
    "PHplateauHeightAbsolute", "PHplateauHeightErrAbsolute",
    "PHplateauSlopeAbsolute", "PHplateauSlopeErrAbsolute",						
    "QtotLandauMPV1GeVAllAbsolute", "QtotLandauWidth1GeVAllAbsolute"
  };
  for(Int_t i=0; i<kNESDtrends; ++i)
    (*treeStreamer)<< "trending" << Form("%s=",kESDTrendNames[i].Data()) << esdTrendValues[i];
  
  // process the QA output from the other tasks----------------------------------------
  if(dataType.Contains("sim"))
    makeResults(friendsOpt, qaFile.Data());
  else  
    makeResults(Form("NOMC %s", friendsOpt), qaFile.Data());
  
  TFile *trendFile = TFile::Open("TRD.Trend.root","READ");
  if(!trendFile || !trendFile->IsOpen() ){
    Warning("ProcessTRDRunQA.C", "Couldn't open the TRD.Trend.root file.");
    if(trendFile) delete trendFile; trendFile=0;
  }
  TFile *trendDB = TFile::Open("$ALICE_PHYSICS/PWGPP/TRD/data/TRD.Trend.root","READ");
  if(!trendDB || !trendDB->IsOpen() ){
    Error("ProcessTRDRunQA.C", "Couldn't open the Trending DB !");
    if(trendDB) delete trendDB; trendDB=0;
  }
  
  if(trendDB){
    TKey *tk(NULL); AliTRDtrendValue *tv(NULL); Int_t itv(0);
    const Int_t ntrends(5000);
    Double_t trendValues[ntrends]={0.0};
    TIterator *it(trendDB->GetListOfKeys()->MakeIterator());
    while((tk = (TKey*)it->Next()) && itv < ntrends){
      trendValues[itv] = -999.;
      if(trendFile && (tv = (AliTRDtrendValue*)trendFile->Get(tk->GetName()))){ 
        trendValues[itv] = tv->GetVal();
        printf("Found trend %03d \"%s\" %f\n", itv, tk->GetName(), trendValues[itv]);
      }
      (*treeStreamer)<< "trending" << Form("%s=", tk->GetName()) << trendValues[itv];
      itv++;
    }
  }
  
  // get OCDB information---------------------------------------------------------------
  // switch off grid infos to reduce output and logfilesize                                               
  AliLog::SetGlobalLogLevel(AliLog::kFatal);
  AliCDBManager* man=AliCDBManager::Instance();
  if(ocdbStorage[0]=='\0')
    man->SetDefaultStorage(Form("alien://folder=/alice/data/%d/OCDB/", year));
  else
    man->SetDefaultStorage(ocdbStorage.Data());
  man->SetRun(runNumber);
  
  AliCDBEntry* entryExB = 0x0;
  AliCDBEntry* entryGainFactor = 0x0;
  AliCDBEntry* entryT0 = 0x0;
  AliCDBEntry* entryVdrift = 0x0;
  entryExB = man->Get("TRD/Calib/ChamberExB");
  entryGainFactor = man->Get("TRD/Calib/ChamberGainFactor");
  entryT0 = man->Get("TRD/Calib/ChamberT0");
  entryVdrift = man->Get("TRD/Calib/ChamberVdrift");
  AliTRDCalDet *caldetExB=0x0;
  AliTRDCalDet *caldetGainFactor=0x0;
  AliTRDCalDet *caldetT0=0x0;
  AliTRDCalDet *caldetVdrift=0x0;
  if(entryExB)        caldetExB        = (AliTRDCalDet*)entryExB->GetObject();
  if(entryGainFactor) caldetGainFactor = (AliTRDCalDet*)entryGainFactor->GetObject();
  if(entryT0)         caldetT0         = (AliTRDCalDet*)entryT0->GetObject();
  if(entryVdrift)     caldetVdrift     = (AliTRDCalDet*)entryVdrift->GetObject();
  // get the values
  Double_t meanExB        = (caldetExB ? caldetExB->CalcMean(1) : 0.0);
  Double_t rmsExB         = (caldetExB ? caldetExB->CalcRMS(1) : 0.0);
  Double_t meanGainFactor = (caldetGainFactor ? caldetGainFactor->CalcMean(1) : 0.0);
  Double_t rmsGainFactor  = (caldetGainFactor ? caldetGainFactor->CalcRMS(1) : 0.0);
  Double_t meanT0         = (caldetT0 ? caldetT0->CalcMean(1) : 0.0);
  Double_t rmsT0          = (caldetT0 ? caldetT0->CalcRMS(1) : 0.0);
  Double_t meanVdrift     = (caldetVdrift ? caldetVdrift->CalcMean(1) : 0.0);
  Double_t rmsVdrift      = (caldetVdrift ? caldetVdrift->CalcRMS(1) : 0.0);
  (*treeStreamer)<< "trending"
                 << "meanExB=" << meanExB
                 << "rmsExB=" << rmsExB
                 << "meanGainFactor=" << meanGainFactor
                 << "rmsGainFactor=" << rmsGainFactor
                 << "meanT0=" << meanT0
                 << "rmsT0=" << rmsT0
                 << "meanVdrift=" << meanVdrift
                 << "rmsVdrift=" << rmsVdrift;
  
  // Get the beam luminosity
  AliCDBEntry *entryLHCData = man->Get("GRP/GRP/LHCData");		 
  AliLHCData *lhcData = (entryLHCData ? (AliLHCData*)entryLHCData->GetObject() : 0x0);
  Double_t beamIntensityA=0.0;
  Double_t beamIntensityC=0.0;
  if(lhcData) {
    Int_t nLumiMeasA=lhcData->GetNLuminosityTotal(0); Int_t nA=0;
    Int_t nLumiMeasC=lhcData->GetNLuminosityTotal(1); Int_t nC=0;
    // Sum up the measurements
    AliLHCDipValF *dipVal0,*dipVal1;
    for(Int_t iLumiMeas=0;iLumiMeas<nLumiMeasA;iLumiMeas++){
      dipVal0 = lhcData->GetLuminosityTotal(0,iLumiMeas);
      if(dipVal0) {
        beamIntensityA += dipVal0->GetValue();
        ++nA;
      }
    }
    if(nA) beamIntensityA /= Double_t(nA);
    for(Int_t iLumiMeas=0;iLumiMeas<nLumiMeasC;iLumiMeas++){
      dipVal1 = lhcData->GetLuminosityTotal(1,iLumiMeas);
      if(dipVal1) {
        beamIntensityC += dipVal1->GetValue();
        ++nC;
      }
    }
    if(nC) beamIntensityC /= Double_t(nC);
  }
  (*treeStreamer)<< "trending"
                 << "beamIntensityA=" << beamIntensityA
                 << "beamIntensityC=" << beamIntensityC;
                 
  // Get the magnetic field polarity
  Double_t Bfield=-2.;
  AliGRPManager grpManager;
  if(grpManager.ReadGRPEntry() && grpManager.SetMagField()){
    AliMagF *f=TGeoGlobalMagField::Instance()->GetField();
    Bfield=f->Factor();
  }                  
  (*treeStreamer)<< "trending"
                 << "Bfield=" << Bfield;
		 
  (*treeStreamer)<< "trending"
                 << "\n";
  delete treeStreamer;		 
}
Beispiel #11
0
Double_t g2(Double_t *x, Double_t *par) {
   Double_t r1 = Double_t((x[0]-par[1])/par[2]);
   Double_t r2 = Double_t((x[1]-par[3])/par[4]);
   return par[0]*TMath::Exp(-0.5*(r1*r1+r2*r2));
}
Beispiel #12
0
checkFieldMap()
{

  // Choose field map
  TString fieldName = "field_v12b";
  TString psFile = "check." + fieldName + ".ps";
  Double_t fzref1 =   0.;        // Origin plane
  Double_t fzref2 = 170.;        // RICH entrance
  Double_t fzref3 = 180.;        // RICH PM
  // ---> Regions of interest for the field
  Double_t fxmin =  -200.;    // along x axis
  Double_t fxmax =   200.;
  Double_t fymin =  -200.;    // along y axis
  Double_t fymax =   200.;
  Double_t fzmin =  -300.;    // along z axis
  Double_t fzmax =   300.;
  // ---> Target location
  Double_t targX = 0.;
  Double_t targY = 0.;
  Double_t targZ = 0.;

    // -------  Get magnetic field  -----------------------------------------
  CbmFieldMap* field = NULL;
  if ( fieldName == "field_v12b" ) 
    field = new CbmFieldMapSym3(fieldName.Data());
  else if ( fieldName == "field_v12a" )
    field = new CbmFieldMapSym2(fieldName.Data());
  else {
    cout << "=====> ERROR: Field map " << fieldName << " unknown!" << endl;
    exit;
  }
  field->Init();
  field->Print();
  Int_t type = field->GetType();
  if ( type >=1 && type <= 3) 
    const char* mapFile = field->GetFileName();
  // ----------------------------------------------------------------------



  // -------  Create graphs and histograms  -------------------------------
  Int_t fnx = TMath::Nint( (fxmax-fxmin) * 3. );
  Int_t fny = TMath::Nint( (fymax-fymin) * 3. );
  Int_t fnz = TMath::Nint( (fzmax-fzmin) * 3. );
  Int_t fmx = TMath::Nint( (fxmax-fxmin) * 3. / 10. );
  Int_t fmy = TMath::Nint( (fymax-fymin) * 3. / 10. );
  TGraph hBy1(fnz+1);
  TGraph hBy2(fnz+1);
  TGraph hBt1(fnz+1);
  TGraph hBt2(fnz+1);
  TH2F hB1("hB1", "B at z_{target}", 
	   fmx, fxmin, fxmax, fmy, fymin, fymax);
  TH2F hB2("hB1", "B at RICH entrance", 
	   fmx, fxmin, fxmax, fmy, fymin, fymax);
  TH2F hB3("hB2", "B at RICH PM",       
	   fmx, fxmin, fxmax, fmy, fymin, fymax);
  // ----------------------------------------------------------------------



  // -------  Get field and fill graphs and histograms  -------------------
  cout << endl;
  cout << "=====>  Filling histograms..." << endl;
  Double_t x, y, z;  Double_t bx, by, bz, bt, b;
  Double_t fdx = (fxmax-fxmin) / Double_t(fnx);
  Double_t fdy = (fymax-fymin) / Double_t(fny);
  Double_t fdz = (fzmax-fzmin) / Double_t(fnz);


  // ---> Loop over z axis (x=y=0)
  cout << "                           ... z axis 1" << endl;
  x = y = 0.;
  for (Int_t iz=0; iz<=fnz; iz++) {
    z = fzmin + Double_t(iz) * fdz;
    bx = field->GetBx(x,y,z) / 10.;
    by = field->GetBy(x,y,z) / 10.;
    bz = field->GetBz(x,y,z) / 10.;
    bt = TMath::Sqrt(bx*bx + bz*bz);
    hBy1.SetPoint(iz, z, by);
    hBt1.SetPoint(iz, z, bt);
  }

  // ---> Loop over z axis (x=y=20)
  cout << "                           ... z axis 2" << endl;
  x = y = 20.;
  for (Int_t iz=0; iz<=fnz; iz++) {
    z = fzmin + Double_t(iz) * fdz;
    bx = field->GetBx(x,y,z) / 10.;
    by = field->GetBy(x,y,z) / 10.;
    bz = field->GetBz(x,y,z) / 10.;
    bt = TMath::Sqrt(bx*bx + bz*bz);
    hBy2.SetPoint(iz, z, by);
    hBt2.SetPoint(iz, z, bt);
  }

  // ---> Double loop over z (target) plane
  cout << "                           ... target plane" << endl;
  fdx = (fxmax-fxmin) / Double_t(fmx);
  fdy = (fymax-fymin) / Double_t(fmy);
  z = fzref1;
  for (Int_t ix=0; ix<fmx; ix++) {
    x = fxmin + (Double_t(ix)+0.5) * fdx;
    for (Int_t iy=0; iy<fmy; iy++) {
      y = fymin + (Double_t(iy)+0.5) * fdy;
      bx = field->GetBx(x,y,z) / 10.;
      by = field->GetBy(x,y,z) / 10.;
      bz = field->GetBz(x,y,z) / 10.;
      b = TMath::Sqrt(bx*bx + by*by + bz*bz);
      hB1.SetBinContent(ix, iy, b);
    }
  }

  // ---> Double loop over z (RICH entrance) plane
  cout << "                           ... RICH entrance plane" << endl;
  fdx = (fxmax-fxmin) / Double_t(fmx);
  fdy = (fymax-fymin) / Double_t(fmy);
  z = fzref2;
  for (Int_t ix=0; ix<fmx; ix++) {
    x = fxmin + (Double_t(ix)+0.5) * fdx;
    for (Int_t iy=0; iy<fmy; iy++) {
      y = fymin + (Double_t(iy)+0.5) * fdy;
      bx = field->GetBx(x,y,z) / 10.;
      by = field->GetBy(x,y,z) / 10.;
      bz = field->GetBz(x,y,z) / 10.;
      b = TMath::Sqrt(bx*bx + by*by + bz*bz);
      hB2.SetBinContent(ix, iy, b);
    }
  }

  // ---> Double loop over z (RICH PM) plane
  cout << "                           ... RICH PM plane" << endl;
  fdx = (fxmax-fxmin) / Double_t(fmx);
  fdy = (fymax-fymin) / Double_t(fmy);
  z = fzref3;
  for (Int_t ix=0; ix<fmx; ix++) {
    x = fxmin + (Double_t(ix)+0.5) * fdx;
    for (Int_t iy=0; iy<fmy; iy++) {
      y = fymin + (Double_t(iy)+0.5) * fdy;
      bx = field->GetBx(x,y,z) / 10.;
      by = field->GetBy(x,y,z) / 10.;
      bz = field->GetBz(x,y,z) / 10.;
      b = TMath::Sqrt(bx*bx + by*by + bz*bz);
      hB3.SetBinContent(ix, iy, b);
    }
  }
  // ----------------------------------------------------------------------



  // --------   Calculate field integral along z axis   -------------------
  Double_t zint1 = -400.;
  Double_t zint2 =  400.;
  Int_t nz = Int_t(zint2-zint1);
  Double_t bint = 0;
  z = zint1 - 1.;
  for (Int_t iz=0; iz<=nz; iz++) {
    z += 1;
    by = field->GetBy(targX, targY, z) / 10.;
    bint += by * 0.01;
  }
  // ----------------------------------------------------------------------



  // -------  Draw graphs and histogram   ---------------------------------
  cout << endl << "=====>  Drawing..." << endl;
  gROOT->SetStyle("Plain");
  gStyle->SetOptStat(0000);
  gStyle->SetPalette(1,0);
  gStyle->SetTitleW(0.5);
  gStyle->SetTitleAlign(13);
  gStyle->SetTitleBorderSize(0.);
  gStyle->SetTitleOffset(2.,"y");
  gStyle->SetOptDate(2);
  gStyle->GetAttDate()->SetTextSize(0.02);

  TPostScript* ps = new TPostScript(psFile, -111);
  ps->Range(20,30);

  TCanvas* c1 = new TCanvas("c1", "canvas", 768, 1152);
  TPad* master = new TPad("master","", 0.10, 0.05, 0.95, 0.95);
  master->Draw();
  master->cd();

  TPad* padinf = new TPad("padinf", "", 0.12, 0.80, 0.88, 0.90);
  TPad* pad1   = new TPad("pad1",   "", 0.05, 0.60, 0.48, 0.78);
  TPad* pad2   = new TPad("pad2",   "", 0.52, 0.60, 0.95, 0.78);
  TPad* pad3   = new TPad("pad3",   "", 0.05, 0.41, 0.48, 0.59);
  TPad* pad4   = new TPad("pad4",   "", 0.52, 0.41, 0.95, 0.59);
  TPad* pad5   = new TPad("pad5",   "", 0.30, 0.22, 0.70, 0.40);
  TPad* pad6   = new TPad("pad6",   "", 0.10, 0.02, 0.47, 0.20);
  TPad* pad7   = new TPad("pad7",   "", 0.53, 0.02, 0.90, 0.20);

  padinf->Draw();
  pad1->Draw();
  pad2->Draw();
  pad3->Draw();
  pad4->Draw();
  pad5->Draw();
  pad6->Draw();
  pad7->Draw();

  Double_t max, min;

  pad1->cd();
  gPad->SetFillColor(10);
  gPad->SetLeftMargin(0.15);
  hBy1.SetLineColor(4);
  hBy1.SetLineWidth(2);
  hBy1.SetTitle("x = y = 0");
  hBy1.GetXaxis()->SetTitle("z [cm]");
  hBy1.GetYaxis()->SetTitle("B_{y} [T]");
  hBy1.Draw("AC");
  max = hBy1.GetHistogram()->GetMaximum();
  min = hBy1.GetHistogram()->GetMinimum();
  TLine l1(targZ, min, targZ, max);
  l1.Draw();

  pad2->cd();
  gPad->SetFillColor(10);
  gPad->SetLeftMargin(0.15);
  hBy2.SetLineColor(4);
  hBy2.SetLineWidth(2);
  hBy2.SetTitle("x = y = 20 cm");
  hBy2.GetXaxis()->SetTitle("z [cm]");
  hBy2.GetYaxis()->SetTitle("B_{y} [T]");
  hBy2.Draw("AC");
  max = hBy2.GetHistogram()->GetMaximum();
  min = hBy2.GetHistogram()->GetMinimum();
  TLine l2(targZ, min, targZ, max);
  l2.Draw();

  pad3->cd();
  gPad->SetFillColor(10);
  gPad->SetLeftMargin(0.15);
  hBt1.SetLineColor(2);
  hBt1.SetLineWidth(2);
  hBt1.SetTitle("x = y = 0");
  hBt1.GetXaxis()->SetTitle("z [cm]");
  hBt1.GetYaxis()->SetTitle("B_{xz} [T]");
  hBt1.Draw("AC");
  max = hBt1.GetHistogram()->GetMaximum();
  min = hBt1.GetHistogram()->GetMinimum();
  TLine l3(targZ, min, targZ, max);
  l3.Draw();

  pad4->cd();
  gPad->SetFillColor(10);
  gPad->SetLeftMargin(0.15);
  hBt2.SetLineColor(2);
  hBt2.SetLineWidth(2);
  hBt2.SetTitle("x = y = 20 cm");
  hBt2.GetXaxis()->SetTitle("z [cm]");
  hBt2.GetYaxis()->SetTitle("B_{xz} [T]");
  hBt2.Draw("AC");
  max = hBt2.GetHistogram()->GetMaximum();
  min = hBt2.GetHistogram()->GetMinimum();
  TLine l4(targZ, min, targZ, max);
  l4.Draw();

  pad5->cd();
  gPad->SetLeftMargin(0.15);
  gPad->SetFillColor(10);
  hB1.UseCurrentStyle();
  hB1.GetXaxis()->SetTitle("x [cm]");
  hB1.GetYaxis()->SetTitle("y [cm]");
  char t[100];
  sprintf(t,"B [T] at z= 0",fzref1);
  hB1.SetTitle(t);
  hB1.Draw("COLZ");

  pad6->cd();
  gPad->SetFillColor(10);
  gPad->SetLeftMargin(0.15);
  hB2.UseCurrentStyle();
  hB2.GetXaxis()->SetTitle("x [cm]");
  hB2.GetYaxis()->SetTitle("y [cm]");
  char t[100];
  sprintf(t,"B [T] at RICH entrance (z=%8.2f cm)",fzref2);
  hB2->SetTitle(t);
  hB2.Draw("COLZ");

  pad7->cd();
  gPad->SetFillColor(10);
  gPad->SetLeftMargin(0.15);
  hB3.UseCurrentStyle();
  hB3.GetXaxis()->SetTitle("x [cm]");
  hB3.GetYaxis()->SetTitle("y [cm]");
  sprintf(t,"B [T] at RICH PM plane (z=%8.2f cm)",fzref3);
  hB3.SetTitle(t);
  hB3.Draw("COLZ");


  TString fieldType = "";
  if      ( type == 0 ) fieldType = "Constant field";
  else if ( type == 1 ) fieldType = "Field map";
  else if ( type == 2 ) fieldType = "Field Map Sym2";
  else if ( type == 3 ) fieldType = "Field Map Sym3";


  char t1[300];
  padinf->cd();
  TPaveText info(0.1,0.1,0.9,0.9);
  info.SetFillColor(10);
  info.SetBorderSize(0);
  info.SetTextAlign(2);
  sprintf(t1,"Field name: %s, type: %s",field->GetName(),fieldType.Data());
  info.AddText(0.05, 0.9, t1);
  Double_t bx = field->GetBx(0.,0.,0.) / 10.;
  Double_t by = field->GetBy(0.,0.,0.) / 10.;
  Double_t bz = field->GetBz(0.,0.,0.) / 10.;
  sprintf(t1,"Field at origin is (%7.4f, %7.4f, %7.4f) T",bx,by,bz);
  cout << t1 << endl;
  info.AddText(0.05, 0.7, t1);
  if ( type >= 1 && type <=3 ) {
    sprintf(t1, "Map file: %s",mapFile);
    cout << t1 << endl;
    info.AddText(0.05, 0.5, t1);
    Double_t xp = field->GetPositionX();
    Double_t yp = field->GetPositionY();
    Double_t zp = field->GetPositionZ();
    sprintf(t1,"Centre position (%.2f, %.2f, %.2f) cm",xp,yp,zp);
    info->AddText(0.05, 0.3, t1);
    Double_t scale = field->GetScale();
    sprintf(t1,"Scaling factor %.2f, Field integral along z = %.4f Tm",
	    scale,bint);
    info->AddText(0.05, 0.1, t1);
  }
  info.Draw();

  master->cd();
  sprintf(t1,"Field check for %s", field->GetName());
  TPaveLabel label(0.20, 0.92, 0.88, 0.97, t1);
  label->Draw();
  
  /*
  c1->cd();
  const char* wrkdir = getenv("VMCWORKDIR");
  TString logo = TString(wrkdir) + "/input/cbmlogo.gif";
  TImage* cbm = TImage::Open(logo);
  TPad* padimg = new TPad("padimg", "", 0.05, 0.80, 0.20, 0.95);
  padimg->Draw();
  padimg->cd();
  cbm->Draw();
  */
  


  ps->Close();
  
}
Beispiel #13
0
void selectAntiWm(const TString conf="wm.conf", // input file
              const TString outputDir="."       // output directory
) {
  gBenchmark->Start("selectAntiWm");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 

  const Double_t PT_CUT    = 25;
  const Double_t ETA_CUT   = 2.4;
  const Double_t MUON_MASS = 0.105658369;

  const Double_t VETO_PT   = 10;
  const Double_t VETO_ETA  = 2.4;

  const Int_t BOSON_ID  = 24;
  const Int_t LEPTON_ID = 13;

  // load trigger menu
  const baconhep::TTrigger triggerMenu("../../BaconAna/DataFormats/data/HLT_50nsGRun");

  // load pileup reweighting file
  TFile *f_rw = TFile::Open("../Tools/pileup_weights_2015B.root", "read");
  TH1D *h_rw = (TH1D*) f_rw->Get("npv_rw");

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  vector<TString>  snamev;      // sample name (for output files)  
  vector<CSample*> samplev;     // data/MC samples

  //
  // parse .conf file
  //
  confParse(conf, snamev, samplev);
  const Bool_t hasData = (samplev[0]->fnamev.size()>0);

  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  const TString ntupDir = outputDir + TString("/ntuples");
  gSystem->mkdir(ntupDir,kTRUE);
  
  //
  // Declare output ntuple variables
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  npv, npu;
  UInt_t  id_1, id_2;
  Double_t x_1, x_2, xPDF_1, xPDF_2;
  Double_t scalePDF, weightPDF;
  TLorentzVector *genV=0, *genLep=0;
  Float_t genVPt, genVPhi, genVy, genVMass;
  Float_t genLepPt, genLepPhi;
  Float_t scale1fb, puWeight;
  Float_t met, metPhi, sumEt, mt, u1, u2;
  Float_t tkMet, tkMetPhi, tkSumEt, tkMt, tkU1, tkU2;
  Float_t mvaMet, mvaMetPhi, mvaSumEt, mvaMt, mvaU1, mvaU2;
  Int_t   q;
  TLorentzVector *lep=0;
  ///// muon specific /////
  Float_t trkIso, emIso, hadIso;
  Float_t pfChIso, pfGamIso, pfNeuIso, pfCombIso;
  Float_t d0, dz;
  Float_t muNchi2;
  UInt_t nPixHits, nTkLayers, nValidHits, nMatch, typeBits;
  
  // Data structures to store info from TTrees
  baconhep::TEventInfo *info  = new baconhep::TEventInfo();
  baconhep::TGenEventInfo *gen  = new baconhep::TGenEventInfo();
  TClonesArray *genPartArr = new TClonesArray("baconhep::TGenParticle");
  TClonesArray *muonArr    = new TClonesArray("baconhep::TMuon");
  TClonesArray *vertexArr  = new TClonesArray("baconhep::TVertex");
  
  TFile *infile=0;
  TTree *eventTree=0;
  
  //
  // loop over samples
  //  
  for(UInt_t isam=0; isam<samplev.size(); isam++) {
    
    // Assume data sample is first sample in .conf file
    // If sample is empty (i.e. contains no ntuple files), skip to next sample
    Bool_t isData=kFALSE;
    if(isam==0 && !hasData) continue;
    else if (isam==0) isData=kTRUE;
    
    // Assume signal sample is given name "wm"
    Bool_t isSignal = (snamev[isam].CompareTo("wm",TString::kIgnoreCase)==0);
    // flag to reject W->mnu events when selecting wrong-flavor background events
    Bool_t isWrongFlavor = (snamev[isam].CompareTo("wx",TString::kIgnoreCase)==0);  
    
    CSample* samp = samplev[isam];
  
    //
    // Set up output ntuple
    //
    TString outfilename = ntupDir + TString("/") + snamev[isam] + TString("_select.root");
    TFile *outFile = new TFile(outfilename,"RECREATE"); 
    TTree *outTree = new TTree("Events","Events");

    outTree->Branch("runNum",     &runNum,     "runNum/i");     // event run number
    outTree->Branch("lumiSec",    &lumiSec,    "lumiSec/i");    // event lumi section
    outTree->Branch("evtNum",     &evtNum,     "evtNum/i");     // event number
    outTree->Branch("npv",        &npv,        "npv/i");        // number of primary vertices
    outTree->Branch("npu",        &npu,        "npu/i");        // number of in-time PU events (MC)
    outTree->Branch("id_1",       &id_1,       "id_1/i");       // PDF info -- parton ID for parton 1
    outTree->Branch("id_2",       &id_2,       "id_2/i");       // PDF info -- parton ID for parton 2
    outTree->Branch("x_1",        &x_1,        "x_1/d");        // PDF info -- x for parton 1
    outTree->Branch("x_2",        &x_2,        "x_2/d");        // PDF info -- x for parton 2
    outTree->Branch("xPDF_1",     &xPDF_1,     "xPDF_1/d");     // PDF info -- x*F for parton 1
    outTree->Branch("xPDF_2",     &xPDF_2,     "xPDF_2/d");     // PDF info -- x*F for parton 2
    outTree->Branch("scalePDF",   &scalePDF,   "scalePDF/d");   // PDF info -- energy scale of parton interaction
    outTree->Branch("weightPDF",  &weightPDF,  "weightPDF/d");  // PDF info -- PDF weight
    outTree->Branch("genV",       "TLorentzVector", &genV);     // GEN boson 4-vector (signal MC)
    outTree->Branch("genLep",     "TLorentzVector", &genLep);   // GEN lepton 4-vector (signal MC)
    outTree->Branch("genVPt",     &genVPt,     "genVPt/F");     // GEN boson pT (signal MC)
    outTree->Branch("genVPhi",    &genVPhi,    "genVPhi/F");    // GEN boson phi (signal MC)
    outTree->Branch("genVy",      &genVy,      "genVy/F");      // GEN boson rapidity (signal MC)
    outTree->Branch("genVMass",   &genVMass,   "genVMass/F");   // GEN boson mass (signal MC)
    outTree->Branch("genLepPt",   &genLepPt,   "genLepPt/F");   // GEN lepton pT (signal MC)
    outTree->Branch("genLepPhi",  &genLepPhi,  "genLepPhi/F");  // GEN lepton phi (signal MC)
    outTree->Branch("scale1fb",   &scale1fb,   "scale1fb/F");   // event weight per 1/fb (MC)
    outTree->Branch("puWeight",   &puWeight,   "puWeight/F");    // scale factor for pileup reweighting (MC)
    outTree->Branch("met",        &met,        "met/F");        // MET
    outTree->Branch("metPhi",     &metPhi,     "metPhi/F");     // phi(MET)
    outTree->Branch("sumEt",      &sumEt,      "sumEt/F");      // Sum ET
    outTree->Branch("mt",         &mt,         "mt/F");         // transverse mass
    outTree->Branch("u1",         &u1,         "u1/F");         // parallel component of recoil
    outTree->Branch("u2",         &u2,         "u2/F");         // perpendicular component of recoil
    outTree->Branch("tkMet",      &tkMet,      "tkMet/F");      // MET (track MET)
    outTree->Branch("tkMetPhi",   &tkMetPhi,   "tkMetPhi/F");   // phi(MET) (track MET)
    outTree->Branch("tkSumEt",    &tkSumEt,    "tkSumEt/F");    // Sum ET (track MET)
    outTree->Branch("tkMt",       &tkMt,       "tkMt/F");       // transverse mass (track MET)
    outTree->Branch("tkU1",       &tkU1,       "tkU1/F");       // parallel component of recoil (track MET)
    outTree->Branch("tkU2",       &tkU2,       "tkU2/F");       // perpendicular component of recoil (track MET)
    outTree->Branch("mvaMet",     &mvaMet,     "mvaMet/F");     // MVA MET
    outTree->Branch("mvaMetPhi",  &mvaMetPhi,  "mvaMetPhi/F");  // phi(MVA MET)
    outTree->Branch("mvaSumEt",   &mvaSumEt,   "mvaSumEt/F");   // Sum ET (MVA MET)
    outTree->Branch("mvaMt",      &mvaMt,      "mvaMt/F");      // transverse mass (MVA MET)
    outTree->Branch("mvaU1",      &mvaU1,      "mvaU1/F");      // parallel component of recoil (mva MET)
    outTree->Branch("mvaU2",      &mvaU2,      "mvaU2/F");      // perpendicular component of recoil (mva MET)
    outTree->Branch("q",          &q,          "q/I");          // lepton charge
    outTree->Branch("lep",        "TLorentzVector", &lep);      // lepton 4-vector
    ///// muon specific /////
    outTree->Branch("trkIso",     &trkIso,     "trkIso/F");     // track isolation of lepton
    outTree->Branch("emIso",      &emIso,      "emIso/F");      // ECAL isolation of lepton
    outTree->Branch("hadIso",     &hadIso,     "hadIso/F");     // HCAL isolation of lepton
    outTree->Branch("pfChIso",    &pfChIso,    "pfChIso/F");    // PF charged hadron isolation of lepton
    outTree->Branch("pfGamIso",   &pfGamIso,   "pfGamIso/F");   // PF photon isolation of lepton
    outTree->Branch("pfNeuIso",   &pfNeuIso,   "pfNeuIso/F");   // PF neutral hadron isolation of lepton
    outTree->Branch("pfCombIso",  &pfCombIso,  "pfCombIso/F");  // PF combined isolation of lepton
    outTree->Branch("d0",         &d0,         "d0/F");         // transverse impact parameter of lepton
    outTree->Branch("dz",         &dz,         "dz/F");         // longitudinal impact parameter of lepton
    outTree->Branch("muNchi2",    &muNchi2,    "muNchi2/F");    // muon fit normalized chi^2 of lepton
    outTree->Branch("nPixHits",   &nPixHits,   "nPixHits/i");   // number of pixel hits of muon
    outTree->Branch("nTkLayers",  &nTkLayers,  "nTkLayers/i");  // number of tracker layers of muon
    outTree->Branch("nMatch",     &nMatch,     "nMatch/i");     // number of matched segments of muon	 
    outTree->Branch("nValidHits", &nValidHits, "nValidHits/i"); // number of valid muon hits of muon 
    outTree->Branch("typeBits",   &typeBits,   "typeBits/i");   // number of valid muon hits of muon 
    
    //
    // loop through files
    //
    const UInt_t nfiles = samp->fnamev.size();
    for(UInt_t ifile=0; ifile<nfiles; ifile++) {  

      // Read input file and get the TTrees
      cout << "Processing " << samp->fnamev[ifile] << " [xsec = " << samp->xsecv[ifile] << " pb] ... "; cout.flush();
      infile = TFile::Open(samp->fnamev[ifile]); 
      assert(infile);
      
      Bool_t hasJSON = kFALSE;
      baconhep::RunLumiRangeMap rlrm;
      if(samp->jsonv[ifile].CompareTo("NONE")!=0) { 
	hasJSON = kTRUE;
	rlrm.addJSONFile(samp->jsonv[ifile].Data()); 
      }

      eventTree = (TTree*)infile->Get("Events");
      assert(eventTree);
      eventTree->SetBranchAddress("Info", &info);    TBranch *infoBr = eventTree->GetBranch("Info");
      eventTree->SetBranchAddress("Muon", &muonArr); TBranch *muonBr = eventTree->GetBranch("Muon");
      eventTree->SetBranchAddress("PV",   &vertexArr); TBranch *vertexBr = eventTree->GetBranch("PV");
      Bool_t hasGen = eventTree->GetBranchStatus("GenEvtInfo");
      TBranch *genBr=0, *genPartBr=0;
      if(hasGen) {
        eventTree->SetBranchAddress("GenEvtInfo", &gen); genBr = eventTree->GetBranch("GenEvtInfo");
        eventTree->SetBranchAddress("GenParticle",&genPartArr); genPartBr = eventTree->GetBranch("GenParticle");
      }
    
      // Compute MC event weight per 1/fb
      const Double_t xsec = samp->xsecv[ifile];
      Double_t totalWeight=0;

      if (hasGen) {
	TH1D *hall = new TH1D("hall", "", 1,0,1);
	eventTree->Draw("0.5>>hall", "GenEvtInfo->weight");
	totalWeight=hall->Integral();
	delete hall;
	hall=0;
      }

      //
      // loop over events
      //
      Double_t nsel=0, nselvar=0;
      for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
        infoBr->GetEntry(ientry);

	if(ientry%1000000==0) cout << "Processing event " << ientry << ". " << (double)ientry/(double)eventTree->GetEntries()*100 << " percent done with this file." << endl;

        Double_t weight=1;
        if(xsec>0 && totalWeight>0) weight = xsec/totalWeight;
	if(hasGen) {
          genPartArr->Clear();
          genBr->GetEntry(ientry);
          genPartBr->GetEntry(ientry);
	  weight*=gen->weight;
        }

        // veto w -> xv decays for signal and w -> mv for bacground samples (needed for inclusive WToLNu sample)
        if (isWrongFlavor && hasGen && fabs(toolbox::flavor(genPartArr, BOSON_ID))==LEPTON_ID) continue;
	else if (isSignal && hasGen && fabs(toolbox::flavor(genPartArr, BOSON_ID))!=LEPTON_ID) continue;
        
	// check for certified lumi (if applicable)
        baconhep::RunLumiRangeMap::RunLumiPairType rl(info->runNum, info->lumiSec);      
        if(hasJSON && !rlrm.hasRunLumi(rl)) continue;  

        // trigger requirement               
	if (!isMuonTrigger(triggerMenu, info->triggerBits)) continue;
      
        // good vertex requirement
        if(!(info->hasGoodPV)) continue;

        //
	// SELECTION PROCEDURE:
	//  (1) Look for 1 good muon matched to trigger
	//  (2) Reject event if another muon is present passing looser cuts
	//
	muonArr->Clear();
        muonBr->GetEntry(ientry);

	Int_t nLooseLep=0;
	const baconhep::TMuon *goodMuon=0;
	Bool_t passSel=kFALSE;

        for(Int_t i=0; i<muonArr->GetEntriesFast(); i++) {
          const baconhep::TMuon *mu = (baconhep::TMuon*)((*muonArr)[i]);

          if(fabs(mu->eta) > VETO_PT)  continue; // loose lepton |eta| cut
          if(mu->pt        < VETO_ETA) continue; // loose lepton pT cut
//          if(passMuonLooseID(mu)) nLooseLep++; // loose lepton selection
          if(nLooseLep>1) {  // extra lepton veto
            passSel=kFALSE;
            break;
          }
          
          if(fabs(mu->eta) > ETA_CUT)         continue; // lepton |eta| cut
          if(mu->pt < PT_CUT)                 continue; // lepton pT cut   
          if(!passAntiMuonID(mu))             continue; // lepton anti-selection
          if(!isMuonTriggerObj(triggerMenu, mu->hltMatchBits, kFALSE)) continue;
	  
	  passSel=kTRUE;
	  goodMuon = mu;
	}

	if(passSel) {	  
	  /******** We have a W candidate! HURRAY! ********/
	  nsel+=weight;
          nselvar+=weight*weight;
	  
	  TLorentzVector vLep; 
	  vLep.SetPtEtaPhiM(goodMuon->pt, goodMuon->eta, goodMuon->phi, MUON_MASS);

	  //
	  // Fill tree
	  //
	  runNum   = info->runNum;
	  lumiSec  = info->lumiSec;
	  evtNum   = info->evtNum;
	  
	  vertexArr->Clear();
	  vertexBr->GetEntry(ientry);

	  npv      = vertexArr->GetEntries();
	  npu	   = info->nPUmean;
	  genV      = new TLorentzVector(0,0,0,0);
          genLep    = new TLorentzVector(0,0,0,0);
	  genVPt    = -999;
          genVPhi   = -999;
          genVy     = -999;
          genVMass  = -999;
          u1        = -999;
          u2        = -999;
          tkU1      = -999;
          tkU2      = -999;
	  mvaU1     = -999;
          mvaU2     = -999;
          id_1      = -999;
          id_2      = -999;
          x_1       = -999;
          x_2       = -999;
          xPDF_1    = -999;
          xPDF_2    = -999;
          scalePDF  = -999;
          weightPDF = -999;

	  if(isSignal && hasGen) {
	    TLorentzVector *gvec=new TLorentzVector(0,0,0,0);
            TLorentzVector *glep1=new TLorentzVector(0,0,0,0);
            TLorentzVector *glep2=new TLorentzVector(0,0,0,0);
	    toolbox::fillGen(genPartArr, BOSON_ID, gvec, glep1, glep2,1);

            if (gvec && glep1) {
	      genV      = new TLorentzVector(0,0,0,0);
              genV->SetPtEtaPhiM(gvec->Pt(),gvec->Eta(),gvec->Phi(),gvec->M());
              genLep    = new TLorentzVector(0,0,0,0);
              genLep->SetPtEtaPhiM(glep1->Pt(),glep1->Eta(),glep1->Phi(),glep1->M());
              genVPt    = gvec->Pt();
              genVPhi   = gvec->Phi();
              genVy     = gvec->Rapidity();
              genVMass  = gvec->M();
              genLepPt  = glep1->Pt();
              genLepPhi = glep1->Phi();

	      TVector2 vWPt((genVPt)*cos(genVPhi),(genVPt)*sin(genVPhi));
	      TVector2 vLepPt(vLep.Px(),vLep.Py());
	      
	      TVector2 vMet((info->pfMETC)*cos(info->pfMETCphi), (info->pfMETC)*sin(info->pfMETCphi));
	      TVector2 vU = -1.0*(vMet+vLepPt);
	      u1 = ((vWPt.Px())*(vU.Px()) + (vWPt.Py())*(vU.Py()))/(genVPt);  // u1 = (pT . u)/|pT|
	      u2 = ((vWPt.Px())*(vU.Py()) - (vWPt.Py())*(vU.Px()))/(genVPt);  // u2 = (pT x u)/|pT|

	      TVector2 vTkMet((info->trkMET)*cos(info->trkMETphi), (info->trkMET)*sin(info->trkMETphi));
	      TVector2 vTkU = -1.0*(vTkMet+vLepPt);
	      tkU1 = ((vWPt.Px())*(vTkU.Px()) + (vWPt.Py())*(vTkU.Py()))/(genVPt);  // u1 = (pT . u)/|pT|
	      tkU2 = ((vWPt.Px())*(vTkU.Py()) - (vWPt.Py())*(vTkU.Px()))/(genVPt);  // u2 = (pT x u)/|pT|
	      
	      TVector2 vMvaMet((info->mvaMET)*cos(info->mvaMETphi), (info->mvaMET)*sin(info->mvaMETphi));
	      TVector2 vMvaU = -1.0*(vMvaMet+vLepPt);
	      mvaU1 = ((vWPt.Px())*(vMvaU.Px()) + (vWPt.Py())*(vMvaU.Py()))/(genVPt);  // u1 = (pT . u)/|pT|
	      mvaU2 = ((vWPt.Px())*(vMvaU.Py()) - (vWPt.Py())*(vMvaU.Px()))/(genVPt);  // u2 = (pT x u)/|pT|
          
            }
	    id_1      = gen->id_1;
            id_2      = gen->id_2;
            x_1       = gen->x_1;
            x_2       = gen->x_2;
            xPDF_1    = gen->xPDF_1;
            xPDF_2    = gen->xPDF_2;
            scalePDF  = gen->scalePDF;
            weightPDF = gen->weight;

	    delete gvec;
            delete glep1;
            delete glep2;
            gvec=0; glep1=0; glep2=0;
	  }
	  scale1fb = weight;
	  puWeight = h_rw->GetBinContent(info->nPUmean+1);
	  met	   = info->pfMETC;
	  metPhi   = info->pfMETCphi;
	  sumEt    = 0;
	  mt       = sqrt( 2.0 * (vLep.Pt()) * (info->pfMETC) * (1.0-cos(toolbox::deltaPhi(vLep.Phi(),info->pfMETCphi))) );
	  tkMet    = info->trkMET;
          tkMetPhi = info->trkMETphi;
          tkSumEt  = 0;
          tkMt     = sqrt( 2.0 * (vLep.Pt()) * (info->trkMET) * (1.0-cos(toolbox::deltaPhi(vLep.Phi(),info->trkMETphi))) );
	  mvaMet   = info->mvaMET;
          mvaMetPhi = info->mvaMETphi;
          mvaSumEt  = 0;
          mvaMt     = sqrt( 2.0 * (vLep.Pt()) * (info->mvaMET) * (1.0-cos(toolbox::deltaPhi(vLep.Phi(),info->mvaMETphi))) );
	  q        = goodMuon->q;
	  lep      = &vLep;
	  
	  ///// muon specific /////
	  trkIso     = goodMuon->trkIso;
          emIso      = goodMuon->ecalIso;
          hadIso     = goodMuon->hcalIso;
          pfChIso    = goodMuon->chHadIso;
          pfGamIso   = goodMuon->gammaIso;
          pfNeuIso   = goodMuon->neuHadIso;
          pfCombIso  = goodMuon->chHadIso + TMath::Max(goodMuon->neuHadIso + goodMuon->gammaIso -
						       0.5*(goodMuon->puIso),Double_t(0));
	  d0         = goodMuon->d0;
	  dz         = goodMuon->dz;
	  muNchi2    = goodMuon->muNchi2;
	  nPixHits   = goodMuon->nPixHits;
	  nTkLayers  = goodMuon->nTkLayers;
	  nMatch     = goodMuon->nMatchStn;
	  nValidHits = goodMuon->nValidHits;
	  typeBits   = goodMuon->typeBits;

	  outTree->Fill();
	  delete genV;
	  delete genLep;
	  genV=0, genLep=0, lep=0;
        }
      }
      delete infile;
      infile=0, eventTree=0;    

      cout << nsel  << " +/- " << sqrt(nselvar);
      if(isam!=0) cout << " per 1/fb";
      cout << endl;
    }
    outFile->Write();
    outFile->Close();
  }
  delete h_rw;
  delete f_rw;
  delete info;
  delete gen;
  delete genPartArr;
  delete muonArr;
  delete vertexArr;
      
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  cout << " W -> mu nu" << endl;
  cout << "  pT > " << PT_CUT << endl;
  cout << "  |eta| < " << ETA_CUT << endl;
  cout << endl;
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;  
      
  gBenchmark->Show("selectAntiWm"); 
}
Beispiel #14
0
void Eff3Liq(TH1F * hN=0){

  Double_t x[71]={0.0075000,
		  0.0250000,
		  0.0450000,
		  0.0650000,
		  0.0850000,
		  0.1050000,
		  0.1250000,
		  0.1500000,
		  0.1800000,
		  0.2100000,
		  0.2400000,
		  0.2800000,
		  0.3300000,
		  0.3800000,
		  0.4300000,
		  0.4800000,
		  0.5300000,
		  0.5800000,
		  0.6300000,
		  0.6800000,
		  0.7300000,
		  0.7800000,
		  0.8300000,
		  0.8800000,
		  0.9300000,
		  1.0025000,
		  1.1000000,
		  1.2000000,
		  1.3000000,
		  1.4000000,
		  1.5000000,
		  1.6000000,
		  1.7000000,
		  1.8000000,
		  1.9000000,
		  2.0500000,
		  2.2500000,
		  2.4500000,
		  2.6500000,
		  2.8500000,
		  3.1000000,
		  3.4000000,
		  3.7000000,
		  4.0000000,
		  4.3000000,
		  4.6000000,
		  4.9000000,
		  5.3000000,
		  5.8000000,
		  6.3000000,
		  6.8000000,
		  7.3000000,
		  7.8000000,
		  8.3000000,
		  8.8000000,
		  9.3000000,
		  9.8000000,
		  10.3000000,
		  10.8000000,
		  11.3000000,
		  11.8000000,
		  12.3000000,
		  12.8000000,
		  13.3000000,
		  13.8000000,
		  14.3250000,
		  15.2500000,
		  16.4000000,
		  17.4000000,
		  18.5000000,
		  19.5500000};
  Double_t ex[71] = {0.0075000,
		     0.0100000,
		     0.0100000,
		     0.0100000,
		     0.0100000,
		     0.0100000,
		     0.0100000,
		     0.0150000,
		     0.0150000,
		     0.0150000,
		     0.0150000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0250000,
		     0.0475000,
		     0.0500000,
		     0.0500000,
		     0.0500000,
		     0.0500000,
		     0.0500000,
		     0.0500000,
		     0.0500000,
		     0.0500000,
		     0.0500000,
		     0.1000000,
		     0.1000000,
		     0.1000000,
		     0.1000000,
		     0.1000000,
		     0.1500000,
		     0.1500000,
		     0.1500000,
		     0.1500000,
		     0.1500000,
		     0.1500000,
		     0.1500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2500000,
		     0.2750000,
		     0.6500000,
		     0.5000000,
		     0.5000000,
		     0.6000000,
		     0.4500000};
  Double_t y[71] ={5.1405333e-02,
		   9.8349500e-02,
		   1.3175000e-01,
		   1.5643750e-01,
		   1.7663350e-01,
		   1.9363550e-01,
		   2.0850400e-01,
		   2.2458900e-01,
		   2.4100000e-01,
		   2.5523733e-01,
		   2.6748400e-01,
		   2.8124000e-01,
		   2.9507200e-01,
		   3.0641600e-01,
		   3.1503400e-01,
		   3.2242800e-01,
		   3.2723000e-01,
		   3.3126800e-01,
		   3.3392000e-01,
		   3.3561000e-01,
		   3.3608000e-01,
		   3.3571400e-01,
		   3.3533800e-01,
		   3.3394000e-01,
		   3.3184000e-01,
		   3.2844632e-01,
		   3.2205000e-01,
		   3.1490200e-01,
		   3.0596700e-01,
		   2.9673300e-01,
		   2.8734700e-01,
		   2.7704000e-01,
		   2.6658000e-01,
		   2.5612000e-01,
		   2.4566000e-01,
		   2.3020050e-01,
		   2.1007500e-01,
		   1.9050950e-01,
		   1.7230650e-01,
		   1.5540000e-01,
		   1.3587233e-01,
		   1.1480600e-01,
		   9.6560667e-02,
		   8.0777667e-02,
		   6.7334333e-02,
		   5.5928667e-02,
		   4.6381333e-02,
		   3.6111800e-02,
		   2.6234400e-02,
		   1.8971620e-02,
		   1.3666760e-02,
		   9.8124400e-03,
		   7.0360200e-03,
		   5.0407600e-03,
		   3.6132800e-03,
		   2.5885200e-03,
		   1.8538120e-03,
		   1.3248120e-03,
		   9.4736800e-04,
		   6.7701400e-04,
		   4.8375800e-04,
		   3.4512600e-04,
		   2.4605200e-04,
		   1.7495000e-04,
		   1.2437880e-04,
		   8.6900727e-05,
		   4.8199615e-05,
		   2.1518400e-05,
		   1.0859600e-05,
		   5.0966000e-06,
		   2.4220667e-06};
  
  Float_t bins[71];

  bins[0]=x[0]-ex[0];//first bin is left side of bin
  for (int i=1;i<70;i++){
    bins[i] = x[i]-ex[i];
  }
  bins[70]=x[70]+ex[70];//last bin to the right side of last bin

  
  TH1F * Yield=new TH1F("Yield","",70,bins);
  TH1F * eff=new TH1F("eff","",70,bins);
  eff->SetDirectory(0);
  Yield->SetDirectory(0);


  TH1D * N2=new TH1D("N2","",200,0,20);
  for(int i=0;i<71;i++){
    //    cout<<h->GetBinLowEdge(i+1)<<" "<<h->GetBinWidth(i+1)+h->GetBinLowEdge(i+1)<<endl;
    Yield->SetBinContent(i+1,y[i]*Yield->GetBinWidth(i+1));
   }
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //  Doule_t thresh =53.73; // 26.3 KeV 
  double fudge =10.0;
  Double_t thresh=0;
  stringstream ss112;
  ss112<<"softwareCFDs[0]>0 &&softwareCFDs[1]>0&&NumOfChannelsInEvent==2 && channels[0]==8 && channels[1]==9 &&longGates[1]/shortGates[1]<1.12&&shortGates[1]>200&&ShiftTOFInternal>1.5&&ShiftTOFInternal<100&&sqrt(energies[0]*energies[1])>"<<thresh;

  
  
  //  flt->Draw("TOFEnergy","channels[0]==0&&softwareCFDs[0]>0&&softwareCFDs[1]>0&&softwareCFDs[2]>0&&NumOfChannelsInEvent==3&&channels[2]==9&&longGates[2]/shortGates[2]<1.12&&ShiftTOF>2")


  cout<<gDirectory->GetName()<<endl;
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  TFile frun354("~/analysis/run354/CoRFL3FG0d3w0run-0354-tw100-softwareCFD.root");
  TH1D * NWithCubicTimes=new TH1D("NWithCubicTimes","",70,bins);
  TH1D * NWithInternalTimes=new TH1D("NWithInternalTimes","",70,bins);


  //  flt->Project("N","TOFEnergy","ErrorBit==0 && NumOfChannelsInEvent==3 && channels[0]==0 && channels[2]==9 &&PulseShape<1.12&&sqrt(energies[0]*energies[1])>53.73");
  flt->Project("NWithCubicTimes","TOFEnergy",ss112.str().c_str());
  flt->Project("NWithInternalTimes","TOFEnergyInternal",ss112.str().c_str());
  NWithCubicTimes->SetDirectory(0);
  NWithInternalTimes->SetDirectory(0);
  /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  TFile frun354bkg("~/analysis/run354/CoRFL3FG0d3w0run-0354-twrandom1000-softwareCFD.root");
  TH1D * RandomBackGround354WithInternalTimes = new TH1D("RandomBackGround354WithInternalTimes","",70,bins);
  flt->Project("RandomBackGround354WithInternalTimes","TOFEnergyInternal",ss112.str().c_str());

  TH1D * RandomBackGround354WithCubicTimes = new TH1D("RandomBackGround354WithCubicTimes","",70,bins);
  flt->Project("RandomBackGround354WithCubicTimes","TOFEnergy",ss112.str().c_str());

  RandomBackGround354WithInternalTimes->SetDirectory(0);
  RandomBackGround354WithCubicTimes->SetDirectory(0);


  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  TFile frun355("~/analysis/run358/CoRrun-0358-LG17-SG7.root");
  TH1D * ShadowBarRun=new TH1D("ShadowBarRun","",70,bins);
  TH1D * ShadowBarRunInternalTimes=new TH1D("ShadowBarRunInternalTimes","",70,bins);
  
  flt->Project("ShadowBarRun","TOFEnergy",ss112.str().c_str());
  flt->Project("ShadowBarRunInternalTimes","TOFEnergyInternal",ss112.str().c_str());

  ShadowBarRun->SetDirectory(0);
  ShadowBarRunInternalTimes->SetDirectory(0);
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

  TFile frun355bkg("~/analysis/run999/CoRrun-0999-tw1000random-softwareCFD-output.root");
  TH1D * ShadowBarRandomBackGround = new TH1D("ShadowBarRandomBackGround","",70,bins);
  flt->Project("ShadowBarRandomBackGround","TOFEnergy",ss112.str().c_str());
  ShadowBarRandomBackGround->SetDirectory(0);

  TH1D * ShadowBarRandomBackGroundInternal = new TH1D("ShadowBarRandomBackGroundInternal","",70,bins);
  flt->Project("ShadowBarRandomBackGroundInternal","TOFEnergyInternal",ss112.str().c_str());
  ShadowBarRandomBackGroundInternal->SetDirectory(0);

  TH1F * hresult= new TH1F ("hresult","",70,bins);
  TH1F * shadowBarSubtracted= new TH1F ("shadowBarSubtracted","",70,bins);
  TH1F * NSubtracted= new TH1F ("NSubtracted","",70,bins);

  Double_t errors[71];
  Double_t errorsNB[71];
  Double_t errorNsub[71];
  Double_t errorShadowSub[71];

  errors[0]=0;
  errorsNB[0]=0;
  errorNsub[0]=0;
  errorShadowSub[0]=0;

  for (int i=1;i<=70;i++){
    Double_t nV, bkgV, bkg355V, bkg354V;
    //cubicTimes
    /*  
    nV= NWithCubicTimes->GetBinContent(i); //data run
    bkgV=ShadowBarRun->GetBinContent( i);//shadow bar run
    bkg355V =ShadowBarRandomBackGround->GetBinContent(i);//random coin build shadow bar
    bkg354V = RandomBackGround354WithCubicTimes->GetBinContent(i);//random coin build normal run
    
*/
    
    //Internal times
    nV= NWithInternalTimes->GetBinContent(i); //data run
    bkgV=ShadowBarRunInternalTimes->GetBinContent( i);//shadow bar run
    bkg355V =ShadowBarRandomBackGroundInternal->GetBinContent(i);//random coin build shadow bar
    bkg354V = RandomBackGround354WithInternalTimes->GetBinContent(i);//random coin build normal run
    



    hresult->SetBinContent(i,nV -(bkgV-(bkg355V/fudge))-(bkg354V/fudge));
    shadowBarSubtracted->SetBinContent(i,bkgV-(bkg355V/fudge));
    NSubtracted->SetBinContent(i,nV-(bkg354V/fudge));


    errorNsub[i]=sqrt( pow(sqrt(nV),2) + pow(sqrt(bkg354V)/fudge,2));
    errorShadowSub[i]=sqrt( pow(sqrt(bkgV),2)+pow(sqrt(bkg355V)/fudge,2) );
    //    errors[i]=sqrt (pow(sqrt(nV),2) + pow(sqrt(bkg354V),2)+pow(sqrt(bkgV),2) + pow(sqrt(bkg355V),2));
    errors[i]=sqrt( pow(errorNsub[i],2)+pow(errorShadowSub[i],2));
  }

  hresult->SetError(errors);
  NSubtracted->SetError(errorNsub);
  shadowBarSubtracted->SetError(errorShadowSub);
  hresult->SetDirectory(0);

  TH1F * hresultNB= new TH1F ("hresultNB","",70,bins);
  TH1F * shadowBarSubtractedNB= new TH1F ("shadowBarSubtractedNB","",70,bins);
  TH1F * NSubtractedNB= new TH1F ("NSubtractedNB","",70,bins);

  TH1D * NWithCubicTimesNB=new TH1D("NWithCubicTimesNB","",70,bins);
  TH1D * NWithInternalTimesNB=new TH1D("NWithInternalTimesNB","",70,bins);

  TH1D * RandomBackGround354WithInternalTimesNB = new TH1D("RandomBackGround354WithInternalTimesNB","",70,bins);
  TH1D * RandomBackGround354WithCubicTimesNB = new TH1D("RandomBackGround354WithCubicTimesNB","",70,bins);
  
  for (int i=1;i<=70;i++){
    hresultNB->SetBinContent(i,hresult->GetBinContent(i)/(hresult->GetBinWidth(i)));
    errorsNB[i]=errors[i]/(hresult->GetBinWidth(i));

    shadowBarSubtractedNB->SetBinContent(i,shadowBarSubtracted->GetBinContent(i)/(shadowBarSubtracted->GetBinWidth(i)));
    errorShadowSub[i]=errorShadowSub[i]/(shadowBarSubtracted->GetBinWidth(i));

    NSubtractedNB->SetBinContent(i,NSubtracted->GetBinContent(i)/(NSubtracted->GetBinWidth(i)));
    errorNsub[i]=errorNsub[i]/(NSubtracted->GetBinWidth(i));
    
    NWithInternalTimesNB->SetBinContent(i,NWithInternalTimes->GetBinContent(i)/NWithInternalTimes->GetBinWidth(i));
    NWithCubicTimesNB->SetBinContent(i,NWithCubicTimes->GetBinContent(i)/NWithCubicTimes->GetBinWidth(i));

    //    RandomBackGround354WithInternalTimesNB->

  }
  hresultNB->SetError(errorsNB);
  NSubtractedNB->SetError(errorNsub);
  shadowBarSubtractedNB->SetError(errorShadowSub);


  /*
  Int_t numEntries = hN->GetNbinsX();
  
  cout<<"NNNNNN "<<numEntries<<endl;

  Double_t time=0;

  Double_t c= 2.99 * TMath::Power(10,8);

  for (int i=1;i<=numEntries;i++){
    
    time = hN->GetBinCenter(i);
    double shiftTime = time*10.0 -(40.6651-3.3444);
    if (time >3){

      time = shiftTime*(1.0/(TMath::Power(10,9)));// put time in secs

      Double_t beta = (1.0/c)*(1.0/time);
      Double_t gamma = 1.0/(TMath::Sqrt(1-beta*beta));
      Double_t KE = (gamma-1)*939.5650; // MEV
      

      // cout<<"time is "<<time<<endl;
      //	    cout<<"Ke is "<<KE<<endl;
      
      //      int bin= N->GetXaxis()->FindBin((Double_t)KE);
      // N->SetBinContent(bin,);
      int bin =N->FindBin((Double_t)KE);
      N->SetBinContent(bin,hN->GetBinContent(i)+N->GetBinContent(bin));
    }
  }*/

 
  
  for (int i=0;i<71;i++){
    eff->SetBinContent(i+1,Double_t((hresult->GetBinContent(i+1)))/(Yield->GetBinContent(i+1)));
    if (i!=70)
      errors[i+1]=errors[i+1]/Yield->GetBinContent(i+1);

  }
  eff->SetError(errors);
  TCanvas * cC = new TCanvas("c");
  cC->cd(1);
  eff->Draw();

  TFile f("EffoutLiq.root","recreate");
  eff->Write();
  hresult->Write();
  NWithCubicTimes->Write();
  NWithInternalTimes->Write();

  NWithCubicTimesNB->Write();
  NWithInternalTimesNB->Write();

  ShadowBarRun->Write();
  ShadowBarRunInternalTimes->Write();
  ShadowBarRandomBackGround->Write();

  RandomBackGround354WithCubicTimes->Write();
  RandomBackGround354WithInternalTimes->Write();

  shadowBarSubtractedNB->Write();
  NSubtractedNB->Write();
  hresultNB->Write();

  Yield->Write();
  shadowBarSubtracted->Write();
  NSubtracted->Write();

  f.Close();

}
void makeSamePhiPlots() 
{
   gSystem->AddIncludePath("-I${EVENT_READER_DIR}");
   gSystem->AddIncludePath("-I${PLOTTER_DIR}");
   //  cout << gSystem->GetIncludePath() <<endl;
   
   gSystem->Load("libMathMore.so");
   gSystem->Load("/usr/lib64/libfftw3.so");
   gSystem->Load("libAnitaEvent.so");
   gSystem->Load("libAnitaCorrelator.so");
   TChain *deltaTTree = new TChain("deltaTTree");
   //   TFile *fp = new TFile("deltaTFile1027.root");
   //   TTree *deltaTTree = (TTree*) fp->Get("deltaTTree");
   deltaTTree->Add("deltaTFileClock*.root");
   
   AnitaGeomTool *fGeomTool = AnitaGeomTool::Instance();



   char plotCond[180];
   char plotTitle[180];
   char histName[180];
   TF1 *fitty = new TF1("fitty","gaus",-1,1);

   TH1F *histMeanDiff = new TH1F("histMeanDiff","histMeanDiff",100,-1,1);
   TH1F *histChiSq = new TH1F("histChiSq","histChiSq",100,0,3);
   TH1F *histSigma = new TH1F("histSigma","histSigma",100,0,10);
   TH1F *histConstant = new TH1F("histConstant","histConstant",100,0,100);

   ofstream Output("diffsDown.txt");

   for(int ant=0;ant<16;ant++) {
      TCanvas *can = new TCanvas();//"can","can");
      can->Divide(2,2);
      int topAnt=ant; 
      int bottomAnt=fGeomTool->getAzimuthPartner(topAnt); 
      for(int chip=0;chip<4;chip++) {
	 fitty->SetParameters(10,0,0.05);
	 //	 fitty->SetParLimits(2,0,0.1);

	 can->cd(chip+1);
	 sprintf(plotCond,"((firstAnt==%d && secondAnt==%d))  && labChip==%d && (corPeak/corRMS)>6",topAnt,bottomAnt,chip);	 
	 sprintf(plotTitle,"Ant %d -  Ant %d (Chip %d)",topAnt,bottomAnt,chip);
	 sprintf(histName,"histDt_%d_%d",ant,chip);
	 TH1F *histDt11 = new TH1F(histName,plotTitle,40,-0.5,0.5);

	 deltaTTree->Project(histName,"deltaT-deltaTExpected",plotCond);
	 //	 cout << plotCond << endl;
	 histDt11->Draw();
	 histDt11->Fit("fitty","Q");
	 Int_t numUnder= histDt11->GetBinContent(0);
	 Int_t numOver =histDt11->GetBinContent(1+histDt11->GetNbinsX());
// 	 cout << topAnt << "\t" << bottomAnt << "\t" << chip << "\t" << histDt11->GetEntries() << "\t"
// 	      << (histDt11->GetEntries()-(numOver+numUnder)) << "\t" << histDt11->GetMean() << "\t" << histDt11->GetRMS() << "\t"
// 	      << fitty->GetParameter(1) << "\t" << fitty->GetParError(1) << "\t" << fitty->GetParameter(2) << "\t"
// 	      << fitty->GetParError(2)  << "\t" << fitty->GetChisquare() << "\t" << fitty->GetNDF() << "\n";
	 histMeanDiff->Fill(fitty->GetParameter(1));
	 histChiSq->Fill(fitty->GetChisquare()/Double_t(fitty->GetNDF()));
	 histSigma->Fill(fitty->GetParameter(2));
	 histConstant->Fill(fitty->GetParameter(0));


	 Double_t constant=histDt11->GetMean();
	 Double_t error=0;
	 if(histDt11->GetEntries())
	    error=histDt11->GetRMS()/TMath::Sqrt(histDt11->GetEntries());
	 Int_t entries=(histDt11->GetEntries()-(numOver+numUnder));

	 if(TMath::Abs(fitty->GetParameter(1)-histDt11->GetMean())<0.01 || (entries>=20 && fitty->GetParError(1)<0.08)) {
	    constant=fitty->GetParameter(1);
	    error=fitty->GetParError(1);
	 }
	 else {
	    cout << topAnt << "\t" << bottomAnt << "\t" << chip << "\n";
	 }
	 Output << topAnt << "\t" << bottomAnt << "\t" << chip << "\t" << constant << "\t" << error << "\t"
		<< entries << "\n";
      }
	 
   }
   TCanvas *canSum = new TCanvas();
   canSum->Divide(2,2);
   canSum->cd(1);
   histChiSq->Draw();
   canSum->cd(2);
   histConstant->Draw();
   canSum->cd(3);
   histMeanDiff->Draw();
   canSum->cd(4);
   histSigma->Draw();    

      
}
Beispiel #16
0
void stat(Double_t low, Double_t up)
{
  // count number of signal, background and data MC
  if (FindFirstHisto() < 0) {
    return;
  }

  // total counts
  Double_t  nTotSignal    = 0;                // number of signal
  Double_t  nTotal        = 0;                // number of all mc
  Double_t  nTotExpected  = 0;                // number of expected signal
  Double_t  nData         = 0;                // number of data
  Double_t  nTotErrSig    = 0;
  Double_t  nTotErrBack   = 0;

  // for each mc/signal mc
  Double_t  * nEvents   = new Double_t[gMaxProcess-1]; // number of selected events
  Double_t  * nGene     = new Double_t[gMaxProcess-1]; // number of generated events
  Double_t  * nExpected = new Double_t[gMaxProcess-1]; // number of expected events
  Double_t  * weight    = new Double_t[gMaxProcess-1]; // weight of this MC

  // find bins to start and end with
  Int_t start, end;
  findbins(low, up, start, end);
  Int_t hstart = FindFirstHisto();
  if (hstart < 0)
    return;

  // total number of data events
  if (gHisto[gPadNr][gMaxProcess-1]) {
    nData = gHisto[gPadNr][gMaxProcess-1]->Integral(start, end);
  }
  DEBUG("nData = " << nData);

  // compute numbers for each mc separately
  for (Int_t i = 0; i < gMaxProcess-1; i++) {
    // zero out all values
    nEvents[i] = 0;
    nExpected[i] = 0;
    nGene[i] = 0;
    weight[i] = 0;
    // check if mc exists
    if (gHisto[gPadNr][i] == 0) {
      // mc does not exist
      continue;
    }
    // get integral for this mc
    nEvents[i] = gHisto[gPadNr][i]->Integral(start, end);
    nTotal += nEvents[i];

    // get expected number from global process information
    for (Int_t period = gStart; period <= gEnd; period++) {
      // compute expected events
      nExpected[i] += gLumi[period] * gProcessInfo[period][i].xs;
      DEBUG("gLumi[" << period << "]=" << gLumi[period] << ", xs = " 
	    << gProcessInfo[period][i].xs);
      DEBUG("nExpected = " << nExpected[i]);
      // compute generated events
      nGene[i] += gProcessInfo[period][i].Nev;
      double mcLumi = gProcessInfo[period][i].Nev/gProcessInfo[period][i].xs;
      weight[i] += gLumi[period]/mcLumi * gProcessInfo[period][i].weight;
    }
    weight[i] /= (gEnd-gStart+1);
    // something we do for signal only
    if (i < gMaxSignal) {
      // add signal events
      nTotSignal += nEvents[i];
    }
    nTotExpected += nExpected[i];
  }

  Double_t effi; // efficiency
  Double_t puri; // purity
  Double_t nErr; // error on number of selected events

  printf("*******************************************************************************\n");
  Int_t  nfill = 15 - strlen(gStack[gPadNr][hstart]->GetName());
  printf("%15s       N_events +/-    Delta_N      effi      purity  av. weight\n", 
	 gStack[gPadNr][hstart]->GetName());
  printf("*******************************************************************************\n");
  // inform user for each mc (ordered)
  for (Int_t k = 0; k < gMaxProcess-1; k++) {
    Int_t i = gOrder[gPadNr][k];
    if (nExpected[i] < 1E-9)
      effi = 0;
    else
      effi = nEvents[i] / nExpected[i];
    if (nTotal == 0)
      puri = 0;
    else
      puri = nEvents[i] / nTotal;
    if (effi > 0 && nGene[i] > 0) {
      nErr = nEvents[i] * sqrt((1.-effi)/(effi*nGene[i]));
    }
    else
      nErr = 0;
    // INFO("nExpected= " << nExpected[i] << ", nEvents= " << nEvents[i] << ", nGene= " << nGene[i] << ", effi= " << effi << ", radicand= " << (1-effi)/(effi*nGene[i]));
    if (i < gMaxSignal) {
      nTotErrSig += nErr*nErr;
    }
    else {
      nTotErrBack += nErr*nErr;
    }

    printf("%s:", gProcess[i].fname);
    nfill = 16 - strlen(gProcess[i].fname);
    for (Int_t j = 0; j < nfill; j++)
      printf(" ");
    printf(" %12.3f +/- %10.3f  %8.4f %%  %8.4f %%  %8.3f\n", 
	   nEvents[i], nErr, effi*100, puri*100, weight[i]);
  }

  // summaries
  printf("-------------------------------------------------------------------------------\n");
  if (nTotExpected != 0)
    effi = nTotSignal / nTotExpected;
  else 
    effi = 0;
  if (nTotal != 0)
    puri = nTotSignal / nTotal;
  else
    puri = 0;
  printf("total signal:     %12.3f +/- %10.3f  %8.4f %%  %8.4f %%  %8.6f\n", 
	 nTotSignal, TMath::Sqrt(nTotErrSig), effi*100, puri*100, effi*puri);
  printf("total back:       %12.3f +/- %10.3f\n", 
	 nTotal-nTotSignal, TMath::Sqrt(nTotErrBack));
  printf("===============================================================================\n");
  // total, under & overflow mc
  Double_t uflow  = 0;
  Double_t oflow  = 0;
  for (Int_t k = 0; k < gMaxProcess-1; k++) {
    Int_t i = gOrder[gPadNr][k];
    if (gHisto[gPadNr][i] == 0)
      continue;
    // sum up stacked and unstacked histograms
    uflow      += gHisto[gPadNr][i]->GetBinContent(0);
    Int_t obin  = gHisto[gPadNr][i]->GetNbinsX()+1;
    oflow      += gHisto[gPadNr][i]->GetBinContent(obin);
  }
  printf("total mc:         %12.3f +/- %10.3f (u: %7.3f) (o: %7.3f)   Lumi:\n", 
	 nTotal, TMath::Sqrt(nTotErrSig+nTotErrBack), uflow, oflow);
  // total, under & overflow data
  uflow  = 0;
  oflow  = 0;
  if (gStack[gPadNr][gMaxProcess-1]) {
    uflow      = gStack[gPadNr][gMaxProcess-1]->GetBinContent(0);
    Int_t obin = gStack[gPadNr][gMaxProcess-1]->GetNbinsX()+1;
    oflow      = gStack[gPadNr][gMaxProcess-1]->GetBinContent(obin);
  }
  // compute lumi
  Double_t lumi = 0;
  for (Int_t period = gStart; period <= gEnd; period++) {
    lumi += gLumi[period];
  }
  printf("data:             %12.3f +/- %10.3f (u: %7.3f) (o: %7.3f) %6.2f\n", 
	 nData, TMath::Sqrt(Double_t(nData)), uflow, oflow, lumi);
  // deviation and chi2
  Int_t ndof, nlow;
  Double_t ChiSquare = chi2_int(start, end, ndof, nlow);
  Double_t Deviation = 0;
  if (nTotal != 0)
    Deviation = (nData - nTotal) / TMath::Sqrt(nTotal);
  printf("Deviation:        %9.3f sigma   Chi2/ndof: %8.0f/%3d   Prob: %9.6f %%\n", 
	 Deviation, ChiSquare, ndof, 100 * TMath::Prob(ChiSquare, ndof));

  printf("*******************************************************************************\n");

  

  delete[] nExpected;
  delete[] nGene;
  delete[] nEvents;
  delete[] weight;
}
void convertResonanceShapes(const string& fFileIn, const string& fFileOut, Int_t fNbins, Double_t* fBinBoundaries, const string& fResonanceType)
{

   TFile *file_in = new TFile(fFileIn.c_str());
   TFile *file_out = new TFile(fFileOut.c_str(),"RECREATE");

   Int_t nKeys = file_in->GetListOfKeys()->GetEntries();

   for(Int_t i=0; i<nKeys; ++i)
   {
     string histname = file_in->GetListOfKeys()->At(i)->GetName();
     if(histname.find("cdf")!=string::npos || histname.find("Efficiency")!=string::npos) continue;
     std::cout << "Converting " << ("h_" + fResonanceType + "_" + histname.substr(8)) << std::endl;

     TH1D* h_shape = new TH1D(("h_" + fResonanceType + "_" + histname.substr(8)).c_str(), (fResonanceType + " Resonance Shape").c_str(), fNbins, fBinBoundaries);
     TH1D* h_pdf = new TH1D(Form("h_pdf_%i",i), "", 14000, 0, 14000);
     TH1D* h_cdf = new TH1D(("h_" + fResonanceType + "_" + histname.substr(8) + "_cdf").c_str(), (fResonanceType + " Resonance Shape CDF").c_str(), 14000, 0, 14000);

     TH1D* h_shape_in = (TH1D*)file_in->Get(histname.c_str());

     h_shape_in->Scale(5.); // Maxime's resonance shapes are normalized to 0.2 so they need to be scaled up by a factor of 5

     for(Int_t j=1; j<=h_shape_in->GetNbinsX(); ++j)
     {
       Int_t bin_min = h_pdf->GetXaxis()->FindBin(h_shape_in->GetXaxis()->GetBinLowEdge(j)+0.5);
       Int_t bin_max = h_pdf->GetXaxis()->FindBin(h_shape_in->GetXaxis()->GetBinUpEdge(j)-0.5);
       Double_t bin_content = h_shape_in->GetBinContent(j)/Double_t(bin_max-bin_min+1);
       for(Int_t b=bin_min; b<=bin_max; ++b)
         h_pdf->SetBinContent(b, bin_content);
     }

     for(Int_t j=1; j<=h_cdf->GetNbinsX(); ++j)
     {
       Int_t bin_min = h_pdf->GetXaxis()->FindBin(h_cdf->GetXaxis()->GetBinLowEdge(j)+0.5);
       Int_t bin_max = h_pdf->GetXaxis()->FindBin(h_cdf->GetXaxis()->GetBinUpEdge(j)-0.5);

       Double_t curr = 0.;
       for(Int_t b=bin_min; b<=bin_max; ++b)
         curr += h_pdf->GetBinContent(b);

       Double_t prev = h_cdf->GetBinContent(j-1);

       h_cdf->SetBinContent(j, prev+curr);
     }

     for(Int_t j=1; j<=h_shape->GetNbinsX(); ++j)
     {
       Int_t bin_min = h_pdf->GetXaxis()->FindBin(h_shape->GetXaxis()->GetBinLowEdge(j)+0.5);
       Int_t bin_max = h_pdf->GetXaxis()->FindBin(h_shape->GetXaxis()->GetBinUpEdge(j)-0.5);
       Double_t bin_content = h_pdf->Integral(bin_min,bin_max);
       h_shape->SetBinContent(j, bin_content);
     }

     file_out->cd();
     h_shape->Write();
     h_cdf->Write();

     delete h_pdf;
  }

  file_out->Close();
  file_in->Close();

  return;
}
Beispiel #18
0
Datei: FFT.C Projekt: Y--/root
void FFT()
{
   // Histograms
   // =========
   //prepare the canvas for drawing
   TCanvas *myc = new TCanvas("myc", "Fast Fourier Transform", 800, 600);
   myc->SetFillColor(45);
   TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.67,0.49,0.99);
   TPad *c1_2 = new TPad("c1_2", "c1_2",0.51,0.67,0.99,0.99);
   TPad *c1_3 = new TPad("c1_3", "c1_3",0.01,0.34,0.49,0.65);
   TPad *c1_4 = new TPad("c1_4", "c1_4",0.51,0.34,0.99,0.65);
   TPad *c1_5 = new TPad("c1_5", "c1_5",0.01,0.01,0.49,0.32);
   TPad *c1_6 = new TPad("c1_6", "c1_6",0.51,0.01,0.99,0.32);
   c1_1->Draw();
   c1_2->Draw();
   c1_3->Draw();
   c1_4->Draw();
   c1_5->Draw();
   c1_6->Draw();
   c1_1->SetFillColor(30);
   c1_1->SetFrameFillColor(42);
   c1_2->SetFillColor(30);
   c1_2->SetFrameFillColor(42);
   c1_3->SetFillColor(30);
   c1_3->SetFrameFillColor(42);
   c1_4->SetFillColor(30);
   c1_4->SetFrameFillColor(42);
   c1_5->SetFillColor(30);
   c1_5->SetFrameFillColor(42);
   c1_6->SetFillColor(30);
   c1_6->SetFrameFillColor(42);

   c1_1->cd();
   TH1::AddDirectory(kFALSE);

   //A function to sample
   TF1 *fsin = new TF1("fsin", "sin(x)+sin(2*x)+sin(0.5*x)+1", 0, 4*TMath::Pi());
   fsin->Draw();

   Int_t n=25;
   TH1D *hsin = new TH1D("hsin", "hsin", n+1, 0, 4*TMath::Pi());
   Double_t x;

   //Fill the histogram with function values
   for (Int_t i=0; i<=n; i++){
      x = (Double_t(i)/n)*(4*TMath::Pi());
      hsin->SetBinContent(i+1, fsin->Eval(x));
   }
   hsin->Draw("same");
   fsin->GetXaxis()->SetLabelSize(0.05);
   fsin->GetYaxis()->SetLabelSize(0.05);

   c1_2->cd();
   //Compute the transform and look at the magnitude of the output
   TH1 *hm =0;
   TVirtualFFT::SetTransform(0);
   hm = hsin->FFT(hm, "MAG");
   hm->SetTitle("Magnitude of the 1st transform");
   hm->Draw();
   //NOTE: for "real" frequencies you have to divide the x-axes range with the range of your function
   //(in this case 4*Pi); y-axes has to be rescaled by a factor of 1/SQRT(n) to be right: this is not done automatically!

   hm->SetStats(kFALSE);
   hm->GetXaxis()->SetLabelSize(0.05);
   hm->GetYaxis()->SetLabelSize(0.05);
   c1_3->cd();
   //Look at the phase of the output
   TH1 *hp = 0;
   hp = hsin->FFT(hp, "PH");
   hp->SetTitle("Phase of the 1st transform");
   hp->Draw();
   hp->SetStats(kFALSE);
   hp->GetXaxis()->SetLabelSize(0.05);
   hp->GetYaxis()->SetLabelSize(0.05);

   //Look at the DC component and the Nyquist harmonic:
   Double_t re, im;
   //That's the way to get the current transform object:
   TVirtualFFT *fft = TVirtualFFT::GetCurrentTransform();
   c1_4->cd();
   //Use the following method to get just one point of the output
   fft->GetPointComplex(0, re, im);
   printf("1st transform: DC component: %f\n", re);
   fft->GetPointComplex(n/2+1, re, im);
   printf("1st transform: Nyquist harmonic: %f\n", re);

   //Use the following method to get the full output:
   Double_t *re_full = new Double_t[n];
   Double_t *im_full = new Double_t[n];
   fft->GetPointsComplex(re_full,im_full);

   //Now let's make a backward transform:
   TVirtualFFT *fft_back = TVirtualFFT::FFT(1, &n, "C2R M K");
   fft_back->SetPointsComplex(re_full,im_full);
   fft_back->Transform();
   TH1 *hb = 0;
   //Let's look at the output
   hb = TH1::TransformHisto(fft_back,hb,"Re");
   hb->SetTitle("The backward transform result");
   hb->Draw();
   //NOTE: here you get at the x-axes number of bins and not real values
   //(in this case 25 bins has to be rescaled to a range between 0 and 4*Pi;
   //also here the y-axes has to be rescaled (factor 1/bins)
   hb->SetStats(kFALSE);
   hb->GetXaxis()->SetLabelSize(0.05);
   hb->GetYaxis()->SetLabelSize(0.05);
   delete fft_back;
   fft_back=0;

// Data array - same transform
// ===========================

   //Allocate an array big enough to hold the transform output
   //Transform output in 1d contains, for a transform of size N,
   //N/2+1 complex numbers, i.e. 2*(N/2+1) real numbers
   //our transform is of size n+1, because the histogram has n+1 bins

   Double_t *in = new Double_t[2*((n+1)/2+1)];
   Double_t re_2,im_2;
   for (Int_t i=0; i<=n; i++){
      x = (Double_t(i)/n)*(4*TMath::Pi());
      in[i] =  fsin->Eval(x);
   }

   //Make our own TVirtualFFT object (using option "K")
   //Third parameter (option) consists of 3 parts:
   //- transform type:
   // real input/complex output in our case
   //- transform flag:
   // the amount of time spent in planning
   // the transform (see TVirtualFFT class description)
   //- to create a new TVirtualFFT object (option "K") or use the global (default)
   Int_t n_size = n+1;
   TVirtualFFT *fft_own = TVirtualFFT::FFT(1, &n_size, "R2C ES K");
   if (!fft_own) return;
   fft_own->SetPoints(in);
   fft_own->Transform();

   //Copy all the output points:
   fft_own->GetPoints(in);
   //Draw the real part of the output
   c1_5->cd();
   TH1 *hr = 0;
   hr = TH1::TransformHisto(fft_own, hr, "RE");
   hr->SetTitle("Real part of the 3rd (array) tranfsorm");
   hr->Draw();
   hr->SetStats(kFALSE);
   hr->GetXaxis()->SetLabelSize(0.05);
   hr->GetYaxis()->SetLabelSize(0.05);
   c1_6->cd();
   TH1 *him = 0;
   him = TH1::TransformHisto(fft_own, him, "IM");
   him->SetTitle("Im. part of the 3rd (array) transform");
   him->Draw();
   him->SetStats(kFALSE);
   him->GetXaxis()->SetLabelSize(0.05);
   him->GetYaxis()->SetLabelSize(0.05);

   myc->cd();
   //Now let's make another transform of the same size
   //The same transform object can be used, as the size and the type of the transform
   //haven't changed
   TF1 *fcos = new TF1("fcos", "cos(x)+cos(0.5*x)+cos(2*x)+1", 0, 4*TMath::Pi());
   for (Int_t i=0; i<=n; i++){
      x = (Double_t(i)/n)*(4*TMath::Pi());
      in[i] =  fcos->Eval(x);
   }
   fft_own->SetPoints(in);
   fft_own->Transform();
   fft_own->GetPointComplex(0, re_2, im_2);
   printf("2nd transform: DC component: %f\n", re_2);
   fft_own->GetPointComplex(n/2+1, re_2, im_2);
   printf("2nd transform: Nyquist harmonic: %f\n", re_2);
   delete fft_own;
   delete [] in;
   delete [] re_full;
   delete [] im_full;
}
Beispiel #19
0
void THSEventsFit::PrepareForFarm(){
  if(!fDataBins) {cout<<"Error : Need to define at least 1 bin for this class e.g. RF->LoadBinVars(\"Eg\",1,3,4);"<<endl; exit(0);}
  DefineSets();
  MakeBins();
  cout<<" THSEventsFit::PrepareForFarm(); number of bins "<<fDataBins->GetN()<<endl;
  TDirectory *saveDir=gDirectory;
  THSBins* savedBins=new THSBins("HSDataBins",fOutDir+"DataEntries.root");
  fTree->SetBranchStatus("*",0);
  for(Int_t i=0;i<fVariables.getSize();i++){//only copy variable branches for speed
    fTree->SetBranchStatus(fVariables[i].GetName(),1);
  }
  //but always need ID branch
  if(fTree->GetBranch(fIDBranchName)){
   fTree->SetBranchStatus(fIDBranchName,1);
  }
   for(Int_t i=0;i<fDataBins->GetN();i++){
     Long64_t PdfN[GetPDFs().getSize()];
     Long64_t TotalN=0;

    THSRooFit* rf=CreateSubFitBins(savedBins->GetBinnedTree(fTree,i),kFALSE);
    cout<<"THSEventsFit::PrepareForFarm() made data for "<<fDataBins->GetBinName(i)<<" with entries =" <<rf->GetDataSet()->numEntries()<<endl;
     //iterate over models and set their entry lists id THSEventsPdf
    RooAbsPdf* pdf=0;
    for(Int_t ip=0;ip<rf->GetPDFs().getSize();ip++){
      pdf=(RooAbsPdf*)&(rf->GetPDFs()[ip]);
      THSEventsPDF* mpdf=0;
      cout<<" THSEventsFit::PrepareForFarm(); PDFs "<<pdf->GetName()<<endl;
      if(mpdf=dynamic_cast<THSEventsPDF*>(pdf)){//Only applies to THSEventsPDF

	THSBins* savedMCBins=new THSBins("MCModelBins",fOutDir+TString("Bins")+mpdf->GetName()+".root");
	//Get tree for this bin
  	mpdf->SetTree(savedMCBins->GetBinnedTree(dynamic_cast<THSEventsPDF*>(fPDFs.find(mpdf->GetName()))->GetTree(),i));
      	PdfN[ip]=mpdf->AddSmearedModel(0,rf->GetAuxVars());
	TotalN+=PdfN[ip];
	
	if(PdfN[ip]<10) {
	  cout<<" THSEventsFit::InitialiseFit() no events found for "<<rf->GetName()<<" MODEL: "<<pdf->GetName()<<" probably no events kinmatically allowed in this bin" <<endl;
	  rf->GetPDFsp()->remove(rf->GetPDFs()[ip]);
	  rf->GetYieldsp()->remove(*(rf->GetWorkSpace()->var(fYld+pdf->GetName())));
	  rf->GetWorkSpace()->removeSet("Yields");
	  rf->GetWorkSpace()->removeSet("PDFs");
	  rf->GetWorkSpace()->defineSet("Yields",rf->GetYields());
	  rf->GetWorkSpace()->defineSet("PDFs",rf->GetPDFs());	
	}
	delete savedMCBins;
      }
    }
   for(Int_t ip=0;ip<GetPDFs().getSize();ip++){
 	pdf=(RooAbsPdf*)&(rf->GetPDFs()[ip]);
	THSEventsPDF* mpdf=0;
 	if(mpdf=dynamic_cast<THSEventsPDF*>(pdf)){
	  if(Double_t(PdfN[ip])/TotalN<fAccFrac){
	    cout<<" THSEventsFit::InitialiseFit()  "<<GetName()<<" MODEL: "<<GetPDFs()[ip].GetName()<<" N events below acceptance fraction so not considered significant enough background " <<PdfN[ip] <<" out of "<<TotalN<<" "<<fAccFrac<<endl;
	    GetPDFsp()->remove(GetPDFs()[ip]);
	    GetYieldsp()->remove(*(GetWorkSpace()->var(fYld+pdf->GetName())));
	    GetWorkSpace()->removeSet("Yields");
	    GetWorkSpace()->removeSet("PDFs");
	    GetWorkSpace()->defineSet("Yields",GetYields());
	    GetWorkSpace()->defineSet("PDFs",GetPDFs());	
	    
	  }
	}
    }
  
    //also need to import custom PDF class
   rf->GetWorkSpace()->Print();
   //rf->GetWorkSpace()->importClassCode(THSEventsPDF::Class(),kTRUE);
    rf->GetWorkSpace()->writeToFile(fOutDir+TString("Farm")+fDataBins->GetBinName(i)+".root");
    // cout <<" THSEventsFit::PrepareForFarm() Saved Workspace with "<<rf->GetDataSet()->numEntries()<<" for bin "<<fDataBins->GetBinName(i)<<endl;
    rf->RemoveDataSet();//save memory
    delete rf;
  }
  delete savedBins;

  cout<<"THSRooFit::PrepareForFarm() Done all files "<<endl;
 }
Beispiel #20
0
void THSEventsFit::RunWeights(Int_t Nbins){
  if(!fDataBins) {cout<<"Error : Need to define at least 1 bin for this class e.g. RF->LoadBinVars(\"Eg\",1,3,4);"<<endl; exit(0);}
  DefineSets();
  MakeBins();
  cout<<"THSEventsFit::RunWithBins(); number of bins "<<fDataBins->GetN()<<endl;
  TDirectory *saveDir=gDirectory;
  THSBins* savedBins=new THSBins("HSDataBins",fOutDir+"DataEntries.root");
  fTree->SetBranchStatus("*",0);
  for(Int_t i=0;i<fVariables.getSize();i++){//only copy variable branches for speed
    fTree->SetBranchStatus(fVariables[i].GetName(),1);
  }
  //but always need ID branch
  if(fTree->GetBranch(fIDBranchName)){
   fTree->SetBranchStatus(fIDBranchName,1);
  }
 
  for(Int_t i=0;i<fDataBins->GetN();i++){
    Long64_t PdfN[GetPDFs().getSize()];
    for(Int_t ipdf=0;ipdf<GetPDFs().getSize();ipdf++)  PdfN[ipdf]=0;
    Long64_t TotalN=0;
    THSsPlot* rf=static_cast<THSsPlot*>(CreateSubFitBins(savedBins->GetBinnedTree(fTree,i),kFALSE));
    //iterate over models and set their entry lists id THSEventsPdf
    RooAbsPdf* pdf=0;
    for(Int_t ip=0;ip<rf->GetPDFs().getSize();ip++){
      pdf=(RooAbsPdf*)&(rf->GetPDFs()[ip]);
      THSEventsPDF* mpdf=0;
      cout<<"THSEventsFit::RunWithBins(); PDFs "<<pdf->GetName()<<endl;
      if(mpdf=dynamic_cast<THSEventsPDF*>(pdf)){//Only applies to THSEventsPDF
	THSBins* savedMCBins=new THSBins("MCModelBins",fOutDir+TString("Bins")+mpdf->GetName()+".root");
  	mpdf->SetTree(savedMCBins->GetBinnedTree(dynamic_cast<THSEventsPDF*>(fPDFs.find(mpdf->GetName()))->GetTree(),i));
	delete savedMCBins;
       	PdfN[ip]=mpdf->AddSmearedModel(0,rf->GetAuxVars());
	cout<<"CHCK "<<PdfN[ip]<<" "<<TotalN<<endl;
	TotalN+=PdfN[ip];
	cout<<"CHCK "<<PdfN[ip]<<" "<<TotalN<<endl;
	if(PdfN[ip]<10) {
	  cout<<"THSEventsFitfrom::RunWithBins() no events found for "<<fDataBins->GetBinName(i)<<" MODEL: "<<pdf->GetName()<<" probably no events kinmatically allowed in this bin" <<endl;
	  rf->GetPDFsp()->remove(rf->GetPDFs()[ip]);
	  rf->GetYieldsp()->remove(*(rf->GetWorkSpace()->var(fYld+pdf->GetName())));
	  rf->GetWorkSpace()->removeSet("Yields");
	  rf->GetWorkSpace()->removeSet("PDFs");
	  rf->GetWorkSpace()->defineSet("Yields",rf->GetYields());
	  rf->GetWorkSpace()->defineSet("PDFs",rf->GetPDFs());
	}
      }
    }
    for(Int_t ip=0;ip<GetPDFs().getSize();ip++){
 	pdf=(RooAbsPdf*)&(rf->GetPDFs()[ip]);
	THSEventsPDF* mpdf=0;
 	if(mpdf=dynamic_cast<THSEventsPDF*>(pdf)){
	  if(Double_t(PdfN[ip])/TotalN<fAccFrac){
	    cout<<" THSEventsFit::InitialiseFit()  "<<GetName()<<" MODEL: "<<GetPDFs()[ip].GetName()<<" N events below acceptance fraction so not considered significant enough background " <<PdfN[ip] <<" out of "<<TotalN<<" "<<fAccFrac<<endl;
	    GetPDFsp()->remove(GetPDFs()[ip]);
	    GetYieldsp()->remove(*(GetWorkSpace()->var(fYld+pdf->GetName())));
	    GetWorkSpace()->removeSet("Yields");
	    GetWorkSpace()->removeSet("PDFs");
	    GetWorkSpace()->defineSet("Yields",GetYields());
	    GetWorkSpace()->defineSet("PDFs",GetPDFs());	

	  }
	}
    }
    if(rf->GetPDFs().getSize()) rf->TotalPDF();
    else {
      cout<<"THSEventsFit::RunWithBins() no model found for "<<fDataBins->GetBinName(i)<<" probably no events kinmatically allowed in this bin" <<endl;
      rf->RemoveDataSet();//save memory
      delete rf;
      continue;
    }
    cout<<fData->numEntries()<<endl;
    if(rf->GetDataSet()->numEntries()<2) {delete rf;continue;}
    rf->FitMany(Nbins);
    rf->sPlot();
    rf->SavePlots("");//save plots for each bin fit
    if(rf->GetWeights()){
      rf->GetWeights()->PrintWeight();
      AddWeightMap(rf->GetWeights());
      rf->GetWeights()->Save();
    }
    rf->RemoveDataSet();//save memory
    delete rf;
  }
  //tfile->Close();
   delete savedBins;
   //delete tfile;
  fTree->SetBranchStatus("*",1);
  cout<<"THSRooFit::RunWithBins() Done all Fits "<<endl;
  // AddSubWeights();
  if(fWeights)GetWeights()->PrintWeight();
  if(fWeights) GetWeights()->SortWeights();
}
Beispiel #21
0
void selectZmm(const TString conf="zmm.conf", // input file
               const TString outputDir=".",   // output directory
	       const Bool_t  doScaleCorr=0,    // apply energy scale corrections
	       const Bool_t  doPU=0
) {
  gBenchmark->Start("selectZmm");

  //--------------------------------------------------------------------------------------------------------------
  // Settings 
  //============================================================================================================== 

  const Double_t MASS_LOW  = 40;
  const Double_t MASS_HIGH = 200;
  const Double_t PT_CUT    = 22;
  const Double_t ETA_CUT   = 2.4;
  const Double_t MUON_MASS = 0.105658369;

  const Int_t BOSON_ID  = 23;
  const Int_t LEPTON_ID = 13;

  // load trigger menu                                                                                                  
  const baconhep::TTrigger triggerMenu("../../BaconAna/DataFormats/data/HLT_50nsGRun");

  // load pileup reweighting file                                                                                       
  TFile *f_rw = TFile::Open("../Tools/puWeights_76x.root", "read");

  TH1D *h_rw = (TH1D*) f_rw->Get("puWeights");
  TH1D *h_rw_up = (TH1D*) f_rw->Get("puWeightsUp");
  TH1D *h_rw_down = (TH1D*) f_rw->Get("puWeightsDown");


  if (h_rw==NULL) cout<<"WARNING h_rw == NULL"<<endl;
  if (h_rw_up==NULL) cout<<"WARNING h_rw == NULL"<<endl;
  if (h_rw_down==NULL) cout<<"WARNING h_rw == NULL"<<endl;

  //--------------------------------------------------------------------------------------------------------------
  // Main analysis code 
  //==============================================================================================================  

  enum { eMuMu2HLT=1, eMuMu1HLT1L1, eMuMu1HLT, eMuMuNoSel, eMuSta, eMuTrk };  // event category enum
  
  vector<TString>  snamev;      // sample name (for output files)  
  vector<CSample*> samplev;     // data/MC samples

  //
  // parse .conf file
  //
  confParse(conf, snamev, samplev);
  const Bool_t hasData = (samplev[0]->fnamev.size()>0);

  // Create output directory
  gSystem->mkdir(outputDir,kTRUE);
  const TString ntupDir = outputDir + TString("/ntuples");
  gSystem->mkdir(ntupDir,kTRUE);
  
  //
  // Declare output ntuple variables
  //
  UInt_t  runNum, lumiSec, evtNum;
  UInt_t  matchGen;
  UInt_t  category;
  UInt_t  npv, npu;
  UInt_t  id_1, id_2;
  Double_t x_1, x_2, xPDF_1, xPDF_2;
  Double_t scalePDF, weightPDF;
  TLorentzVector *genV=0;
  Float_t genVPt, genVPhi, genVy, genVMass;
  Float_t genWeight, PUWeight;
  Float_t scale1fb,scale1fbUp,scale1fbDown;
  Float_t met, metPhi, sumEt, u1, u2;
  Float_t tkMet, tkMetPhi, tkSumEt, tkU1, tkU2;
  Float_t mvaMet, mvaMetPhi, mvaSumEt, mvaU1, mvaU2;
  Float_t puppiMet, puppiMetPhi, puppiSumEt, puppiU1, puppiU2;
  Int_t   q1, q2;
  TLorentzVector *dilep=0, *lep1=0, *lep2=0;
  ///// muon specific /////
  Float_t trkIso1, emIso1, hadIso1, trkIso2, emIso2, hadIso2;
  Float_t pfChIso1, pfGamIso1, pfNeuIso1, pfCombIso1, pfChIso2, pfGamIso2, pfNeuIso2, pfCombIso2;
  Float_t d01, dz1, d02, dz2;
  Float_t muNchi21,  muNchi22;
  UInt_t nPixHits1, nTkLayers1, nPixHits2, nTkLayers2;
  UInt_t nValidHits1, nMatch1, nValidHits2, nMatch2;
  UInt_t typeBits1, typeBits2;
  TLorentzVector *sta1=0, *sta2=0;
  
  // Data structures to store info from TTrees
  baconhep::TEventInfo *info   = new baconhep::TEventInfo();
  baconhep::TGenEventInfo *gen = new baconhep::TGenEventInfo();
  TClonesArray *genPartArr = new TClonesArray("baconhep::TGenParticle");
  TClonesArray *muonArr    = new TClonesArray("baconhep::TMuon");
  TClonesArray *vertexArr  = new TClonesArray("baconhep::TVertex");
  
  TFile *infile=0;
  TTree *eventTree=0;

    
  //
  // loop over samples
  //  
  for(UInt_t isam=0; isam<samplev.size(); isam++) {
    // Assume data sample is first sample in .conf file
    // If sample is empty (i.e. contains no ntuple files), skip to next sample
    Bool_t isData=kFALSE;
    if(isam==0 && !hasData) continue;
    else if (isam==0) isData=kTRUE;
    
    // Assume signal sample is given name "zmm" - flag to store GEN Z kinematics
    Bool_t isSignal = (snamev[isam].CompareTo("zmm",TString::kIgnoreCase)==0);
    // flag to reject Z->mm events when selecting at wrong-flavor background events
    Bool_t isWrongFlavor = (snamev[isam].CompareTo("zxx",TString::kIgnoreCase)==0);
    
    CSample* samp = samplev[isam];
    
    //
    // Set up output ntuple
    //
    TString outfilename = ntupDir + TString("/") + snamev[isam] + TString("_select.root");
    if(isam!=0 && !doScaleCorr) outfilename = ntupDir + TString("/") + snamev[isam] + TString("_select.raw.root");
    
    TFile *outFile = new TFile(outfilename,"RECREATE"); 
    TTree *outTree = new TTree("Events","Events");
    outTree->Branch("runNum",      &runNum,     "runNum/i");      // event run number
    outTree->Branch("lumiSec",     &lumiSec,    "lumiSec/i");     // event lumi section
    outTree->Branch("evtNum",      &evtNum,     "evtNum/i");      // event number
    outTree->Branch("matchGen",    &matchGen,   "matchGen/i");    // event has both leptons matched to MC Z->ll
    outTree->Branch("category",    &category,   "category/i");    // dilepton category
    outTree->Branch("id_1",        &id_1,       "id_1/i");        // PDF info -- parton ID for parton 1
    outTree->Branch("id_2",        &id_2,       "id_2/i");        // PDF info -- parton ID for parton 2
    outTree->Branch("x_1",         &x_1,        "x_1/d");         // PDF info -- x for parton 1
    outTree->Branch("x_2",         &x_2,        "x_2/d");         // PDF info -- x for parton 2
    outTree->Branch("xPDF_1",      &xPDF_1,     "xPDF_1/d");      // PDF info -- x*F for parton 1
    outTree->Branch("xPDF_2",      &xPDF_2,     "xPDF_2/d");      // PDF info -- x*F for parton 2
    outTree->Branch("scalePDF",    &scalePDF,   "scalePDF/d");    // PDF info -- energy scale of parton interaction
    outTree->Branch("weightPDF",   &weightPDF,  "weightPDF/d");   // PDF info -- PDF weight
    outTree->Branch("npv",         &npv,        "npv/i");         // number of primary vertices
    outTree->Branch("npu",         &npu,        "npu/i");         // number of in-time PU events (MC)
    outTree->Branch("genV",        "TLorentzVector",  &genV);     // GEN boson 4-vector (signal MC)
    outTree->Branch("genVPt",      &genVPt,     "genVPt/F");      // GEN boson pT (signal MC)
    outTree->Branch("genVPhi",     &genVPhi,    "genVPhi/F");     // GEN boson phi (signal MC)
    outTree->Branch("genVy",       &genVy,      "genVy/F");       // GEN boson rapidity (signal MC)
    outTree->Branch("genVMass",    &genVMass,   "genVMass/F");    // GEN boson mass (signal MC)
    outTree->Branch("genWeight",   &genWeight,  "genWeight/F");
    outTree->Branch("PUWeight",    &PUWeight,   "PUWeight/F");
    outTree->Branch("scale1fb",    &scale1fb,   "scale1fb/F");    // event weight per 1/fb (MC)
    outTree->Branch("scale1fbUp",    &scale1fbUp,   "scale1fbUp/F");    // event weight per 1/fb (MC)
    outTree->Branch("scale1fbDown",    &scale1fbDown,   "scale1fbDown/F");    // event weight per 1/fb (MC)
    outTree->Branch("met",         &met,        "met/F");         // MET
    outTree->Branch("metPhi",      &metPhi,     "metPhi/F");      // phi(MET)
    outTree->Branch("sumEt",       &sumEt,      "sumEt/F");       // Sum ET
    outTree->Branch("u1",          &u1,         "u1/F");          // parallel component of recoil
    outTree->Branch("u2",          &u2,         "u2/F");          // perpendicular component of recoil
    outTree->Branch("tkMet",       &tkMet,      "tkMet/F");       // MET (track MET)
    outTree->Branch("tkMetPhi",    &tkMetPhi,   "tkMetPhi/F");    // phi(MET) (track MET)
    outTree->Branch("tkSumEt",     &tkSumEt,    "tkSumEt/F");     // Sum ET (track MET)
    outTree->Branch("tkU1",        &tkU1,       "tkU1/F");        // parallel component of recoil (track MET)
    outTree->Branch("tkU2",        &tkU2,       "tkU2/F");        // perpendicular component of recoil (track MET)
    outTree->Branch("mvaMet",      &mvaMet,     "mvaMet/F");      // MVA MET
    outTree->Branch("mvaMetPhi",   &mvaMetPhi,  "mvaMetPhi/F");   // phi(MVA MET)
    outTree->Branch("mvaSumEt",    &mvaSumEt,   "mvaSumEt/F");    // Sum ET (mva MET)
    outTree->Branch("mvaU1",       &mvaU1,      "mvaU1/F");       // parallel component of recoil (mva MET)
    outTree->Branch("mvaU2",       &mvaU2,      "mvaU2/F");       // perpendicular component of recoil (mva MET) 
    outTree->Branch("puppiMet",    &puppiMet,   "puppiMet/F");      // Puppi MET
    outTree->Branch("puppiMetPhi", &puppiMetPhi,"puppiMetPhi/F");   // phi(Puppi MET)
    outTree->Branch("puppiSumEt",  &puppiSumEt, "puppiSumEt/F");    // Sum ET (Puppi MET)
    outTree->Branch("puppiU1",     &puppiU1,    "puppiU1/F");       // parallel component of recoil (Puppi MET)
    outTree->Branch("puppiU2",     &puppiU2,    "puppiU2/F");       // perpendicular component of recoil (Puppi MET)
    outTree->Branch("q1",          &q1,         "q1/I");          // charge of tag lepton
    outTree->Branch("q2",          &q2,         "q2/I");          // charge of probe lepton
    outTree->Branch("dilep",       "TLorentzVector", &dilep);     // di-lepton 4-vector
    outTree->Branch("lep1",        "TLorentzVector", &lep1);      // tag lepton 4-vector
    outTree->Branch("lep2",        "TLorentzVector", &lep2);      // probe lepton 4-vector
    ///// muon specific /////
    outTree->Branch("trkIso1",     &trkIso1,     "trkIso1/F");       // track isolation of tag lepton
    outTree->Branch("trkIso2",     &trkIso2,     "trkIso2/F");       // track isolation of probe lepton
    outTree->Branch("emIso1",      &emIso1,      "emIso1/F");        // ECAL isolation of tag lepton
    outTree->Branch("emIso2",      &emIso2,      "emIso2/F");        // ECAL isolation of probe lepton
    outTree->Branch("hadIso1",     &hadIso1,     "hadIso1/F");       // HCAL isolation of tag lepton
    outTree->Branch("hadIso2",     &hadIso2,     "hadIso2/F");       // HCAL isolation of probe lepton
    outTree->Branch("pfChIso1",    &pfChIso1,    "pfChIso1/F");      // PF charged hadron isolation of tag lepton
    outTree->Branch("pfChIso2",    &pfChIso2,    "pfChIso2/F");      // PF charged hadron isolation of probe lepton
    outTree->Branch("pfGamIso1",   &pfGamIso1,   "pfGamIso1/F");     // PF photon isolation of tag lepton
    outTree->Branch("pfGamIso2",   &pfGamIso2,   "pfGamIso2/F");     // PF photon isolation of probe lepton
    outTree->Branch("pfNeuIso1",   &pfNeuIso1,   "pfNeuIso1/F");     // PF neutral hadron isolation of tag lepton
    outTree->Branch("pfNeuIso2",   &pfNeuIso2,   "pfNeuIso2/F");     // PF neutral hadron isolation of probe lepton
    outTree->Branch("pfCombIso1",  &pfCombIso1,  "pfCombIso1/F");    // PF combined isolation of tag lepton
    outTree->Branch("pfCombIso2",  &pfCombIso2,  "pfCombIso2/F");    // PF combined isolation of probe lepton    
    outTree->Branch("d01",         &d01,         "d01/F");           // transverse impact parameter of tag lepton
    outTree->Branch("d02",         &d02,         "d02/F");           // transverse impact parameter of probe lepton	 
    outTree->Branch("dz1",         &dz1,         "dz1/F");           // longitudinal impact parameter of tag lepton
    outTree->Branch("dz2",         &dz2,         "dz2/F");           // longitudinal impact parameter of probe lepton	 
    outTree->Branch("muNchi21",    &muNchi21,    "muNchi21/F");      // muon fit normalized chi^2 of tag lepton
    outTree->Branch("muNchi22",    &muNchi22,    "muNchi22/F");      // muon fit normalized chi^2 of probe lepton
    outTree->Branch("nPixHits1",   &nPixHits1,	 "nPixHits1/i");     // number of pixel hits of tag muon
    outTree->Branch("nPixHits2",   &nPixHits2,	 "nPixHits2/i");     // number of pixel hits of probe muon
    outTree->Branch("nTkLayers1",  &nTkLayers1,  "nTkLayers1/i");    // number of tracker layers of tag muon
    outTree->Branch("nTkLayers2",  &nTkLayers2,  "nTkLayers2/i");    // number of tracker layers of probe muon
    outTree->Branch("nMatch1",     &nMatch1,	 "nMatch1/i");       // number of matched segments of tag muon
    outTree->Branch("nMatch2",     &nMatch2,	 "nMatch2/i");       // number of matched segments of probe muon 
    outTree->Branch("nValidHits1", &nValidHits1, "nValidHits1/i");   // number of valid muon hits of tag muon
    outTree->Branch("nValidHits2", &nValidHits2, "nValidHits2/i");   // number of valid muon hits of probe muon
    outTree->Branch("typeBits1",   &typeBits1,   "typeBits1/i");     // muon type of tag muon
    outTree->Branch("typeBits2",   &typeBits2,   "typeBits2/i");     // muon type of probe muon
    outTree->Branch("sta1",        "TLorentzVector", &sta1);         // tag standalone muon 4-vector
    outTree->Branch("sta2",        "TLorentzVector", &sta2);         // probe standalone muon 4-vector
    
    //
    // loop through files
    //
    const UInt_t nfiles = samp->fnamev.size();
    for(UInt_t ifile=0; ifile<nfiles; ifile++) {  
      
      // Read input file and get the TTrees
      cout << "Processing " << samp->fnamev[ifile] << " [xsec = " << samp->xsecv[ifile] << " pb] ... "; cout.flush();
      infile = TFile::Open(samp->fnamev[ifile]); 
      assert(infile);
      if (samp->fnamev[ifile] == "/dev/null") 
	      {
	     	cout <<"-> Ignoring null input "<<endl; 
		continue;
	      }


      Bool_t hasJSON = kFALSE;
      baconhep::RunLumiRangeMap rlrm;
      if(samp->jsonv[ifile].CompareTo("NONE")!=0) { 
        hasJSON = kTRUE;
	rlrm.addJSONFile(samp->jsonv[ifile].Data()); 
      }
  
      eventTree = (TTree*)infile->Get("Events"); assert(eventTree);  
      eventTree->SetBranchAddress("Info", &info);      TBranch *infoBr = eventTree->GetBranch("Info");
      eventTree->SetBranchAddress("Muon", &muonArr);   TBranch *muonBr = eventTree->GetBranch("Muon");
      eventTree->SetBranchAddress("PV",   &vertexArr); TBranch *vertexBr = eventTree->GetBranch("PV");
      Bool_t hasGen = eventTree->GetBranchStatus("GenEvtInfo");
      TBranch *genBr=0, *genPartBr=0;
      if(hasGen) {
        eventTree->SetBranchAddress("GenEvtInfo", &gen); genBr = eventTree->GetBranch("GenEvtInfo");
	eventTree->SetBranchAddress("GenParticle",&genPartArr); genPartBr = eventTree->GetBranch("GenParticle");
      }

      // Compute MC event weight per 1/fb
      const Double_t xsec = samp->xsecv[ifile];
      Double_t totalWeight=0;
      Double_t totalWeightUp=0;
      Double_t totalWeightDown=0;
      Double_t puWeight=0;
      Double_t puWeightUp=0;
      Double_t puWeightDown=0;

      if (hasGen) {
	for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
	  infoBr->GetEntry(ientry);
	  genBr->GetEntry(ientry);
	  puWeight = doPU ? h_rw->GetBinContent(h_rw->FindBin(info->nPUmean)) : 1.;
	  puWeightUp = doPU ? h_rw_up->GetBinContent(h_rw_up->FindBin(info->nPUmean)) : 1.;
	  puWeightDown = doPU ? h_rw_down->GetBinContent(h_rw_down->FindBin(info->nPUmean)) : 1.;
	  totalWeight+=gen->weight*puWeight;
	  totalWeightUp+=gen->weight*puWeightUp;
	  totalWeightDown+=gen->weight*puWeightDown;
	}
      }
      else if (not isData){
	for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
	  puWeight = doPU ? h_rw->GetBinContent(h_rw->FindBin(info->nPUmean)) : 1.;
	  puWeightUp = doPU ? h_rw_up->GetBinContent(h_rw_up->FindBin(info->nPUmean)) : 1.;
	  puWeightDown = doPU ? h_rw_down->GetBinContent(h_rw_down->FindBin(info->nPUmean)) : 1.;
	  totalWeight+= 1.0*puWeight;
	  totalWeightUp+= 1.0*puWeightUp;
	  totalWeightDown+= 1.0*puWeightDown;
	}

      }
   
      //
      // loop over events
      //
      Double_t nsel=0, nselvar=0;
      for(UInt_t ientry=0; ientry<eventTree->GetEntries(); ientry++) {
        infoBr->GetEntry(ientry);

	if(ientry%1000000==0) cout << "Processing event " << ientry << ". " << (double)ientry/(double)eventTree->GetEntries()*100 << " percent done with this file." << endl;

	Double_t weight=1;
	Double_t weightUp=1;
	Double_t weightDown=1;
    if(xsec>0 && totalWeight>0) weight = xsec/totalWeight;
	if(xsec>0 && totalWeightUp>0) weightUp = xsec/totalWeightUp;
	if(xsec>0 && totalWeightDown>0) weightDown = xsec/totalWeightDown;
	if(hasGen) {
	  genPartArr->Clear();
	  genBr->GetEntry(ientry);
          genPartBr->GetEntry(ientry);
	  puWeight = doPU ? h_rw->GetBinContent(h_rw->FindBin(info->nPUmean)) : 1.;
	  puWeightUp = doPU ? h_rw_up->GetBinContent(h_rw_up->FindBin(info->nPUmean)) : 1.;
	  puWeightDown = doPU ? h_rw_down->GetBinContent(h_rw_down->FindBin(info->nPUmean)) : 1.;
	  weight*=gen->weight*puWeight;
	  weightUp*=gen->weight*puWeightUp;
	  weightDown*=gen->weight*puWeightDown;
	}

	// veto z -> xx decays for signal and z -> mm for bacground samples (needed for inclusive DYToLL sample)
        if (isWrongFlavor && hasGen && fabs(toolbox::flavor(genPartArr, BOSON_ID))==LEPTON_ID) continue;
        else if (isSignal && hasGen && fabs(toolbox::flavor(genPartArr, BOSON_ID))!=LEPTON_ID) continue;
     
        // check for certified lumi (if applicable)
        baconhep::RunLumiRangeMap::RunLumiPairType rl(info->runNum, info->lumiSec);      
        if(hasJSON && !rlrm.hasRunLumi(rl)) continue;

        // trigger requirement               
        if (!isMuonTrigger(triggerMenu, info->triggerBits)) continue;

        // good vertex requirement
        if(!(info->hasGoodPV)) continue;

	muonArr->Clear();
        muonBr->GetEntry(ientry);

	TLorentzVector vTag(0,0,0,0);
	TLorentzVector vTagSta(0,0,0,0);
	Double_t tagPt=0;
	Double_t Pt1=0;
	Double_t Pt2=0;
	Int_t itag=-1;
	
        for(Int_t i1=0; i1<muonArr->GetEntriesFast(); i1++) {
          const baconhep::TMuon *tag = (baconhep::TMuon*)((*muonArr)[i1]);

          // apply scale and resolution corrections to MC
          Double_t tagpt_corr = tag->pt;
          if(doScaleCorr && snamev[isam].CompareTo("data",TString::kIgnoreCase)!=0)
            tagpt_corr = gRandom->Gaus(tag->pt*getMuScaleCorr(tag->eta,0),getMuResCorr(tag->eta,0));
	
	  if(tagpt_corr     < PT_CUT)        continue;  // lepton pT cut
	  if(fabs(tag->eta) > ETA_CUT)       continue;  // lepton |eta| cut
	  if(!passMuonID(tag))               continue;  // lepton selection

	  double Mu_Pt=0;
	  if(doScaleCorr) {
	    Mu_Pt=gRandom->Gaus(tag->pt*getMuScaleCorr(tag->eta,0),getMuResCorr(tag->eta,0));
	  }
	  else
	    {
	      Mu_Pt=tag->pt;
	    }

	  if(Mu_Pt>Pt1)
	    {
	      Pt2=Pt1;
	      Pt1=Mu_Pt;
	    }
	  else if(Mu_Pt>Pt2&&Mu_Pt<Pt1)
	    {
	      Pt2=Mu_Pt;
	    }

          if(!isMuonTriggerObj(triggerMenu, tag->hltMatchBits, kFALSE)) continue;

	  if(Mu_Pt<tagPt) continue;

	  tagPt=Mu_Pt;
	  itag=i1;
        
          // apply scale and resolution corrections to MC
          if(doScaleCorr && snamev[isam].CompareTo("data",TString::kIgnoreCase)!=0) {
            vTag.SetPtEtaPhiM(tagpt_corr,tag->eta,tag->phi,MUON_MASS);
            vTagSta.SetPtEtaPhiM(gRandom->Gaus(tag->staPt*getMuScaleCorr(tag->eta,0),getMuResCorr(tag->eta,0)),tag->staEta,tag->staPhi,MUON_MASS);
          } else {
            vTag.SetPtEtaPhiM(tag->pt,tag->eta,tag->phi,MUON_MASS);
            vTagSta.SetPtEtaPhiM(tag->staPt,tag->staEta,tag->staPhi,MUON_MASS);
          }

	  trkIso1     = tag->trkIso;
	  emIso1      = tag->ecalIso;	    
	  hadIso1     = tag->hcalIso;
	  pfChIso1    = tag->chHadIso;
	  pfGamIso1   = tag->gammaIso;
	  pfNeuIso1   = tag->neuHadIso;
	  pfCombIso1  = tag->chHadIso + TMath::Max(tag->neuHadIso + tag->gammaIso - 
						   0.5*(tag->puIso),Double_t(0));
	  d01         = tag->d0;
	  dz1         = tag->dz;
	  muNchi21    = tag->muNchi2;
	  nPixHits1   = tag->nPixHits;
	  nTkLayers1  = tag->nTkLayers;
	  nMatch1     = tag->nMatchStn;
	  nValidHits1 = tag->nValidHits;
	  typeBits1   = tag->typeBits;
	  q1 = tag->q;
	}

	if(tagPt<Pt2) continue;

	TLorentzVector vProbe(0,0,0,0); TLorentzVector vProbeSta(0,0,0,0);
	Double_t probePt=0;
	Int_t passID=false;
	UInt_t icat=0;

	for(Int_t i2=0; i2<muonArr->GetEntriesFast(); i2++) {
	  if(itag==i2) continue;
	  const baconhep::TMuon *probe = (baconhep::TMuon*)((*muonArr)[i2]);
	  

	  // apply scale and resolution corrections to MC
	  Double_t probept_corr = probe->pt;
	  if(doScaleCorr && snamev[isam].CompareTo("data",TString::kIgnoreCase)!=0)
	    probept_corr = gRandom->Gaus(probe->pt*getMuScaleCorr(probe->eta,0),getMuResCorr(probe->eta,0));

	  if(probept_corr     < PT_CUT)  continue;  // lepton pT cut
	  if(fabs(probe->eta) > ETA_CUT) continue;  // lepton |eta| cut

	  double Mu_Pt=probept_corr;
  
	  if(passID&&passMuonID(probe)&&Mu_Pt<probePt) continue;
	  if(passID&&!passMuonID(probe)) continue;
	  if(!passID&&!passMuonID(probe)&&Mu_Pt<probePt) continue;

	  if(!passID&&passMuonID(probe)) passID=true;

	  probePt=Mu_Pt;

	  // apply scale and resolution corrections to MC
	  if(doScaleCorr && snamev[isam].CompareTo("data",TString::kIgnoreCase)!=0) {
	    vProbe.SetPtEtaPhiM(probept_corr,probe->eta,probe->phi,MUON_MASS);
	    if(probe->typeBits & baconhep::EMuType::kStandalone)
	      vProbeSta.SetPtEtaPhiM(gRandom->Gaus(probe->staPt*getMuScaleCorr(probe->eta,0),getMuResCorr(probe->eta,0)),probe->staEta,probe->staPhi,MUON_MASS);
	  } else {
	    vProbe.SetPtEtaPhiM(probe->pt,probe->eta,probe->phi,MUON_MASS);
	    if(probe->typeBits & baconhep::EMuType::kStandalone)
	      vProbeSta.SetPtEtaPhiM(probe->staPt,probe->staEta,probe->staPhi,MUON_MASS);
	  }

	  trkIso2     = probe->trkIso;
	  emIso2      = probe->ecalIso;
	  hadIso2     = probe->hcalIso;
	  pfChIso2    = probe->chHadIso;
	  pfGamIso2   = probe->gammaIso;
	  pfNeuIso2   = probe->neuHadIso;
	  pfCombIso2  = probe->chHadIso + TMath::Max(probe->neuHadIso + probe->gammaIso - 
						     0.5*(probe->puIso),Double_t(0));
	  d02         = probe->d0;
	  dz2         = probe->dz;
	  muNchi22    = probe->muNchi2;
	  nPixHits2   = probe->nPixHits;
	  nTkLayers2  = probe->nTkLayers;
	  nMatch2     = probe->nMatchStn;
	  nValidHits2 = probe->nValidHits;
	  typeBits2   = probe->typeBits;
	  q2 = probe->q;

	  // determine event category
	  if(passMuonID(probe)) {
	    if(isMuonTriggerObj(triggerMenu, probe->hltMatchBits, kFALSE)) {
	      icat=eMuMu2HLT;
	    }
	    else if(isMuonTriggerObj(triggerMenu, probe->hltMatchBits, kTRUE)) {
	      icat=eMuMu1HLT1L1;
	  }
	    else {
	      icat=eMuMu1HLT;
	    }
	  }
	  else if(probe->typeBits & baconhep::EMuType::kGlobal) { icat=eMuMuNoSel; }
	  else if(probe->typeBits & baconhep::EMuType::kStandalone) { icat=eMuSta; }
	  else if(probe->nTkLayers>=6 && probe->nPixHits>=1)        { icat=eMuTrk; }
	}
	
	if(q1 == q2)         continue;  // opposite charge requirement
	    
	// mass window
	TLorentzVector vDilep = vTag + vProbe;
	if((vDilep.M()<MASS_LOW) || (vDilep.M()>MASS_HIGH)) continue;
	
	if(icat==0) continue;
	
	/******** We have a Z candidate! HURRAY! ********/
	nsel+=weight;
	nselvar+=weight*weight;
	
	// Perform matching of dileptons to GEN leptons from Z decay

	Int_t glepq1=-99;
	Int_t glepq2=-99;
	TLorentzVector *gvec=new TLorentzVector(0,0,0,0);
	TLorentzVector *glep1=new TLorentzVector(0,0,0,0);
	TLorentzVector *glep2=new TLorentzVector(0,0,0,0);
	TLorentzVector *gph=new TLorentzVector(0,0,0,0);
	Bool_t hasGenMatch = kFALSE;
	if(isSignal && hasGen) {
	  toolbox::fillGen(genPartArr, BOSON_ID, gvec, glep1, glep2,&glepq1,&glepq2,1);
	  
	  Bool_t match1 = ( ((glep1) && toolbox::deltaR(vTag.Eta(), vTag.Phi(), glep1->Eta(), glep1->Phi())<0.5) ||
			    ((glep2) && toolbox::deltaR(vTag.Eta(), vTag.Phi(), glep2->Eta(), glep2->Phi())<0.5) );
	  
	  Bool_t match2 = ( ((glep1) && toolbox::deltaR(vProbe.Eta(), vProbe.Phi(), glep1->Eta(), glep1->Phi())<0.5) ||
			    ((glep2) && toolbox::deltaR(vProbe.Eta(), vProbe.Phi(), glep2->Eta(), glep2->Phi())<0.5) );

	  if(match1 && match2) {
	    hasGenMatch = kTRUE;
	    if (gvec!=0) {
	      genV=new TLorentzVector(0,0,0,0);
	      genV->SetPtEtaPhiM(gvec->Pt(), gvec->Eta(), gvec->Phi(), gvec->M());
	      genVPt   = gvec->Pt();
	      genVPhi  = gvec->Phi();
	      genVy    = gvec->Rapidity();
	      genVMass = gvec->M();
	    }
	    else {
	      TLorentzVector tvec=*glep1+*glep2;
	      genV=new TLorentzVector(0,0,0,0);
	      genV->SetPtEtaPhiM(tvec.Pt(), tvec.Eta(), tvec.Phi(), tvec.M());
	      genVPt   = tvec.Pt();
	      genVPhi  = tvec.Phi();
	      genVy    = tvec.Rapidity();
	      genVMass = tvec.M();
	    }
	    delete gvec;
	    delete glep1;
	    delete glep2;
	    glep1=0; glep2=0; gvec=0;
	  }
	  else {
	    genV     = new TLorentzVector(0,0,0,0); 
	    genVPt   = -999;
	    genVPhi  = -999;
	    genVy    = -999;
	    genVMass = -999;
	  }
	}
	
	if (hasGen) {
	  id_1      = gen->id_1;
	  id_2      = gen->id_2;
	  x_1       = gen->x_1;
	  x_2       = gen->x_2;
	  xPDF_1    = gen->xPDF_1;
	  xPDF_2    = gen->xPDF_2;
	  scalePDF  = gen->scalePDF;
	  weightPDF = gen->weight;
	}
	else {
	  id_1      = -999;
	  id_2      = -999;
	  x_1       = -999;
	  x_2       = -999;
	  xPDF_1    = -999;
	  xPDF_2    = -999;
	  scalePDF  = -999;
	  weightPDF = -999;
	}
	
	//
	// Fill tree
	//
	runNum   = info->runNum;
	lumiSec  = info->lumiSec;
	evtNum   = info->evtNum;
	
	if (hasGenMatch) matchGen=1;
	else matchGen=0;
	
	category = icat;
	
	vertexArr->Clear();
	vertexBr->GetEntry(ientry);
	
	npv      = vertexArr->GetEntries();
	npu      = info->nPUmean;
	genWeight= hasGen ? gen->weight: 1.;
	PUWeight = puWeight;
	scale1fb = weight;
	scale1fbUp = weightUp;
	scale1fbDown = weightDown;
	met      = info->pfMETC;
	metPhi   = info->pfMETCphi;
	sumEt    = 0;
	tkMet    = info->trkMET;
	tkMetPhi = info->trkMETphi;
	tkSumEt  = 0;
	mvaMet   = info->mvaMET;
	mvaMetPhi = info->mvaMETphi;
	mvaSumEt = 0;
	TVector2 vZPt((vDilep.Pt())*cos(vDilep.Phi()),(vDilep.Pt())*sin(vDilep.Phi()));

        puppiMet = info->puppET;
        puppiMetPhi = info->puppETphi;
	puppiSumEt = 0;
	lep1     = &vTag;
	lep2     = &vProbe;
	dilep    = &vDilep;
	sta1        = &vTagSta;
	sta2        = &vProbeSta;
	
	TVector2 vMet((info->pfMETC)*cos(info->pfMETCphi), (info->pfMETC)*sin(info->pfMETCphi));
	TVector2 vU = -1.0*(vMet+vZPt);
	u1 = ((vDilep.Px())*(vU.Px()) + (vDilep.Py())*(vU.Py()))/(vDilep.Pt());  // u1 = (pT . u)/|pT|
	u2 = ((vDilep.Px())*(vU.Py()) - (vDilep.Py())*(vU.Px()))/(vDilep.Pt());  // u2 = (pT x u)/|pT|
	
	TVector2 vTkMet((info->trkMET)*cos(info->trkMETphi), (info->trkMET)*sin(info->trkMETphi));
	TVector2 vTkU = -1.0*(vTkMet+vZPt);
	tkU1 = ((vDilep.Px())*(vTkU.Px()) + (vDilep.Py())*(vTkU.Py()))/(vDilep.Pt());  // u1 = (pT . u)/|pT|
	tkU2 = ((vDilep.Px())*(vTkU.Py()) - (vDilep.Py())*(vTkU.Px()))/(vDilep.Pt());  // u2 = (pT x u)/|pT|
	
	TVector2 vMvaMet((info->mvaMET)*cos(info->mvaMETphi), (info->mvaMET)*sin(info->mvaMETphi));
	TVector2 vMvaU = -1.0*(vMvaMet+vZPt);
	mvaU1 = ((vDilep.Px())*(vMvaU.Px()) + (vDilep.Py())*(vMvaU.Py()))/(vDilep.Pt());  // u1 = (pT . u)/|pT|
	mvaU2 = ((vDilep.Px())*(vMvaU.Py()) - (vDilep.Py())*(vMvaU.Px()))/(vDilep.Pt());  // u2 = (pT x u)/|pT|
        
        TVector2 vPuppiMet((info->puppET)*cos(info->puppETphi), (info->puppET)*sin(info->puppETphi));
	TVector2 vPuppiU = -1.0*(vPuppiMet+vZPt);
	puppiU1 = ((vDilep.Px())*(vPuppiU.Px()) + (vDilep.Py())*(vPuppiU.Py()))/(vDilep.Pt());  // u1 = (pT . u)/|pT|
	puppiU2 = ((vDilep.Px())*(vPuppiU.Py()) - (vDilep.Py())*(vPuppiU.Px()))/(vDilep.Pt());  // u2 = (pT x u)/|pT|
	
        outTree->Fill();
	delete genV;
	genV=0, dilep=0, lep1=0, lep2=0, sta1=0, sta2=0;
      }
      delete infile;
      infile=0, eventTree=0;    
      
      cout << nsel  << " +/- " << sqrt(nselvar);
      if(!isData) cout << " per 1/fb";
      cout << endl;
    }
    outFile->Write();
    outFile->Close(); 
  }
  delete h_rw;
  delete h_rw_up;
  delete h_rw_down;
  delete f_rw;
  delete info;
  delete gen;
  delete genPartArr;
  delete muonArr;
  delete vertexArr;
    
  //--------------------------------------------------------------------------------------------------------------
  // Output
  //==============================================================================================================
   
  cout << "*" << endl;
  cout << "* SUMMARY" << endl;
  cout << "*--------------------------------------------------" << endl;
  cout << " Z -> mu mu" << endl;
  cout << "  Mass window: [" << MASS_LOW << ", " << MASS_HIGH << "]" << endl;
  cout << "  pT > " << PT_CUT << endl;
  cout << "  |eta| < " << ETA_CUT << endl;
  cout << endl;
  
  cout << endl;
  cout << "  <> Output saved in " << outputDir << "/" << endl;    
  cout << endl;  
      
  gBenchmark->Show("selectZmm"); 
}
Beispiel #22
0
//________________________________________________________________
void KVCalorimetry::SumUp()
{
   // protected method
   // Appelé par Calculate pour mettre à jour les différents ingrédients
   // de la calorimétrie :
   //
   // Trois modes de sommes:
   //------------------
   // - mode normal (par defaut)
   // détermination de l excès de masse de la source recontruite, dernier ingrédient de l'équation :
   // Exci + Qini  = \Sigma Ek + \Sigma Q -> Exci = \Sigma Ek + \Sigma Q - Qini
   //
   // - mode avec distinction particules / fragments, actif si la méthode
   // UseChargeDiff(Int_t FragmentMinimumCharge,Double_t ParticleFactor) a été appelée :
   // -> une distinction entre produits avec une charge strictement inférieur à FragmentMinimumCharge (particules)
   // et supérieur ou égale (fragments) est appliquée
   // Ainsi dans la méthode SumUp() pour les énergies cinétiques, par exemple
   // l'énergie cinétique de la source reconstruite sera
   // Eksum = Ekfrag(Z>=[FragmentMinimumCharge]) + [ParticleFactor]*Ekpart(Z<[FragmentMinimumCharge])
   // Détermination ensuite de l excès de masse de la source
   //
   // - mode avec prise en compte des neutrons libres, actif si la métode
   // IncludeFreeNeutrons(Double_t AsurZ,Double_t NeutronMeanEnergyFactor,Double_t LevelDensityParameter)
   // L'estimation du nombre neutrons, est fait en utilisant un AsurZ (paramètre de la calorimétrie)
   // supposé de la source reconstruite :
   // le nombre de neutrons libres est alors égal :
   // Mn =  [AsurZ]*Zsum - Asum
   // Pour un Zsou reconstruit, on rajoute des neutrons pour que le Asou corresponde à un AsurZ prédéfini
   // On en déduit ensuite l'exces de masse asscoié à ces neutrons
   // Détermination ensuite de l excès de masse de la source

   // Les proprietes de la source sont calculees

   if (kchargediff) {
      // somme des contributions fragments et particules
      AddIngValue("Zsum", GetIngValue("Zfrag") + GetParValue("ParticleFactor")*GetIngValue("Zpart"));
      AddIngValue("Asum", GetIngValue("Afrag") + GetParValue("ParticleFactor")*GetIngValue("Apart"));
      AddIngValue("Eksum", GetIngValue("Ekfrag") + GetParValue("ParticleFactor")*GetIngValue("Ekpart"));
      AddIngValue("Qsum", GetIngValue("Qfrag") + GetParValue("ParticleFactor")*GetIngValue("Qpart"));
      AddIngValue("Msum", GetIngValue("Mfrag") + GetParValue("ParticleFactor")*GetIngValue("Mpart"));
   }

   //printf("Eksum=%lf avant neutrons \n",GetIngValue("Eksum"));

   if (kfree_neutrons_included) {
      // conservation du AsurZ du systeme --> multiplicite moyenne des neutrons
      Double_t Mneutron = Double_t(TMath::Nint(GetParValue("AsurZ") * GetIngValue("Zsum") - GetIngValue("Asum")));
      if (Mneutron < 0) {
         //Warning("SumUp","Nombre de neutrons déduits négatif : %1.0lf -> on le met à zéro",Mneutron);
         SetIngValue("Aexcess", TMath::Abs(Mneutron));
         Mneutron = 0;
      }
      SetIngValue("Aneu", Mneutron);
      SetIngValue("Qneu", Mneutron * nn.GetMassExcess(0, 1));
      SetIngValue("Mneu", Mneutron);

      // prise en compte des neutrons dans la source
      AddIngValue("Asum", GetIngValue("Mneu"));
      AddIngValue("Qsum", GetIngValue("Qneu"));
      AddIngValue("Msum", GetIngValue("Mneu"));

   }
   //printf("Eksum=%lf apres neutrons \n",GetIngValue("Eksum"));
   // defaut de masse de la source reconstruite
   KVCaloBase::SumUp();

}
void
plot2DSignalHisto(
    TString filename1,
    TString filename2, 
    TString histogramName,
//    TString drawopts = "",
    TString xtitle = "x",
    TString ytitle = "y",
    double xtitleOffset = 1.1,
    double ytitleOffset = 1.3
    )
{
// {{{
    InitgStyle();
    //gStyle->SetOptStat(0);
    //gCanvas = new TCanvas("gCanvas", "gCanvas", 0, 0, 800, 600);
    
    TFile *outputFile = new TFile("FitErgebnisse.root","RECREATE");
    TH2D *histogram__DiffAbs = new TH2D("histogram__DiffAbs","Differenz Fit - Input (Absolut)", 5, -1, 1, 5, -1, 1);
    TH2D *histogram__DiffRel = new TH2D("histogram__DiffRel","Differenz Fit - Input (Relativ)", 5, -1, 1, 5, -1, 1);
    TH2D *histogram__FitResult = new TH2D("histogram__FitResult ", "Ergebnis-Histogramm des Fits", 5, -1, 1, 5, -1, 1);


    
//    LoadHistogramTH2D(histogramName , filename1, 1.0, histogram);// Summe (SM)
    LoadHistogramTH2D("histogram__Correlation"+histogramName , filename1, 1.0, histogram);// Summe (SM

    //LoadHistogramTH2D(histogramName+"_LL" , filename2, 1.0, histo1);	// LL
    //LoadHistogramTH2D(histogramName+"_LR" , filename2, 1.0, histo2);	// LR
    //LoadHistogramTH2D(histogramName+"_RL" , filename2, 1.0, histo3);	// RL
    //LoadHistogramTH2D(histogramName+"_RR" , filename2, 1.0, histo4);	// RR
    
    //LoadHistogramTH2D("histogram__gen_N" , filename2, 1.0, histo1);
    //LoadHistogramTH2D("histogram__gen_A" , filename2, 1.0, histo2);
    
    LoadHistogramTH2D("histogram__N"+histogramName , filename2, 1.0, histo1);
    LoadHistogramTH2D("histogram__A"+histogramName , filename2, 1.0, histo2);


    //gCanvas->Clear();
  

    histogram->GetXaxis()->SetTitle(xtitle);
    histogram->GetXaxis()->SetTitleOffset(xtitleOffset);
    histogram->GetYaxis()->SetTitle(ytitle);
    histogram->GetYaxis()->SetTitleOffset(ytitleOffset);
    //histogram->GetZaxis()->SetTitle("d^{2}#sigma / dM_{#bar{t}}dM_{t} [pb]");
    //histogram->GetZaxis()->SetTitleOffset(ytitleOffset);

//    gCanvas->Update();

    /*    
    histo1->Scale(1.0/histo4->Integral());
    histo2->Scale(1.0/histo4->Integral());
    histo3->Scale(1.0/histo4->Integral());
    histo4->Scale(1.0/histo4->Integral());
    */

       
    //faktor = 1.0;
    faktor=Double_t(histogram->Integral())/Double_t(histo1->Integral());
    cout<<faktor<<endl; 
    
    TF2 *fitFunction = new TF2("fitFunction", HistoSum, -1, 1, -1, 1, 2);  //allgemeine "return"-Varianten
    //fitFunction->SetParameters(0.9,0.,0.);
    //fitFunction->SetLineColor(kRed);
    
    histogram->Fit(fitFunction, "N");
    fitFunction->SetNpx(5);
    fitFunction->SetNpy(5);
    
    double p0 = fitFunction->GetParameter(0);
    double p1 = fitFunction->GetParameter(1);
//    double p2 = fitFunction->GetParameter(2);
//    double p3 = fitFunction->GetParameter(3);

    for(int i =1; i <= 5; i++)
    {
        for(int j = 1; j <= 5; j++)
        {
            //double sigmaLL = p0*faktor*histo1->GetBinError(i,j);
            //double sigmaLR = p1*faktor*histo2->GetBinError(i,j);
            //double sigmaRL = p2*faktor*histo3->GetBinError(i,j);
            //double sigmaRR = p3*faktor*histo4->GetBinError(i,j);
            double sigmaN = p0*faktor*histo1->GetBinError(i,j);
            double sigmaA = p1*faktor*histo2->GetBinError(i,j);
            //histogram->SetBinError(i,j, sqrt( histogram->GetBinContent(i,j) + pow(sigmaLL,2) + pow(sigmaRR,2) + pow(sigmaRL,2) + pow(sigmaLR, 2) ));
            histogram->SetBinError(i,j, sqrt( histogram->GetBinContent(i,j) + pow(sigmaN,2) + pow(sigmaA,2) ));
        }
    }
    histogram->Fit(fitFunction, "NE");

    p0 = fitFunction->GetParameter(0);
    p1 = fitFunction->GetParameter(1);

    for(int i =1; i <= 5; i++)
    {
        for(int j = 1; j <= 5; j++)
        {
            //double sigmaLL = p0*faktor*histo1->GetBinError(i,j);
            //double sigmaLR = p1*faktor*histo2->GetBinError(i,j);
            //double sigmaRL = p2*faktor*histo3->GetBinError(i,j);
            //double sigmaRR = p3*faktor*histo4->GetBinError(i,j);
            double sigmaN = p0*faktor*histo1->GetBinError(i,j);
            double sigmaA = p1*faktor*histo2->GetBinError(i,j);
            //histogram->SetBinError(i,j, sqrt( histogram->GetBinContent(i,j) + pow(sigmaLL,2) + pow(sigmaRR,2) + pow(sigmaRL,2) + pow(sigmaLR, 2) ));
            histogram->SetBinError(i,j, sqrt( histogram->GetBinContent(i,j) + pow(sigmaN,2) + pow(sigmaA,2) ));
        }
    }
    histogram->Fit(fitFunction, "NE");

        
    //histogram->Draw("lego1");  
    //fitFunction->Draw("lego");
    cout << fitFunction->GetChisquare()/fitFunction->GetNDF() << endl;

    for(int i = 1; i <= 5; i++)
    {
        for(int j = 1; j <= 5; j++)
        {
            histogram__DiffAbs->SetBinContent(i,j, fitFunction->Eval(histogram->GetXaxis()->GetBinCenter(i),histogram->GetYaxis()->GetBinCenter(j))-histogram->GetBinContent(i,j) );
            histogram__DiffRel->SetBinContent(i,j, (fitFunction->Eval(histogram->GetXaxis()->GetBinCenter(i),histogram->GetYaxis()->GetBinCenter(j))-histogram->GetBinContent(i,j))/histogram->GetBinContent(i,j) );
            histogram__FitResult->SetBinContent(i,j, fitFunction->Eval(histogram->GetXaxis()->GetBinCenter(i),histogram->GetYaxis()->GetBinCenter(j)));
        }
    }
    
        
    outputFile->cd("");
    histogram__DiffAbs->Write("histogram__DiffAbs");
    histogram__DiffRel->Write("histogram__DiffRel");
    histogram__FitResult->Write("histogram__FitResult");
    outputFile->Close();
    delete outputFile;
       
    
    //gCanvas->Print(epsFilename(filename, histogramName)+".eps");
	//cout << histogram[0]->Integral() << endl;
// }}}
};
Beispiel #24
0
void FFT()
{

//This tutorial illustrates the Fast Fourier Transforms interface in ROOT.
//FFT transform types provided in ROOT:
// - "C2CFORWARD" - a complex input/output discrete Fourier transform (DFT) 
//                  in one or more dimensions, -1 in the exponent
// - "C2CBACKWARD"- a complex input/output discrete Fourier transform (DFT) 
//                  in one or more dimensions, +1 in the exponent
// - "R2C"        - a real-input/complex-output discrete Fourier transform (DFT)
//                  in one or more dimensions,
// - "C2R"        - inverse transforms to "R2C", taking complex input 
//                  (storing the non-redundant half of a logically Hermitian array) 
//                  to real output
// - "R2HC"       - a real-input DFT with output in ¡Èhalfcomplex¡É format, 
//                  i.e. real and imaginary parts for a transform of size n stored as
//                  r0, r1, r2, ..., rn/2, i(n+1)/2-1, ..., i2, i1
// - "HC2R"       - computes the reverse of FFTW_R2HC, above
// - "DHT"        - computes a discrete Hartley transform
// Sine/cosine transforms:
//  DCT-I  (REDFT00 in FFTW3 notation)
//  DCT-II (REDFT10 in FFTW3 notation)
//  DCT-III(REDFT01 in FFTW3 notation)
//  DCT-IV (REDFT11 in FFTW3 notation)
//  DST-I  (RODFT00 in FFTW3 notation)
//  DST-II (RODFT10 in FFTW3 notation)
//  DST-III(RODFT01 in FFTW3 notation)
//  DST-IV (RODFT11 in FFTW3 notation)
//First part of the tutorial shows how to transform the histograms
//Second part shows how to transform the data arrays directly
//Authors: Anna Kreshuk and Jens Hoffmann


//********* Histograms ********//


   //prepare the canvas for drawing
   TCanvas *myc = new TCanvas("myc", "Fast Fourier Transform", 800, 600);
   myc->SetFillColor(45);
   TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.67,0.49,0.99);
   TPad *c1_2 = new TPad("c1_2", "c1_2",0.51,0.67,0.99,0.99);
   TPad *c1_3 = new TPad("c1_3", "c1_3",0.01,0.34,0.49,0.65);
   TPad *c1_4 = new TPad("c1_4", "c1_4",0.51,0.34,0.99,0.65);
   TPad *c1_5 = new TPad("c1_5", "c1_5",0.01,0.01,0.49,0.32);
   TPad *c1_6 = new TPad("c1_6", "c1_6",0.51,0.01,0.99,0.32);
   c1_1->Draw();
   c1_2->Draw();
   c1_3->Draw();
   c1_4->Draw();
   c1_5->Draw();
   c1_6->Draw();
   c1_1->SetFillColor(30);
   c1_1->SetFrameFillColor(42);
   c1_2->SetFillColor(30);
   c1_2->SetFrameFillColor(42);
   c1_3->SetFillColor(30);
   c1_3->SetFrameFillColor(42);
   c1_4->SetFillColor(30);
   c1_4->SetFrameFillColor(42);
   c1_5->SetFillColor(30);
   c1_5->SetFrameFillColor(42);
   c1_6->SetFillColor(30);
   c1_6->SetFrameFillColor(42);
   
   c1_1->cd();
   TH1::AddDirectory(kFALSE);
     
   //A function to sample
   TF1 *fsin = new TF1("fsin", "exp(-(x-679.)/40.0)*TMath::Erfc(-(1/sqrt(2))*((x-679.)/2.0 + 0.05))", 0, 1023);
   TF1 *model = new TF1("model", "[0]*exp(-(x-[1])/[2])*TMath::Erfc(-(1/sqrt(2))*((x-[1])/[3] + [3]/[2]))", 0, 1023);
   model->SetParameter( 0, 1. );
   model->SetParameter( 1, 679. );
   model->SetParameter( 2, 40. );
   model->SetParameter( 3, 2. );
   model->SetLineColor( kViolet );
   
   TF1 *model2 = new TF1("model2", "[0]*exp(-(x-[1])/[2])*TMath::Erfc(-(1/sqrt(2))*((x-[1])/[3] + [3]/[2])) + [4]*sin(2*TMath::Pi()*[5]*x)", 0, 1023);
   model2->SetParameter( 0, 1. );
   model2->SetParameter( 1, 679. );
   model2->SetParameter( 2, 40. );
   model2->SetParameter( 3, 2. );
   model2->SetParameter( 4, 0.05 );
   model2->SetParameter( 5, 2. );
   model2->SetLineColor( kViolet );
   //fsin->Draw();
   
   Int_t n=1024;
   TH1D *hsin = new TH1D("hsin", "hsin", n+1, 0, 1023);
   Double_t x;
   //hsin->Fit( model,"MLR" );
   //Fill the histogram with function values
   for (Int_t i=0; i<=n; i++){
     /*
     if( i >= n/2 )
       {
	 x = (Double_t(i-(n/2+1))/n)*(160*TMath::Pi());
       }
     else
       {
	 x = -80*TMath::Pi()+(Double_t(i)/n)*(160*TMath::Pi());
       }
     */
     x = (Double_t(i)/n)*(1024);
     //std::cout << "n: " << i << " x: " << x << std::endl;
     hsin->SetBinContent(i+1, fsin->Eval(x));
   }
   
   hsin->Fit( model2,"MLR" );
   //TFile* fn = new TFile("/Users/cmorgoth/Software/git/TimingAna_New/CIT_Laser_022015_69_ana.root", "READ");
   TFile* fn = new TFile("/Users/cmorgoth/Work/data/LaserDataAtCaltech/02282015/CIT_Laser_022015_69_ana.root", "READ");
   TH1F* pulse = (TH1F*)fn->Get("CH2pulse");
   //hsin->Draw("same");
   hsin->SetLineColor(kGreen-4);
   hsin->Draw();
   model->Draw("same");
   //pulse->SetAxisRange(650, 780, "X");
   pulse->Scale(22.0);
   pulse->Draw("same");
   fsin->GetXaxis()->SetLabelSize(0.05);
   fsin->GetYaxis()->SetLabelSize(0.05);

   c1_2->cd();
   //Compute the transform and look at the magnitude of the output
   TH1 *hm =0;
   TVirtualFFT::SetTransform(0);
   //hm = hsin->FFT(hm, "MAG");
   hm = pulse->FFT(hm, "MAG");
   hm->SetTitle("Magnitude of the 1st transform");
   //hm->Draw();
   double sf = 5e3;//to go from sample to picosecons and also from Hz to MHz
   double range = sf*(double)n/(1023.);
   int n_bin_fft = hm->GetNbinsX();
   TH1F* hmr = new TH1F( "hmr" ,"Magnitude of the 1st transform Rescaled", n_bin_fft, 0, range);
   for( int i = 1; i <= n_bin_fft; i++)
     {
       double bc = hm->GetBinContent( i )/sqrt( n );
       hmr->SetBinContent( i, bc );
     }
   hmr->SetXTitle("f (MHz)");
   hmr->Draw();
   //Transfor to the theoretical function
   TH1 *hm2 =0;
   TVirtualFFT::SetTransform(0);
   hm2 = hsin->FFT(hm2, "MAG");
   hm2->SetLineColor(2);
   //hm2->Draw("same");
   TH1F* hmr2 = new TH1F( "hmr2" ,"Magnitude of the 1st transform Rescaled", n_bin_fft, 0, range);
   for( int i = 1; i <= n_bin_fft; i++)
     {
       double bc = hm2->GetBinContent( i )/sqrt( n );
       hmr2->SetBinContent( i, bc );
     }
   hmr2->SetLineColor( kRed );
   hmr2->Draw("same");
   //NOTE: for "real" frequencies you have to divide the x-axes range with the range of your function 
   //(in this case 4*Pi); y-axes has to be rescaled by a factor of 1/SQRT(n) to be right: this is not done automatically!
   hm->SetStats(kFALSE);
   hm->GetXaxis()->SetLabelSize(0.05);
   hm->GetYaxis()->SetLabelSize(0.05);

   
   c1_3->cd();   
   //Look at the phase of the output   
   TH1 *hp = 0;
   hp = hsin->FFT(hp, "PH");
   hp->SetTitle("Phase of the 1st transform");
   hp->Draw();
   hp->SetStats(kFALSE);
   hp->GetXaxis()->SetLabelSize(0.05);
   hp->GetYaxis()->SetLabelSize(0.05);
   
   //Look at the DC component and the Nyquist harmonic:
   Double_t re, im;
   //That's the way to get the current transform object:
   TVirtualFFT *fft = TVirtualFFT::GetCurrentTransform();
   c1_4->cd();
   //Use the following method to get just one point of the output
   fft->GetPointComplex(0, re, im);
   printf("1st transform: DC component: %f\n", re);
   fft->GetPointComplex(n/2+1, re, im);
   printf("1st transform: Nyquist harmonic: %f\n", re);

   //Use the following method to get the full output:
   Double_t *re_full = new Double_t[n];
   Double_t *im_full = new Double_t[n];
   fft->GetPointsComplex(re_full,im_full);
  
   //Now let's make a backward transform:
   TVirtualFFT *fft_back = TVirtualFFT::FFT(1, &n, "C2R M K");
   fft_back->SetPointsComplex(re_full,im_full);
   fft_back->Transform();
   TH1 *hb = 0;
   //Let's look at the output
   hb = TH1::TransformHisto(fft_back,hb,"Re");
   hb->SetTitle("The backward transform result");
   hb->Draw();
   //NOTE: here you get at the x-axes number of bins and not real values
   //(in this case 25 bins has to be rescaled to a range between 0 and 4*Pi; 
   //also here the y-axes has to be rescaled (factor 1/bins)
   hb->SetStats(kFALSE);
   hb->GetXaxis()->SetLabelSize(0.05);
   hb->GetYaxis()->SetLabelSize(0.05);
   delete fft_back;
   fft_back=0;

//********* Data array - same transform ********//

   //Allocate an array big enough to hold the transform output
   //Transform output in 1d contains, for a transform of size N, 
   //N/2+1 complex numbers, i.e. 2*(N/2+1) real numbers
   //our transform is of size n+1, because the histogram has n+1 bins

   Double_t *in = new Double_t[2*((n+1)/2+1)];
   Double_t re_2,im_2;
   for (Int_t i=0; i<=n; i++){
      x = (Double_t(i)/n)*(4*TMath::Pi());
      in[i] =  fsin->Eval(x);
   }

   //Make our own TVirtualFFT object (using option "K")
   //Third parameter (option) consists of 3 parts:
   //-transform type:
   // real input/complex output in our case
   //-transform flag: 
   // the amount of time spent in planning
   // the transform (see TVirtualFFT class description)
   //-to create a new TVirtualFFT object (option "K") or use the global (default)
   Int_t n_size = n+1;
   TVirtualFFT *fft_own = TVirtualFFT::FFT(1, &n_size, "R2C ES K");
   if (!fft_own) return;
   fft_own->SetPoints(in);
   fft_own->Transform();

   //Copy all the output points:
   fft_own->GetPoints(in);
   //Draw the real part of the output
   c1_5->cd();
   TH1 *hr = 0;
   hr = TH1::TransformHisto(fft_own, hr, "RE");
   hr->SetTitle("Real part of the 3rd (array) tranfsorm");
   hr->Draw();
   hr->SetStats(kFALSE);
   hr->GetXaxis()->SetLabelSize(0.05);
   hr->GetYaxis()->SetLabelSize(0.05);
   c1_6->cd();
   TH1 *him = 0;
   him = TH1::TransformHisto(fft_own, him, "IM");
   him->SetTitle("Im. part of the 3rd (array) transform");
   him->Draw();
   him->SetStats(kFALSE);
   him->GetXaxis()->SetLabelSize(0.05);
   him->GetYaxis()->SetLabelSize(0.05);

   myc->cd();
   //Now let's make another transform of the same size
   //The same transform object can be used, as the size and the type of the transform
   //haven't changed
   TF1 *fcos = new TF1("fcos", "cos(x)+cos(0.5*x)+cos(2*x)+1", 0, 4*TMath::Pi());
   for (Int_t i=0; i<=n; i++){
      x = (Double_t(i)/n)*(4*TMath::Pi());
      in[i] =  fcos->Eval(x);
   }
   fft_own->SetPoints(in);
   fft_own->Transform();
   fft_own->GetPointComplex(0, re_2, im_2);
   printf("2nd transform: DC component: %f\n", re_2);
   fft_own->GetPointComplex(n/2+1, re_2, im_2);
   printf("2nd transform: Nyquist harmonic: %f\n", re_2);
   delete fft_own;
   delete [] in;
   delete [] re_full;
   delete [] im_full;
}
Beispiel #25
0
//___________________________________________________________________________________________
void KVValues::FillVar(Double_t val, Double_t weight)
{

   if (weight >= 0) {
      if (val < values[0]) values[0] = val; //GetIntValue("MIN")=0
      if (val > values[1]) values[1] = val; //GetIntValue("MAX")=1
   }
   for (Int_t nn = 0; nn <= kordre_mom_max; nn += 1) values[nn + kdeb] += weight * TMath::Power(val, Double_t(nn));
   kToBeRecalculated = kTRUE;
   kTimesFillVarIsCalled += 1;
}
Beispiel #26
0
void MUONTriggerEfficiency(const char* filenameSim="galice_sim.root", 
                           const char* filenameRec="galice.root",  
                           Bool_t readFromRP = 0)
{
  
  // Set default CDB storage
  AliCDBManager* man = AliCDBManager::Instance();
  man->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
  man->SetRun(0);
  
  // output file
  
  AliMUONMCDataInterface diSim(filenameSim);
  AliMUONDataInterface diRec(filenameRec);
  
  if (!diSim.IsValid())
  {
    cerr << "Cannot access " << filenameSim << endl;
    return;
  }
  
  if (!diRec.IsValid())
  {
    cerr << "Cannot access " << filenameRec << endl;
    return;
  }
  
  FILE* fdat = fopen("MUONTriggerEfficiency.out","w");          
  if (!fdat)
  {
    cerr << "Cannot create output file" << endl;
    return;
  }
  
  Int_t coincmuon,muonlpt,muonhpt;
  Int_t CoincMuPlus,CoincMuMinus;
  coincmuon=0;
  muonlpt=0;  
  muonhpt=0;
  
  Int_t nevents = diSim.NumberOfEvents();          
  
  for (Int_t ievent=0; ievent<nevents; ++ievent) 
  {   
    CoincMuPlus=0;
    CoincMuMinus=0;
    
    if (ievent%1000==0) printf("\t Event = %d\n",ievent);    
    
    // Hits
    
    Int_t NbHits[2][4];
    for (Int_t j=0; j<2; j++) 
    {
      for (Int_t jj=0; jj<4; jj++) 
      {
        NbHits[j][jj]=0;
      }
    } 
    
    Int_t ntracks = (Int_t) diSim.NumberOfTracks(ievent);
    
    for ( Int_t itrack=0; itrack<ntracks; ++itrack ) 
    {
      AliMUONVHitStore* hitStore = diSim.HitStore(ievent,itrack);      
      AliMUONHit* mHit;
      TIter next(hitStore->CreateIterator());
      
      while ( ( mHit = static_cast<AliMUONHit*>(next()) ) )
      {
        Int_t Nch = mHit->Chamber(); 
        Int_t hittrack = mHit->Track();
        Float_t IdPart = mHit->Particle();
        
        for (Int_t j=0;j<4;j++) 
        {
          Int_t kch=11+j;
          if (hittrack==1 || hittrack==2) 
          {
            if (Nch==kch && IdPart==-13 && NbHits[0][j]==0) NbHits[0][j]++; 
            if (Nch==kch && IdPart==13 && NbHits[1][j]==0) NbHits[1][j]++; 
          }       
        }
      }
    } // end track loop     
    
    // 3/4 coincidence
    Int_t SumNbHits=NbHits[0][0]+NbHits[0][1]+NbHits[0][2]+NbHits[0][3];
    if (SumNbHits==3 || SumNbHits==4) CoincMuPlus=1;
    
    SumNbHits=NbHits[1][0]+NbHits[1][1]+NbHits[1][2]+NbHits[1][3];
    if (SumNbHits==3 || SumNbHits==4) CoincMuMinus=1;
    
    if (CoincMuPlus==1 && CoincMuMinus==1) coincmuon++;         
          
    TString tree("D");
    if ( readFromRP ) tree = "R";
    
    AliMUONVTriggerStore* triggerStore = diRec.TriggerStore(ievent,tree.Data());

    AliMUONGlobalTrigger* gloTrg = triggerStore->Global();
    
    if (gloTrg->PairUnlikeLpt()>=1) muonlpt++;
    if (gloTrg->PairUnlikeHpt()>=1) muonhpt++;

  } // end loop on event  
 
  // calculate efficiency with as a ref. at least 3/4 planes fired
  Float_t efficiencylpt,efficiencyhpt;
  Double_t coincmu,lptmu,hptmu;  
  Float_t error;  
  coincmu=Double_t(coincmuon);
  lptmu=Double_t(muonlpt); 
  hptmu=Double_t(muonhpt); 

  // output
  fprintf(fdat,"\n"); 
  fprintf(fdat," Number of events = %d \n",nevents);  
  fprintf(fdat," Number of events with 3/4 coinc = %d \n",coincmuon);  
  fprintf(fdat," Nomber of dimuons with 3/4 coinc Lpt cut = %d \n",muonlpt);  
  fprintf(fdat," Number of dimuons with 3/4 coinc Hpt cut = %d \n",muonhpt);  
  fprintf(fdat,"\n");
  
  efficiencylpt=lptmu/coincmu;  
  error=efficiencylpt*TMath::Sqrt((lptmu+coincmu)/(lptmu*coincmu));  
  fprintf(fdat," Efficiency Lpt cut = %4.4f +/- %4.4f\n",efficiencylpt,error); 
 
  efficiencyhpt=hptmu/coincmu; 
  error=efficiencyhpt*TMath::Sqrt((hptmu+coincmu)/(hptmu*coincmu));          
  fprintf(fdat," Efficiency Hpt cut = %4.4f +/- %4.4f\n",efficiencyhpt,error);
      

  fclose(fdat);  
}
//___________________________________________________________________________________
void SliceH2(
  // input
  const TH2 *h, const TString &axis, const Int_t n, Double_t fitMin, Double_t fitMax, const Double_t &factorSigma,
  // output
  TGraphErrors &*grMean, TGraphErrors &*grSigma)
{
  // Slice the h
  // Fit each slice to the gaus
  
  // Arrays for the output graphs
  Double_t x[n]    = {0.};
  Double_t errX[n] = {0.};
  Double_t sigma[n]    = {0.};
  Double_t errSigma[n] = {0.};
  Double_t mean[n]    = {0.};
  Double_t errMean[n] = {0.};
  
  // Get # of bin in the h
  Int_t nbins = 0;
  TAxis *axisPr, *axisSliced;
  if (axis != "y")
  {
    cout << "X-projections" << endl;
    nbins = h->GetNbinsY();
    axisSliced = h->GetYaxis();
    axisPr = h->GetXaxis();
  }
  else
  {
    cout << "Y-projections" << endl;
    nbins = h->GetNbinsX();
    axisSliced = h->GetXaxis();
    axisPr = h->GetYaxis();
  }
  
  // Slice step
  Int_t step = 0;
  if ( n != 0 ) step = ceil(Double_t(nbins)/n);
  
  // Bin counter. The first bin = 1
  Int_t i = 1;
  
  // # of points in the output graphs
  Int_t nPoints = 0;
  
  // Make the slices
  TH1D *hTmp = NULL;
  TCanvas *cTmp = new TCanvas();
  Char_t buf[10];
  Double_t xTmp;
  TString nameTmp;
  Int_t iUp = (step != 0) ? i+step-1 : nbins+1;
  while ( iUp <= nbins )
  {
    xTmp = (axisSliced->GetBinLowEdge(i) + axisSliced->GetBinUpEdge(iUp))/2.;
    sprintf(buf,"%d",xTmp);
    nameTmp = TString(axisSliced->GetTitle())+" = "+TString(buf);
    if (axis != "y") hTmp = h->ProjectionX(nameTmp, i, iUp, "e");
    else             hTmp = h->ProjectionY(nameTmp, i, iUp, "e");
    hTmp->Draw();
    if (fitMin != fitMax) hTmp->Fit("gaus","","",fitMin,fitMax);
//     cTmp->WaitPrimitive();
    if ( hTmp->GetFunction("gaus") )
    {
      x[nPoints] = xTmp;
      sigma[nPoints]    = hTmp->GetFunction("gaus")->GetParameter(2)/factorSigma;
      errSigma[nPoints] = hTmp->GetFunction("gaus")->GetParError(2)/factorSigma;
      mean[nPoints]     = hTmp->GetFunction("gaus")->GetParameter(1);
      errMean[nPoints]  = hTmp->GetFunction("gaus")->GetParError(1);
      if ( errSigma[nPoints] < 99999.9 ) ++nPoints;
    }
    i += step;
    iUp = i+step-1;
    delete hTmp;
  }
  
  // "Sigma" graph
  grSigma = new TGraphErrors(nPoints,x,sigma,errX,errSigma);
  
  // "Mean" graph
  grMean = new TGraphErrors(nPoints,x,mean,errX,errMean);
  
  delete cTmp;
}
Beispiel #28
0
//
// AsymmetryCTH( bin, draw)
//
// Plots the full, empty, or subtracted asymmetry as a function of
// cos(theta) for a specific tagger-channel range.
//
// Bins run from 0-17.
//
void AsymmetryCTH( UInt_t bin = 0, Bool_t draw = kFALSE)
{
	UInt_t i, chan_lo, chan_hi, cthbins;
	UInt_t col;
	Double_t eg, deg;
	Double_t par[6], red_chisq;
	Double_t cth[9], dcth[9], as[9], das[9];
	Double_t polgrad;
	TString subt, name;

	if ( bin < 3) {
		chan_lo = 304 - 2*bin;
		chan_hi = chan_lo + 1;
	}
	else {
		chan_lo = 302 - bin;
		chan_hi = chan_lo;
	}

	if ( bin < 4) cthbins = 7;
	else cthbins = 9;

	TH1D* asym;
	TH1D* hscal;

	subt = "subt";
	if ( subt == "full") col = 4;
	else if ( subt == "empty") col = 2;
	else if ( subt == "subt") col = 1;

	hscal = (TH1D*) fparaFile.Get( "SumScalers152to503");
	eg = WeightedPar( hscal, "energy", chan_lo, chan_hi);
	deg = ((tcd[chan_lo].energy + tcd[chan_lo].denergy) -
		(tcd[chan_hi].energy - tcd[chan_hi].denergy))/2;

	// Everything is weighted to para...
	if ( subt != "empty") polgrad = WeightedPol( hscal, chan_lo, chan_hi, 1);
	else polgrad = WeightedPol( hscal, chan_hi, chan_hi, 3);

	cout << "polgrad = " << polgrad << endl;

	name = Form( "xs/pi0/asym/asymmetry_cth_%d.out", bin);
	ofstream outFile( name);
	if ( !outFile.is_open()) {
		cout << "Error opening file ";
		cout << name;
		cout << endl;
		break;
	}

	for ( i = 0; i <= cthbins; i++)
		name = Form( "asym_%s_%d_%d", subt.Data(), chan_lo, i+1);

	Double_t interval = 2/Double_t( cthbins);
	UInt_t cthb_lo, cthb_hi;
	for ( i = 0; i < cthbins; i++)
	{
		cth[i] = -1 + interval*(i + 0.5);
		dcth[i] = 0;

		cthb_lo = 1 + 63/cthbins*i;
		cthb_hi = 63/cthbins*(i + 1);

//		name = Form( "%1d %6.3f %2d %2d\n", i, cth[i], cthb_lo[i], cthb_hi[i]);
//		cout << name;

		Get1DHist( chan_lo, chan_hi, subt, cthb_lo, cthb_hi, kTRUE);
		name = Form( "asym_%s_%d_%d", subt.Data(), chan_lo, i+1);
		asym = (TH1D*) hA->Clone( name);
		hA->Reset();

		TF1 *f1 = new TF1( "f1", "[0]*cos(2*x*0.01745+[1])", -180, 180);
		asym->Fit( "f1", "REMQ0");
		par[0] = f1->GetParameter(0);
		par[1] = f1->GetParError(0);
		par[2] = f1->GetParameter(1);
		par[3] = f1->GetParError(1);
		red_chisq = f1->GetChisquare()/17;
		if ( par[2] < 0) {
			par[0] *= -1;
			par[2] *= -1;
		}

		as[i] = par[0]/polgrad;
		das[i] = par[1]/polgrad;

		Asym[i].cth = cth[i];
		Asym[i].dcth = dcth[i];
		Asym[i].as = as[i];
		Asym[i].das = das[i];

		name = Form( "%6.3f  %6.3f %4.3f  %4.2f %3.1f  %5.3f", cth[i],
				as[i], das[i], par[2], par[3], red_chisq);
		cout << name << endl ;
		outFile << name << endl ;
	}
	outFile.close();

	if ( draw == kTRUE) {

		c1 = new TCanvas( "c1", "Asymmetry", 100, 10, 700, 500);

		gr = new TGraphErrors( cthbins, cth, as, dcth, das);
		name = Form( "Asymmetry for E_{#gamma} = %5.1f #pm %4.1f MeV", eg, deg);
		gr->SetTitle( name);
		gr->SetMarkerStyle( 21);
		gr->SetMarkerSize( 1.2);
		gr->SetLineWidth(2);
		gr->GetXaxis()->SetTitleOffset( 1.1);
		gr->GetYaxis()->SetTitleOffset( 0.8);
		gr->GetYaxis()->SetTitleSize( 0.05);
		gr->GetXaxis()->SetTitle( "cos #theta");
		gr->GetYaxis()->SetTitle( "#Sigma");
		gr->GetXaxis()->SetLabelSize( 0.03);
		gr->GetYaxis()->SetLabelSize( 0.03);
		gr->GetXaxis()->SetRangeUser( -1, 1);
		if ( bin > 1) gr->SetMinimum( 0);
		gr->GetXaxis()->CenterTitle();
		gr->GetYaxis()->CenterTitle();
		gr->SetLineColor( col);
		gr->SetMarkerColor( col);
		gr->Draw( "AP");

		l1 = new TLine( -1, 0, 1, 0);
		l1->Draw();

//		pl = new TPaveLabel( 0.70, 0.75, 0.9, 0.85, subt, "NDC");
//		pl->SetTextAlign( 12);
//		pl->SetTextSize( 0.8);
//		pl->SetTextFont( 132);
//		pl->SetTextColor( col);
//		pl->SetBorderSize( 0);
//		pl->SetFillColor( 0);
//		pl->Draw();

		name = Form( "plots/Pi0/Asymmetry_cth_%d", bin);
		name.Append( ".pdf");
//		name.Append( ".eps");
		c1->Print( name);
	}
}
Beispiel #29
0
void FFT()
{

//This tutorial illustrates the Fast Fourier Transforms interface in ROOT.
//FFT transform types provided in ROOT:
// - "C2CFORWARD" - a complex input/output discrete Fourier transform (DFT) 
//                  in one or more dimensions, -1 in the exponent
// - "C2CBACKWARD"- a complex input/output discrete Fourier transform (DFT) 
//                  in one or more dimensions, +1 in the exponent
// - "R2C"        - a real-input/complex-output discrete Fourier transform (DFT)
//                  in one or more dimensions,
// - "C2R"        - inverse transforms to "R2C", taking complex input 
//                  (storing the non-redundant half of a logically Hermitian array) 
//                  to real output
// - "R2HC"       - a real-input DFT with output in ¡Èhalfcomplex¡É format, 
//                  i.e. real and imaginary parts for a transform of size n stored as
//                  r0, r1, r2, ..., rn/2, i(n+1)/2-1, ..., i2, i1
// - "HC2R"       - computes the reverse of FFTW_R2HC, above
// - "DHT"        - computes a discrete Hartley transform
// Sine/cosine transforms:
//  DCT-I  (REDFT00 in FFTW3 notation)
//  DCT-II (REDFT10 in FFTW3 notation)
//  DCT-III(REDFT01 in FFTW3 notation)
//  DCT-IV (REDFT11 in FFTW3 notation)
//  DST-I  (RODFT00 in FFTW3 notation)
//  DST-II (RODFT10 in FFTW3 notation)
//  DST-III(RODFT01 in FFTW3 notation)
//  DST-IV (RODFT11 in FFTW3 notation)
//First part of the tutorial shows how to transform the histograms
//Second part shows how to transform the data arrays directly
//Authors: Anna Kreshuk and Jens Hoffmann


//********* Histograms ********//


   //prepare the canvas for drawing
   TCanvas *myc = new TCanvas("myc", "Fast Fourier Transform", 800, 600);
   myc->SetFillColor(45);
   TPad *c1_1 = new TPad("c1_1", "c1_1",0.01,0.67,0.49,0.99);
   TPad *c1_2 = new TPad("c1_2", "c1_2",0.51,0.67,0.99,0.99);
   TPad *c1_3 = new TPad("c1_3", "c1_3",0.01,0.34,0.49,0.65);
   TPad *c1_4 = new TPad("c1_4", "c1_4",0.51,0.34,0.99,0.65);
   TPad *c1_5 = new TPad("c1_5", "c1_5",0.01,0.01,0.49,0.32);
   TPad *c1_6 = new TPad("c1_6", "c1_6",0.51,0.01,0.99,0.32);
   c1_1->Draw();
   c1_2->Draw();
   c1_3->Draw();
   c1_4->Draw();
   c1_5->Draw();
   c1_6->Draw();
   c1_1->SetFillColor(30);
   c1_1->SetFrameFillColor(42);
   c1_2->SetFillColor(30);
   c1_2->SetFrameFillColor(42);
   c1_3->SetFillColor(30);
   c1_3->SetFrameFillColor(42);
   c1_4->SetFillColor(30);
   c1_4->SetFrameFillColor(42);
   c1_5->SetFillColor(30);
   c1_5->SetFrameFillColor(42);
   c1_6->SetFillColor(30);
   c1_6->SetFrameFillColor(42);
   
   c1_1->cd();
   TH1::AddDirectory(kFALSE);
     
   //A function to sample
   TF1 *fsin = new TF1("fsin", "sin(x)*sin(x)/(x*x)", 0, 4*TMath::Pi());
   fsin->Draw();
   
   Int_t n=25;
   TH1D *hsin = new TH1D("hsin", "hsin", n+1, 0, 4*TMath::Pi());
   Double_t x;
   
   //Fill the histogram with function values
   for (Int_t i=0; i<=n; i++){
      x = (Double_t(i)/n)*(4*TMath::Pi());
      hsin->SetBinContent(i+1, fsin->Eval(x));
   }
   hsin->Draw("same");
   fsin->GetXaxis()->SetLabelSize(0.05);
   fsin->GetYaxis()->SetLabelSize(0.05);
   
   c1_2->cd();
   //Compute the transform and look at the magnitude of the output
   TH1 *hm =0;
   TVirtualFFT::SetTransform(0);
   hm = hsin->FFT(hm, "MAG");
   hm->SetTitle("Magnitude of the 1st transform");
   hm->Draw();
   //NOTE: for "real" frequencies you have to divide the x-axes range with the range of your function 
   //(in this case 4*Pi); y-axes has to be rescaled by a factor of 1/SQRT(n) to be right: this is not done automatically!
   
   hm->SetStats(kFALSE);
   hm->GetXaxis()->SetLabelSize(0.05);
   hm->GetYaxis()->SetLabelSize(0.05);
   c1_3->cd();   
   //Look at the phase of the output   
   TH1 *hp = 0;
   hp = hsin->FFT(hp, "PH");
   hp->SetTitle("Phase of the 1st transform");
   hp->Draw();
   hp->SetStats(kFALSE);
   hp->GetXaxis()->SetLabelSize(0.05);
   hp->GetYaxis()->SetLabelSize(0.05);
   
   //Look at the DC component and the Nyquist harmonic:
   Double_t re, im;
   //That's the way to get the current transform object:
   TVirtualFFT *fft = TVirtualFFT::GetCurrentTransform();
   c1_4->cd();
   //Use the following method to get just one point of the output
   fft->GetPointComplex(0, re, im);
   printf("1st transform: DC component: %f\n", re);
   fft->GetPointComplex(n/2+1, re, im);
   printf("1st transform: Nyquist harmonic: %f\n", re);

   //Use the following method to get the full output:
   Double_t *re_full = new Double_t[n];
   Double_t *im_full = new Double_t[n];
   fft->GetPointsComplex(re_full,im_full);
  
   //Now let's make a backward transform:
   TVirtualFFT *fft_back = TVirtualFFT::FFT(1, &n, "C2R M K");
   fft_back->SetPointsComplex(re_full,im_full);
   fft_back->Transform();
   TH1 *hb = 0;
   //Let's look at the output
   hb = TH1::TransformHisto(fft_back,hb,"Re");
   hb->SetTitle("The backward transform result");
   hb->Draw();
   //NOTE: here you get at the x-axes number of bins and not real values
   //(in this case 25 bins has to be rescaled to a range between 0 and 4*Pi; 
   //also here the y-axes has to be rescaled (factor 1/bins)
   hb->SetStats(kFALSE);
   hb->GetXaxis()->SetLabelSize(0.05);
   hb->GetYaxis()->SetLabelSize(0.05);
   delete fft_back;
   fft_back=0;

//********* Data array - same transform ********//

   //Allocate an array big enough to hold the transform output
   //Transform output in 1d contains, for a transform of size N, 
   //N/2+1 complex numbers, i.e. 2*(N/2+1) real numbers
   //our transform is of size n+1, because the histogram has n+1 bins

   Double_t *in = new Double_t[2*((n+1)/2+1)];
   Double_t re_2,im_2;
   for (Int_t i=0; i<=n; i++){
      x = (Double_t(i)/n)*(4*TMath::Pi());
      in[i] =  fsin->Eval(x);
   }

   //Make our own TVirtualFFT object (using option "K")
   //Third parameter (option) consists of 3 parts:
   //-transform type:
   // real input/complex output in our case
   //-transform flag: 
   // the amount of time spent in planning
   // the transform (see TVirtualFFT class description)
   //-to create a new TVirtualFFT object (option "K") or use the global (default)
   Int_t n_size = n+1;
   TVirtualFFT *fft_own = TVirtualFFT::FFT(1, &n_size, "R2C ES K");
   if (!fft_own) return;
   fft_own->SetPoints(in);
   fft_own->Transform();

   //Copy all the output points:
   fft_own->GetPoints(in);
   //Draw the real part of the output
   c1_5->cd();
   TH1 *hr = 0;
   hr = TH1::TransformHisto(fft_own, hr, "RE");
   hr->SetTitle("Real part of the 3rd (array) tranfsorm");
   hr->Draw();
   hr->SetStats(kFALSE);
   hr->GetXaxis()->SetLabelSize(0.05);
   hr->GetYaxis()->SetLabelSize(0.05);
   c1_6->cd();
   TH1 *him = 0;
   him = TH1::TransformHisto(fft_own, him, "IM");
   him->SetTitle("Im. part of the 3rd (array) transform");
   him->Draw();
   him->SetStats(kFALSE);
   him->GetXaxis()->SetLabelSize(0.05);
   him->GetYaxis()->SetLabelSize(0.05);

   myc->cd();
   //Now let's make another transform of the same size
   //The same transform object can be used, as the size and the type of the transform
   //haven't changed
   TF1 *fcos = new TF1("fcos", "cos(x)+cos(0.5*x)+cos(2*x)+1", 0, 4*TMath::Pi());
   for (Int_t i=0; i<=n; i++){
      x = (Double_t(i)/n)*(4*TMath::Pi());
      in[i] =  fcos->Eval(x);
   }
   fft_own->SetPoints(in);
   fft_own->Transform();
   fft_own->GetPointComplex(0, re_2, im_2);
   printf("2nd transform: DC component: %f\n", re_2);
   fft_own->GetPointComplex(n/2+1, re_2, im_2);
   printf("2nd transform: Nyquist harmonic: %f\n", re_2);
   delete fft_own;
   delete [] in;
   delete [] re_full;
   delete [] im_full;
}
Beispiel #30
0
void rulevisHists( TDirectory *rfdir, TDirectory *vardir, TDirectory *corrdir, TMVAGlob::TypeOfPlot type) {
   //
   if (rfdir==0)   return;
   if (vardir==0)  return;
   if (corrdir==0) return;
   //
   const TString rfName    = rfdir->GetName();
   const TString maintitle = rfName + " : Rule Importance";
   const TString rfNameOpt = "_RF2D_";
   const TString outfname[TMVAGlob::kNumOfMethods] = { "rulevisHists",
                                                       "rulevisHists_decorr",
                                                       "rulevisCorr_pca",
                                                       "rulevisCorr_gaussdecorr" };

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

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

   ///////////////////////////
   vardir->cd();
 
   // how many plots are in the directory?
   Int_t noPlots = ((vardir->GetListOfKeys())->GetEntries()) / 2;
 
   // define Canvas layout here!
   // default setting
   Int_t xPad;  // no of plots in x
   Int_t yPad;  // no of plots in y
   Int_t width; // size of canvas
   Int_t height;
   switch (noPlots) {
   case 1:
      xPad = 1; yPad = 1; width = 500; height = 0.7*width; break;
   case 2:
      xPad = 2; yPad = 1; width = 600; height = 0.7*width; break;
   case 3:
      xPad = 3; yPad = 1; width = 900; height = 0.4*width; break;
   case 4:
      xPad = 2; yPad = 2; width = 600; height = width; break;
   default:
      xPad = 3; yPad = 2; width = 800; height = 0.7*width; break;
   }
   Int_t noPad = xPad * yPad ;   

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   if (countPad <= noPad) {
      c[countCanvas]->Update();
      TString fname = Form( "plots/%s_c%i", outputName.Data(), countCanvas+1 );
      TMVAGlob::imgconv( c[countCanvas], fname );
   }
}