]> git.uio.no Git - u/mrichter/AliRoot.git/blob - PWG2/SPECTRA/Fit/AliBWTools.cxx
CombineSpectra:
[u/mrichter/AliRoot.git] / PWG2 / SPECTRA / Fit / AliBWTools.cxx
1 // ----------------------------------------------------------------------
2 //                     AliBWTools
3 // 
4 // This class provides some tools which can be useful in the analsis
5 // of spectra, to fit or transform histograms. See the comments of the
6 // individual methods for details
7 //
8 // Author: M. Floris (CERN)
9 // ----------------------------------------------------------------------
10
11 #include "AliBWTools.h"
12 #include "TH1D.h"
13 #include "TF1.h"
14 #include "TH1.h"
15 #include "TMath.h"
16 #include "TGraphErrors.h"
17 #include "TVirtualFitter.h"
18 #include "TMinuit.h"
19 #include "AliLog.h"
20 #include <iostream>
21
22 using namespace std;
23
24
25 ClassImp(AliBWTools)
26
27 AliBWTools::AliBWTools() {
28   // ctor
29 }
30
31 AliBWTools::~AliBWTools(){
32   // dtor
33 }
34
35 TH1 * AliBWTools::GetdNdmtFromdNdpt(const TH1 * hpt, Double_t mass) {
36   // convert the x axis from pt to mt. Assumes you have 1/pt dNdpt in the histo you start with
37
38   Int_t nbins = hpt->GetNbinsX();
39   Float_t * xbins = new Float_t[nbins+1];
40   for(Int_t ibins = 0; ibins <= nbins; ibins++){
41     xbins[ibins] = TMath::Sqrt(hpt->GetBinLowEdge(ibins+1)*hpt->GetBinLowEdge(ibins+1) +
42                                mass *mass) - mass;
43     // // xbins[ibins] = TMath::Sqrt(hpt->GetBinLowEdge(ibins+1)*hpt->GetBinLowEdge(ibins+1) +
44     // //                              mass *mass);
45     //    cout << ibins << " "<< xbins[ibins]  << endl;
46
47   }
48
49   TH1D * hmt = new TH1D(TString(hpt->GetName())+"_mt",
50                       TString(hpt->GetName())+"_mt",
51                       nbins, xbins);
52   for(Int_t ibins = 1; ibins <= nbins; ibins++){
53     hmt->SetBinContent(ibins, hpt->GetBinContent(ibins));
54     hmt->SetBinError(ibins,   hpt->GetBinError(ibins));
55
56   }
57
58   hmt->SetXTitle("m_{t} - m_{0} (GeV/c^{2})");
59   hmt->SetYTitle("1/m_{t} dN/dm_{t} (a.u.)");
60   hmt->SetMarkerStyle(hpt->GetMarkerStyle());
61   hmt->SetMarkerColor(hpt->GetMarkerColor());
62   hmt->SetLineColor(hpt->GetLineColor());
63
64   return hmt;
65
66 }
67
68 TH1 * AliBWTools::GetdNdPtFromOneOverPt(const TH1 * h1Pt) {
69
70   // convert an histo from 1/pt dNdpt to dNdpt, using the pt at the center of the bin
71
72
73   TH1 * hPt = (TH1 *) h1Pt->Clone((TString(h1Pt->GetName()) + "_inv").Data());
74   hPt->Reset();
75
76   Int_t nbinx = hPt->GetNbinsX();
77
78   for(Int_t ibinx = 1; ibinx <= nbinx; ibinx++){
79
80     Double_t cont = h1Pt->GetBinContent(ibinx);
81     Double_t err  = h1Pt->GetBinError(ibinx);
82     
83     Double_t pt   = h1Pt->GetBinCenter(ibinx);
84     
85     if(pt > 0) {
86       cont *= pt;
87       err  *= pt;
88     } else {
89       cont = 0;
90       err  = 0;
91     }
92
93     hPt->SetBinContent(ibinx, cont);
94     hPt->SetBinError(ibinx, err);
95     
96   }
97
98   hPt->SetXTitle("p_{t} (GeV)");
99   hPt->SetYTitle("dN/dp_{t} (GeV^{-2})");
100
101   return hPt;    
102
103 }
104
105
106
107
108 TH1 * AliBWTools::GetOneOverPtdNdPt(const TH1 * hPt) {
109
110   // convert an histo from dNdpt to 1/pt dNdpt, using the pt at the center of the bin
111
112   TH1 * h1Pt = (TH1 *) hPt->Clone((TString(hPt->GetName()) + "_inv").Data());
113   h1Pt->Reset();
114
115   Int_t nbinx = h1Pt->GetNbinsX();
116
117   for(Int_t ibinx = 1; ibinx <= nbinx; ibinx++){
118
119     Double_t cont = hPt->GetBinContent(ibinx);
120     Double_t err  = hPt->GetBinError(ibinx);
121     
122     Double_t pt   = hPt->GetBinCenter(ibinx);
123     
124     if(pt > 0) {
125       cont /= pt;
126       err  /= pt;
127     } else {
128       cont = 0;
129       err  = 0;
130     }
131
132     h1Pt->SetBinContent(ibinx, cont);
133     h1Pt->SetBinError(ibinx, err);
134     
135   }
136
137   h1Pt->SetXTitle("p_{t} (GeV)");
138   h1Pt->SetYTitle("1/p_{t} dN/dp_{t} (GeV^{-2})");
139
140   return h1Pt;    
141
142 }
143
144
145 TGraphErrors * AliBWTools::GetGraphFromHisto(const TH1F * h, Bool_t binWidth) {
146   // Convert a histo to a graph
147   // if binWidth is true ex is set to the bin width of the histos, otherwise it is set to zero
148   Int_t nbin = h->GetNbinsX();
149
150   TGraphErrors * g = new TGraphErrors();
151   Int_t ipoint = 0;
152   for(Int_t ibin = 1; ibin <= nbin; ibin++){
153     Double_t xerr = binWidth ? h->GetBinWidth(ibin)/2 : 0;
154     if (h->GetBinContent(ibin)) {
155       g->SetPoint     (ipoint,   h->GetBinCenter(ibin), h->GetBinContent(ibin));
156       g->SetPointError(ipoint,   xerr,  h->GetBinError(ibin));
157       ipoint++;
158     }
159   }
160   
161   g->SetMarkerStyle(h->GetMarkerStyle());
162   g->SetMarkerColor(h->GetMarkerColor());
163   g->SetLineColor(h->GetLineColor());
164   g->SetLineStyle(h->GetLineStyle());
165   g->SetLineWidth(h->GetLineWidth());
166
167   g->SetTitle(h->GetTitle());
168   g->SetName(TString("g_")+h->GetName());
169
170   return g;
171
172 }
173
174 TH1F * AliBWTools::GetHistoFromGraph(const TGraphErrors * g, const TH1F* hTemplate) {
175
176   // convert a graph to histo with the binning of hTemplate.
177   // Warning: the template should be chosen
178   // properly: if you have two graph points in the same histo bin this
179   // won't work!
180
181   TH1F * h = (TH1F*) hTemplate->Clone(TString("h_")+g->GetName());
182   h->Reset();
183   Int_t npoint = g->GetN();
184   //  g->Print();
185   for(Int_t ipoint = 0; ipoint < npoint; ipoint++){
186     Float_t x  = g->GetX() [ipoint];
187     Float_t y  = g->GetY() [ipoint];
188     Float_t ey = g->GetEY()[ipoint];
189     Int_t bin = h->FindBin(x);
190     //    cout << "bin: "<< bin << " -> " << x << ", "<< y <<", " << ey << endl;
191     
192     h->SetBinContent(bin,y);
193     h->SetBinError  (bin,ey);
194   }
195  
196   h->SetMarkerStyle(g->GetMarkerStyle());
197   h->SetMarkerColor(g->GetMarkerColor());
198   h->SetLineColor  (g->GetLineColor());
199
200  
201   return h;
202 }
203
204 TGraphErrors * AliBWTools::ConcatenateGraphs(const TGraphErrors * g1,const TGraphErrors * g2){
205
206   // concatenates two graphs
207
208   Int_t npoint1=g1->GetN();
209   Int_t npoint2=g2->GetN();
210
211   TGraphErrors * gClone = (TGraphErrors*) g1->Clone();
212
213 //   for(Int_t ipoint = 0; ipoint < npoint1; ipoint++){
214 //     gClone->SetPointError(ipoint,0,g1->GetEY()[ipoint]);
215
216 //   }
217   for(Int_t ipoint = 0; ipoint < npoint2; ipoint++){
218     gClone->SetPoint(ipoint+npoint1,g2->GetX()[ipoint],g2->GetY()[ipoint]);
219     gClone->SetPointError(ipoint+npoint1,g2->GetEX()[ipoint],g2->GetEY()[ipoint]);
220     //    gClone->SetPointError(ipoint+npoint1,0,g2->GetEY()[ipoint]);
221   }
222
223   gClone->GetHistogram()->GetXaxis()->SetTimeDisplay(1);
224   gClone->SetTitle(TString(gClone->GetTitle())+" + "+g2->GetTitle());
225   gClone->SetName(TString(gClone->GetName())+"_"+g2->GetName());
226
227   return gClone;
228 }
229
230
231 TH1F * AliBWTools::Combine3HistosWithErrors(const TH1 * h1,  const TH1 * h2,  const TH1* h3, 
232                                             TH1 * he1,  TH1 * he2,  TH1 * he3, 
233                                             const TH1* htemplate, Int_t statFrom, 
234                                             Float_t renorm1, Float_t renorm2, Float_t renorm3,
235                                             TH1 ** hSyst, Bool_t errorFromBinContent) {
236
237   // Combines 3 histos (h1,h2,h3), weighting by the errors provided in
238   // he1,he2,he3, supposed to be the independent systematic errors.
239   // he1,he2,he3 are also assumed to have the same binning as h1,h2,h3
240   // The combined histo must fit the template provided (no check is performed on this)
241   // The histogram are supposed to come from the same (nearly) sample
242   // of tracks. statFrom tells the stat error of which of the 3 is
243   // going to be assigned to the combined
244   // Optionally, it is possible to rescale any of the histograms.
245   // if hSyst is give, the histo is filled with combined syst error vs pt
246   // if errorFromBinContent is true, the weights are taken from the he* content rather than errors
247   TH1F * hcomb = (TH1F*) htemplate->Clone(TString("hComb_")+h1->GetName()+"_"+h2->GetName()+h3->GetName());
248
249   // TODO: I should have used an array for h*local...
250
251   // Clone histos locally to rescale them
252   TH1F * h1local = (TH1F*) h1->Clone();
253   TH1F * h2local = (TH1F*) h2->Clone();
254   TH1F * h3local = (TH1F*) h3->Clone();
255   h1local->Scale(renorm1);
256   h2local->Scale(renorm2);
257   h3local->Scale(renorm3);
258
259   const TH1 * hStatError = 0;
260   if (statFrom == 0)      hStatError = h1; 
261   else if (statFrom == 1) hStatError = h2; 
262   else if (statFrom == 2) hStatError = h3; 
263   else Printf("AliBWTools::Combine3HistosWithErrors: wrong value of the statFrom parameter");
264   Printf("AliBWTools::Combine3HistosWithErrors: improve error on combined");
265   // Loop over all bins and take weighted mean of all points
266   Int_t nBinComb = hcomb->GetNbinsX();
267   for(Int_t ibin = 1; ibin <= nBinComb; ibin++){
268     Int_t ibin1 = h1local->FindBin(hcomb->GetBinCenter(ibin));
269     Int_t ibin2 = h2local->FindBin(hcomb->GetBinCenter(ibin));
270     Int_t ibin3 = h3local->FindBin(hcomb->GetBinCenter(ibin));
271     Int_t ibinError = -1; // bin used to get stat error
272
273     if (statFrom == 0)      ibinError = ibin1; 
274     else if (statFrom == 1) ibinError = ibin2; 
275     else if (statFrom == 2) ibinError = ibin3; 
276     else Printf("AliBWTools::Combine3HistosWithErrors: wrong value of the statFrom parameter");
277
278
279     Double_t y[3];
280     Double_t ye[3];
281     y[0]  = h1local->GetBinContent(ibin1);
282     y[1]  = h2local->GetBinContent(ibin2);
283     y[2]  = h3local->GetBinContent(ibin3);
284     if (errorFromBinContent) {
285       ye[0] = he1->GetBinContent(he1->FindBin(hcomb->GetBinCenter(ibin)));
286       ye[1] = he2->GetBinContent(he2->FindBin(hcomb->GetBinCenter(ibin)));
287       ye[2] = he3->GetBinContent(he3->FindBin(hcomb->GetBinCenter(ibin)));
288     } else {
289       ye[0] = he1->GetBinError(ibin1);
290       ye[1] = he2->GetBinError(ibin2);
291       ye[2] = he3->GetBinError(ibin3);
292     }
293     // Set error to 0 if content is 0 (means it was not filled)
294     if(!h1local->GetBinContent(ibin1)) ye[0] = 0;
295     if(!h2local->GetBinContent(ibin2)) ye[1] = 0;
296     if(!h3local->GetBinContent(ibin3)) ye[2] = 0;
297     
298     // Compute weighted mean
299     //    cout << "Bins:  "<< ibin1 << " " << ibin2 << " " << ibin3 << endl;    
300     Double_t mean, err;
301     WeightedMean(3,y,ye,mean,err);
302
303
304     // Fill combined
305     hcomb->SetBinContent(ibin,mean);
306     Double_t statError = 0;
307     if (hStatError->GetBinContent(ibinError)) {
308       //      cout << "def" << endl;
309       statError = hStatError->GetBinError(ibinError)/hStatError->GetBinContent(ibinError)*hcomb->GetBinContent(ibin);
310     }
311     else if (h1local->GetBinContent(ibin1)) {
312       //      cout << "1" << endl;
313       statError = h1local->GetBinError(ibin1)/h1local->GetBinContent(ibin1)*hcomb->GetBinContent(ibin);
314     }
315     else if (h2local->GetBinContent(ibin2)) {
316       //      cout << "2" << endl;
317       statError = h2local->GetBinError(ibin2)/h2local->GetBinContent(ibin2)*hcomb->GetBinContent(ibin);
318     }
319     else if (h3local->GetBinContent(ibin3)) {
320       //      cout << "3" << endl;
321       statError = h3local->GetBinError(ibin3)/h3local->GetBinContent(ibin3)*hcomb->GetBinContent(ibin);
322     }
323     hcomb->SetBinError  (ibin,statError);
324     if(hSyst) (*hSyst)->SetBinContent(ibin,err);
325     //    cout << "BIN " << ibin << " " << mean << " " << statError << endl;
326
327   }
328
329   hcomb->SetMarkerStyle(hStatError->GetMarkerStyle());
330   hcomb->SetMarkerColor(hStatError->GetMarkerColor());
331   hcomb->SetLineColor  (hStatError->GetLineColor());
332
333   hcomb->SetXTitle(hStatError->GetXaxis()->GetTitle());
334   hcomb->SetYTitle(hStatError->GetYaxis()->GetTitle());
335
336   delete h1local;
337   delete h2local;
338   delete h3local;
339
340   return hcomb;
341 }
342
343
344 void AliBWTools::GetMeanDataAndExtrapolation(const TH1 * hData, TF1 * fExtrapolation, Double_t &mean, Double_t &error, Float_t min, Float_t max){
345   // Computes the mean of the combined data and extrapolation in a
346   // given range, use data where they are available and the function
347   // where data are not available
348   // ERROR is from DATA ONLY returned in this version! 
349   //
350   Printf("AliBWTools::GetMeanDataAndExtrapolation: WARNING from data only");
351   Float_t minData    = GetLowestNotEmptyBinEdge (hData);
352   Float_t minDataBin = GetLowestNotEmptyBin     (hData);
353   Float_t maxData    = GetHighestNotEmptyBinEdge(hData);
354   Float_t maxDataBin = GetHighestNotEmptyBin    (hData);
355   Double_t integral  = 0; 
356   mean      = 0;
357   error     = 0; 
358   if (min < minData) {
359     // Compute integral exploiting root function to calculate moments, "unnormalizing" them
360     mean     += fExtrapolation->Mean(min,minData)*fExtrapolation->Integral(min,minData);
361     integral += fExtrapolation->Integral(min,minData);
362     cout << " Low "<< mean << " " << integral << endl;
363     
364   }
365   
366   if (max > maxData) {
367     // Compute integral exploiting root function to calculate moments, "unnormalizing" them
368     mean     += fExtrapolation->Mean(maxData,max)*fExtrapolation->Integral(maxData,max);
369     integral += fExtrapolation->Integral(maxData,max);
370     cout << " Hi "<< mean << " " << integral << endl;
371   } 
372   Float_t err2 = 0;
373   
374   for(Int_t ibin = minDataBin; ibin <= maxDataBin; ibin++){
375     if(hData->GetBinCenter(ibin) < min) continue;
376     if(hData->GetBinCenter(ibin) > max) continue;
377     mean     = mean + (hData->GetBinCenter(ibin) *  hData->GetBinWidth(ibin)* hData->GetBinContent(ibin));
378     err2     = err2 + TMath::Power(hData->GetBinError(ibin) * hData->GetBinCenter(ibin) *  hData->GetBinWidth(ibin),2);
379     integral = integral + hData->GetBinContent(ibin) * hData->GetBinWidth(ibin);
380   }
381   cout << " Data "<< mean << " " << integral << endl;
382   
383   mean = mean/integral;
384   error = TMath::Sqrt(err2)/integral;
385
386
387 }
388
389 TH1F * AliBWTools::CombineHistos(const TH1 * h1, TH1 * h2, const TH1* htemplate, Float_t renorm1){
390   // Combine two histos. This assumes the histos have the same binning
391   // in the overlapping region. It computes the arithmetic mean in the
392   // overlapping region and assigns as an error the relative error
393   // h2. TO BE IMPROVED
394
395   TH1F * hcomb = (TH1F*) htemplate->Clone(TString(h1->GetName())+"_"+h2->GetName());
396
397   TH1F * h1local = (TH1F*) h1->Clone();
398   h1local->Scale(renorm1);
399   
400   Int_t nBinComb = hcomb->GetNbinsX();
401   for(Int_t ibin = 1; ibin <= nBinComb; ibin++){
402     Int_t ibin1 = h1local->FindBin(hcomb->GetBinCenter(ibin));
403     Int_t ibin2 = h2->FindBin(hcomb->GetBinCenter(ibin));
404     
405       if (!h1local->GetBinContent(ibin1) && !h2->GetBinContent(ibin2) ) {
406         // None has data: go to next bin
407         hcomb->SetBinContent(ibin,0);
408         hcomb->SetBinError  (ibin,0);   
409       } else if(h1local->GetBinContent(ibin1) && !h2->GetBinContent(ibin2)) {
410         // take data from h1local:
411         hcomb->SetBinContent(ibin,h1local->GetBinContent(ibin1));
412         hcomb->SetBinError  (ibin,h1local->GetBinError(ibin1));
413       } else if(!h1local->GetBinContent(ibin1) && h2->GetBinContent(ibin2)) {
414         // take data from h2:
415         hcomb->SetBinContent(ibin,h2->GetBinContent(ibin2));
416         hcomb->SetBinError  (ibin,h2->GetBinError(ibin2));
417       }  else {
418         hcomb->SetBinContent(ibin,(h1local->GetBinContent(ibin1) +h2->GetBinContent(ibin2))/2);
419         //      hcomb->SetBinError  (ibin,h1local->GetBinError(ibin1)/h1local->GetBinContent(ibin1)*hcomb->GetBinContent(ibin));
420         hcomb->SetBinError  (ibin,h2->GetBinError(ibin2)/h2->GetBinContent(ibin2)*hcomb->GetBinContent(ibin));
421       }
422
423
424   }
425   
426
427   hcomb->SetMarkerStyle(h1local->GetMarkerStyle());
428   hcomb->SetMarkerColor(h1local->GetMarkerColor());
429   hcomb->SetLineColor  (h1local->GetLineColor());
430
431   hcomb->SetXTitle(h1local->GetXaxis()->GetTitle());
432   hcomb->SetYTitle(h1local->GetYaxis()->GetTitle());
433   delete h1local;
434   return hcomb;  
435
436 }
437
438
439 void AliBWTools::GetFromHistoGraphDifferentX(const TH1F * h, TF1 * f, TGraphErrors ** gBarycentre, TGraphErrors ** gXlw) {
440
441   // Computes the baycentre in each bin and the xlw as defined in NIMA
442   // 355 - 541 using f. Returs 2 graphs with the same y content of h
443   // but with a different x (barycentre and xlw)
444
445   Int_t nbin = h->GetNbinsX();
446   
447   (*gBarycentre) = new TGraphErrors();
448   (*gXlw)        = new TGraphErrors();
449
450   Int_t ipoint = 0;
451   for(Int_t ibin = 1; ibin <= nbin; ibin++){
452     Float_t min = h->GetBinLowEdge(ibin);
453     Float_t max = h->GetBinLowEdge(ibin+1);
454     Double_t xerr = 0;
455     Double_t xbar = f->Mean(min,max);
456     // compute xLW
457     Double_t temp = 1./(max-min) * f->Integral(min,max);
458     Double_t epsilon   = 0.000000001;
459     Double_t increment = 0.0000000001;
460     Double_t xLW = min;
461
462     while ((f->Eval(xLW)- temp) > epsilon) {
463       xLW += increment;
464       if(xLW > max) {
465         Printf("Cannot find xLW");
466         break;
467       }
468     }
469       
470     if (h->GetBinContent(ibin)!=0) {
471       (*gBarycentre)->SetPoint     (ipoint,   xbar, h->GetBinContent(ibin));
472       (*gBarycentre)->SetPointError(ipoint,   xerr, h->GetBinError(ibin));
473       (*gXlw)       ->SetPoint     (ipoint,   xLW,  h->GetBinContent(ibin));
474       (*gXlw)       ->SetPointError(ipoint,   xerr, h->GetBinError(ibin));
475       ipoint++;
476     }
477   }
478   
479   (*gBarycentre)->SetMarkerStyle(h->GetMarkerStyle());
480   (*gBarycentre)->SetMarkerColor(h->GetMarkerColor());
481   (*gBarycentre)->SetLineColor(h->GetLineColor());
482
483   (*gBarycentre)->SetTitle(h->GetTitle());
484   (*gBarycentre)->SetName(TString("g_")+h->GetName());
485
486   (*gXlw)->SetMarkerStyle(h->GetMarkerStyle());
487   (*gXlw)->SetMarkerColor(h->GetMarkerColor());
488   (*gXlw)->SetLineColor(h->GetLineColor());
489   (*gXlw)->SetTitle(h->GetTitle());
490   (*gXlw)->SetName(TString("g_")+h->GetName());
491
492
493 }
494
495
496 Float_t AliBWTools::GetMean(TH1F * h, Float_t min, Float_t max, Float_t * error) {
497
498   // Get the mean of histo in a range; root is not reliable in sub
499   // ranges with variable binning.  
500   Int_t minBin = h->FindBin(min);
501   Int_t maxBin = h->FindBin(max-0.00001);
502
503   Float_t mean = 0 ;
504   Float_t integral = 0;
505   Float_t err2 = 0;
506   for(Int_t ibin = minBin; ibin <= maxBin; ibin++){
507     mean     = mean + (h->GetBinCenter(ibin) *  h->GetBinWidth(ibin)* h->GetBinContent(ibin));
508     err2     = err2 + TMath::Power(h->GetBinError(ibin) * h->GetBinCenter(ibin) *  h->GetBinWidth(ibin),2);
509     integral = integral + h->GetBinContent(ibin) * h->GetBinWidth(ibin);
510   }
511   
512   Float_t value = mean/integral;  
513   if (error) (*error) = TMath::Sqrt(err2);
514   return value;
515
516
517 }
518
519 void AliBWTools::GetMean(TF1 * func, Float_t &mean, Float_t &error, Float_t min, Float_t max, Int_t normPar) {
520
521   // Get the mean of function in a range; If normPar is >= 0, it means
522   // that the function is defined such that par[normPar] is its
523   // integral.  In this case the error on meanpt can be calculated
524   // correctly. Otherwise, the function is normalized in get moment,
525   // but the error is not computed correctly.
526
527   return GetMoment("fMean", TString("x*")+func->GetExpFormula(), func, mean, error, min, max, normPar);
528
529 }
530
531 void AliBWTools::GetMeanSquare(TF1 * func, Float_t &mean, Float_t &error, Float_t min, Float_t max, Int_t normPar) {
532
533   // Get the mean2 of function in a range;  If normPar is >= 0, it means
534   // that the function is defined such that par[normPar] is its
535   // integral.  In this case the error on meanpt can be calculated
536   // correctly. Otherwise, the function is normalized in get moment,
537   // but the error is not computed correctly.
538
539   return GetMoment("fMean2", TString("x*x*")+func->GetExpFormula(), func, mean, error, min, max, normPar);
540
541
542 }
543
544 void AliBWTools::GetMoment(TString name, TString var, TF1 * func, Float_t &mean, Float_t &error, Float_t min, Float_t max, Int_t normPar) {
545
546   // returns the integral of a function derived from func by prefixing some operation.
547   // the derived function MUST have the same parameter in the same order
548   // Used as a base method for mean and mean2
549   //  If normPar is >= 0, it means that the function is defined such
550   // that par[normPar] is its integral.  In this case the error on
551   // meanpt can be calculated correctly. Otherwise, the function is
552   // normalized using its numerical integral, but the error is not computed
553   // correctly. 
554
555   // TODO:
556   // - improve to propagate error also in the case you need the
557   //   numerical integrals (will be rather slow)
558   // - this version assumes that func is defined using a
559   //   TFormula. Generalize to the case of a C++ function
560
561   if (normPar<0) Printf("AliBWTools::GetMoment: Warning: If normalization is required, the error may bot be correct");
562   if (!strcmp(func->GetExpFormula(),"")) Printf("AliBWTools::GetMoment: Warning: Empty formula in the base function");
563   Int_t npar = func->GetNpar();
564
565   // Definition changes according to the value of normPar
566   TF1 * f = normPar < 0 ? 
567     new TF1(name, var) :                      // not normalized
568     new TF1(name, var+Form("/[%d]",normPar)); // normalized with par normPar
569
570   // integr is used to normalize if no parameter is provided
571   Double_t integr  = normPar < 0 ? func->Integral(min,max) : 1;
572   
573   // The parameter of the function used to compute the mean should be
574   // the same as the parent function: fixed if needed and they should
575   // also have the same errors.
576
577   //  cout << "npar :" << npar << endl;
578   
579   for(Int_t ipar = 0; ipar < npar; ipar++){
580     Double_t parmin, parmax;
581     Double_t value = func->GetParameter(ipar);
582     f->SetParameter(ipar,value);
583     func->GetParLimits(ipar, parmin, parmax);
584     if ( parmin == parmax )   {
585       //      if ( parmin || (parmin == 1 && !value) ) { // not sure we I check parmin == 1 here. 
586       if ( parmin || (TMath::Abs(parmin-1)<0.000001 && !value) ) { // not sure we I check parmin == 1 here. Changed like this because of coding conventions. Does it still work? FIXME
587         f->FixParameter(ipar,func->GetParameter(ipar));
588         //      cout << "Fixing " << ipar << "("<<value<<","<<parmin<<","<<parmax<<")"<<endl;
589       }       
590       else {
591         f->SetParError (ipar,func->GetParError(ipar) );
592         //      cout << "Setting Err" << ipar << "("<<func->GetParError(ipar)<<")"<<endl;      
593       }
594     }
595     else {
596       f->SetParError (ipar,func->GetParError(ipar) );
597       //      cout << "Setting Err" << ipar << "("<<func->GetParError(ipar)<<")"<<endl;      
598     }
599   }
600
601 //   f->Print();
602 //   cout << "----" << endl;
603 //   func->Print();
604
605   mean  = normPar < 0 ? f->Integral     (min,max)/integr : f->Integral     (min,max);
606   error = normPar < 0 ? f->IntegralError(min,max)/integr : f->IntegralError(min,max);
607 //   cout << "Mean " << mean <<"+-"<< error<< endl;
608 //   cout << "Integral Error "  << error << endl;
609   
610 }
611
612
613
614 Bool_t AliBWTools::Fit (TH1 * h1, TF1* func, Float_t min, Float_t max) { 
615   
616   // Fits h1 with func, preforms several checks on the quality of the
617   // fit and tries to improve it. If the fit is not good enough, it
618   // returs false.
619
620   Double_t amin; Double_t edm; Double_t errdef; Int_t nvpar; Int_t nparx;
621   TVirtualFitter *fitter;
622   cout << "--- Fitting : " << h1->GetName() << " ["<< h1->GetTitle() <<"] ---"<< endl;
623
624   h1-> Fit(func,"IME0","",min,max);      
625   Int_t fitResult = h1-> Fit(func,"IME0","",min,max);      
626 //   h1-> Fit(func,"0","",min,max);      
627 //   Int_t fitResult = h1-> Fit(func,"0IE","",min,max);      
628   
629
630 // From TH1:
631 // The fitStatus is 0 if the fit is OK (i.e no error occurred).  The
632 // value of the fit status code is negative in case of an error not
633 // connected with the minimization procedure, for example when a wrong
634 // function is used.  Otherwise the return value is the one returned
635 // from the minimization procedure.  When TMinuit (default case) or
636 // Minuit2 are used as minimizer the status returned is : fitStatus =
637 // migradResult + 10*minosResult + 100*hesseResult +
638 // 1000*improveResult.  TMinuit will return 0 (for migrad, minos,
639 // hesse or improve) in case of success and 4 in case of error (see
640 // the documentation of TMinuit::mnexcm). So for example, for an error
641 // only in Minos but not in Migrad a fitStatus of 40 will be returned.
642 // Minuit2 will return also 0 in case of success and different values
643 // in migrad minos or hesse depending on the error. See in this case
644 // the documentation of Minuit2Minimizer::Minimize for the
645 // migradResult, Minuit2Minimizer::GetMinosError for the minosResult
646 // and Minuit2Minimizer::Hesse for the hesseResult.  If other
647 // minimizers are used see their specific documentation for the status
648 // code returned.  For example in the case of Fumili, for the status
649 // returned see TFumili::Minimize.
650  
651
652   if( gMinuit->fLimset ) {
653     Printf("ERROR: AliBWTools: Parameters at limits");
654     return kFALSE;
655   } 
656
657
658   ///
659   fitter = TVirtualFitter::GetFitter();   
660   Int_t  fitStat = fitter->GetStats(amin, edm, errdef, nvpar, nparx);  
661
662   if( ( (fitStat < 3  && gMinuit->fCstatu != "UNCHANGED ")|| (edm > 1e6) || (fitResult !=0 && fitResult < 4000) ) && 
663       TString(gMinuit->fCstatu) != "SUCCESSFUL"  &&
664       TString(gMinuit->fCstatu) != "CONVERGED "  ) {
665     if(fitStat < 3 && gMinuit->fCstatu != "UNCHANGED ") {
666       Printf("WARNING: AliBWTools: Cannot properly compute errors");
667       if (fitStat == 0) Printf(" not calculated at all");
668       if (fitStat == 1) Printf(" approximation only, not accurate");
669       if (fitStat == 2) Printf(" full matrix, but forced positive-definite");
670     }
671
672     if (edm > 1e6) {
673
674       Printf("WARNING: AliBWTools: Huge EDM  (%f): Fit probably failed!", edm);
675     }
676     if (fitResult != 0) {
677       Printf("WARNING: AliBWTools: Fit Result (%d)", fitResult);
678     }
679       
680     Printf ("AliBWTools: Trying Again with Strategy = 2");
681
682     gMinuit->Command("SET STRATEGY 2"); // more effort
683     fitResult = 0;
684     fitResult = h1-> Fit(func,"0","",min,max);      
685     fitResult = h1-> Fit(func,"IME0","",min,max);      
686     fitResult = h1-> Fit(func,"IME0","",min,max);      
687       
688     fitter = TVirtualFitter::GetFitter();   
689   
690     fitStat = fitter->GetStats(amin, edm, errdef, nvpar, nparx);  
691
692     if(fitStat < 3 && gMinuit->fCstatu != "UNCHANGED ") {
693       Printf("ERROR: AliBWTools: Cannot properly compute errors");
694       if (fitStat == 0) Printf(" not calculated at all");
695       if (fitStat == 1) Printf(" approximation only, not accurate");
696       if (fitStat == 2) Printf(" full matrix, but forced positive-definite");
697       cout << "[" <<gMinuit->fCstatu<<"]" << endl;
698       return kFALSE;
699     }
700
701     if (edm > 1e6) {
702       Printf("ERROR: AliBWTools: Huge EDM  (%f): Fit probably failed!", edm);
703
704       return kFALSE;
705     }
706     if (fitResult != 0) {
707       Printf("ERROR: AliBWTools: Fit Result (%d)", fitResult);
708
709       return kFALSE;
710     }
711       
712     gMinuit->Command("SET STRATEGY 1"); // back to normal value
713
714   }
715
716   cout << "---- FIT OK ----" << endl;
717   
718   return kTRUE;
719   
720 }
721
722 Int_t AliBWTools::GetLowestNotEmptyBin(const TH1*h) {
723
724   // Return the index of the lowest non empty bin in the histo h
725
726   Int_t nbin = h->GetNbinsX();
727   for(Int_t ibin = 1; ibin <= nbin; ibin++){
728     if(h->GetBinContent(ibin)>0) return ibin;
729   }
730   
731   return -1;
732
733 }
734
735 Int_t AliBWTools::GetHighestNotEmptyBin(const TH1*h) {
736
737   // Return the index of the highest non empty bin in the histo h
738
739   Int_t nbin = h->GetNbinsX();
740   for(Int_t ibin = nbin; ibin > 0; ibin--){
741     if(h->GetBinContent(ibin)>0) return ibin;
742   }
743   
744   return -1;
745
746 }
747
748 void AliBWTools::GetResiduals(const TGraphErrors * gdata, const TF1 * func, TH1F ** hres, TGraphErrors ** gres) {
749
750   // Returns a graph of residuals vs point and the res/err distribution
751
752   Int_t npoint = gdata->GetN();
753
754   (*gres) =new TGraphErrors();
755   (*hres) = new TH1F(TString("hres_")+gdata->GetName()+"-"+func->GetName(),
756                   TString("hres_")+gdata->GetName()+"-"+func->GetName(),
757                   20,-5,5);
758
759
760   for(Int_t ipoint = 0; ipoint < npoint; ipoint++){
761     Float_t x   = gdata->GetX()[ipoint];
762     Float_t res = (gdata->GetY()[ipoint] - func->Eval(x))/func->Eval(x);
763     Float_t err = gdata->GetEY()[ipoint]/func->Eval(x);
764     (*hres)->Fill(res/err);
765     (*gres)->SetPoint(ipoint, x, res/err);
766     //    (*gres)->SetPointError(ipoint, 0, err);
767     
768   }
769   
770   (*gres)->SetMarkerStyle(gdata->GetMarkerStyle());
771   (*gres)->SetMarkerColor(gdata->GetMarkerColor());
772   (*gres)->SetLineColor  (gdata->GetLineColor());
773   (*gres)->GetHistogram()->GetYaxis()->SetTitle("(data-function)/function");
774   (*hres)->SetMarkerStyle(gdata->GetMarkerStyle());
775   (*hres)->SetMarkerColor(gdata->GetMarkerColor());
776   (*hres)->SetLineColor  (gdata->GetLineColor());
777
778
779
780 }
781
782 void AliBWTools::GetResiduals(const TH1F* hdata, const TF1 * func, TH1F ** hres, TH1F ** hresVsBin) {
783
784   // Returns an histo of residuals bin by bin and the res/err distribution
785
786   if (!func) {
787     Printf("AliBWTools::GetResiduals: No function provided");
788     return;
789   }
790   if (!hdata) {
791     Printf("AliBWTools::GetResiduals: No data provided");
792     return;
793   }
794
795   (*hresVsBin) = (TH1F*) hdata->Clone(TString("hres_")+hdata->GetName());
796   (*hresVsBin)->Reset();
797   (*hres) = new TH1F(TString("hres_")+hdata->GetName()+"-"+func->GetName(),
798                      TString("hres_")+hdata->GetName()+"-"+func->GetName(),
799                      20,-5,5);
800
801   Int_t nbin = hdata->GetNbinsX();
802   for(Int_t ibin = 1; ibin <= nbin; ibin++){
803     if(!hdata->GetBinContent(ibin)) continue;
804     Float_t res = (hdata->GetBinContent(ibin) - func->Eval(hdata->GetBinCenter(ibin)) ) / 
805       func->Eval(hdata->GetBinCenter(ibin));
806     Float_t err = hdata->GetBinError  (ibin) /  func->Eval(hdata->GetBinCenter(ibin));
807     (*hresVsBin)->SetBinContent(ibin,res);
808     (*hresVsBin)->SetBinError  (ibin,err);
809     (*hres)->Fill(res/err);
810     
811   }
812   
813   (*hresVsBin)->SetMarkerStyle(hdata->GetMarkerStyle());
814   (*hresVsBin)->SetMarkerColor(hdata->GetMarkerColor());
815   (*hresVsBin)->SetLineColor  (hdata->GetLineColor()  );
816   (*hresVsBin)->GetYaxis()->SetTitle("(data-function)/function");
817   (*hres)->SetMarkerStyle(hdata->GetMarkerStyle());
818   (*hres)->SetMarkerColor(hdata->GetMarkerColor());
819   (*hres)->SetLineColor  (hdata->GetLineColor()  );
820
821 }
822
823 void AliBWTools::GetYield(TH1* h,  TF1 * f, Double_t &yield, Double_t &yieldError, Float_t min, Float_t max,
824                           Double_t *partialYields, Double_t *partialYieldsErrors){
825
826   // Returns the yield extracted from the data in the histo where
827   // there are points and from the fit to extrapolate, in the given
828   // range.
829
830   // Partial yields are also returned if the corresponding pointers are non null
831
832   Int_t bin1 = h->FindBin(min);
833   Int_t bin2 = h->FindBin(max);
834   Float_t bin1Edge = GetLowestNotEmptyBinEdge (h);
835   Float_t bin2Edge = GetHighestNotEmptyBinEdge(h);
836
837   Double_t integralFromHistoError ;
838   Double_t integralFromHisto = h->IntegralAndError(bin1,bin2,integralFromHistoError,"width");
839   
840   Double_t integralBelow      = min < bin1Edge ? f->Integral(min,bin1Edge) : 0;
841   Double_t integralBelowError = min < bin1Edge ? f->IntegralError(min,bin1Edge) : 0;
842   Double_t integralAbove      = max > bin2Edge ? f->Integral(bin2Edge,max) : 0;
843   Double_t integralAboveError = max > bin2Edge ? f->Integral(bin2Edge,max) : 0;
844
845 //   cout << "GetYield INFO" << endl;
846 //   cout << " " << bin1Edge << " " << bin2Edge << endl;  
847 //   cout << " " << integralFromHisto      << " " << integralBelow      << " " << integralAbove      << endl;
848 //   cout << " " << integralFromHistoError << " " << integralBelowError << " " << integralAboveError << endl;
849   
850   if(partialYields) {
851     partialYields[0] = integralFromHisto;
852     partialYields[1] = integralBelow;
853     partialYields[2] = integralAbove;
854   }
855   if(partialYieldsErrors) {
856     partialYieldsErrors[0] = integralFromHistoError;
857     partialYieldsErrors[1] = integralBelowError;
858     partialYieldsErrors[2] = integralAboveError;
859   }
860   yield      = integralFromHisto+integralBelow+integralAbove;
861   yieldError = TMath::Sqrt(integralFromHistoError*integralFromHistoError+
862                            integralBelowError*integralBelowError+
863                            integralAboveError*integralAboveError);
864
865 }
866
867 TGraphErrors * AliBWTools::DivideGraphByFunc(const TGraphErrors * g, const TF1 * f, Bool_t invert){ 
868
869   // Divides g/f. If invert == true => f/g
870
871   TGraphErrors * gRatio = new TGraphErrors();
872   Int_t npoint = g->GetN();
873   for(Int_t ipoint = 0; ipoint < npoint; ipoint++){
874     Double_t x = g->GetX()[ipoint];
875     Double_t ratio  = invert ? f->Eval(x)/g->GetY()[ipoint] :g->GetY()[ipoint]/f->Eval(x);
876     gRatio->SetPoint     (ipoint, x, ratio);
877     gRatio->SetPointError(ipoint, 0, g->GetEY()[ipoint]/f->Eval(x));
878     //    cout << x << " " << g->GetY()[ipoint] << " " << f->Eval(x) << endl;
879     
880   }
881   gRatio->SetMarkerStyle(20);
882   //gRatio->Print();
883   return gRatio;
884
885 }
886
887 TGraphErrors * AliBWTools::DivideGraphByHisto(const TGraphErrors * g, TH1 * h, Bool_t invert){ 
888
889   // Divides g/h. If invert == true => h/g
890
891
892   TGraphErrors * gRatio = new TGraphErrors();
893   Int_t npoint = g->GetN();
894   for(Int_t ipoint = 0; ipoint < npoint; ipoint++){
895     Double_t xj  = g->GetX()[ipoint];
896     Double_t yj  = g->GetY()[ipoint];
897     Double_t yje = g->GetEY()[ipoint];
898
899     Int_t binData = h->FindBin(xj);
900     Double_t yd   = h->GetBinContent(binData);
901     Double_t yde  = h->GetBinError(binData);
902     Double_t xd   = h->GetBinCenter(binData);
903     
904
905      
906     if (!yd) continue;
907     
908     if (TMath::Abs(xd-xj)/TMath::Abs(xd) > 0.01){
909       Printf( "WARNING: bin center (%f)  and x graph (%f) are more than 1 %% away, skipping",xd,xj );
910       continue;
911       
912     }
913
914     Double_t ratio = invert ? yd/yj : yj/yd;
915
916     gRatio->SetPoint(ipoint, xj, ratio);
917     gRatio->SetPointError(ipoint, 0, TMath::Sqrt(yde*yde/yd/yd + yje*yje/yj/yj)*ratio);
918     //    gRatio->SetPointError(ipoint, 0, yje/yj * ratio);
919   }
920
921   return gRatio;
922
923
924 }
925
926 TH1F * AliBWTools::DivideHistoByFunc(TH1F * h, TF1 * f, Bool_t invert){ 
927
928   // Divides h/f. If invert == true => f/g
929   // Performs the integral of f on the bin range to perform the ratio
930   // Returns a histo with the same binnig as h
931
932   // Prepare histo for ratio
933   TH1F * hRatio = (TH1F*) h->Clone(TString("hRatio_")+h->GetName()+"_"+f->GetName());
934   hRatio->Reset();
935   // Set y title
936   if(!invert) hRatio->SetYTitle(TString(h->GetName())+"/"+f->GetName());
937   else        hRatio->SetYTitle(TString(f->GetName())+"/"+h->GetName());
938
939   // Loop over all bins
940   Int_t nbin = hRatio->GetNbinsX();
941
942   for(Int_t ibin = 1; ibin <= nbin; ibin++){
943     Double_t yhisto = h->GetBinContent(ibin);
944     Double_t yerror = h->GetBinError(ibin);
945     Double_t xmin   = h->GetBinLowEdge(ibin);
946     Double_t xmax   = h->GetBinLowEdge(ibin+1);
947     Double_t yfunc  = f->Integral(xmin,xmax)/(xmax-xmin);
948     Double_t ratio = invert ? yfunc/yhisto : yhisto/yfunc ;
949     Double_t error = yerror/yfunc  ;
950     hRatio->SetBinContent(ibin,ratio);
951     hRatio->SetBinError  (ibin,error);
952   }
953
954   return hRatio;
955
956 }
957
958 void AliBWTools::WeightedMean(Int_t npoints, const Double_t *x, const Double_t *xerr, Double_t &mean, Double_t &meanerr){
959
960   // Performs the weighted mean of npoints numbers in x with errors in xerr
961
962   mean = 0;
963   meanerr = 0;
964
965   Double_t sumweight = 0;
966
967   for (Int_t ipoint = 0; ipoint < npoints; ipoint++){
968     
969     Double_t xerr2 = xerr[ipoint]*xerr[ipoint];
970     if(xerr2>0){
971       //      cout << "xe2 " << xerr2 << endl;
972       Double_t weight = 1. / xerr2;
973       sumweight += weight;
974       mean += weight * x[ipoint];
975     }// else cout << " Skipping " << ipoint << endl;
976     
977   }
978
979
980   if(sumweight){
981     mean /= sumweight;
982     meanerr = TMath::Sqrt(1./ sumweight);
983   }
984   else {
985     //    cout << " No sumweight" << endl;
986     mean = 0;
987     meanerr = 0;
988   }
989
990   
991 }
992
993 void AliBWTools::GetValueAndError(TH1 * hdest, const TH1 * hvalue, const TH1 * herror, Bool_t isPercentError) {
994   
995   // Put into source, bin-by-bin, the values from hvalue and the
996   // errors from content from herror. 
997   // Used mainly to combine histos of systemati errors with their spectra
998   // Set isPercentError to kTRUE if the error is given in % 
999
1000   if(hdest == NULL){ 
1001     Printf("AliBWTools::GetValueAndError Errror: hdest is null");
1002     return;
1003   }
1004
1005
1006   Int_t nbin  = hdest->GetNbinsX();
1007   Int_t nBinSourceVal = hvalue->GetNbinsX();
1008   Int_t nBinSourceErr = herror->GetNbinsX();
1009   
1010   for(Int_t iBinDest = 1; iBinDest <= nbin; iBinDest++){
1011     Float_t lowPtDest=hdest->GetBinLowEdge(iBinDest);
1012     Float_t binWidDest=hdest->GetBinWidth(iBinDest);
1013     // Loop over Source bins and find overlapping bins to Dest
1014     // First value then error
1015     // Value
1016     Bool_t foundValue = kFALSE;
1017     for(Int_t iBinSourceVal=1; iBinSourceVal<=nBinSourceVal; iBinSourceVal++){
1018       Float_t lowPtSource=  hvalue->GetBinLowEdge(iBinSourceVal) ;
1019       Float_t binWidSource= hvalue->GetBinWidth(iBinSourceVal);
1020       if(TMath::Abs(lowPtDest-lowPtSource)<0.001 && TMath::Abs(binWidSource-binWidDest)<0.001){
1021         Double_t content = hvalue->GetBinContent(iBinSourceVal);
1022         hdest->SetBinContent(iBinDest, content);
1023         foundValue = kTRUE;
1024         break;
1025       }
1026     }
1027     // if (!foundValue){
1028     //   Printf("AliBWTools::GetValueAndError: Error: cannot find matching value source bin for destination %d",iBinDest);
1029     // }
1030
1031     // Error
1032     Bool_t foundError = kFALSE;
1033     for(Int_t iBinSourceErr=1; iBinSourceErr<=nBinSourceErr; iBinSourceErr++){
1034       Float_t lowPtSource=  herror->GetBinLowEdge(iBinSourceErr) ;
1035       Float_t binWidSource= herror->GetBinWidth(iBinSourceErr);
1036       if(TMath::Abs(lowPtDest-lowPtSource)<0.001 && TMath::Abs(binWidSource-binWidDest)<0.001){
1037         Double_t error = herror->GetBinContent(iBinSourceErr);
1038         //      cout << "-> " << iBinDest << " " << error << " " << hdest->GetBinContent(iBinDest) << endl;
1039         
1040         hdest->SetBinError(iBinDest, isPercentError ? error * hdest->GetBinContent(iBinDest) : error);
1041         foundError=kTRUE;
1042         break;
1043       }      
1044     }
1045     // if (!foundError ){
1046     //   Printf("AliBWTools::GetValueAndError: Error: cannot find matching error source bin for destination %d",iBinDest);
1047     // }
1048   }
1049   
1050
1051 }
1052
1053 void AliBWTools::AddHisto(TH1 * hdest, const TH1* hsource, Bool_t getMirrorBins) {
1054
1055   // Adds hsource to hdest bin by bin, even if they have a different
1056   // binning If getMirrorBins is true, it takes the negative bins
1057   // (Needed because sometimes the TPC uses the positive axis for
1058   // negative particles and the possitive axis for positive
1059   // particles).
1060
1061
1062   if (hdest == NULL) {
1063     Printf("Error: hdest is NULL\n");
1064   } 
1065   if (hsource == NULL) {
1066     Printf("Error: hsource is NULL\n");
1067   } 
1068
1069   Int_t nBinSource = hsource->GetNbinsX();
1070   Int_t nBinDest = hdest->GetNbinsX();
1071
1072   // Loop over destination bins, 
1073   for(Int_t iBinDest=1; iBinDest<=nBinDest; iBinDest++){
1074     Float_t lowPtDest=hdest->GetBinLowEdge(iBinDest);
1075     Float_t binWidDest=hdest->GetBinWidth(iBinDest);
1076     // Loop over Source bins and find overlapping bins to Dest
1077     Bool_t found = kFALSE;
1078     for(Int_t iBinSource=1; iBinSource<=nBinSource; iBinSource++){      
1079       Float_t lowPtSource= getMirrorBins ? -hsource->GetBinLowEdge(iBinSource)+hsource->GetBinWidth(iBinSource) : hsource->GetBinLowEdge(iBinSource) ;
1080       Float_t binWidSource= hsource->GetBinWidth(iBinSource)  ;
1081       if(TMath::Abs(lowPtDest-lowPtSource)<0.001 && TMath::Abs(binWidSource-binWidDest)<0.001){
1082         Float_t dest=hdest->GetBinContent(iBinDest);
1083         Float_t source=hsource->GetBinContent(iBinSource);
1084         Float_t edest=hdest->GetBinError(iBinDest);
1085         Float_t esource=hsource->GetBinError(iBinSource);
1086         Double_t cont=dest+source;
1087         Double_t econt=TMath::Sqrt(edest*edest+esource*esource);
1088         hdest->SetBinContent(iBinDest,cont);
1089         hdest->SetBinError  (iBinDest,econt);
1090         found = kTRUE;
1091         
1092         break;
1093       }
1094     }
1095     // if (!found){
1096     //   Printf("Error: cannot find matching source bin for destination %d",iBinDest);
1097     // }
1098   }
1099
1100
1101 }
1102
1103 void AliBWTools::GetHistoCombinedErrors(TH1 * hdest, const TH1 * h1) {
1104
1105   // Combine the errors of hdest with the errors of h1, summing in
1106   // quadrature. Results are put in hdest. Histograms are assumed to
1107   // have the same binning
1108
1109   Int_t nbin = hdest->GetNbinsX();
1110   for(Int_t ibin = 0; ibin < nbin; ibin++){
1111     Double_t e1 = hdest->GetBinError(ibin);
1112     Double_t e2 = h1->GetBinError(ibin);
1113     hdest->SetBinError(ibin, TMath::Sqrt(e1*e1+e2*e2));
1114   }
1115   
1116
1117 }
1118
1119 TH1F * AliBWTools::DivideHistosDifferentBins(const TH1F* h1, const TH1F* h2) {
1120   // Divides 2 histos even if they have a different binning. Finds
1121   // overlapping bins and divides them
1122   
1123   // 1. clone histo
1124   TH1F * hRatio = new TH1F(*h1);
1125   Int_t nBinsH1=h1->GetNbinsX();
1126   Int_t nBinsH2=h2->GetNbinsX();
1127   // Loop over H1 bins, 
1128   for(Int_t iBin=1; iBin<=nBinsH1; iBin++){
1129     hRatio->SetBinContent(iBin,0.);
1130     hRatio->SetBinContent(iBin,0.);
1131     Float_t lowPtH1=h1->GetBinLowEdge(iBin);
1132     Float_t binWidH1=h1->GetBinWidth(iBin);
1133     // Loop over H2 bins and find overlapping bins to H1
1134     for(Int_t jBin=1; jBin<=nBinsH2; jBin++){
1135       Float_t lowPtH2=h2->GetBinLowEdge(jBin);
1136       Float_t binWidH2=h2->GetBinWidth(jBin);
1137       if(TMath::Abs(lowPtH1-lowPtH2)<0.001 && TMath::Abs(binWidH2-binWidH1)<0.001){
1138         Float_t numer=h1->GetBinContent(iBin);
1139         Float_t denom=h2->GetBinContent(jBin);
1140         Float_t enumer=h1->GetBinError(iBin);
1141         Float_t edenom=h2->GetBinError(jBin);
1142         Double_t ratio=0.;
1143         Double_t eratio=0.;
1144         if(numer>0. && denom>0.){
1145           ratio=numer/denom;
1146           eratio=ratio*TMath::Sqrt((enumer/numer)*(enumer/numer)+(edenom/denom)*(edenom/denom));
1147         }
1148         hRatio->SetBinContent(iBin,ratio);
1149         hRatio->SetBinError(iBin,eratio);
1150         break;
1151       }
1152     }
1153   }
1154   return hRatio;
1155 }