Logo ROOT   6.16/01
Reference Guide
TH1.cxx
Go to the documentation of this file.
1// @(#)root/hist:$Id$
2// Author: Rene Brun 26/12/94
3
4/*************************************************************************
5 * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
6 * All rights reserved. *
7 * *
8 * For the licensing terms see $ROOTSYS/LICENSE. *
9 * For the list of contributors see $ROOTSYS/README/CREDITS. *
10 *************************************************************************/
11
12#include <stdlib.h>
13#include <string.h>
14#include <stdio.h>
15#include <ctype.h>
16#include <sstream>
17#include <cmath>
18
19#include "Riostream.h"
20#include "TROOT.h"
21#include "TEnv.h"
22#include "TClass.h"
23#include "TMath.h"
24#include "THashList.h"
25#include "TH1.h"
26#include "TH2.h"
27#include "TH3.h"
28#include "TF2.h"
29#include "TF3.h"
30#include "TPluginManager.h"
31#include "TVirtualPad.h"
32#include "TRandom.h"
33#include "TVirtualFitter.h"
34#include "THLimitsFinder.h"
35#include "TProfile.h"
36#include "TStyle.h"
37#include "TVectorF.h"
38#include "TVectorD.h"
39#include "TBrowser.h"
40#include "TObjString.h"
41#include "TError.h"
42#include "TVirtualHistPainter.h"
43#include "TVirtualFFT.h"
44#include "TSystem.h"
45
46#include "HFitInterface.h"
47#include "Fit/DataRange.h"
48#include "Fit/BinData.h"
49#include "Math/GoFTest.h"
52
53#include "TH1Merger.h"
54
55/** \addtogroup Hist
56@{
57\class TH1C
58\brief 1-D histogram with a byte per channel (see TH1 documentation)
59\class TH1S
60\brief 1-D histogram with a short per channel (see TH1 documentation)
61\class TH1I
62\brief 1-D histogram with an int per channel (see TH1 documentation)}
63\class TH1F
64\brief 1-D histogram with a float per channel (see TH1 documentation)}
65\class TH1D
66\brief 1-D histogram with a double per channel (see TH1 documentation)}
67@}
68*/
69
70/** \class TH1
71The TH1 histogram class.
72
73### The Histogram classes
74ROOT supports the following histogram types:
75
76 - 1-D histograms:
77 - TH1C : histograms with one byte per channel. Maximum bin content = 127
78 - TH1S : histograms with one short per channel. Maximum bin content = 32767
79 - TH1I : histograms with one int per channel. Maximum bin content = 2147483647
80 - TH1F : histograms with one float per channel. Maximum precision 7 digits
81 - TH1D : histograms with one double per channel. Maximum precision 14 digits
82 - 2-D histograms:
83 - TH2C : histograms with one byte per channel. Maximum bin content = 127
84 - TH2S : histograms with one short per channel. Maximum bin content = 32767
85 - TH2I : histograms with one int per channel. Maximum bin content = 2147483647
86 - TH2F : histograms with one float per channel. Maximum precision 7 digits
87 - TH2D : histograms with one double per channel. Maximum precision 14 digits
88 - 3-D histograms:
89 - TH3C : histograms with one byte per channel. Maximum bin content = 127
90 - TH3S : histograms with one short per channel. Maximum bin content = 32767
91 - TH3I : histograms with one int per channel. Maximum bin content = 2147483647
92 - TH3F : histograms with one float per channel. Maximum precision 7 digits
93 - TH3D : histograms with one double per channel. Maximum precision 14 digits
94 - Profile histograms: See classes TProfile, TProfile2D and TProfile3D.
95 Profile histograms are used to display the mean value of Y and its standard deviation
96 for each bin in X. Profile histograms are in many cases an elegant
97 replacement of two-dimensional histograms : the inter-relation of two
98 measured quantities X and Y can always be visualized by a two-dimensional
99 histogram or scatter-plot; If Y is an unknown (but single-valued)
100 approximate function of X, this function is displayed by a profile
101 histogram with much better precision than by a scatter-plot.
102
103
104All histogram classes are derived from the base class TH1
105~~~ {.cpp}
106 TH1
107 ^
108 |
109 |
110 |
111 +----------------+-------+------+------+-----+-----+
112 | | | | | | |
113 | | TH1C TH1S TH1I TH1F TH1D
114 | | |
115 | | |
116 | TH2 TProfile
117 | |
118 | |
119 | +-------+------+------+-----+-----+
120 | | | | | |
121 | TH2C TH2S TH2I TH2F TH2D
122 | |
123 TH3 |
124 | TProfile2D
125 |
126 +-------+------+------+------+------+
127 | | | | |
128 TH3C TH3S TH3I TH3F TH3D
129 |
130 |
131 TProfile3D
132
133 The TH*C classes also inherit from the array class TArrayC.
134 The TH*S classes also inherit from the array class TArrayS.
135 The TH*I classes also inherit from the array class TArrayI.
136 The TH*F classes also inherit from the array class TArrayF.
137 The TH*D classes also inherit from the array class TArrayD.
138~~~
139
140#### Creating histograms
141
142Histograms are created by invoking one of the constructors, e.g.
143~~~ {.cpp}
144 TH1F *h1 = new TH1F("h1", "h1 title", 100, 0, 4.4);
145 TH2F *h2 = new TH2F("h2", "h2 title", 40, 0, 4, 30, -3, 3);
146~~~
147Histograms may also be created by:
148
149 - calling the Clone function, see below
150 - making a projection from a 2-D or 3-D histogram, see below
151 - reading an histogram from a file
152
153 When an histogram is created, a reference to it is automatically added
154 to the list of in-memory objects for the current file or directory.
155 This default behaviour can be changed by:
156~~~ {.cpp}
157 h->SetDirectory(0); for the current histogram h
158 TH1::AddDirectory(kFALSE); sets a global switch disabling the reference
159~~~
160 When the histogram is deleted, the reference to it is removed from
161 the list of objects in memory.
162 When a file is closed, all histograms in memory associated with this file
163 are automatically deleted.
164
165#### Fix or variable bin size
166
167 All histogram types support either fix or variable bin sizes.
168 2-D histograms may have fix size bins along X and variable size bins
169 along Y or vice-versa. The functions to fill, manipulate, draw or access
170 histograms are identical in both cases.
171
172 Each histogram always contains 3 objects TAxis: fXaxis, fYaxis and fZaxis
173 o access the axis parameters, do:
174~~~ {.cpp}
175 TAxis *xaxis = h->GetXaxis(); etc.
176 Double_t binCenter = xaxis->GetBinCenter(bin), etc.
177~~~
178 See class TAxis for a description of all the access functions.
179 The axis range is always stored internally in double precision.
180
181#### Convention for numbering bins
182
183 For all histogram types: nbins, xlow, xup
184~~~ {.cpp}
185 bin = 0; underflow bin
186 bin = 1; first bin with low-edge xlow INCLUDED
187 bin = nbins; last bin with upper-edge xup EXCLUDED
188 bin = nbins+1; overflow bin
189~~~
190 In case of 2-D or 3-D histograms, a "global bin" number is defined.
191 For example, assuming a 3-D histogram with (binx, biny, binz), the function
192~~~ {.cpp}
193 Int_t gbin = h->GetBin(binx, biny, binz);
194~~~
195 returns a global/linearized gbin number. This global gbin is useful
196 to access the bin content/error information independently of the dimension.
197 Note that to access the information other than bin content and errors
198 one should use the TAxis object directly with e.g.:
199~~~ {.cpp}
200 Double_t xcenter = h3->GetZaxis()->GetBinCenter(27);
201~~~
202 returns the center along z of bin number 27 (not the global bin)
203 in the 3-D histogram h3.
204
205#### Alphanumeric Bin Labels
206
207 By default, an histogram axis is drawn with its numeric bin labels.
208 One can specify alphanumeric labels instead with:
209
210 - call TAxis::SetBinLabel(bin, label);
211 This can always be done before or after filling.
212 When the histogram is drawn, bin labels will be automatically drawn.
213 See examples labels1.C and labels2.C
214 - call to a Fill function with one of the arguments being a string, e.g.
215~~~ {.cpp}
216 hist1->Fill(somename, weight);
217 hist2->Fill(x, somename, weight);
218 hist2->Fill(somename, y, weight);
219 hist2->Fill(somenamex, somenamey, weight);
220~~~
221 See examples hlabels1.C and hlabels2.C
222 - via TTree::Draw. see for example cernstaff.C
223~~~ {.cpp}
224 tree.Draw("Nation::Division");
225~~~
226 where "Nation" and "Division" are two branches of a Tree.
227
228When using the options 2 or 3 above, the labels are automatically
229 added to the list (THashList) of labels for a given axis.
230 By default, an axis is drawn with the order of bins corresponding
231 to the filling sequence. It is possible to reorder the axis
232
233 - alphabetically
234 - by increasing or decreasing values
235
236 The reordering can be triggered via the TAxis context menu by selecting
237 the menu item "LabelsOption" or by calling directly
238 TH1::LabelsOption(option, axis) where
239
240 - axis may be "X", "Y" or "Z"
241 - option may be:
242 - "a" sort by alphabetic order
243 - ">" sort by decreasing values
244 - "<" sort by increasing values
245 - "h" draw labels horizontal
246 - "v" draw labels vertical
247 - "u" draw labels up (end of label right adjusted)
248 - "d" draw labels down (start of label left adjusted)
249
250 When using the option 2 above, new labels are added by doubling the current
251 number of bins in case one label does not exist yet.
252 When the Filling is terminated, it is possible to trim the number
253 of bins to match the number of active labels by calling
254~~~ {.cpp}
255 TH1::LabelsDeflate(axis) with axis = "X", "Y" or "Z"
256~~~
257 This operation is automatic when using TTree::Draw.
258 Once bin labels have been created, they become persistent if the histogram
259 is written to a file or when generating the C++ code via SavePrimitive.
260
261#### Histograms with automatic bins
262
263 When an histogram is created with an axis lower limit greater or equal
264 to its upper limit, the SetBuffer is automatically called with an
265 argument fBufferSize equal to fgBufferSize (default value=1000).
266 fgBufferSize may be reset via the static function TH1::SetDefaultBufferSize.
267 The axis limits will be automatically computed when the buffer will
268 be full or when the function BufferEmpty is called.
269
270#### Filling histograms
271
272 An histogram is typically filled with statements like:
273~~~ {.cpp}
274 h1->Fill(x);
275 h1->Fill(x, w); //fill with weight
276 h2->Fill(x, y)
277 h2->Fill(x, y, w)
278 h3->Fill(x, y, z)
279 h3->Fill(x, y, z, w)
280~~~
281 or via one of the Fill functions accepting names described above.
282 The Fill functions compute the bin number corresponding to the given
283 x, y or z argument and increment this bin by the given weight.
284 The Fill functions return the bin number for 1-D histograms or global
285 bin number for 2-D and 3-D histograms.
286 If TH1::Sumw2 has been called before filling, the sum of squares of
287 weights is also stored.
288 One can also increment directly a bin number via TH1::AddBinContent
289 or replace the existing content via TH1::SetBinContent.
290 To access the bin content of a given bin, do:
291~~~ {.cpp}
292 Double_t binContent = h->GetBinContent(bin);
293~~~
294
295 By default, the bin number is computed using the current axis ranges.
296 If the automatic binning option has been set via
297~~~ {.cpp}
298 h->SetCanExtend(TH1::kAllAxes);
299~~~
300 then, the Fill Function will automatically extend the axis range to
301 accomodate the new value specified in the Fill argument. The method
302 used is to double the bin size until the new value fits in the range,
303 merging bins two by two. This automatic binning options is extensively
304 used by the TTree::Draw function when histogramming Tree variables
305 with an unknown range.
306 This automatic binning option is supported for 1-D, 2-D and 3-D histograms.
307
308 During filling, some statistics parameters are incremented to compute
309 the mean value and Root Mean Square with the maximum precision.
310
311 In case of histograms of type TH1C, TH1S, TH2C, TH2S, TH3C, TH3S
312 a check is made that the bin contents do not exceed the maximum positive
313 capacity (127 or 32767). Histograms of all types may have positive
314 or/and negative bin contents.
315
316#### Rebinning
317 At any time, an histogram can be rebinned via TH1::Rebin. This function
318 returns a new histogram with the rebinned contents.
319 If bin errors were stored, they are recomputed during the rebinning.
320
321#### Associated errors
322 By default, for each bin, the sum of weights is computed at fill time.
323 One can also call TH1::Sumw2 to force the storage and computation
324 of the sum of the square of weights per bin.
325 If Sumw2 has been called, the error per bin is computed as the
326 sqrt(sum of squares of weights), otherwise the error is set equal
327 to the sqrt(bin content).
328 To return the error for a given bin number, do:
329~~~ {.cpp}
330 Double_t error = h->GetBinError(bin);
331~~~
332
333#### Associated functions
334 One or more object (typically a TF1*) can be added to the list
335 of functions (fFunctions) associated to each histogram.
336 When TH1::Fit is invoked, the fitted function is added to this list.
337 Given an histogram h, one can retrieve an associated function
338 with:
339~~~ {.cpp}
340 TF1 *myfunc = h->GetFunction("myfunc");
341~~~
342
343#### Operations on histograms
344
345 Many types of operations are supported on histograms or between histograms
346
347 - Addition of an histogram to the current histogram.
348 - Additions of two histograms with coefficients and storage into the current
349 histogram.
350 - Multiplications and Divisions are supported in the same way as additions.
351 - The Add, Divide and Multiply functions also exist to add, divide or multiply
352 an histogram by a function.
353
354 If an histogram has associated error bars (TH1::Sumw2 has been called),
355 the resulting error bars are also computed assuming independent histograms.
356 In case of divisions, Binomial errors are also supported.
357 One can mark a histogram to be an "average" histogram by setting its bit kIsAverage via
358 myhist.SetBit(TH1::kIsAverage);
359 When adding (see TH1::Add) average histograms, the histograms are averaged and not summed.
360
361#### Fitting histograms
362
363 Histograms (1-D, 2-D, 3-D and Profiles) can be fitted with a user
364 specified function via TH1::Fit. When an histogram is fitted, the
365 resulting function with its parameters is added to the list of functions
366 of this histogram. If the histogram is made persistent, the list of
367 associated functions is also persistent. Given a pointer (see above)
368 to an associated function myfunc, one can retrieve the function/fit
369 parameters with calls such as:
370~~~ {.cpp}
371 Double_t chi2 = myfunc->GetChisquare();
372 Double_t par0 = myfunc->GetParameter(0); value of 1st parameter
373 Double_t err0 = myfunc->GetParError(0); error on first parameter
374~~~
375
376#### Projections of histograms
377
378 One can:
379
380 - make a 1-D projection of a 2-D histogram or Profile
381 see functions TH2::ProjectionX,Y, TH2::ProfileX,Y, TProfile::ProjectionX
382 - make a 1-D, 2-D or profile out of a 3-D histogram
383 see functions TH3::ProjectionZ, TH3::Project3D.
384
385 One can fit these projections via:
386~~~ {.cpp}
387 TH2::FitSlicesX,Y, TH3::FitSlicesZ.
388~~~
389
390#### Random Numbers and histograms
391
392 TH1::FillRandom can be used to randomly fill an histogram using
393 the contents of an existing TF1 function or another
394 TH1 histogram (for all dimensions).
395 For example the following two statements create and fill an histogram
396 10000 times with a default gaussian distribution of mean 0 and sigma 1:
397~~~ {.cpp}
398 TH1F h1("h1", "histo from a gaussian", 100, -3, 3);
399 h1.FillRandom("gaus", 10000);
400~~~
401 TH1::GetRandom can be used to return a random number distributed
402 according the contents of an histogram.
403
404#### Making a copy of an histogram
405 Like for any other ROOT object derived from TObject, one can use
406 the Clone() function. This makes an identical copy of the original
407 histogram including all associated errors and functions, e.g.:
408~~~ {.cpp}
409 TH1F *hnew = (TH1F*)h->Clone("hnew");
410~~~
411
412#### Normalizing histograms
413
414 One can scale an histogram such that the bins integral is equal to
415 the normalization parameter via TH1::Scale(Double_t norm), where norm
416 is the desired normalization divided by the integral of the histogram.
417
418#### Drawing histograms
419
420 Histograms are drawn via the THistPainter class. Each histogram has
421 a pointer to its own painter (to be usable in a multithreaded program).
422 Many drawing options are supported.
423 See THistPainter::Paint() for more details.
424
425 The same histogram can be drawn with different options in different pads.
426 When an histogram drawn in a pad is deleted, the histogram is
427 automatically removed from the pad or pads where it was drawn.
428 If an histogram is drawn in a pad, then filled again, the new status
429 of the histogram will be automatically shown in the pad next time
430 the pad is updated. One does not need to redraw the histogram.
431 To draw the current version of an histogram in a pad, one can use
432~~~ {.cpp}
433 h->DrawCopy();
434~~~
435 This makes a clone (see Clone below) of the histogram. Once the clone
436 is drawn, the original histogram may be modified or deleted without
437 affecting the aspect of the clone.
438
439 One can use TH1::SetMaximum() and TH1::SetMinimum() to force a particular
440 value for the maximum or the minimum scale on the plot. (For 1-D
441 histograms this means the y-axis, while for 2-D histograms these
442 functions affect the z-axis).
443
444 TH1::UseCurrentStyle() can be used to change all histogram graphics
445 attributes to correspond to the current selected style.
446 This function must be called for each histogram.
447 In case one reads and draws many histograms from a file, one can force
448 the histograms to inherit automatically the current graphics style
449 by calling before gROOT->ForceStyle().
450
451#### Setting Drawing histogram contour levels (2-D hists only)
452
453 By default contours are automatically generated at equidistant
454 intervals. A default value of 20 levels is used. This can be modified
455 via TH1::SetContour() or TH1::SetContourLevel().
456 the contours level info is used by the drawing options "cont", "surf",
457 and "lego".
458
459#### Setting histogram graphics attributes
460
461 The histogram classes inherit from the attribute classes:
462 TAttLine, TAttFill, and TAttMarker.
463 See the member functions of these classes for the list of options.
464
465#### Giving titles to the X, Y and Z axis
466
467~~~ {.cpp}
468 h->GetXaxis()->SetTitle("X axis title");
469 h->GetYaxis()->SetTitle("Y axis title");
470~~~
471 The histogram title and the axis titles can be any TLatex string.
472 The titles are part of the persistent histogram.
473 It is also possible to specify the histogram title and the axis
474 titles at creation time. These titles can be given in the "title"
475 parameter. They must be separated by ";":
476~~~ {.cpp}
477 TH1F* h=new TH1F("h", "Histogram title;X Axis;Y Axis;Z Axis", 100, 0, 1);
478~~~
479 Any title can be omitted:
480~~~ {.cpp}
481 TH1F* h=new TH1F("h", "Histogram title;;Y Axis", 100, 0, 1);
482 TH1F* h=new TH1F("h", ";;Y Axis", 100, 0, 1);
483~~~
484 The method SetTitle has the same syntax:
485~~~ {.cpp}
486 h->SetTitle("Histogram title;Another X title Axis");
487~~~
488
489#### Saving/Reading histograms to/from a ROOT file
490
491 The following statements create a ROOT file and store an histogram
492 on the file. Because TH1 derives from TNamed, the key identifier on
493 the file is the histogram name:
494~~~ {.cpp}
495 TFile f("histos.root", "new");
496 TH1F h1("hgaus", "histo from a gaussian", 100, -3, 3);
497 h1.FillRandom("gaus", 10000);
498 h1->Write();
499~~~
500 To read this histogram in another Root session, do:
501~~~ {.cpp}
502 TFile f("histos.root");
503 TH1F *h = (TH1F*)f.Get("hgaus");
504~~~
505 One can save all histograms in memory to the file by:
506~~~ {.cpp}
507 file->Write();
508~~~
509
510#### Miscellaneous operations
511
512~~~ {.cpp}
513 TH1::KolmogorovTest(): statistical test of compatibility in shape
514 between two histograms
515 TH1::Smooth() smooths the bin contents of a 1-d histogram
516 TH1::Integral() returns the integral of bin contents in a given bin range
517 TH1::GetMean(int axis) returns the mean value along axis
518 TH1::GetStdDev(int axis) returns the sigma distribution along axis
519 TH1::GetEntries() returns the number of entries
520 TH1::Reset() resets the bin contents and errors of an histogram
521~~~
522*/
523
524TF1 *gF1=0; //left for back compatibility (use TVirtualFitter::GetUserFunc instead)
525
530
531extern void H1InitGaus();
532extern void H1InitExpo();
533extern void H1InitPolynom();
534extern void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a);
535extern void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail);
536extern void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b);
537
538// Internal exceptions for the CheckConsistency method
539class DifferentDimension: public std::exception {};
540class DifferentNumberOfBins: public std::exception {};
541class DifferentAxisLimits: public std::exception {};
542class DifferentBinLimits: public std::exception {};
543class DifferentLabels: public std::exception {};
544
546
547////////////////////////////////////////////////////////////////////////////////
548/// Histogram default constructor.
549
551{
552 fDirectory = 0;
553 fFunctions = new TList;
554 fNcells = 0;
555 fIntegral = 0;
556 fPainter = 0;
557 fEntries = 0;
558 fNormFactor = 0;
560 fMaximum = -1111;
561 fMinimum = -1111;
562 fBufferSize = 0;
563 fBuffer = 0;
565 fStatOverflows = EStatOverflows::kNeutral;
566 fXaxis.SetName("xaxis");
567 fYaxis.SetName("yaxis");
568 fZaxis.SetName("zaxis");
569 fXaxis.SetParent(this);
570 fYaxis.SetParent(this);
571 fZaxis.SetParent(this);
573}
574
575////////////////////////////////////////////////////////////////////////////////
576/// Histogram default destructor.
577
579{
580 if (!TestBit(kNotDeleted)) {
581 return;
582 }
583 delete[] fIntegral;
584 fIntegral = 0;
585 delete[] fBuffer;
586 fBuffer = 0;
587 if (fFunctions) {
589
591 TObject* obj = 0;
592 //special logic to support the case where the same object is
593 //added multiple times in fFunctions.
594 //This case happens when the same object is added with different
595 //drawing modes
596 //In the loop below we must be careful with objects (eg TCutG) that may
597 // have been added to the list of functions of several histograms
598 //and may have been already deleted.
599 while ((obj = fFunctions->First())) {
600 while(fFunctions->Remove(obj)) { }
601 if (!obj->TestBit(kNotDeleted)) {
602 break;
603 }
604 delete obj;
605 obj = 0;
606 }
607 delete fFunctions;
608 fFunctions = 0;
609 }
610 if (fDirectory) {
611 fDirectory->Remove(this);
612 fDirectory = 0;
613 }
614 delete fPainter;
615 fPainter = 0;
616}
617
618////////////////////////////////////////////////////////////////////////////////
619/// Normal constructor for fix bin size histograms.
620/// Creates the main histogram structure.
621///
622/// \param[in] name name of histogram (avoid blanks)
623/// \param[in] title histogram title.
624/// If title is of the form stringt;stringx;stringy;stringz`
625/// the histogram title is set to `stringt`,
626/// the x axis title to `stringy`, the y axis title to `stringy`, etc.
627/// \param[in] nbins number of bins
628/// \param[in] xlow low edge of first bin
629/// \param[in] xup upper edge of last bin (not included in last bin)
630///
631/// When an histogram is created, it is automatically added to the list
632/// of special objects in the current directory.
633/// To find the pointer to this histogram in the current directory
634/// by its name, do:
635/// ~~~ {.cpp}
636/// TH1F *h1 = (TH1F*)gDirectory->FindObject(name);
637/// ~~~
638
639TH1::TH1(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
640 :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
641{
642 Build();
643 if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
644 fXaxis.Set(nbins,xlow,xup);
645 fNcells = fXaxis.GetNbins()+2;
646}
647
648////////////////////////////////////////////////////////////////////////////////
649/// Normal constructor for variable bin size histograms.
650/// Creates the main histogram structure.
651///
652/// \param[in] name name of histogram (avoid blanks)
653/// \param[in] title histogram title.
654/// If title is of the form `stringt;stringx;stringy;stringz`
655/// the histogram title is set to `stringt`,
656/// the x axis title to `stringy`, the y axis title to `stringy`, etc.
657/// \param[in] nbins number of bins
658/// \param[in] xbins array of low-edges for each bin.
659/// This is an array of size nbins+1
660
661TH1::TH1(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
662 :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
663{
664 Build();
665 if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
666 if (xbins) fXaxis.Set(nbins,xbins);
667 else fXaxis.Set(nbins,0,1);
668 fNcells = fXaxis.GetNbins()+2;
669}
670
671////////////////////////////////////////////////////////////////////////////////
672/// Normal constructor for variable bin size histograms.
673///
674/// \param[in] name name of histogram (avoid blanks)
675/// \param[in] title histogram title.
676/// If title is of the form `stringt;stringx;stringy;stringz`
677/// the histogram title is set to `stringt`,
678/// the x axis title to `stringy`, the y axis title to `stringy`, etc.
679/// \param[in] nbins number of bins
680/// \param[in] xbins array of low-edges for each bin.
681/// This is an array of size nbins+1
682
683TH1::TH1(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
684 :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
685{
686 Build();
687 if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
688 if (xbins) fXaxis.Set(nbins,xbins);
689 else fXaxis.Set(nbins,0,1);
690 fNcells = fXaxis.GetNbins()+2;
691}
692
693////////////////////////////////////////////////////////////////////////////////
694/// Copy constructor.
695/// The list of functions is not copied. (Use Clone if needed)
696
698{
699 ((TH1&)h).Copy(*this);
700}
701
702////////////////////////////////////////////////////////////////////////////////
703/// Static function: cannot be inlined on Windows/NT.
704
706{
707 return fgAddDirectory;
708}
709
710////////////////////////////////////////////////////////////////////////////////
711/// Browse the Histogram object.
712
714{
715 Draw(b ? b->GetDrawOption() : "");
716 gPad->Update();
717}
718
719////////////////////////////////////////////////////////////////////////////////
720/// Creates histogram basic data structure.
721
723{
724 fDirectory = 0;
725 fPainter = 0;
726 fIntegral = 0;
727 fEntries = 0;
728 fNormFactor = 0;
730 fMaximum = -1111;
731 fMinimum = -1111;
732 fBufferSize = 0;
733 fBuffer = 0;
735 fStatOverflows = EStatOverflows::kNeutral;
736 fXaxis.SetName("xaxis");
737 fYaxis.SetName("yaxis");
738 fZaxis.SetName("zaxis");
739 fYaxis.Set(1,0.,1.);
740 fZaxis.Set(1,0.,1.);
741 fXaxis.SetParent(this);
742 fYaxis.SetParent(this);
743 fZaxis.SetParent(this);
744
746
747 fFunctions = new TList;
748
750
753 if (fDirectory) {
755 fDirectory->Append(this,kTRUE);
756 }
757 }
758}
759
760////////////////////////////////////////////////////////////////////////////////
761/// Performs the operation: `this = this + c1*f1`
762/// if errors are defined (see TH1::Sumw2), errors are also recalculated.
763///
764/// By default, the function is computed at the centre of the bin.
765/// if option "I" is specified (1-d histogram only), the integral of the
766/// function in each bin is used instead of the value of the function at
767/// the centre of the bin.
768///
769/// Only bins inside the function range are recomputed.
770///
771/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
772/// you should call Sumw2 before making this operation.
773/// This is particularly important if you fit the histogram after TH1::Add
774///
775/// The function return kFALSE if the Add operation failed
776
778{
779 if (!f1) {
780 Error("Add","Attempt to add a non-existing function");
781 return kFALSE;
782 }
783
784 TString opt = option;
785 opt.ToLower();
786 Bool_t integral = kFALSE;
787 if (opt.Contains("i") && fDimension == 1) integral = kTRUE;
788
789 Int_t ncellsx = GetNbinsX() + 2; // cells = normal bins + underflow bin + overflow bin
790 Int_t ncellsy = GetNbinsY() + 2;
791 Int_t ncellsz = GetNbinsZ() + 2;
792 if (fDimension < 2) ncellsy = 1;
793 if (fDimension < 3) ncellsz = 1;
794
795 // delete buffer if it is there since it will become invalid
796 if (fBuffer) BufferEmpty(1);
797
798 // - Add statistics
799 Double_t s1[10];
800 for (Int_t i = 0; i < 10; ++i) s1[i] = 0;
801 PutStats(s1);
802 SetMinimum();
803 SetMaximum();
804
805 // - Loop on bins (including underflows/overflows)
806 Int_t bin, binx, biny, binz;
807 Double_t cu=0;
808 Double_t xx[3];
809 Double_t *params = 0;
810 f1->InitArgs(xx,params);
811 for (binz = 0; binz < ncellsz; ++binz) {
812 xx[2] = fZaxis.GetBinCenter(binz);
813 for (biny = 0; biny < ncellsy; ++biny) {
814 xx[1] = fYaxis.GetBinCenter(biny);
815 for (binx = 0; binx < ncellsx; ++binx) {
816 xx[0] = fXaxis.GetBinCenter(binx);
817 if (!f1->IsInside(xx)) continue;
819 bin = binx + ncellsx * (biny + ncellsy * binz);
820 if (integral) {
821 cu = c1*f1->Integral(fXaxis.GetBinLowEdge(binx), fXaxis.GetBinUpEdge(binx), 0.) / fXaxis.GetBinWidth(binx);
822 } else {
823 cu = c1*f1->EvalPar(xx);
824 }
825 if (TF1::RejectedPoint()) continue;
826 AddBinContent(bin,cu);
827 }
828 }
829 }
830
831 return kTRUE;
832}
833
834////////////////////////////////////////////////////////////////////////////////
835/// Performs the operation: `this = this + c1*h1`
836/// If errors are defined (see TH1::Sumw2), errors are also recalculated.
837///
838/// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
839/// if not already set.
840///
841/// Note also that adding histogram with labels is not supported, histogram will be
842/// added merging them by bin number independently of the labels.
843/// For adding histogram with labels one should use TH1::Merge
844///
845/// SPECIAL CASE (Average/Efficiency histograms)
846/// For histograms representing averages or efficiencies, one should compute the average
847/// of the two histograms and not the sum. One can mark a histogram to be an average
848/// histogram by setting its bit kIsAverage with
849/// myhist.SetBit(TH1::kIsAverage);
850/// Note that the two histograms must have their kIsAverage bit set
851///
852/// IMPORTANT NOTE1: If you intend to use the errors of this histogram later
853/// you should call Sumw2 before making this operation.
854/// This is particularly important if you fit the histogram after TH1::Add
855///
856/// IMPORTANT NOTE2: if h1 has a normalisation factor, the normalisation factor
857/// is used , ie this = this + c1*factor*h1
858/// Use the other TH1::Add function if you do not want this feature
859///
860/// The function return kFALSE if the Add operation failed
861
863{
864 if (!h1) {
865 Error("Add","Attempt to add a non-existing histogram");
866 return kFALSE;
867 }
868
869 // delete buffer if it is there since it will become invalid
870 if (fBuffer) BufferEmpty(1);
871
872 bool useMerge = (c1 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
873 try {
874 CheckConsistency(this,h1);
875 useMerge = kFALSE;
876 } catch(DifferentNumberOfBins&) {
877 if (useMerge)
878 Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
879 else {
880 Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
881 return kFALSE;
882 }
883 } catch(DifferentAxisLimits&) {
884 if (useMerge)
885 Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
886 else
887 Warning("Add","Attempt to add histograms with different axis limits");
888 } catch(DifferentBinLimits&) {
889 if (useMerge)
890 Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
891 else
892 Warning("Add","Attempt to add histograms with different bin limits");
893 } catch(DifferentLabels&) {
894 // in case of different labels -
895 if (useMerge)
896 Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
897 else
898 Info("Warning","Attempt to add histograms with different labels");
899 }
900
901 if (useMerge) {
902 TList l;
903 l.Add(const_cast<TH1*>(h1));
904 auto iret = Merge(&l);
905 return (iret >= 0);
906 }
907
908 // Create Sumw2 if h1 has Sumw2 set
909 if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
910
911 // - Add statistics
912 Double_t entries = TMath::Abs( GetEntries() + c1 * h1->GetEntries() );
913
914 // statistics can be preserved only in case of positive coefficients
915 // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
916 Bool_t resetStats = (c1 < 0);
917 Double_t s1[kNstat] = {0};
918 Double_t s2[kNstat] = {0};
919 if (!resetStats) {
920 // need to initialize to zero s1 and s2 since
921 // GetStats fills only used elements depending on dimension and type
922 GetStats(s1);
923 h1->GetStats(s2);
924 }
925
926 SetMinimum();
927 SetMaximum();
928
929 // - Loop on bins (including underflows/overflows)
930 Double_t factor = 1;
931 if (h1->GetNormFactor() != 0) factor = h1->GetNormFactor()/h1->GetSumOfWeights();;
932 Double_t c1sq = c1 * c1;
933 Double_t factsq = factor * factor;
934
935 for (Int_t bin = 0; bin < fNcells; ++bin) {
936 //special case where histograms have the kIsAverage bit set
937 if (this->TestBit(kIsAverage) && h1->TestBit(kIsAverage)) {
938 Double_t y1 = h1->RetrieveBinContent(bin);
939 Double_t y2 = this->RetrieveBinContent(bin);
941 Double_t e2sq = this->GetBinErrorSqUnchecked(bin);
942 Double_t w1 = 1., w2 = 1.;
943
944 // consider all special cases when bin errors are zero
945 // see http://root-forum.cern.ch/viewtopic.php?f=3&t=13299
946 if (e1sq) w1 = 1. / e1sq;
947 else if (h1->fSumw2.fN) {
948 w1 = 1.E200; // use an arbitrary huge value
949 if (y1 == 0) {
950 // use an estimated error from the global histogram scale
951 double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
952 w1 = 1./(sf*sf);
953 }
954 }
955 if (e2sq) w2 = 1. / e2sq;
956 else if (fSumw2.fN) {
957 w2 = 1.E200; // use an arbitrary huge value
958 if (y2 == 0) {
959 // use an estimated error from the global histogram scale
960 double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
961 w2 = 1./(sf*sf);
962 }
963 }
964
965 double y = (w1*y1 + w2*y2)/(w1 + w2);
966 UpdateBinContent(bin, y);
967 if (fSumw2.fN) {
968 double err2 = 1./(w1 + w2);
969 if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
970 fSumw2.fArray[bin] = err2;
971 }
972 } else { // normal case of addition between histograms
973 AddBinContent(bin, c1 * factor * h1->RetrieveBinContent(bin));
974 if (fSumw2.fN) fSumw2.fArray[bin] += c1sq * factsq * h1->GetBinErrorSqUnchecked(bin);
975 }
976 }
977
978 // update statistics (do here to avoid changes by SetBinContent)
979 if (resetStats) {
980 // statistics need to be reset in case coefficient are negative
981 ResetStats();
982 }
983 else {
984 for (Int_t i=0;i<kNstat;i++) {
985 if (i == 1) s1[i] += c1*c1*s2[i];
986 else s1[i] += c1*s2[i];
987 }
988 PutStats(s1);
989 SetEntries(entries);
990 }
991 return kTRUE;
992}
993
994////////////////////////////////////////////////////////////////////////////////
995/// Replace contents of this histogram by the addition of h1 and h2.
996///
997/// `this = c1*h1 + c2*h2`
998/// if errors are defined (see TH1::Sumw2), errors are also recalculated
999///
1000/// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
1001/// if not already set.
1002///
1003/// Note also that adding histogram with labels is not supported, histogram will be
1004/// added merging them by bin number independently of the labels.
1005/// For adding histogram ith labels one should use TH1::Merge
1006///
1007/// SPECIAL CASE (Average/Efficiency histograms)
1008/// For histograms representing averages or efficiencies, one should compute the average
1009/// of the two histograms and not the sum. One can mark a histogram to be an average
1010/// histogram by setting its bit kIsAverage with
1011/// myhist.SetBit(TH1::kIsAverage);
1012/// Note that the two histograms must have their kIsAverage bit set
1013///
1014/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
1015/// you should call Sumw2 before making this operation.
1016/// This is particularly important if you fit the histogram after TH1::Add
1017///
1018/// ANOTHER SPECIAL CASE : h1 = h2 and c2 < 0
1019/// do a scaling this = c1 * h1 / (bin Volume)
1020///
1021/// The function returns kFALSE if the Add operation failed
1022
1024{
1025
1026 if (!h1 || !h2) {
1027 Error("Add","Attempt to add a non-existing histogram");
1028 return kFALSE;
1029 }
1030
1031 // delete buffer if it is there since it will become invalid
1032 if (fBuffer) BufferEmpty(1);
1033
1034 Bool_t normWidth = kFALSE;
1035 if (h1 == h2 && c2 < 0) {c2 = 0; normWidth = kTRUE;}
1036
1037 if (h1 != h2) {
1038 bool useMerge = (c1 == 1. && c2 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
1039
1040 try {
1041 CheckConsistency(h1,h2);
1042 CheckConsistency(this,h1);
1043 useMerge = kFALSE;
1044 } catch(DifferentNumberOfBins&) {
1045 if (useMerge)
1046 Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
1047 else {
1048 Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
1049 return kFALSE;
1050 }
1051 } catch(DifferentAxisLimits&) {
1052 if (useMerge)
1053 Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
1054 else
1055 Warning("Add","Attempt to add histograms with different axis limits");
1056 } catch(DifferentBinLimits&) {
1057 if (useMerge)
1058 Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
1059 else
1060 Warning("Add","Attempt to add histograms with different bin limits");
1061 } catch(DifferentLabels&) {
1062 // in case of different labels -
1063 if (useMerge)
1064 Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
1065 else
1066 Info("Warning","Attempt to add histograms with different labels");
1067 }
1068
1069 if (useMerge) {
1070 TList l;
1071 // why TList takes non-const pointers ????
1072 l.Add(const_cast<TH1*>(h1));
1073 l.Add(const_cast<TH1*>(h2));
1074 Reset("ICE");
1075 auto iret = Merge(&l);
1076 return (iret >= 0);
1077 }
1078 }
1079
1080 // Create Sumw2 if h1 or h2 have Sumw2 set
1081 if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
1082
1083 // - Add statistics
1084 Double_t nEntries = TMath::Abs( c1*h1->GetEntries() + c2*h2->GetEntries() );
1085
1086 // TODO remove
1087 // statistics can be preserved only in case of positive coefficients
1088 // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
1089 // also in case of scaling with the width we cannot preserve the statistics
1090 Double_t s1[kNstat] = {0};
1091 Double_t s2[kNstat] = {0};
1092 Double_t s3[kNstat];
1093
1094
1095 Bool_t resetStats = (c1*c2 < 0) || normWidth;
1096 if (!resetStats) {
1097 // need to initialize to zero s1 and s2 since
1098 // GetStats fills only used elements depending on dimension and type
1099 h1->GetStats(s1);
1100 h2->GetStats(s2);
1101 for (Int_t i=0;i<kNstat;i++) {
1102 if (i == 1) s3[i] = c1*c1*s1[i] + c2*c2*s2[i];
1103 //else s3[i] = TMath::Abs(c1)*s1[i] + TMath::Abs(c2)*s2[i];
1104 else s3[i] = c1*s1[i] + c2*s2[i];
1105 }
1106 }
1107
1108 SetMinimum();
1109 SetMaximum();
1110
1111 if (normWidth) { // DEPRECATED CASE: belongs to fitting / drawing modules
1112
1113 Int_t nbinsx = GetNbinsX() + 2; // normal bins + underflow, overflow
1114 Int_t nbinsy = GetNbinsY() + 2;
1115 Int_t nbinsz = GetNbinsZ() + 2;
1116
1117 if (fDimension < 2) nbinsy = 1;
1118 if (fDimension < 3) nbinsz = 1;
1119
1120 Int_t bin, binx, biny, binz;
1121 for (binz = 0; binz < nbinsz; ++binz) {
1122 Double_t wz = h1->GetZaxis()->GetBinWidth(binz);
1123 for (biny = 0; biny < nbinsy; ++biny) {
1124 Double_t wy = h1->GetYaxis()->GetBinWidth(biny);
1125 for (binx = 0; binx < nbinsx; ++binx) {
1126 Double_t wx = h1->GetXaxis()->GetBinWidth(binx);
1127 bin = GetBin(binx, biny, binz);
1128 Double_t w = wx*wy*wz;
1129 UpdateBinContent(bin, c1 * h1->RetrieveBinContent(bin) / w);
1130 if (fSumw2.fN) {
1131 Double_t e1 = h1->GetBinError(bin)/w;
1132 fSumw2.fArray[bin] = c1*c1*e1*e1;
1133 }
1134 }
1135 }
1136 }
1137 } else if (h1->TestBit(kIsAverage) && h2->TestBit(kIsAverage)) {
1138 for (Int_t i = 0; i < fNcells; ++i) { // loop on cells (bins including underflow / overflow)
1139 // special case where histograms have the kIsAverage bit set
1141 Double_t y2 = h2->RetrieveBinContent(i);
1143 Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
1144 Double_t w1 = 1., w2 = 1.;
1145
1146 // consider all special cases when bin errors are zero
1147 // see http://root-forum.cern.ch/viewtopic.php?f=3&t=13299
1148 if (e1sq) w1 = 1./ e1sq;
1149 else if (h1->fSumw2.fN) {
1150 w1 = 1.E200; // use an arbitrary huge value
1151 if (y1 == 0 ) { // use an estimated error from the global histogram scale
1152 double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
1153 w1 = 1./(sf*sf);
1154 }
1155 }
1156 if (e2sq) w2 = 1./ e2sq;
1157 else if (h2->fSumw2.fN) {
1158 w2 = 1.E200; // use an arbitrary huge value
1159 if (y2 == 0) { // use an estimated error from the global histogram scale
1160 double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
1161 w2 = 1./(sf*sf);
1162 }
1163 }
1164
1165 double y = (w1*y1 + w2*y2)/(w1 + w2);
1166 UpdateBinContent(i, y);
1167 if (fSumw2.fN) {
1168 double err2 = 1./(w1 + w2);
1169 if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
1170 fSumw2.fArray[i] = err2;
1171 }
1172 }
1173 } else { // case of simple histogram addition
1174 Double_t c1sq = c1 * c1;
1175 Double_t c2sq = c2 * c2;
1176 for (Int_t i = 0; i < fNcells; ++i) { // Loop on cells (bins including underflows/overflows)
1178 if (fSumw2.fN) {
1179 fSumw2.fArray[i] = c1sq * h1->GetBinErrorSqUnchecked(i) + c2sq * h2->GetBinErrorSqUnchecked(i);
1180 }
1181 }
1182 }
1183
1184 if (resetStats) {
1185 // statistics need to be reset in case coefficient are negative
1186 ResetStats();
1187 }
1188 else {
1189 // update statistics (do here to avoid changes by SetBinContent) FIXME remove???
1190 PutStats(s3);
1191 SetEntries(nEntries);
1192 }
1193
1194 return kTRUE;
1195}
1196
1197////////////////////////////////////////////////////////////////////////////////
1198/// Increment bin content by 1.
1199
1201{
1202 AbstractMethod("AddBinContent");
1203}
1204
1205////////////////////////////////////////////////////////////////////////////////
1206/// Increment bin content by a weight w.
1207
1209{
1210 AbstractMethod("AddBinContent");
1211}
1212
1213////////////////////////////////////////////////////////////////////////////////
1214/// Sets the flag controlling the automatic add of histograms in memory
1215///
1216/// By default (fAddDirectory = kTRUE), histograms are automatically added
1217/// to the list of objects in memory.
1218/// Note that one histogram can be removed from its support directory
1219/// by calling h->SetDirectory(0) or h->SetDirectory(dir) to add it
1220/// to the list of objects in the directory dir.
1221///
1222/// NOTE that this is a static function. To call it, use;
1223/// TH1::AddDirectory
1224
1226{
1227 fgAddDirectory = add;
1228}
1229
1230////////////////////////////////////////////////////////////////////////////////
1231/// Auxilliary function to get the power of 2 next (larger) or previous (smaller)
1232/// a given x
1233///
1234/// next = kTRUE : next larger
1235/// next = kFALSE : previous smaller
1236///
1237/// Used by the autobin power of 2 algorithm
1238
1240{
1241 Int_t nn;
1242 Double_t f2 = std::frexp(x, &nn);
1243 return ((next && x > 0.) || (!next && x <= 0.)) ? std::ldexp(std::copysign(1., f2), nn)
1244 : std::ldexp(std::copysign(1., f2), --nn);
1245}
1246
1247////////////////////////////////////////////////////////////////////////////////
1248/// Auxilliary function to get the next power of 2 integer value larger then n
1249///
1250/// Used by the autobin power of 2 algorithm
1251
1253{
1254 Int_t nn;
1255 Double_t f2 = std::frexp(n, &nn);
1256 if (TMath::Abs(f2 - .5) > 0.001)
1257 return (Int_t)std::ldexp(1., nn);
1258 return n;
1259}
1260
1261////////////////////////////////////////////////////////////////////////////////
1262/// Buffer-based estimate of the histogram range using the power of 2 algorithm.
1263///
1264/// Used by the autobin power of 2 algorithm.
1265///
1266/// Works on arguments (min and max from fBuffer) and internal inputs: fXmin,
1267/// fXmax, NBinsX (from fXaxis), ...
1268/// Result save internally in fXaxis.
1269///
1270/// Overloaded by TH2 and TH3.
1271///
1272/// Return -1 if internal inputs are incosistent, 0 otherwise.
1273///
1274
1276{
1277 // We need meaningful raw limits
1278 if (xmi >= xma)
1279 return -1;
1280
1282 Double_t xhmi = fXaxis.GetXmin();
1283 Double_t xhma = fXaxis.GetXmax();
1284
1285 // Now adjust
1286 if (TMath::Abs(xhma) > TMath::Abs(xhmi)) {
1287 // Start from the upper limit
1288 xhma = TH1::AutoP2GetPower2(xhma);
1289 xhmi = xhma - TH1::AutoP2GetPower2(xhma - xhmi);
1290 } else {
1291 // Start from the lower limit
1292 xhmi = TH1::AutoP2GetPower2(xhmi, kFALSE);
1293 xhma = xhmi + TH1::AutoP2GetPower2(xhma - xhmi);
1294 }
1295
1296 // Round the bins to the next power of 2; take into account the possible inflation
1297 // of the range
1298 Double_t rr = (xhma - xhmi) / (xma - xmi);
1299 Int_t nb = TH1::AutoP2GetBins((Int_t)(rr * GetNbinsX()));
1300
1301 // Adjust using the same bin width and offsets
1302 Double_t bw = (xhma - xhmi) / nb;
1303 // Bins to left free on each side
1304 Double_t autoside = gEnv->GetValue("Hist.Binning.Auto.Side", 0.05);
1305 Int_t nbside = (Int_t)(nb * autoside);
1306
1307 // Side up
1308 Int_t nbup = (xhma - xma) / bw;
1309 if (nbup % 2 != 0)
1310 nbup++; // Must be even
1311 if (nbup != nbside) {
1312 // Accounts also for both case: larger or smaller
1313 xhma -= bw * (nbup - nbside);
1314 nb -= (nbup - nbside);
1315 }
1316
1317 // Side low
1318 Int_t nblw = (xmi - xhmi) / bw;
1319 if (nblw % 2 != 0)
1320 nblw++; // Must be even
1321 if (nblw != nbside) {
1322 // Accounts also for both case: larger or smaller
1323 xhmi += bw * (nblw - nbside);
1324 nb -= (nblw - nbside);
1325 }
1326
1327 // Set everything and project
1328 SetBins(nb, xhmi, xhma);
1329
1330 // Done
1331 return 0;
1332}
1333
1334/// Fill histogram with all entries in the buffer.
1335///
1336/// - action = -1 histogram is reset and refilled from the buffer (called by THistPainter::Paint)
1337/// - action = 0 histogram is reset and filled from the buffer. When the histogram is filled from the
1338/// buffer the value fBuffer[0] is set to a negative number (= - number of entries)
1339/// When calling with action == 0 the histogram is NOT refilled when fBuffer[0] is < 0
1340/// While when calling with action = -1 the histogram is reset and ALWAYS refilled independently if
1341/// the histogram was filled before. This is needed when drawing the histogram
1342/// - action = 1 histogram is filled and buffer is deleted
1343/// The buffer is automatically deleted when filling the histogram and the entries is
1344/// larger than the buffer size
1345
1347{
1348 // do we need to compute the bin size?
1349 if (!fBuffer) return 0;
1350 Int_t nbentries = (Int_t)fBuffer[0];
1351
1352 // nbentries correspond to the number of entries of histogram
1353
1354 if (nbentries == 0) {
1355 // if action is 1 we delete the buffer
1356 // this will avoid infinite recursion
1357 if (action > 0) {
1358 delete [] fBuffer;
1359 fBuffer = 0;
1360 fBufferSize = 0;
1361 }
1362 return 0;
1363 }
1364 if (nbentries < 0 && action == 0) return 0; // case histogram has been already filled from the buffer
1365
1366 Double_t *buffer = fBuffer;
1367 if (nbentries < 0) {
1368 nbentries = -nbentries;
1369 // a reset might call BufferEmpty() giving an infinite recursion
1370 // Protect it by setting fBuffer = 0
1371 fBuffer=0;
1372 //do not reset the list of functions
1373 Reset("ICES");
1374 fBuffer = buffer;
1375 }
1376 if (CanExtendAllAxes() || (fXaxis.GetXmax() <= fXaxis.GetXmin())) {
1377 //find min, max of entries in buffer
1378 Double_t xmin = fBuffer[2];
1379 Double_t xmax = xmin;
1380 for (Int_t i=1;i<nbentries;i++) {
1381 Double_t x = fBuffer[2*i+2];
1382 if (x < xmin) xmin = x;
1383 if (x > xmax) xmax = x;
1384 }
1385 if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
1386 Int_t rc = -1;
1388 if ((rc = AutoP2FindLimits(xmin, xmax)) < 0)
1389 Warning("BufferEmpty",
1390 "incosistency found by power-of-2 autobin algorithm: fallback to standard method");
1391 }
1392 if (rc < 0)
1394 } else {
1395 fBuffer = 0;
1396 Int_t keep = fBufferSize; fBufferSize = 0;
1398 if (xmax >= fXaxis.GetXmax()) ExtendAxis(xmax, &fXaxis);
1399 fBuffer = buffer;
1400 fBufferSize = keep;
1401 }
1402 }
1403
1404 // call DoFillN which will not put entries in the buffer as FillN does
1405 // set fBuffer to zero to avoid re-emptying the buffer from functions called
1406 // by DoFillN (e.g Sumw2)
1407 buffer = fBuffer; fBuffer = 0;
1408 DoFillN(nbentries,&buffer[2],&buffer[1],2);
1409 fBuffer = buffer;
1410
1411 // if action == 1 - delete the buffer
1412 if (action > 0) {
1413 delete [] fBuffer;
1414 fBuffer = 0;
1415 fBufferSize = 0;
1416 } else {
1417 // if number of entries is consistent with buffer - set it negative to avoid
1418 // refilling the histogram every time BufferEmpty(0) is called
1419 // In case it is not consistent, by setting fBuffer[0]=0 is like resetting the buffer
1420 // (it will not be used anymore the next time BufferEmpty is called)
1421 if (nbentries == (Int_t)fEntries)
1422 fBuffer[0] = -nbentries;
1423 else
1424 fBuffer[0] = 0;
1425 }
1426 return nbentries;
1427}
1428
1429////////////////////////////////////////////////////////////////////////////////
1430/// accumulate arguments in buffer. When buffer is full, empty the buffer
1431///
1432/// - `fBuffer[0]` = number of entries in buffer
1433/// - `fBuffer[1]` = w of first entry
1434/// - `fBuffer[2]` = x of first entry
1435
1437{
1438 if (!fBuffer) return -2;
1439 Int_t nbentries = (Int_t)fBuffer[0];
1440
1441
1442 if (nbentries < 0) {
1443 // reset nbentries to a positive value so next time BufferEmpty() is called
1444 // the histogram will be refilled
1445 nbentries = -nbentries;
1446 fBuffer[0] = nbentries;
1447 if (fEntries > 0) {
1448 // set fBuffer to zero to avoid calling BufferEmpty in Reset
1449 Double_t *buffer = fBuffer; fBuffer=0;
1450 Reset("ICES"); // do not reset list of functions
1451 fBuffer = buffer;
1452 }
1453 }
1454 if (2*nbentries+2 >= fBufferSize) {
1455 BufferEmpty(1);
1456 if (!fBuffer)
1457 // to avoid infinite recursion Fill->BufferFill->Fill
1458 return Fill(x,w);
1459 // this cannot happen
1460 R__ASSERT(0);
1461 }
1462 fBuffer[2*nbentries+1] = w;
1463 fBuffer[2*nbentries+2] = x;
1464 fBuffer[0] += 1;
1465 return -2;
1466}
1467
1468////////////////////////////////////////////////////////////////////////////////
1469/// Check bin limits.
1470
1471bool TH1::CheckBinLimits(const TAxis* a1, const TAxis * a2)
1472{
1473 const TArrayD * h1Array = a1->GetXbins();
1474 const TArrayD * h2Array = a2->GetXbins();
1475 Int_t fN = h1Array->fN;
1476 if ( fN != 0 ) {
1477 if ( h2Array->fN != fN ) {
1478 throw DifferentBinLimits();
1479 return false;
1480 }
1481 else {
1482 for ( int i = 0; i < fN; ++i ) {
1483 if ( ! TMath::AreEqualRel( h1Array->GetAt(i), h2Array->GetAt(i), 1E-10 ) ) {
1484 throw DifferentBinLimits();
1485 return false;
1486 }
1487 }
1488 }
1489 }
1490
1491 return true;
1492}
1493
1494////////////////////////////////////////////////////////////////////////////////
1495/// Check that axis have same labels.
1496
1497bool TH1::CheckBinLabels(const TAxis* a1, const TAxis * a2)
1498{
1499 THashList *l1 = a1->GetLabels();
1500 THashList *l2 = a2->GetLabels();
1501
1502 if (!l1 && !l2 )
1503 return true;
1504 if (!l1 || !l2 ) {
1505 throw DifferentLabels();
1506 return false;
1507 }
1508 // check now labels sizes are the same
1509 if (l1->GetSize() != l2->GetSize() ) {
1510 throw DifferentLabels();
1511 return false;
1512 }
1513 for (int i = 1; i <= a1->GetNbins(); ++i) {
1514 TString label1 = a1->GetBinLabel(i);
1515 TString label2 = a2->GetBinLabel(i);
1516 if (label1 != label2) {
1517 throw DifferentLabels();
1518 return false;
1519 }
1520 }
1521
1522 return true;
1523}
1524
1525////////////////////////////////////////////////////////////////////////////////
1526/// Check that the axis limits of the histograms are the same.
1527/// If a first and last bin is passed the axis is compared between the given range
1528
1529bool TH1::CheckAxisLimits(const TAxis *a1, const TAxis *a2 )
1530{
1531 if ( ! TMath::AreEqualRel(a1->GetXmin(), a2->GetXmin(),1.E-12) ||
1532 ! TMath::AreEqualRel(a1->GetXmax(), a2->GetXmax(),1.E-12) ) {
1533 throw DifferentAxisLimits();
1534 return false;
1535 }
1536 return true;
1537}
1538
1539////////////////////////////////////////////////////////////////////////////////
1540/// Check that the axis are the same
1541
1542bool TH1::CheckEqualAxes(const TAxis *a1, const TAxis *a2 )
1543{
1544 if (a1->GetNbins() != a2->GetNbins() ) {
1545 //throw DifferentNumberOfBins();
1546 ::Info("CheckEqualAxes","Axes have different number of bins : nbin1 = %d nbin2 = %d",a1->GetNbins(),a2->GetNbins() );
1547 return false;
1548 }
1549 try {
1550 CheckAxisLimits(a1,a2);
1551 } catch (DifferentAxisLimits&) {
1552 ::Info("CheckEqualAxes","Axes have different limits");
1553 return false;
1554 }
1555 try {
1556 CheckBinLimits(a1,a2);
1557 } catch (DifferentBinLimits&) {
1558 ::Info("CheckEqualAxes","Axes have different bin limits");
1559 return false;
1560 }
1561
1562 // check labels
1563 try {
1564 CheckBinLabels(a1,a2);
1565 } catch (DifferentLabels&) {
1566 ::Info("CheckEqualAxes","Axes have different labels");
1567 return false;
1568 }
1569
1570 return true;
1571}
1572
1573////////////////////////////////////////////////////////////////////////////////
1574/// Check that two sub axis are the same.
1575/// The limits are defined by first bin and last bin
1576/// N.B. no check is done in this case for variable bins
1577
1578bool TH1::CheckConsistentSubAxes(const TAxis *a1, Int_t firstBin1, Int_t lastBin1, const TAxis * a2, Int_t firstBin2, Int_t lastBin2 )
1579{
1580 // By default is assumed that no bins are given for the second axis
1581 Int_t nbins1 = lastBin1-firstBin1 + 1;
1582 Double_t xmin1 = a1->GetBinLowEdge(firstBin1);
1583 Double_t xmax1 = a1->GetBinUpEdge(lastBin1);
1584
1585 Int_t nbins2 = a2->GetNbins();
1586 Double_t xmin2 = a2->GetXmin();
1587 Double_t xmax2 = a2->GetXmax();
1588
1589 if (firstBin2 < lastBin2) {
1590 // in this case assume no bins are given for the second axis
1591 nbins2 = lastBin1-firstBin1 + 1;
1592 xmin2 = a1->GetBinLowEdge(firstBin1);
1593 xmax2 = a1->GetBinUpEdge(lastBin1);
1594 }
1595
1596 if (nbins1 != nbins2 ) {
1597 ::Info("CheckConsistentSubAxes","Axes have different number of bins");
1598 return false;
1599 }
1600
1601 if ( ! TMath::AreEqualRel(xmin1,xmin2,1.E-12) ||
1602 ! TMath::AreEqualRel(xmax1,xmax2,1.E-12) ) {
1603 ::Info("CheckConsistentSubAxes","Axes have different limits");
1604 return false;
1605 }
1606
1607 return true;
1608}
1609
1610////////////////////////////////////////////////////////////////////////////////
1611/// Check histogram compatibility.
1612
1613bool TH1::CheckConsistency(const TH1* h1, const TH1* h2)
1614{
1615 if (h1 == h2) return true;
1616
1617 if (h1->GetDimension() != h2->GetDimension() ) {
1618 throw DifferentDimension();
1619 return false;
1620 }
1621 Int_t dim = h1->GetDimension();
1622
1623 // returns kTRUE if number of bins and bin limits are identical
1624 Int_t nbinsx = h1->GetNbinsX();
1625 Int_t nbinsy = h1->GetNbinsY();
1626 Int_t nbinsz = h1->GetNbinsZ();
1627
1628 // Check whether the histograms have the same number of bins.
1629 if (nbinsx != h2->GetNbinsX() ||
1630 (dim > 1 && nbinsy != h2->GetNbinsY()) ||
1631 (dim > 2 && nbinsz != h2->GetNbinsZ()) ) {
1632 throw DifferentNumberOfBins();
1633 return false;
1634 }
1635
1636 bool ret = true;
1637
1638 // check axis limits
1639 ret &= CheckAxisLimits(h1->GetXaxis(), h2->GetXaxis());
1640 if (dim > 1) ret &= CheckAxisLimits(h1->GetYaxis(), h2->GetYaxis());
1641 if (dim > 2) ret &= CheckAxisLimits(h1->GetZaxis(), h2->GetZaxis());
1642
1643 // check bin limits
1644 ret &= CheckBinLimits(h1->GetXaxis(), h2->GetXaxis());
1645 if (dim > 1) ret &= CheckBinLimits(h1->GetYaxis(), h2->GetYaxis());
1646 if (dim > 2) ret &= CheckBinLimits(h1->GetZaxis(), h2->GetZaxis());
1647
1648 // check labels if histograms are both not empty
1649 if ( !h1->IsEmpty() && !h2->IsEmpty() ) {
1650 ret &= CheckBinLabels(h1->GetXaxis(), h2->GetXaxis());
1651 if (dim > 1) ret &= CheckBinLabels(h1->GetYaxis(), h2->GetYaxis());
1652 if (dim > 2) ret &= CheckBinLabels(h1->GetZaxis(), h2->GetZaxis());
1653 }
1654
1655 return ret;
1656}
1657
1658////////////////////////////////////////////////////////////////////////////////
1659/// \f$ \chi^{2} \f$ test for comparing weighted and unweighted histograms
1660///
1661/// Function: Returns p-value. Other return values are specified by the 3rd parameter
1662///
1663/// \param[in] h2 the second histogram
1664/// \param[in] option
1665/// - "UU" = experiment experiment comparison (unweighted-unweighted)
1666/// - "UW" = experiment MC comparison (unweighted-weighted). Note that
1667/// the first histogram should be unweighted
1668/// - "WW" = MC MC comparison (weighted-weighted)
1669/// - "NORM" = to be used when one or both of the histograms is scaled
1670/// but the histogram originally was unweighted
1671/// - by default underflows and overflows are not included:
1672/// * "OF" = overflows included
1673/// * "UF" = underflows included
1674/// - "P" = print chi2, ndf, p_value, igood
1675/// - "CHI2" = returns chi2 instead of p-value
1676/// - "CHI2/NDF" = returns \f$ \chi^{2} \f$/ndf
1677/// \param[in] res not empty - computes normalized residuals and returns them in this array
1678///
1679/// The current implementation is based on the papers \f$ \chi^{2} \f$ test for comparison
1680/// of weighted and unweighted histograms" in Proceedings of PHYSTAT05 and
1681/// "Comparison weighted and unweighted histograms", arXiv:physics/0605123
1682/// by N.Gagunashvili. This function has been implemented by Daniel Haertl in August 2006.
1683///
1684/// #### Introduction:
1685///
1686/// A frequently used technique in data analysis is the comparison of
1687/// histograms. First suggested by Pearson [1] the \f$ \chi^{2} \f$ test of
1688/// homogeneity is used widely for comparing usual (unweighted) histograms.
1689/// This paper describes the implementation modified \f$ \chi^{2} \f$ tests
1690/// for comparison of weighted and unweighted histograms and two weighted
1691/// histograms [2] as well as usual Pearson's \f$ \chi^{2} \f$ test for
1692/// comparison two usual (unweighted) histograms.
1693///
1694/// #### Overview:
1695///
1696/// Comparison of two histograms expect hypotheses that two histograms
1697/// represent identical distributions. To make a decision p-value should
1698/// be calculated. The hypotheses of identity is rejected if the p-value is
1699/// lower then some significance level. Traditionally significance levels
1700/// 0.1, 0.05 and 0.01 are used. The comparison procedure should include an
1701/// analysis of the residuals which is often helpful in identifying the
1702/// bins of histograms responsible for a significant overall \f$ \chi^{2} \f$ value.
1703/// Residuals are the difference between bin contents and expected bin
1704/// contents. Most convenient for analysis are the normalized residuals. If
1705/// hypotheses of identity are valid then normalized residuals are
1706/// approximately independent and identically distributed random variables
1707/// having N(0,1) distribution. Analysis of residuals expect test of above
1708/// mentioned properties of residuals. Notice that indirectly the analysis
1709/// of residuals increase the power of \f$ \chi^{2} \f$ test.
1710///
1711/// #### Methods of comparison:
1712///
1713/// \f$ \chi^{2} \f$ test for comparison two (unweighted) histograms:
1714/// Let us consider two histograms with the same binning and the number
1715/// of bins equal to r. Let us denote the number of events in the ith bin
1716/// in the first histogram as ni and as mi in the second one. The total
1717/// number of events in the first histogram is equal to:
1718/// \f[
1719/// N = \sum_{i=1}^{r} n_{i}
1720/// \f]
1721/// and
1722/// \f[
1723/// M = \sum_{i=1}^{r} m_{i}
1724/// \f]
1725/// in the second histogram. The hypothesis of identity (homogeneity) [3]
1726/// is that the two histograms represent random values with identical
1727/// distributions. It is equivalent that there exist r constants p1,...,pr,
1728/// such that
1729/// \f[
1730///\sum_{i=1}^{r} p_{i}=1
1731/// \f]
1732/// and the probability of belonging to the ith bin for some measured value
1733/// in both experiments is equal to pi. The number of events in the ith
1734/// bin is a random variable with a distribution approximated by a Poisson
1735/// probability distribution
1736/// \f[
1737///\frac{e^{-Np_{i}}(Np_{i})^{n_{i}}}{n_{i}!}
1738/// \f]
1739///for the first histogram and with distribution
1740/// \f[
1741///\frac{e^{-Mp_{i}}(Mp_{i})^{m_{i}}}{m_{i}!}
1742/// \f]
1743/// for the second histogram. If the hypothesis of homogeneity is valid,
1744/// then the maximum likelihood estimator of pi, i=1,...,r, is
1745/// \f[
1746///\hat{p}_{i}= \frac{n_{i}+m_{i}}{N+M}
1747/// \f]
1748/// and then
1749/// \f[
1750/// 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}}
1751/// \f]
1752/// has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [3].
1753/// The comparison procedure can include an analysis of the residuals which
1754/// is often helpful in identifying the bins of histograms responsible for
1755/// a significant overall \f$ \chi^{2} \f$ value. Most convenient for
1756/// analysis are the adjusted (normalized) residuals [4]
1757/// \f[
1758/// 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))}}
1759/// \f]
1760/// If hypotheses of homogeneity are valid then residuals ri are
1761/// approximately independent and identically distributed random variables
1762/// having N(0,1) distribution. The application of the \f$ \chi^{2} \f$ test has
1763/// restrictions related to the value of the expected frequencies Npi,
1764/// Mpi, i=1,...,r. A conservative rule formulated in [5] is that all the
1765/// expectations must be 1 or greater for both histograms. In practical
1766/// cases when expected frequencies are not known the estimated expected
1767/// frequencies \f$ M\hat{p}_{i}, N\hat{p}_{i}, i=1,...,r \f$ can be used.
1768///
1769/// #### Unweighted and weighted histograms comparison:
1770///
1771/// A simple modification of the ideas described above can be used for the
1772/// comparison of the usual (unweighted) and weighted histograms. Let us
1773/// denote the number of events in the ith bin in the unweighted
1774/// histogram as ni and the common weight of events in the ith bin of the
1775/// weighted histogram as wi. The total number of events in the
1776/// unweighted histogram is equal to
1777///\f[
1778/// N = \sum_{i=1}^{r} n_{i}
1779///\f]
1780/// and the total weight of events in the weighted histogram is equal to
1781///\f[
1782/// W = \sum_{i=1}^{r} w_{i}
1783///\f]
1784/// Let us formulate the hypothesis of identity of an unweighted histogram
1785/// to a weighted histogram so that there exist r constants p1,...,pr, such
1786/// that
1787///\f[
1788/// \sum_{i=1}^{r} p_{i} = 1
1789///\f]
1790/// for the unweighted histogram. The weight wi is a random variable with a
1791/// distribution approximated by the normal probability distribution
1792/// \f$ N(Wp_{i},\sigma_{i}^{2}) \f$ where \f$ \sigma_{i}^{2} \f$ is the variance of the weight wi.
1793/// If we replace the variance \f$ \sigma_{i}^{2} \f$
1794/// with estimate \f$ s_{i}^{2} \f$ (sum of squares of weights of
1795/// events in the ith bin) and the hypothesis of identity is valid, then the
1796/// maximum likelihood estimator of pi,i=1,...,r, is
1797///\f[
1798/// \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}}
1799///\f]
1800/// We may then use the test statistic
1801///\f[
1802/// 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}}
1803///\f]
1804/// and it has approximately a \f$ \sigma^{2}_{(r-1)} \f$ distribution [2]. This test, as well
1805/// as the original one [3], has a restriction on the expected frequencies. The
1806/// expected frequencies recommended for the weighted histogram is more than 25.
1807/// The value of the minimal expected frequency can be decreased down to 10 for
1808/// the case when the weights of the events are close to constant. In the case
1809/// of a weighted histogram if the number of events is unknown, then we can
1810/// apply this recommendation for the equivalent number of events as
1811///\f[
1812/// n_{i}^{equiv} = \frac{ w_{i}^{2} }{ s_{i}^{2} }
1813///\f]
1814/// The minimal expected frequency for an unweighted histogram must be 1. Notice
1815/// that any usual (unweighted) histogram can be considered as a weighted
1816/// histogram with events that have constant weights equal to 1.
1817/// The variance \f$ z_{i}^{2} \f$ of the difference between the weight wi
1818/// and the estimated expectation value of the weight is approximately equal to:
1819///\f[
1820/// 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}
1821///\f]
1822/// The residuals
1823///\f[
1824/// r_{i} = \frac{w_{i}-W\hat{p}_{i}}{z_{i}}
1825///\f]
1826/// have approximately a normal distribution with mean equal to 0 and standard
1827/// deviation equal to 1.
1828///
1829/// #### Two weighted histograms comparison:
1830///
1831/// Let us denote the common weight of events of the ith bin in the first
1832/// histogram as w1i and as w2i in the second one. The total weight of events
1833/// in the first histogram is equal to
1834///\f[
1835/// W_{1} = \sum_{i=1}^{r} w_{1i}
1836///\f]
1837/// and
1838///\f[
1839/// W_{2} = \sum_{i=1}^{r} w_{2i}
1840///\f]
1841/// in the second histogram. Let us formulate the hypothesis of identity of
1842/// weighted histograms so that there exist r constants p1,...,pr, such that
1843///\f[
1844/// \sum_{i=1}^{r} p_{i} = 1
1845///\f]
1846/// and also expectation value of weight w1i equal to W1pi and expectation value
1847/// of weight w2i equal to W2pi. Weights in both the histograms are random
1848/// variables with distributions which can be approximated by a normal
1849/// probability distribution \f$ N(W_{1}p_{i},\sigma_{1i}^{2}) \f$ for the first histogram
1850/// and by a distribution \f$ N(W_{2}p_{i},\sigma_{2i}^{2}) \f$ for the second.
1851/// Here \f$ \sigma_{1i}^{2} \f$ and \f$ \sigma_{2i}^{2} \f$ are the variances
1852/// of w1i and w2i with estimators \f$ s_{1i}^{2} \f$ and \f$ s_{2i}^{2} \f$ respectively.
1853/// If the hypothesis of identity is valid, then the maximum likelihood and
1854/// Least Square Method estimator of pi,i=1,...,r, is
1855///\f[
1856/// \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}}
1857///\f]
1858/// We may then use the test statistic
1859///\f[
1860/// 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}}
1861///\f]
1862/// and it has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [2].
1863/// The normalized or studentised residuals [6]
1864///\f[
1865/// 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})}}}
1866///\f]
1867/// have approximately a normal distribution with mean equal to 0 and standard
1868/// deviation 1. A recommended minimal expected frequency is equal to 10 for
1869/// the proposed test.
1870///
1871/// #### Numerical examples:
1872///
1873/// The method described herein is now illustrated with an example.
1874/// We take a distribution
1875///\f[
1876/// \phi(x) = \frac{2}{(x-10)^{2}+1} + \frac{1}{(x-14)^{2}+1} (1)
1877///\f]
1878/// defined on the interval [4,16]. Events distributed according to the formula
1879/// (1) are simulated to create the unweighted histogram. Uniformly distributed
1880/// events are simulated for the weighted histogram with weights calculated by
1881/// formula (1). Each histogram has the same number of bins: 20. Fig.1 shows
1882/// the result of comparison of the unweighted histogram with 200 events
1883/// (minimal expected frequency equal to one) and the weighted histogram with
1884/// 500 events (minimal expected frequency equal to 25)
1885/// Begin_Macro
1886/// ../../../tutorials/math/chi2test.C
1887/// End_Macro
1888/// Fig 1. An example of comparison of the unweighted histogram with 200 events
1889/// and the weighted histogram with 500 events:
1890/// 1. unweighted histogram;
1891/// 2. weighted histogram;
1892/// 3. normalized residuals plot;
1893/// 4. normal Q-Q plot of residuals.
1894///
1895/// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1896/// 21.09 with p-value equal to 0.33, therefore the hypothesis of identity of
1897/// the two histograms can be accepted for 0.05 significant level. The behavior
1898/// of the normalized residuals plot (see Fig. 1c) and the normal Q-Q plot
1899/// (see Fig. 1d) of residuals are regular and we cannot identify the outliers
1900/// or bins with a big influence on \f$ \chi^{2} \f$.
1901///
1902/// The second example presents the same two histograms but 17 events was added
1903/// to content of bin number 15 in unweighted histogram. Fig.2 shows the result
1904/// of comparison of the unweighted histogram with 217 events (minimal expected
1905/// frequency equal to one) and the weighted histogram with 500 events (minimal
1906/// expected frequency equal to 25)
1907/// Begin_Macro
1908/// ../../../tutorials/math/chi2test.C(17)
1909/// End_Macro
1910/// Fig 2. An example of comparison of the unweighted histogram with 217 events
1911/// and the weighted histogram with 500 events:
1912/// 1. unweighted histogram;
1913/// 2. weighted histogram;
1914/// 3. normalized residuals plot;
1915/// 4. normal Q-Q plot of residuals.
1916///
1917/// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1918/// 32.33 with p-value equal to 0.029, therefore the hypothesis of identity of
1919/// the two histograms is rejected for 0.05 significant level. The behavior of
1920/// the normalized residuals plot (see Fig. 2c) and the normal Q-Q plot (see
1921/// Fig. 2d) of residuals are not regular and we can identify the outlier or
1922/// bin with a big influence on \f$ \chi^{2} \f$.
1923///
1924/// #### References:
1925///
1926/// - [1] Pearson, K., 1904. On the Theory of Contingency and Its Relation to
1927/// Association and Normal Correlation. Drapers' Co. Memoirs, Biometric
1928/// Series No. 1, London.
1929/// - [2] Gagunashvili, N., 2006. \f$ \sigma^{2} \f$ test for comparison
1930/// of weighted and unweighted histograms. Statistical Problems in Particle
1931/// Physics, Astrophysics and Cosmology, Proceedings of PHYSTAT05,
1932/// Oxford, UK, 12-15 September 2005, Imperial College Press, London, 43-44.
1933/// Gagunashvili,N., Comparison of weighted and unweighted histograms,
1934/// arXiv:physics/0605123, 2006.
1935/// - [3] Cramer, H., 1946. Mathematical methods of statistics.
1936/// Princeton University Press, Princeton.
1937/// - [4] Haberman, S.J., 1973. The analysis of residuals in cross-classified tables.
1938/// Biometrics 29, 205-220.
1939/// - [5] Lewontin, R.C. and Felsenstein, J., 1965. The robustness of homogeneity
1940/// test in 2xN tables. Biometrics 21, 19-33.
1941/// - [6] Seber, G.A.F., Lee, A.J., 2003, Linear Regression Analysis.
1942/// John Wiley & Sons Inc., New York.
1943
1944Double_t TH1::Chi2Test(const TH1* h2, Option_t *option, Double_t *res) const
1945{
1946 Double_t chi2 = 0;
1947 Int_t ndf = 0, igood = 0;
1948
1949 TString opt = option;
1950 opt.ToUpper();
1951
1952 Double_t prob = Chi2TestX(h2,chi2,ndf,igood,option,res);
1953
1954 if(opt.Contains("P")) {
1955 printf("Chi2 = %f, Prob = %g, NDF = %d, igood = %d\n", chi2,prob,ndf,igood);
1956 }
1957 if(opt.Contains("CHI2/NDF")) {
1958 if (ndf == 0) return 0;
1959 return chi2/ndf;
1960 }
1961 if(opt.Contains("CHI2")) {
1962 return chi2;
1963 }
1964
1965 return prob;
1966}
1967
1968////////////////////////////////////////////////////////////////////////////////
1969/// The computation routine of the Chisquare test. For the method description,
1970/// see Chi2Test() function.
1971///
1972/// \return p-value
1973/// \param[in] h2 the second histogram
1974/// \param[in] option
1975/// - "UU" = experiment experiment comparison (unweighted-unweighted)
1976/// - "UW" = experiment MC comparison (unweighted-weighted). Note that the first
1977/// histogram should be unweighted
1978/// - "WW" = MC MC comparison (weighted-weighted)
1979/// - "NORM" = if one or both histograms is scaled
1980/// - "OF" = overflows included
1981/// - "UF" = underflows included
1982/// by default underflows and overflows are not included
1983/// \param[out] igood test output
1984/// - igood=0 - no problems
1985/// - For unweighted unweighted comparison
1986/// - igood=1'There is a bin in the 1st histogram with less than 1 event'
1987/// - igood=2'There is a bin in the 2nd histogram with less than 1 event'
1988/// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1989/// - For unweighted weighted comparison
1990/// - igood=1'There is a bin in the 1st histogram with less then 1 event'
1991/// - igood=2'There is a bin in the 2nd histogram with less then 10 effective number of events'
1992/// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1993/// - For weighted weighted comparison
1994/// - igood=1'There is a bin in the 1st histogram with less then 10 effective
1995/// number of events'
1996/// - igood=2'There is a bin in the 2nd histogram with less then 10 effective
1997/// number of events'
1998/// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1999/// \param[out] chi2 chisquare of the test
2000/// \param[out] ndf number of degrees of freedom (important, when both histograms have the same empty bins)
2001/// \param[out] res normalized residuals for further analysis
2002
2003Double_t TH1::Chi2TestX(const TH1* h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option, Double_t *res) const
2004{
2005
2006 Int_t i_start, i_end;
2007 Int_t j_start, j_end;
2008 Int_t k_start, k_end;
2009
2010 Double_t sum1 = 0.0, sumw1 = 0.0;
2011 Double_t sum2 = 0.0, sumw2 = 0.0;
2012
2013 chi2 = 0.0;
2014 ndf = 0;
2015
2016 TString opt = option;
2017 opt.ToUpper();
2018
2019 if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
2020
2021 const TAxis *xaxis1 = GetXaxis();
2022 const TAxis *xaxis2 = h2->GetXaxis();
2023 const TAxis *yaxis1 = GetYaxis();
2024 const TAxis *yaxis2 = h2->GetYaxis();
2025 const TAxis *zaxis1 = GetZaxis();
2026 const TAxis *zaxis2 = h2->GetZaxis();
2027
2028 Int_t nbinx1 = xaxis1->GetNbins();
2029 Int_t nbinx2 = xaxis2->GetNbins();
2030 Int_t nbiny1 = yaxis1->GetNbins();
2031 Int_t nbiny2 = yaxis2->GetNbins();
2032 Int_t nbinz1 = zaxis1->GetNbins();
2033 Int_t nbinz2 = zaxis2->GetNbins();
2034
2035 //check dimensions
2036 if (this->GetDimension() != h2->GetDimension() ){
2037 Error("Chi2TestX","Histograms have different dimensions.");
2038 return 0.0;
2039 }
2040
2041 //check number of channels
2042 if (nbinx1 != nbinx2) {
2043 Error("Chi2TestX","different number of x channels");
2044 }
2045 if (nbiny1 != nbiny2) {
2046 Error("Chi2TestX","different number of y channels");
2047 }
2048 if (nbinz1 != nbinz2) {
2049 Error("Chi2TestX","different number of z channels");
2050 }
2051
2052 //check for ranges
2053 i_start = j_start = k_start = 1;
2054 i_end = nbinx1;
2055 j_end = nbiny1;
2056 k_end = nbinz1;
2057
2058 if (xaxis1->TestBit(TAxis::kAxisRange)) {
2059 i_start = xaxis1->GetFirst();
2060 i_end = xaxis1->GetLast();
2061 }
2062 if (yaxis1->TestBit(TAxis::kAxisRange)) {
2063 j_start = yaxis1->GetFirst();
2064 j_end = yaxis1->GetLast();
2065 }
2066 if (zaxis1->TestBit(TAxis::kAxisRange)) {
2067 k_start = zaxis1->GetFirst();
2068 k_end = zaxis1->GetLast();
2069 }
2070
2071
2072 if (opt.Contains("OF")) {
2073 if (GetDimension() == 3) k_end = ++nbinz1;
2074 if (GetDimension() >= 2) j_end = ++nbiny1;
2075 if (GetDimension() >= 1) i_end = ++nbinx1;
2076 }
2077
2078 if (opt.Contains("UF")) {
2079 if (GetDimension() == 3) k_start = 0;
2080 if (GetDimension() >= 2) j_start = 0;
2081 if (GetDimension() >= 1) i_start = 0;
2082 }
2083
2084 ndf = (i_end - i_start + 1) * (j_end - j_start + 1) * (k_end - k_start + 1) - 1;
2085
2086 Bool_t comparisonUU = opt.Contains("UU");
2087 Bool_t comparisonUW = opt.Contains("UW");
2088 Bool_t comparisonWW = opt.Contains("WW");
2089 Bool_t scaledHistogram = opt.Contains("NORM");
2090
2091 if (scaledHistogram && !comparisonUU) {
2092 Info("Chi2TestX", "NORM option should be used together with UU option. It is ignored");
2093 }
2094
2095 // look at histo global bin content and effective entries
2096 Stat_t s[kNstat];
2097 GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
2098 Double_t sumBinContent1 = s[0];
2099 Double_t effEntries1 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
2100
2101 h2->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
2102 Double_t sumBinContent2 = s[0];
2103 Double_t effEntries2 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
2104
2105 if (!comparisonUU && !comparisonUW && !comparisonWW ) {
2106 // deduce automatically from type of histogram
2107 if (TMath::Abs(sumBinContent1 - effEntries1) < 1) {
2108 if ( TMath::Abs(sumBinContent2 - effEntries2) < 1) comparisonUU = true;
2109 else comparisonUW = true;
2110 }
2111 else comparisonWW = true;
2112 }
2113 // check unweighted histogram
2114 if (comparisonUW) {
2115 if (TMath::Abs(sumBinContent1 - effEntries1) >= 1) {
2116 Warning("Chi2TestX","First histogram is not unweighted and option UW has been requested");
2117 }
2118 }
2119 if ( (!scaledHistogram && comparisonUU) ) {
2120 if ( ( TMath::Abs(sumBinContent1 - effEntries1) >= 1) || (TMath::Abs(sumBinContent2 - effEntries2) >= 1) ) {
2121 Warning("Chi2TestX","Both histograms are not unweighted and option UU has been requested");
2122 }
2123 }
2124
2125
2126 //get number of events in histogram
2127 if (comparisonUU && scaledHistogram) {
2128 for (Int_t i = i_start; i <= i_end; ++i) {
2129 for (Int_t j = j_start; j <= j_end; ++j) {
2130 for (Int_t k = k_start; k <= k_end; ++k) {
2131
2132 Int_t bin = GetBin(i, j, k);
2133
2134 Double_t cnt1 = RetrieveBinContent(bin);
2135 Double_t cnt2 = h2->RetrieveBinContent(bin);
2136 Double_t e1sq = GetBinErrorSqUnchecked(bin);
2137 Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2138
2139 if (e1sq > 0.0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2140 else cnt1 = 0.0;
2141
2142 if (e2sq > 0.0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2143 else cnt2 = 0.0;
2144
2145 // sum contents
2146 sum1 += cnt1;
2147 sum2 += cnt2;
2148 sumw1 += e1sq;
2149 sumw2 += e2sq;
2150 }
2151 }
2152 }
2153 if (sumw1 <= 0.0 || sumw2 <= 0.0) {
2154 Error("Chi2TestX", "Cannot use option NORM when one histogram has all zero errors");
2155 return 0.0;
2156 }
2157
2158 } else {
2159 for (Int_t i = i_start; i <= i_end; ++i) {
2160 for (Int_t j = j_start; j <= j_end; ++j) {
2161 for (Int_t k = k_start; k <= k_end; ++k) {
2162
2163 Int_t bin = GetBin(i, j, k);
2164
2165 sum1 += RetrieveBinContent(bin);
2166 sum2 += h2->RetrieveBinContent(bin);
2167
2168 if ( comparisonWW ) sumw1 += GetBinErrorSqUnchecked(bin);
2169 if ( comparisonUW || comparisonWW ) sumw2 += h2->GetBinErrorSqUnchecked(bin);
2170 }
2171 }
2172 }
2173 }
2174 //checks that the histograms are not empty
2175 if (sum1 == 0.0 || sum2 == 0.0) {
2176 Error("Chi2TestX","one histogram is empty");
2177 return 0.0;
2178 }
2179
2180 if ( comparisonWW && ( sumw1 <= 0.0 && sumw2 <= 0.0 ) ){
2181 Error("Chi2TestX","Hist1 and Hist2 have both all zero errors\n");
2182 return 0.0;
2183 }
2184
2185 //THE TEST
2186 Int_t m = 0, n = 0;
2187
2188 //Experiment - experiment comparison
2189 if (comparisonUU) {
2190 Double_t sum = sum1 + sum2;
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
2197 Double_t cnt1 = RetrieveBinContent(bin);
2198 Double_t cnt2 = h2->RetrieveBinContent(bin);
2199
2200 if (scaledHistogram) {
2201 // scale bin value to effective bin entries
2202 Double_t e1sq = GetBinErrorSqUnchecked(bin);
2203 Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2204
2205 if (e1sq > 0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2206 else cnt1 = 0;
2207
2208 if (e2sq > 0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2209 else cnt2 = 0;
2210 }
2211
2212 if (Int_t(cnt1) == 0 && Int_t(cnt2) == 0) --ndf; // no data means one degree of freedom less
2213 else {
2214
2215 Double_t cntsum = cnt1 + cnt2;
2216 Double_t nexp1 = cntsum * sum1 / sum;
2217 //Double_t nexp2 = binsum*sum2/sum;
2218
2219 if (res) res[i - i_start] = (cnt1 - nexp1) / TMath::Sqrt(nexp1);
2220
2221 if (cnt1 < 1) ++m;
2222 if (cnt2 < 1) ++n;
2223
2224 //Habermann correction for residuals
2225 Double_t correc = (1. - sum1 / sum) * (1. - cntsum / sum);
2226 if (res) res[i - i_start] /= TMath::Sqrt(correc);
2227
2228 Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2229 chi2 += delta * delta / cntsum;
2230 }
2231 }
2232 }
2233 }
2234 chi2 /= sum1 * sum2;
2235
2236 // flag error only when of the two histogram is zero
2237 if (m) {
2238 igood += 1;
2239 Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2240 }
2241 if (n) {
2242 igood += 2;
2243 Info("Chi2TestX","There is a bin in h2 with less than 1 event.\n");
2244 }
2245
2246 Double_t prob = TMath::Prob(chi2,ndf);
2247 return prob;
2248
2249 }
2250
2251 // unweighted - weighted comparison
2252 // case of error = 0 and content not zero is treated without problems by excluding second chi2 sum
2253 // and can be considered as a data-theory comparison
2254 if ( comparisonUW ) {
2255 for (Int_t i = i_start; i <= i_end; ++i) {
2256 for (Int_t j = j_start; j <= j_end; ++j) {
2257 for (Int_t k = k_start; k <= k_end; ++k) {
2258
2259 Int_t bin = GetBin(i, j, k);
2260
2261 Double_t cnt1 = RetrieveBinContent(bin);
2262 Double_t cnt2 = h2->RetrieveBinContent(bin);
2263 Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2264
2265 // case both histogram have zero bin contents
2266 if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2267 --ndf; //no data means one degree of freedom less
2268 continue;
2269 }
2270
2271 // case weighted histogram has zero bin content and error
2272 if (cnt2 * cnt2 == 0 && e2sq == 0) {
2273 if (sumw2 > 0) {
2274 // use as approximated error as 1 scaled by a scaling ratio
2275 // estimated from the total sum weight and sum weight squared
2276 e2sq = sumw2 / sum2;
2277 }
2278 else {
2279 // return error because infinite discrepancy here:
2280 // bin1 != 0 and bin2 =0 in a histogram with all errors zero
2281 Error("Chi2TestX","Hist2 has in bin (%d,%d,%d) zero content and zero errors\n", i, j, k);
2282 chi2 = 0; return 0;
2283 }
2284 }
2285
2286 if (cnt1 < 1) m++;
2287 if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2288
2289 Double_t var1 = sum2 * cnt2 - sum1 * e2sq;
2290 Double_t var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2291
2292 // if cnt1 is zero and cnt2 = 1 and sum1 = sum2 var1 = 0 && var2 == 0
2293 // approximate by incrementing cnt1
2294 // LM (this need to be fixed for numerical errors)
2295 while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2296 sum1++;
2297 cnt1++;
2298 var1 = sum2 * cnt2 - sum1 * e2sq;
2299 var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2300 }
2301 var2 = TMath::Sqrt(var2);
2302
2303 while (var1 + var2 == 0) {
2304 sum1++;
2305 cnt1++;
2306 var1 = sum2 * cnt2 - sum1 * e2sq;
2307 var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2308 while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2309 sum1++;
2310 cnt1++;
2311 var1 = sum2 * cnt2 - sum1 * e2sq;
2312 var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2313 }
2314 var2 = TMath::Sqrt(var2);
2315 }
2316
2317 Double_t probb = (var1 + var2) / (2. * sum2 * sum2);
2318
2319 Double_t nexp1 = probb * sum1;
2320 Double_t nexp2 = probb * sum2;
2321
2322 Double_t delta1 = cnt1 - nexp1;
2323 Double_t delta2 = cnt2 - nexp2;
2324
2325 chi2 += delta1 * delta1 / nexp1;
2326
2327 if (e2sq > 0) {
2328 chi2 += delta2 * delta2 / e2sq;
2329 }
2330
2331 if (res) {
2332 if (e2sq > 0) {
2333 Double_t temp1 = sum2 * e2sq / var2;
2334 Double_t temp2 = 1.0 + (sum1 * e2sq - sum2 * cnt2) / var2;
2335 temp2 = temp1 * temp1 * sum1 * probb * (1.0 - probb) + temp2 * temp2 * e2sq / 4.0;
2336 // invert sign here
2337 res[i - i_start] = - delta2 / TMath::Sqrt(temp2);
2338 }
2339 else
2340 res[i - i_start] = delta1 / TMath::Sqrt(nexp1);
2341 }
2342 }
2343 }
2344 }
2345
2346 if (m) {
2347 igood += 1;
2348 Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2349 }
2350 if (n) {
2351 igood += 2;
2352 Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2353 }
2354
2355 Double_t prob = TMath::Prob(chi2, ndf);
2356
2357 return prob;
2358 }
2359
2360 // weighted - weighted comparison
2361 if (comparisonWW) {
2362 for (Int_t i = i_start; i <= i_end; ++i) {
2363 for (Int_t j = j_start; j <= j_end; ++j) {
2364 for (Int_t k = k_start; k <= k_end; ++k) {
2365
2366 Int_t bin = GetBin(i, j, k);
2367 Double_t cnt1 = RetrieveBinContent(bin);
2368 Double_t cnt2 = h2->RetrieveBinContent(bin);
2369 Double_t e1sq = GetBinErrorSqUnchecked(bin);
2370 Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2371
2372 // case both histogram have zero bin contents
2373 // (use square of content to avoid numerical errors)
2374 if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2375 --ndf; //no data means one degree of freedom less
2376 continue;
2377 }
2378
2379 if (e1sq == 0 && e2sq == 0) {
2380 // cannot treat case of booth histogram have zero zero errors
2381 Error("Chi2TestX","h1 and h2 both have bin %d,%d,%d with all zero errors\n", i,j,k);
2382 chi2 = 0; return 0;
2383 }
2384
2385 Double_t sigma = sum1 * sum1 * e2sq + sum2 * sum2 * e1sq;
2386 Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2387 chi2 += delta * delta / sigma;
2388
2389 if (res) {
2390 Double_t temp = cnt1 * sum1 * e2sq + cnt2 * sum2 * e1sq;
2391 Double_t probb = temp / sigma;
2392 Double_t z = 0;
2393 if (e1sq > e2sq) {
2394 Double_t d1 = cnt1 - sum1 * probb;
2395 Double_t s1 = e1sq * ( 1. - e2sq * sum1 * sum1 / sigma );
2396 z = d1 / TMath::Sqrt(s1);
2397 }
2398 else {
2399 Double_t d2 = cnt2 - sum2 * probb;
2400 Double_t s2 = e2sq * ( 1. - e1sq * sum2 * sum2 / sigma );
2401 z = -d2 / TMath::Sqrt(s2);
2402 }
2403 res[i - i_start] = z;
2404 }
2405
2406 if (e1sq > 0 && cnt1 * cnt1 / e1sq < 10) m++;
2407 if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2408 }
2409 }
2410 }
2411 if (m) {
2412 igood += 1;
2413 Info("Chi2TestX","There is a bin in h1 with less than 10 effective events.\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 Double_t prob = TMath::Prob(chi2, ndf);
2420 return prob;
2421 }
2422 return 0;
2423}
2424////////////////////////////////////////////////////////////////////////////////
2425/// Compute and return the chisquare of this histogram with respect to a function
2426/// The chisquare is computed by weighting each histogram point by the bin error
2427/// By default the full range of the histogram is used.
2428/// Use option "R" for restricting the chisquare calculation to the given range of the function
2429/// Use option "L" for using the chisquare based on the poisson likelihood (Baker-Cousins Chisquare)
2430
2431Double_t TH1::Chisquare(TF1 * func, Option_t *option) const
2432{
2433 if (!func) {
2434 Error("Chisquare","Function pointer is Null - return -1");
2435 return -1;
2436 }
2437
2438 TString opt(option); opt.ToUpper();
2439 bool useRange = opt.Contains("R");
2440 bool usePL = opt.Contains("L");
2441
2442 return ROOT::Fit::Chisquare(*this, *func, useRange, usePL);
2443}
2444
2445////////////////////////////////////////////////////////////////////////////////
2446/// Remove all the content from the underflow and overflow bins, without changing the number of entries
2447/// After calling this method, every undeflow and overflow bins will have content 0.0
2448/// The Sumw2 is also cleared, since there is no more content in the bins
2449
2451{
2452 for (Int_t bin = 0; bin < fNcells; ++bin)
2453 if (IsBinUnderflow(bin) || IsBinOverflow(bin)) {
2454 UpdateBinContent(bin, 0.0);
2455 if (fSumw2.fN) fSumw2.fArray[bin] = 0.0;
2456 }
2457}
2458
2459////////////////////////////////////////////////////////////////////////////////
2460/// Compute integral (cumulative sum of bins)
2461/// The result stored in fIntegral is used by the GetRandom functions.
2462/// This function is automatically called by GetRandom when the fIntegral
2463/// array does not exist or when the number of entries in the histogram
2464/// has changed since the previous call to GetRandom.
2465/// The resulting integral is normalized to 1
2466/// If the routine is called with the onlyPositive flag set an error will
2467/// be produced in case of negative bin content and a NaN value returned
2468
2470{
2471 if (fBuffer) BufferEmpty();
2472
2473 // delete previously computed integral (if any)
2474 if (fIntegral) delete [] fIntegral;
2475
2476 // - Allocate space to store the integral and compute integral
2477 Int_t nbinsx = GetNbinsX();
2478 Int_t nbinsy = GetNbinsY();
2479 Int_t nbinsz = GetNbinsZ();
2480 Int_t nbins = nbinsx * nbinsy * nbinsz;
2481
2482 fIntegral = new Double_t[nbins + 2];
2483 Int_t ibin = 0; fIntegral[ibin] = 0;
2484
2485 for (Int_t binz=1; binz <= nbinsz; ++binz) {
2486 for (Int_t biny=1; biny <= nbinsy; ++biny) {
2487 for (Int_t binx=1; binx <= nbinsx; ++binx) {
2488 ++ibin;
2489 Double_t y = RetrieveBinContent(GetBin(binx, biny, binz));
2490 if (onlyPositive && y < 0) {
2491 Error("ComputeIntegral","Bin content is negative - return a NaN value");
2492 fIntegral[nbins] = TMath::QuietNaN();
2493 break;
2494 }
2495 fIntegral[ibin] = fIntegral[ibin - 1] + y;
2496 }
2497 }
2498 }
2499
2500 // - Normalize integral to 1
2501 if (fIntegral[nbins] == 0 ) {
2502 Error("ComputeIntegral", "Integral = zero"); return 0;
2503 }
2504 for (Int_t bin=1; bin <= nbins; ++bin) fIntegral[bin] /= fIntegral[nbins];
2505 fIntegral[nbins+1] = fEntries;
2506 return fIntegral[nbins];
2507}
2508
2509////////////////////////////////////////////////////////////////////////////////
2510/// Return a pointer to the array of bins integral.
2511/// if the pointer fIntegral is null, TH1::ComputeIntegral is called
2512/// The array dimension is the number of bins in the histograms
2513/// including underflow and overflow (fNCells)
2514/// the last value integral[fNCells] is set to the number of entries of
2515/// the histogram
2516
2518{
2519 if (!fIntegral) ComputeIntegral();
2520 return fIntegral;
2521}
2522
2523////////////////////////////////////////////////////////////////////////////////
2524/// Return a pointer to an histogram containing the cumulative The
2525/// cumulative can be computed both in the forward (default) or backward
2526/// direction; the name of the new histogram is constructed from
2527/// the name of this histogram with the suffix suffix appended.
2528///
2529/// The cumulative distribution is formed by filling each bin of the
2530/// resulting histogram with the sum of that bin and all previous
2531/// (forward == kTRUE) or following (forward = kFALSE) bins.
2532///
2533/// note: while cumulative distributions make sense in one dimension, you
2534/// may not be getting what you expect in more than 1D because the concept
2535/// of a cumulative distribution is much trickier to define; make sure you
2536/// understand the order of summation before you use this method with
2537/// histograms of dimension >= 2.
2538
2539TH1 *TH1::GetCumulative(Bool_t forward, const char* suffix) const
2540{
2541 const Int_t nbinsx = GetNbinsX();
2542 const Int_t nbinsy = GetNbinsY();
2543 const Int_t nbinsz = GetNbinsZ();
2544 TH1* hintegrated = (TH1*) Clone(fName + suffix);
2545 hintegrated->Reset();
2546 if (forward) { // Forward computation
2547 Double_t sum = 0.;
2548 for (Int_t binz = 1; binz <= nbinsz; ++binz) {
2549 for (Int_t biny = 1; biny <= nbinsy; ++biny) {
2550 for (Int_t binx = 1; binx <= nbinsx; ++binx) {
2551 const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2552 sum += GetBinContent(bin);
2553 hintegrated->SetBinContent(bin, sum);
2554 }
2555 }
2556 }
2557 } else { // Backward computation
2558 Double_t sum = 0.;
2559 for (Int_t binz = nbinsz; binz >= 1; --binz) {
2560 for (Int_t biny = nbinsy; biny >= 1; --biny) {
2561 for (Int_t binx = nbinsx; binx >= 1; --binx) {
2562 const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2563 sum += GetBinContent(bin);
2564 hintegrated->SetBinContent(bin, sum);
2565 }
2566 }
2567 }
2568 }
2569 return hintegrated;
2570}
2571
2572////////////////////////////////////////////////////////////////////////////////
2573/// Copy this histogram structure to newth1.
2574///
2575/// Note that this function does not copy the list of associated functions.
2576/// Use TObject::Clone to make a full copy of an histogram.
2577///
2578/// Note also that the histogram it will be created in gDirectory (if AddDirectoryStatus()=true)
2579/// or will not be added to any directory if AddDirectoryStatus()=false
2580/// independently of the current directory stored in the original histogram
2581
2582void TH1::Copy(TObject &obj) const
2583{
2584 if (((TH1&)obj).fDirectory) {
2585 // We are likely to change the hash value of this object
2586 // with TNamed::Copy, to keep things correct, we need to
2587 // clean up its existing entries.
2588 ((TH1&)obj).fDirectory->Remove(&obj);
2589 ((TH1&)obj).fDirectory = 0;
2590 }
2591 TNamed::Copy(obj);
2592 ((TH1&)obj).fDimension = fDimension;
2593 ((TH1&)obj).fNormFactor= fNormFactor;
2594 ((TH1&)obj).fNcells = fNcells;
2595 ((TH1&)obj).fBarOffset = fBarOffset;
2596 ((TH1&)obj).fBarWidth = fBarWidth;
2597 ((TH1&)obj).fOption = fOption;
2598 ((TH1&)obj).fBinStatErrOpt = fBinStatErrOpt;
2599 ((TH1&)obj).fBufferSize= fBufferSize;
2600 // copy the Buffer
2601 // delete first a previously existing buffer
2602 if (((TH1&)obj).fBuffer != 0) {
2603 delete [] ((TH1&)obj).fBuffer;
2604 ((TH1&)obj).fBuffer = 0;
2605 }
2606 if (fBuffer) {
2607 Double_t *buf = new Double_t[fBufferSize];
2608 for (Int_t i=0;i<fBufferSize;i++) buf[i] = fBuffer[i];
2609 // obj.fBuffer has been deleted before
2610 ((TH1&)obj).fBuffer = buf;
2611 }
2612
2613
2614 TArray* a = dynamic_cast<TArray*>(&obj);
2615 if (a) a->Set(fNcells);
2616 for (Int_t i = 0; i < fNcells; i++) ((TH1&)obj).UpdateBinContent(i, RetrieveBinContent(i));
2617
2618 ((TH1&)obj).fEntries = fEntries;
2619
2620 // which will call BufferEmpty(0) and set fBuffer[0] to a Maybe one should call
2621 // assignment operator on the TArrayD
2622
2623 ((TH1&)obj).fTsumw = fTsumw;
2624 ((TH1&)obj).fTsumw2 = fTsumw2;
2625 ((TH1&)obj).fTsumwx = fTsumwx;
2626 ((TH1&)obj).fTsumwx2 = fTsumwx2;
2627 ((TH1&)obj).fMaximum = fMaximum;
2628 ((TH1&)obj).fMinimum = fMinimum;
2629
2630 TAttLine::Copy(((TH1&)obj));
2631 TAttFill::Copy(((TH1&)obj));
2632 TAttMarker::Copy(((TH1&)obj));
2633 fXaxis.Copy(((TH1&)obj).fXaxis);
2634 fYaxis.Copy(((TH1&)obj).fYaxis);
2635 fZaxis.Copy(((TH1&)obj).fZaxis);
2636 ((TH1&)obj).fXaxis.SetParent(&obj);
2637 ((TH1&)obj).fYaxis.SetParent(&obj);
2638 ((TH1&)obj).fZaxis.SetParent(&obj);
2639 fContour.Copy(((TH1&)obj).fContour);
2640 fSumw2.Copy(((TH1&)obj).fSumw2);
2641 // fFunctions->Copy(((TH1&)obj).fFunctions);
2642 // when copying an histogram if the AddDirectoryStatus() is true it
2643 // will be added to gDirectory independently of the fDirectory stored.
2644 // and if the AddDirectoryStatus() is false it will not be added to
2645 // any directory (fDirectory = 0)
2646 if (fgAddDirectory && gDirectory) {
2647 gDirectory->Append(&obj);
2648 ((TH1&)obj).fFunctions->UseRWLock();
2649 ((TH1&)obj).fDirectory = gDirectory;
2650 } else
2651 ((TH1&)obj).fDirectory = 0;
2652
2653}
2654
2655////////////////////////////////////////////////////////////////////////////////
2656/// Make a complete copy of the underlying object. If 'newname' is set,
2657/// the copy's name will be set to that name.
2658
2659TObject* TH1::Clone(const char* newname) const
2660{
2661 TH1* obj = (TH1*)IsA()->GetNew()(0);
2662 Copy(*obj);
2663
2664 // Now handle the parts that Copy doesn't do
2665 if(fFunctions) {
2666 // The Copy above might have published 'obj' to the ListOfCleanups.
2667 // Clone can call RecursiveRemove, for example via TCheckHashRecursiveRemoveConsistency
2668 // when dictionary information is initialized, so we need to
2669 // keep obj->fFunction valid during its execution and
2670 // protect the update with the write lock.
2671 auto newlist = (TList*)fFunctions->Clone();
2672 auto oldlist = obj->fFunctions;
2673 {
2675 obj->fFunctions = newlist;
2676 }
2677 delete oldlist;
2678 }
2679 if(newname && strlen(newname) ) {
2680 obj->SetName(newname);
2681 }
2682 return obj;
2683}
2684
2685////////////////////////////////////////////////////////////////////////////////
2686/// Perform the automatic addition of the histogram to the given directory
2687///
2688/// Note this function is called in place when the semantic requires
2689/// this object to be added to a directory (I.e. when being read from
2690/// a TKey or being Cloned)
2691
2693{
2694 Bool_t addStatus = TH1::AddDirectoryStatus();
2695 if (addStatus) {
2696 SetDirectory(dir);
2697 if (dir) {
2699 }
2700 }
2701}
2702
2703////////////////////////////////////////////////////////////////////////////////
2704/// Compute distance from point px,py to a line.
2705///
2706/// Compute the closest distance of approach from point px,py to elements
2707/// of an histogram.
2708/// The distance is computed in pixels units.
2709///
2710/// #### Algorithm:
2711/// Currently, this simple model computes the distance from the mouse
2712/// to the histogram contour only.
2713
2715{
2716 if (!fPainter) return 9999;
2717 return fPainter->DistancetoPrimitive(px,py);
2718}
2719
2720////////////////////////////////////////////////////////////////////////////////
2721/// Performs the operation: `this = this/(c1*f1)`
2722/// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2723///
2724/// Only bins inside the function range are recomputed.
2725/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2726/// you should call Sumw2 before making this operation.
2727/// This is particularly important if you fit the histogram after TH1::Divide
2728///
2729/// The function return kFALSE if the divide operation failed
2730
2732{
2733 if (!f1) {
2734 Error("Divide","Attempt to divide by a non-existing function");
2735 return kFALSE;
2736 }
2737
2738 // delete buffer if it is there since it will become invalid
2739 if (fBuffer) BufferEmpty(1);
2740
2741 Int_t nx = GetNbinsX() + 2; // normal bins + uf / of
2742 Int_t ny = GetNbinsY() + 2;
2743 Int_t nz = GetNbinsZ() + 2;
2744 if (fDimension < 2) ny = 1;
2745 if (fDimension < 3) nz = 1;
2746
2747
2748 SetMinimum();
2749 SetMaximum();
2750
2751 // - Loop on bins (including underflows/overflows)
2752 Int_t bin, binx, biny, binz;
2753 Double_t cu, w;
2754 Double_t xx[3];
2755 Double_t *params = 0;
2756 f1->InitArgs(xx,params);
2757 for (binz = 0; binz < nz; ++binz) {
2758 xx[2] = fZaxis.GetBinCenter(binz);
2759 for (biny = 0; biny < ny; ++biny) {
2760 xx[1] = fYaxis.GetBinCenter(biny);
2761 for (binx = 0; binx < nx; ++binx) {
2762 xx[0] = fXaxis.GetBinCenter(binx);
2763 if (!f1->IsInside(xx)) continue;
2765 bin = binx + nx * (biny + ny * binz);
2766 cu = c1 * f1->EvalPar(xx);
2767 if (TF1::RejectedPoint()) continue;
2768 if (cu) w = RetrieveBinContent(bin) / cu;
2769 else w = 0;
2770 UpdateBinContent(bin, w);
2771 if (fSumw2.fN) {
2772 if (cu != 0) fSumw2.fArray[bin] = GetBinErrorSqUnchecked(bin) / (cu * cu);
2773 else fSumw2.fArray[bin] = 0;
2774 }
2775 }
2776 }
2777 }
2778 ResetStats();
2779 return kTRUE;
2780}
2781
2782////////////////////////////////////////////////////////////////////////////////
2783/// Divide this histogram by h1.
2784///
2785/// `this = this/h1`
2786/// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2787/// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
2788/// if not already set.
2789/// The resulting errors are calculated assuming uncorrelated histograms.
2790/// See the other TH1::Divide that gives the possibility to optionally
2791/// compute binomial errors.
2792///
2793/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2794/// you should call Sumw2 before making this operation.
2795/// This is particularly important if you fit the histogram after TH1::Scale
2796///
2797/// The function return kFALSE if the divide operation failed
2798
2799Bool_t TH1::Divide(const TH1 *h1)
2800{
2801 if (!h1) {
2802 Error("Divide", "Input histogram passed does not exist (NULL).");
2803 return kFALSE;
2804 }
2805
2806 // delete buffer if it is there since it will become invalid
2807 if (fBuffer) BufferEmpty(1);
2808
2809 try {
2810 CheckConsistency(this,h1);
2811 } catch(DifferentNumberOfBins&) {
2812 Error("Divide","Cannot divide histograms with different number of bins");
2813 return kFALSE;
2814 } catch(DifferentAxisLimits&) {
2815 Warning("Divide","Dividing histograms with different axis limits");
2816 } catch(DifferentBinLimits&) {
2817 Warning("Divide","Dividing histograms with different bin limits");
2818 } catch(DifferentLabels&) {
2819 Warning("Divide","Dividing histograms with different labels");
2820 }
2821
2822 // Create Sumw2 if h1 has Sumw2 set
2823 if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
2824
2825 // - Loop on bins (including underflows/overflows)
2826 for (Int_t i = 0; i < fNcells; ++i) {
2829 if (c1) UpdateBinContent(i, c0 / c1);
2830 else UpdateBinContent(i, 0);
2831
2832 if(fSumw2.fN) {
2833 if (c1 == 0) { fSumw2.fArray[i] = 0; continue; }
2834 Double_t c1sq = c1 * c1;
2835 fSumw2.fArray[i] = (GetBinErrorSqUnchecked(i) * c1sq + h1->GetBinErrorSqUnchecked(i) * c0 * c0) / (c1sq * c1sq);
2836 }
2837 }
2838 ResetStats();
2839 return kTRUE;
2840}
2841
2842////////////////////////////////////////////////////////////////////////////////
2843/// Replace contents of this histogram by the division of h1 by h2.
2844///
2845/// `this = c1*h1/(c2*h2)`
2846///
2847/// If errors are defined (see TH1::Sumw2), errors are also recalculated
2848/// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
2849/// if not already set.
2850/// The resulting errors are calculated assuming uncorrelated histograms.
2851/// However, if option ="B" is specified, Binomial errors are computed.
2852/// In this case c1 and c2 do not make real sense and they are ignored.
2853///
2854/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2855/// you should call Sumw2 before making this operation.
2856/// This is particularly important if you fit the histogram after TH1::Divide
2857///
2858/// Please note also that in the binomial case errors are calculated using standard
2859/// binomial statistics, which means when b1 = b2, the error is zero.
2860/// If you prefer to have efficiency errors not going to zero when the efficiency is 1, you must
2861/// use the function TGraphAsymmErrors::BayesDivide, which will return an asymmetric and non-zero lower
2862/// error for the case b1=b2.
2863///
2864/// The function return kFALSE if the divide operation failed
2865
2866Bool_t TH1::Divide(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2, Option_t *option)
2867{
2868
2869 TString opt = option;
2870 opt.ToLower();
2871 Bool_t binomial = kFALSE;
2872 if (opt.Contains("b")) binomial = kTRUE;
2873 if (!h1 || !h2) {
2874 Error("Divide", "At least one of the input histograms passed does not exist (NULL).");
2875 return kFALSE;
2876 }
2877
2878 // delete buffer if it is there since it will become invalid
2879 if (fBuffer) BufferEmpty(1);
2880
2881 try {
2882 CheckConsistency(h1,h2);
2883 CheckConsistency(this,h1);
2884 } catch(DifferentNumberOfBins&) {
2885 Error("Divide","Cannot divide histograms with different number of bins");
2886 return kFALSE;
2887 } catch(DifferentAxisLimits&) {
2888 Warning("Divide","Dividing histograms with different axis limits");
2889 } catch(DifferentBinLimits&) {
2890 Warning("Divide","Dividing histograms with different bin limits");
2891 } catch(DifferentLabels&) {
2892 Warning("Divide","Dividing histograms with different labels");
2893 }
2894
2895
2896 if (!c2) {
2897 Error("Divide","Coefficient of dividing histogram cannot be zero");
2898 return kFALSE;
2899 }
2900
2901 // Create Sumw2 if h1 or h2 have Sumw2 set, or if binomial errors are explicitly requested
2902 if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0 || binomial)) Sumw2();
2903
2904 SetMinimum();
2905 SetMaximum();
2906
2907 // - Loop on bins (including underflows/overflows)
2908 for (Int_t i = 0; i < fNcells; ++i) {
2910 Double_t b2 = h2->RetrieveBinContent(i);
2911 if (b2) UpdateBinContent(i, c1 * b1 / (c2 * b2));
2912 else UpdateBinContent(i, 0);
2913
2914 if (fSumw2.fN) {
2915 if (b2 == 0) { fSumw2.fArray[i] = 0; continue; }
2916 Double_t b1sq = b1 * b1; Double_t b2sq = b2 * b2;
2917 Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
2919 Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
2920 if (binomial) {
2921 if (b1 != b2) {
2922 // in the case of binomial statistics c1 and c2 must be 1 otherwise it does not make sense
2923 // c1 and c2 are ignored
2924 //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/(c2*b2));//this is the formula in Hbook/Hoper1
2925 //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/b2); // old formula from G. Flucke
2926 // formula which works also for weighted histogram (see http://root-forum.cern.ch/viewtopic.php?t=3753 )
2927 fSumw2.fArray[i] = TMath::Abs( ( (1. - 2.* b1 / b2) * e1sq + b1sq * e2sq / b2sq ) / b2sq );
2928 } else {
2929 //in case b1=b2 error is zero
2930 //use TGraphAsymmErrors::BayesDivide for getting the asymmetric error not equal to zero
2931 fSumw2.fArray[i] = 0;
2932 }
2933 } else {
2934 fSumw2.fArray[i] = c1sq * c2sq * (e1sq * b2sq + e2sq * b1sq) / (c2sq * c2sq * b2sq * b2sq);
2935 }
2936 }
2937 }
2938 ResetStats();
2939 if (binomial)
2940 // in case of binomial division use denominator for number of entries
2941 SetEntries ( h2->GetEntries() );
2942
2943 return kTRUE;
2944}
2945
2946////////////////////////////////////////////////////////////////////////////////
2947/// Draw this histogram with options.
2948///
2949/// Histograms are drawn via the THistPainter class. Each histogram has
2950/// a pointer to its own painter (to be usable in a multithreaded program).
2951/// The same histogram can be drawn with different options in different pads.
2952/// When an histogram drawn in a pad is deleted, the histogram is
2953/// automatically removed from the pad or pads where it was drawn.
2954/// If an histogram is drawn in a pad, then filled again, the new status
2955/// of the histogram will be automatically shown in the pad next time
2956/// the pad is updated. One does not need to redraw the histogram.
2957/// To draw the current version of an histogram in a pad, one can use
2958/// `h->DrawCopy();`
2959/// This makes a clone of the histogram. Once the clone is drawn, the original
2960/// histogram may be modified or deleted without affecting the aspect of the
2961/// clone.
2962/// By default, TH1::Draw clears the current pad.
2963///
2964/// One can use TH1::SetMaximum and TH1::SetMinimum to force a particular
2965/// value for the maximum or the minimum scale on the plot.
2966///
2967/// TH1::UseCurrentStyle can be used to change all histogram graphics
2968/// attributes to correspond to the current selected style.
2969/// This function must be called for each histogram.
2970/// In case one reads and draws many histograms from a file, one can force
2971/// the histograms to inherit automatically the current graphics style
2972/// by calling before gROOT->ForceStyle();
2973///
2974/// See the THistPainter class for a description of all the drawing options.
2975
2976void TH1::Draw(Option_t *option)
2977{
2978 TString opt1 = option; opt1.ToLower();
2979 TString opt2 = option;
2980 Int_t index = opt1.Index("same");
2981
2982 // Check if the string "same" is part of a TCutg name.
2983 if (index>=0) {
2984 Int_t indb = opt1.Index("[");
2985 if (indb>=0) {
2986 Int_t indk = opt1.Index("]");
2987 if (index>indb && index<indk) index = -1;
2988 }
2989 }
2990
2991 // If there is no pad or an empty pad the "same" option is ignored.
2992 if (gPad) {
2993 if (!gPad->IsEditable()) gROOT->MakeDefCanvas();
2994 if (index>=0) {
2995 if (gPad->GetX1() == 0 && gPad->GetX2() == 1 &&
2996 gPad->GetY1() == 0 && gPad->GetY2() == 1 &&
2997 gPad->GetListOfPrimitives()->GetSize()==0) opt2.Remove(index,4);
2998 } else {
2999 //the following statement is necessary in case one attempts to draw
3000 //a temporary histogram already in the current pad
3001 if (TestBit(kCanDelete)) gPad->GetListOfPrimitives()->Remove(this);
3002 gPad->Clear();
3003 }
3004 gPad->IncrementPaletteColor(1, opt1);
3005 } else {
3006 if (index>=0) opt2.Remove(index,4);
3007 }
3008
3009 AppendPad(opt2.Data());
3010}
3011
3012////////////////////////////////////////////////////////////////////////////////
3013/// Copy this histogram and Draw in the current pad.
3014///
3015/// Once the histogram is drawn into the pad, any further modification
3016/// using graphics input will be made on the copy of the histogram,
3017/// and not to the original object.
3018/// By default a postfix "_copy" is added to the histogram name. Pass an empty postfix in case
3019/// you want to draw an histogram with the same name
3020///
3021/// See Draw for the list of options
3022
3023TH1 *TH1::DrawCopy(Option_t *option, const char * name_postfix) const
3024{
3025 TString opt = option;
3026 opt.ToLower();
3027 if (gPad && !opt.Contains("same")) gPad->Clear();
3028 TString newName = (name_postfix) ? TString::Format("%s%s",GetName(),name_postfix) : "";
3029 TH1 *newth1 = (TH1 *)Clone(newName);
3030 newth1->SetDirectory(0);
3031 newth1->SetBit(kCanDelete);
3032 if (gPad) gPad->IncrementPaletteColor(1, opt);
3033
3034 newth1->AppendPad(option);
3035 return newth1;
3036}
3037
3038////////////////////////////////////////////////////////////////////////////////
3039/// Draw a normalized copy of this histogram.
3040///
3041/// A clone of this histogram is normalized to norm and drawn with option.
3042/// A pointer to the normalized histogram is returned.
3043/// The contents of the histogram copy are scaled such that the new
3044/// sum of weights (excluding under and overflow) is equal to norm.
3045/// Note that the returned normalized histogram is not added to the list
3046/// of histograms in the current directory in memory.
3047/// It is the user's responsibility to delete this histogram.
3048/// The kCanDelete bit is set for the returned object. If a pad containing
3049/// this copy is cleared, the histogram will be automatically deleted.
3050///
3051/// See Draw for the list of options
3052
3053TH1 *TH1::DrawNormalized(Option_t *option, Double_t norm) const
3054{
3056 if (sum == 0) {
3057 Error("DrawNormalized","Sum of weights is null. Cannot normalize histogram: %s",GetName());
3058 return 0;
3059 }
3060 Bool_t addStatus = TH1::AddDirectoryStatus();
3062 TH1 *h = (TH1*)Clone();
3063 h->SetBit(kCanDelete);
3064 // in case of drawing with error options - scale correctly the error
3065 TString opt(option); opt.ToUpper();
3066 if (fSumw2.fN == 0) {
3067 h->Sumw2();
3068 // do not use in this case the "Error option " for drawing which is enabled by default since the normalized histogram has now errors
3069 if (opt.IsNull() || opt == "SAME") opt += "HIST";
3070 }
3071 h->Scale(norm/sum);
3072 if (TMath::Abs(fMaximum+1111) > 1e-3) h->SetMaximum(fMaximum*norm/sum);
3073 if (TMath::Abs(fMinimum+1111) > 1e-3) h->SetMinimum(fMinimum*norm/sum);
3074 h->Draw(opt);
3075 TH1::AddDirectory(addStatus);
3076 return h;
3077}
3078
3079////////////////////////////////////////////////////////////////////////////////
3080/// Display a panel with all histogram drawing options.
3081///
3082/// See class TDrawPanelHist for example
3083
3084void TH1::DrawPanel()
3085{
3086 if (!fPainter) {Draw(); if (gPad) gPad->Update();}
3087 if (fPainter) fPainter->DrawPanel();
3088}
3089
3090////////////////////////////////////////////////////////////////////////////////
3091/// Evaluate function f1 at the center of bins of this histogram.
3092///
3093/// - If option "R" is specified, the function is evaluated only
3094/// for the bins included in the function range.
3095/// - If option "A" is specified, the value of the function is added to the
3096/// existing bin contents
3097/// - If option "S" is specified, the value of the function is used to
3098/// generate a value, distributed according to the Poisson
3099/// distribution, with f1 as the mean.
3100
3101void TH1::Eval(TF1 *f1, Option_t *option)
3102{
3103 Double_t x[3];
3104 Int_t range, stat, add;
3105 if (!f1) return;
3106
3107 TString opt = option;
3108 opt.ToLower();
3109 if (opt.Contains("a")) add = 1;
3110 else add = 0;
3111 if (opt.Contains("s")) stat = 1;
3112 else stat = 0;
3113 if (opt.Contains("r")) range = 1;
3114 else range = 0;
3115
3116 // delete buffer if it is there since it will become invalid
3117 if (fBuffer) BufferEmpty(1);
3118
3119 Int_t nbinsx = fXaxis.GetNbins();
3120 Int_t nbinsy = fYaxis.GetNbins();
3121 Int_t nbinsz = fZaxis.GetNbins();
3122 if (!add) Reset();
3123
3124 for (Int_t binz = 1; binz <= nbinsz; ++binz) {
3125 x[2] = fZaxis.GetBinCenter(binz);
3126 for (Int_t biny = 1; biny <= nbinsy; ++biny) {
3127 x[1] = fYaxis.GetBinCenter(biny);
3128 for (Int_t binx = 1; binx <= nbinsx; ++binx) {
3129 Int_t bin = GetBin(binx,biny,binz);
3130 x[0] = fXaxis.GetBinCenter(binx);
3131 if (range && !f1->IsInside(x)) continue;
3132 Double_t fu = f1->Eval(x[0], x[1], x[2]);
3133 if (stat) fu = gRandom->PoissonD(fu);
3134 AddBinContent(bin, fu);
3135 if (fSumw2.fN) fSumw2.fArray[bin] += TMath::Abs(fu);
3136 }
3137 }
3138 }
3139}
3140
3141////////////////////////////////////////////////////////////////////////////////
3142/// Execute action corresponding to one event.
3143///
3144/// This member function is called when a histogram is clicked with the locator
3145///
3146/// If Left button clicked on the bin top value, then the content of this bin
3147/// is modified according to the new position of the mouse when it is released.
3148
3149void TH1::ExecuteEvent(Int_t event, Int_t px, Int_t py)
3150{
3151 if (fPainter) fPainter->ExecuteEvent(event, px, py);
3152}
3153
3154////////////////////////////////////////////////////////////////////////////////
3155/// This function allows to do discrete Fourier transforms of TH1 and TH2.
3156/// Available transform types and flags are described below.
3157///
3158/// To extract more information about the transform, use the function
3159/// TVirtualFFT::GetCurrentTransform() to get a pointer to the current
3160/// transform object.
3161///
3162/// \param[out] h_output histogram for the output. If a null pointer is passed, a new histogram is created
3163/// and returned, otherwise, the provided histogram is used and should be big enough
3164/// \param[in] option option parameters consists of 3 parts:
3165/// - option on what to return
3166/// - "RE" - returns a histogram of the real part of the output
3167/// - "IM" - returns a histogram of the imaginary part of the output
3168/// - "MAG"- returns a histogram of the magnitude of the output
3169/// - "PH" - returns a histogram of the phase of the output
3170/// - option of transform type
3171/// - "R2C" - real to complex transforms - default
3172/// - "R2HC" - real to halfcomplex (special format of storing output data,
3173/// results the same as for R2C)
3174/// - "DHT" - discrete Hartley transform
3175/// real to real transforms (sine and cosine):
3176/// - "R2R_0", "R2R_1", "R2R_2", "R2R_3" - discrete cosine transforms of types I-IV
3177/// - "R2R_4", "R2R_5", "R2R_6", "R2R_7" - discrete sine transforms of types I-IV
3178/// To specify the type of each dimension of a 2-dimensional real to real
3179/// transform, use options of form "R2R_XX", for example, "R2R_02" for a transform,
3180/// which is of type "R2R_0" in 1st dimension and "R2R_2" in the 2nd.
3181/// - option of transform flag
3182/// - "ES" (from "estimate") - no time in preparing the transform, but probably sub-optimal
3183/// performance
3184/// - "M" (from "measure") - some time spend in finding the optimal way to do the transform
3185/// - "P" (from "patient") - more time spend in finding the optimal way to do the transform
3186/// - "EX" (from "exhaustive") - the most optimal way is found
3187/// This option should be chosen depending on how many transforms of the same size and
3188/// type are going to be done. Planning is only done once, for the first transform of this
3189/// size and type. Default is "ES".
3190///
3191/// Examples of valid options: "Mag R2C M" "Re R2R_11" "Im R2C ES" "PH R2HC EX"
3192
3193TH1* TH1::FFT(TH1* h_output, Option_t *option)
3194{
3195
3196 Int_t ndim[3];
3197 ndim[0] = this->GetNbinsX();
3198 ndim[1] = this->GetNbinsY();
3199 ndim[2] = this->GetNbinsZ();
3200
3201 TVirtualFFT *fft;
3202 TString opt = option;
3203 opt.ToUpper();
3204 if (!opt.Contains("2R")){
3205 if (!opt.Contains("2C") && !opt.Contains("2HC") && !opt.Contains("DHT")) {
3206 //no type specified, "R2C" by default
3207 opt.Append("R2C");
3208 }
3209 fft = TVirtualFFT::FFT(this->GetDimension(), ndim, opt.Data());
3210 }
3211 else {
3212 //find the kind of transform
3213 Int_t ind = opt.Index("R2R", 3);
3214 Int_t *kind = new Int_t[2];
3215 char t;
3216 t = opt[ind+4];
3217 kind[0] = atoi(&t);
3218 if (h_output->GetDimension()>1) {
3219 t = opt[ind+5];
3220 kind[1] = atoi(&t);
3221 }
3222 fft = TVirtualFFT::SineCosine(this->GetDimension(), ndim, kind, option);
3223 delete [] kind;
3224 }
3225
3226 if (!fft) return 0;
3227 Int_t in=0;
3228 for (Int_t binx = 1; binx<=ndim[0]; binx++) {
3229 for (Int_t biny=1; biny<=ndim[1]; biny++) {
3230 for (Int_t binz=1; binz<=ndim[2]; binz++) {
3231 fft->SetPoint(in, this->GetBinContent(binx, biny, binz));
3232 in++;
3233 }
3234 }
3235 }
3236 fft->Transform();
3237 h_output = TransformHisto(fft, h_output, option);
3238 return h_output;
3239}
3240
3241////////////////////////////////////////////////////////////////////////////////
3242/// Increment bin with abscissa X by 1.
3243///
3244/// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3245/// if x is equal to or greater than the upper edge of last bin, the Overflow bin is incremented
3246///
3247/// If the storage of the sum of squares of weights has been triggered,
3248/// via the function Sumw2, then the sum of the squares of weights is incremented
3249/// by 1 in the bin corresponding to x.
3250///
3251/// The function returns the corresponding bin number which has its content incremented by 1
3252
3254{
3255 if (fBuffer) return BufferFill(x,1);
3256
3257 Int_t bin;
3258 fEntries++;
3259 bin =fXaxis.FindBin(x);
3260 if (bin <0) return -1;
3261 AddBinContent(bin);
3262 if (fSumw2.fN) ++fSumw2.fArray[bin];
3263 if (bin == 0 || bin > fXaxis.GetNbins()) {
3264 if (!GetStatOverflowsBehaviour()) return -1;
3265 }
3266 ++fTsumw;
3267 ++fTsumw2;
3268 fTsumwx += x;
3269 fTsumwx2 += x*x;
3270 return bin;
3271}
3272
3273////////////////////////////////////////////////////////////////////////////////
3274/// Increment bin with abscissa X with a weight w.
3275///
3276/// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3277/// if x is equal to or greater than the upper edge of last bin, the Overflow bin is incremented
3278///
3279/// If the weight is not equal to 1, the storage of the sum of squares of
3280/// weights is automatically triggered and the sum of the squares of weights is incremented
3281/// by \f$ w^2 \f$ in the bin corresponding to x.
3282///
3283/// The function returns the corresponding bin number which has its content incremented by w
3284
3286{
3287
3288 if (fBuffer) return BufferFill(x,w);
3289
3290 Int_t bin;
3291 fEntries++;
3292 bin =fXaxis.FindBin(x);
3293 if (bin <0) return -1;
3294 if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW) ) Sumw2(); // must be called before AddBinContent
3295 if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3296 AddBinContent(bin, w);
3297 if (bin == 0 || bin > fXaxis.GetNbins()) {
3298 if (!GetStatOverflowsBehaviour()) return -1;
3299 }
3300 Double_t z= w;
3301 fTsumw += z;
3302 fTsumw2 += z*z;
3303 fTsumwx += z*x;
3304 fTsumwx2 += z*x*x;
3305 return bin;
3306}
3307
3308////////////////////////////////////////////////////////////////////////////////
3309/// Increment bin with namex with a weight w
3310///
3311/// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3312/// if x is equal to or greater than the upper edge of last bin, the Overflow bin is incremented
3313///
3314/// If the weight is not equal to 1, the storage of the sum of squares of
3315/// weights is automatically triggered and the sum of the squares of weights is incremented
3316/// by \f$ w^2 \f$ in the bin corresponding to x.
3317///
3318/// The function returns the corresponding bin number which has its content
3319/// incremented by w.
3320
3321Int_t TH1::Fill(const char *namex, Double_t w)
3322{
3323 Int_t bin;
3324 fEntries++;
3325 bin =fXaxis.FindBin(namex);
3326 if (bin <0) return -1;
3327 if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3328 if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3329 AddBinContent(bin, w);
3330 if (bin == 0 || bin > fXaxis.GetNbins()) return -1;
3331 Double_t z= w;
3332 fTsumw += z;
3333 fTsumw2 += z*z;
3334 // this make sense if the histogram is not expanding (no axis can be extended)
3335 if (!CanExtendAllAxes()) {
3337 fTsumwx += z*x;
3338 fTsumwx2 += z*x*x;
3339 }
3340 return bin;
3341}
3342
3343////////////////////////////////////////////////////////////////////////////////
3344/// Fill this histogram with an array x and weights w.
3345///
3346/// \param[in] ntimes number of entries in arrays x and w (array size must be ntimes*stride)
3347/// \param[in] x array of values to be histogrammed
3348/// \param[in] w array of weighs
3349/// \param[in] stride step size through arrays x and w
3350///
3351/// If the weight is not equal to 1, the storage of the sum of squares of
3352/// weights is automatically triggered and the sum of the squares of weights is incremented
3353/// by \f$ w^2 \f$ in the bin corresponding to x.
3354/// if w is NULL each entry is assumed a weight=1
3355
3356void TH1::FillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3357{
3358 //If a buffer is activated, fill buffer
3359 if (fBuffer) {
3360 ntimes *= stride;
3361 Int_t i = 0;
3362 for (i=0;i<ntimes;i+=stride) {
3363 if (!fBuffer) break; // buffer can be deleted in BufferFill when is empty
3364 if (w) BufferFill(x[i],w[i]);
3365 else BufferFill(x[i], 1.);
3366 }
3367 // fill the remaining entries if the buffer has been deleted
3368 if (i < ntimes && fBuffer==0) {
3369 auto weights = w ? &w[i] : nullptr;
3370 DoFillN((ntimes-i)/stride,&x[i],weights,stride);
3371 }
3372 return;
3373 }
3374 // call internal method
3375 DoFillN(ntimes, x, w, stride);
3376}
3377
3378////////////////////////////////////////////////////////////////////////////////
3379/// Internal method to fill histogram content from a vector
3380/// called directly by TH1::BufferEmpty
3381
3382void TH1::DoFillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3383{
3384 Int_t bin,i;
3385
3386 fEntries += ntimes;
3387 Double_t ww = 1;
3388 Int_t nbins = fXaxis.GetNbins();
3389 ntimes *= stride;
3390 for (i=0;i<ntimes;i+=stride) {
3391 bin =fXaxis.FindBin(x[i]);
3392 if (bin <0) continue;
3393 if (w) ww = w[i];
3394 if (!fSumw2.fN && ww != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3395 if (fSumw2.fN) fSumw2.fArray[bin] += ww*ww;
3396 AddBinContent(bin, ww);
3397 if (bin == 0 || bin > nbins) {
3398 if (!GetStatOverflowsBehaviour()) continue;
3399 }
3400 Double_t z= ww;
3401 fTsumw += z;
3402 fTsumw2 += z*z;
3403 fTsumwx += z*x[i];
3404 fTsumwx2 += z*x[i]*x[i];
3405 }
3406}
3407
3408////////////////////////////////////////////////////////////////////////////////
3409/// Fill histogram following distribution in function fname.
3410///
3411/// The distribution contained in the function fname (TF1) is integrated
3412/// over the channel contents for the bin range of this histogram.
3413/// It is normalized to 1.
3414///
3415/// Getting one random number implies:
3416/// - Generating a random number between 0 and 1 (say r1)
3417/// - Look in which bin in the normalized integral r1 corresponds to
3418/// - Fill histogram channel
3419/// ntimes random numbers are generated
3420///
3421/// One can also call TF1::GetRandom to get a random variate from a function.
3422
3423void TH1::FillRandom(const char *fname, Int_t ntimes)
3424{
3425 Int_t bin, binx, ibin, loop;
3426 Double_t r1, x;
3427 // - Search for fname in the list of ROOT defined functions
3428 TF1 *f1 = (TF1*)gROOT->GetFunction(fname);
3429 if (!f1) { Error("FillRandom", "Unknown function: %s",fname); return; }
3430
3431 // - Allocate temporary space to store the integral and compute integral
3432
3433 TAxis * xAxis = &fXaxis;
3434
3435 // in case axis of histogram is not defined use the function axis
3436 if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
3438 f1->GetRange(xmin,xmax);
3439 Info("FillRandom","Using function axis and range [%g,%g]",xmin, xmax);
3440 xAxis = f1->GetHistogram()->GetXaxis();
3441 }
3442
3443 Int_t first = xAxis->GetFirst();
3444 Int_t last = xAxis->GetLast();
3445 Int_t nbinsx = last-first+1;
3446
3447 Double_t *integral = new Double_t[nbinsx+1];
3448 integral[0] = 0;
3449 for (binx=1;binx<=nbinsx;binx++) {
3450 Double_t fint = f1->Integral(xAxis->GetBinLowEdge(binx+first-1),xAxis->GetBinUpEdge(binx+first-1), 0.);
3451 integral[binx] = integral[binx-1] + fint;
3452 }
3453
3454 // - Normalize integral to 1
3455 if (integral[nbinsx] == 0 ) {
3456 delete [] integral;
3457 Error("FillRandom", "Integral = zero"); return;
3458 }
3459 for (bin=1;bin<=nbinsx;bin++) integral[bin] /= integral[nbinsx];
3460
3461 // --------------Start main loop ntimes
3462 for (loop=0;loop<ntimes;loop++) {
3463 r1 = gRandom->Rndm();
3464 ibin = TMath::BinarySearch(nbinsx,&integral[0],r1);
3465 //binx = 1 + ibin;
3466 //x = xAxis->GetBinCenter(binx); //this is not OK when SetBuffer is used
3467 x = xAxis->GetBinLowEdge(ibin+first)
3468 +xAxis->GetBinWidth(ibin+first)*(r1-integral[ibin])/(integral[ibin+1] - integral[ibin]);
3469 Fill(x);
3470 }
3471 delete [] integral;
3472}
3473
3474////////////////////////////////////////////////////////////////////////////////
3475/// Fill histogram following distribution in histogram h.
3476///
3477/// The distribution contained in the histogram h (TH1) is integrated
3478/// over the channel contents for the bin range of this histogram.
3479/// It is normalized to 1.
3480///
3481/// Getting one random number implies:
3482/// - Generating a random number between 0 and 1 (say r1)
3483/// - Look in which bin in the normalized integral r1 corresponds to
3484/// - Fill histogram channel ntimes random numbers are generated
3485///
3486/// SPECIAL CASE when the target histogram has the same binning as the source.
3487/// in this case we simply use a poisson distribution where
3488/// the mean value per bin = bincontent/integral.
3489
3490void TH1::FillRandom(TH1 *h, Int_t ntimes)
3491{
3492 if (!h) { Error("FillRandom", "Null histogram"); return; }
3493 if (fDimension != h->GetDimension()) {
3494 Error("FillRandom", "Histograms with different dimensions"); return;
3495 }
3496 if (std::isnan(h->ComputeIntegral(true))) {
3497 Error("FillRandom", "Histograms contains negative bins, does not represent probabilities");
3498 return;
3499 }
3500
3501 //in case the target histogram has the same binning and ntimes much greater
3502 //than the number of bins we can use a fast method
3504 Int_t last = fXaxis.GetLast();
3505 Int_t nbins = last-first+1;
3506 if (ntimes > 10*nbins) {
3507 try {
3508 CheckConsistency(this,h);
3509 Double_t sumw = h->Integral(first,last);
3510 if (sumw == 0) return;
3511 Double_t sumgen = 0;
3512 for (Int_t bin=first;bin<=last;bin++) {
3513 Double_t mean = h->RetrieveBinContent(bin)*ntimes/sumw;
3514 Double_t cont = (Double_t)gRandom->Poisson(mean);
3515 sumgen += cont;
3516 AddBinContent(bin,cont);
3517 if (fSumw2.fN) fSumw2.fArray[bin] += cont;
3518 }
3519
3520 // fix for the fluctuations in the total number n
3521 // since we use Poisson instead of multinomial
3522 // add a correction to have ntimes as generated entries
3523 Int_t i;
3524 if (sumgen < ntimes) {
3525 // add missing entries
3526 for (i = Int_t(sumgen+0.5); i < ntimes; ++i)
3527 {
3528 Double_t x = h->GetRandom();
3529 Fill(x);
3530 }
3531 }
3532 else if (sumgen > ntimes) {
3533 // remove extra entries
3534 i = Int_t(sumgen+0.5);
3535 while( i > ntimes) {
3536 Double_t x = h->GetRandom();
3537 Int_t ibin = fXaxis.FindBin(x);
3539 // skip in case bin is empty
3540 if (y > 0) {
3541 SetBinContent(ibin, y-1.);
3542 i--;
3543 }
3544 }
3545 }
3546
3547 ResetStats();
3548 return;
3549 }
3550 catch(std::exception&) {} // do nothing
3551 }
3552 // case of different axis and not too large ntimes
3553
3554 if (h->ComputeIntegral() ==0) return;
3555 Int_t loop;
3556 Double_t x;
3557 for (loop=0;loop<ntimes;loop++) {
3558 x = h->GetRandom();
3559 Fill(x);
3560 }
3561}
3562
3563////////////////////////////////////////////////////////////////////////////////
3564/// Return Global bin number corresponding to x,y,z
3565///
3566/// 2-D and 3-D histograms are represented with a one dimensional
3567/// structure. This has the advantage that all existing functions, such as
3568/// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3569/// This function tries to extend the axis if the given point belongs to an
3570/// under-/overflow bin AND if CanExtendAllAxes() is true.
3571///
3572/// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3573
3575{
3576 if (GetDimension() < 2) {
3577 return fXaxis.FindBin(x);
3578 }
3579 if (GetDimension() < 3) {
3580 Int_t nx = fXaxis.GetNbins()+2;
3581 Int_t binx = fXaxis.FindBin(x);
3582 Int_t biny = fYaxis.FindBin(y);
3583 return binx + nx*biny;
3584 }
3585 if (GetDimension() < 4) {
3586 Int_t nx = fXaxis.GetNbins()+2;
3587 Int_t ny = fYaxis.GetNbins()+2;
3588 Int_t binx = fXaxis.FindBin(x);
3589 Int_t biny = fYaxis.FindBin(y);
3590 Int_t binz = fZaxis.FindBin(z);
3591 return binx + nx*(biny +ny*binz);
3592 }
3593 return -1;
3594}
3595
3596////////////////////////////////////////////////////////////////////////////////
3597/// Return Global bin number corresponding to x,y,z.
3598///
3599/// 2-D and 3-D histograms are represented with a one dimensional
3600/// structure. This has the advantage that all existing functions, such as
3601/// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3602/// This function DOES NOT try to extend the axis if the given point belongs
3603/// to an under-/overflow bin.
3604///
3605/// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3606
3608{
3609 if (GetDimension() < 2) {
3610 return fXaxis.FindFixBin(x);
3611 }
3612 if (GetDimension() < 3) {
3613 Int_t nx = fXaxis.GetNbins()+2;
3614 Int_t binx = fXaxis.FindFixBin(x);
3615 Int_t biny = fYaxis.FindFixBin(y);
3616 return binx + nx*biny;
3617 }
3618 if (GetDimension() < 4) {
3619 Int_t nx = fXaxis.GetNbins()+2;
3620 Int_t ny = fYaxis.GetNbins()+2;
3621 Int_t binx = fXaxis.FindFixBin(x);
3622 Int_t biny = fYaxis.FindFixBin(y);
3623 Int_t binz = fZaxis.FindFixBin(z);
3624 return binx + nx*(biny +ny*binz);
3625 }
3626 return -1;
3627}
3628
3629////////////////////////////////////////////////////////////////////////////////
3630/// Find first bin with content > threshold for axis (1=x, 2=y, 3=z)
3631/// if no bins with content > threshold is found the function returns -1.
3632
3633Int_t TH1::FindFirstBinAbove(Double_t threshold, Int_t axis) const
3634{
3635 if (fBuffer) ((TH1*)this)->BufferEmpty();
3636
3637 if (axis != 1) {
3638 Warning("FindFirstBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3639 axis = 1;
3640 }
3641 Int_t nbins = fXaxis.GetNbins();
3642 for (Int_t bin=1;bin<=nbins;bin++) {
3643 if (RetrieveBinContent(bin) > threshold) return bin;
3644 }
3645 return -1;
3646}
3647
3648////////////////////////////////////////////////////////////////////////////////
3649/// Find last bin with content > threshold for axis (1=x, 2=y, 3=z)
3650/// if no bins with content > threshold is found the function returns -1.
3651
3652Int_t TH1::FindLastBinAbove(Double_t threshold, Int_t axis) const
3653{
3654 if (fBuffer) ((TH1*)this)->BufferEmpty();
3655
3656 if (axis != 1) {
3657 Warning("FindLastBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3658 axis = 1;
3659 }
3660 Int_t nbins = fXaxis.GetNbins();
3661 for (Int_t bin=nbins;bin>=1;bin--) {
3662 if (RetrieveBinContent(bin) > threshold) return bin;
3663 }
3664 return -1;
3665}
3666
3667////////////////////////////////////////////////////////////////////////////////
3668/// Search object named name in the list of functions.
3669
3670TObject *TH1::FindObject(const char *name) const
3671{
3672 if (fFunctions) return fFunctions->FindObject(name);
3673 return 0;
3674}
3675
3676////////////////////////////////////////////////////////////////////////////////
3677/// Search object obj in the list of functions.
3678
3679TObject *TH1::FindObject(const TObject *obj) const
3680{
3681 if (fFunctions) return fFunctions->FindObject(obj);
3682 return 0;
3683}
3684
3685////////////////////////////////////////////////////////////////////////////////
3686/// Fit histogram with function fname.
3687///
3688/// fname is the name of an already predefined function created by TF1 or TF2
3689/// Predefined functions such as gaus, expo and poln are automatically
3690/// created by ROOT.
3691/// fname can also be a formula, accepted by the linear fitter (linear parts divided
3692/// by "++" sign), for example "x++sin(x)" for fitting "[0]*x+[1]*sin(x)"
3693///
3694/// This function finds a pointer to the TF1 object with name fname
3695/// and calls TH1::Fit(TF1 *f1,...)
3696
3697TFitResultPtr TH1::Fit(const char *fname ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
3698{
3699 char *linear;
3700 linear= (char*)strstr(fname, "++");
3701 TF1 *f1=0;
3702 TF2 *f2=0;
3703 TF3 *f3=0;
3704 Int_t ndim=GetDimension();
3705 if (linear){
3706 if (ndim<2){
3707 f1=new TF1(fname, fname, xxmin, xxmax);
3708 return Fit(f1,option,goption,xxmin,xxmax);
3709 }
3710 else if (ndim<3){
3711 f2=new TF2(fname, fname);
3712 return Fit(f2,option,goption,xxmin,xxmax);
3713 }
3714 else{
3715 f3=new TF3(fname, fname);
3716 return Fit(f3,option,goption,xxmin,xxmax);
3717 }
3718 }
3719
3720 else{
3721 f1 = (TF1*)gROOT->GetFunction(fname);
3722 if (!f1) { Printf("Unknown function: %s",fname); return -1; }
3723 return Fit(f1,option,goption,xxmin,xxmax);
3724 }
3725}
3726
3727////////////////////////////////////////////////////////////////////////////////
3728/// Fit histogram with function f1.
3729///
3730/// \param[in] option fit options is given in parameter option.
3731/// - "W" Set all weights to 1 for non empty bins; ignore error bars
3732/// - "WW" Set all weights to 1 including empty bins; ignore error bars
3733/// - "I" Use integral of function in bin, normalized by the bin volume,
3734/// instead of value at bin center
3735/// - "L" Use Loglikelihood method (default is chisquare method)
3736/// - "WL" Use Loglikelihood method and bin contents are not integer,
3737/// i.e. histogram is weighted (must have Sumw2() set)
3738/// - "P" Use Pearson chi2 (using expected errors instead of observed errors)
3739/// - "U" Use a User specified fitting algorithm (via SetFCN)
3740/// - "Q" Quiet mode (minimum printing)
3741/// - "V" Verbose mode (default is between Q and V)
3742/// - "E" Perform better Errors estimation using Minos technique
3743/// - "B" User defined parameter settings are used for predefined functions
3744/// like "gaus", "expo", "poln", "landau".
3745/// Use this option when you want to fix one or more parameters for these functions.
3746/// - "M" More. Improve fit results.
3747/// It uses the IMPROVE command of TMinuit (see TMinuit::mnimpr).
3748/// This algorithm attempts to improve the found local minimum by searching for a
3749/// better one.
3750/// - "R" Use the Range specified in the function range
3751/// - "N" Do not store the graphics function, do not draw
3752/// - "0" Do not plot the result of the fit. By default the fitted function
3753/// is drawn unless the option"N" above is specified.
3754/// - "+" Add this new fitted function to the list of fitted functions
3755/// (by default, any previous function is deleted)
3756/// - "C" In case of linear fitting, don't calculate the chisquare
3757/// (saves time)
3758/// - "F" If fitting a polN, switch to minuit fitter
3759/// - "S" The result of the fit is returned in the TFitResultPtr
3760/// (see below Access to the Fit Result)
3761/// \param[in] goption specify a list of graphics options. See TH1::Draw for a complete list of these options.
3762/// \param[in] xxmin range
3763/// \param[in] xxmax range
3764///
3765/// In order to use the Range option, one must first create a function
3766/// with the expression to be fitted. For example, if your histogram
3767/// has a defined range between -4 and 4 and you want to fit a gaussian
3768/// only in the interval 1 to 3, you can do:
3769///
3770/// ~~~ {.cpp}
3771/// TF1 *f1 = new TF1("f1", "gaus", 1, 3);
3772/// histo->Fit("f1", "R");
3773/// ~~~
3774///
3775/// ## Setting initial conditions
3776/// Parameters must be initialized before invoking the Fit function.
3777/// The setting of the parameter initial values is automatic for the
3778/// predefined functions : poln, expo, gaus, landau. One can however disable
3779/// this automatic computation by specifying the option "B".
3780/// Note that if a predefined function is defined with an argument,
3781/// eg, gaus(0), expo(1), you must specify the initial values for
3782/// the parameters.
3783/// You can specify boundary limits for some or all parameters via
3784///
3785/// ~~~ {.cpp}
3786/// f1->SetParLimits(p_number, parmin, parmax);
3787/// ~~~
3788///
3789/// if parmin>=parmax, the parameter is fixed
3790/// Note that you are not forced to fix the limits for all parameters.
3791/// For example, if you fit a function with 6 parameters, you can do:
3792///
3793/// ~~~ {.cpp}
3794/// func->SetParameters(0, 3.1, 1.e-6, -8, 0, 100);
3795/// func->SetParLimits(3, -10, -4);
3796/// func->FixParameter(4, 0);
3797/// func->SetParLimits(5, 1, 1);
3798/// ~~~
3799///
3800/// With this setup, parameters 0->2 can vary freely
3801/// Parameter 3 has boundaries [-10,-4] with initial value -8
3802/// Parameter 4 is fixed to 0
3803/// Parameter 5 is fixed to 100.
3804/// When the lower limit and upper limit are equal, the parameter is fixed.
3805/// However to fix a parameter to 0, one must call the FixParameter function.
3806///
3807/// Note that option "I" gives better results but is slower.
3808///
3809/// #### Changing the fitting objective function
3810///
3811/// By default a chi square function is used for fitting. When option "L" (or "LL") is used
3812/// a Poisson likelihood function (see note below) is used.
3813/// The functions are defined in the header Fit/Chi2Func.h or Fit/PoissonLikelihoodFCN and they
3814/// are implemented using the routines FitUtil::EvaluateChi2 or FitUtil::EvaluatePoissonLogL in
3815/// the file math/mathcore/src/FitUtil.cxx.
3816/// To specify a User defined fitting function, specify option "U" and
3817/// call the following functions:
3818///
3819/// ~~~ {.cpp}
3820/// TVirtualFitter::Fitter(myhist)->SetFCN(MyFittingFunction)
3821/// ~~~
3822///
3823/// where MyFittingFunction is of type:
3824///
3825/// ~~~ {.cpp}
3826/// extern void MyFittingFunction(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag);
3827/// ~~~
3828///
3829/// #### Chi2 Fits
3830///
3831/// By default a chi2 (least-square) fit is performed on the histogram. The so-called modified least-square method
3832/// is used where the residual for each bin is computed using as error the observed value (the bin error)
3833///
3834/// \f[
3835/// Chi2 = \sum{ \left(y(i) - \frac{f(x(i) | p )}{e(i)} \right)^2 }
3836/// \f]
3837///
3838/// 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
3839/// an un-weighted histogram. Bins with zero errors are excluded from the fit. See also later the note on the treatment of empty bins.
3840/// When using option "I" the residual is computed not using the function value at the bin center, f (x(i) | p), but the integral
3841/// of the function in the bin, Integral{ f(x|p)dx } divided by the bin volume
3842///
3843/// #### Likelihood Fits
3844///
3845/// When using option "L" a likelihood fit is used instead of the default chi2 square fit.
3846/// The likelihood is built assuming a Poisson probability density function for each bin.
3847/// The negative log-likelihood to be minimized is
3848///
3849/// \f[
3850/// NLL = \sum{ log Poisson ( y(i) | f(x(i) | p ) ) }
3851/// \f]
3852///
3853/// The exact likelihood used is the Poisson likelihood described in this paper:
3854/// S. Baker and R. D. Cousins, “Clarification of the use of chi-square and likelihood functions in fits to histograms,”
3855/// Nucl. Instrum. Meth. 221 (1984) 437.
3856///
3857/// This method can then be used only when the bin content represents counts (i.e. errors are sqrt(N) ).
3858/// The likelihood method has the advantage of treating correctly bins with low statistics. In case of high
3859/// statistics/bin the distribution of the bin content becomes a normal distribution and the likelihood and chi2 fit
3860/// give the same result.
3861///
3862/// The likelihood method, although a bit slower, it is therefore the recommended method in case of low
3863/// bin statistics, where the chi2 method may give incorrect results, in particular when there are
3864/// several empty bins (see also below).
3865/// In case of a weighted histogram, it is possible to perform a likelihood fit by using the
3866/// option "WL". Note a weighted histogram is an histogram which has been filled with weights and it
3867/// contains the sum of the weight square ( TH1::Sumw2() has been called). The bin error for a weighted
3868/// histogram is the square root of the sum of the weight square.
3869///
3870/// #### Treatment of Empty Bins
3871///
3872/// Empty bins, which have the content equal to zero AND error equal to zero,
3873/// are excluded by default from the chisquare fit, but they are considered in the likelihood fit.
3874/// since they affect the likelihood if the function value in these bins is not negligible.
3875/// When using option "WW" these bins will be considered in the chi2 fit with an error of 1.
3876/// Note that if the histogram is having bins with zero content and non zero-errors they are considered as
3877/// any other bins in the fit. Instead bins with zero error and non-zero content are excluded in the chi2 fit.
3878/// A likelihood fit should also not be performed on such an histogram, since we are assuming a wrong pdf for each bin.
3879/// In general, one should not fit an histogram with non-empty bins and zero errors, apart if all the bins have zero errors.
3880/// In this case one could use the option "w", which gives a weight=1 for each bin (unweighted least-square fit).
3881///
3882/// #### Fitting a histogram of dimension N with a function of dimension N-1
3883///
3884/// It is possible to fit a TH2 with a TF1 or a TH3 with a TF2.
3885/// In this case the option "Integral" is not allowed and each cell has
3886/// equal weight.
3887///
3888/// #### Associated functions
3889///
3890/// One or more object (typically a TF1*) can be added to the list
3891/// of functions (fFunctions) associated to each histogram.
3892/// When TH1::Fit is invoked, the fitted function is added to this list.
3893/// Given an histogram h, one can retrieve an associated function
3894/// with:
3895///
3896/// ~~~ {.cpp}
3897/// TF1 *myfunc = h->GetFunction("myfunc");
3898/// ~~~
3899///
3900/// #### Access to the fit result
3901///
3902/// The function returns a TFitResultPtr which can hold a pointer to a TFitResult object.
3903/// By default the TFitResultPtr contains only the status of the fit which is return by an
3904/// automatic conversion of the TFitResultPtr to an integer. One can write in this case directly:
3905///
3906/// ~~~ {.cpp}
3907/// Int_t fitStatus = h->Fit(myFunc)
3908/// ~~~
3909///
3910/// If the option "S" is instead used, TFitResultPtr contains the TFitResult and behaves as a smart
3911/// pointer to it. For example one can do:
3912///
3913/// ~~~ {.cpp}
3914/// TFitResultPtr r = h->Fit(myFunc,"S");
3915/// TMatrixDSym cov = r->GetCovarianceMatrix(); // to access the covariance matrix
3916/// Double_t chi2 = r->Chi2(); // to retrieve the fit chi2
3917/// Double_t par0 = r->Parameter(0); // retrieve the value for the parameter 0
3918/// Double_t err0 = r->ParError(0); // retrieve the error for the parameter 0
3919/// r->Print("V"); // print full information of fit including covariance matrix
3920/// r->Write(); // store the result in a file
3921/// ~~~
3922///
3923/// The fit parameters, error and chi2 (but not covariance matrix) can be retrieved also
3924/// from the fitted function.
3925/// If the histogram is made persistent, the list of
3926/// associated functions is also persistent. Given a pointer (see above)
3927/// to an associated function myfunc, one can retrieve the function/fit
3928/// parameters with calls such as:
3929///
3930/// ~~~ {.cpp}
3931/// Double_t chi2 = myfunc->GetChisquare();
3932/// Double_t par0 = myfunc->GetParameter(0); //value of 1st parameter
3933/// Double_t err0 = myfunc->GetParError(0); //error on first parameter
3934/// ~~~
3935///
3936/// #### Access to the fit status
3937///
3938/// The status of the fit can be obtained converting the TFitResultPtr to an integer
3939/// independently if the fit option "S" is used or not:
3940///
3941/// ~~~ {.cpp}
3942/// TFitResultPtr r = h->Fit(myFunc,opt);
3943/// Int_t fitStatus = r;
3944/// ~~~
3945///
3946/// The fitStatus is 0 if the fit is OK (i.e no error occurred).
3947/// The value of the fit status code is negative in case of an error not connected with the
3948/// minimization procedure, for example when a wrong function is used.
3949/// Otherwise the return value is the one returned from the minimization procedure.
3950/// When TMinuit (default case) or Minuit2 are used as minimizer the status returned is :
3951/// `fitStatus = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult`.
3952/// TMinuit will return 0 (for migrad, minos, hesse or improve) in case of success and 4 in
3953/// case of error (see the documentation of TMinuit::mnexcm). So for example, for an error
3954/// only in Minos but not in Migrad a fitStatus of 40 will be returned.
3955/// Minuit2 will return also 0 in case of success and different values in migrad minos or
3956/// hesse depending on the error. See in this case the documentation of
3957/// Minuit2Minimizer::Minimize for the migradResult, Minuit2Minimizer::GetMinosError for the
3958/// minosResult and Minuit2Minimizer::Hesse for the hesseResult.
3959/// If other minimizers are used see their specific documentation for the status code returned.
3960/// For example in the case of Fumili, for the status returned see TFumili::Minimize.
3961///
3962/// #### Excluding points
3963///
3964/// Use TF1::RejectPoint inside your fitting function to exclude points
3965/// within a certain range from the fit. Example:
3966///
3967/// ~~~ {.cpp}
3968/// Double_t fline(Double_t *x, Double_t *par)
3969/// {
3970/// if (x[0] > 2.5 && x[0] < 3.5) {
3971/// TF1::RejectPoint();
3972/// return 0;
3973/// }
3974/// return par[0] + par[1]*x[0];
3975/// }
3976///
3977/// void exclude() {
3978/// TF1 *f1 = new TF1("f1", "[0] +[1]*x +gaus(2)", 0, 5);
3979/// f1->SetParameters(6, -1,5, 3, 0.2);
3980/// TH1F *h = new TH1F("h", "background + signal", 100, 0, 5);
3981/// h->FillRandom("f1", 2000);
3982/// TF1 *fline = new TF1("fline", fline, 0, 5, 2);
3983/// fline->SetParameters(2, -1);
3984/// h->Fit("fline", "l");
3985/// }
3986/// ~~~
3987///
3988/// #### Warning when using the option "0"
3989///
3990/// When selecting the option "0", the fitted function is added to
3991/// the list of functions of the histogram, but it is not drawn.
3992/// You can undo what you disabled in the following way:
3993///
3994/// ~~~ {.cpp}
3995/// h.Fit("myFunction", "0"); // fit, store function but do not draw
3996/// h.Draw(); function is not drawn
3997/// const Int_t kNotDraw = 1<<9;
3998/// h.GetFunction("myFunction")->ResetBit(kNotDraw);
3999/// h.Draw(); // function is visible again
4000/// ~~~
4001///
4002/// #### Access to the Minimizer information during fitting
4003///
4004/// This function calls, the ROOT::Fit::FitObject function implemented in HFitImpl.cxx
4005/// which uses the ROOT::Fit::Fitter class. The Fitter class creates the objective function
4006/// (e.g. chi2 or likelihood) and uses an implementation of the Minimizer interface for minimizing
4007/// the function.
4008/// The default minimizer is Minuit (class TMinuitMinimizer which calls TMinuit).
4009/// The default can be set in the resource file in etc/system.rootrc. For example
4010///
4011/// ~~~ {.cpp}
4012/// Root.Fitter: Minuit2
4013/// ~~~
4014///
4015/// A different fitter can also be set via ROOT::Math::MinimizerOptions::SetDefaultMinimizer
4016/// (or TVirtualFitter::SetDefaultFitter).
4017/// For example ROOT::Math::MinimizerOptions::SetDefaultMinimizer("GSLMultiMin","BFGS");
4018/// will set the usage of the BFGS algorithm of the GSL multi-dimensional minimization
4019/// (implemented in libMathMore). ROOT::Math::MinimizerOptions can be used also to set other
4020/// default options, like maximum number of function calls, minimization tolerance or print
4021/// level. See the documentation of this class.
4022///
4023/// For fitting linear functions (containing the "++" sign" and polN functions,
4024/// the linear fitter is automatically initialized.
4025
4026TFitResultPtr TH1::Fit(TF1 *f1 ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
4027{
4028 // implementation of Fit method is in file hist/src/HFitImpl.cxx
4029 Foption_t fitOption;
4031
4032 // create range and minimizer options with default values
4033 ROOT::Fit::DataRange range(xxmin,xxmax);
4035
4036 // need to empty the buffer before
4037 // (t.b.d. do a ML unbinned fit with buffer data)
4038 if (fBuffer) BufferEmpty();
4039
4040 return ROOT::Fit::FitObject(this, f1 , fitOption , minOption, goption, range);
4041}
4042
4043////////////////////////////////////////////////////////////////////////////////
4044/// Display a panel with all histogram fit options.
4045///
4046/// See class TFitPanel for example
4047
4048void TH1::FitPanel()
4049{
4050 if (!gPad)
4051 gROOT->MakeDefCanvas();
4052
4053 if (!gPad) {
4054 Error("FitPanel", "Unable to create a default canvas");
4055 return;
4056 }
4057
4058
4059 // use plugin manager to create instance of TFitEditor
4060 TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TFitEditor");
4061 if (handler && handler->LoadPlugin() != -1) {
4062 if (handler->ExecPlugin(2, gPad, this) == 0)
4063 Error("FitPanel", "Unable to create the FitPanel");
4064 }
4065 else
4066 Error("FitPanel", "Unable to find the FitPanel plug-in");
4067}
4068
4069////////////////////////////////////////////////////////////////////////////////
4070/// Return an histogram containing the asymmetry of this histogram with h2,
4071/// where the asymmetry is defined as:
4072///
4073/// ~~~ {.cpp}
4074/// Asymmetry = (h1 - h2)/(h1 + h2) where h1 = this
4075/// ~~~
4076///
4077/// works for 1D, 2D, etc. histograms
4078/// c2 is an optional argument that gives a relative weight between the two
4079/// histograms, and dc2 is the error on this weight. This is useful, for example,
4080/// when forming an asymmetry between two histograms from 2 different data sets that
4081/// need to be normalized to each other in some way. The function calculates
4082/// the errors assuming Poisson statistics on h1 and h2 (that is, dh = sqrt(h)).
4083///
4084/// example: assuming 'h1' and 'h2' are already filled
4085///
4086/// ~~~ {.cpp}
4087/// h3 = h1->GetAsymmetry(h2)
4088/// ~~~
4089///
4090/// then 'h3' is created and filled with the asymmetry between 'h1' and 'h2';
4091/// h1 and h2 are left intact.
4092///
4093/// Note that it is the user's responsibility to manage the created histogram.
4094/// The name of the returned histogram will be `Asymmetry_nameOfh1-nameOfh2`
4095///
4096/// code proposed by Jason Seely (seely@mit.edu) and adapted by R.Brun
4097///
4098/// clone the histograms so top and bottom will have the
4099/// correct dimensions:
4100/// Sumw2 just makes sure the errors will be computed properly
4101/// when we form sums and ratios below.
4102
4104{
4105 TH1 *h1 = this;
4106 TString name = TString::Format("Asymmetry_%s-%s",h1->GetName(),h2->GetName() );
4107 TH1 *asym = (TH1*)Clone(name);
4108
4109 // set also the title
4110 TString title = TString::Format("(%s - %s)/(%s+%s)",h1->GetName(),h2->GetName(),h1->GetName(),h2->GetName() );
4111 asym->SetTitle(title);
4112
4113 asym->Sumw2();
4114 Bool_t addStatus = TH1::AddDirectoryStatus();
4116 TH1 *top = (TH1*)asym->Clone();
4117 TH1 *bottom = (TH1*)asym->Clone();
4118 TH1::AddDirectory(addStatus);
4119
4120 // form the top and bottom of the asymmetry, and then divide:
4121 top->Add(h1,h2,1,-c2);
4122 bottom->Add(h1,h2,1,c2);
4123 asym->Divide(top,bottom);
4124
4125 Int_t xmax = asym->GetNbinsX();
4126 Int_t ymax = asym->GetNbinsY();
4127 Int_t zmax = asym->GetNbinsZ();
4128
4129 if (h1->fBuffer) h1->BufferEmpty(1);
4130 if (h2->fBuffer) h2->BufferEmpty(1);
4131 if (bottom->fBuffer) bottom->BufferEmpty(1);
4132
4133 // now loop over bins to calculate the correct errors
4134 // the reason this error calculation looks complex is because of c2
4135 for(Int_t i=1; i<= xmax; i++){
4136 for(Int_t j=1; j<= ymax; j++){
4137 for(Int_t k=1; k<= zmax; k++){
4138 Int_t bin = GetBin(i, j, k);
4139 // here some bin contents are written into variables to make the error
4140 // calculation a little more legible:
4142 Double_t b = h2->RetrieveBinContent(bin);
4143 Double_t bot = bottom->RetrieveBinContent(bin);
4144
4145 // make sure there are some events, if not, then the errors are set = 0
4146 // automatically.
4147 //if(bot < 1){} was changed to the next line from recommendation of Jason Seely (28 Nov 2005)
4148 if(bot < 1e-6){}
4149 else{
4150 // computation of errors by Christos Leonidopoulos
4151 Double_t dasq = h1->GetBinErrorSqUnchecked(bin);
4152 Double_t dbsq = h2->GetBinErrorSqUnchecked(bin);
4153 Double_t error = 2*TMath::Sqrt(a*a*c2*c2*dbsq + c2*c2*b*b*dasq+a*a*b*b*dc2*dc2)/(bot*bot);
4154 asym->SetBinError(i,j,k,error);
4155 }
4156 }
4157 }
4158 }
4159 delete top;
4160 delete bottom;
4161
4162 return asym;
4163}
4164
4165////////////////////////////////////////////////////////////////////////////////
4166/// Static function
4167/// return the default buffer size for automatic histograms
4168/// the parameter fgBufferSize may be changed via SetDefaultBufferSize
4169
4171{
4172 return fgBufferSize;
4173}
4174
4175////////////////////////////////////////////////////////////////////////////////
4176/// Return kTRUE if TH1::Sumw2 must be called when creating new histograms.
4177/// see TH1::SetDefaultSumw2.
4178
4180{
4181 return fgDefaultSumw2;
4182}
4183
4184////////////////////////////////////////////////////////////////////////////////
4185/// Return the current number of entries.
4186
4188{
4189 if (fBuffer) {
4190 Int_t nentries = (Int_t) fBuffer[0];
4191 if (nentries > 0) return nentries;
4192 }
4193
4194 return fEntries;
4195}
4196
4197////////////////////////////////////////////////////////////////////////////////
4198/// Number of effective entries of the histogram.
4199///
4200/// \f[
4201/// neff = \frac{(\sum Weights )^2}{(\sum Weight^2 )}
4202/// \f]
4203///
4204/// In case of an unweighted histogram this number is equivalent to the
4205/// number of entries of the histogram.
4206/// For a weighted histogram, this number corresponds to the hypothetical number of unweighted entries
4207/// a histogram would need to have the same statistical power as this weighted histogram.
4208/// Note: The underflow/overflow are included if one has set the TH1::StatOverFlows flag
4209/// and if the statistics has been computed at filling time.
4210/// If a range is set in the histogram the number is computed from the given range.
4211
4213{
4214 Stat_t s[kNstat];
4215 this->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
4216 return (s[1] ? s[0]*s[0]/s[1] : TMath::Abs(s[0]) );
4217}
4218
4219////////////////////////////////////////////////////////////////////////////////
4220/// Set highlight (enable/disable) mode for the histogram
4221/// by default highlight mode is disable
4222
4223void TH1::SetHighlight(Bool_t set)
4224{
4225 if (IsHighlight() == set) return;
4226 if (fDimension > 2) {
4227 Info("SetHighlight", "Supported only 1-D or 2-D histograms");
4228 return;
4229 }
4230
4231 if (!fPainter) {
4232 Info("SetHighlight", "Need to draw histogram first");
4233 return;
4234 }
4235 SetBit(kIsHighlight, set);
4237}
4238
4239////////////////////////////////////////////////////////////////////////////////
4240/// Redefines TObject::GetObjectInfo.
4241/// Displays the histogram info (bin number, contents, integral up to bin
4242/// corresponding to cursor position px,py
4243
4244char *TH1::GetObjectInfo(Int_t px, Int_t py) const
4245{
4246 return ((TH1*)this)->GetPainter()->GetObjectInfo(px,py);
4247}
4248
4249////////////////////////////////////////////////////////////////////////////////
4250/// Return pointer to painter.
4251/// If painter does not exist, it is created
4252
4254{
4255 if (!fPainter) {
4256 TString opt = option;
4257 opt.ToLower();
4258 if (opt.Contains("gl") || gStyle->GetCanvasPreferGL()) {
4259 //try to create TGLHistPainter
4260 TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TGLHistPainter");
4261
4262 if (handler && handler->LoadPlugin() != -1)
4263 fPainter = reinterpret_cast<TVirtualHistPainter *>(handler->ExecPlugin(1, this));
4264 }
4265 }
4266
4268
4269 return fPainter;
4270}
4271
4272////////////////////////////////////////////////////////////////////////////////
4273/// Compute Quantiles for this histogram
4274/// Quantile x_q of a probability distribution Function F is defined as
4275///
4276/// ~~~ {.cpp}
4277/// F(x_q) = q with 0 <= q <= 1.
4278/// ~~~
4279///
4280/// For instance the median x_0.5 of a distribution is defined as that value
4281/// of the random variable for which the distribution function equals 0.5:
4282///
4283/// ~~~ {.cpp}
4284/// F(x_0.5) = Probability(x < x_0.5) = 0.5
4285/// ~~~
4286///
4287/// code from Eddy Offermann, Renaissance
4288///
4289/// \param[in] nprobSum maximum size of array q and size of array probSum (if given)
4290/// \param[in] probSum array of positions where quantiles will be computed.
4291/// - if probSum is null, probSum will be computed internally and will
4292/// have a size = number of bins + 1 in h. it will correspond to the
4293/// quantiles calculated at the lowest edge of the histogram (quantile=0) and
4294/// all the upper edges of the bins.
4295/// - if probSum is not null, it is assumed to contain at least nprobSum values.
4296/// \param[out] q array q filled with nq quantiles
4297/// \return value nq (<=nprobSum) with the number of quantiles computed
4298///
4299/// Note that the Integral of the histogram is automatically recomputed
4300/// if the number of entries is different of the number of entries when
4301/// the integral was computed last time. In case you do not use the Fill
4302/// functions to fill your histogram, but SetBinContent, you must call
4303/// TH1::ComputeIntegral before calling this function.
4304///
4305/// Getting quantiles q from two histograms and storing results in a TGraph,
4306/// a so-called QQ-plot
4307///
4308/// ~~~ {.cpp}
4309/// TGraph *gr = new TGraph(nprob);
4310/// h1->GetQuantiles(nprob,gr->GetX());
4311/// h2->GetQuantiles(nprob,gr->GetY());
4312/// gr->Draw("alp");
4313/// ~~~
4314///
4315/// Example:
4316///
4317/// ~~~ {.cpp}
4318/// void quantiles() {
4319/// // demo for quantiles
4320/// const Int_t nq = 20;
4321/// TH1F *h = new TH1F("h","demo quantiles",100,-3,3);
4322/// h->FillRandom("gaus",5000);
4323///
4324/// Double_t xq[nq]; // position where to compute the quantiles in [0,1]
4325/// Double_t yq[nq]; // array to contain the quantiles
4326/// for (Int_t i=0;i<nq;i++) xq[i] = Float_t(i+1)/nq;
4327/// h->GetQuantiles(nq,yq,xq);
4328///
4329/// //show the original histogram in the top pad
4330/// TCanvas *c1 = new TCanvas("c1","demo quantiles",10,10,700,900);
4331/// c1->Divide(1,2);
4332/// c1->cd(1);
4333/// h->Draw();
4334///
4335/// // show the quantiles in the bottom pad
4336/// c1->cd(2);
4337/// gPad->SetGrid();
4338/// TGraph *gr = new TGraph(nq,xq,yq);
4339/// gr->SetMarkerStyle(21);
4340/// gr->Draw("alp");
4341/// }
4342/// ~~~
4343
4344Int_t TH1::GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum)
4345{
4346 if (GetDimension() > 1) {
4347 Error("GetQuantiles","Only available for 1-d histograms");
4348 return 0;
4349 }
4350
4351 const Int_t nbins = GetXaxis()->GetNbins();
4352 if (!fIntegral) ComputeIntegral();
4353 if (fIntegral[nbins+1] != fEntries) ComputeIntegral();
4354
4355 Int_t i, ibin;
4356 Double_t *prob = (Double_t*)probSum;
4357 Int_t nq = nprobSum;
4358 if (probSum == 0) {
4359 nq = nbins+1;
4360 prob = new Double_t[nq];
4361 prob[0] = 0;
4362 for (i=1;i<nq;i++) {
4363 prob[i] = fIntegral[i]/fIntegral[nbins];
4364 }
4365 }
4366
4367 for (i = 0; i < nq; i++) {
4368 ibin = TMath::BinarySearch(nbins,fIntegral,prob[i]);
4369 while (ibin < nbins-1 && fIntegral[ibin+1] == prob[i]) {
4370 if (fIntegral[ibin+2] == prob[i]) ibin++;
4371 else break;
4372 }
4373 q[i] = GetBinLowEdge(ibin+1);
4374 const Double_t dint = fIntegral[ibin+1]-fIntegral[ibin];
4375 if (dint > 0) q[i] += GetBinWidth(ibin+1)*(prob[i]-fIntegral[ibin])/dint;
4376 }
4377
4378 if (!probSum) delete [] prob;
4379 return nq;
4380}
4381
4382////////////////////////////////////////////////////////////////////////////////
4383/// Decode string choptin and fill fitOption structure.
4384
4385Int_t TH1::FitOptionsMake(Option_t *choptin, Foption_t &fitOption)
4386{
4388 return 1;
4389}
4390
4391////////////////////////////////////////////////////////////////////////////////
4392/// Compute Initial values of parameters for a gaussian.
4393
4394void H1InitGaus()
4395{
4396 Double_t allcha, sumx, sumx2, x, val, stddev, mean;
4397 Int_t bin;
4398 const Double_t sqrtpi = 2.506628;
4399
4400 // - Compute mean value and StdDev of the histogram in the given range
4402 TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4403 Int_t hxfirst = hFitter->GetXfirst();
4404 Int_t hxlast = hFitter->GetXlast();
4405 Double_t valmax = curHist->GetBinContent(hxfirst);
4406 Double_t binwidx = curHist->GetBinWidth(hxfirst);
4407 allcha = sumx = sumx2 = 0;
4408 for (bin=hxfirst;bin<=hxlast;bin++) {
4409 x = curHist->GetBinCenter(bin);
4410 val = TMath::Abs(curHist->GetBinContent(bin));
4411 if (val > valmax) valmax = val;
4412 sumx += val*x;
4413 sumx2 += val*x*x;
4414 allcha += val;
4415 }
4416 if (allcha == 0) return;
4417 mean = sumx/allcha;
4418 stddev = sumx2/allcha - mean*mean;
4419 if (stddev > 0) stddev = TMath::Sqrt(stddev);
4420 else stddev = 0;
4421 if (stddev == 0) stddev = binwidx*(hxlast-hxfirst+1)/4;
4422 //if the distribution is really gaussian, the best approximation
4423 //is binwidx*allcha/(sqrtpi*stddev)
4424 //However, in case of non-gaussian tails, this underestimates
4425 //the normalisation constant. In this case the maximum value
4426 //is a better approximation.
4427 //We take the average of both quantities
4428 Double_t constant = 0.5*(valmax+binwidx*allcha/(sqrtpi*stddev));
4429
4430 //In case the mean value is outside the histo limits and
4431 //the StdDev is bigger than the range, we take
4432 // mean = center of bins
4433 // stddev = half range
4434 Double_t xmin = curHist->GetXaxis()->GetXmin();
4435 Double_t xmax = curHist->GetXaxis()->GetXmax();
4436 if ((mean < xmin || mean > xmax) && stddev > (xmax-xmin)) {
4437 mean = 0.5*(xmax+xmin);
4438 stddev = 0.5*(xmax-xmin);
4439 }
4440 TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4441 f1->SetParameter(0,constant);
4442 f1->SetParameter(1,mean);
4443 f1->SetParameter(2,stddev);
4444 f1->SetParLimits(2,0,10*stddev);
4445}
4446
4447////////////////////////////////////////////////////////////////////////////////
4448/// Compute Initial values of parameters for an exponential.
4449
4450void H1InitExpo()
4451{
4452 Double_t constant, slope;
4453 Int_t ifail;
4455 Int_t hxfirst = hFitter->GetXfirst();
4456 Int_t hxlast = hFitter->GetXlast();
4457 Int_t nchanx = hxlast - hxfirst + 1;
4458
4459 H1LeastSquareLinearFit(-nchanx, constant, slope, ifail);
4460
4461 TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4462 f1->SetParameter(0,constant);
4463 f1->SetParameter(1,slope);
4464
4465}
4466
4467////////////////////////////////////////////////////////////////////////////////
4468/// Compute Initial values of parameters for a polynom.
4469
4470void H1InitPolynom()
4471{
4472 Double_t fitpar[25];
4473
4475 TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4476 Int_t hxfirst = hFitter->GetXfirst();
4477 Int_t hxlast = hFitter->GetXlast();
4478 Int_t nchanx = hxlast - hxfirst + 1;
4479 Int_t npar = f1->GetNpar();
4480
4481 if (nchanx <=1 || npar == 1) {
4482 TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4483 fitpar[0] = curHist->GetSumOfWeights()/Double_t(nchanx);
4484 } else {
4485 H1LeastSquareFit( nchanx, npar, fitpar);
4486 }
4487 for (Int_t i=0;i<npar;i++) f1->SetParameter(i, fitpar[i]);
4488}
4489
4490////////////////////////////////////////////////////////////////////////////////
4491/// Least squares lpolynomial fitting without weights.
4492///
4493/// \param[in] n number of points to fit
4494/// \param[in] m number of parameters
4495/// \param[in] a array of parameters
4496///
4497/// based on CERNLIB routine LSQ: Translated to C++ by Rene Brun
4498/// (E.Keil. revised by B.Schorr, 23.10.1981.)
4499
4501{
4502 const Double_t zero = 0.;
4503 const Double_t one = 1.;
4504 const Int_t idim = 20;
4505
4506 Double_t b[400] /* was [20][20] */;
4507 Int_t i, k, l, ifail;
4508 Double_t power;
4509 Double_t da[20], xk, yk;
4510
4511 if (m <= 2) {
4512 H1LeastSquareLinearFit(n, a[0], a[1], ifail);
4513 return;
4514 }
4515 if (m > idim || m > n) return;
4516 b[0] = Double_t(n);
4517 da[0] = zero;
4518 for (l = 2; l <= m; ++l) {
4519 b[l-1] = zero;
4520 b[m + l*20 - 21] = zero;
4521 da[l-1] = zero;
4522 }
4524 TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4525 Int_t hxfirst = hFitter->GetXfirst();
4526 Int_t hxlast = hFitter->GetXlast();
4527 for (k = hxfirst; k <= hxlast; ++k) {
4528 xk = curHist->GetBinCenter(k);
4529 yk = curHist->GetBinContent(k);
4530 power = one;
4531 da[0] += yk;
4532 for (l = 2; l <= m; ++l) {
4533 power *= xk;
4534 b[l-1] += power;
4535 da[l-1] += power*yk;
4536 }
4537 for (l = 2; l <= m; ++l) {
4538 power *= xk;
4539 b[m + l*20 - 21] += power;
4540 }
4541 }
4542 for (i = 3; i <= m; ++i) {
4543 for (k = i; k <= m; ++k) {
4544 b[k - 1 + (i-1)*20 - 21] = b[k + (i-2)*20 - 21];
4545 }
4546 }
4547 H1LeastSquareSeqnd(m, b, idim, ifail, 1, da);
4548
4549 for (i=0; i<m; ++i) a[i] = da[i];
4550
4551}
4552
4553////////////////////////////////////////////////////////////////////////////////
4554/// Least square linear fit without weights.
4555///
4556/// extracted from CERNLIB LLSQ: Translated to C++ by Rene Brun
4557/// (added to LSQ by B. Schorr, 15.02.1982.)
4558
4559void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
4560{
4561 Double_t xbar, ybar, x2bar;
4562 Int_t i, n;
4563 Double_t xybar;
4564 Double_t fn, xk, yk;
4565 Double_t det;
4566
4567 n = TMath::Abs(ndata);
4568 ifail = -2;
4569 xbar = ybar = x2bar = xybar = 0;
4571 TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4572 Int_t hxfirst = hFitter->GetXfirst();
4573 Int_t hxlast = hFitter->GetXlast();
4574 for (i = hxfirst; i <= hxlast; ++i) {
4575 xk = curHist->GetBinCenter(i);
4576 yk = curHist->GetBinContent(i);
4577 if (ndata < 0) {
4578 if (yk <= 0) yk = 1e-9;
4579 yk = TMath::Log(yk);
4580 }
4581 xbar += xk;
4582 ybar += yk;
4583 x2bar += xk*xk;
4584 xybar += xk*yk;
4585 }
4586 fn = Double_t(n);
4587 det = fn*x2bar - xbar*xbar;
4588 ifail = -1;
4589 if (det <= 0) {
4590 a0 = ybar/fn;
4591 a1 = 0;
4592 return;
4593 }
4594 ifail = 0;
4595 a0 = (x2bar*ybar - xbar*xybar) / det;
4596 a1 = (fn*xybar - xbar*ybar) / det;
4597
4598}
4599
4600////////////////////////////////////////////////////////////////////////////////
4601/// Extracted from CERN Program library routine DSEQN.
4602///
4603/// Translated to C++ by Rene Brun
4604
4605void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b)
4606{
4607 Int_t a_dim1, a_offset, b_dim1, b_offset;
4608 Int_t nmjp1, i, j, l;
4609 Int_t im1, jp1, nm1, nmi;
4610 Double_t s1, s21, s22;
4611 const Double_t one = 1.;
4612
4613 /* Parameter adjustments */
4614 b_dim1 = idim;
4615 b_offset = b_dim1 + 1;
4616 b -= b_offset;
4617 a_dim1 = idim;
4618 a_offset = a_dim1 + 1;
4619 a -= a_offset;
4620
4621 if (idim < n) return;
4622
4623 ifail = 0;
4624 for (j = 1; j <= n; ++j) {
4625 if (a[j + j*a_dim1] <= 0) { ifail = -1; return; }
4626 a[j + j*a_dim1] = one / a[j + j*a_dim1];
4627 if (j == n) continue;
4628 jp1 = j + 1;
4629 for (l = jp1; l <= n; ++l) {
4630 a[j + l*a_dim1] = a[j + j*a_dim1] * a[l + j*a_dim1];
4631 s1 = -a[l + (j+1)*a_dim1];
4632 for (i = 1; i <= j; ++i) { s1 = a[l + i*a_dim1] * a[i + (j+1)*a_dim1] + s1; }
4633 a[l + (j+1)*a_dim1] = -s1;
4634 }
4635 }
4636 if (k <= 0) return;
4637
4638 for (l = 1; l <= k; ++l) {
4639 b[l*b_dim1 + 1] = a[a_dim1 + 1]*b[l*b_dim1 + 1];
4640 }
4641 if (n == 1) return;
4642 for (l = 1; l <= k; ++l) {
4643 for (i = 2; i <= n; ++i) {
4644 im1 = i - 1;
4645 s21 = -b[i + l*b_dim1];
4646 for (j = 1; j <= im1; ++j) {
4647 s21 = a[i + j*a_dim1]*b[j + l*b_dim1] + s21;
4648 }
4649 b[i + l*b_dim1] = -a[i + i*a_dim1]*s21;
4650 }
4651 nm1 = n - 1;
4652 for (i = 1; i <= nm1; ++i) {
4653 nmi = n - i;
4654 s22 = -b[nmi + l*b_dim1];
4655 for (j = 1; j <= i; ++j) {
4656 nmjp1 = n - j + 1;
4657 s22 = a[nmi + nmjp1*a_dim1]*b[nmjp1 + l*b_dim1] + s22;
4658 }
4659 b[nmi + l*b_dim1] = -s22;
4660 }
4661 }
4662}
4663
4664////////////////////////////////////////////////////////////////////////////////
4665/// Return Global bin number corresponding to binx,y,z.
4666///
4667/// 2-D and 3-D histograms are represented with a one dimensional
4668/// structure.
4669/// This has the advantage that all existing functions, such as
4670/// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
4671///
4672/// In case of a TH1x, returns binx directly.
4673/// see TH1::GetBinXYZ for the inverse transformation.
4674///
4675/// Convention for numbering bins
4676///
4677/// For all histogram types: nbins, xlow, xup
4678///
4679/// - bin = 0; underflow bin
4680/// - bin = 1; first bin with low-edge xlow INCLUDED
4681/// - bin = nbins; last bin with upper-edge xup EXCLUDED
4682/// - bin = nbins+1; overflow bin
4683///
4684/// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4685/// For example, assuming a 3-D histogram with binx,biny,binz, the function
4686///
4687/// ~~~ {.cpp}
4688/// Int_t bin = h->GetBin(binx,biny,binz);
4689/// ~~~
4690///
4691/// returns a global/linearized bin number. This global bin is useful
4692/// to access the bin information independently of the dimension.
4693
4694Int_t TH1::GetBin(Int_t binx, Int_t, Int_t) const
4695{
4696 Int_t ofx = fXaxis.GetNbins() + 1; // overflow bin
4697 if (binx < 0) binx = 0;
4698 if (binx > ofx) binx = ofx;
4699
4700 return binx;
4701}
4702
4703////////////////////////////////////////////////////////////////////////////////
4704/// Return binx, biny, binz corresponding to the global bin number globalbin
4705/// see TH1::GetBin function above
4706
4707void TH1::GetBinXYZ(Int_t binglobal, Int_t &binx, Int_t &biny, Int_t &binz) const
4708{
4709 Int_t nx = fXaxis.GetNbins()+2;
4710 Int_t ny = fYaxis.GetNbins()+2;
4711
4712 if (GetDimension() == 1) {
4713 binx = binglobal%nx;
4714 biny = 0;
4715 binz = 0;
4716 return;
4717 }
4718 if (GetDimension() == 2) {
4719 binx = binglobal%nx;
4720 biny = ((binglobal-binx)/nx)%ny;
4721 binz = 0;
4722 return;
4723 }
4724 if (GetDimension() == 3) {
4725 binx = binglobal%nx;
4726 biny = ((binglobal-binx)/nx)%ny;
4727 binz = ((binglobal-binx)/nx -biny)/ny;
4728 }
4729}
4730
4731////////////////////////////////////////////////////////////////////////////////
4732/// Return a random number distributed according the histogram bin contents.
4733/// This function checks if the bins integral exists. If not, the integral
4734/// is evaluated, normalized to one.
4735///
4736/// The integral is automatically recomputed if the number of entries
4737/// is not the same then when the integral was computed.
4738/// NB Only valid for 1-d histograms. Use GetRandom2 or 3 otherwise.
4739/// If the histogram has a bin with negative content a NaN is returned
4740
4742{
4743 if (fDimension > 1) {
4744 Error("GetRandom","Function only valid for 1-d histograms");
4745 return 0;
4746 }
4747 Int_t nbinsx = GetNbinsX();
4748 Double_t integral = 0;
4749 // compute integral checking that all bins have positive content (see ROOT-5894)
4750 if (fIntegral) {
4751 if (fIntegral[nbinsx+1] != fEntries) integral = ((TH1*)this)->ComputeIntegral(true);
4752 else integral = fIntegral[nbinsx];
4753 } else {
4754 integral = ((TH1*)this)->ComputeIntegral(true);
4755 }
4756 if (integral == 0) return 0;
4757 // return a NaN in case some bins have negative content
4758 if (integral == TMath::QuietNaN() ) return TMath::QuietNaN();
4759
4760 Double_t r1 = gRandom->Rndm();
4761 Int_t ibin = TMath::BinarySearch(nbinsx,fIntegral,r1);
4762 Double_t x = GetBinLowEdge(ibin+1);
4763 if (r1 > fIntegral[ibin]) x +=
4764 GetBinWidth(ibin+1)*(r1-fIntegral[ibin])/(fIntegral[ibin+1] - fIntegral[ibin]);
4765 return x;
4766}
4767
4768////////////////////////////////////////////////////////////////////////////////
4769/// Return content of bin number bin.
4770///
4771/// Implemented in TH1C,S,F,D
4772///
4773/// Convention for numbering bins
4774///
4775/// For all histogram types: nbins, xlow, xup
4776///
4777/// - bin = 0; underflow bin
4778/// - bin = 1; first bin with low-edge xlow INCLUDED
4779/// - bin = nbins; last bin with upper-edge xup EXCLUDED
4780/// - bin = nbins+1; overflow bin
4781///
4782/// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4783/// For example, assuming a 3-D histogram with binx,biny,binz, the function
4784///
4785/// ~~~ {.cpp}
4786/// Int_t bin = h->GetBin(binx,biny,binz);
4787/// ~~~
4788///
4789/// returns a global/linearized bin number. This global bin is useful
4790/// to access the bin information independently of the dimension.
4791
4793{
4794 if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
4795 if (bin < 0) bin = 0;
4796 if (bin >= fNcells) bin = fNcells-1;
4797
4798 return RetrieveBinContent(bin);
4799}
4800
4801////////////////////////////////////////////////////////////////////////////////
4802/// Compute first binx in the range [firstx,lastx] for which
4803/// diff = abs(bin_content-c) <= maxdiff
4804///
4805/// In case several bins in the specified range with diff=0 are found
4806/// the first bin found is returned in binx.
4807/// In case several bins in the specified range satisfy diff <=maxdiff
4808/// the bin with the smallest difference is returned in binx.
4809/// In all cases the function returns the smallest difference.
4810///
4811/// NOTE1: if firstx <= 0, firstx is set to bin 1
4812/// if (lastx < firstx then firstx is set to the number of bins
4813/// ie if firstx=0 and lastx=0 (default) the search is on all bins.
4814///
4815/// NOTE2: if maxdiff=0 (default), the first bin with content=c is returned.
4816
4817Double_t TH1::GetBinWithContent(Double_t c, Int_t &binx, Int_t firstx, Int_t lastx,Double_t maxdiff) const
4818{
4819 if (fDimension > 1) {
4820 binx = 0;
4821 Error("GetBinWithContent","function is only valid for 1-D histograms");
4822 return 0;
4823 }
4824
4825 if (fBuffer) ((TH1*)this)->BufferEmpty();
4826
4827 if (firstx <= 0) firstx = 1;
4828 if (lastx < firstx) lastx = fXaxis.GetNbins();
4829 Int_t binminx = 0;
4830 Double_t diff, curmax = 1.e240;
4831 for (Int_t i=firstx;i<=lastx;i++) {
4832 diff = TMath::Abs(RetrieveBinContent(i)-c);
4833 if (diff <= 0) {binx = i; return diff;}
4834 if (diff < curmax && diff <= maxdiff) {curmax = diff, binminx=i;}
4835 }
4836 binx = binminx;
4837 return curmax;
4838}
4839
4840////////////////////////////////////////////////////////////////////////////////
4841/// Given a point x, approximates the value via linear interpolation
4842/// based on the two nearest bin centers
4843///
4844/// Andy Mastbaum 10/21/08
4845
4847{
4848 if (fBuffer) ((TH1*)this)->BufferEmpty();
4849
4850 Int_t xbin = FindBin(x);
4851 Double_t x0,x1,y0,y1;
4852
4853 if(x<=GetBinCenter(1)) {
4854 return RetrieveBinContent(1);
4855 } else if(x>=GetBinCenter(GetNbinsX())) {
4856 return RetrieveBinContent(GetNbinsX());
4857 } else {
4858 if(x<=GetBinCenter(xbin)) {
4859 y0 = RetrieveBinContent(xbin-1);
4860 x0 = GetBinCenter(xbin-1);
4861 y1 = RetrieveBinContent(xbin);
4862 x1 = GetBinCenter(xbin);
4863 } else {
4864 y0 = RetrieveBinContent(xbin);
4865 x0 = GetBinCenter(xbin);
4866 y1 = RetrieveBinContent(xbin+1);
4867 x1 = GetBinCenter(xbin+1);
4868 }
4869 return y0 + (x-x0)*((y1-y0)/(x1-x0));
4870 }
4871}
4872
4873////////////////////////////////////////////////////////////////////////////////
4874/// Interpolate. Not yet implemented.
4875
4877{
4878 Error("Interpolate","This function must be called with 1 argument for a TH1");
4879 return 0;
4880}
4881
4882////////////////////////////////////////////////////////////////////////////////
4883/// Interpolate. Not yet implemented.
4884
4886{
4887 Error("Interpolate","This function must be called with 1 argument for a TH1");
4888 return 0;
4889}
4890
4891///////////////////////////////////////////////////////////////////////////////
4892/// Check if an histogram is empty
4893/// (this a protected method used mainly by TH1Merger )
4894
4895Bool_t TH1::IsEmpty() const
4896{
4897 // if fTsumw or fentries are not zero histogram is not empty
4898 // need to use GetEntries() instead of fEntries in case of bugger histograms
4899 // so we will flash the buffer
4900 if (fTsumw != 0) return kFALSE;
4901 if (GetEntries() != 0) return kFALSE;
4902 // case fTSumw == 0 amd entries are also zero
4903 // this should not really happening, but if one sets content by hand
4904 // it can happen. a call to ResetStats() should be done in such cases
4905 double sumw = 0;
4906 for (int i = 0; i< GetNcells(); ++i) sumw += RetrieveBinContent(i);
4907 return (sumw != 0) ? kFALSE : kTRUE;
4908}
4909
4910////////////////////////////////////////////////////////////////////////////////
4911/// Return true if the bin is overflow.
4912
4913Bool_t TH1::IsBinOverflow(Int_t bin, Int_t iaxis) const
4914{
4915 Int_t binx, biny, binz;
4916 GetBinXYZ(bin, binx, biny, binz);
4917
4918 if (iaxis == 0) {
4919 if ( fDimension == 1 )
4920 return binx >= GetNbinsX() + 1;
4921 if ( fDimension == 2 )
4922 return (binx >= GetNbinsX() + 1) ||
4923 (biny >= GetNbinsY() + 1);
4924 if ( fDimension == 3 )
4925 return (binx >= GetNbinsX() + 1) ||
4926 (biny >= GetNbinsY() + 1) ||
4927 (binz >= GetNbinsZ() + 1);
4928 return kFALSE;
4929 }
4930 if (iaxis == 1)
4931 return binx >= GetNbinsX() + 1;
4932 if (iaxis == 2)
4933 return biny >= GetNbinsY() + 1;
4934 if (iaxis == 3)
4935 return binz >= GetNbinsZ() + 1;
4936
4937 Error("IsBinOverflow","Invalid axis value");
4938 return kFALSE;
4939}
4940
4941////////////////////////////////////////////////////////////////////////////////
4942/// Return true if the bin is underflow.
4943/// If iaxis = 0 make OR with all axes otherwise check only for the given axis
4944
4945Bool_t TH1::IsBinUnderflow(Int_t bin, Int_t iaxis) const
4946{
4947 Int_t binx, biny, binz;
4948 GetBinXYZ(bin, binx, biny, binz);
4949
4950 if (iaxis == 0) {
4951 if ( fDimension == 1 )
4952 return (binx <= 0);
4953 else if ( fDimension == 2 )
4954 return (binx <= 0 || biny <= 0);
4955 else if ( fDimension == 3 )
4956 return (binx <= 0 || biny <= 0 || binz <= 0);
4957 else
4958 return kFALSE;
4959 }
4960 if (iaxis == 1)
4961 return (binx <= 0);
4962 if (iaxis == 2)
4963 return (biny <= 0);
4964 if (iaxis == 3)
4965 return (binz <= 0);
4966
4967 Error("IsBinUnderflow","Invalid axis value");
4968 return kFALSE;
4969}
4970
4971////////////////////////////////////////////////////////////////////////////////
4972/// Reduce the number of bins for the axis passed in the option to the number of bins having a label.
4973/// The method will remove only the extra bins existing after the last "labeled" bin.
4974/// Note that if there are "un-labeled" bins present between "labeled" bins they will not be removed
4975
4977{
4978 Int_t iaxis = AxisChoice(ax);
4979 TAxis *axis = 0;
4980 if (iaxis == 1) axis = GetXaxis();
4981 if (iaxis == 2) axis = GetYaxis();
4982 if (iaxis == 3) axis = GetZaxis();
4983 if (!axis) {
4984 Error("LabelsDeflate","Invalid axis option %s",ax);
4985 return;
4986 }
4987 if (!axis->GetLabels()) return;
4988
4989 // find bin with last labels
4990 // bin number is object ID in list of labels
4991 // therefore max bin number is number of bins of the deflated histograms
4992 TIter next(axis->GetLabels());
4993 TObject *obj;
4994 Int_t nbins = 0;
4995 while ((obj = next())) {
4996 Int_t ibin = obj->GetUniqueID();
4997 if (ibin > nbins) nbins = ibin;
4998 }
4999 if (nbins < 1) nbins = 1;
5000
5001 // Do nothing in case it was the last bin
5002 if (nbins==axis->GetNbins()) return;
5003
5004 TH1 *hold = (TH1*)IsA()->New();
5005 R__ASSERT(hold);
5006 hold->SetDirectory(0);
5007 Copy(*hold);
5008
5009 Bool_t timedisp = axis->GetTimeDisplay();
5010 Double_t xmin = axis->GetXmin();
5011 Double_t xmax = axis->GetBinUpEdge(nbins);
5012 if (xmax <= xmin) xmax = xmin +nbins;
5013 axis->SetRange(0,0);
5014 axis->Set(nbins,xmin,xmax);
5015 SetBinsLength(-1); // reset the number of cells
5016 Int_t errors = fSumw2.fN;
5017 if (errors) fSumw2.Set(fNcells);
5018 axis->SetTimeDisplay(timedisp);
5019 // reset histogram content
5020 Reset("ICE");
5021
5022 //now loop on all bins and refill
5023 // NOTE that if the bins without labels have content
5024 // it will be put in the underflow/overflow.
5025 // For this reason we use AddBinContent method
5026 Double_t oldEntries = fEntries;
5027 Int_t bin,binx,biny,binz;
5028 for (bin=0; bin < hold->fNcells; ++bin) {
5029 hold->GetBinXYZ(bin,binx,biny,binz);
5030 Int_t ibin = GetBin(binx,biny,binz);
5031 Double_t cu = hold->RetrieveBinContent(bin);
5032 AddBinContent(ibin,cu);
5033 if (errors) {
5034 fSumw2.fArray[ibin] += hold->fSumw2.fArray[bin];
5035 }
5036 }
5037 fEntries = oldEntries;
5038 delete hold;
5039}
5040
5041////////////////////////////////////////////////////////////////////////////////
5042/// Double the number of bins for axis.
5043/// Refill histogram
5044/// This function is called by TAxis::FindBin(const char *label)
5045
5047{
5048 Int_t iaxis = AxisChoice(ax);
5049 TAxis *axis = 0;
5050 if (iaxis == 1) axis = GetXaxis();
5051 if (iaxis == 2) axis = GetYaxis();
5052 if (iaxis == 3) axis = GetZaxis();
5053 if (!axis) return;
5054
5055 TH1 *hold = (TH1*)IsA()->New();;
5056 hold->SetDirectory(0);
5057 Copy(*hold);
5058
5059 Bool_t timedisp = axis->GetTimeDisplay();
5060 Int_t nbins = axis->GetNbins();
5061 Double_t xmin = axis->GetXmin();
5062 Double_t xmax = axis->GetXmax();
5063 xmax = xmin + 2*(xmax-xmin);
5064 axis->SetRange(0,0);
5065 // double the bins and recompute ncells
5066 axis->Set(2*nbins,xmin,xmax);
5067 SetBinsLength(-1);
5068 Int_t errors = fSumw2.fN;
5069 if (errors) fSumw2.Set(fNcells);
5070 axis->SetTimeDisplay(timedisp);
5071
5072 Reset("ICE"); // reset content and error
5073
5074 //now loop on all bins and refill
5075 Double_t oldEntries = fEntries;
5076 Int_t bin,ibin,binx,biny,binz;
5077 for (ibin =0; ibin < hold->fNcells; ibin++) {
5078 // get the binx,y,z values . The x-y-z (axis) bin values will stay the same between new-old after the expanding
5079 hold->GetBinXYZ(ibin,binx,biny,binz);
5080 bin = GetBin(binx,biny,binz);
5081
5082 // underflow and overflow will be cleaned up because their meaning has been altered
5083 if (hold->IsBinUnderflow(ibin,iaxis) || hold->IsBinOverflow(ibin,iaxis)) {
5084 continue;
5085 }
5086 else {
5087 AddBinContent(bin, hold->RetrieveBinContent(ibin));
5088 if (errors) fSumw2.fArray[bin] += hold->fSumw2.fArray[ibin];
5089 }
5090 }
5091 fEntries = oldEntries;
5092 delete hold;
5093}
5094
5095////////////////////////////////////////////////////////////////////////////////
5096/// Set option(s) to draw axis with labels
5097/// \param[in] option
5098/// - "a" sort by alphabetic order
5099/// - ">" sort by decreasing values
5100/// - "<" sort by increasing values
5101/// - "h" draw labels horizontal
5102/// - "v" draw labels vertical
5103/// - "u" draw labels up (end of label right adjusted)
5104/// - "d" draw labels down (start of label left adjusted)
5105/// \param[in] ax axis
5106
5107void TH1::LabelsOption(Option_t *option, Option_t *ax)
5108{
5109 Int_t iaxis = AxisChoice(ax);
5110 TAxis *axis = 0;
5111 if (iaxis == 1) axis = GetXaxis();
5112 if (iaxis == 2) axis = GetYaxis();
5113 if (iaxis == 3) axis = GetZaxis();
5114 if (!axis) return;
5115 THashList *labels = axis->GetLabels();
5116 if (!labels) {
5117 Warning("LabelsOption","Cannot sort. No labels");
5118 return;
5119 }
5120 TString opt = option;
5121 opt.ToLower();
5122 if (opt.Contains("h")) {
5127 }
5128 if (opt.Contains("v")) {
5133 }
5134 if (opt.Contains("u")) {
5135 axis->SetBit(TAxis::kLabelsUp);
5139 }
5140 if (opt.Contains("d")) {
5145 }
5146 Int_t sort = -1;
5147 if (opt.Contains("a")) sort = 0;
5148 if (opt.Contains(">")) sort = 1;
5149 if (opt.Contains("<")) sort = 2;
5150 if (sort < 0) return;
5151 if (sort > 0 && GetDimension() > 2) {
5152 Error("LabelsOption","Sorting by value not implemented for 3-D histograms");
5153 return;
5154 }
5155
5156 Double_t entries = fEntries;
5157 Int_t n = TMath::Min(axis->GetNbins(), labels->GetSize());
5158 std::vector<Int_t> a(n+2);
5159
5160 Int_t i,j,k;
5161 std::vector<Double_t> cont;
5162 std::vector<Double_t> errors;
5163 THashList *labold = new THashList(labels->GetSize(),1);
5164 TIter nextold(labels);
5165 TObject *obj;
5166 while ((obj=nextold())) {
5167 labold->Add(obj);
5168 }
5169 labels->Clear();
5170 if (sort > 0) {
5171 //---sort by values of bins
5172 if (GetDimension() == 1) {
5173 cont.resize(n);
5174 if (fSumw2.fN) errors.resize(n);
5175 for (i=1;i<=n;i++) {
5176 cont[i-1] = GetBinContent(i);
5177 if (!errors.empty()) errors[i-1] = GetBinError(i);
5178 }
5179 if (sort ==1) TMath::Sort(n,cont.data(),a.data(),kTRUE); //sort by decreasing values
5180 else TMath::Sort(n,cont.data(),a.data(),kFALSE); //sort by increasing values
5181 for (i=1;i<=n;i++) {
5182 SetBinContent(i,cont[a[i-1]]);
5183 if (!errors.empty()) SetBinError(i,errors[a[i-1]]);
5184 }
5185 for (i=1;i<=n;i++) {
5186 obj = labold->At(a[i-1]);
5187 labels->Add(obj);
5188 obj->SetUniqueID(i);
5189 }
5190 } else if (GetDimension()== 2) {
5191 std::vector<Double_t> pcont(n+2);
5192 Int_t nx = fXaxis.GetNbins();
5193 Int_t ny = fYaxis.GetNbins();
5194 cont.resize( (nx+2)*(ny+2));
5195 if (fSumw2.fN) errors.resize( (nx+2)*(ny+2));
5196 for (i=1;i<=nx;i++) {
5197 for (j=1;j<=ny;j++) {
5198 cont[i+nx*j] = GetBinContent(i,j);
5199 if (!errors.empty()) errors[i+nx*j] = GetBinError(i,j);
5200 if (axis == GetXaxis()) k = i;
5201 else k = j;
5202 pcont[k-1] += cont[i+nx*j];
5203 }
5204 }
5205 if (sort ==1) TMath::Sort(n,pcont.data(),a.data(),kTRUE); //sort by decreasing values
5206 else TMath::Sort(n,pcont.data(),a.data(),kFALSE); //sort by increasing values
5207 for (i=0;i<n;i++) {
5208 obj = labold->At(a[i]);
5209 labels->Add(obj);
5210 obj->SetUniqueID(i+1);
5211 }
5212 if (axis == GetXaxis()) {
5213 for (i=1;i<=n;i++) {
5214 for (j=1;j<=ny;j++) {
5215 SetBinContent(i,j,cont[a[i-1]+1+nx*j]);
5216 if (!errors.empty()) SetBinError(i,j,errors[a[i-1]+1+nx*j]);
5217 }
5218 }
5219 }
5220 else {
5221 // using y axis
5222 for (i=1;i<=nx;i++) {
5223 for (j=1;j<=n;j++) {
5224 SetBinContent(i,j,cont[i+nx*(a[j-1]+1)]);
5225 if (!errors.empty()) SetBinError(i,j,errors[i+nx*(a[j-1]+1)]);
5226 }
5227 }
5228 }
5229 } else {
5230 //to be implemented for 3d
5231 }
5232 } else {
5233 //---alphabetic sort
5234 const UInt_t kUsed = 1<<18;
5235 TObject *objk=0;
5236 a[0] = 0;
5237 a[n+1] = n+1;
5238 for (i=1;i<=n;i++) {
5239 const char *label = "zzzzzzzzzzzz";
5240 for (j=1;j<=n;j++) {
5241 obj = labold->At(j-1);
5242 if (!obj) continue;
5243 if (obj->TestBit(kUsed)) continue;
5244 //use strcasecmp for case non-sensitive sort (may be an option)
5245 if (strcmp(label,obj->GetName()) < 0) continue;
5246 objk = obj;
5247 a[i] = j;
5248 label = obj->GetName();
5249 }
5250 if (objk) {
5251 objk->SetUniqueID(i);
5252 labels->Add(objk);
5253 objk->SetBit(kUsed);
5254 }
5255 }
5256 for (i=1;i<=n;i++) {
5257 obj = labels->At(i-1);
5258 if (!obj) continue;
5259 obj->ResetBit(kUsed);
5260 }
5261
5262 if (GetDimension() == 1) {
5263 cont.resize(n+2);
5264 if (fSumw2.fN) errors.resize(n+2);
5265 for (i=1;i<=n;i++) {
5266 cont[i] = GetBinContent(a[i]);
5267 if (!errors.empty()) errors[i] = GetBinError(a[i]);
5268 }
5269 for (i=1;i<=n;i++) {
5270 SetBinContent(i,cont[i]);
5271 if (!errors.empty()) SetBinError(i,errors[i]);
5272 }
5273 } else if (GetDimension()== 2) {
5274 Int_t nx = fXaxis.GetNbins()+2;
5275 Int_t ny = fYaxis.GetNbins()+2;
5276 cont.resize(nx*ny);
5277 if (fSumw2.fN) errors.resize(nx*ny);
5278 for (i=0;i<nx;i++) {
5279 for (j=0;j<ny;j++) {
5280 cont[i+nx*j] = GetBinContent(i,j);
5281 if (!errors.empty()) errors[i+nx*j] = GetBinError(i,j);
5282 }
5283 }
5284 if (axis == GetXaxis()) {
5285 for (i=1;i<=n;i++) {
5286 for (j=0;j<ny;j++) {
5287 SetBinContent(i,j,cont[a[i]+nx*j]);
5288 if (!errors.empty()) SetBinError(i,j,errors[a[i]+nx*j]);
5289 }
5290 }
5291 } else {
5292 for (i=0;i<nx;i++) {
5293 for (j=1;j<=n;j++) {
5294 SetBinContent(i,j,cont[i+nx*a[j]]);
5295 if (!errors.empty()) SetBinError(i,j,errors[i+nx*a[j]]);
5296 }
5297 }
5298 }
5299 } else {
5300 Int_t nx = fXaxis.GetNbins()+2;
5301 Int_t ny = fYaxis.GetNbins()+2;
5302 Int_t nz = fZaxis.GetNbins()+2;
5303 cont.resize(nx*ny*nz);
5304 if (fSumw2.fN) errors.resize(nx*ny*nz);
5305 for (i=0;i<nx;i++) {
5306 for (j=0;j<ny;j++) {
5307 for (k=0;k<nz;k++) {
5308 cont[i+nx*(j+ny*k)] = GetBinContent(i,j,k);
5309 if (!errors.empty()) errors[i+nx*(j+ny*k)] = GetBinError(i,j,k);
5310 }
5311 }
5312 }
5313 if (axis == GetXaxis()) {
5314 // labels on x axis
5315 for (i=1;i<=n;i++) {
5316 for (j=0;j<ny;j++) {
5317 for (k=0;k<nz;k++) {
5318 SetBinContent(i,j,k,cont[a[i]+nx*(j+ny*k)]);
5319 if (!errors.empty()) SetBinError(i,j,k,errors[a[i]+nx*(j+ny*k)]);
5320 }
5321 }
5322 }
5323 }
5324 else if (axis == GetYaxis()) {
5325 // labels on y axis
5326 for (i=0;i<nx;i++) {
5327 for (j=1;j<=n;j++) {
5328 for (k=0;k<nz;k++) {
5329 SetBinContent(i,j,k,cont[i+nx*(a[j]+ny*k)]);
5330 if (!errors.empty()) SetBinError(i,j,k,errors[i+nx*(a[j]+ny*k)]);
5331 }
5332 }
5333 }
5334 }
5335 else {
5336 // labels on z axis
5337 for (i=0;i<nx;i++) {
5338 for (j=0;j<ny;j++) {
5339 for (k=1;k<=n;k++) {
5340 SetBinContent(i,j,k,cont[i+nx*(j+ny*a[k])]);
5341 if (!errors.empty()) SetBinError(i,j,k,errors[i+nx*(j+ny*a[k])]);
5342 }
5343 }
5344 }
5345 }
5346 }
5347 }
5348 fEntries = entries;
5349 delete labold;
5350}
5351
5352////////////////////////////////////////////////////////////////////////////////
5353/// Test if two double are almost equal.
5354
5355static inline Bool_t AlmostEqual(Double_t a, Double_t b, Double_t epsilon = 0.00000001)
5356{
5357 return TMath::Abs(a - b) < epsilon;
5358}
5359
5360////////////////////////////////////////////////////////////////////////////////
5361/// Test if a double is almost an integer.
5362
5363static inline Bool_t AlmostInteger(Double_t a, Double_t epsilon = 0.00000001)
5364{
5365 return AlmostEqual(a - TMath::Floor(a), 0, epsilon) ||
5367}
5368
5369////////////////////////////////////////////////////////////////////////////////
5370/// Test if the binning is equidistant.
5371
5372static inline bool IsEquidistantBinning(const TAxis& axis)
5373{
5374 // check if axis bin are equals
5375 if (!axis.GetXbins()->fN) return true; //
5376 // not able to check if there is only one axis entry
5377 bool isEquidistant = true;
5378 const Double_t firstBinWidth = axis.GetBinWidth(1);
5379 for (int i = 1; i < axis.GetNbins(); ++i) {
5380 const Double_t binWidth = axis.GetBinWidth(i);
5381 const bool match = TMath::AreEqualRel(firstBinWidth, binWidth, TMath::Limits<Double_t>::Epsilon());
5382 isEquidistant &= match;
5383 if (!match)
5384 break;
5385 }
5386 return isEquidistant;
5387}
5388
5389////////////////////////////////////////////////////////////////////////////////
5390/// Same limits and bins.
5391
5392Bool_t TH1::SameLimitsAndNBins(const TAxis& axis1, const TAxis& axis2)
5393{
5394 return axis1.GetNbins() == axis2.GetNbins()
5395 && axis1.GetXmin() == axis2.GetXmin()
5396 && axis1.GetXmax() == axis2.GetXmax();
5397}
5398
5399////////////////////////////////////////////////////////////////////////////////
5400/// Finds new limits for the axis for the Merge function.
5401/// returns false if the limits are incompatible
5402
5403Bool_t TH1::RecomputeAxisLimits(TAxis& destAxis, const TAxis& anAxis)
5404{
5405 if (SameLimitsAndNBins(destAxis, anAxis))
5406 return kTRUE;
5407
5408 if (!IsEquidistantBinning(destAxis) || !IsEquidistantBinning(anAxis))
5409 return kFALSE; // not equidistant user binning not supported
5410
5411 Double_t width1 = destAxis.GetBinWidth(0);
5412 Double_t width2 = anAxis.GetBinWidth(0);
5413 if (width1 == 0 || width2 == 0)
5414 return kFALSE; // no binning not supported
5415
5416 Double_t xmin = TMath::Min(destAxis.GetXmin(), anAxis.GetXmin());
5417 Double_t xmax = TMath::Max(destAxis.GetXmax(), anAxis.GetXmax());
5418 Double_t width = TMath::Max(width1, width2);
5419
5420 // check the bin size
5421 if (!AlmostInteger(width/width1) || !AlmostInteger(width/width2))
5422 return kFALSE;
5423
5424 // std::cout << "Find new limit using given axis " << anAxis.GetXmin() << " , " << anAxis.GetXmax() << " bin width " << width2 << std::endl;
5425 // std::cout << " and destination axis " << destAxis.GetXmin() << " , " << destAxis.GetXmax() << " bin width " << width1 << std::endl;
5426
5427
5428 // check the limits
5429 Double_t delta;
5430 delta = (destAxis.GetXmin() - xmin)/width1;
5431 if (!AlmostInteger(delta))
5432 xmin -= (TMath::Ceil(delta) - delta)*width1;
5433
5434 delta = (anAxis.GetXmin() - xmin)/width2;
5435 if (!AlmostInteger(delta))
5436 xmin -= (TMath::Ceil(delta) - delta)*width2;
5437
5438
5439 delta = (destAxis.GetXmin() - xmin)/width1;
5440 if (!AlmostInteger(delta))
5441 return kFALSE;
5442
5443
5444 delta = (xmax - destAxis.GetXmax())/width1;
5445 if (!AlmostInteger(delta))
5446 xmax += (TMath::Ceil(delta) - delta)*width1;
5447
5448
5449 delta = (xmax - anAxis.GetXmax())/width2;
5450 if (!AlmostInteger(delta))
5451 xmax += (TMath::Ceil(delta) - delta)*width2;
5452
5453
5454 delta = (xmax - destAxis.GetXmax())/width1;
5455 if (!AlmostInteger(delta))
5456 return kFALSE;
5457#ifdef DEBUG
5458 if (!AlmostInteger((xmax - xmin) / width)) { // unnecessary check
5459 printf("TH1::RecomputeAxisLimits - Impossible\n");
5460 return kFALSE;
5461 }
5462#endif
5463
5464
5465 destAxis.Set(TMath::Nint((xmax - xmin)/width), xmin, xmax);
5466
5467 //std::cout << "New re-computed axis : [ " << xmin << " , " << xmax << " ] width = " << width << " nbins " << destAxis.GetNbins() << std::endl;
5468
5469 return kTRUE;
5470}
5471
5472////////////////////////////////////////////////////////////////////////////////
5473/// Add all histograms in the collection to this histogram.
5474/// This function computes the min/max for the x axis,
5475/// compute a new number of bins, if necessary,
5476/// add bin contents, errors and statistics.
5477/// If all histograms have bin labels, bins with identical labels
5478/// will be merged, no matter what their order is.
5479/// If overflows are present and limits are different the function will fail.
5480/// The function returns the total number of entries in the result histogram
5481/// if the merge is successful, -1 otherwise.
5482///
5483/// Possible option:
5484/// -NOL : the merger will ignore the labels and merge the histograms bin by bin using bin center values to match bins
5485/// -NOCHECK: the histogram will not perform a check for duplicate labels in case of axes with labels. The check
5486/// (enabled by default) slows down the merging
5487///
5488/// IMPORTANT remark. The axis x may have different number
5489/// of bins and different limits, BUT the largest bin width must be
5490/// a multiple of the smallest bin width and the upper limit must also
5491/// be a multiple of the bin width.
5492/// Example:
5493///
5494/// ~~~ {.cpp}
5495/// void atest() {
5496/// TH1F *h1 = new TH1F("h1","h1",110,-110,0);
5497/// TH1F *h2 = new TH1F("h2","h2",220,0,110);
5498/// TH1F *h3 = new TH1F("h3","h3",330,-55,55);
5499/// TRandom r;
5500/// for (Int_t i=0;i<10000;i++) {
5501/// h1->Fill(r.Gaus(-55,10));
5502/// h2->Fill(r.Gaus(55,10));
5503/// h3->Fill(r.Gaus(0,10));
5504/// }
5505///
5506/// TList *list = new TList;
5507/// list->Add(h1);
5508/// list->Add(h2);
5509/// list->Add(h3);
5510/// TH1F *h = (TH1F*)h1->Clone("h");
5511/// h->Reset();
5512/// h->Merge(list);
5513/// h->Draw();
5514/// }
5515/// ~~~
5516
5518{
5519 if (!li) return 0;
5520 if (li->IsEmpty()) return (Long64_t) GetEntries();
5521
5522 // use TH1Merger class
5523 TH1Merger merger(*this,*li,opt);
5524 Bool_t ret = merger();
5525
5526 return (ret) ? GetEntries() : -1;
5527}
5528
5529
5530////////////////////////////////////////////////////////////////////////////////
5531/// Performs the operation:
5532///
5533/// `this = this*c1*f1`
5534///
5535/// If errors are defined (see TH1::Sumw2), errors are also recalculated.
5536///
5537/// Only bins inside the function range are recomputed.
5538/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5539/// you should call Sumw2 before making this operation.
5540/// This is particularly important if you fit the histogram after TH1::Multiply
5541///
5542/// The function return kFALSE if the Multiply operation failed
5543
5545{
5546 if (!f1) {
5547 Error("Multiply","Attempt to multiply by a non-existing function");
5548 return kFALSE;
5549 }
5550
5551 // delete buffer if it is there since it will become invalid
5552 if (fBuffer) BufferEmpty(1);
5553
5554 Int_t nx = GetNbinsX() + 2; // normal bins + uf / of (cells)
5555 Int_t ny = GetNbinsY() + 2;
5556 Int_t nz = GetNbinsZ() + 2;
5557 if (fDimension < 2) ny = 1;
5558 if (fDimension < 3) nz = 1;
5559
5560 // reset min-maximum
5561 SetMinimum();
5562 SetMaximum();
5563
5564 // - Loop on bins (including underflows/overflows)
5565 Double_t xx[3];
5566 Double_t *params = 0;
5567 f1->InitArgs(xx,params);
5568
5569 for (Int_t binz = 0; binz < nz; ++binz) {
5570 xx[2] = fZaxis.GetBinCenter(binz);
5571 for (Int_t biny = 0; biny < ny; ++biny) {
5572 xx[1] = fYaxis.GetBinCenter(biny);
5573 for (Int_t binx = 0; binx < nx; ++binx) {
5574 xx[0] = fXaxis.GetBinCenter(binx);
5575 if (!f1->IsInside(xx)) continue;
5577 Int_t bin = binx + nx * (biny + ny *binz);
5578 Double_t cu = c1*f1->EvalPar(xx);
5579 if (TF1::RejectedPoint()) continue;
5580 UpdateBinContent(bin, RetrieveBinContent(bin) * cu);
5581 if (fSumw2.fN) {
5582 fSumw2.fArray[bin] = cu * cu * GetBinErrorSqUnchecked(bin);
5583 }
5584 }
5585 }
5586 }
5587 ResetStats();
5588 return kTRUE;
5589}
5590
5591////////////////////////////////////////////////////////////////////////////////
5592/// Multiply this histogram by h1.
5593///
5594/// `this = this*h1`
5595///
5596/// If errors of this are available (TH1::Sumw2), errors are recalculated.
5597/// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
5598/// if not already set.
5599///
5600/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5601/// you should call Sumw2 before making this operation.
5602/// This is particularly important if you fit the histogram after TH1::Multiply
5603///
5604/// The function return kFALSE if the Multiply operation failed
5605
5606Bool_t TH1::Multiply(const TH1 *h1)
5607{
5608 if (!h1) {
5609 Error("Multiply","Attempt to multiply by a non-existing histogram");
5610 return kFALSE;
5611 }
5612
5613 // delete buffer if it is there since it will become invalid
5614 if (fBuffer) BufferEmpty(1);
5615
5616 try {
5617 CheckConsistency(this,h1);
5618 } catch(DifferentNumberOfBins&) {
5619 Error("Multiply","Attempt to multiply histograms with different number of bins");
5620 return kFALSE;
5621 } catch(DifferentAxisLimits&) {
5622 Warning("Multiply","Attempt to multiply histograms with different axis limits");
5623 } catch(DifferentBinLimits&) {
5624 Warning("Multiply","Attempt to multiply histograms with different bin limits");
5625 } catch(DifferentLabels&) {
5626 Warning("Multiply","Attempt to multiply histograms with different labels");
5627 }
5628
5629 // Create Sumw2 if h1 has Sumw2 set
5630 if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
5631
5632 // - Reset min- maximum
5633 SetMinimum();
5634 SetMaximum();
5635
5636 // - Loop on bins (including underflows/overflows)
5637 for (Int_t i = 0; i < fNcells; ++i) {
5640 UpdateBinContent(i, c0 * c1);
5641 if (fSumw2.fN) {
5643 }
5644 }
5645 ResetStats();
5646 return kTRUE;
5647}
5648
5649////////////////////////////////////////////////////////////////////////////////
5650/// Replace contents of this histogram by multiplication of h1 by h2.
5651///
5652/// `this = (c1*h1)*(c2*h2)`
5653///
5654/// If errors of this are available (TH1::Sumw2), errors are recalculated.
5655/// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
5656/// if not already set.
5657///
5658/// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5659/// you should call Sumw2 before making this operation.
5660/// This is particularly important if you fit the histogram after TH1::Multiply
5661///
5662/// The function return kFALSE if the Multiply operation failed
5663
5664Bool_t TH1::Multiply(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2, Option_t *option)
5665{
5666 TString opt = option;
5667 opt.ToLower();
5668 // Bool_t binomial = kFALSE;
5669 // if (opt.Contains("b")) binomial = kTRUE;
5670 if (!h1 || !h2) {
5671 Error("Multiply","Attempt to multiply by a non-existing histogram");
5672 return kFALSE;
5673 }
5674
5675 // delete buffer if it is there since it will become invalid
5676 if (fBuffer) BufferEmpty(1);
5677
5678 try {
5679 CheckConsistency(h1,h2);
5680 CheckConsistency(this,h1);
5681 } catch(DifferentNumberOfBins&) {
5682 Error("Multiply","Attempt to multiply histograms with different number of bins");
5683 return kFALSE;
5684 } catch(DifferentAxisLimits&) {
5685 Warning("Multiply","Attempt to multiply histograms with different axis limits");
5686 } catch(DifferentBinLimits&) {
5687 Warning("Multiply","Attempt to multiply histograms with different bin limits");
5688 } catch(DifferentLabels&) {
5689 Warning("Multiply","Attempt to multiply histograms with different labels");
5690 }
5691
5692 // Create Sumw2 if h1 or h2 have Sumw2 set
5693 if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
5694
5695 // - Reset min - maximum
5696 SetMinimum();
5697 SetMaximum();
5698
5699 // - Loop on bins (including underflows/overflows)
5700 Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
5701 for (Int_t i = 0; i < fNcells; ++i) {
5703 Double_t b2 = h2->RetrieveBinContent(i);
5704 UpdateBinContent(i, c1 * b1 * c2 * b2);
5705 if (fSumw2.fN) {
5706 fSumw2.fArray[i] = c1sq * c2sq * (h1->GetBinErrorSqUnchecked(i) * b2 * b2 + h2->GetBinErrorSqUnchecked(i) * b1 * b1);
5707 }
5708 }
5709 ResetStats();
5710 return kTRUE;
5711}
5712
5713////////////////////////////////////////////////////////////////////////////////
5714/// Control routine to paint any kind of histograms.
5715///
5716/// This function is automatically called by TCanvas::Update.
5717/// (see TH1::Draw for the list of options)
5718
5719void TH1::Paint(Option_t *option)
5720{
5721 GetPainter(option);
5722
5723 if (fPainter) {
5724 if (strlen(option) > 0) fPainter->Paint(option);
5725 else fPainter->Paint(fOption.Data());
5726 }
5727}
5728
5729////////////////////////////////////////////////////////////////////////////////
5730/// Rebin this histogram
5731///
5732/// #### case 1 xbins=0
5733///
5734/// If newname is blank (default), the current histogram is modified and
5735/// a pointer to it is returned.
5736///
5737/// If newname is not blank, the current histogram is not modified, and a
5738/// new histogram is returned which is a Clone of the current histogram
5739/// with its name set to newname.
5740///
5741/// The parameter ngroup indicates how many bins of this have to be merged
5742/// into one bin of the result.
5743///
5744/// If the original histogram has errors stored (via Sumw2), the resulting
5745/// histograms has new errors correctly calculated.
5746///
5747/// examples: if h1 is an existing TH1F histogram with 100 bins
5748///
5749/// ~~~ {.cpp}
5750/// h1->Rebin(); //merges two bins in one in h1: previous contents of h1 are lost
5751/// h1->Rebin(5); //merges five bins in one in h1
5752/// TH1F *hnew = dynamic_cast<TH1F*>(h1->Rebin(5,"hnew")); // creates a new histogram hnew
5753/// // merging 5 bins of h1 in one bin
5754/// ~~~
5755///
5756/// NOTE: If ngroup is not an exact divider of the number of bins,
5757/// the top limit of the rebinned histogram is reduced
5758/// to the upper edge of the last bin that can make a complete
5759/// group. The remaining bins are added to the overflow bin.
5760/// Statistics will be recomputed from the new bin contents.
5761///
5762/// #### case 2 xbins!=0
5763///
5764/// A new histogram is created (you should specify newname).
5765/// The parameter ngroup is the number of variable size bins in the created histogram.
5766/// The array xbins must contain ngroup+1 elements that represent the low-edges
5767/// of the bins.
5768/// If the original histogram has errors stored (via Sumw2), the resulting
5769/// histograms has new errors correctly calculated.
5770///
5771/// NOTE: The bin edges specified in xbins should correspond to bin edges
5772/// in the original histogram. If a bin edge in the new histogram is
5773/// in the middle of a bin in the original histogram, all entries in
5774/// the split bin in the original histogram will be transfered to the
5775/// lower of the two possible bins in the new histogram. This is
5776/// probably not what you want. A warning message is emitted in this
5777/// case
5778///
5779/// examples: if h1 is an existing TH1F histogram with 100 bins
5780///
5781/// ~~~ {.cpp}
5782/// Double_t xbins[25] = {...} array of low-edges (xbins[25] is the upper edge of last bin
5783/// h1->Rebin(24,"hnew",xbins); //creates a new variable bin size histogram hnew
5784/// ~~~
5785
5786TH1 *TH1::Rebin(Int_t ngroup, const char*newname, const Double_t *xbins)
5787{
5788 Int_t nbins = fXaxis.GetNbins();
5791 if ((ngroup <= 0) || (ngroup > nbins)) {
5792 Error("Rebin", "Illegal value of ngroup=%d",ngroup);
5793 return 0;
5794 }
5795
5796 if (fDimension > 1 || InheritsFrom(TProfile::Class())) {
5797 Error("Rebin", "Operation valid on 1-D histograms only");
5798 return 0;
5799 }
5800 if (!newname && xbins) {
5801 Error("Rebin","if xbins is specified, newname must be given");
5802 return 0;
5803 }
5804
5805 Int_t newbins = nbins/ngroup;
5806 if (!xbins) {
5807 Int_t nbg = nbins/ngroup;
5808 if (nbg*ngroup != nbins) {
5809 Warning("Rebin", "ngroup=%d is not an exact divider of nbins=%d.",ngroup,nbins);
5810 }
5811 }
5812 else {
5813 // in the case that xbins is given (rebinning in variable bins), ngroup is
5814 // the new number of bins and number of grouped bins is not constant.
5815 // when looping for setting the contents for the new histogram we
5816 // need to loop on all bins of original histogram. Then set ngroup=nbins
5817 newbins = ngroup;
5818 ngroup = nbins;
5819 }
5820
5821 // Save old bin contents into a new array
5822 Double_t entries = fEntries;
5823 Double_t *oldBins = new Double_t[nbins+2];
5824 Int_t bin, i;
5825 for (bin=0;bin<nbins+2;bin++) oldBins[bin] = RetrieveBinContent(bin);
5826 Double_t *oldErrors = 0;
5827 if (fSumw2.fN != 0) {
5828 oldErrors = new Double_t[nbins+2];
5829 for (bin=0;bin<nbins+2;bin++) oldErrors[bin] = GetBinError(bin);
5830 }
5831 // rebin will not include underflow/overflow if new axis range is larger than old axis range
5832 if (xbins) {
5833 if (xbins[0] < fXaxis.GetXmin() && oldBins[0] != 0 )
5834 Warning("Rebin","underflow entries will not be used when rebinning");
5835 if (xbins[newbins] > fXaxis.GetXmax() && oldBins[nbins+1] != 0 )
5836 Warning("Rebin","overflow entries will not be used when rebinning");
5837 }
5838
5839
5840 // create a clone of the old histogram if newname is specified
5841 TH1 *hnew = this;
5842 if ((newname && strlen(newname) > 0) || xbins) {
5843 hnew = (TH1*)Clone(newname);
5844 }
5845
5846 //reset can extend bit to avoid an axis extension in SetBinContent
5847 UInt_t oldExtendBitMask = hnew->SetCanExtend(kNoAxis);
5848
5849 // save original statistics
5850 Double_t stat[kNstat];
5851 GetStats(stat);
5852 bool resetStat = false;
5853 // change axis specs and rebuild bin contents array::RebinAx
5854 if(!xbins && (newbins*ngroup != nbins)) {
5855 xmax = fXaxis.GetBinUpEdge(newbins*ngroup);
5856 resetStat = true; //stats must be reset because top bins will be moved to overflow bin
5857 }
5858 // save the TAttAxis members (reset by SetBins)
5859 Int_t nDivisions = fXaxis.GetNdivisions();
5860 Color_t axisColor = fXaxis.GetAxisColor();
5861 Color_t labelColor = fXaxis.GetLabelColor();
5862 Style_t labelFont = fXaxis.GetLabelFont();
5863 Float_t labelOffset = fXaxis.GetLabelOffset();
5864 Float_t labelSize = fXaxis.GetLabelSize();
5865 Float_t tickLength = fXaxis.GetTickLength();
5866 Float_t titleOffset = fXaxis.GetTitleOffset();
5867 Float_t titleSize = fXaxis.GetTitleSize();
5868 Color_t titleColor = fXaxis.GetTitleColor();
5869 Style_t titleFont = fXaxis.GetTitleFont();
5870
5871 if(!xbins && (fXaxis.GetXbins()->GetSize() > 0)){ // variable bin sizes
5872 Double_t *bins = new Double_t[newbins+1];
5873 for(i = 0; i <= newbins; ++i) bins[i] = fXaxis.GetBinLowEdge(1+i*ngroup);
5874 hnew->SetBins(newbins,bins); //this also changes errors array (if any)
5875 delete [] bins;
5876 } else if (xbins) {
5877 hnew->SetBins(newbins,xbins);
5878 } else {
5879 hnew->SetBins(newbins,xmin,xmax);
5880 }
5881
5882 // Restore axis attributes
5883 fXaxis.SetNdivisions(nDivisions);
5884 fXaxis.SetAxisColor(axisColor);
5885 fXaxis.SetLabelColor(labelColor);
5886 fXaxis.SetLabelFont(labelFont);
5887 fXaxis.SetLabelOffset(labelOffset);
5888 fXaxis.SetLabelSize(labelSize);
5889 fXaxis.SetTickLength(tickLength);
5890 fXaxis.SetTitleOffset(titleOffset);
5891 fXaxis.SetTitleSize(titleSize);
5892 fXaxis.SetTitleColor(titleColor);
5893 fXaxis.SetTitleFont(titleFont);
5894
5895 // copy merged bin contents (ignore under/overflows)
5896 // Start merging only once the new lowest edge is reached
5897 Int_t startbin = 1;
5898 const Double_t newxmin = hnew->GetXaxis()->GetBinLowEdge(1);
5899 while( fXaxis.GetBinCenter(startbin) < newxmin && startbin <= nbins ) {
5900 startbin++;
5901 }
5902 Int_t oldbin = startbin;
5903 Double_t binContent, binError;
5904 for (bin = 1;bin<=newbins;bin++) {
5905 binContent = 0;
5906 binError = 0;
5907 Int_t imax = ngroup;
5908 Double_t xbinmax = hnew->GetXaxis()->GetBinUpEdge(bin);
5909 // check bin edges for the cases when we provide an array of bins
5910 // be careful in case bins can have zero width
5911 if (xbins && !TMath::AreEqualAbs(fXaxis.GetBinLowEdge(oldbin),
5912 hnew->GetXaxis()->GetBinLowEdge(bin),
5913 TMath::Max(1.E-8 * fXaxis.GetBinWidth(oldbin), 1.E-16 )) )
5914 {
5915 Warning("Rebin","Bin edge %d of rebinned histogram does not much any bin edges of the old histogram. Result can be inconsistent",bin);
5916 }
5917 for (i=0;i<ngroup;i++) {
5918 if( (oldbin+i > nbins) ||
5919 ( hnew != this && (fXaxis.GetBinCenter(oldbin+i) > xbinmax)) ) {
5920 imax = i;
5921 break;
5922 }
5923 binContent += oldBins[oldbin+i];
5924 if (oldErrors) binError += oldErrors[oldbin+i]*oldErrors[oldbin+i];
5925 }
5926 hnew->SetBinContent(bin,binContent);
5927 if (oldErrors) hnew->SetBinError(bin,TMath::Sqrt(binError));
5928 oldbin += imax;
5929 }
5930
5931 // sum underflow and overflow contents until startbin
5932 binContent = 0;
5933 binError = 0;
5934 for (i = 0; i < startbin; ++i) {
5935 binContent += oldBins[i];
5936 if (oldErrors) binError += oldErrors[i]*oldErrors[i];
5937 }
5938 hnew->SetBinContent(0,binContent);
5939 if (oldErrors) hnew->SetBinError(0,TMath::Sqrt(binError));
5940 // sum overflow
5941 binContent = 0;
5942 binError = 0;
5943 for (i = oldbin; i <= nbins+1; ++i) {
5944 binContent += oldBins[i];
5945 if (oldErrors) binError += oldErrors[i]*oldErrors[i];
5946 }
5947 hnew->SetBinContent(newbins+1,binContent);
5948 if (oldErrors) hnew->SetBinError(newbins+1,TMath::Sqrt(binError));
5949
5950 hnew->SetCanExtend(oldExtendBitMask); // restore previous state
5951
5952 // restore statistics and entries modified by SetBinContent
5953 hnew->SetEntries(entries);
5954 if (!resetStat) hnew->PutStats(stat);
5955 delete [] oldBins;
5956 if (oldErrors) delete [] oldErrors;
5957 return hnew;
5958}
5959
5960////////////////////////////////////////////////////////////////////////////////
5961/// finds new limits for the axis so that *point* is within the range and
5962/// the limits are compatible with the previous ones (see TH1::Merge).
5963/// new limits are put into *newMin* and *newMax* variables.
5964/// axis - axis whose limits are to be recomputed
5965/// point - point that should fit within the new axis limits
5966/// newMin - new minimum will be stored here
5967/// newMax - new maximum will be stored here.
5968/// false if failed (e.g. if the initial axis limits are wrong
5969/// or the new range is more than \f$ 2^{64} \f$ times the old one).
5970
5971Bool_t TH1::FindNewAxisLimits(const TAxis* axis, const Double_t point, Double_t& newMin, Double_t &newMax)
5972{
5973 Double_t xmin = axis->GetXmin();
5974 Double_t xmax = axis->GetXmax();
5975 if (xmin >= xmax) return kFALSE;
5976 Double_t range = xmax-xmin;
5977 Double_t binsize = range / axis->GetNbins();
5978
5979 //recompute new axis limits by doubling the current range
5980 Int_t ntimes = 0;
5981 while (point < xmin) {
5982 if (ntimes++ > 64)
5983 return kFALSE;
5984 xmin = xmin - range;
5985 range *= 2;
5986 binsize *= 2;
5987 // // make sure that the merging will be correct
5988 // if ( xmin / binsize - TMath::Floor(xmin / binsize) >= 0.5) {
5989 // xmin += 0.5 * binsize;
5990 // xmax += 0.5 * binsize; // won't work with a histogram with only one bin, but I don't care
5991 // }
5992 }
5993 while (point >= xmax) {
5994 if (ntimes++ > 64)
5995 return kFALSE;
5996 xmax = xmax + range;
5997 range *= 2;
5998 binsize *= 2;
5999 // // make sure that the merging will be correct
6000 // if ( xmin / binsize - TMath::Floor(xmin / binsize) >= 0.5) {
6001 // xmin -= 0.5 * binsize;
6002 // xmax -= 0.5 * binsize; // won't work with a histogram with only one bin, but I don't care
6003 // }
6004 }
6005 newMin = xmin;
6006 newMax = xmax;
6007 // Info("FindNewAxisLimits", "OldAxis: (%lf, %lf), new: (%lf, %lf), point: %lf",
6008 // axis->GetXmin(), axis->GetXmax(), xmin, xmax, point);
6009
6010 return kTRUE;
6011}
6012
6013////////////////////////////////////////////////////////////////////////////////
6014/// Histogram is resized along axis such that x is in the axis range.
6015/// The new axis limits are recomputed by doubling iteratively
6016/// the current axis range until the specified value x is within the limits.
6017/// The algorithm makes a copy of the histogram, then loops on all bins
6018/// of the old histogram to fill the extended histogram.
6019/// Takes into account errors (Sumw2) if any.
6020/// The algorithm works for 1-d, 2-D and 3-D histograms.
6021/// The axis must be extendable before invoking this function.
6022/// Ex:
6023///
6024/// ~~~ {.cpp}
6025/// h->GetXaxis()->SetCanExtend(kTRUE);
6026/// ~~~
6027
6028void TH1::ExtendAxis(Double_t x, TAxis *axis)
6029{
6030 if (!axis->CanExtend()) return;
6031 if (TMath::IsNaN(x)) { // x may be a NaN
6033 return;
6034 }
6035
6036 if (axis->GetXmin() >= axis->GetXmax()) return;
6037 if (axis->GetNbins() <= 0) return;
6038
6040 if (!FindNewAxisLimits(axis, x, xmin, xmax))
6041 return;
6042
6043 //save a copy of this histogram
6044 TH1 *hold = (TH1*)IsA()->New();
6045 hold->SetDirectory(0);
6046 Copy(*hold);
6047 //set new axis limits
6048 axis->SetLimits(xmin,xmax);
6049
6050
6051 //now loop on all bins and refill
6052 Int_t errors = GetSumw2N();
6053
6054 Reset("ICE"); //reset only Integral, contents and Errors
6055
6056 int iaxis = 0;
6057 if (axis == &fXaxis) iaxis = 1;
6058 if (axis == &fYaxis) iaxis = 2;
6059 if (axis == &fZaxis) iaxis = 3;
6060 bool firstw = kTRUE;
6061 Int_t binx,biny, binz = 0;
6062 Int_t ix = 0,iy = 0,iz = 0;
6063 Double_t bx,by,bz;
6064 Int_t ncells = hold->GetNcells();
6065 for (Int_t bin = 0; bin < ncells; ++bin) {
6066 hold->GetBinXYZ(bin,binx,biny,binz);
6067 bx = hold->GetXaxis()->GetBinCenter(binx);
6068 ix = fXaxis.FindFixBin(bx);
6069 if (fDimension > 1) {
6070 by = hold->GetYaxis()->GetBinCenter(biny);
6071 iy = fYaxis.FindFixBin(by);
6072 if (fDimension > 2) {
6073 bz = hold->GetZaxis()->GetBinCenter(binz);
6074 iz = fZaxis.FindFixBin(bz);
6075 }
6076 }
6077 // exclude underflow/overflow
6078 double content = hold->RetrieveBinContent(bin);
6079 if (content == 0) continue;
6080 if (IsBinUnderflow(bin,iaxis) || IsBinOverflow(bin,iaxis) ) {
6081 if (firstw) {
6082 Warning("ExtendAxis","Histogram %s has underflow or overflow in the axis that is extendable"
6083 " their content will be lost",GetName() );
6084 firstw= kFALSE;
6085 }
6086 continue;
6087 }
6088 Int_t ibin= GetBin(ix,iy,iz);
6089 AddBinContent(ibin, content);
6090 if (errors) {
6091 fSumw2.fArray[ibin] += hold->GetBinErrorSqUnchecked(bin);
6092 }
6093 }
6094 delete hold;
6095}
6096
6097////////////////////////////////////////////////////////////////////////////////
6098/// Recursively remove object from the list of functions
6099
6101{
6102 // Rely on TROOT::RecursiveRemove to take the readlock.
6103
6104 if (fFunctions) {
6106 }
6107}
6108
6109////////////////////////////////////////////////////////////////////////////////
6110/// Multiply this histogram by a constant c1.
6111///
6112/// `this = c1*this`
6113///
6114/// Note that both contents and errors(if any) are scaled.
6115/// This function uses the services of TH1::Add
6116///
6117/// IMPORTANT NOTE: Sumw2() is called automatically when scaling
6118/// If you are not interested in the histogram statistics you can call
6119/// Sumw2(off) or use the option "nosw2"
6120///
6121/// One can scale an histogram such that the bins integral is equal to
6122/// the normalization parameter via TH1::Scale(Double_t norm), where norm
6123/// is the desired normalization divided by the integral of the histogram.
6124///
6125/// If option contains "width" the bin contents and errors are divided
6126/// by the bin width.
6127
6128void TH1::Scale(Double_t c1, Option_t *option)
6129{
6130
6131 TString opt = option; opt.ToLower();
6132 // store bin errors when scaling since cannot anymore be computed as sqrt(N)
6133 if (!opt.Contains("nosw2") && GetSumw2N() == 0) Sumw2();
6134 if (opt.Contains("width")) Add(this, this, c1, -1);
6135 else {
6136 if (fBuffer) BufferEmpty(1);
6137 for(Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, c1 * RetrieveBinContent(i));
6138 if (fSumw2.fN) for(Int_t i = 0; i < fNcells; ++i) fSumw2.fArray[i] *= (c1 * c1); // update errors
6139 SetMinimum(); SetMaximum(); // minimum and maximum value will be recalculated the next time
6140 }
6141
6142 // if contours set, must also scale contours
6143 Int_t ncontours = GetContour();
6144 if (ncontours == 0) return;
6145 Double_t* levels = fContour.GetArray();
6146 for (Int_t i = 0; i < ncontours; ++i) levels[i] *= c1;
6147}
6148
6149////////////////////////////////////////////////////////////////////////////////
6150/// Returns true if all axes are extendable.
6151
6153{
6154 Bool_t canExtend = fXaxis.CanExtend();
6155 if (GetDimension() > 1) canExtend &= fYaxis.CanExtend();
6156 if (GetDimension() > 2) canExtend &= fZaxis.CanExtend();
6157
6158 return canExtend;
6159}
6160
6161////////////////////////////////////////////////////////////////////////////////
6162/// Make the histogram axes extendable / not extendable according to the bit mask
6163/// returns the previous bit mask specifying which axes are extendable
6164
6165UInt_t TH1::SetCanExtend(UInt_t extendBitMask)
6166{
6167 UInt_t oldExtendBitMask = kNoAxis;
6168
6169 if (fXaxis.CanExtend()) oldExtendBitMask |= kXaxis;
6170 if (extendBitMask & kXaxis) fXaxis.SetCanExtend(kTRUE);
6172
6173 if (GetDimension() > 1) {
6174 if (fYaxis.CanExtend()) oldExtendBitMask |= kYaxis;
6175 if (extendBitMask & kYaxis) fYaxis.SetCanExtend(kTRUE);
6177 }
6178
6179 if (GetDimension() > 2) {
6180 if (fZaxis.CanExtend()) oldExtendBitMask |= kZaxis;
6181 if (extendBitMask & kZaxis) fZaxis.SetCanExtend(kTRUE);
6183 }
6184
6185 return oldExtendBitMask;
6186}
6187
6188////////////////////////////////////////////////////////////////////////////////
6189/// Static function to set the default buffer size for automatic histograms.
6190/// When an histogram is created with one of its axis lower limit greater
6191/// or equal to its upper limit, the function SetBuffer is automatically
6192/// called with the default buffer size.
6193
6194void TH1::SetDefaultBufferSize(Int_t buffersize)
6195{
6196 fgBufferSize = buffersize > 0 ? buffersize : 0;
6197}
6198
6199////////////////////////////////////////////////////////////////////////////////
6200/// When this static function is called with `sumw2=kTRUE`, all new
6201/// histograms will automatically activate the storage
6202/// of the sum of squares of errors, ie TH1::Sumw2 is automatically called.
6203
6204void TH1::SetDefaultSumw2(Bool_t sumw2)
6205{
6206 fgDefaultSumw2 = sumw2;
6207}
6208
6209////////////////////////////////////////////////////////////////////////////////
6210/// Change (i.e. set) the title
6211///
6212/// if title is in the form `stringt;stringx;stringy;stringz`
6213/// the histogram title is set to `stringt`, the x axis title to `stringx`,
6214/// the y axis title to `stringy`, and the z axis title to `stringz`.
6215///
6216/// To insert the character `;` in one of the titles, one should use `#;`
6217/// or `#semicolon`.
6218
6219void TH1::SetTitle(const char *title)
6220{
6221 fTitle = title;
6222 fTitle.ReplaceAll("#;",2,"#semicolon",10);
6223
6224 // Decode fTitle. It may contain X, Y and Z titles
6225 TString str1 = fTitle, str2;
6226 Int_t isc = str1.Index(";");
6227 Int_t lns = str1.Length();
6228
6229 if (isc >=0 ) {
6230 fTitle = str1(0,isc);
6231 str1 = str1(isc+1, lns);
6232 isc = str1.Index(";");
6233 if (isc >=0 ) {
6234 str2 = str1(0,isc);
6235 str2.ReplaceAll("#semicolon",10,";",1);
6236 fXaxis.SetTitle(str2.Data());
6237 lns = str1.Length();
6238 str1 = str1(isc+1, lns);
6239 isc = str1.Index(";");
6240 if (isc >=0 ) {
6241 str2 = str1(0,isc);
6242 str2.ReplaceAll("#semicolon",10,";",1);
6243 fYaxis.SetTitle(str2.Data());
6244 lns = str1.Length();
6245 str1 = str1(isc+1, lns);
6246 str1.ReplaceAll("#semicolon",10,";",1);
6247 fZaxis.SetTitle(str1.Data());
6248 } else {
6249 str1.ReplaceAll("#semicolon",10,";",1);
6250 fYaxis.SetTitle(str1.Data());
6251 }
6252 } else {
6253 str1.ReplaceAll("#semicolon",10,";",1);
6254 fXaxis.SetTitle(str1.Data());
6255 }
6256 }
6257
6258 fTitle.ReplaceAll("#semicolon",10,";",1);
6259
6260 if (gPad && TestBit(kMustCleanup)) gPad->Modified();
6261}
6262
6263////////////////////////////////////////////////////////////////////////////////
6264/// Smooth array xx, translation of Hbook routine hsmoof.F
6265/// based on algorithm 353QH twice presented by J. Friedman
6266/// in Proc.of the 1974 CERN School of Computing, Norway, 11-24 August, 1974.
6267
6268void TH1::SmoothArray(Int_t nn, Double_t *xx, Int_t ntimes)
6269{
6270 if (nn < 3 ) {
6271 ::Error("SmoothArray","Need at least 3 points for smoothing: n = %d",nn);
6272 return;
6273 }
6274
6275 Int_t ii;
6276 Double_t hh[6] = {0,0,0,0,0,0};
6277
6278 std::vector<double> yy(nn);
6279 std::vector<double> zz(nn);
6280 std::vector<double> rr(nn);
6281
6282 for (Int_t pass=0;pass<ntimes;pass++) {
6283 // first copy original data into temp array
6284 std::copy(xx, xx+nn, zz.begin() );
6285
6286 for (int noent = 0; noent < 2; ++noent) { // run algorithm two times
6287
6288 // do 353 i.e. running median 3, 5, and 3 in a single loop
6289 for (int kk = 0; kk < 3; kk++) {
6290 std::copy(zz.begin(), zz.end(), yy.begin());
6291 int medianType = (kk != 1) ? 3 : 5;
6292 int ifirst = (kk != 1 ) ? 1 : 2;
6293 int ilast = (kk != 1 ) ? nn-1 : nn -2;
6294 //nn2 = nn - ik - 1;
6295 // do all elements beside the first and last point for median 3
6296 // and first two and last 2 for median 5
6297 for ( ii = ifirst; ii < ilast; ii++) {
6298 assert(ii - ifirst >= 0);
6299 for (int jj = 0; jj < medianType; jj++) {
6300 hh[jj] = yy[ii - ifirst + jj ];
6301 }
6302 zz[ii] = TMath::Median(medianType, hh);
6303 }
6304
6305 if (kk == 0) { // first median 3
6306 // first point
6307 hh[0] = zz[1];
6308 hh[1] = zz[0];
6309 hh[2] = 3*zz[1] - 2*zz[2];
6310 zz[0] = TMath::Median(3, hh);
6311 // last point
6312 hh[0] = zz[nn - 2];
6313 hh[1] = zz[nn - 1];
6314 hh[2] = 3*zz[nn - 2] - 2*zz[nn - 3];
6315 zz[nn - 1] = TMath::Median(3, hh);
6316 }
6317
6318 if (kk == 1) { // median 5
6319 for (ii = 0; ii < 3; ii++) {
6320 hh[ii] = yy[ii];
6321 }
6322 zz[1] = TMath::Median(3, hh);
6323 // last two points
6324 for (ii = 0; ii < 3; ii++) {
6325 hh[ii] = yy[nn - 3 + ii];
6326 }
6327 zz[nn - 2] = TMath::Median(3, hh);
6328 }
6329
6330 }
6331
6332 std::copy ( zz.begin(), zz.end(), yy.begin() );
6333
6334 // quadratic interpolation for flat segments
6335 for (ii = 2; ii < (nn - 2); ii++) {
6336 if (zz[ii - 1] != zz[ii]) continue;
6337 if (zz[ii] != zz[ii + 1]) continue;
6338 hh[0] = zz[ii - 2] - zz[ii];
6339 hh[1] = zz[ii + 2] - zz[ii];
6340 if (hh[0] * hh[1] <= 0) continue;
6341 int jk = 1;
6342 if ( TMath::Abs(hh[1]) > TMath::Abs(hh[0]) ) jk = -1;
6343 yy[ii] = -0.5*zz[ii - 2*jk] + zz[ii]/0.75 + zz[ii + 2*jk] /6.;
6344 yy[ii + jk] = 0.5*(zz[ii + 2*jk] - zz[ii - 2*jk]) + zz[ii];
6345 }
6346
6347 // running means
6348 //std::copy(zz.begin(), zz.end(), yy.begin());
6349 for (ii = 1; ii < nn - 1; ii++) {
6350 zz[ii] = 0.25*yy[ii - 1] + 0.5*yy[ii] + 0.25*yy[ii + 1];
6351 }
6352 zz[0] = yy[0];
6353 zz[nn - 1] = yy[nn - 1];
6354
6355 if (noent == 0) {
6356
6357 // save computed values
6358 std::copy(zz.begin(), zz.end(), rr.begin());
6359
6360 // COMPUTE residuals
6361 for (ii = 0; ii < nn; ii++) {
6362 zz[ii] = xx[ii] - zz[ii];
6363 }
6364 }
6365
6366 } // end loop on noent
6367
6368
6369 double xmin = TMath::MinElement(nn,xx);
6370 for (ii = 0; ii < nn; ii++) {
6371 if (xmin < 0) xx[ii] = rr[ii] + zz[ii];
6372 // make smoothing defined positive - not better using 0 ?
6373 else xx[ii] = TMath::Max((rr[ii] + zz[ii]),0.0 );
6374 }
6375 }
6376}
6377
6378////////////////////////////////////////////////////////////////////////////////
6379/// Smooth bin contents of this histogram.
6380/// if option contains "R" smoothing is applied only to the bins
6381/// defined in the X axis range (default is to smooth all bins)
6382/// Bin contents are replaced by their smooth values.
6383/// Errors (if any) are not modified.
6384/// the smoothing procedure is repeated ntimes (default=1)
6385
6386void TH1::Smooth(Int_t ntimes, Option_t *option)
6387{
6388 if (fDimension != 1) {
6389 Error("Smooth","Smooth only supported for 1-d histograms");
6390 return;
6391 }
6392 Int_t nbins = fXaxis.GetNbins();
6393 if (nbins < 3) {
6394 Error("Smooth","Smooth only supported for histograms with >= 3 bins. Nbins = %d",nbins);
6395 return;
6396 }
6397
6398 // delete buffer if it is there since it will become invalid
6399 if (fBuffer) BufferEmpty(1);
6400
6401 Int_t firstbin = 1, lastbin = nbins;
6402 TString opt = option;
6403 opt.ToLower();
6404 if (opt.Contains("r")) {
6405 firstbin= fXaxis.GetFirst();
6406 lastbin = fXaxis.GetLast();
6407 }
6408 nbins = lastbin - firstbin + 1;
6409 Double_t *xx = new Double_t[nbins];
6410 Double_t nent = fEntries;
6411 Int_t i;
6412 for (i=0;i<nbins;i++) {
6413 xx[i] = RetrieveBinContent(i+firstbin);
6414 }
6415
6416 TH1::SmoothArray(nbins,xx,ntimes);
6417
6418 for (i=0;i<nbins;i++) {
6419 UpdateBinContent(i+firstbin,xx[i]);
6420 }
6421 fEntries = nent;
6422 delete [] xx;
6423
6424 if (gPad) gPad->Modified();
6425}
6426
6427////////////////////////////////////////////////////////////////////////////////
6428/// if flag=kTRUE, underflows and overflows are used by the Fill functions
6429/// in the computation of statistics (mean value, StdDev).
6430/// By default, underflows or overflows are not used.
6431
6432void TH1::StatOverflows(Bool_t flag)
6433{
6434 fgStatOverflows = flag;
6435}
6436
6437////////////////////////////////////////////////////////////////////////////////
6438/// Stream a class object.
6439
6440void TH1::Streamer(TBuffer &b)
6441{
6442 if (b.IsReading()) {
6443 UInt_t R__s, R__c;
6444 Version_t R__v = b.ReadVersion(&R__s, &R__c);
6445 if (fDirectory) fDirectory->Remove(this);
6446 fDirectory = 0;
6447 if (R__v > 2) {
6448 b.ReadClassBuffer(TH1::Class(), this, R__v, R__s, R__c);
6449
6451 fXaxis.SetParent(this);
6452 fYaxis.SetParent(this);
6453 fZaxis.SetParent(this);
6454 TIter next(fFunctions);
6455 TObject *obj;
6456 while ((obj=next())) {
6457 if (obj->InheritsFrom(TF1::Class())) ((TF1*)obj)->SetParent(this);
6458 }
6459 return;
6460 }
6461 //process old versions before automatic schema evolution
6462 TNamed::Streamer(b);
6463 TAttLine::Streamer(b);
6464 TAttFill::Streamer(b);
6465 TAttMarker::Streamer(b);
6466 b >> fNcells;
6467 fXaxis.Streamer(b);
6468 fYaxis.Streamer(b);
6469 fZaxis.Streamer(b);
6470 fXaxis.SetParent(this);
6471 fYaxis.SetParent(this);
6472 fZaxis.SetParent(this);
6473 b >> fBarOffset;
6474 b >> fBarWidth;
6475 b >> fEntries;
6476 b >> fTsumw;
6477 b >> fTsumw2;
6478 b >> fTsumwx;
6479 b >> fTsumwx2;
6480 if (R__v < 2) {
6481 Float_t maximum, minimum, norm;
6482 Float_t *contour=0;
6483 b >> maximum; fMaximum = maximum;
6484 b >> minimum; fMinimum = minimum;
6485 b >> norm; fNormFactor = norm;
6486 Int_t n = b.ReadArray(contour);
6487 fContour.Set(n);
6488 for (Int_t i=0;i<n;i++) fContour.fArray[i] = contour[i];
6489 delete [] contour;
6490 } else {
6491 b >> fMaximum;
6492 b >> fMinimum;
6493 b >> fNormFactor;
6494 fContour.Streamer(b);
6495 }
6496 fSumw2.Streamer(b);
6497 fOption.Streamer(b);
6498 fFunctions->Delete();
6499 fFunctions->Streamer(b);
6500 b.CheckByteCount(R__s, R__c, TH1::IsA());
6501
6502 } else {
6503 b.WriteClassBuffer(TH1::Class(),this);
6504 }
6505}
6506
6507////////////////////////////////////////////////////////////////////////////////
6508/// Print some global quantities for this histogram.
6509/// \param[in] option
6510/// - "base" is given, number of bins and ranges are also printed
6511/// - "range" is given, bin contents and errors are also printed
6512/// for all bins in the current range (default 1-->nbins)
6513/// - "all" is given, bin contents and errors are also printed
6514/// for all bins including under and overflows.
6515
6516void TH1::Print(Option_t *option) const
6517{
6518 if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
6519 printf( "TH1.Print Name = %s, Entries= %d, Total sum= %g\n",GetName(),Int_t(fEntries),GetSumOfWeights());
6520 TString opt = option;
6521 opt.ToLower();
6522 Int_t all;
6523 if (opt.Contains("all")) all = 0;
6524 else if (opt.Contains("range")) all = 1;
6525 else if (opt.Contains("base")) all = 2;
6526 else return;
6527
6528 Int_t bin, binx, biny, binz;
6529 Int_t firstx=0,lastx=0,firsty=0,lasty=0,firstz=0,lastz=0;
6530 if (all == 0) {
6531 lastx = fXaxis.GetNbins()+1;
6532 if (fDimension > 1) lasty = fYaxis.GetNbins()+1;
6533 if (fDimension > 2) lastz = fZaxis.GetNbins()+1;
6534 } else {
6535 firstx = fXaxis.GetFirst(); lastx = fXaxis.GetLast();
6536 if (fDimension > 1) {firsty = fYaxis.GetFirst(); lasty = fYaxis.GetLast();}
6537 if (fDimension > 2) {firstz = fZaxis.GetFirst(); lastz = fZaxis.GetLast();}
6538 }
6539
6540 if (all== 2) {
6541 printf(" Title = %s\n", GetTitle());
6542 printf(" NbinsX= %d, xmin= %g, xmax=%g", fXaxis.GetNbins(), fXaxis.GetXmin(), fXaxis.GetXmax());
6543 if( fDimension > 1) printf(", NbinsY= %d, ymin= %g, ymax=%g", fYaxis.GetNbins(), fYaxis.GetXmin(), fYaxis.GetXmax());
6544 if( fDimension > 2) printf(", NbinsZ= %d, zmin= %g, zmax=%g", fZaxis.GetNbins(), fZaxis.GetXmin(), fZaxis.GetXmax());
6545 printf("\n");
6546 return;
6547 }
6548
6549 Double_t w,e;
6550 Double_t x,y,z;
6551 if (fDimension == 1) {
6552 for (binx=firstx;binx<=lastx;binx++) {
6553 x = fXaxis.GetBinCenter(binx);
6554 w = RetrieveBinContent(binx);
6555 e = GetBinError(binx);
6556 if(fSumw2.fN) printf(" fSumw[%d]=%g, x=%g, error=%g\n",binx,w,x,e);
6557 else printf(" fSumw[%d]=%g, x=%g\n",binx,w,x);
6558 }
6559 }
6560 if (fDimension == 2) {
6561 for (biny=firsty;biny<=lasty;biny++) {
6562 y = fYaxis.GetBinCenter(biny);
6563 for (binx=firstx;binx<=lastx;binx++) {
6564 bin = GetBin(binx,biny);
6565 x = fXaxis.GetBinCenter(binx);
6566 w = RetrieveBinContent(bin);
6567 e = GetBinError(bin);
6568 if(fSumw2.fN) printf(" fSumw[%d][%d]=%g, x=%g, y=%g, error=%g\n",binx,biny,w,x,y,e);
6569 else printf(" fSumw[%d][%d]=%g, x=%g, y=%g\n",binx,biny,w,x,y);
6570 }
6571 }
6572 }
6573 if (fDimension == 3) {
6574 for (binz=firstz;binz<=lastz;binz++) {
6575 z = fZaxis.GetBinCenter(binz);
6576 for (biny=firsty;biny<=lasty;biny++) {
6577 y = fYaxis.GetBinCenter(biny);
6578 for (binx=firstx;binx<=lastx;binx++) {
6579 bin = GetBin(binx,biny,binz);
6580 x = fXaxis.GetBinCenter(binx);
6581 w = RetrieveBinContent(bin);
6582 e = GetBinError(bin);
6583 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);
6584 else printf(" fSumw[%d][%d][%d]=%g, x=%g, y=%g, z=%g\n",binx,biny,binz,w,x,y,z);
6585 }
6586 }
6587 }
6588 }
6589}
6590
6591////////////////////////////////////////////////////////////////////////////////
6592/// Using the current bin info, recompute the arrays for contents and errors
6593
6594void TH1::Rebuild(Option_t *)
6595{
6596 SetBinsLength();
6597 if (fSumw2.fN) {
6599 }
6600}
6601
6602////////////////////////////////////////////////////////////////////////////////
6603/// Reset this histogram: contents, errors, etc.
6604/// \param[in] option
6605/// - if "ICE" is specified, resets only Integral, Contents and Errors.
6606/// - if "ICES" is specified, resets only Integral, Contents, Errors and Statistics
6607/// This option is used
6608/// - if "M" is specified, resets also Minimum and Maximum
6609
6610void TH1::Reset(Option_t *option)
6611{
6612 // The option "ICE" is used when extending the histogram (in ExtendAxis, LabelInflate, etc..)
6613 // The option "ICES is used in combination with the buffer (see BufferEmpty and BufferFill)
6614
6615 TString opt = option;
6616 opt.ToUpper();
6617 fSumw2.Reset();
6618 if (fIntegral) {delete [] fIntegral; fIntegral = 0;}
6619
6620 if (opt.Contains("M")) {
6621 SetMinimum();
6622 SetMaximum();
6623 }
6624
6625 if (opt.Contains("ICE") && !opt.Contains("S")) return;
6626
6627 // Setting fBuffer[0] = 0 is like resetting the buffer but not deleting it
6628 // But what is the sense of calling BufferEmpty() ? For making the axes ?
6629 // BufferEmpty will update contents that later will be
6630 // reset in calling TH1D::Reset. For this we need to reset the stats afterwards
6631 // It may be needed for computing the axis limits....
6632 if (fBuffer) {BufferEmpty(); fBuffer[0] = 0;}
6633
6634 // need to reset also the statistics
6635 // (needs to be done after calling BufferEmpty() )
6636 fTsumw = 0;
6637 fTsumw2 = 0;
6638 fTsumwx = 0;
6639 fTsumwx2 = 0;
6640 fEntries = 0;
6641
6642 if (opt == "ICES") return;
6643
6644
6645 TObject *stats = fFunctions->FindObject("stats");
6646 fFunctions->Remove(stats);
6647 //special logic to support the case where the same object is
6648 //added multiple times in fFunctions.
6649 //This case happens when the same object is added with different
6650 //drawing modes
6651 TObject *obj;
6652 while ((obj = fFunctions->First())) {
6653 while(fFunctions->Remove(obj)) { }
6654 delete obj;
6655 }
6656 if(stats) fFunctions->Add(stats);
6657 fContour.Set(0);
6658}
6659
6660////////////////////////////////////////////////////////////////////////////////
6661/// Save primitive as a C++ statement(s) on output stream out
6662
6663void TH1::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/)
6664{
6665 // empty the buffer before if it exists
6666 if (fBuffer) BufferEmpty();
6667
6668 Bool_t nonEqiX = kFALSE;
6669 Bool_t nonEqiY = kFALSE;
6670 Bool_t nonEqiZ = kFALSE;
6671 Int_t i;
6672 static Int_t nxaxis = 0;
6673 static Int_t nyaxis = 0;
6674 static Int_t nzaxis = 0;
6675 TString sxaxis="xAxis",syaxis="yAxis",szaxis="zAxis";
6676
6677 // Check if the histogram has equidistant X bins or not. If not, we
6678 // create an array holding the bins.
6679 if (GetXaxis()->GetXbins()->fN && GetXaxis()->GetXbins()->fArray) {
6680 nonEqiX = kTRUE;
6681 nxaxis++;
6682 sxaxis += nxaxis;
6683 out << " Double_t "<<sxaxis<<"[" << GetXaxis()->GetXbins()->fN
6684 << "] = {";
6685 for (i = 0; i < GetXaxis()->GetXbins()->fN; i++) {
6686 if (i != 0) out << ", ";
6687 out << GetXaxis()->GetXbins()->fArray[i];
6688 }
6689 out << "}; " << std::endl;
6690 }
6691 // If the histogram is 2 or 3 dimensional, check if the histogram
6692 // has equidistant Y bins or not. If not, we create an array
6693 // holding the bins.
6694 if (fDimension > 1 && GetYaxis()->GetXbins()->fN &&
6695 GetYaxis()->GetXbins()->fArray) {
6696 nonEqiY = kTRUE;
6697 nyaxis++;
6698 syaxis += nyaxis;
6699 out << " Double_t "<<syaxis<<"[" << GetYaxis()->GetXbins()->fN
6700 << "] = {";
6701 for (i = 0; i < GetYaxis()->GetXbins()->fN; i++) {
6702 if (i != 0) out << ", ";
6703 out << GetYaxis()->GetXbins()->fArray[i];
6704 }
6705 out << "}; " << std::endl;
6706 }
6707 // IF the histogram is 3 dimensional, check if the histogram
6708 // has equidistant Z bins or not. If not, we create an array
6709 // holding the bins.
6710 if (fDimension > 2 && GetZaxis()->GetXbins()->fN &&
6711 GetZaxis()->GetXbins()->fArray) {
6712 nonEqiZ = kTRUE;
6713 nzaxis++;
6714 szaxis += nzaxis;
6715 out << " Double_t "<<szaxis<<"[" << GetZaxis()->GetXbins()->fN
6716 << "] = {";
6717 for (i = 0; i < GetZaxis()->GetXbins()->fN; i++) {
6718 if (i != 0) out << ", ";
6719 out << GetZaxis()->GetXbins()->fArray[i];
6720 }
6721 out << "}; " << std::endl;
6722 }
6723
6724 char quote = '"';
6725 out <<" "<<std::endl;
6726 out <<" "<< ClassName() <<" *";
6727
6728 // Histogram pointer has by default the histogram name with an incremental suffix.
6729 // If the histogram belongs to a graph or a stack the suffix is not added because
6730 // the graph and stack objects are not aware of this new name. Same thing if
6731 // the histogram is drawn with the option COLZ because the TPaletteAxis drawn
6732 // when this option is selected, does not know this new name either.
6733 TString opt = option;
6734 opt.ToLower();
6735 static Int_t hcounter = 0;
6736 TString histName = GetName();
6737 if ( !histName.Contains("Graph")
6738 && !histName.Contains("_stack_")
6739 && !opt.Contains("colz")) {
6740 hcounter++;
6741 histName += "__";
6742 histName += hcounter;
6743 }
6744 histName = gInterpreter-> MapCppName(histName);
6745 const char *hname = histName.Data();
6746 if (!strlen(hname)) hname = "unnamed";
6747 TString savedName = GetName();
6748 this->SetName(hname);
6749 TString t(GetTitle());
6750 t.ReplaceAll("\\","\\\\");
6751 t.ReplaceAll("\"","\\\"");
6752 out << hname << " = new " << ClassName() << "(" << quote
6753 << hname << quote << "," << quote<< t.Data() << quote
6754 << "," << GetXaxis()->GetNbins();
6755 if (nonEqiX)
6756 out << ", "<<sxaxis;
6757 else
6758 out << "," << GetXaxis()->GetXmin()
6759 << "," << GetXaxis()->GetXmax();
6760 if (fDimension > 1) {
6761 out << "," << GetYaxis()->GetNbins();
6762 if (nonEqiY)
6763 out << ", "<<syaxis;
6764 else
6765 out << "," << GetYaxis()->GetXmin()
6766 << "," << GetYaxis()->GetXmax();
6767 }
6768 if (fDimension > 2) {
6769 out << "," << GetZaxis()->GetNbins();
6770 if (nonEqiZ)
6771 out << ", "<<szaxis;
6772 else
6773 out << "," << GetZaxis()->GetXmin()
6774 << "," << GetZaxis()->GetXmax();
6775 }
6776 out << ");" << std::endl;
6777
6778 // save bin contents
6779 Int_t bin;
6780 for (bin=0;bin<fNcells;bin++) {
6781 Double_t bc = RetrieveBinContent(bin);
6782 if (bc) {
6783 out<<" "<<hname<<"->SetBinContent("<<bin<<","<<bc<<");"<<std::endl;
6784 }
6785 }
6786
6787 // save bin errors
6788 if (fSumw2.fN) {
6789 for (bin=0;bin<fNcells;bin++) {
6790 Double_t be = GetBinError(bin);
6791 if (be) {
6792 out<<" "<<hname<<"->SetBinError("<<bin<<","<<be<<");"<<std::endl;
6793 }
6794 }
6795 }
6796
6797 TH1::SavePrimitiveHelp(out, hname, option);
6798 this->SetName(savedName.Data());
6799}
6800
6801////////////////////////////////////////////////////////////////////////////////
6802/// Helper function for the SavePrimitive functions from TH1
6803/// or classes derived from TH1, eg TProfile, TProfile2D.
6804
6805void TH1::SavePrimitiveHelp(std::ostream &out, const char *hname, Option_t *option /*= ""*/)
6806{
6807 char quote = '"';
6808 if (TMath::Abs(GetBarOffset()) > 1e-5) {
6809 out<<" "<<hname<<"->SetBarOffset("<<GetBarOffset()<<");"<<std::endl;
6810 }
6811 if (TMath::Abs(GetBarWidth()-1) > 1e-5) {
6812 out<<" "<<hname<<"->SetBarWidth("<<GetBarWidth()<<");"<<std::endl;
6813 }
6814 if (fMinimum != -1111) {
6815 out<<" "<<hname<<"->SetMinimum("<<fMinimum<<");"<<std::endl;
6816 }
6817 if (fMaximum != -1111) {
6818 out<<" "<<hname<<"->SetMaximum("<<fMaximum<<");"<<std::endl;
6819 }
6820 if (fNormFactor != 0) {
6821 out<<" "<<hname<<"->SetNormFactor("<<fNormFactor<<");"<<std::endl;
6822 }
6823 if (fEntries != 0) {
6824 out<<" "<<hname<<"->SetEntries("<<fEntries<<");"<<std::endl;
6825 }
6826 if (fDirectory == 0) {
6827 out<<" "<<hname<<"->SetDirectory(0);"<<std::endl;
6828 }
6829 if (TestBit(kNoStats)) {
6830 out<<" "<<hname<<"->SetStats(0);"<<std::endl;
6831 }
6832 if (fOption.Length() != 0) {
6833 out<<" "<<hname<<"->SetOption("<<quote<<fOption.Data()<<quote<<");"<<std::endl;
6834 }
6835
6836 // save contour levels
6837 Int_t ncontours = GetContour();
6838 if (ncontours > 0) {
6839 out<<" "<<hname<<"->SetContour("<<ncontours<<");"<<std::endl;
6840 Double_t zlevel;
6841 for (Int_t bin=0;bin<ncontours;bin++) {
6842 if (gPad->GetLogz()) {
6843 zlevel = TMath::Power(10,GetContourLevel(bin));
6844 } else {
6845 zlevel = GetContourLevel(bin);
6846 }
6847 out<<" "<<hname<<"->SetContourLevel("<<bin<<","<<zlevel<<");"<<std::endl;
6848 }
6849 }
6850
6851 // save list of functions
6853 TObject *obj;
6854 static Int_t funcNumber = 0;
6855 while (lnk) {
6856 obj = lnk->GetObject();
6857 obj->SavePrimitive(out,Form("nodraw #%d\n",++funcNumber));
6858 if (obj->InheritsFrom(TF1::Class())) {
6859 TString fname;
6860 fname.Form("%s%d",obj->GetName(),funcNumber);
6861 out << " " << fname << "->SetParent(" << hname << ");\n";
6862 out<<" "<<hname<<"->GetListOfFunctions()->Add("
6863 << fname <<");"<<std::endl;
6864 } else if (obj->InheritsFrom("TPaveStats")) {
6865 out<<" "<<hname<<"->GetListOfFunctions()->Add(ptstats);"<<std::endl;
6866 out<<" ptstats->SetParent("<<hname<<");"<<std::endl;
6867 } else if (obj->InheritsFrom("TPolyMarker")) {
6868 out<<" "<<hname<<"->GetListOfFunctions()->Add("
6869 <<"pmarker ,"<<quote<<lnk->GetOption()<<quote<<");"<<std::endl;
6870 } else {
6871 out<<" "<<hname<<"->GetListOfFunctions()->Add("
6872 <<obj->GetName()
6873 <<","<<quote<<lnk->GetOption()<<quote<<");"<<std::endl;
6874 }
6875 lnk = (TObjOptLink*)lnk->Next();
6876 }
6877
6878 // save attributes
6879 SaveFillAttributes(out,hname,0,1001);
6880 SaveLineAttributes(out,hname,1,1,1);
6881 SaveMarkerAttributes(out,hname,1,1,1);
6882 fXaxis.SaveAttributes(out,hname,"->GetXaxis()");
6883 fYaxis.SaveAttributes(out,hname,"->GetYaxis()");
6884 fZaxis.SaveAttributes(out,hname,"->GetZaxis()");
6885 TString opt = option;
6886 opt.ToLower();
6887 if (!opt.Contains("nodraw")) {
6888 out<<" "<<hname<<"->Draw("
6889 <<quote<<option<<quote<<");"<<std::endl;
6890 }
6891}
6892
6893////////////////////////////////////////////////////////////////////////////////
6894/// Copy current attributes from/to current style
6895
6897{
6898 if (!gStyle) return;
6899 if (gStyle->IsReading()) {
6900 fXaxis.ResetAttAxis("X");
6901 fYaxis.ResetAttAxis("Y");
6902 fZaxis.ResetAttAxis("Z");
6913 Int_t dostat = gStyle->GetOptStat();
6914 if (gStyle->GetOptFit() && !dostat) dostat = 1000000001;
6915 SetStats(dostat);
6916 } else {
6928 }
6929 TIter next(GetListOfFunctions());
6930 TObject *obj;
6931
6932 while ((obj = next())) {
6933 obj->UseCurrentStyle();
6934 }
6935}
6936
6937////////////////////////////////////////////////////////////////////////////////
6938/// For axis = 1,2 or 3 returns the mean value of the histogram along
6939/// X,Y or Z axis.
6940///
6941/// For axis = 11, 12, 13 returns the standard error of the mean value
6942/// of the histogram along X, Y or Z axis
6943///
6944/// Note that the mean value/StdDev is computed using the bins in the currently
6945/// defined range (see TAxis::SetRange). By default the range includes
6946/// all bins from 1 to nbins included, excluding underflows and overflows.
6947/// To force the underflows and overflows in the computation, one must
6948/// call the static function TH1::StatOverflows(kTRUE) before filling
6949/// the histogram.
6950///
6951/// Return mean value of this histogram along the X axis.
6952///
6953/// Note that the mean value/StdDev is computed using the bins in the currently
6954/// defined range (see TAxis::SetRange). By default the range includes
6955/// all bins from 1 to nbins included, excluding underflows and overflows.
6956/// To force the underflows and overflows in the computation, one must
6957/// call the static function TH1::StatOverflows(kTRUE) before filling
6958/// the histogram.
6959
6960Double_t TH1::GetMean(Int_t axis) const
6961{
6962 if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
6963 Double_t stats[kNstat];
6964 for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
6965 GetStats(stats);
6966 if (stats[0] == 0) return 0;
6967 if (axis<4){
6968 Int_t ax[3] = {2,4,7};
6969 return stats[ax[axis-1]]/stats[0];
6970 } else {
6971 // mean error = StdDev / sqrt( Neff )
6972 Double_t stddev = GetStdDev(axis-10);
6974 return ( neff > 0 ? stddev/TMath::Sqrt(neff) : 0. );
6975 }
6976}
6977
6978////////////////////////////////////////////////////////////////////////////////
6979/// Return standard error of mean of this histogram along the X axis.
6980///
6981/// Note that the mean value/StdDev is computed using the bins in the currently
6982/// defined range (see TAxis::SetRange). By default the range includes
6983/// all bins from 1 to nbins included, excluding underflows and overflows.
6984/// To force the underflows and overflows in the computation, one must
6985/// call the static function TH1::StatOverflows(kTRUE) before filling
6986/// the histogram.
6987///
6988/// Also note, that although the definition of standard error doesn't include the
6989/// assumption of normality, many uses of this feature implicitly assume it.
6990
6992{
6993 return GetMean(axis+10);
6994}
6995
6996////////////////////////////////////////////////////////////////////////////////
6997/// Returns the Standard Deviation (Sigma).
6998/// The Sigma estimate is computed as
6999/// \f[
7000/// \sqrt{\frac{1}{N}(\sum(x_i-x_{mean})^2)}
7001/// \f]
7002/// For axis = 1,2 or 3 returns the Sigma value of the histogram along
7003/// X, Y or Z axis
7004/// For axis = 11, 12 or 13 returns the error of StdDev estimation along
7005/// X, Y or Z axis for Normal distribution
7006///
7007/// Note that the mean value/sigma is computed using the bins in the currently
7008/// defined range (see TAxis::SetRange). By default the range includes
7009/// all bins from 1 to nbins included, excluding underflows and overflows.
7010/// To force the underflows and overflows in the computation, one must
7011/// call the static function TH1::StatOverflows(kTRUE) before filling
7012/// the histogram.
7013
7014Double_t TH1::GetStdDev(Int_t axis) const
7015{
7016 if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
7017
7018 Double_t x, stddev2, stats[kNstat];
7019 for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
7020 GetStats(stats);
7021 if (stats[0] == 0) return 0;
7022 Int_t ax[3] = {2,4,7};
7023 Int_t axm = ax[axis%10 - 1];
7024 x = stats[axm]/stats[0];
7025 stddev2 = TMath::Abs(stats[axm+1]/stats[0] -x*x);
7026 if (axis<10)
7027 return TMath::Sqrt(stddev2);
7028 else {
7029 // The right formula for StdDev error depends on 4th momentum (see Kendall-Stuart Vol 1 pag 243)
7030 // formula valid for only gaussian distribution ( 4-th momentum = 3 * sigma^4 )
7032 return ( neff > 0 ? TMath::Sqrt(stddev2/(2*neff) ) : 0. );
7033 }
7034}
7035
7036////////////////////////////////////////////////////////////////////////////////
7037/// Return error of standard deviation estimation for Normal distribution
7038///
7039/// Note that the mean value/StdDev is computed using the bins in the currently
7040/// defined range (see TAxis::SetRange). By default the range includes
7041/// all bins from 1 to nbins included, excluding underflows and overflows.
7042/// To force the underflows and overflows in the computation, one must
7043/// call the static function TH1::StatOverflows(kTRUE) before filling
7044/// the histogram.
7045///
7046/// Value returned is standard deviation of sample standard deviation.
7047/// Note that it is an approximated value which is valid only in the case that the
7048/// original data distribution is Normal. The correct one would require
7049/// the 4-th momentum value, which cannot be accurately estimated from an histogram since
7050/// the x-information for all entries is not kept.
7051
7053{
7054 return GetStdDev(axis+10);
7055}
7056
7057////////////////////////////////////////////////////////////////////////////////
7058/// - For axis = 1, 2 or 3 returns skewness of the histogram along x, y or z axis.
7059/// - For axis = 11, 12 or 13 returns the approximate standard error of skewness
7060/// of the histogram along x, y or z axis
7061///
7062///Note, that since third and fourth moment are not calculated
7063///at the fill time, skewness and its standard error are computed bin by bin
7064
7066{
7067
7068 if (axis > 0 && axis <= 3){
7069
7070 Double_t mean = GetMean(axis);
7071 Double_t stddev = GetStdDev(axis);
7072 Double_t stddev3 = stddev*stddev*stddev;
7073
7074 Int_t firstBinX = fXaxis.GetFirst();
7075 Int_t lastBinX = fXaxis.GetLast();
7076 Int_t firstBinY = fYaxis.GetFirst();
7077 Int_t lastBinY = fYaxis.GetLast();
7078 Int_t firstBinZ = fZaxis.GetFirst();
7079 Int_t lastBinZ = fZaxis.GetLast();
7080 // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7083 if (firstBinX == 1) firstBinX = 0;
7084 if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7085 }
7087 if (firstBinY == 1) firstBinY = 0;
7088 if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
7089 }
7091 if (firstBinZ == 1) firstBinZ = 0;
7092 if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
7093 }
7094 }
7095
7096 Double_t x = 0;
7097 Double_t sum=0;
7098 Double_t np=0;
7099 for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
7100 for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
7101 for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
7102 if (axis==1 ) x = fXaxis.GetBinCenter(binx);
7103 else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
7104 else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
7105 Double_t w = GetBinContent(binx,biny,binz);
7106 np+=w;
7107 sum+=w*(x-mean)*(x-mean)*(x-mean);
7108 }
7109 }
7110 }
7111 sum/=np*stddev3;
7112 return sum;
7113 }
7114 else if (axis > 10 && axis <= 13) {
7115 //compute standard error of skewness
7116 // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
7118 return ( neff > 0 ? TMath::Sqrt(6./neff ) : 0. );
7119 }
7120 else {
7121 Error("GetSkewness", "illegal value of parameter");
7122 return 0;
7123 }
7124}
7125
7126////////////////////////////////////////////////////////////////////////////////
7127/// - For axis =1, 2 or 3 returns kurtosis of the histogram along x, y or z axis.
7128/// Kurtosis(gaussian(0, 1)) = 0.
7129/// - For axis =11, 12 or 13 returns the approximate standard error of kurtosis
7130/// of the histogram along x, y or z axis
7131////
7132/// Note, that since third and fourth moment are not calculated
7133/// at the fill time, kurtosis and its standard error are computed bin by bin
7134
7136{
7137 if (axis > 0 && axis <= 3){
7138
7139 Double_t mean = GetMean(axis);
7140 Double_t stddev = GetStdDev(axis);
7141 Double_t stddev4 = stddev*stddev*stddev*stddev;
7142
7143 Int_t firstBinX = fXaxis.GetFirst();
7144 Int_t lastBinX = fXaxis.GetLast();
7145 Int_t firstBinY = fYaxis.GetFirst();
7146 Int_t lastBinY = fYaxis.GetLast();
7147 Int_t firstBinZ = fZaxis.GetFirst();
7148 Int_t lastBinZ = fZaxis.GetLast();
7149 // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7152 if (firstBinX == 1) firstBinX = 0;
7153 if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7154 }
7156 if (firstBinY == 1) firstBinY = 0;
7157 if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
7158 }
7160 if (firstBinZ == 1) firstBinZ = 0;
7161 if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
7162 }
7163 }
7164
7165 Double_t x = 0;
7166 Double_t sum=0;
7167 Double_t np=0;
7168 for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
7169 for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
7170 for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
7171 if (axis==1 ) x = fXaxis.GetBinCenter(binx);
7172 else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
7173 else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
7174 Double_t w = GetBinContent(binx,biny,binz);
7175 np+=w;
7176 sum+=w*(x-mean)*(x-mean)*(x-mean)*(x-mean);
7177 }
7178 }
7179 }
7180 sum/=(np*stddev4);
7181 return sum-3;
7182
7183 } else if (axis > 10 && axis <= 13) {
7184 //compute standard error of skewness
7185 // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
7187 return ( neff > 0 ? TMath::Sqrt(24./neff ) : 0. );
7188 }
7189 else {
7190 Error("GetKurtosis", "illegal value of parameter");
7191 return 0;
7192 }
7193}
7194
7195////////////////////////////////////////////////////////////////////////////////
7196/// fill the array stats from the contents of this histogram
7197/// The array stats must be correctly dimensioned in the calling program.
7198///
7199/// ~~~ {.cpp}
7200/// stats[0] = sumw
7201/// stats[1] = sumw2
7202/// stats[2] = sumwx
7203/// stats[3] = sumwx2
7204/// ~~~
7205///
7206/// If no axis-subrange is specified (via TAxis::SetRange), the array stats
7207/// is simply a copy of the statistics quantities computed at filling time.
7208/// If a sub-range is specified, the function recomputes these quantities
7209/// from the bin contents in the current axis range.
7210///
7211/// Note that the mean value/StdDev is computed using the bins in the currently
7212/// defined range (see TAxis::SetRange). By default the range includes
7213/// all bins from 1 to nbins included, excluding underflows and overflows.
7214/// To force the underflows and overflows in the computation, one must
7215/// call the static function TH1::StatOverflows(kTRUE) before filling
7216/// the histogram.
7217
7218void TH1::GetStats(Double_t *stats) const
7219{
7220 if (fBuffer) ((TH1*)this)->BufferEmpty();
7221
7222 // Loop on bins (possibly including underflows/overflows)
7223 Int_t bin, binx;
7224 Double_t w,err;
7225 Double_t x;
7226 // identify the case of labels with extension of axis range
7227 // in this case the statistics in x does not make any sense
7228 Bool_t labelHist = ((const_cast<TAxis&>(fXaxis)).GetLabels() && CanExtendAllAxes() );
7229 // fTsumw == 0 && fEntries > 0 is a special case when uses SetBinContent or calls ResetStats before
7230 if ((fTsumw == 0 && fEntries > 0) || ( fXaxis.TestBit(TAxis::kAxisRange) && !labelHist) ) {
7231 for (bin=0;bin<4;bin++) stats[bin] = 0;
7232
7233 Int_t firstBinX = fXaxis.GetFirst();
7234 Int_t lastBinX = fXaxis.GetLast();
7235 // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7237 if (firstBinX == 1) firstBinX = 0;
7238 if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7239 }
7240 for (binx = firstBinX; binx <= lastBinX; binx++) {
7241 x = fXaxis.GetBinCenter(binx);
7242 //w = TMath::Abs(RetrieveBinContent(binx));
7243 // not sure what to do here if w < 0
7244 w = RetrieveBinContent(binx);
7245 err = TMath::Abs(GetBinError(binx));
7246 stats[0] += w;
7247 stats[1] += err*err;
7248 // statistics in x makes sense only for not labels histograms
7249 if (!labelHist) {
7250 stats[2] += w*x;
7251 stats[3] += w*x*x;
7252 }
7253 }
7254 // if (stats[0] < 0) {
7255 // // in case total is negative do something ??
7256 // stats[0] = 0;
7257 // }
7258 } else {
7259 stats[0] = fTsumw;
7260 stats[1] = fTsumw2;
7261 stats[2] = fTsumwx;
7262 stats[3] = fTsumwx2;
7263 }
7264}
7265
7266////////////////////////////////////////////////////////////////////////////////
7267/// Replace current statistics with the values in array stats
7268
7269void TH1::PutStats(Double_t *stats)
7270{
7271 fTsumw = stats[0];
7272 fTsumw2 = stats[1];
7273 fTsumwx = stats[2];
7274 fTsumwx2 = stats[3];
7275}
7276
7277////////////////////////////////////////////////////////////////////////////////
7278/// Reset the statistics including the number of entries
7279/// and replace with values calculates from bin content
7280///
7281/// The number of entries is set to the total bin content or (in case of weighted histogram)
7282/// to number of effective entries
7283
7284void TH1::ResetStats()
7285{
7286 Double_t stats[kNstat] = {0};
7287 fTsumw = 0;
7288 fEntries = 1; // to force re-calculation of the statistics in TH1::GetStats
7289 GetStats(stats);
7290 PutStats(stats);
7292 // use effective entries for weighted histograms: (sum_w) ^2 / sum_w2
7293 if (fSumw2.fN > 0 && fTsumw > 0 && stats[1] > 0 ) fEntries = stats[0]*stats[0]/ stats[1];
7294}
7295
7296////////////////////////////////////////////////////////////////////////////////
7297/// Return the sum of weights excluding under/overflows.
7298
7300{
7301 if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
7302
7303 Int_t bin,binx,biny,binz;
7304 Double_t sum =0;
7305 for(binz=1; binz<=fZaxis.GetNbins(); binz++) {
7306 for(biny=1; biny<=fYaxis.GetNbins(); biny++) {
7307 for(binx=1; binx<=fXaxis.GetNbins(); binx++) {
7308 bin = GetBin(binx,biny,binz);
7309 sum += RetrieveBinContent(bin);
7310 }
7311 }
7312 }
7313 return sum;
7314}
7315
7316////////////////////////////////////////////////////////////////////////////////
7317///Return integral of bin contents. Only bins in the bins range are considered.
7318///
7319/// By default the integral is computed as the sum of bin contents in the range.
7320/// if option "width" is specified, the integral is the sum of
7321/// the bin contents multiplied by the bin width in x.
7322
7323Double_t TH1::Integral(Option_t *option) const
7324{
7325 return Integral(fXaxis.GetFirst(),fXaxis.GetLast(),option);
7326}
7327
7328////////////////////////////////////////////////////////////////////////////////
7329/// Return integral of bin contents in range [binx1,binx2].
7330///
7331/// By default the integral is computed as the sum of bin contents in the range.
7332/// if option "width" is specified, the integral is the sum of
7333/// the bin contents multiplied by the bin width in x.
7334
7335Double_t TH1::Integral(Int_t binx1, Int_t binx2, Option_t *option) const
7336{
7337 double err = 0;
7338 return DoIntegral(binx1,binx2,0,-1,0,-1,err,option);
7339}
7340
7341////////////////////////////////////////////////////////////////////////////////
7342/// Return integral of bin contents in range [binx1,binx2] and its error.
7343///
7344/// By default the integral is computed as the sum of bin contents in the range.
7345/// if option "width" is specified, the integral is the sum of
7346/// the bin contents multiplied by the bin width in x.
7347/// the error is computed using error propagation from the bin errors assuming that
7348/// all the bins are uncorrelated
7349
7350Double_t TH1::IntegralAndError(Int_t binx1, Int_t binx2, Double_t & error, Option_t *option) const
7351{
7352 return DoIntegral(binx1,binx2,0,-1,0,-1,error,option,kTRUE);
7353}
7354
7355////////////////////////////////////////////////////////////////////////////////
7356/// Internal function compute integral and optionally the error between the limits
7357/// specified by the bin number values working for all histograms (1D, 2D and 3D)
7358
7359Double_t TH1::DoIntegral(Int_t binx1, Int_t binx2, Int_t biny1, Int_t biny2, Int_t binz1, Int_t binz2, Double_t & error ,
7360 Option_t *option, Bool_t doError) const
7361{
7362 if (fBuffer) ((TH1*)this)->BufferEmpty();
7363
7364 Int_t nx = GetNbinsX() + 2;
7365 if (binx1 < 0) binx1 = 0;
7366 if (binx2 >= nx || binx2 < binx1) binx2 = nx - 1;
7367
7368 if (GetDimension() > 1) {
7369 Int_t ny = GetNbinsY() + 2;
7370 if (biny1 < 0) biny1 = 0;
7371 if (biny2 >= ny || biny2 < biny1) biny2 = ny - 1;
7372 } else {
7373 biny1 = 0; biny2 = 0;
7374 }
7375
7376 if (GetDimension() > 2) {
7377 Int_t nz = GetNbinsZ() + 2;
7378 if (binz1 < 0) binz1 = 0;
7379 if (binz2 >= nz || binz2 < binz1) binz2 = nz - 1;
7380 } else {
7381 binz1 = 0; binz2 = 0;
7382 }
7383
7384 // - Loop on bins in specified range
7385 TString opt = option;
7386 opt.ToLower();
7388 if (opt.Contains("width")) width = kTRUE;
7389
7390
7391 Double_t dx = 1., dy = .1, dz =.1;
7392 Double_t integral = 0;
7393 Double_t igerr2 = 0;
7394 for (Int_t binx = binx1; binx <= binx2; ++binx) {
7395 if (width) dx = fXaxis.GetBinWidth(binx);
7396 for (Int_t biny = biny1; biny <= biny2; ++biny) {
7397 if (width) dy = fYaxis.GetBinWidth(biny);
7398 for (Int_t binz = binz1; binz <= binz2; ++binz) {
7399 Int_t bin = GetBin(binx, biny, binz);
7400 Double_t dv = 0.0;
7401 if (width) {
7402 dz = fZaxis.GetBinWidth(binz);
7403 dv = dx * dy * dz;
7404 integral += RetrieveBinContent(bin) * dv;
7405 } else {
7406 integral += RetrieveBinContent(bin);
7407 }
7408 if (doError) {
7409 if (width) igerr2 += GetBinErrorSqUnchecked(bin) * dv * dv;
7410 else igerr2 += GetBinErrorSqUnchecked(bin);
7411 }
7412 }
7413 }
7414 }
7415
7416 if (doError) error = TMath::Sqrt(igerr2);
7417 return integral;
7418}
7419
7420////////////////////////////////////////////////////////////////////////////////
7421/// Statistical test of compatibility in shape between
7422/// this histogram and h2, using the Anderson-Darling 2 sample test.
7423///
7424/// The AD 2 sample test formula are derived from the paper
7425/// F.W Scholz, M.A. Stephens "k-Sample Anderson-Darling Test".
7426///
7427/// The test is implemented in root in the ROOT::Math::GoFTest class
7428/// It is the same formula ( (6) in the paper), and also shown in
7429/// [this preprint](http://arxiv.org/pdf/0804.0380v1.pdf)
7430///
7431/// Binned data are considered as un-binned data
7432/// with identical observation happening in the bin center.
7433///
7434/// \param[in] option is a character string to specify options
7435/// - "D" Put out a line of "Debug" printout
7436/// - "T" Return the normalized A-D test statistic
7437///
7438/// - Note1: Underflow and overflow are not considered in the test
7439/// - Note2: The test works only for un-weighted histogram (i.e. representing counts)
7440/// - Note3: The histograms are not required to have the same X axis
7441/// - Note4: The test works only for 1-dimensional histograms
7442
7443Double_t TH1::AndersonDarlingTest(const TH1 *h2, Option_t *option) const
7444{
7445 Double_t advalue = 0;
7446 Double_t pvalue = AndersonDarlingTest(h2, advalue);
7447
7448 TString opt = option;
7449 opt.ToUpper();
7450 if (opt.Contains("D") ) {
7451 printf(" AndersonDarlingTest Prob = %g, AD TestStatistic = %g\n",pvalue,advalue);
7452 }
7453 if (opt.Contains("T") ) return advalue;
7454
7455 return pvalue;
7456}
7457
7458////////////////////////////////////////////////////////////////////////////////
7459/// Same function as above but returning also the test statistic value
7460
7461Double_t TH1::AndersonDarlingTest(const TH1 *h2, Double_t & advalue) const
7462{
7463 if (GetDimension() != 1 || h2->GetDimension() != 1) {
7464 Error("AndersonDarlingTest","Histograms must be 1-D");
7465 return -1;
7466 }
7467
7468 // empty the buffer. Probably we could add as an unbinned test
7469 if (fBuffer) ((TH1*)this)->BufferEmpty();
7470
7471 // use the BinData class
7472 ROOT::Fit::BinData data1;
7473 ROOT::Fit::BinData data2;
7474
7475 ROOT::Fit::FillData(data1, this, 0);
7476 ROOT::Fit::FillData(data2, h2, 0);
7477
7478 double pvalue;
7479 ROOT::Math::GoFTest::AndersonDarling2SamplesTest(data1,data2, pvalue,advalue);
7480
7481 return pvalue;
7482}
7483
7484////////////////////////////////////////////////////////////////////////////////
7485/// Statistical test of compatibility in shape between
7486/// this histogram and h2, using Kolmogorov test.
7487/// Note that the KolmogorovTest (KS) test should in theory be used only for unbinned data
7488/// and not for binned data as in the case of the histogram (see NOTE 3 below).
7489/// So, before using this method blindly, read the NOTE 3.
7490///
7491/// Default: Ignore under- and overflow bins in comparison
7492///
7493/// \param[in] h2 histogram
7494/// \param[in] option is a character string to specify options
7495/// - "U" include Underflows in test (also for 2-dim)
7496/// - "O" include Overflows (also valid for 2-dim)
7497/// - "N" include comparison of normalizations
7498/// - "D" Put out a line of "Debug" printout
7499/// - "M" Return the Maximum Kolmogorov distance instead of prob
7500/// - "X" Run the pseudo experiments post-processor with the following procedure:
7501/// make pseudoexperiments based on random values from the parent distribution,
7502/// compare the KS distance of the pseudoexperiment to the parent
7503/// distribution, and count all the KS values above the value
7504/// obtained from the original data to Monte Carlo distribution.
7505/// The number of pseudo-experiments nEXPT is currently fixed at 1000.
7506/// The function returns the probability.
7507/// (thanks to Ben Kilminster to submit this procedure). Note that
7508/// this option "X" is much slower.
7509///
7510/// The returned function value is the probability of test
7511/// (much less than one means NOT compatible)
7512///
7513/// Code adapted by Rene Brun from original HBOOK routine HDIFF
7514///
7515/// NOTE1
7516/// A good description of the Kolmogorov test can be seen at:
7517/// http://www.itl.nist.gov/div898/handbook/eda/section3/eda35g.htm
7518///
7519/// NOTE2
7520/// see also alternative function TH1::Chi2Test
7521/// The Kolmogorov test is assumed to give better results than Chi2Test
7522/// in case of histograms with low statistics.
7523///
7524/// NOTE3 (Jan Conrad, Fred James)
7525/// "The returned value PROB is calculated such that it will be
7526/// uniformly distributed between zero and one for compatible histograms,
7527/// provided the data are not binned (or the number of bins is very large
7528/// compared with the number of events). Users who have access to unbinned
7529/// data and wish exact confidence levels should therefore not put their data
7530/// into histograms, but should call directly TMath::KolmogorovTest. On
7531/// the other hand, since TH1 is a convenient way of collecting data and
7532/// saving space, this function has been provided. However, the values of
7533/// PROB for binned data will be shifted slightly higher than expected,
7534/// depending on the effects of the binning. For example, when comparing two
7535/// uniform distributions of 500 events in 100 bins, the values of PROB,
7536/// instead of being exactly uniformly distributed between zero and one, have
7537/// a mean value of about 0.56. We can apply a useful
7538/// rule: As long as the bin width is small compared with any significant
7539/// physical effect (for example the experimental resolution) then the binning
7540/// cannot have an important effect. Therefore, we believe that for all
7541/// practical purposes, the probability value PROB is calculated correctly
7542/// provided the user is aware that:
7543///
7544/// 1. The value of PROB should not be expected to have exactly the correct
7545/// distribution for binned data.
7546/// 2. The user is responsible for seeing to it that the bin widths are
7547/// small compared with any physical phenomena of interest.
7548/// 3. The effect of binning (if any) is always to make the value of PROB
7549/// slightly too big. That is, setting an acceptance criterion of (PROB>0.05
7550/// will assure that at most 5% of truly compatible histograms are rejected,
7551/// and usually somewhat less."
7552///
7553/// Note also that for GoF test of unbinned data ROOT provides also the class
7554/// ROOT::Math::GoFTest. The class has also method for doing one sample tests
7555/// (i.e. comparing the data with a given distribution).
7556
7557Double_t TH1::KolmogorovTest(const TH1 *h2, Option_t *option) const
7558{
7559 TString opt = option;
7560 opt.ToUpper();
7561
7562 Double_t prob = 0;
7563 TH1 *h1 = (TH1*)this;
7564 if (h2 == 0) return 0;
7565 const TAxis *axis1 = h1->GetXaxis();
7566 const TAxis *axis2 = h2->GetXaxis();
7567 Int_t ncx1 = axis1->GetNbins();
7568 Int_t ncx2 = axis2->GetNbins();
7569
7570 // Check consistency of dimensions
7571 if (h1->GetDimension() != 1 || h2->GetDimension() != 1) {
7572 Error("KolmogorovTest","Histograms must be 1-D\n");
7573 return 0;
7574 }
7575
7576 // Check consistency in number of channels
7577 if (ncx1 != ncx2) {
7578 Error("KolmogorovTest","Histograms have different number of bins, %d and %d\n",ncx1,ncx2);
7579 return 0;
7580 }
7581
7582 // empty the buffer. Probably we could add as an unbinned test
7583 if (fBuffer) ((TH1*)this)->BufferEmpty();
7584
7585 // Check consistency in bin edges
7586 for(Int_t i = 1; i <= axis1->GetNbins() + 1; ++i) {
7587 if(!TMath::AreEqualRel(axis1->GetBinLowEdge(i), axis2->GetBinLowEdge(i), 1.E-15)) {
7588 Error("KolmogorovTest","Histograms are not consistent: they have different bin edges");
7589 return 0;
7590 }
7591 }
7592
7593 Bool_t afunc1 = kFALSE;
7594 Bool_t afunc2 = kFALSE;
7595 Double_t sum1 = 0, sum2 = 0;
7596 Double_t ew1, ew2, w1 = 0, w2 = 0;
7597 Int_t bin;
7598 Int_t ifirst = 1;
7599 Int_t ilast = ncx1;
7600 // integral of all bins (use underflow/overflow if option)
7601 if (opt.Contains("U")) ifirst = 0;
7602 if (opt.Contains("O")) ilast = ncx1 +1;
7603 for (bin = ifirst; bin <= ilast; bin++) {
7604 sum1 += h1->RetrieveBinContent(bin);
7605 sum2 += h2->RetrieveBinContent(bin);
7606 ew1 = h1->GetBinError(bin);
7607 ew2 = h2->GetBinError(bin);
7608 w1 += ew1*ew1;
7609 w2 += ew2*ew2;
7610 }
7611 if (sum1 == 0) {
7612 Error("KolmogorovTest","Histogram1 %s integral is zero\n",h1->GetName());
7613 return 0;
7614 }
7615 if (sum2 == 0) {
7616 Error("KolmogorovTest","Histogram2 %s integral is zero\n",h2->GetName());
7617 return 0;
7618 }
7619
7620 // calculate the effective entries.
7621 // the case when errors are zero (w1 == 0 or w2 ==0) are equivalent to
7622 // compare to a function. In that case the rescaling is done only on sqrt(esum2) or sqrt(esum1)
7623 Double_t esum1 = 0, esum2 = 0;
7624 if (w1 > 0)
7625 esum1 = sum1 * sum1 / w1;
7626 else
7627 afunc1 = kTRUE; // use later for calculating z
7628
7629 if (w2 > 0)
7630 esum2 = sum2 * sum2 / w2;
7631 else
7632 afunc2 = kTRUE; // use later for calculating z
7633
7634 if (afunc2 && afunc1) {
7635 Error("KolmogorovTest","Errors are zero for both histograms\n");
7636 return 0;
7637 }
7638
7639
7640 Double_t s1 = 1/sum1;
7641 Double_t s2 = 1/sum2;
7642
7643 // Find largest difference for Kolmogorov Test
7644 Double_t dfmax =0, rsum1 = 0, rsum2 = 0;
7645
7646 for (bin=ifirst;bin<=ilast;bin++) {
7647 rsum1 += s1*h1->RetrieveBinContent(bin);
7648 rsum2 += s2*h2->RetrieveBinContent(bin);
7649 dfmax = TMath::Max(dfmax,TMath::Abs(rsum1-rsum2));
7650 }
7651
7652 // Get Kolmogorov probability
7653 Double_t z, prb1=0, prb2=0, prb3=0;
7654
7655 // case h1 is exact (has zero errors)
7656 if (afunc1)
7657 z = dfmax*TMath::Sqrt(esum2);
7658 // case h2 has zero errors
7659 else if (afunc2)
7660 z = dfmax*TMath::Sqrt(esum1);
7661 else
7662 // for comparison between two data sets
7663 z = dfmax*TMath::Sqrt(esum1*esum2/(esum1+esum2));
7664
7665 prob = TMath::KolmogorovProb(z);
7666
7667 // option N to combine normalization makes sense if both afunc1 and afunc2 are false
7668 if (opt.Contains("N") && !(afunc1 || afunc2 ) ) {
7669 // Combine probabilities for shape and normalization,
7670 prb1 = prob;
7671 Double_t d12 = esum1-esum2;
7672 Double_t chi2 = d12*d12/(esum1+esum2);
7673 prb2 = TMath::Prob(chi2,1);
7674 // see Eadie et al., section 11.6.2
7675 if (prob > 0 && prb2 > 0) prob *= prb2*(1-TMath::Log(prob*prb2));
7676 else prob = 0;
7677 }
7678 // X option. Pseudo-experiments post-processor to determine KS probability
7679 const Int_t nEXPT = 1000;
7680 if (opt.Contains("X") && !(afunc1 || afunc2 ) ) {
7681 Double_t dSEXPT;
7682 TH1 *h1_cpy = (TH1 *)(gDirectory ? gDirectory->CloneObject(this, kFALSE) : gROOT->CloneObject(this, kFALSE));
7683 TH1 *hExpt = (TH1*)(gDirectory ? gDirectory->CloneObject(this,kFALSE) : gROOT->CloneObject(this,kFALSE));
7684
7685 if (h1_cpy->GetMinimum() < 0.0) {
7686 // With negative bins we can't draw random samples in a meaningful way.
7687 Warning("KolmogorovTest", "Detected bins with negative weights, these have been ignored and output might be "
7688 "skewed. Reduce number of bins for histogram?");
7689 while (h1_cpy->GetMinimum() < 0.0) {
7690 Int_t idx = h1_cpy->GetMinimumBin();
7691 h1_cpy->SetBinContent(idx, 0.0);
7692 }
7693 }
7694
7695 // make nEXPT experiments (this should be a parameter)
7696 prb3 = 0;
7697 for (Int_t i=0; i < nEXPT; i++) {
7698 hExpt->Reset();
7699 hExpt->FillRandom(h1_cpy, (Int_t)esum2);
7700 dSEXPT = KolmogorovTest(hExpt,"M");
7701 if (dSEXPT>dfmax) prb3 += 1.0;
7702 }
7703 prb3 /= (Double_t)nEXPT;
7704 delete h1_cpy;
7705 delete hExpt;
7706 }
7707
7708 // debug printout
7709 if (opt.Contains("D")) {
7710 printf(" Kolmo Prob h1 = %s, sum bin content =%g effective entries =%g\n",h1->GetName(),sum1,esum1);
7711 printf(" Kolmo Prob h2 = %s, sum bin content =%g effective entries =%g\n",h2->GetName(),sum2,esum2);
7712 printf(" Kolmo Prob = %g, Max Dist = %g\n",prob,dfmax);
7713 if (opt.Contains("N"))
7714 printf(" Kolmo Prob = %f for shape alone, =%f for normalisation alone\n",prb1,prb2);
7715 if (opt.Contains("X"))
7716 printf(" Kolmo Prob = %f with %d pseudo-experiments\n",prb3,nEXPT);
7717 }
7718 // This numerical error condition should never occur:
7719 if (TMath::Abs(rsum1-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h1=%s\n",h1->GetName());
7720 if (TMath::Abs(rsum2-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h2=%s\n",h2->GetName());
7721
7722 if(opt.Contains("M")) return dfmax;
7723 else if(opt.Contains("X")) return prb3;
7724 else return prob;
7725}
7726
7727////////////////////////////////////////////////////////////////////////////////
7728/// Replace bin contents by the contents of array content
7729
7730void TH1::SetContent(const Double_t *content)
7731{
7732 fEntries = fNcells;
7733 fTsumw = 0;
7734 for (Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, content[i]);
7735}
7736
7737////////////////////////////////////////////////////////////////////////////////
7738/// Return contour values into array levels if pointer levels is non zero.
7739///
7740/// The function returns the number of contour levels.
7741/// see GetContourLevel to return one contour only
7742
7744{
7745 Int_t nlevels = fContour.fN;
7746 if (levels) {
7747 if (nlevels == 0) {
7748 nlevels = 20;
7749 SetContour(nlevels);
7750 } else {
7751 if (TestBit(kUserContour) == 0) SetContour(nlevels);
7752 }
7753 for (Int_t level=0; level<nlevels; level++) levels[level] = fContour.fArray[level];
7754 }
7755 return nlevels;
7756}
7757
7758////////////////////////////////////////////////////////////////////////////////
7759/// Return value of contour number level.
7760/// Use GetContour to return the array of all contour levels
7761
7763{
7764 return (level >= 0 && level < fContour.fN) ? fContour.fArray[level] : 0.0;
7765}
7766
7767////////////////////////////////////////////////////////////////////////////////
7768/// Return the value of contour number "level" in Pad coordinates.
7769/// ie: if the Pad is in log scale along Z it returns le log of the contour level
7770/// value. See GetContour to return the array of all contour levels
7771
7773{
7774 if (level <0 || level >= fContour.fN) return 0;
7775 Double_t zlevel = fContour.fArray[level];
7776
7777 // In case of user defined contours and Pad in log scale along Z,
7778 // fContour.fArray doesn't contain the log of the contour whereas it does
7779 // in case of equidistant contours.
7780 if (gPad && gPad->GetLogz() && TestBit(kUserContour)) {
7781 if (zlevel <= 0) return 0;
7782 zlevel = TMath::Log10(zlevel);
7783 }
7784 return zlevel;
7785}
7786
7787////////////////////////////////////////////////////////////////////////////////
7788/// Set the maximum number of entries to be kept in the buffer.
7789
7790void TH1::SetBuffer(Int_t buffersize, Option_t * /*option*/)
7791{
7792 if (fBuffer) {
7793 BufferEmpty();
7794 delete [] fBuffer;
7795 fBuffer = 0;
7796 }
7797 if (buffersize <= 0) {
7798 fBufferSize = 0;
7799 return;
7800 }
7801 if (buffersize < 100) buffersize = 100;
7802 fBufferSize = 1 + buffersize*(fDimension+1);
7804 memset(fBuffer,0,sizeof(Double_t)*fBufferSize);
7805}
7806
7807////////////////////////////////////////////////////////////////////////////////
7808/// Set the number and values of contour levels.
7809///
7810/// By default the number of contour levels is set to 20. The contours values
7811/// in the array "levels" should be specified in increasing order.
7812///
7813/// if argument levels = 0 or missing, equidistant contours are computed
7814
7815void TH1::SetContour(Int_t nlevels, const Double_t *levels)
7816{
7817 Int_t level;
7819 if (nlevels <=0 ) {
7820 fContour.Set(0);
7821 return;
7822 }
7823 fContour.Set(nlevels);
7824
7825 // - Contour levels are specified
7826 if (levels) {
7828 for (level=0; level<nlevels; level++) fContour.fArray[level] = levels[level];
7829 } else {
7830 // - contour levels are computed automatically as equidistant contours
7831 Double_t zmin = GetMinimum();
7832 Double_t zmax = GetMaximum();
7833 if ((zmin == zmax) && (zmin != 0)) {
7834 zmax += 0.01*TMath::Abs(zmax);
7835 zmin -= 0.01*TMath::Abs(zmin);
7836 }
7837 Double_t dz = (zmax-zmin)/Double_t(nlevels);
7838 if (gPad && gPad->GetLogz()) {
7839 if (zmax <= 0) return;
7840 if (zmin <= 0) zmin = 0.001*zmax;
7841 zmin = TMath::Log10(zmin);
7842 zmax = TMath::Log10(zmax);
7843 dz = (zmax-zmin)/Double_t(nlevels);
7844 }
7845 for (level=0; level<nlevels; level++) {
7846 fContour.fArray[level] = zmin + dz*Double_t(level);
7847 }
7848 }
7849}
7850
7851////////////////////////////////////////////////////////////////////////////////
7852/// Set value for one contour level.
7853
7854void TH1::SetContourLevel(Int_t level, Double_t value)
7855{
7856 if (level < 0 || level >= fContour.fN) return;
7858 fContour.fArray[level] = value;
7859}
7860
7861////////////////////////////////////////////////////////////////////////////////
7862/// Return maximum value smaller than maxval of bins in the range,
7863/// unless the value has been overridden by TH1::SetMaximum,
7864/// in which case it returns that value. (This happens, for example,
7865/// when the histogram is drawn and the y or z axis limits are changed
7866///
7867/// To get the maximum value of bins in the histogram regardless of
7868/// whether the value has been overridden, use
7869///
7870/// ~~~ {.cpp}
7871/// h->GetBinContent(h->GetMaximumBin())
7872/// ~~~
7873
7874Double_t TH1::GetMaximum(Double_t maxval) const
7875{
7876 if (fMaximum != -1111) return fMaximum;
7877
7878 // empty the buffer
7879 if (fBuffer) ((TH1*)this)->BufferEmpty();
7880
7881 Int_t bin, binx, biny, binz;
7882 Int_t xfirst = fXaxis.GetFirst();
7883 Int_t xlast = fXaxis.GetLast();
7884 Int_t yfirst = fYaxis.GetFirst();
7885 Int_t ylast = fYaxis.GetLast();
7886 Int_t zfirst = fZaxis.GetFirst();
7887 Int_t zlast = fZaxis.GetLast();
7888 Double_t maximum = -FLT_MAX, value;
7889 for (binz=zfirst;binz<=zlast;binz++) {
7890 for (biny=yfirst;biny<=ylast;biny++) {
7891 for (binx=xfirst;binx<=xlast;binx++) {
7892 bin = GetBin(binx,biny,binz);
7893 value = RetrieveBinContent(bin);
7894 if (value > maximum && value < maxval) maximum = value;
7895 }
7896 }
7897 }
7898 return maximum;
7899}
7900
7901////////////////////////////////////////////////////////////////////////////////
7902/// Return location of bin with maximum value in the range.
7903
7905{
7906 Int_t locmax, locmay, locmaz;
7907 return GetMaximumBin(locmax, locmay, locmaz);
7908}
7909
7910////////////////////////////////////////////////////////////////////////////////
7911/// Return location of bin with maximum value in the range.
7912
7913Int_t TH1::GetMaximumBin(Int_t &locmax, Int_t &locmay, Int_t &locmaz) const
7914{
7915 // empty the buffer
7916 if (fBuffer) ((TH1*)this)->BufferEmpty();
7917
7918 Int_t bin, binx, biny, binz;
7919 Int_t locm;
7920 Int_t xfirst = fXaxis.GetFirst();
7921 Int_t xlast = fXaxis.GetLast();
7922 Int_t yfirst = fYaxis.GetFirst();
7923 Int_t ylast = fYaxis.GetLast();
7924 Int_t zfirst = fZaxis.GetFirst();
7925 Int_t zlast = fZaxis.GetLast();
7926 Double_t maximum = -FLT_MAX, value;
7927 locm = locmax = locmay = locmaz = 0;
7928 for (binz=zfirst;binz<=zlast;binz++) {
7929 for (biny=yfirst;biny<=ylast;biny++) {
7930 for (binx=xfirst;binx<=xlast;binx++) {
7931 bin = GetBin(binx,biny,binz);
7932 value = RetrieveBinContent(bin);
7933 if (value > maximum) {
7934 maximum = value;
7935 locm = bin;
7936 locmax = binx;
7937 locmay = biny;
7938 locmaz = binz;
7939 }
7940 }
7941 }
7942 }
7943 return locm;
7944}
7945
7946////////////////////////////////////////////////////////////////////////////////
7947/// Return minimum value larger than minval of bins in the range,
7948/// unless the value has been overridden by TH1::SetMinimum,
7949/// in which case it returns that value. (This happens, for example,
7950/// when the histogram is drawn and the y or z axis limits are changed
7951///
7952/// To get the minimum value of bins in the histogram regardless of
7953/// whether the value has been overridden, use
7954///
7955/// ~~~ {.cpp}
7956/// h->GetBinContent(h->GetMinimumBin())
7957/// ~~~
7958
7959Double_t TH1::GetMinimum(Double_t minval) const
7960{
7961 if (fMinimum != -1111) return fMinimum;
7962
7963 // empty the buffer
7964 if (fBuffer) ((TH1*)this)->BufferEmpty();
7965
7966 Int_t bin, binx, biny, binz;
7967 Int_t xfirst = fXaxis.GetFirst();
7968 Int_t xlast = fXaxis.GetLast();
7969 Int_t yfirst = fYaxis.GetFirst();
7970 Int_t ylast = fYaxis.GetLast();
7971 Int_t zfirst = fZaxis.GetFirst();
7972 Int_t zlast = fZaxis.GetLast();
7973 Double_t minimum=FLT_MAX, value;
7974 for (binz=zfirst;binz<=zlast;binz++) {
7975 for (biny=yfirst;biny<=ylast;biny++) {
7976 for (binx=xfirst;binx<=xlast;binx++) {
7977 bin = GetBin(binx,biny,binz);
7978 value = RetrieveBinContent(bin);
7979 if (value < minimum && value > minval) minimum = value;
7980 }
7981 }
7982 }
7983 return minimum;
7984}
7985
7986////////////////////////////////////////////////////////////////////////////////
7987/// Return location of bin with minimum value in the range.
7988
7990{
7991 Int_t locmix, locmiy, locmiz;
7992 return GetMinimumBin(locmix, locmiy, locmiz);
7993}
7994
7995////////////////////////////////////////////////////////////////////////////////
7996/// Return location of bin with minimum value in the range.
7997
7998Int_t TH1::GetMinimumBin(Int_t &locmix, Int_t &locmiy, Int_t &locmiz) const
7999{
8000 // empty the buffer
8001 if (fBuffer) ((TH1*)this)->BufferEmpty();
8002
8003 Int_t bin, binx, biny, binz;
8004 Int_t locm;
8005 Int_t xfirst = fXaxis.GetFirst();
8006 Int_t xlast = fXaxis.GetLast();
8007 Int_t yfirst = fYaxis.GetFirst();
8008 Int_t ylast = fYaxis.GetLast();
8009 Int_t zfirst = fZaxis.GetFirst();
8010 Int_t zlast = fZaxis.GetLast();
8011 Double_t minimum = FLT_MAX, value;
8012 locm = locmix = locmiy = locmiz = 0;
8013 for (binz=zfirst;binz<=zlast;binz++) {
8014 for (biny=yfirst;biny<=ylast;biny++) {
8015 for (binx=xfirst;binx<=xlast;binx++) {
8016 bin = GetBin(binx,biny,binz);
8017 value = RetrieveBinContent(bin);
8018 if (value < minimum) {
8019 minimum = value;
8020 locm = bin;
8021 locmix = binx;
8022 locmiy = biny;
8023 locmiz = binz;
8024 }
8025 }
8026 }
8027 }
8028 return locm;
8029}
8030
8031///////////////////////////////////////////////////////////////////////////////
8032/// Retrieve the minimum and maximum values in the histogram
8033///
8034/// This will not return a cached value and will always search the
8035/// histogram for the min and max values. The user can condition whether
8036/// or not to call this with the GetMinimumStored() and GetMaximumStored()
8037/// methods. If the cache is empty, then the value will be -1111. Users
8038/// can then use the SetMinimum() or SetMaximum() methods to cache the results.
8039/// For example, the following recipe will make efficient use of this method
8040/// and the cached minimum and maximum values.
8041//
8042/// \code{.cpp}
8043/// Double_t currentMin = pHist->GetMinimumStored();
8044/// Double_t currentMax = pHist->GetMaximumStored();
8045/// if ((currentMin == -1111) || (currentMax == -1111)) {
8046/// pHist->GetMinimumAndMaximum(currentMin, currentMax);
8047/// pHist->SetMinimum(currentMin);
8048/// pHist->SetMaximum(currentMax);
8049/// }
8050/// \endcode
8051///
8052/// \param min reference to variable that will hold found minimum value
8053/// \param max reference to variable that will hold found maximum value
8054
8055void TH1::GetMinimumAndMaximum(Double_t& min, Double_t& max) const
8056{
8057 // empty the buffer
8058 if (fBuffer) ((TH1*)this)->BufferEmpty();
8059
8060 Int_t bin, binx, biny, binz;
8061 Int_t xfirst = fXaxis.GetFirst();
8062 Int_t xlast = fXaxis.GetLast();
8063 Int_t yfirst = fYaxis.GetFirst();
8064 Int_t ylast = fYaxis.GetLast();
8065 Int_t zfirst = fZaxis.GetFirst();
8066 Int_t zlast = fZaxis.GetLast();
8067 min=TMath::Infinity();
8068 max=-TMath::Infinity();
8069 Double_t value;
8070 for (binz=zfirst;binz<=zlast;binz++) {
8071 for (biny=yfirst;biny<=ylast;biny++) {
8072 for (binx=xfirst;binx<=xlast;binx++) {
8073 bin = GetBin(binx,biny,binz);
8074 value = RetrieveBinContent(bin);
8075 if (value < min) min = value;
8076 if (value > max) max = value;
8077 }
8078 }
8079 }
8080}
8081
8082////////////////////////////////////////////////////////////////////////////////
8083/// Redefine x axis parameters.
8084///
8085/// The X axis parameters are modified.
8086/// The bins content array is resized
8087/// if errors (Sumw2) the errors array is resized
8088/// The previous bin contents are lost
8089/// To change only the axis limits, see TAxis::SetRange
8090
8092{
8093 if (GetDimension() != 1) {
8094 Error("SetBins","Operation only valid for 1-d histograms");
8095 return;
8096 }
8097 fXaxis.SetRange(0,0);
8098 fXaxis.Set(nx,xmin,xmax);
8099 fYaxis.Set(1,0,1);
8100 fZaxis.Set(1,0,1);
8101 fNcells = nx+2;
8103 if (fSumw2.fN) {
8105 }
8106}
8107
8108////////////////////////////////////////////////////////////////////////////////
8109/// Redefine x axis parameters with variable bin sizes.
8110///
8111/// The X axis parameters are modified.
8112/// The bins content array is resized
8113/// if errors (Sumw2) the errors array is resized
8114/// The previous bin contents are lost
8115/// To change only the axis limits, see TAxis::SetRange
8116/// xBins is supposed to be of length nx+1
8117
8118void TH1::SetBins(Int_t nx, const Double_t *xBins)
8119{
8120 if (GetDimension() != 1) {
8121 Error("SetBins","Operation only valid for 1-d histograms");
8122 return;
8123 }
8124 fXaxis.SetRange(0,0);
8125 fXaxis.Set(nx,xBins);
8126 fYaxis.Set(1,0,1);
8127 fZaxis.Set(1,0,1);
8128 fNcells = nx+2;
8130 if (fSumw2.fN) {
8132 }
8133}
8134
8135////////////////////////////////////////////////////////////////////////////////
8136/// Redefine x and y axis parameters.
8137///
8138/// The X and Y axis parameters are modified.
8139/// The bins content array is resized
8140/// if errors (Sumw2) the errors array is resized
8141/// The previous bin contents are lost
8142/// To change only the axis limits, see TAxis::SetRange
8143
8145{
8146 if (GetDimension() != 2) {
8147 Error("SetBins","Operation only valid for 2-D histograms");
8148 return;
8149 }
8150 fXaxis.SetRange(0,0);
8151 fYaxis.SetRange(0,0);
8152 fXaxis.Set(nx,xmin,xmax);
8153 fYaxis.Set(ny,ymin,ymax);
8154 fZaxis.Set(1,0,1);
8155 fNcells = (nx+2)*(ny+2);
8157 if (fSumw2.fN) {
8159 }
8160}
8161
8162////////////////////////////////////////////////////////////////////////////////
8163/// Redefine x and y axis parameters with variable bin sizes.
8164///
8165/// The X and Y axis parameters are modified.
8166/// The bins content array is resized
8167/// if errors (Sumw2) the errors array is resized
8168/// The previous bin contents are lost
8169/// To change only the axis limits, see TAxis::SetRange
8170/// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1
8171
8172void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins)
8173{
8174 if (GetDimension() != 2) {
8175 Error("SetBins","Operation only valid for 2-D histograms");
8176 return;
8177 }
8178 fXaxis.SetRange(0,0);
8179 fYaxis.SetRange(0,0);
8180 fXaxis.Set(nx,xBins);
8181 fYaxis.Set(ny,yBins);
8182 fZaxis.Set(1,0,1);
8183 fNcells = (nx+2)*(ny+2);
8185 if (fSumw2.fN) {
8187 }
8188}
8189
8190////////////////////////////////////////////////////////////////////////////////
8191/// Redefine x, y and z axis parameters.
8192///
8193/// The X, Y and Z axis parameters are modified.
8194/// The bins content array is resized
8195/// if errors (Sumw2) the errors array is resized
8196/// The previous bin contents are lost
8197/// To change only the axis limits, see TAxis::SetRange
8198
8200{
8201 if (GetDimension() != 3) {
8202 Error("SetBins","Operation only valid for 3-D histograms");
8203 return;
8204 }
8205 fXaxis.SetRange(0,0);
8206 fYaxis.SetRange(0,0);
8207 fZaxis.SetRange(0,0);
8208 fXaxis.Set(nx,xmin,xmax);
8209 fYaxis.Set(ny,ymin,ymax);
8210 fZaxis.Set(nz,zmin,zmax);
8211 fNcells = (nx+2)*(ny+2)*(nz+2);
8213 if (fSumw2.fN) {
8215 }
8216}
8217
8218////////////////////////////////////////////////////////////////////////////////
8219/// Redefine x, y and z axis parameters with variable bin sizes.
8220///
8221/// The X, Y and Z axis parameters are modified.
8222/// The bins content array is resized
8223/// if errors (Sumw2) the errors array is resized
8224/// The previous bin contents are lost
8225/// To change only the axis limits, see TAxis::SetRange
8226/// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1,
8227/// zBins is supposed to be of length nz+1
8228
8229void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins, Int_t nz, const Double_t *zBins)
8230{
8231 if (GetDimension() != 3) {
8232 Error("SetBins","Operation only valid for 3-D histograms");
8233 return;
8234 }
8235 fXaxis.SetRange(0,0);
8236 fYaxis.SetRange(0,0);
8237 fZaxis.SetRange(0,0);
8238 fXaxis.Set(nx,xBins);
8239 fYaxis.Set(ny,yBins);
8240 fZaxis.Set(nz,zBins);
8241 fNcells = (nx+2)*(ny+2)*(nz+2);
8243 if (fSumw2.fN) {
8245 }
8246}
8247
8248////////////////////////////////////////////////////////////////////////////////
8249/// By default when an histogram is created, it is added to the list
8250/// of histogram objects in the current directory in memory.
8251/// Remove reference to this histogram from current directory and add
8252/// reference to new directory dir. dir can be 0 in which case the
8253/// histogram does not belong to any directory.
8254///
8255/// Note that the directory is not a real property of the histogram and
8256/// it will not be copied when the histogram is copied or cloned.
8257/// If the user wants to have the copied (cloned) histogram in the same
8258/// directory, he needs to set again the directory using SetDirectory to the
8259/// copied histograms
8260
8262{
8263 if (fDirectory == dir) return;
8264 if (fDirectory) fDirectory->Remove(this);
8265 fDirectory = dir;
8266 if (fDirectory) {
8268 fDirectory->Append(this);
8269 }
8270}
8271
8272////////////////////////////////////////////////////////////////////////////////
8273/// Replace bin errors by values in array error.
8274
8275void TH1::SetError(const Double_t *error)
8276{
8277 for (Int_t i = 0; i < fNcells; ++i) SetBinError(i, error[i]);
8278}
8279
8280////////////////////////////////////////////////////////////////////////////////
8281/// Change the name of this histogram
8283
8284void TH1::SetName(const char *name)
8285{
8286 // Histograms are named objects in a THashList.
8287 // We must update the hashlist if we change the name
8288 // We protect this operation
8290 if (fDirectory) fDirectory->Remove(this);
8291 fName = name;
8292 if (fDirectory) fDirectory->Append(this);
8293}
8294
8295////////////////////////////////////////////////////////////////////////////////
8296/// Change the name and title of this histogram
8297
8298void TH1::SetNameTitle(const char *name, const char *title)
8299{
8300 // Histograms are named objects in a THashList.
8301 // We must update the hashlist if we change the name
8302 SetName(name);
8303 SetTitle(title);
8304}
8305
8306////////////////////////////////////////////////////////////////////////////////
8307/// Set statistics option on/off
8308///
8309/// By default, the statistics box is drawn.
8310/// The paint options can be selected via gStyle->SetOptStats.
8311/// This function sets/resets the kNoStats bin in the histogram object.
8312/// It has priority over the Style option.
8313
8314void TH1::SetStats(Bool_t stats)
8315{
8317 if (!stats) {
8319 //remove the "stats" object from the list of functions
8320 if (fFunctions) {
8321 TObject *obj = fFunctions->FindObject("stats");
8322 if (obj) {
8323 fFunctions->Remove(obj);
8324 delete obj;
8325 }
8326 }
8327 }
8328}
8329
8330////////////////////////////////////////////////////////////////////////////////
8331/// Create structure to store sum of squares of weights.
8332///
8333/// if histogram is already filled, the sum of squares of weights
8334/// is filled with the existing bin contents
8335///
8336/// The error per bin will be computed as sqrt(sum of squares of weight)
8337/// for each bin.
8338///
8339/// This function is automatically called when the histogram is created
8340/// if the static function TH1::SetDefaultSumw2 has been called before.
8341/// If flag = false the structure is deleted
8342
8343void TH1::Sumw2(Bool_t flag)
8344{
8345 if (!flag) {
8346 // clear the array if existing - do nothing otherwise
8347 if (fSumw2.fN > 0 ) fSumw2.Set(0);
8348 return;
8349 }
8350
8351 if (fSumw2.fN == fNcells) {
8352 if (!fgDefaultSumw2 )
8353 Warning("Sumw2","Sum of squares of weights structure already created");
8354 return;
8355 }
8356
8358
8359 // empty the buffer
8360 if (fBuffer) BufferEmpty();
8361
8362 if (fEntries > 0)
8363 for (Int_t i = 0; i < fNcells; ++i)
8365}
8366
8367////////////////////////////////////////////////////////////////////////////////
8368/// Return pointer to function with name.
8369///
8370///
8371/// Functions such as TH1::Fit store the fitted function in the list of
8372/// functions of this histogram.
8373
8374TF1 *TH1::GetFunction(const char *name) const
8375{
8376 return (TF1*)fFunctions->FindObject(name);
8377}
8378
8379////////////////////////////////////////////////////////////////////////////////
8380/// Return value of error associated to bin number bin.
8381///
8382/// if the sum of squares of weights has been defined (via Sumw2),
8383/// this function returns the sqrt(sum of w2).
8384/// otherwise it returns the sqrt(contents) for this bin.
8385
8387{
8388 if (bin < 0) bin = 0;
8389 if (bin >= fNcells) bin = fNcells-1;
8390 if (fBuffer) ((TH1*)this)->BufferEmpty();
8391 if (fSumw2.fN) return TMath::Sqrt(fSumw2.fArray[bin]);
8392
8394}
8395
8396////////////////////////////////////////////////////////////////////////////////
8397/// Return lower error associated to bin number bin.
8398///
8399/// The error will depend on the statistic option used will return
8400/// the binContent - lower interval value
8401
8403{
8404 if (fBinStatErrOpt == kNormal) return GetBinError(bin);
8405 // in case of weighted histogram check if it is really weighted
8406 if (fSumw2.fN && fTsumw != fTsumw2) return GetBinError(bin);
8407
8408 if (bin < 0) bin = 0;
8409 if (bin >= fNcells) bin = fNcells-1;
8410 if (fBuffer) ((TH1*)this)->BufferEmpty();
8411
8412 Double_t alpha = 1.- 0.682689492;
8413 if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
8414
8416 Int_t n = int(c);
8417 if (n < 0) {
8418 Warning("GetBinErrorLow","Histogram has negative bin content-force usage to normal errors");
8419 ((TH1*)this)->fBinStatErrOpt = kNormal;
8420 return GetBinError(bin);
8421 }
8422
8423 if (n == 0) return 0;
8424 return c - ROOT::Math::gamma_quantile( alpha/2, n, 1.);
8425}
8426
8427////////////////////////////////////////////////////////////////////////////////
8428/// Return upper error associated to bin number bin.
8429///
8430/// The error will depend on the statistic option used will return
8431/// the binContent - upper interval value
8432
8434{
8435 if (fBinStatErrOpt == kNormal) return GetBinError(bin);
8436 // in case of weighted histogram check if it is really weighted
8437 if (fSumw2.fN && fTsumw != fTsumw2) return GetBinError(bin);
8438 if (bin < 0) bin = 0;
8439 if (bin >= fNcells) bin = fNcells-1;
8440 if (fBuffer) ((TH1*)this)->BufferEmpty();
8441
8442 Double_t alpha = 1.- 0.682689492;
8443 if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
8444
8446 Int_t n = int(c);
8447 if (n < 0) {
8448 Warning("GetBinErrorUp","Histogram has negative bin content-force usage to normal errors");
8449 ((TH1*)this)->fBinStatErrOpt = kNormal;
8450 return GetBinError(bin);
8451 }
8452
8453 // for N==0 return an upper limit at 0.68 or (1-alpha)/2 ?
8454 // decide to return always (1-alpha)/2 upper interval
8455 //if (n == 0) return ROOT::Math::gamma_quantile_c(alpha,n+1,1);
8456 return ROOT::Math::gamma_quantile_c( alpha/2, n+1, 1) - c;
8457}
8458
8459//L.M. These following getters are useless and should be probably deprecated
8460////////////////////////////////////////////////////////////////////////////////
8461/// Return bin center for 1D histogram.
8462/// Better to use h1.GetXaxis().GetBinCenter(bin)
8463
8465{
8466 if (fDimension == 1) return fXaxis.GetBinCenter(bin);
8467 Error("GetBinCenter","Invalid method for a %d-d histogram - return a NaN",fDimension);
8468 return TMath::QuietNaN();
8469}
8470
8471////////////////////////////////////////////////////////////////////////////////
8472/// Return bin lower edge for 1D histogram.
8473/// Better to use h1.GetXaxis().GetBinLowEdge(bin)
8474
8476{
8477 if (fDimension == 1) return fXaxis.GetBinLowEdge(bin);
8478 Error("GetBinLowEdge","Invalid method for a %d-d histogram - return a NaN",fDimension);
8479 return TMath::QuietNaN();
8480}
8481
8482////////////////////////////////////////////////////////////////////////////////
8483/// Return bin width for 1D histogram.
8484/// Better to use h1.GetXaxis().GetBinWidth(bin)
8485
8487{
8488 if (fDimension == 1) return fXaxis.GetBinWidth(bin);
8489 Error("GetBinWidth","Invalid method for a %d-d histogram - return a NaN",fDimension);
8490 return TMath::QuietNaN();
8491}
8492
8493////////////////////////////////////////////////////////////////////////////////
8494/// Fill array with center of bins for 1D histogram
8495/// Better to use h1.GetXaxis().GetCenter(center)
8496
8497void TH1::GetCenter(Double_t *center) const
8498{
8499 if (fDimension == 1) {
8500 fXaxis.GetCenter(center);
8501 return;
8502 }
8503 Error("GetCenter","Invalid method for a %d-d histogram ",fDimension);
8504}
8505
8506////////////////////////////////////////////////////////////////////////////////
8507/// Fill array with low edge of bins for 1D histogram
8508/// Better to use h1.GetXaxis().GetLowEdge(edge)
8509
8510void TH1::GetLowEdge(Double_t *edge) const
8511{
8512 if (fDimension == 1) {
8513 fXaxis.GetLowEdge(edge);
8514 return;
8515 }
8516 Error("GetLowEdge","Invalid method for a %d-d histogram ",fDimension);
8517}
8518
8519////////////////////////////////////////////////////////////////////////////////
8520/// Set the bin Error
8521/// Note that this resets the bin eror option to be of Normal Type and for the
8522/// non-empty bin the bin error is set by default to the square root of their content,
8523/// but in case the user sets explicitly a new bin content (using SetBinContent) he needs to provide also
8524/// the error, otherwise a default error = 0 is used.
8525///
8526/// See convention for numbering bins in TH1::GetBin
8527
8528void TH1::SetBinError(Int_t bin, Double_t error)
8529{
8530 if (!fSumw2.fN) Sumw2();
8531 if (bin < 0 || bin>= fSumw2.fN) return;
8532 fSumw2.fArray[bin] = error * error;
8533 // reset the bin error option
8535}
8536
8537////////////////////////////////////////////////////////////////////////////////
8538/// Set bin content
8539/// see convention for numbering bins in TH1::GetBin
8540/// In case the bin number is greater than the number of bins and
8541/// the timedisplay option is set or CanExtendAllAxes(),
8542/// the number of bins is automatically doubled to accommodate the new bin
8543
8544void TH1::SetBinContent(Int_t bin, Double_t content)
8545{
8546 fEntries++;
8547 fTsumw = 0;
8548 if (bin < 0) return;
8549 if (bin >= fNcells-1) {
8551 while (bin >= fNcells-1) LabelsInflate();
8552 } else {
8553 if (bin == fNcells-1) UpdateBinContent(bin, content);
8554 return;
8555 }
8556 }
8557 UpdateBinContent(bin, content);
8558}
8559
8560////////////////////////////////////////////////////////////////////////////////
8561/// See convention for numbering bins in TH1::GetBin
8562
8563void TH1::SetBinError(Int_t binx, Int_t biny, Double_t error)
8564{
8565 if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
8566 if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
8567 SetBinError(GetBin(binx, biny), error);
8568}
8569
8570////////////////////////////////////////////////////////////////////////////////
8571/// See convention for numbering bins in TH1::GetBin
8572
8573void TH1::SetBinError(Int_t binx, Int_t biny, Int_t binz, Double_t error)
8574{
8575 if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
8576 if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
8577 if (binz < 0 || binz > fZaxis.GetNbins() + 1) return;
8578 SetBinError(GetBin(binx, biny, binz), error);
8579}
8580
8581////////////////////////////////////////////////////////////////////////////////
8582/// This function calculates the background spectrum in this histogram.
8583/// The background is returned as a histogram.
8584///
8585/// \param[in] niter number of iterations (default value = 2)
8586/// Increasing niter make the result smoother and lower.
8587/// \param[in] option may contain one of the following options
8588/// - to set the direction parameter
8589/// "BackDecreasingWindow". By default the direction is BackIncreasingWindow
8590/// - filterOrder-order of clipping filter (default "BackOrder2")
8591/// possible values= "BackOrder4" "BackOrder6" "BackOrder8"
8592/// - "nosmoothing" - if selected, the background is not smoothed
8593/// By default the background is smoothed.
8594/// - smoothWindow - width of smoothing window, (default is "BackSmoothing3")
8595/// possible values= "BackSmoothing5" "BackSmoothing7" "BackSmoothing9"
8596/// "BackSmoothing11" "BackSmoothing13" "BackSmoothing15"
8597/// - "nocompton" - if selected the estimation of Compton edge
8598/// will be not be included (by default the compton estimation is set)
8599/// - "same" if this option is specified, the resulting background
8600/// histogram is superimposed on the picture in the current pad.
8601/// This option is given by default.
8602///
8603/// NOTE that the background is only evaluated in the current range of this histogram.
8604/// i.e., if this has a bin range (set via h->GetXaxis()->SetRange(binmin, binmax),
8605/// the returned histogram will be created with the same number of bins
8606/// as this input histogram, but only bins from binmin to binmax will be filled
8607/// with the estimated background.
8608
8609TH1 *TH1::ShowBackground(Int_t niter, Option_t *option)
8610{
8611
8612 return (TH1*)gROOT->ProcessLineFast(Form("TSpectrum::StaticBackground((TH1*)0x%lx,%d,\"%s\")",
8613 (ULong_t)this, niter, option));
8614}
8615
8616////////////////////////////////////////////////////////////////////////////////
8617/// Interface to TSpectrum::Search.
8618/// The function finds peaks in this histogram where the width is > sigma
8619/// and the peak maximum greater than threshold*maximum bin content of this.
8620/// For more details see TSpectrum::Search.
8621/// Note the difference in the default value for option compared to TSpectrum::Search
8622/// option="" by default (instead of "goff").
8623
8625{
8626 return (Int_t)gROOT->ProcessLineFast(Form("TSpectrum::StaticSearch((TH1*)0x%lx,%g,\"%s\",%g)",
8627 (ULong_t)this, sigma, option, threshold));
8628}
8629
8630////////////////////////////////////////////////////////////////////////////////
8631/// For a given transform (first parameter), fills the histogram (second parameter)
8632/// with the transform output data, specified in the third parameter
8633/// If the 2nd parameter h_output is empty, a new histogram (TH1D or TH2D) is created
8634/// and the user is responsible for deleting it.
8635///
8636/// Available options:
8637/// - "RE" - real part of the output
8638/// - "IM" - imaginary part of the output
8639/// - "MAG" - magnitude of the output
8640/// - "PH" - phase of the output
8641
8642TH1* TH1::TransformHisto(TVirtualFFT *fft, TH1* h_output, Option_t *option)
8643{
8644 if (!fft || !fft->GetN() ) {
8645 ::Error("TransformHisto","Invalid FFT transform class");
8646 return 0;
8647 }
8648
8649 if (fft->GetNdim()>2){
8650 ::Error("TransformHisto","Only 1d and 2D transform are supported");
8651 return 0;
8652 }
8653 Int_t binx,biny;
8654 TString opt = option;
8655 opt.ToUpper();
8656 Int_t *n = fft->GetN();
8657 TH1 *hout=0;
8658 if (h_output) {
8659 hout = h_output;
8660 }
8661 else {
8662 TString name = TString::Format("out_%s", opt.Data());
8663 if (fft->GetNdim()==1)
8664 hout = new TH1D(name, name,n[0], 0, n[0]);
8665 else if (fft->GetNdim()==2)
8666 hout = new TH2D(name, name, n[0], 0, n[0], n[1], 0, n[1]);
8667 }
8668 R__ASSERT(hout != 0);
8669 TString type=fft->GetType();
8670 Int_t ind[2];
8671 if (opt.Contains("RE")){
8672 if (type.Contains("2C") || type.Contains("2HC")) {
8673 Double_t re, im;
8674 for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8675 for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8676 ind[0] = binx-1; ind[1] = biny-1;
8677 fft->GetPointComplex(ind, re, im);
8678 hout->SetBinContent(binx, biny, re);
8679 }
8680 }
8681 } else {
8682 for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8683 for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8684 ind[0] = binx-1; ind[1] = biny-1;
8685 hout->SetBinContent(binx, biny, fft->GetPointReal(ind));
8686 }
8687 }
8688 }
8689 }
8690 if (opt.Contains("IM")) {
8691 if (type.Contains("2C") || type.Contains("2HC")) {
8692 Double_t re, im;
8693 for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8694 for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8695 ind[0] = binx-1; ind[1] = biny-1;
8696 fft->GetPointComplex(ind, re, im);
8697 hout->SetBinContent(binx, biny, im);
8698 }
8699 }
8700 } else {
8701 ::Error("TransformHisto","No complex numbers in the output");
8702 return 0;
8703 }
8704 }
8705 if (opt.Contains("MA")) {
8706 if (type.Contains("2C") || type.Contains("2HC")) {
8707 Double_t re, im;
8708 for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8709 for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8710 ind[0] = binx-1; ind[1] = biny-1;
8711 fft->GetPointComplex(ind, re, im);
8712 hout->SetBinContent(binx, biny, TMath::Sqrt(re*re + im*im));
8713 }
8714 }
8715 } else {
8716 for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8717 for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8718 ind[0] = binx-1; ind[1] = biny-1;
8719 hout->SetBinContent(binx, biny, TMath::Abs(fft->GetPointReal(ind)));
8720 }
8721 }
8722 }
8723 }
8724 if (opt.Contains("PH")) {
8725 if (type.Contains("2C") || type.Contains("2HC")){
8726 Double_t re, im, ph;
8727 for (binx = 1; binx<=hout->GetNbinsX(); binx++){
8728 for (biny=1; biny<=hout->GetNbinsY(); biny++){
8729 ind[0] = binx-1; ind[1] = biny-1;
8730 fft->GetPointComplex(ind, re, im);
8731 if (TMath::Abs(re) > 1e-13){
8732 ph = TMath::ATan(im/re);
8733 //find the correct quadrant
8734 if (re<0 && im<0)
8735 ph -= TMath::Pi();
8736 if (re<0 && im>=0)
8737 ph += TMath::Pi();
8738 } else {
8739 if (TMath::Abs(im) < 1e-13)
8740 ph = 0;
8741 else if (im>0)
8742 ph = TMath::Pi()*0.5;
8743 else
8744 ph = -TMath::Pi()*0.5;
8745 }
8746 hout->SetBinContent(binx, biny, ph);
8747 }
8748 }
8749 } else {
8750 printf("Pure real output, no phase");
8751 return 0;
8752 }
8753 }
8754
8755 return hout;
8756}
8757
8758////////////////////////////////////////////////////////////////////////////////
8759/// Raw retrieval of bin content on internal data structure
8760/// see convention for numbering bins in TH1::GetBin
8761
8763{
8764 AbstractMethod("RetrieveBinContent");
8765 return 0;
8766}
8767
8768////////////////////////////////////////////////////////////////////////////////
8769/// Raw update of bin content on internal data structure
8770/// see convention for numbering bins in TH1::GetBin
8771
8773{
8774 AbstractMethod("UpdateBinContent");
8775}
8776
8777////////////////////////////////////////////////////////////////////////////////
8778/// Print value overload
8779
8780std::string cling::printValue(TH1 *val) {
8781 std::ostringstream strm;
8782 strm << cling::printValue((TObject*)val) << " NbinsX: " << val->GetNbinsX();
8783 return strm.str();
8784}
8785
8786//______________________________________________________________________________
8787// TH1C methods
8788// TH1C : histograms with one byte per channel. Maximum bin content = 127
8789//______________________________________________________________________________
8790
8791ClassImp(TH1C);
8792
8793////////////////////////////////////////////////////////////////////////////////
8794/// Constructor.
8795
8796TH1C::TH1C(): TH1(), TArrayC()
8797{
8798 fDimension = 1;
8799 SetBinsLength(3);
8800 if (fgDefaultSumw2) Sumw2();
8801}
8802
8803////////////////////////////////////////////////////////////////////////////////
8804/// Create a 1-Dim histogram with fix bins of type char (one byte per channel)
8805/// (see TH1::TH1 for explanation of parameters)
8806
8807TH1C::TH1C(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
8808: TH1(name,title,nbins,xlow,xup)
8809{
8810 fDimension = 1;
8812
8813 if (xlow >= xup) SetBuffer(fgBufferSize);
8814 if (fgDefaultSumw2) Sumw2();
8815}
8816
8817////////////////////////////////////////////////////////////////////////////////
8818/// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
8819/// (see TH1::TH1 for explanation of parameters)
8820
8821TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
8822: TH1(name,title,nbins,xbins)
8823{
8824 fDimension = 1;
8826 if (fgDefaultSumw2) Sumw2();
8827}
8828
8829////////////////////////////////////////////////////////////////////////////////
8830/// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
8831/// (see TH1::TH1 for explanation of parameters)
8832
8833TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
8834: TH1(name,title,nbins,xbins)
8835{
8836 fDimension = 1;
8838 if (fgDefaultSumw2) Sumw2();
8839}
8840
8841////////////////////////////////////////////////////////////////////////////////
8842/// Destructor.
8843
8845{
8846}
8847
8848////////////////////////////////////////////////////////////////////////////////
8849/// Copy constructor.
8850
8851TH1C::TH1C(const TH1C &h1c) : TH1(), TArrayC()
8852{
8853 ((TH1C&)h1c).Copy(*this);
8854}
8855
8856////////////////////////////////////////////////////////////////////////////////
8857/// Increment bin content by 1.
8858
8859void TH1C::AddBinContent(Int_t bin)
8860{
8861 if (fArray[bin] < 127) fArray[bin]++;
8862}
8863
8864////////////////////////////////////////////////////////////////////////////////
8865/// Increment bin content by w.
8866
8868{
8869 Int_t newval = fArray[bin] + Int_t(w);
8870 if (newval > -128 && newval < 128) {fArray[bin] = Char_t(newval); return;}
8871 if (newval < -127) fArray[bin] = -127;
8872 if (newval > 127) fArray[bin] = 127;
8873}
8874
8875////////////////////////////////////////////////////////////////////////////////
8876/// Copy this to newth1
8877
8878void TH1C::Copy(TObject &newth1) const
8879{
8880 TH1::Copy(newth1);
8881}
8882
8883////////////////////////////////////////////////////////////////////////////////
8884/// Reset.
8885
8886void TH1C::Reset(Option_t *option)
8887{
8888 TH1::Reset(option);
8890}
8891
8892////////////////////////////////////////////////////////////////////////////////
8893/// Set total number of bins including under/overflow
8894/// Reallocate bin contents array
8895
8897{
8898 if (n < 0) n = fXaxis.GetNbins() + 2;
8899 fNcells = n;
8900 TArrayC::Set(n);
8901}
8902
8903////////////////////////////////////////////////////////////////////////////////
8904/// Operator =
8905
8906TH1C& TH1C::operator=(const TH1C &h1)
8907{
8908 if (this != &h1) ((TH1C&)h1).Copy(*this);
8909 return *this;
8910}
8911
8912////////////////////////////////////////////////////////////////////////////////
8913/// Operator *
8914
8916{
8917 TH1C hnew = h1;
8918 hnew.Scale(c1);
8919 hnew.SetDirectory(0);
8920 return hnew;
8921}
8922
8923////////////////////////////////////////////////////////////////////////////////
8924/// Operator +
8925
8926TH1C operator+(const TH1C &h1, const TH1C &h2)
8927{
8928 TH1C hnew = h1;
8929 hnew.Add(&h2,1);
8930 hnew.SetDirectory(0);
8931 return hnew;
8932}
8933
8934////////////////////////////////////////////////////////////////////////////////
8935/// Operator -
8936
8937TH1C operator-(const TH1C &h1, const TH1C &h2)
8938{
8939 TH1C hnew = h1;
8940 hnew.Add(&h2,-1);
8941 hnew.SetDirectory(0);
8942 return hnew;
8943}
8944
8945////////////////////////////////////////////////////////////////////////////////
8946/// Operator *
8947
8948TH1C operator*(const TH1C &h1, const TH1C &h2)
8949{
8950 TH1C hnew = h1;
8951 hnew.Multiply(&h2);
8952 hnew.SetDirectory(0);
8953 return hnew;
8954}
8955
8956////////////////////////////////////////////////////////////////////////////////
8957/// Operator /
8958
8959TH1C operator/(const TH1C &h1, const TH1C &h2)
8960{
8961 TH1C hnew = h1;
8962 hnew.Divide(&h2);
8963 hnew.SetDirectory(0);
8964 return hnew;
8965}
8966
8967//______________________________________________________________________________
8968// TH1S methods
8969// TH1S : histograms with one short per channel. Maximum bin content = 32767
8970//______________________________________________________________________________
8971
8972ClassImp(TH1S);
8973
8974////////////////////////////////////////////////////////////////////////////////
8975/// Constructor.
8976
8977TH1S::TH1S(): TH1(), TArrayS()
8978{
8979 fDimension = 1;
8980 SetBinsLength(3);
8981 if (fgDefaultSumw2) Sumw2();
8982}
8983
8984////////////////////////////////////////////////////////////////////////////////
8985/// Create a 1-Dim histogram with fix bins of type short
8986/// (see TH1::TH1 for explanation of parameters)
8987
8988TH1S::TH1S(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
8989: TH1(name,title,nbins,xlow,xup)
8990{
8991 fDimension = 1;
8993
8994 if (xlow >= xup) SetBuffer(fgBufferSize);
8995 if (fgDefaultSumw2) Sumw2();
8996}
8997
8998////////////////////////////////////////////////////////////////////////////////
8999/// Create a 1-Dim histogram with variable bins of type short
9000/// (see TH1::TH1 for explanation of parameters)
9001
9002TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9003: TH1(name,title,nbins,xbins)
9004{
9005 fDimension = 1;
9007 if (fgDefaultSumw2) Sumw2();
9008}
9009
9010////////////////////////////////////////////////////////////////////////////////
9011/// Create a 1-Dim histogram with variable bins of type short
9012/// (see TH1::TH1 for explanation of parameters)
9013
9014TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9015: TH1(name,title,nbins,xbins)
9016{
9017 fDimension = 1;
9019 if (fgDefaultSumw2) Sumw2();
9020}
9021
9022////////////////////////////////////////////////////////////////////////////////
9023/// Destructor.
9024
9026{
9027}
9028
9029////////////////////////////////////////////////////////////////////////////////
9030/// Copy constructor.
9031
9032TH1S::TH1S(const TH1S &h1s) : TH1(), TArrayS()
9033{
9034 ((TH1S&)h1s).Copy(*this);
9035}
9036
9037////////////////////////////////////////////////////////////////////////////////
9038/// Increment bin content by 1.
9039
9040void TH1S::AddBinContent(Int_t bin)
9041{
9042 if (fArray[bin] < 32767) fArray[bin]++;
9043}
9044
9045////////////////////////////////////////////////////////////////////////////////
9046/// Increment bin content by w
9047
9049{
9050 Int_t newval = fArray[bin] + Int_t(w);
9051 if (newval > -32768 && newval < 32768) {fArray[bin] = Short_t(newval); return;}
9052 if (newval < -32767) fArray[bin] = -32767;
9053 if (newval > 32767) fArray[bin] = 32767;
9054}
9055
9056////////////////////////////////////////////////////////////////////////////////
9057/// Copy this to newth1
9058
9059void TH1S::Copy(TObject &newth1) const
9060{
9061 TH1::Copy(newth1);
9062}
9063
9064////////////////////////////////////////////////////////////////////////////////
9065/// Reset.
9066
9067void TH1S::Reset(Option_t *option)
9068{
9069 TH1::Reset(option);
9071}
9072
9073////////////////////////////////////////////////////////////////////////////////
9074/// Set total number of bins including under/overflow
9075/// Reallocate bin contents array
9076
9078{
9079 if (n < 0) n = fXaxis.GetNbins() + 2;
9080 fNcells = n;
9081 TArrayS::Set(n);
9082}
9083
9084////////////////////////////////////////////////////////////////////////////////
9085/// Operator =
9086
9087TH1S& TH1S::operator=(const TH1S &h1)
9088{
9089 if (this != &h1) ((TH1S&)h1).Copy(*this);
9090 return *this;
9091}
9092
9093////////////////////////////////////////////////////////////////////////////////
9094/// Operator *
9095
9097{
9098 TH1S hnew = h1;
9099 hnew.Scale(c1);
9100 hnew.SetDirectory(0);
9101 return hnew;
9102}
9103
9104////////////////////////////////////////////////////////////////////////////////
9105/// Operator +
9106
9107TH1S operator+(const TH1S &h1, const TH1S &h2)
9108{
9109 TH1S hnew = h1;
9110 hnew.Add(&h2,1);
9111 hnew.SetDirectory(0);
9112 return hnew;
9113}
9114
9115////////////////////////////////////////////////////////////////////////////////
9116/// Operator -
9117
9118TH1S operator-(const TH1S &h1, const TH1S &h2)
9119{
9120 TH1S hnew = h1;
9121 hnew.Add(&h2,-1);
9122 hnew.SetDirectory(0);
9123 return hnew;
9124}
9125
9126////////////////////////////////////////////////////////////////////////////////
9127/// Operator *
9128
9129TH1S operator*(const TH1S &h1, const TH1S &h2)
9130{
9131 TH1S hnew = h1;
9132 hnew.Multiply(&h2);
9133 hnew.SetDirectory(0);
9134 return hnew;
9135}
9136
9137////////////////////////////////////////////////////////////////////////////////
9138/// Operator /
9139
9140TH1S operator/(const TH1S &h1, const TH1S &h2)
9141{
9142 TH1S hnew = h1;
9143 hnew.Divide(&h2);
9144 hnew.SetDirectory(0);
9145 return hnew;
9146}
9147
9148//______________________________________________________________________________
9149// TH1I methods
9150// TH1I : histograms with one int per channel. Maximum bin content = 2147483647
9151//______________________________________________________________________________
9152
9153ClassImp(TH1I);
9154
9155////////////////////////////////////////////////////////////////////////////////
9156/// Constructor.
9157
9158TH1I::TH1I(): TH1(), TArrayI()
9159{
9160 fDimension = 1;
9161 SetBinsLength(3);
9162 if (fgDefaultSumw2) Sumw2();
9163}
9164
9165////////////////////////////////////////////////////////////////////////////////
9166/// Create a 1-Dim histogram with fix bins of type integer
9167/// (see TH1::TH1 for explanation of parameters)
9168
9169TH1I::TH1I(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9170: TH1(name,title,nbins,xlow,xup)
9171{
9172 fDimension = 1;
9174
9175 if (xlow >= xup) SetBuffer(fgBufferSize);
9176 if (fgDefaultSumw2) Sumw2();
9177}
9178
9179////////////////////////////////////////////////////////////////////////////////
9180/// Create a 1-Dim histogram with variable bins of type integer
9181/// (see TH1::TH1 for explanation of parameters)
9182
9183TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9184: TH1(name,title,nbins,xbins)
9185{
9186 fDimension = 1;
9188 if (fgDefaultSumw2) Sumw2();
9189}
9190
9191////////////////////////////////////////////////////////////////////////////////
9192/// Create a 1-Dim histogram with variable bins of type integer
9193/// (see TH1::TH1 for explanation of parameters)
9194
9195TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9196: TH1(name,title,nbins,xbins)
9197{
9198 fDimension = 1;
9200 if (fgDefaultSumw2) Sumw2();
9201}
9202
9203////////////////////////////////////////////////////////////////////////////////
9204/// Destructor.
9205
9207{
9208}
9209
9210////////////////////////////////////////////////////////////////////////////////
9211/// Copy constructor.
9212
9213TH1I::TH1I(const TH1I &h1i) : TH1(), TArrayI()
9214{
9215 ((TH1I&)h1i).Copy(*this);
9216}
9217
9218////////////////////////////////////////////////////////////////////////////////
9219/// Increment bin content by 1.
9220
9221void TH1I::AddBinContent(Int_t bin)
9222{
9223 if (fArray[bin] < 2147483647) fArray[bin]++;
9224}
9225
9226////////////////////////////////////////////////////////////////////////////////
9227/// Increment bin content by w
9228
9230{
9231 Long64_t newval = fArray[bin] + Long64_t(w);
9232 if (newval > -2147483647 && newval < 2147483647) {fArray[bin] = Int_t(newval); return;}
9233 if (newval < -2147483647) fArray[bin] = -2147483647;
9234 if (newval > 2147483647) fArray[bin] = 2147483647;
9235}
9236
9237////////////////////////////////////////////////////////////////////////////////
9238/// Copy this to newth1
9239
9240void TH1I::Copy(TObject &newth1) const
9241{
9242 TH1::Copy(newth1);
9243}
9244
9245////////////////////////////////////////////////////////////////////////////////
9246/// Reset.
9247
9248void TH1I::Reset(Option_t *option)
9249{
9250 TH1::Reset(option);
9252}
9253
9254////////////////////////////////////////////////////////////////////////////////
9255/// Set total number of bins including under/overflow
9256/// Reallocate bin contents array
9257
9259{
9260 if (n < 0) n = fXaxis.GetNbins() + 2;
9261 fNcells = n;
9262 TArrayI::Set(n);
9263}
9264
9265////////////////////////////////////////////////////////////////////////////////
9266/// Operator =
9267
9268TH1I& TH1I::operator=(const TH1I &h1)
9269{
9270 if (this != &h1) ((TH1I&)h1).Copy(*this);
9271 return *this;
9272}
9273
9274
9275////////////////////////////////////////////////////////////////////////////////
9276/// Operator *
9277
9279{
9280 TH1I hnew = h1;
9281 hnew.Scale(c1);
9282 hnew.SetDirectory(0);
9283 return hnew;
9284}
9285
9286////////////////////////////////////////////////////////////////////////////////
9287/// Operator +
9288
9289TH1I operator+(const TH1I &h1, const TH1I &h2)
9290{
9291 TH1I hnew = h1;
9292 hnew.Add(&h2,1);
9293 hnew.SetDirectory(0);
9294 return hnew;
9295}
9296
9297////////////////////////////////////////////////////////////////////////////////
9298/// Operator -
9299
9300TH1I operator-(const TH1I &h1, const TH1I &h2)
9301{
9302 TH1I hnew = h1;
9303 hnew.Add(&h2,-1);
9304 hnew.SetDirectory(0);
9305 return hnew;
9306}
9307
9308////////////////////////////////////////////////////////////////////////////////
9309/// Operator *
9310
9311TH1I operator*(const TH1I &h1, const TH1I &h2)
9312{
9313 TH1I hnew = h1;
9314 hnew.Multiply(&h2);
9315 hnew.SetDirectory(0);
9316 return hnew;
9317}
9318
9319////////////////////////////////////////////////////////////////////////////////
9320/// Operator /
9321
9322TH1I operator/(const TH1I &h1, const TH1I &h2)
9323{
9324 TH1I hnew = h1;
9325 hnew.Divide(&h2);
9326 hnew.SetDirectory(0);
9327 return hnew;
9328}
9329
9330//______________________________________________________________________________
9331// TH1F methods
9332// TH1F : histograms with one float per channel. Maximum precision 7 digits
9333//______________________________________________________________________________
9334
9335ClassImp(TH1F);
9336
9337////////////////////////////////////////////////////////////////////////////////
9338/// Constructor.
9339
9340TH1F::TH1F(): TH1(), TArrayF()
9341{
9342 fDimension = 1;
9343 SetBinsLength(3);
9344 if (fgDefaultSumw2) Sumw2();
9345}
9346
9347////////////////////////////////////////////////////////////////////////////////
9348/// Create a 1-Dim histogram with fix bins of type float
9349/// (see TH1::TH1 for explanation of parameters)
9350
9351TH1F::TH1F(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9352: TH1(name,title,nbins,xlow,xup)
9353{
9354 fDimension = 1;
9356
9357 if (xlow >= xup) SetBuffer(fgBufferSize);
9358 if (fgDefaultSumw2) Sumw2();
9359}
9360
9361////////////////////////////////////////////////////////////////////////////////
9362/// Create a 1-Dim histogram with variable bins of type float
9363/// (see TH1::TH1 for explanation of parameters)
9364
9365TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9366: TH1(name,title,nbins,xbins)
9367{
9368 fDimension = 1;
9370 if (fgDefaultSumw2) Sumw2();
9371}
9372
9373////////////////////////////////////////////////////////////////////////////////
9374/// Create a 1-Dim histogram with variable bins of type float
9375/// (see TH1::TH1 for explanation of parameters)
9376
9377TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9378: TH1(name,title,nbins,xbins)
9379{
9380 fDimension = 1;
9382 if (fgDefaultSumw2) Sumw2();
9383}
9384
9385////////////////////////////////////////////////////////////////////////////////
9386/// Create a histogram from a TVectorF
9387/// by default the histogram name is "TVectorF" and title = ""
9388
9389TH1F::TH1F(const TVectorF &v)
9390: TH1("TVectorF","",v.GetNrows(),0,v.GetNrows())
9391{
9393 fDimension = 1;
9394 Int_t ivlow = v.GetLwb();
9395 for (Int_t i=0;i<fNcells-2;i++) {
9396 SetBinContent(i+1,v(i+ivlow));
9397 }
9399 if (fgDefaultSumw2) Sumw2();
9400}
9401
9402////////////////////////////////////////////////////////////////////////////////
9403/// Copy Constructor.
9404
9405TH1F::TH1F(const TH1F &h) : TH1(), TArrayF()
9406{
9407 ((TH1F&)h).Copy(*this);
9408}
9409
9410////////////////////////////////////////////////////////////////////////////////
9411/// Destructor.
9412
9414{
9415}
9416
9417////////////////////////////////////////////////////////////////////////////////
9418/// Copy this to newth1.
9419
9420void TH1F::Copy(TObject &newth1) const
9421{
9422 TH1::Copy(newth1);
9423}
9424
9425////////////////////////////////////////////////////////////////////////////////
9426/// Reset.
9427
9428void TH1F::Reset(Option_t *option)
9429{
9430 TH1::Reset(option);
9432}
9433
9434////////////////////////////////////////////////////////////////////////////////
9435/// Set total number of bins including under/overflow
9436/// Reallocate bin contents array
9437
9439{
9440 if (n < 0) n = fXaxis.GetNbins() + 2;
9441 fNcells = n;
9442 TArrayF::Set(n);
9443}
9444
9445////////////////////////////////////////////////////////////////////////////////
9446/// Operator =
9447
9448TH1F& TH1F::operator=(const TH1F &h1)
9449{
9450 if (this != &h1) ((TH1F&)h1).Copy(*this);
9451 return *this;
9452}
9453
9454////////////////////////////////////////////////////////////////////////////////
9455/// Operator *
9456
9458{
9459 TH1F hnew = h1;
9460 hnew.Scale(c1);
9461 hnew.SetDirectory(0);
9462 return hnew;
9463}
9464
9465////////////////////////////////////////////////////////////////////////////////
9466/// Operator +
9467
9468TH1F operator+(const TH1F &h1, const TH1F &h2)
9469{
9470 TH1F hnew = h1;
9471 hnew.Add(&h2,1);
9472 hnew.SetDirectory(0);
9473 return hnew;
9474}
9475
9476////////////////////////////////////////////////////////////////////////////////
9477/// Operator -
9478
9479TH1F operator-(const TH1F &h1, const TH1F &h2)
9480{
9481 TH1F hnew = h1;
9482 hnew.Add(&h2,-1);
9483 hnew.SetDirectory(0);
9484 return hnew;
9485}
9486
9487////////////////////////////////////////////////////////////////////////////////
9488/// Operator *
9489
9490TH1F operator*(const TH1F &h1, const TH1F &h2)
9491{
9492 TH1F hnew = h1;
9493 hnew.Multiply(&h2);
9494 hnew.SetDirectory(0);
9495 return hnew;
9496}
9497
9498////////////////////////////////////////////////////////////////////////////////
9499/// Operator /
9500
9501TH1F operator/(const TH1F &h1, const TH1F &h2)
9502{
9503 TH1F hnew = h1;
9504 hnew.Divide(&h2);
9505 hnew.SetDirectory(0);
9506 return hnew;
9507}
9508
9509//______________________________________________________________________________
9510// TH1D methods
9511// TH1D : histograms with one double per channel. Maximum precision 14 digits
9512//______________________________________________________________________________
9513
9514ClassImp(TH1D);
9515
9516////////////////////////////////////////////////////////////////////////////////
9517/// Constructor.
9518
9519TH1D::TH1D(): TH1(), TArrayD()
9520{
9521 fDimension = 1;
9522 SetBinsLength(3);
9523 if (fgDefaultSumw2) Sumw2();
9524}
9525
9526////////////////////////////////////////////////////////////////////////////////
9527/// Create a 1-Dim histogram with fix bins of type double
9528/// (see TH1::TH1 for explanation of parameters)
9529
9530TH1D::TH1D(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9531: TH1(name,title,nbins,xlow,xup)
9532{
9533 fDimension = 1;
9535
9536 if (xlow >= xup) SetBuffer(fgBufferSize);
9537 if (fgDefaultSumw2) Sumw2();
9538}
9539
9540////////////////////////////////////////////////////////////////////////////////
9541/// Create a 1-Dim histogram with variable bins of type double
9542/// (see TH1::TH1 for explanation of parameters)
9543
9544TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9545: TH1(name,title,nbins,xbins)
9546{
9547 fDimension = 1;
9549 if (fgDefaultSumw2) Sumw2();
9550}
9551
9552////////////////////////////////////////////////////////////////////////////////
9553/// Create a 1-Dim histogram with variable bins of type double
9554/// (see TH1::TH1 for explanation of parameters)
9555
9556TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9557: TH1(name,title,nbins,xbins)
9558{
9559 fDimension = 1;
9561 if (fgDefaultSumw2) Sumw2();
9562}
9563
9564////////////////////////////////////////////////////////////////////////////////
9565/// Create a histogram from a TVectorD
9566/// by default the histogram name is "TVectorD" and title = ""
9567
9568TH1D::TH1D(const TVectorD &v)
9569: TH1("TVectorD","",v.GetNrows(),0,v.GetNrows())
9570{
9572 fDimension = 1;
9573 Int_t ivlow = v.GetLwb();
9574 for (Int_t i=0;i<fNcells-2;i++) {
9575 SetBinContent(i+1,v(i+ivlow));
9576 }
9578 if (fgDefaultSumw2) Sumw2();
9579}
9580
9581////////////////////////////////////////////////////////////////////////////////
9582/// Destructor.
9583
9585{
9586}
9587
9588////////////////////////////////////////////////////////////////////////////////
9589/// Constructor.
9590
9591TH1D::TH1D(const TH1D &h1d) : TH1(), TArrayD()
9592{
9593 ((TH1D&)h1d).Copy(*this);
9594}
9595
9596////////////////////////////////////////////////////////////////////////////////
9597/// Copy this to newth1
9598
9599void TH1D::Copy(TObject &newth1) const
9600{
9601 TH1::Copy(newth1);
9602}
9603
9604////////////////////////////////////////////////////////////////////////////////
9605/// Reset.
9606
9607void TH1D::Reset(Option_t *option)
9608{
9609 TH1::Reset(option);
9611}
9612
9613////////////////////////////////////////////////////////////////////////////////
9614/// Set total number of bins including under/overflow
9615/// Reallocate bin contents array
9616
9618{
9619 if (n < 0) n = fXaxis.GetNbins() + 2;
9620 fNcells = n;
9621 TArrayD::Set(n);
9622}
9623
9624////////////////////////////////////////////////////////////////////////////////
9625/// Operator =
9626
9627TH1D& TH1D::operator=(const TH1D &h1)
9628{
9629 if (this != &h1) ((TH1D&)h1).Copy(*this);
9630 return *this;
9631}
9632
9633////////////////////////////////////////////////////////////////////////////////
9634/// Operator *
9635
9637{
9638 TH1D hnew = h1;
9639 hnew.Scale(c1);
9640 hnew.SetDirectory(0);
9641 return hnew;
9642}
9643
9644////////////////////////////////////////////////////////////////////////////////
9645/// Operator +
9646
9647TH1D operator+(const TH1D &h1, const TH1D &h2)
9648{
9649 TH1D hnew = h1;
9650 hnew.Add(&h2,1);
9651 hnew.SetDirectory(0);
9652 return hnew;
9653}
9654
9655////////////////////////////////////////////////////////////////////////////////
9656/// Operator -
9657
9658TH1D operator-(const TH1D &h1, const TH1D &h2)
9659{
9660 TH1D hnew = h1;
9661 hnew.Add(&h2,-1);
9662 hnew.SetDirectory(0);
9663 return hnew;
9664}
9665
9666////////////////////////////////////////////////////////////////////////////////
9667/// Operator *
9668
9669TH1D operator*(const TH1D &h1, const TH1D &h2)
9670{
9671 TH1D hnew = h1;
9672 hnew.Multiply(&h2);
9673 hnew.SetDirectory(0);
9674 return hnew;
9675}
9676
9677////////////////////////////////////////////////////////////////////////////////
9678/// Operator /
9679
9680TH1D operator/(const TH1D &h1, const TH1D &h2)
9681{
9682 TH1D hnew = h1;
9683 hnew.Divide(&h2);
9684 hnew.SetDirectory(0);
9685 return hnew;
9686}
9687
9688////////////////////////////////////////////////////////////////////////////////
9689///return pointer to histogram with name
9690///hid if id >=0
9691///h_id if id <0
9692
9693TH1 *R__H(Int_t hid)
9694{
9695 TString hname;
9696 if(hid >= 0) hname.Form("h%d",hid);
9697 else hname.Form("h_%d",hid);
9698 return (TH1*)gDirectory->Get(hname);
9699}
9700
9701////////////////////////////////////////////////////////////////////////////////
9702///return pointer to histogram with name hname
9703
9704TH1 *R__H(const char * hname)
9705{
9706 return (TH1*)gDirectory->Get(hname);
9707}
void Class()
Definition: Class.C:29
SVector< double, 2 > v
Definition: Dict.h:5
#define b(i)
Definition: RSha256.hxx:100
#define c(i)
Definition: RSha256.hxx:101
#define s1(x)
Definition: RSha256.hxx:91
#define h(i)
Definition: RSha256.hxx:106
#define e(i)
Definition: RSha256.hxx:103
static const double x1[5]
int Int_t
Definition: RtypesCore.h:41
short Version_t
Definition: RtypesCore.h:61
char Char_t
Definition: RtypesCore.h:29
unsigned int UInt_t
Definition: RtypesCore.h:42
const Bool_t kFALSE
Definition: RtypesCore.h:88
unsigned long ULong_t
Definition: RtypesCore.h:51
bool Bool_t
Definition: RtypesCore.h:59
short Short_t
Definition: RtypesCore.h:35
double Double_t
Definition: RtypesCore.h:55
double Stat_t
Definition: RtypesCore.h:73
short Color_t
Definition: RtypesCore.h:79
long long Long64_t
Definition: RtypesCore.h:69
short Style_t
Definition: RtypesCore.h:76
float Float_t
Definition: RtypesCore.h:53
const Bool_t kTRUE
Definition: RtypesCore.h:87
const char Option_t
Definition: RtypesCore.h:62
#define ClassImp(name)
Definition: Rtypes.h:363
#define gDirectory
Definition: TDirectory.h:213
include TDocParser_001 C image html pict1_TDocParser_001 png width
Definition: TDocParser.cxx:121
R__EXTERN TEnv * gEnv
Definition: TEnv.h:171
#define R__ASSERT(e)
Definition: TError.h:96
int type
Definition: TGX11.cxx:120
#define Printf
Definition: TGeoToOCC.h:18
static bool IsEquidistantBinning(const TAxis &axis)
Test if the binning is equidistant.
Definition: TH1.cxx:5370
void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
Least square linear fit without weights.
Definition: TH1.cxx:4557
void H1InitGaus()
Compute Initial values of parameters for a gaussian.
Definition: TH1.cxx:4392
void H1InitExpo()
Compute Initial values of parameters for an exponential.
Definition: TH1.cxx:4448
TH1C operator+(const TH1C &h1, const TH1C &h2)
Operator +.
Definition: TH1.cxx:8924
TH1C operator-(const TH1C &h1, const TH1C &h2)
Operator -.
Definition: TH1.cxx:8935
TH1C operator/(const TH1C &h1, const TH1C &h2)
Operator /.
Definition: TH1.cxx:8957
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:4603
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:5353
static Bool_t AlmostInteger(Double_t a, Double_t epsilon=0.00000001)
Test if a double is almost an integer.
Definition: TH1.cxx:5361
TF1 * gF1
Definition: TH1.cxx:524
TH1 * R__H(Int_t hid)
return pointer to histogram with name hid if id >=0 h_id if id <0
Definition: TH1.cxx:9691
TH1C operator*(Double_t c1, const TH1C &h1)
Operator *.
Definition: TH1.cxx:8913
void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a)
Least squares lpolynomial fitting without weights.
Definition: TH1.cxx:4498
void H1InitPolynom()
Compute Initial values of parameters for a polynom.
Definition: TH1.cxx:4468
float xmin
Definition: THbookFile.cxx:93
int nentries
Definition: THbookFile.cxx:89
float * q
Definition: THbookFile.cxx:87
float ymin
Definition: THbookFile.cxx:93
float xmax
Definition: THbookFile.cxx:93
float ymax
Definition: THbookFile.cxx:93
#define gInterpreter
Definition: TInterpreter.h:538
int isnan(double)
double ldexp(double, int)
R__EXTERN TVirtualMutex * gROOTMutex
Definition: TROOT.h:57
#define gROOT
Definition: TROOT.h:410
R__EXTERN TRandom * gRandom
Definition: TRandom.h:62
char * Form(const char *fmt,...)
R__EXTERN TStyle * gStyle
Definition: TStyle.h:406
#define R__LOCKGUARD(mutex)
#define gPad
Definition: TVirtualPad.h:286
#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:53
class describing the range in the coordinates it supports multiple range in a coordinate.
Definition: DataRange.h:34
void AndersonDarling2SamplesTest(Double_t &pvalue, Double_t &testStat) const
Definition: GoFTest.cxx:646
Array of chars or bytes (8 bits per element).
Definition: TArrayC.h:27
void Set(Int_t n)
Set size of this array to n chars.
Definition: TArrayC.cxx:105
Char_t * fArray
Definition: TArrayC.h:30
void Copy(TArrayC &array) const
Definition: TArrayC.h:42
void Reset(Char_t val=0)
Definition: TArrayC.h:47
Array of doubles (64 bits per element).
Definition: TArrayD.h:27
Double_t GetAt(Int_t i) const
Definition: TArrayD.h:45
Double_t * fArray
Definition: TArrayD.h:30
void Copy(TArrayD &array) const
Definition: TArrayD.h:42
void Set(Int_t n)
Set size of this array to n doubles.
Definition: TArrayD.cxx:106
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 Copy(TArrayF &array) const
Definition: TArrayF.h:42
void Reset()
Definition: TArrayF.h:47
void Set(Int_t n)
Set size of this array to n floats.
Definition: TArrayF.cxx:105
Array of integers (32 bits per element).
Definition: TArrayI.h:27
Int_t * fArray
Definition: TArrayI.h:30
void Set(Int_t n)
Set size of this array to n ints.
Definition: TArrayI.cxx:105
void Reset()
Definition: TArrayI.h:47
void Copy(TArrayI &array) const
Definition: TArrayI.h:42
Array of shorts (16 bits per element).
Definition: TArrayS.h:27
void Set(Int_t n)
Set size of this array to n shorts.
Definition: TArrayS.cxx:105
void Reset()
Definition: TArrayS.h:47
void Copy(TArrayS &array) const
Definition: TArrayS.h:42
Short_t * fArray
Definition: TArrayS.h:30
Abstract array base class.
Definition: TArray.h:31
Int_t fN
Definition: TArray.h:38
Int_t GetSize() const
Definition: TArray.h:47
virtual Color_t GetTitleColor() const
Definition: TAttAxis.h:45
virtual Color_t GetLabelColor() const
Definition: TAttAxis.h:38
virtual Int_t GetNdivisions() const
Definition: TAttAxis.h:36
virtual Color_t GetAxisColor() const
Definition: TAttAxis.h:37
virtual void SetTitleOffset(Float_t offset=1)
Set distance between the axis and the axis title Offset is a correction factor with respect to the "s...
Definition: TAttAxis.cxx:294
virtual Style_t GetTitleFont() const
Definition: TAttAxis.h:46
virtual Float_t GetLabelOffset() const
Definition: TAttAxis.h:40
virtual void SetAxisColor(Color_t color=1, Float_t alpha=1.)
Set color of the line axis and tick marks.
Definition: TAttAxis.cxx:163
virtual void SetLabelSize(Float_t size=0.04)
Set size of axis labels The size is expressed in per cent of the pad width.
Definition: TAttAxis.cxx:204
virtual Style_t GetLabelFont() const
Definition: TAttAxis.h:39
virtual void SetTitleFont(Style_t font=62)
Set the title font.
Definition: TAttAxis.cxx:322
virtual void SetLabelOffset(Float_t offset=0.005)
Set distance between the axis and the labels The distance is expressed in per cent of the pad width.
Definition: TAttAxis.cxx:193
virtual void SetLabelFont(Style_t font=62)
Set labels' font.
Definition: TAttAxis.cxx:183
virtual void SetTitleSize(Float_t size=0.04)
Set size of axis title The size is expressed in per cent of the pad width.
Definition: TAttAxis.cxx:304
virtual void SetTitleColor(Color_t color=1)
Set color of axis title.
Definition: TAttAxis.cxx:313
virtual Float_t GetTitleSize() const
Definition: TAttAxis.h:43
virtual Float_t GetLabelSize() const
Definition: TAttAxis.h:41
virtual Float_t GetTickLength() const
Definition: TAttAxis.h:44
virtual void ResetAttAxis(Option_t *option="")
Reset axis attributes.
Definition: TAttAxis.cxx:79
virtual Float_t GetTitleOffset() const
Definition: TAttAxis.h:42
virtual void SetTickLength(Float_t length=0.03)
Set tick mark length The length is expressed in per cent of the pad width.
Definition: TAttAxis.cxx:280
virtual void SetNdivisions(Int_t n=510, Bool_t optim=kTRUE)
Set the number of divisions for this axis.
Definition: TAttAxis.cxx:229
virtual void SetLabelColor(Color_t color=1, Float_t alpha=1.)
Set color of labels.
Definition: TAttAxis.cxx:173
Fill Area Attributes class.
Definition: TAttFill.h:19
virtual Color_t GetFillColor() const
Return the fill area color.
Definition: TAttFill.h:30
void Copy(TAttFill &attfill) const
Copy this fill attributes to a new TAttFill.
Definition: TAttFill.cxx:201
virtual Style_t GetFillStyle() const
Return the fill area style.
Definition: TAttFill.h:31
virtual void SetFillColor(Color_t fcolor)
Set the fill area color.
Definition: TAttFill.h:37
virtual void SetFillStyle(Style_t fstyle)
Set the fill area style.
Definition: TAttFill.h:39
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:233
Line Attributes class.
Definition: TAttLine.h:18
virtual Color_t GetLineColor() const
Return the line color.
Definition: TAttLine.h:33
virtual void SetLineStyle(Style_t lstyle)
Set the line style.
Definition: TAttLine.h:42
virtual Width_t GetLineWidth() const
Return the line width.
Definition: TAttLine.h:35
virtual void SetLineWidth(Width_t lwidth)
Set the line width.
Definition: TAttLine.h:43
virtual void SetLineColor(Color_t lcolor)
Set the line color.
Definition: TAttLine.h:40
virtual Style_t GetLineStyle() const
Return the line style.
Definition: TAttLine.h:34
void Copy(TAttLine &attline) const
Copy this line attributes to a new TAttLine.
Definition: TAttLine.cxx:164
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:262
Marker Attributes class.
Definition: TAttMarker.h:19
virtual void SaveMarkerAttributes(std::ostream &out, const char *name, Int_t coldef=1, Int_t stydef=1, Int_t sizdef=1)
Save line attributes as C++ statement(s) on output stream out.
Definition: TAttMarker.cxx:245
virtual Style_t GetMarkerStyle() const
Return the marker style.
Definition: TAttMarker.h:32
virtual void SetMarkerColor(Color_t mcolor=1)
Set the marker color.
Definition: TAttMarker.h:38
virtual Color_t GetMarkerColor() const
Return the marker color.
Definition: TAttMarker.h:31
virtual Size_t GetMarkerSize() const
Return the marker size.
Definition: TAttMarker.h:33
virtual void SetMarkerStyle(Style_t mstyle=1)
Set the marker style.
Definition: TAttMarker.h:40
void Copy(TAttMarker &attmarker) const
Copy this marker attributes to a new TAttMarker.
Definition: TAttMarker.cxx:210
virtual void SetMarkerSize(Size_t msize=1)
Set the marker size.
Definition: TAttMarker.h:41
Class to manage histogram axis.
Definition: TAxis.h:30
virtual void GetCenter(Double_t *center) const
Return an array with the center of all bins.
Definition: TAxis.cxx:539
virtual Bool_t GetTimeDisplay() const
Definition: TAxis.h:126
virtual Double_t GetBinCenter(Int_t bin) const
Return center of bin.
Definition: TAxis.cxx:464
Bool_t CanExtend() const
Definition: TAxis.h:82
virtual void SetParent(TObject *obj)
Definition: TAxis.h:157
const TArrayD * GetXbins() const
Definition: TAxis.h:130
void SetCanExtend(Bool_t canExtend)
Definition: TAxis.h:86
Double_t GetXmax() const
Definition: TAxis.h:134
virtual void SaveAttributes(std::ostream &out, const char *name, const char *subname)
Save axis attributes as C++ statement(s) on output stream out.
Definition: TAxis.cxx:647
@ kLabelsUp
Definition: TAxis.h:70
@ kLabelsDown
Definition: TAxis.h:69
@ kLabelsHori
Definition: TAxis.h:67
@ kAxisRange
Definition: TAxis.h:61
@ kLabelsVert
Definition: TAxis.h:68
const char * GetBinLabel(Int_t bin) const
Return label for bin.
Definition: TAxis.cxx:426
virtual Int_t FindBin(Double_t x)
Find bin number corresponding to abscissa x.
Definition: TAxis.cxx:279
virtual Double_t GetBinLowEdge(Int_t bin) const
Return low edge of bin.
Definition: TAxis.cxx:504
virtual void SetTimeDisplay(Int_t value)
Definition: TAxis.h:161
virtual void Set(Int_t nbins, Double_t xmin, Double_t xmax)
Initialize axis with fix bins.
Definition: TAxis.cxx:717
virtual Int_t FindFixBin(Double_t x) const
Find bin number corresponding to abscissa x.
Definition: TAxis.cxx:405
virtual void Copy(TObject &axis) const
Copy axis structure to another axis.
Definition: TAxis.cxx:208
Int_t GetLast() const
Return last bin on the axis i.e.
Definition: TAxis.cxx:455
virtual void SetLimits(Double_t xmin, Double_t xmax)
Definition: TAxis.h:154
Double_t GetXmin() const
Definition: TAxis.h:133
Int_t GetNbins() const
Definition: TAxis.h:121
virtual void GetLowEdge(Double_t *edge) const
Return an array with the low edge of all bins.
Definition: TAxis.cxx:548
virtual void SetRange(Int_t first=0, Int_t last=0)
Set the viewing range for the axis from bin first to last.
Definition: TAxis.cxx:903
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width.
Definition: TAxis.cxx:526
virtual Double_t GetBinUpEdge(Int_t bin) const
Return up edge of bin.
Definition: TAxis.cxx:514
Int_t GetFirst() const
Return first bin on the axis i.e.
Definition: TAxis.cxx:444
THashList * GetLabels() const
Definition: TAxis.h:117
Using a TBrowser one can browse all ROOT objects.
Definition: TBrowser.h:37
Buffer base class used for serializing objects.
Definition: TBuffer.h:40
Collection abstract base class.
Definition: TCollection.h:63
virtual bool UseRWLock()
Set this collection to use a RW lock upon access, making it thread safe.
virtual TObject * Clone(const char *newname="") const
Make a clone of an collection using the Streamer facility.
virtual Bool_t IsEmpty() const
Definition: TCollection.h:186
virtual Int_t GetSize() const
Return the capacity of the collection, i.e.
Definition: TCollection.h:182
Describe directory structure in memory.
Definition: TDirectory.h:34
virtual void Append(TObject *obj, Bool_t replace=kFALSE)
Append object to this directory.
Definition: TDirectory.cxx:190
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:491
1-Dim function class
Definition: TF1.h:211
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:3644
virtual TH1 * GetHistogram() const
Return a pointer to the histogram used to visualise the function.
Definition: TF1.cxx:1559
virtual Int_t GetNpar() const
Definition: TF1.h:465
virtual Double_t Integral(Double_t a, Double_t b, Double_t epsrel=1.e-12)
IntegralOneDim or analytical integral.
Definition: TF1.cxx:2496
virtual Double_t EvalPar(const Double_t *x, const Double_t *params=0)
Evaluate function with given coordinates and parameters.
Definition: TF1.cxx:1453
virtual void InitArgs(const Double_t *x, const Double_t *params)
Initialize parameters addresses.
Definition: TF1.cxx:2448
virtual void GetRange(Double_t *xmin, Double_t *xmax) const
Return range of a generic N-D function.
Definition: TF1.cxx:2257
virtual void SetParLimits(Int_t ipar, Double_t parmin, Double_t parmax)
Set limits for parameter ipar.
Definition: TF1.cxx:3491
static Bool_t RejectedPoint()
See TF1::RejectPoint above.
Definition: TF1.cxx:3653
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:1424
virtual void SetParameter(Int_t param, Double_t value)
Definition: TF1.h:618
virtual Bool_t IsInside(const Double_t *x) const
return kTRUE if the point is inside the function range
Definition: TF1.h:582
A 2-Dim function with parameters.
Definition: TF2.h:29
A 3-Dim function with parameters.
Definition: TF3.h:28
Provides an indirection to the TFitResult class and with a semantics identical to a TFitResult pointe...
Definition: TFitResultPtr.h:31
1-D histogram with a byte per channel (see TH1 documentation)
Definition: TH1.h:448
TH1C & operator=(const TH1C &h1)
Operator =.
Definition: TH1.cxx:8904
TH1C()
Constructor.
Definition: TH1.cxx:8794
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:8876
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:8894
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:8857
virtual ~TH1C()
Destructor.
Definition: TH1.cxx:8842
virtual void Reset(Option_t *option="")
Reset.
Definition: TH1.cxx:8884
1-D histogram with a double per channel (see TH1 documentation)}
Definition: TH1.h:614
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9597
virtual ~TH1D()
Destructor.
Definition: TH1.cxx:9582
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9615
TH1D()
Constructor.
Definition: TH1.cxx:9517
TH1D & operator=(const TH1D &h1)
Operator =.
Definition: TH1.cxx:9625
1-D histogram with a float per channel (see TH1 documentation)}
Definition: TH1.h:571
virtual Double_t RetrieveBinContent(Int_t bin) const
Raw retrieval of bin content on internal data structure see convention for numbering bins in TH1::Get...
Definition: TH1.h:600
virtual ~TH1F()
Destructor.
Definition: TH1.cxx:9411
TH1F & operator=(const TH1F &h1)
Operator =.
Definition: TH1.cxx:9446
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9436
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9418
TH1F()
Constructor.
Definition: TH1.cxx:9338
1-D histogram with an int per channel (see TH1 documentation)}
Definition: TH1.h:530
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9238
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:9219
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9256
virtual ~TH1I()
Destructor.
Definition: TH1.cxx:9204
TH1I()
Constructor.
Definition: TH1.cxx:9156
TH1I & operator=(const TH1I &h1)
Operator =.
Definition: TH1.cxx:9266
1-D histogram with a short per channel (see TH1 documentation)
Definition: TH1.h:489
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:9038
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9075
virtual ~TH1S()
Destructor.
Definition: TH1.cxx:9023
TH1S & operator=(const TH1S &h1)
Operator =.
Definition: TH1.cxx:9085
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9057
TH1S()
Constructor.
Definition: TH1.cxx:8975
The TH1 histogram class.
Definition: TH1.h:56
virtual void SetError(const Double_t *error)
Replace bin errors by values in array error.
Definition: TH1.cxx:8273
virtual void SetDirectory(TDirectory *dir)
By default when an histogram is created, it is added to the list of histogram objects in the current ...
Definition: TH1.cxx:8259
virtual void FitPanel()
Display a panel with all histogram fit options.
Definition: TH1.cxx:4046
Double_t * fBuffer
[fBufferSize] entry buffer
Definition: TH1.h:105
virtual Int_t AutoP2FindLimits(Double_t min, Double_t max)
Buffer-based estimate of the histogram range using the power of 2 algorithm.
Definition: TH1.cxx:1275
virtual Double_t GetEffectiveEntries() const
Number of effective entries of the histogram.
Definition: TH1.cxx:4210
virtual void SavePrimitive(std::ostream &out, Option_t *option="")
Save primitive as a C++ statement(s) on output stream out.
Definition: TH1.cxx:6661
virtual void SetTitle(const char *title)
See GetStatOverflows for more information.
Definition: TH1.cxx:6217
virtual void Smooth(Int_t ntimes=1, Option_t *option="")
Smooth bin contents of this histogram.
Definition: TH1.cxx:6384
virtual void Print(Option_t *option="") const
Print some global quantities for this histogram.
Definition: TH1.cxx:6514
virtual Double_t GetBinCenter(Int_t bin) const
Return bin center for 1D histogram.
Definition: TH1.cxx:8462
virtual void Rebuild(Option_t *option="")
Using the current bin info, recompute the arrays for contents and errors.
Definition: TH1.cxx:6592
static Bool_t fgStatOverflows
!flag to use under/overflows in statistics
Definition: TH1.h:114
TAxis * GetZaxis()
Definition: TH1.h:318
virtual Bool_t Multiply(TF1 *f1, Double_t c1=1)
Performs the operation:
Definition: TH1.cxx:5542
virtual void Browse(TBrowser *b)
Browse the Histogram object.
Definition: TH1.cxx:713
Int_t fNcells
number of bins(1D), cells (2D) +U/Overflows
Definition: TH1.h:86
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:7216
virtual void FillRandom(const char *fname, Int_t ntimes=5000)
Fill histogram following distribution in function fname.
Definition: TH1.cxx:3421
Double_t fTsumw
Total Sum of weights.
Definition: TH1.h:93
virtual Float_t GetBarWidth() const
Definition: TH1.h:252
Double_t fTsumw2
Total Sum of squares of weights.
Definition: TH1.h:94
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:6430
virtual Float_t GetBarOffset() const
Definition: TH1.h:251
virtual ~TH1()
Histogram default destructor.
Definition: TH1.cxx:578
TList * fFunctions
->Pointer to list of functions (fits and user)
Definition: TH1.h:103
static Bool_t fgAddDirectory
!flag to add histograms to the directory
Definition: TH1.h:113
virtual Int_t GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum=0)
Compute Quantiles for this histogram Quantile x_q of a probability distribution Function F is defined...
Definition: TH1.cxx:4342
@ kXaxis
Definition: TH1.h:70
@ kNoAxis
NOTE: Must always be 0 !!!
Definition: TH1.h:69
@ kZaxis
Definition: TH1.h:72
@ kYaxis
Definition: TH1.h:71
static Int_t GetDefaultBufferSize()
Static function return the default buffer size for automatic histograms the parameter fgBufferSize ma...
Definition: TH1.cxx:4168
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:7357
Double_t fTsumwx2
Total Sum of weight*X*X.
Definition: TH1.h:96
virtual Double_t GetStdDev(Int_t axis=1) const
Returns the Standard Deviation (Sigma).
Definition: TH1.cxx:7012
TH1()
Histogram default constructor.
Definition: TH1.cxx:550
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:8640
virtual void LabelsOption(Option_t *option="h", Option_t *axis="X")
Set option(s) to draw axis with labels.
Definition: TH1.cxx:5105
virtual Int_t GetNbinsY() const
Definition: TH1.h:293
Short_t fBarOffset
(1000*offset) for bar charts or legos
Definition: TH1.h:90
static bool CheckBinLimits(const TAxis *a1, const TAxis *a2)
Check bin limits.
Definition: TH1.cxx:1471
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:1200
virtual Double_t GetBinError(Int_t bin) const
Return value of error associated to bin number bin.
Definition: TH1.cxx:8384
static Int_t FitOptionsMake(Option_t *option, Foption_t &Foption)
Decode string choptin and fill fitOption structure.
Definition: TH1.cxx:4383
virtual Int_t GetNbinsZ() const
Definition: TH1.h:294
virtual Double_t GetNormFactor() const
Definition: TH1.h:296
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:6958
virtual Double_t GetSkewness(Int_t axis=1) const
Definition: TH1.cxx:7063
virtual void ClearUnderflowAndOverflow()
Remove all the content from the underflow and overflow bins, without changing the number of entries A...
Definition: TH1.cxx:2448
virtual Double_t GetContourLevelPad(Int_t level) const
Return the value of contour number "level" in Pad coordinates.
Definition: TH1.cxx:7770
virtual TH1 * DrawNormalized(Option_t *option="", Double_t norm=1) const
Draw a normalized copy of this histogram.
Definition: TH1.cxx:3051
virtual Double_t Chi2TestX(const TH1 *h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option="UU", Double_t *res=0) const
The computation routine of the Chisquare test.
Definition: TH1.cxx:2001
virtual Int_t GetDimension() const
Definition: TH1.h:278
static void AddDirectory(Bool_t add=kTRUE)
Sets the flag controlling the automatic add of histograms in memory.
Definition: TH1.cxx:1225
@ kIsAverage
Bin contents are average (used by Add)
Definition: TH1.h:166
@ kUserContour
user specified contour levels
Definition: TH1.h:161
@ kNoStats
don't draw stats box
Definition: TH1.h:160
@ kAutoBinPTwo
Use Power(2)-based algorithm for autobinning.
Definition: TH1.h:169
@ kIsNotW
Histogram is forced to be not weighted even when the histogram is filled with weighted different than...
Definition: TH1.h:167
@ kIsHighlight
bit set if histo is highlight
Definition: TH1.h:170
virtual Double_t GetRandom() const
Return a random number distributed according the histogram bin contents.
Definition: TH1.cxx:4739
virtual void SetContourLevel(Int_t level, Double_t value)
Set value for one contour level.
Definition: TH1.cxx:7852
virtual Bool_t CanExtendAllAxes() const
Returns true if all axes are extendable.
Definition: TH1.cxx:6150
TDirectory * fDirectory
!Pointer to directory holding this histogram
Definition: TH1.h:106
virtual void Reset(Option_t *option="")
Reset this histogram: contents, errors, etc.
Definition: TH1.cxx:6608
TAxis * GetXaxis()
Get the behaviour adopted by the object about the statoverflows. See EStatOverflows for more informat...
Definition: TH1.h:316
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:4705
TH1 * GetCumulative(Bool_t forward=kTRUE, const char *suffix="_cumulative") const
Return a pointer to an histogram containing the cumulative The cumulative can be computed both in the...
Definition: TH1.cxx:2537
void UseCurrentStyle()
Copy current attributes from/to current style.
Definition: TH1.cxx:6894
static Double_t AutoP2GetPower2(Double_t x, Bool_t next=kTRUE)
Auxilliary function to get the power of 2 next (larger) or previous (smaller) a given x.
Definition: TH1.cxx:1239
virtual Int_t GetNcells() const
Definition: TH1.h:295
virtual Int_t ShowPeaks(Double_t sigma=2, Option_t *option="", Double_t threshold=0.05)
Interface to TSpectrum::Search.
Definition: TH1.cxx:8622
static Bool_t RecomputeAxisLimits(TAxis &destAxis, const TAxis &anAxis)
Finds new limits for the axis for the Merge function.
Definition: TH1.cxx:5401
virtual void PutStats(Double_t *stats)
Replace current statistics with the values in array stats.
Definition: TH1.cxx:7267
TVirtualHistPainter * GetPainter(Option_t *option="")
Return pointer to painter.
Definition: TH1.cxx:4251
TObject * Clone(const char *newname=0) const
Make a complete copy of the underlying object.
Definition: TH1.cxx:2657
static Bool_t GetDefaultSumw2()
Return kTRUE if TH1::Sumw2 must be called when creating new histograms.
Definition: TH1.cxx:4177
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:3695
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:4692
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:7872
virtual Int_t GetNbinsX() const
Definition: TH1.h:292
virtual void SetMaximum(Double_t maximum=-1111)
Definition: TH1.h:394
virtual TH1 * FFT(TH1 *h_output, Option_t *option)
This function allows to do discrete Fourier transforms of TH1 and TH2.
Definition: TH1.cxx:3191
virtual void LabelsInflate(Option_t *axis="X")
Double the number of bins for axis.
Definition: TH1.cxx:5044
virtual TH1 * ShowBackground(Int_t niter=20, Option_t *option="same")
This function calculates the background spectrum in this histogram.
Definition: TH1.cxx:8607
virtual Double_t Chi2Test(const TH1 *h2, Option_t *option="UU", Double_t *res=0) const
test for comparing weighted and unweighted histograms
Definition: TH1.cxx:1942
static Bool_t SameLimitsAndNBins(const TAxis &axis1, const TAxis &axis2)
Same limits and bins.
Definition: TH1.cxx:5390
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:777
Double_t fMaximum
Maximum value for plotting.
Definition: TH1.h:97
Int_t fBufferSize
fBuffer size
Definition: TH1.h:104
virtual void RecursiveRemove(TObject *obj)
Recursively remove object from the list of functions.
Definition: TH1.cxx:6098
virtual Double_t RetrieveBinContent(Int_t bin) const
Raw retrieval of bin content on internal data structure see convention for numbering bins in TH1::Get...
Definition: TH1.cxx:8760
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:7348
Int_t fDimension
!Histogram dimension (1, 2 or 3 dim)
Definition: TH1.h:107
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:8526
EBinErrorOpt fBinStatErrOpt
option for bin statistical errors
Definition: TH1.h:110
static Int_t fgBufferSize
!default buffer size for automatic histograms
Definition: TH1.h:112
virtual void SetBinsLength(Int_t=-1)
Definition: TH1.h:371
Double_t fNormFactor
Normalization factor.
Definition: TH1.h:99
virtual Int_t Fill(Double_t x)
Increment bin with abscissa X by 1.
Definition: TH1.cxx:3251
virtual TObject * FindObject(const char *name) const
Search object named name in the list of functions.
Definition: TH1.cxx:3668
TAxis * GetYaxis()
Definition: TH1.h:317
TArrayD fContour
Array to display contour levels.
Definition: TH1.h:100
virtual Double_t GetBinErrorLow(Int_t bin) const
Return lower error associated to bin number bin.
Definition: TH1.cxx:8400
virtual void SetContent(const Double_t *content)
Replace bin contents by the contents of array content.
Definition: TH1.cxx:7728
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:6803
Short_t fBarWidth
(1000*width) for bar charts or legos
Definition: TH1.h:91
virtual void SetContour(Int_t nlevels, const Double_t *levels=0)
Set the number and values of contour levels.
Definition: TH1.cxx:7813
virtual Double_t GetBinErrorSqUnchecked(Int_t bin) const
Definition: TH1.h:439
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:395
Bool_t IsBinUnderflow(Int_t bin, Int_t axis=0) const
Return true if the bin is underflow.
Definition: TH1.cxx:4943
static bool CheckBinLabels(const TAxis *a1, const TAxis *a2)
Check that axis have same labels.
Definition: TH1.cxx:1497
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:6202
Bool_t IsBinOverflow(Int_t bin, Int_t axis=0) const
Return true if the bin is overflow.
Definition: TH1.cxx:4911
Double_t * fIntegral
!Integral of bins used by GetRandom
Definition: TH1.h:108
Double_t fMinimum
Minimum value for plotting.
Definition: TH1.h:98
virtual Double_t Integral(Option_t *option="") const
Return integral of bin contents.
Definition: TH1.cxx:7321
virtual void SetBarWidth(Float_t width=0.5)
Definition: TH1.h:356
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:8542
virtual void DirectoryAutoAdd(TDirectory *)
Perform the automatic addition of the histogram to the given directory.
Definition: TH1.cxx:2690
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:8508
virtual Double_t GetBinLowEdge(Int_t bin) const
Return bin lower edge for 1D histogram.
Definition: TH1.cxx:8473
void Build()
Creates histogram basic data structure.
Definition: TH1.cxx:722
virtual Int_t FindLastBinAbove(Double_t threshold=0, Int_t axis=1) const
Find last bin with content > threshold for axis (1=x, 2=y, 3=z) if no bins with content > threshold i...
Definition: TH1.cxx:3650
virtual Double_t GetEntries() const
Return the current number of entries.
Definition: TH1.cxx:4185
virtual TF1 * GetFunction(const char *name) const
Return pointer to function with name.
Definition: TH1.cxx:8372
virtual Int_t BufferFill(Double_t x, Double_t w)
accumulate arguments in buffer.
Definition: TH1.cxx:1436
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:4815
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:6163
TList * GetListOfFunctions() const
Definition: TH1.h:239
virtual TH1 * DrawCopy(Option_t *option="", const char *name_postfix="_copy") const
Copy this histogram and Draw in the current pad.
Definition: TH1.cxx:3021
virtual void Copy(TObject &hnew) const
Copy this histogram structure to newth1.
Definition: TH1.cxx:2580
virtual Int_t FindFirstBinAbove(Double_t threshold=0, Int_t axis=1) const
Find first bin with content > threshold for axis (1=x, 2=y, 3=z) if no bins with content > threshold ...
Definition: TH1.cxx:3631
Bool_t IsEmpty() const
Check if an histogram is empty (this a protected method used mainly by TH1Merger )
Definition: TH1.cxx:4893
virtual Double_t GetMeanError(Int_t axis=1) const
Return standard error of mean of this histogram along the X axis.
Definition: TH1.cxx:6989
virtual void Draw(Option_t *option="")
Draw this histogram with options.
Definition: TH1.cxx:2974
virtual void SetBarOffset(Float_t offset=0.25)
Definition: TH1.h:355
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:7441
virtual void ResetStats()
Reset the statistics including the number of entries and replace with values calculates from bin cont...
Definition: TH1.cxx:7282
static void SetDefaultBufferSize(Int_t buffersize=1000)
Static function to set the default buffer size for automatic histograms.
Definition: TH1.cxx:6192
virtual void SetBinErrorOption(EBinErrorOpt type)
Definition: TH1.h:372
virtual void SetBuffer(Int_t buffersize, Option_t *option="")
Set the maximum number of entries to be kept in the buffer.
Definition: TH1.cxx:7788
virtual void DrawPanel()
Display a panel with all histogram drawing options.
Definition: TH1.cxx:3082
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:2429
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:3380
virtual void GetMinimumAndMaximum(Double_t &min, Double_t &max) const
Retrieve the minimum and maximum values in the histogram.
Definition: TH1.cxx:8053
virtual Int_t GetMaximumBin() const
Return location of bin with maximum value in the range.
Definition: TH1.cxx:7902
static Int_t AutoP2GetBins(Int_t n)
Auxilliary function to get the next power of 2 integer value larger then n.
Definition: TH1.cxx:1252
Double_t fEntries
Number of entries.
Definition: TH1.h:92
virtual Long64_t Merge(TCollection *list)
Definition: TH1.h:337
virtual void SetName(const char *name)
Change the name of this histogram.
Definition: TH1.cxx:8282
virtual Double_t * GetIntegral()
Return a pointer to the array of bins integral.
Definition: TH1.cxx:2515
TAxis fZaxis
Z axis descriptor.
Definition: TH1.h:89
EStatOverflows fStatOverflows
per object flag to use under/overflows in statistics
Definition: TH1.h:111
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:3354
virtual void UpdateBinContent(Int_t bin, Double_t content)
Raw update of bin content on internal data structure see convention for numbering bins in TH1::GetBin...
Definition: TH1.cxx:8770
static bool CheckEqualAxes(const TAxis *a1, const TAxis *a2)
Check that the axis are the same.
Definition: TH1.cxx:1542
@ kPoisson2
errors from Poisson interval at 95% CL (~ 2 sigma)
Definition: TH1.h:64
@ kNormal
errors with Normal (Wald) approximation: errorUp=errorLow= sqrt(N)
Definition: TH1.h:62
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
Definition: TH1.cxx:4790
TAxis fXaxis
X axis descriptor.
Definition: TH1.h:87
virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py)
Execute action corresponding to one event.
Definition: TH1.cxx:3147
virtual Bool_t IsHighlight() const
Definition: TH1.h:330
virtual Double_t Interpolate(Double_t x)
Given a point x, approximates the value via linear interpolation based on the two nearest bin centers...
Definition: TH1.cxx:4844
virtual void ExtendAxis(Double_t x, TAxis *axis)
Histogram is resized along axis such that x is in the axis range.
Definition: TH1.cxx:6026
virtual void SetNameTitle(const char *name, const char *title)
Change the name and title of this histogram.
Definition: TH1.cxx:8296
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width for 1D histogram.
Definition: TH1.cxx:8484
static bool CheckConsistency(const TH1 *h1, const TH1 *h2)
Check histogram compatibility.
Definition: TH1.cxx:1613
TArrayD fSumw2
Array of sum of squares of weights.
Definition: TH1.h:101
TH1 * GetAsymmetry(TH1 *h2, Double_t c2=1, Double_t dc2=0)
Return an histogram containing the asymmetry of this histogram with h2, where the asymmetry is define...
Definition: TH1.cxx:4101
virtual Double_t GetContourLevel(Int_t level) const
Return value of contour number level.
Definition: TH1.cxx:7760
virtual void SetHighlight(Bool_t set=kTRUE)
Set highlight (enable/disable) mode for the histogram by default highlight mode is disable.
Definition: TH1.cxx:4221
virtual Double_t GetBinErrorUp(Int_t bin) const
Return upper error associated to bin number bin.
Definition: TH1.cxx:8431
virtual void Scale(Double_t c1=1, Option_t *option="")
Multiply this histogram by a constant c1.
Definition: TH1.cxx:6126
virtual void Paint(Option_t *option="")
Control routine to paint any kind of histograms.
Definition: TH1.cxx:5717
virtual Int_t GetMinimumBin() const
Return location of bin with minimum value in the range.
Definition: TH1.cxx:7987
virtual Int_t GetSumw2N() const
Definition: TH1.h:310
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:3572
Bool_t GetStatOverflowsBehaviour() const
Definition: TH1.h:148
virtual Double_t GetStdDevError(Int_t axis=1) const
Return error of standard deviation estimation for Normal distribution.
Definition: TH1.cxx:7050
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:2729
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:7957
static bool CheckConsistentSubAxes(const TAxis *a1, Int_t firstBin1, Int_t lastBin1, const TAxis *a2, Int_t firstBin2=0, Int_t lastBin2=0)
Check that two sub axis are the same.
Definition: TH1.cxx:1578
TAxis fYaxis
Y axis descriptor.
Definition: TH1.h:88
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:7555
virtual Double_t GetSumOfWeights() const
Return the sum of weights excluding under/overflows.
Definition: TH1.cxx:7297
static void SmoothArray(Int_t NN, Double_t *XX, Int_t ntimes=1)
Smooth array xx, translation of Hbook routine hsmoof.F based on algorithm 353QH twice presented by J.
Definition: TH1.cxx:6266
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:8495
TVirtualHistPainter * fPainter
!pointer to histogram painter
Definition: TH1.h:109
virtual void SetBins(Int_t nx, Double_t xmin, Double_t xmax)
Redefine x axis parameters.
Definition: TH1.cxx:8089
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:3605
virtual char * GetObjectInfo(Int_t px, Int_t py) const
Redefines TObject::GetObjectInfo.
Definition: TH1.cxx:4242
virtual void Sumw2(Bool_t flag=kTRUE)
Create structure to store sum of squares of weights.
Definition: TH1.cxx:8341
virtual void SetEntries(Double_t n)
Definition: TH1.h:381
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:5969
static bool CheckAxisLimits(const TAxis *a1, const TAxis *a2)
Check that the axis limits of the histograms are the same.
Definition: TH1.cxx:1529
static Bool_t AddDirectoryStatus()
Static function: cannot be inlined on Windows/NT.
Definition: TH1.cxx:705
static Bool_t fgDefaultSumw2
!flag to call TH1::Sumw2 automatically at histogram creation time
Definition: TH1.h:115
virtual Int_t DistancetoPrimitive(Int_t px, Int_t py)
Compute distance from point px,py to a line.
Definition: TH1.cxx:2712
Double_t fTsumwx
Total Sum of weight*X.
Definition: TH1.h:95
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:4974
virtual Double_t ComputeIntegral(Bool_t onlyPositive=false)
Compute integral (cumulative sum of bins) The result stored in fIntegral is used by the GetRandom fun...
Definition: TH1.cxx:2467
@ kNstat
Definition: TH1.h:179
TString fOption
histogram options
Definition: TH1.h:102
virtual Int_t GetContour(Double_t *levels=0)
Return contour values into array levels if pointer levels is non zero.
Definition: TH1.cxx:7741
virtual void Eval(TF1 *f1, Option_t *option="")
Evaluate function f1 at the center of bins of this histogram.
Definition: TH1.cxx:3099
virtual Int_t BufferEmpty(Int_t action=0)
Fill histogram with all entries in the buffer.
Definition: TH1.cxx:1346
virtual void SetStats(Bool_t stats=kTRUE)
Set statistics option on/off.
Definition: TH1.cxx:8312
virtual TH1 * Rebin(Int_t ngroup=2, const char *newname="", const Double_t *xbins=0)
Rebin this histogram.
Definition: TH1.cxx:5784
virtual Double_t GetKurtosis(Int_t axis=1) const
Definition: TH1.cxx:7133
2-D histogram with a double per channel (see TH1 documentation)}
Definition: TH2.h:291
static THLimitsFinder * GetLimitsFinder()
Return pointer to the current finder.
virtual Int_t FindGoodLimits(TH1 *h, Double_t xmin, Double_t xmax)
Compute the best axis limits for the X axis.
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="")
Remove all objects from the list.
Definition: THashList.cxx:189
A doubly linked list.
Definition: TList.h:44
virtual void Add(TObject *obj)
Definition: TList.h:87
virtual TObject * Remove(TObject *obj)
Remove object from the list.
Definition: TList.cxx:818
virtual TObject * FindObject(const char *name) const
Delete a TObjLink object.
Definition: TList.cxx:574
virtual TObjLink * FirstLink() const
Definition: TList.h:108
virtual TObject * At(Int_t idx) const
Returns the object at position idx. Returns 0 if idx is out of range.
Definition: TList.cxx:354
virtual void RecursiveRemove(TObject *obj)
Remove object from this collection and recursively remove the object from all other objects (and coll...
Definition: TList.cxx:760
virtual void Delete(Option_t *option="")
Remove all objects from the list AND delete all heap based objects.
Definition: TList.cxx:467
virtual TObject * First() const
Return the first object in the list. Returns 0 when list is empty.
Definition: TList.cxx:655
The TNamed class is the base class for all named ROOT classes.
Definition: TNamed.h:29
virtual void Copy(TObject &named) const
Copy this to obj.
Definition: TNamed.cxx:94
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition: TNamed.cxx:164
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:140
virtual const char * GetTitle() const
Returns title of object.
Definition: TNamed.h:48
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:47
Mother of all ROOT objects.
Definition: TObject.h:37
void AbstractMethod(const char *method) const
Use this method to implement an "abstract" method that you don't want to leave purely abstract.
Definition: TObject.cxx:922
@ kNotDeleted
object has not been deleted
Definition: TObject.h:78
virtual const char * GetName() const
Returns name of object.
Definition: TObject.cxx:357
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition: TObject.h:172
virtual UInt_t GetUniqueID() const
Return the unique object id.
Definition: TObject.cxx:375
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition: TObject.cxx:128
virtual void UseCurrentStyle()
Set current style settings in this object This function is called when either TCanvas::UseCurrentStyl...
Definition: TObject.cxx:715
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:866
virtual void AppendPad(Option_t *option="")
Append graphics object to current pad.
Definition: TObject.cxx:105
virtual void SavePrimitive(std::ostream &out, Option_t *option="")
Save a primitive as a C++ statement(s) on output stream "out".
Definition: TObject.cxx:664
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition: TObject.cxx:694
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition: TObject.cxx:443
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:880
virtual void SetUniqueID(UInt_t uid)
Set the unique object id.
Definition: TObject.cxx:705
void ResetBit(UInt_t f)
Definition: TObject.h:171
@ kCanDelete
if object in a list can be deleted
Definition: TObject.h:58
@ kInvalidObject
if object ctor succeeded but object should not be used
Definition: TObject.h:68
@ kMustCleanup
if object destructor must call RecursiveRemove()
Definition: TObject.h:60
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition: TObject.cxx:854
Long_t ExecPlugin(int nargs, const T &... params)
Int_t LoadPlugin()
Load the plugin library for this handler.
virtual Int_t Poisson(Double_t mean)
Generates a random integer N according to a Poisson law.
Definition: TRandom.cxx:383
virtual Double_t PoissonD(Double_t mean)
Generates a random number according to a Poisson law.
Definition: TRandom.cxx:435
virtual Double_t Rndm()
Machine independent random number generator.
Definition: TRandom.cxx:533
Basic string class.
Definition: TString.h:131
Ssiz_t Length() const
Definition: TString.h:405
void ToLower()
Change string to lower-case.
Definition: TString.cxx:1100
const char * Data() const
Definition: TString.h:364
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition: TString.h:687
void ToUpper()
Change string to upper case.
Definition: TString.cxx:1113
Bool_t IsNull() const
Definition: TString.h:402
TString & Remove(Ssiz_t pos)
Definition: TString.h:668
TString & Append(const char *cs)
Definition: TString.h:559
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:2286
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition: TString.cxx:2264
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:619
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition: TString.h:634
Int_t GetOptStat() const
Definition: TStyle.h:232
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:1444
void SetHistFillColor(Color_t color=1)
Definition: TStyle.h:356
Color_t GetHistLineColor() const
Definition: TStyle.h:220
Bool_t IsReading() const
Definition: TStyle.h:277
Float_t GetBarOffset() const
Definition: TStyle.h:170
void SetHistLineStyle(Style_t styl=0)
Definition: TStyle.h:359
Style_t GetHistFillStyle() const
Definition: TStyle.h:221
Color_t GetHistFillColor() const
Definition: TStyle.h:219
Float_t GetBarWidth() const
Definition: TStyle.h:171
Bool_t GetCanvasPreferGL() const
Definition: TStyle.h:175
void SetHistLineColor(Color_t color=1)
Definition: TStyle.h:357
void SetBarOffset(Float_t baroff=0.5)
Definition: TStyle.h:313
Style_t GetHistLineStyle() const
Definition: TStyle.h:222
void SetBarWidth(Float_t barwidth=0.5)
Definition: TStyle.h:314
void SetHistFillStyle(Style_t styl=0)
Definition: TStyle.h:358
Width_t GetHistLineWidth() const
Definition: TStyle.h:223
Int_t GetOptFit() const
Definition: TStyle.h:231
void SetHistLineWidth(Width_t width=1)
Definition: TStyle.h:360
TVectorT.
Definition: TVectorT.h:27
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.
virtual Int_t GetNdim() const =0
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.
virtual Option_t * GetType() const =0
virtual void Transform()=0
virtual void GetPointComplex(Int_t ipoint, Double_t &re, Double_t &im, Bool_t fromInput=kFALSE) const =0
virtual Int_t * GetN() const =0
virtual Double_t GetPointReal(Int_t ipoint, Bool_t fromInput=kFALSE) const =0
virtual void SetPoint(Int_t ipoint, Double_t re, Double_t im=0)=0
Abstract Base Class for Fitting.
virtual Int_t GetXlast() const
virtual TObject * GetObjectFit() const
virtual Int_t GetXfirst() const
static TVirtualFitter * GetFitter()
static: return the current Fitter
virtual TObject * GetUserFunc() const
Abstract interface to a histogram painter.
virtual void DrawPanel()=0
virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py)=0
Execute action corresponding to an event at (px,py).
virtual void Paint(Option_t *option="")=0
This method must be overridden if a class wants to paint itself.
virtual Int_t DistancetoPrimitive(Int_t px, Int_t py)=0
Computes distance from point (px,py) to the object.
virtual void SetHighlight()=0
static TVirtualHistPainter * HistPainter(TH1 *obj)
Static function returning a pointer to the current histogram painter.
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
return c1
Definition: legend1.C:41
Double_t y[n]
Definition: legend1.C:17
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
TFitResultPtr FitObject(TH1 *h1, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption, const char *goption, ROOT::Fit::DataRange &range)
fitting function for a TH1 (called from TH1::Fit)
Definition: HFitImpl.cxx:964
void FitOptionsMake(EFitObjectType type, const char *option, Foption_t &fitOption)
Decode list of options into fitOption.
Definition: HFitImpl.cxx:681
void FillData(BinData &dv, const TH1 *hist, TF1 *func=0)
fill the data vector from a TH1.
double Chisquare(const TH1 &h1, TF1 &f1, bool useRange, bool usePL=false)
compute the chi2 value for an histogram given a function (see TH1::Chisquare for the documentation)
Definition: HFitImpl.cxx:1018
R__EXTERN TVirtualRWMutex * gCoreMutex
static constexpr double s
void forward(const LAYERDATA &prevLayerData, LAYERDATA &currLayerData)
apply the weights (and functions) in forward direction of the DNN
Definition: NeuralNet.icc:544
Bool_t IsNaN(Double_t x)
Definition: TMath.h:880
Int_t Nint(T x)
Round to nearest integer. Rounds half integers to the nearest even integer.
Definition: TMath.h:701
Short_t Max(Short_t a, Short_t b)
Definition: TMathBase.h:212
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:621
Double_t QuietNaN()
Returns a quiet NaN as defined by IEEE 754
Definition: TMath.h:889
Double_t Floor(Double_t x)
Definition: TMath.h:691
Double_t ATan(Double_t)
Definition: TMath.h:663
Double_t Ceil(Double_t x)
Definition: TMath.h:683
T MinElement(Long64_t n, const T *a)
Return minimum of array a of length n.
Definition: TMath.h:940
constexpr Double_t E()
Base of natural log:
Definition: TMath.h:97
Double_t Log(Double_t x)
Definition: TMath.h:748
Double_t Sqrt(Double_t x)
Definition: TMath.h:679
LongDouble_t Power(LongDouble_t x, LongDouble_t y)
Definition: TMath.h:723
Short_t Min(Short_t a, Short_t b)
Definition: TMathBase.h:180
constexpr Double_t Pi()
Definition: TMath.h:38
Bool_t AreEqualRel(Double_t af, Double_t bf, Double_t relPrec)
Definition: TMath.h:416
Bool_t AreEqualAbs(Double_t af, Double_t bf, Double_t epsilon)
Definition: TMath.h:412
Double_t KolmogorovProb(Double_t z)
Calculates the Kolmogorov distribution function,.
Definition: TMath.cxx:663
void Sort(Index n, const Element *a, Index *index, Bool_t down=kTRUE)
Definition: TMathBase.h:362
Double_t Median(Long64_t n, const T *a, const Double_t *w=0, Long64_t *work=0)
Return the median of the array a where each entry i has weight w[i] .
Definition: TMath.h:1235
Long64_t BinarySearch(Long64_t n, const T *array, T value)
Definition: TMathBase.h:278
Double_t Log10(Double_t x)
Definition: TMath.h:752
Short_t Abs(Short_t d)
Definition: TMathBase.h:120
Double_t Infinity()
Returns an infinity as defined by the IEEE standard.
Definition: TMath.h:902
std::string printValue(const TDatime *val)
Print a TDatime at the prompt.
Definition: TDatime.cxx:514
Definition: first.py:1
auto * m
Definition: textangle.C:8
auto * l
Definition: textangle.C:4
auto * a
Definition: textangle.C:12
static long int sum(long int i)
Definition: Factory.cxx:2258
REAL epsilon
Definition: triangle.c:617