Logo ROOT   6.12/07
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 #include <cmath>
18 
19 #include "Riostream.h"
20 #include "TROOT.h"
21 #include "TEnv.h"
22 #include "TClass.h"
23 #include "TMath.h"
24 #include "THashList.h"
25 #include "TH1.h"
26 #include "TH2.h"
27 #include "TH3.h"
28 #include "TF2.h"
29 #include "TF3.h"
30 #include "TPluginManager.h"
31 #include "TVirtualPad.h"
32 #include "TRandom.h"
33 #include "TVirtualFitter.h"
34 #include "THLimitsFinder.h"
35 #include "TProfile.h"
36 #include "TStyle.h"
37 #include "TVectorF.h"
38 #include "TVectorD.h"
39 #include "TBrowser.h"
40 #include "TObjString.h"
41 #include "TError.h"
42 #include "TVirtualHistPainter.h"
43 #include "TVirtualFFT.h"
44 #include "TSystem.h"
45 
46 #include "HFitInterface.h"
47 #include "Fit/DataRange.h"
48 #include "Fit/BinData.h"
49 #include "Math/GoFTest.h"
50 #include "Math/MinimizerOptions.h"
51 #include "Math/QuantFuncMathCore.h"
52 
53 #include "TH1Merger.h"
54 
55 /** \addtogroup Hist
56 @{
57 \class TH1C
58 \brief 1-D histogram with a byte per channel (see TH1 documentation)
59 \class TH1S
60 \brief 1-D histogram with a short per channel (see TH1 documentation)
61 \class TH1I
62 \brief 1-D histogram with an int per channel (see TH1 documentation)}
63 \class TH1F
64 \brief 1-D histogram with a float per channel (see TH1 documentation)}
65 \class TH1D
66 \brief 1-D histogram with a double per channel (see TH1 documentation)}
67 @}
68 */
69 
70 /** \class TH1
71 The TH1 histogram class.
72 
73 ### The Histogram classes
74 ROOT supports the following histogram types:
75 
76  - 1-D histograms:
77  - TH1C : histograms with one byte per channel. Maximum bin content = 127
78  - TH1S : histograms with one short per channel. Maximum bin content = 32767
79  - TH1I : histograms with one int per channel. Maximum bin content = 2147483647
80  - TH1F : histograms with one float per channel. Maximum precision 7 digits
81  - TH1D : histograms with one double per channel. Maximum precision 14 digits
82  - 2-D histograms:
83  - TH2C : histograms with one byte per channel. Maximum bin content = 127
84  - TH2S : histograms with one short per channel. Maximum bin content = 32767
85  - TH2I : histograms with one int per channel. Maximum bin content = 2147483647
86  - TH2F : histograms with one float per channel. Maximum precision 7 digits
87  - TH2D : histograms with one double per channel. Maximum precision 14 digits
88  - 3-D histograms:
89  - TH3C : histograms with one byte per channel. Maximum bin content = 127
90  - TH3S : histograms with one short per channel. Maximum bin content = 32767
91  - TH3I : histograms with one int per channel. Maximum bin content = 2147483647
92  - TH3F : histograms with one float per channel. Maximum precision 7 digits
93  - TH3D : histograms with one double per channel. Maximum precision 14 digits
94  - Profile histograms: See classes TProfile, TProfile2D and TProfile3D.
95  Profile histograms are used to display the mean value of Y and its standard deviation
96  for each bin in X. Profile histograms are in many cases an elegant
97  replacement of two-dimensional histograms : the inter-relation of two
98  measured quantities X and Y can always be visualized by a two-dimensional
99  histogram or scatter-plot; If Y is an unknown (but single-valued)
100  approximate function of X, this function is displayed by a profile
101  histogram with much better precision than by a scatter-plot.
102 
103 
104 All histogram classes are derived from the base class TH1
105 ~~~ {.cpp}
106  TH1
107  ^
108  |
109  |
110  |
111  +----------------+-------+------+------+-----+-----+
112  | | | | | | |
113  | | TH1C TH1S TH1I TH1F TH1D
114  | | |
115  | | |
116  | TH2 TProfile
117  | |
118  | |
119  | +-------+------+------+-----+-----+
120  | | | | | |
121  | TH2C TH2S TH2I TH2F TH2D
122  | |
123  TH3 |
124  | TProfile2D
125  |
126  +-------+------+------+------+------+
127  | | | | |
128  TH3C TH3S TH3I TH3F TH3D
129  |
130  |
131  TProfile3D
132 
133  The TH*C classes also inherit from the array class TArrayC.
134  The TH*S classes also inherit from the array class TArrayS.
135  The TH*I classes also inherit from the array class TArrayI.
136  The TH*F classes also inherit from the array class TArrayF.
137  The TH*D classes also inherit from the array class TArrayD.
138 ~~~
139 
140 #### Creating histograms
141 
142 Histograms are created by invoking one of the constructors, e.g.
143 ~~~ {.cpp}
144  TH1F *h1 = new TH1F("h1", "h1 title", 100, 0, 4.4);
145  TH2F *h2 = new TH2F("h2", "h2 title", 40, 0, 4, 30, -3, 3);
146 ~~~
147 Histograms may also be created by:
148 
149  - calling the Clone function, see below
150  - making a projection from a 2-D or 3-D histogram, see below
151  - reading an histogram from a file
152 
153  When an histogram is created, a reference to it is automatically added
154  to the list of in-memory objects for the current file or directory.
155  This default behaviour can be changed by:
156 ~~~ {.cpp}
157  h->SetDirectory(0); for the current histogram h
158  TH1::AddDirectory(kFALSE); sets a global switch disabling the reference
159 ~~~
160  When the histogram is deleted, the reference to it is removed from
161  the list of objects in memory.
162  When a file is closed, all histograms in memory associated with this file
163  are automatically deleted.
164 
165 #### Fix or variable bin size
166 
167  All histogram types support either fix or variable bin sizes.
168  2-D histograms may have fix size bins along X and variable size bins
169  along Y or vice-versa. The functions to fill, manipulate, draw or access
170  histograms are identical in both cases.
171 
172  Each histogram always contains 3 objects TAxis: fXaxis, fYaxis and fZaxis
173  o access the axis parameters, do:
174 ~~~ {.cpp}
175  TAxis *xaxis = h->GetXaxis(); etc.
176  Double_t binCenter = xaxis->GetBinCenter(bin), etc.
177 ~~~
178  See class TAxis for a description of all the access functions.
179  The axis range is always stored internally in double precision.
180 
181 #### Convention for numbering bins
182 
183  For all histogram types: nbins, xlow, xup
184 ~~~ {.cpp}
185  bin = 0; underflow bin
186  bin = 1; first bin with low-edge xlow INCLUDED
187  bin = nbins; last bin with upper-edge xup EXCLUDED
188  bin = nbins+1; overflow bin
189 ~~~
190  In case of 2-D or 3-D histograms, a "global bin" number is defined.
191  For example, assuming a 3-D histogram with (binx, biny, binz), the function
192 ~~~ {.cpp}
193  Int_t gbin = h->GetBin(binx, biny, binz);
194 ~~~
195  returns a global/linearized gbin number. This global gbin is useful
196  to access the bin content/error information independently of the dimension.
197  Note that to access the information other than bin content and errors
198  one should use the TAxis object directly with e.g.:
199 ~~~ {.cpp}
200  Double_t xcenter = h3->GetZaxis()->GetBinCenter(27);
201 ~~~
202  returns the center along z of bin number 27 (not the global bin)
203  in the 3-D histogram h3.
204 
205 #### Alphanumeric Bin Labels
206 
207  By default, an histogram axis is drawn with its numeric bin labels.
208  One can specify alphanumeric labels instead with:
209 
210  - call TAxis::SetBinLabel(bin, label);
211  This can always be done before or after filling.
212  When the histogram is drawn, bin labels will be automatically drawn.
213  See examples labels1.C and labels2.C
214  - call to a Fill function with one of the arguments being a string, e.g.
215 ~~~ {.cpp}
216  hist1->Fill(somename, weight);
217  hist2->Fill(x, somename, weight);
218  hist2->Fill(somename, y, weight);
219  hist2->Fill(somenamex, somenamey, weight);
220 ~~~
221  See examples hlabels1.C and hlabels2.C
222  - via TTree::Draw. see for example cernstaff.C
223 ~~~ {.cpp}
224  tree.Draw("Nation::Division");
225 ~~~
226  where "Nation" and "Division" are two branches of a Tree.
227 
228 When using the options 2 or 3 above, the labels are automatically
229  added to the list (THashList) of labels for a given axis.
230  By default, an axis is drawn with the order of bins corresponding
231  to the filling sequence. It is possible to reorder the axis
232 
233  - alphabetically
234  - by increasing or decreasing values
235 
236  The reordering can be triggered via the TAxis context menu by selecting
237  the menu item "LabelsOption" or by calling directly
238  TH1::LabelsOption(option, axis) where
239 
240  - axis may be "X", "Y" or "Z"
241  - option may be:
242  - "a" sort by alphabetic order
243  - ">" sort by decreasing values
244  - "<" sort by increasing values
245  - "h" draw labels horizontal
246  - "v" draw labels vertical
247  - "u" draw labels up (end of label right adjusted)
248  - "d" draw labels down (start of label left adjusted)
249 
250  When using the option 2 above, new labels are added by doubling the current
251  number of bins in case one label does not exist yet.
252  When the Filling is terminated, it is possible to trim the number
253  of bins to match the number of active labels by calling
254 ~~~ {.cpp}
255  TH1::LabelsDeflate(axis) with axis = "X", "Y" or "Z"
256 ~~~
257  This operation is automatic when using TTree::Draw.
258  Once bin labels have been created, they become persistent if the histogram
259  is written to a file or when generating the C++ code via SavePrimitive.
260 
261 #### Histograms with automatic bins
262 
263  When an histogram is created with an axis lower limit greater or equal
264  to its upper limit, the SetBuffer is automatically called with an
265  argument fBufferSize equal to fgBufferSize (default value=1000).
266  fgBufferSize may be reset via the static function TH1::SetDefaultBufferSize.
267  The axis limits will be automatically computed when the buffer will
268  be full or when the function BufferEmpty is called.
269 
270 #### Filling histograms
271 
272  An histogram is typically filled with statements like:
273 ~~~ {.cpp}
274  h1->Fill(x);
275  h1->Fill(x, w); //fill with weight
276  h2->Fill(x, y)
277  h2->Fill(x, y, w)
278  h3->Fill(x, y, z)
279  h3->Fill(x, y, z, w)
280 ~~~
281  or via one of the Fill functions accepting names described above.
282  The Fill functions compute the bin number corresponding to the given
283  x, y or z argument and increment this bin by the given weight.
284  The Fill functions return the bin number for 1-D histograms or global
285  bin number for 2-D and 3-D histograms.
286  If TH1::Sumw2 has been called before filling, the sum of squares of
287  weights is also stored.
288  One can also increment directly a bin number via TH1::AddBinContent
289  or replace the existing content via TH1::SetBinContent.
290  To access the bin content of a given bin, do:
291 ~~~ {.cpp}
292  Double_t binContent = h->GetBinContent(bin);
293 ~~~
294 
295  By default, the bin number is computed using the current axis ranges.
296  If the automatic binning option has been set via
297 ~~~ {.cpp}
298  h->SetCanExtend(TH1::kAllAxes);
299 ~~~
300  then, the Fill Function will automatically extend the axis range to
301  accomodate the new value specified in the Fill argument. The method
302  used is to double the bin size until the new value fits in the range,
303  merging bins two by two. This automatic binning options is extensively
304  used by the TTree::Draw function when histogramming Tree variables
305  with an unknown range.
306  This automatic binning option is supported for 1-D, 2-D and 3-D histograms.
307 
308  During filling, some statistics parameters are incremented to compute
309  the mean value and Root Mean Square with the maximum precision.
310 
311  In case of histograms of type TH1C, TH1S, TH2C, TH2S, TH3C, TH3S
312  a check is made that the bin contents do not exceed the maximum positive
313  capacity (127 or 32767). Histograms of all types may have positive
314  or/and negative bin contents.
315 
316 #### Rebinning
317  At any time, an histogram can be rebinned via TH1::Rebin. This function
318  returns a new histogram with the rebinned contents.
319  If bin errors were stored, they are recomputed during the rebinning.
320 
321 #### Associated errors
322  By default, for each bin, the sum of weights is computed at fill time.
323  One can also call TH1::Sumw2 to force the storage and computation
324  of the sum of the square of weights per bin.
325  If Sumw2 has been called, the error per bin is computed as the
326  sqrt(sum of squares of weights), otherwise the error is set equal
327  to the sqrt(bin content).
328  To return the error for a given bin number, do:
329 ~~~ {.cpp}
330  Double_t error = h->GetBinError(bin);
331 ~~~
332 
333 #### Associated functions
334  One or more object (typically a TF1*) can be added to the list
335  of functions (fFunctions) associated to each histogram.
336  When TH1::Fit is invoked, the fitted function is added to this list.
337  Given an histogram h, one can retrieve an associated function
338  with:
339 ~~~ {.cpp}
340  TF1 *myfunc = h->GetFunction("myfunc");
341 ~~~
342 
343 #### Operations on histograms
344 
345  Many types of operations are supported on histograms or between histograms
346 
347  - Addition of an histogram to the current histogram.
348  - Additions of two histograms with coefficients and storage into the current
349  histogram.
350  - Multiplications and Divisions are supported in the same way as additions.
351  - The Add, Divide and Multiply functions also exist to add, divide or multiply
352  an histogram by a function.
353 
354  If an histogram has associated error bars (TH1::Sumw2 has been called),
355  the resulting error bars are also computed assuming independent histograms.
356  In case of divisions, Binomial errors are also supported.
357  One can mark a histogram to be an "average" histogram by setting its bit kIsAverage via
358  myhist.SetBit(TH1::kIsAverage);
359  When adding (see TH1::Add) average histograms, the histograms are averaged and not summed.
360 
361 #### Fitting histograms
362 
363  Histograms (1-D, 2-D, 3-D and Profiles) can be fitted with a user
364  specified function via TH1::Fit. When an histogram is fitted, the
365  resulting function with its parameters is added to the list of functions
366  of this histogram. If the histogram is made persistent, the list of
367  associated functions is also persistent. Given a pointer (see above)
368  to an associated function myfunc, one can retrieve the function/fit
369  parameters with calls such as:
370 ~~~ {.cpp}
371  Double_t chi2 = myfunc->GetChisquare();
372  Double_t par0 = myfunc->GetParameter(0); value of 1st parameter
373  Double_t err0 = myfunc->GetParError(0); error on first parameter
374 ~~~
375 
376 #### Projections of histograms
377 
378  One can:
379 
380  - make a 1-D projection of a 2-D histogram or Profile
381  see functions TH2::ProjectionX,Y, TH2::ProfileX,Y, TProfile::ProjectionX
382  - make a 1-D, 2-D or profile out of a 3-D histogram
383  see functions TH3::ProjectionZ, TH3::Project3D.
384 
385  One can fit these projections via:
386 ~~~ {.cpp}
387  TH2::FitSlicesX,Y, TH3::FitSlicesZ.
388 ~~~
389 
390 #### Random Numbers and histograms
391 
392  TH1::FillRandom can be used to randomly fill an histogram using
393  the contents of an existing TF1 function or another
394  TH1 histogram (for all dimensions).
395  For example the following two statements create and fill an histogram
396  10000 times with a default gaussian distribution of mean 0 and sigma 1:
397 ~~~ {.cpp}
398  TH1F h1("h1", "histo from a gaussian", 100, -3, 3);
399  h1.FillRandom("gaus", 10000);
400 ~~~
401  TH1::GetRandom can be used to return a random number distributed
402  according the contents of an histogram.
403 
404 #### Making a copy of an histogram
405  Like for any other ROOT object derived from TObject, one can use
406  the Clone() function. This makes an identical copy of the original
407  histogram including all associated errors and functions, e.g.:
408 ~~~ {.cpp}
409  TH1F *hnew = (TH1F*)h->Clone("hnew");
410 ~~~
411 
412 #### Normalizing histograms
413 
414  One can scale an histogram such that the bins integral is equal to
415  the normalization parameter via TH1::Scale(Double_t norm), where norm
416  is the desired normalization divided by the integral of the histogram.
417 
418 #### Drawing histograms
419 
420  Histograms are drawn via the THistPainter class. Each histogram has
421  a pointer to its own painter (to be usable in a multithreaded program).
422  Many drawing options are supported.
423  See THistPainter::Paint() for more details.
424 
425  The same histogram can be drawn with different options in different pads.
426  When an histogram drawn in a pad is deleted, the histogram is
427  automatically removed from the pad or pads where it was drawn.
428  If an histogram is drawn in a pad, then filled again, the new status
429  of the histogram will be automatically shown in the pad next time
430  the pad is updated. One does not need to redraw the histogram.
431  To draw the current version of an histogram in a pad, one can use
432 ~~~ {.cpp}
433  h->DrawCopy();
434 ~~~
435  This makes a clone (see Clone below) of the histogram. Once the clone
436  is drawn, the original histogram may be modified or deleted without
437  affecting the aspect of the clone.
438 
439  One can use TH1::SetMaximum() and TH1::SetMinimum() to force a particular
440  value for the maximum or the minimum scale on the plot. (For 1-D
441  histograms this means the y-axis, while for 2-D histograms these
442  functions affect the z-axis).
443 
444  TH1::UseCurrentStyle() can be used to change all histogram graphics
445  attributes to correspond to the current selected style.
446  This function must be called for each histogram.
447  In case one reads and draws many histograms from a file, one can force
448  the histograms to inherit automatically the current graphics style
449  by calling before gROOT->ForceStyle().
450 
451 #### Setting Drawing histogram contour levels (2-D hists only)
452 
453  By default contours are automatically generated at equidistant
454  intervals. A default value of 20 levels is used. This can be modified
455  via TH1::SetContour() or TH1::SetContourLevel().
456  the contours level info is used by the drawing options "cont", "surf",
457  and "lego".
458 
459 #### Setting histogram graphics attributes
460 
461  The histogram classes inherit from the attribute classes:
462  TAttLine, TAttFill, and TAttMarker.
463  See the member functions of these classes for the list of options.
464 
465 #### Giving titles to the X, Y and Z axis
466 
467 ~~~ {.cpp}
468  h->GetXaxis()->SetTitle("X axis title");
469  h->GetYaxis()->SetTitle("Y axis title");
470 ~~~
471  The histogram title and the axis titles can be any TLatex string.
472  The titles are part of the persistent histogram.
473  It is also possible to specify the histogram title and the axis
474  titles at creation time. These titles can be given in the "title"
475  parameter. They must be separated by ";":
476 ~~~ {.cpp}
477  TH1F* h=new TH1F("h", "Histogram title;X Axis;Y Axis;Z Axis", 100, 0, 1);
478 ~~~
479  Any title can be omitted:
480 ~~~ {.cpp}
481  TH1F* h=new TH1F("h", "Histogram title;;Y Axis", 100, 0, 1);
482  TH1F* h=new TH1F("h", ";;Y Axis", 100, 0, 1);
483 ~~~
484  The method SetTitle has the same syntax:
485 ~~~ {.cpp}
486  h->SetTitle("Histogram title;Another X title Axis");
487 ~~~
488 
489 #### Saving/Reading histograms to/from a ROOT file
490 
491  The following statements create a ROOT file and store an histogram
492  on the file. Because TH1 derives from TNamed, the key identifier on
493  the file is the histogram name:
494 ~~~ {.cpp}
495  TFile f("histos.root", "new");
496  TH1F h1("hgaus", "histo from a gaussian", 100, -3, 3);
497  h1.FillRandom("gaus", 10000);
498  h1->Write();
499 ~~~
500  To read this histogram in another Root session, do:
501 ~~~ {.cpp}
502  TFile f("histos.root");
503  TH1F *h = (TH1F*)f.Get("hgaus");
504 ~~~
505  One can save all histograms in memory to the file by:
506 ~~~ {.cpp}
507  file->Write();
508 ~~~
509 
510 #### Miscellaneous operations
511 
512 ~~~ {.cpp}
513  TH1::KolmogorovTest(): statistical test of compatibility in shape
514  between two histograms
515  TH1::Smooth() smooths the bin contents of a 1-d histogram
516  TH1::Integral() returns the integral of bin contents in a given bin range
517  TH1::GetMean(int axis) returns the mean value along axis
518  TH1::GetStdDev(int axis) returns the sigma distribution along axis
519  TH1::GetEntries() returns the number of entries
520  TH1::Reset() resets the bin contents and errors of an histogram
521 ~~~
522 */
523 
524 TF1 *gF1=0; //left for back compatibility (use TVirtualFitter::GetUserFunc instead)
525 
526 Int_t TH1::fgBufferSize = 1000;
530 
531 extern void H1InitGaus();
532 extern void H1InitExpo();
533 extern void H1InitPolynom();
534 extern void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a);
535 extern void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail);
536 extern void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b);
537 
538 // Internal exceptions for the CheckConsistency method
539 class DifferentDimension: public std::exception {};
540 class DifferentNumberOfBins: public std::exception {};
541 class DifferentAxisLimits: public std::exception {};
542 class DifferentBinLimits: public std::exception {};
543 class DifferentLabels: public std::exception {};
544 
545 ClassImp(TH1);
546 
547 ////////////////////////////////////////////////////////////////////////////////
548 /// Histogram default constructor.
549 
551 {
552  fDirectory = 0;
553  fFunctions = new TList;
554  fNcells = 0;
555  fIntegral = 0;
556  fPainter = 0;
557  fEntries = 0;
558  fNormFactor = 0;
560  fMaximum = -1111;
561  fMinimum = -1111;
562  fBufferSize = 0;
563  fBuffer = 0;
565  fStatOverflows = EStatOverflows::kNeutral;
566  fXaxis.SetName("xaxis");
567  fYaxis.SetName("yaxis");
568  fZaxis.SetName("zaxis");
569  fXaxis.SetParent(this);
570  fYaxis.SetParent(this);
571  fZaxis.SetParent(this);
572  UseCurrentStyle();
573 }
574 
575 ////////////////////////////////////////////////////////////////////////////////
576 /// Histogram default destructor.
577 
579 {
580  if (!TestBit(kNotDeleted)) {
581  return;
582  }
583  delete[] fIntegral;
584  fIntegral = 0;
585  delete[] fBuffer;
586  fBuffer = 0;
587  if (fFunctions) {
589 
591  TObject* obj = 0;
592  //special logic to support the case where the same object is
593  //added multiple times in fFunctions.
594  //This case happens when the same object is added with different
595  //drawing modes
596  //In the loop below we must be careful with objects (eg TCutG) that may
597  // have been added to the list of functions of several histograms
598  //and may have been already deleted.
599  while ((obj = fFunctions->First())) {
600  while(fFunctions->Remove(obj)) { }
601  if (!obj->TestBit(kNotDeleted)) {
602  break;
603  }
604  delete obj;
605  obj = 0;
606  }
607  delete fFunctions;
608  fFunctions = 0;
609  }
610  if (fDirectory) {
611  fDirectory->Remove(this);
612  fDirectory = 0;
613  }
614  delete fPainter;
615  fPainter = 0;
616 }
617 
618 ////////////////////////////////////////////////////////////////////////////////
619 /// Normal constructor for fix bin size histograms.
620 /// Creates the main histogram structure.
621 ///
622 /// \param[in] name name of histogram (avoid blanks)
623 /// \param[in] title histogram title.
624 /// If title is of the form stringt;stringx;stringy;stringz`
625 /// the histogram title is set to `stringt`,
626 /// the x axis title to `stringy`, the y axis title to `stringy`, etc.
627 /// \param[in] nbins number of bins
628 /// \param[in] xlow low edge of first bin
629 /// \param[in] xup upper edge of last bin (not included in last bin)
630 ///
631 /// When an histogram is created, it is automatically added to the list
632 /// of special objects in the current directory.
633 /// To find the pointer to this histogram in the current directory
634 /// by its name, do:
635 /// ~~~ {.cpp}
636 /// TH1F *h1 = (TH1F*)gDirectory->FindObject(name);
637 /// ~~~
638 
639 TH1::TH1(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
640  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
641 {
642  Build();
643  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
644  fXaxis.Set(nbins,xlow,xup);
645  fNcells = fXaxis.GetNbins()+2;
646 }
647 
648 ////////////////////////////////////////////////////////////////////////////////
649 /// Normal constructor for variable bin size histograms.
650 /// Creates the main histogram structure.
651 ///
652 /// \param[in] name name of histogram (avoid blanks)
653 /// \param[in] title histogram title.
654 /// If title is of the form `stringt;stringx;stringy;stringz`
655 /// the histogram title is set to `stringt`,
656 /// the x axis title to `stringy`, the y axis title to `stringy`, etc.
657 /// \param[in] nbins number of bins
658 /// \param[in] xbins array of low-edges for each bin.
659 /// This is an array of size nbins+1
660 
661 TH1::TH1(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
662  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
663 {
664  Build();
665  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
666  if (xbins) fXaxis.Set(nbins,xbins);
667  else fXaxis.Set(nbins,0,1);
668  fNcells = fXaxis.GetNbins()+2;
669 }
670 
671 ////////////////////////////////////////////////////////////////////////////////
672 /// Normal constructor for variable bin size histograms.
673 ///
674 /// \param[in] name name of histogram (avoid blanks)
675 /// \param[in] title histogram title.
676 /// If title is of the form `stringt;stringx;stringy;stringz`
677 /// the histogram title is set to `stringt`,
678 /// the x axis title to `stringy`, the y axis title to `stringy`, etc.
679 /// \param[in] nbins number of bins
680 /// \param[in] xbins array of low-edges for each bin.
681 /// This is an array of size nbins+1
682 
683 TH1::TH1(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
684  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
685 {
686  Build();
687  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
688  if (xbins) fXaxis.Set(nbins,xbins);
689  else fXaxis.Set(nbins,0,1);
690  fNcells = fXaxis.GetNbins()+2;
691 }
692 
693 ////////////////////////////////////////////////////////////////////////////////
694 /// Copy constructor.
695 /// The list of functions is not copied. (Use Clone if needed)
696 
698 {
699  ((TH1&)h).Copy(*this);
700 }
701 
702 ////////////////////////////////////////////////////////////////////////////////
703 /// Static function: cannot be inlined on Windows/NT.
704 
706 {
707  return fgAddDirectory;
708 }
709 
710 ////////////////////////////////////////////////////////////////////////////////
711 /// Browse the Histogram object.
712 
714 {
715  Draw(b ? b->GetDrawOption() : "");
716  gPad->Update();
717 }
718 
719 ////////////////////////////////////////////////////////////////////////////////
720 /// Creates histogram basic data structure.
721 
723 {
724  fDirectory = 0;
725  fPainter = 0;
726  fIntegral = 0;
727  fEntries = 0;
728  fNormFactor = 0;
730  fMaximum = -1111;
731  fMinimum = -1111;
732  fBufferSize = 0;
733  fBuffer = 0;
735  fStatOverflows = EStatOverflows::kNeutral;
736  fXaxis.SetName("xaxis");
737  fYaxis.SetName("yaxis");
738  fZaxis.SetName("zaxis");
739  fYaxis.Set(1,0.,1.);
740  fZaxis.Set(1,0.,1.);
741  fXaxis.SetParent(this);
742  fYaxis.SetParent(this);
743  fZaxis.SetParent(this);
744 
745  SetTitle(fTitle.Data());
746 
747  fFunctions = new TList;
748 
749  UseCurrentStyle();
750 
751  if (TH1::AddDirectoryStatus()) {
753  if (fDirectory) {
754  fFunctions->UseRWLock();
755  fDirectory->Append(this,kTRUE);
756  }
757  }
758 }
759 
760 ////////////////////////////////////////////////////////////////////////////////
761 /// Performs the operation: `this = this + c1*f1`
762 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
763 ///
764 /// By default, the function is computed at the centre of the bin.
765 /// if option "I" is specified (1-d histogram only), the integral of the
766 /// function in each bin is used instead of the value of the function at
767 /// the centre of the bin.
768 ///
769 /// Only bins inside the function range are recomputed.
770 ///
771 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
772 /// you should call Sumw2 before making this operation.
773 /// This is particularly important if you fit the histogram after TH1::Add
774 ///
775 /// The function return kFALSE if the Add operation failed
776 
778 {
779  if (!f1) {
780  Error("Add","Attempt to add a non-existing function");
781  return kFALSE;
782  }
783 
784  TString opt = option;
785  opt.ToLower();
786  Bool_t integral = kFALSE;
787  if (opt.Contains("i") && fDimension == 1) integral = kTRUE;
788 
789  Int_t ncellsx = GetNbinsX() + 2; // cells = normal bins + underflow bin + overflow bin
790  Int_t ncellsy = GetNbinsY() + 2;
791  Int_t ncellsz = GetNbinsZ() + 2;
792  if (fDimension < 2) ncellsy = 1;
793  if (fDimension < 3) ncellsz = 1;
794 
795  // delete buffer if it is there since it will become invalid
796  if (fBuffer) BufferEmpty(1);
797 
798  // - Add statistics
799  Double_t s1[10];
800  for (Int_t i = 0; i < 10; ++i) s1[i] = 0;
801  PutStats(s1);
802  SetMinimum();
803  SetMaximum();
804 
805  // - Loop on bins (including underflows/overflows)
806  Int_t bin, binx, biny, binz;
807  Double_t cu=0;
808  Double_t xx[3];
809  Double_t *params = 0;
810  f1->InitArgs(xx,params);
811  for (binz = 0; binz < ncellsz; ++binz) {
812  xx[2] = fZaxis.GetBinCenter(binz);
813  for (biny = 0; biny < ncellsy; ++biny) {
814  xx[1] = fYaxis.GetBinCenter(biny);
815  for (binx = 0; binx < ncellsx; ++binx) {
816  xx[0] = fXaxis.GetBinCenter(binx);
817  if (!f1->IsInside(xx)) continue;
819  bin = binx + ncellsx * (biny + ncellsy * binz);
820  if (integral) {
821  cu = c1*f1->Integral(fXaxis.GetBinLowEdge(binx), fXaxis.GetBinUpEdge(binx)) / fXaxis.GetBinWidth(binx);
822  } else {
823  cu = c1*f1->EvalPar(xx);
824  }
825  if (TF1::RejectedPoint()) continue;
826  AddBinContent(bin,cu);
827  }
828  }
829  }
830 
831  return kTRUE;
832 }
833 
834 ////////////////////////////////////////////////////////////////////////////////
835 /// Performs the operation: `this = this + c1*h1`
836 /// If errors are defined (see TH1::Sumw2), errors are also recalculated.
837 ///
838 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
839 /// if not already set.
840 ///
841 /// Note also that adding histogram with labels is not supported, histogram will be
842 /// added merging them by bin number independently of the labels.
843 /// For adding histogram with labels one should use TH1::Merge
844 ///
845 /// SPECIAL CASE (Average/Efficiency histograms)
846 /// For histograms representing averages or efficiencies, one should compute the average
847 /// of the two histograms and not the sum. One can mark a histogram to be an average
848 /// histogram by setting its bit kIsAverage with
849 /// myhist.SetBit(TH1::kIsAverage);
850 /// Note that the two histograms must have their kIsAverage bit set
851 ///
852 /// IMPORTANT NOTE1: If you intend to use the errors of this histogram later
853 /// you should call Sumw2 before making this operation.
854 /// This is particularly important if you fit the histogram after TH1::Add
855 ///
856 /// IMPORTANT NOTE2: if h1 has a normalisation factor, the normalisation factor
857 /// is used , ie this = this + c1*factor*h1
858 /// Use the other TH1::Add function if you do not want this feature
859 ///
860 /// The function return kFALSE if the Add operation failed
861 
863 {
864  if (!h1) {
865  Error("Add","Attempt to add a non-existing histogram");
866  return kFALSE;
867  }
868 
869  // delete buffer if it is there since it will become invalid
870  if (fBuffer) BufferEmpty(1);
871 
872  bool useMerge = (c1 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
873  try {
874  CheckConsistency(this,h1);
875  useMerge = kFALSE;
876  } catch(DifferentNumberOfBins&) {
877  if (useMerge)
878  Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
879  else {
880  Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
881  return kFALSE;
882  }
883  } catch(DifferentAxisLimits&) {
884  if (useMerge)
885  Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
886  else
887  Warning("Add","Attempt to add histograms with different axis limits");
888  } catch(DifferentBinLimits&) {
889  if (useMerge)
890  Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
891  else
892  Warning("Add","Attempt to add histograms with different bin limits");
893  } catch(DifferentLabels&) {
894  // in case of different labels -
895  if (useMerge)
896  Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
897  else
898  Info("Warning","Attempt to add histograms with different labels");
899  }
900 
901  if (useMerge) {
902  TList l;
903  l.Add(const_cast<TH1*>(h1));
904  auto iret = Merge(&l);
905  return (iret >= 0);
906  }
907 
908  // Create Sumw2 if h1 has Sumw2 set
909  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
910 
911  // - Add statistics
912  Double_t entries = TMath::Abs( GetEntries() + c1 * h1->GetEntries() );
913 
914  // statistics can be preserved only in case of positive coefficients
915  // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
916  Bool_t resetStats = (c1 < 0);
917  Double_t s1[kNstat] = {0};
918  Double_t s2[kNstat] = {0};
919  if (!resetStats) {
920  // need to initialize to zero s1 and s2 since
921  // GetStats fills only used elements depending on dimension and type
922  GetStats(s1);
923  h1->GetStats(s2);
924  }
925 
926  SetMinimum();
927  SetMaximum();
928 
929  // - Loop on bins (including underflows/overflows)
930  Double_t factor = 1;
931  if (h1->GetNormFactor() != 0) factor = h1->GetNormFactor()/h1->GetSumOfWeights();;
932  Double_t c1sq = c1 * c1;
933  Double_t factsq = factor * factor;
934 
935  for (Int_t bin = 0; bin < fNcells; ++bin) {
936  //special case where histograms have the kIsAverage bit set
937  if (this->TestBit(kIsAverage) && h1->TestBit(kIsAverage)) {
938  Double_t y1 = h1->RetrieveBinContent(bin);
939  Double_t y2 = this->RetrieveBinContent(bin);
940  Double_t e1sq = h1->GetBinErrorSqUnchecked(bin);
941  Double_t e2sq = this->GetBinErrorSqUnchecked(bin);
942  Double_t w1 = 1., w2 = 1.;
943 
944  // consider all special cases when bin errors are zero
945  // see http://root-forum.cern.ch/viewtopic.php?f=3&t=13299
946  if (e1sq) w1 = 1. / e1sq;
947  else if (h1->fSumw2.fN) {
948  w1 = 1.E200; // use an arbitrary huge value
949  if (y1 == 0) {
950  // use an estimated error from the global histogram scale
951  double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
952  w1 = 1./(sf*sf);
953  }
954  }
955  if (e2sq) w2 = 1. / e2sq;
956  else if (fSumw2.fN) {
957  w2 = 1.E200; // use an arbitrary huge value
958  if (y2 == 0) {
959  // use an estimated error from the global histogram scale
960  double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
961  w2 = 1./(sf*sf);
962  }
963  }
964 
965  double y = (w1*y1 + w2*y2)/(w1 + w2);
966  UpdateBinContent(bin, y);
967  if (fSumw2.fN) {
968  double err2 = 1./(w1 + w2);
969  if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
970  fSumw2.fArray[bin] = err2;
971  }
972  } else { // normal case of addition between histograms
973  AddBinContent(bin, c1 * factor * h1->RetrieveBinContent(bin));
974  if (fSumw2.fN) fSumw2.fArray[bin] += c1sq * factsq * h1->GetBinErrorSqUnchecked(bin);
975  }
976  }
977 
978  // update statistics (do here to avoid changes by SetBinContent)
979  if (resetStats) {
980  // statistics need to be reset in case coefficient are negative
981  ResetStats();
982  }
983  else {
984  for (Int_t i=0;i<kNstat;i++) {
985  if (i == 1) s1[i] += c1*c1*s2[i];
986  else s1[i] += c1*s2[i];
987  }
988  PutStats(s1);
989  SetEntries(entries);
990  }
991  return kTRUE;
992 }
993 
994 ////////////////////////////////////////////////////////////////////////////////
995 /// Replace contents of this histogram by the addition of h1 and h2.
996 ///
997 /// `this = c1*h1 + c2*h2`
998 /// if errors are defined (see TH1::Sumw2), errors are also recalculated
999 ///
1000 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
1001 /// if not already set.
1002 ///
1003 /// Note also that adding histogram with labels is not supported, histogram will be
1004 /// added merging them by bin number independently of the labels.
1005 /// For adding histogram ith labels one should use TH1::Merge
1006 ///
1007 /// SPECIAL CASE (Average/Efficiency histograms)
1008 /// For histograms representing averages or efficiencies, one should compute the average
1009 /// of the two histograms and not the sum. One can mark a histogram to be an average
1010 /// histogram by setting its bit kIsAverage with
1011 /// myhist.SetBit(TH1::kIsAverage);
1012 /// Note that the two histograms must have their kIsAverage bit set
1013 ///
1014 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
1015 /// you should call Sumw2 before making this operation.
1016 /// This is particularly important if you fit the histogram after TH1::Add
1017 ///
1018 /// ANOTHER SPECIAL CASE : h1 = h2 and c2 < 0
1019 /// do a scaling this = c1 * h1 / (bin Volume)
1020 ///
1021 /// The function returns kFALSE if the Add operation failed
1022 
1024 {
1025 
1026  if (!h1 || !h2) {
1027  Error("Add","Attempt to add a non-existing histogram");
1028  return kFALSE;
1029  }
1030 
1031  // delete buffer if it is there since it will become invalid
1032  if (fBuffer) BufferEmpty(1);
1033 
1034  Bool_t normWidth = kFALSE;
1035  if (h1 == h2 && c2 < 0) {c2 = 0; normWidth = kTRUE;}
1036 
1037  if (h1 != h2) {
1038  bool useMerge = (c1 == 1. && c2 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
1039 
1040  try {
1041  CheckConsistency(h1,h2);
1042  CheckConsistency(this,h1);
1043  useMerge = kFALSE;
1044  } catch(DifferentNumberOfBins&) {
1045  if (useMerge)
1046  Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
1047  else {
1048  Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
1049  return kFALSE;
1050  }
1051  } catch(DifferentAxisLimits&) {
1052  if (useMerge)
1053  Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
1054  else
1055  Warning("Add","Attempt to add histograms with different axis limits");
1056  } catch(DifferentBinLimits&) {
1057  if (useMerge)
1058  Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
1059  else
1060  Warning("Add","Attempt to add histograms with different bin limits");
1061  } catch(DifferentLabels&) {
1062  // in case of different labels -
1063  if (useMerge)
1064  Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
1065  else
1066  Info("Warning","Attempt to add histograms with different labels");
1067  }
1068 
1069  if (useMerge) {
1070  TList l;
1071  // why TList takes non-const pointers ????
1072  l.Add(const_cast<TH1*>(h1));
1073  l.Add(const_cast<TH1*>(h2));
1074  Reset("ICE");
1075  auto iret = Merge(&l);
1076  return (iret >= 0);
1077  }
1078  }
1079 
1080  // Create Sumw2 if h1 or h2 have Sumw2 set
1081  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
1082 
1083  // - Add statistics
1084  Double_t nEntries = TMath::Abs( c1*h1->GetEntries() + c2*h2->GetEntries() );
1085 
1086  // TODO remove
1087  // statistics can be preserved only in case of positive coefficients
1088  // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
1089  // also in case of scaling with the width we cannot preserve the statistics
1090  Double_t s1[kNstat] = {0};
1091  Double_t s2[kNstat] = {0};
1092  Double_t s3[kNstat];
1093 
1094 
1095  Bool_t resetStats = (c1*c2 < 0) || normWidth;
1096  if (!resetStats) {
1097  // need to initialize to zero s1 and s2 since
1098  // GetStats fills only used elements depending on dimension and type
1099  h1->GetStats(s1);
1100  h2->GetStats(s2);
1101  for (Int_t i=0;i<kNstat;i++) {
1102  if (i == 1) s3[i] = c1*c1*s1[i] + c2*c2*s2[i];
1103  //else s3[i] = TMath::Abs(c1)*s1[i] + TMath::Abs(c2)*s2[i];
1104  else s3[i] = c1*s1[i] + c2*s2[i];
1105  }
1106  }
1107 
1108  SetMinimum();
1109  SetMaximum();
1110 
1111  if (normWidth) { // DEPRECATED CASE: belongs to fitting / drawing modules
1112 
1113  Int_t nbinsx = GetNbinsX() + 2; // normal bins + underflow, overflow
1114  Int_t nbinsy = GetNbinsY() + 2;
1115  Int_t nbinsz = GetNbinsZ() + 2;
1116 
1117  if (fDimension < 2) nbinsy = 1;
1118  if (fDimension < 3) nbinsz = 1;
1119 
1120  Int_t bin, binx, biny, binz;
1121  for (binz = 0; binz < nbinsz; ++binz) {
1122  Double_t wz = h1->GetZaxis()->GetBinWidth(binz);
1123  for (biny = 0; biny < nbinsy; ++biny) {
1124  Double_t wy = h1->GetYaxis()->GetBinWidth(biny);
1125  for (binx = 0; binx < nbinsx; ++binx) {
1126  Double_t wx = h1->GetXaxis()->GetBinWidth(binx);
1127  bin = GetBin(binx, biny, binz);
1128  Double_t w = wx*wy*wz;
1129  UpdateBinContent(bin, c1 * h1->RetrieveBinContent(bin) / w);
1130  if (fSumw2.fN) {
1131  Double_t e1 = h1->GetBinError(bin)/w;
1132  fSumw2.fArray[bin] = c1*c1*e1*e1;
1133  }
1134  }
1135  }
1136  }
1137  } else if (h1->TestBit(kIsAverage) && h2->TestBit(kIsAverage)) {
1138  for (Int_t i = 0; i < fNcells; ++i) { // loop on cells (bins including underflow / overflow)
1139  // special case where histograms have the kIsAverage bit set
1140  Double_t y1 = h1->RetrieveBinContent(i);
1141  Double_t y2 = h2->RetrieveBinContent(i);
1142  Double_t e1sq = h1->GetBinErrorSqUnchecked(i);
1143  Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
1144  Double_t w1 = 1., w2 = 1.;
1145 
1146  // consider all special cases when bin errors are zero
1147  // see http://root-forum.cern.ch/viewtopic.php?f=3&t=13299
1148  if (e1sq) w1 = 1./ e1sq;
1149  else if (h1->fSumw2.fN) {
1150  w1 = 1.E200; // use an arbitrary huge value
1151  if (y1 == 0 ) { // use an estimated error from the global histogram scale
1152  double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
1153  w1 = 1./(sf*sf);
1154  }
1155  }
1156  if (e2sq) w2 = 1./ e2sq;
1157  else if (h2->fSumw2.fN) {
1158  w2 = 1.E200; // use an arbitrary huge value
1159  if (y2 == 0) { // use an estimated error from the global histogram scale
1160  double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
1161  w2 = 1./(sf*sf);
1162  }
1163  }
1164 
1165  double y = (w1*y1 + w2*y2)/(w1 + w2);
1166  UpdateBinContent(i, y);
1167  if (fSumw2.fN) {
1168  double err2 = 1./(w1 + w2);
1169  if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
1170  fSumw2.fArray[i] = err2;
1171  }
1172  }
1173  } else { // case of simple histogram addition
1174  Double_t c1sq = c1 * c1;
1175  Double_t c2sq = c2 * c2;
1176  for (Int_t i = 0; i < fNcells; ++i) { // Loop on cells (bins including underflows/overflows)
1177  UpdateBinContent(i, c1 * h1->RetrieveBinContent(i) + c2 * h2->RetrieveBinContent(i));
1178  if (fSumw2.fN) {
1179  fSumw2.fArray[i] = c1sq * h1->GetBinErrorSqUnchecked(i) + c2sq * h2->GetBinErrorSqUnchecked(i);
1180  }
1181  }
1182  }
1183 
1184  if (resetStats) {
1185  // statistics need to be reset in case coefficient are negative
1186  ResetStats();
1187  }
1188  else {
1189  // update statistics (do here to avoid changes by SetBinContent) FIXME remove???
1190  PutStats(s3);
1191  SetEntries(nEntries);
1192  }
1193 
1194  return kTRUE;
1195 }
1196 
1197 ////////////////////////////////////////////////////////////////////////////////
1198 /// Increment bin content by 1.
1199 
1201 {
1202  AbstractMethod("AddBinContent");
1203 }
1204 
1205 ////////////////////////////////////////////////////////////////////////////////
1206 /// Increment bin content by a weight w.
1207 
1209 {
1210  AbstractMethod("AddBinContent");
1211 }
1212 
1213 ////////////////////////////////////////////////////////////////////////////////
1214 /// Sets the flag controlling the automatic add of histograms in memory
1215 ///
1216 /// By default (fAddDirectory = kTRUE), histograms are automatically added
1217 /// to the list of objects in memory.
1218 /// Note that one histogram can be removed from its support directory
1219 /// by calling h->SetDirectory(0) or h->SetDirectory(dir) to add it
1220 /// to the list of objects in the directory dir.
1221 ///
1222 /// NOTE that this is a static function. To call it, use;
1223 /// TH1::AddDirectory
1224 
1226 {
1227  fgAddDirectory = add;
1228 }
1229 
1230 ////////////////////////////////////////////////////////////////////////////////
1231 /// Auxilliary function to get the power of 2 next (larger) or previous (smaller)
1232 /// a given x
1233 ///
1234 /// next = kTRUE : next larger
1235 /// next = kFALSE : previous smaller
1236 ///
1237 /// Used by the autobin power of 2 algorithm
1238 
1240 {
1241  Int_t nn;
1242  Double_t f2 = std::frexp(x, &nn);
1243  return ((next && x > 0.) || (!next && x <= 0.)) ? std::ldexp(std::copysign(1., f2), nn)
1244  : std::ldexp(std::copysign(1., f2), --nn);
1245 }
1246 
1247 ////////////////////////////////////////////////////////////////////////////////
1248 /// Auxilliary function to get the next power of 2 integer value larger then n
1249 ///
1250 /// Used by the autobin power of 2 algorithm
1251 
1253 {
1254  Int_t nn;
1255  Double_t f2 = std::frexp(n, &nn);
1256  if (TMath::Abs(f2 - .5) > 0.001)
1257  return (Int_t)std::ldexp(1., nn);
1258  return n;
1259 }
1260 
1261 ////////////////////////////////////////////////////////////////////////////////
1262 /// Buffer-based estimate of the histogram range using the power of 2 algorithm.
1263 ///
1264 /// Used by the autobin power of 2 algorithm.
1265 ///
1266 /// Works on arguments (min and max from fBuffer) and internal inputs: fXmin,
1267 /// fXmax, NBinsX (from fXaxis), ...
1268 /// Result save internally in fXaxis.
1269 ///
1270 /// Overloaded by TH2 and TH3.
1271 ///
1272 /// Return -1 if internal inputs are incosistent, 0 otherwise.
1273 ///
1274 
1276 {
1277  // We need meaningful raw limits
1278  if (xmi >= xma)
1279  return -1;
1280 
1282  Double_t xhmi = fXaxis.GetXmin();
1283  Double_t xhma = fXaxis.GetXmax();
1284 
1285  // Now adjust
1286  if (TMath::Abs(xhma) > TMath::Abs(xhmi)) {
1287  // Start from the upper limit
1288  xhma = TH1::AutoP2GetPower2(xhma);
1289  xhmi = xhma - TH1::AutoP2GetPower2(xhma - xhmi);
1290  } else {
1291  // Start from the lower limit
1292  xhmi = TH1::AutoP2GetPower2(xhmi, kFALSE);
1293  xhma = xhmi + TH1::AutoP2GetPower2(xhma - xhmi);
1294  }
1295 
1296  // Round the bins to the next power of 2; take into account the possible inflation
1297  // of the range
1298  Double_t rr = (xhma - xhmi) / (xma - xmi);
1299  Int_t nb = TH1::AutoP2GetBins((Int_t)(rr * GetNbinsX()));
1300 
1301  // Adjust using the same bin width and offsets
1302  Double_t bw = (xhma - xhmi) / nb;
1303  // Bins to left free on each side
1304  Double_t autoside = gEnv->GetValue("Hist.Binning.Auto.Side", 0.05);
1305  Int_t nbside = (Int_t)(nb * autoside);
1306 
1307  // Side up
1308  Int_t nbup = (xhma - xma) / bw;
1309  if (nbup % 2 != 0)
1310  nbup++; // Must be even
1311  if (nbup != nbside) {
1312  // Accounts also for both case: larger or smaller
1313  xhma -= bw * (nbup - nbside);
1314  nb -= (nbup - nbside);
1315  }
1316 
1317  // Side low
1318  Int_t nblw = (xmi - xhmi) / bw;
1319  if (nblw % 2 != 0)
1320  nblw++; // Must be even
1321  if (nblw != nbside) {
1322  // Accounts also for both case: larger or smaller
1323  xhmi += bw * (nblw - nbside);
1324  nb -= (nblw - nbside);
1325  }
1326 
1327  // Set everything and project
1328  SetBins(nb, xhmi, xhma);
1329 
1330  // Done
1331  return 0;
1332 }
1333 
1334 /// Fill histogram with all entries in the buffer.
1335 ///
1336 /// - action = -1 histogram is reset and refilled from the buffer (called by THistPainter::Paint)
1337 /// - action = 0 histogram is reset and filled from the buffer. When the histogram is filled from the
1338 /// buffer the value fBuffer[0] is set to a negative number (= - number of entries)
1339 /// When calling with action == 0 the histogram is NOT refilled when fBuffer[0] is < 0
1340 /// While when calling with action = -1 the histogram is reset and ALWAYS refilled independently if
1341 /// the histogram was filled before. This is needed when drawing the histogram
1342 /// - action = 1 histogram is filled and buffer is deleted
1343 /// The buffer is automatically deleted when filling the histogram and the entries is
1344 /// larger than the buffer size
1345 
1347 {
1348  // do we need to compute the bin size?
1349  if (!fBuffer) return 0;
1350  Int_t nbentries = (Int_t)fBuffer[0];
1351 
1352  // nbentries correspond to the number of entries of histogram
1353 
1354  if (nbentries == 0) {
1355  // if action is 1 we delete the buffer
1356  // this will avoid infinite recursion
1357  if (action > 0) {
1358  delete [] fBuffer;
1359  fBuffer = 0;
1360  fBufferSize = 0;
1361  }
1362  return 0;
1363  }
1364  if (nbentries < 0 && action == 0) return 0; // case histogram has been already filled from the buffer
1365 
1366  Double_t *buffer = fBuffer;
1367  if (nbentries < 0) {
1368  nbentries = -nbentries;
1369  // a reset might call BufferEmpty() giving an infinite recursion
1370  // Protect it by setting fBuffer = 0
1371  fBuffer=0;
1372  //do not reset the list of functions
1373  Reset("ICES");
1374  fBuffer = buffer;
1375  }
1376  if (CanExtendAllAxes() || (fXaxis.GetXmax() <= fXaxis.GetXmin())) {
1377  //find min, max of entries in buffer
1378  Double_t xmin = fBuffer[2];
1379  Double_t xmax = xmin;
1380  for (Int_t i=1;i<nbentries;i++) {
1381  Double_t x = fBuffer[2*i+2];
1382  if (x < xmin) xmin = x;
1383  if (x > xmax) xmax = x;
1384  }
1385  if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
1386  Int_t rc = -1;
1387  if (TestBit(TH1::kAutoBinPTwo)) {
1388  if ((rc = AutoP2FindLimits(xmin, xmax)) < 0)
1389  Warning("BufferEmpty",
1390  "incosistency found by power-of-2 autobin algorithm: fallback to standard method");
1391  }
1392  if (rc < 0)
1393  THLimitsFinder::GetLimitsFinder()->FindGoodLimits(this, xmin, xmax);
1394  } else {
1395  fBuffer = 0;
1396  Int_t keep = fBufferSize; fBufferSize = 0;
1397  if (xmin < fXaxis.GetXmin()) ExtendAxis(xmin, &fXaxis);
1398  if (xmax >= fXaxis.GetXmax()) ExtendAxis(xmax, &fXaxis);
1399  fBuffer = buffer;
1400  fBufferSize = keep;
1401  }
1402  }
1403 
1404  // call DoFillN which will not put entries in the buffer as FillN does
1405  // set fBuffer to zero to avoid re-emptying the buffer from functions called
1406  // by DoFillN (e.g Sumw2)
1407  buffer = fBuffer; fBuffer = 0;
1408  DoFillN(nbentries,&buffer[2],&buffer[1],2);
1409  fBuffer = buffer;
1410 
1411  // if action == 1 - delete the buffer
1412  if (action > 0) {
1413  delete [] fBuffer;
1414  fBuffer = 0;
1415  fBufferSize = 0;
1416  } else {
1417  // if number of entries is consistent with buffer - set it negative to avoid
1418  // refilling the histogram every time BufferEmpty(0) is called
1419  // In case it is not consistent, by setting fBuffer[0]=0 is like resetting the buffer
1420  // (it will not be used anymore the next time BufferEmpty is called)
1421  if (nbentries == (Int_t)fEntries)
1422  fBuffer[0] = -nbentries;
1423  else
1424  fBuffer[0] = 0;
1425  }
1426  return nbentries;
1427 }
1428 
1429 ////////////////////////////////////////////////////////////////////////////////
1430 /// accumulate arguments in buffer. When buffer is full, empty the buffer
1431 ///
1432 /// - `fBuffer[0]` = number of entries in buffer
1433 /// - `fBuffer[1]` = w of first entry
1434 /// - `fBuffer[2]` = x of first entry
1435 
1437 {
1438  if (!fBuffer) return -2;
1439  Int_t nbentries = (Int_t)fBuffer[0];
1440 
1441 
1442  if (nbentries < 0) {
1443  // reset nbentries to a positive value so next time BufferEmpty() is called
1444  // the histogram will be refilled
1445  nbentries = -nbentries;
1446  fBuffer[0] = nbentries;
1447  if (fEntries > 0) {
1448  // set fBuffer to zero to avoid calling BufferEmpty in Reset
1449  Double_t *buffer = fBuffer; fBuffer=0;
1450  Reset("ICES"); // do not reset list of functions
1451  fBuffer = buffer;
1452  }
1453  }
1454  if (2*nbentries+2 >= fBufferSize) {
1455  BufferEmpty(1);
1456  if (!fBuffer)
1457  // to avoid infinite recursion Fill->BufferFill->Fill
1458  return Fill(x,w);
1459  // this cannot happen
1460  R__ASSERT(0);
1461  }
1462  fBuffer[2*nbentries+1] = w;
1463  fBuffer[2*nbentries+2] = x;
1464  fBuffer[0] += 1;
1465  return -2;
1466 }
1467 
1468 ////////////////////////////////////////////////////////////////////////////////
1469 /// Check bin limits.
1470 
1471 bool TH1::CheckBinLimits(const TAxis* a1, const TAxis * a2)
1472 {
1473  const TArrayD * h1Array = a1->GetXbins();
1474  const TArrayD * h2Array = a2->GetXbins();
1475  Int_t fN = h1Array->fN;
1476  if ( fN != 0 ) {
1477  if ( h2Array->fN != fN ) {
1478  throw DifferentBinLimits();
1479  return false;
1480  }
1481  else {
1482  for ( int i = 0; i < fN; ++i ) {
1483  if ( ! TMath::AreEqualRel( h1Array->GetAt(i), h2Array->GetAt(i), 1E-10 ) ) {
1484  throw DifferentBinLimits();
1485  return false;
1486  }
1487  }
1488  }
1489  }
1490 
1491  return true;
1492 }
1493 
1494 ////////////////////////////////////////////////////////////////////////////////
1495 /// Check that axis have same labels.
1496 
1497 bool TH1::CheckBinLabels(const TAxis* a1, const TAxis * a2)
1498 {
1499  THashList *l1 = a1->GetLabels();
1500  THashList *l2 = a2->GetLabels();
1501 
1502  if (!l1 && !l2 )
1503  return true;
1504  if (!l1 || !l2 ) {
1505  throw DifferentLabels();
1506  return false;
1507  }
1508  // check now labels sizes are the same
1509  if (l1->GetSize() != l2->GetSize() ) {
1510  throw DifferentLabels();
1511  return false;
1512  }
1513  for (int i = 1; i <= a1->GetNbins(); ++i) {
1514  TString label1 = a1->GetBinLabel(i);
1515  TString label2 = a2->GetBinLabel(i);
1516  if (label1 != label2) {
1517  throw DifferentLabels();
1518  return false;
1519  }
1520  }
1521 
1522  return true;
1523 }
1524 
1525 ////////////////////////////////////////////////////////////////////////////////
1526 /// Check that the axis limits of the histograms are the same.
1527 /// If a first and last bin is passed the axis is compared between the given range
1528 
1529 bool TH1::CheckAxisLimits(const TAxis *a1, const TAxis *a2 )
1530 {
1531  if ( ! TMath::AreEqualRel(a1->GetXmin(), a2->GetXmin(),1.E-12) ||
1532  ! TMath::AreEqualRel(a1->GetXmax(), a2->GetXmax(),1.E-12) ) {
1533  throw DifferentAxisLimits();
1534  return false;
1535  }
1536  return true;
1537 }
1538 
1539 ////////////////////////////////////////////////////////////////////////////////
1540 /// Check that the axis are the same
1541 
1542 bool TH1::CheckEqualAxes(const TAxis *a1, const TAxis *a2 )
1543 {
1544  if (a1->GetNbins() != a2->GetNbins() ) {
1545  //throw DifferentNumberOfBins();
1546  ::Info("CheckEqualAxes","Axes have different number of bins : nbin1 = %d nbin2 = %d",a1->GetNbins(),a2->GetNbins() );
1547  return false;
1548  }
1549  try {
1550  CheckAxisLimits(a1,a2);
1551  } catch (DifferentAxisLimits&) {
1552  ::Info("CheckEqualAxes","Axes have different limits");
1553  return false;
1554  }
1555  try {
1556  CheckBinLimits(a1,a2);
1557  } catch (DifferentBinLimits&) {
1558  ::Info("CheckEqualAxes","Axes have different bin limits");
1559  return false;
1560  }
1561 
1562  // check labels
1563  try {
1564  CheckBinLabels(a1,a2);
1565  } catch (DifferentLabels&) {
1566  ::Info("CheckEqualAxes","Axes have different labels");
1567  return false;
1568  }
1569 
1570  return true;
1571 }
1572 
1573 ////////////////////////////////////////////////////////////////////////////////
1574 /// Check that two sub axis are the same.
1575 /// The limits are defined by first bin and last bin
1576 /// N.B. no check is done in this case for variable bins
1577 
1578 bool TH1::CheckConsistentSubAxes(const TAxis *a1, Int_t firstBin1, Int_t lastBin1, const TAxis * a2, Int_t firstBin2, Int_t lastBin2 )
1579 {
1580  // By default is assumed that no bins are given for the second axis
1581  Int_t nbins1 = lastBin1-firstBin1 + 1;
1582  Double_t xmin1 = a1->GetBinLowEdge(firstBin1);
1583  Double_t xmax1 = a1->GetBinUpEdge(lastBin1);
1584 
1585  Int_t nbins2 = a2->GetNbins();
1586  Double_t xmin2 = a2->GetXmin();
1587  Double_t xmax2 = a2->GetXmax();
1588 
1589  if (firstBin2 < lastBin2) {
1590  // in this case assume no bins are given for the second axis
1591  nbins2 = lastBin1-firstBin1 + 1;
1592  xmin2 = a1->GetBinLowEdge(firstBin1);
1593  xmax2 = a1->GetBinUpEdge(lastBin1);
1594  }
1595 
1596  if (nbins1 != nbins2 ) {
1597  ::Info("CheckConsistentSubAxes","Axes have different number of bins");
1598  return false;
1599  }
1600 
1601  if ( ! TMath::AreEqualRel(xmin1,xmin2,1.E-12) ||
1602  ! TMath::AreEqualRel(xmax1,xmax2,1.E-12) ) {
1603  ::Info("CheckConsistentSubAxes","Axes have different limits");
1604  return false;
1605  }
1606 
1607  return true;
1608 }
1609 
1610 ////////////////////////////////////////////////////////////////////////////////
1611 /// Check histogram compatibility.
1612 
1613 bool TH1::CheckConsistency(const TH1* h1, const TH1* h2)
1614 {
1615  if (h1 == h2) return true;
1616 
1617  if (h1->GetDimension() != h2->GetDimension() ) {
1618  throw DifferentDimension();
1619  return false;
1620  }
1621  Int_t dim = h1->GetDimension();
1622 
1623  // returns kTRUE if number of bins and bin limits are identical
1624  Int_t nbinsx = h1->GetNbinsX();
1625  Int_t nbinsy = h1->GetNbinsY();
1626  Int_t nbinsz = h1->GetNbinsZ();
1627 
1628  // Check whether the histograms have the same number of bins.
1629  if (nbinsx != h2->GetNbinsX() ||
1630  (dim > 1 && nbinsy != h2->GetNbinsY()) ||
1631  (dim > 2 && nbinsz != h2->GetNbinsZ()) ) {
1632  throw DifferentNumberOfBins();
1633  return false;
1634  }
1635 
1636  bool ret = true;
1637 
1638  // check axis limits
1639  ret &= CheckAxisLimits(h1->GetXaxis(), h2->GetXaxis());
1640  if (dim > 1) ret &= CheckAxisLimits(h1->GetYaxis(), h2->GetYaxis());
1641  if (dim > 2) ret &= CheckAxisLimits(h1->GetZaxis(), h2->GetZaxis());
1642 
1643  // check bin limits
1644  ret &= CheckBinLimits(h1->GetXaxis(), h2->GetXaxis());
1645  if (dim > 1) ret &= CheckBinLimits(h1->GetYaxis(), h2->GetYaxis());
1646  if (dim > 2) ret &= CheckBinLimits(h1->GetZaxis(), h2->GetZaxis());
1647 
1648  // check labels if histograms are both not empty
1649  if ( (h1->fTsumw != 0 || h1->GetEntries() != 0) &&
1650  (h2->fTsumw != 0 || h2->GetEntries() != 0) ) {
1651  ret &= CheckBinLabels(h1->GetXaxis(), h2->GetXaxis());
1652  if (dim > 1) ret &= CheckBinLabels(h1->GetYaxis(), h2->GetYaxis());
1653  if (dim > 2) ret &= CheckBinLabels(h1->GetZaxis(), h2->GetZaxis());
1654  }
1655 
1656  return ret;
1657 }
1658 
1659 ////////////////////////////////////////////////////////////////////////////////
1660 /// \f$ \chi^{2} \f$ test for comparing weighted and unweighted histograms
1661 ///
1662 /// Function: Returns p-value. Other return values are specified by the 3rd parameter
1663 ///
1664 /// \param[in] h2 the second histogram
1665 /// \param[in] option
1666 /// - "UU" = experiment experiment comparison (unweighted-unweighted)
1667 /// - "UW" = experiment MC comparison (unweighted-weighted). Note that
1668 /// the first histogram should be unweighted
1669 /// - "WW" = MC MC comparison (weighted-weighted)
1670 /// - "NORM" = to be used when one or both of the histograms is scaled
1671 /// but the histogram originally was unweighted
1672 /// - by default underflows and overflows are not included:
1673 /// * "OF" = overflows included
1674 /// * "UF" = underflows included
1675 /// - "P" = print chi2, ndf, p_value, igood
1676 /// - "CHI2" = returns chi2 instead of p-value
1677 /// - "CHI2/NDF" = returns \f$ \chi^{2} \f$/ndf
1678 /// \param[in] res not empty - computes normalized residuals and returns them in this array
1679 ///
1680 /// The current implementation is based on the papers \f$ \chi^{2} \f$ test for comparison
1681 /// of weighted and unweighted histograms" in Proceedings of PHYSTAT05 and
1682 /// "Comparison weighted and unweighted histograms", arXiv:physics/0605123
1683 /// by N.Gagunashvili. This function has been implemented by Daniel Haertl in August 2006.
1684 ///
1685 /// #### Introduction:
1686 ///
1687 /// A frequently used technique in data analysis is the comparison of
1688 /// histograms. First suggested by Pearson [1] the \f$ \chi^{2} \f$ test of
1689 /// homogeneity is used widely for comparing usual (unweighted) histograms.
1690 /// This paper describes the implementation modified \f$ \chi^{2} \f$ tests
1691 /// for comparison of weighted and unweighted histograms and two weighted
1692 /// histograms [2] as well as usual Pearson's \f$ \chi^{2} \f$ test for
1693 /// comparison two usual (unweighted) histograms.
1694 ///
1695 /// #### Overview:
1696 ///
1697 /// Comparison of two histograms expect hypotheses that two histograms
1698 /// represent identical distributions. To make a decision p-value should
1699 /// be calculated. The hypotheses of identity is rejected if the p-value is
1700 /// lower then some significance level. Traditionally significance levels
1701 /// 0.1, 0.05 and 0.01 are used. The comparison procedure should include an
1702 /// analysis of the residuals which is often helpful in identifying the
1703 /// bins of histograms responsible for a significant overall \f$ \chi^{2} \f$ value.
1704 /// Residuals are the difference between bin contents and expected bin
1705 /// contents. Most convenient for analysis are the normalized residuals. If
1706 /// hypotheses of identity are valid then normalized residuals are
1707 /// approximately independent and identically distributed random variables
1708 /// having N(0,1) distribution. Analysis of residuals expect test of above
1709 /// mentioned properties of residuals. Notice that indirectly the analysis
1710 /// of residuals increase the power of \f$ \chi^{2} \f$ test.
1711 ///
1712 /// #### Methods of comparison:
1713 ///
1714 /// \f$ \chi^{2} \f$ test for comparison two (unweighted) histograms:
1715 /// Let us consider two histograms with the same binning and the number
1716 /// of bins equal to r. Let us denote the number of events in the ith bin
1717 /// in the first histogram as ni and as mi in the second one. The total
1718 /// number of events in the first histogram is equal to:
1719 /// \f[
1720 /// N = \sum_{i=1}^{r} n_{i}
1721 /// \f]
1722 /// and
1723 /// \f[
1724 /// M = \sum_{i=1}^{r} m_{i}
1725 /// \f]
1726 /// in the second histogram. The hypothesis of identity (homogeneity) [3]
1727 /// is that the two histograms represent random values with identical
1728 /// distributions. It is equivalent that there exist r constants p1,...,pr,
1729 /// such that
1730 /// \f[
1731 ///\sum_{i=1}^{r} p_{i}=1
1732 /// \f]
1733 /// and the probability of belonging to the ith bin for some measured value
1734 /// in both experiments is equal to pi. The number of events in the ith
1735 /// bin is a random variable with a distribution approximated by a Poisson
1736 /// probability distribution
1737 /// \f[
1738 ///\frac{e^{-Np_{i}}(Np_{i})^{n_{i}}}{n_{i}!}
1739 /// \f]
1740 ///for the first histogram and with distribution
1741 /// \f[
1742 ///\frac{e^{-Mp_{i}}(Mp_{i})^{m_{i}}}{m_{i}!}
1743 /// \f]
1744 /// for the second histogram. If the hypothesis of homogeneity is valid,
1745 /// then the maximum likelihood estimator of pi, i=1,...,r, is
1746 /// \f[
1747 ///\hat{p}_{i}= \frac{n_{i}+m_{i}}{N+M}
1748 /// \f]
1749 /// and then
1750 /// \f[
1751 /// 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}}
1752 /// \f]
1753 /// has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [3].
1754 /// The comparison procedure can include an analysis of the residuals which
1755 /// is often helpful in identifying the bins of histograms responsible for
1756 /// a significant overall \f$ \chi^{2} \f$ value. Most convenient for
1757 /// analysis are the adjusted (normalized) residuals [4]
1758 /// \f[
1759 /// 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))}}
1760 /// \f]
1761 /// If hypotheses of homogeneity are valid then residuals ri are
1762 /// approximately independent and identically distributed random variables
1763 /// having N(0,1) distribution. The application of the \f$ \chi^{2} \f$ test has
1764 /// restrictions related to the value of the expected frequencies Npi,
1765 /// Mpi, i=1,...,r. A conservative rule formulated in [5] is that all the
1766 /// expectations must be 1 or greater for both histograms. In practical
1767 /// cases when expected frequencies are not known the estimated expected
1768 /// frequencies \f$ M\hat{p}_{i}, N\hat{p}_{i}, i=1,...,r \f$ can be used.
1769 ///
1770 /// #### Unweighted and weighted histograms comparison:
1771 ///
1772 /// A simple modification of the ideas described above can be used for the
1773 /// comparison of the usual (unweighted) and weighted histograms. Let us
1774 /// denote the number of events in the ith bin in the unweighted
1775 /// histogram as ni and the common weight of events in the ith bin of the
1776 /// weighted histogram as wi. The total number of events in the
1777 /// unweighted histogram is equal to
1778 ///\f[
1779 /// N = \sum_{i=1}^{r} n_{i}
1780 ///\f]
1781 /// and the total weight of events in the weighted histogram is equal to
1782 ///\f[
1783 /// W = \sum_{i=1}^{r} w_{i}
1784 ///\f]
1785 /// Let us formulate the hypothesis of identity of an unweighted histogram
1786 /// to a weighted histogram so that there exist r constants p1,...,pr, such
1787 /// that
1788 ///\f[
1789 /// \sum_{i=1}^{r} p_{i} = 1
1790 ///\f]
1791 /// for the unweighted histogram. The weight wi is a random variable with a
1792 /// distribution approximated by the normal probability distribution
1793 /// \f$ N(Wp_{i},\sigma_{i}^{2}) \f$ where \f$ \sigma_{i}^{2} \f$ is the variance of the weight wi.
1794 /// If we replace the variance \f$ \sigma_{i}^{2} \f$
1795 /// with estimate \f$ s_{i}^{2} \f$ (sum of squares of weights of
1796 /// events in the ith bin) and the hypothesis of identity is valid, then the
1797 /// maximum likelihood estimator of pi,i=1,...,r, is
1798 ///\f[
1799 /// \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}}
1800 ///\f]
1801 /// We may then use the test statistic
1802 ///\f[
1803 /// 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}}
1804 ///\f]
1805 /// and it has approximately a \f$ \sigma^{2}_{(r-1)} \f$ distribution [2]. This test, as well
1806 /// as the original one [3], has a restriction on the expected frequencies. The
1807 /// expected frequencies recommended for the weighted histogram is more than 25.
1808 /// The value of the minimal expected frequency can be decreased down to 10 for
1809 /// the case when the weights of the events are close to constant. In the case
1810 /// of a weighted histogram if the number of events is unknown, then we can
1811 /// apply this recommendation for the equivalent number of events as
1812 ///\f[
1813 /// n_{i}^{equiv} = \frac{ w_{i}^{2} }{ s_{i}^{2} }
1814 ///\f]
1815 /// The minimal expected frequency for an unweighted histogram must be 1. Notice
1816 /// that any usual (unweighted) histogram can be considered as a weighted
1817 /// histogram with events that have constant weights equal to 1.
1818 /// The variance \f$ z_{i}^{2} \f$ of the difference between the weight wi
1819 /// and the estimated expectation value of the weight is approximately equal to:
1820 ///\f[
1821 /// 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}
1822 ///\f]
1823 /// The residuals
1824 ///\f[
1825 /// r_{i} = \frac{w_{i}-W\hat{p}_{i}}{z_{i}}
1826 ///\f]
1827 /// have approximately a normal distribution with mean equal to 0 and standard
1828 /// deviation equal to 1.
1829 ///
1830 /// #### Two weighted histograms comparison:
1831 ///
1832 /// Let us denote the common weight of events of the ith bin in the first
1833 /// histogram as w1i and as w2i in the second one. The total weight of events
1834 /// in the first histogram is equal to
1835 ///\f[
1836 /// W_{1} = \sum_{i=1}^{r} w_{1i}
1837 ///\f]
1838 /// and
1839 ///\f[
1840 /// W_{2} = \sum_{i=1}^{r} w_{2i}
1841 ///\f]
1842 /// in the second histogram. Let us formulate the hypothesis of identity of
1843 /// weighted histograms so that there exist r constants p1,...,pr, such that
1844 ///\f[
1845 /// \sum_{i=1}^{r} p_{i} = 1
1846 ///\f]
1847 /// and also expectation value of weight w1i equal to W1pi and expectation value
1848 /// of weight w2i equal to W2pi. Weights in both the histograms are random
1849 /// variables with distributions which can be approximated by a normal
1850 /// probability distribution \f$ N(W_{1}p_{i},\sigma_{1i}^{2}) \f$ for the first histogram
1851 /// and by a distribution \f$ N(W_{2}p_{i},\sigma_{2i}^{2}) \f$ for the second.
1852 /// Here \f$ \sigma_{1i}^{2} \f$ and \f$ \sigma_{2i}^{2} \f$ are the variances
1853 /// of w1i and w2i with estimators \f$ s_{1i}^{2} \f$ and \f$ s_{2i}^{2} \f$ respectively.
1854 /// If the hypothesis of identity is valid, then the maximum likelihood and
1855 /// Least Square Method estimator of pi,i=1,...,r, is
1856 ///\f[
1857 /// \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}}
1858 ///\f]
1859 /// We may then use the test statistic
1860 ///\f[
1861 /// 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}}
1862 ///\f]
1863 /// and it has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [2].
1864 /// The normalized or studentised residuals [6]
1865 ///\f[
1866 /// 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})}}}
1867 ///\f]
1868 /// have approximately a normal distribution with mean equal to 0 and standard
1869 /// deviation 1. A recommended minimal expected frequency is equal to 10 for
1870 /// the proposed test.
1871 ///
1872 /// #### Numerical examples:
1873 ///
1874 /// The method described herein is now illustrated with an example.
1875 /// We take a distribution
1876 ///\f[
1877 /// \phi(x) = \frac{2}{(x-10)^{2}+1} + \frac{1}{(x-14)^{2}+1} (1)
1878 ///\f]
1879 /// defined on the interval [4,16]. Events distributed according to the formula
1880 /// (1) are simulated to create the unweighted histogram. Uniformly distributed
1881 /// events are simulated for the weighted histogram with weights calculated by
1882 /// formula (1). Each histogram has the same number of bins: 20. Fig.1 shows
1883 /// the result of comparison of the unweighted histogram with 200 events
1884 /// (minimal expected frequency equal to one) and the weighted histogram with
1885 /// 500 events (minimal expected frequency equal to 25)
1886 /// Begin_Macro
1887 /// ../../../tutorials/math/chi2test.C
1888 /// End_Macro
1889 /// Fig 1. An example of comparison of the unweighted histogram with 200 events
1890 /// and the weighted histogram with 500 events:
1891 /// 1. unweighted histogram;
1892 /// 2. weighted histogram;
1893 /// 3. normalized residuals plot;
1894 /// 4. normal Q-Q plot of residuals.
1895 ///
1896 /// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1897 /// 21.09 with p-value equal to 0.33, therefore the hypothesis of identity of
1898 /// the two histograms can be accepted for 0.05 significant level. The behavior
1899 /// of the normalized residuals plot (see Fig. 1c) and the normal Q-Q plot
1900 /// (see Fig. 1d) of residuals are regular and we cannot identify the outliers
1901 /// or bins with a big influence on \f$ \chi^{2} \f$.
1902 ///
1903 /// The second example presents the same two histograms but 17 events was added
1904 /// to content of bin number 15 in unweighted histogram. Fig.2 shows the result
1905 /// of comparison of the unweighted histogram with 217 events (minimal expected
1906 /// frequency equal to one) and the weighted histogram with 500 events (minimal
1907 /// expected frequency equal to 25)
1908 /// Begin_Macro
1909 /// ../../../tutorials/math/chi2test.C(17)
1910 /// End_Macro
1911 /// Fig 2. An example of comparison of the unweighted histogram with 217 events
1912 /// and the weighted histogram with 500 events:
1913 /// 1. unweighted histogram;
1914 /// 2. weighted histogram;
1915 /// 3. normalized residuals plot;
1916 /// 4. normal Q-Q plot of residuals.
1917 ///
1918 /// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1919 /// 32.33 with p-value equal to 0.029, therefore the hypothesis of identity of
1920 /// the two histograms is rejected for 0.05 significant level. The behavior of
1921 /// the normalized residuals plot (see Fig. 2c) and the normal Q-Q plot (see
1922 /// Fig. 2d) of residuals are not regular and we can identify the outlier or
1923 /// bin with a big influence on \f$ \chi^{2} \f$.
1924 ///
1925 /// #### References:
1926 ///
1927 /// - [1] Pearson, K., 1904. On the Theory of Contingency and Its Relation to
1928 /// Association and Normal Correlation. Drapers' Co. Memoirs, Biometric
1929 /// Series No. 1, London.
1930 /// - [2] Gagunashvili, N., 2006. \f$ \sigma^{2} \f$ test for comparison
1931 /// of weighted and unweighted histograms. Statistical Problems in Particle
1932 /// Physics, Astrophysics and Cosmology, Proceedings of PHYSTAT05,
1933 /// Oxford, UK, 12-15 September 2005, Imperial College Press, London, 43-44.
1934 /// Gagunashvili,N., Comparison of weighted and unweighted histograms,
1935 /// arXiv:physics/0605123, 2006.
1936 /// - [3] Cramer, H., 1946. Mathematical methods of statistics.
1937 /// Princeton University Press, Princeton.
1938 /// - [4] Haberman, S.J., 1973. The analysis of residuals in cross-classified tables.
1939 /// Biometrics 29, 205-220.
1940 /// - [5] Lewontin, R.C. and Felsenstein, J., 1965. The robustness of homogeneity
1941 /// test in 2xN tables. Biometrics 21, 19-33.
1942 /// - [6] Seber, G.A.F., Lee, A.J., 2003, Linear Regression Analysis.
1943 /// John Wiley & Sons Inc., New York.
1944 
1945 Double_t TH1::Chi2Test(const TH1* h2, Option_t *option, Double_t *res) const
1946 {
1947  Double_t chi2 = 0;
1948  Int_t ndf = 0, igood = 0;
1949 
1950  TString opt = option;
1951  opt.ToUpper();
1952 
1953  Double_t prob = Chi2TestX(h2,chi2,ndf,igood,option,res);
1954 
1955  if(opt.Contains("P")) {
1956  printf("Chi2 = %f, Prob = %g, NDF = %d, igood = %d\n", chi2,prob,ndf,igood);
1957  }
1958  if(opt.Contains("CHI2/NDF")) {
1959  if (ndf == 0) return 0;
1960  return chi2/ndf;
1961  }
1962  if(opt.Contains("CHI2")) {
1963  return chi2;
1964  }
1965 
1966  return prob;
1967 }
1968 
1969 ////////////////////////////////////////////////////////////////////////////////
1970 /// The computation routine of the Chisquare test. For the method description,
1971 /// see Chi2Test() function.
1972 ///
1973 /// \return p-value
1974 /// \param[in] h2 the second histogram
1975 /// \param[in] option
1976 /// - "UU" = experiment experiment comparison (unweighted-unweighted)
1977 /// - "UW" = experiment MC comparison (unweighted-weighted). Note that the first
1978 /// histogram should be unweighted
1979 /// - "WW" = MC MC comparison (weighted-weighted)
1980 /// - "NORM" = if one or both histograms is scaled
1981 /// - "OF" = overflows included
1982 /// - "UF" = underflows included
1983 /// by default underflows and overflows are not included
1984 /// \param[out] igood test output
1985 /// - igood=0 - no problems
1986 /// - For unweighted unweighted comparison
1987 /// - igood=1'There is a bin in the 1st histogram with less than 1 event'
1988 /// - igood=2'There is a bin in the 2nd histogram with less than 1 event'
1989 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1990 /// - For unweighted weighted comparison
1991 /// - igood=1'There is a bin in the 1st histogram with less then 1 event'
1992 /// - igood=2'There is a bin in the 2nd histogram with less then 10 effective number of events'
1993 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1994 /// - For weighted weighted comparison
1995 /// - igood=1'There is a bin in the 1st histogram with less then 10 effective
1996 /// number of events'
1997 /// - igood=2'There is a bin in the 2nd histogram with less then 10 effective
1998 /// number of events'
1999 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
2000 /// \param[out] chi2 chisquare of the test
2001 /// \param[out] ndf number of degrees of freedom (important, when both histograms have the same empty bins)
2002 /// \param[out] res normalized residuals for further analysis
2003 
2004 Double_t TH1::Chi2TestX(const TH1* h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option, Double_t *res) const
2005 {
2007  Int_t i_start, i_end;
2008  Int_t j_start, j_end;
2009  Int_t k_start, k_end;
2010 
2011  Double_t sum1 = 0.0, sumw1 = 0.0;
2012  Double_t sum2 = 0.0, sumw2 = 0.0;
2013 
2014  chi2 = 0.0;
2015  ndf = 0;
2016 
2017  TString opt = option;
2018  opt.ToUpper();
2019 
2020  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
2021 
2022  const TAxis *xaxis1 = GetXaxis();
2023  const TAxis *xaxis2 = h2->GetXaxis();
2024  const TAxis *yaxis1 = GetYaxis();
2025  const TAxis *yaxis2 = h2->GetYaxis();
2026  const TAxis *zaxis1 = GetZaxis();
2027  const TAxis *zaxis2 = h2->GetZaxis();
2028 
2029  Int_t nbinx1 = xaxis1->GetNbins();
2030  Int_t nbinx2 = xaxis2->GetNbins();
2031  Int_t nbiny1 = yaxis1->GetNbins();
2032  Int_t nbiny2 = yaxis2->GetNbins();
2033  Int_t nbinz1 = zaxis1->GetNbins();
2034  Int_t nbinz2 = zaxis2->GetNbins();
2035 
2036  //check dimensions
2037  if (this->GetDimension() != h2->GetDimension() ){
2038  Error("Chi2TestX","Histograms have different dimensions.");
2039  return 0.0;
2040  }
2041 
2042  //check number of channels
2043  if (nbinx1 != nbinx2) {
2044  Error("Chi2TestX","different number of x channels");
2045  }
2046  if (nbiny1 != nbiny2) {
2047  Error("Chi2TestX","different number of y channels");
2048  }
2049  if (nbinz1 != nbinz2) {
2050  Error("Chi2TestX","different number of z channels");
2051  }
2052 
2053  //check for ranges
2054  i_start = j_start = k_start = 1;
2055  i_end = nbinx1;
2056  j_end = nbiny1;
2057  k_end = nbinz1;
2058 
2059  if (xaxis1->TestBit(TAxis::kAxisRange)) {
2060  i_start = xaxis1->GetFirst();
2061  i_end = xaxis1->GetLast();
2062  }
2063  if (yaxis1->TestBit(TAxis::kAxisRange)) {
2064  j_start = yaxis1->GetFirst();
2065  j_end = yaxis1->GetLast();
2066  }
2067  if (zaxis1->TestBit(TAxis::kAxisRange)) {
2068  k_start = zaxis1->GetFirst();
2069  k_end = zaxis1->GetLast();
2070  }
2071 
2072 
2073  if (opt.Contains("OF")) {
2074  if (GetDimension() == 3) k_end = ++nbinz1;
2075  if (GetDimension() >= 2) j_end = ++nbiny1;
2076  if (GetDimension() >= 1) i_end = ++nbinx1;
2077  }
2078 
2079  if (opt.Contains("UF")) {
2080  if (GetDimension() == 3) k_start = 0;
2081  if (GetDimension() >= 2) j_start = 0;
2082  if (GetDimension() >= 1) i_start = 0;
2083  }
2084 
2085  ndf = (i_end - i_start + 1) * (j_end - j_start + 1) * (k_end - k_start + 1) - 1;
2086 
2087  Bool_t comparisonUU = opt.Contains("UU");
2088  Bool_t comparisonUW = opt.Contains("UW");
2089  Bool_t comparisonWW = opt.Contains("WW");
2090  Bool_t scaledHistogram = opt.Contains("NORM");
2091 
2092  if (scaledHistogram && !comparisonUU) {
2093  Info("Chi2TestX", "NORM option should be used together with UU option. It is ignored");
2094  }
2095 
2096  // look at histo global bin content and effective entries
2097  Stat_t s[kNstat];
2098  GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
2099  Double_t sumBinContent1 = s[0];
2100  Double_t effEntries1 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
2101 
2102  h2->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
2103  Double_t sumBinContent2 = s[0];
2104  Double_t effEntries2 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
2105 
2106  if (!comparisonUU && !comparisonUW && !comparisonWW ) {
2107  // deduce automatically from type of histogram
2108  if (TMath::Abs(sumBinContent1 - effEntries1) < 1) {
2109  if ( TMath::Abs(sumBinContent2 - effEntries2) < 1) comparisonUU = true;
2110  else comparisonUW = true;
2111  }
2112  else comparisonWW = true;
2113  }
2114  // check unweighted histogram
2115  if (comparisonUW) {
2116  if (TMath::Abs(sumBinContent1 - effEntries1) >= 1) {
2117  Warning("Chi2TestX","First histogram is not unweighted and option UW has been requested");
2118  }
2119  }
2120  if ( (!scaledHistogram && comparisonUU) ) {
2121  if ( ( TMath::Abs(sumBinContent1 - effEntries1) >= 1) || (TMath::Abs(sumBinContent2 - effEntries2) >= 1) ) {
2122  Warning("Chi2TestX","Both histograms are not unweighted and option UU has been requested");
2123  }
2124  }
2125 
2126 
2127  //get number of events in histogram
2128  if (comparisonUU && scaledHistogram) {
2129  for (Int_t i = i_start; i <= i_end; ++i) {
2130  for (Int_t j = j_start; j <= j_end; ++j) {
2131  for (Int_t k = k_start; k <= k_end; ++k) {
2132 
2133  Int_t bin = GetBin(i, j, k);
2134 
2135  Double_t cnt1 = RetrieveBinContent(bin);
2136  Double_t cnt2 = h2->RetrieveBinContent(bin);
2137  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2138  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2139 
2140  if (e1sq > 0.0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2141  else cnt1 = 0.0;
2142 
2143  if (e2sq > 0.0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2144  else cnt2 = 0.0;
2145 
2146  // sum contents
2147  sum1 += cnt1;
2148  sum2 += cnt2;
2149  sumw1 += e1sq;
2150  sumw2 += e2sq;
2151  }
2152  }
2153  }
2154  if (sumw1 <= 0.0 || sumw2 <= 0.0) {
2155  Error("Chi2TestX", "Cannot use option NORM when one histogram has all zero errors");
2156  return 0.0;
2157  }
2158 
2159  } else {
2160  for (Int_t i = i_start; i <= i_end; ++i) {
2161  for (Int_t j = j_start; j <= j_end; ++j) {
2162  for (Int_t k = k_start; k <= k_end; ++k) {
2163 
2164  Int_t bin = GetBin(i, j, k);
2165 
2166  sum1 += RetrieveBinContent(bin);
2167  sum2 += h2->RetrieveBinContent(bin);
2168 
2169  if ( comparisonWW ) sumw1 += GetBinErrorSqUnchecked(bin);
2170  if ( comparisonUW || comparisonWW ) sumw2 += h2->GetBinErrorSqUnchecked(bin);
2171  }
2172  }
2173  }
2174  }
2175  //checks that the histograms are not empty
2176  if (sum1 == 0.0 || sum2 == 0.0) {
2177  Error("Chi2TestX","one histogram is empty");
2178  return 0.0;
2179  }
2180 
2181  if ( comparisonWW && ( sumw1 <= 0.0 && sumw2 <= 0.0 ) ){
2182  Error("Chi2TestX","Hist1 and Hist2 have both all zero errors\n");
2183  return 0.0;
2184  }
2185 
2186  //THE TEST
2187  Int_t m = 0, n = 0;
2188 
2189  //Experiment - experiment comparison
2190  if (comparisonUU) {
2191  Double_t sum = sum1 + sum2;
2192  for (Int_t i = i_start; i <= i_end; ++i) {
2193  for (Int_t j = j_start; j <= j_end; ++j) {
2194  for (Int_t k = k_start; k <= k_end; ++k) {
2195 
2196  Int_t bin = GetBin(i, j, k);
2197 
2198  Double_t cnt1 = RetrieveBinContent(bin);
2199  Double_t cnt2 = h2->RetrieveBinContent(bin);
2200 
2201  if (scaledHistogram) {
2202  // scale bin value to effective bin entries
2203  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2204  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2205 
2206  if (e1sq > 0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2207  else cnt1 = 0;
2208 
2209  if (e2sq > 0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2210  else cnt2 = 0;
2211  }
2212 
2213  if (Int_t(cnt1) == 0 && Int_t(cnt2) == 0) --ndf; // no data means one degree of freedom less
2214  else {
2215 
2216  Double_t cntsum = cnt1 + cnt2;
2217  Double_t nexp1 = cntsum * sum1 / sum;
2218  //Double_t nexp2 = binsum*sum2/sum;
2219 
2220  if (res) res[i - i_start] = (cnt1 - nexp1) / TMath::Sqrt(nexp1);
2221 
2222  if (cnt1 < 1) ++m;
2223  if (cnt2 < 1) ++n;
2224 
2225  //Habermann correction for residuals
2226  Double_t correc = (1. - sum1 / sum) * (1. - cntsum / sum);
2227  if (res) res[i - i_start] /= TMath::Sqrt(correc);
2228 
2229  Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2230  chi2 += delta * delta / cntsum;
2231  }
2232  }
2233  }
2234  }
2235  chi2 /= sum1 * sum2;
2236 
2237  // flag error only when of the two histogram is zero
2238  if (m) {
2239  igood += 1;
2240  Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2241  }
2242  if (n) {
2243  igood += 2;
2244  Info("Chi2TestX","There is a bin in h2 with less than 1 event.\n");
2245  }
2246 
2247  Double_t prob = TMath::Prob(chi2,ndf);
2248  return prob;
2249 
2250  }
2251 
2252  // unweighted - weighted comparison
2253  // case of error = 0 and content not zero is treated without problems by excluding second chi2 sum
2254  // and can be considered as a data-theory comparison
2255  if ( comparisonUW ) {
2256  for (Int_t i = i_start; i <= i_end; ++i) {
2257  for (Int_t j = j_start; j <= j_end; ++j) {
2258  for (Int_t k = k_start; k <= k_end; ++k) {
2259 
2260  Int_t bin = GetBin(i, j, k);
2261 
2262  Double_t cnt1 = RetrieveBinContent(bin);
2263  Double_t cnt2 = h2->RetrieveBinContent(bin);
2264  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2265 
2266  // case both histogram have zero bin contents
2267  if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2268  --ndf; //no data means one degree of freedom less
2269  continue;
2270  }
2271 
2272  // case weighted histogram has zero bin content and error
2273  if (cnt2 * cnt2 == 0 && e2sq == 0) {
2274  if (sumw2 > 0) {
2275  // use as approximated error as 1 scaled by a scaling ratio
2276  // estimated from the total sum weight and sum weight squared
2277  e2sq = sumw2 / sum2;
2278  }
2279  else {
2280  // return error because infinite discrepancy here:
2281  // bin1 != 0 and bin2 =0 in a histogram with all errors zero
2282  Error("Chi2TestX","Hist2 has in bin (%d,%d,%d) zero content and zero errors\n", i, j, k);
2283  chi2 = 0; return 0;
2284  }
2285  }
2286 
2287  if (cnt1 < 1) m++;
2288  if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2289 
2290  Double_t var1 = sum2 * cnt2 - sum1 * e2sq;
2291  Double_t var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2292 
2293  // if cnt1 is zero and cnt2 = 1 and sum1 = sum2 var1 = 0 && var2 == 0
2294  // approximate by incrementing cnt1
2295  // LM (this need to be fixed for numerical errors)
2296  while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2297  sum1++;
2298  cnt1++;
2299  var1 = sum2 * cnt2 - sum1 * e2sq;
2300  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2301  }
2302  var2 = TMath::Sqrt(var2);
2303 
2304  while (var1 + var2 == 0) {
2305  sum1++;
2306  cnt1++;
2307  var1 = sum2 * cnt2 - sum1 * e2sq;
2308  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2309  while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2310  sum1++;
2311  cnt1++;
2312  var1 = sum2 * cnt2 - sum1 * e2sq;
2313  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2314  }
2315  var2 = TMath::Sqrt(var2);
2316  }
2317 
2318  Double_t probb = (var1 + var2) / (2. * sum2 * sum2);
2319 
2320  Double_t nexp1 = probb * sum1;
2321  Double_t nexp2 = probb * sum2;
2322 
2323  Double_t delta1 = cnt1 - nexp1;
2324  Double_t delta2 = cnt2 - nexp2;
2325 
2326  chi2 += delta1 * delta1 / nexp1;
2327 
2328  if (e2sq > 0) {
2329  chi2 += delta2 * delta2 / e2sq;
2330  }
2331 
2332  if (res) {
2333  if (e2sq > 0) {
2334  Double_t temp1 = sum2 * e2sq / var2;
2335  Double_t temp2 = 1.0 + (sum1 * e2sq - sum2 * cnt2) / var2;
2336  temp2 = temp1 * temp1 * sum1 * probb * (1.0 - probb) + temp2 * temp2 * e2sq / 4.0;
2337  // invert sign here
2338  res[i - i_start] = - delta2 / TMath::Sqrt(temp2);
2339  }
2340  else
2341  res[i - i_start] = delta1 / TMath::Sqrt(nexp1);
2342  }
2343  }
2344  }
2345  }
2346 
2347  if (m) {
2348  igood += 1;
2349  Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2350  }
2351  if (n) {
2352  igood += 2;
2353  Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2354  }
2355 
2356  Double_t prob = TMath::Prob(chi2, ndf);
2357 
2358  return prob;
2359  }
2360 
2361  // weighted - weighted comparison
2362  if (comparisonWW) {
2363  for (Int_t i = i_start; i <= i_end; ++i) {
2364  for (Int_t j = j_start; j <= j_end; ++j) {
2365  for (Int_t k = k_start; k <= k_end; ++k) {
2366 
2367  Int_t bin = GetBin(i, j, k);
2368  Double_t cnt1 = RetrieveBinContent(bin);
2369  Double_t cnt2 = h2->RetrieveBinContent(bin);
2370  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2371  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2372 
2373  // case both histogram have zero bin contents
2374  // (use square of content to avoid numerical errors)
2375  if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2376  --ndf; //no data means one degree of freedom less
2377  continue;
2378  }
2379 
2380  if (e1sq == 0 && e2sq == 0) {
2381  // cannot treat case of booth histogram have zero zero errors
2382  Error("Chi2TestX","h1 and h2 both have bin %d,%d,%d with all zero errors\n", i,j,k);
2383  chi2 = 0; return 0;
2384  }
2385 
2386  Double_t sigma = sum1 * sum1 * e2sq + sum2 * sum2 * e1sq;
2387  Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2388  chi2 += delta * delta / sigma;
2389 
2390  if (res) {
2391  Double_t temp = cnt1 * sum1 * e2sq + cnt2 * sum2 * e1sq;
2392  Double_t probb = temp / sigma;
2393  Double_t z = 0;
2394  if (e1sq > e2sq) {
2395  Double_t d1 = cnt1 - sum1 * probb;
2396  Double_t s1 = e1sq * ( 1. - e2sq * sum1 * sum1 / sigma );
2397  z = d1 / TMath::Sqrt(s1);
2398  }
2399  else {
2400  Double_t d2 = cnt2 - sum2 * probb;
2401  Double_t s2 = e2sq * ( 1. - e1sq * sum2 * sum2 / sigma );
2402  z = -d2 / TMath::Sqrt(s2);
2403  }
2404  res[i - i_start] = z;
2405  }
2406 
2407  if (e1sq > 0 && cnt1 * cnt1 / e1sq < 10) m++;
2408  if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2409  }
2410  }
2411  }
2412  if (m) {
2413  igood += 1;
2414  Info("Chi2TestX","There is a bin in h1 with less than 10 effective events.\n");
2415  }
2416  if (n) {
2417  igood += 2;
2418  Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2419  }
2420  Double_t prob = TMath::Prob(chi2, ndf);
2421  return prob;
2422  }
2423  return 0;
2424 }
2425 ////////////////////////////////////////////////////////////////////////////////
2426 /// Compute and return the chisquare of this histogram with respect to a function
2427 /// The chisquare is computed by weighting each histogram point by the bin error
2428 /// By default the full range of the histogram is used.
2429 /// Use option "R" for restricting the chisquare calculation to the given range of the function
2430 /// Use option "L" for using the chisquare based on the poisson likelihood (Baker-Cousins Chisquare)
2431 
2432 Double_t TH1::Chisquare(TF1 * func, Option_t *option) const
2433 {
2434  if (!func) {
2435  Error("Chisquare","Function pointer is Null - return -1");
2436  return -1;
2437  }
2438 
2439  TString opt(option); opt.ToUpper();
2440  bool useRange = opt.Contains("R");
2441  bool usePL = opt.Contains("L");
2442 
2443  return ROOT::Fit::Chisquare(*this, *func, useRange, usePL);
2444 }
2445 
2446 ////////////////////////////////////////////////////////////////////////////////
2447 /// Remove all the content from the underflow and overflow bins, without changing the number of entries
2448 /// After calling this method, every undeflow and overflow bins will have content 0.0
2449 /// The Sumw2 is also cleared, since there is no more content in the bins
2450 
2452 {
2453  for (Int_t bin = 0; bin < fNcells; ++bin)
2454  if (IsBinUnderflow(bin) || IsBinOverflow(bin)) {
2455  UpdateBinContent(bin, 0.0);
2456  if (fSumw2.fN) fSumw2.fArray[bin] = 0.0;
2457  }
2458 }
2459 
2460 ////////////////////////////////////////////////////////////////////////////////
2461 /// Compute integral (cumulative sum of bins)
2462 /// The result stored in fIntegral is used by the GetRandom functions.
2463 /// This function is automatically called by GetRandom when the fIntegral
2464 /// array does not exist or when the number of entries in the histogram
2465 /// has changed since the previous call to GetRandom.
2466 /// The resulting integral is normalized to 1
2467 /// If the routine is called with the onlyPositive flag set an error will
2468 /// be produced in case of negative bin content and a NaN value returned
2469 
2470 Double_t TH1::ComputeIntegral(Bool_t onlyPositive)
2471 {
2473 
2474  // delete previously computed integral (if any)
2475  if (fIntegral) delete [] fIntegral;
2476 
2477  // - Allocate space to store the integral and compute integral
2478  Int_t nbinsx = GetNbinsX();
2479  Int_t nbinsy = GetNbinsY();
2480  Int_t nbinsz = GetNbinsZ();
2481  Int_t nbins = nbinsx * nbinsy * nbinsz;
2482 
2483  fIntegral = new Double_t[nbins + 2];
2484  Int_t ibin = 0; fIntegral[ibin] = 0;
2485 
2486  for (Int_t binz=1; binz <= nbinsz; ++binz) {
2487  for (Int_t biny=1; biny <= nbinsy; ++biny) {
2488  for (Int_t binx=1; binx <= nbinsx; ++binx) {
2489  ++ibin;
2490  Double_t y = RetrieveBinContent(GetBin(binx, biny, binz));
2491  if (onlyPositive && y < 0) {
2492  Error("ComputeIntegral","Bin content is negative - return a NaN value");
2493  fIntegral[nbins] = TMath::QuietNaN();
2494  break;
2495  }
2496  fIntegral[ibin] = fIntegral[ibin - 1] + y;
2497  }
2498  }
2499  }
2500 
2501  // - Normalize integral to 1
2502  if (fIntegral[nbins] == 0 ) {
2503  Error("ComputeIntegral", "Integral = zero"); return 0;
2504  }
2505  for (Int_t bin=1; bin <= nbins; ++bin) fIntegral[bin] /= fIntegral[nbins];
2506  fIntegral[nbins+1] = fEntries;
2507  return fIntegral[nbins];
2508 }
2509 
2510 ////////////////////////////////////////////////////////////////////////////////
2511 /// Return a pointer to the array of bins integral.
2512 /// if the pointer fIntegral is null, TH1::ComputeIntegral is called
2513 /// The array dimension is the number of bins in the histograms
2514 /// including underflow and overflow (fNCells)
2515 /// the last value integral[fNCells] is set to the number of entries of
2516 /// the histogram
2517 
2519 {
2521  return fIntegral;
2522 }
2523 
2524 ////////////////////////////////////////////////////////////////////////////////
2525 /// Return a pointer to an histogram containing the cumulative The
2526 /// cumulative can be computed both in the forward (default) or backward
2527 /// direction; the name of the new histogram is constructed from
2528 /// the name of this histogram with the suffix suffix appended.
2529 ///
2530 /// The cumulative distribution is formed by filling each bin of the
2531 /// resulting histogram with the sum of that bin and all previous
2532 /// (forward == kTRUE) or following (forward = kFALSE) bins.
2533 ///
2534 /// note: while cumulative distributions make sense in one dimension, you
2535 /// may not be getting what you expect in more than 1D because the concept
2536 /// of a cumulative distribution is much trickier to define; make sure you
2537 /// understand the order of summation before you use this method with
2538 /// histograms of dimension >= 2.
2539 
2540 TH1 *TH1::GetCumulative(Bool_t forward, const char* suffix) const
2541 {
2542  const Int_t nbinsx = GetNbinsX();
2543  const Int_t nbinsy = GetNbinsY();
2544  const Int_t nbinsz = GetNbinsZ();
2545  TH1* hintegrated = (TH1*) Clone(fName + suffix);
2546  hintegrated->Reset();
2547  if (forward) { // Forward computation
2548  Double_t sum = 0.;
2549  for (Int_t binz = 1; binz <= nbinsz; ++binz) {
2550  for (Int_t biny = 1; biny <= nbinsy; ++biny) {
2551  for (Int_t binx = 1; binx <= nbinsx; ++binx) {
2552  const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2553  sum += GetBinContent(bin);
2554  hintegrated->SetBinContent(bin, sum);
2555  }
2556  }
2557  }
2558  } else { // Backward computation
2559  Double_t sum = 0.;
2560  for (Int_t binz = nbinsz; binz >= 1; --binz) {
2561  for (Int_t biny = nbinsy; biny >= 1; --biny) {
2562  for (Int_t binx = nbinsx; binx >= 1; --binx) {
2563  const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2564  sum += GetBinContent(bin);
2565  hintegrated->SetBinContent(bin, sum);
2566  }
2567  }
2568  }
2569  }
2570  return hintegrated;
2571 }
2572 
2573 ////////////////////////////////////////////////////////////////////////////////
2574 /// Copy this histogram structure to newth1.
2575 ///
2576 /// Note that this function does not copy the list of associated functions.
2577 /// Use TObject::Clone to make a full copy of an histogram.
2578 ///
2579 /// Note also that the histogram it will be created in gDirectory (if AddDirectoryStatus()=true)
2580 /// or will not be added to any directory if AddDirectoryStatus()=false
2581 /// independently of the current directory stored in the original histogram
2582 
2583 void TH1::Copy(TObject &obj) const
2584 {
2585  if (((TH1&)obj).fDirectory) {
2586  // We are likely to change the hash value of this object
2587  // with TNamed::Copy, to keep things correct, we need to
2588  // clean up its existing entries.
2589  ((TH1&)obj).fDirectory->Remove(&obj);
2590  ((TH1&)obj).fDirectory = 0;
2591  }
2592  TNamed::Copy(obj);
2593  ((TH1&)obj).fDimension = fDimension;
2594  ((TH1&)obj).fNormFactor= fNormFactor;
2595  ((TH1&)obj).fNcells = fNcells;
2596  ((TH1&)obj).fBarOffset = fBarOffset;
2597  ((TH1&)obj).fBarWidth = fBarWidth;
2598  ((TH1&)obj).fOption = fOption;
2599  ((TH1&)obj).fBinStatErrOpt = fBinStatErrOpt;
2600  ((TH1&)obj).fBufferSize= fBufferSize;
2601  // copy the Buffer
2602  // delete first a previously existing buffer
2603  if (((TH1&)obj).fBuffer != 0) {
2604  delete [] ((TH1&)obj).fBuffer;
2605  ((TH1&)obj).fBuffer = 0;
2606  }
2607  if (fBuffer) {
2608  Double_t *buf = new Double_t[fBufferSize];
2609  for (Int_t i=0;i<fBufferSize;i++) buf[i] = fBuffer[i];
2610  // obj.fBuffer has been deleted before
2611  ((TH1&)obj).fBuffer = buf;
2612  }
2613 
2614 
2615  TArray* a = dynamic_cast<TArray*>(&obj);
2616  if (a) a->Set(fNcells);
2617  for (Int_t i = 0; i < fNcells; i++) ((TH1&)obj).UpdateBinContent(i, RetrieveBinContent(i));
2618 
2619  ((TH1&)obj).fEntries = fEntries;
2620 
2621  // which will call BufferEmpty(0) and set fBuffer[0] to a Maybe one should call
2622  // assignment operator on the TArrayD
2623 
2624  ((TH1&)obj).fTsumw = fTsumw;
2625  ((TH1&)obj).fTsumw2 = fTsumw2;
2626  ((TH1&)obj).fTsumwx = fTsumwx;
2627  ((TH1&)obj).fTsumwx2 = fTsumwx2;
2628  ((TH1&)obj).fMaximum = fMaximum;
2629  ((TH1&)obj).fMinimum = fMinimum;
2630 
2631  TAttLine::Copy(((TH1&)obj));
2632  TAttFill::Copy(((TH1&)obj));
2633  TAttMarker::Copy(((TH1&)obj));
2634  fXaxis.Copy(((TH1&)obj).fXaxis);
2635  fYaxis.Copy(((TH1&)obj).fYaxis);
2636  fZaxis.Copy(((TH1&)obj).fZaxis);
2637  ((TH1&)obj).fXaxis.SetParent(&obj);
2638  ((TH1&)obj).fYaxis.SetParent(&obj);
2639  ((TH1&)obj).fZaxis.SetParent(&obj);
2640  fContour.Copy(((TH1&)obj).fContour);
2641  fSumw2.Copy(((TH1&)obj).fSumw2);
2642  // fFunctions->Copy(((TH1&)obj).fFunctions);
2643  // when copying an histogram if the AddDirectoryStatus() is true it
2644  // will be added to gDirectory independently of the fDirectory stored.
2645  // and if the AddDirectoryStatus() is false it will not be added to
2646  // any directory (fDirectory = 0)
2647  if (fgAddDirectory && gDirectory) {
2648  gDirectory->Append(&obj);
2649  ((TH1&)obj).fFunctions->UseRWLock();
2650  ((TH1&)obj).fDirectory = gDirectory;
2651  } else
2652  ((TH1&)obj).fDirectory = 0;
2653 
2654 }
2655 
2656 ////////////////////////////////////////////////////////////////////////////////
2657 /// Make a complete copy of the underlying object. If 'newname' is set,
2658 /// the copy's name will be set to that name.
2659 
2660 TObject* TH1::Clone(const char* newname) const
2661 {
2662  TH1* obj = (TH1*)IsA()->GetNew()(0);
2663  Copy(*obj);
2664 
2665  //Now handle the parts that Copy doesn't do
2666  if(fFunctions) {
2667  if (obj->fFunctions) delete obj->fFunctions;
2668  obj->fFunctions = (TList*)fFunctions->Clone();
2669  }
2670  if(newname && strlen(newname) ) {
2671  obj->SetName(newname);
2672  }
2673  return obj;
2674 }
2675 
2676 ////////////////////////////////////////////////////////////////////////////////
2677 /// Perform the automatic addition of the histogram to the given directory
2678 ///
2679 /// Note this function is called in place when the semantic requires
2680 /// this object to be added to a directory (I.e. when being read from
2681 /// a TKey or being Cloned)
2682 
2684 {
2686  if (addStatus) {
2687  SetDirectory(dir);
2688  if (dir) {
2690  }
2691  }
2692 }
2693 
2694 ////////////////////////////////////////////////////////////////////////////////
2695 /// Compute distance from point px,py to a line.
2696 ///
2697 /// Compute the closest distance of approach from point px,py to elements
2698 /// of an histogram.
2699 /// The distance is computed in pixels units.
2700 ///
2701 /// #### Algorithm:
2702 /// Currently, this simple model computes the distance from the mouse
2703 /// to the histogram contour only.
2704 
2706 {
2707  if (!fPainter) return 9999;
2708  return fPainter->DistancetoPrimitive(px,py);
2709 }
2710 
2711 ////////////////////////////////////////////////////////////////////////////////
2712 /// Performs the operation: `this = this/(c1*f1)`
2713 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2714 ///
2715 /// Only bins inside the function range are recomputed.
2716 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2717 /// you should call Sumw2 before making this operation.
2718 /// This is particularly important if you fit the histogram after TH1::Divide
2719 ///
2720 /// The function return kFALSE if the divide operation failed
2721 
2723 {
2724  if (!f1) {
2725  Error("Add","Attempt to divide by a non-existing function");
2726  return kFALSE;
2727  }
2728 
2729  // delete buffer if it is there since it will become invalid
2730  if (fBuffer) BufferEmpty(1);
2731 
2732  Int_t nx = GetNbinsX() + 2; // normal bins + uf / of
2733  Int_t ny = GetNbinsY() + 2;
2734  Int_t nz = GetNbinsZ() + 2;
2735  if (fDimension < 2) ny = 1;
2736  if (fDimension < 3) nz = 1;
2737 
2738 
2739  SetMinimum();
2740  SetMaximum();
2741 
2742  // - Loop on bins (including underflows/overflows)
2743  Int_t bin, binx, biny, binz;
2744  Double_t cu, w;
2745  Double_t xx[3];
2746  Double_t *params = 0;
2747  f1->InitArgs(xx,params);
2748  for (binz = 0; binz < nz; ++binz) {
2749  xx[2] = fZaxis.GetBinCenter(binz);
2750  for (biny = 0; biny < ny; ++biny) {
2751  xx[1] = fYaxis.GetBinCenter(biny);
2752  for (binx = 0; binx < nx; ++binx) {
2753  xx[0] = fXaxis.GetBinCenter(binx);
2754  if (!f1->IsInside(xx)) continue;
2756  bin = binx + nx * (biny + ny * binz);
2757  cu = c1 * f1->EvalPar(xx);
2758  if (TF1::RejectedPoint()) continue;
2759  if (cu) w = RetrieveBinContent(bin) / cu;
2760  else w = 0;
2761  UpdateBinContent(bin, w);
2762  if (fSumw2.fN) {
2763  if (cu != 0) fSumw2.fArray[bin] = GetBinErrorSqUnchecked(bin) / (cu * cu);
2764  else fSumw2.fArray[bin] = 0;
2765  }
2766  }
2767  }
2768  }
2769  ResetStats();
2770  return kTRUE;
2771 }
2772 
2773 ////////////////////////////////////////////////////////////////////////////////
2774 /// Divide this histogram by h1.
2775 ///
2776 /// `this = this/h1`
2777 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2778 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
2779 /// if not already set.
2780 /// The resulting errors are calculated assuming uncorrelated histograms.
2781 /// See the other TH1::Divide that gives the possibility to optionally
2782 /// compute binomial errors.
2783 ///
2784 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2785 /// you should call Sumw2 before making this operation.
2786 /// This is particularly important if you fit the histogram after TH1::Scale
2787 ///
2788 /// The function return kFALSE if the divide operation failed
2789 
2790 Bool_t TH1::Divide(const TH1 *h1)
2791 {
2792  if (!h1) {
2793  Error("Divide", "Input histogram passed does not exist (NULL).");
2794  return kFALSE;
2795  }
2796 
2797  // delete buffer if it is there since it will become invalid
2798  if (fBuffer) BufferEmpty(1);
2799 
2800  try {
2801  CheckConsistency(this,h1);
2802  } catch(DifferentNumberOfBins&) {
2803  Error("Divide","Cannot divide histograms with different number of bins");
2804  return kFALSE;
2805  } catch(DifferentAxisLimits&) {
2806  Warning("Divide","Dividing histograms with different axis limits");
2807  } catch(DifferentBinLimits&) {
2808  Warning("Divide","Dividing histograms with different bin limits");
2809  } catch(DifferentLabels&) {
2810  Warning("Divide","Dividing histograms with different labels");
2811  }
2812 
2813  // Create Sumw2 if h1 has Sumw2 set
2814  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
2815 
2816  // - Loop on bins (including underflows/overflows)
2817  for (Int_t i = 0; i < fNcells; ++i) {
2818  Double_t c0 = RetrieveBinContent(i);
2819  Double_t c1 = h1->RetrieveBinContent(i);
2820  if (c1) UpdateBinContent(i, c0 / c1);
2821  else UpdateBinContent(i, 0);
2822 
2823  if(fSumw2.fN) {
2824  if (c1 == 0) { fSumw2.fArray[i] = 0; continue; }
2825  Double_t c1sq = c1 * c1;
2826  fSumw2.fArray[i] = (GetBinErrorSqUnchecked(i) * c1sq + h1->GetBinErrorSqUnchecked(i) * c0 * c0) / (c1sq * c1sq);
2827  }
2828  }
2829  ResetStats();
2830  return kTRUE;
2831 }
2832 
2833 ////////////////////////////////////////////////////////////////////////////////
2834 /// Replace contents of this histogram by the division of h1 by h2.
2835 ///
2836 /// `this = c1*h1/(c2*h2)`
2837 ///
2838 /// If errors are defined (see TH1::Sumw2), errors are also recalculated
2839 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
2840 /// if not already set.
2841 /// The resulting errors are calculated assuming uncorrelated histograms.
2842 /// However, if option ="B" is specified, Binomial errors are computed.
2843 /// In this case c1 and c2 do not make real sense and they are ignored.
2844 ///
2845 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2846 /// you should call Sumw2 before making this operation.
2847 /// This is particularly important if you fit the histogram after TH1::Divide
2848 ///
2849 /// Please note also that in the binomial case errors are calculated using standard
2850 /// binomial statistics, which means when b1 = b2, the error is zero.
2851 /// If you prefer to have efficiency errors not going to zero when the efficiency is 1, you must
2852 /// use the function TGraphAsymmErrors::BayesDivide, which will return an asymmetric and non-zero lower
2853 /// error for the case b1=b2.
2854 ///
2855 /// The function return kFALSE if the divide operation failed
2856 
2857 Bool_t TH1::Divide(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2, Option_t *option)
2858 {
2860  TString opt = option;
2861  opt.ToLower();
2862  Bool_t binomial = kFALSE;
2863  if (opt.Contains("b")) binomial = kTRUE;
2864  if (!h1 || !h2) {
2865  Error("Divide", "At least one of the input histograms passed does not exist (NULL).");
2866  return kFALSE;
2867  }
2868 
2869  // delete buffer if it is there since it will become invalid
2870  if (fBuffer) BufferEmpty(1);
2871 
2872  try {
2873  CheckConsistency(h1,h2);
2874  CheckConsistency(this,h1);
2875  } catch(DifferentNumberOfBins&) {
2876  Error("Divide","Cannot divide histograms with different number of bins");
2877  return kFALSE;
2878  } catch(DifferentAxisLimits&) {
2879  Warning("Divide","Dividing histograms with different axis limits");
2880  } catch(DifferentBinLimits&) {
2881  Warning("Divide","Dividing histograms with different bin limits");
2882  } catch(DifferentLabels&) {
2883  Warning("Divide","Dividing histograms with different labels");
2884  }
2885 
2886 
2887  if (!c2) {
2888  Error("Divide","Coefficient of dividing histogram cannot be zero");
2889  return kFALSE;
2890  }
2891 
2892  // Create Sumw2 if h1 or h2 have Sumw2 set
2893  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
2894 
2895  SetMinimum();
2896  SetMaximum();
2897 
2898  // - Loop on bins (including underflows/overflows)
2899  for (Int_t i = 0; i < fNcells; ++i) {
2900  Double_t b1 = h1->RetrieveBinContent(i);
2901  Double_t b2 = h2->RetrieveBinContent(i);
2902  if (b2) UpdateBinContent(i, c1 * b1 / (c2 * b2));
2903  else UpdateBinContent(i, 0);
2904 
2905  if (fSumw2.fN) {
2906  if (b2 == 0) { fSumw2.fArray[i] = 0; continue; }
2907  Double_t b1sq = b1 * b1; Double_t b2sq = b2 * b2;
2908  Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
2909  Double_t e1sq = h1->GetBinErrorSqUnchecked(i);
2910  Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
2911  if (binomial) {
2912  if (b1 != b2) {
2913  // in the case of binomial statistics c1 and c2 must be 1 otherwise it does not make sense
2914  // c1 and c2 are ignored
2915  //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/(c2*b2));//this is the formula in Hbook/Hoper1
2916  //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/b2); // old formula from G. Flucke
2917  // formula which works also for weighted histogram (see http://root-forum.cern.ch/viewtopic.php?t=3753 )
2918  fSumw2.fArray[i] = TMath::Abs( ( (1. - 2.* b1 / b2) * e1sq + b1sq * e2sq / b2sq ) / b2sq );
2919  } else {
2920  //in case b1=b2 error is zero
2921  //use TGraphAsymmErrors::BayesDivide for getting the asymmetric error not equal to zero
2922  fSumw2.fArray[i] = 0;
2923  }
2924  } else {
2925  fSumw2.fArray[i] = c1sq * c2sq * (e1sq * b2sq + e2sq * b1sq) / (c2sq * c2sq * b2sq * b2sq);
2926  }
2927  }
2928  }
2929  ResetStats();
2930  if (binomial)
2931  // in case of binomial division use denominator for number of entries
2932  SetEntries ( h2->GetEntries() );
2933 
2934  return kTRUE;
2935 }
2936 
2937 ////////////////////////////////////////////////////////////////////////////////
2938 /// Draw this histogram with options.
2939 ///
2940 /// Histograms are drawn via the THistPainter class. Each histogram has
2941 /// a pointer to its own painter (to be usable in a multithreaded program).
2942 /// The same histogram can be drawn with different options in different pads.
2943 /// When an histogram drawn in a pad is deleted, the histogram is
2944 /// automatically removed from the pad or pads where it was drawn.
2945 /// If an histogram is drawn in a pad, then filled again, the new status
2946 /// of the histogram will be automatically shown in the pad next time
2947 /// the pad is updated. One does not need to redraw the histogram.
2948 /// To draw the current version of an histogram in a pad, one can use
2949 /// `h->DrawCopy();`
2950 /// This makes a clone of the histogram. Once the clone is drawn, the original
2951 /// histogram may be modified or deleted without affecting the aspect of the
2952 /// clone.
2953 /// By default, TH1::Draw clears the current pad.
2954 ///
2955 /// One can use TH1::SetMaximum and TH1::SetMinimum to force a particular
2956 /// value for the maximum or the minimum scale on the plot.
2957 ///
2958 /// TH1::UseCurrentStyle can be used to change all histogram graphics
2959 /// attributes to correspond to the current selected style.
2960 /// This function must be called for each histogram.
2961 /// In case one reads and draws many histograms from a file, one can force
2962 /// the histograms to inherit automatically the current graphics style
2963 /// by calling before gROOT->ForceStyle();
2964 ///
2965 /// See the THistPainter class for a description of all the drawing options.
2966 
2967 void TH1::Draw(Option_t *option)
2968 {
2969  TString opt1 = option; opt1.ToLower();
2970  TString opt2 = option;
2971  Int_t index = opt1.Index("same");
2972 
2973  // Check if the string "same" is part of a TCutg name.
2974  if (index>=0) {
2975  Int_t indb = opt1.Index("[");
2976  if (indb>=0) {
2977  Int_t indk = opt1.Index("]");
2978  if (index>indb && index<indk) index = -1;
2979  }
2980  }
2981 
2982  // If there is no pad or an empty pad the "same" option is ignored.
2983  if (gPad) {
2984  if (!gPad->IsEditable()) gROOT->MakeDefCanvas();
2985  if (index>=0) {
2986  if (gPad->GetX1() == 0 && gPad->GetX2() == 1 &&
2987  gPad->GetY1() == 0 && gPad->GetY2() == 1 &&
2988  gPad->GetListOfPrimitives()->GetSize()==0) opt2.Remove(index,4);
2989  } else {
2990  //the following statement is necessary in case one attempts to draw
2991  //a temporary histogram already in the current pad
2992  if (TestBit(kCanDelete)) gPad->GetListOfPrimitives()->Remove(this);
2993  gPad->Clear();
2994  }
2995  gPad->IncrementPaletteColor(1, opt1);
2996  } else {
2997  if (index>=0) opt2.Remove(index,4);
2998  }
2999 
3000  AppendPad(opt2.Data());
3001 }
3002 
3003 ////////////////////////////////////////////////////////////////////////////////
3004 /// Copy this histogram and Draw in the current pad.
3005 ///
3006 /// Once the histogram is drawn into the pad, any further modification
3007 /// using graphics input will be made on the copy of the histogram,
3008 /// and not to the original object.
3009 /// By default a postfix "_copy" is added to the histogram name. Pass an empty postfix in case
3010 /// you want to draw an histogram with the same name
3011 ///
3012 /// See Draw for the list of options
3013 
3014 TH1 *TH1::DrawCopy(Option_t *option, const char * name_postfix) const
3015 {
3016  TString opt = option;
3017  opt.ToLower();
3018  if (gPad && !opt.Contains("same")) gPad->Clear();
3019  TString newName = (name_postfix) ? TString::Format("%s%s",GetName(),name_postfix) : "";
3020  TH1 *newth1 = (TH1 *)Clone(newName);
3021  newth1->SetDirectory(0);
3022  newth1->SetBit(kCanDelete);
3023  newth1->AppendPad(option);
3024  return newth1;
3025 }
3026 
3027 ////////////////////////////////////////////////////////////////////////////////
3028 /// Draw a normalized copy of this histogram.
3029 ///
3030 /// A clone of this histogram is normalized to norm and drawn with option.
3031 /// A pointer to the normalized histogram is returned.
3032 /// The contents of the histogram copy are scaled such that the new
3033 /// sum of weights (excluding under and overflow) is equal to norm.
3034 /// Note that the returned normalized histogram is not added to the list
3035 /// of histograms in the current directory in memory.
3036 /// It is the user's responsibility to delete this histogram.
3037 /// The kCanDelete bit is set for the returned object. If a pad containing
3038 /// this copy is cleared, the histogram will be automatically deleted.
3039 ///
3040 /// See Draw for the list of options
3041 
3042 TH1 *TH1::DrawNormalized(Option_t *option, Double_t norm) const
3043 {
3045  if (sum == 0) {
3046  Error("DrawNormalized","Sum of weights is null. Cannot normalize histogram: %s",GetName());
3047  return 0;
3048  }
3049  Bool_t addStatus = TH1::AddDirectoryStatus();
3051  TH1 *h = (TH1*)Clone();
3052  h->SetBit(kCanDelete);
3053  // in case of drawing with error options - scale correctly the error
3054  TString opt(option); opt.ToUpper();
3055  if (fSumw2.fN == 0) {
3056  h->Sumw2();
3057  // do not use in this case the "Error option " for drawing which is enabled by default since the normalized histogram has now errors
3058  if (opt.IsNull() || opt == "SAME") opt += "HIST";
3059  }
3060  h->Scale(norm/sum);
3061  if (TMath::Abs(fMaximum+1111) > 1e-3) h->SetMaximum(fMaximum*norm/sum);
3062  if (TMath::Abs(fMinimum+1111) > 1e-3) h->SetMinimum(fMinimum*norm/sum);
3063  h->Draw(opt);
3064  TH1::AddDirectory(addStatus);
3065  return h;
3066 }
3067 
3068 ////////////////////////////////////////////////////////////////////////////////
3069 /// Display a panel with all histogram drawing options.
3070 ///
3071 /// See class TDrawPanelHist for example
3072 
3073 void TH1::DrawPanel()
3074 {
3075  if (!fPainter) {Draw(); if (gPad) gPad->Update();}
3076  if (fPainter) fPainter->DrawPanel();
3077 }
3078 
3079 ////////////////////////////////////////////////////////////////////////////////
3080 /// Evaluate function f1 at the center of bins of this histogram.
3081 ///
3082 /// - If option "R" is specified, the function is evaluated only
3083 /// for the bins included in the function range.
3084 /// - If option "A" is specified, the value of the function is added to the
3085 /// existing bin contents
3086 /// - If option "S" is specified, the value of the function is used to
3087 /// generate a value, distributed according to the Poisson
3088 /// distribution, with f1 as the mean.
3089 
3090 void TH1::Eval(TF1 *f1, Option_t *option)
3091 {
3093  Int_t range, stat, add;
3094  if (!f1) return;
3095 
3096  TString opt = option;
3097  opt.ToLower();
3098  if (opt.Contains("a")) add = 1;
3099  else add = 0;
3100  if (opt.Contains("s")) stat = 1;
3101  else stat = 0;
3102  if (opt.Contains("r")) range = 1;
3103  else range = 0;
3104 
3105  // delete buffer if it is there since it will become invalid
3106  if (fBuffer) BufferEmpty(1);
3107 
3108  Int_t nbinsx = fXaxis.GetNbins();
3109  Int_t nbinsy = fYaxis.GetNbins();
3110  Int_t nbinsz = fZaxis.GetNbins();
3111  if (!add) Reset();
3112 
3113  for (Int_t binz = 1; binz <= nbinsz; ++binz) {
3114  x[2] = fZaxis.GetBinCenter(binz);
3115  for (Int_t biny = 1; biny <= nbinsy; ++biny) {
3116  x[1] = fYaxis.GetBinCenter(biny);
3117  for (Int_t binx = 1; binx <= nbinsx; ++binx) {
3118  Int_t bin = GetBin(binx,biny,binz);
3119  x[0] = fXaxis.GetBinCenter(binx);
3120  if (range && !f1->IsInside(x)) continue;
3121  Double_t fu = f1->Eval(x[0], x[1], x[2]);
3122  if (stat) fu = gRandom->PoissonD(fu);
3123  AddBinContent(bin, fu);
3124  if (fSumw2.fN) fSumw2.fArray[bin] += TMath::Abs(fu);
3125  }
3126  }
3127  }
3128 }
3129 
3130 ////////////////////////////////////////////////////////////////////////////////
3131 /// Execute action corresponding to one event.
3132 ///
3133 /// This member function is called when a histogram is clicked with the locator
3134 ///
3135 /// If Left button clicked on the bin top value, then the content of this bin
3136 /// is modified according to the new position of the mouse when it is released.
3137 
3138 void TH1::ExecuteEvent(Int_t event, Int_t px, Int_t py)
3139 {
3140  if (fPainter) fPainter->ExecuteEvent(event, px, py);
3141 }
3142 
3143 ////////////////////////////////////////////////////////////////////////////////
3144 /// This function allows to do discrete Fourier transforms of TH1 and TH2.
3145 /// Available transform types and flags are described below.
3146 ///
3147 /// To extract more information about the transform, use the function
3148 /// TVirtualFFT::GetCurrentTransform() to get a pointer to the current
3149 /// transform object.
3150 ///
3151 /// \param[out] h_output histogram for the output. If a null pointer is passed, a new histogram is created
3152 /// and returned, otherwise, the provided histogram is used and should be big enough
3153 /// \param[in] option option parameters consists of 3 parts:
3154 /// - option on what to return
3155 /// - "RE" - returns a histogram of the real part of the output
3156 /// - "IM" - returns a histogram of the imaginary part of the output
3157 /// - "MAG"- returns a histogram of the magnitude of the output
3158 /// - "PH" - returns a histogram of the phase of the output
3159 /// - option of transform type
3160 /// - "R2C" - real to complex transforms - default
3161 /// - "R2HC" - real to halfcomplex (special format of storing output data,
3162 /// results the same as for R2C)
3163 /// - "DHT" - discrete Hartley transform
3164 /// real to real transforms (sine and cosine):
3165 /// - "R2R_0", "R2R_1", "R2R_2", "R2R_3" - discrete cosine transforms of types I-IV
3166 /// - "R2R_4", "R2R_5", "R2R_6", "R2R_7" - discrete sine transforms of types I-IV
3167 /// To specify the type of each dimension of a 2-dimensional real to real
3168 /// transform, use options of form "R2R_XX", for example, "R2R_02" for a transform,
3169 /// which is of type "R2R_0" in 1st dimension and "R2R_2" in the 2nd.
3170 /// - option of transform flag
3171 /// - "ES" (from "estimate") - no time in preparing the transform, but probably sub-optimal
3172 /// performance
3173 /// - "M" (from "measure") - some time spend in finding the optimal way to do the transform
3174 /// - "P" (from "patient") - more time spend in finding the optimal way to do the transform
3175 /// - "EX" (from "exhaustive") - the most optimal way is found
3176 /// This option should be chosen depending on how many transforms of the same size and
3177 /// type are going to be done. Planning is only done once, for the first transform of this
3178 /// size and type. Default is "ES".
3179 ///
3180 /// Examples of valid options: "Mag R2C M" "Re R2R_11" "Im R2C ES" "PH R2HC EX"
3181 
3182 TH1* TH1::FFT(TH1* h_output, Option_t *option)
3183 {
3185  Int_t ndim[3];
3186  ndim[0] = this->GetNbinsX();
3187  ndim[1] = this->GetNbinsY();
3188  ndim[2] = this->GetNbinsZ();
3189 
3190  TVirtualFFT *fft;
3191  TString opt = option;
3192  opt.ToUpper();
3193  if (!opt.Contains("2R")){
3194  if (!opt.Contains("2C") && !opt.Contains("2HC") && !opt.Contains("DHT")) {
3195  //no type specified, "R2C" by default
3196  opt.Append("R2C");
3197  }
3198  fft = TVirtualFFT::FFT(this->GetDimension(), ndim, opt.Data());
3199  }
3200  else {
3201  //find the kind of transform
3202  Int_t ind = opt.Index("R2R", 3);
3203  Int_t *kind = new Int_t[2];
3204  char t;
3205  t = opt[ind+4];
3206  kind[0] = atoi(&t);
3207  if (h_output->GetDimension()>1) {
3208  t = opt[ind+5];
3209  kind[1] = atoi(&t);
3210  }
3211  fft = TVirtualFFT::SineCosine(this->GetDimension(), ndim, kind, option);
3212  delete [] kind;
3213  }
3214 
3215  if (!fft) return 0;
3216  Int_t in=0;
3217  for (Int_t binx = 1; binx<=ndim[0]; binx++) {
3218  for (Int_t biny=1; biny<=ndim[1]; biny++) {
3219  for (Int_t binz=1; binz<=ndim[2]; binz++) {
3220  fft->SetPoint(in, this->GetBinContent(binx, biny, binz));
3221  in++;
3222  }
3223  }
3224  }
3225  fft->Transform();
3226  h_output = TransformHisto(fft, h_output, option);
3227  return h_output;
3228 }
3229 
3230 ////////////////////////////////////////////////////////////////////////////////
3231 /// Increment bin with abscissa X by 1.
3232 ///
3233 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3234 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3235 ///
3236 /// If the storage of the sum of squares of weights has been triggered,
3237 /// via the function Sumw2, then the sum of the squares of weights is incremented
3238 /// by 1 in the bin corresponding to x.
3239 ///
3240 /// The function returns the corresponding bin number which has its content incremented by 1
3241 
3243 {
3244  if (fBuffer) return BufferFill(x,1);
3245 
3246  Int_t bin;
3247  fEntries++;
3248  bin =fXaxis.FindBin(x);
3249  if (bin <0) return -1;
3250  AddBinContent(bin);
3251  if (fSumw2.fN) ++fSumw2.fArray[bin];
3252  if (bin == 0 || bin > fXaxis.GetNbins()) {
3253  if (!GetStatOverflowsBehaviour()) return -1;
3254  }
3255  ++fTsumw;
3256  ++fTsumw2;
3257  fTsumwx += x;
3258  fTsumwx2 += x*x;
3259  return bin;
3260 }
3261 
3262 ////////////////////////////////////////////////////////////////////////////////
3263 /// Increment bin with abscissa X with a weight w.
3264 ///
3265 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3266 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3267 ///
3268 /// If the weight is not equal to 1, the storage of the sum of squares of
3269 /// weights is automatically triggered and the sum of the squares of weights is incremented
3270 /// by \f$ w^2 \f$ in the bin corresponding to x.
3271 ///
3272 /// The function returns the corresponding bin number which has its content incremented by w
3273 
3275 {
3277  if (fBuffer) return BufferFill(x,w);
3278 
3279  Int_t bin;
3280  fEntries++;
3281  bin =fXaxis.FindBin(x);
3282  if (bin <0) return -1;
3283  if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW) ) Sumw2(); // must be called before AddBinContent
3284  if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3285  AddBinContent(bin, w);
3286  if (bin == 0 || bin > fXaxis.GetNbins()) {
3287  if (!GetStatOverflowsBehaviour()) return -1;
3288  }
3289  Double_t z= w;
3290  fTsumw += z;
3291  fTsumw2 += z*z;
3292  fTsumwx += z*x;
3293  fTsumwx2 += z*x*x;
3294  return bin;
3295 }
3296 
3297 ////////////////////////////////////////////////////////////////////////////////
3298 /// Increment bin with namex with a weight w
3299 ///
3300 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3301 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3302 ///
3303 /// If the weight is not equal to 1, the storage of the sum of squares of
3304 /// weights is automatically triggered and the sum of the squares of weights is incremented
3305 /// by \f$ w^2 \f$ in the bin corresponding to x.
3306 ///
3307 /// The function returns the corresponding bin number which has its content
3308 /// incremented by w.
3309 
3310 Int_t TH1::Fill(const char *namex, Double_t w)
3311 {
3312  Int_t bin;
3313  fEntries++;
3314  bin =fXaxis.FindBin(namex);
3315  if (bin <0) return -1;
3316  if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3317  if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3318  AddBinContent(bin, w);
3319  if (bin == 0 || bin > fXaxis.GetNbins()) return -1;
3320  Double_t z= w;
3321  fTsumw += z;
3322  fTsumw2 += z*z;
3323  // this make sense if the histogram is not expanding (no axis can be extended)
3324  if (!CanExtendAllAxes()) {
3325  Double_t x = fXaxis.GetBinCenter(bin);
3326  fTsumwx += z*x;
3327  fTsumwx2 += z*x*x;
3328  }
3329  return bin;
3330 }
3331 
3332 ////////////////////////////////////////////////////////////////////////////////
3333 /// Fill this histogram with an array x and weights w.
3334 ///
3335 /// \param[in] ntimes number of entries in arrays x and w (array size must be ntimes*stride)
3336 /// \param[in] x array of values to be histogrammed
3337 /// \param[in] w array of weighs
3338 /// \param[in] stride step size through arrays x and w
3339 ///
3340 /// If the weight is not equal to 1, the storage of the sum of squares of
3341 /// weights is automatically triggered and the sum of the squares of weights is incremented
3342 /// by \f$ w^2 \f$ in the bin corresponding to x.
3343 /// if w is NULL each entry is assumed a weight=1
3344 
3345 void TH1::FillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3346 {
3347  //If a buffer is activated, fill buffer
3348  if (fBuffer) {
3349  ntimes *= stride;
3350  Int_t i = 0;
3351  for (i=0;i<ntimes;i+=stride) {
3352  if (!fBuffer) break; // buffer can be deleted in BufferFill when is empty
3353  if (w) BufferFill(x[i],w[i]);
3354  else BufferFill(x[i], 1.);
3355  }
3356  // fill the remaining entries if the buffer has been deleted
3357  if (i < ntimes && fBuffer==0) {
3358  auto weights = w ? &w[i] : nullptr;
3359  DoFillN((ntimes-i)/stride,&x[i],weights,stride);
3360  }
3361  return;
3362  }
3363  // call internal method
3364  DoFillN(ntimes, x, w, stride);
3365 }
3366 
3367 ////////////////////////////////////////////////////////////////////////////////
3368 /// Internal method to fill histogram content from a vector
3369 /// called directly by TH1::BufferEmpty
3370 
3371 void TH1::DoFillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3372 {
3373  Int_t bin,i;
3374 
3375  fEntries += ntimes;
3376  Double_t ww = 1;
3377  Int_t nbins = fXaxis.GetNbins();
3378  ntimes *= stride;
3379  for (i=0;i<ntimes;i+=stride) {
3380  bin =fXaxis.FindBin(x[i]);
3381  if (bin <0) continue;
3382  if (w) ww = w[i];
3383  if (!fSumw2.fN && ww != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3384  if (fSumw2.fN) fSumw2.fArray[bin] += ww*ww;
3385  AddBinContent(bin, ww);
3386  if (bin == 0 || bin > nbins) {
3387  if (!GetStatOverflowsBehaviour()) continue;
3388  }
3389  Double_t z= ww;
3390  fTsumw += z;
3391  fTsumw2 += z*z;
3392  fTsumwx += z*x[i];
3393  fTsumwx2 += z*x[i]*x[i];
3394  }
3395 }
3396 
3397 ////////////////////////////////////////////////////////////////////////////////
3398 /// Fill histogram following distribution in function fname.
3399 ///
3400 /// The distribution contained in the function fname (TF1) is integrated
3401 /// over the channel contents for the bin range of this histogram.
3402 /// It is normalized to 1.
3403 ///
3404 /// Getting one random number implies:
3405 /// - Generating a random number between 0 and 1 (say r1)
3406 /// - Look in which bin in the normalized integral r1 corresponds to
3407 /// - Fill histogram channel
3408 /// ntimes random numbers are generated
3409 ///
3410 /// One can also call TF1::GetRandom to get a random variate from a function.
3411 
3412 void TH1::FillRandom(const char *fname, Int_t ntimes)
3413 {
3414  Int_t bin, binx, ibin, loop;
3415  Double_t r1, x;
3416  // - Search for fname in the list of ROOT defined functions
3417  TF1 *f1 = (TF1*)gROOT->GetFunction(fname);
3418  if (!f1) { Error("FillRandom", "Unknown function: %s",fname); return; }
3419 
3420  // - Allocate temporary space to store the integral and compute integral
3421 
3422  TAxis * xAxis = &fXaxis;
3423 
3424  // in case axis of histogram is not defined use the function axis
3425  if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
3426  Double_t xmin,xmax;
3427  f1->GetRange(xmin,xmax);
3428  Info("FillRandom","Using function axis and range [%g,%g]",xmin, xmax);
3429  xAxis = f1->GetHistogram()->GetXaxis();
3430  }
3431 
3432  Int_t first = xAxis->GetFirst();
3433  Int_t last = xAxis->GetLast();
3434  Int_t nbinsx = last-first+1;
3435 
3436  Double_t *integral = new Double_t[nbinsx+1];
3437  integral[0] = 0;
3438  for (binx=1;binx<=nbinsx;binx++) {
3439  Double_t fint = f1->Integral(xAxis->GetBinLowEdge(binx+first-1),xAxis->GetBinUpEdge(binx+first-1));
3440  integral[binx] = integral[binx-1] + fint;
3441  }
3442 
3443  // - Normalize integral to 1
3444  if (integral[nbinsx] == 0 ) {
3445  delete [] integral;
3446  Error("FillRandom", "Integral = zero"); return;
3447  }
3448  for (bin=1;bin<=nbinsx;bin++) integral[bin] /= integral[nbinsx];
3449 
3450  // --------------Start main loop ntimes
3451  for (loop=0;loop<ntimes;loop++) {
3452  r1 = gRandom->Rndm();
3453  ibin = TMath::BinarySearch(nbinsx,&integral[0],r1);
3454  //binx = 1 + ibin;
3455  //x = xAxis->GetBinCenter(binx); //this is not OK when SetBuffer is used
3456  x = xAxis->GetBinLowEdge(ibin+first)
3457  +xAxis->GetBinWidth(ibin+first)*(r1-integral[ibin])/(integral[ibin+1] - integral[ibin]);
3458  Fill(x);
3459  }
3460  delete [] integral;
3461 }
3462 
3463 ////////////////////////////////////////////////////////////////////////////////
3464 /// Fill histogram following distribution in histogram h.
3465 ///
3466 /// The distribution contained in the histogram h (TH1) is integrated
3467 /// over the channel contents for the bin range of this histogram.
3468 /// It is normalized to 1.
3469 ///
3470 /// Getting one random number implies:
3471 /// - Generating a random number between 0 and 1 (say r1)
3472 /// - Look in which bin in the normalized integral r1 corresponds to
3473 /// - Fill histogram channel ntimes random numbers are generated
3474 ///
3475 /// SPECIAL CASE when the target histogram has the same binning as the source.
3476 /// in this case we simply use a poisson distribution where
3477 /// the mean value per bin = bincontent/integral.
3478 
3479 void TH1::FillRandom(TH1 *h, Int_t ntimes)
3480 {
3481  if (!h) { Error("FillRandom", "Null histogram"); return; }
3482  if (fDimension != h->GetDimension()) {
3483  Error("FillRandom", "Histograms with different dimensions"); return;
3484  }
3485  if (std::isnan(h->ComputeIntegral(true))) {
3486  Error("FillRandom", "Histograms contains negative bins, does not represent probabilities");
3487  return;
3488  }
3489 
3490  //in case the target histogram has the same binning and ntimes much greater
3491  //than the number of bins we can use a fast method
3492  Int_t first = fXaxis.GetFirst();
3493  Int_t last = fXaxis.GetLast();
3494  Int_t nbins = last-first+1;
3495  if (ntimes > 10*nbins) {
3496  try {
3497  CheckConsistency(this,h);
3498  Double_t sumw = h->Integral(first,last);
3499  if (sumw == 0) return;
3500  Double_t sumgen = 0;
3501  for (Int_t bin=first;bin<=last;bin++) {
3502  Double_t mean = h->RetrieveBinContent(bin)*ntimes/sumw;
3503  Double_t cont = (Double_t)gRandom->Poisson(mean);
3504  sumgen += cont;
3505  AddBinContent(bin,cont);
3506  if (fSumw2.fN) fSumw2.fArray[bin] += cont;
3507  }
3508 
3509  // fix for the fluctuations in the total number n
3510  // since we use Poisson instead of multinomial
3511  // add a correction to have ntimes as generated entries
3512  Int_t i;
3513  if (sumgen < ntimes) {
3514  // add missing entries
3515  for (i = Int_t(sumgen+0.5); i < ntimes; ++i)
3516  {
3517  Double_t x = h->GetRandom();
3518  Fill(x);
3519  }
3520  }
3521  else if (sumgen > ntimes) {
3522  // remove extra entries
3523  i = Int_t(sumgen+0.5);
3524  while( i > ntimes) {
3525  Double_t x = h->GetRandom();
3526  Int_t ibin = fXaxis.FindBin(x);
3527  Double_t y = RetrieveBinContent(ibin);
3528  // skip in case bin is empty
3529  if (y > 0) {
3530  SetBinContent(ibin, y-1.);
3531  i--;
3532  }
3533  }
3534  }
3535 
3536  ResetStats();
3537  return;
3538  }
3539  catch(std::exception&) {} // do nothing
3540  }
3541  // case of different axis and not too large ntimes
3542 
3543  if (h->ComputeIntegral() ==0) return;
3544  Int_t loop;
3545  Double_t x;
3546  for (loop=0;loop<ntimes;loop++) {
3547  x = h->GetRandom();
3548  Fill(x);
3549  }
3550 }
3551 
3552 ////////////////////////////////////////////////////////////////////////////////
3553 /// Return Global bin number corresponding to x,y,z
3554 ///
3555 /// 2-D and 3-D histograms are represented with a one dimensional
3556 /// structure. This has the advantage that all existing functions, such as
3557 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3558 /// This function tries to extend the axis if the given point belongs to an
3559 /// under-/overflow bin AND if CanExtendAllAxes() is true.
3560 ///
3561 /// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3562 
3564 {
3565  if (GetDimension() < 2) {
3566  return fXaxis.FindBin(x);
3567  }
3568  if (GetDimension() < 3) {
3569  Int_t nx = fXaxis.GetNbins()+2;
3570  Int_t binx = fXaxis.FindBin(x);
3571  Int_t biny = fYaxis.FindBin(y);
3572  return binx + nx*biny;
3573  }
3574  if (GetDimension() < 4) {
3575  Int_t nx = fXaxis.GetNbins()+2;
3576  Int_t ny = fYaxis.GetNbins()+2;
3577  Int_t binx = fXaxis.FindBin(x);
3578  Int_t biny = fYaxis.FindBin(y);
3579  Int_t binz = fZaxis.FindBin(z);
3580  return binx + nx*(biny +ny*binz);
3581  }
3582  return -1;
3583 }
3584 
3585 ////////////////////////////////////////////////////////////////////////////////
3586 /// Return Global bin number corresponding to x,y,z.
3587 ///
3588 /// 2-D and 3-D histograms are represented with a one dimensional
3589 /// structure. This has the advantage that all existing functions, such as
3590 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3591 /// This function DOES NOT try to extend the axis if the given point belongs
3592 /// to an under-/overflow bin.
3593 ///
3594 /// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3595 
3597 {
3598  if (GetDimension() < 2) {
3599  return fXaxis.FindFixBin(x);
3600  }
3601  if (GetDimension() < 3) {
3602  Int_t nx = fXaxis.GetNbins()+2;
3603  Int_t binx = fXaxis.FindFixBin(x);
3604  Int_t biny = fYaxis.FindFixBin(y);
3605  return binx + nx*biny;
3606  }
3607  if (GetDimension() < 4) {
3608  Int_t nx = fXaxis.GetNbins()+2;
3609  Int_t ny = fYaxis.GetNbins()+2;
3610  Int_t binx = fXaxis.FindFixBin(x);
3611  Int_t biny = fYaxis.FindFixBin(y);
3612  Int_t binz = fZaxis.FindFixBin(z);
3613  return binx + nx*(biny +ny*binz);
3614  }
3615  return -1;
3616 }
3617 
3618 ////////////////////////////////////////////////////////////////////////////////
3619 /// Find first bin with content > threshold for axis (1=x, 2=y, 3=z)
3620 /// if no bins with content > threshold is found the function returns -1.
3621 
3622 Int_t TH1::FindFirstBinAbove(Double_t threshold, Int_t axis) const
3623 {
3624  if (fBuffer) ((TH1*)this)->BufferEmpty();
3625 
3626  if (axis != 1) {
3627  Warning("FindFirstBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3628  axis = 1;
3629  }
3630  Int_t nbins = fXaxis.GetNbins();
3631  for (Int_t bin=1;bin<=nbins;bin++) {
3632  if (RetrieveBinContent(bin) > threshold) return bin;
3633  }
3634  return -1;
3635 }
3636 
3637 ////////////////////////////////////////////////////////////////////////////////
3638 /// Find last bin with content > threshold for axis (1=x, 2=y, 3=z)
3639 /// if no bins with content > threshold is found the function returns -1.
3640 
3641 Int_t TH1::FindLastBinAbove(Double_t threshold, Int_t axis) const
3642 {
3643  if (fBuffer) ((TH1*)this)->BufferEmpty();
3644 
3645  if (axis != 1) {
3646  Warning("FindLastBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3647  axis = 1;
3648  }
3649  Int_t nbins = fXaxis.GetNbins();
3650  for (Int_t bin=nbins;bin>=1;bin--) {
3651  if (RetrieveBinContent(bin) > threshold) return bin;
3652  }
3653  return -1;
3654 }
3655 
3656 ////////////////////////////////////////////////////////////////////////////////
3657 /// Search object named name in the list of functions.
3658 
3659 TObject *TH1::FindObject(const char *name) const
3660 {
3661  if (fFunctions) return fFunctions->FindObject(name);
3662  return 0;
3663 }
3664 
3665 ////////////////////////////////////////////////////////////////////////////////
3666 /// Search object obj in the list of functions.
3667 
3668 TObject *TH1::FindObject(const TObject *obj) const
3669 {
3670  if (fFunctions) return fFunctions->FindObject(obj);
3671  return 0;
3672 }
3673 
3674 ////////////////////////////////////////////////////////////////////////////////
3675 /// Fit histogram with function fname.
3676 ///
3677 /// fname is the name of an already predefined function created by TF1 or TF2
3678 /// Predefined functions such as gaus, expo and poln are automatically
3679 /// created by ROOT.
3680 /// fname can also be a formula, accepted by the linear fitter (linear parts divided
3681 /// by "++" sign), for example "x++sin(x)" for fitting "[0]*x+[1]*sin(x)"
3682 ///
3683 /// This function finds a pointer to the TF1 object with name fname
3684 /// and calls TH1::Fit(TF1 *f1,...)
3685 
3686 TFitResultPtr TH1::Fit(const char *fname ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
3687 {
3688  char *linear;
3689  linear= (char*)strstr(fname, "++");
3690  TF1 *f1=0;
3691  TF2 *f2=0;
3692  TF3 *f3=0;
3693  Int_t ndim=GetDimension();
3694  if (linear){
3695  if (ndim<2){
3696  f1=new TF1(fname, fname, xxmin, xxmax);
3697  return Fit(f1,option,goption,xxmin,xxmax);
3698  }
3699  else if (ndim<3){
3700  f2=new TF2(fname, fname);
3701  return Fit(f2,option,goption,xxmin,xxmax);
3702  }
3703  else{
3704  f3=new TF3(fname, fname);
3705  return Fit(f3,option,goption,xxmin,xxmax);
3706  }
3707  }
3708 
3709  else{
3710  f1 = (TF1*)gROOT->GetFunction(fname);
3711  if (!f1) { Printf("Unknown function: %s",fname); return -1; }
3712  return Fit(f1,option,goption,xxmin,xxmax);
3713  }
3714 }
3715 
3716 ////////////////////////////////////////////////////////////////////////////////
3717 /// Fit histogram with function f1.
3718 ///
3719 /// \param[in] option fit options is given in parameter option.
3720 /// - "W" Set all weights to 1 for non empty bins; ignore error bars
3721 /// - "WW" Set all weights to 1 including empty bins; ignore error bars
3722 /// - "I" Use integral of function in bin, normalized by the bin volume,
3723 /// instead of value at bin center
3724 /// - "L" Use Loglikelihood method (default is chisquare method)
3725 /// - "WL" Use Loglikelihood method and bin contents are not integer,
3726 /// i.e. histogram is weighted (must have Sumw2() set)
3727 /// - "P" Use Pearson chi2 (using expected errors instead of observed errors)
3728 /// - "U" Use a User specified fitting algorithm (via SetFCN)
3729 /// - "Q" Quiet mode (minimum printing)
3730 /// - "V" Verbose mode (default is between Q and V)
3731 /// - "E" Perform better Errors estimation using Minos technique
3732 /// - "B" User defined parameter settings are used for predefined functions
3733 /// like "gaus", "expo", "poln", "landau".
3734 /// Use this option when you want to fix one or more parameters for these functions.
3735 /// - "M" More. Improve fit results.
3736 /// It uses the IMPROVE command of TMinuit (see TMinuit::mnimpr).
3737 /// This algorithm attempts to improve the found local minimum by searching for a
3738 /// better one.
3739 /// - "R" Use the Range specified in the function range
3740 /// - "N" Do not store the graphics function, do not draw
3741 /// - "0" Do not plot the result of the fit. By default the fitted function
3742 /// is drawn unless the option"N" above is specified.
3743 /// - "+" Add this new fitted function to the list of fitted functions
3744 /// (by default, any previous function is deleted)
3745 /// - "C" In case of linear fitting, don't calculate the chisquare
3746 /// (saves time)
3747 /// - "F" If fitting a polN, switch to minuit fitter
3748 /// - "S" The result of the fit is returned in the TFitResultPtr
3749 /// (see below Access to the Fit Result)
3750 /// \param[in] goption specify a list of graphics options. See TH1::Draw for a complete list of these options.
3751 /// \param[in] xxmin range
3752 /// \param[in] xxmax range
3753 ///
3754 /// In order to use the Range option, one must first create a function
3755 /// with the expression to be fitted. For example, if your histogram
3756 /// has a defined range between -4 and 4 and you want to fit a gaussian
3757 /// only in the interval 1 to 3, you can do:
3758 ///
3759 /// ~~~ {.cpp}
3760 /// TF1 *f1 = new TF1("f1", "gaus", 1, 3);
3761 /// histo->Fit("f1", "R");
3762 /// ~~~
3763 ///
3764 /// ## Setting initial conditions
3765 /// Parameters must be initialized before invoking the Fit function.
3766 /// The setting of the parameter initial values is automatic for the
3767 /// predefined functions : poln, expo, gaus, landau. One can however disable
3768 /// this automatic computation by specifying the option "B".
3769 /// Note that if a predefined function is defined with an argument,
3770 /// eg, gaus(0), expo(1), you must specify the initial values for
3771 /// the parameters.
3772 /// You can specify boundary limits for some or all parameters via
3773 ///
3774 /// ~~~ {.cpp}
3775 /// f1->SetParLimits(p_number, parmin, parmax);
3776 /// ~~~
3777 ///
3778 /// if parmin>=parmax, the parameter is fixed
3779 /// Note that you are not forced to fix the limits for all parameters.
3780 /// For example, if you fit a function with 6 parameters, you can do:
3781 ///
3782 /// ~~~ {.cpp}
3783 /// func->SetParameters(0, 3.1, 1.e-6, -8, 0, 100);
3784 /// func->SetParLimits(3, -10, -4);
3785 /// func->FixParameter(4, 0);
3786 /// func->SetParLimits(5, 1, 1);
3787 /// ~~~
3788 ///
3789 /// With this setup, parameters 0->2 can vary freely
3790 /// Parameter 3 has boundaries [-10,-4] with initial value -8
3791 /// Parameter 4 is fixed to 0
3792 /// Parameter 5 is fixed to 100.
3793 /// When the lower limit and upper limit are equal, the parameter is fixed.
3794 /// However to fix a parameter to 0, one must call the FixParameter function.
3795 ///
3796 /// Note that option "I" gives better results but is slower.
3797 ///
3798 /// #### Changing the fitting objective function
3799 ///
3800 /// By default a chi square function is used for fitting. When option "L" (or "LL") is used
3801 /// a Poisson likelihood function (see note below) is used.
3802 /// The functions are defined in the header Fit/Chi2Func.h or Fit/PoissonLikelihoodFCN and they
3803 /// are implemented using the routines FitUtil::EvaluateChi2 or FitUtil::EvaluatePoissonLogL in
3804 /// the file math/mathcore/src/FitUtil.cxx.
3805 /// To specify a User defined fitting function, specify option "U" and
3806 /// call the following functions:
3807 ///
3808 /// ~~~ {.cpp}
3809 /// TVirtualFitter::Fitter(myhist)->SetFCN(MyFittingFunction)
3810 /// ~~~
3811 ///
3812 /// where MyFittingFunction is of type:
3813 ///
3814 /// ~~~ {.cpp}
3815 /// extern void MyFittingFunction(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag);
3816 /// ~~~
3817 ///
3818 /// #### Chi2 Fits
3819 ///
3820 /// By default a chi2 (least-square) fit is performed on the histogram. The so-called modified least-square method
3821 /// is used where the residual for each bin is computed using as error the observed value (the bin error)
3822 ///
3823 /// \f[
3824 /// Chi2 = \sum{ \left(y(i) - \frac{f(x(i) | p )}{e(i)} \right)^2 }
3825 /// \f]
3826 ///
3827 /// 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
3828 /// an un-weighted histogram. Bins with zero errors are excluded from the fit. See also later the note on the treatment of empty bins.
3829 /// When using option "I" the residual is computed not using the function value at the bin center, f (x(i) | p), but the integral
3830 /// of the function in the bin, Integral{ f(x|p)dx } divided by the bin volume
3831 ///
3832 /// #### Likelihood Fits
3833 ///
3834 /// When using option "L" a likelihood fit is used instead of the default chi2 square fit.
3835 /// The likelihood is built assuming a Poisson probability density function for each bin.
3836 /// The negative log-likelihood to be minimized is
3837 ///
3838 /// \f[
3839 /// NLL = \sum{ log Poisson ( y(i) | f(x(i) | p ) ) }
3840 /// \f]
3841 ///
3842 /// The exact likelihood used is the Poisson likelihood described in this paper:
3843 /// S. Baker and R. D. Cousins, “Clarification of the use of chi-square and likelihood functions in fits to histograms,”
3844 /// Nucl. Instrum. Meth. 221 (1984) 437.
3845 ///
3846 /// This method can then be used only when the bin content represents counts (i.e. errors are sqrt(N) ).
3847 /// The likelihood method has the advantage of treating correctly bins with low statistics. In case of high
3848 /// statistics/bin the distribution of the bin content becomes a normal distribution and the likelihood and chi2 fit
3849 /// give the same result.
3850 ///
3851 /// The likelihood method, although a bit slower, it is therefore the recommended method in case of low
3852 /// bin statistics, where the chi2 method may give incorrect results, in particular when there are
3853 /// several empty bins (see also below).
3854 /// In case of a weighted histogram, it is possible to perform a likelihood fit by using the
3855 /// option "WL". Note a weighted histogram is an histogram which has been filled with weights and it
3856 /// contains the sum of the weight square ( TH1::Sumw2() has been called). The bin error for a weighted
3857 /// histogram is the square root of the sum of the weight square.
3858 ///
3859 /// #### Treatment of Empty Bins
3860 ///
3861 /// Empty bins, which have the content equal to zero AND error equal to zero,
3862 /// are excluded by default from the chisquare fit, but they are considered in the likelihood fit.
3863 /// since they affect the likelihood if the function value in these bins is not negligible.
3864 /// When using option "WW" these bins will be considered in the chi2 fit with an error of 1.
3865 /// Note that if the histogram is having bins with zero content and non zero-errors they are considered as
3866 /// any other bins in the fit. Instead bins with zero error and non-zero content are excluded in the chi2 fit.
3867 /// A likelihood fit should also not be performed on such an histogram, since we are assuming a wrong pdf for each bin.
3868 /// In general, one should not fit an histogram with non-empty bins and zero errors, apart if all the bins have zero errors.
3869 /// In this case one could use the option "w", which gives a weight=1 for each bin (unweighted least-square fit).
3870 ///
3871 /// #### Fitting a histogram of dimension N with a function of dimension N-1
3872 ///
3873 /// It is possible to fit a TH2 with a TF1 or a TH3 with a TF2.
3874 /// In this case the option "Integral" is not allowed and each cell has
3875 /// equal weight.
3876 ///
3877 /// #### Associated functions
3878 ///
3879 /// One or more object (typically a TF1*) can be added to the list
3880 /// of functions (fFunctions) associated to each histogram.
3881 /// When TH1::Fit is invoked, the fitted function is added to this list.
3882 /// Given an histogram h, one can retrieve an associated function
3883 /// with:
3884 ///
3885 /// ~~~ {.cpp}
3886 /// TF1 *myfunc = h->GetFunction("myfunc");
3887 /// ~~~
3888 ///
3889 /// #### Access to the fit result
3890 ///
3891 /// The function returns a TFitResultPtr which can hold a pointer to a TFitResult object.
3892 /// By default the TFitResultPtr contains only the status of the fit which is return by an
3893 /// automatic conversion of the TFitResultPtr to an integer. One can write in this case directly:
3894 ///
3895 /// ~~~ {.cpp}
3896 /// Int_t fitStatus = h->Fit(myFunc)
3897 /// ~~~
3898 ///
3899 /// If the option "S" is instead used, TFitResultPtr contains the TFitResult and behaves as a smart
3900 /// pointer to it. For example one can do:
3901 ///
3902 /// ~~~ {.cpp}
3903 /// TFitResultPtr r = h->Fit(myFunc,"S");
3904 /// TMatrixDSym cov = r->GetCovarianceMatrix(); // to access the covariance matrix
3905 /// Double_t chi2 = r->Chi2(); // to retrieve the fit chi2
3906 /// Double_t par0 = r->Parameter(0); // retrieve the value for the parameter 0
3907 /// Double_t err0 = r->ParError(0); // retrieve the error for the parameter 0
3908 /// r->Print("V"); // print full information of fit including covariance matrix
3909 /// r->Write(); // store the result in a file
3910 /// ~~~
3911 ///
3912 /// The fit parameters, error and chi2 (but not covariance matrix) can be retrieved also
3913 /// from the fitted function.
3914 /// If the histogram is made persistent, the list of
3915 /// associated functions is also persistent. Given a pointer (see above)
3916 /// to an associated function myfunc, one can retrieve the function/fit
3917 /// parameters with calls such as:
3918 ///
3919 /// ~~~ {.cpp}
3920 /// Double_t chi2 = myfunc->GetChisquare();
3921 /// Double_t par0 = myfunc->GetParameter(0); //value of 1st parameter
3922 /// Double_t err0 = myfunc->GetParError(0); //error on first parameter
3923 /// ~~~
3924 ///
3925 /// #### Access to the fit status
3926 ///
3927 /// The status of the fit can be obtained converting the TFitResultPtr to an integer
3928 /// independently if the fit option "S" is used or not:
3929 ///
3930 /// ~~~ {.cpp}
3931 /// TFitResultPtr r = h->Fit(myFunc,opt);
3932 /// Int_t fitStatus = r;
3933 /// ~~~
3934 ///
3935 /// The fitStatus is 0 if the fit is OK (i.e no error occurred).
3936 /// The value of the fit status code is negative in case of an error not connected with the
3937 /// minimization procedure, for example when a wrong function is used.
3938 /// Otherwise the return value is the one returned from the minimization procedure.
3939 /// When TMinuit (default case) or Minuit2 are used as minimizer the status returned is :
3940 /// `fitStatus = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult`.
3941 /// TMinuit will return 0 (for migrad, minos, hesse or improve) in case of success and 4 in
3942 /// case of error (see the documentation of TMinuit::mnexcm). So for example, for an error
3943 /// only in Minos but not in Migrad a fitStatus of 40 will be returned.
3944 /// Minuit2 will return also 0 in case of success and different values in migrad minos or
3945 /// hesse depending on the error. See in this case the documentation of
3946 /// Minuit2Minimizer::Minimize for the migradResult, Minuit2Minimizer::GetMinosError for the
3947 /// minosResult and Minuit2Minimizer::Hesse for the hesseResult.
3948 /// If other minimizers are used see their specific documentation for the status code returned.
3949 /// For example in the case of Fumili, for the status returned see TFumili::Minimize.
3950 ///
3951 /// #### Excluding points
3952 ///
3953 /// Use TF1::RejectPoint inside your fitting function to exclude points
3954 /// within a certain range from the fit. Example:
3955 ///
3956 /// ~~~ {.cpp}
3957 /// Double_t fline(Double_t *x, Double_t *par)
3958 /// {
3959 /// if (x[0] > 2.5 && x[0] < 3.5) {
3960 /// TF1::RejectPoint();
3961 /// return 0;
3962 /// }
3963 /// return par[0] + par[1]*x[0];
3964 /// }
3965 ///
3966 /// void exclude() {
3967 /// TF1 *f1 = new TF1("f1", "[0] +[1]*x +gaus(2)", 0, 5);
3968 /// f1->SetParameters(6, -1,5, 3, 0.2);
3969 /// TH1F *h = new TH1F("h", "background + signal", 100, 0, 5);
3970 /// h->FillRandom("f1", 2000);
3971 /// TF1 *fline = new TF1("fline", fline, 0, 5, 2);
3972 /// fline->SetParameters(2, -1);
3973 /// h->Fit("fline", "l");
3974 /// }
3975 /// ~~~
3976 ///
3977 /// #### Warning when using the option "0"
3978 ///
3979 /// When selecting the option "0", the fitted function is added to
3980 /// the list of functions of the histogram, but it is not drawn.
3981 /// You can undo what you disabled in the following way:
3982 ///
3983 /// ~~~ {.cpp}
3984 /// h.Fit("myFunction", "0"); // fit, store function but do not draw
3985 /// h.Draw(); function is not drawn
3986 /// const Int_t kNotDraw = 1<<9;
3987 /// h.GetFunction("myFunction")->ResetBit(kNotDraw);
3988 /// h.Draw(); // function is visible again
3989 /// ~~~
3990 ///
3991 /// #### Access to the Minimizer information during fitting
3992 ///
3993 /// This function calls, the ROOT::Fit::FitObject function implemented in HFitImpl.cxx
3994 /// which uses the ROOT::Fit::Fitter class. The Fitter class creates the objective function
3995 /// (e.g. chi2 or likelihood) and uses an implementation of the Minimizer interface for minimizing
3996 /// the function.
3997 /// The default minimizer is Minuit (class TMinuitMinimizer which calls TMinuit).
3998 /// The default can be set in the resource file in etc/system.rootrc. For example
3999 ///
4000 /// ~~~ {.cpp}
4001 /// Root.Fitter: Minuit2
4002 /// ~~~
4003 ///
4004 /// A different fitter can also be set via ROOT::Math::MinimizerOptions::SetDefaultMinimizer
4005 /// (or TVirtualFitter::SetDefaultFitter).
4006 /// For example ROOT::Math::MinimizerOptions::SetDefaultMinimizer("GSLMultiMin","BFGS");
4007 /// will set the usage of the BFGS algorithm of the GSL multi-dimensional minimization
4008 /// (implemented in libMathMore). ROOT::Math::MinimizerOptions can be used also to set other
4009 /// default options, like maximum number of function calls, minimization tolerance or print
4010 /// level. See the documentation of this class.
4011 ///
4012 /// For fitting linear functions (containing the "++" sign" and polN functions,
4013 /// the linear fitter is automatically initialized.
4014 
4015 TFitResultPtr TH1::Fit(TF1 *f1 ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
4016 {
4017  // implementation of Fit method is in file hist/src/HFitImpl.cxx
4018  Foption_t fitOption;
4020 
4021  // create range and minimizer options with default values
4022  ROOT::Fit::DataRange range(xxmin,xxmax);
4023  ROOT::Math::MinimizerOptions minOption;
4024 
4025  // need to empty the buffer before
4026  // (t.b.d. do a ML unbinned fit with buffer data)
4027  if (fBuffer) BufferEmpty();
4028 
4029  return ROOT::Fit::FitObject(this, f1 , fitOption , minOption, goption, range);
4030 }
4031 
4032 ////////////////////////////////////////////////////////////////////////////////
4033 /// Display a panel with all histogram fit options.
4034 ///
4035 /// See class TFitPanel for example
4036 
4037 void TH1::FitPanel()
4038 {
4039  if (!gPad)
4040  gROOT->MakeDefCanvas();
4041 
4042  if (!gPad) {
4043  Error("FitPanel", "Unable to create a default canvas");
4044  return;
4045  }
4046 
4047 
4048  // use plugin manager to create instance of TFitEditor
4049  TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TFitEditor");
4050  if (handler && handler->LoadPlugin() != -1) {
4051  if (handler->ExecPlugin(2, gPad, this) == 0)
4052  Error("FitPanel", "Unable to create the FitPanel");
4053  }
4054  else
4055  Error("FitPanel", "Unable to find the FitPanel plug-in");
4056 }
4057 
4058 ////////////////////////////////////////////////////////////////////////////////
4059 /// Return an histogram containing the asymmetry of this histogram with h2,
4060 /// where the asymmetry is defined as:
4061 ///
4062 /// ~~~ {.cpp}
4063 /// Asymmetry = (h1 - h2)/(h1 + h2) where h1 = this
4064 /// ~~~
4065 ///
4066 /// works for 1D, 2D, etc. histograms
4067 /// c2 is an optional argument that gives a relative weight between the two
4068 /// histograms, and dc2 is the error on this weight. This is useful, for example,
4069 /// when forming an asymmetry between two histograms from 2 different data sets that
4070 /// need to be normalized to each other in some way. The function calculates
4071 /// the errors assuming Poisson statistics on h1 and h2 (that is, dh = sqrt(h)).
4072 ///
4073 /// example: assuming 'h1' and 'h2' are already filled
4074 ///
4075 /// ~~~ {.cpp}
4076 /// h3 = h1->GetAsymmetry(h2)
4077 /// ~~~
4078 ///
4079 /// then 'h3' is created and filled with the asymmetry between 'h1' and 'h2';
4080 /// h1 and h2 are left intact.
4081 ///
4082 /// Note that it is the user's responsibility to manage the created histogram.
4083 /// The name of the returned histogram will be `Asymmetry_nameOfh1-nameOfh2`
4084 ///
4085 /// code proposed by Jason Seely (seely@mit.edu) and adapted by R.Brun
4086 ///
4087 /// clone the histograms so top and bottom will have the
4088 /// correct dimensions:
4089 /// Sumw2 just makes sure the errors will be computed properly
4090 /// when we form sums and ratios below.
4091 
4092 TH1 *TH1::GetAsymmetry(TH1* h2, Double_t c2, Double_t dc2)
4093 {
4094  TH1 *h1 = this;
4095  TString name = TString::Format("Asymmetry_%s-%s",h1->GetName(),h2->GetName() );
4096  TH1 *asym = (TH1*)Clone(name);
4097 
4098  // set also the title
4099  TString title = TString::Format("(%s - %s)/(%s+%s)",h1->GetName(),h2->GetName(),h1->GetName(),h2->GetName() );
4100  asym->SetTitle(title);
4101 
4102  asym->Sumw2();
4103  Bool_t addStatus = TH1::AddDirectoryStatus();
4105  TH1 *top = (TH1*)asym->Clone();
4106  TH1 *bottom = (TH1*)asym->Clone();
4107  TH1::AddDirectory(addStatus);
4108 
4109  // form the top and bottom of the asymmetry, and then divide:
4110  top->Add(h1,h2,1,-c2);
4111  bottom->Add(h1,h2,1,c2);
4112  asym->Divide(top,bottom);
4113 
4114  Int_t xmax = asym->GetNbinsX();
4115  Int_t ymax = asym->GetNbinsY();
4116  Int_t zmax = asym->GetNbinsZ();
4117 
4118  if (h1->fBuffer) h1->BufferEmpty(1);
4119  if (h2->fBuffer) h2->BufferEmpty(1);
4120  if (bottom->fBuffer) bottom->BufferEmpty(1);
4121 
4122  // now loop over bins to calculate the correct errors
4123  // the reason this error calculation looks complex is because of c2
4124  for(Int_t i=1; i<= xmax; i++){
4125  for(Int_t j=1; j<= ymax; j++){
4126  for(Int_t k=1; k<= zmax; k++){
4127  Int_t bin = GetBin(i, j, k);
4128  // here some bin contents are written into variables to make the error
4129  // calculation a little more legible:
4130  Double_t a = h1->RetrieveBinContent(bin);
4131  Double_t b = h2->RetrieveBinContent(bin);
4132  Double_t bot = bottom->RetrieveBinContent(bin);
4133 
4134  // make sure there are some events, if not, then the errors are set = 0
4135  // automatically.
4136  //if(bot < 1){} was changed to the next line from recommendation of Jason Seely (28 Nov 2005)
4137  if(bot < 1e-6){}
4138  else{
4139  // computation of errors by Christos Leonidopoulos
4140  Double_t dasq = h1->GetBinErrorSqUnchecked(bin);
4141  Double_t dbsq = h2->GetBinErrorSqUnchecked(bin);
4142  Double_t error = 2*TMath::Sqrt(a*a*c2*c2*dbsq + c2*c2*b*b*dasq+a*a*b*b*dc2*dc2)/(bot*bot);
4143  asym->SetBinError(i,j,k,error);
4144  }
4145  }
4146  }
4147  }
4148  delete top;
4149  delete bottom;
4150 
4151  return asym;
4152 }
4153 
4154 ////////////////////////////////////////////////////////////////////////////////
4155 /// Static function
4156 /// return the default buffer size for automatic histograms
4157 /// the parameter fgBufferSize may be changed via SetDefaultBufferSize
4158 
4160 {
4162 }
4163 
4164 ////////////////////////////////////////////////////////////////////////////////
4165 /// Return kTRUE if TH1::Sumw2 must be called when creating new histograms.
4166 /// see TH1::SetDefaultSumw2.
4167 
4169 {
4171 }
4172 
4173 ////////////////////////////////////////////////////////////////////////////////
4174 /// Return the current number of entries.
4175 
4176 Double_t TH1::GetEntries() const
4177 {
4178  if (fBuffer) {
4179  Int_t nentries = (Int_t) fBuffer[0];
4180  if (nentries > 0) return nentries;
4181  }
4182 
4183  return fEntries;
4184 }
4185 
4186 ////////////////////////////////////////////////////////////////////////////////
4187 /// Number of effective entries of the histogram.
4188 ///
4189 /// \f[
4190 /// neff = \frac{(\sum Weights )^2}{(\sum Weight^2 )}
4191 /// \f]
4192 ///
4193 /// In case of an unweighted histogram this number is equivalent to the
4194 /// number of entries of the histogram.
4195 /// For a weighted histogram, this number corresponds to the hypothetical number of unweighted entries
4196 /// a histogram would need to have the same statistical power as this weighted histogram.
4197 /// Note: The underflow/overflow are included if one has set the TH1::StatOverFlows flag
4198 /// and if the statistics has been computed at filling time.
4199 /// If a range is set in the histogram the number is computed from the given range.
4200 
4202 {
4204  this->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
4205  return (s[1] ? s[0]*s[0]/s[1] : TMath::Abs(s[0]) );
4206 }
4207 
4208 ////////////////////////////////////////////////////////////////////////////////
4209 /// Redefines TObject::GetObjectInfo.
4210 /// Displays the histogram info (bin number, contents, integral up to bin
4211 /// corresponding to cursor position px,py
4212 
4213 char *TH1::GetObjectInfo(Int_t px, Int_t py) const
4214 {
4215  return ((TH1*)this)->GetPainter()->GetObjectInfo(px,py);
4216 }
4217 
4218 ////////////////////////////////////////////////////////////////////////////////
4219 /// Return pointer to painter.
4220 /// If painter does not exist, it is created
4221 
4223 {
4224  if (!fPainter) {
4225  TString opt = option;
4226  opt.ToLower();
4227  if (opt.Contains("gl") || gStyle->GetCanvasPreferGL()) {
4228  //try to create TGLHistPainter
4229  TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TGLHistPainter");
4230 
4231  if (handler && handler->LoadPlugin() != -1)
4232  fPainter = reinterpret_cast<TVirtualHistPainter *>(handler->ExecPlugin(1, this));
4233  }
4234  }
4235 
4237 
4238  return fPainter;
4239 }
4240 
4241 ////////////////////////////////////////////////////////////////////////////////
4242 /// Compute Quantiles for this histogram
4243 /// Quantile x_q of a probability distribution Function F is defined as
4244 ///
4245 /// ~~~ {.cpp}
4246 /// F(x_q) = q with 0 <= q <= 1.
4247 /// ~~~
4248 ///
4249 /// For instance the median x_0.5 of a distribution is defined as that value
4250 /// of the random variable for which the distribution function equals 0.5:
4251 ///
4252 /// ~~~ {.cpp}
4253 /// F(x_0.5) = Probability(x < x_0.5) = 0.5
4254 /// ~~~
4255 ///
4256 /// code from Eddy Offermann, Renaissance
4257 ///
4258 /// \param[in] nprobSum maximum size of array q and size of array probSum (if given)
4259 /// \param[in] probSum array of positions where quantiles will be computed.
4260 /// - if probSum is null, probSum will be computed internally and will
4261 /// have a size = number of bins + 1 in h. it will correspond to the
4262 /// quantiles calculated at the lowest edge of the histogram (quantile=0) and
4263 /// all the upper edges of the bins.
4264 /// - if probSum is not null, it is assumed to contain at least nprobSum values.
4265 /// \param[out] q array q filled with nq quantiles
4266 /// \return value nq (<=nprobSum) with the number of quantiles computed
4267 ///
4268 /// Note that the Integral of the histogram is automatically recomputed
4269 /// if the number of entries is different of the number of entries when
4270 /// the integral was computed last time. In case you do not use the Fill
4271 /// functions to fill your histogram, but SetBinContent, you must call
4272 /// TH1::ComputeIntegral before calling this function.
4273 ///
4274 /// Getting quantiles q from two histograms and storing results in a TGraph,
4275 /// a so-called QQ-plot
4276 ///
4277 /// ~~~ {.cpp}
4278 /// TGraph *gr = new TGraph(nprob);
4279 /// h1->GetQuantiles(nprob,gr->GetX());
4280 /// h2->GetQuantiles(nprob,gr->GetY());
4281 /// gr->Draw("alp");
4282 /// ~~~
4283 ///
4284 /// Example:
4285 ///
4286 /// ~~~ {.cpp}
4287 /// void quantiles() {
4288 /// // demo for quantiles
4289 /// const Int_t nq = 20;
4290 /// TH1F *h = new TH1F("h","demo quantiles",100,-3,3);
4291 /// h->FillRandom("gaus",5000);
4292 ///
4293 /// Double_t xq[nq]; // position where to compute the quantiles in [0,1]
4294 /// Double_t yq[nq]; // array to contain the quantiles
4295 /// for (Int_t i=0;i<nq;i++) xq[i] = Float_t(i+1)/nq;
4296 /// h->GetQuantiles(nq,yq,xq);
4297 ///
4298 /// //show the original histogram in the top pad
4299 /// TCanvas *c1 = new TCanvas("c1","demo quantiles",10,10,700,900);
4300 /// c1->Divide(1,2);
4301 /// c1->cd(1);
4302 /// h->Draw();
4303 ///
4304 /// // show the quantiles in the bottom pad
4305 /// c1->cd(2);
4306 /// gPad->SetGrid();
4307 /// TGraph *gr = new TGraph(nq,xq,yq);
4308 /// gr->SetMarkerStyle(21);
4309 /// gr->Draw("alp");
4310 /// }
4311 /// ~~~
4312 
4313 Int_t TH1::GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum)
4314 {
4315  if (GetDimension() > 1) {
4316  Error("GetQuantiles","Only available for 1-d histograms");
4317  return 0;
4318  }
4319 
4320  const Int_t nbins = GetXaxis()->GetNbins();
4321  if (!fIntegral) ComputeIntegral();
4322  if (fIntegral[nbins+1] != fEntries) ComputeIntegral();
4323 
4324  Int_t i, ibin;
4325  Double_t *prob = (Double_t*)probSum;
4326  Int_t nq = nprobSum;
4327  if (probSum == 0) {
4328  nq = nbins+1;
4329  prob = new Double_t[nq];
4330  prob[0] = 0;
4331  for (i=1;i<nq;i++) {
4332  prob[i] = fIntegral[i]/fIntegral[nbins];
4333  }
4334  }
4335 
4336  for (i = 0; i < nq; i++) {
4337  ibin = TMath::BinarySearch(nbins,fIntegral,prob[i]);
4338  while (ibin < nbins-1 && fIntegral[ibin+1] == prob[i]) {
4339  if (fIntegral[ibin+2] == prob[i]) ibin++;
4340  else break;
4341  }
4342  q[i] = GetBinLowEdge(ibin+1);
4343  const Double_t dint = fIntegral[ibin+1]-fIntegral[ibin];
4344  if (dint > 0) q[i] += GetBinWidth(ibin+1)*(prob[i]-fIntegral[ibin])/dint;
4345  }
4346 
4347  if (!probSum) delete [] prob;
4348  return nq;
4349 }
4350 
4351 ////////////////////////////////////////////////////////////////////////////////
4352 /// Decode string choptin and fill fitOption structure.
4353 
4354 Int_t TH1::FitOptionsMake(Option_t *choptin, Foption_t &fitOption)
4355 {
4357  return 1;
4358 }
4359 
4360 ////////////////////////////////////////////////////////////////////////////////
4361 /// Compute Initial values of parameters for a gaussian.
4362 
4363 void H1InitGaus()
4364 {
4365  Double_t allcha, sumx, sumx2, x, val, stddev, mean;
4366  Int_t bin;
4367  const Double_t sqrtpi = 2.506628;
4368 
4369  // - Compute mean value and StdDev of the histogram in the given range
4371  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4372  Int_t hxfirst = hFitter->GetXfirst();
4373  Int_t hxlast = hFitter->GetXlast();
4374  Double_t valmax = curHist->GetBinContent(hxfirst);
4375  Double_t binwidx = curHist->GetBinWidth(hxfirst);
4376  allcha = sumx = sumx2 = 0;
4377  for (bin=hxfirst;bin<=hxlast;bin++) {
4378  x = curHist->GetBinCenter(bin);
4379  val = TMath::Abs(curHist->GetBinContent(bin));
4380  if (val > valmax) valmax = val;
4381  sumx += val*x;
4382  sumx2 += val*x*x;
4383  allcha += val;
4384  }
4385  if (allcha == 0) return;
4386  mean = sumx/allcha;
4387  stddev = sumx2/allcha - mean*mean;
4388  if (stddev > 0) stddev = TMath::Sqrt(stddev);
4389  else stddev = 0;
4390  if (stddev == 0) stddev = binwidx*(hxlast-hxfirst+1)/4;
4391  //if the distribution is really gaussian, the best approximation
4392  //is binwidx*allcha/(sqrtpi*stddev)
4393  //However, in case of non-gaussian tails, this underestimates
4394  //the normalisation constant. In this case the maximum value
4395  //is a better approximation.
4396  //We take the average of both quantities
4397  Double_t constant = 0.5*(valmax+binwidx*allcha/(sqrtpi*stddev));
4398 
4399  //In case the mean value is outside the histo limits and
4400  //the StdDev is bigger than the range, we take
4401  // mean = center of bins
4402  // stddev = half range
4403  Double_t xmin = curHist->GetXaxis()->GetXmin();
4404  Double_t xmax = curHist->GetXaxis()->GetXmax();
4405  if ((mean < xmin || mean > xmax) && stddev > (xmax-xmin)) {
4406  mean = 0.5*(xmax+xmin);
4407  stddev = 0.5*(xmax-xmin);
4408  }
4409  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4410  f1->SetParameter(0,constant);
4411  f1->SetParameter(1,mean);
4412  f1->SetParameter(2,stddev);
4413  f1->SetParLimits(2,0,10*stddev);
4414 }
4415 
4416 ////////////////////////////////////////////////////////////////////////////////
4417 /// Compute Initial values of parameters for an exponential.
4418 
4419 void H1InitExpo()
4420 {
4421  Double_t constant, slope;
4422  Int_t ifail;
4424  Int_t hxfirst = hFitter->GetXfirst();
4425  Int_t hxlast = hFitter->GetXlast();
4426  Int_t nchanx = hxlast - hxfirst + 1;
4427 
4428  H1LeastSquareLinearFit(-nchanx, constant, slope, ifail);
4429 
4430  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4431  f1->SetParameter(0,constant);
4432  f1->SetParameter(1,slope);
4433 
4434 }
4435 
4436 ////////////////////////////////////////////////////////////////////////////////
4437 /// Compute Initial values of parameters for a polynom.
4438 
4439 void H1InitPolynom()
4440 {
4441  Double_t fitpar[25];
4442 
4444  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4445  Int_t hxfirst = hFitter->GetXfirst();
4446  Int_t hxlast = hFitter->GetXlast();
4447  Int_t nchanx = hxlast - hxfirst + 1;
4448  Int_t npar = f1->GetNpar();
4449 
4450  if (nchanx <=1 || npar == 1) {
4451  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4452  fitpar[0] = curHist->GetSumOfWeights()/Double_t(nchanx);
4453  } else {
4454  H1LeastSquareFit( nchanx, npar, fitpar);
4455  }
4456  for (Int_t i=0;i<npar;i++) f1->SetParameter(i, fitpar[i]);
4457 }
4458 
4459 ////////////////////////////////////////////////////////////////////////////////
4460 /// Least squares lpolynomial fitting without weights.
4461 ///
4462 /// \param[in] n number of points to fit
4463 /// \param[in] m number of parameters
4464 /// \param[in] a array of parameters
4465 ///
4466 /// based on CERNLIB routine LSQ: Translated to C++ by Rene Brun
4467 /// (E.Keil. revised by B.Schorr, 23.10.1981.)
4468 
4469 void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a)
4470 {
4471  const Double_t zero = 0.;
4472  const Double_t one = 1.;
4473  const Int_t idim = 20;
4474 
4475  Double_t b[400] /* was [20][20] */;
4476  Int_t i, k, l, ifail;
4477  Double_t power;
4478  Double_t da[20], xk, yk;
4479 
4480  if (m <= 2) {
4481  H1LeastSquareLinearFit(n, a[0], a[1], ifail);
4482  return;
4483  }
4484  if (m > idim || m > n) return;
4485  b[0] = Double_t(n);
4486  da[0] = zero;
4487  for (l = 2; l <= m; ++l) {
4488  b[l-1] = zero;
4489  b[m + l*20 - 21] = zero;
4490  da[l-1] = zero;
4491  }
4493  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4494  Int_t hxfirst = hFitter->GetXfirst();
4495  Int_t hxlast = hFitter->GetXlast();
4496  for (k = hxfirst; k <= hxlast; ++k) {
4497  xk = curHist->GetBinCenter(k);
4498  yk = curHist->GetBinContent(k);
4499  power = one;
4500  da[0] += yk;
4501  for (l = 2; l <= m; ++l) {
4502  power *= xk;
4503  b[l-1] += power;
4504  da[l-1] += power*yk;
4505  }
4506  for (l = 2; l <= m; ++l) {
4507  power *= xk;
4508  b[m + l*20 - 21] += power;
4509  }
4510  }
4511  for (i = 3; i <= m; ++i) {
4512  for (k = i; k <= m; ++k) {
4513  b[k - 1 + (i-1)*20 - 21] = b[k + (i-2)*20 - 21];
4514  }
4515  }
4516  H1LeastSquareSeqnd(m, b, idim, ifail, 1, da);
4517 
4518  for (i=0; i<m; ++i) a[i] = da[i];
4519 
4520 }
4521 
4522 ////////////////////////////////////////////////////////////////////////////////
4523 /// Least square linear fit without weights.
4524 ///
4525 /// extracted from CERNLIB LLSQ: Translated to C++ by Rene Brun
4526 /// (added to LSQ by B. Schorr, 15.02.1982.)
4527 
4528 void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
4529 {
4530  Double_t xbar, ybar, x2bar;
4531  Int_t i, n;
4532  Double_t xybar;
4533  Double_t fn, xk, yk;
4534  Double_t det;
4535 
4536  n = TMath::Abs(ndata);
4537  ifail = -2;
4538  xbar = ybar = x2bar = xybar = 0;
4540  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4541  Int_t hxfirst = hFitter->GetXfirst();
4542  Int_t hxlast = hFitter->GetXlast();
4543  for (i = hxfirst; i <= hxlast; ++i) {
4544  xk = curHist->GetBinCenter(i);
4545  yk = curHist->GetBinContent(i);
4546  if (ndata < 0) {
4547  if (yk <= 0) yk = 1e-9;
4548  yk = TMath::Log(yk);
4549  }
4550  xbar += xk;
4551  ybar += yk;
4552  x2bar += xk*xk;
4553  xybar += xk*yk;
4554  }
4555  fn = Double_t(n);
4556  det = fn*x2bar - xbar*xbar;
4557  ifail = -1;
4558  if (det <= 0) {
4559  a0 = ybar/fn;
4560  a1 = 0;
4561  return;
4562  }
4563  ifail = 0;
4564  a0 = (x2bar*ybar - xbar*xybar) / det;
4565  a1 = (fn*xybar - xbar*ybar) / det;
4566 
4567 }
4568 
4569 ////////////////////////////////////////////////////////////////////////////////
4570 /// Extracted from CERN Program library routine DSEQN.
4571 ///
4572 /// Translated to C++ by Rene Brun
4573 
4574 void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b)
4575 {
4576  Int_t a_dim1, a_offset, b_dim1, b_offset;
4577  Int_t nmjp1, i, j, l;
4578  Int_t im1, jp1, nm1, nmi;
4579  Double_t s1, s21, s22;
4580  const Double_t one = 1.;
4581 
4582  /* Parameter adjustments */
4583  b_dim1 = idim;
4584  b_offset = b_dim1 + 1;
4585  b -= b_offset;
4586  a_dim1 = idim;
4587  a_offset = a_dim1 + 1;
4588  a -= a_offset;
4589 
4590  if (idim < n) return;
4591 
4592  ifail = 0;
4593  for (j = 1; j <= n; ++j) {
4594  if (a[j + j*a_dim1] <= 0) { ifail = -1; return; }
4595  a[j + j*a_dim1] = one / a[j + j*a_dim1];
4596  if (j == n) continue;
4597  jp1 = j + 1;
4598  for (l = jp1; l <= n; ++l) {
4599  a[j + l*a_dim1] = a[j + j*a_dim1] * a[l + j*a_dim1];
4600  s1 = -a[l + (j+1)*a_dim1];
4601  for (i = 1; i <= j; ++i) { s1 = a[l + i*a_dim1] * a[i + (j+1)*a_dim1] + s1; }
4602  a[l + (j+1)*a_dim1] = -s1;
4603  }
4604  }
4605  if (k <= 0) return;
4606 
4607  for (l = 1; l <= k; ++l) {
4608  b[l*b_dim1 + 1] = a[a_dim1 + 1]*b[l*b_dim1 + 1];
4609  }
4610  if (n == 1) return;
4611  for (l = 1; l <= k; ++l) {
4612  for (i = 2; i <= n; ++i) {
4613  im1 = i - 1;
4614  s21 = -b[i + l*b_dim1];
4615  for (j = 1; j <= im1; ++j) {
4616  s21 = a[i + j*a_dim1]*b[j + l*b_dim1] + s21;
4617  }
4618  b[i + l*b_dim1] = -a[i + i*a_dim1]*s21;
4619  }
4620  nm1 = n - 1;
4621  for (i = 1; i <= nm1; ++i) {
4622  nmi = n - i;
4623  s22 = -b[nmi + l*b_dim1];
4624  for (j = 1; j <= i; ++j) {
4625  nmjp1 = n - j + 1;
4626  s22 = a[nmi + nmjp1*a_dim1]*b[nmjp1 + l*b_dim1] + s22;
4627  }
4628  b[nmi + l*b_dim1] = -s22;
4629  }
4630  }
4631 }
4632 
4633 ////////////////////////////////////////////////////////////////////////////////
4634 /// Return Global bin number corresponding to binx,y,z.
4635 ///
4636 /// 2-D and 3-D histograms are represented with a one dimensional
4637 /// structure.
4638 /// This has the advantage that all existing functions, such as
4639 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
4640 ///
4641 /// In case of a TH1x, returns binx directly.
4642 /// see TH1::GetBinXYZ for the inverse transformation.
4643 ///
4644 /// Convention for numbering bins
4645 ///
4646 /// For all histogram types: nbins, xlow, xup
4647 ///
4648 /// - bin = 0; underflow bin
4649 /// - bin = 1; first bin with low-edge xlow INCLUDED
4650 /// - bin = nbins; last bin with upper-edge xup EXCLUDED
4651 /// - bin = nbins+1; overflow bin
4652 ///
4653 /// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4654 /// For example, assuming a 3-D histogram with binx,biny,binz, the function
4655 ///
4656 /// ~~~ {.cpp}
4657 /// Int_t bin = h->GetBin(binx,biny,binz);
4658 /// ~~~
4659 ///
4660 /// returns a global/linearized bin number. This global bin is useful
4661 /// to access the bin information independently of the dimension.
4662 
4663 Int_t TH1::GetBin(Int_t binx, Int_t, Int_t) const
4664 {
4665  Int_t ofx = fXaxis.GetNbins() + 1; // overflow bin
4666  if (binx < 0) binx = 0;
4667  if (binx > ofx) binx = ofx;
4668 
4669  return binx;
4670 }
4671 
4672 ////////////////////////////////////////////////////////////////////////////////
4673 /// Return binx, biny, binz corresponding to the global bin number globalbin
4674 /// see TH1::GetBin function above
4675 
4676 void TH1::GetBinXYZ(Int_t binglobal, Int_t &binx, Int_t &biny, Int_t &binz) const
4677 {
4679  Int_t ny = fYaxis.GetNbins()+2;
4680 
4681  if (GetDimension() == 1) {
4682  binx = binglobal%nx;
4683  biny = 0;
4684  binz = 0;
4685  return;
4686  }
4687  if (GetDimension() == 2) {
4688  binx = binglobal%nx;
4689  biny = ((binglobal-binx)/nx)%ny;
4690  binz = 0;
4691  return;
4692  }
4693  if (GetDimension() == 3) {
4694  binx = binglobal%nx;
4695  biny = ((binglobal-binx)/nx)%ny;
4696  binz = ((binglobal-binx)/nx -biny)/ny;
4697  }
4698 }
4699 
4700 ////////////////////////////////////////////////////////////////////////////////
4701 /// Return a random number distributed according the histogram bin contents.
4702 /// This function checks if the bins integral exists. If not, the integral
4703 /// is evaluated, normalized to one.
4704 ///
4705 /// The integral is automatically recomputed if the number of entries
4706 /// is not the same then when the integral was computed.
4707 /// NB Only valid for 1-d histograms. Use GetRandom2 or 3 otherwise.
4708 /// If the histogram has a bin with negative content a NaN is returned
4709 
4710 Double_t TH1::GetRandom() const
4711 {
4712  if (fDimension > 1) {
4713  Error("GetRandom","Function only valid for 1-d histograms");
4714  return 0;
4715  }
4716  Int_t nbinsx = GetNbinsX();
4717  Double_t integral = 0;
4718  // compute integral checking that all bins have positive content (see ROOT-5894)
4719  if (fIntegral) {
4720  if (fIntegral[nbinsx+1] != fEntries) integral = ((TH1*)this)->ComputeIntegral(true);
4721  else integral = fIntegral[nbinsx];
4722  } else {
4723  integral = ((TH1*)this)->ComputeIntegral(true);
4724  }
4725  if (integral == 0) return 0;
4726  // return a NaN in case some bins have negative content
4727  if (integral == TMath::QuietNaN() ) return TMath::QuietNaN();
4728 
4729  Double_t r1 = gRandom->Rndm();
4730  Int_t ibin = TMath::BinarySearch(nbinsx,fIntegral,r1);
4731  Double_t x = GetBinLowEdge(ibin+1);
4732  if (r1 > fIntegral[ibin]) x +=
4733  GetBinWidth(ibin+1)*(r1-fIntegral[ibin])/(fIntegral[ibin+1] - fIntegral[ibin]);
4734  return x;
4735 }
4736 
4737 ////////////////////////////////////////////////////////////////////////////////
4738 /// Return content of bin number bin.
4739 ///
4740 /// Implemented in TH1C,S,F,D
4741 ///
4742 /// Convention for numbering bins
4743 ///
4744 /// For all histogram types: nbins, xlow, xup
4745 ///
4746 /// - bin = 0; underflow bin
4747 /// - bin = 1; first bin with low-edge xlow INCLUDED
4748 /// - bin = nbins; last bin with upper-edge xup EXCLUDED
4749 /// - bin = nbins+1; overflow bin
4750 ///
4751 /// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4752 /// For example, assuming a 3-D histogram with binx,biny,binz, the function
4753 ///
4754 /// ~~~ {.cpp}
4755 /// Int_t bin = h->GetBin(binx,biny,binz);
4756 /// ~~~
4757 ///
4758 /// returns a global/linearized bin number. This global bin is useful
4759 /// to access the bin information independently of the dimension.
4760 
4762 {
4763  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
4764  if (bin < 0) bin = 0;
4765  if (bin >= fNcells) bin = fNcells-1;
4766 
4767  return RetrieveBinContent(bin);
4768 }
4769 
4770 ////////////////////////////////////////////////////////////////////////////////
4771 /// Compute first binx in the range [firstx,lastx] for which
4772 /// diff = abs(bin_content-c) <= maxdiff
4773 ///
4774 /// In case several bins in the specified range with diff=0 are found
4775 /// the first bin found is returned in binx.
4776 /// In case several bins in the specified range satisfy diff <=maxdiff
4777 /// the bin with the smallest difference is returned in binx.
4778 /// In all cases the function returns the smallest difference.
4779 ///
4780 /// NOTE1: if firstx <= 0, firstx is set to bin 1
4781 /// if (lastx < firstx then firstx is set to the number of bins
4782 /// ie if firstx=0 and lastx=0 (default) the search is on all bins.
4783 ///
4784 /// NOTE2: if maxdiff=0 (default), the first bin with content=c is returned.
4785 
4786 Double_t TH1::GetBinWithContent(Double_t c, Int_t &binx, Int_t firstx, Int_t lastx,Double_t maxdiff) const
4787 {
4788  if (fDimension > 1) {
4789  binx = 0;
4790  Error("GetBinWithContent","function is only valid for 1-D histograms");
4791  return 0;
4792  }
4793 
4794  if (fBuffer) ((TH1*)this)->BufferEmpty();
4795 
4796  if (firstx <= 0) firstx = 1;
4797  if (lastx < firstx) lastx = fXaxis.GetNbins();
4798  Int_t binminx = 0;
4799  Double_t diff, curmax = 1.e240;
4800  for (Int_t i=firstx;i<=lastx;i++) {
4801  diff = TMath::Abs(RetrieveBinContent(i)-c);
4802  if (diff <= 0) {binx = i; return diff;}
4803  if (diff < curmax && diff <= maxdiff) {curmax = diff, binminx=i;}
4804  }
4805  binx = binminx;
4806  return curmax;
4807 }
4808 
4809 ////////////////////////////////////////////////////////////////////////////////
4810 /// Given a point x, approximates the value via linear interpolation
4811 /// based on the two nearest bin centers
4812 ///
4813 /// Andy Mastbaum 10/21/08
4814 
4816 {
4817  if (fBuffer) ((TH1*)this)->BufferEmpty();
4818 
4819  Int_t xbin = FindBin(x);
4820  Double_t x0,x1,y0,y1;
4821 
4822  if(x<=GetBinCenter(1)) {
4823  return RetrieveBinContent(1);
4824  } else if(x>=GetBinCenter(GetNbinsX())) {
4825  return RetrieveBinContent(GetNbinsX());
4826  } else {
4827  if(x<=GetBinCenter(xbin)) {
4828  y0 = RetrieveBinContent(xbin-1);
4829  x0 = GetBinCenter(xbin-1);
4830  y1 = RetrieveBinContent(xbin);
4831  x1 = GetBinCenter(xbin);
4832  } else {
4833  y0 = RetrieveBinContent(xbin);
4834  x0 = GetBinCenter(xbin);
4835  y1 = RetrieveBinContent(xbin+1);
4836  x1 = GetBinCenter(xbin+1);
4837  }
4838  return y0 + (x-x0)*((y1-y0)/(x1-x0));
4839  }
4840 }
4841 
4842 ////////////////////////////////////////////////////////////////////////////////
4843 /// Interpolate. Not yet implemented.
4844 
4846 {
4847  Error("Interpolate","This function must be called with 1 argument for a TH1");
4848  return 0;
4849 }
4850 
4851 ////////////////////////////////////////////////////////////////////////////////
4852 /// Interpolate. Not yet implemented.
4853 
4855 {
4856  Error("Interpolate","This function must be called with 1 argument for a TH1");
4857  return 0;
4858 }
4859 
4860 ////////////////////////////////////////////////////////////////////////////////
4861 /// Return true if the bin is overflow.
4862 
4863 Bool_t TH1::IsBinOverflow(Int_t bin, Int_t iaxis) const
4864 {
4865  Int_t binx, biny, binz;
4866  GetBinXYZ(bin, binx, biny, binz);
4867 
4868  if (iaxis == 0) {
4869  if ( fDimension == 1 )
4870  return binx >= GetNbinsX() + 1;
4871  if ( fDimension == 2 )
4872  return (binx >= GetNbinsX() + 1) ||
4873  (biny >= GetNbinsY() + 1);
4874  if ( fDimension == 3 )
4875  return (binx >= GetNbinsX() + 1) ||
4876  (biny >= GetNbinsY() + 1) ||
4877  (binz >= GetNbinsZ() + 1);
4878  return kFALSE;
4879  }
4880  if (iaxis == 1)
4881  return binx >= GetNbinsX() + 1;
4882  if (iaxis == 2)
4883  return biny >= GetNbinsY() + 1;
4884  if (iaxis == 3)
4885  return binz >= GetNbinsZ() + 1;
4886 
4887  Error("IsBinOverflow","Invalid axis value");
4888  return kFALSE;
4889 }
4890 
4891 ////////////////////////////////////////////////////////////////////////////////
4892 /// Return true if the bin is underflow.
4893 /// If iaxis = 0 make OR with all axes otherwise check only for the given axis
4894 
4895 Bool_t TH1::IsBinUnderflow(Int_t bin, Int_t iaxis) const
4896 {
4897  Int_t binx, biny, binz;
4898  GetBinXYZ(bin, binx, biny, binz);
4899 
4900  if (iaxis == 0) {
4901  if ( fDimension == 1 )
4902  return (binx <= 0);
4903  else if ( fDimension == 2 )
4904  return (binx <= 0 || biny <= 0);
4905  else if ( fDimension == 3 )
4906  return (binx <= 0 || biny <= 0 || binz <= 0);
4907  else
4908  return kFALSE;
4909  }
4910  if (iaxis == 1)
4911  return (binx <= 0);
4912  if (iaxis == 2)
4913  return (biny <= 0);
4914  if (iaxis == 3)
4915  return (binz <= 0);
4916 
4917  Error("IsBinUnderflow","Invalid axis value");
4918  return kFALSE;
4919 }
4920 
4921 ////////////////////////////////////////////////////////////////////////////////
4922 /// Reduce the number of bins for the axis passed in the option to the number of bins having a label.
4923 /// The method will remove only the extra bins existing after the last "labeled" bin.
4924 /// Note that if there are "un-labeled" bins present between "labeled" bins they will not be removed
4925 
4926 void TH1::LabelsDeflate(Option_t *ax)
4927 {
4928  Int_t iaxis = AxisChoice(ax);
4929  TAxis *axis = 0;
4930  if (iaxis == 1) axis = GetXaxis();
4931  if (iaxis == 2) axis = GetYaxis();
4932  if (iaxis == 3) axis = GetZaxis();
4933  if (!axis) {
4934  Error("LabelsDeflate","Invalid axis option %s",ax);
4935  return;
4936  }
4937  if (!axis->GetLabels()) return;
4938 
4939  // find bin with last labels
4940  // bin number is object ID in list of labels
4941  // therefore max bin number is number of bins of the deflated histograms
4942  TIter next(axis->GetLabels());
4943  TObject *obj;
4944  Int_t nbins = 0;
4945  while ((obj = next())) {
4946  Int_t ibin = obj->GetUniqueID();
4947  if (ibin > nbins) nbins = ibin;
4948  }
4949  if (nbins < 1) nbins = 1;
4950 
4951  // Do nothing in case it was the last bin
4952  if (nbins==axis->GetNbins()) return;
4953 
4954  TH1 *hold = (TH1*)IsA()->New();
4955  R__ASSERT(hold);
4956  hold->SetDirectory(0);
4957  Copy(*hold);
4958 
4959  Bool_t timedisp = axis->GetTimeDisplay();
4960  Double_t xmin = axis->GetXmin();
4961  Double_t xmax = axis->GetBinUpEdge(nbins);
4962  if (xmax <= xmin) xmax = xmin +nbins;
4963  axis->SetRange(0,0);
4964  axis->Set(nbins,xmin,xmax);
4965  SetBinsLength(-1); // reset the number of cells
4966  Int_t errors = fSumw2.fN;
4967  if (errors) fSumw2.Set(fNcells);
4968  axis->SetTimeDisplay(timedisp);
4969  // reset histogram content
4970  Reset("ICE");
4971 
4972  //now loop on all bins and refill
4973  // NOTE that if the bins without labels have content
4974  // it will be put in the underflow/overflow.
4975  // For this reason we use AddBinContent method
4976  Double_t oldEntries = fEntries;
4977  Int_t bin,binx,biny,binz;
4978  for (bin=0; bin < hold->fNcells; ++bin) {
4979  hold->GetBinXYZ(bin,binx,biny,binz);
4980  Int_t ibin = GetBin(binx,biny,binz);
4981  Double_t cu = hold->RetrieveBinContent(bin);
4982  AddBinContent(ibin,cu);
4983  if (errors) {
4984  fSumw2.fArray[ibin] += hold->fSumw2.fArray[bin];
4985  }
4986  }
4987  fEntries = oldEntries;
4988  delete hold;
4989 }
4990 
4991 ////////////////////////////////////////////////////////////////////////////////
4992 /// Double the number of bins for axis.
4993 /// Refill histogram
4994 /// This function is called by TAxis::FindBin(const char *label)
4995 
4996 void TH1::LabelsInflate(Option_t *ax)
4997 {
4998  Int_t iaxis = AxisChoice(ax);
4999  TAxis *axis = 0;
5000  if (iaxis == 1) axis = GetXaxis();
5001  if (iaxis == 2) axis = GetYaxis();
5002  if (iaxis == 3) axis = GetZaxis();
5003  if (!axis) return;
5004 
5005  TH1 *hold = (TH1*)IsA()->New();;
5006  hold->SetDirectory(0);
5007  Copy(*hold);
5008 
5009  Bool_t timedisp = axis->GetTimeDisplay();
5010  Int_t nbins = axis->GetNbins();
5011  Double_t xmin = axis->GetXmin();
5012  Double_t xmax = axis->GetXmax();
5013  xmax = xmin + 2*(xmax-xmin);
5014  axis->SetRange(0,0);
5015  // double the bins and recompute ncells
5016  axis->Set(2*nbins,xmin,xmax);
5017  SetBinsLength(-1);
5018  Int_t errors = fSumw2.fN;
5019  if (errors) fSumw2.Set(fNcells);
5020  axis->SetTimeDisplay(timedisp);
5021 
5022  Reset("ICE"); // reset content and error
5023 
5024  //now loop on all bins and refill
5025  Double_t oldEntries = fEntries;
5026  Int_t bin,ibin,binx,biny,binz;
5027  for (ibin =0; ibin < hold->fNcells; ibin++) {
5028  // get the binx,y,z values . The x-y-z (axis) bin values will stay the same between new-old after the expanding
5029  hold->GetBinXYZ(ibin,binx,biny,binz);
5030  bin = GetBin(binx,biny,binz);
5031 
5032  // underflow and overflow will be cleaned up because their meaning has been altered
5033  if (hold->IsBinUnderflow(ibin,iaxis) || hold->IsBinOverflow(ibin,iaxis)) {
5034  continue;
5035  }
5036  else {
5037  AddBinContent(bin, hold->RetrieveBinContent(ibin));
5038  if (errors) fSumw2.fArray[bin] += hold->fSumw2.fArray[ibin];
5039  }
5040  }
5041  fEntries = oldEntries;
5042  delete hold;
5043 }
5044 
5045 ////////////////////////////////////////////////////////////////////////////////
5046 /// Set option(s) to draw axis with labels
5047 /// \param[in] option
5048 /// - "a" sort by alphabetic order
5049 /// - ">" sort by decreasing values
5050 /// - "<" sort by increasing values
5051 /// - "h" draw labels horizontal
5052 /// - "v" draw labels vertical
5053 /// - "u" draw labels up (end of label right adjusted)
5054 /// - "d" draw labels down (start of label left adjusted)
5055 /// \param[in] ax axis
5056 
5057 void TH1::LabelsOption(Option_t *option, Option_t *ax)
5058 {
5059  Int_t iaxis = AxisChoice(ax);
5060  TAxis *axis = 0;
5061  if (iaxis == 1) axis = GetXaxis();
5062  if (iaxis == 2) axis = GetYaxis();
5063  if (iaxis == 3) axis = GetZaxis();
5064  if (!axis) return;
5065  THashList *labels = axis->GetLabels();
5066  if (!labels) {
5067  Warning("LabelsOption","Cannot sort. No labels");
5068  return;
5069  }
5070  TString opt = option;
5071  opt.ToLower();
5072  if (opt.Contains("h")) {
5073  axis->SetBit(TAxis::kLabelsHori);
5076  axis->ResetBit(TAxis::kLabelsUp);
5077  }
5078  if (opt.Contains("v")) {
5079  axis->SetBit(TAxis::kLabelsVert);
5082  axis->ResetBit(TAxis::kLabelsUp);
5083  }
5084  if (opt.Contains("u")) {
5085  axis->SetBit(TAxis::kLabelsUp);
5089  }
5090  if (opt.Contains("d")) {
5091  axis->SetBit(TAxis::kLabelsDown);
5094  axis->ResetBit(TAxis::kLabelsUp);
5095  }
5096  Int_t sort = -1;
5097  if (opt.Contains("a")) sort = 0;
5098  if (opt.Contains(">")) sort = 1;
5099  if (opt.Contains("<")) sort = 2;
5100  if (sort < 0) return;
5101  if (sort > 0 && GetDimension() > 2) {
5102  Error("LabelsOption","Sorting by value not implemented for 3-D histograms");
5103  return;
5104  }
5105 
5106  Double_t entries = fEntries;
5107  Int_t n = TMath::Min(axis->GetNbins(), labels->GetSize());
5108  std::vector<Int_t> a(n+2);
5109 
5110  Int_t i,j,k;
5111  std::vector<Double_t> cont;
5112  std::vector<Double_t> errors;
5113  THashList *labold = new THashList(labels->GetSize(),1);
5114  TIter nextold(labels);
5115  TObject *obj;
5116  while ((obj=nextold())) {
5117  labold->Add(obj);
5118  }
5119  labels->Clear();
5120  if (sort > 0) {
5121  //---sort by values of bins
5122  if (GetDimension() == 1) {
5123  cont.resize(n);
5124  if (fSumw2.fN) errors.resize(n);
5125  for (i=1;i<=n;i++) {
5126  cont[i-1] = GetBinContent(i);
5127  if (!errors.empty()) errors[i-1] = GetBinError(i);
5128  }
5129  if (sort ==1) TMath::Sort(n,cont.data(),a.data(),kTRUE); //sort by decreasing values
5130  else TMath::Sort(n,cont.data(),a.data(),kFALSE); //sort by increasing values
5131  for (i=1;i<=n;i++) {
5132  SetBinContent(i,cont[a[i-1]]);
5133  if (!errors.empty()) SetBinError(i,errors[a[i-1]]);
5134  }
5135  for (i=1;i<=n;i++) {
5136  obj = labold->At(a[i-1]);
5137  labels->Add(obj);
5138  obj->SetUniqueID(i);
5139  }
5140  } else if (GetDimension()== 2) {
5141  std::vector<Double_t> pcont(n+2);
5142  Int_t nx = fXaxis.GetNbins();
5143  Int_t ny = fYaxis.GetNbins();
5144  cont.resize( (nx+2)*(ny+2));
5145  if (fSumw2.fN) errors.resize( (nx+2)*(ny+2));
5146  for (i=1;i<=nx;i++) {
5147  for (j=1;j<=ny;j++) {
5148  cont[i+nx*j] = GetBinContent(i,j);
5149  if (!errors.empty()) errors[i+nx*j] = GetBinError(i,j);
5150  if (axis == GetXaxis()) k = i;
5151  else k = j;
5152  pcont[k-1] += cont[i+nx*j];
5153  }
5154  }
5155  if (sort ==1) TMath::Sort(n,pcont.data(),a.data(),kTRUE); //sort by decreasing values
5156  else TMath::Sort(n,pcont.data(),a.data(),kFALSE); //sort by increasing values
5157  for (i=0;i<n;i++) {
5158  obj = labold->At(a[i]);
5159  labels->Add(obj);
5160  obj->SetUniqueID(i+1);
5161  }
5162  if (axis == GetXaxis()) {
5163  for (i=1;i<=n;i++) {
5164  for (j=1;j<=ny;j++) {
5165  SetBinContent(i,j,cont[a[i-1]+1+nx*j]);
5166  if (!errors.empty()) SetBinError(i,j,errors[a[i-1]+1+nx*j]);
5167  }
5168  }
5169  }
5170  else {
5171  // using y axis
5172  for (i=1;i<=nx;i++) {
5173  for (j=1;j<=n;j++) {
5174  SetBinContent(i,j,cont[i+nx*(a[j-1]+1)]);
5175  if (!errors.empty()) SetBinError(i,j,errors[i+nx*(a[j-1]+1)]);
5176  }
5177  }
5178  }
5179  } else {
5180  //to be implemented for 3d
5181  }
5182  } else {
5183  //---alphabetic sort
5184  const UInt_t kUsed = 1<<18;
5185  TObject *objk=0;
5186  a[0] = 0;
5187  a[n+1] = n+1;
5188  for (i=1;i<=n;i++) {
5189  const char *label = "zzzzzzzzzzzz";
5190  for (j=1;j<=n;j++) {
5191  obj = labold->At(j-1);
5192  if (!obj) continue;
5193  if (obj->TestBit(kUsed)) continue;
5194  //use strcasecmp for case non-sensitive sort (may be an option)
5195  if (strcmp(label,obj->GetName()) < 0) continue;
5196  objk = obj;
5197  a[i] = j;
5198  label = obj->GetName();
5199  }
5200  if (objk) {
5201  objk->SetUniqueID(i);
5202  labels->Add(objk);
5203  objk->SetBit(kUsed);
5204  }
5205  }
5206  for (i=1;i<=n;i++) {
5207  obj = labels->At(i-1);
5208  if (!obj) continue;
5209  obj->ResetBit(kUsed);
5210  }
5211 
5212  if (GetDimension() == 1) {
5213  cont.resize(n+2);
5214  if (fSumw2.fN) errors.resize(n+2);
5215  for (i=1;i<=n;i++) {
5216  cont[i] = GetBinContent(a[i]);
5217  if (!errors.empty()) errors[i] = GetBinError(a[i]);
5218  }
5219  for (i=1;i<=n;i++) {
5220  SetBinContent(i,cont[i]);
5221  if (!errors.empty()) SetBinError(i,errors[i]);
5222  }
5223  } else if (GetDimension()== 2) {
5224  Int_t nx = fXaxis.GetNbins()+2;
5225  Int_t ny = fYaxis.GetNbins()+2;
5226  cont.resize(nx*ny);
5227  if (fSumw2.fN) errors.resize(nx*ny);
5228  for (i=0;i<nx;i++) {
5229  for (j=0;j<ny;j++) {
5230  cont[i+nx*j] = GetBinContent(i,j);
5231  if (!errors.empty()) errors[i+nx*j] = GetBinError(i,j);
5232  }
5233  }
5234  if (axis == GetXaxis()) {
5235  for (i=1;i<=n;i++) {
5236  for (j=0;j<ny;j++) {
5237  SetBinContent(i,j,cont[a[i]+nx*j]);
5238  if (!errors.empty()) SetBinError(i,j,errors[a[i]+nx*j]);
5239  }
5240  }
5241  } else {
5242  for (i=0;i<nx;i++) {
5243  for (j=1;j<=n;j++) {
5244  SetBinContent(i,j,cont[i+nx*a[j]]);
5245  if (!errors.empty()) SetBinError(i,j,errors[i+nx*a[j]]);
5246  }
5247  }
5248  }
5249  } else {
5250  Int_t nx = fXaxis.GetNbins()+2;
5251  Int_t ny = fYaxis.GetNbins()+2;
5252  Int_t nz = fZaxis.GetNbins()+2;
5253  cont.resize(nx*ny*nz);
5254  if (fSumw2.fN) errors.resize(nx*ny*nz);
5255  for (i=0;i<nx;i++) {
5256  for (j=0;j<ny;j++) {
5257  for (k=0;k<nz;k++) {
5258  cont[i+nx*(j+ny*k)] = GetBinContent(i,j,k);
5259  if (!errors.empty()) errors[i+nx*(j+ny*k)] = GetBinError(i,j,k);
5260  }
5261  }
5262  }
5263  if (axis == GetXaxis()) {
5264  // labels on x axis
5265  for (i=1;i<=n;i++) {
5266  for (j=0;j<ny;j++) {
5267  for (k=0;k<nz;k++) {
5268  SetBinContent(i,j,k,cont[a[i]+nx*(j+ny*k)]);
5269  if (!errors.empty()) SetBinError(i,j,k,errors[a[i]+nx*(j+ny*k)]);
5270  }
5271  }
5272  }
5273  }
5274  else if (axis == GetYaxis()) {
5275  // labels on y axis
5276  for (i=0;i<nx;i++) {
5277  for (j=1;j<=n;j++) {
5278  for (k=0;k<nz;k++) {
5279  SetBinContent(i,j,k,cont[i+nx*(a[j]+ny*k)]);
5280  if (!errors.empty()) SetBinError(i,j,k,errors[i+nx*(a[j]+ny*k)]);
5281  }
5282  }
5283  }
5284  }
5285  else {
5286  // labels on z axis
5287  for (i=0;i<nx;i++) {
5288  for (j=0;j<ny;j++) {
5289  for (k=1;k<=n;k++) {
5290  SetBinContent(i,j,k,cont[i+nx*(j+ny*a[k])]);
5291  if (!errors.empty()) SetBinError(i,j,k,errors[i+nx*(j+ny*a[k])]);
5292  }
5293  }
5294  }
5295  }
5296  }
5297  }
5298  fEntries = entries;
5299  delete labold;
5300 }
5301 
5302 ////////////////////////////////////////////////////////////////////////////////
5303 /// Test if two double are almost equal.
5304 
5305 static inline Bool_t AlmostEqual(Double_t a, Double_t b, Double_t epsilon = 0.00000001)
5306 {
5307  return TMath::Abs(a - b) < epsilon;
5308 }
5309 
5310 ////////////////////////////////////////////////////////////////////////////////
5311 /// Test if a double is almost an integer.
5312 
5313 static inline Bool_t AlmostInteger(Double_t a, Double_t epsilon = 0.00000001)
5314 {
5315  return AlmostEqual(a - TMath::Floor(a), 0, epsilon) ||
5316  AlmostEqual(a - TMath::Floor(a), 1, epsilon);
5317 }
5318 
5319 ////////////////////////////////////////////////////////////////////////////////
5320 /// Test if the binning is equidistant.
5321 
5322 static inline bool IsEquidistantBinning(const TAxis& axis)
5323 {
5324  // check if axis bin are equals
5325  if (!axis.GetXbins()->fN) return true; //
5326  // not able to check if there is only one axis entry
5327  bool isEquidistant = true;
5328  const Double_t firstBinWidth = axis.GetBinWidth(1);
5329  for (int i = 1; i < axis.GetNbins(); ++i) {
5330  const Double_t binWidth = axis.GetBinWidth(i);
5331  const bool match = TMath::AreEqualRel(firstBinWidth, binWidth, TMath::Limits<Double_t>::Epsilon());
5332  isEquidistant &= match;
5333  if (!match)
5334  break;
5335  }
5336  return isEquidistant;
5337 }
5338 
5339 ////////////////////////////////////////////////////////////////////////////////
5340 /// Same limits and bins.
5341 
5342 Bool_t TH1::SameLimitsAndNBins(const TAxis& axis1, const TAxis& axis2)
5343 {
5344  return axis1.GetNbins() == axis2.GetNbins()
5345  && axis1.GetXmin() == axis2.GetXmin()
5346  && axis1.GetXmax() == axis2.GetXmax();
5347 }
5348 
5349 ////////////////////////////////////////////////////////////////////////////////
5350 /// Finds new limits for the axis for the Merge function.
5351 /// returns false if the limits are incompatible
5352 
5353 Bool_t TH1::RecomputeAxisLimits(TAxis& destAxis, const TAxis& anAxis)
5354 {
5355  if (SameLimitsAndNBins(destAxis, anAxis))
5356  return kTRUE;
5357 
5358  if (!IsEquidistantBinning(destAxis) || !IsEquidistantBinning(anAxis))
5359  return kFALSE; // not equidistant user binning not supported
5360 
5361  Double_t width1 = destAxis.GetBinWidth(0);
5362  Double_t width2 = anAxis.GetBinWidth(0);
5363  if (width1 == 0 || width2 == 0)
5364  return kFALSE; // no binning not supported
5365 
5366  Double_t xmin = TMath::Min(destAxis.GetXmin(), anAxis.GetXmin());
5367  Double_t xmax = TMath::Max(destAxis.GetXmax(), anAxis.GetXmax());
5368  Double_t width = TMath::Max(width1, width2);
5369 
5370  // check the bin size
5371  if (!AlmostInteger(width/width1) || !AlmostInteger(width/width2))
5372  return kFALSE;
5373 
5374  // std::cout << "Find new limit using given axis " << anAxis.GetXmin() << " , " << anAxis.GetXmax() << " bin width " << width2 << std::endl;
5375  // std::cout << " and destination axis " << destAxis.GetXmin() << " , " << destAxis.GetXmax() << " bin width " << width1 << std::endl;
5376 
5377 
5378  // check the limits
5379  Double_t delta;
5380  delta = (destAxis.GetXmin() - xmin)/width1;
5381  if (!AlmostInteger(delta))
5382  xmin -= (TMath::Ceil(delta) - delta)*width1;
5383 
5384  delta = (anAxis.GetXmin() - xmin)/width2;
5385  if (!AlmostInteger(delta))
5386  xmin -= (TMath::Ceil(delta) - delta)*width2;
5387 
5388 
5389  delta = (destAxis.GetXmin() - xmin)/width1;
5390  if (!AlmostInteger(delta))
5391  return kFALSE;
5392 
5393 
5394  delta = (xmax - destAxis.GetXmax())/width1;
5395  if (!AlmostInteger(delta))
5396  xmax += (TMath::Ceil(delta) - delta)*width1;
5397 
5398 
5399  delta = (xmax - anAxis.GetXmax())/width2;
5400  if (!AlmostInteger(delta))
5401  xmax += (TMath::Ceil(delta) - delta)*width2;
5402 
5403 
5404  delta = (xmax - destAxis.GetXmax())/width1;
5405  if (!AlmostInteger(delta))
5406  return kFALSE;
5407 #ifdef DEBUG
5408  if (!AlmostInteger((xmax - xmin) / width)) { // unnecessary check
5409  printf("TH1::RecomputeAxisLimits - Impossible\n");
5410  return kFALSE;
5411  }
5412 #endif
5413 
5414 
5415  destAxis.Set(TMath::Nint((xmax - xmin)/width), xmin, xmax);
5416 
5417  //std::cout << "New re-computed axis : [ " << xmin << " , " << xmax << " ] width = " << width << " nbins " << destAxis.GetNbins() << std::endl;
5418 
5419  return kTRUE;
5420 }
5421 
5422 ////////////////////////////////////////////////////////////////////////////////
5423 /// Add all histograms in the collection to this histogram.
5424 /// This function computes the min/max for the x axis,
5425 /// compute a new number of bins, if necessary,
5426 /// add bin contents, errors and statistics.
5427 /// If all histograms have bin labels, bins with identical labels
5428 /// will be merged, no matter what their order is.
5429 /// If overflows are present and limits are different the function will fail.
5430 /// The function returns the total number of entries in the result histogram
5431 /// if the merge is successful, -1 otherwise.
5432 ///
5433 /// IMPORTANT remark. The axis x may have different number
5434 /// of bins and different limits, BUT the largest bin width must be
5435 /// a multiple of the smallest bin width and the upper limit must also
5436 /// be a multiple of the bin width.
5437 /// Example:
5438 ///
5439 /// ~~~ {.cpp}
5440 /// void atest() {
5441 /// TH1F *h1 = new TH1F("h1","h1",110,-110,0);
5442 /// TH1F *h2 = new TH1F("h2","h2",220,0,110);
5443 /// TH1F *h3 = new TH1F("h3","h3",330,-55,55);
5444 /// TRandom r;
5445 /// for (Int_t i=0;i<10000;i++) {
5446 /// h1->Fill(r.Gaus(-55,10));
5447 /// h2->Fill(r.Gaus(55,10));
5448 /// h3->Fill(r.Gaus(0,10));
5449 /// }
5450 ///
5451 /// TList *list = new TList;
5452 /// list->Add(h1);
5453 /// list->Add(h2);
5454 /// list->Add(h3);
5455 /// TH1F *h = (TH1F*)h1->Clone("h");
5456 /// h->Reset();
5457 /// h->Merge(list);
5458 /// h->Draw();
5459 /// }
5460 /// ~~~
5461 
5463 {
5464  if (!li) return 0;
5465  if (li->IsEmpty()) return (Long64_t) GetEntries();
5466 
5467  // use TH1Merger class
5468  TH1Merger merger(*this,*li);
5469  Bool_t ret = merger();
5470 
5471  return (ret) ? GetEntries() : -1;
5472 }
5473 
5474 
5475 ////////////////////////////////////////////////////////////////////////////////
5476 /// Performs the operation: this = this*c1*f1
5477 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
5478 ///
5479 /// Only bins inside the function range are recomputed.
5480 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5481 /// you should call Sumw2 before making this operation.
5482 /// This is particularly important if you fit the histogram after TH1::Multiply
5483 ///
5484 /// The function return kFALSE if the Multiply operation failed
5485 
5487 {
5488  if (!f1) {
5489  Error("Add","Attempt to multiply by a non-existing function");
5490  return kFALSE;
5491  }
5492 
5493  // delete buffer if it is there since it will become invalid
5494  if (fBuffer) BufferEmpty(1);
5495 
5496  Int_t nx = GetNbinsX() + 2; // normal bins + uf / of (cells)
5497  Int_t ny = GetNbinsY() + 2;
5498  Int_t nz = GetNbinsZ() + 2;
5499  if (fDimension < 2) ny = 1;
5500  if (fDimension < 3) nz = 1;
5501 
5502  // reset min-maximum
5503  SetMinimum();
5504  SetMaximum();
5505 
5506  // - Loop on bins (including underflows/overflows)
5507  Double_t xx[3];
5508  Double_t *params = 0;
5509  f1->InitArgs(xx,params);
5510 
5511  for (Int_t binz = 0; binz < nz; ++binz) {
5512  xx[2] = fZaxis.GetBinCenter(binz);
5513  for (Int_t biny = 0; biny < ny; ++biny) {
5514  xx[1] = fYaxis.GetBinCenter(biny);
5515  for (Int_t binx = 0; binx < nx; ++binx) {
5516  xx[0] = fXaxis.GetBinCenter(binx);
5517  if (!f1->IsInside(xx)) continue;
5519  Int_t bin = binx + nx * (biny + ny *binz);
5520  Double_t cu = c1*f1->EvalPar(xx);
5521  if (TF1::RejectedPoint()) continue;
5522  UpdateBinContent(bin, RetrieveBinContent(bin) * cu);
5523  if (fSumw2.fN) {
5524  fSumw2.fArray[bin] = cu * cu * GetBinErrorSqUnchecked(bin);
5525  }
5526  }
5527  }
5528  }
5529  ResetStats();
5530  return kTRUE;
5531 }
5532 
5533 ////////////////////////////////////////////////////////////////////////////////
5534 /// Multiply this histogram by h1.
5535 ///
5536 /// `this = this*h1`
5537 ///
5538 /// If errors of this are available (TH1::Sumw2), errors are recalculated.
5539 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
5540 /// if not already set.
5541 ///
5542 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5543 /// you should call Sumw2 before making this operation.
5544 /// This is particularly important if you fit the histogram after TH1::Multiply
5545 ///
5546 /// The function return kFALSE if the Multiply operation failed
5547 
5548 Bool_t TH1::Multiply(const TH1 *h1)
5549 {
5550  if (!h1) {
5551  Error("Multiply","Attempt to multiply by a non-existing histogram");
5552  return kFALSE;
5553  }
5554 
5555  // delete buffer if it is there since it will become invalid
5556  if (fBuffer) BufferEmpty(1);
5557 
5558  try {
5559  CheckConsistency(this,h1);
5560  } catch(DifferentNumberOfBins&) {
5561  Error("Multiply","Attempt to multiply histograms with different number of bins");
5562  return kFALSE;
5563  } catch(DifferentAxisLimits&) {
5564  Warning("Multiply","Attempt to multiply histograms with different axis limits");
5565  } catch(DifferentBinLimits&) {
5566  Warning("Multiply","Attempt to multiply histograms with different bin limits");
5567  } catch(DifferentLabels&) {
5568  Warning("Multiply","Attempt to multiply histograms with different labels");
5569  }
5570 
5571  // Create Sumw2 if h1 has Sumw2 set
5572  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
5573 
5574  // - Reset min- maximum
5575  SetMinimum();
5576  SetMaximum();
5577 
5578  // - Loop on bins (including underflows/overflows)
5579  for (Int_t i = 0; i < fNcells; ++i) {
5580  Double_t c0 = RetrieveBinContent(i);
5581  Double_t c1 = h1->RetrieveBinContent(i);
5582  UpdateBinContent(i, c0 * c1);
5583  if (fSumw2.fN) {
5584  fSumw2.fArray[i] = GetBinErrorSqUnchecked(i) * c1 * c1 + h1->GetBinErrorSqUnchecked(i) * c0 * c0;
5585  }
5586  }
5587  ResetStats();
5588  return kTRUE;
5589 }
5590 
5591 ////////////////////////////////////////////////////////////////////////////////
5592 /// Replace contents of this histogram by multiplication of h1 by h2.
5593 ///
5594 /// `this = (c1*h1)*(c2*h2)`
5595 ///
5596 /// If errors of this are available (TH1::Sumw2), errors are recalculated.
5597 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
5598 /// if not already set.
5599 ///
5600 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5601 /// you should call Sumw2 before making this operation.
5602 /// This is particularly important if you fit the histogram after TH1::Multiply
5603 ///
5604 /// The function return kFALSE if the Multiply operation failed
5605 
5606 Bool_t TH1::Multiply(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2, Option_t *option)
5607 {
5608  TString opt = option;
5609  opt.ToLower();
5610  // Bool_t binomial = kFALSE;
5611  // if (opt.Contains("b")) binomial = kTRUE;
5612  if (!h1 || !h2) {
5613  Error("Multiply","Attempt to multiply by a non-existing histogram");
5614  return kFALSE;
5615  }
5616 
5617  // delete buffer if it is there since it will become invalid
5618  if (fBuffer) BufferEmpty(1);
5619 
5620  try {
5621  CheckConsistency(h1,h2);
5622  CheckConsistency(this,h1);
5623  } catch(DifferentNumberOfBins&) {
5624  Error("Multiply","Attempt to multiply histograms with different number of bins");
5625  return kFALSE;
5626  } catch(DifferentAxisLimits&) {
5627  Warning("Multiply","Attempt to multiply histograms with different axis limits");
5628  } catch(DifferentBinLimits&) {
5629  Warning("Multiply","Attempt to multiply histograms with different bin limits");
5630  } catch(DifferentLabels&) {
5631  Warning("Multiply","Attempt to multiply histograms with different labels");
5632  }
5633 
5634  // Create Sumw2 if h1 or h2 have Sumw2 set
5635  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
5636 
5637  // - Reset min - maximum
5638  SetMinimum();
5639  SetMaximum();
5640 
5641  // - Loop on bins (including underflows/overflows)
5642  Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
5643  for (Int_t i = 0; i < fNcells; ++i) {
5644  Double_t b1 = h1->RetrieveBinContent(i);
5645  Double_t b2 = h2->RetrieveBinContent(i);
5646  UpdateBinContent(i, c1 * b1 * c2 * b2);
5647  if (fSumw2.fN) {
5648  fSumw2.fArray[i] = c1sq * c2sq * (h1->GetBinErrorSqUnchecked(i) * b2 * b2 + h2->GetBinErrorSqUnchecked(i) * b1 * b1);
5649  }
5650  }
5651  ResetStats();
5652  return kTRUE;
5653 }
5654 
5655 ////////////////////////////////////////////////////////////////////////////////
5656 /// Control routine to paint any kind of histograms.
5657 ///
5658 /// This function is automatically called by TCanvas::Update.
5659 /// (see TH1::Draw for the list of options)
5660 
5661 void TH1::Paint(Option_t *option)
5662 {
5663  GetPainter(option);
5664 
5665  if (fPainter) {
5666  if (strlen(option) > 0) fPainter->Paint(option);
5667  else fPainter->Paint(fOption.Data());
5668  }
5669 }
5670 
5671 ////////////////////////////////////////////////////////////////////////////////
5672 /// Rebin this histogram
5673 ///
5674 /// #### case 1 xbins=0
5675 ///
5676 /// If newname is blank (default), the current histogram is modified and
5677 /// a pointer to it is returned.
5678 ///
5679 /// If newname is not blank, the current histogram is not modified, and a
5680 /// new histogram is returned which is a Clone of the current histogram
5681 /// with its name set to newname.
5682 ///
5683 /// The parameter ngroup indicates how many bins of this have to be merged
5684 /// into one bin of the result.
5685 ///
5686 /// If the original histogram has errors stored (via Sumw2), the resulting
5687 /// histograms has new errors correctly calculated.
5688 ///
5689 /// examples: if h1 is an existing TH1F histogram with 100 bins
5690 ///
5691 /// ~~~ {.cpp}
5692 /// h1->Rebin(); //merges two bins in one in h1: previous contents of h1 are lost
5693 /// h1->Rebin(5); //merges five bins in one in h1
5694 /// TH1F *hnew = dynamic_cast<TH1F*>(h1->Rebin(5,"hnew")); // creates a new histogram hnew
5695 /// // merging 5 bins of h1 in one bin
5696 /// ~~~
5697 ///
5698 /// NOTE: If ngroup is not an exact divider of the number of bins,
5699 /// the top limit of the rebinned histogram is reduced
5700 /// to the upper edge of the last bin that can make a complete
5701 /// group. The remaining bins are added to the overflow bin.
5702 /// Statistics will be recomputed from the new bin contents.
5703 ///
5704 /// #### case 2 xbins!=0
5705 ///
5706 /// A new histogram is created (you should specify newname).
5707 /// The parameter ngroup is the number of variable size bins in the created histogram.
5708 /// The array xbins must contain ngroup+1 elements that represent the low-edges
5709 /// of the bins.
5710 /// If the original histogram has errors stored (via Sumw2), the resulting
5711 /// histograms has new errors correctly calculated.
5712 ///
5713 /// NOTE: The bin edges specified in xbins should correspond to bin edges
5714 /// in the original histogram. If a bin edge in the new histogram is
5715 /// in the middle of a bin in the original histogram, all entries in
5716 /// the split bin in the original histogram will be transfered to the
5717 /// lower of the two possible bins in the new histogram. This is
5718 /// probably not what you want.
5719 ///
5720 /// examples: if h1 is an existing TH1F histogram with 100 bins
5721 ///
5722 /// ~~~ {.cpp}
5723 /// Double_t xbins[25] = {...} array of low-edges (xbins[25] is the upper edge of last bin
5724 /// h1->Rebin(24,"hnew",xbins); //creates a new variable bin size histogram hnew
5725 /// ~~~
5726 
5727 TH1 *TH1::Rebin(Int_t ngroup, const char*newname, const Double_t *xbins)
5728 {
5729  Int_t nbins = fXaxis.GetNbins();
5730  Double_t xmin = fXaxis.GetXmin();
5731  Double_t xmax = fXaxis.GetXmax();
5732  if ((ngroup <= 0) || (ngroup > nbins)) {
5733  Error("Rebin", "Illegal value of ngroup=%d",ngroup);
5734  return 0;
5735  }
5736 
5737  if (fDimension > 1 || InheritsFrom(TProfile::Class())) {
5738  Error("Rebin", "Operation valid on 1-D histograms only");
5739  return 0;
5740  }
5741  if (!newname && xbins) {
5742  Error("Rebin","if xbins is specified, newname must be given");
5743  return 0;
5744  }
5745 
5746  Int_t newbins = nbins/ngroup;
5747  if (!xbins) {
5748  Int_t nbg = nbins/ngroup;
5749  if (nbg*ngroup != nbins) {
5750  Warning("Rebin", "ngroup=%d is not an exact divider of nbins=%d.",ngroup,nbins);
5751  }
5752  }
5753  else {
5754  // in the case that xbins is given (rebinning in variable bins), ngroup is
5755  // the new number of bins and number of grouped bins is not constant.
5756  // when looping for setting the contents for the new histogram we
5757  // need to loop on all bins of original histogram. Then set ngroup=nbins
5758  newbins = ngroup;
5759  ngroup = nbins;
5760  }
5761 
5762  // Save old bin contents into a new array
5763  Double_t entries = fEntries;
5764  Double_t *oldBins = new Double_t[nbins+2];
5765  Int_t bin, i;
5766  for (bin=0;bin<nbins+2;bin++) oldBins[bin] = RetrieveBinContent(bin);
5767  Double_t *oldErrors = 0;
5768  if (fSumw2.fN != 0) {
5769  oldErrors = new Double_t[nbins+2];
5770  for (bin=0;bin<nbins+2;bin++) oldErrors[bin] = GetBinError(bin);
5771  }
5772  // rebin will not include underflow/overflow if new axis range is larger than old axis range
5773  if (xbins) {
5774  if (xbins[0] < fXaxis.GetXmin() && oldBins[0] != 0 )
5775  Warning("Rebin","underflow entries will not be used when rebinning");
5776  if (xbins[newbins] > fXaxis.GetXmax() && oldBins[nbins+1] != 0 )
5777  Warning("Rebin","overflow entries will not be used when rebinning");
5778  }
5779 
5780 
5781  // create a clone of the old histogram if newname is specified
5782  TH1 *hnew = this;
5783  if ((newname && strlen(newname) > 0) || xbins) {
5784  hnew = (TH1*)Clone(newname);
5785  }
5786 
5787  //reset can extend bit to avoid an axis extension in SetBinContent
5788  UInt_t oldExtendBitMask = hnew->SetCanExtend(kNoAxis);
5789 
5790  // save original statistics
5791  Double_t stat[kNstat];
5792  GetStats(stat);
5793  bool resetStat = false;
5794  // change axis specs and rebuild bin contents array::RebinAx
5795  if(!xbins && (newbins*ngroup != nbins)) {
5796  xmax = fXaxis.GetBinUpEdge(newbins*ngroup);
5797  resetStat = true; //stats must be reset because top bins will be moved to overflow bin
5798  }
5799  // save the TAttAxis members (reset by SetBins)
5800  Int_t nDivisions = fXaxis.GetNdivisions();
5801  Color_t axisColor = fXaxis.GetAxisColor();
5802  Color_t labelColor = fXaxis.GetLabelColor();
5803  Style_t labelFont = fXaxis.GetLabelFont();
5804  Float_t labelOffset = fXaxis.GetLabelOffset();
5805  Float_t labelSize = fXaxis.GetLabelSize();
5806  Float_t tickLength = fXaxis.GetTickLength();
5807  Float_t titleOffset = fXaxis.GetTitleOffset();
5808  Float_t titleSize = fXaxis.GetTitleSize();
5809  Color_t titleColor = fXaxis.GetTitleColor();
5810  Style_t titleFont = fXaxis.GetTitleFont();
5811 
5812  if(!xbins && (fXaxis.GetXbins()->GetSize() > 0)){ // variable bin sizes
5813  Double_t *bins = new Double_t[newbins+1];
5814  for(i = 0; i <= newbins; ++i) bins[i] = fXaxis.GetBinLowEdge(1+i*ngroup);
5815  hnew->SetBins(newbins,bins); //this also changes errors array (if any)
5816  delete [] bins;
5817  } else if (xbins) {
5818  hnew->SetBins(newbins,xbins);
5819  } else {
5820  hnew->SetBins(newbins,xmin,xmax);
5821  }
5822 
5823  // Restore axis attributes
5824  fXaxis.SetNdivisions(nDivisions);
5825  fXaxis.SetAxisColor(axisColor);
5826  fXaxis.SetLabelColor(labelColor);
5827  fXaxis.SetLabelFont(labelFont);
5828  fXaxis.SetLabelOffset(labelOffset);
5829  fXaxis.SetLabelSize(labelSize);
5830  fXaxis.SetTickLength(tickLength);
5831  fXaxis.SetTitleOffset(titleOffset);
5832  fXaxis.SetTitleSize(titleSize);
5833  fXaxis.SetTitleColor(titleColor);
5834  fXaxis.SetTitleFont(titleFont);
5835 
5836  // copy merged bin contents (ignore under/overflows)
5837  // Start merging only once the new lowest edge is reached
5838  Int_t startbin = 1;
5839  const Double_t newxmin = hnew->GetXaxis()->GetBinLowEdge(1);
5840  while( fXaxis.GetBinCenter(startbin) < newxmin && startbin <= nbins ) {
5841  startbin++;
5842  }
5843  Int_t oldbin = startbin;
5844  Double_t binContent, binError;
5845  for (bin = 1;bin<=newbins;bin++) {
5846  binContent = 0;
5847  binError = 0;
5848  Int_t imax = ngroup;
5849  Double_t xbinmax = hnew->GetXaxis()->GetBinUpEdge(bin);
5850  for (i=0;i<ngroup;i++) {
5851  if( (oldbin+i > nbins) ||
5852  ( hnew != this && (fXaxis.GetBinCenter(oldbin+i) > xbinmax)) ) {
5853  imax = i;
5854  break;
5855  }
5856  binContent += oldBins[oldbin+i];
5857  if (oldErrors) binError += oldErrors[oldbin+i]*oldErrors[oldbin+i];
5858  }
5859  hnew->SetBinContent(bin,binContent);
5860  if (oldErrors) hnew->SetBinError(bin,TMath::Sqrt(binError));
5861  oldbin += imax;
5862  }
5863 
5864  // sum underflow and overflow contents until startbin
5865  binContent = 0;
5866  binError = 0;
5867  for (i = 0; i < startbin; ++i) {
5868  binContent += oldBins[i];
5869  if (oldErrors) binError += oldErrors[i]*oldErrors[i];
5870  }
5871  hnew->SetBinContent(0,binContent);
5872  if (oldErrors) hnew->SetBinError(0,TMath::Sqrt(binError));
5873  // sum overflow
5874  binContent = 0;
5875  binError = 0;
5876  for (i = oldbin; i <= nbins+1; ++i) {
5877  binContent += oldBins[i];
5878  if (oldErrors) binError += oldErrors[i]*oldErrors[i];
5879  }
5880  hnew->SetBinContent(newbins+1,binContent);
5881  if (oldErrors) hnew->SetBinError(newbins+1,TMath::Sqrt(binError));
5882 
5883  hnew->SetCanExtend(oldExtendBitMask); // restore previous state
5884 
5885  // restore statistics and entries modified by SetBinContent
5886  hnew->SetEntries(entries);
5887  if (!resetStat) hnew->PutStats(stat);
5888  delete [] oldBins;
5889  if (oldErrors) delete [] oldErrors;
5890  return hnew;
5891 }
5892 
5893 ////////////////////////////////////////////////////////////////////////////////
5894 /// finds new limits for the axis so that *point* is within the range and
5895 /// the limits are compatible with the previous ones (see TH1::Merge).
5896 /// new limits are put into *newMin* and *newMax* variables.
5897 /// axis - axis whose limits are to be recomputed
5898 /// point - point that should fit within the new axis limits
5899 /// newMin - new minimum will be stored here
5900 /// newMax - new maximum will be stored here.
5901 /// false if failed (e.g. if the initial axis limits are wrong
5902 /// or the new range is more than \f$ 2^{64} \f$ times the old one).
5903 
5904 Bool_t TH1::FindNewAxisLimits(const TAxis* axis, const Double_t point, Double_t& newMin, Double_t &newMax)
5905 {
5906  Double_t xmin = axis->GetXmin();
5907  Double_t xmax = axis->GetXmax();
5908  if (xmin >= xmax) return kFALSE;
5909  Double_t range = xmax-xmin;
5910  Double_t binsize = range / axis->GetNbins();
5911 
5912  //recompute new axis limits by doubling the current range
5913  Int_t ntimes = 0;
5914  while (point < xmin) {
5915  if (ntimes++ > 64)
5916  return kFALSE;
5917  xmin = xmin - range;
5918  range *= 2;
5919  binsize *= 2;
5920  // // make sure that the merging will be correct
5921  // if ( xmin / binsize - TMath::Floor(xmin / binsize) >= 0.5) {
5922  // xmin += 0.5 * binsize;
5923  // xmax += 0.5 * binsize; // won't work with a histogram with only one bin, but I don't care
5924  // }
5925  }
5926  while (point >= xmax) {
5927  if (ntimes++ > 64)
5928  return kFALSE;
5929  xmax = xmax + range;
5930  range *= 2;
5931  binsize *= 2;
5932  // // make sure that the merging will be correct
5933  // if ( xmin / binsize - TMath::Floor(xmin / binsize) >= 0.5) {
5934  // xmin -= 0.5 * binsize;
5935  // xmax -= 0.5 * binsize; // won't work with a histogram with only one bin, but I don't care
5936  // }
5937  }
5938  newMin = xmin;
5939  newMax = xmax;
5940  // Info("FindNewAxisLimits", "OldAxis: (%lf, %lf), new: (%lf, %lf), point: %lf",
5941  // axis->GetXmin(), axis->GetXmax(), xmin, xmax, point);
5942 
5943  return kTRUE;
5944 }
5945 
5946 ////////////////////////////////////////////////////////////////////////////////
5947 /// Histogram is resized along axis such that x is in the axis range.
5948 /// The new axis limits are recomputed by doubling iteratively
5949 /// the current axis range until the specified value x is within the limits.
5950 /// The algorithm makes a copy of the histogram, then loops on all bins
5951 /// of the old histogram to fill the extended histogram.
5952 /// Takes into account errors (Sumw2) if any.
5953 /// The algorithm works for 1-d, 2-D and 3-D histograms.
5954 /// The axis must be extendable before invoking this function.
5955 /// Ex:
5956 ///
5957 /// ~~~ {.cpp}
5958 /// h->GetXaxis()->SetCanExtend(kTRUE);
5959 /// ~~~
5960 
5961 void TH1::ExtendAxis(Double_t x, TAxis *axis)
5962 {
5963  if (!axis->CanExtend()) return;
5964  if (TMath::IsNaN(x)) { // x may be a NaN
5966  return;
5967  }
5968 
5969  if (axis->GetXmin() >= axis->GetXmax()) return;
5970  if (axis->GetNbins() <= 0) return;
5971 
5972  Double_t xmin, xmax;
5973  if (!FindNewAxisLimits(axis, x, xmin, xmax))
5974  return;
5975 
5976  //save a copy of this histogram
5977  TH1 *hold = (TH1*)IsA()->New();
5978  hold->SetDirectory(0);
5979  Copy(*hold);
5980  //set new axis limits
5981  axis->SetLimits(xmin,xmax);
5982 
5983 
5984  //now loop on all bins and refill
5985  Int_t errors = GetSumw2N();
5986 
5987  Reset("ICE"); //reset only Integral, contents and Errors
5988 
5989  int iaxis = 0;
5990  if (axis == &fXaxis) iaxis = 1;
5991  if (axis == &fYaxis) iaxis = 2;
5992  if (axis == &fZaxis) iaxis = 3;
5993  bool firstw = kTRUE;
5994  Int_t binx,biny, binz = 0;
5995  Int_t ix = 0,iy = 0,iz = 0;
5996  Double_t bx,by,bz;
5997  Int_t ncells = hold->GetNcells();
5998  for (Int_t bin = 0; bin < ncells; ++bin) {
5999  hold->GetBinXYZ(bin,binx,biny,binz);
6000  bx = hold->GetXaxis()->GetBinCenter(binx);
6001  ix = fXaxis.FindFixBin(bx);
6002  if (fDimension > 1) {
6003  by = hold->GetYaxis()->GetBinCenter(biny);
6004  iy = fYaxis.FindFixBin(by);
6005  if (fDimension > 2) {
6006  bz = hold->GetZaxis()->GetBinCenter(binz);
6007  iz = fZaxis.FindFixBin(bz);
6008  }
6009  }
6010  // exclude underflow/overflow
6011  double content = hold->RetrieveBinContent(bin);
6012  if (content == 0) continue;
6013  if (IsBinUnderflow(bin,iaxis) || IsBinOverflow(bin,iaxis) ) {
6014  if (firstw) {
6015  Warning("ExtendAxis","Histogram %s has underflow or overflow in the axis that is extendable"
6016  " their content will be lost",GetName() );
6017  firstw= kFALSE;
6018  }
6019  continue;
6020  }
6021  Int_t ibin= GetBin(ix,iy,iz);
6022  AddBinContent(ibin, content);
6023  if (errors) {
6024  fSumw2.fArray[ibin] += hold->GetBinErrorSqUnchecked(bin);
6025  }
6026  }
6027  delete hold;
6028 }
6029 
6030 ////////////////////////////////////////////////////////////////////////////////
6031 /// Recursively remove object from the list of functions
6032 
6033 void TH1::RecursiveRemove(TObject *obj)
6034 {
6035  // Rely on TROOT::RecursiveRemove to take the readlock.
6036 
6037  if (fFunctions) {
6039  }
6040 }
6041 
6042 ////////////////////////////////////////////////////////////////////////////////
6043 /// Multiply this histogram by a constant c1.
6044 ///
6045 /// `this = c1*this`
6046 ///
6047 /// Note that both contents and errors(if any) are scaled.
6048 /// This function uses the services of TH1::Add
6049 ///
6050 /// IMPORTANT NOTE: Sumw2() is called automatically when scaling
6051 /// If you are not interested in the histogram statistics you can call
6052 /// Sumw2(off) or use the option "nosw2"
6053 ///
6054 /// One can scale an histogram such that the bins integral is equal to
6055 /// the normalization parameter via TH1::Scale(Double_t norm), where norm
6056 /// is the desired normalization divided by the integral of the histogram.
6057 ///
6058 /// If option contains "width" the bin contents and errors are divided
6059 /// by the bin width.
6060 
6061 void TH1::Scale(Double_t c1, Option_t *option)
6062 {
6064  TString opt = option; opt.ToLower();
6065  // store bin errors when scaling since cannot anymore be computed as sqrt(N)
6066  if (!opt.Contains("nosw2") && GetSumw2N() == 0) Sumw2();
6067  if (opt.Contains("width")) Add(this, this, c1, -1);
6068  else {
6069  if (fBuffer) BufferEmpty(1);
6070  for(Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, c1 * RetrieveBinContent(i));
6071  if (fSumw2.fN) for(Int_t i = 0; i < fNcells; ++i) fSumw2.fArray[i] *= (c1 * c1); // update errors
6072  SetMinimum(); SetMaximum(); // minimum and maximum value will be recalculated the next time
6073  }
6074 
6075  // if contours set, must also scale contours
6076  Int_t ncontours = GetContour();
6077  if (ncontours == 0) return;
6078  Double_t* levels = fContour.GetArray();
6079  for (Int_t i = 0; i < ncontours; ++i) levels[i] *= c1;
6080 }
6081 
6082 ////////////////////////////////////////////////////////////////////////////////
6083 /// Returns true if all axes are extendable.
6084 
6086 {
6087  Bool_t canExtend = fXaxis.CanExtend();
6088  if (GetDimension() > 1) canExtend &= fYaxis.CanExtend();
6089  if (GetDimension() > 2) canExtend &= fZaxis.CanExtend();
6090 
6091  return canExtend;
6092 }
6093 
6094 ////////////////////////////////////////////////////////////////////////////////
6095 /// Make the histogram axes extendable / not extendable according to the bit mask
6096 /// returns the previous bit mask specifying which axes are extendable
6097 
6098 UInt_t TH1::SetCanExtend(UInt_t extendBitMask)
6099 {
6100  UInt_t oldExtendBitMask = kNoAxis;
6101 
6102  if (fXaxis.CanExtend()) oldExtendBitMask |= kXaxis;
6103  if (extendBitMask & kXaxis) fXaxis.SetCanExtend(kTRUE);
6104  else fXaxis.SetCanExtend(kFALSE);
6105 
6106  if (GetDimension() > 1) {
6107  if (fYaxis.CanExtend()) oldExtendBitMask |= kYaxis;
6108  if (extendBitMask & kYaxis) fYaxis.SetCanExtend(kTRUE);
6109  else fYaxis.SetCanExtend(kFALSE);
6110  }
6111 
6112  if (GetDimension() > 2) {
6113  if (fZaxis.CanExtend()) oldExtendBitMask |= kZaxis;
6114  if (extendBitMask & kZaxis) fZaxis.SetCanExtend(kTRUE);
6115  else fZaxis.SetCanExtend(kFALSE);
6116  }
6117 
6118  return oldExtendBitMask;
6119 }
6120 
6121 ////////////////////////////////////////////////////////////////////////////////
6122 /// Static function to set the default buffer size for automatic histograms.
6123 /// When an histogram is created with one of its axis lower limit greater
6124 /// or equal to its upper limit, the function SetBuffer is automatically
6125 /// called with the default buffer size.
6126 
6127 void TH1::SetDefaultBufferSize(Int_t buffersize)
6128 {
6129  fgBufferSize = buffersize > 0 ? buffersize : 0;
6130 }
6131 
6132 ////////////////////////////////////////////////////////////////////////////////
6133 /// When this static function is called with `sumw2=kTRUE`, all new
6134 /// histograms will automatically activate the storage
6135 /// of the sum of squares of errors, ie TH1::Sumw2 is automatically called.
6136 
6137 void TH1::SetDefaultSumw2(Bool_t sumw2)
6138 {
6140 }
6141 
6142 ////////////////////////////////////////////////////////////////////////////////
6143 /// Change (i.e. set) the title
6144 ///
6145 /// if title is in the form `stringt;stringx;stringy;stringz`
6146 /// the histogram title is set to `stringt`, the x axis title to `stringx`,
6147 /// the y axis title to `stringy`, and the z axis title to `stringz`.
6148 ///
6149 /// To insert the character `;` in one of the titles, one should use `#;`
6150 /// or `#semicolon`.
6151 
6152 void TH1::SetTitle(const char *title)
6153 {
6154  fTitle = title;
6155  fTitle.ReplaceAll("#;",2,"#semicolon",10);
6156 
6157  // Decode fTitle. It may contain X, Y and Z titles
6158  TString str1 = fTitle, str2;
6159  Int_t isc = str1.Index(";");
6160  Int_t lns = str1.Length();
6161 
6162  if (isc >=0 ) {
6163  fTitle = str1(0,isc);
6164  str1 = str1(isc+1, lns);
6165  isc = str1.Index(";");
6166  if (isc >=0 ) {
6167  str2 = str1(0,isc);
6168  str2.ReplaceAll("#semicolon",10,";",1);
6169  fXaxis.SetTitle(str2.Data());
6170  lns = str1.Length();
6171  str1 = str1(isc+1, lns);
6172  isc = str1.Index(";");
6173  if (isc >=0 ) {
6174  str2 = str1(0,isc);
6175  str2.ReplaceAll("#semicolon",10,";",1);
6176  fYaxis.SetTitle(str2.Data());
6177  lns = str1.Length();
6178  str1 = str1(isc+1, lns);
6179  str1.ReplaceAll("#semicolon",10,";",1);
6180  fZaxis.SetTitle(str1.Data());
6181  } else {
6182  str1.ReplaceAll("#semicolon",10,";",1);
6183  fYaxis.SetTitle(str1.Data());
6184  }
6185  } else {
6186  str1.ReplaceAll("#semicolon",10,";",1);
6187  fXaxis.SetTitle(str1.Data());
6188  }
6189  }
6190 
6191  fTitle.ReplaceAll("#semicolon",10,";",1);
6192 
6193  if (gPad && TestBit(kMustCleanup)) gPad->Modified();
6194 }
6195 
6196 ////////////////////////////////////////////////////////////////////////////////
6197 /// Smooth array xx, translation of Hbook routine hsmoof.F
6198 /// based on algorithm 353QH twice presented by J. Friedman
6199 /// in Proc.of the 1974 CERN School of Computing, Norway, 11-24 August, 1974.
6200 
6201 void TH1::SmoothArray(Int_t nn, Double_t *xx, Int_t ntimes)
6202 {
6203  if (nn < 3 ) {
6204  ::Error("SmoothArray","Need at least 3 points for smoothing: n = %d",nn);
6205  return;
6206  }
6207 
6208  Int_t ii;
6209  Double_t hh[6] = {0,0,0,0,0,0};
6210 
6211  std::vector<double> yy(nn);
6212  std::vector<double> zz(nn);
6213  std::vector<double> rr(nn);
6214 
6215  for (Int_t pass=0;pass<ntimes;pass++) {
6216  // first copy original data into temp array
6217  std::copy(xx, xx+nn, zz.begin() );
6218 
6219  for (int noent = 0; noent < 2; ++noent) { // run algorithm two times
6220 
6221  // do 353 i.e. running median 3, 5, and 3 in a single loop
6222  for (int kk = 0; kk < 3; kk++) {
6223  std::copy(zz.begin(), zz.end(), yy.begin());
6224  int medianType = (kk != 1) ? 3 : 5;
6225  int ifirst = (kk != 1 ) ? 1 : 2;
6226  int ilast = (kk != 1 ) ? nn-1 : nn -2;
6227  //nn2 = nn - ik - 1;
6228  // do all elements beside the first and last point for median 3
6229  // and first two and last 2 for median 5
6230  for ( ii = ifirst; ii < ilast; ii++) {
6231  assert(ii - ifirst >= 0);
6232  for (int jj = 0; jj < medianType; jj++) {
6233  hh[jj] = yy[ii - ifirst + jj ];
6234  }
6235  zz[ii] = TMath::Median(medianType, hh);
6236  }
6237 
6238  if (kk == 0) { // first median 3
6239  // first point
6240  hh[0] = zz[1];
6241  hh[1] = zz[0];
6242  hh[2] = 3*zz[1] - 2*zz[2];
6243  zz[0] = TMath::Median(3, hh);
6244  // last point
6245  hh[0] = zz[nn - 2];
6246  hh[1] = zz[nn - 1];
6247  hh[2] = 3*zz[nn - 2] - 2*zz[nn - 3];
6248  zz[nn - 1] = TMath::Median(3, hh);
6249  }
6250 
6251  if (kk == 1) { // median 5
6252  for (ii = 0; ii < 3; ii++) {
6253  hh[ii] = yy[ii];
6254  }
6255  zz[1] = TMath::Median(3, hh);
6256  // last two points
6257  for (ii = 0; ii < 3; ii++) {
6258  hh[ii] = yy[nn - 3 + ii];
6259  }
6260  zz[nn - 2] = TMath::Median(3, hh);
6261  }
6262 
6263  }
6264 
6265  std::copy ( zz.begin(), zz.end(), yy.begin() );
6266 
6267  // quadratic interpolation for flat segments
6268  for (ii = 2; ii < (nn - 2); ii++) {
6269  if (zz[ii - 1] != zz[ii]) continue;
6270  if (zz[ii] != zz[ii + 1]) continue;
6271  hh[0] = zz[ii - 2] - zz[ii];
6272  hh[1] = zz[ii + 2] - zz[ii];
6273  if (hh[0] * hh[1] <= 0) continue;
6274  int jk = 1;
6275  if ( TMath::Abs(hh[1]) > TMath::Abs(hh[0]) ) jk = -1;
6276  yy[ii] = -0.5*zz[ii - 2*jk] + zz[ii]/0.75 + zz[ii + 2*jk] /6.;
6277  yy[ii + jk] = 0.5*(zz[ii + 2*jk] - zz[ii - 2*jk]) + zz[ii];
6278  }
6279 
6280  // running means
6281  //std::copy(zz.begin(), zz.end(), yy.begin());
6282  for (ii = 1; ii < nn - 1; ii++) {
6283  zz[ii] = 0.25*yy[ii - 1] + 0.5*yy[ii] + 0.25*yy[ii + 1];
6284  }
6285  zz[0] = yy[0];
6286  zz[nn - 1] = yy[nn - 1];
6287 
6288  if (noent == 0) {
6289 
6290  // save computed values
6291  std::copy(zz.begin(), zz.end(), rr.begin());
6292 
6293  // COMPUTE residuals
6294  for (ii = 0; ii < nn; ii++) {
6295  zz[ii] = xx[ii] - zz[ii];
6296  }
6297  }
6298 
6299  } // end loop on noent
6300 
6301 
6302  double xmin = TMath::MinElement(nn,xx);
6303  for (ii = 0; ii < nn; ii++) {
6304  if (xmin < 0) xx[ii] = rr[ii] + zz[ii];
6305  // make smoothing defined positive - not better using 0 ?
6306  else xx[ii] = TMath::Max((rr[ii] + zz[ii]),0.0 );
6307  }
6308  }
6309 }
6310 
6311 ////////////////////////////////////////////////////////////////////////////////
6312 /// Smooth bin contents of this histogram.
6313 /// if option contains "R" smoothing is applied only to the bins
6314 /// defined in the X axis range (default is to smooth all bins)
6315 /// Bin contents are replaced by their smooth values.
6316 /// Errors (if any) are not modified.
6317 /// the smoothing procedure is repeated ntimes (default=1)
6318 
6319 void TH1::Smooth(Int_t ntimes, Option_t *option)
6320 {
6321  if (fDimension != 1) {
6322  Error("Smooth","Smooth only supported for 1-d histograms");
6323  return;
6324  }
6325  Int_t nbins = fXaxis.GetNbins();
6326  if (nbins < 3) {
6327  Error("Smooth","Smooth only supported for histograms with >= 3 bins. Nbins = %d",nbins);
6328  return;
6329  }
6330 
6331  // delete buffer if it is there since it will become invalid
6332  if (fBuffer) BufferEmpty(1);
6333 
6334  Int_t firstbin = 1, lastbin = nbins;
6335  TString opt = option;
6336  opt.ToLower();
6337  if (opt.Contains("r")) {
6338  firstbin= fXaxis.GetFirst();
6339  lastbin = fXaxis.GetLast();
6340  }
6341  nbins = lastbin - firstbin + 1;
6342  Double_t *xx = new Double_t[nbins];
6343  Double_t nent = fEntries;
6344  Int_t i;
6345  for (i=0;i<nbins;i++) {
6346  xx[i] = RetrieveBinContent(i+firstbin);
6347  }
6348 
6349  TH1::SmoothArray(nbins,xx,ntimes);
6350 
6351  for (i=0;i<nbins;i++) {
6352  UpdateBinContent(i+firstbin,xx[i]);
6353  }
6354  fEntries = nent;
6355  delete [] xx;
6356 
6357  if (gPad) gPad->Modified();
6358 }
6359 
6360 ////////////////////////////////////////////////////////////////////////////////
6361 /// if flag=kTRUE, underflows and overflows are used by the Fill functions
6362 /// in the computation of statistics (mean value, StdDev).
6363 /// By default, underflows or overflows are not used.
6364 
6365 void TH1::StatOverflows(Bool_t flag)
6366 {
6368 }
6369 
6370 ////////////////////////////////////////////////////////////////////////////////
6371 /// Stream a class object.
6372 
6373 void TH1::Streamer(TBuffer &b)
6374 {
6375  if (b.IsReading()) {
6376  UInt_t R__s, R__c;
6377  Version_t R__v = b.ReadVersion(&R__s, &R__c);
6378  if (fDirectory) fDirectory->Remove(this);
6379  fDirectory = 0;
6380  if (R__v > 2) {
6381  b.ReadClassBuffer(TH1::Class(), this, R__v, R__s, R__c);
6382 
6384  fXaxis.SetParent(this);
6385  fYaxis.SetParent(this);
6386  fZaxis.SetParent(this);
6387  TIter next(fFunctions);
6388  TObject *obj;
6389  while ((obj=next())) {
6390  if (obj->InheritsFrom(TF1::Class())) ((TF1*)obj)->SetParent(this);
6391  }
6392  return;
6393  }
6394  //process old versions before automatic schema evolution
6395  TNamed::Streamer(b);
6396  TAttLine::Streamer(b);
6397  TAttFill::Streamer(b);
6398  TAttMarker::Streamer(b);
6399  b >> fNcells;
6400  fXaxis.Streamer(b);
6401  fYaxis.Streamer(b);
6402  fZaxis.Streamer(b);
6403  fXaxis.SetParent(this);
6404  fYaxis.SetParent(this);
6405  fZaxis.SetParent(this);
6406  b >> fBarOffset;
6407  b >> fBarWidth;
6408  b >> fEntries;
6409  b >> fTsumw;
6410  b >> fTsumw2;
6411  b >> fTsumwx;
6412  b >> fTsumwx2;
6413  if (R__v < 2) {
6414  Float_t maximum, minimum, norm;
6415  Float_t *contour=0;
6416  b >> maximum; fMaximum = maximum;
6417  b >> minimum; fMinimum = minimum;
6418  b >> norm; fNormFactor = norm;
6419  Int_t n = b.ReadArray(contour);
6420  fContour.Set(n);
6421  for (Int_t i=0;i<n;i++) fContour.fArray[i] = contour[i];
6422  delete [] contour;
6423  } else {
6424  b >> fMaximum;
6425  b >> fMinimum;
6426  b >> fNormFactor;
6427  fContour.Streamer(b);
6428  }
6429  fSumw2.Streamer(b);
6430  fOption.Streamer(b);
6431  fFunctions->Delete();
6432  fFunctions->Streamer(b);
6433  b.CheckByteCount(R__s, R__c, TH1::IsA());
6434 
6435  } else {
6436  b.WriteClassBuffer(TH1::Class(),this);
6437  }
6438 }
6439 
6440 ////////////////////////////////////////////////////////////////////////////////
6441 /// Print some global quantities for this histogram.
6442 /// \param[in] option
6443 /// - "base" is given, number of bins and ranges are also printed
6444 /// - "range" is given, bin contents and errors are also printed
6445 /// for all bins in the current range (default 1-->nbins)
6446 /// - "all" is given, bin contents and errors are also printed
6447 /// for all bins including under and overflows.
6448 
6449 void TH1::Print(Option_t *option) const
6450 {
6451  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
6452  printf( "TH1.Print Name = %s, Entries= %d, Total sum= %g\n",GetName(),Int_t(fEntries),GetSumOfWeights());
6453  TString opt = option;
6454  opt.ToLower();
6455  Int_t all;
6456  if (opt.Contains("all")) all = 0;
6457  else if (opt.Contains("range")) all = 1;
6458  else if (opt.Contains("base")) all = 2;
6459  else return;
6460 
6461  Int_t bin, binx, biny, binz;
6462  Int_t firstx=0,lastx=0,firsty=0,lasty=0,firstz=0,lastz=0;
6463  if (all == 0) {
6464  lastx = fXaxis.GetNbins()+1;
6465  if (fDimension > 1) lasty = fYaxis.GetNbins()+1;
6466  if (fDimension > 2) lastz = fZaxis.GetNbins()+1;
6467  } else {
6468  firstx = fXaxis.GetFirst(); lastx = fXaxis.GetLast();
6469  if (fDimension > 1) {firsty = fYaxis.GetFirst(); lasty = fYaxis.GetLast();}
6470  if (fDimension > 2) {firstz = fZaxis.GetFirst(); lastz = fZaxis.GetLast();}
6471  }
6472 
6473  if (all== 2) {
6474  printf(" Title = %s\n", GetTitle());
6475  printf(" NbinsX= %d, xmin= %g, xmax=%g", fXaxis.GetNbins(), fXaxis.GetXmin(), fXaxis.GetXmax());
6476  if( fDimension > 1) printf(", NbinsY= %d, ymin= %g, ymax=%g", fYaxis.GetNbins(), fYaxis.GetXmin(), fYaxis.GetXmax());
6477  if( fDimension > 2) printf(", NbinsZ= %d, zmin= %g, zmax=%g", fZaxis.GetNbins(), fZaxis.GetXmin(), fZaxis.GetXmax());
6478  printf("\n");
6479  return;
6480  }
6481 
6482  Double_t w,e;
6483  Double_t x,y,z;
6484  if (fDimension == 1) {
6485  for (binx=firstx;binx<=lastx;binx++) {
6486  x = fXaxis.GetBinCenter(binx);
6487  w = RetrieveBinContent(binx);
6488  e = GetBinError(binx);
6489  if(fSumw2.fN) printf(" fSumw[%d]=%g, x=%g, error=%g\n",binx,w,x,e);
6490  else printf(" fSumw[%d]=%g, x=%g\n",binx,w,x);
6491  }
6492  }
6493  if (fDimension == 2) {
6494  for (biny=firsty;biny<=lasty;biny++) {
6495  y = fYaxis.GetBinCenter(biny);
6496  for (binx=firstx;binx<=lastx;binx++) {
6497  bin = GetBin(binx,biny);
6498  x = fXaxis.GetBinCenter(binx);
6499  w = RetrieveBinContent(bin);
6500  e = GetBinError(bin);
6501  if(fSumw2.fN) printf(" fSumw[%d][%d]=%g, x=%g, y=%g, error=%g\n",binx,biny,w,x,y,e);
6502  else printf(" fSumw[%d][%d]=%g, x=%g, y=%g\n",binx,biny,w,x,y);
6503  }
6504  }
6505  }
6506  if (fDimension == 3) {
6507  for (binz=firstz;binz<=lastz;binz++) {
6508  z = fZaxis.GetBinCenter(binz);
6509  for (biny=firsty;biny<=lasty;biny++) {
6510  y = fYaxis.GetBinCenter(biny);
6511  for (binx=firstx;binx<=lastx;binx++) {
6512  bin = GetBin(binx,biny,binz);
6513  x = fXaxis.GetBinCenter(binx);
6514  w = RetrieveBinContent(bin);
6515  e = GetBinError(bin);
6516  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);
6517  else printf(" fSumw[%d][%d][%d]=%g, x=%g, y=%g, z=%g\n",binx,biny,binz,w,x,y,z);
6518  }
6519  }
6520  }
6521  }
6522 }
6523 
6524 ////////////////////////////////////////////////////////////////////////////////
6525 /// Using the current bin info, recompute the arrays for contents and errors
6526 
6527 void TH1::Rebuild(Option_t *)
6528 {
6530  if (fSumw2.fN) {
6531  fSumw2.Set(fNcells);
6532  }
6533 }
6534 
6535 ////////////////////////////////////////////////////////////////////////////////
6536 /// Reset this histogram: contents, errors, etc.
6537 /// \param[in] option
6538 /// - "ICE" is specified, resets only Integral, Contents and Errors.
6539 /// - "ICES" is specified, resets only Integral, Contents , Errors and Statistics
6540 /// This option is used
6541 /// - "M" is specified, resets also Minimum and Maximum
6542 
6543 void TH1::Reset(Option_t *option)
6544 {
6545  // The option "ICE" is used when extending the histogram (in ExtendAxis, LabelInflate, etc..)
6546  // The option "ICES is used in combination with the buffer (see BufferEmpty and BufferFill)
6547 
6548  TString opt = option;
6549  opt.ToUpper();
6550  fSumw2.Reset();
6551  if (fIntegral) {delete [] fIntegral; fIntegral = 0;}
6552 
6553  if (opt.Contains("M")) {
6554  SetMinimum();
6555  SetMaximum();
6556  }
6557 
6558  if (opt.Contains("ICE") && !opt.Contains("S")) return;
6559 
6560  // Setting fBuffer[0] = 0 is like resetting the buffer but not deleting it
6561  // But what is the sense of calling BufferEmpty() ? For making the axes ?
6562  // BufferEmpty will update contents that later will be
6563  // reset in calling TH1D::Reset. For this we need to reset the stats afterwards
6564  // It may be needed for computing the axis limits....
6565  if (fBuffer) {BufferEmpty(); fBuffer[0] = 0;}
6566 
6567  // need to reset also the statistics
6568  // (needs to be done after calling BufferEmpty() )
6569  fTsumw = 0;
6570  fTsumw2 = 0;
6571  fTsumwx = 0;
6572  fTsumwx2 = 0;
6573  fEntries = 0;
6574 
6575  if (opt == "ICES") return;
6576 
6577 
6578  TObject *stats = fFunctions->FindObject("stats");
6579  fFunctions->Remove(stats);
6580  //special logic to support the case where the same object is
6581  //added multiple times in fFunctions.
6582  //This case happens when the same object is added with different
6583  //drawing modes
6584  TObject *obj;
6585  while ((obj = fFunctions->First())) {
6586  while(fFunctions->Remove(obj)) { }
6587  delete obj;
6588  }
6589  if(stats) fFunctions->Add(stats);
6590  fContour.Set(0);
6591 }
6592 
6593 ////////////////////////////////////////////////////////////////////////////////
6594 /// Save primitive as a C++ statement(s) on output stream out
6595 
6596 void TH1::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/)
6597 {
6598  // empty the buffer before if it exists
6599  if (fBuffer) BufferEmpty();
6600 
6601  Bool_t nonEqiX = kFALSE;
6602  Bool_t nonEqiY = kFALSE;
6603  Bool_t nonEqiZ = kFALSE;
6604  Int_t i;
6605  static Int_t nxaxis = 0;
6606  static Int_t nyaxis = 0;
6607  static Int_t nzaxis = 0;
6608  TString sxaxis="xAxis",syaxis="yAxis",szaxis="zAxis";
6609 
6610  // Check if the histogram has equidistant X bins or not. If not, we
6611  // create an array holding the bins.
6612  if (GetXaxis()->GetXbins()->fN && GetXaxis()->GetXbins()->fArray) {
6613  nonEqiX = kTRUE;
6614  nxaxis++;
6615  sxaxis += nxaxis;
6616  out << " Double_t "<<sxaxis<<"[" << GetXaxis()->GetXbins()->fN
6617  << "] = {";
6618  for (i = 0; i < GetXaxis()->GetXbins()->fN; i++) {
6619  if (i != 0) out << ", ";
6620  out << GetXaxis()->GetXbins()->fArray[i];
6621  }
6622  out << "}; " << std::endl;
6623  }
6624  // If the histogram is 2 or 3 dimensional, check if the histogram
6625  // has equidistant Y bins or not. If not, we create an array
6626  // holding the bins.
6627  if (fDimension > 1 && GetYaxis()->GetXbins()->fN &&
6628  GetYaxis()->GetXbins()->fArray) {
6629  nonEqiY = kTRUE;
6630  nyaxis++;
6631  syaxis += nyaxis;
6632  out << " Double_t "<<syaxis<<"[" << GetYaxis()->GetXbins()->fN
6633  << "] = {";
6634  for (i = 0; i < GetYaxis()->GetXbins()->fN; i++) {
6635  if (i != 0) out << ", ";
6636  out << GetYaxis()->GetXbins()->fArray[i];
6637  }
6638  out << "}; " << std::endl;
6639  }
6640  // IF the histogram is 3 dimensional, check if the histogram
6641  // has equidistant Z bins or not. If not, we create an array
6642  // holding the bins.
6643  if (fDimension > 2 && GetZaxis()->GetXbins()->fN &&
6644  GetZaxis()->GetXbins()->fArray) {
6645  nonEqiZ = kTRUE;
6646  nzaxis++;
6647  szaxis += nzaxis;
6648  out << " Double_t "<<szaxis<<"[" << GetZaxis()->GetXbins()->fN
6649  << "] = {";
6650  for (i = 0; i < GetZaxis()->GetXbins()->fN; i++) {
6651  if (i != 0) out << ", ";
6652  out << GetZaxis()->GetXbins()->fArray[i];
6653  }
6654  out << "}; " << std::endl;
6655  }
6656 
6657  char quote = '"';
6658  out <<" "<<std::endl;
6659  out <<" "<< ClassName() <<" *";
6660 
6661  // Histogram pointer has by default the histogram name with an incremental suffix.
6662  // If the histogram belongs to a graph or a stack the suffix is not added because
6663  // the graph and stack objects are not aware of this new name. Same thing if
6664  // the histogram is drawn with the option COLZ because the TPaletteAxis drawn
6665  // when this option is selected, does not know this new name either.
6666  TString opt = option;
6667  opt.ToLower();
6668  static Int_t hcounter = 0;
6669  TString histName = GetName();
6670  if ( !histName.Contains("Graph")
6671  && !histName.Contains("_stack_")
6672  && !opt.Contains("colz")) {
6673  hcounter++;
6674  histName += "__";
6675  histName += hcounter;
6676  }
6677  histName = gInterpreter-> MapCppName(histName);
6678  const char *hname = histName.Data();
6679  if (!strlen(hname)) hname = "unnamed";
6680  TString savedName = GetName();
6681  this->SetName(hname);
6682  TString t(GetTitle());
6683  t.ReplaceAll("\\","\\\\");
6684  t.ReplaceAll("\"","\\\"");
6685  out << hname << " = new " << ClassName() << "(" << quote
6686  << hname << quote << "," << quote<< t.Data() << quote
6687  << "," << GetXaxis()->GetNbins();
6688  if (nonEqiX)
6689  out << ", "<<sxaxis;
6690  else
6691  out << "," << GetXaxis()->GetXmin()
6692  << "," << GetXaxis()->GetXmax();
6693  if (fDimension > 1) {
6694  out << "," << GetYaxis()->GetNbins();
6695  if (nonEqiY)
6696  out << ", "<<syaxis;
6697  else
6698  out << "," << GetYaxis()->GetXmin()
6699  << "," << GetYaxis()->GetXmax();
6700  }
6701  if (fDimension > 2) {
6702  out << "," << GetZaxis()->GetNbins();
6703  if (nonEqiZ)
6704  out << ", "<<szaxis;
6705  else
6706  out << "," << GetZaxis()->GetXmin()
6707  << "," << GetZaxis()->GetXmax();
6708  }
6709  out << ");" << std::endl;
6710 
6711  // save bin contents
6712  Int_t bin;
6713  for (bin=0;bin<fNcells;bin++) {
6714  Double_t bc = RetrieveBinContent(bin);
6715  if (bc) {
6716  out<<" "<<hname<<"->SetBinContent("<<bin<<","<<bc<<");"<<std::endl;
6717  }
6718  }
6719 
6720  // save bin errors
6721  if (fSumw2.fN) {
6722  for (bin=0;bin<fNcells;bin++) {
6723  Double_t be = GetBinError(bin);
6724  if (be) {
6725  out<<" "<<hname<<"->SetBinError("<<bin<<","<<be<<");"<<std::endl;
6726  }
6727  }
6728  }
6729 
6730  TH1::SavePrimitiveHelp(out, hname, option);
6731  this->SetName(savedName.Data());
6732 }
6733 
6734 ////////////////////////////////////////////////////////////////////////////////
6735 /// Helper function for the SavePrimitive functions from TH1
6736 /// or classes derived from TH1, eg TProfile, TProfile2D.
6737 
6738 void TH1::SavePrimitiveHelp(std::ostream &out, const char *hname, Option_t *option /*= ""*/)
6739 {
6740  char quote = '"';
6741  if (TMath::Abs(GetBarOffset()) > 1e-5) {
6742  out<<" "<<hname<<"->SetBarOffset("<<GetBarOffset()<<");"<<std::endl;
6743  }
6744  if (TMath::Abs(GetBarWidth()-1) > 1e-5) {
6745  out<<" "<<hname<<"->SetBarWidth("<<GetBarWidth()<<");"<<std::endl;
6746  }
6747  if (fMinimum != -1111) {
6748  out<<" "<<hname<<"->SetMinimum("<<fMinimum<<");"<<std::endl;
6749  }
6750  if (fMaximum != -1111) {
6751  out<<" "<<hname<<"->SetMaximum("<<fMaximum<<");"<<std::endl;
6752  }
6753  if (fNormFactor != 0) {
6754  out<<" "<<hname<<"->SetNormFactor("<<fNormFactor<<");"<<std::endl;
6755  }
6756  if (fEntries != 0) {
6757  out<<" "<<hname<<"->SetEntries("<<fEntries<<");"<<std::endl;
6758  }
6759  if (fDirectory == 0) {
6760  out<<" "<<hname<<"->SetDirectory(0);"<<std::endl;
6761  }
6762  if (TestBit(kNoStats)) {
6763  out<<" "<<hname<<"->SetStats(0);"<<std::endl;
6764  }
6765  if (fOption.Length() != 0) {
6766  out<<" "<<hname<<"->SetOption("<<quote<<fOption.Data()<<quote<<");"<<std::endl;
6767  }
6768 
6769  // save contour levels
6770  Int_t ncontours = GetContour();
6771  if (ncontours > 0) {
6772  out<<" "<<hname<<"->SetContour("<<ncontours<<");"<<std::endl;
6773  Double_t zlevel;
6774  for (Int_t bin=0;bin<ncontours;bin++) {
6775  if (gPad->GetLogz()) {
6776  zlevel = TMath::Power(10,GetContourLevel(bin));
6777  } else {
6778  zlevel = GetContourLevel(bin);
6779  }
6780  out<<" "<<hname<<"->SetContourLevel("<<bin<<","<<zlevel<<");"<<std::endl;
6781  }
6782  }
6783 
6784  // save list of functions
6786  TObject *obj;
6787  static Int_t funcNumber = 0;
6788  while (lnk) {
6789  obj = lnk->GetObject();
6790  obj->SavePrimitive(out,Form("nodraw #%d\n",++funcNumber));
6791  if (obj->InheritsFrom(TF1::Class())) {
6792  TString fname;
6793  fname.Form("%s%d",obj->GetName(),funcNumber);
6794  out << " " << fname << "->SetParent(" << hname << ");\n";
6795  out<<" "<<hname<<"->GetListOfFunctions()->Add("
6796  << fname <<");"<<std::endl;
6797  } else if (obj->InheritsFrom("TPaveStats")) {
6798  out<<" "<<hname<<"->GetListOfFunctions()->Add(ptstats);"<<std::endl;
6799  out<<" ptstats->SetParent("<<hname<<");"<<std::endl;
6800  } else {
6801  out<<" "<<hname<<"->GetListOfFunctions()->Add("
6802  <<obj->GetName()
6803  <<","<<quote<<lnk->GetOption()<<quote<<");"<<std::endl;
6804  }
6805  lnk = (TObjOptLink*)lnk->Next();
6806  }
6807 
6808  // save attributes
6809  SaveFillAttributes(out,hname,0,1001);
6810  SaveLineAttributes(out,hname,1,1,1);
6811  SaveMarkerAttributes(out,hname,1,1,1);
6812  fXaxis.SaveAttributes(out,hname,"->GetXaxis()");
6813  fYaxis.SaveAttributes(out,hname,"->GetYaxis()");
6814  fZaxis.SaveAttributes(out,hname,"->GetZaxis()");
6815  TString opt = option;
6816  opt.ToLower();
6817  if (!opt.Contains("nodraw")) {
6818  out<<" "<<hname<<"->Draw("
6819  <<quote<<option<<quote<<");"<<std::endl;
6820  }
6821 }
6822 
6823 ////////////////////////////////////////////////////////////////////////////////
6824 /// Copy current attributes from/to current style
6825 
6826 void TH1::UseCurrentStyle()
6827 {
6828  if (!gStyle) return;
6829  if (gStyle->IsReading()) {
6830  fXaxis.ResetAttAxis("X");
6831  fYaxis.ResetAttAxis("Y");
6832  fZaxis.ResetAttAxis("Z");
6843  Int_t dostat = gStyle->GetOptStat();
6844  if (gStyle->GetOptFit() && !dostat) dostat = 1000000001;
6845  SetStats(dostat);
6846  } else {
6858  }
6859  TIter next(GetListOfFunctions());
6860  TObject *obj;
6861 
6862  while ((obj = next())) {
6863  obj->UseCurrentStyle();
6864  }
6865 }
6866 
6867 ////////////////////////////////////////////////////////////////////////////////
6868 /// For axis = 1,2 or 3 returns the mean value of the histogram along
6869 /// X,Y or Z axis.
6870 ///
6871 /// For axis = 11, 12, 13 returns the standard error of the mean value
6872 /// of the histogram along X, Y or Z axis
6873 ///
6874 /// Note that the mean value/StdDev is computed using the bins in the currently
6875 /// defined range (see TAxis::SetRange). By default the range includes
6876 /// all bins from 1 to nbins included, excluding underflows and overflows.
6877 /// To force the underflows and overflows in the computation, one must
6878 /// call the static function TH1::StatOverflows(kTRUE) before filling
6879 /// the histogram.
6880 ///
6881 /// Return mean value of this histogram along the X axis.
6882 ///
6883 /// Note that the mean value/StdDev is computed using the bins in the currently
6884 /// defined range (see TAxis::SetRange). By default the range includes
6885 /// all bins from 1 to nbins included, excluding underflows and overflows.
6886 /// To force the underflows and overflows in the computation, one must
6887 /// call the static function TH1::StatOverflows(kTRUE) before filling
6888 /// the histogram.
6889 
6890 Double_t TH1::GetMean(Int_t axis) const
6891 {
6892  if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
6893  Double_t stats[kNstat];
6894  for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
6895  GetStats(stats);
6896  if (stats[0] == 0) return 0;
6897  if (axis<4){
6898  Int_t ax[3] = {2,4,7};
6899  return stats[ax[axis-1]]/stats[0];
6900  } else {
6901  // mean error = StdDev / sqrt( Neff )
6902  Double_t stddev = GetStdDev(axis-10);
6903  Double_t neff = GetEffectiveEntries();
6904  return ( neff > 0 ? stddev/TMath::Sqrt(neff) : 0. );
6905  }
6906 }
6907 
6908 ////////////////////////////////////////////////////////////////////////////////
6909 /// Return standard error of mean of this histogram along the X axis.
6910 ///
6911 /// Note that the mean value/StdDev is computed using the bins in the currently
6912 /// defined range (see TAxis::SetRange). By default the range includes
6913 /// all bins from 1 to nbins included, excluding underflows and overflows.
6914 /// To force the underflows and overflows in the computation, one must
6915 /// call the static function TH1::StatOverflows(kTRUE) before filling
6916 /// the histogram.
6917 ///
6918 /// Also note, that although the definition of standard error doesn't include the
6919 /// assumption of normality, many uses of this feature implicitly assume it.
6920 
6921 Double_t TH1::GetMeanError(Int_t axis) const
6922 {
6923  return GetMean(axis+10);
6924 }
6925 
6926 ////////////////////////////////////////////////////////////////////////////////
6927 /// Returns the Standard Deviation (Sigma).
6928 /// The Sigma estimate is computed as
6929 /// \f[
6930 /// \sqrt{\frac{1}{N}(\sum(x_i-x_{mean})^2)}
6931 /// \f]
6932 /// For axis = 1,2 or 3 returns the Sigma value of the histogram along
6933 /// X, Y or Z axis
6934 /// For axis = 11, 12 or 13 returns the error of StdDev estimation along
6935 /// X, Y or Z axis for Normal distribution
6936 ///
6937 /// Note that the mean value/sigma is computed using the bins in the currently
6938 /// defined range (see TAxis::SetRange). By default the range includes
6939 /// all bins from 1 to nbins included, excluding underflows and overflows.
6940 /// To force the underflows and overflows in the computation, one must
6941 /// call the static function TH1::StatOverflows(kTRUE) before filling
6942 /// the histogram.
6943 
6944 Double_t TH1::GetStdDev(Int_t axis) const
6945 {
6946  if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
6947 
6948  Double_t x, stddev2, stats[kNstat];
6949  for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
6950  GetStats(stats);
6951  if (stats[0] == 0) return 0;
6952  Int_t ax[3] = {2,4,7};
6953  Int_t axm = ax[axis%10 - 1];
6954  x = stats[axm]/stats[0];
6955  stddev2 = TMath::Abs(stats[axm+1]/stats[0] -x*x);
6956  if (axis<10)
6957  return TMath::Sqrt(stddev2);
6958  else {
6959  // The right formula for StdDev error depends on 4th momentum (see Kendall-Stuart Vol 1 pag 243)
6960  // formula valid for only gaussian distribution ( 4-th momentum = 3 * sigma^4 )
6961  Double_t neff = GetEffectiveEntries();
6962  return ( neff > 0 ? TMath::Sqrt(stddev2/(2*neff) ) : 0. );
6963  }
6964 }
6965 
6966 ////////////////////////////////////////////////////////////////////////////////
6967 /// Return error of standard deviation estimation for Normal distribution
6968 ///
6969 /// Note that the mean value/StdDev is computed using the bins in the currently
6970 /// defined range (see TAxis::SetRange). By default the range includes
6971 /// all bins from 1 to nbins included, excluding underflows and overflows.
6972 /// To force the underflows and overflows in the computation, one must
6973 /// call the static function TH1::StatOverflows(kTRUE) before filling
6974 /// the histogram.
6975 ///
6976 /// Value returned is standard deviation of sample standard deviation.
6977 /// Note that it is an approximated value which is valid only in the case that the
6978 /// original data distribution is Normal. The correct one would require
6979 /// the 4-th momentum value, which cannot be accurately estimated from an histogram since
6980 /// the x-information for all entries is not kept.
6981 
6983 {
6984  return GetStdDev(axis+10);
6985 }
6986 
6987 ////////////////////////////////////////////////////////////////////////////////
6988 /// - For axis = 1, 2 or 3 returns skewness of the histogram along x, y or z axis.
6989 /// - For axis = 11, 12 or 13 returns the approximate standard error of skewness
6990 /// of the histogram along x, y or z axis
6991 ///
6992 ///Note, that since third and fourth moment are not calculated
6993 ///at the fill time, skewness and its standard error are computed bin by bin
6994 
6995 Double_t TH1::GetSkewness(Int_t axis) const
6996 {
6998  if (axis > 0 && axis <= 3){
6999 
7000  Double_t mean = GetMean(axis);
7001  Double_t stddev = GetStdDev(axis);
7002  Double_t stddev3 = stddev*stddev*stddev;
7003 
7004  Int_t firstBinX = fXaxis.GetFirst();
7005  Int_t lastBinX = fXaxis.GetLast();
7006  Int_t firstBinY = fYaxis.GetFirst();
7007  Int_t lastBinY = fYaxis.GetLast();
7008  Int_t firstBinZ = fZaxis.GetFirst();
7009  Int_t lastBinZ = fZaxis.GetLast();
7010  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7011  if (GetStatOverflowsBehaviour()) {
7012  if ( !fXaxis.TestBit(TAxis::kAxisRange) ) {
7013  if (firstBinX == 1) firstBinX = 0;
7014  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7015  }
7016  if ( !fYaxis.TestBit(TAxis::kAxisRange) ) {
7017  if (firstBinY == 1) firstBinY = 0;
7018  if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
7019  }
7020  if ( !fZaxis.TestBit(TAxis::kAxisRange) ) {
7021  if (firstBinZ == 1) firstBinZ = 0;
7022  if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
7023  }
7024  }
7025 
7026  Double_t x = 0;
7027  Double_t sum=0;
7028  Double_t np=0;
7029  for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
7030  for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
7031  for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
7032  if (axis==1 ) x = fXaxis.GetBinCenter(binx);
7033  else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
7034  else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
7035  Double_t w = GetBinContent(binx,biny,binz);
7036  np+=w;
7037  sum+=w*(x-mean)*(x-mean)*(x-mean);
7038  }
7039  }
7040  }
7041  sum/=np*stddev3;
7042  return sum;
7043  }
7044  else if (axis > 10 && axis <= 13) {
7045  //compute standard error of skewness
7046  // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
7047  Double_t neff = GetEffectiveEntries();
7048  return ( neff > 0 ? TMath::Sqrt(6./neff ) : 0. );
7049  }
7050  else {
7051  Error("GetSkewness", "illegal value of parameter");
7052  return 0;
7053  }
7054 }
7055 
7056 ////////////////////////////////////////////////////////////////////////////////
7057 /// - For axis =1, 2 or 3 returns kurtosis of the histogram along x, y or z axis.
7058 /// Kurtosis(gaussian(0, 1)) = 0.
7059 /// - For axis =11, 12 or 13 returns the approximate standard error of kurtosis
7060 /// of the histogram along x, y or z axis
7061 ////
7062 /// Note, that since third and fourth moment are not calculated
7063 /// at the fill time, kurtosis and its standard error are computed bin by bin
7064 
7065 Double_t TH1::GetKurtosis(Int_t axis) const
7066 {
7067  if (axis > 0 && axis <= 3){
7068 
7069  Double_t mean = GetMean(axis);
7070  Double_t stddev = GetStdDev(axis);
7071  Double_t stddev4 = stddev*stddev*stddev*stddev;
7072 
7073  Int_t firstBinX = fXaxis.GetFirst();
7074  Int_t lastBinX = fXaxis.GetLast();
7075  Int_t firstBinY = fYaxis.GetFirst();
7076  Int_t lastBinY = fYaxis.GetLast();
7077  Int_t firstBinZ = fZaxis.GetFirst();
7078  Int_t lastBinZ = fZaxis.GetLast();
7079  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7080  if (GetStatOverflowsBehaviour()) {
7081  if ( !fXaxis.TestBit(TAxis::kAxisRange) ) {
7082  if (firstBinX == 1) firstBinX = 0;
7083  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7084  }
7085  if ( !fYaxis.TestBit(TAxis::kAxisRange) ) {
7086  if (firstBinY == 1) firstBinY = 0;
7087  if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
7088  }
7089  if ( !fZaxis.TestBit(TAxis::kAxisRange) ) {
7090  if (firstBinZ == 1) firstBinZ = 0;
7091  if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
7092  }
7093  }
7094 
7095  Double_t x = 0;
7096  Double_t sum=0;
7097  Double_t np=0;
7098  for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
7099  for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
7100  for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
7101  if (axis==1 ) x = fXaxis.GetBinCenter(binx);
7102  else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
7103  else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
7104  Double_t w = GetBinContent(binx,biny,binz);
7105  np+=w;
7106  sum+=w*(x-mean)*(x-mean)*(x-mean)*(x-mean);
7107  }
7108  }
7109  }
7110  sum/=(np*stddev4);
7111  return sum-3;
7112 
7113  } else if (axis > 10 && axis <= 13) {
7114  //compute standard error of skewness
7115  // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
7116  Double_t neff = GetEffectiveEntries();
7117  return ( neff > 0 ? TMath::Sqrt(24./neff ) : 0. );
7118  }
7119  else {
7120  Error("GetKurtosis", "illegal value of parameter");
7121  return 0;
7122  }
7123 }
7124 
7125 ////////////////////////////////////////////////////////////////////////////////
7126 /// fill the array stats from the contents of this histogram
7127 /// The array stats must be correctly dimensioned in the calling program.
7128 ///
7129 /// ~~~ {.cpp}
7130 /// stats[0] = sumw
7131 /// stats[1] = sumw2
7132 /// stats[2] = sumwx
7133 /// stats[3] = sumwx2
7134 /// ~~~
7135 ///
7136 /// If no axis-subrange is specified (via TAxis::SetRange), the array stats
7137 /// is simply a copy of the statistics quantities computed at filling time.
7138 /// If a sub-range is specified, the function recomputes these quantities
7139 /// from the bin contents in the current axis range.
7140 ///
7141 /// Note that the mean value/StdDev is computed using the bins in the currently
7142 /// defined range (see TAxis::SetRange). By default the range includes
7143 /// all bins from 1 to nbins included, excluding underflows and overflows.
7144 /// To force the underflows and overflows in the computation, one must
7145 /// call the static function TH1::StatOverflows(kTRUE) before filling
7146 /// the histogram.
7147 
7148 void TH1::GetStats(Double_t *stats) const
7149 {
7150  if (fBuffer) ((TH1*)this)->BufferEmpty();
7151 
7152  // Loop on bins (possibly including underflows/overflows)
7153  Int_t bin, binx;
7154  Double_t w,err;
7155  Double_t x;
7156  // case of labels with extension of axis range
7157  // statistics in x does not make any sense - set to zero
7158  if ((const_cast<TAxis&>(fXaxis)).GetLabels() && CanExtendAllAxes() ) {
7159  stats[0] = fTsumw;
7160  stats[1] = fTsumw2;
7161  stats[2] = 0;
7162  stats[3] = 0;
7163  }
7164  else if ((fTsumw == 0 && fEntries > 0) || fXaxis.TestBit(TAxis::kAxisRange)) {
7165  for (bin=0;bin<4;bin++) stats[bin] = 0;
7166 
7167  Int_t firstBinX = fXaxis.GetFirst();
7168  Int_t lastBinX = fXaxis.GetLast();
7169  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7171  if (firstBinX == 1) firstBinX = 0;
7172  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7173  }
7174  for (binx = firstBinX; binx <= lastBinX; binx++) {
7175  x = fXaxis.GetBinCenter(binx);
7176  //w = TMath::Abs(RetrieveBinContent(binx));
7177  // not sure what to do here if w < 0
7178  w = RetrieveBinContent(binx);
7179  err = TMath::Abs(GetBinError(binx));
7180  stats[0] += w;
7181  stats[1] += err*err;
7182  stats[2] += w*x;
7183  stats[3] += w*x*x;
7184  }
7185  // if (stats[0] < 0) {
7186  // // in case total is negative do something ??
7187  // stats[0] = 0;
7188  // }
7189  } else {
7190  stats[0] = fTsumw;
7191  stats[1] = fTsumw2;
7192  stats[2] = fTsumwx;
7193  stats[3] = fTsumwx2;
7194  }
7195 }
7196 
7197 ////////////////////////////////////////////////////////////////////////////////
7198 /// Replace current statistics with the values in array stats
7199 
7200 void TH1::PutStats(Double_t *stats)
7201 {
7202  fTsumw = stats[0];
7203  fTsumw2 = stats[1];
7204  fTsumwx = stats[2];
7205  fTsumwx2 = stats[3];
7206 }
7207 
7208 ////////////////////////////////////////////////////////////////////////////////
7209 /// Reset the statistics including the number of entries
7210 /// and replace with values calculates from bin content
7211 ///
7212 /// The number of entries is set to the total bin content or (in case of weighted histogram)
7213 /// to number of effective entries
7214 
7215 void TH1::ResetStats()
7216 {
7217  Double_t stats[kNstat] = {0};
7218  fTsumw = 0;
7219  fEntries = 1; // to force re-calculation of the statistics in TH1::GetStats
7220  GetStats(stats);
7221  PutStats(stats);
7223  // use effective entries for weighted histograms: (sum_w) ^2 / sum_w2
7224  if (fSumw2.fN > 0 && fTsumw > 0 && stats[1] > 0 ) fEntries = stats[0]*stats[0]/ stats[1];
7225 }
7226 
7227 ////////////////////////////////////////////////////////////////////////////////
7228 /// Return the sum of weights excluding under/overflows.
7229 
7231 {
7232  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
7233 
7234  Int_t bin,binx,biny,binz;
7235  Double_t sum =0;
7236  for(binz=1; binz<=fZaxis.GetNbins(); binz++) {
7237  for(biny=1; biny<=fYaxis.GetNbins(); biny++) {
7238  for(binx=1; binx<=fXaxis.GetNbins(); binx++) {
7239  bin = GetBin(binx,biny,binz);
7240  sum += RetrieveBinContent(bin);
7241  }
7242  }
7243  }
7244  return sum;
7245 }
7246 
7247 ////////////////////////////////////////////////////////////////////////////////
7248 ///Return integral of bin contents. Only bins in the bins range are considered.
7249 ///
7250 /// By default the integral is computed as the sum of bin contents in the range.
7251 /// if option "width" is specified, the integral is the sum of
7252 /// the bin contents multiplied by the bin width in x.
7253 
7254 Double_t TH1::Integral(Option_t *option) const
7255 {
7256  return Integral(fXaxis.GetFirst(),fXaxis.GetLast(),option);
7257 }
7258 
7259 ////////////////////////////////////////////////////////////////////////////////
7260 /// Return integral of bin contents in range [binx1,binx2].
7261 ///
7262 /// By default the integral is computed as the sum of bin contents in the range.
7263 /// if option "width" is specified, the integral is the sum of
7264 /// the bin contents multiplied by the bin width in x.
7265 
7266 Double_t TH1::Integral(Int_t binx1, Int_t binx2, Option_t *option) const
7267 {
7268  double err = 0;
7269  return DoIntegral(binx1,binx2,0,-1,0,-1,err,option);
7270 }
7271 
7272 ////////////////////////////////////////////////////////////////////////////////
7273 /// Return integral of bin contents in range [binx1,binx2] and its error.
7274 ///
7275 /// By default the integral is computed as the sum of bin contents in the range.
7276 /// if option "width" is specified, the integral is the sum of
7277 /// the bin contents multiplied by the bin width in x.
7278 /// the error is computed using error propagation from the bin errors assuming that
7279 /// all the bins are uncorrelated
7280 
7281 Double_t TH1::IntegralAndError(Int_t binx1, Int_t binx2, Double_t & error, Option_t *option) const
7282 {
7283  return DoIntegral(binx1,binx2,0,-1,0,-1,error,option,kTRUE);
7284 }
7285 
7286 ////////////////////////////////////////////////////////////////////////////////
7287 /// Internal function compute integral and optionally the error between the limits
7288 /// specified by the bin number values working for all histograms (1D, 2D and 3D)
7289 
7290 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 ,
7291  Option_t *option, Bool_t doError) const
7293  if (fBuffer) ((TH1*)this)->BufferEmpty();
7294 
7295  Int_t nx = GetNbinsX() + 2;
7296  if (binx1 < 0) binx1 = 0;
7297  if (binx2 >= nx || binx2 < binx1) binx2 = nx - 1;
7298 
7299  if (GetDimension() > 1) {
7300  Int_t ny = GetNbinsY() + 2;
7301  if (biny1 < 0) biny1 = 0;
7302  if (biny2 >= ny || biny2 < biny1) biny2 = ny - 1;
7303  } else {
7304  biny1 = 0; biny2 = 0;
7305  }
7306 
7307  if (GetDimension() > 2) {
7308  Int_t nz = GetNbinsZ() + 2;
7309  if (binz1 < 0) binz1 = 0;
7310  if (binz2 >= nz || binz2 < binz1) binz2 = nz - 1;
7311  } else {
7312  binz1 = 0; binz2 = 0;
7313  }
7314 
7315  // - Loop on bins in specified range
7316  TString opt = option;
7317  opt.ToLower();
7318  Bool_t width = kFALSE;
7319  if (opt.Contains("width")) width = kTRUE;
7320 
7321 
7322  Double_t dx = 1., dy = .1, dz =.1;
7323  Double_t integral = 0;
7324  Double_t igerr2 = 0;
7325  for (Int_t binx = binx1; binx <= binx2; ++binx) {
7326  if (width) dx = fXaxis.GetBinWidth(binx);
7327  for (Int_t biny = biny1; biny <= biny2; ++biny) {
7328  if (width) dy = fYaxis.GetBinWidth(biny);
7329  for (Int_t binz = binz1; binz <= binz2; ++binz) {
7330  Int_t bin = GetBin(binx, biny, binz);
7331  Double_t dv = 0.0;
7332  if (width) {
7333  dz = fZaxis.GetBinWidth(binz);
7334  dv = dx * dy * dz;
7335  integral += RetrieveBinContent(bin) * dv;
7336  } else {
7337  integral += RetrieveBinContent(bin);
7338  }
7339  if (doError) {
7340  if (width) igerr2 += GetBinErrorSqUnchecked(bin) * dv * dv;
7341  else igerr2 += GetBinErrorSqUnchecked(bin);
7342  }
7343  }
7344  }
7345  }
7346 
7347  if (doError) error = TMath::Sqrt(igerr2);
7348  return integral;
7349 }
7350 
7351 ////////////////////////////////////////////////////////////////////////////////
7352 /// Statistical test of compatibility in shape between
7353 /// this histogram and h2, using the Anderson-Darling 2 sample test.
7354 ///
7355 /// The AD 2 sample test formula are derived from the paper
7356 /// F.W Scholz, M.A. Stephens "k-Sample Anderson-Darling Test".
7357 ///
7358 /// The test is implemented in root in the ROOT::Math::GoFTest class
7359 /// It is the same formula ( (6) in the paper), and also shown in
7360 /// [this preprint](http://arxiv.org/pdf/0804.0380v1.pdf)
7361 ///
7362 /// Binned data are considered as un-binned data
7363 /// with identical observation happening in the bin center.
7364 ///
7365 /// \param[in] option is a character string to specify options
7366 /// - "D" Put out a line of "Debug" printout
7367 /// - "T" Return the normalized A-D test statistic
7368 ///
7369 /// - Note1: Underflow and overflow are not considered in the test
7370 /// - Note2: The test works only for un-weighted histogram (i.e. representing counts)
7371 /// - Note3: The histograms are not required to have the same X axis
7372 /// - Note4: The test works only for 1-dimensional histograms
7373 
7374 Double_t TH1::AndersonDarlingTest(const TH1 *h2, Option_t *option) const
7375 {
7376  Double_t advalue = 0;
7377  Double_t pvalue = AndersonDarlingTest(h2, advalue);
7378 
7379  TString opt = option;
7380  opt.ToUpper();
7381  if (opt.Contains("D") ) {
7382  printf(" AndersonDarlingTest Prob = %g, AD TestStatistic = %g\n",pvalue,advalue);
7383  }
7384  if (opt.Contains("T") ) return advalue;
7385 
7386  return pvalue;
7387 }
7388 
7389 ////////////////////////////////////////////////////////////////////////////////
7390 /// Same function as above but returning also the test statistic value
7391 
7392 Double_t TH1::AndersonDarlingTest(const TH1 *h2, Double_t & advalue) const
7393 {
7394  if (GetDimension() != 1 || h2->GetDimension() != 1) {
7395  Error("AndersonDarlingTest","Histograms must be 1-D");
7396  return -1;
7397  }
7398 
7399  // empty the buffer. Probably we could add as an unbinned test
7400  if (fBuffer) ((TH1*)this)->BufferEmpty();
7401 
7402  // use the BinData class
7403  ROOT::Fit::BinData data1;
7404  ROOT::Fit::BinData data2;
7405 
7406  ROOT::Fit::FillData(data1, this, 0);
7407  ROOT::Fit::FillData(data2, h2, 0);
7408 
7409  double pvalue;
7410  ROOT::Math::GoFTest::AndersonDarling2SamplesTest(data1,data2, pvalue,advalue);
7411 
7412  return pvalue;
7413 }
7414 
7415 ////////////////////////////////////////////////////////////////////////////////
7416 /// Statistical test of compatibility in shape between
7417 /// this histogram and h2, using Kolmogorov test.
7418 /// Note that the KolmogorovTest (KS) test should in theory be used only for unbinned data
7419 /// and not for binned data as in the case of the histogram (see NOTE 3 below).
7420 /// So, before using this method blindly, read the NOTE 3.
7421 ///
7422 /// Default: Ignore under- and overflow bins in comparison
7423 ///
7424 /// \param[in] h2 histogram
7425 /// \param[in] option is a character string to specify options
7426 /// - "U" include Underflows in test (also for 2-dim)
7427 /// - "O" include Overflows (also valid for 2-dim)
7428 /// - "N" include comparison of normalizations
7429 /// - "D" Put out a line of "Debug" printout
7430 /// - "M" Return the Maximum Kolmogorov distance instead of prob
7431 /// - "X" Run the pseudo experiments post-processor with the following procedure:
7432 /// make pseudoexperiments based on random values from the parent distribution,
7433 /// compare the KS distance of the pseudoexperiment to the parent
7434 /// distribution, and count all the KS values above the value
7435 /// obtained from the original data to Monte Carlo distribution.
7436 /// The number of pseudo-experiments nEXPT is currently fixed at 1000.
7437 /// The function returns the probability.
7438 /// (thanks to Ben Kilminster to submit this procedure). Note that
7439 /// this option "X" is much slower.
7440 ///
7441 /// The returned function value is the probability of test
7442 /// (much less than one means NOT compatible)
7443 ///
7444 /// Code adapted by Rene Brun from original HBOOK routine HDIFF
7445 ///
7446 /// NOTE1
7447 /// A good description of the Kolmogorov test can be seen at:
7448 /// http://www.itl.nist.gov/div898/handbook/eda/section3/eda35g.htm
7449 ///
7450 /// NOTE2
7451 /// see also alternative function TH1::Chi2Test
7452 /// The Kolmogorov test is assumed to give better results than Chi2Test
7453 /// in case of histograms with low statistics.
7454 ///
7455 /// NOTE3 (Jan Conrad, Fred James)
7456 /// "The returned value PROB is calculated such that it will be
7457 /// uniformly distributed between zero and one for compatible histograms,
7458 /// provided the data are not binned (or the number of bins is very large
7459 /// compared with the number of events). Users who have access to unbinned
7460 /// data and wish exact confidence levels should therefore not put their data
7461 /// into histograms, but should call directly TMath::KolmogorovTest. On
7462 /// the other hand, since TH1 is a convenient way of collecting data and
7463 /// saving space, this function has been provided. However, the values of
7464 /// PROB for binned data will be shifted slightly higher than expected,
7465 /// depending on the effects of the binning. For example, when comparing two
7466 /// uniform distributions of 500 events in 100 bins, the values of PROB,
7467 /// instead of being exactly uniformly distributed between zero and one, have
7468 /// a mean value of about 0.56. We can apply a useful
7469 /// rule: As long as the bin width is small compared with any significant
7470 /// physical effect (for example the experimental resolution) then the binning
7471 /// cannot have an important effect. Therefore, we believe that for all
7472 /// practical purposes, the probability value PROB is calculated correctly
7473 /// provided the user is aware that:
7474 ///
7475 /// 1. The value of PROB should not be expected to have exactly the correct
7476 /// distribution for binned data.
7477 /// 2. The user is responsible for seeing to it that the bin widths are
7478 /// small compared with any physical phenomena of interest.
7479 /// 3. The effect of binning (if any) is always to make the value of PROB
7480 /// slightly too big. That is, setting an acceptance criterion of (PROB>0.05
7481 /// will assure that at most 5% of truly compatible histograms are rejected,
7482 /// and usually somewhat less."
7483 ///
7484 /// Note also that for GoF test of unbinned data ROOT provides also the class
7485 /// ROOT::Math::GoFTest. The class has also method for doing one sample tests
7486 /// (i.e. comparing the data with a given distribution).
7487 
7488 Double_t TH1::KolmogorovTest(const TH1 *h2, Option_t *option) const
7489 {
7490  TString opt = option;
7491  opt.ToUpper();
7492 
7493  Double_t prob = 0;
7494  TH1 *h1 = (TH1*)this;
7495  if (h2 == 0) return 0;
7496  const TAxis *axis1 = h1->GetXaxis();
7497  const TAxis *axis2 = h2->GetXaxis();
7498  Int_t ncx1 = axis1->GetNbins();
7499  Int_t ncx2 = axis2->GetNbins();
7500 
7501  // Check consistency of dimensions
7502  if (h1->GetDimension() != 1 || h2->GetDimension() != 1) {
7503  Error("KolmogorovTest","Histograms must be 1-D\n");
7504  return 0;
7505  }
7506 
7507  // Check consistency in number of channels
7508  if (ncx1 != ncx2) {
7509  Error("KolmogorovTest","Histograms have different number of bins, %d and %d\n",ncx1,ncx2);
7510  return 0;
7511  }
7512 
7513  // empty the buffer. Probably we could add as an unbinned test
7514  if (fBuffer) ((TH1*)this)->BufferEmpty();
7515 
7516  // Check consistency in bin edges
7517  for(Int_t i = 1; i <= axis1->GetNbins() + 1; ++i) {
7518  if(!TMath::AreEqualRel(axis1->GetBinLowEdge(i), axis2->GetBinLowEdge(i), 1.E-15)) {
7519  Error("KolmogorovTest","Histograms are not consistent: they have different bin edges");
7520  return 0;
7521  }
7522  }
7523 
7524  Bool_t afunc1 = kFALSE;
7525  Bool_t afunc2 = kFALSE;
7526  Double_t sum1 = 0, sum2 = 0;
7527  Double_t ew1, ew2, w1 = 0, w2 = 0;
7528  Int_t bin;
7529  Int_t ifirst = 1;
7530  Int_t ilast = ncx1;
7531  // integral of all bins (use underflow/overflow if option)
7532  if (opt.Contains("U")) ifirst = 0;
7533  if (opt.Contains("O")) ilast = ncx1 +1;
7534  for (bin = ifirst; bin <= ilast; bin++) {
7535  sum1 += h1->RetrieveBinContent(bin);
7536  sum2 += h2->RetrieveBinContent(bin);
7537  ew1 = h1->GetBinError(bin);
7538  ew2 = h2->GetBinError(bin);
7539  w1 += ew1*ew1;
7540  w2 += ew2*ew2;
7541  }
7542  if (sum1 == 0) {
7543  Error("KolmogorovTest","Histogram1 %s integral is zero\n",h1->GetName());
7544  return 0;
7545  }
7546  if (sum2 == 0) {
7547  Error("KolmogorovTest","Histogram2 %s integral is zero\n",h2->GetName());
7548  return 0;
7549  }
7550 
7551  // calculate the effective entries.
7552  // the case when errors are zero (w1 == 0 or w2 ==0) are equivalent to
7553  // compare to a function. In that case the rescaling is done only on sqrt(esum2) or sqrt(esum1)
7554  Double_t esum1 = 0, esum2 = 0;
7555  if (w1 > 0)
7556  esum1 = sum1 * sum1 / w1;
7557  else
7558  afunc1 = kTRUE; // use later for calculating z
7559 
7560  if (w2 > 0)
7561  esum2 = sum2 * sum2 / w2;
7562  else
7563  afunc2 = kTRUE; // use later for calculating z
7564 
7565  if (afunc2 && afunc1) {
7566  Error("KolmogorovTest","Errors are zero for both histograms\n");
7567  return 0;
7568  }
7569 
7570 
7571  Double_t s1 = 1/sum1;
7572  Double_t s2 = 1/sum2;
7573 
7574  // Find largest difference for Kolmogorov Test
7575  Double_t dfmax =0, rsum1 = 0, rsum2 = 0;
7576 
7577  for (bin=ifirst;bin<=ilast;bin++) {
7578  rsum1 += s1*h1->RetrieveBinContent(bin);
7579  rsum2 += s2*h2->RetrieveBinContent(bin);
7580  dfmax = TMath::Max(dfmax,TMath::Abs(rsum1-rsum2));
7581  }
7582 
7583  // Get Kolmogorov probability
7584  Double_t z, prb1=0, prb2=0, prb3=0;
7585 
7586  // case h1 is exact (has zero errors)
7587  if (afunc1)
7588  z = dfmax*TMath::Sqrt(esum2);
7589  // case h2 has zero errors
7590  else if (afunc2)
7591  z = dfmax*TMath::Sqrt(esum1);
7592  else
7593  // for comparison between two data sets
7594  z = dfmax*TMath::Sqrt(esum1*esum2/(esum1+esum2));
7595 
7596  prob = TMath::KolmogorovProb(z);
7597 
7598  // option N to combine normalization makes sense if both afunc1 and afunc2 are false
7599  if (opt.Contains("N") && !(afunc1 || afunc2 ) ) {
7600  // Combine probabilities for shape and normalization,
7601  prb1 = prob;
7602  Double_t d12 = esum1-esum2;
7603  Double_t chi2 = d12*d12/(esum1+esum2);
7604  prb2 = TMath::Prob(chi2,1);
7605  // see Eadie et al., section 11.6.2
7606  if (prob > 0 && prb2 > 0) prob *= prb2*(1-TMath::Log(prob*prb2));
7607  else prob = 0;
7608  }
7609  // X option. Pseudo-experiments post-processor to determine KS probability
7610  const Int_t nEXPT = 1000;
7611  if (opt.Contains("X") && !(afunc1 || afunc2 ) ) {
7612  Double_t dSEXPT;
7613  TH1 *h1_cpy = (TH1 *)(gDirectory ? gDirectory->CloneObject(this, kFALSE) : gROOT->CloneObject(this, kFALSE));
7614  TH1 *hExpt = (TH1*)(gDirectory ? gDirectory->CloneObject(this,kFALSE) : gROOT->CloneObject(this,kFALSE));
7615 
7616  if (h1_cpy->GetMinimum() < 0.0) {
7617  // With negative bins we can't draw random samples in a meaningful way.
7618  Warning("KolmogorovTest", "Detected bins with negative weights, these have been ignored and output might be "
7619  "skewed. Reduce number of bins for histogram?");
7620  while (h1_cpy->GetMinimum() < 0.0) {
7621  Int_t idx = h1_cpy->GetMinimumBin();
7622  h1_cpy->SetBinContent(idx, 0.0);
7623  }
7624  }
7625 
7626  // make nEXPT experiments (this should be a parameter)
7627  prb3 = 0;
7628  for (Int_t i=0; i < nEXPT; i++) {
7629  hExpt->Reset();
7630  hExpt->FillRandom(h1_cpy, (Int_t)esum2);
7631  dSEXPT = KolmogorovTest(hExpt,"M");
7632  if (dSEXPT>dfmax) prb3 += 1.0;
7633  }
7634  prb3 /= (Double_t)nEXPT;
7635  delete h1_cpy;
7636  delete hExpt;
7637  }
7638 
7639  // debug printout
7640  if (opt.Contains("D")) {
7641  printf(" Kolmo Prob h1 = %s, sum bin content =%g effective entries =%g\n",h1->GetName(),sum1,esum1);
7642  printf(" Kolmo Prob h2 = %s, sum bin content =%g effective entries =%g\n",h2->GetName(),sum2,esum2);
7643  printf(" Kolmo Prob = %g, Max Dist = %g\n",prob,dfmax);
7644  if (opt.Contains("N"))
7645  printf(" Kolmo Prob = %f for shape alone, =%f for normalisation alone\n",prb1,prb2);
7646  if (opt.Contains("X"))
7647  printf(" Kolmo Prob = %f with %d pseudo-experiments\n",prb3,nEXPT);
7648  }
7649  // This numerical error condition should never occur:
7650  if (TMath::Abs(rsum1-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h1=%s\n",h1->GetName());
7651  if (TMath::Abs(rsum2-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h2=%s\n",h2->GetName());
7652 
7653  if(opt.Contains("M")) return dfmax;
7654  else if(opt.Contains("X")) return prb3;
7655  else return prob;
7656 }
7657 
7658 ////////////////////////////////////////////////////////////////////////////////
7659 /// Replace bin contents by the contents of array content
7660 
7661 void TH1::SetContent(const Double_t *content)
7662 {
7664  fTsumw = 0;
7665  for (Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, content[i]);
7666 }
7667 
7668 ////////////////////////////////////////////////////////////////////////////////
7669 /// Return contour values into array levels if pointer levels is non zero.
7670 ///
7671 /// The function returns the number of contour levels.
7672 /// see GetContourLevel to return one contour only
7673 
7675 {
7676  Int_t nlevels = fContour.fN;
7677  if (levels) {
7678  if (nlevels == 0) {
7679  nlevels = 20;
7680  SetContour(nlevels);
7681  } else {
7682  if (TestBit(kUserContour) == 0) SetContour(nlevels);
7683  }
7684  for (Int_t level=0; level<nlevels; level++) levels[level] = fContour.fArray[level];
7685  }
7686  return nlevels;
7687 }
7688 
7689 ////////////////////////////////////////////////////////////////////////////////
7690 /// Return value of contour number level.
7691 /// Use GetContour to return the array of all contour levels
7692 
7693 Double_t TH1::GetContourLevel(Int_t level) const
7694 {
7695  return (level >= 0 && level < fContour.fN) ? fContour.fArray[level] : 0.0;
7696 }
7697 
7698 ////////////////////////////////////////////////////////////////////////////////
7699 /// Return the value of contour number "level" in Pad coordinates.
7700 /// ie: if the Pad is in log scale along Z it returns le log of the contour level
7701 /// value. See GetContour to return the array of all contour levels
7702 
7704 {
7705  if (level <0 || level >= fContour.fN) return 0;
7706  Double_t zlevel = fContour.fArray[level];
7707 
7708  // In case of user defined contours and Pad in log scale along Z,
7709  // fContour.fArray doesn't contain the log of the contour whereas it does
7710  // in case of equidistant contours.
7711  if (gPad && gPad->GetLogz() && TestBit(kUserContour)) {
7712  if (zlevel <= 0) return 0;
7713  zlevel = TMath::Log10(zlevel);
7714  }
7715  return zlevel;
7716 }
7717 
7718 ////////////////////////////////////////////////////////////////////////////////
7719 /// Set the maximum number of entries to be kept in the buffer.
7720 
7721 void TH1::SetBuffer(Int_t buffersize, Option_t * /*option*/)
7722 {
7723  if (fBuffer) {
7724  BufferEmpty();
7725  delete [] fBuffer;
7726  fBuffer = 0;
7727  }
7728  if (buffersize <= 0) {
7729  fBufferSize = 0;
7730  return;
7731  }
7732  if (buffersize < 100) buffersize = 100;
7733  fBufferSize = 1 + buffersize*(fDimension+1);
7734  fBuffer = new Double_t[fBufferSize];
7735  memset(fBuffer,0,sizeof(Double_t)*fBufferSize);
7736 }
7737 
7738 ////////////////////////////////////////////////////////////////////////////////
7739 /// Set the number and values of contour levels.
7740 ///
7741 /// By default the number of contour levels is set to 20. The contours values
7742 /// in the array "levels" should be specified in increasing order.
7743 ///
7744 /// if argument levels = 0 or missing, equidistant contours are computed
7745 
7746 void TH1::SetContour(Int_t nlevels, const Double_t *levels)
7747 {
7748  Int_t level;
7750  if (nlevels <=0 ) {
7751  fContour.Set(0);
7752  return;
7753  }
7754  fContour.Set(nlevels);
7755 
7756  // - Contour levels are specified
7757  if (levels) {
7759  for (level=0; level<nlevels; level++) fContour.fArray[level] = levels[level];
7760  } else {
7761  // - contour levels are computed automatically as equidistant contours
7762  Double_t zmin = GetMinimum();
7763  Double_t zmax = GetMaximum();
7764  if ((zmin == zmax) && (zmin != 0)) {
7765  zmax += 0.01*TMath::Abs(zmax);
7766  zmin -= 0.01*TMath::Abs(zmin);
7767  }
7768  Double_t dz = (zmax-zmin)/Double_t(nlevels);
7769  if (gPad && gPad->GetLogz()) {
7770  if (zmax <= 0) return;
7771  if (zmin <= 0) zmin = 0.001*zmax;
7772  zmin = TMath::Log10(zmin);
7773  zmax = TMath::Log10(zmax);
7774  dz = (zmax-zmin)/Double_t(nlevels);
7775  }
7776  for (level=0; level<nlevels; level++) {
7777  fContour.fArray[level] = zmin + dz*Double_t(level);
7778  }
7779  }
7780 }
7781 
7782 ////////////////////////////////////////////////////////////////////////////////
7783 /// Set value for one contour level.
7784 
7785 void TH1::SetContourLevel(Int_t level, Double_t value)
7786 {
7787  if (level < 0 || level >= fContour.fN) return;
7789  fContour.fArray[level] = value;
7790 }
7791 
7792 ////////////////////////////////////////////////////////////////////////////////
7793 /// Return maximum value smaller than maxval of bins in the range,
7794 /// unless the value has been overridden by TH1::SetMaximum,
7795 /// in which case it returns that value. (This happens, for example,
7796 /// when the histogram is drawn and the y or z axis limits are changed
7797 ///
7798 /// To get the maximum value of bins in the histogram regardless of
7799 /// whether the value has been overridden, use
7800 ///
7801 /// ~~~ {.cpp}
7802 /// h->GetBinContent(h->GetMaximumBin())
7803 /// ~~~
7804 
7805 Double_t TH1::GetMaximum(Double_t maxval) const
7806 {
7807  if (fMaximum != -1111) return fMaximum;
7808 
7809  // empty the buffer
7810  if (fBuffer) ((TH1*)this)->BufferEmpty();
7811 
7812  Int_t bin, binx, biny, binz;
7813  Int_t xfirst = fXaxis.GetFirst();
7814  Int_t xlast = fXaxis.GetLast();
7815  Int_t yfirst = fYaxis.GetFirst();
7816  Int_t ylast = fYaxis.GetLast();
7817  Int_t zfirst = fZaxis.GetFirst();
7818  Int_t zlast = fZaxis.GetLast();
7819  Double_t maximum = -FLT_MAX, value;
7820  for (binz=zfirst;binz<=zlast;binz++) {
7821  for (biny=yfirst;biny<=ylast;biny++) {
7822  for (binx=xfirst;binx<=xlast;binx++) {
7823  bin = GetBin(binx,biny,binz);
7824  value = RetrieveBinContent(bin);
7825  if (value > maximum && value < maxval) maximum = value;
7826  }
7827  }
7828  }
7829  return maximum;
7830 }
7831 
7832 ////////////////////////////////////////////////////////////////////////////////
7833 /// Return location of bin with maximum value in the range.
7834 
7835 Int_t TH1::GetMaximumBin() const
7836 {
7837  Int_t locmax, locmay, locmaz;
7838  return GetMaximumBin(locmax, locmay, locmaz);
7839 }
7840 
7841 ////////////////////////////////////////////////////////////////////////////////
7842 /// Return location of bin with maximum value in the range.
7843 
7844 Int_t TH1::GetMaximumBin(Int_t &locmax, Int_t &locmay, Int_t &locmaz) const
7845 {
7846  // empty the buffer
7847  if (fBuffer) ((TH1*)this)->BufferEmpty();
7848 
7849  Int_t bin, binx, biny, binz;
7850  Int_t locm;
7851  Int_t xfirst = fXaxis.GetFirst();
7852  Int_t xlast = fXaxis.GetLast();
7853  Int_t yfirst = fYaxis.GetFirst();
7854  Int_t ylast = fYaxis.GetLast();
7855  Int_t zfirst = fZaxis.GetFirst();
7856  Int_t zlast = fZaxis.GetLast();
7857  Double_t maximum = -FLT_MAX, value;
7858  locm = locmax = locmay = locmaz = 0;
7859  for (binz=zfirst;binz<=zlast;binz++) {
7860  for (biny=yfirst;biny<=ylast;biny++) {
7861  for (binx=xfirst;binx<=xlast;binx++) {
7862  bin = GetBin(binx,biny,binz);
7863  value = RetrieveBinContent(bin);
7864  if (value > maximum) {
7865  maximum = value;
7866  locm = bin;
7867  locmax = binx;
7868  locmay = biny;
7869  locmaz = binz;
7870  }
7871  }
7872  }
7873  }
7874  return locm;
7875 }
7876 
7877 ////////////////////////////////////////////////////////////////////////////////
7878 /// Return minimum value larger than minval of bins in the range,
7879 /// unless the value has been overridden by TH1::SetMinimum,
7880 /// in which case it returns that value. (This happens, for example,
7881 /// when the histogram is drawn and the y or z axis limits are changed
7882 ///
7883 /// To get the minimum value of bins in the histogram regardless of
7884 /// whether the value has been overridden, use
7885 ///
7886 /// ~~~ {.cpp}
7887 /// h->GetBinContent(h->GetMinimumBin())
7888 /// ~~~
7889 
7890 Double_t TH1::GetMinimum(Double_t minval) const
7891 {
7892  if (fMinimum != -1111) return fMinimum;
7893 
7894  // empty the buffer
7895  if (fBuffer) ((TH1*)this)->BufferEmpty();
7896 
7897  Int_t bin, binx, biny, binz;
7898  Int_t xfirst = fXaxis.GetFirst();
7899  Int_t xlast = fXaxis.GetLast();
7900  Int_t yfirst = fYaxis.GetFirst();
7901  Int_t ylast = fYaxis.GetLast();
7902  Int_t zfirst = fZaxis.GetFirst();
7903  Int_t zlast = fZaxis.GetLast();
7904  Double_t minimum=FLT_MAX, value;
7905  for (binz=zfirst;binz<=zlast;binz++) {
7906  for (biny=yfirst;biny<=ylast;biny++) {
7907  for (binx=xfirst;binx<=xlast;binx++) {
7908  bin = GetBin(binx,biny,binz);
7909  value = RetrieveBinContent(bin);
7910  if (value < minimum && value > minval) minimum = value;
7911  }
7912  }
7913  }
7914  return minimum;
7915 }
7916 
7917 ////////////////////////////////////////////////////////////////////////////////
7918 /// Return location of bin with minimum value in the range.
7919 
7920 Int_t TH1::GetMinimumBin() const
7921 {
7922  Int_t locmix, locmiy, locmiz;
7923  return GetMinimumBin(locmix, locmiy, locmiz);
7924 }
7925 
7926 ////////////////////////////////////////////////////////////////////////////////
7927 /// Return location of bin with minimum value in the range.
7928 
7929 Int_t TH1::GetMinimumBin(Int_t &locmix, Int_t &locmiy, Int_t &locmiz) const
7930 {
7931  // empty the buffer
7932  if (fBuffer) ((TH1*)this)->BufferEmpty();
7933 
7934  Int_t bin, binx, biny, binz;
7935  Int_t locm;
7936  Int_t xfirst = fXaxis.GetFirst();
7937  Int_t xlast = fXaxis.GetLast();
7938  Int_t yfirst = fYaxis.GetFirst();
7939  Int_t ylast = fYaxis.GetLast();
7940  Int_t zfirst = fZaxis.GetFirst();
7941  Int_t zlast = fZaxis.GetLast();
7942  Double_t minimum = FLT_MAX, value;
7943  locm = locmix = locmiy = locmiz = 0;
7944  for (binz=zfirst;binz<=zlast;binz++) {
7945  for (biny=yfirst;biny<=ylast;biny++) {
7946  for (binx=xfirst;binx<=xlast;binx++) {
7947  bin = GetBin(binx,biny,binz);
7948  value = RetrieveBinContent(bin);
7949  if (value < minimum) {
7950  minimum = value;
7951  locm = bin;
7952  locmix = binx;
7953  locmiy = biny;
7954  locmiz = binz;
7955  }
7956  }
7957  }
7958  }
7959  return locm;
7960 }
7961 
7962 ///////////////////////////////////////////////////////////////////////////////
7963 /// Retrieve the minimum and maximum values in the histogram
7964 ///
7965 /// This will not return a cached value and will always search the
7966 /// histogram for the min and max values. The user can condition whether
7967 /// or not to call this with the GetMinimumStored() and GetMaximumStored()
7968 /// methods. If the cache is empty, then the value will be -1111. Users
7969 /// can then use the SetMinimum() or SetMaximum() methods to cache the results.
7970 /// For example, the following recipe will make efficient use of this method
7971 /// and the cached minimum and maximum values.
7972 //
7973 /// \code{.cpp}
7974 /// Double_t currentMin = pHist->GetMinimumStored();
7975 /// Double_t currentMax = pHist->GetMaximumStored();
7976 /// if ((currentMin == -1111) || (currentMax == -1111)) {
7977 /// pHist->GetMinimumAndMaximum(currentMin, currentMax);
7978 /// pHist->SetMinimum(currentMin);
7979 /// pHist->SetMaximum(currentMax);
7980 /// }
7981 /// \endcode
7982 ///
7983 /// \param min reference to variable that will hold found minimum value
7984 /// \param max reference to variable that will hold found maximum value
7985 
7986 void TH1::GetMinimumAndMaximum(Double_t& min, Double_t& max) const
7987 {
7988  // empty the buffer
7989  if (fBuffer) ((TH1*)this)->BufferEmpty();
7990 
7991  Int_t bin, binx, biny, binz;
7992  Int_t xfirst = fXaxis.GetFirst();
7993  Int_t xlast = fXaxis.GetLast();
7994  Int_t yfirst = fYaxis.GetFirst();
7995  Int_t ylast = fYaxis.GetLast();
7996  Int_t zfirst = fZaxis.GetFirst();
7997  Int_t zlast = fZaxis.GetLast();
7998  min=TMath::Infinity();
7999  max=-TMath::Infinity();
8000  Double_t value;
8001  for (binz=zfirst;binz<=zlast;binz++) {
8002  for (biny=yfirst;biny<=ylast;biny++) {
8003  for (binx=xfirst;binx<=xlast;binx++) {
8004  bin = GetBin(binx,biny,binz);
8005  value = RetrieveBinContent(bin);
8006  if (value < min) min = value;
8007  if (value > max) max = value;
8008  }
8009  }
8010  }
8011 }
8012 
8013 ////////////////////////////////////////////////////////////////////////////////
8014 /// Redefine x axis parameters.
8015 ///
8016 /// The X axis parameters are modified.
8017 /// The bins content array is resized
8018 /// if errors (Sumw2) the errors array is resized
8019 /// The previous bin contents are lost
8020 /// To change only the axis limits, see TAxis::SetRange
8021 
8022 void TH1::SetBins(Int_t nx, Double_t xmin, Double_t xmax)
8023 {
8024  if (GetDimension() != 1) {
8025  Error("SetBins","Operation only valid for 1-d histograms");
8026  return;
8027  }
8028  fXaxis.SetRange(0,0);
8029  fXaxis.Set(nx,xmin,xmax);
8030  fYaxis.Set(1,0,1);
8031  fZaxis.Set(1,0,1);
8032  fNcells = nx+2;
8033  SetBinsLength(fNcells);
8034  if (fSumw2.fN) {
8035  fSumw2.Set(fNcells);
8036  }
8037 }
8038 
8039 ////////////////////////////////////////////////////////////////////////////////
8040 /// Redefine x axis parameters with variable bin sizes.
8041 ///
8042 /// The X axis parameters are modified.
8043 /// The bins content array is resized
8044 /// if errors (Sumw2) the errors array is resized
8045 /// The previous bin contents are lost
8046 /// To change only the axis limits, see TAxis::SetRange
8047 /// xBins is supposed to be of length nx+1
8048 
8049 void TH1::SetBins(Int_t nx, const Double_t *xBins)
8050 {
8051  if (GetDimension() != 1) {
8052  Error("SetBins","Operation only valid for 1-d histograms");
8053  return;
8054  }
8055  fXaxis.SetRange(0,0);
8056  fXaxis.Set(nx,xBins);
8057  fYaxis.Set(1,0,1);
8058  fZaxis.Set(1,0,1);
8059  fNcells = nx+2;
8060  SetBinsLength(fNcells);
8061  if (fSumw2.fN) {
8062  fSumw2.Set(fNcells);
8063  }
8064 }
8065 
8066 ////////////////////////////////////////////////////////////////////////////////
8067 /// Redefine x and y axis parameters.
8068 ///
8069 /// The X and Y axis parameters are modified.
8070 /// The bins content array is resized
8071 /// if errors (Sumw2) the errors array is resized
8072 /// The previous bin contents are lost
8073 /// To change only the axis limits, see TAxis::SetRange
8074 
8075 void TH1::SetBins(Int_t nx, Double_t xmin, Double_t xmax, Int_t ny, Double_t ymin, Double_t ymax)
8076 {
8077  if (GetDimension() != 2) {
8078  Error("SetBins","Operation only valid for 2-D histograms");
8079  return;
8080  }
8081  fXaxis.SetRange(0,0);
8082  fYaxis.SetRange(0,0);
8083  fXaxis.Set(nx,xmin,xmax);
8084  fYaxis.Set(ny,ymin,ymax);
8085  fZaxis.Set(1,0,1);
8086  fNcells = (nx+2)*(ny+2);
8087  SetBinsLength(fNcells);
8088  if (fSumw2.fN) {
8089  fSumw2.Set(fNcells);
8090  }
8091 }
8092 
8093 ////////////////////////////////////////////////////////////////////////////////
8094 /// Redefine x and y axis parameters with variable bin sizes.
8095 ///
8096 /// The X and Y axis parameters are modified.
8097 /// The bins content array is resized
8098 /// if errors (Sumw2) the errors array is resized
8099 /// The previous bin contents are lost
8100 /// To change only the axis limits, see TAxis::SetRange
8101 /// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1
8102 
8103 void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins)
8104 {
8105  if (GetDimension() != 2) {
8106  Error("SetBins","Operation only valid for 2-D histograms");
8107  return;
8108  }
8109  fXaxis.SetRange(0,0);
8110  fYaxis.SetRange(0,0);
8111  fXaxis.Set(nx,xBins);
8112  fYaxis.Set(ny,yBins);
8113  fZaxis.Set(1,0,1);
8114  fNcells = (nx+2)*(ny+2);
8115  SetBinsLength(fNcells);
8116  if (fSumw2.fN) {
8117  fSumw2.Set(fNcells);
8118  }
8119 }
8120 
8121 ////////////////////////////////////////////////////////////////////////////////
8122 /// Redefine x, y and z axis parameters.
8123 ///
8124 /// The X, Y and Z axis parameters are modified.
8125 /// The bins content array is resized
8126 /// if errors (Sumw2) the errors array is resized
8127 /// The previous bin contents are lost
8128 /// To change only the axis limits, see TAxis::SetRange
8129 
8130 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)
8131 {
8132  if (GetDimension() != 3) {
8133  Error("SetBins","Operation only valid for 3-D histograms");
8134  return;
8135  }
8136  fXaxis.SetRange(0,0);
8137  fYaxis.SetRange(0,0);
8138  fZaxis.SetRange(0,0);
8139  fXaxis.Set(nx,xmin,xmax);
8140  fYaxis.Set(ny,ymin,ymax);
8141  fZaxis.Set(nz,zmin,zmax);
8142  fNcells = (nx+2)*(ny+2)*(nz+2);
8143  SetBinsLength(fNcells);
8144  if (fSumw2.fN) {
8145  fSumw2.Set(fNcells);
8146  }
8147 }
8148 
8149 ////////////////////////////////////////////////////////////////////////////////
8150 /// Redefine x, y and z axis parameters with variable bin sizes.
8151 ///
8152 /// The X, Y and Z axis parameters are modified.
8153 /// The bins content array is resized
8154 /// if errors (Sumw2) the errors array is resized
8155 /// The previous bin contents are lost
8156 /// To change only the axis limits, see TAxis::SetRange
8157 /// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1,
8158 /// zBins is supposed to be of length nz+1
8159 
8160 void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins, Int_t nz, const Double_t *zBins)
8161 {
8162  if (GetDimension() != 3) {
8163  Error("SetBins","Operation only valid for 3-D histograms");
8164  return;
8165  }
8166  fXaxis.SetRange(0,0);
8167  fYaxis.SetRange(0,0);
8168  fZaxis.SetRange(0,0);
8169  fXaxis.Set(nx,xBins);
8170  fYaxis.Set(ny,yBins);
8171  fZaxis.Set(nz,zBins);
8172  fNcells = (nx+2)*(ny+2)*(nz+2);
8173  SetBinsLength(fNcells);
8174  if (fSumw2.fN) {
8175  fSumw2.Set(fNcells);
8176  }
8177 }
8178 
8179 ////////////////////////////////////////////////////////////////////////////////
8180 /// By default when an histogram is created, it is added to the list
8181 /// of histogram objects in the current directory in memory.
8182 /// Remove reference to this histogram from current directory and add
8183 /// reference to new directory dir. dir can be 0 in which case the
8184 /// histogram does not belong to any directory.
8185 ///
8186 /// Note that the directory is not a real property of the histogram and
8187 /// it will not be copied when the histogram is copied or cloned.
8188 /// If the user wants to have the copied (cloned) histogram in the same
8189 /// directory, he needs to set again the directory using SetDirectory to the
8190 /// copied histograms
8191 
8192 void TH1::SetDirectory(TDirectory *dir)
8193 {
8194  if (fDirectory == dir) return;
8195  if (fDirectory) fDirectory->Remove(this);
8196  fDirectory = dir;
8197  if (fDirectory) {
8198  fFunctions->UseRWLock();
8199  fDirectory->Append(this);
8200  }
8201 }
8202 
8203 ////////////////////////////////////////////////////////////////////////////////
8204 /// Replace bin errors by values in array error.
8205 
8206 void TH1::SetError(const Double_t *error)
8207 {
8208  for (Int_t i = 0; i < fNcells; ++i) SetBinError(i, error[i]);
8209 }
8210 
8211 ////////////////////////////////////////////////////////////////////////////////
8212 /// Change the name of this histogram
8213 ///
8214 
8215 void TH1::SetName(const char *name)
8216 {
8217  // Histograms are named objects in a THashList.
8218  // We must update the hashlist if we change the name
8219  // We protect this operation
8221  if (fDirectory) fDirectory->Remove(this);
8222  fName = name;
8223  if (fDirectory) fDirectory->Append(this);
8224 }
8225 
8226 ////////////////////////////////////////////////////////////////////////////////
8227 /// Change the name and title of this histogram
8228 
8229 void TH1::SetNameTitle(const char *name, const char *title)
8230 {
8231  // Histograms are named objects in a THashList.
8232  // We must update the hashlist if we change the name
8233  SetName(name);
8234  SetTitle(title);
8235 }
8236 
8237 ////////////////////////////////////////////////////////////////////////////////
8238 /// Set statistics option on/off
8239 ///
8240 /// By default, the statistics box is drawn.
8241 /// The paint options can be selected via gStyle->SetOptStats.
8242 /// This function sets/resets the kNoStats bin in the histogram object.
8243 /// It has priority over the Style option.
8244 
8245 void TH1::SetStats(Bool_t stats)
8246 {
8248  if (!stats) {
8249  SetBit(kNoStats);
8250  //remove the "stats" object from the list of functions
8251  if (fFunctions) {
8252  TObject *obj = fFunctions->FindObject("stats");
8253  if (obj) {
8254  fFunctions->Remove(obj);
8255  delete obj;
8256  }
8257  }
8258  }
8259 }
8260 
8261 ////////////////////////////////////////////////////////////////////////////////
8262 /// Create structure to store sum of squares of weights.
8263 ///
8264 /// if histogram is already filled, the sum of squares of weights
8265 /// is filled with the existing bin contents
8266 ///
8267 /// The error per bin will be computed as sqrt(sum of squares of weight)
8268 /// for each bin.
8269 ///
8270 /// This function is automatically called when the histogram is created
8271 /// if the static function TH1::SetDefaultSumw2 has been called before.
8272 /// If flag = false the structure is deleted
8273 
8274 void TH1::Sumw2(Bool_t flag)
8275 {
8276  if (!flag) {
8277  // clear the array if existing - do nothing otherwise
8278  if (fSumw2.fN > 0 ) fSumw2.Set(0);
8279  return;
8280  }
8281 
8282  if (fSumw2.fN == fNcells) {
8283  if (!fgDefaultSumw2 )
8284  Warning("Sumw2","Sum of squares of weights structure already created");
8285  return;
8286  }
8287 
8288  fSumw2.Set(fNcells);
8289 
8290  // empty the buffer
8291  if (fBuffer) BufferEmpty();
8292 
8293  if (fEntries > 0)
8294  for (Int_t i = 0; i < fNcells; ++i)
8296 }
8297 
8298 ////////////////////////////////////////////////////////////////////////////////
8299 /// Return pointer to function with name.
8300 ///
8301 ///
8302 /// Functions such as TH1::Fit store the fitted function in the list of
8303 /// functions of this histogram.
8304 
8305 TF1 *TH1::GetFunction(const char *name) const
8306 {
8307  return (TF1*)fFunctions->FindObject(name);
8308 }
8309 
8310 ////////////////////////////////////////////////////////////////////////////////
8311 /// Return value of error associated to bin number bin.
8312 ///
8313 /// if the sum of squares of weights has been defined (via Sumw2),
8314 /// this function returns the sqrt(sum of w2).
8315 /// otherwise it returns the sqrt(contents) for this bin.
8316 
8317 Double_t TH1::GetBinError(Int_t bin) const
8318 {
8319  if (bin < 0) bin = 0;
8320  if (bin >= fNcells) bin = fNcells-1;
8321  if (fBuffer) ((TH1*)this)->BufferEmpty();
8322  if (fSumw2.fN) return TMath::Sqrt(fSumw2.fArray[bin]);
8323 
8325 }
8326 
8327 ////////////////////////////////////////////////////////////////////////////////
8328 /// Return lower error associated to bin number bin.
8329 ///
8330 /// The error will depend on the statistic option used will return
8331 /// the binContent - lower interval value
8332 
8334 {
8335  if (fBinStatErrOpt == kNormal) return GetBinError(bin);
8336  // in case of weighted histogram check if it is really weighted
8337  if (fSumw2.fN && fTsumw != fTsumw2) return GetBinError(bin);
8338 
8339  if (bin < 0) bin = 0;
8340  if (bin >= fNcells) bin = fNcells-1;
8341  if (fBuffer) ((TH1*)this)->BufferEmpty();
8342 
8343  Double_t alpha = 1.- 0.682689492;
8344  if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
8345 
8346  Double_t c = RetrieveBinContent(bin);
8347  Int_t n = int(c);
8348  if (n < 0) {
8349  Warning("GetBinErrorLow","Histogram has negative bin content-force usage to normal errors");
8350  ((TH1*)this)->fBinStatErrOpt = kNormal;
8351  return GetBinError(bin);
8352  }
8353 
8354  if (n == 0) return 0;
8355  return c - ROOT::Math::gamma_quantile( alpha/2, n, 1.);
8356 }
8357 
8358 ////////////////////////////////////////////////////////////////////////////////
8359 /// Return upper error associated to bin number bin.
8360 ///
8361 /// The error will depend on the statistic option used will return
8362 /// the binContent - upper interval value
8363 
8365 {
8366  if (fBinStatErrOpt == kNormal) return GetBinError(bin);
8367  // in case of weighted histogram check if it is really weighted
8368  if (fSumw2.fN && fTsumw != fTsumw2) return GetBinError(bin);
8369  if (bin < 0) bin = 0;
8370  if (bin >= fNcells) bin = fNcells-1;
8371  if (fBuffer) ((TH1*)this)->BufferEmpty();
8372 
8373  Double_t alpha = 1.- 0.682689492;
8374  if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
8375 
8376  Double_t c = RetrieveBinContent(bin);
8377  Int_t n = int(c);
8378  if (n < 0) {
8379  Warning("GetBinErrorUp","Histogram has negative bin content-force usage to normal errors");
8380  ((TH1*)this)->fBinStatErrOpt = kNormal;
8381  return GetBinError(bin);
8382  }
8383 
8384  // for N==0 return an upper limit at 0.68 or (1-alpha)/2 ?
8385  // decide to return always (1-alpha)/2 upper interval
8386  //if (n == 0) return ROOT::Math::gamma_quantile_c(alpha,n+1,1);
8387  return ROOT::Math::gamma_quantile_c( alpha/2, n+1, 1) - c;
8388 }
8389 
8390 //L.M. These following getters are useless and should be probably deprecated
8391 ////////////////////////////////////////////////////////////////////////////////
8392 /// Return bin center for 1D histogram.
8393 /// Better to use h1.GetXaxis().GetBinCenter(bin)
8394 
8395 Double_t TH1::GetBinCenter(Int_t bin) const
8396 {
8397  if (fDimension == 1) return fXaxis.GetBinCenter(bin);
8398  Error("GetBinCenter","Invalid method for a %d-d histogram - return a NaN",fDimension);
8399  return TMath::QuietNaN();
8400 }
8401 
8402 ////////////////////////////////////////////////////////////////////////////////
8403 /// Return bin lower edge for 1D histogram.
8404 /// Better to use h1.GetXaxis().GetBinLowEdge(bin)
8405 
8407 {
8408  if (fDimension == 1) return fXaxis.GetBinLowEdge(bin);
8409  Error("GetBinLowEdge","Invalid method for a %d-d histogram - return a NaN",fDimension);
8410  return TMath::QuietNaN();
8411 }
8412 
8413 ////////////////////////////////////////////////////////////////////////////////
8414 /// Return bin width for 1D histogram.
8415 /// Better to use h1.GetXaxis().GetBinWidth(bin)
8416 
8417 Double_t TH1::GetBinWidth(Int_t bin) const
8418 {
8419  if (fDimension == 1) return fXaxis.GetBinWidth(bin);
8420  Error("GetBinWidth","Invalid method for a %d-d histogram - return a NaN",fDimension);
8421  return TMath::QuietNaN();
8422 }
8423 
8424 ////////////////////////////////////////////////////////////////////////////////
8425 /// Fill array with center of bins for 1D histogram
8426 /// Better to use h1.GetXaxis().GetCenter(center)
8427 
8428 void TH1::GetCenter(Double_t *center) const
8429 {
8430  if (fDimension == 1) {
8431  fXaxis.GetCenter(center);
8432  return;
8433  }
8434  Error("GetCenter","Invalid method for a %d-d histogram ",fDimension);
8435 }
8436 
8437 ////////////////////////////////////////////////////////////////////////////////
8438 /// Fill array with low edge of bins for 1D histogram
8439 /// Better to use h1.GetXaxis().GetLowEdge(edge)
8440 
8441 void TH1::GetLowEdge(Double_t *edge) const
8442 {
8443  if (fDimension == 1) {
8444  fXaxis.GetLowEdge(edge);
8445  return;
8446  }
8447  Error("GetLowEdge","Invalid method for a %d-d histogram ",fDimension);
8448 }
8449 
8450 ////////////////////////////////////////////////////////////////////////////////
8451 /// Set the bin Error
8452 /// Note that this resets the bin eror option to be of Normal Type and for the
8453 /// non-empty bin the bin error is set by default to the square root of their content,
8454 /// but in case the user sets explicitly a new bin content (using SetBinContent) he needs to provide also
8455 /// the error, otherwise a default error = 0 is used.
8456 ///
8457 /// See convention for numbering bins in TH1::GetBin
8458 
8459 void TH1::SetBinError(Int_t bin, Double_t error)
8460 {
8461  if (!fSumw2.fN) Sumw2();
8462  if (bin < 0 || bin>= fSumw2.fN) return;
8463  fSumw2.fArray[bin] = error * error;
8464  // reset the bin error option
8466 }
8467 
8468 ////////////////////////////////////////////////////////////////////////////////
8469 /// Set bin content
8470 /// see convention for numbering bins in TH1::GetBin
8471 /// In case the bin number is greater than the number of bins and
8472 /// the timedisplay option is set or CanExtendAllAxes(),
8473 /// the number of bins is automatically doubled to accommodate the new bin
8474 
8475 void TH1::SetBinContent(Int_t bin, Double_t content)
8476 {
8478  fTsumw = 0;
8479  if (bin < 0) return;
8480  if (bin >= fNcells-1) {
8481  if (fXaxis.GetTimeDisplay() || CanExtendAllAxes() ) {
8482  while (bin >= fNcells-1) LabelsInflate();
8483  } else {
8484  if (bin == fNcells-1) UpdateBinContent(bin, content);
8485  return;
8486  }
8487  }
8488  UpdateBinContent(bin, content);
8489 }
8490 
8491 ////////////////////////////////////////////////////////////////////////////////
8492 /// See convention for numbering bins in TH1::GetBin
8493 
8494 void TH1::SetBinError(Int_t binx, Int_t biny, Double_t error)
8495 {
8496  if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
8497  if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
8498  SetBinError(GetBin(binx, biny), error);
8499 }
8500 
8501 ////////////////////////////////////////////////////////////////////////////////
8502 /// See convention for numbering bins in TH1::GetBin
8503 
8504 void TH1::SetBinError(Int_t binx, Int_t biny, Int_t binz, Double_t error)
8505 {
8506  if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
8507  if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
8508  if (binz < 0 || binz > fZaxis.GetNbins() + 1) return;
8509  SetBinError(GetBin(binx, biny, binz), error);
8510 }
8511 
8512 ////////////////////////////////////////////////////////////////////////////////
8513 /// This function calculates the background spectrum in this histogram.
8514 /// The background is returned as a histogram.
8515 ///
8516 /// \param[in] niter number of iterations (default value = 2)
8517 /// Increasing niter make the result smoother and lower.
8518 /// \param[in] option may contain one of the following options
8519 /// - to set the direction parameter
8520 /// "BackDecreasingWindow". By default the direction is BackIncreasingWindow
8521 /// - filterOrder-order of clipping filter (default "BackOrder2")
8522 /// possible values= "BackOrder4" "BackOrder6" "BackOrder8"
8523 /// - "nosmoothing" - if selected, the background is not smoothed
8524 /// By default the background is smoothed.
8525 /// - smoothWindow - width of smoothing window, (default is "BackSmoothing3")
8526 /// possible values= "BackSmoothing5" "BackSmoothing7" "BackSmoothing9"
8527 /// "BackSmoothing11" "BackSmoothing13" "BackSmoothing15"
8528 /// - "nocompton" - if selected the estimation of Compton edge
8529 /// will be not be included (by default the compton estimation is set)
8530 /// - "same" if this option is specified, the resulting background
8531 /// histogram is superimposed on the picture in the current pad.
8532 /// This option is given by default.
8533 ///
8534 /// NOTE that the background is only evaluated in the current range of this histogram.
8535 /// i.e., if this has a bin range (set via h->GetXaxis()->SetRange(binmin, binmax),
8536 /// the returned histogram will be created with the same number of bins
8537 /// as this input histogram, but only bins from binmin to binmax will be filled
8538 /// with the estimated background.
8539 
8540 TH1 *TH1::ShowBackground(Int_t niter, Option_t *option)
8541 {
8543  return (TH1*)gROOT->ProcessLineFast(Form("TSpectrum::StaticBackground((TH1*)0x%lx,%d,\"%s\")",
8544  (ULong_t)this, niter, option));
8545 }
8546 
8547 ////////////////////////////////////////////////////////////////////////////////
8548 /// Interface to TSpectrum::Search.
8549 /// The function finds peaks in this histogram where the width is > sigma
8550 /// and the peak maximum greater than threshold*maximum bin content of this.
8551 /// For more details see TSpectrum::Search.
8552 /// Note the difference in the default value for option compared to TSpectrum::Search
8553 /// option="" by default (instead of "goff").
8554 
8555 Int_t TH1::ShowPeaks(Double_t sigma, Option_t *option, Double_t threshold)
8556 {
8557  return (Int_t)gROOT->ProcessLineFast(Form("TSpectrum::StaticSearch((TH1*)0x%lx,%g,\"%s\",%g)",
8558  (ULong_t)this, sigma, option, threshold));
8559 }
8560 
8561 ////////////////////////////////////////////////////////////////////////////////
8562 /// For a given transform (first parameter), fills the histogram (second parameter)
8563 /// with the transform output data, specified in the third parameter
8564 /// If the 2nd parameter h_output is empty, a new histogram (TH1D or TH2D) is created
8565 /// and the user is responsible for deleting it.
8566 ///
8567 /// Available options:
8568 /// - "RE" - real part of the output
8569 /// - "IM" - imaginary part of the output
8570 /// - "MAG" - magnitude of the output
8571 /// - "PH" - phase of the output
8572 
8573 TH1* TH1::TransformHisto(TVirtualFFT *fft, TH1* h_output, Option_t *option)
8574 {
8575  if (!fft || !fft->GetN() ) {
8576  ::Error("TransformHisto","Invalid FFT transform class");
8577  return 0;
8578  }
8579 
8580  if (fft->GetNdim()>2){
8581  ::Error("TransformHisto","Only 1d and 2D transform are supported");
8582  return 0;
8583  }
8584  Int_t binx,biny;
8585  TString opt = option;
8586  opt.ToUpper();
8587  Int_t *n = fft->GetN();
8588  TH1 *hout=0;
8589  if (h_output) {
8590  hout = h_output;
8591  }
8592  else {
8593  TString name = TString::Format("out_%s", opt.Data());
8594  if (fft->GetNdim()==1)
8595  hout = new TH1D(name, name,n[0], 0, n[0]);
8596  else if (fft->GetNdim()==2)
8597  hout = new TH2D(name, name, n[0], 0, n[0], n[1], 0, n[1]);
8598  }
8599  R__ASSERT(hout != 0);
8600  TString type=fft->GetType();
8601  Int_t ind[2];
8602  if (opt.Contains("RE")){
8603  if (type.Contains("2C") || type.Contains("2HC")) {
8604  Double_t re, im;
8605  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8606  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8607  ind[0] = binx-1; ind[1] = biny-1;
8608  fft->GetPointComplex(ind, re, im);
8609  hout->SetBinContent(binx, biny, re);
8610  }
8611  }
8612  } else {
8613  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8614  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8615  ind[0] = binx-1; ind[1] = biny-1;
8616  hout->SetBinContent(binx, biny, fft->GetPointReal(ind));
8617  }
8618  }
8619  }
8620  }
8621  if (opt.Contains("IM")) {
8622  if (type.Contains("2C") || type.Contains("2HC")) {
8623  Double_t re, im;
8624  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8625  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8626  ind[0] = binx-1; ind[1] = biny-1;
8627  fft->GetPointComplex(ind, re, im);
8628  hout->SetBinContent(binx, biny, im);
8629  }
8630  }
8631  } else {
8632  ::Error("TransformHisto","No complex numbers in the output");
8633  return 0;
8634  }
8635  }
8636  if (opt.Contains("MA")) {
8637  if (type.Contains("2C") || type.Contains("2HC")) {
8638  Double_t re, im;
8639  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8640  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8641  ind[0] = binx-1; ind[1] = biny-1;
8642  fft->GetPointComplex(ind, re, im);
8643  hout->SetBinContent(binx, biny, TMath::Sqrt(re*re + im*im));
8644  }
8645  }
8646  } else {
8647  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8648  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8649  ind[0] = binx-1; ind[1] = biny-1;
8650  hout->SetBinContent(binx, biny, TMath::Abs(fft->GetPointReal(ind)));
8651  }
8652  }
8653  }
8654  }
8655  if (opt.Contains("PH")) {
8656  if (type.Contains("2C") || type.Contains("2HC")){
8657  Double_t re, im, ph;
8658  for (binx = 1; binx<=hout->GetNbinsX(); binx++){
8659  for (biny=1; biny<=hout->GetNbinsY(); biny++){
8660  ind[0] = binx-1; ind[1] = biny-1;
8661  fft->GetPointComplex(ind, re, im);
8662  if (TMath::Abs(re) > 1e-13){
8663  ph = TMath::ATan(im/re);
8664  //find the correct quadrant
8665  if (re<0 && im<0)
8666  ph -= TMath::Pi();
8667  if (re<0 && im>=0)
8668  ph += TMath::Pi();
8669  } else {
8670  if (TMath::Abs(im) < 1e-13)
8671  ph = 0;
8672  else if (im>0)
8673  ph = TMath::Pi()*0.5;
8674  else
8675  ph = -TMath::Pi()*0.5;
8676  }
8677  hout->SetBinContent(binx, biny, ph);
8678  }
8679  }
8680  } else {
8681  printf("Pure real output, no phase");
8682  return 0;
8683  }
8684  }
8685 
8686  return hout;
8687 }
8688 
8689 ////////////////////////////////////////////////////////////////////////////////
8690 /// Raw retrieval of bin content on internal data structure
8691 /// see convention for numbering bins in TH1::GetBin
8692 
8694 {
8695  AbstractMethod("RetrieveBinContent");
8696  return 0;
8697 }
8698 
8699 ////////////////////////////////////////////////////////////////////////////////
8700 /// Raw update of bin content on internal data structure
8701 /// see convention for numbering bins in TH1::GetBin
8702 
8704 {
8705  AbstractMethod("UpdateBinContent");
8706 }
8707 
8708 ////////////////////////////////////////////////////////////////////////////////
8709 /// Print value overload
8710 
8711 std::string cling::printValue(TH1 *val) {
8712  std::ostringstream strm;
8713  strm << cling::printValue((TObject*)val) << " NbinsX: " << val->GetNbinsX();
8714  return strm.str();
8715 }
8716 
8717 //______________________________________________________________________________
8718 // TH1C methods
8719 // TH1C : histograms with one byte per channel. Maximum bin content = 127
8720 //______________________________________________________________________________
8721 
8722 ClassImp(TH1C);
8723 
8724 ////////////////////////////////////////////////////////////////////////////////
8725 /// Constructor.
8726 
8727 TH1C::TH1C(): TH1(), TArrayC()
8728 {
8729  fDimension = 1;
8730  SetBinsLength(3);
8731  if (fgDefaultSumw2) Sumw2();
8732 }
8733 
8734 ////////////////////////////////////////////////////////////////////////////////
8735 /// Create a 1-Dim histogram with fix bins of type char (one byte per channel)
8736 /// (see TH1::TH1 for explanation of parameters)
8737 
8738 TH1C::TH1C(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
8739 : TH1(name,title,nbins,xlow,xup)
8741  fDimension = 1;
8742  TArrayC::Set(fNcells);
8743 
8744  if (xlow >= xup) SetBuffer(fgBufferSize);
8745  if (fgDefaultSumw2) Sumw2();
8746 }
8747 
8748 ////////////////////////////////////////////////////////////////////////////////
8749 /// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
8750 /// (see TH1::TH1 for explanation of parameters)
8751 
8752 TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
8753 : TH1(name,title,nbins,xbins)
8755  fDimension = 1;
8756  TArrayC::Set(fNcells);
8757  if (fgDefaultSumw2) Sumw2();
8758 }
8759 
8760 ////////////////////////////////////////////////////////////////////////////////
8761 /// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
8762 /// (see TH1::TH1 for explanation of parameters)
8763 
8764 TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
8765 : TH1(name,title,nbins,xbins)
8767  fDimension = 1;
8768  TArrayC::Set(fNcells);
8769  if (fgDefaultSumw2) Sumw2();
8770 }
8771 
8772 ////////////////////////////////////////////////////////////////////////////////
8773 /// Destructor.
8774 
8775 TH1C::~TH1C()
8776 {
8778 
8779 ////////////////////////////////////////////////////////////////////////////////
8780 /// Copy constructor.
8781 
8782 TH1C::TH1C(const TH1C &h1c) : TH1(), TArrayC()
8783 {
8784  ((TH1C&)h1c).Copy(*this);
8785 }
8786 
8787 ////////////////////////////////////////////////////////////////////////////////
8788 /// Increment bin content by 1.
8789 
8790 void TH1C::AddBinContent(Int_t bin)
8791 {
8792  if (fArray[bin] < 127) fArray[bin]++;
8793 }
8794 
8795 ////////////////////////////////////////////////////////////////////////////////
8796 /// Increment bin content by w.
8797 
8798 void TH1C::AddBinContent(Int_t bin, Double_t w)
8799 {
8800  Int_t newval = fArray[bin] + Int_t(w);
8801  if (newval > -128 && newval < 128) {fArray[bin] = Char_t(newval); return;}
8802  if (newval < -127) fArray[bin] = -127;
8803  if (newval > 127) fArray[bin] = 127;
8804 }
8805 
8806 ////////////////////////////////////////////////////////////////////////////////
8807 /// Copy this to newth1
8808 
8809 void TH1C::Copy(TObject &newth1) const
8810 {
8811  TH1::Copy(newth1);
8812 }
8813 
8814 ////////////////////////////////////////////////////////////////////////////////
8815 /// Reset.
8816 
8817 void TH1C::Reset(Option_t *option)
8818 {
8819  TH1::Reset(option);
8820  TArrayC::Reset();
8821 }
8822 
8823 ////////////////////////////////////////////////////////////////////////////////
8824 /// Set total number of bins including under/overflow
8825 /// Reallocate bin contents array
8826 
8827 void TH1C::SetBinsLength(Int_t n)
8828 {
8829  if (n < 0) n = fXaxis.GetNbins() + 2;
8830  fNcells = n;
8831  TArrayC::Set(n);
8832 }
8833 
8834 ////////////////////////////////////////////////////////////////////////////////
8835 /// Operator =
8836 
8837 TH1C& TH1C::operator=(const TH1C &h1)
8838 {
8839  if (this != &h1) ((TH1C&)h1).Copy(*this);
8840  return *this;
8841 }
8842 
8843 ////////////////////////////////////////////////////////////////////////////////
8844 /// Operator *
8845 
8846 TH1C operator*(Double_t c1, const TH1C &h1)
8847 {
8848  TH1C hnew = h1;
8849  hnew.Scale(c1);
8850  hnew.SetDirectory(0);
8851  return hnew;
8852 }
8853 
8854 ////////////////////////////////////////////////////////////////////////////////
8855 /// Operator +
8856 
8857 TH1C operator+(const TH1C &h1, const TH1C &h2)
8858 {
8859  TH1C hnew = h1;
8860  hnew.Add(&h2,1);
8861  hnew.SetDirectory(0);
8862  return hnew;
8863 }
8864 
8865 ////////////////////////////////////////////////////////////////////////////////
8866 /// Operator -
8867 
8868 TH1C operator-(const TH1C &h1, const TH1C &h2)
8869 {
8870  TH1C hnew = h1;
8871  hnew.Add(&h2,-1);
8872  hnew.SetDirectory(0);
8873  return hnew;
8874 }
8875 
8876 ////////////////////////////////////////////////////////////////////////////////
8877 /// Operator *
8878 
8879 TH1C operator*(const TH1C &h1, const TH1C &h2)
8880 {
8881  TH1C hnew = h1;
8882  hnew.Multiply(&h2);
8883  hnew.SetDirectory(0);
8884  return hnew;
8885 }
8886 
8887 ////////////////////////////////////////////////////////////////////////////////
8888 /// Operator /
8889 
8890 TH1C operator/(const TH1C &h1, const TH1C &h2)
8891 {
8892  TH1C hnew = h1;
8893  hnew.Divide(&h2);
8894  hnew.SetDirectory(0);
8895  return hnew;
8896 }
8897 
8898 //______________________________________________________________________________
8899 // TH1S methods
8900 // TH1S : histograms with one short per channel. Maximum bin content = 32767
8901 //______________________________________________________________________________
8902 
8903 ClassImp(TH1S);
8904 
8905 ////////////////////////////////////////////////////////////////////////////////
8906 /// Constructor.
8907 
8908 TH1S::TH1S(): TH1(), TArrayS()
8909 {
8910  fDimension = 1;
8911  SetBinsLength(3);
8912  if (fgDefaultSumw2) Sumw2();
8913 }
8914 
8915 ////////////////////////////////////////////////////////////////////////////////
8916 /// Create a 1-Dim histogram with fix bins of type short
8917 /// (see TH1::TH1 for explanation of parameters)
8918 
8919 TH1S::TH1S(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
8920 : TH1(name,title,nbins,xlow,xup)
8922  fDimension = 1;
8923  TArrayS::Set(fNcells);
8924 
8925  if (xlow >= xup) SetBuffer(fgBufferSize);
8926  if (fgDefaultSumw2) Sumw2();
8927 }
8928 
8929 ////////////////////////////////////////////////////////////////////////////////
8930 /// Create a 1-Dim histogram with variable bins of type short
8931 /// (see TH1::TH1 for explanation of parameters)
8932 
8933 TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
8934 : TH1(name,title,nbins,xbins)
8936  fDimension = 1;
8937  TArrayS::Set(fNcells);
8938  if (fgDefaultSumw2) Sumw2();
8939 }
8940 
8941 ////////////////////////////////////////////////////////////////////////////////
8942 /// Create a 1-Dim histogram with variable bins of type short
8943 /// (see TH1::TH1 for explanation of parameters)
8944 
8945 TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
8946 : TH1(name,title,nbins,xbins)
8948  fDimension = 1;
8949  TArrayS::Set(fNcells);
8950  if (fgDefaultSumw2) Sumw2();
8951 }
8952 
8953 ////////////////////////////////////////////////////////////////////////////////
8954 /// Destructor.
8955 
8956 TH1S::~TH1S()
8957 {
8959 
8960 ////////////////////////////////////////////////////////////////////////////////
8961 /// Copy constructor.
8962 
8963 TH1S::TH1S(const TH1S &h1s) : TH1(), TArrayS()
8964 {
8965  ((TH1S&)h1s).Copy(*this);
8966 }
8967 
8968 ////////////////////////////////////////////////////////////////////////////////
8969 /// Increment bin content by 1.
8970 
8971 void TH1S::AddBinContent(Int_t bin)
8972 {
8973  if (fArray[bin] < 32767) fArray[bin]++;
8974 }
8975 
8976 ////////////////////////////////////////////////////////////////////////////////
8977 /// Increment bin content by w
8978 
8979 void TH1S::AddBinContent(Int_t bin, Double_t w)
8980 {
8981  Int_t newval = fArray[bin] + Int_t(w);
8982  if (newval > -32768 && newval < 32768) {fArray[bin] = Short_t(newval); return;}
8983  if (newval < -32767) fArray[bin] = -32767;
8984  if (newval > 32767) fArray[bin] = 32767;
8985 }
8986 
8987 ////////////////////////////////////////////////////////////////////////////////
8988 /// Copy this to newth1
8989 
8990 void TH1S::Copy(TObject &newth1) const
8991 {
8992  TH1::Copy(newth1);
8993 }
8994 
8995 ////////////////////////////////////////////////////////////////////////////////
8996 /// Reset.
8997 
8998 void TH1S::Reset(Option_t *option)
8999 {
9000  TH1::Reset(option);
9001  TArrayS::Reset();
9002 }
9003 
9004 ////////////////////////////////////////////////////////////////////////////////
9005 /// Set total number of bins including under/overflow
9006 /// Reallocate bin contents array
9007 
9008 void TH1S::SetBinsLength(Int_t n)
9009 {
9010  if (n < 0) n = fXaxis.GetNbins() + 2;
9011  fNcells = n;
9012  TArrayS::Set(n);
9013 }
9014 
9015 ////////////////////////////////////////////////////////////////////////////////
9016 /// Operator =
9017 
9018 TH1S& TH1S::operator=(const TH1S &h1)
9019 {
9020  if (this != &h1) ((TH1S&)h1).Copy(*this);
9021  return *this;
9022 }
9023 
9024 ////////////////////////////////////////////////////////////////////////////////
9025 /// Operator *
9026 
9027 TH1S operator*(Double_t c1, const TH1S &h1)
9028 {
9029  TH1S hnew = h1;
9030  hnew.Scale(c1);
9031  hnew.SetDirectory(0);
9032  return hnew;
9033 }
9034 
9035 ////////////////////////////////////////////////////////////////////////////////
9036 /// Operator +
9037 
9038 TH1S operator+(const TH1S &h1, const TH1S &h2)
9039 {
9040  TH1S hnew = h1;
9041  hnew.Add(&h2,1);
9042  hnew.SetDirectory(0);
9043  return hnew;
9044 }
9045 
9046 ////////////////////////////////////////////////////////////////////////////////
9047 /// Operator -
9048 
9049 TH1S operator-(const TH1S &h1, const TH1S &h2)
9050 {
9051  TH1S hnew = h1;
9052  hnew.Add(&h2,-1);
9053  hnew.SetDirectory(0);
9054  return hnew;
9055 }
9056 
9057 ////////////////////////////////////////////////////////////////////////////////
9058 /// Operator *
9059 
9060 TH1S operator*(const TH1S &h1, const TH1S &h2)
9061 {
9062  TH1S hnew = h1;
9063  hnew.Multiply(&h2);
9064  hnew.SetDirectory(0);
9065  return hnew;
9066 }
9067 
9068 ////////////////////////////////////////////////////////////////////////////////
9069 /// Operator /
9070 
9071 TH1S operator/(const TH1S &h1, const TH1S &h2)
9072 {
9073  TH1S hnew = h1;
9074  hnew.Divide(&h2);
9075  hnew.SetDirectory(0);
9076  return hnew;
9077 }
9078 
9079 //______________________________________________________________________________
9080 // TH1I methods
9081 // TH1I : histograms with one int per channel. Maximum bin content = 2147483647
9082 //______________________________________________________________________________
9083 
9084 ClassImp(TH1I);
9085 
9086 ////////////////////////////////////////////////////////////////////////////////
9087 /// Constructor.
9088 
9089 TH1I::TH1I(): TH1(), TArrayI()
9090 {
9091  fDimension = 1;
9092  SetBinsLength(3);
9093  if (fgDefaultSumw2) Sumw2();
9094 }
9095 
9096 ////////////////////////////////////////////////////////////////////////////////
9097 /// Create a 1-Dim histogram with fix bins of type integer
9098 /// (see TH1::TH1 for explanation of parameters)
9099 
9100 TH1I::TH1I(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9101 : TH1(name,title,nbins,xlow,xup)
9103  fDimension = 1;
9104  TArrayI::Set(fNcells);
9105 
9106  if (xlow >= xup) SetBuffer(fgBufferSize);
9107  if (fgDefaultSumw2) Sumw2();
9108 }
9109 
9110 ////////////////////////////////////////////////////////////////////////////////
9111 /// Create a 1-Dim histogram with variable bins of type integer
9112 /// (see TH1::TH1 for explanation of parameters)
9113 
9114 TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9115 : TH1(name,title,nbins,xbins)
9117  fDimension = 1;
9118  TArrayI::Set(fNcells);
9119  if (fgDefaultSumw2) Sumw2();
9120 }
9121 
9122 ////////////////////////////////////////////////////////////////////////////////
9123 /// Create a 1-Dim histogram with variable bins of type integer
9124 /// (see TH1::TH1 for explanation of parameters)
9125 
9126 TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9127 : TH1(name,title,nbins,xbins)
9129  fDimension = 1;
9130  TArrayI::Set(fNcells);
9131  if (fgDefaultSumw2) Sumw2();
9132 }
9133 
9134 ////////////////////////////////////////////////////////////////////////////////
9135 /// Destructor.
9136 
9137 TH1I::~TH1I()
9138 {
9140 
9141 ////////////////////////////////////////////////////////////////////////////////
9142 /// Copy constructor.
9143 
9144 TH1I::TH1I(const TH1I &h1i) : TH1(), TArrayI()
9145 {
9146  ((TH1I&)h1i).Copy(*this);
9147 }
9148 
9149 ////////////////////////////////////////////////////////////////////////////////
9150 /// Increment bin content by 1.
9151 
9152 void TH1I::AddBinContent(Int_t bin)
9153 {
9154  if (fArray[bin] < 2147483647) fArray[bin]++;
9155 }
9156 
9157 ////////////////////////////////////////////////////////////////////////////////
9158 /// Increment bin content by w
9159 
9160 void TH1I::AddBinContent(Int_t bin, Double_t w)
9161 {
9162  Long64_t newval = fArray[bin] + Long64_t(w);
9163  if (newval > -2147483647 && newval < 2147483647) {fArray[bin] = Int_t(newval); return;}
9164  if (newval < -2147483647) fArray[bin] = -2147483647;
9165  if (newval > 2147483647) fArray[bin] = 2147483647;
9166 }
9167 
9168 ////////////////////////////////////////////////////////////////////////////////
9169 /// Copy this to newth1
9170 
9171 void TH1I::Copy(TObject &newth1) const
9172 {
9173  TH1::Copy(newth1);
9174 }
9175 
9176 ////////////////////////////////////////////////////////////////////////////////
9177 /// Reset.
9178 
9179 void TH1I::Reset(Option_t *option)
9180 {
9181  TH1::Reset(option);
9182  TArrayI::Reset();
9183 }
9184 
9185 ////////////////////////////////////////////////////////////////////////////////
9186 /// Set total number of bins including under/overflow
9187 /// Reallocate bin contents array
9188 
9189 void TH1I::SetBinsLength(Int_t n)
9190 {
9191  if (n < 0) n = fXaxis.GetNbins() + 2;
9192  fNcells = n;
9193  TArrayI::Set(n);
9194 }
9195 
9196 ////////////////////////////////////////////////////////////////////////////////
9197 /// Operator =
9198 
9199 TH1I& TH1I::operator=(const TH1I &h1)
9200 {
9201  if (this != &h1) ((TH1I&)h1).Copy(*this);
9202  return *this;
9203 }
9204 
9205 
9206 ////////////////////////////////////////////////////////////////////////////////
9207 /// Operator *
9208 
9209 TH1I operator*(Double_t c1, const TH1I &h1)
9210 {
9211  TH1I hnew = h1;
9212  hnew.Scale(c1);
9213  hnew.SetDirectory(0);
9214  return hnew;
9215 }
9216 
9217 ////////////////////////////////////////////////////////////////////////////////
9218 /// Operator +
9219 
9220 TH1I operator+(const TH1I &h1, const TH1I &h2)
9221 {
9222  TH1I hnew = h1;
9223  hnew.Add(&h2,1);
9224  hnew.SetDirectory(0);
9225  return hnew;
9226 }
9227 
9228 ////////////////////////////////////////////////////////////////////////////////
9229 /// Operator -
9230 
9231 TH1I operator-(const TH1I &h1, const TH1I &h2)
9232 {
9233  TH1I hnew = h1;
9234  hnew.Add(&h2,-1);
9235  hnew.SetDirectory(0);
9236  return hnew;
9237 }
9238 
9239 ////////////////////////////////////////////////////////////////////////////////
9240 /// Operator *
9241 
9242 TH1I operator*(const TH1I &h1, const TH1I &h2)
9243 {
9244  TH1I hnew = h1;
9245  hnew.Multiply(&h2);
9246  hnew.SetDirectory(0);
9247  return hnew;
9248 }
9249 
9250 ////////////////////////////////////////////////////////////////////////////////
9251 /// Operator /
9252 
9253 TH1I operator/(const TH1I &h1, const TH1I &h2)
9254 {
9255  TH1I hnew = h1;
9256  hnew.Divide(&h2);
9257  hnew.SetDirectory(0);
9258  return hnew;
9259 }
9260 
9261 //______________________________________________________________________________
9262 // TH1F methods
9263 // TH1F : histograms with one float per channel. Maximum precision 7 digits
9264 //______________________________________________________________________________
9265 
9266 ClassImp(TH1F);
9267 
9268 ////////////////////////////////////////////////////////////////////////////////
9269 /// Constructor.
9270 
9271 TH1F::TH1F(): TH1(), TArrayF()
9272 {
9273  fDimension = 1;
9274  SetBinsLength(3);
9275  if (fgDefaultSumw2) Sumw2();
9276 }
9277 
9278 ////////////////////////////////////////////////////////////////////////////////
9279 /// Create a 1-Dim histogram with fix bins of type float
9280 /// (see TH1::TH1 for explanation of parameters)
9281 
9282 TH1F::TH1F(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9283 : TH1(name,title,nbins,xlow,xup)
9285  fDimension = 1;
9286  TArrayF::Set(fNcells);
9287 
9288  if (xlow >= xup) SetBuffer(fgBufferSize);
9289  if (fgDefaultSumw2) Sumw2();
9290 }
9291 
9292 ////////////////////////////////////////////////////////////////////////////////
9293 /// Create a 1-Dim histogram with variable bins of type float
9294 /// (see TH1::TH1 for explanation of parameters)
9295 
9296 TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9297 : TH1(name,title,nbins,xbins)
9299  fDimension = 1;
9300  TArrayF::Set(fNcells);
9301  if (fgDefaultSumw2) Sumw2();
9302 }
9303 
9304 ////////////////////////////////////////////////////////////////////////////////
9305 /// Create a 1-Dim histogram with variable bins of type float
9306 /// (see TH1::TH1 for explanation of parameters)
9307 
9308 TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9309 : TH1(name,title,nbins,xbins)
9311  fDimension = 1;
9312  TArrayF::Set(fNcells);
9313  if (fgDefaultSumw2) Sumw2();
9314 }
9315 
9316 ////////////////////////////////////////////////////////////////////////////////
9317 /// Create a histogram from a TVectorF
9318 /// by default the histogram name is "TVectorF" and title = ""
9319 
9320 TH1F::TH1F(const TVectorF &v)
9321 : TH1("TVectorF","",v.GetNrows(),0,v.GetNrows())
9323  TArrayF::Set(fNcells);
9324  fDimension = 1;
9325  Int_t ivlow = v.GetLwb();
9326  for (Int_t i=0;i<fNcells-2;i++) {
9327  SetBinContent(i+1,v(i+ivlow));
9328  }
9329  TArrayF::Set(fNcells);
9330  if (fgDefaultSumw2) Sumw2();
9331 }
9332 
9333 ////////////////////////////////////////////////////////////////////////////////
9334 /// Copy Constructor.
9335 
9336 TH1F::TH1F(const TH1F &h) : TH1(), TArrayF()
9337 {
9338  ((TH1F&)h).Copy(*this);
9339 }
9340 
9341 ////////////////////////////////////////////////////////////////////////////////
9342 /// Destructor.
9343 
9344 TH1F::~TH1F()
9345 {
9347 
9348 ////////////////////////////////////////////////////////////////////////////////
9349 /// Copy this to newth1.
9350 
9351 void TH1F::Copy(TObject &newth1) const
9352 {
9353  TH1::Copy(newth1);
9354 }
9355 
9356 ////////////////////////////////////////////////////////////////////////////////
9357 /// Reset.
9358 
9359 void TH1F::Reset(Option_t *option)
9360 {
9361  TH1::Reset(option);
9362  TArrayF::Reset();
9363 }
9364 
9365 ////////////////////////////////////////////////////////////////////////////////
9366 /// Set total number of bins including under/overflow
9367 /// Reallocate bin contents array
9368 
9369 void TH1F::SetBinsLength(Int_t n)
9370 {
9371  if (n < 0) n = fXaxis.GetNbins() + 2;
9372  fNcells = n;
9373  TArrayF::Set(n);
9374 }
9375 
9376 ////////////////////////////////////////////////////////////////////////////////
9377 /// Operator =
9378 
9379 TH1F& TH1F::operator=(const TH1F &h1)
9380 {
9381  if (this != &h1) ((TH1F&)h1).Copy(*this);
9382  return *this;
9383 }
9384 
9385 ////////////////////////////////////////////////////////////////////////////////
9386 /// Operator *
9387 
9388 TH1F operator*(Double_t c1, const TH1F &h1)
9389 {
9390  TH1F hnew = h1;
9391  hnew.Scale(c1);
9392  hnew.SetDirectory(0);
9393  return hnew;
9394 }
9395 
9396 ////////////////////////////////////////////////////////////////////////////////
9397 /// Operator +
9398 
9399 TH1F operator+(const TH1F &h1, const TH1F &h2)
9400 {
9401  TH1F hnew = h1;
9402  hnew.Add(&h2,1);
9403  hnew.SetDirectory(0);
9404  return hnew;
9405 }
9406 
9407 ////////////////////////////////////////////////////////////////////////////////
9408 /// Operator -
9409 
9410 TH1F operator-(const TH1F &h1, const TH1F &h2)
9411 {
9412  TH1F hnew = h1;
9413  hnew.Add(&h2,-1);
9414  hnew.SetDirectory(0);
9415  return hnew;
9416 }
9417 
9418 ////////////////////////////////////////////////////////////////////////////////
9419 /// Operator *
9420 
9421 TH1F operator*(const TH1F &h1, const TH1F &h2)
9422 {
9423  TH1F hnew = h1;
9424  hnew.Multiply(&h2);
9425  hnew.SetDirectory(0);
9426  return hnew;
9427 }
9428 
9429 ////////////////////////////////////////////////////////////////////////////////
9430 /// Operator /
9431 
9432 TH1F operator/(const TH1F &h1, const TH1F &h2)
9433 {
9434  TH1F hnew = h1;
9435  hnew.Divide(&h2);
9436  hnew.SetDirectory(0);
9437  return hnew;
9438 }
9439 
9440 //______________________________________________________________________________
9441 // TH1D methods
9442 // TH1D : histograms with one double per channel. Maximum precision 14 digits
9443 //______________________________________________________________________________
9444 
9445 ClassImp(TH1D);
9446 
9447 ////////////////////////////////////////////////////////////////////////////////
9448 /// Constructor.
9449 
9450 TH1D::TH1D(): TH1(), TArrayD()
9451 {
9452  fDimension = 1;
9453  SetBinsLength(3);
9454  if (fgDefaultSumw2) Sumw2();
9455 }
9456 
9457 ////////////////////////////////////////////////////////////////////////////////
9458 /// Create a 1-Dim histogram with fix bins of type double
9459 /// (see TH1::TH1 for explanation of parameters)
9460 
9461 TH1D::TH1D(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9462 : TH1(name,title,nbins,xlow,xup)
9464  fDimension = 1;
9465  TArrayD::Set(fNcells);
9466 
9467  if (xlow >= xup) SetBuffer(fgBufferSize);
9468  if (fgDefaultSumw2) Sumw2();
9469 }
9470 
9471 ////////////////////////////////////////////////////////////////////////////////
9472 /// Create a 1-Dim histogram with variable bins of type double
9473 /// (see TH1::TH1 for explanation of parameters)
9474 
9475 TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9476 : TH1(name,title,nbins,xbins)
9478  fDimension = 1;
9479  TArrayD::Set(fNcells);
9480  if (fgDefaultSumw2) Sumw2();
9481 }
9482 
9483 ////////////////////////////////////////////////////////////////////////////////
9484 /// Create a 1-Dim histogram with variable bins of type double
9485 /// (see TH1::TH1 for explanation of parameters)
9486 
9487 TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9488 : TH1(name,title,nbins,xbins)
9490  fDimension = 1;
9491  TArrayD::Set(fNcells);
9492  if (fgDefaultSumw2) Sumw2();
9493 }
9494 
9495 ////////////////////////////////////////////////////////////////////////////////
9496 /// Create a histogram from a TVectorD
9497 /// by default the histogram name is "TVectorD" and title = ""
9498 
9499 TH1D::TH1D(const TVectorD &v)
9500 : TH1("TVectorD","",v.GetNrows(),0,v.GetNrows())
9502  TArrayD::Set(fNcells);
9503  fDimension = 1;
9504  Int_t ivlow = v.GetLwb();
9505  for (Int_t i=0;i<fNcells-2;i++) {
9506  SetBinContent(i+1,v(i+ivlow));
9507  }
9508  TArrayD::Set(fNcells);
9509  if (fgDefaultSumw2) Sumw2();
9510 }
9511 
9512 ////////////////////////////////////////////////////////////////////////////////
9513 /// Destructor.
9514 
9515 TH1D::~TH1D()
9516 {
9518 
9519 ////////////////////////////////////////////////////////////////////////////////
9520 /// Constructor.
9521 
9522 TH1D::TH1D(const TH1D &h1d) : TH1(), TArrayD()
9523 {
9524  ((TH1D&)h1d).Copy(*this);
9525 }
9526 
9527 ////////////////////////////////////////////////////////////////////////////////
9528 /// Copy this to newth1
9529 
9530 void TH1D::Copy(TObject &newth1) const
9531 {
9532  TH1::Copy(newth1);
9533 }
9534 
9535 ////////////////////////////////////////////////////////////////////////////////
9536 /// Reset.
9537 
9538 void TH1D::Reset(Option_t *option)
9539 {
9540  TH1::Reset(option);
9541  TArrayD::Reset();
9542 }
9543 
9544 ////////////////////////////////////////////////////////////////////////////////
9545 /// Set total number of bins including under/overflow
9546 /// Reallocate bin contents array
9547 
9548 void TH1D::SetBinsLength(Int_t n)
9549 {
9550  if (n < 0) n = fXaxis.GetNbins() + 2;
9551  fNcells = n;
9552  TArrayD::Set(n);
9553 }
9554 
9555 ////////////////////////////////////////////////////////////////////////////////
9556 /// Operator =
9557 
9558 TH1D& TH1D::operator=(const TH1D &h1)
9559 {
9560  if (this != &h1) ((TH1D&)h1).Copy(*this);
9561  return *this;
9562 }
9563 
9564 ////////////////////////////////////////////////////////////////////////////////
9565 /// Operator *
9566 
9567 TH1D operator*(Double_t c1, const TH1D &h1)
9568 {
9569  TH1D hnew = h1;
9570  hnew.Scale(c1);
9571  hnew.SetDirectory(0);
9572  return hnew;
9573 }
9574 
9575 ////////////////////////////////////////////////////////////////////////////////
9576 /// Operator +
9577 
9578 TH1D operator+(const TH1D &h1, const TH1D &h2)
9579 {
9580  TH1D hnew = h1;
9581  hnew.Add(&h2,1);
9582  hnew.SetDirectory(0);
9583  return hnew;
9584 }
9585 
9586 ////////////////////////////////////////////////////////////////////////////////
9587 /// Operator -
9588 
9589 TH1D operator-(const TH1D &h1, const TH1D &h2)
9590 {
9591  TH1D hnew = h1;
9592  hnew.Add(&h2,-1);
9593  hnew.SetDirectory(0);
9594  return hnew;
9595 }
9596 
9597 ////////////////////////////////////////////////////////////////////////////////
9598 /// Operator *
9599 
9600 TH1D operator*(const TH1D &h1, const TH1D &h2)
9601 {
9602  TH1D hnew = h1;
9603  hnew.Multiply(&h2);
9604  hnew.SetDirectory(0);
9605  return hnew;
9606 }
9607 
9608 ////////////////////////////////////////////////////////////////////////////////
9609 /// Operator /
9610 
9611 TH1D operator/(const TH1D &h1, const TH1D &h2)
9612 {
9613  TH1D hnew = h1;
9614  hnew.Divide(&h2);
9615  hnew.SetDirectory(0);
9616  return hnew;
9617 }
9618 
9619 ////////////////////////////////////////////////////////////////////////////////
9620 ///return pointer to histogram with name
9621 ///hid if id >=0
9622 ///h_id if id <0
9623 
9624 TH1 *R__H(Int_t hid)
9625 {
9626  TString hname;
9627  if(hid >= 0) hname.Form("h%d",hid);
9628  else hname.Form("h_%d",hid);
9629  return (TH1*)gDirectory->Get(hname);
9630 }
9631 
9632 ////////////////////////////////////////////////////////////////////////////////
9633 ///return pointer to histogram with name hname
9634 
9635 TH1 *R__H(const char * hname)
9636 {
9637  return (TH1*)gDirectory->Get(hname);
9638 }
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:6367
TString fTitle
Definition: TNamed.h:33
Abstract array base class.
Definition: TArray.h:31
virtual void Browse(TBrowser *b)
Browse the Histogram object.
Definition: TH1.cxx:713
virtual void SavePrimitive(std::ostream &out, Option_t *option="")
Save primitive as a C++ statement(s) on output stream out.
Definition: TH1.cxx:6598
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:294
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:47
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9550
virtual void Print(Option_t *option="") const
Print some global quantities for this histogram.
Definition: TH1.cxx:6451
virtual void SetNameTitle(const char *name, const char *title)
Change the name and title of this histogram.
Definition: TH1.cxx:8231
virtual void SetLineWidth(Width_t lwidth)
Set the line width.
Definition: TAttLine.h:43
virtual UInt_t GetUniqueID() const
Return the unique object id.
Definition: TObject.cxx:375
Bool_t IsReading() const
Definition: TBuffer.h:83
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:3565
virtual Float_t GetTickLength() const
Definition: TAttAxis.h:44
virtual Int_t GetNcells() const
Definition: TH1.h:294
Double_t fNormFactor
Normalization factor.
Definition: TH1.h:99
virtual void SetBarOffset(Float_t offset=0.25)
Definition: TH1.h:352
virtual void Scale(Double_t c1=1, Option_t *option="")
Multiply this histogram by a constant c1.
Definition: TH1.cxx:6063
virtual Int_t Fill(Double_t x)
Increment bin with abscissa X by 1.
Definition: TH1.cxx:3244
virtual Int_t ShowPeaks(Double_t sigma=2, Option_t *option="", Double_t threshold=0.05)
Interface to TSpectrum::Search.
Definition: TH1.cxx:8557
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:7807
TH1D & operator=(const TH1D &h1)
Operator =.
Definition: TH1.cxx:9560
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.
Definition: TH1.cxx:7283
void SetBarWidth(Float_t barwidth=0.5)
Definition: TStyle.h:311
static long int sum(long int i)
Definition: Factory.cxx:2173
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:647
virtual Double_t GetEffectiveEntries() const
Number of effective entries of the histogram.
Definition: TH1.cxx:4203
virtual void Paint(Option_t *option="")
Control routine to paint any kind of histograms.
Definition: TH1.cxx:5663
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:467
virtual Double_t GetBinCenter(Int_t bin) const
Return bin center for 1D histogram.
Definition: TH1.cxx:8397
const char * GetBinLabel(Int_t bin) const
Return label for bin.
Definition: TAxis.cxx:426
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition: TObject.cxx:854
virtual Double_t PoissonD(Double_t mean)
Generates a random number according to a Poisson law.
Definition: TRandom.cxx:435
Bool_t IsBinUnderflow(Int_t bin, Int_t axis=0) const
Return true if the bin is underflow.
Definition: TH1.cxx:4897
Double_t Floor(Double_t x)
Definition: TMath.h:599
void Set(Int_t n)
Set size of this array to n chars.
Definition: TArrayC.cxx:105
virtual ~TH1I()
Destructor.
Definition: TH1.cxx:9139
Int_t GetFirst() const
Return first bin on the axis i.e.
Definition: TAxis.cxx:444
long long Long64_t
Definition: RtypesCore.h:69
virtual Int_t AutoP2FindLimits(Double_t min, Double_t max)
Buffer-based estimate of the histogram range using the power of 2 algorithm.
Definition: TH1.cxx:1275
virtual void SetMaximum(Double_t maximum=-1111)
Definition: TH1.h:390
double Chisquare(const TH1 &h1, TF1 &f1, bool useRange, bool usePL=false)
compute the chi2 value for an histogram given a function (see TH1::Chisquare for the documentation) ...
Definition: HFitImpl.cxx:1018
auto * m
Definition: textangle.C:8
void UseCurrentStyle()
Copy current attributes from/to current style.
Definition: TH1.cxx:6828
void Copy(TArrayI &array) const
Definition: TArrayI.h:42
virtual void LabelsOption(Option_t *option="h", Option_t *axis="X")
Set option(s) to draw axis with labels.
Definition: TH1.cxx:5059
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:648
Short_t fBarWidth
(1000*width) for bar charts or legos
Definition: TH1.h:91
short Version_t
Definition: RtypesCore.h:61
TH1C()
Constructor.
Definition: TH1.cxx:8729
Bool_t IsBinOverflow(Int_t bin, Int_t axis=0) const
Return true if the bin is overflow.
Definition: TH1.cxx:4865
static Bool_t fgDefaultSumw2
!flag to call TH1::Sumw2 automatically at histogram creation time
Definition: TH1.h:115
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.
Definition: TH1.cxx:4224
virtual void FitPanel()
Display a panel with all histogram fit options.
Definition: TH1.cxx:4039
float Float_t
Definition: RtypesCore.h:53
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:8194
virtual TF1 * GetFunction(const char *name) const
Return pointer to function with name.
Definition: TH1.cxx:8307
virtual Float_t GetLabelOffset() const
Definition: TAttAxis.h:40
Short_t * fArray
Definition: TArrayS.h:30
const char Option_t
Definition: RtypesCore.h:62
virtual Float_t GetBarOffset() const
Definition: TH1.h:250
virtual Double_t GetBinLowEdge(Int_t bin) const
Return low edge of bin.
Definition: TAxis.cxx:504
Double_t KolmogorovProb(Double_t z)
Calculates the Kolmogorov distribution function,.
Definition: TMath.cxx:665
return c1
Definition: legend1.C:41
void Reset()
Definition: TArrayD.h:47
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:79
Double_t QuietNaN()
Definition: TMath.h:783
virtual void SetError(const Double_t *error)
Replace bin errors by values in array error.
Definition: TH1.cxx:8208
virtual Double_t GetNormFactor() const
Definition: TH1.h:295
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition: TString.h:638
TAxis fYaxis
Y axis descriptor.
Definition: TH1.h:88
virtual Int_t BufferFill(Double_t x, Double_t w)
accumulate arguments in buffer.
Definition: TH1.cxx:1436
virtual void SetContour(Int_t nlevels, const Double_t *levels=0)
Set the number and values of contour levels.
Definition: TH1.cxx:7748
R__EXTERN TStyle * gStyle
Definition: TStyle.h:402
virtual void PutStats(Double_t *stats)
Replace current statistics with the values in array stats.
Definition: TH1.cxx:7202
void SetHistLineWidth(Width_t width=1)
Definition: TStyle.h:357
const Double_t * GetArray() const
Definition: TArrayD.h:43
Bool_t GetStatOverflowsBehaviour() const
Definition: TH1.h:148
TList * fFunctions
->Pointer to list of functions (fits and user)
Definition: TH1.h:103
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:3643
virtual void SetBins(Int_t nx, Double_t xmin, Double_t xmax)
Redefine x axis parameters.
Definition: TH1.cxx:8024
Int_t GetLwb() const
Definition: TVectorT.h:73
virtual Int_t GetXfirst() const
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition: TNamed.cxx:140
virtual Color_t GetAxisColor() const
Definition: TAttAxis.h:37
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:4094
static Bool_t fgStatOverflows
!flag to use under/overflows in statistics
Definition: TH1.h:114
virtual TH1 * DrawNormalized(Option_t *option="", Double_t norm=1) const
Draw a normalized copy of this histogram.
Definition: TH1.cxx:3044
static Bool_t SameLimitsAndNBins(const TAxis &axis1, const TAxis &axis2)
Same limits and bins.
Definition: TH1.cxx:5344
virtual ~TH1F()
Destructor.
Definition: TH1.cxx:9346
virtual void SetLabelColor(Color_t color=1, Float_t alpha=1.)
Set color of labels.
Definition: TAttAxis.cxx:173
void Build()
Creates histogram basic data structure.
Definition: TH1.cxx:722
EStatOverflows fStatOverflows
per object flag to use under/overflows in statistics
Definition: TH1.h:111
virtual Double_t GetSumOfWeights() const
Return the sum of weights excluding under/overflows.
Definition: TH1.cxx:7232
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
Definition: TH1.cxx:4763
virtual void SetNdivisions(Int_t n=510, Bool_t optim=kTRUE)
Set the number of divisions for this axis.
Definition: TAttAxis.cxx:229
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:8811
TVectorT.
Definition: TMatrixTBase.h:77
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:4315
virtual Double_t Integral(Option_t *option="") const
Return integral of bin contents.
Definition: TH1.cxx:7256
void ToUpper()
Change string to upper case.
Definition: TString.cxx:1112
virtual void Reset(Option_t *option="")
Reset.
Definition: TH1.cxx:8819
TH1D()
Constructor.
Definition: TH1.cxx:9452
friend TH1D operator/(const TH1D &h1, const TH1D &h2)
Operator /.
Definition: TH1.cxx:9613
static bool CheckAxisLimits(const TAxis *a1, const TAxis *a2)
Check that the axis limits of the histograms are the same.
Definition: TH1.cxx:1529
Buffer base class used for serializing objects.
Definition: TBuffer.h:40
friend TH1S operator+(const TH1S &h1, const TH1S &h2)
Operator +.
Definition: TH1.cxx:9040
virtual Double_t GetMeanError(Int_t axis=1) const
Return standard error of mean of this histogram along the X axis.
Definition: TH1.cxx:6923
virtual Int_t GetNbinsZ() const
Definition: TH1.h:293
TH1F()
Constructor.
Definition: TH1.cxx:9273
#define R__ASSERT(e)
Definition: TError.h:96
virtual void SetMinimum(Double_t minimum=-1111)
Definition: TH1.h:391
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:402
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:6892
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition: TString.h:585
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition: TObject.h:172
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9532
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:4678
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:9353
Basic string class.
Definition: TString.h:125
static Bool_t AddDirectoryStatus()
Static function: cannot be inlined on Windows/NT.
Definition: TH1.cxx:705
1-D histogram with a float per channel (see TH1 documentation)}
Definition: TH1.h:567
Int_t GetNrows() const
Definition: TVectorT.h:75
1-D histogram with a short per channel (see TH1 documentation)
Definition: TH1.h:485
void H1InitExpo()
Compute Initial values of parameters for an exponential.
Definition: TH1.cxx:4421
Array of floats (32 bits per element).
Definition: TArrayF.h:27
static Double_t AutoP2GetPower2(Double_t x, Bool_t next=kTRUE)
Auxilliary function to get the power of 2 next (larger) or previous (smaller) a given x...
Definition: TH1.cxx:1239
virtual void SetTitleFont(Style_t font=62)
Set the title font.
Definition: TAttAxis.cxx:322
Short_t Min(Short_t a, Short_t b)
Definition: TMathBase.h:168
void ToLower()
Change string to lower-case.
Definition: TString.cxx:1099
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
void SetBarOffset(Float_t baroff=0.5)
Definition: TStyle.h:310
R__EXTERN TVirtualMutex * gROOTMutex
Definition: TROOT.h:57
void Copy(TAttMarker &attmarker) const
Copy this marker attributes to a new TAttMarker.
Definition: TAttMarker.cxx:209
virtual TH1 * DrawCopy(Option_t *option="", const char *name_postfix="_copy") const
Copy this histogram and Draw in the current pad.
Definition: TH1.cxx:3016
virtual void SetFillStyle(Style_t fstyle)
Set the fill area style.
Definition: TAttFill.h:39
virtual void Smooth(Int_t ntimes=1, Option_t *option="")
Smooth bin contents of this histogram.
Definition: TH1.cxx:6321
#define gInterpreter
Definition: TInterpreter.h:526
Bool_t IsNaN(Double_t x)
Definition: TMath.h:777
TArrayD fSumw2
Array of sum of squares of weights.
Definition: TH1.h:101
user specified contour levels
Definition: TH1.h:161
virtual void UseCurrentStyle()
Set current style settings in this object This function is called when either TCanvas::UseCurrentStyl...
Definition: TObject.cxx:715
virtual void Copy(TObject &axis) const
Copy axis structure to another axis.
Definition: TAxis.cxx:208
void Copy(TArrayC &array) const
Definition: TArrayC.h:42
virtual Float_t GetLabelSize() const
Definition: TAttAxis.h:41
virtual Double_t GetBinLowEdge(Int_t bin) const
Return bin lower edge for 1D histogram.
Definition: TH1.cxx:8408
static Bool_t AlmostInteger(Double_t a, Double_t epsilon=0.00000001)
Test if a double is almost an integer.
Definition: TH1.cxx:5315
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9173
void Reset()
Definition: TArrayF.h:47
virtual Double_t Integral(Double_t a, Double_t b, Double_t epsrel=1.e-12)
IntegralOneDim or analytical integral.
Definition: TF1.cxx:2402
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:5355
TAxis fZaxis
Z axis descriptor.
Definition: TH1.h:89
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:5488
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9371
virtual TObject * Clone(const char *newname="") const
Make a clone of an collection using the Streamer facility.
Bool_t CanExtend() const
Definition: TAxis.h:82
virtual Double_t GetContourLevel(Int_t level) const
Return value of contour number level.
Definition: TH1.cxx:7695
TF1 * gF1
Definition: TH1.cxx:524
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:193
Short_t Abs(Short_t d)
Definition: TMathBase.h:108
virtual Width_t GetLineWidth() const
Return the line width.
Definition: TAttLine.h:35
don&#39;t draw stats box
Definition: TH1.h:160
friend TH1D operator+(const TH1D &h1, const TH1D &h2)
Operator +.
Definition: TH1.cxx:9580
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:624
static bool CheckBinLimits(const TAxis *a1, const TAxis *a2)
Check bin limits.
Definition: TH1.cxx:1471
Array of integers (32 bits per element).
Definition: TArrayI.h:27
void Reset(Char_t val=0)
Definition: TArrayC.h:47
LongDouble_t Power(LongDouble_t x, LongDouble_t y)
Definition: TMath.h:627
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition: TObject.cxx:694
virtual void SetBuffer(Int_t buffersize, Option_t *option="")
Set the maximum number of entries to be kept in the buffer.
Definition: TH1.cxx:7723
Double_t fTsumwx2
Total Sum of weight*X*X.
Definition: TH1.h:96
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:7150
virtual Bool_t CanExtendAllAxes() const
Returns true if all axes are extendable.
Definition: TH1.cxx:6087
virtual void Reset(Option_t *option="")
Reset this histogram: contents, errors, etc.
Definition: TH1.cxx:6545
friend TH1S operator-(const TH1S &h1, const TH1S &h2)
Operator -.
Definition: TH1.cxx:9051
virtual TObject * FindObject(const char *name) const
Delete a TObjLink object.
Definition: TList.cxx:574
Width_t GetHistLineWidth() const
Definition: TStyle.h:221
static void AddDirectory(Bool_t add=kTRUE)
Sets the flag controlling the automatic add of histograms in memory.
Definition: TH1.cxx:1225
if object in a list can be deleted
Definition: TObject.h:58
virtual Double_t GetBinUpEdge(Int_t bin) const
Return up edge of bin.
Definition: TAxis.cxx:514
virtual void SetBarWidth(Float_t width=0.5)
Definition: TH1.h:353
virtual void SetLabelFont(Style_t font=62)
Set labels&#39; font.
Definition: TAttAxis.cxx:183
virtual void AppendPad(Option_t *option="")
Append graphics object to current pad.
Definition: TObject.cxx:105
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
Return the marker style.
Definition: TAttMarker.h:32
TDirectory * fDirectory
!Pointer to directory holding this histogram
Definition: TH1.h:106
static void SetDefaultSumw2(Bool_t sumw2=kTRUE)
When this static function is called with sumw2=kTRUE, all new histograms will automatically activate ...
Definition: TH1.cxx:6139
Marker Attributes class.
Definition: TAttMarker.h:19
virtual Style_t GetTitleFont() const
Definition: TAttAxis.h:46
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.
Definition: TH1.cxx:1578
virtual Style_t GetLineStyle() const
Return the line style.
Definition: TAttLine.h:34
virtual Int_t GetDimension() const
Definition: TH1.h:277
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:4817
virtual Int_t GetContour(Double_t *levels=0)
Return contour values into array levels if pointer levels is non zero.
Definition: TH1.cxx:7676
TH1C & operator=(const TH1C &h1)
Operator =.
Definition: TH1.cxx:8839
Double_t GetXmin() const
Definition: TAxis.h:133
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:128
Fill Area Attributes class.
Definition: TAttFill.h:19
Double_t x[n]
Definition: legend1.C:17
static Int_t FitOptionsMake(Option_t *option, Foption_t &Foption)
Decode string choptin and fill fitOption structure.
Definition: TH1.cxx:4356
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:2365
virtual void Eval(TF1 *f1, Option_t *option="")
Evaluate function f1 at the center of bins of this histogram.
Definition: TH1.cxx:3092
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:34
static Bool_t GetDefaultSumw2()
Return kTRUE if TH1::Sumw2 must be called when creating new histograms.
Definition: TH1.cxx:4170
void SetHistFillColor(Color_t color=1)
Definition: TStyle.h:353
virtual Bool_t GetTimeDisplay() const
Definition: TAxis.h:126
static void SetDefaultBufferSize(Int_t buffersize=1000)
Static function to set the default buffer size for automatic histograms.
Definition: TH1.cxx:6129
Use Power(2)-based algorithm for autobinning.
Definition: TH1.h:169
void Copy(TAttLine &attline) const
Copy this line attributes to a new TAttLine.
Definition: TAttLine.cxx:162
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:260
virtual Double_t Chi2Test(const TH1 *h2, Option_t *option="UU", Double_t *res=0) const
test for comparing weighted and unweighted histograms
Definition: TH1.cxx:1947
The TNamed class is the base class for all named ROOT classes.
Definition: TNamed.h:29
virtual ~TH1()
Histogram default destructor.
Definition: TH1.cxx:578
THashList * GetLabels() const
Definition: TAxis.h:117
friend TH1D operator-(const TH1D &h1, const TH1D &h2)
Operator -.
Definition: TH1.cxx:9591
Int_t GetOptFit() const
Definition: TStyle.h:228
Double_t Log10(Double_t x)
Definition: TMath.h:651
virtual void SetContourLevel(Int_t level, Double_t value)
Set value for one contour level.
Definition: TH1.cxx:7787
#define R__WRITE_LOCKGUARD(mutex)
virtual void GetCenter(Double_t *center) const
Return an array with the center of all bins.
Definition: TAxis.cxx:539
TH1I()
Constructor.
Definition: TH1.cxx:9091
Abstract interface to a histogram painter.
virtual Double_t GetBinCenter(Int_t bin) const
Return center of bin.
Definition: TAxis.cxx:464
virtual void SetMarkerColor(Color_t mcolor=1)
Set the marker color.
Definition: TAttMarker.h:38
Style_t GetHistFillStyle() const
Definition: TStyle.h:219
TH1S()
Constructor.
Definition: TH1.cxx:8910
TString & Append(const char *cs)
Definition: TString.h:495
virtual void GetLowEdge(Double_t *edge) const
Return an array with the lod edge of all bins.
Definition: TAxis.cxx:548
void Sort(Index n, const Element *a, Index *index, Bool_t down=kTRUE)
Definition: TMath.h:1150
Double_t * fArray
Definition: TArrayD.h:30
void H1InitGaus()
Compute Initial values of parameters for a gaussian.
Definition: TH1.cxx:4365
virtual Size_t GetMarkerSize() const
Return the marker size.
Definition: TAttMarker.h:33
R__EXTERN TVirtualRWMutex * gCoreMutex
virtual bool UseRWLock()
Set this collection to use a RW lock upon access, making it thread safe.
virtual void DrawPanel()=0
errors from Poisson interval at 95% CL (~ 2 sigma)
Definition: TH1.h:64
const Double_t sigma
TString fOption
histogram options
Definition: TH1.h:102
friend TH1I operator-(const TH1I &h1, const TH1I &h2)
Operator -.
Definition: TH1.cxx:9233
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:244
virtual Int_t * GetN() const =0
Float_t GetBarWidth() const
Definition: TStyle.h:169
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:5906
TH1F * h1
Definition: legend1.C:5
constexpr Double_t Pi()
Definition: TMath.h:40
virtual void SetContent(const Double_t *content)
Replace bin contents by the contents of array content.
Definition: TH1.cxx:7663
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:1200
friend TH1C operator*(Double_t c1, const TH1C &h1)
Operator *.
Definition: TH1.cxx:8848
virtual void ResetStats()
Reset the statistics including the number of entries and replace with values calculates from bin cont...
Definition: TH1.cxx:7217
void Set(Int_t n)
Set size of this array to n ints.
Definition: TArrayI.cxx:105
Double_t Infinity()
Definition: TMath.h:796
TArrayD fContour
Array to display contour levels.
Definition: TH1.h:100
virtual void SetBinError(Int_t bin, Double_t error)
Set the bin Error Note that this resets the bin eror option to be of Normal Type and for the non-empt...
Definition: TH1.cxx:8461
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:2472
virtual void LabelsInflate(Option_t *axis="X")
Double the number of bins for axis.
Definition: TH1.cxx:4998
virtual Color_t GetLabelColor() const
Definition: TAttAxis.h:38
object has not been deleted
Definition: TObject.h:78
short Color_t
Definition: RtypesCore.h:79
virtual Double_t GetSkewness(Int_t axis=1) const
Definition: TH1.cxx:6997
virtual void SetTimeDisplay(Int_t value)
Definition: TAxis.h:161
Double_t fTsumwx
Total Sum of weight*X.
Definition: TH1.h:95
void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a)
Least squares lpolynomial fitting without weights.
Definition: TH1.cxx:4471
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:2724
virtual Int_t GetNdivisions() const
Definition: TAttAxis.h:36
static Int_t AutoP2GetBins(Int_t n)
Auxilliary function to get the next power of 2 integer value larger then n.
Definition: TH1.cxx:1252
static Bool_t fgAddDirectory
!flag to add histograms to the directory
Definition: TH1.h:113
virtual void SetUniqueID(UInt_t uid)
Set the unique object id.
Definition: TObject.cxx:705
A doubly linked list.
Definition: TList.h:44
void Set(Int_t n)
Set size of this array to n shorts.
Definition: TArrayS.cxx:105
virtual void GetMinimumAndMaximum(Double_t &min, Double_t &max) const
Retrieve the minimum and maximum values in the histogram.
Definition: TH1.cxx:7988
virtual Double_t Rndm()
Machine independent random number generator.
Definition: TRandom.cxx:533
virtual Double_t GetStdDevError(Int_t axis=1) const
Return error of standard deviation estimation for Normal distribution.
Definition: TH1.cxx:6984
Double_t fMinimum
Minimum value for plotting.
Definition: TH1.h:98
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:7490
virtual void ExtendAxis(Double_t x, TAxis *axis)
Histogram is resized along axis such that x is in the axis range.
Definition: TH1.cxx:5963
Bool_t AreEqualRel(Double_t af, Double_t bf, Double_t relPrec)
Definition: TMath.h:322
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:2542
virtual TH1 * FFT(TH1 *h_output, Option_t *option)
This function allows to do discrete Fourier transforms of TH1 and TH2.
Definition: TH1.cxx:3184
virtual Int_t DistancetoPrimitive(Int_t px, Int_t py)
Compute distance from point px,py to a line.
Definition: TH1.cxx:2707
void Reset()
Definition: TArrayS.h:47
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:8973
virtual void SetLineColor(Color_t lcolor)
Set the line color.
Definition: TAttLine.h:40
friend TH1S operator/(const TH1S &h1, const TH1S &h2)
Operator /.
Definition: TH1.cxx:9073
Using a TBrowser one can browse all ROOT objects.
Definition: TBrowser.h:37
virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py)
Execute action corresponding to one event.
Definition: TH1.cxx:3140
Int_t fN
Definition: TArray.h:38
int isnan(double)
virtual Double_t * GetIntegral()
Return a pointer to the array of bins integral.
Definition: TH1.cxx:2520
NOTE: Must always be 0 !!!
Definition: TH1.h:69
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:903
void Clear(Option_t *option="")
Remove all objects from the list.
Definition: THashList.cxx:189
float ymax
Definition: THbookFile.cxx:93
std::string printValue(const TDatime *val)
Print a TDatime at the prompt.
Definition: TDatime.cxx:514
virtual void SetParLimits(Int_t ipar, Double_t parmin, Double_t parmax)
Set limits for parameter ipar.
Definition: TF1.cxx:3385
friend TH1C operator-(const TH1C &h1, const TH1C &h2)
Operator -.
Definition: TH1.cxx:8870
void Copy(TArrayF &array) const
Definition: TArrayF.h:42
friend TH1C operator+(const TH1C &h1, const TH1C &h2)
Operator +.
Definition: TH1.cxx:8859
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:655
virtual void FillRandom(const char *fname, Int_t ntimes=5000)
Fill histogram following distribution in function fname.
Definition: TH1.cxx:3414
void SetHistFillStyle(Style_t styl=0)
Definition: TStyle.h:355
Int_t GetLast() const
Return last bin on the axis i.e.
Definition: TAxis.cxx:455
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:6203
Class to manage histogram axis.
Definition: TAxis.h:30
virtual Double_t GetKurtosis(Int_t axis=1) const
Definition: TH1.cxx:7067
virtual void Draw(Option_t *option="")
Draw this histogram with options.
Definition: TH1.cxx:2969
static bool CheckBinLabels(const TAxis *a1, const TAxis *a2)
Check that axis have same labels.
Definition: TH1.cxx:1497
Array of shorts (16 bits per element).
Definition: TArrayS.h:27
virtual Double_t GetPointReal(Int_t ipoint, Bool_t fromInput=kFALSE) const =0
Int_t GetSize() const
Definition: TArray.h:47
SVector< double, 2 > v
Definition: Dict.h:5
if object ctor succeeded but object should not be used
Definition: TObject.h:68
TH1 * R__H(Int_t hid)
return pointer to histogram with name hid if id >=0 h_id if id <0
Definition: TH1.cxx:9626
virtual void SetFillColor(Color_t fcolor)
Set the fill area color.
Definition: TAttFill.h:37
auto * a
Definition: textangle.C:12
A 3-Dim function with parameters.
Definition: TF3.h:28
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...
Definition: TH1.cxx:4788
friend TH1I operator+(const TH1I &h1, const TH1I &h2)
Operator +.
Definition: TH1.cxx:9222
void SetCanExtend(Bool_t canExtend)
Definition: TAxis.h:86
1-D histogram with an int per channel (see TH1 documentation)}
Definition: TH1.h:526
Long_t ExecPlugin(int nargs, const T &... params)
virtual TObject * Remove(TObject *obj)
Remove object from the list.
Definition: TList.cxx:818
virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py)=0
Execute action corresponding to an event at (px,py).
Provides an indirection to the TFitResult class and with a semantics identical to a TFitResult pointe...
Definition: TFitResultPtr.h:31
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:8575
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:443
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:8477
Collection abstract base class.
Definition: TCollection.h:63
static Int_t fgBufferSize
!default buffer size for automatic histograms
Definition: TH1.h:112
virtual TH1 * Rebin(Int_t ngroup=2, const char *newname="", const Double_t *xbins=0)
Rebin this histogram.
Definition: TH1.cxx:5729
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:7376
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition: TString.cxx:2343
Double_t fEntries
Number of entries.
Definition: TH1.h:92
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:232
virtual Float_t GetTitleOffset() const
Definition: TAttAxis.h:42
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:4928
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:3373
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:880
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:2434
Ssiz_t Length() const
Definition: TString.h:386
virtual void Append(TObject *obj, Bool_t replace=kFALSE)
Append object to this directory.
Definition: TDirectory.cxx:190
static TVirtualFitter * GetFitter()
static: return the current Fitter
virtual void Copy(TObject &hnew) const
Copy this histogram structure to newth1.
Definition: TH1.cxx:2585
virtual TH1 * ShowBackground(Int_t niter=20, Option_t *option="same")
This function calculates the background spectrum in this histogram.
Definition: TH1.cxx:8542
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9191
virtual ~TH1C()
Destructor.
Definition: TH1.cxx:8777
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:3591
short Short_t
Definition: RtypesCore.h:35
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:8992
virtual void SetMarkerStyle(Style_t mstyle=1)
Set the marker style.
Definition: TAttMarker.h:40
virtual Double_t GetContourLevelPad(Int_t level) const
Return the value of contour number "level" in Pad coordinates.
Definition: TH1.cxx:7705
TAxis * GetYaxis()
Definition: TH1.h:316
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition: BinData.h:53
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:354
virtual Color_t GetTitleColor() const
Definition: TAttAxis.h:45
Double_t * fIntegral
!Integral of bins used by GetRandom
Definition: TH1.h:108
virtual void SetBinErrorOption(EBinErrorOpt type)
Definition: TH1.h:369
friend TH1F operator*(Double_t c1, const TH1F &h1)
Operator *.
Definition: TH1.cxx:9390
static bool CheckConsistency(const TH1 *h1, const TH1 *h2)
Check histogram compatibility.
Definition: TH1.cxx:1613
A 2-Dim function with parameters.
Definition: TF2.h:29
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:4576
TH1()
Histogram default constructor.
Definition: TH1.cxx:550
R__EXTERN TRandom * gRandom
Definition: TRandom.h:62
1-D histogram with a double per channel (see TH1 documentation)}
Definition: TH1.h:610
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:4665
static Int_t GetDefaultBufferSize()
Static function return the default buffer size for automatic histograms the parameter fgBufferSize ma...
Definition: TH1.cxx:4161
virtual void SetAxisColor(Color_t color=1, Float_t alpha=1.)
Set color of the line axis and tick marks.
Definition: TAttAxis.cxx:163
TString fName
Definition: TNamed.h:32
virtual TObject * FindObject(const char *name) const
Search object named name in the list of functions.
Definition: TH1.cxx:3661
virtual void Rebuild(Option_t *option="")
Using the current bin info, recompute the arrays for contents and errors.
Definition: TH1.cxx:6529
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:3624
if object destructor must call RecursiveRemove()
Definition: TObject.h:60
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:204
virtual void SetMarkerSize(Size_t msize=1)
Set the marker size.
Definition: TAttMarker.h:41
friend TH1I operator/(const TH1I &h1, const TH1I &h2)
Operator /.
Definition: TH1.cxx:9255
REAL epsilon
Definition: triangle.c:617
virtual void SetTitleColor(Color_t color=1)
Set color of axis title.
Definition: TAttAxis.cxx:313
constexpr Double_t E()
Definition: TMath.h:74
virtual TObjLink * FirstLink() const
Definition: TList.h:108
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:304
#define Printf
Definition: TGeoToOCC.h:18
virtual void RecursiveRemove(TObject *obj)
Recursively remove object from the list of functions.
Definition: TH1.cxx:6035
EBinErrorOpt fBinStatErrOpt
option for bin statistical errors
Definition: TH1.h:110
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:8695
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:7892
errors with Normal (Wald) approximation: errorUp=errorLow= sqrt(N)
Definition: TH1.h:62
const Bool_t kFALSE
Definition: RtypesCore.h:88
TVirtualFFT is an interface class for Fast Fourier Transforms.
Definition: TVirtualFFT.h:88
virtual Color_t GetLineColor() const
Return the line color.
Definition: TAttLine.h:33
virtual Int_t FindBin(Double_t x)
Find bin number corresponding to abscissa x.
Definition: TAxis.cxx:279
virtual void SetName(const char *name)
Change the name of this histogram.
Definition: TH1.cxx:8217
friend TH1I operator*(Double_t c1, const TH1I &h1)
Operator *.
Definition: TH1.cxx:9211
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:619
virtual Int_t ReadClassBuffer(const TClass *cl, void *pointer, const TClass *onfile_class=0)=0
virtual Int_t GetSumw2N() const
Definition: TH1.h:309
Double_t fTsumw2
Total Sum of squares of weights.
Definition: TH1.h:94
Color_t GetHistFillColor() const
Definition: TStyle.h:217
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:1334
virtual void GetPointComplex(Int_t ipoint, Double_t &re, Double_t &im, Bool_t fromInput=kFALSE) const =0
Bin contents are average (used by Add)
Definition: TH1.h:166
virtual Bool_t IsEmpty() const
Definition: TCollection.h:184
return c2
Definition: legend2.C:14
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width for 1D histogram.
Definition: TH1.cxx:8419
static const double x1[5]
virtual TObject * Remove(TObject *)
Remove an object from the in-memory list.
#define ClassImp(name)
Definition: Rtypes.h:359
class describing the range in the coordinates it supports multiple range in a coordinate.
Definition: DataRange.h:34
virtual Double_t GetBinErrorLow(Int_t bin) const
Return lower error associated to bin number bin.
Definition: TH1.cxx:8335
friend TH1F operator+(const TH1F &h1, const TH1F &h2)
Operator +.
Definition: TH1.cxx:9401
double Double_t
Definition: RtypesCore.h:55
Int_t GetOptStat() const
Definition: TStyle.h:229
Int_t * fArray
Definition: TArrayI.h:30
void SetHistLineStyle(Style_t styl=0)
Definition: TStyle.h:356
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:6740
Double_t fTsumw
Total Sum of weights.
Definition: TH1.h:93
Color_t GetHistLineColor() const
Definition: TStyle.h:218
friend TH1D operator*(Double_t c1, const TH1D &h1)
Operator *.
Definition: TH1.cxx:9569
Describe directory structure in memory.
Definition: TDirectory.h:34
Histogram is forced to be not weighted even when the histogram is filled with weighted different than...
Definition: TH1.h:167
int type
Definition: TGX11.cxx:120
R__EXTERN TEnv * gEnv
Definition: TEnv.h:171
Double_t Median(Long64_t n, const T *a, const Double_t *w=0, Long64_t *work=0)
Definition: TMath.h:1225
unsigned long ULong_t
Definition: RtypesCore.h:51
int nentries
Definition: THbookFile.cxx:89
Double_t y[n]
Definition: legend1.C:17
virtual Color_t GetFillColor() const
Return the fill area color.
Definition: TAttFill.h:30
TH1I & operator=(const TH1I &h1)
Operator =.
Definition: TH1.cxx:9201
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:570
The TH1 histogram class.
Definition: TH1.h:56
static constexpr double s
you should not use this method at all Int_t Int_t Double_t Double_t Double_t e
Definition: TRolke.cxx:630
virtual Double_t GetEntries() const
Return the current number of entries.
Definition: TH1.cxx:4178
friend TH1F operator/(const TH1F &h1, const TH1F &h2)
Operator /.
Definition: TH1.cxx:9434
#define R__LOCKGUARD(mutex)
void forward(const LAYERDATA &prevLayerData, LAYERDATA &currLayerData)
apply the weights (and functions) in forward direction of the DNN
Definition: NeuralNet.icc:545
THist< 2, double, THistStatContent, THistStatUncertainty > TH2D
Definition: THist.hxx:290
virtual Float_t GetTitleSize() const
Definition: TAttAxis.h:43
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:2006
static bool IsEquidistantBinning(const TAxis &axis)
Test if the binning is equidistant.
Definition: TH1.cxx:5324
Short_t fBarOffset
(1000*offset) for bar charts or legos
Definition: TH1.h:90
virtual void SetLineStyle(Style_t lstyle)
Set the line style.
Definition: TAttLine.h:42
double Stat_t
Definition: RtypesCore.h:73
Array of doubles (64 bits per element).
Definition: TArrayD.h:27
Bool_t IsNull() const
Definition: TString.h:383
void FitOptionsMake(EFitObjectType type, const char *option, Foption_t &fitOption)
Decode list of options into fitOption.
Definition: HFitImpl.cxx:681
virtual void InitArgs(const Double_t *x, const Double_t *params)
Initialize parameters addresses.
Definition: TF1.cxx:2354
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:777
Abstract Base Class for Fitting.
TAxis * GetZaxis()
Definition: TH1.h:317
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:6100
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:3598
Mother of all ROOT objects.
Definition: TObject.h:37
virtual Int_t FindFixBin(Double_t x) const
Find bin number corresponding to abscissa x.
Definition: TAxis.cxx:405
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9010
you should not use this method at all Int_t Int_t z
Definition: TRolke.cxx:630
Bool_t IsReading() const
Definition: TStyle.h:274
virtual void ClearUnderflowAndOverflow()
Remove all the content from the underflow and overflow bins, without changing the number of entries A...
Definition: TH1.cxx:2453
virtual Bool_t IsInside(const Double_t *x) const
return kTRUE if the point is inside the function range
Definition: TF1.h:582
char Char_t
Definition: RtypesCore.h:29
virtual char * GetObjectInfo(Int_t px, Int_t py) const
Redefines TObject::GetObjectInfo.
Definition: TH1.cxx:4215
TH1S & operator=(const TH1S &h1)
Operator =.
Definition: TH1.cxx:9020
virtual Int_t GetNpar() const
Definition: TF1.h:465
Style_t GetHistLineStyle() const
Definition: TStyle.h:220
Double_t fMaximum
Maximum value for plotting.
Definition: TH1.h:97
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width.
Definition: TAxis.cxx:526
virtual void DirectoryAutoAdd(TDirectory *)
Perform the automatic addition of the histogram to the given directory.
Definition: TH1.cxx:2685
TVirtualHistPainter * fPainter
!pointer to histogram painter
Definition: TH1.h:109
virtual void Copy(TObject &named) const
Copy this to obj.
Definition: TNamed.cxx:94
friend TH1C operator/(const TH1C &h1, const TH1C &h2)
Operator /.
Definition: TH1.cxx:8892
friend TH1S operator*(Double_t c1, const TH1S &h1)
Operator *.
Definition: TH1.cxx:9029
static Bool_t RejectedPoint()
See TF1::RejectPoint above.
Definition: TF1.cxx:3600
virtual void DrawPanel()
Display a panel with all histogram drawing options.
Definition: TH1.cxx:3075
virtual void Add(TObject *obj)
Definition: TList.h:87
auto * l
Definition: textangle.C:4
Int_t fBufferSize
fBuffer size
Definition: TH1.h:104
virtual void RecursiveRemove(TObject *obj)
Remove object from this collection and recursively remove the object from all other objects (and coll...
Definition: TList.cxx:760
virtual Int_t GetMinimumBin() const
Return location of bin with minimum value in the range.
Definition: TH1.cxx:7922
virtual Double_t GetBinErrorSqUnchecked(Int_t bin) const
Definition: TH1.h:435
virtual void GetRange(Double_t *xmin, Double_t *xmax) const
Return range of a generic N-D function.
Definition: TF1.cxx:2163
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:7292
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:3347
Short_t Max(Short_t a, Short_t b)
Definition: TMathBase.h:200
1-Dim function class
Definition: TF1.h:211
virtual void SetBinsLength(Int_t=-1)
Definition: TH1.h:368
Char_t * fArray
Definition: TArrayC.h:30
1-D histogram with a byte per channel (see TH1 documentation)
Definition: TH1.h:444
virtual void Sumw2(Bool_t flag=kTRUE)
Create structure to store sum of squares of weights.
Definition: TH1.cxx:8276
TObject * Clone(const char *newname=0) const
Make a complete copy of the underlying object.
Definition: TH1.cxx:2662
TF1 * f1
Definition: legend1.C:11
you should not use this method at all Int_t Int_t Double_t Double_t Double_t Int_t Double_t Double_t Double_t Double_t b
Definition: TRolke.cxx:630
Double_t GetAt(Int_t i) const
Definition: TArrayD.h:45
Double_t Ceil(Double_t x)
Definition: TMath.h:593
friend TH1F operator-(const TH1F &h1, const TH1F &h2)
Operator -.
Definition: TH1.cxx:9412
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:1266
Int_t fDimension
!Histogram dimension (1, 2 or 3 dim)
Definition: TH1.h:107
THist< 1, double, THistStatContent, THistStatUncertainty > TH1D
Definition: THist.hxx:284
#define gPad
Definition: TVirtualPad.h:285
void Reset()
Definition: TArrayI.h:47
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:280
virtual Int_t GetXlast() const
virtual Double_t GetBinErrorUp(Int_t bin) const
Return upper error associated to bin number bin.
Definition: TH1.cxx:8366
virtual Int_t BufferEmpty(Int_t action=0)
Fill histogram with all entries in the buffer.
Definition: TH1.cxx:1346
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:105
virtual ~TH1D()
Destructor.
Definition: TH1.cxx:9517
virtual void SetEntries(Double_t n)
Definition: TH1.h:378
TAxis fXaxis
X axis descriptor.
Definition: TH1.h:87
Float_t GetBarOffset() const
Definition: TStyle.h:168
#define gDirectory
Definition: TDirectory.h:213
virtual TH1 * GetHistogram() const
Return a pointer to the histogram used to visualise the function.
Definition: TF1.cxx:1469
void ResetBit(UInt_t f)
Definition: TObject.h:171
virtual void SetParameter(Int_t param, Double_t value)
Definition: TF1.h:618
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:9154
virtual void SetTitle(const char *title)
See GetStatOverflows for more information.
Definition: TH1.cxx:6154
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:964
virtual Int_t GetNdim() const =0
virtual Color_t GetMarkerColor() const
Return the marker color.
Definition: TAttMarker.h:31
Definition: first.py:1
virtual Int_t GetNbinsX() const
Definition: TH1.h:291
Option_t * GetDrawOption() const
Get option used by the graphics system to draw this object.
Definition: TBrowser.h:104
virtual Int_t Poisson(Double_t mean)
Generates a random integer N according to a Poisson law.
Definition: TRandom.cxx:383
virtual Style_t GetFillStyle() const
Return the fill area style.
Definition: TAttFill.h:31
Double_t Sqrt(Double_t x)
Definition: TMath.h:590
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:8792
Int_t GetNbins() const
Definition: TAxis.h:121
Bool_t GetCanvasPreferGL() const
Definition: TStyle.h:173
virtual const char * GetName() const
Returns name of object.
Definition: TObject.cxx:357
virtual Int_t GetSize() const
Definition: TCollection.h:180
virtual void Set(Int_t nbins, Double_t xmin, Double_t xmax)
Initialize axis with fix bins.
Definition: TAxis.cxx:717
float * q
Definition: THbookFile.cxx:87
static Bool_t AlmostEqual(Double_t a, Double_t b, Double_t epsilon=0.00000001)
Test if two double are almost equal.
Definition: TH1.cxx:5307
virtual Double_t EvalPar(const Double_t *x, const Double_t *params=0)
Evaluate function with given coordinates and parameters.
Definition: TF1.cxx:1363
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition: TNamed.cxx:164
TList * GetListOfFunctions() const
Definition: TH1.h:238
void SetHistLineColor(Color_t color=1)
Definition: TStyle.h:354
virtual TObject * GetUserFunc() const
virtual TObject * GetObjectFit() const
Double_t * fBuffer
[fBufferSize] entry buffer
Definition: TH1.h:105
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition: TEnv.cxx:491
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:3688
const Bool_t kTRUE
Definition: RtypesCore.h:87
Int_t Nint(T x)
Definition: TMath.h:606
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:922
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:8705
virtual Double_t GetStdDev(Int_t axis=1) const
Returns the Standard Deviation (Sigma).
Definition: TH1.cxx:6946
void Set(Int_t n)
Set size of this array to n doubles.
Definition: TArrayD.cxx:106
virtual Double_t GetRandom() const
Return a random number distributed according the histogram bin contents.
Definition: TH1.cxx:4712
static bool CheckEqualAxes(const TAxis *a1, const TAxis *a2)
Check that the axis are the same.
Definition: TH1.cxx:1542
Double_t GetXmax() const
Definition: TAxis.h:134
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:8958
void Copy(TArrayD &array) const
Definition: TArrayD.h:42
virtual Int_t GetMaximumBin() const
Return location of bin with maximum value in the range.
Definition: TH1.cxx:7837
const Int_t n
Definition: legend1.C:16
Line Attributes class.
Definition: TAttLine.h:18
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:8430
void H1InitPolynom()
Compute Initial values of parameters for a polynom.
Definition: TH1.cxx:4441
virtual void SetStats(Bool_t stats=kTRUE)
Set statistics option on/off.
Definition: TH1.cxx:8247
TH1F & operator=(const TH1F &h1)
Operator =.
Definition: TH1.cxx:9381
virtual Float_t GetBarWidth() const
Definition: TH1.h:251
Long64_t BinarySearch(Long64_t n, const T *array, T value)
Definition: TMath.h:1092
char name[80]
Definition: TGX11.cxx:109
const TArrayD * GetXbins() const
Definition: TAxis.h:130
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:8443
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:866
TAxis * GetXaxis()
Get the behaviour adopted by the object about the statoverflows. See EStatOverflows for more informat...
Definition: TH1.h:315
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:8829
virtual Style_t GetLabelFont() const
Definition: TAttAxis.h:39
void Copy(TArrayS &array) const
Definition: TArrayS.h:42
virtual Long64_t Merge(TCollection *list)
Add all histograms in the collection to this histogram.
Definition: TH1.cxx:5464
virtual Version_t ReadVersion(UInt_t *start=0, UInt_t *bcnt=0, const TClass *cl=0)=0
double ldexp(double, int)
virtual const char * GetTitle() const
Returns title of object.
Definition: TNamed.h:48
virtual Int_t GetNbinsY() const
Definition: TH1.h:292
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:8319
virtual Int_t ReadArray(Bool_t *&b)=0
Int_t fNcells
number of bins(1D), cells (2D) +U/Overflows
Definition: TH1.h:86
void Copy(TAttFill &attfill) const
Copy this fill attributes to a new TAttFill.
Definition: TAttFill.cxx:200
void AndersonDarling2SamplesTest(Double_t &pvalue, Double_t &testStat) const
Definition: GoFTest.cxx:646
T MinElement(Long64_t n, const T *a)
Definition: TMath.h:829
void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
Least square linear fit without weights.
Definition: TH1.cxx:4530
const char * Data() const
Definition: TString.h:345
Array of chars or bytes (8 bits per element).
Definition: TArrayC.h:27
virtual void SavePrimitive(std::ostream &out, Option_t *option="")
Save a primitive as a C++ statement(s) on output stream "out".
Definition: TObject.cxx:664
Double_t ATan(Double_t)
Definition: TMath.h:577