ROOT  6.06/08
Reference Guide
TH1.cxx
Go to the documentation of this file.
1 // @(#)root/hist:$Id$
2 // Author: Rene Brun 26/12/94
3 
4 /*************************************************************************
5  * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
6  * All rights reserved. *
7  * *
8  * For the licensing terms see $ROOTSYS/LICENSE. *
9  * For the list of contributors see $ROOTSYS/README/CREDITS. *
10  *************************************************************************/
11 
12 #include <stdlib.h>
13 #include <string.h>
14 #include <stdio.h>
15 #include <ctype.h>
16 #include <sstream>
17 
18 #include "Riostream.h"
19 #include "TROOT.h"
20 #include "TClass.h"
21 #include "TMath.h"
22 #include "THashList.h"
23 #include "TH1.h"
24 #include "TH2.h"
25 #include "TF2.h"
26 #include "TF3.h"
27 #include "TPluginManager.h"
28 #include "TVirtualPad.h"
29 #include "TRandom.h"
30 #include "TVirtualFitter.h"
31 #include "THLimitsFinder.h"
32 #include "TProfile.h"
33 #include "TStyle.h"
34 #include "TVectorF.h"
35 #include "TVectorD.h"
36 #include "TBrowser.h"
37 #include "TObjString.h"
38 #include "TError.h"
39 #include "TVirtualHistPainter.h"
40 #include "TVirtualFFT.h"
41 #include "TSystem.h"
42 
43 #include "HFitInterface.h"
44 #include "Fit/DataRange.h"
45 #include "Fit/BinData.h"
46 #include "Math/GoFTest.h"
47 #include "Math/MinimizerOptions.h"
48 #include "Math/QuantFuncMathCore.h"
49 
50 /** \addtogroup Hist
51 @{
52 \class TH1C
53 \brief 1-D histogram with a byte per channel (see TH1 documentation)
54 \class TH1S
55 \brief 1-D histogram with a short per channel (see TH1 documentation)
56 \class TH1I
57 \brief 1-D histogram with an int per channel (see TH1 documentation)}
58 \class TH1F
59 \brief 1-D histogram with a float per channel (see TH1 documentation)}
60 \class TH1D
61 \brief 1-D histogram with a double per channel (see TH1 documentation)}
62 @}
63 */
64 
65 ////////////////////////////////////////////////////////////////////////////////
66 /** \class TH1
67 The TH1 histogram class
68 <h2>The Histogram classes</h2>
69 ROOT supports the following histogram types:
70 <ul>
71  <li>1-D histograms:
72  <ul>
73  <li>TH1C : histograms with one byte per channel. Maximum bin content = 127
74  <li>TH1S : histograms with one short per channel. Maximum bin content = 32767
75  <li>TH1I : histograms with one int per channel. Maximum bin content = 2147483647
76  <li>TH1F : histograms with one float per channel. Maximum precision 7 digits
77  <li>TH1D : histograms with one double per channel. Maximum precision 14 digits
78  </ul>
79 
80  <li>2-D histograms:
81  <ul>
82  <li>TH2C : histograms with one byte per channel. Maximum bin content = 127
83  <li>TH2S : histograms with one short per channel. Maximum bin content = 32767
84  <li>TH2I : histograms with one int per channel. Maximum bin content = 2147483647
85  <li>TH2F : histograms with one float per channel. Maximum precision 7 digits
86  <li>TH2D : histograms with one double per channel. Maximum precision 14 digits
87  </ul>
88 
89  <li>3-D histograms:
90  <ul>
91  <li>TH3C : histograms with one byte per channel. Maximum bin content = 127
92  <li>TH3S : histograms with one short per channel. Maximum bin content = 32767
93  <li>TH3I : histograms with one int per channel. Maximum bin content = 2147483647
94  <li>TH3F : histograms with one float per channel. Maximum precision 7 digits
95  <li>TH3D : histograms with one double per channel. Maximum precision 14 digits
96  </ul>
97  <li>Profile histograms: See classes TProfile, TProfile2D and TProfile3D.
98  Profile histograms are used to display the mean value of Y and its standard deviation
99  for each bin in X. Profile histograms are in many cases an elegant
100  replacement of two-dimensional histograms : the inter-relation of two
101  measured quantities X and Y can always be visualized by a two-dimensional
102  histogram or scatter-plot; If Y is an unknown (but single-valued)
103  approximate function of X, this function is displayed by a profile
104  histogram with much better precision than by a scatter-plot.
105 </ul>
106 
107 All histogram classes are derived from the base class TH1
108 <pre>
109  TH1
110  ^
111  |
112  |
113  |
114  -----------------------------------------------------------
115  | | | | | | |
116  | | TH1C TH1S TH1I TH1F TH1D
117  | | |
118  | | |
119  | TH2 TProfile
120  | |
121  | |
122  | ----------------------------------
123  | | | | | |
124  | TH2C TH2S TH2I TH2F TH2D
125  | |
126  TH3 |
127  | TProfile2D
128  |
129  -------------------------------------
130  | | | | |
131  TH3C TH3S TH3I TH3F TH3D
132  |
133  |
134  TProfile3D
135 
136  The TH*C classes also inherit from the array class TArrayC.
137  The TH*S classes also inherit from the array class TArrayS.
138  The TH*I classes also inherit from the array class TArrayI.
139  The TH*F classes also inherit from the array class TArrayF.
140  The TH*D classes also inherit from the array class TArrayD.
141 </pre>
142 
143 <h4>Creating histograms</h4>
144 <p>
145  Histograms are created by invoking one of the constructors, e.g.
146 <pre>
147  TH1F *h1 = new TH1F("h1", "h1 title", 100, 0, 4.4);
148  TH2F *h2 = new TH2F("h2", "h2 title", 40, 0, 4, 30, -3, 3);
149 </pre>
150 <p> Histograms may also be created by:
151  <ul>
152  <li> calling the Clone function, see below
153  <li> making a projection from a 2-D or 3-D histogram, see below
154  <li> reading an histogram from a file
155  </ul>
156 <p> When an histogram is created, a reference to it is automatically added
157  to the list of in-memory objects for the current file or directory.
158  This default behaviour can be changed by:
159 <pre>
160  h->SetDirectory(0); for the current histogram h
161  TH1::AddDirectory(kFALSE); sets a global switch disabling the reference
162 </pre>
163  When the histogram is deleted, the reference to it is removed from
164  the list of objects in memory.
165  When a file is closed, all histograms in memory associated with this file
166  are automatically deleted.
167 
168 <h4>Fix or variable bin size</h4>
169 
170  All histogram types support either fix or variable bin sizes.
171  2-D histograms may have fix size bins along X and variable size bins
172  along Y or vice-versa. The functions to fill, manipulate, draw or access
173  histograms are identical in both cases.
174 
175  Each histogram always contains 3 objects TAxis: fXaxis, fYaxis and fZaxis
176  o access the axis parameters, do:
177 <pre>
178  TAxis *xaxis = h->GetXaxis(); etc.
179  Double_t binCenter = xaxis->GetBinCenter(bin), etc.
180 </pre>
181  See class TAxis for a description of all the access functions.
182  The axis range is always stored internally in double precision.
183 
184 <h4>Convention for numbering bins</h4>
185 
186  For all histogram types: nbins, xlow, xup
187 <pre>
188  bin = 0; underflow bin
189  bin = 1; first bin with low-edge xlow INCLUDED
190  bin = nbins; last bin with upper-edge xup EXCLUDED
191  bin = nbins+1; overflow bin
192 </pre>
193  In case of 2-D or 3-D histograms, a "global bin" number is defined.
194  For example, assuming a 3-D histogram with (binx, biny, binz), the function
195 <pre>
196  Int_t gbin = h->GetBin(binx, biny, binz);
197 </pre>
198  returns a global/linearized gbin number. This global gbin is useful
199  to access the bin content/error information independently of the dimension.
200  Note that to access the information other than bin content and errors
201  one should use the TAxis object directly with e.g.:
202 <pre>
203  Double_t xcenter = h3->GetZaxis()->GetBinCenter(27);
204 </pre>
205  returns the center along z of bin number 27 (not the global bin)
206  in the 3-D histogram h3.
207 
208 <h4>Alphanumeric Bin Labels</h4>
209 
210  By default, an histogram axis is drawn with its numeric bin labels.
211  One can specify alphanumeric labels instead with:
212 <ul>
213  <li> call TAxis::SetBinLabel(bin, label);
214  This can always be done before or after filling.
215  When the histogram is drawn, bin labels will be automatically drawn.
216  See example in $ROOTSYS/tutorials/graphs/labels1.C, labels2.C
217  <li> call to a Fill function with one of the arguments being a string, e.g.
218 <pre>
219  hist1->Fill(somename, weigth);
220  hist2->Fill(x, somename, weight);
221  hist2->Fill(somename, y, weight);
222  hist2->Fill(somenamex, somenamey, weight);
223 </pre>
224  See example in $ROOTSYS/tutorials/hist/hlabels1.C, hlabels2.C
225  <li> via TTree::Draw.
226  see for example $ROOTSYS/tutorials/tree/cernstaff.C
227 <pre>
228  tree.Draw("Nation::Division");
229 </pre>
230  where "Nation" and "Division" are two branches of a Tree.
231 </ul>
232 
233 <p>When using the options 2 or 3 above, the labels are automatically
234  added to the list (THashList) of labels for a given axis.
235  By default, an axis is drawn with the order of bins corresponding
236  to the filling sequence. It is possible to reorder the axis
237 
238 <ul>
239  <li>alphabetically
240  <li>by increasing or decreasing values
241 </ul>
242 
243 <p> The reordering can be triggered via the TAxis context menu by selecting
244  the menu item "LabelsOption" or by calling directly
245  TH1::LabelsOption(option, axis) where
246 <ul>
247  <li>axis may be "X", "Y" or "Z"
248  <li>option may be:
249  <ul>
250  <li>"a" sort by alphabetic order
251  <li>">" sort by decreasing values
252  <li>"<" sort by increasing values
253  <li>"h" draw labels horizontal
254  <li>"v" draw labels vertical
255  <li>"u" draw labels up (end of label right adjusted)
256  <li>"d" draw labels down (start of label left adjusted)
257  </ul>
258 </ul>
259 <p> When using the option 2 above, new labels are added by doubling the current
260  number of bins in case one label does not exist yet.
261  When the Filling is terminated, it is possible to trim the number
262  of bins to match the number of active labels by calling
263 <pre>
264  TH1::LabelsDeflate(axis) with axis = "X", "Y" or "Z"
265 </pre>
266  This operation is automatic when using TTree::Draw.
267  Once bin labels have been created, they become persistent if the histogram
268  is written to a file or when generating the C++ code via SavePrimitive.
269 
270 <h4>Histograms with automatic bins</h4>
271 
272  When an histogram is created with an axis lower limit greater or equal
273  to its upper limit, the SetBuffer is automatically called with an
274  argument fBufferSize equal to fgBufferSize (default value=1000).
275  fgBufferSize may be reset via the static function TH1::SetDefaultBufferSize.
276  The axis limits will be automatically computed when the buffer will
277  be full or when the function BufferEmpty is called.
278 
279 <h4>Filling histograms</h4>
280 
281  An histogram is typically filled with statements like:
282 <pre>
283  h1->Fill(x);
284  h1->Fill(x, w); //fill with weight
285  h2->Fill(x, y)
286  h2->Fill(x, y, w)
287  h3->Fill(x, y, z)
288  h3->Fill(x, y, z, w)
289 </pre>
290  or via one of the Fill functions accepting names described above.
291  The Fill functions compute the bin number corresponding to the given
292  x, y or z argument and increment this bin by the given weight.
293  The Fill functions return the bin number for 1-D histograms or global
294  bin number for 2-D and 3-D histograms.
295 <p> If TH1::Sumw2 has been called before filling, the sum of squares of
296  weights is also stored.
297  One can also increment directly a bin number via TH1::AddBinContent
298  or replace the existing content via TH1::SetBinContent.
299  To access the bin content of a given bin, do:
300 <pre>
301  Double_t binContent = h->GetBinContent(bin);
302 </pre>
303 
304 <p> By default, the bin number is computed using the current axis ranges.
305  If the automatic binning option has been set via
306 <pre>
307  h->SetCanExtend(kAllAxes);
308 </pre>
309  then, the Fill Function will automatically extend the axis range to
310  accomodate the new value specified in the Fill argument. The method
311  used is to double the bin size until the new value fits in the range,
312  merging bins two by two. This automatic binning options is extensively
313  used by the TTree::Draw function when histogramming Tree variables
314  with an unknown range.
315 <p> This automatic binning option is supported for 1-D, 2-D and 3-D histograms.
316 
317  During filling, some statistics parameters are incremented to compute
318  the mean value and Root Mean Square with the maximum precision.
319 
320 <p> In case of histograms of type TH1C, TH1S, TH2C, TH2S, TH3C, TH3S
321  a check is made that the bin contents do not exceed the maximum positive
322  capacity (127 or 32767). Histograms of all types may have positive
323  or/and negative bin contents.
324 
325 <h4>Rebinning</h4>
326  At any time, an histogram can be rebinned via TH1::Rebin. This function
327  returns a new histogram with the rebinned contents.
328  If bin errors were stored, they are recomputed during the rebinning.
329 
330 <h4>Associated errors</h4>
331  By default, for each bin, the sum of weights is computed at fill time.
332  One can also call TH1::Sumw2 to force the storage and computation
333  of the sum of the square of weights per bin.
334  If Sumw2 has been called, the error per bin is computed as the
335  sqrt(sum of squares of weights), otherwise the error is set equal
336  to the sqrt(bin content).
337  To return the error for a given bin number, do:
338 <pre>
339  Double_t error = h->GetBinError(bin);
340 </pre>
341 
342 <h4>Associated functions</h4>
343  One or more object (typically a TF1*) can be added to the list
344  of functions (fFunctions) associated to each histogram.
345  When TH1::Fit is invoked, the fitted function is added to this list.
346  Given an histogram h, one can retrieve an associated function
347  with:
348 <pre>
349  TF1 *myfunc = h->GetFunction("myfunc");
350 </pre>
351 
352 <h4>Operations on histograms</h4>
353 
354  Many types of operations are supported on histograms or between histograms
355 <ul>
356  <li> Addition of an histogram to the current histogram.
357  <li> Additions of two histograms with coefficients and storage into the current
358  histogram.
359  <li> Multiplications and Divisions are supported in the same way as additions.
360  <li> The Add, Divide and Multiply functions also exist to add, divide or multiply
361  an histogram by a function.
362 </ul>
363  If an histogram has associated error bars (TH1::Sumw2 has been called),
364  the resulting error bars are also computed assuming independent histograms.
365  In case of divisions, Binomial errors are also supported.
366  One can mark a histogram to be an "average" histogram by setting its bit kIsAverage via
367  myhist.SetBit(TH1::kIsAverage);
368  When adding (see TH1::Add) average histograms, the histograms are averaged and not summed.
369 
370 <h4>Fitting histograms</h4>
371 
372  Histograms (1-D, 2-D, 3-D and Profiles) can be fitted with a user
373  specified function via TH1::Fit. When an histogram is fitted, the
374  resulting function with its parameters is added to the list of functions
375  of this histogram. If the histogram is made persistent, the list of
376  associated functions is also persistent. Given a pointer (see above)
377  to an associated function myfunc, one can retrieve the function/fit
378  parameters with calls such as:
379 <pre>
380  Double_t chi2 = myfunc->GetChisquare();
381  Double_t par0 = myfunc->GetParameter(0); value of 1st parameter
382  Double_t err0 = myfunc->GetParError(0); error on first parameter
383 </pre>
384 
385 <h4>Projections of histograms</h4>
386 
387 <p> One can:
388 <ul>
389  <li> make a 1-D projection of a 2-D histogram or Profile
390  see functions TH2::ProjectionX,Y, TH2::ProfileX,Y, TProfile::ProjectionX
391  <li> make a 1-D, 2-D or profile out of a 3-D histogram
392  see functions TH3::ProjectionZ, TH3::Project3D.
393 </ul>
394 
395 <p> One can fit these projections via:
396 <pre>
397  TH2::FitSlicesX,Y, TH3::FitSlicesZ.
398 </pre>
399 
400 <h4>Random Numbers and histograms</h4>
401 
402  TH1::FillRandom can be used to randomly fill an histogram using
403  the contents of an existing TF1 function or another
404  TH1 histogram (for all dimensions).
405 <p> For example the following two statements create and fill an histogram
406  10000 times with a default gaussian distribution of mean 0 and sigma 1:
407 <pre>
408  TH1F h1("h1", "histo from a gaussian", 100, -3, 3);
409  h1.FillRandom("gaus", 10000);
410 </pre>
411  TH1::GetRandom can be used to return a random number distributed
412  according the contents of an histogram.
413 
414 <h4>Making a copy of an histogram</h4>
415  Like for any other ROOT object derived from TObject, one can use
416  the Clone() function. This makes an identical copy of the original
417  histogram including all associated errors and functions, e.g.:
418 <pre>
419  TH1F *hnew = (TH1F*)h->Clone("hnew");
420 </pre>
421 
422 <h4>Normalizing histograms</h4>
423 
424  One can scale an histogram such that the bins integral is equal to
425  the normalization parameter via TH1::Scale(Double_t norm), where norm
426  is the desired normalization divided by the integral of the histogram.
427 
428 <h4>Drawing histograms</h4>
429 
430  Histograms are drawn via the THistPainter class. Each histogram has
431  a pointer to its own painter (to be usable in a multithreaded program).
432  Many drawing options are supported.
433  See THistPainter::Paint() for more details.
434 <p>
435  The same histogram can be drawn with different options in different pads.
436  When an histogram drawn in a pad is deleted, the histogram is
437  automatically removed from the pad or pads where it was drawn.
438  If an histogram is drawn in a pad, then filled again, the new status
439  of the histogram will be automatically shown in the pad next time
440  the pad is updated. One does not need to redraw the histogram.
441  To draw the current version of an histogram in a pad, one can use
442 <pre>
443  h->DrawCopy();
444 </pre>
445  This makes a clone (see Clone below) of the histogram. Once the clone
446  is drawn, the original histogram may be modified or deleted without
447  affecting the aspect of the clone.
448 <p>
449  One can use TH1::SetMaximum() and TH1::SetMinimum() to force a particular
450  value for the maximum or the minimum scale on the plot. (For 1-D
451  histograms this means the y-axis, while for 2-D histograms these
452  functions affect the z-axis).
453 <p>
454  TH1::UseCurrentStyle() can be used to change all histogram graphics
455  attributes to correspond to the current selected style.
456  This function must be called for each histogram.
457  In case one reads and draws many histograms from a file, one can force
458  the histograms to inherit automatically the current graphics style
459  by calling before gROOT->ForceStyle().
460 
461 
462 <h4>Setting Drawing histogram contour levels (2-D hists only)</h4>
463 
464  By default contours are automatically generated at equidistant
465  intervals. A default value of 20 levels is used. This can be modified
466  via TH1::SetContour() or TH1::SetContourLevel().
467  the contours level info is used by the drawing options "cont", "surf",
468  and "lego".
469 
470 <h4>Setting histogram graphics attributes</h4>
471 
472  The histogram classes inherit from the attribute classes:
473  TAttLine, TAttFill, and TAttMarker.
474  See the member functions of these classes for the list of options.
475 
476 <h4>Giving titles to the X, Y and Z axis</h4>
477 <pre>
478  h->GetXaxis()->SetTitle("X axis title");
479  h->GetYaxis()->SetTitle("Y axis title");
480 </pre>
481  The histogram title and the axis titles can be any TLatex string.
482  The titles are part of the persistent histogram.
483  It is also possible to specify the histogram title and the axis
484  titles at creation time. These titles can be given in the "title"
485  parameter. They must be separated by ";":
486 <pre>
487  TH1F* h=new TH1F("h", "Histogram title;X Axis;Y Axis;Z Axis", 100, 0, 1);
488 </pre>
489  Any title can be omitted:
490 <pre>
491  TH1F* h=new TH1F("h", "Histogram title;;Y Axis", 100, 0, 1);
492  TH1F* h=new TH1F("h", ";;Y Axis", 100, 0, 1);
493 </pre>
494  The method SetTitle has the same syntax:
495 <pre>
496 </pre>
497  h->SetTitle("Histogram title;Another X title Axis");
498 
499 <h4>Saving/Reading histograms to/from a ROOT file</h4>
500 
501  The following statements create a ROOT file and store an histogram
502  on the file. Because TH1 derives from TNamed, the key identifier on
503  the file is the histogram name:
504 <pre>
505  TFile f("histos.root", "new");
506  TH1F h1("hgaus", "histo from a gaussian", 100, -3, 3);
507  h1.FillRandom("gaus", 10000);
508  h1->Write();
509 </pre>
510  To read this histogram in another Root session, do:
511 <pre>
512  TFile f("histos.root");
513  TH1F *h = (TH1F*)f.Get("hgaus");
514 </pre>
515  One can save all histograms in memory to the file by:
516 <pre>
517  file->Write();
518 </pre>
519 
520 <h4>Miscelaneous operations</h4>
521 
522 <pre>
523  TH1::KolmogorovTest(): statistical test of compatibility in shape
524  between two histograms
525  TH1::Smooth() smooths the bin contents of a 1-d histogram
526  TH1::Integral() returns the integral of bin contents in a given bin range
527  TH1::GetMean(int axis) returns the mean value along axis
528  TH1::GetStdDev(int axis) returns the sigma distribution along axis
529  TH1::GetEntries() returns the number of entries
530  TH1::Reset() resets the bin contents and errors of an histogram
531 </pre>
532 */
533 
534 TF1 *gF1=0; //left for back compatibility (use TVirtualFitter::GetUserFunc instead)
535 
536 Int_t TH1::fgBufferSize = 1000;
540 
541 extern void H1InitGaus();
542 extern void H1InitExpo();
543 extern void H1InitPolynom();
544 extern void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a);
545 extern void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail);
546 extern void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b);
547 
548 // Internal exceptions for the CheckConsistency method
549 class DifferentDimension: public std::exception {};
550 class DifferentNumberOfBins: public std::exception {};
551 class DifferentAxisLimits: public std::exception {};
552 class DifferentBinLimits: public std::exception {};
553 class DifferentLabels: public std::exception {};
554 
555 ClassImp(TH1)
556 
557 
558 ////////////////////////////////////////////////////////////////////////////////
559 /// Histogram default constructor.
560 
562 {
563  fDirectory = 0;
564  fFunctions = new TList;
565  fNcells = 0;
566  fIntegral = 0;
567  fPainter = 0;
568  fEntries = 0;
569  fNormFactor = 0;
570  fTsumw = fTsumw2=fTsumwx=fTsumwx2=0;
571  fMaximum = -1111;
572  fMinimum = -1111;
573  fBufferSize = 0;
574  fBuffer = 0;
575  fBinStatErrOpt = kNormal;
576  fXaxis.SetName("xaxis");
577  fYaxis.SetName("yaxis");
578  fZaxis.SetName("zaxis");
579  fXaxis.SetParent(this);
580  fYaxis.SetParent(this);
581  fZaxis.SetParent(this);
582  UseCurrentStyle();
583 }
584 
585 
586 ////////////////////////////////////////////////////////////////////////////////
587 /// Histogram default destructor.
588 
590 {
591  if (!TestBit(kNotDeleted)) {
592  return;
593  }
594  delete[] fIntegral;
595  fIntegral = 0;
596  delete[] fBuffer;
597  fBuffer = 0;
598  if (fFunctions) {
599  fFunctions->SetBit(kInvalidObject);
600  TObject* obj = 0;
601  //special logic to support the case where the same object is
602  //added multiple times in fFunctions.
603  //This case happens when the same object is added with different
604  //drawing modes
605  //In the loop below we must be careful with objects (eg TCutG) that may
606  // have been added to the list of functions of several histograms
607  //and may have been already deleted.
608  while ((obj = fFunctions->First())) {
609  while(fFunctions->Remove(obj)) { }
610  if (!obj->TestBit(kNotDeleted)) {
611  break;
612  }
613  delete obj;
614  obj = 0;
615  }
616  delete fFunctions;
617  fFunctions = 0;
618  }
619  if (fDirectory) {
620  fDirectory->Remove(this);
621  fDirectory = 0;
622  }
623  delete fPainter;
624  fPainter = 0;
625 }
626 
627 
628 ////////////////////////////////////////////////////////////////////////////////
629 /// Normal constructor for fix bin size histograms. Creates the main histogram structure.
630 /// \param[in] name name of histogram (avoid blanks)
631 /// \param[in] title histogram title.
632 /// If title is of the form "stringt;stringx;stringy;stringz"
633 /// the histogram title is set to stringt,
634 /// the x axis title to stringy, the y axis title to stringy, etc.
635 /// \param[in] nbins number of bins
636 /// \param[in] xlow low edge of first bin
637 /// \param[in] xup upper edge of last bin (not included in last bin)
638 ///
639 /// When an histogram is created, it is automatically added to the list
640 /// of special objects in the current directory.
641 /// To find the pointer to this histogram in the current directory
642 /// by its name, do:
643 ///
644 /// TH1F *h1 = (TH1F*)gDirectory->FindObject(name);
645 
646 TH1::TH1(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
647  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
648 {
649  Build();
650  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
651  fXaxis.Set(nbins,xlow,xup);
652  fNcells = fXaxis.GetNbins()+2;
653 }
654 
655 
656 ////////////////////////////////////////////////////////////////////////////////
657 /// Normal constructor for variable bin size histograms. Creates the main histogram structure.
658 /// \param[in] name name of histogram (avoid blanks)
659 /// \param[in] title histogram title.
660 /// If title is of the form "stringt;stringx;stringy;stringz"
661 /// the histogram title is set to stringt,
662 /// the x axis title to stringy, the y axis title to stringy, etc.
663 /// \param[in] nbins number of bins
664 /// \param[in] xbins array of low-edges for each bin.
665 /// This is an array of size nbins+1
666 
667 TH1::TH1(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
668  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
669 {
670  Build();
671  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
672  if (xbins) fXaxis.Set(nbins,xbins);
673  else fXaxis.Set(nbins,0,1);
674  fNcells = fXaxis.GetNbins()+2;
675 }
676 
677 
678 ////////////////////////////////////////////////////////////////////////////////
679 /// Normal constructor for variable bin size histograms.
680 ///
681 /// \param[in] name name of histogram (avoid blanks)
682 /// \param[in] title histogram title.
683 /// If title is of the form "stringt;stringx;stringy;stringz"
684 /// the histogram title is set to stringt,
685 /// the x axis title to stringy, the y axis title to stringy, etc.
686 /// \param[in] nbins number of bins
687 /// \param[in] xbins array of low-edges for each bin.
688 /// This is an array of size nbins+1
689 
690 TH1::TH1(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
691  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
692 {
693  Build();
694  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
695  if (xbins) fXaxis.Set(nbins,xbins);
696  else fXaxis.Set(nbins,0,1);
697  fNcells = fXaxis.GetNbins()+2;
698 }
699 
700 
701 ////////////////////////////////////////////////////////////////////////////////
702 /// Copy constructor.
703 /// The list of functions is not copied. (Use Clone if needed)
704 
706 {
707  ((TH1&)h).Copy(*this);
708 }
709 
710 
711 ////////////////////////////////////////////////////////////////////////////////
712 ///static function: cannot be inlined on Windows/NT
713 
715 {
716  return fgAddDirectory;
717 }
718 
719 
720 ////////////////////////////////////////////////////////////////////////////////
721 /// Browe the Histogram object.
722 
724 {
725  Draw(b ? b->GetDrawOption() : "");
726  gPad->Update();
727 }
728 
729 
730 ////////////////////////////////////////////////////////////////////////////////
731 /// Creates histogram basic data structure.
732 
734 {
735  fDirectory = 0;
736  fPainter = 0;
737  fIntegral = 0;
738  fEntries = 0;
739  fNormFactor = 0;
741  fMaximum = -1111;
742  fMinimum = -1111;
743  fBufferSize = 0;
744  fBuffer = 0;
746  fXaxis.SetName("xaxis");
747  fYaxis.SetName("yaxis");
748  fZaxis.SetName("zaxis");
749  fYaxis.Set(1,0.,1.);
750  fZaxis.Set(1,0.,1.);
751  fXaxis.SetParent(this);
752  fYaxis.SetParent(this);
753  fZaxis.SetParent(this);
754 
755  SetTitle(fTitle.Data());
756 
757  fFunctions = new TList;
758 
759  UseCurrentStyle();
760 
761  if (TH1::AddDirectoryStatus()) {
763  if (fDirectory) {
764  fDirectory->Append(this,kTRUE);
765  }
766  }
767 }
768 
769 
770 ////////////////////////////////////////////////////////////////////////////////
771 /// Performs the operation: this = this + c1*f1
772 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
773 ///
774 /// By default, the function is computed at the centre of the bin.
775 /// if option "I" is specified (1-d histogram only), the integral of the
776 /// function in each bin is used instead of the value of the function at
777 /// the centre of the bin.
778 /// Only bins inside the function range are recomputed.
779 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
780 /// you should call Sumw2 before making this operation.
781 /// This is particularly important if you fit the histogram after TH1::Add
782 ///
783 /// The function return kFALSE if the Add operation failed
784 
786 {
787  if (!f1) {
788  Error("Add","Attempt to add a non-existing function");
789  return kFALSE;
790  }
791 
792  TString opt = option;
793  opt.ToLower();
794  Bool_t integral = kFALSE;
795  if (opt.Contains("i") && fDimension == 1) integral = kTRUE;
796 
797  Int_t ncellsx = GetNbinsX() + 2; // cells = normal bins + underflow bin + overflow bin
798  Int_t ncellsy = GetNbinsY() + 2;
799  Int_t ncellsz = GetNbinsZ() + 2;
800  if (fDimension < 2) ncellsy = 1;
801  if (fDimension < 3) ncellsz = 1;
802 
803  // delete buffer if it is there since it will become invalid
804  if (fBuffer) BufferEmpty(1);
805 
806  // - Add statistics
807  Double_t s1[10];
808  for (Int_t i = 0; i < 10; ++i) s1[i] = 0;
809  PutStats(s1);
810  SetMinimum();
811  SetMaximum();
812 
813  // - Loop on bins (including underflows/overflows)
814  Int_t bin, binx, biny, binz;
815  Double_t cu=0;
816  Double_t xx[3];
817  Double_t *params = 0;
818  f1->InitArgs(xx,params);
819  for (binz = 0; binz < ncellsz; ++binz) {
820  xx[2] = fZaxis.GetBinCenter(binz);
821  for (biny = 0; biny < ncellsy; ++biny) {
822  xx[1] = fYaxis.GetBinCenter(biny);
823  for (binx = 0; binx < ncellsx; ++binx) {
824  xx[0] = fXaxis.GetBinCenter(binx);
825  if (!f1->IsInside(xx)) continue;
827  bin = binx + ncellsx * (biny + ncellsy * binz);
828  if (integral) {
829  xx[0] = fXaxis.GetBinLowEdge(binx);
830  cu = c1*f1->EvalPar(xx);
831  cu += c1*f1->Integral(fXaxis.GetBinLowEdge(binx), fXaxis.GetBinUpEdge(binx)) * fXaxis.GetBinWidth(binx);
832  } else {
833  cu = c1*f1->EvalPar(xx);
834  }
835  if (TF1::RejectedPoint()) continue;
836  AddBinContent(bin,cu);
837  }
838  }
839  }
840 
841  return kTRUE;
842 }
843 
844 
845 ////////////////////////////////////////////////////////////////////////////////
846 /// Performs the operation: this = this + c1*h1
847 /// If errors are defined (see TH1::Sumw2), errors are also recalculated.
848 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
849 /// if not already set.
850 /// Note also that adding histogram with labels is not supported, histogram will be
851 /// added merging them by bin number independently of the labels.
852 /// For adding histogram with labels one should use TH1::Merge
853 ///
854 /// SPECIAL CASE (Average/Efficiency histograms)
855 /// For histograms representing averages or efficiencies, one should compute the average
856 /// of the two histograms and not the sum. One can mark a histogram to be an average
857 /// histogram by setting its bit kIsAverage with
858 /// myhist.SetBit(TH1::kIsAverage);
859 /// Note that the two histograms must have their kIsAverage bit set
860 ///
861 /// IMPORTANT NOTE1: If you intend to use the errors of this histogram later
862 /// you should call Sumw2 before making this operation.
863 /// This is particularly important if you fit the histogram after TH1::Add
864 ///
865 /// IMPORTANT NOTE2: if h1 has a normalisation factor, the normalisation factor
866 /// is used , ie this = this + c1*factor*h1
867 /// Use the other TH1::Add function if you do not want this feature
868 ///
869 /// The function return kFALSE if the Add operation failed
870 
872 {
873  if (!h1) {
874  Error("Add","Attempt to add a non-existing histogram");
875  return kFALSE;
876  }
877 
878  // delete buffer if it is there since it will become invalid
879  if (fBuffer) BufferEmpty(1);
880 
881  bool useMerge = (c1 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
882  try {
883  CheckConsistency(this,h1);
884  useMerge = kFALSE;
885  } catch(DifferentNumberOfBins&) {
886  if (useMerge)
887  Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
888  else {
889  Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
890  return kFALSE;
891  }
892  } catch(DifferentAxisLimits&) {
893  if (useMerge)
894  Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
895  else
896  Warning("Add","Attempt to add histograms with different axis limits");
897  } catch(DifferentBinLimits&) {
898  if (useMerge)
899  Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
900  else
901  Warning("Add","Attempt to add histograms with different bin limits");
902  } catch(DifferentLabels&) {
903  // in case of different labels -
904  if (useMerge)
905  Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
906  else
907  Info("Warning","Attempt to add histograms with different labels");
908  }
909 
910  if (useMerge) {
911  TList l;
912  l.Add(const_cast<TH1*>(h1));
913  auto iret = Merge(&l);
914  return (iret >= 0);
915  }
916 
917  // Create Sumw2 if h1 has Sumw2 set
918  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
919 
920  // - Add statistics
921  Double_t entries = TMath::Abs( GetEntries() + c1 * h1->GetEntries() );
922 
923  // statistics can be preserbed only in case of positive coefficients
924  // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
925  Bool_t resetStats = (c1 < 0);
926  Double_t s1[kNstat] = {0};
927  Double_t s2[kNstat] = {0};
928  if (!resetStats) {
929  // need to initialize to zero s1 and s2 since
930  // GetStats fills only used elements depending on dimension and type
931  GetStats(s1);
932  h1->GetStats(s2);
933  }
934 
935  SetMinimum();
936  SetMaximum();
937 
938  // - Loop on bins (including underflows/overflows)
939  Double_t factor = 1;
940  if (h1->GetNormFactor() != 0) factor = h1->GetNormFactor()/h1->GetSumOfWeights();;
941  Double_t c1sq = c1 * c1;
942  Double_t factsq = factor * factor;
943 
944  for (Int_t bin = 0; bin < fNcells; ++bin) {
945  //special case where histograms have the kIsAverage bit set
946  if (this->TestBit(kIsAverage) && h1->TestBit(kIsAverage)) {
947  Double_t y1 = h1->RetrieveBinContent(bin);
948  Double_t y2 = this->RetrieveBinContent(bin);
949  Double_t e1sq = h1->GetBinErrorSqUnchecked(bin);
950  Double_t e2sq = this->GetBinErrorSqUnchecked(bin);
951  Double_t w1 = 1., w2 = 1.;
952 
953  // consider all special cases when bin errors are zero
954  // see http://root.cern.ch/phpBB3//viewtopic.php?f=3&t=13299
955  if (e1sq) w1 = 1. / e1sq;
956  else if (h1->fSumw2.fN) {
957  w1 = 1.E200; // use an arbitrary huge value
958  if (y1 == 0) {
959  // use an estimated error from the global histogram scale
960  double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
961  w1 = 1./(sf*sf);
962  }
963  }
964  if (e2sq) w2 = 1. / e2sq;
965  else if (fSumw2.fN) {
966  w2 = 1.E200; // use an arbitrary huge value
967  if (y2 == 0) {
968  // use an estimated error from the global histogram scale
969  double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
970  w2 = 1./(sf*sf);
971  }
972  }
973 
974  double y = (w1*y1 + w2*y2)/(w1 + w2);
975  UpdateBinContent(bin, y);
976  if (fSumw2.fN) {
977  double err2 = 1./(w1 + w2);
978  if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
979  fSumw2.fArray[bin] = err2;
980  }
981  } else { // normal case of addition between histograms
982  AddBinContent(bin, c1 * factor * h1->RetrieveBinContent(bin));
983  if (fSumw2.fN) fSumw2.fArray[bin] += c1sq * factsq * h1->GetBinErrorSqUnchecked(bin);
984  }
985  }
986 
987  // update statistics (do here to avoid changes by SetBinContent)
988  if (resetStats) {
989  // statistics need to be reset in case coefficient are negative
990  ResetStats();
991  }
992  else {
993  for (Int_t i=0;i<kNstat;i++) {
994  if (i == 1) s1[i] += c1*c1*s2[i];
995  else s1[i] += c1*s2[i];
996  }
997  PutStats(s1);
998  SetEntries(entries);
999  }
1000  return kTRUE;
1001 }
1002 
1003 
1004 ////////////////////////////////////////////////////////////////////////////////
1005 /// Replace contents of this histogram by the addition of h1 and h2.
1006 ///
1007 ///this = c1*h1 + c2*h2
1008 ///if errors are defined (see TH1::Sumw2), errors are also recalculated
1009 ///Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
1010 ///if not already set.
1011 ///Note also that adding histogram with labels is not supported, histogram will be
1012 ///added merging them by bin number independently of the labels.
1013 ///For adding histogram ith labels one should use TH1::Merge
1014 ///
1015 /// SPECIAL CASE (Average/Efficiency histograms)
1016 /// For histograms representing averages or efficiencies, one should compute the average
1017 /// of the two histograms and not the sum. One can mark a histogram to be an average
1018 /// histogram by setting its bit kIsAverage with
1019 /// myhist.SetBit(TH1::kIsAverage);
1020 /// Note that the two histograms must have their kIsAverage bit set
1021 ///
1022 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
1023 /// you should call Sumw2 before making this operation.
1024 /// This is particularly important if you fit the histogram after TH1::Add
1025 ///
1026 /// ANOTHER SPECIAL CASE : h1 = h2 and c2 < 0
1027 /// do a scaling this = c1 * h1 / (bin Volume)
1028 ///
1029 /// The function returns kFALSE if the Add operation failed
1030 
1032 {
1033 
1034  if (!h1 || !h2) {
1035  Error("Add","Attempt to add a non-existing histogram");
1036  return kFALSE;
1037  }
1038 
1039  // delete buffer if it is there since it will become invalid
1040  if (fBuffer) BufferEmpty(1);
1041 
1042  Bool_t normWidth = kFALSE;
1043  if (h1 == h2 && c2 < 0) {c2 = 0; normWidth = kTRUE;}
1044 
1045  if (h1 != h2) {
1046  bool useMerge = (c1 == 1. && c2 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
1047 
1048  try {
1049  CheckConsistency(h1,h2);
1050  CheckConsistency(this,h1);
1051  useMerge = kFALSE;
1052  } catch(DifferentNumberOfBins&) {
1053  if (useMerge)
1054  Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
1055  else {
1056  Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
1057  return kFALSE;
1058  }
1059  } catch(DifferentAxisLimits&) {
1060  if (useMerge)
1061  Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
1062  else
1063  Warning("Add","Attempt to add histograms with different axis limits");
1064  } catch(DifferentBinLimits&) {
1065  if (useMerge)
1066  Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
1067  else
1068  Warning("Add","Attempt to add histograms with different bin limits");
1069  } catch(DifferentLabels&) {
1070  // in case of different labels -
1071  if (useMerge)
1072  Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
1073  else
1074  Info("Warning","Attempt to add histograms with different labels");
1075  }
1076 
1077  if (useMerge) {
1078  TList l;
1079  // why TList takes non-const pointers ????
1080  l.Add(const_cast<TH1*>(h1));
1081  l.Add(const_cast<TH1*>(h2));
1082  Reset("ICE");
1083  auto iret = Merge(&l);
1084  return (iret >= 0);
1085  }
1086  }
1087 
1088  // Create Sumw2 if h1 or h2 have Sumw2 set
1089  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
1090 
1091  // - Add statistics
1092  Double_t nEntries = TMath::Abs( c1*h1->GetEntries() + c2*h2->GetEntries() );
1093 
1094  // TODO remove
1095  // statistics can be preserved only in case of positive coefficients
1096  // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
1097  // also in case of scaling with the width we cannot preserve the statistics
1098  Double_t s1[kNstat] = {0};
1099  Double_t s2[kNstat] = {0};
1100  Double_t s3[kNstat];
1101 
1102 
1103  Bool_t resetStats = (c1*c2 < 0) || normWidth;
1104  if (!resetStats) {
1105  // need to initialize to zero s1 and s2 since
1106  // GetStats fills only used elements depending on dimension and type
1107  h1->GetStats(s1);
1108  h2->GetStats(s2);
1109  for (Int_t i=0;i<kNstat;i++) {
1110  if (i == 1) s3[i] = c1*c1*s1[i] + c2*c2*s2[i];
1111  //else s3[i] = TMath::Abs(c1)*s1[i] + TMath::Abs(c2)*s2[i];
1112  else s3[i] = c1*s1[i] + c2*s2[i];
1113  }
1114  }
1115 
1116  SetMinimum();
1117  SetMaximum();
1118 
1119  if (normWidth) { // DEPRECATED CASE: belongs to fitting / drawing modules
1120 
1121  Int_t nbinsx = GetNbinsX() + 2; // normal bins + underflow, overflow
1122  Int_t nbinsy = GetNbinsY() + 2;
1123  Int_t nbinsz = GetNbinsZ() + 2;
1124 
1125  if (fDimension < 2) nbinsy = 1;
1126  if (fDimension < 3) nbinsz = 1;
1127 
1128  Int_t bin, binx, biny, binz;
1129  for (binz = 0; binz < nbinsz; ++binz) {
1130  Double_t wz = h1->GetZaxis()->GetBinWidth(binz);
1131  for (biny = 0; biny < nbinsy; ++biny) {
1132  Double_t wy = h1->GetYaxis()->GetBinWidth(biny);
1133  for (binx = 0; binx < nbinsx; ++binx) {
1134  Double_t wx = h1->GetXaxis()->GetBinWidth(binx);
1135  bin = GetBin(binx, biny, binz);
1136  Double_t w = wx*wy*wz;
1137  UpdateBinContent(bin, c1 * h1->RetrieveBinContent(bin) / w);
1138  if (fSumw2.fN) {
1139  Double_t e1 = h1->GetBinError(bin)/w;
1140  fSumw2.fArray[bin] = c1*c1*e1*e1;
1141  }
1142  }
1143  }
1144  }
1145  } else if (h1->TestBit(kIsAverage) && h2->TestBit(kIsAverage)) {
1146  for (Int_t i = 0; i < fNcells; ++i) { // loop on cells (bins including underflow / overflow)
1147  // special case where histograms have the kIsAverage bit set
1148  Double_t y1 = h1->RetrieveBinContent(i);
1149  Double_t y2 = h2->RetrieveBinContent(i);
1150  Double_t e1sq = h1->GetBinErrorSqUnchecked(i);
1151  Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
1152  Double_t w1 = 1., w2 = 1.;
1153 
1154  // consider all special cases when bin errors are zero
1155  // see http://root.cern.ch/phpBB3//viewtopic.php?f=3&t=13299
1156  if (e1sq) w1 = 1./ e1sq;
1157  else if (h1->fSumw2.fN) {
1158  w1 = 1.E200; // use an arbitrary huge value
1159  if (y1 == 0 ) { // use an estimated error from the global histogram scale
1160  double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
1161  w1 = 1./(sf*sf);
1162  }
1163  }
1164  if (e2sq) w2 = 1./ e2sq;
1165  else if (h2->fSumw2.fN) {
1166  w2 = 1.E200; // use an arbitrary huge value
1167  if (y2 == 0) { // use an estimated error from the global histogram scale
1168  double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
1169  w2 = 1./(sf*sf);
1170  }
1171  }
1172 
1173  double y = (w1*y1 + w2*y2)/(w1 + w2);
1174  UpdateBinContent(i, y);
1175  if (fSumw2.fN) {
1176  double err2 = 1./(w1 + w2);
1177  if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
1178  fSumw2.fArray[i] = err2;
1179  }
1180  }
1181  } else { // case of simple histogram addition
1182  Double_t c1sq = c1 * c1;
1183  Double_t c2sq = c2 * c2;
1184  for (Int_t i = 0; i < fNcells; ++i) { // Loop on cells (bins including underflows/overflows)
1185  UpdateBinContent(i, c1 * h1->RetrieveBinContent(i) + c2 * h2->RetrieveBinContent(i));
1186  if (fSumw2.fN) {
1187  fSumw2.fArray[i] = c1sq * h1->GetBinErrorSqUnchecked(i) + c2sq * h2->GetBinErrorSqUnchecked(i);
1188  }
1189  }
1190  }
1191 
1192  if (resetStats) {
1193  // statistics need to be reset in case coefficient are negative
1194  ResetStats();
1195  }
1196  else {
1197  // update statistics (do here to avoid changes by SetBinContent) FIXME remove???
1198  PutStats(s3);
1199  SetEntries(nEntries);
1200  }
1201 
1202  return kTRUE;
1203 }
1204 
1205 
1206 ////////////////////////////////////////////////////////////////////////////////
1207 /// Increment bin content by 1.
1208 
1210 {
1211  AbstractMethod("AddBinContent");
1212 }
1213 
1214 
1215 ////////////////////////////////////////////////////////////////////////////////
1216 /// Increment bin content by a weight w.
1217 
1219 {
1220  AbstractMethod("AddBinContent");
1221 }
1222 
1223 
1224 ////////////////////////////////////////////////////////////////////////////////
1225 /// Sets the flag controlling the automatic add of histograms in memory
1226 ///
1227 /// By default (fAddDirectory = kTRUE), histograms are automatically added
1228 /// to the list of objects in memory.
1229 /// Note that one histogram can be removed from its support directory
1230 /// by calling h->SetDirectory(0) or h->SetDirectory(dir) to add it
1231 /// to the list of objects in the directory dir.
1232 ///
1233 /// NOTE that this is a static function. To call it, use;
1234 /// TH1::AddDirectory
1235 
1237 {
1238  fgAddDirectory = add;
1239 }
1240 
1241 
1242 ////////////////////////////////////////////////////////////////////////////////
1243 /// Fill histogram with all entries in the buffer.
1244 /// action = -1 histogram is reset and refilled from the buffer (called by THistPainter::Paint)
1245 /// action = 0 histogram is reset and filled from the buffer. When the histogram is filled from the
1246 /// buffer the value fBuffer[0] is set to a negative number (= - number of entries)
1247 /// When calling with action == 0 the histogram is NOT refilled when fBuffer[0] is < 0
1248 /// While when calling with action = -1 the histogram is reset and ALWAYS refilled independently if
1249 /// the histogram was filled before. This is needed when drawing the histogram
1250 ///
1251 /// action = 1 histogram is filled and buffer is deleted
1252 /// The buffer is automatically deleted when filling the histogram and the entries is
1253 /// larger than the buffer size
1254 ///
1255 
1257 {
1258  // do we need to compute the bin size?
1259  if (!fBuffer) return 0;
1260  Int_t nbentries = (Int_t)fBuffer[0];
1261 
1262  // nbentries correspond to the number of entries of histogram
1263 
1264  if (nbentries == 0) {
1265  // if action is 1 we delete the buffer
1266  // this will avoid infinite recursion
1267  if (action > 0) {
1268  delete [] fBuffer;
1269  fBuffer = 0;
1270  fBufferSize = 0;
1271  }
1272  return 0;
1273  }
1274  if (nbentries < 0 && action == 0) return 0; // case histogram has been already filled from the buffer
1275 
1276  Double_t *buffer = fBuffer;
1277  if (nbentries < 0) {
1278  nbentries = -nbentries;
1279  // a reset might call BufferEmpty() giving an infinite recursion
1280  // Protect it by setting fBuffer = 0
1281  fBuffer=0;
1282  //do not reset the list of functions
1283  Reset("ICES");
1284  fBuffer = buffer;
1285  }
1286  if (CanExtendAllAxes() || (fXaxis.GetXmax() <= fXaxis.GetXmin())) {
1287  //find min, max of entries in buffer
1288  Double_t xmin = fBuffer[2];
1289  Double_t xmax = xmin;
1290  for (Int_t i=1;i<nbentries;i++) {
1291  Double_t x = fBuffer[2*i+2];
1292  if (x < xmin) xmin = x;
1293  if (x > xmax) xmax = x;
1294  }
1295  if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
1297  } else {
1298  fBuffer = 0;
1299  Int_t keep = fBufferSize; fBufferSize = 0;
1300  if (xmin < fXaxis.GetXmin()) ExtendAxis(xmin,&fXaxis);
1301  if (xmax >= fXaxis.GetXmax()) ExtendAxis(xmax,&fXaxis);
1302  fBuffer = buffer;
1303  fBufferSize = keep;
1304  }
1305  }
1306 
1307  // call DoFillN which will not put entries in the buffer as FillN does
1308  // set fBuffer to zero to avoid re-emptying the buffer from functions called
1309  // by DoFillN (e.g Sumw2)
1310  buffer = fBuffer; fBuffer = 0;
1311  DoFillN(nbentries,&buffer[2],&buffer[1],2);
1312  fBuffer = buffer;
1313 
1314  // if action == 1 - delete the buffer
1315  if (action > 0) {
1316  delete [] fBuffer;
1317  fBuffer = 0;
1318  fBufferSize = 0;}
1319  else {
1320  // if number of entries is consistent with buffer - set it negative to avoid
1321  // refilling the histogram every time BufferEmpty(0) is called
1322  // In case it is not consistent, by setting fBuffer[0]=0 is like resetting the buffer
1323  // (it will not be used anymore the next time BufferEmpty is called)
1324  if (nbentries == (Int_t)fEntries)
1325  fBuffer[0] = -nbentries;
1326  else
1327  fBuffer[0] = 0;
1328  }
1329  return nbentries;
1330 }
1331 
1332 
1333 ////////////////////////////////////////////////////////////////////////////////
1334 /// accumulate arguments in buffer. When buffer is full, empty the buffer
1335 /// fBuffer[0] = number of entries in buffer
1336 /// fBuffer[1] = w of first entry
1337 /// fBuffer[2] = x of first entry
1338 
1340 {
1341  if (!fBuffer) return -2;
1342  Int_t nbentries = (Int_t)fBuffer[0];
1343 
1344 
1345  if (nbentries < 0) {
1346  // reset nbentries to a positive value so next time BufferEmpty() is called
1347  // the histogram will be refilled
1348  nbentries = -nbentries;
1349  fBuffer[0] = nbentries;
1350  if (fEntries > 0) {
1351  // set fBuffer to zero to avoid calling BufferEmpty in Reset
1352  Double_t *buffer = fBuffer; fBuffer=0;
1353  Reset("ICES"); // do not reset list of functions
1354  fBuffer = buffer;
1355  }
1356  }
1357  if (2*nbentries+2 >= fBufferSize) {
1358  BufferEmpty(1);
1359  if (!fBuffer)
1360  // to avoid infinite recursion Fill->BufferFill->Fill
1361  return Fill(x,w);
1362  // this cannot happen
1363  R__ASSERT(0);
1364  }
1365  fBuffer[2*nbentries+1] = w;
1366  fBuffer[2*nbentries+2] = x;
1367  fBuffer[0] += 1;
1368  return -2;
1369 }
1370 
1371 
1372 ////////////////////////////////////////////////////////////////////////////////
1373 
1374 bool TH1::CheckBinLimits(const TAxis* a1, const TAxis * a2)
1375 {
1376  const TArrayD * h1Array = a1->GetXbins();
1377  const TArrayD * h2Array = a2->GetXbins();
1378  Int_t fN = h1Array->fN;
1379  if ( fN != 0 ) {
1380  if ( h2Array->fN != fN ) {
1381  throw DifferentBinLimits();
1382  return false;
1383  }
1384  else {
1385  for ( int i = 0; i < fN; ++i ) {
1386  if ( ! TMath::AreEqualRel( h1Array->GetAt(i), h2Array->GetAt(i), 1E-10 ) ) {
1387  throw DifferentBinLimits();
1388  return false;
1389  }
1390  }
1391  }
1392  }
1393 
1394  return true;
1395 }
1396 
1397 
1398 ////////////////////////////////////////////////////////////////////////////////
1399 /// check that axis have same labels
1400 
1401 bool TH1::CheckBinLabels(const TAxis* a1, const TAxis * a2)
1402 {
1403  THashList *l1 = a1->GetLabels();
1404  THashList *l2 = a2->GetLabels();
1405 
1406  if (!l1 && !l2 )
1407  return true;
1408  if (!l1 || !l2 ) {
1409  throw DifferentLabels();
1410  return false;
1411  }
1412  // check now labels sizes are the same
1413  if (l1->GetSize() != l2->GetSize() ) {
1414  throw DifferentLabels();
1415  return false;
1416  }
1417  for (int i = 1; i <= a1->GetNbins(); ++i) {
1418  TString label1 = a1->GetBinLabel(i);
1419  TString label2 = a2->GetBinLabel(i);
1420  if (label1 != label2) {
1421  throw DifferentLabels();
1422  return false;
1423  }
1424  }
1425 
1426  return true;
1427 }
1428 
1429 
1430 ////////////////////////////////////////////////////////////////////////////////
1431 /// Check that the axis limits of the histograms are the same
1432 /// if a first and last bin is passed the axis is compared between the given range
1433 
1434 bool TH1::CheckAxisLimits(const TAxis *a1, const TAxis *a2 )
1435 {
1436  if ( ! TMath::AreEqualRel(a1->GetXmin(), a2->GetXmin(),1.E-12) ||
1437  ! TMath::AreEqualRel(a1->GetXmax(), a2->GetXmax(),1.E-12) ) {
1438  throw DifferentAxisLimits();
1439  return false;
1440  }
1441  return true;
1442 }
1443 
1444 
1445 ////////////////////////////////////////////////////////////////////////////////
1446 /// Check that the axis are the same
1447 
1448 bool TH1::CheckEqualAxes(const TAxis *a1, const TAxis *a2 )
1449 {
1450  if (a1->GetNbins() != a2->GetNbins() ) {
1451  //throw DifferentNumberOfBins();
1452  ::Info("CheckEqualAxes","Axes have different number of bins : nbin1 = %d nbin2 = %d",a1->GetNbins(),a2->GetNbins() );
1453  return false;
1454  }
1455  try {
1456  CheckAxisLimits(a1,a2);
1457  } catch (DifferentAxisLimits&) {
1458  ::Info("CheckEqualAxes","Axes have different limits");
1459  return false;
1460  }
1461  try {
1462  CheckBinLimits(a1,a2);
1463  } catch (DifferentBinLimits&) {
1464  ::Info("CheckEqualAxes","Axes have different bin limits");
1465  return false;
1466  }
1467 
1468  // check labels
1469  try {
1470  CheckBinLabels(a1,a2);
1471  } catch (DifferentLabels&) {
1472  ::Info("CheckEqualAxes","Axes have different labels");
1473  return false;
1474  }
1475 
1476  return true;
1477 }
1478 
1479 
1480 ////////////////////////////////////////////////////////////////////////////////
1481 /// Check that two sub axis are the same
1482 /// the limits are defined by first bin and last bin
1483 /// N.B. no check is done in this case for variable bins
1484 
1485 bool TH1::CheckConsistentSubAxes(const TAxis *a1, Int_t firstBin1, Int_t lastBin1, const TAxis * a2, Int_t firstBin2, Int_t lastBin2 )
1486 {
1487  // By default is assumed that no bins are given for the second axis
1488  Int_t nbins1 = lastBin1-firstBin1 + 1;
1489  Double_t xmin1 = a1->GetBinLowEdge(firstBin1);
1490  Double_t xmax1 = a1->GetBinUpEdge(lastBin1);
1491 
1492  Int_t nbins2 = a2->GetNbins();
1493  Double_t xmin2 = a2->GetXmin();
1494  Double_t xmax2 = a2->GetXmax();
1495 
1496  if (firstBin2 < lastBin2) {
1497  // in this case assume no bins are given for the second axis
1498  nbins2 = lastBin1-firstBin1 + 1;
1499  xmin2 = a1->GetBinLowEdge(firstBin1);
1500  xmax2 = a1->GetBinUpEdge(lastBin1);
1501  }
1502 
1503  if (nbins1 != nbins2 ) {
1504  ::Info("CheckConsistentSubAxes","Axes have different number of bins");
1505  return false;
1506  }
1507 
1508  if ( ! TMath::AreEqualRel(xmin1,xmin2,1.E-12) ||
1509  ! TMath::AreEqualRel(xmax1,xmax2,1.E-12) ) {
1510  ::Info("CheckConsistentSubAxes","Axes have different limits");
1511  return false;
1512  }
1513 
1514  return true;
1515 }
1516 
1517 
1518 ////////////////////////////////////////////////////////////////////////////////
1519 /// Check histogram compatibility
1520 
1521 bool TH1::CheckConsistency(const TH1* h1, const TH1* h2)
1522 {
1523  if (h1 == h2) return true;
1524 
1525  if (h1->GetDimension() != h2->GetDimension() ) {
1526  throw DifferentDimension();
1527  return false;
1528  }
1529  Int_t dim = h1->GetDimension();
1530 
1531  // returns kTRUE if number of bins and bin limits are identical
1532  Int_t nbinsx = h1->GetNbinsX();
1533  Int_t nbinsy = h1->GetNbinsY();
1534  Int_t nbinsz = h1->GetNbinsZ();
1535 
1536  // Check whether the histograms have the same number of bins.
1537  if (nbinsx != h2->GetNbinsX() ||
1538  (dim > 1 && nbinsy != h2->GetNbinsY()) ||
1539  (dim > 2 && nbinsz != h2->GetNbinsZ()) ) {
1540  throw DifferentNumberOfBins();
1541  return false;
1542  }
1543 
1544  bool ret = true;
1545 
1546  // check axis limits
1547  ret &= CheckAxisLimits(h1->GetXaxis(), h2->GetXaxis());
1548  if (dim > 1) ret &= CheckAxisLimits(h1->GetYaxis(), h2->GetYaxis());
1549  if (dim > 2) ret &= CheckAxisLimits(h1->GetZaxis(), h2->GetZaxis());
1550 
1551  // check bin limits
1552  ret &= CheckBinLimits(h1->GetXaxis(), h2->GetXaxis());
1553  if (dim > 1) ret &= CheckBinLimits(h1->GetYaxis(), h2->GetYaxis());
1554  if (dim > 2) ret &= CheckBinLimits(h1->GetZaxis(), h2->GetZaxis());
1555 
1556  // check labels if histograms are both not empty
1557  if ( (h1->fTsumw != 0 || h1->GetEntries() != 0) &&
1558  (h2->fTsumw != 0 || h2->GetEntries() != 0) ) {
1559  ret &= CheckBinLabels(h1->GetXaxis(), h2->GetXaxis());
1560  if (dim > 1) ret &= CheckBinLabels(h1->GetYaxis(), h2->GetYaxis());
1561  if (dim > 2) ret &= CheckBinLabels(h1->GetZaxis(), h2->GetZaxis());
1562  }
1563 
1564  return ret;
1565 }
1566 
1567 
1568 ////////////////////////////////////////////////////////////////////////////////
1569 /// chi^{2} test for comparing weighted and unweighted histograms
1570 ///
1571 /// Function: Returns p-value. Other return values are specified by the 3rd parameter
1572 ///
1573 /// \param[in] h2 the second histogram
1574 /// \param[in] option
1575 /// - "UU" = experiment experiment comparison (unweighted-unweighted)
1576 /// - "UW" = experiment MC comparison (unweighted-weighted). Note that
1577 /// the first histogram should be unweighted
1578 /// - "WW" = MC MC comparison (weighted-weighted)
1579 /// - "NORM" = to be used when one or both of the histograms is scaled
1580 /// but the histogram originally was unweighted
1581 /// - by default underflows and overlows are not included:
1582 /// * "OF" = overflows included
1583 /// * "UF" = underflows included
1584 /// - "P" = print chi2, ndf, p_value, igood
1585 /// - "CHI2" = returns chi2 instead of p-value
1586 /// - "CHI2/NDF" = returns #chi^{2}/ndf
1587 /// \param[in] res not empty - computes normalized residuals and returns them in this array
1588 ///
1589 /// The current implementation is based on the papers chi^{2} test for comparison
1590 /// of weighted and unweighted histograms" in Proceedings of PHYSTAT05 and
1591 /// "Comparison weighted and unweighted histograms", arXiv:physics/0605123
1592 /// by N.Gagunashvili. This function has been implemented by Daniel Haertl in August 2006.
1593 ///
1594 /// Introduction:
1595 ///
1596 /// A frequently used technique in data analysis is the comparison of
1597 /// histograms. First suggested by Pearson [1] the #chi^{2} test of
1598 /// homogeneity is used widely for comparing usual (unweighted) histograms.
1599 /// This paper describes the implementation modified #chi^{2} tests
1600 /// for comparison of weighted and unweighted histograms and two weighted
1601 /// histograms [2] as well as usual Pearson's #chi^{2} test for
1602 /// comparison two usual (unweighted) histograms.
1603 ///
1604 /// Overview:
1605 ///
1606 /// Comparison of two histograms expect hypotheses that two histograms
1607 /// represent identical distributions. To make a decision p-value should
1608 /// be calculated. The hypotheses of identity is rejected if the p-value is
1609 /// lower then some significance level. Traditionally significance levels
1610 /// 0.1, 0.05 and 0.01 are used. The comparison procedure should include an
1611 /// analysis of the residuals which is often helpful in identifying the
1612 /// bins of histograms responsible for a significant overall #chi^{2} value.
1613 /// Residuals are the difference between bin contents and expected bin
1614 /// contents. Most convenient for analysis are the normalized residuals. If
1615 /// hypotheses of identity are valid then normalized residuals are
1616 /// approximately independent and identically distributed random variables
1617 /// having N(0,1) distribution. Analysis of residuals expect test of above
1618 /// mentioned properties of residuals. Notice that indirectly the analysis
1619 /// of residuals increase the power of #chi^{2} test.
1620 ///
1621 /// Methods of comparison:
1622 ///
1623 /// #chi^{2} test for comparison two (unweighted) histograms:
1624 /// Let us consider two histograms with the same binning and the number
1625 /// of bins equal to r. Let us denote the number of events in the ith bin
1626 /// in the first histogram as ni and as mi in the second one. The total
1627 /// number of events in the first histogram is equal to:
1628 /// \f[
1629 /// N = \sum_{i=1}^{r} n_{i}
1630 /// \f]
1631 /// and
1632 /// \f[
1633 /// M = \sum_{i=1}^{r} m_{i}
1634 /// \f]
1635 /// in the second histogram. The hypothesis of identity (homogeneity) [3]
1636 /// is that the two histograms represent random values with identical
1637 /// distributions. It is equivalent that there exist r constants p1,...,pr,
1638 /// such that
1639 /// \f[
1640 ///\sum_{i=1}^{r} p_{i}=1
1641 /// \f]
1642 /// and the probability of belonging to the ith bin for some measured value
1643 /// in both experiments is equal to pi. The number of events in the ith
1644 /// bin is a random variable with a distribution approximated by a Poisson
1645 /// probability distribution
1646 /// \f[
1647 ///\frac{e^{-Np_{i}}(Np_{i})^{n_{i}}}{n_{i}!}
1648 /// \f]
1649 ///for the first histogram and with distribution
1650 /// \f[
1651 ///\frac{e^{-Mp_{i}}(Mp_{i})^{m_{i}}}{m_{i}!}
1652 /// \f]
1653 /// for the second histogram. If the hypothesis of homogeneity is valid,
1654 /// then the maximum likelihood estimator of pi, i=1,...,r, is
1655 /// \f[
1656 ///\hat{p}_{i}= \frac{n_{i}+m_{i}}{N+M}
1657 /// \f]
1658 /// and then
1659 /// \f[
1660 /// X^{2} = \sum_{i=1}^{r}\frac{(n_{i}-N\hat{p}_{i})^{2}}{N\hat{p}_{i}} + \sum_{i=1}^{r}\frac{(m_{i}-M\hat{p}_{i})^{2}}{M\hat{p}_{i}} =\frac{1}{MN} \sum_{i=1}^{r}\frac{(Mn_{i}-Nm_{i})^{2}}{n_{i}+m_{i}}
1661 /// \f]
1662 /// has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [3].
1663 /// The comparison procedure can include an analysis of the residuals which
1664 /// is often helpful in identifying the bins of histograms responsible for
1665 /// a significant overall #chi^{2} value. Most convenient for
1666 /// analysis are the adjusted (normalized) residuals [4]
1667 /// \f[
1668 /// r_{i} = \frac{n_{i}-N\hat{p}_{i}}{\sqrt{N\hat{p}_{i}}\sqrt{(1-N/(N+M))(1-(n_{i}+m_{i})/(N+M))}}
1669 /// \f]
1670 /// If hypotheses of homogeneity are valid then residuals ri are
1671 /// approximately independent and identically distributed random variables
1672 /// having N(0,1) distribution. The application of the #chi^{2} test has
1673 /// restrictions related to the value of the expected frequencies Npi,
1674 /// Mpi, i=1,...,r. A conservative rule formulated in [5] is that all the
1675 /// expectations must be 1 or greater for both histograms. In practical
1676 /// cases when expected frequencies are not known the estimated expected
1677 /// frequencies \f$ M\hat{p}_{i}, N\hat{p}_{i}, i=1,...,r \f$ can be used.
1678 ///
1679 /// Unweighted and weighted histograms comparison:
1680 ///
1681 /// A simple modification of the ideas described above can be used for the
1682 /// comparison of the usual (unweighted) and weighted histograms. Let us
1683 /// denote the number of events in the ith bin in the unweighted
1684 /// histogram as ni and the common weight of events in the ith bin of the
1685 /// weighted histogram as wi. The total number of events in the
1686 /// unweighted histogram is equal to
1687 ///\f[
1688 /// N = \sum_{i=1}^{r} n_{i}
1689 ///\f]
1690 /// and the total weight of events in the weighted histogram is equal to
1691 ///\f[
1692 /// W = \sum_{i=1}^{r} w_{i}
1693 ///\f]
1694 /// Let us formulate the hypothesis of identity of an unweighted histogram
1695 /// to a weighted histogram so that there exist r constants p1,...,pr, such
1696 /// that
1697 ///\f[
1698 /// \sum_{i=1}^{r} p_{i} = 1
1699 ///\f]
1700 /// for the unweighted histogram. The weight wi is a random variable with a
1701 /// distribution approximated by the normal probability distribution
1702 /// \f$ N(Wp_{i},\sigma_{i}^{2}) \f$ where \f$ \sigma_{i}^{2} \f$ is the variance of the weight wi.
1703 /// If we replace the variance \f$ \sigma_{i}^{2} \f$
1704 /// with estimate \f$ s_{i}^{2} \f$ (sum of squares of weights of
1705 /// events in the ith bin) and the hypothesis of identity is valid, then the
1706 /// maximum likelihood estimator of pi,i=1,...,r, is
1707 ///\f[
1708 /// \hat{p}_{i} = \frac{Ww_{i}-Ns_{i}^{2}+\sqrt{(Ww_{i}-Ns_{i}^{2})^{2}+4W^{2}s_{i}^{2}n_{i}}}{2W^{2}}
1709 ///\f]
1710 /// We may then use the test statistic
1711 ///\f[
1712 /// X^{2} = \sum_{i=1}^{r} \frac{(n_{i}-N\hat{p}_{i})^{2}}{N\hat{p}_{i}} + \sum_{i=1}^{r} \frac{(w_{i}-W\hat{p}_{i})^{2}}{s_{i}^{2}}
1713 ///\f]
1714 /// and it has approximately a \f$ \sigma^{2}_{(r-1)} \f$ distribution [2]. This test, as well
1715 /// as the original one [3], has a restriction on the expected frequencies. The
1716 /// expected frequencies recommended for the weighted histogram is more than 25.
1717 /// The value of the minimal expected frequency can be decreased down to 10 for
1718 /// the case when the weights of the events are close to constant. In the case
1719 /// of a weighted histogram if the number of events is unknown, then we can
1720 /// apply this recommendation for the equivalent number of events as
1721 ///\f[
1722 /// n_{i}^{equiv} = \frac{ w_{i}^{2} }{ s_{i}^{2} }
1723 ///\f]
1724 /// The minimal expected frequency for an unweighted histogram must be 1. Notice
1725 /// that any usual (unweighted) histogram can be considered as a weighted
1726 /// histogram with events that have constant weights equal to 1.
1727 /// The variance \f$ z_{i}^{2} \f$ of the difference between the weight wi
1728 /// and the estimated expectation value of the weight is approximately equal to:
1729 ///\f[
1730 /// z_{i}^{2} = Var(w_{i}-W\hat{p}_{i}) = N\hat{p}_{i}(1-N\hat{p}_{i})\left(\frac{Ws_{i}^{2}}{\sqrt{(Ns_{i}^{2}-w_{i}W)^{2}+4W^{2}s_{i}^{2}n_{i}}}\right)^{2}+\frac{s_{i}^{2}}{4}\left(1+\frac{Ns_{i}^{2}-w_{i}W}{\sqrt{(Ns_{i}^{2}-w_{i}W)^{2}+4W^{2}s_{i}^{2}n_{i}}}\right)^{2}
1731 ///\f]
1732 /// The residuals
1733 ///\f[
1734 /// r_{i} = \frac{w_{i}-W\hat{p}_{i}}{z_{i}}
1735 ///\f]
1736 /// have approximately a normal distribution with mean equal to 0 and standard
1737 /// deviation equal to 1.
1738 ///
1739 /// Two weighted histograms comparison:
1740 ///
1741 /// Let us denote the common weight of events of the ith bin in the first
1742 /// histogram as w1i and as w2i in the second one. The total weight of events
1743 /// in the first histogram is equal to
1744 ///\f[
1745 /// W_{1} = \sum_{i=1}^{r} w_{1i}
1746 ///\f]
1747 /// and
1748 ///\f[
1749 /// W_{2} = \sum_{i=1}^{r} w_{2i}
1750 ///\f]
1751 /// in the second histogram. Let us formulate the hypothesis of identity of
1752 /// weighted histograms so that there exist r constants p1,...,pr, such that
1753 ///\f[
1754 /// \sum_{i=1}^{r} p_{i} = 1
1755 ///\f]
1756 /// and also expectation value of weight w1i equal to W1pi and expectation value
1757 /// of weight w2i equal to W2pi. Weights in both the histograms are random
1758 /// variables with distributions which can be approximated by a normal
1759 /// probability distribution \f$ N(W_{1}p_{i},\sigma_{1i}^{2}) \f$ for the first histogram
1760 /// and by a distribution \f$ N(W_{2}p_{i},\sigma_{2i}^{2}) \f$ for the second.
1761 /// Here \f$ \sigma_{1i}^{2} \f$ and \f$ \sigma_{2i}^{2} \f$ are the variances
1762 /// of w1i and w2i with estimators \f$ s_{1i}^{2} \f$ and \f$ s_{2i}^{2} \f$ respectively.
1763 /// If the hypothesis of identity is valid, then the maximum likelihood and
1764 /// Least Square Method estimator of pi,i=1,...,r, is
1765 ///\f[
1766 /// \hat{p}_{i} = \frac{w_{1i}W_{1}/s_{1i}^{2}+w_{2i}W_{2} /s_{2i}^{2}}{W_{1}^{2}/s_{1i}^{2}+W_{2}^{2}/s_{2i}^{2}}
1767 ///\f]
1768 /// We may then use the test statistic
1769 ///\f[
1770 /// X^{2} = \sum_{i=1}^{r} \frac{(w_{1i}-W_{1}\hat{p}_{i})^{2}}{s_{1i}^{2}} + \sum_{i=1}^{r} \frac{(w_{2i}-W_{2}\hat{p}_{i})^{2}}{s_{2i}^{2}} = \sum_{i=1}^{r} \frac{(W_{1}w_{2i}-W_{2}w_{1i})^{2}}{W_{1}^{2}s_{2i}^{2}+W_{2}^{2}s_{1i}^{2}}
1771 ///\f]
1772 /// and it has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [2].
1773 /// The normalized or studentised residuals [6]
1774 ///\f[
1775 /// r_{i} = \frac{w_{1i}-W_{1}\hat{p}_{i}}{s_{1i}\sqrt{1 - \frac{1}{(1+W_{2}^{2}s_{1i}^{2}/W_{1}^{2}s_{2i}^{2})}}}
1776 ///\f]
1777 /// have approximately a normal distribution with mean equal to 0 and standard
1778 /// deviation 1. A recommended minimal expected frequency is equal to 10 for
1779 /// the proposed test.
1780 ///
1781 /// Numerical examples:
1782 ///
1783 /// The method described herein is now illustrated with an example.
1784 /// We take a distribution
1785 ///\f[
1786 /// \phi(x) = \frac{2}{(x-10)^{2}+1} + \frac{1}{(x-14)^{2}+1} (1)
1787 ///\f]
1788 /// defined on the interval [4,16]. Events distributed according to the formula
1789 /// (1) are simulated to create the unweighted histogram. Uniformly distributed
1790 /// events are simulated for the weighted histogram with weights calculated by
1791 /// formula (1). Each histogram has the same number of bins: 20. Fig.1 shows
1792 /// the result of comparison of the unweighted histogram with 200 events
1793 /// (minimal expected frequency equal to one) and the weighted histogram with
1794 /// 500 events (minimal expected frequency equal to 25)
1795 /// Begin_Macro
1796 /// ../../../tutorials/math/chi2test.C
1797 /// End_Macro
1798 /// Fig 1. An example of comparison of the unweighted histogram with 200 events
1799 /// and the weighted histogram with 500 events:
1800 /// a) unweighted histogram;
1801 /// b) weighted histogram;
1802 /// c) normalized residuals plot;
1803 /// d) normal Q-Q plot of residuals.
1804 ///
1805 /// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1806 /// 21.09 with p-value equal to 0.33, therefore the hypothesis of identity of
1807 /// the two histograms can be accepted for 0.05 significant level. The behavior
1808 /// of the normalized residuals plot (see Fig. 1c) and the normal Q-Q plot
1809 /// (see Fig. 1d) of residuals are regular and we cannot identify the outliers
1810 /// or bins with a big influence on \f$ \chi^{2} \f$.
1811 ///
1812 /// The second example presents the same two histograms but 17 events was added
1813 /// to content of bin number 15 in unweighted histogram. Fig.2 shows the result
1814 /// of comparison of the unweighted histogram with 217 events (minimal expected
1815 /// frequency equal to one) and the weighted histogram with 500 events (minimal
1816 /// expected frequency equal to 25)
1817 /// Begin_Macro
1818 /// ../../../tutorials/math/chi2test.C(17)
1819 /// End_Macro
1820 /// Fig 2. An example of comparison of the unweighted histogram with 217 events
1821 /// and the weighted histogram with 500 events:
1822 /// a) unweighted histogram;
1823 /// b) weighted histogram;
1824 /// c) normalized residuals plot;
1825 /// d) normal Q-Q plot of residuals.
1826 ///
1827 /// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1828 /// 32.33 with p-value equal to 0.029, therefore the hypothesis of identity of
1829 /// the two histograms is rejected for 0.05 significant level. The behavior of
1830 /// the normalized residuals plot (see Fig. 2c) and the normal Q-Q plot (see
1831 /// Fig. 2d) of residuals are not regular and we can identify the outlier or
1832 /// bin with a big influence on \f$ \chi^{2} \f$.
1833 ///
1834 /// References:
1835 ///
1836 /// [1] Pearson, K., 1904. On the Theory of Contingency and Its Relation to
1837 /// Association and Normal Correlation. Drapers' Co. Memoirs, Biometric
1838 /// Series No. 1, London.
1839 /// [2] Gagunashvili, N., 2006. \f$ \sigma^{2} \f$ test for comparison
1840 /// of weighted and unweighted histograms. Statistical Problems in Particle
1841 /// Physics, Astrophysics and Cosmology, Proceedings of PHYSTAT05,
1842 /// Oxford, UK, 12-15 September 2005, Imperial College Press, London, 43-44.
1843 /// Gagunashvili,N., Comparison of weighted and unweighted histograms,
1844 /// arXiv:physics/0605123, 2006.
1845 /// [3] Cramer, H., 1946. Mathematical methods of statistics.
1846 /// Princeton University Press, Princeton.
1847 /// [4] Haberman, S.J., 1973. The analysis of residuals in cross-classified tables.
1848 /// Biometrics 29, 205-220.
1849 /// [5] Lewontin, R.C. and Felsenstein, J., 1965. The robustness of homogeneity
1850 /// test in 2xN tables. Biometrics 21, 19-33.
1851 /// [6] Seber, G.A.F., Lee, A.J., 2003, Linear Regression Analysis.
1852 /// John Wiley & Sons Inc., New York.
1853 
1854 Double_t TH1::Chi2Test(const TH1* h2, Option_t *option, Double_t *res) const
1855 {
1856  Double_t chi2 = 0;
1857  Int_t ndf = 0, igood = 0;
1858 
1859  TString opt = option;
1860  opt.ToUpper();
1861 
1862  Double_t prob = Chi2TestX(h2,chi2,ndf,igood,option,res);
1863 
1864  if(opt.Contains("P")) {
1865  printf("Chi2 = %f, Prob = %g, NDF = %d, igood = %d\n", chi2,prob,ndf,igood);
1866  }
1867  if(opt.Contains("CHI2/NDF")) {
1868  if (ndf == 0) return 0;
1869  return chi2/ndf;
1870  }
1871  if(opt.Contains("CHI2")) {
1872  return chi2;
1873  }
1874 
1875  return prob;
1876 }
1877 
1878 
1879 ////////////////////////////////////////////////////////////////////////////////
1880 /// The computation routine of the Chisquare test. For the method description,
1881 /// see Chi2Test() function.
1882 /// \return p-value
1883 /// \param[in] h2 the second histogram
1884 /// \param[in] option
1885 /// - "UU" = experiment experiment comparison (unweighted-unweighted)
1886 /// - "UW" = experiment MC comparison (unweighted-weighted). Note that the first
1887 /// histogram should be unweighted
1888 /// - "WW" = MC MC comparison (weighted-weighted)
1889 /// - "NORM" = if one or both histograms is scaled
1890 /// - "OF" = overflows included
1891 /// - "UF" = underflows included
1892 /// by default underflows and overflows are not included
1893 /// \param[out] igood test output
1894 /// - igood=0 - no problems
1895 /// - For unweighted unweighted comparison
1896 /// - igood=1'There is a bin in the 1st histogram with less than 1 event'
1897 /// - igood=2'There is a bin in the 2nd histogram with less than 1 event'
1898 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1899 /// - For unweighted weighted comparison
1900 /// - igood=1'There is a bin in the 1st histogram with less then 1 event'
1901 /// - igood=2'There is a bin in the 2nd histogram with less then 10 effective number of events'
1902 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1903 /// - For weighted weighted comparison
1904 /// - igood=1'There is a bin in the 1st histogram with less then 10 effective
1905 /// number of events'
1906 /// - igood=2'There is a bin in the 2nd histogram with less then 10 effective
1907 /// number of events'
1908 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1909 /// \param[out] chi2 chisquare of the test
1910 /// \param[out] ndf number of degrees of freedom (important, when both histograms have the same empty bins)
1911 /// \param[out] res normalized residuals for further analysis
1912 
1913 Double_t TH1::Chi2TestX(const TH1* h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option, Double_t *res) const
1914 {
1916  Int_t i_start, i_end;
1917  Int_t j_start, j_end;
1918  Int_t k_start, k_end;
1919 
1920  Double_t sum1 = 0.0, sumw1 = 0.0;
1921  Double_t sum2 = 0.0, sumw2 = 0.0;
1922 
1923  chi2 = 0.0;
1924  ndf = 0;
1925 
1926  TString opt = option;
1927  opt.ToUpper();
1928 
1929  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
1930 
1931  const TAxis *xaxis1 = GetXaxis();
1932  const TAxis *xaxis2 = h2->GetXaxis();
1933  const TAxis *yaxis1 = GetYaxis();
1934  const TAxis *yaxis2 = h2->GetYaxis();
1935  const TAxis *zaxis1 = GetZaxis();
1936  const TAxis *zaxis2 = h2->GetZaxis();
1937 
1938  Int_t nbinx1 = xaxis1->GetNbins();
1939  Int_t nbinx2 = xaxis2->GetNbins();
1940  Int_t nbiny1 = yaxis1->GetNbins();
1941  Int_t nbiny2 = yaxis2->GetNbins();
1942  Int_t nbinz1 = zaxis1->GetNbins();
1943  Int_t nbinz2 = zaxis2->GetNbins();
1944 
1945  //check dimensions
1946  if (this->GetDimension() != h2->GetDimension() ){
1947  Error("Chi2TestX","Histograms have different dimensions.");
1948  return 0.0;
1949  }
1950 
1951  //check number of channels
1952  if (nbinx1 != nbinx2) {
1953  Error("Chi2TestX","different number of x channels");
1954  }
1955  if (nbiny1 != nbiny2) {
1956  Error("Chi2TestX","different number of y channels");
1957  }
1958  if (nbinz1 != nbinz2) {
1959  Error("Chi2TestX","different number of z channels");
1960  }
1961 
1962  //check for ranges
1963  i_start = j_start = k_start = 1;
1964  i_end = nbinx1;
1965  j_end = nbiny1;
1966  k_end = nbinz1;
1967 
1968  if (xaxis1->TestBit(TAxis::kAxisRange)) {
1969  i_start = xaxis1->GetFirst();
1970  i_end = xaxis1->GetLast();
1971  }
1972  if (yaxis1->TestBit(TAxis::kAxisRange)) {
1973  j_start = yaxis1->GetFirst();
1974  j_end = yaxis1->GetLast();
1975  }
1976  if (zaxis1->TestBit(TAxis::kAxisRange)) {
1977  k_start = zaxis1->GetFirst();
1978  k_end = zaxis1->GetLast();
1979  }
1980 
1981 
1982  if (opt.Contains("OF")) {
1983  if (GetDimension() == 3) k_end = ++nbinz1;
1984  if (GetDimension() >= 2) j_end = ++nbiny1;
1985  if (GetDimension() >= 1) i_end = ++nbinx1;
1986  }
1987 
1988  if (opt.Contains("UF")) {
1989  if (GetDimension() == 3) k_start = 0;
1990  if (GetDimension() >= 2) j_start = 0;
1991  if (GetDimension() >= 1) i_start = 0;
1992  }
1993 
1994  ndf = (i_end - i_start + 1) * (j_end - j_start + 1) * (k_end - k_start + 1) - 1;
1995 
1996  Bool_t comparisonUU = opt.Contains("UU");
1997  Bool_t comparisonUW = opt.Contains("UW");
1998  Bool_t comparisonWW = opt.Contains("WW");
1999  Bool_t scaledHistogram = opt.Contains("NORM");
2000 
2001  if (scaledHistogram && !comparisonUU) {
2002  Info("Chi2TestX", "NORM option should be used together with UU option. It is ignored");
2003  }
2004 
2005  // look at histo global bin content and effective entries
2006  Stat_t s[kNstat];
2007  GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
2008  Double_t sumBinContent1 = s[0];
2009  Double_t effEntries1 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
2010 
2011  h2->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
2012  Double_t sumBinContent2 = s[0];
2013  Double_t effEntries2 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
2014 
2015  if (!comparisonUU && !comparisonUW && !comparisonWW ) {
2016  // deduce automatically from type of histogram
2017  if (TMath::Abs(sumBinContent1 - effEntries1) < 1) {
2018  if ( TMath::Abs(sumBinContent2 - effEntries2) < 1) comparisonUU = true;
2019  else comparisonUW = true;
2020  }
2021  else comparisonWW = true;
2022  }
2023  // check unweighted histogram
2024  if (comparisonUW) {
2025  if (TMath::Abs(sumBinContent1 - effEntries1) >= 1) {
2026  Warning("Chi2TestX","First histogram is not unweighted and option UW has been requested");
2027  }
2028  }
2029  if ( (!scaledHistogram && comparisonUU) ) {
2030  if ( ( TMath::Abs(sumBinContent1 - effEntries1) >= 1) || (TMath::Abs(sumBinContent2 - effEntries2) >= 1) ) {
2031  Warning("Chi2TestX","Both histograms are not unweighted and option UU has been requested");
2032  }
2033  }
2034 
2035 
2036  //get number of events in histogram
2037  if (comparisonUU && scaledHistogram) {
2038  for (Int_t i = i_start; i <= i_end; ++i) {
2039  for (Int_t j = j_start; j <= j_end; ++j) {
2040  for (Int_t k = k_start; k <= k_end; ++k) {
2041 
2042  Int_t bin = GetBin(i, j, k);
2043 
2044  Double_t cnt1 = RetrieveBinContent(bin);
2045  Double_t cnt2 = h2->RetrieveBinContent(bin);
2046  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2047  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2048 
2049  if (e1sq > 0.0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2050  else cnt1 = 0.0;
2051 
2052  if (e2sq > 0.0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2053  else cnt2 = 0.0;
2054 
2055  // sum contents
2056  sum1 += cnt1;
2057  sum2 += cnt2;
2058  sumw1 += e1sq;
2059  sumw2 += e2sq;
2060  }
2061  }
2062  }
2063  if (sumw1 <= 0.0 || sumw2 <= 0.0) {
2064  Error("Chi2TestX", "Cannot use option NORM when one histogram has all zero errors");
2065  return 0.0;
2066  }
2067 
2068  } else {
2069  for (Int_t i = i_start; i <= i_end; ++i) {
2070  for (Int_t j = j_start; j <= j_end; ++j) {
2071  for (Int_t k = k_start; k <= k_end; ++k) {
2072 
2073  Int_t bin = GetBin(i, j, k);
2074 
2075  sum1 += RetrieveBinContent(bin);
2076  sum2 += h2->RetrieveBinContent(bin);
2077 
2078  if ( comparisonWW ) sumw1 += GetBinErrorSqUnchecked(bin);
2079  if ( comparisonUW || comparisonWW ) sumw2 += h2->GetBinErrorSqUnchecked(bin);
2080  }
2081  }
2082  }
2083  }
2084  //checks that the histograms are not empty
2085  if (sum1 == 0.0 || sum2 == 0.0) {
2086  Error("Chi2TestX","one histogram is empty");
2087  return 0.0;
2088  }
2089 
2090  if ( comparisonWW && ( sumw1 <= 0.0 && sumw2 <= 0.0 ) ){
2091  Error("Chi2TestX","Hist1 and Hist2 have both all zero errors\n");
2092  return 0.0;
2093  }
2094 
2095  //THE TEST
2096  Int_t m = 0, n = 0;
2097 
2098  //Experiment - experiment comparison
2099  if (comparisonUU) {
2100  Double_t sum = sum1 + sum2;
2101  for (Int_t i = i_start; i <= i_end; ++i) {
2102  for (Int_t j = j_start; j <= j_end; ++j) {
2103  for (Int_t k = k_start; k <= k_end; ++k) {
2104 
2105  Int_t bin = GetBin(i, j, k);
2106 
2107  Double_t cnt1 = RetrieveBinContent(bin);
2108  Double_t cnt2 = h2->RetrieveBinContent(bin);
2109 
2110  if (scaledHistogram) {
2111  // scale bin value to effective bin entries
2112  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2113  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2114 
2115  if (e1sq > 0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2116  else cnt1 = 0;
2117 
2118  if (e2sq > 0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2119  else cnt2 = 0;
2120  }
2121 
2122  if (Int_t(cnt1) == 0 && Int_t(cnt2) == 0) --ndf; // no data means one degree of freedom less
2123  else {
2124 
2125  Double_t cntsum = cnt1 + cnt2;
2126  Double_t nexp1 = cntsum * sum1 / sum;
2127  //Double_t nexp2 = binsum*sum2/sum;
2128 
2129  if (res) res[i - i_start] = (cnt1 - nexp1) / TMath::Sqrt(nexp1);
2130 
2131  if (cnt1 < 1) ++m;
2132  if (cnt2 < 1) ++n;
2133 
2134  //Habermann correction for residuals
2135  Double_t correc = (1. - sum1 / sum) * (1. - cntsum / sum);
2136  if (res) res[i - i_start] /= TMath::Sqrt(correc);
2137 
2138  Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2139  chi2 += delta * delta / cntsum;
2140  }
2141  }
2142  }
2143  }
2144  chi2 /= sum1 * sum2;
2145 
2146  // flag error only when of the two histogram is zero
2147  if (m) {
2148  igood += 1;
2149  Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2150  }
2151  if (n) {
2152  igood += 2;
2153  Info("Chi2TestX","There is a bin in h2 with less than 1 event.\n");
2154  }
2155 
2156  Double_t prob = TMath::Prob(chi2,ndf);
2157  return prob;
2158 
2159  }
2160 
2161  // unweighted - weighted comparison
2162  // case of error = 0 and content not zero is treated without problems by excluding second chi2 sum
2163  // and can be considered as a data-theory comparison
2164  if ( comparisonUW ) {
2165  for (Int_t i = i_start; i <= i_end; ++i) {
2166  for (Int_t j = j_start; j <= j_end; ++j) {
2167  for (Int_t k = k_start; k <= k_end; ++k) {
2168 
2169  Int_t bin = GetBin(i, j, k);
2170 
2171  Double_t cnt1 = RetrieveBinContent(bin);
2172  Double_t cnt2 = h2->RetrieveBinContent(bin);
2173  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2174 
2175  // case both histogram have zero bin contents
2176  if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2177  --ndf; //no data means one degree of freedom less
2178  continue;
2179  }
2180 
2181  // case weighted histogram has zero bin content and error
2182  if (cnt2 * cnt2 == 0 && e2sq == 0) {
2183  if (sumw2 > 0) {
2184  // use as approximated error as 1 scaled by a scaling ratio
2185  // estimated from the total sum weight and sum weight squared
2186  e2sq = sumw2 / sum2;
2187  }
2188  else {
2189  // return error because infinite discrepancy here:
2190  // bin1 != 0 and bin2 =0 in a histogram with all errors zero
2191  Error("Chi2TestX","Hist2 has in bin (%d,%d,%d) zero content and zero errors\n", i, j, k);
2192  chi2 = 0; return 0;
2193  }
2194  }
2195 
2196  if (cnt1 < 1) m++;
2197  if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2198 
2199  Double_t var1 = sum2 * cnt2 - sum1 * e2sq;
2200  Double_t var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2201 
2202  // if cnt1 is zero and cnt2 = 1 and sum1 = sum2 var1 = 0 && var2 == 0
2203  // approximate by incrementing cnt1
2204  // LM (this need to be fixed for numerical errors)
2205  while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2206  sum1++;
2207  cnt1++;
2208  var1 = sum2 * cnt2 - sum1 * e2sq;
2209  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2210  }
2211  var2 = TMath::Sqrt(var2);
2212 
2213  while (var1 + var2 == 0) {
2214  sum1++;
2215  cnt1++;
2216  var1 = sum2 * cnt2 - sum1 * e2sq;
2217  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2218  while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2219  sum1++;
2220  cnt1++;
2221  var1 = sum2 * cnt2 - sum1 * e2sq;
2222  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2223  }
2224  var2 = TMath::Sqrt(var2);
2225  }
2226 
2227  Double_t probb = (var1 + var2) / (2. * sum2 * sum2);
2228 
2229  Double_t nexp1 = probb * sum1;
2230  Double_t nexp2 = probb * sum2;
2231 
2232  Double_t delta1 = cnt1 - nexp1;
2233  Double_t delta2 = cnt2 - nexp2;
2234 
2235  chi2 += delta1 * delta1 / nexp1;
2236 
2237  if (e2sq > 0) {
2238  chi2 += delta2 * delta2 / e2sq;
2239  }
2240 
2241  if (res) {
2242  if (e2sq > 0) {
2243  Double_t temp1 = sum2 * e2sq / var2;
2244  Double_t temp2 = 1.0 + (sum1 * e2sq - sum2 * cnt2) / var2;
2245  temp2 = temp1 * temp1 * sum1 * probb * (1.0 - probb) + temp2 * temp2 * e2sq / 4.0;
2246  // invert sign here
2247  res[i - i_start] = - delta2 / TMath::Sqrt(temp2);
2248  }
2249  else
2250  res[i - i_start] = delta1 / TMath::Sqrt(nexp1);
2251  }
2252  }
2253  }
2254  }
2255 
2256  if (m) {
2257  igood += 1;
2258  Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2259  }
2260  if (n) {
2261  igood += 2;
2262  Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2263  }
2264 
2265  Double_t prob = TMath::Prob(chi2, ndf);
2266 
2267  return prob;
2268  }
2269 
2270  // weighted - weighted comparison
2271  if (comparisonWW) {
2272  for (Int_t i = i_start; i <= i_end; ++i) {
2273  for (Int_t j = j_start; j <= j_end; ++j) {
2274  for (Int_t k = k_start; k <= k_end; ++k) {
2275 
2276  Int_t bin = GetBin(i, j, k);
2277  Double_t cnt1 = RetrieveBinContent(bin);
2278  Double_t cnt2 = h2->RetrieveBinContent(bin);
2279  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2280  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2281 
2282  // case both histogram have zero bin contents
2283  // (use square of content to avoid numerical errors)
2284  if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2285  --ndf; //no data means one degree of freedom less
2286  continue;
2287  }
2288 
2289  if (e1sq == 0 && e2sq == 0) {
2290  // cannot treat case of booth histogram have zero zero errors
2291  Error("Chi2TestX","h1 and h2 both have bin %d,%d,%d with all zero errors\n", i,j,k);
2292  chi2 = 0; return 0;
2293  }
2294 
2295  Double_t sigma = sum1 * sum1 * e2sq + sum2 * sum2 * e1sq;
2296  Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2297  chi2 += delta * delta / sigma;
2298 
2299  if (res) {
2300  Double_t temp = cnt1 * sum1 * e2sq + cnt2 * sum2 * e1sq;
2301  Double_t probb = temp / sigma;
2302  Double_t z = 0;
2303  if (e1sq > e2sq) {
2304  Double_t d1 = cnt1 - sum1 * probb;
2305  Double_t s1 = e1sq * ( 1. - e2sq * sum1 * sum1 / sigma );
2306  z = d1 / TMath::Sqrt(s1);
2307  }
2308  else {
2309  Double_t d2 = cnt2 - sum2 * probb;
2310  Double_t s2 = e2sq * ( 1. - e1sq * sum2 * sum2 / sigma );
2311  z = -d2 / TMath::Sqrt(s2);
2312  }
2313  res[i - i_start] = z;
2314  }
2315 
2316  if (e1sq > 0 && cnt1 * cnt1 / e1sq < 10) m++;
2317  if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2318  }
2319  }
2320  }
2321  if (m) {
2322  igood += 1;
2323  Info("Chi2TestX","There is a bin in h1 with less than 10 effective events.\n");
2324  }
2325  if (n) {
2326  igood += 2;
2327  Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2328  }
2329  Double_t prob = TMath::Prob(chi2, ndf);
2330  return prob;
2331  }
2332  return 0;
2333 }
2334 ////////////////////////////////////////////////////////////////////////////////
2335 /// Compute and return the chisquare of this histogram with respect to a function
2336 /// The chisquare is computed by weighting each histogram point by the bin error
2337 /// By default the full range of the histogram is used.
2338 /// Use option "R" for restricting the chisquare calculation to the given range of the function
2339 
2340 Double_t TH1::Chisquare(TF1 * func, Option_t *option) const
2341 {
2342  if (!func) {
2343  Error("Chisquare","Function pointer is Null - return -1");
2344  return -1;
2345  }
2346 
2347  TString opt(option); opt.ToUpper();
2348  bool useRange = opt.Contains("R");
2349 
2350  return ROOT::Fit::Chisquare(*this, *func, useRange);
2351 }
2352 
2353 ////////////////////////////////////////////////////////////////////////////////
2354 /// Remove all the content from the underflow and overflow bins, without changing the number of entries
2355 /// After calling this method, every undeflow and overflow bins will have content 0.0
2356 /// The Sumw2 is also cleared, since there is no more content in the bins
2357 
2359 {
2360  for (Int_t bin = 0; bin < fNcells; ++bin)
2361  if (IsBinUnderflow(bin) || IsBinOverflow(bin)) {
2362  UpdateBinContent(bin, 0.0);
2363  if (fSumw2.fN) fSumw2.fArray[bin] = 0.0;
2364  }
2365 }
2366 
2367 ////////////////////////////////////////////////////////////////////////////////
2368 /// Compute integral (cumulative sum of bins)
2369 /// The result stored in fIntegral is used by the GetRandom functions.
2370 /// This function is automatically called by GetRandom when the fIntegral
2371 /// array does not exist or when the number of entries in the histogram
2372 /// has changed since the previous call to GetRandom.
2373 /// The resulting integral is normalized to 1
2374 /// If the routine is called with the onlyPositive flag set an error will
2375 /// be produced in case of negative bin content and a NaN value returned
2376 
2377 Double_t TH1::ComputeIntegral(Bool_t onlyPositive)
2378 {
2380 
2381  // delete previously computed integral (if any)
2382  if (fIntegral) delete [] fIntegral;
2383 
2384  // - Allocate space to store the integral and compute integral
2385  Int_t nbinsx = GetNbinsX();
2386  Int_t nbinsy = GetNbinsY();
2387  Int_t nbinsz = GetNbinsZ();
2388  Int_t nbins = nbinsx * nbinsy * nbinsz;
2389 
2390  fIntegral = new Double_t[nbins + 2];
2391  Int_t ibin = 0; fIntegral[ibin] = 0;
2392 
2393  for (Int_t binz=1; binz <= nbinsz; ++binz) {
2394  for (Int_t biny=1; biny <= nbinsy; ++biny) {
2395  for (Int_t binx=1; binx <= nbinsx; ++binx) {
2396  ++ibin;
2397  Double_t y = RetrieveBinContent(GetBin(binx, biny, binz));
2398  if (onlyPositive && y < 0) {
2399  Error("ComputeIntegral","Bin content is negative - return a NaN value");
2401  break;
2402  }
2403  fIntegral[ibin] = fIntegral[ibin - 1] + y;
2404  }
2405  }
2406  }
2407 
2408  // - Normalize integral to 1
2409  if (fIntegral[nbins] == 0 ) {
2410  Error("ComputeIntegral", "Integral = zero"); return 0;
2411  }
2412  for (Int_t bin=1; bin <= nbins; ++bin) fIntegral[bin] /= fIntegral[nbins];
2413  fIntegral[nbins+1] = fEntries;
2414  return fIntegral[nbins];
2415 }
2416 
2417 
2418 ////////////////////////////////////////////////////////////////////////////////
2419 /// Return a pointer to the array of bins integral.
2420 /// if the pointer fIntegral is null, TH1::ComputeIntegral is called
2421 /// The array dimension is the number of bins in the histograms
2422 /// including underflow and overflow (fNCells)
2423 /// the last value integral[fNCells] is set to the number of entries of
2424 /// the histogram
2425 
2427 {
2429  return fIntegral;
2430 }
2431 
2432 
2433 ////////////////////////////////////////////////////////////////////////////////
2434 /// Return a pointer to an histogram containing the cumulative The
2435 /// cumulative can be computed both in the forward (default) or backward
2436 /// direction; the name of the new histogram is constructed from
2437 /// the name of this histogram with the suffix suffix appended.
2438 ///
2439 /// The cumulative distribution is formed by filling each bin of the
2440 /// resulting histogram with the sum of that bin and all previous
2441 /// (forward == kTRUE) or following (forward = kFALSE) bins.
2442 ///
2443 /// note: while cumulative distributions make sense in one dimension, you
2444 /// may not be getting what you expect in more than 1D because the concept
2445 /// of a cumulative distribution is much trickier to define; make sure you
2446 /// understand the order of summation before you use this method with
2447 /// histograms of dimension >= 2.
2448 
2449 TH1 *TH1::GetCumulative(Bool_t forward, const char* suffix) const
2450 {
2451  const Int_t nbinsx = GetNbinsX();
2452  const Int_t nbinsy = GetNbinsY();
2453  const Int_t nbinsz = GetNbinsZ();
2454  TH1* hintegrated = (TH1*) Clone(fName + suffix);
2455  hintegrated->Reset();
2456  if (forward) { // Forward computation
2457  Double_t sum = 0.;
2458  for (Int_t binz = 1; binz <= nbinsz; ++binz) {
2459  for (Int_t biny = 1; biny <= nbinsy; ++biny) {
2460  for (Int_t binx = 1; binx <= nbinsx; ++binx) {
2461  const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2462  sum += GetBinContent(bin);
2463  hintegrated->SetBinContent(bin, sum);
2464  }
2465  }
2466  }
2467  } else { // Backward computation
2468  Double_t sum = 0.;
2469  for (Int_t binz = nbinsz; binz >= 1; --binz) {
2470  for (Int_t biny = nbinsy; biny >= 1; --biny) {
2471  for (Int_t binx = nbinsx; binx >= 1; --binx) {
2472  const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2473  sum += GetBinContent(bin);
2474  hintegrated->SetBinContent(bin, sum);
2475  }
2476  }
2477  }
2478  }
2479  return hintegrated;
2480 }
2481 
2482 ////////////////////////////////////////////////////////////////////////////////
2483 /// Copy this histogram structure to newth1.
2484 ///
2485 /// Note that this function does not copy the list of associated functions.
2486 /// Use TObject::Clone to make a full copy of an histogram.
2487 ///
2488 /// Note also that the histogram it will be created in gDirectory (if AddDirectoryStatus()=true)
2489 /// or will not be added to any directory if AddDirectoryStatus()=false
2490 /// independently of the current directory stored in the original histogram
2491 
2492 void TH1::Copy(TObject &obj) const
2493 {
2494  if (((TH1&)obj).fDirectory) {
2495  // We are likely to change the hash value of this object
2496  // with TNamed::Copy, to keep things correct, we need to
2497  // clean up its existing entries.
2498  ((TH1&)obj).fDirectory->Remove(&obj);
2499  ((TH1&)obj).fDirectory = 0;
2500  }
2501  TNamed::Copy(obj);
2502  ((TH1&)obj).fDimension = fDimension;
2503  ((TH1&)obj).fNormFactor= fNormFactor;
2504  ((TH1&)obj).fNcells = fNcells;
2505  ((TH1&)obj).fBarOffset = fBarOffset;
2506  ((TH1&)obj).fBarWidth = fBarWidth;
2507  ((TH1&)obj).fOption = fOption;
2508  ((TH1&)obj).fBinStatErrOpt = fBinStatErrOpt;
2509  ((TH1&)obj).fBufferSize= fBufferSize;
2510  // copy the Buffer
2511  // delete first a previously existing buffer
2512  if (((TH1&)obj).fBuffer != 0) {
2513  delete [] ((TH1&)obj).fBuffer;
2514  ((TH1&)obj).fBuffer = 0;
2515  }
2516  if (fBuffer) {
2517  Double_t *buf = new Double_t[fBufferSize];
2518  for (Int_t i=0;i<fBufferSize;i++) buf[i] = fBuffer[i];
2519  // obj.fBuffer has been deleted before
2520  ((TH1&)obj).fBuffer = buf;
2521  }
2522 
2523 
2524  TArray* a = dynamic_cast<TArray*>(&obj);
2525  if (a) a->Set(fNcells);
2526  for (Int_t i = 0; i < fNcells; i++) ((TH1&)obj).UpdateBinContent(i, RetrieveBinContent(i));
2527 
2528  ((TH1&)obj).fEntries = fEntries;
2529 
2530  // which will call BufferEmpty(0) and set fBuffer[0] to a Maybe one should call
2531  // assignment operator on the TArrayD
2532 
2533  ((TH1&)obj).fTsumw = fTsumw;
2534  ((TH1&)obj).fTsumw2 = fTsumw2;
2535  ((TH1&)obj).fTsumwx = fTsumwx;
2536  ((TH1&)obj).fTsumwx2 = fTsumwx2;
2537  ((TH1&)obj).fMaximum = fMaximum;
2538  ((TH1&)obj).fMinimum = fMinimum;
2539 
2540  TAttLine::Copy(((TH1&)obj));
2541  TAttFill::Copy(((TH1&)obj));
2542  TAttMarker::Copy(((TH1&)obj));
2543  fXaxis.Copy(((TH1&)obj).fXaxis);
2544  fYaxis.Copy(((TH1&)obj).fYaxis);
2545  fZaxis.Copy(((TH1&)obj).fZaxis);
2546  ((TH1&)obj).fXaxis.SetParent(&obj);
2547  ((TH1&)obj).fYaxis.SetParent(&obj);
2548  ((TH1&)obj).fZaxis.SetParent(&obj);
2549  fContour.Copy(((TH1&)obj).fContour);
2550  fSumw2.Copy(((TH1&)obj).fSumw2);
2551  // fFunctions->Copy(((TH1&)obj).fFunctions);
2552  // when copying an histogram if the AddDirectoryStatus() is true it
2553  // will be added to gDirectory independently of the fDirectory stored.
2554  // and if the AddDirectoryStatus() is false it will not be added to
2555  // any directory (fDirectory = 0)
2556  if (fgAddDirectory && gDirectory) {
2557  gDirectory->Append(&obj);
2558  ((TH1&)obj).fDirectory = gDirectory;
2559  } else
2560  ((TH1&)obj).fDirectory = 0;
2561 
2562 }
2563 
2564 
2565 ////////////////////////////////////////////////////////////////////////////////
2566 /// Make a complete copy of the underlying object. If 'newname' is set,
2567 /// the copy's name will be set to that name.
2568 
2569 TObject* TH1::Clone(const char* newname) const
2570 {
2571  TH1* obj = (TH1*)IsA()->GetNew()(0);
2572  Copy(*obj);
2573 
2574  //Now handle the parts that Copy doesn't do
2575  if(fFunctions) {
2576  if (obj->fFunctions) delete obj->fFunctions;
2577  obj->fFunctions = (TList*)fFunctions->Clone();
2578  }
2579  if(newname && strlen(newname) ) {
2580  obj->SetName(newname);
2581  }
2582  return obj;
2583 }
2584 
2585 ////////////////////////////////////////////////////////////////////////////////
2586 /// Perform the automatic addition of the histogram to the given directory
2587 ///
2588 /// Note this function is called in place when the semantic requires
2589 /// this object to be added to a directory (I.e. when being read from
2590 /// a TKey or being Cloned)
2591 ///
2592 
2594 {
2596  if (addStatus) {
2597  SetDirectory(dir);
2598  if (dir) {
2600  }
2601  }
2602 }
2603 
2604 
2605 ////////////////////////////////////////////////////////////////////////////////
2606 /// Compute distance from point px,py to a line.
2607 ///
2608 /// Compute the closest distance of approach from point px,py to elements
2609 /// of an histogram.
2610 /// The distance is computed in pixels units.
2611 ///
2612 /// Algorithm:
2613 /// Currently, this simple model computes the distance from the mouse
2614 /// to the histogram contour only.
2615 
2617 {
2618  if (!fPainter) return 9999;
2619  return fPainter->DistancetoPrimitive(px,py);
2620 }
2621 
2622 
2623 ////////////////////////////////////////////////////////////////////////////////
2624 /// Performs the operation: this = this/(c1*f1)
2625 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2626 ///
2627 /// Only bins inside the function range are recomputed.
2628 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2629 /// you should call Sumw2 before making this operation.
2630 /// This is particularly important if you fit the histogram after TH1::Divide
2631 ///
2632 /// The function return kFALSE if the divide operation failed
2633 
2635 {
2636  if (!f1) {
2637  Error("Add","Attempt to divide by a non-existing function");
2638  return kFALSE;
2639  }
2640 
2641  // delete buffer if it is there since it will become invalid
2642  if (fBuffer) BufferEmpty(1);
2643 
2644  Int_t nx = GetNbinsX() + 2; // normal bins + uf / of
2645  Int_t ny = GetNbinsY() + 2;
2646  Int_t nz = GetNbinsZ() + 2;
2647  if (fDimension < 2) ny = 1;
2648  if (fDimension < 3) nz = 1;
2649 
2650 
2651  SetMinimum();
2652  SetMaximum();
2653 
2654  // - Loop on bins (including underflows/overflows)
2655  Int_t bin, binx, biny, binz;
2656  Double_t cu, w;
2657  Double_t xx[3];
2658  Double_t *params = 0;
2659  f1->InitArgs(xx,params);
2660  for (binz = 0; binz < nz; ++binz) {
2661  xx[2] = fZaxis.GetBinCenter(binz);
2662  for (biny = 0; biny < ny; ++biny) {
2663  xx[1] = fYaxis.GetBinCenter(biny);
2664  for (binx = 0; binx < nx; ++binx) {
2665  xx[0] = fXaxis.GetBinCenter(binx);
2666  if (!f1->IsInside(xx)) continue;
2668  bin = binx + nx * (biny + ny * binz);
2669  cu = c1 * f1->EvalPar(xx);
2670  if (TF1::RejectedPoint()) continue;
2671  if (cu) w = RetrieveBinContent(bin) / cu;
2672  else w = 0;
2673  UpdateBinContent(bin, w);
2674  if (fSumw2.fN) {
2675  if (cu != 0) fSumw2.fArray[bin] = GetBinErrorSqUnchecked(bin) / (cu * cu);
2676  else fSumw2.fArray[bin] = 0;
2677  }
2678  }
2679  }
2680  }
2681  ResetStats();
2682  return kTRUE;
2683 }
2684 
2685 
2686 ////////////////////////////////////////////////////////////////////////////////
2687 /// Divide this histogram by h1.
2688 ///
2689 /// this = this/h1
2690 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2691 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
2692 /// if not already set.
2693 /// The resulting errors are calculated assuming uncorrelated histograms.
2694 /// See the other TH1::Divide that gives the possibility to optionally
2695 /// compute binomial errors.
2696 ///
2697 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2698 /// you should call Sumw2 before making this operation.
2699 /// This is particularly important if you fit the histogram after TH1::Scale
2700 ///
2701 /// The function return kFALSE if the divide operation failed
2702 
2703 Bool_t TH1::Divide(const TH1 *h1)
2704 {
2705  if (!h1) {
2706  Error("Divide", "Input histogram passed does not exist (NULL).");
2707  return kFALSE;
2708  }
2709 
2710  // delete buffer if it is there since it will become invalid
2711  if (fBuffer) BufferEmpty(1);
2712 
2713  try {
2714  CheckConsistency(this,h1);
2715  } catch(DifferentNumberOfBins&) {
2716  Error("Divide","Cannot divide histograms with different number of bins");
2717  return kFALSE;
2718  } catch(DifferentAxisLimits&) {
2719  Warning("Divide","Dividing histograms with different axis limits");
2720  } catch(DifferentBinLimits&) {
2721  Warning("Divide","Dividing histograms with different bin limits");
2722  } catch(DifferentLabels&) {
2723  Warning("Divide","Dividing histograms with different labels");
2724  }
2725 
2726  // Create Sumw2 if h1 has Sumw2 set
2727  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
2728 
2729  // - Loop on bins (including underflows/overflows)
2730  for (Int_t i = 0; i < fNcells; ++i) {
2731  Double_t c0 = RetrieveBinContent(i);
2732  Double_t c1 = h1->RetrieveBinContent(i);
2733  if (c1) UpdateBinContent(i, c0 / c1);
2734  else UpdateBinContent(i, 0);
2735 
2736  if(fSumw2.fN) {
2737  if (c1 == 0) { fSumw2.fArray[i] = 0; continue; }
2738  Double_t c1sq = c1 * c1;
2739  fSumw2.fArray[i] = (GetBinErrorSqUnchecked(i) * c1sq + h1->GetBinErrorSqUnchecked(i) * c0 * c0) / (c1sq * c1sq);
2740  }
2741  }
2742  ResetStats();
2743  return kTRUE;
2744 }
2745 
2746 
2747 ////////////////////////////////////////////////////////////////////////////////
2748 /// Replace contents of this histogram by the division of h1 by h2.
2749 ///
2750 /// this = c1*h1/(c2*h2)
2751 ///
2752 /// If errors are defined (see TH1::Sumw2), errors are also recalculated
2753 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
2754 /// if not already set.
2755 /// The resulting errors are calculated assuming uncorrelated histograms.
2756 /// However, if option ="B" is specified, Binomial errors are computed.
2757 /// In this case c1 and c2 do not make real sense and they are ignored.
2758 ///
2759 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2760 /// you should call Sumw2 before making this operation.
2761 /// This is particularly important if you fit the histogram after TH1::Divide
2762 ///
2763 /// Please note also that in the binomial case errors are calculated using standard
2764 /// binomial statistics, which means when b1 = b2, the error is zero.
2765 /// If you prefer to have efficiency errors not going to zero when the efficiency is 1, you must
2766 /// use the function TGraphAsymmErrors::BayesDivide, which will return an asymmetric and non-zero lower
2767 /// error for the case b1=b2.
2768 ///
2769 /// The function return kFALSE if the divide operation failed
2770 
2771 Bool_t TH1::Divide(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2, Option_t *option)
2772 {
2774  TString opt = option;
2775  opt.ToLower();
2776  Bool_t binomial = kFALSE;
2777  if (opt.Contains("b")) binomial = kTRUE;
2778  if (!h1 || !h2) {
2779  Error("Divide", "At least one of the input histograms passed does not exist (NULL).");
2780  return kFALSE;
2781  }
2782 
2783  // delete buffer if it is there since it will become invalid
2784  if (fBuffer) BufferEmpty(1);
2785 
2786  try {
2787  CheckConsistency(h1,h2);
2788  CheckConsistency(this,h1);
2789  } catch(DifferentNumberOfBins&) {
2790  Error("Divide","Cannot divide histograms with different number of bins");
2791  return kFALSE;
2792  } catch(DifferentAxisLimits&) {
2793  Warning("Divide","Dividing histograms with different axis limits");
2794  } catch(DifferentBinLimits&) {
2795  Warning("Divide","Dividing histograms with different bin limits");
2796  } catch(DifferentLabels&) {
2797  Warning("Divide","Dividing histograms with different labels");
2798  }
2799 
2800 
2801  if (!c2) {
2802  Error("Divide","Coefficient of dividing histogram cannot be zero");
2803  return kFALSE;
2804  }
2805 
2806  // Create Sumw2 if h1 or h2 have Sumw2 set
2807  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
2808 
2809  SetMinimum();
2810  SetMaximum();
2811 
2812  // - Loop on bins (including underflows/overflows)
2813  for (Int_t i = 0; i < fNcells; ++i) {
2814  Double_t b1 = h1->RetrieveBinContent(i);
2815  Double_t b2 = h2->RetrieveBinContent(i);
2816  if (b2) UpdateBinContent(i, c1 * b1 / (c2 * b2));
2817  else UpdateBinContent(i, 0);
2818 
2819  if (fSumw2.fN) {
2820  if (b2 == 0) { fSumw2.fArray[i] = 0; continue; }
2821  Double_t b1sq = b1 * b1; Double_t b2sq = b2 * b2;
2822  Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
2823  Double_t e1sq = h1->GetBinErrorSqUnchecked(i);
2824  Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
2825  if (binomial) {
2826  if (b1 != b2) {
2827  // in the case of binomial statistics c1 and c2 must be 1 otherwise it does not make sense
2828  // c1 and c2 are ignored
2829  //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/(c2*b2));//this is the formula in Hbook/Hoper1
2830  //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/b2); // old formula from G. Flucke
2831  // formula which works also for weighted histogram (see http://root.cern.ch/phpBB2/viewtopic.php?t=3753 )
2832  fSumw2.fArray[i] = TMath::Abs( ( (1. - 2.* b1 / b2) * e1sq + b1sq * e2sq / b2sq ) / b2sq );
2833  } else {
2834  //in case b1=b2 error is zero
2835  //use TGraphAsymmErrors::BayesDivide for getting the asymmetric error not equal to zero
2836  fSumw2.fArray[i] = 0;
2837  }
2838  } else {
2839  fSumw2.fArray[i] = c1sq * c2sq * (e1sq * b2sq + e2sq * b1sq) / (c2sq * c2sq * b2sq * b2sq);
2840  }
2841  }
2842  }
2843  ResetStats();
2844  if (binomial)
2845  // in case of binomial division use denominator for number of entries
2846  SetEntries ( h2->GetEntries() );
2847 
2848  return kTRUE;
2849 }
2850 
2851 
2852 ////////////////////////////////////////////////////////////////////////////////
2853 /// Draw this histogram with options.
2854 ///
2855 /// Histograms are drawn via the THistPainter class. Each histogram has
2856 /// a pointer to its own painter (to be usable in a multithreaded program).
2857 /// The same histogram can be drawn with different options in different pads.
2858 /// When an histogram drawn in a pad is deleted, the histogram is
2859 /// automatically removed from the pad or pads where it was drawn.
2860 /// If an histogram is drawn in a pad, then filled again, the new status
2861 /// of the histogram will be automatically shown in the pad next time
2862 /// the pad is updated. One does not need to redraw the histogram.
2863 /// To draw the current version of an histogram in a pad, one can use
2864 /// h->DrawCopy();
2865 /// This makes a clone of the histogram. Once the clone is drawn, the original
2866 /// histogram may be modified or deleted without affecting the aspect of the
2867 /// clone.
2868 /// By default, TH1::Draw clears the current pad.
2869 ///
2870 /// One can use TH1::SetMaximum and TH1::SetMinimum to force a particular
2871 /// value for the maximum or the minimum scale on the plot.
2872 ///
2873 /// TH1::UseCurrentStyle can be used to change all histogram graphics
2874 /// attributes to correspond to the current selected style.
2875 /// This function must be called for each histogram.
2876 /// In case one reads and draws many histograms from a file, one can force
2877 /// the histograms to inherit automatically the current graphics style
2878 /// by calling before gROOT->ForceStyle();
2879 ///
2880 /// See the THistPainter class for a description of all the drawing options.
2881 
2882 void TH1::Draw(Option_t *option)
2883 {
2884  TString opt1 = option; opt1.ToLower();
2885  TString opt2 = option;
2886  Int_t index = opt1.Index("same");
2887 
2888  // Check if the string "same" is part of a TCutg name.
2889  if (index>=0) {
2890  Int_t indb = opt1.Index("[");
2891  if (indb>=0) {
2892  Int_t indk = opt1.Index("]");
2893  if (index>indb && index<indk) index = -1;
2894  }
2895  }
2896 
2897  // If there is no pad or an empty pad the the "same" is ignored.
2898  if (gPad) {
2899  if (!gPad->IsEditable()) gROOT->MakeDefCanvas();
2900  if (index>=0) {
2901  if (gPad->GetX1() == 0 && gPad->GetX2() == 1 &&
2902  gPad->GetY1() == 0 && gPad->GetY2() == 1 &&
2903  gPad->GetListOfPrimitives()->GetSize()==0) opt2.Remove(index,4);
2904  } else {
2905  //the following statement is necessary in case one attempts to draw
2906  //a temporary histogram already in the current pad
2907  if (TestBit(kCanDelete)) gPad->GetListOfPrimitives()->Remove(this);
2908  gPad->Clear();
2909  }
2910  } else {
2911  if (index>=0) opt2.Remove(index,4);
2912  }
2913 
2914  AppendPad(opt2.Data());
2915 }
2916 
2917 
2918 ////////////////////////////////////////////////////////////////////////////////
2919 /// Copy this histogram and Draw in the current pad.
2920 ///
2921 /// Once the histogram is drawn into the pad, any further modification
2922 /// using graphics input will be made on the copy of the histogram,
2923 /// and not to the original object.
2924 /// By default a postfix "_copy" is added to the histogram name. Pass an empty postfix in case
2925 /// you want to draw an histogram with the same name
2926 ///
2927 /// See Draw for the list of options
2928 
2929 TH1 *TH1::DrawCopy(Option_t *option, const char * name_postfix) const
2930 {
2931  TString opt = option;
2932  opt.ToLower();
2933  if (gPad && !opt.Contains("same")) gPad->Clear();
2934  TString newName = (name_postfix) ? TString::Format("%s%s",GetName(),name_postfix) : "";
2935  TH1 *newth1 = (TH1 *)Clone(newName);
2936  newth1->SetDirectory(0);
2937  newth1->SetBit(kCanDelete);
2938  newth1->AppendPad(option);
2939  return newth1;
2940 }
2941 
2942 
2943 ////////////////////////////////////////////////////////////////////////////////
2944 /// Draw a normalized copy of this histogram.
2945 ///
2946 /// A clone of this histogram is normalized to norm and drawn with option.
2947 /// A pointer to the normalized histogram is returned.
2948 /// The contents of the histogram copy are scaled such that the new
2949 /// sum of weights (excluding under and overflow) is equal to norm.
2950 /// Note that the returned normalized histogram is not added to the list
2951 /// of histograms in the current directory in memory.
2952 /// It is the user's responsability to delete this histogram.
2953 /// The kCanDelete bit is set for the returned object. If a pad containing
2954 /// this copy is cleared, the histogram will be automatically deleted.
2955 ///
2956 /// See Draw for the list of options
2957 
2958 TH1 *TH1::DrawNormalized(Option_t *option, Double_t norm) const
2959 {
2961  if (sum == 0) {
2962  Error("DrawNormalized","Sum of weights is null. Cannot normalize histogram: %s",GetName());
2963  return 0;
2964  }
2965  Bool_t addStatus = TH1::AddDirectoryStatus();
2967  TH1 *h = (TH1*)Clone();
2968  h->SetBit(kCanDelete);
2969  // in case of drawing with error options - scale correctly the error
2970  TString opt(option); opt.ToUpper();
2971  if (fSumw2.fN == 0) {
2972  h->Sumw2();
2973  // do not use in this case the "Error option " for drawing which is enabled by default since the normalized histogram has now errors
2974  if (opt.IsNull() || opt == "SAME") opt += "HIST";
2975  }
2976  h->Scale(norm/sum);
2977  if (TMath::Abs(fMaximum+1111) > 1e-3) h->SetMaximum(fMaximum*norm/sum);
2978  if (TMath::Abs(fMinimum+1111) > 1e-3) h->SetMinimum(fMinimum*norm/sum);
2979  h->Draw(opt);
2980  TH1::AddDirectory(addStatus);
2981  return h;
2982 }
2983 
2984 
2985 ////////////////////////////////////////////////////////////////////////////////
2986 /// Display a panel with all histogram drawing options.
2987 ///
2988 /// See class TDrawPanelHist for example
2989 
2990 void TH1::DrawPanel()
2991 {
2992  if (!fPainter) {Draw(); if (gPad) gPad->Update();}
2993  if (fPainter) fPainter->DrawPanel();
2994 }
2995 
2996 
2997 ////////////////////////////////////////////////////////////////////////////////
2998 /// Evaluate function f1 at the center of bins of this histogram.
2999 ///
3000 /// If option "R" is specified, the function is evaluated only
3001 /// for the bins included in the function range.
3002 /// If option "A" is specified, the value of the function is added to the
3003 /// existing bin contents
3004 /// If option "S" is specified, the value of the function is used to
3005 /// generate a value, distributed according to the Poisson
3006 /// distribution, with f1 as the mean.
3007 
3008 void TH1::Eval(TF1 *f1, Option_t *option)
3009 {
3011  Int_t range, stat, add;
3012  if (!f1) return;
3013 
3014  TString opt = option;
3015  opt.ToLower();
3016  if (opt.Contains("a")) add = 1;
3017  else add = 0;
3018  if (opt.Contains("s")) stat = 1;
3019  else stat = 0;
3020  if (opt.Contains("r")) range = 1;
3021  else range = 0;
3022 
3023  // delete buffer if it is there since it will become invalid
3024  if (fBuffer) BufferEmpty(1);
3025 
3026  Int_t nbinsx = fXaxis.GetNbins();
3027  Int_t nbinsy = fYaxis.GetNbins();
3028  Int_t nbinsz = fZaxis.GetNbins();
3029  if (!add) Reset();
3030 
3031  for (Int_t binz = 1; binz <= nbinsz; ++binz) {
3032  x[2] = fZaxis.GetBinCenter(binz);
3033  for (Int_t biny = 1; biny <= nbinsy; ++biny) {
3034  x[1] = fYaxis.GetBinCenter(biny);
3035  for (Int_t binx = 1; binx <= nbinsx; ++binx) {
3036  Int_t bin = GetBin(binx,biny,binz);
3037  x[0] = fXaxis.GetBinCenter(binx);
3038  if (range && !f1->IsInside(x)) continue;
3039  Double_t fu = f1->Eval(x[0], x[1], x[2]);
3040  if (stat) fu = gRandom->PoissonD(fu);
3041  AddBinContent(bin, fu);
3042  if (fSumw2.fN) fSumw2.fArray[bin] += TMath::Abs(fu);
3043  }
3044  }
3045  }
3046 }
3047 
3048 
3049 ////////////////////////////////////////////////////////////////////////////////
3050 /// Execute action corresponding to one event.
3051 ///
3052 /// This member function is called when a histogram is clicked with the locator
3053 ///
3054 /// If Left button clicked on the bin top value, then the content of this bin
3055 /// is modified according to the new position of the mouse when it is released.
3056 
3057 void TH1::ExecuteEvent(Int_t event, Int_t px, Int_t py)
3058 {
3059  if (fPainter) fPainter->ExecuteEvent(event, px, py);
3060 }
3061 
3062 
3063 ////////////////////////////////////////////////////////////////////////////////
3064 /// This function allows to do discrete Fourier transforms of TH1 and TH2.
3065 /// Available transform types and flags are described below.
3066 ///
3067 /// To extract more information about the transform, use the function
3068 /// TVirtualFFT::GetCurrentTransform() to get a pointer to the current
3069 /// transform object.
3070 ///
3071 /// \param[out] h_output histogram for the output. If a null pointer is passed, a new histogram is created
3072 /// and returned, otherwise, the provided histogram is used and should be big enough
3073 /// \param[in] option option parameters consists of 3 parts:
3074 /// - option on what to return
3075 /// - "RE" - returns a histogram of the real part of the output
3076 /// - "IM" - returns a histogram of the imaginary part of the output
3077 /// - "MAG"- returns a histogram of the magnitude of the output
3078 /// - "PH" - returns a histogram of the phase of the output
3079 /// - option of transform type
3080 /// - "R2C" - real to complex transforms - default
3081 /// - "R2HC" - real to halfcomplex (special format of storing output data,
3082 /// results the same as for R2C)
3083 /// - "DHT" - discrete Hartley transform
3084 /// real to real transforms (sine and cosine):
3085 /// - "R2R_0", "R2R_1", "R2R_2", "R2R_3" - discrete cosine transforms of types I-IV
3086 /// - "R2R_4", "R2R_5", "R2R_6", "R2R_7" - discrete sine transforms of types I-IV
3087 /// To specify the type of each dimension of a 2-dimensional real to real
3088 /// transform, use options of form "R2R_XX", for example, "R2R_02" for a transform,
3089 /// which is of type "R2R_0" in 1st dimension and "R2R_2" in the 2nd.
3090 /// - option of transform flag
3091 /// - "ES" (from "estimate") - no time in preparing the transform, but probably sub-optimal
3092 /// performance
3093 /// - "M" (from "measure") - some time spend in finding the optimal way to do the transform
3094 /// - "P" (from "patient") - more time spend in finding the optimal way to do the transform
3095 /// - "EX" (from "exhaustive") - the most optimal way is found
3096 /// This option should be chosen depending on how many transforms of the same size and
3097 /// type are going to be done. Planning is only done once, for the first transform of this
3098 /// size and type. Default is "ES".
3099 ///
3100 /// Examples of valid options: "Mag R2C M" "Re R2R_11" "Im R2C ES" "PH R2HC EX"
3101 
3102 TH1* TH1::FFT(TH1* h_output, Option_t *option)
3103 {
3105  Int_t ndim[3];
3106  ndim[0] = this->GetNbinsX();
3107  ndim[1] = this->GetNbinsY();
3108  ndim[2] = this->GetNbinsZ();
3109 
3110  TVirtualFFT *fft;
3111  TString opt = option;
3112  opt.ToUpper();
3113  if (!opt.Contains("2R")){
3114  if (!opt.Contains("2C") && !opt.Contains("2HC") && !opt.Contains("DHT")) {
3115  //no type specified, "R2C" by default
3116  opt.Append("R2C");
3117  }
3118  fft = TVirtualFFT::FFT(this->GetDimension(), ndim, opt.Data());
3119  }
3120  else {
3121  //find the kind of transform
3122  Int_t ind = opt.Index("R2R", 3);
3123  Int_t *kind = new Int_t[2];
3124  char t;
3125  t = opt[ind+4];
3126  kind[0] = atoi(&t);
3127  if (h_output->GetDimension()>1) {
3128  t = opt[ind+5];
3129  kind[1] = atoi(&t);
3130  }
3131  fft = TVirtualFFT::SineCosine(this->GetDimension(), ndim, kind, option);
3132  delete [] kind;
3133  }
3134 
3135  if (!fft) return 0;
3136  Int_t in=0;
3137  for (Int_t binx = 1; binx<=ndim[0]; binx++) {
3138  for (Int_t biny=1; biny<=ndim[1]; biny++) {
3139  for (Int_t binz=1; binz<=ndim[2]; binz++) {
3140  fft->SetPoint(in, this->GetBinContent(binx, biny, binz));
3141  in++;
3142  }
3143  }
3144  }
3145  fft->Transform();
3146  h_output = TransformHisto(fft, h_output, option);
3147  return h_output;
3148 }
3149 
3150 
3151 ////////////////////////////////////////////////////////////////////////////////
3152 /// Increment bin with abscissa X by 1.
3153 ///
3154 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3155 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3156 ///
3157 /// If the storage of the sum of squares of weights has been triggered,
3158 /// via the function Sumw2, then the sum of the squares of weights is incremented
3159 /// by 1 in the bin corresponding to x.
3160 ///
3161 /// The function returns the corresponding bin number which has its content incremented by 1
3162 
3164 {
3165  if (fBuffer) return BufferFill(x,1);
3166 
3167  Int_t bin;
3168  fEntries++;
3169  bin =fXaxis.FindBin(x);
3170  if (bin <0) return -1;
3171  AddBinContent(bin);
3172  if (fSumw2.fN) ++fSumw2.fArray[bin];
3173  if (bin == 0 || bin > fXaxis.GetNbins()) {
3174  if (!fgStatOverflows) return -1;
3175  }
3176  ++fTsumw;
3177  ++fTsumw2;
3178  fTsumwx += x;
3179  fTsumwx2 += x*x;
3180  return bin;
3181 }
3182 
3183 
3184 ////////////////////////////////////////////////////////////////////////////////
3185 /// Increment bin with abscissa X with a weight w.
3186 ///
3187 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3188 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3189 ///
3190 /// If the weight is not equal to 1, the storage of the sum of squares of
3191 /// weights is automatically triggered and the sum of the squares of weights is incremented
3192 /// by w^2 in the bin corresponding to x.
3193 ///
3194 /// The function returns the corresponding bin number which has its content incremented by w
3195 
3197 {
3199  if (fBuffer) return BufferFill(x,w);
3200 
3201  Int_t bin;
3202  fEntries++;
3203  bin =fXaxis.FindBin(x);
3204  if (bin <0) return -1;
3205  if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW) ) Sumw2(); // must be called before AddBinContent
3206  if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3207  AddBinContent(bin, w);
3208  if (bin == 0 || bin > fXaxis.GetNbins()) {
3209  if (!fgStatOverflows) return -1;
3210  }
3211  Double_t z= w;
3212  fTsumw += z;
3213  fTsumw2 += z*z;
3214  fTsumwx += z*x;
3215  fTsumwx2 += z*x*x;
3216  return bin;
3217 }
3218 
3219 
3220 ////////////////////////////////////////////////////////////////////////////////
3221 /// Increment bin with namex with a weight w
3222 ///
3223 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3224 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3225 ///
3226 /// If the weight is not equal to 1, the storage of the sum of squares of
3227 /// weights is automatically triggered and the sum of the squares of weights is incremented
3228 /// by w^2 in the bin corresponding to x.
3229 ///
3230 /// The function returns the corresponding bin number which has its content
3231 /// incremented by w
3232 
3233 Int_t TH1::Fill(const char *namex, Double_t w)
3234 {
3235  Int_t bin;
3236  fEntries++;
3237  bin =fXaxis.FindBin(namex);
3238  if (bin <0) return -1;
3239  if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3240  if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3241  AddBinContent(bin, w);
3242  if (bin == 0 || bin > fXaxis.GetNbins()) return -1;
3243  Double_t z= w;
3244  fTsumw += z;
3245  fTsumw2 += z*z;
3246  // this make sense if the histogram is not expanding (no axis can be extended)
3247  if (!CanExtendAllAxes()) {
3248  Double_t x = fXaxis.GetBinCenter(bin);
3249  fTsumwx += z*x;
3250  fTsumwx2 += z*x*x;
3251  }
3252  return bin;
3253 }
3254 
3255 
3256 ////////////////////////////////////////////////////////////////////////////////
3257 /// Fill this histogram with an array x and weights w.
3258 ///
3259 /// \param[in] ntimes number of entries in arrays x and w (array size must be ntimes*stride)
3260 /// \param[in] x array of values to be histogrammed
3261 /// \param[in[ w array of weighs
3262 /// \param[in] stride step size through arrays x and w
3263 ///
3264 /// If the weight is not equal to 1, the storage of the sum of squares of
3265 /// weights is automatically triggered and the sum of the squares of weights is incremented
3266 /// y w^2 in the bin corresponding to x.
3267 /// if w is NULL each entry is assumed a weight=1
3268 
3269 void TH1::FillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3270 {
3271  //If a buffer is activated, fill buffer
3272  if (fBuffer) {
3273  ntimes *= stride;
3274  Int_t i = 0;
3275  for (i=0;i<ntimes;i+=stride) {
3276  if (!fBuffer) break; // buffer can be deleted in BufferFill when is empty
3277  if (w) BufferFill(x[i],w[i]);
3278  else BufferFill(x[i], 1.);
3279  }
3280  // fill the remaining entries if the buffer has been deleted
3281  if (i < ntimes && fBuffer==0)
3282  DoFillN((ntimes-i)/stride,&x[i],&w[i],stride);
3283  return;
3284  }
3285  // call internal method
3286  DoFillN(ntimes, x, w, stride);
3287 }
3288 
3289 ////////////////////////////////////////////////////////////////////////////////
3290 /// internal method to fill histogram content from a vector
3291 /// called directly by TH1::BufferEmpty
3292 
3293 void TH1::DoFillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3294 {
3295  Int_t bin,i;
3296 
3297  fEntries += ntimes;
3298  Double_t ww = 1;
3299  Int_t nbins = fXaxis.GetNbins();
3300  ntimes *= stride;
3301  for (i=0;i<ntimes;i+=stride) {
3302  bin =fXaxis.FindBin(x[i]);
3303  if (bin <0) continue;
3304  if (w) ww = w[i];
3305  if (!fSumw2.fN && ww != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3306  if (fSumw2.fN) fSumw2.fArray[bin] += ww*ww;
3307  AddBinContent(bin, ww);
3308  if (bin == 0 || bin > nbins) {
3309  if (!fgStatOverflows) continue;
3310  }
3311  Double_t z= ww;
3312  fTsumw += z;
3313  fTsumw2 += z*z;
3314  fTsumwx += z*x[i];
3315  fTsumwx2 += z*x[i]*x[i];
3316  }
3317 }
3318 
3319 
3320 ////////////////////////////////////////////////////////////////////////////////
3321 /// Fill histogram following distribution in function fname.
3322 ///
3323 /// The distribution contained in the function fname (TF1) is integrated
3324 /// over the channel contents for the bin range of this histogram.
3325 /// It is normalized to 1.
3326 /// Getting one random number implies:
3327 /// - Generating a random number between 0 and 1 (say r1)
3328 /// - Look in which bin in the normalized integral r1 corresponds to
3329 /// - Fill histogram channel
3330 /// ntimes random numbers are generated
3331 ///
3332 /// One can also call TF1::GetRandom to get a random variate from a function.
3333 
3334 void TH1::FillRandom(const char *fname, Int_t ntimes)
3335 {
3336  Int_t bin, binx, ibin, loop;
3337  Double_t r1, x;
3338  // - Search for fname in the list of ROOT defined functions
3339  TF1 *f1 = (TF1*)gROOT->GetFunction(fname);
3340  if (!f1) { Error("FillRandom", "Unknown function: %s",fname); return; }
3341 
3342  // - Allocate temporary space to store the integral and compute integral
3343 
3344  TAxis * xAxis = &fXaxis;
3345 
3346  // in case axis of histogram is not defined use the function axis
3347  if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
3348  Double_t xmin,xmax;
3349  f1->GetRange(xmin,xmax);
3350  Info("FillRandom","Using function axis and range [%g,%g]",xmin, xmax);
3351  xAxis = f1->GetHistogram()->GetXaxis();
3352  }
3353 
3354  Int_t first = xAxis->GetFirst();
3355  Int_t last = xAxis->GetLast();
3356  Int_t nbinsx = last-first+1;
3357 
3358  Double_t *integral = new Double_t[nbinsx+1];
3359  integral[0] = 0;
3360  for (binx=1;binx<=nbinsx;binx++) {
3361  Double_t fint = f1->Integral(xAxis->GetBinLowEdge(binx+first-1),xAxis->GetBinUpEdge(binx+first-1));
3362  integral[binx] = integral[binx-1] + fint;
3363  }
3364 
3365  // - Normalize integral to 1
3366  if (integral[nbinsx] == 0 ) {
3367  delete [] integral;
3368  Error("FillRandom", "Integral = zero"); return;
3369  }
3370  for (bin=1;bin<=nbinsx;bin++) integral[bin] /= integral[nbinsx];
3371 
3372  // --------------Start main loop ntimes
3373  for (loop=0;loop<ntimes;loop++) {
3374  r1 = gRandom->Rndm(loop);
3375  ibin = TMath::BinarySearch(nbinsx,&integral[0],r1);
3376  //binx = 1 + ibin;
3377  //x = xAxis->GetBinCenter(binx); //this is not OK when SetBuffer is used
3378  x = xAxis->GetBinLowEdge(ibin+first)
3379  +xAxis->GetBinWidth(ibin+first)*(r1-integral[ibin])/(integral[ibin+1] - integral[ibin]);
3380  Fill(x);
3381  }
3382  delete [] integral;
3383 }
3384 
3385 
3386 ////////////////////////////////////////////////////////////////////////////////
3387 /// Fill histogram following distribution in histogram h.
3388 ///
3389 /// The distribution contained in the histogram h (TH1) is integrated
3390 /// over the channel contents for the bin range of this histogram.
3391 /// It is normalized to 1.
3392 /// Getting one random number implies:
3393 /// - Generating a random number between 0 and 1 (say r1)
3394 /// - Look in which bin in the normalized integral r1 corresponds to
3395 /// - Fill histogram channel ntimes random numbers are generated
3396 ///
3397 /// SPECIAL CASE when the target histogram has the same binning as the source.
3398 /// in this case we simply use a poisson distribution where
3399 /// the mean value per bin = bincontent/integral.
3400 
3401 void TH1::FillRandom(TH1 *h, Int_t ntimes)
3402 {
3403  if (!h) { Error("FillRandom", "Null histogram"); return; }
3404  if (fDimension != h->GetDimension()) {
3405  Error("FillRandom", "Histograms with different dimensions"); return;
3406  }
3407 
3408  //in case the target histogram has the same binning and ntimes much greater
3409  //than the number of bins we can use a fast method
3410  Int_t first = fXaxis.GetFirst();
3411  Int_t last = fXaxis.GetLast();
3412  Int_t nbins = last-first+1;
3413  if (ntimes > 10*nbins) {
3414  try {
3415  CheckConsistency(this,h);
3416  Double_t sumw = h->Integral(first,last);
3417  if (sumw == 0) return;
3418  Double_t sumgen = 0;
3419  for (Int_t bin=first;bin<=last;bin++) {
3420  Double_t mean = h->RetrieveBinContent(bin)*ntimes/sumw;
3421  Double_t cont = (Double_t)gRandom->Poisson(mean);
3422  sumgen += cont;
3423  AddBinContent(bin,cont);
3424  if (fSumw2.fN) fSumw2.fArray[bin] += cont;
3425  }
3426 
3427  // fix for the fluctations in the total number n
3428  // since we use Poisson instead of multinomial
3429  // add a correction to have ntimes as generated entries
3430  Int_t i;
3431  if (sumgen < ntimes) {
3432  // add missing entries
3433  for (i = Int_t(sumgen+0.5); i < ntimes; ++i)
3434  {
3435  Double_t x = h->GetRandom();
3436  Fill(x);
3437  }
3438  }
3439  else if (sumgen > ntimes) {
3440  // remove extra entries
3441  i = Int_t(sumgen+0.5);
3442  while( i > ntimes) {
3443  Double_t x = h->GetRandom();
3444  Int_t ibin = fXaxis.FindBin(x);
3445  Double_t y = RetrieveBinContent(ibin);
3446  // skip in case bin is empty
3447  if (y > 0) {
3448  SetBinContent(ibin, y-1.);
3449  i--;
3450  }
3451  }
3452  }
3453 
3454  ResetStats();
3455  return;
3456  }
3457  catch(std::exception&) {} // do nothing
3458  }
3459  // case of different axis and not too large ntimes
3460 
3461  if (h->ComputeIntegral() ==0) return;
3462  Int_t loop;
3463  Double_t x;
3464  for (loop=0;loop<ntimes;loop++) {
3465  x = h->GetRandom();
3466  Fill(x);
3467  }
3468 }
3469 
3470 
3471 ////////////////////////////////////////////////////////////////////////////////
3472 /// Return Global bin number corresponding to x,y,z
3473 ///
3474 /// 2-D and 3-D histograms are represented with a one dimensional
3475 /// structure. This has the advantage that all existing functions, such as
3476 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3477 /// This function tries to extend the axis if the given point belongs to an
3478 /// under-/overflow bin AND if CanExtendAllAxes() is true.
3479 ///
3480 /// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3481 
3483 {
3484  if (GetDimension() < 2) {
3485  return fXaxis.FindBin(x);
3486  }
3487  if (GetDimension() < 3) {
3488  Int_t nx = fXaxis.GetNbins()+2;
3489  Int_t binx = fXaxis.FindBin(x);
3490  Int_t biny = fYaxis.FindBin(y);
3491  return binx + nx*biny;
3492  }
3493  if (GetDimension() < 4) {
3494  Int_t nx = fXaxis.GetNbins()+2;
3495  Int_t ny = fYaxis.GetNbins()+2;
3496  Int_t binx = fXaxis.FindBin(x);
3497  Int_t biny = fYaxis.FindBin(y);
3498  Int_t binz = fZaxis.FindBin(z);
3499  return binx + nx*(biny +ny*binz);
3500  }
3501  return -1;
3502 }
3503 
3504 
3505 ////////////////////////////////////////////////////////////////////////////////
3506 /// Return Global bin number corresponding to x,y,z.
3507 ///
3508 /// 2-D and 3-D histograms are represented with a one dimensional
3509 /// structure. This has the advantage that all existing functions, such as
3510 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3511 /// This function DOES NOT try to extend the axis if the given point belongs
3512 /// to an under-/overflow bin.
3513 ///
3514 /// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3515 
3517 {
3518  if (GetDimension() < 2) {
3519  return fXaxis.FindFixBin(x);
3520  }
3521  if (GetDimension() < 3) {
3522  Int_t nx = fXaxis.GetNbins()+2;
3523  Int_t binx = fXaxis.FindFixBin(x);
3524  Int_t biny = fYaxis.FindFixBin(y);
3525  return binx + nx*biny;
3526  }
3527  if (GetDimension() < 4) {
3528  Int_t nx = fXaxis.GetNbins()+2;
3529  Int_t ny = fYaxis.GetNbins()+2;
3530  Int_t binx = fXaxis.FindFixBin(x);
3531  Int_t biny = fYaxis.FindFixBin(y);
3532  Int_t binz = fZaxis.FindFixBin(z);
3533  return binx + nx*(biny +ny*binz);
3534  }
3535  return -1;
3536 }
3537 
3538 
3539 ////////////////////////////////////////////////////////////////////////////////
3540 /// Find first bin with content > threshold for axis (1=x, 2=y, 3=z)
3541 /// if no bins with content > threshold is found the function returns -1.
3542 
3543 Int_t TH1::FindFirstBinAbove(Double_t threshold, Int_t axis) const
3544 {
3545  if (fBuffer) ((TH1*)this)->BufferEmpty();
3546 
3547  if (axis != 1) {
3548  Warning("FindFirstBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3549  axis = 1;
3550  }
3551  Int_t nbins = fXaxis.GetNbins();
3552  for (Int_t bin=1;bin<=nbins;bin++) {
3553  if (RetrieveBinContent(bin) > threshold) return bin;
3554  }
3555  return -1;
3556 }
3557 
3558 
3559 ////////////////////////////////////////////////////////////////////////////////
3560 /// Find last bin with content > threshold for axis (1=x, 2=y, 3=z)
3561 /// if no bins with content > threshold is found the function returns -1.
3562 
3563 Int_t TH1::FindLastBinAbove(Double_t threshold, Int_t axis) const
3564 {
3565  if (fBuffer) ((TH1*)this)->BufferEmpty();
3566 
3567  if (axis != 1) {
3568  Warning("FindLastBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3569  axis = 1;
3570  }
3571  Int_t nbins = fXaxis.GetNbins();
3572  for (Int_t bin=nbins;bin>=1;bin--) {
3573  if (RetrieveBinContent(bin) > threshold) return bin;
3574  }
3575  return -1;
3576 }
3577 
3578 
3579 ////////////////////////////////////////////////////////////////////////////////
3580 /// search object named name in the list of functions
3581 
3582 TObject *TH1::FindObject(const char *name) const
3583 {
3584  if (fFunctions) return fFunctions->FindObject(name);
3585  return 0;
3586 }
3587 
3588 
3589 ////////////////////////////////////////////////////////////////////////////////
3590 /// search object obj in the list of functions
3591 
3592 TObject *TH1::FindObject(const TObject *obj) const
3593 {
3594  if (fFunctions) return fFunctions->FindObject(obj);
3595  return 0;
3596 }
3597 
3598 
3599 ////////////////////////////////////////////////////////////////////////////////
3600 /// Fit histogram with function fname.
3601 ///
3602 /// fname is the name of an already predefined function created by TF1 or TF2
3603 /// Predefined functions such as gaus, expo and poln are automatically
3604 /// created by ROOT.
3605 /// fname can also be a formula, accepted by the linear fitter (linear parts divided
3606 /// by "++" sign), for example "x++sin(x)" for fitting "[0]*x+[1]*sin(x)"
3607 ///
3608 /// This function finds a pointer to the TF1 object with name fname
3609 /// and calls TH1::Fit(TF1 *f1,...)
3610 
3611 TFitResultPtr TH1::Fit(const char *fname ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
3612 {
3613  char *linear;
3614  linear= (char*)strstr(fname, "++");
3615  TF1 *f1=0;
3616  TF2 *f2=0;
3617  TF3 *f3=0;
3618  Int_t ndim=GetDimension();
3619  if (linear){
3620  if (ndim<2){
3621  f1=new TF1(fname, fname, xxmin, xxmax);
3622  return Fit(f1,option,goption,xxmin,xxmax);
3623  }
3624  else if (ndim<3){
3625  f2=new TF2(fname, fname);
3626  return Fit(f2,option,goption,xxmin,xxmax);
3627  }
3628  else{
3629  f3=new TF3(fname, fname);
3630  return Fit(f3,option,goption,xxmin,xxmax);
3631  }
3632  }
3633 
3634  else{
3635  f1 = (TF1*)gROOT->GetFunction(fname);
3636  if (!f1) { Printf("Unknown function: %s",fname); return -1; }
3637  return Fit(f1,option,goption,xxmin,xxmax);
3638  }
3639 }
3640 
3641 
3642 ////////////////////////////////////////////////////////////////////////////////
3643 /// Fit histogram with function f1.
3644 ///
3645 /// \param[in] option fit options is given in parameter option.
3646 /// - "W" Set all weights to 1 for non empty bins; ignore error bars
3647 /// - "WW" Set all weights to 1 including empty bins; ignore error bars
3648 /// - "I" Use integral of function in bin, normalized by the bin volume,
3649 /// instead of value at bin center
3650 /// - "L" Use Loglikelihood method (default is chisquare method)
3651 /// - "WL" Use Loglikelihood method and bin contents are not integer,
3652 /// i.e. histogram is weighted (must have Sumw2() set)
3653 /// - "P" Use Pearson chi2 (using expected errors instead of observed errors)
3654 /// - "U" Use a User specified fitting algorithm (via SetFCN)
3655 /// - "Q" Quiet mode (minimum printing)
3656 /// - "V" Verbose mode (default is between Q and V)
3657 /// - "E" Perform better Errors estimation using Minos technique
3658 /// - "B" User defined parameter settings are used for predefined functions
3659 /// like "gaus", "expo", "poln", "landau".
3660 /// Use this option when you want to fix one or more parameters for these functions.
3661 /// - "M" More. Improve fit results.
3662 /// It uses the IMPROVE command of TMinuit (see TMinuit::mnimpr).
3663 /// This algorithm attempts to improve the found local minimum by searching for a
3664 /// better one.
3665 /// - "R" Use the Range specified in the function range
3666 /// - "N" Do not store the graphics function, do not draw
3667 /// - "0" Do not plot the result of the fit. By default the fitted function
3668 /// is drawn unless the option"N" above is specified.
3669 /// - "+" Add this new fitted function to the list of fitted functions
3670 /// (by default, any previous function is deleted)
3671 /// - "C" In case of linear fitting, don't calculate the chisquare
3672 /// (saves time)
3673 /// - "F" If fitting a polN, switch to minuit fitter
3674 /// - "S" The result of the fit is returned in the TFitResultPtr
3675 /// (see below Access to the Fit Result)
3676 /// \param[in] goption specify a list of graphics options. See TH1::Draw for a complete list of these options.
3677 /// \param[in] xxmin range
3678 /// \param[in] xxmax range
3679 ///
3680 /// In order to use the Range option, one must first create a function
3681 /// with the expression to be fitted. For example, if your histogram
3682 /// has a defined range between -4 and 4 and you want to fit a gaussian
3683 /// only in the interval 1 to 3, you can do:
3684 ///
3685 /// TF1 *f1 = new TF1("f1", "gaus", 1, 3);
3686 /// histo->Fit("f1", "R");
3687 ///
3688 /// ## Setting initial conditions
3689 /// Parameters must be initialized before invoking the Fit function.
3690 /// The setting of the parameter initial values is automatic for the
3691 /// predefined functions : poln, expo, gaus, landau. One can however disable
3692 /// this automatic computation by specifying the option "B".
3693 /// Note that if a predefined function is defined with an argument,
3694 /// eg, gaus(0), expo(1), you must specify the initial values for
3695 /// the parameters.
3696 /// You can specify boundary limits for some or all parameters via
3697 ///
3698 /// f1->SetParLimits(p_number, parmin, parmax);
3699 /// if parmin>=parmax, the parameter is fixed
3700 /// Note that you are not forced to fix the limits for all parameters.
3701 /// For example, if you fit a function with 6 parameters, you can do:
3702 ///
3703 /// func->SetParameters(0, 3.1, 1.e-6, -8, 0, 100);
3704 /// func->SetParLimits(3, -10, -4);
3705 /// func->FixParameter(4, 0);
3706 /// func->SetParLimits(5, 1, 1);
3707 /// With this setup, parameters 0->2 can vary freely
3708 /// Parameter 3 has boundaries [-10,-4] with initial value -8
3709 /// Parameter 4 is fixed to 0
3710 /// Parameter 5 is fixed to 100.
3711 /// When the lower limit and upper limit are equal, the parameter is fixed.
3712 /// However to fix a parameter to 0, one must call the FixParameter function.
3713 ///
3714 /// Note that option "I" gives better results but is slower.
3715 ///
3716 /// ## Changing the fitting objective function
3717 /// By default a chi square function is used for fitting. When option "L" (or "LL") is used
3718 /// a Poisson likelihood function (see note below) is used.
3719 /// The functions are defined in the header Fit/Chi2Func.h or Fit/PoissonLikelihoodFCN and they
3720 /// are implemented using the routines FitUtil::EvaluateChi2 or FitUtil::EvaluatePoissonLogL in
3721 /// the file math/mathcore/src/FitUtil.cxx.
3722 /// To specify a User defined fitting function, specify option "U" and
3723 /// call the following functions:
3724 ///
3725 /// TVirtualFitter::Fitter(myhist)->SetFCN(MyFittingFunction)
3726 /// where MyFittingFunction is of type:
3727 ///
3728 /// extern void MyFittingFunction(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag);
3729 ///
3730 /// ## Chi2 Fits
3731 /// By default a chi2 (least-square) fit is performed on the histogram. The so-called modified least-square method
3732 /// is used where the residual for each bin is computed using as error the observed value (the bin error)
3733 ///
3734 /// Chi2 = Sum{ ( y(i) - f (x(i) | p )/ e(i) )^2 }
3735 ///
3736 /// where y(i) is the bin content for each bin i, x(i) is the bin center and e(i) is the bin error (sqrt(y(i) for
3737 /// an un-weighted histogram. Bins with zero errors are excluded from the fit. See also later the note on the treatment of empty bins.
3738 /// When using option "I" the residual is computed not using the function value at the bin center, f (x(i) | p), but the integral
3739 /// of the function in the bin, Integral{ f(x|p)dx } divided by the bin volume
3740 ///
3741 /// ## Likelihood Fits
3742 /// When using option "L" a likelihood fit is used instead of the default chi2 square fit.
3743 /// The likelihood is built assuming a Poisson probability density function for each bin.
3744 /// The negative log-likelihood to be minimized is
3745 ///
3746 /// NLL = Sum{ log Poisson( y(i) |{ f(x(i) | p ) ) }
3747 /// The exact likelihood used is the Poisson likelihood described in this paper:
3748 /// S. Baker and R. D. Cousins, “Clarification of the use of chi-square and likelihood functions in fits to histograms,”
3749 /// Nucl. Instrum. Meth. 221 (1984) 437.
3750 ///
3751 /// This method can then be used only when the bin content represents counts (i.e. errors are sqrt(N) ).
3752 /// The likelihood method has the advantage of treating correctly bins with low statistics. In case of high
3753 /// statistics/bin the distribution of the bin content becomes a normal distribution and the likelihood and chi2 fit
3754 /// give the same result.
3755 ///
3756 /// The likelihood method, although a bit slower, it is therefore the recommended method in case of low
3757 /// bin statistics, where the chi2 method may give incorrect results, in particular when there are
3758 /// several empty bins (see also below).
3759 /// In case of a weighted histogram, it is possible to perform a likelihood fit by using the
3760 /// option "WL". Note a weighted histogram is an histogram which has been filled with weights and it
3761 /// contains the sum of the weight square ( TH1::Sumw2() has been called). The bin error for a weighted
3762 /// histogram is the square root of the sum of the weight square.
3763 ///
3764 /// ## Treatment of Empty Bins
3765 /// Empty bins, which have the content equal to zero AND error equal to zero,
3766 /// are excluded by default from the chisquare fit, but they are considered in the likelihood fit.
3767 /// since they affect the likelihood if the function value in these bins is not negligible.
3768 /// When using option "WW" these bins will be considered in the chi2 fit with an error of 1.
3769 /// Note that if the histogram is having bins with zero content and non zero-errors they are considered as
3770 /// any other bins in the fit. Instead bins with zero error and non-zero content are excluded in the chi2 fit.
3771 /// A likelihood fit should also not be peformed on such an histogram, since we are assuming a wrong pdf for each bin.
3772 /// In general, one should not fit an histogram with non-empty bins and zero errors, apart if all the bins have zero errors.
3773 /// In this case one could use the option "w", which gives a weight=1 for each bin (unweighted least-square fit).
3774 ///
3775 /// ## Fitting a histogram of dimension N with a function of dimension N-1
3776 /// It is possible to fit a TH2 with a TF1 or a TH3 with a TF2.
3777 /// In this case the option "Integral" is not allowed and each cell has
3778 /// equal weight.
3779 ///
3780 /// ## Associated functions
3781 /// One or more object (typically a TF1*) can be added to the list
3782 /// of functions (fFunctions) associated to each histogram.
3783 /// When TH1::Fit is invoked, the fitted function is added to this list.
3784 /// Given an histogram h, one can retrieve an associated function
3785 /// with: TF1 *myfunc = h->GetFunction("myfunc");
3786 ///
3787 /// ##Access to the fit result
3788 /// The function returns a TFitResultPtr which can hold a pointer to a TFitResult object.
3789 /// By default the TFitResultPtr contains only the status of the fit which is return by an
3790 /// automatic conversion of the TFitResultPtr to an integer. One can write in this case directly:
3791 ///
3792 /// Int_t fitStatus = h->Fit(myFunc)
3793 ///
3794 /// If the option "S" is instead used, TFitResultPtr contains the TFitResult and behaves as a smart
3795 /// pointer to it. For example one can do:
3796 ///
3797 /// TFitResultPtr r = h->Fit(myFunc,"S");
3798 /// TMatrixDSym cov = r->GetCovarianceMatrix(); // to access the covariance matrix
3799 /// Double_t chi2 = r->Chi2(); // to retrieve the fit chi2
3800 /// Double_t par0 = r->Parameter(0); // retrieve the value for the parameter 0
3801 /// Double_t err0 = r->ParError(0); // retrieve the error for the parameter 0
3802 /// r->Print("V"); // print full information of fit including covariance matrix
3803 /// r->Write(); // store the result in a file
3804 ///
3805 /// The fit parameters, error and chi2 (but not covariance matrix) can be retrieved also
3806 /// from the fitted function.
3807 /// If the histogram is made persistent, the list of
3808 /// associated functions is also persistent. Given a pointer (see above)
3809 /// to an associated function myfunc, one can retrieve the function/fit
3810 /// parameters with calls such as:
3811 ///
3812 /// Double_t chi2 = myfunc->GetChisquare();
3813 /// Double_t par0 = myfunc->GetParameter(0); //value of 1st parameter
3814 /// Double_t err0 = myfunc->GetParError(0); //error on first parameter
3815 ///
3816 /// ## Access to the fit status
3817 /// The status of the fit can be obtained converting the TFitResultPtr to an integer
3818 /// independently if the fit option "S" is used or not:
3819 ///
3820 /// TFitResultPtr r = h->Fit(myFunc,opt);
3821 /// Int_t fitStatus = r;
3822 ///
3823 /// The fitStatus is 0 if the fit is OK (i.e no error occurred).
3824 /// The value of the fit status code is negative in case of an error not connected with the
3825 /// minimization procedure, for example when a wrong function is used.
3826 /// Otherwise the return value is the one returned from the minimization procedure.
3827 /// When TMinuit (default case) or Minuit2 are used as minimizer the status returned is :
3828 /// fitStatus = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult.
3829 /// TMinuit will return 0 (for migrad, minos, hesse or improve) in case of success and 4 in
3830 /// case of error (see the documentation of TMinuit::mnexcm). So for example, for an error
3831 /// only in Minos but not in Migrad a fitStatus of 40 will be returned.
3832 /// Minuit2 will return also 0 in case of success and different values in migrad minos or
3833 /// hesse depending on the error. See in this case the documentation of
3834 /// Minuit2Minimizer::Minimize for the migradResult, Minuit2Minimizer::GetMinosError for the
3835 /// minosResult and Minuit2Minimizer::Hesse for the hesseResult.
3836 /// If other minimizers are used see their specific documentation for the status code returned.
3837 /// For example in the case of Fumili, for the status returned see TFumili::Minimize.
3838 ///
3839 /// ## Excluding points
3840 /// Use TF1::RejectPoint inside your fitting function to exclude points
3841 /// within a certain range from the fit. Example:
3842 ///
3843 /// Double_t fline(Double_t *x, Double_t *par)
3844 /// {
3845 /// if (x[0] > 2.5 && x[0] < 3.5) {
3846 /// TF1::RejectPoint();
3847 /// return 0;
3848 /// }
3849 /// return par[0] + par[1]*x[0];
3850 /// }
3851 ///
3852 /// void exclude() {
3853 /// TF1 *f1 = new TF1("f1", "[0] +[1]*x +gaus(2)", 0, 5);
3854 /// f1->SetParameters(6, -1,5, 3, 0.2);
3855 /// TH1F *h = new TH1F("h", "background + signal", 100, 0, 5);
3856 /// h->FillRandom("f1", 2000);
3857 /// TF1 *fline = new TF1("fline", fline, 0, 5, 2);
3858 /// fline->SetParameters(2, -1);
3859 /// h->Fit("fline", "l");
3860 /// }
3861 ///
3862 /// ## Warning when using the option "0"
3863 /// When selecting the option "0", the fitted function is added to
3864 /// the list of functions of the histogram, but it is not drawn.
3865 /// You can undo what you disabled in the following way:
3866 ///
3867 /// h.Fit("myFunction", "0"); // fit, store function but do not draw
3868 /// h.Draw(); function is not drawn
3869 /// const Int_t kNotDraw = 1<<9;
3870 /// h.GetFunction("myFunction")->ResetBit(kNotDraw);
3871 /// h.Draw(); // function is visible again
3872 ///
3873 /// ## Access to the Minimizer information during fitting
3874 /// This function calls, the ROOT::Fit::FitObject function implemented in HFitImpl.cxx
3875 /// which uses the ROOT::Fit::Fitter class. The Fitter class creates the objective fuction
3876 /// (e.g. chi2 or likelihood) and uses an implementation of the Minimizer interface for minimizing
3877 /// the function.
3878 /// The default minimizer is Minuit (class TMinuitMinimizer which calls TMinuit).
3879 /// The default can be set in the resource file in etc/system.rootrc. For example
3880 ///
3881 /// Root.Fitter: Minuit2
3882 /// A different fitter can also be set via ROOT::Math::MinimizerOptions::SetDefaultMinimizer
3883 /// (or TVirtualFitter::SetDefaultFitter).
3884 /// For example ROOT::Math::MinimizerOptions::SetDefaultMinimizer("GSLMultiMin","BFGS");
3885 /// will set the usdage of the BFGS algorithm of the GSL multi-dimensional minimization
3886 /// (implemented in libMathMore). ROOT::Math::MinimizerOptions can be used also to set other
3887 /// default options, like maximum number of function calls, minimization tolerance or print
3888 /// level. See the documentation of this class.
3889 ///
3890 /// For fitting linear functions (containing the "++" sign" and polN functions,
3891 /// the linear fitter is automatically initialized.
3892 
3893 TFitResultPtr TH1::Fit(TF1 *f1 ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
3894 {
3895  // implementation of Fit method is in file hist/src/HFitImpl.cxx
3896  Foption_t fitOption;
3898 
3899  // create range and minimizer options with default values
3900  ROOT::Fit::DataRange range(xxmin,xxmax);
3901  ROOT::Math::MinimizerOptions minOption;
3902 
3903  // need to empty the buffer before
3904  // (t.b.d. do a ML unbinned fit with buffer data)
3905  if (fBuffer) BufferEmpty();
3906 
3907  return ROOT::Fit::FitObject(this, f1 , fitOption , minOption, goption, range);
3908 }
3909 
3910 
3911 ////////////////////////////////////////////////////////////////////////////////
3912 /// Display a panel with all histogram fit options.
3913 ///
3914 /// See class TFitPanel for example
3915 
3916 void TH1::FitPanel()
3917 {
3918  if (!gPad)
3919  gROOT->MakeDefCanvas();
3920 
3921  if (!gPad) {
3922  Error("FitPanel", "Unable to create a default canvas");
3923  return;
3924  }
3925 
3926 
3927  // use plugin manager to create instance of TFitEditor
3928  TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TFitEditor");
3929  if (handler && handler->LoadPlugin() != -1) {
3930  if (handler->ExecPlugin(2, gPad, this) == 0)
3931  Error("FitPanel", "Unable to create the FitPanel");
3932  }
3933  else
3934  Error("FitPanel", "Unable to find the FitPanel plug-in");
3935 }
3936 
3937 
3938 ////////////////////////////////////////////////////////////////////////////////
3939 /// Return an histogram containing the asymmetry of this histogram with h2,
3940 /// where the asymmetry is defined as:
3941 ///
3942 /// Asymmetry = (h1 - h2)/(h1 + h2) where h1 = this
3943 ///
3944 /// works for 1D, 2D, etc. histograms
3945 /// c2 is an optional argument that gives a relative weight between the two
3946 /// histograms, and dc2 is the error on this weight. This is useful, for example,
3947 /// when forming an asymmetry between two histograms from 2 different data sets that
3948 /// need to be normalized to each other in some way. The function calculates
3949 /// the errors asumming Poisson statistics on h1 and h2 (that is, dh = sqrt(h)).
3950 ///
3951 /// example: assuming 'h1' and 'h2' are already filled
3952 ///
3953 /// h3 = h1->GetAsymmetry(h2)
3954 ///
3955 /// then 'h3' is created and filled with the asymmetry between 'h1' and 'h2';
3956 /// h1 and h2 are left intact.
3957 ///
3958 /// Note that it is the user's responsibility to manage the created histogram.
3959 /// The name of the returned histogram will be Asymmetry_nameOfh1-nameOfh2
3960 ///
3961 /// code proposed by Jason Seely (seely@mit.edu) and adapted by R.Brun
3962 ///
3963 /// clone the histograms so top and bottom will have the
3964 /// correct dimensions:
3965 /// Sumw2 just makes sure the errors will be computed properly
3966 /// when we form sums and ratios below.
3967 
3968 TH1 *TH1::GetAsymmetry(TH1* h2, Double_t c2, Double_t dc2)
3969 {
3970  TH1 *h1 = this;
3971  TString name = TString::Format("Asymmetry_%s-%s",h1->GetName(),h2->GetName() );
3972  TH1 *asym = (TH1*)Clone(name);
3973 
3974  // set also the title
3975  TString title = TString::Format("(%s - %s)/(%s+%s)",h1->GetName(),h2->GetName(),h1->GetName(),h2->GetName() );
3976  asym->SetTitle(title);
3977 
3978  asym->Sumw2();
3979  Bool_t addStatus = TH1::AddDirectoryStatus();
3981  TH1 *top = (TH1*)asym->Clone();
3982  TH1 *bottom = (TH1*)asym->Clone();
3983  TH1::AddDirectory(addStatus);
3984 
3985  // form the top and bottom of the asymmetry, and then divide:
3986  top->Add(h1,h2,1,-c2);
3987  bottom->Add(h1,h2,1,c2);
3988  asym->Divide(top,bottom);
3989 
3990  Int_t xmax = asym->GetNbinsX();
3991  Int_t ymax = asym->GetNbinsY();
3992  Int_t zmax = asym->GetNbinsZ();
3993 
3994  if (h1->fBuffer) h1->BufferEmpty(1);
3995  if (h2->fBuffer) h2->BufferEmpty(1);
3996  if (bottom->fBuffer) bottom->BufferEmpty(1);
3997 
3998  // now loop over bins to calculate the correct errors
3999  // the reason this error calculation looks complex is because of c2
4000  for(Int_t i=1; i<= xmax; i++){
4001  for(Int_t j=1; j<= ymax; j++){
4002  for(Int_t k=1; k<= zmax; k++){
4003  Int_t bin = GetBin(i, j, k);
4004  // here some bin contents are written into variables to make the error
4005  // calculation a little more legible:
4006  Double_t a = h1->RetrieveBinContent(bin);
4007  Double_t b = h2->RetrieveBinContent(bin);
4008  Double_t bot = bottom->RetrieveBinContent(bin);
4009 
4010  // make sure there are some events, if not, then the errors are set = 0
4011  // automatically.
4012  //if(bot < 1){} was changed to the next line from recommendation of Jason Seely (28 Nov 2005)
4013  if(bot < 1e-6){}
4014  else{
4015  // computation of errors by Christos Leonidopoulos
4016  Double_t dasq = h1->GetBinErrorSqUnchecked(bin);
4017  Double_t dbsq = h2->GetBinErrorSqUnchecked(bin);
4018  Double_t error = 2*TMath::Sqrt(a*a*c2*c2*dbsq + c2*c2*b*b*dasq+a*a*b*b*dc2*dc2)/(bot*bot);
4019  asym->SetBinError(i,j,k,error);
4020  }
4021  }
4022  }
4023  }
4024  delete top;
4025  delete bottom;
4026 
4027  return asym;
4028 }
4029 
4030 
4031 ////////////////////////////////////////////////////////////////////////////////
4032 /// static function
4033 /// return the default buffer size for automatic histograms
4034 /// the parameter fgBufferSize may be changed via SetDefaultBufferSize
4035 
4037 {
4039 }
4040 
4041 
4042 ////////////////////////////////////////////////////////////////////////////////
4043 /// return kTRUE if TH1::Sumw2 must be called when creating new histograms.
4044 /// see TH1::SetDefaultSumw2.
4045 
4047 {
4049 }
4050 
4051 
4052 ////////////////////////////////////////////////////////////////////////////////
4053 /// return the current number of entries
4054 
4055 Double_t TH1::GetEntries() const
4056 {
4057  if (fBuffer) {
4058  Int_t nentries = (Int_t) fBuffer[0];
4059  if (nentries > 0) return nentries;
4060  }
4061 
4062  return fEntries;
4063 }
4064 
4065 
4066 ////////////////////////////////////////////////////////////////////////////////
4067 /// number of effective entries of the histogram,
4068 /// neff = (Sum of weights )^2 / (Sum of weight^2 )
4069 /// In case of an unweighted histogram this number is equivalent to the
4070 /// number of entries of the histogram.
4071 /// For a weighted histogram, this number corresponds to the hypotetical number of unweighted entries
4072 /// a histogram would need to have the same statistical power as this weighted histogram.
4073 /// Note: The underflow/overflow are included if one has set the TH1::StatOverFlows flag
4074 /// and if the statistics has been computed at filling time.
4075 /// If a range is set in the histogram the number is computed from the given range.
4076 
4078 {
4080  this->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
4081  return (s[1] ? s[0]*s[0]/s[1] : TMath::Abs(s[0]) );
4082 }
4083 
4084 
4085 ////////////////////////////////////////////////////////////////////////////////
4086 /// Redefines TObject::GetObjectInfo.
4087 /// Displays the histogram info (bin number, contents, integral up to bin
4088 /// corresponding to cursor position px,py
4089 
4090 char *TH1::GetObjectInfo(Int_t px, Int_t py) const
4091 {
4092  return ((TH1*)this)->GetPainter()->GetObjectInfo(px,py);
4093 }
4094 
4095 
4096 ////////////////////////////////////////////////////////////////////////////////
4097 /// return pointer to painter
4098 /// if painter does not exist, it is created
4099 
4101 {
4102  if (!fPainter) {
4103  TString opt = option;
4104  opt.ToLower();
4105  if (opt.Contains("gl") || gStyle->GetCanvasPreferGL()) {
4106  //try to create TGLHistPainter
4107  TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TGLHistPainter");
4108 
4109  if (handler && handler->LoadPlugin() != -1)
4110  fPainter = reinterpret_cast<TVirtualHistPainter *>(handler->ExecPlugin(1, this));
4111  }
4112  }
4113 
4115 
4116  return fPainter;
4117 }
4118 
4119 
4120 ////////////////////////////////////////////////////////////////////////////////
4121 /// Compute Quantiles for this histogram
4122 /// Quantile x_q of a probability distribution Function F is defined as
4123 ///
4124 /// F(x_q) = q with 0 <= q <= 1.
4125 ///
4126 /// For instance the median x_0.5 of a distribution is defined as that value
4127 /// of the random variable for which the distribution function equals 0.5:
4128 ///
4129 /// F(x_0.5) = Probability(x < x_0.5) = 0.5
4130 ///
4131 /// code from Eddy Offermann, Renaissance
4132 ///
4133 /// \param[in] nprobSum maximum size of array q and size of array probSum (if given)
4134 /// \param[in] probSum array of positions where quantiles will be computed.
4135 /// - if probSum is null, probSum will be computed internally and will
4136 /// have a size = number of bins + 1 in h. it will correspond to the
4137 /// quantiles calculated at the lowest edge of the histogram (quantile=0) and
4138 /// all the upper edges of the bins.
4139 /// - if probSum is not null, it is assumed to contain at least nprobSum values.
4140 /// \param[out] q array q filled with nq quantiles
4141 /// \return value nq (<=nprobSum) with the number of quantiles computed
4142 ///
4143 /// Note that the Integral of the histogram is automatically recomputed
4144 /// if the number of entries is different of the number of entries when
4145 /// the integral was computed last time. In case you do not use the Fill
4146 /// functions to fill your histogram, but SetBinContent, you must call
4147 /// TH1::ComputeIntegral before calling this function.
4148 ///
4149 /// Getting quantiles q from two histograms and storing results in a TGraph,
4150 /// a so-called QQ-plot
4151 /// ~~~{.cpp}
4152 /// TGraph *gr = new TGraph(nprob);
4153 /// h1->GetQuantiles(nprob,gr->GetX());
4154 /// h2->GetQuantiles(nprob,gr->GetY());
4155 /// gr->Draw("alp");
4156 /// ~~~
4157 ///
4158 /// Example:
4159 /// ~~~{cpp}
4160 /// void quantiles() {
4161 /// // demo for quantiles
4162 /// const Int_t nq = 20;
4163 /// TH1F *h = new TH1F("h","demo quantiles",100,-3,3);
4164 /// h->FillRandom("gaus",5000);
4165 ///
4166 /// Double_t xq[nq]; // position where to compute the quantiles in [0,1]
4167 /// Double_t yq[nq]; // array to contain the quantiles
4168 /// for (Int_t i=0;i<nq;i++) xq[i] = Float_t(i+1)/nq;
4169 /// h->GetQuantiles(nq,yq,xq);
4170 ///
4171 /// //show the original histogram in the top pad
4172 /// TCanvas *c1 = new TCanvas("c1","demo quantiles",10,10,700,900);
4173 /// c1->Divide(1,2);
4174 /// c1->cd(1);
4175 /// h->Draw();
4176 ///
4177 /// // show the quantiles in the bottom pad
4178 /// c1->cd(2);
4179 /// gPad->SetGrid();
4180 /// TGraph *gr = new TGraph(nq,xq,yq);
4181 /// gr->SetMarkerStyle(21);
4182 /// gr->Draw("alp");
4183 /// }
4184 /// ~~~
4185 
4186 Int_t TH1::GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum)
4187 {
4188  if (GetDimension() > 1) {
4189  Error("GetQuantiles","Only available for 1-d histograms");
4190  return 0;
4191  }
4192 
4193  const Int_t nbins = GetXaxis()->GetNbins();
4194  if (!fIntegral) ComputeIntegral();
4195  if (fIntegral[nbins+1] != fEntries) ComputeIntegral();
4196 
4197  Int_t i, ibin;
4198  Double_t *prob = (Double_t*)probSum;
4199  Int_t nq = nprobSum;
4200  if (probSum == 0) {
4201  nq = nbins+1;
4202  prob = new Double_t[nq];
4203  prob[0] = 0;
4204  for (i=1;i<nq;i++) {
4205  prob[i] = fIntegral[i]/fIntegral[nbins];
4206  }
4207  }
4208 
4209  for (i = 0; i < nq; i++) {
4210  ibin = TMath::BinarySearch(nbins,fIntegral,prob[i]);
4211  while (ibin < nbins-1 && fIntegral[ibin+1] == prob[i]) {
4212  if (fIntegral[ibin+2] == prob[i]) ibin++;
4213  else break;
4214  }
4215  q[i] = GetBinLowEdge(ibin+1);
4216  const Double_t dint = fIntegral[ibin+1]-fIntegral[ibin];
4217  if (dint > 0) q[i] += GetBinWidth(ibin+1)*(prob[i]-fIntegral[ibin])/dint;
4218  }
4219 
4220  if (!probSum) delete [] prob;
4221  return nq;
4222 }
4223 
4224 
4225 ////////////////////////////////////////////////////////////////////////////////
4226 /// Decode string choptin and fill fitOption structure.
4227 
4228 Int_t TH1::FitOptionsMake(Option_t *choptin, Foption_t &fitOption)
4229 {
4231  return 1;
4232 }
4233 
4234 
4235 ////////////////////////////////////////////////////////////////////////////////
4236 /// Compute Initial values of parameters for a gaussian.
4237 
4238 void H1InitGaus()
4239 {
4240  Double_t allcha, sumx, sumx2, x, val, stddev, mean;
4241  Int_t bin;
4242  const Double_t sqrtpi = 2.506628;
4243 
4244  // - Compute mean value and StdDev of the histogram in the given range
4246  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4247  Int_t hxfirst = hFitter->GetXfirst();
4248  Int_t hxlast = hFitter->GetXlast();
4249  Double_t valmax = curHist->GetBinContent(hxfirst);
4250  Double_t binwidx = curHist->GetBinWidth(hxfirst);
4251  allcha = sumx = sumx2 = 0;
4252  for (bin=hxfirst;bin<=hxlast;bin++) {
4253  x = curHist->GetBinCenter(bin);
4254  val = TMath::Abs(curHist->GetBinContent(bin));
4255  if (val > valmax) valmax = val;
4256  sumx += val*x;
4257  sumx2 += val*x*x;
4258  allcha += val;
4259  }
4260  if (allcha == 0) return;
4261  mean = sumx/allcha;
4262  stddev = sumx2/allcha - mean*mean;
4263  if (stddev > 0) stddev = TMath::Sqrt(stddev);
4264  else stddev = 0;
4265  if (stddev == 0) stddev = binwidx*(hxlast-hxfirst+1)/4;
4266  //if the distribution is really gaussian, the best approximation
4267  //is binwidx*allcha/(sqrtpi*stddev)
4268  //However, in case of non-gaussian tails, this underestimates
4269  //the normalisation constant. In this case the maximum value
4270  //is a better approximation.
4271  //We take the average of both quantities
4272  Double_t constant = 0.5*(valmax+binwidx*allcha/(sqrtpi*stddev));
4273 
4274  //In case the mean value is outside the histo limits and
4275  //the StdDev is bigger than the range, we take
4276  // mean = center of bins
4277  // stddev = half range
4278  Double_t xmin = curHist->GetXaxis()->GetXmin();
4279  Double_t xmax = curHist->GetXaxis()->GetXmax();
4280  if ((mean < xmin || mean > xmax) && stddev > (xmax-xmin)) {
4281  mean = 0.5*(xmax+xmin);
4282  stddev = 0.5*(xmax-xmin);
4283  }
4284  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4285  f1->SetParameter(0,constant);
4286  f1->SetParameter(1,mean);
4287  f1->SetParameter(2,stddev);
4288  f1->SetParLimits(2,0,10*stddev);
4289 }
4290 
4291 
4292 ////////////////////////////////////////////////////////////////////////////////
4293 /// Compute Initial values of parameters for an exponential.
4294 
4295 void H1InitExpo()
4296 {
4297  Double_t constant, slope;
4298  Int_t ifail;
4300  Int_t hxfirst = hFitter->GetXfirst();
4301  Int_t hxlast = hFitter->GetXlast();
4302  Int_t nchanx = hxlast - hxfirst + 1;
4303 
4304  H1LeastSquareLinearFit(-nchanx, constant, slope, ifail);
4305 
4306  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4307  f1->SetParameter(0,constant);
4308  f1->SetParameter(1,slope);
4309 
4310 }
4311 
4312 
4313 ////////////////////////////////////////////////////////////////////////////////
4314 /// Compute Initial values of parameters for a polynom.
4315 
4316 void H1InitPolynom()
4317 {
4318  Double_t fitpar[25];
4319 
4321  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4322  Int_t hxfirst = hFitter->GetXfirst();
4323  Int_t hxlast = hFitter->GetXlast();
4324  Int_t nchanx = hxlast - hxfirst + 1;
4325  Int_t npar = f1->GetNpar();
4326 
4327  if (nchanx <=1 || npar == 1) {
4328  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4329  fitpar[0] = curHist->GetSumOfWeights()/Double_t(nchanx);
4330  } else {
4331  H1LeastSquareFit( nchanx, npar, fitpar);
4332  }
4333  for (Int_t i=0;i<npar;i++) f1->SetParameter(i, fitpar[i]);
4334 }
4335 
4336 
4337 ////////////////////////////////////////////////////////////////////////////////
4338 /// Least squares lpolynomial fitting without weights.
4339 ///
4340 /// \param[in] n number of points to fit
4341 /// \param[in] m number of parameters
4342 /// \param[in] a array of parameters
4343 ///
4344 /// based on CERNLIB routine LSQ: Translated to C++ by Rene Brun
4345 /// (E.Keil. revised by B.Schorr, 23.10.1981.)
4346 
4347 void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a)
4348 {
4349  const Double_t zero = 0.;
4350  const Double_t one = 1.;
4351  const Int_t idim = 20;
4352 
4353  Double_t b[400] /* was [20][20] */;
4354  Int_t i, k, l, ifail;
4355  Double_t power;
4356  Double_t da[20], xk, yk;
4357 
4358  if (m <= 2) {
4359  H1LeastSquareLinearFit(n, a[0], a[1], ifail);
4360  return;
4361  }
4362  if (m > idim || m > n) return;
4363  b[0] = Double_t(n);
4364  da[0] = zero;
4365  for (l = 2; l <= m; ++l) {
4366  b[l-1] = zero;
4367  b[m + l*20 - 21] = zero;
4368  da[l-1] = zero;
4369  }
4371  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4372  Int_t hxfirst = hFitter->GetXfirst();
4373  Int_t hxlast = hFitter->GetXlast();
4374  for (k = hxfirst; k <= hxlast; ++k) {
4375  xk = curHist->GetBinCenter(k);
4376  yk = curHist->GetBinContent(k);
4377  power = one;
4378  da[0] += yk;
4379  for (l = 2; l <= m; ++l) {
4380  power *= xk;
4381  b[l-1] += power;
4382  da[l-1] += power*yk;
4383  }
4384  for (l = 2; l <= m; ++l) {
4385  power *= xk;
4386  b[m + l*20 - 21] += power;
4387  }
4388  }
4389  for (i = 3; i <= m; ++i) {
4390  for (k = i; k <= m; ++k) {
4391  b[k - 1 + (i-1)*20 - 21] = b[k + (i-2)*20 - 21];
4392  }
4393  }
4394  H1LeastSquareSeqnd(m, b, idim, ifail, 1, da);
4395 
4396  for (i=0; i<m; ++i) a[i] = da[i];
4397 
4398 }
4399 
4400 
4401 ////////////////////////////////////////////////////////////////////////////////
4402 /// Least square linear fit without weights.
4403 ///
4404 /// extracted from CERNLIB LLSQ: Translated to C++ by Rene Brun
4405 /// (added to LSQ by B. Schorr, 15.02.1982.)
4406 
4407 void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
4408 {
4409  Double_t xbar, ybar, x2bar;
4410  Int_t i, n;
4411  Double_t xybar;
4412  Double_t fn, xk, yk;
4413  Double_t det;
4414 
4415  n = TMath::Abs(ndata);
4416  ifail = -2;
4417  xbar = ybar = x2bar = xybar = 0;
4419  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4420  Int_t hxfirst = hFitter->GetXfirst();
4421  Int_t hxlast = hFitter->GetXlast();
4422  for (i = hxfirst; i <= hxlast; ++i) {
4423  xk = curHist->GetBinCenter(i);
4424  yk = curHist->GetBinContent(i);
4425  if (ndata < 0) {
4426  if (yk <= 0) yk = 1e-9;
4427  yk = TMath::Log(yk);
4428  }
4429  xbar += xk;
4430  ybar += yk;
4431  x2bar += xk*xk;
4432  xybar += xk*yk;
4433  }
4434  fn = Double_t(n);
4435  det = fn*x2bar - xbar*xbar;
4436  ifail = -1;
4437  if (det <= 0) {
4438  a0 = ybar/fn;
4439  a1 = 0;
4440  return;
4441  }
4442  ifail = 0;
4443  a0 = (x2bar*ybar - xbar*xybar) / det;
4444  a1 = (fn*xybar - xbar*ybar) / det;
4445 
4446 }
4447 
4448 
4449 ////////////////////////////////////////////////////////////////////////////////
4450 /// Extracted from CERN Program library routine DSEQN.
4451 ///
4452 /// : Translated to C++ by Rene Brun
4453 
4454 void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b)
4455 {
4456  Int_t a_dim1, a_offset, b_dim1, b_offset;
4457  Int_t nmjp1, i, j, l;
4458  Int_t im1, jp1, nm1, nmi;
4459  Double_t s1, s21, s22;
4460  const Double_t one = 1.;
4461 
4462  /* Parameter adjustments */
4463  b_dim1 = idim;
4464  b_offset = b_dim1 + 1;
4465  b -= b_offset;
4466  a_dim1 = idim;
4467  a_offset = a_dim1 + 1;
4468  a -= a_offset;
4469 
4470  if (idim < n) return;
4471 
4472  ifail = 0;
4473  for (j = 1; j <= n; ++j) {
4474  if (a[j + j*a_dim1] <= 0) { ifail = -1; return; }
4475  a[j + j*a_dim1] = one / a[j + j*a_dim1];
4476  if (j == n) continue;
4477  jp1 = j + 1;
4478  for (l = jp1; l <= n; ++l) {
4479  a[j + l*a_dim1] = a[j + j*a_dim1] * a[l + j*a_dim1];
4480  s1 = -a[l + (j+1)*a_dim1];
4481  for (i = 1; i <= j; ++i) { s1 = a[l + i*a_dim1] * a[i + (j+1)*a_dim1] + s1; }
4482  a[l + (j+1)*a_dim1] = -s1;
4483  }
4484  }
4485  if (k <= 0) return;
4486 
4487  for (l = 1; l <= k; ++l) {
4488  b[l*b_dim1 + 1] = a[a_dim1 + 1]*b[l*b_dim1 + 1];
4489  }
4490  if (n == 1) return;
4491  for (l = 1; l <= k; ++l) {
4492  for (i = 2; i <= n; ++i) {
4493  im1 = i - 1;
4494  s21 = -b[i + l*b_dim1];
4495  for (j = 1; j <= im1; ++j) {
4496  s21 = a[i + j*a_dim1]*b[j + l*b_dim1] + s21;
4497  }
4498  b[i + l*b_dim1] = -a[i + i*a_dim1]*s21;
4499  }
4500  nm1 = n - 1;
4501  for (i = 1; i <= nm1; ++i) {
4502  nmi = n - i;
4503  s22 = -b[nmi + l*b_dim1];
4504  for (j = 1; j <= i; ++j) {
4505  nmjp1 = n - j + 1;
4506  s22 = a[nmi + nmjp1*a_dim1]*b[nmjp1 + l*b_dim1] + s22;
4507  }
4508  b[nmi + l*b_dim1] = -s22;
4509  }
4510  }
4511 }
4512 
4513 
4514 ////////////////////////////////////////////////////////////////////////////////
4515 /// Return Global bin number corresponding to binx,y,z.
4516 ///
4517 /// 2-D and 3-D histograms are represented with a one dimensional
4518 /// structure.
4519 /// This has the advantage that all existing functions, such as
4520 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
4521 ///
4522 /// In case of a TH1x, returns binx directly.
4523 /// see TH1::GetBinXYZ for the inverse transformation.
4524 ///
4525 /// Convention for numbering bins
4526 ///
4527 /// For all histogram types: nbins, xlow, xup
4528 /// bin = 0; underflow bin
4529 /// bin = 1; first bin with low-edge xlow INCLUDED
4530 /// bin = nbins; last bin with upper-edge xup EXCLUDED
4531 /// bin = nbins+1; overflow bin
4532 /// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4533 /// For example, assuming a 3-D histogram with binx,biny,binz, the function
4534 ///
4535 /// Int_t bin = h->GetBin(binx,biny,binz);
4536 /// returns a global/linearized bin number. This global bin is useful
4537 /// to access the bin information independently of the dimension.
4538 
4539 Int_t TH1::GetBin(Int_t binx, Int_t, Int_t) const
4540 {
4541  Int_t ofx = fXaxis.GetNbins() + 1; // overflow bin
4542  if (binx < 0) binx = 0;
4543  if (binx > ofx) binx = ofx;
4544 
4545  return binx;
4546 }
4547 
4548 
4549 ////////////////////////////////////////////////////////////////////////////////
4550 /// return binx, biny, binz corresponding to the global bin number globalbin
4551 /// see TH1::GetBin function above
4552 
4553 void TH1::GetBinXYZ(Int_t binglobal, Int_t &binx, Int_t &biny, Int_t &binz) const
4554 {
4556  Int_t ny = fYaxis.GetNbins()+2;
4557 
4558  if (GetDimension() == 1) {
4559  binx = binglobal%nx;
4560  biny = 0;
4561  binz = 0;
4562  return;
4563  }
4564  if (GetDimension() == 2) {
4565  binx = binglobal%nx;
4566  biny = ((binglobal-binx)/nx)%ny;
4567  binz = 0;
4568  return;
4569  }
4570  if (GetDimension() == 3) {
4571  binx = binglobal%nx;
4572  biny = ((binglobal-binx)/nx)%ny;
4573  binz = ((binglobal-binx)/nx -biny)/ny;
4574  }
4575 }
4576 
4577 
4578 ////////////////////////////////////////////////////////////////////////////////
4579 /// return a random number distributed according the histogram bin contents.
4580 /// This function checks if the bins integral exists. If not, the integral
4581 /// is evaluated, normalized to one.
4582 /// The integral is automatically recomputed if the number of entries
4583 /// is not the same then when the integral was computed.
4584 /// NB Only valid for 1-d histograms. Use GetRandom2 or 3 otherwise.
4585 /// If the histogram has a bin with negative content a NaN is returned
4586 
4587 Double_t TH1::GetRandom() const
4588 {
4589  if (fDimension > 1) {
4590  Error("GetRandom","Function only valid for 1-d histograms");
4591  return 0;
4592  }
4593  Int_t nbinsx = GetNbinsX();
4594  Double_t integral = 0;
4595  // compute integral checking that all bins have positive content (see ROOT-5894)
4596  if (fIntegral) {
4597  if (fIntegral[nbinsx+1] != fEntries) integral = ((TH1*)this)->ComputeIntegral(true);
4598  else integral = fIntegral[nbinsx];
4599  } else {
4600  integral = ((TH1*)this)->ComputeIntegral(true);
4601  }
4602  if (integral == 0) return 0;
4603  // return a NaN in case some bins have negative content
4604  if (integral == TMath::QuietNaN() ) return TMath::QuietNaN();
4605 
4606  Double_t r1 = gRandom->Rndm();
4607  Int_t ibin = TMath::BinarySearch(nbinsx,fIntegral,r1);
4608  Double_t x = GetBinLowEdge(ibin+1);
4609  if (r1 > fIntegral[ibin]) x +=
4610  GetBinWidth(ibin+1)*(r1-fIntegral[ibin])/(fIntegral[ibin+1] - fIntegral[ibin]);
4611  return x;
4612 }
4613 
4614 
4615 ////////////////////////////////////////////////////////////////////////////////
4616 /// Return content of bin number bin.
4617 ///
4618 /// Implemented in TH1C,S,F,D
4619 ///
4620 /// Convention for numbering bins
4621 ///
4622 /// For all histogram types: nbins, xlow, xup
4623 /// bin = 0; underflow bin
4624 /// bin = 1; first bin with low-edge xlow INCLUDED
4625 /// bin = nbins; last bin with upper-edge xup EXCLUDED
4626 /// bin = nbins+1; overflow bin
4627 /// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4628 /// For example, assuming a 3-D histogram with binx,biny,binz, the function
4629 /// Int_t bin = h->GetBin(binx,biny,binz);
4630 /// returns a global/linearized bin number. This global bin is useful
4631 /// to access the bin information independently of the dimension.
4632 
4634 {
4635  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
4636  if (bin < 0) bin = 0;
4637  if (bin >= fNcells) bin = fNcells-1;
4638 
4639  return RetrieveBinContent(bin);
4640 }
4641 
4642 
4643 ////////////////////////////////////////////////////////////////////////////////
4644 /// compute first binx in the range [firstx,lastx] for which
4645 /// diff = abs(bin_content-c) <= maxdiff
4646 /// In case several bins in the specified range with diff=0 are found
4647 /// the first bin found is returned in binx.
4648 /// In case several bins in the specified range satisfy diff <=maxdiff
4649 /// the bin with the smallest difference is returned in binx.
4650 /// In all cases the function returns the smallest difference.
4651 ///
4652 /// NOTE1: if firstx <= 0, firstx is set to bin 1
4653 /// if (lastx < firstx then firstx is set to the number of bins
4654 /// ie if firstx=0 and lastx=0 (default) the search is on all bins.
4655 /// NOTE2: if maxdiff=0 (default), the first bin with content=c is returned.
4656 
4657 Double_t TH1::GetBinWithContent(Double_t c, Int_t &binx, Int_t firstx, Int_t lastx,Double_t maxdiff) const
4658 {
4659  if (fDimension > 1) {
4660  binx = 0;
4661  Error("GetBinWithContent","function is only valid for 1-D histograms");
4662  return 0;
4663  }
4664 
4665  if (fBuffer) ((TH1*)this)->BufferEmpty();
4666 
4667  if (firstx <= 0) firstx = 1;
4668  if (lastx < firstx) lastx = fXaxis.GetNbins();
4669  Int_t binminx = 0;
4670  Double_t diff, curmax = 1.e240;
4671  for (Int_t i=firstx;i<=lastx;i++) {
4672  diff = TMath::Abs(RetrieveBinContent(i)-c);
4673  if (diff <= 0) {binx = i; return diff;}
4674  if (diff < curmax && diff <= maxdiff) {curmax = diff, binminx=i;}
4675  }
4676  binx = binminx;
4677  return curmax;
4678 }
4679 
4680 
4681 ////////////////////////////////////////////////////////////////////////////////
4682 /// Given a point x, approximates the value via linear interpolation
4683 /// based on the two nearest bin centers
4684 /// Andy Mastbaum 10/21/08
4685 
4687 {
4688  if (fBuffer) ((TH1*)this)->BufferEmpty();
4689 
4690  Int_t xbin = FindBin(x);
4691  Double_t x0,x1,y0,y1;
4692 
4693  if(x<=GetBinCenter(1)) {
4694  return RetrieveBinContent(1);
4695  } else if(x>=GetBinCenter(GetNbinsX())) {
4696  return RetrieveBinContent(GetNbinsX());
4697  } else {
4698  if(x<=GetBinCenter(xbin)) {
4699  y0 = RetrieveBinContent(xbin-1);
4700  x0 = GetBinCenter(xbin-1);
4701  y1 = RetrieveBinContent(xbin);
4702  x1 = GetBinCenter(xbin);
4703  } else {
4704  y0 = RetrieveBinContent(xbin);
4705  x0 = GetBinCenter(xbin);
4706  y1 = RetrieveBinContent(xbin+1);
4707  x1 = GetBinCenter(xbin+1);
4708  }
4709  return y0 + (x-x0)*((y1-y0)/(x1-x0));
4710  }
4711 }
4712 
4713 
4714 ////////////////////////////////////////////////////////////////////////////////
4715 
4717 {
4718  //Not yet implemented
4719  Error("Interpolate","This function must be called with 1 argument for a TH1");
4720  return 0;
4721 }
4722 
4723 
4724 ////////////////////////////////////////////////////////////////////////////////
4725 
4727 {
4728  //Not yet implemented
4729  Error("Interpolate","This function must be called with 1 argument for a TH1");
4730  return 0;
4731 }
4732 
4733 
4734 ////////////////////////////////////////////////////////////////////////////////
4735 
4736 Bool_t TH1::IsBinOverflow(Int_t bin) const
4737 {
4738  // Return true if the bin is overflow.
4739  Int_t binx, biny, binz;
4740  GetBinXYZ(bin, binx, biny, binz);
4741 
4742  if ( fDimension == 1 )
4743  return binx >= GetNbinsX() + 1;
4744  else if ( fDimension == 2 )
4745  return (binx >= GetNbinsX() + 1) ||
4746  (biny >= GetNbinsY() + 1);
4747  else if ( fDimension == 3 )
4748  return (binx >= GetNbinsX() + 1) ||
4749  (biny >= GetNbinsY() + 1) ||
4750  (binz >= GetNbinsZ() + 1);
4751  else
4752  return 0;
4753 }
4754 
4755 
4756 ////////////////////////////////////////////////////////////////////////////////
4757 
4758 Bool_t TH1::IsBinUnderflow(Int_t bin) const
4759 {
4760  // Return true if the bin is overflow.
4761  Int_t binx, biny, binz;
4762  GetBinXYZ(bin, binx, biny, binz);
4763 
4764  if ( fDimension == 1 )
4765  return (binx <= 0);
4766  else if ( fDimension == 2 )
4767  return (binx <= 0 || biny <= 0);
4768  else if ( fDimension == 3 )
4769  return (binx <= 0 || biny <= 0 || binz <= 0);
4770  else
4771  return 0;
4772 }
4773 
4774 
4775 ////////////////////////////////////////////////////////////////////////////////
4776 /// Reduce the number of bins for the axis passed in the option to the number of bins having a label.
4777 /// The method will remove only the extra bins existing after the last "labeled" bin.
4778 /// Note that if there are "un-labeled" bins present between "labeled" bins they will not be removed
4779 
4780 void TH1::LabelsDeflate(Option_t *ax)
4781 {
4782  Int_t iaxis = AxisChoice(ax);
4783  TAxis *axis = 0;
4784  if (iaxis == 1) axis = GetXaxis();
4785  if (iaxis == 2) axis = GetYaxis();
4786  if (iaxis == 3) axis = GetZaxis();
4787  if (!axis) {
4788  Error("LabelsDeflate","Invalid axis option %s",ax);
4789  return;
4790  }
4791  if (!axis->GetLabels()) return;
4792 
4793  // find bin with last labels
4794  // bin number is object ID in list of labels
4795  // therefore max bin number is number of bins of the deflated histograms
4796  TIter next(axis->GetLabels());
4797  TObject *obj;
4798  Int_t nbins = 0;
4799  while ((obj = next())) {
4800  Int_t ibin = obj->GetUniqueID();
4801  if (ibin > nbins) nbins = ibin;
4802  }
4803  if (nbins < 1) nbins = 1;
4804  TH1 *hold = (TH1*)IsA()->New();
4805  R__ASSERT(hold);
4806  hold->SetDirectory(0);
4807  Copy(*hold);
4808 
4809  Bool_t timedisp = axis->GetTimeDisplay();
4810  Double_t xmin = axis->GetXmin();
4811  Double_t xmax = axis->GetBinUpEdge(nbins);
4812  if (xmax <= xmin) xmax = xmin +nbins;
4813  axis->SetRange(0,0);
4814  axis->Set(nbins,xmin,xmax);
4815  SetBinsLength(-1); // reset the number of cells
4816  Int_t errors = fSumw2.fN;
4817  if (errors) fSumw2.Set(fNcells);
4818  axis->SetTimeDisplay(timedisp);
4819  // reset histogram content
4820  Reset("ICE");
4821 
4822  //now loop on all bins and refill
4823  // NOTE that if the bins without labels have content
4824  // it will be put in the underflow/overflow.
4825  // For this reason we use AddBinContent method
4826  Double_t oldEntries = fEntries;
4827  Int_t bin,binx,biny,binz;
4828  for (bin=0; bin < hold->fNcells; ++bin) {
4829  hold->GetBinXYZ(bin,binx,biny,binz);
4830  Int_t ibin = GetBin(binx,biny,binz);
4831  Double_t cu = hold->RetrieveBinContent(bin);
4832  AddBinContent(ibin,cu);
4833  if (errors) {
4834  fSumw2.fArray[ibin] += hold->fSumw2.fArray[bin];
4835  }
4836  }
4837  fEntries = oldEntries;
4838  delete hold;
4839 }
4840 
4841 
4842 ////////////////////////////////////////////////////////////////////////////////
4843 /// Double the number of bins for axis.
4844 /// Refill histogram
4845 /// This function is called by TAxis::FindBin(const char *label)
4846 
4847 void TH1::LabelsInflate(Option_t *ax)
4848 {
4849  Int_t iaxis = AxisChoice(ax);
4850  TAxis *axis = 0;
4851  if (iaxis == 1) axis = GetXaxis();
4852  if (iaxis == 2) axis = GetYaxis();
4853  if (iaxis == 3) axis = GetZaxis();
4854  if (!axis) return;
4855 
4856  TH1 *hold = (TH1*)IsA()->New();;
4857  hold->SetDirectory(0);
4858  Copy(*hold);
4859 
4860  Bool_t timedisp = axis->GetTimeDisplay();
4861  Int_t nbins = axis->GetNbins();
4862  Double_t xmin = axis->GetXmin();
4863  Double_t xmax = axis->GetXmax();
4864  xmax = xmin + 2*(xmax-xmin);
4865  axis->SetRange(0,0);
4866  // double the bins and recompute ncells
4867  axis->Set(2*nbins,xmin,xmax);
4868  SetBinsLength(-1);
4869  Int_t errors = fSumw2.fN;
4870  if (errors) fSumw2.Set(fNcells);
4871  axis->SetTimeDisplay(timedisp);
4872 
4873  Reset("ICE"); // reset content and error
4874 
4875  //now loop on all bins and refill
4876  Double_t oldEntries = fEntries;
4877  Int_t bin,ibin,binx,biny,binz;
4878  for (ibin =0; ibin < fNcells; ibin++) {
4879  GetBinXYZ(ibin,binx,biny,binz);
4880  bin = hold->GetBin(binx,biny,binz);
4881 
4882  // underflow and overflow will be cleaned up because their meaning has been altered
4883  if (IsBinUnderflow(bin) || IsBinOverflow(bin)) UpdateBinContent(ibin, 0.0);
4884  else {
4885  AddBinContent(ibin, hold->RetrieveBinContent(bin));
4886  if (errors) fSumw2.fArray[ibin] += hold->fSumw2.fArray[bin];
4887  }
4888  }
4889  fEntries = oldEntries;
4890  delete hold;
4891 }
4892 
4893 
4894 ////////////////////////////////////////////////////////////////////////////////
4895 /// Set option(s) to draw axis with labels
4896 /// \param[in] option
4897 /// - "a" sort by alphabetic order
4898 /// - ">" sort by decreasing values
4899 /// - "<" sort by increasing values
4900 /// - "h" draw labels horizontal
4901 /// - "v" draw labels vertical
4902 /// - "u" draw labels up (end of label right adjusted)
4903 /// - "d" draw labels down (start of label left adjusted)
4904 
4905 void TH1::LabelsOption(Option_t *option, Option_t *ax)
4906 {
4907  Int_t iaxis = AxisChoice(ax);
4908  TAxis *axis = 0;
4909  if (iaxis == 1) axis = GetXaxis();
4910  if (iaxis == 2) axis = GetYaxis();
4911  if (iaxis == 3) axis = GetZaxis();
4912  if (!axis) return;
4913  THashList *labels = axis->GetLabels();
4914  if (!labels) {
4915  Warning("LabelsOption","Cannot sort. No labels");
4916  return;
4917  }
4918  TString opt = option;
4919  opt.ToLower();
4920  if (opt.Contains("h")) {
4921  axis->SetBit(TAxis::kLabelsHori);
4924  axis->ResetBit(TAxis::kLabelsUp);
4925  }
4926  if (opt.Contains("v")) {
4927  axis->SetBit(TAxis::kLabelsVert);
4930  axis->ResetBit(TAxis::kLabelsUp);
4931  }
4932  if (opt.Contains("u")) {
4933  axis->SetBit(TAxis::kLabelsUp);
4937  }
4938  if (opt.Contains("d")) {
4939  axis->SetBit(TAxis::kLabelsDown);
4942  axis->ResetBit(TAxis::kLabelsUp);
4943  }
4944  Int_t sort = -1;
4945  if (opt.Contains("a")) sort = 0;
4946  if (opt.Contains(">")) sort = 1;
4947  if (opt.Contains("<")) sort = 2;
4948  if (sort < 0) return;
4949  if (sort > 0 && GetDimension() > 2) {
4950  Error("LabelsOption","Sorting by value not implemented for 3-D histograms");
4951  return;
4952  }
4953 
4954  Double_t entries = fEntries;
4955  Int_t n = TMath::Min(axis->GetNbins(), labels->GetSize());
4956  std::vector<Int_t> a(n+2);
4957 
4958  Int_t i,j,k;
4959  std::vector<Double_t> cont;
4960  std::vector<Double_t> errors;
4961  THashList *labold = new THashList(labels->GetSize(),1);
4962  TIter nextold(labels);
4963  TObject *obj;
4964  while ((obj=nextold())) {
4965  labold->Add(obj);
4966  }
4967  labels->Clear();
4968  if (sort > 0) {
4969  //---sort by values of bins
4970  if (GetDimension() == 1) {
4971  cont.resize(n);
4972  if (fSumw2.fN) errors.resize(n);
4973  for (i=1;i<=n;i++) {
4974  cont[i-1] = GetBinContent(i);
4975  if (!errors.empty()) errors[i-1] = GetBinError(i);
4976  }
4977  if (sort ==1) TMath::Sort(n,cont.data(),a.data(),kTRUE); //sort by decreasing values
4978  else TMath::Sort(n,cont.data(),a.data(),kFALSE); //sort by increasing values
4979  for (i=1;i<=n;i++) {
4980  SetBinContent(i,cont[a[i-1]]);
4981  if (!errors.empty()) SetBinError(i,errors[a[i-1]]);
4982  }
4983  for (i=1;i<=n;i++) {
4984  obj = labold->At(a[i-1]);
4985  labels->Add(obj);
4986  obj->SetUniqueID(i);
4987  }
4988  } else if (GetDimension()== 2) {
4989  std::vector<Double_t> pcont(n+2);
4990  Int_t nx = fXaxis.GetNbins();
4991  Int_t ny = fYaxis.GetNbins();
4992  cont.resize( (nx+2)*(ny+2));
4993  if (fSumw2.fN) errors.resize( (nx+2)*(ny+2));
4994  for (i=1;i<=nx;i++) {
4995  for (j=1;j<=ny;j++) {
4996  cont[i+nx*j] = GetBinContent(i,j);
4997  if (!errors.empty()) errors[i+nx*j] = GetBinError(i,j);
4998  if (axis == GetXaxis()) k = i;
4999  else k = j;
5000  pcont[k-1] += cont[i+nx*j];
5001  }
5002  }
5003  if (sort ==1) TMath::Sort(n,pcont.data(),a.data(),kTRUE); //sort by decreasing values
5004  else TMath::Sort(n,pcont.data(),a.data(),kFALSE); //sort by increasing values
5005  for (i=0;i<n;i++) {
5006  obj = labold->At(a[i]);
5007  labels->Add(obj);
5008  obj->SetUniqueID(i+1);
5009  }
5010  if (axis == GetXaxis()) {
5011  for (i=1;i<=n;i++) {
5012  for (j=1;j<=ny;j++) {
5013  SetBinContent(i,j,cont[a[i-1]+1+nx*j]);
5014  if (!errors.empty()) SetBinError(i,j,errors[a[i-1]+1+nx*j]);
5015  }
5016  }
5017  }
5018  else {
5019  // using y axis
5020  for (i=1;i<=nx;i++) {
5021  for (j=1;j<=n;j++) {
5022  SetBinContent(i,j,cont[i+nx*(a[j-1]+1)]);
5023  if (!errors.empty()) SetBinError(i,j,errors[i+nx*(a[j-1]+1)]);
5024  }
5025  }
5026  }
5027  } else {
5028  //to be implemented for 3d
5029  }
5030  } else {
5031  //---alphabetic sort
5032  const UInt_t kUsed = 1<<18;
5033  TObject *objk=0;
5034  a[0] = 0;
5035  a[n+1] = n+1;
5036  for (i=1;i<=n;i++) {
5037  const char *label = "zzzzzzzzzzzz";
5038  for (j=1;j<=n;j++) {
5039  obj = labold->At(j-1);
5040  if (!obj) continue;
5041  if (obj->TestBit(kUsed)) continue;
5042  //use strcasecmp for case non-sensitive sort (may be an option)
5043  if (strcmp(label,obj->GetName()) < 0) continue;
5044  objk = obj;
5045  a[i] = j;
5046  label = obj->GetName();
5047  }
5048  if (objk) {
5049  objk->SetUniqueID(i);
5050  labels->Add(objk);
5051  objk->SetBit(kUsed);
5052  }
5053  }
5054  for (i=1;i<=n;i++) {
5055  obj = labels->At(i-1);
5056  if (!obj) continue;
5057  obj->ResetBit(kUsed);
5058  }
5059 
5060  if (GetDimension() == 1) {
5061  cont.resize(n+2);
5062  if (fSumw2.fN) errors.resize(n+2);
5063  for (i=1;i<=n;i++) {
5064  cont[i] = GetBinContent(a[i]);
5065  if (!errors.empty()) errors[i] = GetBinError(a[i]);
5066  }
5067  for (i=1;i<=n;i++) {
5068  SetBinContent(i,cont[i]);
5069  if (!errors.empty()) SetBinError(i,errors[i]);
5070  }
5071  } else if (GetDimension()== 2) {
5072  Int_t nx = fXaxis.GetNbins()+2;
5073  Int_t ny = fYaxis.GetNbins()+2;
5074  cont.resize(nx*ny);
5075  if (fSumw2.fN) errors.resize(nx*ny);
5076  for (i=0;i<nx;i++) {
5077  for (j=0;j<ny;j++) {
5078  cont[i+nx*j] = GetBinContent(i,j);
5079  if (!errors.empty()) errors[i+nx*j] = GetBinError(i,j);
5080  }
5081  }
5082  if (axis == GetXaxis()) {
5083  for (i=1;i<=n;i++) {
5084  for (j=0;j<ny;j++) {
5085  SetBinContent(i,j,cont[a[i]+nx*j]);
5086  if (!errors.empty()) SetBinError(i,j,errors[a[i]+nx*j]);
5087  }
5088  }
5089  } else {
5090  for (i=0;i<nx;i++) {
5091  for (j=1;j<=n;j++) {
5092  SetBinContent(i,j,cont[i+nx*a[j]]);
5093  if (!errors.empty()) SetBinError(i,j,errors[i+nx*a[j]]);
5094  }
5095  }
5096  }
5097  } else {
5098  Int_t nx = fXaxis.GetNbins()+2;
5099  Int_t ny = fYaxis.GetNbins()+2;
5100  Int_t nz = fZaxis.GetNbins()+2;
5101  cont.resize(nx*ny*nz);
5102  if (fSumw2.fN) errors.resize(nx*ny*nz);
5103  for (i=0;i<nx;i++) {
5104  for (j=0;j<ny;j++) {
5105  for (k=0;k<nz;k++) {
5106  cont[i+nx*(j+ny*k)] = GetBinContent(i,j,k);
5107  if (!errors.empty()) errors[i+nx*(j+ny*k)] = GetBinError(i,j,k);
5108  }
5109  }
5110  }
5111  if (axis == GetXaxis()) {
5112  // labels on x axis
5113  for (i=1;i<=n;i++) {
5114  for (j=0;j<ny;j++) {
5115  for (k=0;k<nz;k++) {
5116  SetBinContent(i,j,k,cont[a[i]+nx*(j+ny*k)]);
5117  if (!errors.empty()) SetBinError(i,j,k,errors[a[i]+nx*(j+ny*k)]);
5118  }
5119  }
5120  }
5121  }
5122  else if (axis == GetYaxis()) {
5123  // labels on y axis
5124  for (i=0;i<nx;i++) {
5125  for (j=1;j<=n;j++) {
5126  for (k=0;k<nz;k++) {
5127  SetBinContent(i,j,k,cont[i+nx*(a[j]+ny*k)]);
5128  if (!errors.empty()) SetBinError(i,j,k,errors[i+nx*(a[j]+ny*k)]);
5129  }
5130  }
5131  }
5132  }
5133  else {
5134  // labels on z axis
5135  for (i=0;i<nx;i++) {
5136  for (j=0;j<ny;j++) {
5137  for (k=1;k<=n;k++) {
5138  SetBinContent(i,j,k,cont[i+nx*(j+ny*a[k])]);
5139  if (!errors.empty()) SetBinError(i,j,k,errors[i+nx*(j+ny*a[k])]);
5140  }
5141  }
5142  }
5143  }
5144  }
5145  }
5146  fEntries = entries;
5147  delete labold;
5148 }
5149 
5150 
5151 ////////////////////////////////////////////////////////////////////////////////
5152 
5153 static inline Bool_t AlmostEqual(Double_t a, Double_t b, Double_t epsilon = 0.00000001)
5154 {
5155  return TMath::Abs(a - b) < epsilon;
5156 }
5157 
5158 
5159 ////////////////////////////////////////////////////////////////////////////////
5160 
5161 static inline Bool_t AlmostInteger(Double_t a, Double_t epsilon = 0.00000001)
5162 {
5163  return AlmostEqual(a - TMath::Floor(a), 0, epsilon) ||
5164  AlmostEqual(a - TMath::Floor(a), 1, epsilon);
5165 }
5166 
5167 static inline bool IsEquidistantBinning(const TAxis& axis)
5168 {
5169  // check if axis bin are equals
5170  if (!axis.GetXbins()->fN) return true; //
5171  // not able to check if there is only one axis entry
5172  bool isEquidistant = true;
5173  const Double_t firstBinWidth = axis.GetBinWidth(1);
5174  for (int i = 1; i < axis.GetNbins(); ++i) {
5175  const Double_t binWidth = axis.GetBinWidth(i);
5176  const bool match = TMath::AreEqualRel(firstBinWidth, binWidth, TMath::Limits<Double_t>::Epsilon());
5177  isEquidistant &= match;
5178  if (!match)
5179  break;
5180  }
5181  return isEquidistant;
5182 }
5183 
5184 
5185 ////////////////////////////////////////////////////////////////////////////////
5186 /// Same limits and bins.
5187 
5188 Bool_t TH1::SameLimitsAndNBins(const TAxis& axis1, const TAxis& axis2)
5189 {
5190  return axis1.GetNbins() == axis2.GetNbins()
5191  && axis1.GetXmin() == axis2.GetXmin()
5192  && axis1.GetXmax() == axis2.GetXmax();
5193 }
5194 
5195 ////////////////////////////////////////////////////////////////////////////////
5196 /// Finds new limits for the axis for the Merge function.
5197 /// returns false if the limits are incompatible
5198 
5199 Bool_t TH1::RecomputeAxisLimits(TAxis& destAxis, const TAxis& anAxis)
5200 {
5201  if (SameLimitsAndNBins(destAxis, anAxis))
5202  return kTRUE;
5203 
5204  if (!IsEquidistantBinning(destAxis) || !IsEquidistantBinning(anAxis))
5205  return kFALSE; // not equidistant user binning not supported
5206 
5207  Double_t width1 = destAxis.GetBinWidth(0);
5208  Double_t width2 = anAxis.GetBinWidth(0);
5209  if (width1 == 0 || width2 == 0)
5210  return kFALSE; // no binning not supported
5211 
5212  Double_t xmin = TMath::Min(destAxis.GetXmin(), anAxis.GetXmin());
5213  Double_t xmax = TMath::Max(destAxis.GetXmax(), anAxis.GetXmax());
5214  Double_t width = TMath::Max(width1, width2);
5215 
5216  // check the bin size
5217  if (!AlmostInteger(width/width1) || !AlmostInteger(width/width2))
5218  return kFALSE;
5219 
5220  // std::cout << "Find new limit using given axis " << anAxis.GetXmin() << " , " << anAxis.GetXmax() << " bin width " << width2 << std::endl;
5221  // std::cout << " and destination axis " << destAxis.GetXmin() << " , " << destAxis.GetXmax() << " bin width " << width1 << std::endl;
5222 
5223 
5224  // check the limits
5225  Double_t delta;
5226  delta = (destAxis.GetXmin() - xmin)/width1;
5227  if (!AlmostInteger(delta))
5228  xmin -= (TMath::Ceil(delta) - delta)*width1;
5229 
5230  delta = (anAxis.GetXmin() - xmin)/width2;
5231  if (!AlmostInteger(delta))
5232  xmin -= (TMath::Ceil(delta) - delta)*width2;
5233 
5234 
5235  delta = (destAxis.GetXmin() - xmin)/width1;
5236  if (!AlmostInteger(delta))
5237  return kFALSE;
5238 
5239 
5240  delta = (xmax - destAxis.GetXmax())/width1;
5241  if (!AlmostInteger(delta))
5242  xmax += (TMath::Ceil(delta) - delta)*width1;
5243 
5244 
5245  delta = (xmax - anAxis.GetXmax())/width2;
5246  if (!AlmostInteger(delta))
5247  xmax += (TMath::Ceil(delta) - delta)*width2;
5248 
5249 
5250  delta = (xmax - destAxis.GetXmax())/width1;
5251  if (!AlmostInteger(delta))
5252  return kFALSE;
5253 #ifdef DEBUG
5254  if (!AlmostInteger((xmax - xmin) / width)) { // unnecessary check
5255  printf("TH1::RecomputeAxisLimits - Impossible\n");
5256  return kFALSE;
5257  }
5258 #endif
5259 
5260 
5261  destAxis.Set(TMath::Nint((xmax - xmin)/width), xmin, xmax);
5262 
5263  //std::cout << "New re-computed axis : [ " << xmin << " , " << xmax << " ] width = " << width << " nbins " << destAxis.GetNbins() << std::endl;
5264 
5265  return kTRUE;
5266 }
5267 
5268 
5269 ////////////////////////////////////////////////////////////////////////////////
5270 /// Add all histograms in the collection to this histogram.
5271 /// This function computes the min/max for the x axis,
5272 /// compute a new number of bins, if necessary,
5273 /// add bin contents, errors and statistics.
5274 /// If all histograms have bin labels, bins with identical labels
5275 /// will be merged, no matter what their order is.
5276 /// If overflows are present and limits are different the function will fail.
5277 /// The function returns the total number of entries in the result histogram
5278 /// if the merge is successful, -1 otherwise.
5279 ///
5280 /// IMPORTANT remark. The axis x may have different number
5281 /// of bins and different limits, BUT the largest bin width must be
5282 /// a multiple of the smallest bin width and the upper limit must also
5283 /// be a multiple of the bin width.
5284 /// Example:
5285 ///
5286 /// ~~~{.cpp}
5287 /// void atest() {
5288 /// TH1F *h1 = new TH1F("h1","h1",110,-110,0);
5289 /// TH1F *h2 = new TH1F("h2","h2",220,0,110);
5290 /// TH1F *h3 = new TH1F("h3","h3",330,-55,55);
5291 /// TRandom r;
5292 /// for (Int_t i=0;i<10000;i++) {
5293 /// h1->Fill(r.Gaus(-55,10));
5294 /// h2->Fill(r.Gaus(55,10));
5295 /// h3->Fill(r.Gaus(0,10));
5296 /// }
5297 ///
5298 /// TList *list = new TList;
5299 /// list->Add(h1);
5300 /// list->Add(h2);
5301 /// list->Add(h3);
5302 /// TH1F *h = (TH1F*)h1->Clone("h");
5303 /// h->Reset();
5304 /// h->Merge(list);
5305 /// h->Draw();
5306 /// }
5307 /// ~~~
5308 
5310 {
5311  if (!li) return 0;
5312  if (li->IsEmpty()) return (Long64_t) GetEntries();
5313 
5314  // is this really needed ?
5315  TList inlist;
5316  inlist.AddAll(li);
5317 
5318 
5319  TAxis newXAxis;
5320 
5321  Bool_t initialLimitsFound = kFALSE;
5322  Bool_t allHaveLabels = kTRUE; // assume all histo have labels and check later
5323  Bool_t allHaveLimits = kTRUE;
5324  Bool_t allSameLimits = kTRUE;
5325  Bool_t foundLabelHist = kFALSE;
5326  //Bool_t firstHistWithLimits = kTRUE;
5327 
5328 
5329  TIter next(&inlist);
5330  // start looping with this histogram
5331  TH1 * h = this;
5332 
5333  do {
5334  // do not skip anymore empty histograms
5335  // since are used to set the limits
5336  Bool_t hasLimits = h->GetXaxis()->GetXmin() < h->GetXaxis()->GetXmax();
5337  allHaveLimits = allHaveLimits && hasLimits;
5338 
5339  if (hasLimits) {
5340  h->BufferEmpty();
5341 
5342  // this is done in case the first histograms are empty and
5343  // the histogram have different limits
5344 #ifdef LATER
5345  if (firstHistWithLimits ) {
5346  // set axis limits in the case the first histogram did not have limits
5347  if (h != this && !SameLimitsAndNBins( fXaxis, *h->GetXaxis()) ) {
5348  if (h->GetXaxis()->GetXbins()->GetSize() != 0) fXaxis.Set(h->GetXaxis()->GetNbins(), h->GetXaxis()->GetXbins()->GetArray());
5349  else fXaxis.Set(h->GetXaxis()->GetNbins(), h->GetXaxis()->GetXmin(), h->GetXaxis()->GetXmax());
5350  }
5351  firstHistWithLimits = kFALSE;
5352  }
5353 #endif
5354 
5355  // this is executed the first time an histogram with limits is found
5356  // to set some initial values on the new axis
5357  if (!initialLimitsFound) {
5358  initialLimitsFound = kTRUE;
5359  if (h->GetXaxis()->GetXbins()->GetSize() != 0) newXAxis.Set(h->GetXaxis()->GetNbins(), h->GetXaxis()->GetXbins()->GetArray());
5360  else newXAxis.Set(h->GetXaxis()->GetNbins(), h->GetXaxis()->GetXmin(), h->GetXaxis()->GetXmax());
5361  }
5362  else {
5363  // check first if histograms have same bins
5364  if (!SameLimitsAndNBins(newXAxis, *(h->GetXaxis())) ) {
5365  allSameLimits = kFALSE;
5366  // recompute the limits in this case the optimal limits
5367  // The condition to works is that the histogram have same bin with
5368  // and one common bin edge
5369  if (!RecomputeAxisLimits(newXAxis, *(h->GetXaxis()))) {
5370  Error("Merge", "Cannot merge histograms - limits are inconsistent:\n "
5371  "first: (%d, %f, %f), second: (%d, %f, %f)",
5372  newXAxis.GetNbins(), newXAxis.GetXmin(), newXAxis.GetXmax(),
5373  h->GetXaxis()->GetNbins(), h->GetXaxis()->GetXmin(),
5374  h->GetXaxis()->GetXmax());
5375  return -1;
5376  }
5377  }
5378  }
5379  }
5380  if (allHaveLabels) {
5381  THashList* hlabels=h->GetXaxis()->GetLabels();
5382  Bool_t haveOneLabel = (hlabels != 0);
5383  // do here to print message only one time
5384  if (foundLabelHist && allHaveLabels && !haveOneLabel) {
5385  Warning("Merge","Not all histograms have labels. I will ignore labels,"
5386  " falling back to bin numbering mode.");
5387  }
5388 
5389  allHaveLabels &= (haveOneLabel);
5390  // for the error message
5391  if (haveOneLabel) foundLabelHist = kTRUE;
5392  // If histograms have labels but CanExtendAllAxes() is false
5393  // use merging of bin content
5394  if (allHaveLabels && !CanExtendAllAxes()) {
5395  allHaveLabels = kFALSE;
5396  }
5397  // it means
5398  // I could add a check if histogram contains bins without a label
5399  // and with non-zero bin content
5400  // Do we want to support this ???
5401  // only in case the !h->CanExtendAllAxes()
5402  if (allHaveLabels && !h->CanExtendAllAxes()) {
5403  // count number of bins with non-null content
5404  Int_t non_zero_bins = 0;
5405  Int_t nbins = h->GetXaxis()->GetNbins();
5406  if (nbins > hlabels->GetEntries() ) {
5407  for (Int_t i = 1; i <= nbins; i++) {
5408  if (h->RetrieveBinContent(i) != 0 || (fSumw2.fN && h->GetBinError(i) != 0) ) {
5409  non_zero_bins++;
5410  }
5411  }
5412  if (non_zero_bins > hlabels->GetEntries() ) {
5413  Warning("Merge","Histogram %s contains non-empty bins without labels - falling back to bin numbering mode",h->GetName() );
5414  allHaveLabels = kFALSE;
5415  }
5416  }
5417  // else if (h == this) {
5418  // // in case of a full labels histogram set
5419  // // the kCanRebin bit otherwise labels will be lost
5420  // // Info("Merge","Histogram %s has labels but has not the kCanRebin bit set - set the bit on to not loose labels",GetName() );
5421  // // allHaveLabels = kFALSE;
5422  // }
5423  }
5424  }
5425  } while ( ( h = dynamic_cast<TH1*> ( next() ) ) != NULL );
5426 
5427  if (!h && (*next) ) {
5428  Error("Merge","Attempt to merge object of class: %s to a %s",
5429  (*next)->ClassName(),this->ClassName());
5430  return -1;
5431  }
5432 
5433 
5434  next.Reset();
5435  // In the case of histogram with different limits
5436  // newXAxis will now have the new found limits
5437  // but one needs first to clone this histogram to perform the merge
5438  // The clone is not needed when all histograms have the same limits
5439  TH1 * hclone = 0;
5440  if (!allSameLimits) {
5441  // We don't want to add the clone to gDirectory,
5442  // so remove our kMustCleanup bit temporarily
5443  Bool_t mustCleanup = TestBit(kMustCleanup);
5444  if (mustCleanup) ResetBit(kMustCleanup);
5445  hclone = (TH1*)IsA()->New();
5446  hclone->SetDirectory(0);
5447  Copy(*hclone);
5448  if (mustCleanup) SetBit(kMustCleanup);
5449  BufferEmpty(1); // To remove buffer.
5450  Reset(); // BufferEmpty sets limits so we can't use it later.
5451  SetEntries(0);
5452  inlist.AddFirst(hclone);
5453  }
5454 
5455  // set the binning and cell content on the histogram to merge when the histograms do not have the same binning
5456  // and when one of the histogram does not have limits
5457  if (initialLimitsFound && (!allSameLimits || !allHaveLimits )) {
5458  if (newXAxis.GetXbins()->GetSize() != 0) SetBins(newXAxis.GetNbins(), newXAxis.GetXbins()->GetArray());
5459  else SetBins(newXAxis.GetNbins(), newXAxis.GetXmin(), newXAxis.GetXmax());
5460  }
5461 
5462  // std::cout << "Merging on histogram " << GetName() << std::endl;
5463  // std::cout << "Merging flags : allHaveLimits - allHaveLabels - initialLimitsFound - allSameLimits " << std::endl;
5464  // std::cout << " " << allHaveLimits << "\t\t" << allHaveLabels << "\t\t" << initialLimitsFound << "\t\t" << allSameLimits << std::endl;
5465 
5466 
5467  if (!allHaveLimits && !allHaveLabels) {
5468  // fill this histogram with all the data from buffers of histograms without limits
5469  while (TH1* hist = (TH1*)next()) {
5470  // support also case where some histogram have limits and some have the buffer
5471  if ( (hist->GetXaxis()->GetXmin() >= hist->GetXaxis()->GetXmax() ) && hist->fBuffer ) {
5472  // no limits
5473  Int_t nbentries = (Int_t)hist->fBuffer[0];
5474  for (Int_t i = 0; i < nbentries; i++)
5475  Fill(hist->fBuffer[2*i + 2], hist->fBuffer[2*i + 1]);
5476  // Entries from buffers have to be filled one by one
5477  // because FillN doesn't resize histograms.
5478  }
5479  }
5480 
5481  // all histograms have been processed
5482  if (!initialLimitsFound ) {
5483  // here the case where all histograms don't have limits
5484  // In principle I should not have copied in hclone since
5485  // when initialLimitsFound = false then allSameLimits should be true
5486  if (hclone) {
5487  inlist.Remove(hclone);
5488  delete hclone;
5489  }
5490  return (Long64_t) GetEntries();
5491  }
5492 
5493  // In case some of the histograms do not have limits
5494  // I need to remove the buffer
5495  if (fBuffer) BufferEmpty(1);
5496 
5497  next.Reset();
5498  }
5499 
5500  //merge bin contents and errors
5501  // in case when histogram have limits
5502 
5503  Double_t stats[kNstat], totstats[kNstat];
5504  for (Int_t i=0;i<kNstat;i++) {totstats[i] = stats[i] = 0;}
5505  GetStats(totstats);
5507  UInt_t oldExtendBitMask = CanExtendAllAxes();
5508  // reset, otherwise setting the under/overflow will extend the axis and make a mess
5509  if (!allHaveLabels) SetCanExtend(kNoAxis);
5510  while (TH1* hist=(TH1*)next()) {
5511  // process only if the histogram has limits; otherwise it was processed before
5512  // in the case of an existing buffer (see if statement just before)
5513 
5514  //std::cout << "merging histogram " << GetName() << " with " << hist->GetName() << std::endl;
5515 
5516  // skip empty histograms
5517  Double_t histEntries = hist->GetEntries();
5518  if (hist->fTsumw == 0 && histEntries == 0) continue;
5519 
5520 
5521  // merge for labels or histogram with limits
5522  if (allHaveLabels || (hist->GetXaxis()->GetXmin() < hist->GetXaxis()->GetXmax()) ) {
5523  // import statistics
5524  hist->GetStats(stats);
5525  for (Int_t i=0;i<kNstat;i++)
5526  totstats[i] += stats[i];
5527  nentries += histEntries;
5528 
5529  Int_t nx = hist->GetXaxis()->GetNbins();
5530  // loop on bins of the histogram and do the merge
5531  for (Int_t binx = 0; binx <= nx + 1; binx++) {
5532 
5533  Double_t cu = hist->RetrieveBinContent(binx);
5534  Double_t e1sq = 0.0;
5535  Int_t ix = -1;
5536  if (fSumw2.fN) e1sq= hist->GetBinErrorSqUnchecked(binx);
5537  // do only for bins with non null bin content or non-null errors (if Sumw2)
5538  if (TMath::Abs(cu) > 0 || (fSumw2.fN && e1sq > 0 ) ) {
5539  // case of overflow bins
5540  // they do not make sense also in the case of labels
5541  if (!allHaveLabels) {
5542  // case of bins without labels
5543  if (!allSameLimits) {
5544  if ( binx==0 || binx== nx+1) {
5545  Error("Merge", "Cannot merge histograms - the histograms have"
5546  " different limits and undeflows/overflows are present."
5547  " The initial histogram is now broken!");
5548  return -1;
5549  }
5550  // NOTE: in the case of one of the histogram as labels - it is treated as
5551  // an error and it has been flagged before
5552  // since calling FindBin(x) for histo with labels does not make sense
5553  // and the result is unpredictable
5554  ix = fXaxis.FindBin(hist->GetXaxis()->GetBinCenter(binx));
5555  }
5556  else {
5557  // histogram have same limits - no need to call FindBin
5558  ix = binx;
5559  }
5560  } else {
5561  // here only in the case of bins with labels
5562  const char* label=hist->GetXaxis()->GetBinLabel(binx);
5563  // do we need to support case when there are bins with labels and bins without them ??
5564  // NO -then return an error
5565  if (label == 0 ) {
5566  Error("Merge","Histogram %s with labels has NULL label pointer for bin %d",
5567  hist->GetName(),binx );
5568  return -1;
5569  }
5570  // special case for underflow/overflows
5571  if (label[0] == 0 && (binx == 0 || binx ==(nx+1)) ) {
5572  ix = binx;
5573  }
5574  else {
5575  // if bin does not exists FindBin will add it automatically
5576  // by calling LabelsInflate() if the bit is set
5577  // otherwise it will return zero and bin will be merged in underflow/overflow
5578  // Do we want to keep this case ??
5579  ix = fXaxis.FindBin(label);
5580  if (ix <= 0) {
5581  Warning("Merge", "Histogram %s has labels but CanExtendAllAxes() is false - label %s is lost", GetName(), label);
5582  continue;
5583  }
5584  }
5585  }
5586  if (ix >= 0) {
5587  // MERGE here the bin contents
5588  //std::cout << "merging bin " << binx << " into " << ix << " with bin content " << cu << " bin center x = " << GetBinCenter(ix) << std::endl;
5589  if (ix > fNcells )
5590  Fatal("Merge","Fatal error merging histogram %s - bin number is %d and array size is %d",GetName(), ix,fNcells);
5591 
5592  AddBinContent(ix,cu);
5593  if (fSumw2.fN) fSumw2.fArray[ix] += e1sq;
5594  }
5595  }
5596  }
5597  }
5598  }
5599  SetCanExtend(oldExtendBitMask); // restore previous extend state
5600 
5601 
5602  //copy merged stats
5603  PutStats(totstats);
5604  SetEntries(nentries);
5605  if (hclone) {
5606  inlist.Remove(hclone);
5607  delete hclone;
5608  }
5609  return (Long64_t)nentries;
5610 }
5611 
5612 
5613 ////////////////////////////////////////////////////////////////////////////////
5614 /// Performs the operation: this = this*c1*f1
5615 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
5616 ///
5617 /// Only bins inside the function range are recomputed.
5618 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5619 /// you should call Sumw2 before making this operation.
5620 /// This is particularly important if you fit the histogram after TH1::Multiply
5621 ///
5622 /// The function return kFALSE if the Multiply operation failed
5623 
5625 {
5626  if (!f1) {
5627  Error("Add","Attempt to multiply by a non-existing function");
5628  return kFALSE;
5629  }
5630 
5631  // delete buffer if it is there since it will become invalid
5632  if (fBuffer) BufferEmpty(1);
5633 
5634  Int_t nx = GetNbinsX() + 2; // normal bins + uf / of (cells)
5635  Int_t ny = GetNbinsY() + 2;
5636  Int_t nz = GetNbinsZ() + 2;
5637  if (fDimension < 2) ny = 1;
5638  if (fDimension < 3) nz = 1;
5639 
5640  // reset min-maximum
5641  SetMinimum();
5642  SetMaximum();
5643 
5644  // - Loop on bins (including underflows/overflows)
5645  Double_t xx[3];
5646  Double_t *params = 0;
5647  f1->InitArgs(xx,params);
5648 
5649  for (Int_t binz = 0; binz < nz; ++binz) {
5650  xx[2] = fZaxis.GetBinCenter(binz);
5651  for (Int_t biny = 0; biny < ny; ++biny) {
5652  xx[1] = fYaxis.GetBinCenter(biny);
5653  for (Int_t binx = 0; binx < nx; ++binx) {
5654  xx[0] = fXaxis.GetBinCenter(binx);
5655  if (!f1->IsInside(xx)) continue;
5657  Int_t bin = binx + nx * (biny + ny *binz);
5658  Double_t cu = c1*f1->EvalPar(xx);
5659  if (TF1::RejectedPoint()) continue;
5660  UpdateBinContent(bin, RetrieveBinContent(bin) * cu);
5661  if (fSumw2.fN) {
5662  fSumw2.fArray[bin] = cu * cu * GetBinErrorSqUnchecked(bin);
5663  }
5664  }
5665  }
5666  }
5667  ResetStats();
5668  return kTRUE;
5669 }
5670 
5671 
5672 ////////////////////////////////////////////////////////////////////////////////
5673 /// Multiply this histogram by h1.
5674 ///
5675 /// this = this*h1
5676 ///
5677 /// If errors of this are available (TH1::Sumw2), errors are recalculated.
5678 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
5679 /// if not already set.
5680 ///
5681 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5682 /// you should call Sumw2 before making this operation.
5683 /// This is particularly important if you fit the histogram after TH1::Multiply
5684 ///
5685 /// The function return kFALSE if the Multiply operation failed
5686 
5687 Bool_t TH1::Multiply(const TH1 *h1)
5688 {
5689  if (!h1) {
5690  Error("Multiply","Attempt to multiply by a non-existing histogram");
5691  return kFALSE;
5692  }
5693 
5694  // delete buffer if it is there since it will become invalid
5695  if (fBuffer) BufferEmpty(1);
5696 
5697  try {
5698  CheckConsistency(this,h1);
5699  } catch(DifferentNumberOfBins&) {
5700  Error("Multiply","Attempt to multiply histograms with different number of bins");
5701  return kFALSE;
5702  } catch(DifferentAxisLimits&) {
5703  Warning("Multiply","Attempt to multiply histograms with different axis limits");
5704  } catch(DifferentBinLimits&) {
5705  Warning("Multiply","Attempt to multiply histograms with different bin limits");
5706  } catch(DifferentLabels&) {
5707  Warning("Multiply","Attempt to multiply histograms with different labels");
5708  }
5709 
5710  // Create Sumw2 if h1 has Sumw2 set
5711  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
5712 
5713  // - Reset min- maximum
5714  SetMinimum();
5715  SetMaximum();
5716 
5717  // - Loop on bins (including underflows/overflows)
5718  for (Int_t i = 0; i < fNcells; ++i) {
5719  Double_t c0 = RetrieveBinContent(i);
5720  Double_t c1 = h1->RetrieveBinContent(i);
5721  UpdateBinContent(i, c0 * c1);
5722  if (fSumw2.fN) {
5723  fSumw2.fArray[i] = GetBinErrorSqUnchecked(i) * c1 * c1 + h1->GetBinErrorSqUnchecked(i) * c0 * c0;
5724  }
5725  }
5726  ResetStats();
5727  return kTRUE;
5728 }
5729 
5730 
5731 ////////////////////////////////////////////////////////////////////////////////
5732 /// Replace contents of this histogram by multiplication of h1 by h2.
5733 ///
5734 /// this = (c1*h1)*(c2*h2)
5735 ///
5736 /// If errors of this are available (TH1::Sumw2), errors are recalculated.
5737 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
5738 /// if not already set.
5739 ///
5740 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5741 /// you should call Sumw2 before making this operation.
5742 /// This is particularly important if you fit the histogram after TH1::Multiply
5743 ///
5744 /// The function return kFALSE if the Multiply operation failed
5745 
5746 Bool_t TH1::Multiply(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2, Option_t *option)
5747 {
5748  TString opt = option;
5749  opt.ToLower();
5750  // Bool_t binomial = kFALSE;
5751  // if (opt.Contains("b")) binomial = kTRUE;
5752  if (!h1 || !h2) {
5753  Error("Multiply","Attempt to multiply by a non-existing histogram");
5754  return kFALSE;
5755  }
5756 
5757  // delete buffer if it is there since it will become invalid
5758  if (fBuffer) BufferEmpty(1);
5759 
5760  try {
5761  CheckConsistency(h1,h2);
5762  CheckConsistency(this,h1);
5763  } catch(DifferentNumberOfBins&) {
5764  Error("Multiply","Attempt to multiply histograms with different number of bins");
5765  return kFALSE;
5766  } catch(DifferentAxisLimits&) {
5767  Warning("Multiply","Attempt to multiply histograms with different axis limits");
5768  } catch(DifferentBinLimits&) {
5769  Warning("Multiply","Attempt to multiply histograms with different bin limits");
5770  } catch(DifferentLabels&) {
5771  Warning("Multiply","Attempt to multiply histograms with different labels");
5772  }
5773 
5774  // Create Sumw2 if h1 or h2 have Sumw2 set
5775  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
5776 
5777  // - Reset min - maximum
5778  SetMinimum();
5779  SetMaximum();
5780 
5781  // - Loop on bins (including underflows/overflows)
5782  Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
5783  for (Int_t i = 0; i < fNcells; ++i) {
5784  Double_t b1 = h1->RetrieveBinContent(i);
5785  Double_t b2 = h2->RetrieveBinContent(i);
5786  UpdateBinContent(i, c1 * b1 * c2 * b2);
5787  if (fSumw2.fN) {
5788  fSumw2.fArray[i] = c1sq * c2sq * (h1->GetBinErrorSqUnchecked(i) * b2 * b2 + h2->GetBinErrorSqUnchecked(i) * b1 * b1);
5789  }
5790  }
5791  ResetStats();
5792  return kTRUE;
5793 }
5794 
5795 
5796 ////////////////////////////////////////////////////////////////////////////////
5797 /// Control routine to paint any kind of histograms.
5798 ///
5799 /// This function is automatically called by TCanvas::Update.
5800 /// (see TH1::Draw for the list of options)
5801 
5802 void TH1::Paint(Option_t *option)
5803 {
5804  GetPainter(option);
5805 
5806  if (fPainter) {
5807  if (strlen(option) > 0) fPainter->Paint(option);
5808  else fPainter->Paint(fOption.Data());
5809  }
5810 }
5811 
5812 
5813 ////////////////////////////////////////////////////////////////////////////////
5814 /// Rebin this histogram
5815 ///
5816 /// ### case 1 xbins=0
5817 /// If newname is blank (default), the current histogram is modified and
5818 /// a pointer to it is returned.
5819 ///
5820 /// If newname is not blank, the current histogram is not modified, and a
5821 /// new histogram is returned which is a Clone of the current histogram
5822 /// with its name set to newname.
5823 ///
5824 /// The parameter ngroup indicates how many bins of this have to be merged
5825 /// into one bin of the result.
5826 ///
5827 /// If the original histogram has errors stored (via Sumw2), the resulting
5828 /// histograms has new errors correctly calculated.
5829 ///
5830 /// examples: if h1 is an existing TH1F histogram with 100 bins
5831 ///
5832 /// h1->Rebin(); //merges two bins in one in h1: previous contents of h1 are lost
5833 /// h1->Rebin(5); //merges five bins in one in h1
5834 /// TH1F *hnew = h1->Rebin(5,"hnew"); // creates a new histogram hnew
5835 /// // merging 5 bins of h1 in one bin
5836 ///
5837 /// NOTE: If ngroup is not an exact divider of the number of bins,
5838 /// the top limit of the rebinned histogram is reduced
5839 /// to the upper edge of the last bin that can make a complete
5840 /// group. The remaining bins are added to the overflow bin.
5841 /// Statistics will be recomputed from the new bin contents.
5842 ///
5843 /// ### case 2 xbins!=0
5844 /// A new histogram is created (you should specify newname).
5845 /// The parameter ngroup is the number of variable size bins in the created histogram.
5846 /// The array xbins must contain ngroup+1 elements that represent the low-edges
5847 /// of the bins.
5848 /// If the original histogram has errors stored (via Sumw2), the resulting
5849 /// histograms has new errors correctly calculated.
5850 ///
5851 /// NOTE: The bin edges specified in xbins should correspond to bin edges
5852 /// in the original histogram. If a bin edge in the new histogram is
5853 /// in the middle of a bin in the original histogram, all entries in
5854 /// the split bin in the original histogram will be transfered to the
5855 /// lower of the two possible bins in the new histogram. This is
5856 /// probably not what you want.
5857 ///
5858 /// examples: if h1 is an existing TH1F histogram with 100 bins
5859 ///
5860 /// Double_t xbins[25] = {...} array of low-edges (xbins[25] is the upper edge of last bin
5861 /// h1->Rebin(24,"hnew",xbins); //creates a new variable bin size histogram hnew
5862 
5863 TH1 *TH1::Rebin(Int_t ngroup, const char*newname, const Double_t *xbins)
5864 {
5865  Int_t nbins = fXaxis.GetNbins();
5866  Double_t xmin = fXaxis.GetXmin();
5867  Double_t xmax = fXaxis.GetXmax();
5868  if ((ngroup <= 0) || (ngroup > nbins)) {
5869  Error("Rebin", "Illegal value of ngroup=%d",ngroup);
5870  return 0;
5871  }
5872 
5873  if (fDimension > 1 || InheritsFrom(TProfile::Class())) {
5874  Error("Rebin", "Operation valid on 1-D histograms only");
5875  return 0;
5876  }
5877  if (!newname && xbins) {
5878  Error("Rebin","if xbins is specified, newname must be given");
5879  return 0;
5880  }
5881 
5882  Int_t newbins = nbins/ngroup;
5883  if (!xbins) {
5884  Int_t nbg = nbins/ngroup;
5885  if (nbg*ngroup != nbins) {
5886  Warning("Rebin", "ngroup=%d is not an exact divider of nbins=%d.",ngroup,nbins);
5887  }
5888  }
5889  else {
5890  // in the case that xbins is given (rebinning in variable bins), ngroup is
5891  // the new number of bins and number of grouped bins is not constant.
5892  // when looping for setting the contents for the new histogram we
5893  // need to loop on all bins of original histogram. Then set ngroup=nbins
5894  newbins = ngroup;
5895  ngroup = nbins;
5896  }
5897 
5898  // Save old bin contents into a new array
5899  Double_t entries = fEntries;
5900  Double_t *oldBins = new Double_t[nbins+2];
5901  Int_t bin, i;
5902  for (bin=0;bin<nbins+2;bin++) oldBins[bin] = RetrieveBinContent(bin);
5903  Double_t *oldErrors = 0;
5904  if (fSumw2.fN != 0) {
5905  oldErrors = new Double_t[nbins+2];
5906  for (bin=0;bin<nbins+2;bin++) oldErrors[bin] = GetBinError(bin);
5907  }
5908  // rebin will not include underflow/overflow if new axis range is larger than old axis range
5909  if (xbins) {
5910  if (xbins[0] < fXaxis.GetXmin() && oldBins[0] != 0 )
5911  Warning("Rebin","underflow entries will not be used when rebinning");
5912  if (xbins[newbins] > fXaxis.GetXmax() && oldBins[nbins+1] != 0 )
5913  Warning("Rebin","overflow entries will not be used when rebinning");
5914  }
5915 
5916 
5917  // create a clone of the old histogram if newname is specified
5918  TH1 *hnew = this;
5919  if ((newname && strlen(newname) > 0) || xbins) {
5920  hnew = (TH1*)Clone(newname);
5921  }
5922 
5923  //reset can extend bit to avoid an axis extension in SetBinContent
5924  UInt_t oldExtendBitMask = hnew->SetCanExtend(kNoAxis);
5925 
5926  // save original statistics
5927  Double_t stat[kNstat];
5928  GetStats(stat);
5929  bool resetStat = false;
5930  // change axis specs and rebuild bin contents array::RebinAx
5931  if(!xbins && (newbins*ngroup != nbins)) {
5932  xmax = fXaxis.GetBinUpEdge(newbins*ngroup);
5933  resetStat = true; //stats must be reset because top bins will be moved to overflow bin
5934  }
5935  // save the TAttAxis members (reset by SetBins)
5936  Int_t nDivisions = fXaxis.GetNdivisions();
5937  Color_t axisColor = fXaxis.GetAxisColor();
5938  Color_t labelColor = fXaxis.GetLabelColor();
5939  Style_t labelFont = fXaxis.GetLabelFont();
5940  Float_t labelOffset = fXaxis.GetLabelOffset();
5941  Float_t labelSize = fXaxis.GetLabelSize();
5942  Float_t tickLength = fXaxis.GetTickLength();
5943  Float_t titleOffset = fXaxis.GetTitleOffset();
5944  Float_t titleSize = fXaxis.GetTitleSize();
5945  Color_t titleColor = fXaxis.GetTitleColor();
5946  Style_t titleFont = fXaxis.GetTitleFont();
5947 
5948  if(!xbins && (fXaxis.GetXbins()->GetSize() > 0)){ // variable bin sizes
5949  Double_t *bins = new Double_t[newbins+1];
5950  for(i = 0; i <= newbins; ++i) bins[i] = fXaxis.GetBinLowEdge(1+i*ngroup);
5951  hnew->SetBins(newbins,bins); //this also changes errors array (if any)
5952  delete [] bins;
5953  } else if (xbins) {
5954  hnew->SetBins(newbins,xbins);
5955  } else {
5956  hnew->SetBins(newbins,xmin,xmax);
5957  }
5958 
5959  // Restore axis attributes
5960  fXaxis.SetNdivisions(nDivisions);
5961  fXaxis.SetAxisColor(axisColor);
5962  fXaxis.SetLabelColor(labelColor);
5963  fXaxis.SetLabelFont(labelFont);
5964  fXaxis.SetLabelOffset(labelOffset);
5965  fXaxis.SetLabelSize(labelSize);
5966  fXaxis.SetTickLength(tickLength);
5967  fXaxis.SetTitleOffset(titleOffset);
5968  fXaxis.SetTitleSize(titleSize);
5969  fXaxis.SetTitleColor(titleColor);
5970  fXaxis.SetTitleFont(titleFont);
5971 
5972  // copy merged bin contents (ignore under/overflows)
5973  // Start merging only once the new lowest edge is reached
5974  Int_t startbin = 1;
5975  const Double_t newxmin = hnew->GetXaxis()->GetBinLowEdge(1);
5976  while( fXaxis.GetBinCenter(startbin) < newxmin && startbin <= nbins ) {
5977  startbin++;
5978  }
5979  Int_t oldbin = startbin;
5980  Double_t binContent, binError;
5981  for (bin = 1;bin<=newbins;bin++) {
5982  binContent = 0;
5983  binError = 0;
5984  Int_t imax = ngroup;
5985  Double_t xbinmax = hnew->GetXaxis()->GetBinUpEdge(bin);
5986  for (i=0;i<ngroup;i++) {
5987  if( (oldbin+i > nbins) ||
5988  ( hnew != this && (fXaxis.GetBinCenter(oldbin+i) > xbinmax)) ) {
5989  imax = i;
5990  break;
5991  }
5992  binContent += oldBins[oldbin+i];
5993  if (oldErrors) binError += oldErrors[oldbin+i]*oldErrors[oldbin+i];
5994  }
5995  hnew->SetBinContent(bin,binContent);
5996  if (oldErrors) hnew->SetBinError(bin,TMath::Sqrt(binError));
5997  oldbin += imax;
5998  }
5999 
6000  // sum underflow and overflow contents until startbin
6001  binContent = 0;
6002  binError = 0;
6003  for (i = 0; i < startbin; ++i) {
6004  binContent += oldBins[i];
6005  if (oldErrors) binError += oldErrors[i]*oldErrors[i];
6006  }
6007  hnew->SetBinContent(0,binContent);
6008  if (oldErrors) hnew->SetBinError(0,TMath::Sqrt(binError));
6009  // sum overflow
6010  binContent = 0;
6011  binError = 0;
6012  for (i = oldbin; i <= nbins+1; ++i) {
6013  binContent += oldBins[i];
6014  if (oldErrors) binError += oldErrors[i]*oldErrors[i];
6015  }
6016  hnew->SetBinContent(newbins+1,binContent);
6017  if (oldErrors) hnew->SetBinError(newbins+1,TMath::Sqrt(binError));
6018 
6019  hnew->SetCanExtend(oldExtendBitMask); // restore previous state
6020 
6021  // restore statistics and entries modified by SetBinContent
6022  hnew->SetEntries(entries);
6023  if (!resetStat) hnew->PutStats(stat);
6024  delete [] oldBins;
6025  if (oldErrors) delete [] oldErrors;
6026  return hnew;
6027 }
6028 
6029 
6030 ////////////////////////////////////////////////////////////////////////////////
6031 /// finds new limits for the axis so that *point* is within the range and
6032 /// the limits are compatible with the previous ones (see TH1::Merge).
6033 /// new limits are put into *newMin* and *newMax* variables.
6034 /// axis - axis whose limits are to be recomputed
6035 /// point - point that should fit within the new axis limits
6036 /// newMin - new minimum will be stored here
6037 /// newMax - new maximum will be stored here.
6038 /// false if failed (e.g. if the initial axis limits are wrong
6039 /// or the new range is more than 2^64 times the old one).
6040 
6041 Bool_t TH1::FindNewAxisLimits(const TAxis* axis, const Double_t point, Double_t& newMin, Double_t &newMax)
6042 {
6043  Double_t xmin = axis->GetXmin();
6044  Double_t xmax = axis->GetXmax();
6045  if (xmin >= xmax) return kFALSE;
6046  Double_t range = xmax-xmin;
6047  Double_t binsize = range / axis->GetNbins();
6048 
6049  //recompute new axis limits by doubling the current range
6050  Int_t ntimes = 0;
6051  while (point < xmin) {
6052  if (ntimes++ > 64)
6053  return kFALSE;
6054  xmin = xmin - range;
6055  range *= 2;
6056  binsize *= 2;
6057  // // make sure that the merging will be correct
6058  // if ( xmin / binsize - TMath::Floor(xmin / binsize) >= 0.5) {
6059  // xmin += 0.5 * binsize;
6060  // xmax += 0.5 * binsize; // won't work with a histogram with only one bin, but I don't care
6061  // }
6062  }
6063  while (point >= xmax) {
6064  if (ntimes++ > 64)
6065  return kFALSE;
6066  xmax = xmax + range;
6067  range *= 2;
6068  binsize *= 2;
6069  // // make sure that the merging will be correct
6070  // if ( xmin / binsize - TMath::Floor(xmin / binsize) >= 0.5) {
6071  // xmin -= 0.5 * binsize;
6072  // xmax -= 0.5 * binsize; // won't work with a histogram with only one bin, but I don't care
6073  // }
6074  }
6075  newMin = xmin;
6076  newMax = xmax;
6077  // Info("FindNewAxisLimits", "OldAxis: (%lf, %lf), new: (%lf, %lf), point: %lf",
6078  // axis->GetXmin(), axis->GetXmax(), xmin, xmax, point);
6079 
6080  return kTRUE;
6081 }
6082 
6083 
6084 ////////////////////////////////////////////////////////////////////////////////
6085 /// Histogram is resized along axis such that x is in the axis range.
6086 /// The new axis limits are recomputed by doubling iteratively
6087 /// the current axis range until the specified value x is within the limits.
6088 /// The algorithm makes a copy of the histogram, then loops on all bins
6089 /// of the old histogram to fill the extended histogram.
6090 /// Takes into account errors (Sumw2) if any.
6091 /// The algorithm works for 1-d, 2-D and 3-D histograms.
6092 /// The axis must be extendable before invoking this function.
6093 /// Ex: h->GetXaxis()->SetCanExtend(kTRUE);
6094 
6095 void TH1::ExtendAxis(Double_t x, TAxis *axis)
6096 {
6097  if (!axis->CanExtend()) return;
6098  if (TMath::IsNaN(x)) { // x may be a NaN
6100  return;
6101  }
6102 
6103  if (axis->GetXmin() >= axis->GetXmax()) return;
6104  if (axis->GetNbins() <= 0) return;
6105 
6106  Double_t xmin, xmax;
6107  if (!FindNewAxisLimits(axis, x, xmin, xmax))
6108  return;
6109 
6110  //save a copy of this histogram
6111  TH1 *hold = (TH1*)IsA()->New();
6112  hold->SetDirectory(0);
6113  Copy(*hold);
6114  //set new axis limits
6115  axis->SetLimits(xmin,xmax);
6116 
6117  Int_t nbinsx = fXaxis.GetNbins();
6118  Int_t nbinsy = fYaxis.GetNbins();
6119  Int_t nbinsz = fZaxis.GetNbins();
6120 
6121  //now loop on all bins and refill
6122  Double_t bx,by,bz;
6123  Int_t errors = GetSumw2N();
6124  Int_t ix,iy,iz,ibin,binx,biny,binz,bin;
6125  Reset("ICE"); //reset only Integral, contents and Errors
6126  for (binz=1;binz<=nbinsz;binz++) {
6127  bz = hold->GetZaxis()->GetBinCenter(binz);
6128  iz = fZaxis.FindFixBin(bz);
6129  for (biny=1;biny<=nbinsy;biny++) {
6130  by = hold->GetYaxis()->GetBinCenter(biny);
6131  iy = fYaxis.FindFixBin(by);
6132  for (binx=1;binx<=nbinsx;binx++) {
6133  bx = hold->GetXaxis()->GetBinCenter(binx);
6134  ix = fXaxis.FindFixBin(bx);
6135  bin = hold->GetBin(binx,biny,binz);
6136  ibin= GetBin(ix,iy,iz);
6137  AddBinContent(ibin, hold->RetrieveBinContent(bin));
6138  if (errors) {
6139  fSumw2.fArray[ibin] += hold->GetBinErrorSqUnchecked(bin);
6140  }
6141  }
6142  }
6143  }
6144  delete hold;
6145 }
6146 
6147 
6148 ////////////////////////////////////////////////////////////////////////////////
6149 /// Recursively remove object from the list of functions
6150 
6151 void TH1::RecursiveRemove(TObject *obj)
6152 {
6153  if (fFunctions) {
6155  }
6156 }
6157 
6158 
6159 ////////////////////////////////////////////////////////////////////////////////
6160 /// Multiply this histogram by a constant c1.
6161 ///
6162 ///this = c1*this
6163 ///
6164 /// Note that both contents and errors(if any) are scaled.
6165 /// This function uses the services of TH1::Add
6166 ///
6167 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
6168 /// you should call Sumw2 before making this operation.
6169 /// This is particularly important if you fit the histogram after TH1::Scale
6170 ///
6171 /// One can scale an histogram such that the bins integral is equal to
6172 /// the normalization parameter via TH1::Scale(Double_t norm), where norm
6173 /// is the desired normalization divided by the integral of the histogram.
6174 ///
6175 /// If option contains "width" the bin contents and errors are divided
6176 /// by the bin width.
6177 
6178 void TH1::Scale(Double_t c1, Option_t *option)
6179 {
6181  TString opt = option; opt.ToLower();
6182  if (opt.Contains("width")) Add(this, this, c1, -1);
6183  else {
6184  if (fBuffer) BufferEmpty(1);
6185  for(Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, c1 * RetrieveBinContent(i));
6186  if (fSumw2.fN) for(Int_t i = 0; i < fNcells; ++i) fSumw2.fArray[i] *= (c1 * c1); // update errors
6187  SetMinimum(); SetMaximum(); // minimum and maximum value will be recalculated the next time
6188  }
6189 
6190  // if contours set, must also scale contours
6191  Int_t ncontours = GetContour();
6192  if (ncontours == 0) return;
6193  Double_t* levels = fContour.GetArray();
6194  for (Int_t i = 0; i < ncontours; ++i) levels[i] *= c1;
6195 }
6196 
6197 
6198 ////////////////////////////////////////////////////////////////////////////////
6199 /// returns true if all axes are extendable
6200 
6202 {
6203  Bool_t canExtend = fXaxis.CanExtend();
6204  if (GetDimension() > 1) canExtend &= fYaxis.CanExtend();
6205  if (GetDimension() > 2) canExtend &= fZaxis.CanExtend();
6206 
6207  return canExtend;
6208 }
6209 
6210 
6211 ////////////////////////////////////////////////////////////////////////////////
6212 /// make the histogram axes extendable / not extendable according to the bit mask
6213 /// returns the previous bit mask specifying which axes are extendable
6214 
6215 UInt_t TH1::SetCanExtend(UInt_t extendBitMask)
6216 {
6217  UInt_t oldExtendBitMask = kNoAxis;
6218 
6219  if (fXaxis.CanExtend()) oldExtendBitMask |= kXaxis;
6220  if (extendBitMask & kXaxis) fXaxis.SetCanExtend(kTRUE);
6221  else fXaxis.SetCanExtend(kFALSE);
6222 
6223  if (GetDimension() > 1) {
6224  if (fYaxis.CanExtend()) oldExtendBitMask |= kYaxis;
6225  if (extendBitMask & kYaxis) fYaxis.SetCanExtend(kTRUE);
6226  else fYaxis.SetCanExtend(kFALSE);
6227  }
6228 
6229  if (GetDimension() > 2) {
6230  if (fZaxis.CanExtend()) oldExtendBitMask |= kZaxis;
6231  if (extendBitMask & kZaxis) fZaxis.SetCanExtend(kTRUE);
6232  else fZaxis.SetCanExtend(kFALSE);
6233  }
6234 
6235  return oldExtendBitMask;
6236 }
6237 
6238 
6239 ////////////////////////////////////////////////////////////////////////////////
6240 /// static function to set the default buffer size for automatic histograms.
6241 /// When an histogram is created with one of its axis lower limit greater
6242 /// or equal to its upper limit, the function SetBuffer is automatically
6243 /// called with the default buffer size.
6244 
6245 void TH1::SetDefaultBufferSize(Int_t buffersize)
6246 {
6247  fgBufferSize = buffersize > 0 ? buffersize : 0;
6248 }
6249 
6250 
6251 ////////////////////////////////////////////////////////////////////////////////
6252 /// static function.
6253 /// When this static function is called with sumw2=kTRUE, all new
6254 /// histograms will automatically activate the storage
6255 /// of the sum of squares of errors, ie TH1::Sumw2 is automatically called.
6256 
6257 void TH1::SetDefaultSumw2(Bool_t sumw2)
6258 {
6260 }
6261 
6262 
6263 ////////////////////////////////////////////////////////////////////////////////
6264 /// Change (i.e. set) the title
6265 ///
6266 ///if title is in the form "stringt;stringx;stringy;stringz"
6267 ///the histogram title is set to stringt, the x axis title to stringx,
6268 ///the y axis title to stringy, and the z axis title to stringz.
6269 ///To insert the character ";" in one of the titles, one should use "#;"
6270 ///or "#semicolon".
6271 
6272 void TH1::SetTitle(const char *title)
6273 {
6274  fTitle = title;
6275  fTitle.ReplaceAll("#;",2,"#semicolon",10);
6276 
6277  // Decode fTitle. It may contain X, Y and Z titles
6278  TString str1 = fTitle, str2;
6279  Int_t isc = str1.Index(";");
6280  Int_t lns = str1.Length();
6281 
6282  if (isc >=0 ) {
6283  fTitle = str1(0,isc);
6284  str1 = str1(isc+1, lns);
6285  isc = str1.Index(";");
6286  if (isc >=0 ) {
6287  str2 = str1(0,isc);
6288  str2.ReplaceAll("#semicolon",10,";",1);
6289  fXaxis.SetTitle(str2.Data());
6290  lns = str1.Length();
6291  str1 = str1(isc+1, lns);
6292  isc = str1.Index(";");
6293  if (isc >=0 ) {
6294  str2 = str1(0,isc);
6295  str2.ReplaceAll("#semicolon",10,";",1);
6296  fYaxis.SetTitle(str2.Data());
6297  lns = str1.Length();
6298  str1 = str1(isc+1, lns);
6299  str1.ReplaceAll("#semicolon",10,";",1);
6300  fZaxis.SetTitle(str1.Data());
6301  } else {
6302  str1.ReplaceAll("#semicolon",10,";",1);
6303  fYaxis.SetTitle(str1.Data());
6304  }
6305  } else {
6306  str1.ReplaceAll("#semicolon",10,";",1);
6307  fXaxis.SetTitle(str1.Data());
6308  }
6309  }
6310 
6311  fTitle.ReplaceAll("#semicolon",10,";",1);
6312 
6313  if (gPad && TestBit(kMustCleanup)) gPad->Modified();
6314 }
6315 
6316 
6317 ////////////////////////////////////////////////////////////////////////////////
6318 /// smooth array xx, translation of Hbook routine hsmoof.F
6319 /// based on algorithm 353QH twice presented by J. Friedman
6320 /// in Proc.of the 1974 CERN School of Computing, Norway, 11-24 August, 1974.
6321 
6322 void TH1::SmoothArray(Int_t nn, Double_t *xx, Int_t ntimes)
6323 {
6324  if (nn < 3 ) {
6325  ::Error("SmoothArray","Need at least 3 points for smoothing: n = %d",nn);
6326  return;
6327  }
6328 
6329  Int_t ii;
6330  Double_t hh[6] = {0,0,0,0,0,0};
6331 
6332  std::vector<double> yy(nn);
6333  std::vector<double> zz(nn);
6334  std::vector<double> rr(nn);
6335 
6336  for (Int_t pass=0;pass<ntimes;pass++) {
6337  // first copy original data into temp array
6338  std::copy(xx, xx+nn, zz.begin() );
6339 
6340 
6341 
6342  for (int noent = 0; noent < 2; ++noent) { // run algorithm two times
6343 
6344  // do 353 i.e. running median 3, 5, and 3 in a single loop
6345  for (int kk = 0; kk < 3; kk++) {
6346  std::copy(zz.begin(), zz.end(), yy.begin());
6347  int medianType = (kk != 1) ? 3 : 5;
6348  int ifirst = (kk != 1 ) ? 1 : 2;
6349  int ilast = (kk != 1 ) ? nn-1 : nn -2;
6350  //nn2 = nn - ik - 1;
6351  // do all elements beside the first and last point for median 3
6352  // and first two and last 2 for median 5
6353  for ( ii = ifirst; ii < ilast; ii++) {
6354  assert(ii - ifirst >= 0);
6355  for (int jj = 0; jj < medianType; jj++) {
6356  hh[jj] = yy[ii - ifirst + jj ];
6357  }
6358  zz[ii] = TMath::Median(medianType, hh);
6359  }
6360 
6361  if (kk == 0) { // first median 3
6362  // first point
6363  hh[0] = zz[1];
6364  hh[1] = zz[0];
6365  hh[2] = 3*zz[1] - 2*zz[2];
6366  zz[0] = TMath::Median(3, hh);
6367  // last point
6368  hh[0] = zz[nn - 2];
6369  hh[1] = zz[nn - 1];
6370  hh[2] = 3*zz[nn - 2] - 2*zz[nn - 3];
6371  zz[nn - 1] = TMath::Median(3, hh);
6372  }
6373 
6374 
6375  if (kk == 1) { // median 5
6376  for (ii = 0; ii < 3; ii++) {
6377  hh[ii] = yy[ii];
6378  }
6379  zz[1] = TMath::Median(3, hh);
6380  // last two points
6381  for (ii = 0; ii < 3; ii++) {
6382  hh[ii] = yy[nn - 3 + ii];
6383  }
6384  zz[nn - 2] = TMath::Median(3, hh);
6385  }
6386 
6387  }
6388 
6389  std::copy ( zz.begin(), zz.end(), yy.begin() );
6390 
6391  // quadratic interpolation for flat segments
6392  for (ii = 2; ii < (nn - 2); ii++) {
6393  if (zz[ii - 1] != zz[ii]) continue;
6394  if (zz[ii] != zz[ii + 1]) continue;
6395  hh[0] = zz[ii - 2] - zz[ii];
6396  hh[1] = zz[ii + 2] - zz[ii];
6397  if (hh[0] * hh[1] <= 0) continue;
6398  int jk = 1;
6399  if ( TMath::Abs(hh[1]) > TMath::Abs(hh[0]) ) jk = -1;
6400  yy[ii] = -0.5*zz[ii - 2*jk] + zz[ii]/0.75 + zz[ii + 2*jk] /6.;
6401  yy[ii + jk] = 0.5*(zz[ii + 2*jk] - zz[ii - 2*jk]) + zz[ii];
6402  }
6403 
6404  // running means
6405  //std::copy(zz.begin(), zz.end(), yy.begin());
6406  for (ii = 1; ii < nn - 1; ii++) {
6407  zz[ii] = 0.25*yy[ii - 1] + 0.5*yy[ii] + 0.25*yy[ii + 1];
6408  }
6409  zz[0] = yy[0];
6410  zz[nn - 1] = yy[nn - 1];
6411 
6412  if (noent == 0) {
6413 
6414  // save computed values
6415  std::copy(zz.begin(), zz.end(), rr.begin());
6416 
6417  // COMPUTE residuals
6418  for (ii = 0; ii < nn; ii++) {
6419  zz[ii] = xx[ii] - zz[ii];
6420  }
6421  }
6422 
6423  } // end loop on noent
6424 
6425 
6426  double xmin = TMath::MinElement(nn,xx);
6427  for (ii = 0; ii < nn; ii++) {
6428  if (xmin < 0) xx[ii] = rr[ii] + zz[ii];
6429  // make smoothing defined positive - not better using 0 ?
6430  else xx[ii] = TMath::Max((rr[ii] + zz[ii]),0.0 );
6431  }
6432  }
6433 }
6434 
6435 
6436 ////////////////////////////////////////////////////////////////////////////////
6437 /// Smooth bin contents of this histogram.
6438 /// if option contains "R" smoothing is applied only to the bins
6439 /// defined in the X axis range (default is to smooth all bins)
6440 /// Bin contents are replaced by their smooth values.
6441 /// Errors (if any) are not modified.
6442 /// the smoothing procedure is repeated ntimes (default=1)
6443 
6444 void TH1::Smooth(Int_t ntimes, Option_t *option)
6445 {
6446  if (fDimension != 1) {
6447  Error("Smooth","Smooth only supported for 1-d histograms");
6448  return;
6449  }
6450  Int_t nbins = fXaxis.GetNbins();
6451  if (nbins < 3) {
6452  Error("Smooth","Smooth only supported for histograms with >= 3 bins. Nbins = %d",nbins);
6453  return;
6454  }
6455 
6456  // delete buffer if it is there since it will become invalid
6457  if (fBuffer) BufferEmpty(1);
6458 
6459  Int_t firstbin = 1, lastbin = nbins;
6460  TString opt = option;
6461  opt.ToLower();
6462  if (opt.Contains("r")) {
6463  firstbin= fXaxis.GetFirst();
6464  lastbin = fXaxis.GetLast();
6465  }
6466  nbins = lastbin - firstbin + 1;
6467  Double_t *xx = new Double_t[nbins];
6468  Double_t nent = fEntries;
6469  Int_t i;
6470  for (i=0;i<nbins;i++) {
6471  xx[i] = RetrieveBinContent(i+firstbin);
6472  }
6473 
6474  TH1::SmoothArray(nbins,xx,ntimes);
6475 
6476  for (i=0;i<nbins;i++) {
6477  UpdateBinContent(i+firstbin,xx[i]);
6478  }
6479  fEntries = nent;
6480  delete [] xx;
6481 
6482  if (gPad) gPad->Modified();
6483 }
6484 
6485 
6486 ////////////////////////////////////////////////////////////////////////////////
6487 /// if flag=kTRUE, underflows and overflows are used by the Fill functions
6488 /// in the computation of statistics (mean value, StdDev).
6489 /// By default, underflows or overflows are not used.
6490 
6491 void TH1::StatOverflows(Bool_t flag)
6492 {
6494 }
6495 
6496 
6497 ////////////////////////////////////////////////////////////////////////////////
6498 /// Stream a class object.
6499 
6500 void TH1::Streamer(TBuffer &b)
6501 {
6502  if (b.IsReading()) {
6503  UInt_t R__s, R__c;
6504  Version_t R__v = b.ReadVersion(&R__s, &R__c);
6505  if (fDirectory) fDirectory->Remove(this);
6506  fDirectory = 0;
6507  if (R__v > 2) {
6508  b.ReadClassBuffer(TH1::Class(), this, R__v, R__s, R__c);
6509 
6511  fXaxis.SetParent(this);
6512  fYaxis.SetParent(this);
6513  fZaxis.SetParent(this);
6514  TIter next(fFunctions);
6515  TObject *obj;
6516  while ((obj=next())) {
6517  if (obj->InheritsFrom(TF1::Class())) ((TF1*)obj)->SetParent(this);
6518  }
6519  return;
6520  }
6521  //process old versions before automatic schema evolution
6522  TNamed::Streamer(b);
6523  TAttLine::Streamer(b);
6524  TAttFill::Streamer(b);
6525  TAttMarker::Streamer(b);
6526  b >> fNcells;
6527  fXaxis.Streamer(b);
6528  fYaxis.Streamer(b);
6529  fZaxis.Streamer(b);
6530  fXaxis.SetParent(this);
6531  fYaxis.SetParent(this);
6532  fZaxis.SetParent(this);
6533  b >> fBarOffset;
6534  b >> fBarWidth;
6535  b >> fEntries;
6536  b >> fTsumw;
6537  b >> fTsumw2;
6538  b >> fTsumwx;
6539  b >> fTsumwx2;
6540  if (R__v < 2) {
6541  Float_t maximum, minimum, norm;
6542  Float_t *contour=0;
6543  b >> maximum; fMaximum = maximum;
6544  b >> minimum; fMinimum = minimum;
6545  b >> norm; fNormFactor = norm;
6546  Int_t n = b.ReadArray(contour);
6547  fContour.Set(n);
6548  for (Int_t i=0;i<n;i++) fContour.fArray[i] = contour[i];
6549  delete [] contour;
6550  } else {
6551  b >> fMaximum;
6552  b >> fMinimum;
6553  b >> fNormFactor;
6554  fContour.Streamer(b);
6555  }
6556  fSumw2.Streamer(b);
6557  fOption.Streamer(b);
6558  fFunctions->Delete();
6559  fFunctions->Streamer(b);
6560  b.CheckByteCount(R__s, R__c, TH1::IsA());
6561 
6562  } else {
6563  b.WriteClassBuffer(TH1::Class(),this);
6564  }
6565 }
6566 
6567 
6568 ////////////////////////////////////////////////////////////////////////////////
6569 /// Print some global quantities for this histogram.
6570 /// \param[in] option
6571 /// - "base" is given, number of bins and ranges are also printed
6572 /// - "range" is given, bin contents and errors are also printed
6573 /// for all bins in the current range (default 1-->nbins)
6574 /// - "all" is given, bin contents and errors are also printed
6575 /// for all bins including under and overflows.
6576 
6577 void TH1::Print(Option_t *option) const
6578 {
6579  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
6580  printf( "TH1.Print Name = %s, Entries= %d, Total sum= %g\n",GetName(),Int_t(fEntries),GetSumOfWeights());
6581  TString opt = option;
6582  opt.ToLower();
6583  Int_t all;
6584  if (opt.Contains("all")) all = 0;
6585  else if (opt.Contains("range")) all = 1;
6586  else if (opt.Contains("base")) all = 2;
6587  else return;
6588 
6589  Int_t bin, binx, biny, binz;
6590  Int_t firstx=0,lastx=0,firsty=0,lasty=0,firstz=0,lastz=0;
6591  if (all == 0) {
6592  lastx = fXaxis.GetNbins()+1;
6593  if (fDimension > 1) lasty = fYaxis.GetNbins()+1;
6594  if (fDimension > 2) lastz = fZaxis.GetNbins()+1;
6595  } else {
6596  firstx = fXaxis.GetFirst(); lastx = fXaxis.GetLast();
6597  if (fDimension > 1) {firsty = fYaxis.GetFirst(); lasty = fYaxis.GetLast();}
6598  if (fDimension > 2) {firstz = fZaxis.GetFirst(); lastz = fZaxis.GetLast();}
6599  }
6600 
6601  if (all== 2) {
6602  printf(" Title = %s\n", GetTitle());
6603  printf(" NbinsX= %d, xmin= %g, xmax=%g", fXaxis.GetNbins(), fXaxis.GetXmin(), fXaxis.GetXmax());
6604  if( fDimension > 1) printf(", NbinsY= %d, ymin= %g, ymax=%g", fYaxis.GetNbins(), fYaxis.GetXmin(), fYaxis.GetXmax());
6605  if( fDimension > 2) printf(", NbinsZ= %d, zmin= %g, zmax=%g", fZaxis.GetNbins(), fZaxis.GetXmin(), fZaxis.GetXmax());
6606  printf("\n");
6607  return;
6608  }
6609 
6610  Double_t w,e;
6611  Double_t x,y,z;
6612  if (fDimension == 1) {
6613  for (binx=firstx;binx<=lastx;binx++) {
6614  x = fXaxis.GetBinCenter(binx);
6615  w = RetrieveBinContent(binx);
6616  e = GetBinError(binx);
6617  if(fSumw2.fN) printf(" fSumw[%d]=%g, x=%g, error=%g\n",binx,w,x,e);
6618  else printf(" fSumw[%d]=%g, x=%g\n",binx,w,x);
6619  }
6620  }
6621  if (fDimension == 2) {
6622  for (biny=firsty;biny<=lasty;biny++) {
6623  y = fYaxis.GetBinCenter(biny);
6624  for (binx=firstx;binx<=lastx;binx++) {
6625  bin = GetBin(binx,biny);
6626  x = fXaxis.GetBinCenter(binx);
6627  w = RetrieveBinContent(bin);
6628  e = GetBinError(bin);
6629  if(fSumw2.fN) printf(" fSumw[%d][%d]=%g, x=%g, y=%g, error=%g\n",binx,biny,w,x,y,e);
6630  else printf(" fSumw[%d][%d]=%g, x=%g, y=%g\n",binx,biny,w,x,y);
6631  }
6632  }
6633  }
6634  if (fDimension == 3) {
6635  for (binz=firstz;binz<=lastz;binz++) {
6636  z = fZaxis.GetBinCenter(binz);
6637  for (biny=firsty;biny<=lasty;biny++) {
6638  y = fYaxis.GetBinCenter(biny);
6639  for (binx=firstx;binx<=lastx;binx++) {
6640  bin = GetBin(binx,biny,binz);
6641  x = fXaxis.GetBinCenter(binx);
6642  w = RetrieveBinContent(bin);
6643  e = GetBinError(bin);
6644  if(fSumw2.fN) printf(" fSumw[%d][%d][%d]=%g, x=%g, y=%g, z=%g, error=%g\n",binx,biny,binz,w,x,y,z,e);
6645  else printf(" fSumw[%d][%d][%d]=%g, x=%g, y=%g, z=%g\n",binx,biny,binz,w,x,y,z);
6646  }
6647  }
6648  }
6649  }
6650 }
6651 
6652 
6653 ////////////////////////////////////////////////////////////////////////////////
6654 /// Using the current bin info, recompute the arrays for contents and errors
6655 
6656 void TH1::Rebuild(Option_t *)
6657 {
6659  if (fSumw2.fN) {
6660  fSumw2.Set(fNcells);
6661  }
6662 }
6663 
6664 
6665 ////////////////////////////////////////////////////////////////////////////////
6666 /// Reset this histogram: contents, errors, etc.
6667 /// \param[in] option
6668 /// - "ICE" is specified, resets only Integral, Contents and Errors.
6669 /// - "ICES" is specified, resets only Integral, Contents , Errors and Statistics
6670 /// This option is used
6671 /// - "M" is specified, resets also Minimum and Maximum
6672 
6673 void TH1::Reset(Option_t *option)
6674 {
6675  // The option "ICE" is used when extending the histogram (in ExtendAxis, LabelInflate, etc..)
6676  // The option "ICES is used in combination with the buffer (see BufferEmpty and BufferFill)
6677 
6678  TString opt = option;
6679  opt.ToUpper();
6680  fSumw2.Reset();
6681  if (fIntegral) {delete [] fIntegral; fIntegral = 0;}
6682 
6683  if (opt.Contains("M")) {
6684  SetMinimum();
6685  SetMaximum();
6686  }
6687 
6688  if (opt.Contains("ICE") && !opt.Contains("S")) return;
6689 
6690  // Setting fBuffer[0] = 0 is like resetting the buffer but not deleting it
6691  // But what is the sense of calling BufferEmpty() ? For making the axes ?
6692  // BufferEmpty will update contents that later will be
6693  // reset in calling TH1D::Reset. For this we need to reset the stats afterwards
6694  // It may be needed for computing the axis limits....
6695  if (fBuffer) {BufferEmpty(); fBuffer[0] = 0;}
6696 
6697  // need to reset also the statistics
6698  // (needs to be done after calling BufferEmpty() )
6699  fTsumw = 0;
6700  fTsumw2 = 0;
6701  fTsumwx = 0;
6702  fTsumwx2 = 0;
6703  fEntries = 0;
6704 
6705  if (opt == "ICES") return;
6706 
6707 
6708  TObject *stats = fFunctions->FindObject("stats");
6709  fFunctions->Remove(stats);
6710  //special logic to support the case where the same object is
6711  //added multiple times in fFunctions.
6712  //This case happens when the same object is added with different
6713  //drawing modes
6714  TObject *obj;
6715  while ((obj = fFunctions->First())) {
6716  while(fFunctions->Remove(obj)) { }
6717  delete obj;
6718  }
6719  if(stats) fFunctions->Add(stats);
6720  fContour.Set(0);
6721 }
6722 
6723 
6724 ////////////////////////////////////////////////////////////////////////////////
6725 /// Save primitive as a C++ statement(s) on output stream out
6726 
6727 void TH1::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/)
6728 {
6729  // empty the buffer before if it exists
6730  if (fBuffer) BufferEmpty();
6731 
6732  Bool_t nonEqiX = kFALSE;
6733  Bool_t nonEqiY = kFALSE;
6734  Bool_t nonEqiZ = kFALSE;
6735  Int_t i;
6736  static Int_t nxaxis = 0;
6737  static Int_t nyaxis = 0;
6738  static Int_t nzaxis = 0;
6739  TString sxaxis="xAxis",syaxis="yAxis",szaxis="zAxis";
6740 
6741  // Check if the histogram has equidistant X bins or not. If not, we
6742  // create an array holding the bins.
6743  if (GetXaxis()->GetXbins()->fN && GetXaxis()->GetXbins()->fArray) {
6744  nonEqiX = kTRUE;
6745  nxaxis++;
6746  sxaxis += nxaxis;
6747  out << " Double_t "<<sxaxis<<"[" << GetXaxis()->GetXbins()->fN
6748  << "] = {";
6749  for (i = 0; i < GetXaxis()->GetXbins()->fN; i++) {
6750  if (i != 0) out << ", ";
6751  out << GetXaxis()->GetXbins()->fArray[i];
6752  }
6753  out << "}; " << std::endl;
6754  }
6755  // If the histogram is 2 or 3 dimensional, check if the histogram
6756  // has equidistant Y bins or not. If not, we create an array
6757  // holding the bins.
6758  if (fDimension > 1 && GetYaxis()->GetXbins()->fN &&
6759  GetYaxis()->GetXbins()->fArray) {
6760  nonEqiY = kTRUE;
6761  nyaxis++;
6762  syaxis += nyaxis;
6763  out << " Double_t "<<syaxis<<"[" << GetYaxis()->GetXbins()->fN
6764  << "] = {";
6765  for (i = 0; i < GetYaxis()->GetXbins()->fN; i++) {
6766  if (i != 0) out << ", ";
6767  out << GetYaxis()->GetXbins()->fArray[i];
6768  }
6769  out << "}; " << std::endl;
6770  }
6771  // IF the histogram is 3 dimensional, check if the histogram
6772  // has equidistant Z bins or not. If not, we create an array
6773  // holding the bins.
6774  if (fDimension > 2 && GetZaxis()->GetXbins()->fN &&
6775  GetZaxis()->GetXbins()->fArray) {
6776  nonEqiZ = kTRUE;
6777  nzaxis++;
6778  szaxis += nzaxis;
6779  out << " Double_t "<<szaxis<<"[" << GetZaxis()->GetXbins()->fN
6780  << "] = {";
6781  for (i = 0; i < GetZaxis()->GetXbins()->fN; i++) {
6782  if (i != 0) out << ", ";
6783  out << GetZaxis()->GetXbins()->fArray[i];
6784  }
6785  out << "}; " << std::endl;
6786  }
6787 
6788  char quote = '"';
6789  out <<" "<<std::endl;
6790  out <<" "<< ClassName() <<" *";
6791 
6792  // Histogram pointer has by default the histogram name with an incremental suffix.
6793  // If the histogram belongs to a graph or a stack the suffix is not added because
6794  // the graph and stack objects are not aware of this new name. Same thing if
6795  // the histogram is drawn with the option COLZ because the TPaletteAxis drawn
6796  // when this option is selected, does not know this new name either.
6797  TString opt = option;
6798  opt.ToLower();
6799  static Int_t hcounter = 0;
6800  TString histName = GetName();
6801  if ( !histName.Contains("Graph")
6802  && !histName.Contains("_stack_")
6803  && !opt.Contains("colz")) {
6804  hcounter++;
6805  histName += "__";
6806  histName += hcounter;
6807  }
6808  histName = gInterpreter-> MapCppName(histName);
6809  const char *hname = histName.Data();
6810  if (!strlen(hname)) hname = "unnamed";
6811 
6812  TString t(GetTitle());
6813  t.ReplaceAll("\\","\\\\");
6814  t.ReplaceAll("\"","\\\"");
6815  out << hname << " = new " << ClassName() << "(" << quote
6816  << hname << quote << "," << quote<< t.Data() << quote
6817  << "," << GetXaxis()->GetNbins();
6818  if (nonEqiX)
6819  out << ", "<<sxaxis;
6820  else
6821  out << "," << GetXaxis()->GetXmin()
6822  << "," << GetXaxis()->GetXmax();
6823  if (fDimension > 1) {
6824  out << "," << GetYaxis()->GetNbins();
6825  if (nonEqiY)
6826  out << ", "<<syaxis;
6827  else
6828  out << "," << GetYaxis()->GetXmin()
6829  << "," << GetYaxis()->GetXmax();
6830  }
6831  if (fDimension > 2) {
6832  out << "," << GetZaxis()->GetNbins();
6833  if (nonEqiZ)
6834  out << ", "<<szaxis;
6835  else
6836  out << "," << GetZaxis()->GetXmin()
6837  << "," << GetZaxis()->GetXmax();
6838  }
6839  out << ");" << std::endl;
6840 
6841  // save bin contents
6842  Int_t bin;
6843  for (bin=0;bin<fNcells;bin++) {
6844  Double_t bc = RetrieveBinContent(bin);
6845  if (bc) {
6846  out<<" "<<hname<<"->SetBinContent("<<bin<<","<<bc<<");"<<std::endl;
6847  }
6848  }
6849 
6850  // save bin errors
6851  if (fSumw2.fN) {
6852  for (bin=0;bin<fNcells;bin++) {
6853  Double_t be = GetBinError(bin);
6854  if (be) {
6855  out<<" "<<hname<<"->SetBinError("<<bin<<","<<be<<");"<<std::endl;
6856  }
6857  }
6858  }
6859 
6860  TH1::SavePrimitiveHelp(out, hname, option);
6861 }
6862 
6863 
6864 ////////////////////////////////////////////////////////////////////////////////
6865 /// helper function for the SavePrimitive functions from TH1
6866 /// or classes derived from TH1, eg TProfile, TProfile2D.
6867 
6868 void TH1::SavePrimitiveHelp(std::ostream &out, const char *hname, Option_t *option /*= ""*/)
6869 {
6870  char quote = '"';
6871  if (TMath::Abs(GetBarOffset()) > 1e-5) {
6872  out<<" "<<hname<<"->SetBarOffset("<<GetBarOffset()<<");"<<std::endl;
6873  }
6874  if (TMath::Abs(GetBarWidth()-1) > 1e-5) {
6875  out<<" "<<hname<<"->SetBarWidth("<<GetBarWidth()<<");"<<std::endl;
6876  }
6877  if (fMinimum != -1111) {
6878  out<<" "<<hname<<"->SetMinimum("<<fMinimum<<");"<<std::endl;
6879  }
6880  if (fMaximum != -1111) {
6881  out<<" "<<hname<<"->SetMaximum("<<fMaximum<<");"<<std::endl;
6882  }
6883  if (fNormFactor != 0) {
6884  out<<" "<<hname<<"->SetNormFactor("<<fNormFactor<<");"<<std::endl;
6885  }
6886  if (fEntries != 0) {
6887  out<<" "<<hname<<"->SetEntries("<<fEntries<<");"<<std::endl;
6888  }
6889  if (fDirectory == 0) {
6890  out<<" "<<hname<<"->SetDirectory(0);"<<std::endl;
6891  }
6892  if (TestBit(kNoStats)) {
6893  out<<" "<<hname<<"->SetStats(0);"<<std::endl;
6894  }
6895  if (fOption.Length() != 0) {
6896  out<<" "<<hname<<"->SetOption("<<quote<<fOption.Data()<<quote<<");"<<std::endl;
6897  }
6898 
6899  // save contour levels
6900  Int_t ncontours = GetContour();
6901  if (ncontours > 0) {
6902  out<<" "<<hname<<"->SetContour("<<ncontours<<");"<<std::endl;
6903  Double_t zlevel;
6904  for (Int_t bin=0;bin<ncontours;bin++) {
6905  if (gPad->GetLogz()) {
6906  zlevel = TMath::Power(10,GetContourLevel(bin));
6907  } else {
6908  zlevel = GetContourLevel(bin);
6909  }
6910  out<<" "<<hname<<"->SetContourLevel("<<bin<<","<<zlevel<<");"<<std::endl;
6911  }
6912  }
6913 
6914  // save list of functions
6916  TObject *obj;
6917  static Int_t funcNumber = 0;
6918  while (lnk) {
6919  obj = lnk->GetObject();
6920  obj->SavePrimitive(out,Form("nodraw #%d\n",++funcNumber));
6921  if (obj->InheritsFrom(TF1::Class())) {
6922  out<<" "<<hname<<"->GetListOfFunctions()->Add("
6923  <<Form("%s%d",obj->GetName(),funcNumber)<<");"<<std::endl;
6924  } else if (obj->InheritsFrom("TPaveStats")) {
6925  out<<" "<<hname<<"->GetListOfFunctions()->Add(ptstats);"<<std::endl;
6926  out<<" ptstats->SetParent("<<hname<<");"<<std::endl;
6927  } else {
6928  out<<" "<<hname<<"->GetListOfFunctions()->Add("
6929  <<obj->GetName()
6930  <<","<<quote<<lnk->GetOption()<<quote<<");"<<std::endl;
6931  }
6932  lnk = (TObjOptLink*)lnk->Next();
6933  }
6934 
6935  // save attributes
6936  SaveFillAttributes(out,hname,0,1001);
6937  SaveLineAttributes(out,hname,1,1,1);
6938  SaveMarkerAttributes(out,hname,1,1,1);
6939  fXaxis.SaveAttributes(out,hname,"->GetXaxis()");
6940  fYaxis.SaveAttributes(out,hname,"->GetYaxis()");
6941  fZaxis.SaveAttributes(out,hname,"->GetZaxis()");
6942  TString opt = option;
6943  opt.ToLower();
6944  if (!opt.Contains("nodraw")) {
6945  out<<" "<<hname<<"->Draw("
6946  <<quote<<option<<quote<<");"<<std::endl;
6947  }
6948 }
6949 
6950 
6951 ////////////////////////////////////////////////////////////////////////////////
6952 ///Copy current attributes from/to current style
6953 
6954 void TH1::UseCurrentStyle()
6955 {
6956  if (!gStyle) return;
6957  if (gStyle->IsReading()) {
6958  fXaxis.ResetAttAxis("X");
6959  fYaxis.ResetAttAxis("Y");
6960  fZaxis.ResetAttAxis("Z");
6971  Int_t dostat = gStyle->GetOptStat();
6972  if (gStyle->GetOptFit() && !dostat) dostat = 1000000001;
6973  SetStats(dostat);
6974  } else {
6986  }
6987  TIter next(GetListOfFunctions());
6988  TObject *obj;
6989 
6990  while ((obj = next())) {
6991  obj->UseCurrentStyle();
6992  }
6993 }
6994 
6995 
6996 ////////////////////////////////////////////////////////////////////////////////
6997 /// For axis = 1,2 or 3 returns the mean value of the histogram along
6998 /// X,Y or Z axis.
6999 /// For axis = 11, 12, 13 returns the standard error of the mean value
7000 /// of the histogram along X, Y or Z axis
7001 ///
7002 /// Note that the mean value/StdDev is computed using the bins in the currently
7003 /// defined range (see TAxis::SetRange). By default the range includes
7004 /// all bins from 1 to nbins included, excluding underflows and overflows.
7005 /// To force the underflows and overflows in the computation, one must
7006 /// call the static function TH1::StatOverflows(kTRUE) before filling
7007 /// the histogram.
7008 ///
7009 /// Return mean value of this histogram along the X axis.
7010 ///
7011 /// Note that the mean value/StdDev is computed using the bins in the currently
7012 /// defined range (see TAxis::SetRange). By default the range includes
7013 /// all bins from 1 to nbins included, excluding underflows and overflows.
7014 /// To force the underflows and overflows in the computation, one must
7015 /// call the static function TH1::StatOverflows(kTRUE) before filling
7016 /// the histogram.
7017 
7018 Double_t TH1::GetMean(Int_t axis) const
7019 {
7020  if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
7021  Double_t stats[kNstat];
7022  for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
7023  GetStats(stats);
7024  if (stats[0] == 0) return 0;
7025  if (axis<4){
7026  Int_t ax[3] = {2,4,7};
7027  return stats[ax[axis-1]]/stats[0];
7028  } else {
7029  // mean error = StdDev / sqrt( Neff )
7030  Double_t stddev = GetStdDev(axis-10);
7031  Double_t neff = GetEffectiveEntries();
7032  return ( neff > 0 ? stddev/TMath::Sqrt(neff) : 0. );
7033  }
7034 }
7035 
7036 
7037 ////////////////////////////////////////////////////////////////////////////////
7038 /// Return standard error of mean of this histogram along the X axis.
7039 ///
7040 /// Note that the mean value/StdDev is computed using the bins in the currently
7041 /// defined range (see TAxis::SetRange). By default the range includes
7042 /// all bins from 1 to nbins included, excluding underflows and overflows.
7043 /// To force the underflows and overflows in the computation, one must
7044 /// call the static function TH1::StatOverflows(kTRUE) before filling
7045 /// the histogram.
7046 /// Also note, that although the definition of standard error doesn't include the
7047 /// assumption of normality, many uses of this feature implicitly assume it.
7048 
7049 Double_t TH1::GetMeanError(Int_t axis) const
7050 {
7051  return GetMean(axis+10);
7052 }
7053 
7054 
7055 ////////////////////////////////////////////////////////////////////////////////
7056 /// Returns the Standard Deviation (Sigma).
7057 /// The Sigma estimate is computed as Sqrt((1/N)*(Sum(x_i-x_mean)^2))
7058 ///
7059 /// For axis = 1,2 or 3 returns the Sigma value of the histogram along
7060 /// X, Y or Z axis
7061 /// For axis = 11, 12 or 13 returns the error of StdDev estimation along
7062 /// X, Y or Z axis for Normal distribution
7063 ///
7064 /// Note that the mean value/sigma is computed using the bins in the currently
7065 /// defined range (see TAxis::SetRange). By default the range includes
7066 /// all bins from 1 to nbins included, excluding underflows and overflows.
7067 /// To force the underflows and overflows in the computation, one must
7068 /// call the static function TH1::StatOverflows(kTRUE) before filling
7069 /// the histogram.
7070 
7071 Double_t TH1::GetStdDev(Int_t axis) const
7072 {
7073  if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
7074 
7075  Double_t x, stddev2, stats[kNstat];
7076  for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
7077  GetStats(stats);
7078  if (stats[0] == 0) return 0;
7079  Int_t ax[3] = {2,4,7};
7080  Int_t axm = ax[axis%10 - 1];
7081  x = stats[axm]/stats[0];
7082  stddev2 = TMath::Abs(stats[axm+1]/stats[0] -x*x);
7083  if (axis<10)
7084  return TMath::Sqrt(stddev2);
7085  else {
7086  // The right formula for StdDev error depends on 4th momentum (see Kendall-Stuart Vol 1 pag 243)
7087  // formula valid for only gaussian distribution ( 4-th momentum = 3 * sigma^4 )
7088  Double_t neff = GetEffectiveEntries();
7089  return ( neff > 0 ? TMath::Sqrt(stddev2/(2*neff) ) : 0. );
7090  }
7091 }
7092 
7093 
7094 ////////////////////////////////////////////////////////////////////////////////
7095 /// Return error of standard deviation estimation for Normal distribution
7096 ///
7097 /// Note that the mean value/StdDev is computed using the bins in the currently
7098 /// defined range (see TAxis::SetRange). By default the range includes
7099 /// all bins from 1 to nbins included, excluding underflows and overflows.
7100 /// To force the underflows and overflows in the computation, one must
7101 /// call the static function TH1::StatOverflows(kTRUE) before filling
7102 /// the histogram.
7103 /// Value returned is standard deviation of sample standard deviation.
7104 /// Note that it is an approximated value which is valid only in the case that the
7105 /// original data distribution is Normal. The correct one would require
7106 /// the 4-th momentum value, which cannot be accurately estimated from an histogram since
7107 /// the x-information for all entries is not kept.
7108 
7110 {
7111  return GetStdDev(axis+10);
7112 }
7113 
7114 
7115 ////////////////////////////////////////////////////////////////////////////////
7116 ///For axis = 1, 2 or 3 returns skewness of the histogram along x, y or z axis.
7117 ///For axis = 11, 12 or 13 returns the approximate standard error of skewness
7118 ///of the histogram along x, y or z axis
7119 ///Note, that since third and fourth moment are not calculated
7120 ///at the fill time, skewness and its standard error are computed bin by bin
7121 
7122 Double_t TH1::GetSkewness(Int_t axis) const
7123 {
7125  if (axis > 0 && axis <= 3){
7126 
7127  Double_t mean = GetMean(axis);
7128  Double_t stddev = GetStdDev(axis);
7129  Double_t stddev3 = stddev*stddev*stddev;
7130 
7131  Int_t firstBinX = fXaxis.GetFirst();
7132  Int_t lastBinX = fXaxis.GetLast();
7133  Int_t firstBinY = fYaxis.GetFirst();
7134  Int_t lastBinY = fYaxis.GetLast();
7135  Int_t firstBinZ = fZaxis.GetFirst();
7136  Int_t lastBinZ = fZaxis.GetLast();
7137  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7138  if (fgStatOverflows) {
7139  if ( !fXaxis.TestBit(TAxis::kAxisRange) ) {
7140  if (firstBinX == 1) firstBinX = 0;
7141  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7142  }
7143  if ( !fYaxis.TestBit(TAxis::kAxisRange) ) {
7144  if (firstBinY == 1) firstBinY = 0;
7145  if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
7146  }
7147  if ( !fZaxis.TestBit(TAxis::kAxisRange) ) {
7148  if (firstBinZ == 1) firstBinZ = 0;
7149  if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
7150  }
7151  }
7152 
7153  Double_t x = 0;
7154  Double_t sum=0;
7155  Double_t np=0;
7156  for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
7157  for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
7158  for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
7159  if (axis==1 ) x = fXaxis.GetBinCenter(binx);
7160  else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
7161  else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
7162  Double_t w = GetBinContent(binx,biny,binz);
7163  np+=w;
7164  sum+=w*(x-mean)*(x-mean)*(x-mean);
7165  }
7166  }
7167  }
7168  sum/=np*stddev3;
7169  return sum;
7170  }
7171  else if (axis > 10 && axis <= 13) {
7172  //compute standard error of skewness
7173  // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
7174  Double_t neff = GetEffectiveEntries();
7175  return ( neff > 0 ? TMath::Sqrt(6./neff ) : 0. );
7176  }
7177  else {
7178  Error("GetSkewness", "illegal value of parameter");
7179  return 0;
7180  }
7181 }
7182 
7183 
7184 ////////////////////////////////////////////////////////////////////////////////
7185 ///For axis =1, 2 or 3 returns kurtosis of the histogram along x, y or z axis.
7186 ///Kurtosis(gaussian(0, 1)) = 0.
7187 ///For axis =11, 12 or 13 returns the approximate standard error of kurtosis
7188 ///of the histogram along x, y or z axis
7189 ///Note, that since third and fourth moment are not calculated
7190 ///at the fill time, kurtosis and its standard error are computed bin by bin
7191 
7192 Double_t TH1::GetKurtosis(Int_t axis) const
7193 {
7194  if (axis > 0 && axis <= 3){
7195 
7196  Double_t mean = GetMean(axis);
7197  Double_t stddev = GetStdDev(axis);
7198  Double_t stddev4 = stddev*stddev*stddev*stddev;
7199 
7200  Int_t firstBinX = fXaxis.GetFirst();
7201  Int_t lastBinX = fXaxis.GetLast();
7202  Int_t firstBinY = fYaxis.GetFirst();
7203  Int_t lastBinY = fYaxis.GetLast();
7204  Int_t firstBinZ = fZaxis.GetFirst();
7205  Int_t lastBinZ = fZaxis.GetLast();
7206  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7207  if (fgStatOverflows) {
7208  if ( !fXaxis.TestBit(TAxis::kAxisRange) ) {
7209  if (firstBinX == 1) firstBinX = 0;
7210  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7211  }
7212  if ( !fYaxis.TestBit(TAxis::kAxisRange) ) {
7213  if (firstBinY == 1) firstBinY = 0;
7214  if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
7215  }
7216  if ( !fZaxis.TestBit(TAxis::kAxisRange) ) {
7217  if (firstBinZ == 1) firstBinZ = 0;
7218  if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
7219  }
7220  }
7221 
7222  Double_t x = 0;
7223  Double_t sum=0;
7224  Double_t np=0;
7225  for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
7226  for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
7227  for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
7228  if (axis==1 ) x = fXaxis.GetBinCenter(binx);
7229  else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
7230  else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
7231  Double_t w = GetBinContent(binx,biny,binz);
7232  np+=w;
7233  sum+=w*(x-mean)*(x-mean)*(x-mean)*(x-mean);
7234  }
7235  }
7236  }
7237  sum/=(np*stddev4);
7238  return sum-3;
7239 
7240  } else if (axis > 10 && axis <= 13) {
7241  //compute standard error of skewness
7242  // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
7243  Double_t neff = GetEffectiveEntries();
7244  return ( neff > 0 ? TMath::Sqrt(24./neff ) : 0. );
7245  }
7246  else {
7247  Error("GetKurtosis", "illegal value of parameter");
7248  return 0;
7249  }
7250 }
7251 
7252 
7253 ////////////////////////////////////////////////////////////////////////////////
7254 /// fill the array stats from the contents of this histogram
7255 /// The array stats must be correctly dimensioned in the calling program.
7256 ///
7257 /// stats[0] = sumw
7258 /// stats[1] = sumw2
7259 /// stats[2] = sumwx
7260 /// stats[3] = sumwx2
7261 ///
7262 /// If no axis-subrange is specified (via TAxis::SetRange), the array stats
7263 /// is simply a copy of the statistics quantities computed at filling time.
7264 /// If a sub-range is specified, the function recomputes these quantities
7265 /// from the bin contents in the current axis range.
7266 ///
7267 /// Note that the mean value/StdDev is computed using the bins in the currently
7268 /// defined range (see TAxis::SetRange). By default the range includes
7269 /// all bins from 1 to nbins included, excluding underflows and overflows.
7270 /// To force the underflows and overflows in the computation, one must
7271 /// call the static function TH1::StatOverflows(kTRUE) before filling
7272 /// the histogram.
7273 
7274 void TH1::GetStats(Double_t *stats) const
7275 {
7276  if (fBuffer) ((TH1*)this)->BufferEmpty();
7277 
7278  // Loop on bins (possibly including underflows/overflows)
7279  Int_t bin, binx;
7280  Double_t w,err;
7281  Double_t x;
7282  // case of labels with extension of axis range
7283  // statistics in x does not make any sense - set to zero
7284  if ((const_cast<TAxis&>(fXaxis)).GetLabels() && CanExtendAllAxes() ) {
7285  stats[0] = fTsumw;
7286  stats[1] = fTsumw2;
7287  stats[2] = 0;
7288  stats[3] = 0;
7289  }
7290  else if ((fTsumw == 0 && fEntries > 0) || fXaxis.TestBit(TAxis::kAxisRange)) {
7291  for (bin=0;bin<4;bin++) stats[bin] = 0;
7292 
7293  Int_t firstBinX = fXaxis.GetFirst();
7294  Int_t lastBinX = fXaxis.GetLast();
7295  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7297  if (firstBinX == 1) firstBinX = 0;
7298  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7299  }
7300  for (binx = firstBinX; binx <= lastBinX; binx++) {
7301  x = fXaxis.GetBinCenter(binx);
7302  //w = TMath::Abs(RetrieveBinContent(binx));
7303  // not sure what to do here if w < 0
7304  w = RetrieveBinContent(binx);
7305  err = TMath::Abs(GetBinError(binx));
7306  stats[0] += w;
7307  stats[1] += err*err;
7308  stats[2] += w*x;
7309  stats[3] += w*x*x;
7310  }
7311  // if (stats[0] < 0) {
7312  // // in case total is negative do something ??
7313  // stats[0] = 0;
7314  // }
7315  } else {
7316  stats[0] = fTsumw;
7317  stats[1] = fTsumw2;
7318  stats[2] = fTsumwx;
7319  stats[3] = fTsumwx2;
7320  }
7321 }
7322 
7323 
7324 ////////////////////////////////////////////////////////////////////////////////
7325 /// Replace current statistics with the values in array stats
7326 
7327 void TH1::PutStats(Double_t *stats)
7328 {
7329  fTsumw = stats[0];
7330  fTsumw2 = stats[1];
7331  fTsumwx = stats[2];
7332  fTsumwx2 = stats[3];
7333 }
7334 
7335 
7336 ////////////////////////////////////////////////////////////////////////////////
7337 /// Reset the statistics including the number of entries
7338 /// and replace with values calculates from bin content
7339 /// The number of entries is set to the total bin content or (in case of weighted histogram)
7340 /// to number of effective entries
7341 
7342 void TH1::ResetStats()
7343 {
7344  Double_t stats[kNstat] = {0};
7345  fTsumw = 0;
7346  fEntries = 1; // to force re-calculation of the statistics in TH1::GetStats
7347  GetStats(stats);
7348  PutStats(stats);
7350  // use effective entries for weighted histograms: (sum_w) ^2 / sum_w2
7351  if (fSumw2.fN > 0 && fTsumw > 0 && stats[1] > 0 ) fEntries = stats[0]*stats[0]/ stats[1];
7352 }
7353 
7354 
7355 ////////////////////////////////////////////////////////////////////////////////
7356 /// Return the sum of weights excluding under/overflows.
7357 
7359 {
7360  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
7361 
7362  Int_t bin,binx,biny,binz;
7363  Double_t sum =0;
7364  for(binz=1; binz<=fZaxis.GetNbins(); binz++) {
7365  for(biny=1; biny<=fYaxis.GetNbins(); biny++) {
7366  for(binx=1; binx<=fXaxis.GetNbins(); binx++) {
7367  bin = GetBin(binx,biny,binz);
7368  sum += RetrieveBinContent(bin);
7369  }
7370  }
7371  }
7372  return sum;
7373 }
7374 
7375 
7376 ////////////////////////////////////////////////////////////////////////////////
7377 ///Return integral of bin contents. Only bins in the bins range are considered.
7378 /// By default the integral is computed as the sum of bin contents in the range.
7379 /// if option "width" is specified, the integral is the sum of
7380 /// the bin contents multiplied by the bin width in x.
7381 
7382 Double_t TH1::Integral(Option_t *option) const
7383 {
7384  return Integral(fXaxis.GetFirst(),fXaxis.GetLast(),option);
7385 }
7386 
7387 
7388 ////////////////////////////////////////////////////////////////////////////////
7389 ///Return integral of bin contents in range [binx1,binx2]
7390 /// By default the integral is computed as the sum of bin contents in the range.
7391 /// if option "width" is specified, the integral is the sum of
7392 /// the bin contents multiplied by the bin width in x.
7393 
7394 Double_t TH1::Integral(Int_t binx1, Int_t binx2, Option_t *option) const
7395 {
7396  double err = 0;
7397  return DoIntegral(binx1,binx2,0,-1,0,-1,err,option);
7398 }
7399 
7400 
7401 ////////////////////////////////////////////////////////////////////////////////
7402 ///Return integral of bin contents in range [binx1,binx2] and its error
7403 /// By default the integral is computed as the sum of bin contents in the range.
7404 /// if option "width" is specified, the integral is the sum of
7405 /// the bin contents multiplied by the bin width in x.
7406 /// the error is computed using error propagation from the bin errors assumming that
7407 /// all the bins are uncorrelated
7408 
7409 Double_t TH1::IntegralAndError(Int_t binx1, Int_t binx2, Double_t & error, Option_t *option) const
7410 {
7411  return DoIntegral(binx1,binx2,0,-1,0,-1,error,option,kTRUE);
7412 }
7413 
7414 
7415 ////////////////////////////////////////////////////////////////////////////////
7416 /// internal function compute integral and optionally the error between the limits
7417 /// specified by the bin number values working for all histograms (1D, 2D and 3D)
7418 
7419 Double_t TH1::DoIntegral(Int_t binx1, Int_t binx2, Int_t biny1, Int_t biny2, Int_t binz1, Int_t binz2, Double_t & error ,
7420  Option_t *option, Bool_t doError) const
7422  if (fBuffer) ((TH1*)this)->BufferEmpty();
7423 
7424  Int_t nx = GetNbinsX() + 2;
7425  if (binx1 < 0) binx1 = 0;
7426  if (binx2 >= nx || binx2 < binx1) binx2 = nx - 1;
7427 
7428  if (GetDimension() > 1) {
7429  Int_t ny = GetNbinsY() + 2;
7430  if (biny1 < 0) biny1 = 0;
7431  if (biny2 >= ny || biny2 < biny1) biny2 = ny - 1;
7432  } else {
7433  biny1 = 0; biny2 = 0;
7434  }
7435 
7436  if (GetDimension() > 2) {
7437  Int_t nz = GetNbinsZ() + 2;
7438  if (binz1 < 0) binz1 = 0;
7439  if (binz2 >= nz || binz2 < binz1) binz2 = nz - 1;
7440  } else {
7441  binz1 = 0; binz2 = 0;
7442  }
7443 
7444  // - Loop on bins in specified range
7445  TString opt = option;
7446  opt.ToLower();
7447  Bool_t width = kFALSE;
7448  if (opt.Contains("width")) width = kTRUE;
7449 
7450 
7451  Double_t dx = 1., dy = .1, dz =.1;
7452  Double_t integral = 0;
7453  Double_t igerr2 = 0;
7454  for (Int_t binx = binx1; binx <= binx2; ++binx) {
7455  if (width) dx = fXaxis.GetBinWidth(binx);
7456  for (Int_t biny = biny1; biny <= biny2; ++biny) {
7457  if (width) dy = fYaxis.GetBinWidth(biny);
7458  for (Int_t binz = binz1; binz <= binz2; ++binz) {
7459  Int_t bin = GetBin(binx, biny, binz);
7460  Double_t dv = 0.0;
7461  if (width) {
7462  dz = fZaxis.GetBinWidth(binz);
7463  dv = dx * dy * dz;
7464  integral += RetrieveBinContent(bin) * dv;
7465  } else {
7466  integral += RetrieveBinContent(bin);
7467  }
7468  if (doError) {
7469  if (width) igerr2 += GetBinErrorSqUnchecked(bin) * dv * dv;
7470  else igerr2 += GetBinErrorSqUnchecked(bin);
7471  }
7472  }
7473  }
7474  }
7475 
7476  if (doError) error = TMath::Sqrt(igerr2);
7477  return integral;
7478 }
7479 
7480 
7481 ////////////////////////////////////////////////////////////////////////////////
7482 /// Statistical test of compatibility in shape between
7483 /// this histogram and h2, using the Anderson-Darling 2 sample test.
7484 /// The AD 2 sample test formula are derived from the paper
7485 /// F.W Scholz, M.A. Stephens "k-Sample Anderson-Darling Test".
7486 /// The test is implemented in root in the ROOT::Math::GoFTest class
7487 /// It is the same formula ( (6) in the paper), and also shown in this preprint
7488 /// http://arxiv.org/pdf/0804.0380v1.pdf
7489 /// Binned data are considered as un-binned data
7490 /// with identical observation happening in the bin center.
7491 ///
7492 /// \param[in] option is a character string to specify options
7493 /// - "D" Put out a line of "Debug" printout
7494 /// - "T" Return the normalized A-D test statistic
7495 ///
7496 /// - Note1: Underflow and overflow are not considered in the test
7497 /// - Note2: The test works only for un-weighted histogram (i.e. representing counts)
7498 /// - Note3: The histograms are not required to have the same X axis
7499 /// - Note4: The test works only for 1-dimensional histograms
7500 
7501 Double_t TH1::AndersonDarlingTest(const TH1 *h2, Option_t *option) const
7502 {
7503  Double_t advalue = 0;
7504  Double_t pvalue = AndersonDarlingTest(h2, advalue);
7505 
7506  TString opt = option;
7507  opt.ToUpper();
7508  if (opt.Contains("D") ) {
7509  printf(" AndersonDarlingTest Prob = %g, AD TestStatistic = %g\n",pvalue,advalue);
7510  }
7511  if (opt.Contains("T") ) return advalue;
7512 
7513  return pvalue;
7514 }
7515 
7516 ////////////////////////////////////////////////////////////////////////////////
7517 /// Same funciton as above but returning also the test statistic value
7518 
7519 Double_t TH1::AndersonDarlingTest(const TH1 *h2, Double_t & advalue) const
7520 {
7521  if (GetDimension() != 1 || h2->GetDimension() != 1) {
7522  Error("AndersonDarlingTest","Histograms must be 1-D");
7523  return -1;
7524  }
7525 
7526  // empty the buffer. Probably we could add as an unbinned test
7527  if (fBuffer) ((TH1*)this)->BufferEmpty();
7528 
7529  // use the BinData class
7530  ROOT::Fit::BinData data1;
7531  ROOT::Fit::BinData data2;
7532 
7533  ROOT::Fit::FillData(data1, this, 0);
7534  ROOT::Fit::FillData(data2, h2, 0);
7535 
7536  double pvalue;
7537  ROOT::Math::GoFTest::AndersonDarling2SamplesTest(data1,data2, pvalue,advalue);
7538 
7539  return pvalue;
7540 }
7541 
7542 ////////////////////////////////////////////////////////////////////////////////
7543 /// Statistical test of compatibility in shape between
7544 /// this histogram and h2, using Kolmogorov test.
7545 /// Note that the KolmogorovTest (KS) test should in theory be used only for unbinned data
7546 /// and not for binned data as in the case of the histogram (see NOTE 3 below).
7547 /// So, before using this method blindly, read the NOTE 3.
7548 ///
7549 /// Default: Ignore under- and overflow bins in comparison
7550 ///
7551 /// \param[in] option is a character string to specify options
7552 /// - "U" include Underflows in test (also for 2-dim)
7553 /// - "O" include Overflows (also valid for 2-dim)
7554 /// - "N" include comparison of normalizations
7555 /// - "D" Put out a line of "Debug" printout
7556 /// - "M" Return the Maximum Kolmogorov distance instead of prob
7557 /// - "X" Run the pseudo experiments post-processor with the following procedure:
7558 /// make pseudoexperiments based on random values from the parent
7559 /// distribution and compare the KS distance of the pseudoexperiment
7560 /// to the parent distribution. Bin the KS distances in a histogram,
7561 /// and then take the integral of all the KS values above the value
7562 /// obtained from the original data to Monte Carlo distribution.
7563 /// The number of pseudo-experiments nEXPT is currently fixed at 1000.
7564 /// The function returns the integral.
7565 /// (thanks to Ben Kilminster to submit this procedure). Note that
7566 /// this option "X" is much slower.
7567 ///
7568 /// The returned function value is the probability of test
7569 /// (much less than one means NOT compatible)
7570 ///
7571 /// Code adapted by Rene Brun from original HBOOK routine HDIFF
7572 ///
7573 /// NOTE1
7574 /// A good description of the Kolmogorov test can be seen at:
7575 /// http://www.itl.nist.gov/div898/handbook/eda/section3/eda35g.htm
7576 ///
7577 /// NOTE2
7578 /// see also alternative function TH1::Chi2Test
7579 /// The Kolmogorov test is assumed to give better results than Chi2Test
7580 /// in case of histograms with low statistics.
7581 ///
7582 /// NOTE3 (Jan Conrad, Fred James)
7583 /// "The returned value PROB is calculated such that it will be
7584 /// uniformly distributed between zero and one for compatible histograms,
7585 /// provided the data are not binned (or the number of bins is very large
7586 /// compared with the number of events). Users who have access to unbinned
7587 /// data and wish exact confidence levels should therefore not put their data
7588 /// into histograms, but should call directly TMath::KolmogorovTest. On
7589 /// the other hand, since TH1 is a convenient way of collecting data and
7590 /// saving space, this function has been provided. However, the values of
7591 /// PROB for binned data will be shifted slightly higher than expected,
7592 /// depending on the effects of the binning. For example, when comparing two
7593 /// uniform distributions of 500 events in 100 bins, the values of PROB,
7594 /// instead of being exactly uniformly distributed between zero and one, have
7595 /// a mean value of about 0.56. We can apply a useful
7596 /// rule: As long as the bin width is small compared with any significant
7597 /// physical effect (for example the experimental resolution) then the binning
7598 /// cannot have an important effect. Therefore, we believe that for all
7599 /// practical purposes, the probability value PROB is calculated correctly
7600 /// provided the user is aware that:
7601 /// 1. The value of PROB should not be expected to have exactly the correct
7602 /// distribution for binned data.
7603 /// 2. The user is responsible for seeing to it that the bin widths are
7604 /// small compared with any physical phenomena of interest.
7605 /// 3. The effect of binning (if any) is always to make the value of PROB
7606 /// slightly too big. That is, setting an acceptance criterion of (PROB>0.05
7607 /// will assure that at most 5% of truly compatible histograms are rejected,
7608 /// and usually somewhat less."
7609 ///
7610 /// Note also that for GoF test of unbinned data ROOT provides also the class
7611 /// ROOT::Math::GoFTest. The class has also method for doing one sample tests
7612 /// (i.e. comparing the data with a given distribution).
7613 
7614 Double_t TH1::KolmogorovTest(const TH1 *h2, Option_t *option) const
7615 {
7616  TString opt = option;
7617  opt.ToUpper();
7618 
7619  Double_t prob = 0;
7620  TH1 *h1 = (TH1*)this;
7621  if (h2 == 0) return 0;
7622  const TAxis *axis1 = h1->GetXaxis();
7623  const TAxis *axis2 = h2->GetXaxis();
7624  Int_t ncx1 = axis1->GetNbins();
7625  Int_t ncx2 = axis2->GetNbins();
7626 
7627  // Check consistency of dimensions
7628  if (h1->GetDimension() != 1 || h2->GetDimension() != 1) {
7629  Error("KolmogorovTest","Histograms must be 1-D\n");
7630  return 0;
7631  }
7632 
7633  // Check consistency in number of channels
7634  if (ncx1 != ncx2) {
7635  Error("KolmogorovTest","Number of channels is different, %d and %d\n",ncx1,ncx2);
7636  return 0;
7637  }
7638 
7639  // empty the buffer. Probably we could add as an unbinned test
7640  if (fBuffer) ((TH1*)this)->BufferEmpty();
7641 
7642  // Check consistency in channel edges
7643  Double_t difprec = 1e-5;
7644  Double_t diff1 = TMath::Abs(axis1->GetXmin() - axis2->GetXmin());
7645  Double_t diff2 = TMath::Abs(axis1->GetXmax() - axis2->GetXmax());
7646  if (diff1 > difprec || diff2 > difprec) {
7647  Error("KolmogorovTest","histograms with different binning");
7648  return 0;
7649  }
7650 
7651  Bool_t afunc1 = kFALSE;
7652  Bool_t afunc2 = kFALSE;
7653  Double_t sum1 = 0, sum2 = 0;
7654  Double_t ew1, ew2, w1 = 0, w2 = 0;
7655  Int_t bin;
7656  Int_t ifirst = 1;
7657  Int_t ilast = ncx1;
7658  // integral of all bins (use underflow/overflow if option)
7659  if (opt.Contains("U")) ifirst = 0;
7660  if (opt.Contains("O")) ilast = ncx1 +1;
7661  for (bin = ifirst; bin <= ilast; bin++) {
7662  sum1 += h1->RetrieveBinContent(bin);
7663  sum2 += h2->RetrieveBinContent(bin);
7664  ew1 = h1->GetBinError(bin);
7665  ew2 = h2->GetBinError(bin);
7666  w1 += ew1*ew1;
7667  w2 += ew2*ew2;
7668  }
7669  if (sum1 == 0) {
7670  Error("KolmogorovTest","Histogram1 %s integral is zero\n",h1->GetName());
7671  return 0;
7672  }
7673  if (sum2 == 0) {
7674  Error("KolmogorovTest","Histogram2 %s integral is zero\n",h2->GetName());
7675  return 0;
7676  }
7677 
7678  // calculate the effective entries.
7679  // the case when errors are zero (w1 == 0 or w2 ==0) are equivalent to
7680  // compare to a function. In that case the rescaling is done only on sqrt(esum2) or sqrt(esum1)
7681  Double_t esum1 = 0, esum2 = 0;
7682  if (w1 > 0)
7683  esum1 = sum1 * sum1 / w1;
7684  else
7685  afunc1 = kTRUE; // use later for calculating z
7686 
7687  if (w2 > 0)
7688  esum2 = sum2 * sum2 / w2;
7689  else
7690  afunc2 = kTRUE; // use later for calculating z
7691 
7692  if (afunc2 && afunc1) {
7693  Error("KolmogorovTest","Errors are zero for both histograms\n");
7694  return 0;
7695  }
7696 
7697 
7698  Double_t s1 = 1/sum1;
7699  Double_t s2 = 1/sum2;
7700 
7701  // Find largest difference for Kolmogorov Test
7702  Double_t dfmax =0, rsum1 = 0, rsum2 = 0;
7703 
7704  for (bin=ifirst;bin<=ilast;bin++) {
7705  rsum1 += s1*h1->RetrieveBinContent(bin);
7706  rsum2 += s2*h2->RetrieveBinContent(bin);
7707  dfmax = TMath::Max(dfmax,TMath::Abs(rsum1-rsum2));
7708  }
7709 
7710  // Get Kolmogorov probability
7711  Double_t z, prb1=0, prb2=0, prb3=0;
7712 
7713  // case h1 is exact (has zero errors)
7714  if (afunc1)
7715  z = dfmax*TMath::Sqrt(esum2);
7716  // case h2 has zero errors
7717  else if (afunc2)
7718  z = dfmax*TMath::Sqrt(esum1);
7719  else
7720  // for comparison between two data sets
7721  z = dfmax*TMath::Sqrt(esum1*esum2/(esum1+esum2));
7722 
7723  prob = TMath::KolmogorovProb(z);
7724 
7725  // option N to combine normalization makes sense if both afunc1 and afunc2 are false
7726  if (opt.Contains("N") && !(afunc1 || afunc2 ) ) {
7727  // Combine probabilities for shape and normalization,
7728  prb1 = prob;
7729  Double_t d12 = esum1-esum2;
7730  Double_t chi2 = d12*d12/(esum1+esum2);
7731  prb2 = TMath::Prob(chi2,1);
7732  // see Eadie et al., section 11.6.2
7733  if (prob > 0 && prb2 > 0) prob *= prb2*(1-TMath::Log(prob*prb2));
7734  else prob = 0;
7735  }
7736  // X option. Pseudo-experiments post-processor to determine KS probability
7737  const Int_t nEXPT = 1000;
7738  if (opt.Contains("X") && !(afunc1 || afunc2 ) ) {
7739  Double_t dSEXPT;
7740  TH1 *hExpt = (TH1*)(gDirectory ? gDirectory->CloneObject(this,kFALSE) : gROOT->CloneObject(this,kFALSE));
7741  // make nEXPT experiments (this should be a parameter)
7742  prb3 = 0;
7743  for (Int_t i=0; i < nEXPT; i++) {
7744  hExpt->Reset();
7745  hExpt->FillRandom(h1,(Int_t)esum2);
7746  dSEXPT = KolmogorovTest(hExpt,"M");
7747  if (dSEXPT>dfmax) prb3 += 1.0;
7748  }
7749  prb3 /= (Double_t)nEXPT;
7750  delete hExpt;
7751  }
7752 
7753  // debug printout
7754  if (opt.Contains("D")) {
7755  printf(" Kolmo Prob h1 = %s, sum bin content =%g effective entries =%g\n",h1->GetName(),sum1,esum1);
7756  printf(" Kolmo Prob h2 = %s, sum bin content =%g effective entries =%g\n",h2->GetName(),sum2,esum2);
7757  printf(" Kolmo Prob = %g, Max Dist = %g\n",prob,dfmax);
7758  if (opt.Contains("N"))
7759  printf(" Kolmo Prob = %f for shape alone, =%f for normalisation alone\n",prb1,prb2);
7760  if (opt.Contains("X"))
7761  printf(" Kolmo Prob = %f with %d pseudo-experiments\n",prb3,nEXPT);
7762  }
7763  // This numerical error condition should never occur:
7764  if (TMath::Abs(rsum1-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h1=%s\n",h1->GetName());
7765  if (TMath::Abs(rsum2-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h2=%s\n",h2->GetName());
7766 
7767  if(opt.Contains("M")) return dfmax;
7768  else if(opt.Contains("X")) return prb3;
7769  else return prob;
7770 }
7771 
7772 
7773 ////////////////////////////////////////////////////////////////////////////////
7774 /// Replace bin contents by the contents of array content
7775 
7776 void TH1::SetContent(const Double_t *content)
7777 {
7779  fTsumw = 0;
7780  for (Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, content[i]);
7781 }
7782 
7783 
7784 ////////////////////////////////////////////////////////////////////////////////
7785 /// Return contour values into array levels if pointer levels is non zero
7786 ///
7787 /// The function returns the number of contour levels.
7788 /// see GetContourLevel to return one contour only
7789 ///
7790 
7792 {
7793  Int_t nlevels = fContour.fN;
7794  if (levels) {
7795  if (nlevels == 0) {
7796  nlevels = 20;
7797  SetContour(nlevels);
7798  } else {
7799  if (TestBit(kUserContour) == 0) SetContour(nlevels);
7800  }
7801  for (Int_t level=0; level<nlevels; level++) levels[level] = fContour.fArray[level];
7802  }
7803  return nlevels;
7804 }
7805 
7806 
7807 ////////////////////////////////////////////////////////////////////////////////
7808 /// Return value of contour number level
7809 /// use GetContour to return the array of all contour levels
7810 
7811 Double_t TH1::GetContourLevel(Int_t level) const
7812 {
7813  return (level >= 0 && level < fContour.fN) ? fContour.fArray[level] : 0.0;
7814 }
7815 
7816 
7817 ////////////////////////////////////////////////////////////////////////////////
7818 /// Return the value of contour number "level" in Pad coordinates ie: if the Pad
7819 /// is in log scale along Z it returns le log of the contour level value.
7820 /// see GetContour to return the array of all contour levels
7821 
7823 {
7824  if (level <0 || level >= fContour.fN) return 0;
7825  Double_t zlevel = fContour.fArray[level];
7826 
7827  // In case of user defined contours and Pad in log scale along Z,
7828  // fContour.fArray doesn't contain the log of the contour whereas it does
7829  // in case of equidistant contours.
7830  if (gPad && gPad->GetLogz() && TestBit(kUserContour)) {
7831  if (zlevel <= 0) return 0;
7832  zlevel = TMath::Log10(zlevel);
7833  }
7834  return zlevel;
7835 }
7836 
7837 
7838 ////////////////////////////////////////////////////////////////////////////////
7839 /// set the maximum number of entries to be kept in the buffer
7840 
7841 void TH1::SetBuffer(Int_t buffersize, Option_t * /*option*/)
7842 {
7843  if (fBuffer) {
7844  BufferEmpty();
7845  delete [] fBuffer;
7846  fBuffer = 0;
7847  }
7848  if (buffersize <= 0) {
7849  fBufferSize = 0;
7850  return;
7851  }
7852  if (buffersize < 100) buffersize = 100;
7853  fBufferSize = 1 + buffersize*(fDimension+1);
7854  fBuffer = new Double_t[fBufferSize];
7855  memset(fBuffer,0,sizeof(Double_t)*fBufferSize);
7856 }
7857 
7858 
7859 ////////////////////////////////////////////////////////////////////////////////
7860 /// Set the number and values of contour levels.
7861 ///
7862 /// By default the number of contour levels is set to 20. The contours values
7863 /// in the array "levels" should be specified in increasing order.
7864 ///
7865 /// if argument levels = 0 or missing, equidistant contours are computed
7866 
7867 void TH1::SetContour(Int_t nlevels, const Double_t *levels)
7868 {
7869  Int_t level;
7871  if (nlevels <=0 ) {
7872  fContour.Set(0);
7873  return;
7874  }
7875  fContour.Set(nlevels);
7876 
7877  // - Contour levels are specified
7878  if (levels) {
7880  for (level=0; level<nlevels; level++) fContour.fArray[level] = levels[level];
7881  } else {
7882  // - contour levels are computed automatically as equidistant contours
7883  Double_t zmin = GetMinimum();
7884  Double_t zmax = GetMaximum();
7885  if ((zmin == zmax) && (zmin != 0)) {
7886  zmax += 0.01*TMath::Abs(zmax);
7887  zmin -= 0.01*TMath::Abs(zmin);
7888  }
7889  Double_t dz = (zmax-zmin)/Double_t(nlevels);
7890  if (gPad && gPad->GetLogz()) {
7891  if (zmax <= 0) return;
7892  if (zmin <= 0) zmin = 0.001*zmax;
7893  zmin = TMath::Log10(zmin);
7894  zmax = TMath::Log10(zmax);
7895  dz = (zmax-zmin)/Double_t(nlevels);
7896  }
7897  for (level=0; level<nlevels; level++) {
7898  fContour.fArray[level] = zmin + dz*Double_t(level);
7899  }
7900  }
7901 }
7902 
7903 
7904 ////////////////////////////////////////////////////////////////////////////////
7905 /// Set value for one contour level.
7906 
7908 {
7909  if (level < 0 || level >= fContour.fN) return;
7911  fContour.fArray[level] = value;
7912 }
7913 
7914 
7915 ////////////////////////////////////////////////////////////////////////////////
7916 /// Return maximum value smaller than maxval of bins in the range,
7917 /// unless the value has been overridden by TH1::SetMaximum,
7918 /// in which case it returns that value. (This happens, for example,
7919 /// when the histogram is drawn and the y or z axis limits are changed
7920 ///
7921 /// To get the maximum value of bins in the histogram regardless of
7922 /// whether the value has been overridden, use
7923 /// h->GetBinContent(h->GetMaximumBin())
7924 
7925 Double_t TH1::GetMaximum(Double_t maxval) const
7926 {
7927  if (fMaximum != -1111) return fMaximum;
7928 
7929  // empty the buffer
7930  if (fBuffer) ((TH1*)this)->BufferEmpty();
7931 
7932  Int_t bin, binx, biny, binz;
7933  Int_t xfirst = fXaxis.GetFirst();
7934  Int_t xlast = fXaxis.GetLast();
7935  Int_t yfirst = fYaxis.GetFirst();
7936  Int_t ylast = fYaxis.GetLast();
7937  Int_t zfirst = fZaxis.GetFirst();
7938  Int_t zlast = fZaxis.GetLast();
7939  Double_t maximum = -FLT_MAX, value;
7940  for (binz=zfirst;binz<=zlast;binz++) {
7941  for (biny=yfirst;biny<=ylast;biny++) {
7942  for (binx=xfirst;binx<=xlast;binx++) {
7943  bin = GetBin(binx,biny,binz);
7944  value = RetrieveBinContent(bin);
7945  if (value > maximum && value < maxval) maximum = value;
7946  }
7947  }
7948  }
7949  return maximum;
7950 }
7951 
7952 
7953 ////////////////////////////////////////////////////////////////////////////////
7954 /// Return location of bin with maximum value in the range.
7955 
7956 Int_t TH1::GetMaximumBin() const
7957 {
7958  Int_t locmax, locmay, locmaz;
7959  return GetMaximumBin(locmax, locmay, locmaz);
7960 }
7961 
7962 
7963 ////////////////////////////////////////////////////////////////////////////////
7964 /// Return location of bin with maximum value in the range.
7965 
7966 Int_t TH1::GetMaximumBin(Int_t &locmax, Int_t &locmay, Int_t &locmaz) const
7967 {
7968  // empty the buffer
7969  if (fBuffer) ((TH1*)this)->BufferEmpty();
7970 
7971  Int_t bin, binx, biny, binz;
7972  Int_t locm;
7973  Int_t xfirst = fXaxis.GetFirst();
7974  Int_t xlast = fXaxis.GetLast();
7975  Int_t yfirst = fYaxis.GetFirst();
7976  Int_t ylast = fYaxis.GetLast();
7977  Int_t zfirst = fZaxis.GetFirst();
7978  Int_t zlast = fZaxis.GetLast();
7979  Double_t maximum = -FLT_MAX, value;
7980  locm = locmax = locmay = locmaz = 0;
7981  for (binz=zfirst;binz<=zlast;binz++) {
7982  for (biny=yfirst;biny<=ylast;biny++) {
7983  for (binx=xfirst;binx<=xlast;binx++) {
7984  bin = GetBin(binx,biny,binz);
7985  value = RetrieveBinContent(bin);
7986  if (value > maximum) {
7987  maximum = value;
7988  locm = bin;
7989  locmax = binx;
7990  locmay = biny;
7991  locmaz = binz;
7992  }
7993  }
7994  }
7995  }
7996  return locm;
7997 }
7998 
7999 
8000 ////////////////////////////////////////////////////////////////////////////////
8001 /// Return minimum value larger than minval of bins in the range,
8002 /// unless the value has been overridden by TH1::SetMinimum,
8003 /// in which case it returns that value. (This happens, for example,
8004 /// when the histogram is drawn and the y or z axis limits are changed
8005 ///
8006 /// To get the minimum value of bins in the histogram regardless of
8007 /// whether the value has been overridden, use
8008 /// h->GetBinContent(h->GetMinimumBin())
8009 
8010 Double_t TH1::GetMinimum(Double_t minval) const
8011 {
8012  if (fMinimum != -1111) return fMinimum;
8013 
8014  // empty the buffer
8015  if (fBuffer) ((TH1*)this)->BufferEmpty();
8016 
8017  Int_t bin, binx, biny, binz;
8018  Int_t xfirst = fXaxis.GetFirst();
8019  Int_t xlast = fXaxis.GetLast();
8020  Int_t yfirst = fYaxis.GetFirst();
8021  Int_t ylast = fYaxis.GetLast();
8022  Int_t zfirst = fZaxis.GetFirst();
8023  Int_t zlast = fZaxis.GetLast();
8024  Double_t minimum=FLT_MAX, value;
8025  for (binz=zfirst;binz<=zlast;binz++) {
8026  for (biny=yfirst;biny<=ylast;biny++) {
8027  for (binx=xfirst;binx<=xlast;binx++) {
8028  bin = GetBin(binx,biny,binz);
8029  value = RetrieveBinContent(bin);
8030  if (value < minimum && value > minval) minimum = value;
8031  }
8032  }
8033  }
8034  return minimum;
8035 }
8036 
8037 
8038 ////////////////////////////////////////////////////////////////////////////////
8039 /// Return location of bin with minimum value in the range.
8040 
8041 Int_t TH1::GetMinimumBin() const
8042 {
8043  Int_t locmix, locmiy, locmiz;
8044  return GetMinimumBin(locmix, locmiy, locmiz);
8045 }
8046 
8047 
8048 ////////////////////////////////////////////////////////////////////////////////
8049 /// Return location of bin with minimum value in the range.
8050 
8051 Int_t TH1::GetMinimumBin(Int_t &locmix, Int_t &locmiy, Int_t &locmiz) const
8052 {
8053  // empty the buffer
8054  if (fBuffer) ((TH1*)this)->BufferEmpty();
8055 
8056  Int_t bin, binx, biny, binz;
8057  Int_t locm;
8058  Int_t xfirst = fXaxis.GetFirst();
8059  Int_t xlast = fXaxis.GetLast();
8060  Int_t yfirst = fYaxis.GetFirst();
8061  Int_t ylast = fYaxis.GetLast();
8062  Int_t zfirst = fZaxis.GetFirst();
8063  Int_t zlast = fZaxis.GetLast();
8064  Double_t minimum = FLT_MAX, value;
8065  locm = locmix = locmiy = locmiz = 0;
8066  for (binz=zfirst;binz<=zlast;binz++) {
8067  for (biny=yfirst;biny<=ylast;biny++) {
8068  for (binx=xfirst;binx<=xlast;binx++) {
8069  bin = GetBin(binx,biny,binz);
8070  value = RetrieveBinContent(bin);
8071  if (value < minimum) {
8072  minimum = value;
8073  locm = bin;
8074  locmix = binx;
8075  locmiy = biny;
8076  locmiz = binz;
8077  }
8078  }
8079  }
8080  }
8081  return locm;
8082 }
8083 
8084 
8085 ////////////////////////////////////////////////////////////////////////////////
8086 /// Redefine x axis parameters.
8087 ///
8088 /// The X axis parameters are modified.
8089 /// The bins content array is resized
8090 /// if errors (Sumw2) the errors array is resized
8091 /// The previous bin contents are lost
8092 /// To change only the axis limits, see TAxis::SetRange
8093 
8094 void TH1::SetBins(Int_t nx, Double_t xmin, Double_t xmax)
8095 {
8096  if (GetDimension() != 1) {
8097  Error("SetBins","Operation only valid for 1-d histograms");
8098  return;
8099  }
8100  fXaxis.SetRange(0,0);
8101  fXaxis.Set(nx,xmin,xmax);
8102  fYaxis.Set(1,0,1);
8103  fZaxis.Set(1,0,1);
8104  fNcells = nx+2;
8105  SetBinsLength(fNcells);
8106  if (fSumw2.fN) {
8107  fSumw2.Set(fNcells);
8108  }
8109 }
8110 
8111 
8112 ////////////////////////////////////////////////////////////////////////////////
8113 /// Redefine x axis parameters with variable bin sizes.
8114 ///
8115 /// The X axis parameters are modified.
8116 /// The bins content array is resized
8117 /// if errors (Sumw2) the errors array is resized
8118 /// The previous bin contents are lost
8119 /// To change only the axis limits, see TAxis::SetRange
8120 /// xBins is supposed to be of length nx+1
8121 
8122 void TH1::SetBins(Int_t nx, const Double_t *xBins)
8123 {
8124  if (GetDimension() != 1) {
8125  Error("SetBins","Operation only valid for 1-d histograms");
8126  return;
8127  }
8128  fXaxis.SetRange(0,0);
8129  fXaxis.Set(nx,xBins);
8130  fYaxis.Set(1,0,1);
8131  fZaxis.Set(1,0,1);
8132  fNcells = nx+2;
8133  SetBinsLength(fNcells);
8134  if (fSumw2.fN) {
8135  fSumw2.Set(fNcells);
8136  }
8137 }
8138 
8139 
8140 ////////////////////////////////////////////////////////////////////////////////
8141 /// Redefine x and y axis parameters.
8142 ///
8143 /// The X and Y axis parameters are modified.
8144 /// The bins content array is resized
8145 /// if errors (Sumw2) the errors array is resized
8146 /// The previous bin contents are lost
8147 /// To change only the axis limits, see TAxis::SetRange
8148 
8149 void TH1::SetBins(Int_t nx, Double_t xmin, Double_t xmax, Int_t ny, Double_t ymin, Double_t ymax)
8150 {
8151  if (GetDimension() != 2) {
8152  Error("SetBins","Operation only valid for 2-D histograms");
8153  return;
8154  }
8155  fXaxis.SetRange(0,0);
8156  fYaxis.SetRange(0,0);
8157  fXaxis.Set(nx,xmin,xmax);
8158  fYaxis.Set(ny,ymin,ymax);
8159  fZaxis.Set(1,0,1);
8160  fNcells = (nx+2)*(ny+2);
8161  SetBinsLength(fNcells);
8162  if (fSumw2.fN) {
8163  fSumw2.Set(fNcells);
8164  }
8165 }
8166 
8167 
8168 ////////////////////////////////////////////////////////////////////////////////
8169 /// Redefine x and y axis parameters with variable bin sizes.
8170 ///
8171 /// The X and Y axis parameters are modified.
8172 /// The bins content array is resized
8173 /// if errors (Sumw2) the errors array is resized
8174 /// The previous bin contents are lost
8175 /// To change only the axis limits, see TAxis::SetRange
8176 /// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1
8177 
8178 void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins)
8179 {
8180  if (GetDimension() != 2) {
8181  Error("SetBins","Operation only valid for 2-D histograms");
8182  return;
8183  }
8184  fXaxis.SetRange(0,0);
8185  fYaxis.SetRange(0,0);
8186  fXaxis.Set(nx,xBins);
8187  fYaxis.Set(ny,yBins);
8188  fZaxis.Set(1,0,1);
8189  fNcells = (nx+2)*(ny+2);
8190  SetBinsLength(fNcells);
8191  if (fSumw2.fN) {
8192  fSumw2.Set(fNcells);
8193  }
8194 }
8195 
8196 
8197 ////////////////////////////////////////////////////////////////////////////////
8198 /// Redefine x, y and z axis parameters.
8199 ///
8200 /// The X, Y and Z axis parameters are modified.
8201 /// The bins content array is resized
8202 /// if errors (Sumw2) the errors array is resized
8203 /// The previous bin contents are lost
8204 /// To change only the axis limits, see TAxis::SetRange
8205 
8206 void TH1::SetBins(Int_t nx, Double_t xmin, Double_t xmax, Int_t ny, Double_t ymin, Double_t ymax, Int_t nz, Double_t zmin, Double_t zmax)
8207 {
8208  if (GetDimension() != 3) {
8209  Error("SetBins","Operation only valid for 3-D histograms");
8210  return;
8211  }
8212  fXaxis.SetRange(0,0);
8213  fYaxis.SetRange(0,0);
8214  fZaxis.SetRange(0,0);
8215  fXaxis.Set(nx,xmin,xmax);
8216  fYaxis.Set(ny,ymin,ymax);
8217  fZaxis.Set(nz,zmin,zmax);
8218  fNcells = (nx+2)*(ny+2)*(nz+2);
8219  SetBinsLength(fNcells);
8220  if (fSumw2.fN) {
8221  fSumw2.Set(fNcells);
8222  }
8223 }
8224 
8225 
8226 ////////////////////////////////////////////////////////////////////////////////
8227 /// Redefine x, y and z axis parameters with variable bin sizes.
8228 ///
8229 /// The X, Y and Z axis parameters are modified.
8230 /// The bins content array is resized
8231 /// if errors (Sumw2) the errors array is resized
8232 /// The previous bin contents are lost
8233 /// To change only the axis limits, see TAxis::SetRange
8234 /// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1,
8235 /// zBins is supposed to be of length nz+1
8236 
8237 void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins, Int_t nz, const Double_t *zBins)
8238 {
8239  if (GetDimension() != 3) {
8240  Error("SetBins","Operation only valid for 3-D histograms");
8241  return;
8242  }
8243  fXaxis.SetRange(0,0);
8244  fYaxis.SetRange(0,0);
8245  fZaxis.SetRange(0,0);
8246  fXaxis.Set(nx,xBins);
8247  fYaxis.Set(ny,yBins);
8248  fZaxis.Set(nz,zBins);
8249  fNcells = (nx+2)*(ny+2)*(nz+2);
8250  SetBinsLength(fNcells);
8251  if (fSumw2.fN) {
8252  fSumw2.Set(fNcells);
8253  }
8254 }
8255 
8256 
8257 ////////////////////////////////////////////////////////////////////////////////
8258 /// By default when an histogram is created, it is added to the list
8259 /// of histogram objects in the current directory in memory.
8260 /// Remove reference to this histogram from current directory and add
8261 /// reference to new directory dir. dir can be 0 in which case the
8262 /// histogram does not belong to any directory.
8263 ///
8264 /// Note that the directory is not a real property of the histogram and
8265 /// it will not be copied when the histogram is copied or cloned.
8266 /// If the user wants to have the copied (cloned) histogram in the same
8267 /// directory, he needs to set again the directory using SetDirectory to the
8268 /// copied histograms
8269 
8270 void TH1::SetDirectory(TDirectory *dir)
8271 {
8272  if (fDirectory == dir) return;
8273  if (fDirectory) fDirectory->Remove(this);
8274  fDirectory = dir;
8275  if (fDirectory) fDirectory->Append(this);
8276 }
8277 
8278 
8279 ////////////////////////////////////////////////////////////////////////////////
8280 /// Replace bin errors by values in array error.
8281 
8282 void TH1::SetError(const Double_t *error)
8283 {
8284  for (Int_t i = 0; i < fNcells; ++i) SetBinError(i, error[i]);
8285 }
8286 
8287 
8288 ////////////////////////////////////////////////////////////////////////////////
8289 /// Change the name of this histogram
8290 ///
8291 
8292 void TH1::SetName(const char *name)
8293 {
8294  // Histograms are named objects in a THashList.
8295  // We must update the hashlist if we change the name
8296  // We protect this operation
8298  if (fDirectory) fDirectory->Remove(this);
8299  fName = name;
8300  if (fDirectory) fDirectory->Append(this);
8301 }
8302 
8303 
8304 ////////////////////////////////////////////////////////////////////////////////
8305 /// Change the name and title of this histogram
8306 
8307 void TH1::SetNameTitle(const char *name, const char *title)
8308 {
8309  // Histograms are named objects in a THashList.
8310  // We must update the hashlist if we change the name
8311  SetName(name);
8312  SetTitle(title);
8313 }
8314 
8315 
8316 ////////////////////////////////////////////////////////////////////////////////
8317 /// Set statistics option on/off
8318 ///
8319 /// By default, the statistics box is drawn.
8320 /// The paint options can be selected via gStyle->SetOptStats.
8321 /// This function sets/resets the kNoStats bin in the histogram object.
8322 /// It has priority over the Style option.
8323 
8324 void TH1::SetStats(Bool_t stats)
8325 {
8327  if (!stats) {
8328  SetBit(kNoStats);
8329  //remove the "stats" object from the list of functions
8330  if (fFunctions) {
8331  TObject *obj = fFunctions->FindObject("stats");
8332  if (obj) {
8333  fFunctions->Remove(obj);
8334  delete obj;
8335  }
8336  }
8337  }
8338 }
8339 
8340 
8341 ////////////////////////////////////////////////////////////////////////////////
8342 /// Create structure to store sum of squares of weights.
8343 ///
8344 /// if histogram is already filled, the sum of squares of weights
8345 /// is filled with the existing bin contents
8346 ///
8347 /// The error per bin will be computed as sqrt(sum of squares of weight)
8348 /// for each bin.
8349 ///
8350 /// This function is automatically called when the histogram is created
8351 /// if the static function TH1::SetDefaultSumw2 has been called before.
8352 /// If flag = false the structure is deleted
8353 
8354 void TH1::Sumw2(Bool_t flag)
8355 {
8356  if (!flag) {
8357  // clear the array if existing - do nothing otherwise
8358  if (fSumw2.fN > 0 ) fSumw2.Set(0);
8359  return;
8360  }
8361 
8362  if (fSumw2.fN == fNcells) {
8363  if (!fgDefaultSumw2 )
8364  Warning("Sumw2","Sum of squares of weights structure already created");
8365  return;
8366  }
8367 
8368  fSumw2.Set(fNcells);
8369 
8370  // empty the buffer
8371  if (fBuffer) BufferEmpty();
8372 
8373  if (fEntries > 0)
8374  for (Int_t i = 0; i < fNcells; ++i)
8376 }
8377 
8378 
8379 ////////////////////////////////////////////////////////////////////////////////
8380 /// Return pointer to function with name.
8381 ///
8382 ///
8383 /// Functions such as TH1::Fit store the fitted function in the list of
8384 /// functions of this histogram.
8385 
8386 TF1 *TH1::GetFunction(const char *name) const
8387 {
8388  return (TF1*)fFunctions->FindObject(name);
8389 }
8390 
8391 
8392 ////////////////////////////////////////////////////////////////////////////////
8393 /// Return value of error associated to bin number bin.
8394 ///
8395 /// if the sum of squares of weights has been defined (via Sumw2),
8396 /// this function returns the sqrt(sum of w2).
8397 /// otherwise it returns the sqrt(contents) for this bin.
8398 
8399 Double_t TH1::GetBinError(Int_t bin) const
8400 {
8401  if (bin < 0) bin = 0;
8402  if (bin >= fNcells) bin = fNcells-1;
8403  if (fBuffer) ((TH1*)this)->BufferEmpty();
8404  if (fSumw2.fN) return TMath::Sqrt(fSumw2.fArray[bin]);
8405 
8407 }
8408 
8409 
8410 ////////////////////////////////////////////////////////////////////////////////
8411 /// Return lower error associated to bin number bin.
8412 ///
8413 /// The error will depend on the statistic option used will return
8414 /// the binContent - lower interval value
8415 
8417 {
8418  if (fBinStatErrOpt == kNormal || fSumw2.fN) return GetBinError(bin);
8419  if (bin < 0) bin = 0;
8420  if (bin >= fNcells) bin = fNcells-1;
8421  if (fBuffer) ((TH1*)this)->BufferEmpty();
8422 
8423  Double_t alpha = 1.- 0.682689492;
8424  if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
8425 
8426  Double_t c = RetrieveBinContent(bin);
8427  Int_t n = int(c);
8428  if (n < 0) {
8429  Warning("GetBinErrorLow","Histogram has negative bin content-force usage to normal errors");
8430  ((TH1*)this)->fBinStatErrOpt = kNormal;
8431  return GetBinError(bin);
8432  }
8433 
8434  if (n == 0) return 0;
8435  return c - ROOT::Math::gamma_quantile( alpha/2, n, 1.);
8436 }
8437 
8438 
8439 ////////////////////////////////////////////////////////////////////////////////
8440 /// Return upper error associated to bin number bin.
8441 ///
8442 /// The error will depend on the statistic option used will return
8443 /// the binContent - upper interval value
8444 
8446 {
8447  if (fBinStatErrOpt == kNormal || fSumw2.fN) return GetBinError(bin);
8448  if (bin < 0) bin = 0;
8449  if (bin >= fNcells) bin = fNcells-1;
8450  if (fBuffer) ((TH1*)this)->BufferEmpty();
8451 
8452  Double_t alpha = 1.- 0.682689492;
8453  if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
8454 
8455  Double_t c = RetrieveBinContent(bin);
8456  Int_t n = int(c);
8457  if (n < 0) {
8458  Warning("GetBinErrorUp","Histogram has negative bin content-force usage to normal errors");
8459  ((TH1*)this)->fBinStatErrOpt = kNormal;
8460  return GetBinError(bin);
8461  }
8462 
8463  // for N==0 return an upper limit at 0.68 or (1-alpha)/2 ?
8464  // decide to return always (1-alpha)/2 upper interval
8465  //if (n == 0) return ROOT::Math::gamma_quantile_c(alpha,n+1,1);
8466  return ROOT::Math::gamma_quantile_c( alpha/2, n+1, 1) - c;
8467 }
8468 
8469 //L.M. These following getters are useless and should be probably deprecated
8470 ////////////////////////////////////////////////////////////////////////////////
8471 /// return bin center for 1D historam
8472 /// Better to use h1.GetXaxis().GetBinCenter(bin)
8473 
8474 Double_t TH1::GetBinCenter(Int_t bin) const
8475 {
8476  if (fDimension == 1) return fXaxis.GetBinCenter(bin);
8477  Error("GetBinCenter","Invalid method for a %d-d histogram - return a NaN",fDimension);
8478  return TMath::QuietNaN();
8479 }
8480 
8481 ////////////////////////////////////////////////////////////////////////////////
8482 /// return bin lower edge for 1D historam
8483 /// Better to use h1.GetXaxis().GetBinLowEdge(bin)
8484 
8486 {
8487  if (fDimension == 1) return fXaxis.GetBinLowEdge(bin);
8488  Error("GetBinLowEdge","Invalid method for a %d-d histogram - return a NaN",fDimension);
8489  return TMath::QuietNaN();
8490 }
8491 
8492 ////////////////////////////////////////////////////////////////////////////////
8493 /// return bin width for 1D historam
8494 /// Better to use h1.GetXaxis().GetBinWidth(bin)
8495 
8496 Double_t TH1::GetBinWidth(Int_t bin) const
8497 {
8498  if (fDimension == 1) return fXaxis.GetBinWidth(bin);
8499  Error("GetBinWidth","Invalid method for a %d-d histogram - return a NaN",fDimension);
8500  return TMath::QuietNaN();
8501 }
8502 
8503 ////////////////////////////////////////////////////////////////////////////////
8504 /// Fill array with center of bins for 1D histogram
8505 /// Better to use h1.GetXaxis().GetCenter(center)
8506 
8507 void TH1::GetCenter(Double_t *center) const
8508 {
8509  if (fDimension == 1) {
8510  fXaxis.GetCenter(center);
8511  return;
8512  }
8513  Error("GetCenter","Invalid method for a %d-d histogram ",fDimension);
8514 }
8515 
8516 ////////////////////////////////////////////////////////////////////////////////
8517 /// Fill array with low edge of bins for 1D histogram
8518 /// Better to use h1.GetXaxis().GetLowEdge(edge)
8519 
8520 void TH1::GetLowEdge(Double_t *edge) const
8521 {
8522  if (fDimension == 1) {
8523  fXaxis.GetLowEdge(edge);
8524  return;
8525  }
8526  Error("GetLowEdge","Invalid method for a %d-d histogram ",fDimension);
8527 }
8528 
8529 ////////////////////////////////////////////////////////////////////////////////
8530 /// see convention for numbering bins in TH1::GetBin
8531 
8532 void TH1::SetBinError(Int_t bin, Double_t error)
8533 {
8534  if (!fSumw2.fN) Sumw2();
8535  if (bin < 0 || bin>= fSumw2.fN) return;
8536  fSumw2.fArray[bin] = error * error;
8537 }
8538 
8539 
8540 ////////////////////////////////////////////////////////////////////////////////
8541 /// Set bin content
8542 /// see convention for numbering bins in TH1::GetBin
8543 /// In case the bin number is greater than the number of bins and
8544 /// the timedisplay option is set or CanExtendAllAxes(),
8545 /// the number of bins is automatically doubled to accommodate the new bin
8546 
8547 void TH1::SetBinContent(Int_t bin, Double_t content)
8548 {
8550  fTsumw = 0;
8551  if (bin < 0) return;
8552  if (bin >= fNcells-1) {
8553  if (fXaxis.GetTimeDisplay() || CanExtendAllAxes() ) {
8554  while (bin >= fNcells-1) LabelsInflate();
8555  } else {
8556  if (bin == fNcells-1) UpdateBinContent(bin, content);
8557  return;
8558  }
8559  }
8560  UpdateBinContent(bin, content);
8561 }
8562 
8563 
8564 ////////////////////////////////////////////////////////////////////////////////
8565 /// see convention for numbering bins in TH1::GetBin
8566 
8567 void TH1::SetBinError(Int_t binx, Int_t biny, Double_t error)
8568 {
8569  if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
8570  if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
8571  SetBinError(GetBin(binx, biny), error);
8572 }
8573 
8574 
8575 ////////////////////////////////////////////////////////////////////////////////
8576 /// see convention for numbering bins in TH1::GetBin
8577 
8578 void TH1::SetBinError(Int_t binx, Int_t biny, Int_t binz, Double_t error)
8579 {
8580  if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
8581  if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
8582  if (binz < 0 || binz > fZaxis.GetNbins() + 1) return;
8583  SetBinError(GetBin(binx, biny, binz), error);
8584 }
8585 
8586 
8587 ////////////////////////////////////////////////////////////////////////////////
8588 /// This function calculates the background spectrum in this histogram.
8589 /// The background is returned as a histogram.
8590 ///
8591 /// \param[in] niter number of iterations (default value = 2)
8592 /// Increasing niter make the result smoother and lower.
8593 /// \param[in] option may contain one of the following options
8594 /// - to set the direction parameter
8595 /// "BackDecreasingWindow". By default the direction is BackIncreasingWindow
8596 /// - filterOrder-order of clipping filter (default "BackOrder2")
8597 /// possible values= "BackOrder4" "BackOrder6" "BackOrder8"
8598 /// - "nosmoothing" - if selected, the background is not smoothed
8599 /// By default the background is smoothed.
8600 /// - smoothWindow - width of smoothing window, (default is "BackSmoothing3")
8601 /// possible values= "BackSmoothing5" "BackSmoothing7" "BackSmoothing9"
8602 /// "BackSmoothing11" "BackSmoothing13" "BackSmoothing15"
8603 /// - "nocompton" - if selected the estimation of Compton edge
8604 /// will be not be included (by default the compton estimation is set)
8605 /// - "same" if this option is specified, the resulting background
8606 /// histogram is superimposed on the picture in the current pad.
8607 /// This option is given by default.
8608 ///
8609 /// NOTE that the background is only evaluated in the current range of this histogram.
8610 /// i.e., if this has a bin range (set via h->GetXaxis()->SetRange(binmin, binmax),
8611 /// the returned histogram will be created with the same number of bins
8612 /// as this input histogram, but only bins from binmin to binmax will be filled
8613 /// with the estimated background.
8614 ///
8615 
8616 TH1 *TH1::ShowBackground(Int_t niter, Option_t *option)
8617 {
8619  return (TH1*)gROOT->ProcessLineFast(Form("TSpectrum::StaticBackground((TH1*)0x%lx,%d,\"%s\")",
8620  (ULong_t)this, niter, option));
8621 }
8622 
8623 
8624 ////////////////////////////////////////////////////////////////////////////////
8625 /// Interface to TSpectrum::Search.
8626 /// The function finds peaks in this histogram where the width is > sigma
8627 /// and the peak maximum greater than threshold*maximum bin content of this.
8628 /// For more details see TSpectrum::Search.
8629 /// Note the difference in the default value for option compared to TSpectrum::Search
8630 /// option="" by default (instead of "goff").
8631 
8632 Int_t TH1::ShowPeaks(Double_t sigma, Option_t *option, Double_t threshold)
8633 {
8634  return (Int_t)gROOT->ProcessLineFast(Form("TSpectrum::StaticSearch((TH1*)0x%lx,%g,\"%s\",%g)",
8635  (ULong_t)this, sigma, option, threshold));
8636 }
8637 
8638 
8639 
8640 ////////////////////////////////////////////////////////////////////////////////
8641 /// For a given transform (first parameter), fills the histogram (second parameter)
8642 /// with the transform output data, specified in the third parameter
8643 /// If the 2nd parameter h_output is empty, a new histogram (TH1D or TH2D) is created
8644 /// and the user is responsible for deleting it.
8645 /// Available options:
8646 /// - "RE" - real part of the output
8647 /// - "IM" - imaginary part of the output
8648 /// - "MAG" - magnitude of the output
8649 /// - "PH" - phase of the output
8650 
8651 TH1* TH1::TransformHisto(TVirtualFFT *fft, TH1* h_output, Option_t *option)
8652 {
8653  if (!fft || !fft->GetN() ) {
8654  ::Error("TransformHisto","Invalid FFT transform class");
8655  return 0;
8656  }
8657 
8658  if (fft->GetNdim()>2){
8659  ::Error("TransformHisto","Only 1d and 2D transform are supported");
8660  return 0;
8661  }
8662  Int_t binx,biny;
8663  TString opt = option;
8664  opt.ToUpper();
8665  Int_t *n = fft->GetN();
8666  TH1 *hout=0;
8667  if (h_output) {
8668  hout = h_output;
8669  }
8670  else {
8671  TString name = TString::Format("out_%s", opt.Data());
8672  if (fft->GetNdim()==1)
8673  hout = new TH1D(name, name,n[0], 0, n[0]);
8674  else if (fft->GetNdim()==2)
8675  hout = new TH2D(name, name, n[0], 0, n[0], n[1], 0, n[1]);
8676  }
8677  R__ASSERT(hout != 0);
8678  TString type=fft->GetType();
8679  Int_t ind[2];
8680  if (opt.Contains("RE")){
8681  if (type.Contains("2C") || type.Contains("2HC")) {
8682  Double_t re, im;
8683  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8684  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8685  ind[0] = binx-1; ind[1] = biny-1;
8686  fft->GetPointComplex(ind, re, im);
8687  hout->SetBinContent(binx, biny, re);
8688  }
8689  }
8690  } else {
8691  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8692  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8693  ind[0] = binx-1; ind[1] = biny-1;
8694  hout->SetBinContent(binx, biny, fft->GetPointReal(ind));
8695  }
8696  }
8697  }
8698  }
8699  if (opt.Contains("IM")) {
8700  if (type.Contains("2C") || type.Contains("2HC")) {
8701  Double_t re, im;
8702  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8703  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8704  ind[0] = binx-1; ind[1] = biny-1;
8705  fft->GetPointComplex(ind, re, im);
8706  hout->SetBinContent(binx, biny, im);
8707  }
8708  }
8709  } else {
8710  ::Error("TransformHisto","No complex numbers in the output");
8711  return 0;
8712  }
8713  }
8714  if (opt.Contains("MA")) {
8715  if (type.Contains("2C") || type.Contains("2HC")) {
8716  Double_t re, im;
8717  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8718  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8719  ind[0] = binx-1; ind[1] = biny-1;
8720  fft->GetPointComplex(ind, re, im);
8721  hout->SetBinContent(binx, biny, TMath::Sqrt(re*re + im*im));
8722  }
8723  }
8724  } else {
8725  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8726  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8727  ind[0] = binx-1; ind[1] = biny-1;
8728  hout->SetBinContent(binx, biny, TMath::Abs(fft->GetPointReal(ind)));
8729  }
8730  }
8731  }
8732  }
8733  if (opt.Contains("PH")) {
8734  if (type.Contains("2C") || type.Contains("2HC")){
8735  Double_t re, im, ph;
8736  for (binx = 1; binx<=hout->GetNbinsX(); binx++){
8737  for (biny=1; biny<=hout->GetNbinsY(); biny++){
8738  ind[0] = binx-1; ind[1] = biny-1;
8739  fft->GetPointComplex(ind, re, im);
8740  if (TMath::Abs(re) > 1e-13){
8741  ph = TMath::ATan(im/re);
8742  //find the correct quadrant
8743  if (re<0 && im<0)
8744  ph -= TMath::Pi();
8745  if (re<0 && im>=0)
8746  ph += TMath::Pi();
8747  } else {
8748  if (TMath::Abs(im) < 1e-13)
8749  ph = 0;
8750  else if (im>0)
8751  ph = TMath::Pi()*0.5;
8752  else
8753  ph = -TMath::Pi()*0.5;
8754  }
8755  hout->SetBinContent(binx, biny, ph);
8756  }
8757  }
8758  } else {
8759  printf("Pure real output, no phase");
8760  return 0;
8761  }
8762  }
8763 
8764  return hout;
8765 }
8766 
8767 
8768 ////////////////////////////////////////////////////////////////////////////////
8769 /// raw retrieval of bin content on internal data structure
8770 /// see convention for numbering bins in TH1::GetBin
8771 
8773 {
8774  AbstractMethod("RetrieveBinContent");
8775  return 0;
8776 }
8777 
8778 
8779 ////////////////////////////////////////////////////////////////////////////////
8780 /// raw update of bin content on internal data structure
8781 /// see convention for numbering bins in TH1::GetBin
8782 
8784 {
8785  AbstractMethod("UpdateBinContent");
8786 }
8787 
8788 ////////////////////////////////////////////////////////////////////////////////
8789 /// Print value overload
8790 
8791 std::string cling::printValue(TH1 *val) {
8792  std::ostringstream strm;
8793  strm << cling::printValue((TObject*)val) << " NbinsX: " << val->GetNbinsX();
8794  return strm.str();
8795 }
8796 
8797 
8798 //______________________________________________________________________________
8799 // TH1C methods
8800 // TH1C : histograms with one byte per channel. Maximum bin content = 127
8801 //______________________________________________________________________________
8802 
8803 ClassImp(TH1C)
8804 
8805 
8806 ////////////////////////////////////////////////////////////////////////////////
8807 /// Constructor.
8808 
8809 TH1C::TH1C(): TH1(), TArrayC()
8810 {
8812  SetBinsLength(3);
8813  if (fgDefaultSumw2) Sumw2();
8814 }
8815 
8816 
8817 ////////////////////////////////////////////////////////////////////////////////
8818 /// Create a 1-Dim histogram with fix bins of type char (one byte per channel)
8819 /// (see TH1::TH1 for explanation of parameters)
8820 
8821 TH1C::TH1C(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
8822 : TH1(name,title,nbins,xlow,xup)
8824  fDimension = 1;
8825  TArrayC::Set(fNcells);
8826 
8827  if (xlow >= xup) SetBuffer(fgBufferSize);
8828  if (fgDefaultSumw2) Sumw2();
8829 }
8830 
8831 
8832 ////////////////////////////////////////////////////////////////////////////////
8833 /// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
8834 /// (see TH1::TH1 for explanation of parameters)
8835 
8836 TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
8837 : TH1(name,title,nbins,xbins)
8839  fDimension = 1;
8840  TArrayC::Set(fNcells);
8841  if (fgDefaultSumw2) Sumw2();
8842 }
8843 
8844 
8845 ////////////////////////////////////////////////////////////////////////////////
8846 /// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
8847 /// (see TH1::TH1 for explanation of parameters)
8848 
8849 TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
8850 : TH1(name,title,nbins,xbins)
8852  fDimension = 1;
8853  TArrayC::Set(fNcells);
8854  if (fgDefaultSumw2) Sumw2();
8855 }
8856 
8857 
8858 ////////////////////////////////////////////////////////////////////////////////
8859 /// Destructor.
8860 
8861 TH1C::~TH1C()
8862 {
8864 
8865 
8866 ////////////////////////////////////////////////////////////////////////////////
8867 /// Copy constructor.
8868 
8869 TH1C::TH1C(const TH1C &h1c) : TH1(), TArrayC()
8870 {
8871  ((TH1C&)h1c).Copy(*this);
8872 }
8873 
8874 
8875 ////////////////////////////////////////////////////////////////////////////////
8876 /// Increment bin content by 1.
8877 
8878 void TH1C::AddBinContent(Int_t bin)
8879 {
8880  if (fArray[bin] < 127) fArray[bin]++;
8881 }
8882 
8883 
8884 ////////////////////////////////////////////////////////////////////////////////
8885 /// Increment bin content by w.
8886 
8887 void TH1C::AddBinContent(Int_t bin, Double_t w)
8888 {
8889  Int_t newval = fArray[bin] + Int_t(w);
8890  if (newval > -128 && newval < 128) {fArray[bin] = Char_t(newval); return;}
8891  if (newval < -127) fArray[bin] = -127;
8892  if (newval > 127) fArray[bin] = 127;
8893 }
8894 
8895 
8896 ////////////////////////////////////////////////////////////////////////////////
8897 /// Copy this to newth1
8898 
8899 void TH1C::Copy(TObject &newth1) const
8900 {
8901  TH1::Copy(newth1);
8902 }
8903 
8904 
8905 ////////////////////////////////////////////////////////////////////////////////
8906 /// Reset.
8907 
8908 void TH1C::Reset(Option_t *option)
8909 {
8910  TH1::Reset(option);
8911  TArrayC::Reset();
8912 }
8913 
8914 
8915 ////////////////////////////////////////////////////////////////////////////////
8916 /// Set total number of bins including under/overflow
8917 /// Reallocate bin contents array
8918 
8919 void TH1C::SetBinsLength(Int_t n)
8920 {
8921  if (n < 0) n = fXaxis.GetNbins() + 2;
8922  fNcells = n;
8923  TArrayC::Set(n);
8924 }
8925 
8926 
8927 ////////////////////////////////////////////////////////////////////////////////
8928 /// Operator =
8929 
8930 TH1C& TH1C::operator=(const TH1C &h1)
8931 {
8932  if (this != &h1) ((TH1C&)h1).Copy(*this);
8933  return *this;
8934 }
8935 
8936 
8937 
8938 ////////////////////////////////////////////////////////////////////////////////
8939 /// Operator *
8940 
8941 TH1C operator*(Double_t c1, const TH1C &h1)
8942 {
8943  TH1C hnew = h1;
8944  hnew.Scale(c1);
8945  hnew.SetDirectory(0);
8946  return hnew;
8947 }
8948 
8949 
8950 ////////////////////////////////////////////////////////////////////////////////
8951 /// Operator +
8952 
8953 TH1C operator+(const TH1C &h1, const TH1C &h2)
8954 {
8955  TH1C hnew = h1;
8956  hnew.Add(&h2,1);
8957  hnew.SetDirectory(0);
8958  return hnew;
8959 }
8960 
8961 
8962 ////////////////////////////////////////////////////////////////////////////////
8963 /// Operator -
8964 
8965 TH1C operator-(const TH1C &h1, const TH1C &h2)
8966 {
8967  TH1C hnew = h1;
8968  hnew.Add(&h2,-1);
8969  hnew.SetDirectory(0);
8970  return hnew;
8971 }
8972 
8973 
8974 ////////////////////////////////////////////////////////////////////////////////
8975 /// Operator *
8976 
8977 TH1C operator*(const TH1C &h1, const TH1C &h2)
8978 {
8979  TH1C hnew = h1;
8980  hnew.Multiply(&h2);
8981  hnew.SetDirectory(0);
8982  return hnew;
8983 }
8984 
8985 
8986 ////////////////////////////////////////////////////////////////////////////////
8987 /// Operator /
8988 
8989 TH1C operator/(const TH1C &h1, const TH1C &h2)
8990 {
8991  TH1C hnew = h1;
8992  hnew.Divide(&h2);
8993  hnew.SetDirectory(0);
8994  return hnew;
8995 }
8996 
8997 
8998 
8999 //______________________________________________________________________________
9000 // TH1S methods
9001 // TH1S : histograms with one short per channel. Maximum bin content = 32767
9002 //______________________________________________________________________________
9003 
9004 ClassImp(TH1S)
9005 
9006 
9007 ////////////////////////////////////////////////////////////////////////////////
9008 /// Constructor.
9009 
9010 TH1S::TH1S(): TH1(), TArrayS()
9011 {
9013  SetBinsLength(3);
9014  if (fgDefaultSumw2) Sumw2();
9015 }
9016 
9017 
9018 ////////////////////////////////////////////////////////////////////////////////
9019 /// Create a 1-Dim histogram with fix bins of type short
9020 /// (see TH1::TH1 for explanation of parameters)
9021 
9022 TH1S::TH1S(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9023 : TH1(name,title,nbins,xlow,xup)
9025  fDimension = 1;
9026  TArrayS::Set(fNcells);
9027 
9028  if (xlow >= xup) SetBuffer(fgBufferSize);
9029  if (fgDefaultSumw2) Sumw2();
9030 }
9031 
9032 
9033 ////////////////////////////////////////////////////////////////////////////////
9034 /// Create a 1-Dim histogram with variable bins of type short
9035 /// (see TH1::TH1 for explanation of parameters)
9036 
9037 TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9038 : TH1(name,title,nbins,xbins)
9040  fDimension = 1;
9041  TArrayS::Set(fNcells);
9042  if (fgDefaultSumw2) Sumw2();
9043 }
9044 
9045 
9046 ////////////////////////////////////////////////////////////////////////////////
9047 /// Create a 1-Dim histogram with variable bins of type short
9048 /// (see TH1::TH1 for explanation of parameters)
9049 
9050 TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9051 : TH1(name,title,nbins,xbins)
9053  fDimension = 1;
9054  TArrayS::Set(fNcells);
9055  if (fgDefaultSumw2) Sumw2();
9056 }
9057 
9058 
9059 ////////////////////////////////////////////////////////////////////////////////
9060 /// Destructor.
9061 
9062 TH1S::~TH1S()
9063 {
9065 
9066 
9067 ////////////////////////////////////////////////////////////////////////////////
9068 /// Copy constructor.
9069 
9070 TH1S::TH1S(const TH1S &h1s) : TH1(), TArrayS()
9071 {
9072  ((TH1S&)h1s).Copy(*this);
9073 }
9074 
9075 
9076 ////////////////////////////////////////////////////////////////////////////////
9077 /// Increment bin content by 1.
9078 
9079 void TH1S::AddBinContent(Int_t bin)
9080 {
9081  if (fArray[bin] < 32767) fArray[bin]++;
9082 }
9083 
9084 
9085 ////////////////////////////////////////////////////////////////////////////////
9086 /// Increment bin content by w
9087 
9088 void TH1S::AddBinContent(Int_t bin, Double_t w)
9089 {
9090  Int_t newval = fArray[bin] + Int_t(w);
9091  if (newval > -32768 && newval < 32768) {fArray[bin] = Short_t(newval); return;}
9092  if (newval < -32767) fArray[bin] = -32767;
9093  if (newval > 32767) fArray[bin] = 32767;
9094 }
9095 
9096 
9097 ////////////////////////////////////////////////////////////////////////////////
9098 /// Copy this to newth1
9099 
9100 void TH1S::Copy(TObject &newth1) const
9101 {
9102  TH1::Copy(newth1);
9103 }
9104 
9105 
9106 ////////////////////////////////////////////////////////////////////////////////
9107 /// Reset.
9108 
9109 void TH1S::Reset(Option_t *option)
9110 {
9111  TH1::Reset(option);
9112  TArrayS::Reset();
9113 }
9114 
9115 
9116 ////////////////////////////////////////////////////////////////////////////////
9117 /// Set total number of bins including under/overflow
9118 /// Reallocate bin contents array
9119 
9120 void TH1S::SetBinsLength(Int_t n)
9121 {
9122  if (n < 0) n = fXaxis.GetNbins() + 2;
9123  fNcells = n;
9124  TArrayS::Set(n);
9125 }
9126 
9127 
9128 ////////////////////////////////////////////////////////////////////////////////
9129 /// Operator =
9130 
9131 TH1S& TH1S::operator=(const TH1S &h1)
9132 {
9133  if (this != &h1) ((TH1S&)h1).Copy(*this);
9134  return *this;
9135 }
9136 
9137 
9138 ////////////////////////////////////////////////////////////////////////////////
9139 /// Operator *
9140 
9141 TH1S operator*(Double_t c1, const TH1S &h1)
9142 {
9143  TH1S hnew = h1;
9144  hnew.Scale(c1);
9145  hnew.SetDirectory(0);
9146  return hnew;
9147 }
9148 
9149 
9150 ////////////////////////////////////////////////////////////////////////////////
9151 /// Operator +
9152 
9153 TH1S operator+(const TH1S &h1, const TH1S &h2)
9154 {
9155  TH1S hnew = h1;
9156  hnew.Add(&h2,1);
9157  hnew.SetDirectory(0);
9158  return hnew;
9159 }
9160 
9161 
9162 ////////////////////////////////////////////////////////////////////////////////
9163 /// Operator -
9164 
9165 TH1S operator-(const TH1S &h1, const TH1S &h2)
9166 {
9167  TH1S hnew = h1;
9168  hnew.Add(&h2,-1);
9169  hnew.SetDirectory(0);
9170  return hnew;
9171 }
9172 
9173 
9174 ////////////////////////////////////////////////////////////////////////////////
9175 /// Operator *
9176 
9177 TH1S operator*(const TH1S &h1, const TH1S &h2)
9178 {
9179  TH1S hnew = h1;
9180  hnew.Multiply(&h2);
9181  hnew.SetDirectory(0);
9182  return hnew;
9183 }
9184 
9185 
9186 ////////////////////////////////////////////////////////////////////////////////
9187 /// Operator /
9188 
9189 TH1S operator/(const TH1S &h1, const TH1S &h2)
9190 {
9191  TH1S hnew = h1;
9192  hnew.Divide(&h2);
9193  hnew.SetDirectory(0);
9194  return hnew;
9195 }
9196 
9197 
9198 //______________________________________________________________________________
9199 // TH1I methods
9200 // TH1I : histograms with one int per channel. Maximum bin content = 2147483647
9201 //______________________________________________________________________________
9202 
9203 ClassImp(TH1I)
9204 
9205 
9206 ////////////////////////////////////////////////////////////////////////////////
9207 /// Constructor.
9208 
9209 TH1I::TH1I(): TH1(), TArrayI()
9210 {
9212  SetBinsLength(3);
9213  if (fgDefaultSumw2) Sumw2();
9214 }
9215 
9216 
9217 ////////////////////////////////////////////////////////////////////////////////
9218 /// Create a 1-Dim histogram with fix bins of type integer
9219 /// (see TH1::TH1 for explanation of parameters)
9220 
9221 TH1I::TH1I(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9222 : TH1(name,title,nbins,xlow,xup)
9224  fDimension = 1;
9225  TArrayI::Set(fNcells);
9226 
9227  if (xlow >= xup) SetBuffer(fgBufferSize);
9228  if (fgDefaultSumw2) Sumw2();
9229 }
9230 
9231 
9232 ////////////////////////////////////////////////////////////////////////////////
9233 /// Create a 1-Dim histogram with variable bins of type integer
9234 /// (see TH1::TH1 for explanation of parameters)
9235 
9236 TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9237 : TH1(name,title,nbins,xbins)
9239  fDimension = 1;
9240  TArrayI::Set(fNcells);
9241  if (fgDefaultSumw2) Sumw2();
9242 }
9243 
9244 
9245 ////////////////////////////////////////////////////////////////////////////////
9246 /// Create a 1-Dim histogram with variable bins of type integer
9247 /// (see TH1::TH1 for explanation of parameters)
9248 
9249 TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9250 : TH1(name,title,nbins,xbins)
9252  fDimension = 1;
9253  TArrayI::Set(fNcells);
9254  if (fgDefaultSumw2) Sumw2();
9255 }
9256 
9257 
9258 ////////////////////////////////////////////////////////////////////////////////
9259 /// Destructor.
9260 
9261 TH1I::~TH1I()
9262 {
9264 
9265 
9266 ////////////////////////////////////////////////////////////////////////////////
9267 /// Copy constructor.
9268 
9269 TH1I::TH1I(const TH1I &h1i) : TH1(), TArrayI()
9270 {
9271  ((TH1I&)h1i).Copy(*this);
9272 }
9273 
9274 
9275 ////////////////////////////////////////////////////////////////////////////////
9276 /// Increment bin content by 1.
9277 
9278 void TH1I::AddBinContent(Int_t bin)
9279 {
9280  if (fArray[bin] < 2147483647) fArray[bin]++;
9281 }
9282 
9283 
9284 ////////////////////////////////////////////////////////////////////////////////
9285 /// Increment bin content by w
9286 
9287 void TH1I::AddBinContent(Int_t bin, Double_t w)
9288 {
9289  Int_t newval = fArray[bin] + Int_t(w);
9290  if (newval > -2147483647 && newval < 2147483647) {fArray[bin] = Int_t(newval); return;}
9291  if (newval < -2147483647) fArray[bin] = -2147483647;
9292  if (newval > 2147483647) fArray[bin] = 2147483647;
9293 }
9294 
9295 
9296 ////////////////////////////////////////////////////////////////////////////////
9297 /// Copy this to newth1
9298 
9299 void TH1I::Copy(TObject &newth1) const
9300 {
9301  TH1::Copy(newth1);
9302 }
9303 
9304 
9305 ////////////////////////////////////////////////////////////////////////////////
9306 /// Reset.
9307 
9308 void TH1I::Reset(Option_t *option)
9309 {
9310  TH1::Reset(option);
9311  TArrayI::Reset();
9312 }
9313 
9314 
9315 ////////////////////////////////////////////////////////////////////////////////
9316 /// Set total number of bins including under/overflow
9317 /// Reallocate bin contents array
9318 
9319 void TH1I::SetBinsLength(Int_t n)
9320 {
9321  if (n < 0) n = fXaxis.GetNbins() + 2;
9322  fNcells = n;
9323  TArrayI::Set(n);
9324 }
9325 
9326 
9327 ////////////////////////////////////////////////////////////////////////////////
9328 /// Operator =
9329 
9330 TH1I& TH1I::operator=(const TH1I &h1)
9331 {
9332  if (this != &h1) ((TH1I&)h1).Copy(*this);
9333  return *this;
9334 }
9335 
9336 
9337 
9338 ////////////////////////////////////////////////////////////////////////////////
9339 /// Operator *
9340 
9341 TH1I operator*(Double_t c1, const TH1I &h1)
9342 {
9343  TH1I hnew = h1;
9344  hnew.Scale(c1);
9345  hnew.SetDirectory(0);
9346  return hnew;
9347 }
9348 
9349 
9350 ////////////////////////////////////////////////////////////////////////////////
9351 /// Operator +
9352 
9353 TH1I operator+(const TH1I &h1, const TH1I &h2)
9354 {
9355  TH1I hnew = h1;
9356  hnew.Add(&h2,1);
9357  hnew.SetDirectory(0);
9358  return hnew;
9359 }
9360 
9361 
9362 ////////////////////////////////////////////////////////////////////////////////
9363 /// Operator -
9364 
9365 TH1I operator-(const TH1I &h1, const TH1I &h2)
9366 {
9367  TH1I hnew = h1;
9368  hnew.Add(&h2,-1);
9369  hnew.SetDirectory(0);
9370  return hnew;
9371 }
9372 
9373 
9374 ////////////////////////////////////////////////////////////////////////////////
9375 /// Operator *
9376 
9377 TH1I operator*(const TH1I &h1, const TH1I &h2)
9378 {
9379  TH1I hnew = h1;
9380  hnew.Multiply(&h2);
9381  hnew.SetDirectory(0);
9382  return hnew;
9383 }
9384 
9385 
9386 ////////////////////////////////////////////////////////////////////////////////
9387 /// Operator /
9388 
9389 TH1I operator/(const TH1I &h1, const TH1I &h2)
9390 {
9391  TH1I hnew = h1;
9392  hnew.Divide(&h2);
9393  hnew.SetDirectory(0);
9394  return hnew;
9395 }
9396 
9397 
9398 //______________________________________________________________________________
9399 // TH1F methods
9400 // TH1F : histograms with one float per channel. Maximum precision 7 digits
9401 //______________________________________________________________________________
9402 
9403 ClassImp(TH1F)
9404 
9405 
9406 ////////////////////////////////////////////////////////////////////////////////
9407 /// Constructor.
9408 
9409 TH1F::TH1F(): TH1(), TArrayF()
9410 {
9412  SetBinsLength(3);
9413  if (fgDefaultSumw2) Sumw2();
9414 }
9415 
9416 
9417 ////////////////////////////////////////////////////////////////////////////////
9418 /// Create a 1-Dim histogram with fix bins of type float
9419 /// (see TH1::TH1 for explanation of parameters)
9420 
9421 TH1F::TH1F(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9422 : TH1(name,title,nbins,xlow,xup)
9424  fDimension = 1;
9425  TArrayF::Set(fNcells);
9426 
9427  if (xlow >= xup) SetBuffer(fgBufferSize);
9428  if (fgDefaultSumw2) Sumw2();
9429 }
9430 
9431 
9432 ////////////////////////////////////////////////////////////////////////////////
9433 /// Create a 1-Dim histogram with variable bins of type float
9434 /// (see TH1::TH1 for explanation of parameters)
9435 
9436 TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9437 : TH1(name,title,nbins,xbins)
9439  fDimension = 1;
9440  TArrayF::Set(fNcells);
9441  if (fgDefaultSumw2) Sumw2();
9442 }
9443 
9444 
9445 ////////////////////////////////////////////////////////////////////////////////
9446 /// Create a 1-Dim histogram with variable bins of type float
9447 /// (see TH1::TH1 for explanation of parameters)
9448 
9449 TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9450 : TH1(name,title,nbins,xbins)
9452  fDimension = 1;
9453  TArrayF::Set(fNcells);
9454  if (fgDefaultSumw2) Sumw2();
9455 }
9456 
9457 
9458 ////////////////////////////////////////////////////////////////////////////////
9459 /// Create a histogram from a TVectorF
9460 /// by default the histogram name is "TVectorF" and title = ""
9461 
9462 TH1F::TH1F(const TVectorF &v)
9463 : TH1("TVectorF","",v.GetNrows(),0,v.GetNrows())
9465  TArrayF::Set(fNcells);
9466  fDimension = 1;
9467  Int_t ivlow = v.GetLwb();
9468  for (Int_t i=0;i<fNcells-2;i++) {
9469  SetBinContent(i+1,v(i+ivlow));
9470  }
9471  TArrayF::Set(fNcells);
9472  if (fgDefaultSumw2) Sumw2();
9473 }
9474 
9475 
9476 ////////////////////////////////////////////////////////////////////////////////
9477 /// Copy Constructor.
9478 
9479 TH1F::TH1F(const TH1F &h) : TH1(), TArrayF()
9480 {
9481  ((TH1F&)h).Copy(*this);
9482 }
9483 
9484 
9485 ////////////////////////////////////////////////////////////////////////////////
9486 /// Destructor.
9487 
9488 TH1F::~TH1F()
9489 {
9491 
9492 
9493 ////////////////////////////////////////////////////////////////////////////////
9494 /// Copy this to newth1.
9495 
9496 void TH1F::Copy(TObject &newth1) const
9497 {
9498  TH1::Copy(newth1);
9499 }
9500 
9501 
9502 ////////////////////////////////////////////////////////////////////////////////
9503 /// Reset.
9504 
9505 void TH1F::Reset(Option_t *option)
9506 {
9507  TH1::Reset(option);
9508  TArrayF::Reset();
9509 }
9510 
9511 
9512 ////////////////////////////////////////////////////////////////////////////////
9513 /// Set total number of bins including under/overflow
9514 /// Reallocate bin contents array
9515 
9516 void TH1F::SetBinsLength(Int_t n)
9517 {
9518  if (n < 0) n = fXaxis.GetNbins() + 2;
9519  fNcells = n;
9520  TArrayF::Set(n);
9521 }
9522 
9523 
9524 ////////////////////////////////////////////////////////////////////////////////
9525 /// Operator =
9526 
9527 TH1F& TH1F::operator=(const TH1F &h1)
9528 {
9529  if (this != &h1) ((TH1F&)h1).Copy(*this);
9530  return *this;
9531 }
9532 
9533 
9534 ////////////////////////////////////////////////////////////////////////////////
9535 /// Operator *
9536 
9537 TH1F operator*(Double_t c1, const TH1F &h1)
9538 {
9539  TH1F hnew = h1;
9540  hnew.Scale(c1);
9541  hnew.SetDirectory(0);
9542  return hnew;
9543 }
9544 
9545 
9546 ////////////////////////////////////////////////////////////////////////////////
9547 /// Operator +
9548 
9549 TH1F operator+(const TH1F &h1, const TH1F &h2)
9550 {
9551  TH1F hnew = h1;
9552  hnew.Add(&h2,1);
9553  hnew.SetDirectory(0);
9554  return hnew;
9555 }
9556 
9557 
9558 ////////////////////////////////////////////////////////////////////////////////
9559 /// Operator -
9560 
9561 TH1F operator-(const TH1F &h1, const TH1F &h2)
9562 {
9563  TH1F hnew = h1;
9564  hnew.Add(&h2,-1);
9565  hnew.SetDirectory(0);
9566  return hnew;
9567 }
9568 
9569 
9570 ////////////////////////////////////////////////////////////////////////////////
9571 /// Operator *
9572 
9573 TH1F operator*(const TH1F &h1, const TH1F &h2)
9574 {
9575  TH1F hnew = h1;
9576  hnew.Multiply(&h2);
9577  hnew.SetDirectory(0);
9578  return hnew;
9579 }
9580 
9581 
9582 ////////////////////////////////////////////////////////////////////////////////
9583 /// Operator /
9584 
9585 TH1F operator/(const TH1F &h1, const TH1F &h2)
9586 {
9587  TH1F hnew = h1;
9588  hnew.Divide(&h2);
9589  hnew.SetDirectory(0);
9590  return hnew;
9591 }
9592 
9593 
9594 
9595 //______________________________________________________________________________
9596 // TH1D methods
9597 // TH1D : histograms with one double per channel. Maximum precision 14 digits
9598 //______________________________________________________________________________
9599 
9600 ClassImp(TH1D)
9601 
9602 
9603 ////////////////////////////////////////////////////////////////////////////////
9604 /// Constructor.
9605 
9606 TH1D::TH1D(): TH1(), TArrayD()
9607 {
9609  SetBinsLength(3);
9610  if (fgDefaultSumw2) Sumw2();
9611 }
9612 
9613 
9614 ////////////////////////////////////////////////////////////////////////////////
9615 /// Create a 1-Dim histogram with fix bins of type double
9616 /// (see TH1::TH1 for explanation of parameters)
9617 
9618 TH1D::TH1D(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9619 : TH1(name,title,nbins,xlow,xup)
9621  fDimension = 1;
9622  TArrayD::Set(fNcells);
9623 
9624  if (xlow >= xup) SetBuffer(fgBufferSize);
9625  if (fgDefaultSumw2) Sumw2();
9626 }
9627 
9628 
9629 ////////////////////////////////////////////////////////////////////////////////
9630 /// Create a 1-Dim histogram with variable bins of type double
9631 /// (see TH1::TH1 for explanation of parameters)
9632 
9633 TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9634 : TH1(name,title,nbins,xbins)
9636  fDimension = 1;
9637  TArrayD::Set(fNcells);
9638  if (fgDefaultSumw2) Sumw2();
9639 }
9640 
9641 
9642 ////////////////////////////////////////////////////////////////////////////////
9643 /// Create a 1-Dim histogram with variable bins of type double
9644 /// (see TH1::TH1 for explanation of parameters)
9645 
9646 TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9647 : TH1(name,title,nbins,xbins)
9649  fDimension = 1;
9650  TArrayD::Set(fNcells);
9651  if (fgDefaultSumw2) Sumw2();
9652 }
9653 
9654 
9655 ////////////////////////////////////////////////////////////////////////////////
9656 /// Create a histogram from a TVectorD
9657 /// by default the histogram name is "TVectorD" and title = ""
9658 
9659 TH1D::TH1D(const TVectorD &v)
9660 : TH1("TVectorD","",v.GetNrows(),0,v.GetNrows())
9662  TArrayD::Set(fNcells);
9663  fDimension = 1;
9664  Int_t ivlow = v.GetLwb();
9665  for (Int_t i=0;i<fNcells-2;i++) {
9666  SetBinContent(i+1,v(i+ivlow));
9667  }
9668  TArrayD::Set(fNcells);
9669  if (fgDefaultSumw2) Sumw2();
9670 }
9671 
9672 
9673 ////////////////////////////////////////////////////////////////////////////////
9674 /// Destructor.
9675 
9676 TH1D::~TH1D()
9677 {
9679 
9680 
9681 ////////////////////////////////////////////////////////////////////////////////
9682 /// Constructor.
9683 
9684 TH1D::TH1D(const TH1D &h1d) : TH1(), TArrayD()
9685 {
9686  ((TH1D&)h1d).Copy(*this);
9687 }
9688 
9689 
9690 ////////////////////////////////////////////////////////////////////////////////
9691 /// Copy this to newth1
9692 
9693 void TH1D::Copy(TObject &newth1) const
9694 {
9695  TH1::Copy(newth1);
9696 }
9697 
9698 
9699 ////////////////////////////////////////////////////////////////////////////////
9700 /// Reset.
9701 
9702 void TH1D::Reset(Option_t *option)
9703 {
9704  TH1::Reset(option);
9705  TArrayD::Reset();
9706 }
9707 
9708 
9709 ////////////////////////////////////////////////////////////////////////////////
9710 /// Set total number of bins including under/overflow
9711 /// Reallocate bin contents array
9712 
9713 void TH1D::SetBinsLength(Int_t n)
9714 {
9715  if (n < 0) n = fXaxis.GetNbins() + 2;
9716  fNcells = n;
9717  TArrayD::Set(n);
9718 }
9719 
9720 
9721 ////////////////////////////////////////////////////////////////////////////////
9722 /// Operator =
9723 
9724 TH1D& TH1D::operator=(const TH1D &h1)
9725 {
9726  if (this != &h1) ((TH1D&)h1).Copy(*this);
9727  return *this;
9728 }
9729 
9730 
9731 ////////////////////////////////////////////////////////////////////////////////
9732 /// Operator *
9733 
9734 TH1D operator*(Double_t c1, const TH1D &h1)
9735 {
9736  TH1D hnew = h1;
9737  hnew.Scale(c1);
9738  hnew.SetDirectory(0);
9739  return hnew;
9740 }
9741 
9742 
9743 ////////////////////////////////////////////////////////////////////////////////
9744 /// Operator +
9745 
9746 TH1D operator+(const TH1D &h1, const TH1D &h2)
9747 {
9748  TH1D hnew = h1;
9749  hnew.Add(&h2,1);
9750  hnew.SetDirectory(0);
9751  return hnew;
9752 }
9753 
9754 
9755 ////////////////////////////////////////////////////////////////////////////////
9756 /// Operator -
9757 
9758 TH1D operator-(const TH1D &h1, const TH1D &h2)
9759 {
9760  TH1D hnew = h1;
9761  hnew.Add(&h2,-1);
9762  hnew.SetDirectory(0);
9763  return hnew;
9764 }
9765 
9766 
9767 ////////////////////////////////////////////////////////////////////////////////
9768 /// Operator *
9769 
9770 TH1D operator*(const TH1D &h1, const TH1D &h2)
9771 {
9772  TH1D hnew = h1;
9773  hnew.Multiply(&h2);
9774  hnew.SetDirectory(0);
9775  return hnew;
9776 }
9777 
9778 
9779 ////////////////////////////////////////////////////////////////////////////////
9780 /// Operator /
9781 
9782 TH1D operator/(const TH1D &h1, const TH1D &h2)
9783 {
9784  TH1D hnew = h1;
9785  hnew.Divide(&h2);
9786  hnew.SetDirectory(0);
9787  return hnew;
9788 }
9789 
9790 
9791 ////////////////////////////////////////////////////////////////////////////////
9792 ///return pointer to histogram with name
9793 ///hid if id >=0
9794 ///h_id if id <0
9795 
9796 TH1 *R__H(Int_t hid)
9797 {
9798  TString hname;
9799  if(hid >= 0) hname.Form("h%d",hid);
9800  else hname.Form("h_%d",hid);
9801  return (TH1*)gDirectory->Get(hname);
9802 }
9803 
9804 
9805 ////////////////////////////////////////////////////////////////////////////////
9806 ///return pointer to histogram with name hname
9807 
9808 TH1 *R__H(const char * hname)
9809 {
9810  return (TH1*)gDirectory->Get(hname);
9811 }
static void StatOverflows(Bool_t flag=kTRUE)
if flag=kTRUE, underflows and overflows are used by the Fill functions in the computation of statisti...
Definition: TH1.cxx:6493
const int nx
Definition: kalman.C:16
const int ndata
TString fTitle
Definition: TNamed.h:37
Abstract array base class.
Definition: TArray.h:33
virtual void Browse(TBrowser *b)
Browe the Histogram object.
Definition: TH1.cxx:723
for(Int_t i=0;i< n;i++)
Definition: legend1.C:18
virtual void SavePrimitive(std::ostream &out, Option_t *option="")
Save primitive as a C++ statement(s) on output stream out.
Definition: TH1.cxx:6729
virtual void SetTitleOffset(Float_t offset=1)
Set distance between the axis and the axis title Offset is a correction factor with respect to the "s...
Definition: TAttAxis.cxx:244
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:51
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9715
virtual void Print(Option_t *option="") const
Print some global quantities for this histogram.
Definition: TH1.cxx:6579
virtual void SetNameTitle(const char *name, const char *title)
Change the name and title of this histogram.
Definition: TH1.cxx:8309
virtual void SetLineWidth(Width_t lwidth)
Definition: TAttLine.h:57
virtual UInt_t GetUniqueID() const
Return the unique object id.
Definition: TObject.cxx:433
Bool_t IsReading() const
Definition: TBuffer.h:81
virtual Int_t FindBin(Double_t x, Double_t y=0, Double_t z=0)
Return Global bin number corresponding to x,y,z.
Definition: TH1.cxx:3484
virtual Float_t GetTickLength() const
Definition: TAttAxis.h:58
Double_t fNormFactor
Definition: TH1.h:114
virtual void SetBarOffset(Float_t offset=0.25)
Definition: TH1.h:356
virtual void Scale(Double_t c1=1, Option_t *option="")
Multiply this histogram by a constant c1.
Definition: TH1.cxx:6180
virtual Int_t Fill(Double_t x)
Increment bin with abscissa X by 1.
Definition: TH1.cxx:3165
virtual Int_t ShowPeaks(Double_t sigma=2, Option_t *option="", Double_t threshold=0.05)
Interface to TSpectrum::Search.
Definition: TH1.cxx:8634
virtual Double_t GetMaximum(Double_t maxval=FLT_MAX) const
Return maximum value smaller than maxval of bins in the range, unless the value has been overridden b...
Definition: TH1.cxx:7927
TH1D & operator=(const TH1D &h1)
Operator =.
Definition: TH1.cxx:9726
virtual Double_t IntegralAndError(Int_t binx1, Int_t binx2, Double_t &err, Option_t *option="") const
Return integral of bin contents in range [binx1,binx2] and its error By default the integral is compu...
Definition: TH1.cxx:7411
void SetBarWidth(Float_t barwidth=0.5)
Definition: TStyle.h:332
virtual void SaveAttributes(std::ostream &out, const char *name, const char *subname)
Save axis attributes as C++ statement(s) on output stream out.
Definition: TAxis.cxx:631
virtual Double_t GetEffectiveEntries() const
number of effective entries of the histogram, neff = (Sum of weights )^2 / (Sum of weight^2 ) In case...
Definition: TH1.cxx:4079
virtual void Paint(Option_t *option="")
Control routine to paint any kind of histograms.
Definition: TH1.cxx:5804
action
Definition: ROOT.py:93
float xmin
Definition: THbookFile.cxx:93
virtual Int_t WriteClassBuffer(const TClass *cl, void *pointer)=0
virtual void Delete(Option_t *option="")
Remove all objects from the list AND delete all heap based objects.
Definition: TList.cxx:404
virtual Double_t GetBinCenter(Int_t bin) const
return bin center for 1D historam Better to use h1.GetXaxis().GetBinCenter(bin)
Definition: TH1.cxx:8476
const char * GetBinLabel(Int_t bin) const
Return label for bin.
Definition: TAxis.cxx:411
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition: TObject.cxx:892
virtual Double_t PoissonD(Double_t mean)
Generates a random number according to a Poisson law.
Definition: TRandom.cxx:414
Double_t Floor(Double_t x)
Definition: TMath.h:473
void Set(Int_t n)
Set size of this array to n chars.
Definition: TArrayC.cxx:104
virtual ~TH1I()
Destructor.
Definition: TH1.cxx:9263
Int_t GetFirst() const
Return first bin on the axis i.e.
Definition: TAxis.cxx:429
THist< 2, double > TH2D
Definition: THist.h:320
long long Long64_t
Definition: RtypesCore.h:69
static float fu(float x)
Definition: main.cpp:53
virtual void SetMaximum(Double_t maximum=-1111)
Definition: TH1.h:394
void UseCurrentStyle()
Copy current attributes from/to current style.
Definition: TH1.cxx:6956
virtual void LabelsOption(Option_t *option="h", Option_t *axis="X")
Set option(s) to draw axis with labels.
Definition: TH1.cxx:4907
short Style_t
Definition: RtypesCore.h:76
virtual void SetLimits(Double_t xmin, Double_t xmax)
Definition: TAxis.h:154
Double_t Log(Double_t x)
Definition: TMath.h:526
Short_t fBarWidth
Definition: TH1.h:106
short Version_t
Definition: RtypesCore.h:61
TH1C()
Constructor.
Definition: TH1.cxx:8811
static Bool_t fgDefaultSumw2
flag to use under/overflows in statistics
Definition: TH1.h:129
virtual Int_t DistancetoPrimitive(Int_t px, Int_t py)=0
Computes distance from point (px,py) to the object.
TVirtualHistPainter * GetPainter(Option_t *option="")
return pointer to painter if painter does not exist, it is created
Definition: TH1.cxx:4102
virtual void FitPanel()
Display a panel with all histogram fit options.
Definition: TH1.cxx:3918
float Float_t
Definition: RtypesCore.h:53
virtual Double_t Rndm(Int_t i=0)
Machine independent random number generator.
Definition: TRandom.cxx:512
virtual void SetDirectory(TDirectory *dir)
By default when an histogram is created, it is added to the list of histogram objects in the current ...
Definition: TH1.cxx:8272
virtual TF1 * GetFunction(const char *name) const
Return pointer to function with name.
Definition: TH1.cxx:8388
virtual Float_t GetLabelOffset() const
Definition: TAttAxis.h:54
Short_t * fArray
Definition: TArrayS.h:32
const char Option_t
Definition: RtypesCore.h:62
virtual Float_t GetBarOffset() const
Definition: TH1.h:256
virtual Double_t GetBinLowEdge(Int_t bin) const
Return low edge of bin.
Definition: TAxis.cxx:489
Double_t KolmogorovProb(Double_t z)
Calculates the Kolmogorov distribution function, which gives the probability that Kolmogorov&#39;s test ...
Definition: TMath.cxx:661
return c1
Definition: legend1.C:41
void Reset()
Definition: TArrayD.h:49
float ymin
Definition: THbookFile.cxx:93
virtual void Set(Int_t n)=0
virtual void ResetAttAxis(Option_t *option="")
Reset axis attributes.
Definition: TAttAxis.cxx:61
Double_t QuietNaN()
Definition: TMath.h:635
virtual void SetError(const Double_t *error)
Replace bin errors by values in array error.
Definition: TH1.cxx:8284
virtual Double_t GetNormFactor() const
Definition: TH1.h:300
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition: TString.h:635
#define assert(cond)
Definition: unittest.h:542
TAxis fYaxis
Definition: TH1.h:103
virtual Int_t BufferFill(Double_t x, Double_t w)
accumulate arguments in buffer.
Definition: TH1.cxx:1339
virtual void SetContour(Int_t nlevels, const Double_t *levels=0)
Set the number and values of contour levels.
Definition: TH1.cxx:7869
R__EXTERN TStyle * gStyle
Definition: TStyle.h:423
virtual void PutStats(Double_t *stats)
Replace current statistics with the values in array stats.
Definition: TH1.cxx:7329
void SetHistLineWidth(Width_t width=1)
Definition: TStyle.h:378
const Double_t * GetArray() const
Definition: TArrayD.h:45
TList * fFunctions
Definition: TH1.h:118
virtual Int_t FindLastBinAbove(Double_t threshold=0, Int_t axis=1) const
Find last bin with content > threshold for axis (1=x, 2=y, 3=z) if no bins with content > threshold i...
Definition: TH1.cxx:3565
#define gDirectory
Definition: TDirectory.h:218
Bool_t TestBit(UInt_t f) const
Definition: TObject.h:173
virtual void SetBins(Int_t nx, Double_t xmin, Double_t xmax)
Redefine x axis parameters.
Definition: TH1.cxx:8096
Int_t GetLwb() const
Definition: TVectorT.h:79
virtual Int_t GetXfirst() const
virtual void SetName(const char *name)
Change (i.e.
Definition: TNamed.cxx:128
virtual Color_t GetAxisColor() const
Definition: TAttAxis.h:51
TH1 * h
Definition: legend2.C:5
TH1 * GetAsymmetry(TH1 *h2, Double_t c2=1, Double_t dc2=0)
Return an histogram containing the asymmetry of this histogram with h2, where the asymmetry is define...
Definition: TH1.cxx:3970
static Bool_t fgStatOverflows
flag to add histograms to the directory
Definition: TH1.h:128
virtual TH1 * DrawNormalized(Option_t *option="", Double_t norm=1) const
Draw a normalized copy of this histogram.
Definition: TH1.cxx:2960
static Bool_t SameLimitsAndNBins(const TAxis &axis1, const TAxis &axis2)
Same limits and bins.
Definition: TH1.cxx:5190
virtual ~TH1F()
Destructor.
Definition: TH1.cxx:9490
virtual void SetLabelColor(Color_t color=1, Float_t alpha=1.)
Set color of labels.
Definition: TAttAxis.cxx:155
void Build()
Creates histogram basic data structure.
Definition: TH1.cxx:733
virtual Double_t GetSumOfWeights() const
Return the sum of weights excluding under/overflows.
Definition: TH1.cxx:7360
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
Definition: TH1.cxx:4635
virtual void SetNdivisions(Int_t n=510, Bool_t optim=kTRUE)
Set the number of divisions for this axis.
Definition: TAttAxis.cxx:211
virtual Int_t GetEntries() const
Definition: TCollection.h:92
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:8901
virtual Int_t GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum=0)
Compute Quantiles for this histogram Quantile x_q of a probability distribution Function F is defined...
Definition: TH1.cxx:4188
virtual Double_t Integral(Option_t *option="") const
Return integral of bin contents.
Definition: TH1.cxx:7384
virtual void AddFirst(TObject *obj)
Add object at the beginning of the list.
Definition: TList.cxx:92
void ToUpper()
Change string to upper case.
Definition: TString.cxx:1101
virtual void Reset(Option_t *option="")
Reset.
Definition: TH1.cxx:8910
TH1D()
Constructor.
Definition: TH1.cxx:9608
friend TH1D operator/(const TH1D &h1, const TH1D &h2)
Operator /.
Definition: TH1.cxx:9784
static bool CheckAxisLimits(const TAxis *a1, const TAxis *a2)
Check that the axis limits of the histograms are the same if a first and last bin is passed the axis ...
Definition: TH1.cxx:1434
virtual void AddAll(const TCollection *col)
Add all objects from collection col to this collection.
Definition: TCollection.cxx:57
Buffer base class used for serializing objects.
Definition: TBuffer.h:40
friend TH1S operator+(const TH1S &h1, const TH1S &h2)
Operator +.
Definition: TH1.cxx:9155
virtual Double_t GetMeanError(Int_t axis=1) const
Return standard error of mean of this histogram along the X axis.
Definition: TH1.cxx:7051
virtual Int_t GetNbinsZ() const
Definition: TH1.h:298
TH1F()
Constructor.
Definition: TH1.cxx:9411
#define R__ASSERT(e)
Definition: TError.h:98
virtual void SetMinimum(Double_t minimum=-1111)
Definition: TH1.h:395
static THLimitsFinder * GetLimitsFinder()
Return pointer to the current finder.
virtual Int_t CheckByteCount(UInt_t startpos, UInt_t bcnt, const TClass *clss)=0
#define gROOT
Definition: TROOT.h:352
virtual Double_t GetMean(Int_t axis=1) const
For axis = 1,2 or 3 returns the mean value of the histogram along X,Y or Z axis.
Definition: TH1.cxx:7020
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition: TString.h:582
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9695
Int_t LoadPlugin()
Load the plugin library for this handler.
virtual void GetBinXYZ(Int_t binglobal, Int_t &binx, Int_t &biny, Int_t &binz) const
return binx, biny, binz corresponding to the global bin number globalbin see TH1::GetBin function abo...
Definition: TH1.cxx:4555
double gamma_quantile_c(double z, double alpha, double theta)
Inverse ( ) of the cumulative distribution function of the upper tail of the gamma distribution (gamm...
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9498
Basic string class.
Definition: TString.h:137
static Bool_t AddDirectoryStatus()
static function: cannot be inlined on Windows/NT
Definition: TH1.cxx:714
1-D histogram with a float per channel (see TH1 documentation)}
Definition: TH1.h:570
Int_t GetNrows() const
Definition: TVectorT.h:81
1-D histogram with a short per channel (see TH1 documentation)
Definition: TH1.h:488
void H1InitExpo()
Compute Initial values of parameters for an exponential.
Definition: TH1.cxx:4297
Array of floats (32 bits per element).
Definition: TArrayF.h:29
virtual void SetTitleFont(Style_t font=62)
Set the title font.
Definition: TAttAxis.cxx:272
Short_t Min(Short_t a, Short_t b)
Definition: TMathBase.h:170
void ToLower()
Change string to lower-case.
Definition: TString.cxx:1088
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
void SetBarOffset(Float_t baroff=0.5)
Definition: TStyle.h:331
TArc * a
Definition: textangle.C:12
R__EXTERN TVirtualMutex * gROOTMutex
Definition: TROOT.h:63
const Bool_t kFALSE
Definition: Rtypes.h:92
void Copy(TAttMarker &attmarker) const
Copy this marker attributes to a new TAttMarker.
Definition: TAttMarker.cxx:191
virtual TH1 * DrawCopy(Option_t *option="", const char *name_postfix="_copy") const
Copy this histogram and Draw in the current pad.
Definition: TH1.cxx:2931
virtual void SetFillStyle(Style_t fstyle)
Definition: TAttFill.h:52
virtual void Smooth(Int_t ntimes=1, Option_t *option="")
Smooth bin contents of this histogram.
Definition: TH1.cxx:6446
#define gInterpreter
Definition: TInterpreter.h:502
int nbins[3]
TArrayD fSumw2
Definition: TH1.h:116
virtual void UseCurrentStyle()
Set current style settings in this object This function is called when either TCanvas::UseCurrentStyl...
Definition: TObject.cxx:753
virtual void Copy(TObject &axis) const
Copy axis structure to another axis.
Definition: TAxis.cxx:198
virtual Float_t GetLabelSize() const
Definition: TAttAxis.h:55
virtual Double_t GetBinLowEdge(Int_t bin) const
return bin lower edge for 1D historam Better to use h1.GetXaxis().GetBinLowEdge(bin) ...
Definition: TH1.cxx:8487
static Bool_t AlmostInteger(Double_t a, Double_t epsilon=0.00000001)
Definition: TH1.cxx:5163
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9301
void Reset()
Definition: TArrayF.h:49
virtual Double_t Integral(Double_t a, Double_t b, Double_t epsrel=1.e-12)
IntegralOneDim or analytical integral.
Definition: TF1.cxx:2264
virtual Int_t FindGoodLimits(TH1 *h, Double_t xmin, Double_t xmax)
compute the best axis limits for the X axis.
static Bool_t RecomputeAxisLimits(TAxis &destAxis, const TAxis &anAxis)
Finds new limits for the axis for the Merge function.
Definition: TH1.cxx:5201
TAxis fZaxis
Definition: TH1.h:104
virtual Bool_t Multiply(TF1 *h1, Double_t c1=1)
Performs the operation: this = this*c1*f1 if errors are defined (see TH1::Sumw2), errors are also rec...
Definition: TH1.cxx:5626
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9518
virtual TObject * Clone(const char *newname="") const
Make a clone of an collection using the Streamer facility.
Bool_t CanExtend() const
Definition: TAxis.h:90
virtual Double_t GetContourLevel(Int_t level) const
Return value of contour number level use GetContour to return the array of all contour levels...
Definition: TH1.cxx:7813
virtual void SetLabelOffset(Float_t offset=0.005)
Set distance between the axis and the labels The distance is expressed in per cent of the pad width...
Definition: TAttAxis.cxx:175
Short_t Abs(Short_t d)
Definition: TMathBase.h:110
THist< 1, double > TH1D
Definition: THist.h:314
virtual Width_t GetLineWidth() const
Definition: TAttLine.h:49
friend TH1D operator+(const TH1D &h1, const TH1D &h2)
Operator +.
Definition: TH1.cxx:9748
Double_t Prob(Double_t chi2, Int_t ndf)
Computation of the probability for a certain Chi-squared (chi2) and number of degrees of freedom (ndf...
Definition: TMath.cxx:622
static bool CheckBinLimits(const TAxis *a1, const TAxis *a2)
Definition: TH1.cxx:1374
Array of integers (32 bits per element).
Definition: TArrayI.h:29
void Reset(Char_t val=0)
Definition: TArrayC.h:49
LongDouble_t Power(LongDouble_t x, LongDouble_t y)
Definition: TMath.h:501
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition: TObject.cxx:732
virtual void SetBuffer(Int_t buffersize, Option_t *option="")
set the maximum number of entries to be kept in the buffer
Definition: TH1.cxx:7843
Double_t fTsumwx2
Definition: TH1.h:111
virtual void GetStats(Double_t *stats) const
fill the array stats from the contents of this histogram The array stats must be correctly dimensione...
Definition: TH1.cxx:7276
virtual Bool_t CanExtendAllAxes() const
returns true if all axes are extendable
Definition: TH1.cxx:6203
virtual void Reset(Option_t *option="")
Reset this histogram: contents, errors, etc.
Definition: TH1.cxx:6675
friend TH1S operator-(const TH1S &h1, const TH1S &h2)
Operator -.
Definition: TH1.cxx:9167
virtual TObject * FindObject(const char *name) const
Find an object in this list using its name.
Definition: TList.cxx:496
Width_t GetHistLineWidth() const
Definition: TStyle.h:245
static void AddDirectory(Bool_t add=kTRUE)
Sets the flag controlling the automatic add of histograms in memory.
Definition: TH1.cxx:1236
virtual Double_t GetBinUpEdge(Int_t bin) const
Return up edge of bin.
Definition: TAxis.cxx:499
virtual void SetBarWidth(Float_t width=0.5)
Definition: TH1.h:357
virtual void SetLabelFont(Style_t font=62)
Set labels&#39; font.
Definition: TAttAxis.cxx:165
virtual void AppendPad(Option_t *option="")
Append graphics object to current pad.
Definition: TObject.cxx:164
static TVirtualHistPainter * HistPainter(TH1 *obj)
Static function returning a pointer to the current histogram painter.
virtual void SetPoint(Int_t ipoint, Double_t re, Double_t im=0)=0
virtual Style_t GetMarkerStyle() const
Definition: TAttMarker.h:45
TDirectory * fDirectory
Definition: TH1.h:121
static void SetDefaultSumw2(Bool_t sumw2=kTRUE)
static function.
Definition: TH1.cxx:6259
Marker Attributes class.
Definition: TAttMarker.h:32
virtual Style_t GetTitleFont() const
Definition: TAttAxis.h:60
static bool CheckConsistentSubAxes(const TAxis *a1, Int_t firstBin1, Int_t lastBin1, const TAxis *a2, Int_t firstBin2=0, Int_t lastBin2=0)
Check that two sub axis are the same the limits are defined by first bin and last bin N...
Definition: TH1.cxx:1485
virtual Style_t GetLineStyle() const
Definition: TAttLine.h:48
virtual Int_t GetDimension() const
Definition: TH1.h:283
virtual Double_t Interpolate(Double_t x)
Given a point x, approximates the value via linear interpolation based on the two nearest bin centers...
Definition: TH1.cxx:4688
virtual Int_t GetContour(Double_t *levels=0)
Return contour values into array levels if pointer levels is non zero.
Definition: TH1.cxx:7793
TH1C & operator=(const TH1C &h1)
Operator =.
Definition: TH1.cxx:8932
Double_t GetXmin() const
Definition: TAxis.h:137
virtual void Paint(Option_t *option="")=0
This method must be overridden if a class wants to paint itself.
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition: TObject.cxx:187
Fill Area Attributes class.
Definition: TAttFill.h:32
Double_t x[n]
Definition: legend1.C:17
static Int_t FitOptionsMake(Option_t *option, Foption_t &Foption)
flag to call TH1::Sumw2 automatically at histogram creation time
Definition: TH1.cxx:4230
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString...
Definition: TString.cxx:2334
virtual void Eval(TF1 *f1, Option_t *option="")
Evaluate function f1 at the center of bins of this histogram.
Definition: TH1.cxx:3010
void Class()
Definition: Class.C:29
THashList implements a hybrid collection class consisting of a hash table and a list to store TObject...
Definition: THashList.h:36
static Bool_t GetDefaultSumw2()
return kTRUE if TH1::Sumw2 must be called when creating new histograms.
Definition: TH1.cxx:4048
void SetHistFillColor(Color_t color=1)
Definition: TStyle.h:374
virtual Bool_t GetTimeDisplay() const
Definition: TAxis.h:130
static void SetDefaultBufferSize(Int_t buffersize=1000)
static function to set the default buffer size for automatic histograms.
Definition: TH1.cxx:6247
void Copy(TAttLine &attline) const
Copy this line attributes to a new TAttLine.
Definition: TAttLine.cxx:159
virtual void SaveLineAttributes(std::ostream &out, const char *name, Int_t coldef=1, Int_t stydef=1, Int_t widdef=1)
Save line attributes as C++ statement(s) on output stream out.
Definition: TAttLine.cxx:257
virtual Double_t Chi2Test(const TH1 *h2, Option_t *option="UU", Double_t *res=0) const
chi^{2} test for comparing weighted and unweighted histograms
Definition: TH1.cxx:1856
The TNamed class is the base class for all named ROOT classes.
Definition: TNamed.h:33
virtual ~TH1()
Histogram default destructor.
Definition: TH1.cxx:589
const int ny
Definition: kalman.C:17
THashList * GetLabels() const
Definition: TAxis.h:122
friend TH1D operator-(const TH1D &h1, const TH1D &h2)
Operator -.
Definition: TH1.cxx:9760
Int_t GetOptFit() const
Definition: TStyle.h:252
Double_t Log10(Double_t x)
Definition: TMath.h:529
virtual void SetContourLevel(Int_t level, Double_t value)
Set value for one contour level.
Definition: TH1.cxx:7909
virtual void GetCenter(Double_t *center) const
Return an array with the center of all bins.
Definition: TAxis.cxx:524
TH1I()
Constructor.
Definition: TH1.cxx:9211
Abstract interface to a histogram painter.
virtual Double_t GetBinCenter(Int_t bin) const
Return center of bin.
Definition: TAxis.cxx:449
virtual void SetMarkerColor(Color_t mcolor=1)
Definition: TAttMarker.h:51
Style_t GetHistFillStyle() const
Definition: TStyle.h:243
TH1S()
Constructor.
Definition: TH1.cxx:9012
TString & Append(const char *cs)
Definition: TString.h:492
virtual void GetLowEdge(Double_t *edge) const
Return an array with the lod edge of all bins.
Definition: TAxis.cxx:533
void Sort(Index n, const Element *a, Index *index, Bool_t down=kTRUE)
Definition: TMath.h:1002
Double_t * fArray
Definition: TArrayD.h:32
void H1InitGaus()
Compute Initial values of parameters for a gaussian.
Definition: TH1.cxx:4240
virtual Size_t GetMarkerSize() const
Definition: TAttMarker.h:46
virtual void DrawPanel()=0
TString fOption
Definition: TH1.h:117
friend TH1I operator-(const TH1I &h1, const TH1I &h2)
Operator -.
Definition: TH1.cxx:9367
virtual void SaveMarkerAttributes(std::ostream &out, const char *name, Int_t coldef=1, Int_t stydef=1, Int_t sizdef=1)
Save line attributes as C++ statement(s) on output stream out.
Definition: TAttMarker.cxx:226
virtual Int_t * GetN() const =0
Float_t GetBarWidth() const
Definition: TStyle.h:193
virtual Bool_t FindNewAxisLimits(const TAxis *axis, const Double_t point, Double_t &newMin, Double_t &newMax)
finds new limits for the axis so that point is within the range and the limits are compatible with th...
Definition: TH1.cxx:6043
TH1F * h1
Definition: legend1.C:5
virtual void SetContent(const Double_t *content)
Replace bin contents by the contents of array content.
Definition: TH1.cxx:7778
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:1209
friend TH1C operator*(Double_t c1, const TH1C &h1)
Operator *.
Definition: TH1.cxx:8943
virtual void ResetStats()
Reset the statistics including the number of entries and replace with values calculates from bin cont...
Definition: TH1.cxx:7344
void Set(Int_t n)
Set size of this array to n ints.
Definition: TArrayI.cxx:104
TArrayD fContour
Definition: TH1.h:115
virtual void SetBinError(Int_t bin, Double_t error)
see convention for numbering bins in TH1::GetBin
Definition: TH1.cxx:8534
Int_t AxisChoice(Option_t *axis) const
Choose an axis according to "axis".
Definition: Haxis.cxx:14
virtual Double_t ComputeIntegral(Bool_t onlyPositive=false)
Compute integral (cumulative sum of bins) The result stored in fIntegral is used by the GetRandom fun...
Definition: TH1.cxx:2379
virtual void LabelsInflate(Option_t *axis="X")
Double the number of bins for axis.
Definition: TH1.cxx:4849
virtual Color_t GetLabelColor() const
Definition: TAttAxis.h:52
short Color_t
Definition: RtypesCore.h:79
virtual Double_t GetSkewness(Int_t axis=1) const
For axis = 1, 2 or 3 returns skewness of the histogram along x, y or z axis.
Definition: TH1.cxx:7124
virtual void SetTimeDisplay(Int_t value)
Definition: TAxis.h:161
Double_t fTsumwx
Definition: TH1.h:110
void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a)
Least squares lpolynomial fitting without weights.
Definition: TH1.cxx:4349
virtual Bool_t Divide(TF1 *f1, Double_t c1=1)
Performs the operation: this = this/(c1*f1) if errors are defined (see TH1::Sumw2), errors are also recalculated.
Definition: TH1.cxx:2636
virtual Int_t GetNdivisions() const
Definition: TAttAxis.h:50
Bool_t IsBinUnderflow(Int_t bin) const
Definition: TH1.cxx:4760
static Bool_t fgAddDirectory
default buffer size for automatic histograms
Definition: TH1.h:127
virtual void SetUniqueID(UInt_t uid)
Set the unique object id.
Definition: TObject.cxx:743
A doubly linked list.
Definition: TList.h:47
void Set(Int_t n)
Set size of this array to n shorts.
Definition: TArrayS.cxx:104
virtual Double_t GetStdDevError(Int_t axis=1) const
Return error of standard deviation estimation for Normal distribution.
Definition: TH1.cxx:7111
Double_t fMinimum
Definition: TH1.h:113
virtual Double_t KolmogorovTest(const TH1 *h2, Option_t *option="") const
Statistical test of compatibility in shape between this histogram and h2, using Kolmogorov test...
Definition: TH1.cxx:7616
virtual void ExtendAxis(Double_t x, TAxis *axis)
Histogram is resized along axis such that x is in the axis range.
Definition: TH1.cxx:6097
Bool_t AreEqualRel(Double_t af, Double_t bf, Double_t relPrec)
Definition: TMath.h:196
TH1 * GetCumulative(Bool_t forward=kTRUE, const char *suffix="_cumulative") const
Return a pointer to an histogram containing the cumulative The cumulative can be computed both in the...
Definition: TH1.cxx:2451
virtual TH1 * FFT(TH1 *h_output, Option_t *option)
This function allows to do discrete Fourier transforms of TH1 and TH2.
Definition: TH1.cxx:3104
virtual Int_t DistancetoPrimitive(Int_t px, Int_t py)
Compute distance from point px,py to a line.
Definition: TH1.cxx:2618
std::string printValue(const TDatime &val)
Print a TDatime at the prompt.
Definition: TDatime.cxx:447
void Reset()
Definition: TArrayS.h:49
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:9081
virtual void SetLineColor(Color_t lcolor)
Definition: TAttLine.h:54
friend TH1S operator/(const TH1S &h1, const TH1S &h2)
Operator /.
Definition: TH1.cxx:9191
Using a TBrowser one can browse all ROOT objects.
Definition: TBrowser.h:41
virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py)
Execute action corresponding to one event.
Definition: TH1.cxx:3059
Int_t fN
Definition: TArray.h:40
virtual Double_t * GetIntegral()
Return a pointer to the array of bins integral.
Definition: TH1.cxx:2428
virtual void SetRange(Int_t first=0, Int_t last=0)
Set the viewing range for the axis from bin first to last.
Definition: TAxis.cxx:831
void Clear(Option_t *option="")
Remove all objects from the list.
Definition: THashList.cxx:167
float ymax
Definition: THbookFile.cxx:93
virtual void SetParLimits(Int_t ipar, Double_t parmin, Double_t parmax)
Set limits for parameter ipar.
Definition: TF1.cxx:3206
friend TH1C operator-(const TH1C &h1, const TH1C &h2)
Operator -.
Definition: TH1.cxx:8967
friend TH1C operator+(const TH1C &h1, const TH1C &h2)
Operator +.
Definition: TH1.cxx:8955
void FillData(BinData &dv, const TH1 *hist, TF1 *func=0)
fill the data vector from a TH1.
virtual TObject * First() const
Return the first object in the list. Returns 0 when list is empty.
Definition: TList.cxx:556
virtual void FillRandom(const char *fname, Int_t ntimes=5000)
Fill histogram following distribution in function fname.
Definition: TH1.cxx:3336
void SetHistFillStyle(Style_t styl=0)
Definition: TStyle.h:376
Int_t GetLast() const
Return last bin on the axis i.e.
Definition: TAxis.cxx:440
static void SmoothArray(Int_t NN, Double_t *XX, Int_t ntimes=1)
smooth array xx, translation of Hbook routine hsmoof.F based on algorithm 353QH twice presented by J...
Definition: TH1.cxx:6324
Class to manage histogram axis.
Definition: TAxis.h:36
virtual Double_t GetKurtosis(Int_t axis=1) const
For axis =1, 2 or 3 returns kurtosis of the histogram along x, y or z axis.
Definition: TH1.cxx:7194
virtual void Draw(Option_t *option="")
Draw this histogram with options.
Definition: TH1.cxx:2884
static bool CheckBinLabels(const TAxis *a1, const TAxis *a2)
check that axis have same labels
Definition: TH1.cxx:1401
Array of shorts (16 bits per element).
Definition: TArrayS.h:29
virtual Double_t GetPointReal(Int_t ipoint, Bool_t fromInput=kFALSE) const =0
Int_t GetSize() const
Definition: TArray.h:49
SVector< double, 2 > v
Definition: Dict.h:5
TH1 * R__H(Int_t hid)
return pointer to histogram with name hid if id >=0 h_id if id <0
Definition: TH1.cxx:9798
virtual void SetFillColor(Color_t fcolor)
Definition: TAttFill.h:50
A 3-Dim function with parameters.
Definition: TF3.h:30
virtual Double_t GetBinWithContent(Double_t c, Int_t &binx, Int_t firstx=0, Int_t lastx=0, Double_t maxdiff=0) const
compute first binx in the range [firstx,lastx] for which diff = abs(bin_content-c) <= maxdiff In case...
Definition: TH1.cxx:4659
friend TH1I operator+(const TH1I &h1, const TH1I &h2)
Operator +.
Definition: TH1.cxx:9355
void SetCanExtend(Bool_t canExtend)
Definition: TAxis.h:91
1-D histogram with an int per channel (see TH1 documentation)}
Definition: TH1.h:529
Long_t ExecPlugin(int nargs, const T &... params)
virtual TObject * Remove(TObject *obj)
Remove object from the list.
Definition: TList.cxx:674
virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py)=0
Execute action corresponding to an event at (px,py).
unsigned int r1[N_CITIES]
Definition: simanTSP.cxx:321
Provides an indirection to the TFitResult class and with a semantics identical to a TFitResult pointe...
Definition: TFitResultPtr.h:33
static TH1 * TransformHisto(TVirtualFFT *fft, TH1 *h_output, Option_t *option)
For a given transform (first parameter), fills the histogram (second parameter) with the transform ou...
Definition: TH1.cxx:8653
static TVirtualFFT * FFT(Int_t ndim, Int_t *n, Option_t *option)
Returns a pointer to the FFT of requested size and type.
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition: TObject.cxx:487
virtual void SetBinContent(Int_t bin, Double_t content)
Set bin content see convention for numbering bins in TH1::GetBin In case the bin number is greater th...
Definition: TH1.cxx:8549
Collection abstract base class.
Definition: TCollection.h:48
static Int_t fgBufferSize
Definition: TH1.h:126
virtual TH1 * Rebin(Int_t ngroup=2, const char *newname="", const Double_t *xbins=0)
Rebin this histogram.
Definition: TH1.cxx:5865
virtual Double_t AndersonDarlingTest(const TH1 *h2, Option_t *option="") const
Statistical test of compatibility in shape between this histogram and h2, using the Anderson-Darling ...
Definition: TH1.cxx:7503
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition: TString.cxx:2321
Double_t fEntries
Definition: TH1.h:107
unsigned int UInt_t
Definition: RtypesCore.h:42
virtual void SaveFillAttributes(std::ostream &out, const char *name, Int_t coldef=1, Int_t stydef=1001)
Save fill attributes as C++ statement(s) on output stream out.
Definition: TAttFill.cxx:229
virtual Float_t GetTitleOffset() const
Definition: TAttAxis.h:56
virtual void LabelsDeflate(Option_t *axis="X")
Reduce the number of bins for the axis passed in the option to the number of bins having a label...
Definition: TH1.cxx:4782
virtual void DoFillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride=1)
internal method to fill histogram content from a vector called directly by TH1::BufferEmpty ...
Definition: TH1.cxx:3295
TMarker * m
Definition: textangle.C:8
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:918
char * Form(const char *fmt,...)
virtual void Transform()=0
virtual Double_t Chisquare(TF1 *f1, Option_t *option="") const
Compute and return the chisquare of this histogram with respect to a function The chisquare is comput...
Definition: TH1.cxx:2342
Ssiz_t Length() const
Definition: TString.h:390
virtual void Append(TObject *obj, Bool_t replace=kFALSE)
Append object to this directory.
Definition: TDirectory.cxx:151
static TVirtualFitter * GetFitter()
static: return the current Fitter
Double_t E()
Definition: TMath.h:54
virtual void Copy(TObject &hnew) const
Copy this histogram structure to newth1.
Definition: TH1.cxx:2494
virtual TH1 * ShowBackground(Int_t niter=20, Option_t *option="same")
This function calculates the background spectrum in this histogram.
Definition: TH1.cxx:8618
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9321
virtual ~TH1C()
Destructor.
Definition: TH1.cxx:8863
static void RejectPoint(Bool_t reject=kTRUE)
Static function to set the global flag to reject points the fgRejectPoint global flag is tested by al...
Definition: TF1.cxx:3390
short Short_t
Definition: RtypesCore.h:35
TLine * l
Definition: textangle.C:4
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9102
virtual void SetMarkerStyle(Style_t mstyle=1)
Definition: TAttMarker.h:53
virtual Double_t GetContourLevelPad(Int_t level) const
Return the value of contour number "level" in Pad coordinates ie: if the Pad is in log scale along Z ...
Definition: TH1.cxx:7824
double Chisquare(const TH1 &h1, TF1 &f1, bool useRange)
compute the chi2 value for an histogram given a function (see TH1::Chisquare for the documentation) ...
Definition: HFitImpl.cxx:989
TAxis * GetYaxis()
Definition: TH1.h:320
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition: BinData.h:61
float xmax
Definition: THbookFile.cxx:93
virtual TObject * At(Int_t idx) const
Returns the object at position idx. Returns 0 if idx is out of range.
Definition: TList.cxx:310
virtual Color_t GetTitleColor() const
Definition: TAttAxis.h:59
Double_t * fIntegral
Histogram dimension (1, 2 or 3 dim)
Definition: TH1.h:123
static bool CheckConsistency(const TH1 *h1, const TH1 *h2)
Check histogram compatibility.
Definition: TH1.cxx:1521
void SetName(const char *name)
Definition: TCollection.h:116
A 2-Dim function with parameters.
Definition: TF2.h:33
void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b)
Extracted from CERN Program library routine DSEQN.
Definition: TH1.cxx:4456
TH1()
Histogram default constructor.
Definition: TH1.cxx:561
R__EXTERN TRandom * gRandom
Definition: TRandom.h:62
1-D histogram with a double per channel (see TH1 documentation)}
Definition: TH1.h:613
virtual Int_t GetBin(Int_t binx, Int_t biny=0, Int_t binz=0) const
Return Global bin number corresponding to binx,y,z.
Definition: TH1.cxx:4541
static Int_t GetDefaultBufferSize()
static function return the default buffer size for automatic histograms the parameter fgBufferSize ma...
Definition: TH1.cxx:4038
virtual void SetAxisColor(Color_t color=1, Float_t alpha=1.)
Set color of the line axis and tick marks.
Definition: TAttAxis.cxx:145
TString fName
Definition: TNamed.h:36
virtual TObject * FindObject(const char *name) const
search object named name in the list of functions
Definition: TH1.cxx:3584
virtual void Rebuild(Option_t *option="")
Using the current bin info, recompute the arrays for contents and errors.
Definition: TH1.cxx:6658
virtual Int_t FindFirstBinAbove(Double_t threshold=0, Int_t axis=1) const
Find first bin with content > threshold for axis (1=x, 2=y, 3=z) if no bins with content > threshold ...
Definition: TH1.cxx:3545
virtual void SetLabelSize(Float_t size=0.04)
Set size of axis labels The size is expressed in per cent of the pad width.
Definition: TAttAxis.cxx:186
virtual void SetMarkerSize(Size_t msize=1)
Definition: TAttMarker.h:54
friend TH1I operator/(const TH1I &h1, const TH1I &h2)
Operator /.
Definition: TH1.cxx:9391
REAL epsilon
Definition: triangle.c:617
virtual void SetTitleColor(Color_t color=1)
Set color of axis title.
Definition: TAttAxis.cxx:263
virtual TObjLink * FirstLink() const
Definition: TList.h:101
virtual void SetTitleSize(Float_t size=0.04)
Set size of axis title The size is expressed in per cent of the pad width.
Definition: TAttAxis.cxx:254
#define Printf
Definition: TGeoToOCC.h:18
virtual void RecursiveRemove(TObject *obj)
Recursively remove object from the list of functions.
Definition: TH1.cxx:6153
EBinErrorOpt fBinStatErrOpt
pointer to histogram painter
Definition: TH1.h:125
virtual Double_t RetrieveBinContent(Int_t bin) const
raw retrieval of bin content on internal data structure see convention for numbering bins in TH1::Get...
Definition: TH1.cxx:8774
virtual Double_t GetMinimum(Double_t minval=-FLT_MAX) const
Return minimum value larger than minval of bins in the range, unless the value has been overridden by...
Definition: TH1.cxx:8012
#define R__LOCKGUARD2(mutex)
TVirtualFFT is an interface class for Fast Fourier Transforms.
Definition: TVirtualFFT.h:92
virtual Color_t GetLineColor() const
Definition: TAttLine.h:47
Double_t Pi()
Definition: TMath.h:44
virtual Int_t FindBin(Double_t x)
Find bin number corresponding to abscissa x.
Definition: TAxis.cxx:264
virtual void SetName(const char *name)
Change the name of this histogram.
Definition: TH1.cxx:8294
friend TH1I operator*(Double_t c1, const TH1I &h1)
Operator *.
Definition: TH1.cxx:9343
static TVirtualFFT * SineCosine(Int_t ndim, Int_t *n, Int_t *r2rkind, Option_t *option)
Returns a pointer to a sine or cosine transform of requested size and kind.
TString & Remove(Ssiz_t pos)
Definition: TString.h:616
virtual Int_t ReadClassBuffer(const TClass *cl, void *pointer, const TClass *onfile_class=0)=0
virtual Int_t GetSumw2N() const
Definition: TH1.h:314
Double_t fTsumw2
Definition: TH1.h:109
Color_t GetHistFillColor() const
Definition: TStyle.h:241
virtual Double_t Eval(Double_t x, Double_t y=0, Double_t z=0, Double_t t=0) const
Evaluate this function.
Definition: TF1.cxx:1185
virtual void GetPointComplex(Int_t ipoint, Double_t &re, Double_t &im, Bool_t fromInput=kFALSE) const =0
virtual Bool_t IsEmpty() const
Definition: TCollection.h:99
return c2
Definition: legend2.C:14
virtual Double_t GetBinWidth(Int_t bin) const
return bin width for 1D historam Better to use h1.GetXaxis().GetBinWidth(bin)
Definition: TH1.cxx:8498
static const double x1[5]
virtual TObject * Remove(TObject *)
Remove an object from the in-memory list.
#define ClassImp(name)
Definition: Rtypes.h:279
class describing the range in the coordinates it supports multiple range in a coordinate.
Definition: DataRange.h:34
Bool_t IsBinOverflow(Int_t bin) const
Definition: TH1.cxx:4738
virtual Double_t GetBinErrorLow(Int_t bin) const
Return lower error associated to bin number bin.
Definition: TH1.cxx:8418
double Double_t
Definition: RtypesCore.h:55
Int_t GetOptStat() const
Definition: TStyle.h:253
Int_t * fArray
Definition: TArrayI.h:32
void SetHistLineStyle(Style_t styl=0)
Definition: TStyle.h:377
virtual void SavePrimitiveHelp(std::ostream &out, const char *hname, Option_t *option="")
helper function for the SavePrimitive functions from TH1 or classes derived from TH1, eg TProfile, TProfile2D.
Definition: TH1.cxx:6870
Double_t fTsumw
Definition: TH1.h:108
Color_t GetHistLineColor() const
Definition: TStyle.h:242
friend TH1D operator*(Double_t c1, const TH1D &h1)
Operator *.
Definition: TH1.cxx:9736
Describe directory structure in memory.
Definition: TDirectory.h:41
int type
Definition: TGX11.cxx:120
Double_t Median(Long64_t n, const T *a, const Double_t *w=0, Long64_t *work=0)
Definition: TMath.h:1077
unsigned long ULong_t
Definition: RtypesCore.h:51
int nentries
Definition: THbookFile.cxx:89
Double_t y[n]
Definition: legend1.C:17
double func(double *x, double *p)
Definition: stressTF1.cxx:213
virtual Color_t GetFillColor() const
Definition: TAttFill.h:43
TH1I & operator=(const TH1I &h1)
Operator =.
Definition: TH1.cxx:9332
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:567
The TH1 histogram class.
Definition: TH1.h:80
virtual Double_t GetEntries() const
return the current number of entries
Definition: TH1.cxx:4057
virtual Float_t GetTitleSize() const
Definition: TAttAxis.h:57
virtual Double_t Chi2TestX(const TH1 *h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option="UU", Double_t *res=0) const
The computation routine of the Chisquare test.
Definition: TH1.cxx:1915
static bool IsEquidistantBinning(const TAxis &axis)
Definition: TH1.cxx:5169
Short_t fBarOffset
Definition: TH1.h:105
virtual void SetLineStyle(Style_t lstyle)
Definition: TAttLine.h:56
double Stat_t
Definition: RtypesCore.h:73
Array of doubles (64 bits per element).
Definition: TArrayD.h:29
Bool_t IsNull() const
Definition: TString.h:387
void FitOptionsMake(EFitObjectType type, const char *option, Foption_t &fitOption)
Decode list of options into fitOption.
Definition: HFitImpl.cxx:673
virtual void InitArgs(const Double_t *x, const Double_t *params)
Initialize parameters addresses.
Definition: TF1.cxx:2221
#define name(a, b)
Definition: linkTestLib0.cpp:5
virtual Bool_t Add(TF1 *h1, Double_t c1=1, Option_t *option="")
Performs the operation: this = this + c1*f1 if errors are defined (see TH1::Sumw2), errors are also recalculated.
Definition: TH1.cxx:785
Abstract Base Class for Fitting.
TAxis * GetZaxis()
Definition: TH1.h:321
virtual UInt_t SetCanExtend(UInt_t extendBitMask)
make the histogram axes extendable / not extendable according to the bit mask returns the previous bi...
Definition: TH1.cxx:6217
virtual Int_t FindFixBin(Double_t x, Double_t y=0, Double_t z=0) const
Return Global bin number corresponding to x,y,z.
Definition: TH1.cxx:3518
Mother of all ROOT objects.
Definition: TObject.h:58
virtual Int_t FindFixBin(Double_t x) const
Find bin number corresponding to abscissa x.
Definition: TAxis.cxx:390
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9122
Bool_t IsReading() const
Definition: TStyle.h:296
virtual void ClearUnderflowAndOverflow()
Remove all the content from the underflow and overflow bins, without changing the number of entries A...
Definition: TH1.cxx:2360
virtual Bool_t IsInside(const Double_t *x) const
return kTRUE if the point is inside the function range
Definition: TF1.h:411
char Char_t
Definition: RtypesCore.h:29
virtual char * GetObjectInfo(Int_t px, Int_t py) const
Redefines TObject::GetObjectInfo.
Definition: TH1.cxx:4092
TH1S & operator=(const TH1S &h1)
Operator =.
Definition: TH1.cxx:9133
virtual Int_t GetNpar() const
Definition: TF1.h:349
Style_t GetHistLineStyle() const
Definition: TStyle.h:244
Double_t fMaximum
Definition: TH1.h:112
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width.
Definition: TAxis.cxx:511
virtual void DirectoryAutoAdd(TDirectory *)
Perform the automatic addition of the histogram to the given directory.
Definition: TH1.cxx:2595
TVirtualHistPainter * fPainter
Integral of bins used by GetRandom.
Definition: TH1.h:124
virtual void Copy(TObject &named) const
Copy this to obj.
Definition: TNamed.cxx:83
friend TH1C operator/(const TH1C &h1, const TH1C &h2)
Operator /.
Definition: TH1.cxx:8991
friend TH1S operator*(Double_t c1, const TH1S &h1)
Operator *.
Definition: TH1.cxx:9143
static Bool_t RejectedPoint()
See TF1::RejectPoint above.
Definition: TF1.cxx:3399
virtual void DrawPanel()
Display a panel with all histogram drawing options.
Definition: TH1.cxx:2992
virtual void Add(TObject *obj)
Definition: TList.h:81
Int_t fBufferSize
Definition: TH1.h:119
double f2(const double *x)
virtual void RecursiveRemove(TObject *obj)
Remove object from this collection and recursively remove the object from all other objects (and coll...
Definition: TList.cxx:634
virtual Int_t GetMinimumBin() const
Return location of bin with minimum value in the range.
Definition: TH1.cxx:8043
virtual Double_t GetBinErrorSqUnchecked(Int_t bin) const
Definition: TH1.h:438
virtual void GetRange(Double_t *xmin, Double_t *xmax) const
Return range of a generic N-D function.
Definition: TF1.cxx:1976
virtual Double_t DoIntegral(Int_t ix1, Int_t ix2, Int_t iy1, Int_t iy2, Int_t iz1, Int_t iz2, Double_t &err, Option_t *opt, Bool_t doerr=kFALSE) const
internal function compute integral and optionally the error between the limits specified by the bin n...
Definition: TH1.cxx:7421
virtual void FillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride=1)
Fill this histogram with an array x and weights w.
Definition: TH1.cxx:3271
Short_t Max(Short_t a, Short_t b)
Definition: TMathBase.h:202
1-Dim function class
Definition: TF1.h:149
virtual void SetBinsLength(Int_t=-1)
Definition: TH1.h:372
Int_t IsNaN(Double_t x)
Definition: TMath.h:617
Char_t * fArray
Definition: TArrayC.h:32
1-D histogram with a byte per channel (see TH1 documentation)
Definition: TH1.h:447
virtual void Sumw2(Bool_t flag=kTRUE)
Create structure to store sum of squares of weights.
Definition: TH1.cxx:8356
TObject * Clone(const char *newname=0) const
Make a complete copy of the underlying object.
Definition: TH1.cxx:2571
TF1 * f1
Definition: legend1.C:11
Double_t GetAt(Int_t i) const
Definition: TArrayD.h:47
Double_t Ceil(Double_t x)
Definition: TMath.h:467
void SetOptStat(Int_t stat=1)
The type of information printed in the histogram statistics box can be selected via the parameter mod...
Definition: TStyle.cxx:1252
#define NULL
Definition: Rtypes.h:82
Int_t fDimension
Pointer to directory holding this histogram.
Definition: TH1.h:122
#define gPad
Definition: TVirtualPad.h:288
void Reset()
Definition: TArrayI.h:49
virtual void SetTickLength(Float_t length=0.03)
Set tick mark length The length is expressed in per cent of the pad width.
Definition: TAttAxis.cxx:231
virtual Int_t GetXlast() const
virtual Double_t GetBinErrorUp(Int_t bin) const
Return upper error associated to bin number bin.
Definition: TH1.cxx:8447
virtual Int_t BufferEmpty(Int_t action=0)
Fill histogram with all entries in the buffer.
Definition: TH1.cxx:1256
virtual void SetParent(TObject *obj)
Definition: TAxis.h:157
void Set(Int_t n)
Set size of this array to n floats.
Definition: TArrayF.cxx:104
virtual ~TH1D()
Destructor.
Definition: TH1.cxx:9678
virtual void SetEntries(Double_t n)
Definition: TH1.h:382
TAxis fXaxis
Definition: TH1.h:102
Float_t GetBarOffset() const
Definition: TStyle.h:192
virtual TH1 * GetHistogram() const
Return a pointer to the histogram used to vusualize the function.
Definition: TF1.cxx:1297
void ResetBit(UInt_t f)
Definition: TObject.h:172
virtual void SetParameter(Int_t param, Double_t value)
Definition: TF1.h:431
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:9280
virtual void SetTitle(const char *title)
Change (i.e.
Definition: TH1.cxx:6274
TFitResultPtr FitObject(TH1 *h1, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption, const char *goption, ROOT::Fit::DataRange &range)
fitting function for a TH1 (called from TH1::Fit)
Definition: HFitImpl.cxx:935
virtual Int_t GetNdim() const =0
virtual Color_t GetMarkerColor() const
Definition: TAttMarker.h:44
virtual Int_t GetNbinsX() const
Definition: TH1.h:296
Option_t * GetDrawOption() const
Get option used by the graphics system to draw this object.
Definition: TBrowser.h:108
virtual Int_t Poisson(Double_t mean)
Generates a random integer N according to a Poisson law.
Definition: TRandom.cxx:362
virtual Style_t GetFillStyle() const
Definition: TAttFill.h:44
Double_t Sqrt(Double_t x)
Definition: TMath.h:464
virtual void Fatal(const char *method, const char *msgfmt,...) const
Issue fatal error message.
Definition: TObject.cxx:946
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:8880
Int_t GetNbins() const
Definition: TAxis.h:125
Bool_t GetCanvasPreferGL() const
Definition: TStyle.h:197
virtual const char * GetName() const
Returns name of object.
Definition: TObject.cxx:415
virtual Int_t GetSize() const
Definition: TCollection.h:95
virtual void Set(Int_t nbins, Double_t xmin, Double_t xmax)
Initialize axis with fix bins.
Definition: TAxis.cxx:701
const Bool_t kTRUE
Definition: Rtypes.h:91
float * q
Definition: THbookFile.cxx:87
static Bool_t AlmostEqual(Double_t a, Double_t b, Double_t epsilon=0.00000001)
Definition: TH1.cxx:5155
virtual Double_t EvalPar(const Double_t *x, const Double_t *params=0)
Evaluate function with given coordinates and parameters.
Definition: TF1.cxx:1215
virtual void SetTitle(const char *title="")
Change (i.e. set) the title of the TNamed.
Definition: TNamed.cxx:152
TList * GetListOfFunctions() const
Definition: TH1.h:244
void SetHistLineColor(Color_t color=1)
Definition: TStyle.h:375
virtual TObject * GetUserFunc() const
virtual TObject * GetObjectFit() const
Double_t * fBuffer
Definition: TH1.h:120
float value
Definition: math.cpp:443
virtual TFitResultPtr Fit(const char *formula, Option_t *option="", Option_t *goption="", Double_t xmin=0, Double_t xmax=0)
Fit histogram with function fname.
Definition: TH1.cxx:3613
double norm(double *x, double *p)
Definition: unuranDistr.cxx:40
Int_t Nint(T x)
Definition: TMath.h:480
void AbstractMethod(const char *method) const
Use this method to implement an "abstract" method that you don&#39;t want to leave purely abstract...
Definition: TObject.cxx:960
virtual void UpdateBinContent(Int_t bin, Double_t content)
raw update of bin content on internal data structure see convention for numbering bins in TH1::GetBin...
Definition: TH1.cxx:8785
virtual Double_t GetStdDev(Int_t axis=1) const
Returns the Standard Deviation (Sigma).
Definition: TH1.cxx:7073
void Set(Int_t n)
Set size of this array to n doubles.
Definition: TArrayD.cxx:104
virtual Double_t GetRandom() const
return a random number distributed according the histogram bin contents.
Definition: TH1.cxx:4589
static bool CheckEqualAxes(const TAxis *a1, const TAxis *a2)
Check that the axis are the same.
Definition: TH1.cxx:1448
Double_t GetXmax() const
Definition: TAxis.h:138
double gamma_quantile(double z, double alpha, double theta)
Inverse ( ) of the cumulative distribution function of the lower tail of the gamma distribution (gamm...
virtual ~TH1S()
Destructor.
Definition: TH1.cxx:9064
void Copy(TArrayD &array) const
Definition: TArrayD.h:44
virtual Int_t GetMaximumBin() const
Return location of bin with maximum value in the range.
Definition: TH1.cxx:7958
const Int_t n
Definition: legend1.C:16
Line Attributes class.
Definition: TAttLine.h:32
virtual void GetCenter(Double_t *center) const
Fill array with center of bins for 1D histogram Better to use h1.GetXaxis().GetCenter(center) ...
Definition: TH1.cxx:8509
void H1InitPolynom()
Compute Initial values of parameters for a polynom.
Definition: TH1.cxx:4318
virtual void SetStats(Bool_t stats=kTRUE)
Set statistics option on/off.
Definition: TH1.cxx:8326
TH1F & operator=(const TH1F &h1)
Operator =.
Definition: TH1.cxx:9529
virtual Float_t GetBarWidth() const
Definition: TH1.h:257
Long64_t BinarySearch(Long64_t n, const T *array, T value)
Definition: TMath.h:944
const TArrayD * GetXbins() const
Definition: TAxis.h:134
virtual void GetLowEdge(Double_t *edge) const
Fill array with low edge of bins for 1D histogram Better to use h1.GetXaxis().GetLowEdge(edge) ...
Definition: TH1.cxx:8522
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:904
TAxis * GetXaxis()
Definition: TH1.h:319
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:8921
virtual Style_t GetLabelFont() const
Definition: TAttAxis.h:53
virtual Long64_t Merge(TCollection *list)
Add all histograms in the collection to this histogram.
Definition: TH1.cxx:5311
virtual Version_t ReadVersion(UInt_t *start=0, UInt_t *bcnt=0, const TClass *cl=0)=0
virtual const char * GetTitle() const
Returns title of object.
Definition: TNamed.h:52
virtual Int_t GetNbinsY() const
Definition: TH1.h:297
virtual Option_t * GetType() const =0
virtual Double_t GetBinError(Int_t bin) const
Return value of error associated to bin number bin.
Definition: TH1.cxx:8401
virtual Int_t ReadArray(Bool_t *&b)=0
Int_t fNcells
Definition: TH1.h:101
void Copy(TAttFill &attfill) const
Copy this fill attributes to a new TAttFill.
Definition: TAttFill.cxx:197
void AndersonDarling2SamplesTest(Double_t &pvalue, Double_t &testStat) const
Definition: GoFTest.cxx:643
T MinElement(Long64_t n, const T *a)
Definition: TMath.h:681
void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
Least square linear fit without weights.
Definition: TH1.cxx:4409
const char * Data() const
Definition: TString.h:349
Array of chars or bytes (8 bits per element).
Definition: TArrayC.h:29
virtual void SavePrimitive(std::ostream &out, Option_t *option="")
Save a primitive as a C++ statement(s) on output stream "out".
Definition: TObject.cxx:702
Double_t ATan(Double_t)
Definition: TMath.h:451