]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWG0/dNdPt/AlidNdPtHelper.cxx
a5b4aa4d15500281ac0e09bbc26a4419c9c71fbe
[u/mrichter/AliRoot.git] / PWG0 / dNdPt / AlidNdPtHelper.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
3  *                                                                        *
4  * Author: The ALICE Off-line Project.                                    *
5  * Contributors are mentioned in the code where appropriate.              *
6  *                                                                        *
7  * Permission to use, copy, modify and distribute this software and its   *
8  * documentation strictly for non-commercial purposes is hereby granted   *
9  * without fee, provided that the above copyright notice appears in all   *
10  * copies and that both the copyright notice and this permission notice   *
11  * appear in the supporting documentation. The authors make no claims     *
12  * about the suitability of this software for any purpose. It is          *
13  * provided "as is" without express or implied warranty.                  *
14  **************************************************************************/
15
16 #include <TROOT.h>
17 #include <TParticle.h>
18 #include <TParticlePDG.h>
19 #include <TH1.h>
20 #include <TH2.h>
21 #include <TH3.h>
22 #include <TCanvas.h>
23 #include <TList.h>
24 #include <TTree.h>
25 #include <TBranch.h>
26 #include <TLeaf.h>
27 #include <TArrayI.h>
28 #include <TF1.h>
29
30 #include <AliHeader.h>
31 #include <AliStack.h>
32 #include <AliLog.h>
33
34 #include <AliLog.h>
35 #include <AliESD.h>
36 #include <AliESDEvent.h>
37 #include <AliMCEvent.h>
38 #include <AliESDVertex.h>
39 #include <AliVertexerTracks.h>
40
41 #include <AliGenEventHeader.h>
42 #include <AliGenPythiaEventHeader.h>
43 #include <AliGenCocktailEventHeader.h>
44 #include <AliGenDPMjetEventHeader.h>
45
46 #include <AliMathBase.h>
47 #include <AliESDtrackCuts.h>
48 #include "dNdPt/AlidNdPtEventCuts.h"
49 #include "dNdPt/AlidNdPtAcceptanceCuts.h"
50 #include "dNdPt/AlidNdPtHelper.h"
51
52 //____________________________________________________________________
53 ClassImp(AlidNdPtHelper)
54
55 Int_t AlidNdPtHelper::fgLastProcessType = -1;
56
57 //____________________________________________________________________
58 Bool_t AlidNdPtHelper::IsEventTriggered(const AliESD* aEsd, Trigger trigger)
59 {
60   // see function with ULong64_t argument
61
62   ULong64_t triggerMask = aEsd->GetTriggerMask();
63   return IsEventTriggered(triggerMask, trigger);
64 }
65
66 //____________________________________________________________________
67 Bool_t AlidNdPtHelper::IsEventTriggered(ULong64_t triggerMask, Trigger trigger)
68 {
69   // check if the event was triggered
70   //
71   // this function needs the branch fTriggerMask
72   
73   // definitions from p-p.cfg
74   ULong64_t spdFO = (1 << 14);
75   ULong64_t v0left = (1 << 11);
76   ULong64_t v0right = (1 << 12);
77
78   switch (trigger)
79   {
80     case kMB1:
81     {
82       if (triggerMask & spdFO || ((triggerMask & v0left) || (triggerMask & v0right)))
83         return kTRUE;
84       break;
85     }
86     case kMB2:
87     {
88       if (triggerMask & spdFO && ((triggerMask & v0left) || (triggerMask & v0right)))
89         return kTRUE;
90       break;
91     }
92     case kSPDFASTOR:
93     {
94       if (triggerMask & spdFO)
95         return kTRUE;
96       break;
97     }
98   }
99
100   return kFALSE;
101 }
102
103 //____________________________________________________________________
104 const Bool_t AlidNdPtHelper::TestVertex(const AliESDVertex* vertex, AnalysisMode analysisMode, Bool_t debug)
105 {
106   // Checks if a vertex meets the needed quality criteria
107   if(!vertex) return kFALSE;
108
109   Float_t requiredZResolution = -1;
110   if (analysisMode == kSPD || analysisMode == kTPCITS || analysisMode == kTPCSPDvtx)
111   {
112     requiredZResolution = 0.1;
113   }
114   else if (analysisMode == kTPC || analysisMode == kMCRec || 
115            analysisMode == kMCPion || analysisMode == kMCKaon || 
116            analysisMode == kMCProton || analysisMode ==kPlus || analysisMode ==kMinus)
117     requiredZResolution = 10.;
118
119   // check Ncontributors
120   if (vertex->GetNContributors() <= 0) {
121     if (debug){
122       Printf("AlidNdPtHelper::GetVertex: NContributors() <= 0: %d",vertex->GetNContributors());
123       Printf("AlidNdPtHelper::GetVertex: NIndices(): %d",vertex->GetNIndices());
124       vertex->Print();
125     }
126     return kFALSE;
127   }
128
129   // check resolution
130   Double_t zRes = vertex->GetZRes();
131   if (zRes == 0) {
132     Printf("AlidNdPtHelper::GetVertex: UNEXPECTED: resolution is 0.");
133     return kFALSE;
134   }
135
136   if (zRes > requiredZResolution) {
137     if (debug)
138       Printf("AlidNdPtHelper::TestVertex: Resolution too poor %f (required: %f", zRes, requiredZResolution);
139     return kFALSE;
140   }
141
142   return kTRUE;
143 }
144
145 //____________________________________________________________________
146 const AliESDVertex* AlidNdPtHelper::GetVertex(AliESDEvent* aEsd, AlidNdPtEventCuts *evtCuts, AlidNdPtAcceptanceCuts *accCuts, AliESDtrackCuts *trackCuts, AnalysisMode analysisMode, Bool_t debug, Bool_t bRedoTPC, Bool_t bUseMeanVertex)
147 {
148   // Get the vertex from the ESD and returns it if the vertex is valid
149   //
150   // Second argument decides which vertex is used (this selects
151   // also the quality criteria that are applied)
152
153   if(!aEsd) 
154   { 
155     ::Error("AlidNdPtHelper::GetVertex()","esd event is NULL");
156     return NULL;  
157   }
158  
159   if(!evtCuts || !accCuts || !trackCuts) 
160   { 
161     ::Error("AlidNdPtHelper::GetVertex()","cuts not available");
162     return NULL;  
163   }
164
165   const AliESDVertex* vertex = 0;
166   AliESDVertex *initVertex = 0;
167   if (analysisMode == kSPD || analysisMode == kTPCITS || analysisMode == kTPCSPDvtx ||  
168       analysisMode == kMCRec || analysisMode == kMCPion || analysisMode == kMCKaon || 
169       analysisMode == kMCProton || analysisMode ==kPlus || analysisMode ==kMinus )
170   {
171     vertex = aEsd->GetPrimaryVertexSPD();
172     if (debug)
173       Printf("AlidNdPtHelper::GetVertex: Returning SPD vertex");
174   }
175   else if (analysisMode == kTPC || analysisMode == kMCRec || 
176            analysisMode == kMCPion || analysisMode == kMCKaon || analysisMode == kMCProton || 
177            analysisMode == kPlus || analysisMode == kMinus)
178   {
179     if(bRedoTPC) {
180
181       Double_t kBz = aEsd->GetMagneticField();
182       AliVertexerTracks vertexer(kBz);
183
184       if(bUseMeanVertex) {
185          Double_t pos[3]={evtCuts->GetMeanXv(),evtCuts->GetMeanYv(),evtCuts->GetMeanZv()};
186          Double_t err[3]={evtCuts->GetSigmaMeanXv(),evtCuts->GetSigmaMeanYv(),evtCuts->GetSigmaMeanZv()};
187          //printf("pos[0] %f, pos[1] %f, pos[2] %f \n", pos[0], pos[1], pos[2]);
188          initVertex = new AliESDVertex(pos,err);
189          vertexer.SetVtxStart(initVertex);
190          vertexer.SetConstraintOn();
191       }
192
193       //vertexer.SetTPCMode(Double_t dcacut=0.1, Double_t dcacutIter0=1.0, Double_t maxd0z0=5.0, Int_t minCls=10, Int_t mintrks=1, Double_t nsigma=3., Double_t mindetfitter=0.1, Double_t maxtgl=1.5, Double_t fidR=3., Double_t fidZ=30., Int_t finderAlgo=1, Int_t finderAlgoIter0=4);
194
195       Double_t maxDCAr = accCuts->GetMaxDCAr();
196       Double_t maxDCAz = accCuts->GetMaxDCAz();
197       Int_t minTPCClust = trackCuts->GetMinNClusterTPC();
198
199       vertexer.SetTPCMode(0.1,1.0,5.0,minTPCClust,1,3.,0.1,2.0,maxDCAr,maxDCAz,1,4);
200
201       // TPC track preselection
202       Int_t ntracks = aEsd->GetNumberOfTracks();
203       TObjArray array(ntracks);
204       UShort_t *id = new UShort_t[ntracks];
205
206       Int_t count=0;
207       for (Int_t i=0;i <ntracks; i++) {
208         AliESDtrack *t = aEsd->GetTrack(i);
209         if (!t) continue;
210         if (t->Charge() == 0) continue;
211         if (!t->GetTPCInnerParam()) continue;
212         if (t->GetTPCNcls()<vertexer.GetMinClusters()) continue;
213         AliExternalTrackParam  *tpcTrack  = new AliExternalTrackParam(*(t->GetTPCInnerParam()));
214         if(tpcTrack) { 
215           array.AddLast(tpcTrack);
216           id[count] = (UShort_t)t->GetID();
217           count++;
218         }
219       } 
220       AliESDVertex *vTPC = vertexer.VertexForSelectedTracks(&array,id, kTRUE, kTRUE, bUseMeanVertex);
221       aEsd->SetPrimaryVertexTPC(vTPC);
222
223       for (Int_t i=0; i<aEsd->GetNumberOfTracks(); i++) {
224         AliESDtrack *t = aEsd->GetTrack(i);
225         t->RelateToVertexTPC(vTPC, kBz, kVeryBig);
226       }
227       
228       delete vTPC;
229       array.Delete();
230       delete [] id; id=NULL;
231
232     }
233     vertex = aEsd->GetPrimaryVertexTPC();
234     if (debug)
235       Printf("AlidNdPtHelper::GetVertex: Returning vertex from tracks");
236     }
237       else
238        Printf("AlidNdPtHelper::GetVertex: ERROR: Invalid second argument %d", analysisMode);
239
240     if (!vertex) {
241      if (debug)
242       Printf("AlidNdPtHelper::GetVertex: No vertex found in ESD");
243       return 0;
244     }
245
246   if (debug)
247   {
248     Printf("AlidNdPtHelper::GetVertex: Returning valid vertex: %s", vertex->GetTitle());
249     vertex->Print();
250   }
251   
252   if(initVertex) delete initVertex; initVertex=NULL;
253   return vertex;
254 }
255
256 //____________________________________________________________________
257 Bool_t AlidNdPtHelper::IsPrimaryParticle(AliStack* stack, Int_t idx, AnalysisMode analysisMode)
258 {
259 // check primary particles 
260 // depending on the analysis mode
261 //
262   if(!stack) return kFALSE;
263
264   TParticle* particle = stack->Particle(idx);
265   if (!particle) return  kFALSE;
266
267   // only charged particles
268   Double_t charge = particle->GetPDG()->Charge()/3.;
269   if (charge == 0.0) return kFALSE;
270
271   Int_t pdg = TMath::Abs(particle->GetPdgCode());
272
273   // physical primary
274   Bool_t prim = stack->IsPhysicalPrimary(idx);
275
276   if(analysisMode==kMCPion) {
277     if(prim && pdg==kPiPlus) return kTRUE;
278     else return kFALSE;
279   } 
280
281   if (analysisMode==kMCKaon) {
282     if(prim && pdg==kKPlus) return kTRUE;
283     else return kFALSE;
284   }
285     
286   if (analysisMode==kMCProton) {
287     if(prim && pdg==kProton) return kTRUE;
288     else return kFALSE;
289   }
290
291 return prim;
292 }
293
294 //____________________________________________________________________
295 Bool_t AlidNdPtHelper::IsPrimaryCharged(TParticle* aParticle, Int_t aTotalPrimaries, Bool_t adebug)
296 {
297   //
298   // this function checks if a particle from the event generator (i.e. among the nPrim particles in the stack)
299   // shall be counted as a primary particle
300   //
301   // This function or a equivalent should be available in some common place of AliRoot
302   //
303   // WARNING: Call this function only for particles that are among the particles from the event generator!
304   // --> stack->Particle(id) with id < stack->GetNprimary()
305
306   // if the particle has a daughter primary, we do not want to count it
307   if (aParticle->GetFirstDaughter() != -1 && aParticle->GetFirstDaughter() < aTotalPrimaries)
308   {
309     if (adebug)
310       printf("Dropping particle because it has a daughter among the primaries.\n");
311     return kFALSE;
312   }
313
314   Int_t pdgCode = TMath::Abs(aParticle->GetPdgCode());
315   
316
317   // skip quarks and gluon
318   if (pdgCode <= 10 || pdgCode == 21)
319   {
320     if (adebug)
321       printf("Dropping particle because it is a quark or gluon.\n");
322     return kFALSE;
323   }
324
325   Int_t status = aParticle->GetStatusCode();
326   // skip non final state particles..
327   if(status!=1){
328     if (adebug)
329       printf("Dropping particle because it is not a final state particle.\n");
330     return kFALSE;
331   }
332
333   if (strcmp(aParticle->GetName(),"XXX") == 0)
334   {
335     Printf("WARNING: There is a particle named XXX (pdg code %d).", pdgCode);
336     return kFALSE;
337   }
338
339   TParticlePDG* pdgPart = aParticle->GetPDG();
340
341   if (strcmp(pdgPart->ParticleClass(),"Unknown") == 0)
342   {
343     Printf("WARNING: There is a particle with an unknown particle class (pdg code %d).", pdgCode);
344     return kFALSE;
345   }
346
347   if (pdgPart->Charge() == 0)
348   {
349     if (adebug)
350       printf("Dropping particle because it is not charged.\n");
351     return kFALSE;
352   }
353
354   return kTRUE;
355 }
356
357 //____________________________________________________________________
358 void AlidNdPtHelper::CreateProjections(TH3* hist, Bool_t save)
359 {
360   // create projections of 3d hists to all 2d combinations
361   // the histograms are not returned, just use them from memory or use this to create them in a file
362
363   TH1* proj = hist->Project3D("yx");
364   proj->SetXTitle(hist->GetXaxis()->GetTitle());
365   proj->SetYTitle(hist->GetYaxis()->GetTitle());
366   if (save)
367     proj->Write();
368
369   proj = hist->Project3D("zx");
370   proj->SetXTitle(hist->GetXaxis()->GetTitle());
371   proj->SetYTitle(hist->GetZaxis()->GetTitle());
372   if (save)
373     proj->Write();
374
375   proj = hist->Project3D("zy");
376   proj->SetXTitle(hist->GetYaxis()->GetTitle());
377   proj->SetYTitle(hist->GetZaxis()->GetTitle());
378   if (save)
379     proj->Write();
380 }
381
382 //____________________________________________________________________
383 void AlidNdPtHelper::CreateDividedProjections(TH3* hist, TH3* hist2, const char* axis, Bool_t putErrors, Bool_t save)
384 {
385   // create projections of the 3d hists divides them
386   // axis decides to which plane, if axis is 0 to all planes
387   // the histograms are not returned, just use them from memory or use this to create them in a file
388
389   if (axis == 0)
390   {
391     CreateDividedProjections(hist, hist2, "yx", putErrors, save);
392     CreateDividedProjections(hist, hist2, "zx", putErrors, save);
393     CreateDividedProjections(hist, hist2, "zy", putErrors, save);
394
395     return;
396   }
397
398   TH1* proj = hist->Project3D(axis);
399
400   if (strlen(axis) == 2)
401   {
402     proj->SetYTitle(GetAxisTitle(hist, axis[0]));
403     proj->SetXTitle(GetAxisTitle(hist, axis[1]));
404   }
405   else if (strlen(axis) == 1)
406     proj->SetXTitle(GetAxisTitle(hist, axis[0]));
407
408   TH1* proj2 = hist2->Project3D(axis);
409   if (strlen(axis) == 2)
410   {
411     proj2->SetYTitle(GetAxisTitle(hist2, axis[0]));
412     proj2->SetXTitle(GetAxisTitle(hist2, axis[1]));
413   }
414   else if (strlen(axis) == 1)
415     proj2->SetXTitle(GetAxisTitle(hist2, axis[0]));
416
417   TH1* division = dynamic_cast<TH1*> (proj->Clone(Form("%s_div_%s", proj->GetName(), proj2->GetName())));
418   //printf("doing axis: %s, x axis has %d %d bins, min %f %f max %f %f\n", axis, division->GetNbinsX(), proj2->GetNbinsX(), division->GetXaxis()->GetBinLowEdge(1), proj2->GetXaxis()->GetBinLowEdge(1), division->GetXaxis()->GetBinUpEdge(division->GetNbinsX()), proj2->GetXaxis()->GetBinUpEdge(proj2->GetNbinsX()));
419   //printf("doing axis: %s, y axis has %d %d bins, min %f %f max %f %f\n", axis, division->GetNbinsY(), proj2->GetNbinsY(), division->GetYaxis()->GetBinLowEdge(1), proj2->GetYaxis()->GetBinLowEdge(1), division->GetYaxis()->GetBinUpEdge(division->GetNbinsY()), proj2->GetYaxis()->GetBinUpEdge(proj2->GetNbinsY()));
420   division->Divide(proj, proj2, 1, 1, "B");
421   division->SetTitle(Form("%s divided %s", proj->GetTitle(), proj2->GetTitle()));
422
423   if (putErrors)
424   {
425     division->Sumw2();
426     if (division->GetDimension() == 1)
427     {
428       Int_t nBins = division->GetNbinsX();
429       for (Int_t i = 1; i <= nBins; ++i)
430         if (proj2->GetBinContent(i) != 0)
431           division->SetBinError(i, TMath::Sqrt(proj->GetBinContent(i)) / proj2->GetBinContent(i));
432     }
433     else if (division->GetDimension() == 2)
434     {
435       Int_t nBinsX = division->GetNbinsX();
436       Int_t nBinsY = division->GetNbinsY();
437       for (Int_t i = 1; i <= nBinsX; ++i)
438         for (Int_t j = 1; j <= nBinsY; ++j)
439           if (proj2->GetBinContent(i, j) != 0)
440             division->SetBinError(i, j, TMath::Sqrt(proj->GetBinContent(i, j)) / proj2->GetBinContent(i, j));
441     }
442   }
443
444   if (save)
445   {
446     proj->Write();
447     proj2->Write();
448     division->Write();
449   }
450 }
451
452 //____________________________________________________________________
453 const char* AlidNdPtHelper::GetAxisTitle(TH3* hist, const char axis)
454 {
455   // returns the title of the axis given in axis (x, y, z)
456
457   if (axis == 'x')
458     return hist->GetXaxis()->GetTitle();
459   else if (axis == 'y')
460     return hist->GetYaxis()->GetTitle();
461   else if (axis == 'z')
462     return hist->GetZaxis()->GetTitle();
463
464   return 0;
465 }
466
467
468 AlidNdPtHelper::MCProcessType AlidNdPtHelper::GetPythiaEventProcessType(AliGenEventHeader* aHeader, Bool_t adebug) {
469
470   AliGenPythiaEventHeader* pythiaGenHeader = dynamic_cast<AliGenPythiaEventHeader*>(aHeader);
471
472   if (!pythiaGenHeader) {
473     printf("AlidNdPtHelper::GetProcessType : Unknown gen Header type). \n");
474     return kInvalidProcess;
475   }
476
477
478   Int_t pythiaType = pythiaGenHeader->ProcessType();
479   fgLastProcessType = pythiaType;
480   MCProcessType globalType = kInvalidProcess;  
481
482
483   if (adebug) {
484     printf("AlidNdPtHelper::GetProcessType : Pythia process type found: %d \n",pythiaType);
485   }
486
487
488   if(pythiaType==92||pythiaType==93){
489     globalType = kSD;
490   }
491   else if(pythiaType==94){
492     globalType = kDD;
493   }
494   //else if(pythiaType != 91){ // also exclude elastic to be sure... CKB??
495   else {
496     globalType = kND;
497   }
498   return globalType;
499 }
500
501
502 AlidNdPtHelper::MCProcessType AlidNdPtHelper::GetDPMjetEventProcessType(AliGenEventHeader* aHeader, Bool_t adebug) {
503   //
504   // get the process type of the event.
505   //
506
507   // can only read pythia headers, either directly or from cocktalil header
508   AliGenDPMjetEventHeader* dpmJetGenHeader = dynamic_cast<AliGenDPMjetEventHeader*>(aHeader);
509
510   if (!dpmJetGenHeader) {
511     printf("AlidNdPtHelper::GetDPMjetProcessType : Unknown header type (not DPMjet or). \n");
512     return kInvalidProcess;
513   }
514
515   Int_t dpmJetType = dpmJetGenHeader->ProcessType();
516   fgLastProcessType = dpmJetType;
517   MCProcessType globalType = kInvalidProcess;  
518
519
520   if (adebug) {
521     printf("AlidNdPtHelper::GetDPMJetProcessType : DPMJet process type found: %d \n",dpmJetType);
522   }
523
524
525   if(dpmJetType == 1){ // this is explicitly inelastic
526     globalType = kND;
527   }  
528   else if(dpmJetType==5||dpmJetType==6){
529     globalType = kSD;
530   }
531   else if(dpmJetType==7||dpmJetType==4){// DD and double pomeron
532     globalType = kDD;
533   }
534   return globalType;
535 }
536
537
538 AlidNdPtHelper::MCProcessType AlidNdPtHelper::GetEventProcessType(AliHeader* aHeader, Bool_t adebug) {
539   //
540   // get the process type of the event.
541   //
542
543
544   // Check for simple headers first
545
546   AliGenPythiaEventHeader* pythiaGenHeader = dynamic_cast<AliGenPythiaEventHeader*>(aHeader->GenEventHeader());
547   if (pythiaGenHeader) {
548     return GetPythiaEventProcessType(pythiaGenHeader,adebug);
549   }
550
551   AliGenDPMjetEventHeader* dpmJetGenHeader = dynamic_cast<AliGenDPMjetEventHeader*>(aHeader->GenEventHeader());
552   if (dpmJetGenHeader) {
553     return GetDPMjetEventProcessType(dpmJetGenHeader,adebug);
554   }
555   
556
557   // check for cocktail
558
559   AliGenCocktailEventHeader* genCocktailHeader = dynamic_cast<AliGenCocktailEventHeader*>(aHeader->GenEventHeader());
560   if (!genCocktailHeader) {
561     printf("AlidNdPtHelper::GetProcessType : Unknown header type (not Pythia or Cocktail). \n");
562     return kInvalidProcess;
563   }
564
565   TList* headerList = genCocktailHeader->GetHeaders();
566   if (!headerList) {
567     return kInvalidProcess;
568   }
569
570   for (Int_t i=0; i<headerList->GetEntries(); i++) {
571
572     pythiaGenHeader = dynamic_cast<AliGenPythiaEventHeader*>(headerList->At(i));
573     if (pythiaGenHeader) {
574       return GetPythiaEventProcessType(pythiaGenHeader,adebug);
575     }
576
577     dpmJetGenHeader = dynamic_cast<AliGenDPMjetEventHeader*>(headerList->At(i));
578     if (dpmJetGenHeader) {
579       return GetDPMjetEventProcessType(dpmJetGenHeader,adebug);
580     }
581   }
582   return kInvalidProcess;
583 }
584
585
586
587 //____________________________________________________________________
588 TParticle* AlidNdPtHelper::FindPrimaryMother(AliStack* stack, Int_t label)
589 {
590   //
591   // Finds the first mother among the primary particles of the particle identified by <label>,
592   // i.e. the primary that "caused" this particle
593   //
594
595   Int_t motherLabel = FindPrimaryMotherLabel(stack, label);
596   if (motherLabel < 0)
597     return 0;
598
599   return stack->Particle(motherLabel);
600 }
601
602 //____________________________________________________________________
603 Int_t AlidNdPtHelper::FindPrimaryMotherLabel(AliStack* stack, Int_t label)
604 {
605   //
606   // Finds the first mother among the primary particles of the particle identified by <label>,
607   // i.e. the primary that "caused" this particle
608   //
609   // returns its label
610   //
611
612   Int_t nPrim  = stack->GetNprimary();
613
614   while (label >= nPrim)
615   {
616     //printf("Particle %d (pdg %d) is not a primary. Let's check its mother %d\n", label, mother->GetPdgCode(), mother->GetMother(0));
617
618     TParticle* particle = stack->Particle(label);
619     if (!particle)
620     {
621       AliDebugGeneral("FindPrimaryMother", AliLog::kError, Form("UNEXPECTED: particle with label %d not found in stack.", label));
622       return -1;
623     }
624  
625     // find mother
626     if (particle->GetMother(0) < 0)
627     {
628       AliDebugGeneral("FindPrimaryMother", AliLog::kError, Form("UNEXPECTED: Could not find mother of secondary particle %d.", label));
629       return -1;
630     }
631
632     label = particle->GetMother(0);
633   }
634
635   return label;
636 }
637
638 //____________________________________________________________________
639 void AlidNdPtHelper::NormalizeToBinWidth(TH1* hist)
640 {
641   //
642   // normalizes a 1-d histogram to its bin width
643   //
644
645   for (Int_t i=1; i<=hist->GetNbinsX(); ++i)
646   {
647     hist->SetBinContent(i, hist->GetBinContent(i) / hist->GetBinWidth(i));
648     hist->SetBinError(i, hist->GetBinError(i) / hist->GetBinWidth(i));
649   }
650 }
651
652 //____________________________________________________________________
653 void AlidNdPtHelper::NormalizeToBinWidth(TH2* hist)
654 {
655   //
656   // normalizes a 2-d histogram to its bin width (x width * y width)
657   //
658
659   for (Int_t i=1; i<=hist->GetNbinsX(); ++i)
660     for (Int_t j=1; j<=hist->GetNbinsY(); ++j)
661     {
662       Double_t factor = hist->GetXaxis()->GetBinWidth(i) * hist->GetYaxis()->GetBinWidth(j);
663       hist->SetBinContent(i, j, hist->GetBinContent(i, j) / factor);
664       hist->SetBinError(i, j, hist->GetBinError(i, j) / factor);
665     }
666 }
667
668 //____________________________________________________________________
669 void AlidNdPtHelper::PrintConf(AnalysisMode analysisMode, Trigger trigger)
670 {
671   //
672   // Prints the given configuration
673   //
674
675   TString str(">>>> Running with ");
676
677   switch (analysisMode)
678   {
679     case kInvalid: str += "invalid setting"; break;
680     case kSPD : str += "SPD-only"; break;
681     case kTPC : str += "TPC-only"; break;
682     case kTPCITS : str += "Global tracking"; break;
683     case kTPCSPDvtx : str += "TPC tracking + SPD event vertex"; break;
684     case kMCRec : str += "TPC tracking + Replace rec. with MC values"; break;
685     case kMCPion : str += "TPC tracking + only pion MC tracks"; break;
686     case kMCKaon : str += "TPC tracking + only kaon MC tracks"; break;
687     case kMCProton : str += "TPC tracking + only proton MC tracks"; break;
688     case kPlus: str += "TPC tracking + only positive charged tracks"; break;
689     case kMinus : str += "TPC tracking + only negative charge tracks"; break;
690   }
691   str += " and trigger ";
692
693   switch (trigger)
694   {
695     case kMB1 : str += "MB1"; break;
696     case kMB2 : str += "MB2"; break;
697     case kSPDFASTOR : str += "SPD FASTOR"; break;
698   }
699
700   str += " <<<<";
701
702   Printf("%s", str.Data());
703 }
704
705 //____________________________________________________________________
706 Int_t AlidNdPtHelper::ConvertPdgToPid(TParticle *particle) {
707 //
708 // Convert Abs(pdg) to pid 
709 // (0 - e, 1 - muons, 2 - pions, 3 - kaons, 4 - protons, 5 -all rest)
710 //
711 Int_t pid=-1;
712
713   if (TMath::Abs(particle->GetPdgCode()) == kElectron)         { pid = 0; }
714   else if (TMath::Abs(particle->GetPdgCode()) == kMuonMinus) { pid = 1; }
715   else if (TMath::Abs(particle->GetPdgCode()) == kPiPlus)    { pid = 2; }
716   else if (TMath::Abs(particle->GetPdgCode()) == kKPlus)     { pid = 3; }
717   else if (TMath::Abs(particle->GetPdgCode()) == kProton)    { pid = 4; }
718   else                                                       { pid = 5; }
719
720 return pid;
721 }
722
723 //_____________________________________________________________________________
724 TH1F* AlidNdPtHelper::CreateResHisto(TH2F* hRes2, TH1F **phMean, Int_t integ,  Bool_t drawBinFits, Int_t minHistEntries)
725 {
726   TVirtualPad* currentPad = gPad;
727   TAxis* axis = hRes2->GetXaxis();
728   Int_t nBins = axis->GetNbins();
729   Bool_t overflowBinFits = kFALSE;
730   TH1F* hRes, *hMean;
731   if (axis->GetXbins()->GetSize()){
732     hRes = new TH1F("hRes", "", nBins, axis->GetXbins()->GetArray());
733     hMean = new TH1F("hMean", "", nBins, axis->GetXbins()->GetArray());
734   }
735   else{
736     hRes = new TH1F("hRes", "", nBins, axis->GetXmin(), axis->GetXmax());
737     hMean = new TH1F("hMean", "", nBins, axis->GetXmin(), axis->GetXmax());
738
739   }
740   hRes->SetStats(false);
741   hRes->SetOption("E");
742   hRes->SetMinimum(0.);
743   //
744   hMean->SetStats(false);
745   hMean->SetOption("E");
746  
747   // create the fit function
748   TF1 * fitFunc = new TF1("G","[0]*exp(-(x-[1])*(x-[1])/(2.*[2]*[2]))",-3,3);
749   
750   fitFunc->SetLineWidth(2);
751   fitFunc->SetFillStyle(0);
752   // create canvas for fits
753   TCanvas* canBinFits = NULL;
754   Int_t nPads = (overflowBinFits) ? nBins+2 : nBins;
755   Int_t nx = Int_t(sqrt(nPads-1.));// + 1;
756   Int_t ny = (nPads-1) / nx + 1;
757   if (drawBinFits) {
758     canBinFits = (TCanvas*)gROOT->FindObject("canBinFits");
759     if (canBinFits) delete canBinFits;
760     canBinFits = new TCanvas("canBinFits", "fits of bins", 200, 100, 500, 700);
761     canBinFits->Divide(nx, ny);
762   }
763
764   // loop over x bins and fit projection
765   Int_t dBin = ((overflowBinFits) ? 1 : 0);
766   for (Int_t bin = 1-dBin; bin <= nBins+dBin; bin++) {
767     if (drawBinFits) canBinFits->cd(bin + dBin);
768     Int_t bin0=TMath::Max(bin-integ,0);
769     Int_t bin1=TMath::Min(bin+integ,nBins);
770     TH1D* hBin = hRes2->ProjectionY("hBin", bin0, bin1);
771     //    
772     if (hBin->GetEntries() > minHistEntries) {
773       fitFunc->SetParameters(hBin->GetMaximum(),hBin->GetMean(),hBin->GetRMS());
774       hBin->Fit(fitFunc,"s");
775       Double_t sigma = TMath::Abs(fitFunc->GetParameter(2));
776
777       if (sigma > 0.){
778         hRes->SetBinContent(bin, TMath::Abs(fitFunc->GetParameter(2)));
779         hMean->SetBinContent(bin, fitFunc->GetParameter(1));    
780       }
781       else{
782         hRes->SetBinContent(bin, 0.);
783         hMean->SetBinContent(bin,0);
784       }
785       hRes->SetBinError(bin, fitFunc->GetParError(2));
786       hMean->SetBinError(bin, fitFunc->GetParError(1));
787       
788       //
789       //
790
791     } else {
792       hRes->SetBinContent(bin, 0.);
793       hRes->SetBinError(bin, 0.);
794       hMean->SetBinContent(bin, 0.);
795       hMean->SetBinError(bin, 0.);
796     }
797     
798
799     if (drawBinFits) {
800       char name[256];
801       if (bin == 0) {
802         sprintf(name, "%s < %.4g", axis->GetTitle(), axis->GetBinUpEdge(bin));
803       } else if (bin == nBins+1) {
804         sprintf(name, "%.4g < %s", axis->GetBinLowEdge(bin), axis->GetTitle());
805       } else {
806         sprintf(name, "%.4g < %s < %.4g", axis->GetBinLowEdge(bin),
807                 axis->GetTitle(), axis->GetBinUpEdge(bin));
808       }
809       canBinFits->cd(bin + dBin);
810       hBin->SetTitle(name);
811       hBin->SetStats(kTRUE);
812       hBin->DrawCopy("E");
813       canBinFits->Update();
814       canBinFits->Modified();
815       canBinFits->Update();
816     }
817     
818     delete hBin;
819   }
820
821   delete fitFunc;
822   currentPad->cd();
823   *phMean = hMean;
824   return hRes;
825 }
826
827 //_____________________________________________________________________________
828 TH1F* AlidNdPtHelper::MakeResol(TH2F * his, Int_t integ, Bool_t type, Bool_t drawBins, Int_t minHistEntries){
829 // Create resolution histograms
830   
831      TH1F *hisr=0, *hism=0;
832      if (!gPad) new TCanvas;
833          //hisr = AliTreeDraw::CreateResHistoI(his,&hism,integ);
834          hisr = CreateResHisto(his,&hism,integ,drawBins,minHistEntries);
835          if (type) return hism;
836          else return hisr;
837
838 return hisr;     
839 }
840
841 //_____________________________________________________________________________
842 AliESDtrack* AlidNdPtHelper::GetTPCOnlyTrack(AliESDEvent* esd, const AliESDVertex *vtx, Int_t iTrack)
843 {
844   // creates a TPC only track from the given esd track
845   // the track has to be deleted by the user
846   //
847   // NB. most of the functionality to get a TPC only track from an ESD track is in AliESDtrack, where it should be
848   // there are only missing propagations here that are needed for old data
849   // this function will therefore become obsolete
850   //
851   // adapted from code provided by CKB
852
853   // no vertex
854   if (!vtx) return 0;  
855   if(!vtx->GetStatus()) return 0; 
856
857   AliESDtrack* track = esd->GetTrack(iTrack);
858   if (!track)
859     return 0;
860
861   AliESDtrack *tpcTrack = new AliESDtrack();
862
863   // This should have been done during the reconstruction
864   // fixed by Juri in r26675
865   // but recalculate for older data CKB
866   Float_t p[2],cov[3];
867   track->GetImpactParametersTPC(p,cov);
868   if(p[0]==0&&p[1]==0)
869     //track->RelateToVertexTPC(esd->GetPrimaryVertexTPC(),esd->GetMagneticField(),kVeryBig);
870     track->RelateToVertexTPC(vtx,esd->GetMagneticField(),kVeryBig);
871   // BKC
872
873   // only true if we have a tpc track
874   if (!track->FillTPCOnlyTrack(*tpcTrack))
875   {
876     delete tpcTrack;
877     return 0;
878   }
879
880   // propagate to Vertex
881   // not needed for normal reconstructed ESDs...
882   // Double_t pTPC[2],covTPC[3];
883   //tpcTrack->PropagateToDCA(esd->GetPrimaryVertexTPC(), esd->GetMagneticField(), 10000,  pTPC, covTPC);
884   //tpcTrack->PropagateToDCA(vtx, esd->GetMagneticField(), 10000,  pTPC, covTPC);
885
886   return tpcTrack;
887 }
888
889 //_____________________________________________________________________________
890 TObjArray* AlidNdPtHelper::GetAllChargedTracks(AliESDEvent *esdEvent, const AliESDVertex *vtx, AnalysisMode analysisMode)
891 {
892   //
893   // all charged TPC particles 
894   //
895   TObjArray *allTracks = new TObjArray();
896   if(!allTracks) return allTracks;
897
898   AliESDtrack *track=0;
899   for (Int_t iTrack = 0; iTrack < esdEvent->GetNumberOfTracks(); iTrack++) 
900   { 
901     if(analysisMode == AlidNdPtHelper::kTPC || analysisMode == AlidNdPtHelper::kTPCSPDvtx || analysisMode == AlidNdPtHelper::kMCRec || analysisMode == kMCPion || analysisMode == kMCKaon || analysisMode == kMCProton || analysisMode ==kPlus || analysisMode ==kMinus) { 
902       // track must be deleted by the user 
903       track = GetTPCOnlyTrack(esdEvent,vtx,iTrack);
904       //track = AliESDtrackCuts::GetTPCOnlyTrack(esdEvent,iTrack);
905     } else {
906       track=esdEvent->GetTrack(iTrack);
907     }
908     if(!track) continue;
909
910     if(track->Charge()==0) { 
911       if(analysisMode == AlidNdPtHelper::kTPC || analysisMode == AlidNdPtHelper::kTPCSPDvtx ||  analysisMode == AlidNdPtHelper::kMCRec || analysisMode == kMCPion || analysisMode == kMCKaon || analysisMode == kMCProton || analysisMode ==kPlus || analysisMode ==kMinus) {
912         delete track; continue; 
913       } else {
914         continue;
915       } 
916     }
917
918     allTracks->Add(track);
919   }
920   if(analysisMode == AlidNdPtHelper::kTPC || analysisMode == AlidNdPtHelper::kTPCSPDvtx || analysisMode == AlidNdPtHelper::kMCRec || analysisMode == kMCPion || analysisMode == kMCKaon || analysisMode == kMCProton || analysisMode ==kPlus || analysisMode ==kMinus) allTracks->SetOwner(kTRUE);
921
922 return allTracks;
923 }
924
925 //_____________________________________________________________________________
926 Int_t AlidNdPtHelper::GetTPCMBTrackMult(AliESDEvent *esdEvent, AlidNdPtEventCuts *evtCuts, AlidNdPtAcceptanceCuts *accCuts, AliESDtrackCuts *trackCuts)
927 {
928   //
929   // get MB event track multiplicity
930   //
931   if(!esdEvent) 
932   { 
933     ::Error("AlidNdPtHelper::GetTPCMBTrackMult()","esd event is NULL");
934     return 0;  
935   }
936  
937   if(!evtCuts || !accCuts || !trackCuts) 
938   { 
939     ::Error("AlidNdPtHelper::GetTPCMBTrackMult()","cuts not available");
940     return 0;  
941   }
942
943   //
944   Double_t pos[3]={evtCuts->GetMeanXv(),evtCuts->GetMeanYv(),evtCuts->GetMeanZv()};
945   Double_t err[3]={evtCuts->GetSigmaMeanXv(),evtCuts->GetSigmaMeanYv(),evtCuts->GetSigmaMeanZv()};
946   AliESDVertex vtx0(pos,err);
947
948   //
949   Float_t maxDCAr = accCuts->GetMaxDCAr();
950   Float_t maxDCAz = accCuts->GetMaxDCAz();
951   Float_t minTPCClust = trackCuts->GetMinNClusterTPC();
952   //
953   Int_t ntracks = esdEvent->GetNumberOfTracks();
954   Double_t dca[2],cov[3];
955   Int_t mult=0;
956   for (Int_t i=0;i <ntracks; i++){
957     AliESDtrack *t = esdEvent->GetTrack(i);
958     if (!t) continue;
959     if (t->Charge() == 0) continue;
960     if (!t->GetTPCInnerParam()) continue;
961     if (t->GetTPCNcls()<minTPCClust) continue;
962     //
963     AliExternalTrackParam  *tpcTrack  = new AliExternalTrackParam(*(t->GetTPCInnerParam()));
964     if (!tpcTrack->PropagateToDCA(&vtx0,esdEvent->GetMagneticField(),100.,dca,cov)) 
965     {
966       if(tpcTrack) delete tpcTrack; 
967       continue;
968     }
969     //
970     if (TMath::Abs(dca[0])>maxDCAr || TMath::Abs(dca[1])>maxDCAz) {
971       if(tpcTrack) delete tpcTrack; 
972       continue;
973     }
974
975     mult++;    
976
977     if(tpcTrack) delete tpcTrack; 
978   }
979
980 return mult;  
981 }
982
983 //_____________________________________________________________________________
984 Int_t AlidNdPtHelper::GetTPCMBPrimTrackMult(AliESDEvent *esdEvent, AliStack * stack, AlidNdPtEventCuts *evtCuts, AlidNdPtAcceptanceCuts *accCuts, AliESDtrackCuts *trackCuts)
985 {
986   //
987   // get MB primary event track multiplicity
988   //
989   if(!esdEvent) 
990   { 
991     ::Error("AlidNdPtHelper::GetTPCMBPrimTrackMult()","esd event is NULL");
992     return 0;  
993   }
994
995   if(!stack) 
996   { 
997     ::Error("AlidNdPtHelper::GetTPCMBPrimTrackMult()","esd event is NULL");
998     return 0;  
999   }
1000  
1001   if(!evtCuts || !accCuts || !trackCuts) 
1002   { 
1003     ::Error("AlidNdPtHelper::GetTPCMBPrimTrackMult()","cuts not available");
1004     return 0;  
1005   }
1006
1007   //
1008   Double_t pos[3]={evtCuts->GetMeanXv(),evtCuts->GetMeanYv(),evtCuts->GetMeanZv()};
1009   Double_t err[3]={evtCuts->GetSigmaMeanXv(),evtCuts->GetSigmaMeanYv(),evtCuts->GetSigmaMeanZv()};
1010   AliESDVertex vtx0(pos,err);
1011
1012   //
1013   Float_t maxDCAr = accCuts->GetMaxDCAr();
1014   Float_t maxDCAz = accCuts->GetMaxDCAz();
1015   Float_t minTPCClust = trackCuts->GetMinNClusterTPC();
1016
1017   //
1018   Int_t ntracks = esdEvent->GetNumberOfTracks();
1019   Double_t dca[2],cov[3];
1020   Int_t mult=0;
1021   for (Int_t i=0;i <ntracks; i++){
1022     AliESDtrack *t = esdEvent->GetTrack(i);
1023     if (!t) continue;
1024     if (t->Charge() == 0) continue;
1025     if (!t->GetTPCInnerParam()) continue;
1026     if (t->GetTPCNcls()<minTPCClust) continue;
1027     //
1028     AliExternalTrackParam  *tpcTrack  = new AliExternalTrackParam(*(t->GetTPCInnerParam()));
1029     if (!tpcTrack->PropagateToDCA(&vtx0,esdEvent->GetMagneticField(),100.,dca,cov)) 
1030     {
1031       if(tpcTrack) delete tpcTrack; 
1032       continue;
1033     }
1034     //
1035     if (TMath::Abs(dca[0])>maxDCAr || TMath::Abs(dca[1])>maxDCAz) {
1036       if(tpcTrack) delete tpcTrack; 
1037       continue;
1038     }
1039
1040     Int_t label = TMath::Abs(t->GetLabel());
1041     TParticle *part = stack->Particle(label);
1042     if(!part) { 
1043       if(tpcTrack) delete tpcTrack; 
1044       continue;
1045     }
1046     if(!stack->IsPhysicalPrimary(label)) 
1047     { 
1048       if(tpcTrack) delete tpcTrack; 
1049       continue;
1050     }
1051
1052     mult++;    
1053
1054     if(tpcTrack) delete tpcTrack; 
1055   }
1056
1057 return mult;  
1058 }
1059
1060
1061
1062
1063
1064 //_____________________________________________________________________________
1065 Int_t AlidNdPtHelper::GetMCTrueTrackMult(AliMCEvent *mcEvent, AlidNdPtEventCuts *evtCuts, AlidNdPtAcceptanceCuts *accCuts)
1066 {
1067   //
1068   // calculate mc event true track multiplicity
1069   //
1070   if(!mcEvent) return 0;
1071
1072   AliStack* stack = 0;
1073   Int_t mult = 0;
1074
1075   // MC particle stack
1076   stack = mcEvent->Stack();
1077   if (!stack) return 0;
1078
1079   Bool_t isEventOK = evtCuts->AcceptMCEvent(mcEvent);
1080   if(!isEventOK) return 0; 
1081
1082   Int_t nPart  = stack->GetNtrack();
1083   for (Int_t iMc = 0; iMc < nPart; ++iMc) 
1084   {
1085      TParticle* particle = stack->Particle(iMc);
1086      if (!particle)
1087      continue;
1088
1089      // only charged particles
1090      Double_t charge = particle->GetPDG()->Charge()/3.;
1091      if (charge == 0.0)
1092      continue;
1093       
1094      // physical primary
1095      Bool_t prim = stack->IsPhysicalPrimary(iMc);
1096      if(!prim) continue;
1097
1098      // checked accepted
1099      if(accCuts->AcceptTrack(particle)) 
1100      {
1101        mult++;
1102      }
1103   }
1104
1105 return mult;  
1106 }
1107
1108 //_______________________________________________________________________
1109 void  AlidNdPtHelper::PrintMCInfo(AliStack *pStack,Int_t label)
1110 {
1111 // print information about particles in the stack
1112
1113   if(!pStack)return;
1114   label = TMath::Abs(label);
1115   TParticle *part = pStack->Particle(label);
1116   Printf("########################");
1117   Printf("%s:%d %d UniqueID %d PDG %d P %3.3f",(char*)__FILE__,__LINE__,label,part->GetUniqueID(),part->GetPdgCode(),part->P());
1118   part->Print();
1119   TParticle* mother = part;
1120   Int_t imo = part->GetFirstMother();
1121   Int_t nprim = pStack->GetNprimary();
1122
1123   while((imo >= nprim)) {
1124       mother =  pStack->Particle(imo);
1125       Printf("Mother %s:%d Label %d UniqueID %d PDG %d P %3.3f",(char*)__FILE__,__LINE__,imo,mother->GetUniqueID(),mother->GetPdgCode(),mother->P());
1126       mother->Print();
1127       imo =  mother->GetFirstMother();
1128  }
1129
1130  Printf("########################");
1131 }
1132
1133
1134 //_____________________________________________________________________________
1135 TH1* AlidNdPtHelper::GetContCorrHisto(TH1 *hist) 
1136 {
1137 //
1138 // get contamination histogram
1139 //
1140  if(!hist) return 0;
1141
1142  Int_t nbins = hist->GetNbinsX();
1143  TH1 *h_cont = (TH1D *)hist->Clone();
1144
1145  for(Int_t i=0; i<=nbins+1; i++) {
1146    Double_t binContent = hist->GetBinContent(i);
1147    Double_t binError = hist->GetBinError(i);
1148
1149    h_cont->SetBinContent(i,1.-binContent);
1150    h_cont->SetBinError(i,binError);
1151  }
1152
1153 return h_cont;
1154 }
1155
1156
1157 //_____________________________________________________________________________
1158 TH1* AlidNdPtHelper::ScaleByBinWidth(TH1 *hist) 
1159 {
1160 //
1161 // scale by bin width
1162 //
1163  if(!hist) return 0;
1164
1165  TH1 *h_scale = (TH1D *)hist->Clone();
1166  h_scale->Scale(1.,"width");
1167
1168 return h_scale;
1169 }
1170
1171 //_____________________________________________________________________________
1172 TH1* AlidNdPtHelper::CalcRelativeDifference(TH1 *hist1, TH1 *hist2) 
1173 {
1174 //
1175 // calculate rel. difference 
1176 //
1177
1178  if(!hist1) return 0;
1179  if(!hist2) return 0;
1180
1181  TH1 *h1_clone = (TH1D *)hist1->Clone();
1182  h1_clone->Sumw2();
1183
1184  // (rec-mc)/mc
1185  h1_clone->Add(hist2,-1);
1186  h1_clone->Divide(hist2);
1187
1188 return h1_clone;
1189 }
1190
1191 //_____________________________________________________________________________
1192 TH1* AlidNdPtHelper::CalcRelativeDifferenceFun(TH1 *hist1, TF1 *fun) 
1193 {
1194 //
1195 // calculate rel. difference
1196 // between histogram and function
1197 //
1198  if(!hist1) return 0;
1199  if(!fun) return 0;
1200
1201  TH1 *h1_clone = (TH1D *)hist1->Clone();
1202  h1_clone->Sumw2();
1203
1204  // 
1205  h1_clone->Add(fun,-1);
1206  h1_clone->Divide(hist1);
1207
1208 return h1_clone;
1209 }
1210
1211 //_____________________________________________________________________________
1212 TH1* AlidNdPtHelper::NormalizeToEvent(TH2 *hist1, TH1 *hist2) 
1213 {
1214 // normalise to event for a given multiplicity bin
1215 // return pt histogram 
1216
1217  if(!hist1) return 0;
1218  if(!hist2) return 0;
1219  char name[256];
1220
1221  Int_t nbinsX = hist1->GetNbinsX();
1222  //Int_t nbinsY = hist1->GetNbinsY();
1223
1224  TH1D *hist_norm = 0;
1225  for(Int_t i=0; i<=nbinsX+1; i++) {
1226    sprintf(name,"mom_%d",i);
1227    TH1D *hist = (TH1D*)hist1->ProjectionY(name,i+1,i+1);
1228
1229    sprintf(name,"mom_norm");
1230    if(i==0) { 
1231      hist_norm = (TH1D *)hist->Clone(name);
1232      hist_norm->Reset();
1233    }
1234
1235    Double_t nbEvents = hist2->GetBinContent(i);
1236    if(!nbEvents) { nbEvents = 1.; };
1237
1238    hist->Scale(1./nbEvents);
1239    hist_norm->Add(hist);
1240  }
1241
1242 return hist_norm;
1243 }
1244
1245 //_____________________________________________________________________________
1246 THnSparse* AlidNdPtHelper::GenerateCorrMatrix(THnSparse *hist1, THnSparse *hist2, char *name) {
1247 // generate correction matrix
1248 if(!hist1 || !hist2) return 0; 
1249
1250 THnSparse *h =(THnSparse*)hist1->Clone(name);;
1251 h->Divide(hist1,hist2,1,1,"B");
1252
1253 return h;
1254 }
1255
1256 //_____________________________________________________________________________
1257 TH2* AlidNdPtHelper::GenerateCorrMatrix(TH2 *hist1, TH2 *hist2, char *name) {
1258 // generate correction matrix
1259 if(!hist1 || !hist2) return 0; 
1260
1261 TH2D *h =(TH2D*)hist1->Clone(name);;
1262 h->Divide(hist1,hist2,1,1,"B");
1263
1264 return h;
1265 }
1266
1267 //_____________________________________________________________________________
1268 TH1* AlidNdPtHelper::GenerateCorrMatrix(TH1 *hist1, TH1 *hist2, char *name) {
1269 // generate correction matrix
1270 if(!hist1 || !hist2) return 0; 
1271
1272 TH1D *h =(TH1D*)hist1->Clone(name);;
1273 h->Divide(hist1,hist2,1,1,"B");
1274
1275 return h;
1276 }
1277
1278 //_____________________________________________________________________________
1279 THnSparse* AlidNdPtHelper::GenerateContCorrMatrix(THnSparse *hist1, THnSparse *hist2, char *name) {
1280 // generate contamination correction matrix
1281 if(!hist1 || !hist2) return 0; 
1282
1283 THnSparse *hist =  GenerateCorrMatrix(hist1, hist2, name);
1284 if(!hist) return 0;
1285
1286 // only for non ZERO bins!!!!
1287
1288 Int_t* coord = new Int_t[hist->GetNdimensions()];
1289 memset(coord, 0, sizeof(Int_t) * hist->GetNdimensions());
1290
1291   for (Long64_t i = 0; i < hist->GetNbins(); ++i) {
1292     Double_t v = hist->GetBinContent(i, coord);
1293     hist->SetBinContent(coord, 1.0-v);
1294     //printf("v %f, hist->GetBinContent(i, coord) %f \n",v,hist->GetBinContent(i, coord));
1295     Double_t err = hist->GetBinError(coord);
1296     hist->SetBinError(coord, err);
1297   }
1298
1299 delete [] coord;
1300
1301 return hist;
1302 }
1303
1304 //_____________________________________________________________________________
1305 TH2* AlidNdPtHelper::GenerateContCorrMatrix(TH2 *hist1, TH2 *hist2, char *name) {
1306 // generate contamination correction matrix
1307 if(!hist1 || !hist2) return 0; 
1308
1309 TH2 *hist = GenerateCorrMatrix(hist1, hist2, name);
1310 if(!hist) return 0;
1311
1312 Int_t nBinsX = hist->GetNbinsX();
1313 Int_t nBinsY = hist->GetNbinsY();
1314
1315   for (Int_t i = 0; i < nBinsX+1; i++) {
1316   for (Int_t j = 0; j < nBinsY+1; j++) {
1317      Double_t cont = hist->GetBinContent(i,j);
1318      hist->SetBinContent(i,j,1.-cont);
1319      Double_t err = hist->GetBinError(i,j);
1320      hist->SetBinError(i,j,err);
1321   }
1322   }
1323
1324 return hist;
1325 }
1326
1327 //_____________________________________________________________________________
1328 TH1* AlidNdPtHelper::GenerateContCorrMatrix(TH1 *hist1, TH1 *hist2, char *name) {
1329 // generate contamination correction matrix
1330 if(!hist1 || !hist2) return 0; 
1331
1332 TH1 *hist = GenerateCorrMatrix(hist1, hist2, name);
1333 if(!hist) return 0;
1334
1335 Int_t nBinsX = hist->GetNbinsX();
1336
1337   for (Int_t i = 0; i < nBinsX+1; i++) {
1338      Double_t cont = hist->GetBinContent(i);
1339      hist->SetBinContent(i,1.-cont);
1340      Double_t err = hist->GetBinError(i);
1341      hist->SetBinError(i,err);
1342   }
1343
1344 return hist;
1345 }
1346
1347 //_____________________________________________________________________________
1348 const AliESDVertex* AlidNdPtHelper::GetTPCVertexZ(AliESDEvent* esdEvent, Float_t sigmaXYcut, Float_t distXYcut, Float_t distZcut, Int_t nclCut, Float_t fraction, Int_t ntracksMin){
1349   //
1350   // TPC Z vertexer
1351   //
1352   Double_t vtxpos[3]={0.,0.,0.};
1353   Double_t vtxsigma[3]={.2,.2,100.};
1354   AliESDVertex vtx0(vtxpos,vtxsigma);
1355   //
1356   Int_t ntracks = esdEvent->GetNumberOfTracks();
1357   TVectorD ztrack(ntracks);
1358   //Float_t dcar, dcaz;
1359   //Float_t point[2],cov[3];
1360   Double_t dca[2],cov[3];
1361   Int_t counter=0;
1362   for (Int_t i=0;i <ntracks; i++){
1363     AliESDtrack *t = esdEvent->GetTrack(i);
1364     if (!t) continue;
1365     if (!t->GetTPCInnerParam()) continue;
1366     if (t->GetTPCNcls()<nclCut) continue;
1367     //
1368     AliExternalTrackParam  *tpcTrack  = new AliExternalTrackParam(*(t->GetTPCInnerParam()));
1369     if (!tpcTrack->PropagateToDCA(&vtx0,esdEvent->GetMagneticField(),100.,dca,cov)) continue;
1370
1371     //
1372     if (TMath::Abs(dca[0])>distXYcut) continue;
1373     if (TMath::Sqrt(cov[0])>sigmaXYcut) continue;    
1374     if (TMath::Abs(tpcTrack->GetZ())>distZcut) continue;
1375
1376     /*
1377     t->GetImpactParametersTPC(dcar,dcaz);
1378     if (TMath::Abs(dcar)>distXYcut) continue;
1379     //
1380     t->GetImpactParametersTPC(point,cov);
1381     if (TMath::Sqrt(cov[0])>sigmaXYcut) continue;    
1382     //
1383     AliExternalTrackParam  tpcTrack(*(t->GetTPCInnerParam()));
1384     if (!tpcTrack.PropagateToDCA(&vtx0,esdEvent->GetMagneticField(), 100)) continue;
1385     if (TMath::Abs(tpcTrack.GetZ())>distZcut) continue;
1386     */
1387     ztrack[counter]=tpcTrack->GetZ();
1388     counter++;    
1389
1390     if(tpcTrack) delete tpcTrack;
1391   }
1392   //
1393   // Find LTM z position
1394   //
1395   Double_t mean=0, sigma=0;
1396   if (counter<ntracksMin) return 0;
1397   //
1398   Int_t nused = TMath::Nint(counter*fraction);
1399   if (nused==counter) nused=counter-1;  
1400   if (nused>1){
1401     AliMathBase::EvaluateUni(counter, ztrack.GetMatrixArray(), mean,sigma, TMath::Nint(counter*fraction));
1402     sigma/=TMath::Sqrt(nused);
1403   }else{
1404     mean  = TMath::Mean(counter, ztrack.GetMatrixArray());
1405     sigma = TMath::RMS(counter, ztrack.GetMatrixArray());
1406     sigma/=TMath::Sqrt(counter-1);
1407   }
1408   vtxpos[2]=mean;
1409   vtxsigma[2]=sigma;
1410   const AliESDVertex* vertex = new AliESDVertex(vtxpos, vtxsigma);
1411   return vertex;
1412 }
1413
1414 //_____________________________________________________________________________
1415 Int_t  AlidNdPtHelper::GetSPDMBTrackMult(AliESDEvent* esdEvent, Float_t deltaThetaCut, Float_t deltaPhiCut) 
1416 {
1417   //
1418   // SPD track multiplicity
1419   //
1420
1421   // get tracklets
1422   const AliMultiplicity* mult = esdEvent->GetMultiplicity();
1423   if (!mult)
1424      return 0;
1425
1426   // get multiplicity from SPD tracklets
1427   Int_t inputCount = 0; 
1428   for (Int_t i=0; i<mult->GetNumberOfTracklets(); ++i)
1429   {
1430     //printf("%d %f %f %f\n", i, mult->GetTheta(i), mult->GetPhi(i), mult->GetDeltaPhi(i));
1431
1432      Float_t phi = mult->GetPhi(i);
1433      if (phi < 0)
1434        phi += TMath::Pi() * 2;
1435      Float_t deltaPhi = mult->GetDeltaPhi(i);
1436      Float_t deltaTheta = mult->GetDeltaTheta(i);
1437
1438      if (TMath::Abs(deltaPhi) > 1)
1439        printf("WARNING: Very high Delta Phi: %d %f %f %f\n", i, mult->GetTheta(i), mult->GetPhi(i), deltaPhi);
1440
1441      if (deltaThetaCut > 0. && TMath::Abs(deltaTheta) > deltaThetaCut)
1442         continue;
1443
1444      if (deltaPhiCut > 0. && TMath::Abs(deltaPhi) > deltaPhiCut)
1445         continue;
1446       
1447      ++inputCount;
1448   }
1449
1450 return inputCount;
1451 }
1452
1453 //_____________________________________________________________________________
1454 Int_t  AlidNdPtHelper::GetSPDMBPrimTrackMult(AliESDEvent* esdEvent, AliStack* stack, Float_t deltaThetaCut, Float_t deltaPhiCut) 
1455 {
1456   //
1457   // SPD track multiplicity
1458   //
1459
1460   // get tracklets
1461   const AliMultiplicity* mult = esdEvent->GetMultiplicity();
1462   if (!mult)
1463      return 0;
1464
1465   // get multiplicity from SPD tracklets
1466   Int_t inputCount = 0; 
1467   for (Int_t i=0; i<mult->GetNumberOfTracklets(); ++i)
1468   {
1469     //printf("%d %f %f %f\n", i, mult->GetTheta(i), mult->GetPhi(i), mult->GetDeltaPhi(i));
1470
1471      Float_t phi = mult->GetPhi(i);
1472      if (phi < 0)
1473        phi += TMath::Pi() * 2;
1474      Float_t deltaPhi = mult->GetDeltaPhi(i);
1475      Float_t deltaTheta = mult->GetDeltaTheta(i);
1476
1477      if (TMath::Abs(deltaPhi) > 1)
1478        printf("WARNING: Very high Delta Phi: %d %f %f %f\n", i, mult->GetTheta(i), mult->GetPhi(i), deltaPhi);
1479
1480      if (deltaThetaCut > 0. && TMath::Abs(deltaTheta) > deltaThetaCut)
1481         continue;
1482
1483      if (deltaPhiCut > 0. && TMath::Abs(deltaPhi) > deltaPhiCut)
1484         continue;
1485
1486
1487      if (mult->GetLabel(i, 0) < 0 || mult->GetLabel(i, 0) != mult->GetLabel(i, 1) || 
1488          !stack->IsPhysicalPrimary(mult->GetLabel(i, 0)))
1489         continue;
1490
1491       
1492      ++inputCount;
1493   }
1494
1495 return inputCount;
1496 }
1497
1498