]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWG/muon/AliAnalysisTaskSingleMu.cxx
Add method to transparently get SPD vertex (Diego)
[u/mrichter/AliRoot.git] / PWG / muon / AliAnalysisTaskSingleMu.cxx
1 /**************************************************************************
2  * Copyright(c) 1998-2007, 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 /* $Id$ */
17
18 //-----------------------------------------------------------------------------
19 /// \class AliAnalysisTaskSingleMu
20 /// Analysis task for single muons in the spectrometer.
21 /// The output is a list of histograms and CF containers.
22 /// The macro class can run on AODs or ESDs.
23 /// In the latter case a flag can be activated to produce a tree as output.
24 /// If Monte Carlo information is present, some basics checks are performed.
25 ///
26 /// \author Diego Stocco
27 //-----------------------------------------------------------------------------
28
29 #define AliAnalysisTaskSingleMu_cxx
30
31 #include "AliAnalysisTaskSingleMu.h"
32
33 // ROOT includes
34 #include "TROOT.h"
35 #include "TH1.h"
36 #include "TH2.h"
37 #include "TAxis.h"
38 #include "TCanvas.h"
39 #include "TLegend.h"
40 #include "TMath.h"
41 #include "TObjString.h"
42 #include "TObjArray.h"
43 #include "TF1.h"
44 #include "TStyle.h"
45 //#include "TMCProcess.h"
46 #include "TArrayI.h"
47 #include "TPaveStats.h"
48 #include "TFitResultPtr.h"
49
50 // STEER includes
51 #include "AliAODEvent.h"
52 #include "AliAODTrack.h"
53 #include "AliAODMCParticle.h"
54 #include "AliMCEvent.h"
55 #include "AliMCParticle.h"
56 #include "AliESDEvent.h"
57 #include "AliESDMuonTrack.h"
58 #include "AliVHeader.h"
59 #include "AliAODMCHeader.h"
60 #include "AliStack.h"
61
62 // ANALYSIS includes
63 #include "AliAnalysisManager.h"
64
65 // CORRFW includes
66 #include "AliCFContainer.h"
67 #include "AliCFGridSparse.h"
68 #include "AliCFEffGrid.h"
69
70 // PWG includes
71 #include "AliVAnalysisMuon.h"
72 #include "AliMergeableCollection.h"
73 #include "AliCounterCollection.h"
74 #include "AliMuonTrackCuts.h"
75
76
77 /// \cond CLASSIMP
78 ClassImp(AliAnalysisTaskSingleMu) // Class implementation in ROOT context
79 /// \endcond
80
81
82 //________________________________________________________________________
83 AliAnalysisTaskSingleMu::AliAnalysisTaskSingleMu() :
84   AliVAnalysisMuon(),
85   fThetaAbsKeys(0x0)
86 {
87   /// Default ctor.
88 }
89
90 //________________________________________________________________________
91 AliAnalysisTaskSingleMu::AliAnalysisTaskSingleMu(const char *name, const AliMuonTrackCuts& cuts) :
92   AliVAnalysisMuon(name, cuts),
93   fThetaAbsKeys(0x0)
94 {
95   //
96   /// Constructor.
97   //
98   TString thetaAbsKeys = "ThetaAbs23 ThetaAbs310";
99   fThetaAbsKeys = thetaAbsKeys.Tokenize(" ");
100 }
101
102
103 //________________________________________________________________________
104 AliAnalysisTaskSingleMu::~AliAnalysisTaskSingleMu()
105 {
106   //
107   /// Destructor
108   //
109
110   delete fThetaAbsKeys;
111 }
112
113 //___________________________________________________________________________
114 void AliAnalysisTaskSingleMu::MyUserCreateOutputObjects()
115 {
116
117   TH1* histo = 0x0;
118   TString histoName = "", histoTitle = "";
119   
120   Int_t nVzBins = 40;
121   Double_t vzMin = -20., vzMax = 20.;
122   TString vzName("Vz"), vzTitle("Vz"), vzUnits("cm");  
123   
124   histoName = "hIpVtx";
125   histo = new TH1F(histoName.Data(), histoName.Data(), nVzBins, vzMin, vzMax);
126   histo->SetXTitle("v_{z} (cm)");
127   AddObjectToCollection(histo, kIPVz);
128
129   
130   Int_t nPtBins = 80;
131   Double_t ptMin = 0., ptMax = 80.;
132   TString ptName("Pt"), ptTitle("p_{t}"), ptUnits("GeV/c");
133   
134   Int_t nEtaBins = 25;
135   Double_t etaMin = -4.5, etaMax = -2.;
136   TString etaName("Eta"), etaTitle("#eta"), etaUnits("");
137   
138   Int_t nPhiBins = 36;
139   Double_t phiMin = 0.; Double_t phiMax = 2.*TMath::Pi();
140   TString phiName("Phi"), phiTitle("#phi"), phiUnits("rad");
141     
142   Int_t nChargeBins = 2;
143   Double_t chargeMin = -2, chargeMax = 2.;
144   TString chargeName("Charge"), chargeTitle("charge"), chargeUnits("e");
145   
146   Int_t nThetaAbsEndBins = 2;
147   Double_t thetaAbsEndMin = -0.5, thetaAbsEndMax = 1.5;
148   TString thetaAbsEndName("ThetaAbsEnd"), thetaAbsEndTitle("#theta_{abs}"), thetaAbsEndUnits("a.u.");    
149   
150   Int_t nMotherTypeBins = kNtrackSources;
151   Double_t motherTypeMin = -0.5, motherTypeMax = (Double_t)kNtrackSources - 0.5;
152   TString motherType("MotherType"), motherTypeTitle("motherType"), motherTypeUnits("");
153     
154   Int_t nbins[kNvars] = {nPtBins, nEtaBins, nPhiBins, nVzBins, nChargeBins, nThetaAbsEndBins, nMotherTypeBins};
155   Double_t xmin[kNvars] = {ptMin, etaMin, phiMin, vzMin, chargeMin, thetaAbsEndMin, motherTypeMin};
156   Double_t xmax[kNvars] = {ptMax, etaMax, phiMax, vzMax, chargeMax, thetaAbsEndMax, motherTypeMax};
157   TString axisTitle[kNvars] = {ptTitle, etaTitle, phiTitle, vzTitle, chargeTitle, thetaAbsEndTitle, motherTypeTitle};
158   TString axisUnits[kNvars] = {ptUnits, etaUnits, phiUnits, vzUnits, chargeUnits, thetaAbsEndUnits, motherTypeUnits};
159
160   AliCFContainer* cfContainer = new AliCFContainer("SingleMuContainer","Container for tracks",kNsteps,kNvars,nbins);
161   
162   for ( Int_t idim = 0; idim<kNvars; idim++){
163     histoTitle = Form("%s (%s)", axisTitle[idim].Data(), axisUnits[idim].Data());
164     histoTitle.ReplaceAll("()","");
165     
166     cfContainer->SetVarTitle(idim, histoTitle.Data());
167     cfContainer->SetBinLimits(idim, xmin[idim], xmax[idim]);
168   }
169   
170   TString stepTitle[kNsteps] = {"reconstructed", "generated"};
171
172   TAxis* currAxis = 0x0;
173   for (Int_t istep=0; istep<kNsteps; istep++){
174     cfContainer->SetStepTitle(istep, stepTitle[istep].Data());
175     AliCFGridSparse* gridSparse = cfContainer->GetGrid(istep);
176         
177     currAxis = gridSparse->GetAxis(kHvarMotherType);
178     for ( Int_t ibin=0; ibin<fSrcKeys->GetEntries(); ibin++ ) {
179       currAxis->SetBinLabel(ibin+1, fSrcKeys->At(ibin)->GetName());
180     }
181   }
182   
183   AddObjectToCollection(cfContainer, kTrackContainer);
184   
185   fMuonTrackCuts->Print("mask");
186 }
187
188 //________________________________________________________________________
189 void AliAnalysisTaskSingleMu::ProcessEvent(TString physSel, const TObjArray& selectTrigClasses, TString centrality)
190 {
191   //
192   /// Fill output objects
193   //
194
195   if ( GetVertexSPD()->GetNContributors() < fMinNvtxContirbutors ) return;
196
197   Double_t ipVz = GetVertexSPD()->GetZ();
198   Double_t ipVzMC = 0;
199   if ( IsMC() ) {
200     if ( fMCEvent ) ipVzMC = fMCEvent->GetPrimaryVertex()->GetZ();
201     else if ( fAODEvent ) {
202       AliAODMCHeader* aodMCHeader = (AliAODMCHeader *)fAODEvent->FindListObject(AliAODMCHeader::StdBranchName());
203       if ( aodMCHeader ) ipVzMC = aodMCHeader->GetVtxZ();
204     }
205   }
206   
207   for ( Int_t itrig=0; itrig<selectTrigClasses.GetEntries(); ++itrig ) {
208     TString trigClassName = ((TObjString*)selectTrigClasses.At(itrig))->GetString();
209     ((TH1*)GetMergeableObject(physSel, trigClassName, centrality, "hIpVtx"))->Fill(ipVz);
210   }
211
212   Bool_t isPileupFromSPD = ( fAODEvent && ! fAODEvent->GetTracklets() ) ? InputEvent()->IsPileupFromSPD(3, 0.8, 3., 2., 5.) : InputEvent()->IsPileupFromSPDInMultBins(); // Avoid break when reading Muon AODs (tracklet info is not present and IsPileupFromSPDInMultBins crashes
213   if ( isPileupFromSPD ) return;
214   
215   Double_t containerInput[kNvars];
216   AliVParticle* track = 0x0;
217
218   for ( Int_t istep = 0; istep<2; ++istep ) {
219     Int_t nTracks = ( istep == kStepReconstructed ) ? GetNTracks() : GetNMCTracks();
220     for (Int_t itrack = 0; itrack < nTracks; itrack++) {
221       track = ( istep == kStepReconstructed ) ? GetTrack(itrack) : GetMCTrack(itrack);
222       
223       Bool_t isSelected = ( istep == kStepReconstructed ) ? fMuonTrackCuts->IsSelected(track) : ( TMath::Abs(track->PdgCode()) == 13 );
224       if ( ! isSelected ) continue;
225       
226       // In W simulations with Pythia, sometimes muon is stored twice.
227       // Remove muon in case it has another muon as daugther
228       if ( istep == kStepGeneratedMC ) {
229         Int_t firstDaughter = GetDaughterIndex(track, 0);
230         if ( firstDaughter >= 0 ) {
231           Bool_t hasMuonDaughter = kFALSE;
232           Int_t lastDaughter = GetDaughterIndex(track, 1);
233           for ( Int_t idaugh=firstDaughter; idaugh<=lastDaughter; idaugh++ ) {
234             AliVParticle* currTrack = GetMCTrack(idaugh);
235             if ( currTrack->PdgCode() == track->PdgCode() ) {
236               hasMuonDaughter = kTRUE;
237               break;
238             }
239           }
240           if ( hasMuonDaughter ) {
241             AliDebug(1, Form("Current muon (%i) has muon daughter: rejecting it", itrack));
242             continue;
243           }
244         }
245       }      
246       
247       Int_t trackSrc = ( istep == kStepReconstructed ) ? GetParticleType(track) : RecoTrackMother(track);
248       
249       Double_t thetaAbsEndDeg = 0;
250       if ( istep == kStepReconstructed ) {
251         Double_t rAbsEnd =  ( fAODEvent ) ? ((AliAODTrack*)track)->GetRAtAbsorberEnd(): ((AliESDMuonTrack*)track)->GetRAtAbsorberEnd();
252         thetaAbsEndDeg = TMath::ATan( rAbsEnd / 505. ) * TMath::RadToDeg();
253       }
254       else {
255         thetaAbsEndDeg = ( TMath::Pi()-track->Theta() ) * TMath::RadToDeg();
256       }
257       Int_t thetaAbsBin = ( thetaAbsEndDeg < 3. ) ? kThetaAbs23 : kThetaAbs310;
258
259       containerInput[kHvarPt]         = track->Pt();
260       containerInput[kHvarEta]        = track->Eta();
261       containerInput[kHvarPhi]        = track->Phi();
262       containerInput[kHvarVz]         = ( istep == kStepReconstructed ) ? ipVz : ipVzMC;
263       containerInput[kHvarCharge]     = track->Charge()/3.;
264       containerInput[kHvarThetaAbs]   = (Double_t)thetaAbsBin;
265       containerInput[kHvarMotherType] = (Double_t)trackSrc;
266       
267       for ( Int_t itrig=0; itrig<selectTrigClasses.GetEntries(); ++itrig ) {
268         TString trigClassName = ((TObjString*)selectTrigClasses.At(itrig))->GetString();
269         if ( istep == kStepReconstructed && ! TrackPtCutMatchTrigClass(track, trigClassName) ) continue;
270         ((AliCFContainer*)GetMergeableObject(physSel, trigClassName, centrality, "SingleMuContainer"))->Fill(containerInput,istep);
271       } // loop on selected trigger classes
272     } // loop on tracks
273   } // loop on container steps
274 }
275
276
277 //________________________________________________________________________
278 void AliAnalysisTaskSingleMu::Terminate(Option_t *) {
279   //
280   /// Draw some histograms at the end.
281   //
282
283   AliVAnalysisMuon::Terminate("");
284
285   if ( ! fMergeableCollection ) return;
286   
287   TString physSel = fTerminateOptions->At(0)->GetName();
288   TString trigClassName = fTerminateOptions->At(1)->GetName();
289   TString centralityRange = fTerminateOptions->At(2)->GetName();
290   TString furtherOpt = fTerminateOptions->At(3)->GetName();
291   
292   TString minBiasTrig = "";
293   TObjArray* optArr = furtherOpt.Tokenize(" ");
294   TString currName = "";
295   for ( Int_t iopt=0; iopt<optArr->GetEntries(); iopt++ ) {
296     currName = optArr->At(iopt)->GetName();
297     if ( currName.Contains("-B-") ) minBiasTrig = currName;
298   }
299   delete optArr;
300
301   furtherOpt.ToUpper();
302   
303   AliCFContainer* cfContainer = static_cast<AliCFContainer*> ( GetSum(physSel,trigClassName,centralityRange,"SingleMuContainer") );
304   if ( ! cfContainer ) return;
305   
306   AliCFEffGrid* effSparse = new AliCFEffGrid(Form("eff%s", cfContainer->GetName()),Form("Efficiency %s", cfContainer->GetTitle()),*cfContainer);
307   effSparse->CalculateEfficiency(kStepReconstructed, kStepGeneratedMC);
308   
309   AliCFGridSparse* gridSparseArray[3] = {effSparse->GetNum(), effSparse->GetDen(), effSparse};
310   TString gridSparseName[3] = {cfContainer->GetStepTitle(kStepReconstructed), cfContainer->GetStepTitle(kStepGeneratedMC), "Efficiency"};
311
312   Int_t srcColors[kNtrackSources] = {kBlack, kRed, kSpring, kTeal, kBlue, kViolet, kMagenta, kOrange};
313 //  TString allSrcNames = "";
314 //  for ( Int_t isrc=0; isrc<kNtrackSources; ++isrc ) {
315 //    if ( ! allSrcNames.IsNull() ) allSrcNames.Append(" ");
316 //    allSrcNames += fSrcKeys->At(isrc)->GetName();
317 //  }
318
319   TCanvas* can = 0x0;
320   Int_t xshift = 100;
321   Int_t yshift = 100;
322   Int_t igroup1 = -1;
323   Int_t igroup2 = 0;
324   
325   Bool_t isMC = furtherOpt.Contains("MC");
326   Int_t firstSrc = ( isMC ) ? 0 : kUnidentified;
327   Int_t lastSrc  = ( isMC ) ? kNtrackSources - 1 : kUnidentified;
328   if ( ! isMC ) srcColors[kUnidentified] = 1;
329
330   TString histoName = "", histoPattern = "", drawOpt = "";
331   ////////////////
332   // Kinematics //
333   ////////////////
334   TCanvas* canKine[3] = {0x0, 0x0, 0x0};
335   TLegend* legKine[3] = {0x0, 0x0, 0x0};
336   for ( Int_t isrc = firstSrc; isrc <= lastSrc; ++isrc ) {
337     for ( Int_t icharge=0; icharge<2; ++icharge ) {        
338       for ( Int_t igrid=0; igrid<3; ++igrid ) {
339         if ( gridSparseArray[igrid]->GetEntries() == 0. ) break;
340         if ( gridSparseArray[igrid]->IsA() != AliCFEffGrid::Class() ) {
341           SetSparseRange(gridSparseArray[igrid], kHvarEta, "", -3.999, -2.501);
342           SetSparseRange(gridSparseArray[igrid], kHvarMotherType, "", isrc+1, isrc+1, "USEBIN");
343           SetSparseRange(gridSparseArray[igrid], kHvarCharge, "", icharge+1, icharge+1, "USEBIN");
344         }
345         if ( ! canKine[igrid] ) {
346           igroup1++;
347           igroup2 = 0;
348           currName = Form("%s_proj_%s", GetName(), gridSparseName[igrid].Data());
349           canKine[igrid] = new TCanvas(currName.Data(),currName.Data(),igroup1*xshift,igroup2*yshift,600,600);
350           canKine[igrid]->Divide(2,2);
351           legKine[igrid] = new TLegend(0.6, 0.6, 0.8, 0.8);
352           igroup2++;
353         }
354         for ( Int_t iproj=0; iproj<4; ++iproj ) {
355           canKine[igrid]->cd(iproj+1);
356           if ( ( iproj == kHvarPt || iproj == kHvarVz ) && gridSparseArray[igrid]->IsA() != AliCFEffGrid::Class() ) gPad->SetLogy();
357           TH1* projHisto = gridSparseArray[igrid]->Project(iproj);
358           projHisto->SetName(Form("proj%i_%s_src%i_charge%i", iproj, gridSparseName[igrid].Data(), isrc, icharge));
359           if ( projHisto->GetEntries() == 0 ) continue;
360           Bool_t isFirst = ( gPad->GetListOfPrimitives()->GetEntries() == 0 );
361           drawOpt = isFirst ? "e" : "esames";
362           //if ( isrc == kUnidentified && ! drawOpt.Contains("same") ) isMC = kFALSE;
363           //if ( ! isMC ) srcColors[kUnidentified] = 1;
364           projHisto->SetLineColor(srcColors[isrc]);
365           projHisto->SetMarkerColor(srcColors[isrc]);
366           projHisto->SetMarkerStyle(20+4*icharge);
367           projHisto->Draw(drawOpt.Data());
368           gPad->Update();
369           TPaveStats* paveStats = (TPaveStats*)projHisto->FindObject("stats");
370           if ( paveStats ) paveStats->SetTextColor(srcColors[isrc]);
371           if ( iproj == 0 ) {
372             TString legEntry = fChargeKeys->At(icharge)->GetName();
373             if ( isMC ) legEntry += Form(" %s", fSrcKeys->At(isrc)->GetName());
374             legKine[igrid]->AddEntry(projHisto,legEntry.Data(), "lp");
375           }
376         } // loop on grid sparse
377       } // loop on projections
378     } // loop on mu charge
379   } // loop on track sources
380   
381   
382   for ( Int_t igrid=0; igrid<3; igrid++ ) {
383     if ( ! canKine[igrid] ) continue;
384     canKine[igrid]->cd(1);
385     legKine[igrid]->Draw("same");
386     if ( gridSparseArray[igrid]->IsA() == AliCFEffGrid::Class() ) continue;
387     SetSparseRange(gridSparseArray[igrid], kHvarCharge, "", 1, gridSparseArray[igrid]->GetAxis(kHvarCharge)->GetNbins(), "USEBIN"); // Reset range
388   } // loop on container steps
389   
390   
391   //////////////////////
392   // Event statistics //
393   //////////////////////
394   printf("\nTotal analyzed events:\n");
395   TString evtSel = Form("trigger:%s", trigClassName.Data());
396   fEventCounters->PrintSum(evtSel.Data());
397   printf("Physics selected analyzed events:\n");
398   evtSel = Form("trigger:%s/selected:yes", trigClassName.Data());
399   fEventCounters->PrintSum(evtSel.Data());
400   
401   TString countPhysSel = "any";
402   if ( physSel.Contains(fPhysSelKeys->At(kPhysSelPass)->GetName()) ) countPhysSel = "yes";
403   else if ( physSel.Contains(fPhysSelKeys->At(kPhysSelReject)->GetName()) ) countPhysSel="no";
404   countPhysSel.Prepend("selected:");
405   printf("Analyzed events vs. centrality:\n");
406   evtSel = Form("trigger:%s/%s", trigClassName.Data(), countPhysSel.Data());
407   fEventCounters->Print("centrality",evtSel.Data(),kTRUE);
408   
409   
410   ///////////////////
411   // Vertex method //
412   ///////////////////
413   if ( ! furtherOpt.Contains("VERTEX") ) return;
414   Int_t firstMother = kUnidentified, lastMother = kUnidentified;
415   igroup1++;
416   TH1* eventVertex = (TH1*)GetSum(physSel, minBiasTrig, centralityRange, "hIpVtx");
417   if ( ! eventVertex ) return;
418   Double_t minZ = -9.99, maxZ = 9.99;
419   Double_t meanZ = 0., sigmaZ = 4.;
420   Double_t nSigma = 2.;
421   TString fitOpt = "R0S";
422   Bool_t fixFitRange = kFALSE;
423   TString fitFormula = Form("[0]+[1]*(x+[2])");
424     
425   // Get vertex shape    
426   if ( eventVertex->GetSumw2N() == 0 ) eventVertex->Sumw2();
427   Double_t eventVtxIntegral = eventVertex->Integral(0,eventVertex->GetNbinsX()+1); // Include under/overflow
428   printf("Event vertex integral %.0f\n\n", eventVtxIntegral);
429   if ( eventVtxIntegral <= 0. ) return;
430   eventVertex->Scale(1./eventVtxIntegral);
431   printf("\nFit MB vertex\n");
432   eventVertex->Fit("gaus",fitOpt.Data(),"",minZ,maxZ);
433   TF1* vtxFit = (TF1*)eventVertex->GetListOfFunctions()->FindObject("gaus");
434   currName = "vtxIntegrated";
435   can = new TCanvas(currName.Data(),currName.Data(),igroup1*xshift,igroup2*yshift,600,600);
436   can->SetLogy();
437   eventVertex->Draw();
438   vtxFit->Draw("same");
439
440   
441   enum {kRecoHF, kRecoBkg, kInputHF, kInputDecay, kRecoAll, kNrecoHistos};
442   TString baseRecoName[kNrecoHistos] = {"RecoHF", "RecoBkg", "InputHF", "InputDecay", "RecoAll"};
443   TArrayI sumMothers[kNrecoHistos];
444   sumMothers[kRecoHF].Set(0);
445   sumMothers[kRecoBkg].Set(0);
446   sumMothers[kInputHF].Set(3);
447   sumMothers[kInputHF][0] = kCharmMu;
448   sumMothers[kInputHF][1] = kBeautyMu;
449   sumMothers[kInputHF][2] = kQuarkoniumMu;
450   sumMothers[kInputDecay].Set(1);
451   sumMothers[kInputDecay][0] = kDecayMu;
452   sumMothers[kRecoAll].Set(kNtrackSources);
453   for ( Int_t isrc=0; isrc<kNtrackSources; ++isrc ) {
454     sumMothers[kRecoAll][isrc] = isrc;
455   }
456   
457   meanZ = vtxFit->GetParameter(1);
458   sigmaZ = vtxFit->GetParameter(2);
459   
460   Double_t minZfit = ( fixFitRange ) ? minZ : meanZ - nSigma*sigmaZ;
461   Double_t maxZfit = ( fixFitRange ) ? maxZ : meanZ + nSigma*sigmaZ;
462   
463   TF1* fitFunc = new TF1("fitFunc", fitFormula.Data(), minZ, maxZ);
464   fitFunc->SetLineColor(2);
465   fitFunc->SetParNames("Line norm", "Line slope", "Free path");
466   const Double_t kFreePath = 153.; // 150.; // 130.; // cm
467   //fitFunc->SetParameters(0.,1.);
468   fitFunc->FixParameter(2, kFreePath);
469
470   AliCFGridSparse* gridSparse = cfContainer->GetGrid(kStepReconstructed);
471   TAxis* ptAxis = gridSparse->GetAxis(kHvarPt);
472   
473   Double_t slope = 0.;
474   Double_t limitNorm = 0., limitSlope = 0.;
475   Int_t firstPtBin = 0, lastPtBin = 0;
476   
477   gStyle->SetOptFit(1111);
478
479   for ( Int_t itheta=0; itheta<kNthetaAbs; ++itheta ) {
480     igroup2++;
481     SetSparseRange(gridSparse, kHvarThetaAbs, "", itheta+1, itheta+1, "USEBIN");
482     SetSparseRange(gridSparse, kHvarPt, "", 1, ptAxis->GetNbins(), "USEBIN");
483     TH1* recoHisto[kNrecoHistos];
484     for ( Int_t ireco=0; ireco<kNrecoHistos; ++ireco ) {
485       recoHisto[ireco] = gridSparse->Project(kHvarPt);
486       histoName = Form("%sMuon_%s", baseRecoName[ireco].Data(), fThetaAbsKeys->At(itheta)->GetName());
487       recoHisto[ireco]->SetName(histoName.Data());
488       recoHisto[ireco]->SetTitle(histoName.Data());
489       recoHisto[ireco]->Reset();
490       recoHisto[ireco]->Sumw2();
491       for ( Int_t isrc=0; isrc<sumMothers[ireco].GetSize(); ++isrc ) {
492         SetSparseRange(gridSparse, kHvarMotherType, "", sumMothers[ireco][isrc]+1, sumMothers[ireco][isrc]+1, "USEBIN");
493         TH1* auxHisto = gridSparse->Project(kHvarPt);
494         recoHisto[ireco]->Add(auxHisto);
495         delete auxHisto;
496       }
497     }
498     SetSparseRange(gridSparse, kHvarMotherType, "", firstMother+1, lastMother+1, "USEBIN");
499     Int_t currDraw = 0;
500
501     for ( Int_t ibinpt=0; ibinpt<=ptAxis->GetNbins(); ++ibinpt ) {
502       firstPtBin = ibinpt;
503       lastPtBin = ( ibinpt == 0 ) ? ptAxis->GetNbins() : ibinpt;
504       SetSparseRange(gridSparse, kHvarPt, "", firstPtBin, lastPtBin, "USEBIN");
505       TH1* histo = gridSparse->Project(kHvarVz);
506       histo->SetName(Form("hVtx_%s_%s_ptBin%i", cfContainer->GetStepTitle(kStepReconstructed), fThetaAbsKeys->At(itheta)->GetName(), ibinpt));
507       if ( histo->GetEntries() < 100. ) break;
508       printf("\nFit %.2f < pt < %.2f (entries %g)\n", ptAxis->GetBinLowEdge(firstPtBin), ptAxis->GetBinUpEdge(lastPtBin), histo->GetEntries());
509       histo->Divide(eventVertex);
510       Double_t norm = histo->GetBinContent(histo->FindBin(0.));
511       histo->GetYaxis()->SetTitle("#frac{dN_{#mu}}{dv_{z}} / #left(#frac{1}{N_{MB}}#frac{dN_{MB}}{dv_{z}}#right)");
512       slope = ( histo->GetBinContent(histo->FindBin(meanZ+sigmaZ)) - 
513                histo->GetBinContent(histo->FindBin(meanZ-sigmaZ)) ) / ( 2. * sigmaZ );
514       
515       if ( slope < 0. ) slope = norm/kFreePath;
516       
517       // Try to fit twice: it fit fails the first time
518       // set some limits on parameters
519       for ( Int_t itry=0; itry<2; itry++ ) {
520         fitFunc->SetParameter(0, norm);
521         fitFunc->SetParameter(1, slope);
522         if ( itry > 0 ) {
523           limitNorm = 2.*histo->Integral();
524           limitSlope = 2.*histo->Integral()/kFreePath;
525           //fitFunc->SetParLimits(0, 0., limitNorm); // REMEMBER TO CHECK
526           fitFunc->SetParLimits(1, 0., limitSlope); // REMEMBER TO CHECK
527           printf("Norm 0. < %f < %f  slope  0. < %f < %f\n", norm, limitNorm, slope, limitSlope);
528         }
529         TFitResultPtr fitRes = histo->Fit(fitFunc, fitOpt.Data(), "", minZfit, maxZfit);
530         
531 //      if ( gMinuit->fCstatu.Contains("CONVERGED") && 
532         if ( ((Int_t)fitRes) == 0 &&
533             fitFunc->GetParameter(0) > 0. && 
534             fitFunc->GetParameter(1) > 0. )
535           break;
536         else if ( furtherOpt.Contains("REFIT") ) printf("Re-fit with limits\n");
537         else {
538           printf("Warning: fit problems !!!\n");
539           break;
540         }
541       }
542       
543       Double_t p0 = fitFunc->GetParameter(0);
544       Double_t p0err = fitFunc->GetParError(0);
545       Double_t p1 = fitFunc->GetParameter(1);
546       Double_t p1err = fitFunc->GetParError(1);
547       
548       Double_t nullVz = ( p1 != 0. ) ? -p0/p1 : 0.;
549       Double_t nullVzErr = ( p0 != 0. && p1 != 0. ) ? TMath::Abs(nullVz) * TMath::Sqrt(p0err*p0err/(p0*p0) + p1err*p1err/(p1*p1) ) : 0.;
550       
551       printf("Null value at %f +- %f\n", nullVz - kFreePath, nullVzErr);
552       
553       recoHisto[kRecoHF]->SetBinContent(ibinpt, p0);
554       recoHisto[kRecoHF]->SetBinError(ibinpt, p0err);
555       recoHisto[kRecoBkg]->SetBinContent(ibinpt, ( kFreePath + meanZ ) * p1);
556       recoHisto[kRecoBkg]->SetBinError(ibinpt, ( kFreePath + meanZ ) * p1err);
557       if ( currDraw%4 == 0 ){
558         currName = Form("vtx_%s_PtBin%i",fThetaAbsKeys->At(itheta)->GetName(), ibinpt);
559         can = new TCanvas(currName.Data(),currName.Data(),igroup1*xshift,igroup2*yshift,600,600);
560         can->Divide(2,2);
561       }
562       can->cd( currDraw%4 + 1 );
563       can->SetLogy();
564       histo->Draw();
565       fitFunc->DrawCopy("same");
566       currDraw++;
567     } // loop on pt bins
568     SetSparseRange(gridSparse, kHvarMotherType, "", firstMother+1, lastMother+1, "USEBIN");
569     currName = Form("recoPt_%s",fThetaAbsKeys->At(itheta)->GetName());
570     can = new TCanvas(currName.Data(),currName.Data(),(igroup1+1)*xshift,igroup2*yshift,600,600);
571     TLegend* leg = new TLegend(0.6, 0.6, 0.8, 0.8);
572     drawOpt = "e";
573     for ( Int_t ireco=0; ireco<kNrecoHistos-1; ++ireco ) {
574       if ( recoHisto[ireco]->GetEntries() == 0. ) continue;
575       TH1* ratio = (TH1*)recoHisto[ireco]->Clone(Form("%s_ratio", recoHisto[ireco]->GetName()));
576       ratio->Divide(recoHisto[kRecoAll]);
577       ratio->SetLineColor(srcColors[ireco]);
578       ratio->SetMarkerColor(srcColors[ireco]);
579       ratio->SetMarkerStyle(20+ireco);
580       ratio->GetYaxis()->SetTitle("fraction of total");
581       ratio->Draw(drawOpt.Data());
582       leg->AddEntry(ratio,baseRecoName[ireco].Data(), "lp");
583       drawOpt = "esame";
584     }
585     leg->Draw("same");
586   } // loop on theta abs
587 }