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 <memory>
21#include <sstream>
22#include <fstream>
23#include <limits>
24#include <iomanip>
25
26#include "TROOT.h"
27#include "TBuffer.h"
28#include "TEnv.h"
29#include "TClass.h"
30#include "TMath.h"
31#include "THashList.h"
32#include "TH1.h"
33#include "TH2.h"
34#include "TH3.h"
35#include "TF2.h"
36#include "TF3.h"
37#include "TPluginManager.h"
38#include "TVirtualPad.h"
39#include "TRandom.h"
40#include "TVirtualFitter.h"
41#include "THLimitsFinder.h"
42#include "TProfile.h"
43#include "TStyle.h"
44#include "TVectorF.h"
45#include "TVectorD.h"
46#include "TBrowser.h"
47#include "TError.h"
48#include "TVirtualHistPainter.h"
49#include "TVirtualFFT.h"
50#include "TVirtualPaveStats.h"
51
52#include "HFitInterface.h"
53#include "Fit/DataRange.h"
54#include "Fit/BinData.h"
55#include "Math/GoFTest.h"
58
59#include "TH1Merger.h"
60
61/** \addtogroup Histograms
62@{
63\class TH1C
64\brief 1-D histogram with a byte per channel (see TH1 documentation)
65\class TH1S
66\brief 1-D histogram with a short per channel (see TH1 documentation)
67\class TH1I
68\brief 1-D histogram with an int per channel (see TH1 documentation)
69\class TH1L
70\brief 1-D histogram with a long64 per channel (see TH1 documentation)
71\class TH1F
72\brief 1-D histogram with a float per channel (see TH1 documentation)
73\class TH1D
74\brief 1-D histogram with a double per channel (see TH1 documentation)
75@}
76*/
77
78/** \class TH1
79 \ingroup Histograms
80TH1 is the base class of all histogram classes in %ROOT.
81
82It provides the common interface for operations such as binning, filling, drawing, which
83will be detailed below.
84
85-# [Creating histograms](\ref creating-histograms)
86 - [Labelling axes](\ref labelling-axis)
87-# [Binning](\ref binning)
88 - [Fix or variable bin size](\ref fix-var)
89 - [Convention for numbering bins](\ref convention)
90 - [Alphanumeric Bin Labels](\ref alpha)
91 - [Histograms with automatic bins](\ref auto-bin)
92 - [Rebinning](\ref rebinning)
93-# [Filling histograms](\ref filling-histograms)
94 - [Associated errors](\ref associated-errors)
95 - [Associated functions](\ref associated-functions)
96 - [Projections of histograms](\ref prof-hist)
97 - [Random Numbers and histograms](\ref random-numbers)
98 - [Making a copy of a histogram](\ref making-a-copy)
99 - [Normalizing histograms](\ref normalizing)
100-# [Drawing histograms](\ref drawing-histograms)
101 - [Setting Drawing histogram contour levels (2-D hists only)](\ref cont-level)
102 - [Setting histogram graphics attributes](\ref graph-att)
103 - [Customising how axes are drawn](\ref axis-drawing)
104-# [Fitting histograms](\ref fitting-histograms)
105-# [Saving/reading histograms to/from a ROOT file](\ref saving-histograms)
106-# [Operations on histograms](\ref operations-on-histograms)
107-# [Miscellaneous operations](\ref misc)
108
109ROOT supports the following histogram types:
110
111 - 1-D histograms:
112 - TH1C : histograms with one byte per channel. Maximum bin content = 127
113 - TH1S : histograms with one short per channel. Maximum bin content = 32767
114 - TH1I : histograms with one int per channel. Maximum bin content = INT_MAX (\ref intmax "*")
115 - TH1L : histograms with one long64 per channel. Maximum bin content = LLONG_MAX (\ref llongmax "**")
116 - TH1F : histograms with one float per channel. Maximum precision 7 digits, maximum integer bin content = +/-16777216 (\ref floatmax "***")
117 - TH1D : histograms with one double per channel. Maximum precision 14 digits, maximum integer bin content = +/-9007199254740992 (\ref doublemax "****")
118 - 2-D histograms:
119 - TH2C : histograms with one byte per channel. Maximum bin content = 127
120 - TH2S : histograms with one short per channel. Maximum bin content = 32767
121 - TH2I : histograms with one int per channel. Maximum bin content = INT_MAX (\ref intmax "*")
122 - TH2L : histograms with one long64 per channel. Maximum bin content = LLONG_MAX (\ref llongmax "**")
123 - TH2F : histograms with one float per channel. Maximum precision 7 digits, maximum integer bin content = +/-16777216 (\ref floatmax "***")
124 - TH2D : histograms with one double per channel. Maximum precision 14 digits, maximum integer bin content = +/-9007199254740992 (\ref doublemax "****")
125 - 3-D histograms:
126 - TH3C : histograms with one byte per channel. Maximum bin content = 127
127 - TH3S : histograms with one short per channel. Maximum bin content = 32767
128 - TH3I : histograms with one int per channel. Maximum bin content = INT_MAX (\ref intmax "*")
129 - TH3L : histograms with one long64 per channel. Maximum bin content = LLONG_MAX (\ref llongmax "**")
130 - TH3F : histograms with one float per channel. Maximum precision 7 digits, maximum integer bin content = +/-16777216 (\ref floatmax "***")
131 - TH3D : histograms with one double per channel. Maximum precision 14 digits, maximum integer bin content = +/-9007199254740992 (\ref doublemax "****")
132 - Profile histograms: See classes TProfile, TProfile2D and TProfile3D.
133 Profile histograms are used to display the mean value of Y and its standard deviation
134 for each bin in X. Profile histograms are in many cases an elegant
135 replacement of two-dimensional histograms : the inter-relation of two
136 measured quantities X and Y can always be visualized by a two-dimensional
137 histogram or scatter-plot; If Y is an unknown (but single-valued)
138 approximate function of X, this function is displayed by a profile
139 histogram with much better precision than by a scatter-plot.
140
141<sup>
142\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)<br>
143\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)<br>
144\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)<br>
145\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)
146</sup>
147
148The inheritance hierarchy looks as follows:
149
150\image html classTH1__inherit__graph_org.svg width=100%
151
152\anchor creating-histograms
153## Creating histograms
154
155Histograms are created by invoking one of the constructors, e.g.
156~~~ {.cpp}
157 TH1F *h1 = new TH1F("h1", "h1 title", 100, 0, 4.4);
158 TH2F *h2 = new TH2F("h2", "h2 title", 40, 0, 4, 30, -3, 3);
159~~~
160Histograms may also be created by:
161
162 - calling the Clone() function, see below
163 - making a projection from a 2-D or 3-D histogram, see below
164 - reading a histogram from a file
165
166 When a histogram is created, a reference to it is automatically added
167 to the list of in-memory objects for the current file or directory.
168 Then the pointer to this histogram in the current directory can be found
169 by its name, doing:
170~~~ {.cpp}
171 TH1F *h1 = (TH1F*)gDirectory->FindObject(name);
172~~~
173
174 This default behaviour can be changed by:
175~~~ {.cpp}
176 h->SetDirectory(nullptr); // for the current histogram h
177 TH1::AddDirectory(kFALSE); // sets a global switch disabling the referencing
178~~~
179 When the histogram is deleted, the reference to it is removed from
180 the list of objects in memory.
181 When a file is closed, all histograms in memory associated with this file
182 are automatically deleted.
183
184\anchor labelling-axis
185### Labelling axes
186
187 Axis titles can be specified in the title argument of the constructor.
188 They must be separated by ";":
189~~~ {.cpp}
190 TH1F* h=new TH1F("h", "Histogram title;X Axis;Y Axis", 100, 0, 1);
191~~~
192 The histogram title and the axis titles can be any TLatex string, and
193 are persisted if a histogram is written to a file.
194
195 Any title can be omitted:
196~~~ {.cpp}
197 TH1F* h=new TH1F("h", "Histogram title;;Y Axis", 100, 0, 1);
198 TH1F* h=new TH1F("h", ";;Y Axis", 100, 0, 1);
199~~~
200 The method SetTitle() has the same syntax:
201~~~ {.cpp}
202 h->SetTitle("Histogram title;Another X title Axis");
203~~~
204Alternatively, the title of each axis can be set directly:
205~~~ {.cpp}
206 h->GetXaxis()->SetTitle("X axis title");
207 h->GetYaxis()->SetTitle("Y axis title");
208~~~
209For bin labels see \ref binning.
210
211\anchor binning
212## Binning
213
214\anchor fix-var
215### Fix or variable bin size
216
217 All histogram types support either fix or variable bin sizes.
218 2-D histograms may have fix size bins along X and variable size bins
219 along Y or vice-versa. The functions to fill, manipulate, draw or access
220 histograms are identical in both cases.
221
222 Each histogram always contains 3 axis objects of type TAxis: fXaxis, fYaxis and fZaxis.
223 To access the axis parameters, use:
224~~~ {.cpp}
225 TAxis *xaxis = h->GetXaxis(); etc.
226 Double_t binCenter = xaxis->GetBinCenter(bin), etc.
227~~~
228 See class TAxis for a description of all the access functions.
229 The axis range is always stored internally in double precision.
230
231\anchor convention
232### Convention for numbering bins
233
234 For all histogram types: nbins, xlow, xup
235~~~ {.cpp}
236 bin = 0; underflow bin
237 bin = 1; first bin with low-edge xlow INCLUDED
238 bin = nbins; last bin with upper-edge xup EXCLUDED
239 bin = nbins+1; overflow bin
240~~~
241 In case of 2-D or 3-D histograms, a "global bin" number is defined.
242 For example, assuming a 3-D histogram with (binx, biny, binz), the function
243~~~ {.cpp}
244 Int_t gbin = h->GetBin(binx, biny, binz);
245~~~
246 returns a global/linearized gbin number. This global gbin is useful
247 to access the bin content/error information independently of the dimension.
248 Note that to access the information other than bin content and errors
249 one should use the TAxis object directly with e.g.:
250~~~ {.cpp}
251 Double_t xcenter = h3->GetZaxis()->GetBinCenter(27);
252~~~
253 returns the center along z of bin number 27 (not the global bin)
254 in the 3-D histogram h3.
255
256\anchor alpha
257### Alphanumeric Bin Labels
258
259 By default, a histogram axis is drawn with its numeric bin labels.
260 One can specify alphanumeric labels instead with:
261
262 - call TAxis::SetBinLabel(bin, label);
263 This can always be done before or after filling.
264 When the histogram is drawn, bin labels will be automatically drawn.
265 See examples labels1.C and labels2.C
266 - call to a Fill function with one of the arguments being a string, e.g.
267~~~ {.cpp}
268 hist1->Fill(somename, weight);
269 hist2->Fill(x, somename, weight);
270 hist2->Fill(somename, y, weight);
271 hist2->Fill(somenamex, somenamey, weight);
272~~~
273 See examples hlabels1.C and hlabels2.C
274 - via TTree::Draw. see for example cernstaff.C
275~~~ {.cpp}
276 tree.Draw("Nation::Division");
277~~~
278 where "Nation" and "Division" are two branches of a Tree.
279
280When using the options 2 or 3 above, the labels are automatically
281 added to the list (THashList) of labels for a given axis.
282 By default, an axis is drawn with the order of bins corresponding
283 to the filling sequence. It is possible to reorder the axis
284
285 - alphabetically
286 - by increasing or decreasing values
287
288 The reordering can be triggered via the TAxis context menu by selecting
289 the menu item "LabelsOption" or by calling directly
290 TH1::LabelsOption(option, axis) where
291
292 - axis may be "X", "Y" or "Z"
293 - option may be:
294 - "a" sort by alphabetic order
295 - ">" sort by decreasing values
296 - "<" sort by increasing values
297 - "h" draw labels horizontal
298 - "v" draw labels vertical
299 - "u" draw labels up (end of label right adjusted)
300 - "d" draw labels down (start of label left adjusted)
301
302 When using the option 2 above, new labels are added by doubling the current
303 number of bins in case one label does not exist yet.
304 When the Filling is terminated, it is possible to trim the number
305 of bins to match the number of active labels by calling
306~~~ {.cpp}
307 TH1::LabelsDeflate(axis) with axis = "X", "Y" or "Z"
308~~~
309 This operation is automatic when using TTree::Draw.
310 Once bin labels have been created, they become persistent if the histogram
311 is written to a file or when generating the C++ code via SavePrimitive.
312
313\anchor auto-bin
314### Histograms with automatic bins
315
316 When a histogram is created with an axis lower limit greater or equal
317 to its upper limit, the SetBuffer is automatically called with an
318 argument fBufferSize equal to fgBufferSize (default value=1000).
319 fgBufferSize may be reset via the static function TH1::SetDefaultBufferSize.
320 The axis limits will be automatically computed when the buffer will
321 be full or when the function BufferEmpty is called.
322
323\anchor rebinning
324### Rebinning
325
326 At any time, a histogram can be rebinned via TH1::Rebin. This function
327 returns a new histogram with the rebinned contents.
328 If bin errors were stored, they are recomputed during the rebinning.
329
330
331\anchor filling-histograms
332## Filling histograms
333
334 A histogram is typically filled with statements like:
335~~~ {.cpp}
336 h1->Fill(x);
337 h1->Fill(x, w); //fill with weight
338 h2->Fill(x, y)
339 h2->Fill(x, y, w)
340 h3->Fill(x, y, z)
341 h3->Fill(x, y, z, w)
342~~~
343 or via one of the Fill functions accepting names described above.
344 The Fill functions compute the bin number corresponding to the given
345 x, y or z argument and increment this bin by the given weight.
346 The Fill functions return the bin number for 1-D histograms or global
347 bin number for 2-D and 3-D histograms.
348 If TH1::Sumw2 has been called before filling, the sum of squares of
349 weights is also stored.
350 One can also increment directly a bin number via TH1::AddBinContent
351 or replace the existing content via TH1::SetBinContent. Passing an
352 out-of-range bin to TH1::AddBinContent leads to undefined behavior.
353 To access the bin content of a given bin, do:
354~~~ {.cpp}
355 Double_t binContent = h->GetBinContent(bin);
356~~~
357
358 By default, the bin number is computed using the current axis ranges.
359 If the automatic binning option has been set via
360~~~ {.cpp}
361 h->SetCanExtend(TH1::kAllAxes);
362~~~
363 then, the Fill Function will automatically extend the axis range to
364 accommodate the new value specified in the Fill argument. The method
365 used is to double the bin size until the new value fits in the range,
366 merging bins two by two. This automatic binning options is extensively
367 used by the TTree::Draw function when histogramming Tree variables
368 with an unknown range.
369 This automatic binning option is supported for 1-D, 2-D and 3-D histograms.
370
371 During filling, some statistics parameters are incremented to compute
372 the mean value and Root Mean Square with the maximum precision.
373
374 In case of histograms of type TH1C, TH1S, TH2C, TH2S, TH3C, TH3S
375 a check is made that the bin contents do not exceed the maximum positive
376 capacity (127 or 32767). Histograms of all types may have positive
377 or/and negative bin contents.
378
379\anchor associated-errors
380### Associated errors
381 By default, for each bin, the sum of weights is computed at fill time.
382 One can also call TH1::Sumw2 to force the storage and computation
383 of the sum of the square of weights per bin.
384 If Sumw2 has been called, the error per bin is computed as the
385 sqrt(sum of squares of weights), otherwise the error is set equal
386 to the sqrt(bin content).
387 To return the error for a given bin number, do:
388~~~ {.cpp}
389 Double_t error = h->GetBinError(bin);
390~~~
391
392\anchor associated-functions
393### Associated functions
394 One or more objects (typically a TF1*) can be added to the list
395 of functions (fFunctions) associated to each histogram.
396 When TH1::Fit is invoked, the fitted function is added to this list.
397 Given a histogram (or TGraph) `h`, one can retrieve an associated function
398 with:
399~~~ {.cpp}
400 TF1 *myfunc = h->GetFunction("myfunc");
401~~~
402
403
404\anchor operations-on-histograms
405## Operations on histograms
406
407 Many types of operations are supported on histograms or between histograms
408
409 - Addition of a histogram to the current histogram.
410 - Additions of two histograms with coefficients and storage into the current
411 histogram.
412 - Multiplications and Divisions are supported in the same way as additions.
413 - The Add, Divide and Multiply functions also exist to add, divide or multiply
414 a histogram by a function.
415
416 If a histogram has associated error bars (TH1::Sumw2 has been called),
417 the resulting error bars are also computed assuming independent histograms.
418 In case of divisions, Binomial errors are also supported.
419 One can mark a histogram to be an "average" histogram by setting its bit kIsAverage via
420 myhist.SetBit(TH1::kIsAverage);
421 When adding (see TH1::Add) average histograms, the histograms are averaged and not summed.
422
423
424\anchor prof-hist
425### Projections of histograms
426
427 One can:
428
429 - make a 1-D projection of a 2-D histogram or Profile
430 see functions TH2::ProjectionX,Y, TH2::ProfileX,Y, TProfile::ProjectionX
431 - make a 1-D, 2-D or profile out of a 3-D histogram
432 see functions TH3::ProjectionZ, TH3::Project3D.
433
434 One can fit these projections via:
435~~~ {.cpp}
436 TH2::FitSlicesX,Y, TH3::FitSlicesZ.
437~~~
438
439\anchor random-numbers
440### Random Numbers and histograms
441
442 TH1::FillRandom can be used to randomly fill a histogram using
443 the contents of an existing TF1 function or another
444 TH1 histogram (for all dimensions).
445 For example, the following two statements create and fill a histogram
446 10000 times with a default gaussian distribution of mean 0 and sigma 1:
447~~~ {.cpp}
448 TH1F h1("h1", "histo from a gaussian", 100, -3, 3);
449 h1.FillRandom("gaus", 10000);
450~~~
451 TH1::GetRandom can be used to return a random number distributed
452 according to the contents of a histogram.
453
454\anchor making-a-copy
455### Making a copy of a histogram
456 Like for any other ROOT object derived from TObject, one can use
457 the Clone() function. This makes an identical copy of the original
458 histogram including all associated errors and functions, e.g.:
459~~~ {.cpp}
460 TH1F *hnew = (TH1F*)h->Clone("hnew");
461~~~
462
463\anchor normalizing
464### Normalizing histograms
465
466 One can scale a histogram such that the bins integral is equal to
467 the normalization parameter via TH1::Scale(Double_t norm), where norm
468 is the desired normalization divided by the integral of the histogram.
471\anchor drawing-histograms
472## Drawing histograms
473
474 Histograms are drawn via the THistPainter class. Each histogram has
475 a pointer to its own painter (to be usable in a multithreaded program).
476 Many drawing options are supported.
477 See THistPainter::Paint() for more details.
478
479 The same histogram can be drawn with different options in different pads.
480 When a histogram drawn in a pad is deleted, the histogram is
481 automatically removed from all pads where it was drawn.
482 If a histogram is drawn in a pad, then modified, the new status
483 of the histogram will be automatically shown in the pad next time
484 the pad is updated. One does not need to redraw the histogram.
485 To draw the current version of a histogram in a pad, one can use
486~~~ {.cpp}
487 h->DrawCopy();
488~~~
489 DrawCopy() is also useful when a temporary histogram should be drawn, for
490 example in
491~~~ {.cpp}
492 void drawHisto() {
493 TH1D histo("histo", "An example histogram", 10, 0, 10);
494 // ...
495 histo.DrawCopy();
496 } // histo goes out of scope here, but the copy stays visible
497~~~
498
499 One can use TH1::SetMaximum() and TH1::SetMinimum() to force a particular
500 value for the maximum or the minimum scale on the plot. (For 1-D
501 histograms this means the y-axis, while for 2-D histograms these
502 functions affect the z-axis).
503
504 TH1::UseCurrentStyle() can be used to change all histogram graphics
505 attributes to correspond to the current selected style.
506 This function must be called for each histogram.
507 In case one reads and draws many histograms from a file, one can force
508 the histograms to inherit automatically the current graphics style
509 by calling before gROOT->ForceStyle().
510
511\anchor cont-level
512### Setting Drawing histogram contour levels (2-D hists only)
513
514 By default contours are automatically generated at equidistant
515 intervals. A default value of 20 levels is used. This can be modified
516 via TH1::SetContour() or TH1::SetContourLevel().
517 the contours level info is used by the drawing options "cont", "surf",
518 and "lego".
519
520\anchor graph-att
521### Setting histogram graphics attributes
522
523 The histogram classes inherit from the attribute classes:
524 TAttLine, TAttFill, and TAttMarker.
525 See the member functions of these classes for the list of options.
526
527\anchor axis-drawing
528### Customizing how axes are drawn
529
530 Use the functions of TAxis, such as
531~~~ {.cpp}
532 histogram.GetXaxis()->SetTicks("+");
533 histogram.GetYaxis()->SetRangeUser(1., 5.);
534~~~
535
536\anchor fitting-histograms
537## Fitting histograms
538
539 Histograms (1-D, 2-D, 3-D and Profiles) can be fitted with a user
540 specified function or a pre-defined function via TH1::Fit.
541 See TH1::Fit(TF1*, Option_t *, Option_t *, Double_t, Double_t) for the fitting documentation and the possible [fitting options](\ref HFitOpt)
542
543 The FitPanel can also be used for fitting an histogram. See the [FitPanel documentation](https://root.cern/manual/fitting/#using-the-fit-panel).
544
545\anchor saving-histograms
546## Saving/reading histograms to/from a ROOT file
547
548 The following statements create a ROOT file and store a histogram
549 on the file. Because TH1 derives from TNamed, the key identifier on
550 the file is the histogram name:
551~~~ {.cpp}
552 TFile f("histos.root", "new");
553 TH1F h1("hgaus", "histo from a gaussian", 100, -3, 3);
554 h1.FillRandom("gaus", 10000);
555 h1->Write();
556~~~
557 To read this histogram in another Root session, do:
558~~~ {.cpp}
559 TFile f("histos.root");
560 TH1F *h = (TH1F*)f.Get("hgaus");
561~~~
562 One can save all histograms in memory to the file by:
563~~~ {.cpp}
564 file->Write();
565~~~
566
567
568\anchor misc
569## Miscellaneous operations
570
571~~~ {.cpp}
572 TH1::KolmogorovTest(): statistical test of compatibility in shape
573 between two histograms
574 TH1::Smooth() smooths the bin contents of a 1-d histogram
575 TH1::Integral() returns the integral of bin contents in a given bin range
576 TH1::GetMean(int axis) returns the mean value along axis
577 TH1::GetStdDev(int axis) returns the sigma distribution along axis
578 TH1::GetEntries() returns the number of entries
579 TH1::Reset() resets the bin contents and errors of a histogram
580~~~
581 IMPORTANT NOTE: The returned values for GetMean and GetStdDev depend on how the
582 histogram statistics are calculated. By default, if no range has been set, the
583 returned values are the (unbinned) ones calculated at fill time. If a range has been
584 set, however, the values are calculated using the bins in range; THIS IS TRUE EVEN
585 IF THE RANGE INCLUDES ALL BINS--use TAxis::SetRange(0, 0) to unset the range.
586 To ensure that the returned values are always those of the binned data stored in the
587 histogram, call TH1::ResetStats. See TH1::GetStats.
588*/
589
590TF1 *gF1=nullptr; //left for back compatibility (use TVirtualFitter::GetUserFunc instead)
591
596
597extern void H1InitGaus();
598extern void H1InitExpo();
599extern void H1InitPolynom();
600extern void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a);
603
604
605////////////////////////////////////////////////////////////////////////////////
606/// Histogram default constructor.
607
609{
610 fDirectory = nullptr;
611 fFunctions = new TList;
612 fNcells = 0;
613 fIntegral = nullptr;
614 fPainter = nullptr;
615 fEntries = 0;
616 fNormFactor = 0;
618 fMaximum = -1111;
619 fMinimum = -1111;
620 fBufferSize = 0;
621 fBuffer = nullptr;
624 fXaxis.SetName("xaxis");
625 fYaxis.SetName("yaxis");
626 fZaxis.SetName("zaxis");
627 fXaxis.SetParent(this);
628 fYaxis.SetParent(this);
629 fZaxis.SetParent(this);
631}
632
633////////////////////////////////////////////////////////////////////////////////
634/// Histogram default destructor.
635
637{
639 return;
640 }
641 delete[] fIntegral;
642 fIntegral = nullptr;
643 delete[] fBuffer;
644 fBuffer = nullptr;
645 if (fFunctions) {
647
649 TObject* obj = nullptr;
650 //special logic to support the case where the same object is
651 //added multiple times in fFunctions.
652 //This case happens when the same object is added with different
653 //drawing modes
654 //In the loop below we must be careful with objects (eg TCutG) that may
655 // have been added to the list of functions of several histograms
656 //and may have been already deleted.
657 while ((obj = fFunctions->First())) {
658 while(fFunctions->Remove(obj)) { }
660 break;
661 }
662 delete obj;
663 obj = nullptr;
664 }
665 delete fFunctions;
666 fFunctions = nullptr;
667 }
668 if (fDirectory) {
669 fDirectory->Remove(this);
670 fDirectory = nullptr;
671 }
672 delete fPainter;
673 fPainter = nullptr;
674}
675
676////////////////////////////////////////////////////////////////////////////////
677/// Constructor for fix bin size histograms.
678/// Creates the main histogram structure.
679///
680/// \param[in] name name of histogram (avoid blanks)
681/// \param[in] title histogram title.
682/// If title is of the form `stringt;stringx;stringy;stringz`,
683/// the histogram title is set to `stringt`,
684/// the x axis title to `stringx`, the y axis title to `stringy`, etc.
685/// \param[in] nbins number of bins
686/// \param[in] xlow low edge of first bin
687/// \param[in] xup upper edge of last bin (not included in last bin)
688
689
690TH1::TH1(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
691 :TNamed(name,title)
692{
693 Build();
694 if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
695 fXaxis.Set(nbins,xlow,xup);
696 fNcells = fXaxis.GetNbins()+2;
697}
698
699////////////////////////////////////////////////////////////////////////////////
700/// Constructor for variable bin size histograms using an input array of type float.
701/// Creates the main histogram structure.
702///
703/// \param[in] name name of histogram (avoid blanks)
704/// \param[in] title histogram title.
705/// If title is of the form `stringt;stringx;stringy;stringz`
706/// the histogram title is set to `stringt`,
707/// the x axis title to `stringx`, the y axis title to `stringy`, etc.
708/// \param[in] nbins number of bins
709/// \param[in] xbins array of low-edges for each bin.
710/// This is an array of type float and size nbins+1
711
712TH1::TH1(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
713 :TNamed(name,title)
714{
715 Build();
716 if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
717 if (xbins) fXaxis.Set(nbins,xbins);
718 else fXaxis.Set(nbins,0,1);
719 fNcells = fXaxis.GetNbins()+2;
720}
721
722////////////////////////////////////////////////////////////////////////////////
723/// Constructor for variable bin size histograms using an input array of type double.
724///
725/// \param[in] name name of histogram (avoid blanks)
726/// \param[in] title histogram title.
727/// If title is of the form `stringt;stringx;stringy;stringz`
728/// the histogram title is set to `stringt`,
729/// the x axis title to `stringx`, the y axis title to `stringy`, etc.
730/// \param[in] nbins number of bins
731/// \param[in] xbins array of low-edges for each bin.
732/// This is an array of type double and size nbins+1
733
734TH1::TH1(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
735 :TNamed(name,title)
736{
737 Build();
738 if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
739 if (xbins) fXaxis.Set(nbins,xbins);
740 else fXaxis.Set(nbins,0,1);
741 fNcells = fXaxis.GetNbins()+2;
742}
743
744////////////////////////////////////////////////////////////////////////////////
745/// Static function: cannot be inlined on Windows/NT.
746
751
752////////////////////////////////////////////////////////////////////////////////
753/// Browse the Histogram object.
754
756{
757 Draw(b ? b->GetDrawOption() : "");
758 gPad->Update();
759}
760
761////////////////////////////////////////////////////////////////////////////////
762/// Creates histogram basic data structure.
763
765{
766 fDirectory = nullptr;
767 fPainter = nullptr;
768 fIntegral = nullptr;
769 fEntries = 0;
770 fNormFactor = 0;
772 fMaximum = -1111;
773 fMinimum = -1111;
774 fBufferSize = 0;
775 fBuffer = nullptr;
778 fXaxis.SetName("xaxis");
779 fYaxis.SetName("yaxis");
780 fZaxis.SetName("zaxis");
781 fYaxis.Set(1,0.,1.);
782 fZaxis.Set(1,0.,1.);
783 fXaxis.SetParent(this);
784 fYaxis.SetParent(this);
785 fZaxis.SetParent(this);
786
788
789 fFunctions = new TList;
790
792
795 if (fDirectory) {
797 fDirectory->Append(this,kTRUE);
798 }
799 }
800}
801
802////////////////////////////////////////////////////////////////////////////////
803/// Performs the operation: `this = this + c1*f1`
804/// if errors are defined (see TH1::Sumw2), errors are also recalculated.
805///
806/// By default, the function is computed at the centre of the bin.
807/// if option "I" is specified (1-d histogram only), the integral of the
808/// function in each bin is used instead of the value of the function at
809/// the centre of the bin.
810///
811/// Only bins inside the function range are recomputed.
812///
813/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
814/// you should call Sumw2 before making this operation.
815/// This is particularly important if you fit the histogram after TH1::Add
816///
817/// The function return kFALSE if the Add operation failed
818
820{
821 if (!f1) {
822 Error("Add","Attempt to add a non-existing function");
823 return kFALSE;
824 }
825
826 TString opt = option;
827 opt.ToLower();
828 Bool_t integral = kFALSE;
829 if (opt.Contains("i") && fDimension == 1) integral = kTRUE;
830
831 Int_t ncellsx = GetNbinsX() + 2; // cells = normal bins + underflow bin + overflow bin
832 Int_t ncellsy = GetNbinsY() + 2;
833 Int_t ncellsz = GetNbinsZ() + 2;
834 if (fDimension < 2) ncellsy = 1;
835 if (fDimension < 3) ncellsz = 1;
836
837 // delete buffer if it is there since it will become invalid
838 if (fBuffer) BufferEmpty(1);
839
840 // - Add statistics
841 Double_t s1[10];
842 for (Int_t i = 0; i < 10; ++i) s1[i] = 0;
843 PutStats(s1);
844 SetMinimum();
845 SetMaximum();
846
847 // - Loop on bins (including underflows/overflows)
848 Int_t bin, binx, biny, binz;
849 Double_t cu=0;
850 Double_t xx[3];
851 Double_t *params = nullptr;
852 f1->InitArgs(xx,params);
853 for (binz = 0; binz < ncellsz; ++binz) {
855 for (biny = 0; biny < ncellsy; ++biny) {
857 for (binx = 0; binx < ncellsx; ++binx) {
859 if (!f1->IsInside(xx)) continue;
861 bin = binx + ncellsx * (biny + ncellsy * binz);
862 if (integral) {
864 } else {
865 cu = c1*f1->EvalPar(xx);
866 }
867 if (TF1::RejectedPoint()) continue;
868 AddBinContent(bin,cu);
869 }
870 }
871 }
872
873 return kTRUE;
874}
875
876int TH1::LoggedInconsistency(const char *name, const TH1 *h1, const TH1 *h2, bool useMerge) const
877{
878 const auto inconsistency = CheckConsistency(h1, h2);
879
881 if (useMerge)
882 Info(name, "Histograms have different dimensions - trying to use TH1::Merge");
883 else {
884 Error(name, "Histograms have different dimensions");
885 }
887 if (useMerge)
888 Info(name, "Histograms have different number of bins - trying to use TH1::Merge");
889 else {
890 Error(name, "Histograms have different number of bins");
891 }
892 } else if (inconsistency & kDifferentAxisLimits) {
893 if (useMerge)
894 Info(name, "Histograms have different axis limits - trying to use TH1::Merge");
895 else
896 Warning(name, "Histograms have different axis limits");
897 } else if (inconsistency & kDifferentBinLimits) {
898 if (useMerge)
899 Info(name, "Histograms have different bin limits - trying to use TH1::Merge");
900 else
901 Warning(name, "Histograms have different bin limits");
902 } else if (inconsistency & kDifferentLabels) {
903 // in case of different labels -
904 if (useMerge)
905 Info(name, "Histograms have different labels - trying to use TH1::Merge");
906 else
907 Info(name, "Histograms have different labels");
908 }
909
910 return inconsistency;
911}
912
913////////////////////////////////////////////////////////////////////////////////
914/// Performs the operation: `this = this + c1*h1`
915/// If errors are defined (see TH1::Sumw2), errors are also recalculated.
916///
917/// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
918/// if not already set.
919///
920/// Note also that adding histogram with labels is not supported, histogram will be
921/// added merging them by bin number independently of the labels.
922/// For adding histogram with labels one should use TH1::Merge
923///
924/// SPECIAL CASE (Average/Efficiency histograms)
925/// For histograms representing averages or efficiencies, one should compute the average
926/// of the two histograms and not the sum. One can mark a histogram to be an average
927/// histogram by setting its bit kIsAverage with
928/// myhist.SetBit(TH1::kIsAverage);
929/// Note that the two histograms must have their kIsAverage bit set
930///
931/// IMPORTANT NOTE1: If you intend to use the errors of this histogram later
932/// you should call Sumw2 before making this operation.
933/// This is particularly important if you fit the histogram after TH1::Add
934///
935/// IMPORTANT NOTE2: if h1 has a normalisation factor, the normalisation factor
936/// is used , ie this = this + c1*factor*h1
937/// Use the other TH1::Add function if you do not want this feature
938///
939/// IMPORTANT NOTE3: You should be careful about the statistics of the
940/// returned histogram, whose statistics may be binned or unbinned,
941/// depending on whether c1 is negative, whether TAxis::kAxisRange is true,
942/// and whether TH1::ResetStats has been called on either this or h1.
943/// See TH1::GetStats.
944///
945/// The function return kFALSE if the Add operation failed
946
948{
949 if (!h1) {
950 Error("Add","Attempt to add a non-existing histogram");
951 return kFALSE;
952 }
953
954 // delete buffer if it is there since it will become invalid
955 if (fBuffer) BufferEmpty(1);
956
957 bool useMerge = false;
958 const bool considerMerge = (c1 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
959 const auto inconsistency = LoggedInconsistency("Add", this, h1, considerMerge);
960 // If there is a bad inconsistency and we can't even consider merging, just give up
962 return false;
963 }
964 // If there is an inconsistency, we try to use merging
967 }
968
969 if (useMerge) {
970 TList l;
971 l.Add(const_cast<TH1*>(h1));
972 auto iret = Merge(&l);
973 return (iret >= 0);
974 }
975
976 // Create Sumw2 if h1 has Sumw2 set
977 if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
978 // In addition, create Sumw2 if is not a simple addition, otherwise errors will not be correctly computed
979 if (fSumw2.fN == 0 && c1 != 1.0) Sumw2();
980
981 // - Add statistics (for c1=1)
982 Double_t entries = GetEntries() + h1->GetEntries();
983
984 // statistics can be preserved only in case of positive coefficients
985 // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
986 Bool_t resetStats = (c1 < 0);
987 Double_t s1[kNstat] = {0};
988 Double_t s2[kNstat] = {0};
989 if (!resetStats) {
990 // need to initialize to zero s1 and s2 since
991 // GetStats fills only used elements depending on dimension and type
992 GetStats(s1);
993 h1->GetStats(s2);
994 }
995
996 SetMinimum();
997 SetMaximum();
998
999 // - Loop on bins (including underflows/overflows)
1000 Double_t factor = 1;
1001 if (h1->GetNormFactor() != 0) factor = h1->GetNormFactor()/h1->GetSumOfWeights();
1002 Double_t c1sq = c1 * c1;
1003 Double_t factsq = factor * factor;
1004
1005 for (Int_t bin = 0; bin < fNcells; ++bin) {
1006 //special case where histograms have the kIsAverage bit set
1007 if (this->TestBit(kIsAverage) && h1->TestBit(kIsAverage)) {
1009 Double_t y2 = this->RetrieveBinContent(bin);
1012 Double_t w1 = 1., w2 = 1.;
1013
1014 // consider all special cases when bin errors are zero
1015 // see http://root-forum.cern.ch/viewtopic.php?f=3&t=13299
1016 if (e1sq) w1 = 1. / e1sq;
1017 else if (h1->fSumw2.fN) {
1018 w1 = 1.E200; // use an arbitrary huge value
1019 if (y1 == 0) {
1020 // use an estimated error from the global histogram scale
1021 double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
1022 w1 = 1./(sf*sf);
1023 }
1024 }
1025 if (e2sq) w2 = 1. / e2sq;
1026 else if (fSumw2.fN) {
1027 w2 = 1.E200; // use an arbitrary huge value
1028 if (y2 == 0) {
1029 // use an estimated error from the global histogram scale
1030 double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
1031 w2 = 1./(sf*sf);
1032 }
1033 }
1034
1035 double y = (w1*y1 + w2*y2)/(w1 + w2);
1036 UpdateBinContent(bin, y);
1037 if (fSumw2.fN) {
1038 double err2 = 1./(w1 + w2);
1039 if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
1040 fSumw2.fArray[bin] = err2;
1041 }
1042 } else { // normal case of addition between histograms
1043 AddBinContent(bin, c1 * factor * h1->RetrieveBinContent(bin));
1044 if (fSumw2.fN) fSumw2.fArray[bin] += c1sq * factsq * h1->GetBinErrorSqUnchecked(bin);
1045 }
1046 }
1047
1048 // update statistics (do here to avoid changes by SetBinContent)
1049 if (resetStats) {
1050 // statistics need to be reset in case coefficient are negative
1051 ResetStats();
1052 }
1053 else {
1054 for (Int_t i=0;i<kNstat;i++) {
1055 if (i == 1) s1[i] += c1*c1*s2[i];
1056 else s1[i] += c1*s2[i];
1057 }
1058 PutStats(s1);
1059 if (c1 == 1.0)
1060 SetEntries(entries);
1061 else {
1062 // compute entries as effective entries in case of
1063 // weights different than 1
1064 double sumw2 = 0;
1065 double sumw = GetSumOfAllWeights(true, &sumw2);
1066 if (sumw2 > 0) SetEntries( sumw*sumw/sumw2);
1067 }
1068 }
1069 return kTRUE;
1070}
1071
1072////////////////////////////////////////////////////////////////////////////////
1073/// Replace contents of this histogram by the addition of h1 and h2.
1074///
1075/// `this = c1*h1 + c2*h2`
1076/// if errors are defined (see TH1::Sumw2), errors are also recalculated
1077///
1078/// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
1079/// if not already set.
1080///
1081/// Note also that adding histogram with labels is not supported, histogram will be
1082/// added merging them by bin number independently of the labels.
1083/// For adding histogram ith labels one should use TH1::Merge
1084///
1085/// SPECIAL CASE (Average/Efficiency histograms)
1086/// For histograms representing averages or efficiencies, one should compute the average
1087/// of the two histograms and not the sum. One can mark a histogram to be an average
1088/// histogram by setting its bit kIsAverage with
1089/// myhist.SetBit(TH1::kIsAverage);
1090/// Note that the two histograms must have their kIsAverage bit set
1091///
1092/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
1093/// you should call Sumw2 before making this operation.
1094/// This is particularly important if you fit the histogram after TH1::Add
1095///
1096/// IMPORTANT NOTE2: You should be careful about the statistics of the
1097/// returned histogram, whose statistics may be binned or unbinned,
1098/// depending on whether c1 is negative, whether TAxis::kAxisRange is true,
1099/// and whether TH1::ResetStats has been called on either this or h1.
1100/// See TH1::GetStats.
1101///
1102/// ANOTHER SPECIAL CASE : h1 = h2 and c2 < 0
1103/// do a scaling this = c1 * h1 / (bin Volume)
1104///
1105/// The function returns kFALSE if the Add operation failed
1106
1108{
1109
1110 if (!h1 || !h2) {
1111 Error("Add","Attempt to add a non-existing histogram");
1112 return kFALSE;
1113 }
1114
1115 // delete buffer if it is there since it will become invalid
1116 if (fBuffer) BufferEmpty(1);
1117
1119 if (h1 == h2 && c2 < 0) {c2 = 0; normWidth = kTRUE;}
1120
1121 if (h1 != h2) {
1122 bool useMerge = false;
1123 const bool considerMerge = (c1 == 1. && c2 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
1124
1125 // We can combine inconsistencies like this, since they are ordered and a
1126 // higher inconsistency is worse
1127 auto const inconsistency = std::max(LoggedInconsistency("Add", this, h1, considerMerge),
1128 LoggedInconsistency("Add", h1, h2, considerMerge));
1129
1130 // If there is a bad inconsistency and we can't even consider merging, just give up
1132 return false;
1133 }
1134 // If there is an inconsistency, we try to use merging
1137 }
1138
1139 if (useMerge) {
1140 TList l;
1141 // why TList takes non-const pointers ????
1142 l.Add(const_cast<TH1*>(h1));
1143 l.Add(const_cast<TH1*>(h2));
1144 Reset("ICE");
1145 auto iret = Merge(&l);
1146 return (iret >= 0);
1147 }
1148 }
1149
1150 // Create Sumw2 if h1 or h2 have Sumw2 set
1151 if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
1152 // Create also Sumw2 if not a simple addition (c1 = 1, c2 = 1)
1153 if (fSumw2.fN == 0 && (c1 != 1.0 || c2 != 1.0)) Sumw2();
1154 // - Add statistics
1155 Double_t nEntries = TMath::Abs( c1*h1->GetEntries() + c2*h2->GetEntries() );
1156
1157 // TODO remove
1158 // statistics can be preserved only in case of positive coefficients
1159 // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
1160 // also in case of scaling with the width we cannot preserve the statistics
1161 Double_t s1[kNstat] = {0};
1162 Double_t s2[kNstat] = {0};
1164
1165
1166 Bool_t resetStats = (c1*c2 < 0) || normWidth;
1167 if (!resetStats) {
1168 // need to initialize to zero s1 and s2 since
1169 // GetStats fills only used elements depending on dimension and type
1170 h1->GetStats(s1);
1171 h2->GetStats(s2);
1172 for (Int_t i=0;i<kNstat;i++) {
1173 if (i == 1) s3[i] = c1*c1*s1[i] + c2*c2*s2[i];
1174 //else s3[i] = TMath::Abs(c1)*s1[i] + TMath::Abs(c2)*s2[i];
1175 else s3[i] = c1*s1[i] + c2*s2[i];
1176 }
1177 }
1178
1179 SetMinimum();
1180 SetMaximum();
1181
1182 if (normWidth) { // DEPRECATED CASE: belongs to fitting / drawing modules
1183
1184 Int_t nbinsx = GetNbinsX() + 2; // normal bins + underflow, overflow
1185 Int_t nbinsy = GetNbinsY() + 2;
1186 Int_t nbinsz = GetNbinsZ() + 2;
1187
1188 if (fDimension < 2) nbinsy = 1;
1189 if (fDimension < 3) nbinsz = 1;
1190
1191 Int_t bin, binx, biny, binz;
1192 for (binz = 0; binz < nbinsz; ++binz) {
1194 for (biny = 0; biny < nbinsy; ++biny) {
1196 for (binx = 0; binx < nbinsx; ++binx) {
1198 bin = GetBin(binx, biny, binz);
1199 Double_t w = wx*wy*wz;
1200 UpdateBinContent(bin, c1 * h1->RetrieveBinContent(bin) / w);
1201 if (fSumw2.fN) {
1202 Double_t e1 = h1->GetBinError(bin)/w;
1203 fSumw2.fArray[bin] = c1*c1*e1*e1;
1204 }
1205 }
1206 }
1207 }
1208 } else if (h1->TestBit(kIsAverage) && h2->TestBit(kIsAverage)) {
1209 for (Int_t i = 0; i < fNcells; ++i) { // loop on cells (bins including underflow / overflow)
1210 // special case where histograms have the kIsAverage bit set
1212 Double_t y2 = h2->RetrieveBinContent(i);
1214 Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
1215 Double_t w1 = 1., w2 = 1.;
1216
1217 // consider all special cases when bin errors are zero
1218 // see http://root-forum.cern.ch/viewtopic.php?f=3&t=13299
1219 if (e1sq) w1 = 1./ e1sq;
1220 else if (h1->fSumw2.fN) {
1221 w1 = 1.E200; // use an arbitrary huge value
1222 if (y1 == 0 ) { // use an estimated error from the global histogram scale
1223 double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
1224 w1 = 1./(sf*sf);
1225 }
1226 }
1227 if (e2sq) w2 = 1./ e2sq;
1228 else if (h2->fSumw2.fN) {
1229 w2 = 1.E200; // use an arbitrary huge value
1230 if (y2 == 0) { // use an estimated error from the global histogram scale
1231 double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
1232 w2 = 1./(sf*sf);
1233 }
1234 }
1235
1236 double y = (w1*y1 + w2*y2)/(w1 + w2);
1237 UpdateBinContent(i, y);
1238 if (fSumw2.fN) {
1239 double err2 = 1./(w1 + w2);
1240 if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
1241 fSumw2.fArray[i] = err2;
1242 }
1243 }
1244 } else { // case of simple histogram addition
1245 Double_t c1sq = c1 * c1;
1246 Double_t c2sq = c2 * c2;
1247 for (Int_t i = 0; i < fNcells; ++i) { // Loop on cells (bins including underflows/overflows)
1248 UpdateBinContent(i, c1 * h1->RetrieveBinContent(i) + c2 * h2->RetrieveBinContent(i));
1249 if (fSumw2.fN) {
1250 fSumw2.fArray[i] = c1sq * h1->GetBinErrorSqUnchecked(i) + c2sq * h2->GetBinErrorSqUnchecked(i);
1251 }
1252 }
1253 }
1254
1255 if (resetStats) {
1256 // statistics need to be reset in case coefficient are negative
1257 ResetStats();
1258 }
1259 else {
1260 // update statistics
1261 PutStats(s3);
1262 // previous entries are correct only if c1=1 and c2=1
1263 if (c1 == 1.0 && c2 == 1.0)
1265 else {
1266 // compute entries as effective entries in case of
1267 // weights different than 1
1268 double sumw2 = 0;
1269 double sumw = GetSumOfAllWeights(true, &sumw2);
1270 if (sumw2 > 0) SetEntries( sumw*sumw/sumw2);
1271 }
1272 }
1273
1274 return kTRUE;
1275}
1276
1277////////////////////////////////////////////////////////////////////////////////
1278/// Sets the flag controlling the automatic add of histograms in memory
1279///
1280/// By default (fAddDirectory = kTRUE), histograms are automatically added
1281/// to the list of objects in memory.
1282/// Note that one histogram can be removed from its support directory
1283/// by calling h->SetDirectory(nullptr) or h->SetDirectory(dir) to add it
1284/// to the list of objects in the directory dir.
1285///
1286/// NOTE that this is a static function. To call it, use;
1287/// TH1::AddDirectory
1288
1290{
1291 fgAddDirectory = add;
1292}
1293
1294////////////////////////////////////////////////////////////////////////////////
1295/// Auxiliary function to get the power of 2 next (larger) or previous (smaller)
1296/// a given x
1297///
1298/// next = kTRUE : next larger
1299/// next = kFALSE : previous smaller
1300///
1301/// Used by the autobin power of 2 algorithm
1302
1304{
1305 Int_t nn;
1306 Double_t f2 = std::frexp(x, &nn);
1307 return ((next && x > 0.) || (!next && x <= 0.)) ? std::ldexp(std::copysign(1., f2), nn)
1308 : std::ldexp(std::copysign(1., f2), --nn);
1309}
1310
1311////////////////////////////////////////////////////////////////////////////////
1312/// Auxiliary function to get the next power of 2 integer value larger then n
1313///
1314/// Used by the autobin power of 2 algorithm
1315
1317{
1318 Int_t nn;
1319 Double_t f2 = std::frexp(n, &nn);
1320 if (TMath::Abs(f2 - .5) > 0.001)
1321 return (Int_t)std::ldexp(1., nn);
1322 return n;
1323}
1324
1325////////////////////////////////////////////////////////////////////////////////
1326/// Buffer-based estimate of the histogram range using the power of 2 algorithm.
1327///
1328/// Used by the autobin power of 2 algorithm.
1329///
1330/// Works on arguments (min and max from fBuffer) and internal inputs: fXmin,
1331/// fXmax, NBinsX (from fXaxis), ...
1332/// Result save internally in fXaxis.
1333///
1334/// Overloaded by TH2 and TH3.
1335///
1336/// Return -1 if internal inputs are inconsistent, 0 otherwise.
1337
1339{
1340 // We need meaningful raw limits
1341 if (xmi >= xma)
1342 return -1;
1343
1344 THLimitsFinder::GetLimitsFinder()->FindGoodLimits(this, xmi, xma);
1347
1348 // Now adjust
1349 if (TMath::Abs(xhma) > TMath::Abs(xhmi)) {
1350 // Start from the upper limit
1353 } else {
1354 // Start from the lower limit
1357 }
1358
1359 // Round the bins to the next power of 2; take into account the possible inflation
1360 // of the range
1361 Double_t rr = (xhma - xhmi) / (xma - xmi);
1363
1364 // Adjust using the same bin width and offsets
1365 Double_t bw = (xhma - xhmi) / nb;
1366 // Bins to left free on each side
1367 Double_t autoside = gEnv->GetValue("Hist.Binning.Auto.Side", 0.05);
1368 Int_t nbside = (Int_t)(nb * autoside);
1369
1370 // Side up
1371 Int_t nbup = (xhma - xma) / bw;
1372 if (nbup % 2 != 0)
1373 nbup++; // Must be even
1374 if (nbup != nbside) {
1375 // Accounts also for both case: larger or smaller
1376 xhma -= bw * (nbup - nbside);
1377 nb -= (nbup - nbside);
1378 }
1379
1380 // Side low
1381 Int_t nblw = (xmi - xhmi) / bw;
1382 if (nblw % 2 != 0)
1383 nblw++; // Must be even
1384 if (nblw != nbside) {
1385 // Accounts also for both case: larger or smaller
1386 xhmi += bw * (nblw - nbside);
1387 nb -= (nblw - nbside);
1388 }
1389
1390 // Set everything and project
1391 SetBins(nb, xhmi, xhma);
1392
1393 // Done
1394 return 0;
1395}
1396
1397/// Fill histogram with all entries in the buffer.
1398///
1399/// - action = -1 histogram is reset and refilled from the buffer (called by THistPainter::Paint)
1400/// - action = 0 histogram is reset and filled from the buffer. When the histogram is filled from the
1401/// buffer the value fBuffer[0] is set to a negative number (= - number of entries)
1402/// When calling with action == 0 the histogram is NOT refilled when fBuffer[0] is < 0
1403/// While when calling with action = -1 the histogram is reset and ALWAYS refilled independently if
1404/// the histogram was filled before. This is needed when drawing the histogram
1405/// - action = 1 histogram is filled and buffer is deleted
1406/// The buffer is automatically deleted when filling the histogram and the entries is
1407/// larger than the buffer size
1408
1410{
1411 // do we need to compute the bin size?
1412 if (!fBuffer) return 0;
1414
1415 // nbentries correspond to the number of entries of histogram
1416
1417 if (nbentries == 0) {
1418 // if action is 1 we delete the buffer
1419 // this will avoid infinite recursion
1420 if (action > 0) {
1421 delete [] fBuffer;
1422 fBuffer = nullptr;
1423 fBufferSize = 0;
1424 }
1425 return 0;
1426 }
1427 if (nbentries < 0 && action == 0) return 0; // case histogram has been already filled from the buffer
1428
1429 Double_t *buffer = fBuffer;
1430 if (nbentries < 0) {
1432 // a reset might call BufferEmpty() giving an infinite recursion
1433 // Protect it by setting fBuffer = nullptr
1434 fBuffer = nullptr;
1435 //do not reset the list of functions
1436 Reset("ICES");
1437 fBuffer = buffer;
1438 }
1439 if (CanExtendAllAxes() || (fXaxis.GetXmax() <= fXaxis.GetXmin())) {
1440 //find min, max of entries in buffer
1443 for (Int_t i=0;i<nbentries;i++) {
1444 Double_t x = fBuffer[2*i+2];
1445 // skip infinity or NaN values
1446 if (!std::isfinite(x)) continue;
1447 if (x < xmin) xmin = x;
1448 if (x > xmax) xmax = x;
1449 }
1450 if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
1451 Int_t rc = -1;
1453 if ((rc = AutoP2FindLimits(xmin, xmax)) < 0)
1454 Warning("BufferEmpty",
1455 "inconsistency found by power-of-2 autobin algorithm: fallback to standard method");
1456 }
1457 if (rc < 0)
1458 THLimitsFinder::GetLimitsFinder()->FindGoodLimits(this, xmin, xmax);
1459 } else {
1460 fBuffer = nullptr;
1463 if (xmax >= fXaxis.GetXmax()) ExtendAxis(xmax, &fXaxis);
1464 fBuffer = buffer;
1465 fBufferSize = keep;
1466 }
1467 }
1468
1469 // call DoFillN which will not put entries in the buffer as FillN does
1470 // set fBuffer to zero to avoid re-emptying the buffer from functions called
1471 // by DoFillN (e.g Sumw2)
1472 buffer = fBuffer; fBuffer = nullptr;
1473 DoFillN(nbentries,&buffer[2],&buffer[1],2);
1474 fBuffer = buffer;
1475
1476 // if action == 1 - delete the buffer
1477 if (action > 0) {
1478 delete [] fBuffer;
1479 fBuffer = nullptr;
1480 fBufferSize = 0;
1481 } else {
1482 // if number of entries is consistent with buffer - set it negative to avoid
1483 // refilling the histogram every time BufferEmpty(0) is called
1484 // In case it is not consistent, by setting fBuffer[0]=0 is like resetting the buffer
1485 // (it will not be used anymore the next time BufferEmpty is called)
1486 if (nbentries == (Int_t)fEntries)
1487 fBuffer[0] = -nbentries;
1488 else
1489 fBuffer[0] = 0;
1490 }
1491 return nbentries;
1492}
1493
1494////////////////////////////////////////////////////////////////////////////////
1495/// accumulate arguments in buffer. When buffer is full, empty the buffer
1496///
1497/// - `fBuffer[0]` = number of entries in buffer
1498/// - `fBuffer[1]` = w of first entry
1499/// - `fBuffer[2]` = x of first entry
1500
1502{
1503 if (!fBuffer) return -2;
1505
1506
1507 if (nbentries < 0) {
1508 // reset nbentries to a positive value so next time BufferEmpty() is called
1509 // the histogram will be refilled
1511 fBuffer[0] = nbentries;
1512 if (fEntries > 0) {
1513 // set fBuffer to zero to avoid calling BufferEmpty in Reset
1514 Double_t *buffer = fBuffer; fBuffer=nullptr;
1515 Reset("ICES"); // do not reset list of functions
1516 fBuffer = buffer;
1517 }
1518 }
1519 if (2*nbentries+2 >= fBufferSize) {
1520 BufferEmpty(1);
1521 if (!fBuffer)
1522 // to avoid infinite recursion Fill->BufferFill->Fill
1523 return Fill(x,w);
1524 // this cannot happen
1525 R__ASSERT(0);
1526 }
1527 fBuffer[2*nbentries+1] = w;
1528 fBuffer[2*nbentries+2] = x;
1529 fBuffer[0] += 1;
1530 return -2;
1531}
1532
1533////////////////////////////////////////////////////////////////////////////////
1534/// Check bin limits.
1535
1536bool TH1::CheckBinLimits(const TAxis* a1, const TAxis * a2)
1537{
1538 const TArrayD * h1Array = a1->GetXbins();
1539 const TArrayD * h2Array = a2->GetXbins();
1540 Int_t fN = h1Array->fN;
1541 if ( fN != 0 ) {
1542 if ( h2Array->fN != fN ) {
1543 return false;
1544 }
1545 else {
1546 for ( int i = 0; i < fN; ++i ) {
1547 // for i==fN (nbin+1) a->GetBinWidth() returns last bin width
1548 // we do not need to exclude that case
1549 double binWidth = a1->GetBinWidth(i);
1550 if ( ! TMath::AreEqualAbs( h1Array->GetAt(i), h2Array->GetAt(i), binWidth*1E-10 ) ) {
1551 return false;
1552 }
1553 }
1554 }
1555 }
1556
1557 return true;
1558}
1559
1560////////////////////////////////////////////////////////////////////////////////
1561/// Check that axis have same labels.
1562
1563bool TH1::CheckBinLabels(const TAxis* a1, const TAxis * a2)
1564{
1565 THashList *l1 = a1->GetLabels();
1566 THashList *l2 = a2->GetLabels();
1567
1568 if (!l1 && !l2 )
1569 return true;
1570 if (!l1 || !l2 ) {
1571 return false;
1572 }
1573 // check now labels sizes are the same
1574 if (l1->GetSize() != l2->GetSize() ) {
1575 return false;
1576 }
1577 for (int i = 1; i <= a1->GetNbins(); ++i) {
1578 TString label1 = a1->GetBinLabel(i);
1579 TString label2 = a2->GetBinLabel(i);
1580 if (label1 != label2) {
1581 return false;
1582 }
1583 }
1584
1585 return true;
1586}
1587
1588////////////////////////////////////////////////////////////////////////////////
1589/// Check that the axis limits of the histograms are the same.
1590/// If a first and last bin is passed the axis is compared between the given range
1591
1592bool TH1::CheckAxisLimits(const TAxis *a1, const TAxis *a2 )
1593{
1594 double firstBin = a1->GetBinWidth(1);
1595 double lastBin = a1->GetBinWidth( a1->GetNbins() );
1596 if ( ! TMath::AreEqualAbs(a1->GetXmin(), a2->GetXmin(), firstBin* 1.E-10) ||
1597 ! TMath::AreEqualAbs(a1->GetXmax(), a2->GetXmax(), lastBin*1.E-10) ) {
1598 return false;
1599 }
1600 return true;
1601}
1602
1603////////////////////////////////////////////////////////////////////////////////
1604/// Check that the axis are the same
1605
1606bool TH1::CheckEqualAxes(const TAxis *a1, const TAxis *a2 )
1607{
1608 if (a1->GetNbins() != a2->GetNbins() ) {
1609 ::Info("CheckEqualAxes","Axes have different number of bins : nbin1 = %d nbin2 = %d",a1->GetNbins(),a2->GetNbins() );
1610 return false;
1611 }
1612 if(!CheckAxisLimits(a1,a2)) {
1613 ::Info("CheckEqualAxes","Axes have different limits");
1614 return false;
1615 }
1616 if(!CheckBinLimits(a1,a2)) {
1617 ::Info("CheckEqualAxes","Axes have different bin limits");
1618 return false;
1619 }
1620
1621 // check labels
1622 if(!CheckBinLabels(a1,a2)) {
1623 ::Info("CheckEqualAxes","Axes have different labels");
1624 return false;
1625 }
1626
1627 return true;
1628}
1629
1630////////////////////////////////////////////////////////////////////////////////
1631/// Check that two sub axis are the same.
1632/// The limits are defined by first bin and last bin
1633/// N.B. no check is done in this case for variable bins
1634
1636{
1637 // By default is assumed that no bins are given for the second axis
1639 Double_t xmin1 = a1->GetBinLowEdge(firstBin1);
1640 Double_t xmax1 = a1->GetBinUpEdge(lastBin1);
1641
1642 Int_t nbins2 = a2->GetNbins();
1643 Double_t xmin2 = a2->GetXmin();
1644 Double_t xmax2 = a2->GetXmax();
1645
1646 if (firstBin2 < lastBin2) {
1647 // in this case assume no bins are given for the second axis
1649 xmin2 = a1->GetBinLowEdge(firstBin1);
1650 xmax2 = a1->GetBinUpEdge(lastBin1);
1651 }
1652
1653 if (nbins1 != nbins2 ) {
1654 ::Info("CheckConsistentSubAxes","Axes have different number of bins");
1655 return false;
1656 }
1657
1658 Double_t firstBin = a1->GetBinWidth(firstBin1);
1659 Double_t lastBin = a1->GetBinWidth(lastBin1);
1660 if ( ! TMath::AreEqualAbs(xmin1,xmin2,1.E-10 * firstBin) ||
1661 ! TMath::AreEqualAbs(xmax1,xmax2,1.E-10 * lastBin) ) {
1662 ::Info("CheckConsistentSubAxes","Axes have different limits");
1663 return false;
1664 }
1665
1666 return true;
1667}
1668
1669////////////////////////////////////////////////////////////////////////////////
1670/// Check histogram compatibility.
1671/// The returned integer is part of EInconsistencyBits
1672/// The value 0 means that the histograms are compatible
1673
1675{
1676 if (h1 == h2) return kFullyConsistent;
1677
1678 if (h1->GetDimension() != h2->GetDimension() ) {
1679 return kDifferentDimensions;
1680 }
1681 Int_t dim = h1->GetDimension();
1682
1683 // returns kTRUE if number of bins and bin limits are identical
1684 Int_t nbinsx = h1->GetNbinsX();
1685 Int_t nbinsy = h1->GetNbinsY();
1686 Int_t nbinsz = h1->GetNbinsZ();
1687
1688 // Check whether the histograms have the same number of bins.
1689 if (nbinsx != h2->GetNbinsX() ||
1690 (dim > 1 && nbinsy != h2->GetNbinsY()) ||
1691 (dim > 2 && nbinsz != h2->GetNbinsZ()) ) {
1693 }
1694
1695 bool ret = true;
1696
1697 // check axis limits
1698 ret &= CheckAxisLimits(h1->GetXaxis(), h2->GetXaxis());
1699 if (dim > 1) ret &= CheckAxisLimits(h1->GetYaxis(), h2->GetYaxis());
1700 if (dim > 2) ret &= CheckAxisLimits(h1->GetZaxis(), h2->GetZaxis());
1701 if (!ret) return kDifferentAxisLimits;
1702
1703 // check bin limits
1704 ret &= CheckBinLimits(h1->GetXaxis(), h2->GetXaxis());
1705 if (dim > 1) ret &= CheckBinLimits(h1->GetYaxis(), h2->GetYaxis());
1706 if (dim > 2) ret &= CheckBinLimits(h1->GetZaxis(), h2->GetZaxis());
1707 if (!ret) return kDifferentBinLimits;
1708
1709 // check labels if histograms are both not empty
1710 if ( !h1->IsEmpty() && !h2->IsEmpty() ) {
1711 ret &= CheckBinLabels(h1->GetXaxis(), h2->GetXaxis());
1712 if (dim > 1) ret &= CheckBinLabels(h1->GetYaxis(), h2->GetYaxis());
1713 if (dim > 2) ret &= CheckBinLabels(h1->GetZaxis(), h2->GetZaxis());
1714 if (!ret) return kDifferentLabels;
1715 }
1716
1717 return kFullyConsistent;
1718}
1719
1720////////////////////////////////////////////////////////////////////////////////
1721/// \f$ \chi^{2} \f$ test for comparing weighted and unweighted histograms.
1722///
1723/// Compares the histograms' adjusted (normalized) residuals.
1724/// Function: Returns p-value. Other return values are specified by the 3rd parameter
1725///
1726/// \param[in] h2 the second histogram
1727/// \param[in] option
1728/// - "UU" = experiment experiment comparison (unweighted-unweighted)
1729/// - "UW" = experiment MC comparison (unweighted-weighted). Note that
1730/// the first histogram should be unweighted
1731/// - "WW" = MC MC comparison (weighted-weighted)
1732/// - "NORM" = to be used when one or both of the histograms is scaled
1733/// but the histogram originally was unweighted
1734/// - by default underflows and overflows are not included:
1735/// * "OF" = overflows included
1736/// * "UF" = underflows included
1737/// - "P" = print chi2, ndf, p_value, igood
1738/// - "CHI2" = returns chi2 instead of p-value
1739/// - "CHI2/NDF" = returns \f$ \chi^{2} \f$/ndf
1740/// \param[in] res not empty - computes normalized residuals and returns them in this array
1741///
1742/// The current implementation is based on the papers \f$ \chi^{2} \f$ test for comparison
1743/// of weighted and unweighted histograms" in Proceedings of PHYSTAT05 and
1744/// "Comparison weighted and unweighted histograms", arXiv:physics/0605123
1745/// by N.Gagunashvili. This function has been implemented by Daniel Haertl in August 2006.
1746///
1747/// #### Introduction:
1748///
1749/// A frequently used technique in data analysis is the comparison of
1750/// histograms. First suggested by Pearson [1] the \f$ \chi^{2} \f$ test of
1751/// homogeneity is used widely for comparing usual (unweighted) histograms.
1752/// This paper describes the implementation modified \f$ \chi^{2} \f$ tests
1753/// for comparison of weighted and unweighted histograms and two weighted
1754/// histograms [2] as well as usual Pearson's \f$ \chi^{2} \f$ test for
1755/// comparison two usual (unweighted) histograms.
1756///
1757/// #### Overview:
1758///
1759/// Comparison of two histograms expect hypotheses that two histograms
1760/// represent identical distributions. To make a decision p-value should
1761/// be calculated. The hypotheses of identity is rejected if the p-value is
1762/// lower then some significance level. Traditionally significance levels
1763/// 0.1, 0.05 and 0.01 are used. The comparison procedure should include an
1764/// analysis of the residuals which is often helpful in identifying the
1765/// bins of histograms responsible for a significant overall \f$ \chi^{2} \f$ value.
1766/// Residuals are the difference between bin contents and expected bin
1767/// contents. Most convenient for analysis are the normalized residuals. If
1768/// hypotheses of identity are valid then normalized residuals are
1769/// approximately independent and identically distributed random variables
1770/// having N(0,1) distribution. Analysis of residuals expect test of above
1771/// mentioned properties of residuals. Notice that indirectly the analysis
1772/// of residuals increase the power of \f$ \chi^{2} \f$ test.
1773///
1774/// #### Methods of comparison:
1775///
1776/// \f$ \chi^{2} \f$ test for comparison two (unweighted) histograms:
1777/// Let us consider two histograms with the same binning and the number
1778/// of bins equal to r. Let us denote the number of events in the ith bin
1779/// in the first histogram as ni and as mi in the second one. The total
1780/// number of events in the first histogram is equal to:
1781/// \f[
1782/// N = \sum_{i=1}^{r} n_{i}
1783/// \f]
1784/// and
1785/// \f[
1786/// M = \sum_{i=1}^{r} m_{i}
1787/// \f]
1788/// in the second histogram. The hypothesis of identity (homogeneity) [3]
1789/// is that the two histograms represent random values with identical
1790/// distributions. It is equivalent that there exist r constants p1,...,pr,
1791/// such that
1792/// \f[
1793///\sum_{i=1}^{r} p_{i}=1
1794/// \f]
1795/// and the probability of belonging to the ith bin for some measured value
1796/// in both experiments is equal to pi. The number of events in the ith
1797/// bin is a random variable with a distribution approximated by a Poisson
1798/// probability distribution
1799/// \f[
1800///\frac{e^{-Np_{i}}(Np_{i})^{n_{i}}}{n_{i}!}
1801/// \f]
1802///for the first histogram and with distribution
1803/// \f[
1804///\frac{e^{-Mp_{i}}(Mp_{i})^{m_{i}}}{m_{i}!}
1805/// \f]
1806/// for the second histogram. If the hypothesis of homogeneity is valid,
1807/// then the maximum likelihood estimator of pi, i=1,...,r, is
1808/// \f[
1809///\hat{p}_{i}= \frac{n_{i}+m_{i}}{N+M}
1810/// \f]
1811/// and then
1812/// \f[
1813/// 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}}
1814/// \f]
1815/// has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [3].
1816/// The comparison procedure can include an analysis of the residuals which
1817/// is often helpful in identifying the bins of histograms responsible for
1818/// a significant overall \f$ \chi^{2} \f$ value. Most convenient for
1819/// analysis are the adjusted (normalized) residuals [4]
1820/// \f[
1821/// 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))}}
1822/// \f]
1823/// If hypotheses of homogeneity are valid then residuals ri are
1824/// approximately independent and identically distributed random variables
1825/// having N(0,1) distribution. The application of the \f$ \chi^{2} \f$ test has
1826/// restrictions related to the value of the expected frequencies Npi,
1827/// Mpi, i=1,...,r. A conservative rule formulated in [5] is that all the
1828/// expectations must be 1 or greater for both histograms. In practical
1829/// cases when expected frequencies are not known the estimated expected
1830/// frequencies \f$ M\hat{p}_{i}, N\hat{p}_{i}, i=1,...,r \f$ can be used.
1831///
1832/// #### Unweighted and weighted histograms comparison:
1833///
1834/// A simple modification of the ideas described above can be used for the
1835/// comparison of the usual (unweighted) and weighted histograms. Let us
1836/// denote the number of events in the ith bin in the unweighted
1837/// histogram as ni and the common weight of events in the ith bin of the
1838/// weighted histogram as wi. The total number of events in the
1839/// unweighted histogram is equal to
1840///\f[
1841/// N = \sum_{i=1}^{r} n_{i}
1842///\f]
1843/// and the total weight of events in the weighted histogram is equal to
1844///\f[
1845/// W = \sum_{i=1}^{r} w_{i}
1846///\f]
1847/// Let us formulate the hypothesis of identity of an unweighted histogram
1848/// to a weighted histogram so that there exist r constants p1,...,pr, such
1849/// that
1850///\f[
1851/// \sum_{i=1}^{r} p_{i} = 1
1852///\f]
1853/// for the unweighted histogram. The weight wi is a random variable with a
1854/// distribution approximated by the normal probability distribution
1855/// \f$ N(Wp_{i},\sigma_{i}^{2}) \f$ where \f$ \sigma_{i}^{2} \f$ is the variance of the weight wi.
1856/// If we replace the variance \f$ \sigma_{i}^{2} \f$
1857/// with estimate \f$ s_{i}^{2} \f$ (sum of squares of weights of
1858/// events in the ith bin) and the hypothesis of identity is valid, then the
1859/// maximum likelihood estimator of pi,i=1,...,r, is
1860///\f[
1861/// \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}}
1862///\f]
1863/// We may then use the test statistic
1864///\f[
1865/// 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}}
1866///\f]
1867/// and it has approximately a \f$ \sigma^{2}_{(r-1)} \f$ distribution [2]. This test, as well
1868/// as the original one [3], has a restriction on the expected frequencies. The
1869/// expected frequencies recommended for the weighted histogram is more than 25.
1870/// The value of the minimal expected frequency can be decreased down to 10 for
1871/// the case when the weights of the events are close to constant. In the case
1872/// of a weighted histogram if the number of events is unknown, then we can
1873/// apply this recommendation for the equivalent number of events as
1874///\f[
1875/// n_{i}^{equiv} = \frac{ w_{i}^{2} }{ s_{i}^{2} }
1876///\f]
1877/// The minimal expected frequency for an unweighted histogram must be 1. Notice
1878/// that any usual (unweighted) histogram can be considered as a weighted
1879/// histogram with events that have constant weights equal to 1.
1880/// The variance \f$ z_{i}^{2} \f$ of the difference between the weight wi
1881/// and the estimated expectation value of the weight is approximately equal to:
1882///\f[
1883/// 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}
1884///\f]
1885/// The residuals
1886///\f[
1887/// r_{i} = \frac{w_{i}-W\hat{p}_{i}}{z_{i}}
1888///\f]
1889/// have approximately a normal distribution with mean equal to 0 and standard
1890/// deviation equal to 1.
1891///
1892/// #### Two weighted histograms comparison:
1893///
1894/// Let us denote the common weight of events of the ith bin in the first
1895/// histogram as w1i and as w2i in the second one. The total weight of events
1896/// in the first histogram is equal to
1897///\f[
1898/// W_{1} = \sum_{i=1}^{r} w_{1i}
1899///\f]
1900/// and
1901///\f[
1902/// W_{2} = \sum_{i=1}^{r} w_{2i}
1903///\f]
1904/// in the second histogram. Let us formulate the hypothesis of identity of
1905/// weighted histograms so that there exist r constants p1,...,pr, such that
1906///\f[
1907/// \sum_{i=1}^{r} p_{i} = 1
1908///\f]
1909/// and also expectation value of weight w1i equal to W1pi and expectation value
1910/// of weight w2i equal to W2pi. Weights in both the histograms are random
1911/// variables with distributions which can be approximated by a normal
1912/// probability distribution \f$ N(W_{1}p_{i},\sigma_{1i}^{2}) \f$ for the first histogram
1913/// and by a distribution \f$ N(W_{2}p_{i},\sigma_{2i}^{2}) \f$ for the second.
1914/// Here \f$ \sigma_{1i}^{2} \f$ and \f$ \sigma_{2i}^{2} \f$ are the variances
1915/// of w1i and w2i with estimators \f$ s_{1i}^{2} \f$ and \f$ s_{2i}^{2} \f$ respectively.
1916/// If the hypothesis of identity is valid, then the maximum likelihood and
1917/// Least Square Method estimator of pi,i=1,...,r, is
1918///\f[
1919/// \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}}
1920///\f]
1921/// We may then use the test statistic
1922///\f[
1923/// 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}}
1924///\f]
1925/// and it has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [2].
1926/// The normalized or studentised residuals [6]
1927///\f[
1928/// 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})}}}
1929///\f]
1930/// have approximately a normal distribution with mean equal to 0 and standard
1931/// deviation 1. A recommended minimal expected frequency is equal to 10 for
1932/// the proposed test.
1933///
1934/// #### Numerical examples:
1935///
1936/// The method described herein is now illustrated with an example.
1937/// We take a distribution
1938///\f[
1939/// \phi(x) = \frac{2}{(x-10)^{2}+1} + \frac{1}{(x-14)^{2}+1} (1)
1940///\f]
1941/// defined on the interval [4,16]. Events distributed according to the formula
1942/// (1) are simulated to create the unweighted histogram. Uniformly distributed
1943/// events are simulated for the weighted histogram with weights calculated by
1944/// formula (1). Each histogram has the same number of bins: 20. Fig.1 shows
1945/// the result of comparison of the unweighted histogram with 200 events
1946/// (minimal expected frequency equal to one) and the weighted histogram with
1947/// 500 events (minimal expected frequency equal to 25)
1948/// Begin_Macro
1949/// ../../../tutorials/math/chi2test.C
1950/// End_Macro
1951/// Fig 1. An example of comparison of the unweighted histogram with 200 events
1952/// and the weighted histogram with 500 events:
1953/// 1. unweighted histogram;
1954/// 2. weighted histogram;
1955/// 3. normalized residuals plot;
1956/// 4. normal Q-Q plot of residuals.
1957///
1958/// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1959/// 21.09 with p-value equal to 0.33, therefore the hypothesis of identity of
1960/// the two histograms can be accepted for 0.05 significant level. The behavior
1961/// of the normalized residuals plot (see Fig. 1c) and the normal Q-Q plot
1962/// (see Fig. 1d) of residuals are regular and we cannot identify the outliers
1963/// or bins with a big influence on \f$ \chi^{2} \f$.
1964///
1965/// The second example presents the same two histograms but 17 events was added
1966/// to content of bin number 15 in unweighted histogram. Fig.2 shows the result
1967/// of comparison of the unweighted histogram with 217 events (minimal expected
1968/// frequency equal to one) and the weighted histogram with 500 events (minimal
1969/// expected frequency equal to 25)
1970/// Begin_Macro
1971/// ../../../tutorials/math/chi2test.C(17)
1972/// End_Macro
1973/// Fig 2. An example of comparison of the unweighted histogram with 217 events
1974/// and the weighted histogram with 500 events:
1975/// 1. unweighted histogram;
1976/// 2. weighted histogram;
1977/// 3. normalized residuals plot;
1978/// 4. normal Q-Q plot of residuals.
1979///
1980/// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1981/// 32.33 with p-value equal to 0.029, therefore the hypothesis of identity of
1982/// the two histograms is rejected for 0.05 significant level. The behavior of
1983/// the normalized residuals plot (see Fig. 2c) and the normal Q-Q plot (see
1984/// Fig. 2d) of residuals are not regular and we can identify the outlier or
1985/// bin with a big influence on \f$ \chi^{2} \f$.
1986///
1987/// #### References:
1988///
1989/// - [1] Pearson, K., 1904. On the Theory of Contingency and Its Relation to
1990/// Association and Normal Correlation. Drapers' Co. Memoirs, Biometric
1991/// Series No. 1, London.
1992/// - [2] Gagunashvili, N., 2006. \f$ \sigma^{2} \f$ test for comparison
1993/// of weighted and unweighted histograms. Statistical Problems in Particle
1994/// Physics, Astrophysics and Cosmology, Proceedings of PHYSTAT05,
1995/// Oxford, UK, 12-15 September 2005, Imperial College Press, London, 43-44.
1996/// Gagunashvili,N., Comparison of weighted and unweighted histograms,
1997/// arXiv:physics/0605123, 2006.
1998/// - [3] Cramer, H., 1946. Mathematical methods of statistics.
1999/// Princeton University Press, Princeton.
2000/// - [4] Haberman, S.J., 1973. The analysis of residuals in cross-classified tables.
2001/// Biometrics 29, 205-220.
2002/// - [5] Lewontin, R.C. and Felsenstein, J., 1965. The robustness of homogeneity
2003/// test in 2xN tables. Biometrics 21, 19-33.
2004/// - [6] Seber, G.A.F., Lee, A.J., 2003, Linear Regression Analysis.
2005/// John Wiley & Sons Inc., New York.
2006
2007Double_t TH1::Chi2Test(const TH1* h2, Option_t *option, Double_t *res) const
2008{
2009 Double_t chi2 = 0;
2010 Int_t ndf = 0, igood = 0;
2011
2012 TString opt = option;
2013 opt.ToUpper();
2014
2015 Double_t prob = Chi2TestX(h2,chi2,ndf,igood,option,res);
2016
2017 if(opt.Contains("P")) {
2018 printf("Chi2 = %f, Prob = %g, NDF = %d, igood = %d\n", chi2,prob,ndf,igood);
2019 }
2020 if(opt.Contains("CHI2/NDF")) {
2021 if (ndf == 0) return 0;
2022 return chi2/ndf;
2023 }
2024 if(opt.Contains("CHI2")) {
2025 return chi2;
2026 }
2027
2028 return prob;
2029}
2030
2031////////////////////////////////////////////////////////////////////////////////
2032/// The computation routine of the Chisquare test. For the method description,
2033/// see Chi2Test() function.
2034///
2035/// \return p-value
2036/// \param[in] h2 the second histogram
2037/// \param[in] option
2038/// - "UU" = experiment experiment comparison (unweighted-unweighted)
2039/// - "UW" = experiment MC comparison (unweighted-weighted). Note that the first
2040/// histogram should be unweighted
2041/// - "WW" = MC MC comparison (weighted-weighted)
2042/// - "NORM" = if one or both histograms is scaled
2043/// - "OF" = overflows included
2044/// - "UF" = underflows included
2045/// by default underflows and overflows are not included
2046/// \param[out] igood test output
2047/// - igood=0 - no problems
2048/// - For unweighted unweighted comparison
2049/// - igood=1'There is a bin in the 1st histogram with less than 1 event'
2050/// - igood=2'There is a bin in the 2nd histogram with less than 1 event'
2051/// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
2052/// - For unweighted weighted comparison
2053/// - igood=1'There is a bin in the 1st histogram with less then 1 event'
2054/// - igood=2'There is a bin in the 2nd histogram with less then 10 effective number of events'
2055/// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
2056/// - For weighted weighted comparison
2057/// - igood=1'There is a bin in the 1st histogram with less then 10 effective
2058/// number of events'
2059/// - igood=2'There is a bin in the 2nd histogram with less then 10 effective
2060/// number of events'
2061/// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
2062/// \param[out] chi2 chisquare of the test
2063/// \param[out] ndf number of degrees of freedom (important, when both histograms have the same empty bins)
2064/// \param[out] res normalized residuals for further analysis
2065
2066Double_t TH1::Chi2TestX(const TH1* h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option, Double_t *res) const
2067{
2068
2072
2073 Double_t sum1 = 0.0, sumw1 = 0.0;
2074 Double_t sum2 = 0.0, sumw2 = 0.0;
2075
2076 chi2 = 0.0;
2077 ndf = 0;
2078
2079 TString opt = option;
2080 opt.ToUpper();
2081
2082 if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
2083
2084 const TAxis *xaxis1 = GetXaxis();
2085 const TAxis *xaxis2 = h2->GetXaxis();
2086 const TAxis *yaxis1 = GetYaxis();
2087 const TAxis *yaxis2 = h2->GetYaxis();
2088 const TAxis *zaxis1 = GetZaxis();
2089 const TAxis *zaxis2 = h2->GetZaxis();
2090
2091 Int_t nbinx1 = xaxis1->GetNbins();
2092 Int_t nbinx2 = xaxis2->GetNbins();
2093 Int_t nbiny1 = yaxis1->GetNbins();
2094 Int_t nbiny2 = yaxis2->GetNbins();
2095 Int_t nbinz1 = zaxis1->GetNbins();
2096 Int_t nbinz2 = zaxis2->GetNbins();
2097
2098 //check dimensions
2099 if (this->GetDimension() != h2->GetDimension() ){
2100 Error("Chi2TestX","Histograms have different dimensions.");
2101 return 0.0;
2102 }
2103
2104 //check number of channels
2105 if (nbinx1 != nbinx2) {
2106 Error("Chi2TestX","different number of x channels");
2107 }
2108 if (nbiny1 != nbiny2) {
2109 Error("Chi2TestX","different number of y channels");
2110 }
2111 if (nbinz1 != nbinz2) {
2112 Error("Chi2TestX","different number of z channels");
2113 }
2114
2115 //check for ranges
2116 i_start = j_start = k_start = 1;
2117 i_end = nbinx1;
2118 j_end = nbiny1;
2119 k_end = nbinz1;
2120
2121 if (xaxis1->TestBit(TAxis::kAxisRange)) {
2122 i_start = xaxis1->GetFirst();
2123 i_end = xaxis1->GetLast();
2124 }
2125 if (yaxis1->TestBit(TAxis::kAxisRange)) {
2126 j_start = yaxis1->GetFirst();
2127 j_end = yaxis1->GetLast();
2128 }
2129 if (zaxis1->TestBit(TAxis::kAxisRange)) {
2130 k_start = zaxis1->GetFirst();
2131 k_end = zaxis1->GetLast();
2132 }
2133
2134
2135 if (opt.Contains("OF")) {
2136 if (GetDimension() == 3) k_end = ++nbinz1;
2137 if (GetDimension() >= 2) j_end = ++nbiny1;
2138 if (GetDimension() >= 1) i_end = ++nbinx1;
2139 }
2140
2141 if (opt.Contains("UF")) {
2142 if (GetDimension() == 3) k_start = 0;
2143 if (GetDimension() >= 2) j_start = 0;
2144 if (GetDimension() >= 1) i_start = 0;
2145 }
2146
2147 ndf = (i_end - i_start + 1) * (j_end - j_start + 1) * (k_end - k_start + 1) - 1;
2148
2149 Bool_t comparisonUU = opt.Contains("UU");
2150 Bool_t comparisonUW = opt.Contains("UW");
2151 Bool_t comparisonWW = opt.Contains("WW");
2152 Bool_t scaledHistogram = opt.Contains("NORM");
2153
2154 if (scaledHistogram && !comparisonUU) {
2155 Info("Chi2TestX", "NORM option should be used together with UU option. It is ignored");
2156 }
2157
2158 // look at histo global bin content and effective entries
2159 Stat_t s[kNstat];
2160 GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
2161 Double_t sumBinContent1 = s[0];
2162 Double_t effEntries1 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
2163
2164 h2->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
2165 Double_t sumBinContent2 = s[0];
2166 Double_t effEntries2 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
2167
2168 if (!comparisonUU && !comparisonUW && !comparisonWW ) {
2169 // deduce automatically from type of histogram
2172 else comparisonUW = true;
2173 }
2174 else comparisonWW = true;
2175 }
2176 // check unweighted histogram
2177 if (comparisonUW) {
2179 Warning("Chi2TestX","First histogram is not unweighted and option UW has been requested");
2180 }
2181 }
2182 if ( (!scaledHistogram && comparisonUU) ) {
2184 Warning("Chi2TestX","Both histograms are not unweighted and option UU has been requested");
2185 }
2186 }
2187
2188
2189 //get number of events in histogram
2191 for (Int_t i = i_start; i <= i_end; ++i) {
2192 for (Int_t j = j_start; j <= j_end; ++j) {
2193 for (Int_t k = k_start; k <= k_end; ++k) {
2194
2195 Int_t bin = GetBin(i, j, k);
2196
2198 Double_t cnt2 = h2->RetrieveBinContent(bin);
2200 Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2201
2202 if (e1sq > 0.0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2203 else cnt1 = 0.0;
2204
2205 if (e2sq > 0.0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2206 else cnt2 = 0.0;
2207
2208 // sum contents
2209 sum1 += cnt1;
2210 sum2 += cnt2;
2211 sumw1 += e1sq;
2212 sumw2 += e2sq;
2213 }
2214 }
2215 }
2216 if (sumw1 <= 0.0 || sumw2 <= 0.0) {
2217 Error("Chi2TestX", "Cannot use option NORM when one histogram has all zero errors");
2218 return 0.0;
2219 }
2220
2221 } else {
2222 for (Int_t i = i_start; i <= i_end; ++i) {
2223 for (Int_t j = j_start; j <= j_end; ++j) {
2224 for (Int_t k = k_start; k <= k_end; ++k) {
2225
2226 Int_t bin = GetBin(i, j, k);
2227
2228 sum1 += RetrieveBinContent(bin);
2229 sum2 += h2->RetrieveBinContent(bin);
2230
2232 if ( comparisonUW || comparisonWW ) sumw2 += h2->GetBinErrorSqUnchecked(bin);
2233 }
2234 }
2235 }
2236 }
2237 //checks that the histograms are not empty
2238 if (sum1 == 0.0 || sum2 == 0.0) {
2239 Error("Chi2TestX","one histogram is empty");
2240 return 0.0;
2241 }
2242
2243 if ( comparisonWW && ( sumw1 <= 0.0 && sumw2 <= 0.0 ) ){
2244 Error("Chi2TestX","Hist1 and Hist2 have both all zero errors\n");
2245 return 0.0;
2246 }
2247
2248 //THE TEST
2249 Int_t m = 0, n = 0;
2250 //Experiment - experiment comparison
2251 if (comparisonUU) {
2252 Int_t resIndex = 0;
2253 Double_t sum = sum1 + sum2;
2254 for (Int_t i = i_start; i <= i_end; ++i) {
2255 for (Int_t j = j_start; j <= j_end; ++j) {
2256 for (Int_t k = k_start; k <= k_end; ++k) {
2257
2258 Int_t bin = GetBin(i, j, k);
2259
2261 Double_t cnt2 = h2->RetrieveBinContent(bin);
2262
2263 if (scaledHistogram) {
2264 // scale bin value to effective bin entries
2266 Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2267
2268 if (e1sq > 0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2269 else cnt1 = 0;
2270
2271 if (e2sq > 0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2272 else cnt2 = 0;
2273 }
2274
2275 if (Int_t(cnt1) == 0 && Int_t(cnt2) == 0) --ndf; // no data means one degree of freedom less
2276 else {
2277
2280 //Double_t nexp2 = binsum*sum2/sum;
2281
2282 if (res) res[resIndex] = (cnt1 - nexp1) / TMath::Sqrt(nexp1);
2283
2284 if (cnt1 < 1) ++m;
2285 if (cnt2 < 1) ++n;
2286
2287 //Habermann correction for residuals
2288 Double_t correc = (1. - sum1 / sum) * (1. - cntsum / sum);
2289 if (res) res[resIndex] /= TMath::Sqrt(correc);
2290 if (res) resIndex++;
2291 Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2292 chi2 += delta * delta / cntsum;
2293 }
2294 }
2295 }
2296 }
2297 chi2 /= sum1 * sum2;
2298
2299 // flag error only when of the two histogram is zero
2300 if (m) {
2301 igood += 1;
2302 Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2303 }
2304 if (n) {
2305 igood += 2;
2306 Info("Chi2TestX","There is a bin in h2 with less than 1 event.\n");
2307 }
2308
2310 return prob;
2311
2312 }
2313
2314 // unweighted - weighted comparison
2315 // case of error = 0 and content not zero is treated without problems by excluding second chi2 sum
2316 // and can be considered as a data-theory comparison
2317 if ( comparisonUW ) {
2318 Int_t resIndex = 0;
2319 for (Int_t i = i_start; i <= i_end; ++i) {
2320 for (Int_t j = j_start; j <= j_end; ++j) {
2321 for (Int_t k = k_start; k <= k_end; ++k) {
2322
2323 Int_t bin = GetBin(i, j, k);
2324
2326 Double_t cnt2 = h2->RetrieveBinContent(bin);
2327 Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2328
2329 // case both histogram have zero bin contents
2330 if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2331 --ndf; //no data means one degree of freedom less
2332 continue;
2333 }
2334
2335 // case weighted histogram has zero bin content and error
2336 if (cnt2 * cnt2 == 0 && e2sq == 0) {
2337 if (sumw2 > 0) {
2338 // use as approximated error as 1 scaled by a scaling ratio
2339 // estimated from the total sum weight and sum weight squared
2340 e2sq = sumw2 / sum2;
2341 }
2342 else {
2343 // return error because infinite discrepancy here:
2344 // bin1 != 0 and bin2 =0 in a histogram with all errors zero
2345 Error("Chi2TestX","Hist2 has in bin (%d,%d,%d) zero content and zero errors\n", i, j, k);
2346 chi2 = 0; return 0;
2347 }
2348 }
2349
2350 if (cnt1 < 1) m++;
2351 if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2352
2353 Double_t var1 = sum2 * cnt2 - sum1 * e2sq;
2354 Double_t var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2355
2356 // if cnt1 is zero and cnt2 = 1 and sum1 = sum2 var1 = 0 && var2 == 0
2357 // approximate by incrementing cnt1
2358 // LM (this need to be fixed for numerical errors)
2359 while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2360 sum1++;
2361 cnt1++;
2362 var1 = sum2 * cnt2 - sum1 * e2sq;
2363 var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2364 }
2366
2367 while (var1 + var2 == 0) {
2368 sum1++;
2369 cnt1++;
2370 var1 = sum2 * cnt2 - sum1 * e2sq;
2371 var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2372 while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2373 sum1++;
2374 cnt1++;
2375 var1 = sum2 * cnt2 - sum1 * e2sq;
2376 var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2377 }
2379 }
2380
2381 Double_t probb = (var1 + var2) / (2. * sum2 * sum2);
2382
2385
2388
2389 chi2 += delta1 * delta1 / nexp1;
2390
2391 if (e2sq > 0) {
2392 chi2 += delta2 * delta2 / e2sq;
2393 }
2394
2395 if (res) {
2396 if (e2sq > 0) {
2397 Double_t temp1 = sum2 * e2sq / var2;
2398 Double_t temp2 = 1.0 + (sum1 * e2sq - sum2 * cnt2) / var2;
2399 temp2 = temp1 * temp1 * sum1 * probb * (1.0 - probb) + temp2 * temp2 * e2sq / 4.0;
2400 // invert sign here
2401 res[resIndex] = - delta2 / TMath::Sqrt(temp2);
2402 }
2403 else
2404 res[resIndex] = delta1 / TMath::Sqrt(nexp1);
2405 resIndex++;
2406 }
2407 }
2408 }
2409 }
2410
2411 if (m) {
2412 igood += 1;
2413 Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2414 }
2415 if (n) {
2416 igood += 2;
2417 Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2418 }
2419
2420 Double_t prob = TMath::Prob(chi2, ndf);
2421
2422 return prob;
2423 }
2424
2425 // weighted - weighted comparison
2426 if (comparisonWW) {
2427 Int_t resIndex = 0;
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);
2434 Double_t cnt2 = h2->RetrieveBinContent(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[resIndex] = z;
2470 resIndex++;
2471 }
2472
2473 if (e1sq > 0 && cnt1 * cnt1 / e1sq < 10) m++;
2474 if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2475 }
2476 }
2477 }
2478 if (m) {
2479 igood += 1;
2480 Info("Chi2TestX","There is a bin in h1 with less than 10 effective events.\n");
2481 }
2482 if (n) {
2483 igood += 2;
2484 Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2485 }
2486 Double_t prob = TMath::Prob(chi2, ndf);
2487 return prob;
2488 }
2489 return 0;
2490}
2491////////////////////////////////////////////////////////////////////////////////
2492/// Compute and return the chisquare of this histogram with respect to a function
2493/// The chisquare is computed by weighting each histogram point by the bin error
2494/// By default the full range of the histogram is used, unless TAxis::SetRange or TAxis::SetRangeUser was called before.
2495/// Use option "R" for restricting the chisquare calculation to the given range of the function
2496/// Use option "L" for using the chisquare based on the poisson likelihood (Baker-Cousins Chisquare)
2497/// Use option "P" for using the Pearson chisquare based on the expected bin errors
2498
2500{
2501 if (!func) {
2502 Error("Chisquare","Function pointer is Null - return -1");
2503 return -1;
2504 }
2505
2506 TString opt(option); opt.ToUpper();
2507 bool useRange = opt.Contains("R");
2508 ROOT::Fit::EChisquareType type = ROOT::Fit::EChisquareType::kNeyman; // default chi2 with observed error
2511
2512 return ROOT::Fit::Chisquare(*this, *func, useRange, type);
2513}
2514
2515////////////////////////////////////////////////////////////////////////////////
2516/// Remove all the content from the underflow and overflow bins, without changing the number of entries
2517/// After calling this method, every undeflow and overflow bins will have content 0.0
2518/// The Sumw2 is also cleared, since there is no more content in the bins
2519
2521{
2522 for (Int_t bin = 0; bin < fNcells; ++bin)
2523 if (IsBinUnderflow(bin) || IsBinOverflow(bin)) {
2524 UpdateBinContent(bin, 0.0);
2525 if (fSumw2.fN) fSumw2.fArray[bin] = 0.0;
2526 }
2527}
2528
2529////////////////////////////////////////////////////////////////////////////////
2530/// Compute integral (normalized cumulative sum of bins) w/o under/overflows
2531/// The result is stored in fIntegral and used by the GetRandom functions.
2532/// This function is automatically called by GetRandom when the fIntegral
2533/// array does not exist or when the number of entries in the histogram
2534/// has changed since the previous call to GetRandom.
2535/// The resulting integral is normalized to 1.
2536/// If the routine is called with the onlyPositive flag set an error will
2537/// be produced in case of negative bin content and a NaN value returned
2538/// \param onlyPositive If set to true, an error will be produced and NaN will be returned
2539/// when a bin with negative number of entries is encountered.
2540/// \param option
2541/// - `""` (default) Compute the cumulative density function assuming current bin contents represent counts.
2542/// - `"width"` Computes the cumulative density function assuming current bin contents represent densities.
2543/// \return 1 if success, 0 if integral is zero, NAN if onlyPositive-test fails
2544
2546{
2547 if (fBuffer) BufferEmpty();
2549 // delete previously computed integral (if any)
2550 if (fIntegral) delete [] fIntegral;
2551
2552 // - Allocate space to store the integral and compute integral
2556 Int_t nbins = nbinsx * nbinsy * nbinsz;
2557
2558 fIntegral = new Double_t[nbins + 2];
2559 Int_t ibin = 0; fIntegral[ibin] = 0;
2560
2561 for (Int_t binz=1; binz <= nbinsz; ++binz) {
2563 for (Int_t biny=1; biny <= nbinsy; ++biny) {
2565 for (Int_t binx=1; binx <= nbinsx; ++binx) {
2567 ++ibin;
2569 if (useArea)
2570 y *= xWidth * yWidth * zWidth;
2571
2572 if (onlyPositive && y < 0) {
2573 Error("ComputeIntegral","Bin content is negative - return a NaN value");
2574 fIntegral[nbins] = TMath::QuietNaN();
2575 break;
2576 }
2577 fIntegral[ibin] = fIntegral[ibin - 1] + y;
2578 }
2579 }
2580 }
2581
2582 // - Normalize integral to 1
2583 if (fIntegral[nbins] == 0 ) {
2584 Error("ComputeIntegral", "Integral = 0, no hits in histogram bins (excluding over/underflow).");
2585 return 0;
2586 }
2587 for (Int_t bin=1; bin <= nbins; ++bin) fIntegral[bin] /= fIntegral[nbins];
2588 fIntegral[nbins+1] = fEntries;
2589 return fIntegral[nbins];
2590}
2591
2592////////////////////////////////////////////////////////////////////////////////
2593/// Return a pointer to the array of bins integral.
2594/// if the pointer fIntegral is null, TH1::ComputeIntegral is called
2595/// The array dimension is the number of bins in the histograms
2596/// including underflow and overflow (fNCells)
2597/// the last value integral[fNCells] is set to the number of entries of
2598/// the histogram
2599
2601{
2602 if (!fIntegral) ComputeIntegral();
2603 return fIntegral;
2604}
2605
2606////////////////////////////////////////////////////////////////////////////////
2607/// Return a pointer to a histogram containing the cumulative content.
2608/// The cumulative can be computed both in the forward (default) or backward
2609/// direction; the name of the new histogram is constructed from
2610/// the name of this histogram with the suffix "suffix" appended provided
2611/// by the user. If not provided a default suffix="_cumulative" is used.
2612///
2613/// The cumulative distribution is formed by filling each bin of the
2614/// resulting histogram with the sum of that bin and all previous
2615/// (forward == kTRUE) or following (forward = kFALSE) bins.
2616///
2617/// Note: while cumulative distributions make sense in one dimension, you
2618/// may not be getting what you expect in more than 1D because the concept
2619/// of a cumulative distribution is much trickier to define; make sure you
2620/// understand the order of summation before you use this method with
2621/// histograms of dimension >= 2.
2622///
2623/// Note 2: By default the cumulative is computed from bin 1 to Nbins
2624/// If an axis range is set, values between the minimum and maximum of the range
2625/// are set.
2626/// Setting an axis range can also be used for including underflow and overflow in
2627/// the cumulative (e.g. by setting h->GetXaxis()->SetRange(0, h->GetNbinsX()+1); )
2629
2630TH1 *TH1::GetCumulative(Bool_t forward, const char* suffix) const
2631{
2632 const Int_t firstX = fXaxis.GetFirst();
2633 const Int_t lastX = fXaxis.GetLast();
2634 const Int_t firstY = (fDimension > 1) ? fYaxis.GetFirst() : 1;
2635 const Int_t lastY = (fDimension > 1) ? fYaxis.GetLast() : 1;
2636 const Int_t firstZ = (fDimension > 1) ? fZaxis.GetFirst() : 1;
2637 const Int_t lastZ = (fDimension > 1) ? fZaxis.GetLast() : 1;
2638
2640 hintegrated->Reset();
2641 Double_t sum = 0.;
2642 Double_t esum = 0;
2643 if (forward) { // Forward computation
2644 for (Int_t binz = firstZ; binz <= lastZ; ++binz) {
2645 for (Int_t biny = firstY; biny <= lastY; ++biny) {
2646 for (Int_t binx = firstX; binx <= lastX; ++binx) {
2647 const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2648 sum += RetrieveBinContent(bin);
2649 hintegrated->AddBinContent(bin, sum);
2650 if (fSumw2.fN) {
2652 hintegrated->fSumw2.fArray[bin] = esum;
2653 }
2654 }
2655 }
2656 }
2657 } else { // Backward computation
2658 for (Int_t binz = lastZ; binz >= firstZ; --binz) {
2659 for (Int_t biny = lastY; biny >= firstY; --biny) {
2660 for (Int_t binx = lastX; binx >= firstX; --binx) {
2661 const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2662 sum += RetrieveBinContent(bin);
2663 hintegrated->AddBinContent(bin, sum);
2664 if (fSumw2.fN) {
2666 hintegrated->fSumw2.fArray[bin] = esum;
2667 }
2668 }
2669 }
2670 }
2671 }
2672 return hintegrated;
2673}
2674
2675////////////////////////////////////////////////////////////////////////////////
2676/// Copy this histogram structure to newth1.
2677///
2678/// Note that this function does not copy the list of associated functions.
2679/// Use TObject::Clone to make a full copy of a histogram.
2680///
2681/// Note also that the histogram it will be created in gDirectory (if AddDirectoryStatus()=true)
2682/// or will not be added to any directory if AddDirectoryStatus()=false
2683/// independently of the current directory stored in the original histogram
2684
2685void TH1::Copy(TObject &obj) const
2686{
2687 if (((TH1&)obj).fDirectory) {
2688 // We are likely to change the hash value of this object
2689 // with TNamed::Copy, to keep things correct, we need to
2690 // clean up its existing entries.
2691 ((TH1&)obj).fDirectory->Remove(&obj);
2692 ((TH1&)obj).fDirectory = nullptr;
2693 }
2694 TNamed::Copy(obj);
2695 ((TH1&)obj).fDimension = fDimension;
2696 ((TH1&)obj).fNormFactor= fNormFactor;
2697 ((TH1&)obj).fNcells = fNcells;
2698 ((TH1&)obj).fBarOffset = fBarOffset;
2699 ((TH1&)obj).fBarWidth = fBarWidth;
2700 ((TH1&)obj).fOption = fOption;
2701 ((TH1&)obj).fBinStatErrOpt = fBinStatErrOpt;
2702 ((TH1&)obj).fBufferSize= fBufferSize;
2703 // copy the Buffer
2704 // delete first a previously existing buffer
2705 if (((TH1&)obj).fBuffer != nullptr) {
2706 delete [] ((TH1&)obj).fBuffer;
2707 ((TH1&)obj).fBuffer = nullptr;
2708 }
2709 if (fBuffer) {
2710 Double_t *buf = new Double_t[fBufferSize];
2711 for (Int_t i=0;i<fBufferSize;i++) buf[i] = fBuffer[i];
2712 // obj.fBuffer has been deleted before
2713 ((TH1&)obj).fBuffer = buf;
2714 }
2715
2716 // copy bin contents (this should be done by the derived classes, since TH1 does not store the bin content)
2717 // Do this in case derived from TArray
2718 TArray* a = dynamic_cast<TArray*>(&obj);
2719 if (a) {
2720 a->Set(fNcells);
2721 for (Int_t i = 0; i < fNcells; i++)
2723 }
2724
2725 ((TH1&)obj).fEntries = fEntries;
2726
2727 // which will call BufferEmpty(0) and set fBuffer[0] to a Maybe one should call
2728 // assignment operator on the TArrayD
2729
2730 ((TH1&)obj).fTsumw = fTsumw;
2731 ((TH1&)obj).fTsumw2 = fTsumw2;
2732 ((TH1&)obj).fTsumwx = fTsumwx;
2733 ((TH1&)obj).fTsumwx2 = fTsumwx2;
2734 ((TH1&)obj).fMaximum = fMaximum;
2735 ((TH1&)obj).fMinimum = fMinimum;
2736
2737 TAttLine::Copy(((TH1&)obj));
2738 TAttFill::Copy(((TH1&)obj));
2739 TAttMarker::Copy(((TH1&)obj));
2740 fXaxis.Copy(((TH1&)obj).fXaxis);
2741 fYaxis.Copy(((TH1&)obj).fYaxis);
2742 fZaxis.Copy(((TH1&)obj).fZaxis);
2743 ((TH1&)obj).fXaxis.SetParent(&obj);
2744 ((TH1&)obj).fYaxis.SetParent(&obj);
2745 ((TH1&)obj).fZaxis.SetParent(&obj);
2746 fContour.Copy(((TH1&)obj).fContour);
2747 fSumw2.Copy(((TH1&)obj).fSumw2);
2748 // fFunctions->Copy(((TH1&)obj).fFunctions);
2749 // when copying an histogram if the AddDirectoryStatus() is true it
2750 // will be added to gDirectory independently of the fDirectory stored.
2751 // and if the AddDirectoryStatus() is false it will not be added to
2752 // any directory (fDirectory = nullptr)
2753 if (fgAddDirectory && gDirectory) {
2754 gDirectory->Append(&obj);
2755 ((TH1&)obj).fFunctions->UseRWLock();
2756 ((TH1&)obj).fDirectory = gDirectory;
2757 } else
2758 ((TH1&)obj).fDirectory = nullptr;
2759
2760}
2761
2762////////////////////////////////////////////////////////////////////////////////
2763/// Make a complete copy of the underlying object. If 'newname' is set,
2764/// the copy's name will be set to that name.
2765
2766TObject* TH1::Clone(const char* newname) const
2767{
2768 TH1* obj = (TH1*)IsA()->GetNew()(nullptr);
2769 Copy(*obj);
2770
2771 // Now handle the parts that Copy doesn't do
2772 if(fFunctions) {
2773 // The Copy above might have published 'obj' to the ListOfCleanups.
2774 // Clone can call RecursiveRemove, for example via TCheckHashRecursiveRemoveConsistency
2775 // when dictionary information is initialized, so we need to
2776 // keep obj->fFunction valid during its execution and
2777 // protect the update with the write lock.
2778
2779 // Reset stats parent - else cloning the stats will clone this histogram, too.
2780 auto oldstats = dynamic_cast<TVirtualPaveStats*>(fFunctions->FindObject("stats"));
2781 TObject *oldparent = nullptr;
2782 if (oldstats) {
2783 oldparent = oldstats->GetParent();
2784 oldstats->SetParent(nullptr);
2785 }
2786
2787 auto newlist = (TList*)fFunctions->Clone();
2788
2789 if (oldstats)
2790 oldstats->SetParent(oldparent);
2791 auto newstats = dynamic_cast<TVirtualPaveStats*>(obj->fFunctions->FindObject("stats"));
2792 if (newstats)
2793 newstats->SetParent(obj);
2794
2795 auto oldlist = obj->fFunctions;
2796 {
2798 obj->fFunctions = newlist;
2799 }
2800 delete oldlist;
2801 }
2802 if(newname && strlen(newname) ) {
2803 obj->SetName(newname);
2804 }
2805 return obj;
2806}
2807
2808////////////////////////////////////////////////////////////////////////////////
2809/// Perform the automatic addition of the histogram to the given directory
2810///
2811/// Note this function is called in place when the semantic requires
2812/// this object to be added to a directory (I.e. when being read from
2813/// a TKey or being Cloned)
2814
2816{
2818 if (addStatus) {
2819 SetDirectory(dir);
2820 if (dir) {
2822 }
2823 }
2824}
2825
2826////////////////////////////////////////////////////////////////////////////////
2827/// Compute distance from point px,py to a line.
2828///
2829/// Compute the closest distance of approach from point px,py to elements
2830/// of a histogram.
2831/// The distance is computed in pixels units.
2832///
2833/// #### Algorithm:
2834/// Currently, this simple model computes the distance from the mouse
2835/// to the histogram contour only.
2836
2838{
2839 if (!fPainter) return 9999;
2840 return fPainter->DistancetoPrimitive(px,py);
2841}
2842
2843////////////////////////////////////////////////////////////////////////////////
2844/// Performs the operation: `this = this/(c1*f1)`
2845/// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2846///
2847/// Only bins inside the function range are recomputed.
2848/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2849/// you should call Sumw2 before making this operation.
2850/// This is particularly important if you fit the histogram after TH1::Divide
2851///
2852/// The function return kFALSE if the divide operation failed
2853
2855{
2856 if (!f1) {
2857 Error("Divide","Attempt to divide by a non-existing function");
2858 return kFALSE;
2859 }
2860
2861 // delete buffer if it is there since it will become invalid
2862 if (fBuffer) BufferEmpty(1);
2863
2864 Int_t nx = GetNbinsX() + 2; // normal bins + uf / of
2865 Int_t ny = GetNbinsY() + 2;
2866 Int_t nz = GetNbinsZ() + 2;
2867 if (fDimension < 2) ny = 1;
2868 if (fDimension < 3) nz = 1;
2869
2870
2871 SetMinimum();
2872 SetMaximum();
2873
2874 // - Loop on bins (including underflows/overflows)
2875 Int_t bin, binx, biny, binz;
2876 Double_t cu, w;
2877 Double_t xx[3];
2878 Double_t *params = nullptr;
2879 f1->InitArgs(xx,params);
2880 for (binz = 0; binz < nz; ++binz) {
2881 xx[2] = fZaxis.GetBinCenter(binz);
2882 for (biny = 0; biny < ny; ++biny) {
2883 xx[1] = fYaxis.GetBinCenter(biny);
2884 for (binx = 0; binx < nx; ++binx) {
2885 xx[0] = fXaxis.GetBinCenter(binx);
2886 if (!f1->IsInside(xx)) continue;
2888 bin = binx + nx * (biny + ny * binz);
2889 cu = c1 * f1->EvalPar(xx);
2890 if (TF1::RejectedPoint()) continue;
2891 if (cu) w = RetrieveBinContent(bin) / cu;
2892 else w = 0;
2893 UpdateBinContent(bin, w);
2894 if (fSumw2.fN) {
2895 if (cu != 0) fSumw2.fArray[bin] = GetBinErrorSqUnchecked(bin) / (cu * cu);
2896 else fSumw2.fArray[bin] = 0;
2897 }
2898 }
2899 }
2900 }
2901 ResetStats();
2902 return kTRUE;
2903}
2904
2905////////////////////////////////////////////////////////////////////////////////
2906/// Divide this histogram by h1.
2907///
2908/// `this = this/h1`
2909/// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2910/// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
2911/// if not already set.
2912/// The resulting errors are calculated assuming uncorrelated histograms.
2913/// See the other TH1::Divide that gives the possibility to optionally
2914/// compute binomial errors.
2915///
2916/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2917/// you should call Sumw2 before making this operation.
2918/// This is particularly important if you fit the histogram after TH1::Scale
2919///
2920/// The function return kFALSE if the divide operation failed
2921
2922Bool_t TH1::Divide(const TH1 *h1)
2923{
2924 if (!h1) {
2925 Error("Divide", "Input histogram passed does not exist (NULL).");
2926 return kFALSE;
2927 }
2928
2929 // delete buffer if it is there since it will become invalid
2930 if (fBuffer) BufferEmpty(1);
2931
2932 if (LoggedInconsistency("Divide", this, h1) >= kDifferentNumberOfBins) {
2933 return false;
2934 }
2935
2936 // Create Sumw2 if h1 has Sumw2 set
2937 if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
2938
2939 // - Loop on bins (including underflows/overflows)
2940 for (Int_t i = 0; i < fNcells; ++i) {
2943 if (c1) UpdateBinContent(i, c0 / c1);
2944 else UpdateBinContent(i, 0);
2945
2946 if(fSumw2.fN) {
2947 if (c1 == 0) { fSumw2.fArray[i] = 0; continue; }
2948 Double_t c1sq = c1 * c1;
2949 fSumw2.fArray[i] = (GetBinErrorSqUnchecked(i) * c1sq + h1->GetBinErrorSqUnchecked(i) * c0 * c0) / (c1sq * c1sq);
2950 }
2951 }
2952 ResetStats();
2953 return kTRUE;
2954}
2955
2956////////////////////////////////////////////////////////////////////////////////
2957/// Replace contents of this histogram by the division of h1 by h2.
2958///
2959/// `this = c1*h1/(c2*h2)`
2960///
2961/// If errors are defined (see TH1::Sumw2), errors are also recalculated
2962/// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
2963/// if not already set.
2964/// The resulting errors are calculated assuming uncorrelated histograms.
2965/// However, if option ="B" is specified, Binomial errors are computed.
2966/// In this case c1 and c2 do not make real sense and they are ignored.
2967///
2968/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2969/// you should call Sumw2 before making this operation.
2970/// This is particularly important if you fit the histogram after TH1::Divide
2971///
2972/// Please note also that in the binomial case errors are calculated using standard
2973/// binomial statistics, which means when b1 = b2, the error is zero.
2974/// If you prefer to have efficiency errors not going to zero when the efficiency is 1, you must
2975/// use the function TGraphAsymmErrors::BayesDivide, which will return an asymmetric and non-zero lower
2976/// error for the case b1=b2.
2977///
2978/// The function return kFALSE if the divide operation failed
2979
2981{
2982
2983 TString opt = option;
2984 opt.ToLower();
2985 Bool_t binomial = kFALSE;
2986 if (opt.Contains("b")) binomial = kTRUE;
2987 if (!h1 || !h2) {
2988 Error("Divide", "At least one of the input histograms passed does not exist (NULL).");
2989 return kFALSE;
2990 }
2991
2992 // delete buffer if it is there since it will become invalid
2993 if (fBuffer) BufferEmpty(1);
2994
2995 if (LoggedInconsistency("Divide", this, h1) >= kDifferentNumberOfBins ||
2996 LoggedInconsistency("Divide", h1, h2) >= kDifferentNumberOfBins) {
2997 return false;
2998 }
2999
3000 if (!c2) {
3001 Error("Divide","Coefficient of dividing histogram cannot be zero");
3002 return kFALSE;
3003 }
3004
3005 // Create Sumw2 if h1 or h2 have Sumw2 set, or if binomial errors are explicitly requested
3006 if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0 || binomial)) Sumw2();
3007
3008 SetMinimum();
3009 SetMaximum();
3010
3011 // - Loop on bins (including underflows/overflows)
3012 for (Int_t i = 0; i < fNcells; ++i) {
3014 Double_t b2 = h2->RetrieveBinContent(i);
3015 if (b2) UpdateBinContent(i, c1 * b1 / (c2 * b2));
3016 else UpdateBinContent(i, 0);
3017
3018 if (fSumw2.fN) {
3019 if (b2 == 0) { fSumw2.fArray[i] = 0; continue; }
3020 Double_t b1sq = b1 * b1; Double_t b2sq = b2 * b2;
3021 Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
3023 Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
3024 if (binomial) {
3025 if (b1 != b2) {
3026 // in the case of binomial statistics c1 and c2 must be 1 otherwise it does not make sense
3027 // c1 and c2 are ignored
3028 //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/(c2*b2));//this is the formula in Hbook/Hoper1
3029 //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/b2); // old formula from G. Flucke
3030 // formula which works also for weighted histogram (see http://root-forum.cern.ch/viewtopic.php?t=3753 )
3031 fSumw2.fArray[i] = TMath::Abs( ( (1. - 2.* b1 / b2) * e1sq + b1sq * e2sq / b2sq ) / b2sq );
3032 } else {
3033 //in case b1=b2 error is zero
3034 //use TGraphAsymmErrors::BayesDivide for getting the asymmetric error not equal to zero
3035 fSumw2.fArray[i] = 0;
3036 }
3037 } else {
3038 fSumw2.fArray[i] = c1sq * c2sq * (e1sq * b2sq + e2sq * b1sq) / (c2sq * c2sq * b2sq * b2sq);
3039 }
3040 }
3041 }
3042 ResetStats();
3043 if (binomial)
3044 // in case of binomial division use denominator for number of entries
3045 SetEntries ( h2->GetEntries() );
3046
3047 return kTRUE;
3048}
3049
3050////////////////////////////////////////////////////////////////////////////////
3051/// Draw this histogram with options.
3052///
3053/// Histograms are drawn via the THistPainter class. Each histogram has
3054/// a pointer to its own painter (to be usable in a multithreaded program).
3055/// The same histogram can be drawn with different options in different pads.
3056/// If a histogram is updated after it has been drawn, the updated data will
3057/// be shown the next time the pad is updated. One does not need to
3058/// redraw the histogram.
3059///
3060/// When a histogram is deleted, the histogram is **automatically removed from
3061/// all pads where it was drawn**. If a histogram should be modified or deleted
3062/// without affecting what is drawn, it should be drawn using DrawCopy().
3063///
3064/// By default, TH1::Draw clears the current pad. Passing the option "SAME", the
3065/// histogram will be drawn on top of what's in the pad.
3066/// One can use TH1::SetMaximum and TH1::SetMinimum to force a particular
3067/// value for the maximum or the minimum scale on the plot.
3068///
3069/// TH1::UseCurrentStyle can be used to change all histogram graphics
3070/// attributes to correspond to the current selected style.
3071/// This function must be called for each histogram.
3072/// In case one reads and draws many histograms from a file, one can force
3073/// the histograms to inherit automatically the current graphics style
3074/// by calling before gROOT->ForceStyle();
3075///
3076/// See the THistPainter class for a description of all the drawing options.
3077
3079{
3080 TString opt1 = option; opt1.ToLower();
3082 Int_t index = opt1.Index("same");
3083
3084 // Check if the string "same" is part of a TCutg name.
3085 if (index>=0) {
3086 Int_t indb = opt1.Index("[");
3087 if (indb>=0) {
3088 Int_t indk = opt1.Index("]");
3089 if (index>indb && index<indk) index = -1;
3090 }
3091 }
3092
3093 // If there is no pad or an empty pad the "same" option is ignored.
3094 if (gPad) {
3095 if (!gPad->IsEditable()) gROOT->MakeDefCanvas();
3096 if (index>=0) {
3097 if (gPad->GetX1() == 0 && gPad->GetX2() == 1 &&
3098 gPad->GetY1() == 0 && gPad->GetY2() == 1 &&
3099 gPad->GetListOfPrimitives()->GetSize()==0) opt2.Remove(index,4);
3100 } else {
3101 //the following statement is necessary in case one attempts to draw
3102 //a temporary histogram already in the current pad
3103 if (TestBit(kCanDelete)) gPad->Remove(this);
3104 gPad->Clear();
3105 }
3106 gPad->IncrementPaletteColor(1, opt1);
3107 } else {
3108 if (index>=0) opt2.Remove(index,4);
3109 }
3110
3111 AppendPad(opt2.Data());
3112}
3113
3114////////////////////////////////////////////////////////////////////////////////
3115/// Copy this histogram and Draw in the current pad.
3116///
3117/// Once the histogram is drawn into the pad, the original and its drawn copy can be modified or deleted without
3118/// affecting each other. The copied histogram will be owned by the pad, and is deleted when the pad is cleared.
3119///
3120/// DrawCopy() is useful if the original histogram is a temporary, e.g. from code such as
3121/// ~~~ {.cpp}
3122/// void someFunction(...) {
3123/// TH1D histogram(...);
3124/// histogram.DrawCopy();
3125///
3126/// // or equivalently
3127/// std::unique_ptr<TH1F> histogram(...);
3128/// histogram->DrawCopy();
3129/// }
3130/// ~~~
3131/// If Draw() has been used, the histograms would disappear from the canvas at the end of this function.
3132///
3133/// By default a postfix "_copy" is added to the histogram name. Pass an empty postfix in case
3134/// you want to draw a histogram with the same name.
3135///
3136/// See Draw() for the list of options.
3137///
3138/// In contrast to TObject::DrawClone(), DrawCopy
3139/// - Ignores `gROOT->SetSelectedPad()`.
3140/// - Does not register the histogram to any directory.
3141/// - And can cycle through a colour palette when multiple objects are drawn with auto colouring.
3142
3143TH1 *TH1::DrawCopy(Option_t *option, const char * name_postfix) const
3144{
3145 TString opt = option;
3146 opt.ToLower();
3147 if (gPad && !opt.Contains("same")) gPad->Clear();
3149 if (name_postfix) newName.Form("%s%s", GetName(), name_postfix);
3150 TH1 *newth1 = (TH1 *)Clone(newName.Data());
3151 newth1->SetDirectory(nullptr);
3152 newth1->SetBit(kCanDelete);
3153 if (gPad) gPad->IncrementPaletteColor(1, opt);
3154
3155 newth1->AppendPad(option);
3156 return newth1;
3157}
3158
3159////////////////////////////////////////////////////////////////////////////////
3160/// Draw a normalized copy of this histogram.
3161///
3162/// A clone of this histogram is normalized to norm and drawn with option.
3163/// A pointer to the normalized histogram is returned.
3164/// The contents of the histogram copy are scaled such that the new
3165/// sum of weights (excluding under and overflow) is equal to norm.
3166/// Note that the returned normalized histogram is not added to the list
3167/// of histograms in the current directory in memory.
3168/// It is the user's responsibility to delete this histogram.
3169/// The kCanDelete bit is set for the returned object. If a pad containing
3170/// this copy is cleared, the histogram will be automatically deleted.
3171///
3172/// See Draw for the list of options
3173
3175{
3177 if (sum == 0) {
3178 Error("DrawNormalized","Sum of weights is null. Cannot normalize histogram: %s",GetName());
3179 return nullptr;
3180 }
3181
3182 TDirectory::TContext ctx{nullptr};
3183 TH1 *h = (TH1*)Clone();
3185 // in case of drawing with error options - scale correctly the error
3186 TString opt(option); opt.ToUpper();
3187 if (fSumw2.fN == 0) {
3188 h->Sumw2();
3189 // do not use in this case the "Error option " for drawing which is enabled by default since the normalized histogram has now errors
3190 if (opt.IsNull() || opt == "SAME") opt += "HIST";
3191 }
3192 h->Scale(norm/sum);
3193 if (TMath::Abs(fMaximum+1111) > 1e-3) h->SetMaximum(fMaximum*norm/sum);
3194 if (TMath::Abs(fMinimum+1111) > 1e-3) h->SetMinimum(fMinimum*norm/sum);
3195 h->Draw(opt);
3196
3197 return h;
3198}
3199
3200////////////////////////////////////////////////////////////////////////////////
3201/// Display a panel with all histogram drawing options.
3202///
3203/// See class TDrawPanelHist for example
3204
3205void TH1::DrawPanel()
3206{
3207 if (!fPainter) {Draw(); if (gPad) gPad->Update();}
3208 if (fPainter) fPainter->DrawPanel();
3209}
3210
3211////////////////////////////////////////////////////////////////////////////////
3212/// Evaluate function f1 at the center of bins of this histogram.
3213///
3214/// - If option "R" is specified, the function is evaluated only
3215/// for the bins included in the function range.
3216/// - If option "A" is specified, the value of the function is added to the
3217/// existing bin contents
3218/// - If option "S" is specified, the value of the function is used to
3219/// generate a value, distributed according to the Poisson
3220/// distribution, with f1 as the mean.
3221
3223{
3224 Double_t x[3];
3225 Int_t range, stat, add;
3226 if (!f1) return;
3227
3228 TString opt = option;
3229 opt.ToLower();
3230 if (opt.Contains("a")) add = 1;
3231 else add = 0;
3232 if (opt.Contains("s")) stat = 1;
3233 else stat = 0;
3234 if (opt.Contains("r")) range = 1;
3235 else range = 0;
3236
3237 // delete buffer if it is there since it will become invalid
3238 if (fBuffer) BufferEmpty(1);
3239
3243 if (!add) Reset();
3244
3245 for (Int_t binz = 1; binz <= nbinsz; ++binz) {
3246 x[2] = fZaxis.GetBinCenter(binz);
3247 for (Int_t biny = 1; biny <= nbinsy; ++biny) {
3248 x[1] = fYaxis.GetBinCenter(biny);
3249 for (Int_t binx = 1; binx <= nbinsx; ++binx) {
3250 Int_t bin = GetBin(binx,biny,binz);
3251 x[0] = fXaxis.GetBinCenter(binx);
3252 if (range && !f1->IsInside(x)) continue;
3253 Double_t fu = f1->Eval(x[0], x[1], x[2]);
3254 if (stat) fu = gRandom->PoissonD(fu);
3255 AddBinContent(bin, fu);
3256 if (fSumw2.fN) fSumw2.fArray[bin] += TMath::Abs(fu);
3257 }
3258 }
3259 }
3260}
3261
3262////////////////////////////////////////////////////////////////////////////////
3263/// Execute action corresponding to one event.
3264///
3265/// This member function is called when a histogram is clicked with the locator
3266///
3267/// If Left button clicked on the bin top value, then the content of this bin
3268/// is modified according to the new position of the mouse when it is released.
3269
3270void TH1::ExecuteEvent(Int_t event, Int_t px, Int_t py)
3271{
3272 if (fPainter) fPainter->ExecuteEvent(event, px, py);
3273}
3274
3275////////////////////////////////////////////////////////////////////////////////
3276/// This function allows to do discrete Fourier transforms of TH1 and TH2.
3277/// Available transform types and flags are described below.
3278///
3279/// To extract more information about the transform, use the function
3280/// TVirtualFFT::GetCurrentTransform() to get a pointer to the current
3281/// transform object.
3282///
3283/// \param[out] h_output histogram for the output. If a null pointer is passed, a new histogram is created
3284/// and returned, otherwise, the provided histogram is used and should be big enough
3285/// \param[in] option option parameters consists of 3 parts:
3286/// - option on what to return
3287/// - "RE" - returns a histogram of the real part of the output
3288/// - "IM" - returns a histogram of the imaginary part of the output
3289/// - "MAG"- returns a histogram of the magnitude of the output
3290/// - "PH" - returns a histogram of the phase of the output
3291/// - option of transform type
3292/// - "R2C" - real to complex transforms - default
3293/// - "R2HC" - real to halfcomplex (special format of storing output data,
3294/// results the same as for R2C)
3295/// - "DHT" - discrete Hartley transform
3296/// real to real transforms (sine and cosine):
3297/// - "R2R_0", "R2R_1", "R2R_2", "R2R_3" - discrete cosine transforms of types I-IV
3298/// - "R2R_4", "R2R_5", "R2R_6", "R2R_7" - discrete sine transforms of types I-IV
3299/// To specify the type of each dimension of a 2-dimensional real to real
3300/// transform, use options of form "R2R_XX", for example, "R2R_02" for a transform,
3301/// which is of type "R2R_0" in 1st dimension and "R2R_2" in the 2nd.
3302/// - option of transform flag
3303/// - "ES" (from "estimate") - no time in preparing the transform, but probably sub-optimal
3304/// performance
3305/// - "M" (from "measure") - some time spend in finding the optimal way to do the transform
3306/// - "P" (from "patient") - more time spend in finding the optimal way to do the transform
3307/// - "EX" (from "exhaustive") - the most optimal way is found
3308/// This option should be chosen depending on how many transforms of the same size and
3309/// type are going to be done. Planning is only done once, for the first transform of this
3310/// size and type. Default is "ES".
3311///
3312/// Examples of valid options: "Mag R2C M" "Re R2R_11" "Im R2C ES" "PH R2HC EX"
3313
3315{
3316
3317 Int_t ndim[3];
3318 ndim[0] = this->GetNbinsX();
3319 ndim[1] = this->GetNbinsY();
3320 ndim[2] = this->GetNbinsZ();
3321
3323 TString opt = option;
3324 opt.ToUpper();
3325 if (!opt.Contains("2R")){
3326 if (!opt.Contains("2C") && !opt.Contains("2HC") && !opt.Contains("DHT")) {
3327 //no type specified, "R2C" by default
3328 opt.Append("R2C");
3329 }
3330 fft = TVirtualFFT::FFT(this->GetDimension(), ndim, opt.Data());
3331 }
3332 else {
3333 //find the kind of transform
3334 Int_t ind = opt.Index("R2R", 3);
3335 Int_t *kind = new Int_t[2];
3336 char t;
3337 t = opt[ind+4];
3338 kind[0] = atoi(&t);
3339 if (h_output->GetDimension()>1) {
3340 t = opt[ind+5];
3341 kind[1] = atoi(&t);
3342 }
3343 fft = TVirtualFFT::SineCosine(this->GetDimension(), ndim, kind, option);
3344 delete [] kind;
3345 }
3346
3347 if (!fft) return nullptr;
3348 Int_t in=0;
3349 for (Int_t binx = 1; binx<=ndim[0]; binx++) {
3350 for (Int_t biny=1; biny<=ndim[1]; biny++) {
3351 for (Int_t binz=1; binz<=ndim[2]; binz++) {
3352 fft->SetPoint(in, this->GetBinContent(binx, biny, binz));
3353 in++;
3354 }
3355 }
3356 }
3357 fft->Transform();
3359 return h_output;
3360}
3361
3362////////////////////////////////////////////////////////////////////////////////
3363/// Increment bin with abscissa X by 1.
3364///
3365/// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3366/// if x is equal to or greater than the upper edge of last bin, the Overflow bin is incremented
3367///
3368/// If the storage of the sum of squares of weights has been triggered,
3369/// via the function Sumw2, then the sum of the squares of weights is incremented
3370/// by 1 in the bin corresponding to x.
3371///
3372/// The function returns the corresponding bin number which has its content incremented by 1
3373
3375{
3376 if (fBuffer) return BufferFill(x,1);
3377
3378 Int_t bin;
3379 fEntries++;
3380 bin =fXaxis.FindBin(x);
3381 if (bin <0) return -1;
3382 AddBinContent(bin);
3383 if (fSumw2.fN) ++fSumw2.fArray[bin];
3384 if (bin == 0 || bin > fXaxis.GetNbins()) {
3385 if (!GetStatOverflowsBehaviour()) return -1;
3386 }
3387 ++fTsumw;
3388 ++fTsumw2;
3389 fTsumwx += x;
3390 fTsumwx2 += x*x;
3391 return bin;
3392}
3393
3394////////////////////////////////////////////////////////////////////////////////
3395/// Increment bin with abscissa X with a weight w.
3396///
3397/// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3398/// if x is equal to or greater than the upper edge of last bin, the Overflow bin is incremented
3399///
3400/// If the weight is not equal to 1, the storage of the sum of squares of
3401/// weights is automatically triggered and the sum of the squares of weights is incremented
3402/// by \f$ w^2 \f$ in the bin corresponding to x.
3403///
3404/// The function returns the corresponding bin number which has its content incremented by w
3405
3407{
3408
3409 if (fBuffer) return BufferFill(x,w);
3410
3411 Int_t bin;
3412 fEntries++;
3413 bin =fXaxis.FindBin(x);
3414 if (bin <0) return -1;
3415 if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW) ) Sumw2(); // must be called before AddBinContent
3416 if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3417 AddBinContent(bin, w);
3418 if (bin == 0 || bin > fXaxis.GetNbins()) {
3419 if (!GetStatOverflowsBehaviour()) return -1;
3420 }
3421 Double_t z= w;
3422 fTsumw += z;
3423 fTsumw2 += z*z;
3424 fTsumwx += z*x;
3425 fTsumwx2 += z*x*x;
3426 return bin;
3427}
3428
3429////////////////////////////////////////////////////////////////////////////////
3430/// Increment bin with namex with a weight w
3431///
3432/// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3433/// if x is equal to or greater than the upper edge of last bin, the Overflow bin is incremented
3434///
3435/// If the weight is not equal to 1, the storage of the sum of squares of
3436/// weights is automatically triggered and the sum of the squares of weights is incremented
3437/// by \f$ w^2 \f$ in the bin corresponding to x.
3438///
3439/// The function returns the corresponding bin number which has its content
3440/// incremented by w.
3441
3442Int_t TH1::Fill(const char *namex, Double_t w)
3443{
3444 Int_t bin;
3445 fEntries++;
3446 bin =fXaxis.FindBin(namex);
3447 if (bin <0) return -1;
3448 if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3449 if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3450 AddBinContent(bin, w);
3451 if (bin == 0 || bin > fXaxis.GetNbins()) return -1;
3452 Double_t z= w;
3453 fTsumw += z;
3454 fTsumw2 += z*z;
3455 // this make sense if the histogram is not expanding (the x axis cannot be extended)
3456 if (!fXaxis.CanExtend() || !fXaxis.IsAlphanumeric()) {
3458 fTsumwx += z*x;
3459 fTsumwx2 += z*x*x;
3460 }
3461 return bin;
3462}
3463
3464////////////////////////////////////////////////////////////////////////////////
3465/// Fill this histogram with an array x and weights w.
3466///
3467/// \param[in] ntimes number of entries in arrays x and w (array size must be ntimes*stride)
3468/// \param[in] x array of values to be histogrammed
3469/// \param[in] w array of weighs
3470/// \param[in] stride step size through arrays x and w
3471///
3472/// If the weight is not equal to 1, the storage of the sum of squares of
3473/// weights is automatically triggered and the sum of the squares of weights is incremented
3474/// by \f$ w^2 \f$ in the bin corresponding to x.
3475/// if w is NULL each entry is assumed a weight=1
3476
3477void TH1::FillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3478{
3479 //If a buffer is activated, fill buffer
3480 if (fBuffer) {
3481 ntimes *= stride;
3482 Int_t i = 0;
3483 for (i=0;i<ntimes;i+=stride) {
3484 if (!fBuffer) break; // buffer can be deleted in BufferFill when is empty
3485 if (w) BufferFill(x[i],w[i]);
3486 else BufferFill(x[i], 1.);
3487 }
3488 // fill the remaining entries if the buffer has been deleted
3489 if (i < ntimes && !fBuffer) {
3490 auto weights = w ? &w[i] : nullptr;
3491 DoFillN((ntimes-i)/stride,&x[i],weights,stride);
3492 }
3493 return;
3494 }
3495 // call internal method
3496 DoFillN(ntimes, x, w, stride);
3497}
3498
3499////////////////////////////////////////////////////////////////////////////////
3500/// Internal method to fill histogram content from a vector
3501/// called directly by TH1::BufferEmpty
3502
3503void TH1::DoFillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3504{
3505 Int_t bin,i;
3506
3507 fEntries += ntimes;
3508 Double_t ww = 1;
3509 Int_t nbins = fXaxis.GetNbins();
3510 ntimes *= stride;
3511 for (i=0;i<ntimes;i+=stride) {
3512 bin =fXaxis.FindBin(x[i]);
3513 if (bin <0) continue;
3514 if (w) ww = w[i];
3515 if (!fSumw2.fN && ww != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3516 if (fSumw2.fN) fSumw2.fArray[bin] += ww*ww;
3517 AddBinContent(bin, ww);
3518 if (bin == 0 || bin > nbins) {
3519 if (!GetStatOverflowsBehaviour()) continue;
3520 }
3521 Double_t z= ww;
3522 fTsumw += z;
3523 fTsumw2 += z*z;
3524 fTsumwx += z*x[i];
3525 fTsumwx2 += z*x[i]*x[i];
3526 }
3527}
3528
3529////////////////////////////////////////////////////////////////////////////////
3530/// Fill histogram following distribution in function fname.
3531///
3532/// @param fname : Function name used for filling the histogram
3533/// @param ntimes : number of times the histogram is filled
3534/// @param rng : (optional) Random number generator used to sample
3535///
3536///
3537/// The distribution contained in the function fname (TF1) is integrated
3538/// over the channel contents for the bin range of this histogram.
3539/// It is normalized to 1.
3540///
3541/// Getting one random number implies:
3542/// - Generating a random number between 0 and 1 (say r1)
3543/// - Look in which bin in the normalized integral r1 corresponds to
3544/// - Fill histogram channel
3545/// ntimes random numbers are generated
3546///
3547/// One can also call TF1::GetRandom to get a random variate from a function.
3548
3549void TH1::FillRandom(const char *fname, Int_t ntimes, TRandom * rng)
3550{
3551 // - Search for fname in the list of ROOT defined functions
3552 TF1 *f1 = (TF1*)gROOT->GetFunction(fname);
3553 if (!f1) { Error("FillRandom", "Unknown function: %s",fname); return; }
3554
3557
3559{
3560 Int_t bin, binx, ibin, loop;
3561 Double_t r1, x;
3562
3563 // - Allocate temporary space to store the integral and compute integral
3564
3565 TAxis * xAxis = &fXaxis;
3566
3567 // in case axis of histogram is not defined use the function axis
3568 if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
3570 f1->GetRange(xmin,xmax);
3571 Info("FillRandom","Using function axis and range [%g,%g]",xmin, xmax);
3572 xAxis = f1->GetHistogram()->GetXaxis();
3573 }
3574
3575 Int_t first = xAxis->GetFirst();
3576 Int_t last = xAxis->GetLast();
3577 Int_t nbinsx = last-first+1;
3578
3579 Double_t *integral = new Double_t[nbinsx+1];
3580 integral[0] = 0;
3581 for (binx=1;binx<=nbinsx;binx++) {
3582 Double_t fint = f1->Integral(xAxis->GetBinLowEdge(binx+first-1),xAxis->GetBinUpEdge(binx+first-1), 0.);
3583 integral[binx] = integral[binx-1] + fint;
3584 }
3585
3586 // - Normalize integral to 1
3587 if (integral[nbinsx] == 0 ) {
3588 delete [] integral;
3589 Error("FillRandom", "Integral = zero"); return;
3590 }
3591 for (bin=1;bin<=nbinsx;bin++) integral[bin] /= integral[nbinsx];
3592
3593 // --------------Start main loop ntimes
3594 for (loop=0;loop<ntimes;loop++) {
3595 r1 = (rng) ? rng->Rndm() : gRandom->Rndm();
3596 ibin = TMath::BinarySearch(nbinsx,&integral[0],r1);
3597 //binx = 1 + ibin;
3598 //x = xAxis->GetBinCenter(binx); //this is not OK when SetBuffer is used
3599 x = xAxis->GetBinLowEdge(ibin+first)
3600 +xAxis->GetBinWidth(ibin+first)*(r1-integral[ibin])/(integral[ibin+1] - integral[ibin]);
3601 Fill(x);
3602 }
3603 delete [] integral;
3604}
3605
3606////////////////////////////////////////////////////////////////////////////////
3607/// Fill histogram following distribution in histogram h.
3608///
3609/// @param h : Histogram pointer used for sampling random number
3610/// @param ntimes : number of times the histogram is filled
3611/// @param rng : (optional) Random number generator used for sampling
3612///
3613/// The distribution contained in the histogram h (TH1) is integrated
3614/// over the channel contents for the bin range of this histogram.
3615/// It is normalized to 1.
3616///
3617/// Getting one random number implies:
3618/// - Generating a random number between 0 and 1 (say r1)
3619/// - Look in which bin in the normalized integral r1 corresponds to
3620/// - Fill histogram channel ntimes random numbers are generated
3621///
3622/// SPECIAL CASE when the target histogram has the same binning as the source.
3623/// in this case we simply use a poisson distribution where
3624/// the mean value per bin = bincontent/integral.
3625
3627{
3628 if (!h) { Error("FillRandom", "Null histogram"); return; }
3629 if (fDimension != h->GetDimension()) {
3630 Error("FillRandom", "Histograms with different dimensions"); return;
3631 }
3632 if (std::isnan(h->ComputeIntegral(true))) {
3633 Error("FillRandom", "Histograms contains negative bins, does not represent probabilities");
3634 return;
3635 }
3636
3637 //in case the target histogram has the same binning and ntimes much greater
3638 //than the number of bins we can use a fast method
3639 Int_t first = fXaxis.GetFirst();
3640 Int_t last = fXaxis.GetLast();
3641 Int_t nbins = last-first+1;
3642 if (ntimes > 10*nbins) {
3643 auto inconsistency = CheckConsistency(this,h);
3644 if (inconsistency != kFullyConsistent) return; // do nothing
3645 Double_t sumw = h->Integral(first,last);
3646 if (sumw == 0) return;
3647 Double_t sumgen = 0;
3648 for (Int_t bin=first;bin<=last;bin++) {
3649 Double_t mean = h->RetrieveBinContent(bin)*ntimes/sumw;
3650 Double_t cont = (rng) ? rng->Poisson(mean) : gRandom->Poisson(mean);
3651 sumgen += cont;
3652 AddBinContent(bin,cont);
3653 if (fSumw2.fN) fSumw2.fArray[bin] += cont;
3654 }
3655
3656 // fix for the fluctuations in the total number n
3657 // since we use Poisson instead of multinomial
3658 // add a correction to have ntimes as generated entries
3659 Int_t i;
3660 if (sumgen < ntimes) {
3661 // add missing entries
3662 for (i = Int_t(sumgen+0.5); i < ntimes; ++i)
3663 {
3664 Double_t x = h->GetRandom();
3665 Fill(x);
3666 }
3667 }
3668 else if (sumgen > ntimes) {
3669 // remove extra entries
3670 i = Int_t(sumgen+0.5);
3671 while( i > ntimes) {
3672 Double_t x = h->GetRandom(rng);
3675 // skip in case bin is empty
3676 if (y > 0) {
3677 SetBinContent(ibin, y-1.);
3678 i--;
3679 }
3680 }
3681 }
3682
3683 ResetStats();
3684 return;
3685 }
3686 // case of different axis and not too large ntimes
3687
3688 if (h->ComputeIntegral() ==0) return;
3689 Int_t loop;
3690 Double_t x;
3691 for (loop=0;loop<ntimes;loop++) {
3692 x = h->GetRandom();
3693 Fill(x);
3694 }
3695}
3696
3697////////////////////////////////////////////////////////////////////////////////
3698/// Return Global bin number corresponding to x,y,z
3699///
3700/// 2-D and 3-D histograms are represented with a one dimensional
3701/// structure. This has the advantage that all existing functions, such as
3702/// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3703/// This function tries to extend the axis if the given point belongs to an
3704/// under-/overflow bin AND if CanExtendAllAxes() is true.
3705///
3706/// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3707
3709{
3710 if (GetDimension() < 2) {
3711 return fXaxis.FindBin(x);
3712 }
3713 if (GetDimension() < 3) {
3714 Int_t nx = fXaxis.GetNbins()+2;
3717 return binx + nx*biny;
3718 }
3719 if (GetDimension() < 4) {
3720 Int_t nx = fXaxis.GetNbins()+2;
3721 Int_t ny = fYaxis.GetNbins()+2;
3724 Int_t binz = fZaxis.FindBin(z);
3725 return binx + nx*(biny +ny*binz);
3726 }
3727 return -1;
3728}
3729
3730////////////////////////////////////////////////////////////////////////////////
3731/// Return Global bin number corresponding to x,y,z.
3732///
3733/// 2-D and 3-D histograms are represented with a one dimensional
3734/// structure. This has the advantage that all existing functions, such as
3735/// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3736/// This function DOES NOT try to extend the axis if the given point belongs
3737/// to an under-/overflow bin.
3738///
3739/// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3740
3742{
3743 if (GetDimension() < 2) {
3744 return fXaxis.FindFixBin(x);
3745 }
3746 if (GetDimension() < 3) {
3747 Int_t nx = fXaxis.GetNbins()+2;
3750 return binx + nx*biny;
3751 }
3752 if (GetDimension() < 4) {
3753 Int_t nx = fXaxis.GetNbins()+2;
3754 Int_t ny = fYaxis.GetNbins()+2;
3758 return binx + nx*(biny +ny*binz);
3759 }
3760 return -1;
3761}
3762
3763////////////////////////////////////////////////////////////////////////////////
3764/// Find first bin with content > threshold for axis (1=x, 2=y, 3=z)
3765/// if no bins with content > threshold is found the function returns -1.
3766/// The search will occur between the specified first and last bin. Specifying
3767/// the value of the last bin to search to less than zero will search until the
3768/// last defined bin.
3769
3771{
3772 if (fBuffer) ((TH1*)this)->BufferEmpty();
3773
3774 if (axis < 1 || (axis > 1 && GetDimension() == 1 ) ||
3775 ( axis > 2 && GetDimension() == 2 ) || ( axis > 3 && GetDimension() > 3 ) ) {
3776 Warning("FindFirstBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3777 axis = 1;
3778 }
3779 if (firstBin < 1) {
3780 firstBin = 1;
3781 }
3783 Int_t nbinsy = (GetDimension() > 1 ) ? fYaxis.GetNbins() : 1;
3784 Int_t nbinsz = (GetDimension() > 2 ) ? fZaxis.GetNbins() : 1;
3785
3786 if (axis == 1) {
3789 }
3790 for (Int_t binx = firstBin; binx <= lastBin; binx++) {
3791 for (Int_t biny = 1; biny <= nbinsy; biny++) {
3792 for (Int_t binz = 1; binz <= nbinsz; binz++) {
3794 }
3795 }
3796 }
3797 }
3798 else if (axis == 2) {
3801 }
3802 for (Int_t biny = firstBin; biny <= lastBin; biny++) {
3803 for (Int_t binx = 1; binx <= nbinsx; binx++) {
3804 for (Int_t binz = 1; binz <= nbinsz; binz++) {
3806 }
3807 }
3808 }
3809 }
3810 else if (axis == 3) {
3813 }
3814 for (Int_t binz = firstBin; binz <= lastBin; binz++) {
3815 for (Int_t binx = 1; binx <= nbinsx; binx++) {
3816 for (Int_t biny = 1; biny <= nbinsy; biny++) {
3818 }
3819 }
3820 }
3821 }
3822
3823 return -1;
3824}
3825
3826////////////////////////////////////////////////////////////////////////////////
3827/// Find last bin with content > threshold for axis (1=x, 2=y, 3=z)
3828/// if no bins with content > threshold is found the function returns -1.
3829/// The search will occur between the specified first and last bin. Specifying
3830/// the value of the last bin to search to less than zero will search until the
3831/// last defined bin.
3832
3834{
3835 if (fBuffer) ((TH1*)this)->BufferEmpty();
3836
3837
3838 if (axis < 1 || ( axis > 1 && GetDimension() == 1 ) ||
3839 ( axis > 2 && GetDimension() == 2 ) || ( axis > 3 && GetDimension() > 3) ) {
3840 Warning("FindFirstBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3841 axis = 1;
3842 }
3843 if (firstBin < 1) {
3844 firstBin = 1;
3845 }
3847 Int_t nbinsy = (GetDimension() > 1 ) ? fYaxis.GetNbins() : 1;
3848 Int_t nbinsz = (GetDimension() > 2 ) ? fZaxis.GetNbins() : 1;
3849
3850 if (axis == 1) {
3853 }
3854 for (Int_t binx = lastBin; binx >= firstBin; binx--) {
3855 for (Int_t biny = 1; biny <= nbinsy; biny++) {
3856 for (Int_t binz = 1; binz <= nbinsz; binz++) {
3858 }
3859 }
3860 }
3861 }
3862 else if (axis == 2) {
3865 }
3866 for (Int_t biny = lastBin; biny >= firstBin; biny--) {
3867 for (Int_t binx = 1; binx <= nbinsx; binx++) {
3868 for (Int_t binz = 1; binz <= nbinsz; binz++) {
3870 }
3871 }
3872 }
3873 }
3874 else if (axis == 3) {
3877 }
3878 for (Int_t binz = lastBin; binz >= firstBin; binz--) {
3879 for (Int_t binx = 1; binx <= nbinsx; binx++) {
3880 for (Int_t biny = 1; biny <= nbinsy; biny++) {
3882 }
3883 }
3884 }
3885 }
3886
3887 return -1;
3888}
3889
3890////////////////////////////////////////////////////////////////////////////////
3891/// Search object named name in the list of functions.
3892
3893TObject *TH1::FindObject(const char *name) const
3894{
3895 if (fFunctions) return fFunctions->FindObject(name);
3896 return nullptr;
3897}
3898
3899////////////////////////////////////////////////////////////////////////////////
3900/// Search object obj in the list of functions.
3901
3902TObject *TH1::FindObject(const TObject *obj) const
3903{
3904 if (fFunctions) return fFunctions->FindObject(obj);
3905 return nullptr;
3906}
3907
3908////////////////////////////////////////////////////////////////////////////////
3909/// Fit histogram with function fname.
3910///
3911///
3912/// fname is the name of a function available in the global ROOT list of functions
3913/// `gROOT->GetListOfFunctions`. Note that this is not thread safe.
3914/// The list include any TF1 object created by the user plus some pre-defined functions
3915/// which are automatically created by ROOT the first time a pre-defined function is requested from `gROOT`
3916/// (i.e. when calling `gROOT->GetFunction(const char *name)`).
3917/// These pre-defined functions are:
3918/// - `gaus, gausn` where gausn is the normalized Gaussian
3919/// - `landau, landaun`
3920/// - `expo`
3921/// - `pol1,...9, chebyshev1,...9`.
3922///
3923/// For printing the list of all available functions do:
3924///
3925/// TF1::InitStandardFunctions(); // not needed if `gROOT->GetFunction` is called before
3926/// TF2::InitStandardFunctions(); TF3::InitStandardFunctions(); // For 2D or 3D
3927/// gROOT->GetListOfFunctions()->ls()
3928///
3929/// `fname` can also be a formula that is accepted by the linear fitter containing the special operator `++`,
3930/// representing linear components separated by `++` sign, for example `x++sin(x)` for fitting `[0]*x+[1]*sin(x)`
3931///
3932/// This function finds a pointer to the TF1 object with name `fname` and calls TH1::Fit(TF1 *, Option_t *, Option_t *,
3933/// Double_t, Double_t). See there for the fitting options and the details about fitting histograms
3934
3936{
3937 char *linear;
3938 linear= (char*)strstr(fname, "++");
3939 Int_t ndim=GetDimension();
3940 if (linear){
3941 if (ndim<2){
3943 return Fit(&f1,option,goption,xxmin,xxmax);
3944 }
3945 else if (ndim<3){
3946 TF2 f2(fname, fname);
3947 return Fit(&f2,option,goption,xxmin,xxmax);
3948 }
3949 else{
3950 TF3 f3(fname, fname);
3951 return Fit(&f3,option,goption,xxmin,xxmax);
3952 }
3953 }
3954 else{
3955 TF1 * f1 = (TF1*)gROOT->GetFunction(fname);
3956 if (!f1) { Printf("Unknown function: %s",fname); return -1; }
3957 return Fit(f1,option,goption,xxmin,xxmax);
3958 }
3959}
3960
3961////////////////////////////////////////////////////////////////////////////////
3962/// Fit histogram with the function pointer f1.
3963///
3964/// \param[in] f1 pointer to the function object
3965/// \param[in] option string defining the fit options (see table below).
3966/// \param[in] goption specify a list of graphics options. See TH1::Draw for a complete list of these options.
3967/// \param[in] xxmin lower fitting range
3968/// \param[in] xxmax upper fitting range
3969/// \return A smart pointer to the TFitResult class
3970///
3971/// \anchor HFitOpt
3972/// ### Histogram Fitting Options
3973///
3974/// Here is the full list of fit options that can be given in the parameter `option`.
3975/// Several options can be used together by concatanating the strings without the need of any delimiters.
3976///
3977/// option | description
3978/// -------|------------
3979/// "L" | Uses a log likelihood method (default is chi-square method). To be used when the histogram represents counts.
3980/// "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.
3981/// "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.
3982/// "MULTI" | Uses Loglikelihood method based on multi-nomial distribution. In this case the function must be normalized and one fits only the function shape.
3983/// "W" | Fit using the chi-square method and ignoring the bin uncertainties and skip empty bins.
3984/// "WW" | Fit using the chi-square method and ignoring the bin uncertainties and include the empty bins.
3985/// "I" | Uses the integral of function in the bin instead of the default bin center value.
3986/// "F" | Uses the default minimizer (e.g. Minuit) when fitting a linear function (e.g. polN) instead of the linear fitter.
3987/// "U" | Uses a user specified objective function (e.g. user providedlikelihood function) defined using `TVirtualFitter::SetFCN`
3988/// "E" | Performs a better parameter errors estimation using the Minos technique for all fit parameters.
3989/// "M" | Uses the IMPROVE algorithm (available only in TMinuit). This algorithm attempts improve the found local minimum by searching for a better one.
3990/// "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`.
3991/// "Q" | Quiet mode (minimum printing)
3992/// "V" | Verbose mode (default is between Q and V)
3993/// "+" | 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.
3994/// "N" | Does not store the graphics function, does not draw the histogram with the function after fitting.
3995/// "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.
3996/// "R" | Fit using a fitting range specified in the function range with `TF1::SetRange`.
3997/// "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.
3998/// "C" | In case of linear fitting, do no calculate the chisquare (saves CPU time).
3999/// "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.
4000/// "WIDTH" | Scales the histogran bin content by the bin width (useful for variable bins histograms)
4001/// "SERIAL" | Runs in serial mode. By default 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
4002/// "MULTITHREAD" | Forces usage of multi-thread execution whenever possible
4003///
4004/// The default fitting of an histogram (when no option is given) is perfomed as following:
4005/// - a chi-square fit (see below Chi-square Fits) computed using the bin histogram errors and excluding bins with zero errors (empty bins);
4006/// - the full range of the histogram is used, unless TAxis::SetRange or TAxis::SetRangeUser was called before;
4007/// - the default Minimizer with its default configuration is used (see below Minimizer Configuration) except for linear function;
4008/// - for linear functions (`polN`, `chenbyshev` or formula expressions combined using operator `++`) a linear minimization is used.
4009/// - only the status of the fit is returned;
4010/// - the fit is performed in Multithread whenever is enabled in ROOT;
4011/// - only the last fitted function is saved in the histogram;
4012/// - the histogram is drawn after fitting overalyed with the resulting fitting function
4013///
4014/// \anchor HFitMinimizer
4015/// ### Minimizer Configuration
4016///
4017/// The Fit is perfomed using the default Minimizer, defined in the `ROOT::Math::MinimizerOptions` class.
4018/// It is possible to change the default minimizer and its configuration parameters by calling these static functions before fitting (before calling `TH1::Fit`):
4019/// - `ROOT::Math::MinimizerOptions::SetDefaultMinimizer(minimizerName, minimizerAgorithm)` for changing the minmizer and/or the corresponding algorithm.
4020/// For example `ROOT::Math::MinimizerOptions::SetDefaultMinimizer("GSLMultiMin","BFGS");` will set the usage of the BFGS algorithm of the GSL multi-dimensional minimization
4021/// The current defaults are ("Minuit","Migrad").
4022/// See the documentation of the `ROOT::Math::MinimizerOptions` for the available minimizers in ROOT and their corresponding algorithms.
4023/// - `ROOT::Math::MinimizerOptions::SetDefaultTolerance` for setting a different tolerance value for the minimization.
4024/// - `ROOT::Math::MinimizerOptions::SetDefaultMaxFunctionCalls` for setting the maximum number of function calls.
4025/// - `ROOT::Math::MinimizerOptions::SetDefaultPrintLevel` for changing the minimizer print level from level=0 (minimal printing) to level=3 maximum printing
4026///
4027/// Other options are possible depending on the Minimizer used, see the corresponding documentation.
4028/// The default minimizer can be also set in the resource file in etc/system.rootrc. For example
4029///
4030/// ~~~ {.cpp}
4031/// Root.Fitter: Minuit2
4032/// ~~~
4033///
4034/// \anchor HFitChi2
4035/// ### Chi-square Fits
4036///
4037/// By default a chi-square (least-square) fit is performed on the histogram. The so-called modified least-square method
4038/// is used where the residual for each bin is computed using as error the observed value (the bin error) returned by `TH1::GetBinError`
4039///
4040/// \f[
4041/// Chi2 = \sum_{i}{ \left(\frac{y(i) - f(x(i) | p )}{e(i)} \right)^2 }
4042/// \f]
4043///
4044/// 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
4045/// an un-weighted histogram). Bins with zero errors are excluded from the fit. See also later the note on the treatment
4046/// of empty bins. When using option "I" the residual is computed not using the function value at the bin center, `f(x(i)|p)`,
4047/// but the integral of the function in the bin, Integral{ f(x|p)dx }, divided by the bin volume.
4048/// When using option `P` (Pearson chi2), the expected error computed as `e(i) = sqrt(f(x(i)|p))` is used.
4049/// In this case empty bins are considered in the fit.
4050/// Both chi-square methods should not be used when the bin content represent counts, especially in case of low bin statistics,
4051/// because they could return a biased result.
4052///
4053/// \anchor HFitNLL
4054/// ### Likelihood Fits
4055///
4056/// When using option "L" a likelihood fit is used instead of the default chi-square fit.
4057/// The likelihood is built assuming a Poisson probability density function for each bin.
4058/// The negative log-likelihood to be minimized is
4059///
4060/// \f[
4061/// NLL = - \sum_{i}{ \log {\mathrm P} ( y(i) | f(x(i) | p ) ) }
4062/// \f]
4063/// 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)`.
4064/// The exact likelihood used is the Poisson likelihood described in this paper:
4065/// S. Baker and R. D. Cousins, “Clarification of the use of chi-square and likelihood functions in fits to histograms,”
4066/// Nucl. Instrum. Meth. 221 (1984) 437.
4067///
4068/// \f[
4069/// NLL = \sum_{i}{( f(x(i) | p ) + y(i)\log(y(i)/ f(x(i) | p )) - y(i)) }
4070/// \f]
4071/// By using this formulation, `2*NLL` can be interpreted as the chi-square resulting from the fit.
4072///
4073/// This method should be always used when the bin content represents counts (i.e. errors are sqrt(N) ).
4074/// The likelihood method has the advantage of treating correctly bins with low statistics. In case of high
4075/// statistics/bin the distribution of the bin content becomes a normal distribution and the likelihood and the chi2 fit
4076/// give the same result.
4077///
4078/// The likelihood method, although a bit slower, it is therefore the recommended method,
4079/// when the histogram represent counts (Poisson statistics), where the chi-square methods may
4080/// give incorrect results, especially in case of low statistics.
4081/// In case of a weighted histogram, it is possible to perform also a likelihood fit by using the
4082/// option "WL". Note a weighted histogram is a histogram which has been filled with weights and it
4083/// has the information on the sum of the weight square for each bin ( TH1::Sumw2() has been called).
4084/// The bin error for a weighted histogram is the square root of the sum of the weight square.
4085///
4086/// \anchor HFitRes
4087/// ### Fit Result
4088///
4089/// The function returns a TFitResultPtr which can hold a pointer to a TFitResult object.
4090/// By default the TFitResultPtr contains only the status of the fit which is return by an
4091/// automatic conversion of the TFitResultPtr to an integer. One can write in this case directly:
4092///
4093/// ~~~ {.cpp}
4094/// Int_t fitStatus = h->Fit(myFunc);
4095/// ~~~
4096///
4097/// If the option "S" is instead used, TFitResultPtr behaves as a smart
4098/// pointer to the TFitResult object. This is useful for retrieving the full result information from the fit, such as the covariance matrix,
4099/// as shown in this example code:
4100///
4101/// ~~~ {.cpp}
4102/// TFitResultPtr r = h->Fit(myFunc,"S");
4103/// TMatrixDSym cov = r->GetCovarianceMatrix(); // to access the covariance matrix
4104/// Double_t chi2 = r->Chi2(); // to retrieve the fit chi2
4105/// Double_t par0 = r->Parameter(0); // retrieve the value for the parameter 0
4106/// Double_t err0 = r->ParError(0); // retrieve the error for the parameter 0
4107/// r->Print("V"); // print full information of fit including covariance matrix
4108/// r->Write(); // store the result in a file
4109/// ~~~
4110///
4111/// The fit parameters, error and chi-square (but not covariance matrix) can be retrieved also
4112/// directly from the fitted function that is passed to this call.
4113/// Given a pointer to an associated fitted function `myfunc`, one can retrieve the function/fit
4114/// parameters with calls such as:
4115///
4116/// ~~~ {.cpp}
4117/// Double_t chi2 = myfunc->GetChisquare();
4118/// Double_t par0 = myfunc->GetParameter(0); //value of 1st parameter
4119/// Double_t err0 = myfunc->GetParError(0); //error on first parameter
4120/// ~~~
4121///
4122/// ##### Associated functions
4123///
4124/// One or more objects (typically a TF1*) can be added to the list
4125/// of functions (fFunctions) associated to each histogram.
4126/// When TH1::Fit is invoked, the fitted function is added to the histogram list of functions (fFunctions).
4127/// If the histogram is made persistent, the list of associated functions is also persistent.
4128/// Given a histogram h, one can retrieve an associated function with:
4129///
4130/// ~~~ {.cpp}
4131/// TF1 *myfunc = h->GetFunction("myfunc");
4132/// ~~~
4133/// or by quering directly the list obtained by calling `TH1::GetListOfFunctions`.
4134///
4135/// \anchor HFitStatus
4136/// ### Fit status
4137///
4138/// The status of the fit is obtained converting the TFitResultPtr to an integer
4139/// independently if the fit option "S" is used or not:
4140///
4141/// ~~~ {.cpp}
4142/// TFitResultPtr r = h->Fit(myFunc,opt);
4143/// Int_t fitStatus = r;
4144/// ~~~
4145///
4146/// - `status = 0` : the fit has been performed successfully (i.e no error occurred).
4147/// - `status < 0` : there is an error not connected with the minimization procedure, for example when a wrong function is used.
4148/// - `status > 0` : return status from Minimizer, depends on used Minimizer. For example for TMinuit and Minuit2 we have:
4149/// - `status = migradStatus + 10*minosStatus + 100*hesseStatus + 1000*improveStatus`.
4150/// 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
4151/// only in Minos but not in Migrad a fitStatus of 40 will be returned.
4152/// Minuit2 returns 0 in case of success and different values in migrad,minos or
4153/// hesse depending on the error. See in this case the documentation of
4154/// Minuit2Minimizer::Minimize for the migrad return status, Minuit2Minimizer::GetMinosError for the
4155/// minos return status and Minuit2Minimizer::Hesse for the hesse return status.
4156/// If other minimizers are used see their specific documentation for the status code returned.
4157/// For example in the case of Fumili, see TFumili::Minimize.
4158///
4159/// \anchor HFitRange
4160/// ### Fitting in a range
4161///
4162/// In order to fit in a sub-range of the histogram you have two options:
4163/// - pass to this function the lower (`xxmin`) and upper (`xxmax`) values for the fitting range;
4164/// - define a specific range in the fitted function and use the fitting option "R".
4165/// For example, if your histogram has a defined range between -4 and 4 and you want to fit a gaussian
4166/// only in the interval 1 to 3, you can do:
4167///
4168/// ~~~ {.cpp}
4169/// TF1 *f1 = new TF1("f1", "gaus", 1, 3);
4170/// histo->Fit("f1", "R");
4171/// ~~~
4172///
4173/// The fitting range is also limited by the histogram range defined using TAxis::SetRange
4174/// or TAxis::SetRangeUser. Therefore the fitting range is the smallest range between the
4175/// histogram one and the one defined by one of the two previous options described above.
4176///
4177/// \anchor HFitInitial
4178/// ### Setting initial conditions
4179///
4180/// Parameters must be initialized before invoking the Fit function.
4181/// The setting of the parameter initial values is automatic for the
4182/// predefined functions such as poln, expo, gaus, landau. One can however disable
4183/// this automatic computation by using the option "B".
4184/// Note that if a predefined function is defined with an argument,
4185/// eg, gaus(0), expo(1), you must specify the initial values for
4186/// the parameters.
4187/// You can specify boundary limits for some or all parameters via
4188///
4189/// ~~~ {.cpp}
4190/// f1->SetParLimits(p_number, parmin, parmax);
4191/// ~~~
4192///
4193/// if `parmin >= parmax`, the parameter is fixed
4194/// Note that you are not forced to fix the limits for all parameters.
4195/// For example, if you fit a function with 6 parameters, you can do:
4196///
4197/// ~~~ {.cpp}
4198/// func->SetParameters(0, 3.1, 1.e-6, -8, 0, 100);
4199/// func->SetParLimits(3, -10, -4);
4200/// func->FixParameter(4, 0);
4201/// func->SetParLimits(5, 1, 1);
4202/// ~~~
4203///
4204/// With this setup, parameters 0->2 can vary freely
4205/// Parameter 3 has boundaries [-10,-4] with initial value -8
4206/// Parameter 4 is fixed to 0
4207/// Parameter 5 is fixed to 100.
4208/// When the lower limit and upper limit are equal, the parameter is fixed.
4209/// However to fix a parameter to 0, one must call the FixParameter function.
4210///
4211/// \anchor HFitStatBox
4212/// ### Fit Statistics Box
4213///
4214/// The statistics box can display the result of the fit.
4215/// You can change the statistics box to display the fit parameters with
4216/// the TStyle::SetOptFit(mode) method. This mode has four digits.
4217/// mode = pcev (default = 0111)
4218///
4219/// v = 1; print name/values of parameters
4220/// e = 1; print errors (if e=1, v must be 1)
4221/// c = 1; print Chisquare/Number of degrees of freedom
4222/// p = 1; print Probability
4223///
4224/// For example: gStyle->SetOptFit(1011);
4225/// prints the fit probability, parameter names/values, and errors.
4226/// You can change the position of the statistics box with these lines
4227/// (where g is a pointer to the TGraph):
4228///
4229/// TPaveStats *st = (TPaveStats*)g->GetListOfFunctions()->FindObject("stats");
4230/// st->SetX1NDC(newx1); //new x start position
4231/// st->SetX2NDC(newx2); //new x end position
4232///
4233/// \anchor HFitExtra
4234/// ### Additional Notes on Fitting
4235///
4236/// #### Fitting a histogram of dimension N with a function of dimension N-1
4237///
4238/// It is possible to fit a TH2 with a TF1 or a TH3 with a TF2.
4239/// 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.
4240/// For correct error scaling, the obtained parameter error are corrected as in the case when the
4241/// option "W" is used.
4242///
4243/// #### User defined objective functions
4244///
4245/// By default when fitting a chi square function is used for fitting. When option "L" is used
4246/// a Poisson likelihood function is used. Using option "MULTI" a multinomial likelihood fit is used.
4247/// Thes functions are defined in the header Fit/Chi2Func.h or Fit/PoissonLikelihoodFCN and they
4248/// are implemented using the routines FitUtil::EvaluateChi2 or FitUtil::EvaluatePoissonLogL in
4249/// the file math/mathcore/src/FitUtil.cxx.
4250/// It is possible to specify a user defined fitting function, using option "U" and
4251/// calling the following functions:
4252///
4253/// ~~~ {.cpp}
4254/// TVirtualFitter::Fitter(myhist)->SetFCN(MyFittingFunction);
4255/// ~~~
4256///
4257/// where MyFittingFunction is of type:
4258///
4259/// ~~~ {.cpp}
4260/// extern void MyFittingFunction(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag);
4261/// ~~~
4262///
4263/// #### Note on treatment of empty bins
4264///
4265/// Empty bins, which have the content equal to zero AND error equal to zero,
4266/// are excluded by default from the chi-square fit, but they are considered in the likelihood fit.
4267/// since they affect the likelihood if the function value in these bins is not negligible.
4268/// Note that if the histogram is having bins with zero content and non zero-errors they are considered as
4269/// any other bins in the fit. Instead bins with zero error and non-zero content are by default excluded in the chi-squared fit.
4270/// In general, one should not fit a histogram with non-empty bins and zero errors.
4271///
4272/// 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
4273/// fit). When using option "WW" the empty bins will be also considered in the chi-square fit with an error of 1.
4274/// Note that in this fitting case (option "W" or "WW") the resulting fitted parameter errors
4275/// are corrected by the obtained chi2 value using this scaling expression:
4276/// `errorp *= sqrt(chisquare/(ndf-1))` as it is done when fitting a TGraph with
4277/// no point errors.
4278///
4279/// #### Excluding points
4280///
4281/// You can use TF1::RejectPoint inside your fitting function to exclude some points
4282/// within a certain range from the fit. See the tutorial `fit/fitExclude.C`.
4283///
4284///
4285/// #### Warning when using the option "0"
4286///
4287/// When selecting the option "0", the fitted function is added to
4288/// the list of functions of the histogram, but it is not drawn when the histogram is drawn.
4289/// You can undo this behaviour resetting its corresponding bit in the TF1 object as following:
4290///
4291/// ~~~ {.cpp}
4292/// h.Fit("myFunction", "0"); // fit, store function but do not draw
4293/// h.Draw(); // function is not drawn
4294/// h.GetFunction("myFunction")->ResetBit(TF1::kNotDraw);
4295/// h.Draw(); // function is visible again
4296/// ~~~
4298
4300{
4301 // implementation of Fit method is in file hist/src/HFitImpl.cxx
4304
4305 // create range and minimizer options with default values
4308
4309 // need to empty the buffer before
4310 // (t.b.d. do a ML unbinned fit with buffer data)
4311 if (fBuffer) BufferEmpty();
4312
4314}
4315
4316////////////////////////////////////////////////////////////////////////////////
4317/// Display a panel with all histogram fit options.
4318///
4319/// See class TFitPanel for example
4320
4321void TH1::FitPanel()
4322{
4323 if (!gPad)
4324 gROOT->MakeDefCanvas();
4325
4326 if (!gPad) {
4327 Error("FitPanel", "Unable to create a default canvas");
4328 return;
4329 }
4330
4331
4332 // use plugin manager to create instance of TFitEditor
4333 TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TFitEditor");
4334 if (handler && handler->LoadPlugin() != -1) {
4335 if (handler->ExecPlugin(2, gPad, this) == 0)
4336 Error("FitPanel", "Unable to create the FitPanel");
4337 }
4338 else
4339 Error("FitPanel", "Unable to find the FitPanel plug-in");
4340}
4341
4342////////////////////////////////////////////////////////////////////////////////
4343/// Return a histogram containing the asymmetry of this histogram with h2,
4344/// where the asymmetry is defined as:
4345///
4346/// ~~~ {.cpp}
4347/// Asymmetry = (h1 - h2)/(h1 + h2) where h1 = this
4348/// ~~~
4349///
4350/// works for 1D, 2D, etc. histograms
4351/// c2 is an optional argument that gives a relative weight between the two
4352/// histograms, and dc2 is the error on this weight. This is useful, for example,
4353/// when forming an asymmetry between two histograms from 2 different data sets that
4354/// need to be normalized to each other in some way. The function calculates
4355/// the errors assuming Poisson statistics on h1 and h2 (that is, dh = sqrt(h)).
4356///
4357/// example: assuming 'h1' and 'h2' are already filled
4358///
4359/// ~~~ {.cpp}
4360/// h3 = h1->GetAsymmetry(h2)
4361/// ~~~
4362///
4363/// then 'h3' is created and filled with the asymmetry between 'h1' and 'h2';
4364/// h1 and h2 are left intact.
4365///
4366/// Note that it is the user's responsibility to manage the created histogram.
4367/// The name of the returned histogram will be `Asymmetry_nameOfh1-nameOfh2`
4368///
4369/// code proposed by Jason Seely (seely@mit.edu) and adapted by R.Brun
4370///
4371/// clone the histograms so top and bottom will have the
4372/// correct dimensions:
4373/// Sumw2 just makes sure the errors will be computed properly
4374/// when we form sums and ratios below.
4375
4377{
4378 TH1 *h1 = this;
4379 TString name = TString::Format("Asymmetry_%s-%s",h1->GetName(),h2->GetName() );
4380 TH1 *asym = (TH1*)Clone(name);
4381
4382 // set also the title
4383 TString title = TString::Format("(%s - %s)/(%s+%s)",h1->GetName(),h2->GetName(),h1->GetName(),h2->GetName() );
4384 asym->SetTitle(title);
4385
4386 asym->Sumw2();
4387
4388 TDirectory::TContext ctx{nullptr};
4389 TH1 *top = (TH1*)asym->Clone();
4390 TH1 *bottom = (TH1*)asym->Clone();
4391
4392 // form the top and bottom of the asymmetry, and then divide:
4393 top->Add(h1,h2,1,-c2);
4394 bottom->Add(h1,h2,1,c2);
4395 asym->Divide(top,bottom);
4396
4397 Int_t xmax = asym->GetNbinsX();
4398 Int_t ymax = asym->GetNbinsY();
4399 Int_t zmax = asym->GetNbinsZ();
4400
4401 if (h1->fBuffer) h1->BufferEmpty(1);
4402 if (h2->fBuffer) h2->BufferEmpty(1);
4403 if (bottom->fBuffer) bottom->BufferEmpty(1);
4404
4405 // now loop over bins to calculate the correct errors
4406 // the reason this error calculation looks complex is because of c2
4407 for(Int_t i=1; i<= xmax; i++){
4408 for(Int_t j=1; j<= ymax; j++){
4409 for(Int_t k=1; k<= zmax; k++){
4410 Int_t bin = GetBin(i, j, k);
4411 // here some bin contents are written into variables to make the error
4412 // calculation a little more legible:
4414 Double_t b = h2->RetrieveBinContent(bin);
4415 Double_t bot = bottom->RetrieveBinContent(bin);
4416
4417 // make sure there are some events, if not, then the errors are set = 0
4418 // automatically.
4419 //if(bot < 1){} was changed to the next line from recommendation of Jason Seely (28 Nov 2005)
4420 if(bot < 1e-6){}
4421 else{
4422 // computation of errors by Christos Leonidopoulos
4424 Double_t dbsq = h2->GetBinErrorSqUnchecked(bin);
4425 Double_t error = 2*TMath::Sqrt(a*a*c2*c2*dbsq + c2*c2*b*b*dasq+a*a*b*b*dc2*dc2)/(bot*bot);
4426 asym->SetBinError(i,j,k,error);
4427 }
4428 }
4429 }
4430 }
4431 delete top;
4432 delete bottom;
4433
4434 return asym;
4435}
4436
4437////////////////////////////////////////////////////////////////////////////////
4438/// Static function
4439/// return the default buffer size for automatic histograms
4440/// the parameter fgBufferSize may be changed via SetDefaultBufferSize
4441
4443{
4444 return fgBufferSize;
4445}
4446
4447////////////////////////////////////////////////////////////////////////////////
4448/// Return kTRUE if TH1::Sumw2 must be called when creating new histograms.
4449/// see TH1::SetDefaultSumw2.
4450
4452{
4453 return fgDefaultSumw2;
4454}
4455
4456////////////////////////////////////////////////////////////////////////////////
4457/// Return the current number of entries.
4458
4460{
4461 if (fBuffer) {
4462 Int_t nentries = (Int_t) fBuffer[0];
4463 if (nentries > 0) return nentries;
4464 }
4465
4466 return fEntries;
4467}
4468
4469////////////////////////////////////////////////////////////////////////////////
4470/// Number of effective entries of the histogram.
4471///
4472/// \f[
4473/// neff = \frac{(\sum Weights )^2}{(\sum Weight^2 )}
4474/// \f]
4475///
4476/// In case of an unweighted histogram this number is equivalent to the
4477/// number of entries of the histogram.
4478/// For a weighted histogram, this number corresponds to the hypothetical number of unweighted entries
4479/// a histogram would need to have the same statistical power as this weighted histogram.
4480/// Note: The underflow/overflow are included if one has set the TH1::StatOverFlows flag
4481/// and if the statistics has been computed at filling time.
4482/// If a range is set in the histogram the number is computed from the given range.
4483
4485{
4486 Stat_t s[kNstat];
4487 this->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
4488 return (s[1] ? s[0]*s[0]/s[1] : TMath::Abs(s[0]) );
4489}
4490
4491////////////////////////////////////////////////////////////////////////////////
4492/// Shortcut to set the three histogram colors with a single call.
4493///
4494/// By default: linecolor = markercolor = fillcolor = -1
4495/// If a color is < 0 this method does not change the corresponding color if positive or null it set the color.
4496///
4497/// For instance:
4498/// ~~~ {.cpp}
4499/// h->SetColors(kRed, kRed);
4500/// ~~~
4501/// will set the line color and the marker color to red.
4502
4504{
4505 if (linecolor >= 0)
4507 if (markercolor >= 0)
4509 if (fillcolor >= 0)
4511}
4512
4513
4514////////////////////////////////////////////////////////////////////////////////
4515/// Set highlight (enable/disable) mode for the histogram
4516/// by default highlight mode is disable
4517
4518void TH1::SetHighlight(Bool_t set)
4519{
4520 if (IsHighlight() == set)
4521 return;
4522 if (fDimension > 2) {
4523 Info("SetHighlight", "Supported only 1-D or 2-D histograms");
4524 return;
4525 }
4526
4527 SetBit(kIsHighlight, set);
4528
4529 if (fPainter)
4531}
4532
4533////////////////////////////////////////////////////////////////////////////////
4534/// Redefines TObject::GetObjectInfo.
4535/// Displays the histogram info (bin number, contents, integral up to bin
4536/// corresponding to cursor position px,py
4537
4538char *TH1::GetObjectInfo(Int_t px, Int_t py) const
4539{
4540 return ((TH1*)this)->GetPainter()->GetObjectInfo(px,py);
4541}
4542
4543////////////////////////////////////////////////////////////////////////////////
4544/// Return pointer to painter.
4545/// If painter does not exist, it is created
4546
4548{
4549 if (!fPainter) {
4550 TString opt = option;
4551 opt.ToLower();
4552 if (opt.Contains("gl") || gStyle->GetCanvasPreferGL()) {
4553 //try to create TGLHistPainter
4554 TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TGLHistPainter");
4555
4556 if (handler && handler->LoadPlugin() != -1)
4557 fPainter = reinterpret_cast<TVirtualHistPainter *>(handler->ExecPlugin(1, this));
4558 }
4559 }
4560
4562
4563 return fPainter;
4564}
4565
4566////////////////////////////////////////////////////////////////////////////////
4567/// Compute Quantiles for this histogram.
4568/// A quantile x_p := Q(p) is defined as the value x_p such that the cumulative
4569/// probability distribution Function F of variable X yields:
4570///
4571/// ~~~ {.cpp}
4572/// F(x_p) = Pr(X <= x_p) = p with 0 <= p <= 1.
4573/// x_p = Q(p) = F_inv(p)
4574/// ~~~
4575///
4576/// For instance the median x_0.5 of a distribution is defined as that value
4577/// of the random variable X for which the distribution function equals 0.5:
4578///
4579/// ~~~ {.cpp}
4580/// F(x_0.5) = Probability(X < x_0.5) = 0.5
4581/// x_0.5 = Q(0.5)
4582/// ~~~
4583///
4584/// \author Eddy Offermann
4585/// code from Eddy Offermann, Renaissance
4586///
4587/// \param[in] n maximum size of the arrays xp and p (if given)
4588/// \param[out] xp array to be filled with nq quantiles evaluated at (p). Memory has to be preallocated by caller.
4589/// - If `p == nullptr`, the quantiles are computed at the (first `n`) probabilities p given by the CDF of the histogram;
4590/// `n` must thus be smaller or equal Nbins+1, otherwise the extra values of `xp` will not be filled and `nq` will be smaller than `n`.
4591/// If all bins have non-zero entries, the quantiles happen to be the bin centres.
4592/// Empty bins will, however, be skipped in the quantiles.
4593/// If the CDF is e.g. [0., 0., 0.1, ...], the quantiles would be, [3., 3., 3., ...], with the third bin starting
4594/// at 3.
4595/// \param[in] p array of cumulative probabilities where quantiles should be evaluated.
4596/// - if `p == nullptr`, the CDF of the histogram will be used to compute the quantiles, and will
4597/// have a size of n.
4598/// - Otherwise, it is assumed to contain at least n values.
4599/// \return number of quantiles computed
4600/// \note Unlike in TF1::GetQuantiles, `p` is here an optional argument
4601///
4602/// Note that the Integral of the histogram is automatically recomputed
4603/// if the number of entries is different of the number of entries when
4604/// the integral was computed last time. In case you do not use the Fill
4605/// functions to fill your histogram, but SetBinContent, you must call
4606/// TH1::ComputeIntegral before calling this function.
4607///
4608/// Getting quantiles xp from two histograms and storing results in a TGraph,
4609/// a so-called QQ-plot
4610///
4611/// ~~~ {.cpp}
4612/// TGraph *gr = new TGraph(nprob);
4613/// h1->GetQuantiles(nprob,gr->GetX());
4614/// h2->GetQuantiles(nprob,gr->GetY());
4615/// gr->Draw("alp");
4616/// ~~~
4617///
4618/// Example:
4619///
4620/// ~~~ {.cpp}
4621/// void quantiles() {
4622/// // demo for quantiles
4623/// const Int_t nq = 20;
4624/// TH1F *h = new TH1F("h","demo quantiles",100,-3,3);
4625/// h->FillRandom("gaus",5000);
4626/// h->GetXaxis()->SetTitle("x");
4627/// h->GetYaxis()->SetTitle("Counts");
4628///
4629/// Double_t p[nq]; // probabilities where to evaluate the quantiles in [0,1]
4630/// Double_t xp[nq]; // array of positions X to store the resulting quantiles
4631/// for (Int_t i=0;i<nq;i++) p[i] = Float_t(i+1)/nq;
4632/// h->GetQuantiles(nq,xp,p);
4633///
4634/// //show the original histogram in the top pad
4635/// TCanvas *c1 = new TCanvas("c1","demo quantiles",10,10,700,900);
4636/// c1->Divide(1,2);
4637/// c1->cd(1);
4638/// h->Draw();
4639///
4640/// // show the quantiles in the bottom pad
4641/// c1->cd(2);
4642/// gPad->SetGrid();
4643/// TGraph *gr = new TGraph(nq,p,xp);
4644/// gr->SetMarkerStyle(21);
4645/// gr->GetXaxis()->SetTitle("p");
4646/// gr->GetYaxis()->SetTitle("x");
4647/// gr->Draw("alp");
4648/// }
4649/// ~~~
4650
4652{
4653 if (GetDimension() > 1) {
4654 Error("GetQuantiles","Only available for 1-d histograms");
4655 return 0;
4656 }
4657
4658 const Int_t nbins = GetXaxis()->GetNbins();
4659 if (!fIntegral) ComputeIntegral();
4660 if (fIntegral[nbins+1] != fEntries) ComputeIntegral();
4661
4662 Int_t i, ibin;
4663 Int_t nq = n;
4664 std::unique_ptr<Double_t[]> localProb;
4665 if (p == nullptr) {
4666 nq = nbins+1;
4667 localProb.reset(new Double_t[nq]);
4668 localProb[0] = 0;
4669 for (i=1;i<nq;i++) {
4670 localProb[i] = fIntegral[i] / fIntegral[nbins];
4671 }
4672 }
4673 Double_t const *const prob = p ? p : localProb.get();
4674
4675 for (i = 0; i < nq; i++) {
4677 if (fIntegral[ibin] == prob[i]) {
4678 if (prob[i] == 0.) {
4679 for (; ibin+1 <= nbins && fIntegral[ibin+1] == 0.; ++ibin) {
4680
4681 }
4682 xp[i] = fXaxis.GetBinUpEdge(ibin);
4683 }
4684 else if (prob[i] == 1.) {
4685 xp[i] = fXaxis.GetBinUpEdge(ibin);
4686 }
4687 else {
4688 // Find equal integral in later bins (ie their entries are zero)
4689 Double_t width = 0;
4690 for (Int_t j = ibin+1; j <= nbins; ++j) {
4691 if (prob[i] == fIntegral[j]) {
4693 }
4694 else
4695 break;
4696 }
4698 }
4699 }
4700 else {
4701 xp[i] = GetBinLowEdge(ibin+1);
4703 if (dint > 0) xp[i] += GetBinWidth(ibin+1)*(prob[i]-fIntegral[ibin])/dint;
4704 }
4705 }
4706
4707 return nq;
4708}
4709
4710////////////////////////////////////////////////////////////////////////////////
4716 return 1;
4717}
4718
4719////////////////////////////////////////////////////////////////////////////////
4720/// Compute Initial values of parameters for a gaussian.
4721
4722void H1InitGaus()
4723{
4724 Double_t allcha, sumx, sumx2, x, val, stddev, mean;
4725 Int_t bin;
4726 const Double_t sqrtpi = 2.506628;
4727
4728 // - Compute mean value and StdDev of the histogram in the given range
4730 TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4731 Int_t hxfirst = hFitter->GetXfirst();
4732 Int_t hxlast = hFitter->GetXlast();
4733 Double_t valmax = curHist->GetBinContent(hxfirst);
4734 Double_t binwidx = curHist->GetBinWidth(hxfirst);
4735 allcha = sumx = sumx2 = 0;
4736 for (bin=hxfirst;bin<=hxlast;bin++) {
4737 x = curHist->GetBinCenter(bin);
4738 val = TMath::Abs(curHist->GetBinContent(bin));
4739 if (val > valmax) valmax = val;
4740 sumx += val*x;
4741 sumx2 += val*x*x;
4742 allcha += val;
4743 }
4744 if (allcha == 0) return;
4745 mean = sumx/allcha;
4746 stddev = sumx2/allcha - mean*mean;
4747 if (stddev > 0) stddev = TMath::Sqrt(stddev);
4748 else stddev = 0;
4749 if (stddev == 0) stddev = binwidx*(hxlast-hxfirst+1)/4;
4750 //if the distribution is really gaussian, the best approximation
4751 //is binwidx*allcha/(sqrtpi*stddev)
4752 //However, in case of non-gaussian tails, this underestimates
4753 //the normalisation constant. In this case the maximum value
4754 //is a better approximation.
4755 //We take the average of both quantities
4757
4758 //In case the mean value is outside the histo limits and
4759 //the StdDev is bigger than the range, we take
4760 // mean = center of bins
4761 // stddev = half range
4762 Double_t xmin = curHist->GetXaxis()->GetXmin();
4763 Double_t xmax = curHist->GetXaxis()->GetXmax();
4764 if ((mean < xmin || mean > xmax) && stddev > (xmax-xmin)) {
4765 mean = 0.5*(xmax+xmin);
4766 stddev = 0.5*(xmax-xmin);
4767 }
4768 TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4770 f1->SetParameter(1,mean);
4772 f1->SetParLimits(2,0,10*stddev);
4773}
4774
4775////////////////////////////////////////////////////////////////////////////////
4776/// Compute Initial values of parameters for an exponential.
4777
4778void H1InitExpo()
4779{
4781 Int_t ifail;
4783 Int_t hxfirst = hFitter->GetXfirst();
4784 Int_t hxlast = hFitter->GetXlast();
4785 Int_t nchanx = hxlast - hxfirst + 1;
4786
4788
4789 TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4791 f1->SetParameter(1,slope);
4792
4793}
4794
4795////////////////////////////////////////////////////////////////////////////////
4796/// Compute Initial values of parameters for a polynom.
4797
4798void H1InitPolynom()
4799{
4800 Double_t fitpar[25];
4801
4803 TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4804 Int_t hxfirst = hFitter->GetXfirst();
4805 Int_t hxlast = hFitter->GetXlast();
4806 Int_t nchanx = hxlast - hxfirst + 1;
4807 Int_t npar = f1->GetNpar();
4808
4809 if (nchanx <=1 || npar == 1) {
4810 TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4811 fitpar[0] = curHist->GetSumOfWeights()/Double_t(nchanx);
4812 } else {
4814 }
4815 for (Int_t i=0;i<npar;i++) f1->SetParameter(i, fitpar[i]);
4816}
4817
4818////////////////////////////////////////////////////////////////////////////////
4819/// Least squares lpolynomial fitting without weights.
4820///
4821/// \param[in] n number of points to fit
4822/// \param[in] m number of parameters
4823/// \param[in] a array of parameters
4824///
4825/// based on CERNLIB routine LSQ: Translated to C++ by Rene Brun
4826/// (E.Keil. revised by B.Schorr, 23.10.1981.)
4827
4829{
4830 const Double_t zero = 0.;
4831 const Double_t one = 1.;
4832 const Int_t idim = 20;
4833
4834 Double_t b[400] /* was [20][20] */;
4835 Int_t i, k, l, ifail;
4837 Double_t da[20], xk, yk;
4838
4839 if (m <= 2) {
4840 H1LeastSquareLinearFit(n, a[0], a[1], ifail);
4841 return;
4842 }
4843 if (m > idim || m > n) return;
4844 b[0] = Double_t(n);
4845 da[0] = zero;
4846 for (l = 2; l <= m; ++l) {
4847 b[l-1] = zero;
4848 b[m + l*20 - 21] = zero;
4849 da[l-1] = zero;
4850 }
4852 TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4853 Int_t hxfirst = hFitter->GetXfirst();
4854 Int_t hxlast = hFitter->GetXlast();
4855 for (k = hxfirst; k <= hxlast; ++k) {
4856 xk = curHist->GetBinCenter(k);
4857 yk = curHist->GetBinContent(k);
4858 power = one;
4859 da[0] += yk;
4860 for (l = 2; l <= m; ++l) {
4861 power *= xk;
4862 b[l-1] += power;
4863 da[l-1] += power*yk;
4864 }
4865 for (l = 2; l <= m; ++l) {
4866 power *= xk;
4867 b[m + l*20 - 21] += power;
4868 }
4869 }
4870 for (i = 3; i <= m; ++i) {
4871 for (k = i; k <= m; ++k) {
4872 b[k - 1 + (i-1)*20 - 21] = b[k + (i-2)*20 - 21];
4873 }
4874 }
4876
4877 for (i=0; i<m; ++i) a[i] = da[i];
4878
4879}
4880
4881////////////////////////////////////////////////////////////////////////////////
4882/// Least square linear fit without weights.
4883///
4884/// extracted from CERNLIB LLSQ: Translated to C++ by Rene Brun
4885/// (added to LSQ by B. Schorr, 15.02.1982.)
4886
4888{
4890 Int_t i, n;
4892 Double_t fn, xk, yk;
4893 Double_t det;
4894
4895 n = TMath::Abs(ndata);
4896 ifail = -2;
4897 xbar = ybar = x2bar = xybar = 0;
4899 TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4900 Int_t hxfirst = hFitter->GetXfirst();
4901 Int_t hxlast = hFitter->GetXlast();
4902 for (i = hxfirst; i <= hxlast; ++i) {
4903 xk = curHist->GetBinCenter(i);
4904 yk = curHist->GetBinContent(i);
4905 if (ndata < 0) {
4906 if (yk <= 0) yk = 1e-9;
4907 yk = TMath::Log(yk);
4908 }
4909 xbar += xk;
4910 ybar += yk;
4911 x2bar += xk*xk;
4912 xybar += xk*yk;
4913 }
4914 fn = Double_t(n);
4915 det = fn*x2bar - xbar*xbar;
4916 ifail = -1;
4917 if (det <= 0) {
4918 a0 = ybar/fn;
4919 a1 = 0;
4920 return;
4921 }
4922 ifail = 0;
4923 a0 = (x2bar*ybar - xbar*xybar) / det;
4924 a1 = (fn*xybar - xbar*ybar) / det;
4925
4926}
4927
4928////////////////////////////////////////////////////////////////////////////////
4929/// Extracted from CERN Program library routine DSEQN.
4930///
4931/// Translated to C++ by Rene Brun
4932
4934{
4936 Int_t nmjp1, i, j, l;
4937 Int_t im1, jp1, nm1, nmi;
4938 Double_t s1, s21, s22;
4939 const Double_t one = 1.;
4940
4941 /* Parameter adjustments */
4942 b_dim1 = idim;
4943 b_offset = b_dim1 + 1;
4944 b -= b_offset;
4945 a_dim1 = idim;
4946 a_offset = a_dim1 + 1;
4947 a -= a_offset;
4948
4949 if (idim < n) return;
4950
4951 ifail = 0;
4952 for (j = 1; j <= n; ++j) {
4953 if (a[j + j*a_dim1] <= 0) { ifail = -1; return; }
4954 a[j + j*a_dim1] = one / a[j + j*a_dim1];
4955 if (j == n) continue;
4956 jp1 = j + 1;
4957 for (l = jp1; l <= n; ++l) {
4958 a[j + l*a_dim1] = a[j + j*a_dim1] * a[l + j*a_dim1];
4959 s1 = -a[l + (j+1)*a_dim1];
4960 for (i = 1; i <= j; ++i) { s1 = a[l + i*a_dim1] * a[i + (j+1)*a_dim1] + s1; }
4961 a[l + (j+1)*a_dim1] = -s1;
4962 }
4963 }
4964 if (k <= 0) return;
4965
4966 for (l = 1; l <= k; ++l) {
4967 b[l*b_dim1 + 1] = a[a_dim1 + 1]*b[l*b_dim1 + 1];
4968 }
4969 if (n == 1) return;
4970 for (l = 1; l <= k; ++l) {
4971 for (i = 2; i <= n; ++i) {
4972 im1 = i - 1;
4973 s21 = -b[i + l*b_dim1];
4974 for (j = 1; j <= im1; ++j) {
4975 s21 = a[i + j*a_dim1]*b[j + l*b_dim1] + s21;
4976 }
4977 b[i + l*b_dim1] = -a[i + i*a_dim1]*s21;
4978 }
4979 nm1 = n - 1;
4980 for (i = 1; i <= nm1; ++i) {
4981 nmi = n - i;
4982 s22 = -b[nmi + l*b_dim1];
4983 for (j = 1; j <= i; ++j) {
4984 nmjp1 = n - j + 1;
4985 s22 = a[nmi + nmjp1*a_dim1]*b[nmjp1 + l*b_dim1] + s22;
4986 }
4987 b[nmi + l*b_dim1] = -s22;
4988 }
4989 }
4990}
4991
4992////////////////////////////////////////////////////////////////////////////////
4993/// Return Global bin number corresponding to binx,y,z.
4994///
4995/// 2-D and 3-D histograms are represented with a one dimensional
4996/// structure.
4997/// This has the advantage that all existing functions, such as
4998/// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
4999///
5000/// In case of a TH1x, returns binx directly.
5001/// see TH1::GetBinXYZ for the inverse transformation.
5002///
5003/// Convention for numbering bins
5004///
5005/// For all histogram types: nbins, xlow, xup
5006///
5007/// - bin = 0; underflow bin
5008/// - bin = 1; first bin with low-edge xlow INCLUDED
5009/// - bin = nbins; last bin with upper-edge xup EXCLUDED
5010/// - bin = nbins+1; overflow bin
5011///
5012/// In case of 2-D or 3-D histograms, a "global bin" number is defined.
5013/// For example, assuming a 3-D histogram with binx,biny,binz, the function
5014///
5015/// ~~~ {.cpp}
5016/// Int_t bin = h->GetBin(binx,biny,binz);
5017/// ~~~
5018///
5019/// returns a global/linearized bin number. This global bin is useful
5020/// to access the bin information independently of the dimension.
5021
5023{
5024 Int_t ofx = fXaxis.GetNbins() + 1; // overflow bin
5025 if (binx < 0) binx = 0;
5026 if (binx > ofx) binx = ofx;
5027
5028 return binx;
5029}
5030
5031////////////////////////////////////////////////////////////////////////////////
5032/// Return binx, biny, binz corresponding to the global bin number globalbin
5033/// see TH1::GetBin function above
5034
5036{
5037 Int_t nx = fXaxis.GetNbins()+2;
5038 Int_t ny = fYaxis.GetNbins()+2;
5039
5040 if (GetDimension() == 1) {
5041 binx = binglobal%nx;
5042 biny = 0;
5043 binz = 0;
5044 return;
5045 }
5046 if (GetDimension() == 2) {
5047 binx = binglobal%nx;
5048 biny = ((binglobal-binx)/nx)%ny;
5049 binz = 0;
5050 return;
5051 }
5052 if (GetDimension() == 3) {
5053 binx = binglobal%nx;
5054 biny = ((binglobal-binx)/nx)%ny;
5055 binz = ((binglobal-binx)/nx -biny)/ny;
5056 }
5057}
5058
5059////////////////////////////////////////////////////////////////////////////////
5060/// Return a random number distributed according the histogram bin contents.
5061/// This function checks if the bins integral exists. If not, the integral
5062/// is evaluated, normalized to one.
5063///
5064/// @param rng (optional) Random number generator pointer used (default is gRandom)
5065/// @param option (optional) Set it to "width" if your non-uniform bin contents represent a density rather than counts
5066///
5067/// The integral is automatically recomputed if the number of entries
5068/// is not the same then when the integral was computed.
5069/// @note Only valid for 1-d histograms. Use GetRandom2 or GetRandom3 otherwise.
5070/// If the histogram has a bin with negative content, a NaN is returned.
5071
5073{
5074 if (fDimension > 1) {
5075 Error("GetRandom","Function only valid for 1-d histograms");
5076 return 0;
5077 }
5079 Double_t integral = 0;
5080 // compute integral checking that all bins have positive content (see ROOT-5894)
5081 if (fIntegral) {
5082 if (fIntegral[nbinsx + 1] != fEntries)
5083 integral = const_cast<TH1 *>(this)->ComputeIntegral(true, option);
5084 else integral = fIntegral[nbinsx];
5085 } else {
5086 integral = const_cast<TH1 *>(this)->ComputeIntegral(true, option);
5087 }
5088 if (integral == 0) return 0;
5089 // return a NaN in case some bins have negative content
5090 if (integral == TMath::QuietNaN() ) return TMath::QuietNaN();
5091
5092 Double_t r1 = (rng) ? rng->Rndm() : gRandom->Rndm();
5095 if (r1 > fIntegral[ibin]) x +=
5097 return x;
5098}
5099
5100////////////////////////////////////////////////////////////////////////////////
5101/// Return content of bin number bin.
5102///
5103/// Implemented in TH1C,S,F,D
5104///
5105/// Convention for numbering bins
5106///
5107/// For all histogram types: nbins, xlow, xup
5108///
5109/// - bin = 0; underflow bin
5110/// - bin = 1; first bin with low-edge xlow INCLUDED
5111/// - bin = nbins; last bin with upper-edge xup EXCLUDED
5112/// - bin = nbins+1; overflow bin
5113///
5114/// In case of 2-D or 3-D histograms, a "global bin" number is defined.
5115/// For example, assuming a 3-D histogram with binx,biny,binz, the function
5116///
5117/// ~~~ {.cpp}
5118/// Int_t bin = h->GetBin(binx,biny,binz);
5119/// ~~~
5120///
5121/// returns a global/linearized bin number. This global bin is useful
5122/// to access the bin information independently of the dimension.
5123
5125{
5126 if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
5127 if (bin < 0) bin = 0;
5128 if (bin >= fNcells) bin = fNcells-1;
5129
5130 return RetrieveBinContent(bin);
5131}
5132
5133////////////////////////////////////////////////////////////////////////////////
5134/// Compute first binx in the range [firstx,lastx] for which
5135/// diff = abs(bin_content-c) <= maxdiff
5136///
5137/// In case several bins in the specified range with diff=0 are found
5138/// the first bin found is returned in binx.
5139/// In case several bins in the specified range satisfy diff <=maxdiff
5140/// the bin with the smallest difference is returned in binx.
5141/// In all cases the function returns the smallest difference.
5142///
5143/// NOTE1: if firstx <= 0, firstx is set to bin 1
5144/// if (lastx < firstx then firstx is set to the number of bins
5145/// ie if firstx=0 and lastx=0 (default) the search is on all bins.
5146///
5147/// NOTE2: if maxdiff=0 (default), the first bin with content=c is returned.
5148
5150{
5151 if (fDimension > 1) {
5152 binx = 0;
5153 Error("GetBinWithContent","function is only valid for 1-D histograms");
5154 return 0;
5155 }
5156
5157 if (fBuffer) ((TH1*)this)->BufferEmpty();
5158
5159 if (firstx <= 0) firstx = 1;
5160 if (lastx < firstx) lastx = fXaxis.GetNbins();
5161 Int_t binminx = 0;
5162 Double_t diff, curmax = 1.e240;
5163 for (Int_t i=firstx;i<=lastx;i++) {
5165 if (diff <= 0) {binx = i; return diff;}
5166 if (diff < curmax && diff <= maxdiff) {curmax = diff, binminx=i;}
5167 }
5168 binx = binminx;
5169 return curmax;
5170}
5171
5172////////////////////////////////////////////////////////////////////////////////
5173/// Given a point x, approximates the value via linear interpolation
5174/// based on the two nearest bin centers
5175///
5176/// Andy Mastbaum 10/21/08
5177
5179{
5180 if (fBuffer) ((TH1*)this)->BufferEmpty();
5181
5183 Double_t x0,x1,y0,y1;
5184
5185 if(x<=GetBinCenter(1)) {
5186 return RetrieveBinContent(1);
5187 } else if(x>=GetBinCenter(GetNbinsX())) {
5188 return RetrieveBinContent(GetNbinsX());
5189 } else {
5190 if(x<=GetBinCenter(xbin)) {
5192 x0 = GetBinCenter(xbin-1);
5194 x1 = GetBinCenter(xbin);
5195 } else {
5197 x0 = GetBinCenter(xbin);
5199 x1 = GetBinCenter(xbin+1);
5200 }
5201 return y0 + (x-x0)*((y1-y0)/(x1-x0));
5202 }
5203}
5204
5205////////////////////////////////////////////////////////////////////////////////
5206/// 2d Interpolation. Not yet implemented.
5207
5209{
5210 Error("Interpolate","This function must be called with 1 argument for a TH1");
5211 return 0;
5212}
5213
5214////////////////////////////////////////////////////////////////////////////////
5215/// 3d Interpolation. Not yet implemented.
5216
5218{
5219 Error("Interpolate","This function must be called with 1 argument for a TH1");
5220 return 0;
5221}
5222
5223///////////////////////////////////////////////////////////////////////////////
5224/// Check if a histogram is empty
5225/// (this is a protected method used mainly by TH1Merger )
5226
5227Bool_t TH1::IsEmpty() const
5228{
5229 // if fTsumw or fentries are not zero histogram is not empty
5230 // need to use GetEntries() instead of fEntries in case of bugger histograms
5231 // so we will flash the buffer
5232 if (fTsumw != 0) return kFALSE;
5233 if (GetEntries() != 0) return kFALSE;
5234 // case fTSumw == 0 amd entries are also zero
5235 // this should not really happening, but if one sets content by hand
5236 // it can happen. a call to ResetStats() should be done in such cases
5237 double sumw = 0;
5238 for (int i = 0; i< GetNcells(); ++i) sumw += RetrieveBinContent(i);
5239 return (sumw != 0) ? kFALSE : kTRUE;
5240}
5241
5242////////////////////////////////////////////////////////////////////////////////
5243/// Return true if the bin is overflow.
5244
5246{
5247 Int_t binx, biny, binz;
5248 GetBinXYZ(bin, binx, biny, binz);
5249
5250 if (iaxis == 0) {
5251 if ( fDimension == 1 )
5252 return binx >= GetNbinsX() + 1;
5253 if ( fDimension == 2 )
5254 return (binx >= GetNbinsX() + 1) ||
5255 (biny >= GetNbinsY() + 1);
5256 if ( fDimension == 3 )
5257 return (binx >= GetNbinsX() + 1) ||
5258 (biny >= GetNbinsY() + 1) ||
5259 (binz >= GetNbinsZ() + 1);
5260 return kFALSE;
5261 }
5262 if (iaxis == 1)
5263 return binx >= GetNbinsX() + 1;
5264 if (iaxis == 2)
5265 return biny >= GetNbinsY() + 1;
5266 if (iaxis == 3)
5267 return binz >= GetNbinsZ() + 1;
5268
5269 Error("IsBinOverflow","Invalid axis value");
5270 return kFALSE;
5271}
5272
5273////////////////////////////////////////////////////////////////////////////////
5274/// Return true if the bin is underflow.
5275/// If iaxis = 0 make OR with all axes otherwise check only for the given axis
5276
5278{
5279 Int_t binx, biny, binz;
5280 GetBinXYZ(bin, binx, biny, binz);
5281
5282 if (iaxis == 0) {
5283 if ( fDimension == 1 )
5284 return (binx <= 0);
5285 else if ( fDimension == 2 )
5286 return (binx <= 0 || biny <= 0);
5287 else if ( fDimension == 3 )
5288 return (binx <= 0 || biny <= 0 || binz <= 0);
5289 else
5290 return kFALSE;
5291 }
5292 if (iaxis == 1)
5293 return (binx <= 0);
5294 if (iaxis == 2)
5295 return (biny <= 0);
5296 if (iaxis == 3)
5297 return (binz <= 0);
5298
5299 Error("IsBinUnderflow","Invalid axis value");
5300 return kFALSE;
5301}
5302
5303////////////////////////////////////////////////////////////////////////////////
5304/// Reduce the number of bins for the axis passed in the option to the number of bins having a label.
5305/// The method will remove only the extra bins existing after the last "labeled" bin.
5306/// Note that if there are "un-labeled" bins present between "labeled" bins they will not be removed
5307
5309{
5311 TAxis *axis = nullptr;
5312 if (iaxis == 1) axis = GetXaxis();
5313 if (iaxis == 2) axis = GetYaxis();
5314 if (iaxis == 3) axis = GetZaxis();
5315 if (!axis) {
5316 Error("LabelsDeflate","Invalid axis option %s",ax);
5317 return;
5318 }
5319 if (!axis->GetLabels()) return;
5320
5321 // find bin with last labels
5322 // bin number is object ID in list of labels
5323 // therefore max bin number is number of bins of the deflated histograms
5324 TIter next(axis->GetLabels());
5325 TObject *obj;
5326 Int_t nbins = 0;
5327 while ((obj = next())) {
5328 Int_t ibin = obj->GetUniqueID();
5329 if (ibin > nbins) nbins = ibin;
5330 }
5331 if (nbins < 1) nbins = 1;
5332
5333 // Do nothing in case it was the last bin
5334 if (nbins==axis->GetNbins()) return;
5335
5336 TH1 *hold = (TH1*)IsA()->New();
5337 R__ASSERT(hold);
5338 hold->SetDirectory(nullptr);
5339 Copy(*hold);
5340
5341 Bool_t timedisp = axis->GetTimeDisplay();
5342 Double_t xmin = axis->GetXmin();
5343 Double_t xmax = axis->GetBinUpEdge(nbins);
5344 if (xmax <= xmin) xmax = xmin +nbins;
5345 axis->SetRange(0,0);
5346 axis->Set(nbins,xmin,xmax);
5347 SetBinsLength(-1); // reset the number of cells
5349 if (errors) fSumw2.Set(fNcells);
5350 axis->SetTimeDisplay(timedisp);
5351 // reset histogram content
5352 Reset("ICE");
5353
5354 //now loop on all bins and refill
5355 // NOTE that if the bins without labels have content
5356 // it will be put in the underflow/overflow.
5357 // For this reason we use AddBinContent method
5359 Int_t bin,binx,biny,binz;
5360 for (bin=0; bin < hold->fNcells; ++bin) {
5361 hold->GetBinXYZ(bin,binx,biny,binz);
5363 Double_t cu = hold->RetrieveBinContent(bin);
5365 if (errors) {
5366 fSumw2.fArray[ibin] += hold->fSumw2.fArray[bin];
5367 }
5368 }
5370 delete hold;
5371}
5372
5373////////////////////////////////////////////////////////////////////////////////
5374/// Double the number of bins for axis.
5375/// Refill histogram.
5376/// This function is called by TAxis::FindBin(const char *label)
5377
5379{
5381 TAxis *axis = nullptr;
5382 if (iaxis == 1) axis = GetXaxis();
5383 if (iaxis == 2) axis = GetYaxis();
5384 if (iaxis == 3) axis = GetZaxis();
5385 if (!axis) return;
5386
5387 TH1 *hold = (TH1*)IsA()->New();
5388 hold->SetDirectory(nullptr);
5389 Copy(*hold);
5390 hold->ResetBit(kMustCleanup);
5391
5392 Bool_t timedisp = axis->GetTimeDisplay();
5393 Int_t nbins = axis->GetNbins();
5394 Double_t xmin = axis->GetXmin();
5395 Double_t xmax = axis->GetXmax();
5396 xmax = xmin + 2*(xmax-xmin);
5397 axis->SetRange(0,0);
5398 // double the bins and recompute ncells
5399 axis->Set(2*nbins,xmin,xmax);
5400 SetBinsLength(-1);
5402 if (errors) fSumw2.Set(fNcells);
5403 axis->SetTimeDisplay(timedisp);
5404
5405 Reset("ICE"); // reset content and error
5406
5407 //now loop on all bins and refill
5409 Int_t bin,ibin,binx,biny,binz;
5410 for (ibin =0; ibin < hold->fNcells; ibin++) {
5411 // get the binx,y,z values . The x-y-z (axis) bin values will stay the same between new-old after the expanding
5412 hold->GetBinXYZ(ibin,binx,biny,binz);
5413 bin = GetBin(binx,biny,binz);
5414
5415 // underflow and overflow will be cleaned up because their meaning has been altered
5416 if (hold->IsBinUnderflow(ibin,iaxis) || hold->IsBinOverflow(ibin,iaxis)) {
5417 continue;
5418 }
5419 else {
5420 AddBinContent(bin, hold->RetrieveBinContent(ibin));
5421 if (errors) fSumw2.fArray[bin] += hold->fSumw2.fArray[ibin];
5422 }
5423 }
5425 delete hold;
5426}
5427
5428////////////////////////////////////////////////////////////////////////////////
5429/// Sort bins with labels or set option(s) to draw axis with labels
5430/// \param[in] option
5431/// - "a" sort by alphabetic order
5432/// - ">" sort by decreasing values
5433/// - "<" sort by increasing values
5434/// - "h" draw labels horizontal
5435/// - "v" draw labels vertical
5436/// - "u" draw labels up (end of label right adjusted)
5437/// - "d" draw labels down (start of label left adjusted)
5438///
5439/// In case not all bins have labels sorting will work only in the case
5440/// the first `n` consecutive bins have all labels and sorting will be performed on
5441/// those label bins.
5442///
5443/// \param[in] ax axis
5444
5446{
5448 TAxis *axis = nullptr;
5449 if (iaxis == 1)
5450 axis = GetXaxis();
5451 if (iaxis == 2)
5452 axis = GetYaxis();
5453 if (iaxis == 3)
5454 axis = GetZaxis();
5455 if (!axis)
5456 return;
5457 THashList *labels = axis->GetLabels();
5458 if (!labels) {
5459 Warning("LabelsOption", "Axis %s has no labels!",axis->GetName());
5460 return;
5461 }
5462 TString opt = option;
5463 opt.ToLower();
5464 Int_t iopt = -1;
5465 if (opt.Contains("h")) {
5470 iopt = 0;
5471 }
5472 if (opt.Contains("v")) {
5477 iopt = 1;
5478 }
5479 if (opt.Contains("u")) {
5480 axis->SetBit(TAxis::kLabelsUp);
5484 iopt = 2;
5485 }
5486 if (opt.Contains("d")) {
5491 iopt = 3;
5492 }
5493 Int_t sort = -1;
5494 if (opt.Contains("a"))
5495 sort = 0;
5496 if (opt.Contains(">"))
5497 sort = 1;
5498 if (opt.Contains("<"))
5499 sort = 2;
5500 if (sort < 0) {
5501 if (iopt < 0)
5502 Error("LabelsOption", "%s is an invalid label placement option!",opt.Data());
5503 return;
5504 }
5505
5506 // Code works only if first n bins have labels if we uncomment following line
5507 // but we don't want to support this special case
5508 // Int_t n = TMath::Min(axis->GetNbins(), labels->GetSize());
5509
5510 // support only cases where each bin has a labels (should be when axis is alphanumeric)
5511 Int_t n = labels->GetSize();
5512 if (n != axis->GetNbins()) {
5513 // check if labels are all consecutive and starts from the first bin
5514 // in that case the current code will work fine
5515 Int_t firstLabelBin = axis->GetNbins()+1;
5516 Int_t lastLabelBin = -1;
5517 for (Int_t i = 0; i < n; ++i) {
5518 Int_t bin = labels->At(i)->GetUniqueID();
5519 if (bin < firstLabelBin) firstLabelBin = bin;
5520 if (bin > lastLabelBin) lastLabelBin = bin;
5521 }
5522 if (firstLabelBin != 1 || lastLabelBin-firstLabelBin +1 != n) {
5523 Error("LabelsOption", "%s of Histogram %s contains bins without labels. Sorting will not work correctly - return",
5524 axis->GetName(), GetName());
5525 return;
5526 }
5527 // case where label bins are consecutive starting from first bin will work
5528 // calling before a TH1::LabelsDeflate() will avoid this error message
5529 Warning("LabelsOption", "axis %s of Histogram %s has extra following bins without labels. Sorting will work only for first label bins",
5530 axis->GetName(), GetName());
5531 }
5532 std::vector<Int_t> a(n);
5533 std::vector<Int_t> b(n);
5534
5535
5536 Int_t i, j, k;
5537 std::vector<Double_t> cont;
5538 std::vector<Double_t> errors2;
5539 THashList *labold = new THashList(labels->GetSize(), 1);
5540 TIter nextold(labels);
5541 TObject *obj = nullptr;
5542 labold->AddAll(labels);
5543 labels->Clear();
5544
5545 // delete buffer if it is there since bins will be reordered.
5546 if (fBuffer)
5547 BufferEmpty(1);
5548
5549 if (sort > 0) {
5550 //---sort by values of bins
5551 if (GetDimension() == 1) {
5552 cont.resize(n);
5553 if (fSumw2.fN)
5554 errors2.resize(n);
5555 for (i = 0; i < n; i++) {
5556 cont[i] = RetrieveBinContent(i + 1);
5557 if (!errors2.empty())
5558 errors2[i] = GetBinErrorSqUnchecked(i + 1);
5559 b[i] = labold->At(i)->GetUniqueID(); // this is the bin corresponding to the label
5560 a[i] = i;
5561 }
5562 if (sort == 1)
5563 TMath::Sort(n, cont.data(), a.data(), kTRUE); // sort by decreasing values
5564 else
5565 TMath::Sort(n, cont.data(), a.data(), kFALSE); // sort by increasing values
5566 for (i = 0; i < n; i++) {
5567 // use UpdateBinCOntent to not screw up histogram entries
5568 UpdateBinContent(i + 1, cont[b[a[i]] - 1]); // b[a[i]] returns bin number. .we need to subtract 1
5569 if (gDebug)
5570 Info("LabelsOption","setting bin %d value %f from bin %d label %s at pos %d ",
5571 i+1,cont[b[a[i]] - 1],b[a[i]],labold->At(a[i])->GetName(),a[i]);
5572 if (!errors2.empty())
5573 fSumw2.fArray[i + 1] = errors2[b[a[i]] - 1];
5574 }
5575 for (i = 0; i < n; i++) {
5576 obj = labold->At(a[i]);
5577 labels->Add(obj);
5578 obj->SetUniqueID(i + 1);
5579 }
5580 } else if (GetDimension() == 2) {
5581 std::vector<Double_t> pcont(n + 2);
5582 Int_t nx = fXaxis.GetNbins() + 2;
5583 Int_t ny = fYaxis.GetNbins() + 2;
5584 cont.resize((nx + 2) * (ny + 2));
5585 if (fSumw2.fN)
5586 errors2.resize((nx + 2) * (ny + 2));
5587 for (i = 0; i < nx; i++) {
5588 for (j = 0; j < ny; j++) {
5589 Int_t bin = GetBin(i,j);
5590 cont[i + nx * j] = RetrieveBinContent(bin);
5591 if (!errors2.empty())
5592 errors2[i + nx * j] = GetBinErrorSqUnchecked(bin);
5593 if (axis == GetXaxis())
5594 k = i - 1;
5595 else
5596 k = j - 1;
5597 if (k >= 0 && k < n) { // we consider underflow/overflows in y for ordering the bins
5598 pcont[k] += cont[i + nx * j];
5599 a[k] = k;
5600 }
5601 }
5602 }
5603 if (sort == 1)
5604 TMath::Sort(n, pcont.data(), a.data(), kTRUE); // sort by decreasing values
5605 else
5606 TMath::Sort(n, pcont.data(), a.data(), kFALSE); // sort by increasing values
5607 for (i = 0; i < n; i++) {
5608 // iterate on old label list to find corresponding bin match
5609 TIter next(labold);
5610 UInt_t bin = a[i] + 1;
5611 while ((obj = next())) {
5612 if (obj->GetUniqueID() == (UInt_t)bin)
5613 break;
5614 else
5615 obj = nullptr;
5616 }
5617 if (!obj) {
5618 // this should not really happen
5619 R__ASSERT("LabelsOption - No corresponding bin found when ordering labels");
5620 return;
5621 }
5622
5623 labels->Add(obj);
5624 if (gDebug)
5625 std::cout << " set label " << obj->GetName() << " to bin " << i + 1 << " from order " << a[i] << " bin "
5626 << b[a[i]] << "content " << pcont[a[i]] << std::endl;
5627 }
5628 // need to set here new ordered labels - otherwise loop before does not work since labold and labels list
5629 // contain same objects
5630 for (i = 0; i < n; i++) {
5631 labels->At(i)->SetUniqueID(i + 1);
5632 }
5633 // set now the bin contents
5634 if (axis == GetXaxis()) {
5635 for (i = 0; i < n; i++) {
5636 Int_t ix = a[i] + 1;
5637 for (j = 0; j < ny; j++) {
5638 Int_t bin = GetBin(i + 1, j);
5639 UpdateBinContent(bin, cont[ix + nx * j]);
5640 if (!errors2.empty())
5641 fSumw2.fArray[bin] = errors2[ix + nx * j];
5642 }
5643 }
5644 } else {
5645 // using y axis
5646 for (i = 0; i < nx; i++) {
5647 for (j = 0; j < n; j++) {
5648 Int_t iy = a[j] + 1;
5649 Int_t bin = GetBin(i, j + 1);
5650 UpdateBinContent(bin, cont[i + nx * iy]);
5651 if (!errors2.empty())
5652 fSumw2.fArray[bin] = errors2[i + nx * iy];
5653 }
5654 }
5655 }
5656 } else {
5657 // sorting histograms: 3D case
5658 std::vector<Double_t> pcont(n + 2);
5659 Int_t nx = fXaxis.GetNbins() + 2;
5660 Int_t ny = fYaxis.GetNbins() + 2;
5661 Int_t nz = fZaxis.GetNbins() + 2;
5662 Int_t l = 0;
5663 cont.resize((nx + 2) * (ny + 2) * (nz + 2));
5664 if (fSumw2.fN)
5665 errors2.resize((nx + 2) * (ny + 2) * (nz + 2));
5666 for (i = 0; i < nx; i++) {
5667 for (j = 0; j < ny; j++) {
5668 for (k = 0; k < nz; k++) {
5669 Int_t bin = GetBin(i,j,k);
5671 if (axis == GetXaxis())
5672 l = i - 1;
5673 else if (axis == GetYaxis())
5674 l = j - 1;
5675 else
5676 l = k - 1;
5677 if (l >= 0 && l < n) { // we consider underflow/overflows in y for ordering the bins
5678 pcont[l] += c;
5679 a[l] = l;
5680 }
5681 cont[i + nx * (j + ny * k)] = c;
5682 if (!errors2.empty())
5683 errors2[i + nx * (j + ny * k)] = GetBinErrorSqUnchecked(bin);
5684 }
5685 }
5686 }
5687 if (sort == 1)
5688 TMath::Sort(n, pcont.data(), a.data(), kTRUE); // sort by decreasing values
5689 else
5690 TMath::Sort(n, pcont.data(), a.data(), kFALSE); // sort by increasing values
5691 for (i = 0; i < n; i++) {
5692 // iterate on the old label list to find corresponding bin match
5693 TIter next(labold);
5694 UInt_t bin = a[i] + 1;
5695 obj = nullptr;
5696 while ((obj = next())) {
5697 if (obj->GetUniqueID() == (UInt_t)bin) {
5698 break;
5699 }
5700 else
5701 obj = nullptr;
5702 }
5703 if (!obj) {
5704 R__ASSERT("LabelsOption - No corresponding bin found when ordering labels");
5705 return;
5706 }
5707 labels->Add(obj);
5708 if (gDebug)
5709 std::cout << " set label " << obj->GetName() << " to bin " << i + 1 << " from bin " << a[i] << "content "
5710 << pcont[a[i]] << std::endl;
5711 }
5712
5713 // need to set here new ordered labels - otherwise loop before does not work since labold and llabels list
5714 // contain same objects
5715 for (i = 0; i < n; i++) {
5716 labels->At(i)->SetUniqueID(i + 1);
5717 }
5718 // set now the bin contents
5719 if (axis == GetXaxis()) {
5720 for (i = 0; i < n; i++) {
5721 Int_t ix = a[i] + 1;
5722 for (j = 0; j < ny; j++) {
5723 for (k = 0; k < nz; k++) {
5724 Int_t bin = GetBin(i + 1, j, k);
5725 UpdateBinContent(bin, cont[ix + nx * (j + ny * k)]);
5726 if (!errors2.empty())
5727 fSumw2.fArray[bin] = errors2[ix + nx * (j + ny * k)];
5728 }
5729 }
5730 }
5731 } else if (axis == GetYaxis()) {
5732 // using y axis
5733 for (i = 0; i < nx; i++) {
5734 for (j = 0; j < n; j++) {
5735 Int_t iy = a[j] + 1;
5736 for (k = 0; k < nz; k++) {
5737 Int_t bin = GetBin(i, j + 1, k);
5738 UpdateBinContent(bin, cont[i + nx * (iy + ny * k)]);
5739 if (!errors2.empty())
5740 fSumw2.fArray[bin] = errors2[i + nx * (iy + ny * k)];
5741 }
5742 }
5743 }
5744 } else {
5745 // using z axis
5746 for (i = 0; i < nx; i++) {
5747 for (j = 0; j < ny; j++) {
5748 for (k = 0; k < n; k++) {
5749 Int_t iz = a[k] + 1;
5750 Int_t bin = GetBin(i, j , k +1);
5751 UpdateBinContent(bin, cont[i + nx * (j + ny * iz)]);
5752 if (!errors2.empty())
5753 fSumw2.fArray[bin] = errors2[i + nx * (j + ny * iz)];
5754 }
5755 }
5756 }
5757 }
5758 }
5759 } else {
5760 //---alphabetic sort
5761 // sort labels using vector of strings and TMath::Sort
5762 // I need to array because labels order in list is not necessary that of the bins
5763 std::vector<std::string> vecLabels(n);
5764 for (i = 0; i < n; i++) {
5765 vecLabels[i] = labold->At(i)->GetName();
5766 b[i] = labold->At(i)->GetUniqueID(); // this is the bin corresponding to the label
5767 a[i] = i;
5768 }
5769 // sort in ascending order for strings
5770 TMath::Sort(n, vecLabels.data(), a.data(), kFALSE);
5771 // set the new labels
5772 for (i = 0; i < n; i++) {
5773 TObject *labelObj = labold->At(a[i]);
5774 labels->Add(labold->At(a[i]));
5775 // set the corresponding bin. NB bin starts from 1
5776 labelObj->SetUniqueID(i + 1);
5777 if (gDebug)
5778 std::cout << "bin " << i + 1 << " setting new labels for axis " << labold->At(a[i])->GetName() << " from "
5779 << b[a[i]] << std::endl;
5780 }
5781
5782 if (GetDimension() == 1) {
5783 cont.resize(n + 2);
5784 if (fSumw2.fN)
5785 errors2.resize(n + 2);
5786 for (i = 0; i < n; i++) {
5787 cont[i] = RetrieveBinContent(b[a[i]]);
5788 if (!errors2.empty())
5790 }
5791 for (i = 0; i < n; i++) {
5792 UpdateBinContent(i + 1, cont[i]);
5793 if (!errors2.empty())
5794 fSumw2.fArray[i+1] = errors2[i];
5795 }
5796 } else if (GetDimension() == 2) {
5797 Int_t nx = fXaxis.GetNbins() + 2;
5798 Int_t ny = fYaxis.GetNbins() + 2;
5799 cont.resize(nx * ny);
5800 if (fSumw2.fN)
5801 errors2.resize(nx * ny);
5802 // copy old bin contents and then set to new ordered bins
5803 // N.B. bin in histograms starts from 1, but in y we consider under/overflows
5804 for (i = 0; i < nx; i++) {
5805 for (j = 0; j < ny; j++) { // ny is nbins+2
5806 Int_t bin = GetBin(i, j);
5807 cont[i + nx * j] = RetrieveBinContent(bin);
5808 if (!errors2.empty())
5809 errors2[i + nx * j] = GetBinErrorSqUnchecked(bin);
5810 }
5811 }
5812 if (axis == GetXaxis()) {
5813 for (i = 0; i < n; i++) {
5814 for (j = 0; j < ny; j++) {
5815 Int_t bin = GetBin(i + 1 , j);
5816 UpdateBinContent(bin, cont[b[a[i]] + nx * j]);
5817 if (!errors2.empty())
5818 fSumw2.fArray[bin] = errors2[b[a[i]] + nx * j];
5819 }
5820 }
5821 } else {
5822 for (i = 0; i < nx; i++) {
5823 for (j = 0; j < n; j++) {
5824 Int_t bin = GetBin(i, j + 1);
5825 UpdateBinContent(bin, cont[i + nx * b[a[j]]]);
5826 if (!errors2.empty())
5827 fSumw2.fArray[bin] = errors2[i + nx * b[a[j]]];
5828 }
5829 }
5830 }
5831 } else {
5832 // case of 3D (needs to be tested)
5833 Int_t nx = fXaxis.GetNbins() + 2;
5834 Int_t ny = fYaxis.GetNbins() + 2;
5835 Int_t nz = fZaxis.GetNbins() + 2;
5836 cont.resize(nx * ny * nz);
5837 if (fSumw2.fN)
5838 errors2.resize(nx * ny * nz);
5839 for (i = 0; i < nx; i++) {
5840 for (j = 0; j < ny; j++) {
5841 for (k = 0; k < nz; k++) {
5842 Int_t bin = GetBin(i, j, k);
5843 cont[i + nx * (j + ny * k)] = RetrieveBinContent(bin);
5844 if (!errors2.empty())
5845 errors2[i + nx * (j + ny * k)] = GetBinErrorSqUnchecked(bin);
5846 }
5847 }
5848 }
5849 if (axis == GetXaxis()) {
5850 // labels on x axis
5851 for (i = 0; i < n; i++) { // for x we loop only on bins with the labels
5852 for (j = 0; j < ny; j++) {
5853 for (k = 0; k < nz; k++) {
5854 Int_t bin = GetBin(i + 1, j, k);
5855 UpdateBinContent(bin, cont[b[a[i]] + nx * (j + ny * k)]);
5856 if (!errors2.empty())
5857 fSumw2.fArray[bin] = errors2[b[a[i]] + nx * (j + ny * k)];
5858 }
5859 }
5860 }
5861 } else if (axis == GetYaxis()) {
5862 // labels on y axis
5863 for (i = 0; i < nx; i++) {
5864 for (j = 0; j < n; j++) {
5865 for (k = 0; k < nz; k++) {
5866 Int_t bin = GetBin(i, j+1, k);
5867 UpdateBinContent(bin, cont[i + nx * (b[a[j]] + ny * k)]);
5868 if (!errors2.empty())
5869 fSumw2.fArray[bin] = errors2[i + nx * (b[a[j]] + ny * k)];
5870 }
5871 }
5872 }
5873 } else {
5874 // labels on z axis
5875 for (i = 0; i < nx; i++) {
5876 for (j = 0; j < ny; j++) {
5877 for (k = 0; k < n; k++) {
5878 Int_t bin = GetBin(i, j, k+1);
5879 UpdateBinContent(bin, cont[i + nx * (j + ny * b[a[k]])]);
5880 if (!errors2.empty())
5881 fSumw2.fArray[bin] = errors2[i + nx * (j + ny * b[a[k]])];
5882 }
5883 }
5884 }
5885 }
5886 }
5887 }
5888 // need to set to zero the statistics if axis has been sorted
5889 // see for example TH3::PutStats for definition of s vector
5890 bool labelsAreSorted = kFALSE;
5891 for (i = 0; i < n; ++i) {
5892 if (a[i] != i) {
5894 break;
5895 }
5896 }
5897 if (labelsAreSorted) {
5898 double s[TH1::kNstat];
5899 GetStats(s);
5900 if (iaxis == 1) {
5901 s[2] = 0; // fTsumwx
5902 s[3] = 0; // fTsumwx2
5903 s[6] = 0; // fTsumwxy
5904 s[9] = 0; // fTsumwxz
5905 } else if (iaxis == 2) {
5906 s[4] = 0; // fTsumwy
5907 s[5] = 0; // fTsumwy2
5908 s[6] = 0; // fTsumwxy
5909 s[10] = 0; // fTsumwyz
5910 } else if (iaxis == 3) {
5911 s[7] = 0; // fTsumwz
5912 s[8] = 0; // fTsumwz2
5913 s[9] = 0; // fTsumwxz
5914 s[10] = 0; // fTsumwyz
5915 }
5916 PutStats(s);
5917 }
5918 delete labold;
5919}
5920
5921////////////////////////////////////////////////////////////////////////////////
5922/// Test if two double are almost equal.
5923
5924static inline Bool_t AlmostEqual(Double_t a, Double_t b, Double_t epsilon = 0.00000001)
5925{
5926 return TMath::Abs(a - b) < epsilon;
5927}
5928
5929////////////////////////////////////////////////////////////////////////////////
5930/// Test if a double is almost an integer.
5931
5932static inline Bool_t AlmostInteger(Double_t a, Double_t epsilon = 0.00000001)
5933{
5934 return AlmostEqual(a - TMath::Floor(a), 0, epsilon) ||
5935 AlmostEqual(a - TMath::Floor(a), 1, epsilon);
5936}
5937
5938////////////////////////////////////////////////////////////////////////////////
5939/// Test if the binning is equidistant.
5940
5941static inline bool IsEquidistantBinning(const TAxis& axis)
5942{
5943 // check if axis bin are equals
5944 if (!axis.GetXbins()->fN) return true; //
5945 // not able to check if there is only one axis entry
5946 bool isEquidistant = true;
5947 const Double_t firstBinWidth = axis.GetBinWidth(1);
5948 for (int i = 1; i < axis.GetNbins(); ++i) {
5949 const Double_t binWidth = axis.GetBinWidth(i);
5950 const bool match = TMath::AreEqualRel(firstBinWidth, binWidth, 1.E-10);
5951 isEquidistant &= match;
5952 if (!match)
5953 break;
5954 }
5955 return isEquidistant;
5956}
5957
5958////////////////////////////////////////////////////////////////////////////////
5959/// Same limits and bins.
5960
5962 return axis1.GetNbins() == axis2.GetNbins() &&
5963 TMath::AreEqualAbs(axis1.GetXmin(), axis2.GetXmin(), axis1.GetBinWidth(axis1.GetNbins()) * 1.E-10) &&
5964 TMath::AreEqualAbs(axis1.GetXmax(), axis2.GetXmax(), axis1.GetBinWidth(axis1.GetNbins()) * 1.E-10);
5965}
5966
5967////////////////////////////////////////////////////////////////////////////////
5968/// Finds new limits for the axis for the Merge function.
5969/// returns false if the limits are incompatible
5970
5972{
5974 return kTRUE;
5975
5977 return kFALSE; // not equidistant user binning not supported
5978
5979 Double_t width1 = destAxis.GetBinWidth(0);
5980 Double_t width2 = anAxis.GetBinWidth(0);
5981 if (width1 == 0 || width2 == 0)
5982 return kFALSE; // no binning not supported
5983
5984 Double_t xmin = TMath::Min(destAxis.GetXmin(), anAxis.GetXmin());
5985 Double_t xmax = TMath::Max(destAxis.GetXmax(), anAxis.GetXmax());
5987
5988 // check the bin size
5990 return kFALSE;
5991
5992 // std::cout << "Find new limit using given axis " << anAxis.GetXmin() << " , " << anAxis.GetXmax() << " bin width " << width2 << std::endl;
5993 // std::cout << " and destination axis " << destAxis.GetXmin() << " , " << destAxis.GetXmax() << " bin width " << width1 << std::endl;
5994
5995
5996 // check the limits
5997 Double_t delta;
5998 delta = (destAxis.GetXmin() - xmin)/width1;
5999 if (!AlmostInteger(delta))
6000 xmin -= (TMath::Ceil(delta) - delta)*width1;
6001
6002 delta = (anAxis.GetXmin() - xmin)/width2;
6003 if (!AlmostInteger(delta))
6004 xmin -= (TMath::Ceil(delta) - delta)*width2;
6005
6006
6007 delta = (destAxis.GetXmin() - xmin)/width1;
6008 if (!AlmostInteger(delta))
6009 return kFALSE;
6010
6011
6012 delta = (xmax - destAxis.GetXmax())/width1;
6013 if (!AlmostInteger(delta))
6014 xmax += (TMath::Ceil(delta) - delta)*width1;
6015
6016
6017 delta = (xmax - anAxis.GetXmax())/width2;
6018 if (!AlmostInteger(delta))
6019 xmax += (TMath::Ceil(delta) - delta)*width2;
6020
6021
6022 delta = (xmax - destAxis.GetXmax())/width1;
6023 if (!AlmostInteger(delta))
6024 return kFALSE;
6025#ifdef DEBUG
6026 if (!AlmostInteger((xmax - xmin) / width)) { // unnecessary check
6027 printf("TH1::RecomputeAxisLimits - Impossible\n");
6028 return kFALSE;
6029 }
6030#endif
6031
6032
6034
6035 //std::cout << "New re-computed axis : [ " << xmin << " , " << xmax << " ] width = " << width << " nbins " << destAxis.GetNbins() << std::endl;
6036
6037 return kTRUE;
6038}
6039
6040////////////////////////////////////////////////////////////////////////////////
6041/// Add all histograms in the collection to this histogram.
6042/// This function computes the min/max for the x axis,
6043/// compute a new number of bins, if necessary,
6044/// add bin contents, errors and statistics.
6045/// If all histograms have bin labels, bins with identical labels
6046/// will be merged, no matter what their order is.
6047/// If overflows are present and limits are different the function will fail.
6048/// The function returns the total number of entries in the result histogram
6049/// if the merge is successful, -1 otherwise.
6050///
6051/// Possible option:
6052/// -NOL : the merger will ignore the labels and merge the histograms bin by bin using bin center values to match bins
6053/// -NOCHECK: the histogram will not perform a check for duplicate labels in case of axes with labels. The check
6054/// (enabled by default) slows down the merging
6055///
6056/// IMPORTANT remark. The axis x may have different number
6057/// of bins and different limits, BUT the largest bin width must be
6058/// a multiple of the smallest bin width and the upper limit must also
6059/// be a multiple of the bin width.
6060/// Example:
6061///
6062/// ~~~ {.cpp}
6063/// void atest() {
6064/// TH1F *h1 = new TH1F("h1","h1",110,-110,0);
6065/// TH1F *h2 = new TH1F("h2","h2",220,0,110);
6066/// TH1F *h3 = new TH1F("h3","h3",330,-55,55);
6067/// TRandom r;
6068/// for (Int_t i=0;i<10000;i++) {
6069/// h1->Fill(r.Gaus(-55,10));
6070/// h2->Fill(r.Gaus(55,10));
6071/// h3->Fill(r.Gaus(0,10));
6072/// }
6073///
6074/// TList *list = new TList;
6075/// list->Add(h1);
6076/// list->Add(h2);
6077/// list->Add(h3);
6078/// TH1F *h = (TH1F*)h1->Clone("h");
6079/// h->Reset();
6080/// h->Merge(list);
6081/// h->Draw();
6082/// }
6083/// ~~~
6084
6086{
6087 if (!li) return 0;
6088 if (li->IsEmpty()) return (Long64_t) GetEntries();
6089
6090 // use TH1Merger class
6091 TH1Merger merger(*this,*li,opt);
6092 Bool_t ret = merger();
6093
6094 return (ret) ? GetEntries() : -1;
6095}
6096
6097
6098////////////////////////////////////////////////////////////////////////////////
6099/// Performs the operation:
6100///
6101/// `this = this*c1*f1`
6102///
6103/// If errors are defined (see TH1::Sumw2), errors are also recalculated.
6104///
6105/// Only bins inside the function range are recomputed.
6106/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
6107/// you should call Sumw2 before making this operation.
6108/// This is particularly important if you fit the histogram after TH1::Multiply
6109///
6110/// The function return kFALSE if the Multiply operation failed
6111
6113{
6114 if (!f1) {
6115 Error("Multiply","Attempt to multiply by a non-existing function");
6116 return kFALSE;
6117 }
6118
6119 // delete buffer if it is there since it will become invalid
6120 if (fBuffer) BufferEmpty(1);
6121
6122 Int_t nx = GetNbinsX() + 2; // normal bins + uf / of (cells)
6123 Int_t ny = GetNbinsY() + 2;
6124 Int_t nz = GetNbinsZ() + 2;
6125 if (fDimension < 2) ny = 1;
6126 if (fDimension < 3) nz = 1;
6127
6128 // reset min-maximum
6129 SetMinimum();
6130 SetMaximum();
6131
6132 // - Loop on bins (including underflows/overflows)
6133 Double_t xx[3];
6134 Double_t *params = nullptr;
6135 f1->InitArgs(xx,params);
6136
6137 for (Int_t binz = 0; binz < nz; ++binz) {
6138 xx[2] = fZaxis.GetBinCenter(binz);
6139 for (Int_t biny = 0; biny < ny; ++biny) {
6140 xx[1] = fYaxis.GetBinCenter(biny);
6141 for (Int_t binx = 0; binx < nx; ++binx) {
6142 xx[0] = fXaxis.GetBinCenter(binx);
6143 if (!f1->IsInside(xx)) continue;
6145 Int_t bin = binx + nx * (biny + ny *binz);
6146 Double_t cu = c1*f1->EvalPar(xx);
6147 if (TF1::RejectedPoint()) continue;
6149 if (fSumw2.fN) {
6150 fSumw2.fArray[bin] = cu * cu * GetBinErrorSqUnchecked(bin);
6151 }
6152 }
6153 }
6154 }
6155 ResetStats();
6156 return kTRUE;
6157}
6158
6159////////////////////////////////////////////////////////////////////////////////
6160/// Multiply this histogram by h1.
6161///
6162/// `this = this*h1`
6163///
6164/// If errors of this are available (TH1::Sumw2), errors are recalculated.
6165/// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
6166/// if not already set.
6167///
6168/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
6169/// you should call Sumw2 before making this operation.
6170/// This is particularly important if you fit the histogram after TH1::Multiply
6171///
6172/// The function return kFALSE if the Multiply operation failed
6173
6174Bool_t TH1::Multiply(const TH1 *h1)
6175{
6176 if (!h1) {
6177 Error("Multiply","Attempt to multiply by a non-existing histogram");
6178 return kFALSE;
6179 }
6180
6181 // delete buffer if it is there since it will become invalid
6182 if (fBuffer) BufferEmpty(1);
6183
6184 if (LoggedInconsistency("Multiply", this, h1) >= kDifferentNumberOfBins) {
6185 return false;
6186 }
6187
6188 // Create Sumw2 if h1 has Sumw2 set
6189 if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
6190
6191 // - Reset min- maximum
6192 SetMinimum();
6193 SetMaximum();
6194
6195 // - Loop on bins (including underflows/overflows)
6196 for (Int_t i = 0; i < fNcells; ++i) {
6199 UpdateBinContent(i, c0 * c1);
6200 if (fSumw2.fN) {
6202 }
6203 }
6204 ResetStats();
6205 return kTRUE;
6206}
6207
6208////////////////////////////////////////////////////////////////////////////////
6209/// Replace contents of this histogram by multiplication of h1 by h2.
6210///
6211/// `this = (c1*h1)*(c2*h2)`
6212///
6213/// If errors of this are available (TH1::Sumw2), errors are recalculated.
6214/// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
6215/// if not already set.
6216///
6217/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
6218/// you should call Sumw2 before making this operation.
6219/// This is particularly important if you fit the histogram after TH1::Multiply
6220///
6221/// The function return kFALSE if the Multiply operation failed
6222
6224{
6225 TString opt = option;
6226 opt.ToLower();
6227 // Bool_t binomial = kFALSE;
6228 // if (opt.Contains("b")) binomial = kTRUE;
6229 if (!h1 || !h2) {
6230 Error("Multiply","Attempt to multiply by a non-existing histogram");
6231 return kFALSE;
6232 }
6233
6234 // delete buffer if it is there since it will become invalid
6235 if (fBuffer) BufferEmpty(1);
6236
6237 if (LoggedInconsistency("Multiply", this, h1) >= kDifferentNumberOfBins ||
6238 LoggedInconsistency("Multiply", h1, h2) >= kDifferentNumberOfBins) {
6239 return false;
6240 }
6241
6242 // Create Sumw2 if h1 or h2 have Sumw2 set
6243 if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
6244
6245 // - Reset min - maximum
6246 SetMinimum();
6247 SetMaximum();
6248
6249 // - Loop on bins (including underflows/overflows)
6250 Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
6251 for (Int_t i = 0; i < fNcells; ++i) {
6253 Double_t b2 = h2->RetrieveBinContent(i);
6254 UpdateBinContent(i, c1 * b1 * c2 * b2);
6255 if (fSumw2.fN) {
6256 fSumw2.fArray[i] = c1sq * c2sq * (h1->GetBinErrorSqUnchecked(i) * b2 * b2 + h2->GetBinErrorSqUnchecked(i) * b1 * b1);
6257 }
6258 }
6259 ResetStats();
6260 return kTRUE;
6261}
6262
6263////////////////////////////////////////////////////////////////////////////////
6264/// @brief Normalize a histogram to its integral or to its maximum.
6265/// @note Works for TH1, TH2, TH3, ...
6266/// @param option: normalization strategy ("", "max" or "sum")
6267/// - "": Scale to `1/(sum*bin_width)`.
6268/// - max: Scale to `1/GetMaximum()`
6269/// - sum: Scale to `1/sum`.
6270///
6271/// In case the norm is zero, it raises an error.
6272/// @sa https://root-forum.cern.ch/t/different-ways-of-normalizing-histograms/15582/
6273
6275{
6276 TString opt = option;
6277 opt.ToLower();
6278 if (!opt.IsNull() && (opt != "max") && (opt != "sum")) {
6279 Error("Normalize", "Unrecognized option %s", option);
6280 return;
6281 }
6282
6283 const Double_t norm = (opt == "max") ? GetMaximum() : Integral(opt.IsNull() ? "width" : "");
6284
6285 if (norm == 0) {
6286 Error("Normalize", "Attempt to normalize histogram with zero integral");
6287 } else {
6288 Scale(1.0 / norm, "");
6289 // An alternative could have been to call Integral("") and Scale(1/norm, "width"), but this
6290 // will lead to a different value of GetEntries.
6291 // Instead, doing simultaneously Integral("width") and Scale(1/norm, "width") leads to an error since you are
6292 // dividing twice by bin width.
6293 }
6294}
6295
6296////////////////////////////////////////////////////////////////////////////////
6297/// Control routine to paint any kind of histograms.
6298///
6299/// This function is automatically called by TCanvas::Update.
6300/// (see TH1::Draw for the list of options)
6301
6303{
6305
6306 if (fPainter) {
6307 if (option && strlen(option) > 0)
6309 else
6311 }
6312}
6313
6314////////////////////////////////////////////////////////////////////////////////
6315/// Rebin this histogram
6316///
6317/// #### case 1 xbins=0
6318///
6319/// If newname is blank (default), the current histogram is modified and
6320/// a pointer to it is returned.
6321///
6322/// If newname is not blank, the current histogram is not modified, and a
6323/// new histogram is returned which is a Clone of the current histogram
6324/// with its name set to newname.
6325///
6326/// The parameter ngroup indicates how many bins of this have to be merged
6327/// into one bin of the result.
6328///
6329/// If the original histogram has errors stored (via Sumw2), the resulting
6330/// histograms has new errors correctly calculated.
6331///
6332/// examples: if h1 is an existing TH1F histogram with 100 bins
6333///
6334/// ~~~ {.cpp}
6335/// h1->Rebin(); //merges two bins in one in h1: previous contents of h1 are lost
6336/// h1->Rebin(5); //merges five bins in one in h1
6337/// TH1F *hnew = dynamic_cast<TH1F*>(h1->Rebin(5,"hnew")); // creates a new histogram hnew
6338/// // merging 5 bins of h1 in one bin
6339/// ~~~
6340///
6341/// NOTE: If ngroup is not an exact divider of the number of bins,
6342/// the top limit of the rebinned histogram is reduced
6343/// to the upper edge of the last bin that can make a complete
6344/// group. The remaining bins are added to the overflow bin.
6345/// Statistics will be recomputed from the new bin contents.
6346///
6347/// #### case 2 xbins!=0
6348///
6349/// A new histogram is created (you should specify newname).
6350/// The parameter ngroup is the number of variable size bins in the created histogram.
6351/// The array xbins must contain ngroup+1 elements that represent the low-edges
6352/// of the bins.
6353/// If the original histogram has errors stored (via Sumw2), the resulting
6354/// histograms has new errors correctly calculated.
6355///
6356/// NOTE: The bin edges specified in xbins should correspond to bin edges
6357/// in the original histogram. If a bin edge in the new histogram is
6358/// in the middle of a bin in the original histogram, all entries in
6359/// the split bin in the original histogram will be transferred to the
6360/// lower of the two possible bins in the new histogram. This is
6361/// probably not what you want. A warning message is emitted in this
6362/// case
6363///
6364/// examples: if h1 is an existing TH1F histogram with 100 bins
6365///
6366/// ~~~ {.cpp}
6367/// Double_t xbins[25] = {...} array of low-edges (xbins[25] is the upper edge of last bin
6368/// h1->Rebin(24,"hnew",xbins); //creates a new variable bin size histogram hnew
6369/// ~~~
6370
6371TH1 *TH1::Rebin(Int_t ngroup, const char*newname, const Double_t *xbins)
6372{
6373 Int_t nbins = fXaxis.GetNbins();
6376 if ((ngroup <= 0) || (ngroup > nbins)) {
6377 Error("Rebin", "Illegal value of ngroup=%d",ngroup);
6378 return nullptr;
6379 }
6380
6381 if (fDimension > 1 || InheritsFrom(TProfile::Class())) {
6382 Error("Rebin", "Operation valid on 1-D histograms only");
6383 return nullptr;
6384 }
6385 if (!newname && xbins) {
6386 Error("Rebin","if xbins is specified, newname must be given");
6387 return nullptr;
6388 }
6389
6390 Int_t newbins = nbins/ngroup;
6391 if (!xbins) {
6392 Int_t nbg = nbins/ngroup;
6393 if (nbg*ngroup != nbins) {
6394 Warning("Rebin", "ngroup=%d is not an exact divider of nbins=%d.",ngroup,nbins);
6395 }
6396 }
6397 else {
6398 // in the case that xbins is given (rebinning in variable bins), ngroup is
6399 // the new number of bins and number of grouped bins is not constant.
6400 // when looping for setting the contents for the new histogram we
6401 // need to loop on all bins of original histogram. Then set ngroup=nbins
6402 newbins = ngroup;
6403 ngroup = nbins;
6404 }
6405
6406 // Save old bin contents into a new array
6407 Double_t entries = fEntries;
6408 Double_t *oldBins = new Double_t[nbins+2];
6409 Int_t bin, i;
6410 for (bin=0;bin<nbins+2;bin++) oldBins[bin] = RetrieveBinContent(bin);
6411 Double_t *oldErrors = nullptr;
6412 if (fSumw2.fN != 0) {
6413 oldErrors = new Double_t[nbins+2];
6414 for (bin=0;bin<nbins+2;bin++) oldErrors[bin] = GetBinError(bin);
6415 }
6416 // rebin will not include underflow/overflow if new axis range is larger than old axis range
6417 if (xbins) {
6418 if (xbins[0] < fXaxis.GetXmin() && oldBins[0] != 0 )
6419 Warning("Rebin","underflow entries will not be used when rebinning");
6420 if (xbins[newbins] > fXaxis.GetXmax() && oldBins[nbins+1] != 0 )
6421 Warning("Rebin","overflow entries will not be used when rebinning");
6422 }
6423
6424
6425 // create a clone of the old histogram if newname is specified
6426 TH1 *hnew = this;
6427 if ((newname && strlen(newname) > 0) || xbins) {
6428 hnew = (TH1*)Clone(newname);
6429 }
6430
6431 //reset can extend bit to avoid an axis extension in SetBinContent
6432 UInt_t oldExtendBitMask = hnew->SetCanExtend(kNoAxis);
6433
6434 // save original statistics
6435 Double_t stat[kNstat];
6436 GetStats(stat);
6437 bool resetStat = false;
6438 // change axis specs and rebuild bin contents array::RebinAx
6439 if(!xbins && (newbins*ngroup != nbins)) {
6441 resetStat = true; //stats must be reset because top bins will be moved to overflow bin
6442 }
6443 // save the TAttAxis members (reset by SetBins)
6455
6456 if(!xbins && (fXaxis.GetXbins()->GetSize() > 0)){ // variable bin sizes
6457 Double_t *bins = new Double_t[newbins+1];
6458 for(i = 0; i <= newbins; ++i) bins[i] = fXaxis.GetBinLowEdge(1+i*ngroup);
6459 hnew->SetBins(newbins,bins); //this also changes errors array (if any)
6460 delete [] bins;
6461 } else if (xbins) {
6462 hnew->SetBins(newbins,xbins);
6463 } else {
6464 hnew->SetBins(newbins,xmin,xmax);
6465 }
6466
6467 // Restore axis attributes
6479
6480 // copy merged bin contents (ignore under/overflows)
6481 // Start merging only once the new lowest edge is reached
6482 Int_t startbin = 1;
6483 const Double_t newxmin = hnew->GetXaxis()->GetBinLowEdge(1);
6484 while( fXaxis.GetBinCenter(startbin) < newxmin && startbin <= nbins ) {
6485 startbin++;
6486 }
6489 for (bin = 1;bin<=newbins;bin++) {
6490 binContent = 0;
6491 binError = 0;
6492 Int_t imax = ngroup;
6493 Double_t xbinmax = hnew->GetXaxis()->GetBinUpEdge(bin);
6494 // check bin edges for the cases when we provide an array of bins
6495 // be careful in case bins can have zero width
6497 hnew->GetXaxis()->GetBinLowEdge(bin),
6498 TMath::Max(1.E-8 * fXaxis.GetBinWidth(oldbin), 1.E-16 )) )
6499 {
6500 Warning("Rebin","Bin edge %d of rebinned histogram does not match any bin edges of the old histogram. Result can be inconsistent",bin);
6501 }
6502 for (i=0;i<ngroup;i++) {
6503 if( (oldbin+i > nbins) ||
6504 ( hnew != this && (fXaxis.GetBinCenter(oldbin+i) > xbinmax)) ) {
6505 imax = i;
6506 break;
6507 }
6510 }
6511 hnew->SetBinContent(bin,binContent);
6512 if (oldErrors) hnew->SetBinError(bin,TMath::Sqrt(binError));
6513 oldbin += imax;
6514 }
6515
6516 // sum underflow and overflow contents until startbin
6517 binContent = 0;
6518 binError = 0;
6519 for (i = 0; i < startbin; ++i) {
6520 binContent += oldBins[i];
6521 if (oldErrors) binError += oldErrors[i]*oldErrors[i];
6522 }
6523 hnew->SetBinContent(0,binContent);
6524 if (oldErrors) hnew->SetBinError(0,TMath::Sqrt(binError));
6525 // sum overflow
6526 binContent = 0;
6527 binError = 0;
6528 for (i = oldbin; i <= nbins+1; ++i) {
6529 binContent += oldBins[i];
6530 if (oldErrors) binError += oldErrors[i]*oldErrors[i];
6531 }
6532 hnew->SetBinContent(newbins+1,binContent);
6533 if (oldErrors) hnew->SetBinError(newbins+1,TMath::Sqrt(binError));
6534
6535 hnew->SetCanExtend(oldExtendBitMask); // restore previous state
6536
6537 // restore statistics and entries modified by SetBinContent
6538 hnew->SetEntries(entries);
6539 if (!resetStat) hnew->PutStats(stat);
6540 delete [] oldBins;
6541 if (oldErrors) delete [] oldErrors;
6542 return hnew;
6543}
6544
6545////////////////////////////////////////////////////////////////////////////////
6546/// finds new limits for the axis so that *point* is within the range and
6547/// the limits are compatible with the previous ones (see TH1::Merge).
6548/// new limits are put into *newMin* and *newMax* variables.
6549/// axis - axis whose limits are to be recomputed
6550/// point - point that should fit within the new axis limits
6551/// newMin - new minimum will be stored here
6552/// newMax - new maximum will be stored here.
6553/// false if failed (e.g. if the initial axis limits are wrong
6554/// or the new range is more than \f$ 2^{64} \f$ times the old one).
6555
6557{
6558 Double_t xmin = axis->GetXmin();
6559 Double_t xmax = axis->GetXmax();
6560 if (xmin >= xmax) return kFALSE;
6562
6563 //recompute new axis limits by doubling the current range
6564 Int_t ntimes = 0;
6565 while (point < xmin) {
6566 if (ntimes++ > 64)
6567 return kFALSE;
6568 xmin = xmin - range;
6569 range *= 2;
6570 }
6571 while (point >= xmax) {
6572 if (ntimes++ > 64)
6573 return kFALSE;
6574 xmax = xmax + range;
6575 range *= 2;
6576 }
6577 newMin = xmin;
6578 newMax = xmax;
6579 // Info("FindNewAxisLimits", "OldAxis: (%lf, %lf), new: (%lf, %lf), point: %lf",
6580 // axis->GetXmin(), axis->GetXmax(), xmin, xmax, point);
6581
6582 return kTRUE;
6583}
6584
6585////////////////////////////////////////////////////////////////////////////////
6586/// Histogram is resized along axis such that x is in the axis range.
6587/// The new axis limits are recomputed by doubling iteratively
6588/// the current axis range until the specified value x is within the limits.
6589/// The algorithm makes a copy of the histogram, then loops on all bins
6590/// of the old histogram to fill the extended histogram.
6591/// Takes into account errors (Sumw2) if any.
6592/// The algorithm works for 1-d, 2-D and 3-D histograms.
6593/// The axis must be extendable before invoking this function.
6594/// Ex:
6595///
6596/// ~~~ {.cpp}
6597/// h->GetXaxis()->SetCanExtend(kTRUE);
6598/// ~~~
6599
6600void TH1::ExtendAxis(Double_t x, TAxis *axis)
6601{
6602 if (!axis->CanExtend()) return;
6603 if (TMath::IsNaN(x)) { // x may be a NaN
6605 return;
6606 }
6607
6608 if (axis->GetXmin() >= axis->GetXmax()) return;
6609 if (axis->GetNbins() <= 0) return;
6610
6612 if (!FindNewAxisLimits(axis, x, xmin, xmax))
6613 return;
6614
6615 //save a copy of this histogram
6616 TH1 *hold = (TH1*)IsA()->New();
6617 hold->SetDirectory(nullptr);
6618 Copy(*hold);
6619 //set new axis limits
6620 axis->SetLimits(xmin,xmax);
6621
6622
6623 //now loop on all bins and refill
6625
6626 Reset("ICE"); //reset only Integral, contents and Errors
6627
6628 int iaxis = 0;
6629 if (axis == &fXaxis) iaxis = 1;
6630 if (axis == &fYaxis) iaxis = 2;
6631 if (axis == &fZaxis) iaxis = 3;
6632 bool firstw = kTRUE;
6633 Int_t binx,biny, binz = 0;
6634 Int_t ix = 0,iy = 0,iz = 0;
6635 Double_t bx,by,bz;
6636 Int_t ncells = hold->GetNcells();
6637 for (Int_t bin = 0; bin < ncells; ++bin) {
6638 hold->GetBinXYZ(bin,binx,biny,binz);
6639 bx = hold->GetXaxis()->GetBinCenter(binx);
6640 ix = fXaxis.FindFixBin(bx);
6641 if (fDimension > 1) {
6642 by = hold->GetYaxis()->GetBinCenter(biny);
6643 iy = fYaxis.FindFixBin(by);
6644 if (fDimension > 2) {
6645 bz = hold->GetZaxis()->GetBinCenter(binz);
6646 iz = fZaxis.FindFixBin(bz);
6647 }
6648 }
6649 // exclude underflow/overflow
6650 double content = hold->RetrieveBinContent(bin);
6651 if (content == 0) continue;
6652 if (IsBinUnderflow(bin,iaxis) || IsBinOverflow(bin,iaxis) ) {
6653 if (firstw) {
6654 Warning("ExtendAxis","Histogram %s has underflow or overflow in the axis that is extendable"
6655 " their content will be lost",GetName() );
6656 firstw= kFALSE;
6657 }
6658 continue;
6659 }
6660 Int_t ibin= GetBin(ix,iy,iz);
6662 if (errors) {
6663 fSumw2.fArray[ibin] += hold->GetBinErrorSqUnchecked(bin);
6664 }
6665 }
6666 delete hold;
6667}
6668
6669////////////////////////////////////////////////////////////////////////////////
6670/// Recursively remove object from the list of functions
6671
6673{
6674 // Rely on TROOT::RecursiveRemove to take the readlock.
6675
6676 if (fFunctions) {
6678 }
6679}
6680
6681////////////////////////////////////////////////////////////////////////////////
6682/// Multiply this histogram by a constant c1.
6683///
6684/// `this = c1*this`
6685///
6686/// Note that both contents and errors (if any) are scaled.
6687/// This function uses the services of TH1::Add
6688///
6689/// IMPORTANT NOTE: Sumw2() is called automatically when scaling.
6690/// If you are not interested in the histogram statistics you can call
6691/// Sumw2(kFALSE) or use the option "nosw2"
6692///
6693/// One can scale a histogram such that the bins integral is equal to
6694/// the normalization parameter via TH1::Scale(Double_t norm), where norm
6695/// is the desired normalization divided by the integral of the histogram.
6696///
6697/// If option contains "width" the bin contents and errors are divided
6698/// by the bin width.
6699
6701{
6702
6703 TString opt = option; opt.ToLower();
6704 // store bin errors when scaling since cannot anymore be computed as sqrt(N)
6705 if (!opt.Contains("nosw2") && GetSumw2N() == 0) Sumw2();
6706 if (opt.Contains("width")) Add(this, this, c1, -1);
6707 else {
6708 if (fBuffer) BufferEmpty(1);
6709 for(Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, c1 * RetrieveBinContent(i));
6710 if (fSumw2.fN) for(Int_t i = 0; i < fNcells; ++i) fSumw2.fArray[i] *= (c1 * c1); // update errors
6711 // update global histograms statistics
6712 Double_t s[kNstat] = {0};
6713 GetStats(s);
6714 for (Int_t i=0 ; i < kNstat; i++) {
6715 if (i == 1) s[i] = c1*c1*s[i];
6716 else s[i] = c1*s[i];
6717 }
6718 PutStats(s);
6719 SetMinimum(); SetMaximum(); // minimum and maximum value will be recalculated the next time
6720 }
6721
6722 // if contours set, must also scale contours
6724 if (ncontours == 0) return;
6726 for (Int_t i = 0; i < ncontours; ++i) levels[i] *= c1;
6727}
6728
6729////////////////////////////////////////////////////////////////////////////////
6730/// Returns true if all axes are extendable.
6731
6733{
6735 if (GetDimension() > 1) canExtend &= fYaxis.CanExtend();
6736 if (GetDimension() > 2) canExtend &= fZaxis.CanExtend();
6737
6738 return canExtend;
6739}
6740
6741////////////////////////////////////////////////////////////////////////////////
6742/// Make the histogram axes extendable / not extendable according to the bit mask
6743/// returns the previous bit mask specifying which axes are extendable
6744
6746{
6748
6752
6753 if (GetDimension() > 1) {
6757 }
6758
6759 if (GetDimension() > 2) {
6763 }
6764
6765 return oldExtendBitMask;
6766}
6767
6768///////////////////////////////////////////////////////////////////////////////
6769/// Internal function used in TH1::Fill to see which axis is full alphanumeric,
6770/// i.e. can be extended and is alphanumeric
6772{
6776 bitMask |= kYaxis;
6778 bitMask |= kZaxis;
6779
6780 return bitMask;
6781}
6782
6783////////////////////////////////////////////////////////////////////////////////
6784/// Static function to set the default buffer size for automatic histograms.
6785/// When a histogram is created with one of its axis lower limit greater
6786/// or equal to its upper limit, the function SetBuffer is automatically
6787/// called with the default buffer size.
6788
6790{
6791 fgBufferSize = bufsize > 0 ? bufsize : 0;
6792}
6793
6794////////////////////////////////////////////////////////////////////////////////
6795/// When this static function is called with `sumw2=kTRUE`, all new
6796/// histograms will automatically activate the storage
6797/// of the sum of squares of errors, ie TH1::Sumw2 is automatically called.
6798
6800{
6802}
6803
6804////////////////////////////////////////////////////////////////////////////////
6805/// Change/set the title.
6806///
6807/// If title is in the form `stringt;stringx;stringy;stringz;stringc`
6808/// the histogram title is set to `stringt`, the x axis title to `stringx`,
6809/// the y axis title to `stringy`, the z axis title to `stringz`, and the c
6810/// axis title for the palette is ignored at this stage.
6811/// Note that you can use e.g. `stringt;stringx` if you only want to specify
6812/// title and x axis title.
6813///
6814/// To insert the character `;` in one of the titles, one should use `#;`
6815/// or `#semicolon`.
6816
6817void TH1::SetTitle(const char *title)
6818{
6819 fTitle = title;
6820 fTitle.ReplaceAll("#;",2,"#semicolon",10);
6821
6822 // Decode fTitle. It may contain X, Y and Z titles
6824 Int_t isc = str1.Index(";");
6825 Int_t lns = str1.Length();
6826
6827 if (isc >=0 ) {
6828 fTitle = str1(0,isc);
6829 str1 = str1(isc+1, lns);
6830 isc = str1.Index(";");
6831 if (isc >=0 ) {
6832 str2 = str1(0,isc);
6833 str2.ReplaceAll("#semicolon",10,";",1);
6834 fXaxis.SetTitle(str2.Data());
6835 lns = str1.Length();
6836 str1 = str1(isc+1, lns);
6837 isc = str1.Index(";");
6838 if (isc >=0 ) {
6839 str2 = str1(0,isc);
6840 str2.ReplaceAll("#semicolon",10,";",1);
6841 fYaxis.SetTitle(str2.Data());
6842 lns = str1.Length();
6843 str1 = str1(isc+1, lns);
6844 isc = str1.Index(";");
6845 if (isc >=0 ) {
6846 str2 = str1(0,isc);
6847 str2.ReplaceAll("#semicolon",10,";",1);
6848 fZaxis.SetTitle(str2.Data());
6849 } else {
6850 str1.ReplaceAll("#semicolon",10,";",1);
6851 fZaxis.SetTitle(str1.Data());
6852 }
6853 } else {
6854 str1.ReplaceAll("#semicolon",10,";",1);
6855 fYaxis.SetTitle(str1.Data());
6856 }
6857 } else {
6858 str1.ReplaceAll("#semicolon",10,";",1);
6859 fXaxis.SetTitle(str1.Data());
6860 }
6861 }
6862
6863 fTitle.ReplaceAll("#semicolon",10,";",1);
6864
6865 if (gPad && TestBit(kMustCleanup)) gPad->Modified();
6866}
6867
6868////////////////////////////////////////////////////////////////////////////////
6869/// Smooth array xx, translation of Hbook routine `hsmoof.F`.
6870/// Based on algorithm 353QH twice presented by J. Friedman
6871/// in [Proc. of the 1974 CERN School of Computing, Norway, 11-24 August, 1974](https://cds.cern.ch/record/186223).
6872/// See also Section 4.2 in [J. Friedman, Data Analysis Techniques for High Energy Physics](https://www.slac.stanford.edu/pubs/slacreports/reports16/slac-r-176.pdf).
6873
6875{
6876 if (nn < 3 ) {
6877 ::Error("SmoothArray","Need at least 3 points for smoothing: n = %d",nn);
6878 return;
6879 }
6880
6881 Int_t ii;
6882 std::array<double, 3> hh{};
6883
6884 std::vector<double> yy(nn);
6885 std::vector<double> zz(nn);
6886 std::vector<double> rr(nn);
6887
6888 for (Int_t pass=0;pass<ntimes;pass++) {
6889 // first copy original data into temp array
6890 std::copy(xx, xx+nn, zz.begin() );
6891
6892 for (int noent = 0; noent < 2; ++noent) { // run algorithm two times
6893
6894 // do 353 i.e. running median 3, 5, and 3 in a single loop
6895 for (int kk = 0; kk < 3; kk++) {
6896 std::copy(zz.begin(), zz.end(), yy.begin());
6897 int medianType = (kk != 1) ? 3 : 5;
6898 int ifirst = (kk != 1 ) ? 1 : 2;
6899 int ilast = (kk != 1 ) ? nn-1 : nn -2;
6900 //nn2 = nn - ik - 1;
6901 // do all elements beside the first and last point for median 3
6902 // and first two and last 2 for median 5
6903 for ( ii = ifirst; ii < ilast; ii++) {
6904 zz[ii] = TMath::Median(medianType, yy.data() + ii - ifirst);
6905 }
6906
6907 if (kk == 0) { // first median 3
6908 // first point
6909 hh[0] = zz[1];
6910 hh[1] = zz[0];
6911 hh[2] = 3*zz[1] - 2*zz[2];
6912 zz[0] = TMath::Median(3, hh.data());
6913 // last point
6914 hh[0] = zz[nn - 2];
6915 hh[1] = zz[nn - 1];
6916 hh[2] = 3*zz[nn - 2] - 2*zz[nn - 3];
6917 zz[nn - 1] = TMath::Median(3, hh.data());
6918 }
6919
6920 if (kk == 1) { // median 5
6921 // second point with window length 3
6922 zz[1] = TMath::Median(3, yy.data());
6923 // second-to-last point with window length 3
6924 zz[nn - 2] = TMath::Median(3, yy.data() + nn - 3);
6925 }
6926
6927 // In the third iteration (kk == 2), the first and last point stay
6928 // the same (see paper linked in the documentation).
6929 }
6930
6931 std::copy ( zz.begin(), zz.end(), yy.begin() );
6932
6933 // quadratic interpolation for flat segments
6934 for (ii = 2; ii < (nn - 2); ii++) {
6935 if (zz[ii - 1] != zz[ii]) continue;
6936 if (zz[ii] != zz[ii + 1]) continue;
6937 const double tmp0 = zz[ii - 2] - zz[ii];
6938 const double tmp1 = zz[ii + 2] - zz[ii];
6939 if (tmp0 * tmp1 <= 0) continue;
6940 int jk = 1;
6941 if ( std::abs(tmp1) > std::abs(tmp0) ) jk = -1;
6942 yy[ii] = -0.5*zz[ii - 2*jk] + zz[ii]/0.75 + zz[ii + 2*jk] /6.;
6943 yy[ii + jk] = 0.5*(zz[ii + 2*jk] - zz[ii - 2*jk]) + zz[ii];
6944 }
6945
6946 // running means
6947 //std::copy(zz.begin(), zz.end(), yy.begin());
6948 for (ii = 1; ii < nn - 1; ii++) {
6949 zz[ii] = 0.25*yy[ii - 1] + 0.5*yy[ii] + 0.25*yy[ii + 1];
6950 }
6951 zz[0] = yy[0];
6952 zz[nn - 1] = yy[nn - 1];
6953
6954 if (noent == 0) {
6955
6956 // save computed values
6957 std::copy(zz.begin(), zz.end(), rr.begin());
6958
6959 // COMPUTE residuals
6960 for (ii = 0; ii < nn; ii++) {
6961 zz[ii] = xx[ii] - zz[ii];
6962 }
6963 }
6964
6965 } // end loop on noent
6966
6967
6968 double xmin = TMath::MinElement(nn,xx);
6969 for (ii = 0; ii < nn; ii++) {
6970 if (xmin < 0) xx[ii] = rr[ii] + zz[ii];
6971 // make smoothing defined positive - not better using 0 ?
6972 else xx[ii] = std::max((rr[ii] + zz[ii]),0.0 );
6973 }
6974 }
6975}
6976
6977////////////////////////////////////////////////////////////////////////////////
6978/// Smooth bin contents of this histogram.
6979/// if option contains "R" smoothing is applied only to the bins
6980/// defined in the X axis range (default is to smooth all bins)
6981/// Bin contents are replaced by their smooth values.
6982/// Errors (if any) are not modified.
6983/// the smoothing procedure is repeated ntimes (default=1)
6984
6986{
6987 if (fDimension != 1) {
6988 Error("Smooth","Smooth only supported for 1-d histograms");
6989 return;
6990 }
6991 Int_t nbins = fXaxis.GetNbins();
6992 if (nbins < 3) {
6993 Error("Smooth","Smooth only supported for histograms with >= 3 bins. Nbins = %d",nbins);
6994 return;
6995 }
6996
6997 // delete buffer if it is there since it will become invalid
6998 if (fBuffer) BufferEmpty(1);
6999
7000 Int_t firstbin = 1, lastbin = nbins;
7001 TString opt = option;
7002 opt.ToLower();
7003 if (opt.Contains("r")) {
7006 }
7007 nbins = lastbin - firstbin + 1;
7008 Double_t *xx = new Double_t[nbins];
7010 Int_t i;
7011 for (i=0;i<nbins;i++) {
7013 }
7014
7015 TH1::SmoothArray(nbins,xx,ntimes);
7016
7017 for (i=0;i<nbins;i++) {
7019 }
7020 fEntries = nent;
7021 delete [] xx;
7022
7023 if (gPad) gPad->Modified();
7024}
7025
7026////////////////////////////////////////////////////////////////////////////////
7027/// if flag=kTRUE, underflows and overflows are used by the Fill functions
7028/// in the computation of statistics (mean value, StdDev).
7029/// By default, underflows or overflows are not used.
7030
7032{
7034}
7035
7036////////////////////////////////////////////////////////////////////////////////
7037/// Stream a class object.
7038
7039void TH1::Streamer(TBuffer &b)
7040{
7041 if (b.IsReading()) {
7042 UInt_t R__s, R__c;
7043 Version_t R__v = b.ReadVersion(&R__s, &R__c);
7044 if (fDirectory) fDirectory->Remove(this);
7045 fDirectory = nullptr;
7046 if (R__v > 2) {
7047 b.ReadClassBuffer(TH1::Class(), this, R__v, R__s, R__c);
7048
7050 fXaxis.SetParent(this);
7051 fYaxis.SetParent(this);
7052 fZaxis.SetParent(this);
7053 TIter next(fFunctions);
7054 TObject *obj;
7055 while ((obj=next())) {
7056 if (obj->InheritsFrom(TF1::Class())) ((TF1*)obj)->SetParent(this);
7057 }
7058 return;
7059 }
7060 //process old versions before automatic schema evolution
7065 b >> fNcells;
7066 fXaxis.Streamer(b);
7067 fYaxis.Streamer(b);
7068 fZaxis.Streamer(b);
7069 fXaxis.SetParent(this);
7070 fYaxis.SetParent(this);
7071 fZaxis.SetParent(this);
7072 b >> fBarOffset;
7073 b >> fBarWidth;
7074 b >> fEntries;
7075 b >> fTsumw;
7076 b >> fTsumw2;
7077 b >> fTsumwx;
7078 b >> fTsumwx2;
7079 if (R__v < 2) {
7081 Float_t *contour=nullptr;
7082 b >> maximum; fMaximum = maximum;
7083 b >> minimum; fMinimum = minimum;
7084 b >> norm; fNormFactor = norm;
7085 Int_t n = b.ReadArray(contour);
7086 fContour.Set(n);
7087 for (Int_t i=0;i<n;i++) fContour.fArray[i] = contour[i];
7088 delete [] contour;
7089 } else {
7090 b >> fMaximum;
7091 b >> fMinimum;
7092 b >> fNormFactor;
7094 }
7095 fSumw2.Streamer(b);
7097 fFunctions->Delete();
7099 b.CheckByteCount(R__s, R__c, TH1::IsA());
7100
7101 } else {
7102 b.WriteClassBuffer(TH1::Class(),this);
7103 }
7104}
7105
7106////////////////////////////////////////////////////////////////////////////////
7107/// Print some global quantities for this histogram.
7108/// \param[in] option
7109/// - "base" is given, number of bins and ranges are also printed
7110/// - "range" is given, bin contents and errors are also printed
7111/// for all bins in the current range (default 1-->nbins)
7112/// - "all" is given, bin contents and errors are also printed
7113/// for all bins including under and overflows.
7114
7115void TH1::Print(Option_t *option) const
7116{
7117 if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
7118 printf( "TH1.Print Name = %s, Entries= %d, Total sum= %g\n",GetName(),Int_t(fEntries),GetSumOfWeights());
7119 TString opt = option;
7120 opt.ToLower();
7121 Int_t all;
7122 if (opt.Contains("all")) all = 0;
7123 else if (opt.Contains("range")) all = 1;
7124 else if (opt.Contains("base")) all = 2;
7125 else return;
7126
7127 Int_t bin, binx, biny, binz;
7129 if (all == 0) {
7130 lastx = fXaxis.GetNbins()+1;
7131 if (fDimension > 1) lasty = fYaxis.GetNbins()+1;
7132 if (fDimension > 2) lastz = fZaxis.GetNbins()+1;
7133 } else {
7135 if (fDimension > 1) {firsty = fYaxis.GetFirst(); lasty = fYaxis.GetLast();}
7136 if (fDimension > 2) {firstz = fZaxis.GetFirst(); lastz = fZaxis.GetLast();}
7137 }
7138
7139 if (all== 2) {
7140 printf(" Title = %s\n", GetTitle());
7141 printf(" NbinsX= %d, xmin= %g, xmax=%g", fXaxis.GetNbins(), fXaxis.GetXmin(), fXaxis.GetXmax());
7142 if( fDimension > 1) printf(", NbinsY= %d, ymin= %g, ymax=%g", fYaxis.GetNbins(), fYaxis.GetXmin(), fYaxis.GetXmax());
7143 if( fDimension > 2) printf(", NbinsZ= %d, zmin= %g, zmax=%g", fZaxis.GetNbins(), fZaxis.GetXmin(), fZaxis.GetXmax());
7144 printf("\n");
7145 return;
7146 }
7147
7148 Double_t w,e;
7149 Double_t x,y,z;
7150 if (fDimension == 1) {
7151 for (binx=firstx;binx<=lastx;binx++) {
7154 e = GetBinError(binx);
7155 if(fSumw2.fN) printf(" fSumw[%d]=%g, x=%g, error=%g\n",binx,w,x,e);
7156 else printf(" fSumw[%d]=%g, x=%g\n",binx,w,x);
7157 }
7158 }
7159 if (fDimension == 2) {
7160 for (biny=firsty;biny<=lasty;biny++) {
7162 for (binx=firstx;binx<=lastx;binx++) {
7163 bin = GetBin(binx,biny);
7165 w = RetrieveBinContent(bin);
7166 e = GetBinError(bin);
7167 if(fSumw2.fN) printf(" fSumw[%d][%d]=%g, x=%g, y=%g, error=%g\n",binx,biny,w,x,y,e);
7168 else printf(" fSumw[%d][%d]=%g, x=%g, y=%g\n",binx,biny,w,x,y);
7169 }
7170 }
7171 }
7172 if (fDimension == 3) {
7173 for (binz=firstz;binz<=lastz;binz++) {
7175 for (biny=firsty;biny<=lasty;biny++) {
7177 for (binx=firstx;binx<=lastx;binx++) {
7178 bin = GetBin(binx,biny,binz);
7180 w = RetrieveBinContent(bin);
7181 e = GetBinError(bin);
7182 if(fSumw2.fN) printf(" fSumw[%d][%d][%d]=%g, x=%g, y=%g, z=%g, error=%g\n",binx,biny,binz,w,x,y,z,e);
7183 else printf(" fSumw[%d][%d][%d]=%g, x=%g, y=%g, z=%g\n",binx,biny,binz,w,x,y,z);
7184 }
7185 }
7186 }
7187 }
7188}
7189
7190////////////////////////////////////////////////////////////////////////////////
7191/// Using the current bin info, recompute the arrays for contents and errors
7192
7193void TH1::Rebuild(Option_t *)
7194{
7195 SetBinsLength();
7196 if (fSumw2.fN) {
7198 }
7199}
7200
7201////////////////////////////////////////////////////////////////////////////////
7202/// Reset this histogram: contents, errors, etc.
7203/// \param[in] option
7204/// - if "ICE" is specified, resets only Integral, Contents and Errors.
7205/// - if "ICES" is specified, resets only Integral, Contents, Errors and Statistics
7206/// This option is used
7207/// - if "M" is specified, resets also Minimum and Maximum
7208
7210{
7211 // The option "ICE" is used when extending the histogram (in ExtendAxis, LabelInflate, etc..)
7212 // The option "ICES is used in combination with the buffer (see BufferEmpty and BufferFill)
7213
7214 TString opt = option;
7215 opt.ToUpper();
7216 fSumw2.Reset();
7217 if (fIntegral) {
7218 delete [] fIntegral;
7219 fIntegral = nullptr;
7220 }
7221
7222 if (opt.Contains("M")) {
7223 SetMinimum();
7224 SetMaximum();
7225 }
7226
7227 if (opt.Contains("ICE") && !opt.Contains("S")) return;
7228
7229 // Setting fBuffer[0] = 0 is like resetting the buffer but not deleting it
7230 // But what is the sense of calling BufferEmpty() ? For making the axes ?
7231 // BufferEmpty will update contents that later will be
7232 // reset in calling TH1D::Reset. For this we need to reset the stats afterwards
7233 // It may be needed for computing the axis limits....
7234 if (fBuffer) {BufferEmpty(); fBuffer[0] = 0;}
7235
7236 // need to reset also the statistics
7237 // (needs to be done after calling BufferEmpty() )
7238 fTsumw = 0;
7239 fTsumw2 = 0;
7240 fTsumwx = 0;
7241 fTsumwx2 = 0;
7242 fEntries = 0;
7243
7244 if (opt == "ICES") return;
7245
7246
7247 TObject *stats = fFunctions->FindObject("stats");
7248 fFunctions->Remove(stats);
7249 //special logic to support the case where the same object is
7250 //added multiple times in fFunctions.
7251 //This case happens when the same object is added with different
7252 //drawing modes
7253 TObject *obj;
7254 while ((obj = fFunctions->First())) {
7255 while(fFunctions->Remove(obj)) { }
7256 delete obj;
7257 }
7258 if(stats) fFunctions->Add(stats);
7259 fContour.Set(0);
7260}
7261
7262////////////////////////////////////////////////////////////////////////////////
7263/// Save the histogram as .csv, .tsv or .txt. In case of any other extension, fall
7264/// back to TObject::SaveAs, which saves as a .C macro (but with the file name
7265/// extension specified by the user)
7266///
7267/// The Under/Overflow bins are also exported (as first and last lines)
7268/// The fist 2 columns are the lower and upper edges of the bins
7269/// Column 3 contains the bin contents
7270/// The last column contains the error in y. If errors are not present, the column
7271/// is left empty
7272///
7273/// The result can be immediately imported into Excel, gnuplot, Python or whatever,
7274/// without the needing to install pyroot, etc.
7275///
7276/// \param filename the name of the file where to store the histogram
7277/// \param option some tuning options
7278///
7279/// The file extension defines the delimiter used:
7280/// - `.csv` : comma
7281/// - `.tsv` : tab
7282/// - `.txt` : space
7283///
7284/// If option = "title" a title line is generated. If the y-axis has a title,
7285/// this title is displayed as column 3 name, otherwise, it shows "BinContent"
7286
7287void TH1::SaveAs(const char *filename, Option_t *option) const
7288{
7289 char del = '\0';
7290 TString ext = "";
7292 TString opt = option;
7293
7294 if (filename) {
7295 if (fname.EndsWith(".csv")) {
7296 del = ',';
7297 ext = "csv";
7298 } else if (fname.EndsWith(".tsv")) {
7299 del = '\t';
7300 ext = "tsv";
7301 } else if (fname.EndsWith(".txt")) {
7302 del = ' ';
7303 ext = "txt";
7304 }
7305 }
7306 if (!del) {
7308 return;
7309 }
7310 std::ofstream out;
7311 out.open(filename, std::ios::out);
7312 if (!out.good()) {
7313 Error("SaveAs", "cannot open file: %s", filename);
7314 return;
7315 }
7316 if (opt.Contains("title")) {
7317 if (std::strcmp(GetYaxis()->GetTitle(), "") == 0) {
7318 out << "# " << "BinLowEdge" << del << "BinUpEdge" << del
7319 << "BinContent"
7320 << del << "ey" << std::endl;
7321 } else {
7322 out << "# " << "BinLowEdge" << del << "BinUpEdge" << del << GetYaxis()->GetTitle() << del << "ey" << std::endl;
7323 }
7324 }
7325 if (fSumw2.fN) {
7326 for (Int_t i = 0; i < fNcells; ++i) { // loop on cells (bins including underflow / overflow)
7327 out << GetXaxis()->GetBinLowEdge(i) << del << GetXaxis()->GetBinUpEdge(i) << del << GetBinContent(i) << del
7328 << GetBinError(i) << std::endl;
7329 }
7330 } else {
7331 for (Int_t i = 0; i < fNcells; ++i) { // loop on cells (bins including underflow / overflow)
7332 out << GetXaxis()->GetBinLowEdge(i) << del << GetXaxis()->GetBinUpEdge(i) << del << GetBinContent(i) << del
7333 << std::endl;
7334 }
7335 }
7336 out.close();
7337 Info("SaveAs", "%s file: %s has been generated", ext.Data(), filename);
7338}
7339
7340////////////////////////////////////////////////////////////////////////////////
7341/// Provide variable name for histogram for saving as primitive
7342/// Histogram pointer has by default the histogram name with an incremental suffix.
7343/// If the histogram belongs to a graph or a stack the suffix is not added because
7344/// the graph and stack objects are not aware of this new name. Same thing if
7345/// the histogram is drawn with the option COLZ because the TPaletteAxis drawn
7346/// when this option is selected, does not know this new name either.
7347
7349{
7350 thread_local Int_t storeNumber = 0;
7351
7352 TString opt = option;
7353 opt.ToLower();
7354 TString histName = GetName();
7355 // for TProfile and TH2Poly also fDirectory should be tested
7356 if (!histName.Contains("Graph") && !histName.Contains("_stack_") && !opt.Contains("colz") &&
7357 (!testfdir || !fDirectory)) {
7358 storeNumber++;
7359 histName += "__";
7360 histName += storeNumber;
7361 }
7362 if (histName.IsNull())
7363 histName = "unnamed";
7364 return gInterpreter->MapCppName(histName);
7365}
7366
7367////////////////////////////////////////////////////////////////////////////////
7368/// Save primitive as a C++ statement(s) on output stream out
7369
7370void TH1::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/)
7371{
7372 // empty the buffer before if it exists
7373 if (fBuffer)
7374 BufferEmpty();
7375
7377
7380 SetName(hname);
7381
7382 out <<" \n";
7383
7384 // Check if the histogram has equidistant X bins or not. If not, we
7385 // create an array holding the bins.
7386 if (GetXaxis()->GetXbins()->fN && GetXaxis()->GetXbins()->fArray)
7387 sxaxis = SavePrimitiveVector(out, hname + "_x", GetXaxis()->GetXbins()->fN, GetXaxis()->GetXbins()->fArray);
7388 // If the histogram is 2 or 3 dimensional, check if the histogram
7389 // has equidistant Y bins or not. If not, we create an array
7390 // holding the bins.
7391 if (fDimension > 1 && GetYaxis()->GetXbins()->fN && GetYaxis()->GetXbins()->fArray)
7392 syaxis = SavePrimitiveVector(out, hname + "_y", GetYaxis()->GetXbins()->fN, GetYaxis()->GetXbins()->fArray);
7393 // IF the histogram is 3 dimensional, check if the histogram
7394 // has equidistant Z bins or not. If not, we create an array
7395 // holding the bins.
7396 if (fDimension > 2 && GetZaxis()->GetXbins()->fN && GetZaxis()->GetXbins()->fArray)
7397 szaxis = SavePrimitiveVector(out, hname + "_z", GetZaxis()->GetXbins()->fN, GetZaxis()->GetXbins()->fArray);
7398
7399 const auto old_precision{out.precision()};
7400 constexpr auto max_precision{std::numeric_limits<double>::digits10 + 1};
7401 out << std::setprecision(max_precision);
7402
7403 out << " " << ClassName() << " *" << hname << " = new " << ClassName() << "(\"" << TString(savedName).ReplaceSpecialCppChars() << "\", \""
7404 << TString(GetTitle()).ReplaceSpecialCppChars() << "\", " << GetXaxis()->GetNbins();
7405 if (!sxaxis.IsNull())
7406 out << ", " << sxaxis << ".data()";
7407 else
7408 out << ", " << GetXaxis()->GetXmin() << ", " << GetXaxis()->GetXmax();
7409 if (fDimension > 1) {
7410 out << ", " << GetYaxis()->GetNbins();
7411 if (!syaxis.IsNull())
7412 out << ", " << syaxis << ".data()";
7413 else
7414 out << ", " << GetYaxis()->GetXmin() << ", " << GetYaxis()->GetXmax();
7415 }
7416 if (fDimension > 2) {
7417 out << ", " << GetZaxis()->GetNbins();
7418 if (!szaxis.IsNull())
7419 out << ", " << szaxis << ".data()";
7420 else
7421 out << ", " << GetZaxis()->GetXmin() << ", " << GetZaxis()->GetXmax();
7422 }
7423 out << ");\n";
7424
7426 Int_t numbins = 0, numerrors = 0;
7427
7428 std::vector<Double_t> content(fNcells), errors(save_errors ? fNcells : 0);
7429 for (Int_t bin = 0; bin < fNcells; bin++) {
7430 content[bin] = RetrieveBinContent(bin);
7431 if (content[bin])
7432 numbins++;
7433 if (save_errors) {
7434 errors[bin] = GetBinError(bin);
7435 if (errors[bin])
7436 numerrors++;
7437 }
7438 }
7439
7440 if ((numbins < 100) && (numerrors < 100)) {
7441 // in case of few non-empty bins store them as before
7442 for (Int_t bin = 0; bin < fNcells; bin++) {
7443 if (content[bin])
7444 out << " " << hname << "->SetBinContent(" << bin << "," << content[bin] << ");\n";
7445 }
7446 if (save_errors)
7447 for (Int_t bin = 0; bin < fNcells; bin++) {
7448 if (errors[bin])
7449 out << " " << hname << "->SetBinError(" << bin << "," << errors[bin] << ");\n";
7450 }
7451 } else {
7452 if (numbins > 0) {
7454 out << " for (Int_t bin = 0; bin < " << fNcells << "; bin++)\n";
7455 out << " if (" << vectname << "[bin])\n";
7456 out << " " << hname << "->SetBinContent(bin, " << vectname << "[bin]);\n";
7457 }
7458 if (numerrors > 0) {
7460 out << " for (Int_t bin = 0; bin < " << fNcells << "; bin++)\n";
7461 out << " if (" << vectname << "[bin])\n";
7462 out << " " << hname << "->SetBinError(bin, " << vectname << "[bin]);\n";
7463 }
7464 }
7465
7467 out << std::setprecision(old_precision);
7468 SetName(savedName.Data());
7469}
7470
7471////////////////////////////////////////////////////////////////////////////////
7472/// Helper function for the SavePrimitive functions from TH1
7473/// or classes derived from TH1, eg TProfile, TProfile2D.
7474
7475void TH1::SavePrimitiveHelp(std::ostream &out, const char *hname, Option_t *option /*= ""*/)
7476{
7477 if (TMath::Abs(GetBarOffset()) > 1e-5)
7478 out << " " << hname << "->SetBarOffset(" << GetBarOffset() << ");\n";
7479 if (TMath::Abs(GetBarWidth() - 1) > 1e-5)
7480 out << " " << hname << "->SetBarWidth(" << GetBarWidth() << ");\n";
7481 if (fMinimum != -1111)
7482 out << " " << hname << "->SetMinimum(" << fMinimum << ");\n";
7483 if (fMaximum != -1111)
7484 out << " " << hname << "->SetMaximum(" << fMaximum << ");\n";
7485 if (fNormFactor != 0)
7486 out << " " << hname << "->SetNormFactor(" << fNormFactor << ");\n";
7487 if (fEntries != 0)
7488 out << " " << hname << "->SetEntries(" << fEntries << ");\n";
7489 if (!fDirectory)
7490 out << " " << hname << "->SetDirectory(nullptr);\n";
7491 if (TestBit(kNoStats))
7492 out << " " << hname << "->SetStats(0);\n";
7493 if (fOption.Length() != 0)
7494 out << " " << hname << "->SetOption(\n" << TString(fOption).ReplaceSpecialCppChars() << "\");\n";
7495
7496 // save contour levels
7498 if (ncontours > 0) {
7500 if (TestBit(kUserContour)) {
7501 std::vector<Double_t> levels(ncontours);
7502 for (Int_t bin = 0; bin < ncontours; bin++)
7503 levels[bin] = GetContourLevel(bin);
7505 }
7506 out << " " << hname << "->SetContour(" << ncontours;
7507 if (!vectname.IsNull())
7508 out << ", " << vectname << ".data()";
7509 out << ");\n";
7510 }
7511
7513
7514 // save attributes
7515 SaveFillAttributes(out, hname, -1, -1);
7516 SaveLineAttributes(out, hname, 1, 1, 1);
7517 SaveMarkerAttributes(out, hname, 1, 1, 1);
7518 fXaxis.SaveAttributes(out, hname, "->GetXaxis()");
7519 fYaxis.SaveAttributes(out, hname, "->GetYaxis()");
7520 fZaxis.SaveAttributes(out, hname, "->GetZaxis()");
7521
7523}
7524
7525////////////////////////////////////////////////////////////////////////////////
7526/// Save list of functions
7527/// Also can be used by TGraph classes
7528
7529void TH1::SavePrimitiveFunctions(std::ostream &out, const char *varname, TList *lst)
7530{
7531 thread_local Int_t funcNumber = 0;
7532
7533 TObjLink *lnk = lst ? lst->FirstLink() : nullptr;
7534 while (lnk) {
7535 auto obj = lnk->GetObject();
7536 obj->SavePrimitive(out, TString::Format("nodraw #%d\n", ++funcNumber).Data());
7537 TString objvarname = obj->GetName();
7539 if (obj->InheritsFrom(TF1::Class())) {
7541 objvarname = gInterpreter->MapCppName(objvarname);
7542 out << " " << objvarname << "->SetParent(" << varname << ");\n";
7543 } else if (obj->InheritsFrom("TPaveStats")) {
7544 objvarname = "ptstats";
7545 withopt = kFALSE; // pave stats preserve own draw options
7546 out << " " << objvarname << "->SetParent(" << varname << ");\n";
7547 } else if (obj->InheritsFrom("TPolyMarker")) {
7548 objvarname = "pmarker";
7549 }
7550
7551 out << " " << varname << "->GetListOfFunctions()->Add(" << objvarname;
7552 if (withopt)
7553 out << ",\"" << TString(lnk->GetOption()).ReplaceSpecialCppChars() << "\"";
7554 out << ");\n";
7555
7556 lnk = lnk->Next();
7557 }
7558}
7559
7560////////////////////////////////////////////////////////////////////////////////
7601 }
7602}
7603
7604////////////////////////////////////////////////////////////////////////////////
7605/// For axis = 1,2 or 3 returns the mean value of the histogram along
7606/// X,Y or Z axis.
7607///
7608/// For axis = 11, 12, 13 returns the standard error of the mean value
7609/// of the histogram along X, Y or Z axis
7610///
7611/// Note that the mean value/StdDev is computed using the bins in the currently
7612/// defined range (see TAxis::SetRange). By default the range includes
7613/// all bins from 1 to nbins included, excluding underflows and overflows.
7614/// To force the underflows and overflows in the computation, one must
7615/// call the static function TH1::StatOverflows(kTRUE) before filling
7616/// the histogram.
7617///
7618/// IMPORTANT NOTE: The returned value depends on how the histogram statistics
7619/// are calculated. By default, if no range has been set, the returned mean is
7620/// the (unbinned) one calculated at fill time. If a range has been set, however,
7621/// the mean is calculated using the bins in range, as described above; THIS
7622/// IS TRUE EVEN IF THE RANGE INCLUDES ALL BINS--use TAxis::SetRange(0, 0) to unset
7623/// the range. To ensure that the returned mean (and all other statistics) is
7624/// always that of the binned data stored in the histogram, call TH1::ResetStats.
7625/// See TH1::GetStats.
7626///
7627/// Return mean value of this histogram along the X axis.
7628
7629Double_t TH1::GetMean(Int_t axis) const
7630{
7631 if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
7632 Double_t stats[kNstat];
7633 for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
7634 GetStats(stats);
7635 if (stats[0] == 0) return 0;
7636 if (axis<4){
7637 Int_t ax[3] = {2,4,7};
7638 return stats[ax[axis-1]]/stats[0];
7639 } else {
7640 // mean error = StdDev / sqrt( Neff )
7641 Double_t stddev = GetStdDev(axis-10);
7643 return ( neff > 0 ? stddev/TMath::Sqrt(neff) : 0. );
7644 }
7645}
7646
7647////////////////////////////////////////////////////////////////////////////////
7648/// Return standard error of mean of this histogram along the X axis.
7649///
7650/// Note that the mean value/StdDev is computed using the bins in the currently
7651/// defined range (see TAxis::SetRange). By default the range includes
7652/// all bins from 1 to nbins included, excluding underflows and overflows.
7653/// To force the underflows and overflows in the computation, one must
7654/// call the static function TH1::StatOverflows(kTRUE) before filling
7655/// the histogram.
7656///
7657/// Also note, that although the definition of standard error doesn't include the
7658/// assumption of normality, many uses of this feature implicitly assume it.
7659///
7660/// IMPORTANT NOTE: The returned value depends on how the histogram statistics
7661/// are calculated. By default, if no range has been set, the returned value is
7662/// the (unbinned) one calculated at fill time. If a range has been set, however,
7663/// the value is calculated using the bins in range, as described above; THIS
7664/// IS TRUE EVEN IF THE RANGE INCLUDES ALL BINS--use TAxis::SetRange(0, 0) to unset
7665/// the range. To ensure that the returned value (and all other statistics) is
7666/// always that of the binned data stored in the histogram, call TH1::ResetStats.
7667/// See TH1::GetStats.
7668
7670{
7671 return GetMean(axis+10);
7672}
7673
7674////////////////////////////////////////////////////////////////////////////////
7675/// Returns the Standard Deviation (Sigma).
7676/// The Sigma estimate is computed as
7677/// \f[
7678/// \sqrt{\frac{1}{N}(\sum(x_i-x_{mean})^2)}
7679/// \f]
7680/// For axis = 1,2 or 3 returns the Sigma value of the histogram along
7681/// X, Y or Z axis
7682/// For axis = 11, 12 or 13 returns the error of StdDev estimation along
7683/// X, Y or Z axis for Normal distribution
7684///
7685/// Note that the mean value/sigma is computed using the bins in the currently
7686/// defined range (see TAxis::SetRange). By default the range includes
7687/// all bins from 1 to nbins included, excluding underflows and overflows.
7688/// To force the underflows and overflows in the computation, one must
7689/// call the static function TH1::StatOverflows(kTRUE) before filling
7690/// the histogram.
7691///
7692/// IMPORTANT NOTE: The returned value depends on how the histogram statistics
7693/// are calculated. By default, if no range has been set, the returned standard
7694/// deviation is the (unbinned) one calculated at fill time. If a range has been
7695/// set, however, the standard deviation is calculated using the bins in range,
7696/// as described above; THIS IS TRUE EVEN IF THE RANGE INCLUDES ALL BINS--use
7697/// TAxis::SetRange(0, 0) to unset the range. To ensure that the returned standard
7698/// deviation (and all other statistics) is always that of the binned data stored
7699/// in the histogram, call TH1::ResetStats. See TH1::GetStats.
7700
7701Double_t TH1::GetStdDev(Int_t axis) const
7702{
7703 if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
7704
7705 Double_t x, stddev2, stats[kNstat];
7706 for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
7707 GetStats(stats);
7708 if (stats[0] == 0) return 0;
7709 Int_t ax[3] = {2,4,7};
7710 Int_t axm = ax[axis%10 - 1];
7711 x = stats[axm]/stats[0];
7712 // for negative stddev (e.g. when having negative weights) - return stdev=0
7713 stddev2 = TMath::Max( stats[axm+1]/stats[0] -x*x, 0.0 );
7714 if (axis<10)
7715 return TMath::Sqrt(stddev2);
7716 else {
7717 // The right formula for StdDev error depends on 4th momentum (see Kendall-Stuart Vol 1 pag 243)
7718 // formula valid for only gaussian distribution ( 4-th momentum = 3 * sigma^4 )
7720 return ( neff > 0 ? TMath::Sqrt(stddev2/(2*neff) ) : 0. );
7721 }
7722}
7723
7724////////////////////////////////////////////////////////////////////////////////
7725/// Return error of standard deviation estimation for Normal distribution
7726///
7727/// Note that the mean value/StdDev is computed using the bins in the currently
7728/// defined range (see TAxis::SetRange). By default the range includes
7729/// all bins from 1 to nbins included, excluding underflows and overflows.
7730/// To force the underflows and overflows in the computation, one must
7731/// call the static function TH1::StatOverflows(kTRUE) before filling
7732/// the histogram.
7733///
7734/// Value returned is standard deviation of sample standard deviation.
7735/// Note that it is an approximated value which is valid only in the case that the
7736/// original data distribution is Normal. The correct one would require
7737/// the 4-th momentum value, which cannot be accurately estimated from a histogram since
7738/// the x-information for all entries is not kept.
7739///
7740/// IMPORTANT NOTE: The returned value depends on how the histogram statistics
7741/// are calculated. By default, if no range has been set, the returned value is
7742/// the (unbinned) one calculated at fill time. If a range has been set, however,
7743/// the value is calculated using the bins in range, as described above; THIS
7744/// IS TRUE EVEN IF THE RANGE INCLUDES ALL BINS--use TAxis::SetRange(0, 0) to unset
7745/// the range. To ensure that the returned value (and all other statistics) is
7746/// always that of the binned data stored in the histogram, call TH1::ResetStats.
7747/// See TH1::GetStats.
7748
7750{
7751 return GetStdDev(axis+10);
7752}
7753
7754////////////////////////////////////////////////////////////////////////////////
7755/// - For axis = 1, 2 or 3 returns skewness of the histogram along x, y or z axis.
7756/// - For axis = 11, 12 or 13 returns the approximate standard error of skewness
7757/// of the histogram along x, y or z axis
7758///
7759///Note, that since third and fourth moment are not calculated
7760///at the fill time, skewness and its standard error are computed bin by bin
7761///
7762/// IMPORTANT NOTE: The returned value depends on how the histogram statistics
7763/// are calculated. See TH1::GetMean and TH1::GetStdDev.
7764
7766{
7767
7768 if (axis > 0 && axis <= 3){
7769
7770 Double_t mean = GetMean(axis);
7771 Double_t stddev = GetStdDev(axis);
7773
7780 // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7783 if (firstBinX == 1) firstBinX = 0;
7784 if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7785 }
7787 if (firstBinY == 1) firstBinY = 0;
7788 if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
7789 }
7791 if (firstBinZ == 1) firstBinZ = 0;
7792 if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
7793 }
7794 }
7795
7796 Double_t x = 0;
7797 Double_t sum=0;
7798 Double_t np=0;
7799 for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
7800 for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
7801 for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
7802 if (axis==1 ) x = fXaxis.GetBinCenter(binx);
7803 else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
7804 else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
7806 np+=w;
7807 sum+=w*(x-mean)*(x-mean)*(x-mean);
7808 }
7809 }
7810 }
7811 sum/=np*stddev3;
7812 return sum;
7813 }
7814 else if (axis > 10 && axis <= 13) {
7815 //compute standard error of skewness
7816 // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
7818 return ( neff > 0 ? TMath::Sqrt(6./neff ) : 0. );
7819 }
7820 else {
7821 Error("GetSkewness", "illegal value of parameter");
7822 return 0;
7823 }
7824}
7825
7826////////////////////////////////////////////////////////////////////////////////
7827/// - For axis =1, 2 or 3 returns kurtosis of the histogram along x, y or z axis.
7828/// Kurtosis(gaussian(0, 1)) = 0.
7829/// - For axis =11, 12 or 13 returns the approximate standard error of kurtosis
7830/// of the histogram along x, y or z axis
7831////
7832/// Note, that since third and fourth moment are not calculated
7833/// at the fill time, kurtosis and its standard error are computed bin by bin
7834///
7835/// IMPORTANT NOTE: The returned value depends on how the histogram statistics
7836/// are calculated. See TH1::GetMean and TH1::GetStdDev.
7837
7839{
7840 if (axis > 0 && axis <= 3){
7841
7842 Double_t mean = GetMean(axis);
7843 Double_t stddev = GetStdDev(axis);
7845
7852 // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7855 if (firstBinX == 1) firstBinX = 0;
7856 if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7857 }
7859 if (firstBinY == 1) firstBinY = 0;
7860 if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
7861 }
7863 if (firstBinZ == 1) firstBinZ = 0;
7864 if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
7865 }
7866 }
7867
7868 Double_t x = 0;
7869 Double_t sum=0;
7870 Double_t np=0;
7871 for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
7872 for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
7873 for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
7874 if (axis==1 ) x = fXaxis.GetBinCenter(binx);
7875 else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
7876 else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
7878 np+=w;
7879 sum+=w*(x-mean)*(x-mean)*(x-mean)*(x-mean);
7880 }
7881 }
7882 }
7883 sum/=(np*stddev4);
7884 return sum-3;
7885
7886 } else if (axis > 10 && axis <= 13) {
7887 //compute standard error of skewness
7888 // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
7890 return ( neff > 0 ? TMath::Sqrt(24./neff ) : 0. );
7891 }
7892 else {
7893 Error("GetKurtosis", "illegal value of parameter");
7894 return 0;
7895 }
7896}
7897
7898////////////////////////////////////////////////////////////////////////////////
7899/// fill the array stats from the contents of this histogram
7900/// The array stats must be correctly dimensioned in the calling program.
7901///
7902/// ~~~ {.cpp}
7903/// stats[0] = sumw
7904/// stats[1] = sumw2
7905/// stats[2] = sumwx
7906/// stats[3] = sumwx2
7907/// ~~~
7908///
7909/// If no axis-subrange is specified (via TAxis::SetRange), the array stats
7910/// is simply a copy of the statistics quantities computed at filling time.
7911/// If a sub-range is specified, the function recomputes these quantities
7912/// from the bin contents in the current axis range.
7913///
7914/// IMPORTANT NOTE: This means that the returned statistics are context-dependent.
7915/// If TAxis::kAxisRange, the returned statistics are dependent on the binning;
7916/// otherwise, they are a copy of the histogram statistics computed at fill time,
7917/// which are unbinned by default (calling TH1::ResetStats forces them to use
7918/// binned statistics). You can reset TAxis::kAxisRange using TAxis::SetRange(0, 0).
7919///
7920/// Note that the mean value/StdDev is computed using the bins in the currently
7921/// defined range (see TAxis::SetRange). By default the range includes
7922/// all bins from 1 to nbins included, excluding underflows and overflows.
7923/// To force the underflows and overflows in the computation, one must
7924/// call the static function TH1::StatOverflows(kTRUE) before filling
7925/// the histogram.
7926
7927void TH1::GetStats(Double_t *stats) const
7928{
7929 if (fBuffer) ((TH1*)this)->BufferEmpty();
7930
7931 // Loop on bins (possibly including underflows/overflows)
7932 Int_t bin, binx;
7933 Double_t w,err;
7934 Double_t x;
7935 // identify the case of labels with extension of axis range
7936 // in this case the statistics in x does not make any sense
7937 Bool_t labelHist = ((const_cast<TAxis&>(fXaxis)).GetLabels() && fXaxis.CanExtend() );
7938 // fTsumw == 0 && fEntries > 0 is a special case when uses SetBinContent or calls ResetStats before
7939 if ( (fTsumw == 0 && fEntries > 0) || fXaxis.TestBit(TAxis::kAxisRange) ) {
7940 for (bin=0;bin<4;bin++) stats[bin] = 0;
7941
7944 // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7946 if (firstBinX == 1) firstBinX = 0;
7947 if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7948 }
7949 for (binx = firstBinX; binx <= lastBinX; binx++) {
7951 //w = TMath::Abs(RetrieveBinContent(binx));
7952 // not sure what to do here if w < 0
7954 err = TMath::Abs(GetBinError(binx));
7955 stats[0] += w;
7956 stats[1] += err*err;
7957 // statistics in x makes sense only for not labels histograms
7958 if (!labelHist) {
7959 stats[2] += w*x;
7960 stats[3] += w*x*x;
7961 }
7962 }
7963 // if (stats[0] < 0) {
7964 // // in case total is negative do something ??
7965 // stats[0] = 0;
7966 // }
7967 } else {
7968 stats[0] = fTsumw;
7969 stats[1] = fTsumw2;
7970 stats[2] = fTsumwx;
7971 stats[3] = fTsumwx2;
7972 }
7973}
7974
7975////////////////////////////////////////////////////////////////////////////////
7976/// Replace current statistics with the values in array stats
7977
7978void TH1::PutStats(Double_t *stats)
7979{
7980 fTsumw = stats[0];
7981 fTsumw2 = stats[1];
7982 fTsumwx = stats[2];
7983 fTsumwx2 = stats[3];
7984}
7985
7986////////////////////////////////////////////////////////////////////////////////
7987/// Reset the statistics including the number of entries
7988/// and replace with values calculated from bin content
7989///
7990/// The number of entries is set to the total bin content or (in case of weighted histogram)
7991/// to number of effective entries
7992///
7993/// \note By default, before calling this function, statistics are those
7994/// computed at fill time, which are unbinned. See TH1::GetStats.
7995
7996void TH1::ResetStats()
7997{
7998 Double_t stats[kNstat] = {0};
7999 fTsumw = 0;
8000 fEntries = 1; // to force re-calculation of the statistics in TH1::GetStats
8001 GetStats(stats);
8002 PutStats(stats);
8003 // histogram entries should include always underflows and overflows
8006 else {
8007 Double_t sumw2 = 0;
8008 Double_t * p_sumw2 = (fSumw2.fN > 0) ? &sumw2 : nullptr;
8010 // use effective entries for weighted histograms: (sum_w) ^2 / sum_w2
8012 }
8013}
8014
8015////////////////////////////////////////////////////////////////////////////////
8016/// Return the sum of all weights and optionally also the sum of weight squares
8017/// \param includeOverflow true to include under/overflows bins, false to exclude those.
8018/// \note Different from TH1::GetSumOfWeights, that always excludes those
8019
8021{
8022 if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
8023
8024 const Int_t start = (includeOverflow ? 0 : 1);
8025 const Int_t lastX = fXaxis.GetNbins() + (includeOverflow ? 1 : 0);
8026 const Int_t lastY = (fDimension > 1) ? (fYaxis.GetNbins() + (includeOverflow ? 1 : 0)) : start;
8027 const Int_t lastZ = (fDimension > 2) ? (fZaxis.GetNbins() + (includeOverflow ? 1 : 0)) : start;
8028 Double_t sum =0;
8029 Double_t sum2 = 0;
8030 for(auto binz = start; binz <= lastZ; binz++) {
8031 for(auto biny = start; biny <= lastY; biny++) {
8032 for(auto binx = start; binx <= lastX; binx++) {
8033 const auto bin = GetBin(binx, biny, binz);
8034 sum += RetrieveBinContent(bin);
8036 }
8037 }
8038 }
8039 if (sumWeightSquare) {
8040 if (fSumw2.fN > 0)
8042 else
8044 }
8045 return sum;
8046}
8047
8048////////////////////////////////////////////////////////////////////////////////
8049///Return integral of bin contents. Only bins in the bins range are considered.
8050///
8051/// By default the integral is computed as the sum of bin contents in the range.
8052/// if option "width" is specified, the integral is the sum of
8053/// the bin contents multiplied by the bin width in x.
8054
8056{
8058}
8059
8060////////////////////////////////////////////////////////////////////////////////
8061/// Return integral of bin contents in range [binx1,binx2].
8062///
8063/// By default the integral is computed as the sum of bin contents in the range.
8064/// if option "width" is specified, the integral is the sum of
8065/// the bin contents multiplied by the bin width in x.
8066
8068{
8069 double err = 0;
8070 return DoIntegral(binx1,binx2,0,-1,0,-1,err,option);
8071}
8072
8073////////////////////////////////////////////////////////////////////////////////
8074/// Return integral of bin contents in range [binx1,binx2] and its error.
8075///
8076/// By default the integral is computed as the sum of bin contents in the range.
8077/// if option "width" is specified, the integral is the sum of
8078/// the bin contents multiplied by the bin width in x.
8079/// the error is computed using error propagation from the bin errors assuming that
8080/// all the bins are uncorrelated
8081
8083{
8084 return DoIntegral(binx1,binx2,0,-1,0,-1,error,option,kTRUE);
8085}
8086
8087////////////////////////////////////////////////////////////////////////////////
8088/// Internal function compute integral and optionally the error between the limits
8089/// specified by the bin number values working for all histograms (1D, 2D and 3D)
8090
8092 Option_t *option, Bool_t doError) const
8093{
8094 if (fBuffer) ((TH1*)this)->BufferEmpty();
8095
8096 Int_t nx = GetNbinsX() + 2;
8097 if (binx1 < 0) binx1 = 0;
8098 if (binx2 >= nx || binx2 < binx1) binx2 = nx - 1;
8099
8100 if (GetDimension() > 1) {
8101 Int_t ny = GetNbinsY() + 2;
8102 if (biny1 < 0) biny1 = 0;
8103 if (biny2 >= ny || biny2 < biny1) biny2 = ny - 1;
8104 } else {
8105 biny1 = 0; biny2 = 0;
8106 }
8107
8108 if (GetDimension() > 2) {
8109 Int_t nz = GetNbinsZ() + 2;
8110 if (binz1 < 0) binz1 = 0;
8111 if (binz2 >= nz || binz2 < binz1) binz2 = nz - 1;
8112 } else {
8113 binz1 = 0; binz2 = 0;
8114 }
8115
8116 // - Loop on bins in specified range
8117 TString opt = option;
8118 opt.ToLower();
8120 if (opt.Contains("width")) width = kTRUE;
8121
8122
8123 Double_t dx = 1., dy = .1, dz =.1;
8124 Double_t integral = 0;
8125 Double_t igerr2 = 0;
8126 for (Int_t binx = binx1; binx <= binx2; ++binx) {
8127 if (width) dx = fXaxis.GetBinWidth(binx);
8128 for (Int_t biny = biny1; biny <= biny2; ++biny) {
8129 if (width) dy = fYaxis.GetBinWidth(biny);
8130 for (Int_t binz = binz1; binz <= binz2; ++binz) {
8131 Int_t bin = GetBin(binx, biny, binz);
8132 Double_t dv = 0.0;
8133 if (width) {
8135 dv = dx * dy * dz;
8136 integral += RetrieveBinContent(bin) * dv;
8137 } else {
8138 integral += RetrieveBinContent(bin);
8139 }
8140 if (doError) {
8141 if (width) igerr2 += GetBinErrorSqUnchecked(bin) * dv * dv;
8142 else igerr2 += GetBinErrorSqUnchecked(bin);
8143 }
8144 }
8145 }
8146 }
8147
8148 if (doError) error = TMath::Sqrt(igerr2);
8149 return integral;
8150}
8151
8152////////////////////////////////////////////////////////////////////////////////
8153/// Statistical test of compatibility in shape between
8154/// this histogram and h2, using the Anderson-Darling 2 sample test.
8155///
8156/// The AD 2 sample test formula are derived from the paper
8157/// F.W Scholz, M.A. Stephens "k-Sample Anderson-Darling Test".
8158///
8159/// The test is implemented in root in the ROOT::Math::GoFTest class
8160/// It is the same formula ( (6) in the paper), and also shown in
8161/// [this preprint](http://arxiv.org/pdf/0804.0380v1.pdf)
8162///
8163/// Binned data are considered as un-binned data
8164/// with identical observation happening in the bin center.
8165///
8166/// \param[in] h2 Pointer to 1D histogram
8167/// \param[in] option is a character string to specify options
8168/// - "D" Put out a line of "Debug" printout
8169/// - "T" Return the normalized A-D test statistic
8170///
8171/// - Note1: Underflow and overflow are not considered in the test
8172/// - Note2: The test works only for un-weighted histogram (i.e. representing counts)
8173/// - Note3: The histograms are not required to have the same X axis
8174/// - Note4: The test works only for 1-dimensional histograms
8175
8177{
8178 Double_t advalue = 0;
8180
8181 TString opt = option;
8182 opt.ToUpper();
8183 if (opt.Contains("D") ) {
8184 printf(" AndersonDarlingTest Prob = %g, AD TestStatistic = %g\n",pvalue,advalue);
8185 }
8186 if (opt.Contains("T") ) return advalue;
8187
8188 return pvalue;
8189}
8190
8191////////////////////////////////////////////////////////////////////////////////
8192/// Same function as above but returning also the test statistic value
8193
8195{
8196 if (GetDimension() != 1 || h2->GetDimension() != 1) {
8197 Error("AndersonDarlingTest","Histograms must be 1-D");
8198 return -1;
8199 }
8200
8201 // empty the buffer. Probably we could add as an unbinned test
8202 if (fBuffer) ((TH1*)this)->BufferEmpty();
8203
8204 // use the BinData class
8207
8208 ROOT::Fit::FillData(data1, this, nullptr);
8209 ROOT::Fit::FillData(data2, h2, nullptr);
8210
8211 double pvalue;
8213
8214 return pvalue;
8215}
8216
8217////////////////////////////////////////////////////////////////////////////////
8218/// Statistical test of compatibility in shape between
8219/// this histogram and h2, using Kolmogorov test.
8220/// Note that the KolmogorovTest (KS) test should in theory be used only for unbinned data
8221/// and not for binned data as in the case of the histogram (see NOTE 3 below).
8222/// So, before using this method blindly, read the NOTE 3.
8223///
8224/// Default: Ignore under- and overflow bins in comparison
8225///
8226/// \param[in] h2 histogram
8227/// \param[in] option is a character string to specify options
8228/// - "U" include Underflows in test (also for 2-dim)
8229/// - "O" include Overflows (also valid for 2-dim)
8230/// - "N" include comparison of normalizations
8231/// - "D" Put out a line of "Debug" printout
8232/// - "M" Return the Maximum Kolmogorov distance instead of prob
8233/// - "X" Run the pseudo experiments post-processor with the following procedure:
8234/// make pseudoexperiments based on random values from the parent distribution,
8235/// compare the KS distance of the pseudoexperiment to the parent
8236/// distribution, and count all the KS values above the value
8237/// obtained from the original data to Monte Carlo distribution.
8238/// The number of pseudo-experiments nEXPT is by default 1000, and
8239/// it can be changed by specifying the option as "X=number",
8240/// for example "X=10000" for 10000 toys.
8241/// The function returns the probability.
8242/// (thanks to Ben Kilminster to submit this procedure). Note that
8243/// this option "X" is much slower.
8244///
8245/// The returned function value is the probability of test
8246/// (much less than one means NOT compatible)
8247///
8248/// Code adapted by Rene Brun from original HBOOK routine HDIFF
8249///
8250/// NOTE1
8251/// A good description of the Kolmogorov test can be seen at:
8252/// http://www.itl.nist.gov/div898/handbook/eda/section3/eda35g.htm
8253///
8254/// NOTE2
8255/// see also alternative function TH1::Chi2Test
8256/// The Kolmogorov test is assumed to give better results than Chi2Test
8257/// in case of histograms with low statistics.
8258///
8259/// NOTE3 (Jan Conrad, Fred James)
8260/// "The returned value PROB is calculated such that it will be
8261/// uniformly distributed between zero and one for compatible histograms,
8262/// provided the data are not binned (or the number of bins is very large
8263/// compared with the number of events). Users who have access to unbinned
8264/// data and wish exact confidence levels should therefore not put their data
8265/// into histograms, but should call directly TMath::KolmogorovTest. On
8266/// the other hand, since TH1 is a convenient way of collecting data and
8267/// saving space, this function has been provided. However, the values of
8268/// PROB for binned data will be shifted slightly higher than expected,
8269/// depending on the effects of the binning. For example, when comparing two
8270/// uniform distributions of 500 events in 100 bins, the values of PROB,
8271/// instead of being exactly uniformly distributed between zero and one, have
8272/// a mean value of about 0.56. We can apply a useful
8273/// rule: As long as the bin width is small compared with any significant
8274/// physical effect (for example the experimental resolution) then the binning
8275/// cannot have an important effect. Therefore, we believe that for all
8276/// practical purposes, the probability value PROB is calculated correctly
8277/// provided the user is aware that:
8278///
8279/// 1. The value of PROB should not be expected to have exactly the correct
8280/// distribution for binned data.
8281/// 2. The user is responsible for seeing to it that the bin widths are
8282/// small compared with any physical phenomena of interest.
8283/// 3. The effect of binning (if any) is always to make the value of PROB
8284/// slightly too big. That is, setting an acceptance criterion of (PROB>0.05
8285/// will assure that at most 5% of truly compatible histograms are rejected,
8286/// and usually somewhat less."
8287///
8288/// Note also that for GoF test of unbinned data ROOT provides also the class
8289/// ROOT::Math::GoFTest. The class has also method for doing one sample tests
8290/// (i.e. comparing the data with a given distribution).
8291
8293{
8294 TString opt = option;
8295 opt.ToUpper();
8296
8297 Double_t prob = 0;
8298 TH1 *h1 = (TH1*)this;
8299 if (h2 == nullptr) return 0;
8300 const TAxis *axis1 = h1->GetXaxis();
8301 const TAxis *axis2 = h2->GetXaxis();
8302 Int_t ncx1 = axis1->GetNbins();
8303 Int_t ncx2 = axis2->GetNbins();
8304
8305 // Check consistency of dimensions
8306 if (h1->GetDimension() != 1 || h2->GetDimension() != 1) {
8307 Error("KolmogorovTest","Histograms must be 1-D\n");
8308 return 0;
8309 }
8310
8311 // Check consistency in number of channels
8312 if (ncx1 != ncx2) {
8313 Error("KolmogorovTest","Histograms have different number of bins, %d and %d\n",ncx1,ncx2);
8314 return 0;
8315 }
8316
8317 // empty the buffer. Probably we could add as an unbinned test
8318 if (fBuffer) ((TH1*)this)->BufferEmpty();
8319
8320 // Check consistency in bin edges
8321 for(Int_t i = 1; i <= axis1->GetNbins() + 1; ++i) {
8322 if(!TMath::AreEqualRel(axis1->GetBinLowEdge(i), axis2->GetBinLowEdge(i), 1.E-15)) {
8323 Error("KolmogorovTest","Histograms are not consistent: they have different bin edges");
8324 return 0;
8325 }
8326 }
8327
8330 Double_t sum1 = 0, sum2 = 0;
8331 Double_t ew1, ew2, w1 = 0, w2 = 0;
8332 Int_t bin;
8333 Int_t ifirst = 1;
8334 Int_t ilast = ncx1;
8335 // integral of all bins (use underflow/overflow if option)
8336 if (opt.Contains("U")) ifirst = 0;
8337 if (opt.Contains("O")) ilast = ncx1 +1;
8338 for (bin = ifirst; bin <= ilast; bin++) {
8339 sum1 += h1->RetrieveBinContent(bin);
8340 sum2 += h2->RetrieveBinContent(bin);
8341 ew1 = h1->GetBinError(bin);
8342 ew2 = h2->GetBinError(bin);
8343 w1 += ew1*ew1;
8344 w2 += ew2*ew2;
8345 }
8346 if (sum1 == 0) {
8347 Error("KolmogorovTest","Histogram1 %s integral is zero\n",h1->GetName());
8348 return 0;
8349 }
8350 if (sum2 == 0) {
8351 Error("KolmogorovTest","Histogram2 %s integral is zero\n",h2->GetName());
8352 return 0;
8353 }
8354
8355 // calculate the effective entries.
8356 // the case when errors are zero (w1 == 0 or w2 ==0) are equivalent to
8357 // compare to a function. In that case the rescaling is done only on sqrt(esum2) or sqrt(esum1)
8358 Double_t esum1 = 0, esum2 = 0;
8359 if (w1 > 0)
8360 esum1 = sum1 * sum1 / w1;
8361 else
8362 afunc1 = kTRUE; // use later for calculating z
8363
8364 if (w2 > 0)
8365 esum2 = sum2 * sum2 / w2;
8366 else
8367 afunc2 = kTRUE; // use later for calculating z
8368
8369 if (afunc2 && afunc1) {
8370 Error("KolmogorovTest","Errors are zero for both histograms\n");
8371 return 0;
8372 }
8373
8374
8375 Double_t s1 = 1/sum1;
8376 Double_t s2 = 1/sum2;
8377
8378 // Find largest difference for Kolmogorov Test
8379 Double_t dfmax =0, rsum1 = 0, rsum2 = 0;
8380
8381 for (bin=ifirst;bin<=ilast;bin++) {
8382 rsum1 += s1*h1->RetrieveBinContent(bin);
8383 rsum2 += s2*h2->RetrieveBinContent(bin);
8385 }
8386
8387 // Get Kolmogorov probability
8388 Double_t z, prb1=0, prb2=0, prb3=0;
8389
8390 // case h1 is exact (has zero errors)
8391 if (afunc1)
8392 z = dfmax*TMath::Sqrt(esum2);
8393 // case h2 has zero errors
8394 else if (afunc2)
8395 z = dfmax*TMath::Sqrt(esum1);
8396 else
8397 // for comparison between two data sets
8399
8401
8402 // option N to combine normalization makes sense if both afunc1 and afunc2 are false
8403 if (opt.Contains("N") && !(afunc1 || afunc2 ) ) {
8404 // Combine probabilities for shape and normalization,
8405 prb1 = prob;
8408 prb2 = TMath::Prob(chi2,1);
8409 // see Eadie et al., section 11.6.2
8410 if (prob > 0 && prb2 > 0) prob *= prb2*(1-TMath::Log(prob*prb2));
8411 else prob = 0;
8412 }
8413 // X option. Run Pseudo-experiments to determine NULL distribution of the
8414 // KS distance. We can find the probability from the number of pseudo-experiment that have a
8415 // KS distance larger than the one opbserved in the data.
8416 // We use the histogram with the largest statistics as a parent distribution for the NULL.
8417 // Note if one histogram has zero errors is considered as a function. In that case we use it
8418 // as parent distribution for the toys.
8419 //
8420 Int_t nEXPT = 1000;
8421 if (opt.Contains("X")) {
8422 // get number of pseudo-experiment of specified
8423 if (opt.Contains("X=")) {
8424 int numpos = opt.Index("X=") + 2; // 2 is length of X=
8425 int numlen = 0;
8426 int len = opt.Length();
8427 while( (numpos+numlen<len) && isdigit(opt[numpos+numlen]) )
8428 numlen++;
8429 TString snum = opt(numpos,numlen);
8430 int num = atoi(snum.Data());
8431 if (num <= 0)
8432 Warning("KolmogorovTest","invalid number of toys given: %d - use 1000",num);
8433 else
8434 nEXPT = num;
8435 }
8436
8438 TH1D hparent;
8439 // we cannot have afunc1 and func2 both True
8440 if (afunc1 || esum1 > esum2 ) h1->Copy(hparent);
8441 else h2->Copy(hparent);
8442
8443 // copy h1Expt from h1 and h2. It is just needed to get the correct binning
8444
8445
8446 if (hparent.GetMinimum() < 0.0) {
8447 // we need to create a new histogram
8448 // With negative bins we can't draw random samples in a meaningful way.
8449 Warning("KolmogorovTest", "Detected bins with negative weights, these have been ignored and output might be "
8450 "skewed. Reduce number of bins for histogram?");
8451 while (hparent.GetMinimum() < 0.0) {
8452 Int_t idx = hparent.GetMinimumBin();
8453 hparent.SetBinContent(idx, 0.0);
8454 }
8455 }
8456
8457 // make nEXPT experiments (this should be a parameter)
8458 prb3 = 0;
8459 TH1D h1Expt;
8460 h1->Copy(h1Expt);
8461 TH1D h2Expt;
8462 h1->Copy(h2Expt);
8463 // loop on pseudoexperients and generate the two histograms h1Expt and h2Expt according to the
8464 // parent distribution. In case the parent distribution is not an histogram but a function randomize only one
8465 // histogram
8466 for (Int_t i=0; i < nEXPT; i++) {
8467 if (!afunc1) {
8468 h1Expt.Reset();
8469 h1Expt.FillRandom(&hparent, (Int_t)esum1);
8470 }
8471 if (!afunc2) {
8472 h2Expt.Reset();
8473 h2Expt.FillRandom(&hparent, (Int_t)esum2);
8474 }
8475 // note we cannot have both afunc1 and afunc2 to be true
8476 if (afunc1)
8477 dSEXPT = hparent.KolmogorovTest(&h2Expt,"M");
8478 else if (afunc2)
8479 dSEXPT = hparent.KolmogorovTest(&h1Expt,"M");
8480 else
8481 dSEXPT = h1Expt.KolmogorovTest(&h2Expt,"M");
8482 // count number of cases toy KS distance (TS) is larger than oberved one
8483 if (dSEXPT>dfmax) prb3 += 1.0;
8484 }
8485 // compute p-value
8486 prb3 /= (Double_t)nEXPT;
8487 }
8488
8489
8490 // debug printout
8491 if (opt.Contains("D")) {
8492 printf(" Kolmo Prob h1 = %s, sum bin content =%g effective entries =%g\n",h1->GetName(),sum1,esum1);
8493 printf(" Kolmo Prob h2 = %s, sum bin content =%g effective entries =%g\n",h2->GetName(),sum2,esum2);
8494 printf(" Kolmo Prob = %g, Max Dist = %g\n",prob,dfmax);
8495 if (opt.Contains("N"))
8496 printf(" Kolmo Prob = %f for shape alone, =%f for normalisation alone\n",prb1,prb2);
8497 if (opt.Contains("X"))
8498 printf(" Kolmo Prob = %f with %d pseudo-experiments\n",prb3,nEXPT);
8499 }
8500 // This numerical error condition should never occur:
8501 if (TMath::Abs(rsum1-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h1=%s\n",h1->GetName());
8502 if (TMath::Abs(rsum2-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h2=%s\n",h2->GetName());
8503
8504 if(opt.Contains("M")) return dfmax;
8505 else if(opt.Contains("X")) return prb3;
8506 else return prob;
8507}
8508
8509////////////////////////////////////////////////////////////////////////////////
8510/// Replace bin contents by the contents of array content
8511
8512void TH1::SetContent(const Double_t *content)
8513{
8514 fEntries = fNcells;
8515 fTsumw = 0;
8516 for (Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, content[i]);
8517}
8518
8519////////////////////////////////////////////////////////////////////////////////
8520/// Return contour values into array levels if pointer levels is non zero.
8521///
8522/// The function returns the number of contour levels.
8523/// see GetContourLevel to return one contour only
8524
8526{
8528 if (levels) {
8529 if (nlevels == 0) {
8530 nlevels = 20;
8532 } else {
8534 }
8535 for (Int_t level=0; level<nlevels; level++) levels[level] = fContour.fArray[level];
8536 }
8537 return nlevels;
8538}
8539
8540////////////////////////////////////////////////////////////////////////////////
8541/// Return value of contour number level.
8542/// Use GetContour to return the array of all contour levels
8543
8545{
8546 return (level >= 0 && level < fContour.fN) ? fContour.fArray[level] : 0.0;
8547}
8548
8549////////////////////////////////////////////////////////////////////////////////
8550/// Return the value of contour number "level" in Pad coordinates.
8551/// ie: if the Pad is in log scale along Z it returns le log of the contour level
8552/// value. See GetContour to return the array of all contour levels
8553
8555{
8556 if (level <0 || level >= fContour.fN) return 0;
8557 Double_t zlevel = fContour.fArray[level];
8558
8559 // In case of user defined contours and Pad in log scale along Z,
8560 // fContour.fArray doesn't contain the log of the contour whereas it does
8561 // in case of equidistant contours.
8562 if (gPad && gPad->GetLogz() && TestBit(kUserContour)) {
8563 if (zlevel <= 0) return 0;
8565 }
8566 return zlevel;
8567}
8568
8569////////////////////////////////////////////////////////////////////////////////
8570/// Set the maximum number of entries to be kept in the buffer.
8571
8572void TH1::SetBuffer(Int_t bufsize, Option_t * /*option*/)
8573{
8574 if (fBuffer) {
8575 BufferEmpty();
8576 delete [] fBuffer;
8577 fBuffer = nullptr;
8578 }
8579 if (bufsize <= 0) {
8580 fBufferSize = 0;
8581 return;
8582 }
8583 if (bufsize < 100) bufsize = 100;
8584 fBufferSize = 1 + bufsize*(fDimension+1);
8586 memset(fBuffer, 0, sizeof(Double_t)*fBufferSize);
8587}
8588
8589////////////////////////////////////////////////////////////////////////////////
8590/// Set the number and values of contour levels.
8591///
8592/// By default the number of contour levels is set to 20. The contours values
8593/// in the array "levels" should be specified in increasing order.
8594///
8595/// if argument levels = 0 or missing, `nlevels` equidistant contours are computed
8596/// between `zmin` and `zmax - dz`, both included, with step
8597/// `dz = (zmax - zmin)/nlevels`. Note that contour lines are not centered, but
8598/// contour surfaces (when drawing with `COLZ`) will be, since contour color `i` covers
8599/// the region of values between contour line `i` and `i+1`.
8600
8602{
8603 Int_t level;
8605 if (nlevels <=0 ) {
8606 fContour.Set(0);
8607 return;
8608 }
8610
8611 // - Contour levels are specified
8612 if (levels) {
8614 for (level=0; level<nlevels; level++) fContour.fArray[level] = levels[level];
8615 } else {
8616 // - contour levels are computed automatically as equidistant contours
8617 Double_t zmin = GetMinimum();
8618 Double_t zmax = GetMaximum();
8619 if ((zmin == zmax) && (zmin != 0)) {
8620 zmax += 0.01*TMath::Abs(zmax);
8621 zmin -= 0.01*TMath::Abs(zmin);
8622 }
8623 Double_t dz = (zmax-zmin)/Double_t(nlevels);
8624 if (gPad && gPad->GetLogz()) {
8625 if (zmax <= 0) return;
8626 if (zmin <= 0) zmin = 0.001*zmax;
8627 zmin = TMath::Log10(zmin);
8628 zmax = TMath::Log10(zmax);
8629 dz = (zmax-zmin)/Double_t(nlevels);
8630 }
8631 for (level=0; level<nlevels; level++) {
8632 fContour.fArray[level] = zmin + dz*Double_t(level);
8633 }
8634 }
8635}
8636
8637////////////////////////////////////////////////////////////////////////////////
8638/// Set value for one contour level.
8639
8641{
8642 if (level < 0 || level >= fContour.fN) return;
8644 fContour.fArray[level] = value;
8645}
8646
8647////////////////////////////////////////////////////////////////////////////////
8648/// Return maximum value smaller than maxval of bins in the range,
8649/// unless the value has been overridden by TH1::SetMaximum,
8650/// in which case it returns that value. This happens, for example,
8651/// when the histogram is drawn and the y or z axis limits are changed
8652///
8653/// To get the maximum value of bins in the histogram regardless of
8654/// whether the value has been overridden (using TH1::SetMaximum), use
8655///
8656/// ~~~ {.cpp}
8657/// h->GetBinContent(h->GetMaximumBin())
8658/// ~~~
8659///
8660/// TH1::GetMaximumBin can be used to get the location of the maximum
8661/// value.
8662
8664{
8665 if (fMaximum != -1111) return fMaximum;
8666
8667 // empty the buffer
8668 if (fBuffer) ((TH1*)this)->BufferEmpty();
8669
8670 Int_t bin, binx, biny, binz;
8671 Int_t xfirst = fXaxis.GetFirst();
8672 Int_t xlast = fXaxis.GetLast();
8673 Int_t yfirst = fYaxis.GetFirst();
8674 Int_t ylast = fYaxis.GetLast();
8675 Int_t zfirst = fZaxis.GetFirst();
8676 Int_t zlast = fZaxis.GetLast();
8678 for (binz=zfirst;binz<=zlast;binz++) {
8679 for (biny=yfirst;biny<=ylast;biny++) {
8680 for (binx=xfirst;binx<=xlast;binx++) {
8681 bin = GetBin(binx,biny,binz);
8683 if (value > maximum && value < maxval) maximum = value;
8684 }
8685 }
8686 }
8687 return maximum;
8688}
8689
8690////////////////////////////////////////////////////////////////////////////////
8691/// Return location of bin with maximum value in the range.
8692///
8693/// TH1::GetMaximum can be used to get the maximum value.
8694
8696{
8699}
8700
8701////////////////////////////////////////////////////////////////////////////////
8702/// Return location of bin with maximum value in the range.
8703
8705{
8706 // empty the buffer
8707 if (fBuffer) ((TH1*)this)->BufferEmpty();
8708
8709 Int_t bin, binx, biny, binz;
8710 Int_t locm;
8711 Int_t xfirst = fXaxis.GetFirst();
8712 Int_t xlast = fXaxis.GetLast();
8713 Int_t yfirst = fYaxis.GetFirst();
8714 Int_t ylast = fYaxis.GetLast();
8715 Int_t zfirst = fZaxis.GetFirst();
8716 Int_t zlast = fZaxis.GetLast();
8718 locm = locmax = locmay = locmaz = 0;
8719 for (binz=zfirst;binz<=zlast;binz++) {
8720 for (biny=yfirst;biny<=ylast;biny++) {
8721 for (binx=xfirst;binx<=xlast;binx++) {
8722 bin = GetBin(binx,biny,binz);
8724 if (value > maximum) {
8725 maximum = value;
8726 locm = bin;
8727 locmax = binx;
8728 locmay = biny;
8729 locmaz = binz;
8730 }
8731 }
8732 }
8733 }
8734 return locm;
8735}
8736
8737////////////////////////////////////////////////////////////////////////////////
8738/// Return minimum value larger than minval of bins in the range,
8739/// unless the value has been overridden by TH1::SetMinimum,
8740/// in which case it returns that value. This happens, for example,
8741/// when the histogram is drawn and the y or z axis limits are changed
8742///
8743/// To get the minimum value of bins in the histogram regardless of
8744/// whether the value has been overridden (using TH1::SetMinimum), use
8745///
8746/// ~~~ {.cpp}
8747/// h->GetBinContent(h->GetMinimumBin())
8748/// ~~~
8749///
8750/// TH1::GetMinimumBin can be used to get the location of the
8751/// minimum value.
8752
8754{
8755 if (fMinimum != -1111) return fMinimum;
8756
8757 // empty the buffer
8758 if (fBuffer) ((TH1*)this)->BufferEmpty();
8759
8760 Int_t bin, binx, biny, binz;
8761 Int_t xfirst = fXaxis.GetFirst();
8762 Int_t xlast = fXaxis.GetLast();
8763 Int_t yfirst = fYaxis.GetFirst();
8764 Int_t ylast = fYaxis.GetLast();
8765 Int_t zfirst = fZaxis.GetFirst();
8766 Int_t zlast = fZaxis.GetLast();
8768 for (binz=zfirst;binz<=zlast;binz++) {
8769 for (biny=yfirst;biny<=ylast;biny++) {
8770 for (binx=xfirst;binx<=xlast;binx++) {
8771 bin = GetBin(binx,biny,binz);
8774 }
8775 }
8776 }
8777 return minimum;
8778}
8779
8780////////////////////////////////////////////////////////////////////////////////
8781/// Return location of bin with minimum value in the range.
8782
8784{
8787}
8788
8789////////////////////////////////////////////////////////////////////////////////
8790/// Return location of bin with minimum value in the range.
8791
8793{
8794 // empty the buffer
8795 if (fBuffer) ((TH1*)this)->BufferEmpty();
8796
8797 Int_t bin, binx, biny, binz;
8798 Int_t locm;
8799 Int_t xfirst = fXaxis.GetFirst();
8800 Int_t xlast = fXaxis.GetLast();
8801 Int_t yfirst = fYaxis.GetFirst();
8802 Int_t ylast = fYaxis.GetLast();
8803 Int_t zfirst = fZaxis.GetFirst();
8804 Int_t zlast = fZaxis.GetLast();
8806 locm = locmix = locmiy = locmiz = 0;
8807 for (binz=zfirst;binz<=zlast;binz++) {
8808 for (biny=yfirst;biny<=ylast;biny++) {
8809 for (binx=xfirst;binx<=xlast;binx++) {
8810 bin = GetBin(binx,biny,binz);
8812 if (value < minimum) {
8813 minimum = value;
8814 locm = bin;
8815 locmix = binx;
8816 locmiy = biny;
8817 locmiz = binz;
8818 }
8819 }
8820 }
8821 }
8822 return locm;
8823}
8824
8825///////////////////////////////////////////////////////////////////////////////
8826/// Retrieve the minimum and maximum values in the histogram
8827///
8828/// This will not return a cached value and will always search the
8829/// histogram for the min and max values. The user can condition whether
8830/// or not to call this with the GetMinimumStored() and GetMaximumStored()
8831/// methods. If the cache is empty, then the value will be -1111. Users
8832/// can then use the SetMinimum() or SetMaximum() methods to cache the results.
8833/// For example, the following recipe will make efficient use of this method
8834/// and the cached minimum and maximum values.
8835//
8836/// \code{.cpp}
8837/// Double_t currentMin = pHist->GetMinimumStored();
8838/// Double_t currentMax = pHist->GetMaximumStored();
8839/// if ((currentMin == -1111) || (currentMax == -1111)) {
8840/// pHist->GetMinimumAndMaximum(currentMin, currentMax);
8841/// pHist->SetMinimum(currentMin);
8842/// pHist->SetMaximum(currentMax);
8843/// }
8844/// \endcode
8845///
8846/// \param min reference to variable that will hold found minimum value
8847/// \param max reference to variable that will hold found maximum value
8848
8849void TH1::GetMinimumAndMaximum(Double_t& min, Double_t& max) const
8850{
8851 // empty the buffer
8852 if (fBuffer) ((TH1*)this)->BufferEmpty();
8853
8854 Int_t bin, binx, biny, binz;
8855 Int_t xfirst = fXaxis.GetFirst();
8856 Int_t xlast = fXaxis.GetLast();
8857 Int_t yfirst = fYaxis.GetFirst();
8858 Int_t ylast = fYaxis.GetLast();
8859 Int_t zfirst = fZaxis.GetFirst();
8860 Int_t zlast = fZaxis.GetLast();
8861 min=TMath::Infinity();
8862 max=-TMath::Infinity();
8864 for (binz=zfirst;binz<=zlast;binz++) {
8865 for (biny=yfirst;biny<=ylast;biny++) {
8866 for (binx=xfirst;binx<=xlast;binx++) {
8867 bin = GetBin(binx,biny,binz);
8869 if (value < min) min = value;
8870 if (value > max) max = value;
8871 }
8872 }
8873 }
8874}
8875
8876////////////////////////////////////////////////////////////////////////////////
8877/// Redefine x axis parameters.
8878///
8879/// The X axis parameters are modified.
8880/// The bins content array is resized
8881/// if errors (Sumw2) the errors array is resized
8882/// The previous bin contents are lost
8883/// To change only the axis limits, see TAxis::SetRange
8884
8886{
8887 if (GetDimension() != 1) {
8888 Error("SetBins","Operation only valid for 1-d histograms");
8889 return;
8890 }
8891 fXaxis.SetRange(0,0);
8893 fYaxis.Set(1,0,1);
8894 fZaxis.Set(1,0,1);
8895 fNcells = nx+2;
8897 if (fSumw2.fN) {
8899 }
8900}
8901
8902////////////////////////////////////////////////////////////////////////////////
8903/// Redefine x axis parameters with variable bin sizes.
8904///
8905/// The X axis parameters are modified.
8906/// The bins content array is resized
8907/// if errors (Sumw2) the errors array is resized
8908/// The previous bin contents are lost
8909/// To change only the axis limits, see TAxis::SetRange
8910/// xBins is supposed to be of length nx+1
8911
8912void TH1::SetBins(Int_t nx, const Double_t *xBins)
8913{
8914 if (GetDimension() != 1) {
8915 Error("SetBins","Operation only valid for 1-d histograms");
8916 return;
8917 }
8918 fXaxis.SetRange(0,0);
8919 fXaxis.Set(nx,xBins);
8920 fYaxis.Set(1,0,1);
8921 fZaxis.Set(1,0,1);
8922 fNcells = nx+2;
8924 if (fSumw2.fN) {
8926 }
8927}
8928
8929////////////////////////////////////////////////////////////////////////////////
8930/// Redefine x and y axis parameters.
8931///
8932/// The X and Y axis parameters are modified.
8933/// The bins content array is resized
8934/// if errors (Sumw2) the errors array is resized
8935/// The previous bin contents are lost
8936/// To change only the axis limits, see TAxis::SetRange
8937
8939{
8940 if (GetDimension() != 2) {
8941 Error("SetBins","Operation only valid for 2-D histograms");
8942 return;
8943 }
8944 fXaxis.SetRange(0,0);
8945 fYaxis.SetRange(0,0);
8948 fZaxis.Set(1,0,1);
8949 fNcells = (nx+2)*(ny+2);
8951 if (fSumw2.fN) {
8953 }
8954}
8955
8956////////////////////////////////////////////////////////////////////////////////
8957/// Redefine x and y axis parameters with variable bin sizes.
8958///
8959/// The X and Y axis parameters are modified.
8960/// The bins content array is resized
8961/// if errors (Sumw2) the errors array is resized
8962/// The previous bin contents are lost
8963/// To change only the axis limits, see TAxis::SetRange
8964/// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1
8965
8966void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins)
8967{
8968 if (GetDimension() != 2) {
8969 Error("SetBins","Operation only valid for 2-D histograms");
8970 return;
8971 }
8972 fXaxis.SetRange(0,0);
8973 fYaxis.SetRange(0,0);
8974 fXaxis.Set(nx,xBins);
8975 fYaxis.Set(ny,yBins);
8976 fZaxis.Set(1,0,1);
8977 fNcells = (nx+2)*(ny+2);
8979 if (fSumw2.fN) {
8981 }
8982}
8983
8984////////////////////////////////////////////////////////////////////////////////
8985/// Redefine x, y and z axis parameters.
8986///
8987/// The X, Y and Z axis parameters are modified.
8988/// The bins content array is resized
8989/// if errors (Sumw2) the errors array is resized
8990/// The previous bin contents are lost
8991/// To change only the axis limits, see TAxis::SetRange
8992
8994{
8995 if (GetDimension() != 3) {
8996 Error("SetBins","Operation only valid for 3-D histograms");
8997 return;
8998 }
8999 fXaxis.SetRange(0,0);
9000 fYaxis.SetRange(0,0);
9001 fZaxis.SetRange(0,0);
9004 fZaxis.Set(nz,zmin,zmax);
9005 fNcells = (nx+2)*(ny+2)*(nz+2);
9007 if (fSumw2.fN) {
9009 }
9010}
9011
9012////////////////////////////////////////////////////////////////////////////////
9013/// Redefine x, y and z axis parameters with variable bin sizes.
9014///
9015/// The X, Y and Z axis parameters are modified.
9016/// The bins content array is resized
9017/// if errors (Sumw2) the errors array is resized
9018/// The previous bin contents are lost
9019/// To change only the axis limits, see TAxis::SetRange
9020/// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1,
9021/// zBins is supposed to be of length nz+1
9022
9023void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins, Int_t nz, const Double_t *zBins)
9024{
9025 if (GetDimension() != 3) {
9026 Error("SetBins","Operation only valid for 3-D histograms");
9027 return;
9028 }
9029 fXaxis.SetRange(0,0);
9030 fYaxis.SetRange(0,0);
9031 fZaxis.SetRange(0,0);
9032 fXaxis.Set(nx,xBins);
9033 fYaxis.Set(ny,yBins);
9034 fZaxis.Set(nz,zBins);
9035 fNcells = (nx+2)*(ny+2)*(nz+2);
9037 if (fSumw2.fN) {
9039 }
9040}
9041
9042////////////////////////////////////////////////////////////////////////////////
9043/// By default, when a histogram is created, it is added to the list
9044/// of histogram objects in the current directory in memory.
9045/// Remove reference to this histogram from current directory and add
9046/// reference to new directory dir. dir can be 0 in which case the
9047/// histogram does not belong to any directory.
9048///
9049/// Note that the directory is not a real property of the histogram and
9050/// it will not be copied when the histogram is copied or cloned.
9051/// If the user wants to have the copied (cloned) histogram in the same
9052/// directory, he needs to set again the directory using SetDirectory to the
9053/// copied histograms
9054
9056{
9057 if (fDirectory == dir) return;
9058 if (fDirectory) fDirectory->Remove(this);
9059 fDirectory = dir;
9060 if (fDirectory) {
9062 fDirectory->Append(this);
9063 }
9064}
9065
9066////////////////////////////////////////////////////////////////////////////////
9067/// Replace bin errors by values in array error.
9068
9069void TH1::SetError(const Double_t *error)
9070{
9071 for (Int_t i = 0; i < fNcells; ++i) SetBinError(i, error[i]);
9072}
9073
9074////////////////////////////////////////////////////////////////////////////////
9075/// Change the name of this histogram
9077
9078void TH1::SetName(const char *name)
9079{
9080 // Histograms are named objects in a THashList.
9081 // We must update the hashlist if we change the name
9082 // We protect this operation
9084 if (fDirectory) fDirectory->Remove(this);
9085 fName = name;
9086 if (fDirectory) fDirectory->Append(this);
9087}
9088
9089////////////////////////////////////////////////////////////////////////////////
9090/// Change the name and title of this histogram
9091
9092void TH1::SetNameTitle(const char *name, const char *title)
9093{
9094 // Histograms are named objects in a THashList.
9095 // We must update the hashlist if we change the name
9096 SetName(name);
9097 SetTitle(title);
9098}
9099
9100////////////////////////////////////////////////////////////////////////////////
9101/// Set statistics option on/off.
9102///
9103/// By default, the statistics box is drawn.
9104/// The paint options can be selected via gStyle->SetOptStat.
9105/// This function sets/resets the kNoStats bit in the histogram object.
9106/// It has priority over the Style option.
9107
9108void TH1::SetStats(Bool_t stats)
9109{
9111 if (!stats) {
9113 //remove the "stats" object from the list of functions
9114 if (fFunctions) {
9115 TObject *obj = fFunctions->FindObject("stats");
9116 if (obj) {
9117 fFunctions->Remove(obj);
9118 delete obj;
9119 }
9120 }
9121 }
9122}
9123
9124////////////////////////////////////////////////////////////////////////////////
9125/// Create structure to store sum of squares of weights.
9126///
9127/// if histogram is already filled, the sum of squares of weights
9128/// is filled with the existing bin contents
9129///
9130/// The error per bin will be computed as sqrt(sum of squares of weight)
9131/// for each bin.
9132///
9133/// This function is automatically called when the histogram is created
9134/// if the static function TH1::SetDefaultSumw2 has been called before.
9135/// If flag = false the structure containing the sum of the square of weights
9136/// is rest and it will be empty, but it is not deleted (i.e. GetSumw2()->fN = 0)
9137
9139{
9140 if (!flag) {
9141 // clear the array if existing - do nothing otherwise
9142 if (fSumw2.fN > 0 ) fSumw2.Set(0);
9143 return;
9144 }
9145
9146 if (fSumw2.fN == fNcells) {
9147 if (!fgDefaultSumw2 )
9148 Warning("Sumw2","Sum of squares of weights structure already created");
9149 return;
9150 }
9151
9153
9154 if (fEntries > 0)
9155 for (Int_t i = 0; i < fNcells; ++i)
9157}
9158
9159////////////////////////////////////////////////////////////////////////////////
9160/// Return pointer to function with name.
9161///
9162///
9163/// Functions such as TH1::Fit store the fitted function in the list of
9164/// functions of this histogram.
9165
9166TF1 *TH1::GetFunction(const char *name) const
9167{
9168 return (TF1*)fFunctions->FindObject(name);
9169}
9170
9171////////////////////////////////////////////////////////////////////////////////
9172/// Return value of error associated to bin number bin.
9173///
9174/// if the sum of squares of weights has been defined (via Sumw2),
9175/// this function returns the sqrt(sum of w2).
9176/// otherwise it returns the sqrt(contents) for this bin.
9177
9179{
9180 if (bin < 0) bin = 0;
9181 if (bin >= fNcells) bin = fNcells-1;
9182 if (fBuffer) ((TH1*)this)->BufferEmpty();
9183 if (fSumw2.fN) return TMath::Sqrt(fSumw2.fArray[bin]);
9184
9186}
9187
9188////////////////////////////////////////////////////////////////////////////////
9189/// Return lower error associated to bin number bin.
9190///
9191/// The error will depend on the statistic option used will return
9192/// the binContent - lower interval value
9193
9195{
9196 if (fBinStatErrOpt == kNormal) return GetBinError(bin);
9197 // in case of weighted histogram check if it is really weighted
9198 if (fSumw2.fN && fTsumw != fTsumw2) return GetBinError(bin);
9199
9200 if (bin < 0) bin = 0;
9201 if (bin >= fNcells) bin = fNcells-1;
9202 if (fBuffer) ((TH1*)this)->BufferEmpty();
9203
9204 Double_t alpha = 1.- 0.682689492;
9205 if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
9206
9208 Int_t n = int(c);
9209 if (n < 0) {
9210 Warning("GetBinErrorLow","Histogram has negative bin content-force usage to normal errors");
9211 ((TH1*)this)->fBinStatErrOpt = kNormal;
9212 return GetBinError(bin);
9213 }
9214
9215 if (n == 0) return 0;
9216 return c - ROOT::Math::gamma_quantile( alpha/2, n, 1.);
9217}
9218
9219////////////////////////////////////////////////////////////////////////////////
9220/// Return upper error associated to bin number bin.
9221///
9222/// The error will depend on the statistic option used will return
9223/// the binContent - upper interval value
9224
9226{
9227 if (fBinStatErrOpt == kNormal) return GetBinError(bin);
9228 // in case of weighted histogram check if it is really weighted
9229 if (fSumw2.fN && fTsumw != fTsumw2) return GetBinError(bin);
9230 if (bin < 0) bin = 0;
9231 if (bin >= fNcells) bin = fNcells-1;
9232 if (fBuffer) ((TH1*)this)->BufferEmpty();
9233
9234 Double_t alpha = 1.- 0.682689492;
9235 if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
9236
9238 Int_t n = int(c);
9239 if (n < 0) {
9240 Warning("GetBinErrorUp","Histogram has negative bin content-force usage to normal errors");
9241 ((TH1*)this)->fBinStatErrOpt = kNormal;
9242 return GetBinError(bin);
9243 }
9244
9245 // for N==0 return an upper limit at 0.68 or (1-alpha)/2 ?
9246 // decide to return always (1-alpha)/2 upper interval
9247 //if (n == 0) return ROOT::Math::gamma_quantile_c(alpha,n+1,1);
9248 return ROOT::Math::gamma_quantile_c( alpha/2, n+1, 1) - c;
9249}
9250
9251//L.M. These following getters are useless and should be probably deprecated
9252////////////////////////////////////////////////////////////////////////////////
9253/// Return bin center for 1D histogram.
9254/// Better to use h1.GetXaxis()->GetBinCenter(bin)
9255
9257{
9258 if (fDimension == 1) return fXaxis.GetBinCenter(bin);
9259 Error("GetBinCenter","Invalid method for a %d-d histogram - return a NaN",fDimension);
9260 return TMath::QuietNaN();
9261}
9262
9263////////////////////////////////////////////////////////////////////////////////
9264/// Return bin lower edge for 1D histogram.
9265/// Better to use h1.GetXaxis()->GetBinLowEdge(bin)
9266
9268{
9269 if (fDimension == 1) return fXaxis.GetBinLowEdge(bin);
9270 Error("GetBinLowEdge","Invalid method for a %d-d histogram - return a NaN",fDimension);
9271 return TMath::QuietNaN();
9272}
9273
9274////////////////////////////////////////////////////////////////////////////////
9275/// Return bin width for 1D histogram.
9276/// Better to use h1.GetXaxis()->GetBinWidth(bin)
9277
9279{
9280 if (fDimension == 1) return fXaxis.GetBinWidth(bin);
9281 Error("GetBinWidth","Invalid method for a %d-d histogram - return a NaN",fDimension);
9282 return TMath::QuietNaN();
9283}
9284
9285////////////////////////////////////////////////////////////////////////////////
9286/// Fill array with center of bins for 1D histogram
9287/// Better to use h1.GetXaxis()->GetCenter(center)
9288
9289void TH1::GetCenter(Double_t *center) const
9290{
9291 if (fDimension == 1) {
9292 fXaxis.GetCenter(center);
9293 return;
9294 }
9295 Error("GetCenter","Invalid method for a %d-d histogram ",fDimension);
9296}
9297
9298////////////////////////////////////////////////////////////////////////////////
9299/// Fill array with low edge of bins for 1D histogram
9300/// Better to use h1.GetXaxis()->GetLowEdge(edge)
9301
9302void TH1::GetLowEdge(Double_t *edge) const
9303{
9304 if (fDimension == 1) {
9306 return;
9307 }
9308 Error("GetLowEdge","Invalid method for a %d-d histogram ",fDimension);
9309}
9310
9311////////////////////////////////////////////////////////////////////////////////
9312/// Set the bin Error
9313/// Note that this resets the bin eror option to be of Normal Type and for the
9314/// non-empty bin the bin error is set by default to the square root of their content.
9315/// Note that in case the user sets after calling SetBinError explicitly a new bin content (e.g. using SetBinContent)
9316/// he needs then to provide also the corresponding bin error (using SetBinError) since the bin error
9317/// will not be recalculated after setting the content and a default error = 0 will be used for those bins.
9318///
9319/// See convention for numbering bins in TH1::GetBin
9320
9321void TH1::SetBinError(Int_t bin, Double_t error)
9322{
9323 if (bin < 0 || bin>= fNcells) return;
9324 if (!fSumw2.fN) Sumw2();
9325 fSumw2.fArray[bin] = error * error;
9326 // reset the bin error option
9328}
9329
9330////////////////////////////////////////////////////////////////////////////////
9331/// Set bin content
9332/// see convention for numbering bins in TH1::GetBin
9333/// In case the bin number is greater than the number of bins and
9334/// the timedisplay option is set or CanExtendAllAxes(),
9335/// the number of bins is automatically doubled to accommodate the new bin
9336
9338{
9339 fEntries++;
9340 fTsumw = 0;
9341 if (bin < 0) return;
9342 if (bin >= fNcells-1) {
9344 while (bin >= fNcells-1) LabelsInflate();
9345 } else {
9346 if (bin == fNcells-1) UpdateBinContent(bin, content);
9347 return;
9348 }
9349 }
9351}
9352
9353////////////////////////////////////////////////////////////////////////////////
9354/// See convention for numbering bins in TH1::GetBin
9355
9357{
9358 if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
9359 if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
9360 SetBinError(GetBin(binx, biny), error);
9361}
9362
9363////////////////////////////////////////////////////////////////////////////////
9364/// See convention for numbering bins in TH1::GetBin
9365
9367{
9368 if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
9369 if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
9370 if (binz < 0 || binz > fZaxis.GetNbins() + 1) return;
9371 SetBinError(GetBin(binx, biny, binz), error);
9372}
9373
9374////////////////////////////////////////////////////////////////////////////////
9375/// This function calculates the background spectrum in this histogram.
9376/// The background is returned as a histogram.
9377///
9378/// \param[in] niter number of iterations (default value = 2)
9379/// Increasing niter make the result smoother and lower.
9380/// \param[in] option may contain one of the following options
9381/// - to set the direction parameter
9382/// "BackDecreasingWindow". By default the direction is BackIncreasingWindow
9383/// - filterOrder-order of clipping filter (default "BackOrder2")
9384/// possible values= "BackOrder4" "BackOrder6" "BackOrder8"
9385/// - "nosmoothing" - if selected, the background is not smoothed
9386/// By default the background is smoothed.
9387/// - smoothWindow - width of smoothing window, (default is "BackSmoothing3")
9388/// possible values= "BackSmoothing5" "BackSmoothing7" "BackSmoothing9"
9389/// "BackSmoothing11" "BackSmoothing13" "BackSmoothing15"
9390/// - "nocompton" - if selected the estimation of Compton edge
9391/// will be not be included (by default the compton estimation is set)
9392/// - "same" if this option is specified, the resulting background
9393/// histogram is superimposed on the picture in the current pad.
9394/// This option is given by default.
9395///
9396/// NOTE that the background is only evaluated in the current range of this histogram.
9397/// i.e., if this has a bin range (set via h->GetXaxis()->SetRange(binmin, binmax),
9398/// the returned histogram will be created with the same number of bins
9399/// as this input histogram, but only bins from binmin to binmax will be filled
9400/// with the estimated background.
9401
9403{
9404 return (TH1*)gROOT->ProcessLineFast(TString::Format("TSpectrum::StaticBackground((TH1*)0x%zx,%d,\"%s\")",
9405 (size_t)this, niter, option).Data());
9406}
9407
9408////////////////////////////////////////////////////////////////////////////////
9409/// Interface to TSpectrum::Search.
9410/// The function finds peaks in this histogram where the width is > sigma
9411/// and the peak maximum greater than threshold*maximum bin content of this.
9412/// For more details see TSpectrum::Search.
9413/// Note the difference in the default value for option compared to TSpectrum::Search
9414/// option="" by default (instead of "goff").
9415
9417{
9418 return (Int_t)gROOT->ProcessLineFast(TString::Format("TSpectrum::StaticSearch((TH1*)0x%zx,%g,\"%s\",%g)",
9419 (size_t)this, sigma, option, threshold).Data());
9420}
9421
9422////////////////////////////////////////////////////////////////////////////////
9423/// For a given transform (first parameter), fills the histogram (second parameter)
9424/// with the transform output data, specified in the third parameter
9425/// If the 2nd parameter h_output is empty, a new histogram (TH1D or TH2D) is created
9426/// and the user is responsible for deleting it.
9427///
9428/// Available options:
9429/// - "RE" - real part of the output
9430/// - "IM" - imaginary part of the output
9431/// - "MAG" - magnitude of the output
9432/// - "PH" - phase of the output
9433
9435{
9436 if (!fft || !fft->GetN() ) {
9437 ::Error("TransformHisto","Invalid FFT transform class");
9438 return nullptr;
9439 }
9440
9441 if (fft->GetNdim()>2){
9442 ::Error("TransformHisto","Only 1d and 2D transform are supported");
9443 return nullptr;
9444 }
9445 Int_t binx,biny;
9446 TString opt = option;
9447 opt.ToUpper();
9448 Int_t *n = fft->GetN();
9449 TH1 *hout=nullptr;
9450 if (h_output) {
9451 hout = h_output;
9452 }
9453 else {
9454 TString name = TString::Format("out_%s", opt.Data());
9455 if (fft->GetNdim()==1)
9456 hout = new TH1D(name, name,n[0], 0, n[0]);
9457 else if (fft->GetNdim()==2)
9458 hout = new TH2D(name, name, n[0], 0, n[0], n[1], 0, n[1]);
9459 }
9460 R__ASSERT(hout != nullptr);
9461 TString type=fft->GetType();
9462 Int_t ind[2];
9463 if (opt.Contains("RE")){
9464 if (type.Contains("2C") || type.Contains("2HC")) {
9465 Double_t re, im;
9466 for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
9467 for (biny=1; biny<=hout->GetNbinsY(); biny++) {
9468 ind[0] = binx-1; ind[1] = biny-1;
9469 fft->GetPointComplex(ind, re, im);
9470 hout->SetBinContent(binx, biny, re);
9471 }
9472 }
9473 } else {
9474 for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
9475 for (biny=1; biny<=hout->GetNbinsY(); biny++) {
9476 ind[0] = binx-1; ind[1] = biny-1;
9477 hout->SetBinContent(binx, biny, fft->GetPointReal(ind));
9478 }
9479 }
9480 }
9481 }
9482 if (opt.Contains("IM")) {
9483 if (type.Contains("2C") || type.Contains("2HC")) {
9484 Double_t re, im;
9485 for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
9486 for (biny=1; biny<=hout->GetNbinsY(); biny++) {
9487 ind[0] = binx-1; ind[1] = biny-1;
9488 fft->GetPointComplex(ind, re, im);
9489 hout->SetBinContent(binx, biny, im);
9490 }
9491 }
9492 } else {
9493 ::Error("TransformHisto","No complex numbers in the output");
9494 return nullptr;
9495 }
9496 }
9497 if (opt.Contains("MA")) {
9498 if (type.Contains("2C") || type.Contains("2HC")) {
9499 Double_t re, im;
9500 for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
9501 for (biny=1; biny<=hout->GetNbinsY(); biny++) {
9502 ind[0] = binx-1; ind[1] = biny-1;
9503 fft->GetPointComplex(ind, re, im);
9504 hout->SetBinContent(binx, biny, TMath::Sqrt(re*re + im*im));
9505 }
9506 }
9507 } else {
9508 for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
9509 for (biny=1; biny<=hout->GetNbinsY(); biny++) {
9510 ind[0] = binx-1; ind[1] = biny-1;
9511 hout->SetBinContent(binx, biny, TMath::Abs(fft->GetPointReal(ind)));
9512 }
9513 }
9514 }
9515 }
9516 if (opt.Contains("PH")) {
9517 if (type.Contains("2C") || type.Contains("2HC")){
9518 Double_t re, im, ph;
9519 for (binx = 1; binx<=hout->GetNbinsX(); binx++){
9520 for (biny=1; biny<=hout->GetNbinsY(); biny++){
9521 ind[0] = binx-1; ind[1] = biny-1;
9522 fft->GetPointComplex(ind, re, im);
9523 if (TMath::Abs(re) > 1e-13){
9524 ph = TMath::ATan(im/re);
9525 //find the correct quadrant
9526 if (re<0 && im<0)
9527 ph -= TMath::Pi();
9528 if (re<0 && im>=0)
9529 ph += TMath::Pi();
9530 } else {
9531 if (TMath::Abs(im) < 1e-13)
9532 ph = 0;
9533 else if (im>0)
9534 ph = TMath::Pi()*0.5;
9535 else
9536 ph = -TMath::Pi()*0.5;
9537 }
9538 hout->SetBinContent(binx, biny, ph);
9539 }
9540 }
9541 } else {
9542 printf("Pure real output, no phase");
9543 return nullptr;
9544 }
9545 }
9546
9547 return hout;
9548}
9549
9550////////////////////////////////////////////////////////////////////////////////
9551/// Print value overload
9552
9553std::string cling::printValue(TH1 *val) {
9554 std::ostringstream strm;
9555 strm << cling::printValue((TObject*)val) << " NbinsX: " << val->GetNbinsX();
9556 return strm.str();
9557}
9558
9559//______________________________________________________________________________
9560// TH1C methods
9561// TH1C : histograms with one byte per channel. Maximum bin content = 127
9562//______________________________________________________________________________
9563
9564
9565////////////////////////////////////////////////////////////////////////////////
9566/// Constructor.
9567
9568TH1C::TH1C()
9569{
9570 fDimension = 1;
9571 SetBinsLength(3);
9572 if (fgDefaultSumw2) Sumw2();
9573}
9574
9575////////////////////////////////////////////////////////////////////////////////
9576/// Create a 1-Dim histogram with fix bins of type char (one byte per channel)
9577/// (see TH1::TH1 for explanation of parameters)
9578
9579TH1C::TH1C(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9580: TH1(name,title,nbins,xlow,xup)
9581{
9582 fDimension = 1;
9584
9585 if (xlow >= xup) SetBuffer(fgBufferSize);
9586 if (fgDefaultSumw2) Sumw2();
9587}
9588
9589////////////////////////////////////////////////////////////////////////////////
9590/// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
9591/// (see TH1::TH1 for explanation of parameters)
9592
9593TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9594: TH1(name,title,nbins,xbins)
9595{
9596 fDimension = 1;
9598 if (fgDefaultSumw2) Sumw2();
9599}
9600
9601////////////////////////////////////////////////////////////////////////////////
9602/// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
9603/// (see TH1::TH1 for explanation of parameters)
9604
9605TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9606: TH1(name,title,nbins,xbins)
9607{
9608 fDimension = 1;
9610 if (fgDefaultSumw2) Sumw2();
9611}
9612
9613////////////////////////////////////////////////////////////////////////////////
9614/// Destructor.
9615
9617{
9618}
9619
9620////////////////////////////////////////////////////////////////////////////////
9621/// Copy constructor.
9622/// The list of functions is not copied. (Use Clone() if needed)
9623
9624TH1C::TH1C(const TH1C &h1c) : TH1(), TArrayC()
9625{
9626 h1c.TH1C::Copy(*this);
9627}
9628
9629////////////////////////////////////////////////////////////////////////////////
9630/// Increment bin content by 1.
9631/// Passing an out-of-range bin leads to undefined behavior
9632
9633void TH1C::AddBinContent(Int_t bin)
9634{
9635 if (fArray[bin] < 127) fArray[bin]++;
9636}
9637
9638////////////////////////////////////////////////////////////////////////////////
9639/// Increment bin content by w.
9640/// \warning The value of w is cast to `Int_t` before being added.
9641/// Passing an out-of-range bin leads to undefined behavior
9642
9644{
9645 Int_t newval = fArray[bin] + Int_t(w);
9646 if (newval > -128 && newval < 128) {fArray[bin] = Char_t(newval); return;}
9647 if (newval < -127) fArray[bin] = -127;
9648 if (newval > 127) fArray[bin] = 127;
9649}
9650
9651////////////////////////////////////////////////////////////////////////////////
9652/// Copy this to newth1
9653
9654void TH1C::Copy(TObject &newth1) const
9655{
9657}
9658
9659////////////////////////////////////////////////////////////////////////////////
9660/// Reset.
9661
9663{
9666}
9667
9668////////////////////////////////////////////////////////////////////////////////
9669/// Set total number of bins including under/overflow
9670/// Reallocate bin contents array
9671
9673{
9674 if (n < 0) n = fXaxis.GetNbins() + 2;
9675 fNcells = n;
9676 TArrayC::Set(n);
9677}
9678
9679////////////////////////////////////////////////////////////////////////////////
9680/// Operator =
9681
9682TH1C& TH1C::operator=(const TH1C &h1)
9683{
9684 if (this != &h1)
9685 h1.TH1C::Copy(*this);
9686 return *this;
9687}
9688
9689////////////////////////////////////////////////////////////////////////////////
9690/// Operator *
9691
9693{
9694 TH1C hnew = h1;
9695 hnew.Scale(c1);
9696 hnew.SetDirectory(nullptr);
9697 return hnew;
9698}
9699
9700////////////////////////////////////////////////////////////////////////////////
9701/// Operator +
9702
9703TH1C operator+(const TH1C &h1, const TH1C &h2)
9704{
9705 TH1C hnew = h1;
9706 hnew.Add(&h2,1);
9707 hnew.SetDirectory(nullptr);
9708 return hnew;
9709}
9710
9711////////////////////////////////////////////////////////////////////////////////
9712/// Operator -
9713
9714TH1C operator-(const TH1C &h1, const TH1C &h2)
9715{
9716 TH1C hnew = h1;
9717 hnew.Add(&h2,-1);
9718 hnew.SetDirectory(nullptr);
9719 return hnew;
9720}
9721
9722////////////////////////////////////////////////////////////////////////////////
9723/// Operator *
9724
9725TH1C operator*(const TH1C &h1, const TH1C &h2)
9726{
9727 TH1C hnew = h1;
9728 hnew.Multiply(&h2);
9729 hnew.SetDirectory(nullptr);
9730 return hnew;
9731}
9732
9733////////////////////////////////////////////////////////////////////////////////
9734/// Operator /
9735
9736TH1C operator/(const TH1C &h1, const TH1C &h2)
9737{
9738 TH1C hnew = h1;
9739 hnew.Divide(&h2);
9740 hnew.SetDirectory(nullptr);
9741 return hnew;
9742}
9743
9744//______________________________________________________________________________
9745// TH1S methods
9746// TH1S : histograms with one short per channel. Maximum bin content = 32767
9747//______________________________________________________________________________
9748
9749
9750////////////////////////////////////////////////////////////////////////////////
9751/// Constructor.
9752
9753TH1S::TH1S()
9754{
9755 fDimension = 1;
9756 SetBinsLength(3);
9757 if (fgDefaultSumw2) Sumw2();
9758}
9759
9760////////////////////////////////////////////////////////////////////////////////
9761/// Create a 1-Dim histogram with fix bins of type short
9762/// (see TH1::TH1 for explanation of parameters)
9763
9764TH1S::TH1S(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9765: TH1(name,title,nbins,xlow,xup)
9766{
9767 fDimension = 1;
9769
9770 if (xlow >= xup) SetBuffer(fgBufferSize);
9771 if (fgDefaultSumw2) Sumw2();
9772}
9773
9774////////////////////////////////////////////////////////////////////////////////
9775/// Create a 1-Dim histogram with variable bins of type short
9776/// (see TH1::TH1 for explanation of parameters)
9777
9778TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9779: TH1(name,title,nbins,xbins)
9780{
9781 fDimension = 1;
9783 if (fgDefaultSumw2) Sumw2();
9784}
9785
9786////////////////////////////////////////////////////////////////////////////////
9787/// Create a 1-Dim histogram with variable bins of type short
9788/// (see TH1::TH1 for explanation of parameters)
9789
9790TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9791: TH1(name,title,nbins,xbins)
9792{
9793 fDimension = 1;
9795 if (fgDefaultSumw2) Sumw2();
9796}
9797
9798////////////////////////////////////////////////////////////////////////////////
9799/// Destructor.
9800
9802{
9803}
9804
9805////////////////////////////////////////////////////////////////////////////////
9806/// Copy constructor.
9807/// The list of functions is not copied. (Use Clone() if needed)
9808
9809TH1S::TH1S(const TH1S &h1s) : TH1(), TArrayS()
9810{
9811 h1s.TH1S::Copy(*this);
9812}
9813
9814////////////////////////////////////////////////////////////////////////////////
9815/// Increment bin content by 1.
9816/// Passing an out-of-range bin leads to undefined behavior
9817
9818void TH1S::AddBinContent(Int_t bin)
9819{
9820 if (fArray[bin] < 32767) fArray[bin]++;
9821}
9822
9823////////////////////////////////////////////////////////////////////////////////
9824/// Increment bin content by w.
9825/// \warning The value of w is cast to `Int_t` before being added.
9826/// Passing an out-of-range bin leads to undefined behavior
9827
9829{
9830 Int_t newval = fArray[bin] + Int_t(w);
9831 if (newval > -32768 && newval < 32768) {fArray[bin] = Short_t(newval); return;}
9832 if (newval < -32767) fArray[bin] = -32767;
9833 if (newval > 32767) fArray[bin] = 32767;
9834}
9835
9836////////////////////////////////////////////////////////////////////////////////
9837/// Copy this to newth1
9838
9839void TH1S::Copy(TObject &newth1) const
9840{
9842}
9843
9844////////////////////////////////////////////////////////////////////////////////
9845/// Reset.
9846
9848{
9851}
9852
9853////////////////////////////////////////////////////////////////////////////////
9854/// Set total number of bins including under/overflow
9855/// Reallocate bin contents array
9856
9858{
9859 if (n < 0) n = fXaxis.GetNbins() + 2;
9860 fNcells = n;
9861 TArrayS::Set(n);
9862}
9863
9864////////////////////////////////////////////////////////////////////////////////
9865/// Operator =
9866
9867TH1S& TH1S::operator=(const TH1S &h1)
9868{
9869 if (this != &h1)
9870 h1.TH1S::Copy(*this);
9871 return *this;
9872}
9873
9874////////////////////////////////////////////////////////////////////////////////
9875/// Operator *
9876
9878{
9879 TH1S hnew = h1;
9880 hnew.Scale(c1);
9881 hnew.SetDirectory(nullptr);
9882 return hnew;
9883}
9884
9885////////////////////////////////////////////////////////////////////////////////
9886/// Operator +
9887
9888TH1S operator+(const TH1S &h1, const TH1S &h2)
9889{
9890 TH1S hnew = h1;
9891 hnew.Add(&h2,1);
9892 hnew.SetDirectory(nullptr);
9893 return hnew;
9894}
9895
9896////////////////////////////////////////////////////////////////////////////////
9897/// Operator -
9898
9899TH1S operator-(const TH1S &h1, const TH1S &h2)
9900{
9901 TH1S hnew = h1;
9902 hnew.Add(&h2,-1);
9903 hnew.SetDirectory(nullptr);
9904 return hnew;
9905}
9906
9907////////////////////////////////////////////////////////////////////////////////
9908/// Operator *
9909
9910TH1S operator*(const TH1S &h1, const TH1S &h2)
9911{
9912 TH1S hnew = h1;
9913 hnew.Multiply(&h2);
9914 hnew.SetDirectory(nullptr);
9915 return hnew;
9916}
9917
9918////////////////////////////////////////////////////////////////////////////////
9919/// Operator /
9920
9921TH1S operator/(const TH1S &h1, const TH1S &h2)
9922{
9923 TH1S hnew = h1;
9924 hnew.Divide(&h2);
9925 hnew.SetDirectory(nullptr);
9926 return hnew;
9927}
9928
9929//______________________________________________________________________________
9930// TH1I methods
9931// TH1I : histograms with one int per channel. Maximum bin content = 2147483647
9932// 2147483647 = INT_MAX
9933//______________________________________________________________________________
9934
9935
9936////////////////////////////////////////////////////////////////////////////////
9937/// Constructor.
9938
9939TH1I::TH1I()
9940{
9941 fDimension = 1;
9942 SetBinsLength(3);
9943 if (fgDefaultSumw2) Sumw2();
9944}
9945
9946////////////////////////////////////////////////////////////////////////////////
9947/// Create a 1-Dim histogram with fix bins of type integer
9948/// (see TH1::TH1 for explanation of parameters)
9949
9950TH1I::TH1I(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9951: TH1(name,title,nbins,xlow,xup)
9952{
9953 fDimension = 1;
9955
9956 if (xlow >= xup) SetBuffer(fgBufferSize);
9957 if (fgDefaultSumw2) Sumw2();
9958}
9959
9960////////////////////////////////////////////////////////////////////////////////
9961/// Create a 1-Dim histogram with variable bins of type integer
9962/// (see TH1::TH1 for explanation of parameters)
9963
9964TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9965: TH1(name,title,nbins,xbins)
9966{
9967 fDimension = 1;
9969 if (fgDefaultSumw2) Sumw2();
9970}
9971
9972////////////////////////////////////////////////////////////////////////////////
9973/// Create a 1-Dim histogram with variable bins of type integer
9974/// (see TH1::TH1 for explanation of parameters)
9975
9976TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9977: TH1(name,title,nbins,xbins)
9978{
9979 fDimension = 1;
9981 if (fgDefaultSumw2) Sumw2();
9982}
9983
9984////////////////////////////////////////////////////////////////////////////////
9985/// Destructor.
9986
9988{
9989}
9990
9991////////////////////////////////////////////////////////////////////////////////
9992/// Copy constructor.
9993/// The list of functions is not copied. (Use Clone() if needed)
9994
9995TH1I::TH1I(const TH1I &h1i) : TH1(), TArrayI()
9996{
9997 h1i.TH1I::Copy(*this);
9998}
9999
10000////////////////////////////////////////////////////////////////////////////////
10001/// Increment bin content by 1.
10002/// Passing an out-of-range bin leads to undefined behavior
10003
10004void TH1I::AddBinContent(Int_t bin)
10005{
10006 if (fArray[bin] < INT_MAX) fArray[bin]++;
10007}
10008
10009////////////////////////////////////////////////////////////////////////////////
10010/// Increment bin content by w
10011/// \warning The value of w is cast to `Long64_t` before being added.
10012/// Passing an out-of-range bin leads to undefined behavior
10013
10015{
10016 Long64_t newval = fArray[bin] + Long64_t(w);
10017 if (newval > -INT_MAX && newval < INT_MAX) {fArray[bin] = Int_t(newval); return;}
10018 if (newval < -INT_MAX) fArray[bin] = -INT_MAX;
10019 if (newval > INT_MAX) fArray[bin] = INT_MAX;
10020}
10021
10022////////////////////////////////////////////////////////////////////////////////
10023/// Copy this to newth1
10024
10025void TH1I::Copy(TObject &newth1) const
10026{
10028}
10029
10030////////////////////////////////////////////////////////////////////////////////
10031/// Reset.
10032
10034{
10037}
10038
10039////////////////////////////////////////////////////////////////////////////////
10040/// Set total number of bins including under/overflow
10041/// Reallocate bin contents array
10042
10044{
10045 if (n < 0) n = fXaxis.GetNbins() + 2;
10046 fNcells = n;
10047 TArrayI::Set(n);
10048}
10049
10050////////////////////////////////////////////////////////////////////////////////
10051/// Operator =
10052
10053TH1I& TH1I::operator=(const TH1I &h1)
10054{
10055 if (this != &h1)
10056 h1.TH1I::Copy(*this);
10057 return *this;
10058}
10059
10060
10061////////////////////////////////////////////////////////////////////////////////
10062/// Operator *
10063
10065{
10066 TH1I hnew = h1;
10067 hnew.Scale(c1);
10068 hnew.SetDirectory(nullptr);
10069 return hnew;
10070}
10071
10072////////////////////////////////////////////////////////////////////////////////
10073/// Operator +
10074
10075TH1I operator+(const TH1I &h1, const TH1I &h2)
10076{
10077 TH1I hnew = h1;
10078 hnew.Add(&h2,1);
10079 hnew.SetDirectory(nullptr);
10080 return hnew;
10081}
10082
10083////////////////////////////////////////////////////////////////////////////////
10084/// Operator -
10085
10086TH1I operator-(const TH1I &h1, const TH1I &h2)
10087{
10088 TH1I hnew = h1;
10089 hnew.Add(&h2,-1);
10090 hnew.SetDirectory(nullptr);
10091 return hnew;
10092}
10093
10094////////////////////////////////////////////////////////////////////////////////
10095/// Operator *
10096
10097TH1I operator*(const TH1I &h1, const TH1I &h2)
10098{
10099 TH1I hnew = h1;
10100 hnew.Multiply(&h2);
10101 hnew.SetDirectory(nullptr);
10102 return hnew;
10103}
10104
10105////////////////////////////////////////////////////////////////////////////////
10106/// Operator /
10107
10108TH1I operator/(const TH1I &h1, const TH1I &h2)
10109{
10110 TH1I hnew = h1;
10111 hnew.Divide(&h2);
10112 hnew.SetDirectory(nullptr);
10113 return hnew;
10114}
10115
10116//______________________________________________________________________________
10117// TH1L methods
10118// TH1L : histograms with one long64 per channel. Maximum bin content = 9223372036854775807
10119// 9223372036854775807 = LLONG_MAX
10120//______________________________________________________________________________
10121
10122
10123////////////////////////////////////////////////////////////////////////////////
10124/// Constructor.
10125
10126TH1L::TH1L()
10127{
10128 fDimension = 1;
10129 SetBinsLength(3);
10130 if (fgDefaultSumw2) Sumw2();
10131}
10132
10133////////////////////////////////////////////////////////////////////////////////
10134/// Create a 1-Dim histogram with fix bins of type long64
10135/// (see TH1::TH1 for explanation of parameters)
10136
10137TH1L::TH1L(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
10138: TH1(name,title,nbins,xlow,xup)
10139{
10140 fDimension = 1;
10142
10143 if (xlow >= xup) SetBuffer(fgBufferSize);
10144 if (fgDefaultSumw2) Sumw2();
10145}
10146
10147////////////////////////////////////////////////////////////////////////////////
10148/// Create a 1-Dim histogram with variable bins of type long64
10149/// (see TH1::TH1 for explanation of parameters)
10150
10151TH1L::TH1L(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
10152: TH1(name,title,nbins,xbins)
10153{
10154 fDimension = 1;
10156 if (fgDefaultSumw2) Sumw2();
10157}
10158
10159////////////////////////////////////////////////////////////////////////////////
10160/// Create a 1-Dim histogram with variable bins of type long64
10161/// (see TH1::TH1 for explanation of parameters)
10162
10163TH1L::TH1L(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
10164: TH1(name,title,nbins,xbins)
10165{
10166 fDimension = 1;
10168 if (fgDefaultSumw2) Sumw2();
10169}
10170
10171////////////////////////////////////////////////////////////////////////////////
10172/// Destructor.
10173
10175{
10176}
10177
10178////////////////////////////////////////////////////////////////////////////////
10179/// Copy constructor.
10180/// The list of functions is not copied. (Use Clone() if needed)
10181
10182TH1L::TH1L(const TH1L &h1l) : TH1(), TArrayL64()
10183{
10184 h1l.TH1L::Copy(*this);
10185}
10186
10187////////////////////////////////////////////////////////////////////////////////
10188/// Increment bin content by 1.
10189/// Passing an out-of-range bin leads to undefined behavior
10190
10191void TH1L::AddBinContent(Int_t bin)
10192{
10193 if (fArray[bin] < LLONG_MAX) fArray[bin]++;
10194}
10195
10196////////////////////////////////////////////////////////////////////////////////
10197/// Increment bin content by w.
10198/// \warning The value of w is cast to `Long64_t` before being added.
10199/// Passing an out-of-range bin leads to undefined behavior
10200
10202{
10203 Long64_t newval = fArray[bin] + Long64_t(w);
10204 if (newval > -LLONG_MAX && newval < LLONG_MAX) {fArray[bin] = newval; return;}
10205 if (newval < -LLONG_MAX) fArray[bin] = -LLONG_MAX;
10206 if (newval > LLONG_MAX) fArray[bin] = LLONG_MAX;
10207}
10208
10209////////////////////////////////////////////////////////////////////////////////
10210/// Copy this to newth1
10211
10212void TH1L::Copy(TObject &newth1) const
10213{
10215}
10216
10217////////////////////////////////////////////////////////////////////////////////
10218/// Reset.
10219
10221{
10224}
10225
10226////////////////////////////////////////////////////////////////////////////////
10227/// Set total number of bins including under/overflow
10228/// Reallocate bin contents array
10229
10231{
10232 if (n < 0) n = fXaxis.GetNbins() + 2;
10233 fNcells = n;
10235}
10236
10237////////////////////////////////////////////////////////////////////////////////
10238/// Operator =
10239
10240TH1L& TH1L::operator=(const TH1L &h1)
10241{
10242 if (this != &h1)
10243 h1.TH1L::Copy(*this);
10244 return *this;
10245}
10246
10247
10248////////////////////////////////////////////////////////////////////////////////
10249/// Operator *
10250
10252{
10253 TH1L hnew = h1;
10254 hnew.Scale(c1);
10255 hnew.SetDirectory(nullptr);
10256 return hnew;
10257}
10258
10259////////////////////////////////////////////////////////////////////////////////
10260/// Operator +
10261
10262TH1L operator+(const TH1L &h1, const TH1L &h2)
10263{
10264 TH1L hnew = h1;
10265 hnew.Add(&h2,1);
10266 hnew.SetDirectory(nullptr);
10267 return hnew;
10268}
10269
10270////////////////////////////////////////////////////////////////////////////////
10271/// Operator -
10272
10273TH1L operator-(const TH1L &h1, const TH1L &h2)
10274{
10275 TH1L hnew = h1;
10276 hnew.Add(&h2,-1);
10277 hnew.SetDirectory(nullptr);
10278 return hnew;
10279}
10280
10281////////////////////////////////////////////////////////////////////////////////
10282/// Operator *
10283
10284TH1L operator*(const TH1L &h1, const TH1L &h2)
10285{
10286 TH1L hnew = h1;
10287 hnew.Multiply(&h2);
10288 hnew.SetDirectory(nullptr);
10289 return hnew;
10290}
10291
10292////////////////////////////////////////////////////////////////////////////////
10293/// Operator /
10294
10295TH1L operator/(const TH1L &h1, const TH1L &h2)
10296{
10297 TH1L hnew = h1;
10298 hnew.Divide(&h2);
10299 hnew.SetDirectory(nullptr);
10300 return hnew;
10301}
10302
10303//______________________________________________________________________________
10304// TH1F methods
10305// TH1F : histograms with one float per channel. Maximum precision 7 digits, maximum integer bin content = +/-16777216
10306//______________________________________________________________________________
10307
10308
10309////////////////////////////////////////////////////////////////////////////////
10310/// Constructor.
10311
10312TH1F::TH1F()
10313{
10314 fDimension = 1;
10315 SetBinsLength(3);
10316 if (fgDefaultSumw2) Sumw2();
10317}
10318
10319////////////////////////////////////////////////////////////////////////////////
10320/// Create a 1-Dim histogram with fix bins of type float
10321/// (see TH1::TH1 for explanation of parameters)
10322
10323TH1F::TH1F(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
10324: TH1(name,title,nbins,xlow,xup)
10325{
10326 fDimension = 1;
10328
10329 if (xlow >= xup) SetBuffer(fgBufferSize);
10330 if (fgDefaultSumw2) Sumw2();
10331}
10332
10333////////////////////////////////////////////////////////////////////////////////
10334/// Create a 1-Dim histogram with variable bins of type float
10335/// (see TH1::TH1 for explanation of parameters)
10336
10337TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
10338: TH1(name,title,nbins,xbins)
10339{
10340 fDimension = 1;
10342 if (fgDefaultSumw2) Sumw2();
10343}
10344
10345////////////////////////////////////////////////////////////////////////////////
10346/// Create a 1-Dim histogram with variable bins of type float
10347/// (see TH1::TH1 for explanation of parameters)
10348
10349TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
10350: TH1(name,title,nbins,xbins)
10351{
10352 fDimension = 1;
10354 if (fgDefaultSumw2) Sumw2();
10355}
10356
10357////////////////////////////////////////////////////////////////////////////////
10358/// Create a histogram from a TVectorF
10359/// by default the histogram name is "TVectorF" and title = ""
10360
10361TH1F::TH1F(const TVectorF &v)
10362: TH1("TVectorF","",v.GetNrows(),0,v.GetNrows())
10363{
10365 fDimension = 1;
10366 Int_t ivlow = v.GetLwb();
10367 for (Int_t i=0;i<fNcells-2;i++) {
10368 SetBinContent(i+1,v(i+ivlow));
10369 }
10371 if (fgDefaultSumw2) Sumw2();
10372}
10373
10374////////////////////////////////////////////////////////////////////////////////
10375/// Copy Constructor.
10376/// The list of functions is not copied. (Use Clone() if needed)
10377
10378TH1F::TH1F(const TH1F &h1f) : TH1(), TArrayF()
10379{
10380 h1f.TH1F::Copy(*this);
10381}
10382
10383////////////////////////////////////////////////////////////////////////////////
10384/// Destructor.
10385
10387{
10388}
10389
10390////////////////////////////////////////////////////////////////////////////////
10391/// Copy this to newth1.
10392
10393void TH1F::Copy(TObject &newth1) const
10394{
10396}
10397
10398////////////////////////////////////////////////////////////////////////////////
10399/// Reset.
10400
10402{
10405}
10406
10407////////////////////////////////////////////////////////////////////////////////
10408/// Set total number of bins including under/overflow
10409/// Reallocate bin contents array
10410
10412{
10413 if (n < 0) n = fXaxis.GetNbins() + 2;
10414 fNcells = n;
10415 TArrayF::Set(n);
10416}
10417
10418////////////////////////////////////////////////////////////////////////////////
10419/// Operator =
10420
10422{
10423 if (this != &h1f)
10424 h1f.TH1F::Copy(*this);
10425 return *this;
10426}
10427
10428////////////////////////////////////////////////////////////////////////////////
10429/// Operator *
10430
10432{
10433 TH1F hnew = h1;
10434 hnew.Scale(c1);
10435 hnew.SetDirectory(nullptr);
10436 return hnew;
10437}
10438
10439////////////////////////////////////////////////////////////////////////////////
10440/// Operator +
10441
10442TH1F operator+(const TH1F &h1, const TH1F &h2)
10443{
10444 TH1F hnew = h1;
10445 hnew.Add(&h2,1);
10446 hnew.SetDirectory(nullptr);
10447 return hnew;
10448}
10449
10450////////////////////////////////////////////////////////////////////////////////
10451/// Operator -
10452
10453TH1F operator-(const TH1F &h1, const TH1F &h2)
10454{
10455 TH1F hnew = h1;
10456 hnew.Add(&h2,-1);
10457 hnew.SetDirectory(nullptr);
10458 return hnew;
10459}
10460
10461////////////////////////////////////////////////////////////////////////////////
10462/// Operator *
10463
10464TH1F operator*(const TH1F &h1, const TH1F &h2)
10465{
10466 TH1F hnew = h1;
10467 hnew.Multiply(&h2);
10468 hnew.SetDirectory(nullptr);
10469 return hnew;
10470}
10471
10472////////////////////////////////////////////////////////////////////////////////
10473/// Operator /
10474
10475TH1F operator/(const TH1F &h1, const TH1F &h2)
10476{
10477 TH1F hnew = h1;
10478 hnew.Divide(&h2);
10479 hnew.SetDirectory(nullptr);
10480 return hnew;
10481}
10482
10483//______________________________________________________________________________
10484// TH1D methods
10485// TH1D : histograms with one double per channel. Maximum precision 14 digits, maximum integer bin content = +/-9007199254740992
10486//______________________________________________________________________________
10487
10488
10489////////////////////////////////////////////////////////////////////////////////
10490/// Constructor.
10491
10492TH1D::TH1D()
10493{
10494 fDimension = 1;
10495 SetBinsLength(3);
10496 if (fgDefaultSumw2) Sumw2();
10497}
10498
10499////////////////////////////////////////////////////////////////////////////////
10500/// Create a 1-Dim histogram with fix bins of type double
10501/// (see TH1::TH1 for explanation of parameters)
10502
10503TH1D::TH1D(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
10504: TH1(name,title,nbins,xlow,xup)
10505{
10506 fDimension = 1;
10508
10509 if (xlow >= xup) SetBuffer(fgBufferSize);
10510 if (fgDefaultSumw2) Sumw2();
10511}
10512
10513////////////////////////////////////////////////////////////////////////////////
10514/// Create a 1-Dim histogram with variable bins of type double
10515/// (see TH1::TH1 for explanation of parameters)
10516
10517TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
10518: TH1(name,title,nbins,xbins)
10519{
10520 fDimension = 1;
10522 if (fgDefaultSumw2) Sumw2();
10523}
10524
10525////////////////////////////////////////////////////////////////////////////////
10526/// Create a 1-Dim histogram with variable bins of type double
10527/// (see TH1::TH1 for explanation of parameters)
10528
10529TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
10530: TH1(name,title,nbins,xbins)
10531{
10532 fDimension = 1;
10534 if (fgDefaultSumw2) Sumw2();
10535}
10536
10537////////////////////////////////////////////////////////////////////////////////
10538/// Create a histogram from a TVectorD
10539/// by default the histogram name is "TVectorD" and title = ""
10540
10541TH1D::TH1D(const TVectorD &v)
10542: TH1("TVectorD","",v.GetNrows(),0,v.GetNrows())
10543{
10545 fDimension = 1;
10546 Int_t ivlow = v.GetLwb();
10547 for (Int_t i=0;i<fNcells-2;i++) {
10548 SetBinContent(i+1,v(i+ivlow));
10549 }
10551 if (fgDefaultSumw2) Sumw2();
10552}
10553
10554////////////////////////////////////////////////////////////////////////////////
10555/// Destructor.
10556
10558{
10559}
10560
10561////////////////////////////////////////////////////////////////////////////////
10562/// Constructor.
10563
10564TH1D::TH1D(const TH1D &h1d) : TH1(), TArrayD()
10565{
10566 // intentially call virtual method to warn if TProfile is copying
10567 h1d.Copy(*this);
10568}
10569
10570////////////////////////////////////////////////////////////////////////////////
10571/// Copy this to newth1
10572
10573void TH1D::Copy(TObject &newth1) const
10574{
10576}
10577
10578////////////////////////////////////////////////////////////////////////////////
10579/// Reset.
10580
10582{
10585}
10586
10587////////////////////////////////////////////////////////////////////////////////
10588/// Set total number of bins including under/overflow
10589/// Reallocate bin contents array
10590
10592{
10593 if (n < 0) n = fXaxis.GetNbins() + 2;
10594 fNcells = n;
10595 TArrayD::Set(n);
10596}
10597
10598////////////////////////////////////////////////////////////////////////////////
10599/// Operator =
10600
10602{
10603 // intentially call virtual method to warn if TProfile is copying
10604 if (this != &h1d)
10605 h1d.Copy(*this);
10606 return *this;
10607}
10608
10609////////////////////////////////////////////////////////////////////////////////
10610/// Operator *
10611
10613{
10614 TH1D hnew = h1;
10615 hnew.Scale(c1);
10616 hnew.SetDirectory(nullptr);
10617 return hnew;
10618}
10619
10620////////////////////////////////////////////////////////////////////////////////
10621/// Operator +
10622
10623TH1D operator+(const TH1D &h1, const TH1D &h2)
10624{
10625 TH1D hnew = h1;
10626 hnew.Add(&h2,1);
10627 hnew.SetDirectory(nullptr);
10628 return hnew;
10629}
10630
10631////////////////////////////////////////////////////////////////////////////////
10632/// Operator -
10633
10634TH1D operator-(const TH1D &h1, const TH1D &h2)
10635{
10636 TH1D hnew = h1;
10637 hnew.Add(&h2,-1);
10638 hnew.SetDirectory(nullptr);
10639 return hnew;
10640}
10641
10642////////////////////////////////////////////////////////////////////////////////
10643/// Operator *
10644
10645TH1D operator*(const TH1D &h1, const TH1D &h2)
10646{
10647 TH1D hnew = h1;
10648 hnew.Multiply(&h2);
10649 hnew.SetDirectory(nullptr);
10650 return hnew;
10651}
10652
10653////////////////////////////////////////////////////////////////////////////////
10654/// Operator /
10655
10656TH1D operator/(const TH1D &h1, const TH1D &h2)
10657{
10658 TH1D hnew = h1;
10659 hnew.Divide(&h2);
10660 hnew.SetDirectory(nullptr);
10661 return hnew;
10662}
10663
10664////////////////////////////////////////////////////////////////////////////////
10665///return pointer to histogram with name
10666///hid if id >=0
10667///h_id if id <0
10668
10669TH1 *R__H(Int_t hid)
10670{
10671 TString hname;
10672 if(hid >= 0) hname.Form("h%d",hid);
10673 else hname.Form("h_%d",hid);
10674 return (TH1*)gDirectory->Get(hname);
10675}
10676
10677////////////////////////////////////////////////////////////////////////////////
10678///return pointer to histogram with name hname
10679
10680TH1 *R__H(const char * hname)
10681{
10682 return (TH1*)gDirectory->Get(hname);
10683}
10684
10685
10686/// \fn void TH1::SetBarOffset(Float_t offset)
10687/// Set the bar offset as fraction of the bin width for drawing mode "B".
10688/// This shifts bars to the right on the x axis, and helps to draw bars next to each other.
10689/// \see THistPainter, SetBarWidth()
10690
10691/// \fn void TH1::SetBarWidth(Float_t width)
10692/// Set the width of bars as fraction of the bin width for drawing mode "B".
10693/// This allows for making bars narrower than the bin width. With SetBarOffset(), this helps to draw multiple bars next to each other.
10694/// \see THistPainter, SetBarOffset()
#define b(i)
Definition RSha256.hxx:100
#define c(i)
Definition RSha256.hxx:101
#define a(i)
Definition RSha256.hxx:99
#define s1(x)
Definition RSha256.hxx:91
#define h(i)
Definition RSha256.hxx:106
#define e(i)
Definition RSha256.hxx:103
short Style_t
Style number (short)
Definition RtypesCore.h:96
bool Bool_t
Boolean (0=false, 1=true) (bool)
Definition RtypesCore.h:77
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:59
short Color_t
Color number (short)
Definition RtypesCore.h:99
short Version_t
Class version identifier (short)
Definition RtypesCore.h:79
char Char_t
Character 1 byte (char)
Definition RtypesCore.h:51
float Float_t
Float 4 bytes (float)
Definition RtypesCore.h:71
short Short_t
Signed Short integer 2 bytes (short)
Definition RtypesCore.h:53
constexpr Bool_t kFALSE
Definition RtypesCore.h:108
double Double_t
Double 8 bytes.
Definition RtypesCore.h:73
long long Long64_t
Portable signed long integer 8 bytes.
Definition RtypesCore.h:83
constexpr Bool_t kTRUE
Definition RtypesCore.h:107
const char Option_t
Option string (const char)
Definition RtypesCore.h:80
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
#define gDirectory
Definition TDirectory.h:385
R__EXTERN TEnv * gEnv
Definition TEnv.h:170
#define R__ASSERT(e)
Checks condition e and reports a fatal error if it's false.
Definition TError.h:125
winID h TVirtualViewer3D TVirtualGLPainter p
Option_t Option_t option
Option_t Option_t SetLineWidth
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char filename
Option_t Option_t SetFillStyle
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t del
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t np
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
Option_t Option_t SetLineColor
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t UChar_t len
Option_t Option_t TPoint TPoint const char x1
Option_t Option_t TPoint TPoint const char y2
Option_t Option_t SetFillColor
Option_t Option_t SetMarkerStyle
Option_t Option_t width
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
Option_t Option_t TPoint TPoint const char y1
char name[80]
Definition TGX11.cxx:110
static bool IsEquidistantBinning(const TAxis &axis)
Test if the binning is equidistant.
Definition TH1.cxx:5939
void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
Least square linear fit without weights.
Definition TH1.cxx:4885
void H1InitGaus()
Compute Initial values of parameters for a gaussian.
Definition TH1.cxx:4720
void H1InitExpo()
Compute Initial values of parameters for an exponential.
Definition TH1.cxx:4776
TH1C operator+(const TH1C &h1, const TH1C &h2)
Operator +.
Definition TH1.cxx:9701
TH1C operator-(const TH1C &h1, const TH1C &h2)
Operator -.
Definition TH1.cxx:9712
TH1C operator/(const TH1C &h1, const TH1C &h2)
Operator /.
Definition TH1.cxx:9734
void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b)
Extracted from CERN Program library routine DSEQN.
Definition TH1.cxx:4931
static Bool_t AlmostEqual(Double_t a, Double_t b, Double_t epsilon=0.00000001)
Test if two double are almost equal.
Definition TH1.cxx:5922
static Bool_t AlmostInteger(Double_t a, Double_t epsilon=0.00000001)
Test if a double is almost an integer.
Definition TH1.cxx:5930
TF1 * gF1
Definition TH1.cxx:590
TH1 * R__H(Int_t hid)
return pointer to histogram with name hid if id >=0 h_id if id <0
Definition TH1.cxx:10667
TH1C operator*(Double_t c1, const TH1C &h1)
Operator *.
Definition TH1.cxx:9690
void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a)
Least squares lpolynomial fitting without weights.
Definition TH1.cxx:4826
void H1InitPolynom()
Compute Initial values of parameters for a polynom.
Definition TH1.cxx:4796
float xmin
int nentries
float ymin
float xmax
float ymax
#define gInterpreter
Int_t gDebug
Global variable setting the debug level. Set to 0 to disable, increase it in steps of 1 to increase t...
Definition TROOT.cxx:627
R__EXTERN TVirtualMutex * gROOTMutex
Definition TROOT.h:63
#define gROOT
Definition TROOT.h:414
R__EXTERN TRandom * gRandom
Definition TRandom.h:62
void Printf(const char *fmt,...)
Formats a string in a circular formatting buffer and prints the string.
Definition TString.cxx:2509
R__EXTERN TStyle * gStyle
Definition TStyle.h:442
#define R__LOCKGUARD(mutex)
#define gPad
#define R__WRITE_LOCKGUARD(mutex)
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition BinData.h:52
class describing the range in the coordinates it supports multiple range in a coordinate.
Definition DataRange.h:35
void AndersonDarling2SamplesTest(Double_t &pvalue, Double_t &testStat) const
Performs the Anderson-Darling 2-Sample Test.
Definition GoFTest.cxx:646
const_iterator begin() const
const_iterator end() const
Array of chars or bytes (8 bits per element).
Definition TArrayC.h:27
Char_t * fArray
Definition TArrayC.h:30
void Reset(Char_t val=0)
Definition TArrayC.h:47
void Set(Int_t n) override
Set size of this array to n chars.
Definition TArrayC.cxx:104
Array of doubles (64 bits per element).
Definition TArrayD.h:27
Double_t * fArray
Definition TArrayD.h:30
void Streamer(TBuffer &) override
Stream a TArrayD object.
Definition TArrayD.cxx:148
void Copy(TArrayD &array) const
Definition TArrayD.h:42
void Set(Int_t n) override
Set size of this array to n doubles.
Definition TArrayD.cxx:105
const Double_t * GetArray() const
Definition TArrayD.h:43
void Reset()
Definition TArrayD.h:47
Array of floats (32 bits per element).
Definition TArrayF.h:27
void Reset()
Definition TArrayF.h:47
void Set(Int_t n) override
Set size of this array to n floats.
Definition TArrayF.cxx:104
Array of integers (32 bits per element).
Definition TArrayI.h:27
Int_t * fArray
Definition TArrayI.h:30
void Set(Int_t n) override
Set size of this array to n ints.
Definition TArrayI.cxx:104
void Reset()
Definition TArrayI.h:47
Array of long64s (64 bits per element).
Definition TArrayL64.h:27
Long64_t * fArray
Definition TArrayL64.h:30
void Set(Int_t n) override
Set size of this array to n long64s.
void Reset()
Definition TArrayL64.h:47
Array of shorts (16 bits per element).
Definition TArrayS.h:27
void Set(Int_t n) override
Set size of this array to n shorts.
Definition TArrayS.cxx:104
void Reset()
Definition TArrayS.h:47
Short_t * fArray
Definition TArrayS.h:30
Abstract array base class.
Definition TArray.h:31
Int_t fN
Definition TArray.h:38
virtual void Set(Int_t n)=0
virtual Color_t GetTitleColor() const
Definition TAttAxis.h:47
virtual Color_t GetLabelColor() const
Definition TAttAxis.h:39
virtual Int_t GetNdivisions() const
Definition TAttAxis.h:37
virtual Color_t GetAxisColor() const
Definition TAttAxis.h:38
virtual void SetTitleOffset(Float_t offset=1)
Set distance between the axis and the axis title.
Definition TAttAxis.cxx:279
virtual Style_t GetTitleFont() const
Definition TAttAxis.h:48
virtual Float_t GetLabelOffset() const
Definition TAttAxis.h:41
virtual void SetAxisColor(Color_t color=1, Float_t alpha=1.)
Set color of the line axis and tick marks.
Definition TAttAxis.cxx:141
virtual void SetLabelSize(Float_t size=0.04)
Set size of axis labels.
Definition TAttAxis.cxx:184
virtual Style_t GetLabelFont() const
Definition TAttAxis.h:40
virtual void SetTitleFont(Style_t font=62)
Set the title font.
Definition TAttAxis.cxx:308
virtual void SetLabelOffset(Float_t offset=0.005)
Set distance between the axis and the labels.
Definition TAttAxis.cxx:172
virtual void SetLabelFont(Style_t font=62)
Set labels' font.
Definition TAttAxis.cxx:161
virtual void SetTitleSize(Float_t size=0.04)
Set size of axis title.
Definition TAttAxis.cxx:290
virtual void SetTitleColor(Color_t color=1)
Set color of axis title.
Definition TAttAxis.cxx:299
virtual Float_t GetTitleSize() const
Definition TAttAxis.h:45
virtual Float_t GetLabelSize() const
Definition TAttAxis.h:42
virtual Float_t GetTickLength() const
Definition TAttAxis.h:46
virtual void ResetAttAxis(Option_t *option="")
Reset axis attributes.
Definition TAttAxis.cxx:78
virtual Float_t GetTitleOffset() const
Definition TAttAxis.h:44
virtual void SetTickLength(Float_t length=0.03)
Set tick mark length.
Definition TAttAxis.cxx:265
virtual void SetNdivisions(Int_t n=510, Bool_t optim=kTRUE)
Set the number of divisions for this axis.
Definition TAttAxis.cxx:214
virtual void SetLabelColor(Color_t color=1, Float_t alpha=1.)
Set color of labels.
Definition TAttAxis.cxx:151
virtual void Streamer(TBuffer &)
virtual Color_t GetFillColor() const
Return the fill area color.
Definition TAttFill.h:31
void Copy(TAttFill &attfill) const
Copy this fill attributes to a new TAttFill.
Definition TAttFill.cxx:206
virtual Style_t GetFillStyle() const
Return the fill area style.
Definition TAttFill.h:32
virtual void SaveFillAttributes(std::ostream &out, const char *name, Int_t coldef=1, Int_t stydef=1001)
Save fill attributes as C++ statement(s) on output stream out.
Definition TAttFill.cxx:238
virtual void Streamer(TBuffer &)
virtual Color_t GetLineColor() const
Return the line color.
Definition TAttLine.h:35
virtual void SetLineStyle(Style_t lstyle)
Set the line style.
Definition TAttLine.h:44
virtual Width_t GetLineWidth() const
Return the line width.
Definition TAttLine.h:37
virtual Style_t GetLineStyle() const
Return the line style.
Definition TAttLine.h:36
void Copy(TAttLine &attline) const
Copy this line attributes to a new TAttLine.
Definition TAttLine.cxx:176
virtual void SaveLineAttributes(std::ostream &out, const char *name, Int_t coldef=1, Int_t stydef=1, Int_t widdef=1)
Save line attributes as C++ statement(s) on output stream out.
Definition TAttLine.cxx:274
virtual void SaveMarkerAttributes(std::ostream &out, const char *name, Int_t coldef=1, Int_t stydef=1, Int_t sizdef=1)
Save line attributes as C++ statement(s) on output stream out.
virtual Style_t GetMarkerStyle() const
Return the marker style.
Definition TAttMarker.h:33
virtual void SetMarkerColor(Color_t mcolor=1)
Set the marker color.
Definition TAttMarker.h:39
virtual Color_t GetMarkerColor() const
Return the marker color.
Definition TAttMarker.h:32
virtual Size_t GetMarkerSize() const
Return the marker size.
Definition TAttMarker.h:34
virtual void SetMarkerStyle(Style_t mstyle=1)
Set the marker style.
Definition TAttMarker.h:41
void Copy(TAttMarker &attmarker) const
Copy this marker attributes to a new TAttMarker.
virtual void Streamer(TBuffer &)
virtual void SetMarkerSize(Size_t msize=1)
Set the marker size.
Definition TAttMarker.h:46
Class to manage histogram axis.
Definition TAxis.h:32
virtual void GetCenter(Double_t *center) const
Return an array with the center of all bins.
Definition TAxis.cxx:558
virtual Bool_t GetTimeDisplay() const
Definition TAxis.h:133
Bool_t IsAlphanumeric() const
Definition TAxis.h:90
const char * GetTitle() const override
Returns title of object.
Definition TAxis.h:137
virtual Double_t GetBinCenter(Int_t bin) const
Return center of bin.
Definition TAxis.cxx:482
Bool_t CanExtend() const
Definition TAxis.h:88
virtual void SetParent(TObject *obj)
Definition TAxis.h:169
const TArrayD * GetXbins() const
Definition TAxis.h:138
void SetCanExtend(Bool_t canExtend)
Definition TAxis.h:92
void Copy(TObject &axis) const override
Copy axis structure to another axis.
Definition TAxis.cxx:211
Double_t GetXmax() const
Definition TAxis.h:142
@ kLabelsUp
Definition TAxis.h:75
@ kLabelsDown
Definition TAxis.h:74
@ kLabelsHori
Definition TAxis.h:72
@ kAxisRange
Definition TAxis.h:66
@ kLabelsVert
Definition TAxis.h:73
virtual Int_t FindBin(Double_t x)
Find bin number corresponding to abscissa x.
Definition TAxis.cxx:293
virtual Double_t GetBinLowEdge(Int_t bin) const
Return low edge of bin.
Definition TAxis.cxx:522
virtual void SetTimeDisplay(Int_t value)
Definition TAxis.h:173
virtual void Set(Int_t nbins, Double_t xmin, Double_t xmax)
Initialize axis with fix bins.
Definition TAxis.cxx:790
virtual Int_t FindFixBin(Double_t x) const
Find bin number corresponding to abscissa x
Definition TAxis.cxx:422
void SaveAttributes(std::ostream &out, const char *name, const char *subname) override
Save axis attributes as C++ statement(s) on output stream out.
Definition TAxis.cxx:715
Int_t GetLast() const
Return last bin on the axis i.e.
Definition TAxis.cxx:473
virtual void SetLimits(Double_t xmin, Double_t xmax)
Definition TAxis.h:166
Double_t GetXmin() const
Definition TAxis.h:141
void Streamer(TBuffer &) override
Stream an object of class TAxis.
Definition TAxis.cxx:1224
Int_t GetNbins() const
Definition TAxis.h:127
virtual void GetLowEdge(Double_t *edge) const
Return an array with the low edge of all bins.
Definition TAxis.cxx:567
virtual void SetRange(Int_t first=0, Int_t last=0)
Set the viewing range for the axis using bin numbers.
Definition TAxis.cxx:1061
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width.
Definition TAxis.cxx:546
virtual Double_t GetBinUpEdge(Int_t bin) const
Return up edge of bin.
Definition TAxis.cxx:532
Int_t GetFirst() const
Return first bin on the axis i.e.
Definition TAxis.cxx:462
THashList * GetLabels() const
Definition TAxis.h:123
Using a TBrowser one can browse all ROOT objects.
Definition TBrowser.h:37
Buffer base class used for serializing objects.
Definition TBuffer.h:43
void * New(ENewType defConstructor=kClassNew, Bool_t quiet=kFALSE) const
Return a pointer to a newly allocated object of this class.
Definition TClass.cxx:5017
ROOT::NewFunc_t GetNew() const
Return the wrapper around new ThisClass().
Definition TClass.cxx:7549
Collection abstract base class.
Definition TCollection.h:65
virtual bool UseRWLock(Bool_t enable=true)
Set this collection to use a RW lock upon access, making it thread safe.
TObject * Clone(const char *newname="") const override
Make a clone of an collection using the Streamer facility.
virtual Int_t GetSize() const
Return the capacity of the collection, i.e.
TDirectory::TContext keeps track and restore the current directory.
Definition TDirectory.h:89
Describe directory structure in memory.
Definition TDirectory.h:45
virtual void Append(TObject *obj, Bool_t replace=kFALSE)
Append object to this directory.
virtual TObject * Remove(TObject *)
Remove an object from the in-memory list.
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition TEnv.cxx:503
1-Dim function class
Definition TF1.h:182
static void RejectPoint(Bool_t reject=kTRUE)
Static function to set the global flag to reject points the fgRejectPoint global flag is tested by al...
Definition TF1.cxx:3723
virtual TH1 * GetHistogram() const
Return a pointer to the histogram used to visualise the function Note that this histogram is managed ...
Definition TF1.cxx:1634
static TClass * Class()
virtual Int_t GetNpar() const
Definition TF1.h:446
virtual Double_t Integral(Double_t a, Double_t b, Double_t epsrel=1.e-12)
IntegralOneDim or analytical integral.
Definition TF1.cxx:2580
virtual void InitArgs(const Double_t *x, const Double_t *params)
Initialize parameters addresses.
Definition TF1.cxx:2530
virtual void GetRange(Double_t *xmin, Double_t *xmax) const
Return range of a generic N-D function.
Definition TF1.cxx:2329
virtual Double_t EvalPar(const Double_t *x, const Double_t *params=nullptr)
Evaluate function with given coordinates and parameters.
Definition TF1.cxx:1498
virtual void SetParLimits(Int_t ipar, Double_t parmin, Double_t parmax)
Set lower and upper limits for parameter ipar.
Definition TF1.cxx:3562
static Bool_t RejectedPoint()
See TF1::RejectPoint above.
Definition TF1.cxx:3732
virtual Double_t Eval(Double_t x, Double_t y=0, Double_t z=0, Double_t t=0) const
Evaluate this function.
Definition TF1.cxx:1446
virtual void SetParameter(Int_t param, Double_t value)
Definition TF1.h:608
virtual Bool_t IsInside(const Double_t *x) const
return kTRUE if the point is inside the function range
Definition TF1.h:567
A 2-Dim function with parameters.
Definition TF2.h:29
TF3 defines a 3D Function with Parameters.
Definition TF3.h:28
Provides an indirection to the TFitResult class and with a semantics identical to a TFitResult pointe...
1-D histogram with a byte per channel (see TH1 documentation)
Definition TH1.h:714
~TH1C() override
Destructor.
Definition TH1.cxx:9614
void SetBinsLength(Int_t n=-1) override
Set total number of bins including under/overflow Reallocate bin contents array.
Definition TH1.cxx:9670
TH1C & operator=(const TH1C &h1)
Operator =.
Definition TH1.cxx:9680
TH1C()
Constructor.
Definition TH1.cxx:9566
void Copy(TObject &hnew) const override
Copy this to newth1.
Definition TH1.cxx:9652
void AddBinContent(Int_t bin) override
Increment bin content by 1.
Definition TH1.cxx:9631
void Reset(Option_t *option="") override
Reset.
Definition TH1.cxx:9660
1-D histogram with a double per channel (see TH1 documentation)
Definition TH1.h:926
~TH1D() override
Destructor.
Definition TH1.cxx:10555
void SetBinsLength(Int_t n=-1) override
Set total number of bins including under/overflow Reallocate bin contents array.
Definition TH1.cxx:10589
void Copy(TObject &hnew) const override
Copy this to newth1.
Definition TH1.cxx:10571
TH1D()
Constructor.
Definition TH1.cxx:10490
TH1D & operator=(const TH1D &h1)
Operator =.
Definition TH1.cxx:10599
1-D histogram with a float per channel (see TH1 documentation)
Definition TH1.h:878
Double_t RetrieveBinContent(Int_t bin) const override
Raw retrieval of bin content on internal data structure see convention for numbering bins in TH1::Get...
Definition TH1.h:912
TH1F & operator=(const TH1F &h1)
Operator =.
Definition TH1.cxx:10419
void Copy(TObject &hnew) const override
Copy this to newth1.
Definition TH1.cxx:10391
void SetBinsLength(Int_t n=-1) override
Set total number of bins including under/overflow Reallocate bin contents array.
Definition TH1.cxx:10409
~TH1F() override
Destructor.
Definition TH1.cxx:10384
TH1F()
Constructor.
Definition TH1.cxx:10310
1-D histogram with an int per channel (see TH1 documentation)
Definition TH1.h:796
void SetBinsLength(Int_t n=-1) override
Set total number of bins including under/overflow Reallocate bin contents array.
Definition TH1.cxx:10041
void AddBinContent(Int_t bin) override
Increment bin content by 1.
Definition TH1.cxx:10002
~TH1I() override
Destructor.
Definition TH1.cxx:9985
TH1I()
Constructor.
Definition TH1.cxx:9937
void Copy(TObject &hnew) const override
Copy this to newth1.
Definition TH1.cxx:10023
TH1I & operator=(const TH1I &h1)
Operator =.
Definition TH1.cxx:10051
1-D histogram with a long64 per channel (see TH1 documentation)
Definition TH1.h:837
TH1L & operator=(const TH1L &h1)
Operator =.
Definition TH1.cxx:10238
void AddBinContent(Int_t bin) override
Increment bin content by 1.
Definition TH1.cxx:10189
void SetBinsLength(Int_t n=-1) override
Set total number of bins including under/overflow Reallocate bin contents array.
Definition TH1.cxx:10228
~TH1L() override
Destructor.
Definition TH1.cxx:10172
TH1L()
Constructor.
Definition TH1.cxx:10124
void Copy(TObject &hnew) const override
Copy this to newth1.
Definition TH1.cxx:10210
1-D histogram with a short per channel (see TH1 documentation)
Definition TH1.h:755
TH1S & operator=(const TH1S &h1)
Operator =.
Definition TH1.cxx:9865
void Copy(TObject &hnew) const override
Copy this to newth1.
Definition TH1.cxx:9837
TH1S()
Constructor.
Definition TH1.cxx:9751
void SetBinsLength(Int_t n=-1) override
Set total number of bins including under/overflow Reallocate bin contents array.
Definition TH1.cxx:9855
~TH1S() override
Destructor.
Definition TH1.cxx:9799
void AddBinContent(Int_t bin) override
Increment bin content by 1.
Definition TH1.cxx:9816
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:109
~TH1() override
Histogram default destructor.
Definition TH1.cxx:636
virtual void SetError(const Double_t *error)
Replace bin errors by values in array error.
Definition TH1.cxx:9067
virtual void SetDirectory(TDirectory *dir)
By default, when a histogram is created, it is added to the list of histogram objects in the current ...
Definition TH1.cxx:9053
virtual void FitPanel()
Display a panel with all histogram fit options.
Definition TH1.cxx:4319
Double_t * fBuffer
[fBufferSize] entry buffer
Definition TH1.h:169
virtual Int_t AutoP2FindLimits(Double_t min, Double_t max)
Buffer-based estimate of the histogram range using the power of 2 algorithm.
Definition TH1.cxx:1338
virtual Double_t GetEffectiveEntries() const
Number of effective entries of the histogram.
Definition TH1.cxx:4482
char * GetObjectInfo(Int_t px, Int_t py) const override
Redefines TObject::GetObjectInfo.
Definition TH1.cxx:4536
virtual void Smooth(Int_t ntimes=1, Option_t *option="")
Smooth bin contents of this histogram.
Definition TH1.cxx:6983
virtual Double_t GetBinCenter(Int_t bin) const
Return bin center for 1D histogram.
Definition TH1.cxx:9254
virtual void Rebuild(Option_t *option="")
Using the current bin info, recompute the arrays for contents and errors.
Definition TH1.cxx:7191
virtual void SetBarOffset(Float_t offset=0.25)
Set the bar offset as fraction of the bin width for drawing mode "B".
Definition TH1.h:612
static Bool_t fgStatOverflows
! Flag to use under/overflows in statistics
Definition TH1.h:178
virtual Int_t FindLastBinAbove(Double_t threshold=0, Int_t axis=1, Int_t firstBin=1, Int_t lastBin=-1) const
Find last bin with content > threshold for axis (1=x, 2=y, 3=z) if no bins with content > threshold i...
Definition TH1.cxx:3831
TAxis * GetZaxis()
Definition TH1.h:573
Int_t DistancetoPrimitive(Int_t px, Int_t py) override
Compute distance from point px,py to a line.
Definition TH1.cxx:2835
virtual Bool_t Multiply(TF1 *f1, Double_t c1=1)
Performs the operation:
Definition TH1.cxx:6110
@ kXaxis
Definition TH1.h:123
@ kNoAxis
NOTE: Must always be 0 !!!
Definition TH1.h:122
@ kZaxis
Definition TH1.h:125
@ kYaxis
Definition TH1.h:124
Int_t fNcells
Number of bins(1D), cells (2D) +U/Overflows.
Definition TH1.h:150
virtual void GetStats(Double_t *stats) const
fill the array stats from the contents of this histogram The array stats must be correctly dimensione...
Definition TH1.cxx:7925
virtual void Normalize(Option_t *option="")
Normalize a histogram to its integral or to its maximum.
Definition TH1.cxx:6272
void Copy(TObject &hnew) const override
Copy this histogram structure to newth1.
Definition TH1.cxx:2683
void SetTitle(const char *title) override
Change/set the title.
Definition TH1.cxx:6815
Double_t fTsumw
Total Sum of weights.
Definition TH1.h:157
virtual Float_t GetBarWidth() const
Definition TH1.h:501
Double_t fTsumw2
Total Sum of squares of weights.
Definition TH1.h:158
static void StatOverflows(Bool_t flag=kTRUE)
if flag=kTRUE, underflows and overflows are used by the Fill functions in the computation of statisti...
Definition TH1.cxx:7029
virtual Float_t GetBarOffset() const
Definition TH1.h:500
Double_t GetSumOfAllWeights(const bool includeOverflow, Double_t *sumWeightSquare=nullptr) const
Return the sum of all weights and optionally also the sum of weight squares.
Definition TH1.cxx:8018
TList * fFunctions
->Pointer to list of functions (fits and user)
Definition TH1.h:167
static Bool_t fgAddDirectory
! Flag to add histograms to the directory
Definition TH1.h:177
static TClass * Class()
static Int_t GetDefaultBufferSize()
Static function return the default buffer size for automatic histograms the parameter fgBufferSize ma...
Definition TH1.cxx:4440
virtual Double_t DoIntegral(Int_t ix1, Int_t ix2, Int_t iy1, Int_t iy2, Int_t iz1, Int_t iz2, Double_t &err, Option_t *opt, Bool_t doerr=kFALSE) const
Internal function compute integral and optionally the error between the limits specified by the bin n...
Definition TH1.cxx:8089
Double_t fTsumwx2
Total Sum of weight*X*X.
Definition TH1.h:160
virtual Double_t GetStdDev(Int_t axis=1) const
Returns the Standard Deviation (Sigma).
Definition TH1.cxx:7699
TH1()
Histogram default constructor.
Definition TH1.cxx:608
static TH1 * TransformHisto(TVirtualFFT *fft, TH1 *h_output, Option_t *option)
For a given transform (first parameter), fills the histogram (second parameter) with the transform ou...
Definition TH1.cxx:9432
void UseCurrentStyle() override
Copy current attributes from/to current style.
Definition TH1.cxx:7561
virtual void LabelsOption(Option_t *option="h", Option_t *axis="X")
Sort bins with labels or set option(s) to draw axis with labels.
Definition TH1.cxx:5443
virtual Int_t GetNbinsY() const
Definition TH1.h:542
Short_t fBarOffset
(1000*offset) for bar charts or legos
Definition TH1.h:154
virtual Double_t Chi2TestX(const TH1 *h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option="UU", Double_t *res=nullptr) const
The computation routine of the Chisquare test.
Definition TH1.cxx:2064
static bool CheckBinLimits(const TAxis *a1, const TAxis *a2)
Check bin limits.
Definition TH1.cxx:1536
virtual Double_t GetBinError(Int_t bin) const
Return value of error associated to bin number bin.
Definition TH1.cxx:9176
static Int_t FitOptionsMake(Option_t *option, Foption_t &Foption)
Decode string choptin and fill fitOption structure.
Definition TH1.cxx:4711
virtual Int_t GetNbinsZ() const
Definition TH1.h:543
virtual Double_t GetNormFactor() const
Definition TH1.h:545
virtual Double_t GetMean(Int_t axis=1) const
For axis = 1,2 or 3 returns the mean value of the histogram along X,Y or Z axis.
Definition TH1.cxx:7627
virtual Double_t GetSkewness(Int_t axis=1) const
Definition TH1.cxx:7763
virtual void ClearUnderflowAndOverflow()
Remove all the content from the underflow and overflow bins, without changing the number of entries A...
Definition TH1.cxx:2518
virtual void FillRandom(TF1 *f1, Int_t ntimes=5000, TRandom *rng=nullptr)
Definition TH1.cxx:3556
virtual Double_t GetContourLevelPad(Int_t level) const
Return the value of contour number "level" in Pad coordinates.
Definition TH1.cxx:8552
virtual TH1 * DrawNormalized(Option_t *option="", Double_t norm=1) const
Draw a normalized copy of this histogram.
Definition TH1.cxx:3172
@ kNeutral
Adapt to the global flag.
Definition TH1.h:133
virtual Int_t GetDimension() const
Definition TH1.h:527
void Streamer(TBuffer &) override
Stream a class object.
Definition TH1.cxx:7037
static void AddDirectory(Bool_t add=kTRUE)
Sets the flag controlling the automatic add of histograms in memory.
Definition TH1.cxx:1289
@ kIsAverage
Bin contents are average (used by Add)
Definition TH1.h:409
@ kUserContour
User specified contour levels.
Definition TH1.h:404
@ kNoStats
Don't draw stats box.
Definition TH1.h:403
@ kAutoBinPTwo
different than 1.
Definition TH1.h:412
@ kIsNotW
Histogram is forced to be not weighted even when the histogram is filled with weighted.
Definition TH1.h:410
@ kIsHighlight
bit set if histo is highlight
Definition TH1.h:413
virtual void SetContourLevel(Int_t level, Double_t value)
Set value for one contour level.
Definition TH1.cxx:8638
virtual Bool_t CanExtendAllAxes() const
Returns true if all axes are extendable.
Definition TH1.cxx:6730
TDirectory * fDirectory
! Pointer to directory holding this histogram
Definition TH1.h:170
virtual void Reset(Option_t *option="")
Reset this histogram: contents, errors, etc.
Definition TH1.cxx:7207
void SetNameTitle(const char *name, const char *title) override
Change the name and title of this histogram.
Definition TH1.cxx:9090
TAxis * GetXaxis()
Definition TH1.h:571
virtual void GetBinXYZ(Int_t binglobal, Int_t &binx, Int_t &biny, Int_t &binz) const
Return binx, biny, binz corresponding to the global bin number globalbin see TH1::GetBin function abo...
Definition TH1.cxx:5033
TH1 * GetCumulative(Bool_t forward=kTRUE, const char *suffix="_cumulative") const
Return a pointer to a histogram containing the cumulative content.
Definition TH1.cxx:2628
static Double_t AutoP2GetPower2(Double_t x, Bool_t next=kTRUE)
Auxiliary function to get the power of 2 next (larger) or previous (smaller) a given x.
Definition TH1.cxx:1303
virtual Int_t GetNcells() const
Definition TH1.h:544
virtual Int_t ShowPeaks(Double_t sigma=2, Option_t *option="", Double_t threshold=0.05)
Interface to TSpectrum::Search.
Definition TH1.cxx:9414
static Bool_t RecomputeAxisLimits(TAxis &destAxis, const TAxis &anAxis)
Finds new limits for the axis for the Merge function.
Definition TH1.cxx:5969
virtual Double_t GetSumOfWeights() const
Return the sum of weights across all bins excluding under/overflows.
Definition TH1.h:559
virtual void PutStats(Double_t *stats)
Replace current statistics with the values in array stats.
Definition TH1.cxx:7976
TVirtualHistPainter * GetPainter(Option_t *option="")
Return pointer to painter.
Definition TH1.cxx:4545
TObject * FindObject(const char *name) const override
Search object named name in the list of functions.
Definition TH1.cxx:3891
void Print(Option_t *option="") const override
Print some global quantities for this histogram.
Definition TH1.cxx:7113
static Bool_t GetDefaultSumw2()
Return kTRUE if TH1::Sumw2 must be called when creating new histograms.
Definition TH1.cxx:4449
virtual Int_t FindFirstBinAbove(Double_t threshold=0, Int_t axis=1, Int_t firstBin=1, Int_t lastBin=-1) const
Find first bin with content > threshold for axis (1=x, 2=y, 3=z) if no bins with content > threshold ...
Definition TH1.cxx:3768
virtual TFitResultPtr Fit(const char *formula, Option_t *option="", Option_t *goption="", Double_t xmin=0, Double_t xmax=0)
Fit histogram with function fname.
Definition TH1.cxx:3933
virtual Int_t GetBin(Int_t binx, Int_t biny=0, Int_t binz=0) const
Return Global bin number corresponding to binx,y,z.
Definition TH1.cxx:5020
virtual Double_t GetMaximum(Double_t maxval=FLT_MAX) const
Return maximum value smaller than maxval of bins in the range, unless the value has been overridden b...
Definition TH1.cxx:8661
virtual Int_t GetNbinsX() const
Definition TH1.h:541
virtual void SetMaximum(Double_t maximum=-1111)
Definition TH1.h:652
virtual TH1 * FFT(TH1 *h_output, Option_t *option)
This function allows to do discrete Fourier transforms of TH1 and TH2.
Definition TH1.cxx:3312
virtual void LabelsInflate(Option_t *axis="X")
Double the number of bins for axis.
Definition TH1.cxx:5376
virtual TH1 * ShowBackground(Int_t niter=20, Option_t *option="same")
This function calculates the background spectrum in this histogram.
Definition TH1.cxx:9400
static Bool_t SameLimitsAndNBins(const TAxis &axis1, const TAxis &axis2)
Same limits and bins.
Definition TH1.cxx:5959
virtual Bool_t Add(TF1 *h1, Double_t c1=1, Option_t *option="")
Performs the operation: this = this + c1*f1 if errors are defined (see TH1::Sumw2),...
Definition TH1.cxx:819
Double_t fMaximum
Maximum value for plotting.
Definition TH1.h:161
Int_t fBufferSize
fBuffer size
Definition TH1.h:168
TString ProvideSaveName(Option_t *option, Bool_t testfdir=kFALSE)
Provide variable name for histogram for saving as primitive Histogram pointer has by default the hist...
Definition TH1.cxx:7346
virtual Double_t IntegralAndError(Int_t binx1, Int_t binx2, Double_t &err, Option_t *option="") const
Return integral of bin contents in range [binx1,binx2] and its error.
Definition TH1.cxx:8080
Int_t fDimension
! Histogram dimension (1, 2 or 3 dim)
Definition TH1.h:171
virtual void SetBinError(Int_t bin, Double_t error)
Set the bin Error Note that this resets the bin eror option to be of Normal Type and for the non-empt...
Definition TH1.cxx:9319
EBinErrorOpt fBinStatErrOpt
Option for bin statistical errors.
Definition TH1.h:174
static Int_t fgBufferSize
! Default buffer size for automatic histograms
Definition TH1.h:176
virtual void SetBinsLength(Int_t=-1)
Definition TH1.h:628
Double_t fNormFactor
Normalization factor.
Definition TH1.h:163
@ kFullyConsistent
Definition TH1.h:139
@ kDifferentNumberOfBins
Definition TH1.h:143
@ kDifferentDimensions
Definition TH1.h:144
@ kDifferentBinLimits
Definition TH1.h:141
@ kDifferentAxisLimits
Definition TH1.h:142
@ kDifferentLabels
Definition TH1.h:140
virtual Int_t Fill(Double_t x)
Increment bin with abscissa X by 1.
Definition TH1.cxx:3372
TAxis * GetYaxis()
Definition TH1.h:572
TArrayD fContour
Array to display contour levels.
Definition TH1.h:164
virtual Double_t GetBinErrorLow(Int_t bin) const
Return lower error associated to bin number bin.
Definition TH1.cxx:9192
void Browse(TBrowser *b) override
Browse the Histogram object.
Definition TH1.cxx:755
virtual void SetContent(const Double_t *content)
Replace bin contents by the contents of array content.
Definition TH1.cxx:8510
void Draw(Option_t *option="") override
Draw this histogram with options.
Definition TH1.cxx:3076
virtual void SavePrimitiveHelp(std::ostream &out, const char *hname, Option_t *option="")
Helper function for the SavePrimitive functions from TH1 or classes derived from TH1,...
Definition TH1.cxx:7473
Short_t fBarWidth
(1000*width) for bar charts or legos
Definition TH1.h:155
virtual Double_t GetBinErrorSqUnchecked(Int_t bin) const
Definition TH1.h:705
Int_t AxisChoice(Option_t *axis) const
Choose an axis according to "axis".
Definition Haxis.cxx:14
virtual void SetMinimum(Double_t minimum=-1111)
Definition TH1.h:653
Bool_t IsBinUnderflow(Int_t bin, Int_t axis=0) const
Return true if the bin is underflow.
Definition TH1.cxx:5275
void SavePrimitive(std::ostream &out, Option_t *option="") override
Save primitive as a C++ statement(s) on output stream out.
Definition TH1.cxx:7368
static bool CheckBinLabels(const TAxis *a1, const TAxis *a2)
Check that axis have same labels.
Definition TH1.cxx:1563
virtual Double_t Interpolate(Double_t x) const
Given a point x, approximates the value via linear interpolation based on the two nearest bin centers...
Definition TH1.cxx:5176
static void SetDefaultSumw2(Bool_t sumw2=kTRUE)
When this static function is called with sumw2=kTRUE, all new histograms will automatically activate ...
Definition TH1.cxx:6797
virtual void SetBuffer(Int_t bufsize, Option_t *option="")
Set the maximum number of entries to be kept in the buffer.
Definition TH1.cxx:8570
Bool_t IsBinOverflow(Int_t bin, Int_t axis=0) const
Return true if the bin is overflow.
Definition TH1.cxx:5243
UInt_t GetAxisLabelStatus() const
Internal function used in TH1::Fill to see which axis is full alphanumeric, i.e.
Definition TH1.cxx:6769
Double_t * fIntegral
! Integral of bins used by GetRandom
Definition TH1.h:172
Double_t fMinimum
Minimum value for plotting.
Definition TH1.h:162
virtual Double_t Integral(Option_t *option="") const
Return integral of bin contents.
Definition TH1.cxx:8053
static void SetDefaultBufferSize(Int_t bufsize=1000)
Static function to set the default buffer size for automatic histograms.
Definition TH1.cxx:6787
virtual void SetBinContent(Int_t bin, Double_t content)
Set bin content see convention for numbering bins in TH1::GetBin In case the bin number is greater th...
Definition TH1.cxx:9335
virtual void DirectoryAutoAdd(TDirectory *)
Perform the automatic addition of the histogram to the given directory.
Definition TH1.cxx:2813
virtual void GetLowEdge(Double_t *edge) const
Fill array with low edge of bins for 1D histogram Better to use h1.GetXaxis()->GetLowEdge(edge)
Definition TH1.cxx:9300
virtual Double_t GetBinLowEdge(Int_t bin) const
Return bin lower edge for 1D histogram.
Definition TH1.cxx:9265
void Build()
Creates histogram basic data structure.
Definition TH1.cxx:764
virtual Double_t GetEntries() const
Return the current number of entries.
Definition TH1.cxx:4457
virtual Double_t RetrieveBinContent(Int_t bin) const =0
Raw retrieval of bin content on internal data structure see convention for numbering bins in TH1::Get...
virtual TF1 * GetFunction(const char *name) const
Return pointer to function with name.
Definition TH1.cxx:9164
virtual TH1 * Rebin(Int_t ngroup=2, const char *newname="", const Double_t *xbins=nullptr)
Rebin this histogram.
Definition TH1.cxx:6369
virtual Int_t BufferFill(Double_t x, Double_t w)
accumulate arguments in buffer.
Definition TH1.cxx:1501
virtual Double_t GetBinWithContent(Double_t c, Int_t &binx, Int_t firstx=0, Int_t lastx=0, Double_t maxdiff=0) const
Compute first binx in the range [firstx,lastx] for which diff = abs(bin_content-c) <= maxdiff.
Definition TH1.cxx:5147
virtual UInt_t SetCanExtend(UInt_t extendBitMask)
Make the histogram axes extendable / not extendable according to the bit mask returns the previous bi...
Definition TH1.cxx:6743
TList * GetListOfFunctions() const
Definition TH1.h:488
void SetName(const char *name) override
Change the name of this histogram.
Definition TH1.cxx:9076
virtual TH1 * DrawCopy(Option_t *option="", const char *name_postfix="_copy") const
Copy this histogram and Draw in the current pad.
Definition TH1.cxx:3141
virtual Double_t GetRandom(TRandom *rng=nullptr, Option_t *option="") const
Return a random number distributed according the histogram bin contents.
Definition TH1.cxx:5070
Bool_t IsEmpty() const
Check if a histogram is empty (this is a protected method used mainly by TH1Merger )
Definition TH1.cxx:5225
virtual Double_t GetMeanError(Int_t axis=1) const
Return standard error of mean of this histogram along the X axis.
Definition TH1.cxx:7667
void Paint(Option_t *option="") override
Control routine to paint any kind of histograms.
Definition TH1.cxx:6300
virtual Double_t AndersonDarlingTest(const TH1 *h2, Option_t *option="") const
Statistical test of compatibility in shape between this histogram and h2, using the Anderson-Darling ...
Definition TH1.cxx:8174
virtual void ResetStats()
Reset the statistics including the number of entries and replace with values calculated from bin cont...
Definition TH1.cxx:7994
virtual void SetBinErrorOption(EBinErrorOpt type)
Definition TH1.h:629
virtual void DrawPanel()
Display a panel with all histogram drawing options.
Definition TH1.cxx:3203
virtual Double_t Chisquare(TF1 *f1, Option_t *option="") const
Compute and return the chisquare of this histogram with respect to a function The chisquare is comput...
Definition TH1.cxx:2497
virtual Double_t Chi2Test(const TH1 *h2, Option_t *option="UU", Double_t *res=nullptr) const
test for comparing weighted and unweighted histograms.
Definition TH1.cxx:2005
virtual void DoFillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride=1)
Internal method to fill histogram content from a vector called directly by TH1::BufferEmpty.
Definition TH1.cxx:3501
virtual void GetMinimumAndMaximum(Double_t &min, Double_t &max) const
Retrieve the minimum and maximum values in the histogram.
Definition TH1.cxx:8847
@ kNstat
Size of statistics data (up to TProfile3D)
Definition TH1.h:422
virtual Int_t GetMaximumBin() const
Return location of bin with maximum value in the range.
Definition TH1.cxx:8693
static Int_t AutoP2GetBins(Int_t n)
Auxiliary function to get the next power of 2 integer value larger then n.
Definition TH1.cxx:1316
Double_t fEntries
Number of entries.
Definition TH1.h:156
virtual Long64_t Merge(TCollection *list)
Definition TH1.h:592
virtual void SetColors(Color_t linecolor=-1, Color_t markercolor=-1, Color_t fillcolor=-1)
Shortcut to set the three histogram colors with a single call.
Definition TH1.cxx:4501
void ExecuteEvent(Int_t event, Int_t px, Int_t py) override
Execute action corresponding to one event.
Definition TH1.cxx:3268
virtual Double_t * GetIntegral()
Return a pointer to the array of bins integral.
Definition TH1.cxx:2598
TAxis fZaxis
Z axis descriptor.
Definition TH1.h:153
EStatOverflows fStatOverflows
Per object flag to use under/overflows in statistics.
Definition TH1.h:175
TClass * IsA() const override
Definition TH1.h:693
virtual void FillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride=1)
Fill this histogram with an array x and weights w.
Definition TH1.cxx:3475
static bool CheckEqualAxes(const TAxis *a1, const TAxis *a2)
Check that the axis are the same.
Definition TH1.cxx:1606
@ kPoisson2
Errors from Poisson interval at 95% CL (~ 2 sigma)
Definition TH1.h:117
@ kNormal
Errors with Normal (Wald) approximation: errorUp=errorLow= sqrt(N)
Definition TH1.h:115
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
Definition TH1.cxx:5122
virtual Int_t GetContour(Double_t *levels=nullptr)
Return contour values into array levels if pointer levels is non zero.
Definition TH1.cxx:8523
TAxis fXaxis
X axis descriptor.
Definition TH1.h:151
virtual Bool_t IsHighlight() const
Definition TH1.h:585
virtual void ExtendAxis(Double_t x, TAxis *axis)
Histogram is resized along axis such that x is in the axis range.
Definition TH1.cxx:6598
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width for 1D histogram.
Definition TH1.cxx:9276
TArrayD fSumw2
Array of sum of squares of weights.
Definition TH1.h:165
TH1 * GetAsymmetry(TH1 *h2, Double_t c2=1, Double_t dc2=0)
Return a histogram containing the asymmetry of this histogram with h2, where the asymmetry is defined...
Definition TH1.cxx:4374
virtual Double_t GetContourLevel(Int_t level) const
Return value of contour number level.
Definition TH1.cxx:8542
virtual void SetContour(Int_t nlevels, const Double_t *levels=nullptr)
Set the number and values of contour levels.
Definition TH1.cxx:8599
virtual void SetHighlight(Bool_t set=kTRUE)
Set highlight (enable/disable) mode for the histogram by default highlight mode is disable.
Definition TH1.cxx:4516
virtual Double_t GetBinErrorUp(Int_t bin) const
Return upper error associated to bin number bin.
Definition TH1.cxx:9223
virtual void Scale(Double_t c1=1, Option_t *option="")
Multiply this histogram by a constant c1.
Definition TH1.cxx:6698
virtual Int_t GetMinimumBin() const
Return location of bin with minimum value in the range.
Definition TH1.cxx:8781
virtual Double_t ComputeIntegral(Bool_t onlyPositive=false, Option_t *option="")
Compute integral (normalized cumulative sum of bins) w/o under/overflows The result is stored in fInt...
Definition TH1.cxx:2543
virtual Int_t GetSumw2N() const
Definition TH1.h:562
virtual Int_t FindBin(Double_t x, Double_t y=0, Double_t z=0)
Return Global bin number corresponding to x,y,z.
Definition TH1.cxx:3706
Bool_t GetStatOverflowsBehaviour() const
Definition TH1.h:391
void SaveAs(const char *filename="hist", Option_t *option="") const override
Save the histogram as .csv, .tsv or .txt.
Definition TH1.cxx:7285
virtual Int_t GetQuantiles(Int_t n, Double_t *xp, const Double_t *p=nullptr)
Compute Quantiles for this histogram.
Definition TH1.cxx:4649
virtual void AddBinContent(Int_t bin)=0
Increment bin content by 1.
TObject * Clone(const char *newname="") const override
Make a complete copy of the underlying object.
Definition TH1.cxx:2764
virtual Double_t GetStdDevError(Int_t axis=1) const
Return error of standard deviation estimation for Normal distribution.
Definition TH1.cxx:7747
virtual Bool_t Divide(TF1 *f1, Double_t c1=1)
Performs the operation: this = this/(c1*f1) if errors are defined (see TH1::Sumw2),...
Definition TH1.cxx:2852
virtual Double_t GetMinimum(Double_t minval=-FLT_MAX) const
Return minimum value larger than minval of bins in the range, unless the value has been overridden by...
Definition TH1.cxx:8751
int LoggedInconsistency(const char *name, const TH1 *h1, const TH1 *h2, bool useMerge=false) const
Definition TH1.cxx:876
static bool CheckConsistentSubAxes(const TAxis *a1, Int_t firstBin1, Int_t lastBin1, const TAxis *a2, Int_t firstBin2=0, Int_t lastBin2=0)
Check that two sub axis are the same.
Definition TH1.cxx:1635
static Int_t CheckConsistency(const TH1 *h1, const TH1 *h2)
Check histogram compatibility.
Definition TH1.cxx:1674
void RecursiveRemove(TObject *obj) override
Recursively remove object from the list of functions.
Definition TH1.cxx:6670
TAxis fYaxis
Y axis descriptor.
Definition TH1.h:152
virtual Double_t KolmogorovTest(const TH1 *h2, Option_t *option="") const
Statistical test of compatibility in shape between this histogram and h2, using Kolmogorov test.
Definition TH1.cxx:8290
static void SmoothArray(Int_t NN, Double_t *XX, Int_t ntimes=1)
Smooth array xx, translation of Hbook routine hsmoof.F.
Definition TH1.cxx:6872
virtual void GetCenter(Double_t *center) const
Fill array with center of bins for 1D histogram Better to use h1.GetXaxis()->GetCenter(center)
Definition TH1.cxx:9287
TVirtualHistPainter * fPainter
! Pointer to histogram painter
Definition TH1.h:173
virtual void SetBins(Int_t nx, Double_t xmin, Double_t xmax)
Redefine x axis parameters.
Definition TH1.cxx:8883
virtual Int_t FindFixBin(Double_t x, Double_t y=0, Double_t z=0) const
Return Global bin number corresponding to x,y,z.
Definition TH1.cxx:3739
virtual void Sumw2(Bool_t flag=kTRUE)
Create structure to store sum of squares of weights.
Definition TH1.cxx:9136
virtual void SetEntries(Double_t n)
Definition TH1.h:639
virtual Bool_t FindNewAxisLimits(const TAxis *axis, const Double_t point, Double_t &newMin, Double_t &newMax)
finds new limits for the axis so that point is within the range and the limits are compatible with th...
Definition TH1.cxx:6554
static bool CheckAxisLimits(const TAxis *a1, const TAxis *a2)
Check that the axis limits of the histograms are the same.
Definition TH1.cxx:1592
static Bool_t AddDirectoryStatus()
Static function: cannot be inlined on Windows/NT.
Definition TH1.cxx:747
static Bool_t fgDefaultSumw2
! Flag to call TH1::Sumw2 automatically at histogram creation time
Definition TH1.h:179
static void SavePrimitiveFunctions(std::ostream &out, const char *varname, TList *lst)
Save list of functions Also can be used by TGraph classes.
Definition TH1.cxx:7527
virtual void UpdateBinContent(Int_t bin, Double_t content)=0
Raw update of bin content on internal data structure see convention for numbering bins in TH1::GetBin...
Double_t fTsumwx
Total Sum of weight*X.
Definition TH1.h:159
virtual void LabelsDeflate(Option_t *axis="X")
Reduce the number of bins for the axis passed in the option to the number of bins having a label.
Definition TH1.cxx:5306
TString fOption
Histogram options.
Definition TH1.h:166
virtual void Eval(TF1 *f1, Option_t *option="")
Evaluate function f1 at the center of bins of this histogram.
Definition TH1.cxx:3220
virtual void SetBarWidth(Float_t width=0.5)
Set the width of bars as fraction of the bin width for drawing mode "B".
Definition TH1.h:613
virtual Int_t BufferEmpty(Int_t action=0)
Fill histogram with all entries in the buffer.
Definition TH1.cxx:1409
virtual void SetStats(Bool_t stats=kTRUE)
Set statistics option on/off.
Definition TH1.cxx:9106
virtual Double_t GetKurtosis(Int_t axis=1) const
Definition TH1.cxx:7836
2-D histogram with a double per channel (see TH1 documentation)
Definition TH2.h:400
static THLimitsFinder * GetLimitsFinder()
Return pointer to the current finder.
THashList implements a hybrid collection class consisting of a hash table and a list to store TObject...
Definition THashList.h:34
void Clear(Option_t *option="") override
Remove all objects from the list.
A doubly linked list.
Definition TList.h:38
void Streamer(TBuffer &) override
Stream all objects in the collection to or from the I/O buffer.
Definition TList.cxx:1323
TObject * FindObject(const char *name) const override
Find an object in this list using its name.
Definition TList.cxx:708
void RecursiveRemove(TObject *obj) override
Remove object from this collection and recursively remove the object from all other objects (and coll...
Definition TList.cxx:894
void Add(TObject *obj) override
Definition TList.h:81
TObject * Remove(TObject *obj) override
Remove object from the list.
Definition TList.cxx:952
TObject * First() const override
Return the first object in the list. Returns 0 when list is empty.
Definition TList.cxx:789
void Delete(Option_t *option="") override
Remove all objects from the list AND delete all heap based objects.
Definition TList.cxx:600
TObject * At(Int_t idx) const override
Returns the object at position idx. Returns 0 if idx is out of range.
Definition TList.cxx:487
The TNamed class is the base class for all named ROOT classes.
Definition TNamed.h:29
void Copy(TObject &named) const override
Copy this to obj.
Definition TNamed.cxx:93
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition TNamed.cxx:173
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
void Streamer(TBuffer &) override
Stream an object of class TObject.
const char * GetTitle() const override
Returns title of object.
Definition TNamed.h:50
TString fTitle
Definition TNamed.h:33
TString fName
Definition TNamed.h:32
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition TNamed.cxx:149
Mother of all ROOT objects.
Definition TObject.h:42
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:458
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition TObject.h:204
virtual UInt_t GetUniqueID() const
Return the unique object id.
Definition TObject.cxx:476
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:226
virtual void UseCurrentStyle()
Set current style settings in this object This function is called when either TCanvas::UseCurrentStyl...
Definition TObject.cxx:903
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition TObject.cxx:1075
virtual void AppendPad(Option_t *option="")
Append graphics object to current pad.
Definition TObject.cxx:203
virtual void SaveAs(const char *filename="", Option_t *option="") const
Save this object in the file specified by filename.
Definition TObject.cxx:706
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition TObject.cxx:882
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition TObject.cxx:544
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition TObject.cxx:1089
virtual void SetUniqueID(UInt_t uid)
Set the unique object id.
Definition TObject.cxx:893
static void SavePrimitiveDraw(std::ostream &out, const char *variable_name, Option_t *option=nullptr)
Save invocation of primitive Draw() method Skipped if option contains "nodraw" string.
Definition TObject.cxx:840
static TString SavePrimitiveVector(std::ostream &out, const char *prefix, Int_t len, Double_t *arr, Int_t flag=0)
Save array in the output stream "out" as vector.
Definition TObject.cxx:791
void ResetBit(UInt_t f)
Definition TObject.h:203
@ kCanDelete
if object in a list can be deleted
Definition TObject.h:70
@ kInvalidObject
if object ctor succeeded but object should not be used
Definition TObject.h:80
@ kMustCleanup
if object destructor must call RecursiveRemove()
Definition TObject.h:72
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition TObject.cxx:1063
Longptr_t ExecPlugin(int nargs)
Int_t LoadPlugin()
Load the plugin library for this handler.
static TClass * Class()
This is the base class for the ROOT Random number generators.
Definition TRandom.h:27
Double_t Rndm() override
Machine independent random number generator.
Definition TRandom.cxx:558
virtual Double_t PoissonD(Double_t mean)
Generates a random number according to a Poisson law.
Definition TRandom.cxx:460
virtual ULong64_t Poisson(Double_t mean)
Generates a random integer N according to a Poisson law.
Definition TRandom.cxx:403
Basic string class.
Definition TString.h:138
Ssiz_t Length() const
Definition TString.h:425
void ToLower()
Change string to lower-case.
Definition TString.cxx:1189
TString & ReplaceSpecialCppChars()
Find special characters which are typically used in printf() calls and replace them by appropriate es...
Definition TString.cxx:1121
const char * Data() const
Definition TString.h:384
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition TString.h:713
@ kIgnoreCase
Definition TString.h:285
void ToUpper()
Change string to upper case.
Definition TString.cxx:1202
Bool_t IsNull() const
Definition TString.h:422
virtual void Streamer(TBuffer &)
Stream a string object.
Definition TString.cxx:1418
TString & Append(const char *cs)
Definition TString.h:581
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString.
Definition TString.cxx:2384
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:641
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition TString.h:660
Int_t GetOptStat() const
Definition TStyle.h:247
void SetOptStat(Int_t stat=1)
The type of information printed in the histogram statistics box can be selected via the parameter mod...
Definition TStyle.cxx:1641
void SetHistFillColor(Color_t color=1)
Definition TStyle.h:383
Color_t GetHistLineColor() const
Definition TStyle.h:235
Bool_t IsReading() const
Definition TStyle.h:300
Float_t GetBarOffset() const
Definition TStyle.h:184
void SetHistLineStyle(Style_t styl=0)
Definition TStyle.h:386
Style_t GetHistFillStyle() const
Definition TStyle.h:236
Color_t GetHistFillColor() const
Definition TStyle.h:234
Float_t GetBarWidth() const
Definition TStyle.h:185
Bool_t GetCanvasPreferGL() const
Definition TStyle.h:189
void SetHistLineColor(Color_t color=1)
Definition TStyle.h:384
void SetBarOffset(Float_t baroff=0.5)
Definition TStyle.h:339
Style_t GetHistLineStyle() const
Definition TStyle.h:237
void SetBarWidth(Float_t barwidth=0.5)
Definition TStyle.h:340
void SetHistFillStyle(Style_t styl=0)
Definition TStyle.h:385
Width_t GetHistLineWidth() const
Definition TStyle.h:238
Int_t GetOptFit() const
Definition TStyle.h:246
void SetHistLineWidth(Width_t width=1)
Definition TStyle.h:387
TVectorT.
Definition TVectorT.h:29
TVirtualFFT is an interface class for Fast Fourier Transforms.
Definition TVirtualFFT.h:88
static TVirtualFFT * FFT(Int_t ndim, Int_t *n, Option_t *option)
Returns a pointer to the FFT of requested size and type.
static TVirtualFFT * SineCosine(Int_t ndim, Int_t *n, Int_t *r2rkind, Option_t *option)
Returns a pointer to a sine or cosine transform of requested size and kind.
Abstract Base Class for Fitting.
static TVirtualFitter * GetFitter()
static: return the current Fitter
Abstract interface to a histogram painter.
virtual void DrawPanel()=0
Int_t DistancetoPrimitive(Int_t px, Int_t py) override=0
Computes distance from point (px,py) to the object.
void ExecuteEvent(Int_t event, Int_t px, Int_t py) override=0
Execute action corresponding to an event at (px,py).
virtual void SetHighlight()=0
static TVirtualHistPainter * HistPainter(TH1 *obj)
Static function returning a pointer to the current histogram painter.
void Paint(Option_t *option="") override=0
This method must be overridden if a class wants to paint itself.
double gamma_quantile_c(double z, double alpha, double theta)
Inverse ( ) of the cumulative distribution function of the upper tail of the gamma distribution (gamm...
double gamma_quantile(double z, double alpha, double theta)
Inverse ( ) of the cumulative distribution function of the lower tail of the gamma distribution (gamm...
const Double_t sigma
Double_t y[n]
Definition legend1.C:17
return c1
Definition legend1.C:41
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
TH1F * h1
Definition legend1.C:5
TF1 * f1
Definition legend1.C:11
return c2
Definition legend2.C:14
R__ALWAYS_INLINE bool HasBeenDeleted(const TObject *obj)
Check if the TObject's memory has been deleted.
Definition TObject.h:407
TFitResultPtr FitObject(TH1 *h1, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption, const char *goption, ROOT::Fit::DataRange &range)
fitting function for a TH1 (called from TH1::Fit)
Definition HFitImpl.cxx:977
double Chisquare(const TH1 &h1, TF1 &f1, bool useRange, EChisquareType type)
compute the chi2 value for an histogram given a function (see TH1::Chisquare for the documentation)
void FitOptionsMake(EFitObjectType type, const char *option, Foption_t &fitOption)
Decode list of options into fitOption.
Definition HFitImpl.cxx:685
void FillData(BinData &dv, const TH1 *hist, TF1 *func=nullptr)
fill the data vector from a TH1.
R__EXTERN TVirtualRWMutex * gCoreMutex
Bool_t IsNaN(Double_t x)
Definition TMath.h:903
Int_t Nint(T x)
Round to nearest integer. Rounds half integers to the nearest even integer.
Definition TMath.h:704
Short_t Max(Short_t a, Short_t b)
Returns the largest of a and b.
Definition TMathBase.h:249
Double_t Prob(Double_t chi2, Int_t ndf)
Computation of the probability for a certain Chi-squared (chi2) and number of degrees of freedom (ndf...
Definition TMath.cxx:637
Double_t Median(Long64_t n, const T *a, const Double_t *w=nullptr, Long64_t *work=nullptr)
Same as RMS.
Definition TMath.h:1359
Double_t QuietNaN()
Returns a quiet NaN as defined by IEEE 754.
Definition TMath.h:913
Double_t Floor(Double_t x)
Rounds x downward, returning the largest integral value that is not greater than x.
Definition TMath.h:691
Double_t ATan(Double_t)
Returns the principal value of the arc tangent of x, expressed in radians.
Definition TMath.h:651
Double_t Ceil(Double_t x)
Rounds x upward, returning the smallest integral value that is not less than x.
Definition TMath.h:679
T MinElement(Long64_t n, const T *a)
Returns minimum of array a of length n.
Definition TMath.h:971
Double_t Log(Double_t x)
Returns the natural logarithm of x.
Definition TMath.h:767
Double_t Sqrt(Double_t x)
Returns the square root of x.
Definition TMath.h:673
Short_t Min(Short_t a, Short_t b)
Returns the smallest of a and b.
Definition TMathBase.h:197
constexpr Double_t Pi()
Definition TMath.h:40
Bool_t AreEqualRel(Double_t af, Double_t bf, Double_t relPrec)
Comparing floating points.
Definition TMath.h:429
Bool_t AreEqualAbs(Double_t af, Double_t bf, Double_t epsilon)
Comparing floating points.
Definition TMath.h:421
Double_t KolmogorovProb(Double_t z)
Calculates the Kolmogorov distribution function,.
Definition TMath.cxx:679
void Sort(Index n, const Element *a, Index *index, Bool_t down=kTRUE)
Sort the n elements of the array a of generic templated type Element.
Definition TMathBase.h:413
Long64_t BinarySearch(Long64_t n, const T *array, T value)
Binary search in an array of n values to locate value.
Definition TMathBase.h:329
Double_t Log10(Double_t x)
Returns the common (base-10) logarithm of x.
Definition TMath.h:773
Short_t Abs(Short_t d)
Returns the absolute value of parameter Short_t d.
Definition TMathBase.h:122
Double_t Infinity()
Returns an infinity as defined by the IEEE standard.
Definition TMath.h:928
th1 Draw()
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2338