Logo ROOT   6.10/09
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 
18 #include "Riostream.h"
19 #include "TROOT.h"
20 #include "TClass.h"
21 #include "TMath.h"
22 #include "THashList.h"
23 #include "TH1.h"
24 #include "TH2.h"
25 #include "TH3.h"
26 #include "TF2.h"
27 #include "TF3.h"
28 #include "TPluginManager.h"
29 #include "TVirtualPad.h"
30 #include "TRandom.h"
31 #include "TVirtualFitter.h"
32 #include "THLimitsFinder.h"
33 #include "TProfile.h"
34 #include "TStyle.h"
35 #include "TVectorF.h"
36 #include "TVectorD.h"
37 #include "TBrowser.h"
38 #include "TObjString.h"
39 #include "TError.h"
40 #include "TVirtualHistPainter.h"
41 #include "TVirtualFFT.h"
42 #include "TSystem.h"
43 
44 #include "HFitInterface.h"
45 #include "Fit/DataRange.h"
46 #include "Fit/BinData.h"
47 #include "Math/GoFTest.h"
48 #include "Math/MinimizerOptions.h"
49 #include "Math/QuantFuncMathCore.h"
50 
51 #include "TH1Merger.h"
52 
53 /** \addtogroup Hist
54 @{
55 \class TH1C
56 \brief tomato 1-D histogram with a byte per channel (see TH1 documentation)
57 \class TH1S
58 \brief tomato 1-D histogram with a short per channel (see TH1 documentation)
59 \class TH1I
60 \brief tomato 1-D histogram with an int per channel (see TH1 documentation)}
61 \class TH1F
62 \brief tomato 1-D histogram with a float per channel (see TH1 documentation)}
63 \class TH1D
64 \brief tomato 1-D histogram with a double per channel (see TH1 documentation)}
65 @}
66 */
67 
68 /** \class TH1
69 The TH1 histogram class.
70 
71 ### The Histogram classes
72 ROOT supports the following histogram types:
73 
74  - 1-D histograms:
75  - TH1C : histograms with one byte per channel. Maximum bin content = 127
76  - TH1S : histograms with one short per channel. Maximum bin content = 32767
77  - TH1I : histograms with one int per channel. Maximum bin content = 2147483647
78  - TH1F : histograms with one float per channel. Maximum precision 7 digits
79  - TH1D : histograms with one double per channel. Maximum precision 14 digits
80  - 2-D histograms:
81  - TH2C : histograms with one byte per channel. Maximum bin content = 127
82  - TH2S : histograms with one short per channel. Maximum bin content = 32767
83  - TH2I : histograms with one int per channel. Maximum bin content = 2147483647
84  - TH2F : histograms with one float per channel. Maximum precision 7 digits
85  - TH2D : histograms with one double per channel. Maximum precision 14 digits
86  - 3-D histograms:
87  - TH3C : histograms with one byte per channel. Maximum bin content = 127
88  - TH3S : histograms with one short per channel. Maximum bin content = 32767
89  - TH3I : histograms with one int per channel. Maximum bin content = 2147483647
90  - TH3F : histograms with one float per channel. Maximum precision 7 digits
91  - TH3D : histograms with one double per channel. Maximum precision 14 digits
92  - Profile histograms: See classes TProfile, TProfile2D and TProfile3D.
93  Profile histograms are used to display the mean value of Y and its standard deviation
94  for each bin in X. Profile histograms are in many cases an elegant
95  replacement of two-dimensional histograms : the inter-relation of two
96  measured quantities X and Y can always be visualized by a two-dimensional
97  histogram or scatter-plot; If Y is an unknown (but single-valued)
98  approximate function of X, this function is displayed by a profile
99  histogram with much better precision than by a scatter-plot.
100 
101 
102 All histogram classes are derived from the base class TH1
103 ~~~ {.cpp}
104  TH1
105  ^
106  |
107  |
108  |
109  +----------------+-------+------+------+-----+-----+
110  | | | | | | |
111  | | TH1C TH1S TH1I TH1F TH1D
112  | | |
113  | | |
114  | TH2 TProfile
115  | |
116  | |
117  | +-------+------+------+-----+-----+
118  | | | | | |
119  | TH2C TH2S TH2I TH2F TH2D
120  | |
121  TH3 |
122  | TProfile2D
123  |
124  +-------+------+------+------+------+
125  | | | | |
126  TH3C TH3S TH3I TH3F TH3D
127  |
128  |
129  TProfile3D
130 
131  The TH*C classes also inherit from the array class TArrayC.
132  The TH*S classes also inherit from the array class TArrayS.
133  The TH*I classes also inherit from the array class TArrayI.
134  The TH*F classes also inherit from the array class TArrayF.
135  The TH*D classes also inherit from the array class TArrayD.
136 ~~~
137 
138 #### Creating histograms
139 
140 Histograms are created by invoking one of the constructors, e.g.
141 ~~~ {.cpp}
142  TH1F *h1 = new TH1F("h1", "h1 title", 100, 0, 4.4);
143  TH2F *h2 = new TH2F("h2", "h2 title", 40, 0, 4, 30, -3, 3);
144 ~~~
145 Histograms may also be created by:
146 
147  - calling the Clone function, see below
148  - making a projection from a 2-D or 3-D histogram, see below
149  - reading an histogram from a file
150 
151  When an histogram is created, a reference to it is automatically added
152  to the list of in-memory objects for the current file or directory.
153  This default behaviour can be changed by:
154 ~~~ {.cpp}
155  h->SetDirectory(0); for the current histogram h
156  TH1::AddDirectory(kFALSE); sets a global switch disabling the reference
157 ~~~
158  When the histogram is deleted, the reference to it is removed from
159  the list of objects in memory.
160  When a file is closed, all histograms in memory associated with this file
161  are automatically deleted.
162 
163 #### Fix or variable bin size
164 
165  All histogram types support either fix or variable bin sizes.
166  2-D histograms may have fix size bins along X and variable size bins
167  along Y or vice-versa. The functions to fill, manipulate, draw or access
168  histograms are identical in both cases.
169 
170  Each histogram always contains 3 objects TAxis: fXaxis, fYaxis and fZaxis
171  o access the axis parameters, do:
172 ~~~ {.cpp}
173  TAxis *xaxis = h->GetXaxis(); etc.
174  Double_t binCenter = xaxis->GetBinCenter(bin), etc.
175 ~~~
176  See class TAxis for a description of all the access functions.
177  The axis range is always stored internally in double precision.
178 
179 #### Convention for numbering bins
180 
181  For all histogram types: nbins, xlow, xup
182 ~~~ {.cpp}
183  bin = 0; underflow bin
184  bin = 1; first bin with low-edge xlow INCLUDED
185  bin = nbins; last bin with upper-edge xup EXCLUDED
186  bin = nbins+1; overflow bin
187 ~~~
188  In case of 2-D or 3-D histograms, a "global bin" number is defined.
189  For example, assuming a 3-D histogram with (binx, biny, binz), the function
190 ~~~ {.cpp}
191  Int_t gbin = h->GetBin(binx, biny, binz);
192 ~~~
193  returns a global/linearized gbin number. This global gbin is useful
194  to access the bin content/error information independently of the dimension.
195  Note that to access the information other than bin content and errors
196  one should use the TAxis object directly with e.g.:
197 ~~~ {.cpp}
198  Double_t xcenter = h3->GetZaxis()->GetBinCenter(27);
199 ~~~
200  returns the center along z of bin number 27 (not the global bin)
201  in the 3-D histogram h3.
202 
203 #### Alphanumeric Bin Labels
204 
205  By default, an histogram axis is drawn with its numeric bin labels.
206  One can specify alphanumeric labels instead with:
207 
208  - call TAxis::SetBinLabel(bin, label);
209  This can always be done before or after filling.
210  When the histogram is drawn, bin labels will be automatically drawn.
211  See examples labels1.C and labels2.C
212  - call to a Fill function with one of the arguments being a string, e.g.
213 ~~~ {.cpp}
214  hist1->Fill(somename, weight);
215  hist2->Fill(x, somename, weight);
216  hist2->Fill(somename, y, weight);
217  hist2->Fill(somenamex, somenamey, weight);
218 ~~~
219  See examples hlabels1.C and hlabels2.C
220  - via TTree::Draw. see for example cernstaff.C
221 ~~~ {.cpp}
222  tree.Draw("Nation::Division");
223 ~~~
224  where "Nation" and "Division" are two branches of a Tree.
225 
226 When using the options 2 or 3 above, the labels are automatically
227  added to the list (THashList) of labels for a given axis.
228  By default, an axis is drawn with the order of bins corresponding
229  to the filling sequence. It is possible to reorder the axis
230 
231  - alphabetically
232  - by increasing or decreasing values
233 
234  The reordering can be triggered via the TAxis context menu by selecting
235  the menu item "LabelsOption" or by calling directly
236  TH1::LabelsOption(option, axis) where
237 
238  - axis may be "X", "Y" or "Z"
239  - option may be:
240  - "a" sort by alphabetic order
241  - ">" sort by decreasing values
242  - "<" sort by increasing values
243  - "h" draw labels horizontal
244  - "v" draw labels vertical
245  - "u" draw labels up (end of label right adjusted)
246  - "d" draw labels down (start of label left adjusted)
247 
248  When using the option 2 above, new labels are added by doubling the current
249  number of bins in case one label does not exist yet.
250  When the Filling is terminated, it is possible to trim the number
251  of bins to match the number of active labels by calling
252 ~~~ {.cpp}
253  TH1::LabelsDeflate(axis) with axis = "X", "Y" or "Z"
254 ~~~
255  This operation is automatic when using TTree::Draw.
256  Once bin labels have been created, they become persistent if the histogram
257  is written to a file or when generating the C++ code via SavePrimitive.
258 
259 #### Histograms with automatic bins
260 
261  When an histogram is created with an axis lower limit greater or equal
262  to its upper limit, the SetBuffer is automatically called with an
263  argument fBufferSize equal to fgBufferSize (default value=1000).
264  fgBufferSize may be reset via the static function TH1::SetDefaultBufferSize.
265  The axis limits will be automatically computed when the buffer will
266  be full or when the function BufferEmpty is called.
267 
268 #### Filling histograms
269 
270  An histogram is typically filled with statements like:
271 ~~~ {.cpp}
272  h1->Fill(x);
273  h1->Fill(x, w); //fill with weight
274  h2->Fill(x, y)
275  h2->Fill(x, y, w)
276  h3->Fill(x, y, z)
277  h3->Fill(x, y, z, w)
278 ~~~
279  or via one of the Fill functions accepting names described above.
280  The Fill functions compute the bin number corresponding to the given
281  x, y or z argument and increment this bin by the given weight.
282  The Fill functions return the bin number for 1-D histograms or global
283  bin number for 2-D and 3-D histograms.
284  If TH1::Sumw2 has been called before filling, the sum of squares of
285  weights is also stored.
286  One can also increment directly a bin number via TH1::AddBinContent
287  or replace the existing content via TH1::SetBinContent.
288  To access the bin content of a given bin, do:
289 ~~~ {.cpp}
290  Double_t binContent = h->GetBinContent(bin);
291 ~~~
292 
293  By default, the bin number is computed using the current axis ranges.
294  If the automatic binning option has been set via
295 ~~~ {.cpp}
296  h->SetCanExtend(kAllAxes);
297 ~~~
298  then, the Fill Function will automatically extend the axis range to
299  accomodate the new value specified in the Fill argument. The method
300  used is to double the bin size until the new value fits in the range,
301  merging bins two by two. This automatic binning options is extensively
302  used by the TTree::Draw function when histogramming Tree variables
303  with an unknown range.
304  This automatic binning option is supported for 1-D, 2-D and 3-D histograms.
305 
306  During filling, some statistics parameters are incremented to compute
307  the mean value and Root Mean Square with the maximum precision.
308 
309  In case of histograms of type TH1C, TH1S, TH2C, TH2S, TH3C, TH3S
310  a check is made that the bin contents do not exceed the maximum positive
311  capacity (127 or 32767). Histograms of all types may have positive
312  or/and negative bin contents.
313 
314 #### Rebinning
315  At any time, an histogram can be rebinned via TH1::Rebin. This function
316  returns a new histogram with the rebinned contents.
317  If bin errors were stored, they are recomputed during the rebinning.
318 
319 #### Associated errors
320  By default, for each bin, the sum of weights is computed at fill time.
321  One can also call TH1::Sumw2 to force the storage and computation
322  of the sum of the square of weights per bin.
323  If Sumw2 has been called, the error per bin is computed as the
324  sqrt(sum of squares of weights), otherwise the error is set equal
325  to the sqrt(bin content).
326  To return the error for a given bin number, do:
327 ~~~ {.cpp}
328  Double_t error = h->GetBinError(bin);
329 ~~~
330 
331 #### Associated functions
332  One or more object (typically a TF1*) can be added to the list
333  of functions (fFunctions) associated to each histogram.
334  When TH1::Fit is invoked, the fitted function is added to this list.
335  Given an histogram h, one can retrieve an associated function
336  with:
337 ~~~ {.cpp}
338  TF1 *myfunc = h->GetFunction("myfunc");
339 ~~~
340 
341 #### Operations on histograms
342 
343  Many types of operations are supported on histograms or between histograms
344 
345  - Addition of an histogram to the current histogram.
346  - Additions of two histograms with coefficients and storage into the current
347  histogram.
348  - Multiplications and Divisions are supported in the same way as additions.
349  - The Add, Divide and Multiply functions also exist to add, divide or multiply
350  an histogram by a function.
351 
352  If an histogram has associated error bars (TH1::Sumw2 has been called),
353  the resulting error bars are also computed assuming independent histograms.
354  In case of divisions, Binomial errors are also supported.
355  One can mark a histogram to be an "average" histogram by setting its bit kIsAverage via
356  myhist.SetBit(TH1::kIsAverage);
357  When adding (see TH1::Add) average histograms, the histograms are averaged and not summed.
358 
359 #### Fitting histograms
360 
361  Histograms (1-D, 2-D, 3-D and Profiles) can be fitted with a user
362  specified function via TH1::Fit. When an histogram is fitted, the
363  resulting function with its parameters is added to the list of functions
364  of this histogram. If the histogram is made persistent, the list of
365  associated functions is also persistent. Given a pointer (see above)
366  to an associated function myfunc, one can retrieve the function/fit
367  parameters with calls such as:
368 ~~~ {.cpp}
369  Double_t chi2 = myfunc->GetChisquare();
370  Double_t par0 = myfunc->GetParameter(0); value of 1st parameter
371  Double_t err0 = myfunc->GetParError(0); error on first parameter
372 ~~~
373 
374 #### Projections of histograms
375 
376  One can:
377 
378  - make a 1-D projection of a 2-D histogram or Profile
379  see functions TH2::ProjectionX,Y, TH2::ProfileX,Y, TProfile::ProjectionX
380  - make a 1-D, 2-D or profile out of a 3-D histogram
381  see functions TH3::ProjectionZ, TH3::Project3D.
382 
383  One can fit these projections via:
384 ~~~ {.cpp}
385  TH2::FitSlicesX,Y, TH3::FitSlicesZ.
386 ~~~
387 
388 #### Random Numbers and histograms
389 
390  TH1::FillRandom can be used to randomly fill an histogram using
391  the contents of an existing TF1 function or another
392  TH1 histogram (for all dimensions).
393  For example the following two statements create and fill an histogram
394  10000 times with a default gaussian distribution of mean 0 and sigma 1:
395 ~~~ {.cpp}
396  TH1F h1("h1", "histo from a gaussian", 100, -3, 3);
397  h1.FillRandom("gaus", 10000);
398 ~~~
399  TH1::GetRandom can be used to return a random number distributed
400  according the contents of an histogram.
401 
402 #### Making a copy of an histogram
403  Like for any other ROOT object derived from TObject, one can use
404  the Clone() function. This makes an identical copy of the original
405  histogram including all associated errors and functions, e.g.:
406 ~~~ {.cpp}
407  TH1F *hnew = (TH1F*)h->Clone("hnew");
408 ~~~
409 
410 #### Normalizing histograms
411 
412  One can scale an histogram such that the bins integral is equal to
413  the normalization parameter via TH1::Scale(Double_t norm), where norm
414  is the desired normalization divided by the integral of the histogram.
415 
416 #### Drawing histograms
417 
418  Histograms are drawn via the THistPainter class. Each histogram has
419  a pointer to its own painter (to be usable in a multithreaded program).
420  Many drawing options are supported.
421  See THistPainter::Paint() for more details.
422 
423  The same histogram can be drawn with different options in different pads.
424  When an histogram drawn in a pad is deleted, the histogram is
425  automatically removed from the pad or pads where it was drawn.
426  If an histogram is drawn in a pad, then filled again, the new status
427  of the histogram will be automatically shown in the pad next time
428  the pad is updated. One does not need to redraw the histogram.
429  To draw the current version of an histogram in a pad, one can use
430 ~~~ {.cpp}
431  h->DrawCopy();
432 ~~~
433  This makes a clone (see Clone below) of the histogram. Once the clone
434  is drawn, the original histogram may be modified or deleted without
435  affecting the aspect of the clone.
436 
437  One can use TH1::SetMaximum() and TH1::SetMinimum() to force a particular
438  value for the maximum or the minimum scale on the plot. (For 1-D
439  histograms this means the y-axis, while for 2-D histograms these
440  functions affect the z-axis).
441 
442  TH1::UseCurrentStyle() can be used to change all histogram graphics
443  attributes to correspond to the current selected style.
444  This function must be called for each histogram.
445  In case one reads and draws many histograms from a file, one can force
446  the histograms to inherit automatically the current graphics style
447  by calling before gROOT->ForceStyle().
448 
449 #### Setting Drawing histogram contour levels (2-D hists only)
450 
451  By default contours are automatically generated at equidistant
452  intervals. A default value of 20 levels is used. This can be modified
453  via TH1::SetContour() or TH1::SetContourLevel().
454  the contours level info is used by the drawing options "cont", "surf",
455  and "lego".
456 
457 #### Setting histogram graphics attributes
458 
459  The histogram classes inherit from the attribute classes:
460  TAttLine, TAttFill, and TAttMarker.
461  See the member functions of these classes for the list of options.
462 
463 #### Giving titles to the X, Y and Z axis
464 
465 ~~~ {.cpp}
466  h->GetXaxis()->SetTitle("X axis title");
467  h->GetYaxis()->SetTitle("Y axis title");
468 ~~~
469  The histogram title and the axis titles can be any TLatex string.
470  The titles are part of the persistent histogram.
471  It is also possible to specify the histogram title and the axis
472  titles at creation time. These titles can be given in the "title"
473  parameter. They must be separated by ";":
474 ~~~ {.cpp}
475  TH1F* h=new TH1F("h", "Histogram title;X Axis;Y Axis;Z Axis", 100, 0, 1);
476 ~~~
477  Any title can be omitted:
478 ~~~ {.cpp}
479  TH1F* h=new TH1F("h", "Histogram title;;Y Axis", 100, 0, 1);
480  TH1F* h=new TH1F("h", ";;Y Axis", 100, 0, 1);
481 ~~~
482  The method SetTitle has the same syntax:
483 ~~~ {.cpp}
484  h->SetTitle("Histogram title;Another X title Axis");
485 ~~~
486 
487 #### Saving/Reading histograms to/from a ROOT file
488 
489  The following statements create a ROOT file and store an histogram
490  on the file. Because TH1 derives from TNamed, the key identifier on
491  the file is the histogram name:
492 ~~~ {.cpp}
493  TFile f("histos.root", "new");
494  TH1F h1("hgaus", "histo from a gaussian", 100, -3, 3);
495  h1.FillRandom("gaus", 10000);
496  h1->Write();
497 ~~~
498  To read this histogram in another Root session, do:
499 ~~~ {.cpp}
500  TFile f("histos.root");
501  TH1F *h = (TH1F*)f.Get("hgaus");
502 ~~~
503  One can save all histograms in memory to the file by:
504 ~~~ {.cpp}
505  file->Write();
506 ~~~
507 
508 #### Miscellaneous operations
509 
510 ~~~ {.cpp}
511  TH1::KolmogorovTest(): statistical test of compatibility in shape
512  between two histograms
513  TH1::Smooth() smooths the bin contents of a 1-d histogram
514  TH1::Integral() returns the integral of bin contents in a given bin range
515  TH1::GetMean(int axis) returns the mean value along axis
516  TH1::GetStdDev(int axis) returns the sigma distribution along axis
517  TH1::GetEntries() returns the number of entries
518  TH1::Reset() resets the bin contents and errors of an histogram
519 ~~~
520 */
521 
522 TF1 *gF1=0; //left for back compatibility (use TVirtualFitter::GetUserFunc instead)
523 
524 Int_t TH1::fgBufferSize = 1000;
528 
529 extern void H1InitGaus();
530 extern void H1InitExpo();
531 extern void H1InitPolynom();
532 extern void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a);
533 extern void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail);
534 extern void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b);
535 
536 // Internal exceptions for the CheckConsistency method
537 class DifferentDimension: public std::exception {};
538 class DifferentNumberOfBins: public std::exception {};
539 class DifferentAxisLimits: public std::exception {};
540 class DifferentBinLimits: public std::exception {};
541 class DifferentLabels: public std::exception {};
542 
543 ClassImp(TH1)
544 
545 ////////////////////////////////////////////////////////////////////////////////
546 /// Histogram default constructor.
547 
549 {
550  fDirectory = 0;
551  fFunctions = new TList;
552  fNcells = 0;
553  fIntegral = 0;
554  fPainter = 0;
555  fEntries = 0;
556  fNormFactor = 0;
557  fTsumw = fTsumw2=fTsumwx=fTsumwx2=0;
558  fMaximum = -1111;
559  fMinimum = -1111;
560  fBufferSize = 0;
561  fBuffer = 0;
562  fBinStatErrOpt = kNormal;
563  fXaxis.SetName("xaxis");
564  fYaxis.SetName("yaxis");
565  fZaxis.SetName("zaxis");
566  fXaxis.SetParent(this);
567  fYaxis.SetParent(this);
568  fZaxis.SetParent(this);
569  UseCurrentStyle();
570 }
571 
572 ////////////////////////////////////////////////////////////////////////////////
573 /// Histogram default destructor.
574 
576 {
577  if (!TestBit(kNotDeleted)) {
578  return;
579  }
580  delete[] fIntegral;
581  fIntegral = 0;
582  delete[] fBuffer;
583  fBuffer = 0;
584  if (fFunctions) {
585  fFunctions->SetBit(kInvalidObject);
586  TObject* obj = 0;
587  //special logic to support the case where the same object is
588  //added multiple times in fFunctions.
589  //This case happens when the same object is added with different
590  //drawing modes
591  //In the loop below we must be careful with objects (eg TCutG) that may
592  // have been added to the list of functions of several histograms
593  //and may have been already deleted.
594  while ((obj = fFunctions->First())) {
595  while(fFunctions->Remove(obj)) { }
596  if (!obj->TestBit(kNotDeleted)) {
597  break;
598  }
599  delete obj;
600  obj = 0;
601  }
602  delete fFunctions;
603  fFunctions = 0;
604  }
605  if (fDirectory) {
606  fDirectory->Remove(this);
607  fDirectory = 0;
608  }
609  delete fPainter;
610  fPainter = 0;
611 }
612 
613 ////////////////////////////////////////////////////////////////////////////////
614 /// Normal constructor for fix bin size histograms.
615 /// Creates the main histogram structure.
616 ///
617 /// \param[in] name name of histogram (avoid blanks)
618 /// \param[in] title histogram title.
619 /// If title is of the form stringt;stringx;stringy;stringz`
620 /// the histogram title is set to `stringt`,
621 /// the x axis title to `stringy`, the y axis title to `stringy`, etc.
622 /// \param[in] nbins number of bins
623 /// \param[in] xlow low edge of first bin
624 /// \param[in] xup upper edge of last bin (not included in last bin)
625 ///
626 /// When an histogram is created, it is automatically added to the list
627 /// of special objects in the current directory.
628 /// To find the pointer to this histogram in the current directory
629 /// by its name, do:
630 /// ~~~ {.cpp}
631 /// TH1F *h1 = (TH1F*)gDirectory->FindObject(name);
632 /// ~~~
633 
634 TH1::TH1(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
635  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
636 {
637  Build();
638  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
639  fXaxis.Set(nbins,xlow,xup);
640  fNcells = fXaxis.GetNbins()+2;
641 }
642 
643 ////////////////////////////////////////////////////////////////////////////////
644 /// Normal constructor for variable bin size histograms.
645 /// Creates the main histogram structure.
646 ///
647 /// \param[in] name name of histogram (avoid blanks)
648 /// \param[in] title histogram title.
649 /// If title is of the form `stringt;stringx;stringy;stringz`
650 /// the histogram title is set to `stringt`,
651 /// the x axis title to `stringy`, the y axis title to `stringy`, etc.
652 /// \param[in] nbins number of bins
653 /// \param[in] xbins array of low-edges for each bin.
654 /// This is an array of size nbins+1
655 
656 TH1::TH1(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
657  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
658 {
659  Build();
660  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
661  if (xbins) fXaxis.Set(nbins,xbins);
662  else fXaxis.Set(nbins,0,1);
663  fNcells = fXaxis.GetNbins()+2;
664 }
665 
666 ////////////////////////////////////////////////////////////////////////////////
667 /// Normal constructor for variable bin size histograms.
668 ///
669 /// \param[in] name name of histogram (avoid blanks)
670 /// \param[in] title histogram title.
671 /// If title is of the form "stringt;stringx;stringy;stringz"
672 /// the histogram title is set to stringt,
673 /// the x axis title to stringy, the y axis title to stringy, etc.
674 /// \param[in] nbins number of bins
675 /// \param[in] xbins array of low-edges for each bin.
676 /// This is an array of size nbins+1
677 
678 TH1::TH1(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
679  :TNamed(name,title), TAttLine(), TAttFill(), TAttMarker()
680 {
681  Build();
682  if (nbins <= 0) {Warning("TH1","nbins is <=0 - set to nbins = 1"); nbins = 1; }
683  if (xbins) fXaxis.Set(nbins,xbins);
684  else fXaxis.Set(nbins,0,1);
685  fNcells = fXaxis.GetNbins()+2;
686 }
687 
688 ////////////////////////////////////////////////////////////////////////////////
689 /// Copy constructor.
690 /// The list of functions is not copied. (Use Clone if needed)
691 
693 {
694  ((TH1&)h).Copy(*this);
695 }
696 
697 ////////////////////////////////////////////////////////////////////////////////
698 /// Static function: cannot be inlined on Windows/NT.
699 
701 {
702  return fgAddDirectory;
703 }
704 
705 ////////////////////////////////////////////////////////////////////////////////
706 /// Browse the Histogram object.
707 
709 {
710  Draw(b ? b->GetDrawOption() : "");
711  gPad->Update();
712 }
713 
714 ////////////////////////////////////////////////////////////////////////////////
715 /// Creates histogram basic data structure.
716 
718 {
719  fDirectory = 0;
720  fPainter = 0;
721  fIntegral = 0;
722  fEntries = 0;
723  fNormFactor = 0;
725  fMaximum = -1111;
726  fMinimum = -1111;
727  fBufferSize = 0;
728  fBuffer = 0;
730  fXaxis.SetName("xaxis");
731  fYaxis.SetName("yaxis");
732  fZaxis.SetName("zaxis");
733  fYaxis.Set(1,0.,1.);
734  fZaxis.Set(1,0.,1.);
735  fXaxis.SetParent(this);
736  fYaxis.SetParent(this);
737  fZaxis.SetParent(this);
738 
739  SetTitle(fTitle.Data());
740 
741  fFunctions = new TList;
742 
743  UseCurrentStyle();
744 
745  if (TH1::AddDirectoryStatus()) {
747  if (fDirectory) {
748  fDirectory->Append(this,kTRUE);
749  }
750  }
751 }
752 
753 ////////////////////////////////////////////////////////////////////////////////
754 /// Performs the operation: `this = this + c1*f1`
755 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
756 ///
757 /// By default, the function is computed at the centre of the bin.
758 /// if option "I" is specified (1-d histogram only), the integral of the
759 /// function in each bin is used instead of the value of the function at
760 /// the centre of the bin.
761 ///
762 /// Only bins inside the function range are recomputed.
763 ///
764 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
765 /// you should call Sumw2 before making this operation.
766 /// This is particularly important if you fit the histogram after TH1::Add
767 ///
768 /// The function return kFALSE if the Add operation failed
769 
771 {
772  if (!f1) {
773  Error("Add","Attempt to add a non-existing function");
774  return kFALSE;
775  }
776 
777  TString opt = option;
778  opt.ToLower();
779  Bool_t integral = kFALSE;
780  if (opt.Contains("i") && fDimension == 1) integral = kTRUE;
781 
782  Int_t ncellsx = GetNbinsX() + 2; // cells = normal bins + underflow bin + overflow bin
783  Int_t ncellsy = GetNbinsY() + 2;
784  Int_t ncellsz = GetNbinsZ() + 2;
785  if (fDimension < 2) ncellsy = 1;
786  if (fDimension < 3) ncellsz = 1;
787 
788  // delete buffer if it is there since it will become invalid
789  if (fBuffer) BufferEmpty(1);
790 
791  // - Add statistics
792  Double_t s1[10];
793  for (Int_t i = 0; i < 10; ++i) s1[i] = 0;
794  PutStats(s1);
795  SetMinimum();
796  SetMaximum();
797 
798  // - Loop on bins (including underflows/overflows)
799  Int_t bin, binx, biny, binz;
800  Double_t cu=0;
801  Double_t xx[3];
802  Double_t *params = 0;
803  f1->InitArgs(xx,params);
804  for (binz = 0; binz < ncellsz; ++binz) {
805  xx[2] = fZaxis.GetBinCenter(binz);
806  for (biny = 0; biny < ncellsy; ++biny) {
807  xx[1] = fYaxis.GetBinCenter(biny);
808  for (binx = 0; binx < ncellsx; ++binx) {
809  xx[0] = fXaxis.GetBinCenter(binx);
810  if (!f1->IsInside(xx)) continue;
812  bin = binx + ncellsx * (biny + ncellsy * binz);
813  if (integral) {
814  cu = c1*f1->Integral(fXaxis.GetBinLowEdge(binx), fXaxis.GetBinUpEdge(binx)) / fXaxis.GetBinWidth(binx);
815  } else {
816  cu = c1*f1->EvalPar(xx);
817  }
818  if (TF1::RejectedPoint()) continue;
819  AddBinContent(bin,cu);
820  }
821  }
822  }
823 
824  return kTRUE;
825 }
826 
827 ////////////////////////////////////////////////////////////////////////////////
828 /// Performs the operation: `this = this + c1*h1`
829 /// If errors are defined (see TH1::Sumw2), errors are also recalculated.
830 ///
831 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
832 /// if not already set.
833 ///
834 /// Note also that adding histogram with labels is not supported, histogram will be
835 /// added merging them by bin number independently of the labels.
836 /// For adding histogram with labels one should use TH1::Merge
837 ///
838 /// SPECIAL CASE (Average/Efficiency histograms)
839 /// For histograms representing averages or efficiencies, one should compute the average
840 /// of the two histograms and not the sum. One can mark a histogram to be an average
841 /// histogram by setting its bit kIsAverage with
842 /// myhist.SetBit(TH1::kIsAverage);
843 /// Note that the two histograms must have their kIsAverage bit set
844 ///
845 /// IMPORTANT NOTE1: If you intend to use the errors of this histogram later
846 /// you should call Sumw2 before making this operation.
847 /// This is particularly important if you fit the histogram after TH1::Add
848 ///
849 /// IMPORTANT NOTE2: if h1 has a normalisation factor, the normalisation factor
850 /// is used , ie this = this + c1*factor*h1
851 /// Use the other TH1::Add function if you do not want this feature
852 ///
853 /// The function return kFALSE if the Add operation failed
854 
856 {
857  if (!h1) {
858  Error("Add","Attempt to add a non-existing histogram");
859  return kFALSE;
860  }
861 
862  // delete buffer if it is there since it will become invalid
863  if (fBuffer) BufferEmpty(1);
864 
865  bool useMerge = (c1 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
866  try {
867  CheckConsistency(this,h1);
868  useMerge = kFALSE;
869  } catch(DifferentNumberOfBins&) {
870  if (useMerge)
871  Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
872  else {
873  Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
874  return kFALSE;
875  }
876  } catch(DifferentAxisLimits&) {
877  if (useMerge)
878  Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
879  else
880  Warning("Add","Attempt to add histograms with different axis limits");
881  } catch(DifferentBinLimits&) {
882  if (useMerge)
883  Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
884  else
885  Warning("Add","Attempt to add histograms with different bin limits");
886  } catch(DifferentLabels&) {
887  // in case of different labels -
888  if (useMerge)
889  Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
890  else
891  Info("Warning","Attempt to add histograms with different labels");
892  }
893 
894  if (useMerge) {
895  TList l;
896  l.Add(const_cast<TH1*>(h1));
897  auto iret = Merge(&l);
898  return (iret >= 0);
899  }
900 
901  // Create Sumw2 if h1 has Sumw2 set
902  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
903 
904  // - Add statistics
905  Double_t entries = TMath::Abs( GetEntries() + c1 * h1->GetEntries() );
906 
907  // statistics can be preserved only in case of positive coefficients
908  // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
909  Bool_t resetStats = (c1 < 0);
910  Double_t s1[kNstat] = {0};
911  Double_t s2[kNstat] = {0};
912  if (!resetStats) {
913  // need to initialize to zero s1 and s2 since
914  // GetStats fills only used elements depending on dimension and type
915  GetStats(s1);
916  h1->GetStats(s2);
917  }
918 
919  SetMinimum();
920  SetMaximum();
921 
922  // - Loop on bins (including underflows/overflows)
923  Double_t factor = 1;
924  if (h1->GetNormFactor() != 0) factor = h1->GetNormFactor()/h1->GetSumOfWeights();;
925  Double_t c1sq = c1 * c1;
926  Double_t factsq = factor * factor;
927 
928  for (Int_t bin = 0; bin < fNcells; ++bin) {
929  //special case where histograms have the kIsAverage bit set
930  if (this->TestBit(kIsAverage) && h1->TestBit(kIsAverage)) {
931  Double_t y1 = h1->RetrieveBinContent(bin);
932  Double_t y2 = this->RetrieveBinContent(bin);
933  Double_t e1sq = h1->GetBinErrorSqUnchecked(bin);
934  Double_t e2sq = this->GetBinErrorSqUnchecked(bin);
935  Double_t w1 = 1., w2 = 1.;
936 
937  // consider all special cases when bin errors are zero
938  // see http://root.cern.ch/phpBB3//viewtopic.php?f=3&t=13299
939  if (e1sq) w1 = 1. / e1sq;
940  else if (h1->fSumw2.fN) {
941  w1 = 1.E200; // use an arbitrary huge value
942  if (y1 == 0) {
943  // use an estimated error from the global histogram scale
944  double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
945  w1 = 1./(sf*sf);
946  }
947  }
948  if (e2sq) w2 = 1. / e2sq;
949  else if (fSumw2.fN) {
950  w2 = 1.E200; // use an arbitrary huge value
951  if (y2 == 0) {
952  // use an estimated error from the global histogram scale
953  double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
954  w2 = 1./(sf*sf);
955  }
956  }
957 
958  double y = (w1*y1 + w2*y2)/(w1 + w2);
959  UpdateBinContent(bin, y);
960  if (fSumw2.fN) {
961  double err2 = 1./(w1 + w2);
962  if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
963  fSumw2.fArray[bin] = err2;
964  }
965  } else { // normal case of addition between histograms
966  AddBinContent(bin, c1 * factor * h1->RetrieveBinContent(bin));
967  if (fSumw2.fN) fSumw2.fArray[bin] += c1sq * factsq * h1->GetBinErrorSqUnchecked(bin);
968  }
969  }
970 
971  // update statistics (do here to avoid changes by SetBinContent)
972  if (resetStats) {
973  // statistics need to be reset in case coefficient are negative
974  ResetStats();
975  }
976  else {
977  for (Int_t i=0;i<kNstat;i++) {
978  if (i == 1) s1[i] += c1*c1*s2[i];
979  else s1[i] += c1*s2[i];
980  }
981  PutStats(s1);
982  SetEntries(entries);
983  }
984  return kTRUE;
985 }
986 
987 ////////////////////////////////////////////////////////////////////////////////
988 /// Replace contents of this histogram by the addition of h1 and h2.
989 ///
990 /// `this = c1*h1 + c2*h2`
991 /// if errors are defined (see TH1::Sumw2), errors are also recalculated
992 ///
993 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
994 /// if not already set.
995 ///
996 /// Note also that adding histogram with labels is not supported, histogram will be
997 /// added merging them by bin number independently of the labels.
998 /// For adding histogram ith labels one should use TH1::Merge
999 ///
1000 /// SPECIAL CASE (Average/Efficiency histograms)
1001 /// For histograms representing averages or efficiencies, one should compute the average
1002 /// of the two histograms and not the sum. One can mark a histogram to be an average
1003 /// histogram by setting its bit kIsAverage with
1004 /// myhist.SetBit(TH1::kIsAverage);
1005 /// Note that the two histograms must have their kIsAverage bit set
1006 ///
1007 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
1008 /// you should call Sumw2 before making this operation.
1009 /// This is particularly important if you fit the histogram after TH1::Add
1010 ///
1011 /// ANOTHER SPECIAL CASE : h1 = h2 and c2 < 0
1012 /// do a scaling this = c1 * h1 / (bin Volume)
1013 ///
1014 /// The function returns kFALSE if the Add operation failed
1015 
1017 {
1018 
1019  if (!h1 || !h2) {
1020  Error("Add","Attempt to add a non-existing histogram");
1021  return kFALSE;
1022  }
1023 
1024  // delete buffer if it is there since it will become invalid
1025  if (fBuffer) BufferEmpty(1);
1026 
1027  Bool_t normWidth = kFALSE;
1028  if (h1 == h2 && c2 < 0) {c2 = 0; normWidth = kTRUE;}
1029 
1030  if (h1 != h2) {
1031  bool useMerge = (c1 == 1. && c2 == 1. && !this->TestBit(kIsAverage) && !h1->TestBit(kIsAverage) );
1032 
1033  try {
1034  CheckConsistency(h1,h2);
1035  CheckConsistency(this,h1);
1036  useMerge = kFALSE;
1037  } catch(DifferentNumberOfBins&) {
1038  if (useMerge)
1039  Info("Add","Attempt to add histograms with different number of bins - trying to use TH1::Merge");
1040  else {
1041  Error("Add","Attempt to add histograms with different number of bins : nbins h1 = %d , nbins h2 = %d",GetNbinsX(), h1->GetNbinsX());
1042  return kFALSE;
1043  }
1044  } catch(DifferentAxisLimits&) {
1045  if (useMerge)
1046  Info("Add","Attempt to add histograms with different axis limits - trying to use TH1::Merge");
1047  else
1048  Warning("Add","Attempt to add histograms with different axis limits");
1049  } catch(DifferentBinLimits&) {
1050  if (useMerge)
1051  Info("Add","Attempt to add histograms with different bin limits - trying to use TH1::Merge");
1052  else
1053  Warning("Add","Attempt to add histograms with different bin limits");
1054  } catch(DifferentLabels&) {
1055  // in case of different labels -
1056  if (useMerge)
1057  Info("Add","Attempt to add histograms with different labels - trying to use TH1::Merge");
1058  else
1059  Info("Warning","Attempt to add histograms with different labels");
1060  }
1061 
1062  if (useMerge) {
1063  TList l;
1064  // why TList takes non-const pointers ????
1065  l.Add(const_cast<TH1*>(h1));
1066  l.Add(const_cast<TH1*>(h2));
1067  Reset("ICE");
1068  auto iret = Merge(&l);
1069  return (iret >= 0);
1070  }
1071  }
1072 
1073  // Create Sumw2 if h1 or h2 have Sumw2 set
1074  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
1075 
1076  // - Add statistics
1077  Double_t nEntries = TMath::Abs( c1*h1->GetEntries() + c2*h2->GetEntries() );
1078 
1079  // TODO remove
1080  // statistics can be preserved only in case of positive coefficients
1081  // otherwise with negative c1 (histogram subtraction) one risks to get negative variances
1082  // also in case of scaling with the width we cannot preserve the statistics
1083  Double_t s1[kNstat] = {0};
1084  Double_t s2[kNstat] = {0};
1085  Double_t s3[kNstat];
1086 
1087 
1088  Bool_t resetStats = (c1*c2 < 0) || normWidth;
1089  if (!resetStats) {
1090  // need to initialize to zero s1 and s2 since
1091  // GetStats fills only used elements depending on dimension and type
1092  h1->GetStats(s1);
1093  h2->GetStats(s2);
1094  for (Int_t i=0;i<kNstat;i++) {
1095  if (i == 1) s3[i] = c1*c1*s1[i] + c2*c2*s2[i];
1096  //else s3[i] = TMath::Abs(c1)*s1[i] + TMath::Abs(c2)*s2[i];
1097  else s3[i] = c1*s1[i] + c2*s2[i];
1098  }
1099  }
1100 
1101  SetMinimum();
1102  SetMaximum();
1103 
1104  if (normWidth) { // DEPRECATED CASE: belongs to fitting / drawing modules
1105 
1106  Int_t nbinsx = GetNbinsX() + 2; // normal bins + underflow, overflow
1107  Int_t nbinsy = GetNbinsY() + 2;
1108  Int_t nbinsz = GetNbinsZ() + 2;
1109 
1110  if (fDimension < 2) nbinsy = 1;
1111  if (fDimension < 3) nbinsz = 1;
1112 
1113  Int_t bin, binx, biny, binz;
1114  for (binz = 0; binz < nbinsz; ++binz) {
1115  Double_t wz = h1->GetZaxis()->GetBinWidth(binz);
1116  for (biny = 0; biny < nbinsy; ++biny) {
1117  Double_t wy = h1->GetYaxis()->GetBinWidth(biny);
1118  for (binx = 0; binx < nbinsx; ++binx) {
1119  Double_t wx = h1->GetXaxis()->GetBinWidth(binx);
1120  bin = GetBin(binx, biny, binz);
1121  Double_t w = wx*wy*wz;
1122  UpdateBinContent(bin, c1 * h1->RetrieveBinContent(bin) / w);
1123  if (fSumw2.fN) {
1124  Double_t e1 = h1->GetBinError(bin)/w;
1125  fSumw2.fArray[bin] = c1*c1*e1*e1;
1126  }
1127  }
1128  }
1129  }
1130  } else if (h1->TestBit(kIsAverage) && h2->TestBit(kIsAverage)) {
1131  for (Int_t i = 0; i < fNcells; ++i) { // loop on cells (bins including underflow / overflow)
1132  // special case where histograms have the kIsAverage bit set
1133  Double_t y1 = h1->RetrieveBinContent(i);
1134  Double_t y2 = h2->RetrieveBinContent(i);
1135  Double_t e1sq = h1->GetBinErrorSqUnchecked(i);
1136  Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
1137  Double_t w1 = 1., w2 = 1.;
1138 
1139  // consider all special cases when bin errors are zero
1140  // see http://root.cern.ch/phpBB3//viewtopic.php?f=3&t=13299
1141  if (e1sq) w1 = 1./ e1sq;
1142  else if (h1->fSumw2.fN) {
1143  w1 = 1.E200; // use an arbitrary huge value
1144  if (y1 == 0 ) { // use an estimated error from the global histogram scale
1145  double sf = (s1[0] != 0) ? s1[1]/s1[0] : 1;
1146  w1 = 1./(sf*sf);
1147  }
1148  }
1149  if (e2sq) w2 = 1./ e2sq;
1150  else if (h2->fSumw2.fN) {
1151  w2 = 1.E200; // use an arbitrary huge value
1152  if (y2 == 0) { // use an estimated error from the global histogram scale
1153  double sf = (s2[0] != 0) ? s2[1]/s2[0] : 1;
1154  w2 = 1./(sf*sf);
1155  }
1156  }
1157 
1158  double y = (w1*y1 + w2*y2)/(w1 + w2);
1159  UpdateBinContent(i, y);
1160  if (fSumw2.fN) {
1161  double err2 = 1./(w1 + w2);
1162  if (err2 < 1.E-200) err2 = 0; // to remove arbitrary value when e1=0 AND e2=0
1163  fSumw2.fArray[i] = err2;
1164  }
1165  }
1166  } else { // case of simple histogram addition
1167  Double_t c1sq = c1 * c1;
1168  Double_t c2sq = c2 * c2;
1169  for (Int_t i = 0; i < fNcells; ++i) { // Loop on cells (bins including underflows/overflows)
1170  UpdateBinContent(i, c1 * h1->RetrieveBinContent(i) + c2 * h2->RetrieveBinContent(i));
1171  if (fSumw2.fN) {
1172  fSumw2.fArray[i] = c1sq * h1->GetBinErrorSqUnchecked(i) + c2sq * h2->GetBinErrorSqUnchecked(i);
1173  }
1174  }
1175  }
1176 
1177  if (resetStats) {
1178  // statistics need to be reset in case coefficient are negative
1179  ResetStats();
1180  }
1181  else {
1182  // update statistics (do here to avoid changes by SetBinContent) FIXME remove???
1183  PutStats(s3);
1184  SetEntries(nEntries);
1185  }
1186 
1187  return kTRUE;
1188 }
1189 
1190 ////////////////////////////////////////////////////////////////////////////////
1191 /// Increment bin content by 1.
1192 
1194 {
1195  AbstractMethod("AddBinContent");
1196 }
1197 
1198 ////////////////////////////////////////////////////////////////////////////////
1199 /// Increment bin content by a weight w.
1200 
1202 {
1203  AbstractMethod("AddBinContent");
1204 }
1205 
1206 ////////////////////////////////////////////////////////////////////////////////
1207 /// Sets the flag controlling the automatic add of histograms in memory
1208 ///
1209 /// By default (fAddDirectory = kTRUE), histograms are automatically added
1210 /// to the list of objects in memory.
1211 /// Note that one histogram can be removed from its support directory
1212 /// by calling h->SetDirectory(0) or h->SetDirectory(dir) to add it
1213 /// to the list of objects in the directory dir.
1214 ///
1215 /// NOTE that this is a static function. To call it, use;
1216 /// TH1::AddDirectory
1217 
1219 {
1220  fgAddDirectory = add;
1221 }
1222 
1223 ////////////////////////////////////////////////////////////////////////////////
1224 /// Fill histogram with all entries in the buffer.
1225 ///
1226 /// - action = -1 histogram is reset and refilled from the buffer (called by THistPainter::Paint)
1227 /// - action = 0 histogram is reset and filled from the buffer. When the histogram is filled from the
1228 /// buffer the value fBuffer[0] is set to a negative number (= - number of entries)
1229 /// When calling with action == 0 the histogram is NOT refilled when fBuffer[0] is < 0
1230 /// While when calling with action = -1 the histogram is reset and ALWAYS refilled independently if
1231 /// the histogram was filled before. This is needed when drawing the histogram
1232 /// - action = 1 histogram is filled and buffer is deleted
1233 /// The buffer is automatically deleted when filling the histogram and the entries is
1234 /// larger than the buffer size
1235 
1237 {
1238  // do we need to compute the bin size?
1239  if (!fBuffer) return 0;
1240  Int_t nbentries = (Int_t)fBuffer[0];
1241 
1242  // nbentries correspond to the number of entries of histogram
1243 
1244  if (nbentries == 0) {
1245  // if action is 1 we delete the buffer
1246  // this will avoid infinite recursion
1247  if (action > 0) {
1248  delete [] fBuffer;
1249  fBuffer = 0;
1250  fBufferSize = 0;
1251  }
1252  return 0;
1253  }
1254  if (nbentries < 0 && action == 0) return 0; // case histogram has been already filled from the buffer
1255 
1256  Double_t *buffer = fBuffer;
1257  if (nbentries < 0) {
1258  nbentries = -nbentries;
1259  // a reset might call BufferEmpty() giving an infinite recursion
1260  // Protect it by setting fBuffer = 0
1261  fBuffer=0;
1262  //do not reset the list of functions
1263  Reset("ICES");
1264  fBuffer = buffer;
1265  }
1266  if (CanExtendAllAxes() || (fXaxis.GetXmax() <= fXaxis.GetXmin())) {
1267  //find min, max of entries in buffer
1268  Double_t xmin = fBuffer[2];
1269  Double_t xmax = xmin;
1270  for (Int_t i=1;i<nbentries;i++) {
1271  Double_t x = fBuffer[2*i+2];
1272  if (x < xmin) xmin = x;
1273  if (x > xmax) xmax = x;
1274  }
1275  if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
1277  } else {
1278  fBuffer = 0;
1279  Int_t keep = fBufferSize; fBufferSize = 0;
1280  if (xmin < fXaxis.GetXmin()) ExtendAxis(xmin,&fXaxis);
1281  if (xmax >= fXaxis.GetXmax()) ExtendAxis(xmax,&fXaxis);
1282  fBuffer = buffer;
1283  fBufferSize = keep;
1284  }
1285  }
1286 
1287  // call DoFillN which will not put entries in the buffer as FillN does
1288  // set fBuffer to zero to avoid re-emptying the buffer from functions called
1289  // by DoFillN (e.g Sumw2)
1290  buffer = fBuffer; fBuffer = 0;
1291  DoFillN(nbentries,&buffer[2],&buffer[1],2);
1292  fBuffer = buffer;
1293 
1294  // if action == 1 - delete the buffer
1295  if (action > 0) {
1296  delete [] fBuffer;
1297  fBuffer = 0;
1298  fBufferSize = 0;}
1299  else {
1300  // if number of entries is consistent with buffer - set it negative to avoid
1301  // refilling the histogram every time BufferEmpty(0) is called
1302  // In case it is not consistent, by setting fBuffer[0]=0 is like resetting the buffer
1303  // (it will not be used anymore the next time BufferEmpty is called)
1304  if (nbentries == (Int_t)fEntries)
1305  fBuffer[0] = -nbentries;
1306  else
1307  fBuffer[0] = 0;
1308  }
1309  return nbentries;
1310 }
1311 
1312 ////////////////////////////////////////////////////////////////////////////////
1313 /// accumulate arguments in buffer. When buffer is full, empty the buffer
1314 ///
1315 /// - `fBuffer[0]` = number of entries in buffer
1316 /// - `fBuffer[1]` = w of first entry
1317 /// - `fBuffer[2]` = x of first entry
1318 
1320 {
1321  if (!fBuffer) return -2;
1322  Int_t nbentries = (Int_t)fBuffer[0];
1323 
1324 
1325  if (nbentries < 0) {
1326  // reset nbentries to a positive value so next time BufferEmpty() is called
1327  // the histogram will be refilled
1328  nbentries = -nbentries;
1329  fBuffer[0] = nbentries;
1330  if (fEntries > 0) {
1331  // set fBuffer to zero to avoid calling BufferEmpty in Reset
1332  Double_t *buffer = fBuffer; fBuffer=0;
1333  Reset("ICES"); // do not reset list of functions
1334  fBuffer = buffer;
1335  }
1336  }
1337  if (2*nbentries+2 >= fBufferSize) {
1338  BufferEmpty(1);
1339  if (!fBuffer)
1340  // to avoid infinite recursion Fill->BufferFill->Fill
1341  return Fill(x,w);
1342  // this cannot happen
1343  R__ASSERT(0);
1344  }
1345  fBuffer[2*nbentries+1] = w;
1346  fBuffer[2*nbentries+2] = x;
1347  fBuffer[0] += 1;
1348  return -2;
1349 }
1350 
1351 ////////////////////////////////////////////////////////////////////////////////
1352 /// Check bin limits.
1353 
1354 bool TH1::CheckBinLimits(const TAxis* a1, const TAxis * a2)
1355 {
1356  const TArrayD * h1Array = a1->GetXbins();
1357  const TArrayD * h2Array = a2->GetXbins();
1358  Int_t fN = h1Array->fN;
1359  if ( fN != 0 ) {
1360  if ( h2Array->fN != fN ) {
1361  throw DifferentBinLimits();
1362  return false;
1363  }
1364  else {
1365  for ( int i = 0; i < fN; ++i ) {
1366  if ( ! TMath::AreEqualRel( h1Array->GetAt(i), h2Array->GetAt(i), 1E-10 ) ) {
1367  throw DifferentBinLimits();
1368  return false;
1369  }
1370  }
1371  }
1372  }
1373 
1374  return true;
1375 }
1376 
1377 ////////////////////////////////////////////////////////////////////////////////
1378 /// Check that axis have same labels.
1379 
1380 bool TH1::CheckBinLabels(const TAxis* a1, const TAxis * a2)
1381 {
1382  THashList *l1 = a1->GetLabels();
1383  THashList *l2 = a2->GetLabels();
1384 
1385  if (!l1 && !l2 )
1386  return true;
1387  if (!l1 || !l2 ) {
1388  throw DifferentLabels();
1389  return false;
1390  }
1391  // check now labels sizes are the same
1392  if (l1->GetSize() != l2->GetSize() ) {
1393  throw DifferentLabels();
1394  return false;
1395  }
1396  for (int i = 1; i <= a1->GetNbins(); ++i) {
1397  TString label1 = a1->GetBinLabel(i);
1398  TString label2 = a2->GetBinLabel(i);
1399  if (label1 != label2) {
1400  throw DifferentLabels();
1401  return false;
1402  }
1403  }
1404 
1405  return true;
1406 }
1407 
1408 ////////////////////////////////////////////////////////////////////////////////
1409 /// Check that the axis limits of the histograms are the same.
1410 /// If a first and last bin is passed the axis is compared between the given range
1411 
1412 bool TH1::CheckAxisLimits(const TAxis *a1, const TAxis *a2 )
1413 {
1414  if ( ! TMath::AreEqualRel(a1->GetXmin(), a2->GetXmin(),1.E-12) ||
1415  ! TMath::AreEqualRel(a1->GetXmax(), a2->GetXmax(),1.E-12) ) {
1416  throw DifferentAxisLimits();
1417  return false;
1418  }
1419  return true;
1420 }
1421 
1422 ////////////////////////////////////////////////////////////////////////////////
1423 /// Check that the axis are the same
1424 
1425 bool TH1::CheckEqualAxes(const TAxis *a1, const TAxis *a2 )
1426 {
1427  if (a1->GetNbins() != a2->GetNbins() ) {
1428  //throw DifferentNumberOfBins();
1429  ::Info("CheckEqualAxes","Axes have different number of bins : nbin1 = %d nbin2 = %d",a1->GetNbins(),a2->GetNbins() );
1430  return false;
1431  }
1432  try {
1433  CheckAxisLimits(a1,a2);
1434  } catch (DifferentAxisLimits&) {
1435  ::Info("CheckEqualAxes","Axes have different limits");
1436  return false;
1437  }
1438  try {
1439  CheckBinLimits(a1,a2);
1440  } catch (DifferentBinLimits&) {
1441  ::Info("CheckEqualAxes","Axes have different bin limits");
1442  return false;
1443  }
1444 
1445  // check labels
1446  try {
1447  CheckBinLabels(a1,a2);
1448  } catch (DifferentLabels&) {
1449  ::Info("CheckEqualAxes","Axes have different labels");
1450  return false;
1451  }
1452 
1453  return true;
1454 }
1455 
1456 ////////////////////////////////////////////////////////////////////////////////
1457 /// Check that two sub axis are the same.
1458 /// The limits are defined by first bin and last bin
1459 /// N.B. no check is done in this case for variable bins
1460 
1461 bool TH1::CheckConsistentSubAxes(const TAxis *a1, Int_t firstBin1, Int_t lastBin1, const TAxis * a2, Int_t firstBin2, Int_t lastBin2 )
1462 {
1463  // By default is assumed that no bins are given for the second axis
1464  Int_t nbins1 = lastBin1-firstBin1 + 1;
1465  Double_t xmin1 = a1->GetBinLowEdge(firstBin1);
1466  Double_t xmax1 = a1->GetBinUpEdge(lastBin1);
1467 
1468  Int_t nbins2 = a2->GetNbins();
1469  Double_t xmin2 = a2->GetXmin();
1470  Double_t xmax2 = a2->GetXmax();
1471 
1472  if (firstBin2 < lastBin2) {
1473  // in this case assume no bins are given for the second axis
1474  nbins2 = lastBin1-firstBin1 + 1;
1475  xmin2 = a1->GetBinLowEdge(firstBin1);
1476  xmax2 = a1->GetBinUpEdge(lastBin1);
1477  }
1478 
1479  if (nbins1 != nbins2 ) {
1480  ::Info("CheckConsistentSubAxes","Axes have different number of bins");
1481  return false;
1482  }
1483 
1484  if ( ! TMath::AreEqualRel(xmin1,xmin2,1.E-12) ||
1485  ! TMath::AreEqualRel(xmax1,xmax2,1.E-12) ) {
1486  ::Info("CheckConsistentSubAxes","Axes have different limits");
1487  return false;
1488  }
1489 
1490  return true;
1491 }
1492 
1493 ////////////////////////////////////////////////////////////////////////////////
1494 /// Check histogram compatibility.
1495 
1496 bool TH1::CheckConsistency(const TH1* h1, const TH1* h2)
1497 {
1498  if (h1 == h2) return true;
1499 
1500  if (h1->GetDimension() != h2->GetDimension() ) {
1501  throw DifferentDimension();
1502  return false;
1503  }
1504  Int_t dim = h1->GetDimension();
1505 
1506  // returns kTRUE if number of bins and bin limits are identical
1507  Int_t nbinsx = h1->GetNbinsX();
1508  Int_t nbinsy = h1->GetNbinsY();
1509  Int_t nbinsz = h1->GetNbinsZ();
1510 
1511  // Check whether the histograms have the same number of bins.
1512  if (nbinsx != h2->GetNbinsX() ||
1513  (dim > 1 && nbinsy != h2->GetNbinsY()) ||
1514  (dim > 2 && nbinsz != h2->GetNbinsZ()) ) {
1515  throw DifferentNumberOfBins();
1516  return false;
1517  }
1518 
1519  bool ret = true;
1520 
1521  // check axis limits
1522  ret &= CheckAxisLimits(h1->GetXaxis(), h2->GetXaxis());
1523  if (dim > 1) ret &= CheckAxisLimits(h1->GetYaxis(), h2->GetYaxis());
1524  if (dim > 2) ret &= CheckAxisLimits(h1->GetZaxis(), h2->GetZaxis());
1525 
1526  // check bin limits
1527  ret &= CheckBinLimits(h1->GetXaxis(), h2->GetXaxis());
1528  if (dim > 1) ret &= CheckBinLimits(h1->GetYaxis(), h2->GetYaxis());
1529  if (dim > 2) ret &= CheckBinLimits(h1->GetZaxis(), h2->GetZaxis());
1530 
1531  // check labels if histograms are both not empty
1532  if ( (h1->fTsumw != 0 || h1->GetEntries() != 0) &&
1533  (h2->fTsumw != 0 || h2->GetEntries() != 0) ) {
1534  ret &= CheckBinLabels(h1->GetXaxis(), h2->GetXaxis());
1535  if (dim > 1) ret &= CheckBinLabels(h1->GetYaxis(), h2->GetYaxis());
1536  if (dim > 2) ret &= CheckBinLabels(h1->GetZaxis(), h2->GetZaxis());
1537  }
1538 
1539  return ret;
1540 }
1541 
1542 ////////////////////////////////////////////////////////////////////////////////
1543 /// \f$ \chi^{2} \f$ test for comparing weighted and unweighted histograms
1544 ///
1545 /// Function: Returns p-value. Other return values are specified by the 3rd parameter
1546 ///
1547 /// \param[in] h2 the second histogram
1548 /// \param[in] option
1549 /// - "UU" = experiment experiment comparison (unweighted-unweighted)
1550 /// - "UW" = experiment MC comparison (unweighted-weighted). Note that
1551 /// the first histogram should be unweighted
1552 /// - "WW" = MC MC comparison (weighted-weighted)
1553 /// - "NORM" = to be used when one or both of the histograms is scaled
1554 /// but the histogram originally was unweighted
1555 /// - by default underflows and overflows are not included:
1556 /// * "OF" = overflows included
1557 /// * "UF" = underflows included
1558 /// - "P" = print chi2, ndf, p_value, igood
1559 /// - "CHI2" = returns chi2 instead of p-value
1560 /// - "CHI2/NDF" = returns \f$ \chi^{2} \f$/ndf
1561 /// \param[in] res not empty - computes normalized residuals and returns them in this array
1562 ///
1563 /// The current implementation is based on the papers \f$ \chi^{2} \f$ test for comparison
1564 /// of weighted and unweighted histograms" in Proceedings of PHYSTAT05 and
1565 /// "Comparison weighted and unweighted histograms", arXiv:physics/0605123
1566 /// by N.Gagunashvili. This function has been implemented by Daniel Haertl in August 2006.
1567 ///
1568 /// #### Introduction:
1569 ///
1570 /// A frequently used technique in data analysis is the comparison of
1571 /// histograms. First suggested by Pearson [1] the \f$ \chi^{2} \f$ test of
1572 /// homogeneity is used widely for comparing usual (unweighted) histograms.
1573 /// This paper describes the implementation modified \f$ \chi^{2} \f$ tests
1574 /// for comparison of weighted and unweighted histograms and two weighted
1575 /// histograms [2] as well as usual Pearson's \f$ \chi^{2} \f$ test for
1576 /// comparison two usual (unweighted) histograms.
1577 ///
1578 /// #### Overview:
1579 ///
1580 /// Comparison of two histograms expect hypotheses that two histograms
1581 /// represent identical distributions. To make a decision p-value should
1582 /// be calculated. The hypotheses of identity is rejected if the p-value is
1583 /// lower then some significance level. Traditionally significance levels
1584 /// 0.1, 0.05 and 0.01 are used. The comparison procedure should include an
1585 /// analysis of the residuals which is often helpful in identifying the
1586 /// bins of histograms responsible for a significant overall \f$ \chi^{2} \f$ value.
1587 /// Residuals are the difference between bin contents and expected bin
1588 /// contents. Most convenient for analysis are the normalized residuals. If
1589 /// hypotheses of identity are valid then normalized residuals are
1590 /// approximately independent and identically distributed random variables
1591 /// having N(0,1) distribution. Analysis of residuals expect test of above
1592 /// mentioned properties of residuals. Notice that indirectly the analysis
1593 /// of residuals increase the power of \f$ \chi^{2} \f$ test.
1594 ///
1595 /// #### Methods of comparison:
1596 ///
1597 /// \f$ \chi^{2} \f$ test for comparison two (unweighted) histograms:
1598 /// Let us consider two histograms with the same binning and the number
1599 /// of bins equal to r. Let us denote the number of events in the ith bin
1600 /// in the first histogram as ni and as mi in the second one. The total
1601 /// number of events in the first histogram is equal to:
1602 /// \f[
1603 /// N = \sum_{i=1}^{r} n_{i}
1604 /// \f]
1605 /// and
1606 /// \f[
1607 /// M = \sum_{i=1}^{r} m_{i}
1608 /// \f]
1609 /// in the second histogram. The hypothesis of identity (homogeneity) [3]
1610 /// is that the two histograms represent random values with identical
1611 /// distributions. It is equivalent that there exist r constants p1,...,pr,
1612 /// such that
1613 /// \f[
1614 ///\sum_{i=1}^{r} p_{i}=1
1615 /// \f]
1616 /// and the probability of belonging to the ith bin for some measured value
1617 /// in both experiments is equal to pi. The number of events in the ith
1618 /// bin is a random variable with a distribution approximated by a Poisson
1619 /// probability distribution
1620 /// \f[
1621 ///\frac{e^{-Np_{i}}(Np_{i})^{n_{i}}}{n_{i}!}
1622 /// \f]
1623 ///for the first histogram and with distribution
1624 /// \f[
1625 ///\frac{e^{-Mp_{i}}(Mp_{i})^{m_{i}}}{m_{i}!}
1626 /// \f]
1627 /// for the second histogram. If the hypothesis of homogeneity is valid,
1628 /// then the maximum likelihood estimator of pi, i=1,...,r, is
1629 /// \f[
1630 ///\hat{p}_{i}= \frac{n_{i}+m_{i}}{N+M}
1631 /// \f]
1632 /// and then
1633 /// \f[
1634 /// 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}}
1635 /// \f]
1636 /// has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [3].
1637 /// The comparison procedure can include an analysis of the residuals which
1638 /// is often helpful in identifying the bins of histograms responsible for
1639 /// a significant overall \f$ \chi^{2} \f$ value. Most convenient for
1640 /// analysis are the adjusted (normalized) residuals [4]
1641 /// \f[
1642 /// 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))}}
1643 /// \f]
1644 /// If hypotheses of homogeneity are valid then residuals ri are
1645 /// approximately independent and identically distributed random variables
1646 /// having N(0,1) distribution. The application of the \f$ \chi^{2} \f$ test has
1647 /// restrictions related to the value of the expected frequencies Npi,
1648 /// Mpi, i=1,...,r. A conservative rule formulated in [5] is that all the
1649 /// expectations must be 1 or greater for both histograms. In practical
1650 /// cases when expected frequencies are not known the estimated expected
1651 /// frequencies \f$ M\hat{p}_{i}, N\hat{p}_{i}, i=1,...,r \f$ can be used.
1652 ///
1653 /// #### Unweighted and weighted histograms comparison:
1654 ///
1655 /// A simple modification of the ideas described above can be used for the
1656 /// comparison of the usual (unweighted) and weighted histograms. Let us
1657 /// denote the number of events in the ith bin in the unweighted
1658 /// histogram as ni and the common weight of events in the ith bin of the
1659 /// weighted histogram as wi. The total number of events in the
1660 /// unweighted histogram is equal to
1661 ///\f[
1662 /// N = \sum_{i=1}^{r} n_{i}
1663 ///\f]
1664 /// and the total weight of events in the weighted histogram is equal to
1665 ///\f[
1666 /// W = \sum_{i=1}^{r} w_{i}
1667 ///\f]
1668 /// Let us formulate the hypothesis of identity of an unweighted histogram
1669 /// to a weighted histogram so that there exist r constants p1,...,pr, such
1670 /// that
1671 ///\f[
1672 /// \sum_{i=1}^{r} p_{i} = 1
1673 ///\f]
1674 /// for the unweighted histogram. The weight wi is a random variable with a
1675 /// distribution approximated by the normal probability distribution
1676 /// \f$ N(Wp_{i},\sigma_{i}^{2}) \f$ where \f$ \sigma_{i}^{2} \f$ is the variance of the weight wi.
1677 /// If we replace the variance \f$ \sigma_{i}^{2} \f$
1678 /// with estimate \f$ s_{i}^{2} \f$ (sum of squares of weights of
1679 /// events in the ith bin) and the hypothesis of identity is valid, then the
1680 /// maximum likelihood estimator of pi,i=1,...,r, is
1681 ///\f[
1682 /// \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}}
1683 ///\f]
1684 /// We may then use the test statistic
1685 ///\f[
1686 /// 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}}
1687 ///\f]
1688 /// and it has approximately a \f$ \sigma^{2}_{(r-1)} \f$ distribution [2]. This test, as well
1689 /// as the original one [3], has a restriction on the expected frequencies. The
1690 /// expected frequencies recommended for the weighted histogram is more than 25.
1691 /// The value of the minimal expected frequency can be decreased down to 10 for
1692 /// the case when the weights of the events are close to constant. In the case
1693 /// of a weighted histogram if the number of events is unknown, then we can
1694 /// apply this recommendation for the equivalent number of events as
1695 ///\f[
1696 /// n_{i}^{equiv} = \frac{ w_{i}^{2} }{ s_{i}^{2} }
1697 ///\f]
1698 /// The minimal expected frequency for an unweighted histogram must be 1. Notice
1699 /// that any usual (unweighted) histogram can be considered as a weighted
1700 /// histogram with events that have constant weights equal to 1.
1701 /// The variance \f$ z_{i}^{2} \f$ of the difference between the weight wi
1702 /// and the estimated expectation value of the weight is approximately equal to:
1703 ///\f[
1704 /// 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}
1705 ///\f]
1706 /// The residuals
1707 ///\f[
1708 /// r_{i} = \frac{w_{i}-W\hat{p}_{i}}{z_{i}}
1709 ///\f]
1710 /// have approximately a normal distribution with mean equal to 0 and standard
1711 /// deviation equal to 1.
1712 ///
1713 /// #### Two weighted histograms comparison:
1714 ///
1715 /// Let us denote the common weight of events of the ith bin in the first
1716 /// histogram as w1i and as w2i in the second one. The total weight of events
1717 /// in the first histogram is equal to
1718 ///\f[
1719 /// W_{1} = \sum_{i=1}^{r} w_{1i}
1720 ///\f]
1721 /// and
1722 ///\f[
1723 /// W_{2} = \sum_{i=1}^{r} w_{2i}
1724 ///\f]
1725 /// in the second histogram. Let us formulate the hypothesis of identity of
1726 /// weighted histograms so that there exist r constants p1,...,pr, such that
1727 ///\f[
1728 /// \sum_{i=1}^{r} p_{i} = 1
1729 ///\f]
1730 /// and also expectation value of weight w1i equal to W1pi and expectation value
1731 /// of weight w2i equal to W2pi. Weights in both the histograms are random
1732 /// variables with distributions which can be approximated by a normal
1733 /// probability distribution \f$ N(W_{1}p_{i},\sigma_{1i}^{2}) \f$ for the first histogram
1734 /// and by a distribution \f$ N(W_{2}p_{i},\sigma_{2i}^{2}) \f$ for the second.
1735 /// Here \f$ \sigma_{1i}^{2} \f$ and \f$ \sigma_{2i}^{2} \f$ are the variances
1736 /// of w1i and w2i with estimators \f$ s_{1i}^{2} \f$ and \f$ s_{2i}^{2} \f$ respectively.
1737 /// If the hypothesis of identity is valid, then the maximum likelihood and
1738 /// Least Square Method estimator of pi,i=1,...,r, is
1739 ///\f[
1740 /// \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}}
1741 ///\f]
1742 /// We may then use the test statistic
1743 ///\f[
1744 /// 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}}
1745 ///\f]
1746 /// and it has approximately a \f$ \chi^{2}_{(r-1)} \f$ distribution [2].
1747 /// The normalized or studentised residuals [6]
1748 ///\f[
1749 /// 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})}}}
1750 ///\f]
1751 /// have approximately a normal distribution with mean equal to 0 and standard
1752 /// deviation 1. A recommended minimal expected frequency is equal to 10 for
1753 /// the proposed test.
1754 ///
1755 /// #### Numerical examples:
1756 ///
1757 /// The method described herein is now illustrated with an example.
1758 /// We take a distribution
1759 ///\f[
1760 /// \phi(x) = \frac{2}{(x-10)^{2}+1} + \frac{1}{(x-14)^{2}+1} (1)
1761 ///\f]
1762 /// defined on the interval [4,16]. Events distributed according to the formula
1763 /// (1) are simulated to create the unweighted histogram. Uniformly distributed
1764 /// events are simulated for the weighted histogram with weights calculated by
1765 /// formula (1). Each histogram has the same number of bins: 20. Fig.1 shows
1766 /// the result of comparison of the unweighted histogram with 200 events
1767 /// (minimal expected frequency equal to one) and the weighted histogram with
1768 /// 500 events (minimal expected frequency equal to 25)
1769 /// Begin_Macro
1770 /// ../../../tutorials/math/chi2test.C
1771 /// End_Macro
1772 /// Fig 1. An example of comparison of the unweighted histogram with 200 events
1773 /// and the weighted histogram with 500 events:
1774 /// 1. unweighted histogram;
1775 /// 2. weighted histogram;
1776 /// 3. normalized residuals plot;
1777 /// 4. normal Q-Q plot of residuals.
1778 ///
1779 /// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1780 /// 21.09 with p-value equal to 0.33, therefore the hypothesis of identity of
1781 /// the two histograms can be accepted for 0.05 significant level. The behavior
1782 /// of the normalized residuals plot (see Fig. 1c) and the normal Q-Q plot
1783 /// (see Fig. 1d) of residuals are regular and we cannot identify the outliers
1784 /// or bins with a big influence on \f$ \chi^{2} \f$.
1785 ///
1786 /// The second example presents the same two histograms but 17 events was added
1787 /// to content of bin number 15 in unweighted histogram. Fig.2 shows the result
1788 /// of comparison of the unweighted histogram with 217 events (minimal expected
1789 /// frequency equal to one) and the weighted histogram with 500 events (minimal
1790 /// expected frequency equal to 25)
1791 /// Begin_Macro
1792 /// ../../../tutorials/math/chi2test.C(17)
1793 /// End_Macro
1794 /// Fig 2. An example of comparison of the unweighted histogram with 217 events
1795 /// and the weighted histogram with 500 events:
1796 /// 1. unweighted histogram;
1797 /// 2. weighted histogram;
1798 /// 3. normalized residuals plot;
1799 /// 4. normal Q-Q plot of residuals.
1800 ///
1801 /// The value of the test statistic \f$ \chi^{2} \f$ is equal to
1802 /// 32.33 with p-value equal to 0.029, therefore the hypothesis of identity of
1803 /// the two histograms is rejected for 0.05 significant level. The behavior of
1804 /// the normalized residuals plot (see Fig. 2c) and the normal Q-Q plot (see
1805 /// Fig. 2d) of residuals are not regular and we can identify the outlier or
1806 /// bin with a big influence on \f$ \chi^{2} \f$.
1807 ///
1808 /// #### References:
1809 ///
1810 /// - [1] Pearson, K., 1904. On the Theory of Contingency and Its Relation to
1811 /// Association and Normal Correlation. Drapers' Co. Memoirs, Biometric
1812 /// Series No. 1, London.
1813 /// - [2] Gagunashvili, N., 2006. \f$ \sigma^{2} \f$ test for comparison
1814 /// of weighted and unweighted histograms. Statistical Problems in Particle
1815 /// Physics, Astrophysics and Cosmology, Proceedings of PHYSTAT05,
1816 /// Oxford, UK, 12-15 September 2005, Imperial College Press, London, 43-44.
1817 /// Gagunashvili,N., Comparison of weighted and unweighted histograms,
1818 /// arXiv:physics/0605123, 2006.
1819 /// - [3] Cramer, H., 1946. Mathematical methods of statistics.
1820 /// Princeton University Press, Princeton.
1821 /// - [4] Haberman, S.J., 1973. The analysis of residuals in cross-classified tables.
1822 /// Biometrics 29, 205-220.
1823 /// - [5] Lewontin, R.C. and Felsenstein, J., 1965. The robustness of homogeneity
1824 /// test in 2xN tables. Biometrics 21, 19-33.
1825 /// - [6] Seber, G.A.F., Lee, A.J., 2003, Linear Regression Analysis.
1826 /// John Wiley & Sons Inc., New York.
1827 
1828 Double_t TH1::Chi2Test(const TH1* h2, Option_t *option, Double_t *res) const
1829 {
1830  Double_t chi2 = 0;
1831  Int_t ndf = 0, igood = 0;
1832 
1833  TString opt = option;
1834  opt.ToUpper();
1835 
1836  Double_t prob = Chi2TestX(h2,chi2,ndf,igood,option,res);
1837 
1838  if(opt.Contains("P")) {
1839  printf("Chi2 = %f, Prob = %g, NDF = %d, igood = %d\n", chi2,prob,ndf,igood);
1840  }
1841  if(opt.Contains("CHI2/NDF")) {
1842  if (ndf == 0) return 0;
1843  return chi2/ndf;
1844  }
1845  if(opt.Contains("CHI2")) {
1846  return chi2;
1847  }
1848 
1849  return prob;
1850 }
1851 
1852 ////////////////////////////////////////////////////////////////////////////////
1853 /// The computation routine of the Chisquare test. For the method description,
1854 /// see Chi2Test() function.
1855 ///
1856 /// \return p-value
1857 /// \param[in] h2 the second histogram
1858 /// \param[in] option
1859 /// - "UU" = experiment experiment comparison (unweighted-unweighted)
1860 /// - "UW" = experiment MC comparison (unweighted-weighted). Note that the first
1861 /// histogram should be unweighted
1862 /// - "WW" = MC MC comparison (weighted-weighted)
1863 /// - "NORM" = if one or both histograms is scaled
1864 /// - "OF" = overflows included
1865 /// - "UF" = underflows included
1866 /// by default underflows and overflows are not included
1867 /// \param[out] igood test output
1868 /// - igood=0 - no problems
1869 /// - For unweighted unweighted comparison
1870 /// - igood=1'There is a bin in the 1st histogram with less than 1 event'
1871 /// - igood=2'There is a bin in the 2nd histogram with less than 1 event'
1872 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1873 /// - For unweighted weighted comparison
1874 /// - igood=1'There is a bin in the 1st histogram with less then 1 event'
1875 /// - igood=2'There is a bin in the 2nd histogram with less then 10 effective number of events'
1876 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1877 /// - For weighted weighted comparison
1878 /// - igood=1'There is a bin in the 1st histogram with less then 10 effective
1879 /// number of events'
1880 /// - igood=2'There is a bin in the 2nd histogram with less then 10 effective
1881 /// number of events'
1882 /// - igood=3'when the conditions for igood=1 and igood=2 are satisfied'
1883 /// \param[out] chi2 chisquare of the test
1884 /// \param[out] ndf number of degrees of freedom (important, when both histograms have the same empty bins)
1885 /// \param[out] res normalized residuals for further analysis
1886 
1887 Double_t TH1::Chi2TestX(const TH1* h2, Double_t &chi2, Int_t &ndf, Int_t &igood, Option_t *option, Double_t *res) const
1888 {
1890  Int_t i_start, i_end;
1891  Int_t j_start, j_end;
1892  Int_t k_start, k_end;
1893 
1894  Double_t sum1 = 0.0, sumw1 = 0.0;
1895  Double_t sum2 = 0.0, sumw2 = 0.0;
1896 
1897  chi2 = 0.0;
1898  ndf = 0;
1899 
1900  TString opt = option;
1901  opt.ToUpper();
1902 
1903  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
1904 
1905  const TAxis *xaxis1 = GetXaxis();
1906  const TAxis *xaxis2 = h2->GetXaxis();
1907  const TAxis *yaxis1 = GetYaxis();
1908  const TAxis *yaxis2 = h2->GetYaxis();
1909  const TAxis *zaxis1 = GetZaxis();
1910  const TAxis *zaxis2 = h2->GetZaxis();
1911 
1912  Int_t nbinx1 = xaxis1->GetNbins();
1913  Int_t nbinx2 = xaxis2->GetNbins();
1914  Int_t nbiny1 = yaxis1->GetNbins();
1915  Int_t nbiny2 = yaxis2->GetNbins();
1916  Int_t nbinz1 = zaxis1->GetNbins();
1917  Int_t nbinz2 = zaxis2->GetNbins();
1918 
1919  //check dimensions
1920  if (this->GetDimension() != h2->GetDimension() ){
1921  Error("Chi2TestX","Histograms have different dimensions.");
1922  return 0.0;
1923  }
1924 
1925  //check number of channels
1926  if (nbinx1 != nbinx2) {
1927  Error("Chi2TestX","different number of x channels");
1928  }
1929  if (nbiny1 != nbiny2) {
1930  Error("Chi2TestX","different number of y channels");
1931  }
1932  if (nbinz1 != nbinz2) {
1933  Error("Chi2TestX","different number of z channels");
1934  }
1935 
1936  //check for ranges
1937  i_start = j_start = k_start = 1;
1938  i_end = nbinx1;
1939  j_end = nbiny1;
1940  k_end = nbinz1;
1941 
1942  if (xaxis1->TestBit(TAxis::kAxisRange)) {
1943  i_start = xaxis1->GetFirst();
1944  i_end = xaxis1->GetLast();
1945  }
1946  if (yaxis1->TestBit(TAxis::kAxisRange)) {
1947  j_start = yaxis1->GetFirst();
1948  j_end = yaxis1->GetLast();
1949  }
1950  if (zaxis1->TestBit(TAxis::kAxisRange)) {
1951  k_start = zaxis1->GetFirst();
1952  k_end = zaxis1->GetLast();
1953  }
1954 
1955 
1956  if (opt.Contains("OF")) {
1957  if (GetDimension() == 3) k_end = ++nbinz1;
1958  if (GetDimension() >= 2) j_end = ++nbiny1;
1959  if (GetDimension() >= 1) i_end = ++nbinx1;
1960  }
1961 
1962  if (opt.Contains("UF")) {
1963  if (GetDimension() == 3) k_start = 0;
1964  if (GetDimension() >= 2) j_start = 0;
1965  if (GetDimension() >= 1) i_start = 0;
1966  }
1967 
1968  ndf = (i_end - i_start + 1) * (j_end - j_start + 1) * (k_end - k_start + 1) - 1;
1969 
1970  Bool_t comparisonUU = opt.Contains("UU");
1971  Bool_t comparisonUW = opt.Contains("UW");
1972  Bool_t comparisonWW = opt.Contains("WW");
1973  Bool_t scaledHistogram = opt.Contains("NORM");
1974 
1975  if (scaledHistogram && !comparisonUU) {
1976  Info("Chi2TestX", "NORM option should be used together with UU option. It is ignored");
1977  }
1978 
1979  // look at histo global bin content and effective entries
1980  Stat_t s[kNstat];
1981  GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
1982  Double_t sumBinContent1 = s[0];
1983  Double_t effEntries1 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
1984 
1985  h2->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
1986  Double_t sumBinContent2 = s[0];
1987  Double_t effEntries2 = (s[1] ? s[0] * s[0] / s[1] : 0.0);
1988 
1989  if (!comparisonUU && !comparisonUW && !comparisonWW ) {
1990  // deduce automatically from type of histogram
1991  if (TMath::Abs(sumBinContent1 - effEntries1) < 1) {
1992  if ( TMath::Abs(sumBinContent2 - effEntries2) < 1) comparisonUU = true;
1993  else comparisonUW = true;
1994  }
1995  else comparisonWW = true;
1996  }
1997  // check unweighted histogram
1998  if (comparisonUW) {
1999  if (TMath::Abs(sumBinContent1 - effEntries1) >= 1) {
2000  Warning("Chi2TestX","First histogram is not unweighted and option UW has been requested");
2001  }
2002  }
2003  if ( (!scaledHistogram && comparisonUU) ) {
2004  if ( ( TMath::Abs(sumBinContent1 - effEntries1) >= 1) || (TMath::Abs(sumBinContent2 - effEntries2) >= 1) ) {
2005  Warning("Chi2TestX","Both histograms are not unweighted and option UU has been requested");
2006  }
2007  }
2008 
2009 
2010  //get number of events in histogram
2011  if (comparisonUU && scaledHistogram) {
2012  for (Int_t i = i_start; i <= i_end; ++i) {
2013  for (Int_t j = j_start; j <= j_end; ++j) {
2014  for (Int_t k = k_start; k <= k_end; ++k) {
2015 
2016  Int_t bin = GetBin(i, j, k);
2017 
2018  Double_t cnt1 = RetrieveBinContent(bin);
2019  Double_t cnt2 = h2->RetrieveBinContent(bin);
2020  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2021  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2022 
2023  if (e1sq > 0.0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2024  else cnt1 = 0.0;
2025 
2026  if (e2sq > 0.0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2027  else cnt2 = 0.0;
2028 
2029  // sum contents
2030  sum1 += cnt1;
2031  sum2 += cnt2;
2032  sumw1 += e1sq;
2033  sumw2 += e2sq;
2034  }
2035  }
2036  }
2037  if (sumw1 <= 0.0 || sumw2 <= 0.0) {
2038  Error("Chi2TestX", "Cannot use option NORM when one histogram has all zero errors");
2039  return 0.0;
2040  }
2041 
2042  } else {
2043  for (Int_t i = i_start; i <= i_end; ++i) {
2044  for (Int_t j = j_start; j <= j_end; ++j) {
2045  for (Int_t k = k_start; k <= k_end; ++k) {
2046 
2047  Int_t bin = GetBin(i, j, k);
2048 
2049  sum1 += RetrieveBinContent(bin);
2050  sum2 += h2->RetrieveBinContent(bin);
2051 
2052  if ( comparisonWW ) sumw1 += GetBinErrorSqUnchecked(bin);
2053  if ( comparisonUW || comparisonWW ) sumw2 += h2->GetBinErrorSqUnchecked(bin);
2054  }
2055  }
2056  }
2057  }
2058  //checks that the histograms are not empty
2059  if (sum1 == 0.0 || sum2 == 0.0) {
2060  Error("Chi2TestX","one histogram is empty");
2061  return 0.0;
2062  }
2063 
2064  if ( comparisonWW && ( sumw1 <= 0.0 && sumw2 <= 0.0 ) ){
2065  Error("Chi2TestX","Hist1 and Hist2 have both all zero errors\n");
2066  return 0.0;
2067  }
2068 
2069  //THE TEST
2070  Int_t m = 0, n = 0;
2071 
2072  //Experiment - experiment comparison
2073  if (comparisonUU) {
2074  Double_t sum = sum1 + sum2;
2075  for (Int_t i = i_start; i <= i_end; ++i) {
2076  for (Int_t j = j_start; j <= j_end; ++j) {
2077  for (Int_t k = k_start; k <= k_end; ++k) {
2078 
2079  Int_t bin = GetBin(i, j, k);
2080 
2081  Double_t cnt1 = RetrieveBinContent(bin);
2082  Double_t cnt2 = h2->RetrieveBinContent(bin);
2083 
2084  if (scaledHistogram) {
2085  // scale bin value to effective bin entries
2086  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2087  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2088 
2089  if (e1sq > 0) cnt1 = TMath::Floor(cnt1 * cnt1 / e1sq + 0.5); // avoid rounding errors
2090  else cnt1 = 0;
2091 
2092  if (e2sq > 0) cnt2 = TMath::Floor(cnt2 * cnt2 / e2sq + 0.5); // avoid rounding errors
2093  else cnt2 = 0;
2094  }
2095 
2096  if (Int_t(cnt1) == 0 && Int_t(cnt2) == 0) --ndf; // no data means one degree of freedom less
2097  else {
2098 
2099  Double_t cntsum = cnt1 + cnt2;
2100  Double_t nexp1 = cntsum * sum1 / sum;
2101  //Double_t nexp2 = binsum*sum2/sum;
2102 
2103  if (res) res[i - i_start] = (cnt1 - nexp1) / TMath::Sqrt(nexp1);
2104 
2105  if (cnt1 < 1) ++m;
2106  if (cnt2 < 1) ++n;
2107 
2108  //Habermann correction for residuals
2109  Double_t correc = (1. - sum1 / sum) * (1. - cntsum / sum);
2110  if (res) res[i - i_start] /= TMath::Sqrt(correc);
2111 
2112  Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2113  chi2 += delta * delta / cntsum;
2114  }
2115  }
2116  }
2117  }
2118  chi2 /= sum1 * sum2;
2119 
2120  // flag error only when of the two histogram is zero
2121  if (m) {
2122  igood += 1;
2123  Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2124  }
2125  if (n) {
2126  igood += 2;
2127  Info("Chi2TestX","There is a bin in h2 with less than 1 event.\n");
2128  }
2129 
2130  Double_t prob = TMath::Prob(chi2,ndf);
2131  return prob;
2132 
2133  }
2134 
2135  // unweighted - weighted comparison
2136  // case of error = 0 and content not zero is treated without problems by excluding second chi2 sum
2137  // and can be considered as a data-theory comparison
2138  if ( comparisonUW ) {
2139  for (Int_t i = i_start; i <= i_end; ++i) {
2140  for (Int_t j = j_start; j <= j_end; ++j) {
2141  for (Int_t k = k_start; k <= k_end; ++k) {
2142 
2143  Int_t bin = GetBin(i, j, k);
2144 
2145  Double_t cnt1 = RetrieveBinContent(bin);
2146  Double_t cnt2 = h2->RetrieveBinContent(bin);
2147  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2148 
2149  // case both histogram have zero bin contents
2150  if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2151  --ndf; //no data means one degree of freedom less
2152  continue;
2153  }
2154 
2155  // case weighted histogram has zero bin content and error
2156  if (cnt2 * cnt2 == 0 && e2sq == 0) {
2157  if (sumw2 > 0) {
2158  // use as approximated error as 1 scaled by a scaling ratio
2159  // estimated from the total sum weight and sum weight squared
2160  e2sq = sumw2 / sum2;
2161  }
2162  else {
2163  // return error because infinite discrepancy here:
2164  // bin1 != 0 and bin2 =0 in a histogram with all errors zero
2165  Error("Chi2TestX","Hist2 has in bin (%d,%d,%d) zero content and zero errors\n", i, j, k);
2166  chi2 = 0; return 0;
2167  }
2168  }
2169 
2170  if (cnt1 < 1) m++;
2171  if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2172 
2173  Double_t var1 = sum2 * cnt2 - sum1 * e2sq;
2174  Double_t var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2175 
2176  // if cnt1 is zero and cnt2 = 1 and sum1 = sum2 var1 = 0 && var2 == 0
2177  // approximate by incrementing cnt1
2178  // LM (this need to be fixed for numerical errors)
2179  while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2180  sum1++;
2181  cnt1++;
2182  var1 = sum2 * cnt2 - sum1 * e2sq;
2183  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2184  }
2185  var2 = TMath::Sqrt(var2);
2186 
2187  while (var1 + var2 == 0) {
2188  sum1++;
2189  cnt1++;
2190  var1 = sum2 * cnt2 - sum1 * e2sq;
2191  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2192  while (var1 * var1 + cnt1 == 0 || var1 + var2 == 0) {
2193  sum1++;
2194  cnt1++;
2195  var1 = sum2 * cnt2 - sum1 * e2sq;
2196  var2 = var1 * var1 + 4. * sum2 * sum2 * cnt1 * e2sq;
2197  }
2198  var2 = TMath::Sqrt(var2);
2199  }
2200 
2201  Double_t probb = (var1 + var2) / (2. * sum2 * sum2);
2202 
2203  Double_t nexp1 = probb * sum1;
2204  Double_t nexp2 = probb * sum2;
2205 
2206  Double_t delta1 = cnt1 - nexp1;
2207  Double_t delta2 = cnt2 - nexp2;
2208 
2209  chi2 += delta1 * delta1 / nexp1;
2210 
2211  if (e2sq > 0) {
2212  chi2 += delta2 * delta2 / e2sq;
2213  }
2214 
2215  if (res) {
2216  if (e2sq > 0) {
2217  Double_t temp1 = sum2 * e2sq / var2;
2218  Double_t temp2 = 1.0 + (sum1 * e2sq - sum2 * cnt2) / var2;
2219  temp2 = temp1 * temp1 * sum1 * probb * (1.0 - probb) + temp2 * temp2 * e2sq / 4.0;
2220  // invert sign here
2221  res[i - i_start] = - delta2 / TMath::Sqrt(temp2);
2222  }
2223  else
2224  res[i - i_start] = delta1 / TMath::Sqrt(nexp1);
2225  }
2226  }
2227  }
2228  }
2229 
2230  if (m) {
2231  igood += 1;
2232  Info("Chi2TestX","There is a bin in h1 with less than 1 event.\n");
2233  }
2234  if (n) {
2235  igood += 2;
2236  Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2237  }
2238 
2239  Double_t prob = TMath::Prob(chi2, ndf);
2240 
2241  return prob;
2242  }
2243 
2244  // weighted - weighted comparison
2245  if (comparisonWW) {
2246  for (Int_t i = i_start; i <= i_end; ++i) {
2247  for (Int_t j = j_start; j <= j_end; ++j) {
2248  for (Int_t k = k_start; k <= k_end; ++k) {
2249 
2250  Int_t bin = GetBin(i, j, k);
2251  Double_t cnt1 = RetrieveBinContent(bin);
2252  Double_t cnt2 = h2->RetrieveBinContent(bin);
2253  Double_t e1sq = GetBinErrorSqUnchecked(bin);
2254  Double_t e2sq = h2->GetBinErrorSqUnchecked(bin);
2255 
2256  // case both histogram have zero bin contents
2257  // (use square of content to avoid numerical errors)
2258  if (cnt1 * cnt1 == 0 && cnt2 * cnt2 == 0) {
2259  --ndf; //no data means one degree of freedom less
2260  continue;
2261  }
2262 
2263  if (e1sq == 0 && e2sq == 0) {
2264  // cannot treat case of booth histogram have zero zero errors
2265  Error("Chi2TestX","h1 and h2 both have bin %d,%d,%d with all zero errors\n", i,j,k);
2266  chi2 = 0; return 0;
2267  }
2268 
2269  Double_t sigma = sum1 * sum1 * e2sq + sum2 * sum2 * e1sq;
2270  Double_t delta = sum2 * cnt1 - sum1 * cnt2;
2271  chi2 += delta * delta / sigma;
2272 
2273  if (res) {
2274  Double_t temp = cnt1 * sum1 * e2sq + cnt2 * sum2 * e1sq;
2275  Double_t probb = temp / sigma;
2276  Double_t z = 0;
2277  if (e1sq > e2sq) {
2278  Double_t d1 = cnt1 - sum1 * probb;
2279  Double_t s1 = e1sq * ( 1. - e2sq * sum1 * sum1 / sigma );
2280  z = d1 / TMath::Sqrt(s1);
2281  }
2282  else {
2283  Double_t d2 = cnt2 - sum2 * probb;
2284  Double_t s2 = e2sq * ( 1. - e1sq * sum2 * sum2 / sigma );
2285  z = -d2 / TMath::Sqrt(s2);
2286  }
2287  res[i - i_start] = z;
2288  }
2289 
2290  if (e1sq > 0 && cnt1 * cnt1 / e1sq < 10) m++;
2291  if (e2sq > 0 && cnt2 * cnt2 / e2sq < 10) n++;
2292  }
2293  }
2294  }
2295  if (m) {
2296  igood += 1;
2297  Info("Chi2TestX","There is a bin in h1 with less than 10 effective events.\n");
2298  }
2299  if (n) {
2300  igood += 2;
2301  Info("Chi2TestX","There is a bin in h2 with less than 10 effective events.\n");
2302  }
2303  Double_t prob = TMath::Prob(chi2, ndf);
2304  return prob;
2305  }
2306  return 0;
2307 }
2308 ////////////////////////////////////////////////////////////////////////////////
2309 /// Compute and return the chisquare of this histogram with respect to a function
2310 /// The chisquare is computed by weighting each histogram point by the bin error
2311 /// By default the full range of the histogram is used.
2312 /// Use option "R" for restricting the chisquare calculation to the given range of the function
2313 /// Use option "L" for using the chisquare based on the poisson likelihood (Baker-Cousins Chisquare)
2314 
2315 Double_t TH1::Chisquare(TF1 * func, Option_t *option) const
2316 {
2317  if (!func) {
2318  Error("Chisquare","Function pointer is Null - return -1");
2319  return -1;
2320  }
2321 
2322  TString opt(option); opt.ToUpper();
2323  bool useRange = opt.Contains("R");
2324  bool usePL = opt.Contains("L");
2325 
2326  return ROOT::Fit::Chisquare(*this, *func, useRange, usePL);
2327 }
2328 
2329 ////////////////////////////////////////////////////////////////////////////////
2330 /// Remove all the content from the underflow and overflow bins, without changing the number of entries
2331 /// After calling this method, every undeflow and overflow bins will have content 0.0
2332 /// The Sumw2 is also cleared, since there is no more content in the bins
2333 
2335 {
2336  for (Int_t bin = 0; bin < fNcells; ++bin)
2337  if (IsBinUnderflow(bin) || IsBinOverflow(bin)) {
2338  UpdateBinContent(bin, 0.0);
2339  if (fSumw2.fN) fSumw2.fArray[bin] = 0.0;
2340  }
2341 }
2342 
2343 ////////////////////////////////////////////////////////////////////////////////
2344 /// Compute integral (cumulative sum of bins)
2345 /// The result stored in fIntegral is used by the GetRandom functions.
2346 /// This function is automatically called by GetRandom when the fIntegral
2347 /// array does not exist or when the number of entries in the histogram
2348 /// has changed since the previous call to GetRandom.
2349 /// The resulting integral is normalized to 1
2350 /// If the routine is called with the onlyPositive flag set an error will
2351 /// be produced in case of negative bin content and a NaN value returned
2352 
2353 Double_t TH1::ComputeIntegral(Bool_t onlyPositive)
2354 {
2356 
2357  // delete previously computed integral (if any)
2358  if (fIntegral) delete [] fIntegral;
2359 
2360  // - Allocate space to store the integral and compute integral
2361  Int_t nbinsx = GetNbinsX();
2362  Int_t nbinsy = GetNbinsY();
2363  Int_t nbinsz = GetNbinsZ();
2364  Int_t nbins = nbinsx * nbinsy * nbinsz;
2365 
2366  fIntegral = new Double_t[nbins + 2];
2367  Int_t ibin = 0; fIntegral[ibin] = 0;
2368 
2369  for (Int_t binz=1; binz <= nbinsz; ++binz) {
2370  for (Int_t biny=1; biny <= nbinsy; ++biny) {
2371  for (Int_t binx=1; binx <= nbinsx; ++binx) {
2372  ++ibin;
2373  Double_t y = RetrieveBinContent(GetBin(binx, biny, binz));
2374  if (onlyPositive && y < 0) {
2375  Error("ComputeIntegral","Bin content is negative - return a NaN value");
2377  break;
2378  }
2379  fIntegral[ibin] = fIntegral[ibin - 1] + y;
2380  }
2381  }
2382  }
2383 
2384  // - Normalize integral to 1
2385  if (fIntegral[nbins] == 0 ) {
2386  Error("ComputeIntegral", "Integral = zero"); return 0;
2387  }
2388  for (Int_t bin=1; bin <= nbins; ++bin) fIntegral[bin] /= fIntegral[nbins];
2389  fIntegral[nbins+1] = fEntries;
2390  return fIntegral[nbins];
2391 }
2392 
2393 ////////////////////////////////////////////////////////////////////////////////
2394 /// Return a pointer to the array of bins integral.
2395 /// if the pointer fIntegral is null, TH1::ComputeIntegral is called
2396 /// The array dimension is the number of bins in the histograms
2397 /// including underflow and overflow (fNCells)
2398 /// the last value integral[fNCells] is set to the number of entries of
2399 /// the histogram
2400 
2402 {
2404  return fIntegral;
2405 }
2406 
2407 ////////////////////////////////////////////////////////////////////////////////
2408 /// Return a pointer to an histogram containing the cumulative The
2409 /// cumulative can be computed both in the forward (default) or backward
2410 /// direction; the name of the new histogram is constructed from
2411 /// the name of this histogram with the suffix suffix appended.
2412 ///
2413 /// The cumulative distribution is formed by filling each bin of the
2414 /// resulting histogram with the sum of that bin and all previous
2415 /// (forward == kTRUE) or following (forward = kFALSE) bins.
2416 ///
2417 /// note: while cumulative distributions make sense in one dimension, you
2418 /// may not be getting what you expect in more than 1D because the concept
2419 /// of a cumulative distribution is much trickier to define; make sure you
2420 /// understand the order of summation before you use this method with
2421 /// histograms of dimension >= 2.
2422 
2423 TH1 *TH1::GetCumulative(Bool_t forward, const char* suffix) const
2424 {
2425  const Int_t nbinsx = GetNbinsX();
2426  const Int_t nbinsy = GetNbinsY();
2427  const Int_t nbinsz = GetNbinsZ();
2428  TH1* hintegrated = (TH1*) Clone(fName + suffix);
2429  hintegrated->Reset();
2430  if (forward) { // Forward computation
2431  Double_t sum = 0.;
2432  for (Int_t binz = 1; binz <= nbinsz; ++binz) {
2433  for (Int_t biny = 1; biny <= nbinsy; ++biny) {
2434  for (Int_t binx = 1; binx <= nbinsx; ++binx) {
2435  const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2436  sum += GetBinContent(bin);
2437  hintegrated->SetBinContent(bin, sum);
2438  }
2439  }
2440  }
2441  } else { // Backward computation
2442  Double_t sum = 0.;
2443  for (Int_t binz = nbinsz; binz >= 1; --binz) {
2444  for (Int_t biny = nbinsy; biny >= 1; --biny) {
2445  for (Int_t binx = nbinsx; binx >= 1; --binx) {
2446  const Int_t bin = hintegrated->GetBin(binx, biny, binz);
2447  sum += GetBinContent(bin);
2448  hintegrated->SetBinContent(bin, sum);
2449  }
2450  }
2451  }
2452  }
2453  return hintegrated;
2454 }
2455 
2456 ////////////////////////////////////////////////////////////////////////////////
2457 /// Copy this histogram structure to newth1.
2458 ///
2459 /// Note that this function does not copy the list of associated functions.
2460 /// Use TObject::Clone to make a full copy of an histogram.
2461 ///
2462 /// Note also that the histogram it will be created in gDirectory (if AddDirectoryStatus()=true)
2463 /// or will not be added to any directory if AddDirectoryStatus()=false
2464 /// independently of the current directory stored in the original histogram
2465 
2466 void TH1::Copy(TObject &obj) const
2467 {
2468  if (((TH1&)obj).fDirectory) {
2469  // We are likely to change the hash value of this object
2470  // with TNamed::Copy, to keep things correct, we need to
2471  // clean up its existing entries.
2472  ((TH1&)obj).fDirectory->Remove(&obj);
2473  ((TH1&)obj).fDirectory = 0;
2474  }
2475  TNamed::Copy(obj);
2476  ((TH1&)obj).fDimension = fDimension;
2477  ((TH1&)obj).fNormFactor= fNormFactor;
2478  ((TH1&)obj).fNcells = fNcells;
2479  ((TH1&)obj).fBarOffset = fBarOffset;
2480  ((TH1&)obj).fBarWidth = fBarWidth;
2481  ((TH1&)obj).fOption = fOption;
2482  ((TH1&)obj).fBinStatErrOpt = fBinStatErrOpt;
2483  ((TH1&)obj).fBufferSize= fBufferSize;
2484  // copy the Buffer
2485  // delete first a previously existing buffer
2486  if (((TH1&)obj).fBuffer != 0) {
2487  delete [] ((TH1&)obj).fBuffer;
2488  ((TH1&)obj).fBuffer = 0;
2489  }
2490  if (fBuffer) {
2491  Double_t *buf = new Double_t[fBufferSize];
2492  for (Int_t i=0;i<fBufferSize;i++) buf[i] = fBuffer[i];
2493  // obj.fBuffer has been deleted before
2494  ((TH1&)obj).fBuffer = buf;
2495  }
2496 
2497 
2498  TArray* a = dynamic_cast<TArray*>(&obj);
2499  if (a) a->Set(fNcells);
2500  for (Int_t i = 0; i < fNcells; i++) ((TH1&)obj).UpdateBinContent(i, RetrieveBinContent(i));
2501 
2502  ((TH1&)obj).fEntries = fEntries;
2503 
2504  // which will call BufferEmpty(0) and set fBuffer[0] to a Maybe one should call
2505  // assignment operator on the TArrayD
2506 
2507  ((TH1&)obj).fTsumw = fTsumw;
2508  ((TH1&)obj).fTsumw2 = fTsumw2;
2509  ((TH1&)obj).fTsumwx = fTsumwx;
2510  ((TH1&)obj).fTsumwx2 = fTsumwx2;
2511  ((TH1&)obj).fMaximum = fMaximum;
2512  ((TH1&)obj).fMinimum = fMinimum;
2513 
2514  TAttLine::Copy(((TH1&)obj));
2515  TAttFill::Copy(((TH1&)obj));
2516  TAttMarker::Copy(((TH1&)obj));
2517  fXaxis.Copy(((TH1&)obj).fXaxis);
2518  fYaxis.Copy(((TH1&)obj).fYaxis);
2519  fZaxis.Copy(((TH1&)obj).fZaxis);
2520  ((TH1&)obj).fXaxis.SetParent(&obj);
2521  ((TH1&)obj).fYaxis.SetParent(&obj);
2522  ((TH1&)obj).fZaxis.SetParent(&obj);
2523  fContour.Copy(((TH1&)obj).fContour);
2524  fSumw2.Copy(((TH1&)obj).fSumw2);
2525  // fFunctions->Copy(((TH1&)obj).fFunctions);
2526  // when copying an histogram if the AddDirectoryStatus() is true it
2527  // will be added to gDirectory independently of the fDirectory stored.
2528  // and if the AddDirectoryStatus() is false it will not be added to
2529  // any directory (fDirectory = 0)
2530  if (fgAddDirectory && gDirectory) {
2531  gDirectory->Append(&obj);
2532  ((TH1&)obj).fDirectory = gDirectory;
2533  } else
2534  ((TH1&)obj).fDirectory = 0;
2535 
2536 }
2537 
2538 ////////////////////////////////////////////////////////////////////////////////
2539 /// Make a complete copy of the underlying object. If 'newname' is set,
2540 /// the copy's name will be set to that name.
2541 
2542 TObject* TH1::Clone(const char* newname) const
2543 {
2544  TH1* obj = (TH1*)IsA()->GetNew()(0);
2545  Copy(*obj);
2546 
2547  //Now handle the parts that Copy doesn't do
2548  if(fFunctions) {
2549  if (obj->fFunctions) delete obj->fFunctions;
2550  obj->fFunctions = (TList*)fFunctions->Clone();
2551  }
2552  if(newname && strlen(newname) ) {
2553  obj->SetName(newname);
2554  }
2555  return obj;
2556 }
2557 
2558 ////////////////////////////////////////////////////////////////////////////////
2559 /// Perform the automatic addition of the histogram to the given directory
2560 ///
2561 /// Note this function is called in place when the semantic requires
2562 /// this object to be added to a directory (I.e. when being read from
2563 /// a TKey or being Cloned)
2564 
2566 {
2568  if (addStatus) {
2569  SetDirectory(dir);
2570  if (dir) {
2572  }
2573  }
2574 }
2575 
2576 ////////////////////////////////////////////////////////////////////////////////
2577 /// Compute distance from point px,py to a line.
2578 ///
2579 /// Compute the closest distance of approach from point px,py to elements
2580 /// of an histogram.
2581 /// The distance is computed in pixels units.
2582 ///
2583 /// #### Algorithm:
2584 /// Currently, this simple model computes the distance from the mouse
2585 /// to the histogram contour only.
2586 
2588 {
2589  if (!fPainter) return 9999;
2590  return fPainter->DistancetoPrimitive(px,py);
2591 }
2592 
2593 ////////////////////////////////////////////////////////////////////////////////
2594 /// Performs the operation: `this = this/(c1*f1)`
2595 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2596 ///
2597 /// Only bins inside the function range are recomputed.
2598 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2599 /// you should call Sumw2 before making this operation.
2600 /// This is particularly important if you fit the histogram after TH1::Divide
2601 ///
2602 /// The function return kFALSE if the divide operation failed
2603 
2605 {
2606  if (!f1) {
2607  Error("Add","Attempt to divide by a non-existing function");
2608  return kFALSE;
2609  }
2610 
2611  // delete buffer if it is there since it will become invalid
2612  if (fBuffer) BufferEmpty(1);
2613 
2614  Int_t nx = GetNbinsX() + 2; // normal bins + uf / of
2615  Int_t ny = GetNbinsY() + 2;
2616  Int_t nz = GetNbinsZ() + 2;
2617  if (fDimension < 2) ny = 1;
2618  if (fDimension < 3) nz = 1;
2619 
2620 
2621  SetMinimum();
2622  SetMaximum();
2623 
2624  // - Loop on bins (including underflows/overflows)
2625  Int_t bin, binx, biny, binz;
2626  Double_t cu, w;
2627  Double_t xx[3];
2628  Double_t *params = 0;
2629  f1->InitArgs(xx,params);
2630  for (binz = 0; binz < nz; ++binz) {
2631  xx[2] = fZaxis.GetBinCenter(binz);
2632  for (biny = 0; biny < ny; ++biny) {
2633  xx[1] = fYaxis.GetBinCenter(biny);
2634  for (binx = 0; binx < nx; ++binx) {
2635  xx[0] = fXaxis.GetBinCenter(binx);
2636  if (!f1->IsInside(xx)) continue;
2638  bin = binx + nx * (biny + ny * binz);
2639  cu = c1 * f1->EvalPar(xx);
2640  if (TF1::RejectedPoint()) continue;
2641  if (cu) w = RetrieveBinContent(bin) / cu;
2642  else w = 0;
2643  UpdateBinContent(bin, w);
2644  if (fSumw2.fN) {
2645  if (cu != 0) fSumw2.fArray[bin] = GetBinErrorSqUnchecked(bin) / (cu * cu);
2646  else fSumw2.fArray[bin] = 0;
2647  }
2648  }
2649  }
2650  }
2651  ResetStats();
2652  return kTRUE;
2653 }
2654 
2655 ////////////////////////////////////////////////////////////////////////////////
2656 /// Divide this histogram by h1.
2657 ///
2658 /// `this = this/h1`
2659 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
2660 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
2661 /// if not already set.
2662 /// The resulting errors are calculated assuming uncorrelated histograms.
2663 /// See the other TH1::Divide that gives the possibility to optionally
2664 /// compute binomial errors.
2665 ///
2666 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2667 /// you should call Sumw2 before making this operation.
2668 /// This is particularly important if you fit the histogram after TH1::Scale
2669 ///
2670 /// The function return kFALSE if the divide operation failed
2671 
2672 Bool_t TH1::Divide(const TH1 *h1)
2673 {
2674  if (!h1) {
2675  Error("Divide", "Input histogram passed does not exist (NULL).");
2676  return kFALSE;
2677  }
2678 
2679  // delete buffer if it is there since it will become invalid
2680  if (fBuffer) BufferEmpty(1);
2681 
2682  try {
2683  CheckConsistency(this,h1);
2684  } catch(DifferentNumberOfBins&) {
2685  Error("Divide","Cannot divide histograms with different number of bins");
2686  return kFALSE;
2687  } catch(DifferentAxisLimits&) {
2688  Warning("Divide","Dividing histograms with different axis limits");
2689  } catch(DifferentBinLimits&) {
2690  Warning("Divide","Dividing histograms with different bin limits");
2691  } catch(DifferentLabels&) {
2692  Warning("Divide","Dividing histograms with different labels");
2693  }
2694 
2695  // Create Sumw2 if h1 has Sumw2 set
2696  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
2697 
2698  // - Loop on bins (including underflows/overflows)
2699  for (Int_t i = 0; i < fNcells; ++i) {
2700  Double_t c0 = RetrieveBinContent(i);
2701  Double_t c1 = h1->RetrieveBinContent(i);
2702  if (c1) UpdateBinContent(i, c0 / c1);
2703  else UpdateBinContent(i, 0);
2704 
2705  if(fSumw2.fN) {
2706  if (c1 == 0) { fSumw2.fArray[i] = 0; continue; }
2707  Double_t c1sq = c1 * c1;
2708  fSumw2.fArray[i] = (GetBinErrorSqUnchecked(i) * c1sq + h1->GetBinErrorSqUnchecked(i) * c0 * c0) / (c1sq * c1sq);
2709  }
2710  }
2711  ResetStats();
2712  return kTRUE;
2713 }
2714 
2715 ////////////////////////////////////////////////////////////////////////////////
2716 /// Replace contents of this histogram by the division of h1 by h2.
2717 ///
2718 /// `this = c1*h1/(c2*h2)`
2719 ///
2720 /// If errors are defined (see TH1::Sumw2), errors are also recalculated
2721 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
2722 /// if not already set.
2723 /// The resulting errors are calculated assuming uncorrelated histograms.
2724 /// However, if option ="B" is specified, Binomial errors are computed.
2725 /// In this case c1 and c2 do not make real sense and they are ignored.
2726 ///
2727 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
2728 /// you should call Sumw2 before making this operation.
2729 /// This is particularly important if you fit the histogram after TH1::Divide
2730 ///
2731 /// Please note also that in the binomial case errors are calculated using standard
2732 /// binomial statistics, which means when b1 = b2, the error is zero.
2733 /// If you prefer to have efficiency errors not going to zero when the efficiency is 1, you must
2734 /// use the function TGraphAsymmErrors::BayesDivide, which will return an asymmetric and non-zero lower
2735 /// error for the case b1=b2.
2736 ///
2737 /// The function return kFALSE if the divide operation failed
2738 
2739 Bool_t TH1::Divide(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2, Option_t *option)
2740 {
2742  TString opt = option;
2743  opt.ToLower();
2744  Bool_t binomial = kFALSE;
2745  if (opt.Contains("b")) binomial = kTRUE;
2746  if (!h1 || !h2) {
2747  Error("Divide", "At least one of the input histograms passed does not exist (NULL).");
2748  return kFALSE;
2749  }
2750 
2751  // delete buffer if it is there since it will become invalid
2752  if (fBuffer) BufferEmpty(1);
2753 
2754  try {
2755  CheckConsistency(h1,h2);
2756  CheckConsistency(this,h1);
2757  } catch(DifferentNumberOfBins&) {
2758  Error("Divide","Cannot divide histograms with different number of bins");
2759  return kFALSE;
2760  } catch(DifferentAxisLimits&) {
2761  Warning("Divide","Dividing histograms with different axis limits");
2762  } catch(DifferentBinLimits&) {
2763  Warning("Divide","Dividing histograms with different bin limits");
2764  } catch(DifferentLabels&) {
2765  Warning("Divide","Dividing histograms with different labels");
2766  }
2767 
2768 
2769  if (!c2) {
2770  Error("Divide","Coefficient of dividing histogram cannot be zero");
2771  return kFALSE;
2772  }
2773 
2774  // Create Sumw2 if h1 or h2 have Sumw2 set
2775  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
2776 
2777  SetMinimum();
2778  SetMaximum();
2779 
2780  // - Loop on bins (including underflows/overflows)
2781  for (Int_t i = 0; i < fNcells; ++i) {
2782  Double_t b1 = h1->RetrieveBinContent(i);
2783  Double_t b2 = h2->RetrieveBinContent(i);
2784  if (b2) UpdateBinContent(i, c1 * b1 / (c2 * b2));
2785  else UpdateBinContent(i, 0);
2786 
2787  if (fSumw2.fN) {
2788  if (b2 == 0) { fSumw2.fArray[i] = 0; continue; }
2789  Double_t b1sq = b1 * b1; Double_t b2sq = b2 * b2;
2790  Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
2791  Double_t e1sq = h1->GetBinErrorSqUnchecked(i);
2792  Double_t e2sq = h2->GetBinErrorSqUnchecked(i);
2793  if (binomial) {
2794  if (b1 != b2) {
2795  // in the case of binomial statistics c1 and c2 must be 1 otherwise it does not make sense
2796  // c1 and c2 are ignored
2797  //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/(c2*b2));//this is the formula in Hbook/Hoper1
2798  //fSumw2.fArray[bin] = TMath::Abs(w*(1-w)/b2); // old formula from G. Flucke
2799  // formula which works also for weighted histogram (see http://root.cern.ch/phpBB2/viewtopic.php?t=3753 )
2800  fSumw2.fArray[i] = TMath::Abs( ( (1. - 2.* b1 / b2) * e1sq + b1sq * e2sq / b2sq ) / b2sq );
2801  } else {
2802  //in case b1=b2 error is zero
2803  //use TGraphAsymmErrors::BayesDivide for getting the asymmetric error not equal to zero
2804  fSumw2.fArray[i] = 0;
2805  }
2806  } else {
2807  fSumw2.fArray[i] = c1sq * c2sq * (e1sq * b2sq + e2sq * b1sq) / (c2sq * c2sq * b2sq * b2sq);
2808  }
2809  }
2810  }
2811  ResetStats();
2812  if (binomial)
2813  // in case of binomial division use denominator for number of entries
2814  SetEntries ( h2->GetEntries() );
2815 
2816  return kTRUE;
2817 }
2818 
2819 ////////////////////////////////////////////////////////////////////////////////
2820 /// Draw this histogram with options.
2821 ///
2822 /// Histograms are drawn via the THistPainter class. Each histogram has
2823 /// a pointer to its own painter (to be usable in a multithreaded program).
2824 /// The same histogram can be drawn with different options in different pads.
2825 /// When an histogram drawn in a pad is deleted, the histogram is
2826 /// automatically removed from the pad or pads where it was drawn.
2827 /// If an histogram is drawn in a pad, then filled again, the new status
2828 /// of the histogram will be automatically shown in the pad next time
2829 /// the pad is updated. One does not need to redraw the histogram.
2830 /// To draw the current version of an histogram in a pad, one can use
2831 /// `h->DrawCopy();`
2832 /// This makes a clone of the histogram. Once the clone is drawn, the original
2833 /// histogram may be modified or deleted without affecting the aspect of the
2834 /// clone.
2835 /// By default, TH1::Draw clears the current pad.
2836 ///
2837 /// One can use TH1::SetMaximum and TH1::SetMinimum to force a particular
2838 /// value for the maximum or the minimum scale on the plot.
2839 ///
2840 /// TH1::UseCurrentStyle can be used to change all histogram graphics
2841 /// attributes to correspond to the current selected style.
2842 /// This function must be called for each histogram.
2843 /// In case one reads and draws many histograms from a file, one can force
2844 /// the histograms to inherit automatically the current graphics style
2845 /// by calling before gROOT->ForceStyle();
2846 ///
2847 /// See the THistPainter class for a description of all the drawing options.
2848 
2849 void TH1::Draw(Option_t *option)
2850 {
2851  TString opt1 = option; opt1.ToLower();
2852  TString opt2 = option;
2853  Int_t index = opt1.Index("same");
2854 
2855  // Check if the string "same" is part of a TCutg name.
2856  if (index>=0) {
2857  Int_t indb = opt1.Index("[");
2858  if (indb>=0) {
2859  Int_t indk = opt1.Index("]");
2860  if (index>indb && index<indk) index = -1;
2861  }
2862  }
2863 
2864  // If there is no pad or an empty pad the "same" option is ignored.
2865  if (gPad) {
2866  if (!gPad->IsEditable()) gROOT->MakeDefCanvas();
2867  if (index>=0) {
2868  if (gPad->GetX1() == 0 && gPad->GetX2() == 1 &&
2869  gPad->GetY1() == 0 && gPad->GetY2() == 1 &&
2870  gPad->GetListOfPrimitives()->GetSize()==0) opt2.Remove(index,4);
2871  } else {
2872  //the following statement is necessary in case one attempts to draw
2873  //a temporary histogram already in the current pad
2874  if (TestBit(kCanDelete)) gPad->GetListOfPrimitives()->Remove(this);
2875  gPad->Clear();
2876  }
2877  gPad->IncrementPaletteColor(1, opt1);
2878  } else {
2879  if (index>=0) opt2.Remove(index,4);
2880  }
2881 
2882  AppendPad(opt2.Data());
2883 }
2884 
2885 ////////////////////////////////////////////////////////////////////////////////
2886 /// Copy this histogram and Draw in the current pad.
2887 ///
2888 /// Once the histogram is drawn into the pad, any further modification
2889 /// using graphics input will be made on the copy of the histogram,
2890 /// and not to the original object.
2891 /// By default a postfix "_copy" is added to the histogram name. Pass an empty postfix in case
2892 /// you want to draw an histogram with the same name
2893 ///
2894 /// See Draw for the list of options
2895 
2896 TH1 *TH1::DrawCopy(Option_t *option, const char * name_postfix) const
2897 {
2898  TString opt = option;
2899  opt.ToLower();
2900  if (gPad && !opt.Contains("same")) gPad->Clear();
2901  TString newName = (name_postfix) ? TString::Format("%s%s",GetName(),name_postfix) : "";
2902  TH1 *newth1 = (TH1 *)Clone(newName);
2903  newth1->SetDirectory(0);
2904  newth1->SetBit(kCanDelete);
2905  newth1->AppendPad(option);
2906  return newth1;
2907 }
2908 
2909 ////////////////////////////////////////////////////////////////////////////////
2910 /// Draw a normalized copy of this histogram.
2911 ///
2912 /// A clone of this histogram is normalized to norm and drawn with option.
2913 /// A pointer to the normalized histogram is returned.
2914 /// The contents of the histogram copy are scaled such that the new
2915 /// sum of weights (excluding under and overflow) is equal to norm.
2916 /// Note that the returned normalized histogram is not added to the list
2917 /// of histograms in the current directory in memory.
2918 /// It is the user's responsibility to delete this histogram.
2919 /// The kCanDelete bit is set for the returned object. If a pad containing
2920 /// this copy is cleared, the histogram will be automatically deleted.
2921 ///
2922 /// See Draw for the list of options
2923 
2924 TH1 *TH1::DrawNormalized(Option_t *option, Double_t norm) const
2925 {
2927  if (sum == 0) {
2928  Error("DrawNormalized","Sum of weights is null. Cannot normalize histogram: %s",GetName());
2929  return 0;
2930  }
2931  Bool_t addStatus = TH1::AddDirectoryStatus();
2933  TH1 *h = (TH1*)Clone();
2934  h->SetBit(kCanDelete);
2935  // in case of drawing with error options - scale correctly the error
2936  TString opt(option); opt.ToUpper();
2937  if (fSumw2.fN == 0) {
2938  h->Sumw2();
2939  // do not use in this case the "Error option " for drawing which is enabled by default since the normalized histogram has now errors
2940  if (opt.IsNull() || opt == "SAME") opt += "HIST";
2941  }
2942  h->Scale(norm/sum);
2943  if (TMath::Abs(fMaximum+1111) > 1e-3) h->SetMaximum(fMaximum*norm/sum);
2944  if (TMath::Abs(fMinimum+1111) > 1e-3) h->SetMinimum(fMinimum*norm/sum);
2945  h->Draw(opt);
2946  TH1::AddDirectory(addStatus);
2947  return h;
2948 }
2949 
2950 ////////////////////////////////////////////////////////////////////////////////
2951 /// Display a panel with all histogram drawing options.
2952 ///
2953 /// See class TDrawPanelHist for example
2954 
2955 void TH1::DrawPanel()
2956 {
2957  if (!fPainter) {Draw(); if (gPad) gPad->Update();}
2958  if (fPainter) fPainter->DrawPanel();
2959 }
2960 
2961 ////////////////////////////////////////////////////////////////////////////////
2962 /// Evaluate function f1 at the center of bins of this histogram.
2963 ///
2964 /// - If option "R" is specified, the function is evaluated only
2965 /// for the bins included in the function range.
2966 /// - If option "A" is specified, the value of the function is added to the
2967 /// existing bin contents
2968 /// - If option "S" is specified, the value of the function is used to
2969 /// generate a value, distributed according to the Poisson
2970 /// distribution, with f1 as the mean.
2971 
2972 void TH1::Eval(TF1 *f1, Option_t *option)
2973 {
2975  Int_t range, stat, add;
2976  if (!f1) return;
2977 
2978  TString opt = option;
2979  opt.ToLower();
2980  if (opt.Contains("a")) add = 1;
2981  else add = 0;
2982  if (opt.Contains("s")) stat = 1;
2983  else stat = 0;
2984  if (opt.Contains("r")) range = 1;
2985  else range = 0;
2986 
2987  // delete buffer if it is there since it will become invalid
2988  if (fBuffer) BufferEmpty(1);
2989 
2990  Int_t nbinsx = fXaxis.GetNbins();
2991  Int_t nbinsy = fYaxis.GetNbins();
2992  Int_t nbinsz = fZaxis.GetNbins();
2993  if (!add) Reset();
2994 
2995  for (Int_t binz = 1; binz <= nbinsz; ++binz) {
2996  x[2] = fZaxis.GetBinCenter(binz);
2997  for (Int_t biny = 1; biny <= nbinsy; ++biny) {
2998  x[1] = fYaxis.GetBinCenter(biny);
2999  for (Int_t binx = 1; binx <= nbinsx; ++binx) {
3000  Int_t bin = GetBin(binx,biny,binz);
3001  x[0] = fXaxis.GetBinCenter(binx);
3002  if (range && !f1->IsInside(x)) continue;
3003  Double_t fu = f1->Eval(x[0], x[1], x[2]);
3004  if (stat) fu = gRandom->PoissonD(fu);
3005  AddBinContent(bin, fu);
3006  if (fSumw2.fN) fSumw2.fArray[bin] += TMath::Abs(fu);
3007  }
3008  }
3009  }
3010 }
3011 
3012 ////////////////////////////////////////////////////////////////////////////////
3013 /// Execute action corresponding to one event.
3014 ///
3015 /// This member function is called when a histogram is clicked with the locator
3016 ///
3017 /// If Left button clicked on the bin top value, then the content of this bin
3018 /// is modified according to the new position of the mouse when it is released.
3019 
3020 void TH1::ExecuteEvent(Int_t event, Int_t px, Int_t py)
3021 {
3022  if (fPainter) fPainter->ExecuteEvent(event, px, py);
3023 }
3024 
3025 ////////////////////////////////////////////////////////////////////////////////
3026 /// This function allows to do discrete Fourier transforms of TH1 and TH2.
3027 /// Available transform types and flags are described below.
3028 ///
3029 /// To extract more information about the transform, use the function
3030 /// TVirtualFFT::GetCurrentTransform() to get a pointer to the current
3031 /// transform object.
3032 ///
3033 /// \param[out] h_output histogram for the output. If a null pointer is passed, a new histogram is created
3034 /// and returned, otherwise, the provided histogram is used and should be big enough
3035 /// \param[in] option option parameters consists of 3 parts:
3036 /// - option on what to return
3037 /// - "RE" - returns a histogram of the real part of the output
3038 /// - "IM" - returns a histogram of the imaginary part of the output
3039 /// - "MAG"- returns a histogram of the magnitude of the output
3040 /// - "PH" - returns a histogram of the phase of the output
3041 /// - option of transform type
3042 /// - "R2C" - real to complex transforms - default
3043 /// - "R2HC" - real to halfcomplex (special format of storing output data,
3044 /// results the same as for R2C)
3045 /// - "DHT" - discrete Hartley transform
3046 /// real to real transforms (sine and cosine):
3047 /// - "R2R_0", "R2R_1", "R2R_2", "R2R_3" - discrete cosine transforms of types I-IV
3048 /// - "R2R_4", "R2R_5", "R2R_6", "R2R_7" - discrete sine transforms of types I-IV
3049 /// To specify the type of each dimension of a 2-dimensional real to real
3050 /// transform, use options of form "R2R_XX", for example, "R2R_02" for a transform,
3051 /// which is of type "R2R_0" in 1st dimension and "R2R_2" in the 2nd.
3052 /// - option of transform flag
3053 /// - "ES" (from "estimate") - no time in preparing the transform, but probably sub-optimal
3054 /// performance
3055 /// - "M" (from "measure") - some time spend in finding the optimal way to do the transform
3056 /// - "P" (from "patient") - more time spend in finding the optimal way to do the transform
3057 /// - "EX" (from "exhaustive") - the most optimal way is found
3058 /// This option should be chosen depending on how many transforms of the same size and
3059 /// type are going to be done. Planning is only done once, for the first transform of this
3060 /// size and type. Default is "ES".
3061 ///
3062 /// Examples of valid options: "Mag R2C M" "Re R2R_11" "Im R2C ES" "PH R2HC EX"
3063 
3064 TH1* TH1::FFT(TH1* h_output, Option_t *option)
3065 {
3067  Int_t ndim[3];
3068  ndim[0] = this->GetNbinsX();
3069  ndim[1] = this->GetNbinsY();
3070  ndim[2] = this->GetNbinsZ();
3071 
3072  TVirtualFFT *fft;
3073  TString opt = option;
3074  opt.ToUpper();
3075  if (!opt.Contains("2R")){
3076  if (!opt.Contains("2C") && !opt.Contains("2HC") && !opt.Contains("DHT")) {
3077  //no type specified, "R2C" by default
3078  opt.Append("R2C");
3079  }
3080  fft = TVirtualFFT::FFT(this->GetDimension(), ndim, opt.Data());
3081  }
3082  else {
3083  //find the kind of transform
3084  Int_t ind = opt.Index("R2R", 3);
3085  Int_t *kind = new Int_t[2];
3086  char t;
3087  t = opt[ind+4];
3088  kind[0] = atoi(&t);
3089  if (h_output->GetDimension()>1) {
3090  t = opt[ind+5];
3091  kind[1] = atoi(&t);
3092  }
3093  fft = TVirtualFFT::SineCosine(this->GetDimension(), ndim, kind, option);
3094  delete [] kind;
3095  }
3096 
3097  if (!fft) return 0;
3098  Int_t in=0;
3099  for (Int_t binx = 1; binx<=ndim[0]; binx++) {
3100  for (Int_t biny=1; biny<=ndim[1]; biny++) {
3101  for (Int_t binz=1; binz<=ndim[2]; binz++) {
3102  fft->SetPoint(in, this->GetBinContent(binx, biny, binz));
3103  in++;
3104  }
3105  }
3106  }
3107  fft->Transform();
3108  h_output = TransformHisto(fft, h_output, option);
3109  return h_output;
3110 }
3111 
3112 ////////////////////////////////////////////////////////////////////////////////
3113 /// Increment bin with abscissa X by 1.
3114 ///
3115 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3116 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3117 ///
3118 /// If the storage of the sum of squares of weights has been triggered,
3119 /// via the function Sumw2, then the sum of the squares of weights is incremented
3120 /// by 1 in the bin corresponding to x.
3121 ///
3122 /// The function returns the corresponding bin number which has its content incremented by 1
3123 
3125 {
3126  if (fBuffer) return BufferFill(x,1);
3127 
3128  Int_t bin;
3129  fEntries++;
3130  bin =fXaxis.FindBin(x);
3131  if (bin <0) return -1;
3132  AddBinContent(bin);
3133  if (fSumw2.fN) ++fSumw2.fArray[bin];
3134  if (bin == 0 || bin > fXaxis.GetNbins()) {
3135  if (!fgStatOverflows) return -1;
3136  }
3137  ++fTsumw;
3138  ++fTsumw2;
3139  fTsumwx += x;
3140  fTsumwx2 += x*x;
3141  return bin;
3142 }
3143 
3144 ////////////////////////////////////////////////////////////////////////////////
3145 /// Increment bin with abscissa X with a weight w.
3146 ///
3147 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3148 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3149 ///
3150 /// If the weight is not equal to 1, the storage of the sum of squares of
3151 /// weights is automatically triggered and the sum of the squares of weights is incremented
3152 /// by \f$ w^2 \f$ in the bin corresponding to x.
3153 ///
3154 /// The function returns the corresponding bin number which has its content incremented by w
3155 
3157 {
3159  if (fBuffer) return BufferFill(x,w);
3160 
3161  Int_t bin;
3162  fEntries++;
3163  bin =fXaxis.FindBin(x);
3164  if (bin <0) return -1;
3165  if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW) ) Sumw2(); // must be called before AddBinContent
3166  if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3167  AddBinContent(bin, w);
3168  if (bin == 0 || bin > fXaxis.GetNbins()) {
3169  if (!fgStatOverflows) return -1;
3170  }
3171  Double_t z= w;
3172  fTsumw += z;
3173  fTsumw2 += z*z;
3174  fTsumwx += z*x;
3175  fTsumwx2 += z*x*x;
3176  return bin;
3177 }
3178 
3179 ////////////////////////////////////////////////////////////////////////////////
3180 /// Increment bin with namex with a weight w
3181 ///
3182 /// if x is less than the low-edge of the first bin, the Underflow bin is incremented
3183 /// if x is greater than the upper edge of last bin, the Overflow bin is incremented
3184 ///
3185 /// If the weight is not equal to 1, the storage of the sum of squares of
3186 /// weights is automatically triggered and the sum of the squares of weights is incremented
3187 /// by \f$ w^2 \f$ in the bin corresponding to x.
3188 ///
3189 /// The function returns the corresponding bin number which has its content
3190 /// incremented by w.
3191 
3192 Int_t TH1::Fill(const char *namex, Double_t w)
3193 {
3194  Int_t bin;
3195  fEntries++;
3196  bin =fXaxis.FindBin(namex);
3197  if (bin <0) return -1;
3198  if (!fSumw2.fN && w != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3199  if (fSumw2.fN) fSumw2.fArray[bin] += w*w;
3200  AddBinContent(bin, w);
3201  if (bin == 0 || bin > fXaxis.GetNbins()) return -1;
3202  Double_t z= w;
3203  fTsumw += z;
3204  fTsumw2 += z*z;
3205  // this make sense if the histogram is not expanding (no axis can be extended)
3206  if (!CanExtendAllAxes()) {
3207  Double_t x = fXaxis.GetBinCenter(bin);
3208  fTsumwx += z*x;
3209  fTsumwx2 += z*x*x;
3210  }
3211  return bin;
3212 }
3213 
3214 ////////////////////////////////////////////////////////////////////////////////
3215 /// Fill this histogram with an array x and weights w.
3216 ///
3217 /// \param[in] ntimes number of entries in arrays x and w (array size must be ntimes*stride)
3218 /// \param[in] x array of values to be histogrammed
3219 /// \param[in] w array of weighs
3220 /// \param[in] stride step size through arrays x and w
3221 ///
3222 /// If the weight is not equal to 1, the storage of the sum of squares of
3223 /// weights is automatically triggered and the sum of the squares of weights is incremented
3224 /// by \f$ w^2 \f$ in the bin corresponding to x.
3225 /// if w is NULL each entry is assumed a weight=1
3226 
3227 void TH1::FillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3228 {
3229  //If a buffer is activated, fill buffer
3230  if (fBuffer) {
3231  ntimes *= stride;
3232  Int_t i = 0;
3233  for (i=0;i<ntimes;i+=stride) {
3234  if (!fBuffer) break; // buffer can be deleted in BufferFill when is empty
3235  if (w) BufferFill(x[i],w[i]);
3236  else BufferFill(x[i], 1.);
3237  }
3238  // fill the remaining entries if the buffer has been deleted
3239  if (i < ntimes && fBuffer==0)
3240  DoFillN((ntimes-i)/stride,&x[i],&w[i],stride);
3241  return;
3242  }
3243  // call internal method
3244  DoFillN(ntimes, x, w, stride);
3245 }
3246 
3247 ////////////////////////////////////////////////////////////////////////////////
3248 /// Internal method to fill histogram content from a vector
3249 /// called directly by TH1::BufferEmpty
3250 
3251 void TH1::DoFillN(Int_t ntimes, const Double_t *x, const Double_t *w, Int_t stride)
3252 {
3253  Int_t bin,i;
3254 
3255  fEntries += ntimes;
3256  Double_t ww = 1;
3257  Int_t nbins = fXaxis.GetNbins();
3258  ntimes *= stride;
3259  for (i=0;i<ntimes;i+=stride) {
3260  bin =fXaxis.FindBin(x[i]);
3261  if (bin <0) continue;
3262  if (w) ww = w[i];
3263  if (!fSumw2.fN && ww != 1.0 && !TestBit(TH1::kIsNotW)) Sumw2();
3264  if (fSumw2.fN) fSumw2.fArray[bin] += ww*ww;
3265  AddBinContent(bin, ww);
3266  if (bin == 0 || bin > nbins) {
3267  if (!fgStatOverflows) continue;
3268  }
3269  Double_t z= ww;
3270  fTsumw += z;
3271  fTsumw2 += z*z;
3272  fTsumwx += z*x[i];
3273  fTsumwx2 += z*x[i]*x[i];
3274  }
3275 }
3276 
3277 ////////////////////////////////////////////////////////////////////////////////
3278 /// Fill histogram following distribution in function fname.
3279 ///
3280 /// The distribution contained in the function fname (TF1) is integrated
3281 /// over the channel contents for the bin range of this histogram.
3282 /// It is normalized to 1.
3283 ///
3284 /// Getting one random number implies:
3285 /// - Generating a random number between 0 and 1 (say r1)
3286 /// - Look in which bin in the normalized integral r1 corresponds to
3287 /// - Fill histogram channel
3288 /// ntimes random numbers are generated
3289 ///
3290 /// One can also call TF1::GetRandom to get a random variate from a function.
3291 
3292 void TH1::FillRandom(const char *fname, Int_t ntimes)
3293 {
3294  Int_t bin, binx, ibin, loop;
3295  Double_t r1, x;
3296  // - Search for fname in the list of ROOT defined functions
3297  TF1 *f1 = (TF1*)gROOT->GetFunction(fname);
3298  if (!f1) { Error("FillRandom", "Unknown function: %s",fname); return; }
3299 
3300  // - Allocate temporary space to store the integral and compute integral
3301 
3302  TAxis * xAxis = &fXaxis;
3303 
3304  // in case axis of histogram is not defined use the function axis
3305  if (fXaxis.GetXmax() <= fXaxis.GetXmin()) {
3306  Double_t xmin,xmax;
3307  f1->GetRange(xmin,xmax);
3308  Info("FillRandom","Using function axis and range [%g,%g]",xmin, xmax);
3309  xAxis = f1->GetHistogram()->GetXaxis();
3310  }
3311 
3312  Int_t first = xAxis->GetFirst();
3313  Int_t last = xAxis->GetLast();
3314  Int_t nbinsx = last-first+1;
3315 
3316  Double_t *integral = new Double_t[nbinsx+1];
3317  integral[0] = 0;
3318  for (binx=1;binx<=nbinsx;binx++) {
3319  Double_t fint = f1->Integral(xAxis->GetBinLowEdge(binx+first-1),xAxis->GetBinUpEdge(binx+first-1));
3320  integral[binx] = integral[binx-1] + fint;
3321  }
3322 
3323  // - Normalize integral to 1
3324  if (integral[nbinsx] == 0 ) {
3325  delete [] integral;
3326  Error("FillRandom", "Integral = zero"); return;
3327  }
3328  for (bin=1;bin<=nbinsx;bin++) integral[bin] /= integral[nbinsx];
3329 
3330  // --------------Start main loop ntimes
3331  for (loop=0;loop<ntimes;loop++) {
3332  r1 = gRandom->Rndm();
3333  ibin = TMath::BinarySearch(nbinsx,&integral[0],r1);
3334  //binx = 1 + ibin;
3335  //x = xAxis->GetBinCenter(binx); //this is not OK when SetBuffer is used
3336  x = xAxis->GetBinLowEdge(ibin+first)
3337  +xAxis->GetBinWidth(ibin+first)*(r1-integral[ibin])/(integral[ibin+1] - integral[ibin]);
3338  Fill(x);
3339  }
3340  delete [] integral;
3341 }
3342 
3343 ////////////////////////////////////////////////////////////////////////////////
3344 /// Fill histogram following distribution in histogram h.
3345 ///
3346 /// The distribution contained in the histogram h (TH1) is integrated
3347 /// over the channel contents for the bin range of this histogram.
3348 /// It is normalized to 1.
3349 ///
3350 /// Getting one random number implies:
3351 /// - Generating a random number between 0 and 1 (say r1)
3352 /// - Look in which bin in the normalized integral r1 corresponds to
3353 /// - Fill histogram channel ntimes random numbers are generated
3354 ///
3355 /// SPECIAL CASE when the target histogram has the same binning as the source.
3356 /// in this case we simply use a poisson distribution where
3357 /// the mean value per bin = bincontent/integral.
3358 
3359 void TH1::FillRandom(TH1 *h, Int_t ntimes)
3360 {
3361  if (!h) { Error("FillRandom", "Null histogram"); return; }
3362  if (fDimension != h->GetDimension()) {
3363  Error("FillRandom", "Histograms with different dimensions"); return;
3364  }
3365 
3366  //in case the target histogram has the same binning and ntimes much greater
3367  //than the number of bins we can use a fast method
3368  Int_t first = fXaxis.GetFirst();
3369  Int_t last = fXaxis.GetLast();
3370  Int_t nbins = last-first+1;
3371  if (ntimes > 10*nbins) {
3372  try {
3373  CheckConsistency(this,h);
3374  Double_t sumw = h->Integral(first,last);
3375  if (sumw == 0) return;
3376  Double_t sumgen = 0;
3377  for (Int_t bin=first;bin<=last;bin++) {
3378  Double_t mean = h->RetrieveBinContent(bin)*ntimes/sumw;
3379  Double_t cont = (Double_t)gRandom->Poisson(mean);
3380  sumgen += cont;
3381  AddBinContent(bin,cont);
3382  if (fSumw2.fN) fSumw2.fArray[bin] += cont;
3383  }
3384 
3385  // fix for the fluctuations in the total number n
3386  // since we use Poisson instead of multinomial
3387  // add a correction to have ntimes as generated entries
3388  Int_t i;
3389  if (sumgen < ntimes) {
3390  // add missing entries
3391  for (i = Int_t(sumgen+0.5); i < ntimes; ++i)
3392  {
3393  Double_t x = h->GetRandom();
3394  Fill(x);
3395  }
3396  }
3397  else if (sumgen > ntimes) {
3398  // remove extra entries
3399  i = Int_t(sumgen+0.5);
3400  while( i > ntimes) {
3401  Double_t x = h->GetRandom();
3402  Int_t ibin = fXaxis.FindBin(x);
3403  Double_t y = RetrieveBinContent(ibin);
3404  // skip in case bin is empty
3405  if (y > 0) {
3406  SetBinContent(ibin, y-1.);
3407  i--;
3408  }
3409  }
3410  }
3411 
3412  ResetStats();
3413  return;
3414  }
3415  catch(std::exception&) {} // do nothing
3416  }
3417  // case of different axis and not too large ntimes
3418 
3419  if (h->ComputeIntegral() ==0) return;
3420  Int_t loop;
3421  Double_t x;
3422  for (loop=0;loop<ntimes;loop++) {
3423  x = h->GetRandom();
3424  Fill(x);
3425  }
3426 }
3427 
3428 ////////////////////////////////////////////////////////////////////////////////
3429 /// Return Global bin number corresponding to x,y,z
3430 ///
3431 /// 2-D and 3-D histograms are represented with a one dimensional
3432 /// structure. This has the advantage that all existing functions, such as
3433 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3434 /// This function tries to extend the axis if the given point belongs to an
3435 /// under-/overflow bin AND if CanExtendAllAxes() is true.
3436 ///
3437 /// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3438 
3440 {
3441  if (GetDimension() < 2) {
3442  return fXaxis.FindBin(x);
3443  }
3444  if (GetDimension() < 3) {
3445  Int_t nx = fXaxis.GetNbins()+2;
3446  Int_t binx = fXaxis.FindBin(x);
3447  Int_t biny = fYaxis.FindBin(y);
3448  return binx + nx*biny;
3449  }
3450  if (GetDimension() < 4) {
3451  Int_t nx = fXaxis.GetNbins()+2;
3452  Int_t ny = fYaxis.GetNbins()+2;
3453  Int_t binx = fXaxis.FindBin(x);
3454  Int_t biny = fYaxis.FindBin(y);
3455  Int_t binz = fZaxis.FindBin(z);
3456  return binx + nx*(biny +ny*binz);
3457  }
3458  return -1;
3459 }
3460 
3461 ////////////////////////////////////////////////////////////////////////////////
3462 /// Return Global bin number corresponding to x,y,z.
3463 ///
3464 /// 2-D and 3-D histograms are represented with a one dimensional
3465 /// structure. This has the advantage that all existing functions, such as
3466 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
3467 /// This function DOES NOT try to extend the axis if the given point belongs
3468 /// to an under-/overflow bin.
3469 ///
3470 /// See also TH1::GetBin, TAxis::FindBin and TAxis::FindFixBin
3471 
3473 {
3474  if (GetDimension() < 2) {
3475  return fXaxis.FindFixBin(x);
3476  }
3477  if (GetDimension() < 3) {
3478  Int_t nx = fXaxis.GetNbins()+2;
3479  Int_t binx = fXaxis.FindFixBin(x);
3480  Int_t biny = fYaxis.FindFixBin(y);
3481  return binx + nx*biny;
3482  }
3483  if (GetDimension() < 4) {
3484  Int_t nx = fXaxis.GetNbins()+2;
3485  Int_t ny = fYaxis.GetNbins()+2;
3486  Int_t binx = fXaxis.FindFixBin(x);
3487  Int_t biny = fYaxis.FindFixBin(y);
3488  Int_t binz = fZaxis.FindFixBin(z);
3489  return binx + nx*(biny +ny*binz);
3490  }
3491  return -1;
3492 }
3493 
3494 ////////////////////////////////////////////////////////////////////////////////
3495 /// Find first bin with content > threshold for axis (1=x, 2=y, 3=z)
3496 /// if no bins with content > threshold is found the function returns -1.
3497 
3498 Int_t TH1::FindFirstBinAbove(Double_t threshold, Int_t axis) const
3499 {
3500  if (fBuffer) ((TH1*)this)->BufferEmpty();
3501 
3502  if (axis != 1) {
3503  Warning("FindFirstBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3504  axis = 1;
3505  }
3506  Int_t nbins = fXaxis.GetNbins();
3507  for (Int_t bin=1;bin<=nbins;bin++) {
3508  if (RetrieveBinContent(bin) > threshold) return bin;
3509  }
3510  return -1;
3511 }
3512 
3513 ////////////////////////////////////////////////////////////////////////////////
3514 /// Find last bin with content > threshold for axis (1=x, 2=y, 3=z)
3515 /// if no bins with content > threshold is found the function returns -1.
3516 
3517 Int_t TH1::FindLastBinAbove(Double_t threshold, Int_t axis) const
3518 {
3519  if (fBuffer) ((TH1*)this)->BufferEmpty();
3520 
3521  if (axis != 1) {
3522  Warning("FindLastBinAbove","Invalid axis number : %d, axis x assumed\n",axis);
3523  axis = 1;
3524  }
3525  Int_t nbins = fXaxis.GetNbins();
3526  for (Int_t bin=nbins;bin>=1;bin--) {
3527  if (RetrieveBinContent(bin) > threshold) return bin;
3528  }
3529  return -1;
3530 }
3531 
3532 ////////////////////////////////////////////////////////////////////////////////
3533 /// Search object named name in the list of functions.
3534 
3535 TObject *TH1::FindObject(const char *name) const
3536 {
3537  if (fFunctions) return fFunctions->FindObject(name);
3538  return 0;
3539 }
3540 
3541 ////////////////////////////////////////////////////////////////////////////////
3542 /// Search object obj in the list of functions.
3543 
3544 TObject *TH1::FindObject(const TObject *obj) const
3545 {
3546  if (fFunctions) return fFunctions->FindObject(obj);
3547  return 0;
3548 }
3549 
3550 ////////////////////////////////////////////////////////////////////////////////
3551 /// Fit histogram with function fname.
3552 ///
3553 /// fname is the name of an already predefined function created by TF1 or TF2
3554 /// Predefined functions such as gaus, expo and poln are automatically
3555 /// created by ROOT.
3556 /// fname can also be a formula, accepted by the linear fitter (linear parts divided
3557 /// by "++" sign), for example "x++sin(x)" for fitting "[0]*x+[1]*sin(x)"
3558 ///
3559 /// This function finds a pointer to the TF1 object with name fname
3560 /// and calls TH1::Fit(TF1 *f1,...)
3561 
3562 TFitResultPtr TH1::Fit(const char *fname ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
3563 {
3564  char *linear;
3565  linear= (char*)strstr(fname, "++");
3566  TF1 *f1=0;
3567  TF2 *f2=0;
3568  TF3 *f3=0;
3569  Int_t ndim=GetDimension();
3570  if (linear){
3571  if (ndim<2){
3572  f1=new TF1(fname, fname, xxmin, xxmax);
3573  return Fit(f1,option,goption,xxmin,xxmax);
3574  }
3575  else if (ndim<3){
3576  f2=new TF2(fname, fname);
3577  return Fit(f2,option,goption,xxmin,xxmax);
3578  }
3579  else{
3580  f3=new TF3(fname, fname);
3581  return Fit(f3,option,goption,xxmin,xxmax);
3582  }
3583  }
3584 
3585  else{
3586  f1 = (TF1*)gROOT->GetFunction(fname);
3587  if (!f1) { Printf("Unknown function: %s",fname); return -1; }
3588  return Fit(f1,option,goption,xxmin,xxmax);
3589  }
3590 }
3591 
3592 ////////////////////////////////////////////////////////////////////////////////
3593 /// Fit histogram with function f1.
3594 ///
3595 /// \param[in] option fit options is given in parameter option.
3596 /// - "W" Set all weights to 1 for non empty bins; ignore error bars
3597 /// - "WW" Set all weights to 1 including empty bins; ignore error bars
3598 /// - "I" Use integral of function in bin, normalized by the bin volume,
3599 /// instead of value at bin center
3600 /// - "L" Use Loglikelihood method (default is chisquare method)
3601 /// - "WL" Use Loglikelihood method and bin contents are not integer,
3602 /// i.e. histogram is weighted (must have Sumw2() set)
3603 /// - "P" Use Pearson chi2 (using expected errors instead of observed errors)
3604 /// - "U" Use a User specified fitting algorithm (via SetFCN)
3605 /// - "Q" Quiet mode (minimum printing)
3606 /// - "V" Verbose mode (default is between Q and V)
3607 /// - "E" Perform better Errors estimation using Minos technique
3608 /// - "B" User defined parameter settings are used for predefined functions
3609 /// like "gaus", "expo", "poln", "landau".
3610 /// Use this option when you want to fix one or more parameters for these functions.
3611 /// - "M" More. Improve fit results.
3612 /// It uses the IMPROVE command of TMinuit (see TMinuit::mnimpr).
3613 /// This algorithm attempts to improve the found local minimum by searching for a
3614 /// better one.
3615 /// - "R" Use the Range specified in the function range
3616 /// - "N" Do not store the graphics function, do not draw
3617 /// - "0" Do not plot the result of the fit. By default the fitted function
3618 /// is drawn unless the option"N" above is specified.
3619 /// - "+" Add this new fitted function to the list of fitted functions
3620 /// (by default, any previous function is deleted)
3621 /// - "C" In case of linear fitting, don't calculate the chisquare
3622 /// (saves time)
3623 /// - "F" If fitting a polN, switch to minuit fitter
3624 /// - "S" The result of the fit is returned in the TFitResultPtr
3625 /// (see below Access to the Fit Result)
3626 /// \param[in] goption specify a list of graphics options. See TH1::Draw for a complete list of these options.
3627 /// \param[in] xxmin range
3628 /// \param[in] xxmax range
3629 ///
3630 /// In order to use the Range option, one must first create a function
3631 /// with the expression to be fitted. For example, if your histogram
3632 /// has a defined range between -4 and 4 and you want to fit a gaussian
3633 /// only in the interval 1 to 3, you can do:
3634 ///
3635 /// ~~~ {.cpp}
3636 /// TF1 *f1 = new TF1("f1", "gaus", 1, 3);
3637 /// histo->Fit("f1", "R");
3638 /// ~~~
3639 ///
3640 /// ## Setting initial conditions
3641 /// Parameters must be initialized before invoking the Fit function.
3642 /// The setting of the parameter initial values is automatic for the
3643 /// predefined functions : poln, expo, gaus, landau. One can however disable
3644 /// this automatic computation by specifying the option "B".
3645 /// Note that if a predefined function is defined with an argument,
3646 /// eg, gaus(0), expo(1), you must specify the initial values for
3647 /// the parameters.
3648 /// You can specify boundary limits for some or all parameters via
3649 ///
3650 /// ~~~ {.cpp}
3651 /// f1->SetParLimits(p_number, parmin, parmax);
3652 /// ~~~
3653 ///
3654 /// if parmin>=parmax, the parameter is fixed
3655 /// Note that you are not forced to fix the limits for all parameters.
3656 /// For example, if you fit a function with 6 parameters, you can do:
3657 ///
3658 /// ~~~ {.cpp}
3659 /// func->SetParameters(0, 3.1, 1.e-6, -8, 0, 100);
3660 /// func->SetParLimits(3, -10, -4);
3661 /// func->FixParameter(4, 0);
3662 /// func->SetParLimits(5, 1, 1);
3663 /// ~~~
3664 ///
3665 /// With this setup, parameters 0->2 can vary freely
3666 /// Parameter 3 has boundaries [-10,-4] with initial value -8
3667 /// Parameter 4 is fixed to 0
3668 /// Parameter 5 is fixed to 100.
3669 /// When the lower limit and upper limit are equal, the parameter is fixed.
3670 /// However to fix a parameter to 0, one must call the FixParameter function.
3671 ///
3672 /// Note that option "I" gives better results but is slower.
3673 ///
3674 /// #### Changing the fitting objective function
3675 ///
3676 /// By default a chi square function is used for fitting. When option "L" (or "LL") is used
3677 /// a Poisson likelihood function (see note below) is used.
3678 /// The functions are defined in the header Fit/Chi2Func.h or Fit/PoissonLikelihoodFCN and they
3679 /// are implemented using the routines FitUtil::EvaluateChi2 or FitUtil::EvaluatePoissonLogL in
3680 /// the file math/mathcore/src/FitUtil.cxx.
3681 /// To specify a User defined fitting function, specify option "U" and
3682 /// call the following functions:
3683 ///
3684 /// ~~~ {.cpp}
3685 /// TVirtualFitter::Fitter(myhist)->SetFCN(MyFittingFunction)
3686 /// ~~~
3687 ///
3688 /// where MyFittingFunction is of type:
3689 ///
3690 /// ~~~ {.cpp}
3691 /// extern void MyFittingFunction(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag);
3692 /// ~~~
3693 ///
3694 /// #### Chi2 Fits
3695 ///
3696 /// By default a chi2 (least-square) fit is performed on the histogram. The so-called modified least-square method
3697 /// is used where the residual for each bin is computed using as error the observed value (the bin error)
3698 ///
3699 /// \f[
3700 /// Chi2 = \sum{ \left(y(i) - \frac{f(x(i) | p )}{e(i)} \right)^2 }
3701 /// \f]
3702 ///
3703 /// 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
3704 /// an un-weighted histogram. Bins with zero errors are excluded from the fit. See also later the note on the treatment of empty bins.
3705 /// When using option "I" the residual is computed not using the function value at the bin center, f (x(i) | p), but the integral
3706 /// of the function in the bin, Integral{ f(x|p)dx } divided by the bin volume
3707 ///
3708 /// #### Likelihood Fits
3709 ///
3710 /// When using option "L" a likelihood fit is used instead of the default chi2 square fit.
3711 /// The likelihood is built assuming a Poisson probability density function for each bin.
3712 /// The negative log-likelihood to be minimized is
3713 ///
3714 /// \f[
3715 /// NLL = \sum{ log Poisson ( y(i) | f(x(i) | p ) ) }
3716 /// \f]
3717 ///
3718 /// The exact likelihood used is the Poisson likelihood described in this paper:
3719 /// S. Baker and R. D. Cousins, “Clarification of the use of chi-square and likelihood functions in fits to histograms,”
3720 /// Nucl. Instrum. Meth. 221 (1984) 437.
3721 ///
3722 /// This method can then be used only when the bin content represents counts (i.e. errors are sqrt(N) ).
3723 /// The likelihood method has the advantage of treating correctly bins with low statistics. In case of high
3724 /// statistics/bin the distribution of the bin content becomes a normal distribution and the likelihood and chi2 fit
3725 /// give the same result.
3726 ///
3727 /// The likelihood method, although a bit slower, it is therefore the recommended method in case of low
3728 /// bin statistics, where the chi2 method may give incorrect results, in particular when there are
3729 /// several empty bins (see also below).
3730 /// In case of a weighted histogram, it is possible to perform a likelihood fit by using the
3731 /// option "WL". Note a weighted histogram is an histogram which has been filled with weights and it
3732 /// contains the sum of the weight square ( TH1::Sumw2() has been called). The bin error for a weighted
3733 /// histogram is the square root of the sum of the weight square.
3734 ///
3735 /// #### Treatment of Empty Bins
3736 ///
3737 /// Empty bins, which have the content equal to zero AND error equal to zero,
3738 /// are excluded by default from the chisquare fit, but they are considered in the likelihood fit.
3739 /// since they affect the likelihood if the function value in these bins is not negligible.
3740 /// When using option "WW" these bins will be considered in the chi2 fit with an error of 1.
3741 /// Note that if the histogram is having bins with zero content and non zero-errors they are considered as
3742 /// any other bins in the fit. Instead bins with zero error and non-zero content are excluded in the chi2 fit.
3743 /// A likelihood fit should also not be performed on such an histogram, since we are assuming a wrong pdf for each bin.
3744 /// In general, one should not fit an histogram with non-empty bins and zero errors, apart if all the bins have zero errors.
3745 /// In this case one could use the option "w", which gives a weight=1 for each bin (unweighted least-square fit).
3746 ///
3747 /// #### Fitting a histogram of dimension N with a function of dimension N-1
3748 ///
3749 /// It is possible to fit a TH2 with a TF1 or a TH3 with a TF2.
3750 /// In this case the option "Integral" is not allowed and each cell has
3751 /// equal weight.
3752 ///
3753 /// #### Associated functions
3754 ///
3755 /// One or more object (typically a TF1*) can be added to the list
3756 /// of functions (fFunctions) associated to each histogram.
3757 /// When TH1::Fit is invoked, the fitted function is added to this list.
3758 /// Given an histogram h, one can retrieve an associated function
3759 /// with:
3760 ///
3761 /// ~~~ {.cpp}
3762 /// TF1 *myfunc = h->GetFunction("myfunc");
3763 /// ~~~
3764 ///
3765 /// #### Access to the fit result
3766 ///
3767 /// The function returns a TFitResultPtr which can hold a pointer to a TFitResult object.
3768 /// By default the TFitResultPtr contains only the status of the fit which is return by an
3769 /// automatic conversion of the TFitResultPtr to an integer. One can write in this case directly:
3770 ///
3771 /// ~~~ {.cpp}
3772 /// Int_t fitStatus = h->Fit(myFunc)
3773 /// ~~~
3774 ///
3775 /// If the option "S" is instead used, TFitResultPtr contains the TFitResult and behaves as a smart
3776 /// pointer to it. For example one can do:
3777 ///
3778 /// ~~~ {.cpp}
3779 /// TFitResultPtr r = h->Fit(myFunc,"S");
3780 /// TMatrixDSym cov = r->GetCovarianceMatrix(); // to access the covariance matrix
3781 /// Double_t chi2 = r->Chi2(); // to retrieve the fit chi2
3782 /// Double_t par0 = r->Parameter(0); // retrieve the value for the parameter 0
3783 /// Double_t err0 = r->ParError(0); // retrieve the error for the parameter 0
3784 /// r->Print("V"); // print full information of fit including covariance matrix
3785 /// r->Write(); // store the result in a file
3786 /// ~~~
3787 ///
3788 /// The fit parameters, error and chi2 (but not covariance matrix) can be retrieved also
3789 /// from the fitted function.
3790 /// If the histogram is made persistent, the list of
3791 /// associated functions is also persistent. Given a pointer (see above)
3792 /// to an associated function myfunc, one can retrieve the function/fit
3793 /// parameters with calls such as:
3794 ///
3795 /// ~~~ {.cpp}
3796 /// Double_t chi2 = myfunc->GetChisquare();
3797 /// Double_t par0 = myfunc->GetParameter(0); //value of 1st parameter
3798 /// Double_t err0 = myfunc->GetParError(0); //error on first parameter
3799 /// ~~~
3800 ///
3801 /// #### Access to the fit status
3802 ///
3803 /// The status of the fit can be obtained converting the TFitResultPtr to an integer
3804 /// independently if the fit option "S" is used or not:
3805 ///
3806 /// ~~~ {.cpp}
3807 /// TFitResultPtr r = h->Fit(myFunc,opt);
3808 /// Int_t fitStatus = r;
3809 /// ~~~
3810 ///
3811 /// The fitStatus is 0 if the fit is OK (i.e no error occurred).
3812 /// The value of the fit status code is negative in case of an error not connected with the
3813 /// minimization procedure, for example when a wrong function is used.
3814 /// Otherwise the return value is the one returned from the minimization procedure.
3815 /// When TMinuit (default case) or Minuit2 are used as minimizer the status returned is :
3816 /// `fitStatus = migradResult + 10*minosResult + 100*hesseResult + 1000*improveResult`.
3817 /// TMinuit will return 0 (for migrad, minos, hesse or improve) in case of success and 4 in
3818 /// case of error (see the documentation of TMinuit::mnexcm). So for example, for an error
3819 /// only in Minos but not in Migrad a fitStatus of 40 will be returned.
3820 /// Minuit2 will return also 0 in case of success and different values in migrad minos or
3821 /// hesse depending on the error. See in this case the documentation of
3822 /// Minuit2Minimizer::Minimize for the migradResult, Minuit2Minimizer::GetMinosError for the
3823 /// minosResult and Minuit2Minimizer::Hesse for the hesseResult.
3824 /// If other minimizers are used see their specific documentation for the status code returned.
3825 /// For example in the case of Fumili, for the status returned see TFumili::Minimize.
3826 ///
3827 /// #### Excluding points
3828 ///
3829 /// Use TF1::RejectPoint inside your fitting function to exclude points
3830 /// within a certain range from the fit. Example:
3831 ///
3832 /// ~~~ {.cpp}
3833 /// Double_t fline(Double_t *x, Double_t *par)
3834 /// {
3835 /// if (x[0] > 2.5 && x[0] < 3.5) {
3836 /// TF1::RejectPoint();
3837 /// return 0;
3838 /// }
3839 /// return par[0] + par[1]*x[0];
3840 /// }
3841 ///
3842 /// void exclude() {
3843 /// TF1 *f1 = new TF1("f1", "[0] +[1]*x +gaus(2)", 0, 5);
3844 /// f1->SetParameters(6, -1,5, 3, 0.2);
3845 /// TH1F *h = new TH1F("h", "background + signal", 100, 0, 5);
3846 /// h->FillRandom("f1", 2000);
3847 /// TF1 *fline = new TF1("fline", fline, 0, 5, 2);
3848 /// fline->SetParameters(2, -1);
3849 /// h->Fit("fline", "l");
3850 /// }
3851 /// ~~~
3852 ///
3853 /// #### Warning when using the option "0"
3854 ///
3855 /// When selecting the option "0", the fitted function is added to
3856 /// the list of functions of the histogram, but it is not drawn.
3857 /// You can undo what you disabled in the following way:
3858 ///
3859 /// ~~~ {.cpp}
3860 /// h.Fit("myFunction", "0"); // fit, store function but do not draw
3861 /// h.Draw(); function is not drawn
3862 /// const Int_t kNotDraw = 1<<9;
3863 /// h.GetFunction("myFunction")->ResetBit(kNotDraw);
3864 /// h.Draw(); // function is visible again
3865 /// ~~~
3866 ///
3867 /// #### Access to the Minimizer information during fitting
3868 ///
3869 /// This function calls, the ROOT::Fit::FitObject function implemented in HFitImpl.cxx
3870 /// which uses the ROOT::Fit::Fitter class. The Fitter class creates the objective function
3871 /// (e.g. chi2 or likelihood) and uses an implementation of the Minimizer interface for minimizing
3872 /// the function.
3873 /// The default minimizer is Minuit (class TMinuitMinimizer which calls TMinuit).
3874 /// The default can be set in the resource file in etc/system.rootrc. For example
3875 ///
3876 /// ~~~ {.cpp}
3877 /// Root.Fitter: Minuit2
3878 /// ~~~
3879 ///
3880 /// A different fitter can also be set via ROOT::Math::MinimizerOptions::SetDefaultMinimizer
3881 /// (or TVirtualFitter::SetDefaultFitter).
3882 /// For example ROOT::Math::MinimizerOptions::SetDefaultMinimizer("GSLMultiMin","BFGS");
3883 /// will set the usage of the BFGS algorithm of the GSL multi-dimensional minimization
3884 /// (implemented in libMathMore). ROOT::Math::MinimizerOptions can be used also to set other
3885 /// default options, like maximum number of function calls, minimization tolerance or print
3886 /// level. See the documentation of this class.
3887 ///
3888 /// For fitting linear functions (containing the "++" sign" and polN functions,
3889 /// the linear fitter is automatically initialized.
3890 
3891 TFitResultPtr TH1::Fit(TF1 *f1 ,Option_t *option ,Option_t *goption, Double_t xxmin, Double_t xxmax)
3892 {
3893  // implementation of Fit method is in file hist/src/HFitImpl.cxx
3894  Foption_t fitOption;
3896 
3897  // create range and minimizer options with default values
3898  ROOT::Fit::DataRange range(xxmin,xxmax);
3899  ROOT::Math::MinimizerOptions minOption;
3900 
3901  // need to empty the buffer before
3902  // (t.b.d. do a ML unbinned fit with buffer data)
3903  if (fBuffer) BufferEmpty();
3904 
3905  return ROOT::Fit::FitObject(this, f1 , fitOption , minOption, goption, range);
3906 }
3907 
3908 ////////////////////////////////////////////////////////////////////////////////
3909 /// Display a panel with all histogram fit options.
3910 ///
3911 /// See class TFitPanel for example
3912 
3913 void TH1::FitPanel()
3914 {
3915  if (!gPad)
3916  gROOT->MakeDefCanvas();
3917 
3918  if (!gPad) {
3919  Error("FitPanel", "Unable to create a default canvas");
3920  return;
3921  }
3922 
3923 
3924  // use plugin manager to create instance of TFitEditor
3925  TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TFitEditor");
3926  if (handler && handler->LoadPlugin() != -1) {
3927  if (handler->ExecPlugin(2, gPad, this) == 0)
3928  Error("FitPanel", "Unable to create the FitPanel");
3929  }
3930  else
3931  Error("FitPanel", "Unable to find the FitPanel plug-in");
3932 }
3933 
3934 ////////////////////////////////////////////////////////////////////////////////
3935 /// Return an histogram containing the asymmetry of this histogram with h2,
3936 /// where the asymmetry is defined as:
3937 ///
3938 /// ~~~ {.cpp}
3939 /// Asymmetry = (h1 - h2)/(h1 + h2) where h1 = this
3940 /// ~~~
3941 ///
3942 /// works for 1D, 2D, etc. histograms
3943 /// c2 is an optional argument that gives a relative weight between the two
3944 /// histograms, and dc2 is the error on this weight. This is useful, for example,
3945 /// when forming an asymmetry between two histograms from 2 different data sets that
3946 /// need to be normalized to each other in some way. The function calculates
3947 /// the errors assuming Poisson statistics on h1 and h2 (that is, dh = sqrt(h)).
3948 ///
3949 /// example: assuming 'h1' and 'h2' are already filled
3950 ///
3951 /// ~~~ {.cpp}
3952 /// h3 = h1->GetAsymmetry(h2)
3953 /// ~~~
3954 ///
3955 /// then 'h3' is created and filled with the asymmetry between 'h1' and 'h2';
3956 /// h1 and h2 are left intact.
3957 ///
3958 /// Note that it is the user's responsibility to manage the created histogram.
3959 /// The name of the returned histogram will be `Asymmetry_nameOfh1-nameOfh2`
3960 ///
3961 /// code proposed by Jason Seely (seely@mit.edu) and adapted by R.Brun
3962 ///
3963 /// clone the histograms so top and bottom will have the
3964 /// correct dimensions:
3965 /// Sumw2 just makes sure the errors will be computed properly
3966 /// when we form sums and ratios below.
3967 
3968 TH1 *TH1::GetAsymmetry(TH1* h2, Double_t c2, Double_t dc2)
3969 {
3970  TH1 *h1 = this;
3971  TString name = TString::Format("Asymmetry_%s-%s",h1->GetName(),h2->GetName() );
3972  TH1 *asym = (TH1*)Clone(name);
3973 
3974  // set also the title
3975  TString title = TString::Format("(%s - %s)/(%s+%s)",h1->GetName(),h2->GetName(),h1->GetName(),h2->GetName() );
3976  asym->SetTitle(title);
3977 
3978  asym->Sumw2();
3979  Bool_t addStatus = TH1::AddDirectoryStatus();
3981  TH1 *top = (TH1*)asym->Clone();
3982  TH1 *bottom = (TH1*)asym->Clone();
3983  TH1::AddDirectory(addStatus);
3984 
3985  // form the top and bottom of the asymmetry, and then divide:
3986  top->Add(h1,h2,1,-c2);
3987  bottom->Add(h1,h2,1,c2);
3988  asym->Divide(top,bottom);
3989 
3990  Int_t xmax = asym->GetNbinsX();
3991  Int_t ymax = asym->GetNbinsY();
3992  Int_t zmax = asym->GetNbinsZ();
3993 
3994  if (h1->fBuffer) h1->BufferEmpty(1);
3995  if (h2->fBuffer) h2->BufferEmpty(1);
3996  if (bottom->fBuffer) bottom->BufferEmpty(1);
3997 
3998  // now loop over bins to calculate the correct errors
3999  // the reason this error calculation looks complex is because of c2
4000  for(Int_t i=1; i<= xmax; i++){
4001  for(Int_t j=1; j<= ymax; j++){
4002  for(Int_t k=1; k<= zmax; k++){
4003  Int_t bin = GetBin(i, j, k);
4004  // here some bin contents are written into variables to make the error
4005  // calculation a little more legible:
4006  Double_t a = h1->RetrieveBinContent(bin);
4007  Double_t b = h2->RetrieveBinContent(bin);
4008  Double_t bot = bottom->RetrieveBinContent(bin);
4009 
4010  // make sure there are some events, if not, then the errors are set = 0
4011  // automatically.
4012  //if(bot < 1){} was changed to the next line from recommendation of Jason Seely (28 Nov 2005)
4013  if(bot < 1e-6){}
4014  else{
4015  // computation of errors by Christos Leonidopoulos
4016  Double_t dasq = h1->GetBinErrorSqUnchecked(bin);
4017  Double_t dbsq = h2->GetBinErrorSqUnchecked(bin);
4018  Double_t error = 2*TMath::Sqrt(a*a*c2*c2*dbsq + c2*c2*b*b*dasq+a*a*b*b*dc2*dc2)/(bot*bot);
4019  asym->SetBinError(i,j,k,error);
4020  }
4021  }
4022  }
4023  }
4024  delete top;
4025  delete bottom;
4026 
4027  return asym;
4028 }
4029 
4030 ////////////////////////////////////////////////////////////////////////////////
4031 /// Static function
4032 /// return the default buffer size for automatic histograms
4033 /// the parameter fgBufferSize may be changed via SetDefaultBufferSize
4034 
4036 {
4038 }
4039 
4040 ////////////////////////////////////////////////////////////////////////////////
4041 /// Return kTRUE if TH1::Sumw2 must be called when creating new histograms.
4042 /// see TH1::SetDefaultSumw2.
4043 
4045 {
4047 }
4048 
4049 ////////////////////////////////////////////////////////////////////////////////
4050 /// Return the current number of entries.
4051 
4052 Double_t TH1::GetEntries() const
4053 {
4054  if (fBuffer) {
4055  Int_t nentries = (Int_t) fBuffer[0];
4056  if (nentries > 0) return nentries;
4057  }
4058 
4059  return fEntries;
4060 }
4061 
4062 ////////////////////////////////////////////////////////////////////////////////
4063 /// Number of effective entries of the histogram.
4064 ///
4065 /// \f[
4066 /// neff = \frac{(\sum Weights )^2}{(\sum Weight^2 )}
4067 /// \f]
4068 ///
4069 /// In case of an unweighted histogram this number is equivalent to the
4070 /// number of entries of the histogram.
4071 /// For a weighted histogram, this number corresponds to the hypothetical number of unweighted entries
4072 /// a histogram would need to have the same statistical power as this weighted histogram.
4073 /// Note: The underflow/overflow are included if one has set the TH1::StatOverFlows flag
4074 /// and if the statistics has been computed at filling time.
4075 /// If a range is set in the histogram the number is computed from the given range.
4076 
4078 {
4080  this->GetStats(s);// s[1] sum of squares of weights, s[0] sum of weights
4081  return (s[1] ? s[0]*s[0]/s[1] : TMath::Abs(s[0]) );
4082 }
4083 
4084 ////////////////////////////////////////////////////////////////////////////////
4085 /// Redefines TObject::GetObjectInfo.
4086 /// Displays the histogram info (bin number, contents, integral up to bin
4087 /// corresponding to cursor position px,py
4088 
4089 char *TH1::GetObjectInfo(Int_t px, Int_t py) const
4090 {
4091  return ((TH1*)this)->GetPainter()->GetObjectInfo(px,py);
4092 }
4093 
4094 ////////////////////////////////////////////////////////////////////////////////
4095 /// Return pointer to painter.
4096 /// If painter does not exist, it is created
4097 
4099 {
4100  if (!fPainter) {
4101  TString opt = option;
4102  opt.ToLower();
4103  if (opt.Contains("gl") || gStyle->GetCanvasPreferGL()) {
4104  //try to create TGLHistPainter
4105  TPluginHandler *handler = gROOT->GetPluginManager()->FindHandler("TGLHistPainter");
4106 
4107  if (handler && handler->LoadPlugin() != -1)
4108  fPainter = reinterpret_cast<TVirtualHistPainter *>(handler->ExecPlugin(1, this));
4109  }
4110  }
4111 
4113 
4114  return fPainter;
4115 }
4116 
4117 ////////////////////////////////////////////////////////////////////////////////
4118 /// Compute Quantiles for this histogram
4119 /// Quantile x_q of a probability distribution Function F is defined as
4120 ///
4121 /// ~~~ {.cpp}
4122 /// F(x_q) = q with 0 <= q <= 1.
4123 /// ~~~
4124 ///
4125 /// For instance the median x_0.5 of a distribution is defined as that value
4126 /// of the random variable for which the distribution function equals 0.5:
4127 ///
4128 /// ~~~ {.cpp}
4129 /// F(x_0.5) = Probability(x < x_0.5) = 0.5
4130 /// ~~~
4131 ///
4132 /// code from Eddy Offermann, Renaissance
4133 ///
4134 /// \param[in] nprobSum maximum size of array q and size of array probSum (if given)
4135 /// \param[in] probSum array of positions where quantiles will be computed.
4136 /// - if probSum is null, probSum will be computed internally and will
4137 /// have a size = number of bins + 1 in h. it will correspond to the
4138 /// quantiles calculated at the lowest edge of the histogram (quantile=0) and
4139 /// all the upper edges of the bins.
4140 /// - if probSum is not null, it is assumed to contain at least nprobSum values.
4141 /// \param[out] q array q filled with nq quantiles
4142 /// \return value nq (<=nprobSum) with the number of quantiles computed
4143 ///
4144 /// Note that the Integral of the histogram is automatically recomputed
4145 /// if the number of entries is different of the number of entries when
4146 /// the integral was computed last time. In case you do not use the Fill
4147 /// functions to fill your histogram, but SetBinContent, you must call
4148 /// TH1::ComputeIntegral before calling this function.
4149 ///
4150 /// Getting quantiles q from two histograms and storing results in a TGraph,
4151 /// a so-called QQ-plot
4152 ///
4153 /// ~~~ {.cpp}
4154 /// TGraph *gr = new TGraph(nprob);
4155 /// h1->GetQuantiles(nprob,gr->GetX());
4156 /// h2->GetQuantiles(nprob,gr->GetY());
4157 /// gr->Draw("alp");
4158 /// ~~~
4159 ///
4160 /// Example:
4161 ///
4162 /// ~~~ {.cpp}
4163 /// void quantiles() {
4164 /// // demo for quantiles
4165 /// const Int_t nq = 20;
4166 /// TH1F *h = new TH1F("h","demo quantiles",100,-3,3);
4167 /// h->FillRandom("gaus",5000);
4168 ///
4169 /// Double_t xq[nq]; // position where to compute the quantiles in [0,1]
4170 /// Double_t yq[nq]; // array to contain the quantiles
4171 /// for (Int_t i=0;i<nq;i++) xq[i] = Float_t(i+1)/nq;
4172 /// h->GetQuantiles(nq,yq,xq);
4173 ///
4174 /// //show the original histogram in the top pad
4175 /// TCanvas *c1 = new TCanvas("c1","demo quantiles",10,10,700,900);
4176 /// c1->Divide(1,2);
4177 /// c1->cd(1);
4178 /// h->Draw();
4179 ///
4180 /// // show the quantiles in the bottom pad
4181 /// c1->cd(2);
4182 /// gPad->SetGrid();
4183 /// TGraph *gr = new TGraph(nq,xq,yq);
4184 /// gr->SetMarkerStyle(21);
4185 /// gr->Draw("alp");
4186 /// }
4187 /// ~~~
4188 
4189 Int_t TH1::GetQuantiles(Int_t nprobSum, Double_t *q, const Double_t *probSum)
4190 {
4191  if (GetDimension() > 1) {
4192  Error("GetQuantiles","Only available for 1-d histograms");
4193  return 0;
4194  }
4195 
4196  const Int_t nbins = GetXaxis()->GetNbins();
4197  if (!fIntegral) ComputeIntegral();
4198  if (fIntegral[nbins+1] != fEntries) ComputeIntegral();
4199 
4200  Int_t i, ibin;
4201  Double_t *prob = (Double_t*)probSum;
4202  Int_t nq = nprobSum;
4203  if (probSum == 0) {
4204  nq = nbins+1;
4205  prob = new Double_t[nq];
4206  prob[0] = 0;
4207  for (i=1;i<nq;i++) {
4208  prob[i] = fIntegral[i]/fIntegral[nbins];
4209  }
4210  }
4211 
4212  for (i = 0; i < nq; i++) {
4213  ibin = TMath::BinarySearch(nbins,fIntegral,prob[i]);
4214  while (ibin < nbins-1 && fIntegral[ibin+1] == prob[i]) {
4215  if (fIntegral[ibin+2] == prob[i]) ibin++;
4216  else break;
4217  }
4218  q[i] = GetBinLowEdge(ibin+1);
4219  const Double_t dint = fIntegral[ibin+1]-fIntegral[ibin];
4220  if (dint > 0) q[i] += GetBinWidth(ibin+1)*(prob[i]-fIntegral[ibin])/dint;
4221  }
4222 
4223  if (!probSum) delete [] prob;
4224  return nq;
4225 }
4226 
4227 ////////////////////////////////////////////////////////////////////////////////
4228 /// Decode string choptin and fill fitOption structure.
4229 
4230 Int_t TH1::FitOptionsMake(Option_t *choptin, Foption_t &fitOption)
4231 {
4233  return 1;
4234 }
4235 
4236 ////////////////////////////////////////////////////////////////////////////////
4237 /// Compute Initial values of parameters for a gaussian.
4238 
4239 void H1InitGaus()
4240 {
4241  Double_t allcha, sumx, sumx2, x, val, stddev, mean;
4242  Int_t bin;
4243  const Double_t sqrtpi = 2.506628;
4244 
4245  // - Compute mean value and StdDev of the histogram in the given range
4247  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4248  Int_t hxfirst = hFitter->GetXfirst();
4249  Int_t hxlast = hFitter->GetXlast();
4250  Double_t valmax = curHist->GetBinContent(hxfirst);
4251  Double_t binwidx = curHist->GetBinWidth(hxfirst);
4252  allcha = sumx = sumx2 = 0;
4253  for (bin=hxfirst;bin<=hxlast;bin++) {
4254  x = curHist->GetBinCenter(bin);
4255  val = TMath::Abs(curHist->GetBinContent(bin));
4256  if (val > valmax) valmax = val;
4257  sumx += val*x;
4258  sumx2 += val*x*x;
4259  allcha += val;
4260  }
4261  if (allcha == 0) return;
4262  mean = sumx/allcha;
4263  stddev = sumx2/allcha - mean*mean;
4264  if (stddev > 0) stddev = TMath::Sqrt(stddev);
4265  else stddev = 0;
4266  if (stddev == 0) stddev = binwidx*(hxlast-hxfirst+1)/4;
4267  //if the distribution is really gaussian, the best approximation
4268  //is binwidx*allcha/(sqrtpi*stddev)
4269  //However, in case of non-gaussian tails, this underestimates
4270  //the normalisation constant. In this case the maximum value
4271  //is a better approximation.
4272  //We take the average of both quantities
4273  Double_t constant = 0.5*(valmax+binwidx*allcha/(sqrtpi*stddev));
4274 
4275  //In case the mean value is outside the histo limits and
4276  //the StdDev is bigger than the range, we take
4277  // mean = center of bins
4278  // stddev = half range
4279  Double_t xmin = curHist->GetXaxis()->GetXmin();
4280  Double_t xmax = curHist->GetXaxis()->GetXmax();
4281  if ((mean < xmin || mean > xmax) && stddev > (xmax-xmin)) {
4282  mean = 0.5*(xmax+xmin);
4283  stddev = 0.5*(xmax-xmin);
4284  }
4285  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4286  f1->SetParameter(0,constant);
4287  f1->SetParameter(1,mean);
4288  f1->SetParameter(2,stddev);
4289  f1->SetParLimits(2,0,10*stddev);
4290 }
4291 
4292 ////////////////////////////////////////////////////////////////////////////////
4293 /// Compute Initial values of parameters for an exponential.
4294 
4295 void H1InitExpo()
4296 {
4297  Double_t constant, slope;
4298  Int_t ifail;
4300  Int_t hxfirst = hFitter->GetXfirst();
4301  Int_t hxlast = hFitter->GetXlast();
4302  Int_t nchanx = hxlast - hxfirst + 1;
4303 
4304  H1LeastSquareLinearFit(-nchanx, constant, slope, ifail);
4305 
4306  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4307  f1->SetParameter(0,constant);
4308  f1->SetParameter(1,slope);
4309 
4310 }
4311 
4312 ////////////////////////////////////////////////////////////////////////////////
4313 /// Compute Initial values of parameters for a polynom.
4314 
4315 void H1InitPolynom()
4316 {
4317  Double_t fitpar[25];
4318 
4320  TF1 *f1 = (TF1*)hFitter->GetUserFunc();
4321  Int_t hxfirst = hFitter->GetXfirst();
4322  Int_t hxlast = hFitter->GetXlast();
4323  Int_t nchanx = hxlast - hxfirst + 1;
4324  Int_t npar = f1->GetNpar();
4325 
4326  if (nchanx <=1 || npar == 1) {
4327  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4328  fitpar[0] = curHist->GetSumOfWeights()/Double_t(nchanx);
4329  } else {
4330  H1LeastSquareFit( nchanx, npar, fitpar);
4331  }
4332  for (Int_t i=0;i<npar;i++) f1->SetParameter(i, fitpar[i]);
4333 }
4334 
4335 ////////////////////////////////////////////////////////////////////////////////
4336 /// Least squares lpolynomial fitting without weights.
4337 ///
4338 /// \param[in] n number of points to fit
4339 /// \param[in] m number of parameters
4340 /// \param[in] a array of parameters
4341 ///
4342 /// based on CERNLIB routine LSQ: Translated to C++ by Rene Brun
4343 /// (E.Keil. revised by B.Schorr, 23.10.1981.)
4344 
4345 void H1LeastSquareFit(Int_t n, Int_t m, Double_t *a)
4346 {
4347  const Double_t zero = 0.;
4348  const Double_t one = 1.;
4349  const Int_t idim = 20;
4350 
4351  Double_t b[400] /* was [20][20] */;
4352  Int_t i, k, l, ifail;
4353  Double_t power;
4354  Double_t da[20], xk, yk;
4355 
4356  if (m <= 2) {
4357  H1LeastSquareLinearFit(n, a[0], a[1], ifail);
4358  return;
4359  }
4360  if (m > idim || m > n) return;
4361  b[0] = Double_t(n);
4362  da[0] = zero;
4363  for (l = 2; l <= m; ++l) {
4364  b[l-1] = zero;
4365  b[m + l*20 - 21] = zero;
4366  da[l-1] = zero;
4367  }
4369  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4370  Int_t hxfirst = hFitter->GetXfirst();
4371  Int_t hxlast = hFitter->GetXlast();
4372  for (k = hxfirst; k <= hxlast; ++k) {
4373  xk = curHist->GetBinCenter(k);
4374  yk = curHist->GetBinContent(k);
4375  power = one;
4376  da[0] += yk;
4377  for (l = 2; l <= m; ++l) {
4378  power *= xk;
4379  b[l-1] += power;
4380  da[l-1] += power*yk;
4381  }
4382  for (l = 2; l <= m; ++l) {
4383  power *= xk;
4384  b[m + l*20 - 21] += power;
4385  }
4386  }
4387  for (i = 3; i <= m; ++i) {
4388  for (k = i; k <= m; ++k) {
4389  b[k - 1 + (i-1)*20 - 21] = b[k + (i-2)*20 - 21];
4390  }
4391  }
4392  H1LeastSquareSeqnd(m, b, idim, ifail, 1, da);
4393 
4394  for (i=0; i<m; ++i) a[i] = da[i];
4395 
4396 }
4397 
4398 ////////////////////////////////////////////////////////////////////////////////
4399 /// Least square linear fit without weights.
4400 ///
4401 /// extracted from CERNLIB LLSQ: Translated to C++ by Rene Brun
4402 /// (added to LSQ by B. Schorr, 15.02.1982.)
4403 
4404 void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
4405 {
4406  Double_t xbar, ybar, x2bar;
4407  Int_t i, n;
4408  Double_t xybar;
4409  Double_t fn, xk, yk;
4410  Double_t det;
4411 
4412  n = TMath::Abs(ndata);
4413  ifail = -2;
4414  xbar = ybar = x2bar = xybar = 0;
4416  TH1 *curHist = (TH1*)hFitter->GetObjectFit();
4417  Int_t hxfirst = hFitter->GetXfirst();
4418  Int_t hxlast = hFitter->GetXlast();
4419  for (i = hxfirst; i <= hxlast; ++i) {
4420  xk = curHist->GetBinCenter(i);
4421  yk = curHist->GetBinContent(i);
4422  if (ndata < 0) {
4423  if (yk <= 0) yk = 1e-9;
4424  yk = TMath::Log(yk);
4425  }
4426  xbar += xk;
4427  ybar += yk;
4428  x2bar += xk*xk;
4429  xybar += xk*yk;
4430  }
4431  fn = Double_t(n);
4432  det = fn*x2bar - xbar*xbar;
4433  ifail = -1;
4434  if (det <= 0) {
4435  a0 = ybar/fn;
4436  a1 = 0;
4437  return;
4438  }
4439  ifail = 0;
4440  a0 = (x2bar*ybar - xbar*xybar) / det;
4441  a1 = (fn*xybar - xbar*ybar) / det;
4442 
4443 }
4444 
4445 ////////////////////////////////////////////////////////////////////////////////
4446 /// Extracted from CERN Program library routine DSEQN.
4447 ///
4448 /// Translated to C++ by Rene Brun
4449 
4450 void H1LeastSquareSeqnd(Int_t n, Double_t *a, Int_t idim, Int_t &ifail, Int_t k, Double_t *b)
4451 {
4452  Int_t a_dim1, a_offset, b_dim1, b_offset;
4453  Int_t nmjp1, i, j, l;
4454  Int_t im1, jp1, nm1, nmi;
4455  Double_t s1, s21, s22;
4456  const Double_t one = 1.;
4457 
4458  /* Parameter adjustments */
4459  b_dim1 = idim;
4460  b_offset = b_dim1 + 1;
4461  b -= b_offset;
4462  a_dim1 = idim;
4463  a_offset = a_dim1 + 1;
4464  a -= a_offset;
4465 
4466  if (idim < n) return;
4467 
4468  ifail = 0;
4469  for (j = 1; j <= n; ++j) {
4470  if (a[j + j*a_dim1] <= 0) { ifail = -1; return; }
4471  a[j + j*a_dim1] = one / a[j + j*a_dim1];
4472  if (j == n) continue;
4473  jp1 = j + 1;
4474  for (l = jp1; l <= n; ++l) {
4475  a[j + l*a_dim1] = a[j + j*a_dim1] * a[l + j*a_dim1];
4476  s1 = -a[l + (j+1)*a_dim1];
4477  for (i = 1; i <= j; ++i) { s1 = a[l + i*a_dim1] * a[i + (j+1)*a_dim1] + s1; }
4478  a[l + (j+1)*a_dim1] = -s1;
4479  }
4480  }
4481  if (k <= 0) return;
4482 
4483  for (l = 1; l <= k; ++l) {
4484  b[l*b_dim1 + 1] = a[a_dim1 + 1]*b[l*b_dim1 + 1];
4485  }
4486  if (n == 1) return;
4487  for (l = 1; l <= k; ++l) {
4488  for (i = 2; i <= n; ++i) {
4489  im1 = i - 1;
4490  s21 = -b[i + l*b_dim1];
4491  for (j = 1; j <= im1; ++j) {
4492  s21 = a[i + j*a_dim1]*b[j + l*b_dim1] + s21;
4493  }
4494  b[i + l*b_dim1] = -a[i + i*a_dim1]*s21;
4495  }
4496  nm1 = n - 1;
4497  for (i = 1; i <= nm1; ++i) {
4498  nmi = n - i;
4499  s22 = -b[nmi + l*b_dim1];
4500  for (j = 1; j <= i; ++j) {
4501  nmjp1 = n - j + 1;
4502  s22 = a[nmi + nmjp1*a_dim1]*b[nmjp1 + l*b_dim1] + s22;
4503  }
4504  b[nmi + l*b_dim1] = -s22;
4505  }
4506  }
4507 }
4508 
4509 ////////////////////////////////////////////////////////////////////////////////
4510 /// Return Global bin number corresponding to binx,y,z.
4511 ///
4512 /// 2-D and 3-D histograms are represented with a one dimensional
4513 /// structure.
4514 /// This has the advantage that all existing functions, such as
4515 /// GetBinContent, GetBinError, GetBinFunction work for all dimensions.
4516 ///
4517 /// In case of a TH1x, returns binx directly.
4518 /// see TH1::GetBinXYZ for the inverse transformation.
4519 ///
4520 /// Convention for numbering bins
4521 ///
4522 /// For all histogram types: nbins, xlow, xup
4523 ///
4524 /// - bin = 0; underflow bin
4525 /// - bin = 1; first bin with low-edge xlow INCLUDED
4526 /// - bin = nbins; last bin with upper-edge xup EXCLUDED
4527 /// - bin = nbins+1; overflow bin
4528 ///
4529 /// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4530 /// For example, assuming a 3-D histogram with binx,biny,binz, the function
4531 ///
4532 /// ~~~ {.cpp}
4533 /// Int_t bin = h->GetBin(binx,biny,binz);
4534 /// ~~~
4535 ///
4536 /// returns a global/linearized bin number. This global bin is useful
4537 /// to access the bin information independently of the dimension.
4538 
4539 Int_t TH1::GetBin(Int_t binx, Int_t, Int_t) const
4540 {
4541  Int_t ofx = fXaxis.GetNbins() + 1; // overflow bin
4542  if (binx < 0) binx = 0;
4543  if (binx > ofx) binx = ofx;
4544 
4545  return binx;
4546 }
4547 
4548 ////////////////////////////////////////////////////////////////////////////////
4549 /// Return binx, biny, binz corresponding to the global bin number globalbin
4550 /// see TH1::GetBin function above
4551 
4552 void TH1::GetBinXYZ(Int_t binglobal, Int_t &binx, Int_t &biny, Int_t &binz) const
4553 {
4555  Int_t ny = fYaxis.GetNbins()+2;
4556 
4557  if (GetDimension() == 1) {
4558  binx = binglobal%nx;
4559  biny = 0;
4560  binz = 0;
4561  return;
4562  }
4563  if (GetDimension() == 2) {
4564  binx = binglobal%nx;
4565  biny = ((binglobal-binx)/nx)%ny;
4566  binz = 0;
4567  return;
4568  }
4569  if (GetDimension() == 3) {
4570  binx = binglobal%nx;
4571  biny = ((binglobal-binx)/nx)%ny;
4572  binz = ((binglobal-binx)/nx -biny)/ny;
4573  }
4574 }
4575 
4576 ////////////////////////////////////////////////////////////////////////////////
4577 /// Return a random number distributed according the histogram bin contents.
4578 /// This function checks if the bins integral exists. If not, the integral
4579 /// is evaluated, normalized to one.
4580 ///
4581 /// The integral is automatically recomputed if the number of entries
4582 /// is not the same then when the integral was computed.
4583 /// NB Only valid for 1-d histograms. Use GetRandom2 or 3 otherwise.
4584 /// If the histogram has a bin with negative content a NaN is returned
4585 
4586 Double_t TH1::GetRandom() const
4587 {
4588  if (fDimension > 1) {
4589  Error("GetRandom","Function only valid for 1-d histograms");
4590  return 0;
4591  }
4592  Int_t nbinsx = GetNbinsX();
4593  Double_t integral = 0;
4594  // compute integral checking that all bins have positive content (see ROOT-5894)
4595  if (fIntegral) {
4596  if (fIntegral[nbinsx+1] != fEntries) integral = ((TH1*)this)->ComputeIntegral(true);
4597  else integral = fIntegral[nbinsx];
4598  } else {
4599  integral = ((TH1*)this)->ComputeIntegral(true);
4600  }
4601  if (integral == 0) return 0;
4602  // return a NaN in case some bins have negative content
4603  if (integral == TMath::QuietNaN() ) return TMath::QuietNaN();
4604 
4605  Double_t r1 = gRandom->Rndm();
4606  Int_t ibin = TMath::BinarySearch(nbinsx,fIntegral,r1);
4607  Double_t x = GetBinLowEdge(ibin+1);
4608  if (r1 > fIntegral[ibin]) x +=
4609  GetBinWidth(ibin+1)*(r1-fIntegral[ibin])/(fIntegral[ibin+1] - fIntegral[ibin]);
4610  return x;
4611 }
4612 
4613 ////////////////////////////////////////////////////////////////////////////////
4614 /// Return content of bin number bin.
4615 ///
4616 /// Implemented in TH1C,S,F,D
4617 ///
4618 /// Convention for numbering bins
4619 ///
4620 /// For all histogram types: nbins, xlow, xup
4621 ///
4622 /// - bin = 0; underflow bin
4623 /// - bin = 1; first bin with low-edge xlow INCLUDED
4624 /// - bin = nbins; last bin with upper-edge xup EXCLUDED
4625 /// - bin = nbins+1; overflow bin
4626 ///
4627 /// In case of 2-D or 3-D histograms, a "global bin" number is defined.
4628 /// For example, assuming a 3-D histogram with binx,biny,binz, the function
4629 ///
4630 /// ~~~ {.cpp}
4631 /// Int_t bin = h->GetBin(binx,biny,binz);
4632 /// ~~~
4633 ///
4634 /// returns a global/linearized bin number. This global bin is useful
4635 /// to access the bin information independently of the dimension.
4636 
4638 {
4639  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
4640  if (bin < 0) bin = 0;
4641  if (bin >= fNcells) bin = fNcells-1;
4642 
4643  return RetrieveBinContent(bin);
4644 }
4645 
4646 ////////////////////////////////////////////////////////////////////////////////
4647 /// Compute first binx in the range [firstx,lastx] for which
4648 /// diff = abs(bin_content-c) <= maxdiff
4649 ///
4650 /// In case several bins in the specified range with diff=0 are found
4651 /// the first bin found is returned in binx.
4652 /// In case several bins in the specified range satisfy diff <=maxdiff
4653 /// the bin with the smallest difference is returned in binx.
4654 /// In all cases the function returns the smallest difference.
4655 ///
4656 /// NOTE1: if firstx <= 0, firstx is set to bin 1
4657 /// if (lastx < firstx then firstx is set to the number of bins
4658 /// ie if firstx=0 and lastx=0 (default) the search is on all bins.
4659 ///
4660 /// NOTE2: if maxdiff=0 (default), the first bin with content=c is returned.
4661 
4662 Double_t TH1::GetBinWithContent(Double_t c, Int_t &binx, Int_t firstx, Int_t lastx,Double_t maxdiff) const
4663 {
4664  if (fDimension > 1) {
4665  binx = 0;
4666  Error("GetBinWithContent","function is only valid for 1-D histograms");
4667  return 0;
4668  }
4669 
4670  if (fBuffer) ((TH1*)this)->BufferEmpty();
4671 
4672  if (firstx <= 0) firstx = 1;
4673  if (lastx < firstx) lastx = fXaxis.GetNbins();
4674  Int_t binminx = 0;
4675  Double_t diff, curmax = 1.e240;
4676  for (Int_t i=firstx;i<=lastx;i++) {
4677  diff = TMath::Abs(RetrieveBinContent(i)-c);
4678  if (diff <= 0) {binx = i; return diff;}
4679  if (diff < curmax && diff <= maxdiff) {curmax = diff, binminx=i;}
4680  }
4681  binx = binminx;
4682  return curmax;
4683 }
4684 
4685 ////////////////////////////////////////////////////////////////////////////////
4686 /// Given a point x, approximates the value via linear interpolation
4687 /// based on the two nearest bin centers
4688 ///
4689 /// Andy Mastbaum 10/21/08
4690 
4692 {
4693  if (fBuffer) ((TH1*)this)->BufferEmpty();
4694 
4695  Int_t xbin = FindBin(x);
4696  Double_t x0,x1,y0,y1;
4697 
4698  if(x<=GetBinCenter(1)) {
4699  return RetrieveBinContent(1);
4700  } else if(x>=GetBinCenter(GetNbinsX())) {
4701  return RetrieveBinContent(GetNbinsX());
4702  } else {
4703  if(x<=GetBinCenter(xbin)) {
4704  y0 = RetrieveBinContent(xbin-1);
4705  x0 = GetBinCenter(xbin-1);
4706  y1 = RetrieveBinContent(xbin);
4707  x1 = GetBinCenter(xbin);
4708  } else {
4709  y0 = RetrieveBinContent(xbin);
4710  x0 = GetBinCenter(xbin);
4711  y1 = RetrieveBinContent(xbin+1);
4712  x1 = GetBinCenter(xbin+1);
4713  }
4714  return y0 + (x-x0)*((y1-y0)/(x1-x0));
4715  }
4716 }
4717 
4718 ////////////////////////////////////////////////////////////////////////////////
4719 /// Interpolate. Not yet implemented.
4720 
4722 {
4723  Error("Interpolate","This function must be called with 1 argument for a TH1");
4724  return 0;
4725 }
4726 
4727 ////////////////////////////////////////////////////////////////////////////////
4728 /// Interpolate. Not yet implemented.
4729 
4731 {
4732  Error("Interpolate","This function must be called with 1 argument for a TH1");
4733  return 0;
4734 }
4735 
4736 ////////////////////////////////////////////////////////////////////////////////
4737 /// Return true if the bin is overflow.
4738 
4739 Bool_t TH1::IsBinOverflow(Int_t bin, Int_t iaxis) const
4740 {
4741  Int_t binx, biny, binz;
4742  GetBinXYZ(bin, binx, biny, binz);
4743 
4744  if (iaxis == 0) {
4745  if ( fDimension == 1 )
4746  return binx >= GetNbinsX() + 1;
4747  if ( fDimension == 2 )
4748  return (binx >= GetNbinsX() + 1) ||
4749  (biny >= GetNbinsY() + 1);
4750  if ( fDimension == 3 )
4751  return (binx >= GetNbinsX() + 1) ||
4752  (biny >= GetNbinsY() + 1) ||
4753  (binz >= GetNbinsZ() + 1);
4754  return kFALSE;
4755  }
4756  if (iaxis == 1)
4757  return binx >= GetNbinsX() + 1;
4758  if (iaxis == 2)
4759  return biny >= GetNbinsY() + 1;
4760  if (iaxis == 3)
4761  return binz >= GetNbinsZ() + 1;
4762 
4763  Error("IsBinOverflow","Invalid axis value");
4764  return kFALSE;
4765 }
4766 
4767 ////////////////////////////////////////////////////////////////////////////////
4768 /// Return true if the bin is underflow.
4769 /// If iaxis = 0 make OR with all axes otherwise check only for the given axis
4770 
4771 Bool_t TH1::IsBinUnderflow(Int_t bin, Int_t iaxis) const
4772 {
4773  Int_t binx, biny, binz;
4774  GetBinXYZ(bin, binx, biny, binz);
4775 
4776  if (iaxis == 0) {
4777  if ( fDimension == 1 )
4778  return (binx <= 0);
4779  else if ( fDimension == 2 )
4780  return (binx <= 0 || biny <= 0);
4781  else if ( fDimension == 3 )
4782  return (binx <= 0 || biny <= 0 || binz <= 0);
4783  else
4784  return kFALSE;
4785  }
4786  if (iaxis == 1)
4787  return (binx <= 0);
4788  if (iaxis == 2)
4789  return (biny <= 0);
4790  if (iaxis == 3)
4791  return (binz <= 0);
4792 
4793  Error("IsBinUnderflow","Invalid axis value");
4794  return kFALSE;
4795 }
4796 
4797 ////////////////////////////////////////////////////////////////////////////////
4798 /// Reduce the number of bins for the axis passed in the option to the number of bins having a label.
4799 /// The method will remove only the extra bins existing after the last "labeled" bin.
4800 /// Note that if there are "un-labeled" bins present between "labeled" bins they will not be removed
4801 
4802 void TH1::LabelsDeflate(Option_t *ax)
4803 {
4804  Int_t iaxis = AxisChoice(ax);
4805  TAxis *axis = 0;
4806  if (iaxis == 1) axis = GetXaxis();
4807  if (iaxis == 2) axis = GetYaxis();
4808  if (iaxis == 3) axis = GetZaxis();
4809  if (!axis) {
4810  Error("LabelsDeflate","Invalid axis option %s",ax);
4811  return;
4812  }
4813  if (!axis->GetLabels()) return;
4814 
4815  // find bin with last labels
4816  // bin number is object ID in list of labels
4817  // therefore max bin number is number of bins of the deflated histograms
4818  TIter next(axis->GetLabels());
4819  TObject *obj;
4820  Int_t nbins = 0;
4821  while ((obj = next())) {
4822  Int_t ibin = obj->GetUniqueID();
4823  if (ibin > nbins) nbins = ibin;
4824  }
4825  if (nbins < 1) nbins = 1;
4826 
4827  // Do nothing in case it was the last bin
4828  if (nbins==axis->GetNbins()) return;
4829 
4830  TH1 *hold = (TH1*)IsA()->New();
4831  R__ASSERT(hold);
4832  hold->SetDirectory(0);
4833  Copy(*hold);
4834 
4835  Bool_t timedisp = axis->GetTimeDisplay();
4836  Double_t xmin = axis->GetXmin();
4837  Double_t xmax = axis->GetBinUpEdge(nbins);
4838  if (xmax <= xmin) xmax = xmin +nbins;
4839  axis->SetRange(0,0);
4840  axis->Set(nbins,xmin,xmax);
4841  SetBinsLength(-1); // reset the number of cells
4842  Int_t errors = fSumw2.fN;
4843  if (errors) fSumw2.Set(fNcells);
4844  axis->SetTimeDisplay(timedisp);
4845  // reset histogram content
4846  Reset("ICE");
4847 
4848  //now loop on all bins and refill
4849  // NOTE that if the bins without labels have content
4850  // it will be put in the underflow/overflow.
4851  // For this reason we use AddBinContent method
4852  Double_t oldEntries = fEntries;
4853  Int_t bin,binx,biny,binz;
4854  for (bin=0; bin < hold->fNcells; ++bin) {
4855  hold->GetBinXYZ(bin,binx,biny,binz);
4856  Int_t ibin = GetBin(binx,biny,binz);
4857  Double_t cu = hold->RetrieveBinContent(bin);
4858  AddBinContent(ibin,cu);
4859  if (errors) {
4860  fSumw2.fArray[ibin] += hold->fSumw2.fArray[bin];
4861  }
4862  }
4863  fEntries = oldEntries;
4864  delete hold;
4865 }
4866 
4867 ////////////////////////////////////////////////////////////////////////////////
4868 /// Double the number of bins for axis.
4869 /// Refill histogram
4870 /// This function is called by TAxis::FindBin(const char *label)
4871 
4872 void TH1::LabelsInflate(Option_t *ax)
4873 {
4874  Int_t iaxis = AxisChoice(ax);
4875  TAxis *axis = 0;
4876  if (iaxis == 1) axis = GetXaxis();
4877  if (iaxis == 2) axis = GetYaxis();
4878  if (iaxis == 3) axis = GetZaxis();
4879  if (!axis) return;
4880 
4881  TH1 *hold = (TH1*)IsA()->New();;
4882  hold->SetDirectory(0);
4883  Copy(*hold);
4884 
4885  Bool_t timedisp = axis->GetTimeDisplay();
4886  Int_t nbins = axis->GetNbins();
4887  Double_t xmin = axis->GetXmin();
4888  Double_t xmax = axis->GetXmax();
4889  xmax = xmin + 2*(xmax-xmin);
4890  axis->SetRange(0,0);
4891  // double the bins and recompute ncells
4892  axis->Set(2*nbins,xmin,xmax);
4893  SetBinsLength(-1);
4894  Int_t errors = fSumw2.fN;
4895  if (errors) fSumw2.Set(fNcells);
4896  axis->SetTimeDisplay(timedisp);
4897 
4898  Reset("ICE"); // reset content and error
4899 
4900  //now loop on all bins and refill
4901  Double_t oldEntries = fEntries;
4902  Int_t bin,ibin,binx,biny,binz;
4903  for (ibin =0; ibin < hold->fNcells; ibin++) {
4904  // get the binx,y,z values . The x-y-z (axis) bin values will stay the same between new-old after the expanding
4905  hold->GetBinXYZ(ibin,binx,biny,binz);
4906  bin = GetBin(binx,biny,binz);
4907 
4908  // underflow and overflow will be cleaned up because their meaning has been altered
4909  if (hold->IsBinUnderflow(ibin,iaxis) || hold->IsBinOverflow(ibin,iaxis)) {
4910  continue;
4911  }
4912  else {
4913  AddBinContent(bin, hold->RetrieveBinContent(ibin));
4914  if (errors) fSumw2.fArray[bin] += hold->fSumw2.fArray[ibin];
4915  }
4916  }
4917  fEntries = oldEntries;
4918  delete hold;
4919 }
4920 
4921 ////////////////////////////////////////////////////////////////////////////////
4922 /// Set option(s) to draw axis with labels
4923 /// \param[in] option
4924 /// - "a" sort by alphabetic order
4925 /// - ">" sort by decreasing values
4926 /// - "<" sort by increasing values
4927 /// - "h" draw labels horizontal
4928 /// - "v" draw labels vertical
4929 /// - "u" draw labels up (end of label right adjusted)
4930 /// - "d" draw labels down (start of label left adjusted)
4931 /// \param[in] ax axis
4932 
4933 void TH1::LabelsOption(Option_t *option, Option_t *ax)
4934 {
4935  Int_t iaxis = AxisChoice(ax);
4936  TAxis *axis = 0;
4937  if (iaxis == 1) axis = GetXaxis();
4938  if (iaxis == 2) axis = GetYaxis();
4939  if (iaxis == 3) axis = GetZaxis();
4940  if (!axis) return;
4941  THashList *labels = axis->GetLabels();
4942  if (!labels) {
4943  Warning("LabelsOption","Cannot sort. No labels");
4944  return;
4945  }
4946  TString opt = option;
4947  opt.ToLower();
4948  if (opt.Contains("h")) {
4949  axis->SetBit(TAxis::kLabelsHori);
4952  axis->ResetBit(TAxis::kLabelsUp);
4953  }
4954  if (opt.Contains("v")) {
4955  axis->SetBit(TAxis::kLabelsVert);
4958  axis->ResetBit(TAxis::kLabelsUp);
4959  }
4960  if (opt.Contains("u")) {
4961  axis->SetBit(TAxis::kLabelsUp);
4965  }
4966  if (opt.Contains("d")) {
4967  axis->SetBit(TAxis::kLabelsDown);
4970  axis->ResetBit(TAxis::kLabelsUp);
4971  }
4972  Int_t sort = -1;
4973  if (opt.Contains("a")) sort = 0;
4974  if (opt.Contains(">")) sort = 1;
4975  if (opt.Contains("<")) sort = 2;
4976  if (sort < 0) return;
4977  if (sort > 0 && GetDimension() > 2) {
4978  Error("LabelsOption","Sorting by value not implemented for 3-D histograms");
4979  return;
4980  }
4981 
4982  Double_t entries = fEntries;
4983  Int_t n = TMath::Min(axis->GetNbins(), labels->GetSize());
4984  std::vector<Int_t> a(n+2);
4985 
4986  Int_t i,j,k;
4987  std::vector<Double_t> cont;
4988  std::vector<Double_t> errors;
4989  THashList *labold = new THashList(labels->GetSize(),1);
4990  TIter nextold(labels);
4991  TObject *obj;
4992  while ((obj=nextold())) {
4993  labold->Add(obj);
4994  }
4995  labels->Clear();
4996  if (sort > 0) {
4997  //---sort by values of bins
4998  if (GetDimension() == 1) {
4999  cont.resize(n);
5000  if (fSumw2.fN) errors.resize(n);
5001  for (i=1;i<=n;i++) {
5002  cont[i-1] = GetBinContent(i);
5003  if (!errors.empty()) errors[i-1] = GetBinError(i);
5004  }
5005  if (sort ==1) TMath::Sort(n,cont.data(),a.data(),kTRUE); //sort by decreasing values
5006  else TMath::Sort(n,cont.data(),a.data(),kFALSE); //sort by increasing values
5007  for (i=1;i<=n;i++) {
5008  SetBinContent(i,cont[a[i-1]]);
5009  if (!errors.empty()) SetBinError(i,errors[a[i-1]]);
5010  }
5011  for (i=1;i<=n;i++) {
5012  obj = labold->At(a[i-1]);
5013  labels->Add(obj);
5014  obj->SetUniqueID(i);
5015  }
5016  } else if (GetDimension()== 2) {
5017  std::vector<Double_t> pcont(n+2);
5018  Int_t nx = fXaxis.GetNbins();
5019  Int_t ny = fYaxis.GetNbins();
5020  cont.resize( (nx+2)*(ny+2));
5021  if (fSumw2.fN) errors.resize( (nx+2)*(ny+2));
5022  for (i=1;i<=nx;i++) {
5023  for (j=1;j<=ny;j++) {
5024  cont[i+nx*j] = GetBinContent(i,j);
5025  if (!errors.empty()) errors[i+nx*j] = GetBinError(i,j);
5026  if (axis == GetXaxis()) k = i;
5027  else k = j;
5028  pcont[k-1] += cont[i+nx*j];
5029  }
5030  }
5031  if (sort ==1) TMath::Sort(n,pcont.data(),a.data(),kTRUE); //sort by decreasing values
5032  else TMath::Sort(n,pcont.data(),a.data(),kFALSE); //sort by increasing values
5033  for (i=0;i<n;i++) {
5034  obj = labold->At(a[i]);
5035  labels->Add(obj);
5036  obj->SetUniqueID(i+1);
5037  }
5038  if (axis == GetXaxis()) {
5039  for (i=1;i<=n;i++) {
5040  for (j=1;j<=ny;j++) {
5041  SetBinContent(i,j,cont[a[i-1]+1+nx*j]);
5042  if (!errors.empty()) SetBinError(i,j,errors[a[i-1]+1+nx*j]);
5043  }
5044  }
5045  }
5046  else {
5047  // using y axis
5048  for (i=1;i<=nx;i++) {
5049  for (j=1;j<=n;j++) {
5050  SetBinContent(i,j,cont[i+nx*(a[j-1]+1)]);
5051  if (!errors.empty()) SetBinError(i,j,errors[i+nx*(a[j-1]+1)]);
5052  }
5053  }
5054  }
5055  } else {
5056  //to be implemented for 3d
5057  }
5058  } else {
5059  //---alphabetic sort
5060  const UInt_t kUsed = 1<<18;
5061  TObject *objk=0;
5062  a[0] = 0;
5063  a[n+1] = n+1;
5064  for (i=1;i<=n;i++) {
5065  const char *label = "zzzzzzzzzzzz";
5066  for (j=1;j<=n;j++) {
5067  obj = labold->At(j-1);
5068  if (!obj) continue;
5069  if (obj->TestBit(kUsed)) continue;
5070  //use strcasecmp for case non-sensitive sort (may be an option)
5071  if (strcmp(label,obj->GetName()) < 0) continue;
5072  objk = obj;
5073  a[i] = j;
5074  label = obj->GetName();
5075  }
5076  if (objk) {
5077  objk->SetUniqueID(i);
5078  labels->Add(objk);
5079  objk->SetBit(kUsed);
5080  }
5081  }
5082  for (i=1;i<=n;i++) {
5083  obj = labels->At(i-1);
5084  if (!obj) continue;
5085  obj->ResetBit(kUsed);
5086  }
5087 
5088  if (GetDimension() == 1) {
5089  cont.resize(n+2);
5090  if (fSumw2.fN) errors.resize(n+2);
5091  for (i=1;i<=n;i++) {
5092  cont[i] = GetBinContent(a[i]);
5093  if (!errors.empty()) errors[i] = GetBinError(a[i]);
5094  }
5095  for (i=1;i<=n;i++) {
5096  SetBinContent(i,cont[i]);
5097  if (!errors.empty()) SetBinError(i,errors[i]);
5098  }
5099  } else if (GetDimension()== 2) {
5100  Int_t nx = fXaxis.GetNbins()+2;
5101  Int_t ny = fYaxis.GetNbins()+2;
5102  cont.resize(nx*ny);
5103  if (fSumw2.fN) errors.resize(nx*ny);
5104  for (i=0;i<nx;i++) {
5105  for (j=0;j<ny;j++) {
5106  cont[i+nx*j] = GetBinContent(i,j);
5107  if (!errors.empty()) errors[i+nx*j] = GetBinError(i,j);
5108  }
5109  }
5110  if (axis == GetXaxis()) {
5111  for (i=1;i<=n;i++) {
5112  for (j=0;j<ny;j++) {
5113  SetBinContent(i,j,cont[a[i]+nx*j]);
5114  if (!errors.empty()) SetBinError(i,j,errors[a[i]+nx*j]);
5115  }
5116  }
5117  } else {
5118  for (i=0;i<nx;i++) {
5119  for (j=1;j<=n;j++) {
5120  SetBinContent(i,j,cont[i+nx*a[j]]);
5121  if (!errors.empty()) SetBinError(i,j,errors[i+nx*a[j]]);
5122  }
5123  }
5124  }
5125  } else {
5126  Int_t nx = fXaxis.GetNbins()+2;
5127  Int_t ny = fYaxis.GetNbins()+2;
5128  Int_t nz = fZaxis.GetNbins()+2;
5129  cont.resize(nx*ny*nz);
5130  if (fSumw2.fN) errors.resize(nx*ny*nz);
5131  for (i=0;i<nx;i++) {
5132  for (j=0;j<ny;j++) {
5133  for (k=0;k<nz;k++) {
5134  cont[i+nx*(j+ny*k)] = GetBinContent(i,j,k);
5135  if (!errors.empty()) errors[i+nx*(j+ny*k)] = GetBinError(i,j,k);
5136  }
5137  }
5138  }
5139  if (axis == GetXaxis()) {
5140  // labels on x axis
5141  for (i=1;i<=n;i++) {
5142  for (j=0;j<ny;j++) {
5143  for (k=0;k<nz;k++) {
5144  SetBinContent(i,j,k,cont[a[i]+nx*(j+ny*k)]);
5145  if (!errors.empty()) SetBinError(i,j,k,errors[a[i]+nx*(j+ny*k)]);
5146  }
5147  }
5148  }
5149  }
5150  else if (axis == GetYaxis()) {
5151  // labels on y axis
5152  for (i=0;i<nx;i++) {
5153  for (j=1;j<=n;j++) {
5154  for (k=0;k<nz;k++) {
5155  SetBinContent(i,j,k,cont[i+nx*(a[j]+ny*k)]);
5156  if (!errors.empty()) SetBinError(i,j,k,errors[i+nx*(a[j]+ny*k)]);
5157  }
5158  }
5159  }
5160  }
5161  else {
5162  // labels on z axis
5163  for (i=0;i<nx;i++) {
5164  for (j=0;j<ny;j++) {
5165  for (k=1;k<=n;k++) {
5166  SetBinContent(i,j,k,cont[i+nx*(j+ny*a[k])]);
5167  if (!errors.empty()) SetBinError(i,j,k,errors[i+nx*(j+ny*a[k])]);
5168  }
5169  }
5170  }
5171  }
5172  }
5173  }
5174  fEntries = entries;
5175  delete labold;
5176 }
5177 
5178 ////////////////////////////////////////////////////////////////////////////////
5179 /// Test if two double are almost equal.
5180 
5181 static inline Bool_t AlmostEqual(Double_t a, Double_t b, Double_t epsilon = 0.00000001)
5182 {
5183  return TMath::Abs(a - b) < epsilon;
5184 }
5185 
5186 ////////////////////////////////////////////////////////////////////////////////
5187 /// Test if a double is almost an integer.
5188 
5189 static inline Bool_t AlmostInteger(Double_t a, Double_t epsilon = 0.00000001)
5190 {
5191  return AlmostEqual(a - TMath::Floor(a), 0, epsilon) ||
5192  AlmostEqual(a - TMath::Floor(a), 1, epsilon);
5193 }
5194 
5195 ////////////////////////////////////////////////////////////////////////////////
5196 /// Test if the binning is equidistant.
5197 
5198 static inline bool IsEquidistantBinning(const TAxis& axis)
5199 {
5200  // check if axis bin are equals
5201  if (!axis.GetXbins()->fN) return true; //
5202  // not able to check if there is only one axis entry
5203  bool isEquidistant = true;
5204  const Double_t firstBinWidth = axis.GetBinWidth(1);
5205  for (int i = 1; i < axis.GetNbins(); ++i) {
5206  const Double_t binWidth = axis.GetBinWidth(i);
5207  const bool match = TMath::AreEqualRel(firstBinWidth, binWidth, TMath::Limits<Double_t>::Epsilon());
5208  isEquidistant &= match;
5209  if (!match)
5210  break;
5211  }
5212  return isEquidistant;
5213 }
5214 
5215 ////////////////////////////////////////////////////////////////////////////////
5216 /// Same limits and bins.
5217 
5218 Bool_t TH1::SameLimitsAndNBins(const TAxis& axis1, const TAxis& axis2)
5219 {
5220  return axis1.GetNbins() == axis2.GetNbins()
5221  && axis1.GetXmin() == axis2.GetXmin()
5222  && axis1.GetXmax() == axis2.GetXmax();
5223 }
5224 
5225 ////////////////////////////////////////////////////////////////////////////////
5226 /// Finds new limits for the axis for the Merge function.
5227 /// returns false if the limits are incompatible
5228 
5229 Bool_t TH1::RecomputeAxisLimits(TAxis& destAxis, const TAxis& anAxis)
5230 {
5231  if (SameLimitsAndNBins(destAxis, anAxis))
5232  return kTRUE;
5233 
5234  if (!IsEquidistantBinning(destAxis) || !IsEquidistantBinning(anAxis))
5235  return kFALSE; // not equidistant user binning not supported
5236 
5237  Double_t width1 = destAxis.GetBinWidth(0);
5238  Double_t width2 = anAxis.GetBinWidth(0);
5239  if (width1 == 0 || width2 == 0)
5240  return kFALSE; // no binning not supported
5241 
5242  Double_t xmin = TMath::Min(destAxis.GetXmin(), anAxis.GetXmin());
5243  Double_t xmax = TMath::Max(destAxis.GetXmax(), anAxis.GetXmax());
5244  Double_t width = TMath::Max(width1, width2);
5245 
5246  // check the bin size
5247  if (!AlmostInteger(width/width1) || !AlmostInteger(width/width2))
5248  return kFALSE;
5249 
5250  // std::cout << "Find new limit using given axis " << anAxis.GetXmin() << " , " << anAxis.GetXmax() << " bin width " << width2 << std::endl;
5251  // std::cout << " and destination axis " << destAxis.GetXmin() << " , " << destAxis.GetXmax() << " bin width " << width1 << std::endl;
5252 
5253 
5254  // check the limits
5255  Double_t delta;
5256  delta = (destAxis.GetXmin() - xmin)/width1;
5257  if (!AlmostInteger(delta))
5258  xmin -= (TMath::Ceil(delta) - delta)*width1;
5259 
5260  delta = (anAxis.GetXmin() - xmin)/width2;
5261  if (!AlmostInteger(delta))
5262  xmin -= (TMath::Ceil(delta) - delta)*width2;
5263 
5264 
5265  delta = (destAxis.GetXmin() - xmin)/width1;
5266  if (!AlmostInteger(delta))
5267  return kFALSE;
5268 
5269 
5270  delta = (xmax - destAxis.GetXmax())/width1;
5271  if (!AlmostInteger(delta))
5272  xmax += (TMath::Ceil(delta) - delta)*width1;
5273 
5274 
5275  delta = (xmax - anAxis.GetXmax())/width2;
5276  if (!AlmostInteger(delta))
5277  xmax += (TMath::Ceil(delta) - delta)*width2;
5278 
5279 
5280  delta = (xmax - destAxis.GetXmax())/width1;
5281  if (!AlmostInteger(delta))
5282  return kFALSE;
5283 #ifdef DEBUG
5284  if (!AlmostInteger((xmax - xmin) / width)) { // unnecessary check
5285  printf("TH1::RecomputeAxisLimits - Impossible\n");
5286  return kFALSE;
5287  }
5288 #endif
5289 
5290 
5291  destAxis.Set(TMath::Nint((xmax - xmin)/width), xmin, xmax);
5292 
5293  //std::cout << "New re-computed axis : [ " << xmin << " , " << xmax << " ] width = " << width << " nbins " << destAxis.GetNbins() << std::endl;
5294 
5295  return kTRUE;
5296 }
5297 
5298 ////////////////////////////////////////////////////////////////////////////////
5299 /// Add all histograms in the collection to this histogram.
5300 /// This function computes the min/max for the x axis,
5301 /// compute a new number of bins, if necessary,
5302 /// add bin contents, errors and statistics.
5303 /// If all histograms have bin labels, bins with identical labels
5304 /// will be merged, no matter what their order is.
5305 /// If overflows are present and limits are different the function will fail.
5306 /// The function returns the total number of entries in the result histogram
5307 /// if the merge is successful, -1 otherwise.
5308 ///
5309 /// IMPORTANT remark. The axis x may have different number
5310 /// of bins and different limits, BUT the largest bin width must be
5311 /// a multiple of the smallest bin width and the upper limit must also
5312 /// be a multiple of the bin width.
5313 /// Example:
5314 ///
5315 /// ~~~ {.cpp}
5316 /// void atest() {
5317 /// TH1F *h1 = new TH1F("h1","h1",110,-110,0);
5318 /// TH1F *h2 = new TH1F("h2","h2",220,0,110);
5319 /// TH1F *h3 = new TH1F("h3","h3",330,-55,55);
5320 /// TRandom r;
5321 /// for (Int_t i=0;i<10000;i++) {
5322 /// h1->Fill(r.Gaus(-55,10));
5323 /// h2->Fill(r.Gaus(55,10));
5324 /// h3->Fill(r.Gaus(0,10));
5325 /// }
5326 ///
5327 /// TList *list = new TList;
5328 /// list->Add(h1);
5329 /// list->Add(h2);
5330 /// list->Add(h3);
5331 /// TH1F *h = (TH1F*)h1->Clone("h");
5332 /// h->Reset();
5333 /// h->Merge(list);
5334 /// h->Draw();
5335 /// }
5336 /// ~~~
5337 
5339 {
5340  if (!li) return 0;
5341  if (li->IsEmpty()) return (Long64_t) GetEntries();
5342 
5343  // use TH1Merger class
5344  TH1Merger merger(*this,*li);
5345  Bool_t ret = merger();
5346 
5347  return (ret) ? GetEntries() : -1;
5348 }
5349 
5350 
5351 ////////////////////////////////////////////////////////////////////////////////
5352 /// Performs the operation: this = this*c1*f1
5353 /// if errors are defined (see TH1::Sumw2), errors are also recalculated.
5354 ///
5355 /// Only bins inside the function range are recomputed.
5356 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5357 /// you should call Sumw2 before making this operation.
5358 /// This is particularly important if you fit the histogram after TH1::Multiply
5359 ///
5360 /// The function return kFALSE if the Multiply operation failed
5361 
5363 {
5364  if (!f1) {
5365  Error("Add","Attempt to multiply by a non-existing function");
5366  return kFALSE;
5367  }
5368 
5369  // delete buffer if it is there since it will become invalid
5370  if (fBuffer) BufferEmpty(1);
5371 
5372  Int_t nx = GetNbinsX() + 2; // normal bins + uf / of (cells)
5373  Int_t ny = GetNbinsY() + 2;
5374  Int_t nz = GetNbinsZ() + 2;
5375  if (fDimension < 2) ny = 1;
5376  if (fDimension < 3) nz = 1;
5377 
5378  // reset min-maximum
5379  SetMinimum();
5380  SetMaximum();
5381 
5382  // - Loop on bins (including underflows/overflows)
5383  Double_t xx[3];
5384  Double_t *params = 0;
5385  f1->InitArgs(xx,params);
5386 
5387  for (Int_t binz = 0; binz < nz; ++binz) {
5388  xx[2] = fZaxis.GetBinCenter(binz);
5389  for (Int_t biny = 0; biny < ny; ++biny) {
5390  xx[1] = fYaxis.GetBinCenter(biny);
5391  for (Int_t binx = 0; binx < nx; ++binx) {
5392  xx[0] = fXaxis.GetBinCenter(binx);
5393  if (!f1->IsInside(xx)) continue;
5395  Int_t bin = binx + nx * (biny + ny *binz);
5396  Double_t cu = c1*f1->EvalPar(xx);
5397  if (TF1::RejectedPoint()) continue;
5398  UpdateBinContent(bin, RetrieveBinContent(bin) * cu);
5399  if (fSumw2.fN) {
5400  fSumw2.fArray[bin] = cu * cu * GetBinErrorSqUnchecked(bin);
5401  }
5402  }
5403  }
5404  }
5405  ResetStats();
5406  return kTRUE;
5407 }
5408 
5409 ////////////////////////////////////////////////////////////////////////////////
5410 /// Multiply this histogram by h1.
5411 ///
5412 /// `this = this*h1`
5413 ///
5414 /// If errors of this are available (TH1::Sumw2), errors are recalculated.
5415 /// Note that if h1 has Sumw2 set, Sumw2 is automatically called for this
5416 /// if not already set.
5417 ///
5418 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5419 /// you should call Sumw2 before making this operation.
5420 /// This is particularly important if you fit the histogram after TH1::Multiply
5421 ///
5422 /// The function return kFALSE if the Multiply operation failed
5423 
5424 Bool_t TH1::Multiply(const TH1 *h1)
5425 {
5426  if (!h1) {
5427  Error("Multiply","Attempt to multiply by a non-existing histogram");
5428  return kFALSE;
5429  }
5430 
5431  // delete buffer if it is there since it will become invalid
5432  if (fBuffer) BufferEmpty(1);
5433 
5434  try {
5435  CheckConsistency(this,h1);
5436  } catch(DifferentNumberOfBins&) {
5437  Error("Multiply","Attempt to multiply histograms with different number of bins");
5438  return kFALSE;
5439  } catch(DifferentAxisLimits&) {
5440  Warning("Multiply","Attempt to multiply histograms with different axis limits");
5441  } catch(DifferentBinLimits&) {
5442  Warning("Multiply","Attempt to multiply histograms with different bin limits");
5443  } catch(DifferentLabels&) {
5444  Warning("Multiply","Attempt to multiply histograms with different labels");
5445  }
5446 
5447  // Create Sumw2 if h1 has Sumw2 set
5448  if (fSumw2.fN == 0 && h1->GetSumw2N() != 0) Sumw2();
5449 
5450  // - Reset min- maximum
5451  SetMinimum();
5452  SetMaximum();
5453 
5454  // - Loop on bins (including underflows/overflows)
5455  for (Int_t i = 0; i < fNcells; ++i) {
5456  Double_t c0 = RetrieveBinContent(i);
5457  Double_t c1 = h1->RetrieveBinContent(i);
5458  UpdateBinContent(i, c0 * c1);
5459  if (fSumw2.fN) {
5460  fSumw2.fArray[i] = GetBinErrorSqUnchecked(i) * c1 * c1 + h1->GetBinErrorSqUnchecked(i) * c0 * c0;
5461  }
5462  }
5463  ResetStats();
5464  return kTRUE;
5465 }
5466 
5467 ////////////////////////////////////////////////////////////////////////////////
5468 /// Replace contents of this histogram by multiplication of h1 by h2.
5469 ///
5470 /// `this = (c1*h1)*(c2*h2)`
5471 ///
5472 /// If errors of this are available (TH1::Sumw2), errors are recalculated.
5473 /// Note that if h1 or h2 have Sumw2 set, Sumw2 is automatically called for this
5474 /// if not already set.
5475 ///
5476 /// IMPORTANT NOTE: If you intend to use the errors of this histogram later
5477 /// you should call Sumw2 before making this operation.
5478 /// This is particularly important if you fit the histogram after TH1::Multiply
5479 ///
5480 /// The function return kFALSE if the Multiply operation failed
5481 
5482 Bool_t TH1::Multiply(const TH1 *h1, const TH1 *h2, Double_t c1, Double_t c2, Option_t *option)
5483 {
5484  TString opt = option;
5485  opt.ToLower();
5486  // Bool_t binomial = kFALSE;
5487  // if (opt.Contains("b")) binomial = kTRUE;
5488  if (!h1 || !h2) {
5489  Error("Multiply","Attempt to multiply by a non-existing histogram");
5490  return kFALSE;
5491  }
5492 
5493  // delete buffer if it is there since it will become invalid
5494  if (fBuffer) BufferEmpty(1);
5495 
5496  try {
5497  CheckConsistency(h1,h2);
5498  CheckConsistency(this,h1);
5499  } catch(DifferentNumberOfBins&) {
5500  Error("Multiply","Attempt to multiply histograms with different number of bins");
5501  return kFALSE;
5502  } catch(DifferentAxisLimits&) {
5503  Warning("Multiply","Attempt to multiply histograms with different axis limits");
5504  } catch(DifferentBinLimits&) {
5505  Warning("Multiply","Attempt to multiply histograms with different bin limits");
5506  } catch(DifferentLabels&) {
5507  Warning("Multiply","Attempt to multiply histograms with different labels");
5508  }
5509 
5510  // Create Sumw2 if h1 or h2 have Sumw2 set
5511  if (fSumw2.fN == 0 && (h1->GetSumw2N() != 0 || h2->GetSumw2N() != 0)) Sumw2();
5512 
5513  // - Reset min - maximum
5514  SetMinimum();
5515  SetMaximum();
5516 
5517  // - Loop on bins (including underflows/overflows)
5518  Double_t c1sq = c1 * c1; Double_t c2sq = c2 * c2;
5519  for (Int_t i = 0; i < fNcells; ++i) {
5520  Double_t b1 = h1->RetrieveBinContent(i);
5521  Double_t b2 = h2->RetrieveBinContent(i);
5522  UpdateBinContent(i, c1 * b1 * c2 * b2);
5523  if (fSumw2.fN) {
5524  fSumw2.fArray[i] = c1sq * c2sq * (h1->GetBinErrorSqUnchecked(i) * b2 * b2 + h2->GetBinErrorSqUnchecked(i) * b1 * b1);
5525  }
5526  }
5527  ResetStats();
5528  return kTRUE;
5529 }
5530 
5531 ////////////////////////////////////////////////////////////////////////////////
5532 /// Control routine to paint any kind of histograms.
5533 ///
5534 /// This function is automatically called by TCanvas::Update.
5535 /// (see TH1::Draw for the list of options)
5536 
5537 void TH1::Paint(Option_t *option)
5538 {
5539  GetPainter(option);
5540 
5541  if (fPainter) {
5542  if (strlen(option) > 0) fPainter->Paint(option);
5543  else fPainter->Paint(fOption.Data());
5544  }
5545 }
5546 
5547 ////////////////////////////////////////////////////////////////////////////////
5548 /// Rebin this histogram
5549 ///
5550 /// #### case 1 xbins=0
5551 ///
5552 /// If newname is blank (default), the current histogram is modified and
5553 /// a pointer to it is returned.
5554 ///
5555 /// If newname is not blank, the current histogram is not modified, and a
5556 /// new histogram is returned which is a Clone of the current histogram
5557 /// with its name set to newname.
5558 ///
5559 /// The parameter ngroup indicates how many bins of this have to be merged
5560 /// into one bin of the result.
5561 ///
5562 /// If the original histogram has errors stored (via Sumw2), the resulting
5563 /// histograms has new errors correctly calculated.
5564 ///
5565 /// examples: if h1 is an existing TH1F histogram with 100 bins
5566 ///
5567 /// ~~~ {.cpp}
5568 /// h1->Rebin(); //merges two bins in one in h1: previous contents of h1 are lost
5569 /// h1->Rebin(5); //merges five bins in one in h1
5570 /// TH1F *hnew = dynamic_cast<TH1F*>(h1->Rebin(5,"hnew")); // creates a new histogram hnew
5571 /// // merging 5 bins of h1 in one bin
5572 /// ~~~
5573 ///
5574 /// NOTE: If ngroup is not an exact divider of the number of bins,
5575 /// the top limit of the rebinned histogram is reduced
5576 /// to the upper edge of the last bin that can make a complete
5577 /// group. The remaining bins are added to the overflow bin.
5578 /// Statistics will be recomputed from the new bin contents.
5579 ///
5580 /// #### case 2 xbins!=0
5581 ///
5582 /// A new histogram is created (you should specify newname).
5583 /// The parameter ngroup is the number of variable size bins in the created histogram.
5584 /// The array xbins must contain ngroup+1 elements that represent the low-edges
5585 /// of the bins.
5586 /// If the original histogram has errors stored (via Sumw2), the resulting
5587 /// histograms has new errors correctly calculated.
5588 ///
5589 /// NOTE: The bin edges specified in xbins should correspond to bin edges
5590 /// in the original histogram. If a bin edge in the new histogram is
5591 /// in the middle of a bin in the original histogram, all entries in
5592 /// the split bin in the original histogram will be transfered to the
5593 /// lower of the two possible bins in the new histogram. This is
5594 /// probably not what you want.
5595 ///
5596 /// examples: if h1 is an existing TH1F histogram with 100 bins
5597 ///
5598 /// ~~~ {.cpp}
5599 /// Double_t xbins[25] = {...} array of low-edges (xbins[25] is the upper edge of last bin
5600 /// h1->Rebin(24,"hnew",xbins); //creates a new variable bin size histogram hnew
5601 /// ~~~
5602 
5603 TH1 *TH1::Rebin(Int_t ngroup, const char*newname, const Double_t *xbins)
5604 {
5605  Int_t nbins = fXaxis.GetNbins();
5606  Double_t xmin = fXaxis.GetXmin();
5607  Double_t xmax = fXaxis.GetXmax();
5608  if ((ngroup <= 0) || (ngroup > nbins)) {
5609  Error("Rebin", "Illegal value of ngroup=%d",ngroup);
5610  return 0;
5611  }
5612 
5613  if (fDimension > 1 || InheritsFrom(TProfile::Class())) {
5614  Error("Rebin", "Operation valid on 1-D histograms only");
5615  return 0;
5616  }
5617  if (!newname && xbins) {
5618  Error("Rebin","if xbins is specified, newname must be given");
5619  return 0;
5620  }
5621 
5622  Int_t newbins = nbins/ngroup;
5623  if (!xbins) {
5624  Int_t nbg = nbins/ngroup;
5625  if (nbg*ngroup != nbins) {
5626  Warning("Rebin", "ngroup=%d is not an exact divider of nbins=%d.",ngroup,nbins);
5627  }
5628  }
5629  else {
5630  // in the case that xbins is given (rebinning in variable bins), ngroup is
5631  // the new number of bins and number of grouped bins is not constant.
5632  // when looping for setting the contents for the new histogram we
5633  // need to loop on all bins of original histogram. Then set ngroup=nbins
5634  newbins = ngroup;
5635  ngroup = nbins;
5636  }
5637 
5638  // Save old bin contents into a new array
5639  Double_t entries = fEntries;
5640  Double_t *oldBins = new Double_t[nbins+2];
5641  Int_t bin, i;
5642  for (bin=0;bin<nbins+2;bin++) oldBins[bin] = RetrieveBinContent(bin);
5643  Double_t *oldErrors = 0;
5644  if (fSumw2.fN != 0) {
5645  oldErrors = new Double_t[nbins+2];
5646  for (bin=0;bin<nbins+2;bin++) oldErrors[bin] = GetBinError(bin);
5647  }
5648  // rebin will not include underflow/overflow if new axis range is larger than old axis range
5649  if (xbins) {
5650  if (xbins[0] < fXaxis.GetXmin() && oldBins[0] != 0 )
5651  Warning("Rebin","underflow entries will not be used when rebinning");
5652  if (xbins[newbins] > fXaxis.GetXmax() && oldBins[nbins+1] != 0 )
5653  Warning("Rebin","overflow entries will not be used when rebinning");
5654  }
5655 
5656 
5657  // create a clone of the old histogram if newname is specified
5658  TH1 *hnew = this;
5659  if ((newname && strlen(newname) > 0) || xbins) {
5660  hnew = (TH1*)Clone(newname);
5661  }
5662 
5663  //reset can extend bit to avoid an axis extension in SetBinContent
5664  UInt_t oldExtendBitMask = hnew->SetCanExtend(kNoAxis);
5665 
5666  // save original statistics
5667  Double_t stat[kNstat];
5668  GetStats(stat);
5669  bool resetStat = false;
5670  // change axis specs and rebuild bin contents array::RebinAx
5671  if(!xbins && (newbins*ngroup != nbins)) {
5672  xmax = fXaxis.GetBinUpEdge(newbins*ngroup);
5673  resetStat = true; //stats must be reset because top bins will be moved to overflow bin
5674  }
5675  // save the TAttAxis members (reset by SetBins)
5676  Int_t nDivisions = fXaxis.GetNdivisions();
5677  Color_t axisColor = fXaxis.GetAxisColor();
5678  Color_t labelColor = fXaxis.GetLabelColor();
5679  Style_t labelFont = fXaxis.GetLabelFont();
5680  Float_t labelOffset = fXaxis.GetLabelOffset();
5681  Float_t labelSize = fXaxis.GetLabelSize();
5682  Float_t tickLength = fXaxis.GetTickLength();
5683  Float_t titleOffset = fXaxis.GetTitleOffset();
5684  Float_t titleSize = fXaxis.GetTitleSize();
5685  Color_t titleColor = fXaxis.GetTitleColor();
5686  Style_t titleFont = fXaxis.GetTitleFont();
5687 
5688  if(!xbins && (fXaxis.GetXbins()->GetSize() > 0)){ // variable bin sizes
5689  Double_t *bins = new Double_t[newbins+1];
5690  for(i = 0; i <= newbins; ++i) bins[i] = fXaxis.GetBinLowEdge(1+i*ngroup);
5691  hnew->SetBins(newbins,bins); //this also changes errors array (if any)
5692  delete [] bins;
5693  } else if (xbins) {
5694  hnew->SetBins(newbins,xbins);
5695  } else {
5696  hnew->SetBins(newbins,xmin,xmax);
5697  }
5698 
5699  // Restore axis attributes
5700  fXaxis.SetNdivisions(nDivisions);
5701  fXaxis.SetAxisColor(axisColor);
5702  fXaxis.SetLabelColor(labelColor);
5703  fXaxis.SetLabelFont(labelFont);
5704  fXaxis.SetLabelOffset(labelOffset);
5705  fXaxis.SetLabelSize(labelSize);
5706  fXaxis.SetTickLength(tickLength);
5707  fXaxis.SetTitleOffset(titleOffset);
5708  fXaxis.SetTitleSize(titleSize);
5709  fXaxis.SetTitleColor(titleColor);
5710  fXaxis.SetTitleFont(titleFont);
5711 
5712  // copy merged bin contents (ignore under/overflows)
5713  // Start merging only once the new lowest edge is reached
5714  Int_t startbin = 1;
5715  const Double_t newxmin = hnew->GetXaxis()->GetBinLowEdge(1);
5716  while( fXaxis.GetBinCenter(startbin) < newxmin && startbin <= nbins ) {
5717  startbin++;
5718  }
5719  Int_t oldbin = startbin;
5720  Double_t binContent, binError;
5721  for (bin = 1;bin<=newbins;bin++) {
5722  binContent = 0;
5723  binError = 0;
5724  Int_t imax = ngroup;
5725  Double_t xbinmax = hnew->GetXaxis()->GetBinUpEdge(bin);
5726  for (i=0;i<ngroup;i++) {
5727  if( (oldbin+i > nbins) ||
5728  ( hnew != this && (fXaxis.GetBinCenter(oldbin+i) > xbinmax)) ) {
5729  imax = i;
5730  break;
5731  }
5732  binContent += oldBins[oldbin+i];
5733  if (oldErrors) binError += oldErrors[oldbin+i]*oldErrors[oldbin+i];
5734  }
5735  hnew->SetBinContent(bin,binContent);
5736  if (oldErrors) hnew->SetBinError(bin,TMath::Sqrt(binError));
5737  oldbin += imax;
5738  }
5739 
5740  // sum underflow and overflow contents until startbin
5741  binContent = 0;
5742  binError = 0;
5743  for (i = 0; i < startbin; ++i) {
5744  binContent += oldBins[i];
5745  if (oldErrors) binError += oldErrors[i]*oldErrors[i];
5746  }
5747  hnew->SetBinContent(0,binContent);
5748  if (oldErrors) hnew->SetBinError(0,TMath::Sqrt(binError));
5749  // sum overflow
5750  binContent = 0;
5751  binError = 0;
5752  for (i = oldbin; i <= nbins+1; ++i) {
5753  binContent += oldBins[i];
5754  if (oldErrors) binError += oldErrors[i]*oldErrors[i];
5755  }
5756  hnew->SetBinContent(newbins+1,binContent);
5757  if (oldErrors) hnew->SetBinError(newbins+1,TMath::Sqrt(binError));
5758 
5759  hnew->SetCanExtend(oldExtendBitMask); // restore previous state
5760 
5761  // restore statistics and entries modified by SetBinContent
5762  hnew->SetEntries(entries);
5763  if (!resetStat) hnew->PutStats(stat);
5764  delete [] oldBins;
5765  if (oldErrors) delete [] oldErrors;
5766  return hnew;
5767 }
5768 
5769 ////////////////////////////////////////////////////////////////////////////////
5770 /// finds new limits for the axis so that *point* is within the range and
5771 /// the limits are compatible with the previous ones (see TH1::Merge).
5772 /// new limits are put into *newMin* and *newMax* variables.
5773 /// axis - axis whose limits are to be recomputed
5774 /// point - point that should fit within the new axis limits
5775 /// newMin - new minimum will be stored here
5776 /// newMax - new maximum will be stored here.
5777 /// false if failed (e.g. if the initial axis limits are wrong
5778 /// or the new range is more than \f$ 2^{64} \f$ times the old one).
5779 
5780 Bool_t TH1::FindNewAxisLimits(const TAxis* axis, const Double_t point, Double_t& newMin, Double_t &newMax)
5781 {
5782  Double_t xmin = axis->GetXmin();
5783  Double_t xmax = axis->GetXmax();
5784  if (xmin >= xmax) return kFALSE;
5785  Double_t range = xmax-xmin;
5786  Double_t binsize = range / axis->GetNbins();
5787 
5788  //recompute new axis limits by doubling the current range
5789  Int_t ntimes = 0;
5790  while (point < xmin) {
5791  if (ntimes++ > 64)
5792  return kFALSE;
5793  xmin = xmin - range;
5794  range *= 2;
5795  binsize *= 2;
5796  // // make sure that the merging will be correct
5797  // if ( xmin / binsize - TMath::Floor(xmin / binsize) >= 0.5) {
5798  // xmin += 0.5 * binsize;
5799  // xmax += 0.5 * binsize; // won't work with a histogram with only one bin, but I don't care
5800  // }
5801  }
5802  while (point >= xmax) {
5803  if (ntimes++ > 64)
5804  return kFALSE;
5805  xmax = xmax + range;
5806  range *= 2;
5807  binsize *= 2;
5808  // // make sure that the merging will be correct
5809  // if ( xmin / binsize - TMath::Floor(xmin / binsize) >= 0.5) {
5810  // xmin -= 0.5 * binsize;
5811  // xmax -= 0.5 * binsize; // won't work with a histogram with only one bin, but I don't care
5812  // }
5813  }
5814  newMin = xmin;
5815  newMax = xmax;
5816  // Info("FindNewAxisLimits", "OldAxis: (%lf, %lf), new: (%lf, %lf), point: %lf",
5817  // axis->GetXmin(), axis->GetXmax(), xmin, xmax, point);
5818 
5819  return kTRUE;
5820 }
5821 
5822 ////////////////////////////////////////////////////////////////////////////////
5823 /// Histogram is resized along axis such that x is in the axis range.
5824 /// The new axis limits are recomputed by doubling iteratively
5825 /// the current axis range until the specified value x is within the limits.
5826 /// The algorithm makes a copy of the histogram, then loops on all bins
5827 /// of the old histogram to fill the extended histogram.
5828 /// Takes into account errors (Sumw2) if any.
5829 /// The algorithm works for 1-d, 2-D and 3-D histograms.
5830 /// The axis must be extendable before invoking this function.
5831 /// Ex:
5832 ///
5833 /// ~~~ {.cpp}
5834 /// h->GetXaxis()->SetCanExtend(kTRUE);
5835 /// ~~~
5836 
5837 void TH1::ExtendAxis(Double_t x, TAxis *axis)
5838 {
5839  if (!axis->CanExtend()) return;
5840  if (TMath::IsNaN(x)) { // x may be a NaN
5842  return;
5843  }
5844 
5845  if (axis->GetXmin() >= axis->GetXmax()) return;
5846  if (axis->GetNbins() <= 0) return;
5847 
5848  Double_t xmin, xmax;
5849  if (!FindNewAxisLimits(axis, x, xmin, xmax))
5850  return;
5851 
5852  //save a copy of this histogram
5853  TH1 *hold = (TH1*)IsA()->New();
5854  hold->SetDirectory(0);
5855  Copy(*hold);
5856  //set new axis limits
5857  axis->SetLimits(xmin,xmax);
5858 
5859 
5860  //now loop on all bins and refill
5861  Int_t errors = GetSumw2N();
5862 
5863  Reset("ICE"); //reset only Integral, contents and Errors
5864 
5865  int iaxis = 0;
5866  if (axis == &fXaxis) iaxis = 1;
5867  if (axis == &fYaxis) iaxis = 2;
5868  if (axis == &fZaxis) iaxis = 3;
5869  bool firstw = kTRUE;
5870  Int_t binx,biny, binz = 0;
5871  Int_t ix = 0,iy = 0,iz = 0;
5872  Double_t bx,by,bz;
5873  Int_t ncells = hold->GetNcells();
5874  for (Int_t bin = 0; bin < ncells; ++bin) {
5875  hold->GetBinXYZ(bin,binx,biny,binz);
5876  bx = hold->GetXaxis()->GetBinCenter(binx);
5877  ix = fXaxis.FindFixBin(bx);
5878  if (fDimension > 1) {
5879  by = hold->GetYaxis()->GetBinCenter(biny);
5880  iy = fYaxis.FindFixBin(by);
5881  if (fDimension > 2) {
5882  bz = hold->GetZaxis()->GetBinCenter(binz);
5883  iz = fZaxis.FindFixBin(bz);
5884  }
5885  }
5886  // exclude underflow/overflow
5887  double content = hold->RetrieveBinContent(bin);
5888  if (content == 0) continue;
5889  if (IsBinUnderflow(bin,iaxis) || IsBinOverflow(bin,iaxis) ) {
5890  if (firstw) {
5891  Warning("ExtendAxis","Histogram %s has underflow or overflow in the axis that is extendable"
5892  " their content will be lost",GetName() );
5893  firstw= kFALSE;
5894  }
5895  continue;
5896  }
5897  Int_t ibin= GetBin(ix,iy,iz);
5898  AddBinContent(ibin, content);
5899  if (errors) {
5900  fSumw2.fArray[ibin] += hold->GetBinErrorSqUnchecked(bin);
5901  }
5902  }
5903  delete hold;
5904 }
5905 
5906 ////////////////////////////////////////////////////////////////////////////////
5907 /// Recursively remove object from the list of functions
5908 
5909 void TH1::RecursiveRemove(TObject *obj)
5910 {
5911  if (fFunctions) {
5913  }
5914 }
5915 
5916 ////////////////////////////////////////////////////////////////////////////////
5917 /// Multiply this histogram by a constant c1.
5918 ///
5919 /// `this = c1*this`
5920 ///
5921 /// Note that both contents and errors(if any) are scaled.
5922 /// This function uses the services of TH1::Add
5923 ///
5924 /// IMPORTANT NOTE: Sumw2() is called automatically when scaling
5925 /// If you are not interested in the histogram statistics you can call
5926 /// Sumw2(off) or use the option "nosw2"
5927 ///
5928 /// One can scale an histogram such that the bins integral is equal to
5929 /// the normalization parameter via TH1::Scale(Double_t norm), where norm
5930 /// is the desired normalization divided by the integral of the histogram.
5931 ///
5932 /// If option contains "width" the bin contents and errors are divided
5933 /// by the bin width.
5934 
5935 void TH1::Scale(Double_t c1, Option_t *option)
5936 {
5938  TString opt = option; opt.ToLower();
5939  // store bin errors when scaling since cannot anymore be computed as sqrt(N)
5940  if (!opt.Contains("nosw2") && GetSumw2N() == 0) Sumw2();
5941  if (opt.Contains("width")) Add(this, this, c1, -1);
5942  else {
5943  if (fBuffer) BufferEmpty(1);
5944  for(Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, c1 * RetrieveBinContent(i));
5945  if (fSumw2.fN) for(Int_t i = 0; i < fNcells; ++i) fSumw2.fArray[i] *= (c1 * c1); // update errors
5946  SetMinimum(); SetMaximum(); // minimum and maximum value will be recalculated the next time
5947  }
5948 
5949  // if contours set, must also scale contours
5950  Int_t ncontours = GetContour();
5951  if (ncontours == 0) return;
5952  Double_t* levels = fContour.GetArray();
5953  for (Int_t i = 0; i < ncontours; ++i) levels[i] *= c1;
5954 }
5955 
5956 ////////////////////////////////////////////////////////////////////////////////
5957 /// Returns true if all axes are extendable.
5958 
5960 {
5961  Bool_t canExtend = fXaxis.CanExtend();
5962  if (GetDimension() > 1) canExtend &= fYaxis.CanExtend();
5963  if (GetDimension() > 2) canExtend &= fZaxis.CanExtend();
5964 
5965  return canExtend;
5966 }
5967 
5968 ////////////////////////////////////////////////////////////////////////////////
5969 /// Make the histogram axes extendable / not extendable according to the bit mask
5970 /// returns the previous bit mask specifying which axes are extendable
5971 
5972 UInt_t TH1::SetCanExtend(UInt_t extendBitMask)
5973 {
5974  UInt_t oldExtendBitMask = kNoAxis;
5975 
5976  if (fXaxis.CanExtend()) oldExtendBitMask |= kXaxis;
5977  if (extendBitMask & kXaxis) fXaxis.SetCanExtend(kTRUE);
5978  else fXaxis.SetCanExtend(kFALSE);
5979 
5980  if (GetDimension() > 1) {
5981  if (fYaxis.CanExtend()) oldExtendBitMask |= kYaxis;
5982  if (extendBitMask & kYaxis) fYaxis.SetCanExtend(kTRUE);
5983  else fYaxis.SetCanExtend(kFALSE);
5984  }
5985 
5986  if (GetDimension() > 2) {
5987  if (fZaxis.CanExtend()) oldExtendBitMask |= kZaxis;
5988  if (extendBitMask & kZaxis) fZaxis.SetCanExtend(kTRUE);
5989  else fZaxis.SetCanExtend(kFALSE);
5990  }
5991 
5992  return oldExtendBitMask;
5993 }
5994 
5995 ////////////////////////////////////////////////////////////////////////////////
5996 /// Static function to set the default buffer size for automatic histograms.
5997 /// When an histogram is created with one of its axis lower limit greater
5998 /// or equal to its upper limit, the function SetBuffer is automatically
5999 /// called with the default buffer size.
6000 
6001 void TH1::SetDefaultBufferSize(Int_t buffersize)
6002 {
6003  fgBufferSize = buffersize > 0 ? buffersize : 0;
6004 }
6005 
6006 ////////////////////////////////////////////////////////////////////////////////
6007 /// When this static function is called with `sumw2=kTRUE`, all new
6008 /// histograms will automatically activate the storage
6009 /// of the sum of squares of errors, ie TH1::Sumw2 is automatically called.
6010 
6011 void TH1::SetDefaultSumw2(Bool_t sumw2)
6012 {
6014 }
6015 
6016 ////////////////////////////////////////////////////////////////////////////////
6017 /// Change (i.e. set) the title
6018 ///
6019 /// if title is in the form `stringt;stringx;stringy;stringz`
6020 /// the histogram title is set to `stringt`, the x axis title to `stringx`,
6021 /// the y axis title to `stringy`, and the z axis title to `stringz`.
6022 ///
6023 /// To insert the character `;` in one of the titles, one should use `#;`
6024 /// or `#semicolon`.
6025 
6026 void TH1::SetTitle(const char *title)
6027 {
6028  fTitle = title;
6029  fTitle.ReplaceAll("#;",2,"#semicolon",10);
6030 
6031  // Decode fTitle. It may contain X, Y and Z titles
6032  TString str1 = fTitle, str2;
6033  Int_t isc = str1.Index(";");
6034  Int_t lns = str1.Length();
6035 
6036  if (isc >=0 ) {
6037  fTitle = str1(0,isc);
6038  str1 = str1(isc+1, lns);
6039  isc = str1.Index(";");
6040  if (isc >=0 ) {
6041  str2 = str1(0,isc);
6042  str2.ReplaceAll("#semicolon",10,";",1);
6043  fXaxis.SetTitle(str2.Data());
6044  lns = str1.Length();
6045  str1 = str1(isc+1, lns);
6046  isc = str1.Index(";");
6047  if (isc >=0 ) {
6048  str2 = str1(0,isc);
6049  str2.ReplaceAll("#semicolon",10,";",1);
6050  fYaxis.SetTitle(str2.Data());
6051  lns = str1.Length();
6052  str1 = str1(isc+1, lns);
6053  str1.ReplaceAll("#semicolon",10,";",1);
6054  fZaxis.SetTitle(str1.Data());
6055  } else {
6056  str1.ReplaceAll("#semicolon",10,";",1);
6057  fYaxis.SetTitle(str1.Data());
6058  }
6059  } else {
6060  str1.ReplaceAll("#semicolon",10,";",1);
6061  fXaxis.SetTitle(str1.Data());
6062  }
6063  }
6064 
6065  fTitle.ReplaceAll("#semicolon",10,";",1);
6066 
6067  if (gPad && TestBit(kMustCleanup)) gPad->Modified();
6068 }
6069 
6070 ////////////////////////////////////////////////////////////////////////////////
6071 /// Smooth array xx, translation of Hbook routine hsmoof.F
6072 /// based on algorithm 353QH twice presented by J. Friedman
6073 /// in Proc.of the 1974 CERN School of Computing, Norway, 11-24 August, 1974.
6074 
6075 void TH1::SmoothArray(Int_t nn, Double_t *xx, Int_t ntimes)
6076 {
6077  if (nn < 3 ) {
6078  ::Error("SmoothArray","Need at least 3 points for smoothing: n = %d",nn);
6079  return;
6080  }
6081 
6082  Int_t ii;
6083  Double_t hh[6] = {0,0,0,0,0,0};
6084 
6085  std::vector<double> yy(nn);
6086  std::vector<double> zz(nn);
6087  std::vector<double> rr(nn);
6088 
6089  for (Int_t pass=0;pass<ntimes;pass++) {
6090  // first copy original data into temp array
6091  std::copy(xx, xx+nn, zz.begin() );
6092 
6093  for (int noent = 0; noent < 2; ++noent) { // run algorithm two times
6094 
6095  // do 353 i.e. running median 3, 5, and 3 in a single loop
6096  for (int kk = 0; kk < 3; kk++) {
6097  std::copy(zz.begin(), zz.end(), yy.begin());
6098  int medianType = (kk != 1) ? 3 : 5;
6099  int ifirst = (kk != 1 ) ? 1 : 2;
6100  int ilast = (kk != 1 ) ? nn-1 : nn -2;
6101  //nn2 = nn - ik - 1;
6102  // do all elements beside the first and last point for median 3
6103  // and first two and last 2 for median 5
6104  for ( ii = ifirst; ii < ilast; ii++) {
6105  assert(ii - ifirst >= 0);
6106  for (int jj = 0; jj < medianType; jj++) {
6107  hh[jj] = yy[ii - ifirst + jj ];
6108  }
6109  zz[ii] = TMath::Median(medianType, hh);
6110  }
6111 
6112  if (kk == 0) { // first median 3
6113  // first point
6114  hh[0] = zz[1];
6115  hh[1] = zz[0];
6116  hh[2] = 3*zz[1] - 2*zz[2];
6117  zz[0] = TMath::Median(3, hh);
6118  // last point
6119  hh[0] = zz[nn - 2];
6120  hh[1] = zz[nn - 1];
6121  hh[2] = 3*zz[nn - 2] - 2*zz[nn - 3];
6122  zz[nn - 1] = TMath::Median(3, hh);
6123  }
6124 
6125  if (kk == 1) { // median 5
6126  for (ii = 0; ii < 3; ii++) {
6127  hh[ii] = yy[ii];
6128  }
6129  zz[1] = TMath::Median(3, hh);
6130  // last two points
6131  for (ii = 0; ii < 3; ii++) {
6132  hh[ii] = yy[nn - 3 + ii];
6133  }
6134  zz[nn - 2] = TMath::Median(3, hh);
6135  }
6136 
6137  }
6138 
6139  std::copy ( zz.begin(), zz.end(), yy.begin() );
6140 
6141  // quadratic interpolation for flat segments
6142  for (ii = 2; ii < (nn - 2); ii++) {
6143  if (zz[ii - 1] != zz[ii]) continue;
6144  if (zz[ii] != zz[ii + 1]) continue;
6145  hh[0] = zz[ii - 2] - zz[ii];
6146  hh[1] = zz[ii + 2] - zz[ii];
6147  if (hh[0] * hh[1] <= 0) continue;
6148  int jk = 1;
6149  if ( TMath::Abs(hh[1]) > TMath::Abs(hh[0]) ) jk = -1;
6150  yy[ii] = -0.5*zz[ii - 2*jk] + zz[ii]/0.75 + zz[ii + 2*jk] /6.;
6151  yy[ii + jk] = 0.5*(zz[ii + 2*jk] - zz[ii - 2*jk]) + zz[ii];
6152  }
6153 
6154  // running means
6155  //std::copy(zz.begin(), zz.end(), yy.begin());
6156  for (ii = 1; ii < nn - 1; ii++) {
6157  zz[ii] = 0.25*yy[ii - 1] + 0.5*yy[ii] + 0.25*yy[ii + 1];
6158  }
6159  zz[0] = yy[0];
6160  zz[nn - 1] = yy[nn - 1];
6161 
6162  if (noent == 0) {
6163 
6164  // save computed values
6165  std::copy(zz.begin(), zz.end(), rr.begin());
6166 
6167  // COMPUTE residuals
6168  for (ii = 0; ii < nn; ii++) {
6169  zz[ii] = xx[ii] - zz[ii];
6170  }
6171  }
6172 
6173  } // end loop on noent
6174 
6175 
6176  double xmin = TMath::MinElement(nn,xx);
6177  for (ii = 0; ii < nn; ii++) {
6178  if (xmin < 0) xx[ii] = rr[ii] + zz[ii];
6179  // make smoothing defined positive - not better using 0 ?
6180  else xx[ii] = TMath::Max((rr[ii] + zz[ii]),0.0 );
6181  }
6182  }
6183 }
6184 
6185 ////////////////////////////////////////////////////////////////////////////////
6186 /// Smooth bin contents of this histogram.
6187 /// if option contains "R" smoothing is applied only to the bins
6188 /// defined in the X axis range (default is to smooth all bins)
6189 /// Bin contents are replaced by their smooth values.
6190 /// Errors (if any) are not modified.
6191 /// the smoothing procedure is repeated ntimes (default=1)
6192 
6193 void TH1::Smooth(Int_t ntimes, Option_t *option)
6194 {
6195  if (fDimension != 1) {
6196  Error("Smooth","Smooth only supported for 1-d histograms");
6197  return;
6198  }
6199  Int_t nbins = fXaxis.GetNbins();
6200  if (nbins < 3) {
6201  Error("Smooth","Smooth only supported for histograms with >= 3 bins. Nbins = %d",nbins);
6202  return;
6203  }
6204 
6205  // delete buffer if it is there since it will become invalid
6206  if (fBuffer) BufferEmpty(1);
6207 
6208  Int_t firstbin = 1, lastbin = nbins;
6209  TString opt = option;
6210  opt.ToLower();
6211  if (opt.Contains("r")) {
6212  firstbin= fXaxis.GetFirst();
6213  lastbin = fXaxis.GetLast();
6214  }
6215  nbins = lastbin - firstbin + 1;
6216  Double_t *xx = new Double_t[nbins];
6217  Double_t nent = fEntries;
6218  Int_t i;
6219  for (i=0;i<nbins;i++) {
6220  xx[i] = RetrieveBinContent(i+firstbin);
6221  }
6222 
6223  TH1::SmoothArray(nbins,xx,ntimes);
6224 
6225  for (i=0;i<nbins;i++) {
6226  UpdateBinContent(i+firstbin,xx[i]);
6227  }
6228  fEntries = nent;
6229  delete [] xx;
6230 
6231  if (gPad) gPad->Modified();
6232 }
6233 
6234 ////////////////////////////////////////////////////////////////////////////////
6235 /// if flag=kTRUE, underflows and overflows are used by the Fill functions
6236 /// in the computation of statistics (mean value, StdDev).
6237 /// By default, underflows or overflows are not used.
6238 
6239 void TH1::StatOverflows(Bool_t flag)
6240 {
6242 }
6243 
6244 ////////////////////////////////////////////////////////////////////////////////
6245 /// Stream a class object.
6246 
6247 void TH1::Streamer(TBuffer &b)
6248 {
6249  if (b.IsReading()) {
6250  UInt_t R__s, R__c;
6251  Version_t R__v = b.ReadVersion(&R__s, &R__c);
6252  if (fDirectory) fDirectory->Remove(this);
6253  fDirectory = 0;
6254  if (R__v > 2) {
6255  b.ReadClassBuffer(TH1::Class(), this, R__v, R__s, R__c);
6256 
6258  fXaxis.SetParent(this);
6259  fYaxis.SetParent(this);
6260  fZaxis.SetParent(this);
6261  TIter next(fFunctions);
6262  TObject *obj;
6263  while ((obj=next())) {
6264  if (obj->InheritsFrom(TF1::Class())) ((TF1*)obj)->SetParent(this);
6265  }
6266  return;
6267  }
6268  //process old versions before automatic schema evolution
6269  TNamed::Streamer(b);
6270  TAttLine::Streamer(b);
6271  TAttFill::Streamer(b);
6272  TAttMarker::Streamer(b);
6273  b >> fNcells;
6274  fXaxis.Streamer(b);
6275  fYaxis.Streamer(b);
6276  fZaxis.Streamer(b);
6277  fXaxis.SetParent(this);
6278  fYaxis.SetParent(this);
6279  fZaxis.SetParent(this);
6280  b >> fBarOffset;
6281  b >> fBarWidth;
6282  b >> fEntries;
6283  b >> fTsumw;
6284  b >> fTsumw2;
6285  b >> fTsumwx;
6286  b >> fTsumwx2;
6287  if (R__v < 2) {
6288  Float_t maximum, minimum, norm;
6289  Float_t *contour=0;
6290  b >> maximum; fMaximum = maximum;
6291  b >> minimum; fMinimum = minimum;
6292  b >> norm; fNormFactor = norm;
6293  Int_t n = b.ReadArray(contour);
6294  fContour.Set(n);
6295  for (Int_t i=0;i<n;i++) fContour.fArray[i] = contour[i];
6296  delete [] contour;
6297  } else {
6298  b >> fMaximum;
6299  b >> fMinimum;
6300  b >> fNormFactor;
6301  fContour.Streamer(b);
6302  }
6303  fSumw2.Streamer(b);
6304  fOption.Streamer(b);
6305  fFunctions->Delete();
6306  fFunctions->Streamer(b);
6307  b.CheckByteCount(R__s, R__c, TH1::IsA());
6308 
6309  } else {
6310  b.WriteClassBuffer(TH1::Class(),this);
6311  }
6312 }
6313 
6314 ////////////////////////////////////////////////////////////////////////////////
6315 /// Print some global quantities for this histogram.
6316 /// \param[in] option
6317 /// - "base" is given, number of bins and ranges are also printed
6318 /// - "range" is given, bin contents and errors are also printed
6319 /// for all bins in the current range (default 1-->nbins)
6320 /// - "all" is given, bin contents and errors are also printed
6321 /// for all bins including under and overflows.
6322 
6323 void TH1::Print(Option_t *option) const
6324 {
6325  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
6326  printf( "TH1.Print Name = %s, Entries= %d, Total sum= %g\n",GetName(),Int_t(fEntries),GetSumOfWeights());
6327  TString opt = option;
6328  opt.ToLower();
6329  Int_t all;
6330  if (opt.Contains("all")) all = 0;
6331  else if (opt.Contains("range")) all = 1;
6332  else if (opt.Contains("base")) all = 2;
6333  else return;
6334 
6335  Int_t bin, binx, biny, binz;
6336  Int_t firstx=0,lastx=0,firsty=0,lasty=0,firstz=0,lastz=0;
6337  if (all == 0) {
6338  lastx = fXaxis.GetNbins()+1;
6339  if (fDimension > 1) lasty = fYaxis.GetNbins()+1;
6340  if (fDimension > 2) lastz = fZaxis.GetNbins()+1;
6341  } else {
6342  firstx = fXaxis.GetFirst(); lastx = fXaxis.GetLast();
6343  if (fDimension > 1) {firsty = fYaxis.GetFirst(); lasty = fYaxis.GetLast();}
6344  if (fDimension > 2) {firstz = fZaxis.GetFirst(); lastz = fZaxis.GetLast();}
6345  }
6346 
6347  if (all== 2) {
6348  printf(" Title = %s\n", GetTitle());
6349  printf(" NbinsX= %d, xmin= %g, xmax=%g", fXaxis.GetNbins(), fXaxis.GetXmin(), fXaxis.GetXmax());
6350  if( fDimension > 1) printf(", NbinsY= %d, ymin= %g, ymax=%g", fYaxis.GetNbins(), fYaxis.GetXmin(), fYaxis.GetXmax());
6351  if( fDimension > 2) printf(", NbinsZ= %d, zmin= %g, zmax=%g", fZaxis.GetNbins(), fZaxis.GetXmin(), fZaxis.GetXmax());
6352  printf("\n");
6353  return;
6354  }
6355 
6356  Double_t w,e;
6357  Double_t x,y,z;
6358  if (fDimension == 1) {
6359  for (binx=firstx;binx<=lastx;binx++) {
6360  x = fXaxis.GetBinCenter(binx);
6361  w = RetrieveBinContent(binx);
6362  e = GetBinError(binx);
6363  if(fSumw2.fN) printf(" fSumw[%d]=%g, x=%g, error=%g\n",binx,w,x,e);
6364  else printf(" fSumw[%d]=%g, x=%g\n",binx,w,x);
6365  }
6366  }
6367  if (fDimension == 2) {
6368  for (biny=firsty;biny<=lasty;biny++) {
6369  y = fYaxis.GetBinCenter(biny);
6370  for (binx=firstx;binx<=lastx;binx++) {
6371  bin = GetBin(binx,biny);
6372  x = fXaxis.GetBinCenter(binx);
6373  w = RetrieveBinContent(bin);
6374  e = GetBinError(bin);
6375  if(fSumw2.fN) printf(" fSumw[%d][%d]=%g, x=%g, y=%g, error=%g\n",binx,biny,w,x,y,e);
6376  else printf(" fSumw[%d][%d]=%g, x=%g, y=%g\n",binx,biny,w,x,y);
6377  }
6378  }
6379  }
6380  if (fDimension == 3) {
6381  for (binz=firstz;binz<=lastz;binz++) {
6382  z = fZaxis.GetBinCenter(binz);
6383  for (biny=firsty;biny<=lasty;biny++) {
6384  y = fYaxis.GetBinCenter(biny);
6385  for (binx=firstx;binx<=lastx;binx++) {
6386  bin = GetBin(binx,biny,binz);
6387  x = fXaxis.GetBinCenter(binx);
6388  w = RetrieveBinContent(bin);
6389  e = GetBinError(bin);
6390  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);
6391  else printf(" fSumw[%d][%d][%d]=%g, x=%g, y=%g, z=%g\n",binx,biny,binz,w,x,y,z);
6392  }
6393  }
6394  }
6395  }
6396 }
6397 
6398 ////////////////////////////////////////////////////////////////////////////////
6399 /// Using the current bin info, recompute the arrays for contents and errors
6400 
6401 void TH1::Rebuild(Option_t *)
6402 {
6404  if (fSumw2.fN) {
6405  fSumw2.Set(fNcells);
6406  }
6407 }
6408 
6409 ////////////////////////////////////////////////////////////////////////////////
6410 /// Reset this histogram: contents, errors, etc.
6411 /// \param[in] option
6412 /// - "ICE" is specified, resets only Integral, Contents and Errors.
6413 /// - "ICES" is specified, resets only Integral, Contents , Errors and Statistics
6414 /// This option is used
6415 /// - "M" is specified, resets also Minimum and Maximum
6416 
6417 void TH1::Reset(Option_t *option)
6418 {
6419  // The option "ICE" is used when extending the histogram (in ExtendAxis, LabelInflate, etc..)
6420  // The option "ICES is used in combination with the buffer (see BufferEmpty and BufferFill)
6421 
6422  TString opt = option;
6423  opt.ToUpper();
6424  fSumw2.Reset();
6425  if (fIntegral) {delete [] fIntegral; fIntegral = 0;}
6426 
6427  if (opt.Contains("M")) {
6428  SetMinimum();
6429  SetMaximum();
6430  }
6431 
6432  if (opt.Contains("ICE") && !opt.Contains("S")) return;
6433 
6434  // Setting fBuffer[0] = 0 is like resetting the buffer but not deleting it
6435  // But what is the sense of calling BufferEmpty() ? For making the axes ?
6436  // BufferEmpty will update contents that later will be
6437  // reset in calling TH1D::Reset. For this we need to reset the stats afterwards
6438  // It may be needed for computing the axis limits....
6439  if (fBuffer) {BufferEmpty(); fBuffer[0] = 0;}
6440 
6441  // need to reset also the statistics
6442  // (needs to be done after calling BufferEmpty() )
6443  fTsumw = 0;
6444  fTsumw2 = 0;
6445  fTsumwx = 0;
6446  fTsumwx2 = 0;
6447  fEntries = 0;
6448 
6449  if (opt == "ICES") return;
6450 
6451 
6452  TObject *stats = fFunctions->FindObject("stats");
6453  fFunctions->Remove(stats);
6454  //special logic to support the case where the same object is
6455  //added multiple times in fFunctions.
6456  //This case happens when the same object is added with different
6457  //drawing modes
6458  TObject *obj;
6459  while ((obj = fFunctions->First())) {
6460  while(fFunctions->Remove(obj)) { }
6461  delete obj;
6462  }
6463  if(stats) fFunctions->Add(stats);
6464  fContour.Set(0);
6465 }
6466 
6467 ////////////////////////////////////////////////////////////////////////////////
6468 /// Save primitive as a C++ statement(s) on output stream out
6469 
6470 void TH1::SavePrimitive(std::ostream &out, Option_t *option /*= ""*/)
6471 {
6472  // empty the buffer before if it exists
6473  if (fBuffer) BufferEmpty();
6474 
6475  Bool_t nonEqiX = kFALSE;
6476  Bool_t nonEqiY = kFALSE;
6477  Bool_t nonEqiZ = kFALSE;
6478  Int_t i;
6479  static Int_t nxaxis = 0;
6480  static Int_t nyaxis = 0;
6481  static Int_t nzaxis = 0;
6482  TString sxaxis="xAxis",syaxis="yAxis",szaxis="zAxis";
6483 
6484  // Check if the histogram has equidistant X bins or not. If not, we
6485  // create an array holding the bins.
6486  if (GetXaxis()->GetXbins()->fN && GetXaxis()->GetXbins()->fArray) {
6487  nonEqiX = kTRUE;
6488  nxaxis++;
6489  sxaxis += nxaxis;
6490  out << " Double_t "<<sxaxis<<"[" << GetXaxis()->GetXbins()->fN
6491  << "] = {";
6492  for (i = 0; i < GetXaxis()->GetXbins()->fN; i++) {
6493  if (i != 0) out << ", ";
6494  out << GetXaxis()->GetXbins()->fArray[i];
6495  }
6496  out << "}; " << std::endl;
6497  }
6498  // If the histogram is 2 or 3 dimensional, check if the histogram
6499  // has equidistant Y bins or not. If not, we create an array
6500  // holding the bins.
6501  if (fDimension > 1 && GetYaxis()->GetXbins()->fN &&
6502  GetYaxis()->GetXbins()->fArray) {
6503  nonEqiY = kTRUE;
6504  nyaxis++;
6505  syaxis += nyaxis;
6506  out << " Double_t "<<syaxis<<"[" << GetYaxis()->GetXbins()->fN
6507  << "] = {";
6508  for (i = 0; i < GetYaxis()->GetXbins()->fN; i++) {
6509  if (i != 0) out << ", ";
6510  out << GetYaxis()->GetXbins()->fArray[i];
6511  }
6512  out << "}; " << std::endl;
6513  }
6514  // IF the histogram is 3 dimensional, check if the histogram
6515  // has equidistant Z bins or not. If not, we create an array
6516  // holding the bins.
6517  if (fDimension > 2 && GetZaxis()->GetXbins()->fN &&
6518  GetZaxis()->GetXbins()->fArray) {
6519  nonEqiZ = kTRUE;
6520  nzaxis++;
6521  szaxis += nzaxis;
6522  out << " Double_t "<<szaxis<<"[" << GetZaxis()->GetXbins()->fN
6523  << "] = {";
6524  for (i = 0; i < GetZaxis()->GetXbins()->fN; i++) {
6525  if (i != 0) out << ", ";
6526  out << GetZaxis()->GetXbins()->fArray[i];
6527  }
6528  out << "}; " << std::endl;
6529  }
6530 
6531  char quote = '"';
6532  out <<" "<<std::endl;
6533  out <<" "<< ClassName() <<" *";
6534 
6535  // Histogram pointer has by default the histogram name with an incremental suffix.
6536  // If the histogram belongs to a graph or a stack the suffix is not added because
6537  // the graph and stack objects are not aware of this new name. Same thing if
6538  // the histogram is drawn with the option COLZ because the TPaletteAxis drawn
6539  // when this option is selected, does not know this new name either.
6540  TString opt = option;
6541  opt.ToLower();
6542  static Int_t hcounter = 0;
6543  TString histName = GetName();
6544  if ( !histName.Contains("Graph")
6545  && !histName.Contains("_stack_")
6546  && !opt.Contains("colz")) {
6547  hcounter++;
6548  histName += "__";
6549  histName += hcounter;
6550  }
6551  histName = gInterpreter-> MapCppName(histName);
6552  const char *hname = histName.Data();
6553  if (!strlen(hname)) hname = "unnamed";
6554  TString savedName = GetName();
6555  this->SetName(hname);
6556  TString t(GetTitle());
6557  t.ReplaceAll("\\","\\\\");
6558  t.ReplaceAll("\"","\\\"");
6559  out << hname << " = new " << ClassName() << "(" << quote
6560  << hname << quote << "," << quote<< t.Data() << quote
6561  << "," << GetXaxis()->GetNbins();
6562  if (nonEqiX)
6563  out << ", "<<sxaxis;
6564  else
6565  out << "," << GetXaxis()->GetXmin()
6566  << "," << GetXaxis()->GetXmax();
6567  if (fDimension > 1) {
6568  out << "," << GetYaxis()->GetNbins();
6569  if (nonEqiY)
6570  out << ", "<<syaxis;
6571  else
6572  out << "," << GetYaxis()->GetXmin()
6573  << "," << GetYaxis()->GetXmax();
6574  }
6575  if (fDimension > 2) {
6576  out << "," << GetZaxis()->GetNbins();
6577  if (nonEqiZ)
6578  out << ", "<<szaxis;
6579  else
6580  out << "," << GetZaxis()->GetXmin()
6581  << "," << GetZaxis()->GetXmax();
6582  }
6583  out << ");" << std::endl;
6584 
6585  // save bin contents
6586  Int_t bin;
6587  for (bin=0;bin<fNcells;bin++) {
6588  Double_t bc = RetrieveBinContent(bin);
6589  if (bc) {
6590  out<<" "<<hname<<"->SetBinContent("<<bin<<","<<bc<<");"<<std::endl;
6591  }
6592  }
6593 
6594  // save bin errors
6595  if (fSumw2.fN) {
6596  for (bin=0;bin<fNcells;bin++) {
6597  Double_t be = GetBinError(bin);
6598  if (be) {
6599  out<<" "<<hname<<"->SetBinError("<<bin<<","<<be<<");"<<std::endl;
6600  }
6601  }
6602  }
6603 
6604  TH1::SavePrimitiveHelp(out, hname, option);
6605  this->SetName(savedName.Data());
6606 }
6607 
6608 ////////////////////////////////////////////////////////////////////////////////
6609 /// Helper function for the SavePrimitive functions from TH1
6610 /// or classes derived from TH1, eg TProfile, TProfile2D.
6611 
6612 void TH1::SavePrimitiveHelp(std::ostream &out, const char *hname, Option_t *option /*= ""*/)
6613 {
6614  char quote = '"';
6615  if (TMath::Abs(GetBarOffset()) > 1e-5) {
6616  out<<" "<<hname<<"->SetBarOffset("<<GetBarOffset()<<");"<<std::endl;
6617  }
6618  if (TMath::Abs(GetBarWidth()-1) > 1e-5) {
6619  out<<" "<<hname<<"->SetBarWidth("<<GetBarWidth()<<");"<<std::endl;
6620  }
6621  if (fMinimum != -1111) {
6622  out<<" "<<hname<<"->SetMinimum("<<fMinimum<<");"<<std::endl;
6623  }
6624  if (fMaximum != -1111) {
6625  out<<" "<<hname<<"->SetMaximum("<<fMaximum<<");"<<std::endl;
6626  }
6627  if (fNormFactor != 0) {
6628  out<<" "<<hname<<"->SetNormFactor("<<fNormFactor<<");"<<std::endl;
6629  }
6630  if (fEntries != 0) {
6631  out<<" "<<hname<<"->SetEntries("<<fEntries<<");"<<std::endl;
6632  }
6633  if (fDirectory == 0) {
6634  out<<" "<<hname<<"->SetDirectory(0);"<<std::endl;
6635  }
6636  if (TestBit(kNoStats)) {
6637  out<<" "<<hname<<"->SetStats(0);"<<std::endl;
6638  }
6639  if (fOption.Length() != 0) {
6640  out<<" "<<hname<<"->SetOption("<<quote<<fOption.Data()<<quote<<");"<<std::endl;
6641  }
6642 
6643  // save contour levels
6644  Int_t ncontours = GetContour();
6645  if (ncontours > 0) {
6646  out<<" "<<hname<<"->SetContour("<<ncontours<<");"<<std::endl;
6647  Double_t zlevel;
6648  for (Int_t bin=0;bin<ncontours;bin++) {
6649  if (gPad->GetLogz()) {
6650  zlevel = TMath::Power(10,GetContourLevel(bin));
6651  } else {
6652  zlevel = GetContourLevel(bin);
6653  }
6654  out<<" "<<hname<<"->SetContourLevel("<<bin<<","<<zlevel<<");"<<std::endl;
6655  }
6656  }
6657 
6658  // save list of functions
6660  TObject *obj;
6661  static Int_t funcNumber = 0;
6662  while (lnk) {
6663  obj = lnk->GetObject();
6664  obj->SavePrimitive(out,Form("nodraw #%d\n",++funcNumber));
6665  if (obj->InheritsFrom(TF1::Class())) {
6666  out<<" "<<hname<<"->GetListOfFunctions()->Add("
6667  <<Form("%s%d",obj->GetName(),funcNumber)<<");"<<std::endl;
6668  } else if (obj->InheritsFrom("TPaveStats")) {
6669  out<<" "<<hname<<"->GetListOfFunctions()->Add(ptstats);"<<std::endl;
6670  out<<" ptstats->SetParent("<<hname<<");"<<std::endl;
6671  } else {
6672  out<<" "<<hname<<"->GetListOfFunctions()->Add("
6673  <<obj->GetName()
6674  <<","<<quote<<lnk->GetOption()<<quote<<");"<<std::endl;
6675  }
6676  lnk = (TObjOptLink*)lnk->Next();
6677  }
6678 
6679  // save attributes
6680  SaveFillAttributes(out,hname,0,1001);
6681  SaveLineAttributes(out,hname,1,1,1);
6682  SaveMarkerAttributes(out,hname,1,1,1);
6683  fXaxis.SaveAttributes(out,hname,"->GetXaxis()");
6684  fYaxis.SaveAttributes(out,hname,"->GetYaxis()");
6685  fZaxis.SaveAttributes(out,hname,"->GetZaxis()");
6686  TString opt = option;
6687  opt.ToLower();
6688  if (!opt.Contains("nodraw")) {
6689  out<<" "<<hname<<"->Draw("
6690  <<quote<<option<<quote<<");"<<std::endl;
6691  }
6692 }
6693 
6694 ////////////////////////////////////////////////////////////////////////////////
6695 /// Copy current attributes from/to current style
6696 
6697 void TH1::UseCurrentStyle()
6698 {
6699  if (!gStyle) return;
6700  if (gStyle->IsReading()) {
6701  fXaxis.ResetAttAxis("X");
6702  fYaxis.ResetAttAxis("Y");
6703  fZaxis.ResetAttAxis("Z");
6714  Int_t dostat = gStyle->GetOptStat();
6715  if (gStyle->GetOptFit() && !dostat) dostat = 1000000001;
6716  SetStats(dostat);
6717  } else {
6729  }
6730  TIter next(GetListOfFunctions());
6731  TObject *obj;
6732 
6733  while ((obj = next())) {
6734  obj->UseCurrentStyle();
6735  }
6736 }
6737 
6738 ////////////////////////////////////////////////////////////////////////////////
6739 /// For axis = 1,2 or 3 returns the mean value of the histogram along
6740 /// X,Y or Z axis.
6741 ///
6742 /// For axis = 11, 12, 13 returns the standard error of the mean value
6743 /// of the histogram along X, Y or Z axis
6744 ///
6745 /// Note that the mean value/StdDev is computed using the bins in the currently
6746 /// defined range (see TAxis::SetRange). By default the range includes
6747 /// all bins from 1 to nbins included, excluding underflows and overflows.
6748 /// To force the underflows and overflows in the computation, one must
6749 /// call the static function TH1::StatOverflows(kTRUE) before filling
6750 /// the histogram.
6751 ///
6752 /// Return mean value of this histogram along the X axis.
6753 ///
6754 /// Note that the mean value/StdDev is computed using the bins in the currently
6755 /// defined range (see TAxis::SetRange). By default the range includes
6756 /// all bins from 1 to nbins included, excluding underflows and overflows.
6757 /// To force the underflows and overflows in the computation, one must
6758 /// call the static function TH1::StatOverflows(kTRUE) before filling
6759 /// the histogram.
6760 
6761 Double_t TH1::GetMean(Int_t axis) const
6762 {
6763  if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
6764  Double_t stats[kNstat];
6765  for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
6766  GetStats(stats);
6767  if (stats[0] == 0) return 0;
6768  if (axis<4){
6769  Int_t ax[3] = {2,4,7};
6770  return stats[ax[axis-1]]/stats[0];
6771  } else {
6772  // mean error = StdDev / sqrt( Neff )
6773  Double_t stddev = GetStdDev(axis-10);
6774  Double_t neff = GetEffectiveEntries();
6775  return ( neff > 0 ? stddev/TMath::Sqrt(neff) : 0. );
6776  }
6777 }
6778 
6779 ////////////////////////////////////////////////////////////////////////////////
6780 /// Return standard error of mean of this histogram along the X axis.
6781 ///
6782 /// Note that the mean value/StdDev is computed using the bins in the currently
6783 /// defined range (see TAxis::SetRange). By default the range includes
6784 /// all bins from 1 to nbins included, excluding underflows and overflows.
6785 /// To force the underflows and overflows in the computation, one must
6786 /// call the static function TH1::StatOverflows(kTRUE) before filling
6787 /// the histogram.
6788 ///
6789 /// Also note, that although the definition of standard error doesn't include the
6790 /// assumption of normality, many uses of this feature implicitly assume it.
6791 
6792 Double_t TH1::GetMeanError(Int_t axis) const
6793 {
6794  return GetMean(axis+10);
6795 }
6796 
6797 ////////////////////////////////////////////////////////////////////////////////
6798 /// Returns the Standard Deviation (Sigma).
6799 /// The Sigma estimate is computed as
6800 /// \f[
6801 /// \sqrt{\frac{1}{N}(\sum(x_i-x_{mean})^2)}
6802 /// \f]
6803 /// For axis = 1,2 or 3 returns the Sigma value of the histogram along
6804 /// X, Y or Z axis
6805 /// For axis = 11, 12 or 13 returns the error of StdDev estimation along
6806 /// X, Y or Z axis for Normal distribution
6807 ///
6808 /// Note that the mean value/sigma is computed using the bins in the currently
6809 /// defined range (see TAxis::SetRange). By default the range includes
6810 /// all bins from 1 to nbins included, excluding underflows and overflows.
6811 /// To force the underflows and overflows in the computation, one must
6812 /// call the static function TH1::StatOverflows(kTRUE) before filling
6813 /// the histogram.
6814 
6815 Double_t TH1::GetStdDev(Int_t axis) const
6816 {
6817  if (axis<1 || (axis>3 && axis<11) || axis>13) return 0;
6818 
6819  Double_t x, stddev2, stats[kNstat];
6820  for (Int_t i=4;i<kNstat;i++) stats[i] = 0;
6821  GetStats(stats);
6822  if (stats[0] == 0) return 0;
6823  Int_t ax[3] = {2,4,7};
6824  Int_t axm = ax[axis%10 - 1];
6825  x = stats[axm]/stats[0];
6826  stddev2 = TMath::Abs(stats[axm+1]/stats[0] -x*x);
6827  if (axis<10)
6828  return TMath::Sqrt(stddev2);
6829  else {
6830  // The right formula for StdDev error depends on 4th momentum (see Kendall-Stuart Vol 1 pag 243)
6831  // formula valid for only gaussian distribution ( 4-th momentum = 3 * sigma^4 )
6832  Double_t neff = GetEffectiveEntries();
6833  return ( neff > 0 ? TMath::Sqrt(stddev2/(2*neff) ) : 0. );
6834  }
6835 }
6836 
6837 ////////////////////////////////////////////////////////////////////////////////
6838 /// Return error of standard deviation estimation for Normal distribution
6839 ///
6840 /// Note that the mean value/StdDev is computed using the bins in the currently
6841 /// defined range (see TAxis::SetRange). By default the range includes
6842 /// all bins from 1 to nbins included, excluding underflows and overflows.
6843 /// To force the underflows and overflows in the computation, one must
6844 /// call the static function TH1::StatOverflows(kTRUE) before filling
6845 /// the histogram.
6846 ///
6847 /// Value returned is standard deviation of sample standard deviation.
6848 /// Note that it is an approximated value which is valid only in the case that the
6849 /// original data distribution is Normal. The correct one would require
6850 /// the 4-th momentum value, which cannot be accurately estimated from an histogram since
6851 /// the x-information for all entries is not kept.
6852 
6854 {
6855  return GetStdDev(axis+10);
6856 }
6857 
6858 ////////////////////////////////////////////////////////////////////////////////
6859 /// - For axis = 1, 2 or 3 returns skewness of the histogram along x, y or z axis.
6860 /// - For axis = 11, 12 or 13 returns the approximate standard error of skewness
6861 /// of the histogram along x, y or z axis
6862 ///
6863 ///Note, that since third and fourth moment are not calculated
6864 ///at the fill time, skewness and its standard error are computed bin by bin
6865 
6866 Double_t TH1::GetSkewness(Int_t axis) const
6867 {
6869  if (axis > 0 && axis <= 3){
6870 
6871  Double_t mean = GetMean(axis);
6872  Double_t stddev = GetStdDev(axis);
6873  Double_t stddev3 = stddev*stddev*stddev;
6874 
6875  Int_t firstBinX = fXaxis.GetFirst();
6876  Int_t lastBinX = fXaxis.GetLast();
6877  Int_t firstBinY = fYaxis.GetFirst();
6878  Int_t lastBinY = fYaxis.GetLast();
6879  Int_t firstBinZ = fZaxis.GetFirst();
6880  Int_t lastBinZ = fZaxis.GetLast();
6881  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
6882  if (fgStatOverflows) {
6883  if ( !fXaxis.TestBit(TAxis::kAxisRange) ) {
6884  if (firstBinX == 1) firstBinX = 0;
6885  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
6886  }
6887  if ( !fYaxis.TestBit(TAxis::kAxisRange) ) {
6888  if (firstBinY == 1) firstBinY = 0;
6889  if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
6890  }
6891  if ( !fZaxis.TestBit(TAxis::kAxisRange) ) {
6892  if (firstBinZ == 1) firstBinZ = 0;
6893  if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
6894  }
6895  }
6896 
6897  Double_t x = 0;
6898  Double_t sum=0;
6899  Double_t np=0;
6900  for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
6901  for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
6902  for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
6903  if (axis==1 ) x = fXaxis.GetBinCenter(binx);
6904  else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
6905  else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
6906  Double_t w = GetBinContent(binx,biny,binz);
6907  np+=w;
6908  sum+=w*(x-mean)*(x-mean)*(x-mean);
6909  }
6910  }
6911  }
6912  sum/=np*stddev3;
6913  return sum;
6914  }
6915  else if (axis > 10 && axis <= 13) {
6916  //compute standard error of skewness
6917  // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
6918  Double_t neff = GetEffectiveEntries();
6919  return ( neff > 0 ? TMath::Sqrt(6./neff ) : 0. );
6920  }
6921  else {
6922  Error("GetSkewness", "illegal value of parameter");
6923  return 0;
6924  }
6925 }
6926 
6927 ////////////////////////////////////////////////////////////////////////////////
6928 /// - For axis =1, 2 or 3 returns kurtosis of the histogram along x, y or z axis.
6929 /// Kurtosis(gaussian(0, 1)) = 0.
6930 /// - For axis =11, 12 or 13 returns the approximate standard error of kurtosis
6931 /// of the histogram along x, y or z axis
6932 ////
6933 /// Note, that since third and fourth moment are not calculated
6934 /// at the fill time, kurtosis and its standard error are computed bin by bin
6935 
6936 Double_t TH1::GetKurtosis(Int_t axis) const
6937 {
6938  if (axis > 0 && axis <= 3){
6939 
6940  Double_t mean = GetMean(axis);
6941  Double_t stddev = GetStdDev(axis);
6942  Double_t stddev4 = stddev*stddev*stddev*stddev;
6943 
6944  Int_t firstBinX = fXaxis.GetFirst();
6945  Int_t lastBinX = fXaxis.GetLast();
6946  Int_t firstBinY = fYaxis.GetFirst();
6947  Int_t lastBinY = fYaxis.GetLast();
6948  Int_t firstBinZ = fZaxis.GetFirst();
6949  Int_t lastBinZ = fZaxis.GetLast();
6950  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
6951  if (fgStatOverflows) {
6952  if ( !fXaxis.TestBit(TAxis::kAxisRange) ) {
6953  if (firstBinX == 1) firstBinX = 0;
6954  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
6955  }
6956  if ( !fYaxis.TestBit(TAxis::kAxisRange) ) {
6957  if (firstBinY == 1) firstBinY = 0;
6958  if (lastBinY == fYaxis.GetNbins() ) lastBinY += 1;
6959  }
6960  if ( !fZaxis.TestBit(TAxis::kAxisRange) ) {
6961  if (firstBinZ == 1) firstBinZ = 0;
6962  if (lastBinZ == fZaxis.GetNbins() ) lastBinZ += 1;
6963  }
6964  }
6965 
6966  Double_t x = 0;
6967  Double_t sum=0;
6968  Double_t np=0;
6969  for (Int_t binx = firstBinX; binx <= lastBinX; binx++) {
6970  for (Int_t biny = firstBinY; biny <= lastBinY; biny++) {
6971  for (Int_t binz = firstBinZ; binz <= lastBinZ; binz++) {
6972  if (axis==1 ) x = fXaxis.GetBinCenter(binx);
6973  else if (axis==2 ) x = fYaxis.GetBinCenter(biny);
6974  else if (axis==3 ) x = fZaxis.GetBinCenter(binz);
6975  Double_t w = GetBinContent(binx,biny,binz);
6976  np+=w;
6977  sum+=w*(x-mean)*(x-mean)*(x-mean)*(x-mean);
6978  }
6979  }
6980  }
6981  sum/=(np*stddev4);
6982  return sum-3;
6983 
6984  } else if (axis > 10 && axis <= 13) {
6985  //compute standard error of skewness
6986  // assume parent normal distribution use formula from Kendall-Stuart, Vol 1 pag 243, second edition
6987  Double_t neff = GetEffectiveEntries();
6988  return ( neff > 0 ? TMath::Sqrt(24./neff ) : 0. );
6989  }
6990  else {
6991  Error("GetKurtosis", "illegal value of parameter");
6992  return 0;
6993  }
6994 }
6995 
6996 ////////////////////////////////////////////////////////////////////////////////
6997 /// fill the array stats from the contents of this histogram
6998 /// The array stats must be correctly dimensioned in the calling program.
6999 ///
7000 /// ~~~ {.cpp}
7001 /// stats[0] = sumw
7002 /// stats[1] = sumw2
7003 /// stats[2] = sumwx
7004 /// stats[3] = sumwx2
7005 /// ~~~
7006 ///
7007 /// If no axis-subrange is specified (via TAxis::SetRange), the array stats
7008 /// is simply a copy of the statistics quantities computed at filling time.
7009 /// If a sub-range is specified, the function recomputes these quantities
7010 /// from the bin contents in the current axis range.
7011 ///
7012 /// Note that the mean value/StdDev is computed using the bins in the currently
7013 /// defined range (see TAxis::SetRange). By default the range includes
7014 /// all bins from 1 to nbins included, excluding underflows and overflows.
7015 /// To force the underflows and overflows in the computation, one must
7016 /// call the static function TH1::StatOverflows(kTRUE) before filling
7017 /// the histogram.
7018 
7019 void TH1::GetStats(Double_t *stats) const
7020 {
7021  if (fBuffer) ((TH1*)this)->BufferEmpty();
7022 
7023  // Loop on bins (possibly including underflows/overflows)
7024  Int_t bin, binx;
7025  Double_t w,err;
7026  Double_t x;
7027  // case of labels with extension of axis range
7028  // statistics in x does not make any sense - set to zero
7029  if ((const_cast<TAxis&>(fXaxis)).GetLabels() && CanExtendAllAxes() ) {
7030  stats[0] = fTsumw;
7031  stats[1] = fTsumw2;
7032  stats[2] = 0;
7033  stats[3] = 0;
7034  }
7035  else if ((fTsumw == 0 && fEntries > 0) || fXaxis.TestBit(TAxis::kAxisRange)) {
7036  for (bin=0;bin<4;bin++) stats[bin] = 0;
7037 
7038  Int_t firstBinX = fXaxis.GetFirst();
7039  Int_t lastBinX = fXaxis.GetLast();
7040  // include underflow/overflow if TH1::StatOverflows(kTRUE) in case no range is set on the axis
7042  if (firstBinX == 1) firstBinX = 0;
7043  if (lastBinX == fXaxis.GetNbins() ) lastBinX += 1;
7044  }
7045  for (binx = firstBinX; binx <= lastBinX; binx++) {
7046  x = fXaxis.GetBinCenter(binx);
7047  //w = TMath::Abs(RetrieveBinContent(binx));
7048  // not sure what to do here if w < 0
7049  w = RetrieveBinContent(binx);
7050  err = TMath::Abs(GetBinError(binx));
7051  stats[0] += w;
7052  stats[1] += err*err;
7053  stats[2] += w*x;
7054  stats[3] += w*x*x;
7055  }
7056  // if (stats[0] < 0) {
7057  // // in case total is negative do something ??
7058  // stats[0] = 0;
7059  // }
7060  } else {
7061  stats[0] = fTsumw;
7062  stats[1] = fTsumw2;
7063  stats[2] = fTsumwx;
7064  stats[3] = fTsumwx2;
7065  }
7066 }
7067 
7068 ////////////////////////////////////////////////////////////////////////////////
7069 /// Replace current statistics with the values in array stats
7070 
7071 void TH1::PutStats(Double_t *stats)
7072 {
7073  fTsumw = stats[0];
7074  fTsumw2 = stats[1];
7075  fTsumwx = stats[2];
7076  fTsumwx2 = stats[3];
7077 }
7078 
7079 ////////////////////////////////////////////////////////////////////////////////
7080 /// Reset the statistics including the number of entries
7081 /// and replace with values calculates from bin content
7082 ///
7083 /// The number of entries is set to the total bin content or (in case of weighted histogram)
7084 /// to number of effective entries
7085 
7086 void TH1::ResetStats()
7087 {
7088  Double_t stats[kNstat] = {0};
7089  fTsumw = 0;
7090  fEntries = 1; // to force re-calculation of the statistics in TH1::GetStats
7091  GetStats(stats);
7092  PutStats(stats);
7094  // use effective entries for weighted histograms: (sum_w) ^2 / sum_w2
7095  if (fSumw2.fN > 0 && fTsumw > 0 && stats[1] > 0 ) fEntries = stats[0]*stats[0]/ stats[1];
7096 }
7097 
7098 ////////////////////////////////////////////////////////////////////////////////
7099 /// Return the sum of weights excluding under/overflows.
7100 
7102 {
7103  if (fBuffer) const_cast<TH1*>(this)->BufferEmpty();
7104 
7105  Int_t bin,binx,biny,binz;
7106  Double_t sum =0;
7107  for(binz=1; binz<=fZaxis.GetNbins(); binz++) {
7108  for(biny=1; biny<=fYaxis.GetNbins(); biny++) {
7109  for(binx=1; binx<=fXaxis.GetNbins(); binx++) {
7110  bin = GetBin(binx,biny,binz);
7111  sum += RetrieveBinContent(bin);
7112  }
7113  }
7114  }
7115  return sum;
7116 }
7117 
7118 ////////////////////////////////////////////////////////////////////////////////
7119 ///Return integral of bin contents. Only bins in the bins range are considered.
7120 ///
7121 /// By default the integral is computed as the sum of bin contents in the range.
7122 /// if option "width" is specified, the integral is the sum of
7123 /// the bin contents multiplied by the bin width in x.
7124 
7125 Double_t TH1::Integral(Option_t *option) const
7126 {
7127  return Integral(fXaxis.GetFirst(),fXaxis.GetLast(),option);
7128 }
7129 
7130 ////////////////////////////////////////////////////////////////////////////////
7131 /// Return integral of bin contents in range [binx1,binx2].
7132 ///
7133 /// By default the integral is computed as the sum of bin contents in the range.
7134 /// if option "width" is specified, the integral is the sum of
7135 /// the bin contents multiplied by the bin width in x.
7136 
7137 Double_t TH1::Integral(Int_t binx1, Int_t binx2, Option_t *option) const
7138 {
7139  double err = 0;
7140  return DoIntegral(binx1,binx2,0,-1,0,-1,err,option);
7141 }
7142 
7143 ////////////////////////////////////////////////////////////////////////////////
7144 /// Return integral of bin contents in range [binx1,binx2] and its error.
7145 ///
7146 /// By default the integral is computed as the sum of bin contents in the range.
7147 /// if option "width" is specified, the integral is the sum of
7148 /// the bin contents multiplied by the bin width in x.
7149 /// the error is computed using error propagation from the bin errors assuming that
7150 /// all the bins are uncorrelated
7151 
7152 Double_t TH1::IntegralAndError(Int_t binx1, Int_t binx2, Double_t & error, Option_t *option) const
7153 {
7154  return DoIntegral(binx1,binx2,0,-1,0,-1,error,option,kTRUE);
7155 }
7156 
7157 ////////////////////////////////////////////////////////////////////////////////
7158 /// Internal function compute integral and optionally the error between the limits
7159 /// specified by the bin number values working for all histograms (1D, 2D and 3D)
7160 
7161 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 ,
7162  Option_t *option, Bool_t doError) const
7164  if (fBuffer) ((TH1*)this)->BufferEmpty();
7165 
7166  Int_t nx = GetNbinsX() + 2;
7167  if (binx1 < 0) binx1 = 0;
7168  if (binx2 >= nx || binx2 < binx1) binx2 = nx - 1;
7169 
7170  if (GetDimension() > 1) {
7171  Int_t ny = GetNbinsY() + 2;
7172  if (biny1 < 0) biny1 = 0;
7173  if (biny2 >= ny || biny2 < biny1) biny2 = ny - 1;
7174  } else {
7175  biny1 = 0; biny2 = 0;
7176  }
7177 
7178  if (GetDimension() > 2) {
7179  Int_t nz = GetNbinsZ() + 2;
7180  if (binz1 < 0) binz1 = 0;
7181  if (binz2 >= nz || binz2 < binz1) binz2 = nz - 1;
7182  } else {
7183  binz1 = 0; binz2 = 0;
7184  }
7185 
7186  // - Loop on bins in specified range
7187  TString opt = option;
7188  opt.ToLower();
7189  Bool_t width = kFALSE;
7190  if (opt.Contains("width")) width = kTRUE;
7191 
7192 
7193  Double_t dx = 1., dy = .1, dz =.1;
7194  Double_t integral = 0;
7195  Double_t igerr2 = 0;
7196  for (Int_t binx = binx1; binx <= binx2; ++binx) {
7197  if (width) dx = fXaxis.GetBinWidth(binx);
7198  for (Int_t biny = biny1; biny <= biny2; ++biny) {
7199  if (width) dy = fYaxis.GetBinWidth(biny);
7200  for (Int_t binz = binz1; binz <= binz2; ++binz) {
7201  Int_t bin = GetBin(binx, biny, binz);
7202  Double_t dv = 0.0;
7203  if (width) {
7204  dz = fZaxis.GetBinWidth(binz);
7205  dv = dx * dy * dz;
7206  integral += RetrieveBinContent(bin) * dv;
7207  } else {
7208  integral += RetrieveBinContent(bin);
7209  }
7210  if (doError) {
7211  if (width) igerr2 += GetBinErrorSqUnchecked(bin) * dv * dv;
7212  else igerr2 += GetBinErrorSqUnchecked(bin);
7213  }
7214  }
7215  }
7216  }
7217 
7218  if (doError) error = TMath::Sqrt(igerr2);
7219  return integral;
7220 }
7221 
7222 ////////////////////////////////////////////////////////////////////////////////
7223 /// Statistical test of compatibility in shape between
7224 /// this histogram and h2, using the Anderson-Darling 2 sample test.
7225 ///
7226 /// The AD 2 sample test formula are derived from the paper
7227 /// F.W Scholz, M.A. Stephens "k-Sample Anderson-Darling Test".
7228 ///
7229 /// The test is implemented in root in the ROOT::Math::GoFTest class
7230 /// It is the same formula ( (6) in the paper), and also shown in
7231 /// [this preprint](http://arxiv.org/pdf/0804.0380v1.pdf)
7232 ///
7233 /// Binned data are considered as un-binned data
7234 /// with identical observation happening in the bin center.
7235 ///
7236 /// \param[in] option is a character string to specify options
7237 /// - "D" Put out a line of "Debug" printout
7238 /// - "T" Return the normalized A-D test statistic
7239 ///
7240 /// - Note1: Underflow and overflow are not considered in the test
7241 /// - Note2: The test works only for un-weighted histogram (i.e. representing counts)
7242 /// - Note3: The histograms are not required to have the same X axis
7243 /// - Note4: The test works only for 1-dimensional histograms
7244 
7245 Double_t TH1::AndersonDarlingTest(const TH1 *h2, Option_t *option) const
7246 {
7247  Double_t advalue = 0;
7248  Double_t pvalue = AndersonDarlingTest(h2, advalue);
7249 
7250  TString opt = option;
7251  opt.ToUpper();
7252  if (opt.Contains("D") ) {
7253  printf(" AndersonDarlingTest Prob = %g, AD TestStatistic = %g\n",pvalue,advalue);
7254  }
7255  if (opt.Contains("T") ) return advalue;
7256 
7257  return pvalue;
7258 }
7259 
7260 ////////////////////////////////////////////////////////////////////////////////
7261 /// Same function as above but returning also the test statistic value
7262 
7263 Double_t TH1::AndersonDarlingTest(const TH1 *h2, Double_t & advalue) const
7264 {
7265  if (GetDimension() != 1 || h2->GetDimension() != 1) {
7266  Error("AndersonDarlingTest","Histograms must be 1-D");
7267  return -1;
7268  }
7269 
7270  // empty the buffer. Probably we could add as an unbinned test
7271  if (fBuffer) ((TH1*)this)->BufferEmpty();
7272 
7273  // use the BinData class
7274  ROOT::Fit::BinData data1;
7275  ROOT::Fit::BinData data2;
7276 
7277  ROOT::Fit::FillData(data1, this, 0);
7278  ROOT::Fit::FillData(data2, h2, 0);
7279 
7280  double pvalue;
7281  ROOT::Math::GoFTest::AndersonDarling2SamplesTest(data1,data2, pvalue,advalue);
7282 
7283  return pvalue;
7284 }
7285 
7286 ////////////////////////////////////////////////////////////////////////////////
7287 /// Statistical test of compatibility in shape between
7288 /// this histogram and h2, using Kolmogorov test.
7289 /// Note that the KolmogorovTest (KS) test should in theory be used only for unbinned data
7290 /// and not for binned data as in the case of the histogram (see NOTE 3 below).
7291 /// So, before using this method blindly, read the NOTE 3.
7292 ///
7293 /// Default: Ignore under- and overflow bins in comparison
7294 ///
7295 /// \param[in] h2 histogram
7296 /// \param[in] option is a character string to specify options
7297 /// - "U" include Underflows in test (also for 2-dim)
7298 /// - "O" include Overflows (also valid for 2-dim)
7299 /// - "N" include comparison of normalizations
7300 /// - "D" Put out a line of "Debug" printout
7301 /// - "M" Return the Maximum Kolmogorov distance instead of prob
7302 /// - "X" Run the pseudo experiments post-processor with the following procedure:
7303 /// make pseudoexperiments based on random values from the parent
7304 /// distribution and compare the KS distance of the pseudoexperiment
7305 /// to the parent distribution. Bin the KS distances in a histogram,
7306 /// and then take the integral of all the KS values above the value
7307 /// obtained from the original data to Monte Carlo distribution.
7308 /// The number of pseudo-experiments nEXPT is currently fixed at 1000.
7309 /// The function returns the integral.
7310 /// (thanks to Ben Kilminster to submit this procedure). Note that
7311 /// this option "X" is much slower.
7312 ///
7313 /// The returned function value is the probability of test
7314 /// (much less than one means NOT compatible)
7315 ///
7316 /// Code adapted by Rene Brun from original HBOOK routine HDIFF
7317 ///
7318 /// NOTE1
7319 /// A good description of the Kolmogorov test can be seen at:
7320 /// http://www.itl.nist.gov/div898/handbook/eda/section3/eda35g.htm
7321 ///
7322 /// NOTE2
7323 /// see also alternative function TH1::Chi2Test
7324 /// The Kolmogorov test is assumed to give better results than Chi2Test
7325 /// in case of histograms with low statistics.
7326 ///
7327 /// NOTE3 (Jan Conrad, Fred James)
7328 /// "The returned value PROB is calculated such that it will be
7329 /// uniformly distributed between zero and one for compatible histograms,
7330 /// provided the data are not binned (or the number of bins is very large
7331 /// compared with the number of events). Users who have access to unbinned
7332 /// data and wish exact confidence levels should therefore not put their data
7333 /// into histograms, but should call directly TMath::KolmogorovTest. On
7334 /// the other hand, since TH1 is a convenient way of collecting data and
7335 /// saving space, this function has been provided. However, the values of
7336 /// PROB for binned data will be shifted slightly higher than expected,
7337 /// depending on the effects of the binning. For example, when comparing two
7338 /// uniform distributions of 500 events in 100 bins, the values of PROB,
7339 /// instead of being exactly uniformly distributed between zero and one, have
7340 /// a mean value of about 0.56. We can apply a useful
7341 /// rule: As long as the bin width is small compared with any significant
7342 /// physical effect (for example the experimental resolution) then the binning
7343 /// cannot have an important effect. Therefore, we believe that for all
7344 /// practical purposes, the probability value PROB is calculated correctly
7345 /// provided the user is aware that:
7346 ///
7347 /// 1. The value of PROB should not be expected to have exactly the correct
7348 /// distribution for binned data.
7349 /// 2. The user is responsible for seeing to it that the bin widths are
7350 /// small compared with any physical phenomena of interest.
7351 /// 3. The effect of binning (if any) is always to make the value of PROB
7352 /// slightly too big. That is, setting an acceptance criterion of (PROB>0.05
7353 /// will assure that at most 5% of truly compatible histograms are rejected,
7354 /// and usually somewhat less."
7355 ///
7356 /// Note also that for GoF test of unbinned data ROOT provides also the class
7357 /// ROOT::Math::GoFTest. The class has also method for doing one sample tests
7358 /// (i.e. comparing the data with a given distribution).
7359 
7360 Double_t TH1::KolmogorovTest(const TH1 *h2, Option_t *option) const
7361 {
7362  TString opt = option;
7363  opt.ToUpper();
7364 
7365  Double_t prob = 0;
7366  TH1 *h1 = (TH1*)this;
7367  if (h2 == 0) return 0;
7368  const TAxis *axis1 = h1->GetXaxis();
7369  const TAxis *axis2 = h2->GetXaxis();
7370  Int_t ncx1 = axis1->GetNbins();
7371  Int_t ncx2 = axis2->GetNbins();
7372 
7373  // Check consistency of dimensions
7374  if (h1->GetDimension() != 1 || h2->GetDimension() != 1) {
7375  Error("KolmogorovTest","Histograms must be 1-D\n");
7376  return 0;
7377  }
7378 
7379  // Check consistency in number of channels
7380  if (ncx1 != ncx2) {
7381  Error("KolmogorovTest","Histograms have different number of bins, %d and %d\n",ncx1,ncx2);
7382  return 0;
7383  }
7384 
7385  // empty the buffer. Probably we could add as an unbinned test
7386  if (fBuffer) ((TH1*)this)->BufferEmpty();
7387 
7388  // Check consistency in bin edges
7389  for(Int_t i = 1; i <= axis1->GetNbins() + 1; ++i) {
7390  if(!TMath::AreEqualRel(axis1->GetBinLowEdge(i), axis2->GetBinLowEdge(i), 1.E-15)) {
7391  Error("KolmogorovTest","Histograms are not consistent: they have different bin edges");
7392  return 0;
7393  }
7394  }
7395 
7396  Bool_t afunc1 = kFALSE;
7397  Bool_t afunc2 = kFALSE;
7398  Double_t sum1 = 0, sum2 = 0;
7399  Double_t ew1, ew2, w1 = 0, w2 = 0;
7400  Int_t bin;
7401  Int_t ifirst = 1;
7402  Int_t ilast = ncx1;
7403  // integral of all bins (use underflow/overflow if option)
7404  if (opt.Contains("U")) ifirst = 0;
7405  if (opt.Contains("O")) ilast = ncx1 +1;
7406  for (bin = ifirst; bin <= ilast; bin++) {
7407  sum1 += h1->RetrieveBinContent(bin);
7408  sum2 += h2->RetrieveBinContent(bin);
7409  ew1 = h1->GetBinError(bin);
7410  ew2 = h2->GetBinError(bin);
7411  w1 += ew1*ew1;
7412  w2 += ew2*ew2;
7413  }
7414  if (sum1 == 0) {
7415  Error("KolmogorovTest","Histogram1 %s integral is zero\n",h1->GetName());
7416  return 0;
7417  }
7418  if (sum2 == 0) {
7419  Error("KolmogorovTest","Histogram2 %s integral is zero\n",h2->GetName());
7420  return 0;
7421  }
7422 
7423  // calculate the effective entries.
7424  // the case when errors are zero (w1 == 0 or w2 ==0) are equivalent to
7425  // compare to a function. In that case the rescaling is done only on sqrt(esum2) or sqrt(esum1)
7426  Double_t esum1 = 0, esum2 = 0;
7427  if (w1 > 0)
7428  esum1 = sum1 * sum1 / w1;
7429  else
7430  afunc1 = kTRUE; // use later for calculating z
7431 
7432  if (w2 > 0)
7433  esum2 = sum2 * sum2 / w2;
7434  else
7435  afunc2 = kTRUE; // use later for calculating z
7436 
7437  if (afunc2 && afunc1) {
7438  Error("KolmogorovTest","Errors are zero for both histograms\n");
7439  return 0;
7440  }
7441 
7442 
7443  Double_t s1 = 1/sum1;
7444  Double_t s2 = 1/sum2;
7445 
7446  // Find largest difference for Kolmogorov Test
7447  Double_t dfmax =0, rsum1 = 0, rsum2 = 0;
7448 
7449  for (bin=ifirst;bin<=ilast;bin++) {
7450  rsum1 += s1*h1->RetrieveBinContent(bin);
7451  rsum2 += s2*h2->RetrieveBinContent(bin);
7452  dfmax = TMath::Max(dfmax,TMath::Abs(rsum1-rsum2));
7453  }
7454 
7455  // Get Kolmogorov probability
7456  Double_t z, prb1=0, prb2=0, prb3=0;
7457 
7458  // case h1 is exact (has zero errors)
7459  if (afunc1)
7460  z = dfmax*TMath::Sqrt(esum2);
7461  // case h2 has zero errors
7462  else if (afunc2)
7463  z = dfmax*TMath::Sqrt(esum1);
7464  else
7465  // for comparison between two data sets
7466  z = dfmax*TMath::Sqrt(esum1*esum2/(esum1+esum2));
7467 
7468  prob = TMath::KolmogorovProb(z);
7469 
7470  // option N to combine normalization makes sense if both afunc1 and afunc2 are false
7471  if (opt.Contains("N") && !(afunc1 || afunc2 ) ) {
7472  // Combine probabilities for shape and normalization,
7473  prb1 = prob;
7474  Double_t d12 = esum1-esum2;
7475  Double_t chi2 = d12*d12/(esum1+esum2);
7476  prb2 = TMath::Prob(chi2,1);
7477  // see Eadie et al., section 11.6.2
7478  if (prob > 0 && prb2 > 0) prob *= prb2*(1-TMath::Log(prob*prb2));
7479  else prob = 0;
7480  }
7481  // X option. Pseudo-experiments post-processor to determine KS probability
7482  const Int_t nEXPT = 1000;
7483  if (opt.Contains("X") && !(afunc1 || afunc2 ) ) {
7484  Double_t dSEXPT;
7485  TH1 *hExpt = (TH1*)(gDirectory ? gDirectory->CloneObject(this,kFALSE) : gROOT->CloneObject(this,kFALSE));
7486  // make nEXPT experiments (this should be a parameter)
7487  prb3 = 0;
7488  for (Int_t i=0; i < nEXPT; i++) {
7489  hExpt->Reset();
7490  hExpt->FillRandom(h1,(Int_t)esum2);
7491  dSEXPT = KolmogorovTest(hExpt,"M");
7492  if (dSEXPT>dfmax) prb3 += 1.0;
7493  }
7494  prb3 /= (Double_t)nEXPT;
7495  delete hExpt;
7496  }
7497 
7498  // debug printout
7499  if (opt.Contains("D")) {
7500  printf(" Kolmo Prob h1 = %s, sum bin content =%g effective entries =%g\n",h1->GetName(),sum1,esum1);
7501  printf(" Kolmo Prob h2 = %s, sum bin content =%g effective entries =%g\n",h2->GetName(),sum2,esum2);
7502  printf(" Kolmo Prob = %g, Max Dist = %g\n",prob,dfmax);
7503  if (opt.Contains("N"))
7504  printf(" Kolmo Prob = %f for shape alone, =%f for normalisation alone\n",prb1,prb2);
7505  if (opt.Contains("X"))
7506  printf(" Kolmo Prob = %f with %d pseudo-experiments\n",prb3,nEXPT);
7507  }
7508  // This numerical error condition should never occur:
7509  if (TMath::Abs(rsum1-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h1=%s\n",h1->GetName());
7510  if (TMath::Abs(rsum2-1) > 0.002) Warning("KolmogorovTest","Numerical problems with h2=%s\n",h2->GetName());
7511 
7512  if(opt.Contains("M")) return dfmax;
7513  else if(opt.Contains("X")) return prb3;
7514  else return prob;
7515 }
7516 
7517 ////////////////////////////////////////////////////////////////////////////////
7518 /// Replace bin contents by the contents of array content
7519 
7520 void TH1::SetContent(const Double_t *content)
7521 {
7523  fTsumw = 0;
7524  for (Int_t i = 0; i < fNcells; ++i) UpdateBinContent(i, content[i]);
7525 }
7526 
7527 ////////////////////////////////////////////////////////////////////////////////
7528 /// Return contour values into array levels if pointer levels is non zero.
7529 ///
7530 /// The function returns the number of contour levels.
7531 /// see GetContourLevel to return one contour only
7532 
7534 {
7535  Int_t nlevels = fContour.fN;
7536  if (levels) {
7537  if (nlevels == 0) {
7538  nlevels = 20;
7539  SetContour(nlevels);
7540  } else {
7541  if (TestBit(kUserContour) == 0) SetContour(nlevels);
7542  }
7543  for (Int_t level=0; level<nlevels; level++) levels[level] = fContour.fArray[level];
7544  }
7545  return nlevels;
7546 }
7547 
7548 ////////////////////////////////////////////////////////////////////////////////
7549 /// Return value of contour number level.
7550 /// Use GetContour to return the array of all contour levels
7551 
7552 Double_t TH1::GetContourLevel(Int_t level) const
7553 {
7554  return (level >= 0 && level < fContour.fN) ? fContour.fArray[level] : 0.0;
7555 }
7556 
7557 ////////////////////////////////////////////////////////////////////////////////
7558 /// Return the value of contour number "level" in Pad coordinates.
7559 /// ie: if the Pad is in log scale along Z it returns le log of the contour level
7560 /// value. See GetContour to return the array of all contour levels
7561 
7563 {
7564  if (level <0 || level >= fContour.fN) return 0;
7565  Double_t zlevel = fContour.fArray[level];
7566 
7567  // In case of user defined contours and Pad in log scale along Z,
7568  // fContour.fArray doesn't contain the log of the contour whereas it does
7569  // in case of equidistant contours.
7570  if (gPad && gPad->GetLogz() && TestBit(kUserContour)) {
7571  if (zlevel <= 0) return 0;
7572  zlevel = TMath::Log10(zlevel);
7573  }
7574  return zlevel;
7575 }
7576 
7577 ////////////////////////////////////////////////////////////////////////////////
7578 /// Set the maximum number of entries to be kept in the buffer.
7579 
7580 void TH1::SetBuffer(Int_t buffersize, Option_t * /*option*/)
7581 {
7582  if (fBuffer) {
7583  BufferEmpty();
7584  delete [] fBuffer;
7585  fBuffer = 0;
7586  }
7587  if (buffersize <= 0) {
7588  fBufferSize = 0;
7589  return;
7590  }
7591  if (buffersize < 100) buffersize = 100;
7592  fBufferSize = 1 + buffersize*(fDimension+1);
7593  fBuffer = new Double_t[fBufferSize];
7594  memset(fBuffer,0,sizeof(Double_t)*fBufferSize);
7595 }
7596 
7597 ////////////////////////////////////////////////////////////////////////////////
7598 /// Set the number and values of contour levels.
7599 ///
7600 /// By default the number of contour levels is set to 20. The contours values
7601 /// in the array "levels" should be specified in increasing order.
7602 ///
7603 /// if argument levels = 0 or missing, equidistant contours are computed
7604 
7605 void TH1::SetContour(Int_t nlevels, const Double_t *levels)
7606 {
7607  Int_t level;
7609  if (nlevels <=0 ) {
7610  fContour.Set(0);
7611  return;
7612  }
7613  fContour.Set(nlevels);
7614 
7615  // - Contour levels are specified
7616  if (levels) {
7618  for (level=0; level<nlevels; level++) fContour.fArray[level] = levels[level];
7619  } else {
7620  // - contour levels are computed automatically as equidistant contours
7621  Double_t zmin = GetMinimum();
7622  Double_t zmax = GetMaximum();
7623  if ((zmin == zmax) && (zmin != 0)) {
7624  zmax += 0.01*TMath::Abs(zmax);
7625  zmin -= 0.01*TMath::Abs(zmin);
7626  }
7627  Double_t dz = (zmax-zmin)/Double_t(nlevels);
7628  if (gPad && gPad->GetLogz()) {
7629  if (zmax <= 0) return;
7630  if (zmin <= 0) zmin = 0.001*zmax;
7631  zmin = TMath::Log10(zmin);
7632  zmax = TMath::Log10(zmax);
7633  dz = (zmax-zmin)/Double_t(nlevels);
7634  }
7635  for (level=0; level<nlevels; level++) {
7636  fContour.fArray[level] = zmin + dz*Double_t(level);
7637  }
7638  }
7639 }
7640 
7641 ////////////////////////////////////////////////////////////////////////////////
7642 /// Set value for one contour level.
7643 
7644 void TH1::SetContourLevel(Int_t level, Double_t value)
7645 {
7646  if (level < 0 || level >= fContour.fN) return;
7648  fContour.fArray[level] = value;
7649 }
7650 
7651 ////////////////////////////////////////////////////////////////////////////////
7652 /// Return maximum value smaller than maxval of bins in the range,
7653 /// unless the value has been overridden by TH1::SetMaximum,
7654 /// in which case it returns that value. (This happens, for example,
7655 /// when the histogram is drawn and the y or z axis limits are changed
7656 ///
7657 /// To get the maximum value of bins in the histogram regardless of
7658 /// whether the value has been overridden, use
7659 ///
7660 /// ~~~ {.cpp}
7661 /// h->GetBinContent(h->GetMaximumBin())
7662 /// ~~~
7663 
7664 Double_t TH1::GetMaximum(Double_t maxval) const
7665 {
7666  if (fMaximum != -1111) return fMaximum;
7667 
7668  // empty the buffer
7669  if (fBuffer) ((TH1*)this)->BufferEmpty();
7670 
7671  Int_t bin, binx, biny, binz;
7672  Int_t xfirst = fXaxis.GetFirst();
7673  Int_t xlast = fXaxis.GetLast();
7674  Int_t yfirst = fYaxis.GetFirst();
7675  Int_t ylast = fYaxis.GetLast();
7676  Int_t zfirst = fZaxis.GetFirst();
7677  Int_t zlast = fZaxis.GetLast();
7678  Double_t maximum = -FLT_MAX, value;
7679  for (binz=zfirst;binz<=zlast;binz++) {
7680  for (biny=yfirst;biny<=ylast;biny++) {
7681  for (binx=xfirst;binx<=xlast;binx++) {
7682  bin = GetBin(binx,biny,binz);
7683  value = RetrieveBinContent(bin);
7684  if (value > maximum && value < maxval) maximum = value;
7685  }
7686  }
7687  }
7688  return maximum;
7689 }
7690 
7691 ////////////////////////////////////////////////////////////////////////////////
7692 /// Return location of bin with maximum value in the range.
7693 
7694 Int_t TH1::GetMaximumBin() const
7695 {
7696  Int_t locmax, locmay, locmaz;
7697  return GetMaximumBin(locmax, locmay, locmaz);
7698 }
7699 
7700 ////////////////////////////////////////////////////////////////////////////////
7701 /// Return location of bin with maximum value in the range.
7702 
7703 Int_t TH1::GetMaximumBin(Int_t &locmax, Int_t &locmay, Int_t &locmaz) const
7704 {
7705  // empty the buffer
7706  if (fBuffer) ((TH1*)this)->BufferEmpty();
7707 
7708  Int_t bin, binx, biny, binz;
7709  Int_t locm;
7710  Int_t xfirst = fXaxis.GetFirst();
7711  Int_t xlast = fXaxis.GetLast();
7712  Int_t yfirst = fYaxis.GetFirst();
7713  Int_t ylast = fYaxis.GetLast();
7714  Int_t zfirst = fZaxis.GetFirst();
7715  Int_t zlast = fZaxis.GetLast();
7716  Double_t maximum = -FLT_MAX, value;
7717  locm = locmax = locmay = locmaz = 0;
7718  for (binz=zfirst;binz<=zlast;binz++) {
7719  for (biny=yfirst;biny<=ylast;biny++) {
7720  for (binx=xfirst;binx<=xlast;binx++) {
7721  bin = GetBin(binx,biny,binz);
7722  value = RetrieveBinContent(bin);
7723  if (value > maximum) {
7724  maximum = value;
7725  locm = bin;
7726  locmax = binx;
7727  locmay = biny;
7728  locmaz = binz;
7729  }
7730  }
7731  }
7732  }
7733  return locm;
7734 }
7735 
7736 ////////////////////////////////////////////////////////////////////////////////
7737 /// Return minimum value larger than minval of bins in the range,
7738 /// unless the value has been overridden by TH1::SetMinimum,
7739 /// in which case it returns that value. (This happens, for example,
7740 /// when the histogram is drawn and the y or z axis limits are changed
7741 ///
7742 /// To get the minimum value of bins in the histogram regardless of
7743 /// whether the value has been overridden, use
7744 ///
7745 /// ~~~ {.cpp}
7746 /// h->GetBinContent(h->GetMinimumBin())
7747 /// ~~~
7748 
7749 Double_t TH1::GetMinimum(Double_t minval) const
7750 {
7751  if (fMinimum != -1111) return fMinimum;
7752 
7753  // empty the buffer
7754  if (fBuffer) ((TH1*)this)->BufferEmpty();
7755 
7756  Int_t bin, binx, biny, binz;
7757  Int_t xfirst = fXaxis.GetFirst();
7758  Int_t xlast = fXaxis.GetLast();
7759  Int_t yfirst = fYaxis.GetFirst();
7760  Int_t ylast = fYaxis.GetLast();
7761  Int_t zfirst = fZaxis.GetFirst();
7762  Int_t zlast = fZaxis.GetLast();
7763  Double_t minimum=FLT_MAX, value;
7764  for (binz=zfirst;binz<=zlast;binz++) {
7765  for (biny=yfirst;biny<=ylast;biny++) {
7766  for (binx=xfirst;binx<=xlast;binx++) {
7767  bin = GetBin(binx,biny,binz);
7768  value = RetrieveBinContent(bin);
7769  if (value < minimum && value > minval) minimum = value;
7770  }
7771  }
7772  }
7773  return minimum;
7774 }
7775 
7776 ////////////////////////////////////////////////////////////////////////////////
7777 /// Return location of bin with minimum value in the range.
7778 
7779 Int_t TH1::GetMinimumBin() const
7780 {
7781  Int_t locmix, locmiy, locmiz;
7782  return GetMinimumBin(locmix, locmiy, locmiz);
7783 }
7784 
7785 ////////////////////////////////////////////////////////////////////////////////
7786 /// Return location of bin with minimum value in the range.
7787 
7788 Int_t TH1::GetMinimumBin(Int_t &locmix, Int_t &locmiy, Int_t &locmiz) const
7789 {
7790  // empty the buffer
7791  if (fBuffer) ((TH1*)this)->BufferEmpty();
7792 
7793  Int_t bin, binx, biny, binz;
7794  Int_t locm;
7795  Int_t xfirst = fXaxis.GetFirst();
7796  Int_t xlast = fXaxis.GetLast();
7797  Int_t yfirst = fYaxis.GetFirst();
7798  Int_t ylast = fYaxis.GetLast();
7799  Int_t zfirst = fZaxis.GetFirst();
7800  Int_t zlast = fZaxis.GetLast();
7801  Double_t minimum = FLT_MAX, value;
7802  locm = locmix = locmiy = locmiz = 0;
7803  for (binz=zfirst;binz<=zlast;binz++) {
7804  for (biny=yfirst;biny<=ylast;biny++) {
7805  for (binx=xfirst;binx<=xlast;binx++) {
7806  bin = GetBin(binx,biny,binz);
7807  value = RetrieveBinContent(bin);
7808  if (value < minimum) {
7809  minimum = value;
7810  locm = bin;
7811  locmix = binx;
7812  locmiy = biny;
7813  locmiz = binz;
7814  }
7815  }
7816  }
7817  }
7818  return locm;
7819 }
7820 
7821 ///////////////////////////////////////////////////////////////////////////////
7822 /// Retrieve the minimum and maximum values in the histogram
7823 ///
7824 /// This will not return a cached value and will always search the
7825 /// histogram for the min and max values. The user can condition whether
7826 /// or not to call this with the GetMinimumStored() and GetMaximumStored()
7827 /// methods. If the cache is empty, then the value will be -1111. Users
7828 /// can then use the SetMinimum() or SetMaximum() methods to cache the results.
7829 /// For example, the following recipe will make efficient use of this method
7830 /// and the cached minimum and maximum values.
7831 //
7832 /// \code{.cpp}
7833 /// Double_t currentMin = pHist->GetMinimumStored();
7834 /// Double_t currentMax = pHist->GetMaximumStored();
7835 /// if ((currentMin == -1111) || (currentMax == -1111)) {
7836 /// pHist->GetMinimumAndMaximum(currentMin, currentMax);
7837 /// pHist->SetMinimum(currentMin);
7838 /// pHist->SetMaximum(currentMax);
7839 /// }
7840 /// \endcode
7841 ///
7842 /// \param min reference to variable that will hold found minimum value
7843 /// \param max reference to variable that will hold found maximum value
7844 
7845 void TH1::GetMinimumAndMaximum(Double_t& min, Double_t& max) const
7846 {
7847  // empty the buffer
7848  if (fBuffer) ((TH1*)this)->BufferEmpty();
7849 
7850  Int_t bin, binx, biny, binz;
7851  Int_t xfirst = fXaxis.GetFirst();
7852  Int_t xlast = fXaxis.GetLast();
7853  Int_t yfirst = fYaxis.GetFirst();
7854  Int_t ylast = fYaxis.GetLast();
7855  Int_t zfirst = fZaxis.GetFirst();
7856  Int_t zlast = fZaxis.GetLast();
7857  min=TMath::Infinity();
7858  max=-TMath::Infinity();
7859  Double_t value;
7860  for (binz=zfirst;binz<=zlast;binz++) {
7861  for (biny=yfirst;biny<=ylast;biny++) {
7862  for (binx=xfirst;binx<=xlast;binx++) {
7863  bin = GetBin(binx,biny,binz);
7864  value = RetrieveBinContent(bin);
7865  if (value < min) min = value;
7866  if (value > max) max = value;
7867  }
7868  }
7869  }
7870 }
7871 
7872 ////////////////////////////////////////////////////////////////////////////////
7873 /// Redefine x axis parameters.
7874 ///
7875 /// The X axis parameters are modified.
7876 /// The bins content array is resized
7877 /// if errors (Sumw2) the errors array is resized
7878 /// The previous bin contents are lost
7879 /// To change only the axis limits, see TAxis::SetRange
7880 
7881 void TH1::SetBins(Int_t nx, Double_t xmin, Double_t xmax)
7882 {
7883  if (GetDimension() != 1) {
7884  Error("SetBins","Operation only valid for 1-d histograms");
7885  return;
7886  }
7887  fXaxis.SetRange(0,0);
7888  fXaxis.Set(nx,xmin,xmax);
7889  fYaxis.Set(1,0,1);
7890  fZaxis.Set(1,0,1);
7891  fNcells = nx+2;
7892  SetBinsLength(fNcells);
7893  if (fSumw2.fN) {
7894  fSumw2.Set(fNcells);
7895  }
7896 }
7897 
7898 ////////////////////////////////////////////////////////////////////////////////
7899 /// Redefine x axis parameters with variable bin sizes.
7900 ///
7901 /// The X axis parameters are modified.
7902 /// The bins content array is resized
7903 /// if errors (Sumw2) the errors array is resized
7904 /// The previous bin contents are lost
7905 /// To change only the axis limits, see TAxis::SetRange
7906 /// xBins is supposed to be of length nx+1
7907 
7908 void TH1::SetBins(Int_t nx, const Double_t *xBins)
7909 {
7910  if (GetDimension() != 1) {
7911  Error("SetBins","Operation only valid for 1-d histograms");
7912  return;
7913  }
7914  fXaxis.SetRange(0,0);
7915  fXaxis.Set(nx,xBins);
7916  fYaxis.Set(1,0,1);
7917  fZaxis.Set(1,0,1);
7918  fNcells = nx+2;
7919  SetBinsLength(fNcells);
7920  if (fSumw2.fN) {
7921  fSumw2.Set(fNcells);
7922  }
7923 }
7924 
7925 ////////////////////////////////////////////////////////////////////////////////
7926 /// Redefine x and y axis parameters.
7927 ///
7928 /// The X and Y axis parameters are modified.
7929 /// The bins content array is resized
7930 /// if errors (Sumw2) the errors array is resized
7931 /// The previous bin contents are lost
7932 /// To change only the axis limits, see TAxis::SetRange
7933 
7934 void TH1::SetBins(Int_t nx, Double_t xmin, Double_t xmax, Int_t ny, Double_t ymin, Double_t ymax)
7935 {
7936  if (GetDimension() != 2) {
7937  Error("SetBins","Operation only valid for 2-D histograms");
7938  return;
7939  }
7940  fXaxis.SetRange(0,0);
7941  fYaxis.SetRange(0,0);
7942  fXaxis.Set(nx,xmin,xmax);
7943  fYaxis.Set(ny,ymin,ymax);
7944  fZaxis.Set(1,0,1);
7945  fNcells = (nx+2)*(ny+2);
7946  SetBinsLength(fNcells);
7947  if (fSumw2.fN) {
7948  fSumw2.Set(fNcells);
7949  }
7950 }
7951 
7952 ////////////////////////////////////////////////////////////////////////////////
7953 /// Redefine x and y axis parameters with variable bin sizes.
7954 ///
7955 /// The X and Y axis parameters are modified.
7956 /// The bins content array is resized
7957 /// if errors (Sumw2) the errors array is resized
7958 /// The previous bin contents are lost
7959 /// To change only the axis limits, see TAxis::SetRange
7960 /// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1
7961 
7962 void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins)
7963 {
7964  if (GetDimension() != 2) {
7965  Error("SetBins","Operation only valid for 2-D histograms");
7966  return;
7967  }
7968  fXaxis.SetRange(0,0);
7969  fYaxis.SetRange(0,0);
7970  fXaxis.Set(nx,xBins);
7971  fYaxis.Set(ny,yBins);
7972  fZaxis.Set(1,0,1);
7973  fNcells = (nx+2)*(ny+2);
7974  SetBinsLength(fNcells);
7975  if (fSumw2.fN) {
7976  fSumw2.Set(fNcells);
7977  }
7978 }
7979 
7980 ////////////////////////////////////////////////////////////////////////////////
7981 /// Redefine x, y and z axis parameters.
7982 ///
7983 /// The X, Y and Z axis parameters are modified.
7984 /// The bins content array is resized
7985 /// if errors (Sumw2) the errors array is resized
7986 /// The previous bin contents are lost
7987 /// To change only the axis limits, see TAxis::SetRange
7988 
7989 void TH1::SetBins(Int_t nx, Double_t xmin, Double_t xmax, Int_t ny, Double_t ymin, Double_t ymax, Int_t nz, Double_t zmin, Double_t zmax)
7990 {
7991  if (GetDimension() != 3) {
7992  Error("SetBins","Operation only valid for 3-D histograms");
7993  return;
7994  }
7995  fXaxis.SetRange(0,0);
7996  fYaxis.SetRange(0,0);
7997  fZaxis.SetRange(0,0);
7998  fXaxis.Set(nx,xmin,xmax);
7999  fYaxis.Set(ny,ymin,ymax);
8000  fZaxis.Set(nz,zmin,zmax);
8001  fNcells = (nx+2)*(ny+2)*(nz+2);
8002  SetBinsLength(fNcells);
8003  if (fSumw2.fN) {
8004  fSumw2.Set(fNcells);
8005  }
8006 }
8007 
8008 ////////////////////////////////////////////////////////////////////////////////
8009 /// Redefine x, y and z axis parameters with variable bin sizes.
8010 ///
8011 /// The X, Y and Z axis parameters are modified.
8012 /// The bins content array is resized
8013 /// if errors (Sumw2) the errors array is resized
8014 /// The previous bin contents are lost
8015 /// To change only the axis limits, see TAxis::SetRange
8016 /// xBins is supposed to be of length nx+1, yBins is supposed to be of length ny+1,
8017 /// zBins is supposed to be of length nz+1
8018 
8019 void TH1::SetBins(Int_t nx, const Double_t *xBins, Int_t ny, const Double_t *yBins, Int_t nz, const Double_t *zBins)
8020 {
8021  if (GetDimension() != 3) {
8022  Error("SetBins","Operation only valid for 3-D histograms");
8023  return;
8024  }
8025  fXaxis.SetRange(0,0);
8026  fYaxis.SetRange(0,0);
8027  fZaxis.SetRange(0,0);
8028  fXaxis.Set(nx,xBins);
8029  fYaxis.Set(ny,yBins);
8030  fZaxis.Set(nz,zBins);
8031  fNcells = (nx+2)*(ny+2)*(nz+2);
8032  SetBinsLength(fNcells);
8033  if (fSumw2.fN) {
8034  fSumw2.Set(fNcells);
8035  }
8036 }
8037 
8038 ////////////////////////////////////////////////////////////////////////////////
8039 /// By default when an histogram is created, it is added to the list
8040 /// of histogram objects in the current directory in memory.
8041 /// Remove reference to this histogram from current directory and add
8042 /// reference to new directory dir. dir can be 0 in which case the
8043 /// histogram does not belong to any directory.
8044 ///
8045 /// Note that the directory is not a real property of the histogram and
8046 /// it will not be copied when the histogram is copied or cloned.
8047 /// If the user wants to have the copied (cloned) histogram in the same
8048 /// directory, he needs to set again the directory using SetDirectory to the
8049 /// copied histograms
8050 
8051 void TH1::SetDirectory(TDirectory *dir)
8052 {
8053  if (fDirectory == dir) return;
8054  if (fDirectory) fDirectory->Remove(this);
8055  fDirectory = dir;
8056  if (fDirectory) fDirectory->Append(this);
8057 }
8058 
8059 ////////////////////////////////////////////////////////////////////////////////
8060 /// Replace bin errors by values in array error.
8061 
8062 void TH1::SetError(const Double_t *error)
8063 {
8064  for (Int_t i = 0; i < fNcells; ++i) SetBinError(i, error[i]);
8065 }
8066 
8067 ////////////////////////////////////////////////////////////////////////////////
8068 /// Change the name of this histogram
8069 ///
8070 
8071 void TH1::SetName(const char *name)
8072 {
8073  // Histograms are named objects in a THashList.
8074  // We must update the hashlist if we change the name
8075  // We protect this operation
8077  if (fDirectory) fDirectory->Remove(this);
8078  fName = name;
8079  if (fDirectory) fDirectory->Append(this);
8080 }
8081 
8082 ////////////////////////////////////////////////////////////////////////////////
8083 /// Change the name and title of this histogram
8084 
8085 void TH1::SetNameTitle(const char *name, const char *title)
8086 {
8087  // Histograms are named objects in a THashList.
8088  // We must update the hashlist if we change the name
8089  SetName(name);
8090  SetTitle(title);
8091 }
8092 
8093 ////////////////////////////////////////////////////////////////////////////////
8094 /// Set statistics option on/off
8095 ///
8096 /// By default, the statistics box is drawn.
8097 /// The paint options can be selected via gStyle->SetOptStats.
8098 /// This function sets/resets the kNoStats bin in the histogram object.
8099 /// It has priority over the Style option.
8100 
8101 void TH1::SetStats(Bool_t stats)
8102 {
8104  if (!stats) {
8105  SetBit(kNoStats);
8106  //remove the "stats" object from the list of functions
8107  if (fFunctions) {
8108  TObject *obj = fFunctions->FindObject("stats");
8109  if (obj) {
8110  fFunctions->Remove(obj);
8111  delete obj;
8112  }
8113  }
8114  }
8115 }
8116 
8117 ////////////////////////////////////////////////////////////////////////////////
8118 /// Create structure to store sum of squares of weights.
8119 ///
8120 /// if histogram is already filled, the sum of squares of weights
8121 /// is filled with the existing bin contents
8122 ///
8123 /// The error per bin will be computed as sqrt(sum of squares of weight)
8124 /// for each bin.
8125 ///
8126 /// This function is automatically called when the histogram is created
8127 /// if the static function TH1::SetDefaultSumw2 has been called before.
8128 /// If flag = false the structure is deleted
8129 
8130 void TH1::Sumw2(Bool_t flag)
8131 {
8132  if (!flag) {
8133  // clear the array if existing - do nothing otherwise
8134  if (fSumw2.fN > 0 ) fSumw2.Set(0);
8135  return;
8136  }
8137 
8138  if (fSumw2.fN == fNcells) {
8139  if (!fgDefaultSumw2 )
8140  Warning("Sumw2","Sum of squares of weights structure already created");
8141  return;
8142  }
8143 
8144  fSumw2.Set(fNcells);
8145 
8146  // empty the buffer
8147  if (fBuffer) BufferEmpty();
8148 
8149  if (fEntries > 0)
8150  for (Int_t i = 0; i < fNcells; ++i)
8152 }
8153 
8154 ////////////////////////////////////////////////////////////////////////////////
8155 /// Return pointer to function with name.
8156 ///
8157 ///
8158 /// Functions such as TH1::Fit store the fitted function in the list of
8159 /// functions of this histogram.
8160 
8161 TF1 *TH1::GetFunction(const char *name) const
8162 {
8163  return (TF1*)fFunctions->FindObject(name);
8164 }
8165 
8166 ////////////////////////////////////////////////////////////////////////////////
8167 /// Return value of error associated to bin number bin.
8168 ///
8169 /// if the sum of squares of weights has been defined (via Sumw2),
8170 /// this function returns the sqrt(sum of w2).
8171 /// otherwise it returns the sqrt(contents) for this bin.
8172 
8173 Double_t TH1::GetBinError(Int_t bin) const
8174 {
8175  if (bin < 0) bin = 0;
8176  if (bin >= fNcells) bin = fNcells-1;
8177  if (fBuffer) ((TH1*)this)->BufferEmpty();
8178  if (fSumw2.fN) return TMath::Sqrt(fSumw2.fArray[bin]);
8179 
8181 }
8182 
8183 ////////////////////////////////////////////////////////////////////////////////
8184 /// Return lower error associated to bin number bin.
8185 ///
8186 /// The error will depend on the statistic option used will return
8187 /// the binContent - lower interval value
8188 
8190 {
8191  if (fBinStatErrOpt == kNormal) return GetBinError(bin);
8192  // in case of weighted histogram check if it is really weighted
8193  if (fSumw2.fN && fTsumw != fTsumw2) return GetBinError(bin);
8194 
8195  if (bin < 0) bin = 0;
8196  if (bin >= fNcells) bin = fNcells-1;
8197  if (fBuffer) ((TH1*)this)->BufferEmpty();
8198 
8199  Double_t alpha = 1.- 0.682689492;
8200  if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
8201 
8202  Double_t c = RetrieveBinContent(bin);
8203  Int_t n = int(c);
8204  if (n < 0) {
8205  Warning("GetBinErrorLow","Histogram has negative bin content-force usage to normal errors");
8206  ((TH1*)this)->fBinStatErrOpt = kNormal;
8207  return GetBinError(bin);
8208  }
8209 
8210  if (n == 0) return 0;
8211  return c - ROOT::Math::gamma_quantile( alpha/2, n, 1.);
8212 }
8213 
8214 ////////////////////////////////////////////////////////////////////////////////
8215 /// Return upper error associated to bin number bin.
8216 ///
8217 /// The error will depend on the statistic option used will return
8218 /// the binContent - upper interval value
8219 
8221 {
8222  if (fBinStatErrOpt == kNormal) return GetBinError(bin);
8223  // in case of weighted histogram check if it is really weighted
8224  if (fSumw2.fN && fTsumw != fTsumw2) return GetBinError(bin);
8225  if (bin < 0) bin = 0;
8226  if (bin >= fNcells) bin = fNcells-1;
8227  if (fBuffer) ((TH1*)this)->BufferEmpty();
8228 
8229  Double_t alpha = 1.- 0.682689492;
8230  if (fBinStatErrOpt == kPoisson2) alpha = 0.05;
8231 
8232  Double_t c = RetrieveBinContent(bin);
8233  Int_t n = int(c);
8234  if (n < 0) {
8235  Warning("GetBinErrorUp","Histogram has negative bin content-force usage to normal errors");
8236  ((TH1*)this)->fBinStatErrOpt = kNormal;
8237  return GetBinError(bin);
8238  }
8239 
8240  // for N==0 return an upper limit at 0.68 or (1-alpha)/2 ?
8241  // decide to return always (1-alpha)/2 upper interval
8242  //if (n == 0) return ROOT::Math::gamma_quantile_c(alpha,n+1,1);
8243  return ROOT::Math::gamma_quantile_c( alpha/2, n+1, 1) - c;
8244 }
8245 
8246 //L.M. These following getters are useless and should be probably deprecated
8247 ////////////////////////////////////////////////////////////////////////////////
8248 /// Return bin center for 1D histogram.
8249 /// Better to use h1.GetXaxis().GetBinCenter(bin)
8250 
8251 Double_t TH1::GetBinCenter(Int_t bin) const
8252 {
8253  if (fDimension == 1) return fXaxis.GetBinCenter(bin);
8254  Error("GetBinCenter","Invalid method for a %d-d histogram - return a NaN",fDimension);
8255  return TMath::QuietNaN();
8256 }
8257 
8258 ////////////////////////////////////////////////////////////////////////////////
8259 /// Return bin lower edge for 1D histogram.
8260 /// Better to use h1.GetXaxis().GetBinLowEdge(bin)
8261 
8263 {
8264  if (fDimension == 1) return fXaxis.GetBinLowEdge(bin);
8265  Error("GetBinLowEdge","Invalid method for a %d-d histogram - return a NaN",fDimension);
8266  return TMath::QuietNaN();
8267 }
8268 
8269 ////////////////////////////////////////////////////////////////////////////////
8270 /// Return bin width for 1D histogram.
8271 /// Better to use h1.GetXaxis().GetBinWidth(bin)
8272 
8273 Double_t TH1::GetBinWidth(Int_t bin) const
8274 {
8275  if (fDimension == 1) return fXaxis.GetBinWidth(bin);
8276  Error("GetBinWidth","Invalid method for a %d-d histogram - return a NaN",fDimension);
8277  return TMath::QuietNaN();
8278 }
8279 
8280 ////////////////////////////////////////////////////////////////////////////////
8281 /// Fill array with center of bins for 1D histogram
8282 /// Better to use h1.GetXaxis().GetCenter(center)
8283 
8284 void TH1::GetCenter(Double_t *center) const
8285 {
8286  if (fDimension == 1) {
8287  fXaxis.GetCenter(center);
8288  return;
8289  }
8290  Error("GetCenter","Invalid method for a %d-d histogram ",fDimension);
8291 }
8292 
8293 ////////////////////////////////////////////////////////////////////////////////
8294 /// Fill array with low edge of bins for 1D histogram
8295 /// Better to use h1.GetXaxis().GetLowEdge(edge)
8296 
8297 void TH1::GetLowEdge(Double_t *edge) const
8298 {
8299  if (fDimension == 1) {
8300  fXaxis.GetLowEdge(edge);
8301  return;
8302  }
8303  Error("GetLowEdge","Invalid method for a %d-d histogram ",fDimension);
8304 }
8305 
8306 ////////////////////////////////////////////////////////////////////////////////
8307 /// See convention for numbering bins in TH1::GetBin
8308 
8309 void TH1::SetBinError(Int_t bin, Double_t error)
8310 {
8311  if (!fSumw2.fN) Sumw2();
8312  if (bin < 0 || bin>= fSumw2.fN) return;
8313  fSumw2.fArray[bin] = error * error;
8314 }
8315 
8316 ////////////////////////////////////////////////////////////////////////////////
8317 /// Set bin content
8318 /// see convention for numbering bins in TH1::GetBin
8319 /// In case the bin number is greater than the number of bins and
8320 /// the timedisplay option is set or CanExtendAllAxes(),
8321 /// the number of bins is automatically doubled to accommodate the new bin
8322 
8323 void TH1::SetBinContent(Int_t bin, Double_t content)
8324 {
8326  fTsumw = 0;
8327  if (bin < 0) return;
8328  if (bin >= fNcells-1) {
8329  if (fXaxis.GetTimeDisplay() || CanExtendAllAxes() ) {
8330  while (bin >= fNcells-1) LabelsInflate();
8331  } else {
8332  if (bin == fNcells-1) UpdateBinContent(bin, content);
8333  return;
8334  }
8335  }
8336  UpdateBinContent(bin, content);
8337 }
8338 
8339 ////////////////////////////////////////////////////////////////////////////////
8340 /// See convention for numbering bins in TH1::GetBin
8341 
8342 void TH1::SetBinError(Int_t binx, Int_t biny, Double_t error)
8343 {
8344  if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
8345  if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
8346  SetBinError(GetBin(binx, biny), error);
8347 }
8348 
8349 ////////////////////////////////////////////////////////////////////////////////
8350 /// See convention for numbering bins in TH1::GetBin
8351 
8352 void TH1::SetBinError(Int_t binx, Int_t biny, Int_t binz, Double_t error)
8353 {
8354  if (binx < 0 || binx > fXaxis.GetNbins() + 1) return;
8355  if (biny < 0 || biny > fYaxis.GetNbins() + 1) return;
8356  if (binz < 0 || binz > fZaxis.GetNbins() + 1) return;
8357  SetBinError(GetBin(binx, biny, binz), error);
8358 }
8359 
8360 ////////////////////////////////////////////////////////////////////////////////
8361 /// This function calculates the background spectrum in this histogram.
8362 /// The background is returned as a histogram.
8363 ///
8364 /// \param[in] niter number of iterations (default value = 2)
8365 /// Increasing niter make the result smoother and lower.
8366 /// \param[in] option may contain one of the following options
8367 /// - to set the direction parameter
8368 /// "BackDecreasingWindow". By default the direction is BackIncreasingWindow
8369 /// - filterOrder-order of clipping filter (default "BackOrder2")
8370 /// possible values= "BackOrder4" "BackOrder6" "BackOrder8"
8371 /// - "nosmoothing" - if selected, the background is not smoothed
8372 /// By default the background is smoothed.
8373 /// - smoothWindow - width of smoothing window, (default is "BackSmoothing3")
8374 /// possible values= "BackSmoothing5" "BackSmoothing7" "BackSmoothing9"
8375 /// "BackSmoothing11" "BackSmoothing13" "BackSmoothing15"
8376 /// - "nocompton" - if selected the estimation of Compton edge
8377 /// will be not be included (by default the compton estimation is set)
8378 /// - "same" if this option is specified, the resulting background
8379 /// histogram is superimposed on the picture in the current pad.
8380 /// This option is given by default.
8381 ///
8382 /// NOTE that the background is only evaluated in the current range of this histogram.
8383 /// i.e., if this has a bin range (set via h->GetXaxis()->SetRange(binmin, binmax),
8384 /// the returned histogram will be created with the same number of bins
8385 /// as this input histogram, but only bins from binmin to binmax will be filled
8386 /// with the estimated background.
8387 
8388 TH1 *TH1::ShowBackground(Int_t niter, Option_t *option)
8389 {
8391  return (TH1*)gROOT->ProcessLineFast(Form("TSpectrum::StaticBackground((TH1*)0x%lx,%d,\"%s\")",
8392  (ULong_t)this, niter, option));
8393 }
8394 
8395 ////////////////////////////////////////////////////////////////////////////////
8396 /// Interface to TSpectrum::Search.
8397 /// The function finds peaks in this histogram where the width is > sigma
8398 /// and the peak maximum greater than threshold*maximum bin content of this.
8399 /// For more details see TSpectrum::Search.
8400 /// Note the difference in the default value for option compared to TSpectrum::Search
8401 /// option="" by default (instead of "goff").
8402 
8403 Int_t TH1::ShowPeaks(Double_t sigma, Option_t *option, Double_t threshold)
8404 {
8405  return (Int_t)gROOT->ProcessLineFast(Form("TSpectrum::StaticSearch((TH1*)0x%lx,%g,\"%s\",%g)",
8406  (ULong_t)this, sigma, option, threshold));
8407 }
8408 
8409 ////////////////////////////////////////////////////////////////////////////////
8410 /// For a given transform (first parameter), fills the histogram (second parameter)
8411 /// with the transform output data, specified in the third parameter
8412 /// If the 2nd parameter h_output is empty, a new histogram (TH1D or TH2D) is created
8413 /// and the user is responsible for deleting it.
8414 ///
8415 /// Available options:
8416 /// - "RE" - real part of the output
8417 /// - "IM" - imaginary part of the output
8418 /// - "MAG" - magnitude of the output
8419 /// - "PH" - phase of the output
8420 
8421 TH1* TH1::TransformHisto(TVirtualFFT *fft, TH1* h_output, Option_t *option)
8422 {
8423  if (!fft || !fft->GetN() ) {
8424  ::Error("TransformHisto","Invalid FFT transform class");
8425  return 0;
8426  }
8427 
8428  if (fft->GetNdim()>2){
8429  ::Error("TransformHisto","Only 1d and 2D transform are supported");
8430  return 0;
8431  }
8432  Int_t binx,biny;
8433  TString opt = option;
8434  opt.ToUpper();
8435  Int_t *n = fft->GetN();
8436  TH1 *hout=0;
8437  if (h_output) {
8438  hout = h_output;
8439  }
8440  else {
8441  TString name = TString::Format("out_%s", opt.Data());
8442  if (fft->GetNdim()==1)
8443  hout = new TH1D(name, name,n[0], 0, n[0]);
8444  else if (fft->GetNdim()==2)
8445  hout = new TH2D(name, name, n[0], 0, n[0], n[1], 0, n[1]);
8446  }
8447  R__ASSERT(hout != 0);
8448  TString type=fft->GetType();
8449  Int_t ind[2];
8450  if (opt.Contains("RE")){
8451  if (type.Contains("2C") || type.Contains("2HC")) {
8452  Double_t re, im;
8453  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8454  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8455  ind[0] = binx-1; ind[1] = biny-1;
8456  fft->GetPointComplex(ind, re, im);
8457  hout->SetBinContent(binx, biny, re);
8458  }
8459  }
8460  } else {
8461  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8462  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8463  ind[0] = binx-1; ind[1] = biny-1;
8464  hout->SetBinContent(binx, biny, fft->GetPointReal(ind));
8465  }
8466  }
8467  }
8468  }
8469  if (opt.Contains("IM")) {
8470  if (type.Contains("2C") || type.Contains("2HC")) {
8471  Double_t re, im;
8472  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8473  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8474  ind[0] = binx-1; ind[1] = biny-1;
8475  fft->GetPointComplex(ind, re, im);
8476  hout->SetBinContent(binx, biny, im);
8477  }
8478  }
8479  } else {
8480  ::Error("TransformHisto","No complex numbers in the output");
8481  return 0;
8482  }
8483  }
8484  if (opt.Contains("MA")) {
8485  if (type.Contains("2C") || type.Contains("2HC")) {
8486  Double_t re, im;
8487  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8488  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8489  ind[0] = binx-1; ind[1] = biny-1;
8490  fft->GetPointComplex(ind, re, im);
8491  hout->SetBinContent(binx, biny, TMath::Sqrt(re*re + im*im));
8492  }
8493  }
8494  } else {
8495  for (binx = 1; binx<=hout->GetNbinsX(); binx++) {
8496  for (biny=1; biny<=hout->GetNbinsY(); biny++) {
8497  ind[0] = binx-1; ind[1] = biny-1;
8498  hout->SetBinContent(binx, biny, TMath::Abs(fft->GetPointReal(ind)));
8499  }
8500  }
8501  }
8502  }
8503  if (opt.Contains("PH")) {
8504  if (type.Contains("2C") || type.Contains("2HC")){
8505  Double_t re, im, ph;
8506  for (binx = 1; binx<=hout->GetNbinsX(); binx++){
8507  for (biny=1; biny<=hout->GetNbinsY(); biny++){
8508  ind[0] = binx-1; ind[1] = biny-1;
8509  fft->GetPointComplex(ind, re, im);
8510  if (TMath::Abs(re) > 1e-13){
8511  ph = TMath::ATan(im/re);
8512  //find the correct quadrant
8513  if (re<0 && im<0)
8514  ph -= TMath::Pi();
8515  if (re<0 && im>=0)
8516  ph += TMath::Pi();
8517  } else {
8518  if (TMath::Abs(im) < 1e-13)
8519  ph = 0;
8520  else if (im>0)
8521  ph = TMath::Pi()*0.5;
8522  else
8523  ph = -TMath::Pi()*0.5;
8524  }
8525  hout->SetBinContent(binx, biny, ph);
8526  }
8527  }
8528  } else {
8529  printf("Pure real output, no phase");
8530  return 0;
8531  }
8532  }
8533 
8534  return hout;
8535 }
8536 
8537 ////////////////////////////////////////////////////////////////////////////////
8538 /// Raw retrieval of bin content on internal data structure
8539 /// see convention for numbering bins in TH1::GetBin
8540 
8542 {
8543  AbstractMethod("RetrieveBinContent");
8544  return 0;
8545 }
8546 
8547 ////////////////////////////////////////////////////////////////////////////////
8548 /// Raw update of bin content on internal data structure
8549 /// see convention for numbering bins in TH1::GetBin
8550 
8552 {
8553  AbstractMethod("UpdateBinContent");
8554 }
8555 
8556 ////////////////////////////////////////////////////////////////////////////////
8557 /// Print value overload
8558 
8559 std::string cling::printValue(TH1 *val) {
8560  std::ostringstream strm;
8561  strm << cling::printValue((TObject*)val) << " NbinsX: " << val->GetNbinsX();
8562  return strm.str();
8563 }
8564 
8565 //______________________________________________________________________________
8566 // TH1C methods
8567 // TH1C : histograms with one byte per channel. Maximum bin content = 127
8568 //______________________________________________________________________________
8569 
8570 ClassImp(TH1C)
8571 
8572 ////////////////////////////////////////////////////////////////////////////////
8573 /// Constructor.
8574 
8575 TH1C::TH1C(): TH1(), TArrayC()
8576 {
8577  fDimension = 1;
8578  SetBinsLength(3);
8579  if (fgDefaultSumw2) Sumw2();
8580 }
8581 
8582 ////////////////////////////////////////////////////////////////////////////////
8583 /// Create a 1-Dim histogram with fix bins of type char (one byte per channel)
8584 /// (see TH1::TH1 for explanation of parameters)
8585 
8586 TH1C::TH1C(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
8587 : TH1(name,title,nbins,xlow,xup)
8589  fDimension = 1;
8590  TArrayC::Set(fNcells);
8591 
8592  if (xlow >= xup) SetBuffer(fgBufferSize);
8593  if (fgDefaultSumw2) Sumw2();
8594 }
8595 
8596 ////////////////////////////////////////////////////////////////////////////////
8597 /// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
8598 /// (see TH1::TH1 for explanation of parameters)
8599 
8600 TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
8601 : TH1(name,title,nbins,xbins)
8603  fDimension = 1;
8604  TArrayC::Set(fNcells);
8605  if (fgDefaultSumw2) Sumw2();
8606 }
8607 
8608 ////////////////////////////////////////////////////////////////////////////////
8609 /// Create a 1-Dim histogram with variable bins of type char (one byte per channel)
8610 /// (see TH1::TH1 for explanation of parameters)
8611 
8612 TH1C::TH1C(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
8613 : TH1(name,title,nbins,xbins)
8615  fDimension = 1;
8616  TArrayC::Set(fNcells);
8617  if (fgDefaultSumw2) Sumw2();
8618 }
8619 
8620 ////////////////////////////////////////////////////////////////////////////////
8621 /// Destructor.
8622 
8623 TH1C::~TH1C()
8624 {
8626 
8627 ////////////////////////////////////////////////////////////////////////////////
8628 /// Copy constructor.
8629 
8630 TH1C::TH1C(const TH1C &h1c) : TH1(), TArrayC()
8631 {
8632  ((TH1C&)h1c).Copy(*this);
8633 }
8634 
8635 ////////////////////////////////////////////////////////////////////////////////
8636 /// Increment bin content by 1.
8637 
8638 void TH1C::AddBinContent(Int_t bin)
8639 {
8640  if (fArray[bin] < 127) fArray[bin]++;
8641 }
8642 
8643 ////////////////////////////////////////////////////////////////////////////////
8644 /// Increment bin content by w.
8645 
8646 void TH1C::AddBinContent(Int_t bin, Double_t w)
8647 {
8648  Int_t newval = fArray[bin] + Int_t(w);
8649  if (newval > -128 && newval < 128) {fArray[bin] = Char_t(newval); return;}
8650  if (newval < -127) fArray[bin] = -127;
8651  if (newval > 127) fArray[bin] = 127;
8652 }
8653 
8654 ////////////////////////////////////////////////////////////////////////////////
8655 /// Copy this to newth1
8656 
8657 void TH1C::Copy(TObject &newth1) const
8658 {
8659  TH1::Copy(newth1);
8660 }
8661 
8662 ////////////////////////////////////////////////////////////////////////////////
8663 /// Reset.
8664 
8665 void TH1C::Reset(Option_t *option)
8666 {
8667  TH1::Reset(option);
8668  TArrayC::Reset();
8669 }
8670 
8671 ////////////////////////////////////////////////////////////////////////////////
8672 /// Set total number of bins including under/overflow
8673 /// Reallocate bin contents array
8674 
8675 void TH1C::SetBinsLength(Int_t n)
8676 {
8677  if (n < 0) n = fXaxis.GetNbins() + 2;
8678  fNcells = n;
8679  TArrayC::Set(n);
8680 }
8681 
8682 ////////////////////////////////////////////////////////////////////////////////
8683 /// Operator =
8684 
8685 TH1C& TH1C::operator=(const TH1C &h1)
8686 {
8687  if (this != &h1) ((TH1C&)h1).Copy(*this);
8688  return *this;
8689 }
8690 
8691 ////////////////////////////////////////////////////////////////////////////////
8692 /// Operator *
8693 
8694 TH1C operator*(Double_t c1, const TH1C &h1)
8695 {
8696  TH1C hnew = h1;
8697  hnew.Scale(c1);
8698  hnew.SetDirectory(0);
8699  return hnew;
8700 }
8701 
8702 ////////////////////////////////////////////////////////////////////////////////
8703 /// Operator +
8704 
8705 TH1C operator+(const TH1C &h1, const TH1C &h2)
8706 {
8707  TH1C hnew = h1;
8708  hnew.Add(&h2,1);
8709  hnew.SetDirectory(0);
8710  return hnew;
8711 }
8712 
8713 ////////////////////////////////////////////////////////////////////////////////
8714 /// Operator -
8715 
8716 TH1C operator-(const TH1C &h1, const TH1C &h2)
8717 {
8718  TH1C hnew = h1;
8719  hnew.Add(&h2,-1);
8720  hnew.SetDirectory(0);
8721  return hnew;
8722 }
8723 
8724 ////////////////////////////////////////////////////////////////////////////////
8725 /// Operator *
8726 
8727 TH1C operator*(const TH1C &h1, const TH1C &h2)
8728 {
8729  TH1C hnew = h1;
8730  hnew.Multiply(&h2);
8731  hnew.SetDirectory(0);
8732  return hnew;
8733 }
8734 
8735 ////////////////////////////////////////////////////////////////////////////////
8736 /// Operator /
8737 
8738 TH1C operator/(const TH1C &h1, const TH1C &h2)
8739 {
8740  TH1C hnew = h1;
8741  hnew.Divide(&h2);
8742  hnew.SetDirectory(0);
8743  return hnew;
8744 }
8745 
8746 //______________________________________________________________________________
8747 // TH1S methods
8748 // TH1S : histograms with one short per channel. Maximum bin content = 32767
8749 //______________________________________________________________________________
8750 
8751 ClassImp(TH1S)
8752 
8753 ////////////////////////////////////////////////////////////////////////////////
8754 /// Constructor.
8755 
8756 TH1S::TH1S(): TH1(), TArrayS()
8757 {
8758  fDimension = 1;
8759  SetBinsLength(3);
8760  if (fgDefaultSumw2) Sumw2();
8761 }
8762 
8763 ////////////////////////////////////////////////////////////////////////////////
8764 /// Create a 1-Dim histogram with fix bins of type short
8765 /// (see TH1::TH1 for explanation of parameters)
8766 
8767 TH1S::TH1S(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
8768 : TH1(name,title,nbins,xlow,xup)
8770  fDimension = 1;
8771  TArrayS::Set(fNcells);
8772 
8773  if (xlow >= xup) SetBuffer(fgBufferSize);
8774  if (fgDefaultSumw2) Sumw2();
8775 }
8776 
8777 ////////////////////////////////////////////////////////////////////////////////
8778 /// Create a 1-Dim histogram with variable bins of type short
8779 /// (see TH1::TH1 for explanation of parameters)
8780 
8781 TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
8782 : TH1(name,title,nbins,xbins)
8784  fDimension = 1;
8785  TArrayS::Set(fNcells);
8786  if (fgDefaultSumw2) Sumw2();
8787 }
8788 
8789 ////////////////////////////////////////////////////////////////////////////////
8790 /// Create a 1-Dim histogram with variable bins of type short
8791 /// (see TH1::TH1 for explanation of parameters)
8792 
8793 TH1S::TH1S(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
8794 : TH1(name,title,nbins,xbins)
8796  fDimension = 1;
8797  TArrayS::Set(fNcells);
8798  if (fgDefaultSumw2) Sumw2();
8799 }
8800 
8801 ////////////////////////////////////////////////////////////////////////////////
8802 /// Destructor.
8803 
8804 TH1S::~TH1S()
8805 {
8807 
8808 ////////////////////////////////////////////////////////////////////////////////
8809 /// Copy constructor.
8810 
8811 TH1S::TH1S(const TH1S &h1s) : TH1(), TArrayS()
8812 {
8813  ((TH1S&)h1s).Copy(*this);
8814 }
8815 
8816 ////////////////////////////////////////////////////////////////////////////////
8817 /// Increment bin content by 1.
8818 
8819 void TH1S::AddBinContent(Int_t bin)
8820 {
8821  if (fArray[bin] < 32767) fArray[bin]++;
8822 }
8823 
8824 ////////////////////////////////////////////////////////////////////////////////
8825 /// Increment bin content by w
8826 
8827 void TH1S::AddBinContent(Int_t bin, Double_t w)
8828 {
8829  Int_t newval = fArray[bin] + Int_t(w);
8830  if (newval > -32768 && newval < 32768) {fArray[bin] = Short_t(newval); return;}
8831  if (newval < -32767) fArray[bin] = -32767;
8832  if (newval > 32767) fArray[bin] = 32767;
8833 }
8834 
8835 ////////////////////////////////////////////////////////////////////////////////
8836 /// Copy this to newth1
8837 
8838 void TH1S::Copy(TObject &newth1) const
8839 {
8840  TH1::Copy(newth1);
8841 }
8842 
8843 ////////////////////////////////////////////////////////////////////////////////
8844 /// Reset.
8845 
8846 void TH1S::Reset(Option_t *option)
8847 {
8848  TH1::Reset(option);
8849  TArrayS::Reset();
8850 }
8851 
8852 ////////////////////////////////////////////////////////////////////////////////
8853 /// Set total number of bins including under/overflow
8854 /// Reallocate bin contents array
8855 
8856 void TH1S::SetBinsLength(Int_t n)
8857 {
8858  if (n < 0) n = fXaxis.GetNbins() + 2;
8859  fNcells = n;
8860  TArrayS::Set(n);
8861 }
8862 
8863 ////////////////////////////////////////////////////////////////////////////////
8864 /// Operator =
8865 
8866 TH1S& TH1S::operator=(const TH1S &h1)
8867 {
8868  if (this != &h1) ((TH1S&)h1).Copy(*this);
8869  return *this;
8870 }
8871 
8872 ////////////////////////////////////////////////////////////////////////////////
8873 /// Operator *
8874 
8875 TH1S operator*(Double_t c1, const TH1S &h1)
8876 {
8877  TH1S hnew = h1;
8878  hnew.Scale(c1);
8879  hnew.SetDirectory(0);
8880  return hnew;
8881 }
8882 
8883 ////////////////////////////////////////////////////////////////////////////////
8884 /// Operator +
8885 
8886 TH1S operator+(const TH1S &h1, const TH1S &h2)
8887 {
8888  TH1S hnew = h1;
8889  hnew.Add(&h2,1);
8890  hnew.SetDirectory(0);
8891  return hnew;
8892 }
8893 
8894 ////////////////////////////////////////////////////////////////////////////////
8895 /// Operator -
8896 
8897 TH1S operator-(const TH1S &h1, const TH1S &h2)
8898 {
8899  TH1S hnew = h1;
8900  hnew.Add(&h2,-1);
8901  hnew.SetDirectory(0);
8902  return hnew;
8903 }
8904 
8905 ////////////////////////////////////////////////////////////////////////////////
8906 /// Operator *
8907 
8908 TH1S operator*(const TH1S &h1, const TH1S &h2)
8909 {
8910  TH1S hnew = h1;
8911  hnew.Multiply(&h2);
8912  hnew.SetDirectory(0);
8913  return hnew;
8914 }
8915 
8916 ////////////////////////////////////////////////////////////////////////////////
8917 /// Operator /
8918 
8919 TH1S operator/(const TH1S &h1, const TH1S &h2)
8920 {
8921  TH1S hnew = h1;
8922  hnew.Divide(&h2);
8923  hnew.SetDirectory(0);
8924  return hnew;
8925 }
8926 
8927 //______________________________________________________________________________
8928 // TH1I methods
8929 // TH1I : histograms with one int per channel. Maximum bin content = 2147483647
8930 //______________________________________________________________________________
8931 
8932 ClassImp(TH1I)
8933 
8934 ////////////////////////////////////////////////////////////////////////////////
8935 /// Constructor.
8936 
8937 TH1I::TH1I(): TH1(), TArrayI()
8938 {
8939  fDimension = 1;
8940  SetBinsLength(3);
8941  if (fgDefaultSumw2) Sumw2();
8942 }
8943 
8944 ////////////////////////////////////////////////////////////////////////////////
8945 /// Create a 1-Dim histogram with fix bins of type integer
8946 /// (see TH1::TH1 for explanation of parameters)
8947 
8948 TH1I::TH1I(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
8949 : TH1(name,title,nbins,xlow,xup)
8951  fDimension = 1;
8952  TArrayI::Set(fNcells);
8953 
8954  if (xlow >= xup) SetBuffer(fgBufferSize);
8955  if (fgDefaultSumw2) Sumw2();
8956 }
8957 
8958 ////////////////////////////////////////////////////////////////////////////////
8959 /// Create a 1-Dim histogram with variable bins of type integer
8960 /// (see TH1::TH1 for explanation of parameters)
8961 
8962 TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
8963 : TH1(name,title,nbins,xbins)
8965  fDimension = 1;
8966  TArrayI::Set(fNcells);
8967  if (fgDefaultSumw2) Sumw2();
8968 }
8969 
8970 ////////////////////////////////////////////////////////////////////////////////
8971 /// Create a 1-Dim histogram with variable bins of type integer
8972 /// (see TH1::TH1 for explanation of parameters)
8973 
8974 TH1I::TH1I(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
8975 : TH1(name,title,nbins,xbins)
8977  fDimension = 1;
8978  TArrayI::Set(fNcells);
8979  if (fgDefaultSumw2) Sumw2();
8980 }
8981 
8982 ////////////////////////////////////////////////////////////////////////////////
8983 /// Destructor.
8984 
8985 TH1I::~TH1I()
8986 {
8988 
8989 ////////////////////////////////////////////////////////////////////////////////
8990 /// Copy constructor.
8991 
8992 TH1I::TH1I(const TH1I &h1i) : TH1(), TArrayI()
8993 {
8994  ((TH1I&)h1i).Copy(*this);
8995 }
8996 
8997 ////////////////////////////////////////////////////////////////////////////////
8998 /// Increment bin content by 1.
8999 
9000 void TH1I::AddBinContent(Int_t bin)
9001 {
9002  if (fArray[bin] < 2147483647) fArray[bin]++;
9003 }
9004 
9005 ////////////////////////////////////////////////////////////////////////////////
9006 /// Increment bin content by w
9007 
9008 void TH1I::AddBinContent(Int_t bin, Double_t w)
9009 {
9010  Int_t newval = fArray[bin] + Int_t(w);
9011  if (newval > -2147483647 && newval < 2147483647) {fArray[bin] = Int_t(newval); return;}
9012  if (newval < -2147483647) fArray[bin] = -2147483647;
9013  if (newval > 2147483647) fArray[bin] = 2147483647;
9014 }
9015 
9016 ////////////////////////////////////////////////////////////////////////////////
9017 /// Copy this to newth1
9018 
9019 void TH1I::Copy(TObject &newth1) const
9020 {
9021  TH1::Copy(newth1);
9022 }
9023 
9024 ////////////////////////////////////////////////////////////////////////////////
9025 /// Reset.
9026 
9027 void TH1I::Reset(Option_t *option)
9028 {
9029  TH1::Reset(option);
9030  TArrayI::Reset();
9031 }
9032 
9033 ////////////////////////////////////////////////////////////////////////////////
9034 /// Set total number of bins including under/overflow
9035 /// Reallocate bin contents array
9036 
9037 void TH1I::SetBinsLength(Int_t n)
9038 {
9039  if (n < 0) n = fXaxis.GetNbins() + 2;
9040  fNcells = n;
9041  TArrayI::Set(n);
9042 }
9043 
9044 ////////////////////////////////////////////////////////////////////////////////
9045 /// Operator =
9046 
9047 TH1I& TH1I::operator=(const TH1I &h1)
9048 {
9049  if (this != &h1) ((TH1I&)h1).Copy(*this);
9050  return *this;
9051 }
9052 
9053 
9054 ////////////////////////////////////////////////////////////////////////////////
9055 /// Operator *
9056 
9057 TH1I operator*(Double_t c1, const TH1I &h1)
9058 {
9059  TH1I hnew = h1;
9060  hnew.Scale(c1);
9061  hnew.SetDirectory(0);
9062  return hnew;
9063 }
9064 
9065 ////////////////////////////////////////////////////////////////////////////////
9066 /// Operator +
9067 
9068 TH1I operator+(const TH1I &h1, const TH1I &h2)
9069 {
9070  TH1I hnew = h1;
9071  hnew.Add(&h2,1);
9072  hnew.SetDirectory(0);
9073  return hnew;
9074 }
9075 
9076 ////////////////////////////////////////////////////////////////////////////////
9077 /// Operator -
9078 
9079 TH1I operator-(const TH1I &h1, const TH1I &h2)
9080 {
9081  TH1I hnew = h1;
9082  hnew.Add(&h2,-1);
9083  hnew.SetDirectory(0);
9084  return hnew;
9085 }
9086 
9087 ////////////////////////////////////////////////////////////////////////////////
9088 /// Operator *
9089 
9090 TH1I operator*(const TH1I &h1, const TH1I &h2)
9091 {
9092  TH1I hnew = h1;
9093  hnew.Multiply(&h2);
9094  hnew.SetDirectory(0);
9095  return hnew;
9096 }
9097 
9098 ////////////////////////////////////////////////////////////////////////////////
9099 /// Operator /
9100 
9101 TH1I operator/(const TH1I &h1, const TH1I &h2)
9102 {
9103  TH1I hnew = h1;
9104  hnew.Divide(&h2);
9105  hnew.SetDirectory(0);
9106  return hnew;
9107 }
9108 
9109 //______________________________________________________________________________
9110 // TH1F methods
9111 // TH1F : histograms with one float per channel. Maximum precision 7 digits
9112 //______________________________________________________________________________
9113 
9114 ClassImp(TH1F)
9115 
9116 ////////////////////////////////////////////////////////////////////////////////
9117 /// Constructor.
9118 
9119 TH1F::TH1F(): TH1(), TArrayF()
9120 {
9121  fDimension = 1;
9122  SetBinsLength(3);
9123  if (fgDefaultSumw2) Sumw2();
9124 }
9125 
9126 ////////////////////////////////////////////////////////////////////////////////
9127 /// Create a 1-Dim histogram with fix bins of type float
9128 /// (see TH1::TH1 for explanation of parameters)
9129 
9130 TH1F::TH1F(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9131 : TH1(name,title,nbins,xlow,xup)
9133  fDimension = 1;
9134  TArrayF::Set(fNcells);
9135 
9136  if (xlow >= xup) SetBuffer(fgBufferSize);
9137  if (fgDefaultSumw2) Sumw2();
9138 }
9139 
9140 ////////////////////////////////////////////////////////////////////////////////
9141 /// Create a 1-Dim histogram with variable bins of type float
9142 /// (see TH1::TH1 for explanation of parameters)
9143 
9144 TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9145 : TH1(name,title,nbins,xbins)
9147  fDimension = 1;
9148  TArrayF::Set(fNcells);
9149  if (fgDefaultSumw2) Sumw2();
9150 }
9151 
9152 ////////////////////////////////////////////////////////////////////////////////
9153 /// Create a 1-Dim histogram with variable bins of type float
9154 /// (see TH1::TH1 for explanation of parameters)
9155 
9156 TH1F::TH1F(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9157 : TH1(name,title,nbins,xbins)
9159  fDimension = 1;
9160  TArrayF::Set(fNcells);
9161  if (fgDefaultSumw2) Sumw2();
9162 }
9163 
9164 ////////////////////////////////////////////////////////////////////////////////
9165 /// Create a histogram from a TVectorF
9166 /// by default the histogram name is "TVectorF" and title = ""
9167 
9168 TH1F::TH1F(const TVectorF &v)
9169 : TH1("TVectorF","",v.GetNrows(),0,v.GetNrows())
9171  TArrayF::Set(fNcells);
9172  fDimension = 1;
9173  Int_t ivlow = v.GetLwb();
9174  for (Int_t i=0;i<fNcells-2;i++) {
9175  SetBinContent(i+1,v(i+ivlow));
9176  }
9177  TArrayF::Set(fNcells);
9178  if (fgDefaultSumw2) Sumw2();
9179 }
9180 
9181 ////////////////////////////////////////////////////////////////////////////////
9182 /// Copy Constructor.
9183 
9184 TH1F::TH1F(const TH1F &h) : TH1(), TArrayF()
9185 {
9186  ((TH1F&)h).Copy(*this);
9187 }
9188 
9189 ////////////////////////////////////////////////////////////////////////////////
9190 /// Destructor.
9191 
9192 TH1F::~TH1F()
9193 {
9195 
9196 ////////////////////////////////////////////////////////////////////////////////
9197 /// Copy this to newth1.
9198 
9199 void TH1F::Copy(TObject &newth1) const
9200 {
9201  TH1::Copy(newth1);
9202 }
9203 
9204 ////////////////////////////////////////////////////////////////////////////////
9205 /// Reset.
9206 
9207 void TH1F::Reset(Option_t *option)
9208 {
9209  TH1::Reset(option);
9210  TArrayF::Reset();
9211 }
9212 
9213 ////////////////////////////////////////////////////////////////////////////////
9214 /// Set total number of bins including under/overflow
9215 /// Reallocate bin contents array
9216 
9217 void TH1F::SetBinsLength(Int_t n)
9218 {
9219  if (n < 0) n = fXaxis.GetNbins() + 2;
9220  fNcells = n;
9221  TArrayF::Set(n);
9222 }
9223 
9224 ////////////////////////////////////////////////////////////////////////////////
9225 /// Operator =
9226 
9227 TH1F& TH1F::operator=(const TH1F &h1)
9228 {
9229  if (this != &h1) ((TH1F&)h1).Copy(*this);
9230  return *this;
9231 }
9232 
9233 ////////////////////////////////////////////////////////////////////////////////
9234 /// Operator *
9235 
9236 TH1F operator*(Double_t c1, const TH1F &h1)
9237 {
9238  TH1F hnew = h1;
9239  hnew.Scale(c1);
9240  hnew.SetDirectory(0);
9241  return hnew;
9242 }
9243 
9244 ////////////////////////////////////////////////////////////////////////////////
9245 /// Operator +
9246 
9247 TH1F operator+(const TH1F &h1, const TH1F &h2)
9248 {
9249  TH1F hnew = h1;
9250  hnew.Add(&h2,1);
9251  hnew.SetDirectory(0);
9252  return hnew;
9253 }
9254 
9255 ////////////////////////////////////////////////////////////////////////////////
9256 /// Operator -
9257 
9258 TH1F operator-(const TH1F &h1, const TH1F &h2)
9259 {
9260  TH1F hnew = h1;
9261  hnew.Add(&h2,-1);
9262  hnew.SetDirectory(0);
9263  return hnew;
9264 }
9265 
9266 ////////////////////////////////////////////////////////////////////////////////
9267 /// Operator *
9268 
9269 TH1F operator*(const TH1F &h1, const TH1F &h2)
9270 {
9271  TH1F hnew = h1;
9272  hnew.Multiply(&h2);
9273  hnew.SetDirectory(0);
9274  return hnew;
9275 }
9276 
9277 ////////////////////////////////////////////////////////////////////////////////
9278 /// Operator /
9279 
9280 TH1F operator/(const TH1F &h1, const TH1F &h2)
9281 {
9282  TH1F hnew = h1;
9283  hnew.Divide(&h2);
9284  hnew.SetDirectory(0);
9285  return hnew;
9286 }
9287 
9288 //______________________________________________________________________________
9289 // TH1D methods
9290 // TH1D : histograms with one double per channel. Maximum precision 14 digits
9291 //______________________________________________________________________________
9292 
9293 ClassImp(TH1D)
9294 
9295 ////////////////////////////////////////////////////////////////////////////////
9296 /// Constructor.
9297 
9298 TH1D::TH1D(): TH1(), TArrayD()
9299 {
9300  fDimension = 1;
9301  SetBinsLength(3);
9302  if (fgDefaultSumw2) Sumw2();
9303 }
9304 
9305 ////////////////////////////////////////////////////////////////////////////////
9306 /// Create a 1-Dim histogram with fix bins of type double
9307 /// (see TH1::TH1 for explanation of parameters)
9308 
9309 TH1D::TH1D(const char *name,const char *title,Int_t nbins,Double_t xlow,Double_t xup)
9310 : TH1(name,title,nbins,xlow,xup)
9312  fDimension = 1;
9313  TArrayD::Set(fNcells);
9314 
9315  if (xlow >= xup) SetBuffer(fgBufferSize);
9316  if (fgDefaultSumw2) Sumw2();
9317 }
9318 
9319 ////////////////////////////////////////////////////////////////////////////////
9320 /// Create a 1-Dim histogram with variable bins of type double
9321 /// (see TH1::TH1 for explanation of parameters)
9322 
9323 TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Float_t *xbins)
9324 : TH1(name,title,nbins,xbins)
9326  fDimension = 1;
9327  TArrayD::Set(fNcells);
9328  if (fgDefaultSumw2) Sumw2();
9329 }
9330 
9331 ////////////////////////////////////////////////////////////////////////////////
9332 /// Create a 1-Dim histogram with variable bins of type double
9333 /// (see TH1::TH1 for explanation of parameters)
9334 
9335 TH1D::TH1D(const char *name,const char *title,Int_t nbins,const Double_t *xbins)
9336 : TH1(name,title,nbins,xbins)
9338  fDimension = 1;
9339  TArrayD::Set(fNcells);
9340  if (fgDefaultSumw2) Sumw2();
9341 }
9342 
9343 ////////////////////////////////////////////////////////////////////////////////
9344 /// Create a histogram from a TVectorD
9345 /// by default the histogram name is "TVectorD" and title = ""
9346 
9347 TH1D::TH1D(const TVectorD &v)
9348 : TH1("TVectorD","",v.GetNrows(),0,v.GetNrows())
9350  TArrayD::Set(fNcells);
9351  fDimension = 1;
9352  Int_t ivlow = v.GetLwb();
9353  for (Int_t i=0;i<fNcells-2;i++) {
9354  SetBinContent(i+1,v(i+ivlow));
9355  }
9356  TArrayD::Set(fNcells);
9357  if (fgDefaultSumw2) Sumw2();
9358 }
9359 
9360 ////////////////////////////////////////////////////////////////////////////////
9361 /// Destructor.
9362 
9363 TH1D::~TH1D()
9364 {
9366 
9367 ////////////////////////////////////////////////////////////////////////////////
9368 /// Constructor.
9369 
9370 TH1D::TH1D(const TH1D &h1d) : TH1(), TArrayD()
9371 {
9372  ((TH1D&)h1d).Copy(*this);
9373 }
9374 
9375 ////////////////////////////////////////////////////////////////////////////////
9376 /// Copy this to newth1
9377 
9378 void TH1D::Copy(TObject &newth1) const
9379 {
9380  TH1::Copy(newth1);
9381 }
9382 
9383 ////////////////////////////////////////////////////////////////////////////////
9384 /// Reset.
9385 
9386 void TH1D::Reset(Option_t *option)
9387 {
9388  TH1::Reset(option);
9389  TArrayD::Reset();
9390 }
9391 
9392 ////////////////////////////////////////////////////////////////////////////////
9393 /// Set total number of bins including under/overflow
9394 /// Reallocate bin contents array
9395 
9396 void TH1D::SetBinsLength(Int_t n)
9397 {
9398  if (n < 0) n = fXaxis.GetNbins() + 2;
9399  fNcells = n;
9400  TArrayD::Set(n);
9401 }
9402 
9403 ////////////////////////////////////////////////////////////////////////////////
9404 /// Operator =
9405 
9406 TH1D& TH1D::operator=(const TH1D &h1)
9407 {
9408  if (this != &h1) ((TH1D&)h1).Copy(*this);
9409  return *this;
9410 }
9411 
9412 ////////////////////////////////////////////////////////////////////////////////
9413 /// Operator *
9414 
9415 TH1D operator*(Double_t c1, const TH1D &h1)
9416 {
9417  TH1D hnew = h1;
9418  hnew.Scale(c1);
9419  hnew.SetDirectory(0);
9420  return hnew;
9421 }
9422 
9423 ////////////////////////////////////////////////////////////////////////////////
9424 /// Operator +
9425 
9426 TH1D operator+(const TH1D &h1, const TH1D &h2)
9427 {
9428  TH1D hnew = h1;
9429  hnew.Add(&h2,1);
9430  hnew.SetDirectory(0);
9431  return hnew;
9432 }
9433 
9434 ////////////////////////////////////////////////////////////////////////////////
9435 /// Operator -
9436 
9437 TH1D operator-(const TH1D &h1, const TH1D &h2)
9438 {
9439  TH1D hnew = h1;
9440  hnew.Add(&h2,-1);
9441  hnew.SetDirectory(0);
9442  return hnew;
9443 }
9444 
9445 ////////////////////////////////////////////////////////////////////////////////
9446 /// Operator *
9447 
9448 TH1D operator*(const TH1D &h1, const TH1D &h2)
9449 {
9450  TH1D hnew = h1;
9451  hnew.Multiply(&h2);
9452  hnew.SetDirectory(0);
9453  return hnew;
9454 }
9455 
9456 ////////////////////////////////////////////////////////////////////////////////
9457 /// Operator /
9458 
9459 TH1D operator/(const TH1D &h1, const TH1D &h2)
9460 {
9461  TH1D hnew = h1;
9462  hnew.Divide(&h2);
9463  hnew.SetDirectory(0);
9464  return hnew;
9465 }
9466 
9467 ////////////////////////////////////////////////////////////////////////////////
9468 ///return pointer to histogram with name
9469 ///hid if id >=0
9470 ///h_id if id <0
9471 
9472 TH1 *R__H(Int_t hid)
9473 {
9474  TString hname;
9475  if(hid >= 0) hname.Form("h%d",hid);
9476  else hname.Form("h_%d",hid);
9477  return (TH1*)gDirectory->Get(hname);
9478 }
9479 
9480 ////////////////////////////////////////////////////////////////////////////////
9481 ///return pointer to histogram with name hname
9482 
9483 TH1 *R__H(const char * hname)
9484 {
9485  return (TH1*)gDirectory->Get(hname);
9486 }
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:6241
const int nx
Definition: kalman.C:16
const int ndata
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:708
virtual void SavePrimitive(std::ostream &out, Option_t *option="")
Save primitive as a C++ statement(s) on output stream out.
Definition: TH1.cxx:6472
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:262
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:9398
virtual void Print(Option_t *option="") const
Print some global quantities for this histogram.
Definition: TH1.cxx:6325
virtual void SetNameTitle(const char *name, const char *title)
Change the name and title of this histogram.
Definition: TH1.cxx:8087
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:382
Bool_t IsReading() const
Definition: TBuffer.h:81
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:3441
virtual Float_t GetTickLength() const
Definition: TAttAxis.h:44
virtual Int_t GetNcells() const
Definition: TH1.h:280
Double_t fNormFactor
Normalization factor.
Definition: TH1.h:92
virtual void SetBarOffset(Float_t offset=0.25)
Definition: TH1.h:337
virtual void Scale(Double_t c1=1, Option_t *option="")
Multiply this histogram by a constant c1.
Definition: TH1.cxx:5937
virtual Int_t Fill(Double_t x)
Increment bin with abscissa X by 1.
Definition: TH1.cxx:3126
virtual Int_t ShowPeaks(Double_t sigma=2, Option_t *option="", Double_t threshold=0.05)
Interface to TSpectrum::Search.
Definition: TH1.cxx:8405
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:7666
TH1D & operator=(const TH1D &h1)
Operator =.
Definition: TH1.cxx:9408
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:7154
void SetBarWidth(Float_t barwidth=0.5)
Definition: TStyle.h:311
static long int sum(long int i)
Definition: Factory.cxx:2162
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:4079
virtual void Paint(Option_t *option="")
Control routine to paint any kind of histograms.
Definition: TH1.cxx:5539
float xmin
Definition: THbookFile.cxx:93
virtual Int_t WriteClassBuffer(const TClass *cl, void *pointer)=0
virtual void Delete(Option_t *option="")
Remove all objects from the list AND delete all heap based objects.
Definition: TList.cxx:409
virtual Double_t GetBinCenter(Int_t bin) const
Return bin center for 1D histogram.
Definition: TH1.cxx:8253
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:847
virtual Double_t PoissonD(Double_t mean)
Generates a random number according to a Poisson law.
Definition: TRandom.cxx:414
Bool_t IsBinUnderflow(Int_t bin, Int_t axis=0) const
Return true if the bin is underflow.
Definition: TH1.cxx:4773
Double_t Floor(Double_t x)
Definition: TMath.h:600
void Set(Int_t n)
Set size of this array to n chars.
Definition: TArrayC.cxx:105
virtual ~TH1I()
Destructor.
Definition: TH1.cxx:8987
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 void SetMaximum(Double_t maximum=-1111)
Definition: TH1.h:375
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:997
void UseCurrentStyle()
Copy current attributes from/to current style.
Definition: TH1.cxx:6699
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:4935
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:649
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:8577
Bool_t IsBinOverflow(Int_t bin, Int_t axis=0) const
Return true if the bin is overflow.
Definition: TH1.cxx:4741
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:4100
virtual void FitPanel()
Display a panel with all histogram fit options.
Definition: TH1.cxx:3915
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:8053
virtual TF1 * GetFunction(const char *name) const
Return pointer to function with name.
Definition: TH1.cxx:8163
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:236
virtual Double_t GetBinLowEdge(Int_t bin) const
Return low edge of bin.
Definition: TAxis.cxx:504
Double_t KolmogorovProb(Double_t z)
Calculates the Kolmogorov distribution function,.
Definition: TMath.cxx:665
return c1
Definition: legend1.C:41
void Reset()
Definition: TArrayD.h:47
float ymin
Definition: THbookFile.cxx:93
virtual void Set(Int_t n)=0
virtual void ResetAttAxis(Option_t *option="")
Reset axis attributes.
Definition: TAttAxis.cxx:79
Double_t QuietNaN()
Definition: TMath.h:784
virtual void SetError(const Double_t *error)
Replace bin errors by values in array error.
Definition: TH1.cxx:8064
virtual Double_t GetNormFactor() const
Definition: TH1.h:281
TString & ReplaceAll(const TString &s1, const TString &s2)
Definition: TString.h:640
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:1319
virtual void SetContour(Int_t nlevels, const Double_t *levels=0)
Set the number and values of contour levels.
Definition: TH1.cxx:7607
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:7073
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:3519
Bool_t TestBit(UInt_t f) const
Definition: TObject.h:159
virtual void SetBins(Int_t nx, Double_t xmin, Double_t xmax)
Redefine x axis parameters.
Definition: TH1.cxx:7883
Int_t GetLwb() const
Definition: TVectorT.h:73
virtual Int_t GetXfirst() const
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition: TNamed.cxx:131
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:3970
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:2926
static Bool_t SameLimitsAndNBins(const TAxis &axis1, const TAxis &axis2)
Same limits and bins.
Definition: TH1.cxx:5220
virtual ~TH1F()
Destructor.
Definition: TH1.cxx:9194
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:717
virtual Double_t GetSumOfWeights() const
Return the sum of weights excluding under/overflows.
Definition: TH1.cxx:7103
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
Definition: TH1.cxx:4639
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:8659
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:4191
virtual Double_t Integral(Option_t *option="") const
Return integral of bin contents.
Definition: TH1.cxx:7127
void ToUpper()
Change string to upper case.
Definition: TString.cxx:1112
virtual void Reset(Option_t *option="")
Reset.
Definition: TH1.cxx:8667
TH1D()
Constructor.
Definition: TH1.cxx:9300
friend TH1D operator/(const TH1D &h1, const TH1D &h2)
Operator /.
Definition: TH1.cxx:9461
static bool CheckAxisLimits(const TAxis *a1, const TAxis *a2)
Check that the axis limits of the histograms are the same.
Definition: TH1.cxx:1412
Buffer base class used for serializing objects.
Definition: TBuffer.h:40
friend TH1S operator+(const TH1S &h1, const TH1S &h2)
Operator +.
Definition: TH1.cxx:8888
virtual Double_t GetMeanError(Int_t axis=1) const
Return standard error of mean of this histogram along the X axis.
Definition: TH1.cxx:6794
virtual Int_t GetNbinsZ() const
Definition: TH1.h:279
TH1F()
Constructor.
Definition: TH1.cxx:9121
#define R__ASSERT(e)
Definition: TError.h:96
virtual void SetMinimum(Double_t minimum=-1111)
Definition: TH1.h:376
static THLimitsFinder * GetLimitsFinder()
Return pointer to the current finder.
virtual Int_t CheckByteCount(UInt_t startpos, UInt_t bcnt, const TClass *clss)=0
#define gROOT
Definition: TROOT.h:375
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:6763
Ssiz_t Index(const char *pat, Ssiz_t i=0, ECaseCompare cmp=kExact) const
Definition: TString.h:587
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9380
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:4554
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:9201
Basic string class.
Definition: TString.h:129
static Bool_t AddDirectoryStatus()
Static function: cannot be inlined on Windows/NT.
Definition: TH1.cxx:700
tomato 1-D histogram with a float per channel (see TH1 documentation)}
Definition: TH1.h:551
Int_t GetNrows() const
Definition: TVectorT.h:75
tomato 1-D histogram with a short per channel (see TH1 documentation)
Definition: TH1.h:469
void H1InitExpo()
Compute Initial values of parameters for an exponential.
Definition: TH1.cxx:4297
Array of floats (32 bits per element).
Definition: TArrayF.h:27
virtual void SetTitleFont(Style_t font=62)
Set the title font.
Definition: TAttAxis.cxx:290
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
TArc * a
Definition: textangle.C:12
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:2898
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:6195
#define gInterpreter
Definition: TInterpreter.h:499
Histogram is forced to be not weighted even when the histogram is filled with weighted different than...
Definition: TH1.h:155
int nbins[3]
TArrayD fSumw2
Array of sum of squares of weights.
Definition: TH1.h:94
virtual void UseCurrentStyle()
Set current style settings in this object This function is called when either TCanvas::UseCurrentStyl...
Definition: TObject.cxx:708
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:8264
static Bool_t AlmostInteger(Double_t a, Double_t epsilon=0.00000001)
Test if a double is almost an integer.
Definition: TH1.cxx:5191
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:9021
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:2309
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:5231
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:5364
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9219
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:7554
TF1 * gF1
Definition: TH1.cxx:522
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
Float_t delta
Short_t Abs(Short_t d)
Definition: TMathBase.h:108
virtual Width_t GetLineWidth() const
Return the line width.
Definition: TAttLine.h:35
friend TH1D operator+(const TH1D &h1, const TH1D &h2)
Operator +.
Definition: TH1.cxx:9428
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:1354
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:628
void SetBit(UInt_t f, Bool_t set)
Set or unset the user status bits as specified in f.
Definition: TObject.cxx:687
virtual void SetBuffer(Int_t buffersize, Option_t *option="")
Set the maximum number of entries to be kept in the buffer.
Definition: TH1.cxx:7582
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:7021
virtual Bool_t CanExtendAllAxes() const
Returns true if all axes are extendable.
Definition: TH1.cxx:5961
virtual void Reset(Option_t *option="")
Reset this histogram: contents, errors, etc.
Definition: TH1.cxx:6419
friend TH1S operator-(const TH1S &h1, const TH1S &h2)
Operator -.
Definition: TH1.cxx:8899
virtual TObject * FindObject(const char *name) const
Find an object in this list using its name.
Definition: TList.cxx:501
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:1218
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:338
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:112
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:6013
Marker Attributes class.
Definition: TAttMarker.h:19
virtual Style_t GetTitleFont() const
Definition: TAttAxis.h:46
static bool CheckConsistentSubAxes(const TAxis *a1, Int_t firstBin1, Int_t lastBin1, const TAxis *a2, Int_t firstBin2=0, Int_t lastBin2=0)
Check that two sub axis are the same.
Definition: TH1.cxx:1461
virtual Style_t GetLineStyle() const
Return the line style.
Definition: TAttLine.h:34
virtual Int_t GetDimension() const
Definition: TH1.h:263
NOTE: Must always be 0 !!!
Definition: TH1.h:69
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:4693
virtual Int_t GetContour(Double_t *levels=0)
Return contour values into array levels if pointer levels is non zero.
Definition: TH1.cxx:7535
TH1C & operator=(const TH1C &h1)
Operator =.
Definition: TH1.cxx:8687
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:135
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:4232
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:2345
virtual void Eval(TF1 *f1, Option_t *option="")
Evaluate function f1 at the center of bins of this histogram.
Definition: TH1.cxx:2974
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:4046
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:6003
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:1830
The TNamed class is the base class for all named ROOT classes.
Definition: TNamed.h:29
virtual ~TH1()
Histogram default destructor.
Definition: TH1.cxx:575
const int ny
Definition: kalman.C:17
THashList * GetLabels() const
Definition: TAxis.h:117
friend TH1D operator-(const TH1D &h1, const TH1D &h2)
Operator -.
Definition: TH1.cxx:9439
Int_t GetOptFit() const
Definition: TStyle.h:228
Double_t Log10(Double_t x)
Definition: TMath.h:652
virtual void SetContourLevel(Int_t level, Double_t value)
Set value for one contour level.
Definition: TH1.cxx:7646
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:8939
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:8758
TString & Append(const char *cs)
Definition: TString.h:497
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:1151
Double_t * fArray
Definition: TArrayD.h:30
void H1InitGaus()
Compute Initial values of parameters for a gaussian.
Definition: TH1.cxx:4241
virtual Size_t GetMarkerSize() const
Return the marker size.
Definition: TAttMarker.h:33
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
friend TH1I operator-(const TH1I &h1, const TH1I &h2)
Operator -.
Definition: TH1.cxx:9081
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:5782
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:7522
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:1193
friend TH1C operator*(Double_t c1, const TH1C &h1)
Operator *.
Definition: TH1.cxx:8696
virtual void ResetStats()
Reset the statistics including the number of entries and replace with values calculates from bin cont...
Definition: TH1.cxx:7088
void Set(Int_t n)
Set size of this array to n ints.
Definition: TArrayI.cxx:105
Double_t Infinity()
Definition: TMath.h:797
TArrayD fContour
Array to display contour levels.
Definition: TH1.h:93
virtual void SetBinError(Int_t bin, Double_t error)
See convention for numbering bins in TH1::GetBin.
Definition: TH1.cxx:8311
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:2355
user specified contour levels
Definition: TH1.h:149
virtual void LabelsInflate(Option_t *axis="X")
Double the number of bins for axis.
Definition: TH1.cxx:4874
virtual Color_t GetLabelColor() const
Definition: TAttAxis.h:38
short Color_t
Definition: RtypesCore.h:79
virtual Double_t GetSkewness(Int_t axis=1) const
Definition: TH1.cxx:6868
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:4347
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:2606
virtual Int_t GetNdivisions() const
Definition: TAttAxis.h:36
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:698
A doubly linked list.
Definition: TList.h:43
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:7847
virtual Double_t Rndm()
Machine independent random number generator.
Definition: TRandom.cxx:512
virtual Double_t GetStdDevError(Int_t axis=1) const
Return error of standard deviation estimation for Normal distribution.
Definition: TH1.cxx:6855
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:7362
virtual void ExtendAxis(Double_t x, TAxis *axis)
Histogram is resized along axis such that x is in the axis range.
Definition: TH1.cxx:5839
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:2425
virtual TH1 * FFT(TH1 *h_output, Option_t *option)
This function allows to do discrete Fourier transforms of TH1 and TH2.
Definition: TH1.cxx:3066
virtual Int_t DistancetoPrimitive(Int_t px, Int_t py)
Compute distance from point px,py to a line.
Definition: TH1.cxx:2589
void Reset()
Definition: TArrayS.h:47
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:8821
virtual void SetLineColor(Color_t lcolor)
Set the line color.
Definition: TAttLine.h:40
don&#39;t draw stats box
Definition: TH1.h:148
friend TH1S operator/(const TH1S &h1, const TH1S &h2)
Operator /.
Definition: TH1.cxx:8921
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:3022
Int_t fN
Definition: TArray.h:38
virtual Double_t * GetIntegral()
Return a pointer to the array of bins integral.
Definition: TH1.cxx:2403
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:889
void Clear(Option_t *option="")
Remove all objects from the list.
Definition: THashList.cxx:168
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:3267
friend TH1C operator-(const TH1C &h1, const TH1C &h2)
Operator -.
Definition: TH1.cxx:8718
void Copy(TArrayF &array) const
Definition: TArrayF.h:42
friend TH1C operator+(const TH1C &h1, const TH1C &h2)
Operator +.
Definition: TH1.cxx:8707
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:561
virtual void FillRandom(const char *fname, Int_t ntimes=5000)
Fill histogram following distribution in function fname.
Definition: TH1.cxx:3294
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:6077
Class to manage histogram axis.
Definition: TAxis.h:30
virtual Double_t GetKurtosis(Int_t axis=1) const
Definition: TH1.cxx:6938
virtual void Draw(Option_t *option="")
Draw this histogram with options.
Definition: TH1.cxx:2851
static bool CheckBinLabels(const TAxis *a1, const TAxis *a2)
Check that axis have same labels.
Definition: TH1.cxx:1380
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:65
TH1 * R__H(Int_t hid)
return pointer to histogram with name hid if id >=0 h_id if id <0
Definition: TH1.cxx:9474
virtual void SetFillColor(Color_t fcolor)
Set the fill area color.
Definition: TAttFill.h:37
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:4664
friend TH1I operator+(const TH1I &h1, const TH1I &h2)
Operator +.
Definition: TH1.cxx:9070
void SetCanExtend(Bool_t canExtend)
Definition: TAxis.h:86
tomato 1-D histogram with an int per channel (see TH1 documentation)}
Definition: TH1.h:510
Long_t ExecPlugin(int nargs, const T &... params)
virtual TObject * Remove(TObject *obj)
Remove object from the list.
Definition: TList.cxx:679
virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py)=0
Execute action corresponding to an event at (px,py).
unsigned int r1[N_CITIES]
Definition: simanTSP.cxx:321
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:8423
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:436
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:8325
Collection abstract base class.
Definition: TCollection.h:42
static Int_t fgBufferSize
!default buffer size for automatic histograms
Definition: TH1.h:104
virtual TH1 * Rebin(Int_t ngroup=2, const char *newname="", const Double_t *xbins=0)
Rebin this histogram.
Definition: TH1.cxx:5605
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:7247
void Form(const char *fmt,...)
Formats a string using a printf style format descriptor.
Definition: TString.cxx:2332
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:4804
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:3253
TMarker * m
Definition: textangle.C:8
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:873
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:2317
Ssiz_t Length() const
Definition: TString.h:388
virtual void Append(TObject *obj, Bool_t replace=kFALSE)
Append object to this directory.
Definition: TDirectory.cxx:153
static TVirtualFitter * GetFitter()
static: return the current Fitter
virtual void Copy(TObject &hnew) const
Copy this histogram structure to newth1.
Definition: TH1.cxx:2468
virtual TH1 * ShowBackground(Int_t niter=20, Option_t *option="same")
This function calculates the background spectrum in this histogram.
Definition: TH1.cxx:8390
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:9039
virtual ~TH1C()
Destructor.
Definition: TH1.cxx:8625
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:3459
short Short_t
Definition: RtypesCore.h:35
TLine * l
Definition: textangle.C:4
virtual void Copy(TObject &hnew) const
Copy this to newth1.
Definition: TH1.cxx:8840
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:7564
TAxis * GetYaxis()
Definition: TH1.h:301
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition: BinData.h:53
Bin contents are average (used by Add)
Definition: TH1.h:154
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:315
virtual Color_t GetTitleColor() const
Definition: TAttAxis.h:45
Double_t * fIntegral
!Integral of bins used by GetRandom
Definition: TH1.h:101
friend TH1F operator*(Double_t c1, const TH1F &h1)
Operator *.
Definition: TH1.cxx:9238
static bool CheckConsistency(const TH1 *h1, const TH1 *h2)
Check histogram compatibility.
Definition: TH1.cxx:1496
void SetName(const char *name)
Definition: TCollection.h:111
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:4452
TH1()
Histogram default constructor.
Definition: TH1.cxx:548
R__EXTERN TRandom * gRandom
Definition: TRandom.h:62
tomato 1-D histogram with a double per channel (see TH1 documentation)}
Definition: TH1.h:594
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:4541
static Int_t GetDefaultBufferSize()
Static function return the default buffer size for automatic histograms the parameter fgBufferSize ma...
Definition: TH1.cxx:4037
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:3537
virtual void Rebuild(Option_t *option="")
Using the current bin info, recompute the arrays for contents and errors.
Definition: TH1.cxx:6403
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:3500
if object destructor must call RecursiveRemove()
Definition: TObject.h:59
virtual void SetLabelSize(Float_t size=0.04)
Set size of axis labels The size is expressed in per cent of the pad width.
Definition: TAttAxis.cxx:204
virtual void SetMarkerSize(Size_t msize=1)
Set the marker size.
Definition: TAttMarker.h:41
friend TH1I operator/(const TH1I &h1, const TH1I &h2)
Operator /.
Definition: TH1.cxx:9103
REAL epsilon
Definition: triangle.c:617
virtual void SetTitleColor(Color_t color=1)
Set color of axis title.
Definition: TAttAxis.cxx:281
constexpr Double_t E()
Definition: TMath.h:74
virtual TObjLink * FirstLink() const
Definition: TList.h:97
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:272
#define Printf
Definition: TGeoToOCC.h:18
virtual void RecursiveRemove(TObject *obj)
Recursively remove object from the list of functions.
Definition: TH1.cxx:5911
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:8543
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:7751
errors with Normal (Wald) approximation: errorUp=errorLow= sqrt(N)
Definition: TH1.h:62
#define R__LOCKGUARD2(mutex)
const Bool_t kFALSE
Definition: RtypesCore.h:92
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:8073
friend TH1I operator*(Double_t c1, const TH1I &h1)
Operator *.
Definition: TH1.cxx:9059
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:621
virtual Int_t ReadClassBuffer(const TClass *cl, void *pointer, const TClass *onfile_class=0)=0
virtual Int_t GetSumw2N() const
Definition: TH1.h:295
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:1197
virtual void GetPointComplex(Int_t ipoint, Double_t &re, Double_t &im, Bool_t fromInput=kFALSE) const =0
virtual Bool_t IsEmpty() const
Definition: TCollection.h:93
return c2
Definition: legend2.C:14
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width for 1D histogram.
Definition: TH1.cxx:8275
static const double x1[5]
virtual TObject * Remove(TObject *)
Remove an object from the in-memory list.
#define ClassImp(name)
Definition: Rtypes.h:336
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:8191
friend TH1F operator+(const TH1F &h1, const TH1F &h2)
Operator +.
Definition: TH1.cxx:9249
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:6614
Double_t fTsumw
Total Sum of weights.
Definition: TH1.h:86
Color_t GetHistLineColor() const
Definition: TStyle.h:218
friend TH1D operator*(Double_t c1, const TH1D &h1)
Operator *.
Definition: TH1.cxx:9417
Describe directory structure in memory.
Definition: TDirectory.h:34
int type
Definition: TGX11.cxx:120
Double_t Median(Long64_t n, const T *a, const Double_t *w=0, Long64_t *work=0)
Definition: TMath.h:1226
unsigned long ULong_t
Definition: RtypesCore.h:51
int nentries
Definition: THbookFile.cxx:89
Double_t y[n]
Definition: legend1.C:17
double func(double *x, double *p)
Definition: stressTF1.cxx:213
virtual Color_t GetFillColor() const
Return the fill area color.
Definition: TAttFill.h:30
TH1I & operator=(const TH1I &h1)
Operator =.
Definition: TH1.cxx:9049
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:572
The TH1 histogram class.
Definition: TH1.h:56
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:4054
friend TH1F operator/(const TH1F &h1, const TH1F &h2)
Operator /.
Definition: TH1.cxx:9282
void forward(const LAYERDATA &prevLayerData, LAYERDATA &currLayerData)
apply the weights (and functions) in forward direction of the DNN
Definition: NeuralNet.icc:544
THist< 2, double, THistStatContent, THistStatUncertainty > TH2D
Definition: THist.hxx:316
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:1889
static bool IsEquidistantBinning(const TAxis &axis)
Test if the binning is equidistant.
Definition: TH1.cxx:5200
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:385
void FitOptionsMake(EFitObjectType type, const char *option, Foption_t &fitOption)
Decode list of options into fitOption.
Definition: HFitImpl.cxx:678
virtual void InitArgs(const Double_t *x, const Double_t *params)
Initialize parameters addresses.
Definition: TF1.cxx:2261
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:770
Abstract Base Class for Fitting.
TAxis * GetZaxis()
Definition: TH1.h:302
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:5974
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:3474
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:8858
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:2336
virtual Bool_t IsInside(const Double_t *x) const
return kTRUE if the point is inside the function range
Definition: TF1.h:542
char Char_t
Definition: RtypesCore.h:29
virtual char * GetObjectInfo(Int_t px, Int_t py) const
Redefines TObject::GetObjectInfo.
Definition: TH1.cxx:4091
TH1S & operator=(const TH1S &h1)
Operator =.
Definition: TH1.cxx:8868
virtual Int_t GetNpar() const
Definition: TF1.h:435
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:2567
TVirtualHistPainter * fPainter
!pointer to histogram painter
Definition: TH1.h:102
virtual void Copy(TObject &named) const
Copy this to obj.
Definition: TNamed.cxx:85
friend TH1C operator/(const TH1C &h1, const TH1C &h2)
Operator /.
Definition: TH1.cxx:8740
friend TH1S operator*(Double_t c1, const TH1S &h1)
Operator *.
Definition: TH1.cxx:8877
static Bool_t RejectedPoint()
See TF1::RejectPoint above.
Definition: TF1.cxx:3468
virtual void DrawPanel()
Display a panel with all histogram drawing options.
Definition: TH1.cxx:2957
virtual void Add(TObject *obj)
Definition: TList.h:77
Int_t fBufferSize
fBuffer size
Definition: TH1.h:97
double f2(const double *x)
virtual void RecursiveRemove(TObject *obj)
Remove object from this collection and recursively remove the object from all other objects (and coll...
Definition: TList.cxx:639
virtual Int_t GetMinimumBin() const
Return location of bin with minimum value in the range.
Definition: TH1.cxx:7781
virtual Double_t GetBinErrorSqUnchecked(Int_t bin) const
Definition: TH1.h:419
virtual void GetRange(Double_t *xmin, Double_t *xmax) const
Return range of a generic N-D function.
Definition: TF1.cxx:2012
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:7163
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:3229
Short_t Max(Short_t a, Short_t b)
Definition: TMathBase.h:200
1-Dim function class
Definition: TF1.h:150
virtual void SetBinsLength(Int_t=-1)
Definition: TH1.h:353
Int_t IsNaN(Double_t x)
Definition: TMath.h:778
Char_t * fArray
Definition: TArrayC.h:30
tomato 1-D histogram with a byte per channel (see TH1 documentation)
Definition: TH1.h:428
virtual void Sumw2(Bool_t flag=kTRUE)
Create structure to store sum of squares of weights.
Definition: TH1.cxx:8132
TObject * Clone(const char *newname=0) const
Make a complete copy of the underlying object.
Definition: TH1.cxx:2544
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:594
friend TH1F operator-(const TH1F &h1, const TH1F &h2)
Operator -.
Definition: TH1.cxx:9260
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:1267
Int_t fDimension
!Histogram dimension (1, 2 or 3 dim)
Definition: TH1.h:100
THist< 1, double, THistStatContent, THistStatUncertainty > TH1D
Definition: THist.hxx:310
#define gPad
Definition: TVirtualPad.h:284
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:249
virtual Int_t GetXlast() const
virtual Double_t GetBinErrorUp(Int_t bin) const
Return upper error associated to bin number bin.
Definition: TH1.cxx:8222
virtual Int_t BufferEmpty(Int_t action=0)
Fill histogram with all entries in the buffer.
Definition: TH1.cxx:1236
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:9365
virtual void SetEntries(Double_t n)
Definition: TH1.h:363
TAxis fXaxis
X axis descriptor.
Definition: TH1.h:80
Float_t GetBarOffset() const
Definition: TStyle.h:168
#define gDirectory
Definition: TDirectory.h:211
virtual TH1 * GetHistogram() const
Return a pointer to the histogram used to visualise the function.
Definition: TF1.cxx:1311
void ResetBit(UInt_t f)
Definition: TObject.h:158
virtual void SetParameter(Int_t param, Double_t value)
Definition: TF1.h:578
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:9002
virtual void SetTitle(const char *title)
Change (i.e.
Definition: TH1.cxx:6028
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:943
virtual Int_t GetNdim() const =0
virtual Color_t GetMarkerColor() const
Return the marker color.
Definition: TAttMarker.h:31
Definition: first.py:1
const int nn
virtual Int_t GetNbinsX() const
Definition: TH1.h:277
Option_t * GetDrawOption() const
Get option used by the graphics system to draw this object.
Definition: TBrowser.h:104
virtual Int_t Poisson(Double_t mean)
Generates a random integer N according to a Poisson law.
Definition: TRandom.cxx:362
virtual Style_t GetFillStyle() const
Return the fill area style.
Definition: TAttFill.h:31
Double_t Sqrt(Double_t x)
Definition: TMath.h:591
virtual void AddBinContent(Int_t bin)
Increment bin content by 1.
Definition: TH1.cxx:8640
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:364
virtual Int_t GetSize() const
Definition: TCollection.h:89
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:5183
virtual Double_t EvalPar(const Double_t *x, const Double_t *params=0)
Evaluate function with given coordinates and parameters.
Definition: TF1.cxx:1226
virtual void SetTitle(const char *title="")
Set the title of the TNamed.
Definition: TNamed.cxx:155
TList * GetListOfFunctions() const
Definition: TH1.h:224
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 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:3564
const Bool_t kTRUE
Definition: RtypesCore.h:91
double norm(double *x, double *p)
Definition: unuranDistr.cxx:40
Int_t Nint(T x)
Definition: TMath.h:607
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:915
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:8553
virtual Double_t GetStdDev(Int_t axis=1) const
Returns the Standard Deviation (Sigma).
Definition: TH1.cxx:6817
void Set(Int_t n)
Set size of this array to n doubles.
Definition: TArrayD.cxx:105
virtual Double_t GetRandom() const
Return a random number distributed according the histogram bin contents.
Definition: TH1.cxx:4588
static bool CheckEqualAxes(const TAxis *a1, const TAxis *a2)
Check that the axis are the same.
Definition: TH1.cxx:1425
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:8806
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:7696
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:8286
void H1InitPolynom()
Compute Initial values of parameters for a polynom.
Definition: TH1.cxx:4317
virtual void SetStats(Bool_t stats=kTRUE)
Set statistics option on/off.
Definition: TH1.cxx:8103
TH1F & operator=(const TH1F &h1)
Operator =.
Definition: TH1.cxx:9229
virtual Float_t GetBarWidth() const
Definition: TH1.h:237
Long64_t BinarySearch(Long64_t n, const T *array, T value)
Definition: TMath.h:1093
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:8299
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:859
TAxis * GetXaxis()
Definition: TH1.h:300
virtual void SetBinsLength(Int_t n=-1)
Set total number of bins including under/overflow Reallocate bin contents array.
Definition: TH1.cxx:8677
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:5340
virtual Version_t ReadVersion(UInt_t *start=0, UInt_t *bcnt=0, const TClass *cl=0)=0
virtual const char * GetTitle() const
Returns title of object.
Definition: TNamed.h:48
virtual Int_t GetNbinsY() const
Definition: TH1.h:278
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:8175
virtual Int_t ReadArray(Bool_t *&b)=0
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:644
T MinElement(Long64_t n, const T *a)
Definition: TMath.h:830
void H1LeastSquareLinearFit(Int_t ndata, Double_t &a0, Double_t &a1, Int_t &ifail)
Least square linear fit without weights.
Definition: TH1.cxx:4406
const char * Data() const
Definition: TString.h:347
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:657
Double_t ATan(Double_t)
Definition: TMath.h:578