Logo ROOT   6.12/06
Reference Guide
TH1.cxx
Go to the documentation of this file.
1 // @(#)root/hist:$Id$
2 // Author: Rene Brun 26/12/94
3 
4 /*************************************************************************
5  * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
6  * All rights reserved. *
7  * *
8  * For the licensing terms see $ROOTSYS/LICENSE. *
9  * For the list of contributors see $ROOTSYS/README/CREDITS. *
10  *************************************************************************/
11 
12 #include <stdlib.h>
13 #include <string.h>
14 #include <stdio.h>
15 #include <ctype.h>
16 #include <sstream>
17 #include <cmath>
18 
19 #include "Riostream.h"
20 #include "TROOT.h"
21 #include "TEnv.h"
22 #include "TClass.h"
23 #include "TMath.h"
24 #include "THashList.h"
25 #include "TH1.h"
26 #include "TH2.h"
27 #include "TH3.h"
28 #include "TF2.h"
29 #include "TF3.h"
30 #include "TPluginManager.h"
31 #include "TVirtualPad.h"
32 #include "TRandom.h"
33 #include "TVirtualFitter.h"
34 #include "THLimitsFinder.h"
35 #include "TProfile.h"
36 #include "TStyle.h"
37 #include "TVectorF.h"
38 #include "TVectorD.h"
39 #include "TBrowser.h"
40 #include "TObjString.h"
41 #include "TError.h"
42 #include "TVirtualHistPainter.h"
43 #include "TVirtualFFT.h"
44 #include "TSystem.h"
45 
46 #include "HFitInterface.h"
47 #include "Fit/DataRange.h"
48 #include "Fit/BinData.h"
49 #include "Math/GoFTest.h"
50 #include "Math/MinimizerOptions.h"
51 #include "Math/QuantFuncMathCore.h"
52 
53 #include "TH1Merger.h"
54 
55 /** \addtogroup Hist
56 @{
57 \class TH1C
58 \brief 1-D histogram with a byte per channel (see TH1 documentation)
59 \class TH1S
60 \brief 1-D histogram with a short per channel (see TH1 documentation)
61 \class TH1I
62 \brief 1-D histogram with an int per channel (see TH1 documentation)}
63 \class TH1F
64 \brief 1-D histogram with a float per channel (see TH1 documentation)}
65 \class TH1D
66 \brief 1-D histogram with a double per channel (see TH1 documentation)}
67 @}
68 */
69 
70 /** \class TH1
71 The TH1 histogram class.
72 
73 ### The Histogram classes
74 ROOT supports the following histogram types:
75 
76  - 1-D histograms:
77  - TH1C : histograms with one byte per channel. Maximum bin content = 127
78  - TH1S : histograms with one short per channel. Maximum bin content = 32767
79  - TH1I : histograms with one int per channel. Maximum bin content = 2147483647
80  - TH1F : histograms with one float per channel. Maximum precision 7 digits
81  - TH1D : histograms with one double per channel. Maximum precision 14 digits
82  - 2-D histograms:
83  - TH2C : histograms with one byte per channel. Maximum bin content = 127
84  - TH2S : histograms with one short per channel. Maximum bin content = 32767
85  - TH2I : histograms with one int per channel. Maximum bin content = 2147483647
86  - TH2F : histograms with one float per channel. Maximum precision 7 digits
87  - TH2D : histograms with one double per channel. Maximum precision 14 digits
88  - 3-D histograms:
89  - TH3C : histograms with one byte per channel. Maximum bin content = 127
90  - TH3S : histograms with one short per channel. Maximum bin content = 32767
91  - TH3I : histograms with one int per channel. Maximum bin content = 2147483647
92  - TH3F : histograms with one float per channel. Maximum precision 7 digits
93  - TH3D : histograms with one double per channel. Maximum precision 14 digits
94  - Profile histograms: See classes TProfile, TProfile2D and TProfile3D.
95  Profile histograms are used to display the mean value of Y and its standard deviation
96  for each bin in X. Profile histograms are in many cases an elegant
97  replacement of two-dimensional histograms : the inter-relation of two
98  measured quantities X and Y can always be visualized by a two-dimensional
99  histogram or scatter-plot; If Y is an unknown (but single-valued)
100  approximate function of X, this function is displayed by a profile
101  histogram with much better precision than by a scatter-plot.
102 
103 
104 All histogram classes are derived from the base class TH1
105 ~~~ {.cpp}
106  TH1
107  ^
108  |
109  |
110  |
111  +----------------+-------+------+------+-----+-----+
112  | | | | | | |
113  | | TH1C TH1S TH1I TH1F TH1D
114  | | |
115  | | |
116  | TH2 TProfile
117  | |
118  | |
119  | +-------+------+------+-----+-----+
120  | | | | | |
121  | TH2C TH2S TH2I TH2F TH2D
122  | |
123  TH3 |
124  | TProfile2D
125  |
126  +-------+------+------+------+------+
127  | | | | |
128  TH3C TH3S TH3I TH3F TH3D
129  |
130  |
131  TProfile3D
132 
133  The TH*C classes also inherit from the array class TArrayC.
134  The TH*S classes also inherit from the array class TArrayS.
135  The TH*I classes also inherit from the array class TArrayI.
136  The TH*F classes also inherit from the array class TArrayF.
137  The TH*D classes also inherit from the array class TArrayD.
138 ~~~
139 
140 #### Creating histograms
141 
142 Histograms are created by invoking one of the constructors, e.g.
143 ~~~ {.cpp}
144  TH1F *h1 = new TH1F("h1", "h1 title", 100, 0, 4.4);
145  TH2F *h2 = new TH2F("h2", "h2 title", 40, 0, 4, 30, -3, 3);
146 ~~~
147 Histograms may also be created by:
148 
149  - calling the Clone function, see below
150  - making a projection from a 2-D or 3-D histogram, see below
151  - reading an histogram from a file
152 
153  When an histogram is created, a reference to it is automatically added
154  to the list of in-memory objects for the current file or directory.
155  This default behaviour can be changed by:
156 ~~~ {.cpp}
157  h->SetDirectory(0); for the current histogram h
158  TH1::AddDirectory(kFALSE); sets a global switch disabling the reference
159 ~~~
160  When the histogram is deleted, the reference to it is removed from
161  the list of objects in memory.
162  When a file is closed, all histograms in memory associated with this file
163  are automatically deleted.
164 
165 #### Fix or variable bin size
166 
167  All histogram types support either fix or variable bin sizes.
168  2-D histograms may have fix size bins along X and variable size bins
169  along Y or vice-versa. The functions to fill, manipulate, draw or access
170  histograms are identical in both cases.
171 
172  Each histogram always contains 3 objects TAxis: fXaxis, fYaxis and fZaxis
173  o access the axis parameters, do:
174 ~~~ {.cpp}
175  TAxis *xaxis = h->GetXaxis(); etc.
176  Double_t binCenter = xaxis->GetBinCenter(bin), etc.
177 ~~~
178  See class TAxis for a description of all the access functions.
179  The axis range is always stored internally in double precision.
180 
181 #### Convention for numbering bins
182 
183  For all histogram types: nbins, xlow, xup
184 ~~~ {.cpp}
185  bin = 0; underflow bin
186  bin = 1; first bin with low-edge xlow INCLUDED
187  bin = nbins; last bin with upper-edge xup EXCLUDED
188  bin = nbins+1; overflow bin
189 ~~~
190  In case of 2-D or 3-D histograms, a "global bin" number is defined.
191  For example, assuming a 3-D histogram with (binx, biny, binz), the function
192 ~~~ {.cpp}
193  Int_t gbin = h->GetBin(binx, biny, binz);
194 ~~~
195  returns a global/linearized gbin number. This global gbin is useful
196  to access the bin content/error information independently of the dimension.
197  Note that to access the information other than bin content and errors
198  one should use the TAxis object directly with e.g.:
199 ~~~ {.cpp}
200  Double_t xcenter = h3->GetZaxis()->GetBinCenter(27);
201 ~~~
202  returns the center along z of bin number 27 (not the global bin)
203  in the 3-D histogram h3.
204 
205 #### Alphanumeric Bin Labels
206 
207  By default, an histogram axis is drawn with its numeric bin labels.
208  One can specify alphanumeric labels instead with:
209 
210  - call TAxis::SetBinLabel(bin, label);
211  This can always be done before or after filling.
212  When the histogram is drawn, bin labels will be automatically drawn.
213  See examples labels1.C and labels2.C
214  - call to a Fill function with one of the arguments being a string, e.g.
215 ~~~ {.cpp}
216  hist1->Fill(somename, weight);
217  hist2->Fill(x, somename, weight);
218  hist2->Fill(somename, y, weight);
219  hist2->Fill(somenamex, somenamey, weight);
220 ~~~
221  See examples hlabels1.C and hlabels2.C
222  - via TTree::Draw. see for example cernstaff.C
223 ~~~ {.cpp}
224  tree.Draw("Nation::Division");
225 ~~~
226  where "Nation" and "Division" are two branches of a Tree.
227 
228 When using the options 2 or 3 above, the labels are automatically
229  added to the list (THashList) of labels for a given axis.
230  By default, an axis is drawn with the order of bins corresponding
231  to the filling sequence. It is possible to reorder the axis
232 
233  - alphabetically
234  - by increasing or decreasing values
235 
236  The reordering can be triggered via the TAxis context menu by selecting
237  the menu item "LabelsOption" or by calling directly
238  TH1::LabelsOption(option, axis) where
239 
240  - axis may be "X", "Y" or "Z"
241  - option may be:
242  - "a" sort by alphabetic order
243  - ">" sort by decreasing values
244  - "<" sort by increasing values
245  - "h" draw labels horizontal
246  - "v" draw labels vertical
247  - "u" draw labels up (end of label right adjusted)
248  - "d" draw labels down (start of label left adjusted)
249 
250  When using the option 2 above, new labels are added by doubling the current
251  number of bins in case one label does not exist yet.
252  When the Filling is terminated, it is possible to trim the number
253  of bins to match the number of active labels by calling
254 ~~~ {.cpp}
255  TH1::LabelsDeflate(axis) with axis = "X", "Y" or "Z"
256 ~~~
257  This operation is automatic when using TTree::Draw.
258  Once bin labels have been created, they become persistent if the histogram
259  is written to a file or when generating the C++ code via SavePrimitive.
260 
261 #### Histograms with automatic bins
262 
263  When an histogram is created with an axis lower limit greater or equal
264  to its upper limit, the SetBuffer is automatically called with an
265  argument fBufferSize equal to fgBufferSize (default value=1000).
266  fgBufferSize may be reset via the static function TH1::SetDefaultBufferSize.
267  The axis limits will be automatically computed when the buffer will
268  be full or when the function BufferEmpty is called.
269 
270 #### Filling histograms
271 
272  An histogram is typically filled with statements like:
273 ~~~ {.cpp}
274  h1->Fill(x);
275  h1->Fill(x, w); //fill with weight
276  h2->Fill(x, y)
277  h2->Fill(x, y, w)
278  h3->Fill(x, y, z)
279  h3->Fill(x, y, z, w)
280 ~~~
281  or via one of the Fill functions accepting names described above.
282  The Fill functions compute the bin number corresponding to the given
283  x, y or z argument and increment this bin by the given weight.
284  The Fill functions return the bin number for 1-D histograms or global
285  bin number for 2-D and 3-D histograms.
286  If TH1::Sumw2 has been called before filling, the sum of squares of
287  weights is also stored.
288  One can also increment directly a bin number via TH1::AddBinContent
289  or replace the existing content via TH1::SetBinContent.
290  To access the bin content of a given bin, do:
291 ~~~ {.cpp}
292  Double_t binContent = h->GetBinContent(bin);
293 ~~~
294 
295  By default, the bin number is computed using the current axis ranges.
296  If the automatic binning option has been set via
297 ~~~ {.cpp}
298  h->SetCanExtend(TH1::kAllAxes);
299 ~~~
300  then, the Fill Function will automatically extend the axis range to
301  accomodate the new value specified in the Fill argument. The method
302  used is to double the bin size until the new value fits in the range,
303  merging bins two by two. This automatic binning options is extensively
304  used by the TTree::Draw function when histogramming Tree variables
305  with an unknown range.
306  This automatic binning option is supported for 1-D, 2-D and 3-D histograms.
307 
308  During filling, some statistics parameters are incremented to compute
309  the mean value and Root Mean Square with the maximum precision.
310 
311  In case of histograms of type TH1C, TH1S, TH2C, TH2S, TH3C, TH3S
312  a check is made that the bin contents do not exceed the maximum positive
313  capacity (127 or 32767). Histograms of all types may have positive
314  or/and negative bin contents.
315 
316 #### Rebinning
317  At any time, an histogram can be rebinned via TH1::Rebin. This function
318  returns a new histogram with the rebinned contents.
319  If bin errors were stored, they are recomputed during the rebinning.
320 
321 #### Associated errors
322  By default, for each bin, the sum of weights is computed at fill time.
323  One can also call TH1::Sumw2 to force the storage and computation
324  of the sum of the square of weights per bin.
325  If Sumw2 has been called, the error per bin is computed as the
326  sqrt(sum of squares of weights), otherwise the error is set equal
327  to the sqrt(bin content).
328  To return the error for a given bin number, do:
329 ~~~ {.cpp}
330  Double_t error = h->GetBinError(bin);
331 ~~~
332 
333 #### Associated functions
334  One or more object (typically a TF1*) can be added to the list
335  of functions (fFunctions) associated to each histogram.
336  When TH1::Fit is invoked, the fitted function is added to this list.
337  Given an histogram h, one can retrieve an associated function
338  with:
339 ~~~ {.cpp}
340  TF1 *myfunc = h->GetFunction("myfunc");
341 ~~~
342 
343 #### Operations on histograms
344 
345  Many types of operations are supported on histograms or between histograms
346 
347  - Addition of an histogram to the current histogram.
348  - Additions of two histograms with coefficients and storage into the current
349  histogram.
350  - Multiplications and Divisions are supported in the same way as additions.
351  - The Add, Divide and Multiply functions also exist to add, divide or multiply
352  an histogram by a function.
353 
354  If an histogram has associated error bars (TH1::Sumw2 has been called),
355  the resulting error bars are also computed assuming independent histograms.
356  In case of divisions, Binomial errors are also supported.
357  One can mark a histogram to be an "average" histogram by setting its bit kIsAverage via
358  myhist.SetBit(TH1::kIsAverage);
359  When adding (see TH1::Add) average histograms, the histograms are averaged and not summed.
360 
361 #### Fitting histograms
362 
363  Histograms (1-D, 2-D, 3-D and Profiles) can be fitted with a user
364  specified function via TH1::Fit. When an histogram is fitted, the
365  resulting function with its parameters is added to the list of functions
366  of this histogram. If the histogram is made persistent, the list of
367  associated functions is also persistent. Given a pointer (see above)
368  to an associated function myfunc, one can retrieve the function/fit
369  parameters with calls such as:
370 ~~~ {.cpp}
371  Double_t chi2 = myfunc->GetChisquare();
372  Double_t par0 = myfunc->GetParameter(0); value of 1st parameter
373  Double_t err0 = myfunc->GetParError(0); error on first parameter
374 ~~~
375 
376 #### Projections of histograms
377 
378  One can:
379 
380  - make a 1-D projection of a 2-D histogram or Profile
381  see functions TH2::ProjectionX,Y, TH2::ProfileX,Y, TProfile::ProjectionX
382  - make a 1-D, 2-D or profile out of a 3-D histogram
383  see functions TH3::ProjectionZ, TH3::Project3D.
384 
385  One can fit these projections via:
386 ~~~ {.cpp}
387  TH2::FitSlicesX,Y, TH3::FitSlicesZ.
388 ~~~
389 
390 #### Random Numbers and histograms
391 
392  TH1::FillRandom can be used to randomly fill an histogram using
393  the contents of an existing TF1 function or another
394  TH1 histogram (for all dimensions).
395  For example the following two statements create and fill an histogram
396  10000 times with a default gaussian distribution of mean 0 and sigma 1:
397 ~~~ {.cpp}
398  TH1F h1("h1", "histo from a gaussian", 100, -3, 3);
399  h1.FillRandom("gaus", 10000);
400 ~~~
401  TH1::GetRandom can be used to return a random number distributed
402  according the contents of an histogram.
403 
404 #### Making a copy of an histogram
405  Like for any other ROOT object derived from TObject, one can use
406  the Clone() function. This makes an identical copy of the original
407  histogram including all associated errors and functions, e.g.:
408 ~~~ {.cpp}
409  TH1F *hnew = (TH1F*)h->Clone("hnew");
410 ~~~
411 
412 #### Normalizing histograms
413 
414  One can scale an histogram such that the bins integral is equal to
415  the normalization parameter via TH1::Scale(Double_t norm), where norm
416  is the desired normalization divided by the integral of the histogram.
417 
418 #### Drawing histograms
419 
420  Histograms are drawn via the THistPainter class. Each histogram has
421  a pointer to its own painter (to be usable in a multithreaded program).
422  Many drawing options are supported.
423  See THistPainter::Paint() for more details.
424 
425  The same histogram can be drawn with different options in different pads.
426  When an histogram drawn in a pad is deleted, the histogram is
427  automatically removed from the pad or pads where it was drawn.
428  If an histogram is drawn in a pad, then filled again, the new status
429  of the histogram will be automatically shown in the pad next time
430  the pad is updated. One does not need to redraw the histogram.
431  To draw the current version of an histogram in a pad, one can use
432 ~~~ {.cpp}
433  h->DrawCopy();
434 ~~~
435  This makes a clone (see Clone below) of the histogram. Once the clone
436  is drawn, the original histogram may be modified or deleted without
437  affecting the aspect of the clone.
438 
439  One can use TH1::SetMaximum() and TH1::SetMinimum() to force a particular
440  value for the maximum or the minimum scale on the plot. (For 1-D
441  histograms this means the y-axis, while for 2-D histograms these
442  functions affect the z-axis).
443 
444  TH1::UseCurrentStyle() can be used to change all histogram graphics
445  attributes to correspond to the current selected style.
446  This function must be called for each histogram.
447  In case one reads and draws many histograms from a file, one can force
448  the histograms to inherit automatically the current graphics style
449  by calling before gROOT->ForceStyle().
450 
451 #### Setting Drawing histogram contour levels (2-D hists only)
452 
453  By default contours are automatically generated at equidistant
454  intervals. A default value of 20 levels is used. This can be modified
455  via TH1::SetContour() or TH1::SetContourLevel().
456  the contours level info is used by the drawing options "cont", "surf",
457  and "lego".
458 
459 #### Setting histogram graphics attributes
460 
461  The histogram classes inherit from the attribute classes:
462  TAttLine, TAttFill, and TAttMarker.
463  See the member functions of these classes for the list of options.
464 
465 #### Giving titles to the X, Y and Z axis
466 
467 ~~~ {.cpp}
468  h->GetXaxis()->SetTitle("X axis title");
469  h->GetYaxis()->SetTitle("Y axis title");
470 ~~~
471  The histogram title and the axis titles can be any TLatex string.
472  The titles are part of the persistent histogram.
473  It is also possible to specify the histogram title and the axis
474  titles at creation time. These titles can be given in the "title"
475  parameter. They must be separated by ";":
476 ~~~ {.cpp}
477  TH1F* h=new TH1F("h", "Histogram title;X Axis;Y Axis;Z Axis", 100, 0, 1);
478 ~~~
479  Any title can be omitted:
480 ~~~ {.cpp}
481  TH1F* h=new TH1F("h", "Histogram title;;Y Axis", 100, 0, 1);
482  TH1F* h=new TH1F("h", ";;Y Axis", 100, 0, 1);
483 ~~~
484  The method SetTitle has the same syntax:
485 ~~~ {.cpp}
486  h->SetTitle("Histogram title;Another X title Axis");
487 ~~~
488 
489 #### Saving/Reading histograms to/from a ROOT file
490 
491  The following statements create a ROOT file and store an histogram
492  on the file. Because TH1 derives from TNamed, the key identifier on
493  the file is the histogram name:
494 ~~~ {.cpp}
495  TFile f("histos.root", "new");
496  TH1F h1("hgaus", "histo from a gaussian", 100, -3, 3);
497  h1.FillRandom("gaus", 10000);
498  h1->Write();
499 ~~~
500  To read this histogram in another Root session, do:
501 ~~~ {.cpp}
502  TFile f("histos.root");
503  TH1F *h = (TH1F*)f.Get("hgaus");
504 ~~~
505  One can save all histograms in memory to the file by:
506 ~~~ {.cpp}
507  file->Write();
508 ~~~
509 
510 #### Miscellaneous operations
511 
512 ~~~ {.cpp}
513  TH1::KolmogorovTest(): statistical test of compatibility in shape
514  between two histograms
515  TH1::Smooth() smooths the bin contents of a 1-d histogram
516  TH1::Integral() returns the integral of bin contents in a given bin range
517  TH1::GetMean(int axis) returns the mean value along axis
518  TH1::GetStdDev(int axis) returns the sigma distribution along axis
519  TH1::GetEntries() returns the number of entries
520  TH1::Reset() resets the bin contents and errors of an histogram
521 ~~~
522 */
523 
524 TF1 *gF1=0; //left for back compatibility (use TVirtualFitter::GetUserFunc instead)
525 
526 Int_t TH1::fgBufferSize = 1000;
530 
531 extern void H1InitGaus();
532 extern void H1InitExpo();
533 extern void H1InitPolynom();
534 extern void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a);
535 extern void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail);
536 extern void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b);
537 
538 // Internal exceptions for the CheckConsistency method
539 class DifferentDimension: public std::exception {};
540 class DifferentNumberOfBins: public std::exception {};
541 class DifferentAxisLimits: public std::exception {};
542 class DifferentBinLimits: public std::exception {};
543 class DifferentLabels: public std::exception {};
544 
545 ClassImp(TH1);
546 
547 ////////////////////////////////////////////////////////////////////////////////
548 /// Histogram default constructor.
549 
551 {
552  fDirectory = 0;
553  fFunctions = new TList;
554  fNcells = 0;
555  fIntegral = 0;
556  fPainter = 0;
557  fEntries = 0;
558  fNormFactor = 0;
560  fMaximum = -1111;
561  fMinimum = -1111;
562  fBufferSize = 0;
563  fBuffer = 0;
565  fXaxis.SetName("xaxis");
566  fYaxis.SetName("yaxis");
567  fZaxis.SetName("zaxis");
568  fXaxis.SetParent(this);
569  fYaxis.SetParent(this);
570  fZaxis.SetParent(this);
571  UseCurrentStyle();
572 }
573 
574 ////////////////////////////////////////////////////////////////////////////////
575 /// Histogram default destructor.
576 
578 {
579  if (!TestBit(kNotDeleted)) {
580  return;
581  }
582  delete[] fIntegral;
583  fIntegral = 0;
584  delete[] fBuffer;
585  fBuffer = 0;
586  if (fFunctions) {
588 
590  TObject* obj = 0;
591  //special logic to support the case where the same object is
592  //added multiple times in fFunctions.
593  //This case happens when the same object is added with different
594  //drawing modes
595  //In the loop below we must be careful with objects (eg TCutG) that may
596  // have been added to the list of functions of several histograms
597  //and may have been already deleted.
598  while ((obj = fFunctions->First())) {
599  while(fFunctions->Remove(obj)) { }
600  if (!obj->TestBit(kNotDeleted)) {
601  break;
602  }
603  delete obj;
604  obj = 0;
605  }
606  delete fFunctions;
607  fFunctions = 0;
608  }
609  if (fDirectory) {
610  fDirectory->Remove(this);
611  fDirectory = 0;
612  }
613  delete fPainter;
614  fPainter = 0;
615 }
616 
617 ////////////////////////////////////////////////////////////////////////////////
618 /// Normal constructor for fix bin size histograms.
619 /// Creates the main histogram structure.
620 ///
621 /// \param[in] name name of histogram (avoid blanks)
622 /// \param[in] title histogram title.
623 /// If title is of the form stringt;stringx;stringy;stringz`
624 /// the histogram title is set to `stringt`,
625 /// the x axis title to `stringy`, the y axis title to `stringy`, etc.
626 /// \param[in] nbins number of bins
627 /// \param[in] xlow low edge of first bin
628 /// \param[in] xup upper edge of last bin (not included in last bin)
629 ///
630 /// When an histogram is created, it is automatically added to the list
631 /// of special objects in the current directory.
632 /// To find the pointer to this histogram in the current directory
633 /// by its name, do:
634 /// ~~~ {.cpp}
635 /// TH1F *h1 = (TH1F*)gDirectory->FindObject(name);
636 /// ~~~
637 
638 TH1::TH1(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
639  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
640 {
641  Build();
642  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
643  fXaxis.Set(nbins,xlow,xup);
644  fNcells = fXaxis.GetNbins()+2;
645 }
646 
647 ////////////////////////////////////////////////////////////////////////////////
648 /// Normal constructor for variable bin size histograms.
649 /// Creates the main histogram structure.
650 ///
651 /// \param[in] name name of histogram (avoid blanks)
652 /// \param[in] title histogram title.
653 /// If title is of the form `stringt;stringx;stringy;stringz`
654 /// the histogram title is set to `stringt`,
655 /// the x axis title to `stringy`, the y axis title to `stringy`, etc.
656 /// \param[in] nbins number of bins
657 /// \param[in] xbins array of low-edges for each bin.
658 /// This is an array of size nbins+1
659 
660 TH1::TH1(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
661  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
662 {
663  Build();
664  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
665  if (xbins) fXaxis.Set(nbins,xbins);
666  else fXaxis.Set(nbins,0,1);
667  fNcells = fXaxis.GetNbins()+2;
668 }
669 
670 ////////////////////////////////////////////////////////////////////////////////
671 /// Normal constructor for variable bin size histograms.
672 ///
673 /// \param[in] name name of histogram (avoid blanks)
674 /// \param[in] title histogram title.
675 /// If title is of the form `stringt;stringx;stringy;stringz`
676 /// the histogram title is set to `stringt`,
677 /// the x axis title to `stringy`, the y axis title to `stringy`, etc.
678 /// \param[in] nbins number of bins
679 /// \param[in] xbins array of low-edges for each bin.
680 /// This is an array of size nbins+1
681 
682 TH1::TH1(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
683  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
684 {
685  Build();
686  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
687  if (xbins) fXaxis.Set(nbins,xbins);
688  else fXaxis.Set(nbins,0,1);
689  fNcells = fXaxis.GetNbins()+2;
690 }
691 
692 ////////////////////////////////////////////////////////////////////////////////
693 /// Copy constructor.
694 /// The list of functions is not copied. (Use Clone if needed)
695 
697 {
698  ((TH1&)h).Copy(*this);
699 }
700 
701 ////////////////////////////////////////////////////////////////////////////////
702 /// Static function: cannot be inlined on Windows/NT.
703 
705 {
706  return fgAddDirectory;
707 }
708 
709 ////////////////////////////////////////////////////////////////////////////////
710 /// Browse the Histogram object.
711 
713 {
714  Draw(b ? b->GetDrawOption() : "");
715  gPad->Update();
716 }
717 
718 ////////////////////////////////////////////////////////////////////////////////
719 /// Creates histogram basic data structure.
720 
722 {
723  fDirectory = 0;
724  fPainter = 0;
725  fIntegral = 0;
726  fEntries = 0;
727  fNormFactor = 0;
729  fMaximum = -1111;
730  fMinimum = -1111;
731  fBufferSize = 0;
732  fBuffer = 0;
734  fXaxis.SetName("xaxis");
735  fYaxis.SetName("yaxis");
736  fZaxis.SetName("zaxis");
737  fYaxis.Set(1,0.,1.);
738  fZaxis.Set(1,0.,1.);
739  fXaxis.SetParent(this);
740  fYaxis.SetParent(this);
741  fZaxis.SetParent(this);
742 
743  SetTitle(fTitle.Data());
744 
745  fFunctions = new TList;
746 
747  UseCurrentStyle();
748 
749  if (TH1::AddDirectoryStatus()) {
751  if (fDirectory) {
753  fDirectory->Append(this,kTRUE);
754  }
755  }
756 }
757 
758 ////////////////////////////////////////////////////////////////////////////////
759 /// Performs the operation: `this = this + c1*f1`
760 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
761 ///
762 /// By default, the function is computed at the centre of the bin.
763 /// if option "I" is specified (1-d histogram only), the integral of the
764 /// function in each bin is used instead of the value of the function at
765 /// the centre of the bin.
766 ///
767 /// Only bins inside the function range are recomputed.
768 ///
769 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
770 /// you should call Sumw2 before making this operation.
771 /// This is particularly important if you fit the histogram after TH1::Add
772 ///
773 /// The function return kFALSE if the Add operation failed
774 
776 {
777  if (!f1) {
778  Error("Add","Attempt to add a non-existing function");
779  return kFALSE;
780  }
781 
782  TString opt = option;
783  opt.ToLower();
784  Bool_t integral = kFALSE;
785  if (opt.Contains("i") && fDimension == 1) integral = kTRUE;
786 
787  Int_t ncellsx = GetNbinsX() + 2; // cells = normal bins + underflow bin + overflow bin
788  Int_t ncellsy = GetNbinsY() + 2;
789  Int_t ncellsz = GetNbinsZ() + 2;
790  if (fDimension < 2) ncellsy = 1;
791  if (fDimension < 3) ncellsz = 1;
792 
793  // delete buffer if it is there since it will become invalid
794  if (fBuffer) BufferEmpty(1);
795 
796  // - Add statistics
797  Double_t s1[10];
798  for (Int_t i = 0; i < 10; ++i) s1[i] = 0;
799  PutStats(s1);
800  SetMinimum();
801  SetMaximum();
802 
803  // - Loop on bins (including underflows/overflows)
804  Int_t bin, binx, biny, binz;
805  Double_t cu=0;
806  Double_t xx[3];
807  Double_t *params = 0;
808  f1->InitArgs(xx,params);
809  for (binz = 0; binz < ncellsz; ++binz) {
810  xx[2] = fZaxis.GetBinCenter(binz);
811  for (biny = 0; biny < ncellsy; ++biny) {
812  xx[1] = fYaxis.GetBinCenter(biny);
813  for (binx = 0; binx < ncellsx; ++binx) {
814  xx[0] = fXaxis.GetBinCenter(binx);
815  if (!f1->IsInside(xx)) continue;
817  bin = binx + ncellsx * (biny + ncellsy * binz);
818  if (integral) {
819  cu = c1*f1->Integral(fXaxis.GetBinLowEdge(binx), fXaxis.GetBinUpEdge(binx)) / fXaxis.GetBinWidth(binx);
820  } else {
821  cu = c1*f1->EvalPar(xx);
822  }
823  if (TF1::RejectedPoint()) continue;
824  AddBinContent(bin,cu);
825  }
826  }
827  }
828 
829  return kTRUE;
830 }
831 
832 ////////////////////////////////////////////////////////////////////////////////
833 /// Performs the operation: `this = this + c1*h1`
834 /// If errors are defined (see TH1::Sumw2), errors are also recalculated.
835 ///
836 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
837 /// if not already set.
838 ///
839 /// Note also that adding histogram with labels is not supported, histogram will be
840 /// added merging them by bin number independently of the labels.
841 /// For adding histogram with labels one should use TH1::Merge
842 ///
843 /// SPECIAL CASE (Average/Efficiency histograms)
844 /// For histograms representing averages or efficiencies, one should compute the average
845 /// of the two histograms and not the sum. One can mark a histogram to be an average
846 /// histogram by setting its bit kIsAverage with
847 /// myhist.SetBit(TH1::kIsAverage);
848 /// Note that the two histograms must have their kIsAverage bit set
849 ///
850 /// IMPORTANT NOTE1: If you intend to use the errors of this histogram later
851 /// you should call Sumw2 before making this operation.
852 /// This is particularly important if you fit the histogram after TH1::Add
853 ///
854 /// IMPORTANT NOTE2: if h1 has a normalisation factor, the normalisation factor
855 /// is used , ie this = this + c1*factor*h1
856 /// Use the other TH1::Add function if you do not want this feature
857 ///
858 /// The function return kFALSE if the Add operation failed
859 
861 {
862  if (!h1) {
863  Error("Add","Attempt to add a non-existing histogram");
864  return kFALSE;
865  }
866 
867  // delete buffer if it is there since it will become invalid
868  if (fBuffer) BufferEmpty(1);
869 
870  bool useMerge = (c1 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
871  try {
872  CheckConsistency(this,h1);
873  useMerge = kFALSE;
874  } catch(DifferentNumberOfBins&) {
875  if (useMerge)
876  Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
877  else {
878  Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
879  return kFALSE;
880  }
881  } catch(DifferentAxisLimits&) {
882  if (useMerge)
883  Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
884  else
885  Warning("Add","Attempt to add histograms with different axis limits");
886  } catch(DifferentBinLimits&) {
887  if (useMerge)
888  Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
889  else
890  Warning("Add","Attempt to add histograms with different bin limits");
891  } catch(DifferentLabels&) {
892  // in case of different labels -
893  if (useMerge)
894  Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
895  else
896  Info("Warning","Attempt to add histograms with different labels");
897  }
898 
899  if (useMerge) {
900  TList l;
901  l.Add(const_cast<TH1*>(h1));
902  auto iret = Merge(&l);
903  return (iret >= 0);
904  }
905 
906  // Create Sumw2 if h1 has Sumw2 set
907  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
908 
909  // - Add statistics
910  Double_t entries = TMath::Abs( GetEntries() + c1 * h1->GetEntries() );
911 
912  // statistics can be preserved only in case of positive coefficients
913  // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
914  Bool_t resetStats = (c1 < 0);
915  Double_t s1[kNstat] = {0};
916  Double_t s2[kNstat] = {0};
917  if (!resetStats) {
918  // need to initialize to zero s1 and s2 since
919  // GetStats fills only used elements depending on dimension and type
920  GetStats(s1);
921  h1->GetStats(s2);
922  }
923 
924  SetMinimum();
925  SetMaximum();
926 
927  // - Loop on bins (including underflows/overflows)
928  Double_t factor = 1;
929  if (h1->GetNormFactor() != 0) factor = h1->GetNormFactor()/h1->GetSumOfWeights();;
930  Double_t c1sq = c1 * c1;
931  Double_t factsq = factor * factor;
932 
933  for (Int_t bin = 0; bin < fNcells; ++bin) {
934  //special case where histograms have the kIsAverage bit set
935  if (this->TestBit(kIsAverage) && h1->TestBit(kIsAverage)) {
936  Double_t y1 = h1->RetrieveBinContent(bin);
937  Double_t y2 = this->RetrieveBinContent(bin);
938  Double_t e1sq = h1->GetBinErrorSqUnchecked(bin);
939  Double_t e2sq = this->GetBinErrorSqUnchecked(bin);
940  Double_t w1 = 1., w2 = 1.;
941 
942  // consider all special cases when bin errors are zero
943  // see http://root-forum.cern.ch/viewtopic.php?f=3&t=13299
944  if (e1sq) w1 = 1. / e1sq;
945  else if (h1->fSumw2.fN) {
946  w1 = 1.E200; // use an arbitrary huge value
947  if (y1 == 0) {
948  // use an estimated error from the global histogram scale
949  double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
950  w1 = 1./(sf*sf);
951  }
952  }
953  if (e2sq) w2 = 1. / e2sq;
954  else if (fSumw2.fN) {
955  w2 = 1.E200; // use an arbitrary huge value
956  if (y2 == 0) {
957  // use an estimated error from the global histogram scale
958  double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
959  w2 = 1./(sf*sf);
960  }
961  }
962 
963  double y = (w1*y1 + w2*y2)/(w1 + w2);
964  UpdateBinContent(bin, y);
965  if (fSumw2.fN) {
966  double err2 = 1./(w1 + w2);
967  if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
968  fSumw2.fArray[bin] = err2;
969  }
970  } else { // normal case of addition between histograms
971  AddBinContent(bin, c1 * factor * h1->RetrieveBinContent(bin));
972  if (fSumw2.fN) fSumw2.fArray[bin] += c1sq * factsq * h1->GetBinErrorSqUnchecked(bin);
973  }
974  }
975 
976  // update statistics (do here to avoid changes by SetBinContent)
977  if (resetStats) {
978  // statistics need to be reset in case coefficient are negative
979  ResetStats();
980  }
981  else {
982  for (Int_t i=0;i<kNstat;i++) {
983  if (i == 1) s1[i] += c1*c1*s2[i];
984  else s1[i] += c1*s2[i];
985  }
986  PutStats(s1);
987  SetEntries(entries);
988  }
989  return kTRUE;
990 }
991 
992 ////////////////////////////////////////////////////////////////////////////////
993 /// Replace contents of this histogram by the addition of h1 and h2.
994 ///
995 /// `this = c1*h1 + c2*h2`
996 /// if errors are defined (see TH1::Sumw2), errors are also recalculated
997 ///
998 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
999 /// if not already set.
1000 ///
1001 /// Note also that adding histogram with labels is not supported, histogram will be
1002 /// added merging them by bin number independently of the labels.
1003 /// For adding histogram ith labels one should use TH1::Merge
1004 ///
1005 /// SPECIAL CASE (Average/Efficiency histograms)
1006 /// For histograms representing averages or efficiencies, one should compute the average
1007 /// of the two histograms and not the sum. One can mark a histogram to be an average
1008 /// histogram by setting its bit kIsAverage with
1009 /// myhist.SetBit(TH1::kIsAverage);
1010 /// Note that the two histograms must have their kIsAverage bit set
1011 ///
1012 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
1013 /// you should call Sumw2 before making this operation.
1014 /// This is particularly important if you fit the histogram after TH1::Add
1015 ///
1016 /// ANOTHER SPECIAL CASE : h1 = h2 and c2 < 0
1017 /// do a scaling this = c1 * h1 / (bin Volume)
1018 ///
1019 /// The function returns kFALSE if the Add operation failed
1020 
1022 {
1023 
1024  if (!h1 || !h2) {
1025  Error("Add","Attempt to add a non-existing histogram");
1026  return kFALSE;
1027  }
1028 
1029  // delete buffer if it is there since it will become invalid
1030  if (fBuffer) BufferEmpty(1);
1031 
1032  Bool_t normWidth = kFALSE;
1033  if (h1 == h2 && c2 < 0) {c2 = 0; normWidth = kTRUE;}
1034 
1035  if (h1 != h2) {
1036  bool useMerge = (c1 == 1. && c2 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
1037 
1038  try {
1039  CheckConsistency(h1,h2);
1040  CheckConsistency(this,h1);
1041  useMerge = kFALSE;
1042  } catch(DifferentNumberOfBins&) {
1043  if (useMerge)
1044  Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
1045  else {
1046  Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
1047  return kFALSE;
1048  }
1049  } catch(DifferentAxisLimits&) {
1050  if (useMerge)
1051  Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
1052  else
1053  Warning("Add","Attempt to add histograms with different axis limits");
1054  } catch(DifferentBinLimits&) {
1055  if (useMerge)
1056  Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
1057  else
1058  Warning("Add","Attempt to add histograms with different bin limits");
1059  } catch(DifferentLabels&) {
1060  // in case of different labels -
1061  if (useMerge)
1062  Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
1063  else
1064  Info("Warning","Attempt to add histograms with different labels");
1065  }
1066 
1067  if (useMerge) {
1068  TList l;
1069  // why TList takes non-const pointers ????
1070  l.Add(const_cast<TH1*>(h1));
1071  l.Add(const_cast<TH1*>(h2));
1072  Reset("ICE");
1073  auto iret = Merge(&l);
1074  return (iret >= 0);
1075  }
1076  }
1077 
1078  // Create Sumw2 if h1 or h2 have Sumw2 set
1079  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
1080 
1081  // - Add statistics
1082  Double_t nEntries = TMath::Abs( c1*h1->GetEntries() + c2*h2->GetEntries() );
1083 
1084  // TODO remove
1085  // statistics can be preserved only in case of positive coefficients
1086  // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
1087  // also in case of scaling with the width we cannot preserve the statistics
1088  Double_t s1[kNstat] = {0};
1089  Double_t s2[kNstat] = {0};
1090  Double_t s3[kNstat];
1091 
1092 
1093  Bool_t resetStats = (c1*c2 < 0) || normWidth;
1094  if (!resetStats) {
1095  // need to initialize to zero s1 and s2 since
1096  // GetStats fills only used elements depending on dimension and type
1097  h1->GetStats(s1);
1098  h2->GetStats(s2);
1099  for (Int_t i=0;i<kNstat;i++) {
1100  if (i == 1) s3[i] = c1*c1*s1[i] + c2*c2*s2[i];
1101  //else s3[i] = TMath::Abs(c1)*s1[i] + TMath::Abs(c2)*s2[i];
1102  else s3[i] = c1*s1[i] + c2*s2[i];
1103  }
1104  }
1105 
1106  SetMinimum();
1107  SetMaximum();
1108 
1109  if (normWidth) { // DEPRECATED CASE: belongs to fitting / drawing modules
1110 
1111  Int_t nbinsx = GetNbinsX() + 2; // normal bins + underflow, overflow
1112  Int_t nbinsy = GetNbinsY() + 2;
1113  Int_t nbinsz = GetNbinsZ() + 2;
1114 
1115  if (fDimension < 2) nbinsy = 1;
1116  if (fDimension < 3) nbinsz = 1;
1117 
1118  Int_t bin, binx, biny, binz;
1119  for (binz = 0; binz < nbinsz; ++binz) {
1120  Double_t wz = h1->GetZaxis()->GetBinWidth(binz);
1121  for (biny = 0; biny < nbinsy; ++biny) {
1122  Double_t wy = h1->GetYaxis()->GetBinWidth(biny);
1123  for (binx = 0; binx < nbinsx; ++binx) {
1124  Double_t wx = h1->GetXaxis()->GetBinWidth(binx);
1125  bin = GetBin(binx, biny, binz);
1126  Double_t w = wx*wy*wz;
1127  UpdateBinContent(bin, c1 * h1->RetrieveBinContent(bin) / w);
1128  if (fSumw2.fN) {
1129  Double_t e1 = h1->GetBinError(bin)/w;
1130  fSumw2.fArray[bin] = c1*c1*e1*e1;
1131  }
1132  }
1133  }
1134  }
1135  } else if (h1->TestBit(kIsAverage) && h2->TestBit(kIsAverage)) {
1136  for (Int_t i = 0; i < fNcells; ++i) { // loop on cells (bins including underflow / overflow)
1137  // special case where histograms have the kIsAverage bit set
1138  Double_t y1 = h1->RetrieveBinContent(i);
1139  Double_t y2 = h2->RetrieveBinContent(i);
1140  Double_t e1sq = h1->GetBinErrorSqUnchecked(i);
1141  Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
1142  Double_t w1 = 1., w2 = 1.;
1143 
1144  // consider all special cases when bin errors are zero
1145  // see http://root-forum.cern.ch/viewtopic.php?f=3&t=13299
1146  if (e1sq) w1 = 1./ e1sq;
1147  else if (h1->fSumw2.fN) {
1148  w1 = 1.E200; // use an arbitrary huge value
1149  if (y1 == 0 ) { // use an estimated error from the global histogram scale
1150  double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
1151  w1 = 1./(sf*sf);
1152  }
1153  }
1154  if (e2sq) w2 = 1./ e2sq;
1155  else if (h2->fSumw2.fN) {
1156  w2 = 1.E200; // use an arbitrary huge value
1157  if (y2 == 0) { // use an estimated error from the global histogram scale
1158  double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
1159  w2 = 1./(sf*sf);
1160  }
1161  }
1162 
1163  double y = (w1*y1 + w2*y2)/(w1 + w2);
1164  UpdateBinContent(i, y);
1165  if (fSumw2.fN) {
1166  double err2 = 1./(w1 + w2);
1167  if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
1168  fSumw2.fArray[i] = err2;
1169  }
1170  }
1171  } else { // case of simple histogram addition
1172  Double_t c1sq = c1 * c1;
1173  Double_t c2sq = c2 * c2;
1174  for (Int_t i = 0; i < fNcells; ++i) { // Loop on cells (bins including underflows/overflows)
1176  if (fSumw2.fN) {
1177  fSumw2.fArray[i] = c1sq * h1->GetBinErrorSqUnchecked(i) + c2sq * h2->GetBinErrorSqUnchecked(i);
1178  }
1179  }
1180  }
1181 
1182  if (resetStats) {
1183  // statistics need to be reset in case coefficient are negative
1184  ResetStats();
1185  }
1186  else {
1187  // update statistics (do here to avoid changes by SetBinContent) FIXME remove???
1188  PutStats(s3);
1189  SetEntries(nEntries);
1190  }
1191 
1192  return kTRUE;
1193 }
1194 
1195 ////////////////////////////////////////////////////////////////////////////////
1196 /// Increment bin content by 1.
1197 
1199 {
1200  AbstractMethod("AddBinContent");
1201 }
1202 
1203 ////////////////////////////////////////////////////////////////////////////////
1204 /// Increment bin content by a weight w.
1205 
1207 {
1208  AbstractMethod("AddBinContent");
1209 }
1210 
1211 ////////////////////////////////////////////////////////////////////////////////
1212 /// Sets the flag controlling the automatic add of histograms in memory
1213 ///
1214 /// By default (fAddDirectory = kTRUE), histograms are automatically added
1215 /// to the list of objects in memory.
1216 /// Note that one histogram can be removed from its support directory
1217 /// by calling h->SetDirectory(0) or h->SetDirectory(dir) to add it
1218 /// to the list of objects in the directory dir.
1219 ///
1220 /// NOTE that this is a static function. To call it, use;
1221 /// TH1::AddDirectory
1222 
1224 {
1225  fgAddDirectory = add;
1226 }
1227 
1228 ////////////////////////////////////////////////////////////////////////////////
1229 /// Auxilliary function to get the power of 2 next (larger) or previous (smaller)
1230 /// a given x
1231 ///
1232 /// next = kTRUE : next larger
1233 /// next = kFALSE : previous smaller
1234 ///
1235 /// Used by the autobin power of 2 algorithm
1236 
1238 {
1239  Int_t nn;
1240  Double_t f2 = std::frexp(x, &nn);
1241  return ((next && x > 0.) || (!next && x <= 0.)) ? std::ldexp(std::copysign(1., f2), nn)
1242  : std::ldexp(std::copysign(1., f2), --nn);
1243 }
1244 
1245 ////////////////////////////////////////////////////////////////////////////////
1246 /// Auxilliary function to get the next power of 2 integer value larger then n
1247 ///
1248 /// Used by the autobin power of 2 algorithm
1249 
1251 {
1252  Int_t nn;
1253  Double_t f2 = std::frexp(n, &nn);
1254  if (TMath::Abs(f2 - .5) > 0.001)
1255  return (Int_t)std::ldexp(1., nn);
1256  return n;
1257 }
1258 
1259 ////////////////////////////////////////////////////////////////////////////////
1260 /// Buffer-based estimate of the histogram range using the power of 2 algorithm.
1261 ///
1262 /// Used by the autobin power of 2 algorithm.
1263 ///
1264 /// Works on arguments (min and max from fBuffer) and internal inputs: fXmin,
1265 /// fXmax, NBinsX (from fXaxis), ...
1266 /// Result save internally in fXaxis.
1267 ///
1268 /// Overloaded by TH2 and TH3.
1269 ///
1270 /// Return -1 if internal inputs are incosistent, 0 otherwise.
1271 ///
1272 
1274 {
1275  // We need meaningful raw limits
1276  if (xmi >= xma)
1277  return -1;
1278 
1280  Double_t xhmi = fXaxis.GetXmin();
1281  Double_t xhma = fXaxis.GetXmax();
1282 
1283  // Now adjust
1284  if (TMath::Abs(xhma) > TMath::Abs(xhmi)) {
1285  // Start from the upper limit
1286  xhma = TH1::AutoP2GetPower2(xhma);
1287  xhmi = xhma - TH1::AutoP2GetPower2(xhma - xhmi);
1288  } else {
1289  // Start from the lower limit
1290  xhmi = TH1::AutoP2GetPower2(xhmi, kFALSE);
1291  xhma = xhmi + TH1::AutoP2GetPower2(xhma - xhmi);
1292  }
1293 
1294  // Round the bins to the next power of 2; take into account the possible inflation
1295  // of the range
1296  Double_t rr = (xhma - xhmi) / (xma - xmi);
1297  Int_t nb = TH1::AutoP2GetBins((Int_t)(rr * GetNbinsX()));
1298 
1299  // Adjust using the same bin width and offsets
1300  Double_t bw = (xhma - xhmi) / nb;
1301  // Bins to left free on each side
1302  Double_t autoside = gEnv->GetValue("Hist.Binning.Auto.Side", 0.05);
1303  Int_t nbside = (Int_t)(nb * autoside);
1304 
1305  // Side up
1306  Int_t nbup = (xhma - xma) / bw;
1307  if (nbup % 2 != 0)
1308  nbup++; // Must be even
1309  if (nbup != nbside) {
1310  // Accounts also for both case: larger or smaller
1311  xhma -= bw * (nbup - nbside);
1312  nb -= (nbup - nbside);
1313  }
1314 
1315  // Side low
1316  Int_t nblw = (xmi - xhmi) / bw;
1317  if (nblw % 2 != 0)
1318  nblw++; // Must be even
1319  if (nblw != nbside) {
1320  // Accounts also for both case: larger or smaller
1321  xhmi += bw * (nblw - nbside);
1322  nb -= (nblw - nbside);
1323  }
1324 
1325  // Set everything and project
1326  SetBins(nb, xhmi, xhma);
1327 
1328  // Done
1329  return 0;
1330 }
1331 
1332 /// Fill histogram with all entries in the buffer.
1333 ///
1334 /// - action = -1 histogram is reset and refilled from the buffer (called by THistPainter::Paint)
1335 /// - action = 0 histogram is reset and filled from the buffer. When the histogram is filled from the
1336 /// buffer the value fBuffer[0] is set to a negative number (= - number of entries)
1337 /// When calling with action == 0 the histogram is NOT refilled when fBuffer[0] is < 0
1338 /// While when calling with action = -1 the histogram is reset and ALWAYS refilled independently if
1339 /// the histogram was filled before. This is needed when drawing the histogram
1340 /// - action = 1 histogram is filled and buffer is deleted
1341 /// The buffer is automatically deleted when filling the histogram and the entries is
1342 /// larger than the buffer size
1343 
1345 {
1346  // do we need to compute the bin size?
1347  if (!fBuffer) return 0;
1348  Int_t nbentries = (Int_t)fBuffer[0];
1349 
1350  // nbentries correspond to the number of entries of histogram
1351 
1352  if (nbentries == 0) {
1353  // if action is 1 we delete the buffer
1354  // this will avoid infinite recursion
1355  if (action > 0) {
1356  delete [] fBuffer;
1357  fBuffer = 0;
1358  fBufferSize = 0;
1359  }
1360  return 0;
1361  }
1362  if (nbentries < 0 && action == 0) return 0; // case histogram has been already filled from the buffer
1363 
1364  Double_t *buffer = fBuffer;
1365  if (nbentries < 0) {
1366  nbentries = -nbentries;
1367  // a reset might call BufferEmpty() giving an infinite recursion
1368  // Protect it by setting fBuffer = 0
1369  fBuffer=0;
1370  //do not reset the list of functions
1371  Reset("ICES");
1372  fBuffer = buffer;
1373  }
1374  if (CanExtendAllAxes() || (fXaxis.GetXmax() <= fXaxis.GetXmin())) {
1375  //find min, max of entries in buffer
1376  Double_t xmin = fBuffer[2];
1377  Double_t xmax = xmin;
1378  for (Int_t i=1;i<nbentries;i++) {
1379  Double_t x = fBuffer[2*i+2];
1380  if (x < xmin) xmin = x;
1381  if (x > xmax) xmax = x;
1382  }
1383  if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
1384  Int_t rc = -1;
1385  if (TestBit(TH1::kAutoBinPTwo)) {
1386  if ((rc = AutoP2FindLimits(xmin, xmax)) < 0)
1387  Warning("BufferEmpty",
1388  "incosistency found by power-of-2 autobin algorithm: fallback to standard method");
1389  }
1390  if (rc < 0)
1392  } else {
1393  fBuffer = 0;
1394  Int_t keep = fBufferSize; fBufferSize = 0;
1395  if (xmin < fXaxis.GetXmin()) ExtendAxis(xmin, &fXaxis);
1396  if (xmax >= fXaxis.GetXmax()) ExtendAxis(xmax, &fXaxis);
1397  fBuffer = buffer;
1398  fBufferSize = keep;
1399  }
1400  }
1401 
1402  // call DoFillN which will not put entries in the buffer as FillN does
1403  // set fBuffer to zero to avoid re-emptying the buffer from functions called
1404  // by DoFillN (e.g Sumw2)
1405  buffer = fBuffer; fBuffer = 0;
1406  DoFillN(nbentries,&buffer[2],&buffer[1],2);
1407  fBuffer = buffer;
1408 
1409  // if action == 1 - delete the buffer
1410  if (action > 0) {
1411  delete [] fBuffer;
1412  fBuffer = 0;
1413  fBufferSize = 0;
1414  } else {
1415  // if number of entries is consistent with buffer - set it negative to avoid
1416  // refilling the histogram every time BufferEmpty(0) is called
1417  // In case it is not consistent, by setting fBuffer[0]=0 is like resetting the buffer
1418  // (it will not be used anymore the next time BufferEmpty is called)
1419  if (nbentries == (Int_t)fEntries)
1420  fBuffer[0] = -nbentries;
1421  else
1422  fBuffer[0] = 0;
1423  }
1424  return nbentries;
1425 }
1426 
1427 ////////////////////////////////////////////////////////////////////////////////
1428 /// accumulate arguments in buffer. When buffer is full, empty the buffer
1429 ///
1430 /// - `fBuffer[0]` = number of entries in buffer
1431 /// - `fBuffer[1]` = w of first entry
1432 /// - `fBuffer[2]` = x of first entry
1433 
1435 {
1436  if (!fBuffer) return -2;
1437  Int_t nbentries = (Int_t)fBuffer[0];
1438 
1439 
1440  if (nbentries < 0) {
1441  // reset nbentries to a positive value so next time BufferEmpty() is called
1442  // the histogram will be refilled
1443  nbentries = -nbentries;
1444  fBuffer[0] = nbentries;
1445  if (fEntries > 0) {
1446  // set fBuffer to zero to avoid calling BufferEmpty in Reset
1447  Double_t *buffer = fBuffer; fBuffer=0;
1448  Reset("ICES"); // do not reset list of functions
1449  fBuffer = buffer;
1450  }
1451  }
1452  if (2*nbentries+2 >= fBufferSize) {
1453  BufferEmpty(1);
1454  if (!fBuffer)
1455  // to avoid infinite recursion Fill->BufferFill->Fill
1456  return Fill(x,w);
1457  // this cannot happen
1458  R__ASSERT(0);
1459  }
1460  fBuffer[2*nbentries+1] = w;
1461  fBuffer[2*nbentries+2] = x;
1462  fBuffer[0] += 1;
1463  return -2;
1464 }
1465 
1466 ////////////////////////////////////////////////////////////////////////////////
1467 /// Check bin limits.
1468 
1469 bool TH1::CheckBinLimits(const TAxis* a1, const TAxis * a2)
1470 {
1471  const TArrayD * h1Array = a1->GetXbins();
1472  const TArrayD * h2Array = a2->GetXbins();
1473  Int_t fN = h1Array->fN;
1474  if ( fN != 0 ) {
1475  if ( h2Array->fN != fN ) {
1476  throw DifferentBinLimits();
1477  return false;
1478  }
1479  else {
1480  for ( int i = 0; i < fN; ++i ) {
1481  if ( ! TMath::AreEqualRel( h1Array->GetAt(i), h2Array->GetAt(i), 1E-10 ) ) {
1482  throw DifferentBinLimits();
1483  return false;
1484  }
1485  }
1486  }
1487  }
1488 
1489  return true;
1490 }
1491 
1492 ////////////////////////////////////////////////////////////////////////////////
1493 /// Check that axis have same labels.
1494 
1495 bool TH1::CheckBinLabels(const TAxis* a1, const TAxis * a2)
1496 {
1497  THashList *l1 = a1->GetLabels();
1498  THashList *l2 = a2->GetLabels();
1499 
1500  if (!l1 && !l2 )
1501  return true;
1502  if (!l1 || !l2 ) {
1503  throw DifferentLabels();
1504  return false;
1505  }
1506  // check now labels sizes are the same
1507  if (l1->GetSize() != l2->GetSize() ) {
1508  throw DifferentLabels();
1509  return false;
1510  }
1511  for (int i = 1; i <= a1->GetNbins(); ++i) {
1512  TString label1 = a1->GetBinLabel(i);
1513  TString label2 = a2->GetBinLabel(i);
1514  if (label1 != label2) {
1515  throw DifferentLabels();
1516  return false;
1517  }
1518  }
1519 
1520  return true;
1521 }
1522 
1523 ////////////////////////////////////////////////////////////////////////////////
1524 /// Check that the axis limits of the histograms are the same.
1525 /// If a first and last bin is passed the axis is compared between the given range
1526 
1527 bool TH1::CheckAxisLimits(const TAxis *a1, const TAxis *a2 )
1528 {
1529  if ( ! TMath::AreEqualRel(a1->GetXmin(), a2->GetXmin(),1.E-12) ||
1530  ! TMath::AreEqualRel(a1->GetXmax(), a2->GetXmax(),1.E-12) ) {
1531  throw DifferentAxisLimits();
1532  return false;
1533  }
1534  return true;
1535 }
1536 
1537 ////////////////////////////////////////////////////////////////////////////////
1538 /// Check that the axis are the same
1539 
1540 bool TH1::CheckEqualAxes(const TAxis *a1, const TAxis *a2 )
1541 {
1542  if (a1->GetNbins() != a2->GetNbins() ) {
1543  //throw DifferentNumberOfBins();
1544  ::Info("CheckEqualAxes","Axes have different number of bins : nbin1 = %d nbin2 = %d",a1->GetNbins(),a2->GetNbins() );
1545  return false;
1546  }
1547  try {
1548  CheckAxisLimits(a1,a2);
1549  } catch (DifferentAxisLimits&) {
1550  ::Info("CheckEqualAxes","Axes have different limits");
1551  return false;
1552  }
1553  try {
1554  CheckBinLimits(a1,a2);
1555  } catch (DifferentBinLimits&) {
1556  ::Info("CheckEqualAxes","Axes have different bin limits");
1557  return false;
1558  }
1559 
1560  // check labels
1561  try {
1562  CheckBinLabels(a1,a2);
1563  } catch (DifferentLabels&) {
1564  ::Info("CheckEqualAxes","Axes have different labels");
1565  return false;
1566  }
1567 
1568  return true;
1569 }
1570 
1571 ////////////////////////////////////////////////////////////////////////////////
1572 /// Check that two sub axis are the same.
1573 /// The limits are defined by first bin and last bin
1574 /// N.B. no check is done in this case for variable bins
1575 
1576 bool TH1::CheckConsistentSubAxes(const TAxis *a1, Int_t firstBin1, Int_t lastBin1, const TAxis * a2, Int_t firstBin2, Int_t lastBin2 )
1577 {
1578  // By default is assumed that no bins are given for the second axis
1579  Int_t nbins1 = lastBin1-firstBin1 + 1;
1580  Double_t xmin1 = a1->GetBinLowEdge(firstBin1);
1581  Double_t xmax1 = a1->GetBinUpEdge(lastBin1);
1582 
1583  Int_t nbins2 = a2->GetNbins();
1584  Double_t xmin2 = a2->GetXmin();
1585  Double_t xmax2 = a2->GetXmax();
1586 
1587  if (firstBin2 < lastBin2) {
1588  // in this case assume no bins are given for the second axis
1589  nbins2 = lastBin1-firstBin1 + 1;
1590  xmin2 = a1->GetBinLowEdge(firstBin1);
1591  xmax2 = a1->GetBinUpEdge(lastBin1);
1592  }
1593 
1594  if (nbins1 != nbins2 ) {
1595  ::Info("CheckConsistentSubAxes","Axes have different number of bins");
1596  return false;
1597  }
1598 
1599  if ( ! TMath::AreEqualRel(xmin1,xmin2,1.E-12) ||
1600  ! TMath::AreEqualRel(xmax1,xmax2,1.E-12) ) {
1601  ::Info("CheckConsistentSubAxes","Axes have different limits");
1602  return false;
1603  }
1604 
1605  return true;
1606 }
1607 
1608 ////////////////////////////////////////////////////////////////////////////////
1609 /// Check histogram compatibility.
1610 
1611 bool TH1::CheckConsistency(const TH1* h1, const TH1* h2)
1612 {
1613  if (h1 == h2) return true;
1614 
1615  if (h1->GetDimension() != h2->GetDimension() ) {
1616  throw DifferentDimension();
1617  return false;
1618  }
1619  Int_t dim = h1->GetDimension();
1620 
1621  // returns kTRUE if number of bins and bin limits are identical
1622  Int_t nbinsx = h1->GetNbinsX();
1623  Int_t nbinsy = h1->GetNbinsY();
1624  Int_t nbinsz = h1->GetNbinsZ();
1625 
1626  // Check whether the histograms have the same number of bins.
1627  if (nbinsx != h2->GetNbinsX() ||
1628  (dim > 1 && nbinsy != h2->GetNbinsY()) ||
1629  (dim > 2 && nbinsz != h2->GetNbinsZ()) ) {
1630  throw DifferentNumberOfBins();
1631  return false;
1632  }
1633 
1634  bool ret = true;
1635 
1636  // check axis limits
1637  ret &= CheckAxisLimits(h1->GetXaxis(), h2->GetXaxis());
1638  if (dim > 1) ret &= CheckAxisLimits(h1->GetYaxis(), h2->GetYaxis());
1639  if (dim > 2) ret &= CheckAxisLimits(h1->GetZaxis(), h2->GetZaxis());
1640 
1641  // check bin limits
1642  ret &= CheckBinLimits(h1->GetXaxis(), h2->GetXaxis());
1643  if (dim > 1) ret &= CheckBinLimits(h1->GetYaxis(), h2->GetYaxis());
1644  if (dim > 2) ret &= CheckBinLimits(h1->GetZaxis(), h2->GetZaxis());
1645 
1646  // check labels if histograms are both not empty
1647  if ( (h1->fTsumw != 0 || h1->GetEntries() != 0) &&
1648  (h2->fTsumw != 0 || h2->GetEntries() != 0) ) {
1649  ret &= CheckBinLabels(h1->GetXaxis(), h2->GetXaxis());
1650  if (dim > 1) ret &= CheckBinLabels(h1->GetYaxis(), h2->GetYaxis());
1651  if (dim > 2) ret &= CheckBinLabels(h1->GetZaxis(), h2->GetZaxis());
1652  }
1653 
1654  return ret;
1655 }
1656 
1657 ////////////////////////////////////////////////////////////////////////////////
1658 /// \f$ \chi^{2} \f$ test for comparing weighted and unweighted histograms
1659 ///
1660 /// Function: Returns p-value. Other return values are specified by the 3rd parameter
1661 ///
1662 /// \param[in] h2 the second histogram
1663 /// \param[in] option
1664 /// - "UU" = experiment experiment comparison (unweighted-unweighted)
1665 /// - "UW" = experiment MC comparison (unweighted-weighted). Note that
1666 /// the first histogram should be unweighted
1667 /// - "WW" = MC MC comparison (weighted-weighted)
1668 /// - "NORM" = to be used when one or both of the histograms is scaled
1669 /// but the histogram originally was unweighted
1670 /// - by default underflows and overflows are not included:
1671 /// * "OF" = overflows included
1672 /// * "UF" = underflows included
1673 /// - "P" = print chi2, ndf, p_value, igood
1674 /// - "CHI2" = returns chi2 instead of p-value
1675 /// - "CHI2/NDF" = returns \f$ \chi^{2} \f$/ndf
1676 /// \param[in] res not empty - computes normalized residuals and returns them in this array
1677 ///
1678 /// The current implementation is based on the papers \f$ \chi^{2} \f$ test for comparison
1679 /// of weighted and unweighted histograms" in Proceedings of PHYSTAT05 and
1680 /// "Comparison weighted and unweighted histograms", arXiv:physics/0605123
1681 /// by N.Gagunashvili. This function has been implemented by Daniel Haertl in August 2006.
1682 ///
1683 /// #### Introduction:
1684 ///
1685 /// A frequently used technique in data analysis is the comparison of
1686 /// histograms. First suggested by Pearson [1] the \f$ \chi^{2} \f$ test of
1687 /// homogeneity is used widely for comparing usual (unweighted) histograms.
1688 /// This paper describes the implementation modified \f$ \chi^{2} \f$ tests
1689 /// for comparison of weighted and unweighted histograms and two weighted
1690 /// histograms [2] as well as usual Pearson's \f$ \chi^{2} \f$ test for
1691 /// comparison two usual (unweighted) histograms.
1692 ///
1693 /// #### Overview:
1694 ///
1695 /// Comparison of two histograms expect hypotheses that two histograms
1696 /// represent identical distributions. To make a decision p-value should
1697 /// be calculated. The hypotheses of identity is rejected if the p-value is
1698 /// lower then some significance level. Traditionally significance levels
1699 /// 0.1, 0.05 and 0.01 are used. The comparison procedure should include an
1700 /// analysis of the residuals which is often helpful in identifying the
1701 /// bins of histograms responsible for a significant overall \f$ \chi^{2} \f$ value.
1702 /// Residuals are the difference between bin contents and expected bin
1703 /// contents. Most convenient for analysis are the normalized residuals. If
1704 /// hypotheses of identity are valid then normalized residuals are
1705 /// approximately independent and identically distributed random variables
1706 /// having N(0,1) distribution. Analysis of residuals expect test of above
1707 /// mentioned properties of residuals. Notice that indirectly the analysis
1708 /// of residuals increase the power of \f$ \chi^{2} \f$ test.
1709 ///
1710 /// #### Methods of comparison:
1711 ///
1712 /// \f$ \chi^{2} \f$ test for comparison two (unweighted) histograms:
1713 /// Let us consider two histograms with the same binning and the number
1714 /// of bins equal to r. Let us denote the number of events in the ith bin
1715 /// in the first histogram as ni and as mi in the second one. The total
1716 /// number of events in the first histogram is equal to:
1717 /// \f[
1718 /// N = \sum_{i=1}^{r} n_{i}
1719 /// \f]
1720 /// and
1721 /// \f[
1722 /// M = \sum_{i=1}^{r} m_{i}
1723 /// \f]
1724 /// in the second histogram. The hypothesis of identity (homogeneity) [3]
1725 /// is that the two histograms represent random values with identical
1726 /// distributions. It is equivalent that there exist r constants p1,...,pr,
1727 /// such that
1728 /// \f[
1729 ///\sum_{i=1}^{r} p_{i}=1
1730 /// \f]
1731 /// and the probability of belonging to the ith bin for some measured value
1732 /// in both experiments is equal to pi. The number of events in the ith
1733 /// bin is a random variable with a distribution approximated by a Poisson
1734 /// probability distribution
1735 /// \f[
1736 ///\frac{e^{-Np_{i}}(Np_{i})^{n_{i}}}{n_{i}!}
1737 /// \f]
1738 ///for the first histogram and with distribution
1739 /// \f[
1740 ///\frac{e^{-Mp_{i}}(Mp_{i})^{m_{i}}}{m_{i}!}
1741 /// \f]
1742 /// for the second histogram. If the hypothesis of homogeneity is valid,
1743 /// then the maximum likelihood estimator of pi, i=1,...,r, is
1744 /// \f[
1745 ///\hat{p}_{i}= \frac{n_{i}+m_{i}}{N+M}
1746 /// \f]
1747 /// and then
1748 /// \f[
1749 /// 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}}
1750 /// \f]
1751 /// has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [3].
1752 /// The comparison procedure can include an analysis of the residuals which
1753 /// is often helpful in identifying the bins of histograms responsible for
1754 /// a significant overall \f$ \chi^{2} \f$ value. Most convenient for
1755 /// analysis are the adjusted (normalized) residuals [4]
1756 /// \f[
1757 /// 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))}}
1758 /// \f]
1759 /// If hypotheses of homogeneity are valid then residuals ri are
1760 /// approximately independent and identically distributed random variables
1761 /// having N(0,1) distribution. The application of the \f$ \chi^{2} \f$ test has
1762 /// restrictions related to the value of the expected frequencies Npi,
1763 /// Mpi, i=1,...,r. A conservative rule formulated in [5] is that all the
1764 /// expectations must be 1 or greater for both histograms. In practical
1765 /// cases when expected frequencies are not known the estimated expected
1766 /// frequencies \f$ M\hat{p}_{i}, N\hat{p}_{i}, i=1,...,r \f$ can be used.
1767 ///
1768 /// #### Unweighted and weighted histograms comparison:
1769 ///
1770 /// A simple modification of the ideas described above can be used for the
1771 /// comparison of the usual (unweighted) and weighted histograms. Let us
1772 /// denote the number of events in the ith bin in the unweighted
1773 /// histogram as ni and the common weight of events in the ith bin of the
1774 /// weighted histogram as wi. The total number of events in the
1775 /// unweighted histogram is equal to
1776 ///\f[
1777 /// N = \sum_{i=1}^{r} n_{i}
1778 ///\f]
1779 /// and the total weight of events in the weighted histogram is equal to
1780 ///\f[
1781 /// W = \sum_{i=1}^{r} w_{i}
1782 ///\f]
1783 /// Let us formulate the hypothesis of identity of an unweighted histogram
1784 /// to a weighted histogram so that there exist r constants p1,...,pr, such
1785 /// that
1786 ///\f[
1787 /// \sum_{i=1}^{r} p_{i} = 1
1788 ///\f]
1789 /// for the unweighted histogram. The weight wi is a random variable with a
1790 /// distribution approximated by the normal probability distribution
1791 /// \f$ N(Wp_{i},\sigma_{i}^{2}) \f$ where \f$ \sigma_{i}^{2} \f$ is the variance of the weight wi.
1792 /// If we replace the variance \f$ \sigma_{i}^{2} \f$
1793 /// with estimate \f$ s_{i}^{2} \f$ (sum of squares of weights of
1794 /// events in the ith bin) and the hypothesis of identity is valid, then the
1795 /// maximum likelihood estimator of pi,i=1,...,r, is
1796 ///\f[
1797 /// \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}}
1798 ///\f]
1799 /// We may then use the test statistic
1800 ///\f[
1801 /// 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}}
1802 ///\f]
1803 /// and it has approximately a \f$ \sigma^{2}_{(r-1)} \f$ distribution [2]. This test, as well
1804 /// as the original one [3], has a restriction on the expected frequencies. The
1805 /// expected frequencies recommended for the weighted histogram is more than 25.
1806 /// The value of the minimal expected frequency can be decreased down to 10 for
1807 /// the case when the weights of the events are close to constant. In the case
1808 /// of a weighted histogram if the number of events is unknown, then we can
1809 /// apply this recommendation for the equivalent number of events as
1810 ///\f[
1811 /// n_{i}^{equiv} = \frac{ w_{i}^{2} }{ s_{i}^{2} }
1812 ///\f]
1813 /// The minimal expected frequency for an unweighted histogram must be 1. Notice
1814 /// that any usual (unweighted) histogram can be considered as a weighted
1815 /// histogram with events that have constant weights equal to 1.
1816 /// The variance \f$ z_{i}^{2} \f$ of the difference between the weight wi
1817 /// and the estimated expectation value of the weight is approximately equal to:
1818 ///\f[
1819 /// 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}
1820 ///\f]
1821 /// The residuals
1822 ///\f[
1823 /// r_{i} = \frac{w_{i}-W\hat{p}_{i}}{z_{i}}
1824 ///\f]
1825 /// have approximately a normal distribution with mean equal to 0 and standard
1826 /// deviation equal to 1.
1827 ///
1828 /// #### Two weighted histograms comparison:
1829 ///
1830 /// Let us denote the common weight of events of the ith bin in the first
1831 /// histogram as w1i and as w2i in the second one. The total weight of events
1832 /// in the first histogram is equal to
1833 ///\f[
1834 /// W_{1} = \sum_{i=1}^{r} w_{1i}
1835 ///\f]
1836 /// and
1837 ///\f[
1838 /// W_{2} = \sum_{i=1}^{r} w_{2i}
1839 ///\f]
1840 /// in the second histogram. Let us formulate the hypothesis of identity of
1841 /// weighted histograms so that there exist r constants p1,...,pr, such that
1842 ///\f[
1843 /// \sum_{i=1}^{r} p_{i} = 1
1844 ///\f]
1845 /// and also expectation value of weight w1i equal to W1pi and expectation value
1846 /// of weight w2i equal to W2pi. Weights in both the histograms are random
1847 /// variables with distributions which can be approximated by a normal
1848 /// probability distribution \f$ N(W_{1}p_{i},\sigma_{1i}^{2}) \f$ for the first histogram
1849 /// and by a distribution \f$ N(W_{2}p_{i},\sigma_{2i}^{2}) \f$ for the second.
1850 /// Here \f$ \sigma_{1i}^{2} \f$ and \f$ \sigma_{2i}^{2} \f$ are the variances
1851 /// of w1i and w2i with estimators \f$ s_{1i}^{2} \f$ and \f$ s_{2i}^{2} \f$ respectively.
1852 /// If the hypothesis of identity is valid, then the maximum likelihood and
1853 /// Least Square Method estimator of pi,i=1,...,r, is
1854 ///\f[
1855 /// \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}}
1856 ///\f]
1857 /// We may then use the test statistic
1858 ///\f[
1859 /// 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}}
1860 ///\f]
1861 /// and it has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [2].
1862 /// The normalized or studentised residuals [6]
1863 ///\f[
1864 /// 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})}}}
1865 ///\f]
1866 /// have approximately a normal distribution with mean equal to 0 and standard
1867 /// deviation 1. A recommended minimal expected frequency is equal to 10 for
1868 /// the proposed test.
1869 ///
1870 /// #### Numerical examples:
1871 ///
1872 /// The method described herein is now illustrated with an example.
1873 /// We take a distribution
1874 ///\f[
1875 /// \phi(x) = \frac{2}{(x-10)^{2}+1} + \frac{1}{(x-14)^{2}+1} (1)
1876 ///\f]
1877 /// defined on the interval [4,16]. Events distributed according to the formula
1878 /// (1) are simulated to create the unweighted histogram. Uniformly distributed
1879 /// events are simulated for the weighted histogram with weights calculated by
1880 /// formula (1). Each histogram has the same number of bins: 20. Fig.1 shows
1881 /// the result of comparison of the unweighted histogram with 200 events
1882 /// (minimal expected frequency equal to one) and the weighted histogram with
1883 /// 500 events (minimal expected frequency equal to 25)
1884 /// Begin_Macro
1885 /// ../../../tutorials/math/chi2test.C
1886 /// End_Macro
1887 /// Fig 1. An example of comparison of the unweighted histogram with 200 events
1888 /// and the weighted histogram with 500 events:
1889 /// 1. unweighted histogram;
1890 /// 2. weighted histogram;
1891 /// 3. normalized residuals plot;
1892 /// 4. normal Q-Q plot of residuals.
1893 ///
1894 /// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1895 /// 21.09 with p-value equal to 0.33, therefore the hypothesis of identity of
1896 /// the two histograms can be accepted for 0.05 significant level. The behavior
1897 /// of the normalized residuals plot (see Fig. 1c) and the normal Q-Q plot
1898 /// (see Fig. 1d) of residuals are regular and we cannot identify the outliers
1899 /// or bins with a big influence on \f$ \chi^{2} \f$.
1900 ///
1901 /// The second example presents the same two histograms but 17 events was added
1902 /// to content of bin number 15 in unweighted histogram. Fig.2 shows the result
1903 /// of comparison of the unweighted histogram with 217 events (minimal expected
1904 /// frequency equal to one) and the weighted histogram with 500 events (minimal
1905 /// expected frequency equal to 25)
1906 /// Begin_Macro
1907 /// ../../../tutorials/math/chi2test.C(17)
1908 /// End_Macro
1909 /// Fig 2. An example of comparison of the unweighted histogram with 217 events
1910 /// and the weighted histogram with 500 events:
1911 /// 1. unweighted histogram;
1912 /// 2. weighted histogram;
1913 /// 3. normalized residuals plot;
1914 /// 4. normal Q-Q plot of residuals.
1915 ///
1916 /// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1917 /// 32.33 with p-value equal to 0.029, therefore the hypothesis of identity of
1918 /// the two histograms is rejected for 0.05 significant level. The behavior of
1919 /// the normalized residuals plot (see Fig. 2c) and the normal Q-Q plot (see
1920 /// Fig. 2d) of residuals are not regular and we can identify the outlier or
1921 /// bin with a big influence on \f$ \chi^{2} \f$.
1922 ///
1923 /// #### References:
1924 ///
1925 /// - [1] Pearson, K., 1904. On the Theory of Contingency and Its Relation to
1926 /// Association and Normal Correlation. Drapers' Co. Memoirs, Biometric
1927 /// Series No. 1, London.
1928 /// - [2] Gagunashvili, N., 2006. \f$ \sigma^{2} \f$ test for comparison
1929 /// of weighted and unweighted histograms. Statistical Problems in Particle
1930 /// Physics, Astrophysics and Cosmology, Proceedings of PHYSTAT05,
1931 /// Oxford, UK, 12-15 September 2005, Imperial College Press, London, 43-44.
1932 /// Gagunashvili,N., Comparison of weighted and unweighted histograms,
1933 /// arXiv:physics/0605123, 2006.
1934 /// - [3] Cramer, H., 1946. Mathematical methods of statistics.
1935 /// Princeton University Press, Princeton.
1936 /// - [4] Haberman, S.J., 1973. The analysis of residuals in cross-classified tables.
1937 /// Biometrics 29, 205-220.
1938 /// - [5] Lewontin, R.C. and Felsenstein, J., 1965. The robustness of homogeneity
1939 /// test in 2xN tables. Biometrics 21, 19-33.
1940 /// - [6] Seber, G.A.F., Lee, A.J., 2003, Linear Regression Analysis.
1941 /// John Wiley & Sons Inc., New York.
1942 
1943 Double_t TH1::Chi2Test(const TH1* h2, Option_t *option, Double_t *res) const
1944 {
1945  Double_t chi2 = 0;
1946  Int_t ndf = 0, igood = 0;
1947 
1948  TString opt = option;
1949  opt.ToUpper();
1950 
1951  Double_t prob = Chi2TestX(h2,chi2,ndf,igood,option,res);
1952 
1953  if(opt.Contains("P")) {
1954  printf("Chi2 = %f, Prob = %g, NDF = %d, igood = %d\n", chi2,prob,ndf,igood);
1955  }
1956  if(opt.Contains("CHI2/NDF")) {
1957  if (ndf == 0) return 0;
1958  return chi2/ndf;
1959  }
1960  if(opt.Contains("CHI2")) {
1961  return chi2;
1962  }
1963 
1964  return prob;
1965 }
1966 
1967 ////////////////////////////////////////////////////////////////////////////////
1968 /// The computation routine of the Chisquare test. For the method description,
1969 /// see Chi2Test() function.
1970 ///
1971 /// \return p-value
1972 /// \param[in] h2 the second histogram
1973 /// \param[in] option
1974 /// - "UU" = experiment experiment comparison (unweighted-unweighted)
1975 /// - "UW" = experiment MC comparison (unweighted-weighted). Note that the first
1976 /// histogram should be unweighted
1977 /// - "WW" = MC MC comparison (weighted-weighted)
1978 /// - "NORM" = if one or both histograms is scaled
1979 /// - "OF" = overflows included
1980 /// - "UF" = underflows included
1981 /// by default underflows and overflows are not included
1982 /// \param[out] igood test output
1983 /// - igood=0 - no problems
1984 /// - For unweighted unweighted comparison
1985 /// - igood=1'There is a bin in the 1st histogram with less than 1 event'
1986 /// - igood=2'There is a bin in the 2nd histogram with less than 1 event'
1987 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1988 /// - For unweighted weighted comparison
1989 /// - igood=1'There is a bin in the 1st histogram with less then 1 event'
1990 /// - igood=2'There is a bin in the 2nd histogram with less then 10 effective number of events'
1991 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1992 /// - For weighted weighted comparison
1993 /// - igood=1'There is a bin in the 1st histogram with less then 10 effective
1994 /// number of events'
1995 /// - igood=2'There is a bin in the 2nd histogram with less then 10 effective
1996 /// number of events'
1997 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1998 /// \param[out] chi2 chisquare of the test
1999 /// \param[out] ndf number of degrees of freedom (important, when both histograms have the same empty bins)
2000 /// \param[out] res normalized residuals for further analysis
2001 
2002 Double_t TH1::Chi2TestX(const TH1* h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option, Double_t *res) const
2003 {
2005  Int_t i_start, i_end;
2006  Int_t j_start, j_end;
2007  Int_t k_start, k_end;
2008 
2009  Double_t sum1 = 0.0, sumw1 = 0.0;
2010  Double_t sum2 = 0.0, sumw2 = 0.0;
2011 
2012  chi2 = 0.0;
2013  ndf = 0;
2014 
2015  TString opt = option;
2016  opt.ToUpper();
2017 
2018  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
2019 
2020  const TAxis *xaxis1 = GetXaxis();
2021  const TAxis *xaxis2 = h2->GetXaxis();
2022  const TAxis *yaxis1 = GetYaxis();
2023  const TAxis *yaxis2 = h2->GetYaxis();
2024  const TAxis *zaxis1 = GetZaxis();
2025  const TAxis *zaxis2 = h2->GetZaxis();
2026 
2027  Int_t nbinx1 = xaxis1->GetNbins();
2028  Int_t nbinx2 = xaxis2->GetNbins();
2029  Int_t nbiny1 = yaxis1->GetNbins();
2030  Int_t nbiny2 = yaxis2->GetNbins();
2031  Int_t nbinz1 = zaxis1->GetNbins();
2032  Int_t nbinz2 = zaxis2->GetNbins();
2033 
2034  //check dimensions
2035  if (this->GetDimension() != h2->GetDimension() ){
2036  Error("Chi2TestX","Histograms have different dimensions.");
2037  return 0.0;
2038  }
2039 
2040  //check number of channels
2041  if (nbinx1 != nbinx2) {
2042  Error("Chi2TestX","different number of x channels");
2043  }
2044  if (nbiny1 != nbiny2) {
2045  Error("Chi2TestX","different number of y channels");
2046  }
2047  if (nbinz1 != nbinz2) {
2048  Error("Chi2TestX","different number of z channels");
2049  }
2050 
2051  //check for ranges
2052  i_start = j_start = k_start = 1;
2053  i_end = nbinx1;
2054  j_end = nbiny1;
2055  k_end = nbinz1;
2056 
2057  if (xaxis1->TestBit(TAxis::kAxisRange)) {
2058  i_start = xaxis1->GetFirst();
2059  i_end = xaxis1->GetLast();
2060  }
2061  if (yaxis1->TestBit(TAxis::kAxisRange)) {
2062  j_start = yaxis1->GetFirst();
2063  j_end = yaxis1->GetLast();
2064  }
2065  if (zaxis1->TestBit(TAxis::kAxisRange)) {
2066  k_start = zaxis1->GetFirst();
2067  k_end = zaxis1->GetLast();
2068  }
2069 
2070 
2071  if (opt.Contains("OF")) {
2072  if (GetDimension() == 3) k_end = ++nbinz1;
2073  if (GetDimension() >= 2) j_end = ++nbiny1;
2074  if (GetDimension() >= 1) i_end = ++nbinx1;
2075  }
2076 
2077  if (opt.Contains("UF")) {
2078  if (GetDimension() == 3) k_start = 0;
2079  if (GetDimension() >= 2) j_start = 0;
2080  if (GetDimension() >= 1) i_start = 0;
2081  }
2082 
2083  ndf = (i_end - i_start + 1) * (j_end - j_start + 1) * (k_end - k_start + 1) - 1;
2084 
2085  Bool_t comparisonUU = opt.Contains("UU");
2086  Bool_t comparisonUW = opt.Contains("UW");
2087  Bool_t comparisonWW = opt.Contains("WW");
2088  Bool_t scaledHistogram = opt.Contains("NORM");
2089 
2090  if (scaledHistogram && !comparisonUU) {
2091  Info("Chi2TestX", "NORM option should be used together with UU option. It is ignored");
2092  }
2093 
2094  // look at histo global bin content and effective entries
2095  Stat_t s[kNstat];
2096  GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
2097  Double_t sumBinContent1 = s[0];
2098  Double_t effEntries1 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
2099 
2100  h2->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
2101  Double_t sumBinContent2 = s[0];
2102  Double_t effEntries2 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
2103 
2104  if (!comparisonUU && !comparisonUW && !comparisonWW ) {
2105  // deduce automatically from type of histogram
2106  if (TMath::Abs(sumBinContent1 - effEntries1) < 1) {
2107  if ( TMath::Abs(sumBinContent2 - effEntries2) < 1) comparisonUU = true;
2108  else comparisonUW = true;
2109  }
2110  else comparisonWW = true;
2111  }
2112  // check unweighted histogram
2113  if (comparisonUW) {
2114  if (TMath::Abs(sumBinContent1 - effEntries1) >= 1) {
2115  Warning("Chi2TestX","First histogram is not unweighted and option UW has been requested");
2116  }
2117  }
2118  if ( (!scaledHistogram && comparisonUU) ) {
2119  if ( ( TMath::Abs(sumBinContent1 - effEntries1) >= 1) || (TMath::Abs(sumBinContent2 - effEntries2) >= 1) ) {
2120  Warning("Chi2TestX","Both histograms are not unweighted and option UU has been requested");
2121  }
2122  }
2123 
2124 
2125  //get number of events in histogram
2126  if (comparisonUU && scaledHistogram) {
2127  for (Int_t i = i_start; i <= i_end; ++i) {
2128  for (Int_t j = j_start; j <= j_end; ++j) {
2129  for (Int_t k = k_start; k <= k_end; ++k) {
2130 
2131  Int_t bin = GetBin(i, j, k);
2132 
2133  Double_t cnt1 = RetrieveBinContent(bin);
2134  Double_t cnt2 = h2->RetrieveBinContent(bin);
2135  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2136  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2137 
2138  if (e1sq > 0.0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2139  else cnt1 = 0.0;
2140 
2141  if (e2sq > 0.0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2142  else cnt2 = 0.0;
2143 
2144  // sum contents
2145  sum1 += cnt1;
2146  sum2 += cnt2;
2147  sumw1 += e1sq;
2148  sumw2 += e2sq;
2149  }
2150  }
2151  }
2152  if (sumw1 <= 0.0 || sumw2 <= 0.0) {
2153  Error("Chi2TestX", "Cannot use option NORM when one histogram has all zero errors");
2154  return 0.0;
2155  }
2156 
2157  } else {
2158  for (Int_t i = i_start; i <= i_end; ++i) {
2159  for (Int_t j = j_start; j <= j_end; ++j) {
2160  for (Int_t k = k_start; k <= k_end; ++k) {
2161 
2162  Int_t bin = GetBin(i, j, k);
2163 
2164  sum1 += RetrieveBinContent(bin);
2165  sum2 += h2->RetrieveBinContent(bin);
2166 
2167  if ( comparisonWW ) sumw1 += GetBinErrorSqUnchecked(bin);
2168  if ( comparisonUW || comparisonWW ) sumw2 += h2->GetBinErrorSqUnchecked(bin);
2169  }
2170  }
2171  }
2172  }
2173  //checks that the histograms are not empty
2174  if (sum1 == 0.0 || sum2 == 0.0) {
2175  Error("Chi2TestX","one histogram is empty");
2176  return 0.0;
2177  }
2178 
2179  if ( comparisonWW && ( sumw1 <= 0.0 && sumw2 <= 0.0 ) ){
2180  Error("Chi2TestX","Hist1 and Hist2 have both all zero errors\n");
2181  return 0.0;
2182  }
2183 
2184  //THE TEST
2185  Int_t m = 0, n = 0;
2186 
2187  //Experiment - experiment comparison
2188  if (comparisonUU) {
2189  Double_t sum = sum1 + sum2;
2190  for (Int_t i = i_start; i <= i_end; ++i) {
2191  for (Int_t j = j_start; j <= j_end; ++j) {
2192  for (Int_t k = k_start; k <= k_end; ++k) {
2193 
2194  Int_t bin = GetBin(i, j, k);
2195 
2196  Double_t cnt1 = RetrieveBinContent(bin);
2197  Double_t cnt2 = h2->RetrieveBinContent(bin);
2198 
2199  if (scaledHistogram) {
2200  // scale bin value to effective bin entries
2201  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2202  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2203 
2204  if (e1sq > 0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2205  else cnt1 = 0;
2206 
2207  if (e2sq > 0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2208  else cnt2 = 0;
2209  }
2210 
2211  if (Int_t(cnt1) == 0 && Int_t(cnt2) == 0) --ndf; // no data means one degree of freedom less
2212  else {
2213 
2214  Double_t cntsum = cnt1 + cnt2;
2215  Double_t nexp1 = cntsum * sum1 / sum;
2216  //Double_t nexp2 = binsum*sum2/sum;
2217 
2218  if (res) res[i - i_start] = (cnt1 - nexp1) / TMath::Sqrt(nexp1);
2219 
2220  if (cnt1 < 1) ++m;
2221  if (cnt2 < 1) ++n;
2222 
2223  //Habermann correction for residuals
2224  Double_t correc = (1. - sum1 / sum) * (1. - cntsum / sum);
2225  if (res) res[i - i_start] /= TMath::Sqrt(correc);
2226 
2227  Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2228  chi2 += delta * delta / cntsum;
2229  }
2230  }
2231  }
2232  }
2233  chi2 /= sum1 * sum2;
2234 
2235  // flag error only when of the two histogram is zero
2236  if (m) {
2237  igood += 1;
2238  Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2239  }
2240  if (n) {
2241  igood += 2;
2242  Info("Chi2TestX","There is a bin in h2 with less than 1 event.\n");
2243  }
2244 
2245  Double_t prob = TMath::Prob(chi2,ndf);
2246  return prob;
2247 
2248  }
2249 
2250  // unweighted - weighted comparison
2251  // case of error = 0 and content not zero is treated without problems by excluding second chi2 sum
2252  // and can be considered as a data-theory comparison
2253  if ( comparisonUW ) {
2254  for (Int_t i = i_start; i <= i_end; ++i) {
2255  for (Int_t j = j_start; j <= j_end; ++j) {
2256  for (Int_t k = k_start; k <= k_end; ++k) {
2257 
2258  Int_t bin = GetBin(i, j, k);
2259 
2260  Double_t cnt1 = RetrieveBinContent(bin);
2261  Double_t cnt2 = h2->RetrieveBinContent(bin);
2262  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2263 
2264  // case both histogram have zero bin contents
2265  if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2266  --ndf; //no data means one degree of freedom less
2267  continue;
2268  }
2269 
2270  // case weighted histogram has zero bin content and error
2271  if (cnt2 * cnt2 == 0 && e2sq == 0) {
2272  if (sumw2 > 0) {
2273  // use as approximated error as 1 scaled by a scaling ratio
2274  // estimated from the total sum weight and sum weight squared
2275  e2sq = sumw2 / sum2;
2276  }
2277  else {
2278  // return error because infinite discrepancy here:
2279  // bin1 != 0 and bin2 =0 in a histogram with all errors zero
2280  Error("Chi2TestX","Hist2 has in bin (%d,%d,%d) zero content and zero errors\n", i, j, k);
2281  chi2 = 0; return 0;
2282  }
2283  }
2284 
2285  if (cnt1 < 1) m++;
2286  if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2287 
2288  Double_t var1 = sum2 * cnt2 - sum1 * e2sq;
2289  Double_t var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2290 
2291  // if cnt1 is zero and cnt2 = 1 and sum1 = sum2 var1 = 0 && var2 == 0
2292  // approximate by incrementing cnt1
2293  // LM (this need to be fixed for numerical errors)
2294  while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2295  sum1++;
2296  cnt1++;
2297  var1 = sum2 * cnt2 - sum1 * e2sq;
2298  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2299  }
2300  var2 = TMath::Sqrt(var2);
2301 
2302  while (var1 + var2 == 0) {
2303  sum1++;
2304  cnt1++;
2305  var1 = sum2 * cnt2 - sum1 * e2sq;
2306  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2307  while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2308  sum1++;
2309  cnt1++;
2310  var1 = sum2 * cnt2 - sum1 * e2sq;
2311  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2312  }
2313  var2 = TMath::Sqrt(var2);
2314  }
2315 
2316  Double_t probb = (var1 + var2) / (2. * sum2 * sum2);
2317 
2318  Double_t nexp1 = probb * sum1;
2319  Double_t nexp2 = probb * sum2;
2320 
2321  Double_t delta1 = cnt1 - nexp1;
2322  Double_t delta2 = cnt2 - nexp2;
2323 
2324  chi2 += delta1 * delta1 / nexp1;
2325 
2326  if (e2sq > 0) {
2327  chi2 += delta2 * delta2 / e2sq;
2328  }
2329 
2330  if (res) {
2331  if (e2sq > 0) {
2332  Double_t temp1 = sum2 * e2sq / var2;
2333  Double_t temp2 = 1.0 + (sum1 * e2sq - sum2 * cnt2) / var2;
2334  temp2 = temp1 * temp1 * sum1 * probb * (1.0 - probb) + temp2 * temp2 * e2sq / 4.0;
2335  // invert sign here
2336  res[i - i_start] = - delta2 / TMath::Sqrt(temp2);
2337  }
2338  else
2339  res[i - i_start] = delta1 / TMath::Sqrt(nexp1);
2340  }
2341  }
2342  }
2343  }
2344 
2345  if (m) {
2346  igood += 1;
2347  Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2348  }
2349  if (n) {
2350  igood += 2;
2351  Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2352  }
2353 
2354  Double_t prob = TMath::Prob(chi2, ndf);
2355 
2356  return prob;
2357  }
2358 
2359  // weighted - weighted comparison
2360  if (comparisonWW) {
2361  for (Int_t i = i_start; i <= i_end; ++i) {
2362  for (Int_t j = j_start; j <= j_end; ++j) {
2363  for (Int_t k = k_start; k <= k_end; ++k) {
2364 
2365  Int_t bin = GetBin(i, j, k);
2366  Double_t cnt1 = RetrieveBinContent(bin);
2367  Double_t cnt2 = h2->RetrieveBinContent(bin);
2368  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2369  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2370 
2371  // case both histogram have zero bin contents
2372  // (use square of content to avoid numerical errors)
2373  if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2374  --ndf; //no data means one degree of freedom less
2375  continue;
2376  }
2377 
2378  if (e1sq == 0 && e2sq == 0) {
2379  // cannot treat case of booth histogram have zero zero errors
2380  Error("Chi2TestX","h1 and h2 both have bin %d,%d,%d with all zero errors\n", i,j,k);
2381  chi2 = 0; return 0;
2382  }
2383 
2384  Double_t sigma = sum1 * sum1 * e2sq + sum2 * sum2 * e1sq;
2385  Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2386  chi2 += delta * delta / sigma;
2387 
2388  if (res) {
2389  Double_t temp = cnt1 * sum1 * e2sq + cnt2 * sum2 * e1sq;
2390  Double_t probb = temp / sigma;
2391  Double_t z = 0;
2392  if (e1sq > e2sq) {
2393  Double_t d1 = cnt1 - sum1 * probb;
2394  Double_t s1 = e1sq * ( 1. - e2sq * sum1 * sum1 / sigma );
2395  z = d1 / TMath::Sqrt(s1);
2396  }
2397  else {
2398  Double_t d2 = cnt2 - sum2 * probb;
2399  Double_t s2 = e2sq * ( 1. - e1sq * sum2 * sum2 / sigma );
2400  z = -d2 / TMath::Sqrt(s2);
2401  }
2402  res[i - i_start] = z;
2403  }
2404 
2405  if (e1sq > 0 && cnt1 * cnt1 / e1sq < 10) m++;
2406  if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2407  }
2408  }
2409  }
2410  if (m) {
2411  igood += 1;
2412  Info("Chi2TestX","There is a bin in h1 with less than 10 effective events.\n");
2413  }
2414  if (n) {
2415  igood += 2;
2416  Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2417  }
2418  Double_t prob = TMath::Prob(chi2, ndf);
2419  return prob;
2420  }
2421  return 0;
2422 }
2423 ////////////////////////////////////////////////////////////////////////////////
2424 /// Compute and return the chisquare of this histogram with respect to a function
2425 /// The chisquare is computed by weighting each histogram point by the bin error
2426 /// By default the full range of the histogram is used.
2427 /// Use option "R" for restricting the chisquare calculation to the given range of the function
2428 /// Use option "L" for using the chisquare based on the poisson likelihood (Baker-Cousins Chisquare)
2429 
2430 Double_t TH1::Chisquare(TF1 * func, Option_t *option) const
2431 {
2432  if (!func) {
2433  Error("Chisquare","Function pointer is Null - return -1");
2434  return -1;
2435  }
2436 
2437  TString opt(option); opt.ToUpper();
2438  bool useRange = opt.Contains("R");
2439  bool usePL = opt.Contains("L");
2440 
2441  return ROOT::Fit::Chisquare(*this, *func, useRange, usePL);
2442 }
2443 
2444 ////////////////////////////////////////////////////////////////////////////////
2445 /// Remove all the content from the underflow and overflow bins, without changing the number of entries
2446 /// After calling this method, every undeflow and overflow bins will have content 0.0
2447 /// The Sumw2 is also cleared, since there is no more content in the bins
2448 
2450 {
2451  for (Int_t bin = 0; bin < fNcells; ++bin)
2452  if (IsBinUnderflow(bin) || IsBinOverflow(bin)) {
2453  UpdateBinContent(bin, 0.0);
2454  if (fSumw2.fN) fSumw2.fArray[bin] = 0.0;
2455  }
2456 }
2457 
2458 ////////////////////////////////////////////////////////////////////////////////
2459 /// Compute integral (cumulative sum of bins)
2460 /// The result stored in fIntegral is used by the GetRandom functions.
2461 /// This function is automatically called by GetRandom when the fIntegral
2462 /// array does not exist or when the number of entries in the histogram
2463 /// has changed since the previous call to GetRandom.
2464 /// The resulting integral is normalized to 1
2465 /// If the routine is called with the onlyPositive flag set an error will
2466 /// be produced in case of negative bin content and a NaN value returned
2467 
2468 Double_t TH1::ComputeIntegral(Bool_t onlyPositive)
2469 {
2471 
2472  // delete previously computed integral (if any)
2473  if (fIntegral) delete [] fIntegral;
2474 
2475  // - Allocate space to store the integral and compute integral
2476  Int_t nbinsx = GetNbinsX();
2477  Int_t nbinsy = GetNbinsY();
2478  Int_t nbinsz = GetNbinsZ();
2479  Int_t nbins = nbinsx * nbinsy * nbinsz;
2480 
2481  fIntegral = new Double_t[nbins + 2];
2482  Int_t ibin = 0; fIntegral[ibin] = 0;
2483 
2484  for (Int_t binz=1; binz <= nbinsz; ++binz) {
2485  for (Int_t biny=1; biny <= nbinsy; ++biny) {
2486  for (Int_t binx=1; binx <= nbinsx; ++binx) {
2487  ++ibin;
2488  Double_t y = RetrieveBinContent(GetBin(binx, biny, binz));
2489  if (onlyPositive && y < 0) {
2490  Error("ComputeIntegral","Bin content is negative - return a NaN value");
2491  fIntegral[nbins] = TMath::QuietNaN();
2492  break;
2493  }
2494  fIntegral[ibin] = fIntegral[ibin - 1] + y;
2495  }
2496  }
2497  }
2498 
2499  // - Normalize integral to 1
2500  if (fIntegral[nbins] == 0 ) {
2501  Error("ComputeIntegral", "Integral = zero"); return 0;
2502  }
2503  for (Int_t bin=1; bin <= nbins; ++bin) fIntegral[bin] /= fIntegral[nbins];
2504  fIntegral[nbins+1] = fEntries;
2505  return fIntegral[nbins];
2506 }
2507 
2508 ////////////////////////////////////////////////////////////////////////////////
2509 /// Return a pointer to the array of bins integral.
2510 /// if the pointer fIntegral is null, TH1::ComputeIntegral is called
2511 /// The array dimension is the number of bins in the histograms
2512 /// including underflow and overflow (fNCells)
2513 /// the last value integral[fNCells] is set to the number of entries of
2514 /// the histogram
2515 
2517 {
2519  return fIntegral;
2520 }
2521 
2522 ////////////////////////////////////////////////////////////////////////////////
2523 /// Return a pointer to an histogram containing the cumulative The
2524 /// cumulative can be computed both in the forward (default) or backward
2525 /// direction; the name of the new histogram is constructed from
2526 /// the name of this histogram with the suffix suffix appended.
2527 ///
2528 /// The cumulative distribution is formed by filling each bin of the
2529 /// resulting histogram with the sum of that bin and all previous
2530 /// (forward == kTRUE) or following (forward = kFALSE) bins.
2531 ///
2532 /// note: while cumulative distributions make sense in one dimension, you
2533 /// may not be getting what you expect in more than 1D because the concept
2534 /// of a cumulative distribution is much trickier to define; make sure you
2535 /// understand the order of summation before you use this method with
2536 /// histograms of dimension >= 2.
2537 
2538 TH1 *TH1::GetCumulative(Bool_t forward, const char* suffix) const
2539 {
2540  const Int_t nbinsx = GetNbinsX();
2541  const Int_t nbinsy = GetNbinsY();
2542  const Int_t nbinsz = GetNbinsZ();
2543  TH1* hintegrated = (TH1*) Clone(fName + suffix);
2544  hintegrated->Reset();
2545  if (forward) { // Forward computation
2546  Double_t sum = 0.;
2547  for (Int_t binz = 1; binz <= nbinsz; ++binz) {
2548  for (Int_t biny = 1; biny <= nbinsy; ++biny) {
2549  for (Int_t binx = 1; binx <= nbinsx; ++binx) {
2550  const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2551  sum += GetBinContent(bin);
2552  hintegrated->SetBinContent(bin, sum);
2553  }
2554  }
2555  }
2556  } else { // Backward computation
2557  Double_t sum = 0.;
2558  for (Int_t binz = nbinsz; binz >= 1; --binz) {
2559  for (Int_t biny = nbinsy; biny >= 1; --biny) {
2560  for (Int_t binx = nbinsx; binx >= 1; --binx) {
2561  const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2562  sum += GetBinContent(bin);
2563  hintegrated->SetBinContent(bin, sum);
2564  }
2565  }
2566  }
2567  }
2568  return hintegrated;
2569 }
2570 
2571 ////////////////////////////////////////////////////////////////////////////////
2572 /// Copy this histogram structure to newth1.
2573 ///
2574 /// Note that this function does not copy the list of associated functions.
2575 /// Use TObject::Clone to make a full copy of an histogram.
2576 ///
2577 /// Note also that the histogram it will be created in gDirectory (if AddDirectoryStatus()=true)
2578 /// or will not be added to any directory if AddDirectoryStatus()=false
2579 /// independently of the current directory stored in the original histogram
2580 
2581 void TH1::Copy(TObject &obj) const
2582 {
2583  if (((TH1&)obj).fDirectory) {
2584  // We are likely to change the hash value of this object
2585  // with TNamed::Copy, to keep things correct, we need to
2586  // clean up its existing entries.
2587  ((TH1&)obj).fDirectory->Remove(&obj);
2588  ((TH1&)obj).fDirectory = 0;
2589  }
2590  TNamed::Copy(obj);
2591  ((TH1&)obj).fDimension = fDimension;
2592  ((TH1&)obj).fNormFactor= fNormFactor;
2593  ((TH1&)obj).fNcells = fNcells;
2594  ((TH1&)obj).fBarOffset = fBarOffset;
2595  ((TH1&)obj).fBarWidth = fBarWidth;
2596  ((TH1&)obj).fOption = fOption;
2597  ((TH1&)obj).fBinStatErrOpt = fBinStatErrOpt;
2598  ((TH1&)obj).fBufferSize= fBufferSize;
2599  // copy the Buffer
2600  // delete first a previously existing buffer
2601  if (((TH1&)obj).fBuffer != 0) {
2602  delete [] ((TH1&)obj).fBuffer;
2603  ((TH1&)obj).fBuffer = 0;
2604  }
2605  if (fBuffer) {
2606  Double_t *buf = new Double_t[fBufferSize];
2607  for (Int_t i=0;i<fBufferSize;i++) buf[i] = fBuffer[i];
2608  // obj.fBuffer has been deleted before
2609  ((TH1&)obj).fBuffer = buf;
2610  }
2611 
2612 
2613  TArray* a = dynamic_cast<TArray*>(&obj);
2614  if (a) a->Set(fNcells);
2615  for (Int_t i = 0; i < fNcells; i++) ((TH1&)obj).UpdateBinContent(i, RetrieveBinContent(i));
2616 
2617  ((TH1&)obj).fEntries = fEntries;
2618 
2619  // which will call BufferEmpty(0) and set fBuffer[0] to a Maybe one should call
2620  // assignment operator on the TArrayD
2621 
2622  ((TH1&)obj).fTsumw = fTsumw;
2623  ((TH1&)obj).fTsumw2 = fTsumw2;
2624  ((TH1&)obj).fTsumwx = fTsumwx;
2625  ((TH1&)obj).fTsumwx2 = fTsumwx2;
2626  ((TH1&)obj).fMaximum = fMaximum;
2627  ((TH1&)obj).fMinimum = fMinimum;
2628 
2629  TAttLine::Copy(((TH1&)obj));
2630  TAttFill::Copy(((TH1&)obj));
2631  TAttMarker::Copy(((TH1&)obj));
2632  fXaxis.Copy(((TH1&)obj).fXaxis);
2633  fYaxis.Copy(((TH1&)obj).fYaxis);
2634  fZaxis.Copy(((TH1&)obj).fZaxis);
2635  ((TH1&)obj).fXaxis.SetParent(&obj);
2636  ((TH1&)obj).fYaxis.SetParent(&obj);
2637  ((TH1&)obj).fZaxis.SetParent(&obj);
2638  fContour.Copy(((TH1&)obj).fContour);
2639  fSumw2.Copy(((TH1&)obj).fSumw2);
2640  // fFunctions->Copy(((TH1&)obj).fFunctions);
2641  // when copying an histogram if the AddDirectoryStatus() is true it
2642  // will be added to gDirectory independently of the fDirectory stored.
2643  // and if the AddDirectoryStatus() is false it will not be added to
2644  // any directory (fDirectory = 0)
2645  if (fgAddDirectory && gDirectory) {
2646  gDirectory->Append(&obj);
2647  ((TH1&)obj).fFunctions->UseRWLock();
2648  ((TH1&)obj).fDirectory = gDirectory;
2649  } else
2650  ((TH1&)obj).fDirectory = 0;
2651 
2652 }
2653 
2654 ////////////////////////////////////////////////////////////////////////////////
2655 /// Make a complete copy of the underlying object. If 'newname' is set,
2656 /// the copy's name will be set to that name.
2657 
2658 TObject* TH1::Clone(const char* newname) const
2659 {
2660  TH1* obj = (TH1*)IsA()->GetNew()(0);
2661  Copy(*obj);
2662 
2663  //Now handle the parts that Copy doesn't do
2664  if(fFunctions) {
2665  if (obj->fFunctions) delete obj->fFunctions;
2666  obj->fFunctions = (TList*)fFunctions->Clone();
2667  }
2668  if(newname && strlen(newname) ) {
2669  obj->SetName(newname);
2670  }
2671  return obj;
2672 }
2673 
2674 ////////////////////////////////////////////////////////////////////////////////
2675 /// Perform the automatic addition of the histogram to the given directory
2676 ///
2677 /// Note this function is called in place when the semantic requires
2678 /// this object to be added to a directory (I.e. when being read from
2679 /// a TKey or being Cloned)
2680 
2682 {
2684  if (addStatus) {
2685  SetDirectory(dir);
2686  if (dir) {
2688  }
2689  }
2690 }
2691 
2692 ////////////////////////////////////////////////////////////////////////////////
2693 /// Compute distance from point px,py to a line.
2694 ///
2695 /// Compute the closest distance of approach from point px,py to elements
2696 /// of an histogram.
2697 /// The distance is computed in pixels units.
2698 ///
2699 /// #### Algorithm:
2700 /// Currently, this simple model computes the distance from the mouse
2701 /// to the histogram contour only.
2702 
2704 {
2705  if (!fPainter) return 9999;
2706  return fPainter->DistancetoPrimitive(px,py);
2707 }
2708 
2709 ////////////////////////////////////////////////////////////////////////////////
2710 /// Performs the operation: `this = this/(c1*f1)`
2711 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2712 ///
2713 /// Only bins inside the function range are recomputed.
2714 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2715 /// you should call Sumw2 before making this operation.
2716 /// This is particularly important if you fit the histogram after TH1::Divide
2717 ///
2718 /// The function return kFALSE if the divide operation failed
2719 
2721 {
2722  if (!f1) {
2723  Error("Add","Attempt to divide by a non-existing function");
2724  return kFALSE;
2725  }
2726 
2727  // delete buffer if it is there since it will become invalid
2728  if (fBuffer) BufferEmpty(1);
2729 
2730  Int_t nx = GetNbinsX() + 2; // normal bins + uf / of
2731  Int_t ny = GetNbinsY() + 2;
2732  Int_t nz = GetNbinsZ() + 2;
2733  if (fDimension < 2) ny = 1;
2734  if (fDimension < 3) nz = 1;
2735 
2736 
2737  SetMinimum();
2738  SetMaximum();
2739 
2740  // - Loop on bins (including underflows/overflows)
2741  Int_t bin, binx, biny, binz;
2742  Double_t cu, w;
2743  Double_t xx[3];
2744  Double_t *params = 0;
2745  f1->InitArgs(xx,params);
2746  for (binz = 0; binz < nz; ++binz) {
2747  xx[2] = fZaxis.GetBinCenter(binz);
2748  for (biny = 0; biny < ny; ++biny) {
2749  xx[1] = fYaxis.GetBinCenter(biny);
2750  for (binx = 0; binx < nx; ++binx) {
2751  xx[0] = fXaxis.GetBinCenter(binx);
2752  if (!f1->IsInside(xx)) continue;
2754  bin = binx + nx * (biny + ny * binz);
2755  cu = c1 * f1->EvalPar(xx);
2756  if (TF1::RejectedPoint()) continue;
2757  if (cu) w = RetrieveBinContent(bin) / cu;
2758  else w = 0;
2759  UpdateBinContent(bin, w);
2760  if (fSumw2.fN) {
2761  if (cu != 0) fSumw2.fArray[bin] = GetBinErrorSqUnchecked(bin) / (cu * cu);
2762  else fSumw2.fArray[bin] = 0;
2763  }
2764  }
2765  }
2766  }
2767  ResetStats();
2768  return kTRUE;
2769 }
2770 
2771 ////////////////////////////////////////////////////////////////////////////////
2772 /// Divide this histogram by h1.
2773 ///
2774 /// `this = this/h1`
2775 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2776 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
2777 /// if not already set.
2778 /// The resulting errors are calculated assuming uncorrelated histograms.
2779 /// See the other TH1::Divide that gives the possibility to optionally
2780 /// compute binomial errors.
2781 ///
2782 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2783 /// you should call Sumw2 before making this operation.
2784 /// This is particularly important if you fit the histogram after TH1::Scale
2785 ///
2786 /// The function return kFALSE if the divide operation failed
2787 
2788 Bool_t TH1::Divide(const TH1 *h1)
2789 {
2790  if (!h1) {
2791  Error("Divide", "Input histogram passed does not exist (NULL).");
2792  return kFALSE;
2793  }
2794 
2795  // delete buffer if it is there since it will become invalid
2796  if (fBuffer) BufferEmpty(1);
2797 
2798  try {
2799  CheckConsistency(this,h1);
2800  } catch(DifferentNumberOfBins&) {
2801  Error("Divide","Cannot divide histograms with different number of bins");
2802  return kFALSE;
2803  } catch(DifferentAxisLimits&) {
2804  Warning("Divide","Dividing histograms with different axis limits");
2805  } catch(DifferentBinLimits&) {
2806  Warning("Divide","Dividing histograms with different bin limits");
2807  } catch(DifferentLabels&) {
2808  Warning("Divide","Dividing histograms with different labels");
2809  }
2810 
2811  // Create Sumw2 if h1 has Sumw2 set
2812  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
2813 
2814  // - Loop on bins (including underflows/overflows)
2815  for (Int_t i = 0; i < fNcells; ++i) {
2816  Double_t c0 = RetrieveBinContent(i);
2818  if (c1) UpdateBinContent(i, c0 / c1);
2819  else UpdateBinContent(i, 0);
2820 
2821  if(fSumw2.fN) {
2822  if (c1 == 0) { fSumw2.fArray[i] = 0; continue; }
2823  Double_t c1sq = c1 * c1;
2824  fSumw2.fArray[i] = (GetBinErrorSqUnchecked(i) * c1sq + h1->GetBinErrorSqUnchecked(i) * c0 * c0) / (c1sq * c1sq);
2825  }
2826  }
2827  ResetStats();
2828  return kTRUE;
2829 }
2830 
2831 ////////////////////////////////////////////////////////////////////////////////
2832 /// Replace contents of this histogram by the division of h1 by h2.
2833 ///
2834 /// `this = c1*h1/(c2*h2)`
2835 ///
2836 /// If errors are defined (see TH1::Sumw2), errors are also recalculated
2837 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
2838 /// if not already set.
2839 /// The resulting errors are calculated assuming uncorrelated histograms.
2840 /// However, if option ="B" is specified, Binomial errors are computed.
2841 /// In this case c1 and c2 do not make real sense and they are ignored.
2842 ///
2843 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2844 /// you should call Sumw2 before making this operation.
2845 /// This is particularly important if you fit the histogram after TH1::Divide
2846 ///
2847 /// Please note also that in the binomial case errors are calculated using standard
2848 /// binomial statistics, which means when b1 = b2, the error is zero.
2849 /// If you prefer to have efficiency errors not going to zero when the efficiency is 1, you must
2850 /// use the function TGraphAsymmErrors::BayesDivide, which will return an asymmetric and non-zero lower
2851 /// error for the case b1=b2.
2852 ///
2853 /// The function return kFALSE if the divide operation failed
2854 
2855 Bool_t TH1::Divide(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2, Option_t *option)
2856 {
2858  TString opt = option;
2859  opt.ToLower();
2860  Bool_t binomial = kFALSE;
2861  if (opt.Contains("b")) binomial = kTRUE;
2862  if (!h1 || !h2) {
2863  Error("Divide", "At least one of the input histograms passed does not exist (NULL).");
2864  return kFALSE;
2865  }
2866 
2867  // delete buffer if it is there since it will become invalid
2868  if (fBuffer) BufferEmpty(1);
2869 
2870  try {
2871  CheckConsistency(h1,h2);
2872  CheckConsistency(this,h1);
2873  } catch(DifferentNumberOfBins&) {
2874  Error("Divide","Cannot divide histograms with different number of bins");
2875  return kFALSE;
2876  } catch(DifferentAxisLimits&) {
2877  Warning("Divide","Dividing histograms with different axis limits");
2878  } catch(DifferentBinLimits&) {
2879  Warning("Divide","Dividing histograms with different bin limits");
2880  } catch(DifferentLabels&) {
2881  Warning("Divide","Dividing histograms with different labels");
2882  }
2883 
2884 
2885  if (!c2) {
2886  Error("Divide","Coefficient of dividing histogram cannot be zero");
2887  return kFALSE;
2888  }
2889 
2890  // Create Sumw2 if h1 or h2 have Sumw2 set
2891  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
2892 
2893  SetMinimum();
2894  SetMaximum();
2895 
2896  // - Loop on bins (including underflows/overflows)
2897  for (Int_t i = 0; i < fNcells; ++i) {
2898  Double_t b1 = h1->RetrieveBinContent(i);
2899  Double_t b2 = h2->RetrieveBinContent(i);
2900  if (b2) UpdateBinContent(i, c1 * b1 / (c2 * b2));
2901  else UpdateBinContent(i, 0);
2902 
2903  if (fSumw2.fN) {
2904  if (b2 == 0) { fSumw2.fArray[i] = 0; continue; }
2905  Double_t b1sq = b1 * b1; Double_t b2sq = b2 * b2;
2906  Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
2907  Double_t e1sq = h1->GetBinErrorSqUnchecked(i);
2908  Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
2909  if (binomial) {
2910  if (b1 != b2) {
2911  // in the case of binomial statistics c1 and c2 must be 1 otherwise it does not make sense
2912  // c1 and c2 are ignored
2913  //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/(c2*b2));//this is the formula in Hbook/Hoper1
2914  //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/b2); // old formula from G. Flucke
2915  // formula which works also for weighted histogram (see http://root-forum.cern.ch/viewtopic.php?t=3753 )
2916  fSumw2.fArray[i] = TMath::Abs( ( (1. - 2.* b1 / b2) * e1sq + b1sq * e2sq / b2sq ) / b2sq );
2917  } else {
2918  //in case b1=b2 error is zero
2919  //use TGraphAsymmErrors::BayesDivide for getting the asymmetric error not equal to zero
2920  fSumw2.fArray[i] = 0;
2921  }
2922  } else {
2923  fSumw2.fArray[i] = c1sq * c2sq * (e1sq * b2sq + e2sq * b1sq) / (c2sq * c2sq * b2sq * b2sq);
2924  }
2925  }
2926  }
2927  ResetStats();
2928  if (binomial)
2929  // in case of binomial division use denominator for number of entries
2930  SetEntries ( h2->GetEntries() );
2931 
2932  return kTRUE;
2933 }
2934 
2935 ////////////////////////////////////////////////////////////////////////////////
2936 /// Draw this histogram with options.
2937 ///
2938 /// Histograms are drawn via the THistPainter class. Each histogram has
2939 /// a pointer to its own painter (to be usable in a multithreaded program).
2940 /// The same histogram can be drawn with different options in different pads.
2941 /// When an histogram drawn in a pad is deleted, the histogram is
2942 /// automatically removed from the pad or pads where it was drawn.
2943 /// If an histogram is drawn in a pad, then filled again, the new status
2944 /// of the histogram will be automatically shown in the pad next time
2945 /// the pad is updated. One does not need to redraw the histogram.
2946 /// To draw the current version of an histogram in a pad, one can use
2947 /// `h->DrawCopy();`
2948 /// This makes a clone of the histogram. Once the clone is drawn, the original
2949 /// histogram may be modified or deleted without affecting the aspect of the
2950 /// clone.
2951 /// By default, TH1::Draw clears the current pad.
2952 ///
2953 /// One can use TH1::SetMaximum and TH1::SetMinimum to force a particular
2954 /// value for the maximum or the minimum scale on the plot.
2955 ///
2956 /// TH1::UseCurrentStyle can be used to change all histogram graphics
2957 /// attributes to correspond to the current selected style.
2958 /// This function must be called for each histogram.
2959 /// In case one reads and draws many histograms from a file, one can force
2960 /// the histograms to inherit automatically the current graphics style
2961 /// by calling before gROOT->ForceStyle();
2962 ///
2963 /// See the THistPainter class for a description of all the drawing options.
2964 
2965 void TH1::Draw(Option_t *option)
2966 {
2967  TString opt1 = option; opt1.ToLower();
2968  TString opt2 = option;
2969  Int_t index = opt1.Index("same");
2970 
2971  // Check if the string "same" is part of a TCutg name.
2972  if (index>=0) {
2973  Int_t indb = opt1.Index("[");
2974  if (indb>=0) {
2975  Int_t indk = opt1.Index("]");
2976  if (index>indb && index<indk) index = -1;
2977  }
2978  }
2979 
2980  // If there is no pad or an empty pad the "same" option is ignored.
2981  if (gPad) {
2982  if (!gPad->IsEditable()) gROOT->MakeDefCanvas();
2983  if (index>=0) {
2984  if (gPad->GetX1() == 0 && gPad->GetX2() == 1 &&
2985  gPad->GetY1() == 0 && gPad->GetY2() == 1 &&
2986  gPad->GetListOfPrimitives()->GetSize()==0) opt2.Remove(index,4);
2987  } else {
2988  //the following statement is necessary in case one attempts to draw
2989  //a temporary histogram already in the current pad
2990  if (TestBit(kCanDelete)) gPad->GetListOfPrimitives()->Remove(this);
2991  gPad->Clear();
2992  }
2993  gPad->IncrementPaletteColor(1, opt1);
2994  } else {
2995  if (index>=0) opt2.Remove(index,4);
2996  }
2997 
2998  AppendPad(opt2.Data());
2999 }
3000 
3001 ////////////////////////////////////////////////////////////////////////////////
3002 /// Copy this histogram and Draw in the current pad.
3003 ///
3004 /// Once the histogram is drawn into the pad, any further modification
3005 /// using graphics input will be made on the copy of the histogram,
3006 /// and not to the original object.
3007 /// By default a postfix "_copy" is added to the histogram name. Pass an empty postfix in case
3008 /// you want to draw an histogram with the same name
3009 ///
3010 /// See Draw for the list of options
3011 
3012 TH1 *TH1::DrawCopy(Option_t *option, const char * name_postfix) const
3013 {
3014  TString opt = option;
3015  opt.ToLower();
3016  if (gPad && !opt.Contains("same")) gPad->Clear();
3017  TString newName = (name_postfix) ? TString::Format("%s%s",GetName(),name_postfix) : "";
3018  TH1 *newth1 = (TH1 *)Clone(newName);
3019  newth1->SetDirectory(0);
3020  newth1->SetBit(kCanDelete);
3021  newth1->AppendPad(option);
3022  return newth1;
3023 }
3024 
3025 ////////////////////////////////////////////////////////////////////////////////
3026 /// Draw a normalized copy of this histogram.
3027 ///
3028 /// A clone of this histogram is normalized to norm and drawn with option.
3029 /// A pointer to the normalized histogram is returned.
3030 /// The contents of the histogram copy are scaled such that the new
3031 /// sum of weights (excluding under and overflow) is equal to norm.
3032 /// Note that the returned normalized histogram is not added to the list
3033 /// of histograms in the current directory in memory.
3034 /// It is the user's responsibility to delete this histogram.
3035 /// The kCanDelete bit is set for the returned object. If a pad containing
3036 /// this copy is cleared, the histogram will be automatically deleted.
3037 ///
3038 /// See Draw for the list of options
3039 
3040 TH1 *TH1::DrawNormalized(Option_t *option, Double_t norm) const
3041 {
3043  if (sum == 0) {
3044  Error("DrawNormalized","Sum of weights is null. Cannot normalize histogram: %s",GetName());
3045  return 0;
3046  }
3047  Bool_t addStatus = TH1::AddDirectoryStatus();
3049  TH1 *h = (TH1*)Clone();
3050  h->SetBit(kCanDelete);
3051  // in case of drawing with error options - scale correctly the error
3052  TString opt(option); opt.ToUpper();
3053  if (fSumw2.fN == 0) {
3054  h->Sumw2();
3055  // do not use in this case the "Error option " for drawing which is enabled by default since the normalized histogram has now errors
3056  if (opt.IsNull() || opt == "SAME") opt += "HIST";
3057  }
3058  h->Scale(norm/sum);
3059  if (TMath::Abs(fMaximum+1111) > 1e-3) h->SetMaximum(fMaximum*norm/sum);
3060  if (TMath::Abs(fMinimum+1111) > 1e-3) h->SetMinimum(fMinimum*norm/sum);
3061  h->Draw(opt);
3062  TH1::AddDirectory(addStatus);
3063  return h;
3064 }
3065 
3066 ////////////////////////////////////////////////////////////////////////////////
3067 /// Display a panel with all histogram drawing options.
3068 ///
3069 /// See class TDrawPanelHist for example
3070 
3071 void TH1::DrawPanel()
3072 {
3073  if (!fPainter) {Draw(); if (gPad) gPad->Update();}
3074  if (fPainter) fPainter->DrawPanel();
3075 }
3076 
3077 ////////////////////////////////////////////////////////////////////////////////
3078 /// Evaluate function f1 at the center of bins of this histogram.
3079 ///
3080 /// - If option "R" is specified, the function is evaluated only
3081 /// for the bins included in the function range.
3082 /// - If option "A" is specified, the value of the function is added to the
3083 /// existing bin contents
3084 /// - If option "S" is specified, the value of the function is used to
3085 /// generate a value, distributed according to the Poisson
3086 /// distribution, with f1 as the mean.
3087 
3088 void TH1::Eval(TF1 *f1, Option_t *option)
3089 {
3091  Int_t range, stat, add;
3092  if (!f1) return;
3093 
3094  TString opt = option;
3095  opt.ToLower();
3096  if (opt.Contains("a")) add = 1;
3097  else add = 0;
3098  if (opt.Contains("s")) stat = 1;
3099  else stat = 0;
3100  if (opt.Contains("r")) range = 1;
3101  else range = 0;
3102 
3103  // delete buffer if it is there since it will become invalid
3104  if (fBuffer) BufferEmpty(1);
3105 
3106  Int_t nbinsx = fXaxis.GetNbins();
3107  Int_t nbinsy = fYaxis.GetNbins();
3108  Int_t nbinsz = fZaxis.GetNbins();
3109  if (!add) Reset();
3110 
3111  for (Int_t binz = 1; binz <= nbinsz; ++binz) {
3112  x[2] = fZaxis.GetBinCenter(binz);
3113  for (Int_t biny = 1; biny <= nbinsy; ++biny) {
3114  x[1] = fYaxis.GetBinCenter(biny);
3115  for (Int_t binx = 1; binx <= nbinsx; ++binx) {
3116  Int_t bin = GetBin(binx,biny,binz);
3117  x[0] = fXaxis.GetBinCenter(binx);
3118  if (range && !f1->IsInside(x)) continue;
3119  Double_t fu = f1->Eval(x[0], x[1], x[2]);
3120  if (stat) fu = gRandom->PoissonD(fu);
3121  AddBinContent(bin, fu);
3122  if (fSumw2.fN) fSumw2.fArray[bin] += TMath::Abs(fu);
3123  }
3124  }
3125  }
3126 }
3127 
3128 ////////////////////////////////////////////////////////////////////////////////
3129 /// Execute action corresponding to one event.
3130 ///
3131 /// This member function is called when a histogram is clicked with the locator
3132 ///
3133 /// If Left button clicked on the bin top value, then the content of this bin
3134 /// is modified according to the new position of the mouse when it is released.
3135 
3136 void TH1::ExecuteEvent(Int_t event, Int_t px, Int_t py)
3137 {
3138  if (fPainter) fPainter->ExecuteEvent(event, px, py);
3139 }
3140 
3141 ////////////////////////////////////////////////////////////////////////////////
3142 /// This function allows to do discrete Fourier transforms of TH1 and TH2.
3143 /// Available transform types and flags are described below.
3144 ///
3145 /// To extract more information about the transform, use the function
3146 /// TVirtualFFT::GetCurrentTransform() to get a pointer to the current
3147 /// transform object.
3148 ///
3149 /// \param[out] h_output histogram for the output. If a null pointer is passed, a new histogram is created
3150 /// and returned, otherwise, the provided histogram is used and should be big enough
3151 /// \param[in] option option parameters consists of 3 parts:
3152 /// - option on what to return
3153 /// - "RE" - returns a histogram of the real part of the output
3154 /// - "IM" - returns a histogram of the imaginary part of the output
3155 /// - "MAG"- returns a histogram of the magnitude of the output
3156 /// - "PH" - returns a histogram of the phase of the output
3157 /// - option of transform type
3158 /// - "R2C" - real to complex transforms - default
3159 /// - "R2HC" - real to halfcomplex (special format of storing output data,
3160 /// results the same as for R2C)
3161 /// - "DHT" - discrete Hartley transform
3162 /// real to real transforms (sine and cosine):
3163 /// - "R2R_0", "R2R_1", "R2R_2", "R2R_3" - discrete cosine transforms of types I-IV
3164 /// - "R2R_4", "R2R_5", "R2R_6", "R2R_7" - discrete sine transforms of types I-IV
3165 /// To specify the type of each dimension of a 2-dimensional real to real
3166 /// transform, use options of form "R2R_XX", for example, "R2R_02" for a transform,
3167 /// which is of type "R2R_0" in 1st dimension and "R2R_2" in the 2nd.
3168 /// - option of transform flag
3169 /// - "ES" (from "estimate") - no time in preparing the transform, but probably sub-optimal
3170 /// performance
3171 /// - "M" (from "measure") - some time spend in finding the optimal way to do the transform
3172 /// - "P" (from "patient") - more time spend in finding the optimal way to do the transform
3173 /// - "EX" (from "exhaustive") - the most optimal way is found
3174 /// This option should be chosen depending on how many transforms of the same size and
3175 /// type are going to be done. Planning is only done once, for the first transform of this
3176 /// size and type. Default is "ES".
3177 ///
3178 /// Examples of valid options: "Mag R2C M" "Re R2R_11" "Im R2C ES" "PH R2HC EX"
3179 
3180 TH1* TH1::FFT(TH1* h_output, Option_t *option)
3181 {
3183  Int_t ndim[3];
3184  ndim[0] = this->GetNbinsX();
3185  ndim[1] = this->GetNbinsY();
3186  ndim[2] = this->GetNbinsZ();
3187 
3188  TVirtualFFT *fft;
3189  TString opt = option;
3190  opt.ToUpper();
3191  if (!opt.Contains("2R")){
3192  if (!opt.Contains("2C") && !opt.Contains("2HC") && !opt.Contains("DHT")) {
3193  //no type specified, "R2C" by default
3194  opt.Append("R2C");
3195  }
3196  fft = TVirtualFFT::FFT(this->GetDimension(), ndim, opt.Data());
3197  }
3198  else {
3199  //find the kind of transform
3200  Int_t ind = opt.Index("R2R", 3);
3201  Int_t *kind = new Int_t[2];
3202  char t;
3203  t = opt[ind+4];
3204  kind[0] = atoi(&t);
3205  if (h_output->GetDimension()>1) {
3206  t = opt[ind+5];
3207  kind[1] = atoi(&t);
3208  }
3209  fft = TVirtualFFT::SineCosine(this->GetDimension(), ndim, kind, option);
3210  delete [] kind;
3211  }
3212 
3213  if (!fft) return 0;
3214  Int_t in=0;
3215  for (Int_t binx = 1; binx<=ndim[0]; binx++) {
3216  for (Int_t biny=1; biny<=ndim[1]; biny++) {
3217  for (Int_t binz=1; binz<=ndim[2]; binz++) {
3218  fft->SetPoint(in, this->GetBinContent(binx, biny, binz));
3219  in++;
3220  }
3221  }
3222  }
3223  fft->Transform();
3224  h_output = TransformHisto(fft, h_output, option);
3225  return h_output;
3226 }
3227 
3228 ////////////////////////////////////////////////////////////////////////////////
3229 /// Increment bin with abscissa X by 1.
3230 ///
3231 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3232 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3233 ///
3234 /// If the storage of the sum of squares of weights has been triggered,
3235 /// via the function Sumw2, then the sum of the squares of weights is incremented
3236 /// by 1 in the bin corresponding to x.
3237 ///
3238 /// The function returns the corresponding bin number which has its content incremented by 1
3239 
3241 {
3242  if (fBuffer) return BufferFill(x,1);
3243 
3244  Int_t bin;
3245  fEntries++;
3246  bin =fXaxis.FindBin(x);
3247  if (bin <0) return -1;
3248  AddBinContent(bin);
3249  if (fSumw2.fN) ++fSumw2.fArray[bin];
3250  if (bin == 0 || bin > fXaxis.GetNbins()) {
3251  if (!fgStatOverflows) return -1;
3252  }
3253  ++fTsumw;
3254  ++fTsumw2;
3255  fTsumwx += x;
3256  fTsumwx2 += x*x;
3257  return bin;
3258 }
3259 
3260 ////////////////////////////////////////////////////////////////////////////////
3261 /// Increment bin with abscissa X with a weight w.
3262 ///
3263 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3264 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3265 ///
3266 /// If the weight is not equal to 1, the storage of the sum of squares of
3267 /// weights is automatically triggered and the sum of the squares of weights is incremented
3268 /// by \f$ w^2 \f$ in the bin corresponding to x.
3269 ///
3270 /// The function returns the corresponding bin number which has its content incremented by w
3271 
3273 {
3275  if (fBuffer) return BufferFill(x,w);
3276 
3277  Int_t bin;
3278  fEntries++;
3279  bin =fXaxis.FindBin(x);
3280  if (bin <0) return -1;
3281  if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW) ) Sumw2(); // must be called before AddBinContent
3282  if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3283  AddBinContent(bin, w);
3284  if (bin == 0 || bin > fXaxis.GetNbins()) {
3285  if (!fgStatOverflows) return -1;
3286  }
3287  Double_t z= w;
3288  fTsumw += z;
3289  fTsumw2 += z*z;
3290  fTsumwx += z*x;
3291  fTsumwx2 += z*x*x;
3292  return bin;
3293 }
3294 
3295 ////////////////////////////////////////////////////////////////////////////////
3296 /// Increment bin with namex with a weight w
3297 ///
3298 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3299 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3300 ///
3301 /// If the weight is not equal to 1, the storage of the sum of squares of
3302 /// weights is automatically triggered and the sum of the squares of weights is incremented
3303 /// by \f$ w^2 \f$ in the bin corresponding to x.
3304 ///
3305 /// The function returns the corresponding bin number which has its content
3306 /// incremented by w.
3307 
3308 Int_t TH1::Fill(const char *namex, Double_t w)
3309 {
3310  Int_t bin;
3311  fEntries++;
3312  bin =fXaxis.FindBin(namex);
3313  if (bin <0) return -1;
3314  if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3315  if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3316  AddBinContent(bin, w);
3317  if (bin == 0 || bin > fXaxis.GetNbins()) return -1;
3318  Double_t z= w;
3319  fTsumw += z;
3320  fTsumw2 += z*z;
3321  // this make sense if the histogram is not expanding (no axis can be extended)
3322  if (!CanExtendAllAxes()) {
3323  Double_t x = fXaxis.GetBinCenter(bin);
3324  fTsumwx += z*x;
3325  fTsumwx2 += z*x*x;
3326  }
3327  return bin;
3328 }
3329 
3330 ////////////////////////////////////////////////////////////////////////////////
3331 /// Fill this histogram with an array x and weights w.
3332 ///
3333 /// \param[in] ntimes number of entries in arrays x and w (array size must be ntimes*stride)
3334 /// \param[in] x array of values to be histogrammed
3335 /// \param[in] w array of weighs
3336 /// \param[in] stride step size through arrays x and w
3337 ///
3338 /// If the weight is not equal to 1, the storage of the sum of squares of
3339 /// weights is automatically triggered and the sum of the squares of weights is incremented
3340 /// by \f$ w^2 \f$ in the bin corresponding to x.
3341 /// if w is NULL each entry is assumed a weight=1
3342 
3343 void TH1::FillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3344 {
3345  //If a buffer is activated, fill buffer
3346  if (fBuffer) {
3347  ntimes *= stride;
3348  Int_t i = 0;
3349  for (i=0;i<ntimes;i+=stride) {
3350  if (!fBuffer) break; // buffer can be deleted in BufferFill when is empty
3351  if (w) BufferFill(x[i],w[i]);
3352  else BufferFill(x[i], 1.);
3353  }
3354  // fill the remaining entries if the buffer has been deleted
3355  if (i < ntimes && fBuffer==0) {
3356  auto weights = w ? &w[i] : nullptr;
3357  DoFillN((ntimes-i)/stride,&x[i],weights,stride);
3358  }
3359  return;
3360  }
3361  // call internal method
3362  DoFillN(ntimes, x, w, stride);
3363 }
3364 
3365 ////////////////////////////////////////////////////////////////////////////////
3366 /// Internal method to fill histogram content from a vector
3367 /// called directly by TH1::BufferEmpty
3368 
3369 void TH1::DoFillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3370 {
3371  Int_t bin,i;
3372 
3373  fEntries += ntimes;
3374  Double_t ww = 1;
3375  Int_t nbins = fXaxis.GetNbins();
3376  ntimes *= stride;
3377  for (i=0;i<ntimes;i+=stride) {
3378  bin =fXaxis.FindBin(x[i]);
3379  if (bin <0) continue;
3380  if (w) ww = w[i];
3381  if (!fSumw2.fN && ww != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3382  if (fSumw2.fN) fSumw2.fArray[bin] += ww*ww;
3383  AddBinContent(bin, ww);
3384  if (bin == 0 || bin > nbins) {
3385  if (!fgStatOverflows) continue;
3386  }
3387  Double_t z= ww;
3388  fTsumw += z;
3389  fTsumw2 += z*z;
3390  fTsumwx += z*x[i];
3391  fTsumwx2 += z*x[i]*x[i];
3392  }
3393 }
3394 
3395 ////////////////////////////////////////////////////////////////////////////////
3396 /// Fill histogram following distribution in function fname.
3397 ///
3398 /// The distribution contained in the function fname (TF1) is integrated
3399 /// over the channel contents for the bin range of this histogram.
3400 /// It is normalized to 1.
3401 ///
3402 /// Getting one random number implies:
3403 /// - Generating a random number between 0 and 1 (say r1)
3404 /// - Look in which bin in the normalized integral r1 corresponds to
3405 /// - Fill histogram channel
3406 /// ntimes random numbers are generated
3407 ///
3408 /// One can also call TF1::GetRandom to get a random variate from a function.
3409 
3410 void TH1::FillRandom(const char *fname, Int_t ntimes)
3411 {
3412  Int_t bin, binx, ibin, loop;
3413  Double_t r1, x;
3414  // - Search for fname in the list of ROOT defined functions
3415  TF1 *f1 = (TF1*)gROOT->GetFunction(fname);
3416  if (!f1) { Error("FillRandom", "Unknown function: %s",fname); return; }
3417 
3418  // - Allocate temporary space to store the integral and compute integral
3419 
3420  TAxis * xAxis = &fXaxis;
3421 
3422  // in case axis of histogram is not defined use the function axis
3423  if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
3424  Double_t xmin,xmax;
3425  f1->GetRange(xmin,xmax);
3426  Info("FillRandom","Using function axis and range [%g,%g]",xmin, xmax);
3427  xAxis = f1->GetHistogram()->GetXaxis();
3428  }
3429 
3430  Int_t first = xAxis->GetFirst();
3431  Int_t last = xAxis->GetLast();
3432  Int_t nbinsx = last-first+1;
3433 
3434  Double_t *integral = new Double_t[nbinsx+1];
3435  integral[0] = 0;
3436  for (binx=1;binx<=nbinsx;binx++) {
3437  Double_t fint = f1->Integral(xAxis->GetBinLowEdge(binx+first-1),xAxis->GetBinUpEdge(binx+first-1));
3438  integral[binx] = integral[binx-1] + fint;
3439  }
3440 
3441  // - Normalize integral to 1
3442  if (integral[nbinsx] == 0 ) {
3443  delete [] integral;
3444  Error("FillRandom", "Integral = zero"); return;
3445  }
3446  for (bin=1;bin<=nbinsx;bin++) integral[bin] /= integral[nbinsx];
3447 
3448  // --------------Start main loop ntimes
3449  for (loop=0;loop<ntimes;loop++) {
3450  r1 = gRandom->Rndm();
3451  ibin = TMath::BinarySearch(nbinsx,&integral[0],r1);
3452  //binx = 1 + ibin;
3453  //x = xAxis->GetBinCenter(binx); //this is not OK when SetBuffer is used
3454  x = xAxis->GetBinLowEdge(ibin+first)
3455  +xAxis->GetBinWidth(ibin+first)*(r1-integral[ibin])/(integral[ibin+1] - integral[ibin]);
3456  Fill(x);
3457  }
3458  delete [] integral;
3459 }
3460 
3461 ////////////////////////////////////////////////////////////////////////////////
3462 /// Fill histogram following distribution in histogram h.
3463 ///
3464 /// The distribution contained in the histogram h (TH1) is integrated
3465 /// over the channel contents for the bin range of this histogram.
3466 /// It is normalized to 1.
3467 ///
3468 /// Getting one random number implies:
3469 /// - Generating a random number between 0 and 1 (say r1)
3470 /// - Look in which bin in the normalized integral r1 corresponds to
3471 /// - Fill histogram channel ntimes random numbers are generated
3472 ///
3473 /// SPECIAL CASE when the target histogram has the same binning as the source.
3474 /// in this case we simply use a poisson distribution where
3475 /// the mean value per bin = bincontent/integral.
3476 
3477 void TH1::FillRandom(TH1 *h, Int_t ntimes)
3478 {
3479  if (!h) { Error("FillRandom", "Null histogram"); return; }
3480  if (fDimension != h->GetDimension()) {
3481  Error("FillRandom", "Histograms with different dimensions"); return;
3482  }
3483  if (std::isnan(h->ComputeIntegral(true))) {
3484  Error("FillRandom", "Histograms contains negative bins, does not represent probabilities");
3485  return;
3486  }
3487 
3488  //in case the target histogram has the same binning and ntimes much greater
3489  //than the number of bins we can use a fast method
3490  Int_t first = fXaxis.GetFirst();
3491  Int_t last = fXaxis.GetLast();
3492  Int_t nbins = last-first+1;
3493  if (ntimes > 10*nbins) {
3494  try {
3495  CheckConsistency(this,h);
3496  Double_t sumw = h->Integral(first,last);
3497  if (sumw == 0) return;
3498  Double_t sumgen = 0;
3499  for (Int_t bin=first;bin<=last;bin++) {
3500  Double_t mean = h->RetrieveBinContent(bin)*ntimes/sumw;
3501  Double_t cont = (Double_t)gRandom->Poisson(mean);
3502  sumgen += cont;
3503  AddBinContent(bin,cont);
3504  if (fSumw2.fN) fSumw2.fArray[bin] += cont;
3505  }
3506 
3507  // fix for the fluctuations in the total number n
3508  // since we use Poisson instead of multinomial
3509  // add a correction to have ntimes as generated entries
3510  Int_t i;
3511  if (sumgen < ntimes) {
3512  // add missing entries
3513  for (i = Int_t(sumgen+0.5); i < ntimes; ++i)
3514  {
3515  Double_t x = h->GetRandom();
3516  Fill(x);
3517  }
3518  }
3519  else if (sumgen > ntimes) {
3520  // remove extra entries
3521  i = Int_t(sumgen+0.5);
3522  while( i > ntimes) {
3523  Double_t x = h->GetRandom();
3524  Int_t ibin = fXaxis.FindBin(x);
3525  Double_t y = RetrieveBinContent(ibin);
3526  // skip in case bin is empty
3527  if (y > 0) {
3528  SetBinContent(ibin, y-1.);
3529  i--;
3530  }
3531  }
3532  }
3533 
3534  ResetStats();
3535  return;
3536  }
3537  catch(std::exception&) {} // do nothing
3538  }
3539  // case of different axis and not too large ntimes
3540 
3541  if (h->ComputeIntegral() ==0) return;
3542  Int_t loop;
3543  Double_t x;
3544  for (loop=0;loop<ntimes;loop++) {
3545  x = h->GetRandom();
3546  Fill(x);
3547  }
3548 }
3549 
3550 ////////////////////////////////////////////////////////////////////////////////
3551 /// Return Global bin number corresponding to x,y,z
3552 ///
3553 /// 2-D and 3-D histograms are represented with a one dimensional
3554 /// structure. This has the advantage that all existing functions, such as
3555 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3556 /// This function tries to extend the axis if the given point belongs to an
3557 /// under-/overflow bin AND if CanExtendAllAxes() is true.
3558 ///
3559 /// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3560 
3562 {
3563  if (GetDimension() < 2) {
3564  return fXaxis.FindBin(x);
3565  }
3566  if (GetDimension() < 3) {
3567  Int_t nx = fXaxis.GetNbins()+2;
3568  Int_t binx = fXaxis.FindBin(x);
3569  Int_t biny = fYaxis.FindBin(y);
3570  return binx + nx*biny;
3571  }
3572  if (GetDimension() < 4) {
3573  Int_t nx = fXaxis.GetNbins()+2;
3574  Int_t ny = fYaxis.GetNbins()+2;
3575  Int_t binx = fXaxis.FindBin(x);
3576  Int_t biny = fYaxis.FindBin(y);
3577  Int_t binz = fZaxis.FindBin(z);
3578  return binx + nx*(biny +ny*binz);
3579  }
3580  return -1;
3581 }
3582 
3583 ////////////////////////////////////////////////////////////////////////////////
3584 /// Return Global bin number corresponding to x,y,z.
3585 ///
3586 /// 2-D and 3-D histograms are represented with a one dimensional
3587 /// structure. This has the advantage that all existing functions, such as
3588 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3589 /// This function DOES NOT try to extend the axis if the given point belongs
3590 /// to an under-/overflow bin.
3591 ///
3592 /// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3593 
3595 {
3596  if (GetDimension() < 2) {
3597  return fXaxis.FindFixBin(x);
3598  }
3599  if (GetDimension() < 3) {
3600  Int_t nx = fXaxis.GetNbins()+2;
3601  Int_t binx = fXaxis.FindFixBin(x);
3602  Int_t biny = fYaxis.FindFixBin(y);
3603  return binx + nx*biny;
3604  }
3605  if (GetDimension() < 4) {
3606  Int_t nx = fXaxis.GetNbins()+2;
3607  Int_t ny = fYaxis.GetNbins()+2;
3608  Int_t binx = fXaxis.FindFixBin(x);
3609  Int_t biny = fYaxis.FindFixBin(y);
3610  Int_t binz = fZaxis.FindFixBin(z);
3611  return binx + nx*(biny +ny*binz);
3612  }
3613  return -1;
3614 }
3615 
3616 ////////////////////////////////////////////////////////////////////////////////
3617 /// Find first bin with content > threshold for axis (1=x, 2=y, 3=z)
3618 /// if no bins with content > threshold is found the function returns -1.
3619 
3620 Int_t TH1::FindFirstBinAbove(Double_t threshold, Int_t axis) const
3621 {
3622  if (fBuffer) ((TH1*)this)->BufferEmpty();
3623 
3624  if (axis != 1) {
3625  Warning("FindFirstBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3626  axis = 1;
3627  }
3628  Int_t nbins = fXaxis.GetNbins();
3629  for (Int_t bin=1;bin<=nbins;bin++) {
3630  if (RetrieveBinContent(bin) > threshold) return bin;
3631  }
3632  return -1;
3633 }
3634 
3635 ////////////////////////////////////////////////////////////////////////////////
3636 /// Find last bin with content > threshold for axis (1=x, 2=y, 3=z)
3637 /// if no bins with content > threshold is found the function returns -1.
3638 
3639 Int_t TH1::FindLastBinAbove(Double_t threshold, Int_t axis) const
3640 {
3641  if (fBuffer) ((TH1*)this)->BufferEmpty();
3642 
3643  if (axis != 1) {
3644  Warning("FindLastBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3645  axis = 1;
3646  }
3647  Int_t nbins = fXaxis.GetNbins();
3648  for (Int_t bin=nbins;bin>=1;bin--) {
3649  if (RetrieveBinContent(bin) > threshold) return bin;
3650  }
3651  return -1;
3652 }
3653 
3654 ////////////////////////////////////////////////////////////////////////////////
3655 /// Search object named name in the list of functions.
3656 
3657 TObject *TH1::FindObject(const char *name) const
3658 {
3660  return 0;
3661 }
3662 
3663 ////////////////////////////////////////////////////////////////////////////////
3664 /// Search object obj in the list of functions.
3665 
3666 TObject *TH1::FindObject(const TObject *obj) const
3667 {
3668  if (fFunctions) return fFunctions->FindObject(obj);
3669  return 0;
3670 }
3671 
3672 ////////////////////////////////////////////////////////////////////////////////
3673 /// Fit histogram with function fname.
3674 ///
3675 /// fname is the name of an already predefined function created by TF1 or TF2
3676 /// Predefined functions such as gaus, expo and poln are automatically
3677 /// created by ROOT.
3678 /// fname can also be a formula, accepted by the linear fitter (linear parts divided
3679 /// by "++" sign), for example "x++sin(x)" for fitting "[0]*x+[1]*sin(x)"
3680 ///
3681 /// This function finds a pointer to the TF1 object with name fname
3682 /// and calls TH1::Fit(TF1 *f1,...)
3683 
3684 TFitResultPtr TH1::Fit(const char *fname ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
3685 {
3686  char *linear;
3687  linear= (char*)strstr(fname, "++");
3688  TF1 *f1=0;
3689  TF2 *f2=0;
3690  TF3 *f3=0;
3691  Int_t ndim=GetDimension();
3692  if (linear){
3693  if (ndim<2){
3694  f1=new TF1(fname, fname, xxmin, xxmax);
3695  return Fit(f1,option,goption,xxmin,xxmax);
3696  }
3697  else if (ndim<3){
3698  f2=new TF2(fname, fname);
3699  return Fit(f2,option,goption,xxmin,xxmax);
3700  }
3701  else{
3702  f3=new TF3(fname, fname);
3703  return Fit(f3,option,goption,xxmin,xxmax);
3704  }
3705  }
3706 
3707  else{
3708  f1 = (TF1*)gROOT->GetFunction(fname);
3709  if (!f1) { Printf("Unknown function: %s",fname); return -1; }
3710  return Fit(f1,option,goption,xxmin,xxmax);
3711  }
3712 }
3713 
3714 ////////////////////////////////////////////////////////////////////////////////
3715 /// Fit histogram with function f1.
3716 ///
3717 /// \param[in] option fit options is given in parameter option.
3718 /// - "W" Set all weights to 1 for non empty bins; ignore error bars
3719 /// - "WW" Set all weights to 1 including empty bins; ignore error bars
3720 /// - "I" Use integral of function in bin, normalized by the bin volume,
3721 /// instead of value at bin center
3722 /// - "L" Use Loglikelihood method (default is chisquare method)
3723 /// - "WL" Use Loglikelihood method and bin contents are not integer,
3724 /// i.e. histogram is weighted (must have Sumw2() set)
3725 /// - "P" Use Pearson chi2 (using expected errors instead of observed errors)
3726 /// - "U" Use a User specified fitting algorithm (via SetFCN)
3727 /// - "Q" Quiet mode (minimum printing)
3728 /// - "V" Verbose mode (default is between Q and V)
3729 /// - "E" Perform better Errors estimation using Minos technique
3730 /// - "B" User defined parameter settings are used for predefined functions
3731 /// like "gaus", "expo", "poln", "landau".
3732 /// Use this option when you want to fix one or more parameters for these functions.
3733 /// - "M" More. Improve fit results.
3734 /// It uses the IMPROVE command of TMinuit (see TMinuit::mnimpr).
3735 /// This algorithm attempts to improve the found local minimum by searching for a
3736 /// better one.
3737 /// - "R" Use the Range specified in the function range
3738 /// - "N" Do not store the graphics function, do not draw
3739 /// - "0" Do not plot the result of the fit. By default the fitted function
3740 /// is drawn unless the option"N" above is specified.
3741 /// - "+" Add this new fitted function to the list of fitted functions
3742 /// (by default, any previous function is deleted)
3743 /// - "C" In case of linear fitting, don't calculate the chisquare
3744 /// (saves time)
3745 /// - "F" If fitting a polN, switch to minuit fitter
3746 /// - "S" The result of the fit is returned in the TFitResultPtr
3747 /// (see below Access to the Fit Result)
3748 /// \param[in] goption specify a list of graphics options. See TH1::Draw for a complete list of these options.
3749 /// \param[in] xxmin range
3750 /// \param[in] xxmax range
3751 ///
3752 /// In order to use the Range option, one must first create a function
3753 /// with the expression to be fitted. For example, if your histogram
3754 /// has a defined range between -4 and 4 and you want to fit a gaussian
3755 /// only in the interval 1 to 3, you can do:
3756 ///
3757 /// ~~~ {.cpp}
3758 /// TF1 *f1 = new TF1("f1", "gaus", 1, 3);
3759 /// histo->Fit("f1", "R");
3760 /// ~~~
3761 ///
3762 /// ## Setting initial conditions
3763 /// Parameters must be initialized before invoking the Fit function.
3764 /// The setting of the parameter initial values is automatic for the
3765 /// predefined functions : poln, expo, gaus, landau. One can however disable
3766 /// this automatic computation by specifying the option "B".
3767 /// Note that if a predefined function is defined with an argument,
3768 /// eg, gaus(0), expo(1), you must specify the initial values for
3769 /// the parameters.
3770 /// You can specify boundary limits for some or all parameters via
3771 ///
3772 /// ~~~ {.cpp}
3773 /// f1->SetParLimits(p_number, parmin, parmax);
3774 /// ~~~
3775 ///
3776 /// if parmin>=parmax, the parameter is fixed
3777 /// Note that you are not forced to fix the limits for all parameters.
3778 /// For example, if you fit a function with 6 parameters, you can do:
3779 ///
3780 /// ~~~ {.cpp}
3781 /// func->SetParameters(0, 3.1, 1.e-6, -8, 0, 100);
3782 /// func->SetParLimits(3, -10, -4);
3783 /// func->FixParameter(4, 0);
3784 /// func->SetParLimits(5, 1, 1);
3785 /// ~~~
3786 ///
3787 /// With this setup, parameters 0->2 can vary freely
3788 /// Parameter 3 has boundaries [-10,-4] with initial value -8
3789 /// Parameter 4 is fixed to 0
3790 /// Parameter 5 is fixed to 100.
3791 /// When the lower limit and upper limit are equal, the parameter is fixed.
3792 /// However to fix a parameter to 0, one must call the FixParameter function.
3793 ///
3794 /// Note that option "I" gives better results but is slower.
3795 ///
3796 /// #### Changing the fitting objective function
3797 ///
3798 /// By default a chi square function is used for fitting. When option "L" (or "LL") is used
3799 /// a Poisson likelihood function (see note below) is used.
3800 /// The functions are defined in the header Fit/Chi2Func.h or Fit/PoissonLikelihoodFCN and they
3801 /// are implemented using the routines FitUtil::EvaluateChi2 or FitUtil::EvaluatePoissonLogL in
3802 /// the file math/mathcore/src/FitUtil.cxx.
3803 /// To specify a User defined fitting function, specify option "U" and
3804 /// call the following functions:
3805 ///
3806 /// ~~~ {.cpp}
3807 /// TVirtualFitter::Fitter(myhist)->SetFCN(MyFittingFunction)
3808 /// ~~~
3809 ///
3810 /// where MyFittingFunction is of type:
3811 ///
3812 /// ~~~ {.cpp}
3813 /// extern void MyFittingFunction(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag);
3814 /// ~~~
3815 ///
3816 /// #### Chi2 Fits
3817 ///
3818 /// By default a chi2 (least-square) fit is performed on the histogram. The so-called modified least-square method
3819 /// is used where the residual for each bin is computed using as error the observed value (the bin error)
3820 ///
3821 /// \f[
3822 /// Chi2 = \sum{ \left(y(i) - \frac{f(x(i) | p )}{e(i)} \right)^2 }
3823 /// \f]
3824 ///
3825 /// 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
3826 /// an un-weighted histogram. Bins with zero errors are excluded from the fit. See also later the note on the treatment of empty bins.
3827 /// When using option "I" the residual is computed not using the function value at the bin center, f (x(i) | p), but the integral
3828 /// of the function in the bin, Integral{ f(x|p)dx } divided by the bin volume
3829 ///
3830 /// #### Likelihood Fits
3831 ///
3832 /// When using option "L" a likelihood fit is used instead of the default chi2 square fit.
3833 /// The likelihood is built assuming a Poisson probability density function for each bin.
3834 /// The negative log-likelihood to be minimized is
3835 ///
3836 /// \f[
3837 /// NLL = \sum{ log Poisson ( y(i) | f(x(i) | p ) ) }
3838 /// \f]
3839 ///
3840 /// The exact likelihood used is the Poisson likelihood described in this paper:
3841 /// S. Baker and R. D. Cousins, “Clarification of the use of chi-square and likelihood functions in fits to histograms,”
3842 /// Nucl. Instrum. Meth. 221 (1984) 437.
3843 ///
3844 /// This method can then be used only when the bin content represents counts (i.e. errors are sqrt(N) ).
3845 /// The likelihood method has the advantage of treating correctly bins with low statistics. In case of high
3846 /// statistics/bin the distribution of the bin content becomes a normal distribution and the likelihood and chi2 fit
3847 /// give the same result.
3848 ///
3849 /// The likelihood method, although a bit slower, it is therefore the recommended method in case of low
3850 /// bin statistics, where the chi2 method may give incorrect results, in particular when there are
3851 /// several empty bins (see also below).
3852 /// In case of a weighted histogram, it is possible to perform a likelihood fit by using the
3853 /// option "WL". Note a weighted histogram is an histogram which has been filled with weights and it
3854 /// contains the sum of the weight square ( TH1::Sumw2() has been called). The bin error for a weighted
3855 /// histogram is the square root of the sum of the weight square.
3856 ///
3857 /// #### Treatment of Empty Bins
3858 ///
3859 /// Empty bins, which have the content equal to zero AND error equal to zero,
3860 /// are excluded by default from the chisquare fit, but they are considered in the likelihood fit.
3861 /// since they affect the likelihood if the function value in these bins is not negligible.
3862 /// When using option "WW" these bins will be considered in the chi2 fit with an error of 1.
3863 /// Note that if the histogram is having bins with zero content and non zero-errors they are considered as
3864 /// any other bins in the fit. Instead bins with zero error and non-zero content are excluded in the chi2 fit.
3865 /// A likelihood fit should also not be performed on such an histogram, since we are assuming a wrong pdf for each bin.
3866 /// In general, one should not fit an histogram with non-empty bins and zero errors, apart if all the bins have zero errors.
3867 /// In this case one could use the option "w", which gives a weight=1 for each bin (unweighted least-square fit).
3868 ///
3869 /// #### Fitting a histogram of dimension N with a function of dimension N-1
3870 ///
3871 /// It is possible to fit a TH2 with a TF1 or a TH3 with a TF2.
3872 /// In this case the option "Integral" is not allowed and each cell has
3873 /// equal weight.
3874 ///
3875 /// #### Associated functions
3876 ///
3877 /// One or more object (typically a TF1*) can be added to the list
3878 /// of functions (fFunctions) associated to each histogram.
3879 /// When TH1::Fit is invoked, the fitted function is added to this list.
3880 /// Given an histogram h, one can retrieve an associated function
3881 /// with:
3882 ///
3883 /// ~~~ {.cpp}
3884 /// TF1 *myfunc = h->GetFunction("myfunc");
3885 /// ~~~
3886 ///
3887 /// #### Access to the fit result
3888 ///
3889 /// The function returns a TFitResultPtr which can hold a pointer to a TFitResult object.
3890 /// By default the TFitResultPtr contains only the status of the fit which is return by an
3891 /// automatic conversion of the TFitResultPtr to an integer. One can write in this case directly:
3892 ///
3893 /// ~~~ {.cpp}
3894 /// Int_t fitStatus = h->Fit(myFunc)
3895 /// ~~~
3896 ///
3897 /// If the option "S" is instead used, TFitResultPtr contains the TFitResult and behaves as a smart
3898 /// pointer to it. For example one can do:
3899 ///
3900 /// ~~~ {.cpp}
3901 /// TFitResultPtr r = h->Fit(myFunc,"S");
3902 /// TMatrixDSym cov = r->GetCovarianceMatrix(); // to access the covariance matrix
3903 /// Double_t chi2 = r->Chi2(); // to retrieve the fit chi2
3904 /// Double_t par0 = r->Parameter(0); // retrieve the value for the parameter 0
3905 /// Double_t err0 = r->ParError(0); // retrieve the error for the parameter 0
3906 /// r->Print("V"); // print full information of fit including covariance matrix
3907 /// r->Write(); // store the result in a file
3908 /// ~~~
3909 ///
3910 /// The fit parameters, error and chi2 (but not covariance matrix) can be retrieved also
3911 /// from the fitted function.
3912 /// If the histogram is made persistent, the list of
3913 /// associated functions is also persistent. Given a pointer (see above)
3914 /// to an associated function myfunc, one can retrieve the function/fit
3915 /// parameters with calls such as:
3916 ///
3917 /// ~~~ {.cpp}
3918 /// Double_t chi2 = myfunc->GetChisquare();
3919 /// Double_t par0 = myfunc->GetParameter(0); //value of 1st parameter
3920 /// Double_t err0 = myfunc->GetParError(0); //error on first parameter
3921 /// ~~~
3922 ///
3923 /// #### Access to the fit status
3924 ///
3925 /// The status of the fit can be obtained converting the TFitResultPtr to an integer
3926 /// independently if the fit option "S" is used or not:
3927 ///
3928 /// ~~~ {.cpp}
3929 /// TFitResultPtr r = h->Fit(myFunc,opt);
3930 /// Int_t fitStatus = r;
3931 /// ~~~
3932 ///
3933 /// The fitStatus is 0 if the fit is OK (i.e no error occurred).
3934 /// The value of the fit status code is negative in case of an error not connected with the
3935 /// minimization procedure, for example when a wrong function is used.
3936 /// Otherwise the return value is the one returned from the minimization procedure.
3937 /// When TMinuit (default case) or Minuit2 are used as minimizer the status returned is :
3938 /// `fitStatus = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult`.
3939 /// TMinuit will return 0 (for migrad, minos, hesse or improve) in case of success and 4 in
3940 /// case of error (see the documentation of TMinuit::mnexcm). So for example, for an error
3941 /// only in Minos but not in Migrad a fitStatus of 40 will be returned.
3942 /// Minuit2 will return also 0 in case of success and different values in migrad minos or
3943 /// hesse depending on the error. See in this case the documentation of
3944 /// Minuit2Minimizer::Minimize for the migradResult, Minuit2Minimizer::GetMinosError for the
3945 /// minosResult and Minuit2Minimizer::Hesse for the hesseResult.
3946 /// If other minimizers are used see their specific documentation for the status code returned.
3947 /// For example in the case of Fumili, for the status returned see TFumili::Minimize.
3948 ///
3949 /// #### Excluding points
3950 ///
3951 /// Use TF1::RejectPoint inside your fitting function to exclude points
3952 /// within a certain range from the fit. Example:
3953 ///
3954 /// ~~~ {.cpp}
3955 /// Double_t fline(Double_t *x, Double_t *par)
3956 /// {
3957 /// if (x[0] > 2.5 && x[0] < 3.5) {
3958 /// TF1::RejectPoint();
3959 /// return 0;
3960 /// }
3961 /// return par[0] + par[1]*x[0];
3962 /// }
3963 ///
3964 /// void exclude() {
3965 /// TF1 *f1 = new TF1("f1", "[0] +[1]*x +gaus(2)", 0, 5);
3966 /// f1->SetParameters(6, -1,5, 3, 0.2);
3967 /// TH1F *h = new TH1F("h", "background + signal", 100, 0, 5);
3968 /// h->FillRandom("f1", 2000);
3969 /// TF1 *fline = new TF1("fline", fline, 0, 5, 2);
3970 /// fline->SetParameters(2, -1);
3971 /// h->Fit("fline", "l");
3972 /// }
3973 /// ~~~
3974 ///
3975 /// #### Warning when using the option "0"
3976 ///
3977 /// When selecting the option "0", the fitted function is added to
3978 /// the list of functions of the histogram, but it is not drawn.
3979 /// You can undo what you disabled in the following way:
3980 ///
3981 /// ~~~ {.cpp}
3982 /// h.Fit("myFunction", "0"); // fit, store function but do not draw
3983 /// h.Draw(); function is not drawn
3984 /// const Int_t kNotDraw = 1<<9;
3985 /// h.GetFunction("myFunction")->ResetBit(kNotDraw);
3986 /// h.Draw(); // function is visible again
3987 /// ~~~
3988 ///
3989 /// #### Access to the Minimizer information during fitting
3990 ///
3991 /// This function calls, the ROOT::Fit::FitObject function implemented in HFitImpl.cxx
3992 /// which uses the ROOT::Fit::Fitter class. The Fitter class creates the objective function
3993 /// (e.g. chi2 or likelihood) and uses an implementation of the Minimizer interface for minimizing
3994 /// the function.
3995 /// The default minimizer is Minuit (class TMinuitMinimizer which calls TMinuit).
3996 /// The default can be set in the resource file in etc/system.rootrc. For example
3997 ///
3998 /// ~~~ {.cpp}
3999 /// Root.Fitter: Minuit2
4000 /// ~~~
4001 ///
4002 /// A different fitter can also be set via ROOT::Math::MinimizerOptions::SetDefaultMinimizer
4003 /// (or TVirtualFitter::SetDefaultFitter).
4004 /// For example ROOT::Math::MinimizerOptions::SetDefaultMinimizer("GSLMultiMin","BFGS");
4005 /// will set the usage of the BFGS algorithm of the GSL multi-dimensional minimization
4006 /// (implemented in libMathMore). ROOT::Math::MinimizerOptions can be used also to set other
4007 /// default options, like maximum number of function calls, minimization tolerance or print
4008 /// level. See the documentation of this class.
4009 ///
4010 /// For fitting linear functions (containing the "++" sign" and polN functions,
4011 /// the linear fitter is automatically initialized.
4012 
4013 TFitResultPtr TH1::Fit(TF1 *f1 ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
4014 {
4015  // implementation of Fit method is in file hist/src/HFitImpl.cxx
4016  Foption_t fitOption;
4018 
4019  // create range and minimizer options with default values
4020  ROOT::Fit::DataRange range(xxmin,xxmax);
4021  ROOT::Math::MinimizerOptions minOption;
4022 
4023  // need to empty the buffer before
4024  // (t.b.d. do a ML unbinned fit with buffer data)
4025  if (fBuffer) BufferEmpty();
4026 
4027  return ROOT::Fit::FitObject(this, f1 , fitOption , minOption, goption, range);
4028 }
4029 
4030 ////////////////////////////////////////////////////////////////////////////////
4031 /// Display a panel with all histogram fit options.
4032 ///
4033 /// See class TFitPanel for example
4034 
4035 void TH1::FitPanel()
4036 {
4037  if (!gPad)
4038  gROOT->MakeDefCanvas();
4039 
4040  if (!gPad) {
4041  Error("FitPanel", "Unable to create a default canvas");
4042  return;
4043  }
4044 
4045 
4046  // use plugin manager to create instance of TFitEditor
4047  TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TFitEditor");
4048  if (handler && handler->LoadPlugin() != -1) {
4049  if (handler->ExecPlugin(2, gPad, this) == 0)
4050  Error("FitPanel", "Unable to create the FitPanel");
4051  }
4052  else
4053  Error("FitPanel", "Unable to find the FitPanel plug-in");
4054 }
4055 
4056 ////////////////////////////////////////////////////////////////////////////////
4057 /// Return an histogram containing the asymmetry of this histogram with h2,
4058 /// where the asymmetry is defined as:
4059 ///
4060 /// ~~~ {.cpp}
4061 /// Asymmetry = (h1 - h2)/(h1 + h2) where h1 = this
4062 /// ~~~
4063 ///
4064 /// works for 1D, 2D, etc. histograms
4065 /// c2 is an optional argument that gives a relative weight between the two
4066 /// histograms, and dc2 is the error on this weight. This is useful, for example,
4067 /// when forming an asymmetry between two histograms from 2 different data sets that
4068 /// need to be normalized to each other in some way. The function calculates
4069 /// the errors assuming Poisson statistics on h1 and h2 (that is, dh = sqrt(h)).
4070 ///
4071 /// example: assuming 'h1' and 'h2' are already filled
4072 ///
4073 /// ~~~ {.cpp}
4074 /// h3 = h1->GetAsymmetry(h2)
4075 /// ~~~
4076 ///
4077 /// then 'h3' is created and filled with the asymmetry between 'h1' and 'h2';
4078 /// h1 and h2 are left intact.
4079 ///
4080 /// Note that it is the user's responsibility to manage the created histogram.
4081 /// The name of the returned histogram will be `Asymmetry_nameOfh1-nameOfh2`
4082 ///
4083 /// code proposed by Jason Seely (seely@mit.edu) and adapted by R.Brun
4084 ///
4085 /// clone the histograms so top and bottom will have the
4086 /// correct dimensions:
4087 /// Sumw2 just makes sure the errors will be computed properly
4088 /// when we form sums and ratios below.
4089 
4091 {
4092  TH1 *h1 = this;
4093  TString name = TString::Format("Asymmetry_%s-%s",h1->GetName(),h2->GetName() );
4094  TH1 *asym = (TH1*)Clone(name);
4095 
4096  // set also the title
4097  TString title = TString::Format("(%s - %s)/(%s+%s)",h1->GetName(),h2->GetName(),h1->GetName(),h2->GetName() );
4098  asym->SetTitle(title);
4099 
4100  asym->Sumw2();
4101  Bool_t addStatus = TH1::AddDirectoryStatus();
4103  TH1 *top = (TH1*)asym->Clone();
4104  TH1 *bottom = (TH1*)asym->Clone();
4105  TH1::AddDirectory(addStatus);
4106 
4107  // form the top and bottom of the asymmetry, and then divide:
4108  top->Add(h1,h2,1,-c2);
4109  bottom->Add(h1,h2,1,c2);
4110  asym->Divide(top,bottom);
4111 
4112  Int_t xmax = asym->GetNbinsX();
4113  Int_t ymax = asym->GetNbinsY();
4114  Int_t zmax = asym->GetNbinsZ();
4115 
4116  if (h1->fBuffer) h1->BufferEmpty(1);
4117  if (h2->fBuffer) h2->BufferEmpty(1);
4118  if (bottom->fBuffer) bottom->BufferEmpty(1);
4119 
4120  // now loop over bins to calculate the correct errors
4121  // the reason this error calculation looks complex is because of c2
4122  for(Int_t i=1; i<= xmax; i++){
4123  for(Int_t j=1; j<= ymax; j++){
4124  for(Int_t k=1; k<= zmax; k++){
4125  Int_t bin = GetBin(i, j, k);
4126  // here some bin contents are written into variables to make the error
4127  // calculation a little more legible:
4128  Double_t a = h1->RetrieveBinContent(bin);
4129  Double_t b = h2->RetrieveBinContent(bin);
4130  Double_t bot = bottom->RetrieveBinContent(bin);
4131 
4132  // make sure there are some events, if not, then the errors are set = 0
4133  // automatically.
4134  //if(bot < 1){} was changed to the next line from recommendation of Jason Seely (28 Nov 2005)
4135  if(bot < 1e-6){}
4136  else{
4137  // computation of errors by Christos Leonidopoulos
4138  Double_t dasq = h1->GetBinErrorSqUnchecked(bin);
4139  Double_t dbsq = h2->GetBinErrorSqUnchecked(bin);
4140  Double_t error = 2*TMath::Sqrt(a*a*c2*c2*dbsq + c2*c2*b*b*dasq+a*a*b*b*dc2*dc2)/(bot*bot);
4141  asym->SetBinError(i,j,k,error);
4142  }
4143  }
4144  }
4145  }
4146  delete top;
4147  delete bottom;
4148 
4149  return asym;
4150 }
4151 
4152 ////////////////////////////////////////////////////////////////////////////////
4153 /// Static function
4154 /// return the default buffer size for automatic histograms
4155 /// the parameter fgBufferSize may be changed via SetDefaultBufferSize
4156 
4158 {
4160 }
4161 
4162 ////////////////////////////////////////////////////////////////////////////////
4163 /// Return kTRUE if TH1::Sumw2 must be called when creating new histograms.
4164 /// see TH1::SetDefaultSumw2.
4165 
4167 {
4169 }
4170 
4171 ////////////////////////////////////////////////////////////////////////////////
4172 /// Return the current number of entries.
4173 
4174 Double_t TH1::GetEntries() const
4175 {
4176  if (fBuffer) {
4177  Int_t nentries = (Int_t) fBuffer[0];
4178  if (nentries > 0) return nentries;
4179  }
4180 
4181  return fEntries;
4182 }
4183 
4184 ////////////////////////////////////////////////////////////////////////////////
4185 /// Number of effective entries of the histogram.
4186 ///
4187 /// \f[
4188 /// neff = \frac{(\sum Weights )^2}{(\sum Weight^2 )}
4189 /// \f]
4190 ///
4191 /// In case of an unweighted histogram this number is equivalent to the
4192 /// number of entries of the histogram.
4193 /// For a weighted histogram, this number corresponds to the hypothetical number of unweighted entries
4194 /// a histogram would need to have the same statistical power as this weighted histogram.
4195 /// Note: The underflow/overflow are included if one has set the TH1::StatOverFlows flag
4196 /// and if the statistics has been computed at filling time.
4197 /// If a range is set in the histogram the number is computed from the given range.
4198 
4200 {
4202  this->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
4203  return (s[1] ? s[0]*s[0]/s[1] : TMath::Abs(s[0]) );
4204 }
4205 
4206 ////////////////////////////////////////////////////////////////////////////////
4207 /// Redefines TObject::GetObjectInfo.
4208 /// Displays the histogram info (bin number, contents, integral up to bin
4209 /// corresponding to cursor position px,py
4210 
4211 char *TH1::GetObjectInfo(Int_t px, Int_t py) const
4212 {
4213  return ((TH1*)this)->GetPainter()->GetObjectInfo(px,py);
4214 }
4215 
4216 ////////////////////////////////////////////////////////////////////////////////
4217 /// Return pointer to painter.
4218 /// If painter does not exist, it is created
4219 
4221 {
4222  if (!fPainter) {
4223  TString opt = option;
4224  opt.ToLower();
4225  if (opt.Contains("gl") || gStyle->GetCanvasPreferGL()) {
4226  //try to create TGLHistPainter
4227  TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TGLHistPainter");
4228 
4229  if (handler && handler->LoadPlugin() != -1)
4230  fPainter = reinterpret_cast<TVirtualHistPainter *>(handler->ExecPlugin(1, this));
4231  }
4232  }
4233 
4235 
4236  return fPainter;
4237 }
4238 
4239 ////////////////////////////////////////////////////////////////////////////////
4240 /// Compute Quantiles for this histogram
4241 /// Quantile x_q of a probability distribution Function F is defined as
4242 ///
4243 /// ~~~ {.cpp}
4244 /// F(x_q) = q with 0 <= q <= 1.
4245 /// ~~~
4246 ///
4247 /// For instance the median x_0.5 of a distribution is defined as that value
4248 /// of the random variable for which the distribution function equals 0.5:
4249 ///
4250 /// ~~~ {.cpp}
4251 /// F(x_0.5) = Probability(x < x_0.5) = 0.5
4252 /// ~~~
4253 ///
4254 /// code from Eddy Offermann, Renaissance
4255 ///
4256 /// \param[in] nprobSum maximum size of array q and size of array probSum (if given)
4257 /// \param[in] probSum array of positions where quantiles will be computed.
4258 /// - if probSum is null, probSum will be computed internally and will
4259 /// have a size = number of bins + 1 in h. it will correspond to the
4260 /// quantiles calculated at the lowest edge of the histogram (quantile=0) and
4261 /// all the upper edges of the bins.
4262 /// - if probSum is not null, it is assumed to contain at least nprobSum values.
4263 /// \param[out] q array q filled with nq quantiles
4264 /// \return value nq (<=nprobSum) with the number of quantiles computed
4265 ///
4266 /// Note that the Integral of the histogram is automatically recomputed
4267 /// if the number of entries is different of the number of entries when
4268 /// the integral was computed last time. In case you do not use the Fill
4269 /// functions to fill your histogram, but SetBinContent, you must call
4270 /// TH1::ComputeIntegral before calling this function.
4271 ///
4272 /// Getting quantiles q from two histograms and storing results in a TGraph,
4273 /// a so-called QQ-plot
4274 ///
4275 /// ~~~ {.cpp}
4276 /// TGraph *gr = new TGraph(nprob);
4277 /// h1->GetQuantiles(nprob,gr->GetX());
4278 /// h2->GetQuantiles(nprob,gr->GetY());
4279 /// gr->Draw("alp");
4280 /// ~~~
4281 ///
4282 /// Example:
4283 ///
4284 /// ~~~ {.cpp}
4285 /// void quantiles() {
4286 /// // demo for quantiles
4287 /// const Int_t nq = 20;
4288 /// TH1F *h = new TH1F("h","demo quantiles",100,-3,3);
4289 /// h->FillRandom("gaus",5000);
4290 ///
4291 /// Double_t xq[nq]; // position where to compute the quantiles in [0,1]
4292 /// Double_t yq[nq]; // array to contain the quantiles
4293 /// for (Int_t i=0;i<nq;i++) xq[i] = Float_t(i+1)/nq;
4294 /// h->GetQuantiles(nq,yq,xq);
4295 ///
4296 /// //show the original histogram in the top pad
4297 /// TCanvas *c1 = new TCanvas("c1","demo quantiles",10,10,700,900);
4298 /// c1->Divide(1,2);
4299 /// c1->cd(1);
4300 /// h->Draw();
4301 ///
4302 /// // show the quantiles in the bottom pad
4303 /// c1->cd(2);
4304 /// gPad->SetGrid();
4305 /// TGraph *gr = new TGraph(nq,xq,yq);
4306 /// gr->SetMarkerStyle(21);
4307 /// gr->Draw("alp");
4308 /// }
4309 /// ~~~
4310 
4311 Int_t TH1::GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum)
4312 {
4313  if (GetDimension() > 1) {
4314  Error("GetQuantiles","Only available for 1-d histograms");
4315  return 0;
4316  }
4317 
4318  const Int_t nbins = GetXaxis()->GetNbins();
4319  if (!fIntegral) ComputeIntegral();
4320  if (fIntegral[nbins+1] != fEntries) ComputeIntegral();
4321 
4322  Int_t i, ibin;
4323  Double_t *prob = (Double_t*)probSum;
4324  Int_t nq = nprobSum;
4325  if (probSum == 0) {
4326  nq = nbins+1;
4327  prob = new Double_t[nq];
4328  prob[0] = 0;
4329  for (i=1;i<nq;i++) {
4330  prob[i] = fIntegral[i]/fIntegral[nbins];
4331  }
4332  }
4333 
4334  for (i = 0; i < nq; i++) {
4335  ibin = TMath::BinarySearch(nbins,fIntegral,prob[i]);
4336  while (ibin < nbins-1 && fIntegral[ibin+1] == prob[i]) {
4337  if (fIntegral[ibin+2] == prob[i]) ibin++;
4338  else break;
4339  }
4340  q[i] = GetBinLowEdge(ibin+1);
4341  const Double_t dint = fIntegral[ibin+1]-fIntegral[ibin];
4342  if (dint > 0) q[i] += GetBinWidth(ibin+1)*(prob[i]-fIntegral[ibin])/dint;
4343  }
4344 
4345  if (!probSum) delete [] prob;
4346  return nq;
4347 }
4348 
4349 ////////////////////////////////////////////////////////////////////////////////
4350 /// Decode string choptin and fill fitOption structure.
4351 
4352 Int_t TH1::FitOptionsMake(Option_t *choptin, Foption_t &fitOption)
4353 {
4355  return 1;
4356 }
4357 
4358 ////////////////////////////////////////////////////////////////////////////////
4359 /// Compute Initial values of parameters for a gaussian.
4360 
4361 void H1InitGaus()
4362 {
4363  Double_t allcha, sumx, sumx2, x, val, stddev, mean;
4364  Int_t bin;
4365  const Double_t sqrtpi = 2.506628;
4366 
4367  // - Compute mean value and StdDev of the histogram in the given range
4369  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4370  Int_t hxfirst = hFitter->GetXfirst();
4371  Int_t hxlast = hFitter->GetXlast();
4372  Double_t valmax = curHist->GetBinContent(hxfirst);
4373  Double_t binwidx = curHist->GetBinWidth(hxfirst);
4374  allcha = sumx = sumx2 = 0;
4375  for (bin=hxfirst;bin<=hxlast;bin++) {
4376  x = curHist->GetBinCenter(bin);
4377  val = TMath::Abs(curHist->GetBinContent(bin));
4378  if (val > valmax) valmax = val;
4379  sumx += val*x;
4380  sumx2 += val*x*x;
4381  allcha += val;
4382  }
4383  if (allcha == 0) return;
4384  mean = sumx/allcha;
4385  stddev = sumx2/allcha - mean*mean;
4386  if (stddev > 0) stddev = TMath::Sqrt(stddev);
4387  else stddev = 0;
4388  if (stddev == 0) stddev = binwidx*(hxlast-hxfirst+1)/4;
4389  //if the distribution is really gaussian, the best approximation
4390  //is binwidx*allcha/(sqrtpi*stddev)
4391  //However, in case of non-gaussian tails, this underestimates
4392  //the normalisation constant. In this case the maximum value
4393  //is a better approximation.
4394  //We take the average of both quantities
4395  Double_t constant = 0.5*(valmax+binwidx*allcha/(sqrtpi*stddev));
4396 
4397  //In case the mean value is outside the histo limits and
4398  //the StdDev is bigger than the range, we take
4399  // mean = center of bins
4400  // stddev = half range
4401  Double_t xmin = curHist->GetXaxis()->GetXmin();
4402  Double_t xmax = curHist->GetXaxis()->GetXmax();
4403  if ((mean < xmin || mean > xmax) && stddev > (xmax-xmin)) {
4404  mean = 0.5*(xmax+xmin);
4405  stddev = 0.5*(xmax-xmin);
4406  }
4407  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4408  f1->SetParameter(0,constant);
4409  f1->SetParameter(1,mean);
4410  f1->SetParameter(2,stddev);
4411  f1->SetParLimits(2,0,10*stddev);
4412 }
4413 
4414 ////////////////////////////////////////////////////////////////////////////////
4415 /// Compute Initial values of parameters for an exponential.
4416 
4417 void H1InitExpo()
4418 {
4419  Double_t constant, slope;
4420  Int_t ifail;
4422  Int_t hxfirst = hFitter->GetXfirst();
4423  Int_t hxlast = hFitter->GetXlast();
4424  Int_t nchanx = hxlast - hxfirst + 1;
4425 
4426  H1LeastSquareLinearFit(-nchanx, constant, slope, ifail);
4427 
4428  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4429  f1->SetParameter(0,constant);
4430  f1->SetParameter(1,slope);
4431 
4432 }
4433 
4434 ////////////////////////////////////////////////////////////////////////////////
4435 /// Compute Initial values of parameters for a polynom.
4436 
4437 void H1InitPolynom()
4438 {
4439  Double_t fitpar[25];
4440 
4442  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4443  Int_t hxfirst = hFitter->GetXfirst();
4444  Int_t hxlast = hFitter->GetXlast();
4445  Int_t nchanx = hxlast - hxfirst + 1;
4446  Int_t npar = f1->GetNpar();
4447 
4448  if (nchanx <=1 || npar == 1) {
4449  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4450  fitpar[0] = curHist->GetSumOfWeights()/Double_t(nchanx);
4451  } else {
4452  H1LeastSquareFit( nchanx, npar, fitpar);
4453  }
4454  for (Int_t i=0;i<npar;i++) f1->SetParameter(i, fitpar[i]);
4455 }
4456 
4457 ////////////////////////////////////////////////////////////////////////////////
4458 /// Least squares lpolynomial fitting without weights.
4459 ///
4460 /// \param[in] n number of points to fit
4461 /// \param[in] m number of parameters
4462 /// \param[in] a array of parameters
4463 ///
4464 /// based on CERNLIB routine LSQ: Translated to C++ by Rene Brun
4465 /// (E.Keil. revised by B.Schorr, 23.10.1981.)
4466 
4468 {
4469  const Double_t zero = 0.;
4470  const Double_t one = 1.;
4471  const Int_t idim = 20;
4472 
4473  Double_t b[400] /* was [20][20] */;
4474  Int_t i, k, l, ifail;
4475  Double_t power;
4476  Double_t da[20], xk, yk;
4477 
4478  if (m <= 2) {
4479  H1LeastSquareLinearFit(n, a[0], a[1], ifail);
4480  return;
4481  }
4482  if (m > idim || m > n) return;
4483  b[0] = Double_t(n);
4484  da[0] = zero;
4485  for (l = 2; l <= m; ++l) {
4486  b[l-1] = zero;
4487  b[m + l*20 - 21] = zero;
4488  da[l-1] = zero;
4489  }
4491  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4492  Int_t hxfirst = hFitter->GetXfirst();
4493  Int_t hxlast = hFitter->GetXlast();
4494  for (k = hxfirst; k <= hxlast; ++k) {
4495  xk = curHist->GetBinCenter(k);
4496  yk = curHist->GetBinContent(k);
4497  power = one;
4498  da[0] += yk;
4499  for (l = 2; l <= m; ++l) {
4500  power *= xk;
4501  b[l-1] += power;
4502  da[l-1] += power*yk;
4503  }
4504  for (l = 2; l <= m; ++l) {
4505  power *= xk;
4506  b[m + l*20 - 21] += power;
4507  }
4508  }
4509  for (i = 3; i <= m; ++i) {
4510  for (k = i; k <= m; ++k) {
4511  b[k - 1 + (i-1)*20 - 21] = b[k + (i-2)*20 - 21];
4512  }
4513  }
4514  H1LeastSquareSeqnd(m, b, idim, ifail, 1, da);
4515 
4516  for (i=0; i<m; ++i) a[i] = da[i];
4517 
4518 }
4519 
4520 ////////////////////////////////////////////////////////////////////////////////
4521 /// Least square linear fit without weights.
4522 ///
4523 /// extracted from CERNLIB LLSQ: Translated to C++ by Rene Brun
4524 /// (added to LSQ by B. Schorr, 15.02.1982.)
4525 
4526 void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
4527 {
4528  Double_t xbar, ybar, x2bar;
4529  Int_t i, n;
4530  Double_t xybar;
4531  Double_t fn, xk, yk;
4532  Double_t det;
4533 
4534  n = TMath::Abs(ndata);
4535  ifail = -2;
4536  xbar = ybar = x2bar = xybar = 0;
4538  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4539  Int_t hxfirst = hFitter->GetXfirst();
4540  Int_t hxlast = hFitter->GetXlast();
4541  for (i = hxfirst; i <= hxlast; ++i) {
4542  xk = curHist->GetBinCenter(i);
4543  yk = curHist->GetBinContent(i);
4544  if (ndata < 0) {
4545  if (yk <= 0) yk = 1e-9;
4546  yk = TMath::Log(yk);
4547  }
4548  xbar += xk;
4549  ybar += yk;
4550  x2bar += xk*xk;
4551  xybar += xk*yk;
4552  }
4553  fn = Double_t(n);
4554  det = fn*x2bar - xbar*xbar;
4555  ifail = -1;
4556  if (det <= 0) {
4557  a0 = ybar/fn;
4558  a1 = 0;
4559  return;
4560  }
4561  ifail = 0;
4562  a0 = (x2bar*ybar - xbar*xybar) / det;
4563  a1 = (fn*xybar - xbar*ybar) / det;
4564 
4565 }
4566 
4567 ////////////////////////////////////////////////////////////////////////////////
4568 /// Extracted from CERN Program library routine DSEQN.
4569 ///
4570 /// Translated to C++ by Rene Brun
4571 
4572 void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b)
4573 {
4574  Int_t a_dim1, a_offset, b_dim1, b_offset;
4575  Int_t nmjp1, i, j, l;
4576  Int_t im1, jp1, nm1, nmi;
4577  Double_t s1, s21, s22;
4578  const Double_t one = 1.;
4579 
4580  /* Parameter adjustments */
4581  b_dim1 = idim;
4582  b_offset = b_dim1 + 1;
4583  b -= b_offset;
4584  a_dim1 = idim;
4585  a_offset = a_dim1 + 1;
4586  a -= a_offset;
4587 
4588  if (idim < n) return;
4589 
4590  ifail = 0;
4591  for (j = 1; j <= n; ++j) {
4592  if (a[j + j*a_dim1] <= 0) { ifail = -1; return; }
4593  a[j + j*a_dim1] = one / a[j + j*a_dim1];
4594  if (j == n) continue;
4595  jp1 = j + 1;
4596  for (l = jp1; l <= n; ++l) {
4597  a[j + l*a_dim1] = a[j + j*a_dim1] * a[l + j*a_dim1];
4598  s1 = -a[l + (j+1)*a_dim1];
4599  for (i = 1; i <= j; ++i) { s1 = a[l + i*a_dim1] * a[i + (j+1)*a_dim1] + s1; }
4600  a[l + (j+1)*a_dim1] = -s1;
4601  }
4602  }
4603  if (k <= 0) return;
4604 
4605  for (l = 1; l <= k; ++l) {
4606  b[l*b_dim1 + 1] = a[a_dim1 + 1]*b[l*b_dim1 + 1];
4607  }
4608  if (n == 1) return;
4609  for (l = 1; l <= k; ++l) {
4610  for (i = 2; i <= n; ++i) {
4611  im1 = i - 1;
4612  s21 = -b[i + l*b_dim1];
4613  for (j = 1; j <= im1; ++j) {
4614  s21 = a[i + j*a_dim1]*b[j + l*b_dim1] + s21;
4615  }
4616  b[i + l*b_dim1] = -a[i + i*a_dim1]*s21;
4617  }
4618  nm1 = n - 1;
4619  for (i = 1; i <= nm1; ++i) {
4620  nmi = n - i;
4621  s22 = -b[nmi + l*b_dim1];
4622  for (j = 1; j <= i; ++j) {
4623  nmjp1 = n - j + 1;
4624  s22 = a[nmi + nmjp1*a_dim1]*b[nmjp1 + l*b_dim1] + s22;
4625  }
4626  b[nmi + l*b_dim1] = -s22;
4627  }
4628  }
4629 }
4630 
4631 ////////////////////////////////////////////////////////////////////////////////
4632 /// Return Global bin number corresponding to binx,y,z.
4633 ///
4634 /// 2-D and 3-D histograms are represented with a one dimensional
4635 /// structure.
4636 /// This has the advantage that all existing functions, such as
4637 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
4638 ///
4639 /// In case of a TH1x, returns binx directly.
4640 /// see TH1::GetBinXYZ for the inverse transformation.
4641 ///
4642 /// Convention for numbering bins
4643 ///
4644 /// For all histogram types: nbins, xlow, xup
4645 ///
4646 /// - bin = 0; underflow bin
4647 /// - bin = 1; first bin with low-edge xlow INCLUDED
4648 /// - bin = nbins; last bin with upper-edge xup EXCLUDED
4649 /// - bin = nbins+1; overflow bin
4650 ///
4651 /// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4652 /// For example, assuming a 3-D histogram with binx,biny,binz, the function
4653 ///
4654 /// ~~~ {.cpp}
4655 /// Int_t bin = h->GetBin(binx,biny,binz);
4656 /// ~~~
4657 ///
4658 /// returns a global/linearized bin number. This global bin is useful
4659 /// to access the bin information independently of the dimension.
4660 
4661 Int_t TH1::GetBin(Int_t binx, Int_t, Int_t) const
4662 {
4663  Int_t ofx = fXaxis.GetNbins() + 1; // overflow bin
4664  if (binx < 0) binx = 0;
4665  if (binx > ofx) binx = ofx;
4666 
4667  return binx;
4668 }
4669 
4670 ////////////////////////////////////////////////////////////////////////////////
4671 /// Return binx, biny, binz corresponding to the global bin number globalbin
4672 /// see TH1::GetBin function above
4673 
4674 void TH1::GetBinXYZ(Int_t binglobal, Int_t &binx, Int_t &biny, Int_t &binz) const
4675 {
4677  Int_t ny = fYaxis.GetNbins()+2;
4678 
4679  if (GetDimension() == 1) {
4680  binx = binglobal%nx;
4681  biny = 0;
4682  binz = 0;
4683  return;
4684  }
4685  if (GetDimension() == 2) {
4686  binx = binglobal%nx;
4687  biny = ((binglobal-binx)/nx)%ny;
4688  binz = 0;
4689  return;
4690  }
4691  if (GetDimension() == 3) {
4692  binx = binglobal%nx;
4693  biny = ((binglobal-binx)/nx)%ny;
4694  binz = ((binglobal-binx)/nx -biny)/ny;
4695  }
4696 }
4697 
4698 ////////////////////////////////////////////////////////////////////////////////
4699 /// Return a random number distributed according the histogram bin contents.
4700 /// This function checks if the bins integral exists. If not, the integral
4701 /// is evaluated, normalized to one.
4702 ///
4703 /// The integral is automatically recomputed if the number of entries
4704 /// is not the same then when the integral was computed.
4705 /// NB Only valid for 1-d histograms. Use GetRandom2 or 3 otherwise.
4706 /// If the histogram has a bin with negative content a NaN is returned
4707 
4708 Double_t TH1::GetRandom() const
4709 {
4710  if (fDimension > 1) {
4711  Error("GetRandom","Function only valid for 1-d histograms");
4712  return 0;
4713  }
4714  Int_t nbinsx = GetNbinsX();
4715  Double_t integral = 0;
4716  // compute integral checking that all bins have positive content (see ROOT-5894)
4717  if (fIntegral) {
4718  if (fIntegral[nbinsx+1] != fEntries) integral = ((TH1*)this)->ComputeIntegral(true);
4719  else integral = fIntegral[nbinsx];
4720  } else {
4721  integral = ((TH1*)this)->ComputeIntegral(true);
4722  }
4723  if (integral == 0) return 0;
4724  // return a NaN in case some bins have negative content
4725  if (integral == TMath::QuietNaN() ) return TMath::QuietNaN();
4726 
4727  Double_t r1 = gRandom->Rndm();
4728  Int_t ibin = TMath::BinarySearch(nbinsx,fIntegral,r1);
4729  Double_t x = GetBinLowEdge(ibin+1);
4730  if (r1 > fIntegral[ibin]) x +=
4731  GetBinWidth(ibin+1)*(r1-fIntegral[ibin])/(fIntegral[ibin+1] - fIntegral[ibin]);
4732  return x;
4733 }
4734 
4735 ////////////////////////////////////////////////////////////////////////////////
4736 /// Return content of bin number bin.
4737 ///
4738 /// Implemented in TH1C,S,F,D
4739 ///
4740 /// Convention for numbering bins
4741 ///
4742 /// For all histogram types: nbins, xlow, xup
4743 ///
4744 /// - bin = 0; underflow bin
4745 /// - bin = 1; first bin with low-edge xlow INCLUDED
4746 /// - bin = nbins; last bin with upper-edge xup EXCLUDED
4747 /// - bin = nbins+1; overflow bin
4748 ///
4749 /// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4750 /// For example, assuming a 3-D histogram with binx,biny,binz, the function
4751 ///
4752 /// ~~~ {.cpp}
4753 /// Int_t bin = h->GetBin(binx,biny,binz);
4754 /// ~~~
4755 ///
4756 /// returns a global/linearized bin number. This global bin is useful
4757 /// to access the bin information independently of the dimension.
4758 
4760 {
4761  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
4762  if (bin < 0) bin = 0;
4763  if (bin >= fNcells) bin = fNcells-1;
4764 
4765  return RetrieveBinContent(bin);
4766 }
4767 
4768 ////////////////////////////////////////////////////////////////////////////////
4769 /// Compute first binx in the range [firstx,lastx] for which
4770 /// diff = abs(bin_content-c) <= maxdiff
4771 ///
4772 /// In case several bins in the specified range with diff=0 are found
4773 /// the first bin found is returned in binx.
4774 /// In case several bins in the specified range satisfy diff <=maxdiff
4775 /// the bin with the smallest difference is returned in binx.
4776 /// In all cases the function returns the smallest difference.
4777 ///
4778 /// NOTE1: if firstx <= 0, firstx is set to bin 1
4779 /// if (lastx < firstx then firstx is set to the number of bins
4780 /// ie if firstx=0 and lastx=0 (default) the search is on all bins.
4781 ///
4782 /// NOTE2: if maxdiff=0 (default), the first bin with content=c is returned.
4783 
4784 Double_t TH1::GetBinWithContent(Double_t c, Int_t &binx, Int_t firstx, Int_t lastx,Double_t maxdiff) const
4785 {
4786  if (fDimension > 1) {
4787  binx = 0;
4788  Error("GetBinWithContent","function is only valid for 1-D histograms");
4789  return 0;
4790  }
4791 
4792  if (fBuffer) ((TH1*)this)->BufferEmpty();
4793 
4794  if (firstx <= 0) firstx = 1;
4795  if (lastx < firstx) lastx = fXaxis.GetNbins();
4796  Int_t binminx = 0;
4797  Double_t diff, curmax = 1.e240;
4798  for (Int_t i=firstx;i<=lastx;i++) {
4799  diff = TMath::Abs(RetrieveBinContent(i)-c);
4800  if (diff <= 0) {binx = i; return diff;}
4801  if (diff < curmax && diff <= maxdiff) {curmax = diff, binminx=i;}
4802  }
4803  binx = binminx;
4804  return curmax;
4805 }
4806 
4807 ////////////////////////////////////////////////////////////////////////////////
4808 /// Given a point x, approximates the value via linear interpolation
4809 /// based on the two nearest bin centers
4810 ///
4811 /// Andy Mastbaum 10/21/08
4812 
4814 {
4815  if (fBuffer) ((TH1*)this)->BufferEmpty();
4816 
4817  Int_t xbin = FindBin(x);
4818  Double_t x0,x1,y0,y1;
4819 
4820  if(x<=GetBinCenter(1)) {
4821  return RetrieveBinContent(1);
4822  } else if(x>=GetBinCenter(GetNbinsX())) {
4823  return RetrieveBinContent(GetNbinsX());
4824  } else {
4825  if(x<=GetBinCenter(xbin)) {
4826  y0 = RetrieveBinContent(xbin-1);
4827  x0 = GetBinCenter(xbin-1);
4828  y1 = RetrieveBinContent(xbin);
4829  x1 = GetBinCenter(xbin);
4830  } else {
4831  y0 = RetrieveBinContent(xbin);
4832  x0 = GetBinCenter(xbin);
4833  y1 = RetrieveBinContent(xbin+1);
4834  x1 = GetBinCenter(xbin+1);
4835  }
4836  return y0 + (x-x0)*((y1-y0)/(x1-x0));
4837  }
4838 }
4839 
4840 ////////////////////////////////////////////////////////////////////////////////
4841 /// Interpolate. Not yet implemented.
4842 
4844 {
4845  Error("Interpolate","This function must be called with 1 argument for a TH1");
4846  return 0;
4847 }
4848 
4849 ////////////////////////////////////////////////////////////////////////////////
4850 /// Interpolate. Not yet implemented.
4851 
4853 {
4854  Error("Interpolate","This function must be called with 1 argument for a TH1");
4855  return 0;
4856 }
4857 
4858 ////////////////////////////////////////////////////////////////////////////////
4859 /// Return true if the bin is overflow.
4860 
4861 Bool_t TH1::IsBinOverflow(Int_t bin, Int_t iaxis) const
4862 {
4863  Int_t binx, biny, binz;
4864  GetBinXYZ(bin, binx, biny, binz);
4865 
4866  if (iaxis == 0) {
4867  if ( fDimension == 1 )
4868  return binx >= GetNbinsX() + 1;
4869  if ( fDimension == 2 )
4870  return (binx >= GetNbinsX() + 1) ||
4871  (biny >= GetNbinsY() + 1);
4872  if ( fDimension == 3 )
4873  return (binx >= GetNbinsX() + 1) ||
4874  (biny >= GetNbinsY() + 1) ||
4875  (binz >= GetNbinsZ() + 1);
4876  return kFALSE;
4877  }
4878  if (iaxis == 1)
4879  return binx >= GetNbinsX() + 1;
4880  if (iaxis == 2)
4881  return biny >= GetNbinsY() + 1;
4882  if (iaxis == 3)
4883  return binz >= GetNbinsZ() + 1;
4884 
4885  Error("IsBinOverflow","Invalid axis value");
4886  return kFALSE;
4887 }
4888 
4889 ////////////////////////////////////////////////////////////////////////////////
4890 /// Return true if the bin is underflow.
4891 /// If iaxis = 0 make OR with all axes otherwise check only for the given axis
4892 
4893 Bool_t TH1::IsBinUnderflow(Int_t bin, Int_t iaxis) const
4894 {
4895  Int_t binx, biny, binz;
4896  GetBinXYZ(bin, binx, biny, binz);
4897 
4898  if (iaxis == 0) {
4899  if ( fDimension == 1 )
4900  return (binx <= 0);
4901  else if ( fDimension == 2 )
4902  return (binx <= 0 || biny <= 0);
4903  else if ( fDimension == 3 )
4904  return (binx <= 0 || biny <= 0 || binz <= 0);
4905  else
4906  return kFALSE;
4907  }
4908  if (iaxis == 1)
4909  return (binx <= 0);
4910  if (iaxis == 2)
4911  return (biny <= 0);
4912  if (iaxis == 3)
4913  return (binz <= 0);
4914 
4915  Error("IsBinUnderflow","Invalid axis value");
4916  return kFALSE;
4917 }
4918 
4919 ////////////////////////////////////////////////////////////////////////////////
4920 /// Reduce the number of bins for the axis passed in the option to the number of bins having a label.
4921 /// The method will remove only the extra bins existing after the last "labeled" bin.
4922 /// Note that if there are "un-labeled" bins present between "labeled" bins they will not be removed
4923 
4924 void TH1::LabelsDeflate(Option_t *ax)
4925 {
4926  Int_t iaxis = AxisChoice(ax);
4927  TAxis *axis = 0;
4928  if (iaxis == 1) axis = GetXaxis();
4929  if (iaxis == 2) axis = GetYaxis();
4930  if (iaxis == 3) axis = GetZaxis();
4931  if (!axis) {
4932  Error("LabelsDeflate","Invalid axis option %s",ax);
4933  return;
4934  }
4935  if (!axis->GetLabels()) return;
4936 
4937  // find bin with last labels
4938  // bin number is object ID in list of labels
4939  // therefore max bin number is number of bins of the deflated histograms
4940  TIter next(axis->GetLabels());
4941  TObject *obj;
4942  Int_t nbins = 0;
4943  while ((obj = next())) {
4944  Int_t ibin = obj->GetUniqueID();
4945  if (ibin > nbins) nbins = ibin;
4946  }
4947  if (nbins < 1) nbins = 1;
4948 
4949  // Do nothing in case it was the last bin
4950  if (nbins==axis->GetNbins()) return;
4951 
4952  TH1 *hold = (TH1*)IsA()->New();
4953  R__ASSERT(hold);
4954  hold->SetDirectory(0);
4955  Copy(*hold);
4956 
4957  Bool_t timedisp = axis->GetTimeDisplay();
4958  Double_t xmin = axis->GetXmin();
4959  Double_t xmax = axis->GetBinUpEdge(nbins);
4960  if (xmax <= xmin) xmax = xmin +nbins;
4961  axis->SetRange(0,0);
4962  axis->Set(nbins,xmin,xmax);
4963  SetBinsLength(-1); // reset the number of cells
4964  Int_t errors = fSumw2.fN;
4965  if (errors) fSumw2.Set(fNcells);
4966  axis->SetTimeDisplay(timedisp);
4967  // reset histogram content
4968  Reset("ICE");
4969 
4970  //now loop on all bins and refill
4971  // NOTE that if the bins without labels have content
4972  // it will be put in the underflow/overflow.
4973  // For this reason we use AddBinContent method
4974  Double_t oldEntries = fEntries;
4975  Int_t bin,binx,biny,binz;
4976  for (bin=0; bin < hold->fNcells; ++bin) {
4977  hold->GetBinXYZ(bin,binx,biny,binz);
4978  Int_t ibin = GetBin(binx,biny,binz);
4979  Double_t cu = hold->RetrieveBinContent(bin);
4980  AddBinContent(ibin,cu);
4981  if (errors) {
4982  fSumw2.fArray[ibin] += hold->fSumw2.fArray[bin];
4983  }
4984  }
4985  fEntries = oldEntries;
4986  delete hold;
4987 }
4988 
4989 ////////////////////////////////////////////////////////////////////////////////
4990 /// Double the number of bins for axis.
4991 /// Refill histogram
4992 /// This function is called by TAxis::FindBin(const char *label)
4993 
4994 void TH1::LabelsInflate(Option_t *ax)
4995 {
4996  Int_t iaxis = AxisChoice(ax);
4997  TAxis *axis = 0;
4998  if (iaxis == 1) axis = GetXaxis();
4999  if (iaxis == 2) axis = GetYaxis();
5000  if (iaxis == 3) axis = GetZaxis();
5001  if (!axis) return;
5002 
5003  TH1 *hold = (TH1*)IsA()->New();;
5004  hold->SetDirectory(0);
5005  Copy(*hold);
5006 
5007  Bool_t timedisp = axis->GetTimeDisplay();
5008  Int_t nbins = axis->GetNbins();
5009  Double_t xmin = axis->GetXmin();
5010  Double_t xmax = axis->GetXmax();
5011  xmax = xmin + 2*(xmax-xmin);
5012  axis->SetRange(0,0);
5013  // double the bins and recompute ncells
5014  axis->Set(2*nbins,xmin,xmax);
5015  SetBinsLength(-1);
5016  Int_t errors = fSumw2.fN;
5017  if (errors) fSumw2.Set(fNcells);
5018  axis->SetTimeDisplay(timedisp);
5019 
5020  Reset("ICE"); // reset content and error
5021 
5022  //now loop on all bins and refill
5023  Double_t oldEntries = fEntries;
5024  Int_t bin,ibin,binx,biny,binz;
5025  for (ibin =0; ibin < hold->fNcells; ibin++) {
5026  // get the binx,y,z values . The x-y-z (axis) bin values will stay the same between new-old after the expanding
5027  hold->GetBinXYZ(ibin,binx,biny,binz);
5028  bin = GetBin(binx,biny,binz);
5029 
5030  // underflow and overflow will be cleaned up because their meaning has been altered
5031  if (hold->IsBinUnderflow(ibin,iaxis) || hold->IsBinOverflow(ibin,iaxis)) {
5032  continue;
5033  }
5034  else {
5035  AddBinContent(bin, hold->RetrieveBinContent(ibin));
5036  if (errors) fSumw2.fArray[bin] += hold->fSumw2.fArray[ibin];
5037  }
5038  }
5039  fEntries = oldEntries;
5040  delete hold;
5041 }
5042 
5043 ////////////////////////////////////////////////////////////////////////////////
5044 /// Set option(s) to draw axis with labels
5045 /// \param[in] option
5046 /// - "a" sort by alphabetic order
5047 /// - ">" sort by decreasing values
5048 /// - "<" sort by increasing values
5049 /// - "h" draw labels horizontal
5050 /// - "v" draw labels vertical
5051 /// - "u" draw labels up (end of label right adjusted)
5052 /// - "d" draw labels down (start of label left adjusted)
5053 /// \param[in] ax axis
5054 
5055 void TH1::LabelsOption(Option_t *option, Option_t *ax)
5056 {
5057  Int_t iaxis = AxisChoice(ax);
5058  TAxis *axis = 0;
5059  if (iaxis == 1) axis = GetXaxis();
5060  if (iaxis == 2) axis = GetYaxis();
5061  if (iaxis == 3) axis = GetZaxis();
5062  if (!axis) return;
5063  THashList *labels = axis->GetLabels();
5064  if (!labels) {
5065  Warning("LabelsOption","Cannot sort. No labels");
5066  return;
5067  }
5068  TString opt = option;
5069  opt.ToLower();
5070  if (opt.Contains("h")) {
5071  axis->SetBit(TAxis::kLabelsHori);
5074  axis->ResetBit(TAxis::kLabelsUp);
5075  }
5076  if (opt.Contains("v")) {
5077  axis->SetBit(TAxis::kLabelsVert);
5080  axis->ResetBit(TAxis::kLabelsUp);
5081  }
5082  if (opt.Contains("u")) {
5083  axis->SetBit(TAxis::kLabelsUp);
5087  }
5088  if (opt.Contains("d")) {
5089  axis->SetBit(TAxis::kLabelsDown);
5092  axis->ResetBit(TAxis::kLabelsUp);
5093  }
5094  Int_t sort = -1;
5095  if (opt.Contains("a")) sort = 0;
5096  if (opt.Contains(">")) sort = 1;
5097  if (opt.Contains("<")) sort = 2;
5098  if (sort < 0) return;
5099  if (sort > 0 && GetDimension() > 2) {
5100  Error("LabelsOption","Sorting by value not implemented for 3-D histograms");
5101  return;
5102  }
5103 
5104  Double_t entries = fEntries;
5105  Int_t n = TMath::Min(axis->GetNbins(), labels->GetSize());
5106  std::vector<Int_t> a(n+2);
5107 
5108  Int_t i,j,k;
5109  std::vector<Double_t> cont;
5110  std::vector<Double_t> errors;
5111  THashList *labold = new THashList(labels->GetSize(),1);
5112  TIter nextold(labels);
5113  TObject *obj;
5114  while ((obj=nextold())) {
5115  labold->Add(obj);
5116  }
5117  labels->Clear();
5118  if (sort > 0) {
5119  //---sort by values of bins
5120  if (GetDimension() == 1) {
5121  cont.resize(n);
5122  if (fSumw2.fN) errors.resize(n);
5123  for (i=1;i<=n;i++) {
5124  cont[i-1] = GetBinContent(i);
5125  if (!errors.empty()) errors[i-1] = GetBinError(i);
5126  }
5127  if (sort ==1) TMath::Sort(n,cont.data(),a.data(),kTRUE); //sort by decreasing values
5128  else TMath::Sort(n,cont.data(),a.data(),kFALSE); //sort by increasing values
5129  for (i=1;i<=n;i++) {
5130  SetBinContent(i,cont[a[i-1]]);
5131  if (!errors.empty()) SetBinError(i,errors[a[i-1]]);
5132  }
5133  for (i=1;i<=n;i++) {
5134  obj = labold->At(a[i-1]);
5135  labels->Add(obj);
5136  obj->SetUniqueID(i);
5137  }
5138  } else if (GetDimension()== 2) {
5139  std::vector<Double_t> pcont(n+2);
5140  Int_t nx = fXaxis.GetNbins();
5141  Int_t ny = fYaxis.GetNbins();
5142  cont.resize( (nx+2)*(ny+2));
5143  if (fSumw2.fN) errors.resize( (nx+2)*(ny+2));
5144  for (i=1;i<=nx;i++) {
5145  for (j=1;j<=ny;j++) {
5146  cont[i+nx*j] = GetBinContent(i,j);
5147  if (!errors.empty()) errors[i+nx*j] = GetBinError(i,j);
5148  if (axis == GetXaxis()) k = i;
5149  else k = j;
5150  pcont[k-1] += cont[i+nx*j];
5151  }
5152  }
5153  if (sort ==1) TMath::Sort(n,pcont.data(),a.data(),kTRUE); //sort by decreasing values
5154  else TMath::Sort(n,pcont.data(),a.data(),kFALSE); //sort by increasing values
5155  for (i=0;i<n;i++) {
5156  obj = labold->At(a[i]);
5157  labels->Add(obj);
5158  obj->SetUniqueID(i+1);
5159  }
5160  if (axis == GetXaxis()) {
5161  for (i=1;i<=n;i++) {
5162  for (j=1;j<=ny;j++) {
5163  SetBinContent(i,j,cont[a[i-1]+1+nx*j]);
5164  if (!errors.empty()) SetBinError(i,j,errors[a[i-1]+1+nx*j]);
5165  }
5166  }
5167  }
5168  else {
5169  // using y axis
5170  for (i=1;i<=nx;i++) {
5171  for (j=1;j<=n;j++) {
5172  SetBinContent(i,j,cont[i+nx*(a[j-1]+1)]);
5173  if (!errors.empty()) SetBinError(i,j,errors[i+nx*(a[j-1]+1)]);
5174  }
5175  }
5176  }
5177  } else {
5178  //to be implemented for 3d
5179  }
5180  } else {
5181  //---alphabetic sort
5182  const UInt_t kUsed = 1<<18;
5183  TObject *objk=0;
5184  a[0] = 0;
5185  a[n+1] = n+1;
5186  for (i=1;i<=n;i++) {
5187  const char *label = "zzzzzzzzzzzz";
5188  for (j=1;j<=n;j++) {
5189  obj = labold->At(j-1);
5190  if (!obj) continue;
5191  if (obj->TestBit(kUsed)) continue;
5192  //use strcasecmp for case non-sensitive sort (may be an option)
5193  if (strcmp(label,obj->GetName()) < 0) continue;
5194  objk = obj;
5195  a[i] = j;
5196  label = obj->GetName();
5197  }
5198  if (objk) {
5199  objk->SetUniqueID(i);
5200  labels->Add(objk);
5201  objk->SetBit(kUsed);
5202  }
5203  }
5204  for (i=1;i<=n;i++) {
5205  obj = labels->At(i-1);
5206  if (!obj) continue;
5207  obj->ResetBit(kUsed);
5208  }
5209 
5210  if (GetDimension() == 1) {
5211  cont.resize(n+2);
5212  if (fSumw2.fN) errors.resize(n+2);
5213  for (i=1;i<=n;i++) {
5214  cont[i] = GetBinContent(a[i]);
5215  if (!errors.empty()) errors[i] = GetBinError(a[i]);
5216  }
5217  for (i=1;i<=n;i++) {
5218  SetBinContent(i,cont[i]);
5219  if (!errors.empty()) SetBinError(i,errors[i]);
5220  }
5221  } else if (GetDimension()== 2) {
5222  Int_t nx = fXaxis.GetNbins()+2;
5223  Int_t ny = fYaxis.GetNbins()+2;
5224  cont.resize(nx*ny);
5225  if (fSumw2.fN) errors.resize(nx*ny);
5226  for (i=0;i<nx;i++) {
5227  for (j=0;j<ny;j++) {
5228  cont[i+nx*j] = GetBinContent(i,j);
5229  if (!errors.empty()) errors[i+nx*j] = GetBinError(i,j);
5230  }
5231  }
5232  if (axis == GetXaxis()) {
5233  for (i=1;i<=n;i++) {
5234  for (j=0;j<ny;j++) {
5235  SetBinContent(i,j,cont[a[i]+nx*j]);
5236  if (!errors.empty()) SetBinError(i,j,errors[a[i]+nx*j]);
5237  }
5238  }
5239  } else {
5240  for (i=0;i<nx;i++) {
5241  for (j=1;j<=n;j++) {
5242  SetBinContent(i,j,cont[i+nx*a[j]]);
5243  if (!errors.empty()) SetBinError(i,j,errors[i+nx*a[j]]);
5244  }
5245  }
5246  }
5247  } else {
5248  Int_t nx = fXaxis.GetNbins()+2;
5249  Int_t ny = fYaxis.GetNbins()+2;
5250  Int_t nz = fZaxis.GetNbins()+2;
5251  cont.resize(nx*ny*nz);
5252  if (fSumw2.fN) errors.resize(nx*ny*nz);
5253  for (i=0;i<nx;i++) {
5254  for (j=0;j<ny;j++) {
5255  for (k=0;k<nz;k++) {
5256  cont[i+nx*(j+ny*k)] = GetBinContent(i,j,k);
5257  if (!errors.empty()) errors[i+nx*(j+ny*k)] = GetBinError(i,j,k);
5258  }
5259  }
5260  }
5261  if (axis == GetXaxis()) {
5262  // labels on x axis
5263  for (i=1;i<=n;i++) {
5264  for (j=0;j<ny;j++) {
5265  for (k=0;k<nz;k++) {
5266  SetBinContent(i,j,k,cont[a[i]+nx*(j+ny*k)]);
5267  if (!errors.empty()) SetBinError(i,j,k,errors[a[i]+nx*(j+ny*k)]);
5268  }
5269  }
5270  }
5271  }
5272  else if (axis == GetYaxis()) {
5273  // labels on y axis
5274  for (i=0;i<nx;i++) {
5275  for (j=1;j<=n;j++) {
5276  for (k=0;k<nz;k++) {
5277  SetBinContent(i,j,k,cont[i+nx*(a[j]+ny*k)]);
5278  if (!errors.empty()) SetBinError(i,j,k,errors[i+nx*(a[j]+ny*k)]);
5279  }
5280  }
5281  }
5282  }
5283  else {
5284  // labels on z axis
5285  for (i=0;i<nx;i++) {
5286  for (j=0;j<ny;j++) {
5287  for (k=1;k<=n;k++) {
5288  SetBinContent(i,j,k,cont[i+nx*(j+ny*a[k])]);
5289  if (!errors.empty()) SetBinError(i,j,k,errors[i+nx*(j+ny*a[k])]);
5290  }
5291  }
5292  }
5293  }
5294  }
5295  }
5296  fEntries = entries;
5297  delete labold;
5298 }
5299 
5300 ////////////////////////////////////////////////////////////////////////////////
5301 /// Test if two double are almost equal.
5302 
5303 static inline Bool_t AlmostEqual(Double_t a, Double_t b, Double_t epsilon = 0.00000001)
5304 {
5305  return TMath::Abs(a - b) < epsilon;
5306 }
5307 
5308 ////////////////////////////////////////////////////////////////////////////////
5309 /// Test if a double is almost an integer.
5310 
5311 static inline Bool_t AlmostInteger(Double_t a, Double_t epsilon = 0.00000001)
5312 {
5313  return AlmostEqual(a - TMath::Floor(a), 0, epsilon) ||
5315 }
5316 
5317 ////////////////////////////////////////////////////////////////////////////////
5318 /// Test if the binning is equidistant.
5319 
5320 static inline bool IsEquidistantBinning(const TAxis& axis)
5321 {
5322  // check if axis bin are equals
5323  if (!axis.GetXbins()->fN) return true; //
5324  // not able to check if there is only one axis entry
5325  bool isEquidistant = true;
5326  const Double_t firstBinWidth = axis.GetBinWidth(1);
5327  for (int i = 1; i < axis.GetNbins(); ++i) {
5328  const Double_t binWidth = axis.GetBinWidth(i);
5329  const bool match = TMath::AreEqualRel(firstBinWidth, binWidth, TMath::Limits<Double_t>::Epsilon());
5330  isEquidistant &= match;
5331  if (!match)
5332  break;
5333  }
5334  return isEquidistant;
5335 }
5336 
5337 ////////////////////////////////////////////////////////////////////////////////
5338 /// Same limits and bins.
5339 
5340 Bool_t TH1::SameLimitsAndNBins(const TAxis& axis1, const TAxis& axis2)
5341 {
5342  return axis1.GetNbins() == axis2.GetNbins()
5343  && axis1.GetXmin() == axis2.GetXmin()
5344  && axis1.GetXmax() == axis2.GetXmax();
5345 }
5346 
5347 ////////////////////////////////////////////////////////////////////////////////
5348 /// Finds new limits for the axis for the Merge function.
5349 /// returns false if the limits are incompatible
5350 
5351 Bool_t TH1::RecomputeAxisLimits(TAxis& destAxis, const TAxis& anAxis)
5352 {
5353  if (SameLimitsAndNBins(destAxis, anAxis))
5354  return kTRUE;
5355 
5356  if (!IsEquidistantBinning(destAxis) || !IsEquidistantBinning(anAxis))
5357  return kFALSE; // not equidistant user binning not supported
5358 
5359  Double_t width1 = destAxis.GetBinWidth(0);
5360  Double_t width2 = anAxis.GetBinWidth(0);
5361  if (width1 == 0 || width2 == 0)
5362  return kFALSE; // no binning not supported
5363 
5364  Double_t xmin = TMath::Min(destAxis.GetXmin(), anAxis.GetXmin());
5365  Double_t xmax = TMath::Max(destAxis.GetXmax(), anAxis.GetXmax());
5366  Double_t width = TMath::Max(width1, width2);
5367 
5368  // check the bin size
5369  if (!AlmostInteger(width/width1) || !AlmostInteger(width/width2))
5370  return kFALSE;
5371 
5372  // std::cout << "Find new limit using given axis " << anAxis.GetXmin() << " , " << anAxis.GetXmax() << " bin width " << width2 << std::endl;
5373  // std::cout << " and destination axis " << destAxis.GetXmin() << " , " << destAxis.GetXmax() << " bin width " << width1 << std::endl;
5374 
5375 
5376  // check the limits
5377  Double_t delta;
5378  delta = (destAxis.GetXmin() - xmin)/width1;
5379  if (!AlmostInteger(delta))
5380  xmin -= (TMath::Ceil(delta) - delta)*width1;
5381 
5382  delta = (anAxis.GetXmin() - xmin)/width2;
5383  if (!AlmostInteger(delta))
5384  xmin -= (TMath::Ceil(delta) - delta)*width2;
5385 
5386 
5387  delta = (destAxis.GetXmin() - xmin)/width1;
5388  if (!AlmostInteger(delta))
5389  return kFALSE;
5390 
5391 
5392  delta = (xmax - destAxis.GetXmax())/width1;
5393  if (!AlmostInteger(delta))
5394  xmax += (TMath::Ceil(delta) - delta)*width1;
5395 
5396 
5397  delta = (xmax - anAxis.GetXmax())/width2;
5398  if (!AlmostInteger(delta))
5399  xmax += (TMath::Ceil(delta) - delta)*width2;
5400 
5401 
5402  delta = (xmax - destAxis.GetXmax())/width1;
5403  if (!AlmostInteger(delta))
5404  return kFALSE;
5405 #ifdef DEBUG
5406  if (!AlmostInteger((xmax - xmin) / width)) { // unnecessary check
5407  printf("TH1::RecomputeAxisLimits - Impossible\n");
5408  return kFALSE;
5409  }
5410 #endif
5411 
5412 
5413  destAxis.Set(TMath::Nint((xmax - xmin)/width), xmin, xmax);
5414 
5415  //std::cout << "New re-computed axis : [ " << xmin << " , " << xmax << " ] width = " << width << " nbins " << destAxis.GetNbins() << std::endl;
5416 
5417  return kTRUE;
5418 }
5419 
5420 ////////////////////////////////////////////////////////////////////////////////
5421 /// Add all histograms in the collection to this histogram.
5422 /// This function computes the min/max for the x axis,
5423 /// compute a new number of bins, if necessary,
5424 /// add bin contents, errors and statistics.
5425 /// If all histograms have bin labels, bins with identical labels
5426 /// will be merged, no matter what their order is.
5427 /// If overflows are present and limits are different the function will fail.
5428 /// The function returns the total number of entries in the result histogram
5429 /// if the merge is successful, -1 otherwise.
5430 ///
5431 /// IMPORTANT remark. The axis x may have different number
5432 /// of bins and different limits, BUT the largest bin width must be
5433 /// a multiple of the smallest bin width and the upper limit must also
5434 /// be a multiple of the bin width.
5435 /// Example:
5436 ///
5437 /// ~~~ {.cpp}
5438 /// void atest() {
5439 /// TH1F *h1 = new TH1F("h1","h1",110,-110,0);
5440 /// TH1F *h2 = new TH1F("h2","h2",220,0,110);
5441 /// TH1F *h3 = new TH1F("h3","h3",330,-55,55);
5442 /// TRandom r;
5443 /// for (Int_t i=0;i<10000;i++) {
5444 /// h1->Fill(r.Gaus(-55,10));
5445 /// h2->Fill(r.Gaus(55,10));
5446 /// h3->Fill(r.Gaus(0,10));
5447 /// }
5448 ///
5449 /// TList *list = new TList;
5450 /// list->Add(h1);
5451 /// list->Add(h2);
5452 /// list->Add(h3);
5453 /// TH1F *h = (TH1F*)h1->Clone("h");
5454 /// h->Reset();
5455 /// h->Merge(list);
5456 /// h->Draw();
5457 /// }
5458 /// ~~~
5459 
5461 {
5462  if (!li) return 0;
5463  if (li->IsEmpty()) return (Long64_t) GetEntries();
5464 
5465  // use TH1Merger class
5466  TH1Merger merger(*this,*li);
5467  Bool_t ret = merger();
5468 
5469  return (ret) ? GetEntries() : -1;
5470 }
5471 
5472 
5473 ////////////////////////////////////////////////////////////////////////////////
5474 /// Performs the operation: this = this*c1*f1
5475 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
5476 ///
5477 /// Only bins inside the function range are recomputed.
5478 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5479 /// you should call Sumw2 before making this operation.
5480 /// This is particularly important if you fit the histogram after TH1::Multiply
5481 ///
5482 /// The function return kFALSE if the Multiply operation failed
5483 
5485 {
5486  if (!f1) {
5487  Error("Add","Attempt to multiply by a non-existing function");
5488  return kFALSE;
5489  }
5490 
5491  // delete buffer if it is there since it will become invalid
5492  if (fBuffer) BufferEmpty(1);
5493 
5494  Int_t nx = GetNbinsX() + 2; // normal bins + uf / of (cells)
5495  Int_t ny = GetNbinsY() + 2;
5496  Int_t nz = GetNbinsZ() + 2;
5497  if (fDimension < 2) ny = 1;
5498  if (fDimension < 3) nz = 1;
5499 
5500  // reset min-maximum
5501  SetMinimum();
5502  SetMaximum();
5503 
5504  // - Loop on bins (including underflows/overflows)
5505  Double_t xx[3];
5506  Double_t *params = 0;
5507  f1->InitArgs(xx,params);
5508 
5509  for (Int_t binz = 0; binz < nz; ++binz) {
5510  xx[2] = fZaxis.GetBinCenter(binz);
5511  for (Int_t biny = 0; biny < ny; ++biny) {
5512  xx[1] = fYaxis.GetBinCenter(biny);
5513  for (Int_t binx = 0; binx < nx; ++binx) {
5514  xx[0] = fXaxis.GetBinCenter(binx);
5515  if (!f1->IsInside(xx)) continue;
5517  Int_t bin = binx + nx * (biny + ny *binz);
5518  Double_t cu = c1*f1->EvalPar(xx);
5519  if (TF1::RejectedPoint()) continue;
5520  UpdateBinContent(bin, RetrieveBinContent(bin) * cu);
5521  if (fSumw2.fN) {
5522  fSumw2.fArray[bin] = cu * cu * GetBinErrorSqUnchecked(bin);
5523  }
5524  }
5525  }
5526  }
5527  ResetStats();
5528  return kTRUE;
5529 }
5530 
5531 ////////////////////////////////////////////////////////////////////////////////
5532 /// Multiply this histogram by h1.
5533 ///
5534 /// `this = this*h1`
5535 ///
5536 /// If errors of this are available (TH1::Sumw2), errors are recalculated.
5537 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
5538 /// if not already set.
5539 ///
5540 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5541 /// you should call Sumw2 before making this operation.
5542 /// This is particularly important if you fit the histogram after TH1::Multiply
5543 ///
5544 /// The function return kFALSE if the Multiply operation failed
5545 
5546 Bool_t TH1::Multiply(const TH1 *h1)
5547 {
5548  if (!h1) {
5549  Error("Multiply","Attempt to multiply by a non-existing histogram");
5550  return kFALSE;
5551  }
5552 
5553  // delete buffer if it is there since it will become invalid
5554  if (fBuffer) BufferEmpty(1);
5555 
5556  try {
5557  CheckConsistency(this,h1);
5558  } catch(DifferentNumberOfBins&) {
5559  Error("Multiply","Attempt to multiply histograms with different number of bins");
5560  return kFALSE;
5561  } catch(DifferentAxisLimits&) {
5562  Warning("Multiply","Attempt to multiply histograms with different axis limits");
5563  } catch(DifferentBinLimits&) {
5564  Warning("Multiply","Attempt to multiply histograms with different bin limits");
5565  } catch(DifferentLabels&) {
5566  Warning("Multiply","Attempt to multiply histograms with different labels");
5567  }
5568 
5569  // Create Sumw2 if h1 has Sumw2 set
5570  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
5571 
5572  // - Reset min- maximum
5573  SetMinimum();
5574  SetMaximum();
5575 
5576  // - Loop on bins (including underflows/overflows)
5577  for (Int_t i = 0; i < fNcells; ++i) {
5578  Double_t c0 = RetrieveBinContent(i);
5580  UpdateBinContent(i, c0 * c1);
5581  if (fSumw2.fN) {
5582  fSumw2.fArray[i] = GetBinErrorSqUnchecked(i) * c1 * c1 + h1->GetBinErrorSqUnchecked(i) * c0 * c0;
5583  }
5584  }
5585  ResetStats();
5586  return kTRUE;
5587 }
5588 
5589 ////////////////////////////////////////////////////////////////////////////////
5590 /// Replace contents of this histogram by multiplication of h1 by h2.
5591 ///
5592 /// `this = (c1*h1)*(c2*h2)`
5593 ///
5594 /// If errors of this are available (TH1::Sumw2), errors are recalculated.
5595 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
5596 /// if not already set.
5597 ///
5598 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5599 /// you should call Sumw2 before making this operation.
5600 /// This is particularly important if you fit the histogram after TH1::Multiply
5601 ///
5602 /// The function return kFALSE if the Multiply operation failed
5603 
5604 Bool_t TH1::Multiply(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2, Option_t *option)
5605 {
5606  TString opt = option;
5607  opt.ToLower();
5608  // Bool_t binomial = kFALSE;
5609  // if (opt.Contains("b")) binomial = kTRUE;
5610  if (!h1 || !h2) {
5611  Error("Multiply","Attempt to multiply by a non-existing histogram");
5612  return kFALSE;
5613  }
5614 
5615  // delete buffer if it is there since it will become invalid
5616  if (fBuffer) BufferEmpty(1);
5617 
5618  try {
5619  CheckConsistency(h1,h2);
5620  CheckConsistency(this,h1);
5621  } catch(DifferentNumberOfBins&) {
5622  Error("Multiply","Attempt to multiply histograms with different number of bins");
5623  return kFALSE;
5624  } catch(DifferentAxisLimits&) {
5625  Warning("Multiply","Attempt to multiply histograms with different axis limits");
5626  } catch(DifferentBinLimits&) {
5627  Warning("Multiply","Attempt to multiply histograms with different bin limits");
5628  } catch(DifferentLabels&) {
5629  Warning("Multiply","Attempt to multiply histograms with different labels");
5630  }
5631 
5632  // Create Sumw2 if h1 or h2 have Sumw2 set
5633  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
5634 
5635  // - Reset min - maximum
5636  SetMinimum();
5637  SetMaximum();
5638 
5639  // - Loop on bins (including underflows/overflows)
5640  Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
5641  for (Int_t i = 0; i < fNcells; ++i) {
5642  Double_t b1 = h1->RetrieveBinContent(i);
5643  Double_t b2 = h2->RetrieveBinContent(i);
5644  UpdateBinContent(i, c1 * b1 * c2 * b2);
5645  if (fSumw2.fN) {
5646  fSumw2.fArray[i] = c1sq * c2sq * (h1->GetBinErrorSqUnchecked(i) * b2 * b2 + h2->GetBinErrorSqUnchecked(i) * b1 * b1);
5647  }
5648  }
5649  ResetStats();
5650  return kTRUE;
5651 }
5652 
5653 ////////////////////////////////////////////////////////////////////////////////
5654 /// Control routine to paint any kind of histograms.
5655 ///
5656 /// This function is automatically called by TCanvas::Update.
5657 /// (see TH1::Draw for the list of options)
5658 
5659 void TH1::Paint(Option_t *option)
5660 {
5661  GetPainter(option);
5662 
5663  if (fPainter) {
5664  if (strlen(option) > 0) fPainter->Paint(option);
5665  else fPainter->Paint(fOption.Data());
5666  }
5667 }
5668 
5669 ////////////////////////////////////////////////////////////////////////////////
5670 /// Rebin this histogram
5671 ///
5672 /// #### case 1 xbins=0
5673 ///
5674 /// If newname is blank (default), the current histogram is modified and
5675 /// a pointer to it is returned.
5676 ///
5677 /// If newname is not blank, the current histogram is not modified, and a
5678 /// new histogram is returned which is a Clone of the current histogram
5679 /// with its name set to newname.
5680 ///
5681 /// The parameter ngroup indicates how many bins of this have to be merged
5682 /// into one bin of the result.
5683 ///
5684 /// If the original histogram has errors stored (via Sumw2), the resulting
5685 /// histograms has new errors correctly calculated.
5686 ///
5687 /// examples: if h1 is an existing TH1F histogram with 100 bins
5688 ///
5689 /// ~~~ {.cpp}
5690 /// h1->Rebin(); //merges two bins in one in h1: previous contents of h1 are lost
5691 /// h1->Rebin(5); //merges five bins in one in h1
5692 /// TH1F *hnew = dynamic_cast<TH1F*>(h1->Rebin(5,"hnew")); // creates a new histogram hnew
5693 /// // merging 5 bins of h1 in one bin
5694 /// ~~~
5695 ///
5696 /// NOTE: If ngroup is not an exact divider of the number of bins,
5697 /// the top limit of the rebinned histogram is reduced
5698 /// to the upper edge of the last bin that can make a complete
5699 /// group. The remaining bins are added to the overflow bin.
5700 /// Statistics will be recomputed from the new bin contents.
5701 ///
5702 /// #### case 2 xbins!=0
5703 ///
5704 /// A new histogram is created (you should specify newname).
5705 /// The parameter ngroup is the number of variable size bins in the created histogram.
5706 /// The array xbins must contain ngroup+1 elements that represent the low-edges
5707 /// of the bins.
5708 /// If the original histogram has errors stored (via Sumw2), the resulting
5709 /// histograms has new errors correctly calculated.
5710 ///
5711 /// NOTE: The bin edges specified in xbins should correspond to bin edges
5712 /// in the original histogram. If a bin edge in the new histogram is
5713 /// in the middle of a bin in the original histogram, all entries in
5714 /// the split bin in the original histogram will be transfered to the
5715 /// lower of the two possible bins in the new histogram. This is
5716 /// probably not what you want.
5717 ///
5718 /// examples: if h1 is an existing TH1F histogram with 100 bins
5719 ///
5720 /// ~~~ {.cpp}
5721 /// Double_t xbins[25] = {...} array of low-edges (xbins[25] is the upper edge of last bin
5722 /// h1->Rebin(24,"hnew",xbins); //creates a new variable bin size histogram hnew
5723 /// ~~~
5724 
5725 TH1 *TH1::Rebin(Int_t ngroup, const char*newname, const Double_t *xbins)
5726 {
5727  Int_t nbins = fXaxis.GetNbins();
5730  if ((ngroup <= 0) || (ngroup > nbins)) {
5731  Error("Rebin", "Illegal value of ngroup=%d",ngroup);
5732  return 0;
5733  }
5734 
5735  if (fDimension > 1 || InheritsFrom(TProfile::Class())) {
5736  Error("Rebin", "Operation valid on 1-D histograms only");
5737  return 0;
5738  }
5739  if (!newname && xbins) {
5740  Error("Rebin","if xbins is specified, newname must be given");
5741  return 0;
5742  }
5743 
5744  Int_t newbins = nbins/ngroup;
5745  if (!xbins) {
5746  Int_t nbg = nbins/ngroup;
5747  if (nbg*ngroup != nbins) {
5748  Warning("Rebin", "ngroup=%d is not an exact divider of nbins=%d.",ngroup,nbins);
5749  }
5750  }
5751  else {
5752  // in the case that xbins is given (rebinning in variable bins), ngroup is
5753  // the new number of bins and number of grouped bins is not constant.
5754  // when looping for setting the contents for the new histogram we
5755  // need to loop on all bins of original histogram. Then set ngroup=nbins
5756  newbins = ngroup;
5757  ngroup = nbins;
5758  }
5759 
5760  // Save old bin contents into a new array
5761  Double_t entries = fEntries;
5762  Double_t *oldBins = new Double_t[nbins+2];
5763  Int_t bin, i;
5764  for (bin=0;bin<nbins+2;bin++) oldBins[bin] = RetrieveBinContent(bin);
5765  Double_t *oldErrors = 0;
5766  if (fSumw2.fN != 0) {
5767  oldErrors = new Double_t[nbins+2];
5768  for (bin=0;bin<nbins+2;bin++) oldErrors[bin] = GetBinError(bin);
5769  }
5770  // rebin will not include underflow/overflow if new axis range is larger than old axis range
5771  if (xbins) {
5772  if (xbins[0] < fXaxis.GetXmin() && oldBins[0] != 0 )
5773  Warning("Rebin","underflow entries will not be used when rebinning");
5774  if (xbins[newbins] > fXaxis.GetXmax() && oldBins[nbins+1] != 0 )
5775  Warning("Rebin","overflow entries will not be used when rebinning");
5776  }
5777 
5778 
5779  // create a clone of the old histogram if newname is specified
5780  TH1 *hnew = this;
5781  if ((newname && strlen(newname) > 0) || xbins) {
5782  hnew = (TH1*)Clone(newname);
5783  }
5784 
5785  //reset can extend bit to avoid an axis extension in SetBinContent
5786  UInt_t oldExtendBitMask = hnew->SetCanExtend(kNoAxis);
5787 
5788  // save original statistics
5789  Double_t stat[kNstat];
5790  GetStats(stat);
5791  bool resetStat = false;
5792  // change axis specs and rebuild bin contents array::RebinAx
5793  if(!xbins && (newbins*ngroup != nbins)) {
5794  xmax = fXaxis.GetBinUpEdge(newbins*ngroup);
5795  resetStat = true; //stats must be reset because top bins will be moved to overflow bin
5796  }
5797  // save the TAttAxis members (reset by SetBins)
5798  Int_t nDivisions = fXaxis.GetNdivisions();
5799  Color_t axisColor = fXaxis.GetAxisColor();
5800  Color_t labelColor = fXaxis.GetLabelColor();
5801  Style_t labelFont = fXaxis.GetLabelFont();
5802  Float_t labelOffset = fXaxis.GetLabelOffset();
5803  Float_t labelSize = fXaxis.GetLabelSize();
5804  Float_t tickLength = fXaxis.GetTickLength();
5805  Float_t titleOffset = fXaxis.GetTitleOffset();
5806  Float_t titleSize = fXaxis.GetTitleSize();
5807  Color_t titleColor = fXaxis.GetTitleColor();
5808  Style_t titleFont = fXaxis.GetTitleFont();
5809 
5810  if(!xbins && (fXaxis.GetXbins()->GetSize() > 0)){ // variable bin sizes
5811  Double_t *bins = new Double_t[newbins+1];
5812  for(i = 0; i <= newbins; ++i) bins[i] = fXaxis.GetBinLowEdge(1+i*ngroup);
5813  hnew->SetBins(newbins,bins); //this also changes errors array (if any)
5814  delete [] bins;
5815  } else if (xbins) {
5816  hnew->SetBins(newbins,xbins);
5817  } else {
5818  hnew->SetBins(newbins,xmin,xmax);
5819  }
5820 
5821  // Restore axis attributes
5822  fXaxis.SetNdivisions(nDivisions);
5823  fXaxis.SetAxisColor(axisColor);
5824  fXaxis.SetLabelColor(labelColor);
5825  fXaxis.SetLabelFont(labelFont);
5826  fXaxis.SetLabelOffset(labelOffset);
5827  fXaxis.SetLabelSize(labelSize);
5828  fXaxis.SetTickLength(tickLength);
5829  fXaxis.SetTitleOffset(titleOffset);
5830  fXaxis.SetTitleSize(titleSize);
5831  fXaxis.SetTitleColor(titleColor);
5832  fXaxis.SetTitleFont(titleFont);
5833 
5834  // copy merged bin contents (ignore under/overflows)
5835  // Start merging only once the new lowest edge is reached
5836  Int_t startbin = 1;
5837  const Double_t newxmin = hnew->GetXaxis()->GetBinLowEdge(1);
5838  while( fXaxis.GetBinCenter(startbin) < newxmin && startbin <= nbins ) {
5839  startbin++;
5840  }
5841  Int_t oldbin = startbin;
5842  Double_t binContent, binError;
5843  for (bin = 1;bin<=newbins;bin++) {
5844  binContent = 0;
5845  binError = 0;
5846  Int_t imax = ngroup;
5847  Double_t xbinmax = hnew->GetXaxis()->GetBinUpEdge(bin);
5848  for (i=0;i<ngroup;i++) {
5849  if( (oldbin+i > nbins) ||
5850  ( hnew != this && (fXaxis.GetBinCenter(oldbin+i) > xbinmax)) ) {
5851  imax = i;
5852  break;
5853  }
5854  binContent += oldBins[oldbin+i];
5855  if (oldErrors) binError += oldErrors[oldbin+i]*oldErrors[oldbin+i];
5856  }
5857  hnew->SetBinContent(bin,binContent);
5858  if (oldErrors) hnew->SetBinError(bin,TMath::Sqrt(binError));
5859  oldbin += imax;
5860  }
5861 
5862  // sum underflow and overflow contents until startbin
5863  binContent = 0;
5864  binError = 0;
5865  for (i = 0; i < startbin; ++i) {
5866  binContent += oldBins[i];
5867  if (oldErrors) binError += oldErrors[i]*oldErrors[i];
5868  }
5869  hnew->SetBinContent(0,binContent);
5870  if (oldErrors) hnew->SetBinError(0,TMath::Sqrt(binError));
5871  // sum overflow
5872  binContent = 0;
5873  binError = 0;
5874  for (i = oldbin; i <= nbins+1; ++i) {
5875  binContent += oldBins[i];
5876  if (oldErrors) binError += oldErrors[i]*oldErrors[i];
5877  }
5878  hnew->SetBinContent(newbins+1,binContent);
5879  if (oldErrors) hnew->SetBinError(newbins+1,TMath::Sqrt(binError));
5880 
5881  hnew->SetCanExtend(oldExtendBitMask); // restore previous state
5882 
5883  // restore statistics and entries modified by SetBinContent
5884  hnew->SetEntries(entries);
5885  if (!resetStat) hnew->PutStats(stat);
5886  delete [] oldBins;
5887  if (oldErrors) delete [] oldErrors;
5888  return hnew;
5889 }
5890 
5891 ////////////////////////////////////////////////////////////////////////////////
5892 /// finds new limits for the axis so that *point* is within the range and
5893 /// the limits are compatible with the previous ones (see TH1::Merge).
5894 /// new limits are put into *newMin* and *newMax* variables.
5895 /// axis - axis whose limits are to be recomputed
5896 /// point - point that should fit within the new axis limits
5897 /// newMin - new minimum will be stored here
5898 /// newMax - new maximum will be stored here.
5899 /// false if failed (e.g. if the initial axis limits are wrong
5900 /// or the new range is more than \f$ 2^{64} \f$ times the old one).
5901 
5902 Bool_t TH1::FindNewAxisLimits(const TAxis* axis, const Double_t point, Double_t& newMin, Double_t &newMax)
5903 {
5904  Double_t xmin = axis->GetXmin();
5905  Double_t xmax = axis->GetXmax();
5906  if (xmin >= xmax) return kFALSE;
5907  Double_t range = xmax-xmin;
5908  Double_t binsize = range / axis->GetNbins();
5909 
5910  //recompute new axis limits by doubling the current range
5911  Int_t ntimes = 0;
5912  while (point < xmin) {
5913  if (ntimes++ > 64)
5914  return kFALSE;
5915  xmin = xmin - range;
5916  range *= 2;
5917  binsize *= 2;
5918  // // make sure that the merging will be correct
5919  // if ( xmin / binsize - TMath::Floor(xmin / binsize) >= 0.5) {
5920  // xmin += 0.5 * binsize;
5921  // xmax += 0.5 * binsize; // won't work with a histogram with only one bin, but I don't care
5922  // }
5923  }
5924  while (point >= xmax) {
5925  if (ntimes++ > 64)
5926  return kFALSE;
5927  xmax = xmax + range;
5928  range *= 2;
5929  binsize *= 2;
5930  // // make sure that the merging will be correct
5931  // if ( xmin / binsize - TMath::Floor(xmin / binsize) >= 0.5) {
5932  // xmin -= 0.5 * binsize;
5933  // xmax -= 0.5 * binsize; // won't work with a histogram with only one bin, but I don't care
5934  // }
5935  }
5936  newMin = xmin;
5937  newMax = xmax;
5938  // Info("FindNewAxisLimits", "OldAxis: (%lf, %lf), new: (%lf, %lf), point: %lf",
5939  // axis->GetXmin(), axis->GetXmax(), xmin, xmax, point);
5940 
5941  return kTRUE;
5942 }
5943 
5944 ////////////////////////////////////////////////////////////////////////////////
5945 /// Histogram is resized along axis such that x is in the axis range.
5946 /// The new axis limits are recomputed by doubling iteratively
5947 /// the current axis range until the specified value x is within the limits.
5948 /// The algorithm makes a copy of the histogram, then loops on all bins
5949 /// of the old histogram to fill the extended histogram.
5950 /// Takes into account errors (Sumw2) if any.
5951 /// The algorithm works for 1-d, 2-D and 3-D histograms.
5952 /// The axis must be extendable before invoking this function.
5953 /// Ex:
5954 ///
5955 /// ~~~ {.cpp}
5956 /// h->GetXaxis()->SetCanExtend(kTRUE);
5957 /// ~~~
5958 
5959 void TH1::ExtendAxis(Double_t x, TAxis *axis)
5960 {
5961  if (!axis->CanExtend()) return;
5962  if (TMath::IsNaN(x)) { // x may be a NaN
5964  return;
5965  }
5966 
5967  if (axis->GetXmin() >= axis->GetXmax()) return;
5968  if (axis->GetNbins() <= 0) return;
5969 
5970  Double_t xmin, xmax;
5971  if (!FindNewAxisLimits(axis, x, xmin, xmax))
5972  return;
5973 
5974  //save a copy of this histogram
5975  TH1 *hold = (TH1*)IsA()->New();
5976  hold->SetDirectory(0);
5977  Copy(*hold);
5978  //set new axis limits
5979  axis->SetLimits(xmin,xmax);
5980 
5981 
5982  //now loop on all bins and refill
5983  Int_t errors = GetSumw2N();
5984 
5985  Reset("ICE"); //reset only Integral, contents and Errors
5986 
5987  int iaxis = 0;
5988  if (axis == &fXaxis) iaxis = 1;
5989  if (axis == &fYaxis) iaxis = 2;
5990  if (axis == &fZaxis) iaxis = 3;
5991  bool firstw = kTRUE;
5992  Int_t binx,biny, binz = 0;
5993  Int_t ix = 0,iy = 0,iz = 0;
5994  Double_t bx,by,bz;
5995  Int_t ncells = hold->GetNcells();
5996  for (Int_t bin = 0; bin < ncells; ++bin) {
5997  hold->GetBinXYZ(bin,binx,biny,binz);
5998  bx = hold->GetXaxis()->GetBinCenter(binx);
5999  ix = fXaxis.FindFixBin(bx);
6000  if (fDimension > 1) {
6001  by = hold->GetYaxis()->GetBinCenter(biny);
6002  iy = fYaxis.FindFixBin(by);
6003  if (fDimension > 2) {
6004  bz = hold->GetZaxis()->GetBinCenter(binz);
6005  iz = fZaxis.FindFixBin(bz);
6006  }
6007  }
6008  // exclude underflow/overflow
6009  double content = hold->RetrieveBinContent(bin);
6010  if (content == 0) continue;
6011  if (IsBinUnderflow(bin,iaxis) || IsBinOverflow(bin,iaxis) ) {
6012  if (firstw) {
6013  Warning("ExtendAxis","Histogram %s has underflow or overflow in the axis that is extendable"
6014  " their content will be lost",GetName() );
6015  firstw= kFALSE;
6016  }
6017  continue;
6018  }
6019  Int_t ibin= GetBin(ix,iy,iz);
6020  AddBinContent(ibin, content);
6021  if (errors) {
6022  fSumw2.fArray[ibin] += hold->GetBinErrorSqUnchecked(bin);
6023  }
6024  }
6025  delete hold;
6026 }
6027 
6028 ////////////////////////////////////////////////////////////////////////////////
6029 /// Recursively remove object from the list of functions
6030 
6031 void TH1::RecursiveRemove(TObject *obj)
6032 {
6033  // Rely on TROOT::RecursiveRemove to take the readlock.
6034 
6035  if (fFunctions) {
6037  }
6038 }
6039 
6040 ////////////////////////////////////////////////////////////////////////////////
6041 /// Multiply this histogram by a constant c1.
6042 ///
6043 /// `this = c1*this`
6044 ///
6045 /// Note that both contents and errors(if any) are scaled.
6046 /// This function uses the services of TH1::Add
6047 ///
6048 /// IMPORTANT NOTE: Sumw2() is called automatically when scaling
6049 /// If you are not interested in the histogram statistics you can call
6050 /// Sumw2(off) or use the option "nosw2"
6051 ///
6052 /// One can scale an histogram such that the bins integral is equal to
6053 /// the normalization parameter via TH1::Scale(Double_t norm), where norm
6054 /// is the desired normalization divided by the integral of the histogram.
6055 ///
6056 /// If option contains "width" the bin contents and errors are divided
6057 /// by the bin width.
6058 
6059 void TH1::Scale(Double_t c1, Option_t *option)
6060 {
6062  TString opt = option; opt.ToLower();
6063  // store bin errors when scaling since cannot anymore be computed as sqrt(N)
6064  if (!opt.Contains("nosw2") && GetSumw2N() == 0) Sumw2();
6065  if (opt.Contains("width")) Add(this, this, c1, -1);
6066  else {
6067  if (fBuffer) BufferEmpty(1);
6068  for(Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, c1 * RetrieveBinContent(i));
6069  if (fSumw2.fN) for(Int_t i = 0; i < fNcells; ++i) fSumw2.fArray[i] *= (c1 * c1); // update errors
6070  SetMinimum(); SetMaximum(); // minimum and maximum value will be recalculated the next time
6071  }
6072 
6073  // if contours set, must also scale contours
6074  Int_t ncontours = GetContour();
6075  if (ncontours == 0) return;
6076  Double_t* levels = fContour.GetArray();
6077  for (Int_t i = 0; i < ncontours; ++i) levels[i] *= c1;
6078 }
6079 
6080 ////////////////////////////////////////////////////////////////////////////////
6081 /// Returns true if all axes are extendable.
6082 
6084 {
6085  Bool_t canExtend = fXaxis.CanExtend();
6086  if (GetDimension() > 1) canExtend &= fYaxis.CanExtend();
6087  if (GetDimension() > 2) canExtend &= fZaxis.CanExtend();
6088 
6089  return canExtend;
6090 }
6091 
6092 ////////////////////////////////////////////////////////////////////////////////
6093 /// Make the histogram axes extendable / not extendable according to the bit mask
6094 /// returns the previous bit mask specifying which axes are extendable
6095 
6096 UInt_t TH1::SetCanExtend(UInt_t extendBitMask)
6097 {
6098  UInt_t oldExtendBitMask = kNoAxis;
6099 
6100  if (fXaxis.CanExtend()) oldExtendBitMask |= kXaxis;
6101  if (extendBitMask & kXaxis) fXaxis.SetCanExtend(kTRUE);
6102  else fXaxis.SetCanExtend(kFALSE);
6103 
6104  if (GetDimension() > 1) {
6105  if (fYaxis.CanExtend()) oldExtendBitMask |= kYaxis;
6106  if (extendBitMask & kYaxis) fYaxis.SetCanExtend(kTRUE);
6107  else fYaxis.SetCanExtend(kFALSE);
6108  }
6109 
6110  if (GetDimension() > 2) {
6111  if (fZaxis.CanExtend()) oldExtendBitMask |= kZaxis;
6112  if (extendBitMask & kZaxis) fZaxis.SetCanExtend(kTRUE);
6113  else fZaxis.SetCanExtend(kFALSE);
6114  }
6115 
6116  return oldExtendBitMask;
6117 }
6118 
6119 ////////////////////////////////////////////////////////////////////////////////
6120 /// Static function to set the default buffer size for automatic histograms.
6121 /// When an histogram is created with one of its axis lower limit greater
6122 /// or equal to its upper limit, the function SetBuffer is automatically
6123 /// called with the default buffer size.
6124 
6125 void TH1::SetDefaultBufferSize(Int_t buffersize)
6126 {
6127  fgBufferSize = buffersize > 0 ? buffersize : 0;
6128 }
6129 
6130 ////////////////////////////////////////////////////////////////////////////////
6131 /// When this static function is called with `sumw2=kTRUE`, all new
6132 /// histograms will automatically activate the storage
6133 /// of the sum of squares of errors, ie TH1::Sumw2 is automatically called.
6134 
6135 void TH1::SetDefaultSumw2(Bool_t sumw2)
6136 {
6138 }
6139 
6140 ////////////////////////////////////////////////////////////////////////////////
6141 /// Change (i.e. set) the title
6142 ///
6143 /// if title is in the form `stringt;stringx;stringy;stringz`
6144 /// the histogram title is set to `stringt`, the x axis title to `stringx`,
6145 /// the y axis title to `stringy`, and the z axis title to `stringz`.
6146 ///
6147 /// To insert the character `;` in one of the titles, one should use `#;`
6148 /// or `#semicolon`.
6149 
6150 void TH1::SetTitle(const char *title)
6151 {
6152  fTitle = title;
6153  fTitle.ReplaceAll("#;",2,"#semicolon",10);
6154 
6155  // Decode fTitle. It may contain X, Y and Z titles
6156  TString str1 = fTitle, str2;
6157  Int_t isc = str1.Index(";");
6158  Int_t lns = str1.Length();
6159 
6160  if (isc >=0 ) {
6161  fTitle = str1(0,isc);
6162  str1 = str1(isc+1, lns);
6163  isc = str1.Index(";");
6164  if (isc >=0 ) {
6165  str2 = str1(0,isc);
6166  str2.ReplaceAll("#semicolon",10,";",1);
6167  fXaxis.SetTitle(str2.Data());
6168  lns = str1.Length();
6169  str1 = str1(isc+1, lns);
6170  isc = str1.Index(";");
6171  if (isc >=0 ) {
6172  str2 = str1(0,isc);
6173  str2.ReplaceAll("#semicolon",10,";",1);
6174  fYaxis.SetTitle(str2.Data());
6175  lns = str1.Length();
6176  str1 = str1(isc+1, lns);
6177  str1.ReplaceAll("#semicolon",10,";",1);
6178  fZaxis.SetTitle(str1.Data());
6179  } else {
6180  str1.ReplaceAll("#semicolon",10,";",1);
6181  fYaxis.SetTitle(str1.Data());
6182  }
6183  } else {
6184  str1.ReplaceAll("#semicolon",10,";",1);
6185  fXaxis.SetTitle(str1.Data());
6186  }
6187  }
6188 
6189  fTitle.ReplaceAll("#semicolon",10,";",1);
6190 
6191  if (gPad && TestBit(kMustCleanup)) gPad->Modified();
6192 }
6193 
6194 ////////////////////////////////////////////////////////////////////////////////
6195 /// Smooth array xx, translation of Hbook routine hsmoof.F
6196 /// based on algorithm 353QH twice presented by J. Friedman
6197 /// in Proc.of the 1974 CERN School of Computing, Norway, 11-24 August, 1974.
6198 
6199 void TH1::SmoothArray(Int_t nn, Double_t *xx, Int_t ntimes)
6200 {
6201  if (nn < 3 ) {
6202  ::Error("SmoothArray","Need at least 3 points for smoothing: n = %d",nn);
6203  return;
6204  }
6205 
6206  Int_t ii;
6207  Double_t hh[6] = {0,0,0,0,0,0};
6208 
6209  std::vector<double> yy(nn);
6210  std::vector<double> zz(nn);
6211  std::vector<double> rr(nn);
6212 
6213  for (Int_t pass=0;pass<ntimes;pass++) {
6214  // first copy original data into temp array
6215  std::copy(xx, xx+nn, zz.begin() );
6216 
6217  for (int noent = 0; noent < 2; ++noent) { // run algorithm two times
6218 
6219  // do 353 i.e. running median 3, 5, and 3 in a single loop
6220  for (int kk = 0; kk < 3; kk++) {
6221  std::copy(zz.begin(), zz.end(), yy.begin());
6222  int medianType = (kk != 1) ? 3 : 5;
6223  int ifirst = (kk != 1 ) ? 1 : 2;
6224  int ilast = (kk != 1 ) ? nn-1 : nn -2;
6225  //nn2 = nn - ik - 1;
6226  // do all elements beside the first and last point for median 3
6227  // and first two and last 2 for median 5
6228  for ( ii = ifirst; ii < ilast; ii++) {
6229  assert(ii - ifirst >= 0);
6230  for (int jj = 0; jj < medianType; jj++) {
6231  hh[jj] = yy[ii - ifirst + jj ];
6232  }
6233  zz[ii] = TMath::Median(medianType, hh);
6234  }
6235 
6236  if (kk == 0) { // first median 3
6237  // first point
6238  hh[0] = zz[1];
6239  hh[1] = zz[0];
6240  hh[2] = 3*zz[1] - 2*zz[2];
6241  zz[0] = TMath::Median(3, hh);
6242  // last point
6243  hh[0] = zz[nn - 2];
6244  hh[1] = zz[nn - 1];
6245  hh[2] = 3*zz[nn - 2] - 2*zz[nn - 3];
6246  zz[nn - 1] = TMath::Median(3, hh);
6247  }
6248 
6249  if (kk == 1) { // median 5
6250  for (ii = 0; ii < 3; ii++) {
6251  hh[ii] = yy[ii];
6252  }
6253  zz[1] = TMath::Median(3, hh);
6254  // last two points
6255  for (ii = 0; ii < 3; ii++) {
6256  hh[ii] = yy[nn - 3 + ii];
6257  }
6258  zz[nn - 2] = TMath::Median(3, hh);
6259  }
6260 
6261  }
6262 
6263  std::copy ( zz.begin(), zz.end(), yy.begin() );
6264 
6265  // quadratic interpolation for flat segments
6266  for (ii = 2; ii < (nn - 2); ii++) {
6267  if (zz[ii - 1] != zz[ii]) continue;
6268  if (zz[ii] != zz[ii + 1]) continue;
6269  hh[0] = zz[ii - 2] - zz[ii];
6270  hh[1] = zz[ii + 2] - zz[ii];
6271  if (hh[0] * hh[1] <= 0) continue;
6272  int jk = 1;
6273  if ( TMath::Abs(hh[1]) > TMath::Abs(hh[0]) ) jk = -1;
6274  yy[ii] = -0.5*zz[ii - 2*jk] + zz[ii]/0.75 + zz[ii + 2*jk] /6.;
6275  yy[ii + jk] = 0.5*(zz[ii + 2*jk] - zz[ii - 2*jk]) + zz[ii];
6276  }
6277 
6278  // running means
6279  //std::copy(zz.begin(), zz.end(), yy.begin());
6280  for (ii = 1; ii < nn - 1; ii++) {
6281  zz[ii] = 0.25*yy[ii - 1] + 0.5*yy[ii] + 0.25*yy[ii + 1];
6282  }
6283  zz[0] = yy[0];
6284  zz[nn - 1] = yy[nn - 1];
6285 
6286  if (noent == 0) {
6287 
6288  // save computed values
6289  std::copy(zz.begin(), zz.end(), rr.begin());
6290 
6291  // COMPUTE residuals
6292  for (ii = 0; ii < nn; ii++) {
6293  zz[ii] = xx[ii] - zz[ii];
6294  }
6295  }
6296 
6297  } // end loop on noent
6298 
6299 
6300  double xmin = TMath::MinElement(nn,xx);
6301  for (ii = 0; ii < nn; ii++) {
6302  if (xmin < 0) xx[ii] = rr[ii] + zz[ii];
6303  // make smoothing defined positive - not better using 0 ?
6304  else xx[ii] = TMath::Max((rr[ii] + zz[ii]),0.0 );
6305  }
6306  }
6307 }
6308 
6309 ////////////////////////////////////////////////////////////////////////////////
6310 /// Smooth bin contents of this histogram.
6311 /// if option contains "R" smoothing is applied only to the bins
6312 /// defined in the X axis range (default is to smooth all bins)
6313 /// Bin contents are replaced by their smooth values.
6314 /// Errors (if any) are not modified.
6315 /// the smoothing procedure is repeated ntimes (default=1)
6316 
6317 void TH1::Smooth(Int_t ntimes, Option_t *option)
6318 {
6319  if (fDimension != 1) {
6320  Error("Smooth","Smooth only supported for 1-d histograms");
6321  return;
6322  }
6323  Int_t nbins = fXaxis.GetNbins();
6324  if (nbins < 3) {
6325  Error("Smooth","Smooth only supported for histograms with >= 3 bins. Nbins = %d",nbins);
6326  return;
6327  }
6328 
6329  // delete buffer if it is there since it will become invalid
6330  if (fBuffer) BufferEmpty(1);
6331 
6332  Int_t firstbin = 1, lastbin = nbins;
6333  TString opt = option;
6334  opt.ToLower();
6335  if (opt.Contains("r")) {
6336  firstbin= fXaxis.GetFirst();
6337  lastbin = fXaxis.GetLast();
6338  }
6339  nbins = lastbin - firstbin + 1;
6340  Double_t *xx = new Double_t[nbins];
6341  Double_t nent = fEntries;
6342  Int_t i;
6343  for (i=0;i<nbins;i++) {
6344  xx[i] = RetrieveBinContent(i+firstbin);
6345  }
6346 
6347  TH1::SmoothArray(nbins,xx,ntimes);
6348 
6349  for (i=0;i<nbins;i++) {
6350  UpdateBinContent(i+firstbin,xx[i]);
6351  }
6352  fEntries = nent;
6353  delete [] xx;
6354 
6355  if (gPad) gPad->Modified();
6356 }
6357 
6358 ////////////////////////////////////////////////////////////////////////////////
6359 /// if flag=kTRUE, underflows and overflows are used by the Fill functions
6360 /// in the computation of statistics (mean value, StdDev).
6361 /// By default, underflows or overflows are not used.
6362 
6363 void TH1::StatOverflows(Bool_t flag)
6364 {
6366 }
6367 
6368 ////////////////////////////////////////////////////////////////////////////////
6369 /// Stream a class object.
6370 
6371 void TH1::Streamer(TBuffer &b)
6372 {
6373  if (b.IsReading()) {
6374  UInt_t R__s, R__c;
6375  Version_t R__v = b.ReadVersion(&R__s, &R__c);
6376  if (fDirectory) fDirectory->Remove(this);
6377  fDirectory = 0;
6378  if (R__v > 2) {
6379  b.ReadClassBuffer(TH1::Class(), this, R__v, R__s, R__c);
6380 
6382  fXaxis.SetParent(this);
6383  fYaxis.SetParent(this);
6384  fZaxis.SetParent(this);
6385  TIter next(fFunctions);
6386  TObject *obj;
6387  while ((obj=next())) {
6388  if (obj->InheritsFrom(TF1::Class())) ((TF1*)obj)->SetParent(this);
6389  }
6390  return;
6391  }
6392  //process old versions before automatic schema evolution
6393  TNamed::Streamer(b);
6394  TAttLine::Streamer(b);
6395  TAttFill::Streamer(b);
6396  TAttMarker::Streamer(b);
6397  b >> fNcells;
6398  fXaxis.Streamer(b);
6399  fYaxis.Streamer(b);
6400  fZaxis.Streamer(b);
6401  fXaxis.SetParent(this);
6402  fYaxis.SetParent(this);
6403  fZaxis.SetParent(this);
6404  b >> fBarOffset;
6405  b >> fBarWidth;
6406  b >> fEntries;
6407  b >> fTsumw;
6408  b >> fTsumw2;
6409  b >> fTsumwx;
6410  b >> fTsumwx2;
6411  if (R__v < 2) {
6412  Float_t maximum, minimum, norm;
6413  Float_t *contour=0;
6414  b >> maximum; fMaximum = maximum;
6415  b >> minimum; fMinimum = minimum;
6416  b >> norm; fNormFactor = norm;
6417  Int_t n = b.ReadArray(contour);
6418  fContour.Set(n);
6419  for (Int_t i=0;i<n;i++) fContour.fArray[i] = contour[i];
6420  delete [] contour;
6421  } else {
6422  b >> fMaximum;
6423  b >> fMinimum;
6424  b >> fNormFactor;
6425  fContour.Streamer(b);
6426  }
6427  fSumw2.Streamer(b);
6428  fOption.Streamer(b);
6429  fFunctions->Delete();
6430  fFunctions->Streamer(b);
6431  b.CheckByteCount(R__s, R__c, TH1::IsA());
6432 
6433  } else {
6434  b.WriteClassBuffer(TH1::Class(),this);
6435  }
6436 }
6437 
6438 ////////////////////////////////////////////////////////////////////////////////
6439 /// Print some global quantities for this histogram.
6440 /// \param[in] option
6441 /// - "base" is given, number of bins and ranges are also printed
6442 /// - "range" is given, bin contents and errors are also printed
6443 /// for all bins in the current range (default 1-->nbins)
6444 /// - "all" is given, bin contents and errors are also printed
6445 /// for all bins including under and overflows.
6446 
6447 void TH1::Print(Option_t *option) const
6448 {
6449  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
6450  printf( "TH1.Print Name = %s, Entries= %d, Total sum= %g\n",GetName(),Int_t(fEntries),GetSumOfWeights());
6451  TString opt = option;
6452  opt.ToLower();
6453  Int_t all;
6454  if (opt.Contains("all")) all = 0;
6455  else if (opt.Contains("range")) all = 1;
6456  else if (opt.Contains("base")) all = 2;
6457  else return;
6458 
6459  Int_t bin, binx, biny, binz;
6460  Int_t firstx=0,lastx=0,firsty=0,lasty=0,firstz=0,lastz=0;
6461  if (all == 0) {
6462  lastx = fXaxis.GetNbins()+1;
6463  if (fDimension > 1) lasty = fYaxis.GetNbins()+1;
6464  if (fDimension > 2) lastz = fZaxis.GetNbins()+1;
6465  } else {
6466  firstx = fXaxis.GetFirst(); lastx = fXaxis.GetLast();
6467  if (fDimension > 1) {firsty = fYaxis.GetFirst(); lasty = fYaxis.GetLast();}
6468  if (fDimension > 2) {firstz = fZaxis.GetFirst(); lastz = fZaxis.GetLast();}
6469  }
6470 
6471  if (all== 2) {
6472  printf(" Title = %s\n", GetTitle());
6473  printf(" NbinsX= %d, xmin= %g, xmax=%g", fXaxis.GetNbins(), fXaxis.GetXmin(), fXaxis.GetXmax());
6474  if( fDimension > 1) printf(", NbinsY= %d, ymin= %g, ymax=%g", fYaxis.GetNbins(), fYaxis.GetXmin(), fYaxis.GetXmax());
6475  if( fDimension > 2) printf(", NbinsZ= %d, zmin= %g, zmax=%g", fZaxis.GetNbins(), fZaxis.GetXmin(), fZaxis.GetXmax());
6476  printf("\n");
6477  return;
6478  }
6479 
6480  Double_t w,e;
6481  Double_t x,y,z;
6482  if (fDimension == 1) {
6483  for (binx=firstx;binx<=lastx;binx++) {
6484  x = fXaxis.GetBinCenter(binx);
6485  w = RetrieveBinContent(binx);
6486  e = GetBinError(binx);
6487  if(fSumw2.fN) printf(" fSumw[%d]=%g, x=%g, error=%g\n",binx,w,x,e);
6488  else printf(" fSumw[%d]=%g, x=%g\n",binx,w,x);
6489  }
6490  }
6491  if (fDimension == 2) {
6492  for (biny=firsty;biny<=lasty;biny++) {
6493  y = fYaxis.GetBinCenter(biny);
6494  for (binx=firstx;binx<=lastx;binx++) {
6495  bin = GetBin(binx,biny);
6496  x = fXaxis.GetBinCenter(binx);
6497  w = RetrieveBinContent(bin);
6498  e = GetBinError(bin);
6499  if(fSumw2.fN) printf(" fSumw[%d][%d]=%g, x=%g, y=%g, error=%g\n",binx,biny,w,x,y,e);
6500  else printf(" fSumw[%d][%d]=%g, x=%g, y=%g\n",binx,biny,w,x,y);
6501  }
6502  }
6503  }
6504  if (fDimension == 3) {
6505  for (binz=firstz;binz<=lastz;binz++) {
6506  z = fZaxis.GetBinCenter(binz);
6507  for (biny=firsty;biny<=lasty;biny++) {
6508  y = fYaxis.GetBinCenter(biny);
6509  for (binx=firstx;binx<=lastx;binx++) {
6510  bin = GetBin(binx,biny,binz);
6511  x = fXaxis.GetBinCenter(binx);
6512  w = RetrieveBinContent(bin);
6513  e = GetBinError(bin);
6514  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);
6515  else printf(" fSumw[%d][%d][%d]=%g, x=%g, y=%g, z=%g\n",binx,biny,binz,w,x,y,z);
6516  }
6517  }
6518  }
6519  }
6520 }
6521 
6522 ////////////////////////////////////////////////////////////////////////////////
6523 /// Using the current bin info, recompute the arrays for contents and errors
6524 
6525 void TH1::Rebuild(Option_t *)
6526 {
6528  if (fSumw2.fN) {
6529  fSumw2.Set(fNcells);
6530  }
6531 }
6532 
6533 ////////////////////////////////////////////////////////////////////////////////
6534 /// Reset this histogram: contents, errors, etc.
6535 /// \param[in] option
6536 /// - "ICE" is specified, resets only Integral, Contents and Errors.
6537 /// - "ICES" is specified, resets only Integral, Contents , Errors and Statistics
6538 /// This option is used
6539 /// - "M" is specified, resets also Minimum and Maximum
6540 
6541 void TH1::Reset(Option_t *option)
6542 {
6543  // The option "ICE" is used when extending the histogram (in ExtendAxis, LabelInflate, etc..)
6544  // The option "ICES is used in combination with the buffer (see BufferEmpty and BufferFill)
6545 
6546  TString opt = option;
6547  opt.ToUpper();
6548  fSumw2.Reset();
6549  if (fIntegral) {delete [] fIntegral; fIntegral = 0;}
6550 
6551  if (opt.Contains("M")) {
6552  SetMinimum();
6553  SetMaximum();
6554  }
6555 
6556  if (opt.Contains("ICE") && !opt.Contains("S")) return;
6557 
6558  // Setting fBuffer[0] = 0 is like resetting the buffer but not deleting it
6559  // But what is the sense of calling BufferEmpty() ? For making the axes ?
6560  // BufferEmpty will update contents that later will be
6561  // reset in calling TH1D::Reset. For this we need to reset the stats afterwards
6562  // It may be needed for computing the axis limits....
6563  if (fBuffer) {BufferEmpty(); fBuffer[0] = 0;}
6564 
6565  // need to reset also the statistics
6566  // (needs to be done after calling BufferEmpty() )
6567  fTsumw = 0;
6568  fTsumw2 = 0;
6569  fTsumwx = 0;
6570  fTsumwx2 = 0;
6571  fEntries = 0;
6572 
6573  if (opt == "ICES") return;
6574 
6575 
6576  TObject *stats = fFunctions->FindObject("stats");
6577  fFunctions->Remove(stats);
6578  //special logic to support the case where the same object is
6579  //added multiple times in fFunctions.
6580  //This case happens when the same object is added with different
6581  //drawing modes
6582  TObject *obj;
6583  while ((obj = fFunctions->First())) {
6584  while(fFunctions->Remove(obj)) { }
6585  delete obj;
6586  }
6587  if(stats) fFunctions->Add(stats);
6588  fContour.Set(0);
6589 }
6590 
6591 ////////////////////////////////////////////////////////////////////////////////
6592 /// Save primitive as a C++ statement(s) on output stream out
6593 
6594 void TH1::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/)
6595 {
6596  // empty the buffer before if it exists
6597  if (fBuffer) BufferEmpty();
6598 
6599  Bool_t nonEqiX = kFALSE;
6600  Bool_t nonEqiY = kFALSE;
6601  Bool_t nonEqiZ = kFALSE;
6602  Int_t i;
6603  static Int_t nxaxis = 0;
6604  static Int_t nyaxis = 0;
6605  static Int_t nzaxis = 0;
6606  TString sxaxis="xAxis",syaxis="yAxis",szaxis="zAxis";
6607 
6608  // Check if the histogram has equidistant X bins or not. If not, we
6609  // create an array holding the bins.
6610  if (GetXaxis()->GetXbins()->fN && GetXaxis()->GetXbins()->fArray) {
6611  nonEqiX = kTRUE;
6612  nxaxis++;
6613  sxaxis += nxaxis;
6614  out << " Double_t "<<sxaxis<<"[" << GetXaxis()->GetXbins()->fN
6615  << "] = {";
6616  for (i = 0; i < GetXaxis()->GetXbins()->fN; i++) {
6617  if (i != 0) out << ", ";
6618  out << GetXaxis()->GetXbins()->fArray[i];
6619  }
6620  out << "}; " << std::endl;
6621  }
6622  // If the histogram is 2 or 3 dimensional, check if the histogram
6623  // has equidistant Y bins or not. If not, we create an array
6624  // holding the bins.
6625  if (fDimension > 1 && GetYaxis()->GetXbins()->fN &&
6626  GetYaxis()->GetXbins()->fArray) {
6627  nonEqiY = kTRUE;
6628  nyaxis++;
6629  syaxis += nyaxis;
6630  out << " Double_t "<<syaxis<<"[" << GetYaxis()->GetXbins()->fN
6631  << "] = {";
6632  for (i = 0; i < GetYaxis()->GetXbins()->fN; i++) {
6633  if (i != 0) out << ", ";
6634  out << GetYaxis()->GetXbins()->fArray[i];
6635  }
6636  out << "}; " << std::endl;
6637  }
6638  // IF the histogram is 3 dimensional, check if the histogram
6639  // has equidistant Z bins or not. If not, we create an array
6640  // holding the bins.
6641  if (fDimension > 2 && GetZaxis()->GetXbins()->fN &&
6642  GetZaxis()->GetXbins()->fArray) {
6643  nonEqiZ = kTRUE;
6644  nzaxis++;
6645  szaxis += nzaxis;
6646  out << " Double_t "<<szaxis<<"[" << GetZaxis()->GetXbins()->fN
6647  << "] = {";
6648  for (i = 0; i < GetZaxis()->GetXbins()->fN; i++) {
6649  if (i != 0) out << ", ";
6650  out << GetZaxis()->GetXbins()->fArray[i];
6651  }
6652  out << "}; " << std::endl;
6653  }
6654 
6655  char quote = '"';
6656  out <<" "<<std::endl;
6657  out <<" "<< ClassName() <<" *";
6658 
6659  // Histogram pointer has by default the histogram name with an incremental suffix.
6660  // If the histogram belongs to a graph or a stack the suffix is not added because
6661  // the graph and stack objects are not aware of this new name. Same thing if
6662  // the histogram is drawn with the option COLZ because the TPaletteAxis drawn
6663  // when this option is selected, does not know this new name either.
6664  TString opt = option;
6665  opt.ToLower();
6666  static Int_t hcounter = 0;
6667  TString histName = GetName();
6668  if ( !histName.Contains("Graph")
6669  && !histName.Contains("_stack_")
6670  && !opt.Contains("colz")) {
6671  hcounter++;
6672  histName += "__";
6673  histName += hcounter;
6674  }
6675  histName = gInterpreter-> MapCppName(histName);
6676  const char *hname = histName.Data();
6677  if (!strlen(hname)) hname = "unnamed";
6678  TString savedName = GetName();
6679  this->SetName(hname);
6680  TString t(GetTitle());
6681  t.ReplaceAll("\\","\\\\");
6682  t.ReplaceAll("\"","\\\"");
6683  out << hname << " = new " << ClassName() << "(" << quote
6684  << hname << quote << "," << quote<< t.Data() << quote
6685  << "," << GetXaxis()->GetNbins();
6686  if (nonEqiX)
6687  out << ", "<<sxaxis;
6688  else
6689  out << "," << GetXaxis()->GetXmin()
6690  << "," << GetXaxis()->GetXmax();
6691  if (fDimension > 1) {
6692  out << "," << GetYaxis()->GetNbins();
6693  if (nonEqiY)
6694  out << ", "<<syaxis;
6695  else
6696  out << "," << GetYaxis()->GetXmin()
6697  << "," << GetYaxis()->GetXmax();
6698  }
6699  if (fDimension > 2) {
6700  out << "," << GetZaxis()->GetNbins();
6701  if (nonEqiZ)
6702  out << ", "<<szaxis;
6703  else
6704  out << "," << GetZaxis()->GetXmin()
6705  << "," << GetZaxis()->GetXmax();
6706  }
6707  out << ");" << std::endl;
6708 
6709  // save bin contents
6710  Int_t bin;
6711  for (bin=0;bin<fNcells;bin++) {
6712  Double_t bc = RetrieveBinContent(bin);
6713  if (bc) {
6714  out<<" "<<hname<<"->SetBinContent("<<bin<<","<<bc<<");"<<std::endl;
6715  }
6716  }
6717 
6718  // save bin errors
6719  if (fSumw2.fN) {
6720  for (bin=0;bin<fNcells;bin++) {
6721  Double_t be = GetBinError(bin);
6722  if (be) {
6723  out<<" "<<hname<<"->SetBinError("<<bin<<","<<be<<");"<<std::endl;
6724  }
6725  }
6726  }
6727 
6728  TH1::SavePrimitiveHelp(out, hname, option);
6729  this->SetName(savedName.Data());
6730 }
6731 
6732 ////////////////////////////////////////////////////////////////////////////////
6733 /// Helper function for the SavePrimitive functions from TH1
6734 /// or classes derived from TH1, eg TProfile, TProfile2D.
6735 
6736 void TH1::SavePrimitiveHelp(std::ostream &out, const char *hname, Option_t *option /*= ""*/)
6737 {
6738  char quote = '"';
6739  if (TMath::Abs(GetBarOffset()) > 1e-5) {
6740  out<<" "<<hname<<"->SetBarOffset("<<GetBarOffset()<<");"<<std::endl;
6741  }
6742  if (TMath::Abs(GetBarWidth()-1) > 1e-5) {
6743  out<<" "<<hname<<"->SetBarWidth("<<GetBarWidth()<<");"<<std::endl;
6744  }
6745  if (fMinimum != -1111) {
6746  out<<" "<<hname<<"->SetMinimum("<<fMinimum<<");"<<std::endl;
6747  }
6748  if (fMaximum != -1111) {
6749  out<<" "<<hname<<"->SetMaximum("<<fMaximum<<");"<<std::endl;
6750  }
6751  if (fNormFactor != 0) {
6752  out<<" "<<hname<<"->SetNormFactor("<<fNormFactor<<");"<<std::endl;
6753  }
6754  if (fEntries != 0) {
6755  out<<" "<<hname<<"->SetEntries("<<fEntries<<");"<<std::endl;
6756  }
6757  if (fDirectory == 0) {
6758  out<<" "<<hname<<"->SetDirectory(0);"<<std::endl;
6759  }
6760  if (TestBit(kNoStats)) {
6761  out<<" "<<hname<<"->SetStats(0);"<<std::endl;
6762  }
6763  if (fOption.Length() != 0) {
6764  out<<" "<<hname<<"->SetOption("<<quote<<fOption.Data()<<quote<<");"<<std::endl;
6765  }
6766 
6767  // save contour levels
6768  Int_t ncontours = GetContour();
6769  if (ncontours > 0) {
6770  out<<" "<<hname<<"->SetContour("<<ncontours<<");"<<std::endl;
6771  Double_t zlevel;
6772  for (Int_t bin=0;bin<ncontours;bin++) {
6773  if (gPad->GetLogz()) {
6774  zlevel = TMath::Power(10,GetContourLevel(bin));
6775  } else {
6776  zlevel = GetContourLevel(bin);
6777  }
6778  out<<" "<<hname<<"->SetContourLevel("<<bin<<","<<zlevel<<");"<<std::endl;
6779  }
6780  }
6781 
6782  // save list of functions
6784  TObject *obj;
6785  static Int_t funcNumber = 0;
6786  while (lnk) {
6787  obj = lnk->GetObject();
6788  obj->SavePrimitive(out,Form("nodraw #%d\n",++funcNumber));
6789  if (obj->InheritsFrom(TF1::Class())) {
6790  TString fname;
6791  fname.Form("%s%d",obj->GetName(),funcNumber);
6792  out << " " << fname << "->SetParent(" << hname << ");\n";
6793  out<<" "<<hname<<"->GetListOfFunctions()->Add("
6794  << fname <<");"<<std::endl;
6795  } else if (obj->InheritsFrom("TPaveStats")) {
6796  out<<" "<<hname<<"->GetListOfFunctions()->Add(ptstats);"<<std::endl;
6797  out<<" ptstats->SetParent("<<hname<<");"<<std::endl;
6798  } else {
6799  out<<" "<<hname<<"->GetListOfFunctions()->Add("
6800  <<obj->GetName()
6801  <<","<<quote<<lnk->GetOption()<<quote<<");"<<std::endl;
6802  }
6803  lnk = (TObjOptLink*)lnk->Next();
6804  }
6805 
6806  // save attributes
6807  SaveFillAttributes(out,hname,0,1001);
6808  SaveLineAttributes(out,hname,1,1,1);
6809  SaveMarkerAttributes(out,hname,1,1,1);
6810  fXaxis.SaveAttributes(out,hname,"->GetXaxis()");
6811  fYaxis.SaveAttributes(out,hname,"->GetYaxis()");
6812  fZaxis.SaveAttributes(out,hname,"->GetZaxis()");
6813  TString opt = option;
6814  opt.ToLower();
6815  if (!opt.Contains("nodraw")) {
6816  out<<" "<<hname<<"->Draw("
6817  <<quote<<option<<quote<<");"<<std::endl;
6818  }
6819 }
6820 
6821 ////////////////////////////////////////////////////////////////////////////////
6822 /// Copy current attributes from/to current style
6823 
6824 void TH1::UseCurrentStyle()
6825 {
6826  if (!gStyle) return;
6827  if (gStyle->IsReading()) {
6828  fXaxis.ResetAttAxis("X");
6829  fYaxis.ResetAttAxis("Y");
6830  fZaxis.ResetAttAxis("Z");
6841  Int_t dostat = gStyle->GetOptStat();
6842  if (gStyle->GetOptFit() && !dostat) dostat = 1000000001;
6843  SetStats(dostat);
6844  } else {
6856  }
6857  TIter next(GetListOfFunctions());
6858  TObject *obj;
6859 
6860  while ((obj = next())) {
6861  obj->UseCurrentStyle();
6862  }
6863 }
6864 
6865 ////////////////////////////////////////////////////////////////////////////////
6866 /// For axis = 1,2 or 3 returns the mean value of the histogram along
6867 /// X,Y or Z axis.
6868 ///
6869 /// For axis = 11, 12, 13 returns the standard error of the mean value
6870 /// of the histogram along X, Y or Z axis
6871 ///
6872 /// Note that the mean value/StdDev is computed using the bins in the currently
6873 /// defined range (see TAxis::SetRange). By default the range includes
6874 /// all bins from 1 to nbins included, excluding underflows and overflows.
6875 /// To force the underflows and overflows in the computation, one must
6876 /// call the static function TH1::StatOverflows(kTRUE) before filling
6877 /// the histogram.
6878 ///
6879 /// Return mean value of this histogram along the X axis.
6880 ///
6881 /// Note that the mean value/StdDev is computed using the bins in the currently
6882 /// defined range (see TAxis::SetRange). By default the range includes
6883 /// all bins from 1 to nbins included, excluding underflows and overflows.
6884 /// To force the underflows and overflows in the computation, one must
6885 /// call the static function TH1::StatOverflows(kTRUE) before filling
6886 /// the histogram.
6887 
6888 Double_t TH1::GetMean(Int_t axis) const
6889 {
6890  if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
6891  Double_t stats[kNstat];
6892  for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
6893  GetStats(stats);
6894  if (stats[0] == 0) return 0;
6895  if (axis<4){
6896  Int_t ax[3] = {2,4,7};
6897  return stats[ax[axis-1]]/stats[0];
6898  } else {
6899  // mean error = StdDev / sqrt( Neff )
6900  Double_t stddev = GetStdDev(axis-10);
6901  Double_t neff = GetEffectiveEntries();
6902  return ( neff > 0 ? stddev/TMath::Sqrt(neff) : 0. );
6903  }
6904 }
6905 
6906 ////////////////////////////////////////////////////////////////////////////////
6907 /// Return standard error of mean of this histogram along the X axis.
6908 ///
6909 /// Note that the mean value/StdDev is computed using the bins in the currently
6910 /// defined range (see TAxis::SetRange). By default the range includes
6911 /// all bins from 1 to nbins included, excluding underflows and overflows.
6912 /// To force the underflows and overflows in the computation, one must
6913 /// call the static function TH1::StatOverflows(kTRUE) before filling
6914 /// the histogram.
6915 ///
6916 /// Also note, that although the definition of standard error doesn't include the
6917 /// assumption of normality, many uses of this feature implicitly assume it.
6918 
6919 Double_t TH1::GetMeanError(Int_t axis) const
6920 {
6921  return GetMean(axis+10);
6922 }
6923 
6924 ////////////////////////////////////////////////////////////////////////////////
6925 /// Returns the Standard Deviation (Sigma).
6926 /// The Sigma estimate is computed as
6927 /// \f[
6928 /// \sqrt{\frac{1}{N}(\sum(x_i-x_{mean})^2)}
6929 /// \f]
6930 /// For axis = 1,2 or 3 returns the Sigma value of the histogram along
6931 /// X, Y or Z axis
6932 /// For axis = 11, 12 or 13 returns the error of StdDev estimation along
6933 /// X, Y or Z axis for Normal distribution
6934 ///
6935 /// Note that the mean value/sigma is computed using the bins in the currently
6936 /// defined range (see TAxis::SetRange). By default the range includes
6937 /// all bins from 1 to nbins included, excluding underflows and overflows.
6938 /// To force the underflows and overflows in the computation, one must
6939 /// call the static function TH1::StatOverflows(kTRUE) before filling
6940 /// the histogram.
6941 
6942 Double_t TH1::GetStdDev(Int_t axis) const
6943 {
6944  if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
6945 
6946  Double_t x, stddev2, stats[kNstat];
6947  for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
6948  GetStats(stats);
6949  if (stats[0] == 0) return 0;
6950  Int_t ax[3] = {2,4,7};
6951  Int_t axm = ax[axis%10 - 1];
6952  x = stats[axm]/stats[0];
6953  stddev2 = TMath::Abs(stats[axm+1]/stats[0] -x*x);
6954  if (axis<10)
6955  return TMath::Sqrt(stddev2);
6956  else {
6957  // The right formula for StdDev error depends on 4th momentum (see Kendall-Stuart Vol 1 pag 243)
6958  // formula valid for only gaussian distribution ( 4-th momentum = 3 * sigma^4 )
6959  Double_t neff = GetEffectiveEntries();
6960  return ( neff > 0 ? TMath::Sqrt(stddev2/(2*neff) ) : 0. );
6961  }
6962 }
6963 
6964 ////////////////////////////////////////////////////////////////////////////////
6965 /// Return error of standard deviation estimation for Normal distribution
6966 ///
6967 /// Note that the mean value/StdDev is computed using the bins in the currently
6968 /// defined range (see TAxis::SetRange). By default the range includes
6969 /// all bins from 1 to nbins included, excluding underflows and overflows.
6970 /// To force the underflows and overflows in the computation, one must
6971 /// call the static function TH1::StatOverflows(kTRUE) before filling
6972 /// the histogram.
6973 ///
6974 /// Value returned is standard deviation of sample standard deviation.
6975 /// Note that it is an approximated value which is valid only in the case that the
6976 /// original data distribution is Normal. The correct one would require
6977 /// the 4-th momentum value, which cannot be accurately estimated from an histogram since
6978 /// the x-information for all entries is not kept.
6979 
6981 {
6982  return GetStdDev(axis+10);
6983 }
6984 
6985 ////////////////////////////////////////////////////////////////////////////////
6986 /// - For axis = 1, 2 or 3 returns skewness of the histogram along x, y or z axis.
6987 /// - For axis = 11, 12 or 13 returns the approximate standard error of skewness
6988 /// of the histogram along x, y or z axis
6989 ///
6990 ///Note, that since third and fourth moment are not calculated
6991 ///at the fill time, skewness and its standard error are computed bin by bin
6992 
6993 Double_t TH1::GetSkewness(Int_t axis) const
6994 {
6996  if (axis > 0 && axis <= 3){
6997 
6998  Double_t mean = GetMean(axis);
6999  Double_t stddev = GetStdDev(axis);
7000  Double_t stddev3 = stddev*stddev*stddev;
7001 
7002  Int_t firstBinX = fXaxis.GetFirst();
7003  Int_t lastBinX = fXaxis.GetLast();
7004  Int_t firstBinY = fYaxis.GetFirst();
7005  Int_t lastBinY = fYaxis.GetLast();
7006  Int_t firstBinZ = fZaxis.GetFirst();
7007  Int_t lastBinZ = fZaxis.GetLast();
7008  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7009  if (fgStatOverflows) {
7010  if ( !fXaxis.TestBit(TAxis::kAxisRange) ) {
7011  if (firstBinX == 1) firstBinX = 0;
7012  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7013  }
7014  if ( !fYaxis.TestBit(TAxis::kAxisRange) ) {
7015  if (firstBinY == 1) firstBinY = 0;
7016  if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
7017  }
7018  if ( !fZaxis.TestBit(TAxis::kAxisRange) ) {
7019  if (firstBinZ == 1) firstBinZ = 0;
7020  if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
7021  }
7022  }
7023 
7024  Double_t x = 0;
7025  Double_t sum=0;
7026  Double_t np=0;
7027  for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
7028  for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
7029  for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
7030  if (axis==1 ) x = fXaxis.GetBinCenter(binx);
7031  else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
7032  else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
7033  Double_t w = GetBinContent(binx,biny,binz);
7034  np+=w;
7035  sum+=w*(x-mean)*(x-mean)*(x-mean);
7036  }
7037  }
7038  }
7039  sum/=np*stddev3;
7040  return sum;
7041  }
7042  else if (axis > 10 && axis <= 13) {
7043  //compute standard error of skewness
7044  // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
7045  Double_t neff = GetEffectiveEntries();
7046  return ( neff > 0 ? TMath::Sqrt(6./neff ) : 0. );
7047  }
7048  else {
7049  Error("GetSkewness", "illegal value of parameter");
7050  return 0;
7051  }
7052 }
7053 
7054 ////////////////////////////////////////////////////////////////////////////////
7055 /// - For axis =1, 2 or 3 returns kurtosis of the histogram along x, y or z axis.
7056 /// Kurtosis(gaussian(0, 1)) = 0.
7057 /// - For axis =11, 12 or 13 returns the approximate standard error of kurtosis
7058 /// of the histogram along x, y or z axis
7059 ////
7060 /// Note, that since third and fourth moment are not calculated
7061 /// at the fill time, kurtosis and its standard error are computed bin by bin
7062 
7063 Double_t TH1::GetKurtosis(Int_t axis) const
7064 {
7065  if (axis > 0 && axis <= 3){
7066 
7067  Double_t mean = GetMean(axis);
7068  Double_t stddev = GetStdDev(axis);
7069  Double_t stddev4 = stddev*stddev*stddev*stddev;
7070 
7071  Int_t firstBinX = fXaxis.GetFirst();
7072  Int_t lastBinX = fXaxis.GetLast();
7073  Int_t firstBinY = fYaxis.GetFirst();
7074  Int_t lastBinY = fYaxis.GetLast();
7075  Int_t firstBinZ = fZaxis.GetFirst();
7076  Int_t lastBinZ = fZaxis.GetLast();
7077  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7078  if (fgStatOverflows) {
7079  if ( !fXaxis.TestBit(TAxis::kAxisRange) ) {
7080  if (firstBinX == 1) firstBinX = 0;
7081  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7082  }
7083  if ( !fYaxis.TestBit(TAxis::kAxisRange) ) {
7084  if (firstBinY == 1) firstBinY = 0;
7085  if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
7086  }
7087  if ( !fZaxis.TestBit(TAxis::kAxisRange) ) {
7088  if (firstBinZ == 1) firstBinZ = 0;
7089  if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
7090  }
7091  }
7092 
7093  Double_t x = 0;
7094  Double_t sum=0;
7095  Double_t np=0;
7096  for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
7097  for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
7098  for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
7099  if (axis==1 ) x = fXaxis.GetBinCenter(binx);
7100  else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
7101  else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
7102  Double_t w = GetBinContent(binx,biny,binz);
7103  np+=w;
7104  sum+=w*(x-mean)*(x-mean)*(x-mean)*(x-mean);
7105  }
7106  }
7107  }
7108  sum/=(np*stddev4);
7109  return sum-3;
7110 
7111  } else if (axis > 10 && axis <= 13) {
7112  //compute standard error of skewness
7113  // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
7114  Double_t neff = GetEffectiveEntries();
7115  return ( neff > 0 ? TMath::Sqrt(24./neff ) : 0. );
7116  }
7117  else {
7118  Error("GetKurtosis", "illegal value of parameter");
7119  return 0;
7120  }
7121 }
7122 
7123 ////////////////////////////////////////////////////////////////////////////////
7124 /// fill the array stats from the contents of this histogram
7125 /// The array stats must be correctly dimensioned in the calling program.
7126 ///
7127 /// ~~~ {.cpp}
7128 /// stats[0] = sumw
7129 /// stats[1] = sumw2
7130 /// stats[2] = sumwx
7131 /// stats[3] = sumwx2
7132 /// ~~~
7133 ///
7134 /// If no axis-subrange is specified (via TAxis::SetRange), the array stats
7135 /// is simply a copy of the statistics quantities computed at filling time.
7136 /// If a sub-range is specified, the function recomputes these quantities
7137 /// from the bin contents in the current axis range.
7138 ///
7139 /// Note that the mean value/StdDev is computed using the bins in the currently
7140 /// defined range (see TAxis::SetRange). By default the range includes
7141 /// all bins from 1 to nbins included, excluding underflows and overflows.
7142 /// To force the underflows and overflows in the computation, one must
7143 /// call the static function TH1::StatOverflows(kTRUE) before filling
7144 /// the histogram.
7145 
7146 void TH1::GetStats(Double_t *stats) const
7147 {
7148  if (fBuffer) ((TH1*)this)->BufferEmpty();
7149 
7150  // Loop on bins (possibly including underflows/overflows)
7151  Int_t bin, binx;
7152  Double_t w,err;
7153  Double_t x;
7154  // case of labels with extension of axis range
7155  // statistics in x does not make any sense - set to zero
7156  if ((const_cast<TAxis&>(fXaxis)).GetLabels() && CanExtendAllAxes() ) {
7157  stats[0] = fTsumw;
7158  stats[1] = fTsumw2;
7159  stats[2] = 0;
7160  stats[3] = 0;
7161  }
7162  else if ((fTsumw == 0 && fEntries > 0) || fXaxis.TestBit(TAxis::kAxisRange)) {
7163  for (bin=0;bin<4;bin++) stats[bin] = 0;
7164 
7165  Int_t firstBinX = fXaxis.GetFirst();
7166  Int_t lastBinX = fXaxis.GetLast();
7167  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7169  if (firstBinX == 1) firstBinX = 0;
7170  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7171  }
7172  for (binx = firstBinX; binx <= lastBinX; binx++) {
7173  x = fXaxis.GetBinCenter(binx);
7174  //w = TMath::Abs(RetrieveBinContent(binx));
7175  // not sure what to do here if w < 0
7176  w = RetrieveBinContent(binx);
7177  err = TMath::Abs(GetBinError(binx));
7178  stats[0] += w;
7179  stats[1] += err*err;
7180  stats[2] += w*x;
7181  stats[3] += w*x*x;
7182  }
7183  // if (stats[0] < 0) {
7184  // // in case total is negative do something ??
7185  // stats[0] = 0;
7186  // }
7187  } else {
7188  stats[0] = fTsumw;
7189  stats[1] = fTsumw2;
7190  stats[2] = fTsumwx;
7191  stats[3] = fTsumwx2;
7192  }
7193 }
7194 
7195 ////////////////////////////////////////////////////////////////////////////////
7196 /// Replace current statistics with the values in array stats
7197 
7198 void TH1::PutStats(Double_t *stats)
7199 {
7200  fTsumw = stats[0];
7201  fTsumw2 = stats[1];
7202  fTsumwx = stats[2];
7203  fTsumwx2 = stats[3];
7204 }
7205 
7206 ////////////////////////////////////////////////////////////////////////////////
7207 /// Reset the statistics including the number of entries
7208 /// and replace with values calculates from bin content
7209 ///
7210 /// The number of entries is set to the total bin content or (in case of weighted histogram)
7211 /// to number of effective entries
7212 
7213 void TH1::ResetStats()
7214 {
7215  Double_t stats[kNstat] = {0};
7216  fTsumw = 0;
7217  fEntries = 1; // to force re-calculation of the statistics in TH1::GetStats
7218  GetStats(stats);
7219  PutStats(stats);
7221  // use effective entries for weighted histograms: (sum_w) ^2 / sum_w2
7222  if (fSumw2.fN > 0 && fTsumw > 0 && stats[1] > 0 ) fEntries = stats[0]*stats[0]/ stats[1];
7223 }
7224 
7225 ////////////////////////////////////////////////////////////////////////////////
7226 /// Return the sum of weights excluding under/overflows.
7227 
7229 {
7230  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
7231 
7232  Int_t bin,binx,biny,binz;
7233  Double_t sum =0;
7234  for(binz=1; binz<=fZaxis.GetNbins(); binz++) {
7235  for(biny=1; biny<=fYaxis.GetNbins(); biny++) {
7236  for(binx=1; binx<=fXaxis.GetNbins(); binx++) {
7237  bin = GetBin(binx,biny,binz);
7238  sum += RetrieveBinContent(bin);
7239  }
7240  }
7241  }
7242  return sum;
7243 }
7244 
7245 ////////////////////////////////////////////////////////////////////////////////
7246 ///Return integral of bin contents. Only bins in the bins range are considered.
7247 ///
7248 /// By default the integral is computed as the sum of bin contents in the range.
7249 /// if option "width" is specified, the integral is the sum of
7250 /// the bin contents multiplied by the bin width in x.
7251 
7252 Double_t TH1::Integral(Option_t *option) const
7253 {
7254  return Integral(fXaxis.GetFirst(),fXaxis.GetLast(),option);
7255 }
7256 
7257 ////////////////////////////////////////////////////////////////////////////////
7258 /// Return integral of bin contents in range [binx1,binx2].
7259 ///
7260 /// By default the integral is computed as the sum of bin contents in the range.
7261 /// if option "width" is specified, the integral is the sum of
7262 /// the bin contents multiplied by the bin width in x.
7263 
7264 Double_t TH1::Integral(Int_t binx1, Int_t binx2, Option_t *option) const
7265 {
7266  double err = 0;
7267  return DoIntegral(binx1,binx2,0,-1,0,-1,err,option);
7268 }
7269 
7270 ////////////////////////////////////////////////////////////////////////////////
7271 /// Return integral of bin contents in range [binx1,binx2] and its error.
7272 ///
7273 /// By default the integral is computed as the sum of bin contents in the range.
7274 /// if option "width" is specified, the integral is the sum of
7275 /// the bin contents multiplied by the bin width in x.
7276 /// the error is computed using error propagation from the bin errors assuming that
7277 /// all the bins are uncorrelated
7278 
7279 Double_t TH1::IntegralAndError(Int_t binx1, Int_t binx2, Double_t & error, Option_t *option) const
7280 {
7281  return DoIntegral(binx1,binx2,0,-1,0,-1,error,option,kTRUE);
7282 }
7283 
7284 ////////////////////////////////////////////////////////////////////////////////
7285 /// Internal function compute integral and optionally the error between the limits
7286 /// specified by the bin number values working for all histograms (1D, 2D and 3D)
7287 
7288 Double_t TH1::DoIntegral(Int_t binx1, Int_t binx2, Int_t biny1, Int_t biny2, Int_t binz1, Int_t binz2, Double_t & error ,
7289  Option_t *option, Bool_t doError) const
7291  if (fBuffer) ((TH1*)this)->BufferEmpty();
7292 
7293  Int_t nx = GetNbinsX() + 2;
7294  if (binx1 < 0) binx1 = 0;
7295  if (binx2 >= nx || binx2 < binx1) binx2 = nx - 1;
7296 
7297  if (GetDimension() > 1) {
7298  Int_t ny = GetNbinsY() + 2;
7299  if (biny1 < 0) biny1 = 0;
7300  if (biny2 >= ny || biny2 < biny1) biny2 = ny - 1;
7301  } else {
7302  biny1 = 0; biny2 = 0;
7303  }
7304 
7305  if (GetDimension() > 2) {
7306  Int_t nz = GetNbinsZ() + 2;
7307  if (binz1 < 0) binz1 = 0;
7308  if (binz2 >= nz || binz2 < binz1) binz2 = nz - 1;
7309  } else {
7310  binz1 = 0; binz2 = 0;
7311  }
7312 
7313  // - Loop on bins in specified range
7314  TString opt = option;
7315  opt.ToLower();
7316  Bool_t width = kFALSE;
7317  if (opt.Contains("width")) width = kTRUE;
7318 
7319 
7320  Double_t dx = 1., dy = .1, dz =.1;
7321  Double_t integral = 0;
7322  Double_t igerr2 = 0;
7323  for (Int_t binx = binx1; binx <= binx2; ++binx) {
7324  if (width) dx = fXaxis.GetBinWidth(binx);
7325  for (Int_t biny = biny1; biny <= biny2; ++biny) {
7326  if (width) dy = fYaxis.GetBinWidth(biny);
7327  for (Int_t binz = binz1; binz <= binz2; ++binz) {
7328  Int_t bin = GetBin(binx, biny, binz);
7329  Double_t dv = 0.0;
7330  if (width) {
7331  dz = fZaxis.GetBinWidth(binz);
7332  dv = dx * dy * dz;
7333  integral += RetrieveBinContent(bin) * dv;
7334  } else {
7335  integral += RetrieveBinContent(bin);
7336  }
7337  if (doError) {
7338  if (width) igerr2 += GetBinErrorSqUnchecked(bin) * dv * dv;
7339  else igerr2 += GetBinErrorSqUnchecked(bin);
7340  }
7341  }
7342  }
7343  }
7344 
7345  if (doError) error = TMath::Sqrt(igerr2);
7346  return integral;
7347 }
7348 
7349 ////////////////////////////////////////////////////////////////////////////////
7350 /// Statistical test of compatibility in shape between
7351 /// this histogram and h2, using the Anderson-Darling 2 sample test.
7352 ///
7353 /// The AD 2 sample test formula are derived from the paper
7354 /// F.W Scholz, M.A. Stephens "k-Sample Anderson-Darling Test".
7355 ///
7356 /// The test is implemented in root in the ROOT::Math::GoFTest class
7357 /// It is the same formula ( (6) in the paper), and also shown in
7358 /// [this preprint](http://arxiv.org/pdf/0804.0380v1.pdf)
7359 ///
7360 /// Binned data are considered as un-binned data
7361 /// with identical observation happening in the bin center.
7362 ///
7363 /// \param[in] option is a character string to specify options
7364 /// - "D" Put out a line of "Debug" printout
7365 /// - "T" Return the normalized A-D test statistic
7366 ///
7367 /// - Note1: Underflow and overflow are not considered in the test
7368 /// - Note2: The test works only for un-weighted histogram (i.e. representing counts)
7369 /// - Note3: The histograms are not required to have the same X axis
7370 /// - Note4: The test works only for 1-dimensional histograms
7371 
7372 Double_t TH1::AndersonDarlingTest(const TH1 *h2, Option_t *option) const
7373 {
7374  Double_t advalue = 0;
7375  Double_t pvalue = AndersonDarlingTest(h2, advalue);
7376 
7377  TString opt = option;
7378  opt.ToUpper();
7379  if (opt.Contains("D") ) {
7380  printf(" AndersonDarlingTest Prob = %g, AD TestStatistic = %g\n",pvalue,advalue);
7381  }
7382  if (opt.Contains("T") ) return advalue;
7383 
7384  return pvalue;
7385 }
7386 
7387 ////////////////////////////////////////////////////////////////////////////////
7388 /// Same function as above but returning also the test statistic value
7389 
7390 Double_t TH1::AndersonDarlingTest(const TH1 *h2, Double_t & advalue) const
7391 {
7392  if (GetDimension() != 1 || h2->GetDimension() != 1) {
7393  Error("AndersonDarlingTest","Histograms must be 1-D");
7394  return -1;
7395  }
7396 
7397  // empty the buffer. Probably we could add as an unbinned test
7398  if (fBuffer) ((TH1*)this)->BufferEmpty();
7399 
7400  // use the BinData class
7401  ROOT::Fit::BinData data1;
7402  ROOT::Fit::BinData data2;
7403 
7404  ROOT::Fit::FillData(data1, this, 0);
7405  ROOT::Fit::FillData(data2, h2, 0);
7406 
7407  double pvalue;
7408  ROOT::Math::GoFTest::AndersonDarling2SamplesTest(data1,data2, pvalue,advalue);
7409 
7410  return pvalue;
7411 }
7412 
7413 ////////////////////////////////////////////////////////////////////////////////
7414 /// Statistical test of compatibility in shape between
7415 /// this histogram and h2, using Kolmogorov test.
7416 /// Note that the KolmogorovTest (KS) test should in theory be used only for unbinned data
7417 /// and not for binned data as in the case of the histogram (see NOTE 3 below).
7418 /// So, before using this method blindly, read the NOTE 3.
7419 ///
7420 /// Default: Ignore under- and overflow bins in comparison
7421 ///
7422 /// \param[in] h2 histogram
7423 /// \param[in] option is a character string to specify options
7424 /// - "U" include Underflows in test (also for 2-dim)
7425 /// - "O" include Overflows (also valid for 2-dim)
7426 /// - "N" include comparison of normalizations
7427 /// - "D" Put out a line of "Debug" printout
7428 /// - "M" Return the Maximum Kolmogorov distance instead of prob
7429 /// - "X" Run the pseudo experiments post-processor with the following procedure:
7430 /// make pseudoexperiments based on random values from the parent distribution,
7431 /// compare the KS distance of the pseudoexperiment to the parent
7432 /// distribution, and count all the KS values above the value
7433 /// obtained from the original data to Monte Carlo distribution.
7434 /// The number of pseudo-experiments nEXPT is currently fixed at 1000.
7435 /// The function returns the probability.
7436 /// (thanks to Ben Kilminster to submit this procedure). Note that
7437 /// this option "X" is much slower.
7438 ///
7439 /// The returned function value is the probability of test
7440 /// (much less than one means NOT compatible)
7441 ///
7442 /// Code adapted by Rene Brun from original HBOOK routine HDIFF
7443 ///
7444 /// NOTE1
7445 /// A good description of the Kolmogorov test can be seen at:
7446 /// http://www.itl.nist.gov/div898/handbook/eda/section3/eda35g.htm
7447 ///
7448 /// NOTE2
7449 /// see also alternative function TH1::Chi2Test
7450 /// The Kolmogorov test is assumed to give better results than Chi2Test
7451 /// in case of histograms with low statistics.
7452 ///
7453 /// NOTE3 (Jan Conrad, Fred James)
7454 /// "The returned value PROB is calculated such that it will be
7455 /// uniformly distributed between zero and one for compatible histograms,
7456 /// provided the data are not binned (or the number of bins is very large
7457 /// compared with the number of events). Users who have access to unbinned
7458 /// data and wish exact confidence levels should therefore not put their data
7459 /// into histograms, but should call directly TMath::KolmogorovTest. On
7460 /// the other hand, since TH1 is a convenient way of collecting data and
7461 /// saving space, this function has been provided. However, the values of
7462 /// PROB for binned data will be shifted slightly higher than expected,
7463 /// depending on the effects of the binning. For example, when comparing two
7464 /// uniform distributions of 500 events in 100 bins, the values of PROB,
7465 /// instead of being exactly uniformly distributed between zero and one, have
7466 /// a mean value of about 0.56. We can apply a useful
7467 /// rule: As long as the bin width is small compared with any significant
7468 /// physical effect (for example the experimental resolution) then the binning
7469 /// cannot have an important effect. Therefore, we believe that for all
7470 /// practical purposes, the probability value PROB is calculated correctly
7471 /// provided the user is aware that:
7472 ///
7473 /// 1. The value of PROB should not be expected to have exactly the correct
7474 /// distribution for binned data.
7475 /// 2. The user is responsible for seeing to it that the bin widths are
7476 /// small compared with any physical phenomena of interest.
7477 /// 3. The effect of binning (if any) is always to make the value of PROB
7478 /// slightly too big. That is, setting an acceptance criterion of (PROB>0.05
7479 /// will assure that at most 5% of truly compatible histograms are rejected,
7480 /// and usually somewhat less."
7481 ///
7482 /// Note also that for GoF test of unbinned data ROOT provides also the class
7483 /// ROOT::Math::GoFTest. The class has also method for doing one sample tests
7484 /// (i.e. comparing the data with a given distribution).
7485 
7486 Double_t TH1::KolmogorovTest(const TH1 *h2, Option_t *option) const
7487 {
7488  TString opt = option;
7489  opt.ToUpper();
7490 
7491  Double_t prob = 0;
7492  TH1 *h1 = (TH1*)this;
7493  if (h2 == 0) return 0;
7494  const TAxis *axis1 = h1->GetXaxis();
7495  const TAxis *axis2 = h2->GetXaxis();
7496  Int_t ncx1 = axis1->GetNbins();
7497  Int_t ncx2 = axis2->GetNbins();
7498 
7499  // Check consistency of dimensions
7500  if (h1->GetDimension() != 1 || h2->GetDimension() != 1) {
7501  Error("KolmogorovTest","Histograms must be 1-D\n");
7502  return 0;
7503  }
7504 
7505  // Check consistency in number of channels
7506  if (ncx1 != ncx2) {
7507  Error("KolmogorovTest","Histograms have different number of bins, %d and %d\n",ncx1,ncx2);
7508  return 0;
7509  }
7510 
7511  // empty the buffer. Probably we could add as an unbinned test
7512  if (fBuffer) ((TH1*)this)->BufferEmpty();
7513 
7514  // Check consistency in bin edges
7515  for(Int_t i = 1; i <= axis1->GetNbins() + 1; ++i) {
7516  if(!TMath::AreEqualRel(axis1->GetBinLowEdge(i), axis2->GetBinLowEdge(i), 1.E-15)) {
7517  Error("KolmogorovTest","Histograms are not consistent: they have different bin edges");
7518  return 0;
7519  }
7520  }
7521 
7522  Bool_t afunc1 = kFALSE;
7523  Bool_t afunc2 = kFALSE;
7524  Double_t sum1 = 0, sum2 = 0;
7525  Double_t ew1, ew2, w1 = 0, w2 = 0;
7526  Int_t bin;
7527  Int_t ifirst = 1;
7528  Int_t ilast = ncx1;
7529  // integral of all bins (use underflow/overflow if option)
7530  if (opt.Contains("U")) ifirst = 0;
7531  if (opt.Contains("O")) ilast = ncx1 +1;
7532  for (bin = ifirst; bin <= ilast; bin++) {
7533  sum1 += h1->RetrieveBinContent(bin);
7534  sum2 += h2->RetrieveBinContent(bin);
7535  ew1 = h1->GetBinError(bin);
7536  ew2 = h2->GetBinError(bin);
7537  w1 += ew1*ew1;
7538  w2 += ew2*ew2;
7539  }
7540  if (sum1 == 0) {
7541  Error("KolmogorovTest","Histogram1 %s integral is zero\n",h1->GetName());
7542  return 0;
7543  }
7544  if (sum2 == 0) {
7545  Error("KolmogorovTest","Histogram2 %s integral is zero\n",h2->GetName());
7546  return 0;
7547  }
7548 
7549  // calculate the effective entries.
7550  // the case when errors are zero (w1 == 0 or w2 ==0) are equivalent to
7551  // compare to a function. In that case the rescaling is done only on sqrt(esum2) or sqrt(esum1)
7552  Double_t esum1 = 0, esum2 = 0;
7553  if (w1 > 0)
7554  esum1 = sum1 * sum1 / w1;
7555  else
7556  afunc1 = kTRUE; // use later for calculating z
7557 
7558  if (w2 > 0)
7559  esum2 = sum2 * sum2 / w2;
7560  else
7561  afunc2 = kTRUE; // use later for calculating z
7562 
7563  if (afunc2 && afunc1) {
7564  Error("KolmogorovTest","Errors are zero for both histograms\n");
7565  return 0;
7566  }
7567 
7568 
7569  Double_t s1 = 1/sum1;
7570  Double_t s2 = 1/sum2;
7571 
7572  // Find largest difference for Kolmogorov Test
7573  Double_t dfmax =0, rsum1 = 0, rsum2 = 0;
7574 
7575  for (bin=ifirst;bin<=ilast;bin++) {
7576  rsum1 += s1*h1->RetrieveBinContent(bin);
7577  rsum2 += s2*h2->RetrieveBinContent(bin);
7578  dfmax = TMath::Max(dfmax,TMath::Abs(rsum1-rsum2));
7579  }
7580 
7581  // Get Kolmogorov probability
7582  Double_t z, prb1=0, prb2=0, prb3=0;
7583 
7584  // case h1 is exact (has zero errors)
7585  if (afunc1)
7586  z = dfmax*TMath::Sqrt(esum2);
7587  // case h2 has zero errors
7588  else if (afunc2)
7589  z = dfmax*TMath::Sqrt(esum1);
7590  else
7591  // for comparison between two data sets
7592  z = dfmax*TMath::Sqrt(esum1*esum2/(esum1+esum2));
7593 
7594  prob = TMath::KolmogorovProb(z);
7595 
7596  // option N to combine normalization makes sense if both afunc1 and afunc2 are false
7597  if (opt.Contains("N") && !(afunc1 || afunc2 ) ) {
7598  // Combine probabilities for shape and normalization,
7599  prb1 = prob;
7600  Double_t d12 = esum1-esum2;
7601  Double_t chi2 = d12*d12/(esum1+esum2);
7602  prb2 = TMath::Prob(chi2,1);
7603  // see Eadie et al., section 11.6.2
7604  if (prob > 0 && prb2 > 0) prob *= prb2*(1-TMath::Log(prob*prb2));
7605  else prob = 0;
7606  }
7607  // X option. Pseudo-experiments post-processor to determine KS probability
7608  const Int_t nEXPT = 1000;
7609  if (opt.Contains("X") && !(afunc1 || afunc2 ) ) {
7610  Double_t dSEXPT;
7611  TH1 *h1_cpy = (TH1 *)(gDirectory ? gDirectory->CloneObject(this, kFALSE) : gROOT->CloneObject(this, kFALSE));
7612  TH1 *hExpt = (TH1*)(gDirectory ? gDirectory->CloneObject(this,kFALSE) : gROOT->CloneObject(this,kFALSE));
7613 
7614  if (h1_cpy->GetMinimum() < 0.0) {
7615  // With negative bins we can't draw random samples in a meaningful way.
7616  Warning("KolmogorovTest", "Detected bins with negative weights, these have been ignored and output might be "
7617  "skewed. Reduce number of bins for histogram?");
7618  while (h1_cpy->GetMinimum() < 0.0) {
7619  Int_t idx = h1_cpy->GetMinimumBin();
7620  h1_cpy->SetBinContent(idx, 0.0);
7621  }
7622  }
7623 
7624  // make nEXPT experiments (this should be a parameter)
7625  prb3 = 0;
7626  for (Int_t i=0; i < nEXPT; i++) {
7627  hExpt->Reset();
7628  hExpt->FillRandom(h1_cpy, (Int_t)esum2);
7629  dSEXPT = KolmogorovTest(hExpt,"M");
7630  if (dSEXPT>dfmax) prb3 += 1.0;
7631  }
7632  prb3 /= (Double_t)nEXPT;
7633  delete h1_cpy;
7634  delete hExpt;
7635  }
7636 
7637  // debug printout
7638  if (opt.Contains("D")) {
7639  printf(" Kolmo Prob h1 = %s, sum bin content =%g effective entries =%g\n",h1->GetName(),sum1,esum1);
7640  printf(" Kolmo Prob h2 = %s, sum bin content =%g effective entries =%g\n",h2->GetName(),sum2,esum2);
7641  printf(" Kolmo Prob = %g, Max Dist = %g\n",prob,dfmax);
7642  if (opt.Contains("N"))
7643  printf(" Kolmo Prob = %f for shape alone, =%f for normalisation alone\n",prb1,prb2);
7644  if (opt.Contains("X"))
7645  printf(" Kolmo Prob = %f with %d pseudo-experiments\n",prb3,nEXPT);
7646  }
7647  // This numerical error condition should never occur:
7648  if (TMath::Abs(rsum1-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h1=%s\n",h1->GetName());
7649  if (TMath::Abs(rsum2-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h2=%s\n",h2->GetName());
7650 
7651  if(opt.Contains("M")) return dfmax;
7652  else if(opt.Contains("X")) return prb3;
7653  else return prob;
7654 }
7655 
7656 ////////////////////////////////////////////////////////////////////////////////
7657 /// Replace bin contents by the contents of array content
7658 
7659 void TH1::SetContent(const Double_t *content)
7660 {
7662  fTsumw = 0;
7663  for (Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, content[i]);
7664 }
7665 
7666 ////////////////////////////////////////////////////////////////////////////////
7667 /// Return contour values into array levels if pointer levels is non zero.
7668 ///
7669 /// The function returns the number of contour levels.
7670 /// see GetContourLevel to return one contour only
7671 
7673 {
7674  Int_t nlevels = fContour.fN;
7675  if (levels) {
7676  if (nlevels == 0) {
7677  nlevels = 20;
7678  SetContour(nlevels);
7679  } else {
7680  if (TestBit(kUserContour) == 0) SetContour(nlevels);
7681  }
7682  for (Int_t level=0; level<nlevels; level++) levels[level] = fContour.fArray[level];
7683  }
7684  return nlevels;
7685 }
7686 
7687 ////////////////////////////////////////////////////////////////////////////////
7688 /// Return value of contour number level.
7689 /// Use GetContour to return the array of all contour levels
7690 
7691 Double_t TH1::GetContourLevel(Int_t level) const
7692 {
7693  return (level >= 0 && level < fContour.fN) ? fContour.fArray[level] : 0.0;
7694 }
7695 
7696 ////////////////////////////////////////////////////////////////////////////////
7697 /// Return the value of contour number "level" in Pad coordinates.
7698 /// ie: if the Pad is in log scale along Z it returns le log of the contour level
7699 /// value. See GetContour to return the array of all contour levels
7700 
7702 {
7703  if (level <0 || level >= fContour.fN) return 0;
7704  Double_t zlevel = fContour.fArray[level];
7705 
7706  // In case of user defined contours and Pad in log scale along Z,
7707  // fContour.fArray doesn't contain the log of the contour whereas it does
7708  // in case of equidistant contours.
7709  if (gPad && gPad->GetLogz() && TestBit(kUserContour)) {
7710  if (zlevel <= 0) return 0;
7711  zlevel = TMath::Log10(zlevel);
7712  }
7713  return zlevel;
7714 }
7715 
7716 ////////////////////////////////////////////////////////////////////////////////
7717 /// Set the maximum number of entries to be kept in the buffer.
7718 
7719 void TH1::SetBuffer(Int_t buffersize, Option_t * /*option*/)
7720 {
7721  if (fBuffer) {
7722  BufferEmpty();
7723  delete [] fBuffer;
7724  fBuffer = 0;
7725  }
7726  if (buffersize <= 0) {
7727  fBufferSize = 0;
7728  return;
7729  }
7730  if (buffersize < 100) buffersize = 100;
7731  fBufferSize = 1 + buffersize*(fDimension+1);
7732  fBuffer = new Double_t[fBufferSize];
7733  memset(fBuffer,0,sizeof(Double_t)*fBufferSize);
7734 }
7735 
7736 ////////////////////////////////////////////////////////////////////////////////
7737 /// Set the number and values of contour levels.
7738 ///
7739 /// By default the number of contour levels is set to 20. The contours values
7740 /// in the array "levels" should be specified in increasing order.
7741 ///
7742 /// if argument levels = 0 or missing, equidistant contours are computed
7743 
7744 void TH1::SetContour(Int_t nlevels, const Double_t *levels)
7745 {
7746  Int_t level;
7748  if (nlevels <=0 ) {
7749  fContour.Set(0);
7750  return;
7751  }
7752  fContour.Set(nlevels);
7753 
7754  // - Contour levels are specified
7755  if (levels) {
7757  for (level=0; level<nlevels; level++) fContour.fArray[level] = levels[level];
7758  } else {
7759  // - contour levels are computed automatically as equidistant contours
7760  Double_t zmin = GetMinimum();
7761  Double_t zmax = GetMaximum();
7762  if ((zmin == zmax) && (zmin != 0)) {
7763  zmax += 0.01*TMath::Abs(zmax);
7764  zmin -= 0.01*TMath::Abs(zmin);
7765  }
7766  Double_t dz = (zmax-zmin)/Double_t(nlevels);
7767  if (gPad && gPad->GetLogz()) {
7768  if (zmax <= 0) return;
7769  if (zmin <= 0) zmin = 0.001*zmax;
7770  zmin = TMath::Log10(zmin);
7771  zmax = TMath::Log10(zmax);
7772  dz = (zmax-zmin)/Double_t(nlevels);
7773  }
7774  for (level=0; level<nlevels; level++) {
7775  fContour.fArray[level] = zmin + dz*Double_t(level);
7776  }
7777  }
7778 }
7779 
7780 ////////////////////////////////////////////////////////////////////////////////
7781 /// Set value for one contour level.
7782 
7783 void TH1::SetContourLevel(Int_t level, Double_t value)
7784 {
7785  if (level < 0 || level >= fContour.fN) return;
7787  fContour.fArray[level] = value;
7788 }
7789 
7790 ////////////////////////////////////////////////////////////////////////////////
7791 /// Return maximum value smaller than maxval of bins in the range,
7792 /// unless the value has been overridden by TH1::SetMaximum,
7793 /// in which case it returns that value. (This happens, for example,
7794 /// when the histogram is drawn and the y or z axis limits are changed
7795 ///
7796 /// To get the maximum value of bins in the histogram regardless of
7797 /// whether the value has been overridden, use
7798 ///
7799 /// ~~~ {.cpp}
7800 /// h->GetBinContent(h->GetMaximumBin())
7801 /// ~~~
7802 
7803 Double_t TH1::GetMaximum(Double_t maxval) const
7804 {
7805  if (fMaximum != -1111) return fMaximum;
7806 
7807  // empty the buffer
7808  if (fBuffer) ((TH1*)this)->BufferEmpty();
7809 
7810  Int_t bin, binx, biny, binz;
7811  Int_t xfirst = fXaxis.GetFirst();
7812  Int_t xlast = fXaxis.GetLast();
7813  Int_t yfirst = fYaxis.GetFirst();
7814  Int_t ylast = fYaxis.GetLast();
7815  Int_t zfirst = fZaxis.GetFirst();
7816  Int_t zlast = fZaxis.GetLast();
7817  Double_t maximum = -FLT_MAX, value;
7818  for (binz=zfirst;binz<=zlast;binz++) {
7819  for (biny=yfirst;biny<=ylast;biny++) {
7820  for (binx=xfirst;binx<=xlast;binx++) {
7821  bin = GetBin(binx,biny,binz);
7822  value = RetrieveBinContent(bin);
7823  if (value > maximum && value < maxval) maximum = value;
7824  }
7825  }
7826  }
7827  return maximum;
7828 }
7829 
7830 ////////////////////////////////////////////////////////////////////////////////
7831 /// Return location of bin with maximum value in the range.
7832 
7833 Int_t TH1::GetMaximumBin() const
7834 {
7835  Int_t locmax, locmay, locmaz;
7836  return GetMaximumBin(locmax, locmay, locmaz);
7837 }
7838 
7839 ////////////////////////////////////////////////////////////////////////////////
7840 /// Return location of bin with maximum value in the range.
7841 
7842 Int_t TH1::GetMaximumBin(Int_t &locmax, Int_t &locmay, Int_t &locmaz) const
7843 {
7844  // empty the buffer
7845  if (fBuffer) ((TH1*)this)->BufferEmpty();
7846 
7847  Int_t bin, binx, biny, binz;
7848  Int_t locm;
7849  Int_t xfirst = fXaxis.GetFirst();
7850  Int_t xlast = fXaxis.GetLast();
7851  Int_t yfirst = fYaxis.GetFirst();
7852  Int_t ylast = fYaxis.GetLast();
7853  Int_t zfirst = fZaxis.GetFirst();
7854  Int_t zlast = fZaxis.GetLast();
7855  Double_t maximum = -FLT_MAX, value;
7856  locm = locmax = locmay = locmaz = 0;
7857  for (binz=zfirst;binz<=zlast;binz++) {
7858  for (biny=yfirst;biny<=ylast;biny++) {
7859  for (binx=xfirst;binx<=xlast;binx++) {
7860  bin = GetBin(binx,biny,binz);
7861  value = RetrieveBinContent(bin);
7862  if (value > maximum) {
7863  maximum = value;
7864  locm = bin;
7865  locmax = binx;
7866  locmay = biny;
7867  locmaz = binz;
7868  }
7869  }
7870  }
7871  }
7872  return locm;
7873 }
7874 
7875 ////////////////////////////////////////////////////////////////////////////////
7876 /// Return minimum value larger than minval of bins in the range,
7877 /// unless the value has been overridden by TH1::SetMinimum,
7878 /// in which case it returns that value. (This happens, for example,
7879 /// when the histogram is drawn and the y or z axis limits are changed
7880 ///
7881 /// To get the minimum value of bins in the histogram regardless of
7882 /// whether the value has been overridden, use
7883 ///
7884 /// ~~~ {.cpp}
7885 /// h->GetBinContent(h->GetMinimumBin())
7886 /// ~~~
7887 
7888 Double_t TH1::GetMinimum(Double_t minval) const
7889 {
7890  if (fMinimum != -1111) return fMinimum;
7891 
7892  // empty the buffer
7893  if (fBuffer) ((TH1*)this)->BufferEmpty();
7894 
7895  Int_t bin, binx, biny, binz;
7896  Int_t xfirst = fXaxis.GetFirst();
7897  Int_t xlast = fXaxis.GetLast();
7898  Int_t yfirst = fYaxis.GetFirst();
7899  Int_t ylast = fYaxis.GetLast();
7900  Int_t zfirst = fZaxis.GetFirst();
7901  Int_t zlast = fZaxis.GetLast();
7902  Double_t minimum=FLT_MAX, value;
7903  for (binz=zfirst;binz<=zlast;binz++) {
7904  for (biny=yfirst;biny<=ylast;biny++) {
7905  for (binx=xfirst;binx<=xlast;binx++) {
7906  bin = GetBin(binx,biny,binz);
7907  value = RetrieveBinContent(bin);
7908  if (value < minimum && value > minval) minimum = value;
7909  }
7910  }
7911  }
7912  return minimum;
7913 }
7914 
7915 ////////////////////////////////////////////////////////////////////////////////
7916 /// Return location of bin with minimum value in the range.
7917 
7918 Int_t TH1::GetMinimumBin() const
7919 {
7920  Int_t locmix, locmiy, locmiz;
7921  return GetMinimumBin(locmix, locmiy, locmiz);
7922 }
7923 
7924 ////////////////////////////////////////////////////////////////////////////////
7925 /// Return location of bin with minimum value in the range.
7926 
7927 Int_t TH1::GetMinimumBin(Int_t &locmix, Int_t &locmiy, Int_t &locmiz) const
7928 {
7929  // empty the buffer
7930  if (fBuffer) ((TH1*)this)->BufferEmpty();
7931 
7932  Int_t bin, binx, biny, binz;
7933  Int_t locm;
7934  Int_t xfirst = fXaxis.GetFirst();
7935  Int_t xlast = fXaxis.GetLast();
7936  Int_t yfirst = fYaxis.GetFirst();
7937  Int_t ylast = fYaxis.GetLast();
7938  Int_t zfirst = fZaxis.GetFirst();
7939  Int_t zlast = fZaxis.GetLast();
7940  Double_t minimum = FLT_MAX, value;
7941  locm = locmix = locmiy = locmiz = 0;
7942  for (binz=zfirst;binz<=zlast;binz++) {
7943  for (biny=yfirst;biny<=ylast;biny++) {
7944  for (binx=xfirst;binx<=xlast;binx++) {
7945  bin = GetBin(binx,biny,binz);
7946  value = RetrieveBinContent(bin);
7947  if (value < minimum) {
7948  minimum = value;
7949  locm = bin;
7950  locmix = binx;
7951  locmiy = biny;
7952  locmiz = binz;
7953  }
7954  }
7955  }
7956  }
7957  return locm;
7958 }
7959 
7960 ///////////////////////////////////////////////////////////////////////////////
7961 /// Retrieve the minimum and maximum values in the histogram
7962 ///
7963 /// This will not return a cached value and will always search the
7964 /// histogram for the min and max values. The user can condition whether
7965 /// or not to call this with the GetMinimumStored() and GetMaximumStored()
7966 /// methods. If the cache is empty, then the value will be -1111. Users
7967 /// can then use the SetMinimum() or SetMaximum() methods to cache the results.
7968 /// For example, the following recipe will make efficient use of this method
7969 /// and the cached minimum and maximum values.
7970 //
7971 /// \code{.cpp}
7972 /// Double_t currentMin = pHist->GetMinimumStored();
7973 /// Double_t currentMax = pHist->GetMaximumStored();
7974 /// if ((currentMin == -1111) || (currentMax == -1111)) {
7975 /// pHist->GetMinimumAndMaximum(currentMin, currentMax);
7976 /// pHist->SetMinimum(currentMin);
7977 /// pHist->SetMaximum(currentMax);
7978 /// }
7979 /// \endcode
7980 ///
7981 /// \param min reference to variable that will hold found minimum value
7982 /// \param max reference to variable that will hold found maximum value
7983 
7984 void TH1::GetMinimumAndMaximum(Double_t& min, Double_t& max) const
7985 {
7986  // empty the buffer
7987  if (fBuffer) ((TH1*)this)->BufferEmpty();
7988 
7989  Int_t bin, binx, biny, binz;
7990  Int_t xfirst = fXaxis.GetFirst();
7991  Int_t xlast = fXaxis.GetLast();
7992  Int_t yfirst = fYaxis.GetFirst();
7993  Int_t ylast = fYaxis.GetLast();
7994  Int_t zfirst = fZaxis.GetFirst();
7995  Int_t zlast = fZaxis.GetLast();
7996  min=TMath::Infinity();
7997  max=-TMath::Infinity();
7998  Double_t value;
7999  for (binz=zfirst;binz<=zlast;binz++) {
8000  for (biny=yfirst;biny<=ylast;biny++) {
8001  for (binx=xfirst;binx<=xlast;binx++) {
8002  bin = GetBin(binx,biny,binz);
8003  value = RetrieveBinContent(bin);
8004  if (value < min) min = value;
8005  if (value > max) max = value;
8006  }
8007  }
8008  }
8009 }
8010 
8011 ////////////////////////////////////////////////////////////////////////////////
8012 /// Redefine x axis parameters.
8013 ///
8014 /// The X axis parameters are modified.
8015 /// The bins content array is resized
8016 /// if errors (Sumw2) the errors array is resized
8017 /// The previous bin contents are lost
8018 /// To change only the axis limits, see TAxis::SetRange
8019 
8021 {
8022  if (GetDimension() != 1) {
8023  Error("SetBins","Operation only valid for 1-d histograms");
8024  return;
8025  }
8026  fXaxis.SetRange(0,0);
8027  fXaxis.Set(nx,xmin,xmax);
8028  fYaxis.Set(1,0,1);
8029  fZaxis.Set(1,0,1);
8030  fNcells = nx+2;
8032  if (fSumw2.fN) {
8033  fSumw2.Set(fNcells);
8034  }
8035 }
8036 
8037 ////////////////////////////////////////////////////////////////////////////////
8038 /// Redefine x axis parameters with variable bin sizes.
8039 ///
8040 /// The X axis parameters are modified.
8041 /// The bins content array is resized
8042 /// if errors (Sumw2) the errors array is resized
8043 /// The previous bin contents are lost
8044 /// To change only the axis limits, see TAxis::SetRange
8045 /// xBins is supposed to be of length nx+1
8046 
8047 void TH1::SetBins(Int_t nx, const Double_t *xBins)
8048 {
8049  if (GetDimension() != 1) {
8050  Error("SetBins","Operation only valid for 1-d histograms");
8051  return;
8052  }
8053  fXaxis.SetRange(0,0);
8054  fXaxis.Set(nx,xBins);
8055  fYaxis.Set(1,0,1);
8056  fZaxis.Set(1,0,1);
8057  fNcells = nx+2;
8059  if (fSumw2.fN) {
8060  fSumw2.Set(fNcells);
8061  }
8062 }
8063 
8064 ////////////////////////////////////////////////////////////////////////////////
8065 /// Redefine x and y axis parameters.
8066 ///
8067 /// The X and Y axis parameters are modified.
8068 /// The bins content array is resized
8069 /// if errors (Sumw2) the errors array is resized
8070 /// The previous bin contents are lost
8071 /// To change only the axis limits, see TAxis::SetRange
8072 
8074 {
8075  if (GetDimension() != 2) {
8076  Error("SetBins","Operation only valid for 2-D histograms");
8077  return;
8078  }
8079  fXaxis.SetRange(0,0);
8080  fYaxis.SetRange(0,0);
8081  fXaxis.Set(nx,xmin,xmax);
8082  fYaxis.Set(ny,ymin,ymax);
8083  fZaxis.Set(1,0,1);
8084  fNcells = (nx+2)*(ny+2);
8086  if (fSumw2.fN) {
8087  fSumw2.Set(fNcells);
8088  }
8089 }
8090 
8091 ////////////////////////////////////////////////////////////////////////////////
8092 /// Redefine x and y axis parameters with variable bin sizes.
8093 ///
8094 /// The X and Y axis parameters are modified.
8095 /// The bins content array is resized
8096 /// if errors (Sumw2) the errors array is resized
8097 /// The previous bin contents are lost
8098 /// To change only the axis limits, see TAxis::SetRange
8099 /// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1
8100 
8101 void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins)
8102 {
8103  if (GetDimension() != 2) {
8104  Error("SetBins","Operation only valid for 2-D histograms");
8105  return;
8106  }
8107  fXaxis.SetRange(0,0);
8108  fYaxis.SetRange(0,0);
8109  fXaxis.Set(nx,xBins);
8110  fYaxis.Set(ny,yBins);
8111  fZaxis.Set(1,0,1);
8112  fNcells = (nx+2)*(ny+2);
8114  if (fSumw2.fN) {
8115  fSumw2.Set(fNcells);
8116  }
8117 }
8118 
8119 ////////////////////////////////////////////////////////////////////////////////
8120 /// Redefine x, y and z axis parameters.
8121 ///
8122 /// The X, Y and Z axis parameters are modified.
8123 /// The bins content array is resized
8124 /// if errors (Sumw2) the errors array is resized
8125 /// The previous bin contents are lost
8126 /// To change only the axis limits, see TAxis::SetRange
8127 
8129 {
8130  if (GetDimension() != 3) {
8131  Error("SetBins","Operation only valid for 3-D histograms");
8132  return;
8133  }
8134  fXaxis.SetRange(0,0);
8135  fYaxis.SetRange(0,0);
8136  fZaxis.SetRange(0,0);
8137  fXaxis.Set(nx,xmin,xmax);
8138  fYaxis.Set(ny,ymin,ymax);
8139  fZaxis.Set(nz,zmin,zmax);
8140  fNcells = (nx+2)*(ny+2)*(nz+2);
8142  if (fSumw2.fN) {
8143  fSumw2.Set(fNcells);
8144  }
8145 }
8146 
8147 ////////////////////////////////////////////////////////////////////////////////
8148 /// Redefine x, y and z axis parameters with variable bin sizes.
8149 ///
8150 /// The X, Y and Z axis parameters are modified.
8151 /// The bins content array is resized
8152 /// if errors (Sumw2) the errors array is resized
8153 /// The previous bin contents are lost
8154 /// To change only the axis limits, see TAxis::SetRange
8155 /// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1,
8156 /// zBins is supposed to be of length nz+1
8157 
8158 void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins, Int_t nz, const Double_t *zBins)
8159 {
8160  if (GetDimension() != 3) {
8161  Error("SetBins","Operation only valid for 3-D histograms");
8162  return;
8163  }
8164  fXaxis.SetRange(0,0);
8165  fYaxis.SetRange(0,0);
8166  fZaxis.SetRange(0,0);
8167  fXaxis.Set(nx,xBins);
8168  fYaxis.Set(ny,yBins);
8169  fZaxis.Set(nz,zBins);
8170  fNcells = (nx+2)*(ny+2)*(nz+2);
8172  if (fSumw2.fN) {
8173  fSumw2.Set(fNcells);
8174  }
8175 }
8176 
8177 ////////////////////////////////////////////////////////////////////////////////
8178 /// By default when an histogram is created, it is added to the list
8179 /// of histogram objects in the current directory in memory.
8180 /// Remove reference to this histogram from current directory and add
8181 /// reference to new directory dir. dir can be 0 in which case the
8182 /// histogram does not belong to any directory.
8183 ///
8184 /// Note that the directory is not a real property of the histogram and
8185 /// it will not be copied when the histogram is copied or cloned.
8186 /// If the user wants to have the copied (cloned) histogram in the same
8187 /// directory, he needs to set again the directory using SetDirectory to the
8188 /// copied histograms
8189 
8190 void TH1::SetDirectory(TDirectory *dir)
8191 {
8192  if (fDirectory == dir) return;
8193  if (fDirectory) fDirectory->Remove(this);
8194  fDirectory = dir;
8195  if (fDirectory) {
8196  fFunctions->UseRWLock();
8197  fDirectory->Append(this);
8198  }
8199 }
8200 
8201 ////////////////////////////////////////////////////////////////////////////////
8202 /// Replace bin errors by values in array error.
8203 
8204 void TH1::SetError(const Double_t *error)
8205 {
8206  for (Int_t i = 0; i < fNcells; ++i) SetBinError(i, error[i]);
8207 }
8208 
8209 ////////////////////////////////////////////////////////////////////////////////
8210 /// Change the name of this histogram
8211 ///
8212 
8213 void TH1::SetName(const char *name)
8214 {
8215  // Histograms are named objects in a THashList.
8216  // We must update the hashlist if we change the name
8217  // We protect this operation
8219  if (fDirectory) fDirectory->Remove(this);
8220  fName = name;
8221  if (fDirectory) fDirectory->Append(this);
8222 }
8223 
8224 ////////////////////////////////////////////////////////////////////////////////
8225 /// Change the name and title of this histogram
8226 
8227 void TH1::SetNameTitle(const char *name, const char *title)
8228 {
8229  // Histograms are named objects in a THashList.
8230  // We must update the hashlist if we change the name
8231  SetName(name);
8232  SetTitle(title);
8233 }
8234 
8235 ////////////////////////////////////////////////////////////////////////////////
8236 /// Set statistics option on/off
8237 ///
8238 /// By default, the statistics box is drawn.
8239 /// The paint options can be selected via gStyle->SetOptStats.
8240 /// This function sets/resets the kNoStats bin in the histogram object.
8241 /// It has priority over the Style option.
8242 
8243 void TH1::SetStats(Bool_t stats)
8244 {
8246  if (!stats) {
8247  SetBit(kNoStats);
8248  //remove the "stats" object from the list of functions
8249  if (fFunctions) {
8250  TObject *obj = fFunctions->FindObject("stats");
8251  if (obj) {
8252  fFunctions->Remove(obj);
8253  delete obj;
8254  }
8255  }
8256  }
8257 }
8258 
8259 ////////////////////////////////////////////////////////////////////////////////
8260 /// Create structure to store sum of squares of weights.
8261 ///
8262 /// if histogram is already filled, the sum of squares of weights
8263 /// is filled with the existing bin contents
8264 ///
8265 /// The error per bin will be computed as sqrt(sum of squares of weight)
8266 /// for each bin.
8267 ///
8268 /// This function is automatically called when the histogram is created
8269 /// if the static function TH1::SetDefaultSumw2 has been called before.
8270 /// If flag = false the structure is deleted
8271 
8272 void TH1::Sumw2(Bool_t flag)
8273 {
8274  if (!flag) {
8275  // clear the array if existing - do nothing otherwise
8276  if (fSumw2.fN > 0 ) fSumw2.Set(0);
8277  return;
8278  }
8279 
8280  if (fSumw2.fN == fNcells) {
8281  if (!fgDefaultSumw2 )
8282  Warning("Sumw2","Sum of squares of weights structure already created");
8283  return;
8284  }
8285 
8286  fSumw2.Set(fNcells);
8287 
8288  // empty the buffer
8289  if (fBuffer) BufferEmpty();
8290 
8291  if (fEntries > 0)
8292  for (Int_t i = 0; i < fNcells; ++i)
8294 }
8295 
8296 ////////////////////////////////////////////////////////////////////////////////
8297 /// Return pointer to function with name.
8298 ///
8299 ///
8300 /// Functions such as TH1::Fit store the fitted function in the list of
8301 /// functions of this histogram.
8302 
8303 TF1 *TH1::GetFunction(const char *name) const
8304 {
8306 }
8307 
8308 ////////////////////////////////////////////////////////////////////////////////
8309 /// Return value of error associated to bin number bin.
8310 ///
8311 /// if the sum of squares of weights has been defined (via Sumw2),
8312 /// this function returns the sqrt(sum of w2).
8313 /// otherwise it returns the sqrt(contents) for this bin.
8314 
8315 Double_t TH1::GetBinError(Int_t bin) const
8316 {
8317  if (bin < 0) bin = 0;
8318  if (bin >= fNcells) bin = fNcells-1;
8319  if (fBuffer) ((TH1*)this)->BufferEmpty();
8320  if (fSumw2.fN) return TMath::Sqrt(fSumw2.fArray[bin]);
8321 
8323 }
8324 
8325 ////////////////////////////////////////////////////////////////////////////////
8326 /// Return lower error associated to bin number bin.
8327 ///
8328 /// The error will depend on the statistic option used will return
8329 /// the binContent - lower interval value
8330 
8332 {
8333  if (fBinStatErrOpt == kNormal) return GetBinError(bin);
8334  // in case of weighted histogram check if it is really weighted
8335  if (fSumw2.fN && fTsumw != fTsumw2) return GetBinError(bin);
8336 
8337  if (bin < 0) bin = 0;
8338  if (bin >= fNcells) bin = fNcells-1;
8339  if (fBuffer) ((TH1*)this)->BufferEmpty();
8340 
8341  Double_t alpha = 1.- 0.682689492;
8342  if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
8343 
8344  Double_t c = RetrieveBinContent(bin);
8345  Int_t n = int(c);
8346  if (n < 0) {
8347  Warning("GetBinErrorLow","Histogram has negative bin content-force usage to normal errors");
8348  ((TH1*)this)->fBinStatErrOpt = kNormal;
8349  return GetBinError(bin);
8350  }
8351 
8352  if (n == 0) return 0;
8353  return c - ROOT::Math::gamma_quantile( alpha/2, n, 1.);
8354 }
8355 
8356 ////////////////////////////////////////////////////////////////////////////////
8357 /// Return upper error associated to bin number bin.
8358 ///
8359 /// The error will depend on the statistic option used will return
8360 /// the binContent - upper interval value
8361 
8363 {
8364  if (fBinStatErrOpt == kNormal) return GetBinError(bin);
8365  // in case of weighted histogram check if it is really weighted
8366  if (fSumw2.fN && fTsumw != fTsumw2) return GetBinError(bin);
8367  if (bin < 0) bin = 0;
8368  if (bin >= fNcells) bin = fNcells-1;
8369  if (fBuffer) ((TH1*)this)->BufferEmpty();
8370 
8371  Double_t alpha = 1.- 0.682689492;
8372  if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
8373 
8374  Double_t c = RetrieveBinContent(bin);
8375  Int_t n = int(c);
8376  if (n < 0) {
8377  Warning("GetBinErrorUp","Histogram has negative bin content-force usage to normal errors");
8378  ((TH1*)this)->fBinStatErrOpt = kNormal;
8379  return GetBinError(bin);
8380  }
8381 
8382  // for N==0 return an upper limit at 0.68 or (1-alpha)/2 ?
8383  // decide to return always (1-alpha)/2 upper interval
8384  //if (n == 0) return ROOT::Math::gamma_quantile_c(alpha,n+1,1);
8385  return ROOT::Math::gamma_quantile_c( alpha/2, n+1, 1) - c;
8386 }
8387 
8388 //L.M. These following getters are useless and should be probably deprecated
8389 ////////////////////////////////////////////////////////////////////////////////
8390 /// Return bin center for 1D histogram.
8391 /// Better to use h1.GetXaxis().GetBinCenter(bin)
8392 
8393 Double_t TH1::GetBinCenter(Int_t bin) const
8394 {
8395  if (fDimension == 1) return fXaxis.GetBinCenter(bin);
8396  Error("GetBinCenter","Invalid method for a %d-d histogram - return a NaN",fDimension);
8397  return TMath::QuietNaN();
8398 }
8399 
8400 ////////////////////////////////////////////////////////////////////////////////
8401 /// Return bin lower edge for 1D histogram.
8402 /// Better to use h1.GetXaxis().GetBinLowEdge(bin)
8403 
8405 {
8406  if (fDimension == 1) return fXaxis.GetBinLowEdge(bin);
8407  Error("GetBinLowEdge","Invalid method for a %d-d histogram - return a NaN",fDimension);
8408  return TMath::QuietNaN();
8409 }
8410 
8411 ////////////////////////////////////////////////////////////////////////////////
8412 /// Return bin width for 1D histogram.
8413 /// Better to use h1.GetXaxis().GetBinWidth(bin)
8414 
8415 Double_t TH1::GetBinWidth(Int_t bin) const
8416 {
8417  if (fDimension == 1) return fXaxis.GetBinWidth(bin);
8418  Error("GetBinWidth","Invalid method for a %d-d histogram - return a NaN",fDimension);
8419  return TMath::QuietNaN();
8420 }
8421 
8422 ////////////////////////////////////////////////////////////////////////////////
8423 /// Fill array with center of bins for 1D histogram
8424 /// Better to use h1.GetXaxis().GetCenter(center)
8425 
8426 void TH1::GetCenter(Double_t *center) const
8427 {
8428  if (fDimension == 1) {
8429  fXaxis.GetCenter(center);
8430  return;
8431  }
8432  Error("GetCenter","Invalid method for a %d-d histogram ",fDimension);
8433 }
8434 
8435 ////////////////////////////////////////////////////////////////////////////////
8436 /// Fill array with low edge of bins for 1D histogram
8437 /// Better to use h1.GetXaxis().GetLowEdge(edge)
8438 
8439 void TH1::GetLowEdge(Double_t *edge) const
8440 {
8441  if (fDimension == 1) {
8442  fXaxis.GetLowEdge(edge);
8443  return;
8444  }
8445  Error("GetLowEdge","Invalid method for a %d-d histogram ",fDimension);
8446 }
8447 
8448 ////////////////////////////////////////////////////////////////////////////////
8449 /// Set the bin Error
8450 /// Note that this resets the bin eror option to be of Normal Type and for the
8451 /// non-empty bin the bin error is set by default to the square root of their content,
8452 /// but in case the user sets explicitly a new bin content (using SetBinContent) he needs to provide also
8453 /// the error, otherwise a default error = 0 is used.
8454 ///
8455 /// See convention for numbering bins in TH1::GetBin
8456 
8457 void TH1::SetBinError(Int_t bin, Double_t error)
8458 {
8459  if (!fSumw2.fN) Sumw2();
8460  if (bin < 0 || bin>= fSumw2.fN) return;
8461  fSumw2.fArray[bin] = error * error;
8462  // reset the bin error option
8464 }
8465 
8466 ////////////////////////////////////////////////////////////////////////////////
8467 /// Set bin content
8468 /// see convention for numbering bins in TH1::GetBin
8469 /// In case the bin number is greater than the number of bins and
8470 /// the timedisplay option is set or CanExtendAllAxes(),
8471 /// the number of bins is automatically doubled to accommodate the new bin
8472 
8473 void TH1::SetBinContent(Int_t bin, Double_t content)
8474 {
8476  fTsumw = 0;
8477  if (bin < 0) return;
8478  if (bin >= fNcells-1) {
8479  if (fXaxis.GetTimeDisplay() || CanExtendAllAxes() ) {
8480  while (bin >= fNcells-1) LabelsInflate();
8481  } else {
8482  if (bin == fNcells-1) UpdateBinContent(bin, content);
8483  return;
8484  }
8485  }
8486  UpdateBinContent(bin, content);
8487 }
8488 
8489 ////////////////////////////////////////////////////////////////////////////////
8490 /// See convention for numbering bins in TH1::GetBin
8491 
8492 void TH1::SetBinError(Int_t binx, Int_t biny, Double_t error)
8493 {
8494  if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
8495  if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
8496  SetBinError(GetBin(binx, biny), error);
8497 }
8498 
8499 ////////////////////////////////////////////////////////////////////////////////
8500 /// See convention for numbering bins in TH1::GetBin
8501 
8502 void TH1::SetBinError(Int_t binx, Int_t biny, Int_t binz, Double_t error)
8503 {
8504  if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
8505  if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
8506  if (binz < 0 || binz > fZaxis.GetNbins() + 1) return;
8507  SetBinError(GetBin(binx, biny, binz), error);
8508 }
8509 
8510 ////////////////////////////////////////////////////////////////////////////////
8511 /// This function calculates the background spectrum in this histogram.
8512 /// The background is returned as a histogram.
8513 ///
8514 /// \param[in] niter number of iterations (default value = 2)
8515 /// Increasing niter make the result smoother and lower.
8516 /// \param[in] option may contain one of the following options
8517 /// - to set the direction parameter
8518 /// "BackDecreasingWindow". By default the direction is BackIncreasingWindow
8519 /// - filterOrder-order of clipping filter (default "BackOrder2")
8520 /// possible values= "BackOrder4" "BackOrder6" "BackOrder8"
8521 /// - "nosmoothing" - if selected, the background is not smoothed
8522 /// By default the background is smoothed.
8523 /// - smoothWindow - width of smoothing window, (default is "BackSmoothing3")
8524 /// possible values= "BackSmoothing5" "BackSmoothing7" "BackSmoothing9"
8525 /// "BackSmoothing11" "BackSmoothing13" "BackSmoothing15"
8526 /// - "nocompton" - if selected the estimation of Compton edge
8527 /// will be not be included (by default the compton estimation is set)
8528 /// - "same" if this option is specified, the resulting background
8529 /// histogram is superimposed on the picture in the current pad.
8530 /// This option is given by default.
8531 ///
8532 /// NOTE that the background is only evaluated in the current range of this histogram.
8533 /// i.e., if this has a bin range (set via h->GetXaxis()->SetRange(binmin, binmax),
8534 /// the returned histogram will be created with the same number of bins
8535 /// as this input histogram, but only bins from binmin to binmax will be filled
8536 /// with the estimated background.
8537 
8538 TH1 *TH1::ShowBackground(Int_t niter, Option_t *option)
8539 {
8541  return (TH1*)gROOT->ProcessLineFast(Form("TSpectrum::StaticBackground((TH1*)0x%lx,%d,\"%s\")",
8542  (ULong_t)this, niter, option));
8543 }
8544 
8545 ////////////////////////////////////////////////////////////////////////////////
8546 /// Interface to TSpectrum::Search.
8547 /// The function finds peaks in this histogram where the width is > sigma
8548 /// and the peak maximum greater than threshold*maximum bin content of this.
8549 /// For more details see TSpectrum::Search.
8550 /// Note the difference in the default value for option compared to TSpectrum::Search
8551 /// option="" by default (instead of "goff").
8552 
8553 Int_t TH1::ShowPeaks(Double_t sigma, Option_t *option, Double_t threshold)
8554 {
8555  return (Int_t)gROOT->ProcessLineFast(Form("TSpectrum::StaticSearch((TH1*)0x%lx,%g,\"%s\",%g)",
8556  (ULong_t)this, sigma, option, threshold));
8557 }
8558 
8559 ////////////////////////////////////////////////////////////////////////////////
8560 /// For a given transform (first parameter), fills the histogram (second parameter)
8561 /// with the transform output data, specified in the third parameter
8562 /// If the 2nd parameter h_output is empty, a new histogram (TH1D or TH2D) is created
8563 /// and the user is responsible for deleting it.
8564 ///
8565 /// Available options:
8566 /// - "RE" - real part of the output
8567 /// - "IM" - imaginary part of the output
8568 /// - "MAG" - magnitude of the output
8569 /// - "PH" - phase of the output
8570 
8571 TH1* TH1::TransformHisto(TVirtualFFT *fft, TH1* h_output, Option_t *option)
8572 {
8573  if (!fft || !fft->GetN() ) {
8574  ::Error("TransformHisto","Invalid FFT transform class");
8575  return 0;
8576  }
8577 
8578  if (fft->GetNdim()>2){
8579  ::Error("TransformHisto","Only 1d and 2D transform are supported");
8580  return 0;
8581  }
8582  Int_t binx,biny;
8583  TString opt = option;
8584  opt.ToUpper();
8585  Int_t *n = fft->GetN();
8586  TH1 *hout=0;
8587  if (h_output) {
8588  hout = h_output;
8589  }
8590  else {
8591  TString name = TString::Format("out_%s", opt.Data());
8592  if (fft->GetNdim()==1)
8593  hout = new TH1D(name, name,n[0], 0, n[0]);
8594  else if (fft->GetNdim()==2)
8595  hout = new TH2D(name, name, n[0], 0, n[0], n[1], 0, n[1]);
8596  }
8597  R__ASSERT(hout != 0);
8598  TString type=fft->GetType();
8599  Int_t ind[2];
8600  if (opt.Contains("RE")){
8601  if (type.Contains("2C") || type.Contains("2HC")) {
8602  Double_t re, im;
8603  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8604  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8605  ind[0] = binx-1; ind[1] = biny-1;
8606  fft->GetPointComplex(ind, re, im);
8607  hout->SetBinContent(binx, biny, re);
8608  }
8609  }
8610  } else {
8611  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8612  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8613  ind[0] = binx-1; ind[1] = biny-1;
8614  hout->SetBinContent(binx, biny, fft->GetPointReal(ind));
8615  }
8616  }
8617  }
8618  }
8619  if (opt.Contains("IM")) {
8620  if (type.Contains("2C") || type.Contains("2HC")) {
8621  Double_t re, im;
8622  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8623  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8624  ind[0] = binx-1; ind[1] = biny-1;
8625  fft->GetPointComplex(ind, re, im);
8626  hout->SetBinContent(binx, biny, im);
8627  }
8628  }
8629  } else {
8630  ::Error("TransformHisto","No complex numbers in the output");
8631  return 0;
8632  }
8633  }
8634  if (opt.Contains("MA")) {
8635  if (type.Contains("2C") || type.Contains("2HC")) {
8636  Double_t re, im;
8637  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8638  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8639  ind[0] = binx-1; ind[1] = biny-1;
8640  fft->GetPointComplex(ind, re, im);
8641  hout->SetBinContent(binx, biny, TMath::Sqrt(re*re + im*im));
8642  }
8643  }
8644  } else {
8645  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8646  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8647  ind[0] = binx-1; ind[1] = biny-1;
8648  hout->SetBinContent(binx, biny, TMath::Abs(fft->GetPointReal(ind)));
8649  }
8650  }
8651  }
8652  }
8653  if (opt.Contains("PH")) {
8654  if (type.Contains("2C") || type.Contains("2HC")){
8655  Double_t re, im, ph;
8656  for (binx = 1; binx<=hout->GetNbinsX(); binx++){
8657  for (biny=1; biny<=hout->GetNbinsY(); biny++){
8658  ind[0] = binx-1; ind[1] = biny-1;
8659  fft->GetPointComplex(ind, re, im);
8660  if (TMath::Abs(re) > 1e-13){
8661  ph = TMath::ATan(im/re);
8662  //find the correct quadrant
8663  if (re<0 && im<0)
8664  ph -= TMath::Pi();
8665  if (re<0 && im>=0)
8666  ph += TMath::Pi();
8667  } else {
8668  if (TMath::Abs(im) < 1e-13)
8669  ph = 0;
8670  else if (im>0)
8671  ph = TMath::Pi()*0.5;
8672  else
8673  ph = -TMath::Pi()*0.5;
8674  }
8675  hout->SetBinContent(binx, biny, ph);
8676  }
8677  }
8678  } else {
8679  printf("Pure real output, no phase");
8680  return 0;
8681  }
8682  }
8683 
8684  return hout;
8685 }
8686 
8687 ////////////////////////////////////////////////////////////////////////////////
8688 /// Raw retrieval of bin content on internal data structure
8689 /// see convention for numbering bins in TH1::GetBin
8690 
8692 {
8693  AbstractMethod("RetrieveBinContent");
8694  return 0;
8695 }
8696 
8697 ////////////////////////////////////////////////////////////////////////////////
8698 /// Raw update of bin content on internal data structure
8699 /// see convention for numbering bins in TH1::GetBin
8700 
8702 {
8703  AbstractMethod("UpdateBinContent");
8704 }
8705 
8706 ////////////////////////////////////////////////////////////////////////////////
8707 /// Print value overload
8708 
8709 std::string cling::printValue(TH1 *val) {
8710  std::ostringstream strm;
8711  strm << cling::printValue((TObject*)val) << " NbinsX: " << val->GetNbinsX();
8712  return strm.str();
8713 }
8714 
8715 //______________________________________________________________________________
8716 // TH1C methods
8717 // TH1C : histograms with one byte per channel. Maximum bin content = 127
8718 //______________________________________________________________________________
8719 
8720 ClassImp(TH1C);
8721 
8722 ////////////////////////////////////////////////////////////////////////////////
8723 /// Constructor.
8724 
8725 TH1C::TH1C(): TH1(), TArrayC()
8726 {
8727  fDimension = 1;
8728  SetBinsLength(3);
8729  if (fgDefaultSumw2) Sumw2();
8730 }
8731 
8732 ////////////////////////////////////////////////////////////////////////////////
8733 /// Create a 1-Dim histogram with fix bins of type char (one byte per channel)
8734 /// (see TH1::TH1 for explanation of parameters)
8735 
8736 TH1C::TH1C(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
8737 : TH1(name,title,nbins,xlow,xup)
8739  fDimension = 1;
8740  TArrayC::Set(fNcells);
8741 
8742  if (xlow >= xup) SetBuffer(fgBufferSize);
8743  if (fgDefaultSumw2) Sumw2();
8744 }
8745 
8746 ////////////////////////////////////////////////////////////////////////////////
8747 /// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
8748 /// (see TH1::TH1 for explanation of parameters)
8749 
8750 TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
8751 : TH1(name,title,nbins,xbins)
8753  fDimension = 1;
8754  TArrayC::Set(fNcells);
8755  if (fgDefaultSumw2) Sumw2();
8756 }
8757 
8758 ////////////////////////////////////////////////////////////////////////////////
8759 /// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
8760 /// (see TH1::TH1 for explanation of parameters)
8761 
8762 TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
8763 : TH1(name,title,nbins,xbins)
8765  fDimension = 1;
8766  TArrayC::Set(fNcells);
8767  if (fgDefaultSumw2) Sumw2();
8768 }
8769 
8770 ////////////////////////////////////////////////////////////////////////////////
8771 /// Destructor.
8772 
8773 TH1C::~TH1C()
8774 {
8776 
8777 ////////////////////////////////////////////////////////////////////////////////
8778 /// Copy constructor.
8779 
8780 TH1C::TH1C(const TH1C &h1c) : TH1(), TArrayC()
8781 {
8782  ((TH1C&)h1c).Copy(*this);
8783 }
8784 
8785 ////////////////////////////////////////////////////////////////////////////////
8786 /// Increment bin content by 1.
8787 
8788 void TH1C::AddBinContent(Int_t bin)
8789 {
8790  if (fArray[bin] < 127) fArray[bin]++;
8791 }
8792 
8793 ////////////////////////////////////////////////////////////////////////////////
8794 /// Increment bin content by w.
8795 
8796 void TH1C::AddBinContent(Int_t bin, Double_t w)
8797 {
8798  Int_t newval = fArray[bin] + Int_t(w);
8799  if (newval > -128 && newval < 128) {fArray[bin] = Char_t(newval); return;}
8800  if (newval < -127) fArray[bin] = -127;
8801  if (newval > 127) fArray[bin] = 127;
8802 }
8803 
8804 ////////////////////////////////////////////////////////////////////////////////
8805 /// Copy this to newth1
8806 
8807 void TH1C::Copy(TObject &newth1) const
8808 {
8809  TH1::Copy(newth1);
8810 }
8811 
8812 ////////////////////////////////////////////////////////////////////////////////
8813 /// Reset.
8814 
8815 void TH1C::Reset(Option_t *option)
8816 {
8817  TH1::Reset(option);
8818  TArrayC::Reset();
8819 }
8820 
8821 ////////////////////////////////////////////////////////////////////////////////
8822 /// Set total number of bins including under/overflow
8823 /// Reallocate bin contents array
8824 
8826 {
8827  if (n < 0) n = fXaxis.GetNbins() + 2;
8828  fNcells = n;
8829  TArrayC::Set(n);
8830 }
8831 
8832 ////////////////////////////////////////////////////////////////////////////////
8833 /// Operator =
8834 
8835 TH1C& TH1C::operator=(const TH1C &h1)
8836 {
8837  if (this != &h1) ((TH1C&)h1).Copy(*this);
8838  return *this;
8839 }
8840 
8841 ////////////////////////////////////////////////////////////////////////////////
8842 /// Operator *
8843 
8844 TH1C operator*(Double_t c1, const TH1C &h1)
8845 {
8846  TH1C hnew = h1;
8847  hnew.Scale(c1);
8848  hnew.SetDirectory(0);
8849  return hnew;
8850 }
8851 
8852 ////////////////////////////////////////////////////////////////////////////////
8853 /// Operator +
8854 
8855 TH1C operator+(const TH1C &h1, const TH1C &h2)
8856 {
8857  TH1C hnew = h1;
8858  hnew.Add(&h2,1);
8859  hnew.SetDirectory(0);
8860  return hnew;
8861 }
8862 
8863 ////////////////////////////////////////////////////////////////////////////////
8864 /// Operator -
8865 
8866 TH1C operator-(const TH1C &h1, const TH1C &h2)
8867 {
8868  TH1C hnew = h1;
8869  hnew.Add(&h2,-1);
8870  hnew.SetDirectory(0);
8871  return hnew;
8872 }
8873 
8874 ////////////////////////////////////////////////////////////////////////////////
8875 /// Operator *
8876 
8877 TH1C operator*(const TH1C &h1, const TH1C &h2)
8878 {
8879  TH1C hnew = h1;
8880  hnew.Multiply(&h2);
8881  hnew.SetDirectory(0);
8882  return hnew;
8883 }
8884 
8885 ////////////////////////////////////////////////////////////////////////////////
8886 /// Operator /
8887 
8888 TH1C operator/(const TH1C &h1, const TH1C &h2)
8889 {
8890  TH1C hnew = h1;
8891  hnew.Divide(&h2);
8892  hnew.SetDirectory(0);
8893  return hnew;
8894 }
8895 
8896 //______________________________________________________________________________
8897 // TH1S methods
8898 // TH1S : histograms with one short per channel. Maximum bin content = 32767
8899 //______________________________________________________________________________
8900 
8901 ClassImp(TH1S);
8902 
8903 ////////////////////////////////////////////////////////////////////////////////
8904 /// Constructor.
8905 
8906 TH1S::TH1S(): TH1(), TArrayS()
8907 {
8908  fDimension = 1;
8909  SetBinsLength(3);
8910  if (fgDefaultSumw2) Sumw2();
8911 }
8912 
8913 ////////////////////////////////////////////////////////////////////////////////
8914 /// Create a 1-Dim histogram with fix bins of type short
8915 /// (see TH1::TH1 for explanation of parameters)
8916 
8917 TH1S::TH1S(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
8918 : TH1(name,title,nbins,xlow,xup)
8920  fDimension = 1;
8921  TArrayS::Set(fNcells);
8922 
8923  if (xlow >= xup) SetBuffer(fgBufferSize);
8924  if (fgDefaultSumw2) Sumw2();
8925 }
8926 
8927 ////////////////////////////////////////////////////////////////////////////////
8928 /// Create a 1-Dim histogram with variable bins of type short
8929 /// (see TH1::TH1 for explanation of parameters)
8930 
8931 TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
8932 : TH1(name,title,nbins,xbins)
8934  fDimension = 1;
8935  TArrayS::Set(fNcells);
8936  if (fgDefaultSumw2) Sumw2();
8937 }
8938 
8939 ////////////////////////////////////////////////////////////////////////////////
8940 /// Create a 1-Dim histogram with variable bins of type short
8941 /// (see TH1::TH1 for explanation of parameters)
8942 
8943 TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
8944 : TH1(name,title,nbins,xbins)
8946  fDimension = 1;
8947  TArrayS::Set(fNcells);
8948  if (fgDefaultSumw2) Sumw2();
8949 }
8950 
8951 ////////////////////////////////////////////////////////////////////////////////
8952 /// Destructor.
8953 
8954 TH1S::~TH1S()
8955 {
8957 
8958 ////////////////////////////////////////////////////////////////////////////////
8959 /// Copy constructor.
8960 
8961 TH1S::TH1S(const TH1S &h1s) : TH1(), TArrayS()
8962 {
8963  ((TH1S&)h1s).Copy(*this);
8964 }
8965 
8966 ////////////////////////////////////////////////////////////////////////////////
8967 /// Increment bin content by 1.
8968 
8969 void TH1S::AddBinContent(Int_t bin)
8970 {
8971  if (fArray[bin] < 32767) fArray[bin]++;
8972 }
8973 
8974 ////////////////////////////////////////////////////////////////////////////////
8975 /// Increment bin content by w
8976 
8977 void TH1S::AddBinContent(Int_t bin, Double_t w)
8978 {
8979  Int_t newval = fArray[bin] + Int_t(w);
8980  if (newval > -32768 && newval < 32768) {fArray[bin] = Short_t(newval); return;}
8981  if (newval < -32767) fArray[bin] = -32767;
8982  if (newval > 32767) fArray[bin] = 32767;
8983 }
8984 
8985 ////////////////////////////////////////////////////////////////////////////////
8986 /// Copy this to newth1
8987 
8988 void TH1S::Copy(TObject &newth1) const
8989 {
8990  TH1::Copy(newth1);
8991 }
8992 
8993 ////////////////////////////////////////////////////////////////////////////////
8994 /// Reset.
8995 
8996 void TH1S::Reset(Option_t *option)
8997 {
8998  TH1::Reset(option);
8999  TArrayS::Reset();
9000 }
9001 
9002 ////////////////////////////////////////////////////////////////////////////////
9003 /// Set total number of bins including under/overflow
9004 /// Reallocate bin contents array
9005 
9007 {
9008  if (n < 0) n = fXaxis.GetNbins() + 2;
9009  fNcells = n;
9010  TArrayS::Set(n);
9011 }
9012 
9013 ////////////////////////////////////////////////////////////////////////////////
9014 /// Operator =
9015 
9016 TH1S& TH1S::operator=(const TH1S &h1)
9017 {
9018  if (this != &h1) ((TH1S&)h1).Copy(*this);
9019  return *this;
9020 }
9021 
9022 ////////////////////////////////////////////////////////////////////////////////
9023 /// Operator *
9024 
9025 TH1S operator*(Double_t c1, const TH1S &h1)
9026 {
9027  TH1S hnew = h1;
9028  hnew.Scale(c1);
9029  hnew.SetDirectory(0);
9030  return hnew;
9031 }
9032 
9033 ////////////////////////////////////////////////////////////////////////////////
9034 /// Operator +
9035 
9036 TH1S operator+(const TH1S &h1, const TH1S &h2)
9037 {
9038  TH1S hnew = h1;
9039  hnew.Add(&h2,1);
9040  hnew.SetDirectory(0);
9041  return hnew;
9042 }
9043 
9044 ////////////////////////////////////////////////////////////////////////////////
9045 /// Operator -
9046 
9047 TH1S operator-(const TH1S &h1, const TH1S &h2)
9048 {
9049  TH1S hnew = h1;
9050  hnew.Add(&h2,-1);
9051  hnew.SetDirectory(0);
9052  return hnew;
9053 }
9054 
9055 ////////////////////////////////////////////////////////////////////////////////
9056 /// Operator *
9057 
9058 TH1S operator*(const TH1S &h1, const TH1S &h2)
9059 {
9060  TH1S hnew = h1;
9061  hnew.Multiply(&h2);
9062  hnew.SetDirectory(0);
9063  return hnew;
9064 }
9065 
9066 ////////////////////////////////////////////////////////////////////////////////
9067 /// Operator /
9068 
9069 TH1S operator/(const TH1S &h1, const TH1S &h2)
9070 {
9071  TH1S hnew = h1;
9072  hnew.Divide(&h2);
9073  hnew.SetDirectory(0);
9074  return hnew;
9075 }
9076 
9077 //______________________________________________________________________________
9078 // TH1I methods
9079 // TH1I : histograms with one int per channel. Maximum bin content = 2147483647
9080 //______________________________________________________________________________
9081 
9082 ClassImp(TH1I);
9083 
9084 ////////////////////////////////////////////////////////////////////////////////
9085 /// Constructor.
9086 
9087 TH1I::TH1I(): TH1(), TArrayI()
9088 {
9089  fDimension = 1;
9090  SetBinsLength(3);
9091  if (fgDefaultSumw2) Sumw2();
9092 }
9093 
9094 ////////////////////////////////////////////////////////////////////////////////
9095 /// Create a 1-Dim histogram with fix bins of type integer
9096 /// (see TH1::TH1 for explanation of parameters)
9097 
9098 TH1I::TH1I(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9099 : TH1(name,title,nbins,xlow,xup)
9101  fDimension = 1;
9102  TArrayI::Set(fNcells);
9103 
9104  if (xlow >= xup) SetBuffer(fgBufferSize);
9105  if (fgDefaultSumw2) Sumw2();
9106 }
9107 
9108 ////////////////////////////////////////////////////////////////////////////////
9109 /// Create a 1-Dim histogram with variable bins of type integer
9110 /// (see TH1::TH1 for explanation of parameters)
9111 
9112 TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9113 : TH1(name,title,nbins,xbins)
9115  fDimension = 1;
9116  TArrayI::Set(fNcells);
9117  if (fgDefaultSumw2) Sumw2();
9118 }
9119 
9120 ////////////////////////////////////////////////////////////////////////////////
9121 /// Create a 1-Dim histogram with variable bins of type integer
9122 /// (see TH1::TH1 for explanation of parameters)
9123 
9124 TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9125 : TH1(name,title,nbins,xbins)
9127  fDimension = 1;
9128  TArrayI::Set(fNcells);
9129  if (fgDefaultSumw2) Sumw2();
9130 }
9131 
9132 ////////////////////////////////////////////////////////////////////////////////
9133 /// Destructor.
9134 
9135 TH1I::~TH1I()
9136 {
9138 
9139 ////////////////////////////////////////////////////////////////////////////////
9140 /// Copy constructor.
9141 
9142 TH1I::TH1I(const TH1I &h1i) : TH1(), TArrayI()
9143 {
9144  ((TH1I&)h1i).Copy(*this);
9145 }
9146 
9147 ////////////////////////////////////////////////////////////////////////////////
9148 /// Increment bin content by 1.
9149 
9150 void TH1I::AddBinContent(Int_t bin)
9151 {
9152  if (fArray[bin] < 2147483647) fArray[bin]++;
9153 }
9154 
9155 ////////////////////////////////////////////////////////////////////////////////
9156 /// Increment bin content by w
9157 
9158 void TH1I::AddBinContent(Int_t bin, Double_t w)
9159 {
9160  Long64_t newval = fArray[bin] + Long64_t(w);
9161  if (newval > -2147483647 && newval < 2147483647) {fArray[bin] = Int_t(newval); return;}
9162  if (newval < -2147483647) fArray[bin] = -2147483647;
9163  if (newval > 2147483647) fArray[bin] = 2147483647;
9164 }
9165 
9166 ////////////////////////////////////////////////////////////////////////////////
9167 /// Copy this to newth1
9168 
9169 void TH1I::Copy(TObject &newth1) const
9170 {
9171  TH1::Copy(newth1);
9172 }
9173 
9174 ////////////////////////////////////////////////////////////////////////////////
9175 /// Reset.
9176 
9177 void TH1I::Reset(Option_t *option)
9178 {
9179  TH1::Reset(option);
9180  TArrayI::Reset();
9181 }
9182 
9183 ////////////////////////////////////////////////////////////////////////////////
9184 /// Set total number of bins including under/overflow
9185 /// Reallocate bin contents array
9186 
9188 {
9189  if (n < 0) n = fXaxis.GetNbins() + 2;
9190  fNcells = n;
9191  TArrayI::Set(n);
9192 }
9193 
9194 ////////////////////////////////////////////////////////////////////////////////
9195 /// Operator =
9196 
9197 TH1I& TH1I::operator=(const TH1I &h1)
9198 {
9199  if (this != &h1) ((TH1I&)h1).Copy(*this);
9200  return *this;
9201 }
9202 
9203 
9204 ////////////////////////////////////////////////////////////////////////////////
9205 /// Operator *
9206 
9207 TH1I operator*(Double_t c1, const TH1I &h1)
9208 {
9209  TH1I hnew = h1;
9210  hnew.Scale(c1);
9211  hnew.SetDirectory(0);
9212  return hnew;
9213 }
9214 
9215 ////////////////////////////////////////////////////////////////////////////////
9216 /// Operator +
9217 
9218 TH1I operator+(const TH1I &h1, const TH1I &h2)
9219 {
9220  TH1I hnew = h1;
9221  hnew.Add(&h2,1);
9222  hnew.SetDirectory(0);
9223  return hnew;
9224 }
9225 
9226 ////////////////////////////////////////////////////////////////////////////////
9227 /// Operator -
9228 
9229 TH1I operator-(const TH1I &h1, const TH1I &h2)
9230 {
9231  TH1I hnew = h1;
9232  hnew.Add(&h2,-1);
9233  hnew.SetDirectory(0);
9234  return hnew;
9235 }
9236 
9237 ////////////////////////////////////////////////////////////////////////////////
9238 /// Operator *
9239 
9240 TH1I operator*(const TH1I &h1, const TH1I &h2)
9241 {
9242  TH1I hnew = h1;
9243  hnew.Multiply(&h2);
9244  hnew.SetDirectory(0);
9245  return hnew;
9246 }
9247 
9248 ////////////////////////////////////////////////////////////////////////////////
9249 /// Operator /
9250 
9251 TH1I operator/(const TH1I &h1, const TH1I &h2)
9252 {
9253  TH1I hnew = h1;
9254  hnew.Divide(&h2);
9255  hnew.SetDirectory(0);
9256  return hnew;
9257 }
9258 
9259 //______________________________________________________________________________
9260 // TH1F methods
9261 // TH1F : histograms with one float per channel. Maximum precision 7 digits
9262 //______________________________________________________________________________
9263 
9264 ClassImp(TH1F);
9265 
9266 ////////////////////////////////////////////////////////////////////////////////
9267 /// Constructor.
9268 
9269 TH1F::TH1F(): TH1(), TArrayF()
9270 {
9271  fDimension = 1;
9272  SetBinsLength(3);
9273  if (fgDefaultSumw2) Sumw2();
9274 }
9275 
9276 ////////////////////////////////////////////////////////////////////////////////
9277 /// Create a 1-Dim histogram with fix bins of type float
9278 /// (see TH1::TH1 for explanation of parameters)
9279 
9280 TH1F::TH1F(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9281 : TH1(name,title,nbins,xlow,xup)
9283  fDimension = 1;
9284  TArrayF::Set(fNcells);
9285 
9286  if (xlow >= xup) SetBuffer(fgBufferSize);
9287  if (fgDefaultSumw2) Sumw2();
9288 }
9289 
9290 ////////////////////////////////////////////////////////////////////////////////
9291 /// Create a 1-Dim histogram with variable bins of type float
9292 /// (see TH1::TH1 for explanation of parameters)
9293 
9294 TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9295 : TH1(name,title,nbins,xbins)
9297  fDimension = 1;
9298  TArrayF::Set(fNcells);
9299  if (fgDefaultSumw2) Sumw2();
9300 }
9301 
9302 ////////////////////////////////////////////////////////////////////////////////
9303 /// Create a 1-Dim histogram with variable bins of type float
9304 /// (see TH1::TH1 for explanation of parameters)
9305 
9306 TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9307 : TH1(name,title,nbins,xbins)
9309  fDimension = 1;
9310  TArrayF::Set(fNcells);
9311  if (fgDefaultSumw2) Sumw2();
9312 }
9313 
9314 ////////////////////////////////////////////////////////////////////////////////
9315 /// Create a histogram from a TVectorF
9316 /// by default the histogram name is "TVectorF" and title = ""
9317 
9318 TH1F::TH1F(const TVectorF &v)
9319 : TH1("TVectorF","",v.GetNrows(),0,v.GetNrows())
9321  TArrayF::Set(fNcells);
9322  fDimension = 1;
9323  Int_t ivlow = v.GetLwb();
9324  for (Int_t i=0;i<fNcells-2;i++) {
9325  SetBinContent(i+1,v(i+ivlow));
9326  }
9327  TArrayF::Set(fNcells);
9328  if (fgDefaultSumw2) Sumw2();
9329 }
9330 
9331 ////////////////////////////////////////////////////////////////////////////////
9332 /// Copy Constructor.
9333 
9334 TH1F::TH1F(const TH1F &h) : TH1(), TArrayF()
9335 {
9336  ((TH1F&)h).Copy(*this);
9337 }
9338 
9339 ////////////////////////////////////////////////////////////////////////////////
9340 /// Destructor.
9341 
9342 TH1F::~TH1F()
9343 {
9345 
9346 ////////////////////////////////////////////////////////////////////////////////
9347 /// Copy this to newth1.
9348 
9349 void TH1F::Copy(TObject &newth1) const
9350 {
9351  TH1::Copy(newth1);
9352 }
9353 
9354 ////////////////////////////////////////////////////////////////////////////////
9355 /// Reset.
9356 
9357 void TH1F::Reset(Option_t *option)
9358 {
9359  TH1::Reset(option);
9360  TArrayF::Reset();
9361 }
9362 
9363 ////////////////////////////////////////////////////////////////////////////////
9364 /// Set total number of bins including under/overflow
9365 /// Reallocate bin contents array
9366 
9368 {
9369  if (n < 0) n = fXaxis.GetNbins() + 2;
9370  fNcells = n;
9371  TArrayF::Set(n);
9372 }
9373 
9374 ////////////////////////////////////////////////////////////////////////////////
9375 /// Operator =
9376 
9377 TH1F& TH1F::operator=(const TH1F &h1)
9378 {
9379  if (this != &h1) ((TH1F&)h1).Copy(*this);
9380  return *this;
9381 }
9382 
9383 ////////////////////////////////////////////////////////////////////////////////
9384 /// Operator *
9385 
9386 TH1F operator*(Double_t c1, const TH1F &h1)
9387 {
9388  TH1F hnew = h1;
9389  hnew.Scale(c1);
9390  hnew.SetDirectory(0);
9391  return hnew;
9392 }
9393 
9394 ////////////////////////////////////////////////////////////////////////////////
9395 /// Operator +
9396 
9397 TH1F operator+(const TH1F &h1, const TH1F &h2)
9398 {
9399  TH1F hnew = h1;
9400  hnew.Add(&h2,1);
9401  hnew.SetDirectory(0);
9402  return hnew;
9403 }
9404 
9405 ////////////////////////////////////////////////////////////////////////////////
9406 /// Operator -
9407 
9408 TH1F operator-(const TH1F &h1, const TH1F &h2)
9409 {
9410  TH1F hnew = h1;
9411  hnew.Add(&h2,-1);
9412  hnew.SetDirectory(0);
9413  return hnew;
9414 }
9415 
9416 ////////////////////////////////////////////////////////////////////////////////
9417 /// Operator *
9418 
9419 TH1F operator*(const TH1F &h1, const TH1F &h2)
9420 {
9421  TH1F hnew = h1;
9422  hnew.Multiply(&h2);
9423  hnew.SetDirectory(0);
9424  return hnew;
9425 }
9426 
9427 ////////////////////////////////////////////////////////////////////////////////
9428 /// Operator /
9429 
9430 TH1F operator/(const TH1F &h1, const TH1F &h2)
9431 {
9432  TH1F hnew = h1;
9433  hnew.Divide(&h2);
9434  hnew.SetDirectory(0);
9435  return hnew;
9436 }
9437 
9438 //______________________________________________________________________________
9439 // TH1D methods
9440 // TH1D : histograms with one double per channel. Maximum precision 14 digits
9441 //______________________________________________________________________________
9442 
9443 ClassImp(TH1D);
9444 
9445 ////////////////////////////////////////////////////////////////////////////////
9446 /// Constructor.
9447 
9448 TH1D::TH1D(): TH1(), TArrayD()
9449 {
9450  fDimension = 1;
9451  SetBinsLength(3);
9452  if (fgDefaultSumw2) Sumw2();
9453 }
9454 
9455 ////////////////////////////////////////////////////////////////////////////////
9456 /// Create a 1-Dim histogram with fix bins of type double
9457 /// (see TH1::TH1 for explanation of parameters)
9458 
9459 TH1D::TH1D(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9460 : TH1(name,title,nbins,xlow,xup)
9462  fDimension = 1;
9463  TArrayD::Set(fNcells);
9464 
9465  if (xlow >= xup) SetBuffer(fgBufferSize);
9466  if (fgDefaultSumw2) Sumw2();
9467 }
9468 
9469 ////////////////////////////////////////////////////////////////////////////////
9470 /// Create a 1-Dim histogram with variable bins of type double
9471 /// (see TH1::TH1 for explanation of parameters)
9472 
9473 TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9474 : TH1(name,title,nbins,xbins)
9476  fDimension = 1;
9477  TArrayD::Set(fNcells);
9478  if (fgDefaultSumw2) Sumw2();
9479 }
9480 
9481 ////////////////////////////////////////////////////////////////////////////////
9482 /// Create a 1-Dim histogram with variable bins of type double
9483 /// (see TH1::TH1 for explanation of parameters)
9484 
9485 TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9486 : TH1(name,title,nbins,xbins)
9488  fDimension = 1;
9489  TArrayD::Set(fNcells);
9490  if (fgDefaultSumw2) Sumw2();
9491 }
9492 
9493 ////////////////////////////////////////////////////////////////////////////////
9494 /// Create a histogram from a TVectorD
9495 /// by default the histogram name is "TVectorD" and title = ""
9496 
9497 TH1D::TH1D(const TVectorD &v)
9498 : TH1("TVectorD","",v.GetNrows(),0,v.GetNrows())
9500  TArrayD::Set(fNcells);
9501  fDimension = 1;
9502  Int_t ivlow = v.GetLwb();
9503  for (Int_t i=0;i<fNcells-2;i++) {
9504  SetBinContent(i+1,v(i+ivlow));
9505  }
9506  TArrayD::Set(fNcells);
9507  if (fgDefaultSumw2) Sumw2();
9508 }
9509 
9510 ////////////////////////////////////////////////////////////////////////////////
9511 /// Destructor.
9512 
9513 TH1D::~TH1D()
9514 {
9516 
9517 ////////////////////////////////////////////////////////////////////////////////
9518 /// Constructor.
9519 
9520 TH1D::TH1D(const TH1D &h1d) : TH1(), TArrayD()
9521 {
9522  ((TH1D&)h1d).Copy(*this);
9523 }
9524 
9525 ////////////////////////////////////////////////////////////////////////////////
9526 /// Copy this to newth1
9527 
9528 void TH1D::Copy(TObject &newth1) const
9529 {
9530  TH1::Copy(newth1);
9531 }
9532 
9533 ////////////////////////////////////////////////////////////////////////////////
9534 /// Reset.
9535 
9536 void TH1D::Reset(Option_t *option)
9537 {
9538  TH1::Reset(option);
9539  TArrayD::Reset();
9540 }
9541 
9542 ////////////////////////////////////////////////////////////////////////////////
9543 /// Set total number of bins including under/overflow
9544 /// Reallocate bin contents array
9545 
9547 {
9548  if (n < 0) n = fXaxis.GetNbins() + 2;
9549  fNcells = n;
9550  TArrayD::Set(n);
9551 }
9552 
9553 ////////////////////////////////////////////////////////////////////////////////
9554 /// Operator =
9555 
9556 TH1D& TH1D::operator=(const TH1D &h1)
9557 {
9558  if (this != &h1) ((TH1D&)h1).Copy(*this);
9559  return *this;
9560 }
9561 
9562 ////////////////////////////////////////////////////////////////////////////////
9563 /// Operator *
9564 
9565 TH1D operator*(Double_t c1, const TH1D &h1)
9566 {
9567  TH1D hnew = h1;
9568  hnew.Scale(c1);
9569  hnew.SetDirectory(0);
9570  return hnew;
9571 }
9572 
9573 ////////////////////////////////////////////////////////////////////////////////
9574 /// Operator +
9575 
9576 TH1D operator+(const TH1D &h1, const TH1D &h2)
9577 {
9578  TH1D hnew = h1;
9579  hnew.Add(&h2,1);
9580  hnew.SetDirectory(0);
9581  return hnew;
9582 }
9583 
9584 ////////////////////////////////////////////////////////////////////////////////
9585 /// Operator -
9586 
9587 TH1D operator-(const TH1D &h1, const TH1D &h2)
9588 {
9589  TH1D hnew = h1;
9590  hnew.Add(&h2,-1);
9591  hnew.SetDirectory(0);
9592  return hnew;
9593 }
9594 
9595 ////////////////////////////////////////////////////////////////////////////////
9596 /// Operator *
9597 
9598 TH1D operator*(const TH1D &h1, const TH1D &h2)
9599 {
9600  TH1D hnew = h1;
9601  hnew.Multiply(&h2);
9602  hnew.SetDirectory(0);
9603  return hnew;
9604 }
9605 
9606 ////////////////////////////////////////////////////////////////////////////////
9607 /// Operator /
9608 
9609 TH1D operator/(const TH1D &h1, const TH1D &h2)
9610 {
9611  TH1D hnew = h1;
9612  hnew.Divide(&h2);
9613  hnew.SetDirectory(0);
9614  return hnew;
9615 }
9616 
9617 ////////////////////////////////////////////////////////////////////////////////
9618 ///return pointer to histogram with name
9619 ///hid if id >=0
9620 ///h_id if id <0
9621 
9622 TH1 *R__H(Int_t hid)
9623 {
9624  TString hname;
9625  if(hid >= 0) hname.Form("h%d",hid);
9626  else hname.Form("h_%d",hid);
9627  return (TH1*)gDirectory->Get(hname);
9628 }
9629 
9630 ////////////////////////////////////////////////////////////////////////////////
9631 ///return pointer to histogram with name hname
9632 
9633 TH1 *R__H(const char * hname)
9634 {
9635  return (TH1*)gDirectory->Get(hname);
9636 }
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:6365
TString fTitle
Definition: TNamed.h:33
Abstract array base class.
Definition: TArray.h:31
virtual void Browse(TBrowser *b)
Browse the Histogram object.
Definition: TH1.cxx:712
virtual void SavePrimitive(std::ostream &out, Option_t *option="")
Save primitive as a C++ statement(s) on output stream out.
Definition: TH1.cxx:6596
virtual void SetTitleOffset(Float_t offset=1)
Set distance between the axis and the axis title Offset is a correction factor with respect to the "s...
Definition: TAttAxis.cxx:294
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:47
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9548
virtual void Print(Option_t *option="") const
Print some global quantities for this histogram.
Definition: TH1.cxx:6449
virtual void SetNameTitle(const char *name, const char *title)
Change the name and title of this histogram.
Definition: TH1.cxx:8229
virtual void SetLineWidth(Width_t lwidth)
Set the line width.
Definition: TAttLine.h:43
virtual UInt_t GetUniqueID() const
Return the unique object id.
Definition: TObject.cxx:375
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:3563
virtual Float_t GetTickLength() const
Definition: TAttAxis.h:44
virtual Int_t GetNcells() const
Definition: TH1.h:285
Double_t fNormFactor
Normalization factor.
Definition: TH1.h:92
virtual void SetBarOffset(Float_t offset=0.25)
Definition: TH1.h:342
virtual void Scale(Double_t c1=1, Option_t *option="")
Multiply this histogram by a constant c1.
Definition: TH1.cxx:6061
virtual Int_t Fill(Double_t x)
Increment bin with abscissa X by 1.
Definition: TH1.cxx:3242
virtual Int_t ShowPeaks(Double_t sigma=2, Option_t *option="", Double_t threshold=0.05)
Interface to TSpectrum::Search.
Definition: TH1.cxx:8555
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:7805
TH1D & operator=(const TH1D &h1)
Operator =.
Definition: TH1.cxx:9558
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:7281
void SetBarWidth(Float_t barwidth=0.5)
Definition: TStyle.h:311
static long int sum(long int i)
Definition: Factory.cxx:2173
virtual void SaveAttributes(std::ostream &out, const char *name, const char *subname)
Save axis attributes as C++ statement(s) on output stream out.
Definition: TAxis.cxx:647
virtual Double_t GetEffectiveEntries() const
Number of effective entries of the histogram.
Definition: TH1.cxx:4201
virtual void Paint(Option_t *option="")
Control routine to paint any kind of histograms.
Definition: TH1.cxx:5661
float xmin
Definition: THbookFile.cxx:93
virtual void Delete(Option_t *option="")
Remove all objects from the list AND delete all heap based objects.
Definition: TList.cxx:467
virtual Double_t GetBinCenter(Int_t bin) const
Return bin center for 1D histogram.
Definition: TH1.cxx:8395
const char * GetBinLabel(Int_t bin) const
Return label for bin.
Definition: TAxis.cxx:426
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition: TObject.cxx:854
virtual Double_t PoissonD(Double_t mean)
Generates a random number according to a Poisson law.
Definition: TRandom.cxx:435
Bool_t IsBinUnderflow(Int_t bin, Int_t axis=0) const
Return true if the bin is underflow.
Definition: TH1.cxx:4895
Double_t Floor(Double_t x)
Definition: TMath.h:599
void Set(Int_t n)
Set size of this array to n chars.
Definition: TArrayC.cxx:105
virtual ~TH1I()
Destructor.
Definition: TH1.cxx:9137
Int_t GetFirst() const
Return first bin on the axis i.e.
Definition: TAxis.cxx:444
long long Long64_t
Definition: RtypesCore.h:69
virtual Int_t AutoP2FindLimits(Double_t min, Double_t max)
Buffer-based estimate of the histogram range using the power of 2 algorithm.
Definition: TH1.cxx:1273
virtual void SetMaximum(Double_t maximum=-1111)
Definition: TH1.h:380
double Chisquare(const TH1 &h1, TF1 &f1, bool useRange, bool usePL=false)
compute the chi2 value for an histogram given a function (see TH1::Chisquare for the documentation) ...
Definition: HFitImpl.cxx:1018
auto * m
Definition: textangle.C:8
void UseCurrentStyle()
Copy current attributes from/to current style.
Definition: TH1.cxx:6826
void Copy(TArrayI &array) const
Definition: TArrayI.h:42
virtual void LabelsOption(Option_t *option="h", Option_t *axis="X")
Set option(s) to draw axis with labels.
Definition: TH1.cxx:5057
short Style_t
Definition: RtypesCore.h:76
virtual void SetLimits(Double_t xmin, Double_t xmax)
Definition: TAxis.h:154
Double_t Log(Double_t x)
Definition: TMath.h:648
Short_t fBarWidth
(1000*width) for bar charts or legos
Definition: TH1.h:84
short Version_t
Definition: RtypesCore.h:61
TH1C()
Constructor.
Definition: TH1.cxx:8727
Bool_t IsBinOverflow(Int_t bin, Int_t axis=0) const
Return true if the bin is overflow.
Definition: TH1.cxx:4863
static Bool_t fgDefaultSumw2
!flag to call TH1::Sumw2 automatically at histogram creation time
Definition: TH1.h:107
virtual Int_t DistancetoPrimitive(Int_t px, Int_t py)=0
Computes distance from point (px,py) to the object.
TVirtualHistPainter * GetPainter(Option_t *option="")
Return pointer to painter.
Definition: TH1.cxx:4222
virtual void FitPanel()
Display a panel with all histogram fit options.
Definition: TH1.cxx:4037
float Float_t
Definition: RtypesCore.h:53
virtual void SetDirectory(TDirectory *dir)
By default when an histogram is created, it is added to the list of histogram objects in the current ...
Definition: TH1.cxx:8192
virtual TF1 * GetFunction(const char *name) const
Return pointer to function with name.
Definition: TH1.cxx:8305
virtual Float_t GetLabelOffset() const
Definition: TAttAxis.h:40
Short_t * fArray
Definition: TArrayS.h:30
const char Option_t
Definition: RtypesCore.h:62
virtual Float_t GetBarOffset() const
Definition: TH1.h:241
virtual Double_t GetBinLowEdge(Int_t bin) const
Return low edge of bin.
Definition: TAxis.cxx:504
Double_t KolmogorovProb(Double_t z)
Calculates the Kolmogorov distribution function,.
Definition: TMath.cxx:665
return c1
Definition: legend1.C:41
void Reset()
Definition: TArrayD.h:47
float ymin
Definition: THbookFile.cxx:93
virtual void ResetAttAxis(Option_t *option="")
Reset axis attributes.
Definition: TAttAxis.cxx:79
Double_t QuietNaN()
Definition: TMath.h:783
virtual void SetError(const Double_t *error)
Replace bin errors by values in array error.
Definition: TH1.cxx:8206
virtual Double_t GetNormFactor() const
Definition: TH1.h:286
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition: TString.h:638
TAxis fYaxis
Y axis descriptor.
Definition: TH1.h:81
virtual Int_t BufferFill(Double_t x, Double_t w)
accumulate arguments in buffer.
Definition: TH1.cxx:1434
virtual void SetContour(Int_t nlevels, const Double_t *levels=0)
Set the number and values of contour levels.
Definition: TH1.cxx:7746
R__EXTERN TStyle * gStyle
Definition: TStyle.h:402
virtual void PutStats(Double_t *stats)
Replace current statistics with the values in array stats.
Definition: TH1.cxx:7200
void SetHistLineWidth(Width_t width=1)
Definition: TStyle.h:357
const Double_t * GetArray() const
Definition: TArrayD.h:43
TList * fFunctions
->Pointer to list of functions (fits and user)
Definition: TH1.h:96
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:3641
virtual void SetBins(Int_t nx, Double_t xmin, Double_t xmax)
Redefine x axis parameters.
Definition: TH1.cxx:8022
virtual Int_t GetXfirst() const
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition: TNamed.cxx:140
virtual Color_t GetAxisColor() const
Definition: TAttAxis.h:37
TH1 * h
Definition: legend2.C:5
TH1 * GetAsymmetry(TH1 *h2, Double_t c2=1, Double_t dc2=0)
Return an histogram containing the asymmetry of this histogram with h2, where the asymmetry is define...
Definition: TH1.cxx:4092
static Bool_t fgStatOverflows
!flag to use under/overflows in statistics
Definition: TH1.h:106
virtual TH1 * DrawNormalized(Option_t *option="", Double_t norm=1) const
Draw a normalized copy of this histogram.
Definition: TH1.cxx:3042
static Bool_t SameLimitsAndNBins(const TAxis &axis1, const TAxis &axis2)
Same limits and bins.
Definition: TH1.cxx:5342
virtual ~TH1F()
Destructor.
Definition: TH1.cxx:9344
virtual void SetLabelColor(Color_t color=1, Float_t alpha=1.)
Set color of labels.
Definition: TAttAxis.cxx:173
void Build()
Creates histogram basic data structure.
Definition: TH1.cxx:721
virtual Double_t GetSumOfWeights() const
Return the sum of weights excluding under/overflows.
Definition: TH1.cxx:7230
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
Definition: TH1.cxx:4761
virtual void SetNdivisions(Int_t n=510, Bool_t optim=kTRUE)
Set the number of divisions for this axis.
Definition: TAttAxis.cxx:229
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:8809
TVectorT.
Definition: TMatrixTBase.h:77
virtual Int_t GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum=0)
Compute Quantiles for this histogram Quantile x_q of a probability distribution Function F is defined...
Definition: TH1.cxx:4313
virtual Double_t Integral(Option_t *option="") const
Return integral of bin contents.
Definition: TH1.cxx:7254
void ToUpper()
Change string to upper case.
Definition: TString.cxx:1112
virtual void Reset(Option_t *option="")
Reset.
Definition: TH1.cxx:8817
TH1D()
Constructor.
Definition: TH1.cxx:9450
static bool CheckAxisLimits(const TAxis *a1, const TAxis *a2)
Check that the axis limits of the histograms are the same.
Definition: TH1.cxx:1527
Buffer base class used for serializing objects.
Definition: TBuffer.h:40
virtual Double_t GetMeanError(Int_t axis=1) const
Return standard error of mean of this histogram along the X axis.
Definition: TH1.cxx:6921
virtual Int_t GetNbinsZ() const
Definition: TH1.h:284
TH1F()
Constructor.
Definition: TH1.cxx:9271
#define R__ASSERT(e)
Definition: TError.h:96
virtual void SetMinimum(Double_t minimum=-1111)
Definition: TH1.h:381
static THLimitsFinder * GetLimitsFinder()
Return pointer to the current finder.
#define gROOT
Definition: TROOT.h:393
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:6890
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition: TString.h:585
R__ALWAYS_INLINE Bool_t TestBit(UInt_t f) const
Definition: TObject.h:172
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9530
Int_t LoadPlugin()
Load the plugin library for this handler.
virtual void GetBinXYZ(Int_t binglobal, Int_t &binx, Int_t &biny, Int_t &binz) const
Return binx, biny, binz corresponding to the global bin number globalbin see TH1::GetBin function abo...
Definition: TH1.cxx:4676
double gamma_quantile_c(double z, double alpha, double theta)
Inverse ( ) of the cumulative distribution function of the upper tail of the gamma distribution (gamm...
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9351
Basic string class.
Definition: TString.h:125
static Bool_t AddDirectoryStatus()
Static function: cannot be inlined on Windows/NT.
Definition: TH1.cxx:704
1-D histogram with a float per channel (see TH1 documentation)}
Definition: TH1.h:556
1-D histogram with a short per channel (see TH1 documentation)
Definition: TH1.h:474
void H1InitExpo()
Compute Initial values of parameters for an exponential.
Definition: TH1.cxx:4419
Array of floats (32 bits per element).
Definition: TArrayF.h:27
static Double_t AutoP2GetPower2(Double_t x, Bool_t next=kTRUE)
Auxilliary function to get the power of 2 next (larger) or previous (smaller) a given x...
Definition: TH1.cxx:1237
virtual void SetTitleFont(Style_t font=62)
Set the title font.
Definition: TAttAxis.cxx:322
Short_t Min(Short_t a, Short_t b)
Definition: TMathBase.h:168
void ToLower()
Change string to lower-case.
Definition: TString.cxx:1099
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
void SetBarOffset(Float_t baroff=0.5)
Definition: TStyle.h:310
R__EXTERN TVirtualMutex * gROOTMutex
Definition: TROOT.h:57
void Copy(TAttMarker &attmarker) const
Copy this marker attributes to a new TAttMarker.
Definition: TAttMarker.cxx:209
virtual TH1 * DrawCopy(Option_t *option="", const char *name_postfix="_copy") const
Copy this histogram and Draw in the current pad.
Definition: TH1.cxx:3014
virtual void SetFillStyle(Style_t fstyle)
Set the fill area style.
Definition: TAttFill.h:39
virtual void Smooth(Int_t ntimes=1, Option_t *option="")
Smooth bin contents of this histogram.
Definition: TH1.cxx:6319
#define gInterpreter
Definition: TInterpreter.h:526
Bool_t IsNaN(Double_t x)
Definition: TMath.h:777
TArrayD fSumw2
Array of sum of squares of weights.
Definition: TH1.h:94
user specified contour levels
Definition: TH1.h:152
virtual void UseCurrentStyle()
Set current style settings in this object This function is called when either TCanvas::UseCurrentStyl...
Definition: TObject.cxx:715
virtual void Copy(TObject &axis) const
Copy axis structure to another axis.
Definition: TAxis.cxx:208
void Copy(TArrayC &array) const
Definition: TArrayC.h:42
virtual Float_t GetLabelSize() const
Definition: TAttAxis.h:41
virtual Double_t GetBinLowEdge(Int_t bin) const
Return bin lower edge for 1D histogram.
Definition: TH1.cxx:8406
static Bool_t AlmostInteger(Double_t a, Double_t epsilon=0.00000001)
Test if a double is almost an integer.
Definition: TH1.cxx:5313
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9171
void Reset()
Definition: TArrayF.h:47
virtual Double_t Integral(Double_t a, Double_t b, Double_t epsrel=1.e-12)
IntegralOneDim or analytical integral.
Definition: TF1.cxx:2402
virtual Int_t FindGoodLimits(TH1 *h, Double_t xmin, Double_t xmax)
Compute the best axis limits for the X axis.
static Bool_t RecomputeAxisLimits(TAxis &destAxis, const TAxis &anAxis)
Finds new limits for the axis for the Merge function.
Definition: TH1.cxx:5353
TAxis fZaxis
Z axis descriptor.
Definition: TH1.h:82
virtual Bool_t Multiply(TF1 *h1, Double_t c1=1)
Performs the operation: this = this*c1*f1 if errors are defined (see TH1::Sumw2), errors are also rec...
Definition: TH1.cxx:5486
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9369
virtual TObject * Clone(const char *newname="") const
Make a clone of an collection using the Streamer facility.
Bool_t CanExtend() const
Definition: TAxis.h:82
virtual Double_t GetContourLevel(Int_t level) const
Return value of contour number level.
Definition: TH1.cxx:7693
TF1 * gF1
Definition: TH1.cxx:524
virtual void SetLabelOffset(Float_t offset=0.005)
Set distance between the axis and the labels The distance is expressed in per cent of the pad width...
Definition: TAttAxis.cxx:193
Short_t Abs(Short_t d)
Definition: TMathBase.h:108
virtual Width_t GetLineWidth() const
Return the line width.
Definition: TAttLine.h:35
don&#39;t draw stats box
Definition: TH1.h:151
Double_t Prob(Double_t chi2, Int_t ndf)
Computation of the probability for a certain Chi-squared (chi2) and number of degrees of freedom (ndf...
Definition: TMath.cxx:624
static bool CheckBinLimits(const TAxis *a1, const TAxis *a2)
Check bin limits.
Definition: TH1.cxx:1469
Array of integers (32 bits per element).
Definition: TArrayI.h:27
void Reset(Char_t val=0)
Definition: TArrayC.h:47
LongDouble_t Power(LongDouble_t x, LongDouble_t y)
Definition: TMath.h:627
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition: TObject.cxx:694
virtual void SetBuffer(Int_t buffersize, Option_t *option="")
Set the maximum number of entries to be kept in the buffer.
Definition: TH1.cxx:7721
Double_t fTsumwx2
Total Sum of weight*X*X.
Definition: TH1.h:89
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:7148
virtual Bool_t CanExtendAllAxes() const
Returns true if all axes are extendable.
Definition: TH1.cxx:6085
virtual void Reset(Option_t *option="")
Reset this histogram: contents, errors, etc.
Definition: TH1.cxx:6543
virtual TObject * FindObject(const char *name) const
Delete a TObjLink object.
Definition: TList.cxx:574
Width_t GetHistLineWidth() const
Definition: TStyle.h:221
static void AddDirectory(Bool_t add=kTRUE)
Sets the flag controlling the automatic add of histograms in memory.
Definition: TH1.cxx:1223
if object in a list can be deleted
Definition: TObject.h:58
virtual Double_t GetBinUpEdge(Int_t bin) const
Return up edge of bin.
Definition: TAxis.cxx:514
virtual void SetBarWidth(Float_t width=0.5)
Definition: TH1.h:343
virtual void SetLabelFont(Style_t font=62)
Set labels&#39; font.
Definition: TAttAxis.cxx:183
virtual void AppendPad(Option_t *option="")
Append graphics object to current pad.
Definition: TObject.cxx:105
static TVirtualHistPainter * HistPainter(TH1 *obj)
Static function returning a pointer to the current histogram painter.
virtual void SetPoint(Int_t ipoint, Double_t re, Double_t im=0)=0
virtual Style_t GetMarkerStyle() const
Return the marker style.
Definition: TAttMarker.h:32
TDirectory * fDirectory
!Pointer to directory holding this histogram
Definition: TH1.h:99
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:6137
Marker Attributes class.
Definition: TAttMarker.h:19
virtual Style_t GetTitleFont() const
Definition: TAttAxis.h:46
TH1C operator/(const TH1C &h1, const TH1C &h2)
Operator /.
Definition: TH1.cxx:8890
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:1576
virtual Style_t GetLineStyle() const
Return the line style.
Definition: TAttLine.h:34
virtual Int_t GetDimension() const
Definition: TH1.h:268
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:4815
virtual Int_t GetContour(Double_t *levels=0)
Return contour values into array levels if pointer levels is non zero.
Definition: TH1.cxx:7674
TH1C & operator=(const TH1C &h1)
Operator =.
Definition: TH1.cxx:8837
Double_t GetXmin() const
Definition: TAxis.h:133
virtual void Paint(Option_t *option="")=0
This method must be overridden if a class wants to paint itself.
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition: TObject.cxx:128
Fill Area Attributes class.
Definition: TAttFill.h:19
Double_t x[n]
Definition: legend1.C:17
static Int_t FitOptionsMake(Option_t *option, Foption_t &Foption)
Decode string choptin and fill fitOption structure.
Definition: TH1.cxx:4354
static TString Format(const char *fmt,...)
Static method which formats a string using a printf style format descriptor and return a TString...
Definition: TString.cxx:2365
virtual void Eval(TF1 *f1, Option_t *option="")
Evaluate function f1 at the center of bins of this histogram.
Definition: TH1.cxx:3090
void Class()
Definition: Class.C:29
THashList implements a hybrid collection class consisting of a hash table and a list to store TObject...
Definition: THashList.h:34
static Bool_t GetDefaultSumw2()
Return kTRUE if TH1::Sumw2 must be called when creating new histograms.
Definition: TH1.cxx:4168
void SetHistFillColor(Color_t color=1)
Definition: TStyle.h:353
virtual Bool_t GetTimeDisplay() const
Definition: TAxis.h:126
static void SetDefaultBufferSize(Int_t buffersize=1000)
Static function to set the default buffer size for automatic histograms.
Definition: TH1.cxx:6127
Use Power(2)-based algorithm for autobinning.
Definition: TH1.h:160
void Copy(TAttLine &attline) const
Copy this line attributes to a new TAttLine.
Definition: TAttLine.cxx:162
virtual void SaveLineAttributes(std::ostream &out, const char *name, Int_t coldef=1, Int_t stydef=1, Int_t widdef=1)
Save line attributes as C++ statement(s) on output stream out.
Definition: TAttLine.cxx:260
virtual Double_t Chi2Test(const TH1 *h2, Option_t *option="UU", Double_t *res=0) const
test for comparing weighted and unweighted histograms
Definition: TH1.cxx:1945
The TNamed class is the base class for all named ROOT classes.
Definition: TNamed.h:29
virtual ~TH1()
Histogram default destructor.
Definition: TH1.cxx:577
THashList * GetLabels() const
Definition: TAxis.h:117
Int_t GetOptFit() const
Definition: TStyle.h:228
Double_t Log10(Double_t x)
Definition: TMath.h:651
virtual void SetContourLevel(Int_t level, Double_t value)
Set value for one contour level.
Definition: TH1.cxx:7785
#define R__WRITE_LOCKGUARD(mutex)
virtual void GetCenter(Double_t *center) const
Return an array with the center of all bins.
Definition: TAxis.cxx:539
TH1I()
Constructor.
Definition: TH1.cxx:9089
Abstract interface to a histogram painter.
virtual Double_t GetBinCenter(Int_t bin) const
Return center of bin.
Definition: TAxis.cxx:464
virtual void SetMarkerColor(Color_t mcolor=1)
Set the marker color.
Definition: TAttMarker.h:38
Style_t GetHistFillStyle() const
Definition: TStyle.h:219
TH1S()
Constructor.
Definition: TH1.cxx:8908
TString & Append(const char *cs)
Definition: TString.h:495
virtual void GetLowEdge(Double_t *edge) const
Return an array with the lod edge of all bins.
Definition: TAxis.cxx:548
void Sort(Index n, const Element *a, Index *index, Bool_t down=kTRUE)
Definition: TMath.h:1150
Double_t * fArray
Definition: TArrayD.h:30
void H1InitGaus()
Compute Initial values of parameters for a gaussian.
Definition: TH1.cxx:4363
virtual Size_t GetMarkerSize() const
Return the marker size.
Definition: TAttMarker.h:33
R__EXTERN TVirtualRWMutex * gCoreMutex
virtual bool UseRWLock()
Set this collection to use a RW lock upon access, making it thread safe.
virtual void DrawPanel()=0
errors from Poisson interval at 95% CL (~ 2 sigma)
Definition: TH1.h:64
const Double_t sigma
TString fOption
histogram options
Definition: TH1.h:95
virtual void SaveMarkerAttributes(std::ostream &out, const char *name, Int_t coldef=1, Int_t stydef=1, Int_t sizdef=1)
Save line attributes as C++ statement(s) on output stream out.
Definition: TAttMarker.cxx:244
virtual Int_t * GetN() const =0
Float_t GetBarWidth() const
Definition: TStyle.h:169
virtual Bool_t FindNewAxisLimits(const TAxis *axis, const Double_t point, Double_t &newMin, Double_t &newMax)
finds new limits for the axis so that point is within the range and the limits are compatible with th...
Definition: TH1.cxx:5904
TH1F * h1
Definition: legend1.C:5
constexpr Double_t Pi()
Definition: TMath.h:40
virtual void SetContent(const Double_t *content)
Replace bin contents by the contents of array content.
Definition: TH1.cxx:7661
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:1198
virtual void ResetStats()
Reset the statistics including the number of entries and replace with values calculates from bin cont...
Definition: TH1.cxx:7215
void Set(Int_t n)
Set size of this array to n ints.
Definition: TArrayI.cxx:105
Double_t Infinity()
Definition: TMath.h:796
TArrayD fContour
Array to display contour levels.
Definition: TH1.h:93
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:8459
Int_t AxisChoice(Option_t *axis) const
Choose an axis according to "axis".
Definition: Haxis.cxx:14
virtual Double_t ComputeIntegral(Bool_t onlyPositive=false)
Compute integral (cumulative sum of bins) The result stored in fIntegral is used by the GetRandom fun...
Definition: TH1.cxx:2470
virtual void LabelsInflate(Option_t *axis="X")
Double the number of bins for axis.
Definition: TH1.cxx:4996
virtual Color_t GetLabelColor() const
Definition: TAttAxis.h:38
object has not been deleted
Definition: TObject.h:78
short Color_t
Definition: RtypesCore.h:79
virtual Double_t GetSkewness(Int_t axis=1) const
Definition: TH1.cxx:6995
virtual void SetTimeDisplay(Int_t value)
Definition: TAxis.h:161
Double_t fTsumwx
Total Sum of weight*X.
Definition: TH1.h:88
void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a)
Least squares lpolynomial fitting without weights.
Definition: TH1.cxx:4469
virtual Bool_t Divide(TF1 *f1, Double_t c1=1)
Performs the operation: this = this/(c1*f1) if errors are defined (see TH1::Sumw2), errors are also recalculated.
Definition: TH1.cxx:2722
virtual Int_t GetNdivisions() const
Definition: TAttAxis.h:36
static Int_t AutoP2GetBins(Int_t n)
Auxilliary function to get the next power of 2 integer value larger then n.
Definition: TH1.cxx:1250
static Bool_t fgAddDirectory
!flag to add histograms to the directory
Definition: TH1.h:105
virtual void SetUniqueID(UInt_t uid)
Set the unique object id.
Definition: TObject.cxx:705
A doubly linked list.
Definition: TList.h:44
void Set(Int_t n)
Set size of this array to n shorts.
Definition: TArrayS.cxx:105
virtual void GetMinimumAndMaximum(Double_t &min, Double_t &max) const
Retrieve the minimum and maximum values in the histogram.
Definition: TH1.cxx:7986
virtual Double_t Rndm()
Machine independent random number generator.
Definition: TRandom.cxx:533
virtual Double_t GetStdDevError(Int_t axis=1) const
Return error of standard deviation estimation for Normal distribution.
Definition: TH1.cxx:6982
Double_t fMinimum
Minimum value for plotting.
Definition: TH1.h:91
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:7488
virtual void ExtendAxis(Double_t x, TAxis *axis)
Histogram is resized along axis such that x is in the axis range.
Definition: TH1.cxx:5961
Bool_t AreEqualRel(Double_t af, Double_t bf, Double_t relPrec)
Definition: TMath.h:322
TH1 * GetCumulative(Bool_t forward=kTRUE, const char *suffix="_cumulative") const
Return a pointer to an histogram containing the cumulative The cumulative can be computed both in the...
Definition: TH1.cxx:2540
virtual TH1 * FFT(TH1 *h_output, Option_t *option)
This function allows to do discrete Fourier transforms of TH1 and TH2.
Definition: TH1.cxx:3182
virtual Int_t DistancetoPrimitive(Int_t px, Int_t py)
Compute distance from point px,py to a line.
Definition: TH1.cxx:2705
void Reset()
Definition: TArrayS.h:47
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:8971
virtual void SetLineColor(Color_t lcolor)
Set the line color.
Definition: TAttLine.h:40
Using a TBrowser one can browse all ROOT objects.
Definition: TBrowser.h:37
virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py)
Execute action corresponding to one event.
Definition: TH1.cxx:3138
Int_t fN
Definition: TArray.h:38
int isnan(double)
virtual Double_t * GetIntegral()
Return a pointer to the array of bins integral.
Definition: TH1.cxx:2518
NOTE: Must always be 0 !!!
Definition: TH1.h:69
virtual void SetRange(Int_t first=0, Int_t last=0)
Set the viewing range for the axis from bin first to last.
Definition: TAxis.cxx:903
void Clear(Option_t *option="")
Remove all objects from the list.
Definition: THashList.cxx:189
float ymax
Definition: THbookFile.cxx:93
std::string printValue(const TDatime *val)
Print a TDatime at the prompt.
Definition: TDatime.cxx:514
virtual void SetParLimits(Int_t ipar, Double_t parmin, Double_t parmax)
Set limits for parameter ipar.
Definition: TF1.cxx:3385
void Copy(TArrayF &array) const
Definition: TArrayF.h:42
void FillData(BinData &dv, const TH1 *hist, TF1 *func=0)
fill the data vector from a TH1.
virtual TObject * First() const
Return the first object in the list. Returns 0 when list is empty.
Definition: TList.cxx:655
virtual void FillRandom(const char *fname, Int_t ntimes=5000)
Fill histogram following distribution in function fname.
Definition: TH1.cxx:3412
void SetHistFillStyle(Style_t styl=0)
Definition: TStyle.h:355
Int_t GetLast() const
Return last bin on the axis i.e.
Definition: TAxis.cxx:455
static void SmoothArray(Int_t NN, Double_t *XX, Int_t ntimes=1)
Smooth array xx, translation of Hbook routine hsmoof.F based on algorithm 353QH twice presented by J...
Definition: TH1.cxx:6201
Class to manage histogram axis.
Definition: TAxis.h:30
virtual Double_t GetKurtosis(Int_t axis=1) const
Definition: TH1.cxx:7065
virtual void Draw(Option_t *option="")
Draw this histogram with options.
Definition: TH1.cxx:2967
static bool CheckBinLabels(const TAxis *a1, const TAxis *a2)
Check that axis have same labels.
Definition: TH1.cxx:1495
Array of shorts (16 bits per element).
Definition: TArrayS.h:27
virtual Double_t GetPointReal(Int_t ipoint, Bool_t fromInput=kFALSE) const =0
Int_t GetSize() const
Definition: TArray.h:47
SVector< double, 2 > v
Definition: Dict.h:5
if object ctor succeeded but object should not be used
Definition: TObject.h:68
TH1 * R__H(Int_t hid)
return pointer to histogram with name hid if id >=0 h_id if id <0
Definition: TH1.cxx:9624
virtual void SetFillColor(Color_t fcolor)
Set the fill area color.
Definition: TAttFill.h:37
auto * a
Definition: textangle.C:12
A 3-Dim function with parameters.
Definition: TF3.h:28
virtual Double_t GetBinWithContent(Double_t c, Int_t &binx, Int_t firstx=0, Int_t lastx=0, Double_t maxdiff=0) const
Compute first binx in the range [firstx,lastx] for which diff = abs(bin_content-c) <= maxdiff...
Definition: TH1.cxx:4786
void SetCanExtend(Bool_t canExtend)
Definition: TAxis.h:86
1-D histogram with an int per channel (see TH1 documentation)}
Definition: TH1.h:515
Long_t ExecPlugin(int nargs, const T &... params)
virtual TObject * Remove(TObject *obj)
Remove object from the list.
Definition: TList.cxx:818
virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py)=0
Execute action corresponding to an event at (px,py).
Provides an indirection to the TFitResult class and with a semantics identical to a TFitResult pointe...
Definition: TFitResultPtr.h:31
static TH1 * TransformHisto(TVirtualFFT *fft, TH1 *h_output, Option_t *option)
For a given transform (first parameter), fills the histogram (second parameter) with the transform ou...
Definition: TH1.cxx:8573
static TVirtualFFT * FFT(Int_t ndim, Int_t *n, Option_t *option)
Returns a pointer to the FFT of requested size and type.
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition: TObject.cxx:443
virtual void SetBinContent(Int_t bin, Double_t content)
Set bin content see convention for numbering bins in TH1::GetBin In case the bin number is greater th...
Definition: TH1.cxx:8475
Collection abstract base class.
Definition: TCollection.h:63
static Int_t fgBufferSize
!default buffer size for automatic histograms
Definition: TH1.h:104
TH1C operator-(const TH1C &h1, const TH1C &h2)
Operator -.
Definition: TH1.cxx:8868
virtual TH1 * Rebin(Int_t ngroup=2, const char *newname="", const Double_t *xbins=0)
Rebin this histogram.
Definition: TH1.cxx:5727
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:7374
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition: TString.cxx:2343
Double_t fEntries
Number of entries.
Definition: TH1.h:85
unsigned int UInt_t
Definition: RtypesCore.h:42
virtual void SaveFillAttributes(std::ostream &out, const char *name, Int_t coldef=1, Int_t stydef=1001)
Save fill attributes as C++ statement(s) on output stream out.
Definition: TAttFill.cxx:232
virtual Float_t GetTitleOffset() const
Definition: TAttAxis.h:42
virtual void LabelsDeflate(Option_t *axis="X")
Reduce the number of bins for the axis passed in the option to the number of bins having a label...
Definition: TH1.cxx:4926
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:3371
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:880
char * Form(const char *fmt,...)
virtual void Transform()=0
virtual Double_t Chisquare(TF1 *f1, Option_t *option="") const
Compute and return the chisquare of this histogram with respect to a function The chisquare is comput...
Definition: TH1.cxx:2432
Ssiz_t Length() const
Definition: TString.h:386
virtual void Append(TObject *obj, Bool_t replace=kFALSE)
Append object to this directory.
Definition: TDirectory.cxx:190
static TVirtualFitter * GetFitter()
static: return the current Fitter
virtual void Copy(TObject &hnew) const
Copy this histogram structure to newth1.
Definition: TH1.cxx:2583
virtual TH1 * ShowBackground(Int_t niter=20, Option_t *option="same")
This function calculates the background spectrum in this histogram.
Definition: TH1.cxx:8540
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9189
virtual ~TH1C()
Destructor.
Definition: TH1.cxx:8775
static void RejectPoint(Bool_t reject=kTRUE)
Static function to set the global flag to reject points the fgRejectPoint global flag is tested by al...
Definition: TF1.cxx:3591
short Short_t
Definition: RtypesCore.h:35
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:8990
virtual void SetMarkerStyle(Style_t mstyle=1)
Set the marker style.
Definition: TAttMarker.h:40
virtual Double_t GetContourLevelPad(Int_t level) const
Return the value of contour number "level" in Pad coordinates.
Definition: TH1.cxx:7703
TAxis * GetYaxis()
Definition: TH1.h:306
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition: BinData.h:53
float xmax
Definition: THbookFile.cxx:93
virtual TObject * At(Int_t idx) const
Returns the object at position idx. Returns 0 if idx is out of range.
Definition: TList.cxx:354
virtual Color_t GetTitleColor() const
Definition: TAttAxis.h:45
Double_t * fIntegral
!Integral of bins used by GetRandom
Definition: TH1.h:101
virtual void SetBinErrorOption(EBinErrorOpt type)
Definition: TH1.h:359
static bool CheckConsistency(const TH1 *h1, const TH1 *h2)
Check histogram compatibility.
Definition: TH1.cxx:1611
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:585
A 2-Dim function with parameters.
Definition: TF2.h:29
void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b)
Extracted from CERN Program library routine DSEQN.
Definition: TH1.cxx:4574
TH1()
Histogram default constructor.
Definition: TH1.cxx:550
R__EXTERN TRandom * gRandom
Definition: TRandom.h:62
1-D histogram with a double per channel (see TH1 documentation)}
Definition: TH1.h:599
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:4663
static Int_t GetDefaultBufferSize()
Static function return the default buffer size for automatic histograms the parameter fgBufferSize ma...
Definition: TH1.cxx:4159
virtual void SetAxisColor(Color_t color=1, Float_t alpha=1.)
Set color of the line axis and tick marks.
Definition: TAttAxis.cxx:163
TString fName
Definition: TNamed.h:32
virtual TObject * FindObject(const char *name) const
Search object named name in the list of functions.
Definition: TH1.cxx:3659
virtual void Rebuild(Option_t *option="")
Using the current bin info, recompute the arrays for contents and errors.
Definition: TH1.cxx:6527
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:3622
if object destructor must call RecursiveRemove()
Definition: TObject.h:60
virtual void SetLabelSize(Float_t size=0.04)
Set size of axis labels The size is expressed in per cent of the pad width.
Definition: TAttAxis.cxx:204
virtual void SetMarkerSize(Size_t msize=1)
Set the marker size.
Definition: TAttMarker.h:41
REAL epsilon
Definition: triangle.c:617
virtual void SetTitleColor(Color_t color=1)
Set color of axis title.
Definition: TAttAxis.cxx:313
constexpr Double_t E()
Definition: TMath.h:74
virtual TObjLink * FirstLink() const
Definition: TList.h:108
virtual void SetTitleSize(Float_t size=0.04)
Set size of axis title The size is expressed in per cent of the pad width.
Definition: TAttAxis.cxx:304
#define Printf
Definition: TGeoToOCC.h:18
virtual void RecursiveRemove(TObject *obj)
Recursively remove object from the list of functions.
Definition: TH1.cxx:6033
EBinErrorOpt fBinStatErrOpt
option for bin statistical errors
Definition: TH1.h:103
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:8693
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:7890
errors with Normal (Wald) approximation: errorUp=errorLow= sqrt(N)
Definition: TH1.h:62
const Bool_t kFALSE
Definition: RtypesCore.h:88
TVirtualFFT is an interface class for Fast Fourier Transforms.
Definition: TVirtualFFT.h:88
virtual Color_t GetLineColor() const
Return the line color.
Definition: TAttLine.h:33
virtual Int_t FindBin(Double_t x)
Find bin number corresponding to abscissa x.
Definition: TAxis.cxx:279
virtual void SetName(const char *name)
Change the name of this histogram.
Definition: TH1.cxx:8215
static TVirtualFFT * SineCosine(Int_t ndim, Int_t *n, Int_t *r2rkind, Option_t *option)
Returns a pointer to a sine or cosine transform of requested size and kind.
TString & Remove(Ssiz_t pos)
Definition: TString.h:619
virtual Int_t GetSumw2N() const
Definition: TH1.h:300
Double_t fTsumw2
Total Sum of squares of weights.
Definition: TH1.h:87
Color_t GetHistFillColor() const
Definition: TStyle.h:217
virtual Double_t Eval(Double_t x, Double_t y=0, Double_t z=0, Double_t t=0) const
Evaluate this function.
Definition: TF1.cxx:1334
virtual void GetPointComplex(Int_t ipoint, Double_t &re, Double_t &im, Bool_t fromInput=kFALSE) const =0
Bin contents are average (used by Add)
Definition: TH1.h:157
virtual Bool_t IsEmpty() const
Definition: TCollection.h:184
return c2
Definition: legend2.C:14
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width for 1D histogram.
Definition: TH1.cxx:8417
static const double x1[5]
virtual TObject * Remove(TObject *)
Remove an object from the in-memory list.
#define ClassImp(name)
Definition: Rtypes.h:359
class describing the range in the coordinates it supports multiple range in a coordinate.
Definition: DataRange.h:34
virtual Double_t GetBinErrorLow(Int_t bin) const
Return lower error associated to bin number bin.
Definition: TH1.cxx:8333
double Double_t
Definition: RtypesCore.h:55
Int_t GetOptStat() const
Definition: TStyle.h:229
Int_t * fArray
Definition: TArrayI.h:30
void SetHistLineStyle(Style_t styl=0)
Definition: TStyle.h:356
virtual void SavePrimitiveHelp(std::ostream &out, const char *hname, Option_t *option="")
Helper function for the SavePrimitive functions from TH1 or classes derived from TH1, eg TProfile, TProfile2D.
Definition: TH1.cxx:6738
Double_t fTsumw
Total Sum of weights.
Definition: TH1.h:86
Color_t GetHistLineColor() const
Definition: TStyle.h:218
Describe directory structure in memory.
Definition: TDirectory.h:34
Histogram is forced to be not weighted even when the histogram is filled with weighted different than...
Definition: TH1.h:158
R__EXTERN TEnv * gEnv
Definition: TEnv.h:171
Double_t Median(Long64_t n, const T *a, const Double_t *w=0, Long64_t *work=0)
Definition: TMath.h:1225
unsigned long ULong_t
Definition: RtypesCore.h:51
int nentries
Definition: THbookFile.cxx:89
Double_t y[n]
Definition: legend1.C:17
virtual Color_t GetFillColor() const
Return the fill area color.
Definition: TAttFill.h:30
TH1I & operator=(const TH1I &h1)
Operator =.
Definition: TH1.cxx:9199
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:570
The TH1 histogram class.
Definition: TH1.h:56
static constexpr double s
you should not use this method at all Int_t Int_t Double_t Double_t Double_t e
Definition: TRolke.cxx:630
virtual Double_t GetEntries() const
Return the current number of entries.
Definition: TH1.cxx:4176
#define R__LOCKGUARD(mutex)
void forward(const LAYERDATA &prevLayerData, LAYERDATA &currLayerData)
apply the weights (and functions) in forward direction of the DNN
Definition: NeuralNet.icc:545
THist< 2, double, THistStatContent, THistStatUncertainty > TH2D
Definition: THist.hxx:290
virtual Float_t GetTitleSize() const
Definition: TAttAxis.h:43
virtual Double_t Chi2TestX(const TH1 *h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option="UU", Double_t *res=0) const
The computation routine of the Chisquare test.
Definition: TH1.cxx:2004
static bool IsEquidistantBinning(const TAxis &axis)
Test if the binning is equidistant.
Definition: TH1.cxx:5322
Short_t fBarOffset
(1000*offset) for bar charts or legos
Definition: TH1.h:83
virtual void SetLineStyle(Style_t lstyle)
Set the line style.
Definition: TAttLine.h:42
double Stat_t
Definition: RtypesCore.h:73
Array of doubles (64 bits per element).
Definition: TArrayD.h:27
Bool_t IsNull() const
Definition: TString.h:383
void FitOptionsMake(EFitObjectType type, const char *option, Foption_t &fitOption)
Decode list of options into fitOption.
Definition: HFitImpl.cxx:681
virtual void InitArgs(const Double_t *x, const Double_t *params)
Initialize parameters addresses.
Definition: TF1.cxx:2354
virtual Bool_t Add(TF1 *h1, Double_t c1=1, Option_t *option="")
Performs the operation: this = this + c1*f1 if errors are defined (see TH1::Sumw2), errors are also recalculated.
Definition: TH1.cxx:775
Abstract Base Class for Fitting.
TAxis * GetZaxis()
Definition: TH1.h:307
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:6098
TH1C operator+(const TH1C &h1, const TH1C &h2)
Operator +.
Definition: TH1.cxx:8857
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:3596
Mother of all ROOT objects.
Definition: TObject.h:37
virtual Int_t FindFixBin(Double_t x) const
Find bin number corresponding to abscissa x.
Definition: TAxis.cxx:405
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9008
you should not use this method at all Int_t Int_t z
Definition: TRolke.cxx:630
Bool_t IsReading() const
Definition: TStyle.h:274
virtual void ClearUnderflowAndOverflow()
Remove all the content from the underflow and overflow bins, without changing the number of entries A...
Definition: TH1.cxx:2451
virtual Bool_t IsInside(const Double_t *x) const
return kTRUE if the point is inside the function range
Definition: TF1.h:582
char Char_t
Definition: RtypesCore.h:29
virtual char * GetObjectInfo(Int_t px, Int_t py) const
Redefines TObject::GetObjectInfo.
Definition: TH1.cxx:4213
TH1S & operator=(const TH1S &h1)
Operator =.
Definition: TH1.cxx:9018
virtual Int_t GetNpar() const
Definition: TF1.h:465
Style_t GetHistLineStyle() const
Definition: TStyle.h:220
Double_t fMaximum
Maximum value for plotting.
Definition: TH1.h:90
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width.
Definition: TAxis.cxx:526
virtual void DirectoryAutoAdd(TDirectory *)
Perform the automatic addition of the histogram to the given directory.
Definition: TH1.cxx:2683
TVirtualHistPainter * fPainter
!pointer to histogram painter
Definition: TH1.h:102
virtual void Copy(TObject &named) const
Copy this to obj.
Definition: TNamed.cxx:94
static Bool_t RejectedPoint()
See TF1::RejectPoint above.
Definition: TF1.cxx:3600
virtual void DrawPanel()
Display a panel with all histogram drawing options.
Definition: TH1.cxx:3073
virtual void Add(TObject *obj)
Definition: TList.h:87
auto * l
Definition: textangle.C:4
Int_t fBufferSize
fBuffer size
Definition: TH1.h:97
virtual void RecursiveRemove(TObject *obj)
Remove object from this collection and recursively remove the object from all other objects (and coll...
Definition: TList.cxx:760
virtual Int_t GetMinimumBin() const
Return location of bin with minimum value in the range.
Definition: TH1.cxx:7920
virtual Double_t GetBinErrorSqUnchecked(Int_t bin) const
Definition: TH1.h:424
virtual void GetRange(Double_t *xmin, Double_t *xmax) const
Return range of a generic N-D function.
Definition: TF1.cxx:2163
virtual Double_t DoIntegral(Int_t ix1, Int_t ix2, Int_t iy1, Int_t iy2, Int_t iz1, Int_t iz2, Double_t &err, Option_t *opt, Bool_t doerr=kFALSE) const
Internal function compute integral and optionally the error between the limits specified by the bin n...
Definition: TH1.cxx:7290
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:3345
Short_t Max(Short_t a, Short_t b)
Definition: TMathBase.h:200
1-Dim function class
Definition: TF1.h:211
virtual void SetBinsLength(Int_t=-1)
Definition: TH1.h:358
Char_t * fArray
Definition: TArrayC.h:30
1-D histogram with a byte per channel (see TH1 documentation)
Definition: TH1.h:433
virtual void Sumw2(Bool_t flag=kTRUE)
Create structure to store sum of squares of weights.
Definition: TH1.cxx:8274
TObject * Clone(const char *newname=0) const
Make a complete copy of the underlying object.
Definition: TH1.cxx:2660
TF1 * f1
Definition: legend1.C:11
you should not use this method at all Int_t Int_t Double_t Double_t Double_t Int_t Double_t Double_t Double_t Double_t b
Definition: TRolke.cxx:630
Double_t GetAt(Int_t i) const
Definition: TArrayD.h:45
Double_t Ceil(Double_t x)
Definition: TMath.h:593
void SetOptStat(Int_t stat=1)
The type of information printed in the histogram statistics box can be selected via the parameter mod...
Definition: TStyle.cxx:1266
Int_t fDimension
!Histogram dimension (1, 2 or 3 dim)
Definition: TH1.h:100
THist< 1, double, THistStatContent, THistStatUncertainty > TH1D
Definition: THist.hxx:284
#define gPad
Definition: TVirtualPad.h:285
void Reset()
Definition: TArrayI.h:47
virtual void SetTickLength(Float_t length=0.03)
Set tick mark length The length is expressed in per cent of the pad width.
Definition: TAttAxis.cxx:280
virtual Int_t GetXlast() const
virtual Double_t GetBinErrorUp(Int_t bin) const
Return upper error associated to bin number bin.
Definition: TH1.cxx:8364
virtual Int_t BufferEmpty(Int_t action=0)
Fill histogram with all entries in the buffer.
Definition: TH1.cxx:1344
virtual void SetParent(TObject *obj)
Definition: TAxis.h:157
void Set(Int_t n)
Set size of this array to n floats.
Definition: TArrayF.cxx:105
virtual ~TH1D()
Destructor.
Definition: TH1.cxx:9515
virtual void SetEntries(Double_t n)
Definition: TH1.h:368
TAxis fXaxis
X axis descriptor.
Definition: TH1.h:80
Float_t GetBarOffset() const
Definition: TStyle.h:168
#define gDirectory
Definition: TDirectory.h:213
virtual TH1 * GetHistogram() const
Return a pointer to the histogram used to visualise the function.
Definition: TF1.cxx:1469
void ResetBit(UInt_t f)
Definition: TObject.h:171
virtual void SetParameter(Int_t param, Double_t value)
Definition: TF1.h:618
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:9152
virtual void SetTitle(const char *title)
Change (i.e.
Definition: TH1.cxx:6152
TFitResultPtr FitObject(TH1 *h1, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption, const char *goption, ROOT::Fit::DataRange &range)
fitting function for a TH1 (called from TH1::Fit)
Definition: HFitImpl.cxx:964
virtual Int_t GetNdim() const =0
virtual Color_t GetMarkerColor() const
Return the marker color.
Definition: TAttMarker.h:31
Definition: first.py:1
virtual Int_t GetNbinsX() const
Definition: TH1.h:282
virtual Int_t Poisson(Double_t mean)
Generates a random integer N according to a Poisson law.
Definition: TRandom.cxx:383
virtual Style_t GetFillStyle() const
Return the fill area style.
Definition: TAttFill.h:31
Double_t Sqrt(Double_t x)
Definition: TMath.h:590
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:8790
Int_t GetNbins() const
Definition: TAxis.h:121
Bool_t GetCanvasPreferGL() const
Definition: TStyle.h:173
virtual const char * GetName() const
Returns name of object.
Definition: TObject.cxx:357
virtual Int_t GetSize() const
Definition: TCollection.h:180
virtual void Set(Int_t nbins, Double_t xmin, Double_t xmax)
Initialize axis with fix bins.
Definition: TAxis.cxx:717
float * q
Definition: THbookFile.cxx:87
static Bool_t AlmostEqual(Double_t a, Double_t b, Double_t epsilon=0.00000001)
Test if two double are almost equal.
Definition: TH1.cxx:5305
virtual Double_t EvalPar(const Double_t *x, const Double_t *params=0)
Evaluate function with given coordinates and parameters.
Definition: TF1.cxx:1363
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition: TNamed.cxx:164
TList * GetListOfFunctions() const
Definition: TH1.h:229
void SetHistLineColor(Color_t color=1)
Definition: TStyle.h:354
virtual TObject * GetUserFunc() const
virtual TObject * GetObjectFit() const
Double_t * fBuffer
[fBufferSize] entry buffer
Definition: TH1.h:98
virtual Int_t GetValue(const char *name, Int_t dflt) const
Returns the integer value for a resource.
Definition: TEnv.cxx:491
virtual TFitResultPtr Fit(const char *formula, Option_t *option="", Option_t *goption="", Double_t xmin=0, Double_t xmax=0)
Fit histogram with function fname.
Definition: TH1.cxx:3686
const Bool_t kTRUE
Definition: RtypesCore.h:87
Int_t Nint(T x)
Definition: TMath.h:606
void AbstractMethod(const char *method) const
Use this method to implement an "abstract" method that you don&#39;t want to leave purely abstract...
Definition: TObject.cxx:922
TH1C operator*(Double_t c1, const TH1C &h1)
Operator *.
Definition: TH1.cxx:8846
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:8703
virtual Double_t GetStdDev(Int_t axis=1) const
Returns the Standard Deviation (Sigma).
Definition: TH1.cxx:6944
void Set(Int_t n)
Set size of this array to n doubles.
Definition: TArrayD.cxx:106
virtual Double_t GetRandom() const
Return a random number distributed according the histogram bin contents.
Definition: TH1.cxx:4710
static bool CheckEqualAxes(const TAxis *a1, const TAxis *a2)
Check that the axis are the same.
Definition: TH1.cxx:1540
Double_t GetXmax() const
Definition: TAxis.h:134
double gamma_quantile(double z, double alpha, double theta)
Inverse ( ) of the cumulative distribution function of the lower tail of the gamma distribution (gamm...
virtual ~TH1S()
Destructor.
Definition: TH1.cxx:8956
void Copy(TArrayD &array) const
Definition: TArrayD.h:42
virtual Int_t GetMaximumBin() const
Return location of bin with maximum value in the range.
Definition: TH1.cxx:7835
const Int_t n
Definition: legend1.C:16
Line Attributes class.
Definition: TAttLine.h:18
virtual void GetCenter(Double_t *center) const
Fill array with center of bins for 1D histogram Better to use h1.GetXaxis().GetCenter(center) ...
Definition: TH1.cxx:8428
void H1InitPolynom()
Compute Initial values of parameters for a polynom.
Definition: TH1.cxx:4439
virtual void SetStats(Bool_t stats=kTRUE)
Set statistics option on/off.
Definition: TH1.cxx:8245
TH1F & operator=(const TH1F &h1)
Operator =.
Definition: TH1.cxx:9379
virtual Float_t GetBarWidth() const
Definition: TH1.h:242
Long64_t BinarySearch(Long64_t n, const T *array, T value)
Definition: TMath.h:1092
char name[80]
Definition: TGX11.cxx:109
const TArrayD * GetXbins() const
Definition: TAxis.h:130
virtual void GetLowEdge(Double_t *edge) const
Fill array with low edge of bins for 1D histogram Better to use h1.GetXaxis().GetLowEdge(edge) ...
Definition: TH1.cxx:8441
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:866
TAxis * GetXaxis()
Definition: TH1.h:305
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:8827
virtual Style_t GetLabelFont() const
Definition: TAttAxis.h:39
void Copy(TArrayS &array) const
Definition: TArrayS.h:42
virtual Long64_t Merge(TCollection *list)
Add all histograms in the collection to this histogram.
Definition: TH1.cxx:5462
double ldexp(double, int)
virtual const char * GetTitle() const
Returns title of object.
Definition: TNamed.h:48
virtual Int_t GetNbinsY() const
Definition: TH1.h:283
virtual Option_t * GetType() const =0
virtual Double_t GetBinError(Int_t bin) const
Return value of error associated to bin number bin.
Definition: TH1.cxx:8317
Int_t fNcells
number of bins(1D), cells (2D) +U/Overflows
Definition: TH1.h:79
void Copy(TAttFill &attfill) const
Copy this fill attributes to a new TAttFill.
Definition: TAttFill.cxx:200
void AndersonDarling2SamplesTest(Double_t &pvalue, Double_t &testStat) const
Definition: GoFTest.cxx:646
T MinElement(Long64_t n, const T *a)
Definition: TMath.h:829
void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
Least square linear fit without weights.
Definition: TH1.cxx:4528
const char * Data() const
Definition: TString.h:345
Array of chars or bytes (8 bits per element).
Definition: TArrayC.h:27
virtual void SavePrimitive(std::ostream &out, Option_t *option="")
Save a primitive as a C++ statement(s) on output stream "out".
Definition: TObject.cxx:664
Double_t ATan(Double_t)
Definition: TMath.h:577