Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
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 <array>
13#include <cctype>
14#include <climits>
15#include <cmath>
16#include <cstdio>
17#include <cstdlib>
18#include <cstring>
19#include <iostream>
20#include <sstream>
21#include <fstream>
22
23#include "TROOT.h"
24#include "TBuffer.h"
25#include "TEnv.h"
26#include "TClass.h"
27#include "TMath.h"
28#include "THashList.h"
29#include "TH1.h"
30#include "TH2.h"
31#include "TH3.h"
32#include "TF2.h"
33#include "TF3.h"
34#include "TPluginManager.h"
35#include "TVirtualPad.h"
36#include "TRandom.h"
37#include "TVirtualFitter.h"
38#include "THLimitsFinder.h"
39#include "TProfile.h"
40#include "TStyle.h"
41#include "TVectorF.h"
42#include "TVectorD.h"
43#include "TBrowser.h"
44#include "TError.h"
45#include "TVirtualHistPainter.h"
46#include "TVirtualFFT.h"
47#include "TVirtualPaveStats.h"
48
49#include "HFitInterface.h"
50#include "Fit/DataRange.h"
51#include "Fit/BinData.h"
52#include "Math/GoFTest.h"
55
56#include "TH1Merger.h"
57
58/** \addtogroup Histograms
59@{
60\class TH1C
61\brief 1-D histogram with a byte per channel (see TH1 documentation)
62\class TH1S
63\brief 1-D histogram with a short per channel (see TH1 documentation)
64\class TH1I
65\brief 1-D histogram with an int per channel (see TH1 documentation)
66\class TH1L
67\brief 1-D histogram with a long64 per channel (see TH1 documentation)
68\class TH1F
69\brief 1-D histogram with a float per channel (see TH1 documentation)
70\class TH1D
71\brief 1-D histogram with a double per channel (see TH1 documentation)
72@}
73*/
74
75/** \class TH1
76 \ingroup Histograms
77TH1 is the base class of all histogram classes in %ROOT.
78
79It provides the common interface for operations such as binning, filling, drawing, which
80will be detailed below.
81
82-# [Creating histograms](\ref creating-histograms)
83 - [Labelling axes](\ref labelling-axis)
84-# [Binning](\ref binning)
85 - [Fix or variable bin size](\ref fix-var)
86 - [Convention for numbering bins](\ref convention)
87 - [Alphanumeric Bin Labels](\ref alpha)
88 - [Histograms with automatic bins](\ref auto-bin)
89 - [Rebinning](\ref rebinning)
90-# [Filling histograms](\ref filling-histograms)
91 - [Associated errors](\ref associated-errors)
92 - [Associated functions](\ref associated-functions)
93 - [Projections of histograms](\ref prof-hist)
94 - [Random Numbers and histograms](\ref random-numbers)
95 - [Making a copy of a histogram](\ref making-a-copy)
96 - [Normalizing histograms](\ref normalizing)
97-# [Drawing histograms](\ref drawing-histograms)
98 - [Setting Drawing histogram contour levels (2-D hists only)](\ref cont-level)
99 - [Setting histogram graphics attributes](\ref graph-att)
100 - [Customising how axes are drawn](\ref axis-drawing)
101-# [Fitting histograms](\ref fitting-histograms)
102-# [Saving/reading histograms to/from a ROOT file](\ref saving-histograms)
103-# [Operations on histograms](\ref operations-on-histograms)
104-# [Miscellaneous operations](\ref misc)
105
106ROOT supports the following histogram types:
107
108 - 1-D histograms:
109 - TH1C : histograms with one byte per channel. Maximum bin content = 127
110 - TH1S : histograms with one short per channel. Maximum bin content = 32767
111 - TH1I : histograms with one int per channel. Maximum bin content = INT_MAX (\ref intmax "*")
112 - TH1L : histograms with one long64 per channel. Maximum bin content = LLONG_MAX (\ref llongmax "*")
113 - TH1F : histograms with one float per channel. Maximum precision 7 digits, maximum integer bin content = +/-16777216 (\ref floatmax "**")
114 - TH1D : histograms with one double per channel. Maximum precision 14 digits, maximum integer bin content = +/-9007199254740992 (\ref doublemax "***")
115 - 2-D histograms:
116 - TH2C : histograms with one byte per channel. Maximum bin content = 127
117 - TH2S : histograms with one short per channel. Maximum bin content = 32767
118 - TH2I : histograms with one int per channel. Maximum bin content = INT_MAX (\ref intmax "*")
119 - TH2L : histograms with one long64 per channel. Maximum bin content = LLONG_MAX (\ref llongmax "*")
120 - TH2F : histograms with one float per channel. Maximum precision 7 digits, maximum integer bin content = +/-16777216 (\ref floatmax "**")
121 - TH2D : histograms with one double per channel. Maximum precision 14 digits, maximum integer bin content = +/-9007199254740992 (\ref doublemax "***")
122 - 3-D histograms:
123 - TH3C : histograms with one byte per channel. Maximum bin content = 127
124 - TH3S : histograms with one short per channel. Maximum bin content = 32767
125 - TH3I : histograms with one int per channel. Maximum bin content = INT_MAX (\ref intmax "*")
126 - TH3L : histograms with one long64 per channel. Maximum bin content = LLONG_MAX (\ref llongmax "*")
127 - TH3F : histograms with one float per channel. Maximum precision 7 digits, maximum integer bin content = +/-16777216 (\ref floatmax "**")
128 - TH3D : histograms with one double per channel. Maximum precision 14 digits, maximum integer bin content = +/-9007199254740992 (\ref doublemax "***")
129 - Profile histograms: See classes TProfile, TProfile2D and TProfile3D.
130 Profile histograms are used to display the mean value of Y and its standard deviation
131 for each bin in X. Profile histograms are in many cases an elegant
132 replacement of two-dimensional histograms : the inter-relation of two
133 measured quantities X and Y can always be visualized by a two-dimensional
134 histogram or scatter-plot; If Y is an unknown (but single-valued)
135 approximate function of X, this function is displayed by a profile
136 histogram with much better precision than by a scatter-plot.
137
138<sup>
139\anchor intmax (*) INT_MAX = 2147483647 is the [maximum value for a variable of type int.](https://docs.microsoft.com/en-us/cpp/c-language/cpp-integer-limits)
140\anchor llongmax (*) LLONG_MAX = 9223372036854775807 is the [maximum value for a variable of type long64.](https://docs.microsoft.com/en-us/cpp/c-language/cpp-integer-limits)
141\anchor floatmax (**) 2^24 = 16777216 is the [maximum integer that can be properly represented by a float32 with 23-bit mantissa.](https://stackoverflow.com/a/3793950/7471760)
142\anchor doublemax (***) 2^53 = 9007199254740992 is the [maximum integer that can be properly represented by a double64 with 52-bit mantissa.](https://stackoverflow.com/a/3793950/7471760)
143</sup>
144
145The inheritance hierarchy looks as follows:
146
147\image html classTH1__inherit__graph_org.svg width=100%
148
149\anchor creating-histograms
150## Creating histograms
151
152Histograms are created by invoking one of the constructors, e.g.
153~~~ {.cpp}
154 TH1F *h1 = new TH1F("h1", "h1 title", 100, 0, 4.4);
155 TH2F *h2 = new TH2F("h2", "h2 title", 40, 0, 4, 30, -3, 3);
156~~~
157Histograms may also be created by:
158
159 - calling the Clone() function, see below
160 - making a projection from a 2-D or 3-D histogram, see below
161 - reading a histogram from a file
162
163 When a histogram is created, a reference to it is automatically added
164 to the list of in-memory objects for the current file or directory.
165 Then the pointer to this histogram in the current directory can be found
166 by its name, doing:
167~~~ {.cpp}
168 TH1F *h1 = (TH1F*)gDirectory->FindObject(name);
169~~~
170
171 This default behaviour can be changed by:
172~~~ {.cpp}
173 h->SetDirectory(nullptr); // for the current histogram h
174 TH1::AddDirectory(kFALSE); // sets a global switch disabling the referencing
175~~~
176 When the histogram is deleted, the reference to it is removed from
177 the list of objects in memory.
178 When a file is closed, all histograms in memory associated with this file
179 are automatically deleted.
180
181\anchor labelling-axis
182### Labelling axes
183
184 Axis titles can be specified in the title argument of the constructor.
185 They must be separated by ";":
186~~~ {.cpp}
187 TH1F* h=new TH1F("h", "Histogram title;X Axis;Y Axis", 100, 0, 1);
188~~~
189 The histogram title and the axis titles can be any TLatex string, and
190 are persisted if a histogram is written to a file.
191
192 Any title can be omitted:
193~~~ {.cpp}
194 TH1F* h=new TH1F("h", "Histogram title;;Y Axis", 100, 0, 1);
195 TH1F* h=new TH1F("h", ";;Y Axis", 100, 0, 1);
196~~~
197 The method SetTitle() has the same syntax:
198~~~ {.cpp}
199 h->SetTitle("Histogram title;Another X title Axis");
200~~~
201Alternatively, the title of each axis can be set directly:
202~~~ {.cpp}
203 h->GetXaxis()->SetTitle("X axis title");
204 h->GetYaxis()->SetTitle("Y axis title");
205~~~
206For bin labels see \ref binning.
207
208\anchor binning
209## Binning
210
211\anchor fix-var
212### Fix or variable bin size
213
214 All histogram types support either fix or variable bin sizes.
215 2-D histograms may have fix size bins along X and variable size bins
216 along Y or vice-versa. The functions to fill, manipulate, draw or access
217 histograms are identical in both cases.
218
219 Each histogram always contains 3 axis objects of type TAxis: fXaxis, fYaxis and fZaxis.
220 To access the axis parameters, use:
221~~~ {.cpp}
222 TAxis *xaxis = h->GetXaxis(); etc.
223 Double_t binCenter = xaxis->GetBinCenter(bin), etc.
224~~~
225 See class TAxis for a description of all the access functions.
226 The axis range is always stored internally in double precision.
227
228\anchor convention
229### Convention for numbering bins
230
231 For all histogram types: nbins, xlow, xup
232~~~ {.cpp}
233 bin = 0; underflow bin
234 bin = 1; first bin with low-edge xlow INCLUDED
235 bin = nbins; last bin with upper-edge xup EXCLUDED
236 bin = nbins+1; overflow bin
237~~~
238 In case of 2-D or 3-D histograms, a "global bin" number is defined.
239 For example, assuming a 3-D histogram with (binx, biny, binz), the function
240~~~ {.cpp}
241 Int_t gbin = h->GetBin(binx, biny, binz);
242~~~
243 returns a global/linearized gbin number. This global gbin is useful
244 to access the bin content/error information independently of the dimension.
245 Note that to access the information other than bin content and errors
246 one should use the TAxis object directly with e.g.:
247~~~ {.cpp}
248 Double_t xcenter = h3->GetZaxis()->GetBinCenter(27);
249~~~
250 returns the center along z of bin number 27 (not the global bin)
251 in the 3-D histogram h3.
252
253\anchor alpha
254### Alphanumeric Bin Labels
255
256 By default, a histogram axis is drawn with its numeric bin labels.
257 One can specify alphanumeric labels instead with:
258
259 - call TAxis::SetBinLabel(bin, label);
260 This can always be done before or after filling.
261 When the histogram is drawn, bin labels will be automatically drawn.
262 See examples labels1.C and labels2.C
263 - call to a Fill function with one of the arguments being a string, e.g.
264~~~ {.cpp}
265 hist1->Fill(somename, weight);
266 hist2->Fill(x, somename, weight);
267 hist2->Fill(somename, y, weight);
268 hist2->Fill(somenamex, somenamey, weight);
269~~~
270 See examples hlabels1.C and hlabels2.C
271 - via TTree::Draw. see for example cernstaff.C
272~~~ {.cpp}
273 tree.Draw("Nation::Division");
274~~~
275 where "Nation" and "Division" are two branches of a Tree.
276
277When using the options 2 or 3 above, the labels are automatically
278 added to the list (THashList) of labels for a given axis.
279 By default, an axis is drawn with the order of bins corresponding
280 to the filling sequence. It is possible to reorder the axis
281
282 - alphabetically
283 - by increasing or decreasing values
284
285 The reordering can be triggered via the TAxis context menu by selecting
286 the menu item "LabelsOption" or by calling directly
287 TH1::LabelsOption(option, axis) where
288
289 - axis may be "X", "Y" or "Z"
290 - option may be:
291 - "a" sort by alphabetic order
292 - ">" sort by decreasing values
293 - "<" sort by increasing values
294 - "h" draw labels horizontal
295 - "v" draw labels vertical
296 - "u" draw labels up (end of label right adjusted)
297 - "d" draw labels down (start of label left adjusted)
298
299 When using the option 2 above, new labels are added by doubling the current
300 number of bins in case one label does not exist yet.
301 When the Filling is terminated, it is possible to trim the number
302 of bins to match the number of active labels by calling
303~~~ {.cpp}
304 TH1::LabelsDeflate(axis) with axis = "X", "Y" or "Z"
305~~~
306 This operation is automatic when using TTree::Draw.
307 Once bin labels have been created, they become persistent if the histogram
308 is written to a file or when generating the C++ code via SavePrimitive.
309
310\anchor auto-bin
311### Histograms with automatic bins
312
313 When a histogram is created with an axis lower limit greater or equal
314 to its upper limit, the SetBuffer is automatically called with an
315 argument fBufferSize equal to fgBufferSize (default value=1000).
316 fgBufferSize may be reset via the static function TH1::SetDefaultBufferSize.
317 The axis limits will be automatically computed when the buffer will
318 be full or when the function BufferEmpty is called.
319
320\anchor rebinning
321### Rebinning
322
323 At any time, a histogram can be rebinned via TH1::Rebin. This function
324 returns a new histogram with the rebinned contents.
325 If bin errors were stored, they are recomputed during the rebinning.
326
327
328\anchor filling-histograms
329## Filling histograms
331 A histogram is typically filled with statements like:
332~~~ {.cpp}
333 h1->Fill(x);
334 h1->Fill(x, w); //fill with weight
335 h2->Fill(x, y)
336 h2->Fill(x, y, w)
337 h3->Fill(x, y, z)
338 h3->Fill(x, y, z, w)
339~~~
340 or via one of the Fill functions accepting names described above.
341 The Fill functions compute the bin number corresponding to the given
342 x, y or z argument and increment this bin by the given weight.
343 The Fill functions return the bin number for 1-D histograms or global
344 bin number for 2-D and 3-D histograms.
345 If TH1::Sumw2 has been called before filling, the sum of squares of
346 weights is also stored.
347 One can also increment directly a bin number via TH1::AddBinContent
348 or replace the existing content via TH1::SetBinContent. Passing an
349 out-of-range bin to TH1::AddBinContent leads to undefined behavior.
350 To access the bin content of a given bin, do:
351~~~ {.cpp}
352 Double_t binContent = h->GetBinContent(bin);
353~~~
354
355 By default, the bin number is computed using the current axis ranges.
356 If the automatic binning option has been set via
357~~~ {.cpp}
358 h->SetCanExtend(TH1::kAllAxes);
359~~~
360 then, the Fill Function will automatically extend the axis range to
361 accomodate the new value specified in the Fill argument. The method
362 used is to double the bin size until the new value fits in the range,
363 merging bins two by two. This automatic binning options is extensively
364 used by the TTree::Draw function when histogramming Tree variables
365 with an unknown range.
366 This automatic binning option is supported for 1-D, 2-D and 3-D histograms.
367
368 During filling, some statistics parameters are incremented to compute
369 the mean value and Root Mean Square with the maximum precision.
370
371 In case of histograms of type TH1C, TH1S, TH2C, TH2S, TH3C, TH3S
372 a check is made that the bin contents do not exceed the maximum positive
373 capacity (127 or 32767). Histograms of all types may have positive
374 or/and negative bin contents.
375
376\anchor associated-errors
377### Associated errors
378 By default, for each bin, the sum of weights is computed at fill time.
379 One can also call TH1::Sumw2 to force the storage and computation
380 of the sum of the square of weights per bin.
381 If Sumw2 has been called, the error per bin is computed as the
382 sqrt(sum of squares of weights), otherwise the error is set equal
383 to the sqrt(bin content).
384 To return the error for a given bin number, do:
385~~~ {.cpp}
386 Double_t error = h->GetBinError(bin);
387~~~
388
389\anchor associated-functions
390### Associated functions
391 One or more object (typically a TF1*) can be added to the list
392 of functions (fFunctions) associated to each histogram.
393 When TH1::Fit is invoked, the fitted function is added to this list.
394 Given a histogram h, one can retrieve an associated function
395 with:
396~~~ {.cpp}
397 TF1 *myfunc = h->GetFunction("myfunc");
398~~~
399
400
401\anchor operations-on-histograms
402## Operations on histograms
403
404 Many types of operations are supported on histograms or between histograms
405
406 - Addition of a histogram to the current histogram.
407 - Additions of two histograms with coefficients and storage into the current
408 histogram.
409 - Multiplications and Divisions are supported in the same way as additions.
410 - The Add, Divide and Multiply functions also exist to add, divide or multiply
411 a histogram by a function.
412
413 If a histogram has associated error bars (TH1::Sumw2 has been called),
414 the resulting error bars are also computed assuming independent histograms.
415 In case of divisions, Binomial errors are also supported.
416 One can mark a histogram to be an "average" histogram by setting its bit kIsAverage via
417 myhist.SetBit(TH1::kIsAverage);
418 When adding (see TH1::Add) average histograms, the histograms are averaged and not summed.
419
420
421\anchor prof-hist
422### Projections of histograms
423
424 One can:
425
426 - make a 1-D projection of a 2-D histogram or Profile
427 see functions TH2::ProjectionX,Y, TH2::ProfileX,Y, TProfile::ProjectionX
428 - make a 1-D, 2-D or profile out of a 3-D histogram
429 see functions TH3::ProjectionZ, TH3::Project3D.
430
431 One can fit these projections via:
432~~~ {.cpp}
433 TH2::FitSlicesX,Y, TH3::FitSlicesZ.
434~~~
435
436\anchor random-numbers
437### Random Numbers and histograms
438
439 TH1::FillRandom can be used to randomly fill a histogram using
440 the contents of an existing TF1 function or another
441 TH1 histogram (for all dimensions).
442 For example, the following two statements create and fill a histogram
443 10000 times with a default gaussian distribution of mean 0 and sigma 1:
444~~~ {.cpp}
445 TH1F h1("h1", "histo from a gaussian", 100, -3, 3);
446 h1.FillRandom("gaus", 10000);
447~~~
448 TH1::GetRandom can be used to return a random number distributed
449 according to the contents of a histogram.
450
451\anchor making-a-copy
452### Making a copy of a histogram
453 Like for any other ROOT object derived from TObject, one can use
454 the Clone() function. This makes an identical copy of the original
455 histogram including all associated errors and functions, e.g.:
456~~~ {.cpp}
457 TH1F *hnew = (TH1F*)h->Clone("hnew");
458~~~
459
460\anchor normalizing
461### Normalizing histograms
462
463 One can scale a histogram such that the bins integral is equal to
464 the normalization parameter via TH1::Scale(Double_t norm), where norm
465 is the desired normalization divided by the integral of the histogram.
466
467
468\anchor drawing-histograms
469## Drawing histograms
470
471 Histograms are drawn via the THistPainter class. Each histogram has
472 a pointer to its own painter (to be usable in a multithreaded program).
473 Many drawing options are supported.
474 See THistPainter::Paint() for more details.
475
476 The same histogram can be drawn with different options in different pads.
477 When a histogram drawn in a pad is deleted, the histogram is
478 automatically removed from the pad or pads where it was drawn.
479 If a histogram is drawn in a pad, then filled again, the new status
480 of the histogram will be automatically shown in the pad next time
481 the pad is updated. One does not need to redraw the histogram.
482 To draw the current version of a histogram in a pad, one can use
483~~~ {.cpp}
484 h->DrawCopy();
485~~~
486 This makes a clone (see Clone below) of the histogram. Once the clone
487 is drawn, the original histogram may be modified or deleted without
488 affecting the aspect of the clone.
489
490 One can use TH1::SetMaximum() and TH1::SetMinimum() to force a particular
491 value for the maximum or the minimum scale on the plot. (For 1-D
492 histograms this means the y-axis, while for 2-D histograms these
493 functions affect the z-axis).
494
495 TH1::UseCurrentStyle() can be used to change all histogram graphics
496 attributes to correspond to the current selected style.
497 This function must be called for each histogram.
498 In case one reads and draws many histograms from a file, one can force
499 the histograms to inherit automatically the current graphics style
500 by calling before gROOT->ForceStyle().
501
502\anchor cont-level
503### Setting Drawing histogram contour levels (2-D hists only)
504
505 By default contours are automatically generated at equidistant
506 intervals. A default value of 20 levels is used. This can be modified
507 via TH1::SetContour() or TH1::SetContourLevel().
508 the contours level info is used by the drawing options "cont", "surf",
509 and "lego".
510
511\anchor graph-att
512### Setting histogram graphics attributes
513
514 The histogram classes inherit from the attribute classes:
515 TAttLine, TAttFill, and TAttMarker.
516 See the member functions of these classes for the list of options.
517
518\anchor axis-drawing
519### Customizing how axes are drawn
520
521 Use the functions of TAxis, such as
522~~~ {.cpp}
523 histogram.GetXaxis()->SetTicks("+");
524 histogram.GetYaxis()->SetRangeUser(1., 5.);
525~~~
526
527\anchor fitting-histograms
528## Fitting histograms
529
530 Histograms (1-D, 2-D, 3-D and Profiles) can be fitted with a user
531 specified function or a pre-defined function via TH1::Fit.
532 See TH1::Fit(TF1*, Option_t *, Option_t *, Double_t, Double_t) for the fitting documentation and the possible [fitting options](\ref HFitOpt)
533
534 The FitPanel can also be used for fitting an histogram. See the [FitPanel documentation](https://root.cern/manual/fitting/#using-the-fit-panel).
535
536\anchor saving-histograms
537## Saving/reading histograms to/from a ROOT file
538
539 The following statements create a ROOT file and store a histogram
540 on the file. Because TH1 derives from TNamed, the key identifier on
541 the file is the histogram name:
542~~~ {.cpp}
543 TFile f("histos.root", "new");
544 TH1F h1("hgaus", "histo from a gaussian", 100, -3, 3);
545 h1.FillRandom("gaus", 10000);
546 h1->Write();
547~~~
548 To read this histogram in another Root session, do:
549~~~ {.cpp}
550 TFile f("histos.root");
551 TH1F *h = (TH1F*)f.Get("hgaus");
552~~~
553 One can save all histograms in memory to the file by:
554~~~ {.cpp}
555 file->Write();
556~~~
557
558
559\anchor misc
560## Miscellaneous operations
561
562~~~ {.cpp}
563 TH1::KolmogorovTest(): statistical test of compatibility in shape
564 between two histograms
565 TH1::Smooth() smooths the bin contents of a 1-d histogram
566 TH1::Integral() returns the integral of bin contents in a given bin range
567 TH1::GetMean(int axis) returns the mean value along axis
568 TH1::GetStdDev(int axis) returns the sigma distribution along axis
569 TH1::GetEntries() returns the number of entries
570 TH1::Reset() resets the bin contents and errors of a histogram
571~~~
572 IMPORTANT NOTE: The returned values for GetMean and GetStdDev depend on how the
573 histogram statistics are calculated. By default, if no range has been set, the
574 returned values are the (unbinned) ones calculated at fill time. If a range has been
575 set, however, the values are calculated using the bins in range; THIS IS TRUE EVEN
576 IF THE RANGE INCLUDES ALL BINS--use TAxis::SetRange(0, 0) to unset the range.
577 To ensure that the returned values are always those of the binned data stored in the
578 histogram, call TH1::ResetStats. See TH1::GetStats.
579*/
580
581TF1 *gF1=nullptr; //left for back compatibility (use TVirtualFitter::GetUserFunc instead)
582
587
588extern void H1InitGaus();
589extern void H1InitExpo();
590extern void H1InitPolynom();
591extern void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a);
592extern void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail);
593extern void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b);
594
595namespace {
596
597/// Enumeration specifying inconsistencies between two histograms,
598/// in increasing severity.
599enum EInconsistencyBits {
600 kFullyConsistent = 0,
601 kDifferentLabels = BIT(0),
602 kDifferentBinLimits = BIT(1),
603 kDifferentAxisLimits = BIT(2),
604 kDifferentNumberOfBins = BIT(3),
605 kDifferentDimensions = BIT(4)
606};
607
608} // namespace
609
611
612////////////////////////////////////////////////////////////////////////////////
613/// Histogram default constructor.
614
616{
617 fDirectory = nullptr;
618 fFunctions = new TList;
619 fNcells = 0;
620 fIntegral = nullptr;
621 fPainter = nullptr;
622 fEntries = 0;
623 fNormFactor = 0;
625 fMaximum = -1111;
626 fMinimum = -1111;
627 fBufferSize = 0;
628 fBuffer = nullptr;
631 fXaxis.SetName("xaxis");
632 fYaxis.SetName("yaxis");
633 fZaxis.SetName("zaxis");
634 fXaxis.SetParent(this);
635 fYaxis.SetParent(this);
636 fZaxis.SetParent(this);
638}
639
640////////////////////////////////////////////////////////////////////////////////
641/// Histogram default destructor.
642
644{
646 return;
647 }
648 delete[] fIntegral;
649 fIntegral = nullptr;
650 delete[] fBuffer;
651 fBuffer = nullptr;
652 if (fFunctions) {
654
656 TObject* obj = nullptr;
657 //special logic to support the case where the same object is
658 //added multiple times in fFunctions.
659 //This case happens when the same object is added with different
660 //drawing modes
661 //In the loop below we must be careful with objects (eg TCutG) that may
662 // have been added to the list of functions of several histograms
663 //and may have been already deleted.
664 while ((obj = fFunctions->First())) {
665 while(fFunctions->Remove(obj)) { }
667 break;
668 }
669 delete obj;
670 obj = nullptr;
671 }
672 delete fFunctions;
673 fFunctions = nullptr;
674 }
675 if (fDirectory) {
676 fDirectory->Remove(this);
677 fDirectory = nullptr;
678 }
679 delete fPainter;
680 fPainter = nullptr;
681}
682
683////////////////////////////////////////////////////////////////////////////////
684/// Constructor for fix bin size histograms.
685/// Creates the main histogram structure.
686///
687/// \param[in] name name of histogram (avoid blanks)
688/// \param[in] title histogram title.
689/// If title is of the form `stringt;stringx;stringy;stringz`,
690/// the histogram title is set to `stringt`,
691/// the x axis title to `stringx`, the y axis title to `stringy`, etc.
692/// \param[in] nbins number of bins
693/// \param[in] xlow low edge of first bin
694/// \param[in] xup upper edge of last bin (not included in last bin)
695
696
697TH1::TH1(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
698 :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
699{
700 Build();
701 if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
702 fXaxis.Set(nbins,xlow,xup);
703 fNcells = fXaxis.GetNbins()+2;
704}
705
706////////////////////////////////////////////////////////////////////////////////
707/// Constructor for variable bin size histograms using an input array of type float.
708/// Creates the main histogram structure.
709///
710/// \param[in] name name of histogram (avoid blanks)
711/// \param[in] title histogram title.
712/// If title is of the form `stringt;stringx;stringy;stringz`
713/// the histogram title is set to `stringt`,
714/// the x axis title to `stringx`, the y axis title to `stringy`, etc.
715/// \param[in] nbins number of bins
716/// \param[in] xbins array of low-edges for each bin.
717/// This is an array of type float and size nbins+1
718
719TH1::TH1(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
720 :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
721{
722 Build();
723 if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
724 if (xbins) fXaxis.Set(nbins,xbins);
725 else fXaxis.Set(nbins,0,1);
726 fNcells = fXaxis.GetNbins()+2;
727}
728
729////////////////////////////////////////////////////////////////////////////////
730/// Constructor for variable bin size histograms using an input array of type double.
731///
732/// \param[in] name name of histogram (avoid blanks)
733/// \param[in] title histogram title.
734/// If title is of the form `stringt;stringx;stringy;stringz`
735/// the histogram title is set to `stringt`,
736/// the x axis title to `stringx`, the y axis title to `stringy`, etc.
737/// \param[in] nbins number of bins
738/// \param[in] xbins array of low-edges for each bin.
739/// This is an array of type double and size nbins+1
740
741TH1::TH1(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
742 :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
743{
744 Build();
745 if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
746 if (xbins) fXaxis.Set(nbins,xbins);
747 else fXaxis.Set(nbins,0,1);
748 fNcells = fXaxis.GetNbins()+2;
749}
750
751////////////////////////////////////////////////////////////////////////////////
752/// Static function: cannot be inlined on Windows/NT.
753
755{
756 return fgAddDirectory;
757}
758
759////////////////////////////////////////////////////////////////////////////////
760/// Browse the Histogram object.
761
763{
764 Draw(b ? b->GetDrawOption() : "");
765 gPad->Update();
766}
767
768////////////////////////////////////////////////////////////////////////////////
769/// Creates histogram basic data structure.
770
772{
773 fDirectory = nullptr;
774 fPainter = nullptr;
775 fIntegral = nullptr;
776 fEntries = 0;
777 fNormFactor = 0;
779 fMaximum = -1111;
780 fMinimum = -1111;
781 fBufferSize = 0;
782 fBuffer = nullptr;
785 fXaxis.SetName("xaxis");
786 fYaxis.SetName("yaxis");
787 fZaxis.SetName("zaxis");
788 fYaxis.Set(1,0.,1.);
789 fZaxis.Set(1,0.,1.);
790 fXaxis.SetParent(this);
791 fYaxis.SetParent(this);
792 fZaxis.SetParent(this);
793
795
796 fFunctions = new TList;
797
799
802 if (fDirectory) {
804 fDirectory->Append(this,kTRUE);
805 }
806 }
807}
808
809////////////////////////////////////////////////////////////////////////////////
810/// Performs the operation: `this = this + c1*f1`
811/// if errors are defined (see TH1::Sumw2), errors are also recalculated.
812///
813/// By default, the function is computed at the centre of the bin.
814/// if option "I" is specified (1-d histogram only), the integral of the
815/// function in each bin is used instead of the value of the function at
816/// the centre of the bin.
817///
818/// Only bins inside the function range are recomputed.
819///
820/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
821/// you should call Sumw2 before making this operation.
822/// This is particularly important if you fit the histogram after TH1::Add
823///
824/// The function return kFALSE if the Add operation failed
825
827{
828 if (!f1) {
829 Error("Add","Attempt to add a non-existing function");
830 return kFALSE;
831 }
832
833 TString opt = option;
834 opt.ToLower();
835 Bool_t integral = kFALSE;
836 if (opt.Contains("i") && fDimension == 1) integral = kTRUE;
837
838 Int_t ncellsx = GetNbinsX() + 2; // cells = normal bins + underflow bin + overflow bin
839 Int_t ncellsy = GetNbinsY() + 2;
840 Int_t ncellsz = GetNbinsZ() + 2;
841 if (fDimension < 2) ncellsy = 1;
842 if (fDimension < 3) ncellsz = 1;
843
844 // delete buffer if it is there since it will become invalid
845 if (fBuffer) BufferEmpty(1);
846
847 // - Add statistics
848 Double_t s1[10];
849 for (Int_t i = 0; i < 10; ++i) s1[i] = 0;
850 PutStats(s1);
851 SetMinimum();
852 SetMaximum();
853
854 // - Loop on bins (including underflows/overflows)
855 Int_t bin, binx, biny, binz;
856 Double_t cu=0;
857 Double_t xx[3];
858 Double_t *params = nullptr;
859 f1->InitArgs(xx,params);
860 for (binz = 0; binz < ncellsz; ++binz) {
861 xx[2] = fZaxis.GetBinCenter(binz);
862 for (biny = 0; biny < ncellsy; ++biny) {
863 xx[1] = fYaxis.GetBinCenter(biny);
864 for (binx = 0; binx < ncellsx; ++binx) {
865 xx[0] = fXaxis.GetBinCenter(binx);
866 if (!f1->IsInside(xx)) continue;
868 bin = binx + ncellsx * (biny + ncellsy * binz);
869 if (integral) {
870 cu = c1*f1->Integral(fXaxis.GetBinLowEdge(binx), fXaxis.GetBinUpEdge(binx), 0.) / fXaxis.GetBinWidth(binx);
871 } else {
872 cu = c1*f1->EvalPar(xx);
873 }
874 if (TF1::RejectedPoint()) continue;
875 AddBinContent(bin,cu);
876 }
877 }
878 }
879
880 return kTRUE;
881}
882
883int TH1::LoggedInconsistency(const char *name, const TH1 *h1, const TH1 *h2, bool useMerge) const
884{
885 const auto inconsistency = CheckConsistency(h1, h2);
886
887 if (inconsistency & kDifferentDimensions) {
888 if (useMerge)
889 Info(name, "Histograms have different dimensions - trying to use TH1::Merge");
890 else {
891 Error(name, "Histograms have different dimensions");
892 }
893 } else if (inconsistency & kDifferentNumberOfBins) {
894 if (useMerge)
895 Info(name, "Histograms have different number of bins - trying to use TH1::Merge");
896 else {
897 Error(name, "Histograms have different number of bins");
898 }
899 } else if (inconsistency & kDifferentAxisLimits) {
900 if (useMerge)
901 Info(name, "Histograms have different axis limits - trying to use TH1::Merge");
902 else
903 Warning(name, "Histograms have different axis limits");
904 } else if (inconsistency & kDifferentBinLimits) {
905 if (useMerge)
906 Info(name, "Histograms have different bin limits - trying to use TH1::Merge");
907 else
908 Warning(name, "Histograms have different bin limits");
909 } else if (inconsistency & kDifferentLabels) {
910 // in case of different labels -
911 if (useMerge)
912 Info(name, "Histograms have different labels - trying to use TH1::Merge");
913 else
914 Info(name, "Histograms have different labels");
915 }
916
917 return inconsistency;
918}
919
920////////////////////////////////////////////////////////////////////////////////
921/// Performs the operation: `this = this + c1*h1`
922/// If errors are defined (see TH1::Sumw2), errors are also recalculated.
923///
924/// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
925/// if not already set.
926///
927/// Note also that adding histogram with labels is not supported, histogram will be
928/// added merging them by bin number independently of the labels.
929/// For adding histogram with labels one should use TH1::Merge
930///
931/// SPECIAL CASE (Average/Efficiency histograms)
932/// For histograms representing averages or efficiencies, one should compute the average
933/// of the two histograms and not the sum. One can mark a histogram to be an average
934/// histogram by setting its bit kIsAverage with
935/// myhist.SetBit(TH1::kIsAverage);
936/// Note that the two histograms must have their kIsAverage bit set
937///
938/// IMPORTANT NOTE1: If you intend to use the errors of this histogram later
939/// you should call Sumw2 before making this operation.
940/// This is particularly important if you fit the histogram after TH1::Add
941///
942/// IMPORTANT NOTE2: if h1 has a normalisation factor, the normalisation factor
943/// is used , ie this = this + c1*factor*h1
944/// Use the other TH1::Add function if you do not want this feature
945///
946/// IMPORTANT NOTE3: You should be careful about the statistics of the
947/// returned histogram, whose statistics may be binned or unbinned,
948/// depending on whether c1 is negative, whether TAxis::kAxisRange is true,
949/// and whether TH1::ResetStats has been called on either this or h1.
950/// See TH1::GetStats.
951///
952/// The function return kFALSE if the Add operation failed
953
955{
956 if (!h1) {
957 Error("Add","Attempt to add a non-existing histogram");
958 return kFALSE;
959 }
960
961 // delete buffer if it is there since it will become invalid
962 if (fBuffer) BufferEmpty(1);
963
964 bool useMerge = false;
965 const bool considerMerge = (c1 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
966 const auto inconsistency = LoggedInconsistency("Add", this, h1, considerMerge);
967 // If there is a bad inconsistency and we can't even consider merging, just give up
968 if(inconsistency >= kDifferentNumberOfBins && !considerMerge) {
969 return false;
970 }
971 // If there is an inconsistency, we try to use merging
972 if(inconsistency > kFullyConsistent) {
973 useMerge = considerMerge;
974 }
975
976 if (useMerge) {
977 TList l;
978 l.Add(const_cast<TH1*>(h1));
979 auto iret = Merge(&l);
980 return (iret >= 0);
981 }
982
983 // Create Sumw2 if h1 has Sumw2 set
984 if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
985
986 // - Add statistics
987 Double_t entries = TMath::Abs( GetEntries() + c1 * h1->GetEntries() );
988
989 // statistics can be preserved only in case of positive coefficients
990 // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
991 Bool_t resetStats = (c1 < 0);
992 Double_t s1[kNstat] = {0};
993 Double_t s2[kNstat] = {0};
994 if (!resetStats) {
995 // need to initialize to zero s1 and s2 since
996 // GetStats fills only used elements depending on dimension and type
997 GetStats(s1);
998 h1->GetStats(s2);
999 }
1000
1001 SetMinimum();
1002 SetMaximum();
1003
1004 // - Loop on bins (including underflows/overflows)
1005 Double_t factor = 1;
1006 if (h1->GetNormFactor() != 0) factor = h1->GetNormFactor()/h1->GetSumOfWeights();;
1007 Double_t c1sq = c1 * c1;
1008 Double_t factsq = factor * factor;
1009
1010 for (Int_t bin = 0; bin < fNcells; ++bin) {
1011 //special case where histograms have the kIsAverage bit set
1012 if (this->TestBit(kIsAverage) && h1->TestBit(kIsAverage)) {
1014 Double_t y2 = this->RetrieveBinContent(bin);
1015 Double_t e1sq = h1->GetBinErrorSqUnchecked(bin);
1016 Double_t e2sq = this->GetBinErrorSqUnchecked(bin);
1017 Double_t w1 = 1., w2 = 1.;
1018
1019 // consider all special cases when bin errors are zero
1020 // see http://root-forum.cern.ch/viewtopic.php?f=3&t=13299
1021 if (e1sq) w1 = 1. / e1sq;
1022 else if (h1->fSumw2.fN) {
1023 w1 = 1.E200; // use an arbitrary huge value
1024 if (y1 == 0) {
1025 // use an estimated error from the global histogram scale
1026 double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
1027 w1 = 1./(sf*sf);
1028 }
1029 }
1030 if (e2sq) w2 = 1. / e2sq;
1031 else if (fSumw2.fN) {
1032 w2 = 1.E200; // use an arbitrary huge value
1033 if (y2 == 0) {
1034 // use an estimated error from the global histogram scale
1035 double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
1036 w2 = 1./(sf*sf);
1037 }
1038 }
1039
1040 double y = (w1*y1 + w2*y2)/(w1 + w2);
1041 UpdateBinContent(bin, y);
1042 if (fSumw2.fN) {
1043 double err2 = 1./(w1 + w2);
1044 if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
1045 fSumw2.fArray[bin] = err2;
1046 }
1047 } else { // normal case of addition between histograms
1048 AddBinContent(bin, c1 * factor * h1->RetrieveBinContent(bin));
1049 if (fSumw2.fN) fSumw2.fArray[bin] += c1sq * factsq * h1->GetBinErrorSqUnchecked(bin);
1050 }
1051 }
1052
1053 // update statistics (do here to avoid changes by SetBinContent)
1054 if (resetStats) {
1055 // statistics need to be reset in case coefficient are negative
1056 ResetStats();
1057 }
1058 else {
1059 for (Int_t i=0;i<kNstat;i++) {
1060 if (i == 1) s1[i] += c1*c1*s2[i];
1061 else s1[i] += c1*s2[i];
1062 }
1063 PutStats(s1);
1064 SetEntries(entries);
1065 }
1066 return kTRUE;
1067}
1068
1069////////////////////////////////////////////////////////////////////////////////
1070/// Replace contents of this histogram by the addition of h1 and h2.
1071///
1072/// `this = c1*h1 + c2*h2`
1073/// if errors are defined (see TH1::Sumw2), errors are also recalculated
1074///
1075/// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
1076/// if not already set.
1077///
1078/// Note also that adding histogram with labels is not supported, histogram will be
1079/// added merging them by bin number independently of the labels.
1080/// For adding histogram ith labels one should use TH1::Merge
1081///
1082/// SPECIAL CASE (Average/Efficiency histograms)
1083/// For histograms representing averages or efficiencies, one should compute the average
1084/// of the two histograms and not the sum. One can mark a histogram to be an average
1085/// histogram by setting its bit kIsAverage with
1086/// myhist.SetBit(TH1::kIsAverage);
1087/// Note that the two histograms must have their kIsAverage bit set
1088///
1089/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
1090/// you should call Sumw2 before making this operation.
1091/// This is particularly important if you fit the histogram after TH1::Add
1092///
1093/// IMPORTANT NOTE2: You should be careful about the statistics of the
1094/// returned histogram, whose statistics may be binned or unbinned,
1095/// depending on whether c1 is negative, whether TAxis::kAxisRange is true,
1096/// and whether TH1::ResetStats has been called on either this or h1.
1097/// See TH1::GetStats.
1098///
1099/// ANOTHER SPECIAL CASE : h1 = h2 and c2 < 0
1100/// do a scaling this = c1 * h1 / (bin Volume)
1101///
1102/// The function returns kFALSE if the Add operation failed
1103
1105{
1106
1107 if (!h1 || !h2) {
1108 Error("Add","Attempt to add a non-existing histogram");
1109 return kFALSE;
1110 }
1111
1112 // delete buffer if it is there since it will become invalid
1113 if (fBuffer) BufferEmpty(1);
1114
1115 Bool_t normWidth = kFALSE;
1116 if (h1 == h2 && c2 < 0) {c2 = 0; normWidth = kTRUE;}
1117
1118 if (h1 != h2) {
1119 bool useMerge = false;
1120 const bool considerMerge = (c1 == 1. && c2 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
1121
1122 // We can combine inconsistencies like this, since they are ordered and a
1123 // higher inconsistency is worse
1124 auto const inconsistency = std::max(LoggedInconsistency("Add", this, h1, considerMerge),
1125 LoggedInconsistency("Add", h1, h2, considerMerge));
1126
1127 // If there is a bad inconsistency and we can't even consider merging, just give up
1128 if(inconsistency >= kDifferentNumberOfBins && !considerMerge) {
1129 return false;
1130 }
1131 // If there is an inconsistency, we try to use merging
1132 if(inconsistency > kFullyConsistent) {
1133 useMerge = considerMerge;
1134 }
1135
1136 if (useMerge) {
1137 TList l;
1138 // why TList takes non-const pointers ????
1139 l.Add(const_cast<TH1*>(h1));
1140 l.Add(const_cast<TH1*>(h2));
1141 Reset("ICE");
1142 auto iret = Merge(&l);
1143 return (iret >= 0);
1144 }
1145 }
1146
1147 // Create Sumw2 if h1 or h2 have Sumw2 set
1148 if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
1149
1150 // - Add statistics
1151 Double_t nEntries = TMath::Abs( c1*h1->GetEntries() + c2*h2->GetEntries() );
1152
1153 // TODO remove
1154 // statistics can be preserved only in case of positive coefficients
1155 // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
1156 // also in case of scaling with the width we cannot preserve the statistics
1157 Double_t s1[kNstat] = {0};
1158 Double_t s2[kNstat] = {0};
1159 Double_t s3[kNstat];
1160
1161
1162 Bool_t resetStats = (c1*c2 < 0) || normWidth;
1163 if (!resetStats) {
1164 // need to initialize to zero s1 and s2 since
1165 // GetStats fills only used elements depending on dimension and type
1166 h1->GetStats(s1);
1167 h2->GetStats(s2);
1168 for (Int_t i=0;i<kNstat;i++) {
1169 if (i == 1) s3[i] = c1*c1*s1[i] + c2*c2*s2[i];
1170 //else s3[i] = TMath::Abs(c1)*s1[i] + TMath::Abs(c2)*s2[i];
1171 else s3[i] = c1*s1[i] + c2*s2[i];
1172 }
1173 }
1174
1175 SetMinimum();
1176 SetMaximum();
1177
1178 if (normWidth) { // DEPRECATED CASE: belongs to fitting / drawing modules
1179
1180 Int_t nbinsx = GetNbinsX() + 2; // normal bins + underflow, overflow
1181 Int_t nbinsy = GetNbinsY() + 2;
1182 Int_t nbinsz = GetNbinsZ() + 2;
1183
1184 if (fDimension < 2) nbinsy = 1;
1185 if (fDimension < 3) nbinsz = 1;
1186
1187 Int_t bin, binx, biny, binz;
1188 for (binz = 0; binz < nbinsz; ++binz) {
1189 Double_t wz = h1->GetZaxis()->GetBinWidth(binz);
1190 for (biny = 0; biny < nbinsy; ++biny) {
1191 Double_t wy = h1->GetYaxis()->GetBinWidth(biny);
1192 for (binx = 0; binx < nbinsx; ++binx) {
1193 Double_t wx = h1->GetXaxis()->GetBinWidth(binx);
1194 bin = GetBin(binx, biny, binz);
1195 Double_t w = wx*wy*wz;
1196 UpdateBinContent(bin, c1 * h1->RetrieveBinContent(bin) / w);
1197 if (fSumw2.fN) {
1198 Double_t e1 = h1->GetBinError(bin)/w;
1199 fSumw2.fArray[bin] = c1*c1*e1*e1;
1200 }
1201 }
1202 }
1203 }
1204 } else if (h1->TestBit(kIsAverage) && h2->TestBit(kIsAverage)) {
1205 for (Int_t i = 0; i < fNcells; ++i) { // loop on cells (bins including underflow / overflow)
1206 // special case where histograms have the kIsAverage bit set
1208 Double_t y2 = h2->RetrieveBinContent(i);
1210 Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
1211 Double_t w1 = 1., w2 = 1.;
1212
1213 // consider all special cases when bin errors are zero
1214 // see http://root-forum.cern.ch/viewtopic.php?f=3&t=13299
1215 if (e1sq) w1 = 1./ e1sq;
1216 else if (h1->fSumw2.fN) {
1217 w1 = 1.E200; // use an arbitrary huge value
1218 if (y1 == 0 ) { // use an estimated error from the global histogram scale
1219 double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
1220 w1 = 1./(sf*sf);
1221 }
1222 }
1223 if (e2sq) w2 = 1./ e2sq;
1224 else if (h2->fSumw2.fN) {
1225 w2 = 1.E200; // use an arbitrary huge value
1226 if (y2 == 0) { // use an estimated error from the global histogram scale
1227 double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
1228 w2 = 1./(sf*sf);
1229 }
1230 }
1231
1232 double y = (w1*y1 + w2*y2)/(w1 + w2);
1233 UpdateBinContent(i, y);
1234 if (fSumw2.fN) {
1235 double err2 = 1./(w1 + w2);
1236 if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
1237 fSumw2.fArray[i] = err2;
1238 }
1239 }
1240 } else { // case of simple histogram addition
1241 Double_t c1sq = c1 * c1;
1242 Double_t c2sq = c2 * c2;
1243 for (Int_t i = 0; i < fNcells; ++i) { // Loop on cells (bins including underflows/overflows)
1244 UpdateBinContent(i, c1 * h1->RetrieveBinContent(i) + c2 * h2->RetrieveBinContent(i));
1245 if (fSumw2.fN) {
1246 fSumw2.fArray[i] = c1sq * h1->GetBinErrorSqUnchecked(i) + c2sq * h2->GetBinErrorSqUnchecked(i);
1247 }
1248 }
1249 }
1250
1251 if (resetStats) {
1252 // statistics need to be reset in case coefficient are negative
1253 ResetStats();
1254 }
1255 else {
1256 // update statistics (do here to avoid changes by SetBinContent) FIXME remove???
1257 PutStats(s3);
1258 SetEntries(nEntries);
1259 }
1260
1261 return kTRUE;
1262}
1263
1264////////////////////////////////////////////////////////////////////////////////
1265/// Increment bin content by 1.
1266/// Passing an out-of-range bin leads to undefined behavior
1267
1269{
1270 AbstractMethod("AddBinContent");
1271}
1272
1273////////////////////////////////////////////////////////////////////////////////
1274/// Increment bin content by a weight w.
1275/// Passing an out-of-range bin leads to undefined behavior
1276
1278{
1279 AbstractMethod("AddBinContent");
1280}
1281
1282////////////////////////////////////////////////////////////////////////////////
1283/// Sets the flag controlling the automatic add of histograms in memory
1284///
1285/// By default (fAddDirectory = kTRUE), histograms are automatically added
1286/// to the list of objects in memory.
1287/// Note that one histogram can be removed from its support directory
1288/// by calling h->SetDirectory(nullptr) or h->SetDirectory(dir) to add it
1289/// to the list of objects in the directory dir.
1290///
1291/// NOTE that this is a static function. To call it, use;
1292/// TH1::AddDirectory
1293
1295{
1296 fgAddDirectory = add;
1297}
1298
1299////////////////////////////////////////////////////////////////////////////////
1300/// Auxiliary function to get the power of 2 next (larger) or previous (smaller)
1301/// a given x
1302///
1303/// next = kTRUE : next larger
1304/// next = kFALSE : previous smaller
1305///
1306/// Used by the autobin power of 2 algorithm
1307
1309{
1310 Int_t nn;
1311 Double_t f2 = std::frexp(x, &nn);
1312 return ((next && x > 0.) || (!next && x <= 0.)) ? std::ldexp(std::copysign(1., f2), nn)
1313 : std::ldexp(std::copysign(1., f2), --nn);
1314}
1315
1316////////////////////////////////////////////////////////////////////////////////
1317/// Auxiliary function to get the next power of 2 integer value larger then n
1318///
1319/// Used by the autobin power of 2 algorithm
1320
1322{
1323 Int_t nn;
1324 Double_t f2 = std::frexp(n, &nn);
1325 if (TMath::Abs(f2 - .5) > 0.001)
1326 return (Int_t)std::ldexp(1., nn);
1327 return n;
1328}
1329
1330////////////////////////////////////////////////////////////////////////////////
1331/// Buffer-based estimate of the histogram range using the power of 2 algorithm.
1332///
1333/// Used by the autobin power of 2 algorithm.
1334///
1335/// Works on arguments (min and max from fBuffer) and internal inputs: fXmin,
1336/// fXmax, NBinsX (from fXaxis), ...
1337/// Result save internally in fXaxis.
1338///
1339/// Overloaded by TH2 and TH3.
1340///
1341/// Return -1 if internal inputs are inconsistent, 0 otherwise.
1342
1344{
1345 // We need meaningful raw limits
1346 if (xmi >= xma)
1347 return -1;
1348
1350 Double_t xhmi = fXaxis.GetXmin();
1351 Double_t xhma = fXaxis.GetXmax();
1352
1353 // Now adjust
1354 if (TMath::Abs(xhma) > TMath::Abs(xhmi)) {
1355 // Start from the upper limit
1356 xhma = TH1::AutoP2GetPower2(xhma);
1357 xhmi = xhma - TH1::AutoP2GetPower2(xhma - xhmi);
1358 } else {
1359 // Start from the lower limit
1360 xhmi = TH1::AutoP2GetPower2(xhmi, kFALSE);
1361 xhma = xhmi + TH1::AutoP2GetPower2(xhma - xhmi);
1362 }
1363
1364 // Round the bins to the next power of 2; take into account the possible inflation
1365 // of the range
1366 Double_t rr = (xhma - xhmi) / (xma - xmi);
1367 Int_t nb = TH1::AutoP2GetBins((Int_t)(rr * GetNbinsX()));
1368
1369 // Adjust using the same bin width and offsets
1370 Double_t bw = (xhma - xhmi) / nb;
1371 // Bins to left free on each side
1372 Double_t autoside = gEnv->GetValue("Hist.Binning.Auto.Side", 0.05);
1373 Int_t nbside = (Int_t)(nb * autoside);
1374
1375 // Side up
1376 Int_t nbup = (xhma - xma) / bw;
1377 if (nbup % 2 != 0)
1378 nbup++; // Must be even
1379 if (nbup != nbside) {
1380 // Accounts also for both case: larger or smaller
1381 xhma -= bw * (nbup - nbside);
1382 nb -= (nbup - nbside);
1383 }
1384
1385 // Side low
1386 Int_t nblw = (xmi - xhmi) / bw;
1387 if (nblw % 2 != 0)
1388 nblw++; // Must be even
1389 if (nblw != nbside) {
1390 // Accounts also for both case: larger or smaller
1391 xhmi += bw * (nblw - nbside);
1392 nb -= (nblw - nbside);
1393 }
1394
1395 // Set everything and project
1396 SetBins(nb, xhmi, xhma);
1397
1398 // Done
1399 return 0;
1400}
1401
1402/// Fill histogram with all entries in the buffer.
1403///
1404/// - action = -1 histogram is reset and refilled from the buffer (called by THistPainter::Paint)
1405/// - action = 0 histogram is reset and filled from the buffer. When the histogram is filled from the
1406/// buffer the value fBuffer[0] is set to a negative number (= - number of entries)
1407/// When calling with action == 0 the histogram is NOT refilled when fBuffer[0] is < 0
1408/// While when calling with action = -1 the histogram is reset and ALWAYS refilled independently if
1409/// the histogram was filled before. This is needed when drawing the histogram
1410/// - action = 1 histogram is filled and buffer is deleted
1411/// The buffer is automatically deleted when filling the histogram and the entries is
1412/// larger than the buffer size
1413
1415{
1416 // do we need to compute the bin size?
1417 if (!fBuffer) return 0;
1418 Int_t nbentries = (Int_t)fBuffer[0];
1419
1420 // nbentries correspond to the number of entries of histogram
1421
1422 if (nbentries == 0) {
1423 // if action is 1 we delete the buffer
1424 // this will avoid infinite recursion
1425 if (action > 0) {
1426 delete [] fBuffer;
1427 fBuffer = nullptr;
1428 fBufferSize = 0;
1429 }
1430 return 0;
1431 }
1432 if (nbentries < 0 && action == 0) return 0; // case histogram has been already filled from the buffer
1433
1434 Double_t *buffer = fBuffer;
1435 if (nbentries < 0) {
1436 nbentries = -nbentries;
1437 // a reset might call BufferEmpty() giving an infinite recursion
1438 // Protect it by setting fBuffer = nullptr
1439 fBuffer = nullptr;
1440 //do not reset the list of functions
1441 Reset("ICES");
1442 fBuffer = buffer;
1443 }
1444 if (CanExtendAllAxes() || (fXaxis.GetXmax() <= fXaxis.GetXmin())) {
1445 //find min, max of entries in buffer
1448 for (Int_t i=0;i<nbentries;i++) {
1449 Double_t x = fBuffer[2*i+2];
1450 // skip infinity or NaN values
1451 if (!std::isfinite(x)) continue;
1452 if (x < xmin) xmin = x;
1453 if (x > xmax) xmax = x;
1454 }
1455 if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
1456 Int_t rc = -1;
1458 if ((rc = AutoP2FindLimits(xmin, xmax)) < 0)
1459 Warning("BufferEmpty",
1460 "inconsistency found by power-of-2 autobin algorithm: fallback to standard method");
1461 }
1462 if (rc < 0)
1464 } else {
1465 fBuffer = nullptr;
1466 Int_t keep = fBufferSize; fBufferSize = 0;
1468 if (xmax >= fXaxis.GetXmax()) ExtendAxis(xmax, &fXaxis);
1469 fBuffer = buffer;
1470 fBufferSize = keep;
1471 }
1472 }
1473
1474 // call DoFillN which will not put entries in the buffer as FillN does
1475 // set fBuffer to zero to avoid re-emptying the buffer from functions called
1476 // by DoFillN (e.g Sumw2)
1477 buffer = fBuffer; fBuffer = nullptr;
1478 DoFillN(nbentries,&buffer[2],&buffer[1],2);
1479 fBuffer = buffer;
1480
1481 // if action == 1 - delete the buffer
1482 if (action > 0) {
1483 delete [] fBuffer;
1484 fBuffer = nullptr;
1485 fBufferSize = 0;
1486 } else {
1487 // if number of entries is consistent with buffer - set it negative to avoid
1488 // refilling the histogram every time BufferEmpty(0) is called
1489 // In case it is not consistent, by setting fBuffer[0]=0 is like resetting the buffer
1490 // (it will not be used anymore the next time BufferEmpty is called)
1491 if (nbentries == (Int_t)fEntries)
1492 fBuffer[0] = -nbentries;
1493 else
1494 fBuffer[0] = 0;
1495 }
1496 return nbentries;
1497}
1498
1499////////////////////////////////////////////////////////////////////////////////
1500/// accumulate arguments in buffer. When buffer is full, empty the buffer
1501///
1502/// - `fBuffer[0]` = number of entries in buffer
1503/// - `fBuffer[1]` = w of first entry
1504/// - `fBuffer[2]` = x of first entry
1505
1507{
1508 if (!fBuffer) return -2;
1509 Int_t nbentries = (Int_t)fBuffer[0];
1510
1511
1512 if (nbentries < 0) {
1513 // reset nbentries to a positive value so next time BufferEmpty() is called
1514 // the histogram will be refilled
1515 nbentries = -nbentries;
1516 fBuffer[0] = nbentries;
1517 if (fEntries > 0) {
1518 // set fBuffer to zero to avoid calling BufferEmpty in Reset
1519 Double_t *buffer = fBuffer; fBuffer=nullptr;
1520 Reset("ICES"); // do not reset list of functions
1521 fBuffer = buffer;
1522 }
1523 }
1524 if (2*nbentries+2 >= fBufferSize) {
1525 BufferEmpty(1);
1526 if (!fBuffer)
1527 // to avoid infinite recursion Fill->BufferFill->Fill
1528 return Fill(x,w);
1529 // this cannot happen
1530 R__ASSERT(0);
1531 }
1532 fBuffer[2*nbentries+1] = w;
1533 fBuffer[2*nbentries+2] = x;
1534 fBuffer[0] += 1;
1535 return -2;
1536}
1537
1538////////////////////////////////////////////////////////////////////////////////
1539/// Check bin limits.
1540
1541bool TH1::CheckBinLimits(const TAxis* a1, const TAxis * a2)
1542{
1543 const TArrayD * h1Array = a1->GetXbins();
1544 const TArrayD * h2Array = a2->GetXbins();
1545 Int_t fN = h1Array->fN;
1546 if ( fN != 0 ) {
1547 if ( h2Array->fN != fN ) {
1548 return false;
1549 }
1550 else {
1551 for ( int i = 0; i < fN; ++i ) {
1552 // for i==fN (nbin+1) a->GetBinWidth() returns last bin width
1553 // we do not need to exclude that case
1554 double binWidth = a1->GetBinWidth(i);
1555 if ( ! TMath::AreEqualAbs( h1Array->GetAt(i), h2Array->GetAt(i), binWidth*1E-10 ) ) {
1556 return false;
1557 }
1558 }
1559 }
1560 }
1561
1562 return true;
1563}
1564
1565////////////////////////////////////////////////////////////////////////////////
1566/// Check that axis have same labels.
1567
1568bool TH1::CheckBinLabels(const TAxis* a1, const TAxis * a2)
1569{
1570 THashList *l1 = a1->GetLabels();
1571 THashList *l2 = a2->GetLabels();
1572
1573 if (!l1 && !l2 )
1574 return true;
1575 if (!l1 || !l2 ) {
1576 return false;
1577 }
1578 // check now labels sizes are the same
1579 if (l1->GetSize() != l2->GetSize() ) {
1580 return false;
1581 }
1582 for (int i = 1; i <= a1->GetNbins(); ++i) {
1583 TString label1 = a1->GetBinLabel(i);
1584 TString label2 = a2->GetBinLabel(i);
1585 if (label1 != label2) {
1586 return false;
1587 }
1588 }
1589
1590 return true;
1591}
1592
1593////////////////////////////////////////////////////////////////////////////////
1594/// Check that the axis limits of the histograms are the same.
1595/// If a first and last bin is passed the axis is compared between the given range
1596
1597bool TH1::CheckAxisLimits(const TAxis *a1, const TAxis *a2 )
1598{
1599 double firstBin = a1->GetBinWidth(1);
1600 double lastBin = a1->GetBinWidth( a1->GetNbins() );
1601 if ( ! TMath::AreEqualAbs(a1->GetXmin(), a2->GetXmin(), firstBin* 1.E-10) ||
1602 ! TMath::AreEqualAbs(a1->GetXmax(), a2->GetXmax(), lastBin*1.E-10) ) {
1603 return false;
1604 }
1605 return true;
1606}
1607
1608////////////////////////////////////////////////////////////////////////////////
1609/// Check that the axis are the same
1610
1611bool TH1::CheckEqualAxes(const TAxis *a1, const TAxis *a2 )
1612{
1613 if (a1->GetNbins() != a2->GetNbins() ) {
1614 ::Info("CheckEqualAxes","Axes have different number of bins : nbin1 = %d nbin2 = %d",a1->GetNbins(),a2->GetNbins() );
1615 return false;
1616 }
1617 if(!CheckAxisLimits(a1,a2)) {
1618 ::Info("CheckEqualAxes","Axes have different limits");
1619 return false;
1620 }
1621 if(!CheckBinLimits(a1,a2)) {
1622 ::Info("CheckEqualAxes","Axes have different bin limits");
1623 return false;
1624 }
1625
1626 // check labels
1627 if(!CheckBinLabels(a1,a2)) {
1628 ::Info("CheckEqualAxes","Axes have different labels");
1629 return false;
1630 }
1631
1632 return true;
1633}
1634
1635////////////////////////////////////////////////////////////////////////////////
1636/// Check that two sub axis are the same.
1637/// The limits are defined by first bin and last bin
1638/// N.B. no check is done in this case for variable bins
1639
1640bool TH1::CheckConsistentSubAxes(const TAxis *a1, Int_t firstBin1, Int_t lastBin1, const TAxis * a2, Int_t firstBin2, Int_t lastBin2 )
1641{
1642 // By default is assumed that no bins are given for the second axis
1643 Int_t nbins1 = lastBin1-firstBin1 + 1;
1644 Double_t xmin1 = a1->GetBinLowEdge(firstBin1);
1645 Double_t xmax1 = a1->GetBinUpEdge(lastBin1);
1646
1647 Int_t nbins2 = a2->GetNbins();
1648 Double_t xmin2 = a2->GetXmin();
1649 Double_t xmax2 = a2->GetXmax();
1650
1651 if (firstBin2 < lastBin2) {
1652 // in this case assume no bins are given for the second axis
1653 nbins2 = lastBin1-firstBin1 + 1;
1654 xmin2 = a1->GetBinLowEdge(firstBin1);
1655 xmax2 = a1->GetBinUpEdge(lastBin1);
1656 }
1657
1658 if (nbins1 != nbins2 ) {
1659 ::Info("CheckConsistentSubAxes","Axes have different number of bins");
1660 return false;
1661 }
1662
1663 Double_t firstBin = a1->GetBinWidth(firstBin1);
1664 Double_t lastBin = a1->GetBinWidth(lastBin1);
1665 if ( ! TMath::AreEqualAbs(xmin1,xmin2,1.E-10 * firstBin) ||
1666 ! TMath::AreEqualAbs(xmax1,xmax2,1.E-10 * lastBin) ) {
1667 ::Info("CheckConsistentSubAxes","Axes have different limits");
1668 return false;
1669 }
1670
1671 return true;
1672}
1673
1674////////////////////////////////////////////////////////////////////////////////
1675/// Check histogram compatibility.
1676
1677int TH1::CheckConsistency(const TH1* h1, const TH1* h2)
1678{
1679 if (h1 == h2) return kFullyConsistent;
1680
1681 if (h1->GetDimension() != h2->GetDimension() ) {
1682 return kDifferentDimensions;
1683 }
1684 Int_t dim = h1->GetDimension();
1685
1686 // returns kTRUE if number of bins and bin limits are identical
1687 Int_t nbinsx = h1->GetNbinsX();
1688 Int_t nbinsy = h1->GetNbinsY();
1689 Int_t nbinsz = h1->GetNbinsZ();
1690
1691 // Check whether the histograms have the same number of bins.
1692 if (nbinsx != h2->GetNbinsX() ||
1693 (dim > 1 && nbinsy != h2->GetNbinsY()) ||
1694 (dim > 2 && nbinsz != h2->GetNbinsZ()) ) {
1695 return kDifferentNumberOfBins;
1696 }
1697
1698 bool ret = true;
1699
1700 // check axis limits
1701 ret &= CheckAxisLimits(h1->GetXaxis(), h2->GetXaxis());
1702 if (dim > 1) ret &= CheckAxisLimits(h1->GetYaxis(), h2->GetYaxis());
1703 if (dim > 2) ret &= CheckAxisLimits(h1->GetZaxis(), h2->GetZaxis());
1704 if (!ret) return kDifferentAxisLimits;
1705
1706 // check bin limits
1707 ret &= CheckBinLimits(h1->GetXaxis(), h2->GetXaxis());
1708 if (dim > 1) ret &= CheckBinLimits(h1->GetYaxis(), h2->GetYaxis());
1709 if (dim > 2) ret &= CheckBinLimits(h1->GetZaxis(), h2->GetZaxis());
1710 if (!ret) return kDifferentBinLimits;
1711
1712 // check labels if histograms are both not empty
1713 if ( !h1->IsEmpty() && !h2->IsEmpty() ) {
1714 ret &= CheckBinLabels(h1->GetXaxis(), h2->GetXaxis());
1715 if (dim > 1) ret &= CheckBinLabels(h1->GetYaxis(), h2->GetYaxis());
1716 if (dim > 2) ret &= CheckBinLabels(h1->GetZaxis(), h2->GetZaxis());
1717 if (!ret) return kDifferentLabels;
1718 }
1719
1720 return kFullyConsistent;
1721}
1722
1723////////////////////////////////////////////////////////////////////////////////
1724/// \f$ \chi^{2} \f$ test for comparing weighted and unweighted histograms.
1725///
1726/// Compares the histograms' adjusted (normalized) residuals.
1727/// Function: Returns p-value. Other return values are specified by the 3rd parameter
1728///
1729/// \param[in] h2 the second histogram
1730/// \param[in] option
1731/// - "UU" = experiment experiment comparison (unweighted-unweighted)
1732/// - "UW" = experiment MC comparison (unweighted-weighted). Note that
1733/// the first histogram should be unweighted
1734/// - "WW" = MC MC comparison (weighted-weighted)
1735/// - "NORM" = to be used when one or both of the histograms is scaled
1736/// but the histogram originally was unweighted
1737/// - by default underflows and overflows are not included:
1738/// * "OF" = overflows included
1739/// * "UF" = underflows included
1740/// - "P" = print chi2, ndf, p_value, igood
1741/// - "CHI2" = returns chi2 instead of p-value
1742/// - "CHI2/NDF" = returns \f$ \chi^{2} \f$/ndf
1743/// \param[in] res not empty - computes normalized residuals and returns them in this array
1744///
1745/// The current implementation is based on the papers \f$ \chi^{2} \f$ test for comparison
1746/// of weighted and unweighted histograms" in Proceedings of PHYSTAT05 and
1747/// "Comparison weighted and unweighted histograms", arXiv:physics/0605123
1748/// by N.Gagunashvili. This function has been implemented by Daniel Haertl in August 2006.
1749///
1750/// #### Introduction:
1751///
1752/// A frequently used technique in data analysis is the comparison of
1753/// histograms. First suggested by Pearson [1] the \f$ \chi^{2} \f$ test of
1754/// homogeneity is used widely for comparing usual (unweighted) histograms.
1755/// This paper describes the implementation modified \f$ \chi^{2} \f$ tests
1756/// for comparison of weighted and unweighted histograms and two weighted
1757/// histograms [2] as well as usual Pearson's \f$ \chi^{2} \f$ test for
1758/// comparison two usual (unweighted) histograms.
1759///
1760/// #### Overview:
1761///
1762/// Comparison of two histograms expect hypotheses that two histograms
1763/// represent identical distributions. To make a decision p-value should
1764/// be calculated. The hypotheses of identity is rejected if the p-value is
1765/// lower then some significance level. Traditionally significance levels
1766/// 0.1, 0.05 and 0.01 are used. The comparison procedure should include an
1767/// analysis of the residuals which is often helpful in identifying the
1768/// bins of histograms responsible for a significant overall \f$ \chi^{2} \f$ value.
1769/// Residuals are the difference between bin contents and expected bin
1770/// contents. Most convenient for analysis are the normalized residuals. If
1771/// hypotheses of identity are valid then normalized residuals are
1772/// approximately independent and identically distributed random variables
1773/// having N(0,1) distribution. Analysis of residuals expect test of above
1774/// mentioned properties of residuals. Notice that indirectly the analysis
1775/// of residuals increase the power of \f$ \chi^{2} \f$ test.
1776///
1777/// #### Methods of comparison:
1778///
1779/// \f$ \chi^{2} \f$ test for comparison two (unweighted) histograms:
1780/// Let us consider two histograms with the same binning and the number
1781/// of bins equal to r. Let us denote the number of events in the ith bin
1782/// in the first histogram as ni and as mi in the second one. The total
1783/// number of events in the first histogram is equal to:
1784/// \f[
1785/// N = \sum_{i=1}^{r} n_{i}
1786/// \f]
1787/// and
1788/// \f[
1789/// M = \sum_{i=1}^{r} m_{i}
1790/// \f]
1791/// in the second histogram. The hypothesis of identity (homogeneity) [3]
1792/// is that the two histograms represent random values with identical
1793/// distributions. It is equivalent that there exist r constants p1,...,pr,
1794/// such that
1795/// \f[
1796///\sum_{i=1}^{r} p_{i}=1
1797/// \f]
1798/// and the probability of belonging to the ith bin for some measured value
1799/// in both experiments is equal to pi. The number of events in the ith
1800/// bin is a random variable with a distribution approximated by a Poisson
1801/// probability distribution
1802/// \f[
1803///\frac{e^{-Np_{i}}(Np_{i})^{n_{i}}}{n_{i}!}
1804/// \f]
1805///for the first histogram and with distribution
1806/// \f[
1807///\frac{e^{-Mp_{i}}(Mp_{i})^{m_{i}}}{m_{i}!}
1808/// \f]
1809/// for the second histogram. If the hypothesis of homogeneity is valid,
1810/// then the maximum likelihood estimator of pi, i=1,...,r, is
1811/// \f[
1812///\hat{p}_{i}= \frac{n_{i}+m_{i}}{N+M}
1813/// \f]
1814/// and then
1815/// \f[
1816/// 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}}
1817/// \f]
1818/// has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [3].
1819/// The comparison procedure can include an analysis of the residuals which
1820/// is often helpful in identifying the bins of histograms responsible for
1821/// a significant overall \f$ \chi^{2} \f$ value. Most convenient for
1822/// analysis are the adjusted (normalized) residuals [4]
1823/// \f[
1824/// 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))}}
1825/// \f]
1826/// If hypotheses of homogeneity are valid then residuals ri are
1827/// approximately independent and identically distributed random variables
1828/// having N(0,1) distribution. The application of the \f$ \chi^{2} \f$ test has
1829/// restrictions related to the value of the expected frequencies Npi,
1830/// Mpi, i=1,...,r. A conservative rule formulated in [5] is that all the
1831/// expectations must be 1 or greater for both histograms. In practical
1832/// cases when expected frequencies are not known the estimated expected
1833/// frequencies \f$ M\hat{p}_{i}, N\hat{p}_{i}, i=1,...,r \f$ can be used.
1834///
1835/// #### Unweighted and weighted histograms comparison:
1836///
1837/// A simple modification of the ideas described above can be used for the
1838/// comparison of the usual (unweighted) and weighted histograms. Let us
1839/// denote the number of events in the ith bin in the unweighted
1840/// histogram as ni and the common weight of events in the ith bin of the
1841/// weighted histogram as wi. The total number of events in the
1842/// unweighted histogram is equal to
1843///\f[
1844/// N = \sum_{i=1}^{r} n_{i}
1845///\f]
1846/// and the total weight of events in the weighted histogram is equal to
1847///\f[
1848/// W = \sum_{i=1}^{r} w_{i}
1849///\f]
1850/// Let us formulate the hypothesis of identity of an unweighted histogram
1851/// to a weighted histogram so that there exist r constants p1,...,pr, such
1852/// that
1853///\f[
1854/// \sum_{i=1}^{r} p_{i} = 1
1855///\f]
1856/// for the unweighted histogram. The weight wi is a random variable with a
1857/// distribution approximated by the normal probability distribution
1858/// \f$ N(Wp_{i},\sigma_{i}^{2}) \f$ where \f$ \sigma_{i}^{2} \f$ is the variance of the weight wi.
1859/// If we replace the variance \f$ \sigma_{i}^{2} \f$
1860/// with estimate \f$ s_{i}^{2} \f$ (sum of squares of weights of
1861/// events in the ith bin) and the hypothesis of identity is valid, then the
1862/// maximum likelihood estimator of pi,i=1,...,r, is
1863///\f[
1864/// \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}}
1865///\f]
1866/// We may then use the test statistic
1867///\f[
1868/// 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}}
1869///\f]
1870/// and it has approximately a \f$ \sigma^{2}_{(r-1)} \f$ distribution [2]. This test, as well
1871/// as the original one [3], has a restriction on the expected frequencies. The
1872/// expected frequencies recommended for the weighted histogram is more than 25.
1873/// The value of the minimal expected frequency can be decreased down to 10 for
1874/// the case when the weights of the events are close to constant. In the case
1875/// of a weighted histogram if the number of events is unknown, then we can
1876/// apply this recommendation for the equivalent number of events as
1877///\f[
1878/// n_{i}^{equiv} = \frac{ w_{i}^{2} }{ s_{i}^{2} }
1879///\f]
1880/// The minimal expected frequency for an unweighted histogram must be 1. Notice
1881/// that any usual (unweighted) histogram can be considered as a weighted
1882/// histogram with events that have constant weights equal to 1.
1883/// The variance \f$ z_{i}^{2} \f$ of the difference between the weight wi
1884/// and the estimated expectation value of the weight is approximately equal to:
1885///\f[
1886/// 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}
1887///\f]
1888/// The residuals
1889///\f[
1890/// r_{i} = \frac{w_{i}-W\hat{p}_{i}}{z_{i}}
1891///\f]
1892/// have approximately a normal distribution with mean equal to 0 and standard
1893/// deviation equal to 1.
1894///
1895/// #### Two weighted histograms comparison:
1896///
1897/// Let us denote the common weight of events of the ith bin in the first
1898/// histogram as w1i and as w2i in the second one. The total weight of events
1899/// in the first histogram is equal to
1900///\f[
1901/// W_{1} = \sum_{i=1}^{r} w_{1i}
1902///\f]
1903/// and
1904///\f[
1905/// W_{2} = \sum_{i=1}^{r} w_{2i}
1906///\f]
1907/// in the second histogram. Let us formulate the hypothesis of identity of
1908/// weighted histograms so that there exist r constants p1,...,pr, such that
1909///\f[
1910/// \sum_{i=1}^{r} p_{i} = 1
1911///\f]
1912/// and also expectation value of weight w1i equal to W1pi and expectation value
1913/// of weight w2i equal to W2pi. Weights in both the histograms are random
1914/// variables with distributions which can be approximated by a normal
1915/// probability distribution \f$ N(W_{1}p_{i},\sigma_{1i}^{2}) \f$ for the first histogram
1916/// and by a distribution \f$ N(W_{2}p_{i},\sigma_{2i}^{2}) \f$ for the second.
1917/// Here \f$ \sigma_{1i}^{2} \f$ and \f$ \sigma_{2i}^{2} \f$ are the variances
1918/// of w1i and w2i with estimators \f$ s_{1i}^{2} \f$ and \f$ s_{2i}^{2} \f$ respectively.
1919/// If the hypothesis of identity is valid, then the maximum likelihood and
1920/// Least Square Method estimator of pi,i=1,...,r, is
1921///\f[
1922/// \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}}
1923///\f]
1924/// We may then use the test statistic
1925///\f[
1926/// 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}}
1927///\f]
1928/// and it has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [2].
1929/// The normalized or studentised residuals [6]
1930///\f[
1931/// 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})}}}
1932///\f]
1933/// have approximately a normal distribution with mean equal to 0 and standard
1934/// deviation 1. A recommended minimal expected frequency is equal to 10 for
1935/// the proposed test.
1936///
1937/// #### Numerical examples:
1938///
1939/// The method described herein is now illustrated with an example.
1940/// We take a distribution
1941///\f[
1942/// \phi(x) = \frac{2}{(x-10)^{2}+1} + \frac{1}{(x-14)^{2}+1} (1)
1943///\f]
1944/// defined on the interval [4,16]. Events distributed according to the formula
1945/// (1) are simulated to create the unweighted histogram. Uniformly distributed
1946/// events are simulated for the weighted histogram with weights calculated by
1947/// formula (1). Each histogram has the same number of bins: 20. Fig.1 shows
1948/// the result of comparison of the unweighted histogram with 200 events
1949/// (minimal expected frequency equal to one) and the weighted histogram with
1950/// 500 events (minimal expected frequency equal to 25)
1951/// Begin_Macro
1952/// ../../../tutorials/math/chi2test.C
1953/// End_Macro
1954/// Fig 1. An example of comparison of the unweighted histogram with 200 events
1955/// and the weighted histogram with 500 events:
1956/// 1. unweighted histogram;
1957/// 2. weighted histogram;
1958/// 3. normalized residuals plot;
1959/// 4. normal Q-Q plot of residuals.
1960///
1961/// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1962/// 21.09 with p-value equal to 0.33, therefore the hypothesis of identity of
1963/// the two histograms can be accepted for 0.05 significant level. The behavior
1964/// of the normalized residuals plot (see Fig. 1c) and the normal Q-Q plot
1965/// (see Fig. 1d) of residuals are regular and we cannot identify the outliers
1966/// or bins with a big influence on \f$ \chi^{2} \f$.
1967///
1968/// The second example presents the same two histograms but 17 events was added
1969/// to content of bin number 15 in unweighted histogram. Fig.2 shows the result
1970/// of comparison of the unweighted histogram with 217 events (minimal expected
1971/// frequency equal to one) and the weighted histogram with 500 events (minimal
1972/// expected frequency equal to 25)
1973/// Begin_Macro
1974/// ../../../tutorials/math/chi2test.C(17)
1975/// End_Macro
1976/// Fig 2. An example of comparison of the unweighted histogram with 217 events
1977/// and the weighted histogram with 500 events:
1978/// 1. unweighted histogram;
1979/// 2. weighted histogram;
1980/// 3. normalized residuals plot;
1981/// 4. normal Q-Q plot of residuals.
1982///
1983/// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1984/// 32.33 with p-value equal to 0.029, therefore the hypothesis of identity of
1985/// the two histograms is rejected for 0.05 significant level. The behavior of
1986/// the normalized residuals plot (see Fig. 2c) and the normal Q-Q plot (see
1987/// Fig. 2d) of residuals are not regular and we can identify the outlier or
1988/// bin with a big influence on \f$ \chi^{2} \f$.
1989///
1990/// #### References:
1991///
1992/// - [1] Pearson, K., 1904. On the Theory of Contingency and Its Relation to
1993/// Association and Normal Correlation. Drapers' Co. Memoirs, Biometric
1994/// Series No. 1, London.
1995/// - [2] Gagunashvili, N., 2006. \f$ \sigma^{2} \f$ test for comparison
1996/// of weighted and unweighted histograms. Statistical Problems in Particle
1997/// Physics, Astrophysics and Cosmology, Proceedings of PHYSTAT05,
1998/// Oxford, UK, 12-15 September 2005, Imperial College Press, London, 43-44.
1999/// Gagunashvili,N., Comparison of weighted and unweighted histograms,
2000/// arXiv:physics/0605123, 2006.
2001/// - [3] Cramer, H., 1946. Mathematical methods of statistics.
2002/// Princeton University Press, Princeton.
2003/// - [4] Haberman, S.J., 1973. The analysis of residuals in cross-classified tables.
2004/// Biometrics 29, 205-220.
2005/// - [5] Lewontin, R.C. and Felsenstein, J., 1965. The robustness of homogeneity
2006/// test in 2xN tables. Biometrics 21, 19-33.
2007/// - [6] Seber, G.A.F., Lee, A.J., 2003, Linear Regression Analysis.
2008/// John Wiley & Sons Inc., New York.
2009
2010Double_t TH1::Chi2Test(const TH1* h2, Option_t *option, Double_t *res) const
2011{
2012 Double_t chi2 = 0;
2013 Int_t ndf = 0, igood = 0;
2014
2015 TString opt = option;
2016 opt.ToUpper();
2017
2018 Double_t prob = Chi2TestX(h2,chi2,ndf,igood,option,res);
2019
2020 if(opt.Contains("P")) {
2021 printf("Chi2 = %f, Prob = %g, NDF = %d, igood = %d\n", chi2,prob,ndf,igood);
2022 }
2023 if(opt.Contains("CHI2/NDF")) {
2024 if (ndf == 0) return 0;
2025 return chi2/ndf;
2026 }
2027 if(opt.Contains("CHI2")) {
2028 return chi2;
2029 }
2030
2031 return prob;
2032}
2033
2034////////////////////////////////////////////////////////////////////////////////
2035/// The computation routine of the Chisquare test. For the method description,
2036/// see Chi2Test() function.
2037///
2038/// \return p-value
2039/// \param[in] h2 the second histogram
2040/// \param[in] option
2041/// - "UU" = experiment experiment comparison (unweighted-unweighted)
2042/// - "UW" = experiment MC comparison (unweighted-weighted). Note that the first
2043/// histogram should be unweighted
2044/// - "WW" = MC MC comparison (weighted-weighted)
2045/// - "NORM" = if one or both histograms is scaled
2046/// - "OF" = overflows included
2047/// - "UF" = underflows included
2048/// by default underflows and overflows are not included
2049/// \param[out] igood test output
2050/// - igood=0 - no problems
2051/// - For unweighted unweighted comparison
2052/// - igood=1'There is a bin in the 1st histogram with less than 1 event'
2053/// - igood=2'There is a bin in the 2nd histogram with less than 1 event'
2054/// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
2055/// - For unweighted weighted comparison
2056/// - igood=1'There is a bin in the 1st histogram with less then 1 event'
2057/// - igood=2'There is a bin in the 2nd histogram with less then 10 effective number of events'
2058/// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
2059/// - For weighted weighted comparison
2060/// - igood=1'There is a bin in the 1st histogram with less then 10 effective
2061/// number of events'
2062/// - igood=2'There is a bin in the 2nd histogram with less then 10 effective
2063/// number of events'
2064/// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
2065/// \param[out] chi2 chisquare of the test
2066/// \param[out] ndf number of degrees of freedom (important, when both histograms have the same empty bins)
2067/// \param[out] res normalized residuals for further analysis
2068
2069Double_t TH1::Chi2TestX(const TH1* h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option, Double_t *res) const
2070{
2071
2072 Int_t i_start, i_end;
2073 Int_t j_start, j_end;
2074 Int_t k_start, k_end;
2075
2076 Double_t sum1 = 0.0, sumw1 = 0.0;
2077 Double_t sum2 = 0.0, sumw2 = 0.0;
2078
2079 chi2 = 0.0;
2080 ndf = 0;
2081
2082 TString opt = option;
2083 opt.ToUpper();
2084
2085 if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
2086
2087 const TAxis *xaxis1 = GetXaxis();
2088 const TAxis *xaxis2 = h2->GetXaxis();
2089 const TAxis *yaxis1 = GetYaxis();
2090 const TAxis *yaxis2 = h2->GetYaxis();
2091 const TAxis *zaxis1 = GetZaxis();
2092 const TAxis *zaxis2 = h2->GetZaxis();
2093
2094 Int_t nbinx1 = xaxis1->GetNbins();
2095 Int_t nbinx2 = xaxis2->GetNbins();
2096 Int_t nbiny1 = yaxis1->GetNbins();
2097 Int_t nbiny2 = yaxis2->GetNbins();
2098 Int_t nbinz1 = zaxis1->GetNbins();
2099 Int_t nbinz2 = zaxis2->GetNbins();
2100
2101 //check dimensions
2102 if (this->GetDimension() != h2->GetDimension() ){
2103 Error("Chi2TestX","Histograms have different dimensions.");
2104 return 0.0;
2105 }
2106
2107 //check number of channels
2108 if (nbinx1 != nbinx2) {
2109 Error("Chi2TestX","different number of x channels");
2110 }
2111 if (nbiny1 != nbiny2) {
2112 Error("Chi2TestX","different number of y channels");
2113 }
2114 if (nbinz1 != nbinz2) {
2115 Error("Chi2TestX","different number of z channels");
2116 }
2117
2118 //check for ranges
2119 i_start = j_start = k_start = 1;
2120 i_end = nbinx1;
2121 j_end = nbiny1;
2122 k_end = nbinz1;
2123
2124 if (xaxis1->TestBit(TAxis::kAxisRange)) {
2125 i_start = xaxis1->GetFirst();
2126 i_end = xaxis1->GetLast();
2127 }
2128 if (yaxis1->TestBit(TAxis::kAxisRange)) {
2129 j_start = yaxis1->GetFirst();
2130 j_end = yaxis1->GetLast();
2131 }
2132 if (zaxis1->TestBit(TAxis::kAxisRange)) {
2133 k_start = zaxis1->GetFirst();
2134 k_end = zaxis1->GetLast();
2135 }
2136
2137
2138 if (opt.Contains("OF")) {
2139 if (GetDimension() == 3) k_end = ++nbinz1;
2140 if (GetDimension() >= 2) j_end = ++nbiny1;
2141 if (GetDimension() >= 1) i_end = ++nbinx1;
2142 }
2143
2144 if (opt.Contains("UF")) {
2145 if (GetDimension() == 3) k_start = 0;
2146 if (GetDimension() >= 2) j_start = 0;
2147 if (GetDimension() >= 1) i_start = 0;
2148 }
2149
2150 ndf = (i_end - i_start + 1) * (j_end - j_start + 1) * (k_end - k_start + 1) - 1;
2151
2152 Bool_t comparisonUU = opt.Contains("UU");
2153 Bool_t comparisonUW = opt.Contains("UW");
2154 Bool_t comparisonWW = opt.Contains("WW");
2155 Bool_t scaledHistogram = opt.Contains("NORM");
2156
2157 if (scaledHistogram && !comparisonUU) {
2158 Info("Chi2TestX", "NORM option should be used together with UU option. It is ignored");
2159 }
2160
2161 // look at histo global bin content and effective entries
2162 Stat_t s[kNstat];
2163 GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
2164 Double_t sumBinContent1 = s[0];
2165 Double_t effEntries1 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
2166
2167 h2->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
2168 Double_t sumBinContent2 = s[0];
2169 Double_t effEntries2 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
2170
2171 if (!comparisonUU && !comparisonUW && !comparisonWW ) {
2172 // deduce automatically from type of histogram
2173 if (TMath::Abs(sumBinContent1 - effEntries1) < 1) {
2174 if ( TMath::Abs(sumBinContent2 - effEntries2) < 1) comparisonUU = true;
2175 else comparisonUW = true;
2176 }
2177 else comparisonWW = true;
2178 }
2179 // check unweighted histogram
2180 if (comparisonUW) {
2181 if (TMath::Abs(sumBinContent1 - effEntries1) >= 1) {
2182 Warning("Chi2TestX","First histogram is not unweighted and option UW has been requested");
2183 }
2184 }
2185 if ( (!scaledHistogram && comparisonUU) ) {
2186 if ( ( TMath::Abs(sumBinContent1 - effEntries1) >= 1) || (TMath::Abs(sumBinContent2 - effEntries2) >= 1) ) {
2187 Warning("Chi2TestX","Both histograms are not unweighted and option UU has been requested");
2188 }
2189 }
2190
2191
2192 //get number of events in histogram
2193 if (comparisonUU && scaledHistogram) {
2194 for (Int_t i = i_start; i <= i_end; ++i) {
2195 for (Int_t j = j_start; j <= j_end; ++j) {
2196 for (Int_t k = k_start; k <= k_end; ++k) {
2197
2198 Int_t bin = GetBin(i, j, k);
2199
2200 Double_t cnt1 = RetrieveBinContent(bin);
2201 Double_t cnt2 = h2->RetrieveBinContent(bin);
2202 Double_t e1sq = GetBinErrorSqUnchecked(bin);
2203 Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2204
2205 if (e1sq > 0.0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2206 else cnt1 = 0.0;
2207
2208 if (e2sq > 0.0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2209 else cnt2 = 0.0;
2210
2211 // sum contents
2212 sum1 += cnt1;
2213 sum2 += cnt2;
2214 sumw1 += e1sq;
2215 sumw2 += e2sq;
2216 }
2217 }
2218 }
2219 if (sumw1 <= 0.0 || sumw2 <= 0.0) {
2220 Error("Chi2TestX", "Cannot use option NORM when one histogram has all zero errors");
2221 return 0.0;
2222 }
2223
2224 } else {
2225 for (Int_t i = i_start; i <= i_end; ++i) {
2226 for (Int_t j = j_start; j <= j_end; ++j) {
2227 for (Int_t k = k_start; k <= k_end; ++k) {
2228
2229 Int_t bin = GetBin(i, j, k);
2230
2231 sum1 += RetrieveBinContent(bin);
2232 sum2 += h2->RetrieveBinContent(bin);
2233
2234 if ( comparisonWW ) sumw1 += GetBinErrorSqUnchecked(bin);
2235 if ( comparisonUW || comparisonWW ) sumw2 += h2->GetBinErrorSqUnchecked(bin);
2236 }
2237 }
2238 }
2239 }
2240 //checks that the histograms are not empty
2241 if (sum1 == 0.0 || sum2 == 0.0) {
2242 Error("Chi2TestX","one histogram is empty");
2243 return 0.0;
2244 }
2245
2246 if ( comparisonWW && ( sumw1 <= 0.0 && sumw2 <= 0.0 ) ){
2247 Error("Chi2TestX","Hist1 and Hist2 have both all zero errors\n");
2248 return 0.0;
2249 }
2250
2251 //THE TEST
2252 Int_t m = 0, n = 0;
2253
2254 //Experiment - experiment comparison
2255 if (comparisonUU) {
2256 Double_t sum = sum1 + sum2;
2257 for (Int_t i = i_start; i <= i_end; ++i) {
2258 for (Int_t j = j_start; j <= j_end; ++j) {
2259 for (Int_t k = k_start; k <= k_end; ++k) {
2260
2261 Int_t bin = GetBin(i, j, k);
2262
2263 Double_t cnt1 = RetrieveBinContent(bin);
2264 Double_t cnt2 = h2->RetrieveBinContent(bin);
2265
2266 if (scaledHistogram) {
2267 // scale bin value to effective bin entries
2268 Double_t e1sq = GetBinErrorSqUnchecked(bin);
2269 Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2270
2271 if (e1sq > 0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2272 else cnt1 = 0;
2273
2274 if (e2sq > 0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2275 else cnt2 = 0;
2276 }
2277
2278 if (Int_t(cnt1) == 0 && Int_t(cnt2) == 0) --ndf; // no data means one degree of freedom less
2279 else {
2280
2281 Double_t cntsum = cnt1 + cnt2;
2282 Double_t nexp1 = cntsum * sum1 / sum;
2283 //Double_t nexp2 = binsum*sum2/sum;
2284
2285 if (res) res[i - i_start] = (cnt1 - nexp1) / TMath::Sqrt(nexp1);
2286
2287 if (cnt1 < 1) ++m;
2288 if (cnt2 < 1) ++n;
2289
2290 //Habermann correction for residuals
2291 Double_t correc = (1. - sum1 / sum) * (1. - cntsum / sum);
2292 if (res) res[i - i_start] /= TMath::Sqrt(correc);
2293
2294 Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2295 chi2 += delta * delta / cntsum;
2296 }
2297 }
2298 }
2299 }
2300 chi2 /= sum1 * sum2;
2301
2302 // flag error only when of the two histogram is zero
2303 if (m) {
2304 igood += 1;
2305 Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2306 }
2307 if (n) {
2308 igood += 2;
2309 Info("Chi2TestX","There is a bin in h2 with less than 1 event.\n");
2310 }
2311
2312 Double_t prob = TMath::Prob(chi2,ndf);
2313 return prob;
2314
2315 }
2316
2317 // unweighted - weighted comparison
2318 // case of error = 0 and content not zero is treated without problems by excluding second chi2 sum
2319 // and can be considered as a data-theory comparison
2320 if ( comparisonUW ) {
2321 for (Int_t i = i_start; i <= i_end; ++i) {
2322 for (Int_t j = j_start; j <= j_end; ++j) {
2323 for (Int_t k = k_start; k <= k_end; ++k) {
2324
2325 Int_t bin = GetBin(i, j, k);
2326
2327 Double_t cnt1 = RetrieveBinContent(bin);
2328 Double_t cnt2 = h2->RetrieveBinContent(bin);
2329 Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2330
2331 // case both histogram have zero bin contents
2332 if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2333 --ndf; //no data means one degree of freedom less
2334 continue;
2335 }
2336
2337 // case weighted histogram has zero bin content and error
2338 if (cnt2 * cnt2 == 0 && e2sq == 0) {
2339 if (sumw2 > 0) {
2340 // use as approximated error as 1 scaled by a scaling ratio
2341 // estimated from the total sum weight and sum weight squared
2342 e2sq = sumw2 / sum2;
2343 }
2344 else {
2345 // return error because infinite discrepancy here:
2346 // bin1 != 0 and bin2 =0 in a histogram with all errors zero
2347 Error("Chi2TestX","Hist2 has in bin (%d,%d,%d) zero content and zero errors\n", i, j, k);
2348 chi2 = 0; return 0;
2349 }
2350 }
2351
2352 if (cnt1 < 1) m++;
2353 if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2354
2355 Double_t var1 = sum2 * cnt2 - sum1 * e2sq;
2356 Double_t var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2357
2358 // if cnt1 is zero and cnt2 = 1 and sum1 = sum2 var1 = 0 && var2 == 0
2359 // approximate by incrementing cnt1
2360 // LM (this need to be fixed for numerical errors)
2361 while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2362 sum1++;
2363 cnt1++;
2364 var1 = sum2 * cnt2 - sum1 * e2sq;
2365 var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2366 }
2367 var2 = TMath::Sqrt(var2);
2368
2369 while (var1 + var2 == 0) {
2370 sum1++;
2371 cnt1++;
2372 var1 = sum2 * cnt2 - sum1 * e2sq;
2373 var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2374 while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2375 sum1++;
2376 cnt1++;
2377 var1 = sum2 * cnt2 - sum1 * e2sq;
2378 var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2379 }
2380 var2 = TMath::Sqrt(var2);
2381 }
2382
2383 Double_t probb = (var1 + var2) / (2. * sum2 * sum2);
2384
2385 Double_t nexp1 = probb * sum1;
2386 Double_t nexp2 = probb * sum2;
2387
2388 Double_t delta1 = cnt1 - nexp1;
2389 Double_t delta2 = cnt2 - nexp2;
2390
2391 chi2 += delta1 * delta1 / nexp1;
2392
2393 if (e2sq > 0) {
2394 chi2 += delta2 * delta2 / e2sq;
2395 }
2396
2397 if (res) {
2398 if (e2sq > 0) {
2399 Double_t temp1 = sum2 * e2sq / var2;
2400 Double_t temp2 = 1.0 + (sum1 * e2sq - sum2 * cnt2) / var2;
2401 temp2 = temp1 * temp1 * sum1 * probb * (1.0 - probb) + temp2 * temp2 * e2sq / 4.0;
2402 // invert sign here
2403 res[i - i_start] = - delta2 / TMath::Sqrt(temp2);
2404 }
2405 else
2406 res[i - i_start] = delta1 / TMath::Sqrt(nexp1);
2407 }
2408 }
2409 }
2410 }
2411
2412 if (m) {
2413 igood += 1;
2414 Info("Chi2TestX","There is a bin in h1 with less than 1 event.\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
2421 Double_t prob = TMath::Prob(chi2, ndf);
2422
2423 return prob;
2424 }
2425
2426 // weighted - weighted comparison
2427 if (comparisonWW) {
2428 for (Int_t i = i_start; i <= i_end; ++i) {
2429 for (Int_t j = j_start; j <= j_end; ++j) {
2430 for (Int_t k = k_start; k <= k_end; ++k) {
2431
2432 Int_t bin = GetBin(i, j, k);
2433 Double_t cnt1 = RetrieveBinContent(bin);
2434 Double_t cnt2 = h2->RetrieveBinContent(bin);
2435 Double_t e1sq = GetBinErrorSqUnchecked(bin);
2436 Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2437
2438 // case both histogram have zero bin contents
2439 // (use square of content to avoid numerical errors)
2440 if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2441 --ndf; //no data means one degree of freedom less
2442 continue;
2443 }
2444
2445 if (e1sq == 0 && e2sq == 0) {
2446 // cannot treat case of booth histogram have zero zero errors
2447 Error("Chi2TestX","h1 and h2 both have bin %d,%d,%d with all zero errors\n", i,j,k);
2448 chi2 = 0; return 0;
2449 }
2450
2451 Double_t sigma = sum1 * sum1 * e2sq + sum2 * sum2 * e1sq;
2452 Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2453 chi2 += delta * delta / sigma;
2454
2455 if (res) {
2456 Double_t temp = cnt1 * sum1 * e2sq + cnt2 * sum2 * e1sq;
2457 Double_t probb = temp / sigma;
2458 Double_t z = 0;
2459 if (e1sq > e2sq) {
2460 Double_t d1 = cnt1 - sum1 * probb;
2461 Double_t s1 = e1sq * ( 1. - e2sq * sum1 * sum1 / sigma );
2462 z = d1 / TMath::Sqrt(s1);
2463 }
2464 else {
2465 Double_t d2 = cnt2 - sum2 * probb;
2466 Double_t s2 = e2sq * ( 1. - e1sq * sum2 * sum2 / sigma );
2467 z = -d2 / TMath::Sqrt(s2);
2468 }
2469 res[i - i_start] = z;
2470 }
2471
2472 if (e1sq > 0 && cnt1 * cnt1 / e1sq < 10) m++;
2473 if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2474 }
2475 }
2476 }
2477 if (m) {
2478 igood += 1;
2479 Info("Chi2TestX","There is a bin in h1 with less than 10 effective events.\n");
2480 }
2481 if (n) {
2482 igood += 2;
2483 Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2484 }
2485 Double_t prob = TMath::Prob(chi2, ndf);
2486 return prob;
2487 }
2488 return 0;
2489}
2490////////////////////////////////////////////////////////////////////////////////
2491/// Compute and return the chisquare of this histogram with respect to a function
2492/// The chisquare is computed by weighting each histogram point by the bin error
2493/// By default the full range of the histogram is used.
2494/// Use option "R" for restricting the chisquare calculation to the given range of the function
2495/// Use option "L" for using the chisquare based on the poisson likelihood (Baker-Cousins Chisquare)
2496/// Use option "P" for using the Pearson chisquare based on the expected bin errors
2497
2499{
2500 if (!func) {
2501 Error("Chisquare","Function pointer is Null - return -1");
2502 return -1;
2503 }
2504
2505 TString opt(option); opt.ToUpper();
2506 bool useRange = opt.Contains("R");
2507 ROOT::Fit::EChisquareType type = ROOT::Fit::EChisquareType::kNeyman; // default chi2 with observed error
2510
2511 return ROOT::Fit::Chisquare(*this, *func, useRange, type);
2512}
2513
2514////////////////////////////////////////////////////////////////////////////////
2515/// Remove all the content from the underflow and overflow bins, without changing the number of entries
2516/// After calling this method, every undeflow and overflow bins will have content 0.0
2517/// The Sumw2 is also cleared, since there is no more content in the bins
2518
2520{
2521 for (Int_t bin = 0; bin < fNcells; ++bin)
2522 if (IsBinUnderflow(bin) || IsBinOverflow(bin)) {
2523 UpdateBinContent(bin, 0.0);
2524 if (fSumw2.fN) fSumw2.fArray[bin] = 0.0;
2525 }
2526}
2527
2528////////////////////////////////////////////////////////////////////////////////
2529/// Compute integral (normalized cumulative sum of bins) w/o under/overflows
2530/// The result is stored in fIntegral and used by the GetRandom functions.
2531/// This function is automatically called by GetRandom when the fIntegral
2532/// array does not exist or when the number of entries in the histogram
2533/// has changed since the previous call to GetRandom.
2534/// The resulting integral is normalized to 1.
2535/// If the routine is called with the onlyPositive flag set an error will
2536/// be produced in case of negative bin content and a NaN value returned
2537/// \return 1 if success, 0 if integral is zero, NAN if onlyPositive-test fails
2538
2540{
2541 if (fBuffer) BufferEmpty();
2542
2543 // delete previously computed integral (if any)
2544 if (fIntegral) delete [] fIntegral;
2545
2546 // - Allocate space to store the integral and compute integral
2547 Int_t nbinsx = GetNbinsX();
2548 Int_t nbinsy = GetNbinsY();
2549 Int_t nbinsz = GetNbinsZ();
2550 Int_t nbins = nbinsx * nbinsy * nbinsz;
2551
2552 fIntegral = new Double_t[nbins + 2];
2553 Int_t ibin = 0; fIntegral[ibin] = 0;
2554
2555 for (Int_t binz=1; binz <= nbinsz; ++binz) {
2556 for (Int_t biny=1; biny <= nbinsy; ++biny) {
2557 for (Int_t binx=1; binx <= nbinsx; ++binx) {
2558 ++ibin;
2559 Double_t y = RetrieveBinContent(GetBin(binx, biny, binz));
2560 if (onlyPositive && y < 0) {
2561 Error("ComputeIntegral","Bin content is negative - return a NaN value");
2562 fIntegral[nbins] = TMath::QuietNaN();
2563 break;
2564 }
2565 fIntegral[ibin] = fIntegral[ibin - 1] + y;
2566 }
2567 }
2568 }
2569
2570 // - Normalize integral to 1
2571 if (fIntegral[nbins] == 0 ) {
2572 Error("ComputeIntegral", "Integral = 0, no hits in histogram bins (excluding over/underflow).");
2573 return 0;
2574 }
2575 for (Int_t bin=1; bin <= nbins; ++bin) fIntegral[bin] /= fIntegral[nbins];
2576 fIntegral[nbins+1] = fEntries;
2577 return fIntegral[nbins];
2578}
2579
2580////////////////////////////////////////////////////////////////////////////////
2581/// Return a pointer to the array of bins integral.
2582/// if the pointer fIntegral is null, TH1::ComputeIntegral is called
2583/// The array dimension is the number of bins in the histograms
2584/// including underflow and overflow (fNCells)
2585/// the last value integral[fNCells] is set to the number of entries of
2586/// the histogram
2587
2589{
2590 if (!fIntegral) ComputeIntegral();
2591 return fIntegral;
2592}
2593
2594////////////////////////////////////////////////////////////////////////////////
2595/// Return a pointer to a histogram containing the cumulative content.
2596/// The cumulative can be computed both in the forward (default) or backward
2597/// direction; the name of the new histogram is constructed from
2598/// the name of this histogram with the suffix "suffix" appended provided
2599/// by the user. If not provided a default suffix="_cumulative" is used.
2600///
2601/// The cumulative distribution is formed by filling each bin of the
2602/// resulting histogram with the sum of that bin and all previous
2603/// (forward == kTRUE) or following (forward = kFALSE) bins.
2604///
2605/// Note: while cumulative distributions make sense in one dimension, you
2606/// may not be getting what you expect in more than 1D because the concept
2607/// of a cumulative distribution is much trickier to define; make sure you
2608/// understand the order of summation before you use this method with
2609/// histograms of dimension >= 2.
2610///
2611/// Note 2: By default the cumulative is computed from bin 1 to Nbins
2612/// If an axis range is set, values between the minimum and maximum of the range
2613/// are set.
2614/// Setting an axis range can also be used for including underflow and overflow in
2615/// the cumulative (e.g. by setting h->GetXaxis()->SetRange(0, h->GetNbinsX()+1); )
2617
2618TH1 *TH1::GetCumulative(Bool_t forward, const char* suffix) const
2619{
2620 const Int_t firstX = fXaxis.GetFirst();
2621 const Int_t lastX = fXaxis.GetLast();
2622 const Int_t firstY = (fDimension > 1) ? fYaxis.GetFirst() : 1;
2623 const Int_t lastY = (fDimension > 1) ? fYaxis.GetLast() : 1;
2624 const Int_t firstZ = (fDimension > 1) ? fZaxis.GetFirst() : 1;
2625 const Int_t lastZ = (fDimension > 1) ? fZaxis.GetLast() : 1;
2626
2627 TH1* hintegrated = (TH1*) Clone(fName + suffix);
2628 hintegrated->Reset();
2629 Double_t sum = 0.;
2630 Double_t esum = 0;
2631 if (forward) { // Forward computation
2632 for (Int_t binz = firstZ; binz <= lastZ; ++binz) {
2633 for (Int_t biny = firstY; biny <= lastY; ++biny) {
2634 for (Int_t binx = firstX; binx <= lastX; ++binx) {
2635 const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2636 sum += RetrieveBinContent(bin);
2637 hintegrated->AddBinContent(bin, sum);
2638 if (fSumw2.fN) {
2639 esum += GetBinErrorSqUnchecked(bin);
2640 hintegrated->fSumw2.fArray[bin] = esum;
2641 }
2642 }
2643 }
2644 }
2645 } else { // Backward computation
2646 for (Int_t binz = lastZ; binz >= firstZ; --binz) {
2647 for (Int_t biny = lastY; biny >= firstY; --biny) {
2648 for (Int_t binx = lastX; binx >= firstX; --binx) {
2649 const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2650 sum += RetrieveBinContent(bin);
2651 hintegrated->AddBinContent(bin, sum);
2652 if (fSumw2.fN) {
2653 esum += GetBinErrorSqUnchecked(bin);
2654 hintegrated->fSumw2.fArray[bin] = esum;
2655 }
2656 }
2657 }
2658 }
2659 }
2660 return hintegrated;
2661}
2662
2663////////////////////////////////////////////////////////////////////////////////
2664/// Copy this histogram structure to newth1.
2665///
2666/// Note that this function does not copy the list of associated functions.
2667/// Use TObject::Clone to make a full copy of a histogram.
2668///
2669/// Note also that the histogram it will be created in gDirectory (if AddDirectoryStatus()=true)
2670/// or will not be added to any directory if AddDirectoryStatus()=false
2671/// independently of the current directory stored in the original histogram
2672
2673void TH1::Copy(TObject &obj) const
2674{
2675 if (((TH1&)obj).fDirectory) {
2676 // We are likely to change the hash value of this object
2677 // with TNamed::Copy, to keep things correct, we need to
2678 // clean up its existing entries.
2679 ((TH1&)obj).fDirectory->Remove(&obj);
2680 ((TH1&)obj).fDirectory = nullptr;
2681 }
2682 TNamed::Copy(obj);
2683 ((TH1&)obj).fDimension = fDimension;
2684 ((TH1&)obj).fNormFactor= fNormFactor;
2685 ((TH1&)obj).fNcells = fNcells;
2686 ((TH1&)obj).fBarOffset = fBarOffset;
2687 ((TH1&)obj).fBarWidth = fBarWidth;
2688 ((TH1&)obj).fOption = fOption;
2689 ((TH1&)obj).fBinStatErrOpt = fBinStatErrOpt;
2690 ((TH1&)obj).fBufferSize= fBufferSize;
2691 // copy the Buffer
2692 // delete first a previously existing buffer
2693 if (((TH1&)obj).fBuffer != nullptr) {
2694 delete [] ((TH1&)obj).fBuffer;
2695 ((TH1&)obj).fBuffer = nullptr;
2696 }
2697 if (fBuffer) {
2698 Double_t *buf = new Double_t[fBufferSize];
2699 for (Int_t i=0;i<fBufferSize;i++) buf[i] = fBuffer[i];
2700 // obj.fBuffer has been deleted before
2701 ((TH1&)obj).fBuffer = buf;
2702 }
2703
2704 // copy bin contents (this should be done by the derived classes, since TH1 does not store the bin content)
2705 // Do this in case derived from TArray
2706 TArray* a = dynamic_cast<TArray*>(&obj);
2707 if (a) {
2708 a->Set(fNcells);
2709 for (Int_t i = 0; i < fNcells; i++)
2711 }
2712
2713 ((TH1&)obj).fEntries = fEntries;
2714
2715 // which will call BufferEmpty(0) and set fBuffer[0] to a Maybe one should call
2716 // assignment operator on the TArrayD
2717
2718 ((TH1&)obj).fTsumw = fTsumw;
2719 ((TH1&)obj).fTsumw2 = fTsumw2;
2720 ((TH1&)obj).fTsumwx = fTsumwx;
2721 ((TH1&)obj).fTsumwx2 = fTsumwx2;
2722 ((TH1&)obj).fMaximum = fMaximum;
2723 ((TH1&)obj).fMinimum = fMinimum;
2724
2725 TAttLine::Copy(((TH1&)obj));
2726 TAttFill::Copy(((TH1&)obj));
2727 TAttMarker::Copy(((TH1&)obj));
2728 fXaxis.Copy(((TH1&)obj).fXaxis);
2729 fYaxis.Copy(((TH1&)obj).fYaxis);
2730 fZaxis.Copy(((TH1&)obj).fZaxis);
2731 ((TH1&)obj).fXaxis.SetParent(&obj);
2732 ((TH1&)obj).fYaxis.SetParent(&obj);
2733 ((TH1&)obj).fZaxis.SetParent(&obj);
2734 fContour.Copy(((TH1&)obj).fContour);
2735 fSumw2.Copy(((TH1&)obj).fSumw2);
2736 // fFunctions->Copy(((TH1&)obj).fFunctions);
2737 // when copying an histogram if the AddDirectoryStatus() is true it
2738 // will be added to gDirectory independently of the fDirectory stored.
2739 // and if the AddDirectoryStatus() is false it will not be added to
2740 // any directory (fDirectory = nullptr)
2741 if (fgAddDirectory && gDirectory) {
2742 gDirectory->Append(&obj);
2743 ((TH1&)obj).fFunctions->UseRWLock();
2744 ((TH1&)obj).fDirectory = gDirectory;
2745 } else
2746 ((TH1&)obj).fDirectory = nullptr;
2747
2748}
2749
2750////////////////////////////////////////////////////////////////////////////////
2751/// Make a complete copy of the underlying object. If 'newname' is set,
2752/// the copy's name will be set to that name.
2753
2754TObject* TH1::Clone(const char* newname) const
2755{
2756 TH1* obj = (TH1*)IsA()->GetNew()(nullptr);
2757 Copy(*obj);
2758
2759 // Now handle the parts that Copy doesn't do
2760 if(fFunctions) {
2761 // The Copy above might have published 'obj' to the ListOfCleanups.
2762 // Clone can call RecursiveRemove, for example via TCheckHashRecursiveRemoveConsistency
2763 // when dictionary information is initialized, so we need to
2764 // keep obj->fFunction valid during its execution and
2765 // protect the update with the write lock.
2766
2767 // Reset stats parent - else cloning the stats will clone this histogram, too.
2768 auto oldstats = dynamic_cast<TVirtualPaveStats*>(fFunctions->FindObject("stats"));
2769 TObject *oldparent = nullptr;
2770 if (oldstats) {
2771 oldparent = oldstats->GetParent();
2772 oldstats->SetParent(nullptr);
2773 }
2774
2775 auto newlist = (TList*)fFunctions->Clone();
2776
2777 if (oldstats)
2778 oldstats->SetParent(oldparent);
2779 auto newstats = dynamic_cast<TVirtualPaveStats*>(obj->fFunctions->FindObject("stats"));
2780 if (newstats)
2781 newstats->SetParent(obj);
2782
2783 auto oldlist = obj->fFunctions;
2784 {
2786 obj->fFunctions = newlist;
2787 }
2788 delete oldlist;
2789 }
2790 if(newname && strlen(newname) ) {
2791 obj->SetName(newname);
2792 }
2793 return obj;
2794}
2795
2796////////////////////////////////////////////////////////////////////////////////
2797/// Perform the automatic addition of the histogram to the given directory
2798///
2799/// Note this function is called in place when the semantic requires
2800/// this object to be added to a directory (I.e. when being read from
2801/// a TKey or being Cloned)
2802
2804{
2805 Bool_t addStatus = TH1::AddDirectoryStatus();
2806 if (addStatus) {
2807 SetDirectory(dir);
2808 if (dir) {
2810 }
2811 }
2812}
2813
2814////////////////////////////////////////////////////////////////////////////////
2815/// Compute distance from point px,py to a line.
2816///
2817/// Compute the closest distance of approach from point px,py to elements
2818/// of a histogram.
2819/// The distance is computed in pixels units.
2820///
2821/// #### Algorithm:
2822/// Currently, this simple model computes the distance from the mouse
2823/// to the histogram contour only.
2824
2826{
2827 if (!fPainter) return 9999;
2828 return fPainter->DistancetoPrimitive(px,py);
2829}
2830
2831////////////////////////////////////////////////////////////////////////////////
2832/// Performs the operation: `this = this/(c1*f1)`
2833/// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2834///
2835/// Only bins inside the function range are recomputed.
2836/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2837/// you should call Sumw2 before making this operation.
2838/// This is particularly important if you fit the histogram after TH1::Divide
2839///
2840/// The function return kFALSE if the divide operation failed
2841
2843{
2844 if (!f1) {
2845 Error("Divide","Attempt to divide by a non-existing function");
2846 return kFALSE;
2847 }
2848
2849 // delete buffer if it is there since it will become invalid
2850 if (fBuffer) BufferEmpty(1);
2851
2852 Int_t nx = GetNbinsX() + 2; // normal bins + uf / of
2853 Int_t ny = GetNbinsY() + 2;
2854 Int_t nz = GetNbinsZ() + 2;
2855 if (fDimension < 2) ny = 1;
2856 if (fDimension < 3) nz = 1;
2857
2858
2859 SetMinimum();
2860 SetMaximum();
2861
2862 // - Loop on bins (including underflows/overflows)
2863 Int_t bin, binx, biny, binz;
2864 Double_t cu, w;
2865 Double_t xx[3];
2866 Double_t *params = nullptr;
2867 f1->InitArgs(xx,params);
2868 for (binz = 0; binz < nz; ++binz) {
2869 xx[2] = fZaxis.GetBinCenter(binz);
2870 for (biny = 0; biny < ny; ++biny) {
2871 xx[1] = fYaxis.GetBinCenter(biny);
2872 for (binx = 0; binx < nx; ++binx) {
2873 xx[0] = fXaxis.GetBinCenter(binx);
2874 if (!f1->IsInside(xx)) continue;
2876 bin = binx + nx * (biny + ny * binz);
2877 cu = c1 * f1->EvalPar(xx);
2878 if (TF1::RejectedPoint()) continue;
2879 if (cu) w = RetrieveBinContent(bin) / cu;
2880 else w = 0;
2881 UpdateBinContent(bin, w);
2882 if (fSumw2.fN) {
2883 if (cu != 0) fSumw2.fArray[bin] = GetBinErrorSqUnchecked(bin) / (cu * cu);
2884 else fSumw2.fArray[bin] = 0;
2885 }
2886 }
2887 }
2888 }
2889 ResetStats();
2890 return kTRUE;
2891}
2892
2893////////////////////////////////////////////////////////////////////////////////
2894/// Divide this histogram by h1.
2895///
2896/// `this = this/h1`
2897/// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2898/// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
2899/// if not already set.
2900/// The resulting errors are calculated assuming uncorrelated histograms.
2901/// See the other TH1::Divide that gives the possibility to optionally
2902/// compute binomial errors.
2903///
2904/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2905/// you should call Sumw2 before making this operation.
2906/// This is particularly important if you fit the histogram after TH1::Scale
2907///
2908/// The function return kFALSE if the divide operation failed
2909
2910Bool_t TH1::Divide(const TH1 *h1)
2911{
2912 if (!h1) {
2913 Error("Divide", "Input histogram passed does not exist (NULL).");
2914 return kFALSE;
2915 }
2916
2917 // delete buffer if it is there since it will become invalid
2918 if (fBuffer) BufferEmpty(1);
2919
2920 if (LoggedInconsistency("Divide", this, h1) >= kDifferentNumberOfBins) {
2921 return false;
2922 }
2923
2924 // Create Sumw2 if h1 has Sumw2 set
2925 if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
2926
2927 // - Loop on bins (including underflows/overflows)
2928 for (Int_t i = 0; i < fNcells; ++i) {
2931 if (c1) UpdateBinContent(i, c0 / c1);
2932 else UpdateBinContent(i, 0);
2933
2934 if(fSumw2.fN) {
2935 if (c1 == 0) { fSumw2.fArray[i] = 0; continue; }
2936 Double_t c1sq = c1 * c1;
2937 fSumw2.fArray[i] = (GetBinErrorSqUnchecked(i) * c1sq + h1->GetBinErrorSqUnchecked(i) * c0 * c0) / (c1sq * c1sq);
2938 }
2939 }
2940 ResetStats();
2941 return kTRUE;
2942}
2943
2944////////////////////////////////////////////////////////////////////////////////
2945/// Replace contents of this histogram by the division of h1 by h2.
2946///
2947/// `this = c1*h1/(c2*h2)`
2948///
2949/// If errors are defined (see TH1::Sumw2), errors are also recalculated
2950/// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
2951/// if not already set.
2952/// The resulting errors are calculated assuming uncorrelated histograms.
2953/// However, if option ="B" is specified, Binomial errors are computed.
2954/// In this case c1 and c2 do not make real sense and they are ignored.
2955///
2956/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2957/// you should call Sumw2 before making this operation.
2958/// This is particularly important if you fit the histogram after TH1::Divide
2959///
2960/// Please note also that in the binomial case errors are calculated using standard
2961/// binomial statistics, which means when b1 = b2, the error is zero.
2962/// If you prefer to have efficiency errors not going to zero when the efficiency is 1, you must
2963/// use the function TGraphAsymmErrors::BayesDivide, which will return an asymmetric and non-zero lower
2964/// error for the case b1=b2.
2965///
2966/// The function return kFALSE if the divide operation failed
2967
2969{
2970
2971 TString opt = option;
2972 opt.ToLower();
2973 Bool_t binomial = kFALSE;
2974 if (opt.Contains("b")) binomial = kTRUE;
2975 if (!h1 || !h2) {
2976 Error("Divide", "At least one of the input histograms passed does not exist (NULL).");
2977 return kFALSE;
2978 }
2979
2980 // delete buffer if it is there since it will become invalid
2981 if (fBuffer) BufferEmpty(1);
2982
2983 if (LoggedInconsistency("Divide", this, h1) >= kDifferentNumberOfBins ||
2984 LoggedInconsistency("Divide", h1, h2) >= kDifferentNumberOfBins) {
2985 return false;
2986 }
2987
2988 if (!c2) {
2989 Error("Divide","Coefficient of dividing histogram cannot be zero");
2990 return kFALSE;
2991 }
2992
2993 // Create Sumw2 if h1 or h2 have Sumw2 set, or if binomial errors are explicitly requested
2994 if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0 || binomial)) Sumw2();
2995
2996 SetMinimum();
2997 SetMaximum();
2998
2999 // - Loop on bins (including underflows/overflows)
3000 for (Int_t i = 0; i < fNcells; ++i) {
3002 Double_t b2 = h2->RetrieveBinContent(i);
3003 if (b2) UpdateBinContent(i, c1 * b1 / (c2 * b2));
3004 else UpdateBinContent(i, 0);
3005
3006 if (fSumw2.fN) {
3007 if (b2 == 0) { fSumw2.fArray[i] = 0; continue; }
3008 Double_t b1sq = b1 * b1; Double_t b2sq = b2 * b2;
3009 Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
3011 Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
3012 if (binomial) {
3013 if (b1 != b2) {
3014 // in the case of binomial statistics c1 and c2 must be 1 otherwise it does not make sense
3015 // c1 and c2 are ignored
3016 //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/(c2*b2));//this is the formula in Hbook/Hoper1
3017 //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/b2); // old formula from G. Flucke
3018 // formula which works also for weighted histogram (see http://root-forum.cern.ch/viewtopic.php?t=3753 )
3019 fSumw2.fArray[i] = TMath::Abs( ( (1. - 2.* b1 / b2) * e1sq + b1sq * e2sq / b2sq ) / b2sq );
3020 } else {
3021 //in case b1=b2 error is zero
3022 //use TGraphAsymmErrors::BayesDivide for getting the asymmetric error not equal to zero
3023 fSumw2.fArray[i] = 0;
3024 }
3025 } else {
3026 fSumw2.fArray[i] = c1sq * c2sq * (e1sq * b2sq + e2sq * b1sq) / (c2sq * c2sq * b2sq * b2sq);
3027 }
3028 }
3029 }
3030 ResetStats();
3031 if (binomial)
3032 // in case of binomial division use denominator for number of entries
3033 SetEntries ( h2->GetEntries() );
3034
3035 return kTRUE;
3036}
3037
3038////////////////////////////////////////////////////////////////////////////////
3039/// Draw this histogram with options.
3040///
3041/// Histograms are drawn via the THistPainter class. Each histogram has
3042/// a pointer to its own painter (to be usable in a multithreaded program).
3043/// The same histogram can be drawn with different options in different pads.
3044/// When a histogram drawn in a pad is deleted, the histogram is
3045/// automatically removed from the pad or pads where it was drawn.
3046/// If a histogram is drawn in a pad, then filled again, the new status
3047/// of the histogram will be automatically shown in the pad next time
3048/// the pad is updated. One does not need to redraw the histogram.
3049/// To draw the current version of a histogram in a pad, one can use
3050/// `h->DrawCopy();`
3051/// This makes a clone of the histogram. Once the clone is drawn, the original
3052/// histogram may be modified or deleted without affecting the aspect of the
3053/// clone.
3054/// By default, TH1::Draw clears the current pad.
3055///
3056/// One can use TH1::SetMaximum and TH1::SetMinimum to force a particular
3057/// value for the maximum or the minimum scale on the plot.
3058///
3059/// TH1::UseCurrentStyle can be used to change all histogram graphics
3060/// attributes to correspond to the current selected style.
3061/// This function must be called for each histogram.
3062/// In case one reads and draws many histograms from a file, one can force
3063/// the histograms to inherit automatically the current graphics style
3064/// by calling before gROOT->ForceStyle();
3065///
3066/// See the THistPainter class for a description of all the drawing options.
3067
3069{
3070 TString opt1 = option; opt1.ToLower();
3071 TString opt2 = option;
3072 Int_t index = opt1.Index("same");
3073
3074 // Check if the string "same" is part of a TCutg name.
3075 if (index>=0) {
3076 Int_t indb = opt1.Index("[");
3077 if (indb>=0) {
3078 Int_t indk = opt1.Index("]");
3079 if (index>indb && index<indk) index = -1;
3080 }
3081 }
3082
3083 // If there is no pad or an empty pad the "same" option is ignored.
3084 if (gPad) {
3085 if (!gPad->IsEditable()) gROOT->MakeDefCanvas();
3086 if (index>=0) {
3087 if (gPad->GetX1() == 0 && gPad->GetX2() == 1 &&
3088 gPad->GetY1() == 0 && gPad->GetY2() == 1 &&
3089 gPad->GetListOfPrimitives()->GetSize()==0) opt2.Remove(index,4);
3090 } else {
3091 //the following statement is necessary in case one attempts to draw
3092 //a temporary histogram already in the current pad
3093 if (TestBit(kCanDelete)) gPad->GetListOfPrimitives()->Remove(this);
3094 gPad->Clear();
3095 }
3096 gPad->IncrementPaletteColor(1, opt1);
3097 } else {
3098 if (index>=0) opt2.Remove(index,4);
3099 }
3100
3101 AppendPad(opt2.Data());
3102}
3103
3104////////////////////////////////////////////////////////////////////////////////
3105/// Copy this histogram and Draw in the current pad.
3106///
3107/// Once the histogram is drawn into the pad, any further modification
3108/// using graphics input will be made on the copy of the histogram,
3109/// and not to the original object.
3110/// By default a postfix "_copy" is added to the histogram name. Pass an empty postfix in case
3111/// you want to draw a histogram with the same name
3112///
3113/// See Draw for the list of options
3114
3115TH1 *TH1::DrawCopy(Option_t *option, const char * name_postfix) const
3116{
3117 TString opt = option;
3118 opt.ToLower();
3119 if (gPad && !opt.Contains("same")) gPad->Clear();
3120 TString newName;
3121 if (name_postfix) newName.Form("%s%s", GetName(), name_postfix);
3122 TH1 *newth1 = (TH1 *)Clone(newName.Data());
3123 newth1->SetDirectory(nullptr);
3124 newth1->SetBit(kCanDelete);
3125 if (gPad) gPad->IncrementPaletteColor(1, opt);
3126
3127 newth1->AppendPad(option);
3128 return newth1;
3129}
3130
3131////////////////////////////////////////////////////////////////////////////////
3132/// Draw a normalized copy of this histogram.
3133///
3134/// A clone of this histogram is normalized to norm and drawn with option.
3135/// A pointer to the normalized histogram is returned.
3136/// The contents of the histogram copy are scaled such that the new
3137/// sum of weights (excluding under and overflow) is equal to norm.
3138/// Note that the returned normalized histogram is not added to the list
3139/// of histograms in the current directory in memory.
3140/// It is the user's responsibility to delete this histogram.
3141/// The kCanDelete bit is set for the returned object. If a pad containing
3142/// this copy is cleared, the histogram will be automatically deleted.
3143///
3144/// See Draw for the list of options
3145
3147{
3149 if (sum == 0) {
3150 Error("DrawNormalized","Sum of weights is null. Cannot normalize histogram: %s",GetName());
3151 return nullptr;
3152 }
3153 Bool_t addStatus = TH1::AddDirectoryStatus();
3155 TH1 *h = (TH1*)Clone();
3157 // in case of drawing with error options - scale correctly the error
3158 TString opt(option); opt.ToUpper();
3159 if (fSumw2.fN == 0) {
3160 h->Sumw2();
3161 // do not use in this case the "Error option " for drawing which is enabled by default since the normalized histogram has now errors
3162 if (opt.IsNull() || opt == "SAME") opt += "HIST";
3163 }
3164 h->Scale(norm/sum);
3165 if (TMath::Abs(fMaximum+1111) > 1e-3) h->SetMaximum(fMaximum*norm/sum);
3166 if (TMath::Abs(fMinimum+1111) > 1e-3) h->SetMinimum(fMinimum*norm/sum);
3167 h->Draw(opt);
3168 TH1::AddDirectory(addStatus);
3169 return h;
3170}
3171
3172////////////////////////////////////////////////////////////////////////////////
3173/// Display a panel with all histogram drawing options.
3174///
3175/// See class TDrawPanelHist for example
3176
3177void TH1::DrawPanel()
3178{
3179 if (!fPainter) {Draw(); if (gPad) gPad->Update();}
3180 if (fPainter) fPainter->DrawPanel();
3181}
3182
3183////////////////////////////////////////////////////////////////////////////////
3184/// Evaluate function f1 at the center of bins of this histogram.
3185///
3186/// - If option "R" is specified, the function is evaluated only
3187/// for the bins included in the function range.
3188/// - If option "A" is specified, the value of the function is added to the
3189/// existing bin contents
3190/// - If option "S" is specified, the value of the function is used to
3191/// generate a value, distributed according to the Poisson
3192/// distribution, with f1 as the mean.
3193
3195{
3196 Double_t x[3];
3197 Int_t range, stat, add;
3198 if (!f1) return;
3199
3200 TString opt = option;
3201 opt.ToLower();
3202 if (opt.Contains("a")) add = 1;
3203 else add = 0;
3204 if (opt.Contains("s")) stat = 1;
3205 else stat = 0;
3206 if (opt.Contains("r")) range = 1;
3207 else range = 0;
3208
3209 // delete buffer if it is there since it will become invalid
3210 if (fBuffer) BufferEmpty(1);
3211
3212 Int_t nbinsx = fXaxis.GetNbins();
3213 Int_t nbinsy = fYaxis.GetNbins();
3214 Int_t nbinsz = fZaxis.GetNbins();
3215 if (!add) Reset();
3216
3217 for (Int_t binz = 1; binz <= nbinsz; ++binz) {
3218 x[2] = fZaxis.GetBinCenter(binz);
3219 for (Int_t biny = 1; biny <= nbinsy; ++biny) {
3220 x[1] = fYaxis.GetBinCenter(biny);
3221 for (Int_t binx = 1; binx <= nbinsx; ++binx) {
3222 Int_t bin = GetBin(binx,biny,binz);
3223 x[0] = fXaxis.GetBinCenter(binx);
3224 if (range && !f1->IsInside(x)) continue;
3225 Double_t fu = f1->Eval(x[0], x[1], x[2]);
3226 if (stat) fu = gRandom->PoissonD(fu);
3227 AddBinContent(bin, fu);
3228 if (fSumw2.fN) fSumw2.fArray[bin] += TMath::Abs(fu);
3229 }
3230 }
3231 }
3232}
3233
3234////////////////////////////////////////////////////////////////////////////////
3235/// Execute action corresponding to one event.
3236///
3237/// This member function is called when a histogram is clicked with the locator
3238///
3239/// If Left button clicked on the bin top value, then the content of this bin
3240/// is modified according to the new position of the mouse when it is released.
3241
3242void TH1::ExecuteEvent(Int_t event, Int_t px, Int_t py)
3243{
3244 if (fPainter) fPainter->ExecuteEvent(event, px, py);
3245}
3246
3247////////////////////////////////////////////////////////////////////////////////
3248/// This function allows to do discrete Fourier transforms of TH1 and TH2.
3249/// Available transform types and flags are described below.
3250///
3251/// To extract more information about the transform, use the function
3252/// TVirtualFFT::GetCurrentTransform() to get a pointer to the current
3253/// transform object.
3254///
3255/// \param[out] h_output histogram for the output. If a null pointer is passed, a new histogram is created
3256/// and returned, otherwise, the provided histogram is used and should be big enough
3257/// \param[in] option option parameters consists of 3 parts:
3258/// - option on what to return
3259/// - "RE" - returns a histogram of the real part of the output
3260/// - "IM" - returns a histogram of the imaginary part of the output
3261/// - "MAG"- returns a histogram of the magnitude of the output
3262/// - "PH" - returns a histogram of the phase of the output
3263/// - option of transform type
3264/// - "R2C" - real to complex transforms - default
3265/// - "R2HC" - real to halfcomplex (special format of storing output data,
3266/// results the same as for R2C)
3267/// - "DHT" - discrete Hartley transform
3268/// real to real transforms (sine and cosine):
3269/// - "R2R_0", "R2R_1", "R2R_2", "R2R_3" - discrete cosine transforms of types I-IV
3270/// - "R2R_4", "R2R_5", "R2R_6", "R2R_7" - discrete sine transforms of types I-IV
3271/// To specify the type of each dimension of a 2-dimensional real to real
3272/// transform, use options of form "R2R_XX", for example, "R2R_02" for a transform,
3273/// which is of type "R2R_0" in 1st dimension and "R2R_2" in the 2nd.
3274/// - option of transform flag
3275/// - "ES" (from "estimate") - no time in preparing the transform, but probably sub-optimal
3276/// performance
3277/// - "M" (from "measure") - some time spend in finding the optimal way to do the transform
3278/// - "P" (from "patient") - more time spend in finding the optimal way to do the transform
3279/// - "EX" (from "exhaustive") - the most optimal way is found
3280/// This option should be chosen depending on how many transforms of the same size and
3281/// type are going to be done. Planning is only done once, for the first transform of this
3282/// size and type. Default is "ES".
3283///
3284/// Examples of valid options: "Mag R2C M" "Re R2R_11" "Im R2C ES" "PH R2HC EX"
3285
3286TH1* TH1::FFT(TH1* h_output, Option_t *option)
3287{
3288
3289 Int_t ndim[3];
3290 ndim[0] = this->GetNbinsX();
3291 ndim[1] = this->GetNbinsY();
3292 ndim[2] = this->GetNbinsZ();
3293
3294 TVirtualFFT *fft;
3295 TString opt = option;
3296 opt.ToUpper();
3297 if (!opt.Contains("2R")){
3298 if (!opt.Contains("2C") && !opt.Contains("2HC") && !opt.Contains("DHT")) {
3299 //no type specified, "R2C" by default
3300 opt.Append("R2C");
3301 }
3302 fft = TVirtualFFT::FFT(this->GetDimension(), ndim, opt.Data());
3303 }
3304 else {
3305 //find the kind of transform
3306 Int_t ind = opt.Index("R2R", 3);
3307 Int_t *kind = new Int_t[2];
3308 char t;
3309 t = opt[ind+4];
3310 kind[0] = atoi(&t);
3311 if (h_output->GetDimension()>1) {
3312 t = opt[ind+5];
3313 kind[1] = atoi(&t);
3314 }
3315 fft = TVirtualFFT::SineCosine(this->GetDimension(), ndim, kind, option);
3316 delete [] kind;
3317 }
3318
3319 if (!fft) return nullptr;
3320 Int_t in=0;
3321 for (Int_t binx = 1; binx<=ndim[0]; binx++) {
3322 for (Int_t biny=1; biny<=ndim[1]; biny++) {
3323 for (Int_t binz=1; binz<=ndim[2]; binz++) {
3324 fft->SetPoint(in, this->GetBinContent(binx, biny, binz));
3325 in++;
3326 }
3327 }
3328 }
3329 fft->Transform();
3330 h_output = TransformHisto(fft, h_output, option);
3331 return h_output;
3332}
3333
3334////////////////////////////////////////////////////////////////////////////////
3335/// Increment bin with abscissa X by 1.
3336///
3337/// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3338/// if x is equal to or greater than the upper edge of last bin, the Overflow bin is incremented
3339///
3340/// If the storage of the sum of squares of weights has been triggered,
3341/// via the function Sumw2, then the sum of the squares of weights is incremented
3342/// by 1 in the bin corresponding to x.
3343///
3344/// The function returns the corresponding bin number which has its content incremented by 1
3345
3347{
3348 if (fBuffer) return BufferFill(x,1);
3349
3350 Int_t bin;
3351 fEntries++;
3352 bin =fXaxis.FindBin(x);
3353 if (bin <0) return -1;
3354 AddBinContent(bin);
3355 if (fSumw2.fN) ++fSumw2.fArray[bin];
3356 if (bin == 0 || bin > fXaxis.GetNbins()) {
3357 if (!GetStatOverflowsBehaviour()) return -1;
3358 }
3359 ++fTsumw;
3360 ++fTsumw2;
3361 fTsumwx += x;
3362 fTsumwx2 += x*x;
3363 return bin;
3364}
3365
3366////////////////////////////////////////////////////////////////////////////////
3367/// Increment bin with abscissa X with a weight w.
3368///
3369/// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3370/// if x is equal to or greater than the upper edge of last bin, the Overflow bin is incremented
3371///
3372/// If the weight is not equal to 1, the storage of the sum of squares of
3373/// weights is automatically triggered and the sum of the squares of weights is incremented
3374/// by \f$ w^2 \f$ in the bin corresponding to x.
3375///
3376/// The function returns the corresponding bin number which has its content incremented by w
3377
3379{
3380
3381 if (fBuffer) return BufferFill(x,w);
3382
3383 Int_t bin;
3384 fEntries++;
3385 bin =fXaxis.FindBin(x);
3386 if (bin <0) return -1;
3387 if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW) ) Sumw2(); // must be called before AddBinContent
3388 if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3389 AddBinContent(bin, w);
3390 if (bin == 0 || bin > fXaxis.GetNbins()) {
3391 if (!GetStatOverflowsBehaviour()) return -1;
3392 }
3393 Double_t z= w;
3394 fTsumw += z;
3395 fTsumw2 += z*z;
3396 fTsumwx += z*x;
3397 fTsumwx2 += z*x*x;
3398 return bin;
3399}
3400
3401////////////////////////////////////////////////////////////////////////////////
3402/// Increment bin with namex with a weight w
3403///
3404/// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3405/// if x is equal to or greater than the upper edge of last bin, the Overflow bin is incremented
3406///
3407/// If the weight is not equal to 1, the storage of the sum of squares of
3408/// weights is automatically triggered and the sum of the squares of weights is incremented
3409/// by \f$ w^2 \f$ in the bin corresponding to x.
3410///
3411/// The function returns the corresponding bin number which has its content
3412/// incremented by w.
3413
3414Int_t TH1::Fill(const char *namex, Double_t w)
3415{
3416 Int_t bin;
3417 fEntries++;
3418 bin =fXaxis.FindBin(namex);
3419 if (bin <0) return -1;
3420 if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3421 if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3422 AddBinContent(bin, w);
3423 if (bin == 0 || bin > fXaxis.GetNbins()) return -1;
3424 Double_t z= w;
3425 fTsumw += z;
3426 fTsumw2 += z*z;
3427 // this make sense if the histogram is not expanding (the x axis cannot be extended)
3428 if (!fXaxis.CanExtend() || !fXaxis.IsAlphanumeric()) {
3430 fTsumwx += z*x;
3431 fTsumwx2 += z*x*x;
3432 }
3433 return bin;
3434}
3435
3436////////////////////////////////////////////////////////////////////////////////
3437/// Fill this histogram with an array x and weights w.
3438///
3439/// \param[in] ntimes number of entries in arrays x and w (array size must be ntimes*stride)
3440/// \param[in] x array of values to be histogrammed
3441/// \param[in] w array of weighs
3442/// \param[in] stride step size through arrays x and w
3443///
3444/// If the weight is not equal to 1, the storage of the sum of squares of
3445/// weights is automatically triggered and the sum of the squares of weights is incremented
3446/// by \f$ w^2 \f$ in the bin corresponding to x.
3447/// if w is NULL each entry is assumed a weight=1
3448
3449void TH1::FillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3450{
3451 //If a buffer is activated, fill buffer
3452 if (fBuffer) {
3453 ntimes *= stride;
3454 Int_t i = 0;
3455 for (i=0;i<ntimes;i+=stride) {
3456 if (!fBuffer) break; // buffer can be deleted in BufferFill when is empty
3457 if (w) BufferFill(x[i],w[i]);
3458 else BufferFill(x[i], 1.);
3459 }
3460 // fill the remaining entries if the buffer has been deleted
3461 if (i < ntimes && !fBuffer) {
3462 auto weights = w ? &w[i] : nullptr;
3463 DoFillN((ntimes-i)/stride,&x[i],weights,stride);
3464 }
3465 return;
3466 }
3467 // call internal method
3468 DoFillN(ntimes, x, w, stride);
3469}
3470
3471////////////////////////////////////////////////////////////////////////////////
3472/// Internal method to fill histogram content from a vector
3473/// called directly by TH1::BufferEmpty
3474
3475void TH1::DoFillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3476{
3477 Int_t bin,i;
3478
3479 fEntries += ntimes;
3480 Double_t ww = 1;
3481 Int_t nbins = fXaxis.GetNbins();
3482 ntimes *= stride;
3483 for (i=0;i<ntimes;i+=stride) {
3484 bin =fXaxis.FindBin(x[i]);
3485 if (bin <0) continue;
3486 if (w) ww = w[i];
3487 if (!fSumw2.fN && ww != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3488 if (fSumw2.fN) fSumw2.fArray[bin] += ww*ww;
3489 AddBinContent(bin, ww);
3490 if (bin == 0 || bin > nbins) {
3491 if (!GetStatOverflowsBehaviour()) continue;
3492 }
3493 Double_t z= ww;
3494 fTsumw += z;
3495 fTsumw2 += z*z;
3496 fTsumwx += z*x[i];
3497 fTsumwx2 += z*x[i]*x[i];
3498 }
3499}
3500
3501////////////////////////////////////////////////////////////////////////////////
3502/// Fill histogram following distribution in function fname.
3503///
3504/// @param fname : Function name used for filling the histogram
3505/// @param ntimes : number of times the histogram is filled
3506/// @param rng : (optional) Random number generator used to sample
3507///
3508///
3509/// The distribution contained in the function fname (TF1) is integrated
3510/// over the channel contents for the bin range of this histogram.
3511/// It is normalized to 1.
3512///
3513/// Getting one random number implies:
3514/// - Generating a random number between 0 and 1 (say r1)
3515/// - Look in which bin in the normalized integral r1 corresponds to
3516/// - Fill histogram channel
3517/// ntimes random numbers are generated
3518///
3519/// One can also call TF1::GetRandom to get a random variate from a function.
3520
3521void TH1::FillRandom(const char *fname, Int_t ntimes, TRandom * rng)
3522{
3523 Int_t bin, binx, ibin, loop;
3524 Double_t r1, x;
3525 // - Search for fname in the list of ROOT defined functions
3526 TF1 *f1 = (TF1*)gROOT->GetFunction(fname);
3527 if (!f1) { Error("FillRandom", "Unknown function: %s",fname); return; }
3528
3529 // - Allocate temporary space to store the integral and compute integral
3530
3531 TAxis * xAxis = &fXaxis;
3532
3533 // in case axis of histogram is not defined use the function axis
3534 if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
3536 f1->GetRange(xmin,xmax);
3537 Info("FillRandom","Using function axis and range [%g,%g]",xmin, xmax);
3538 xAxis = f1->GetHistogram()->GetXaxis();
3539 }
3540
3541 Int_t first = xAxis->GetFirst();
3542 Int_t last = xAxis->GetLast();
3543 Int_t nbinsx = last-first+1;
3544
3545 Double_t *integral = new Double_t[nbinsx+1];
3546 integral[0] = 0;
3547 for (binx=1;binx<=nbinsx;binx++) {
3548 Double_t fint = f1->Integral(xAxis->GetBinLowEdge(binx+first-1),xAxis->GetBinUpEdge(binx+first-1), 0.);
3549 integral[binx] = integral[binx-1] + fint;
3550 }
3551
3552 // - Normalize integral to 1
3553 if (integral[nbinsx] == 0 ) {
3554 delete [] integral;
3555 Error("FillRandom", "Integral = zero"); return;
3556 }
3557 for (bin=1;bin<=nbinsx;bin++) integral[bin] /= integral[nbinsx];
3558
3559 // --------------Start main loop ntimes
3560 for (loop=0;loop<ntimes;loop++) {
3561 r1 = (rng) ? rng->Rndm() : gRandom->Rndm();
3562 ibin = TMath::BinarySearch(nbinsx,&integral[0],r1);
3563 //binx = 1 + ibin;
3564 //x = xAxis->GetBinCenter(binx); //this is not OK when SetBuffer is used
3565 x = xAxis->GetBinLowEdge(ibin+first)
3566 +xAxis->GetBinWidth(ibin+first)*(r1-integral[ibin])/(integral[ibin+1] - integral[ibin]);
3567 Fill(x);
3568 }
3569 delete [] integral;
3570}
3571
3572////////////////////////////////////////////////////////////////////////////////
3573/// Fill histogram following distribution in histogram h.
3574///
3575/// @param h : Histogram pointer used for sampling random number
3576/// @param ntimes : number of times the histogram is filled
3577/// @param rng : (optional) Random number generator used for sampling
3578///
3579/// The distribution contained in the histogram h (TH1) is integrated
3580/// over the channel contents for the bin range of this histogram.
3581/// It is normalized to 1.
3582///
3583/// Getting one random number implies:
3584/// - Generating a random number between 0 and 1 (say r1)
3585/// - Look in which bin in the normalized integral r1 corresponds to
3586/// - Fill histogram channel ntimes random numbers are generated
3587///
3588/// SPECIAL CASE when the target histogram has the same binning as the source.
3589/// in this case we simply use a poisson distribution where
3590/// the mean value per bin = bincontent/integral.
3591
3592void TH1::FillRandom(TH1 *h, Int_t ntimes, TRandom * rng)
3593{
3594 if (!h) { Error("FillRandom", "Null histogram"); return; }
3595 if (fDimension != h->GetDimension()) {
3596 Error("FillRandom", "Histograms with different dimensions"); return;
3597 }
3598 if (std::isnan(h->ComputeIntegral(true))) {
3599 Error("FillRandom", "Histograms contains negative bins, does not represent probabilities");
3600 return;
3601 }
3602
3603 //in case the target histogram has the same binning and ntimes much greater
3604 //than the number of bins we can use a fast method
3605 Int_t first = fXaxis.GetFirst();
3606 Int_t last = fXaxis.GetLast();
3607 Int_t nbins = last-first+1;
3608 if (ntimes > 10*nbins) {
3609 auto inconsistency = CheckConsistency(this,h);
3610 if (inconsistency != kFullyConsistent) return; // do nothing
3611 Double_t sumw = h->Integral(first,last);
3612 if (sumw == 0) return;
3613 Double_t sumgen = 0;
3614 for (Int_t bin=first;bin<=last;bin++) {
3615 Double_t mean = h->RetrieveBinContent(bin)*ntimes/sumw;
3616 Double_t cont = (rng) ? rng->Poisson(mean) : gRandom->Poisson(mean);
3617 sumgen += cont;
3618 AddBinContent(bin,cont);
3619 if (fSumw2.fN) fSumw2.fArray[bin] += cont;
3620 }
3621
3622 // fix for the fluctuations in the total number n
3623 // since we use Poisson instead of multinomial
3624 // add a correction to have ntimes as generated entries
3625 Int_t i;
3626 if (sumgen < ntimes) {
3627 // add missing entries
3628 for (i = Int_t(sumgen+0.5); i < ntimes; ++i)
3629 {
3630 Double_t x = h->GetRandom();
3631 Fill(x);
3632 }
3633 }
3634 else if (sumgen > ntimes) {
3635 // remove extra entries
3636 i = Int_t(sumgen+0.5);
3637 while( i > ntimes) {
3638 Double_t x = h->GetRandom(rng);
3639 Int_t ibin = fXaxis.FindBin(x);
3641 // skip in case bin is empty
3642 if (y > 0) {
3643 SetBinContent(ibin, y-1.);
3644 i--;
3645 }
3646 }
3647 }
3648
3649 ResetStats();
3650 return;
3651 }
3652 // case of different axis and not too large ntimes
3653
3654 if (h->ComputeIntegral() ==0) return;
3655 Int_t loop;
3656 Double_t x;
3657 for (loop=0;loop<ntimes;loop++) {
3658 x = h->GetRandom();
3659 Fill(x);
3660 }
3661}
3662
3663////////////////////////////////////////////////////////////////////////////////
3664/// Return Global bin number corresponding to x,y,z
3665///
3666/// 2-D and 3-D histograms are represented with a one dimensional
3667/// structure. This has the advantage that all existing functions, such as
3668/// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3669/// This function tries to extend the axis if the given point belongs to an
3670/// under-/overflow bin AND if CanExtendAllAxes() is true.
3671///
3672/// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3673
3675{
3676 if (GetDimension() < 2) {
3677 return fXaxis.FindBin(x);
3678 }
3679 if (GetDimension() < 3) {
3680 Int_t nx = fXaxis.GetNbins()+2;
3681 Int_t binx = fXaxis.FindBin(x);
3682 Int_t biny = fYaxis.FindBin(y);
3683 return binx + nx*biny;
3684 }
3685 if (GetDimension() < 4) {
3686 Int_t nx = fXaxis.GetNbins()+2;
3687 Int_t ny = fYaxis.GetNbins()+2;
3688 Int_t binx = fXaxis.FindBin(x);
3689 Int_t biny = fYaxis.FindBin(y);
3690 Int_t binz = fZaxis.FindBin(z);
3691 return binx + nx*(biny +ny*binz);
3692 }
3693 return -1;
3694}
3695
3696////////////////////////////////////////////////////////////////////////////////
3697/// Return Global bin number corresponding to x,y,z.
3698///
3699/// 2-D and 3-D histograms are represented with a one dimensional
3700/// structure. This has the advantage that all existing functions, such as
3701/// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3702/// This function DOES NOT try to extend the axis if the given point belongs
3703/// to an under-/overflow bin.
3704///
3705/// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3706
3708{
3709 if (GetDimension() < 2) {
3710 return fXaxis.FindFixBin(x);
3711 }
3712 if (GetDimension() < 3) {
3713 Int_t nx = fXaxis.GetNbins()+2;
3714 Int_t binx = fXaxis.FindFixBin(x);
3715 Int_t biny = fYaxis.FindFixBin(y);
3716 return binx + nx*biny;
3717 }
3718 if (GetDimension() < 4) {
3719 Int_t nx = fXaxis.GetNbins()+2;
3720 Int_t ny = fYaxis.GetNbins()+2;
3721 Int_t binx = fXaxis.FindFixBin(x);
3722 Int_t biny = fYaxis.FindFixBin(y);
3723 Int_t binz = fZaxis.FindFixBin(z);
3724 return binx + nx*(biny +ny*binz);
3725 }
3726 return -1;
3727}
3728
3729////////////////////////////////////////////////////////////////////////////////
3730/// Find first bin with content > threshold for axis (1=x, 2=y, 3=z)
3731/// if no bins with content > threshold is found the function returns -1.
3732/// The search will occur between the specified first and last bin. Specifying
3733/// the value of the last bin to search to less than zero will search until the
3734/// last defined bin.
3735
3736Int_t TH1::FindFirstBinAbove(Double_t threshold, Int_t axis, Int_t firstBin, Int_t lastBin) const
3737{
3738 if (fBuffer) ((TH1*)this)->BufferEmpty();
3739
3740 if (axis < 1 || (axis > 1 && GetDimension() == 1 ) ||
3741 ( axis > 2 && GetDimension() == 2 ) || ( axis > 3 && GetDimension() > 3 ) ) {
3742 Warning("FindFirstBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3743 axis = 1;
3744 }
3745 if (firstBin < 1) {
3746 firstBin = 1;
3747 }
3748 Int_t nbinsx = fXaxis.GetNbins();
3749 Int_t nbinsy = (GetDimension() > 1 ) ? fYaxis.GetNbins() : 1;
3750 Int_t nbinsz = (GetDimension() > 2 ) ? fZaxis.GetNbins() : 1;
3751
3752 if (axis == 1) {
3753 if (lastBin < 0 || lastBin > fXaxis.GetNbins()) {
3754 lastBin = fXaxis.GetNbins();
3755 }
3756 for (Int_t binx = firstBin; binx <= lastBin; binx++) {
3757 for (Int_t biny = 1; biny <= nbinsy; biny++) {
3758 for (Int_t binz = 1; binz <= nbinsz; binz++) {
3759 if (RetrieveBinContent(GetBin(binx,biny,binz)) > threshold) return binx;
3760 }
3761 }
3762 }
3763 }
3764 else if (axis == 2) {
3765 if (lastBin < 0 || lastBin > fYaxis.GetNbins()) {
3766 lastBin = fYaxis.GetNbins();
3767 }
3768 for (Int_t biny = firstBin; biny <= lastBin; biny++) {
3769 for (Int_t binx = 1; binx <= nbinsx; binx++) {
3770 for (Int_t binz = 1; binz <= nbinsz; binz++) {
3771 if (RetrieveBinContent(GetBin(binx,biny,binz)) > threshold) return biny;
3772 }
3773 }
3774 }
3775 }
3776 else if (axis == 3) {
3777 if (lastBin < 0 || lastBin > fZaxis.GetNbins()) {
3778 lastBin = fZaxis.GetNbins();
3779 }
3780 for (Int_t binz = firstBin; binz <= lastBin; binz++) {
3781 for (Int_t binx = 1; binx <= nbinsx; binx++) {
3782 for (Int_t biny = 1; biny <= nbinsy; biny++) {
3783 if (RetrieveBinContent(GetBin(binx,biny,binz)) > threshold) return binz;
3784 }
3785 }
3786 }
3787 }
3788
3789 return -1;
3790}
3791
3792////////////////////////////////////////////////////////////////////////////////
3793/// Find last bin with content > threshold for axis (1=x, 2=y, 3=z)
3794/// if no bins with content > threshold is found the function returns -1.
3795/// The search will occur between the specified first and last bin. Specifying
3796/// the value of the last bin to search to less than zero will search until the
3797/// last defined bin.
3798
3799Int_t TH1::FindLastBinAbove(Double_t threshold, Int_t axis, Int_t firstBin, Int_t lastBin) const
3800{
3801 if (fBuffer) ((TH1*)this)->BufferEmpty();
3802
3803
3804 if (axis < 1 || ( axis > 1 && GetDimension() == 1 ) ||
3805 ( axis > 2 && GetDimension() == 2 ) || ( axis > 3 && GetDimension() > 3) ) {
3806 Warning("FindFirstBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3807 axis = 1;
3808 }
3809 if (firstBin < 1) {
3810 firstBin = 1;
3811 }
3812 Int_t nbinsx = fXaxis.GetNbins();
3813 Int_t nbinsy = (GetDimension() > 1 ) ? fYaxis.GetNbins() : 1;
3814 Int_t nbinsz = (GetDimension() > 2 ) ? fZaxis.GetNbins() : 1;
3815
3816 if (axis == 1) {
3817 if (lastBin < 0 || lastBin > fXaxis.GetNbins()) {
3818 lastBin = fXaxis.GetNbins();
3819 }
3820 for (Int_t binx = lastBin; binx >= firstBin; binx--) {
3821 for (Int_t biny = 1; biny <= nbinsy; biny++) {
3822 for (Int_t binz = 1; binz <= nbinsz; binz++) {
3823 if (RetrieveBinContent(GetBin(binx, biny, binz)) > threshold) return binx;
3824 }
3825 }
3826 }
3827 }
3828 else if (axis == 2) {
3829 if (lastBin < 0 || lastBin > fYaxis.GetNbins()) {
3830 lastBin = fYaxis.GetNbins();
3831 }
3832 for (Int_t biny = lastBin; biny >= firstBin; biny--) {
3833 for (Int_t binx = 1; binx <= nbinsx; binx++) {
3834 for (Int_t binz = 1; binz <= nbinsz; binz++) {
3835 if (RetrieveBinContent(GetBin(binx, biny, binz)) > threshold) return biny;
3836 }
3837 }
3838 }
3839 }
3840 else if (axis == 3) {
3841 if (lastBin < 0 || lastBin > fZaxis.GetNbins()) {
3842 lastBin = fZaxis.GetNbins();
3843 }
3844 for (Int_t binz = lastBin; binz >= firstBin; binz--) {
3845 for (Int_t binx = 1; binx <= nbinsx; binx++) {
3846 for (Int_t biny = 1; biny <= nbinsy; biny++) {
3847 if (RetrieveBinContent(GetBin(binx, biny, binz)) > threshold) return binz;
3848 }
3849 }
3850 }
3851 }
3852
3853 return -1;
3854}
3855
3856////////////////////////////////////////////////////////////////////////////////
3857/// Search object named name in the list of functions.
3858
3859TObject *TH1::FindObject(const char *name) const
3860{
3861 if (fFunctions) return fFunctions->FindObject(name);
3862 return nullptr;
3863}
3864
3865////////////////////////////////////////////////////////////////////////////////
3866/// Search object obj in the list of functions.
3867
3868TObject *TH1::FindObject(const TObject *obj) const
3869{
3870 if (fFunctions) return fFunctions->FindObject(obj);
3871 return nullptr;
3872}
3873
3874////////////////////////////////////////////////////////////////////////////////
3875/// Fit histogram with function fname.
3876///
3877///
3878/// fname is the name of a function available in the global ROOT list of functions
3879/// `gROOT->GetListOfFunctions`
3880/// The list include any TF1 object created by the user plus some pre-defined functions
3881/// which are automatically created by ROOT the first time a pre-defined function is requested from `gROOT`
3882/// (i.e. when calling `gROOT->GetFunction(const char *name)`).
3883/// These pre-defined functions are:
3884/// - `gaus, gausn` where gausn is the normalized Gaussian
3885/// - `landau, landaun`
3886/// - `expo`
3887/// - `pol1,...9, chebyshev1,...9`.
3888///
3889/// For printing the list of all available functions do:
3890///
3891/// TF1::InitStandardFunctions(); // not needed if `gROOT->GetFunction` is called before
3892/// gROOT->GetListOfFunctions()->ls()
3893///
3894/// `fname` can also be a formula that is accepted by the linear fitter containing the special operator `++`,
3895/// representing linear components separated by `++` sign, for example `x++sin(x)` for fitting `[0]*x+[1]*sin(x)`
3896///
3897/// This function finds a pointer to the TF1 object with name `fname` and calls TH1::Fit(TF1 *, Option_t *, Option_t *,
3898/// Double_t, Double_t). See there for the fitting options and the details about fitting histograms
3899
3900TFitResultPtr TH1::Fit(const char *fname ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
3901{
3902 char *linear;
3903 linear= (char*)strstr(fname, "++");
3904 Int_t ndim=GetDimension();
3905 if (linear){
3906 if (ndim<2){
3907 TF1 f1(fname, fname, xxmin, xxmax);
3908 return Fit(&f1,option,goption,xxmin,xxmax);
3909 }
3910 else if (ndim<3){
3911 TF2 f2(fname, fname);
3912 return Fit(&f2,option,goption,xxmin,xxmax);
3913 }
3914 else{
3915 TF3 f3(fname, fname);
3916 return Fit(&f3,option,goption,xxmin,xxmax);
3917 }
3918 }
3919 else{
3920 TF1 * f1 = (TF1*)gROOT->GetFunction(fname);
3921 if (!f1) { Printf("Unknown function: %s",fname); return -1; }
3922 return Fit(f1,option,goption,xxmin,xxmax);
3923 }
3924}
3925
3926////////////////////////////////////////////////////////////////////////////////
3927/// Fit histogram with the function pointer f1.
3928///
3929/// \param[in] f1 pointer to the function object
3930/// \param[in] option string defining the fit options (see table below).
3931/// \param[in] goption specify a list of graphics options. See TH1::Draw for a complete list of these options.
3932/// \param[in] xxmin lower fitting range
3933/// \param[in] xxmax upper fitting range
3934/// \return A smart pointer to the TFitResult class
3935///
3936/// \anchor HFitOpt
3937/// ### Histogram Fitting Options
3938///
3939/// Here is the full list of fit options that can be given in the parameter `option`.
3940/// Several options can be used together by concatanating the strings without the need of any delimiters.
3941///
3942/// option | description
3943/// -------|------------
3944/// "L" | Uses a log likelihood method (default is chi-square method). To be used when the histogram represents counts.
3945/// "WL" | Weighted log likelihood method. To be used when the histogram has been filled with weights different than 1. This is needed for getting correct parameter uncertainties for weighted fits.
3946/// "P" | Uses Pearson chi-square method. Uses expected errors instead of the observed one (default case). The expected error is instead estimated from the square-root of the bin function value.
3947/// "MULTI" | Uses Loglikelihood method based on multi-nomial distribution. In this case the function must be normalized and one fits only the function shape.
3948/// "W" | Fit using the chi-square method and ignoring the bin uncertainties and skip empty bins.
3949/// "WW" | Fit using the chi-square method and ignoring the bin uncertainties and include the empty bins.
3950/// "I" | Uses the integral of function in the bin instead of the default bin center value.
3951/// "F" | Uses the default minimizer (e.g. Minuit) when fitting a linear function (e.g. polN) instead of the linear fitter.
3952/// "U" | Uses a user specified objective function (e.g. user providedlikelihood function) defined using `TVirtualFitter::SetFCN`
3953/// "E" | Performs a better parameter errors estimation using the Minos technique for all fit parameters.
3954/// "M" | Uses the IMPROVE algorithm (available only in TMinuit). This algorithm attempts improve the found local minimum by searching for a better one.
3955/// "S" | The full result of the fit is returned in the `TFitResultPtr`. This is needed to get the covariance matrix of the fit. See `TFitResult` and the base class `ROOT::Math::FitResult`.
3956/// "Q" | Quiet mode (minimum printing)
3957/// "V" | Verbose mode (default is between Q and V)
3958/// "+" | Adds this new fitted function to the list of fitted functions. By default, the previous function is deleted and only the last one is kept.
3959/// "N" | Does not store the graphics function, does not draw the histogram with the function after fitting.
3960/// "0" | Does not draw the histogram and the fitted function after fitting, but in contrast to option "N", it stores the fitted function in the histogram list of functions.
3961/// "R" | Fit using a fitting range specified in the function range with `TF1::SetRange`.
3962/// "B" | Use this option when you want to fix or set limits on one or more parameters and the fitting function is a predefined one (e.g gaus, expo,..), otherwise in case of pre-defined functions, some default initial values and limits will be used.
3963/// "C" | In case of linear fitting, do no calculate the chisquare (saves CPU time).
3964/// "G" | Uses the gradient implemented in `TF1::GradientPar` for the minimization. This allows to use Automatic Differentiation when it is supported by the provided TF1 function.
3965/// "WIDTH" | Scales the histogran bin content by the bin width (useful for variable bins histograms)
3966/// "SERIAL" | Runs in serial mode. By defult if ROOT is built with MT support and MT is enables, the fit is perfomed in multi-thread - "E" Perform better Errors estimation using Minos technique
3967/// "MULTITHREAD" | Forces usage of multi-thread execution whenever possible
3968///
3969/// The default fitting of an histogram (when no option is given) is perfomed as following:
3970/// - a chi-square fit (see below Chi-square Fits) computed using the bin histogram errors and excluding bins with zero errors (empty bins);
3971/// - the full range of the histogram is used;
3972/// - the default Minimizer with its default configuration is used (see below Minimizer Configuration) except for linear function;
3973/// - for linear functions (`polN`, `chenbyshev` or formula expressions combined using operator `++`) a linear minimization is used.
3974/// - only the status of the fit is returned;
3975/// - the fit is performed in Multithread whenever is enabled in ROOT;
3976/// - only the last fitted function is saved in the histogram;
3977/// - the histogram is drawn after fitting overalyed with the resulting fitting function
3978///
3979/// \anchor HFitMinimizer
3980/// ### Minimizer Configuration
3981///
3982/// The Fit is perfomed using the default Minimizer, defined in the `ROOT::Math::MinimizerOptions` class.
3983/// It is possible to change the default minimizer and its configuration parameters by calling these static functions before fitting (before calling `TH1::Fit`):
3984/// - `ROOT::Math::MinimizerOptions::SetDefaultMinimizer(minimizerName, minimizerAgorithm)` for changing the minmizer and/or the corresponding algorithm.
3985/// For example `ROOT::Math::MinimizerOptions::SetDefaultMinimizer("GSLMultiMin","BFGS");` will set the usage of the BFGS algorithm of the GSL multi-dimensional minimization
3986/// The current defaults are ("Minuit","Migrad").
3987/// See the documentation of the `ROOT::Math::MinimizerOptions` for the available minimizers in ROOT and their corresponding algorithms.
3988/// - `ROOT::Math::MinimizerOptions::SetDefaultTolerance` for setting a different tolerance value for the minimization.
3989/// - `ROOT::Math::MinimizerOptions::SetDefaultMaxFunctionCalls` for setting the maximum number of function calls.
3990/// - `ROOT::Math::MinimizerOptions::SetDefaultPrintLevel` for changing the minimizer print level from level=0 (minimal printing) to level=3 maximum printing
3991///
3992/// Other options are possible depending on the Minimizer used, see the corresponding documentation.
3993/// The default minimizer can be also set in the resource file in etc/system.rootrc. For example
3994///
3995/// ~~~ {.cpp}
3996/// Root.Fitter: Minuit2
3997/// ~~~
3998///
3999/// \anchor HFitChi2
4000/// ### Chi-square Fits
4001///
4002/// By default a chi-square (least-square) fit is performed on the histogram. The so-called modified least-square method
4003/// is used where the residual for each bin is computed using as error the observed value (the bin error) returned by `TH1::GetBinError`
4004///
4005/// \f[
4006/// Chi2 = \sum_{i}{ \left(\frac{y(i) - f(x(i) | p )}{e(i)} \right)^2 }
4007/// \f]
4008///
4009/// 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
4010/// an un-weighted histogram). Bins with zero errors are excluded from the fit. See also later the note on the treatment
4011/// of empty bins. When using option "I" the residual is computed not using the function value at the bin center, `f(x(i)|p)`,
4012/// but the integral of the function in the bin, Integral{ f(x|p)dx }, divided by the bin volume.
4013/// When using option `P` (Pearson chi2), the expected error computed as `e(i) = sqrt(f(x(i)|p))` is used.
4014/// In this case empty bins are considered in the fit.
4015/// Both chi-square methods should not be used when the bin content represent counts, especially in case of low bin statistics,
4016/// because they could return a biased result.
4017///
4018/// \anchor HFitNLL
4019/// ### Likelihood Fits
4020///
4021/// When using option "L" a likelihood fit is used instead of the default chi-square fit.
4022/// The likelihood is built assuming a Poisson probability density function for each bin.
4023/// The negative log-likelihood to be minimized is
4024///
4025/// \f[
4026/// NLL = - \sum_{i}{ \log {\mathrm P} ( y(i) | f(x(i) | p ) ) }
4027/// \f]
4028/// where `P(y|f)` is the Poisson distribution of observing a count `y(i)` in the bin when the expected count is `f(x(i)|p)`.
4029/// The exact likelihood used is the Poisson likelihood described in this paper:
4030/// S. Baker and R. D. Cousins, “Clarification of the use of chi-square and likelihood functions in fits to histograms,”
4031/// Nucl. Instrum. Meth. 221 (1984) 437.
4032///
4033/// \f[
4034/// NLL = \sum_{i}{( f(x(i) | p ) + y(i)\log(y(i)/ f(x(i) | p )) - y(i)) }
4035/// \f]
4036/// By using this formulation, `2*NLL` can be interpreted as the chi-square resulting from the fit.
4037///
4038/// This method should be always used when the bin content represents counts (i.e. errors are sqrt(N) ).
4039/// The likelihood method has the advantage of treating correctly bins with low statistics. In case of high
4040/// statistics/bin the distribution of the bin content becomes a normal distribution and the likelihood and the chi2 fit
4041/// give the same result.
4042///
4043/// The likelihood method, although a bit slower, it is therefore the recommended method,
4044/// when the histogram represent counts (Poisson statistics), where the chi-square methods may
4045/// give incorrect results, especially in case of low statistics.
4046/// In case of a weighted histogram, it is possible to perform also a likelihood fit by using the
4047/// option "WL". Note a weighted histogram is a histogram which has been filled with weights and it
4048/// has the information on the sum of the weight square for each bin ( TH1::Sumw2() has been called).
4049/// The bin error for a weighted histogram is the square root of the sum of the weight square.
4050///
4051/// \anchor HFitRes
4052/// ### Fit Result
4053///
4054/// The function returns a TFitResultPtr which can hold a pointer to a TFitResult object.
4055/// By default the TFitResultPtr contains only the status of the fit which is return by an
4056/// automatic conversion of the TFitResultPtr to an integer. One can write in this case directly:
4057///
4058/// ~~~ {.cpp}
4059/// Int_t fitStatus = h->Fit(myFunc);
4060/// ~~~
4061///
4062/// If the option "S" is instead used, TFitResultPtr behaves as a smart
4063/// pointer to the TFitResult object. This is useful for retrieving the full result information from the fit, such as the covariance matrix,
4064/// as shown in this example code:
4065///
4066/// ~~~ {.cpp}
4067/// TFitResultPtr r = h->Fit(myFunc,"S");
4068/// TMatrixDSym cov = r->GetCovarianceMatrix(); // to access the covariance matrix
4069/// Double_t chi2 = r->Chi2(); // to retrieve the fit chi2
4070/// Double_t par0 = r->Parameter(0); // retrieve the value for the parameter 0
4071/// Double_t err0 = r->ParError(0); // retrieve the error for the parameter 0
4072/// r->Print("V"); // print full information of fit including covariance matrix
4073/// r->Write(); // store the result in a file
4074/// ~~~
4075///
4076/// The fit parameters, error and chi-square (but not covariance matrix) can be retrieved also
4077/// directly from the fitted function that is passed to this call.
4078/// Given a pointer to an associated fitted function `myfunc`, one can retrieve the function/fit
4079/// parameters with calls such as:
4080///
4081/// ~~~ {.cpp}
4082/// Double_t chi2 = myfunc->GetChisquare();
4083/// Double_t par0 = myfunc->GetParameter(0); //value of 1st parameter
4084/// Double_t err0 = myfunc->GetParError(0); //error on first parameter
4085/// ~~~
4086///
4087/// ##### Associated functions
4088///
4089/// One or more object ( can be added to the list
4090/// of functions (fFunctions) associated to each histogram.
4091/// When TH1::Fit is invoked, the fitted function is added to the histogram list of functions (fFunctions).
4092/// If the histogram is made persistent, the list of associated functions is also persistent.
4093/// Given a histogram h, one can retrieve an associated function with:
4094///
4095/// ~~~ {.cpp}
4096/// TF1 *myfunc = h->GetFunction("myfunc");
4097/// ~~~
4098/// or by quering directly the list obtained by calling `TH1::GetListOfFunctions`.
4099///
4100/// \anchor HFitStatus
4101/// ### Fit status
4102///
4103/// The status of the fit is obtained converting the TFitResultPtr to an integer
4104/// independently if the fit option "S" is used or not:
4105///
4106/// ~~~ {.cpp}
4107/// TFitResultPtr r = h->Fit(myFunc,opt);
4108/// Int_t fitStatus = r;
4109/// ~~~
4110///
4111/// - `status = 0` : the fit has been performed successfully (i.e no error occurred).
4112/// - `status < 0` : there is an error not connected with the minimization procedure, for example when a wrong function is used.
4113/// - `status > 0` : return status from Minimizer, depends on used Minimizer. For example for TMinuit and Minuit2 we have:
4114/// - `status = migradStatus + 10*minosStatus + 100*hesseStatus + 1000*improveStatus`.
4115/// TMinuit returns 0 (for migrad, minos, hesse or improve) in case of success and 4 in case of error (see the documentation of TMinuit::mnexcm). For example, for an error
4116/// only in Minos but not in Migrad a fitStatus of 40 will be returned.
4117/// Minuit2 returns 0 in case of success and different values in migrad,minos or
4118/// hesse depending on the error. See in this case the documentation of
4119/// Minuit2Minimizer::Minimize for the migrad return status, Minuit2Minimizer::GetMinosError for the
4120/// minos return status and Minuit2Minimizer::Hesse for the hesse return status.
4121/// If other minimizers are used see their specific documentation for the status code returned.
4122/// For example in the case of Fumili, see TFumili::Minimize.
4123///
4124/// \anchor HFitRange
4125/// ### Fitting in a range
4126///
4127/// In order to fit in a sub-range of the histogram you have two options:
4128/// - pass to this function the lower (`xxmin`) and upper (`xxmax`) values for the fitting range;
4129/// - define a specific range in the fitted function and use the fitting option "R".
4130/// For example, if your histogram has a defined range between -4 and 4 and you want to fit a gaussian
4131/// only in the interval 1 to 3, you can do:
4132///
4133/// ~~~ {.cpp}
4134/// TF1 *f1 = new TF1("f1", "gaus", 1, 3);
4135/// histo->Fit("f1", "R");
4136/// ~~~
4137///
4138/// The fitting range is also limited by the histogram range defined using TAxis::SetRange
4139/// or TAxis::SetRangeUser. Therefore the fitting range is the smallest range between the
4140/// histogram one and the one defined by one of the two previous options described above.
4141///
4142/// \anchor HFitInitial
4143/// ### Setting initial conditions
4144///
4145/// Parameters must be initialized before invoking the Fit function.
4146/// The setting of the parameter initial values is automatic for the
4147/// predefined functions such as poln, expo, gaus, landau. One can however disable
4148/// this automatic computation by using the option "B".
4149/// Note that if a predefined function is defined with an argument,
4150/// eg, gaus(0), expo(1), you must specify the initial values for
4151/// the parameters.
4152/// You can specify boundary limits for some or all parameters via
4153///
4154/// ~~~ {.cpp}
4155/// f1->SetParLimits(p_number, parmin, parmax);
4156/// ~~~
4157///
4158/// if `parmin >= parmax`, the parameter is fixed
4159/// Note that you are not forced to fix the limits for all parameters.
4160/// For example, if you fit a function with 6 parameters, you can do:
4161///
4162/// ~~~ {.cpp}
4163/// func->SetParameters(0, 3.1, 1.e-6, -8, 0, 100);
4164/// func->SetParLimits(3, -10, -4);
4165/// func->FixParameter(4, 0);
4166/// func->SetParLimits(5, 1, 1);
4167/// ~~~
4168///
4169/// With this setup, parameters 0->2 can vary freely
4170/// Parameter 3 has boundaries [-10,-4] with initial value -8
4171/// Parameter 4 is fixed to 0
4172/// Parameter 5 is fixed to 100.
4173/// When the lower limit and upper limit are equal, the parameter is fixed.
4174/// However to fix a parameter to 0, one must call the FixParameter function.
4175///
4176/// \anchor HFitStatBox
4177/// ### Fit Statistics Box
4178///
4179/// The statistics box can display the result of the fit.
4180/// You can change the statistics box to display the fit parameters with
4181/// the TStyle::SetOptFit(mode) method. This mode has four digits.
4182/// mode = pcev (default = 0111)
4183///
4184/// v = 1; print name/values of parameters
4185/// e = 1; print errors (if e=1, v must be 1)
4186/// c = 1; print Chisquare/Number of degrees of freedom
4187/// p = 1; print Probability
4188///
4189/// For example: gStyle->SetOptFit(1011);
4190/// prints the fit probability, parameter names/values, and errors.
4191/// You can change the position of the statistics box with these lines
4192/// (where g is a pointer to the TGraph):
4193///
4194/// TPaveStats *st = (TPaveStats*)g->GetListOfFunctions()->FindObject("stats");
4195/// st->SetX1NDC(newx1); //new x start position
4196/// st->SetX2NDC(newx2); //new x end position
4197///
4198/// \anchor HFitExtra
4199/// ### Additional Notes on Fitting
4200///
4201/// #### Fitting a histogram of dimension N with a function of dimension N-1
4202///
4203/// It is possible to fit a TH2 with a TF1 or a TH3 with a TF2.
4204/// In this case the chi-square is computed from the squared error distance between the function values and the bin centers weighted by the bin content.
4205/// For correct error scaling, the obtained parameter error are corrected as in the case when the
4206/// option "W" is used.
4207///
4208/// #### User defined objective functions
4209///
4210/// By default when fitting a chi square function is used for fitting. When option "L" is used
4211/// a Poisson likelihood function is used. Using option "MULTI" a multinomial likelihood fit is used.
4212/// Thes functions are defined in the header Fit/Chi2Func.h or Fit/PoissonLikelihoodFCN and they
4213/// are implemented using the routines FitUtil::EvaluateChi2 or FitUtil::EvaluatePoissonLogL in
4214/// the file math/mathcore/src/FitUtil.cxx.
4215/// It is possible to specify a user defined fitting function, using option "U" and
4216/// calling the following functions:
4217///
4218/// ~~~ {.cpp}
4219/// TVirtualFitter::Fitter(myhist)->SetFCN(MyFittingFunction);
4220/// ~~~
4221///
4222/// where MyFittingFunction is of type:
4223///
4224/// ~~~ {.cpp}
4225/// extern void MyFittingFunction(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag);
4226/// ~~~
4227///
4228/// #### Note on treatment of empty bins
4229///
4230/// Empty bins, which have the content equal to zero AND error equal to zero,
4231/// are excluded by default from the chi-square fit, but they are considered in the likelihood fit.
4232/// since they affect the likelihood if the function value in these bins is not negligible.
4233/// Note that if the histogram is having bins with zero content and non zero-errors they are considered as
4234/// any other bins in the fit. Instead bins with zero error and non-zero content are by default excluded in the chi-squared fit.
4235/// In general, one should not fit a histogram with non-empty bins and zero errors.
4236///
4237/// If the bin errors are not known, one should use the fit option "W", which gives a weight=1 for each bin (it is an unweighted least-square
4238/// fit). When using option "WW" the empty bins will be also considered in the chi-square fit with an error of 1.
4239/// Note that in this fitting case (option "W" or "WW") the resulting fitted parameter errors
4240/// are corrected by the obtained chi2 value using this scaling expression:
4241/// `errorp *= sqrt(chisquare/(ndf-1))` as it is done when fitting a TGraph with
4242/// no point errors.
4243///
4244/// #### Excluding points
4245///
4246/// You can use TF1::RejectPoint inside your fitting function to exclude some points
4247/// within a certain range from the fit. See the tutorial `fit/fitExclude.C`.
4248///
4249///
4250/// #### Warning when using the option "0"
4251///
4252/// When selecting the option "0", the fitted function is added to
4253/// the list of functions of the histogram, but it is not drawn when the histogram is drawn.
4254/// You can undo this behaviour resetting its corresponding bit in the TF1 object as following:
4255///
4256/// ~~~ {.cpp}
4257/// h.Fit("myFunction", "0"); // fit, store function but do not draw
4258/// h.Draw(); // function is not drawn
4259/// h.GetFunction("myFunction")->ResetBit(TF1::kNotDraw);
4260/// h.Draw(); // function is visible again
4261/// ~~~
4263
4265{
4266 // implementation of Fit method is in file hist/src/HFitImpl.cxx
4267 Foption_t fitOption;
4269
4270 // create range and minimizer options with default values
4271 ROOT::Fit::DataRange range(xxmin,xxmax);
4273
4274 // need to empty the buffer before
4275 // (t.b.d. do a ML unbinned fit with buffer data)
4276 if (fBuffer) BufferEmpty();
4277
4278 return ROOT::Fit::FitObject(this, f1 , fitOption , minOption, goption, range);
4279}
4280
4281////////////////////////////////////////////////////////////////////////////////
4282/// Display a panel with all histogram fit options.
4283///
4284/// See class TFitPanel for example
4285
4286void TH1::FitPanel()
4287{
4288 if (!gPad)
4289 gROOT->MakeDefCanvas();
4290
4291 if (!gPad) {
4292 Error("FitPanel", "Unable to create a default canvas");
4293 return;
4294 }
4295
4296
4297 // use plugin manager to create instance of TFitEditor
4298 TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TFitEditor");
4299 if (handler && handler->LoadPlugin() != -1) {
4300 if (handler->ExecPlugin(2, gPad, this) == 0)
4301 Error("FitPanel", "Unable to create the FitPanel");
4302 }
4303 else
4304 Error("FitPanel", "Unable to find the FitPanel plug-in");
4305}
4306
4307////////////////////////////////////////////////////////////////////////////////
4308/// Return a histogram containing the asymmetry of this histogram with h2,
4309/// where the asymmetry is defined as:
4310///
4311/// ~~~ {.cpp}
4312/// Asymmetry = (h1 - h2)/(h1 + h2) where h1 = this
4313/// ~~~
4314///
4315/// works for 1D, 2D, etc. histograms
4316/// c2 is an optional argument that gives a relative weight between the two
4317/// histograms, and dc2 is the error on this weight. This is useful, for example,
4318/// when forming an asymmetry between two histograms from 2 different data sets that
4319/// need to be normalized to each other in some way. The function calculates
4320/// the errors assuming Poisson statistics on h1 and h2 (that is, dh = sqrt(h)).
4321///
4322/// example: assuming 'h1' and 'h2' are already filled
4323///
4324/// ~~~ {.cpp}
4325/// h3 = h1->GetAsymmetry(h2)
4326/// ~~~
4327///
4328/// then 'h3' is created and filled with the asymmetry between 'h1' and 'h2';
4329/// h1 and h2 are left intact.
4330///
4331/// Note that it is the user's responsibility to manage the created histogram.
4332/// The name of the returned histogram will be `Asymmetry_nameOfh1-nameOfh2`
4333///
4334/// code proposed by Jason Seely (seely@mit.edu) and adapted by R.Brun
4335///
4336/// clone the histograms so top and bottom will have the
4337/// correct dimensions:
4338/// Sumw2 just makes sure the errors will be computed properly
4339/// when we form sums and ratios below.
4340
4342{
4343 TH1 *h1 = this;
4344 TString name = TString::Format("Asymmetry_%s-%s",h1->GetName(),h2->GetName() );
4345 TH1 *asym = (TH1*)Clone(name);
4346
4347 // set also the title
4348 TString title = TString::Format("(%s - %s)/(%s+%s)",h1->GetName(),h2->GetName(),h1->GetName(),h2->GetName() );
4349 asym->SetTitle(title);
4350
4351 asym->Sumw2();
4352 Bool_t addStatus = TH1::AddDirectoryStatus();
4354 TH1 *top = (TH1*)asym->Clone();
4355 TH1 *bottom = (TH1*)asym->Clone();
4356 TH1::AddDirectory(addStatus);
4357
4358 // form the top and bottom of the asymmetry, and then divide:
4359 top->Add(h1,h2,1,-c2);
4360 bottom->Add(h1,h2,1,c2);
4361 asym->Divide(top,bottom);
4362
4363 Int_t xmax = asym->GetNbinsX();
4364 Int_t ymax = asym->GetNbinsY();
4365 Int_t zmax = asym->GetNbinsZ();
4366
4367 if (h1->fBuffer) h1->BufferEmpty(1);
4368 if (h2->fBuffer) h2->BufferEmpty(1);
4369 if (bottom->fBuffer) bottom->BufferEmpty(1);
4370
4371 // now loop over bins to calculate the correct errors
4372 // the reason this error calculation looks complex is because of c2
4373 for(Int_t i=1; i<= xmax; i++){
4374 for(Int_t j=1; j<= ymax; j++){
4375 for(Int_t k=1; k<= zmax; k++){
4376 Int_t bin = GetBin(i, j, k);
4377 // here some bin contents are written into variables to make the error
4378 // calculation a little more legible:
4380 Double_t b = h2->RetrieveBinContent(bin);
4381 Double_t bot = bottom->RetrieveBinContent(bin);
4382
4383 // make sure there are some events, if not, then the errors are set = 0
4384 // automatically.
4385 //if(bot < 1){} was changed to the next line from recommendation of Jason Seely (28 Nov 2005)
4386 if(bot < 1e-6){}
4387 else{
4388 // computation of errors by Christos Leonidopoulos
4389 Double_t dasq = h1->GetBinErrorSqUnchecked(bin);
4390 Double_t dbsq = h2->GetBinErrorSqUnchecked(bin);
4391 Double_t error = 2*TMath::Sqrt(a*a*c2*c2*dbsq + c2*c2*b*b*dasq+a*a*b*b*dc2*dc2)/(bot*bot);
4392 asym->SetBinError(i,j,k,error);
4393 }
4394 }
4395 }
4396 }
4397 delete top;
4398 delete bottom;
4399
4400 return asym;
4401}
4402
4403////////////////////////////////////////////////////////////////////////////////
4404/// Static function
4405/// return the default buffer size for automatic histograms
4406/// the parameter fgBufferSize may be changed via SetDefaultBufferSize
4407
4409{
4410 return fgBufferSize;
4411}
4412
4413////////////////////////////////////////////////////////////////////////////////
4414/// Return kTRUE if TH1::Sumw2 must be called when creating new histograms.
4415/// see TH1::SetDefaultSumw2.
4416
4418{
4419 return fgDefaultSumw2;
4420}
4421
4422////////////////////////////////////////////////////////////////////////////////
4423/// Return the current number of entries.
4424
4426{
4427 if (fBuffer) {
4428 Int_t nentries = (Int_t) fBuffer[0];
4429 if (nentries > 0) return nentries;
4430 }
4431
4432 return fEntries;
4433}
4434
4435////////////////////////////////////////////////////////////////////////////////
4436/// Number of effective entries of the histogram.
4437///
4438/// \f[
4439/// neff = \frac{(\sum Weights )^2}{(\sum Weight^2 )}
4440/// \f]
4441///
4442/// In case of an unweighted histogram this number is equivalent to the
4443/// number of entries of the histogram.
4444/// For a weighted histogram, this number corresponds to the hypothetical number of unweighted entries
4445/// a histogram would need to have the same statistical power as this weighted histogram.
4446/// Note: The underflow/overflow are included if one has set the TH1::StatOverFlows flag
4447/// and if the statistics has been computed at filling time.
4448/// If a range is set in the histogram the number is computed from the given range.
4449
4451{
4452 Stat_t s[kNstat];
4453 this->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
4454 return (s[1] ? s[0]*s[0]/s[1] : TMath::Abs(s[0]) );
4455}
4456
4457////////////////////////////////////////////////////////////////////////////////
4458/// Set highlight (enable/disable) mode for the histogram
4459/// by default highlight mode is disable
4460
4461void TH1::SetHighlight(Bool_t set)
4462{
4463 if (IsHighlight() == set)
4464 return;
4465 if (fDimension > 2) {
4466 Info("SetHighlight", "Supported only 1-D or 2-D histograms");
4467 return;
4468 }
4469
4470 SetBit(kIsHighlight, set);
4471
4472 if (fPainter)
4474}
4475
4476////////////////////////////////////////////////////////////////////////////////
4477/// Redefines TObject::GetObjectInfo.
4478/// Displays the histogram info (bin number, contents, integral up to bin
4479/// corresponding to cursor position px,py
4480
4481char *TH1::GetObjectInfo(Int_t px, Int_t py) const
4482{
4483 return ((TH1*)this)->GetPainter()->GetObjectInfo(px,py);
4484}
4485
4486////////////////////////////////////////////////////////////////////////////////
4487/// Return pointer to painter.
4488/// If painter does not exist, it is created
4489
4491{
4492 if (!fPainter) {
4493 TString opt = option;
4494 opt.ToLower();
4495 if (opt.Contains("gl") || gStyle->GetCanvasPreferGL()) {
4496 //try to create TGLHistPainter
4497 TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TGLHistPainter");
4498
4499 if (handler && handler->LoadPlugin() != -1)
4500 fPainter = reinterpret_cast<TVirtualHistPainter *>(handler->ExecPlugin(1, this));
4501 }
4502 }
4503
4505
4506 return fPainter;
4507}
4508
4509////////////////////////////////////////////////////////////////////////////////
4510/// Compute Quantiles for this histogram
4511/// Quantile x_q of a probability distribution Function F is defined as
4512///
4513/// ~~~ {.cpp}
4514/// F(x_q) = q with 0 <= q <= 1.
4515/// ~~~
4516///
4517/// For instance the median x_0.5 of a distribution is defined as that value
4518/// of the random variable for which the distribution function equals 0.5:
4519///
4520/// ~~~ {.cpp}
4521/// F(x_0.5) = Probability(x < x_0.5) = 0.5
4522/// ~~~
4523///
4524/// code from Eddy Offermann, Renaissance
4525///
4526/// \param[in] nprobSum maximum size of array q and size of array probSum (if given)
4527/// \param[in] probSum array of positions where quantiles will be computed.
4528/// - if probSum is null, probSum will be computed internally and will
4529/// have a size = number of bins + 1 in h. it will correspond to the
4530/// quantiles calculated at the lowest edge of the histogram (quantile=0) and
4531/// all the upper edges of the bins.
4532/// - if probSum is not null, it is assumed to contain at least nprobSum values.
4533/// \param[out] q array q filled with nq quantiles
4534/// \return value nq (<=nprobSum) with the number of quantiles computed
4535///
4536/// Note that the Integral of the histogram is automatically recomputed
4537/// if the number of entries is different of the number of entries when
4538/// the integral was computed last time. In case you do not use the Fill
4539/// functions to fill your histogram, but SetBinContent, you must call
4540/// TH1::ComputeIntegral before calling this function.
4541///
4542/// Getting quantiles q from two histograms and storing results in a TGraph,
4543/// a so-called QQ-plot
4544///
4545/// ~~~ {.cpp}
4546/// TGraph *gr = new TGraph(nprob);
4547/// h1->GetQuantiles(nprob,gr->GetX());
4548/// h2->GetQuantiles(nprob,gr->GetY());
4549/// gr->Draw("alp");
4550/// ~~~
4551///
4552/// Example:
4553///
4554/// ~~~ {.cpp}
4555/// void quantiles() {
4556/// // demo for quantiles
4557/// const Int_t nq = 20;
4558/// TH1F *h = new TH1F("h","demo quantiles",100,-3,3);
4559/// h->FillRandom("gaus",5000);
4560///
4561/// Double_t xq[nq]; // position where to compute the quantiles in [0,1]
4562/// Double_t yq[nq]; // array to contain the quantiles
4563/// for (Int_t i=0;i<nq;i++) xq[i] = Float_t(i+1)/nq;
4564/// h->GetQuantiles(nq,yq,xq);
4565///
4566/// //show the original histogram in the top pad
4567/// TCanvas *c1 = new TCanvas("c1","demo quantiles",10,10,700,900);
4568/// c1->Divide(1,2);
4569/// c1->cd(1);
4570/// h->Draw();
4571///
4572/// // show the quantiles in the bottom pad
4573/// c1->cd(2);
4574/// gPad->SetGrid();
4575/// TGraph *gr = new TGraph(nq,xq,yq);
4576/// gr->SetMarkerStyle(21);
4577/// gr->Draw("alp");
4578/// }
4579/// ~~~
4580
4581Int_t TH1::GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum)
4582{
4583 if (GetDimension() > 1) {
4584 Error("GetQuantiles","Only available for 1-d histograms");
4585 return 0;
4586 }
4587
4588 const Int_t nbins = GetXaxis()->GetNbins();
4589 if (!fIntegral) ComputeIntegral();
4590 if (fIntegral[nbins+1] != fEntries) ComputeIntegral();
4591
4592 Int_t i, ibin;
4593 Double_t *prob = (Double_t*)probSum;
4594 Int_t nq = nprobSum;
4595 if (probSum == nullptr) {
4596 nq = nbins+1;
4597 prob = new Double_t[nq];
4598 prob[0] = 0;
4599 for (i=1;i<nq;i++) {
4600 prob[i] = fIntegral[i]/fIntegral[nbins];
4601 }
4602 }
4603
4604 for (i = 0; i < nq; i++) {
4605 ibin = TMath::BinarySearch(nbins,fIntegral,prob[i]);
4606 while (ibin < nbins-1 && fIntegral[ibin+1] == prob[i]) {
4607 if (fIntegral[ibin+2] == prob[i]) ibin++;
4608 else break;
4609 }
4610 q[i] = GetBinLowEdge(ibin+1);
4611 const Double_t dint = fIntegral[ibin+1]-fIntegral[ibin];
4612 if (dint > 0) q[i] += GetBinWidth(ibin+1)*(prob[i]-fIntegral[ibin])/dint;
4613 }
4614
4615 if (!probSum) delete [] prob;
4616 return nq;
4617}
4618
4619////////////////////////////////////////////////////////////////////////////////
4620/// Decode string choptin and fill fitOption structure.
4621
4622Int_t TH1::FitOptionsMake(Option_t *choptin, Foption_t &fitOption)
4623{
4625 return 1;
4626}
4627
4628////////////////////////////////////////////////////////////////////////////////
4629/// Compute Initial values of parameters for a gaussian.
4630
4631void H1InitGaus()
4632{
4633 Double_t allcha, sumx, sumx2, x, val, stddev, mean;
4634 Int_t bin;
4635 const Double_t sqrtpi = 2.506628;
4636
4637 // - Compute mean value and StdDev of the histogram in the given range
4639 TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4640 Int_t hxfirst = hFitter->GetXfirst();
4641 Int_t hxlast = hFitter->GetXlast();
4642 Double_t valmax = curHist->GetBinContent(hxfirst);
4643 Double_t binwidx = curHist->GetBinWidth(hxfirst);
4644 allcha = sumx = sumx2 = 0;
4645 for (bin=hxfirst;bin<=hxlast;bin++) {
4646 x = curHist->GetBinCenter(bin);
4647 val = TMath::Abs(curHist->GetBinContent(bin));
4648 if (val > valmax) valmax = val;
4649 sumx += val*x;
4650 sumx2 += val*x*x;
4651 allcha += val;
4652 }
4653 if (allcha == 0) return;
4654 mean = sumx/allcha;
4655 stddev = sumx2/allcha - mean*mean;
4656 if (stddev > 0) stddev = TMath::Sqrt(stddev);
4657 else stddev = 0;
4658 if (stddev == 0) stddev = binwidx*(hxlast-hxfirst+1)/4;
4659 //if the distribution is really gaussian, the best approximation
4660 //is binwidx*allcha/(sqrtpi*stddev)
4661 //However, in case of non-gaussian tails, this underestimates
4662 //the normalisation constant. In this case the maximum value
4663 //is a better approximation.
4664 //We take the average of both quantities
4665 Double_t constant = 0.5*(valmax+binwidx*allcha/(sqrtpi*stddev));
4666
4667 //In case the mean value is outside the histo limits and
4668 //the StdDev is bigger than the range, we take
4669 // mean = center of bins
4670 // stddev = half range
4671 Double_t xmin = curHist->GetXaxis()->GetXmin();
4672 Double_t xmax = curHist->GetXaxis()->GetXmax();
4673 if ((mean < xmin || mean > xmax) && stddev > (xmax-xmin)) {
4674 mean = 0.5*(xmax+xmin);
4675 stddev = 0.5*(xmax-xmin);
4676 }
4677 TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4678 f1->SetParameter(0,constant);
4679 f1->SetParameter(1,mean);
4680 f1->SetParameter(2,stddev);
4681 f1->SetParLimits(2,0,10*stddev);
4682}
4683
4684////////////////////////////////////////////////////////////////////////////////
4685/// Compute Initial values of parameters for an exponential.
4686
4687void H1InitExpo()
4688{
4689 Double_t constant, slope;
4690 Int_t ifail;
4692 Int_t hxfirst = hFitter->GetXfirst();
4693 Int_t hxlast = hFitter->GetXlast();
4694 Int_t nchanx = hxlast - hxfirst + 1;
4695
4696 H1LeastSquareLinearFit(-nchanx, constant, slope, ifail);
4697
4698 TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4699 f1->SetParameter(0,constant);
4700 f1->SetParameter(1,slope);
4701
4702}
4703
4704////////////////////////////////////////////////////////////////////////////////
4705/// Compute Initial values of parameters for a polynom.
4706
4707void H1InitPolynom()
4708{
4709 Double_t fitpar[25];
4710
4712 TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4713 Int_t hxfirst = hFitter->GetXfirst();
4714 Int_t hxlast = hFitter->GetXlast();
4715 Int_t nchanx = hxlast - hxfirst + 1;
4716 Int_t npar = f1->GetNpar();
4717
4718 if (nchanx <=1 || npar == 1) {
4719 TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4720 fitpar[0] = curHist->GetSumOfWeights()/Double_t(nchanx);
4721 } else {
4722 H1LeastSquareFit( nchanx, npar, fitpar);
4723 }
4724 for (Int_t i=0;i<npar;i++) f1->SetParameter(i, fitpar[i]);
4725}
4726
4727////////////////////////////////////////////////////////////////////////////////
4728/// Least squares lpolynomial fitting without weights.
4729///
4730/// \param[in] n number of points to fit
4731/// \param[in] m number of parameters
4732/// \param[in] a array of parameters
4733///
4734/// based on CERNLIB routine LSQ: Translated to C++ by Rene Brun
4735/// (E.Keil. revised by B.Schorr, 23.10.1981.)
4736
4738{
4739 const Double_t zero = 0.;
4740 const Double_t one = 1.;
4741 const Int_t idim = 20;
4742
4743 Double_t b[400] /* was [20][20] */;
4744 Int_t i, k, l, ifail;
4745 Double_t power;
4746 Double_t da[20], xk, yk;
4747
4748 if (m <= 2) {
4749 H1LeastSquareLinearFit(n, a[0], a[1], ifail);
4750 return;
4751 }
4752 if (m > idim || m > n) return;
4753 b[0] = Double_t(n);
4754 da[0] = zero;
4755 for (l = 2; l <= m; ++l) {
4756 b[l-1] = zero;
4757 b[m + l*20 - 21] = zero;
4758 da[l-1] = zero;
4759 }
4761 TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4762 Int_t hxfirst = hFitter->GetXfirst();
4763 Int_t hxlast = hFitter->GetXlast();
4764 for (k = hxfirst; k <= hxlast; ++k) {
4765 xk = curHist->GetBinCenter(k);
4766 yk = curHist->GetBinContent(k);
4767 power = one;
4768 da[0] += yk;
4769 for (l = 2; l <= m; ++l) {
4770 power *= xk;
4771 b[l-1] += power;
4772 da[l-1] += power*yk;
4773 }
4774 for (l = 2; l <= m; ++l) {
4775 power *= xk;
4776 b[m + l*20 - 21] += power;
4777 }
4778 }
4779 for (i = 3; i <= m; ++i) {
4780 for (k = i; k <= m; ++k) {
4781 b[k - 1 + (i-1)*20 - 21] = b[k + (i-2)*20 - 21];
4782 }
4783 }
4784 H1LeastSquareSeqnd(m, b, idim, ifail, 1, da);
4785
4786 for (i=0; i<m; ++i) a[i] = da[i];
4787
4788}
4789
4790////////////////////////////////////////////////////////////////////////////////
4791/// Least square linear fit without weights.
4792///
4793/// extracted from CERNLIB LLSQ: Translated to C++ by Rene Brun
4794/// (added to LSQ by B. Schorr, 15.02.1982.)
4795
4796void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
4797{
4798 Double_t xbar, ybar, x2bar;
4799 Int_t i, n;
4800 Double_t xybar;
4801 Double_t fn, xk, yk;
4802 Double_t det;
4803
4804 n = TMath::Abs(ndata);
4805 ifail = -2;
4806 xbar = ybar = x2bar = xybar = 0;
4808 TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4809 Int_t hxfirst = hFitter->GetXfirst();
4810 Int_t hxlast = hFitter->GetXlast();
4811 for (i = hxfirst; i <= hxlast; ++i) {
4812 xk = curHist->GetBinCenter(i);
4813 yk = curHist->GetBinContent(i);
4814 if (ndata < 0) {
4815 if (yk <= 0) yk = 1e-9;
4816 yk = TMath::Log(yk);
4817 }
4818 xbar += xk;
4819 ybar += yk;
4820 x2bar += xk*xk;
4821 xybar += xk*yk;
4822 }
4823 fn = Double_t(n);
4824 det = fn*x2bar - xbar*xbar;
4825 ifail = -1;
4826 if (det <= 0) {
4827 a0 = ybar/fn;
4828 a1 = 0;
4829 return;
4830 }
4831 ifail = 0;
4832 a0 = (x2bar*ybar - xbar*xybar) / det;
4833 a1 = (fn*xybar - xbar*ybar) / det;
4834
4835}
4836
4837////////////////////////////////////////////////////////////////////////////////
4838/// Extracted from CERN Program library routine DSEQN.
4839///
4840/// Translated to C++ by Rene Brun
4841
4842void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b)
4843{
4844 Int_t a_dim1, a_offset, b_dim1, b_offset;
4845 Int_t nmjp1, i, j, l;
4846 Int_t im1, jp1, nm1, nmi;
4847 Double_t s1, s21, s22;
4848 const Double_t one = 1.;
4849
4850 /* Parameter adjustments */
4851 b_dim1 = idim;
4852 b_offset = b_dim1 + 1;
4853 b -= b_offset;
4854 a_dim1 = idim;
4855 a_offset = a_dim1 + 1;
4856 a -= a_offset;
4857
4858 if (idim < n) return;
4859
4860 ifail = 0;
4861 for (j = 1; j <= n; ++j) {
4862 if (a[j + j*a_dim1] <= 0) { ifail = -1; return; }
4863 a[j + j*a_dim1] = one / a[j + j*a_dim1];
4864 if (j == n) continue;
4865 jp1 = j + 1;
4866 for (l = jp1; l <= n; ++l) {
4867 a[j + l*a_dim1] = a[j + j*a_dim1] * a[l + j*a_dim1];
4868 s1 = -a[l + (j+1)*a_dim1];
4869 for (i = 1; i <= j; ++i) { s1 = a[l + i*a_dim1] * a[i + (j+1)*a_dim1] + s1; }
4870 a[l + (j+1)*a_dim1] = -s1;
4871 }
4872 }
4873 if (k <= 0) return;
4874
4875 for (l = 1; l <= k; ++l) {
4876 b[l*b_dim1 + 1] = a[a_dim1 + 1]*b[l*b_dim1 + 1];
4877 }
4878 if (n == 1) return;
4879 for (l = 1; l <= k; ++l) {
4880 for (i = 2; i <= n; ++i) {
4881 im1 = i - 1;
4882 s21 = -b[i + l*b_dim1];
4883 for (j = 1; j <= im1; ++j) {
4884 s21 = a[i + j*a_dim1]*b[j + l*b_dim1] + s21;
4885 }
4886 b[i + l*b_dim1] = -a[i + i*a_dim1]*s21;
4887 }
4888 nm1 = n - 1;
4889 for (i = 1; i <= nm1; ++i) {
4890 nmi = n - i;
4891 s22 = -b[nmi + l*b_dim1];
4892 for (j = 1; j <= i; ++j) {
4893 nmjp1 = n - j + 1;
4894 s22 = a[nmi + nmjp1*a_dim1]*b[nmjp1 + l*b_dim1] + s22;
4895 }
4896 b[nmi + l*b_dim1] = -s22;
4897 }
4898 }
4899}
4900
4901////////////////////////////////////////////////////////////////////////////////
4902/// Return Global bin number corresponding to binx,y,z.
4903///
4904/// 2-D and 3-D histograms are represented with a one dimensional
4905/// structure.
4906/// This has the advantage that all existing functions, such as
4907/// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
4908///
4909/// In case of a TH1x, returns binx directly.
4910/// see TH1::GetBinXYZ for the inverse transformation.
4911///
4912/// Convention for numbering bins
4913///
4914/// For all histogram types: nbins, xlow, xup
4915///
4916/// - bin = 0; underflow bin
4917/// - bin = 1; first bin with low-edge xlow INCLUDED
4918/// - bin = nbins; last bin with upper-edge xup EXCLUDED
4919/// - bin = nbins+1; overflow bin
4920///
4921/// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4922/// For example, assuming a 3-D histogram with binx,biny,binz, the function
4923///
4924/// ~~~ {.cpp}
4925/// Int_t bin = h->GetBin(binx,biny,binz);
4926/// ~~~
4927///
4928/// returns a global/linearized bin number. This global bin is useful
4929/// to access the bin information independently of the dimension.
4930
4931Int_t TH1::GetBin(Int_t binx, Int_t, Int_t) const
4932{
4933 Int_t ofx = fXaxis.GetNbins() + 1; // overflow bin
4934 if (binx < 0) binx = 0;
4935 if (binx > ofx) binx = ofx;
4936
4937 return binx;
4938}
4939
4940////////////////////////////////////////////////////////////////////////////////
4941/// Return binx, biny, binz corresponding to the global bin number globalbin
4942/// see TH1::GetBin function above
4943
4944void TH1::GetBinXYZ(Int_t binglobal, Int_t &binx, Int_t &biny, Int_t &binz) const
4945{
4946 Int_t nx = fXaxis.GetNbins()+2;
4947 Int_t ny = fYaxis.GetNbins()+2;
4948
4949 if (GetDimension() == 1) {
4950 binx = binglobal%nx;
4951 biny = 0;
4952 binz = 0;
4953 return;
4954 }
4955 if (GetDimension() == 2) {
4956 binx = binglobal%nx;
4957 biny = ((binglobal-binx)/nx)%ny;
4958 binz = 0;
4959 return;
4960 }
4961 if (GetDimension() == 3) {
4962 binx = binglobal%nx;
4963 biny = ((binglobal-binx)/nx)%ny;
4964 binz = ((binglobal-binx)/nx -biny)/ny;
4965 }
4966}
4967
4968////////////////////////////////////////////////////////////////////////////////
4969/// Return a random number distributed according the histogram bin contents.
4970/// This function checks if the bins integral exists. If not, the integral
4971/// is evaluated, normalized to one.
4972///
4973/// @param rng (optional) Random number generator pointer used (default is gRandom)
4974///
4975/// The integral is automatically recomputed if the number of entries
4976/// is not the same then when the integral was computed.
4977/// NB Only valid for 1-d histograms. Use GetRandom2 or 3 otherwise.
4978/// If the histogram has a bin with negative content a NaN is returned
4979
4980Double_t TH1::GetRandom(TRandom * rng) const
4981{
4982 if (fDimension > 1) {
4983 Error("GetRandom","Function only valid for 1-d histograms");
4984 return 0;
4985 }
4986 Int_t nbinsx = GetNbinsX();
4987 Double_t integral = 0;
4988 // compute integral checking that all bins have positive content (see ROOT-5894)
4989 if (fIntegral) {
4990 if (fIntegral[nbinsx+1] != fEntries) integral = ((TH1*)this)->ComputeIntegral(true);
4991 else integral = fIntegral[nbinsx];
4992 } else {
4993 integral = ((TH1*)this)->ComputeIntegral(true);
4994 }
4995 if (integral == 0) return 0;
4996 // return a NaN in case some bins have negative content
4997 if (integral == TMath::QuietNaN() ) return TMath::QuietNaN();
4998
4999 Double_t r1 = (rng) ? rng->Rndm() : gRandom->Rndm();
5000 Int_t ibin = TMath::BinarySearch(nbinsx,fIntegral,r1);
5001 Double_t x = GetBinLowEdge(ibin+1);
5002 if (r1 > fIntegral[ibin]) x +=
5003 GetBinWidth(ibin+1)*(r1-fIntegral[ibin])/(fIntegral[ibin+1] - fIntegral[ibin]);
5004 return x;
5005}
5006
5007////////////////////////////////////////////////////////////////////////////////
5008/// Return content of bin number bin.
5009///
5010/// Implemented in TH1C,S,F,D
5011///
5012/// Convention for numbering bins
5013///
5014/// For all histogram types: nbins, xlow, xup
5015///
5016/// - bin = 0; underflow bin
5017/// - bin = 1; first bin with low-edge xlow INCLUDED
5018/// - bin = nbins; last bin with upper-edge xup EXCLUDED
5019/// - bin = nbins+1; overflow bin
5020///
5021/// In case of 2-D or 3-D histograms, a "global bin" number is defined.
5022/// For example, assuming a 3-D histogram with binx,biny,binz, the function
5023///
5024/// ~~~ {.cpp}
5025/// Int_t bin = h->GetBin(binx,biny,binz);
5026/// ~~~
5027///
5028/// returns a global/linearized bin number. This global bin is useful
5029/// to access the bin information independently of the dimension.
5030
5032{
5033 if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
5034 if (bin < 0) bin = 0;
5035 if (bin >= fNcells) bin = fNcells-1;
5036
5037 return RetrieveBinContent(bin);
5038}
5039
5040////////////////////////////////////////////////////////////////////////////////
5041/// Compute first binx in the range [firstx,lastx] for which
5042/// diff = abs(bin_content-c) <= maxdiff
5043///
5044/// In case several bins in the specified range with diff=0 are found
5045/// the first bin found is returned in binx.
5046/// In case several bins in the specified range satisfy diff <=maxdiff
5047/// the bin with the smallest difference is returned in binx.
5048/// In all cases the function returns the smallest difference.
5049///
5050/// NOTE1: if firstx <= 0, firstx is set to bin 1
5051/// if (lastx < firstx then firstx is set to the number of bins
5052/// ie if firstx=0 and lastx=0 (default) the search is on all bins.
5053///
5054/// NOTE2: if maxdiff=0 (default), the first bin with content=c is returned.
5055
5056Double_t TH1::GetBinWithContent(Double_t c, Int_t &binx, Int_t firstx, Int_t lastx,Double_t maxdiff) const
5057{
5058 if (fDimension > 1) {
5059 binx = 0;
5060 Error("GetBinWithContent","function is only valid for 1-D histograms");
5061 return 0;
5062 }
5063
5064 if (fBuffer) ((TH1*)this)->BufferEmpty();
5065
5066 if (firstx <= 0) firstx = 1;
5067 if (lastx < firstx) lastx = fXaxis.GetNbins();
5068 Int_t binminx = 0;
5069 Double_t diff, curmax = 1.e240;
5070 for (Int_t i=firstx;i<=lastx;i++) {
5071 diff = TMath::Abs(RetrieveBinContent(i)-c);
5072 if (diff <= 0) {binx = i; return diff;}
5073 if (diff < curmax && diff <= maxdiff) {curmax = diff, binminx=i;}
5074 }
5075 binx = binminx;
5076 return curmax;
5077}
5078
5079////////////////////////////////////////////////////////////////////////////////
5080/// Given a point x, approximates the value via linear interpolation
5081/// based on the two nearest bin centers
5082///
5083/// Andy Mastbaum 10/21/08
5084
5086{
5087 if (fBuffer) ((TH1*)this)->BufferEmpty();
5088
5089 Int_t xbin = fXaxis.FindFixBin(x);
5090 Double_t x0,x1,y0,y1;
5091
5092 if(x<=GetBinCenter(1)) {
5093 return RetrieveBinContent(1);
5094 } else if(x>=GetBinCenter(GetNbinsX())) {
5095 return RetrieveBinContent(GetNbinsX());
5096 } else {
5097 if(x<=GetBinCenter(xbin)) {
5098 y0 = RetrieveBinContent(xbin-1);
5099 x0 = GetBinCenter(xbin-1);
5100 y1 = RetrieveBinContent(xbin);
5101 x1 = GetBinCenter(xbin);
5102 } else {
5103 y0 = RetrieveBinContent(xbin);
5104 x0 = GetBinCenter(xbin);
5105 y1 = RetrieveBinContent(xbin+1);
5106 x1 = GetBinCenter(xbin+1);
5107 }
5108 return y0 + (x-x0)*((y1-y0)/(x1-x0));
5109 }
5110}
5111
5112////////////////////////////////////////////////////////////////////////////////
5113/// 2d Interpolation. Not yet implemented.
5114
5116{
5117 Error("Interpolate","This function must be called with 1 argument for a TH1");
5118 return 0;
5119}
5120
5121////////////////////////////////////////////////////////////////////////////////
5122/// 3d Interpolation. Not yet implemented.
5123
5125{
5126 Error("Interpolate","This function must be called with 1 argument for a TH1");
5127 return 0;
5128}
5129
5130///////////////////////////////////////////////////////////////////////////////
5131/// Check if a histogram is empty
5132/// (this is a protected method used mainly by TH1Merger )
5133
5134Bool_t TH1::IsEmpty() const
5135{
5136 // if fTsumw or fentries are not zero histogram is not empty
5137 // need to use GetEntries() instead of fEntries in case of bugger histograms
5138 // so we will flash the buffer
5139 if (fTsumw != 0) return kFALSE;
5140 if (GetEntries() != 0) return kFALSE;
5141 // case fTSumw == 0 amd entries are also zero
5142 // this should not really happening, but if one sets content by hand
5143 // it can happen. a call to ResetStats() should be done in such cases
5144 double sumw = 0;
5145 for (int i = 0; i< GetNcells(); ++i) sumw += RetrieveBinContent(i);
5146 return (sumw != 0) ? kFALSE : kTRUE;
5147}
5148
5149////////////////////////////////////////////////////////////////////////////////
5150/// Return true if the bin is overflow.
5151
5152Bool_t TH1::IsBinOverflow(Int_t bin, Int_t iaxis) const
5153{
5154 Int_t binx, biny, binz;
5155 GetBinXYZ(bin, binx, biny, binz);
5156
5157 if (iaxis == 0) {
5158 if ( fDimension == 1 )
5159 return binx >= GetNbinsX() + 1;
5160 if ( fDimension == 2 )
5161 return (binx >= GetNbinsX() + 1) ||
5162 (biny >= GetNbinsY() + 1);
5163 if ( fDimension == 3 )
5164 return (binx >= GetNbinsX() + 1) ||
5165 (biny >= GetNbinsY() + 1) ||
5166 (binz >= GetNbinsZ() + 1);
5167 return kFALSE;
5168 }
5169 if (iaxis == 1)
5170 return binx >= GetNbinsX() + 1;
5171 if (iaxis == 2)
5172 return biny >= GetNbinsY() + 1;
5173 if (iaxis == 3)
5174 return binz >= GetNbinsZ() + 1;
5175
5176 Error("IsBinOverflow","Invalid axis value");
5177 return kFALSE;
5178}
5179
5180////////////////////////////////////////////////////////////////////////////////
5181/// Return true if the bin is underflow.
5182/// If iaxis = 0 make OR with all axes otherwise check only for the given axis
5183
5184Bool_t